src/main/java/com/ruoyi/sales/service/impl/SalesLedgerServiceImpl.java
@@ -14,9 +14,11 @@
import com.ruoyi.basic.mapper.ProductModelMapper;
import com.ruoyi.basic.pojo.Customer;
import com.ruoyi.basic.pojo.CustomerRegions;
import com.ruoyi.basic.pojo.ProductModel;
import com.ruoyi.basic.service.ICustomerRegionsService;
import com.ruoyi.common.enums.FileNameType;
import com.ruoyi.common.enums.SaleEnum;
import com.ruoyi.common.enums.StockInQualifiedRecordTypeEnum;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.DateUtils;
@@ -46,6 +48,14 @@
import com.ruoyi.sales.service.ISalesLedgerProductProcessBindService;
import com.ruoyi.sales.service.ISalesLedgerProductProcessService;
import com.ruoyi.sales.service.ISalesLedgerService;
import com.ruoyi.stock.dto.StockInventoryDto;
import com.ruoyi.stock.mapper.StockInRecordMapper;
import com.ruoyi.stock.mapper.StockOutRecordMapper;
import com.ruoyi.stock.pojo.StockInRecord;
import com.ruoyi.stock.pojo.StockOutRecord;
import com.ruoyi.stock.service.StockInRecordService;
import com.ruoyi.stock.service.StockInventoryService;
import com.ruoyi.stock.service.StockOutRecordService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
@@ -125,6 +135,12 @@
    private final ISalesLedgerProcessRouteService salesLedgerProcessRouteService;
    private final StockInventoryService stockInventoryService;
    private final StockInRecordMapper stockInRecordMapper;
    private final StockOutRecordMapper stockOutRecordMapper;
    private final StockInRecordService stockInRecordService;
    private final StockOutRecordService stockOutRecordService;
    @Autowired
    private SysDeptMapper sysDeptMapper;
    @Value("${file.upload-dir}")
@@ -197,6 +213,20 @@
        productWrapper.eq(SalesLedgerProduct::getSalesLedgerId, salesLedger.getId());
        productWrapper.eq(SalesLedgerProduct::getType, 1);
        List<SalesLedgerProduct> products = salesLedgerProductMapper.selectList(productWrapper);
        Map<Long, ProductModel> productModelMap = Collections.emptyMap();
        if (CollectionUtils.isNotEmpty(products)) {
            List<Long> productModelIds = products.stream()
                    .map(SalesLedgerProduct::getProductModelId)
                    .filter(Objects::nonNull)
                    .distinct()
                    .collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(productModelIds)) {
                List<ProductModel> productModels = productModelMapper.selectBatchIds(productModelIds);
                if (CollectionUtils.isNotEmpty(productModels)) {
                    productModelMap = productModels.stream().collect(Collectors.toMap(ProductModel::getId, Function.identity()));
                }
            }
        }
        for (SalesLedgerProduct product : products) {
            product.setOriginalNoInvoiceNum(product.getNoInvoiceNum());
            // 提供临时未开票数,未开票金额供前段计算
@@ -228,6 +258,20 @@
                List<SalesLedgerProductProcess> processList = salesLedgerProductProcessService.listByIds(processIds);
                processList.forEach(p -> p.setQuantity(processQuantityMap.get(p.getId())));
                product.setSalesProductProcessList(processList);
            }
            ProductModel productModel = productModelMap.get(product.getProductModelId());
            if (productModel != null) {
                product.setThickness(productModel.getThickness());
            }
            if (product.getWidth() != null && product.getHeight() != null) {
                BigDecimal pieceArea = product.getWidth().multiply(product.getHeight()).divide(new BigDecimal(1000000), 2, RoundingMode.HALF_UP);
                if (product.getActualPieceArea() == null) {
                    product.setActualPieceArea(pieceArea);
                }
                BigDecimal quantity = product.getQuantity() == null ? BigDecimal.ZERO : product.getQuantity();
                if (product.getActualTotalArea() == null) {
                    product.setActualTotalArea(pieceArea.multiply(quantity).setScale(2, RoundingMode.HALF_UP));
                }
            }
        }
@@ -389,12 +433,6 @@
            // 客户数据
            List<Customer> customers = customerMapper.selectList(new LambdaQueryWrapper<Customer>().in(Customer::getCustomerName,
                    salesLedgerImportDtoList.stream().map(SalesLedgerImportDto::getCustomerName).collect(Collectors.toList())));
//            // 规格型号数据
//            List<ProductModel> productModels = productModelMapper.selectList(new LambdaQueryWrapper<ProductModel>().in(ProductModel::getModel,
//                    salesLedgerProductImportDtoList.stream().map(SalesLedgerImportDto::getSpecificationModel).collect(Collectors.toList())));
//            // 产品大类数据
//            List<Product> productList = productMapper.selectList(new LambdaQueryWrapper<Product>().in(Product::getProductName,
//                    salesLedgerProductImportDtoList.stream().map(SalesLedgerImportDto::getProductCategory).collect(Collectors.toList())));
            List<Map<String, Object>> list = productModelMapper.getProductAndModelList();
            // 录入人数据
            List<SysUser> sysUsers = sysUserMapper.selectList(new LambdaQueryWrapper<SysUser>().in(SysUser::getNickName,
@@ -404,7 +442,7 @@
                        .eq(SalesLedger::getSalesContractNo, salesLedgerImportDto.getSalesContractNo())
                        .last("LIMIT 1"));
                if (salesLedger1 != null) {
                    continue;
                    throw new ServiceException("导入失败:合同号 [" + salesLedgerImportDto.getSalesContractNo() + "] 已存在,请检查后重新导入");
                }
                SalesLedger salesLedger = new SalesLedger();
                BeanUtils.copyProperties(salesLedgerImportDto, salesLedger);
@@ -426,7 +464,7 @@
                        .map(SysUser::getUserId)
                        .orElse(null);
                if (aLong == null)
                    throw new RuntimeException("录入人:" + salesLedger.getEntryPerson() + ",无对应用户!");
                    throw new ServiceException("录入人:" + salesLedger.getEntryPerson() + ",无对应用户!");
                salesLedger.setEntryPerson(aLong.toString());
                // 销售产品数据绑定,通过销售单号获取对应销售产品数据
                List<SalesLedgerProductImportDto> salesLedgerProductImportDtos = salesLedgerProductImportDtoList.stream()
@@ -437,12 +475,16 @@
                salesLedger.setContractAmount(salesLedgerProductImportDtos.stream()
                        .map(SalesLedgerProductImportDto::getTaxInclusiveTotalPrice)
                        .reduce(BigDecimal.ZERO, BigDecimal::add));
                //  发货状态
                salesLedger.setDeliveryStatus(1);
                salesLedgerMapper.insert(salesLedger);
                for (SalesLedgerProductImportDto salesLedgerProductImportDto : salesLedgerProductImportDtos) {
                    SalesLedgerProduct salesLedgerProduct = new SalesLedgerProduct();
                    BeanUtils.copyProperties(salesLedgerProductImportDto, salesLedgerProduct);
                    salesLedgerProduct.setFloorCode(salesLedgerProductImportDto.getFloorNo());
                    salesLedgerProduct.setProcessRequirement(salesLedgerProductImportDto.getProcessingRequirements());
                    salesLedgerProduct.setRemark(salesLedgerProductImportDto.getRemarks());
                    salesLedgerProduct.setSalesLedgerId(salesLedger.getId());
                    salesLedgerProduct.setType(1);
                    // 计算不含税总价
@@ -456,21 +498,48 @@
                                salesLedgerProduct.setProductModelId(Long.parseLong(map.get("modelId").toString()));
                                salesLedgerProduct.setProductId(Long.parseLong(map.get("id").toString()));
                            });
//                    salesLedgerProduct.setProductId(productList.stream()
//                            .filter(product -> product.getProductName().equals(salesLedgerProduct.getProductCategory()))
//                            .findFirst()
//                            .map(Product::getId)
//                            .orElse(null));
//                    salesLedgerProduct.setProductModelId(productModels.stream()
//                            .filter(productModel -> productModel.getModel().equals(salesLedgerProduct.getSpecificationModel()))
//                            .findFirst()
//                            .map(ProductModel::getId)
//                            .orElse(null));
                    salesLedgerProduct.setRegister(loginUser.getNickName());
                    salesLedgerProduct.setRegisterDate(LocalDateTime.now());
                    salesLedgerProduct.setApproveStatus(0);
                    salesLedgerProduct.setPendingInvoiceTotal(salesLedgerProductImportDto.getTaxInclusiveTotalPrice());
                    salesLedgerProductMapper.insert(salesLedgerProduct);
                    // 处理额外加工信息
                    String extraProcessing = salesLedgerProductImportDto.getExtraProcessing();
                    if (StringUtils.hasText(extraProcessing)) {
                        List<SalesLedgerProductProcess> processList = new ArrayList<>();
                        //  中英文分号
                        String[] items = extraProcessing.split("[;;]");
                        for (String item : items) {
                            if (StringUtils.hasText(item)) {
                                String[] parts = item.split("[-—~~]");
                                if (parts.length >= 2) {
                                    String processName = parts[0].trim();
                                    String qtyStr = parts[1].trim();
                                    try {
                                        BigDecimal quantity = new BigDecimal(qtyStr);
                                        SalesLedgerProductProcess process = salesLedgerProductProcessService.getOne(
                                                new LambdaQueryWrapper<SalesLedgerProductProcess>()
                                                        .eq(SalesLedgerProductProcess::getProcessName, processName)
                                                        .last("LIMIT 1")
                                        );
                                        if (process != null) {
                                            SalesLedgerProductProcess p = new SalesLedgerProductProcess();
                                            p.setId(process.getId());
                                            p.setQuantity(quantity.intValue());
                                            processList.add(p);
                                        }
                                    } catch (Exception e) {
                                        log.error("解析额外加工数量失败: {}", qtyStr);
                                    }
                                }
                            }
                        }
                        if (!processList.isEmpty()) {
                            salesLedgerProductProcessBindService.updateProductProcessBind(processList, salesLedgerProduct.getId());
                        }
                    }
                    // 添加生产数据
                    salesLedgerProductServiceImpl.addProductionData(salesLedgerProduct);
                }
@@ -644,6 +713,25 @@
        if (CollectionUtils.isNotEmpty(shippingInfos)) {
            shippingInfoServiceImpl.delete(shippingInfos.stream().map(ShippingInfo::getId).collect(Collectors.toList()));
        }
        // 删除关联的入库/出库记录(走服务层删除,触发库存数量回退)
        List<Long> stockInRecordIds = stockInRecordMapper.selectList(new LambdaQueryWrapper<StockInRecord>()
                        .in(StockInRecord::getSalesLedgerId, idList)
                        .select(StockInRecord::getId))
                .stream()
                .map(StockInRecord::getId)
                .collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(stockInRecordIds)) {
            stockInRecordService.batchDelete(stockInRecordIds);
        }
        List<Long> stockOutRecordIds = stockOutRecordMapper.selectList(new LambdaQueryWrapper<StockOutRecord>()
                        .in(StockOutRecord::getSalesLedgerId, idList)
                        .select(StockOutRecord::getId))
                .stream()
                .map(StockOutRecord::getId)
                .collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(stockOutRecordIds)) {
            stockOutRecordService.batchDelete(stockOutRecordIds);
        }
        // 删除附件表
        commonFileService.deleteByBusinessIds(idList, FileNameType.SALE.getValue());
@@ -677,8 +765,13 @@
            if (salesLedger.getId() == null) {
                String contractNo = generateSalesContractNo();
                salesLedger.setSalesContractNo(contractNo);
                salesLedger.setDeliveryStatus(1);
                salesLedger.setStockStatus(0);
                salesLedgerMapper.insert(salesLedger);
            } else {
                if (salesLedger.getDeliveryStatus() == 5) {
                    throw new ServiceException("订单已发货,禁止编辑");
                }
                salesLedgerMapper.updateById(salesLedger);
            }
@@ -796,6 +889,7 @@
        if (!updateList.isEmpty()) {
            for (SalesLedgerProduct product : updateList) {
                product.setType(type.getCode());
                product.setProductStockStatus(0);
                salesLedgerProductMapper.updateById(product);
                //  清空销售产品绑定的加工
                salesLedgerProductProcessBindService.updateProductProcessBind(product.getSalesProductProcessList(), product.getId());
@@ -808,12 +902,13 @@
                salesLedgerProduct.setNoInvoiceNum(salesLedgerProduct.getQuantity());
                salesLedgerProduct.setNoInvoiceAmount(salesLedgerProduct.getTaxInclusiveTotalPrice());
                salesLedgerProduct.setPendingInvoiceTotal(salesLedgerProduct.getTaxInclusiveTotalPrice());
                salesLedgerProduct.setProductStockStatus(0);
                salesLedgerProductMapper.insert(salesLedgerProduct);
                //  绑定产品额外加工
                //  清空销售产品绑定的加工
                salesLedgerProductProcessBindService.updateProductProcessBind(salesLedgerProduct.getSalesProductProcessList(), salesLedgerProduct.getId());
                // 添加生产数据
                salesLedgerProductServiceImpl.addProductionData(salesLedgerProduct);
//                salesLedgerProductServiceImpl.addProductionData(salesLedgerProduct);
            }
        }
    }
@@ -1306,6 +1401,62 @@
        return dto;
    }
    @Override
    public List<SalesLabelDto> salesLabel(Long salesLedgerId) {
        if (salesLedgerId == null) {
            throw new ServiceException("打印标签失败,数据不能为空");
        }
        SalesLedger salesLedger = baseMapper.selectById(salesLedgerId);
        if (salesLedger == null) {
            throw new ServiceException("打印失败,销售订单不存在");
        }
        // 查询产品列表
        List<SalesLedgerProduct> products = salesLedgerProductMapper.selectList(
                new LambdaQueryWrapper<SalesLedgerProduct>().eq(SalesLedgerProduct::getSalesLedgerId, salesLedgerId));
        // 查询客户地址
        String fullAddress = "";
        if (salesLedger.getCustomerId() != null) {
            Customer customer = customerMapper.selectById(salesLedger.getCustomerId());
            if (customer != null) {
                StringBuilder addressSb = new StringBuilder();
                if (customer.getRegionsId() != null) {
                    CustomerRegions regions = customerRegionsService.getById(customer.getRegionsId());
                    if (regions != null) {
                        addressSb.append(regions.getRegionsName());
                    }
                }
                if (StringUtils.isNotEmpty(customer.getCompanyAddress())) {
                    addressSb.append(customer.getCompanyAddress());
                }
                fullAddress = addressSb.toString();
            }
        }
        List<SalesLabelDto> list = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(products)) {
            for (SalesLedgerProduct p : products) {
                SalesLabelDto dto = new SalesLabelDto();
                dto.setCustomerName(salesLedger.getCustomerName());
                dto.setSalesContractNo(salesLedger.getSalesContractNo());
                dto.setProductName(p.getProductCategory());
                // 宽*高=数量
                String specification = (p.getWidth() != null ? p.getWidth().stripTrailingZeros().toPlainString() : "0") + "*" +
                        (p.getHeight() != null ? p.getHeight().stripTrailingZeros().toPlainString() : "0") + "=" +
                        (p.getQuantity() != null ? p.getQuantity().stripTrailingZeros().toPlainString() : "0");
                dto.setSpecification(specification);
                // 客户地址 + 楼层编号
                dto.setFloorCode(fullAddress + (StringUtils.isNotEmpty(p.getFloorCode()) ? " " + p.getFloorCode() : ""));
                list.add(dto);
            }
        }
        return list;
    }
    private int findFirstMissingSequence(List<Integer> sequences) {
        if (sequences.isEmpty()) {
            return 1;
@@ -1386,4 +1537,51 @@
            return totalAmount;
        }
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void salesStock(SalesProductStockDto dto) {
        if (dto == null || dto.getSalesLedgerId() == null) {
            throw new NullPointerException("入库失败,请选择需要入库的销售订单");
        }
        //  查询销售订单是否存在
        SalesLedger ledger = baseMapper.selectById(dto.getSalesLedgerId());
        if (ledger == null) {
            throw new ServiceException("入库失败,销售订单不存在");
        }
        if (ledger.getStockStatus() == null) {
            throw new ServiceException("入库失败,销售订单入库状态异常");
        }
        if (ledger.getStockStatus() == 2) {
            throw new ServiceException("入库失败,该销售订单已入库,请勿重复入库");
        }
        List<Long> products = dto.getSalesLedgerProducts();
        if (products == null || products.isEmpty()) {
            throw new ServiceException("入库失败,入库产品不能为空");
        }
        //  查询销售订单的产品
        List<SalesLedgerProduct> salesLedgerProducts = salesLedgerProductMapper.selectList(Wrappers.<SalesLedgerProduct>lambdaQuery().in(SalesLedgerProduct::getId, products));
        if (salesLedgerProducts == null || salesLedgerProducts.isEmpty()) {
            throw new ServiceException("入库失败,未查询到该销售订单的销售产品");
        }
        for (SalesLedgerProduct product : salesLedgerProducts) {
            if (product.getProductModelId() == null) {
                continue;
            }
            StockInventoryDto stockInventoryDto = new StockInventoryDto();
            stockInventoryDto.setRecordId(product.getId());
            stockInventoryDto.setRecordType(StockInQualifiedRecordTypeEnum.SALE_STOCK_IN.getCode());
            stockInventoryDto.setQualitity(product.getQuantity());
            stockInventoryDto.setProductModelId(product.getProductModelId());
            stockInventoryDto.setSalesLedgerId(ledger.getId());
            stockInventoryDto.setSalesLedgerProductId(product.getId());
            stockInventoryService.addstockInventory(stockInventoryDto);
        }
        //  按销售订单产品入库情况更新主单入库状态:1-部分入库,2-已入库
        List<SalesLedgerProduct> ledgerAllProducts = salesLedgerProductMapper.selectList(Wrappers.<SalesLedgerProduct>lambdaQuery().eq(SalesLedgerProduct::getSalesLedgerId, ledger.getId()));
        boolean hasStocked = CollectionUtils.isNotEmpty(ledgerAllProducts) && ledgerAllProducts.stream().anyMatch(item -> Objects.equals(item.getProductStockStatus(), 1));
        boolean allStocked = CollectionUtils.isNotEmpty(ledgerAllProducts) && ledgerAllProducts.stream().allMatch(item -> Objects.equals(item.getProductStockStatus(), 1));
        ledger.setStockStatus(allStocked ? 2 : (hasStocked ? 1 : 0));
        baseMapper.updateById(ledger);
    }
}