Subversion Repositories SmartDukaan

Rev

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