diff --git a/bms-back/bms-admin/src/main/java/com/bms/web/controller/customer/supplierinfo/BmsSupplierController.java b/bms-back/bms-admin/src/main/java/com/bms/web/controller/customer/supplierinfo/BmsSupplierController.java index 109e7577..a8d99d6e 100644 --- a/bms-back/bms-admin/src/main/java/com/bms/web/controller/customer/supplierinfo/BmsSupplierController.java +++ b/bms-back/bms-admin/src/main/java/com/bms/web/controller/customer/supplierinfo/BmsSupplierController.java @@ -90,6 +90,16 @@ public class BmsSupplierController extends BaseController return toAjax(bmsSupplierService.updateBmsSupplier(bmsSupplier)); } + /** 只绑定这一家供应商的渠道 */ + @PreAuthorize("@ss.hasPermi('customersupplier:supplierinfo:bindChannel')") + @Log(title = "供应商绑定渠道", businessType = BusinessType.UPDATE) + @PutMapping("/{supplierId}/channels") + public AjaxResult bindChannels(@PathVariable("supplierId") Long supplierId, @RequestBody BmsSupplier bmsSupplier) + { + String channelIds = bmsSupplier == null ? "" : bmsSupplier.getChannelIds(); + return toAjax(bmsSupplierService.bindChannels(supplierId, channelIds)); + } + /** 删除供应商 */ @PreAuthorize("@ss.hasPermi('customersupplier:supplierinfo:remove')") @Log(title = "供应商信息", businessType = BusinessType.DELETE) diff --git a/bms-back/bms-admin/src/main/java/com/bms/web/controller/price/BillingController.java b/bms-back/bms-admin/src/main/java/com/bms/web/controller/price/BillingController.java index 042d08dc..b1253159 100644 --- a/bms-back/bms-admin/src/main/java/com/bms/web/controller/price/BillingController.java +++ b/bms-back/bms-admin/src/main/java/com/bms/web/controller/price/BillingController.java @@ -378,7 +378,7 @@ public class BillingController extends BaseController return query; } - @PreAuthorize("@ss.hasPermi('price:billing:bill') or @ss.hasPermi('price:orderBill:list')") + @PreAuthorize("@ss.hasPermi('price:billing:bill') or @ss.hasPermi('price:orderBill:list') or @ss.hasPermi('price:payOrder:query')") @GetMapping("/bill/{billId}") public AjaxResult getBill(@PathVariable Long billId) { @@ -389,7 +389,7 @@ public class BillingController extends BaseController * 该订单的 ES BILL 日志(计费 / 上游同步 / 失败快照)。 * bizId 优先取 transferNo,其次取 orderNo(与写入路径一致)。 */ - @PreAuthorize("@ss.hasPermi('price:billing:bill') or @ss.hasPermi('price:orderBill:list')") + @PreAuthorize("@ss.hasPermi('price:billing:bill') or @ss.hasPermi('price:orderBill:list') or @ss.hasPermi('price:payOrder:query')") @GetMapping("/bill/{billId}/history") public TableDataInfo billHistory(@PathVariable("billId") Long billId) { diff --git a/bms-back/bms-admin/src/main/java/com/bms/web/controller/price/PayOrderController.java b/bms-back/bms-admin/src/main/java/com/bms/web/controller/price/PayOrderController.java new file mode 100644 index 00000000..0644c6e3 --- /dev/null +++ b/bms-back/bms-admin/src/main/java/com/bms/web/controller/price/PayOrderController.java @@ -0,0 +1,138 @@ +package com.bms.web.controller.price; + +import java.util.HashMap; +import java.util.Map; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import com.bms.common.core.controller.BaseController; +import com.bms.common.core.domain.AjaxResult; +import com.bms.common.core.page.TableDataInfo; +import com.bms.price.domain.PayOrderFeeLine; +import com.bms.price.domain.PayOrderQuery; +import com.bms.price.domain.PayOrderRecalcCommand; +import com.bms.price.domain.PayOrderRecalcTask; +import com.bms.price.service.IPayOrderListService; + +/** 提单管理下的应付列表。 */ +@RestController +@RequestMapping("/price/payOrder") +public class PayOrderController extends BaseController +{ + @Autowired + private IPayOrderListService payOrderListService; + + @PreAuthorize("@ss.hasPermi('price:payOrder:list')") + @GetMapping("/list") + public TableDataInfo list(PayOrderQuery query) + { + startPage(); + return getDataTable(payOrderListService.list(query)); + } + + /** + * 按订单号或提单号批量重算尾程应付。一票失败不影响其他订单。 + * + * @param command sourceType 为 ORDER 或 LADING,text 为单号原文 + * @return 成功数、失败数和每一票的结果 + */ + @PreAuthorize("@ss.hasPermi('price:payOrder:recalc')") + @PostMapping("/recalc") + public AjaxResult recalc(@RequestBody PayOrderRecalcCommand command) + { + Map payload = new HashMap<>(); + payload.put("taskId", payOrderListService.submitRecalc(command)); + return success(payload); + } + + /** + * 查询应付费用重算进度。 + * + * @param taskId 任务号 + * @return Redis 中的进度和每一票结果 + */ + @PreAuthorize("@ss.hasPermi('price:payOrder:recalc')") + @GetMapping("/recalc/task/{taskId}") + public AjaxResult recalcTask(@PathVariable String taskId) + { + PayOrderRecalcTask task = payOrderListService.getRecalcTask(taskId); + if (task == null) + { + return error("重算任务不存在或已过期"); + } + return success(task); + } + + /** + * 取消还没开始的应付费用重算。正在计算的这一票会算完。 + * + * @param taskId 任务号 + * @return 更新后的进度 + */ + @PreAuthorize("@ss.hasPermi('price:payOrder:recalc')") + @PostMapping("/recalc/task/{taskId}/cancel") + public AjaxResult cancelRecalc(@PathVariable String taskId) + { + return success(payOrderListService.cancelRecalc(taskId)); + } + + /** + * 查看一票订单的应付费用,按 A、B、C、D 四段返回。 + * + * @param billId 计费订单 ID + * @return 四段费用 + */ + @PreAuthorize("@ss.hasPermi('price:payOrder:fee')") + @GetMapping("/{billId}/fees") + public AjaxResult fees(@PathVariable String billId) + { + return success(payOrderListService.fees(billId)); + } + + /** + * 在某一段手工增加一行应付费用。创建人取当前登录用户。 + * + * @param billId 计费订单 ID + * @param line 费用项、金额、币种、说明和所属阶段 + * @return 写入后的费用行 + */ + @PreAuthorize("@ss.hasPermi('price:payOrder:feeAdd')") + @PostMapping("/{billId}/fees") + public AjaxResult addFee(@PathVariable String billId, @RequestBody PayOrderFeeLine line) + { + return success(payOrderListService.addManualFee(billId, line)); + } + + /** + * 逻辑删除一条应付费用。 + * + * @param feeId 费用明细 ID + * @return 操作结果 + */ + @PreAuthorize("@ss.hasPermi('price:payOrder:feeRemove')") + @DeleteMapping("/fees/{feeId}") + public AjaxResult removeFee(@PathVariable String feeId) + { + payOrderListService.removeFee(feeId); + return success(); + } + + /** + * 分页查看一票订单的费用操作日志,含变更前和变更后。 + * + * @param billId 计费订单 ID + * @return 当前页日志 + */ + @PreAuthorize("@ss.hasPermi('price:payOrder:log')") + @GetMapping("/{billId}/feeLogs") + public TableDataInfo feeLogs(@PathVariable String billId) + { + return getDataTable(payOrderListService.feeLogs(billId)); + } +} diff --git a/bms-back/bms-admin/src/main/java/com/bms/web/controller/price/PayProductController.java b/bms-back/bms-admin/src/main/java/com/bms/web/controller/price/PayProductController.java index 5925ab50..a04765c6 100644 --- a/bms-back/bms-admin/src/main/java/com/bms/web/controller/price/PayProductController.java +++ b/bms-back/bms-admin/src/main/java/com/bms/web/controller/price/PayProductController.java @@ -37,7 +37,7 @@ import com.bms.price.service.IPaySurchargeRuleService; import jakarta.servlet.http.HttpServletResponse; /** - * 价格基础下的应付配置。导入先预览,确认后才入库。 + * 应付管理下的应付配置。导入先预览,确认后才入库。 */ @RestController @RequestMapping("/price/pay") @@ -173,7 +173,7 @@ public class PayProductController extends BaseController } /** 批量绑定渠道应收/应付产品 */ - @PreAuthorize("@ss.hasAnyPermi('price:pay:edit,data:serviceChannel:edit')") + @PreAuthorize("@ss.hasAnyPermi('price:pay:edit,price:pay:bind,data:serviceChannel:edit')") @Log(title = "渠道批量绑定产品", businessType = BusinessType.UPDATE) @PutMapping("/channel/batchBind") public AjaxResult batchBindChannel(@RequestBody Map body) diff --git a/bms-back/bms-system/src/main/java/com/bms/customer/supplierinfo/domain/BmsSupplier.java b/bms-back/bms-system/src/main/java/com/bms/customer/supplierinfo/domain/BmsSupplier.java index 2f004171..aa7db113 100644 --- a/bms-back/bms-system/src/main/java/com/bms/customer/supplierinfo/domain/BmsSupplier.java +++ b/bms-back/bms-system/src/main/java/com/bms/customer/supplierinfo/domain/BmsSupplier.java @@ -136,6 +136,10 @@ public class BmsSupplier extends BaseEntity @Excel(name = "合作状态", readConverterExp = "0=正常,1=暂停,2=终止") private String cooperationStatus; + /** 数据来源,字典 bms_supplier_data_source。空表示未填写 */ + @Excel(name = "数据来源", dictType = "bms_supplier_data_source") + private String dataSource; + /** 绑定的渠道/服务ID */ private String channelIds; diff --git a/bms-back/bms-system/src/main/java/com/bms/customer/supplierinfo/mapper/BmsSupplierMapper.java b/bms-back/bms-system/src/main/java/com/bms/customer/supplierinfo/mapper/BmsSupplierMapper.java index 2ab75f5c..64332104 100644 --- a/bms-back/bms-system/src/main/java/com/bms/customer/supplierinfo/mapper/BmsSupplierMapper.java +++ b/bms-back/bms-system/src/main/java/com/bms/customer/supplierinfo/mapper/BmsSupplierMapper.java @@ -26,6 +26,9 @@ public interface BmsSupplierMapper /** 修改供应商 */ public int updateBmsSupplier(BmsSupplier bmsSupplier); + /** 只更新供应商绑定的渠道编码。 */ + public int updateSupplierChannels(BmsSupplier bmsSupplier); + /** 删除供应商 */ public int deleteBmsSupplierBySupplierId(Long supplierId); diff --git a/bms-back/bms-system/src/main/java/com/bms/customer/supplierinfo/service/IBmsSupplierService.java b/bms-back/bms-system/src/main/java/com/bms/customer/supplierinfo/service/IBmsSupplierService.java index d4cfd3e2..4747cd16 100644 --- a/bms-back/bms-system/src/main/java/com/bms/customer/supplierinfo/service/IBmsSupplierService.java +++ b/bms-back/bms-system/src/main/java/com/bms/customer/supplierinfo/service/IBmsSupplierService.java @@ -26,6 +26,9 @@ public interface IBmsSupplierService /** 修改供应商 */ public int updateBmsSupplier(BmsSupplier bmsSupplier); + /** 只改这一家供应商绑定的渠道,其它资料不动。 */ + public int bindChannels(Long supplierId, String channelIds); + /** 批量删除供应商 */ public int deleteBmsSupplierBySupplierIds(Long[] supplierIds); diff --git a/bms-back/bms-system/src/main/java/com/bms/customer/supplierinfo/service/impl/BmsSupplierServiceImpl.java b/bms-back/bms-system/src/main/java/com/bms/customer/supplierinfo/service/impl/BmsSupplierServiceImpl.java index 243ea0e7..12f62126 100644 --- a/bms-back/bms-system/src/main/java/com/bms/customer/supplierinfo/service/impl/BmsSupplierServiceImpl.java +++ b/bms-back/bms-system/src/main/java/com/bms/customer/supplierinfo/service/impl/BmsSupplierServiceImpl.java @@ -1,6 +1,7 @@ package com.bms.customer.supplierinfo.service.impl; import java.util.Date; +import java.util.LinkedHashSet; import java.util.List; import com.bms.common.annotation.DataScope; @@ -302,6 +303,61 @@ public class BmsSupplierServiceImpl implements IBmsSupplierService return bmsSupplierMapper.updateBmsSupplier(bmsSupplier); } + /** + * 只改绑定渠道。不走整单修改,避免把附件、采购员和合同日期清掉。 + */ + @Override + public int bindChannels(Long supplierId, String channelIds) + { + if (supplierId == null) + { + throw new ServiceException("请选择供应商"); + } + if (bmsSupplierMapper.selectBmsSupplierBySupplierId(supplierId) == null) + { + throw new ServiceException("供应商不存在"); + } + String value = joinChannels(channelIds); + if (value.length() > 1000) + { + throw new ServiceException("绑定的渠道过多,请减少后再保存"); + } + BmsSupplier row = new BmsSupplier(); + row.setSupplierId(supplierId); + row.setChannelIds(value); + row.setUpdateBy(SecurityUtils.getUsername()); + row.setUpdateTime(DateUtils.getNowDate()); + int rows = bmsSupplierMapper.updateSupplierChannels(row); + if (rows == 0) + { + throw new ServiceException("供应商不存在"); + } + return rows; + } + + /** 渠道编码去空白、去重,仍按选择顺序用逗号拼起来。 */ + private static String joinChannels(String channelIds) + { + if (StringUtils.isEmpty(channelIds)) + { + return ""; + } + LinkedHashSet codes = new LinkedHashSet<>(); + for (String part : channelIds.split(",")) + { + if (part == null) + { + continue; + } + String code = part.trim(); + if (!code.isEmpty()) + { + codes.add(code); + } + } + return String.join(",", codes); + } + @Transactional(rollbackFor = Exception.class) @Override public int deleteBmsSupplierBySupplierIds(Long[] supplierIds) diff --git a/bms-back/bms-system/src/main/java/com/bms/price/airbill/domain/SrvBillAirAllocFee.java b/bms-back/bms-system/src/main/java/com/bms/price/airbill/domain/SrvBillAirAllocFee.java index 19fe0d10..31f00533 100644 --- a/bms-back/bms-system/src/main/java/com/bms/price/airbill/domain/SrvBillAirAllocFee.java +++ b/bms-back/bms-system/src/main/java/com/bms/price/airbill/domain/SrvBillAirAllocFee.java @@ -20,6 +20,9 @@ public class SrvBillAirAllocFee /** 费用状态,字典 bill_fee_status */ private String billFeeStatus; + /** 费用类型,字典 bms_fee_type 的英文编码 */ + private String feeType; + private String feeName; private BigDecimal price; diff --git a/bms-back/bms-system/src/main/java/com/bms/price/airbill/domain/SrvBillAirFee.java b/bms-back/bms-system/src/main/java/com/bms/price/airbill/domain/SrvBillAirFee.java index 4a6de461..17d58bd3 100644 --- a/bms-back/bms-system/src/main/java/com/bms/price/airbill/domain/SrvBillAirFee.java +++ b/bms-back/bms-system/src/main/java/com/bms/price/airbill/domain/SrvBillAirFee.java @@ -15,9 +15,12 @@ public class SrvBillAirFee private String billCode; - /** 附加费编号 prc_surcharge.sc_id */ + /** 费用类型,字典 bms_fee_type 的英文编码 */ private String feeType; + /** 附加费配置ID,对应 prc_surcharge.sc_id */ + private Long scId; + /** 附加费名称,仅展示,不入库 */ private String feeName; diff --git a/bms-back/bms-system/src/main/java/com/bms/price/domain/PayOrderCostResult.java b/bms-back/bms-system/src/main/java/com/bms/price/domain/PayOrderCostResult.java index 2b6c8548..6b39e730 100644 --- a/bms-back/bms-system/src/main/java/com/bms/price/domain/PayOrderCostResult.java +++ b/bms-back/bms-system/src/main/java/com/bms/price/domain/PayOrderCostResult.java @@ -2,6 +2,7 @@ package com.bms.price.domain; import java.math.BigDecimal; import java.util.List; +import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Data; /** 按订单生成应付的结果。skipped 是价卡里有、但这票算不了的附加费。 */ @@ -29,4 +30,12 @@ public class PayOrderCostResult private List fees; private List skipped; + + /** 本次落库的应付费用,供提交成功后写日志。不返回给页面。 */ + @JsonIgnore + private transient List loggedFees; + + /** 本次费用日志的操作类型,字典 bms_pay_fee_log_type */ + @JsonIgnore + private transient String feeLogType; } diff --git a/bms-back/bms-system/src/main/java/com/bms/price/domain/PayOrderFeeBoard.java b/bms-back/bms-system/src/main/java/com/bms/price/domain/PayOrderFeeBoard.java new file mode 100644 index 00000000..8a804275 --- /dev/null +++ b/bms-back/bms-system/src/main/java/com/bms/price/domain/PayOrderFeeBoard.java @@ -0,0 +1,18 @@ +package com.bms.price.domain; + +import java.util.ArrayList; +import java.util.List; +import lombok.Data; + +/** 一票订单的应付费用,按 abcd 四段排好。 */ +@Data +public class PayOrderFeeBoard +{ + private String billId; + + private String orderNo; + + private String ladingNo; + + private List sections = new ArrayList<>(); +} diff --git a/bms-back/bms-system/src/main/java/com/bms/price/domain/PayOrderFeeLine.java b/bms-back/bms-system/src/main/java/com/bms/price/domain/PayOrderFeeLine.java new file mode 100644 index 00000000..936be741 --- /dev/null +++ b/bms-back/bms-system/src/main/java/com/bms/price/domain/PayOrderFeeLine.java @@ -0,0 +1,47 @@ +package com.bms.price.domain; + +import java.math.BigDecimal; +import java.util.Date; +import com.fasterxml.jackson.annotation.JsonFormat; +import lombok.Data; + +/** 应付列表费用弹框里的一条费用。 */ +@Data +public class PayOrderFeeLine +{ + /** 费用明细 ID。新增时为空 */ + private String feeId; + + /** 费用类型,字典 bms_fee_type 的英文编码。手输名称放不下时记 MANUAL */ + private String feeType; + + /** 费用项名称。手工费用按填写的名称保存 */ + private String feeName; + + /** 1A 2B 3C 4D */ + private String level; + + private BigDecimal amount; + + private String currency; + + /** CALC 尾程计算,LADING 提单分摊,MANUAL 手工 */ + private String feeSource; + + private String remark; + + /** 已进入应付账单时不能删除 */ + private Long statementLineId; + + /** 创建人 */ + private String createBy; + + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") + private Date createTime; + + /** 更新人 */ + private String updateBy; + + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") + private Date updateTime; +} diff --git a/bms-back/bms-system/src/main/java/com/bms/price/domain/PayOrderFeeSection.java b/bms-back/bms-system/src/main/java/com/bms/price/domain/PayOrderFeeSection.java new file mode 100644 index 00000000..da687267 --- /dev/null +++ b/bms-back/bms-system/src/main/java/com/bms/price/domain/PayOrderFeeSection.java @@ -0,0 +1,16 @@ +package com.bms.price.domain; + +import java.util.ArrayList; +import java.util.List; +import lombok.Data; + +/** 应付费用的一个阶段。1A 头程仓储,2B 提单运输,3C 清关,4D 尾程。 */ +@Data +public class PayOrderFeeSection +{ + private String level; + + private String title; + + private List fees = new ArrayList<>(); +} diff --git a/bms-back/bms-system/src/main/java/com/bms/price/domain/PayOrderQuery.java b/bms-back/bms-system/src/main/java/com/bms/price/domain/PayOrderQuery.java new file mode 100644 index 00000000..11808847 --- /dev/null +++ b/bms-back/bms-system/src/main/java/com/bms/price/domain/PayOrderQuery.java @@ -0,0 +1,17 @@ +package com.bms.price.domain; + +import lombok.Data; + +/** 应付列表查询条件。 */ +@Data +public class PayOrderQuery +{ + private String orderNo; + + /** 多个订单号。由服务按逗号、空格或换行拆开。 */ + private java.util.List orderNos; + + private String ladingNo; + + private String customerName; +} diff --git a/bms-back/bms-system/src/main/java/com/bms/price/domain/PayOrderRecalcCommand.java b/bms-back/bms-system/src/main/java/com/bms/price/domain/PayOrderRecalcCommand.java new file mode 100644 index 00000000..d03c82ce --- /dev/null +++ b/bms-back/bms-system/src/main/java/com/bms/price/domain/PayOrderRecalcCommand.java @@ -0,0 +1,14 @@ +package com.bms.price.domain; + +import lombok.Data; + +/** 应付列表上的费用重算条件。一次只按订单号或提单号其中一种。 */ +@Data +public class PayOrderRecalcCommand +{ + /** ORDER 按订单号,LADING 按提单号 */ + private String sourceType; + + /** 单号原文。可用逗号、空格或换行分隔 */ + private String text; +} diff --git a/bms-back/bms-system/src/main/java/com/bms/price/domain/PayOrderRecalcLine.java b/bms-back/bms-system/src/main/java/com/bms/price/domain/PayOrderRecalcLine.java new file mode 100644 index 00000000..f1a58adf --- /dev/null +++ b/bms-back/bms-system/src/main/java/com/bms/price/domain/PayOrderRecalcLine.java @@ -0,0 +1,23 @@ +package com.bms.price.domain; + +import lombok.Data; + +/** 费用重算里的一票结果。 */ +@Data +public class PayOrderRecalcLine +{ + private String billId; + + private String orderNo; + + private String ladingNo; + + /** 这一条是否已经处理完 */ + private boolean finished; + + /** 这一票是否已经生成应付费用 */ + private boolean success; + + /** 失败原因。成功时为空 */ + private String message; +} diff --git a/bms-back/bms-system/src/main/java/com/bms/price/domain/PayOrderRecalcResult.java b/bms-back/bms-system/src/main/java/com/bms/price/domain/PayOrderRecalcResult.java new file mode 100644 index 00000000..7c80a173 --- /dev/null +++ b/bms-back/bms-system/src/main/java/com/bms/price/domain/PayOrderRecalcResult.java @@ -0,0 +1,19 @@ +package com.bms.price.domain; + +import java.util.ArrayList; +import java.util.List; +import lombok.Data; + +/** 一次费用重算的结果。失败行不影响已经成功的订单。 */ +@Data +public class PayOrderRecalcResult +{ + /** 计费成功的订单数 */ + private int successCount; + + /** 未生成费用的订单数,含找不到的单号 */ + private int failCount; + + /** 每一票或每一个没对上的单号 */ + private List lines = new ArrayList<>(); +} diff --git a/bms-back/bms-system/src/main/java/com/bms/price/domain/PayOrderRecalcTask.java b/bms-back/bms-system/src/main/java/com/bms/price/domain/PayOrderRecalcTask.java new file mode 100644 index 00000000..43cf6eab --- /dev/null +++ b/bms-back/bms-system/src/main/java/com/bms/price/domain/PayOrderRecalcTask.java @@ -0,0 +1,40 @@ +package com.bms.price.domain; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; +import lombok.Data; + +/** 应付费用重算任务。待处理订单和进度都放在 Redis。 */ +@Data +public class PayOrderRecalcTask implements Serializable +{ + private static final long serialVersionUID = 1L; + + public static final String PENDING = "PENDING"; + + public static final String RUNNING = "RUNNING"; + + public static final String SUCCESS = "SUCCESS"; + + public static final String FAIL = "FAIL"; + + public static final String CANCELLED = "CANCELLED"; + + private String taskId; + + private String status; + + private int percent; + + private String message; + + private int total; + + private int successCount; + + private int failCount; + + /** 查出来的订单,以及没对上的单号。处理完一条就更新这一条。 */ + private List lines = new ArrayList<>(); +} diff --git a/bms-back/bms-system/src/main/java/com/bms/price/domain/PayOrderRow.java b/bms-back/bms-system/src/main/java/com/bms/price/domain/PayOrderRow.java new file mode 100644 index 00000000..75c0422b --- /dev/null +++ b/bms-back/bms-system/src/main/java/com/bms/price/domain/PayOrderRow.java @@ -0,0 +1,49 @@ +package com.bms.price.domain; + +import java.math.BigDecimal; +import java.util.Date; +import com.fasterxml.jackson.annotation.JsonFormat; +import lombok.Data; + +/** 应付列表里的一票订单。提单号来自订单扩展上的空运单号。 */ +@Data +public class PayOrderRow +{ + private String billId; + + private String orderNo; + + private String ladingNo; + + private String trackingNo; + + private String customerName; + + private String productName; + + private String countryName; + + private String channelName; + + private BigDecimal chargeWeight; + + private BigDecimal payTotal; + + private String currency; + + /** 应付计费状态,字典 bms_pay_calc_status:1计费成功,2计费失败 */ + private Integer payCalcStatus; + + /** 计费失败原因 */ + private String payCalcMsg; + + /** 应付主表更新人 */ + private String updateBy; + + /** 应付主表更新时间 */ + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") + private Date updateTime; + + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") + private Date bizDate; +} diff --git a/bms-back/bms-system/src/main/java/com/bms/price/domain/PrcPayBill.java b/bms-back/bms-system/src/main/java/com/bms/price/domain/PrcPayBill.java index d8f14a1c..9c16139a 100644 --- a/bms-back/bms-system/src/main/java/com/bms/price/domain/PrcPayBill.java +++ b/bms-back/bms-system/src/main/java/com/bms/price/domain/PrcPayBill.java @@ -24,8 +24,15 @@ public class PrcPayBill implements Serializable private BigDecimal redlineAmount; /** 成本价合计(当前计费结果) */ private BigDecimal costAmount; - /** 应付合计(当前等于成本价) */ + /** 应付合计(当前等于成本价,落库后按全部未删除明细重算) */ private BigDecimal payTotal; + + /** 应付计费状态,字典 bms_pay_calc_status:1计费成功,2计费失败 */ + private Integer payCalcStatus; + + /** 计费失败原因,最长 100 字 */ + private String payCalcMsg; + /** 业务员/销售员 */ private String belongSaler; /** 销售员编码 */ diff --git a/bms-back/bms-system/src/main/java/com/bms/price/domain/PrcPayBillFee.java b/bms-back/bms-system/src/main/java/com/bms/price/domain/PrcPayBillFee.java index 38e28144..d7f53081 100644 --- a/bms-back/bms-system/src/main/java/com/bms/price/domain/PrcPayBillFee.java +++ b/bms-back/bms-system/src/main/java/com/bms/price/domain/PrcPayBillFee.java @@ -4,6 +4,7 @@ import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Data; /** 应付费用明细 prc_pay_bill_fee */ @@ -17,8 +18,13 @@ public class PrcPayBillFee implements Serializable private Long billId; /** 应付主表ID */ private String payBillId; + /** 费用类型,字典 bms_fee_type 的英文编码 */ private String feeType; + + /** 展示用的费用项名称,不入库。附加费取配置名称,其余取字典标签 */ private String feeName; + + /** 尾程计算时是附加费配置ID。提单分摊时是 srv_bill_air_fee.id */ private Long scId; /** 费用所属阶段:1 a段,2 b段,3 c段,4 d段 */ @@ -31,7 +37,7 @@ public class PrcPayBillFee implements Serializable /** CALC 计算,LADING 提单分摊,MANUAL 人工 */ private String feeSource; - /** 来源数据id */ + /** 来源数据id。提单分摊时为 srv_bill_air_fee.id */ private String sourceId; /** 是否删除:0未删除 1已删除 */ @@ -44,6 +50,32 @@ public class PrcPayBillFee implements Serializable private Long settleSupplierId; private String settleSupplierName; + + /** 创建人 */ + private String createBy; + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date createTime; + + /** 更新人 */ + private String updateBy; + + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") + private Date updateTime; + + /** 写日志时带上的变更前费用项,不入库 */ + @JsonIgnore + private String logBeforeName; + + /** 写日志时带上的变更前金额,不入库 */ + @JsonIgnore + private BigDecimal logBeforeAmount; + + /** 写日志时带上的变更前币种,不入库 */ + @JsonIgnore + private String logBeforeCurrency; + + /** 为 true 时日志只记变更前。重算后消失的计算费用用,不入库 */ + @JsonIgnore + private Boolean logAfterBlank; } diff --git a/bms-back/bms-system/src/main/java/com/bms/price/domain/PrcPayBillFeeLog.java b/bms-back/bms-system/src/main/java/com/bms/price/domain/PrcPayBillFeeLog.java new file mode 100644 index 00000000..7c7b3879 --- /dev/null +++ b/bms-back/bms-system/src/main/java/com/bms/price/domain/PrcPayBillFeeLog.java @@ -0,0 +1,58 @@ +package com.bms.price.domain; + +import java.io.Serializable; +import java.math.BigDecimal; +import java.util.Date; +import com.fasterxml.jackson.annotation.JsonFormat; +import lombok.Data; + +/** 应付费用日志 prc_pay_bill_fee_log */ +@Data +public class PrcPayBillFeeLog implements Serializable +{ + private static final long serialVersionUID = 1L; + + private Long logId; + + private String feeId; + + private Long billId; + + /** 费用项 */ + private String feeName; + + private BigDecimal amount; + + private String currency; + + /** 变更前费用项 */ + private String beforeFeeName; + + /** 变更前金额 */ + private BigDecimal beforeAmount; + + /** 变更前币种 */ + private String beforeCurrency; + + /** 变更后费用项 */ + private String afterFeeName; + + /** 变更后金额 */ + private BigDecimal afterAmount; + + /** 变更后币种 */ + private String afterCurrency; + + /** 操作类型,字典 bms_pay_fee_log_type */ + private String operationType; + + /** 备注。费用重算失败时写入失败原因 */ + private String remark; + + /** 操作人 */ + private String createBy; + + /** 操作时间 */ + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") + private Date createTime; +} diff --git a/bms-back/bms-system/src/main/java/com/bms/price/domain/vo/PrcProfitReportQuery.java b/bms-back/bms-system/src/main/java/com/bms/price/domain/vo/PrcProfitReportQuery.java index 6e62a0bc..651bd1aa 100644 --- a/bms-back/bms-system/src/main/java/com/bms/price/domain/vo/PrcProfitReportQuery.java +++ b/bms-back/bms-system/src/main/java/com/bms/price/domain/vo/PrcProfitReportQuery.java @@ -33,7 +33,9 @@ public class PrcProfitReportQuery extends BaseEntity private List customerNames; private String belongSalerCode; private String productCode; + private String productName; private String countryCode; + private String countryName; private String currency; /** 订单维度应收状态筛选:UNBILLED、PARTIAL、BILLED。 */ private String arBillStatus; diff --git a/bms-back/bms-system/src/main/java/com/bms/price/mapper/PayOrderListMapper.java b/bms-back/bms-system/src/main/java/com/bms/price/mapper/PayOrderListMapper.java new file mode 100644 index 00000000..9c936d3b --- /dev/null +++ b/bms-back/bms-system/src/main/java/com/bms/price/mapper/PayOrderListMapper.java @@ -0,0 +1,30 @@ +package com.bms.price.mapper; + +import java.util.List; +import org.apache.ibatis.annotations.Param; +import com.bms.price.domain.PayOrderQuery; +import com.bms.price.domain.PayOrderRow; + +/** 应付列表。 */ +public interface PayOrderListMapper +{ + List selectList(PayOrderQuery query); + + PayOrderRow selectRow(@Param("billId") String billId); + + /** + * 按订单号精确找出要重算的订单。 + * + * @param orderNos 订单号,已去重 + * @return 订单号和提单号 + */ + List selectByOrderNos(@Param("orderNos") List orderNos); + + /** + * 按提单号找出下面的全部订单。提单号对应订单扩展上的空运单号。 + * + * @param ladingNos 提单号,已去重 + * @return 这些提单下的订单 + */ + List selectByLadingNos(@Param("ladingNos") List ladingNos); +} diff --git a/bms-back/bms-system/src/main/java/com/bms/price/mapper/PrcPayBillFeeLogMapper.java b/bms-back/bms-system/src/main/java/com/bms/price/mapper/PrcPayBillFeeLogMapper.java new file mode 100644 index 00000000..5791bb7d --- /dev/null +++ b/bms-back/bms-system/src/main/java/com/bms/price/mapper/PrcPayBillFeeLogMapper.java @@ -0,0 +1,25 @@ +package com.bms.price.mapper; + +import java.util.List; +import org.apache.ibatis.annotations.Param; +import com.bms.price.domain.PrcPayBillFeeLog; + +/** 应付费用日志 prc_pay_bill_fee_log。 */ +public interface PrcPayBillFeeLogMapper +{ + /** + * 批量写入应付费用日志。 + * + * @param logs 本次操作的费用快照 + * @return 影响行数 + */ + int insertBatch(@Param("list") List logs); + + /** + * 按订单读取费用日志,新的在前。 + * + * @param billId 计费订单 ID + * @return 日志 + */ + List selectByBillId(@Param("billId") Long billId); +} diff --git a/bms-back/bms-system/src/main/java/com/bms/price/mapper/PrcPayBillFeeMapper.java b/bms-back/bms-system/src/main/java/com/bms/price/mapper/PrcPayBillFeeMapper.java index a9802717..043cd4e9 100644 --- a/bms-back/bms-system/src/main/java/com/bms/price/mapper/PrcPayBillFeeMapper.java +++ b/bms-back/bms-system/src/main/java/com/bms/price/mapper/PrcPayBillFeeMapper.java @@ -15,6 +15,39 @@ public interface PrcPayBillFeeMapper */ public List selectByBillId(Long billId); + /** + * 按费用明细 ID 读取一行。已逻辑删除的也返回,调用方自己判断。 + * + * @param feeId 费用明细 ID + * @return 费用行,没有时为 null + */ + public PrcPayBillFee selectByFeeId(@Param("feeId") String feeId); + + /** + * 写入一条手工费用。来源固定为 MANUAL,并记下创建人、更新人。 + * + * @param fee 费用项、金额、币种、说明和所属阶段 + * @return 影响行数 + */ + public int insertManual(PrcPayBillFee fee); + + /** + * 逻辑删除一条费用。已经进入应付账单的行不删。 + * + * @param feeId 费用明细 ID + * @param operator 当前登录人 + * @return 影响行数 + */ + public int markFeeDeleted(@Param("feeId") String feeId, @Param("operator") String operator); + + /** + * 这票订单里已经进入应付账单的计算费用条数。有则不能重算覆盖。 + * + * @param billId 计费订单 ID + * @return 已出账的计算费用条数 + */ + public int countSettledCalc(@Param("billId") Long billId); + /** * 插入一条订单应付费用。 * @@ -35,12 +68,14 @@ public interface PrcPayBillFeeMapper public int fillSourceIdByFeeIds(@Param("feeIds") List feeIds); /** - * 删除一票订单上来源为计算的费用。提单分摊和人工费用保留。 + * 逻辑删除一票订单上来源为计算的费用。提单分摊和人工费用保留。 + * 已进入应付账单的行不删。删除标记写成主键,避免重新生成时撞上唯一键。 * * @param billId 计费订单ID + * @param operator 操作人 * @return 影响行数 */ - public int deleteByBillId(Long billId); + public int markCalcDeleted(@Param("billId") Long billId, @Param("operator") String operator); /** * 逻辑删除某一条提单费用分摊到订单上的明细。 @@ -53,6 +88,9 @@ public interface PrcPayBillFeeMapper /** 这条提单费用已经分摊到的订单。作废前取出,用来重算应付总额。 */ public List selectBillIdsByLadingFee(@Param("feeId") Long feeId); + /** 这条提单费用已经分摊、且还没删除的订单费用。作废前取出,用来记日志。 */ + public List selectAliveByLadingFee(@Param("feeId") Long feeId); + /** 明细还没挂上应付主表时,按订单补上主表 ID。单次不超过 1000 个订单。 */ public int bindPayBillId(@Param("billIds") List billIds); diff --git a/bms-back/bms-system/src/main/java/com/bms/price/mapper/PrcPayBillMapper.java b/bms-back/bms-system/src/main/java/com/bms/price/mapper/PrcPayBillMapper.java index 54b7c749..10bfd992 100644 --- a/bms-back/bms-system/src/main/java/com/bms/price/mapper/PrcPayBillMapper.java +++ b/bms-back/bms-system/src/main/java/com/bms/price/mapper/PrcPayBillMapper.java @@ -65,4 +65,16 @@ public interface PrcPayBillMapper /** 订单还没有应付主表时补一行,总额随后按明细重算。单次不超过 1000 个订单。 */ int insertMissingPayBills(@Param("billIds") List billIds, @Param("operator") String operator); + + /** + * 写下这票应付的计费状态和失败原因。成功时原因传空。 + * + * @param billId 计费订单 ID,对应 prc_pay_bill.bill_id + * @param status 1计费成功,2计费失败 + * @param message 失败原因,最长 100 字;成功时为 null + * @param operator 操作人账号 + * @return 影响行数 + */ + int markCalcStatus(@Param("billId") Long billId, @Param("status") Integer status, + @Param("message") String message, @Param("operator") String operator); } diff --git a/bms-back/bms-system/src/main/java/com/bms/price/pay/PayOrderFeeCalculator.java b/bms-back/bms-system/src/main/java/com/bms/price/pay/PayOrderFeeCalculator.java new file mode 100644 index 00000000..d5e7ab74 --- /dev/null +++ b/bms-back/bms-system/src/main/java/com/bms/price/pay/PayOrderFeeCalculator.java @@ -0,0 +1,646 @@ +package com.bms.price.pay; + +import java.math.BigDecimal; +import java.time.ZoneId; +import java.util.ArrayList; +import java.util.Date; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import com.bms.common.enums.PaymentMesEnum; +import com.bms.common.exception.ServiceException; +import com.bms.masterdata.domain.ServiceChannel; +import com.bms.masterdata.mapper.ServiceChannelMapper; +import com.bms.price.domain.PayOrderCostResult; +import com.bms.price.domain.PayPostcodeGroup; +import com.bms.price.domain.PayPostcodeLine; +import com.bms.price.domain.PayProduct; +import com.bms.price.domain.PaySurcharge; +import com.bms.price.domain.PaySurchargeRule; +import com.bms.price.domain.PayWeightBand; +import com.bms.price.domain.PrcOrderBill; +import com.bms.price.domain.PrcOrderBillExt; +import com.bms.price.mapper.PayPostcodeMapper; +import com.bms.price.mapper.PrcOrderBillExtMapper; +import com.bms.price.mapper.PrcOrderBillMapper; +import com.bms.price.service.IPayProductService; +import com.bms.price.service.IPaySurchargeRuleService; + +/** + * 按一票已经落库的订单,算出应付尾程运费和订单附加费。 + * 这里只计算,不写费用。账单生成、Oracle 订单同步和其他入口都调用这一处。 + */ +@Component +public class PayOrderFeeCalculator +{ + private static final ZoneId SHANGHAI = ZoneId.of("GMT+8"); + + @Autowired + private PrcOrderBillMapper orderBillMapper; + + @Autowired + private PrcOrderBillExtMapper orderBillExtMapper; + + @Autowired + private ServiceChannelMapper serviceChannelMapper; + + @Autowired + private IPayProductService payProductService; + + @Autowired + private PayPostcodeMapper payPostcodeMapper; + + @Autowired + private IPaySurchargeRuleService paySurchargeRuleService; + + /** + * 计算一票订单的尾程运费和附加费。渠道、价卡、分区或重量不齐时抛出业务异常,调用方决定是否落库。 + * + * @param billId 计费订单 ID,对应 prc_order_bill.bill_id + * @return 渠道、价卡版本、币种、尾程运费和订单附加费 + */ + public PayOrderCostResult calculate(Long billId) + { + PrcOrderBill bill = requireOrder(billId); + PrcOrderBillExt ext = orderBillExtMapper.selectByBillId(bill.getBillId()); + ServiceChannel channel = resolveChannel(ext); + Date priceDate = bizDate(bill); + PayProduct product = payProductService.selectPriceForDate(channel.getId(), priceDate); + BigDecimal weight = chargeWeight(bill); + Integer orderStatus = orderStatus(bill, ext); + List linked = linkedGroups(product); + String zoneName = resolveZone(channel, product, bill.getDestPostcode(), bill.getCountryCode(), bill.getCountryName(), linked); + applyCurrentSurcharge(channel.getId(), product); + List billingRules = product.getBillingRules(); + boolean postcodeOn = ruleOn(billingRules, PaySurchargeRules.POSTCODE); + boolean zoneOn = ruleOn(billingRules, PaySurchargeRules.ZONE); + List remoteHits = prefixRules(billingRules, PaySurchargeRules.POSTCODE) + ? null : remoteHits(linked, bill.getDestPostcode(), bill.getCountryCode(), bill.getCountryName()); + PayOrderCostResult result = PayCostCalculator.calculate(product, weight, bill.getPkgLength(), bill.getPkgWidth(), + bill.getPkgHeight(), bill.getDestPostcode(), zoneName, priceDate, orderStatus, remoteHits, postcodeOn, zoneOn, + bill.getCountryCode(), bill.getCountryName()); + result.setBillId(bill.getBillId()); + result.setChannelId(channel.getId()); + result.setChannelName(channel.getChannelName()); + result.setVersionNo(product.getVersionNo()); + result.setMessage(explain(channel, product, result.getMessage())); + return result; + } + + /** + * 读取这票订单当前尾程价卡上的归属供应商。渠道或价卡不齐时返回空字符串,不抛异常。 + * + * @param billId 计费订单 ID + * @return 价卡归属供应商名称,没有时为空字符串 + */ + public String supplierName(Long billId) + { + if (billId == null) + { + return ""; + } + try + { + PrcOrderBill bill = orderBillMapper.selectPrcOrderBillById(billId); + if (bill == null) + { + return ""; + } + ServiceChannel channel = resolveChannel(orderBillExtMapper.selectByBillId(bill.getBillId())); + PayProduct product = payProductService.selectPriceForDate(channel.getId(), bizDate(bill)); + return product.getSupplierName() == null ? "" : product.getSupplierName().trim(); + } + catch (ServiceException ex) + { + return ""; + } + } + + /** + * 读取计费订单。单号为空或库里没有这票时抛出业务异常。 + * + * @param billId 计费订单 ID + * @return 订单主表 + */ + private PrcOrderBill requireOrder(Long billId) + { + if (billId == null) + { + throw PaymentMesEnum.BMS_PAY_PICK_ORDER.exception(); + } + PrcOrderBill bill = orderBillMapper.selectPrcOrderBillById(billId); + if (bill == null) + { + throw PaymentMesEnum.BMS_PAY_ORDER_MISS.exception(); + } + return bill; + } + + /** + * 取价日。优先用订单业务日,没有时用下单时间。 + * + * @param bill 计费订单 + * @return 用来命中价卡版本的日期,两边都空时为 null + */ + private static Date bizDate(PrcOrderBill bill) + { + return bill.getBizDate() != null ? bill.getBizDate() : bill.getOrderTime(); + } + + /** + * 计费重。按计费重、重量、实重、收货重的顺序,取第一个大于 0 的值。 + * + * @param bill 计费订单 + * @return 公斤数,都没有时为 null + */ + private static BigDecimal chargeWeight(PrcOrderBill bill) + { + return firstPositive(bill.getChargeWeight(), bill.getWeight(), bill.getActualWeight(), bill.getReceiveWeight()); + } + + /** + * 订单状态。主表没有时用扩展表,用来判断退件类附加费是否收取。 + * + * @param bill 计费订单 + * @param ext 订单扩展,可以没有 + * @return 订单状态,两边都没有时为 null + */ + private static Integer orderStatus(PrcOrderBill bill, PrcOrderBillExt ext) + { + return bill.getOrderStatus() != null ? bill.getOrderStatus() : (ext == null ? null : ext.getOrderStatus()); + } + + /** + * 拼出这次计算用了哪条渠道、哪个产品和哪一版价卡。 + * + * @param channel 订单渠道 + * @param product 订单日期命中的价卡版本 + * @param detail 计算器给出的费用说明 + * @return 带渠道和版本的说明 + */ + private static String explain(ServiceChannel channel, PayProduct product, String detail) + { + String channelName = channel.getChannelName() == null ? channel.getChannelCode() : channel.getChannelName(); + String end = product.getTermEnd() == null ? "不限" : day(product.getTermEnd()); + return "渠道「" + channelName + "」" + product.getProductName() + " 第 " + product.getVersionNo() + + " 版(" + day(product.getTermStart()) + " 至 " + end + ")," + detail; + } + + /** + * 运费仍按订单日期取版本。附加费明细和计费条件改用这个产品今天生效的版本。 + * + * @param channelId 渠道 ID + * @param priced 订单日期已经命中的价卡,方法会改写它的附加费和计费条件 + */ + private void applyCurrentSurcharge(String channelId, PayProduct priced) + { + try + { + PayProduct current = payProductService.selectPriceForDate(channelId, new Date()); + if (current != null && current.getSurcharges() != null) + { + priced.setSurcharges(current.getSurcharges()); + } + } + catch (ServiceException ignored) + { + // 今天没有生效版本时,附加费明细仍用订单日期命中的那一版 + } + List rules = paySurchargeRuleService.listForCalc(priced); + priced.setBillingRules(rules == null ? new ArrayList<>() : rules); + } + + /** + * 这条计费条件是否启用。没有配置行时视为关闭。 + * + * @param rules 当前产品的计费条件 + * @param calcRule 条件编码,如 POSTCODE、ZONE + * @return 有启用行时为 true + */ + private static boolean ruleOn(List rules, String calcRule) + { + if (rules == null) + { + return false; + } + for (PaySurchargeRule rule : rules) + { + if (rule != null && calcRule.equals(rule.getCalcRule()) && !"0".equals(rule.getEnabled())) + { + return true; + } + } + return false; + } + + /** + * 计费条件里是否已经写了邮编前缀。写了就不再去应付邮编配置里查偏远。 + * + * @param rules 当前产品的计费条件 + * @param calcRule 条件编码,目前用于 POSTCODE + * @return 有非空邮编前缀时为 true + */ + private static boolean prefixRules(List rules, String calcRule) + { + if (rules == null) + { + return false; + } + for (PaySurchargeRule rule : rules) + { + if (rule == null || !calcRule.equals(rule.getCalcRule()) || "0".equals(rule.getEnabled()) || rule.getDetail() == null) + { + continue; + } + Object postcodes = rule.getDetail().get("postcodes"); + if (postcodes != null && !String.valueOf(postcodes).isBlank()) + { + return true; + } + } + return false; + } + + /** + * 用产品名称、报价工作表、字典值和关联分区表,对上这份产品的邮编配置。 + * + * @param product 当前价卡版本 + * @return 名称能对上的邮编组,没有时为空列表 + */ + private List linkedGroups(PayProduct product) + { + List names = new ArrayList<>(); + addName(names, product.getProductName()); + addName(names, product.getSheetName()); + addName(names, product.getDictValue()); + addName(names, product.getRelatedSheet()); + if (names.isEmpty()) + { + return new ArrayList<>(); + } + List found = payPostcodeMapper.selectGroupsForProduct(names); + return found == null ? new ArrayList<>() : found; + } + + /** + * 把非空名称放进匹配列表,已有的不重复加入。 + * + * @param names 已经收集的名称 + * @param value 产品名、工作表名或字典值 + */ + private static void addName(List names, String value) + { + if (value == null || value.isBlank()) + { + return; + } + String name = value.trim(); + if (!names.contains(name)) + { + names.add(name); + } + } + + /** + * 判断这票是否偏远。产品报价表已经挂了偏远名单时只用那一份,没命中就不再回价卡邮编。 + * 没有这份产品名单时,改查目的国家的偏远邮编;国家名单没命中则返回 null,价卡上的邮编条件仍可用。 + * + * @param linked 已对上的邮编组 + * @param postcode 收件邮编 + * @param countryCode 目的国二字码 + * @param countryName 目的国名称 + * @return 命中的偏远分区;产品有名单但没命中时返回空列表 + */ + private List remoteHits(List linked, String postcode, String countryCode, String countryName) + { + boolean productBook = false; + for (PayPostcodeGroup group : linked) + { + if (group != null && PayRemoteBook.remoteGroup(group)) + { + productBook = true; + break; + } + } + if (productBook) + { + return hitsOf(linked, postcode, countryCode, countryName); + } + if (blank(countryCode) && blank(countryName)) + { + return null; + } + List countryGroups = payPostcodeMapper.selectRemoteGroupsByCountry(countryCode, countryName); + if (countryGroups == null || countryGroups.isEmpty()) + { + return null; + } + List hits = hitsOf(countryGroups, postcode, countryCode, countryName); + return hits == null || hits.isEmpty() ? null : hits; + } + + /** + * 在给定邮编组里做偏远匹配。没有偏远组时返回 null,有组但邮编没命中时返回空列表。 + * + * @param groups 参与匹配的邮编组 + * @param postcode 收件邮编 + * @param countryCode 目的国二字码 + * @param countryName 目的国名称 + * @return 命中结果 + */ + private List hitsOf(List groups, String postcode, String countryCode, String countryName) + { + List remoteIds = new ArrayList<>(); + boolean anyRemote = false; + for (PayPostcodeGroup group : groups) + { + if (group == null || group.getGroupId() == null || !PayRemoteBook.remoteGroup(group)) + { + continue; + } + anyRemote = true; + if (sameCountry(group, countryCode, countryName)) + { + remoteIds.add(group.getGroupId()); + } + } + if (!anyRemote) + { + return null; + } + if (remoteIds.isEmpty()) + { + return new ArrayList<>(); + } + List lines = postcode == null || postcode.isBlank() + ? new ArrayList<>() : payPostcodeMapper.selectLinesByGroups(remoteIds); + return PayRemoteBook.hits(groups, lines, postcode, countryCode, countryName); + } + + /** + * 价卡有多个地区时,选出这一票对应的价格列。优先用产品关联的邮编分区,对不上再按名称关键字找。 + * 只有一个地区时返回 null,计费不再按分区过滤。 + * + * @param channel 订单渠道,关键字匹配时备用 + * @param product 当前价卡版本 + * @param postcode 收件邮编 + * @param countryCode 目的国二字码 + * @param countryName 目的国名称 + * @param linked 已对上的邮编组 + * @return 价卡上的地区名,单地区时为 null + */ + private String resolveZone(ServiceChannel channel, PayProduct product, String postcode, String countryCode, String countryName, + List linked) + { + List zoneNames = zoneNames(product); + if (zoneNames.size() <= 1) + { + return null; + } + List linkedZoneIds = zoneGroupIds(linked, countryCode, countryName); + if (!linkedZoneIds.isEmpty()) + { + return decideZone(zoneNames, linkedZoneIds, postcode); + } + List tokens = PayZoneMatcher.searchTokens(product.getProductName(), product.getSheetName()); + if (tokens.isEmpty()) + { + tokens = PayZoneMatcher.searchTokens(channel.getChannelName(), channel.getChannelCode()); + } + if (tokens.isEmpty()) + { + throw new ServiceException("产品「" + product.getProductName() + "」有多个地区,订单邮编无法对应到产品"); + } + List groups = new ArrayList<>(); + for (PayPostcodeGroup group : payPostcodeMapper.selectGroupsByTokens(tokens)) + { + if (sameCountry(group, countryCode, countryName)) + { + groups.add(group); + } + } + if (groups.isEmpty()) + { + throw new ServiceException("产品「" + product.getProductName() + "」有多个地区,没有找到对应的邮编分区"); + } + List groupIds = new ArrayList<>(); + for (PayPostcodeGroup group : groups) + { + groupIds.add(group.getGroupId()); + } + Set usable = new LinkedHashSet<>(); + for (PayPostcodeLine key : payPostcodeMapper.selectRegionKeys(groupIds)) + { + String region = key.getZoneName() != null && !key.getZoneName().isBlank() ? key.getZoneName() : key.getRegionName(); + if (PayZoneMatcher.mapRegion(zoneNames, region) != null) + { + usable.add(key.getGroupId()); + } + } + if (usable.isEmpty()) + { + throw new ServiceException("产品「" + product.getProductName() + "」有多个地区,邮编分区对不上价卡上的地区"); + } + return decideZone(zoneNames, new ArrayList<>(usable), postcode); + } + + /** + * 在给定邮编组里,用收件邮编决定价卡地区。对不上时抛出业务异常。 + * + * @param zoneNames 价卡上的地区名 + * @param groupIds 参与匹配的邮编组 + * @param postcode 收件邮编 + * @return 命中的地区名 + */ + private String decideZone(List zoneNames, List groupIds, String postcode) + { + PayZoneMatcher.Decision decision = PayZoneMatcher.resolve(zoneNames, payPostcodeMapper.selectLinesByGroups(groupIds), postcode); + if (decision.getMessage() != null) + { + throw new ServiceException(decision.getMessage()); + } + if (decision.getZoneName() == null) + { + throw PaymentMesEnum.BMS_PAY_NO_ZONE.exception(); + } + return decision.getZoneName(); + } + + /** + * 取出用来选派送费的普通分区。偏远、附加费邮编和不可达不参与选区。 + * + * @param linked 已对上的邮编组 + * @param countryCode 目的国二字码 + * @param countryName 目的国名称 + * @return 可参与选区的邮编组 ID + */ + private static List zoneGroupIds(List linked, String countryCode, String countryName) + { + List ids = new ArrayList<>(); + if (linked == null) + { + return ids; + } + for (PayPostcodeGroup group : linked) + { + if (group == null || group.getGroupId() == null || PayRemoteBook.remoteGroup(group) || "FEE".equals(group.getConfigKind())) + { + continue; + } + if ("UNREACH".equalsIgnoreCase(group.getCoverage() == null ? "" : group.getCoverage().trim())) + { + continue; + } + if (!sameCountry(group, countryCode, countryName)) + { + continue; + } + ids.add(group.getGroupId()); + } + return ids; + } + + /** + * 收集价卡重量段和分区附加费上的地区名。 + * + * @param product 当前价卡版本 + * @return 去重后的地区名 + */ + private static List zoneNames(PayProduct product) + { + Set names = new LinkedHashSet<>(); + if (product.getWeightBands() != null) + { + for (PayWeightBand band : product.getWeightBands()) + { + if (band != null && band.getZoneName() != null && !band.getZoneName().isBlank()) + { + names.add(band.getZoneName().trim()); + } + } + } + if (product.getSurcharges() != null) + { + for (PaySurcharge fee : product.getSurcharges()) + { + if (fee != null && PaySurchargeRules.ZONE.equals(fee.getCalcRule()) && fee.getZoneName() != null && !fee.getZoneName().isBlank()) + { + names.add(fee.getZoneName().trim()); + } + } + } + return new ArrayList<>(names); + } + + /** + * 判断邮编组是否和订单目的国相同。两边都没写国家时视为相同。 + * + * @param group 邮编组 + * @param countryCode 订单目的国二字码 + * @param countryName 订单目的国名称 + * @return 国家能对上时为 true + */ + private static boolean sameCountry(PayPostcodeGroup group, String countryCode, String countryName) + { + if (blank(countryCode) && blank(countryName)) + { + return true; + } + if (blank(group.getCountryCode()) && blank(group.getCountryName())) + { + return true; + } + if (!blank(countryCode) && countryCode.equalsIgnoreCase(group.getCountryCode())) + { + return true; + } + return !blank(countryName) && countryName.equals(group.getCountryName()); + } + + /** + * 从订单扩展找出渠道。先按渠道 ID,再按渠道编码,最后按渠道名称。 + * + * @param ext 订单计费扩展 + * @return 服务渠道 + */ + private ServiceChannel resolveChannel(PrcOrderBillExt ext) + { + if (ext == null) + { + throw PaymentMesEnum.BMS_PAY_NO_CHANNEL.exception(); + } + ServiceChannel channel = blank(ext.getProductChannelId()) ? null : serviceChannelMapper.selectServiceChannelById(ext.getProductChannelId().trim()); + if (channel == null && !blank(ext.getProductFloorCode())) + { + channel = serviceChannelMapper.selectServiceChannelByCode(ext.getProductFloorCode().trim()); + } + if (channel == null && !blank(ext.getProductFloor())) + { + List named = serviceChannelMapper.selectServiceChannelByName(ext.getProductFloor().trim()); + if (named != null && named.size() > 1) + { + throw new ServiceException("渠道名称「" + ext.getProductFloor().trim() + "」对应了多条渠道,请先在订单上指定渠道"); + } + channel = named == null || named.isEmpty() ? null : named.get(0); + } + if (channel == null) + { + throw PaymentMesEnum.BMS_PAY_CH_SYNC.exception(); + } + return channel; + } + + /** + * 把日期格式化成 yyyy-MM-dd。空日期表示不限。 + * + * @param date 有效期起或止 + * @return 日期文本 + */ + private static String day(Date date) + { + if (date == null) + { + return "不限"; + } + if (date instanceof java.sql.Date sql) + { + return sql.toLocalDate().toString(); + } + return date.toInstant().atZone(SHANGHAI).toLocalDate().toString(); + } + + /** + * 按传入顺序取第一个大于 0 的重量。 + * + * @param values 计费重、重量、实重、收货重 + * @return 第一个正数,都没有时返回 null + */ + private static BigDecimal firstPositive(BigDecimal... values) + { + if (values == null) + { + return null; + } + for (BigDecimal value : values) + { + if (value != null && value.compareTo(BigDecimal.ZERO) > 0) + { + return value; + } + } + return null; + } + + /** + * 判断文本是否为空。 + * + * @param value 待判断文本 + * @return 为 null 或空白时返回 true + */ + private static boolean blank(String value) + { + return value == null || value.isBlank(); + } +} diff --git a/bms-back/bms-system/src/main/java/com/bms/price/service/IPayOrderCostService.java b/bms-back/bms-system/src/main/java/com/bms/price/service/IPayOrderCostService.java index 2ab86d1c..34b64815 100644 --- a/bms-back/bms-system/src/main/java/com/bms/price/service/IPayOrderCostService.java +++ b/bms-back/bms-system/src/main/java/com/bms/price/service/IPayOrderCostService.java @@ -23,6 +23,14 @@ public interface IPayOrderCostService */ PayOrderCostResult generateIsolated(Long billId); + /** + * 订单同步后落地尾程费用。已经进入应付账单的计算费用不再覆盖。 + * + * @param billId 计费订单 ID + * @return 本次落地的结果;费用已经出账时返回 null + */ + PayOrderCostResult landIfOpen(Long billId); + /** * 这票订单当前尾程价卡上的归属供应商名称。没有价卡时返回空字符串。 * @@ -30,4 +38,12 @@ public interface IPayOrderCostService * @return 价卡归属名称 */ String cardSupplierName(Long billId); + + /** + * 把这票订单记成应付计费失败。单独提交,不跟着外面回滚掉。 + * + * @param billId 计费订单 ID + * @param reason 失败原因,最长 100 字 + */ + void markCalcFail(Long billId, String reason); } diff --git a/bms-back/bms-system/src/main/java/com/bms/price/service/IPayOrderListService.java b/bms-back/bms-system/src/main/java/com/bms/price/service/IPayOrderListService.java new file mode 100644 index 00000000..4f44a9b0 --- /dev/null +++ b/bms-back/bms-system/src/main/java/com/bms/price/service/IPayOrderListService.java @@ -0,0 +1,75 @@ +package com.bms.price.service; + +import java.util.List; +import com.bms.price.domain.PayOrderCostResult; +import com.bms.price.domain.PayOrderFeeBoard; +import com.bms.price.domain.PayOrderFeeLine; +import com.bms.price.domain.PayOrderQuery; +import com.bms.price.domain.PayOrderRecalcCommand; +import com.bms.price.domain.PayOrderRecalcTask; +import com.bms.price.domain.PayOrderRow; +import com.bms.price.domain.PrcPayBillFeeLog; + +/** 应付列表。 */ +public interface IPayOrderListService +{ + List list(PayOrderQuery query); + + PayOrderFeeBoard fees(String billId); + + /** + * 在指定费用段手工增加一行费用。来源记 MANUAL,创建人是当前登录用户。 + * + * @param billId 计费订单 ID + * @param line 费用项、金额、币种、说明和所属阶段 + * @return 写入后的费用行 + */ + PayOrderFeeLine addManualFee(String billId, PayOrderFeeLine line); + + /** + * 逻辑删除一条应付费用。已经进入应付账单的费用不能删。 + * + * @param feeId 费用明细 ID + */ + void removeFee(String feeId); + + /** + * 提交应付费用重算。订单先放进 Redis,后台逐票计算,每票更新进度。 + * + * @param command 重算方式(ORDER 或 LADING)和单号原文 + * @return 任务号,用来查询进度 + */ + String submitRecalc(PayOrderRecalcCommand command); + + /** + * 读取 Redis 里的重算进度。 + * + * @param taskId 任务号 + * @return 进度和每一票的结果;任务不存在时返回 null + */ + PayOrderRecalcTask getRecalcTask(String taskId); + + /** + * 取消还没开始的订单。正在计算的这一票会算完。 + * + * @param taskId 任务号 + * @return 更新后的进度 + */ + PayOrderRecalcTask cancelRecalc(String taskId); + + /** + * 重算一票。已经出账的费用不覆盖。成功和失败都回写计费状态、失败原因、更新人和更新时间。 + * + * @param billId 计费订单 ID + * @return 本次生成的费用,供提交成功后写日志 + */ + PayOrderCostResult recalcOne(Long billId); + + /** + * 按页读取一票订单的费用操作日志。 + * + * @param billId 计费订单 ID + * @return 当前页日志,新的在前 + */ + List feeLogs(String billId); +} diff --git a/bms-back/bms-system/src/main/java/com/bms/price/service/PayBillFeeLogService.java b/bms-back/bms-system/src/main/java/com/bms/price/service/PayBillFeeLogService.java new file mode 100644 index 00000000..23406e01 --- /dev/null +++ b/bms-back/bms-system/src/main/java/com/bms/price/service/PayBillFeeLogService.java @@ -0,0 +1,366 @@ +package com.bms.price.service; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import com.bms.common.utils.PageUtils; +import com.bms.common.utils.SecurityUtils; +import com.bms.price.domain.PrcPayBillFee; +import com.bms.price.domain.PrcPayBillFeeLog; +import com.bms.price.mapper.PrcPayBillFeeLogMapper; + +/** + * 应付费用日志。各入口只调用这里,写入失败只打日志,不把异常交回业务。 + */ +@Service +public class PayBillFeeLogService +{ + private static final Logger log = LoggerFactory.getLogger(PayBillFeeLogService.class); + + /** 新增,字典 bms_pay_fee_log_type */ + public static final String ADD = "1"; + + /** 编辑 */ + public static final String EDIT = "2"; + + /** 删除 */ + public static final String DELETE = "3"; + + /** 重算费用 */ + public static final String RECALC = "4"; + + /** 废弃 */ + public static final String VOID = "5"; + + /** 费用日志批量插入条数 */ + public static final int BATCH_SIZE = 1000; + + @Autowired + private PrcPayBillFeeLogMapper payBillFeeLogMapper; + + /** + * 记一条费用日志。异常只打印,不向外抛。 + * + * @param fee 费用项、金额、币种和所属订单 + * @param operationType 字典值,见本类常量 + */ + public void record(PrcPayBillFee fee, String operationType) + { + if (fee == null) + { + return; + } + record(Collections.singletonList(fee), operationType); + } + + /** + * 按同一操作类型记一批费用日志。异常只打印,不向外抛。 + * + * @param fees 本次涉及的费用 + * @param operationType 字典值,见本类常量 + */ + public void record(List fees, String operationType) + { + try + { + List rows = snapshots(fees, operationType); + for (int from = 0; from < rows.size(); from += BATCH_SIZE) + { + payBillFeeLogMapper.insertBatch(rows.subList(from, Math.min(from + BATCH_SIZE, rows.size()))); + } + } + catch (Exception ex) + { + log.error("写入应付费用日志失败 operationType={}", operationType, ex); + } + } + + /** + * 把费用快照放进集合,不写库。调用方凑满 {@link #BATCH_SIZE} 再 {@link #flush}。 + * + * @param bucket 本次重算收集的日志 + * @param fees 已经提交成功的费用 + * @param operationType 字典值,见本类常量 + */ + public void collect(List bucket, List fees, String operationType) + { + if (bucket == null) + { + return; + } + try + { + bucket.addAll(snapshots(fees, operationType)); + } + catch (Exception ex) + { + log.error("收集应付费用日志失败 operationType={}", operationType, ex); + } + } + + /** + * 把集合里凑满的日志按 1000 条写入。不足 1000 的留给 {@link #drain}。写入失败只打印,不向外抛。 + * + * @param bucket 本次重算收集的日志 + */ + @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class) + public void flush(List bucket) + { + write(bucket, false); + } + + /** + * 把集合里剩下的日志写完,最后一批可以不足 1000 条。写入失败只打印,不向外抛。 + * + * @param bucket 本次重算收集的日志 + */ + @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class) + public void drain(List bucket) + { + write(bucket, true); + } + + /** + * 读取一票订单的费用日志。表还没建或查询失败时返回空列表,并打印错误。 + * + * @param billId 计费订单 ID + * @return 日志,新的在前 + */ + public List list(Long billId) + { + if (billId == null) + { + return Collections.emptyList(); + } + try + { + List rows = payBillFeeLogMapper.selectByBillId(billId); + if (rows == null) + { + return Collections.emptyList(); + } + for (PrcPayBillFeeLog row : rows) + { + present(row); + } + return rows; + } + catch (Exception ex) + { + log.error("读取应付费用日志失败 billId={}", billId, ex); + return Collections.emptyList(); + } + } + + /** + * 费用重算失败时给这票订单记一条日志,备注里写失败原因。没有费用明细。异常只打印,不向外抛。 + * + * @param billId 计费订单 ID + * @param reason 失败原因 + */ + public void recordRecalcFailure(Long billId, String reason) + { + if (billId == null) + { + return; + } + try + { + PrcPayBillFeeLog row = new PrcPayBillFeeLog(); + row.setBillId(billId); + row.setFeeName(""); + row.setOperationType(RECALC); + row.setRemark(cut(reason == null || reason.isBlank() ? "应付费用生成失败" : reason, 500)); + row.setCreateBy(operator()); + payBillFeeLogMapper.insertBatch(Collections.singletonList(row)); + } + catch (Exception ex) + { + log.error("写入应付费用重算失败日志失败 billId={}", billId, ex); + } + } + + /** + * 按页读取一票订单的费用日志,新的在前。页码和每页条数取当前请求。 + * + * @param billId 计费订单 ID + * @return 当前页日志。查询失败时返回空列表,并打印错误 + */ + public List page(Long billId) + { + if (billId == null) + { + return Collections.emptyList(); + } + try + { + PageUtils.startPage(); + List rows = payBillFeeLogMapper.selectByBillId(billId); + if (rows == null) + { + return Collections.emptyList(); + } + for (PrcPayBillFeeLog row : rows) + { + present(row); + } + return rows; + } + catch (Exception ex) + { + PageUtils.clearPage(); + log.error("读取应付费用日志失败 billId={}", billId, ex); + return Collections.emptyList(); + } + } + + private void present(PrcPayBillFeeLog row) + { + if (row == null || sideFilled(row)) + { + return; + } + boolean dropped = DELETE.equals(row.getOperationType()) || VOID.equals(row.getOperationType()); + if (dropped) + { + row.setBeforeFeeName(row.getFeeName()); + row.setBeforeAmount(row.getAmount()); + row.setBeforeCurrency(row.getCurrency()); + return; + } + if (row.getFeeName() == null || row.getFeeName().isBlank()) + { + return; + } + row.setAfterFeeName(row.getFeeName()); + row.setAfterAmount(row.getAmount()); + row.setAfterCurrency(row.getCurrency()); + } + + private static boolean sideFilled(PrcPayBillFeeLog row) + { + return row.getBeforeFeeName() != null || row.getBeforeAmount() != null || row.getBeforeCurrency() != null + || row.getAfterFeeName() != null || row.getAfterAmount() != null || row.getAfterCurrency() != null; + } + + private void write(List bucket, boolean drain) + { + if (bucket == null || bucket.isEmpty()) + { + return; + } + while (bucket.size() >= BATCH_SIZE || (drain && !bucket.isEmpty())) + { + int size = Math.min(BATCH_SIZE, bucket.size()); + List chunk = new ArrayList<>(bucket.subList(0, size)); + try + { + payBillFeeLogMapper.insertBatch(chunk); + bucket.subList(0, size).clear(); + } + catch (Exception ex) + { + log.error("写入应付费用日志失败 size={}", size, ex); + break; + } + } + } + + private List snapshots(List fees, String operationType) + { + List rows = new ArrayList<>(); + if (fees == null || fees.isEmpty() || operationType == null || operationType.isBlank()) + { + return rows; + } + String operator = operator(); + String type = cut(operationType.trim(), 32); + for (PrcPayBillFee fee : fees) + { + if (fee == null || fee.getBillId() == null) + { + continue; + } + PrcPayBillFeeLog row = new PrcPayBillFeeLog(); + row.setFeeId(cut(fee.getFeeId(), 64)); + row.setBillId(fee.getBillId()); + row.setFeeName(cut(nameOf(fee), 100)); + row.setAmount(fee.getAmount()); + String currency = fee.getCurrency() == null ? null : fee.getCurrency().trim(); + currency = currency == null || currency.isEmpty() ? null : cut(currency, 10); + row.setCurrency(currency); + boolean dropped = DELETE.equals(type) || VOID.equals(type) || Boolean.TRUE.equals(fee.getLogAfterBlank()); + if (DELETE.equals(type) || VOID.equals(type)) + { + row.setBeforeFeeName(row.getFeeName()); + row.setBeforeAmount(fee.getAmount()); + row.setBeforeCurrency(currency); + } + else if (fee.getLogBeforeName() != null || fee.getLogBeforeAmount() != null || fee.getLogBeforeCurrency() != null) + { + row.setBeforeFeeName(cut(fee.getLogBeforeName(), 100)); + row.setBeforeAmount(fee.getLogBeforeAmount()); + String beforeCurrency = fee.getLogBeforeCurrency() == null ? null : fee.getLogBeforeCurrency().trim(); + row.setBeforeCurrency(beforeCurrency == null || beforeCurrency.isEmpty() ? null : cut(beforeCurrency, 10)); + } + if (!dropped) + { + row.setAfterFeeName(row.getFeeName()); + row.setAfterAmount(fee.getAmount()); + row.setAfterCurrency(currency); + } + row.setOperationType(type); + row.setCreateBy(operator); + rows.add(row); + } + return rows; + } + + private static String nameOf(PrcPayBillFee fee) + { + String name = fee.getFeeName() == null ? "" : fee.getFeeName().trim(); + if (!name.isEmpty()) + { + return name; + } + if ("BASIC_FREIGHT".equals(fee.getFeeType())) + { + return "基础运费"; + } + String type = fee.getFeeType() == null ? "" : fee.getFeeType().trim(); + return type.isEmpty() ? "费用" : type; + } + + private static String operator() + { + try + { + String name = SecurityUtils.getUsername(); + if (name == null || name.isBlank()) + { + return "system"; + } + return cut(name.trim(), 64); + } + catch (Exception ex) + { + return "system"; + } + } + + private static String cut(String value, int max) + { + if (value == null) + { + return null; + } + String text = value.trim(); + return text.length() <= max ? text : text.substring(0, max); + } +} diff --git a/bms-back/bms-system/src/main/java/com/bms/price/service/impl/PayBillServiceImpl.java b/bms-back/bms-system/src/main/java/com/bms/price/service/impl/PayBillServiceImpl.java index e062ee85..3b671a87 100644 --- a/bms-back/bms-system/src/main/java/com/bms/price/service/impl/PayBillServiceImpl.java +++ b/bms-back/bms-system/src/main/java/com/bms/price/service/impl/PayBillServiceImpl.java @@ -42,12 +42,14 @@ import com.bms.price.domain.PayBillOrder; import com.bms.price.domain.PayBillPreview; import com.bms.price.domain.PayOrderCostResult; import com.bms.price.domain.PrcPayBillFee; +import com.bms.price.domain.PrcPayBillFeeLog; import com.bms.price.mapper.PayBillMapper; import com.bms.price.mapper.PayFinanceMapper; import com.bms.price.mapper.PrcPayBillFeeMapper; import com.bms.price.pay.PaySettleSupport; import com.bms.price.service.IPayBillService; import com.bms.price.service.IPayOrderCostService; +import com.bms.price.service.PayBillFeeLogService; import com.bms.price.service.IPrcPayBillFeeService; /** @@ -73,6 +75,9 @@ public class PayBillServiceImpl implements IPayBillService @Autowired private IPrcPayBillFeeService payBillFeeService; + @Autowired + private PayBillFeeLogService payBillFeeLogService; + @Autowired private PayFinanceMapper payFinanceMapper; @@ -155,127 +160,143 @@ public class PayBillServiceImpl implements IPayBillService Map versions = new HashMap<>(); List skipped = new ArrayList<>(); List billIds = new ArrayList<>(); - for (PayBillOrder order : orders) + List feeLogs = new ArrayList<>(); + try { - billIds.add(order.getBillId()); - if (payBillMapper.countCalcFees(order.getBillId()) > 0) + for (PayBillOrder order : orders) { - continue; - } - try - { - PayOrderCostResult cost = payOrderCostService.generateIsolated(order.getBillId()); - if (cost != null) + billIds.add(order.getBillId()); + if (payBillMapper.countCalcFees(order.getBillId()) > 0) { - versions.put(order.getBillId(), cost.getVersionNo()); + continue; + } + try + { + PayOrderCostResult cost = payOrderCostService.generateIsolated(order.getBillId()); + if (cost != null) + { + versions.put(order.getBillId(), cost.getVersionNo()); + payBillFeeLogService.collect(feeLogs, cost.getLoggedFees(), cost.getFeeLogType()); + if (feeLogs.size() >= PayBillFeeLogService.BATCH_SIZE) + { + payBillFeeLogService.flush(feeLogs); + } + } + } + catch (ServiceException ex) + { + skipped.add(order.getOrderNo() + ":" + ex.getMessage()); } } - catch (ServiceException ex) + List fees = billIds.isEmpty() ? new ArrayList<>() : payBillMapper.selectFreeFees(billIds); + List skippedParty = new ArrayList<>(); + fees = keepSupplierFees(fees, orders, supplier, skippedParty); + if (!fees.isEmpty() && fees.get(0).getCurrency() != null && !fees.get(0).getCurrency().isBlank()) { - skipped.add(order.getOrderNo() + ":" + ex.getMessage()); + currency = fees.get(0).getCurrency(); + } + List lines = new ArrayList<>(); + for (PrcPayBillFee fee : fees) + { + PayBillOrder order = findOrder(orders, fee.getBillId()); + PayBillLine line = new PayBillLine(); + line.setOrderBillId(fee.getBillId()); + line.setOrderNo(order == null ? "" : order.getOrderNo()); + line.setLadingNo(order == null ? "" : order.getLadingNo()); + line.setFeeId(fee.getFeeId()); + line.setFeeName(fee.getFeeName() == null || fee.getFeeName().isBlank() ? fee.getFeeType() : fee.getFeeName()); + line.setFeeSource(fee.getFeeSource()); + line.setFeeLevel(fee.getFeeLevel()); + line.setAmount(fee.getAmount()); + line.setDiffStatus("NONE"); + line.setCurrency(fee.getCurrency()); + line.setPriceDate(order == null || order.getBizDate() == null ? null : order.getBizDate()); + line.setVersionNo(versions.get(fee.getBillId())); + line.setLineSource("LADING".equals(fee.getFeeSource()) ? "LADING" : "ORDER"); + lines.add(line); + } + if (lines.isEmpty()) + { + List notes = new ArrayList<>(); + notes.addAll(skipped); + notes.addAll(skippedParty); + throw new ServiceException(notes.isEmpty() ? PaymentMesEnum.BMS_PAY_BILL_FEE.getCnMes() : String.join(";", notes)); + } + BigDecimal total = BigDecimal.ZERO; + for (PayBillLine line : lines) + { + String lineCurrency = line.getCurrency() == null ? "" : line.getCurrency(); + if (!currency.equals(lineCurrency)) + { + throw PaymentMesEnum.BMS_PAY_CURRENCY.exception(); + } + total = total.add(line.getAmount() == null ? BigDecimal.ZERO : line.getAmount()); + } + String operator = SecurityUtils.getUsername(); + PayBill bill = new PayBill(); + bill.setBillNo(nextNo()); + bill.setSupplierId(supplier.getSupplierId()); + bill.setSupplierName(supplier.getSupplierName()); + bill.setCurrency(currency); + bill.setSourceType(mode(command)); + bill.setPeriodStart(parseDay(command.getBeginDate())); + bill.setPeriodEnd(parseDay(command.getEndDate())); + Set orderIds = new HashSet<>(); + for (PayBillLine line : lines) + { + if (line.getOrderBillId() != null) + { + orderIds.add(line.getOrderBillId()); + } + } + BigDecimal scaled = total.setScale(2, RoundingMode.HALF_UP); + bill.setOrderCount(orderIds.size()); + bill.setTotalAmount(scaled); + bill.setSupplierAmount(scaled); + bill.setDiffAmount(BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP)); + bill.setPaidAmount(BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP)); + bill.setBillKind("BLUE"); + int termDays = supplier.getZq() == null || supplier.getZq() < 0 ? 30 : supplier.getZq().intValue(); + bill.setTermDays(termDays); + Date due = parseDay(command.getDueDate()); + bill.setDueDate(due == null ? java.sql.Date.valueOf(LocalDate.now().plusDays(termDays)) : due); + bill.setTaxRate(BigDecimal.ZERO.setScale(4, RoundingMode.HALF_UP)); + bill.setExchangeRate(BigDecimal.ONE); + bill.setAmountNet(scaled); + bill.setTaxAmount(BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP)); + bill.setBaseAmount(scaled); + bill.setRateDate(java.sql.Date.valueOf(LocalDate.now())); + bill.setCreateBy(operator); + bill.setRemark(command.getRemark()); + payBillMapper.insertPayBill(bill); + for (PayBillLine line : lines) + { + line.setBillId(bill.getBillId()); + payBillMapper.insertLine(line); + if (line.getFeeId() != null && !line.getFeeId().isBlank() && payBillMapper.bindFeeLine(line.getFeeId(), line.getLineId()) != 1) + { + throw PaymentMesEnum.BMS_PAY_FEE_TAKEN.exception(); + } + } + String desc = "生成应付账单,订单 " + orderIds.size() + " 票,费用 " + lines.size() + " 行"; + if (!skipped.isEmpty()) + { + desc = desc + ";未补尾程:" + String.join(";", skipped); + } + if (!skippedParty.isEmpty()) + { + desc = desc + ";未并入:" + String.join(";", skippedParty); + } + writeLog(bill.getBillId(), "CREATE", null, "DRAFT", desc.length() > 500 ? desc.substring(0, 500) : desc, operator); + return selectPayBillDetail(bill.getBillId()); + } + finally + { + if (!feeLogs.isEmpty()) + { + payBillFeeLogService.drain(feeLogs); } } - List fees = billIds.isEmpty() ? new ArrayList<>() : payBillMapper.selectFreeFees(billIds); - List skippedParty = new ArrayList<>(); - fees = keepSupplierFees(fees, orders, supplier, skippedParty); - if (!fees.isEmpty() && fees.get(0).getCurrency() != null && !fees.get(0).getCurrency().isBlank()) - { - currency = fees.get(0).getCurrency(); - } - List lines = new ArrayList<>(); - for (PrcPayBillFee fee : fees) - { - PayBillOrder order = findOrder(orders, fee.getBillId()); - PayBillLine line = new PayBillLine(); - line.setOrderBillId(fee.getBillId()); - line.setOrderNo(order == null ? "" : order.getOrderNo()); - line.setLadingNo(order == null ? "" : order.getLadingNo()); - line.setFeeId(fee.getFeeId()); - line.setFeeName(fee.getFeeName() == null || fee.getFeeName().isBlank() ? fee.getFeeType() : fee.getFeeName()); - line.setFeeSource(fee.getFeeSource()); - line.setFeeLevel(fee.getFeeLevel()); - line.setAmount(fee.getAmount()); - line.setDiffStatus("NONE"); - line.setCurrency(fee.getCurrency()); - line.setPriceDate(order == null || order.getBizDate() == null ? null : order.getBizDate()); - line.setVersionNo(versions.get(fee.getBillId())); - line.setLineSource("LADING".equals(fee.getFeeSource()) ? "LADING" : "ORDER"); - lines.add(line); - } - if (lines.isEmpty()) - { - List notes = new ArrayList<>(); - notes.addAll(skipped); - notes.addAll(skippedParty); - throw new ServiceException(notes.isEmpty() ? PaymentMesEnum.BMS_PAY_BILL_FEE.getCnMes() : String.join(";", notes)); - } - BigDecimal total = BigDecimal.ZERO; - for (PayBillLine line : lines) - { - String lineCurrency = line.getCurrency() == null ? "" : line.getCurrency(); - if (!currency.equals(lineCurrency)) - { - throw PaymentMesEnum.BMS_PAY_CURRENCY.exception(); - } - total = total.add(line.getAmount() == null ? BigDecimal.ZERO : line.getAmount()); - } - String operator = SecurityUtils.getUsername(); - PayBill bill = new PayBill(); - bill.setBillNo(nextNo()); - bill.setSupplierId(supplier.getSupplierId()); - bill.setSupplierName(supplier.getSupplierName()); - bill.setCurrency(currency); - bill.setSourceType(mode(command)); - bill.setPeriodStart(parseDay(command.getBeginDate())); - bill.setPeriodEnd(parseDay(command.getEndDate())); - Set orderIds = new HashSet<>(); - for (PayBillLine line : lines) - { - if (line.getOrderBillId() != null) - { - orderIds.add(line.getOrderBillId()); - } - } - BigDecimal scaled = total.setScale(2, RoundingMode.HALF_UP); - bill.setOrderCount(orderIds.size()); - bill.setTotalAmount(scaled); - bill.setSupplierAmount(scaled); - bill.setDiffAmount(BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP)); - bill.setPaidAmount(BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP)); - bill.setBillKind("BLUE"); - int termDays = supplier.getZq() == null || supplier.getZq() < 0 ? 30 : supplier.getZq().intValue(); - bill.setTermDays(termDays); - Date due = parseDay(command.getDueDate()); - bill.setDueDate(due == null ? java.sql.Date.valueOf(LocalDate.now().plusDays(termDays)) : due); - bill.setTaxRate(BigDecimal.ZERO.setScale(4, RoundingMode.HALF_UP)); - bill.setExchangeRate(BigDecimal.ONE); - bill.setAmountNet(scaled); - bill.setTaxAmount(BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP)); - bill.setBaseAmount(scaled); - bill.setRateDate(java.sql.Date.valueOf(LocalDate.now())); - bill.setCreateBy(operator); - bill.setRemark(command.getRemark()); - payBillMapper.insertPayBill(bill); - for (PayBillLine line : lines) - { - line.setBillId(bill.getBillId()); - payBillMapper.insertLine(line); - if (line.getFeeId() != null && !line.getFeeId().isBlank() && payBillMapper.bindFeeLine(line.getFeeId(), line.getLineId()) != 1) - { - throw PaymentMesEnum.BMS_PAY_FEE_TAKEN.exception(); - } - } - String desc = "生成应付账单,订单 " + orderIds.size() + " 票,费用 " + lines.size() + " 行"; - if (!skipped.isEmpty()) - { - desc = desc + ";未补尾程:" + String.join(";", skipped); - } - if (!skippedParty.isEmpty()) - { - desc = desc + ";未并入:" + String.join(";", skippedParty); - } - writeLog(bill.getBillId(), "CREATE", null, "DRAFT", desc.length() > 500 ? desc.substring(0, 500) : desc, operator); - return selectPayBillDetail(bill.getBillId()); } /** @@ -577,22 +598,19 @@ public class PayBillServiceImpl implements IPayBillService adjust.setFeeId(UUID.randomUUID().toString()); adjust.setBillId(line.getOrderBillId()); adjust.setPayBillId(source == null ? null : source.getPayBillId()); - adjust.setFeeType("对账调整"); + adjust.setFeeType("ADJUST"); adjust.setFeeName("对账调整"); adjust.setScId(open.getDiffId()); adjust.setFeeLevel(line.getFeeLevel()); adjust.setAmount(delta); adjust.setCurrency(line.getCurrency()); adjust.setFeeSource("MANUAL"); - adjust.setSourceId(source == null ? null : source.getFeeId()); + adjust.setSourceId(source == null ? null : source.getSourceId()); adjust.setRemark(open.getReason()); adjust.setSettleSupplierId(bill.getSupplierId()); adjust.setSettleSupplierName(bill.getSupplierName()); payBillFeeMapper.insertPrcPayBillFee(adjust); - if (adjust.getSourceId() == null || adjust.getSourceId().isBlank()) - { - payBillFeeMapper.fillSourceIdByFeeIds(List.of(adjust.getFeeId())); - } + payBillFeeLogService.record(adjust, PayBillFeeLogService.ADD); payFinanceMapper.stampFee(adjust.getFeeId(), bill.getSupplierId(), bill.getSupplierName()); if (line.getOrderBillId() != null) { @@ -604,7 +622,7 @@ public class PayBillServiceImpl implements IPayBillService extra.setOrderBillId(line.getOrderBillId()); extra.setOrderNo(line.getOrderNo()); extra.setLadingNo(line.getLadingNo()); - extra.setFeeName(adjust.getFeeName()); + extra.setFeeName("对账调整"); extra.setFeeSource("MANUAL"); extra.setFeeLevel(line.getFeeLevel()); extra.setAmount(delta); diff --git a/bms-back/bms-system/src/main/java/com/bms/price/service/impl/PayOrderCostServiceImpl.java b/bms-back/bms-system/src/main/java/com/bms/price/service/impl/PayOrderCostServiceImpl.java index 1d59652a..0d4dc424 100644 --- a/bms-back/bms-system/src/main/java/com/bms/price/service/impl/PayOrderCostServiceImpl.java +++ b/bms-back/bms-system/src/main/java/com/bms/price/service/impl/PayOrderCostServiceImpl.java @@ -35,6 +35,7 @@ import com.bms.price.pay.PayRemoteBook; import com.bms.price.pay.PaySurchargeRules; import com.bms.price.pay.PayZoneMatcher; import com.bms.price.service.IPayOrderCostService; +import com.bms.price.service.PayBillFeeLogService; import com.bms.price.service.IPayProductService; import com.bms.price.service.IPaySurchargeRuleService; import com.bms.price.service.IPrcPayBillFeeService; @@ -66,6 +67,9 @@ public class PayOrderCostServiceImpl implements IPayOrderCostService @Autowired private IPrcPayBillFeeService payBillFeeService; + @Autowired + private PayBillFeeLogService payBillFeeLogService; + @Autowired private PaySettleSupport paySettleSupport; @@ -89,6 +93,32 @@ public class PayOrderCostServiceImpl implements IPayOrderCostService return generate(billId); } + /** + * 订单同步后落地尾程费用。已经进入应付账单的计算费用不再覆盖。 + * + * @param billId 计费订单 ID + * @return 本次落地的结果;费用已经出账时返回 null + */ + @Override + @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class) + public PayOrderCostResult landIfOpen(Long billId) + { + if (billId == null) + { + return null; + } + if (payBillFeeMapper.countSettledCalc(billId) > 0) + { + return null; + } + PayOrderCostResult result = generate(billId); + if (result != null) + { + payBillFeeLogService.record(result.getLoggedFees(), result.getFeeLogType()); + } + return result; + } + @Override @Transactional(rollbackFor = Exception.class) public PayOrderCostResult generate(Long billId) @@ -132,15 +162,52 @@ public class PayOrderCostServiceImpl implements IPayOrderCostService } String operator = SecurityUtils.getUsername(); PrcPayBill payBill = saveBill(bill, result, operator); - saveFees(bill.getBillId(), payBill.getPayBillId(), result.getFees()); + saveFees(bill.getBillId(), payBill.getPayBillId(), result); String channelName = channel.getChannelName() == null ? channel.getChannelCode() : channel.getChannelName(); String end = product.getTermEnd() == null ? "不限" : day(product.getTermEnd()); result.setMessage("渠道「" + channelName + "」" + product.getProductName() + " 第 " + product.getVersionNo() + " 版(" + day(product.getTermStart()) + " 至 " + end + ")," + result.getMessage()); paySettleSupport.stampCalc(bill.getBillId(), product.getSupplierName()); + payBillMapper.markCalcStatus(bill.getBillId(), 1, null, operator); return result; } + /** + * 单独记下计费失败。重算事务回滚后,这条状态仍然保留。 + * + * @param billId 计费订单 ID + * @param reason 失败原因,超过 100 字会截断 + */ + @Override + @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class) + public void markCalcFail(Long billId, String reason) + { + if (billId == null) + { + return; + } + String message = reason == null ? "" : reason.trim(); + if (message.length() > 100) + { + message = message.substring(0, 100); + } + String operator = "system"; + try + { + String name = SecurityUtils.getUsername(); + if (name != null && !name.isBlank()) + { + operator = name; + } + } + catch (Exception ignored) + { + operator = "system"; + } + payBillMapper.insertMissingPayBills(List.of(billId), operator); + payBillMapper.markCalcStatus(billId, 2, message, operator); + } + @Override public String cardSupplierName(Long billId) { @@ -579,17 +646,32 @@ public class PayOrderCostServiceImpl implements IPayOrderCostService } /** - * 用本次算出的尾程费用替换订单上的计算费用。来源不是计算的费用行会保留。 + * 用本次算出的尾程费用替换订单上的计算费用。原来的计算费用改为逻辑删除,提单分摊和人工费用保留。 + * 新费用只挂到结果上,等事务提交后再写日志。 * * @param billId 计费订单ID * @param payBillId 订单应付主表ID - * @param fees 本次算出的费用 + * @param result 本次计费结果,算出的费用在其中 */ - private void saveFees(Long billId, String payBillId, List fees) + private void saveFees(Long billId, String payBillId, PayOrderCostResult result) { - payBillFeeMapper.deleteByBillId(billId); + List current = payBillFeeMapper.selectByBillId(billId); + java.util.Map oldCalc = new java.util.LinkedHashMap<>(); + if (current != null) + { + for (PrcPayBillFee fee : current) + { + if (calcFee(fee)) + { + oldCalc.put(feeKey(fee.getFeeType(), fee.getScId()), fee); + } + } + } + boolean recalc = !oldCalc.isEmpty(); + payBillFeeMapper.markCalcDeleted(billId, operator()); List rows = new java.util.ArrayList<>(); long fallback = 1L; + List fees = result.getFees() == null ? java.util.List.of() : result.getFees(); for (PayCostLine fee : fees) { PrcPayBillFee row = new PrcPayBillFee(); @@ -597,7 +679,7 @@ public class PayOrderCostServiceImpl implements IPayOrderCostService row.setBillId(billId); row.setPayBillId(payBillId); row.setFeeType(fee.getFeeType()); - row.setFeeName(fee.getFeeName()); + row.setFeeName(cutFeeName(fee.getFeeName())); long scId = fee.getScId() == null ? 0L : fee.getScId(); if ("SURCHARGE".equals(fee.getFeeType()) && scId == 0L) { @@ -608,6 +690,13 @@ public class PayOrderCostServiceImpl implements IPayOrderCostService row.setCurrency(fee.getCurrency()); row.setRoundMode("HALF_UP"); row.setRemark(fee.getRemark()); + PrcPayBillFee old = oldCalc.remove(feeKey(row.getFeeType(), row.getScId())); + if (old != null) + { + row.setLogBeforeName(feeLabel(old)); + row.setLogBeforeAmount(old.getAmount()); + row.setLogBeforeCurrency(old.getCurrency()); + } rows.add(row); } if (!rows.isEmpty()) @@ -618,6 +707,84 @@ public class PayOrderCostServiceImpl implements IPayOrderCostService { payBillFeeService.refreshTotals(java.util.List.of(billId)); } + List logged = new java.util.ArrayList<>(rows); + for (PrcPayBillFee old : oldCalc.values()) + { + PrcPayBillFee gone = new PrcPayBillFee(); + gone.setFeeId(old.getFeeId()); + gone.setBillId(billId); + gone.setFeeType(old.getFeeType()); + gone.setFeeName(feeLabel(old)); + gone.setAmount(old.getAmount()); + gone.setCurrency(old.getCurrency()); + gone.setLogBeforeName(feeLabel(old)); + gone.setLogBeforeAmount(old.getAmount()); + gone.setLogBeforeCurrency(old.getCurrency()); + gone.setLogAfterBlank(true); + logged.add(gone); + } + result.setLoggedFees(logged); + result.setFeeLogType(recalc ? PayBillFeeLogService.RECALC : PayBillFeeLogService.ADD); + } + + /** 计算费用,空来源按计算费用处理。 */ + private static boolean calcFee(PrcPayBillFee fee) + { + if (fee == null) + { + return false; + } + String source = fee.getFeeSource(); + return source == null || source.isBlank() || "CALC".equals(source); + } + + private static String feeKey(String feeType, Long scId) + { + return (feeType == null ? "" : feeType) + "#" + (scId == null ? 0L : scId); + } + + private static String feeLabel(PrcPayBillFee fee) + { + String name = fee.getFeeName() == null ? "" : fee.getFeeName().trim(); + if (!name.isEmpty()) + { + return name; + } + if ("BASIC_FREIGHT".equals(fee.getFeeType())) + { + return "基础运费"; + } + String type = fee.getFeeType() == null ? "" : fee.getFeeType().trim(); + return type.isEmpty() ? "费用" : type; + } + + /** 费用项名称最长 100 字,和费用表、费用日志的长度一致。 */ + private static String cutFeeName(String name) + { + if (name == null) + { + return null; + } + String text = name.trim(); + if (text.isEmpty()) + { + return null; + } + return text.length() <= 100 ? text : text.substring(0, 100); + } + + /** 当前登录人。没有登录信息时记 system。 */ + private static String operator() + { + try + { + String name = SecurityUtils.getUsername(); + return name == null || name.isBlank() ? "system" : name; + } + catch (Exception ignored) + { + return "system"; + } } /** diff --git a/bms-back/bms-system/src/main/java/com/bms/price/service/impl/PayOrderListServiceImpl.java b/bms-back/bms-system/src/main/java/com/bms/price/service/impl/PayOrderListServiceImpl.java new file mode 100644 index 00000000..da17ae3d --- /dev/null +++ b/bms-back/bms-system/src/main/java/com/bms/price/service/impl/PayOrderListServiceImpl.java @@ -0,0 +1,502 @@ +package com.bms.price.service.impl; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Lazy; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import com.bms.common.enums.PaymentMesEnum; +import com.bms.common.exception.ServiceException; +import com.bms.common.utils.SecurityUtils; +import com.bms.common.utils.uuid.IdUtils; +import com.bms.price.domain.PayOrderCostResult; +import com.bms.price.domain.PayOrderFeeBoard; +import com.bms.price.domain.PrcPayBill; +import com.bms.price.domain.PayOrderFeeLine; +import com.bms.price.domain.PayOrderFeeSection; +import com.bms.price.domain.PayOrderQuery; +import com.bms.price.domain.PayOrderRecalcCommand; +import com.bms.price.domain.PayOrderRecalcLine; +import com.bms.price.domain.PayOrderRecalcTask; +import com.bms.price.domain.PayOrderRow; +import com.bms.price.domain.PrcPayBillFee; +import com.bms.price.domain.PrcPayBillFeeLog; +import com.bms.price.mapper.PayOrderListMapper; +import com.bms.price.mapper.PrcPayBillFeeMapper; +import com.bms.price.mapper.PrcPayBillMapper; +import com.bms.price.service.IPayOrderCostService; +import com.bms.price.service.PayBillFeeLogService; +import com.bms.price.service.IPayOrderListService; +import com.bms.price.service.IPrcPayBillFeeService; +import com.bms.price.task.PayOrderRecalcAsyncRunner; + +@Service +public class PayOrderListServiceImpl implements IPayOrderListService +{ + private static final int MAX_ORDER_NOS = 500; + + private static final int MAX_LADING_NOS = 10; + + private static final Map TITLES = new LinkedHashMap<>(); + + static + { + TITLES.put("1", "A段(头程仓储)"); + TITLES.put("2", "B段(提单运输)"); + TITLES.put("3", "C段(清关)"); + TITLES.put("4", "D段(尾程)"); + } + + @Autowired + private PayOrderListMapper payOrderListMapper; + + @Autowired + private PrcPayBillFeeMapper payBillFeeMapper; + + @Autowired + private IPayOrderCostService payOrderCostService; + + @Autowired + private PrcPayBillMapper payBillMapper; + + @Autowired + private IPrcPayBillFeeService payBillFeeService; + + @Autowired + private PayBillFeeLogService payBillFeeLogService; + + @Autowired + @Lazy + private PayOrderRecalcAsyncRunner payOrderRecalcAsyncRunner; + + @Override + public List list(PayOrderQuery query) + { + PayOrderQuery safe = query == null ? new PayOrderQuery() : query; + List orderNos = orderNos(safe.getOrderNo()); + if (orderNos.size() > MAX_ORDER_NOS) + { + throw new ServiceException("一次最多查询" + MAX_ORDER_NOS + "个订单号"); + } + if (orderNos.size() > 1) + { + safe.setOrderNos(orderNos); + safe.setOrderNo(null); + } + else + { + safe.setOrderNos(null); + safe.setOrderNo(orderNos.isEmpty() ? null : orderNos.get(0)); + } + return payOrderListMapper.selectList(safe); + } + + /** + * 查出订单后放进 Redis,马上返回任务号。逐票计算在后台进行。 + * + * @param command 重算方式和单号原文 + * @return 任务号 + */ + @Override + public String submitRecalc(PayOrderRecalcCommand command) + { + if (command == null || command.getSourceType() == null || command.getSourceType().isBlank()) + { + throw new ServiceException("请选择按订单号或按提单号重算"); + } + String source = command.getSourceType().trim(); + List nos = orderNos(command.getText()); + if (nos.isEmpty()) + { + throw new ServiceException("请填写单号"); + } + boolean byOrder = "ORDER".equalsIgnoreCase(source); + boolean byLading = "LADING".equalsIgnoreCase(source); + if (!byOrder && !byLading) + { + throw new ServiceException("请选择按订单号或按提单号重算"); + } + if (byLading && nos.size() > MAX_LADING_NOS) + { + throw new ServiceException("一次最多重算" + MAX_LADING_NOS + "个提单号"); + } + if (byOrder && nos.size() > MAX_ORDER_NOS) + { + throw new ServiceException("一次最多重算" + MAX_ORDER_NOS + "个订单号"); + } + List found = byOrder ? payOrderListMapper.selectByOrderNos(nos) : payOrderListMapper.selectByLadingNos(nos); + if (found == null) + { + found = new ArrayList<>(); + } + if (byOrder && found.size() > MAX_ORDER_NOS) + { + throw new ServiceException("一次最多重算" + MAX_ORDER_NOS + "票订单"); + } + PayOrderRecalcTask task = new PayOrderRecalcTask(); + task.setTaskId(IdUtils.fastSimpleUUID()); + task.setStatus(PayOrderRecalcTask.PENDING); + task.setMessage("排队中"); + LinkedHashSet hit = new LinkedHashSet<>(); + for (PayOrderRow order : found) + { + if (order == null || order.getBillId() == null || order.getBillId().isBlank()) + { + continue; + } + hit.add(byOrder ? order.getOrderNo() : order.getLadingNo()); + PayOrderRecalcLine line = new PayOrderRecalcLine(); + line.setBillId(order.getBillId().trim()); + line.setOrderNo(order.getOrderNo()); + line.setLadingNo(order.getLadingNo()); + task.getLines().add(line); + } + for (String no : nos) + { + if (hit.contains(no)) + { + continue; + } + PayOrderRecalcLine line = new PayOrderRecalcLine(); + if (byOrder) + { + line.setOrderNo(no); + line.setMessage("没有找到这个订单"); + } + else + { + line.setLadingNo(no); + line.setMessage("这个提单下没有订单"); + } + line.setFinished(true); + line.setSuccess(false); + task.getLines().add(line); + } + int finished = 0; + for (PayOrderRecalcLine line : task.getLines()) + { + if (line.isFinished()) + { + finished++; + task.setFailCount(task.getFailCount() + 1); + } + } + task.setTotal(task.getLines().size()); + task.setPercent(task.getTotal() == 0 ? 100 : finished * 100 / task.getTotal()); + payOrderRecalcAsyncRunner.save(task); + payOrderRecalcAsyncRunner.run(task.getTaskId(), SecurityContextHolder.getContext().getAuthentication()); + return task.getTaskId(); + } + + @Override + public PayOrderRecalcTask getRecalcTask(String taskId) + { + return payOrderRecalcAsyncRunner.get(taskId); + } + + @Override + public PayOrderRecalcTask cancelRecalc(String taskId) + { + return payOrderRecalcAsyncRunner.cancel(taskId); + } + + @Override + public PayOrderCostResult recalcOne(Long billId) + { + if (billId == null) + { + throw new ServiceException("请选择订单"); + } + try + { + if (payBillFeeMapper.countSettledCalc(billId) > 0) + { + throw new ServiceException("费用已进入应付账单,未重算"); + } + return payOrderCostService.generateIsolated(billId); + } + catch (Exception ex) + { + String message = ex.getMessage() == null || ex.getMessage().isBlank() ? "应付费用生成失败" : ex.getMessage(); + try + { + payOrderCostService.markCalcFail(billId, message); + } + catch (Exception markEx) + { + message = message + ";计费状态未写入"; + } + payBillFeeLogService.recordRecalcFailure(billId, message); + throw new ServiceException(message); + } + } + + @Override + public List feeLogs(String billId) + { + if (billId == null || billId.isBlank()) + { + throw PaymentMesEnum.BMS_PAY_PICK_ORDER.exception(); + } + return payBillFeeLogService.page(Long.valueOf(billId.trim())); + } + + @Override + public PayOrderFeeBoard fees(String billId) + { + if (billId == null || billId.isBlank()) + { + throw PaymentMesEnum.BMS_PAY_PICK_ORDER.exception(); + } + PayOrderRow order = payOrderListMapper.selectRow(billId.trim()); + if (order == null) + { + throw PaymentMesEnum.BMS_PAY_ORDER_MISS.exception(); + } + Map sections = new LinkedHashMap<>(); + for (Map.Entry title : TITLES.entrySet()) + { + PayOrderFeeSection section = new PayOrderFeeSection(); + section.setLevel(title.getKey()); + section.setTitle(title.getValue()); + sections.put(title.getKey(), section); + } + List owned = payBillFeeMapper.selectByBillId(Long.valueOf(order.getBillId().trim())); + if (owned != null) + { + for (PrcPayBillFee fee : owned) + { + if (fee == null) + { + continue; + } + sections.get(levelOf(fee)).getFees().add(toLine(fee)); + } + } + PayOrderFeeBoard board = new PayOrderFeeBoard(); + board.setBillId(order.getBillId()); + board.setOrderNo(order.getOrderNo()); + board.setLadingNo(order.getLadingNo()); + board.setSections(List.copyOf(sections.values())); + return board; + } + + /** + * 在指定费用段增加一行手工费用,并按未删除明细重算应付总额。 + * + * @param billId 计费订单 ID + * @param line 费用项、金额、币种、说明和所属阶段 + * @return 刚写入的费用行 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public PayOrderFeeLine addManualFee(String billId, PayOrderFeeLine line) + { + PayOrderRow order = requireOrder(billId); + if (line == null) + { + throw new ServiceException("请填写费用"); + } + String level = line.getLevel() == null ? "" : line.getLevel().trim(); + if (!TITLES.containsKey(level)) + { + throw new ServiceException("请选择费用阶段"); + } + String feeName = firstText(line.getFeeName(), line.getFeeType()); + if (feeName.isEmpty()) + { + throw new ServiceException("请填写费用项"); + } + if (feeName.length() > 100) + { + feeName = feeName.substring(0, 100); + } + String feeType = firstText(line.getFeeType(), "MANUAL"); + if (feeType.length() > 30) + { + feeType = "MANUAL"; + } + if (line.getAmount() == null) + { + throw new ServiceException("请填写金额"); + } + BigDecimal amount = line.getAmount().setScale(2, RoundingMode.HALF_UP); + if (amount.abs().compareTo(new BigDecimal("9999999999.99")) > 0) + { + throw new ServiceException("金额超出范围"); + } + String currency = firstText(line.getCurrency(), "CNY").toUpperCase(); + if (currency.length() > 10) + { + throw new ServiceException("币种过长"); + } + String remark = line.getRemark() == null ? null : line.getRemark().trim(); + if (remark != null && remark.length() > 200) + { + throw new ServiceException("说明不能超过200字"); + } + Long orderBillId = Long.valueOf(order.getBillId().trim()); + String operator = operator(); + payBillMapper.insertMissingPayBills(List.of(orderBillId), operator); + PrcPayBill payBill = payBillMapper.selectByBillId(orderBillId); + PrcPayBillFee fee = new PrcPayBillFee(); + fee.setFeeId(UUID.randomUUID().toString()); + fee.setBillId(orderBillId); + fee.setPayBillId(payBill == null ? null : payBill.getPayBillId()); + fee.setFeeType(feeType); + fee.setFeeName(feeName); + fee.setScId(manualScId()); + fee.setFeeLevel(level); + fee.setAmount(amount); + fee.setCurrency(currency); + fee.setRemark(remark == null || remark.isEmpty() ? null : remark); + fee.setFeeSource("MANUAL"); + fee.setCreateBy(operator); + fee.setUpdateBy(operator); + payBillFeeMapper.insertManual(fee); + payBillFeeService.refreshTotals(List.of(orderBillId)); + payBillFeeLogService.record(fee, PayBillFeeLogService.ADD); + PrcPayBillFee saved = payBillFeeMapper.selectByFeeId(fee.getFeeId()); + return toLine(saved == null ? fee : saved); + } + + /** + * 逻辑删除一条费用,并按剩余未删除明细重算应付总额。 + * + * @param feeId 费用明细 ID + */ + @Override + @Transactional(rollbackFor = Exception.class) + public void removeFee(String feeId) + { + if (feeId == null || feeId.isBlank()) + { + throw new ServiceException("请选择要删除的费用"); + } + PrcPayBillFee fee = payBillFeeMapper.selectByFeeId(feeId.trim()); + if (fee == null || "1".equals(fee.getIsDeleted())) + { + throw new ServiceException("费用不存在"); + } + if (fee.getStatementLineId() != null) + { + throw new ServiceException("费用已进入应付账单,不能删除"); + } + int rows = payBillFeeMapper.markFeeDeleted(feeId.trim(), operator()); + if (rows == 0) + { + throw new ServiceException("费用已进入应付账单,不能删除"); + } + payBillFeeLogService.record(fee, PayBillFeeLogService.DELETE); + if (fee.getBillId() != null) + { + payBillFeeService.refreshTotals(List.of(fee.getBillId())); + } + } + + /** 费用弹框一行。手工费用直接用保存下来的名称。 */ + private static PayOrderFeeLine toLine(PrcPayBillFee fee) + { + PayOrderFeeLine line = new PayOrderFeeLine(); + line.setFeeId(fee.getFeeId()); + line.setFeeType(fee.getFeeType()); + line.setFeeName(fee.getFeeName()); + line.setLevel(fee.getFeeLevel()); + line.setAmount(fee.getAmount()); + line.setCurrency(fee.getCurrency()); + line.setFeeSource(fee.getFeeSource() == null || fee.getFeeSource().isBlank() ? "CALC" : fee.getFeeSource()); + line.setRemark(fee.getRemark()); + line.setStatementLineId(fee.getStatementLineId()); + line.setCreateBy(fee.getCreateBy()); + line.setCreateTime(fee.getCreateTime()); + line.setUpdateBy(fee.getUpdateBy()); + line.setUpdateTime(fee.getUpdateTime()); + return line; + } + + /** 当前登录人。同步线程没有登录信息时记 system。 */ + private static String operator() + { + try + { + String name = SecurityUtils.getUsername(); + return name == null || name.isBlank() ? "system" : name; + } + catch (Exception ex) + { + return "system"; + } + } + + private static String firstText(String primary, String fallback) + { + if (primary != null && !primary.isBlank()) + { + return primary.trim(); + } + return fallback == null ? "" : fallback.trim(); + } + + /** 手工费用用负数序号,避免和同一费用项的计算费用撞上唯一键。 */ + private static long manualScId() + { + long tick = System.nanoTime(); + if (tick == Long.MIN_VALUE) + { + return -1L; + } + long value = -Math.abs(tick); + return value == 0L ? -1L : value; + } + + private PayOrderRow requireOrder(String billId) + { + if (billId == null || billId.isBlank()) + { + throw PaymentMesEnum.BMS_PAY_PICK_ORDER.exception(); + } + PayOrderRow order = payOrderListMapper.selectRow(billId.trim()); + if (order == null || order.getBillId() == null || order.getBillId().isBlank()) + { + throw PaymentMesEnum.BMS_PAY_ORDER_MISS.exception(); + } + return order; + } + + /** 订单号按逗号、顿号、分号、空白拆开,并去掉重复和空白。 */ + private static List orderNos(String text) + { + LinkedHashSet values = new LinkedHashSet<>(); + if (text != null) + { + for (String part : text.split("[,,、;;\\s]+")) + { + String token = part.trim(); + if (!token.isEmpty()) + { + values.add(token); + } + } + } + return new ArrayList<>(values); + } + + /** 已经标明阶段的按阶段放。尾程计算出来的派送费和附加费没有阶段时归到 D 段。 */ + private static String levelOf(PrcPayBillFee fee) + { + String level = fee.getFeeLevel(); + if ("1".equals(level) || "2".equals(level) || "3".equals(level) || "4".equals(level)) + { + return level; + } + return "4"; + } +} diff --git a/bms-back/bms-system/src/main/java/com/bms/price/service/impl/PrcOrderBillServiceImpl.java b/bms-back/bms-system/src/main/java/com/bms/price/service/impl/PrcOrderBillServiceImpl.java index c2d9146d..0d755e8e 100644 --- a/bms-back/bms-system/src/main/java/com/bms/price/service/impl/PrcOrderBillServiceImpl.java +++ b/bms-back/bms-system/src/main/java/com/bms/price/service/impl/PrcOrderBillServiceImpl.java @@ -106,6 +106,7 @@ import com.bms.customer.customermoney.api.CreditUsageCommand; import com.bms.customer.customermoney.api.CustomerFundBizType; import com.bms.customer.customermoney.api.ICustomerAccountApi; import com.bms.customer.customermoney.vo.CustomerAccountStatusVO; +import com.bms.price.service.IPayOrderCostService; import com.bms.price.service.IPrcOrderBillService; import com.bms.price.service.IPrcSurchargeService; import com.bms.price.service.ITmsPriceQuoteService; @@ -124,6 +125,9 @@ public class PrcOrderBillServiceImpl implements IPrcOrderBillService @Lazy private IPrcOrderBillService self; + @Autowired + private IPayOrderCostService payOrderCostService; + @Autowired private ITmsPriceQuoteService tmsPriceQuoteService; @@ -3270,7 +3274,7 @@ bill.setWeight(weight); /** * 订单来源同步:用上游字段完整覆盖本地账单 + ext。 - * 不做报价、不占用授信、不涉及费用,也不校验 AR/退费。 + * 不做应收报价、不占用授信。订单提交成功后,再按应付产品落地尾程运费和订单附加费。 */ @Override @Transactional(rollbackFor = Exception.class) @@ -3375,9 +3379,109 @@ bill.setWeight(weight); // ES 映射中 response.ok 为 long 类型,使用 1/0 而非布尔 true/false。 billSearchStore.save(EsLogType.BILL, bizId, req.toJSONString(), "{\"ok\":1,\"action\":\"UPSTREAM_SYNC\"}"); + landTailFeesAfterCommit(bill); return bill.getBillId(); } + /** + * 等这票订单提交成功后再算尾程应付。生成失败只打日志并写入 ES,不回滚订单,也不往外抛。 + * + * @param bill 刚写入的计费订单 + */ + private void landTailFeesAfterCommit(PrcOrderBill bill) + { + if (bill == null || bill.getBillId() == null || payOrderCostService == null) + { + return; + } + Long billId = bill.getBillId(); + String orderNo = bill.getOrderNo(); + String transferNo = bill.getTransferNo(); + if (!TransactionSynchronizationManager.isSynchronizationActive()) + { + landTailFeesQuietly(billId, orderNo, transferNo); + return; + } + try + { + TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() + { + @Override + public void afterCommit() + { + landTailFeesQuietly(billId, orderNo, transferNo); + } + }); + } + catch (RuntimeException ex) + { + log.warn("订单同步后应付费用未安排生成 billId={}", billId, ex); + savePayFeeFailEs(billId, orderNo, transferNo, ex); + } + } + + /** + * 落地还没出账的尾程运费和订单附加费。任何失败都只记录异常并写入 ES,留给下次同步再试。 + * + * @param billId 计费订单 ID + * @param orderNo 订单号 + * @param transferNo 转单号,ES 检索优先用它 + */ + private void landTailFeesQuietly(Long billId, String orderNo, String transferNo) + { + try + { + payOrderCostService.landIfOpen(billId); + } + catch (Exception ex) + { + log.warn("订单同步后应付费用生成失败 billId={}", billId, ex); + savePayFeeFailEs(billId, orderNo, transferNo, ex); + try + { + payOrderCostService.markCalcFail(billId, ex.getMessage()); + } + catch (Exception markEx) + { + log.warn("应付计费失败状态未写入 billId={}", billId, markEx); + } + } + } + + /** + * 把应付费用生成失败写进订单原有的 ES 日志。bizId 与订单同步相同,优先转单号。 + * + * @param billId 计费订单 ID + * @param orderNo 订单号 + * @param transferNo 转单号 + * @param ex 生成失败的异常 + */ + private void savePayFeeFailEs(Long billId, String orderNo, String transferNo, Exception ex) + { + if (billSearchStore == null) + { + return; + } + try + { + String message = ex == null || ex.getMessage() == null ? "应付费用生成失败" : ex.getMessage(); + JSONObject req = new JSONObject(); + req.put("action", "PAY_FEE_FAIL"); + req.put("orderNo", orderNo); + req.put("transferNo", transferNo); + req.put("billId", billId); + req.put("errorMessage", message); + String bizId = StringUtils.isNotEmpty(transferNo) ? transferNo.trim() + : (StringUtils.isNotEmpty(orderNo) ? orderNo.trim() : String.valueOf(billId)); + billSearchStore.save(EsLogType.BILL, bizId, req.toJSONString(), + "{\"ok\":0,\"action\":\"PAY_FEE_FAIL\"}", EsBizLogSupport.STATUS_FAIL, message); + } + catch (Exception logEx) + { + log.warn("应付费用失败日志写入 ES 失败 billId={}", billId, logEx); + } + } + /** 按编码尽力查询客户 ID;查询不到时保留原 ID。 */ private Long resolveCustomerIdByCode(String customerCode, Long previousId) { diff --git a/bms-back/bms-system/src/main/java/com/bms/price/service/impl/PrcPayBillFeeServiceImpl.java b/bms-back/bms-system/src/main/java/com/bms/price/service/impl/PrcPayBillFeeServiceImpl.java index d5a0d215..697bdaba 100644 --- a/bms-back/bms-system/src/main/java/com/bms/price/service/impl/PrcPayBillFeeServiceImpl.java +++ b/bms-back/bms-system/src/main/java/com/bms/price/service/impl/PrcPayBillFeeServiceImpl.java @@ -43,19 +43,6 @@ public class PrcPayBillFeeServiceImpl implements IPrcPayBillFeeService { List chunk = fees.subList(from, Math.min(from + BATCH_SIZE, fees.size())); payBillFeeMapper.insertBatch(chunk); - List ownIds = new ArrayList<>(); - for (PrcPayBillFee fee : chunk) - { - if (fee != null && fee.getFeeId() != null && !fee.getFeeId().isBlank() - && (fee.getSourceId() == null || fee.getSourceId().isBlank())) - { - ownIds.add(fee.getFeeId()); - } - } - if (!ownIds.isEmpty()) - { - payBillFeeMapper.fillSourceIdByFeeIds(ownIds); - } for (PrcPayBillFee fee : chunk) { if (fee != null && fee.getBillId() != null) diff --git a/bms-back/bms-system/src/main/java/com/bms/price/service/impl/SrvBillAirAllocServiceImpl.java b/bms-back/bms-system/src/main/java/com/bms/price/service/impl/SrvBillAirAllocServiceImpl.java index b249f980..4ae2c953 100644 --- a/bms-back/bms-system/src/main/java/com/bms/price/service/impl/SrvBillAirAllocServiceImpl.java +++ b/bms-back/bms-system/src/main/java/com/bms/price/service/impl/SrvBillAirAllocServiceImpl.java @@ -27,6 +27,7 @@ import com.bms.price.mapper.SrvBillAirAllocMapper; import com.bms.price.mapper.SrvBillAirFeeMapper; import com.bms.price.mapper.SrvBillAirMapper; import com.bms.price.service.IPrcPayBillFeeService; +import com.bms.price.service.PayBillFeeLogService; import com.bms.price.service.ISrvBillAirAllocService; /** @@ -59,6 +60,9 @@ public class SrvBillAirAllocServiceImpl implements ISrvBillAirAllocService @Autowired private IPrcPayBillFeeService payBillFeeService; + @Autowired + private PayBillFeeLogService payBillFeeLogService; + @Override public List preview(List billCodes) { @@ -237,9 +241,8 @@ public class SrvBillAirAllocServiceImpl implements ISrvBillAirAllocService row.setFeeId(UUID.randomUUID().toString()); row.setBillId(order.getBillId()); row.setPayBillId(payBillIds.get(order.getBillId())); - String name = blankName(fee); - row.setFeeType(name.length() <= 30 ? name : name.substring(0, 30)); - row.setFeeName(name); + row.setFeeType(dictType(fee.getFeeType())); + row.setFeeName(fee.getFeeName()); row.setScId(fee.getId() == null ? 0L : fee.getId()); row.setFeeLevel(fee.getFeeLevel()); row.setAmount(amount); @@ -247,6 +250,7 @@ public class SrvBillAirAllocServiceImpl implements ISrvBillAirAllocService row.setRoundMode("HALF_UP"); row.setRemark(remark(fee)); row.setFeeSource(FEE_SOURCE); + row.setSourceId(fee.getId() == null ? null : String.valueOf(fee.getId())); row.setIsDeleted("0"); return row; } @@ -259,6 +263,7 @@ public class SrvBillAirAllocServiceImpl implements ISrvBillAirAllocService } int rows = batch.size(); payBillFeeService.insertBatchAndRefreshTotals(new ArrayList<>(batch)); + payBillFeeLogService.record(batch, PayBillFeeLogService.ADD); batch.clear(); return rows; } @@ -378,6 +383,15 @@ public class SrvBillAirAllocServiceImpl implements ISrvBillAirAllocService return ids; } + private static String dictType(String feeType) + { + if (feeType == null || !feeType.trim().matches("[A-Z][A-Z0-9_]*")) + { + return "SURCHARGE"; + } + return feeType.trim(); + } + private static String blankName(SrvBillAirAllocFee fee) { if (fee.getFeeName() != null && !fee.getFeeName().isBlank()) diff --git a/bms-back/bms-system/src/main/java/com/bms/price/service/impl/SrvBillAirFeeServiceImpl.java b/bms-back/bms-system/src/main/java/com/bms/price/service/impl/SrvBillAirFeeServiceImpl.java index 90de96cc..1ebbab8c 100644 --- a/bms-back/bms-system/src/main/java/com/bms/price/service/impl/SrvBillAirFeeServiceImpl.java +++ b/bms-back/bms-system/src/main/java/com/bms/price/service/impl/SrvBillAirFeeServiceImpl.java @@ -28,12 +28,14 @@ import com.bms.price.airbill.domain.SrvBillAirRoleFeeCommand; import com.bms.price.airbill.domain.SrvBillAirRoleFeeQuery; import com.bms.price.airbill.domain.SrvBillAirFeeLog; import com.bms.price.airbill.domain.SrvBillAirFeeSave; +import com.bms.price.domain.PrcPayBillFee; import com.bms.price.domain.PrcSurcharge; import com.bms.price.mapper.PrcPayBillFeeMapper; import com.bms.price.mapper.PrcSurchargeMapper; import com.bms.price.mapper.SrvBillAirFeeMapper; import com.bms.price.mapper.SrvBillAirMapper; import com.bms.price.service.IPrcPayBillFeeService; +import com.bms.price.service.PayBillFeeLogService; import com.bms.price.service.IPrcSurchargeService; import com.bms.price.service.ISrvBillAirFeeService; import com.bms.system.service.ISysDictTypeService; @@ -70,6 +72,9 @@ public class SrvBillAirFeeServiceImpl implements ISrvBillAirFeeService @Autowired private IPrcPayBillFeeService payBillFeeService; + @Autowired + private PayBillFeeLogService payBillFeeLogService; + @Autowired private IPrcSurchargeService surchargeService; @@ -210,7 +215,8 @@ public class SrvBillAirFeeServiceImpl implements ISrvBillAirFeeService throw new ServiceException("第" + line + "行备注不能超过500字"); } SrvBillAirFee fee = new SrvBillAirFee(); - fee.setFeeType(String.valueOf(chosen.getScId())); + fee.setScId(chosen.getScId()); + fee.setFeeType(chosen.getFeeType() == null || chosen.getFeeType().isBlank() ? "SURCHARGE" : chosen.getFeeType().trim()); fee.setFeeName(chosen.getScName()); fee.setFeeLevel(level); fee.setPrice(row.getPrice()); @@ -410,7 +416,9 @@ public class SrvBillAirFeeServiceImpl implements ISrvBillAirFeeService Operator operator = operator(); Date now = DateUtils.getNowDate(); List affectedBills = payBillFeeMapper.selectBillIdsByLadingFee(feeId); + List allocated = payBillFeeMapper.selectAliveByLadingFee(feeId); payBillFeeMapper.markLadingFeeDeleted(feeId); + payBillFeeLogService.record(allocated, PayBillFeeLogService.VOID); payBillFeeService.refreshTotals(affectedBills); if (feeMapper.voidFee(feeId, code, operator.account, now) != 1) { @@ -556,7 +564,7 @@ public class SrvBillAirFeeServiceImpl implements ISrvBillAirFeeService String feeLevel = trim(raw.getFeeLevel()); String currency = trim(raw.getCurrency()); String remark = trim(raw.getRemark()); - Long scId = parseScId(feeType); + Long scId = raw.getScId() != null && raw.getScId() > 0 ? raw.getScId() : parseScId(feeType); if (scId == null) { throw PaymentMesEnum.BMS_PAY_PICK_ITEM.exception(); @@ -566,7 +574,7 @@ public class SrvBillAirFeeServiceImpl implements ISrvBillAirFeeService { throw PaymentMesEnum.BMS_PAY_ITEM_MISS.exception(); } - feeType = String.valueOf(scId); + feeType = surcharge.getFeeType() == null || surcharge.getFeeType().isBlank() ? "SURCHARGE" : surcharge.getFeeType().trim(); if (!feeLevel.isEmpty() && (feeLevel.length() > 32 || !levelLabels.containsKey(feeLevel))) { throw PaymentMesEnum.BMS_PAY_LEVEL.exception(); @@ -597,6 +605,7 @@ public class SrvBillAirFeeServiceImpl implements ISrvBillAirFeeService } SrvBillAirFee fee = new SrvBillAirFee(); fee.setFeeType(feeType); + fee.setScId(scId); fee.setFeeLevel(feeLevel); fee.setFeeScene(trim(raw.getFeeScene())); fee.setAllocFlag("1"); @@ -660,8 +669,8 @@ public class SrvBillAirFeeServiceImpl implements ISrvBillAirFeeService Map dimLabels, Map statusLabels, Map currencyLabels) { List changes = new ArrayList<>(); - addChange(changes, "feeType", "费用项", label(feeLabels, value(before, SrvBillAirFee::getFeeType)), - label(feeLabels, value(after, SrvBillAirFee::getFeeType))); + addChange(changes, "scId", "费用项", label(feeLabels, scKey(before)), + label(feeLabels, scKey(after))); addChange(changes, "price", "价格", priceText(before), priceText(after)); addChange(changes, "currency", "收费币种", label(currencyLabels, value(before, SrvBillAirFee::getCurrency)), label(currencyLabels, value(after, SrvBillAirFee::getCurrency))); @@ -766,7 +775,7 @@ public class SrvBillAirFeeServiceImpl implements ISrvBillAirFeeService { return; } - String id = trim(fee.getFeeType()); + String id = scKey(fee); if (id.isEmpty() || names.containsKey(id)) { return; @@ -774,6 +783,11 @@ public class SrvBillAirFeeServiceImpl implements ISrvBillAirFeeService names.put(id, surchargeName(id)); } + private static String scKey(SrvBillAirFee fee) + { + return fee == null || fee.getScId() == null ? "" : String.valueOf(fee.getScId()); + } + private String surchargeName(String feeType) { Long scId = parseScId(feeType); diff --git a/bms-back/bms-system/src/main/java/com/bms/price/task/PayOrderRecalcAsyncRunner.java b/bms-back/bms-system/src/main/java/com/bms/price/task/PayOrderRecalcAsyncRunner.java new file mode 100644 index 00000000..ab284555 --- /dev/null +++ b/bms-back/bms-system/src/main/java/com/bms/price/task/PayOrderRecalcAsyncRunner.java @@ -0,0 +1,300 @@ +package com.bms.price.task; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Lazy; +import org.springframework.scheduling.annotation.Async; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Component; +import com.alibaba.fastjson2.JSON; +import com.bms.common.core.redis.RedisCache; +import com.bms.common.exception.ServiceException; +import com.bms.price.domain.PayOrderCostResult; +import com.bms.price.domain.PayOrderRecalcLine; +import com.bms.price.domain.PayOrderRecalcTask; +import com.bms.price.domain.PrcPayBillFeeLog; +import com.bms.price.service.IPayOrderListService; +import com.bms.price.service.PayBillFeeLogService; + +/** 异步重算应付费用。订单集合和进度都写在 Redis,每处理一票更新一次。 */ +@Component +public class PayOrderRecalcAsyncRunner +{ + private static final Logger log = LoggerFactory.getLogger(PayOrderRecalcAsyncRunner.class); + + public static final String CACHE_KEY_PREFIX = "price:payOrder:recalc:task:"; + + public static final int TTL_MINUTES = 120; + + @Autowired + @Lazy + private IPayOrderListService payOrderListService; + + @Autowired + private PayBillFeeLogService payBillFeeLogService; + + @Autowired + private RedisCache redisCache; + + private final Map cancelFlags = new ConcurrentHashMap<>(); + + @Async("threadPoolTaskExecutor") + public void run(String taskId, Authentication authentication) + { + SecurityContext previous = SecurityContextHolder.getContext(); + List feeLogs = new ArrayList<>(); + boolean drained = false; + try + { + if (authentication != null) + { + SecurityContext context = SecurityContextHolder.createEmptyContext(); + context.setAuthentication(authentication); + SecurityContextHolder.setContext(context); + } + PayOrderRecalcTask task = require(taskId); + List lines = linesOf(task); + task.setStatus(PayOrderRecalcTask.RUNNING); + task.setMessage("正在重算"); + recount(task); + save(task); + int total = lines.size(); + cancelFlags.computeIfAbsent(taskId, key -> new AtomicBoolean(false)); + for (int i = 0; i < total; i++) + { + if (cancelled(taskId)) + { + finishCancelled(task, feeLogs); + drained = true; + return; + } + PayOrderRecalcLine line = lines.get(i); + if (line.isFinished()) + { + continue; + } + try + { + PayOrderCostResult cost = payOrderListService.recalcOne(Long.valueOf(line.getBillId().trim())); + line.setSuccess(true); + line.setMessage(null); + if (cost != null) + { + payBillFeeLogService.collect(feeLogs, cost.getLoggedFees(), cost.getFeeLogType()); + if (feeLogs.size() >= PayBillFeeLogService.BATCH_SIZE) + { + payBillFeeLogService.flush(feeLogs); + } + } + } + catch (Exception ex) + { + line.setSuccess(false); + line.setMessage(text(ex)); + log.warn("应付费用重算失败 taskId={} billId={}", taskId, line.getBillId(), ex); + } + line.setFinished(true); + recount(task); + int done = task.getSuccessCount() + task.getFailCount(); + task.setPercent(total == 0 ? 100 : Math.min(99, done * 100 / total)); + task.setStatus(PayOrderRecalcTask.RUNNING); + task.setMessage(cancelled(taskId) + ? "正在取消,等待当前订单结束…" + : "正在处理 " + done + "/" + total); + save(task); + } + if (cancelled(taskId)) + { + finishCancelled(task, feeLogs); + drained = true; + return; + } + drain(feeLogs); + drained = true; + recount(task); + task.setStatus(PayOrderRecalcTask.SUCCESS); + task.setPercent(100); + task.setMessage("成功 " + task.getSuccessCount() + " 票,失败 " + task.getFailCount() + " 票"); + save(task); + log.info("应付费用重算完成 taskId={} total={} success={} fail={}", taskId, task.getTotal(), task.getSuccessCount(), task.getFailCount()); + } + catch (Exception ex) + { + if (cancelled(taskId)) + { + PayOrderRecalcTask task = get(taskId); + if (task != null) + { + linesOf(task); + finishCancelled(task, feeLogs); + drained = true; + } + return; + } + log.error("应付费用重算中断 taskId={}", taskId, ex); + PayOrderRecalcTask task = get(taskId); + if (task != null) + { + task.setStatus(PayOrderRecalcTask.FAIL); + task.setPercent(100); + task.setMessage(text(ex)); + save(task); + } + } + finally + { + if (!drained) + { + drain(feeLogs); + } + SecurityContextHolder.setContext(previous); + cancelFlags.remove(taskId); + } + } + + /** + * 停止还没开始的订单。正在算的这一票会算完,已经算完的保留。 + * + * @param taskId 任务号 + * @return 更新后的进度 + */ + public PayOrderRecalcTask cancel(String taskId) + { + PayOrderRecalcTask task = get(taskId); + if (task == null) + { + throw new ServiceException("重算任务不存在或已过期"); + } + String status = task.getStatus(); + if (PayOrderRecalcTask.SUCCESS.equals(status) || PayOrderRecalcTask.FAIL.equals(status) || PayOrderRecalcTask.CANCELLED.equals(status)) + { + return task; + } + cancelFlags.computeIfAbsent(taskId, key -> new AtomicBoolean()).set(true); + task.setMessage("正在取消,等待当前订单结束…"); + save(task); + return task; + } + + private boolean cancelled(String taskId) + { + AtomicBoolean flag = cancelFlags.get(taskId); + return flag != null && flag.get(); + } + + private void finishCancelled(PayOrderRecalcTask task, List feeLogs) + { + recount(task); + task.setStatus(PayOrderRecalcTask.CANCELLED); + task.setPercent(100); + task.setMessage("费用重算已取消:成功 " + task.getSuccessCount() + " / 失败 " + task.getFailCount() + " / 总数 " + task.getTotal()); + save(task); + drain(feeLogs); + } + + public void save(PayOrderRecalcTask task) + { + redisCache.setCacheObject(CACHE_KEY_PREFIX + task.getTaskId(), task, TTL_MINUTES, TimeUnit.MINUTES); + } + + public PayOrderRecalcTask get(String taskId) + { + if (taskId == null || taskId.isBlank()) + { + return null; + } + Object value = redisCache.getCacheObject(CACHE_KEY_PREFIX + taskId.trim()); + if (value == null) + { + return null; + } + if (value instanceof PayOrderRecalcTask) + { + return (PayOrderRecalcTask) value; + } + return JSON.parseObject(JSON.toJSONString(value), PayOrderRecalcTask.class); + } + + private PayOrderRecalcTask require(String taskId) + { + PayOrderRecalcTask task = get(taskId); + if (task == null) + { + throw new IllegalStateException("重算任务不存在"); + } + linesOf(task); + return task; + } + + private static List linesOf(PayOrderRecalcTask task) + { + List lines = new ArrayList<>(); + if (task.getLines() != null) + { + for (Object item : task.getLines()) + { + if (item instanceof PayOrderRecalcLine) + { + lines.add((PayOrderRecalcLine) item); + } + else if (item != null) + { + lines.add(JSON.parseObject(JSON.toJSONString(item), PayOrderRecalcLine.class)); + } + } + } + task.setLines(lines); + return lines; + } + + private static void recount(PayOrderRecalcTask task) + { + int success = 0; + int fail = 0; + for (PayOrderRecalcLine line : task.getLines()) + { + if (line == null || !line.isFinished()) + { + continue; + } + if (line.isSuccess()) + { + success++; + } + else + { + fail++; + } + } + task.setTotal(task.getLines().size()); + task.setSuccessCount(success); + task.setFailCount(fail); + } + + private void drain(List feeLogs) + { + if (feeLogs != null && !feeLogs.isEmpty()) + { + payBillFeeLogService.drain(feeLogs); + } + } + + private static String text(Exception ex) + { + String message = ex.getMessage(); + if (message == null || message.isBlank()) + { + message = "应付费用生成失败"; + } + return message.length() <= 200 ? message : message.substring(0, 200); + } +} diff --git a/bms-back/bms-system/src/main/java/com/bms/price/task/TabOrderSyncAsyncRunner.java b/bms-back/bms-system/src/main/java/com/bms/price/task/TabOrderSyncAsyncRunner.java index 5c89be1f..c84ffa9c 100644 --- a/bms-back/bms-system/src/main/java/com/bms/price/task/TabOrderSyncAsyncRunner.java +++ b/bms-back/bms-system/src/main/java/com/bms/price/task/TabOrderSyncAsyncRunner.java @@ -32,7 +32,7 @@ import com.bms.price.search.TabOrderSyncEsLog; import com.bms.price.service.IPrcOrderBillService; /** - * 分页读取 Oracle TAB_ORDER,再多线程覆盖本地账单字段(不计费)。 + * 分页读取 Oracle TAB_ORDER,覆盖本地订单,并在订单提交后落地尾程应付。 */ @Component public class TabOrderSyncAsyncRunner @@ -316,7 +316,7 @@ public class TabOrderSyncAsyncRunner } } - /** 解析出 Oracle 行后覆盖本地账单及其扩展信息(不计费)。 */ + /** 解析出 Oracle 行后覆盖本地账单。应付费用在订单提交后另算,失败只记日志。 */ private Long overwriteOne(com.bms.price.oracle.TabOrderRow row) { Map raw = row == null ? null : row.getRaw(); diff --git a/bms-back/bms-system/src/main/resources/mapper/customer/BmsSupplierMapper.xml b/bms-back/bms-system/src/main/resources/mapper/customer/BmsSupplierMapper.xml index ab0252bb..5ee55c3f 100644 --- a/bms-back/bms-system/src/main/resources/mapper/customer/BmsSupplierMapper.xml +++ b/bms-back/bms-system/src/main/resources/mapper/customer/BmsSupplierMapper.xml @@ -32,6 +32,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" + @@ -47,7 +48,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" s.is_enable, s.purchaser_user_id, s.purchaser_user, s.settlement_user_id, s.settlement_user, s.service_user_id, s.service_user, s.ed, s.zq, s.settlement_type, s.temp_ed, s.account_balance, s.foreign_currency_balance, s.credit_ed, s.weight_threshold, s.throw_ratio, s.cooperation_start_date, - s.contract_end_date, s.cooperation_status, s.channel_ids, s.remark, + s.contract_end_date, s.cooperation_status, s.data_source, s.channel_ids, s.remark, s.create_by, s.create_time, s.update_by, s.update_time, s.del_flag from sup_supplier s + + diff --git a/bms-front/src/views/report/profit/index.vue b/bms-front/src/views/report/profit/index.vue index 26b39f9d..cc0df466 100644 --- a/bms-front/src/views/report/profit/index.vue +++ b/bms-front/src/views/report/profit/index.vue @@ -24,7 +24,7 @@ - + + + + + + + + + + + + + + + + + + + + + + + - + @@ -119,10 +141,7 @@
- - - - + 订单明细
- - - + + + + + + + + + + + + + + + + + + + + + + + +
@@ -212,35 +207,6 @@ /> - - - - - - - - - - - - - - - - - - - - - - - @@ -309,15 +275,14 @@