From cae863f681a84b968b646d2522c4f5678ef76d9c Mon Sep 17 00:00:00 2001
From: yuan <123@>
Date: 星期五, 14 八月 2026 16:51:47 +0800
Subject: [PATCH] fix: 优化采购台账数据导入逻辑,增强数据校验和处理
---
src/main/java/com/ruoyi/purchase/service/impl/PurchaseLedgerServiceImpl.java | 540 +++++++++++++++++++++++++++++++++++++++++------------------
1 files changed, 372 insertions(+), 168 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 da202a3..1972f03 100644
--- a/src/main/java/com/ruoyi/purchase/service/impl/PurchaseLedgerServiceImpl.java
+++ b/src/main/java/com/ruoyi/purchase/service/impl/PurchaseLedgerServiceImpl.java
@@ -1,6 +1,7 @@
package com.ruoyi.purchase.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
@@ -20,6 +21,7 @@
import com.ruoyi.basic.utils.FileUtil;
import com.ruoyi.common.enums.FileNameType;
import com.ruoyi.common.exception.base.BaseException;
+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;
@@ -28,19 +30,15 @@
import com.ruoyi.other.mapper.TempFileMapper;
import com.ruoyi.procurementrecord.mapper.ProcurementRecordMapper;
import com.ruoyi.procurementrecord.pojo.ProcurementRecordStorage;
+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;
import com.ruoyi.purchase.dto.PurchaseLedgerProductImportDto;
-import com.ruoyi.purchase.mapper.PaymentRegistrationMapper;
-import com.ruoyi.purchase.mapper.ProductRecordMapper;
import com.ruoyi.purchase.mapper.PurchaseLedgerMapper;
-import com.ruoyi.purchase.mapper.TicketRegistrationMapper;
-import com.ruoyi.purchase.pojo.PaymentRegistration;
-import com.ruoyi.purchase.pojo.ProductRecord;
import com.ruoyi.purchase.pojo.PurchaseLedger;
-import com.ruoyi.purchase.pojo.TicketRegistration;
import com.ruoyi.purchase.service.IPurchaseLedgerService;
import com.ruoyi.quality.mapper.QualityInspectMapper;
import com.ruoyi.quality.mapper.QualityInspectParamMapper;
@@ -51,11 +49,9 @@
import com.ruoyi.quality.pojo.QualityTestStandard;
import com.ruoyi.quality.pojo.QualityTestStandardParam;
import com.ruoyi.sales.mapper.CommonFileMapper;
-import com.ruoyi.sales.mapper.InvoiceRegistrationProductMapper;
import com.ruoyi.sales.mapper.SalesLedgerMapper;
import com.ruoyi.sales.mapper.SalesLedgerProductMapper;
import com.ruoyi.sales.pojo.CommonFile;
-import com.ruoyi.sales.pojo.InvoiceRegistrationProduct;
import com.ruoyi.sales.pojo.SalesLedger;
import com.ruoyi.sales.pojo.SalesLedgerProduct;
import com.ruoyi.sales.service.impl.CommonFileServiceImpl;
@@ -69,7 +65,7 @@
import java.io.InputStream;
import java.math.BigDecimal;
-import java.math.RoundingMode;
+import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
@@ -89,20 +85,19 @@
@RequiredArgsConstructor
public class PurchaseLedgerServiceImpl extends ServiceImpl<PurchaseLedgerMapper, PurchaseLedger> implements IPurchaseLedgerService {
+ private static final Long IMPORT_PRODUCT_PARENT_ID = 3L;
+
private final PurchaseLedgerMapper purchaseLedgerMapper;
private final SalesLedgerMapper salesLedgerMapper;
private final SalesLedgerProductMapper salesLedgerProductMapper;
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;
private final SysUserMapper sysUserMapper;
- private final TicketRegistrationMapper ticketRegistrationMapper;
- private final ProductRecordMapper productRecordMapper;
- private final PaymentRegistrationMapper paymentRegistrationMapper;
- private final InvoiceRegistrationProductMapper invoiceRegistrationProductMapper;
private final StringRedisTemplate redisTemplate;
private final QualityInspectMapper qualityInspectMapper;
private final CommonFileServiceImpl commonFileService;
@@ -134,6 +129,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());
@@ -173,14 +169,14 @@
}
purchaseLedgerMapper.updateById(purchaseLedger);
}
- // 6.閲囪喘瀹℃牳鏂板锛涘鎵圭鐞嗘湭閰嶇疆閲囪喘瀹℃壒浜烘椂锛屽鎵规湇鍔′細鑷姩缃负瀹℃壒閫氳繃銆�
- addApproveByPurchase(loginUser, purchaseLedger);
// 4. 澶勭悊瀛愯〃鏁版嵁
List<SalesLedgerProduct> productList = purchaseLedgerDto.getProductData();
if (productList != null && !productList.isEmpty()) {
handleSalesLedgerProducts(purchaseLedger.getId(), productList, purchaseLedgerDto.getType());
}
+ // 6.閲囪喘瀹℃牳鏂板锛涘鎵圭鐞嗘湭閰嶇疆閲囪喘瀹℃壒浜烘椂锛屽鎵规湇鍔′細鑷姩缃负瀹℃壒閫氳繃銆�
+ addApproveByPurchase(loginUser, purchaseLedger);
// 5. 杩佺Щ涓存椂鏂囦欢鍒版寮忕洰褰�
fileUtil.saveStorageAttachment(ApplicationTypeEnum.FILE, RecordTypeEnum.PURCHASE_LEDGER, purchaseLedger.getId(), purchaseLedgerDto.getStorageBlobDTOS());
return 1;
@@ -247,6 +243,7 @@
// 璁剧疆瀛楁
for (SalesLedgerProduct product : products) {
+ AmountUtils.normalizeSalesLedgerProduct(product);
product.setSalesLedgerId(salesLedgerId);
Long productId = product.getProductId();
@@ -283,18 +280,15 @@
LocalDateTime localDateTime = entryDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
salesLedgerProduct.setRegisterDate(localDateTime);
- salesLedgerProduct.setFutureTickets(salesLedgerProduct.getQuantity());
- salesLedgerProduct.setFutureTicketsAmount(salesLedgerProduct.getTaxInclusiveTotalPrice());
- salesLedgerProduct.setPendingTicketsTotal(salesLedgerProduct.getTaxInclusiveTotalPrice());
salesLedgerProductMapper.insert(salesLedgerProduct);
}
}
// 璁$畻鎬诲惈绋庨噾棰�
- 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) {
@@ -333,18 +327,6 @@
queryWrapper.in(SalesLedgerProduct::getSalesLedgerId, ids)
.eq(SalesLedgerProduct::getType, 2);
salesLedgerProductMapper.delete(queryWrapper);
- // 鎵归噺鍒犻櫎鍏宠仈鐨勯噰璐彴璐︾殑鏉ョエ鐧昏
- LambdaQueryWrapper<TicketRegistration> ticketRegistrationLambdaQueryWrapper = new LambdaQueryWrapper<>();
- ticketRegistrationLambdaQueryWrapper.in(TicketRegistration::getPurchaseLedgerId,ids);
- ticketRegistrationMapper.delete(ticketRegistrationLambdaQueryWrapper);
- // 鎵归噺鍒犻櫎鍏宠仈鐨勯噰璐彴璐︾殑鏉ョエ鐧昏璁板綍
- LambdaQueryWrapper<ProductRecord> productRecordLambdaQueryWrapper = new LambdaQueryWrapper<>();
- productRecordLambdaQueryWrapper.in(ProductRecord::getPurchaseLedgerId,ids);
- productRecordMapper.delete(productRecordLambdaQueryWrapper);
- // 鎵归噺鍒犻櫎浠樻鐧昏
- LambdaQueryWrapper<PaymentRegistration> paymentRegistrationLambdaQueryWrapper = new LambdaQueryWrapper<>();
- paymentRegistrationLambdaQueryWrapper.in(PaymentRegistration::getPurchaseLedgerId, ids);
- paymentRegistrationMapper.delete(paymentRegistrationLambdaQueryWrapper);
//鎵归噺鍒犻櫎妫�楠屾爣鍑�
LambdaQueryWrapper<QualityInspect> materialInspectLambdaQueryWrapper = new LambdaQueryWrapper<>();
materialInspectLambdaQueryWrapper.in(QualityInspect::getPurchaseLedgerId, ids);
@@ -404,7 +386,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()));
@@ -447,14 +431,7 @@
queryWrapper.eq(SalesLedgerProduct::getSalesLedgerId, purchaseLedger.getId())
.eq(SalesLedgerProduct::getType, 2);
List<SalesLedgerProduct> productList = salesLedgerProductMapper.selectList(queryWrapper);
- productList.forEach(product -> {
- product.setFutureTickets(product.getFutureTickets() != null ? product.getFutureTickets() : product.getQuantity());
- product.setFutureTicketsAmount(product.getFutureTicketsAmount() != null ? product.getFutureTicketsAmount() : product.getTaxInclusiveTotalPrice());
- product.setTicketsNum(null);
- product.setTicketsAmount(null);
- product.setTempFutureTickets(product.getFutureTickets());
- product.setTempFutureTicketsAmount(product.getFutureTicketsAmount());
- });
+ AmountUtils.normalizeSalesLedgerProducts(productList);
resultDto.setProductData(productList);
return resultDto;
}
@@ -481,35 +458,19 @@
PurchaseLedger purchaseLedger = purchaseLedgerMapper.selectById(id);
BeanUtils.copyProperties(purchaseLedger, purchaseLedgerDto);
-// TicketRegistration ticketRegistration = ticketRegistrationMapper.selectOne(new LambdaQueryWrapper<TicketRegistration>().eq(TicketRegistration::getPurchaseLedgerId, id));
-// if (ticketRegistration != null) {
-// purchaseLedgerDto.setInvoiceNumber(ticketRegistration.getInvoiceNumber());
-// purchaseLedgerDto.setInvoiceAmount(ticketRegistration.getInvoiceAmount());
-// purchaseLedgerDto.setTicketRegistrationId(ticketRegistration.getId());
-// }
return purchaseLedgerDto;
}
@Override
public IPage<PurchaseLedgerDto> selectPurchaseLedgerListPage(IPage ipage, PurchaseLedgerDto purchaseLedger) {
- IPage<PurchaseLedgerDto> purchaseLedgerDtoIPage = purchaseLedgerMapper.selectPurchaseLedgerListPage(ipage, purchaseLedger);
- purchaseLedgerDtoIPage.getRecords().forEach(purchaseLedgerDto -> {
- List<CommonFile> commonFiles = commonFileMapper.selectList(new LambdaQueryWrapper<CommonFile>().eq(CommonFile::getCommonId, purchaseLedgerDto.getId()).eq(CommonFile::getType, FileNameType.PURCHASE.getValue()));
- purchaseLedgerDto.setSalesLedgerFiles(commonFiles);
- });
- return purchaseLedgerDtoIPage;
- }
-
- @Override
- public List<InvoiceRegistrationProduct> getProductBySalesNo(Long id) {
- List<InvoiceRegistrationProduct> invoiceRegistrationProducts = invoiceRegistrationProductMapper.selectList(new LambdaQueryWrapper<InvoiceRegistrationProduct>()
- .select(InvoiceRegistrationProduct::getId, InvoiceRegistrationProduct::getProductCategory, InvoiceRegistrationProduct::getSpecificationModel,
- InvoiceRegistrationProduct::getUnit, InvoiceRegistrationProduct::getQuantity)
- .eq(InvoiceRegistrationProduct::getSalesLedgerId, id));
- if (invoiceRegistrationProducts.isEmpty()) {
- return new ArrayList<>();
+ IPage<PurchaseLedgerDto> page = purchaseLedgerMapper.selectPurchaseLedgerListPage(ipage, purchaseLedger);
+ if (!CollectionUtils.isEmpty(page.getRecords())) {
+ page.getRecords().forEach(record -> {
+ AmountUtils.normalizeContractAmount(record);
+ AmountUtils.normalizeSalesLedgerProducts(record.getProductData());
+ });
}
- return invoiceRegistrationProducts;
+ return page;
}
@Override
@@ -536,115 +497,336 @@
@Transactional(rollbackFor = Exception.class)
public AjaxResult importData(MultipartFile file) {
LoginUser loginUser = SecurityUtils.getLoginUser();
- try {
- InputStream inputStream = file.getInputStream();
- ExcelUtil<PurchaseLedgerImportDto> salesLedgerImportDtoExcelUtil = new ExcelUtil<>(PurchaseLedgerImportDto.class);
- Map<String, List<PurchaseLedgerImportDto>> stringListMap = salesLedgerImportDtoExcelUtil.importExcelMultiSheet(Arrays.asList("閲囪喘鍙拌处鏁版嵁", "閲囪喘浜у搧鏁版嵁"), inputStream, 0);
- if (CollectionUtils.isEmpty(stringListMap)) return AjaxResult.error("閲囪喘琛ㄦ牸涓虹┖锛�");
- // 涓氬姟灞傚悎骞�
- List<PurchaseLedgerImportDto> salesLedgerImportDtoList = stringListMap.get("閲囪喘鍙拌处鏁版嵁");
- if (CollectionUtils.isEmpty(salesLedgerImportDtoList)) return AjaxResult.error("閲囪喘鍙拌处鏁版嵁涓虹┖锛�");
- List<PurchaseLedgerImportDto> salesLedgerProductImportDtoList = stringListMap.get("閲囪喘浜у搧鏁版嵁");
- if (CollectionUtils.isEmpty(salesLedgerProductImportDtoList)) return AjaxResult.error("閲囪喘浜у搧鏁版嵁涓虹┖锛�");
- // 渚涘簲鍟嗘暟鎹�
- List<SupplierManage> customers = supplierManageMapper.selectList(new LambdaQueryWrapper<SupplierManage>().in(SupplierManage::getSupplierName,
- salesLedgerImportDtoList.stream().map(PurchaseLedgerImportDto::getSupplierName).collect(Collectors.toList())));
- List<Map<String,Object>> list = productModelMapper.getProductAndModelList();
- // 褰曞叆浜烘暟鎹�
- List<SysUser> sysUsers = sysUserMapper.selectList(new LambdaQueryWrapper<SysUser>().in(SysUser::getNickName,
- salesLedgerImportDtoList.stream().map(PurchaseLedgerImportDto::getRecorderName).collect(Collectors.toList())));
- for (PurchaseLedgerImportDto salesLedgerImportDto : salesLedgerImportDtoList) {
- PurchaseLedger purchaseLedger = purchaseLedgerMapper.selectOne(new LambdaQueryWrapper<PurchaseLedger>()
- .eq(PurchaseLedger::getPurchaseContractNumber, salesLedgerImportDto.getPurchaseContractNumber())
- .last("limit 1"));
- if(purchaseLedger != null){
- continue;
- }
- PurchaseLedger salesLedger = new PurchaseLedger();
- BeanUtils.copyProperties(salesLedgerImportDto, salesLedger);
- // 閫氳繃渚涘簲鍟嗗悕绉版煡璇D
- salesLedger.setSupplierId(customers.stream()
- .filter(customer -> customer.getSupplierName().equals(salesLedger.getSupplierName()))
- .findFirst()
- .map(SupplierManage::getId)
- .orElse(null));
- Long aLong = sysUsers.stream()
- .filter(sysUser -> sysUser.getNickName().equals(salesLedger.getRecorderName()))
- .findFirst()
- .map(SysUser::getUserId)
- .orElse(null);
- if (aLong == null)
- throw new RuntimeException("褰曞叆浜�:" + salesLedger.getRecorderName() + ",鏃犲搴旂敤鎴凤紒");
- salesLedger.setRecorderId(aLong);
- // 閲囪喘浜у搧鏁版嵁缁戝畾锛岄�氳繃閲囪喘鍗曞彿鑾峰彇瀵瑰簲閲囪喘浜у搧鏁版嵁
- List<PurchaseLedgerProductImportDto> salesLedgerProductImportDtos = salesLedgerProductImportDtoList.stream()
- .filter(salesLedgerProductImportDto -> salesLedgerProductImportDto.getPurchaseContractNumber().equals(salesLedger.getPurchaseContractNumber()))
- .collect(Collectors.toList());
- if (CollectionUtils.isEmpty(salesLedgerProductImportDtos))
- throw new RuntimeException("閲囪喘鍗曞彿:" + salesLedgerImportDto.getPurchaseContractNumber() + ",鏃犲搴斾骇鍝佹暟鎹紒");
- salesLedger.setContractAmount(salesLedgerProductImportDtos.stream()
- .map(PurchaseLedgerProductImportDto::getTaxInclusiveTotalPrice)
- .reduce(BigDecimal.ZERO,BigDecimal::add));
- // 閫氳繃閿�鍞崟鍙风粦瀹氶攢鍞�
- SalesLedger salesLedger1 = salesLedgerMapper.selectOne(new LambdaQueryWrapper<SalesLedger>()
- .eq(SalesLedger::getSalesContractNo, salesLedger.getSalesContractNo())
- .last("LIMIT 1"));
- if(salesLedger1 != null){
- salesLedger.setSalesLedgerId(salesLedger1.getId());
- }
- if (StringUtils.hasText(salesLedger.getApproveUserIds())) {
- // 閲囪喘瀹℃牳锛氬巻鍙插鍏ユā鏉夸紶瀹℃壒浜哄鍚嶆椂锛岀户缁吋瀹硅浆鎹负鐢ㄦ埛ID銆�
- String[] split = salesLedger.getApproveUserIds().split("锛�");
- List<Long> ids = new ArrayList<>();
- for (int i = 0; i < split.length; i++) {
- SysUser sysUser = sysUserMapper.selectOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getNickName, split[i])
- .last("LIMIT 1"));
- if (sysUser != null) {
- ids.add(sysUser.getUserId());
- }
- }
- // 灏嗛泦鍚堣浆涓哄瓧绗︿覆锛岄殧寮�
- String collect = ids.stream().map(Object::toString).collect(Collectors.joining(","));
- salesLedger.setApproveUserIds(collect);
- }
- purchaseLedgerMapper.insert(salesLedger);
-
- for (PurchaseLedgerProductImportDto salesLedgerProductImportDto : salesLedgerProductImportDtos) {
- SalesLedgerProduct salesLedgerProduct = new SalesLedgerProduct();
- BeanUtils.copyProperties(salesLedgerProductImportDto, salesLedgerProduct);
- salesLedgerProduct.setSalesLedgerId(salesLedger.getId());
- salesLedgerProduct.setType(2);
- // 璁$畻涓嶅惈绋庢�讳环
- salesLedgerProduct.setTaxExclusiveTotalPrice(salesLedgerProduct.getTaxInclusiveTotalPrice().divide(new BigDecimal(1).add(salesLedgerProduct.getTaxRate().divide(new BigDecimal(100))), 2, RoundingMode.HALF_UP));
- salesLedgerProduct.setFutureTickets(salesLedgerProduct.getQuantity());
- salesLedgerProduct.setFutureTicketsAmount(salesLedgerProduct.getTaxExclusiveTotalPrice());
- list.stream()
- .filter(map -> map.get("productName").equals(salesLedgerProduct.getProductCategory()) && map.get("model").equals(salesLedgerProduct.getSpecificationModel()))
- .findFirst()
- .ifPresent(map -> {
- salesLedgerProduct.setProductModelId(Long.parseLong(map.get("modelId").toString()));
- salesLedgerProduct.setProductId(Long.parseLong(map.get("id").toString()));
- });
- salesLedgerProduct.setRegister(loginUser.getNickName());
- salesLedgerProduct.setRegisterDate(LocalDateTime.now());
- salesLedgerProduct.setApproveStatus(0);
- salesLedgerProduct.setPendingTicketsTotal(salesLedgerProductImportDto.getTaxInclusiveTotalPrice());
- // 鏄惁璐ㄦ鍒ゆ柇
- salesLedgerProduct.setIsChecked(salesLedgerProductImportDto.getIsChecked() == 1);
- if(salesLedgerProductImportDto.getIsChecked() == 1){
- addQualityInspect(salesLedger, salesLedgerProduct);
- }
- salesLedgerProductMapper.insert(salesLedgerProduct);
- }
- // 閲囪喘瀹℃牳
- addApproveByPurchase(loginUser,salesLedger);
+ try (InputStream inputStream = file.getInputStream()) {
+ ExcelUtil<PurchaseLedgerImportDto> excelUtil = new ExcelUtil<>(PurchaseLedgerImportDto.class);
+ Map<String, List<PurchaseLedgerImportDto>> sheetData = excelUtil.importExcelMultiSheet(
+ Arrays.asList("閲囪喘鍙拌处鏁版嵁", "閲囪喘浜у搧鏁版嵁"), inputStream, 0);
+ if (CollectionUtils.isEmpty(sheetData)) {
+ return AjaxResult.error("閲囪喘琛ㄦ牸涓虹┖锛�");
}
- return AjaxResult.success("瀵煎叆鎴愬姛");
+ List<PurchaseLedgerImportDto> purchaseImports = sheetData.get("閲囪喘鍙拌处鏁版嵁");
+ if (CollectionUtils.isEmpty(purchaseImports)) {
+ return AjaxResult.error("閲囪喘鍙拌处鏁版嵁涓虹┖锛�");
+ }
+ List<PurchaseLedgerImportDto> productImports = sheetData.get("閲囪喘浜у搧鏁版嵁");
+ if (CollectionUtils.isEmpty(productImports)) {
+ return AjaxResult.error("閲囪喘浜у搧鏁版嵁涓虹┖锛�");
+ }
+
+ List<String> supplierNames = purchaseImports.stream()
+ .map(PurchaseLedgerImportDto::getSupplierName)
+ .filter(StringUtils::hasText)
+ .map(StringUtils::trim)
+ .distinct()
+ .collect(Collectors.toList());
+ Map<String, SupplierManage> supplierMap = CollectionUtils.isEmpty(supplierNames)
+ ? Collections.emptyMap()
+ : supplierManageMapper.selectList(new LambdaQueryWrapper<SupplierManage>()
+ .in(SupplierManage::getSupplierName, supplierNames))
+ .stream()
+ .collect(Collectors.toMap(
+ supplier -> StringUtils.trim(supplier.getSupplierName()),
+ supplier -> supplier,
+ (first, ignored) -> first));
+
+ List<String> recorderNames = purchaseImports.stream()
+ .map(PurchaseLedgerImportDto::getRecorderName)
+ .filter(StringUtils::hasText)
+ .map(StringUtils::trim)
+ .distinct()
+ .collect(Collectors.toList());
+ Map<String, SysUser> recorderMap = CollectionUtils.isEmpty(recorderNames)
+ ? Collections.emptyMap()
+ : sysUserMapper.selectList(new LambdaQueryWrapper<SysUser>()
+ .in(SysUser::getNickName, recorderNames))
+ .stream()
+ .collect(Collectors.toMap(
+ user -> StringUtils.trim(user.getNickName()),
+ user -> user,
+ (first, ignored) -> first));
+
+ Map<String, ProductModel> importedProductModelCache = new HashMap<>();
+ int addedCount = 0;
+ int overwrittenCount = 0;
+ int skippedCount = 0;
+
+ for (PurchaseLedgerImportDto purchaseImport : purchaseImports) {
+ String purchaseContractNumber = requireImportText(
+ purchaseImport.getPurchaseContractNumber(), "閲囪喘鍗曞彿涓嶈兘涓虹┖锛�");
+ purchaseImport.setPurchaseContractNumber(purchaseContractNumber);
+ purchaseImport.setSupplierName(StringUtils.trim(purchaseImport.getSupplierName()));
+ purchaseImport.setProjectName(StringUtils.trim(purchaseImport.getProjectName()));
+ purchaseImport.setRecorderName(StringUtils.trim(purchaseImport.getRecorderName()));
+
+ List<PurchaseLedgerProductImportDto> purchaseProducts = productImports.stream()
+ .filter(productImport -> sameImportText(
+ productImport.getPurchaseContractNumber(), purchaseContractNumber))
+ .map(productImport -> (PurchaseLedgerProductImportDto) productImport)
+ .collect(Collectors.toList());
+ if (CollectionUtils.isEmpty(purchaseProducts)) {
+ throw new BaseException("閲囪喘鍗曞彿:" + purchaseContractNumber + ",鏃犲搴斾骇鍝佹暟鎹紒");
+ }
+
+ List<PurchaseLedger> existingLedgers = purchaseLedgerMapper.selectList(
+ new LambdaQueryWrapper<PurchaseLedger>()
+ .eq(PurchaseLedger::getPurchaseContractNumber, purchaseContractNumber));
+ PurchaseLedger ledgerToOverwrite = existingLedgers.stream()
+ .filter(existing -> Objects.equals(existing.getApprovalStatus(), 1))
+ .filter(existing -> isSameImportedPurchase(existing, purchaseImport))
+ .findFirst()
+ .orElse(null);
+ if (ledgerToOverwrite == null && CollectionUtils.isNotEmpty(existingLedgers)) {
+ skippedCount++;
+ continue;
+ }
+
+ PurchaseLedger purchaseLedger = buildImportedPurchaseLedger(
+ purchaseImport, purchaseProducts, supplierMap, recorderMap);
+ boolean overwrite = ledgerToOverwrite != null;
+ if (overwrite) {
+ purchaseLedger.setId(ledgerToOverwrite.getId());
+ purchaseLedger.setApprovalStatus(1);
+ updateImportedPurchaseLedger(purchaseLedger);
+ clearImportedPurchaseContents(purchaseLedger.getId(), purchaseContractNumber);
+ overwrittenCount++;
+ } else {
+ purchaseLedger.setApprovalStatus(1);
+ purchaseLedgerMapper.insert(purchaseLedger);
+ addedCount++;
+ }
+
+ for (PurchaseLedgerProductImportDto productImport : purchaseProducts) {
+ ProductModel productModel = findOrCreateImportedProductModel(
+ productImport, importedProductModelCache);
+ SalesLedgerProduct purchaseProduct = new SalesLedgerProduct();
+ BeanUtils.copyProperties(productImport, purchaseProduct);
+ purchaseProduct.setSalesLedgerId(purchaseLedger.getId());
+ purchaseProduct.setType(2);
+ purchaseProduct.setProductId(productModel.getProductId());
+ purchaseProduct.setProductModelId(productModel.getId());
+ AmountUtils.normalizeSalesLedgerProduct(purchaseProduct);
+ purchaseProduct.setTaxExclusiveTotalPrice(
+ AmountUtils.calcTaxExclusiveTotalPrice(
+ purchaseProduct.getTaxInclusiveTotalPrice(),
+ purchaseProduct.getTaxRate()));
+ purchaseProduct.setRegister(loginUser.getNickName());
+ purchaseProduct.setRegisterDate(LocalDateTime.now());
+ purchaseProduct.setApproveStatus(0);
+ purchaseProduct.setIsChecked(Objects.equals(productImport.getIsChecked(), 1));
+ salesLedgerProductMapper.insert(purchaseProduct);
+ if (Boolean.TRUE.equals(purchaseProduct.getIsChecked())) {
+ addQualityInspect(purchaseLedger, purchaseProduct);
+ }
+ }
+
+ if (!overwrite) {
+ addApproveByPurchase(loginUser, purchaseLedger);
+ }
+ }
+
+ return AjaxResult.success(String.format(
+ "瀵煎叆鎴愬姛锛氭柊澧�%d鏉★紝瑕嗙洊%d鏉★紝璺宠繃%d鏉�", addedCount, overwrittenCount, skippedCount));
+ } catch (BaseException e) {
+ log.error("瀵煎叆閲囪喘鍙拌处澶辫触锛歿}", e.getMessage(), e);
+ throw e;
} catch (Exception e) {
- e.printStackTrace();
+ log.error("瀵煎叆閲囪喘鍙拌处澶辫触", e);
+ throw new BaseException("瀵煎叆澶辫触锛�" + e.getMessage());
}
- return AjaxResult.success("瀵煎叆澶辫触");
+ }
+
+ private PurchaseLedger buildImportedPurchaseLedger(
+ PurchaseLedgerImportDto purchaseImport,
+ List<PurchaseLedgerProductImportDto> purchaseProducts,
+ Map<String, SupplierManage> supplierMap,
+ Map<String, SysUser> recorderMap) {
+ PurchaseLedger purchaseLedger = new PurchaseLedger();
+ BeanUtils.copyProperties(purchaseImport, purchaseLedger);
+
+ SupplierManage supplier = supplierMap.get(purchaseLedger.getSupplierName());
+ purchaseLedger.setSupplierId(supplier == null ? null : supplier.getId());
+
+ SysUser recorder = recorderMap.get(purchaseLedger.getRecorderName());
+ if (recorder == null) {
+ throw new BaseException("褰曞叆浜�:" + purchaseLedger.getRecorderName() + ",鏃犲搴旂敤鎴凤紒");
+ }
+ purchaseLedger.setRecorderId(recorder.getUserId());
+ purchaseLedger.setContractAmount(purchaseProducts.stream()
+ .map(PurchaseLedgerProductImportDto::getTaxInclusiveTotalPrice)
+ .filter(Objects::nonNull)
+ .reduce(BigDecimal.ZERO, BigDecimal::add));
+
+ if (StringUtils.hasText(purchaseLedger.getSalesContractNo())) {
+ SalesLedger salesLedger = salesLedgerMapper.selectOne(new LambdaQueryWrapper<SalesLedger>()
+ .eq(SalesLedger::getSalesContractNo, purchaseLedger.getSalesContractNo())
+ .last("LIMIT 1"));
+ purchaseLedger.setSalesLedgerId(salesLedger == null ? null : salesLedger.getId());
+ } else {
+ purchaseLedger.setSalesLedgerId(null);
+ }
+ purchaseLedger.setApproveUserIds(convertImportedApproverNames(purchaseLedger.getApproveUserIds()));
+ return purchaseLedger;
+ }
+
+ private String convertImportedApproverNames(String approverNames) {
+ if (!StringUtils.hasText(approverNames)) {
+ return approverNames;
+ }
+ List<Long> userIds = new ArrayList<>();
+ for (String approverName : approverNames.split("[锛�,]")) {
+ String trimmedName = StringUtils.trim(approverName);
+ if (!StringUtils.hasText(trimmedName)) {
+ continue;
+ }
+ SysUser user = sysUserMapper.selectOne(new LambdaQueryWrapper<SysUser>()
+ .eq(SysUser::getNickName, trimmedName)
+ .last("LIMIT 1"));
+ if (user != null) {
+ userIds.add(user.getUserId());
+ }
+ }
+ return userIds.stream().map(String::valueOf).collect(Collectors.joining(","));
+ }
+
+ private ProductModel findOrCreateImportedProductModel(
+ PurchaseLedgerProductImportDto productImport,
+ Map<String, ProductModel> cache) {
+ String productCategory = requireImportText(
+ productImport.getProductCategory(), "閲囪喘浜у搧鐨勪骇鍝佸ぇ绫讳笉鑳戒负绌猴紒");
+ String specificationModel = StringUtils.trim(productImport.getSpecificationModel());
+ if (!StringUtils.hasText(specificationModel)) {
+ specificationModel = productCategory;
+ }
+ productImport.setProductCategory(productCategory);
+ productImport.setSpecificationModel(specificationModel);
+ productImport.setUnit(StringUtils.trim(productImport.getUnit()));
+
+ String cacheKey = productCategory + "::" + specificationModel;
+ ProductModel cachedModel = cache.get(cacheKey);
+ if (cachedModel != null) {
+ return cachedModel;
+ }
+
+ List<Product> sameNameProducts = productMapper.selectList(new LambdaQueryWrapper<Product>()
+ .eq(Product::getProductName, productCategory));
+ for (Product product : sameNameProducts) {
+ ProductModel existingModel = productModelMapper.selectOne(new LambdaQueryWrapper<ProductModel>()
+ .eq(ProductModel::getProductId, product.getId())
+ .eq(ProductModel::getModel, specificationModel)
+ .last("LIMIT 1"));
+ if (existingModel != null) {
+ cache.put(cacheKey, existingModel);
+ return existingModel;
+ }
+ }
+
+ Product product = sameNameProducts.stream()
+ .filter(item -> Objects.equals(item.getParentId(), IMPORT_PRODUCT_PARENT_ID))
+ .findFirst()
+ .orElse(null);
+ if (product == null) {
+ product = new Product();
+ product.setParentId(IMPORT_PRODUCT_PARENT_ID);
+ product.setProductName(productCategory);
+ productMapper.insert(product);
+ }
+
+ ProductModel productModel = new ProductModel();
+ productModel.setProductId(product.getId());
+ productModel.setModel(specificationModel);
+ productModel.setUnit(productImport.getUnit());
+ productModel.setProductCode(specificationModel + "-001");
+ productModelMapper.insert(productModel);
+ cache.put(cacheKey, productModel);
+ return productModel;
+ }
+
+ private void updateImportedPurchaseLedger(PurchaseLedger purchaseLedger) {
+ purchaseLedgerMapper.update(null, new LambdaUpdateWrapper<PurchaseLedger>()
+ .eq(PurchaseLedger::getId, purchaseLedger.getId())
+ .set(PurchaseLedger::getPurchaseContractNumber, purchaseLedger.getPurchaseContractNumber())
+ .set(PurchaseLedger::getSupplierId, purchaseLedger.getSupplierId())
+ .set(PurchaseLedger::getSupplierName, purchaseLedger.getSupplierName())
+ .set(PurchaseLedger::getRecorderId, purchaseLedger.getRecorderId())
+ .set(PurchaseLedger::getRecorderName, purchaseLedger.getRecorderName())
+ .set(PurchaseLedger::getSalesContractNo, purchaseLedger.getSalesContractNo())
+ .set(PurchaseLedger::getProjectName, purchaseLedger.getProjectName())
+ .set(PurchaseLedger::getEntryDate, purchaseLedger.getEntryDate())
+ .set(PurchaseLedger::getExecutionDate, purchaseLedger.getExecutionDate())
+ .set(PurchaseLedger::getRemarks, purchaseLedger.getRemarks())
+ .set(PurchaseLedger::getSalesLedgerId, purchaseLedger.getSalesLedgerId())
+ .set(PurchaseLedger::getContractAmount, purchaseLedger.getContractAmount())
+ .set(PurchaseLedger::getPaymentMethod, purchaseLedger.getPaymentMethod())
+ .set(PurchaseLedger::getApproveUserIds, purchaseLedger.getApproveUserIds())
+ .set(PurchaseLedger::getApprovalStatus, 1)
+ .set(PurchaseLedger::getUpdatedAt, new Date()));
+ }
+
+ private void clearImportedPurchaseContents(Long purchaseLedgerId, String purchaseContractNumber) {
+ List<QualityInspect> qualityInspects = qualityInspectMapper.selectList(
+ new LambdaQueryWrapper<QualityInspect>()
+ .eq(QualityInspect::getPurchaseLedgerId, purchaseLedgerId));
+ boolean hasSubmittedInspect = qualityInspects.stream()
+ .anyMatch(inspect -> Objects.equals(inspect.getInspectState(), 1));
+ if (hasSubmittedInspect) {
+ throw new BaseException("閲囪喘鍗曞彿:" + purchaseContractNumber + ",瀛樺湪宸叉彁浜ょ殑妫�楠屽崟锛屼笉鑳借鐩栵紒");
+ }
+ List<Long> inspectIds = qualityInspects.stream()
+ .map(QualityInspect::getId)
+ .collect(Collectors.toList());
+ if (CollectionUtils.isNotEmpty(inspectIds)) {
+ qualityInspectParamMapper.delete(new LambdaQueryWrapper<QualityInspectParam>()
+ .in(QualityInspectParam::getInspectId, inspectIds));
+ qualityInspectMapper.delete(new LambdaQueryWrapper<QualityInspect>()
+ .eq(QualityInspect::getPurchaseLedgerId, purchaseLedgerId));
+ }
+
+ List<SalesLedgerProduct> existingProducts = salesLedgerProductMapper.selectList(
+ new LambdaQueryWrapper<SalesLedgerProduct>()
+ .eq(SalesLedgerProduct::getSalesLedgerId, purchaseLedgerId)
+ .eq(SalesLedgerProduct::getType, 2));
+ for (SalesLedgerProduct existingProduct : existingProducts) {
+ procurementRecordStorageMapper.delete(new LambdaQueryWrapper<ProcurementRecordStorage>()
+ .eq(ProcurementRecordStorage::getSalesLedgerProductId, existingProduct.getId()));
+ }
+ salesLedgerProductMapper.delete(new LambdaQueryWrapper<SalesLedgerProduct>()
+ .eq(SalesLedgerProduct::getSalesLedgerId, purchaseLedgerId)
+ .eq(SalesLedgerProduct::getType, 2));
+ }
+
+ private boolean isSameImportedPurchase(
+ PurchaseLedger existingLedger, PurchaseLedgerImportDto purchaseImport) {
+ return sameImportText(existingLedger.getPurchaseContractNumber(), purchaseImport.getPurchaseContractNumber())
+ && sameImportText(existingLedger.getSupplierName(), purchaseImport.getSupplierName())
+ && sameImportText(existingLedger.getProjectName(), purchaseImport.getProjectName())
+ && sameImportDate(existingLedger.getExecutionDate(), purchaseImport.getExecutionDate())
+ && sameImportDate(existingLedger.getEntryDate(), purchaseImport.getEntryDate());
+ }
+
+ private boolean sameImportText(String left, String right) {
+ return Objects.equals(StringUtils.trim(left), StringUtils.trim(right));
+ }
+
+ private boolean sameImportDate(Date left, Date right) {
+ if (left == null || right == null) {
+ return left == null && right == null;
+ }
+ LocalDate leftDate = Instant.ofEpochMilli(left.getTime())
+ .atZone(ZoneId.systemDefault())
+ .toLocalDate();
+ LocalDate rightDate = Instant.ofEpochMilli(right.getTime())
+ .atZone(ZoneId.systemDefault())
+ .toLocalDate();
+ return leftDate.equals(rightDate);
+ }
+
+ private String requireImportText(String value, String message) {
+ String trimmedValue = StringUtils.trim(value);
+ if (!StringUtils.hasText(trimmedValue)) {
+ throw new BaseException(message);
+ }
+ return trimmedValue;
}
@Override
@@ -666,7 +848,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);
}
@@ -684,6 +868,7 @@
approveProcessVO.setApproveUserIds(purchaseLedger.getApproveUserIds());
approveProcessVO.setApproveUser(loginUser.getUserId());
approveProcessVO.setApproveTime(LocalDate.now().toString());
+ approveProcessVO.setPrice(AmountUtils.scaleAmount(purchaseLedger.getContractAmount()));
approveProcessService.addApprove(approveProcessVO);
}
@@ -708,4 +893,23 @@
}
return sb.toString();
}
+
+ @Override
+ public Map<String, Object> getPrintData(Long id) {
+ PurchaseLedger purchaseLedger = getById(id);
+ if (purchaseLedger == null) {
+ return null;
+ }
+ 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