Rev 33442 | Rev 33556 | 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.TagListing;import com.spice.profitmandi.dao.entity.transaction.LineItem;import com.spice.profitmandi.dao.entity.transaction.Order;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.auth.AuthRepository;import com.spice.profitmandi.dao.repository.catalog.TagListingRepository;import com.spice.profitmandi.dao.repository.dtr.UserRepository;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.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);@AutowiredCartService cartService;@AutowiredTransactionService transactionService;@AutowiredCommonPaymentService commonPaymentService;@AutowiredTagListingRepository tagListingRepository;@AutowiredWalletService walletService;@AutowiredUserRepository userRepository;@AutowiredTransactionRepository transactionRepository;@AutowiredTransactionApprovalRepository transactionApprovalRepository;@AutowiredAddressRepository addressRepository;@AutowiredOrderRepository orderRepository;@AutowiredAuthRepository authRepository;@AutowiredSDCreditRequirementRepository sdCreditRequirementRepository;//TODO:Tejus need to check@AutowiredSDCreditService 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 workbookXSSFSheet 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;}}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() == 0d;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;LOGGER.info("netAmountInHand - " + netAmountInHand);if (totalPayableAmount > ProfitMandiConstants.MAX_NEGATIVE_WALLET_VALUE && netAmountInHand < totalPayableAmount) {throw new ProfitMandiBusinessException("Skipping order due to insufficient balance for id - ", fofoId, " ,Check wallet Balance once");}UserCart userCart = cartService.setCartItems(fofoId, cartItems);// createtransactionInternally set the value in transaction tabledouble creditAmountRequired = totalPayableAmount - walletAmount;if (creditAmountRequired > ProfitMandiConstants.MAX_NEGATIVE_WALLET_VALUE) {sdCreditService.createLoan(userCart.getUserId(), creditAmountRequired, 0);}//return this.createLoan(userCart.getUserId(), creditAmountRequired);int transactionId = transactionService.createTransactionInternally(userCart, totalPayableAmount, 0);//Set here created byTransaction 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("");elsebulkOrderModel.setPartnerName(partneranme.getStringCellValue().trim());Cell description = row.getCell(i++);if (description == null)bulkOrderModel.setDescription("");elsebulkOrderModel.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 approvepublic 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);transactionApprovalModel.setCreatedBy(authUser.getFullName());transactionApprovalModel.setCreatedOn(transaction.getCreateTimestamp());transactionApprovalModel.setTransactionId(transactionApproval.getId());transactionApprovalModel.setLineItemModels(lineItemModelList);approvalModelList.add(transactionApprovalModel);}return approvalModelList;}}