Subversion Repositories SmartDukaan

Rev

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