Subversion Repositories SmartDukaan

Rev

Rev 33219 | Rev 33341 | 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.util.ExcelUtils;
import com.spice.profitmandi.dao.cart.CartService;
import com.spice.profitmandi.dao.entity.catalog.TagListing;
import com.spice.profitmandi.dao.entity.transaction.SDCreditRequirement;
import com.spice.profitmandi.dao.entity.transaction.Transaction;
import com.spice.profitmandi.dao.entity.transaction.TransactionApproval;
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.catalog.TagListingRepository;
import com.spice.profitmandi.dao.repository.dtr.UserRepository;
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.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;
    //TODO:Tejus need to check

    @Autowired
    SDCreditService sdCreditService;


    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<>();
        for (int rowNumber = 1; rowNumber <= mySheet.getLastRowNum(); rowNumber++) {
            XSSFRow row = mySheet.getRow(rowNumber);
            BulkOrderModel bulkOrderModel = this.createBulkModel(row);
            bulkOrderModels.add(bulkOrderModel);
        }
        Map<Integer, List<BulkOrderModel>> fofoBulkOrdersMap = bulkOrderModels.stream().collect(Collectors.groupingBy(x -> x.getFofoId()));
        boolean approvalNotRequired = true;
        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());
                boolean isPriceZero = fofoBulkOrderModel.getItemPrice() == 0.0;
                TagListing tagListing = tagListingRepository.selectByItemId(fofoBulkOrderModel.getItemId());
                double itemSellingPrice = tagListing.getSellingPrice();
                double customSellingPrice = fofoBulkOrderModel.getItemPrice();
                int itemId = cartItem.getItemId();
                if (isPriceZero) {
                    cartItem.setSellingPrice(itemSellingPrice);
                } else {
                    if (customSellingPrice <= tagListing.getMrp() || customSellingPrice <= tagListing.getMop()) {
                        cartItem.setSellingPrice(customSellingPrice);
                        approvalNotRequired = false;

                    } 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);
            }
            LOGGER.info("totalAmount of item " + totalPayableAmount);
            double walletAmount = walletService.getWalletAmount(fofoId);

            BigDecimal creditAvailability = sdCreditService.getAvailableAmount(fofoId);

            double netAmountInHand = creditAvailability.doubleValue() + walletAmount;
            if (totalPayableAmount > 20 && walletAmount < netAmountInHand) {
                throw new ProfitMandiBusinessException("Skippin order due to insufficent balance for id - ", fofoId, " ,Check wallet Balance ones");
            }
            UserCart userCart = cartService.setCartItems(fofoId, cartItems);
            // createtransactionInternally set the value in transaction table

            double creditAmountRequired = totalPayableAmount - walletAmount - 20;
            if (creditAmountRequired > 0d) {
                sdCreditService.createLoan(userCart.getUserId(), creditAmountRequired, 0);
            }
            //return this.createLoan(userCart.getUserId(), creditAmountRequired);
            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 (approvalNotRequired) {
                transactionService.processTransaction(transactionId);
            } else {
                this.createApproval(transactionId);
            }

        }

    }

    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 partneranme = row.getCell(i++);
            if (partneranme == null)
                bulkOrderModel.setPartnerName("");
            else
                bulkOrderModel.setPartnerName(partneranme.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;
    }


}