Subversion Repositories SmartDukaan

Rev

Rev 23116 | Rev 23190 | Go to most recent revision | View as "text/plain" | Blame | Compare with Previous | Last modification | View Log | RSS feed

package com.spice.profitmandi.service.inventory;

import java.time.DateTimeException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
import com.spice.profitmandi.common.model.CartFofo;
import com.spice.profitmandi.common.model.CreateOrderRequest;
import com.spice.profitmandi.common.model.CustomAddress;
import com.spice.profitmandi.common.model.CustomCustomer;
import com.spice.profitmandi.common.model.CustomFofoOrderItem;
import com.spice.profitmandi.common.model.CustomInsurancePolicy;
import com.spice.profitmandi.common.model.CustomOrderItem;
import com.spice.profitmandi.common.model.CustomPaymentOption;
import com.spice.profitmandi.common.model.CustomRetailer;
import com.spice.profitmandi.common.model.GadgetCopsInsuranceModel;
import com.spice.profitmandi.common.model.GstRate;
import com.spice.profitmandi.common.model.ItemIdQuantityAvailability;
import com.spice.profitmandi.common.model.PdfModel;
import com.spice.profitmandi.common.model.PriceModel;
import com.spice.profitmandi.common.model.ProfitMandiConstants;
import com.spice.profitmandi.common.model.Quantity;
import com.spice.profitmandi.common.model.SerialNumberDetail;
import com.spice.profitmandi.common.util.InsuranceUtils;
import com.spice.profitmandi.common.util.StringUtils;
import com.spice.profitmandi.common.util.Utils;
import com.spice.profitmandi.dao.entity.catalog.Item;
import com.spice.profitmandi.dao.entity.dtr.GadgetCopsInsuranceCalc;
import com.spice.profitmandi.dao.entity.dtr.InsurancePolicy;
import com.spice.profitmandi.dao.entity.dtr.InsuranceProvider;
import com.spice.profitmandi.dao.entity.dtr.PolicyNumberGenerationSequence;
import com.spice.profitmandi.dao.entity.dtr.Retailer;
import com.spice.profitmandi.dao.entity.dtr.User;
import com.spice.profitmandi.dao.entity.fofo.CurrentInventorySnapshot;
import com.spice.profitmandi.dao.entity.fofo.Customer;
import com.spice.profitmandi.dao.entity.fofo.CustomerAddress;
import com.spice.profitmandi.dao.entity.fofo.FofoLineItem;
import com.spice.profitmandi.dao.entity.fofo.FofoOrder;
import com.spice.profitmandi.dao.entity.fofo.FofoOrderItem;
import com.spice.profitmandi.dao.entity.fofo.InventoryItem;
import com.spice.profitmandi.dao.entity.fofo.InvoiceNumberGenerationSequence;
import com.spice.profitmandi.dao.entity.fofo.PaymentOption;
import com.spice.profitmandi.dao.entity.fofo.ScanRecord;
import com.spice.profitmandi.dao.entity.user.Address;
import com.spice.profitmandi.dao.entity.user.Counter;
import com.spice.profitmandi.dao.entity.user.PrivateDealUser;
import com.spice.profitmandi.dao.enumuration.fofo.PaymentOptionType;
import com.spice.profitmandi.dao.enumuration.fofo.ScanType;
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
import com.spice.profitmandi.dao.repository.dtr.InsurancePolicyRepository;
import com.spice.profitmandi.dao.repository.dtr.InsuranceProviderRepository;
import com.spice.profitmandi.dao.repository.dtr.PolicyNumberGenerationSequenceRepository;
import com.spice.profitmandi.dao.repository.dtr.RetailerRegisteredAddressRepository;
import com.spice.profitmandi.dao.repository.dtr.RetailerRepository;
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
import com.spice.profitmandi.dao.repository.dtr.UserRepository;
import com.spice.profitmandi.dao.repository.fofo.CurrentInventorySnapshotRepository;
import com.spice.profitmandi.dao.repository.fofo.CustomerAddressRepository;
import com.spice.profitmandi.dao.repository.fofo.CustomerRepository;
import com.spice.profitmandi.dao.repository.fofo.FofoLineItemRepository;
import com.spice.profitmandi.dao.repository.fofo.FofoOrderItemRepository;
import com.spice.profitmandi.dao.repository.fofo.FofoOrderRepository;
import com.spice.profitmandi.dao.repository.fofo.InventoryItemRepository;
import com.spice.profitmandi.dao.repository.fofo.InvoiceNumberGenerationSequenceRepository;
import com.spice.profitmandi.dao.repository.fofo.PaymentOptionRepository;
import com.spice.profitmandi.dao.repository.fofo.ScanRecordRepository;
import com.spice.profitmandi.dao.repository.user.AddressRepository;
import com.spice.profitmandi.dao.repository.user.CounterRepository;
import com.spice.profitmandi.dao.repository.user.PrivateDealUserRepository;
import com.spice.profitmandi.service.pricing.PricingService;
import com.spice.profitmandi.service.scheme.SchemeService;

import in.shop2020.model.v1.catalog.ItemType;

@Component
public class OrderServiceImpl implements OrderService {

        private static final Logger LOGGER = LoggerFactory.getLogger(OrderServiceImpl.class);

        @Autowired
        private InventoryItemRepository inventoryItemRepository;

        @Autowired
        private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;

        @Autowired
        private InvoiceNumberGenerationSequenceRepository invoiceNumberGenerationSequenceRepository;

        @Autowired
        private CustomerRepository customerRepository;

        @Autowired
        private AddressRepository addressRepository;

        @Autowired
        private FofoLineItemRepository fofoLineItemRepository;

        @Autowired
        private FofoOrderItemRepository fofoOrderItemRepository;
        
        @Autowired
        private PaymentOptionRepository paymentOptionRepository;

        @Autowired
        private ScanRecordRepository scanRecordRepository;

        @Autowired
        private FofoOrderRepository fofoOrderRepository;

        @Autowired
        private RetailerRepository retailerRepository;

        @Autowired
        private UserRepository userRepository;

        @Autowired
        private UserAccountRepository userAccountRepository;

        @Autowired
        private RetailerRegisteredAddressRepository retailerRegisteredAddressRepository;

        @Autowired
        private CustomerAddressRepository customerAddressRepository;

        @Autowired
        private ItemRepository itemRepository;
        
        @Autowired
        private InsuranceProviderRepository insuranceProviderRepository;
        
        @Autowired
        private InsurancePolicyRepository insurancePolicyRepository;
        
        @Autowired
        private PolicyNumberGenerationSequenceRepository policyNumberGenerationSequenceRepository;
        
        @Autowired
        private PricingService pricingService;
        
        @Autowired
        private PrivateDealUserRepository privateDealUserRepository;
        
        @Autowired
        private CounterRepository counterRepository;
        
        @Autowired
        private SchemeService schemeService;
        
        @Override
        public int createOrder(CreateOrderRequest createOrderRequest, int fofoId) throws ProfitMandiBusinessException {
                
                CustomCustomer customCustomer = createOrderRequest.getCustomer();

                if(!StringUtils.isValidEmailAddress(customCustomer.getEmailId())){
                        LOGGER.error("invalid customer emailId {} ", customCustomer.getEmailId());
                        throw new ProfitMandiBusinessException(ProfitMandiConstants.EMAIL_ID, customCustomer.getEmailId(), "VE_1016");
                }

                if(!StringUtils.isValidMobile(customCustomer.getMobileNumber())){
                        LOGGER.error("invalid customer mobileNumber {} ", customCustomer.getMobileNumber());
                        throw new ProfitMandiBusinessException(ProfitMandiConstants.MOBILE_NUMBER, customCustomer.getMobileNumber(), "VE_1071");
                }
                
                Map<Integer, Integer> itemIdQuantity = new HashMap<>(); //this is for error
                Map<Integer, CustomFofoOrderItem> itemIdCustomFofoOrderItemMap = new HashMap<>();
                Map<Integer, Float> lineItemPrice = new HashMap<>(); //this is for pricing error
                
                float totalAmount = 0;
                for(CustomFofoOrderItem customFofoOrderItem : createOrderRequest.getFofoOrderItems()){
                        //itemIds.add(customFofoOrderItem.getItemId());
                        if(!customFofoOrderItem.getSerialNumberDetails().isEmpty() && customFofoOrderItem.getQuantity() != customFofoOrderItem.getSerialNumberDetails().size()){
                                itemIdQuantity.put(customFofoOrderItem.getItemId(), customFofoOrderItem.getQuantity());
                        }
                        if(!(customFofoOrderItem.getSellingPrice() > 0)){
                                lineItemPrice.put(customFofoOrderItem.getItemId(), customFofoOrderItem.getSellingPrice());
                        }else{
                                totalAmount = totalAmount + customFofoOrderItem.getSellingPrice() * customFofoOrderItem.getQuantity();
                                totalAmount = totalAmount - customFofoOrderItem.getDiscountAmount() * customFofoOrderItem.getQuantity();
                                for(SerialNumberDetail serialNumberDetail : customFofoOrderItem.getSerialNumberDetails()){
                                        if(serialNumberDetail.isInsurance() && serialNumberDetail.getAmount() > 0){
                                                totalAmount = totalAmount + serialNumberDetail.getAmount();
                                        }
                                }
                        }
                        
                        itemIdCustomFofoOrderItemMap.put(customFofoOrderItem.getItemId(), customFofoOrderItem);
                }
                if(!itemIdQuantity.isEmpty()){
                        // if item quantity does not match with given serialnumbers size
                        LOGGER.error("itemId's quantity should be equal to given serialnumber size {} ", itemIdQuantity);
                        throw new ProfitMandiBusinessException("itemIdQuantity", itemIdQuantity, "FFORDR_1001");
                        //return "error";
                }
                
                this.validatePaymentOptionsAndTotalAmount(createOrderRequest.getPaymentOptions(), totalAmount);
                
                if(!lineItemPrice.isEmpty()){
                        // given fofo line item price must be greater than zero
                        LOGGER.error("requested itemId's selling price must greater than 0");
                        throw new ProfitMandiBusinessException(ProfitMandiConstants.PRICE, lineItemPrice, "FFORDR_1002");
                }

                List<CurrentInventorySnapshot> currentInventorySnapshots = currentInventorySnapshotRepository.selectByFofoItemIds(fofoId, itemIdCustomFofoOrderItemMap.keySet());
                
                this.validateCurrentInventorySnapshotQuantities(currentInventorySnapshots, itemIdCustomFofoOrderItemMap);


                List<Item> items = itemRepository.selectByIds(itemIdCustomFofoOrderItemMap.keySet());
                if(items.size() != itemIdCustomFofoOrderItemMap.keySet().size()){
                        LOGGER.error("Requested ItemIds not found in catalog");
                        // invalid itemIds 
                        throw new ProfitMandiBusinessException("invalidItemIds", itemIdCustomFofoOrderItemMap.keySet(), "FFORDR_1003");
                }
                
                Map<Integer, Item>  itemMap = this.toItemMap(items);

                Set<Integer> nonSerializedItemIds = new HashSet<>();
                Set<String> serialNumbers = new HashSet<>();
                Map<String, Float> insuranceSerialNumberItemPrice = new HashMap<>();
                Map<String, Float> insuranceSerialNumberSaleAmount = new HashMap<>();
                Map<String, String> serialNumberModelName = new HashMap<>();
                Map<String, String> serialNumberBrand = new HashMap<>();
                for (CustomFofoOrderItem customFofoOrderItem: createOrderRequest.getFofoOrderItems()){
                        Item item = itemMap.get(customFofoOrderItem.getItemId());
                        if (item.getType().equals(ItemType.SERIALIZED)){
                                for (SerialNumberDetail serialNumberDetail : customFofoOrderItem.getSerialNumberDetails()){
                                        serialNumbers.add(serialNumberDetail.getSerialNumber());
                                        if(serialNumberDetail.isInsurance()){
                                                insuranceSerialNumberItemPrice.put(serialNumberDetail.getSerialNumber(), customFofoOrderItem.getSellingPrice());
                                                insuranceSerialNumberSaleAmount.put(serialNumberDetail.getSerialNumber(), serialNumberDetail.getAmount());
                                                serialNumberModelName.put(serialNumberDetail.getSerialNumber(), item.getModelName());
                                                serialNumberBrand.put(serialNumberDetail.getSerialNumber(), item.getBrand());
                                        }
                                }
                        }
                        else{
                                nonSerializedItemIds.add(customFofoOrderItem.getItemId());
                        }
                }

                Map<Integer, Set<InventoryItem>> serializedInventoryItemMap = new HashMap<>();
                Map<Integer, Set<InventoryItem>> nonSerializedInventoryItemMap = new HashMap<>();
                Map<Integer, List<Float>> itemIdPriceDropAmount = new HashMap<>();
                //Map<String, Float> serialNumberItemPrice = new HashMap<>();
                
                if (!serialNumbers.isEmpty()){
                        List<InventoryItem> serializedInventoryItems = inventoryItemRepository.selectByFofoIdSerialNumbers(fofoId, serialNumbers);
                        LOGGER.info("serializedInventoryItems {}", serializedInventoryItems);
                        for (InventoryItem inventoryItem : serializedInventoryItems){
                                if (inventoryItem.getGoodQuantity() == 1){
                                        if (serializedInventoryItemMap.containsKey(inventoryItem.getItemId())){
                                                serializedInventoryItemMap.get(inventoryItem.getItemId()).add(inventoryItem);
                                                itemIdPriceDropAmount.get(inventoryItem.getItemId()).
                                                add(inventoryItem.getUnitPrice() - inventoryItem.getPriceDropAmount());
                                        }
                                        else{
                                                Set<InventoryItem> itemIdInventoryItems = new HashSet<>();
                                                itemIdInventoryItems.add(inventoryItem);
                                                serializedInventoryItemMap.put(inventoryItem.getItemId(), itemIdInventoryItems);
                                                ArrayList<Float> priceDropAmouts = new ArrayList<>();
                                                priceDropAmouts.add(inventoryItem.getUnitPrice() - (inventoryItem.getPriceDropAmount()));
                                                itemIdPriceDropAmount.put(inventoryItem.getItemId(), priceDropAmouts);
                                        }
                                }
                        }
                }

                if (!nonSerializedItemIds.isEmpty()){
                        List<InventoryItem> nonSerializedInventoryItems = inventoryItemRepository.selectByFofoIdItemIds(fofoId, nonSerializedItemIds);
                        LOGGER.info("nonSerializedInventoryItems {}", nonSerializedInventoryItems);
                        for (InventoryItem it : nonSerializedInventoryItems){
                                if (it.getGoodQuantity() > 0){
                                        if (nonSerializedInventoryItemMap.containsKey(it.getItemId())){
                                                nonSerializedInventoryItemMap.get(it.getItemId()).add(it);
                                        }
                                        else{
                                                Set<InventoryItem> tmp = new HashSet<>();
                                                tmp.add(it);
                                                nonSerializedInventoryItemMap.put(it.getItemId(), tmp);
                                        }
                                }
                        }
                }
                
                this.validateItemsSerializedNonSerialized(items, itemIdCustomFofoOrderItemMap);

                Map<Integer, Set<InventoryItem>> inventoryItemsToBill = new HashMap<>();
                Map<Integer, Integer> inventoryItemIdQuantityUsed = new HashMap<>(); //to keep track of inventoryitem quanity used for scan records insertion

                LOGGER.info("itemMap keys {}", itemMap.keySet());
                //Lets reduce quantity and decide what inventory items to use.
                for (Item item : items){
                        if (item.getType().equals(ItemType.SERIALIZED)){
                                //TODO:handle null
                                if (serializedInventoryItemMap.get(item.getId()) == null || itemIdCustomFofoOrderItemMap.get(item.getId()).getSerialNumberDetails().size() != serializedInventoryItemMap.get(item.getId()).size()){
                                        //not enough serial numbers
                                        //LOGGER.info("serialNumbers {}", serialNumbers);
                                        //LOGGER.info("serializedInventoryItemMap {}", serializedInventoryItemMap);
                                        LOGGER.error("itemId {} => mismatch size of requested serial numbers", item.getId());
                                        Function<SerialNumberDetail, String> serialNumberDetailToSerialNumberFunction = new Function<SerialNumberDetail, String>() {
                                                @Override
                                                public String apply(SerialNumberDetail serialNumberDetail) {
                                                        return serialNumberDetail.getSerialNumber();
                                                }
                                        };
                                        throw new ProfitMandiBusinessException("invalidSerialNumbers", itemIdCustomFofoOrderItemMap.get(item.getId()).getSerialNumberDetails().stream().map(serialNumberDetailToSerialNumberFunction).collect(Collectors.toList()), "FFORDR_1004");
                                }
                                Set<InventoryItem> inventoryItemsSerializedserialized = serializedInventoryItemMap.get(item.getId());
                                for (InventoryItem inventoryItem : inventoryItemsSerializedserialized){
                                        inventoryItem.setGoodQuantity(0);
                                        inventoryItemIdQuantityUsed.put(inventoryItem.getId(), 1);
                                }
                                inventoryItemsToBill.put(item.getId(), inventoryItemsSerializedserialized);
                        }
                        else{
                                Set<InventoryItem> inventoryItemsNonSerialized = nonSerializedInventoryItemMap.get(item.getId());
                                int quantityToBill = itemIdCustomFofoOrderItemMap.get(item.getId()).getQuantity();
                                int totalLeft = quantityToBill;
                                Set<InventoryItem> inventoryItemsNonSerializedUsed = new HashSet<>();
                                if (inventoryItemsNonSerialized!=null){
                                        for (InventoryItem inventoryItem : inventoryItemsNonSerialized){
                                                if (totalLeft > 0){
                                                        int toUse = Math.min(totalLeft, inventoryItem.getGoodQuantity());
                                                        inventoryItemIdQuantityUsed.put(inventoryItem.getId(), toUse);
                                                        inventoryItem.setGoodQuantity(inventoryItem.getGoodQuantity()  - toUse);
                                                        totalLeft = totalLeft - toUse;
                                                        inventoryItemsNonSerializedUsed.add(inventoryItem);
                                                }
                                        }
                                }
                                
                                if (totalLeft > 0){
                                        //not enough quanity for non-serialized
                                        LOGGER.error("not enough quanity for non-serialized");
                                        throw new ProfitMandiBusinessException("notEnoughQuantityForNonSerialized", totalLeft, "FFORDR_1005");
                                }
                                inventoryItemsToBill.put(item.getId(), inventoryItemsNonSerializedUsed);
                        }
                }
                
                Map<Integer, PriceModel> itemIdMopPriceMap = pricingService.getPurchasePriceMopPriceNotFound(itemIdCustomFofoOrderItemMap.keySet(), fofoId);
                
                this.validateMopPrice(itemIdMopPriceMap, itemIdCustomFofoOrderItemMap);

                InvoiceNumberGenerationSequence invoiceNumberGenerationSequence = this.createAndGetInvoiceNumberGenerationSequence(fofoId);
                
                Customer customer = this.createAndGetCustomer(customCustomer);
                
                CustomerAddress customerAddress = null;
                if(createOrderRequest.getCustomer().getCustomerAddressId() > 0){
                        LOGGER.info("CustomerAddressId found [{}]", createOrderRequest.getCustomer().getCustomerAddressId());
                        try{
                                customerAddress = customerAddressRepository.selectById(createOrderRequest.getCustomer().getCustomerAddressId());
                        }catch(ProfitMandiBusinessException profitMandiBusinessException){
                                LOGGER.warn("Customer address not found with requested customerAddressId [{}]", createOrderRequest.getCustomer().getCustomerAddressId());
                                customerAddress = this.createCustomerAddress(customCustomer.getAddress());
                        }
                }else{
                        LOGGER.info("CustomerAddressId not found");
                        customerAddress = this.createCustomerAddress(customCustomer.getAddress());
                }
                
                customerAddress.setCustomerId(customer.getId());
                customerAddressRepository.persist(customerAddress);
                
                FofoOrder fofoOrder = this.createAndGetFofoOrder(customer.getId(), fofoId, invoiceNumberGenerationSequence, totalAmount, customerAddress.getId());
                
                this.createPaymentOptions(fofoOrder.getId(), createOrderRequest.getPaymentOptions());
                
                int retailerAddressId = retailerRegisteredAddressRepository.selectAddressIdByRetailerId(fofoId);
                
                Address retailerAddress = addressRepository.selectById(retailerAddressId);
                
                Integer stateId = null;
                if(customerAddress.getState().equals(retailerAddress.getState())){
                        try{
                                stateId = Long.valueOf(Utils.getStateInfo(customerAddress.getState()).getId()).intValue();
                        }catch(Exception e){
                                LOGGER.error("Unable to get state rates");
                        }
                }
                
                for(CustomFofoOrderItem customFofoOrderItem : createOrderRequest.getFofoOrderItems()){
                        FofoOrderItem fofoOrderItem = this.createAndGetFofoOrderItem(customFofoOrderItem, fofoOrder.getId(), itemMap, inventoryItemsToBill.get(customFofoOrderItem.getItemId()), itemIdPriceDropAmount, stateId);
                        
                        Set<InventoryItem> inventoryItems = inventoryItemsToBill.get(customFofoOrderItem.getItemId());
                        
                        this.createFofoLineItem(fofoOrderItem.getId(), inventoryItems, inventoryItemIdQuantityUsed);
                        
                        this.updateCurrentInventorySnapshot(currentInventorySnapshots, fofoId, customFofoOrderItem.getItemId(), customFofoOrderItem.getQuantity());
                        
                        this.updateInventoryItemsAndScanRecord(inventoryItems, fofoId, inventoryItemIdQuantityUsed);
                }
                
                // insurance calculation is insurance flag is enabled
                if(!insuranceSerialNumberItemPrice.isEmpty()){
                        LOGGER.info("Processing for insurence for serialNumbers");
                        Map<Float, GadgetCopsInsuranceCalc> insurancePricesMap = pricingService.getInsurancePrices(new HashSet<>(insuranceSerialNumberItemPrice.values()), ProfitMandiConstants.GADGET_COPS);
                        InsuranceProvider insuranceProvider = insuranceProviderRepository.selectByName(ProfitMandiConstants.GADGET_COPS);
                        
                        this.validateInsuranceAmount(insuranceSerialNumberItemPrice, insuranceSerialNumberSaleAmount, insurancePricesMap);
                        
                        this.validateInsuranceMargin(insuranceSerialNumberItemPrice, itemIdCustomFofoOrderItemMap, itemIdMopPriceMap, insurancePricesMap, insuranceSerialNumberSaleAmount);
                        
                        LocalDate customerDateOfBirth = this.validateCustomerDateOfBirth(createOrderRequest.getCustomerDateOfBirth());
                        
                        for(Map.Entry<String, Float> entry : insuranceSerialNumberItemPrice.entrySet()){
                                PolicyNumberGenerationSequence policyNumberGenerationSequence = this.createPolicyNumberGenerationSequence();
                                
                                InsurancePolicy insurancePolicy = this.createInsurancePolicy(
                                                invoiceNumberGenerationSequence, fofoId,
                                                insurancePricesMap.get(entry.getValue()).getDealerPrice(),
                                                insuranceSerialNumberSaleAmount.get(entry.getKey()),entry.getValue(),
                                                entry.getKey(), serialNumberModelName.get(entry.getKey()),
                                                serialNumberBrand.get(entry.getKey()), policyNumberGenerationSequence.getSequence(),
                                                insuranceProvider.getId(), customer, customerDateOfBirth, customerAddress);
                                
                                GadgetCopsInsuranceModel gadgetCopsInsuranceModel = this.createGadgetCopsInsuranceModel(serialNumberBrand.get(entry.getKey()), serialNumberModelName.get(entry.getKey()), entry.getKey(), customerDateOfBirth, customer, customerAddress, insurancePolicy);
                                
                                try{
                                        InsuranceUtils.submitToGadgetCops(gadgetCopsInsuranceModel);
                                        insurancePolicy.setPosted(true);
                                }catch (ProfitMandiBusinessException profitMandiBusinessException) {
                                        LOGGER.info("Unable to submit insurance policy details to {}", insuranceProvider.getName(), profitMandiBusinessException);
                                }
                                insurancePolicyRepository.persist(insurancePolicy);
                        }
                }
                float cashback = schemeService.processSchemeOut(fofoOrder.getId(), fofoId);
                if(cashback > 0){
                        fofoOrder.setCashback(cashback);
                        fofoOrderRepository.persist(fofoOrder);
                }
                return fofoOrder.getId();
        }
        
        @Override
        public PdfModel getInvoicePdfModel(int fofoId, int orderId) throws ProfitMandiBusinessException {
                
                FofoOrder fofoOrder = fofoOrderRepository.selectByFofoIdAndOrderId(fofoId, orderId);
                
                PdfModel pdfModel = new PdfModel();
                pdfModel.setAuther("profitmandi");
                pdfModel.setTitle("Retailer Invoice");
                pdfModel.setInvoiceDate(fofoOrder.getFormattedDate());
                
                // insurance calculation
                List<InsurancePolicy> insurancePolicies = insurancePolicyRepository.selectByRetailerIdInvoiceNumber(fofoId, fofoOrder.getInvoiceNumber());
                Set<CustomInsurancePolicy> customInsurancePolicies = new HashSet<>();
                final float totalInsuranceTaxRate = 18;
                for(InsurancePolicy insurancePolicy : insurancePolicies){
                        float taxableInsurancePrice = insurancePolicy.getSaleAmount() / (1 + totalInsuranceTaxRate / 100);
                        CustomInsurancePolicy customInsurancePolicy = new CustomInsurancePolicy();
                        customInsurancePolicy.setDescription("Damage Protection Plan for device IMEI #" + insurancePolicy.getSerialNumber() + "\n Certificate No. " + insurancePolicy.getPolicyNumber());
                        customInsurancePolicy.setHsnCode("998716");
                        customInsurancePolicy.setRate(taxableInsurancePrice);
                        customInsurancePolicy.setIgstRate(18);
                        customInsurancePolicy.setIgstAmount(taxableInsurancePrice * 18 /100);
                        customInsurancePolicy.setCgstRate(9);
                        customInsurancePolicy.setCgstAmount(taxableInsurancePrice * 9 /100);
                        customInsurancePolicy.setSgstRate(9);
                        customInsurancePolicy.setSgstAmount(taxableInsurancePrice * 9 /100);
                        customInsurancePolicy.setNetAmount(insurancePolicy.getSaleAmount());
                        customInsurancePolicies.add(customInsurancePolicy);
                }
                pdfModel.setInsurancePolicies(customInsurancePolicies);
                List<String> tncs = new ArrayList<>();
                tncs.add("I agree that goods received are in good working condition");
                tncs.add("Goods once sold cannot be exchanged or taken back");
                tncs.add("Warranty for the goods received by me is the responsibility of the manufacturer only.");
        if(pdfModel.getInsurancePolicies() != null && pdfModel.getInsurancePolicies().size() > 0) {
                tncs.add("Damage protection provided is the responisibility of Protection Provider only");
        }
                pdfModel.setTncs(tncs);
                Customer customer = customerRepository.selectById(fofoOrder.getCustomerId());
                CustomCustomer customCustomer = new CustomCustomer();
                customCustomer.setFirstName(customer.getFirstName());
                customCustomer.setLastName(customer.getLastName());
                customCustomer.setEmailId(customer.getEmailId());
                customCustomer.setMobileNumber(customer.getMobileNumber());
                CustomerAddress customerAddress = customerAddressRepository.selectById(fofoOrder.getCustomerAddressId()); 
                customCustomer.setAddress(this.createCustomAddress(customerAddress));
                pdfModel.setCustomer(customCustomer);
                pdfModel.setInvoiceNumber(fofoOrder.getInvoiceNumber());
                pdfModel.setTotalAmount(fofoOrder.getTotalAmount());
                
                Retailer retailer = retailerRepository.selectById(fofoId);
                PrivateDealUser privateDealUser = null;
                try{
                        privateDealUser = privateDealUserRepository.selectById(retailer.getId());
                }catch(ProfitMandiBusinessException profitMandiBusinessException){
                        LOGGER.error("Private Deal User not found : ", profitMandiBusinessException);
                }
                
                User user = userRepository.selectById(userAccountRepository.selectUserIdByRetailerId(retailer.getId()));
                CustomRetailer customRetailer = new CustomRetailer();
                customRetailer.setBusinessName(retailer.getName());
                customRetailer.setMobileNumber(user.getMobileNumber());
                //customRetailer.setTinNumber(retailer.getNumber());
                if(privateDealUser == null){
                        customRetailer.setGstNumber(null);
                }else{
                        if(null != privateDealUser.getCounterId()){
                                Counter counter = counterRepository.selectById(privateDealUser.getCounterId());
                                customRetailer.setGstNumber(counter.getGstin());
                        }else{
                                customRetailer.setGstNumber(null);
                        }
                }
                Address retailerAddress = addressRepository.selectById(retailerRegisteredAddressRepository.selectAddressIdByRetailerId(retailer.getId()));
                customRetailer.setAddress(this.createCustomAddress(retailerAddress));
                pdfModel.setRetailer(customRetailer);
                List<FofoOrderItem> fofoOrderItems = this.getByOrderId(fofoOrder.getId());
                
                Set<CustomOrderItem> customerFofoOrderItems = new HashSet<>();
                for(FofoOrderItem fofoOrderItem : fofoOrderItems){
                        CustomOrderItem customFofoOrderItem = new CustomOrderItem();
                        float totalTaxRate = fofoOrderItem.getIgstRate() + fofoOrderItem.getSgstRate() + fofoOrderItem.getCgstRate();
                        float taxableSellingPrice = fofoOrderItem.getSellingPrice() / (1 + totalTaxRate / 100);
                        float taxableDiscountPrice = fofoOrderItem.getDiscount() / (1 + totalTaxRate / 100);
                        
                        customFofoOrderItem.setAmount(fofoOrderItem.getQuantity() * (taxableSellingPrice - taxableDiscountPrice));
                        customFofoOrderItem.setDescription(fofoOrderItem.getBrand() + " " + fofoOrderItem.getModelName() + " " + fofoOrderItem.getModelNumber() + "-" + fofoOrderItem.getColor() + "\n IMEIS - " + String.join(", ",this.toSerialNumbers(fofoOrderItem.getFofoLineItems())));
                        customFofoOrderItem.setRate(taxableSellingPrice);
                        customFofoOrderItem.setDiscount(taxableDiscountPrice);
                        customFofoOrderItem.setQuantity(fofoOrderItem.getQuantity());
                        customFofoOrderItem.setNetAmount((fofoOrderItem.getSellingPrice()-fofoOrderItem.getDiscount())*fofoOrderItem.getQuantity());
                        float igstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getIgstRate()) / 100;
                        float cgstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getCgstRate()) / 100;
                        float sgstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getSgstRate()) / 100;
                        customFofoOrderItem.setIgstRate(fofoOrderItem.getIgstRate());
                        customFofoOrderItem.setIgstAmount(igstAmount);
                        customFofoOrderItem.setCgstRate(fofoOrderItem.getCgstRate());
                        customFofoOrderItem.setCgstAmount(cgstAmount);
                        customFofoOrderItem.setSgstRate(fofoOrderItem.getSgstRate());
                        customFofoOrderItem.setSgstAmount(sgstAmount);
                        customFofoOrderItem.setHsnCode(fofoOrderItem.getHsnCode());
                        customerFofoOrderItems.add(customFofoOrderItem);
                }
                pdfModel.setOrderItems(customerFofoOrderItems);
                return pdfModel;
        }
        
        public String getBillingAddress(CustomerAddress customerAddress) {
                StringBuilder address = new StringBuilder();
                if ((customerAddress.getLine1() != null) && (!customerAddress.getLine1().isEmpty())) {
                        address.append(customerAddress.getLine1());
                        address.append(", ");
                }

                if ((customerAddress.getLine2() != null) && (!customerAddress.getLine2().isEmpty())) {
                        address.append(customerAddress.getLine2());
                        address.append(", ");
                }

                if ((customerAddress.getLandmark() != null) && (!customerAddress.getLandmark().isEmpty())) {
                        address.append(customerAddress.getLandmark());
                        address.append(", ");
                }

                if ((customerAddress.getCity() != null) && (!customerAddress.getCity().isEmpty())) {
                        address.append(customerAddress.getCity());
                        address.append(", ");
                }

                if ((customerAddress.getState() != null) && (!customerAddress.getState().isEmpty())) {
                        address.append(customerAddress.getState());
                }

                if ((customerAddress.getPinCode() != null) && (!customerAddress.getPinCode().isEmpty())) {
                        address.append("- ");
                        address.append(customerAddress.getPinCode());
                }

                return address.toString();
        }
        
        @Override
        public List<CartFofo> cartCheckout(String cartJson) throws ProfitMandiBusinessException{
                try{
                        JSONObject cartObject = new JSONObject(cartJson);
                        Iterator<?> keys = cartObject.keys();
        
                        Set<Integer> itemIds = new HashSet<>();
                        List<CartFofo> cartItems = new ArrayList<CartFofo>();
        
                        while( keys.hasNext() ) {
                                String key = (String)keys.next();
                                if ( cartObject.get(key) instanceof JSONObject ) {
                                        LOGGER.info(cartObject.get(key).toString());
                                }
                                CartFofo cf = new CartFofo();
                                cf.setItemId(cartObject.getJSONObject(key).getInt("itemId"));
                                cf.setQuantity(cartObject.getJSONObject(key).getInt("quantity"));
                                
                                if (cf.getQuantity() <= 0){
                                        continue;
                                }
                                cartItems.add(cf);
                                itemIds.add(cartObject.getJSONObject(key).getInt("itemId"));
                        }
                        Map<Integer, Item>  itemMap = new HashMap<Integer, Item>();
                        if (itemIds.size() > 0){
                                List<Item> items = itemRepository.selectByIds(itemIds);
                                for (Item i : items){
                                        itemMap.put(i.getId(), i);
                                }
                                
                        }
                        for (CartFofo cf : cartItems){
                                Item i = itemMap.get(cf.getItemId());
                                if (i == null){
                                        continue;
                                }
                                cf.setDisplayName(getValidName(i.getBrand())+" "+getValidName(i.getModelName())+" "+getValidName(i.getModelNumber())+" "+getValidName(i.getColor()).replaceAll("\\s+", " "));
                                cf.setItemType(i.getType());
                        }
                        return cartItems;
                }catch (Exception e) {
                        LOGGER.error("Unable to Prepare cart to place order...", e);
                        throw new ProfitMandiBusinessException("cartData", cartJson, "FFORDR_1006");
                }
        }
        
        private String getValidName(String name){
                return name!=null?name:"";
        }
        
        private Set<String> toSerialNumbers(Set<FofoLineItem> fofoLineItems){
                Function<FofoLineItem, String> fofoLineItemToSerialNumberFunction = new Function<FofoLineItem, String>() {
                        @Override
                        public String apply(FofoLineItem fofoLineItem) {
                                return fofoLineItem.getSerialNumber();
                        }
                };
                return fofoLineItems.stream().map(fofoLineItemToSerialNumberFunction).collect(Collectors.toSet());
        }
        
        
        private PolicyNumberGenerationSequence createPolicyNumberGenerationSequence(){
                PolicyNumberGenerationSequence policyNumberGenerationSequence = null;
                try{
                        policyNumberGenerationSequence = policyNumberGenerationSequenceRepository.select();
                        policyNumberGenerationSequence.setSequence(policyNumberGenerationSequence.getSequence() + 1);
                        policyNumberGenerationSequenceRepository.persist(policyNumberGenerationSequence);
                }catch(ProfitMandiBusinessException profitMandiBusinessException){
                        policyNumberGenerationSequence = new PolicyNumberGenerationSequence();
                        policyNumberGenerationSequence.setSequence(1);
                        policyNumberGenerationSequenceRepository.persist(policyNumberGenerationSequence);
                }
                return policyNumberGenerationSequence;
        }
        
        private GadgetCopsInsuranceModel createGadgetCopsInsuranceModel(String brand, String modelName, String serialNumber, LocalDate customerDateOfBirth, Customer customer, CustomerAddress customerAddress, InsurancePolicy insurancePolicy){
                GadgetCopsInsuranceModel gadgetCopsInsuranceModel = new GadgetCopsInsuranceModel();
                gadgetCopsInsuranceModel.setBrand(brand);
                gadgetCopsInsuranceModel.setModelName(modelName);
                gadgetCopsInsuranceModel.setSerialNumber(serialNumber);
                gadgetCopsInsuranceModel.setCustomerFirstName(customer.getFirstName());
                gadgetCopsInsuranceModel.setCustomerLastName(customer.getLastName());
                gadgetCopsInsuranceModel.setCustomerDateOfBirth(customerDateOfBirth);
                gadgetCopsInsuranceModel.setCustomerMobileNumber(customer.getMobileNumber());
                gadgetCopsInsuranceModel.setCustomerEmailId(customer.getEmailId());
                gadgetCopsInsuranceModel.setCustomerAddress1(customerAddress.getLine1());
                gadgetCopsInsuranceModel.setCustomerAddress2(customerAddress.getLine2());
                gadgetCopsInsuranceModel.setCustomerCity(customerAddress.getCity());
                gadgetCopsInsuranceModel.setCustomerPinCode(customerAddress.getPinCode());
                gadgetCopsInsuranceModel.setCustomerState(customerAddress.getState());
                gadgetCopsInsuranceModel.setPrice(insurancePolicy.getSellingPrice());
                gadgetCopsInsuranceModel.setInvoiceNumber(insurancePolicy.getInvoiceNumber());
                gadgetCopsInsuranceModel.setPolicyNumber(insurancePolicy.getPolicyNumber());
                return gadgetCopsInsuranceModel;
        }
        
        private InsurancePolicy createInsurancePolicy(InvoiceNumberGenerationSequence invoiceNumberGenerationSequence, int retailerId, float purchaseAmount, float saleAmount, float sellingPrice, String serialNumber, String modelName, String brand, int policyNumberGenerationSequence, int insuranceProviderId, Customer customer, LocalDate customerDateOfBirth, CustomerAddress customerAddress){
                InsurancePolicy insurancePolicy = new InsurancePolicy();
                insurancePolicy.setInvoiceNumber(invoiceNumberGenerationSequence.getPrefix() + invoiceNumberGenerationSequence.getSequence());
                insurancePolicy.setRetailerId(retailerId);
                insurancePolicy.setPurchaseAmount(purchaseAmount);
                insurancePolicy.setSaleAmount(saleAmount);
                insurancePolicy.setSellingPrice(sellingPrice);
                insurancePolicy.setSerialNumber(serialNumber);
                insurancePolicy.setModelName(modelName);
                insurancePolicy.setBrand(brand);
                insurancePolicy.setPolicyNumber(StringUtils.generatePolicyNumber(ProfitMandiConstants.POLICY_NUMBER_PREFIX, policyNumberGenerationSequence));
                insurancePolicy.setProviderId(insuranceProviderId);
                insurancePolicy.setCustomerFirstName(customer.getFirstName());
                insurancePolicy.setCustomerLastName(customer.getLastName());
                insurancePolicy.setCustomerMobileNumber(customer.getMobileNumber());
                insurancePolicy.setCustomerEmailId(customer.getEmailId());
                insurancePolicy.setCustomerDateOfBirth(customerDateOfBirth);
                insurancePolicy.setCustomerAddress1(customerAddress.getLine1());
                insurancePolicy.setCustomerAddress2(customerAddress.getLine2());
                insurancePolicy.setCustomerCity(customerAddress.getCity());
                insurancePolicy.setCustomerPinCode(customerAddress.getPinCode());
                insurancePolicy.setCustomerState(customerAddress.getState());
                return insurancePolicy;
        }
        
        private void validateInsuranceMargin(Map<String, Float> insuranceSerialNumberItemPrice, Map<Integer, CustomFofoOrderItem> itemIdCustomFofoOrderItemMap, Map<Integer, PriceModel> itemIdMopPriceMap, Map<Float, GadgetCopsInsuranceCalc> insurancePricesMap, Map<String, Float> insuranceSerialNumberSaleAmount) throws ProfitMandiBusinessException{
                Map<Float, Float> invalidInsuranceMarginAmount = new HashMap<>();
                for(Map.Entry<String, Float> entry : insuranceSerialNumberItemPrice.entrySet()){
                        int itemId = this.getItemIdFromSerialNumber(itemIdCustomFofoOrderItemMap, entry.getKey());
                        float itemPurchasePrice = itemIdMopPriceMap.get(itemId).getPrice();
                        float itemSellingPrice = entry.getValue();
                        float itemMargin = itemSellingPrice - itemPurchasePrice;
                        float insurancePurchasePrice = insurancePricesMap.get(entry.getValue()).getDealerPrice();
                        float insuranceSellingPrice = insuranceSerialNumberSaleAmount.get(entry.getKey());
                        float insuranceMargin = insuranceSellingPrice - insurancePurchasePrice;
                        if(insuranceMargin < (itemMargin * 30 / 100)){
                                invalidInsuranceMarginAmount.put(insuranceMargin, (itemMargin * 30 / 100));
                        }
                }
                if(!invalidInsuranceMarginAmount.isEmpty()){
                        LOGGER.error("insurance marging should be greater than equal to item profit margin insuranceMarginItemIdMargin {}", invalidInsuranceMarginAmount);
                        throw new ProfitMandiBusinessException("invalidInsuranceMarginAmount", invalidInsuranceMarginAmount, "FFORDR_1007");
                }
        }
        
        private void validateInsuranceAmount(Map<String, Float> insuranceSerialNumberItemPrice, Map<String, Float> insuranceSerialNumberSaleAmount, Map<Float, GadgetCopsInsuranceCalc> insurancePricesMap) throws ProfitMandiBusinessException{
                Map<Float, Float> invalidInsurancePurchaseSaleAmount = new HashMap<>();
                Map<Float, Float> invalidInsuranceSalePurchaseAmount = new HashMap<>();
                for(Map.Entry<String, Float> entry : insuranceSerialNumberItemPrice.entrySet()){
                        if(insuranceSerialNumberSaleAmount.get(entry.getKey()) < insurancePricesMap.get(entry.getValue()).getDealerPrice()){
                                invalidInsurancePurchaseSaleAmount.put(insurancePricesMap.get(entry.getValue()).getDealerPrice(), insuranceSerialNumberSaleAmount.get(entry.getKey()));
                        }
                        
                        if(insuranceSerialNumberSaleAmount.get(entry.getKey()) > insurancePricesMap.get(entry.getValue()).getSellingPrice()){
                                invalidInsuranceSalePurchaseAmount.put(insuranceSerialNumberSaleAmount.get(entry.getKey()), insurancePricesMap.get(entry.getValue()).getDealerPrice());
                        }
                }
                
                // insurance sale amount can not be lesser than insurance purchase amount
                if(!invalidInsurancePurchaseSaleAmount.isEmpty()){
                        LOGGER.error("Invalid Insurance prices [{}], insurance sale amount can not be lesser than insurance purchase amount", invalidInsurancePurchaseSaleAmount);
                        throw new ProfitMandiBusinessException("invalidInsurancePurchaseSaleAmount", invalidInsurancePurchaseSaleAmount, "FFORDR_1008");
                }
                
                if(!invalidInsuranceSalePurchaseAmount.isEmpty()){
                        LOGGER.error("Invalid Insurance prices [{}], insurance sale amount can not be greater than than insurance max amount", invalidInsuranceSalePurchaseAmount);
                        throw new ProfitMandiBusinessException("invalidInsuranceSalePurchaseAmount", invalidInsuranceSalePurchaseAmount, "FFORDR_1009");
                }
        }
        
        private void validateMopPrice(Map<Integer, PriceModel> itemIdMopPriceMap, Map<Integer, CustomFofoOrderItem> itemIdCustomFofoLineItemMap) throws ProfitMandiBusinessException{
                Map<Integer, Float> invalidMopItemIdPriceMap = new HashMap<>();
                Map<Integer, Float> invalidDiscountAmountMap = new HashMap<>();
                //Map<Integer, PriceModel> itemIdMopPriceMap = pricingService.getPurchasePriceMopPriceNotFound(itemIds, fofoId);
                for(Map.Entry<Integer, PriceModel> entry : itemIdMopPriceMap.entrySet()){
                        CustomFofoOrderItem customFofoOrderItem = itemIdCustomFofoLineItemMap.get(entry.getKey());
                        if(entry.getValue().getPrice() < Float.MAX_VALUE && customFofoOrderItem.getSellingPrice() < entry.getValue().getPrice()){
                                invalidMopItemIdPriceMap.put(entry.getKey(), customFofoOrderItem.getSellingPrice());
                        }
                        if(entry.getValue().isMop() && customFofoOrderItem.getDiscountAmount() > entry.getValue().getMaxDiscountAmount()){
                                invalidDiscountAmountMap.put(entry.getKey(), customFofoOrderItem.getDiscountAmount());
                        }
                }
                
                if(!invalidMopItemIdPriceMap.isEmpty()){
                        LOGGER.error("Invalid itemIds selling prices{} should be greater than mop prices {}", invalidMopItemIdPriceMap, itemIdMopPriceMap);
                        throw new ProfitMandiBusinessException("invalidMopItemIdPrice", invalidMopItemIdPriceMap, "FFORDR_1010");
                }
                
                if(!invalidMopItemIdPriceMap.isEmpty()){
                        LOGGER.error("Invalid itemIds discount amounts {} should be less than maxDiscount prices {}", invalidDiscountAmountMap, itemIdMopPriceMap);
                        throw new ProfitMandiBusinessException("invalidMopItemIdPrice", invalidDiscountAmountMap, "FFORDR_1011");
                }
        }
        
        private LocalDate validateCustomerDateOfBirth(String customerDateOfBirthString) throws ProfitMandiBusinessException{
                LocalDate customerDateOfBirth = null;
                try{
                        customerDateOfBirth = StringUtils.toDate(customerDateOfBirthString);
                }catch(DateTimeException dateTimeException){
                        LOGGER.error("Unable to parse dateOfBirth", dateTimeException);
                        throw new ProfitMandiBusinessException("dateOfBirth", customerDateOfBirthString, "FFORDR_1012");
                }
                return customerDateOfBirth;
        }
        
        private void updateInventoryItemsAndScanRecord(Set<InventoryItem> inventoryItems, int fofoId, Map<Integer, Integer> inventoryItemQuantityUsed){
                for(InventoryItem inventoryItem : inventoryItems){
                        inventoryItem.setLastScanType(ScanType.SALE);
                        inventoryItemRepository.persist(inventoryItem);
                        ScanRecord scanRecord = new ScanRecord();
                        scanRecord.setInventoryItemId(inventoryItem.getId());
                        scanRecord.setFofoId(fofoId);
                        //correct this
                        scanRecord.setQuantity(inventoryItemQuantityUsed.get(inventoryItem.getId()));
                        scanRecord.setType(ScanType.SALE);
                        scanRecordRepository.persist(scanRecord);
                }
        }
        
        private void createFofoLineItem(int fofoOrderItemId, Set<InventoryItem> inventoryItems, Map<Integer, Integer> inventoryItemIdQuantityUsed){
                for(InventoryItem inventoryItem : inventoryItems){
                        FofoLineItem fofoLineItem = new FofoLineItem();
                        fofoLineItem.setFofoOrderItemId(fofoOrderItemId);
                        fofoLineItem.setSerialNumber(inventoryItem.getSerialNumber());
                        fofoLineItem.setInventoryItemId(inventoryItem.getId());
                        fofoLineItem.setQuantity(inventoryItemIdQuantityUsed.get(inventoryItem.getId()));
                        fofoLineItemRepository.persist(fofoLineItem);
                }
        }
        
        private FofoOrderItem createAndGetFofoOrderItem(CustomFofoOrderItem customFofoOrderItem, int fofoOrderId, Map<Integer, Item> itemMap, Set<InventoryItem> inventoryItems, Map<Integer, List<Float>> itemIdPriceDropAmount, Integer stateId) throws ProfitMandiBusinessException{
                FofoOrderItem fofoOrderItem = new FofoOrderItem();
                fofoOrderItem.setItemId(customFofoOrderItem.getItemId());
                fofoOrderItem.setQuantity(customFofoOrderItem.getQuantity());
                fofoOrderItem.setSellingPrice(customFofoOrderItem.getSellingPrice());
                fofoOrderItem.setOrderId(fofoOrderId);
                fofoOrderItem.setDp(customFofoOrderItem.getSellingPrice());
                fofoOrderItem.setDiscount(customFofoOrderItem.getDiscountAmount());
                Item item = itemMap.get(customFofoOrderItem.getItemId());
                Map<Integer, GstRate> itemIdStateTaxRateMap = null;
                Map<Integer, Float> itemIdIgstTaxRateMap = null;
                if(stateId != null){
                        itemIdStateTaxRateMap = Utils.getStateTaxRate(new ArrayList<>(itemMap.keySet()), stateId);
                }else{
                        itemIdIgstTaxRateMap = Utils.getIgstTaxRate(new ArrayList<>(itemMap.keySet()));
                }
                for(InventoryItem inventoryItem : inventoryItems){
                        if(stateId == null){
                                fofoOrderItem.setIgstRate(itemIdIgstTaxRateMap.get(inventoryItem.getItemId()));
                        }else{
                                fofoOrderItem.setCgstRate(itemIdStateTaxRateMap.get(inventoryItem.getItemId()).getCgstRate());
                                fofoOrderItem.setSgstRate(itemIdStateTaxRateMap.get(inventoryItem.getItemId()).getSgstRate());
                        }
                        
                        fofoOrderItem.setHsnCode(inventoryItem.getHsnCode());
                        break;
                }
                List<Float> priceDropAmounts = itemIdPriceDropAmount.get(customFofoOrderItem.getItemId());
                float cost = 0;
                if (priceDropAmounts!=null){
                        for (Float pda : priceDropAmounts){
                                cost = cost + pda;
                        }
                }
                else{
                        cost = customFofoOrderItem.getSellingPrice() * customFofoOrderItem.getQuantity();
                }
                fofoOrderItem.setCost(cost);
                fofoOrderItem.setBrand(item.getBrand());
                fofoOrderItem.setModelName(item.getModelName());
                fofoOrderItem.setModelNumber(item.getModelNumber());
                fofoOrderItem.setColor(item.getColor());
                fofoOrderItemRepository.persist(fofoOrderItem);
                return fofoOrderItem;
        }
        
        private void updateCurrentInventorySnapshot(List<CurrentInventorySnapshot> currentInventorySnapshots, int fofoId, int itemId, int quantity) throws ProfitMandiBusinessException{
                for(CurrentInventorySnapshot currentInventorySnapshot : currentInventorySnapshots){
                        if(currentInventorySnapshot.getItemId() == itemId && currentInventorySnapshot.getFofoId() == fofoId){
                                currentInventorySnapshotRepository.updateAvailabilityByItemIdAndFofoId(itemId, fofoId, currentInventorySnapshot.getAvailability() - quantity);
                        }
                }
        }
        
        private void createPaymentOptions(int fofoOrderId, Set<CustomPaymentOption> customPaymentOptions){
                for(CustomPaymentOption customPaymentOption : customPaymentOptions){
                        if(customPaymentOption.getAmount() > 0){
                                PaymentOption paymentOption = new PaymentOption();
                                paymentOption.setOrderId(fofoOrderId);
                                paymentOption.setAmount(customPaymentOption.getAmount());
                                paymentOption.setType(PaymentOptionType.valueOf(customPaymentOption.getType()));
                                paymentOptionRepository.persist(paymentOption);
                        }
                }
        }
        
        private FofoOrder createAndGetFofoOrder(int customerId, int fofoId, InvoiceNumberGenerationSequence invoiceNumberGenerationSequence, float totalAmount, int customerAddressId){
                FofoOrder fofoOrder = new FofoOrder();
                fofoOrder.setCustomerId(customerId);
                fofoOrder.setFofoId(fofoId);
                fofoOrder.setInvoiceNumber(invoiceNumberGenerationSequence.getPrefix() + invoiceNumberGenerationSequence.getSequence());
                fofoOrder.setTotalAmount(totalAmount);
                fofoOrder.setCustomerAddressId(customerAddressId);
                fofoOrderRepository.persist(fofoOrder);
                return fofoOrder;
        }
        
        private Customer createAndGetCustomer(CustomCustomer customCustomer) throws ProfitMandiBusinessException{
                Customer customer = null;
                try{
                        customer = customerRepository.selectByMobileNumber(customCustomer.getMobileNumber());
                }catch(ProfitMandiBusinessException profitMandiBusinessException){
                        LOGGER.error("Error : ", profitMandiBusinessException);
                        customer = new Customer();
                        customer.setFirstName(customCustomer.getFirstName());
                        customer.setLastName(customCustomer.getLastName());
                        customer.setEmailId(customCustomer.getEmailId());
                        customer.setMobileNumber(customCustomer.getMobileNumber());
                        customerRepository.persist(customer);
                }
                return customer;
        }
        
        private InvoiceNumberGenerationSequence createAndGetInvoiceNumberGenerationSequence(int fofoId){
                InvoiceNumberGenerationSequence invoiceNumberGenerationSequence = null;
                try{
                        invoiceNumberGenerationSequence = invoiceNumberGenerationSequenceRepository.selectByFofoId(fofoId);
                        invoiceNumberGenerationSequence.setSequence(invoiceNumberGenerationSequence.getSequence() + 1);
                }catch(ProfitMandiBusinessException profitMandiBusinessException){
                        invoiceNumberGenerationSequence = new InvoiceNumberGenerationSequence();
                        invoiceNumberGenerationSequence.setFofoId(fofoId);
                        invoiceNumberGenerationSequence.setPrefix("INVOICE");
                        invoiceNumberGenerationSequence.setSequence(1);
                }
                invoiceNumberGenerationSequenceRepository.persist(invoiceNumberGenerationSequence);
                return invoiceNumberGenerationSequence;
        }
        
        private void validateItemsSerializedNonSerialized(List<Item> items, Map<Integer, CustomFofoOrderItem> customFofoOrderItemMap) throws ProfitMandiBusinessException{
                List<Integer> invalidItemIdSerialNumbers = new ArrayList<Integer>();
                List<Integer> itemIdNonSerializedSerialNumbers = new ArrayList<Integer>();
                for (Item i : items){
                        CustomFofoOrderItem customFofoOrderItem = customFofoOrderItemMap.get(i.getId());
                        if (i.getType().equals(ItemType.SERIALIZED)){
                                if (customFofoOrderItem == null || customFofoOrderItem.getSerialNumberDetails().isEmpty()){
                                        invalidItemIdSerialNumbers.add(i.getId());
                                }
                        }
                        else{
                                if (customFofoOrderItem == null || !customFofoOrderItem.getSerialNumberDetails().isEmpty()){
                                        itemIdNonSerializedSerialNumbers.add(i.getId());
                                }
                        }
                }

                if(!invalidItemIdSerialNumbers.isEmpty()){
                        LOGGER.error("Invalid itemId's serialNumbers for serialized{}", invalidItemIdSerialNumbers);
                        // itemId's are serialized you are saying these are not serialized
                        throw new ProfitMandiBusinessException("invalidItemIdSerialNumbers", invalidItemIdSerialNumbers, "FFORDR_1013");
                }

                if(!itemIdNonSerializedSerialNumbers.isEmpty()){
                        LOGGER.error("Invalid itemId's serialNumbers for non serialized{}", itemIdNonSerializedSerialNumbers);
                        // itemId's are non serialized you are saying these are serialized
                        throw new ProfitMandiBusinessException("itemIdNonSerializedSerialNumbers", itemIdNonSerializedSerialNumbers, "FFORDR_1014");
                }
        }
        
        private void validateCurrentInventorySnapshotQuantities(List<CurrentInventorySnapshot> currentInventorySnapshots, Map<Integer, CustomFofoOrderItem> itemIdCustomFofoOrderItemMap) throws ProfitMandiBusinessException{
                if(itemIdCustomFofoOrderItemMap.keySet().size() != currentInventorySnapshots.size()){
                        throw new ProfitMandiBusinessException("quantiiesSize", currentInventorySnapshots.size(), "");
                }
                List<ItemIdQuantityAvailability> itemIdQuantityAvailabilities = new ArrayList<>(); //this is for error
                LOGGER.info("currentInventorySnapshots "+currentInventorySnapshots);
                LOGGER.info("CustomFofoLineItemMap {}", itemIdCustomFofoOrderItemMap);
                for(CurrentInventorySnapshot currentInventorySnapshot : currentInventorySnapshots){
                        CustomFofoOrderItem customFofoOrderItem = itemIdCustomFofoOrderItemMap.get(currentInventorySnapshot.getItemId());
                        LOGGER.info("customFofoOrderItem {}", customFofoOrderItem);
                        if(customFofoOrderItem.getQuantity() > currentInventorySnapshot.getAvailability()){
                                        ItemIdQuantityAvailability itemIdQuantityAvailability = new ItemIdQuantityAvailability();
                                        itemIdQuantityAvailability.setItemId(customFofoOrderItem.getItemId());
                                        Quantity quantity = new Quantity();
                                        quantity.setAvailable(currentInventorySnapshot.getAvailability());
                                        quantity.setRequested(customFofoOrderItem.getQuantity());
                                        itemIdQuantityAvailability.setQuantity(quantity);
                                        itemIdQuantityAvailabilities.add(itemIdQuantityAvailability);
                                }

                }



                if(!itemIdQuantityAvailabilities.isEmpty()){
                        // itemIdQuantity request is not valid
                        LOGGER.error("Requested quantities should not be greater than currently available quantities {}", itemIdQuantityAvailabilities);
                        throw new ProfitMandiBusinessException("itemIdQuantityAvailabilities", itemIdQuantityAvailabilities, "FFORDR_1015");
                }
        }
        
        private int getItemIdFromSerialNumber(Map<Integer, CustomFofoOrderItem> itemIdCustomFofoOrderItemMap, String serialNumber){
                int itemId = 0;
                for(Map.Entry<Integer, CustomFofoOrderItem> entry : itemIdCustomFofoOrderItemMap.entrySet()){
                        Set<SerialNumberDetail> serialNumberDetails = entry.getValue().getSerialNumberDetails();
                        for(SerialNumberDetail serialNumberDetail : serialNumberDetails){
                                if(serialNumberDetail.getSerialNumber().equals(serialNumber)){
                                        itemId = entry.getKey();
                                        break;
                                }
                        }
                }
                return itemId;
        }
        
        private Map<Integer, Item> toItemMap(List<Item> items){
                Function<Item, Integer> itemIdFunction = new Function<Item, Integer>() {
                        @Override
                        public Integer apply(Item item) {
                                return item.getId();
                        }
                };
                Function<Item, Item> itemFunction = new Function<Item, Item>() {
                        @Override
                        public Item apply(Item item) {
                                return item;
                        }
                };
                return items.stream().collect(Collectors.toMap(itemIdFunction, itemFunction));
        }

        private CustomerAddress createCustomerAddress(CustomAddress customAddress){
                CustomerAddress customerAddress = new CustomerAddress();
                customerAddress.setName(customAddress.getName());
                customerAddress.setLine1(customAddress.getLine1());
                customerAddress.setLine2(customAddress.getLine2());
                customerAddress.setLandmark(customAddress.getLandmark());
                customerAddress.setCity(customAddress.getCity());
                customerAddress.setPinCode(customAddress.getPinCode());
                customerAddress.setState(customAddress.getState());
                customerAddress.setCountry(customAddress.getCountry());
                customerAddress.setPhoneNumber(customAddress.getPhoneNumber());
                return customerAddress;
        }

        private CustomAddress createCustomAddress(Address address){
                CustomAddress customAddress = new CustomAddress();
                customAddress.setName(address.getName());
                customAddress.setLine1(address.getLine1());
                customAddress.setLine2(address.getLine2());
                customAddress.setLandmark(address.getLandmark());
                customAddress.setCity(address.getCity());
                customAddress.setPinCode(address.getPinCode());
                customAddress.setState(address.getState());
                customAddress.setCountry(address.getCountry());
                customAddress.setPhoneNumber(address.getPhoneNumber());
                return customAddress;
        }

        private CustomAddress createCustomAddress(CustomerAddress customerAddress){
                CustomAddress customAddress = new CustomAddress();
                customAddress.setName(customerAddress.getName());
                customAddress.setLine1(customerAddress.getLine1());
                customAddress.setLine2(customerAddress.getLine2());
                customAddress.setLandmark(customerAddress.getLandmark());
                customAddress.setCity(customerAddress.getCity());
                customAddress.setPinCode(customerAddress.getPinCode());
                customAddress.setState(customerAddress.getState());
                customAddress.setCountry(customerAddress.getCountry());
                customAddress.setPhoneNumber(customerAddress.getPhoneNumber());
                return customAddress;
        }

        private void validatePaymentOptionsAndTotalAmount(Set<CustomPaymentOption> customPaymentOptions, float totalAmount) throws ProfitMandiBusinessException
        {
                float calculatedAmount = 0;
                Set<String> paymentOptionTypes = new HashSet<>();
                for(CustomPaymentOption customPaymentOption : customPaymentOptions){
                        if(paymentOptionTypes.contains(PaymentOptionType.valueOf(customPaymentOption.getType()))){
                                throw new ProfitMandiBusinessException(ProfitMandiConstants.PAYMENT_OPTION_TYPE, customPaymentOption.getType(), "");
                        }else{
                                paymentOptionTypes.add(customPaymentOption.getType());
                                calculatedAmount = calculatedAmount + customPaymentOption.getAmount();
                        }
                }
                if(calculatedAmount != totalAmount){
                        LOGGER.warn("Error occured while validating payment options amount[{}] != TotalAmount [{}]", calculatedAmount, totalAmount);
                        throw new ProfitMandiBusinessException(ProfitMandiConstants.PAYMENT_OPTION_CALCULATED_AMOUNT, calculatedAmount, "FFORDR_1016");
                }
        }
        
        @Override
        public List<FofoOrderItem> getByOrderId(int orderId) throws ProfitMandiBusinessException {
                List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(orderId);
                if(!fofoOrderItems.isEmpty()){
                        List<FofoOrderItem> newFofoOrderItems = new ArrayList<>();
                        Map<Integer, Set<FofoLineItem>> fofoOrderItemIdFofoLineItemsMap = this.toFofoOrderItemIdFofoLineItems(fofoOrderItems);
                        Iterator<FofoOrderItem> fofoOrderItemsIterator = fofoOrderItems.iterator();
                        while(fofoOrderItemsIterator.hasNext()){
                                FofoOrderItem fofoOrderItem = fofoOrderItemsIterator.next();
                                fofoOrderItem.setFofoLineItems(fofoOrderItemIdFofoLineItemsMap.get(fofoOrderItem.getId()));
                                newFofoOrderItems.add(fofoOrderItem);
                                fofoOrderItemsIterator.remove();
                        }
                        fofoOrderItems = newFofoOrderItems;
                }
                return fofoOrderItems;
        }
        
        private Set<Integer> toFofoOrderItemIds(List<FofoOrderItem> fofoOrderItems){
                Function<FofoOrderItem, Integer> fofoOrderItemToFofoOrderItemIdFunction = new Function<FofoOrderItem, Integer>() {
                        @Override
                        public Integer apply(FofoOrderItem fofoOrderItem) {
                                return fofoOrderItem.getId();
                        }
                };
                return fofoOrderItems.stream().map(fofoOrderItemToFofoOrderItemIdFunction).collect(Collectors.toSet());
        }
        
        private Map<Integer, Set<FofoLineItem>> toFofoOrderItemIdFofoLineItems(List<FofoOrderItem> fofoOrderItems){
                Set<Integer> fofoOrderItemIds = this.toFofoOrderItemIds(fofoOrderItems);
                List<FofoLineItem> fofoLineItems = fofoLineItemRepository.selectByFofoOrderItemIds(fofoOrderItemIds);
                Map<Integer, Set<FofoLineItem>> fofoOrderItemIdFofoLineItemsMap = new HashMap<>();
                for(FofoLineItem fofoLineItem : fofoLineItems){
                        if(!fofoOrderItemIdFofoLineItemsMap.containsKey(fofoLineItem.getFofoOrderItemId())){
                                Set<FofoLineItem> fofoLineItems2 = new HashSet<>();
                                fofoLineItems2.add(fofoLineItem);
                                fofoOrderItemIdFofoLineItemsMap.put(fofoLineItem.getFofoOrderItemId(), fofoLineItems2);
                        }else{
                                fofoOrderItemIdFofoLineItemsMap.get(fofoLineItem.getFofoOrderItemId()).add(fofoLineItem);
                        }
                }
                return fofoOrderItemIdFofoLineItemsMap;
        }

}