Subversion Repositories SmartDukaan

Rev

Rev 22860 | Rev 23203 | 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.time.LocalDateTime;
import java.util.ArrayList;
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 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.transaction.annotation.Transactional;
import org.springframework.ui.Model;
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.CartFofo;
import com.spice.profitmandi.common.model.CreateOrderRequest;
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.util.PdfUtils;
import com.spice.profitmandi.common.util.StringUtils;
import com.spice.profitmandi.common.web.util.ResponseSender;
import com.spice.profitmandi.dao.entity.dtr.InsurancePolicy;
import com.spice.profitmandi.dao.entity.fofo.Customer;
import com.spice.profitmandi.dao.entity.fofo.CustomerAddress;
import com.spice.profitmandi.dao.entity.fofo.FofoOrder;
import com.spice.profitmandi.dao.entity.fofo.FofoOrderItem;
import com.spice.profitmandi.dao.entity.fofo.PaymentOption;
import com.spice.profitmandi.dao.repository.dtr.InsurancePolicyRepository;
import com.spice.profitmandi.dao.repository.fofo.CustomerAddressRepository;
import com.spice.profitmandi.dao.repository.fofo.CustomerRepository;
import com.spice.profitmandi.dao.repository.fofo.FofoOrderItemRepository;
import com.spice.profitmandi.dao.repository.fofo.FofoOrderRepository;
import com.spice.profitmandi.dao.repository.fofo.PaymentOptionRepository;
import com.spice.profitmandi.service.inventory.OrderService;
import com.spice.profitmandi.service.pricing.PricingService;
import com.spice.profitmandi.web.model.LoginDetails;
import com.spice.profitmandi.web.util.CookiesProcessor;

@Controller
@Transactional(rollbackFor=Throwable.class)
public class OrderController {

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

        @Autowired
        private CustomerRepository customerRepository;

        @Autowired
        private FofoOrderItemRepository fofoLineItemRepository;

        @Autowired
        private PaymentOptionRepository paymentOptionRepository;

        @Autowired
        private FofoOrderRepository fofoOrderRepository;

        @Autowired
        private CustomerAddressRepository customerAddressRepository;
        
        @Autowired
        private InsurancePolicyRepository insurancePolicyRepository;

        @Autowired
        private CookiesProcessor cookiesProcessor;
        
        @Autowired
        private PricingService pricingService;
        
        @Autowired
        private OrderService orderService;
        
        
        @Autowired
        private ResponseSender<?> responseSender;
        
        @RequestMapping(value = "/order")
        public String orderIndex(HttpServletRequest request, @RequestParam(name = "cartData") String cartData, Model model) throws ProfitMandiBusinessException{
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);;
                
                List<CartFofo> cartItems = orderService.cartCheckout(cartData);
                Set<Integer> itemIds = new HashSet<>();
                for(CartFofo cartFofo : cartItems){
                        itemIds.add(cartFofo.getItemId());
                }
                Map<Integer, PriceModel> mopPriceMap = pricingService.getPurchasePriceMopPriceNotFound(itemIds, loginDetails.getFofoId());
                LOGGER.info("mopPriceMap {}", mopPriceMap);
                model.addAttribute("cartObj", cartItems);
                model.addAttribute("mopPriceMap", mopPriceMap);
                return "order-index";
        }
        
        
        @RequestMapping(value = "/insurancePrices", method = RequestMethod.GET)
        public ResponseEntity<?> getInsurancePrices(HttpServletRequest request, @RequestParam(name = ProfitMandiConstants.PRICE) float price) throws ProfitMandiBusinessException{
                LOGGER.info("Request received at url : {}", request.getRequestURI());
                Set<Float> prices = new HashSet<>();
                prices.add(price);
                return responseSender.ok(pricingService.getInsurancePrices(prices, ProfitMandiConstants.GADGET_COPS));
        }
        
        
        @RequestMapping(value = "/get-order", method = RequestMethod.GET)
        public String getOrder(HttpServletRequest request, @RequestParam(name = ProfitMandiConstants.ORDER_ID) int orderId, Model model) throws ProfitMandiBusinessException{
                LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
                FofoOrder fofoOrder = fofoOrderRepository.selectByFofoIdAndOrderId(fofoDetails.getFofoId(), orderId);
                List<FofoOrderItem> fofoLineItems = fofoLineItemRepository.selectByOrderId(fofoOrder.getId());
                CustomerAddress customerAddress = customerAddressRepository.selectById(fofoOrder.getCustomerAddressId());
                Customer customer  = customerRepository.selectById(fofoOrder.getCustomerId());
                customerAddress.setPhoneNumber(customer.getMobileNumber());
                List<PaymentOption> paymentOptions = paymentOptionRepository.selectByOrderId(fofoOrder.getId());
                List<InsurancePolicy> insurancePolicies = insurancePolicyRepository.selectByRetailerIdInvoiceNumber(fofoOrder.getFofoId(), fofoOrder.getInvoiceNumber());
                model.addAttribute("fofoOrder", fofoOrder);
                model.addAttribute("fofoLineItems", fofoLineItems);
                model.addAttribute("customerBillingAddress", orderService.getBillingAddress(customerAddress));
                model.addAttribute("customerBillingAddressObj", customerAddress);
                model.addAttribute("paymentOptions", paymentOptions);
                model.addAttribute("insurancePolicies", insurancePolicies);
                return "order-details";
        }
        
        
        @RequestMapping(value = "/saleDetails", method = RequestMethod.GET)
        public String getSaleDetails(HttpServletRequest request, @RequestParam(name = ProfitMandiConstants.ORDER_ID) int orderId, Model model) throws ProfitMandiBusinessException{
                LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
                
                FofoOrder fofoOrder = fofoOrderRepository.selectByFofoIdAndOrderId(fofoDetails.getFofoId(), orderId);
                List<FofoOrderItem> fofoLineItems = fofoLineItemRepository.selectByOrderId(fofoOrder.getId());
                CustomerAddress customerAddress = customerAddressRepository.selectById(fofoOrder.getCustomerAddressId());
                List<PaymentOption> paymentOptions = paymentOptionRepository.selectByOrderId(fofoOrder.getId());
                List<InsurancePolicy> insurancePolicies = insurancePolicyRepository.selectByRetailerIdInvoiceNumber(fofoOrder.getFofoId(), fofoOrder.getInvoiceNumber());
                model.addAttribute("fofoOrder", fofoOrder);
                model.addAttribute("fofoLineItems", fofoLineItems);
                model.addAttribute("customerBillingAddress", orderService.getBillingAddress(customerAddress));
                model.addAttribute("customerBillingAddressObj", customerAddress);
                model.addAttribute("paymentOptions", paymentOptions);
                model.addAttribute("insurancePolicies", insurancePolicies);
                return "sale-details";
        }
        

        @RequestMapping(value = "/create-order", method = RequestMethod.POST)
        public String createOrder(HttpServletRequest request, @RequestBody CreateOrderRequest createOrderRequest, Model model)  throws ProfitMandiBusinessException{
                LOGGER.info("request at uri {} body {}", request.getRequestURI(), createOrderRequest);
                LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
                
                int fofoOrderId = orderService.createOrder(createOrderRequest, fofoDetails.getFofoId());
                LOGGER.info("Order has been created successfully...");
                return "redirect:/get-order/?orderId="+fofoOrderId;
        }


        @RequestMapping(value = "/generateInvoice")
        public ResponseEntity<?> generateInvoice(HttpServletRequest request, HttpServletResponse response, @RequestParam(name = ProfitMandiConstants.ORDER_ID) int orderId) throws ProfitMandiBusinessException{
                LOGGER.info("Request received at url {} with params [{}={}] ", request.getRequestURI(), ProfitMandiConstants.ORDER_ID, orderId);
                LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);

                PdfModel pdfModel = orderService.getInvoicePdfModel(fofoDetails.getFofoId(), orderId);
                
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                PdfUtils.generateAndWrite(pdfModel, byteArrayOutputStream);
                LOGGER.info("Pdf Stream length {}", byteArrayOutputStream.toByteArray().length);
        final HttpHeaders headers=new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_PDF);
        headers.set("Content-disposition", "inline; filename=invoice-" + pdfModel.getInvoiceNumber() + ".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);
        }
        
        @RequestMapping(value = "/saleHistory")
        public String saleHistory(HttpServletRequest request, @RequestParam(name = ProfitMandiConstants.START_TIME, required = false) String startTimeString, @RequestParam(name = ProfitMandiConstants.END_TIME, required = false) String endTimeString, @RequestParam(name = "offset", defaultValue = "0") int offset, @RequestParam(name = "limit", defaultValue = "10") int limit, @RequestParam(name = ProfitMandiConstants.INVOICE_NUMBER, defaultValue = "") String invoiceNumber, @RequestParam(name = "searchType",defaultValue="") String searchType, Model model) throws ProfitMandiBusinessException{
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                
                LocalDateTime startDateTime = StringUtils.toDateTime(startTimeString);
                LocalDateTime endDateTime = StringUtils.toDateTime(endTimeString);
                long countItems = 0;
                List<FofoOrder> fofoOrders = new ArrayList<>();
                if(searchType.equalsIgnoreCase(ProfitMandiConstants.INVOICE_NUMBER) && !invoiceNumber.isEmpty()){
                        try {
                                FofoOrder fofoOrder = fofoOrderRepository.selectByFofoIdAndInvoiceNumber(loginDetails.getFofoId(), invoiceNumber);
                                fofoOrders.add(fofoOrder);
                        } catch (ProfitMandiBusinessException e) {
                                LOGGER.info("Sale history not found : ", e);
                        }
                }else{
                        fofoOrders = fofoOrderRepository.selectByFofoId(loginDetails.getFofoId(), startDateTime, endDateTime, offset, limit);
                        countItems = fofoOrderRepository.selectCount(loginDetails.getFofoId(), startDateTime, endDateTime, invoiceNumber, searchType);
                }
                
                model.addAttribute("saleHistories", fofoOrders);
                model.addAttribute("start", offset + 1);
                model.addAttribute("size", countItems);
                model.addAttribute("searchType", searchType);
                model.addAttribute(ProfitMandiConstants.START_TIME, startTimeString);
                model.addAttribute(ProfitMandiConstants.END_TIME, endTimeString);
                if (fofoOrders.size() < limit){
                        model.addAttribute("end", offset + fofoOrders.size());
                }
                else{
                        model.addAttribute("end", offset + limit);
                }
                
                return "sale-history";
        }
        
        
        @RequestMapping(value = "/getPaginatedSaleHistory")
        public String getSaleHistoryPaginated(HttpServletRequest request, @RequestParam(name = ProfitMandiConstants.START_TIME, required = false) String startTimeString, @RequestParam(name = ProfitMandiConstants.END_TIME, required = false) String endTimeString, @RequestParam(name = "offset", defaultValue = "0") int offset, @RequestParam(name = "limit", defaultValue="10") int limit, @RequestParam(name = ProfitMandiConstants.INVOICE_NUMBER, defaultValue="") String invoiceNumber, @RequestParam(name = "searchType", defaultValue = "") String searchType, Model model) throws ProfitMandiBusinessException{
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                
                LocalDateTime startDateTime = StringUtils.toDateTime(startTimeString);
                LocalDateTime endDateTime = StringUtils.toDateTime(endTimeString);

                List<FofoOrder> saleHistories = fofoOrderRepository.selectByFofoId(loginDetails.getFofoId(), startDateTime, endDateTime, offset, limit);
                model.addAttribute("saleHistories", saleHistories);
                return "sale-history-paginated";
        }

}