Subversion Repositories SmartDukaan

Rev

Rev 34592 | Rev 34661 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

package com.spice.profitmandi.service.order;

import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
import com.spice.profitmandi.common.model.BulkOrderModel;
import com.spice.profitmandi.common.model.LineItemModel;
import com.spice.profitmandi.common.model.ProfitMandiConstants;
import com.spice.profitmandi.common.model.TransactionApprovalModel;
import com.spice.profitmandi.common.util.ExcelUtils;
import com.spice.profitmandi.dao.cart.CartService;
import com.spice.profitmandi.dao.entity.auth.AuthUser;
import com.spice.profitmandi.dao.entity.catalog.Bid;
import com.spice.profitmandi.dao.entity.catalog.TagListing;
import com.spice.profitmandi.dao.entity.fofo.LoanTransaction;
import com.spice.profitmandi.dao.entity.transaction.*;
import com.spice.profitmandi.dao.enumuration.transaction.TransactionApprovalStatus;
import com.spice.profitmandi.dao.model.CartItem;
import com.spice.profitmandi.dao.model.UserCart;
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
import com.spice.profitmandi.dao.repository.catalog.BidRepository;
import com.spice.profitmandi.dao.repository.catalog.LiquidationRepository;
import com.spice.profitmandi.dao.repository.catalog.TagListingRepository;
import com.spice.profitmandi.dao.repository.cs.CsService;
import com.spice.profitmandi.dao.repository.dtr.UserRepository;
import com.spice.profitmandi.dao.repository.fofo.LoanTransactionRepository;
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
import com.spice.profitmandi.dao.repository.transaction.SDCreditRequirementRepository;
import com.spice.profitmandi.dao.repository.transaction.TransactionApprovalRepository;
import com.spice.profitmandi.dao.repository.transaction.TransactionRepository;
import com.spice.profitmandi.dao.repository.user.AddressRepository;
import com.spice.profitmandi.dao.service.BidService;
import com.spice.profitmandi.service.transaction.SDCreditService;
import com.spice.profitmandi.service.transaction.TransactionService;
import com.spice.profitmandi.service.wallet.CommonPaymentService;
import com.spice.profitmandi.service.wallet.WalletService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional(rollbackFor = Throwable.class)
public class BulkOrderService {
    private static final Logger LOGGER = LogManager.getLogger(BulkOrderService.class);
    @Autowired
    CartService cartService;
    @Autowired
    TransactionService transactionService;
    @Autowired
    CommonPaymentService commonPaymentService;
    @Autowired
    TagListingRepository tagListingRepository;
    @Autowired
    WalletService walletService;
    @Autowired
    UserRepository userRepository;
    @Autowired
    TransactionRepository transactionRepository;
    @Autowired
    TransactionApprovalRepository transactionApprovalRepository;
    @Autowired
    AddressRepository addressRepository;
    @Autowired
    OrderRepository orderRepository;
    //TODO:Tejus need to check
    @Autowired
    SDCreditRequirementRepository sdCreditRequirementRepository;
    @Autowired
    SDCreditService sdCreditService;
    @Autowired
    private CsService csService;
    @Autowired
    private AuthRepository authRepository;
    @Autowired
    private BidRepository bidRepository;
    @Autowired
    private BidService bidService;

    @Autowired
    private LoanTransactionRepository loanTransactionRepository;

    @Autowired
    private LiquidationRepository liquidationRepository;


    public void parseBulkOrders(MultipartFile file, int creatorId) throws Exception {
        XSSFWorkbook myWorkBook = new XSSFWorkbook(file.getInputStream());

        myWorkBook.setMissingCellPolicy(Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
        // Return first sheet from the XLSX workbook
        XSSFSheet mySheet = myWorkBook.getSheetAt(0);
        LOGGER.info("rowCellNum {}", mySheet.getLastRowNum());
        List<BulkOrderModel> bulkOrderModels = new ArrayList<>();
        LOGGER.info("mySheet.getLastRowNum() - {}", mySheet.getLastRowNum());
        for (int rowNumber = 1; rowNumber <= mySheet.getLastRowNum(); rowNumber++) {
            XSSFRow row = mySheet.getRow(rowNumber);
            LOGGER.info("Row - {}", row);
            if (row != null) {
                BulkOrderModel bulkOrderModel = this.createBulkModel(row);
                bulkOrderModels.add(bulkOrderModel);
            } else {
                break;
            }
        }
        this.generatePurchaseOrder(bulkOrderModels, creatorId, ProfitMandiConstants.PO_TYPE.MANUAL, ProfitMandiConstants.BID_CRON_ENUM.TODAY);
    }

    public ProfitMandiConstants.BID_ENUM generatePurchaseOrder(List<BulkOrderModel> bulkOrderModels, int creatorId, ProfitMandiConstants.PO_TYPE type, ProfitMandiConstants.BID_CRON_ENUM scheduleType) throws Exception {
        Map<Integer, List<BulkOrderModel>> fofoBulkOrdersMap = bulkOrderModels.stream().collect(Collectors.groupingBy(x -> x.getFofoId()));
        boolean approvalRequired = false;
        ProfitMandiConstants.BID_ENUM finalBidStatus = ProfitMandiConstants.BID_ENUM.CLOSED;
        for (Map.Entry<Integer, List<BulkOrderModel>> fofoBulkOrderEntry : fofoBulkOrdersMap.entrySet()) {
            int fofoId = fofoBulkOrderEntry.getKey();
            List<BulkOrderModel> fofoBulkOrderModels = fofoBulkOrderEntry.getValue();
            Map<Integer, Long> orderItemCountMap = fofoBulkOrderModels.stream().collect(Collectors.groupingBy(x -> x.getItemId(), Collectors.counting()));

            if (orderItemCountMap.entrySet().stream().filter(x -> x.getValue() > 1).count() > 0) {
                throw new ProfitMandiBusinessException("Fofo ID", fofoId, "Duplicate in items");
            }

            boolean hasZeroQuantity = fofoBulkOrderModels.stream().filter(x -> x.getQuantity() <= 0).count() > 0;
            if (hasZeroQuantity) {
                throw new ProfitMandiBusinessException("Item Quantity", "", "Should be greater than 0");
            }

            List<CartItem> cartItems = new ArrayList<>();
            double totalPayableAmount = 0;
            for (BulkOrderModel fofoBulkOrderModel : fofoBulkOrderModels) {
                CartItem cartItem = new CartItem();
                cartItem.setQuantity(fofoBulkOrderModel.getQuantity());
                cartItem.setItemId(fofoBulkOrderModel.getItemId());
                TagListing tagListing = tagListingRepository.selectByItemId(fofoBulkOrderModel.getItemId());
                if (tagListing == null) {
                    String message = "Pricing Does not exist for " + fofoBulkOrderModel.getItemId() + "(" + fofoBulkOrderModel.getDescription() + ")";
                    throw new ProfitMandiBusinessException(message, message, message);
                }
                double itemSellingPrice = tagListing.getSellingPrice();
                boolean isActualPrice = fofoBulkOrderModel.getItemPrice() == itemSellingPrice;
                boolean isPriceZero = fofoBulkOrderModel.getItemPrice() == 0d;
                double customSellingPrice = fofoBulkOrderModel.getItemPrice();
                int itemId = cartItem.getItemId();
                if (isPriceZero || isActualPrice) {
                    cartItem.setSellingPrice(itemSellingPrice);
                } else {
                    if (customSellingPrice <= tagListing.getMrp() || customSellingPrice <= tagListing.getMop()) {
                        cartItem.setSellingPrice(customSellingPrice);
                        approvalRequired = true;

                    } else {
                        throw new ProfitMandiBusinessException("Given price is greater than selling price for item Id - ", itemId, " it should be less or equal of DP");
                    }

                }
                totalPayableAmount += cartItem.getSellingPrice() * cartItem.getQuantity();
                cartItems.add(cartItem);
            }
            Bid bid = null;
            if (type.equals(ProfitMandiConstants.PO_TYPE.AUTO)) {
                bid = bidRepository.selectById(fofoBulkOrderModels.get(0).getRowIndex());
                approvalRequired = false;
                totalPayableAmount = totalPayableAmount - ProfitMandiConstants.BID_CHARGES;
            }
            LOGGER.info("totalAmount of item " + totalPayableAmount);
            double walletAmount = walletService.getWalletAmount(fofoId);

            BigDecimal creditAvailability = sdCreditService.getAvailableAmount(fofoId);

            double netAmountInHand = creditAvailability.doubleValue() + walletAmount;
            LOGGER.info("netAmountInHand - " + netAmountInHand);
            if (totalPayableAmount > ProfitMandiConstants.MAX_NEGATIVE_WALLET_VALUE && netAmountInHand < totalPayableAmount) {
                if (type.equals(ProfitMandiConstants.PO_TYPE.MANUAL)) {
                    throw new ProfitMandiBusinessException("Skipping order due to insufficient balance for id - ", fofoId, " ,Check wallet Balance once");
                } else {
                    if (scheduleType.equals(ProfitMandiConstants.BID_CRON_ENUM.TODAY)) {
                        finalBidStatus = bidService.sendMailToRBM(netAmountInHand, totalPayableAmount, fofoId);
                        LOGGER.info("Skipping order due to insufficient balance for id - "+ fofoId+ " Sending mail to RBM");
                        //throw new ProfitMandiBusinessException("Skipping order due to insufficient balance for id - ", fofoId, " ,Sending mail to RBM");
                    } else {
                        finalBidStatus = bidService.cancelYesterdayProcessBid(bid);
                        LOGGER.info("Skipping order due to insufficient balance for id - "+ fofoId+ " Cancelling the BID");
                        //throw new ProfitMandiBusinessException("Skipping order due to insufficient balance for id - ", fofoId, " ,Cancelling the BID");
                    }
                }
            }
            UserCart userCart = cartService.setCartItems(fofoId, cartItems);
            // createtransactionInternally set the value in transaction table

            double creditAmountRequired = totalPayableAmount - walletAmount;
            int loanId = 0;
            try {
                if (creditAmountRequired > ProfitMandiConstants.MAX_NEGATIVE_WALLET_VALUE) {
                    LOGGER.info("Creating new loan for: {}",userCart.getUserId());
                    Loan loan = sdCreditService.createLoan(userCart.getUserId(), creditAmountRequired, 0, "Credit limit assigned via SD Credit");
                    loanId = loan.getId();
                }
            } catch (Exception exception){
                if (type.equals(ProfitMandiConstants.PO_TYPE.AUTO)) {
                    finalBidStatus = bidService.sendMailToRBM(netAmountInHand, totalPayableAmount, fofoId);
                    LOGGER.info("Skipping order due to insufficient balance for id - "+ fofoId+ " Cancelling the BID");
                    //throw new ProfitMandiBusinessException("Skipping order unable to create load for id - ", fofoId, " ,Sending mail to RBM");
                }
            }

            LOGGER.info("finalBidStatus: {}",finalBidStatus);
            if (finalBidStatus.equals(ProfitMandiConstants.BID_ENUM.CLOSED)) {
                int transactionId = transactionService.createTransactionInternally(userCart, totalPayableAmount, 0);
                //Set here created by
                Transaction transaction = transactionRepository.selectById(transactionId);
                transaction.setCreatedBy(creatorId);
                LOGGER.info("transaction created by {}", transaction.getCreatedBy());
                commonPaymentService.payThroughWallet(transactionId);
                if (approvalRequired) {
                    this.createApproval(transactionId);
                    if (loanId > 0) {
                        LoanTransaction loanTransaction = new LoanTransaction();
                        loanTransaction.setLoanId(loanId);
                        loanTransaction.setTransactionId(transactionId);
                        loanTransactionRepository.persist(loanTransaction);
                    }
                } else {
                    transactionService.processTransaction(transactionId, loanId);
                }
            }

        }
        return finalBidStatus;
    }

    public void createApproval(int transactionId) {
        TransactionApproval transactionApproval = new TransactionApproval();
        transactionApproval.setId(transactionId);
        transactionApproval.setStatus(TransactionApprovalStatus.PENDING);
        transactionApprovalRepository.persist(transactionApproval);
    }

    private BulkOrderModel createBulkModel(XSSFRow row) throws ProfitMandiBusinessException {
        BulkOrderModel bulkOrderModel = new BulkOrderModel();
        int i = 0;
        bulkOrderModel.setRowIndex(row.getRowNum());
        try {
            Cell partnerName = row.getCell(i++);
            if (partnerName == null)
                bulkOrderModel.setPartnerName("");
            else
                bulkOrderModel.setPartnerName(partnerName.getStringCellValue().trim());
            Cell description = row.getCell(i++);
            if (description == null)
                bulkOrderModel.setDescription("");
            else
                bulkOrderModel.setDescription(description.getStringCellValue().trim());

            bulkOrderModel.setFofoId((int) row.getCell(i++).getNumericCellValue());
            bulkOrderModel.setItemId((int) row.getCell(i++).getNumericCellValue());
            bulkOrderModel.setItemPrice(row.getCell(i++).getNumericCellValue());
            bulkOrderModel.setQuantity((int) row.getCell(i++).getNumericCellValue());
        } catch (Throwable e) {
            LOGGER.info(e.getCause());
            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)));
        }
        LOGGER.info(bulkOrderModel);
        return bulkOrderModel;
    }

    // create model for transaction Approval so that finance team see all order and approve
    public List<TransactionApprovalModel> getAllPendingTransactionApproval() throws ProfitMandiBusinessException {
        List<TransactionApproval> transactionApprovals = transactionApprovalRepository.selectAllPending();
        LOGGER.info("list of Approval transaction Id " + transactionApprovals);
        List<TransactionApprovalModel> approvalModelList = new ArrayList<>();
        for (TransactionApproval transactionApproval : transactionApprovals) {
            List<Order> orderList = orderRepository.selectAllByTransactionId(transactionApproval.getId());
            Transaction transaction = transactionRepository.selectById(transactionApproval.getId());
            List<LineItemModel> lineItemModelList = new ArrayList<>();
            for (Order order : orderList) {
                LineItem lineItem = order.getLineItem();
                LineItemModel lineItemModel = new LineItemModel();
                lineItemModel.setItemId(lineItem.getItemId());
                lineItemModel.setItemName(lineItem.getItem().getItemDescription());
                lineItemModel.setItemQuantity(lineItem.getQuantity());
                lineItemModel.setSellingPrice(lineItem.getUnitPrice());
                lineItemModel.setDp(tagListingRepository.selectByItemId(lineItem.getItemId()).getSellingPrice());
                lineItemModelList.add(lineItemModel);
            }
            AuthUser authUser = authRepository.selectById(transaction.getCreatedBy());
            TransactionApprovalModel transactionApprovalModel = new TransactionApprovalModel();
            String retailerName = " ";
            retailerName = orderList.get(0).getRetailerName();
            transactionApprovalModel.setRetailerName(retailerName);
            if (authUser == null) {
                transactionApprovalModel.setCreatedBy(retailerName);
            } else {
                transactionApprovalModel.setCreatedBy(authUser.getFullName());
            }
            transactionApprovalModel.setCreatedOn(transaction.getCreateTimestamp());
            transactionApprovalModel.setTransactionId(transactionApproval.getId());
            transactionApprovalModel.setLineItemModels(lineItemModelList);
            approvalModelList.add(transactionApprovalModel);

        }
        return approvalModelList;
    }

}