Subversion Repositories SmartDukaan

Rev

Rev 37380 | Show entire file | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 37380 Rev 37400
Line 83... Line 83...
83
import javax.mail.MessagingException;
83
import javax.mail.MessagingException;
84
import javax.servlet.http.HttpServletRequest;
84
import javax.servlet.http.HttpServletRequest;
85
import javax.servlet.http.HttpServletResponse;
85
import javax.servlet.http.HttpServletResponse;
86
import java.io.*;
86
import java.io.*;
87
import java.nio.file.Files;
87
import java.nio.file.Files;
-
 
88
import java.nio.file.Path;
88
import java.time.LocalDate;
89
import java.time.LocalDate;
89
import java.time.LocalDateTime;
90
import java.time.LocalDateTime;
90
import java.time.format.DateTimeFormatter;
91
import java.time.format.DateTimeFormatter;
91
import java.time.temporal.ChronoUnit;
92
import java.time.temporal.ChronoUnit;
92
import java.util.*;
93
import java.util.*;
Line 520... Line 521...
520
            paymentOptionIdPaymentOptionMap.put(paymentOption.getId(), paymentOption);
521
            paymentOptionIdPaymentOptionMap.put(paymentOption.getId(), paymentOption);
521
        }
522
        }
522
        return paymentOptionIdPaymentOptionMap;
523
        return paymentOptionIdPaymentOptionMap;
523
    }
524
    }
524
 
525
 
525
    private Map<Integer, PaymentOption> paymentOptionIdPaymentOptionMapUsingPaymentOptions(
-
 
526
            List<Integer> fofoPartnerPaymentOptions) throws ProfitMandiBusinessException {
-
 
527
        List<PaymentOption> paymentOptions = paymentOptionRepository
-
 
528
                .selectByIds(new HashSet<>(fofoPartnerPaymentOptions));
-
 
529
        Map<Integer, PaymentOption> paymentOptionIdPaymentOptionMap = new HashMap<>();
-
 
530
        for (PaymentOption paymentOption : paymentOptions) {
-
 
531
            paymentOptionIdPaymentOptionMap.put(paymentOption.getId(), paymentOption);
-
 
532
        }
-
 
533
        return paymentOptionIdPaymentOptionMap;
-
 
534
    }
-
 
535
 
-
 
536
    private Map<Integer, PaymentOptionTransaction> paymentOptionIdPaymentOptionTransactionMap(
526
    private Map<Integer, PaymentOptionTransaction> paymentOptionIdPaymentOptionTransactionMap(
537
            List<PaymentOptionTransaction> paymentOptionTransactions) {
527
            List<PaymentOptionTransaction> paymentOptionTransactions) {
538
        Map<Integer, PaymentOptionTransaction> paymentOptionIdPaymentOptionTransactionMap = new HashMap<>();
528
        Map<Integer, PaymentOptionTransaction> paymentOptionIdPaymentOptionTransactionMap = new HashMap<>();
539
        for (PaymentOptionTransaction paymentOptionTransaction : paymentOptionTransactions) {
529
        for (PaymentOptionTransaction paymentOptionTransaction : paymentOptionTransactions) {
540
            paymentOptionIdPaymentOptionTransactionMap.put(paymentOptionTransaction.getPaymentOptionId(),
530
            paymentOptionIdPaymentOptionTransactionMap.put(paymentOptionTransaction.getPaymentOptionId(),
Line 728... Line 718...
728
        //jaihind
718
        //jaihind
729
        return responseSender.ok("Success");
719
        return responseSender.ok("Success");
730
 
720
 
731
    }
721
    }
732
 
722
 
733
    @RequestMapping(value = "/generateInvoice")
-
 
734
    public ResponseEntity<?> generateInvoice(HttpServletRequest request, HttpServletResponse response,
-
 
735
                                             @RequestParam(name = ProfitMandiConstants.ORDER_ID) int orderId) throws ProfitMandiBusinessException {
-
 
736
        LOGGER.info("Request received at url {} with params [{}={}] ", request.getRequestURI(),
723
    /** Provider whose policy certificates we hold on disk and can staple to the invoice. */
737
                ProfitMandiConstants.ORDER_ID, orderId);
724
    private static final int CERTIFICATE_PROVIDER_ID = 6;
738
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
-
 
739
        InvoicePdfModel pdfModel = null;
-
 
740
        if (roleManager.isAdmin(fofoDetails.getRoleIds())) {
-
 
741
            pdfModel = orderService.getInvoicePdfModel(orderId);
-
 
742
        } else {
-
 
743
            pdfModel = orderService.getInvoicePdfModel(fofoDetails.getFofoId(), orderId);
-
 
744
        }
-
 
745
        FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(orderId);
-
 
746
        List<InsurancePolicy> insurancePolicies = insurancePolicyRepository.selectByRetailerIdInvoiceNumber(fofoOrder.getInvoiceNumber());
-
 
747
 
-
 
748
        // Step 1: Generate invoice PDF
-
 
749
        ByteArrayOutputStream invoiceOutput = new ByteArrayOutputStream();
-
 
750
        PdfUtils.generateAndWrite(Arrays.asList(pdfModel), invoiceOutput);
-
 
751
        byte[] invoicePdf = invoiceOutput.toByteArray();
-
 
752
 
725
 
753
        // Step 2: Load all policy certificate PDFs
726
    /** How many of the matching sale-history invoices one download will render. */
754
        List<byte[]> pdfFiles = new ArrayList<>();
727
    private static final int SALE_HISTORY_DOWNLOAD_LIMIT = 100;
755
        pdfFiles.add(invoicePdf); // first add invoice
-
 
756
 
728
 
-
 
729
    /**
757
        for (InsurancePolicy insurancePolicy : insurancePolicies) {
730
     * Single entry point for downloading partner sale invoices.
-
 
731
     *
-
 
732
     * <p>The three ways an operator picks the orders — one order, a partner's date range, or a
758
            if (insurancePolicy.getProviderId() == 6) {
733
     * sale-history search — differ only in how the order ids are resolved and who is allowed to
759
                String policyNumber = insurancePolicy.getPolicyNumber();
734
     * ask. Everything after that (build the models, render, staple the policy certificates,
760
                String safePolicyNo = policyNumber.replace("/", "-");
735
     * respond) is identical, so it lives here once. Keeping them apart is what let them drift:
761
                String filePath = "/uploads/policy-certificate-" + safePolicyNo + ".pdf";
736
     * only the single-order download used to attach the certificates, so the same invoice pulled
762
                File file = new File(filePath);
737
     * from sale history silently came out without them.
763
 
738
     *
764
                if (file.exists()) {
739
     * <p>Selector, in precedence order: {@code orderId} → one invoice; {@code partnerId} with
-
 
740
     * {@code startDate}/{@code endDate} → that partner's range, admin only; otherwise the caller's
765
                    try {
741
     * own sale-history search.
-
 
742
     */
-
 
743
    @RequestMapping(value = "/invoice/download")
-
 
744
    public ResponseEntity<?> downloadInvoice(HttpServletRequest request,
-
 
745
                                             @RequestParam(name = ProfitMandiConstants.ORDER_ID, required = false) Integer orderId,
766
                        byte[] policyPdf = Files.readAllBytes(file.toPath());
746
                                             @RequestParam(required = false) Integer partnerId,
767
                        pdfFiles.add(policyPdf);
747
                                             @RequestParam(required = false) LocalDateTime startDate,
768
                    } catch (IOException e) {
748
                                             @RequestParam(required = false) LocalDateTime endDate,
-
 
749
                                             @RequestParam(name = "searchValue", defaultValue = "") String searchValue,
-
 
750
                                             @RequestParam(name = "searchType", defaultValue = "") SearchType searchType,
769
                        LOGGER.error("Failed to read policy PDF: {}", filePath, e);
751
                                             @RequestParam(required = false) LocalDateTime startTime,
770
                    }
752
                                             @RequestParam(required = false) LocalDateTime endTime,
771
                } else {
753
                                             @RequestParam(name = "offset", defaultValue = "0") int offset,
772
                    LOGGER.warn("Policy PDF not found: {}", filePath);
754
                                             @RequestParam(name = "withPolicies", defaultValue = "true") boolean withPolicies)
773
                }
755
            throws ProfitMandiBusinessException {
-
 
756
        LOGGER.info("Request received at url {} with query [{}]", request.getRequestURI(), request.getQueryString());
774
            }
757
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
775
        }
-
 
776
 
758
 
777
        // Step 3: Merge all PDFs
759
        if (orderId != null) {
-
 
760
            List<InvoicePdfModel> pdfModels = this.modelsForOrder(fofoDetails, orderId);
778
        byte[] mergedPdf;
761
            return this.invoicePdfResponse(pdfModels,
-
 
762
                    "invoice-" + pdfModels.get(0).getInvoiceNumber() + ".pdf", withPolicies);
779
        try {
763
        }
-
 
764
        if (partnerId != null) {
-
 
765
            return this.invoicePdfResponse(this.modelsForPartner(fofoDetails, partnerId, startDate, endDate),
780
            mergedPdf = PdfUtils.mergePdfFiles(pdfFiles);
766
                    "invoice-" + partnerId + ".pdf", withPolicies);
781
        } catch (Exception e) {
767
        }
782
            LOGGER.error("Error merging PDFs", e);
768
        return this.invoicePdfResponse(
783
            throw new ProfitMandiBusinessException("Failed to generate merged PDF", "", "");
769
                this.modelsForSearch(fofoDetails, searchType, searchValue, startTime, endTime, offset),
-
 
770
                "invoices.pdf", withPolicies);
784
        }
771
    }
785
 
772
 
-
 
773
    /** One invoice. An admin can pull any partner's; a partner is pinned to their own store. */
786
        // Step 4: Return merged PDF as response
774
    private List<InvoicePdfModel> modelsForOrder(LoginDetails fofoDetails, int orderId)
787
        HttpHeaders headers = new HttpHeaders();
775
            throws ProfitMandiBusinessException {
788
        headers.setContentType(MediaType.APPLICATION_PDF);
776
        return Arrays.asList(roleManager.isAdmin(fofoDetails.getRoleIds())
789
        headers.setContentDispositionFormData("inline", "invoice-with-policies-" + pdfModel.getInvoiceNumber() + ".pdf");
777
                ? orderService.getInvoicePdfModel(orderId)
790
        headers.setContentLength(mergedPdf.length);
778
                : orderService.getInvoicePdfModel(fofoDetails.getFofoId(), orderId));
-
 
779
    }
791
 
780
 
-
 
781
    /** Every invoice one partner raised in a window. Admin-only, since it reads across stores. */
-
 
782
    private List<InvoicePdfModel> modelsForPartner(LoginDetails fofoDetails, int partnerId,
792
        InputStreamResource resource = new InputStreamResource(new ByteArrayInputStream(mergedPdf));
783
                                                   LocalDateTime startDate, LocalDateTime endDate)
-
 
784
            throws ProfitMandiBusinessException {
793
        return new ResponseEntity<>(resource, headers, HttpStatus.OK);
785
        if (!roleManager.isAdmin(fofoDetails.getRoleIds())) {
-
 
786
            throw new ProfitMandiBusinessException("Auth", fofoDetails.getEmailId(), "Unauthorised access");
-
 
787
        }
-
 
788
        return this.toPdfModels(fofoOrderRepository.selectByFofoId(partnerId, startDate, endDate, 0, 0));
794
    }
789
    }
795
 
790
 
796
   /* @RequestMapping(value = "/generateInvoice")
791
    /** The caller's own sale history, re-running the search the listing screen was showing. */
797
    public ResponseEntity<?> generateInvoice(HttpServletRequest request, HttpServletResponse response,
792
    private List<InvoicePdfModel> modelsForSearch(LoginDetails fofoDetails, SearchType searchType, String searchValue,
798
                                             @RequestParam(name = ProfitMandiConstants.ORDER_ID) int orderId, @RequestParam(required = false) PrinterType printerType) throws ProfitMandiBusinessException {
793
                                                  LocalDateTime startTime, LocalDateTime endTime, int offset)
799
        LOGGER.info("Request received at url {} with params [{}={}] ", request.getRequestURI(),
-
 
800
                ProfitMandiConstants.ORDER_ID, orderId);
794
            throws ProfitMandiBusinessException {
801
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
795
        Map<String, Object> map = orderService.getSaleHistory(fofoDetails.getFofoId(), searchType, searchValue,
802
        InvoicePdfModel pdfModel = null;
-
 
803
        int fofoId;
-
 
804
        if (roleManager.isAdmin(fofoDetails.getRoleIds())) {
796
                startTime, endTime, offset, SALE_HISTORY_DOWNLOAD_LIMIT);
805
            pdfModel = orderService.getInvoicePdfModel(orderId);
797
        List<FofoOrder> fofoOrders = (List<FofoOrder>) map.get("saleHistories");
806
            fofoId = pdfModel.getCustomer().getCustomerId();
798
        if (fofoOrders == null || fofoOrders.isEmpty()) {
807
        } else {
-
 
808
            pdfModel = orderService.getInvoicePdfModel(fofoDetails.getFofoId(), orderId);
799
            throw new ProfitMandiBusinessException("Search criteria", "", "No orders found for criteria");
809
            fofoId = fofoDetails.getFofoId();
-
 
810
        }
800
        }
-
 
801
        return this.toPdfModels(fofoOrders);
-
 
802
    }
811
 
803
 
-
 
804
    /**
-
 
805
     * Builds one model per order, skipping any that fail. A single unbillable order should not cost
-
 
806
     * the operator the whole batch, so the failure is logged and the rest still download.
-
 
807
     */
-
 
808
    private List<InvoicePdfModel> toPdfModels(List<FofoOrder> fofoOrders) {
-
 
809
        List<InvoicePdfModel> pdfModels = new ArrayList<>();
-
 
810
        for (FofoOrder fofoOrder : fofoOrders) {
-
 
811
            try {
-
 
812
                pdfModels.add(orderService.getInvoicePdfModel(fofoOrder.getId()));
812
        if (printerType == null) {
813
            } catch (Exception e) {
813
            FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
814
                LOGGER.info("could not create invoice for {}, invoice number {}", fofoOrder.getId(),
814
            //printerType = fs.getPrinterType();
815
                        fofoOrder.getInvoiceNumber());
-
 
816
            }
815
        }
817
        }
-
 
818
        return pdfModels;
-
 
819
    }
816
 
820
 
-
 
821
    /** Renders the invoices, optionally staples the policy certificates, and sends the PDF inline. */
-
 
822
    private ResponseEntity<?> invoicePdfResponse(List<InvoicePdfModel> pdfModels, String fileName,
-
 
823
                                                 boolean withPolicies) throws ProfitMandiBusinessException {
-
 
824
        ByteArrayOutputStream invoiceOutput = new ByteArrayOutputStream();
-
 
825
        PdfUtils.generateAndWrite(pdfModels, invoiceOutput);
817
 
826
 
-
 
827
        byte[] pdf = invoiceOutput.toByteArray();
-
 
828
        if (withPolicies) {
818
        FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(orderId);
829
            pdf = this.appendPolicyCertificates(pdf, pdfModels);
-
 
830
        }
819
        List<InsurancePolicy> insurancePolicies = insurancePolicyRepository.selectByRetailerIdInvoiceNumber(fofoOrder.getInvoiceNumber());
831
        LOGGER.info("Pdf stream length {} for {} invoice(s)", pdf.length, pdfModels.size());
820
 
832
 
821
        // Step 1: Generate invoice PDF
833
        HttpHeaders headers = new HttpHeaders();
-
 
834
        headers.setContentType(MediaType.APPLICATION_PDF);
822
        ByteArrayOutputStream invoiceOutput = new ByteArrayOutputStream();
835
        headers.set("Content-disposition", "inline; filename=" + fileName);
-
 
836
        headers.setContentLength(pdf.length);
-
 
837
        return new ResponseEntity<>(new InputStreamResource(new ByteArrayInputStream(pdf)), headers, HttpStatus.OK);
-
 
838
    }
823
 
839
 
-
 
840
    /**
-
 
841
     * Staples the policy certificates for these invoices onto the end of the rendered PDF. Only one
824
        PdfUtils.generateAndWrite(Arrays.asList(pdfModel), printerType, invoiceOutput);
842
     * provider's certificates are held on disk, so the lookup filters on it in a single query; a
-
 
843
     * missing or unreadable file is logged and skipped rather than failing the download, since the
-
 
844
     * invoice itself is still the document being asked for.
-
 
845
     */
-
 
846
    private byte[] appendPolicyCertificates(byte[] invoicePdf, List<InvoicePdfModel> pdfModels)
-
 
847
            throws ProfitMandiBusinessException {
825
        byte[] invoicePdf = invoiceOutput.toByteArray();
848
        List<String> invoiceNumbers = new ArrayList<>();
-
 
849
        for (InvoicePdfModel pdfModel : pdfModels) {
-
 
850
            invoiceNumbers.add(pdfModel.getInvoiceNumber());
-
 
851
        }
826
 
852
 
827
        // Step 2: Load all policy certificate PDFs
-
 
828
        List<byte[]> pdfFiles = new ArrayList<>();
853
        List<byte[]> pdfFiles = new ArrayList<>();
829
        pdfFiles.add(invoicePdf); // first add invoice
854
        pdfFiles.add(invoicePdf);
830
 
-
 
831
        for (InsurancePolicy insurancePolicy : insurancePolicies) {
855
        for (InsurancePolicy insurancePolicy : insurancePolicyRepository
832
            if (insurancePolicy.getProviderId() == 6) {
856
                .selectByInvoiceNumbersAndProviderId(invoiceNumbers, CERTIFICATE_PROVIDER_ID)) {
833
                String policyNumber = insurancePolicy.getPolicyNumber();
857
            Path certificate = iciciLombardService.policyCertificatePath(insurancePolicy.getPolicyNumber());
834
                String safePolicyNo = policyNumber.replace("/", "-");
858
            if (!Files.exists(certificate)) {
835
                String filePath = "/uploads/policy-certificate-" + safePolicyNo + ".pdf";
859
                LOGGER.warn("Policy PDF not found: {}", certificate);
836
                File file = new File(filePath);
860
                continue;
837
 
-
 
838
                if (file.exists()) {
861
            }
839
                    try {
862
            try {
840
                        byte[] policyPdf = Files.readAllBytes(file.toPath());
863
                pdfFiles.add(Files.readAllBytes(certificate));
841
                        pdfFiles.add(policyPdf);
-
 
842
                    } catch (IOException e) {
864
            } catch (IOException e) {
843
                        LOGGER.error("Failed to read policy PDF: {}", filePath, e);
865
                LOGGER.error("Failed to read policy PDF: {}", certificate, e);
844
                    }
-
 
845
                } else {
-
 
846
                    LOGGER.warn("Policy PDF not found: {}", filePath);
-
 
847
                }
-
 
848
            }
866
            }
849
 
-
 
850
        }
867
        }
851
 
868
 
852
        // Step 3: Merge all PDFs
869
        if (pdfFiles.size() == 1) {
853
        byte[] mergedPdf;
870
            return invoicePdf;
-
 
871
        }
854
        try {
872
        try {
855
            mergedPdf = PdfUtils.mergePdfFiles(pdfFiles);
873
            return PdfUtils.mergePdfFiles(pdfFiles);
856
        } catch (Exception e) {
874
        } catch (Exception e) {
857
            LOGGER.error("Error merging PDFs", e);
875
            LOGGER.error("Error merging PDFs", e);
858
            throw new ProfitMandiBusinessException("Failed to generate merged PDF", "", "");
876
            throw new ProfitMandiBusinessException("Failed to generate merged PDF", "", "");
859
        }
877
        }
-
 
878
    }
860
 
879
 
861
        // Step 4: Return merged PDF as response
880
    /** @deprecated superseded by {@link #downloadInvoice}; kept so older pages keep working. */
-
 
881
    @Deprecated
862
        HttpHeaders headers = new HttpHeaders();
882
    @RequestMapping(value = "/generateInvoice")
863
        headers.setContentType(MediaType.APPLICATION_PDF);
883
    public ResponseEntity<?> generateInvoice(HttpServletRequest request, HttpServletResponse response,
864
        headers.setContentDispositionFormData("inline", "invoice-with-policies-" + pdfModel.getInvoiceNumber() + ".pdf");
884
                                             @RequestParam(name = ProfitMandiConstants.ORDER_ID) int orderId) throws ProfitMandiBusinessException {
865
        headers.setContentLength(mergedPdf.length);
885
        return this.downloadInvoice(request, orderId, null, null, null, "", null, null, null, 0, true);
-
 
886
    }
866
 
887
 
867
        InputStreamResource resource = new InputStreamResource(new ByteArrayInputStream(mergedPdf));
-
 
868
        return new ResponseEntity<>(resource, headers, HttpStatus.OK);
-
 
869
    }*/
-
 
870
 
888
 
-
 
889
    /** @deprecated superseded by {@link #downloadInvoice}; kept so older pages keep working. */
-
 
890
    @Deprecated
871
    @RequestMapping(value = "/generateInvoices")
891
    @RequestMapping(value = "/generateInvoices")
872
    public ResponseEntity<?> generateInvoice(HttpServletRequest request, HttpServletResponse response,
892
    public ResponseEntity<?> generateInvoice(HttpServletRequest request, HttpServletResponse response,
873
                                             @RequestParam LocalDateTime startDate, @RequestParam LocalDateTime endDate, @RequestParam int partnerId)
893
                                             @RequestParam LocalDateTime startDate, @RequestParam LocalDateTime endDate, @RequestParam int partnerId)
874
            throws ProfitMandiBusinessException {
894
            throws ProfitMandiBusinessException {
875
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
-
 
876
        List<InvoicePdfModel> pdfModels = new ArrayList<>();
-
 
877
        if (roleManager.isAdmin(fofoDetails.getRoleIds())) {
-
 
878
            List<Integer> orderIds = fofoOrderRepository.selectByFofoId(partnerId, startDate, endDate, 0, 0).stream()
895
        return this.downloadInvoice(request, null, partnerId, startDate, endDate, "", null, null, null, 0, true);
879
                    .map(x -> x.getId()).collect(Collectors.toList());
-
 
880
            for (int orderId : orderIds) {
-
 
881
                pdfModels.add(orderService.getInvoicePdfModel(orderId));
-
 
882
            }
-
 
883
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
-
 
884
            PdfUtils.generateAndWrite(pdfModels, byteArrayOutputStream);
-
 
885
            LOGGER.info("Pdf Stream length {}", byteArrayOutputStream.toByteArray().length);
-
 
886
            final HttpHeaders headers = new HttpHeaders();
-
 
887
            headers.setContentType(MediaType.APPLICATION_PDF);
-
 
888
            headers.set("Content-disposition", "inline; filename=invoice-" + partnerId + ".pdf");
-
 
889
            headers.setContentLength(byteArrayOutputStream.toByteArray().length);
-
 
890
            final InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
-
 
891
            final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
-
 
892
            return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
-
 
893
        } else {
-
 
894
            throw new ProfitMandiBusinessException("Auth", fofoDetails.getEmailId(), "Unauthorised access");
-
 
895
        }
-
 
896
    }
896
    }
897
 
897
 
898
    @RequestMapping(value = "/saleHistory")
898
    @RequestMapping(value = "/saleHistory")
899
    public String saleHistory(HttpServletRequest request,
899
    public String saleHistory(HttpServletRequest request,
900
                              @RequestParam(name = "searchValue", defaultValue = "") String searchValue,
900
                              @RequestParam(name = "searchValue", defaultValue = "") String searchValue,
Line 910... Line 910...
910
                startTime, endTime, offset, limit);
910
                startTime, endTime, offset, limit);
911
        model.addAllAttributes(map);
911
        model.addAllAttributes(map);
912
        return "sale-history";
912
        return "sale-history";
913
    }
913
    }
914
 
914
 
-
 
915
    /** @deprecated superseded by {@link #downloadInvoice}; kept so older pages keep working. */
-
 
916
    @Deprecated
915
    @RequestMapping(value = "/downloadInvoices")
917
    @RequestMapping(value = "/downloadInvoices")
916
    public ResponseEntity<?> downloadInvoices(HttpServletRequest request,
918
    public ResponseEntity<?> downloadInvoices(HttpServletRequest request,
917
                                              @RequestParam(name = "searchValue", defaultValue = "") String searchValue,
919
                                              @RequestParam(name = "searchValue", defaultValue = "") String searchValue,
918
                                              @RequestParam(name = "searchType", defaultValue = "") SearchType searchType,
920
                                              @RequestParam(name = "searchType", defaultValue = "") SearchType searchType,
919
                                              @RequestParam(required = false) LocalDateTime startTime,
921
                                              @RequestParam(required = false) LocalDateTime startTime,
920
                                              @RequestParam(required = false) LocalDateTime endTime,
922
                                              @RequestParam(required = false) LocalDateTime endTime,
921
                                              @RequestParam(name = "offset", defaultValue = "0") int offset,
923
                                              @RequestParam(name = "offset", defaultValue = "0") int offset,
922
                                              @RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
924
                                              @RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
923
            throws ProfitMandiBusinessException {
925
            throws ProfitMandiBusinessException {
924
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
-
 
925
 
-
 
926
        Map<String, Object> map = orderService.getSaleHistory(loginDetails.getFofoId(), searchType, searchValue,
926
        return this.downloadInvoice(request, null, null, null, null, searchValue, searchType, startTime, endTime,
927
                startTime, endTime, offset, 100);
-
 
928
        List<FofoOrder> fofoOrders = (List<FofoOrder>) map.get("saleHistories");
-
 
929
 
-
 
930
        if (fofoOrders.size() == 0) {
-
 
931
            throw new ProfitMandiBusinessException("Search criteria", "", "No orders found for criteria");
-
 
932
        }
-
 
933
 
-
 
934
        final HttpHeaders headers = new HttpHeaders();
-
 
935
        headers.setContentType(MediaType.APPLICATION_PDF);
-
 
936
        headers.set("Content-disposition", "inline; filename=invoices.pdf");
-
 
937
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
-
 
938
        List<InvoicePdfModel> pdfModels = new ArrayList<>();
-
 
939
        for (FofoOrder fofoOrder : fofoOrders) {
-
 
940
            try {
-
 
941
                pdfModels.add(orderService.getInvoicePdfModel(fofoOrder.getId()));
-
 
942
            } catch (Exception e) {
927
                offset, true);
943
                LOGGER.info("could not create invoice for {}, invoice number {}", fofoOrder.getId(),
-
 
944
                        fofoOrder.getInvoiceNumber());
-
 
945
            }
-
 
946
        }
-
 
947
        PdfUtils.generateAndWrite(pdfModels, byteArrayOutputStream);
-
 
948
        headers.setContentLength(byteArrayOutputStream.toByteArray().length);
-
 
949
        final InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
-
 
950
        final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
-
 
951
        return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
-
 
952
    }
928
    }
953
 
929
 
954
    @RequestMapping(value = "/credit-note/{creditNoteId}")
930
    @RequestMapping(value = "/credit-note/{creditNoteId}")
955
    public ResponseEntity<?> downloadCreditNote(HttpServletRequest request, @PathVariable int creditNoteId)
931
    public ResponseEntity<?> downloadCreditNote(HttpServletRequest request, @PathVariable int creditNoteId)
956
            throws ProfitMandiBusinessException {
932
            throws ProfitMandiBusinessException {