Subversion Repositories SmartDukaan

Rev

Rev 34695 | Rev 34856 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
33172 tejus.loha 1
package com.spice.profitmandi.service.order;
2
 
3
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
4
import com.spice.profitmandi.common.model.BulkOrderModel;
33341 tejus.loha 5
import com.spice.profitmandi.common.model.LineItemModel;
33547 tejus.loha 6
import com.spice.profitmandi.common.model.ProfitMandiConstants;
33341 tejus.loha 7
import com.spice.profitmandi.common.model.TransactionApprovalModel;
33172 tejus.loha 8
import com.spice.profitmandi.common.util.ExcelUtils;
9
import com.spice.profitmandi.dao.cart.CartService;
33341 tejus.loha 10
import com.spice.profitmandi.dao.entity.auth.AuthUser;
34443 vikas.jang 11
import com.spice.profitmandi.dao.entity.catalog.Bid;
34832 ranu 12
import com.spice.profitmandi.dao.entity.catalog.Item;
33172 tejus.loha 13
import com.spice.profitmandi.dao.entity.catalog.TagListing;
34566 ranu 14
import com.spice.profitmandi.dao.entity.fofo.LoanTransaction;
34674 aman.kumar 15
import com.spice.profitmandi.dao.entity.transaction.LineItem;
16
import com.spice.profitmandi.dao.entity.transaction.Order;
17
import com.spice.profitmandi.dao.entity.transaction.Transaction;
18
import com.spice.profitmandi.dao.entity.transaction.TransactionApproval;
33213 tejus.loha 19
import com.spice.profitmandi.dao.enumuration.transaction.TransactionApprovalStatus;
33172 tejus.loha 20
import com.spice.profitmandi.dao.model.CartItem;
21
import com.spice.profitmandi.dao.model.UserCart;
33341 tejus.loha 22
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
34468 vikas.jang 23
import com.spice.profitmandi.dao.repository.catalog.BidRepository;
34832 ranu 24
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
34468 vikas.jang 25
import com.spice.profitmandi.dao.repository.catalog.LiquidationRepository;
33172 tejus.loha 26
import com.spice.profitmandi.dao.repository.catalog.TagListingRepository;
34443 vikas.jang 27
import com.spice.profitmandi.dao.repository.cs.CsService;
33172 tejus.loha 28
import com.spice.profitmandi.dao.repository.dtr.UserRepository;
34566 ranu 29
import com.spice.profitmandi.dao.repository.fofo.LoanTransactionRepository;
33341 tejus.loha 30
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
33338 amit.gupta 31
import com.spice.profitmandi.dao.repository.transaction.SDCreditRequirementRepository;
33213 tejus.loha 32
import com.spice.profitmandi.dao.repository.transaction.TransactionApprovalRepository;
33
import com.spice.profitmandi.dao.repository.transaction.TransactionRepository;
34
import com.spice.profitmandi.dao.repository.user.AddressRepository;
34468 vikas.jang 35
import com.spice.profitmandi.dao.service.BidService;
34832 ranu 36
import com.spice.profitmandi.service.catalog.BrandsService;
34661 ranu 37
import com.spice.profitmandi.service.transaction.BlockLoanIdSanctionId;
33338 amit.gupta 38
import com.spice.profitmandi.service.transaction.SDCreditService;
33172 tejus.loha 39
import com.spice.profitmandi.service.transaction.TransactionService;
40
import com.spice.profitmandi.service.wallet.CommonPaymentService;
41
import com.spice.profitmandi.service.wallet.WalletService;
42
import org.apache.logging.log4j.LogManager;
43
import org.apache.logging.log4j.Logger;
33213 tejus.loha 44
import org.apache.poi.ss.usermodel.Cell;
33172 tejus.loha 45
import org.apache.poi.ss.usermodel.Row;
46
import org.apache.poi.xssf.usermodel.XSSFRow;
47
import org.apache.poi.xssf.usermodel.XSSFSheet;
48
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
49
import org.springframework.beans.factory.annotation.Autowired;
33213 tejus.loha 50
import org.springframework.stereotype.Service;
51
import org.springframework.transaction.annotation.Transactional;
33172 tejus.loha 52
import org.springframework.web.multipart.MultipartFile;
53
 
33338 amit.gupta 54
import java.math.BigDecimal;
33172 tejus.loha 55
import java.util.ArrayList;
56
import java.util.List;
57
import java.util.Map;
58
import java.util.stream.Collectors;
59
 
33213 tejus.loha 60
@Service
61
@Transactional(rollbackFor = Throwable.class)
33172 tejus.loha 62
public class BulkOrderService {
63
    private static final Logger LOGGER = LogManager.getLogger(BulkOrderService.class);
64
    @Autowired
65
    CartService cartService;
66
    @Autowired
67
    TransactionService transactionService;
68
    @Autowired
69
    CommonPaymentService commonPaymentService;
70
    @Autowired
71
    TagListingRepository tagListingRepository;
72
    @Autowired
73
    WalletService walletService;
74
    @Autowired
75
    UserRepository userRepository;
33213 tejus.loha 76
    @Autowired
77
    TransactionRepository transactionRepository;
78
    @Autowired
79
    TransactionApprovalRepository transactionApprovalRepository;
80
    @Autowired
81
    AddressRepository addressRepository;
33341 tejus.loha 82
    @Autowired
83
    OrderRepository orderRepository;
34443 vikas.jang 84
    //TODO:Tejus need to check
33341 tejus.loha 85
    @Autowired
86
    SDCreditRequirementRepository sdCreditRequirementRepository;
33338 amit.gupta 87
    @Autowired
88
    SDCreditService sdCreditService;
34443 vikas.jang 89
    @Autowired
90
    private CsService csService;
91
    @Autowired
34468 vikas.jang 92
    private AuthRepository authRepository;
34443 vikas.jang 93
    @Autowired
34468 vikas.jang 94
    private BidRepository bidRepository;
95
    @Autowired
96
    private BidService bidService;
97
    @Autowired
34832 ranu 98
    ItemRepository itemRepository;
99
    @Autowired
100
    private BrandsService brandsService;
101
    @Autowired
34566 ranu 102
    private LoanTransactionRepository loanTransactionRepository;
103
 
104
    @Autowired
34468 vikas.jang 105
    private LiquidationRepository liquidationRepository;
33338 amit.gupta 106
 
34674 aman.kumar 107
    @Autowired
108
    com.spice.profitmandi.dao.repository.user.UserRepository user_userRepository;
33338 amit.gupta 109
 
34674 aman.kumar 110
 
34468 vikas.jang 111
    public void parseBulkOrders(MultipartFile file, int creatorId) throws Exception {
33172 tejus.loha 112
        XSSFWorkbook myWorkBook = new XSSFWorkbook(file.getInputStream());
113
 
114
        myWorkBook.setMissingCellPolicy(Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
115
        // Return first sheet from the XLSX workbook
116
        XSSFSheet mySheet = myWorkBook.getSheetAt(0);
117
        LOGGER.info("rowCellNum {}", mySheet.getLastRowNum());
118
        List<BulkOrderModel> bulkOrderModels = new ArrayList<>();
33547 tejus.loha 119
        LOGGER.info("mySheet.getLastRowNum() - {}", mySheet.getLastRowNum());
33172 tejus.loha 120
        for (int rowNumber = 1; rowNumber <= mySheet.getLastRowNum(); rowNumber++) {
121
            XSSFRow row = mySheet.getRow(rowNumber);
33547 tejus.loha 122
            LOGGER.info("Row - {}", row);
123
            if (row != null) {
124
                BulkOrderModel bulkOrderModel = this.createBulkModel(row);
125
                bulkOrderModels.add(bulkOrderModel);
126
            } else {
127
                break;
128
            }
33172 tejus.loha 129
        }
34468 vikas.jang 130
        this.generatePurchaseOrder(bulkOrderModels, creatorId, ProfitMandiConstants.PO_TYPE.MANUAL, ProfitMandiConstants.BID_CRON_ENUM.TODAY);
34443 vikas.jang 131
    }
132
 
34592 vikas.jang 133
    public ProfitMandiConstants.BID_ENUM generatePurchaseOrder(List<BulkOrderModel> bulkOrderModels, int creatorId, ProfitMandiConstants.PO_TYPE type, ProfitMandiConstants.BID_CRON_ENUM scheduleType) throws Exception {
33172 tejus.loha 134
        Map<Integer, List<BulkOrderModel>> fofoBulkOrdersMap = bulkOrderModels.stream().collect(Collectors.groupingBy(x -> x.getFofoId()));
34443 vikas.jang 135
        boolean approvalRequired = false;
34592 vikas.jang 136
        ProfitMandiConstants.BID_ENUM finalBidStatus = ProfitMandiConstants.BID_ENUM.CLOSED;
33172 tejus.loha 137
        for (Map.Entry<Integer, List<BulkOrderModel>> fofoBulkOrderEntry : fofoBulkOrdersMap.entrySet()) {
138
            int fofoId = fofoBulkOrderEntry.getKey();
139
            List<BulkOrderModel> fofoBulkOrderModels = fofoBulkOrderEntry.getValue();
140
            Map<Integer, Long> orderItemCountMap = fofoBulkOrderModels.stream().collect(Collectors.groupingBy(x -> x.getItemId(), Collectors.counting()));
141
 
142
            if (orderItemCountMap.entrySet().stream().filter(x -> x.getValue() > 1).count() > 0) {
143
                throw new ProfitMandiBusinessException("Fofo ID", fofoId, "Duplicate in items");
144
            }
145
 
146
            boolean hasZeroQuantity = fofoBulkOrderModels.stream().filter(x -> x.getQuantity() <= 0).count() > 0;
147
            if (hasZeroQuantity) {
148
                throw new ProfitMandiBusinessException("Item Quantity", "", "Should be greater than 0");
149
            }
150
 
151
            List<CartItem> cartItems = new ArrayList<>();
33338 amit.gupta 152
            double totalPayableAmount = 0;
33172 tejus.loha 153
            for (BulkOrderModel fofoBulkOrderModel : fofoBulkOrderModels) {
154
                CartItem cartItem = new CartItem();
155
                cartItem.setQuantity(fofoBulkOrderModel.getQuantity());
156
                cartItem.setItemId(fofoBulkOrderModel.getItemId());
157
                TagListing tagListing = tagListingRepository.selectByItemId(fofoBulkOrderModel.getItemId());
33556 amit.gupta 158
                if (tagListing == null) {
159
                    String message = "Pricing Does not exist for " + fofoBulkOrderModel.getItemId() + "(" + fofoBulkOrderModel.getDescription() + ")";
160
                    throw new ProfitMandiBusinessException(message, message, message);
161
                }
34832 ranu 162
                List<String> partnerIneligibleBrands = brandsService.partnerIneligibleBrands(fofoId);
163
                Item item = itemRepository.selectById(fofoBulkOrderModel.getItemId());
164
                if (partnerIneligibleBrands.contains(item.getBrand())) {
165
                    throw new ProfitMandiBusinessException("Brand is not allowed", "Brand ( " + item.getBrand() + ") is not allowed for this partner", "");
166
                }
167
 
33213 tejus.loha 168
                double itemSellingPrice = tagListing.getSellingPrice();
33597 tejus.loha 169
                boolean isActualPrice = fofoBulkOrderModel.getItemPrice() == itemSellingPrice;
170
                boolean isPriceZero = fofoBulkOrderModel.getItemPrice() == 0d;
33213 tejus.loha 171
                double customSellingPrice = fofoBulkOrderModel.getItemPrice();
172
                int itemId = cartItem.getItemId();
33597 tejus.loha 173
                if (isPriceZero || isActualPrice) {
33213 tejus.loha 174
                    cartItem.setSellingPrice(itemSellingPrice);
175
                } else {
33216 tejus.loha 176
                    if (customSellingPrice <= tagListing.getMrp() || customSellingPrice <= tagListing.getMop()) {
33213 tejus.loha 177
                        cartItem.setSellingPrice(customSellingPrice);
34443 vikas.jang 178
                        approvalRequired = true;
33213 tejus.loha 179
 
180
                    } else {
181
                        throw new ProfitMandiBusinessException("Given price is greater than selling price for item Id - ", itemId, " it should be less or equal of DP");
182
                    }
183
 
184
                }
33338 amit.gupta 185
                totalPayableAmount += cartItem.getSellingPrice() * cartItem.getQuantity();
33172 tejus.loha 186
                cartItems.add(cartItem);
187
            }
34501 vikas.jang 188
            Bid bid = null;
189
            if (type.equals(ProfitMandiConstants.PO_TYPE.AUTO)) {
190
                bid = bidRepository.selectById(fofoBulkOrderModels.get(0).getRowIndex());
34592 vikas.jang 191
                approvalRequired = false;
34637 vikas.jang 192
                totalPayableAmount = totalPayableAmount - ProfitMandiConstants.BID_CHARGES;
34501 vikas.jang 193
            }
33338 amit.gupta 194
            LOGGER.info("totalAmount of item " + totalPayableAmount);
33172 tejus.loha 195
            double walletAmount = walletService.getWalletAmount(fofoId);
33338 amit.gupta 196
 
197
            BigDecimal creditAvailability = sdCreditService.getAvailableAmount(fofoId);
198
 
199
            double netAmountInHand = creditAvailability.doubleValue() + walletAmount;
33442 tejus.loha 200
            LOGGER.info("netAmountInHand - " + netAmountInHand);
33547 tejus.loha 201
            if (totalPayableAmount > ProfitMandiConstants.MAX_NEGATIVE_WALLET_VALUE && netAmountInHand < totalPayableAmount) {
34468 vikas.jang 202
                if (type.equals(ProfitMandiConstants.PO_TYPE.MANUAL)) {
34695 aman.kumar 203
                    throw new ProfitMandiBusinessException("Skipping order due to insufficient balance for id - ", fofoId, String.valueOf(fofoId));
34443 vikas.jang 204
                } else {
34468 vikas.jang 205
                    if (scheduleType.equals(ProfitMandiConstants.BID_CRON_ENUM.TODAY)) {
34592 vikas.jang 206
                        finalBidStatus = bidService.sendMailToRBM(netAmountInHand, totalPayableAmount, fofoId);
34572 vikas.jang 207
                        LOGGER.info("Skipping order due to insufficient balance for id - "+ fofoId+ " Sending mail to RBM");
208
                        //throw new ProfitMandiBusinessException("Skipping order due to insufficient balance for id - ", fofoId, " ,Sending mail to RBM");
34468 vikas.jang 209
                    } else {
34592 vikas.jang 210
                        finalBidStatus = bidService.cancelYesterdayProcessBid(bid);
34572 vikas.jang 211
                        LOGGER.info("Skipping order due to insufficient balance for id - "+ fofoId+ " Cancelling the BID");
212
                        //throw new ProfitMandiBusinessException("Skipping order due to insufficient balance for id - ", fofoId, " ,Cancelling the BID");
34468 vikas.jang 213
                    }
34443 vikas.jang 214
                }
33172 tejus.loha 215
            }
216
            UserCart userCart = cartService.setCartItems(fofoId, cartItems);
33213 tejus.loha 217
            // createtransactionInternally set the value in transaction table
33338 amit.gupta 218
 
33351 amit.gupta 219
            double creditAmountRequired = totalPayableAmount - walletAmount;
34312 ranu 220
            int loanId = 0;
34492 vikas.jang 221
            try {
222
                if (creditAmountRequired > ProfitMandiConstants.MAX_NEGATIVE_WALLET_VALUE) {
34576 vikas.jang 223
                    LOGGER.info("Creating new loan for: {}",userCart.getUserId());
34675 aman.kumar 224
                    BlockLoanIdSanctionId loan = sdCreditService.createSDDirectOrder(userCart.getUserId(), totalPayableAmount, 0);
34661 ranu 225
                    loanId = loan.getLoanId();
34492 vikas.jang 226
                }
227
            } catch (Exception exception){
34501 vikas.jang 228
                if (type.equals(ProfitMandiConstants.PO_TYPE.AUTO)) {
34592 vikas.jang 229
                    finalBidStatus = bidService.sendMailToRBM(netAmountInHand, totalPayableAmount, fofoId);
34572 vikas.jang 230
                    LOGGER.info("Skipping order due to insufficient balance for id - "+ fofoId+ " Cancelling the BID");
231
                    //throw new ProfitMandiBusinessException("Skipping order unable to create load for id - ", fofoId, " ,Sending mail to RBM");
34501 vikas.jang 232
                }
33338 amit.gupta 233
            }
34443 vikas.jang 234
 
34576 vikas.jang 235
            LOGGER.info("finalBidStatus: {}",finalBidStatus);
34573 vikas.jang 236
            if (finalBidStatus.equals(ProfitMandiConstants.BID_ENUM.CLOSED)) {
237
                int transactionId = transactionService.createTransactionInternally(userCart, totalPayableAmount, 0);
238
                //Set here created by
239
                Transaction transaction = transactionRepository.selectById(transactionId);
240
                transaction.setCreatedBy(creatorId);
34637 vikas.jang 241
                LOGGER.info("transaction created by {}", transaction.getCreatedBy());
34573 vikas.jang 242
                commonPaymentService.payThroughWallet(transactionId);
243
                if (approvalRequired) {
244
                    this.createApproval(transactionId);
245
                    if (loanId > 0) {
246
                        LoanTransaction loanTransaction = new LoanTransaction();
247
                        loanTransaction.setLoanId(loanId);
248
                        loanTransaction.setTransactionId(transactionId);
249
                        loanTransactionRepository.persist(loanTransaction);
250
                    }
251
                } else {
252
                    transactionService.processTransaction(transactionId, loanId);
253
                }
33213 tejus.loha 254
            }
255
 
33172 tejus.loha 256
        }
34592 vikas.jang 257
        return finalBidStatus;
33172 tejus.loha 258
    }
259
 
33213 tejus.loha 260
    public void createApproval(int transactionId) {
261
        TransactionApproval transactionApproval = new TransactionApproval();
262
        transactionApproval.setId(transactionId);
263
        transactionApproval.setStatus(TransactionApprovalStatus.PENDING);
264
        transactionApprovalRepository.persist(transactionApproval);
265
    }
266
 
33172 tejus.loha 267
    private BulkOrderModel createBulkModel(XSSFRow row) throws ProfitMandiBusinessException {
268
        BulkOrderModel bulkOrderModel = new BulkOrderModel();
269
        int i = 0;
270
        bulkOrderModel.setRowIndex(row.getRowNum());
271
        try {
33696 amit.gupta 272
            Cell partnerName = row.getCell(i++);
273
            if (partnerName == null)
33213 tejus.loha 274
                bulkOrderModel.setPartnerName("");
275
            else
33696 amit.gupta 276
                bulkOrderModel.setPartnerName(partnerName.getStringCellValue().trim());
33213 tejus.loha 277
            Cell description = row.getCell(i++);
278
            if (description == null)
279
                bulkOrderModel.setDescription("");
280
            else
281
                bulkOrderModel.setDescription(description.getStringCellValue().trim());
282
 
33172 tejus.loha 283
            bulkOrderModel.setFofoId((int) row.getCell(i++).getNumericCellValue());
284
            bulkOrderModel.setItemId((int) row.getCell(i++).getNumericCellValue());
33213 tejus.loha 285
            bulkOrderModel.setItemPrice(row.getCell(i++).getNumericCellValue());
33172 tejus.loha 286
            bulkOrderModel.setQuantity((int) row.getCell(i++).getNumericCellValue());
287
        } catch (Throwable e) {
288
            LOGGER.info(e.getCause());
33213 tejus.loha 289
            throw new ProfitMandiBusinessException("Field", "Field at row - " + row.getRowNum() + ", column - " + (i - 1), "Invalid field value at - " + ExcelUtils.toAlphabet(i - 1) + (row.getRowNum() + 1) + ", " + ExcelUtils.getCellValue(row.getCell(i - 1)));
33172 tejus.loha 290
        }
291
        LOGGER.info(bulkOrderModel);
292
        return bulkOrderModel;
293
    }
294
 
33341 tejus.loha 295
    // create model for transaction Approval so that finance team see all order and approve
296
    public List<TransactionApprovalModel> getAllPendingTransactionApproval() throws ProfitMandiBusinessException {
297
        List<TransactionApproval> transactionApprovals = transactionApprovalRepository.selectAllPending();
298
        LOGGER.info("list of Approval transaction Id " + transactionApprovals);
299
        List<TransactionApprovalModel> approvalModelList = new ArrayList<>();
300
        for (TransactionApproval transactionApproval : transactionApprovals) {
301
            List<Order> orderList = orderRepository.selectAllByTransactionId(transactionApproval.getId());
302
            Transaction transaction = transactionRepository.selectById(transactionApproval.getId());
303
            List<LineItemModel> lineItemModelList = new ArrayList<>();
304
            for (Order order : orderList) {
305
                LineItem lineItem = order.getLineItem();
306
                LineItemModel lineItemModel = new LineItemModel();
307
                lineItemModel.setItemId(lineItem.getItemId());
308
                lineItemModel.setItemName(lineItem.getItem().getItemDescription());
309
                lineItemModel.setItemQuantity(lineItem.getQuantity());
310
                lineItemModel.setSellingPrice(lineItem.getUnitPrice());
311
                lineItemModel.setDp(tagListingRepository.selectByItemId(lineItem.getItemId()).getSellingPrice());
312
                lineItemModelList.add(lineItemModel);
313
            }
314
            AuthUser authUser = authRepository.selectById(transaction.getCreatedBy());
315
            TransactionApprovalModel transactionApprovalModel = new TransactionApprovalModel();
316
            String retailerName = " ";
317
            retailerName = orderList.get(0).getRetailerName();
318
            transactionApprovalModel.setRetailerName(retailerName);
34573 vikas.jang 319
            if (authUser == null) {
320
                transactionApprovalModel.setCreatedBy(retailerName);
321
            } else {
322
                transactionApprovalModel.setCreatedBy(authUser.getFullName());
323
            }
33341 tejus.loha 324
            transactionApprovalModel.setCreatedOn(transaction.getCreateTimestamp());
325
            transactionApprovalModel.setTransactionId(transactionApproval.getId());
326
            transactionApprovalModel.setLineItemModels(lineItemModelList);
327
            approvalModelList.add(transactionApprovalModel);
33172 tejus.loha 328
 
33341 tejus.loha 329
        }
330
        return approvalModelList;
331
    }
332
 
33172 tejus.loha 333
}