Subversion Repositories SmartDukaan

Rev

Rev 21690 | Rev 21711 | 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.apache.commons.lang.WordUtils;
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.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.dao.entity.Address;
import com.spice.profitmandi.dao.entity.CurrentInventorySnapshot;
import com.spice.profitmandi.dao.entity.Customer;
import com.spice.profitmandi.dao.entity.FofoLineItem;
import com.spice.profitmandi.dao.entity.FofoLineItemSerialNumber;
import com.spice.profitmandi.dao.entity.FofoOrder;
import com.spice.profitmandi.dao.entity.InventoryItem;
import com.spice.profitmandi.dao.entity.InvoiceNumberGenerationSequence;
import com.spice.profitmandi.dao.entity.Item;
import com.spice.profitmandi.dao.entity.LineItem;
import com.spice.profitmandi.dao.entity.Order;
import com.spice.profitmandi.dao.entity.PaymentOption;
import com.spice.profitmandi.dao.entity.Retailer;
import com.spice.profitmandi.dao.entity.ScanRecord;
import com.spice.profitmandi.dao.entity.User;
import com.spice.profitmandi.dao.enumuration.ScanType;
import com.spice.profitmandi.dao.repository.AddressRepository;
import com.spice.profitmandi.dao.repository.CurrentInventorySnapshotRepository;
import com.spice.profitmandi.dao.repository.CustomerRepository;
import com.spice.profitmandi.dao.repository.FofoLineItemRepository;
import com.spice.profitmandi.dao.repository.FofoLineItemSerialNumberRepository;
import com.spice.profitmandi.dao.repository.FofoOrderRepository;
import com.spice.profitmandi.dao.repository.InventoryItemRepository;
import com.spice.profitmandi.dao.repository.InvoiceNumberGenerationSequenceRepository;
import com.spice.profitmandi.dao.repository.OrderRepository;
import com.spice.profitmandi.dao.repository.PaymentOptionRepository;
import com.spice.profitmandi.dao.repository.RetailerRegisteredAddressRepository;
import com.spice.profitmandi.dao.repository.RetailerRepository;
import com.spice.profitmandi.dao.repository.ScanRecordRepository;
import com.spice.profitmandi.dao.repository.UserAccountRepository;
import com.spice.profitmandi.dao.repository.UserRepository;
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;

@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
        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<CustomFofoLineItem> fofoLineItems = createOrderRequest.getFofoLineItems();
                Set<Integer> itemIds = new HashSet<>();
                Set<Integer> nonSerializedItemIds = new HashSet<>();
                Map<Integer, Integer> itemIdQuantity = new HashMap<>();
                for(CustomFofoLineItem fofoLineItem : fofoLineItems){
                        itemIds.add(fofoLineItem.getItemId());
                        if(fofoLineItem.getSerialNumbers().size() > 0 && fofoLineItem.getQuantity() != fofoLineItem.getSerialNumbers().size()){
                                itemIdQuantity.put(fofoLineItem.getItemId(), fofoLineItem.getQuantity());
                        }
                        if(fofoLineItem.getSerialNumbers().isEmpty()){
                                nonSerializedItemIds.add(fofoLineItem.getItemId());
                        }
                }
                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";
                }
                float totalAmount = 0;
                Map<Integer, Float> lineItemPrice = new HashMap<>();
                List<CurrentInventorySnapshot> currentInventorySnapshots = currentInventorySnapshotRepository.selectByFofoItemIds(fofoDetails.getFofoId(), itemIds);
                List<ItemIdQuantityAvailability> itemIdQuantityAvailabilities = new ArrayList<>(); 
                for(CurrentInventorySnapshot currentInventorySnapshot : currentInventorySnapshots){
                        for(CustomFofoLineItem fofoLineItem : fofoLineItems){
                                if(currentInventorySnapshot.getId().getItemId() == fofoLineItem.getItemId()){
                                        if(fofoLineItem.getQuantity() > currentInventorySnapshot.getAvailability()){
                                                ItemIdQuantityAvailability itemIdQuantityAvailability = new ItemIdQuantityAvailability();
                                                itemIdQuantityAvailability.setItemId(fofoLineItem.getItemId());
                                                Quantity quantity = new Quantity();
                                                quantity.setAvailable(currentInventorySnapshot.getAvailability());
                                                quantity.setRequested(fofoLineItem.getQuantity());
                                                itemIdQuantityAvailability.setQuantity(quantity);
                                                itemIdQuantityAvailabilities.add(itemIdQuantityAvailability);
                                        }
                                }
                                if(!(fofoLineItem.getSellingPrice() > 0)){
                                        lineItemPrice.put(fofoLineItem.getItemId(), fofoLineItem.getSellingPrice());
                                }else{
                                        totalAmount = totalAmount + fofoLineItem.getSellingPrice() * fofoLineItem.getQuantity();
                                }
                        }
                }
                
                try{
                        this.validatePaymentOptionsAndTotalAmount(createOrderRequest.getPaymentOptions(), totalAmount);
                }catch(ProfitMandiBusinessException profitMandiBusinessException){
                        LOGGER.error("Error occured while validating payment options : ", profitMandiBusinessException);
                        return "error";
                }
                
                if(!itemIdQuantityAvailabilities.isEmpty()){
                        // itemIdQuantity request is not valid
                        LOGGER.error("Requested quantities should not be greater than currently available quantities {}", itemIdQuantityAvailabilities);
                        return "error";
                }
                
                if(!lineItemPrice.isEmpty()){
                        // given fofo line item price must be greater than zero
                        LOGGER.error("requested itemId's selling price must greater thant 0");
                        return "error";
                }
                
                Set<Integer> invalidItemIdSerialNumbers = new HashSet<>();
                Map<Integer, Set<String>> itemIdSerialNumbers = new HashMap<>();
                List<InventoryItem> inventoryItems = inventoryItemRepository.selectByFofoIdItemIds(fofoDetails.getFofoId(), itemIds);
                if(inventoryItems.isEmpty()){
                        // invalid item ids
                        LOGGER.error("Requested itemId's are not available in inventoryItem");
                        return "error";
                }
                
                for(InventoryItem inventoryItem : inventoryItems){
                        for(CustomFofoLineItem fofoLineItem : fofoLineItems){
                                if(inventoryItem.getItemId() == fofoLineItem.getItemId()){
                                        if(fofoLineItem.getSerialNumbers().isEmpty()){
                                                if(!(inventoryItem.getSerialNumber() == null && inventoryItem.getSerialNumber().equals(""))){
                                                        invalidItemIdSerialNumbers.add(inventoryItem.getItemId());
                                                }
                                        }
                                        if(!fofoLineItem.getSerialNumbers().isEmpty()){
                                                if(!fofoLineItem.getSerialNumbers().contains(inventoryItem.getSerialNumber())){
                                                        if(!itemIdSerialNumbers.containsKey(fofoLineItem.getItemId())){
                                                                Set<String> serialNumbers = new HashSet<>();
                                                                serialNumbers.add(inventoryItem.getSerialNumber());
                                                                itemIdSerialNumbers.put(fofoLineItem.getItemId(), serialNumbers);
                                                        }else{
                                                                itemIdSerialNumbers.get(fofoLineItem.getItemId()).add(inventoryItem.getSerialNumber());
                                                        }
                                                }
                                        }
                                }
                        }
                }
                
                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";
                }
                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";
                }
                
                Address address = this.createAddress(customCustomer.getAddress());
                addressRepository.persist(address);
                
                
                Customer customer = null;
                try{
                        customer = customerRepository.selectByEmailIdAndMobileNumber(customCustomer.getEmailId(), customCustomer.getMobileNumber());
                }catch(ProfitMandiBusinessException profitMandiBusinessException){
                        LOGGER.error("Error : ", profitMandiBusinessException);
                        customer = new Customer();
                        customCustomer.setName(customCustomer.getName());
                        customer.setEmailId(customCustomer.getEmailId());
                        customer.setMobileNumber(customCustomer.getMobileNumber());
                        customer.setAddressId(address.getId());
                        customerRepository.persist(customer);
                }
                
                
                        /*InvoiceNumberGenerationSequence invoiceNumberGenerationSequence = */
                
                
                FofoOrder fofoOrder = new FofoOrder();
                fofoOrder.setCustomerId(customer.getId());
                fofoOrder.setFofoId(fofoDetails.getFofoId());
                fofoOrder.setInvoiceNumber(invoiceNumberGenerationSequence.getPrefix() + invoiceNumberGenerationSequence.getSequence());
                fofoOrder.setTotalAmount(totalAmount);
                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);
                }
                
                List<Order> orders = orderRepository.selectByRetailerIdItemIds(fofoDetails.getFofoId(), itemIds);
                
                Set<Item> items = new HashSet<>(itemIds.size());
                for(Order order : orders){
                        LineItem lineItem = order.getLineItem();
                        items.add(lineItem.getItem());
                }
                
                if(items.size() != itemIds.size()){
                        LOGGER.error("Requested ItemIds not found in catalog");
                        // invalid itemIds 
                        return "error";
                }
                
                Map<Integer, Map<String, String>> itemIdDetails = this.toMap(items);
                
                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());
                        fofoLineItem.setTax(0);
                        fofoLineItem.setTaxRate(0);
                        Map<String, String> itemIdDetail = itemIdDetails.get(customFofoLineItem.getItemId());
                        fofoLineItem.setBrand(itemIdDetail.get(ProfitMandiConstants.BRAND));
                        fofoLineItem.setModelName(itemIdDetail.get(ProfitMandiConstants.MODEL_NAME));
                        fofoLineItem.setModelNumber(itemIdDetail.get(ProfitMandiConstants.MODEL_NUMBER));
                        fofoLineItem.setColor(itemIdDetail.get(ProfitMandiConstants.COLOR));
                        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(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, Map<String, String>> toMap(Set<Item> items){
                Map<Integer, Map<String, String>> map = new HashMap<>();
                for(Item item : items){
                        Map<String, String> detailMap = new HashMap<>();
                        detailMap.put(ProfitMandiConstants.BRAND, item.getBrand());
                        detailMap.put(ProfitMandiConstants.MODEL_NAME, item.getModelName());
                        detailMap.put(ProfitMandiConstants.MODEL_NUMBER, item.getModelNumber());
                        detailMap.put(ProfitMandiConstants.COLOR, item.getColor());
                        map.put(item.getId(), detailMap);
                }
                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 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 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());
                Address customerAddress = addressRepository.selectById(customer.getAddressId()); 
                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() - fofoLineItem.getTax();
                        customFofoOrderItem.setRate(fofoLineItem.getSellingPrice());
                        customFofoOrderItem.setQuantity(fofoLineItem.getQuantity());
                        customFofoOrderItem.setTax(fofoLineItem.getTax());
                        customFofoOrderItem.setTaxRate(fofoLineItem.getTaxRate());
                        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", "retailerInvoice.pdf");
        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;
        }
}