Subversion Repositories SmartDukaan

Rev

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

package com.spice.profitmandi.web.controller;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
import com.spice.profitmandi.common.model.CustomAddress;
import com.spice.profitmandi.common.model.CustomCustomer;
import com.spice.profitmandi.common.model.CustomFofoLineItem;
import com.spice.profitmandi.common.model.CustomFofoOrderItem;
import com.spice.profitmandi.common.model.CustomRetailer;
import com.spice.profitmandi.common.model.GstRate;
import com.spice.profitmandi.common.model.PdfModel;
import com.spice.profitmandi.common.model.ProfitMandiConstants;
import com.spice.profitmandi.common.util.PdfUtils;
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.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.FofoItemId;
import com.spice.profitmandi.dao.entity.fofo.FofoLineItem;
import com.spice.profitmandi.dao.entity.fofo.FofoLineItemSerialNumber;
import com.spice.profitmandi.dao.entity.fofo.FofoOrder;
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.enumuration.fofo.ScanType;
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
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.FofoLineItemSerialNumberRepository;
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.transaction.OrderRepository;
import com.spice.profitmandi.dao.repository.user.AddressRepository;
import com.spice.profitmandi.web.model.FofoDetails;
import com.spice.profitmandi.web.request.CreateOrderRequest;
import com.spice.profitmandi.web.request.CustomPaymentOption;
import com.spice.profitmandi.web.response.ItemIdQuantityAvailability;
import com.spice.profitmandi.web.response.Quantity;
import com.spice.profitmandi.web.util.CookiesFetcher;
import com.spice.profitmandi.web.util.MVCResponseSender;
import com.sun.xml.internal.bind.v2.TODO;

@Controller
@Transactional
public class OrderController {

        private static final Logger LOGGER = LoggerFactory.getLogger(OrderController.class);
        
        @Autowired
        OrderRepository orderRepository;
        
        @Autowired
        InventoryItemRepository inventoryItemRepository;
        
        @Autowired
        CurrentInventorySnapshotRepository currentInventorySnapshotRepository;
        
        @Autowired
        InvoiceNumberGenerationSequenceRepository invoiceNumberGenerationSequenceRepository;
        
        @Autowired
        CustomerRepository customerRepository;
        
        @Autowired
        AddressRepository addressRepository;
        
        @Autowired
        FofoLineItemSerialNumberRepository fofoLineItemSerialNumberRepository;
        
        @Autowired
        FofoLineItemRepository fofoLineItemRepository;
        
        @Autowired
        PaymentOptionRepository paymentOptionRepository;
        
        @Autowired
        ScanRecordRepository scanRecordRepository;
        
        @Autowired
        FofoOrderRepository fofoOrderRepository;
        
        @Autowired
        RetailerRepository retailerRepository;
        
        @Autowired
        UserRepository userRepository;
        
        @Autowired
        UserAccountRepository userAccountRepository;
        
        @Autowired
        RetailerRegisteredAddressRepository retailerRegisteredAddressRepository;
        
        @Autowired
        CustomerAddressRepository customerAddressRepository;
        
        @Autowired
        ItemRepository itemRepository;
        
        @Autowired
        MVCResponseSender mvcResponseSender;
        
        @Autowired
        CookiesFetcher cookiesFetcher;
        
        @RequestMapping(value = "/order", method = RequestMethod.POST)
        public String createOrder(HttpServletRequest request, @RequestBody CreateOrderRequest createOrderRequest)  throws Throwable{
                //FofoDetails fofoDetails = cookiesFetcher.getCookiesObject(request);
                LOGGER.info("/order request {}", createOrderRequest);
                FofoDetails fofoDetails = new FofoDetails();
                fofoDetails.setFofoId(963490);
                Set<Integer> itemIds = new HashSet<>();
                Map<Integer, Integer> itemIdQuantity = new HashMap<>(); //this is for error
                Map<Integer, CustomFofoLineItem> customFofoLineItemMap = new HashMap<>();
                Map<Integer, Float> lineItemPrice = new HashMap<>(); //this is for pricing error
                float totalAmount = 0;
                for(CustomFofoLineItem customFofoLineItem : createOrderRequest.getFofoLineItems()){
                        itemIds.add(customFofoLineItem.getItemId());
                        if(!customFofoLineItem.getSerialNumbers().isEmpty() && customFofoLineItem.getQuantity() != customFofoLineItem.getSerialNumbers().size()){
                                itemIdQuantity.put(customFofoLineItem.getItemId(), customFofoLineItem.getQuantity());
                        }
                        if(!(customFofoLineItem.getSellingPrice() > 0)){
                                lineItemPrice.put(customFofoLineItem.getItemId(), customFofoLineItem.getSellingPrice());
                        }else{
                                totalAmount = totalAmount + customFofoLineItem.getSellingPrice() * customFofoLineItem.getQuantity();
                        }
                        customFofoLineItemMap.put(customFofoLineItem.getItemId(), customFofoLineItem);
                }
                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);
                        return "error";
                }
                try{
                        this.validatePaymentOptionsAndTotalAmount(createOrderRequest.getPaymentOptions(), totalAmount);
                }catch(ProfitMandiBusinessException profitMandiBusinessException){
                        LOGGER.error("Error occured while validating payment options : ", profitMandiBusinessException);
                        return "error";
                }
                if(!lineItemPrice.isEmpty()){
                        // given fofo line item price must be greater than zero
                        LOGGER.error("requested itemId's selling price must greater than 0");
                        return "error";
                }
                
                List<CurrentInventorySnapshot> currentInventorySnapshots = currentInventorySnapshotRepository.selectByFofoItemIds(fofoDetails.getFofoId(), itemIds);
                if(itemIds.size() != currentInventorySnapshots.size()){
                        // error
                }
                List<ItemIdQuantityAvailability> itemIdQuantityAvailabilities = new ArrayList<>(); //this is for error
                for(CurrentInventorySnapshot currentInventorySnapshot : currentInventorySnapshots){
                        CustomFofoLineItem customFofoLineItem = customFofoLineItemMap.get(currentInventorySnapshot.getId().getItemId());
                        if(customFofoLineItem.getQuantity() > currentInventorySnapshot.getAvailability()){
                                ItemIdQuantityAvailability itemIdQuantityAvailability = new ItemIdQuantityAvailability();
                                itemIdQuantityAvailability.setItemId(customFofoLineItem.getItemId());
                                Quantity quantity = new Quantity();
                                quantity.setAvailable(currentInventorySnapshot.getAvailability());
                                quantity.setRequested(customFofoLineItem.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);
                        return "error";
                }
                
                
                
                Set<Integer> invalidItemIdSerialNumbers = new HashSet<>();
                Map<Integer, Set<String>> itemIdSerialNumbers = new HashMap<>();
                List<InventoryItem> inventoryItems = inventoryItemRepository.selectByFofoIdItemIds(fofoDetails.getFofoId(), itemIds);
                
                Map<Integer, Float> itemIdPriceDropAmount = new HashMap<>();
                
                for(InventoryItem inventoryItem : inventoryItems){
                        CustomFofoLineItem customFofoLineItem = customFofoLineItemMap.get(inventoryItem.getItemId());
                        if(customFofoLineItem.getSerialNumbers().isEmpty()){
                                if(!(inventoryItem.getSerialNumber() == null && inventoryItem.getSerialNumber().equals(""))){
                                        invalidItemIdSerialNumbers.add(inventoryItem.getItemId());
                                }
                        }
                        if(!customFofoLineItem.getSerialNumbers().isEmpty()){
                                if(!customFofoLineItem.getSerialNumbers().contains(inventoryItem.getSerialNumber())){
                                        if(!itemIdSerialNumbers.containsKey(customFofoLineItem.getItemId())){
                                                Set<String> serialNumbers = new HashSet<>();
                                                serialNumbers.add(inventoryItem.getSerialNumber());
                                                itemIdSerialNumbers.put(customFofoLineItem.getItemId(), serialNumbers);
                                        }else{
                                                itemIdSerialNumbers.get(customFofoLineItem.getItemId()).add(inventoryItem.getSerialNumber());
                                        }
                                }
                        }
                        itemIdPriceDropAmount.put(inventoryItem.getItemId(), inventoryItem.getUnitPrice() - inventoryItem.getPriceDropAmount());
                }
                
                if(!invalidItemIdSerialNumbers.isEmpty()){
                        LOGGER.error("Invalid itemId's serialNumbers {}", invalidItemIdSerialNumbers);
                        // itemId's are serialized you are saying these are not serialized
                        return "error";
                }
                
                if(!itemIdSerialNumbers.isEmpty()){
                        LOGGER.error("Invalid itemId's serialNumbers {}", itemIdSerialNumbers);
                        // itemId's are non serialized you are saying these are serialized
                        return "error";
                }
                
                List<Item> items = itemRepository.selectByIds(itemIds);
                
                if(items.size() != itemIds.size()){
                        LOGGER.error("Requested ItemIds not found in catalog");
                        // invalid itemIds 
                        return "error";
                }
                
                Map<Integer, Item> itemIdDetails = this.toItemMap(items);
                
                InvoiceNumberGenerationSequence invoiceNumberGenerationSequence = null;
                try{
                        invoiceNumberGenerationSequence = invoiceNumberGenerationSequenceRepository.selectByFofoId(fofoDetails.getFofoId());
                        invoiceNumberGenerationSequence.setSequence(invoiceNumberGenerationSequence.getSequence() + 1);
                        invoiceNumberGenerationSequenceRepository.persist(invoiceNumberGenerationSequence);
                }catch(ProfitMandiBusinessException profitMandiBusinessException){
                        invoiceNumberGenerationSequence = new InvoiceNumberGenerationSequence();
                        invoiceNumberGenerationSequence.setFofoId(fofoDetails.getFofoId());
                        invoiceNumberGenerationSequence.setPrefix("INVOICE");
                        invoiceNumberGenerationSequenceRepository.persist(invoiceNumberGenerationSequence);
                }
                
                CustomCustomer customCustomer = createOrderRequest.getCustomer();
                
                if(!StringUtils.isValidEmailAddress(customCustomer.getEmailId())){
                        LOGGER.error("invalid customer emailId {} ", customCustomer.getEmailId());
                        return "error";
                }
                
                if(!StringUtils.isValidMobile(customCustomer.getMobileNumber())){
                        LOGGER.error("invalid customer mobileNumber {} ", customCustomer.getMobileNumber());
                        return "error";
                }
                
                Customer customer = null;
                try{
                        //TODO:remove email id
                        customer = customerRepository.selectByEmailIdAndMobileNumber(customCustomer.getEmailId(), customCustomer.getMobileNumber());
                }catch(ProfitMandiBusinessException profitMandiBusinessException){
                        LOGGER.error("Error : ", profitMandiBusinessException);
                        customer = new Customer();
                        customer.setName(customCustomer.getName());
                        customer.setEmailId(customCustomer.getEmailId());
                        customer.setMobileNumber(customCustomer.getMobileNumber());
                        customerRepository.persist(customer);
                }
                //TODO:Check if createOrderRequest contains addressId
                CustomerAddress customerAddress = this.createCustomerAddress(customCustomer.getAddress());
                customerAddress.setCustomerId(customer.getId());
                customerAddressRepository.persist(customerAddress);
                
                        /*InvoiceNumberGenerationSequence invoiceNumberGenerationSequence = */
                
                
                FofoOrder fofoOrder = new FofoOrder();
                fofoOrder.setCustomerId(customer.getId());
                fofoOrder.setFofoId(fofoDetails.getFofoId());
                fofoOrder.setInvoiceNumber(invoiceNumberGenerationSequence.getPrefix() + invoiceNumberGenerationSequence.getSequence());
                fofoOrder.setTotalAmount(totalAmount);
                fofoOrder.setCustomerAddressId(customerAddress.getId());
                fofoOrderRepository.persist(fofoOrder);
                
                for(CustomPaymentOption customPaymentOption : createOrderRequest.getPaymentOptions()){
                        PaymentOption paymentOption = new PaymentOption();
                        paymentOption.setOrderId(fofoOrder.getId());
                        paymentOption.setAmount(customPaymentOption.getAmount());
                        paymentOption.setType(customPaymentOption.getType());
                        paymentOptionRepository.persist(paymentOption);
                }
                
                Address retailerAddress = addressRepository.selectById(retailerRegisteredAddressRepository.selectAddressIdByRetailerId(fofoDetails.getFofoId()));
                //
                Map<String, GstRate> gstRateMap = Utils.getGstRates(retailerAddress.getState());
                for(CustomFofoLineItem customFofoLineItem : createOrderRequest.getFofoLineItems()){
                        FofoLineItem fofoLineItem = new FofoLineItem();
                        fofoLineItem.setItemId(customFofoLineItem.getItemId());
                        fofoLineItem.setQuantity(customFofoLineItem.getQuantity());
                        fofoLineItem.setSellingPrice(customFofoLineItem.getSellingPrice());
                        fofoLineItem.setOrderId(fofoOrder.getId());
                        fofoLineItem.setDp(customFofoLineItem.getSellingPrice());
                        Item item = itemIdDetails.get(customFofoLineItem.getItemId());
                        GstRate gstRate = gstRateMap.get(item.getHsnCode());
                        fofoLineItem.setIgstRate(gstRate.getIgstRate());
                        fofoLineItem.setCgstRate(gstRate.getCgstRate());
                        fofoLineItem.setSgstRate(gstRate.getSgstRate());
                        fofoLineItem.setCost(itemIdPriceDropAmount.get(customFofoLineItem.getItemId()));
                        fofoLineItem.setBrand(item.getBrand());
                        fofoLineItem.setModelName(item.getModelName());
                        fofoLineItem.setModelNumber(item.getModelNumber());
                        fofoLineItem.setColor(item.getColor());
                        fofoLineItemRepository.persist(fofoLineItem);
                        LOGGER.info("\n\n");
                        if(!customFofoLineItem.getSerialNumbers().isEmpty()){
                                for(String serialNumber : customFofoLineItem.getSerialNumbers()){
                                        FofoLineItemSerialNumber fofoLineItemSerialNumber = new FofoLineItemSerialNumber();
                                        fofoLineItemSerialNumber.setFofoLineItemId(fofoLineItem.getId());
                                        fofoLineItemSerialNumber.setSerialNumber(serialNumber);
                                        fofoLineItemSerialNumberRepository.persist(fofoLineItemSerialNumber);
                                }
                        }
                        
                        for(CurrentInventorySnapshot currentInventorySnapshot : currentInventorySnapshots){
                                FofoItemId fofoItemId = new FofoItemId();
                                fofoItemId.setFofoId(fofoDetails.getFofoId());
                                fofoItemId.setItemId(fofoLineItem.getItemId());
                                if(currentInventorySnapshot.getId().equals(fofoItemId)){
                                        currentInventorySnapshotRepository.updateAvailabilityByFofoItemId(fofoItemId, currentInventorySnapshot.getAvailability() - customFofoLineItem.getQuantity());
                                }
                        }
                        for(InventoryItem inventoryItem : inventoryItems){
                                if(inventoryItem.getItemId() == fofoLineItem.getItemId()){
                                        if(inventoryItem.getSerialNumber() == null || inventoryItem.getSerialNumber().isEmpty()){
                                                if(fofoLineItem.getQuantity() > 0)
                                                if(fofoLineItem.getQuantity() <= inventoryItem.getGoodQuantity()){
                                                        inventoryItem.setGoodQuantity(inventoryItem.getGoodQuantity() - fofoLineItem.getQuantity());
                                                        inventoryItem.setLastScanType(ScanType.SALE);
                                                        inventoryItemRepository.persist(inventoryItem);
                                                        ScanRecord scanRecord = new ScanRecord();
                                                        scanRecord.setInventoryItemId(inventoryItem.getId());
                                                        scanRecord.setFofoId(fofoDetails.getFofoId());
                                                        scanRecord.setQuantity(fofoLineItem.getQuantity());
                                                        scanRecord.setType(ScanType.SALE);
                                                        scanRecordRepository.persist(scanRecord);
                                                }else{
                                                        int availableGoodQuantity = inventoryItem.getGoodQuantity();
                                                        inventoryItem.setGoodQuantity(0);
                                                        fofoLineItem.setQuantity(fofoLineItem.getQuantity() - availableGoodQuantity);
                                                        inventoryItem.setLastScanType(ScanType.SALE);
                                                        inventoryItemRepository.persist(inventoryItem);
                                                        ScanRecord scanRecord = new ScanRecord();
                                                        scanRecord.setInventoryItemId(inventoryItem.getId());
                                                        scanRecord.setFofoId(fofoDetails.getFofoId());
                                                        scanRecord.setQuantity(availableGoodQuantity);
                                                        scanRecord.setType(ScanType.SALE);
                                                        scanRecordRepository.persist(scanRecord);
                                                }
                                        }else{
                                                inventoryItem.setGoodQuantity(0);
                                                inventoryItem.setLastScanType(ScanType.SALE);
                                                inventoryItemRepository.persist(inventoryItem);
                                                ScanRecord scanRecord = new ScanRecord();
                                                scanRecord.setInventoryItemId(inventoryItem.getId());
                                                scanRecord.setFofoId(fofoDetails.getFofoId());
                                                scanRecord.setQuantity(1);
                                                scanRecord.setType(ScanType.SALE);
                                                scanRecordRepository.persist(scanRecord);
                                        }
                                }
                        }
                                        
                }
                return null;
        }
        
        
        private Map<Integer, Item> toItemMap(List<Item> items){
                Map<Integer, Item> map = new HashMap<>();
                for(Item item : items){
                        map.put(item.getId(), item);
                }
                return map;
        }
        
        /*private Address createAddress(CustomAddress customAddress){
                Address address = new Address();
                address.setName(customAddress.getName());
                address.setLine1(customAddress.getLine1());
                address.setLine2(customAddress.getLine2());
                address.setLandmark(customAddress.getLandmark());
                address.setCity(customAddress.getCity());
                address.setPinCode(customAddress.getPinCode());
                address.setState(customAddress.getState());
                address.setCountry(customAddress.getCountry());
                address.setPhoneNumber(customAddress.getPhoneNumber());
                address.setEnabled(true);
                return address;
        }*/
        
        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(customPaymentOption.getType().name())){
                                throw new ProfitMandiBusinessException(ProfitMandiConstants.PAYMENT_OPTION_TYPE, customPaymentOption.getType().name(), "");
                        }else{
                                paymentOptionTypes.add(customPaymentOption.getType().name());
                                calculatedAmount = calculatedAmount + customPaymentOption.getAmount();
                        }
                }
                if(calculatedAmount != totalAmount){
                        throw new ProfitMandiBusinessException(ProfitMandiConstants.PAYMENT_OPTION_CALCULATED_AMOUNT, calculatedAmount, "");
                }
        }
        
        
        @RequestMapping(value = "/generateInvoice")
        public ResponseEntity<?> generateInvoice(HttpServletRequest request, HttpServletResponse response, @RequestParam(name = ProfitMandiConstants.ORDER_ID) int orderId) throws Throwable{
                LOGGER.info("Request received at url {} with params {} ", request.getRequestURI(), request.getParameterMap());
                //FofoDetails fofoDetails = cookiesFetcher.getCookiesObject(request);
                
                FofoDetails fofoDetails = new FofoDetails();
                fofoDetails.setFofoId(963490);
                FofoOrder fofoOrder = fofoOrderRepository.selectByFofoIdAndOrderId(fofoDetails.getFofoId(), orderId);
                PdfModel pdfModel = new PdfModel();
                pdfModel.setAuther("profitmandi");
                pdfModel.setTitle("Retailer Invoice");
                Customer customer = customerRepository.selectById(fofoOrder.getCustomerId());
                CustomCustomer customCustomer = new CustomCustomer();
                customCustomer.setName(customer.getName());
                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(fofoDetails.getFofoId());
                User user = userRepository.selectById(userAccountRepository.selectUserIdByRetailerId(retailer.getId()));
                CustomRetailer customRetailer = new CustomRetailer();
                customRetailer.setBusinessName(retailer.getName());
                customRetailer.setMobileNumber(user.getMobileNumber());
                customRetailer.setTinNumber(retailer.getNumber());
                Address retailerAddress = addressRepository.selectById(retailerRegisteredAddressRepository.selectAddressIdByRetailerId(retailer.getId()));
                customRetailer.setAddress(this.createCustomAddress(retailerAddress));
                pdfModel.setRetailer(customRetailer);
                List<FofoLineItem> fofoLineItems = fofoLineItemRepository.selectByOrderId(fofoOrder.getId());
                
                Set<CustomFofoOrderItem> customerFofoOrderItems = new HashSet<>();
                for(FofoLineItem fofoLineItem : fofoLineItems){
                        CustomFofoOrderItem customFofoOrderItem = new CustomFofoOrderItem();
                        customFofoOrderItem.setAmount(fofoLineItem.getQuantity() * fofoLineItem.getSellingPrice());
                        customFofoOrderItem.setDescription(fofoLineItem.getBrand() + " " + fofoLineItem.getModelName() + " " + fofoLineItem.getModelNumber() + " " + fofoLineItem.getColor());
                        float itemTotal = customFofoOrderItem.getAmount();
                        customFofoOrderItem.setRate(fofoLineItem.getSellingPrice());
                        customFofoOrderItem.setQuantity(fofoLineItem.getQuantity());
                        customFofoOrderItem.setIgstRate(fofoLineItem.getIgstRate());
                        customFofoOrderItem.setCgstRate(fofoLineItem.getIgstRate());
                        customFofoOrderItem.setSgstRate(fofoLineItem.getIgstRate());
                        customFofoOrderItem.setHsnCode(fofoLineItem.getHsnCode());
                        customFofoOrderItem.setItemTotal(itemTotal);
                        customFofoOrderItem.setSerialNumbers(String.join(", ",this.toSerialNumbers(fofoLineItem.getFofoLineItemSerialNumbers())));
                        customerFofoOrderItems.add(customFofoOrderItem);
                }
                pdfModel.setOrderItems(customerFofoOrderItems);
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                PdfUtils.generateAndWrite(pdfModel, byteArrayOutputStream);
                //final MediaType mediaType=MediaType.parseMediaType(profilePhotoModel.getContentType().getValue());
                LOGGER.info("Pdf Stream length {}", byteArrayOutputStream.toByteArray().length);
        final HttpHeaders headers=new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_PDF);
        //headers.set("Content-Disposition", "Order-pdf-"+custom);
        headers.setContentLength(byteArrayOutputStream.toByteArray().length);
        final InputStream inputStream=new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        final InputStreamResource inputStreamResource=new InputStreamResource(inputStream);
        return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
        }
        
        private Set<String> toSerialNumbers(Set<FofoLineItemSerialNumber> fofoLineItemSerialNumbers){
                Set<String> serialNumbers = new HashSet<>(fofoLineItemSerialNumbers.size());
                for(FofoLineItemSerialNumber fofoLineItemSerialNumber : fofoLineItemSerialNumbers){
                        serialNumbers.add(fofoLineItemSerialNumber.getSerialNumber());
                }
                return serialNumbers;
        }
        
        
}