From 684e4306a08feeae188070f264148e6765da8dcf Mon Sep 17 00:00:00 2001
From: 云 <2163098428@qq.com>
Date: 星期日, 20 九月 2026 19:25:15 +0800
Subject: [PATCH] feat(account): 更新往来付款回款流水表及接口

---
 src/main/java/com/ruoyi/sales/service/impl/SalesLedgerServiceImpl.java |  367 ++++++++++++++++++++++++++++++++++++----------------
 1 files changed, 254 insertions(+), 113 deletions(-)

diff --git a/src/main/java/com/ruoyi/sales/service/impl/SalesLedgerServiceImpl.java b/src/main/java/com/ruoyi/sales/service/impl/SalesLedgerServiceImpl.java
index 05b1ea7..07ab3af 100644
--- a/src/main/java/com/ruoyi/sales/service/impl/SalesLedgerServiceImpl.java
+++ b/src/main/java/com/ruoyi/sales/service/impl/SalesLedgerServiceImpl.java
@@ -1,7 +1,6 @@
 package com.ruoyi.sales.service.impl;
 
 import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
-import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
 import com.baomidou.mybatisplus.core.mapper.BaseMapper;
 import com.baomidou.mybatisplus.core.metadata.IPage;
 import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
@@ -9,16 +8,30 @@
 import com.baomidou.mybatisplus.core.toolkit.Wrappers;
 import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
 import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
-import com.ruoyi.account.service.AccountIncomeService;
+import com.ruoyi.account.mapper.sales.AccountInvoiceApplicationMapper;
+import com.ruoyi.account.mapper.sales.AccountSalesCollectionMapper;
+import com.ruoyi.account.pojo.sales.AccountInvoiceApplication;
+import com.ruoyi.account.pojo.sales.AccountSalesCollection;
+import com.ruoyi.approve.bean.dto.ApprovalInstanceDto;
+import com.ruoyi.approve.mapper.ApprovalTemplateMapper;
+import com.ruoyi.approve.pojo.ApprovalInstance;
+import com.ruoyi.approve.pojo.ApprovalTemplate;
+import com.ruoyi.approve.service.ApprovalInstanceService;
 import com.ruoyi.basic.enums.ApplicationTypeEnum;
 import com.ruoyi.basic.enums.RecordTypeEnum;
 import com.ruoyi.basic.mapper.CustomerMapper;
 import com.ruoyi.basic.mapper.ProductMapper;
 import com.ruoyi.basic.mapper.ProductModelMapper;
+import com.ruoyi.basic.mapper.OilDepotMapper;
+import com.ruoyi.basic.mapper.TankInfoMapper;
 import com.ruoyi.basic.pojo.Customer;
+import com.ruoyi.basic.pojo.OilDepot;
+import com.ruoyi.basic.pojo.TankInfo;
 import com.ruoyi.basic.utils.FileUtil;
 import com.ruoyi.common.enums.FileNameType;
 import com.ruoyi.common.enums.SaleEnum;
+import com.ruoyi.common.enums.SalesQuotationStatusEnum;
+import com.ruoyi.common.enums.TypeEnums;
 import com.ruoyi.common.exception.base.BaseException;
 import com.ruoyi.common.utils.DateUtils;
 import com.ruoyi.common.utils.EnumUtil;
@@ -28,24 +41,28 @@
 import com.ruoyi.framework.security.LoginUser;
 import com.ruoyi.framework.web.domain.AjaxResult;
 import com.ruoyi.other.mapper.TempFileMapper;
-import com.ruoyi.other.pojo.TempFile;
-import com.ruoyi.production.mapper.*;
+import com.ruoyi.production.mapper.ProductionProductInputMapper;
+import com.ruoyi.production.mapper.ProductionProductMainMapper;
+import com.ruoyi.production.mapper.ProductionProductOutputMapper;
 import com.ruoyi.production.service.ProductionProductMainService;
 import com.ruoyi.project.system.domain.SysDept;
 import com.ruoyi.project.system.domain.SysUser;
 import com.ruoyi.project.system.mapper.SysDeptMapper;
 import com.ruoyi.project.system.mapper.SysUserMapper;
-import com.ruoyi.purchase.dto.SimpleReturnOrderGroupDto;
-import com.ruoyi.purchase.mapper.PurchaseReturnOrderProductsMapper;
 import com.ruoyi.quality.mapper.QualityInspectMapper;
 import com.ruoyi.sales.dto.*;
-import com.ruoyi.sales.mapper.*;
-import com.ruoyi.sales.pojo.*;
+import com.ruoyi.sales.mapper.CommonFileMapper;
+import com.ruoyi.sales.mapper.SalesLedgerMapper;
+import com.ruoyi.sales.mapper.SalesLedgerProductMapper;
+import com.ruoyi.sales.mapper.ShippingInfoMapper;
+import com.ruoyi.sales.pojo.CommonFile;
+import com.ruoyi.sales.pojo.SalesLedger;
+import com.ruoyi.sales.pojo.SalesLedgerProduct;
+import com.ruoyi.sales.pojo.ShippingInfo;
 import com.ruoyi.sales.service.ISalesLedgerService;
 import com.ruoyi.sales.vo.SalesLedgerVo;
 import lombok.RequiredArgsConstructor;
 import lombok.extern.slf4j.Slf4j;
-import org.apache.commons.io.FilenameUtils;
 import org.jetbrains.annotations.Nullable;
 import org.springframework.beans.BeanUtils;
 import org.springframework.beans.factory.annotation.Autowired;
@@ -55,16 +72,12 @@
 import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Transactional;
 import org.springframework.web.multipart.MultipartFile;
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
 
-import java.io.IOException;
 import java.io.InputStream;
 import java.lang.reflect.Field;
 import java.math.BigDecimal;
 import java.math.RoundingMode;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.nio.file.StandardCopyOption;
 import java.time.LocalDate;
 import java.time.LocalDateTime;
 import java.time.YearMonth;
@@ -87,26 +100,31 @@
     private static final String LOCK_PREFIX = "contract_no_lock:";
     private static final long LOCK_WAIT_TIMEOUT = 10; // 閿佺瓑寰呰秴鏃舵椂闂达紙绉掞級
     private static final long LOCK_EXPIRE_TIME = 30;  // 閿佽嚜鍔ㄨ繃鏈熸椂闂达紙绉掞級
-    private final AccountIncomeService accountIncomeService;
+    /** 閿�鍞被鍨嬶細鍗栨补锛堣蛋浜у搧鏄庣粏锛� */
+    private static final String LEDGER_TYPE_OIL = "鍗栨补";
+    /** 閿�鍞被鍨嬶細浠e偍锛堝崠瀛樺偍浣嶇疆锛岃蛋娌瑰簱+鍌ㄧ綈+鎵嬪伐鍚堝悓閲戦锛� */
+    private static final String LEDGER_TYPE_DEPOSIT = "浠e偍";
     private final SalesLedgerMapper salesLedgerMapper;
     private final CustomerMapper customerMapper;
     private final SalesLedgerProductMapper salesLedgerProductMapper;
     private final SalesLedgerProductServiceImpl salesLedgerProductServiceImpl;
     private final CommonFileMapper commonFileMapper;
     private final TempFileMapper tempFileMapper;
-    private final ReceiptPaymentMapper receiptPaymentMapper;
     private final ShippingInfoServiceImpl shippingInfoServiceImpl;
     private final CommonFileServiceImpl commonFileService;
     private final ShippingInfoMapper shippingInfoMapper;
-    private final InvoiceLedgerMapper invoiceLedgerMapper;
-    private final InvoiceRegistrationProductMapper invoiceRegistrationProductMapper;
-    private final InvoiceRegistrationMapper invoiceRegistrationMapper;
     private final ProductionProductMainMapper productionProductMainMapper;
     private final ProductionProductOutputMapper productionProductOutputMapper;
     private final ProductionProductInputMapper productionProductInputMapper;
     private final QualityInspectMapper qualityInspectMapper;
     private final RedisTemplate<String, String> redisTemplate;
     private final FileUtil fileUtil;
+    private final AccountInvoiceApplicationMapper accountInvoiceApplicationMapper;
+    private final AccountSalesCollectionMapper accountSalesCollectionMapper;
+    private final ApprovalTemplateMapper approvalTemplateMapper;
+    private final ApprovalInstanceService approvalInstanceService;
+    private final OilDepotMapper oilDepotMapper;
+    private final TankInfoMapper tankInfoMapper;
 
     @Autowired
     private SysDeptMapper sysDeptMapper;
@@ -120,14 +138,13 @@
     @Autowired
     private ProductionProductMainService productionProductMainService;
     @Autowired
-    private PurchaseReturnOrderProductsMapper purchaseReturnOrderProductsMapper;
-    ;
-    @Autowired
     private SysUserMapper sysUserMapper;
 
     @Override
     public List<SalesLedger> selectSalesLedgerList(SalesLedgerDto salesLedgerDto) {
-        return salesLedgerMapper.selectSalesLedgerList(salesLedgerDto);
+        List<SalesLedger> list = salesLedgerMapper.selectSalesLedgerList(salesLedgerDto);
+        fillTrustFund(list);
+        return list;
     }
 
     public List<SalesLedgerProduct> getSalesLedgerProductListByRelateId(Long relateId, SaleEnum type) {
@@ -147,17 +164,11 @@
         productWrapper.eq(SalesLedgerProduct::getType, type.getCode());
         List<SalesLedgerProduct> salesLedgerProducts = salesLedgerProductMapper.selectList(productWrapper);
         if (type.equals(SaleEnum.PURCHASE)) {
-            // 鏌ヨ閫�璐т俊鎭�
-            List<Long> productIds = salesLedgerProducts.stream().map(SalesLedgerProduct::getProductModelId).collect(Collectors.toList());
-            List<SimpleReturnOrderGroupDto> groupListByProductIds = new ArrayList<>();
-            if(CollectionUtils.isNotEmpty(productIds)){
-                groupListByProductIds = purchaseReturnOrderProductsMapper.getReturnOrderGroupListByProductIds(productIds);
-            }
-            Map<Long, BigDecimal> returnOrderGroupDtoMap = groupListByProductIds.stream().collect(Collectors.toMap(SimpleReturnOrderGroupDto::getProductModelId, SimpleReturnOrderGroupDto::getSumReturnQuantity));
             salesLedgerProducts.forEach(item -> {
-                BigDecimal returnQuality = returnOrderGroupDtoMap.getOrDefault(item.getProductModelId(), BigDecimal.ZERO);
-                item.setReturnQuality(returnQuality);
-                item.setAvailableQuality(item.getQuantity().subtract(returnQuality));
+                BigDecimal returnQuantity = item.getReturnQuantity() == null ? BigDecimal.ZERO : item.getReturnQuantity();
+                item.setReturnQuantity(returnQuantity);
+                BigDecimal quantity = item.getQuantity() == null ? BigDecimal.ZERO : item.getQuantity();
+                item.setAvailableQuality(quantity.subtract(returnQuantity));
             });
         }
         return salesLedgerProducts;
@@ -177,10 +188,6 @@
         productWrapper.eq(SalesLedgerProduct::getType, 1);
         List<SalesLedgerProduct> products = salesLedgerProductMapper.selectList(productWrapper);
         for (SalesLedgerProduct product : products) {
-            product.setOriginalNoInvoiceNum(product.getNoInvoiceNum());
-            // 鎻愪緵涓存椂鏈紑绁ㄦ暟锛屾湭寮�绁ㄩ噾棰濅緵鍓嶆璁$畻
-            product.setTempnoInvoiceAmount(product.getNoInvoiceAmount());
-            product.setTempNoInvoiceNum(product.getNoInvoiceNum());
             product.setRegister(SecurityUtils.getLoginUser().getUser().getNickName());
             product.setRegisterDate(LocalDateTime.now());
             // 鍙戣揣淇℃伅
@@ -281,57 +288,73 @@
 
     @Override
     public List<MonthlyAmountDto> getAmountHalfYear(Integer type) {
-
         LocalDate now = LocalDate.now();
         List<MonthlyAmountDto> result = new ArrayList<>();
-
         for (int i = 5; i >= 0; i--) {
             YearMonth yearMonth = YearMonth.from(now.minusMonths(i));
-            LocalDateTime startTime = yearMonth.atDay(1).atStartOfDay();
-            LocalDateTime endTime = yearMonth.atEndOfMonth().atTime(23, 59, 59);
-
-            //  鍥炴閲戦
-            LambdaQueryWrapper<ReceiptPayment> receiptPaymentQuery = new LambdaQueryWrapper<>();
-            receiptPaymentQuery
-                    .ge(ReceiptPayment::getCreateTime, startTime)
-                    .le(ReceiptPayment::getCreateTime, endTime);
-
-            List<ReceiptPayment> receiptPayments =
-                    receiptPaymentMapper.selectList(receiptPaymentQuery);
-
-            BigDecimal receiptAmount = receiptPayments.stream()
-                    .map(ReceiptPayment::getReceiptPaymentAmount)
-                    .filter(Objects::nonNull)
-                    .reduce(BigDecimal.ZERO, BigDecimal::add);
-
-            //  寮�绁ㄩ噾棰�
-            LambdaQueryWrapper<InvoiceLedger> invoiceLedgerQuery = new LambdaQueryWrapper<>();
-            invoiceLedgerQuery
-                    .ge(InvoiceLedger::getCreateTime, startTime)
-                    .le(InvoiceLedger::getCreateTime, endTime);
-
-            List<InvoiceLedger> invoiceLedgers =
-                    invoiceLedgerMapper.selectList(invoiceLedgerQuery);
-
-            BigDecimal invoiceAmount = invoiceLedgers.stream()
-                    .map(InvoiceLedger::getInvoiceTotal)
-                    .filter(Objects::nonNull)
-                    .reduce(BigDecimal.ZERO, BigDecimal::add);
-
+            LocalDate startTime = yearMonth.atDay(1);
+            LocalDate endTime = yearMonth.atEndOfMonth();
             MonthlyAmountDto dto = new MonthlyAmountDto();
             dto.setMonth(yearMonth.format(DateTimeFormatter.ofPattern("yyyy-MM")));
-            dto.setReceiptAmount(receiptAmount);
-            dto.setInvoiceAmount(invoiceAmount);
-
+            //鍥炴閲戦
+            List<AccountSalesCollection> accountSalesCollections = accountSalesCollectionMapper.selectList(new LambdaQueryWrapper<AccountSalesCollection>()
+                    .between(AccountSalesCollection::getCollectionDate, startTime, endTime));
+            BigDecimal totalIncome = Optional.of(
+                    accountSalesCollections.stream()
+                            .map(AccountSalesCollection::getCollectionAmount)
+                            .filter(Objects::nonNull)
+                            .reduce(BigDecimal.ZERO, BigDecimal::add)
+            ).orElse(BigDecimal.ZERO);
+            dto.setReceiptAmount(totalIncome);
+            //寮�绁ㄩ噾棰�
+            List<AccountInvoiceApplication> accountInvoiceApplications = accountInvoiceApplicationMapper.selectList(new LambdaQueryWrapper<AccountInvoiceApplication>()
+                            .eq(AccountInvoiceApplication::getStatus,1)
+                    .between(AccountInvoiceApplication::getApplyDate, startTime, endTime));
+            BigDecimal totalInvoiceAmount = Optional.of(
+                    accountInvoiceApplications.stream()
+                            .map(AccountInvoiceApplication::getInvoiceAmount)
+                            .filter(Objects::nonNull)
+                            .reduce(BigDecimal.ZERO, BigDecimal::add)
+            ).orElse(BigDecimal.ZERO);
+            dto.setInvoiceAmount(totalInvoiceAmount);
             result.add(dto);
         }
-
         return result;
     }
 
     @Override
     public IPage<SalesLedgerVo> selectSalesLedgerListPage(Page page, SalesLedgerDto salesLedgerDto) {
-        return salesLedgerMapper.selectSalesLedgerListPage(page, salesLedgerDto);
+        IPage<SalesLedgerVo> result = salesLedgerMapper.selectSalesLedgerListPage(page, salesLedgerDto);
+        fillTrustFund(result.getRecords());
+        return result;
+    }
+
+    /**
+     * 鍥炲~瀹㈡埛鐨勪俊鎵樺熀閲戯紝骞跺垽鏂湰绗斿悎鍚岄噾棰濇槸鍚﹀凡瓒呭嚭銆�
+     * 瓒呭嚭涓庡惁鐢卞悗绔畻濂借繑鍥烇紝鍓嶇鍙礋璐f爣绾�
+     */
+    private void fillTrustFund(List<? extends SalesLedger> records) {
+        if (CollectionUtils.isEmpty(records)) {
+            return;
+        }
+        List<Long> customerIds = records.stream()
+                .map(SalesLedger::getCustomerId)
+                .filter(Objects::nonNull)
+                .distinct()
+                .collect(Collectors.toList());
+        if (customerIds.isEmpty()) {
+            return;
+        }
+        Map<Long, BigDecimal> trustFundMap = customerMapper.selectBatchIds(customerIds).stream()
+                .filter(item -> item.getTrustFund() != null)
+                .collect(Collectors.toMap(Customer::getId, Customer::getTrustFund, (existing, replacement) -> existing));
+
+        records.forEach(ledger -> {
+            BigDecimal trustFund = trustFundMap.get(ledger.getCustomerId());
+            ledger.setTrustFund(trustFund);
+            ledger.setExceedsTrustFund(trustFund != null && ledger.getContractAmount() != null
+                    && ledger.getContractAmount().compareTo(trustFund) > 0);
+        });
     }
 
     @Override
@@ -376,6 +399,13 @@
                 if (salesLedger1 != null) {
                     continue;
                 }
+
+                // 鍒ゆ柇涓氬姟鍛樻槸鍚﹀瓨鍦�
+                SysUser salesman = sysUserMapper.selectOne(new LambdaQueryWrapper<SysUser>()
+                        .eq(SysUser::getNickName, salesLedgerImportDto.getSalesman()));
+                if (salesman == null) {
+                    throw new RuntimeException("涓氬姟鍛�:" + salesLedgerImportDto.getSalesman() + "涓嶅瓨鍦紒");
+                }
                 SalesLedger salesLedger = new SalesLedger();
                 BeanUtils.copyProperties(salesLedgerImportDto, salesLedger);
                 salesLedger.setExecutionDate(DateUtils.toLocalDate(salesLedgerImportDto.getExecutionDate()));
@@ -406,6 +436,7 @@
                 salesLedger.setContractAmount(salesLedgerProductImportDtos.stream()
                         .map(SalesLedgerProductImportDto::getTaxInclusiveTotalPrice)
                         .reduce(BigDecimal.ZERO, BigDecimal::add));
+                salesLedger.setNetContractAmount(salesLedger.getContractAmount());
                 salesLedgerMapper.insert(salesLedger);
 
 
@@ -416,8 +447,6 @@
                     salesLedgerProduct.setType(1);
                     // 璁$畻涓嶅惈绋庢�讳环
                     salesLedgerProduct.setTaxExclusiveTotalPrice(salesLedgerProduct.getTaxInclusiveTotalPrice().divide(new BigDecimal(1).add(salesLedgerProduct.getTaxRate().divide(new BigDecimal(100))), 2, RoundingMode.HALF_UP));
-                    salesLedgerProduct.setNoInvoiceNum(salesLedgerProduct.getQuantity());
-                    salesLedgerProduct.setNoInvoiceAmount(salesLedgerProduct.getTaxExclusiveTotalPrice());
                     // 鏍¢獙浜у搧瑙勬牸鏄惁瀛樺湪
                     Optional<Map<String, Object>> productModelOptional = list.stream()
                             .filter(map -> Objects.equals(map.get("productName"), salesLedgerProduct.getProductCategory()) && Objects.equals(map.get("model"), salesLedgerProduct.getSpecificationModel()))
@@ -441,7 +470,6 @@
                     salesLedgerProduct.setRegister(loginUser.getNickName());
                     salesLedgerProduct.setRegisterDate(LocalDateTime.now());
                     salesLedgerProduct.setApproveStatus(0);
-                    salesLedgerProduct.setPendingInvoiceTotal(salesLedgerProductImportDto.getTaxInclusiveTotalPrice());
                     salesLedgerProduct.setIsProduction(salesLedgerProductImportDto.getIsProduction() == 1);
                     salesLedgerProductMapper.insert(salesLedgerProduct);
                     // 娣诲姞鐢熶骇鏁版嵁
@@ -475,11 +503,7 @@
             productWrapper.eq(SalesLedgerProduct::getType, 1);
             List<SalesLedgerProduct> products = salesLedgerProductMapper.selectList(productWrapper);
             for (SalesLedgerProduct product : products) {
-                product.setOriginalNoInvoiceNum(product.getNoInvoiceNum());
-                // 鎻愪緵涓存椂鏈紑绁ㄦ暟锛屾湭寮�绁ㄩ噾棰濅緵鍓嶆璁$畻
-                product.setTempnoInvoiceAmount(product.getNoInvoiceAmount());
-                product.setTempNoInvoiceNum(product.getNoInvoiceNum());
-                product.setRegister(SecurityUtils.getLoginUser().getUser().getNickName());
+               product.setRegister(SecurityUtils.getLoginUser().getUser().getNickName());
                 product.setRegisterDate(LocalDateTime.now());
                 // 鍙戣揣淇℃伅
                 ShippingInfo shippingInfo = shippingInfoMapper.selectOne(new LambdaQueryWrapper<ShippingInfo>()
@@ -552,29 +576,8 @@
             salesLedgerProductMapper.deleteBatchIds(productIds);
         }
 
-        LambdaQueryWrapper<InvoiceRegistrationProduct> wrapper = new LambdaQueryWrapper<>();
-        wrapper.in(InvoiceRegistrationProduct::getSalesLedgerId, idList);
-        List<InvoiceRegistrationProduct> invoiceRegistrationProducts = invoiceRegistrationProductMapper.selectList(wrapper);
         List<Integer> invoiceLedgerIds = new ArrayList<>();
-        if (CollectionUtils.isNotEmpty(invoiceRegistrationProducts)) {
-            LambdaQueryWrapper<InvoiceLedger> wrapperOne = new LambdaQueryWrapper<>();
-            wrapperOne.in(InvoiceLedger::getInvoiceRegistrationProductId, invoiceRegistrationProducts.stream().map(InvoiceRegistrationProduct::getId).collect(Collectors.toList()));
-            List<InvoiceLedger> invoiceLedgers = invoiceLedgerMapper.selectList(wrapperOne);
-            if (CollectionUtils.isNotEmpty(invoiceLedgers)) {
-                invoiceLedgerIds = invoiceLedgers.stream().map(InvoiceLedger::getId).collect(Collectors.toList());
-            }
-            invoiceLedgerMapper.delete(wrapperOne);
-        }
-        invoiceRegistrationProductMapper.delete(wrapper);
-        LambdaQueryWrapper<InvoiceRegistration> wrapperTwo = new LambdaQueryWrapper<>();
-        wrapperTwo.in(InvoiceRegistration::getSalesLedgerId, idList);
-        invoiceRegistrationMapper.delete(wrapperTwo);
 
-        if (CollectionUtils.isNotEmpty(invoiceLedgerIds)) {
-            LambdaQueryWrapper<ReceiptPayment> wrapperTree = new LambdaQueryWrapper<>();
-            wrapperTree.in(ReceiptPayment::getInvoiceLedgerId, invoiceLedgerIds);
-            receiptPaymentMapper.delete(wrapperTree);
-        }
         // 鍒犻櫎鍙戣揣鍙拌处璁板綍
         List<ShippingInfo> shippingInfos = shippingInfoMapper.selectList(new LambdaQueryWrapper<ShippingInfo>()
                 .in(ShippingInfo::getSalesLedgerId, idList));
@@ -583,6 +586,19 @@
         }
         // 鍒犻櫎闄勪欢琛�
         commonFileService.deleteByBusinessIds(idList, FileNameType.SALE.getValue());
+
+        // 鍒犻櫎鍙拌处瀵瑰簲鐨勫鎵瑰疄渚嬶紙鍚屼竴鍙拌处鍙兘鍙嶅鎻愪氦/閲嶅锛屼細鏈夊鏉★級
+        List<ApprovalInstance> approvalInstances = approvalInstanceService.list(
+                new LambdaQueryWrapper<ApprovalInstance>()
+                        .in(ApprovalInstance::getBusinessId, idList)
+                        .eq(ApprovalInstance::getBusinessType, TypeEnums.SALES_LEDGER_APPROVAL.getCode())
+                        .eq(ApprovalInstance::getDeleted, 0));
+        if (CollectionUtils.isNotEmpty(approvalInstances)) {
+            approvalInstanceService.delete(approvalInstances.stream()
+                    .map(ApprovalInstance::getId)
+                    .filter(Objects::nonNull)
+                    .collect(Collectors.toList()));
+        }
 
         // 鍒犻櫎鐢熶骇绠℃帶鏁版嵁
         //鏌ヨ鐢熶骇鎶ュ伐id
@@ -609,18 +625,35 @@
         SalesLedger salesLedger = convertToEntity(salesLedgerDto);
         salesLedger.setCustomerName(customer.getCustomerName());
         salesLedger.setTenantId(customer.getTenantId());
+        applyLedgerType(salesLedger, salesLedgerDto);
+        // 褰曞叆浜猴細濡傛灉鏈紶鍒欎娇鐢ㄥ綋鍓嶇櫥褰曠敤鎴�
+        if (StringUtils.isEmpty(salesLedger.getEntryPerson())) {
+            salesLedger.setEntryPerson(String.valueOf(SecurityUtils.getUserId()));
+        }
+        // 鏂板鍜屼慨鏀归兘瑕侀噸鏂拌蛋瀹℃壒
+        salesLedger.setApprovalStatus(SalesQuotationStatusEnum.PENDING.getCode());
         // 3. 鏂板鎴栨洿鏂颁富琛�
         if (salesLedger.getId() == null) {
-            String contractNo = generateSalesContractNo();
+            String contractNo = salesLedger.getSalesContractNo();
+            if (StringUtils.isEmpty(contractNo)) {
+                contractNo = generateSalesContractNo(salesLedgerDto.getEntryDate());
+            }
             salesLedger.setSalesContractNo(contractNo);
             salesLedgerMapper.insert(salesLedger);
         } else {
+            // 鏀瑰崟浼氶噸鏂拌蛋涓�閬嶅鎵癸細鍏堜綔搴熸鍓嶆湭缁撴潫鐨勫鎵瑰疄渚嬶紝浜嬪姟鎻愪氦鍓嶈繕浼氶噸鏂板彂璧�
+            approvalInstanceService.lambdaUpdate()
+                    .set(ApprovalInstance::getStatus, "REJECTED")
+                    .eq(ApprovalInstance::getBusinessId, salesLedger.getId())
+                    .eq(ApprovalInstance::getBusinessType, TypeEnums.SALES_LEDGER_APPROVAL.getCode())
+                    .update();
             salesLedgerMapper.updateById(salesLedger);
         }
 
 
-        // 4. 澶勭悊瀛愯〃鏁版嵁
-        List<SalesLedgerProduct> productList = salesLedgerDto.getProductData();
+        // 4. 澶勭悊瀛愯〃鏁版嵁銆備唬鍌ㄦ病鏈変骇鍝佹槑缁嗭紝鍚堝悓閲戦浠ユ墜宸ュ~鍐欑殑涓哄噯锛屼笉鑳借瀛愯〃姹囨�昏鐩�
+        List<SalesLedgerProduct> productList = LEDGER_TYPE_OIL.equals(salesLedger.getLedgerType())
+                ? salesLedgerDto.getProductData() : null;
         if (productList != null && !productList.isEmpty()) {
             handleSalesLedgerProducts(salesLedger.getId(), productList, EnumUtil.fromCode(SaleEnum.class, salesLedgerDto.getType()));
             updateMainContractAmount(
@@ -632,10 +665,112 @@
             );
         }
 
-        // 5. 淇濆瓨閿�鍞彴璐﹂檮浠�
+        // 5. 鍏滃簳锛氱‘淇濆疄闄呭悎鍚岄噾棰濇湁鍒濆鍊肩瓑浜庡悎鍚岄噾棰�
+        if (salesLedger.getNetContractAmount() == null) {
+            SalesLedger dbLedger = salesLedgerMapper.selectById(salesLedger.getId());
+            if (dbLedger != null && dbLedger.getNetContractAmount() == null && dbLedger.getContractAmount() != null) {
+                SalesLedger updateEntity = new SalesLedger();
+                updateEntity.setId(salesLedger.getId());
+                updateEntity.setNetContractAmount(dbLedger.getContractAmount());
+                salesLedgerMapper.updateById(updateEntity);
+            }
+        }
+
+        // 6. 淇濆瓨閿�鍞彴璐﹂檮浠�
         fileUtil.saveStorageAttachment(ApplicationTypeEnum.FILE, RecordTypeEnum.SALES_LEDGER, salesLedger.getId(), salesLedgerDto.getStorageBlobDTOs());
 
+        // 7. 鍙戣捣瀹℃壒銆傚悎鍚岄噾棰濊鍙栬惤搴撳悗鐨勫�硷紙鍗栨补鐨勯噾棰濈敱绗� 4 姝ョ殑浜у搧鏄庣粏姹囨�诲啓鍥烇級
+        SalesLedger savedLedger = salesLedgerMapper.selectById(salesLedger.getId());
+        startSalesLedgerApproval(savedLedger, customer.getTrustFund());
+
         return 1;
+    }
+
+    /**
+     * 鏍¢獙閿�鍞被鍨嬪苟琛ラ綈浠e偍鐨勬补搴�/鍌ㄧ綈淇℃伅銆�
+     * 鍗栨补锛氬悎鍚岄噾棰濆彧鑳界敱浜у搧鏄庣粏姹囨�讳骇鐢燂紱浠e偍锛氭病鏈夋槑缁嗭紝蹇呴』閫夋补搴撱�佸偍缃愬苟鎵嬪伐濉悎鍚岄噾棰�
+     */
+    private void applyLedgerType(SalesLedger salesLedger, SalesLedgerDto salesLedgerDto) {
+        String ledgerType = salesLedgerDto.getLedgerType();
+        if (StringUtils.isEmpty(ledgerType)) {
+            throw new BaseException("閿�鍞被鍨嬩笉鑳戒负绌�");
+        }
+        if (LEDGER_TYPE_OIL.equals(ledgerType)) {
+            salesLedger.setOilDepotId(null);
+            salesLedger.setOilDepotName(null);
+            salesLedger.setTankId(null);
+            salesLedger.setTankNo(null);
+            // updateById 浼氳烦杩� null锛屽淇敼鏄┖鎿嶄綔锛涙柊澧炴椂涓庢敼閫犲墠涓�鑷达紙鏈氨涓� null锛�
+            salesLedger.setContractAmount(null);
+            return;
+        }
+        if (!LEDGER_TYPE_DEPOSIT.equals(ledgerType)) {
+            throw new BaseException("閿�鍞被鍨嬩笉鍚堟硶:" + ledgerType);
+        }
+        if (salesLedgerDto.getOilDepotId() == null) {
+            throw new BaseException("浠e偍蹇呴』閫夋嫨娌瑰簱");
+        }
+        if (salesLedgerDto.getTankId() == null) {
+            throw new BaseException("浠e偍蹇呴』閫夋嫨鍌ㄧ綈");
+        }
+        if (salesLedgerDto.getContractAmount() == null
+                || salesLedgerDto.getContractAmount().compareTo(BigDecimal.ZERO) <= 0) {
+            throw new BaseException("浠e偍蹇呴』濉啓鍚堝悓閲戦");
+        }
+        OilDepot oilDepot = oilDepotMapper.selectById(salesLedgerDto.getOilDepotId());
+        if (oilDepot == null) {
+            throw new BaseException("娌瑰簱涓嶅瓨鍦�:" + salesLedgerDto.getOilDepotId());
+        }
+        TankInfo tankInfo = tankInfoMapper.selectById(salesLedgerDto.getTankId());
+        if (tankInfo == null) {
+            throw new BaseException("鍌ㄧ綈涓嶅瓨鍦�:" + salesLedgerDto.getTankId());
+        }
+        // 鍚嶇О浠ュ熀纭�鏁版嵁涓哄噯锛屼笉閲囦俊鍓嶇浼犲��
+        salesLedger.setOilDepotName(oilDepot.getDepotName());
+        salesLedger.setTankNo(tankInfo.getTankNo());
+    }
+
+    /**
+     * 鍙戣捣閿�鍞彴璐﹀鎵癸紝璧扮郴缁熷凡鏈夌殑 OA 瀹℃壒娴佺▼銆�
+     * 鍚堝悓閲戦瓒呭嚭瀹㈡埛淇℃墭鍩洪噾鏃讹紝瀹℃壒鏍囬甯︿笂鎻愰啋瀛楃溂
+     */
+    private void startSalesLedgerApproval(SalesLedger ledger, BigDecimal trustFund) {
+        if (ledger == null) {
+            return;
+        }
+        ApprovalTemplate approvalTemplate = approvalTemplateMapper.selectOne(
+                new LambdaQueryWrapper<ApprovalTemplate>()
+                        .eq(ApprovalTemplate::getBusinessType, TypeEnums.SALES_LEDGER_APPROVAL.getCode())
+                        .eq(ApprovalTemplate::getDeleted, 0)
+                        .orderByDesc(ApprovalTemplate::getId)
+                        .last("LIMIT 1")
+        );
+        if (approvalTemplate == null) {
+            throw new RuntimeException("璇峰厛閰嶇疆閿�鍞彴璐﹀鎵规ā鏉�");
+        }
+        boolean exceedsTrustFund = trustFund != null && ledger.getContractAmount() != null
+                && ledger.getContractAmount().compareTo(trustFund) > 0;
+        String title = ledger.getSalesContractNo() + "瀹℃壒";
+        if (exceedsTrustFund) {
+            title += "锛堝悎鍚岄噾棰濊秴鍑哄鎴蜂俊鎵樺熀閲戯紝璇烽噸鐐瑰鏍革級";
+        }
+        LoginUser loginUser = SecurityUtils.getLoginUser();
+        ApprovalInstanceDto approvalInstance = new ApprovalInstanceDto();
+        approvalInstance.setTemplateId(approvalTemplate.getId());
+        approvalInstance.setTemplateName(approvalTemplate.getTemplateName());
+        approvalInstance.setBusinessId(ledger.getId());
+        approvalInstance.setBusinessType(TypeEnums.SALES_LEDGER_APPROVAL.getCode());
+        approvalInstance.setCurrentLevel(1);
+        approvalInstance.setTitle(title);
+        approvalInstance.setApplicantId(loginUser.getUserId());
+        approvalInstance.setApplicantName(loginUser.getNickName());
+        approvalInstance.setApplyTime(LocalDateTime.now());
+        try {
+            approvalInstanceService.add(approvalInstance);
+        } catch (Exception e) {
+            log.error("SalesLedgerServiceImpl approve error for salesContractNo: {}", ledger.getSalesContractNo(), e);
+            throw new RuntimeException("瀹℃壒澶辫触: " + e.getMessage(), e);
+        }
     }
 
     @Override
@@ -659,9 +794,6 @@
         if (!insertList.isEmpty()) {
             for (SalesLedgerProduct salesLedgerProduct : insertList) {
                 salesLedgerProduct.setType(type.getCode());
-                salesLedgerProduct.setNoInvoiceNum(salesLedgerProduct.getQuantity());
-                salesLedgerProduct.setNoInvoiceAmount(salesLedgerProduct.getTaxInclusiveTotalPrice());
-                salesLedgerProduct.setPendingInvoiceTotal(salesLedgerProduct.getTaxInclusiveTotalPrice());
                 salesLedgerProductMapper.insert(salesLedgerProduct);
                 // 娣诲姞鐢熶骇鏁版嵁
                 salesLedgerProductServiceImpl.addProductionData(salesLedgerProduct);
@@ -676,8 +808,8 @@
     }
 
     @Transactional(readOnly = true)
-    public String generateSalesContractNo() {
-        LocalDate currentDate = LocalDate.now();
+    public String generateSalesContractNo(Date entryDate) {
+        LocalDate currentDate = entryDate != null ? DateUtils.toLocalDate(entryDate) : LocalDate.now();
         String datePart = currentDate.format(DateTimeFormatter.BASIC_ISO_DATE);
         String lockKey = LOCK_PREFIX + datePart;
         String lockValue = Thread.currentThread().getId() + "-" + System.nanoTime(); // 鍞竴鏍囪瘑閿佹寔鏈夎��
@@ -773,6 +905,15 @@
             amountField.setAccessible(true);
             amountField.set(entity, totalAmount);
 
+            // 瀹為檯鍚堝悓閲戦鍒濆鍊肩瓑浜庡悎鍚岄噾棰�
+            try {
+                Field netAmountField = mainEntityClass.getDeclaredField("netContractAmount");
+                netAmountField.setAccessible(true);
+                netAmountField.set(entity, totalAmount);
+            } catch (NoSuchFieldException ignored) {
+                // 瀛愮被鍙兘娌℃湁璇ュ瓧娈碉紝蹇界暐
+            }
+
             mainMapper.updateById(entity);
         } catch (Exception e) {
             throw new RuntimeException("鍔ㄦ�佹洿鏂颁富琛ㄩ噾棰濆け璐�", e);

--
Gitblit v1.9.3