Rev 23552 | Rev 23566 | Go to most recent revision | View as "text/plain" | Blame | Compare with Previous | Last modification | View Log | RSS feed
package com.spice.profitmandi.service.order;import java.io.IOException;import java.net.URISyntaxException;import java.time.DateTimeException;import java.time.LocalDate;import java.time.LocalDateTime;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.Random;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.ResponseCodeHolder;import com.spice.profitmandi.common.enumuration.SearchType;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.Otp;import com.spice.profitmandi.dao.entity.dtr.PaymentOptionTransaction;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.FofoStore;import com.spice.profitmandi.dao.entity.fofo.InventoryItem;import com.spice.profitmandi.dao.entity.fofo.InvoiceNumberGenerationSequence;import com.spice.profitmandi.dao.entity.fofo.PrebookingListing;import com.spice.profitmandi.dao.entity.fofo.PrebookingOrder;import com.spice.profitmandi.dao.entity.fofo.PrebookingOrderItem;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.dtr.OtpType;import com.spice.profitmandi.dao.enumuration.dtr.PaymentOptionReferenceType;import com.spice.profitmandi.dao.enumuration.fofo.ScanType;import com.spice.profitmandi.dao.repository.catalog.ItemRepository;import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;import com.spice.profitmandi.dao.repository.dtr.InsurancePolicyRepository;import com.spice.profitmandi.dao.repository.dtr.InsuranceProviderRepository;import com.spice.profitmandi.dao.repository.dtr.OtpRepository;import com.spice.profitmandi.dao.repository.dtr.PaymentOptionTransactionRepository;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.PrebookingListingRepository;import com.spice.profitmandi.dao.repository.fofo.PrebookingOrderItemRepository;import com.spice.profitmandi.dao.repository.fofo.PrebookingOrderRepository;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.inventory.InventoryService;import com.spice.profitmandi.service.pricing.PricingService;import com.spice.profitmandi.service.scheme.SchemeService;import com.spice.profitmandi.service.wallet.WalletService;import in.shop2020.model.v1.catalog.ItemType;import in.shop2020.model.v1.order.WalletReferenceType;@Componentpublic class OrderServiceImpl implements OrderService {private static final Logger LOGGER = LoggerFactory.getLogger(OrderServiceImpl.class);@Autowiredprivate InventoryItemRepository inventoryItemRepository;@Autowiredprivate WalletService walletService;@Autowiredprivate CurrentInventorySnapshotRepository currentInventorySnapshotRepository;@Autowiredprivate InvoiceNumberGenerationSequenceRepository invoiceNumberGenerationSequenceRepository;@Autowiredprivate CustomerRepository customerRepository;@Autowiredprivate AddressRepository addressRepository;@Autowiredprivate FofoLineItemRepository fofoLineItemRepository;@Autowiredprivate FofoOrderItemRepository fofoOrderItemRepository;@Autowiredprivate PaymentOptionRepository paymentOptionRepository;@Autowiredprivate ScanRecordRepository scanRecordRepository;@Autowiredprivate FofoOrderRepository fofoOrderRepository;@Autowiredprivate RetailerRepository retailerRepository;@Autowiredprivate UserRepository userRepository;@Autowiredprivate UserAccountRepository userAccountRepository;@Autowiredprivate RetailerRegisteredAddressRepository retailerRegisteredAddressRepository;@Autowiredprivate CustomerAddressRepository customerAddressRepository;@Autowiredprivate ItemRepository itemRepository;@Autowiredprivate InsuranceProviderRepository insuranceProviderRepository;@Autowiredprivate InsurancePolicyRepository insurancePolicyRepository;@Autowiredprivate PolicyNumberGenerationSequenceRepository policyNumberGenerationSequenceRepository;@Autowiredprivate PricingService pricingService;@Autowiredprivate PrivateDealUserRepository privateDealUserRepository;@Autowiredprivate CounterRepository counterRepository;@Autowiredprivate FofoStoreRepository fofoStoreRepository;@Autowiredprivate PaymentOptionTransactionRepository paymentOptionTransactionRepository;@Autowiredprivate PrebookingListingRepository prebookingListingRepository;@Autowiredprivate PrebookingOrderRepository prebookingOrderRepository;@Autowiredprivate PrebookingOrderItemRepository prebookingOrderItemRepository;@Autowiredprivate SchemeService schemeService;@Autowiredprivate InventoryService inventoryService;@Autowiredprivate OtpRepository otpRepository;@Overridepublic 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");}if(!StringUtils.isValidGstNumber(customCustomer.getGstNumber())) {LOGGER.error("invalid customer gstNumber {} ", customCustomer.getGstNumber());throw new ProfitMandiBusinessException(ProfitMandiConstants.CUSTOMER_GST_NUMBER, customCustomer.getGstNumber(), "VE_1072");}Map<Integer, Integer> itemIdQuantity = new HashMap<>(); //this is for errorMap<Integer, CustomFofoOrderItem> itemIdCustomFofoOrderItemMap = new HashMap<>();Map<Integer, Float> lineItemPrice = new HashMap<>(); //this is for pricing errorMap<Integer, Integer> prebookingOrderItemIdQuantityMap = new HashMap<>(); // for prebooking order adjustmentfloat totalAmount = 0;for(CustomFofoOrderItem customFofoOrderItem : createOrderRequest.getFofoOrderItems()){//itemIds.add(customFofoOrderItem.getItemId());if(customFofoOrderItem.isPrebookingOrder()) {prebookingOrderItemIdQuantityMap.put(customFofoOrderItem.getItemId(), customFofoOrderItem.getQuantity());}Set<String> serialNumbers = this.serialNumberDetailsToSerialNumbers(customFofoOrderItem.getSerialNumberDetails());if(!serialNumbers.isEmpty() && customFofoOrderItem.getQuantity() != serialNumbers.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 sizeLOGGER.error("itemId's quantity should be equal to given serialnumber size {} ", itemIdQuantity);throw new ProfitMandiBusinessException("itemIdQuantity", itemIdQuantity, "FFORDR_1001");//return "error";}List<PrebookingListing> prebookingListings = new ArrayList<>();Map<Integer, PrebookingListing> itemIdPrebookingListingMap = new HashMap<>();List<PrebookingOrder> prebookingOrders = new ArrayList<>();float prebookingOrdersTotalAmount = 0;if(!prebookingOrderItemIdQuantityMap.isEmpty()) {prebookingListings = prebookingListingRepository.selectAllByItemIds(prebookingOrderItemIdQuantityMap.keySet());itemIdPrebookingListingMap = this.prebookingListingsToItemIdPrebookingListingMap(prebookingListings);prebookingOrders = prebookingOrderRepository.selectByFofoIdCustomerMobileNumberItemIds(fofoId, customCustomer.getMobileNumber(), prebookingOrderItemIdQuantityMap.keySet());prebookingOrdersTotalAmount = this.calculatePrebookingOrdersAmount(prebookingOrders, prebookingOrderItemIdQuantityMap, itemIdPrebookingListingMap);}this.validatePaymentOptionsAndTotalAmount(createOrderRequest.getPaymentOptions(), totalAmount - prebookingOrdersTotalAmount);if(!lineItemPrice.isEmpty()){// given fofo line item price must be greater than zeroLOGGER.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 itemIdsthrow 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() + item.getModelNumber()).trim());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<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);}else{Set<InventoryItem> itemIdInventoryItems = new HashSet<>();itemIdInventoryItems.add(inventoryItem);serializedInventoryItemMap.put(inventoryItem.getItemId(), itemIdInventoryItems);}}}}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 insertionLOGGER.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 nullif (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>() {@Overridepublic 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-serializedLOGGER.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);String fofoStoreCode = this.getFofoStoreCode(fofoId);InvoiceNumberGenerationSequence invoiceNumberGenerationSequence = this.createAndGetInvoiceNumberGenerationSequence(fofoId, fofoStoreCode);Customer customer = this.createAndGetCustomer(customCustomer);CustomerAddress customerAddress = this.createCustomerAddress(customCustomer.getAddress(), customer.getId());FofoOrder fofoOrder = this.createAndGetFofoOrder(customer.getId(), customCustomer.getGstNumber(), fofoId, invoiceNumberGenerationSequence, totalAmount, customerAddress.getId());this.createPaymentOptions(fofoOrder.getId(), createOrderRequest.getPaymentOptions());this.processPrebookingOrders(fofoId, fofoOrder.getId(), prebookingOrders, prebookingOrderItemIdQuantityMap, itemIdPrebookingListingMap);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()), 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 enabledif(!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(fofoOrder.getInvoiceNumber(), 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);String walletDescription = "Sale of " + insurancePolicy.getPolicyNumber()+ " for " + fofoOrder.getInvoiceNumber();walletService.consumeAmountFromWallet(fofoId, insurancePolicy.getId(),WalletReferenceType.DAMAGE_PROTECTION, walletDescription, insurancePolicy.getPurchaseAmount());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);}}schemeService.processSchemeOut(fofoOrder.getId(), fofoId);return fofoOrder.getId();}private float calculatePrebookingOrdersAmount(List<PrebookingOrder> prebookingOrders, Map<Integer, Integer> prebookingOrderItemIdQuantityMap, Map<Integer, PrebookingListing> itemIdPrebookingListingMap) {//List<PrebookingOrder> prebookingOrders = prebookingOrderRepository.selectByFofoIdCustomerMobileNumberItemIds(fofoId, customerMobileNumber, prebookingOrderItemIdQuantityMap.keySet());float totalAmount = 0;for(PrebookingOrder prebookingOrder : prebookingOrders) {int requestedQuantity = prebookingOrderItemIdQuantityMap.get(prebookingOrder.getItemId());PrebookingListing prebookingListing = itemIdPrebookingListingMap.get(prebookingOrder.getItemId());if(requestedQuantity < prebookingOrder.getAvailableQuantity()) {LOGGER.info("when requestedQuantity < then requestedQuantity [{}] * advanceAmount [{}]", requestedQuantity, prebookingListing.getAdvanceAmount());totalAmount = totalAmount + (requestedQuantity * prebookingListing.getAdvanceAmount());}else if(requestedQuantity >= prebookingOrder.getAvailableQuantity()) {LOGGER.info("else requestedQuantity [{}] * advanceAmount [{}]", requestedQuantity, prebookingListing.getAdvanceAmount());totalAmount = totalAmount + (prebookingOrder.getAvailableQuantity() * prebookingListing.getAdvanceAmount());}}return totalAmount;}private void processPrebookingOrders(int fofoId, int orderId, List<PrebookingOrder> prebookingOrders, Map<Integer, Integer> prebookingOrderItemIdQuantityMap, Map<Integer, PrebookingListing> itemIdPrebookingListingMap)throws ProfitMandiBusinessException{//Map<Integer, PrebookingOrder> prebookingOrderIdPrebookingOrderMap = this.prebookingOrdersToPrebookingOrderIdPrebookingOrderMap(prebookingOrders);for(PrebookingOrder prebookingOrder : prebookingOrders) {if(prebookingOrder.getCompleteTimestamp() == null) {int requestedQuantity = prebookingOrderItemIdQuantityMap.get(prebookingOrder.getItemId());PrebookingOrderItem prebookingOrderItem = new PrebookingOrderItem();if(requestedQuantity < prebookingOrder.getAvailableQuantity()) {prebookingOrder.setAvailableQuantity(prebookingOrder.getAvailableQuantity() - requestedQuantity);prebookingOrderItem.setQuantity(requestedQuantity);}else if(requestedQuantity >= prebookingOrder.getAvailableQuantity()) {prebookingOrderItem.setQuantity(prebookingOrder.getAvailableQuantity());prebookingOrder.setAvailableQuantity(0);}if(prebookingOrder.getAvailableQuantity() == 0) {prebookingOrder.setCompleteTimestamp(LocalDateTime.now());}prebookingOrderRepository.persist(prebookingOrder);prebookingOrderItem.setOrderId(orderId);prebookingOrderItem.setItemId(prebookingOrder.getItemId());PrebookingListing prebookingListing = itemIdPrebookingListingMap.get(prebookingOrder.getItemId());prebookingOrderItem.setAdvanceAmount(prebookingListing.getAdvanceAmount());prebookingOrderItemRepository.persist(prebookingOrderItem);walletService.addAmountToWallet(fofoId, prebookingOrder.getId(), WalletReferenceType.PREBOOKING_ORDER, "Advance Amount credited for Prebooking Order", prebookingListing.getAdvanceAmount());}}}private Map<Integer, PrebookingListing> prebookingListingsToItemIdPrebookingListingMap(List<PrebookingListing> prebookingListings){Map<Integer, PrebookingListing> itemIdPrebookingListingMap = new HashMap<>();for(PrebookingListing prebookingListing : prebookingListings) {itemIdPrebookingListingMap.put(prebookingListing.getItemId(), prebookingListing);}return itemIdPrebookingListingMap;}private Set<String> serialNumberDetailsToSerialNumbers(Set<SerialNumberDetail> serialNumberDetails){Set<String> serialNumbers = new HashSet<>();for(SerialNumberDetail serialNumberDetail : serialNumberDetails) {if(serialNumberDetail.getSerialNumber() != null && !serialNumberDetail.getSerialNumber().isEmpty()) {serialNumbers.add(serialNumberDetail.getSerialNumber());}}return serialNumbers;}@Overridepublic PdfModel getInvoicePdfModel(int fofoId, int orderId) throws ProfitMandiBusinessException {FofoOrder fofoOrder = fofoOrderRepository.selectByFofoIdAndOrderId(fofoId, orderId);List<PaymentOptionTransaction> paymentOptionTransactions = paymentOptionTransactionRepository.selectByReferenceIdAndType(fofoOrder.getId(), PaymentOptionReferenceType.ORDER);List<CustomPaymentOption> paymentOptions = new ArrayList<>();PdfModel pdfModel = new PdfModel();for(PaymentOptionTransaction paymentOptionTransaction : paymentOptionTransactions) {CustomPaymentOption cpi = new CustomPaymentOption();cpi.setAmount(paymentOptionTransaction.getAmount());cpi.setPaymentOption(paymentOptionRepository.selectById(paymentOptionTransaction.getPaymentOptionId()).getName());paymentOptions.add(cpi);}pdfModel.setPaymentOptions(paymentOptions);pdfModel.setAuther("profitmandi");pdfModel.setTitle("Retailer Invoice");pdfModel.setInvoiceDate(fofoOrder.getFormattedDate());// insurance calculationList<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());customCustomer.setGstNumber(fofoOrder.getCustomerGstNumber());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());Set<String> serialNumbers = this.toSerialNumbers(fofoOrderItem.getFofoLineItems());//LOGGER.info("serialNumbers {}", serialNumbers);//LOGGER.info("serialNumbers is empty {}", serialNumbers.isEmpty());if(!serialNumbers.isEmpty()) {customFofoOrderItem.setDescription(customFofoOrderItem.getDescription() + "\n IMEIS - " + String.join(", ", serialNumbers));}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();}@Overridepublic 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");}}@Overridepublic Map<String, Object> getSaleHistory(int fofoId, SearchType searchType, String searchValue, String startTimeString,String endTimeString, int offset, int limit) throws ProfitMandiBusinessException {LocalDateTime startDateTime = StringUtils.toDateTime(startTimeString);LocalDateTime endDateTime = StringUtils.toDateTime(endTimeString);long countItems = 0;List<FofoOrder> fofoOrders = new ArrayList<>();if(searchType == SearchType.CUSTOMER_MOBILE_NUMBER && !searchValue.isEmpty()){fofoOrders = fofoOrderRepository.selectByFofoIdAndCustomerMobileNumber(fofoId, searchValue, startDateTime, endDateTime, offset, limit);countItems = fofoOrderRepository.selectCountByCustomerMobileNumber(fofoId, searchValue, startDateTime, endDateTime);}else if(searchType == SearchType.CUSTOMER_NAME && !searchValue.isEmpty()){fofoOrders = fofoOrderRepository.selectByFofoIdAndCustomerName(fofoId, searchValue, startDateTime, endDateTime, offset, limit);countItems = fofoOrderRepository.selectCountByCustomerName(fofoId, searchValue, startDateTime, endDateTime);}else if(searchType == SearchType.IMEI && !searchValue.isEmpty()){fofoOrders = fofoOrderRepository.selectByFofoIdAndSerialNumber(fofoId, searchValue, startDateTime, endDateTime, offset, limit);countItems = fofoOrderRepository.selectCountBySerialNumber(fofoId, searchValue, startDateTime, endDateTime);}else if(searchType == SearchType.ITEM_NAME && !searchValue.isEmpty()){fofoOrders = fofoOrderRepository.selectByFofoIdAndItemName(fofoId, searchValue, startDateTime, endDateTime, offset, limit);countItems = fofoOrderRepository.selectCountByItemName(fofoId, searchValue, startDateTime, endDateTime);}else{fofoOrders = fofoOrderRepository.selectByFofoId(fofoId, startDateTime, endDateTime, offset, limit);countItems = fofoOrderRepository.selectCountByFofoId(fofoId, startDateTime, endDateTime);}Map<String, Object> map = new HashMap<>();map.put("saleHistories", fofoOrders);map.put("start", offset + 1);map.put("size", countItems);map.put("searchType", searchType);map.put("searchTypes", SearchType.values());map.put(ProfitMandiConstants.START_TIME, startTimeString);map.put(ProfitMandiConstants.END_TIME, endTimeString);if (fofoOrders.size() < limit){map.put("end", offset + fofoOrders.size());}else{map.put("end", offset + limit);}return map;}@Overridepublic Map<String, Object> getSaleHistoryPaginated(int fofoId, SearchType searchType, String searchValue, String startTimeString,String endTimeString, int offset, int limit) throws ProfitMandiBusinessException {LocalDateTime startDateTime = StringUtils.toDateTime(startTimeString);LocalDateTime endDateTime = StringUtils.toDateTime(endTimeString);List<FofoOrder> fofoOrders = new ArrayList<>();if(searchType == SearchType.CUSTOMER_MOBILE_NUMBER && !searchValue.isEmpty()){fofoOrders = fofoOrderRepository.selectByFofoIdAndCustomerMobileNumber(fofoId, searchValue, startDateTime, endDateTime, offset, limit);}else if(searchType == SearchType.CUSTOMER_NAME && !searchValue.isEmpty()){fofoOrders = fofoOrderRepository.selectByFofoIdAndCustomerName(fofoId, searchValue, startDateTime, endDateTime, offset, limit);}else if(searchType == SearchType.IMEI && !searchValue.isEmpty()){fofoOrders = fofoOrderRepository.selectByFofoIdAndSerialNumber(fofoId, searchValue, startDateTime, endDateTime, offset, limit);}else if(searchType == SearchType.ITEM_NAME && !searchValue.isEmpty()){fofoOrders = fofoOrderRepository.selectByFofoIdAndItemName(fofoId, searchValue, startDateTime, endDateTime, offset, limit);}else{fofoOrders = fofoOrderRepository.selectByFofoId(fofoId, startDateTime, endDateTime, offset, limit);}Map<String, Object> map = new HashMap<>();map.put("saleHistories", fofoOrders);return map;}private String getFofoStoreCode(int fofoId) throws ProfitMandiBusinessException{FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(fofoId);return fofoStore.getCode();}private CustomerAddress createCustomerAddress(CustomAddress customAddress, int customerId){CustomerAddress customerAddress = null;try{//CustomAddress customAddress = customCustomer.getAddress();customerAddress = customerAddressRepository.selectByParams(customAddress.getName(), customAddress.getLine1(), customAddress.getLine2(),customAddress.getLandmark(),customAddress.getCity(), customAddress.getPinCode(),customAddress.getState(), customAddress.getPhoneNumber(), customAddress.getCountry(), customerId);}catch(ProfitMandiBusinessException profitMandiBusinessException){LOGGER.warn("Customer address not found : ", profitMandiBusinessException);customerAddress = new CustomerAddress();this.setCustomerAddress(customerAddress, customAddress);customerAddress.setCustomerId(customerId);}customerAddressRepository.persist(customerAddress);return customerAddress;}private String getValidName(String name){return name!=null?name:"";}private Set<String> toSerialNumbers(Set<FofoLineItem> fofoLineItems){Set<String> serialNumbers = new HashSet<>();for(FofoLineItem fofoLineItem : fofoLineItems) {if(fofoLineItem.getSerialNumber() != null && !fofoLineItem.getSerialNumber().isEmpty()) {serialNumbers.add(fofoLineItem.getSerialNumber());}}return serialNumbers;}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(String invoiceNumber, 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(invoiceNumber);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 amountif(!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 thisscanRecord.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, 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()));}float cost = 0;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;}for(InventoryItem inventoryItem : inventoryItems){if(inventoryItem.getSerialNumber() != null) {cost += inventoryItem.getUnitPrice() - inventoryItem.getPriceDropAmount();} else {cost += inventoryItem.getUnitPrice();}}cost = cost/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) throws ProfitMandiBusinessException{for(CustomPaymentOption customPaymentOption : customPaymentOptions){if(customPaymentOption.getAmount() > 0) {PaymentOptionTransaction paymentOptionTransaction = new PaymentOptionTransaction();paymentOptionTransaction.setReferenceId(fofoOrderId);paymentOptionTransaction.setPaymentOptionId(customPaymentOption.getPaymentOptionId());paymentOptionTransaction.setReferenceType(PaymentOptionReferenceType.ORDER);paymentOptionTransaction.setAmount(customPaymentOption.getAmount());paymentOptionTransactionRepository.persist(paymentOptionTransaction);}}}private FofoOrder createAndGetFofoOrder(int customerId, String customerGstNumber, int fofoId, InvoiceNumberGenerationSequence invoiceNumberGenerationSequence, float totalAmount, int customerAddressId){FofoOrder fofoOrder = new FofoOrder();fofoOrder.setCustomerGstNumber(customerGstNumber);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, String fofoStoreCode){InvoiceNumberGenerationSequence invoiceNumberGenerationSequence = null;try{invoiceNumberGenerationSequence = invoiceNumberGenerationSequenceRepository.selectByFofoId(fofoId);invoiceNumberGenerationSequence.setSequence(invoiceNumberGenerationSequence.getSequence() + 1);}catch(ProfitMandiBusinessException profitMandiBusinessException){invoiceNumberGenerationSequence = new InvoiceNumberGenerationSequence();invoiceNumberGenerationSequence.setFofoId(fofoId);invoiceNumberGenerationSequence.setPrefix(fofoStoreCode);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{Set<String> serialNumbers = this.serialNumberDetailsToSerialNumbers(customFofoOrderItem.getSerialNumberDetails());if (customFofoOrderItem == null || !serialNumbers.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 serializedthrow 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 serializedthrow 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 errorLOGGER.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 validLOGGER.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>() {@Overridepublic Integer apply(Item item) {return item.getId();}};Function<Item, Item> itemFunction = new Function<Item, Item>() {@Overridepublic Item apply(Item item) {return item;}};return items.stream().collect(Collectors.toMap(itemIdFunction, itemFunction));}private void setCustomerAddress(CustomerAddress customerAddress, CustomAddress customAddress){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());}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{Set<Integer> paymentOptionIds = new HashSet<>();float calculatedAmount = 0;for(CustomPaymentOption customPaymentOption : customPaymentOptions){paymentOptionIds.add(customPaymentOption.getPaymentOptionId());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");}List<Integer> foundPaymentOptionIds = paymentOptionRepository.selectIdsByIds(paymentOptionIds);if(foundPaymentOptionIds.size() != paymentOptionIds.size()) {paymentOptionIds.removeAll(foundPaymentOptionIds);throw new ProfitMandiBusinessException(ProfitMandiConstants.PAYMENT_OPTION_ID, paymentOptionIds, "FFORDR_1017");}}@Overridepublic 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>() {@Overridepublic 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;}private String getOtpString(){Random rndm_method = new Random();String numbers ="0123456789";char[] otp = new char[5];for (int i = 0; i < 5; i++){otp[i] = numbers.charAt(rndm_method.nextInt(numbers.length()));}return String.valueOf(otp);}private void sendOtp(String otp_text, String phone, Map<Integer, Float> itemIdAdvanceAmount){Map<Integer, String> itemIdDescriptionMap = inventoryService.getItemIdDescriptionMap(itemIdAdvanceAmount.keySet());StringBuilder itemIdAdvanceAmountString = new StringBuilder();int index = 0;for(Map.Entry<Integer, Float> itemIdAdvanceAmountEntry : itemIdAdvanceAmount.entrySet()) {itemIdAdvanceAmountString.append(itemIdDescriptionMap.get(itemIdAdvanceAmountEntry.getKey()));itemIdAdvanceAmountString.append("'s Advance amount [");itemIdAdvanceAmountString.append(itemIdAdvanceAmountEntry.getValue());itemIdAdvanceAmountString.append("]");if(index + 1 < itemIdAdvanceAmount.size()) {itemIdAdvanceAmountString.append(", ");}index++;}String text = "Dear Customer, {0} is the OTP that you have requested for prebooking orders for items {1} Don't share your OTP with anyone.";String msg = java.text.MessageFormat.format(text, otp_text, itemIdAdvanceAmountString);try {Utils.sendSms(msg, phone);} catch (URISyntaxException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}@Overridepublic int generatePrebookingOrdersOtp(String customerEmailId, String customerMobileNumber, Map<Integer, Float> itemIdAdvanceAmount) throws ProfitMandiBusinessException {if(!StringUtils.isValidEmailAddress(customerEmailId)){LOGGER.error("invalid customer emailId {} ", customerEmailId);throw new ProfitMandiBusinessException(ProfitMandiConstants.EMAIL_ID, customerEmailId, "VE_1016");}if(!StringUtils.isValidMobile(customerMobileNumber)){LOGGER.error("invalid customer mobileNumber {} ", customerMobileNumber);throw new ProfitMandiBusinessException(ProfitMandiConstants.MOBILE_NUMBER, customerMobileNumber, "VE_1071");}List<Otp> otps = otpRepository.selectAllByEmailWithTime(customerEmailId);String otp = null;if (otps.size() >= 5){throw new ProfitMandiBusinessException(ProfitMandiConstants.CUSTOMER_EMAIL_ID, customerEmailId, "FFORDR_1019");}if (!otps.isEmpty()){if (otps.get(0).getCreatedOn().isAfter(LocalDateTime.now().minusMinutes(2))){return otps.get(0).getId();}else if(otps.get(0).getCreatedOn().isAfter(LocalDateTime.now().minusMinutes(10))){otp = otps.get(0).getOtp();}}if (otp == null || otp.isEmpty()){otp = getOtpString();}this.sendOtp(otp, customerMobileNumber, itemIdAdvanceAmount);Otp otp_bean = new Otp();otp_bean.setEmail(customerEmailId);otp_bean.setMobile(customerMobileNumber);otp_bean.setOtp(otp);otp_bean.setOtpType(OtpType.PREBOOKING_ORDER);otp_bean.setCreatedOn(LocalDateTime.now());otp_bean.setExpiryTimestamp(LocalDateTime.now().plusMinutes(10));otpRepository.persist(otp_bean);return otp_bean.getId();}@Overridepublic String validateOtp(String customerEmailId, String customerMobileNumber, int otpId, String otpValue)throws ProfitMandiBusinessException {Otp otp = otpRepository.selectByIdEmailIdMobileNumber(otpId, customerEmailId, customerMobileNumber);otp.setTryCount(otp.getTryCount() + 1);if (!otp.getOtp().equalsIgnoreCase(otpValue)){throw new ProfitMandiBusinessException("otpValue", otpValue, "FFORDR_1020");}if (otp.isExpired() || otp.isVerified() || otp.getExpiryTimestamp().isBefore(LocalDateTime.now())){throw new ProfitMandiBusinessException("otpValue", otpValue, "FFORDR_1021");}if (otp.getTryCount() >5){throw new ProfitMandiBusinessException("otpValue", otpValue, "FFORDR_1022");}otp.setExpired(true);otp.setVerified(true);otpRepository.persist(otp);return ResponseCodeHolder.getMessage("FFORDR_OK_1002");}}