From 47806d9e390ee00e1d29ad1da8c1aa908882a758 Mon Sep 17 00:00:00 2001
From: yuan <123@>
Date: 星期二, 11 八月 2026 14:43:59 +0800
Subject: [PATCH] 用河南鹤壁代码覆盖山西长治

---
 src/main/java/com/ruoyi/purchase/service/impl/PurchaseLedgerServiceImpl.java |  587 ++++++----------------------------------------------------
 1 files changed, 60 insertions(+), 527 deletions(-)

diff --git a/src/main/java/com/ruoyi/purchase/service/impl/PurchaseLedgerServiceImpl.java b/src/main/java/com/ruoyi/purchase/service/impl/PurchaseLedgerServiceImpl.java
index e1c3ec9..96b0a54 100644
--- a/src/main/java/com/ruoyi/purchase/service/impl/PurchaseLedgerServiceImpl.java
+++ b/src/main/java/com/ruoyi/purchase/service/impl/PurchaseLedgerServiceImpl.java
@@ -6,12 +6,8 @@
 import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
 import com.baomidou.mybatisplus.core.toolkit.Wrappers;
 import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
-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.bean.vo.ApproveProcessVO;
 import com.ruoyi.approve.pojo.ApproveProcess;
-import com.ruoyi.approve.service.ApprovalInstanceService;
 import com.ruoyi.approve.service.impl.ApproveProcessServiceImpl;
 import com.ruoyi.basic.enums.ApplicationTypeEnum;
 import com.ruoyi.basic.enums.RecordTypeEnum;
@@ -22,22 +18,20 @@
 import com.ruoyi.basic.pojo.ProductModel;
 import com.ruoyi.basic.pojo.SupplierManage;
 import com.ruoyi.basic.utils.FileUtil;
+import com.ruoyi.common.enums.FileNameType;
 import com.ruoyi.common.exception.base.BaseException;
-import com.ruoyi.common.enums.ApprovalStatusEnum;
-import com.ruoyi.common.enums.ReviewStatusEnum;
-import com.ruoyi.common.enums.StockInQualifiedRecordTypeEnum;
-import com.ruoyi.common.utils.DateUtils;
+import com.ruoyi.common.utils.AmountUtils;
 import com.ruoyi.common.utils.SecurityUtils;
 import com.ruoyi.common.utils.StringUtils;
 import com.ruoyi.common.utils.poi.ExcelUtil;
 import com.ruoyi.framework.security.LoginUser;
 import com.ruoyi.framework.web.domain.AjaxResult;
-import com.ruoyi.framework.web.domain.R;
 import com.ruoyi.other.mapper.TempFileMapper;
 import com.ruoyi.procurementrecord.mapper.ProcurementRecordMapper;
 import com.ruoyi.procurementrecord.pojo.ProcurementRecordStorage;
-import com.ruoyi.procurementrecord.utils.StockUtils;
+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.PurchaseLedgerDto;
 import com.ruoyi.purchase.dto.PurchaseLedgerImportDto;
@@ -53,15 +47,13 @@
 import com.ruoyi.quality.pojo.QualityInspectParam;
 import com.ruoyi.quality.pojo.QualityTestStandard;
 import com.ruoyi.quality.pojo.QualityTestStandardParam;
-import com.ruoyi.quality.service.IQualityInspectService;
 import com.ruoyi.sales.mapper.CommonFileMapper;
 import com.ruoyi.sales.mapper.SalesLedgerMapper;
 import com.ruoyi.sales.mapper.SalesLedgerProductMapper;
+import com.ruoyi.sales.pojo.CommonFile;
 import com.ruoyi.sales.pojo.SalesLedger;
 import com.ruoyi.sales.pojo.SalesLedgerProduct;
 import com.ruoyi.sales.service.impl.CommonFileServiceImpl;
-import com.ruoyi.stock.pojo.StockInRecord;
-import com.ruoyi.stock.service.StockInRecordService;
 import lombok.RequiredArgsConstructor;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.BeanUtils;
@@ -72,7 +64,6 @@
 
 import java.io.InputStream;
 import java.math.BigDecimal;
-import java.math.RoundingMode;
 import java.time.LocalDate;
 import java.time.LocalDateTime;
 import java.time.ZoneId;
@@ -98,6 +89,7 @@
     private final SysUserMapper userMapper;
     private final TempFileMapper tempFileMapper;
     private final CommonFileMapper commonFileMapper;
+    private final SysDeptMapper sysDeptMapper;
     private final SupplierManageMapper supplierManageMapper;
     private final ProductMapper productMapper;
     private final ProductModelMapper productModelMapper;
@@ -111,11 +103,6 @@
     private final ApproveProcessServiceImpl approveProcessService;
     private final ProcurementRecordMapper procurementRecordStorageMapper;
     private final FileUtil fileUtil;
-    private final ApprovalInstanceService approvalInstanceService;
-    private final IQualityInspectService qualityInspectService;
-    private final StockInRecordService stockInRecordService;
-    private final StockUtils stockUtils;
-    private final ApprovalTemplateMapper approvalTemplateMapper;
 
     @Override
     public List<PurchaseLedger> selectPurchaseLedgerList(PurchaseLedger purchaseLedger) {
@@ -138,6 +125,7 @@
         PurchaseLedger purchaseLedger = new PurchaseLedger();
         // DTO杞珽ntity
         BeanUtils.copyProperties(purchaseLedgerDto, purchaseLedger);
+        AmountUtils.normalizeContractAmount(purchaseLedger);
         SalesLedger salesLedger = salesLedgerMapper.selectById(purchaseLedgerDto.getSalesLedgerId());
         //褰曞叆浜�
         SysUser sysUser = userMapper.selectUserById(purchaseLedgerDto.getRecorderId());
@@ -162,13 +150,8 @@
         purchaseLedger.setRecorderId(purchaseLedgerDto.getRecorderId());
 
         purchaseLedger.setApprovalStatus(1);
-        // 瀹為檯鍚堝悓閲戦濮嬬粓绛変簬鍚堝悓閲戦
-        purchaseLedger.setNetContractAmount(purchaseLedger.getContractAmount());
         // 3. 鏂板鎴栨洿鏂颁富琛�
         if (purchaseLedger.getId() == null) {
-            if (!StringUtils.hasText(purchaseLedger.getPurchaseContractNumber())) {
-                purchaseLedger.setPurchaseContractNumber(generatePurchaseContractNo(purchaseLedger.getEntryDate()));
-            }
             purchaseLedgerMapper.insert(purchaseLedger);
         } else {
             // 鍒犻櫎閲囪喘瀹℃牳锛岄噸鏂版彁浜�
@@ -193,188 +176,6 @@
         // 5. 杩佺Щ涓存椂鏂囦欢鍒版寮忕洰褰�
         fileUtil.saveStorageAttachment(ApplicationTypeEnum.FILE, RecordTypeEnum.PURCHASE_LEDGER, purchaseLedger.getId(), purchaseLedgerDto.getStorageBlobDTOS());
         return 1;
-    }
-
-    @Override
-    public R batchInsertPurchaseSteps(List<Long> ids) {
-        if (CollectionUtils.isEmpty(ids)) {
-            return R.fail("璇烽�夋嫨閲囪喘鍙拌处");
-        }
-
-        List<Long> distinctIds = ids.stream()
-                .filter(Objects::nonNull)
-                .distinct()
-                .collect(Collectors.toList());
-        if (CollectionUtils.isEmpty(distinctIds)) {
-            return R.fail("璇烽�夋嫨閲囪喘鍙拌处");
-        }
-
-        PurchaseLedgerDto queryDto = new PurchaseLedgerDto();
-        queryDto.setIds(distinctIds);
-        IPage<PurchaseLedgerDto> pageResult = this.selectPurchaseLedgerListPage(
-                new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(1, distinctIds.size()),
-                queryDto
-        );
-        List<PurchaseLedgerDto> ledgerDtos = pageResult == null || pageResult.getRecords() == null
-                ? Collections.emptyList()
-                : pageResult.getRecords();
-
-        Map<Long, PurchaseLedgerDto> ledgerDtoMap = ledgerDtos.stream()
-                .filter(item -> item.getId() != null)
-                .collect(Collectors.toMap(PurchaseLedgerDto::getId, item -> item, (left, right) -> left, LinkedHashMap::new));
-
-        List<Map<String, Object>> details = new ArrayList<>();
-        int successCount = 0;
-        int skipCount = 0;
-        int failCount = 0;
-        int autoApprovedCount = 0;
-
-        for (Long id : distinctIds) {
-            Map<String, Object> detail = new LinkedHashMap<>();
-            detail.put("purchaseLedgerId", id);
-            PurchaseLedgerDto purchaseLedgerDto = ledgerDtoMap.get(id);
-            if (purchaseLedgerDto == null) {
-                failCount++;
-                detail.put("status", "FAIL");
-                detail.put("message", "閲囪喘鍙拌处涓嶅瓨鍦ㄦ垨鏈煡璇㈠埌");
-                details.add(detail);
-                continue;
-            }
-
-            detail.put("purchaseContractNumber", purchaseLedgerDto.getPurchaseContractNumber());
-            detail.put("approvalStatus", purchaseLedgerDto.getApprovalStatus());
-            detail.put("stockInStatus", purchaseLedgerDto.getStockInStatus());
-
-            if (ApprovalStatusEnum.REJECTED.getCode().equals(purchaseLedgerDto.getApprovalStatus())) {
-                skipCount++;
-                detail.put("status", "SKIP");
-                detail.put("message", "閲囪喘鍗曞凡椹冲洖");
-                details.add(detail);
-                continue;
-            }
-
-            if ("瀹屽叏鍏ュ簱".equals(purchaseLedgerDto.getStockInStatus())) {
-                skipCount++;
-                detail.put("status", "SKIP");
-                detail.put("message", "閲囪喘鍗曞凡瀹屽叏鍏ュ簱");
-                details.add(detail);
-                continue;
-            }
-
-            try {
-                PurchaseLedger purchaseLedger = purchaseLedgerMapper.selectById(id);
-                if (purchaseLedger == null) {
-                    failCount++;
-                    detail.put("status", "FAIL");
-                    detail.put("message", "閲囪喘鍙拌处涓嶅瓨鍦�");
-                    details.add(detail);
-                    continue;
-                }
-
-                if (!ApprovalStatusEnum.APPROVED.getCode().equals(purchaseLedger.getApprovalStatus())) {
-                    ApprovalInstance approvalInstance = approvalInstanceService.getOne(
-                            Wrappers.<ApprovalInstance>lambdaQuery()
-                                    .eq(ApprovalInstance::getBusinessId, purchaseLedger.getId())
-                                    .eq(ApprovalInstance::getBusinessType, 5L)
-                                    .eq(ApprovalInstance::getDeleted, 0)
-                                    .orderByDesc(ApprovalInstance::getId)
-                                    .last("limit 1")
-                    );
-                    if (approvalInstance == null) {
-                        failCount++;
-                        detail.put("status", "FAIL");
-                        detail.put("message", "鏈壘鍒板搴旂殑閲囪喘瀹℃壒瀹炰緥");
-                        details.add(detail);
-                        continue;
-                    }
-
-                    if ("APPROVED".equals(approvalInstance.getStatus())
-                            && !ApprovalStatusEnum.APPROVED.getCode().equals(purchaseLedger.getApprovalStatus())) {
-                        purchaseLedger.setApprovalStatus(ApprovalStatusEnum.APPROVED.getCode());
-                        purchaseLedgerMapper.updateById(purchaseLedger);
-                    } else if (!"APPROVED".equals(approvalInstance.getStatus())) {
-                        R autoApproveResult = approvalInstanceService.autoApprove(approvalInstance.getId());
-                        if (autoApproveResult == null || !R.isSuccess(autoApproveResult)) {
-                            failCount++;
-                            detail.put("status", "FAIL");
-                            detail.put("message", autoApproveResult == null ? "閲囪喘瀹℃壒鑷姩閫氳繃澶辫触" : autoApproveResult.getMsg());
-                            details.add(detail);
-                            continue;
-                        }
-                        autoApprovedCount++;
-                    }
-
-                    purchaseLedger = purchaseLedgerMapper.selectById(id);
-                    if (purchaseLedger == null || !ApprovalStatusEnum.APPROVED.getCode().equals(purchaseLedger.getApprovalStatus())) {
-                        failCount++;
-                        detail.put("status", "FAIL");
-                        detail.put("message", "閲囪喘鍗曞鎵圭姸鎬佹湭鏇存柊涓哄凡閫氳繃");
-                        details.add(detail);
-                        continue;
-                    }
-                }
-
-                List<SalesLedgerProduct> products = salesLedgerProductMapper.selectList(
-                        Wrappers.<SalesLedgerProduct>lambdaQuery()
-                                .eq(SalesLedgerProduct::getSalesLedgerId, purchaseLedger.getId())
-                                .eq(SalesLedgerProduct::getType, 2)
-                                .orderByAsc(SalesLedgerProduct::getId)
-                );
-                if (CollectionUtils.isEmpty(products)) {
-                    skipCount++;
-                    detail.put("status", "SKIP");
-                    detail.put("message", "閲囪喘鍗曟病鏈変骇鍝佹槑缁�");
-                    details.add(detail);
-                    continue;
-                }
-
-                int processedProductCount = 0;
-                int skippedProductCount = 0;
-                int failedProductCount = 0;
-                for (SalesLedgerProduct product : products) {
-                    try {
-                        boolean processed;
-                        if (Boolean.TRUE.equals(product.getIsChecked())) {
-                            processed = processPurchaseQualityProduct(purchaseLedger, product);
-                        } else {
-                            processed = processPurchaseDirectProduct(purchaseLedger, product);
-                        }
-                        if (processed) {
-                            processedProductCount++;
-                        } else {
-                            skippedProductCount++;
-                        }
-                    } catch (Exception ex) {
-                        failedProductCount++;
-                        log.error("鎵归噺鎺ㄨ繘閲囪喘鍙拌处澶辫触, purchaseLedgerId={}, productId={}, productModelId={}",
-                                purchaseLedger.getId(), product.getId(), product.getProductModelId(), ex);
-                    }
-                }
-
-                successCount++;
-                detail.put("status", failedProductCount > 0 ? "PARTIAL" : "SUCCESS");
-                detail.put("processedProductCount", processedProductCount);
-                detail.put("skippedProductCount", skippedProductCount);
-                detail.put("failedProductCount", failedProductCount);
-                detail.put("message", failedProductCount > 0 ? "閮ㄥ垎浜у搧澶勭悊澶辫触" : "澶勭悊瀹屾垚");
-                details.add(detail);
-            } catch (Exception ex) {
-                failCount++;
-                detail.put("status", "FAIL");
-                detail.put("message", ex.getMessage());
-                details.add(detail);
-                log.error("鎵归噺鎺ㄨ繘閲囪喘鍙拌处澶辫触, purchaseLedgerId={}", id, ex);
-            }
-        }
-
-        Map<String, Object> summary = new LinkedHashMap<>();
-        summary.put("totalCount", distinctIds.size());
-        summary.put("successCount", successCount);
-        summary.put("skipCount", skipCount);
-        summary.put("failCount", failCount);
-        summary.put("autoApprovedCount", autoApprovedCount);
-        summary.put("details", details);
-        return R.ok(summary, "鎵归噺鎺ㄨ繘閲囪喘姝ラ瀹屾垚");
     }
 
 
@@ -402,219 +203,7 @@
                         param.setId(null);
                         param.setInspectId(qualityInspect.getId());
                         qualityInspectParamMapper.insert(param);
-            });
-        }
-    }
-
-    private boolean processPurchaseQualityProduct(PurchaseLedger purchaseLedger, SalesLedgerProduct product) {
-        if (purchaseLedger == null || product == null || product.getProductModelId() == null) {
-            return false;
-        }
-
-        QualityInspect qualityInspect = findLatestPurchaseQualityInspect(purchaseLedger.getId(), product.getProductModelId());
-        if (qualityInspect == null) {
-            addQualityInspect(purchaseLedger, product);
-            qualityInspect = findLatestPurchaseQualityInspect(purchaseLedger.getId(), product.getProductModelId());
-        }
-        if (qualityInspect == null) {
-            return false;
-        }
-
-        LocalDateTime purchaseInspectTime = toStartOfDayPlusDays(purchaseLedger.getEntryDate(), 1);
-        if (purchaseInspectTime != null && (qualityInspect.getCheckTime() == null
-                || !DateUtils.toLocalDate(qualityInspect.getCheckTime()).equals(purchaseInspectTime.toLocalDate()))) {
-            qualityInspect.setCheckTime(DateUtils.toDate(purchaseInspectTime.toLocalDate()));
-            qualityInspectMapper.updateById(qualityInspect);
-        }
-
-        List<StockInRecord> stockRecords = findQualityStockRecords(qualityInspect.getId(), product.getProductModelId());
-        if (hasApprovedStockRecord(stockRecords)) {
-            return true;
-        }
-
-        if (!Integer.valueOf(1).equals(qualityInspect.getInspectState())) {
-            R autoSubmitResult = qualityInspectService.autoSubmit(qualityInspect.getId());
-            if (autoSubmitResult == null || !R.isSuccess(autoSubmitResult)) {
-                return false;
-            }
-            qualityInspect = qualityInspectMapper.selectById(qualityInspect.getId());
-        }
-
-        stockRecords = findQualityStockRecords(qualityInspect.getId(), product.getProductModelId());
-        if (CollectionUtils.isEmpty(stockRecords)
-                && qualityInspect.getQualifiedQuantity() != null
-                && qualityInspect.getQualifiedQuantity().compareTo(BigDecimal.ZERO) > 0) {
-            stockUtils.addStockWithBatchNo(
-                    product.getProductModelId(),
-                    qualityInspect.getQualifiedQuantity(),
-                    StockInQualifiedRecordTypeEnum.CUSTOMIZATION_UNSTOCK_OUT.getCode(),
-                    qualityInspect.getId(),
-                    null,
-                    purchaseInspectTime == null ? null : purchaseInspectTime.plusDays(1)
-            );
-            stockRecords = findQualityStockRecords(qualityInspect.getId(), product.getProductModelId());
-        }
-
-        StockInRecord targetStockRecord = findLatestUnapprovedStockRecord(stockRecords);
-        if (targetStockRecord == null) {
-            return false;
-        }
-
-        LocalDateTime qualityStockCreateTime = resolveQualityStockCreateTime(qualityInspect);
-        if (qualityStockCreateTime != null && (targetStockRecord.getCreateTime() == null
-                || !qualityStockCreateTime.equals(targetStockRecord.getCreateTime()))) {
-            targetStockRecord.setCreateTime(qualityStockCreateTime);
-            stockInRecordService.updateById(targetStockRecord);
-        }
-
-        approveStockRecords(Collections.singletonList(targetStockRecord));
-        stockRecords = findQualityStockRecords(qualityInspect.getId(), product.getProductModelId());
-        return hasApprovedStockRecord(stockRecords);
-    }
-
-    private boolean processPurchaseDirectProduct(PurchaseLedger purchaseLedger, SalesLedgerProduct product) {
-        if (purchaseLedger == null || product == null || product.getProductModelId() == null) {
-            return false;
-        }
-        if (product.getQuantity() == null) {
-            return false;
-        }
-        if (!StringUtils.hasText(purchaseLedger.getPurchaseContractNumber())) {
-            return false;
-        }
-
-        LocalDateTime stockCreateTime = toStartOfDayPlusDays(purchaseLedger.getEntryDate(), 1);
-
-        List<StockInRecord> stockRecords = findDirectStockRecords(purchaseLedger.getId(), purchaseLedger.getPurchaseContractNumber(), product.getProductModelId(), product.getId());
-        if (hasApprovedStockRecord(stockRecords)) {
-            return true;
-        }
-
-        if (CollectionUtils.isEmpty(stockRecords)) {
-            stockUtils.addStockWithBatchNo(
-                    product.getProductModelId(),
-                    product.getQuantity(),
-                    StockInQualifiedRecordTypeEnum.PURCHASE_STOCK_IN.getCode(),
-                    purchaseLedger.getId(),
-                    purchaseLedger.getPurchaseContractNumber() + "-" + product.getId(),
-                    stockCreateTime
-            );
-            stockRecords = findDirectStockRecords(purchaseLedger.getId(), purchaseLedger.getPurchaseContractNumber(), product.getProductModelId(), product.getId());
-        }
-
-        if (CollectionUtils.isEmpty(stockRecords)) {
-            return false;
-        }
-
-        StockInRecord targetStockRecord = findLatestUnapprovedStockRecord(stockRecords);
-        if (targetStockRecord == null) {
-            return false;
-        }
-
-        if (stockCreateTime != null && (targetStockRecord.getCreateTime() == null
-                || !stockCreateTime.equals(targetStockRecord.getCreateTime()))) {
-            targetStockRecord.setCreateTime(stockCreateTime);
-            stockInRecordService.updateById(targetStockRecord);
-        }
-
-        approveStockRecords(Collections.singletonList(targetStockRecord));
-        stockRecords = findDirectStockRecords(purchaseLedger.getId(), purchaseLedger.getPurchaseContractNumber(), product.getProductModelId(), product.getId());
-        return hasApprovedStockRecord(stockRecords);
-    }
-
-    private LocalDateTime toStartOfDayPlusDays(Date date, int days) {
-        if (date == null) {
-            return null;
-        }
-        return DateUtils.toLocalDate(date).plusDays(days).atStartOfDay();
-    }
-
-    private LocalDateTime resolveQualityStockCreateTime(QualityInspect qualityInspect) {
-        if (qualityInspect == null || qualityInspect.getCheckTime() == null) {
-            return null;
-        }
-        return DateUtils.toLocalDate(qualityInspect.getCheckTime()).plusDays(1).atStartOfDay();
-    }
-
-    private QualityInspect findLatestPurchaseQualityInspect(Long purchaseLedgerId, Long productModelId) {
-        if (purchaseLedgerId == null || productModelId == null) {
-            return null;
-        }
-        return qualityInspectMapper.selectOne(
-                Wrappers.<QualityInspect>lambdaQuery()
-                        .eq(QualityInspect::getInspectType, 0)
-                        .eq(QualityInspect::getPurchaseLedgerId, purchaseLedgerId)
-                        .eq(QualityInspect::getProductModelId, productModelId)
-                        .orderByDesc(QualityInspect::getId)
-                        .last("limit 1")
-        );
-    }
-
-    private List<StockInRecord> findQualityStockRecords(Long qualityInspectId, Long productModelId) {
-        if (qualityInspectId == null || productModelId == null) {
-            return Collections.emptyList();
-        }
-        return stockInRecordService.list(
-                Wrappers.<StockInRecord>lambdaQuery()
-                        .eq(StockInRecord::getRecordType, StockInQualifiedRecordTypeEnum.CUSTOMIZATION_UNSTOCK_OUT.getCode())
-                        .eq(StockInRecord::getRecordId, qualityInspectId)
-                        .eq(StockInRecord::getProductModelId, productModelId)
-                        .orderByDesc(StockInRecord::getId)
-        );
-    }
-
-    private List<StockInRecord> findDirectStockRecords(Long purchaseLedgerId, String purchaseContractNumber, Long productModelId, Long purchaseProductId) {
-        if (purchaseLedgerId == null || productModelId == null || purchaseProductId == null || !StringUtils.hasText(purchaseContractNumber)) {
-            return Collections.emptyList();
-        }
-        String batchNo = purchaseContractNumber + "-" + purchaseProductId;
-        return stockInRecordService.list(
-                Wrappers.<StockInRecord>lambdaQuery()
-                        .eq(StockInRecord::getRecordType, StockInQualifiedRecordTypeEnum.PURCHASE_STOCK_IN.getCode())
-                        .eq(StockInRecord::getRecordId, purchaseLedgerId)
-                        .eq(StockInRecord::getProductModelId, productModelId)
-                        .eq(StockInRecord::getBatchNo, batchNo)
-                        .orderByDesc(StockInRecord::getId)
-        );
-    }
-
-    private boolean hasApprovedStockRecord(List<StockInRecord> stockRecords) {
-        return stockRecords != null && stockRecords.stream()
-                .anyMatch(item -> ReviewStatusEnum.APPROVED.getCode().equals(item.getApprovalStatus()));
-    }
-
-    private StockInRecord findLatestUnapprovedStockRecord(List<StockInRecord> stockRecords) {
-        if (CollectionUtils.isEmpty(stockRecords)) {
-            return null;
-        }
-        return stockRecords.stream()
-                .filter(item -> !ReviewStatusEnum.APPROVED.getCode().equals(item.getApprovalStatus()))
-                .findFirst()
-                .orElse(null);
-    }
-
-    private void approveStockRecords(List<StockInRecord> stockRecords) {
-        if (CollectionUtils.isEmpty(stockRecords)) {
-            return;
-        }
-        List<Long> rejectedIds = stockRecords.stream()
-                .filter(item -> ReviewStatusEnum.REJECTED.getCode().equals(item.getApprovalStatus()))
-                .map(StockInRecord::getId)
-                .filter(Objects::nonNull)
-                .collect(Collectors.toList());
-        if (!rejectedIds.isEmpty()) {
-            stockInRecordService.batchReAudit(rejectedIds);
-        }
-
-        List<Long> pendingIds = stockRecords.stream()
-                .filter(item -> item.getApprovalStatus() == null
-                        || ReviewStatusEnum.PENDING_REVIEW.getCode().equals(item.getApprovalStatus())
-                        || ReviewStatusEnum.REJECTED.getCode().equals(item.getApprovalStatus()))
-                .map(StockInRecord::getId)
-                .filter(Objects::nonNull)
-                .collect(Collectors.toList());
-        if (!pendingIds.isEmpty()) {
-            stockInRecordService.batchApprove(pendingIds, ReviewStatusEnum.APPROVED.getCode());
+                    });
         }
     }
 
@@ -650,6 +239,7 @@
 
         // 璁剧疆瀛楁
         for (SalesLedgerProduct product : products) {
+            AmountUtils.normalizeSalesLedgerProduct(product);
             product.setSalesLedgerId(salesLedgerId);
 
             Long productId = product.getProductId();
@@ -691,10 +281,10 @@
         }
 
         // 璁$畻鎬诲惈绋庨噾棰�
-        BigDecimal totalTaxInclusiveAmount = products.stream()
+        BigDecimal totalTaxInclusiveAmount = AmountUtils.scaleAmount(products.stream()
                 .map(SalesLedgerProduct::getTaxInclusiveTotalPrice)
                 .filter(Objects::nonNull)
-                .reduce(BigDecimal.ZERO, BigDecimal::add);
+                .reduce(BigDecimal.ZERO, BigDecimal::add));
 
         // 鏇存柊涓昏〃鐨勬�婚噾棰濆瓧娈�
         if (salesLedgerId != null) {
@@ -792,7 +382,9 @@
         // 4. 杞崲 DTO
         PurchaseLedgerDto resultDto = new PurchaseLedgerDto();
         BeanUtils.copyProperties(purchaseLedger, resultDto);
+        AmountUtils.normalizeContractAmount(resultDto);
         if (!products.isEmpty()) {
+            AmountUtils.normalizeSalesLedgerProducts(products);
             resultDto.setHasChildren(true);
             resultDto.setProductData(products);
             resultDto.setStorageBlobVOS(fileUtil.getStorageBlobVOsByApplicationAndRecordTypeAndRecordId(ApplicationTypeEnum.FILE, RecordTypeEnum.PURCHASE_LEDGER, purchaseLedger.getId()));
@@ -835,6 +427,7 @@
         queryWrapper.eq(SalesLedgerProduct::getSalesLedgerId, purchaseLedger.getId())
                 .eq(SalesLedgerProduct::getType, 2);
         List<SalesLedgerProduct> productList = salesLedgerProductMapper.selectList(queryWrapper);
+        AmountUtils.normalizeSalesLedgerProducts(productList);
         resultDto.setProductData(productList);
         return resultDto;
     }
@@ -866,17 +459,23 @@
 
     @Override
     public IPage<PurchaseLedgerDto> selectPurchaseLedgerListPage(IPage ipage, PurchaseLedgerDto purchaseLedger) {
-        return purchaseLedgerMapper.selectPurchaseLedgerListPage(ipage, purchaseLedger);
+        IPage<PurchaseLedgerDto> page = purchaseLedgerMapper.selectPurchaseLedgerListPage(ipage, purchaseLedger);
+        if (!CollectionUtils.isEmpty(page.getRecords())) {
+            page.getRecords().forEach(record -> {
+                AmountUtils.normalizeContractAmount(record);
+                AmountUtils.normalizeSalesLedgerProducts(record.getProductData());
+            });
+        }
+        return page;
     }
 
     @Override
-    public String getPurchaseNo(Date entryDate) {
-        LocalDate localDate = entryDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
+    public String getPurchaseNo() {
         // 鐢熸垚鏃ユ湡鍓嶇紑锛堜緥濡傦細CG20250405锛�
-        String purchaseNo = "CG" + localDate.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
+        String purchaseNo = "CG" + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
 
         // 鏋勫缓 Redis Key锛堟寜澶╁垎闅旓級
-        String redisKey = "purchase_no:" + localDate.format(DateTimeFormatter.ISO_LOCAL_DATE);
+        String redisKey = "purchase_no:" + LocalDate.now().format(DateTimeFormatter.ISO_LOCAL_DATE);
 
         // 鑾峰彇褰撳墠搴忓彿骞堕�掑锛堝師瀛愭搷浣滐級
         Long sequence = redisTemplate.opsForValue().increment(redisKey);
@@ -943,7 +542,6 @@
                 salesLedger.setContractAmount(salesLedgerProductImportDtos.stream()
                         .map(PurchaseLedgerProductImportDto::getTaxInclusiveTotalPrice)
                         .reduce(BigDecimal.ZERO,BigDecimal::add));
-                salesLedger.setNetContractAmount(salesLedger.getContractAmount());
                 // 閫氳繃閿�鍞崟鍙风粦瀹氶攢鍞�
                 SalesLedger salesLedger1 = salesLedgerMapper.selectOne(new LambdaQueryWrapper<SalesLedger>()
                         .eq(SalesLedger::getSalesContractNo, salesLedger.getSalesContractNo())
@@ -973,8 +571,14 @@
                     BeanUtils.copyProperties(salesLedgerProductImportDto, salesLedgerProduct);
                     salesLedgerProduct.setSalesLedgerId(salesLedger.getId());
                     salesLedgerProduct.setType(2);
+                    AmountUtils.normalizeSalesLedgerProduct(salesLedgerProduct);
                     // 璁$畻涓嶅惈绋庢�讳环
-                    salesLedgerProduct.setTaxExclusiveTotalPrice(salesLedgerProduct.getTaxInclusiveTotalPrice().divide(new BigDecimal(1).add(salesLedgerProduct.getTaxRate().divide(new BigDecimal(100))), 2, RoundingMode.HALF_UP));
+                    salesLedgerProduct.setTaxExclusiveTotalPrice(
+                            AmountUtils.calcTaxExclusiveTotalPrice(
+                                    salesLedgerProduct.getTaxInclusiveTotalPrice(),
+                                    salesLedgerProduct.getTaxRate()
+                            )
+                    );
                     list.stream()
                             .filter(map -> map.get("productName").equals(salesLedgerProduct.getProductCategory()) && map.get("model").equals(salesLedgerProduct.getSpecificationModel()))
                             .findFirst()
@@ -1022,7 +626,9 @@
         // 4. 杞崲 DTO
         PurchaseLedgerDto resultDto = new PurchaseLedgerDto();
         BeanUtils.copyProperties(purchaseLedger, resultDto);
+        AmountUtils.normalizeContractAmount(resultDto);
         if (!products.isEmpty()) {
+            AmountUtils.normalizeSalesLedgerProducts(products);
             resultDto.setHasChildren(true);
             resultDto.setProductData(products);
         }
@@ -1033,29 +639,15 @@
         if (loginUser == null) {
             return;
         }
-        ApprovalTemplate approvalTemplate = approvalTemplateMapper.selectOne(
-                new LambdaQueryWrapper<ApprovalTemplate>()
-                        .eq(ApprovalTemplate::getBusinessType, 5L)
-                        .eq(ApprovalTemplate::getDeleted, 0)
-                        .orderByDesc(ApprovalTemplate::getId)
-                        .last("LIMIT 1")
-        );
-        if (approvalTemplate == null) {
-            throw new BaseException("璇峰厛閰嶇疆閲囪喘瀹℃壒妯℃澘");
-        }
-
-        ApprovalInstanceDto approvalInstance = new ApprovalInstanceDto();
-        approvalInstance.setTemplateId(approvalTemplate.getId());
-        approvalInstance.setTemplateName(approvalTemplate.getTemplateName());
-        approvalInstance.setBusinessId(purchaseLedger.getId());
-        approvalInstance.setBusinessType(5L);
-        approvalInstance.setCurrentLevel(1);
-        approvalInstance.setApplicantId(loginUser.getUserId());
-        approvalInstance.setTitle(purchaseLedger.getPurchaseContractNumber()+"瀹℃壒");
-        approvalInstance.setApplicantName(loginUser.getNickName());
-        approvalInstance.setApplyTime(LocalDateTime.now());
-        approvalInstanceService.add(approvalInstance);
-
+        ApproveProcessVO approveProcessVO = new ApproveProcessVO();
+        approveProcessVO.setApproveType(5);
+        approveProcessVO.setApproveDeptId(loginUser.getCurrentDeptId());
+        approveProcessVO.setApproveReason(purchaseLedger.getPurchaseContractNumber());
+        approveProcessVO.setApproveUserIds(purchaseLedger.getApproveUserIds());
+        approveProcessVO.setApproveUser(loginUser.getUserId());
+        approveProcessVO.setApproveTime(LocalDate.now().toString());
+        approveProcessVO.setPrice(AmountUtils.scaleAmount(purchaseLedger.getContractAmount()));
+        approveProcessService.addApprove(approveProcessVO);
     }
 
     /**
@@ -1080,81 +672,22 @@
         return sb.toString();
     }
 
-    private static final String PURCHASE_LOCK_PREFIX = "purchase_contract_no:";
-    private static final long PURCHASE_LOCK_WAIT_TIMEOUT = 10;
-    private static final long PURCHASE_LOCK_EXPIRE_TIME = 30;
-
-    private String generatePurchaseContractNo(Date entryDate) {
-        LocalDate currentDate = entryDate != null ? DateUtils.toLocalDate(entryDate) : LocalDate.now();
-        String datePart = currentDate.format(DateTimeFormatter.BASIC_ISO_DATE);
-        String lockKey = PURCHASE_LOCK_PREFIX + datePart;
-        String lockValue = Thread.currentThread().getId() + "-" + System.nanoTime();
-
-        try {
-            long startWaitTime = System.currentTimeMillis();
-            while (System.currentTimeMillis() - startWaitTime < PURCHASE_LOCK_WAIT_TIMEOUT * 1000) {
-                Boolean locked = redisTemplate.opsForValue().setIfAbsent(lockKey, lockValue, PURCHASE_LOCK_EXPIRE_TIME, TimeUnit.SECONDS);
-                if (Boolean.TRUE.equals(locked)) {
-                    break;
-                }
-                try {
-                    Thread.sleep(100);
-                } catch (InterruptedException e) {
-                    Thread.currentThread().interrupt();
-                    throw new RuntimeException("鑾峰彇閿佹椂琚腑鏂�", e);
-                }
-            }
-
-            if (Boolean.FALSE.equals(redisTemplate.hasKey(lockKey))) {
-                throw new RuntimeException("鑾峰彇閲囪喘鍚堝悓缂栧彿鐢熸垚閿佸け璐ワ細瓒呮椂");
-            }
-
-            String prefix = "CG-" + datePart + "-";
-            List<PurchaseLedger> existingList = purchaseLedgerMapper.selectList(
-                    new LambdaQueryWrapper<PurchaseLedger>()
-                            .likeRight(PurchaseLedger::getPurchaseContractNumber, prefix)
-                            .select(PurchaseLedger::getPurchaseContractNumber));
-            List<Integer> existingSequences = existingList.stream()
-                    .map(PurchaseLedger::getPurchaseContractNumber)
-                    .filter(Objects::nonNull)
-                    .map(no -> {
-                        int lastDash = no.lastIndexOf('-');
-                        if (lastDash >= 0) {
-                            try {
-                                return Integer.parseInt(no.substring(lastDash + 1));
-                            } catch (NumberFormatException e) {
-                                return 0;
-                            }
-                        }
-                        return 0;
-                    })
-                    .collect(Collectors.toList());
-            int nextSequence = findFirstMissingSequence(existingSequences);
-
-            return prefix + String.format("%03d", nextSequence);
-        } finally {
-            String luaScript = "if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) else return 0 end";
-            redisTemplate.execute(
-                    new org.springframework.data.redis.core.script.DefaultRedisScript<>(luaScript, Long.class),
-                    Collections.singletonList(lockKey),
-                    lockValue
-            );
+    @Override
+    public Map<String, Object> getPrintData(Long id) {
+        PurchaseLedger purchaseLedger = getById(id);
+        if (purchaseLedger == null) {
+            return null;
         }
-    }
-
-    private int findFirstMissingSequence(List<Integer> sequences) {
-        if (sequences.isEmpty()) {
-            return 1;
-        }
-        sequences.sort(Integer::compareTo);
-        int next = 1;
-        for (int seq : sequences) {
-            if (seq == next) {
-                next++;
-            } else if (seq > next) {
-                break;
-            }
-        }
-        return next;
+        List<SalesLedgerProduct> products = salesLedgerProductMapper.selectList(
+            new LambdaQueryWrapper<SalesLedgerProduct>()
+                .eq(SalesLedgerProduct::getSalesLedgerId, id)
+                .eq(SalesLedgerProduct::getType, 2)
+        );
+        SysDept dept = sysDeptMapper.selectDeptById(100L);
+        Map<String, Object> result = new HashMap<>();
+        result.put("companyName", dept != null ? dept.getDeptName() : "");
+        result.put("ledger", purchaseLedger);
+        result.put("products", products);
+        return result;
     }
 }

--
Gitblit v1.9.3