Subversion Repositories SmartDukaan

Rev

Rev 30701 | Rev 30715 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

package com.spice.profitmandi.web.controller;

import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
import com.spice.profitmandi.common.model.ProfitMandiConstants;
import com.spice.profitmandi.common.model.ScanSerializedRequest;
import com.spice.profitmandi.common.web.client.RestClient;
import com.spice.profitmandi.common.web.util.ResponseSender;
import com.spice.profitmandi.dao.entity.fofo.InventoryItem;
import com.spice.profitmandi.dao.entity.transaction.Order;
import com.spice.profitmandi.dao.model.ImeiInoviceModel;
import com.spice.profitmandi.dao.repository.fofo.InventoryItemRepository;
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
import com.spice.profitmandi.service.authentication.RoleManager;
import com.spice.profitmandi.service.inventory.PurchaseService;
import com.spice.profitmandi.service.transaction.invoicing.InvoiceService;
import com.spice.profitmandi.web.model.LoginDetails;
import com.spice.profitmandi.web.util.CookiesProcessor;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.entity.ContentType;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
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.*;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import static org.springframework.util.FileCopyUtils.BUFFER_SIZE;

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

        private static final Logger LOGGER = LogManager.getLogger(PurchaseController.class);

        @Autowired
        private PurchaseService purchaseService;

        @Autowired
        private InventoryItemRepository inventoryItemRepository;

        @Autowired
        private OrderRepository orderRepository;

        @Autowired
        RestClient restClient;
        @Autowired
        private RoleManager roleManager;

        @Autowired
        private ResponseSender responseSender;

        @Autowired
        private CookiesProcessor cookiesProcessor;

        @Autowired
        private InvoiceService invoiceService;

        @RequestMapping(value = "/purchase", method = RequestMethod.GET)
        public String purchase(HttpServletRequest request) throws Exception {
                return "purchase";
        }

        @RequestMapping(value = "/pendingGrn", method = RequestMethod.GET)
        public String pendingGrn(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
                LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
                LOGGER.info("Request Received at url {}", request.getRequestURI());
                List<Order> pendingGrns = orderRepository.selectShipmentToDeliveredByRetailerId(fofoDetails.getFofoId());
                model.addAttribute("pendingGrns", pendingGrns);
                return "pending-grn";
        }

        @RequestMapping(value = "/purchase/validate-imeis", method = RequestMethod.POST)
        public ResponseEntity<?> validatePurchaseImeis(HttpServletRequest request, @RequestBody ImeiInoviceModel imeiInoviceModel, Model model) throws ProfitMandiBusinessException {
                LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
                return responseSender.ok(this.getImeiValidationMap(fofoDetails.getFofoId(), imeiInoviceModel));
        }

        private Map<String, Boolean> getImeiValidationMap(int fofoId, ImeiInoviceModel imeiInoviceModel) throws ProfitMandiBusinessException {
                LOGGER.info("serialNumbers - {}", imeiInoviceModel.getSerialNumbers());
                Set<String> serialNumbers = new HashSet<>(orderRepository.selectSerialNumbers(imeiInoviceModel.getInvoiceNumber(), fofoId, imeiInoviceModel.getSerialNumbers()));
                Map<String, Boolean> imeiValidationMap = new HashMap<>();
                imeiInoviceModel.getSerialNumbers().stream().forEach(x -> {
                        imeiValidationMap.put(x, null);
                });
                if (serialNumbers.size() > 0) {
                        List<InventoryItem> inventoryItems = inventoryItemRepository.selectByFofoIdSerialNumbers(fofoId, new HashSet<>(serialNumbers), false);
                        Set<String> grnedSerialNumberSet = inventoryItems.stream().map(x -> x.getSerialNumber()).collect(Collectors.toSet());
                        imeiInoviceModel.getSerialNumbers().stream().forEach(x -> {
                                imeiValidationMap.put(x, serialNumbers.contains(x) && !grnedSerialNumberSet.contains(x));
                        });
                }
                return imeiValidationMap;
        }

        @RequestMapping(value = "/purchase/grn-imeis", method = RequestMethod.POST)
        public ResponseEntity<?> grnImeis(HttpServletRequest request, @RequestBody ImeiInoviceModel imeiInoviceModel, Model model) throws ProfitMandiBusinessException {
                LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
                Map<String, Boolean> imeiValidationMap = this.getImeiValidationMap(fofoDetails.getFofoId(), imeiInoviceModel);
                if (imeiValidationMap.values().stream().filter(x -> !x).findFirst().isPresent()) {
                        throw new ProfitMandiBusinessException("Found invalid imeis cant proceed", "invalid imeis", "invalid imeis");
                }

                Map<Integer, List<String>> itemSerialNumberMap = orderRepository.selectItemSerialNumberMap(imeiInoviceModel.getInvoiceNumber(), fofoDetails.getFofoId(), imeiInoviceModel.getSerialNumbers());
                for (Map.Entry<Integer, List<String>> itemSerialNumberEntry : itemSerialNumberMap.entrySet()) {
                        ScanSerializedRequest scanSerializedRequest = new ScanSerializedRequest();
                        scanSerializedRequest.setSerialNumbers(itemSerialNumberEntry.getValue());
                        scanSerializedRequest.setInvoiceNumber(imeiInoviceModel.getInvoiceNumber());
                        scanSerializedRequest.setItemId(itemSerialNumberEntry.getKey());
                        purchaseService.scanSerializedItems(scanSerializedRequest, fofoDetails.getFofoId());
                }
                return responseSender.ok(true);
        }

        @RequestMapping(value = "/purchase/get-imeis", method = RequestMethod.GET)
        public ResponseEntity<?> getImeis(HttpServletRequest request, @RequestParam String invoiceNumber, @RequestParam int itemId) throws ProfitMandiBusinessException {
                LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
                List<String> serialNumbers = orderRepository.selectSerialNumbersByInvoiceItem(invoiceNumber, itemId, fofoDetails.getFofoId());
                ImeiInoviceModel imeiInoviceModel = new ImeiInoviceModel();
                imeiInoviceModel.setInvoiceNumber(invoiceNumber);
                imeiInoviceModel.setSerialNumbers(serialNumbers);
                List<String> validSerialNumbers = this.getImeiValidationMap(fofoDetails.getFofoId(), imeiInoviceModel).entrySet().stream().filter(x -> x.getValue()).map(x -> x.getKey()).collect(Collectors.toList());
                return responseSender.ok(validSerialNumbers);
        }


        @RequestMapping(value = "/pendingGrnDetails", method = RequestMethod.GET)
        public String pendingGrnDetails(HttpServletRequest request, @RequestParam(name = ProfitMandiConstants.ORDER_ID) int orderId, Model model) throws ProfitMandiBusinessException {
                LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
                LOGGER.info("Request Received at url [{}] with orderId [{}]", request.getRequestURI(), orderId);
                model.addAttribute("pendingGrnDetails", purchaseService.getShippingDetailByOrderId(orderId, fofoDetails.getFofoId()));
                return "pending-grn-details";
        }

        @RequestMapping(value = "/purchaseByInvoiceNumber", method = RequestMethod.GET)
        public String purchaseByAirwayBillOrInvoiceNumber(HttpServletRequest request,
                                                                                                          @RequestParam(name = ProfitMandiConstants.AIRWAY_BILL_OR_INVOICE_NUMBER)
                                                                                                          String airwayBillOrInvoiceNumber, Model model) throws ProfitMandiBusinessException {
                LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
                LOGGER.info("Request Received at url {} with airwayBillOrInvoiceNumber {}", request.getRequestURI(), airwayBillOrInvoiceNumber);
                Map<String, Object> map = purchaseService.purchaseByInvoiceNumber(airwayBillOrInvoiceNumber, fofoDetails.getFofoId());
                model.addAllAttributes(map);
                return "purchase";
        }

        @RequestMapping(value = "/purchase-invoice/{invoiceNumber}", method = RequestMethod.GET)
        public ResponseEntity<?> downloadInvoice(HttpServletRequest request, @PathVariable String invoiceNumber, Model model) throws Exception {
                LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
                List<String> invoiceNumbers = Arrays.asList(invoiceNumber.replaceAll(" ", "").split(","));
                Map<String, List<Order>> invoiceOrdersMap = orderRepository.selectByInvoiceNumbers(invoiceNumbers).stream().collect(Collectors.groupingBy(x -> x.getInvoiceNumber()));
                if (invoiceOrdersMap.size() > 0) {
                        if (roleManager.isAdmin(fofoDetails.getRoleIds()) || invoiceOrdersMap.get(invoiceNumbers.get(0)).get(0).getRetailerId() == fofoDetails.getFofoId()) {

                                final HttpHeaders headers = new HttpHeaders();
                                headers.setContentType(MediaType.APPLICATION_PDF);
                                headers.set("Content-Type", "application/pdf");
                                headers.set("Content-disposition", "inline; filename=" + invoiceNumber + ".pdf");

                                if (false) {
                                        /*InvoicePdfModel invoicePdfModel = invoiceService.getInvoicePdfModel(orders);

                                        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                                        List<InvoicePdfModel> pdfModels = new ArrayList<>();
                                        pdfModels.add(invoicePdfModel);
                                        PdfUtils.generateAndWrite(pdfModels, byteArrayOutputStream);
                                        final InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
                                        final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
                                        LOGGER.info("Before stream - {}", pdfModels);
                                        return new ResponseEntity<>(inputStreamResource, headers, HttpStatus.OK);*/
                                } else {
                                        Map<String, String> headersMap = new HashMap<>();
                                        headersMap.put("Authorization", "Basic " + Base64.getEncoder().encodeToString("smartdukaan:$smart@123#".getBytes()));
                                        if (invoiceNumbers.size() == 1) {
                                                String invoicePath = this.getInvoicePath(invoiceOrdersMap.get(invoiceNumbers.get(0)).get(0));
                                                HttpResponse response = restClient.getResponse("http://45.79.106.95/" + invoicePath, null, headersMap);
                                                InputStreamResource is = new InputStreamResource(response.getEntity().getContent());
                                                return new ResponseEntity<>(is, headers, HttpStatus.OK);

                                        } else {

                                                ByteArrayOutputStream fos = new ByteArrayOutputStream();
                                                ZipOutputStream zipOut = new ZipOutputStream(fos);

                                                for (String invoice : invoiceNumbers) {
                                                        List<Order> orders = invoiceOrdersMap.get(invoice);
                                                        String invoicePath = this.getInvoicePath(orders.get(0));
                                                        HttpResponse response = restClient.getResponse("http://45.79.106.95/" + invoicePath, null, headersMap);
                                                        this.addFileToZip(zipOut, response.getEntity().getContent(), invoice + ".pdf");
                                                }
                                                zipOut.close();
                                                byte[] byteArray = fos.toByteArray();
                                                headers.set("Content-Type", ContentType.APPLICATION_OCTET_STREAM.getMimeType());
                                                headers.set("Content-disposition", "attachment; filename=invoices.zip");
                                                headers.setContentLength(byteArray.length);
                                                final InputStream inputStream = new ByteArrayInputStream(fos.toByteArray());
                                                return new ResponseEntity<>(new InputStreamResource(inputStream), headers, HttpStatus.OK);
                                        }
                                }

                        }
                } else {
                        throw new ProfitMandiBusinessException("Invalid Invoice", invoiceNumber, "Please check with your manager");
                }
                return null;
        }

        private void addFileToZip(ZipOutputStream outZip, InputStream inputStream, String fileName) throws Exception {
                byte data[] = new byte[BUFFER_SIZE];
                ZipEntry entry = new ZipEntry(fileName);
                outZip.putNextEntry(entry);
                IOUtils.copy(inputStream, outZip);
                outZip.closeEntry();
        }

        private String getInvoicePath(Order order) {
                LocalDateTime billTime = order.getBillingTimestamp();
                String dirPath = billTime.getYear() + "-" + (billTime.getMonthValue() - 1) + File.separator + order.getRetailerId();
                String filename = dirPath + File.separator + order.getInvoiceNumber() + ".pdf";
                return filename;
        }
}