From 4e9f2f18aa6d4e4efe11645e251b713869fa9746 Mon Sep 17 00:00:00 2001
From: gongchunyi <deslre0381@gmail.com>
Date: 星期四, 12 二月 2026 14:08:59 +0800
Subject: [PATCH] fix: 修改来票登记时计算来票登记表的总金额错误

---
 src/main/java/com/ruoyi/sales/controller/SalesLedgerController.java |  220 +++++++++++++++++++++++++++++++++++++-----------------
 1 files changed, 151 insertions(+), 69 deletions(-)

diff --git a/src/main/java/com/ruoyi/sales/controller/SalesLedgerController.java b/src/main/java/com/ruoyi/sales/controller/SalesLedgerController.java
index c384520..cbef46f 100644
--- a/src/main/java/com/ruoyi/sales/controller/SalesLedgerController.java
+++ b/src/main/java/com/ruoyi/sales/controller/SalesLedgerController.java
@@ -9,29 +9,34 @@
 import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
 import com.ruoyi.framework.web.controller.BaseController;
 import com.ruoyi.framework.web.domain.AjaxResult;
+import com.ruoyi.framework.web.domain.R;
 import com.ruoyi.framework.web.page.TableDataInfo;
 import com.ruoyi.sales.dto.InvoiceLedgerDto;
 import com.ruoyi.sales.dto.SalesLedgerDto;
 import com.ruoyi.sales.mapper.InvoiceLedgerMapper;
-import com.ruoyi.sales.mapper.InvoiceRegistrationProductMapper;
 import com.ruoyi.sales.mapper.ReceiptPaymentMapper;
-import com.ruoyi.sales.pojo.InvoiceLedger;
-import com.ruoyi.sales.pojo.InvoiceRegistrationProduct;
 import com.ruoyi.sales.pojo.ReceiptPayment;
 import com.ruoyi.sales.pojo.SalesLedger;
 import com.ruoyi.sales.service.ICommonFileService;
 import com.ruoyi.sales.service.ISalesLedgerService;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import io.swagger.annotations.ApiParam;
 import lombok.AllArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.util.CollectionUtils;
 import org.springframework.web.bind.annotation.*;
+import org.springframework.web.multipart.MultipartFile;
 
 import javax.servlet.http.HttpServletResponse;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
 import java.math.BigDecimal;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-import java.util.Objects;
+import java.net.URLEncoder;
+import java.util.*;
 import java.util.stream.Collectors;
 
 /**
@@ -43,6 +48,8 @@
 @RestController
 @RequestMapping("/sales/ledger")
 @AllArgsConstructor
+@Api(tags = "閿�鍞彴璐�")
+@Slf4j
 public class SalesLedgerController extends BaseController {
 
     private ISalesLedgerService salesLedgerService;
@@ -53,10 +60,57 @@
     private InvoiceLedgerMapper invoiceLedgerMapper;
 
     @Autowired
-    private InvoiceRegistrationProductMapper invoiceRegistrationProductMapper;
-
-    @Autowired
     private ReceiptPaymentMapper receiptPaymentMapper;
+
+    /**
+     * 瀵煎叆閿�鍞彴璐�
+     */
+    @Log(title = "瀵煎叆閿�鍞彴璐�", businessType = BusinessType.INSERT)
+    @PostMapping("/import")
+    @ApiOperation("瀵煎叆閿�鍞彴璐�")
+    public AjaxResult importData(@RequestParam("file")
+                                 @ApiParam(value = "Excel鏂囦欢", required = true)
+                                 MultipartFile file) {
+        return salesLedgerService.importData(file);
+    }
+
+    @ApiOperation("瀵煎嚭閿�鍞彴璐︽ā鏉�")
+    @PostMapping("/exportTemplate")
+    public void exportTemplate(HttpServletResponse response) {
+        // 1. 妯℃澘鏂囦欢鍦╮esources/static涓嬬殑璺緞
+        String templatePath = "static/閿�鍞彴璐﹀鍏ユā鏉�.xlsx";
+
+        // 2. 鑾峰彇妯℃澘鏂囦欢鐨勮緭鍏ユ祦
+        try (InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(templatePath)) {
+            if (inputStream == null) {
+                throw new FileNotFoundException("妯℃澘鏂囦欢涓嶅瓨鍦細" + templatePath);
+            }
+
+            // 3. 璁剧疆鍝嶅簲澶达紝瑙﹀彂娴忚鍣ㄤ笅杞�
+            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
+            response.setCharacterEncoding("utf-8");
+            String fileName = URLEncoder.encode("閿�鍞彴璐﹀鍏ユā鏉�.xlsx", "utf-8").replaceAll("\\+", "%20");
+            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName);
+
+            // 4. 灏嗘ā鏉挎枃浠跺啓鍏ュ搷搴旇緭鍑烘祦
+            try (OutputStream outputStream = response.getOutputStream()) {
+                byte[] buffer = new byte[1024];
+                int len;
+                while ((len = inputStream.read(buffer)) > 0) {
+                    outputStream.write(buffer, 0, len);
+                }
+                outputStream.flush();
+            }
+        } catch (IOException e) {
+            log.error("瀵煎嚭閿�鍞彴璐︽ā鏉垮け璐�", e);
+            // 鑻ユā鏉挎枃浠惰鍙栧け璐ワ紝杩斿洖閿欒鎻愮ず
+            try {
+                response.getWriter().write("妯℃澘瀵煎嚭澶辫触锛�" + e.getMessage());
+            } catch (IOException ex) {
+                log.error("鍝嶅簲杈撳嚭閿欒", ex);
+            }
+        }
+    }
 
     /**
      * 鏌ヨ閿�鍞彴璐﹀垪琛�
@@ -100,8 +154,14 @@
     @Log(title = "閿�鍞彴璐�", businessType = BusinessType.EXPORT)
     @PostMapping("/export")
     public void export(HttpServletResponse response, SalesLedgerDto salesLedgerDto) {
-        List<SalesLedger> list = salesLedgerService.selectSalesLedgerList(salesLedgerDto);
+        Page page = new Page(-1,-1);
+        IPage<SalesLedger> salesLedgerIPage = listPage(page, salesLedgerDto);
         ExcelUtil<SalesLedger> util = new ExcelUtil<SalesLedger>(SalesLedger.class);
+        if(salesLedgerIPage == null){
+            util.exportExcel(response, new ArrayList<>(), "閿�鍞彴璐︽暟鎹�");
+            return;
+        }
+        List<SalesLedger> list = salesLedgerIPage.getRecords();
         util.exportExcel(response, list, "閿�鍞彴璐︽暟鎹�");
     }
 
@@ -198,73 +258,95 @@
      */
     @GetMapping("/listPage")
     public IPage<SalesLedger> listPage(Page page, SalesLedgerDto salesLedgerDto) {
-        IPage<SalesLedger> iPage = salesLedgerService.selectSalesLedgerListPage(page,salesLedgerDto);
-        // 璁$畻宸插紑绁ㄩ噾棰�/鏈紑绁ㄩ噾棰�(宸插~鍐欏彂绁ㄩ噾棰濅负鍑�)
-        if(CollectionUtils.isEmpty(iPage.getRecords())){
-            return iPage;
-        }
-        List<Long> salesLedgerIds = iPage.getRecords().stream().map(SalesLedger::getId).collect(Collectors.toList());
-        List<InvoiceLedgerDto> invoiceLedgerDtoList = invoiceLedgerMapper.invoicedTotal(salesLedgerIds);
-        if(CollectionUtils.isEmpty(invoiceLedgerDtoList)){
-            iPage.setTotal(iPage.getRecords().size());
-            return iPage;
-        }
-        // 璁$畻鍥炴閲戦锛屽緟鍥炴閲戦
-        List<InvoiceRegistrationProduct> invoiceRegistrationProducts = invoiceRegistrationProductMapper.selectList(new LambdaQueryWrapper<InvoiceRegistrationProduct>()
-                .in(InvoiceRegistrationProduct::getSalesLedgerId, salesLedgerIds));
+        IPage<SalesLedger> iPage = salesLedgerService.selectSalesLedgerListPage(page, salesLedgerDto);
 
-        List<InvoiceLedger> invoiceLedgers = invoiceLedgerMapper.selectList(new LambdaQueryWrapper<InvoiceLedger>()
-                .in(InvoiceLedger::getInvoiceRegistrationProductId, invoiceRegistrationProducts.stream().map(InvoiceRegistrationProduct::getId).collect(Collectors.toList())));
-        List<ReceiptPayment> receiptPayments = new ArrayList<>();
-        if(!CollectionUtils.isEmpty(invoiceLedgers)){
-            receiptPayments = receiptPaymentMapper.selectList(new LambdaQueryWrapper<ReceiptPayment>()
-                    .in(ReceiptPayment::getInvoiceLedgerId, invoiceLedgers.stream().map(InvoiceLedger::getId).collect(Collectors.toList())));
+        //  鏌ヨ缁撴灉涓虹┖,鐩存帴杩斿洖
+        if (CollectionUtils.isEmpty(iPage.getRecords())) {
+            return iPage;
         }
-        for (SalesLedger salesLedger : iPage.getRecords()) {
-            boolean existFlag = false;
-            BigDecimal noInvoiceAmountTotal = BigDecimal.ZERO;
-            BigDecimal invoiceTotal = BigDecimal.ZERO;
-            for (InvoiceLedgerDto invoiceLedgerDto : invoiceLedgerDtoList) {
-                if (salesLedger.getId().intValue() == invoiceLedgerDto.getSalesLedgerId()) {
-                    noInvoiceAmountTotal = salesLedger.getContractAmount().subtract(invoiceLedgerDto.getInvoiceTotal());
-                    invoiceTotal = invoiceLedgerDto.getInvoiceTotal();
-                    existFlag = true;
-                    if(!CollectionUtils.isEmpty(receiptPayments)){
-                        List<InvoiceRegistrationProduct> collect = invoiceRegistrationProducts.stream()
-                                .filter(item -> salesLedger.getId().equals(Long.parseLong(item.getSalesLedgerId().toString())))
-                                .collect(Collectors.toList());
-                        List<Integer> collect1 = collect.stream()
-                                .map(InvoiceRegistrationProduct::getId).collect(Collectors.toList());
-                        List<InvoiceLedger> collect2 = invoiceLedgers.stream()
-                                .filter(item -> collect1.contains(item.getInvoiceRegistrationProductId()))
-                                .collect(Collectors.toList());
-                        // 鑾峰彇宸插洖娆鹃噾棰�
-                        List<ReceiptPayment> collect3 = receiptPayments.stream()
-                                .filter(item -> collect2.stream().anyMatch(item1 -> item1.getId().equals(item.getInvoiceLedgerId())))
-                                .collect(Collectors.toList());
-                        BigDecimal receiptPaymentAmountTotal = collect3.stream().map(ReceiptPayment::getReceiptPaymentAmount)
-                                .filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
-                        // 鑾峰彇寰呭洖娆鹃噾棰�
-                        BigDecimal noReceiptPaymentAmountTotal = invoiceLedgerDto.getInvoiceTotal().subtract(receiptPaymentAmountTotal);
-                        salesLedger.setReceiptPaymentAmountTotal(receiptPaymentAmountTotal);
-                        salesLedger.setNoReceiptAmount(noReceiptPaymentAmountTotal);
-                    }
-                    break;
+
+        //  鑾峰彇褰撳墠椤垫墍鏈夊彴璐﹁褰曠殑 ID 闆嗗悎
+        List<Long> salesLedgerIds = iPage.getRecords().stream().map(SalesLedger::getId).collect(Collectors.toList());
+
+        //  鏌ヨ鍙戠エ淇℃伅鐨勫凡寮�绁ㄩ噾棰�
+        List<InvoiceLedgerDto> invoiceLedgerDtoList = invoiceLedgerMapper.invoicedTotal(salesLedgerIds);
+        if (CollectionUtils.isEmpty(invoiceLedgerDtoList)) {
+            invoiceLedgerDtoList = Collections.emptyList();
+        }
+
+        //  杞崲鍙戠エ鏁版嵁, key 涓哄彴璐D, value 涓鸿鍙拌处鐨勬�诲紑绁ㄩ噾棰�
+        Map<Long, BigDecimal> invoiceTotals = invoiceLedgerDtoList.stream()
+                .filter(dto -> dto.getSalesLedgerId() != null && dto.getInvoiceTotal() != null)
+                .collect(Collectors.toMap(
+                        dto -> dto.getSalesLedgerId().longValue(),
+                        InvoiceLedgerDto::getInvoiceTotal,
+                        BigDecimal::add // 瀛樺湪閲嶅ID鎵ц绱姞
+                ));
+
+        //  鏌ヨ鍥炴/浠樻璁板綍
+        List<ReceiptPayment> receiptPayments = Collections.emptyList();
+        if (!CollectionUtils.isEmpty(salesLedgerIds)) {
+            receiptPayments = receiptPaymentMapper.selectList(new LambdaQueryWrapper<ReceiptPayment>()
+                    .in(ReceiptPayment::getSalesLedgerId, salesLedgerIds));
+        }
+
+        //  杞崲鍥炴鏁版嵁, key 涓哄彴璐D, value 涓鸿鍙拌处鐨勬�诲洖娆鹃噾棰�
+        Map<Long, BigDecimal> receiptTotals = new HashMap<>();
+        if (!CollectionUtils.isEmpty(receiptPayments)) {
+            for (ReceiptPayment receiptPayment : receiptPayments) {
+                if (receiptPayment.getSalesLedgerId() != null && receiptPayment.getReceiptPaymentAmount() != null) {
+                    //  濡傛灉 key 瀛樺湪鍒欑浉鍔�,涓嶅瓨鍦ㄥ垯鏀惧叆
+                    receiptTotals.merge(receiptPayment.getSalesLedgerId(), receiptPayment.getReceiptPaymentAmount(), BigDecimal::add);
                 }
             }
-            if(existFlag){
-                salesLedger.setNoInvoiceAmountTotal(noInvoiceAmountTotal);
-            }else {
-                salesLedger.setNoInvoiceAmountTotal(salesLedger.getContractAmount());
-            }
-            salesLedger.setInvoiceTotal(invoiceTotal);
         }
+
+        for (SalesLedger salesLedger : iPage.getRecords()) {
+            Long ledgerId = salesLedger.getId();
+            // 鍚堝悓鎬婚噾棰�
+            BigDecimal contractAmount = salesLedger.getContractAmount() == null ? BigDecimal.ZERO : salesLedger.getContractAmount();
+            // 寮�绁ㄦ�婚鍜屽洖娆炬�婚
+            BigDecimal invoiceTotal = invoiceTotals.getOrDefault(ledgerId, BigDecimal.ZERO);
+            BigDecimal receiptPaymentAmountTotal = receiptTotals.getOrDefault(ledgerId, BigDecimal.ZERO);
+
+            //  鏈紑绁ㄩ噾棰� = 鍚堝悓閲戦 - 宸插紑绁ㄩ噾棰�
+            BigDecimal noInvoiceAmountTotal = contractAmount.subtract(invoiceTotal);
+            if (noInvoiceAmountTotal.compareTo(BigDecimal.ZERO) < 0) {
+                noInvoiceAmountTotal = BigDecimal.ZERO;
+            }
+
+            //  寰呭洖娆鹃噾棰� = 宸插紑绁ㄩ噾棰� - 宸插洖娆鹃噾棰�
+            BigDecimal noReceiptPaymentAmountTotal = invoiceTotal.subtract(receiptPaymentAmountTotal);
+            if (noReceiptPaymentAmountTotal.compareTo(BigDecimal.ZERO) < 0) {
+                noReceiptPaymentAmountTotal = BigDecimal.ZERO;
+            }
+
+            salesLedger.setNoInvoiceAmountTotal(noInvoiceAmountTotal);
+            salesLedger.setInvoiceTotal(invoiceTotal);
+            salesLedger.setReceiptPaymentAmountTotal(receiptPaymentAmountTotal);
+            salesLedger.setNoReceiptAmount(noReceiptPaymentAmountTotal);
+
+            //  濡傛灉宸茬粡鏈夎繃寮�绁ㄦ垨鍥炴鎿嶄綔,鍒欎笉鍏佽缂栬緫
+            boolean hasInvoiceOperation = invoiceTotal.compareTo(BigDecimal.ZERO) > 0;
+            boolean hasReceiptOperation = receiptPaymentAmountTotal.compareTo(BigDecimal.ZERO) > 0;
+            salesLedger.setIsEdit(!(hasInvoiceOperation || hasReceiptOperation));
+        }
+
         if (ObjectUtils.isNotEmpty(salesLedgerDto.getStatus())) {
             if (salesLedgerDto.getStatus()) {
-                iPage.getRecords().removeIf(salesLedger -> Objects.equals(salesLedger.getNoInvoiceAmountTotal(), new BigDecimal("0.00")));
+                // 娓呴櫎鎵�鏈夆�滄湭寮�绁ㄩ噾棰濃�濅负 0 鐨勮褰�
+                iPage.getRecords().removeIf(salesLedger ->
+                        Objects.equals(salesLedger.getNoInvoiceAmountTotal(), new BigDecimal("0.00")));
+                iPage.setTotal(iPage.getRecords().size());
             }
         }
-        iPage.setTotal(iPage.getRecords().size());
+
         return iPage;
     }
+
+    @ApiOperation("鏌ヨ閿�鍞彴璐︽秷鑰楃墿鏂欎俊鎭�")
+    @GetMapping("/getSalesLedgerWithProductsLoss")
+    public R getSalesLedgerWithProductsLoss(Long salesLedgerId) {
+        return R.ok(salesLedgerService.getSalesLedgerWithProductsLoss(salesLedgerId));
+    }
 }

--
Gitblit v1.9.3