Subversion Repositories SmartDukaan

Rev

Rev 34958 | Rev 35458 | 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;
60
import java.util.stream.Collectors;
61
 
33213 tejus.loha 62
@Service
63
@Transactional(rollbackFor = Throwable.class)
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
 
156
            List<CartItem> cartItems = new ArrayList<>();
33338 amit.gupta 157
            double totalPayableAmount = 0;
34957 amit 158
            BigDecimal totalPayableAmountBD = new BigDecimal(0);
33172 tejus.loha 159
            for (BulkOrderModel fofoBulkOrderModel : fofoBulkOrderModels) {
160
                CartItem cartItem = new CartItem();
161
                cartItem.setQuantity(fofoBulkOrderModel.getQuantity());
162
                cartItem.setItemId(fofoBulkOrderModel.getItemId());
163
                TagListing tagListing = tagListingRepository.selectByItemId(fofoBulkOrderModel.getItemId());
33556 amit.gupta 164
                if (tagListing == null) {
165
                    String message = "Pricing Does not exist for " + fofoBulkOrderModel.getItemId() + "(" + fofoBulkOrderModel.getDescription() + ")";
166
                    throw new ProfitMandiBusinessException(message, message, message);
167
                }
34832 ranu 168
                List<String> partnerIneligibleBrands = brandsService.partnerIneligibleBrands(fofoId);
169
                Item item = itemRepository.selectById(fofoBulkOrderModel.getItemId());
34856 ranu 170
                FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(fofoId);
171
                if (!fofoStore.isInternal()) {
172
                    if (partnerIneligibleBrands.contains(item.getBrand())) {
173
                        throw new ProfitMandiBusinessException("Brand is not allowed", "Brand ( " + item.getBrand() + ") is not allowed for this partner", "");
174
                    }
34832 ranu 175
                }
176
 
33213 tejus.loha 177
                double itemSellingPrice = tagListing.getSellingPrice();
33597 tejus.loha 178
                boolean isActualPrice = fofoBulkOrderModel.getItemPrice() == itemSellingPrice;
179
                boolean isPriceZero = fofoBulkOrderModel.getItemPrice() == 0d;
33213 tejus.loha 180
                double customSellingPrice = fofoBulkOrderModel.getItemPrice();
181
                int itemId = cartItem.getItemId();
33597 tejus.loha 182
                if (isPriceZero || isActualPrice) {
33213 tejus.loha 183
                    cartItem.setSellingPrice(itemSellingPrice);
184
                } else {
33216 tejus.loha 185
                    if (customSellingPrice <= tagListing.getMrp() || customSellingPrice <= tagListing.getMop()) {
33213 tejus.loha 186
                        cartItem.setSellingPrice(customSellingPrice);
34443 vikas.jang 187
                        approvalRequired = true;
33213 tejus.loha 188
 
189
                    } else {
190
                        throw new ProfitMandiBusinessException("Given price is greater than selling price for item Id - ", itemId, " it should be less or equal of DP");
191
                    }
192
 
193
                }
34958 amit 194
                totalPayableAmountBD = totalPayableAmountBD.add(new BigDecimal(String.valueOf(cartItem.getSellingPrice())).multiply(new BigDecimal(cartItem.getQuantity())));
33172 tejus.loha 195
                cartItems.add(cartItem);
196
            }
34957 amit 197
            totalPayableAmount = totalPayableAmountBD.doubleValue();
34501 vikas.jang 198
            Bid bid = null;
199
            if (type.equals(ProfitMandiConstants.PO_TYPE.AUTO)) {
200
                bid = bidRepository.selectById(fofoBulkOrderModels.get(0).getRowIndex());
34592 vikas.jang 201
                approvalRequired = false;
34957 amit 202
                totalPayableAmount = totalPayableAmountBD.doubleValue() - ProfitMandiConstants.BID_CHARGES;
34501 vikas.jang 203
            }
33338 amit.gupta 204
            LOGGER.info("totalAmount of item " + totalPayableAmount);
33172 tejus.loha 205
            double walletAmount = walletService.getWalletAmount(fofoId);
33338 amit.gupta 206
 
207
            BigDecimal creditAvailability = sdCreditService.getAvailableAmount(fofoId);
208
 
209
            double netAmountInHand = creditAvailability.doubleValue() + walletAmount;
33442 tejus.loha 210
            LOGGER.info("netAmountInHand - " + netAmountInHand);
33547 tejus.loha 211
            if (totalPayableAmount > ProfitMandiConstants.MAX_NEGATIVE_WALLET_VALUE && netAmountInHand < totalPayableAmount) {
34468 vikas.jang 212
                if (type.equals(ProfitMandiConstants.PO_TYPE.MANUAL)) {
34695 aman.kumar 213
                    throw new ProfitMandiBusinessException("Skipping order due to insufficient balance for id - ", fofoId, String.valueOf(fofoId));
34443 vikas.jang 214
                } else {
34468 vikas.jang 215
                    if (scheduleType.equals(ProfitMandiConstants.BID_CRON_ENUM.TODAY)) {
34592 vikas.jang 216
                        finalBidStatus = bidService.sendMailToRBM(netAmountInHand, totalPayableAmount, fofoId);
34572 vikas.jang 217
                        LOGGER.info("Skipping order due to insufficient balance for id - "+ fofoId+ " Sending mail to RBM");
218
                        //throw new ProfitMandiBusinessException("Skipping order due to insufficient balance for id - ", fofoId, " ,Sending mail to RBM");
34468 vikas.jang 219
                    } else {
34592 vikas.jang 220
                        finalBidStatus = bidService.cancelYesterdayProcessBid(bid);
34572 vikas.jang 221
                        LOGGER.info("Skipping order due to insufficient balance for id - "+ fofoId+ " Cancelling the BID");
222
                        //throw new ProfitMandiBusinessException("Skipping order due to insufficient balance for id - ", fofoId, " ,Cancelling the BID");
34468 vikas.jang 223
                    }
34443 vikas.jang 224
                }
33172 tejus.loha 225
            }
226
            UserCart userCart = cartService.setCartItems(fofoId, cartItems);
33213 tejus.loha 227
            // createtransactionInternally set the value in transaction table
33338 amit.gupta 228
 
33351 amit.gupta 229
            double creditAmountRequired = totalPayableAmount - walletAmount;
34312 ranu 230
            int loanId = 0;
34492 vikas.jang 231
            try {
232
                if (creditAmountRequired > ProfitMandiConstants.MAX_NEGATIVE_WALLET_VALUE) {
34576 vikas.jang 233
                    LOGGER.info("Creating new loan for: {}",userCart.getUserId());
34675 aman.kumar 234
                    BlockLoanIdSanctionId loan = sdCreditService.createSDDirectOrder(userCart.getUserId(), totalPayableAmount, 0);
34661 ranu 235
                    loanId = loan.getLoanId();
34492 vikas.jang 236
                }
237
            } catch (Exception exception){
34501 vikas.jang 238
                if (type.equals(ProfitMandiConstants.PO_TYPE.AUTO)) {
34592 vikas.jang 239
                    finalBidStatus = bidService.sendMailToRBM(netAmountInHand, totalPayableAmount, fofoId);
34572 vikas.jang 240
                    LOGGER.info("Skipping order due to insufficient balance for id - "+ fofoId+ " Cancelling the BID");
241
                    //throw new ProfitMandiBusinessException("Skipping order unable to create load for id - ", fofoId, " ,Sending mail to RBM");
34501 vikas.jang 242
                }
33338 amit.gupta 243
            }
34443 vikas.jang 244
 
34576 vikas.jang 245
            LOGGER.info("finalBidStatus: {}",finalBidStatus);
34573 vikas.jang 246
            if (finalBidStatus.equals(ProfitMandiConstants.BID_ENUM.CLOSED)) {
34959 amit 247
                LOGGER.info("totalPayableAmount - {}", totalPayableAmount);
34573 vikas.jang 248
                int transactionId = transactionService.createTransactionInternally(userCart, totalPayableAmount, 0);
249
                //Set here created by
250
                Transaction transaction = transactionRepository.selectById(transactionId);
251
                transaction.setCreatedBy(creatorId);
34637 vikas.jang 252
                LOGGER.info("transaction created by {}", transaction.getCreatedBy());
34573 vikas.jang 253
                commonPaymentService.payThroughWallet(transactionId);
254
                if (approvalRequired) {
255
                    this.createApproval(transactionId);
256
                    if (loanId > 0) {
257
                        LoanTransaction loanTransaction = new LoanTransaction();
258
                        loanTransaction.setLoanId(loanId);
259
                        loanTransaction.setTransactionId(transactionId);
260
                        loanTransactionRepository.persist(loanTransaction);
261
                    }
262
                } else {
263
                    transactionService.processTransaction(transactionId, loanId);
264
                }
33213 tejus.loha 265
            }
266
 
33172 tejus.loha 267
        }
34592 vikas.jang 268
        return finalBidStatus;
33172 tejus.loha 269
    }
270
 
33213 tejus.loha 271
    public void createApproval(int transactionId) {
272
        TransactionApproval transactionApproval = new TransactionApproval();
273
        transactionApproval.setId(transactionId);
274
        transactionApproval.setStatus(TransactionApprovalStatus.PENDING);
275
        transactionApprovalRepository.persist(transactionApproval);
276
    }
277
 
33172 tejus.loha 278
    private BulkOrderModel createBulkModel(XSSFRow row) throws ProfitMandiBusinessException {
279
        BulkOrderModel bulkOrderModel = new BulkOrderModel();
280
        int i = 0;
281
        bulkOrderModel.setRowIndex(row.getRowNum());
282
        try {
33696 amit.gupta 283
            Cell partnerName = row.getCell(i++);
284
            if (partnerName == null)
33213 tejus.loha 285
                bulkOrderModel.setPartnerName("");
286
            else
33696 amit.gupta 287
                bulkOrderModel.setPartnerName(partnerName.getStringCellValue().trim());
33213 tejus.loha 288
            Cell description = row.getCell(i++);
289
            if (description == null)
290
                bulkOrderModel.setDescription("");
291
            else
292
                bulkOrderModel.setDescription(description.getStringCellValue().trim());
293
 
33172 tejus.loha 294
            bulkOrderModel.setFofoId((int) row.getCell(i++).getNumericCellValue());
295
            bulkOrderModel.setItemId((int) row.getCell(i++).getNumericCellValue());
33213 tejus.loha 296
            bulkOrderModel.setItemPrice(row.getCell(i++).getNumericCellValue());
33172 tejus.loha 297
            bulkOrderModel.setQuantity((int) row.getCell(i++).getNumericCellValue());
298
        } catch (Throwable e) {
299
            LOGGER.info(e.getCause());
33213 tejus.loha 300
            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 301
        }
302
        LOGGER.info(bulkOrderModel);
303
        return bulkOrderModel;
304
    }
305
 
33341 tejus.loha 306
    // create model for transaction Approval so that finance team see all order and approve
307
    public List<TransactionApprovalModel> getAllPendingTransactionApproval() throws ProfitMandiBusinessException {
308
        List<TransactionApproval> transactionApprovals = transactionApprovalRepository.selectAllPending();
309
        LOGGER.info("list of Approval transaction Id " + transactionApprovals);
310
        List<TransactionApprovalModel> approvalModelList = new ArrayList<>();
311
        for (TransactionApproval transactionApproval : transactionApprovals) {
312
            List<Order> orderList = orderRepository.selectAllByTransactionId(transactionApproval.getId());
313
            Transaction transaction = transactionRepository.selectById(transactionApproval.getId());
314
            List<LineItemModel> lineItemModelList = new ArrayList<>();
315
            for (Order order : orderList) {
316
                LineItem lineItem = order.getLineItem();
317
                LineItemModel lineItemModel = new LineItemModel();
318
                lineItemModel.setItemId(lineItem.getItemId());
319
                lineItemModel.setItemName(lineItem.getItem().getItemDescription());
320
                lineItemModel.setItemQuantity(lineItem.getQuantity());
321
                lineItemModel.setSellingPrice(lineItem.getUnitPrice());
322
                lineItemModel.setDp(tagListingRepository.selectByItemId(lineItem.getItemId()).getSellingPrice());
323
                lineItemModelList.add(lineItemModel);
324
            }
325
            AuthUser authUser = authRepository.selectById(transaction.getCreatedBy());
326
            TransactionApprovalModel transactionApprovalModel = new TransactionApprovalModel();
327
            String retailerName = " ";
328
            retailerName = orderList.get(0).getRetailerName();
329
            transactionApprovalModel.setRetailerName(retailerName);
34573 vikas.jang 330
            if (authUser == null) {
331
                transactionApprovalModel.setCreatedBy(retailerName);
332
            } else {
333
                transactionApprovalModel.setCreatedBy(authUser.getFullName());
334
            }
33341 tejus.loha 335
            transactionApprovalModel.setCreatedOn(transaction.getCreateTimestamp());
336
            transactionApprovalModel.setTransactionId(transactionApproval.getId());
337
            transactionApprovalModel.setLineItemModels(lineItemModelList);
338
            approvalModelList.add(transactionApprovalModel);
33172 tejus.loha 339
 
33341 tejus.loha 340
        }
341
        return approvalModelList;
342
    }
343
 
33172 tejus.loha 344
}