platformx-business-finance-biz/src/main/java/com/by4cloud/platformx/business/service/impl/OutBoundServiceImpl.java
@@ -6,6 +6,7 @@
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.by4cloud.platformx.business.dto.OutBoundAddDTO;
@@ -17,6 +18,8 @@
import com.by4cloud.platformx.common.security.util.SecurityUtils;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
@@ -41,6 +44,22 @@
   private final ContractPaymentScheduleProcessMapper scheduleProcessMapper;
   private final ContractOutBoundMapper contractOutBoundMapper;
   private final DeliveryOverdueMapper deliveryOverdueMapper;
   private final StringRedisTemplate redisTemplate;
   @Value("${dept.smj}")
   private String smj;
   @Value("${dept.sgb}")
   private String sgb;
   @Value("${dept.jxc}")
   private String jxc;
   @Value("${dept.tfgs}")
   private String tfgs;
   @Value("${dept.ymj}")
   private String ymj;
   @Override
   public R add(OutBoundAddDTO addDTO) {
@@ -78,11 +97,25 @@
      //当前入库标的物
      Map<Long, Object> currentOutMap = new HashMap<>();
      //出库批次
      String batchNumber = DateUtil.format(new Date(), DatePattern.PURE_DATETIME_MS_PATTERN);
//      String batchNumber = DateUtil.format(new Date(), DatePattern.PURE_DATETIME_MS_PATTERN);
      //出库
      addDTO.getSubjectMatterList().stream().forEach(outSubjectMatterAddDTO -> {
         OutBound outBound = BeanUtil.copyProperties(outSubjectMatterAddDTO, OutBound.class);
         outBound.setBatchNumber(batchNumber);
         if (StrUtil.equals(SecurityUtils.getUser().getCompId()+"",smj)){
            outBound.setBatchNumber(generateSMJContractCKNo());
         }
         if (StrUtil.equals(SecurityUtils.getUser().getCompId()+"",sgb)){
            outBound.setBatchNumber(generateGYBContractCKNo());
         }
         if (StrUtil.equals(SecurityUtils.getUser().getCompId()+"",ymj)){
            outBound.setBatchNumber(generateYMJContractCKNo());
         }
         if (StrUtil.equals(SecurityUtils.getUser().getCompId()+"",tfgs)){
            outBound.setBatchNumber(generateTFContractCKNo());
         }
         if (StrUtil.equals(SecurityUtils.getUser().getCompId()+"",jxc)){
            outBound.setBatchNumber(generateJXCContractCKNo());
         }
         outBound.setBusGuestName(addDTO.getBusGuestName());
         outBound.setBusGuestId(addDTO.getBusGuestId());
         outBound.setOutBoundTime(addDTO.getOutBoundTime());
@@ -169,12 +202,17 @@
               //合同金额
               Contract contract = contractMapper.selectById(contractId);
               //出库是否完成
               if (outPirce.compareTo(contract.getAmount()) < 0) {
               if (outPirce.compareTo(contract.getBillingAmout())>0) {
                  contract.setBillingStatus("2");
                  contractMapper.updateById(contract);
               }
               if (outPirce.compareTo(contract.getBillingAmout())==0) {
                  contract.setBillingStatus("1");
                  contractMapper.updateById(contract);
               }
               if (outPirce.compareTo(contract.getAmount()) == 0) {
                  contract.setBillingStatus("2");
               if (outPirce.compareTo(contract.getAmount()) == 0&&
                     outPirce.compareTo(contract.getBillingAmout())==0) {
                  contract.setBillingStatus("3");
                  contractMapper.updateById(contract);
               }
               //计算发货前应收更新资金明细
@@ -380,11 +418,12 @@
      contractOutBound.setBusGuestName(contract.getPartyA());
      contractOutBound.setSubjectMatterCode(subjectMatter.getMaterialCode());
      contractOutBound.setSubjectMatterName(subjectMatter.getMaterialInternalName());
      contractOutBound.setOutBoundTime(addDTO.getOutBoundTime());
      contractOutBound.setOutBoundTime(ObjUtil.isNotNull(addDTO.getOutBoundTime())?addDTO.getOutBoundTime():new Date());
      contractOutBound.setOutBoundNum(subjectMatter.getLastDeliveredQuantity());
      contractOutBound.setOutBoundAttNames(addDTO.getOutBoundAttNames());
      contractOutBound.setOutBoundAttPaths(addDTO.getOutBoundAttPaths());
      contractOutBound.setOutBoundId(outBoundId);
      contractOutBound.setLineNo(subjectMatter.getLineNo());
      contractOutBound.setInvoiceStatus("0");
      contractOutBound.setInvoiceNum(new BigDecimal("0"));
      contractOutBoundMapper.insert(contractOutBound);
@@ -424,17 +463,70 @@
      if (ArrayUtil.isEmpty(addDTO.getSubjectMatterList().toArray())) {
         return R.failed("出库标的物不能为空");
      }
      Contract contract = contractMapper.selectOne(Wrappers.<Contract>lambdaQuery().eq(Contract::getContractNo, addDTO.getContractNo()).eq(Contract::getContractStatus, 2)
            .last("limit 1"));
      // 1. 确定查询用的合同编号字段值
      String targetContractNo = addDTO.getContractNo();
      boolean isSgbAndEmptyOutbound = StrUtil.isEmpty(addDTO.getOutBoundType())
            && StrUtil.equals(String.valueOf(SecurityUtils.getUser().getCompId()), sgb);
      // 2. 构建查询条件
      LambdaQueryWrapper<Contract> queryWrapper = Wrappers.lambdaQuery(Contract.class)
            .eq(Contract::getContractStatus, 2)
            .last("LIMIT 1"); // 注意:last 注入 SQL 片段,需确保防注入或业务可控
      if (isSgbAndEmptyOutbound) {
         // 条件 A: 使用 ERP 合同号查询
         queryWrapper.eq(Contract::getErpContractNo, targetContractNo);
      } else {
         // 条件 B: 使用普通合同号查询
         queryWrapper.eq(Contract::getContractNo, targetContractNo);
      }
      // 3. 执行查询
      Contract contract = contractMapper.selectOne(queryWrapper);
      if (ObjUtil.isNull(contract)) {
         return R.failed("合同信息查询失败");
      }
      //出库批次
      String batchNumber = DateUtil.format(new Date(), DatePattern.PURE_DATETIME_MS_PATTERN);
      //出库数量校验
      for (OutSubjectMatterAddDTO outSubjectMatterAddDTO:   addDTO.getSubjectMatterList()) {
         ContractSubjectMatter subjectMatter = contractSubjectMatterMapper.selectOne(Wrappers.<ContractSubjectMatter>lambdaQuery()
               .eq(ContractSubjectMatter::getContractId,contract.getId())
               .eq(ContractSubjectMatter::getMaterialCode,outSubjectMatterAddDTO.getSubjectMatterCode())
               .eq(StrUtil.isNotEmpty(outSubjectMatterAddDTO.getLineNo()),ContractSubjectMatter::getLineNo,outSubjectMatterAddDTO.getLineNo())
               .last("limit 1"));
         if (ObjUtil.isNull(subjectMatter)){
            continue;
         }
         if (outSubjectMatterAddDTO.getOutBoundNum().compareTo(new BigDecimal("0"))==0){
            return R.failed(outSubjectMatterAddDTO.getSubjectMatterCode()+"出库数量不能为0");
         }
         if (subjectMatter.getDeliveryStatus()==0){
            if (outSubjectMatterAddDTO.getOutBoundNum().compareTo(subjectMatter.getQuantity())>0){
               return R.failed(outSubjectMatterAddDTO.getSubjectMatterCode()+"出库数不能超过合同中数量");
            }
         }
         if (subjectMatter.getDeliveryStatus()==1){
            if (outSubjectMatterAddDTO.getOutBoundNum().compareTo(subjectMatter.getRemainingQuantity())>0){
               return R.failed(outSubjectMatterAddDTO.getSubjectMatterCode()+"出库数不能超过未出库数量");
            }
         }
         if (subjectMatter.getDeliveryStatus()==2){
            return R.failed(outSubjectMatterAddDTO.getSubjectMatterCode()+"已出库完成,不能超额出库");
         }
      }
      addDTO.getSubjectMatterList().stream().forEach(outSubjectMatterAddDTO -> {
         ContractSubjectMatter subjectMatter = contractSubjectMatterMapper.selectById(outSubjectMatterAddDTO.getId());
            ContractSubjectMatter subjectMatter = contractSubjectMatterMapper.selectOne(Wrappers.<ContractSubjectMatter>lambdaQuery()
               .eq(ContractSubjectMatter::getContractId,contract.getId())
               .eq(ContractSubjectMatter::getMaterialCode,outSubjectMatterAddDTO.getSubjectMatterCode())
               .ne(ContractSubjectMatter::getDeliveryStatus,2)
               .eq(StrUtil.isNotEmpty(outSubjectMatterAddDTO.getLineNo()),ContractSubjectMatter::getLineNo,outSubjectMatterAddDTO.getLineNo())
               .last("limit 1"));
         if (ObjUtil.isNull(subjectMatter)){
            return;
         }
         subjectMatter.setLastDeliveredQuantity(outSubjectMatterAddDTO.getOutBoundNum());
         outSubjectMatterAddDTO.setUnitPrice(subjectMatter.getUnitPrice());
         if (subjectMatter.getDeliveryStatus() == 0) {
            subjectMatter.setDeliveredQuantity(outSubjectMatterAddDTO.getOutBoundNum());
            subjectMatter.setRemainingQuantity(subjectMatter.getQuantity().subtract(outSubjectMatterAddDTO.getOutBoundNum()));
@@ -451,15 +543,33 @@
         contractSubjectMatterMapper.updateById(subjectMatter);
         //
         OutBound outBound = new OutBound();
         outBound.setBatchNumber(batchNumber);
         if (StrUtil.equals(SecurityUtils.getUser().getCompId()+"",smj)){
            outBound.setBatchNumber(generateSMJContractCKNo());
         }
         if (StrUtil.equals(SecurityUtils.getUser().getCompId()+"",sgb)){
            outBound.setBatchNumber(generateGYBContractCKNo());
         }
         if (StrUtil.equals(SecurityUtils.getUser().getCompId()+"",ymj)){
            outBound.setBatchNumber(generateYMJContractCKNo());
         }
         if (StrUtil.equals(SecurityUtils.getUser().getCompId()+"",tfgs)){
            outBound.setBatchNumber(generateTFContractCKNo());
         }
         if (StrUtil.equals(SecurityUtils.getUser().getCompId()+"",jxc)){
            outBound.setBatchNumber(generateJXCContractCKNo());
         }
         outBound.setOutBoundNum(outSubjectMatterAddDTO.getOutBoundNum());
         outBound.setOutBoundAttNames(addDTO.getOutBoundAttNames());
         outBound.setOutBoundAttPaths(addDTO.getOutBoundAttPaths());
         outBound.setBusGuestName(contract.getPartyA());
         outBound.setBusGuestId(contract.getPartyAId());
         outBound.setOutBoundTime(addDTO.getOutBoundTime());
         outBound.setOutBoundTime(ObjUtil.isNotNull(addDTO.getOutBoundTime())?addDTO.getOutBoundTime():new Date());
         outBound.setSubjectMatterCode(outSubjectMatterAddDTO.getSubjectMatterCode());
         outBound.setSubjectMatterName(outSubjectMatterAddDTO.getSubjectMatterName());
         outBound.setOutBoundType("1");
         if (StrUtil.isEmpty(addDTO.getOutBoundType())){
            outBound.setOutBoundType("0");
         }
         baseMapper.insert(outBound);
         //
         saveContractOutBound(contract, addDTO, subjectMatter, outBound.getId());
@@ -477,12 +587,17 @@
               .map(item -> (item.getDeliveryStatus() == 1 ? item.getDeliveredQuantity().multiply(item.getUnitPrice()) : item.getQuantity().multiply(item.getUnitPrice())))
               .reduce(BigDecimal.ZERO, BigDecimal::add);
         //出库是否完成
         if (outPirce.compareTo(contract.getAmount()) < 0) {
         if (outPirce.compareTo(contract.getBillingAmout())>0) {
            contract.setBillingStatus("2");
            contractMapper.updateById(contract);
         }
         if (outPirce.compareTo(contract.getBillingAmout())==0) {
            contract.setBillingStatus("1");
            contractMapper.updateById(contract);
         }
         if (outPirce.compareTo(contract.getAmount()) == 0) {
            contract.setBillingStatus("2");
         if (outPirce.compareTo(contract.getAmount()) == 0&&
               outPirce.compareTo(contract.getBillingAmout())==0) {
            contract.setBillingStatus("3");
            contractMapper.updateById(contract);
         }
         //计算发货前应收更新资金明细
@@ -496,36 +611,31 @@
         paymentConfirm.setScheduleId(schedule.getId());
         paymentConfirm.setScheduleName(schedule.getStageName());
         paymentConfirm.setConfirmTime(addDTO.getOutBoundTime());
         //按出库资金比例 计算发货前应收
         paymentConfirm.setTransationAmount(outPirce.divide(contract.getAmount(), 10, RoundingMode.HALF_UP).multiply(schedule.getPlannedAmount()));
         paymentConfirm.setReceivableAmount(paymentConfirm.getTransationAmount());
         //最近应收
         //计算出库金额
         BigDecimal outAmount = addDTO.getSubjectMatterList().stream().map(item->item.getUnitPrice().multiply(item.getOutBoundNum())).reduce(BigDecimal.ZERO, BigDecimal::add);
         paymentConfirm.setTransationAmount(outAmount.divide(new BigDecimal("100")).multiply(schedule.getPaymentRatio()));
         if (ObjUtil.isNotNull(contract.getOutBoundAmout())){
            contract.setOutBoundAmout(outAmount.add(contract.getOutBoundAmout()));
         }else {
            contract.setOutBoundAmout(outAmount);
         }
         contractMapper.updateById(contract);
         //最近明细
         PaymentConfirm lastConfirm = paymentConfirmMapper.selectOne(Wrappers.<PaymentConfirm>lambdaQuery().eq(PaymentConfirm::getContractId, contract.getId())
               .orderByDesc(PaymentConfirm::getCreateTime).last("limit 1"));
         if (ObjUtil.isNotNull(lastConfirm)) {
            //已存在发货应收
            if (StrUtil.equals(lastConfirm.getBusinessType(), paymentConfirm.getBusinessType())) {
               //查询之前所有发货前应收
               List<PaymentConfirm> fhConfirmList = paymentConfirmMapper.selectList(Wrappers.<PaymentConfirm>lambdaQuery().eq(PaymentConfirm::getContractId, contract.getId())
                     .eq(PaymentConfirm::getScheduleId, schedule.getId()).orderByDesc(PaymentConfirm::getCreateTime));
               BigDecimal fhTotalAmount = fhConfirmList.stream().map(item -> item.getTransationAmount()).reduce(BigDecimal.ZERO, BigDecimal::add);
               //本次发货前应收 出库总额 - 所有发货前应收
               paymentConfirm.setTransationAmount(paymentConfirm.getTransationAmount().subtract(fhTotalAmount));
               paymentConfirm.setReceivableAmount(paymentConfirm.getTransationAmount());
               paymentConfirm.setTotalAmount(lastConfirm.getTotalAmount().subtract(paymentConfirm.getTransationAmount()));
               if (schedule.getPaymentRatio().compareTo(new BigDecimal("0")) > 0) {
                  paymentConfirmMapper.insert(paymentConfirm);
               }
            } else {
               //不存在发货应收 出库总额
               paymentConfirm.setTotalAmount(lastConfirm.getTotalAmount().subtract(paymentConfirm.getTransationAmount()));
               if (paymentConfirm.getTotalAmount().compareTo(new BigDecimal("0"))>0){
                  paymentConfirm.setAdvanceAmount(paymentConfirm.getTotalAmount());
               }
               if (paymentConfirm.getTotalAmount().compareTo(new BigDecimal("0"))<0){
                  paymentConfirm.setReceivableAmount(paymentConfirm.getTotalAmount().multiply(new BigDecimal("-1")));
               }
               if (schedule.getPaymentRatio().compareTo(new BigDecimal("0")) > 0) {
                  paymentConfirmMapper.insert(paymentConfirm);
               }
            }
//            }
         } else {
            //无之前阶段应收
            paymentConfirm.setTotalAmount(paymentConfirm.getTransationAmount().multiply(new BigDecimal("-1")));
@@ -582,21 +692,7 @@
         //更新发货前收款生效时间
         if (ObjUtil.isNull(schedule.getEffectiveDate())) {
            schedule.setEffectiveEndDate(DateUtil.offsetDay(addDTO.getOutBoundTime(), schedule.getAgreedDays()));
            //查询是否有后续阶段
//                  List<ContractPaymentSchedule> afterSchedule = scheduleMapper.selectList(Wrappers.<ContractPaymentSchedule>lambdaQuery().eq(ContractPaymentSchedule::getContractId, contractId)
//                        .gt(ContractPaymentSchedule::getStageOrder, schedule.getStageOrder()));
//                  if (ArrayUtil.isEmpty(afterSchedule.toArray())) {
//                     schedule.setEffectiveEndDate(contract.getExpirationDate());
//                  }
            scheduleMapper.updateById(schedule);
            //查询是否有之前阶段
//                  ContractPaymentSchedule beforeSchedule = scheduleMapper.selectOne(Wrappers.<ContractPaymentSchedule>lambdaQuery().eq(ContractPaymentSchedule::getContractId, schedule.getContractId())
//                        .lt(ContractPaymentSchedule::getStageOrder, schedule.getStageOrder()).orderByDesc(ContractPaymentSchedule::getCreateTime).last("limit 1"));
//                  if (ObjUtil.isNotNull(beforeSchedule)) {
//                     beforeSchedule.setEffectiveEndDate(schedule.getEffectiveDate());
//                     scheduleMapper.updateById(beforeSchedule);
//                  }
            //更新履约
            ContractPaymentScheduleProcess contractPaymentScheduleProcess = new ContractPaymentScheduleProcess();
            contractPaymentScheduleProcess.setContractId(schedule.getContractId());
@@ -615,52 +711,16 @@
         List<ContractPaymentSchedule> afterSchedule = scheduleMapper.selectList(Wrappers.<ContractPaymentSchedule>lambdaQuery()
               .eq(ContractPaymentSchedule::getContractId, schedule.getContractId())
               .gt(ContractPaymentSchedule::getStageOrder, schedule.getStageOrder())
               .gt(ContractPaymentSchedule::getPaymentRatio, 0)
               .orderByAsc(ContractPaymentSchedule::getCreateTime));
         if (ArrayUtil.isNotEmpty(afterSchedule.toArray()) && afterSchedule.size() == 1) {
            //最后阶段生效时间
            ContractPaymentSchedule endSchedule = afterSchedule.get(0);
            if (StrUtil.equals(endSchedule.getStageName(), "质保金")) {
//                     endSchedule.setEffectiveEndDate(DateUtil.offsetDay(addDTO.getOutBoundTime(), endSchedule.getAgreedDays()));
//                     scheduleMapper.updateById(endSchedule);
               //当前阶段生效时间
//                     schedule.setEffectiveEndDate(DateUtil.offsetDay(addDTO.getOutBoundTime(), schedule.getAgreedDays()));
//                     scheduleMapper.updateById(schedule);
               //最后阶段应收
               PaymentConfirm newConfim = new PaymentConfirm();
               newConfim.setBusinessType(endSchedule.getStageName() + "应收");
               newConfim.setBusGuestId(contract.getPartyAId());
               newConfim.setBusGuestName(contract.getPartyA());
               newConfim.setContractId(contract.getId());
               newConfim.setContractName(contract.getContractName());
               newConfim.setContractNo(contract.getContractNo());
               newConfim.setScheduleId(endSchedule.getId());
               newConfim.setScheduleName(schedule.getStageName());
               newConfim.setConfirmTime(addDTO.getOutBoundTime());
               newConfim.setTransationAmount(endSchedule.getPlannedAmount());
               newConfim.setReceivableAmount(endSchedule.getPlannedAmount());
               PaymentConfirm lastNewConfirm = paymentConfirmMapper.selectOne(Wrappers.<PaymentConfirm>lambdaQuery().eq(PaymentConfirm::getContractId, contract.getId())
                     .orderByDesc(PaymentConfirm::getCreateTime).last("limit 1"));
               BigDecimal lastNewTotal = new BigDecimal("0");
               if (ObjUtil.isNotNull(lastNewConfirm)) {
                  lastNewTotal = lastNewConfirm.getTotalAmount();
               }
               newConfim.setTotalAmount(lastNewTotal.subtract(newConfim.getReceivableAmount()));
               if (endSchedule.getPaymentRatio().compareTo(new BigDecimal("0")) > 0) {
                  paymentConfirmMapper.insert(newConfim);
               }
            }
            //更新合同下个阶段
            contract.setNextScheduleName(endSchedule.getStageName());
            contractMapper.updateById(contract);
         }
         if (ArrayUtil.isNotEmpty(afterSchedule.toArray()) && afterSchedule.size() > 1) {
            //更新合同下个阶段
         if (ArrayUtil.isNotEmpty(afterSchedule.toArray())&&contract.getOutBoundAmout().compareTo(contract.getAmount())==0) {
            contract.setNextScheduleName(afterSchedule.get(0).getStageName());
            contractMapper.updateById(contract);
         }
         if (ArrayUtil.isEmpty(afterSchedule.toArray())) {
//                  schedule.setEffectiveEndDate(contract.getExpirationDate());
//                  scheduleMapper.updateById(schedule);
            schedule.setEffectiveEndDate(contract.getExpirationDate());
            scheduleMapper.updateById(schedule);
            //更新合同下个阶段
            contract.setNextScheduleName("无");
            contractMapper.updateById(contract);
@@ -676,4 +736,158 @@
      }
      return R.ok();
   }
   /**
    * 生成格式为: yyyyMMdd + 4位序列号 (例如: 20260629000001)
    */
   public  String generateSMJContractCKNo() {
      // 1. 获取当前日期字符串
      String dateStr = DateUtil.format(new Date(), "yyyyMMdd");
      // 2. 构建 Redis Key,按天隔离,例如: order:no:20260629
      String key = "ZB-SMJ-CK:" + dateStr;
      // 3. Redis 原子递增,设置过期时间为2天(防止Key堆积,同时覆盖跨天边界情况)
      Long sequence = redisTemplate.opsForValue().increment(key, 1);
      redisTemplate.expire(key, 1, java.util.concurrent.TimeUnit.DAYS);
      // 4. 格式化序列号,不足6位前补0
      String seqStr = String.format("%04d", sequence);
      // 5. 拼接返回
      return "ZB-SMJ-CK-"+dateStr + seqStr;
   }
   public  String generateYMJContractCKNo() {
      // 1. 获取当前日期字符串
      String dateStr = DateUtil.format(new Date(), "yyyyMMdd");
      // 2. 构建 Redis Key,按天隔离,例如: order:no:20260629
      String key = "ZB-YMJ-CK:" + dateStr;
      // 3. Redis 原子递增,设置过期时间为2天(防止Key堆积,同时覆盖跨天边界情况)
      Long sequence = redisTemplate.opsForValue().increment(key, 1);
      redisTemplate.expire(key, 1, java.util.concurrent.TimeUnit.DAYS);
      // 4. 格式化序列号,不足6位前补0
      String seqStr = String.format("%04d", sequence);
      // 5. 拼接返回
      return "ZB-YMJ-CK-"+dateStr + seqStr;
   }
   public  String generateJXCContractCKNo() {
      // 1. 获取当前日期字符串
      String dateStr = DateUtil.format(new Date(), "yyyyMMdd");
      // 2. 构建 Redis Key,按天隔离,例如: order:no:20260629
      String key = "ZB-JXC-CK:" + dateStr;
      // 3. Redis 原子递增,设置过期时间为2天(防止Key堆积,同时覆盖跨天边界情况)
      Long sequence = redisTemplate.opsForValue().increment(key, 1);
      redisTemplate.expire(key, 1, java.util.concurrent.TimeUnit.DAYS);
      // 4. 格式化序列号,不足6位前补0
      String seqStr = String.format("%04d", sequence);
      // 5. 拼接返回
      return "ZB-JXC-CK-"+dateStr + seqStr;
   }
   public  String generateTFContractCKNo() {
      // 1. 获取当前日期字符串
      String dateStr = DateUtil.format(new Date(), "yyyyMMdd");
      // 2. 构建 Redis Key,按天隔离,例如: order:no:20260629
      String key = "ZB-TF-CK:" + dateStr;
      // 3. Redis 原子递增,设置过期时间为2天(防止Key堆积,同时覆盖跨天边界情况)
      Long sequence = redisTemplate.opsForValue().increment(key, 1);
      redisTemplate.expire(key, 1, java.util.concurrent.TimeUnit.DAYS);
      // 4. 格式化序列号,不足6位前补0
      String seqStr = String.format("%04d", sequence);
      // 5. 拼接返回
      return "ZB-TF-CK-"+dateStr + seqStr;
   }
   public  String generateGYBContractCKNo() {
      // 1. 获取当前日期字符串
      String dateStr = DateUtil.format(new Date(), "yyyyMMdd");
      // 2. 构建 Redis Key,按天隔离,例如: order:no:20260629
      String key = "ZB-GYB-CK:" + dateStr;
      // 3. Redis 原子递增,设置过期时间为2天(防止Key堆积,同时覆盖跨天边界情况)
      Long sequence = redisTemplate.opsForValue().increment(key, 1);
      redisTemplate.expire(key, 1, java.util.concurrent.TimeUnit.DAYS);
      // 4. 格式化序列号,不足6位前补0
      String seqStr = String.format("%04d", sequence);
      // 5. 拼接返回
      return "ZB-GYB-CK-"+dateStr + seqStr;
   }
   @Override
   public R delOutBound(String batchNumber) {
      List<OutBound> outBoundList = baseMapper.selectList(Wrappers.<OutBound>lambdaQuery().eq(OutBound::getBatchNumber,batchNumber));
      if (ArrayUtil.isEmpty(outBoundList)){
         return R.failed("出库信息异常,请联系营销系统管理人员");
      }
      List<ContractOutBound> contractOutBoundList = contractOutBoundMapper.selectList(Wrappers.<ContractOutBound>lambdaQuery()
            .in(ContractOutBound::getOutBoundId,outBoundList.stream().map(OutBound::getId).collect(Collectors.toList())));
      if (ArrayUtil.isEmpty(contractOutBoundList)){
         return R.failed("出库信息异常,请联系营销系统管理人员");
      }
      boolean allZero = true;
      for (ContractOutBound item : contractOutBoundList) {
         // 假设 invoiceNum 是 Integer 对象
         if (item.getInvoiceNum() == null || item.getInvoiceNum().compareTo(new BigDecimal("0"))!=0) {
            allZero = false;
            break; // 发现一个不符合即退出
         }
      }
      if (!allZero){
         return R.failed("请先冲减所有蓝牌后在操作");
      }
      for (ContractOutBound item : contractOutBoundList) {
         ContractSubjectMatter subjectMatter = contractSubjectMatterMapper.selectOne(Wrappers.<ContractSubjectMatter>lambdaQuery()
               .eq(ContractSubjectMatter::getContractId,item.getContractId()).eq(ContractSubjectMatter::getMaterialCode,item.getSubjectMatterCode())
               .eq(ContractSubjectMatter::getLineNo,item.getLineNo()));
         if (ObjUtil.isNotNull(subjectMatter)){
            subjectMatter.setDeliveredQuantity(subjectMatter.getDeliveredQuantity().subtract(item.getOutBoundNum()));
            subjectMatter.setRemainingQuantity(subjectMatter.getRemainingQuantity().add(item.getOutBoundNum()));
            if (subjectMatter.getDeliveredQuantity().compareTo(new BigDecimal("0"))==0){
               subjectMatter.setDeliveryStatus(0);
            }
            if (subjectMatter.getDeliveredQuantity().compareTo(new BigDecimal("0"))>0){
               subjectMatter.setDeliveryStatus(1);
            }
            //标的物更新
            contractSubjectMatterMapper.updateById(subjectMatter);
         }
         //合同开票状态更新
//         List<ContractSubjectMatter> subjectMatterList = contractSubjectMatterMapper.selectList(Wrappers.<ContractSubjectMatter>lambdaQuery()
//               .eq(ContractSubjectMatter::getContractId,subjectMatter.getContractId()));
//         if (subjectMatterList.stream().allMatch(matter -> matter.getDeliveryStatus() != null && matter.getDeliveryStatus() == 0)){
//            Contract contract = contractMapper.selectById(subjectMatter.getContractId());
//            if (ObjUtil.isNotNull(contract)){
//               contract.setBillingStatus("1");
//               contractMapper.updateById(contract);
//            }
//         }else {
//            Contract contract = contractMapper.selectById(subjectMatter.getContractId());
//            if (ObjUtil.isNotNull(contract)){
//               contract.setBillingStatus("1");
//               contractMapper.updateById(contract);
//            }
//         }
         //出库记录删除
         contractOutBoundMapper.deleteById(item);
      }
      baseMapper.delete(Wrappers.<OutBound>lambdaQuery().eq(OutBound::getBatchNumber,batchNumber));
      return R.ok();
   }
}