Subversion Repositories SmartDukaan

Rev

Rev 33173 | 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.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.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.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.Controller;
import org.springframework.web.multipart.MultipartFile;

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

@Controller
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
    ExcelUtils excelUtils;

    public void parseBulkOrders(MultipartFile file) 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()));
        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 totalAmount = 0;
            for (BulkOrderModel fofoBulkOrderModel : fofoBulkOrderModels) {
                CartItem cartItem = new CartItem();
                cartItem.setQuantity(fofoBulkOrderModel.getQuantity());
                cartItem.setItemId(fofoBulkOrderModel.getItemId());
                TagListing tagListing = tagListingRepository.selectByItemId(fofoBulkOrderModel.getItemId());
                //TODO:Tejus need to check
                cartItem.setSellingPrice(tagListing.getSellingPrice());
                totalAmount += cartItem.getSellingPrice() * cartItem.getQuantity();
                cartItems.add(cartItem);


            }
            LOGGER.info("totalAmount of item " + totalAmount);
            double walletAmount = walletService.getWalletAmount(fofoId);

            if (walletAmount < totalAmount) {
                LOGGER.info("Skippin order due to insufficent balance for id - {}", fofoId);
                continue;
            }
            UserCart userCart = cartService.setCartItems(fofoId, cartItems);
            int transactionId = transactionService.createTransactionInternally(userCart, totalAmount, 0);
            commonPaymentService.payThroughWallet(transactionId);
            // Once paid let proceed to process the order further.
            transactionService.processTransaction(transactionId);
        }
    }

    private BulkOrderModel createBulkModel(XSSFRow row) throws ProfitMandiBusinessException {
        BulkOrderModel bulkOrderModel = new BulkOrderModel();
        int i = 0;
        bulkOrderModel.setRowIndex(row.getRowNum());
        try {
            bulkOrderModel.setName(row.getCell(i++).getStringCellValue());
            bulkOrderModel.setDescription(row.getCell(i++).getStringCellValue());
            bulkOrderModel.setFofoId((int) row.getCell(i++).getNumericCellValue());
            bulkOrderModel.setItemId((int) 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;
    }


}