chenxiaofei před 7 hodinami
rodič
revize
83530a1f95

+ 37 - 0
sckw-modules-api/sckw-transport-api/src/main/java/com/sckw/transport/api/dubbo/ParkingWalletFeeRemoteService.java

@@ -0,0 +1,37 @@
+package com.sckw.transport.api.dubbo;
+
+import com.sckw.transport.api.model.param.ParkingWalletFeeFreezeParam;
+import com.sckw.transport.api.model.vo.ParkingWalletFeeFreezeResult;
+
+import java.math.BigDecimal;
+
+/**
+ * 服务费远程服务
+ */
+public interface ParkingWalletFeeRemoteService {
+
+    /**
+     * 贸易订单下单时应用收费策略并冻结服务费余额
+     *
+     * @param param 冻结参数
+     * @return 收费策略应用结果
+     */
+    ParkingWalletFeeFreezeResult applyChargeStrategyFreeze(ParkingWalletFeeFreezeParam param);
+
+    /**
+     * 贸易订单审核拒绝时解冻服务费并返还余额
+     *
+     * @param param 解冻参数
+     * @return 解冻结果(含采购方服务费余额)
+     */
+    ParkingWalletFeeFreezeResult unfreezeChargeStrategy(ParkingWalletFeeFreezeParam param);
+
+    /**
+     * 查询采购方服务费余额
+     *
+     * @param proEntId 采购方企业id
+     * @param supEntId 供应商企业id
+     * @return 服务费余额
+     */
+    BigDecimal queryServiceFeeBalance(Long proEntId, Long supEntId);
+}

+ 42 - 0
sckw-modules-api/sckw-transport-api/src/main/java/com/sckw/transport/api/model/param/ParkingWalletFeeFreezeParam.java

@@ -0,0 +1,42 @@
+package com.sckw.transport.api.model.param;
+
+import lombok.Data;
+
+import java.io.Serial;
+import java.io.Serializable;
+import java.math.BigDecimal;
+
+/**
+ * 贸易订单服务费冻结参数
+ */
+@Data
+public class ParkingWalletFeeFreezeParam implements Serializable {
+
+    @Serial
+    private static final long serialVersionUID = 1L;
+
+    /**
+     * 贸易订单号
+     */
+    private String orderNo;
+
+    /**
+     * 采购方企业id
+     */
+    private Long proEntId;
+
+    /**
+     * 供应商企业id
+     */
+    private Long supEntId;
+
+    /**
+     * 采购数量
+     */
+    private BigDecimal purchaseQuantity;
+
+    /**
+     * 操作人id(Dubbo调用时由订单模块传入)
+     */
+    private Long operatorId;
+}

+ 42 - 0
sckw-modules-api/sckw-transport-api/src/main/java/com/sckw/transport/api/model/vo/ParkingWalletFeeFreezeResult.java

@@ -0,0 +1,42 @@
+package com.sckw.transport.api.model.vo;
+
+import lombok.Data;
+
+import java.io.Serial;
+import java.io.Serializable;
+import java.math.BigDecimal;
+
+/**
+ * 贸易订单服务费冻结结果
+ */
+@Data
+public class ParkingWalletFeeFreezeResult implements Serializable {
+
+    @Serial
+    private static final long serialVersionUID = 1L;
+
+    /**
+     * 是否应用收费策略(0-否,1-是)
+     */
+    private Integer applyChargeStrategy;
+
+    /**
+     * 收费策略id
+     */
+    private Long chargeStrategyId;
+
+    /**
+     * 收费策略描述,如10元/吨
+     */
+    private String chargeStrategyDesc;
+
+    /**
+     * 冻结服务费金额
+     */
+    private BigDecimal freezeAmount;
+
+    /**
+     * 采购方服务费余额
+     */
+    private BigDecimal serviceFeeBalance;
+}

+ 18 - 0
sckw-modules/sckw-order/src/main/java/com/sckw/order/model/KwoTradeOrder.java

@@ -160,5 +160,23 @@ public class KwoTradeOrder extends BaseModel implements Serializable {
     @TableField("agent_flag")
     private Integer agentFlag;
 
+    /**
+     * 是否应用收费策略(0-否,1-是)
+     */
+    @TableField("apply_charge_strategy")
+    private Integer applyChargeStrategy;
+
+    /**
+     * 应用的收费策略id
+     */
+    @TableField("charge_strategy_id")
+    private Long chargeStrategyId;
+
+    /**
+     * 应用的收费策略描述,如10元/吨
+     */
+    @TableField("charge_strategy_desc")
+    private String chargeStrategyDesc;
+
 
 }

+ 22 - 0
sckw-modules/sckw-order/src/main/java/com/sckw/order/model/vo/res/TradeOrderAuditResp.java

@@ -0,0 +1,22 @@
+package com.sckw.order.model.vo.res;
+
+import lombok.Data;
+
+import java.io.Serial;
+import java.io.Serializable;
+import java.math.BigDecimal;
+
+/**
+ * 贸易订单审核结果
+ */
+@Data
+public class TradeOrderAuditResp implements Serializable {
+
+    @Serial
+    private static final long serialVersionUID = 1L;
+
+    /**
+     * 采购方服务费余额
+     */
+    private BigDecimal serviceFeeBalance;
+}

+ 101 - 3
sckw-modules/sckw-order/src/main/java/com/sckw/order/serivce/KwoTradeOrderService.java

@@ -81,13 +81,16 @@ import com.sckw.system.api.feign.DataPermissionFeignService;
 import com.sckw.system.api.model.dto.req.ActualDisPatchDto;
 import com.sckw.system.api.model.dto.req.DataPermissionFilterReqDto;
 import com.sckw.system.api.model.dto.res.*;
+import com.sckw.transport.api.dubbo.ParkingWalletFeeRemoteService;
 import com.sckw.transport.api.dubbo.TransportRemoteStatisticsService;
 import com.sckw.transport.api.dubbo.TransportRemoteService;
 import com.sckw.transport.api.model.param.AddLogisticOrderParam;
 import com.sckw.transport.api.model.param.LogisticInfo;
 import com.sckw.transport.api.model.param.OrderFinishParam;
+import com.sckw.transport.api.model.param.ParkingWalletFeeFreezeParam;
 import com.sckw.transport.api.model.vo.KwtLogisticsOrderVO;
 import com.sckw.transport.api.model.vo.LogisticContractVo;
+import com.sckw.transport.api.model.vo.ParkingWalletFeeFreezeResult;
 import jakarta.annotation.Resource;
 import lombok.RequiredArgsConstructor;
 import lombok.extern.slf4j.Slf4j;
@@ -160,6 +163,9 @@ public class KwoTradeOrderService {
     @DubboReference(version = "1.0.0", group = "design", check = false, timeout = 6000)
     private TransportRemoteStatisticsService transportRemoteStatisticsService;
 
+    @DubboReference(version = "1.0.0", group = "design", check = false, timeout = 6000)
+    private ParkingWalletFeeRemoteService parkingWalletFeeRemoteService;
+
     @DubboReference(version = "1.0.0", group = "design", check = false, timeout = 6000)
     protected RemoteFleetService remoteFleetService;
 
@@ -2561,6 +2567,20 @@ public class KwoTradeOrderService {
         }
         // ====== 下单前校验 end ======
 
+        // 收费策略开启时冻结采购方服务费,并记录订单收费策略信息
+        Long purchaseEntId = resolvePurchaseEntId(tradeContractResDto.getUnitList());
+        Long supplyEntId = resolveSupplyEntId(tradeContractResDto.getUnitList());
+        ParkingWalletFeeFreezeParam feeFreezeParam = new ParkingWalletFeeFreezeParam();
+        feeFreezeParam.setOrderNo(order.getTOrderNo());
+        feeFreezeParam.setProEntId(purchaseEntId);
+        feeFreezeParam.setSupEntId(supplyEntId);
+        feeFreezeParam.setPurchaseQuantity(tradeOrderParam.getAmount());
+        feeFreezeParam.setOperatorId(LoginUserHolder.getUserId());
+        log.info("贸易订单下单应用收费策略,orderNo:{}, feeFreezeParam:{}", order.getTOrderNo(), JSON.toJSONString(feeFreezeParam));
+        ParkingWalletFeeFreezeResult feeFreezeResult = parkingWalletFeeRemoteService.applyChargeStrategyFreeze(feeFreezeParam);
+        fillChargeStrategyInfo(order, feeFreezeResult);
+        log.info("贸易订单收费策略处理完成,orderNo:{}, feeFreezeResult:{}", order.getTOrderNo(), JSON.toJSONString(feeFreezeResult));
+
         //商品地址信息
         AddressInfoDetail goodsAddress = goodsInfoService.getGoodsAddress(tradeOrderParam.getGoodsId());
         if (Objects.isNull(goodsAddress)) {
@@ -2763,6 +2783,49 @@ public class KwoTradeOrderService {
         return StrUtil.equals(contractUnitType, "1") ? "2" : "1";
     }
 
+    /**
+     * 解析贸易合同中的采购方企业id
+     */
+    private Long resolvePurchaseEntId(List<TradeContractUnitDto> unitList) {
+        if (CollUtil.isEmpty(unitList)) {
+            throw new BusinessException("贸易合同企业信息不存在");
+        }
+        return unitList.stream()
+                .filter(unit -> StrUtil.equals(convertContractUnitTypeToOrderUnitType(unit.getUnitType()), "1"))
+                .map(TradeContractUnitDto::getEntId)
+                .filter(Objects::nonNull)
+                .findFirst()
+                .orElseThrow(() -> new BusinessException("采购方企业信息不存在"));
+    }
+
+    /**
+     * 解析贸易合同中的供应方企业id
+     */
+    private Long resolveSupplyEntId(List<TradeContractUnitDto> unitList) {
+        if (CollUtil.isEmpty(unitList)) {
+            throw new BusinessException("贸易合同企业信息不存在");
+        }
+        return unitList.stream()
+                .filter(unit -> StrUtil.equals(convertContractUnitTypeToOrderUnitType(unit.getUnitType()), "2"))
+                .map(TradeContractUnitDto::getEntId)
+                .filter(Objects::nonNull)
+                .findFirst()
+                .orElseThrow(() -> new BusinessException("供应方企业信息不存在"));
+    }
+
+    /**
+     * 回填贸易订单收费策略信息
+     */
+    private void fillChargeStrategyInfo(KwoTradeOrder order, ParkingWalletFeeFreezeResult feeFreezeResult) {
+        if (feeFreezeResult == null) {
+            order.setApplyChargeStrategy(Global.NO);
+            return;
+        }
+        order.setApplyChargeStrategy(feeFreezeResult.getApplyChargeStrategy() == null ? Global.NO : feeFreezeResult.getApplyChargeStrategy());
+        order.setChargeStrategyId(feeFreezeResult.getChargeStrategyId());
+        order.setChargeStrategyDesc(feeFreezeResult.getChargeStrategyDesc());
+    }
+
     /**
      * 代理订单创建物流订单时,将贸易订单企业表中的代理单位同步传递给运输模块。
      *
@@ -2951,7 +3014,7 @@ public class KwoTradeOrderService {
      * @return
      */
     @Transactional(rollbackFor = Exception.class)
-    public Object auditOrder(TradeOrderAuditParam tradeOrderAuditParam) {
+    public TradeOrderAuditResp auditOrder(TradeOrderAuditParam tradeOrderAuditParam) {
         KwoTradeOrder kwoTradeOrder = kwoTradeOrderMapper.selectOne(new LambdaQueryWrapper<KwoTradeOrder>().eq(KwoTradeOrder::getId, tradeOrderAuditParam.getId()).eq(KwoTradeOrder::getDelFlag, 0));
         if (Objects.isNull(kwoTradeOrder)) {
             throw new BusinessException("贸易订单不存在");
@@ -2981,6 +3044,21 @@ public class KwoTradeOrderService {
         }
 
         if (Objects.equals(tradeOrderAuditParam.getStatus(), 2)) {
+            BigDecimal serviceFeeBalance = null;
+            // 审核拒绝:若应用了收费策略,解冻并返还采购方服务费余额
+            if (Objects.equals(kwoTradeOrder.getApplyChargeStrategy(), Global.YES)) {
+                ParkingWalletFeeFreezeParam serviceFeeUnfreezeParam = new ParkingWalletFeeFreezeParam();
+                serviceFeeUnfreezeParam.setOrderNo(kwoTradeOrder.getTOrderNo());
+                serviceFeeUnfreezeParam.setProEntId(unitMap.get(String.valueOf(1)).getEntId());
+                serviceFeeUnfreezeParam.setSupEntId(unitMap.get(String.valueOf(2)).getEntId());
+                serviceFeeUnfreezeParam.setOperatorId(LoginUserHolder.getUserId());
+                log.info("贸易订单审核拒绝解冻服务费,orderNo:{}, param:{}",
+                        kwoTradeOrder.getTOrderNo(), JSON.toJSONString(serviceFeeUnfreezeParam));
+                ParkingWalletFeeFreezeResult unfreezeResult =
+                        parkingWalletFeeRemoteService.unfreezeChargeStrategy(serviceFeeUnfreezeParam);
+                serviceFeeBalance = unfreezeResult.getServiceFeeBalance();
+            }
+
             //钱包退回金额
             WalletPrepaidDto walletFreeze = new WalletPrepaidDto();
 //            walletFreeze.setTTradeOrderId(kwoTradeOrder.getId());
@@ -3017,7 +3095,7 @@ public class KwoTradeOrderService {
             kwoTradeOrderTrackService.insert(kwoTradeOrderTrack);
             kwoTradeOrder.setStatus(Objects.equals(tradeOrderAuditParam.getStatus(), 2) ? TradeOrderStatusEnum.BACK.getCode() : TradeOrderStatusEnum.ING.getCode());
             kwoTradeOrderMapper.updateById(kwoTradeOrder);
-            return true;
+            return buildAuditServiceFeeBalanceResp(kwoTradeOrder, unitMap, serviceFeeBalance);
         }
         TradeContractResDto tradeContractResDto = remoteContractService.queryTradeContract(tradeOrderAuditParam.getTradeContractId(), byOrderId.getGoodsId());
         if (Objects.isNull(tradeContractResDto)) {
@@ -3270,7 +3348,27 @@ public class KwoTradeOrderService {
         //更新贸易订单状态
         kwoTradeOrder.setStatus(Objects.equals(tradeOrderAuditParam.getStatus(), 2) ? TradeOrderStatusEnum.BACK.getCode() : TradeOrderStatusEnum.ING.getCode());
         kwoTradeOrderMapper.updateById(kwoTradeOrder);
-        return true;
+        return buildAuditServiceFeeBalanceResp(kwoTradeOrder, unitMap, null);
+    }
+
+    /**
+     * 构建审核结果,返回采购方服务费余额
+     */
+    private TradeOrderAuditResp buildAuditServiceFeeBalanceResp(KwoTradeOrder order,
+                                                                Map<String, KwoTradeOrderUnit> unitMap,
+                                                                BigDecimal serviceFeeBalance) {
+        TradeOrderAuditResp resp = new TradeOrderAuditResp();
+        if (!Objects.equals(order.getApplyChargeStrategy(), Global.YES)) {
+            return resp;
+        }
+        if (serviceFeeBalance != null) {
+            resp.setServiceFeeBalance(serviceFeeBalance);
+            return resp;
+        }
+        Long proEntId = unitMap.get(String.valueOf(1)).getEntId();
+        Long supEntId = unitMap.get(String.valueOf(2)).getEntId();
+        resp.setServiceFeeBalance(parkingWalletFeeRemoteService.queryServiceFeeBalance(proEntId, supEntId));
+        return resp;
     }
 
     @NotNull

+ 37 - 0
sckw-modules/sckw-transport/src/main/java/com/sckw/transport/dubbo/ParkingWalletFeeRemoteServiceImpl.java

@@ -0,0 +1,37 @@
+package com.sckw.transport.dubbo;
+
+import com.sckw.transport.api.dubbo.ParkingWalletFeeRemoteService;
+import com.sckw.transport.api.model.param.ParkingWalletFeeFreezeParam;
+import com.sckw.transport.api.model.vo.ParkingWalletFeeFreezeResult;
+import com.sckw.transport.service.ParkingWalletFeeService;
+import lombok.RequiredArgsConstructor;
+import org.apache.dubbo.config.annotation.DubboService;
+import org.springframework.stereotype.Service;
+
+import java.math.BigDecimal;
+
+/**
+ * 服务费远程服务实现
+ */
+@Service
+@DubboService(group = "design", version = "1.0.0", timeout = 60000)
+@RequiredArgsConstructor
+public class ParkingWalletFeeRemoteServiceImpl implements ParkingWalletFeeRemoteService {
+
+    private final ParkingWalletFeeService parkingWalletFeeService;
+
+    @Override
+    public ParkingWalletFeeFreezeResult applyChargeStrategyFreeze(ParkingWalletFeeFreezeParam param) {
+        return parkingWalletFeeService.applyChargeStrategyFreeze(param);
+    }
+
+    @Override
+    public ParkingWalletFeeFreezeResult unfreezeChargeStrategy(ParkingWalletFeeFreezeParam param) {
+        return parkingWalletFeeService.unfreezeChargeStrategy(param);
+    }
+
+    @Override
+    public BigDecimal queryServiceFeeBalance(Long proEntId, Long supEntId) {
+        return parkingWalletFeeService.queryPurchaserServiceFeeBalance(proEntId, supEntId);
+    }
+}

+ 14 - 12
sckw-modules/sckw-transport/src/main/java/com/sckw/transport/model/KwtParkingWalletFee.java

@@ -1,5 +1,6 @@
 package com.sckw.transport.model;
 
+import com.baomidou.mybatisplus.annotation.TableField;
 import com.baomidou.mybatisplus.annotation.TableName;
 import lombok.Data;
 
@@ -8,9 +9,7 @@ import java.math.BigDecimal;
 import java.util.Date;
 
 /**
- * @author lfdc
- * @description 服务费
- * @date 2023-06-26 16:06:12
+ * 预存服务费
  */
 @Data
 @TableName("kwt_parking_wallet_fee")
@@ -26,6 +25,12 @@ public class KwtParkingWalletFee implements Serializable {
      */
     private Long proEntId;
 
+    /**
+     * 供应商企业id
+     */
+    @TableField("sup_ent_id")
+    private Long supEntId;
+
     /**
      * 服务费余额
      */
@@ -36,11 +41,6 @@ public class KwtParkingWalletFee implements Serializable {
      */
     private BigDecimal tradingAmount;
 
-    /**
-     * 凭证图片
-     */
-    private String voucherUrl;
-
     /**
      * 备注
      */
@@ -49,7 +49,8 @@ public class KwtParkingWalletFee implements Serializable {
     /**
      * 创建人
      */
-    private Long createBy;
+    @TableField("create_user")
+    private Long createUser;
 
     /**
      * 创建时间
@@ -57,9 +58,10 @@ public class KwtParkingWalletFee implements Serializable {
     private Date createTime;
 
     /**
-     * 创建人更新人
+     * 更新人
      */
-    private Long updateBy;
+    @TableField("update_user")
+    private Long updateUser;
 
     /**
      * 更新时间
@@ -70,4 +72,4 @@ public class KwtParkingWalletFee implements Serializable {
      * 是否删除(0未删除,1删除)
      */
     private Integer delFlag;
-}
+}

+ 20 - 7
sckw-modules/sckw-transport/src/main/java/com/sckw/transport/model/KwtParkingWalletFeeBalance.java

@@ -1,5 +1,6 @@
 package com.sckw.transport.model;
 
+import com.baomidou.mybatisplus.annotation.TableField;
 import com.baomidou.mybatisplus.annotation.TableName;
 import lombok.Data;
 
@@ -8,9 +9,7 @@ import java.math.BigDecimal;
 import java.util.Date;
 
 /**
- * @author lfdc
- * @description 服务费明细
- * @date 2023-06-26 16:06:12
+ * 预存服务费明细(钱包日志)
  */
 @Data
 @TableName("kwt_parking_wallet_fee_balance")
@@ -31,6 +30,12 @@ public class KwtParkingWalletFeeBalance implements Serializable {
      */
     private Long proEntId;
 
+    /**
+     * 供应商企业id
+     */
+    @TableField("sup_ent_id")
+    private Long supEntId;
+
     /**
      * 交易类型 2-预付 3-收益 4-冻结 5-解冻 6-消费 9-人工录入
      */
@@ -51,6 +56,12 @@ public class KwtParkingWalletFeeBalance implements Serializable {
      */
     private BigDecimal tradingAmount;
 
+    /**
+     * 凭证图片
+     */
+    @TableField("voucher_url")
+    private String voucherUrl;
+
     /**
      * 备注
      */
@@ -59,7 +70,8 @@ public class KwtParkingWalletFeeBalance implements Serializable {
     /**
      * 创建人
      */
-    private Long createBy;
+    @TableField("create_user")
+    private Long createUser;
 
     /**
      * 创建时间
@@ -67,9 +79,10 @@ public class KwtParkingWalletFeeBalance implements Serializable {
     private Date createTime;
 
     /**
-     * 创建人更新人
+     * 更新人
      */
-    private Long updateBy;
+    @TableField("update_user")
+    private Long updateUser;
 
     /**
      * 更新时间
@@ -80,4 +93,4 @@ public class KwtParkingWalletFeeBalance implements Serializable {
      * 是否删除(0未删除,1删除)
      */
     private Integer delFlag;
-}
+}

+ 272 - 14
sckw-modules/sckw-transport/src/main/java/com/sckw/transport/service/ParkingWalletFeeService.java

@@ -5,12 +5,16 @@ import com.baomidou.mybatisplus.core.toolkit.Wrappers;
 import com.sckw.core.common.enums.enums.ErrorCodeEnum;
 import com.sckw.core.exception.BusinessPlatfromException;
 import com.sckw.core.model.constant.Global;
+import com.sckw.core.model.enums.ParkingChangeStrategyEnum;
 import com.sckw.core.web.context.LoginUserHolder;
 import com.sckw.transport.model.KwtParkingChargeStrategy;
 import com.sckw.transport.model.KwtParkingChargeStrategyUnit;
 import com.sckw.transport.model.KwtParkingWalletFee;
+import com.sckw.transport.model.KwtParkingWalletFeeBalance;
 import com.sckw.transport.model.param.ParkingWalletFeeEstimateQueryParam;
 import com.sckw.transport.model.param.ParkingWalletFeeEstimateResp;
+import com.sckw.transport.api.model.param.ParkingWalletFeeFreezeParam;
+import com.sckw.transport.api.model.vo.ParkingWalletFeeFreezeResult;
 import com.sckw.transport.repository.KwtParkingChangeStrategyRepository;
 import com.sckw.transport.repository.KwtParkingChangeStrategyUnitRepository;
 import com.sckw.system.api.RemoteSystemService;
@@ -21,10 +25,12 @@ import lombok.extern.slf4j.Slf4j;
 import org.apache.commons.collections4.CollectionUtils;
 import org.apache.dubbo.config.annotation.DubboReference;
 import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
 
 import java.math.BigDecimal;
 import java.math.RoundingMode;
 import java.util.Comparator;
+import java.util.Date;
 import java.util.List;
 import java.util.Objects;
 
@@ -43,6 +49,8 @@ public class ParkingWalletFeeService {
 
     private static final BigDecimal ZERO_AMOUNT = BigDecimal.ZERO;
     private static final int STRATEGY_OPEN = 1;
+    private static final int TRADE_TYPE_FREEZE = 4;
+    private static final int TRADE_TYPE_UNFREEZE = 5;
 
     private final KwtParkingWalletFeeRepository parkingWalletFeeRepository;
     private final KwtParkingWalletFeeBalanceRepository parkingWalletFeeBalanceRepository;
@@ -72,7 +80,7 @@ public class ParkingWalletFeeService {
         }
 
         // 查询采购方当前服务费余额
-        BigDecimal serviceFeeBalance = queryServiceFeeBalance(entId);
+        BigDecimal serviceFeeBalance = queryServiceFeeBalance(entId, null);
 
         // 查询当前企业生效中的收费策略(仅取状态开启的最新一条)
         KwtParkingChargeStrategy currentStrategy = queryCurrentEnableStrategy(entId);
@@ -101,6 +109,261 @@ public class ParkingWalletFeeService {
         return resp;
     }
 
+    /**
+     * 贸易订单下单应用收费策略并冻结服务费
+     * 规则:
+     * 1. 收费策略开关未开启时,不冻结服务费,订单记录为未应用收费策略
+     * 2. 收费策略开关开启时,冻结金额=采购数量*策略单价,并记录策略信息
+     *
+     * @param param 冻结参数
+     * @return 收费策略应用结果
+     */
+    @Transactional(rollbackFor = Exception.class)
+    public ParkingWalletFeeFreezeResult applyChargeStrategyFreeze(ParkingWalletFeeFreezeParam param) {
+        log.info("贸易订单应用收费策略开始,param:{}", param);
+        if (param == null || param.getProEntId() == null) {
+            throw new BusinessPlatfromException(ErrorCodeEnum.PARAM_ERROR, "采购方企业id不能为空");
+        }
+        if (param.getPurchaseQuantity() == null || param.getPurchaseQuantity().compareTo(ZERO_AMOUNT) < 0) {
+            throw new BusinessPlatfromException(ErrorCodeEnum.PARAM_ERROR, "采购数量不能为空且不能小于0");
+        }
+        if (param.getOrderNo() == null || param.getOrderNo().isBlank()) {
+            throw new BusinessPlatfromException(ErrorCodeEnum.PARAM_ERROR, "贸易订单号不能为空");
+        }
+
+        ParkingWalletFeeFreezeResult result = new ParkingWalletFeeFreezeResult();
+        result.setApplyChargeStrategy(Global.NO);
+        result.setFreezeAmount(ZERO_AMOUNT);
+
+        KwtParkingChargeStrategy currentStrategy = queryCurrentEnableStrategy(param.getProEntId());
+        if (currentStrategy == null || !Objects.equals(currentStrategy.getStatus(), STRATEGY_OPEN)) {
+            log.info("收费策略未开启或未匹配,跳过服务费冻结,proEntId:{}, orderNo:{}",
+                    param.getProEntId(), param.getOrderNo());
+            return result;
+        }
+
+        BigDecimal unitFee = currentStrategy.getMethod() == null ? ZERO_AMOUNT : currentStrategy.getMethod();
+        if (unitFee.compareTo(ZERO_AMOUNT) <= 0) {
+            log.info("收费策略单价无效,跳过服务费冻结,strategyId:{}, unitFee:{}",
+                    currentStrategy.getId(), unitFee);
+            return result;
+        }
+
+        BigDecimal freezeAmount = param.getPurchaseQuantity().multiply(unitFee).setScale(2, RoundingMode.HALF_UP);
+        KwtParkingWalletFee walletFee = queryWalletFee(param.getProEntId(), param.getSupEntId());
+        if (walletFee == null) {
+            log.warn("服务费账户不存在,proEntId:{}, supEntId:{}, orderNo:{}",
+                    param.getProEntId(), param.getSupEntId(), param.getOrderNo());
+            throw new BusinessPlatfromException(ErrorCodeEnum.PARAM_ERROR, "采购方服务费账户不存在");
+        }
+
+        BigDecimal currentBalance = walletFee.getServiceFeeBalance() == null ? ZERO_AMOUNT : walletFee.getServiceFeeBalance();
+        if (currentBalance.compareTo(freezeAmount) < 0) {
+            log.warn("服务费余额不足,proEntId:{}, orderNo:{}, balance:{}, freezeAmount:{}",
+                    param.getProEntId(), param.getOrderNo(), currentBalance, freezeAmount);
+            throw new BusinessPlatfromException(ErrorCodeEnum.PARAM_ERROR, "服务费余额不足,无法下单");
+        }
+
+        BigDecimal currentTradingAmount = walletFee.getTradingAmount() == null ? ZERO_AMOUNT : walletFee.getTradingAmount();
+        walletFee.setServiceFeeBalance(currentBalance.subtract(freezeAmount));
+        walletFee.setTradingAmount(currentTradingAmount.add(freezeAmount));
+        parkingWalletFeeRepository.updateById(walletFee);
+
+        saveFreezeWalletBalanceLog(param, walletFee, freezeAmount);
+
+        result.setApplyChargeStrategy(Global.YES);
+        result.setChargeStrategyId(currentStrategy.getId());
+        result.setChargeStrategyDesc(buildStrategyMethodDesc(currentStrategy));
+        result.setFreezeAmount(freezeAmount);
+        result.setServiceFeeBalance(walletFee.getServiceFeeBalance());
+        log.info("贸易订单应用收费策略完成,orderNo:{}, result:{}", param.getOrderNo(), result);
+        return result;
+    }
+
+    /**
+     * 贸易订单审核拒绝解冻服务费
+     * 规则:根据订单冻结记录解冻,返还服务费余额并写入钱包日志
+     *
+     * @param param 解冻参数
+     * @return 解冻结果(含采购方服务费余额)
+     */
+    @Transactional(rollbackFor = Exception.class)
+    public ParkingWalletFeeFreezeResult unfreezeChargeStrategy(ParkingWalletFeeFreezeParam param) {
+        log.info("贸易订单解冻服务费开始,param:{}", param);
+        validateUnfreezeParam(param);
+
+        ParkingWalletFeeFreezeResult result = new ParkingWalletFeeFreezeResult();
+        result.setApplyChargeStrategy(Global.YES);
+
+        if (existsUnfreezeRecord(param.getOrderNo(), param.getProEntId(), param.getSupEntId())) {
+            log.info("服务费已解冻,跳过重复处理,orderNo:{}, proEntId:{}", param.getOrderNo(), param.getProEntId());
+            result.setServiceFeeBalance(queryServiceFeeBalance(param.getProEntId(), param.getSupEntId()));
+            return result;
+        }
+
+        KwtParkingWalletFeeBalance freezeRecord = queryFreezeBalanceRecord(param);
+        if (freezeRecord == null) {
+            log.warn("未找到服务费冻结记录,orderNo:{}, proEntId:{}", param.getOrderNo(), param.getProEntId());
+            throw new BusinessPlatfromException(ErrorCodeEnum.PARAM_ERROR, "服务费冻结记录不存在,无法解冻");
+        }
+
+        BigDecimal unfreezeAmount = freezeRecord.getTradeAmount() == null ? ZERO_AMOUNT : freezeRecord.getTradeAmount();
+        if (unfreezeAmount.compareTo(ZERO_AMOUNT) <= 0) {
+            throw new BusinessPlatfromException(ErrorCodeEnum.PARAM_ERROR, "服务费冻结金额异常,无法解冻");
+        }
+
+        KwtParkingWalletFee walletFee = queryWalletFee(param.getProEntId(), param.getSupEntId());
+        if (walletFee == null) {
+            throw new BusinessPlatfromException(ErrorCodeEnum.PARAM_ERROR, "采购方服务费账户不存在");
+        }
+
+        BigDecimal currentTradingAmount = walletFee.getTradingAmount() == null ? ZERO_AMOUNT : walletFee.getTradingAmount();
+        if (currentTradingAmount.compareTo(unfreezeAmount) < 0) {
+            log.warn("服务费履约中金额不足,无法解冻,orderNo:{}, tradingAmount:{}, unfreezeAmount:{}",
+                    param.getOrderNo(), currentTradingAmount, unfreezeAmount);
+            throw new BusinessPlatfromException(ErrorCodeEnum.PARAM_ERROR, "服务费履约中金额不足,无法解冻");
+        }
+
+        BigDecimal currentBalance = walletFee.getServiceFeeBalance() == null ? ZERO_AMOUNT : walletFee.getServiceFeeBalance();
+        walletFee.setServiceFeeBalance(currentBalance.add(unfreezeAmount));
+        walletFee.setTradingAmount(currentTradingAmount.subtract(unfreezeAmount));
+        parkingWalletFeeRepository.updateById(walletFee);
+
+        saveUnfreezeWalletBalanceLog(param, walletFee, unfreezeAmount);
+        result.setFreezeAmount(unfreezeAmount);
+        result.setServiceFeeBalance(walletFee.getServiceFeeBalance());
+        log.info("贸易订单解冻服务费完成,orderNo:{}, unfreezeAmount:{}, balanceAfter:{}",
+                param.getOrderNo(), unfreezeAmount, walletFee.getServiceFeeBalance());
+        return result;
+    }
+
+    /**
+     * 查询采购方服务费余额
+     */
+    public BigDecimal queryPurchaserServiceFeeBalance(Long proEntId, Long supEntId) {
+        return queryServiceFeeBalance(proEntId, supEntId);
+    }
+
+    private void validateUnfreezeParam(ParkingWalletFeeFreezeParam param) {
+        if (param == null || param.getProEntId() == null) {
+            throw new BusinessPlatfromException(ErrorCodeEnum.PARAM_ERROR, "采购方企业id不能为空");
+        }
+        if (param.getOrderNo() == null || param.getOrderNo().isBlank()) {
+            throw new BusinessPlatfromException(ErrorCodeEnum.PARAM_ERROR, "贸易订单号不能为空");
+        }
+    }
+
+    private boolean existsUnfreezeRecord(String orderNo, Long proEntId, Long supEntId) {
+        return parkingWalletFeeBalanceRepository.count(
+                Wrappers.<KwtParkingWalletFeeBalance>lambdaQuery()
+                        .eq(KwtParkingWalletFeeBalance::getOrderNo, orderNo)
+                        .eq(KwtParkingWalletFeeBalance::getProEntId, proEntId)
+                        .eq(supEntId != null, KwtParkingWalletFeeBalance::getSupEntId, supEntId)
+                        .eq(KwtParkingWalletFeeBalance::getTradeType, TRADE_TYPE_UNFREEZE)
+                        .eq(KwtParkingWalletFeeBalance::getDelFlag, Global.NO)
+        ) > 0;
+    }
+
+    private KwtParkingWalletFeeBalance queryFreezeBalanceRecord(ParkingWalletFeeFreezeParam param) {
+        return parkingWalletFeeBalanceRepository.getOne(
+                Wrappers.<KwtParkingWalletFeeBalance>lambdaQuery()
+                        .eq(KwtParkingWalletFeeBalance::getOrderNo, param.getOrderNo())
+                        .eq(KwtParkingWalletFeeBalance::getProEntId, param.getProEntId())
+                        .eq(param.getSupEntId() != null, KwtParkingWalletFeeBalance::getSupEntId, param.getSupEntId())
+                        .eq(KwtParkingWalletFeeBalance::getTradeType, TRADE_TYPE_FREEZE)
+                        .eq(KwtParkingWalletFeeBalance::getDelFlag, Global.NO)
+                        .orderByDesc(KwtParkingWalletFeeBalance::getId)
+                        .last("limit 1"),
+                false
+        );
+    }
+
+    private void saveUnfreezeWalletBalanceLog(ParkingWalletFeeFreezeParam param,
+                                              KwtParkingWalletFee walletFee,
+                                              BigDecimal unfreezeAmount) {
+        Long operatorId = resolveOperatorId(param.getOperatorId());
+        Date now = new Date();
+        KwtParkingWalletFeeBalance balanceRecord = new KwtParkingWalletFeeBalance();
+        balanceRecord.setOrderNo(param.getOrderNo());
+        balanceRecord.setProEntId(param.getProEntId());
+        balanceRecord.setSupEntId(param.getSupEntId());
+        balanceRecord.setTradeType(TRADE_TYPE_UNFREEZE);
+        balanceRecord.setTradeAmount(unfreezeAmount);
+        balanceRecord.setServiceFeeBalance(walletFee.getServiceFeeBalance());
+        balanceRecord.setTradingAmount(walletFee.getTradingAmount());
+        balanceRecord.setRemark("贸易订单号:" + param.getOrderNo() + ",审核拒绝解冻服务费");
+        balanceRecord.setDelFlag(Global.NO);
+        balanceRecord.setCreateUser(operatorId);
+        balanceRecord.setUpdateUser(operatorId);
+        balanceRecord.setCreateTime(now);
+        balanceRecord.setUpdateTime(now);
+        parkingWalletFeeBalanceRepository.save(balanceRecord);
+        log.info("服务费解冻钱包日志已写入kwt_parking_wallet_fee_balance,orderNo:{}, proEntId:{}, supEntId:{}, tradeType:{}, tradeAmount:{}, balanceAfter:{}",
+                param.getOrderNo(), param.getProEntId(), param.getSupEntId(), TRADE_TYPE_UNFREEZE,
+                unfreezeAmount, walletFee.getServiceFeeBalance());
+    }
+
+    private String buildStrategyMethodDesc(KwtParkingChargeStrategy strategy) {
+        if (strategy == null || strategy.getMethod() == null) {
+            return null;
+        }
+        if (Objects.equals(ParkingChangeStrategyEnum.BY_TON.getCode(), strategy.getType())) {
+            return strategy.getMethod().stripTrailingZeros().toPlainString() + "元/吨";
+        }
+        if (Objects.equals(ParkingChangeStrategyEnum.BY_TIME.getCode(), strategy.getType())) {
+            return strategy.getMethod().stripTrailingZeros().toPlainString() + "元/次";
+        }
+        return strategy.getMethod().stripTrailingZeros().toPlainString() + "元/月";
+    }
+
+    /**
+     * 写入服务费钱包日志(kwt_parking_wallet_fee_balance)
+     */
+    private void saveFreezeWalletBalanceLog(ParkingWalletFeeFreezeParam param,
+                                            KwtParkingWalletFee walletFee,
+                                            BigDecimal freezeAmount) {
+        Long operatorId = resolveOperatorId(param.getOperatorId());
+        Date now = new Date();
+        KwtParkingWalletFeeBalance balanceRecord = new KwtParkingWalletFeeBalance();
+        balanceRecord.setOrderNo(param.getOrderNo());
+        balanceRecord.setProEntId(param.getProEntId());
+        balanceRecord.setSupEntId(param.getSupEntId());
+        balanceRecord.setTradeType(TRADE_TYPE_FREEZE);
+        balanceRecord.setTradeAmount(freezeAmount);
+        balanceRecord.setServiceFeeBalance(walletFee.getServiceFeeBalance());
+        balanceRecord.setTradingAmount(walletFee.getTradingAmount());
+        balanceRecord.setRemark("贸易订单号:" + param.getOrderNo() + ",下单冻结服务费");
+        balanceRecord.setDelFlag(Global.NO);
+        balanceRecord.setCreateUser(operatorId);
+        balanceRecord.setUpdateUser(operatorId);
+        balanceRecord.setCreateTime(now);
+        balanceRecord.setUpdateTime(now);
+        parkingWalletFeeBalanceRepository.save(balanceRecord);
+        log.info("服务费钱包日志已写入kwt_parking_wallet_fee_balance,orderNo:{}, proEntId:{}, supEntId:{}, tradeType:{}, tradeAmount:{}, balanceAfter:{}",
+                param.getOrderNo(), param.getProEntId(), param.getSupEntId(), TRADE_TYPE_FREEZE,
+                freezeAmount, walletFee.getServiceFeeBalance());
+    }
+
+    private KwtParkingWalletFee queryWalletFee(Long proEntId, Long supEntId) {
+        return parkingWalletFeeRepository.getOne(
+                Wrappers.<KwtParkingWalletFee>lambdaQuery()
+                        .eq(KwtParkingWalletFee::getProEntId, proEntId)
+                        .eq(supEntId != null, KwtParkingWalletFee::getSupEntId, supEntId)
+                        .eq(KwtParkingWalletFee::getDelFlag, Global.NO)
+                        .orderByDesc(KwtParkingWalletFee::getId)
+                        .last("limit 1"),
+                false
+        );
+    }
+
+    private Long resolveOperatorId(Long operatorId) {
+        Long loginUserId = LoginUserHolder.getUserId();
+        if (loginUserId != null) {
+            return loginUserId;
+        }
+        return operatorId == null ? -1L : operatorId;
+    }
+
     /**
      * 计算服务费余额支持的最大可购买数量
      * 仅在收费策略开关开启且单价大于0时计算:服务费余额 / 策略单价(向下取整,保留4位小数)
@@ -119,7 +382,8 @@ public class ParkingWalletFeeService {
                     currentStrategy == null ? "未匹配到收费策略" : "收费策略未开启或单价<=0");
             return null;
         }
-        BigDecimal maxPurchaseQuantity = serviceFeeBalance.divide(currentStrategyUnitFee, 4, RoundingMode.DOWN);
+        //向下取整
+        BigDecimal maxPurchaseQuantity = serviceFeeBalance.divide(currentStrategyUnitFee, 0, RoundingMode.DOWN);
         log.info("最大可购买数量计算完成,serviceFeeBalance:{}, unitFee:{}, maxPurchaseQuantity:{}",
                 serviceFeeBalance, currentStrategyUnitFee, maxPurchaseQuantity);
         return maxPurchaseQuantity.max(ZERO_AMOUNT);
@@ -178,23 +442,17 @@ public class ParkingWalletFeeService {
      * 查询企业当前可用服务费余额
      *
      * @param proEntId 采购企业id
+     * @param supEntId 供应商企业id,可为空
      * @return 服务费余额,无记录时返回0
      */
-    private BigDecimal queryServiceFeeBalance(Long proEntId) {
-        KwtParkingWalletFee walletFee = parkingWalletFeeRepository.getOne(
-                Wrappers.<KwtParkingWalletFee>lambdaQuery()
-                        .eq(KwtParkingWalletFee::getProEntId, proEntId)
-                        .eq(KwtParkingWalletFee::getDelFlag, Global.NO)
-                        .orderByDesc(KwtParkingWalletFee::getId)
-                        .last("limit 1"),
-                false
-        );
+    private BigDecimal queryServiceFeeBalance(Long proEntId, Long supEntId) {
+        KwtParkingWalletFee walletFee = queryWalletFee(proEntId, supEntId);
         if (walletFee == null || walletFee.getServiceFeeBalance() == null) {
-            log.info("查询服务费余额为空,按0处理,proEntId:{}", proEntId);
+            log.info("查询服务费余额为空,按0处理,proEntId:{}, supEntId:{}", proEntId, supEntId);
             return ZERO_AMOUNT;
         }
-        log.info("查询服务费余额成功,proEntId:{}, serviceFeeBalance:{}",
-                proEntId, walletFee.getServiceFeeBalance());
+        log.info("查询服务费余额成功,proEntId:{}, supEntId:{}, serviceFeeBalance:{}",
+                proEntId, supEntId, walletFee.getServiceFeeBalance());
         return walletFee.getServiceFeeBalance();
     }
 

+ 4 - 1
sql/2026/06/2026_06_16_create.sql

@@ -30,12 +30,13 @@ create table kwt_parking_charge_strategy_unit
 ) comment '收费策略企业关联表';
 
 
+
 CREATE TABLE `kwt_parking_wallet_fee` (
                                           `id`                            bigint          NOT NULL AUTO_INCREMENT COMMENT '主键',
                                           `pro_ent_id`                    bigint          NOT NULL DEFAULT '-1' COMMENT '采购商企业id',
+                                          `sup_ent_id`                    bigint          NOT NULL DEFAULT '-1' COMMENT '供应商企业id',
                                           `service_fee_balance`           decimal(16,2)   NOT NULL DEFAULT '0.00' COMMENT '服务费余额',
                                           `trading_amount`                decimal(16,2)   NOT NULL DEFAULT '0.00' COMMENT '履约中金额',
-                                          `voucher_url`                   longtext        CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci COMMENT '凭证图片',
                                           `remark`                        varchar(20)     DEFAULT NULL DEFAULT '' COMMENT '备注',
                                           del_flag                        int             NOT NULL DEFAULT '0' COMMENT '是否删除(0未删除,1删除)',
                                           create_time                     datetime        NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
@@ -50,10 +51,12 @@ CREATE TABLE `kwt_parking_wallet_fee_balance` (
                                                   `id`                            bigint          NOT NULL AUTO_INCREMENT COMMENT '主键',
                                                   `order_no`                      varchar(32)     CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '关联订单编号',
                                                   `pro_ent_id`                    bigint          NOT NULL DEFAULT '-1' COMMENT '采购商企业id',
+                                                  `sup_ent_id`                    bigint          NOT NULL DEFAULT '-1' COMMENT '供应商企业id',
                                                   `trade_type`                    int             NOT NULL DEFAULT '0' COMMENT '交易类型 2-预付 3-收益 4-冻结 5-解冻 6-消费 9-人工录入',
                                                   `trade_amount`                  decimal(16,2)   NOT NULL DEFAULT '0.00' COMMENT '交易金额',
                                                   `service_fee_balance`           decimal(16,2)   NOT NULL DEFAULT '0.00' COMMENT '服务费余额',
                                                   `trading_amount`                decimal(16,2)   NOT NULL DEFAULT '0.00' COMMENT '履约中金额',
+                                                  `voucher_url`                   longtext        CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci COMMENT '凭证图片',
                                                   `remark`                        varchar(20)     DEFAULT NULL DEFAULT '' COMMENT '备注',
                                                   del_flag                        int             NOT NULL DEFAULT '0' COMMENT '是否删除(0未删除,1删除)',
                                                   create_time                     datetime        NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',

+ 4 - 0
sql/2026/06/2026_06_25_add_trade_order_charge_strategy.sql

@@ -0,0 +1,4 @@
+ALTER TABLE kwo_trade_order
+    ADD COLUMN apply_charge_strategy tinyint NOT NULL DEFAULT 0 COMMENT '是否应用收费策略(0-否,1-是)' AFTER agent_flag,
+    ADD COLUMN charge_strategy_id bigint DEFAULT NULL COMMENT '应用的收费策略id' AFTER apply_charge_strategy,
+    ADD COLUMN charge_strategy_desc varchar(50) DEFAULT NULL COMMENT '应用的收费策略描述,如10元/吨' AFTER charge_strategy_id;