应付费用重算优化以及样式调整

This commit is contained in:
liuminghui
2026-11-17 10:16:00 +08:00
parent f00f8c619a
commit 54ac6428e7
20 changed files with 1496 additions and 200 deletions
@@ -1,5 +1,7 @@
package com.bms.web.controller.price; package com.bms.web.controller.price;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.DeleteMapping;
@@ -15,6 +17,7 @@ import com.bms.common.core.page.TableDataInfo;
import com.bms.price.domain.PayOrderFeeLine; import com.bms.price.domain.PayOrderFeeLine;
import com.bms.price.domain.PayOrderQuery; import com.bms.price.domain.PayOrderQuery;
import com.bms.price.domain.PayOrderRecalcCommand; import com.bms.price.domain.PayOrderRecalcCommand;
import com.bms.price.domain.PayOrderRecalcTask;
import com.bms.price.service.IPayOrderListService; import com.bms.price.service.IPayOrderListService;
/** 提单管理下的应付列表。 */ /** 提单管理下的应付列表。 */
@@ -43,7 +46,40 @@ public class PayOrderController extends BaseController
@PostMapping("/recalc") @PostMapping("/recalc")
public AjaxResult recalc(@RequestBody PayOrderRecalcCommand command) public AjaxResult recalc(@RequestBody PayOrderRecalcCommand command)
{ {
return success(payOrderListService.recalc(command)); Map<String, String> 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));
} }
/** /**
@@ -86,4 +122,17 @@ public class PayOrderController extends BaseController
payOrderListService.removeFee(feeId); payOrderListService.removeFee(feeId);
return success(); 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));
}
} }
@@ -15,7 +15,4 @@ public class PayOrderFeeBoard
private String ladingNo; private String ladingNo;
private List<PayOrderFeeSection> sections = new ArrayList<>(); private List<PayOrderFeeSection> sections = new ArrayList<>();
/** 这票订单的应付费用日志,新的在前 */
private List<PrcPayBillFeeLog> logs = new ArrayList<>();
} }
@@ -6,10 +6,15 @@ import lombok.Data;
@Data @Data
public class PayOrderRecalcLine public class PayOrderRecalcLine
{ {
private String billId;
private String orderNo; private String orderNo;
private String ladingNo; private String ladingNo;
/** 这一条是否已经处理完 */
private boolean finished;
/** 这一票是否已经生成应付费用 */ /** 这一票是否已经生成应付费用 */
private boolean success; private boolean success;
@@ -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<PayOrderRecalcLine> lines = new ArrayList<>();
}
@@ -37,6 +37,13 @@ public class PayOrderRow
/** 计费失败原因 */ /** 计费失败原因 */
private String payCalcMsg; 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") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date bizDate; private Date bizDate;
} }
@@ -4,6 +4,7 @@ import java.io.Serializable;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.Date; import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data; import lombok.Data;
/** 应付费用明细 prc_pay_bill_fee */ /** 应付费用明细 prc_pay_bill_fee */
@@ -61,4 +62,20 @@ public class PrcPayBillFee implements Serializable
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date updateTime; private Date updateTime;
/** 写日志时带上的变更前费用项,不入库 */
@JsonIgnore
private String logBeforeName;
/** 写日志时带上的变更前金额,不入库 */
@JsonIgnore
private BigDecimal logBeforeAmount;
/** 写日志时带上的变更前币种,不入库 */
@JsonIgnore
private String logBeforeCurrency;
/** 为 true 时日志只记变更前。重算后消失的计算费用用,不入库 */
@JsonIgnore
private Boolean logAfterBlank;
} }
@@ -25,9 +25,30 @@ public class PrcPayBillFeeLog implements Serializable
private String currency; 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 */ /** 操作类型,字典 bms_pay_fee_log_type */
private String operationType; private String operationType;
/** 备注。费用重算失败时写入失败原因 */
private String remark;
/** 操作人 */ /** 操作人 */
private String createBy; private String createBy;
@@ -1,12 +1,14 @@
package com.bms.price.service; package com.bms.price.service;
import java.util.List; import java.util.List;
import com.bms.price.domain.PayOrderCostResult;
import com.bms.price.domain.PayOrderFeeBoard; import com.bms.price.domain.PayOrderFeeBoard;
import com.bms.price.domain.PayOrderFeeLine; import com.bms.price.domain.PayOrderFeeLine;
import com.bms.price.domain.PayOrderQuery; import com.bms.price.domain.PayOrderQuery;
import com.bms.price.domain.PayOrderRecalcCommand; import com.bms.price.domain.PayOrderRecalcCommand;
import com.bms.price.domain.PayOrderRecalcResult; import com.bms.price.domain.PayOrderRecalcTask;
import com.bms.price.domain.PayOrderRow; import com.bms.price.domain.PayOrderRow;
import com.bms.price.domain.PrcPayBillFeeLog;
/** 应付列表。 */ /** 应付列表。 */
public interface IPayOrderListService public interface IPayOrderListService
@@ -32,12 +34,42 @@ public interface IPayOrderListService
void removeFee(String feeId); void removeFee(String feeId);
/** /**
* 按订单号或提单号批量重算尾程应付。一票失败不影响其他订单。 * 提交应付费用重算。订单先放进 Redis,后台逐票计算,每票更新进度。
* 成功时应付主表记计费成功,应付总额按全部未删除明细重算。
* 失败时记计费失败和原因。已经进入应付账单的费用不覆盖。
* *
* @param command 重算方式(ORDER 或 LADING)和单号原文 * @param command 重算方式(ORDER 或 LADING)和单号原文
* @return 成功数、失败数和每一票的结果 * @return 任务号,用来查询进度
*/ */
PayOrderRecalcResult recalc(PayOrderRecalcCommand command); 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<PrcPayBillFeeLog> feeLogs(String billId);
} }
@@ -9,6 +9,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import com.bms.common.utils.PageUtils;
import com.bms.common.utils.SecurityUtils; import com.bms.common.utils.SecurityUtils;
import com.bms.price.domain.PrcPayBillFee; import com.bms.price.domain.PrcPayBillFee;
import com.bms.price.domain.PrcPayBillFeeLog; import com.bms.price.domain.PrcPayBillFeeLog;
@@ -140,7 +141,15 @@ public class PayBillFeeLogService
try try
{ {
List<PrcPayBillFeeLog> rows = payBillFeeLogMapper.selectByBillId(billId); List<PrcPayBillFeeLog> rows = payBillFeeLogMapper.selectByBillId(billId);
return rows == null ? Collections.emptyList() : rows; if (rows == null)
{
return Collections.emptyList();
}
for (PrcPayBillFeeLog row : rows)
{
present(row);
}
return rows;
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -149,6 +158,97 @@ public class PayBillFeeLogService
} }
} }
/**
* 费用重算失败时给这票订单记一条日志,备注里写失败原因。没有费用明细。异常只打印,不向外抛。
*
* @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<PrcPayBillFeeLog> page(Long billId)
{
if (billId == null)
{
return Collections.emptyList();
}
try
{
PageUtils.startPage();
List<PrcPayBillFeeLog> 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<PrcPayBillFeeLog> bucket, boolean drain) private void write(List<PrcPayBillFeeLog> bucket, boolean drain)
{ {
if (bucket == null || bucket.isEmpty()) if (bucket == null || bucket.isEmpty())
@@ -193,7 +293,28 @@ public class PayBillFeeLogService
row.setFeeName(cut(nameOf(fee), 100)); row.setFeeName(cut(nameOf(fee), 100));
row.setAmount(fee.getAmount()); row.setAmount(fee.getAmount());
String currency = fee.getCurrency() == null ? null : fee.getCurrency().trim(); String currency = fee.getCurrency() == null ? null : fee.getCurrency().trim();
row.setCurrency(currency == null || currency.isEmpty() ? null : cut(currency, 10)); 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.setOperationType(type);
row.setCreateBy(operator); row.setCreateBy(operator);
rows.add(row); rows.add(row);
@@ -208,6 +329,10 @@ public class PayBillFeeLogService
{ {
return name; return name;
} }
if ("BASIC_FREIGHT".equals(fee.getFeeType()))
{
return "基础运费";
}
String type = fee.getFeeType() == null ? "" : fee.getFeeType().trim(); String type = fee.getFeeType() == null ? "" : fee.getFeeType().trim();
return type.isEmpty() ? "费用" : type; return type.isEmpty() ? "费用" : type;
} }
@@ -168,6 +168,7 @@ public class PayOrderCostServiceImpl implements IPayOrderCostService
result.setMessage("渠道「" + channelName + "」" + product.getProductName() + " 第 " + product.getVersionNo() result.setMessage("渠道「" + channelName + "」" + product.getProductName() + " 第 " + product.getVersionNo()
+ " 版(" + day(product.getTermStart()) + " 至 " + end + ")," + result.getMessage()); + " 版(" + day(product.getTermStart()) + " 至 " + end + ")," + result.getMessage());
paySettleSupport.stampCalc(bill.getBillId(), product.getSupplierName()); paySettleSupport.stampCalc(bill.getBillId(), product.getSupplierName());
payBillMapper.markCalcStatus(bill.getBillId(), 1, null, operator);
return result; return result;
} }
@@ -654,7 +655,19 @@ public class PayOrderCostServiceImpl implements IPayOrderCostService
*/ */
private void saveFees(Long billId, String payBillId, PayOrderCostResult result) private void saveFees(Long billId, String payBillId, PayOrderCostResult result)
{ {
boolean recalc = hasCalcFee(billId); List<PrcPayBillFee> current = payBillFeeMapper.selectByBillId(billId);
java.util.Map<String, PrcPayBillFee> 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()); payBillFeeMapper.markCalcDeleted(billId, operator());
List<PrcPayBillFee> rows = new java.util.ArrayList<>(); List<PrcPayBillFee> rows = new java.util.ArrayList<>();
long fallback = 1L; long fallback = 1L;
@@ -666,7 +679,7 @@ public class PayOrderCostServiceImpl implements IPayOrderCostService
row.setBillId(billId); row.setBillId(billId);
row.setPayBillId(payBillId); row.setPayBillId(payBillId);
row.setFeeType(fee.getFeeType()); row.setFeeType(fee.getFeeType());
row.setFeeName(fee.getFeeName()); row.setFeeName(cutFeeName(fee.getFeeName()));
long scId = fee.getScId() == null ? 0L : fee.getScId(); long scId = fee.getScId() == null ? 0L : fee.getScId();
if ("SURCHARGE".equals(fee.getFeeType()) && scId == 0L) if ("SURCHARGE".equals(fee.getFeeType()) && scId == 0L)
{ {
@@ -677,6 +690,13 @@ public class PayOrderCostServiceImpl implements IPayOrderCostService
row.setCurrency(fee.getCurrency()); row.setCurrency(fee.getCurrency());
row.setRoundMode("HALF_UP"); row.setRoundMode("HALF_UP");
row.setRemark(fee.getRemark()); 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); rows.add(row);
} }
if (!rows.isEmpty()) if (!rows.isEmpty())
@@ -687,31 +707,70 @@ public class PayOrderCostServiceImpl implements IPayOrderCostService
{ {
payBillFeeService.refreshTotals(java.util.List.of(billId)); payBillFeeService.refreshTotals(java.util.List.of(billId));
} }
result.setLoggedFees(rows); List<PrcPayBillFee> 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); result.setFeeLogType(recalc ? PayBillFeeLogService.RECALC : PayBillFeeLogService.ADD);
} }
/** 这票订单上还有没删除的计算费用。有则本次落库是重算,没有则是首次生成。 */ /** 计算费用,空来源按计算费用处理。 */
private boolean hasCalcFee(Long billId) private static boolean calcFee(PrcPayBillFee fee)
{
List<PrcPayBillFee> current = payBillFeeMapper.selectByBillId(billId);
if (current == null)
{
return false;
}
for (PrcPayBillFee fee : current)
{ {
if (fee == null) if (fee == null)
{ {
continue; return false;
} }
String source = fee.getFeeSource(); String source = fee.getFeeSource();
if (source == null || source.isBlank() || "CALC".equals(source)) return source == null || source.isBlank() || "CALC".equals(source);
}
private static String feeKey(String feeType, Long scId)
{ {
return true; 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;
} }
return false; 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。 */ /** 当前登录人。没有登录信息时记 system。 */
@@ -9,11 +9,14 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired; 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.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import com.bms.common.enums.PaymentMesEnum; import com.bms.common.enums.PaymentMesEnum;
import com.bms.common.exception.ServiceException; import com.bms.common.exception.ServiceException;
import com.bms.common.utils.SecurityUtils; import com.bms.common.utils.SecurityUtils;
import com.bms.common.utils.uuid.IdUtils;
import com.bms.price.domain.PayOrderCostResult; import com.bms.price.domain.PayOrderCostResult;
import com.bms.price.domain.PayOrderFeeBoard; import com.bms.price.domain.PayOrderFeeBoard;
import com.bms.price.domain.PrcPayBill; import com.bms.price.domain.PrcPayBill;
@@ -22,7 +25,7 @@ import com.bms.price.domain.PayOrderFeeSection;
import com.bms.price.domain.PayOrderQuery; import com.bms.price.domain.PayOrderQuery;
import com.bms.price.domain.PayOrderRecalcCommand; import com.bms.price.domain.PayOrderRecalcCommand;
import com.bms.price.domain.PayOrderRecalcLine; import com.bms.price.domain.PayOrderRecalcLine;
import com.bms.price.domain.PayOrderRecalcResult; import com.bms.price.domain.PayOrderRecalcTask;
import com.bms.price.domain.PayOrderRow; import com.bms.price.domain.PayOrderRow;
import com.bms.price.domain.PrcPayBillFee; import com.bms.price.domain.PrcPayBillFee;
import com.bms.price.domain.PrcPayBillFeeLog; import com.bms.price.domain.PrcPayBillFeeLog;
@@ -33,6 +36,7 @@ import com.bms.price.service.IPayOrderCostService;
import com.bms.price.service.PayBillFeeLogService; import com.bms.price.service.PayBillFeeLogService;
import com.bms.price.service.IPayOrderListService; import com.bms.price.service.IPayOrderListService;
import com.bms.price.service.IPrcPayBillFeeService; import com.bms.price.service.IPrcPayBillFeeService;
import com.bms.price.task.PayOrderRecalcAsyncRunner;
@Service @Service
public class PayOrderListServiceImpl implements IPayOrderListService public class PayOrderListServiceImpl implements IPayOrderListService
@@ -69,6 +73,10 @@ public class PayOrderListServiceImpl implements IPayOrderListService
@Autowired @Autowired
private PayBillFeeLogService payBillFeeLogService; private PayBillFeeLogService payBillFeeLogService;
@Autowired
@Lazy
private PayOrderRecalcAsyncRunner payOrderRecalcAsyncRunner;
@Override @Override
public List<PayOrderRow> list(PayOrderQuery query) public List<PayOrderRow> list(PayOrderQuery query)
{ {
@@ -92,13 +100,13 @@ public class PayOrderListServiceImpl implements IPayOrderListService
} }
/** /**
* 按订单号或提单号逐票重算尾程应付。找不到的单号记失败,已经出账的费用不覆盖。 * 查出订单后放进 Redis,马上返回任务号。逐票计算在后台进行。
* *
* @param command 重算方式和单号原文 * @param command 重算方式和单号原文
* @return 成功数、失败数和明细 * @return 任务号
*/ */
@Override @Override
public PayOrderRecalcResult recalc(PayOrderRecalcCommand command) public String submitRecalc(PayOrderRecalcCommand command)
{ {
if (command == null || command.getSourceType() == null || command.getSourceType().isBlank()) if (command == null || command.getSourceType() == null || command.getSourceType().isBlank())
{ {
@@ -133,11 +141,11 @@ public class PayOrderListServiceImpl implements IPayOrderListService
{ {
throw new ServiceException("一次最多重算" + MAX_ORDER_NOS + "票订单"); throw new ServiceException("一次最多重算" + MAX_ORDER_NOS + "票订单");
} }
PayOrderRecalcResult result = new PayOrderRecalcResult(); PayOrderRecalcTask task = new PayOrderRecalcTask();
List<PrcPayBillFeeLog> feeLogs = new ArrayList<>(); task.setTaskId(IdUtils.fastSimpleUUID());
task.setStatus(PayOrderRecalcTask.PENDING);
task.setMessage("排队中");
LinkedHashSet<String> hit = new LinkedHashSet<>(); LinkedHashSet<String> hit = new LinkedHashSet<>();
try
{
for (PayOrderRow order : found) for (PayOrderRow order : found)
{ {
if (order == null || order.getBillId() == null || order.getBillId().isBlank()) if (order == null || order.getBillId() == null || order.getBillId().isBlank())
@@ -146,46 +154,10 @@ public class PayOrderListServiceImpl implements IPayOrderListService
} }
hit.add(byOrder ? order.getOrderNo() : order.getLadingNo()); hit.add(byOrder ? order.getOrderNo() : order.getLadingNo());
PayOrderRecalcLine line = new PayOrderRecalcLine(); PayOrderRecalcLine line = new PayOrderRecalcLine();
line.setBillId(order.getBillId().trim());
line.setOrderNo(order.getOrderNo()); line.setOrderNo(order.getOrderNo());
line.setLadingNo(order.getLadingNo()); line.setLadingNo(order.getLadingNo());
if (payBillFeeMapper.countSettledCalc(Long.valueOf(order.getBillId().trim())) > 0) task.getLines().add(line);
{
line.setSuccess(false);
line.setMessage("费用已进入应付账单,未重算");
result.getLines().add(line);
result.setFailCount(result.getFailCount() + 1);
continue;
}
try
{
PayOrderCostResult cost = payOrderCostService.generateIsolated(Long.valueOf(order.getBillId().trim()));
line.setSuccess(true);
result.setSuccessCount(result.getSuccessCount() + 1);
if (cost != null)
{
payBillFeeLogService.collect(feeLogs, cost.getLoggedFees(), cost.getFeeLogType());
if (feeLogs.size() >= PayBillFeeLogService.BATCH_SIZE)
{
payBillFeeLogService.flush(feeLogs);
}
}
}
catch (Exception ex)
{
String message = ex.getMessage() == null ? "应付费用生成失败" : ex.getMessage();
try
{
payOrderCostService.markCalcFail(Long.valueOf(order.getBillId().trim()), message);
}
catch (Exception markEx)
{
message = message + ";计费状态未写入";
}
line.setSuccess(false);
line.setMessage(message);
result.setFailCount(result.getFailCount() + 1);
}
result.getLines().add(line);
} }
for (String no : nos) for (String no : nos)
{ {
@@ -204,19 +176,77 @@ public class PayOrderListServiceImpl implements IPayOrderListService
line.setLadingNo(no); line.setLadingNo(no);
line.setMessage("这个提单下没有订单"); line.setMessage("这个提单下没有订单");
} }
line.setFinished(true);
line.setSuccess(false); line.setSuccess(false);
result.getLines().add(line); task.getLines().add(line);
result.setFailCount(result.getFailCount() + 1);
} }
return result; int finished = 0;
} for (PayOrderRecalcLine line : task.getLines())
finally
{ {
if (!feeLogs.isEmpty()) if (line.isFinished())
{ {
payBillFeeLogService.drain(feeLogs); 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<PrcPayBillFeeLog> feeLogs(String billId)
{
if (billId == null || billId.isBlank())
{
throw PaymentMesEnum.BMS_PAY_PICK_ORDER.exception();
}
return payBillFeeLogService.page(Long.valueOf(billId.trim()));
} }
@Override @Override
@@ -256,7 +286,6 @@ public class PayOrderListServiceImpl implements IPayOrderListService
board.setOrderNo(order.getOrderNo()); board.setOrderNo(order.getOrderNo());
board.setLadingNo(order.getLadingNo()); board.setLadingNo(order.getLadingNo());
board.setSections(List.copyOf(sections.values())); board.setSections(List.copyOf(sections.values()));
board.setLogs(payBillFeeLogService.list(Long.valueOf(order.getBillId().trim())));
return board; return board;
} }
@@ -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<String, AtomicBoolean> cancelFlags = new ConcurrentHashMap<>();
@Async("threadPoolTaskExecutor")
public void run(String taskId, Authentication authentication)
{
SecurityContext previous = SecurityContextHolder.getContext();
List<PrcPayBillFeeLog> 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<PayOrderRecalcLine> 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<PrcPayBillFeeLog> 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<PayOrderRecalcLine> linesOf(PayOrderRecalcTask task)
{
List<PayOrderRecalcLine> 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<PrcPayBillFeeLog> 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);
}
}
@@ -16,6 +16,8 @@
p.currency as currency, p.currency as currency,
b.pay_calc_status as payCalcStatus, b.pay_calc_status as payCalcStatus,
b.pay_calc_msg as payCalcMsg, b.pay_calc_msg as payCalcMsg,
b.update_by as updateBy,
b.update_time as updateTime,
p.biz_date as bizDate p.biz_date as bizDate
from prc_order_bill p from prc_order_bill p
left join prc_order_bill_ext e on e.bill_id = p.bill_id left join prc_order_bill_ext e on e.bill_id = p.bill_id
@@ -11,23 +11,38 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<result property="feeName" column="fee_name" /> <result property="feeName" column="fee_name" />
<result property="amount" column="amount" /> <result property="amount" column="amount" />
<result property="currency" column="currency" /> <result property="currency" column="currency" />
<result property="beforeFeeName" column="before_fee_name" />
<result property="beforeAmount" column="before_amount" />
<result property="beforeCurrency" column="before_currency" />
<result property="afterFeeName" column="after_fee_name" />
<result property="afterAmount" column="after_amount" />
<result property="afterCurrency" column="after_currency" />
<result property="operationType" column="operation_type" /> <result property="operationType" column="operation_type" />
<result property="remark" column="remark" />
<result property="createBy" column="create_by" /> <result property="createBy" column="create_by" />
<result property="createTime" column="create_time" /> <result property="createTime" column="create_time" />
</resultMap> </resultMap>
<insert id="insertBatch"> <insert id="insertBatch">
insert into prc_pay_bill_fee_log ( insert into prc_pay_bill_fee_log (
fee_id, bill_id, fee_name, amount, currency, operation_type, create_by, create_time fee_id, bill_id, fee_name, amount, currency,
before_fee_name, before_amount, before_currency,
after_fee_name, after_amount, after_currency,
operation_type, remark, create_by, create_time
) values ) values
<foreach collection="list" item="item" separator=","> <foreach collection="list" item="item" separator=",">
(#{item.feeId}, #{item.billId}, #{item.feeName}, #{item.amount}, #{item.currency}, (#{item.feeId}, #{item.billId}, #{item.feeName}, #{item.amount}, #{item.currency},
#{item.operationType}, #{item.createBy}, sysdate()) #{item.beforeFeeName}, #{item.beforeAmount}, #{item.beforeCurrency},
#{item.afterFeeName}, #{item.afterAmount}, #{item.afterCurrency},
#{item.operationType}, #{item.remark}, #{item.createBy}, sysdate())
</foreach> </foreach>
</insert> </insert>
<select id="selectByBillId" resultMap="PrcPayBillFeeLogResult"> <select id="selectByBillId" resultMap="PrcPayBillFeeLogResult">
select log_id, fee_id, bill_id, fee_name, amount, currency, operation_type, create_by, create_time select log_id, fee_id, bill_id, fee_name, amount, currency,
before_fee_name, before_amount, before_currency,
after_fee_name, after_amount, after_currency,
operation_type, remark, create_by, create_time
from prc_pay_bill_fee_log from prc_pay_bill_fee_log
where bill_id = #{billId} where bill_id = #{billId}
order by log_id desc order by log_id desc
@@ -28,10 +28,11 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<sql id="feeItemName"> <sql id="feeItemName">
case case
when f.fee_source = 'MANUAL' and nullif(trim(f.fee_name), '') is not null then f.fee_name
when f.fee_source = 'LADING' and nullif(trim(air_sc.sc_name), '') is not null then air_sc.sc_name
when f.fee_type = 'SURCHARGE' and nullif(trim(item_sc.sc_name), '') is not null then item_sc.sc_name
when nullif(trim(f.fee_name), '') is not null then f.fee_name when nullif(trim(f.fee_name), '') is not null then f.fee_name
when f.fee_source = 'LADING' and nullif(trim(air_sc.sc_name), '') is not null then air_sc.sc_name
when f.fee_type = 'SURCHARGE' and nullif(trim(pay_sc.fee_name), '') is not null then pay_sc.fee_name
when f.fee_type = 'SURCHARGE' and nullif(trim(item_sc.sc_name), '') is not null then item_sc.sc_name
when f.fee_type = 'BASIC_FREIGHT' then '基础运费'
when nullif(trim(dict.dict_label), '') is not null then dict.dict_label when nullif(trim(dict.dict_label), '') is not null then dict.dict_label
else f.fee_type else f.fee_type
end end
@@ -40,7 +41,8 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<sql id="feeItemJoin"> <sql id="feeItemJoin">
left join srv_bill_air_fee air on f.fee_source = 'LADING' and air.id = f.sc_id left join srv_bill_air_fee air on f.fee_source = 'LADING' and air.id = f.sc_id
left join prc_surcharge air_sc on air_sc.sc_id = air.sc_id left join prc_surcharge air_sc on air_sc.sc_id = air.sc_id
left join prc_surcharge item_sc on ifnull(f.fee_source, '') &lt;&gt; 'LADING' and item_sc.sc_id = f.sc_id left join pay_surcharge pay_sc on f.fee_type = 'SURCHARGE' and ifnull(f.fee_source, '') &lt;&gt; 'LADING' and pay_sc.surcharge_id = f.sc_id
left join prc_surcharge item_sc on f.fee_type = 'SURCHARGE' and ifnull(f.fee_source, '') &lt;&gt; 'LADING' and item_sc.sc_id = f.sc_id
left join sys_dict_data dict on dict.dict_type = 'bms_fee_type' and dict.dict_value = f.fee_type left join sys_dict_data dict on dict.dict_type = 'bms_fee_type' and dict.dict_value = f.fee_type
</sql> </sql>
@@ -89,21 +91,21 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<insert id="insertPrcPayBillFee" parameterType="PrcPayBillFee"> <insert id="insertPrcPayBillFee" parameterType="PrcPayBillFee">
insert into prc_pay_bill_fee ( insert into prc_pay_bill_fee (
fee_id, bill_id, pay_bill_id, fee_type, sc_id, fee_level, amount, currency, round_mode, remark, fee_id, bill_id, pay_bill_id, fee_type, fee_name, sc_id, fee_level, amount, currency, round_mode, remark,
fee_source, source_id, is_deleted, create_time fee_source, source_id, is_deleted, create_time
) values ( ) values (
#{feeId}, #{billId}, #{payBillId}, #{feeType}, #{scId}, #{feeLevel}, #{amount}, #{currency}, #{roundMode}, #{remark}, #{feeId}, #{billId}, #{payBillId}, #{feeType}, #{feeName}, #{scId}, #{feeLevel}, #{amount}, #{currency}, #{roundMode}, #{remark},
ifnull(#{feeSource}, 'CALC'), #{sourceId}, ifnull(#{isDeleted}, '0'), sysdate() ifnull(#{feeSource}, 'CALC'), #{sourceId}, ifnull(#{isDeleted}, '0'), sysdate()
) )
</insert> </insert>
<insert id="insertBatch" parameterType="java.util.List"> <insert id="insertBatch" parameterType="java.util.List">
insert into prc_pay_bill_fee ( insert into prc_pay_bill_fee (
fee_id, bill_id, pay_bill_id, fee_type, sc_id, fee_level, amount, currency, round_mode, remark, fee_id, bill_id, pay_bill_id, fee_type, fee_name, sc_id, fee_level, amount, currency, round_mode, remark,
fee_source, source_id, is_deleted, create_time fee_source, source_id, is_deleted, create_time
) values ) values
<foreach collection="list" item="item" separator=","> <foreach collection="list" item="item" separator=",">
(#{item.feeId}, #{item.billId}, #{item.payBillId}, #{item.feeType}, #{item.scId}, #{item.feeLevel}, (#{item.feeId}, #{item.billId}, #{item.payBillId}, #{item.feeType}, #{item.feeName}, #{item.scId}, #{item.feeLevel},
#{item.amount}, #{item.currency}, #{item.roundMode}, #{item.remark}, ifnull(#{item.feeSource}, 'CALC'), #{item.amount}, #{item.currency}, #{item.roundMode}, #{item.remark}, ifnull(#{item.feeSource}, 'CALC'),
#{item.sourceId}, ifnull(#{item.isDeleted}, '0'), sysdate()) #{item.sourceId}, ifnull(#{item.isDeleted}, '0'), sysdate())
</foreach> </foreach>
@@ -0,0 +1,36 @@
-- `prc_pay_bill_fee_log` 增加变更前费用项
ALTER TABLE `bms`.`prc_pay_bill_fee_log` ADD COLUMN `before_fee_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '变更前费用项' AFTER `currency`;
-- `prc_pay_bill_fee_log` 增加变更前金额
ALTER TABLE `bms`.`prc_pay_bill_fee_log` ADD COLUMN `before_amount` decimal(12, 2) NULL DEFAULT NULL COMMENT '变更前金额' AFTER `before_fee_name`;
-- `prc_pay_bill_fee_log` 增加变更前币种
ALTER TABLE `bms`.`prc_pay_bill_fee_log` ADD COLUMN `before_currency` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '变更前币种' AFTER `before_amount`;
-- `prc_pay_bill_fee_log` 增加变更后费用项
ALTER TABLE `bms`.`prc_pay_bill_fee_log` ADD COLUMN `after_fee_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '变更后费用项' AFTER `before_currency`;
-- `prc_pay_bill_fee_log` 增加变更后金额
ALTER TABLE `bms`.`prc_pay_bill_fee_log` ADD COLUMN `after_amount` decimal(12, 2) NULL DEFAULT NULL COMMENT '变更后金额' AFTER `after_fee_name`;
-- `prc_pay_bill_fee_log` 增加变更后币种
ALTER TABLE `bms`.`prc_pay_bill_fee_log` ADD COLUMN `after_currency` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '变更后币种' AFTER `after_amount`;
-- 应付列表增加费用日志按钮
INSERT INTO `bms`.`sys_menu` (`menu_id`, `menu_name`, `parent_id`, `order_num`, `path`, `component`, `is_frame`, `is_cache`, `menu_type`, `visible`, `status`, `perms`, `icon`, `create_by`, `create_time`)
SELECT 2676, '费用日志', 2665, 6, '', '', 1, 0, 'F', '0', '0', 'price:payOrder:log', '#', 'admin', sysdate()
FROM DUAL
WHERE NOT EXISTS (SELECT 1 FROM `bms`.`sys_menu` WHERE `menu_id` = 2676 OR `perms` = 'price:payOrder:log');
-- 管理员拥有费用日志按钮
INSERT INTO `bms`.`sys_role_menu` (`role_id`, `menu_id`)
SELECT 1, 2676
FROM DUAL
WHERE NOT EXISTS (SELECT 1 FROM `bms`.`sys_role_menu` WHERE `role_id` = 1 AND `menu_id` = 2676);
-- 能看应付列表的角色同时拥有费用日志按钮
INSERT INTO `bms`.`sys_role_menu` (`role_id`, `menu_id`)
SELECT DISTINCT rm.`role_id`, 2676
FROM `bms`.`sys_role_menu` rm
WHERE rm.`menu_id` = 2665
AND NOT EXISTS (SELECT 1 FROM `bms`.`sys_role_menu` x WHERE x.`role_id` = rm.`role_id` AND x.`menu_id` = 2676);
@@ -0,0 +1,2 @@
-- `prc_pay_bill_fee_log` 增加备注
ALTER TABLE `bms`.`prc_pay_bill_fee_log` ADD COLUMN `remark` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '备注' AFTER `operation_type`;
+66 -1
View File
@@ -15,6 +15,14 @@ export function listPayOrderFees(billId) {
}) })
} }
export function listPayOrderFeeLogs(billId, query) {
return request({
url: '/price/payOrder/' + billId + '/feeLogs',
method: 'get',
params: query
})
}
export function addPayOrderFee(billId, data) { export function addPayOrderFee(billId, data) {
return request({ return request({
url: '/price/payOrder/' + billId + '/fees', url: '/price/payOrder/' + billId + '/fees',
@@ -30,10 +38,67 @@ export function removePayOrderFee(feeId) {
}) })
} }
export function recalcPayOrder(data) { export function submitPayOrderRecalc(data) {
return request({ return request({
url: '/price/payOrder/recalc', url: '/price/payOrder/recalc',
method: 'post', method: 'post',
data data
}) })
} }
export function getPayOrderRecalcTask(taskId) {
return request({
url: '/price/payOrder/recalc/task/' + taskId,
method: 'get'
})
}
export function cancelPayOrderRecalc(taskId) {
return request({
url: '/price/payOrder/recalc/task/' + taskId + '/cancel',
method: 'post'
})
}
const payOrderRecalcPolls = new Map()
/** 轮询应付重算进度,直到完成、取消或失败。同一任务只保留一轮轮询。 */
export async function pollPayOrderRecalc(taskId, onProgress) {
const id = String(taskId || '')
if (!id) throw new Error('没有拿到重算任务')
const prev = payOrderRecalcPolls.get(id)
if (prev) prev.aborted = true
const ctrl = { aborted: false }
payOrderRecalcPolls.set(id, ctrl)
const started = Date.now()
let lastSig = ''
try {
while (Date.now() - started < 30 * 60 * 1000) {
if (ctrl.aborted) {
const err = new Error('poll superseded')
err.superseded = true
throw err
}
const hidden = typeof document !== 'undefined' && document.visibilityState === 'hidden'
const res = await getPayOrderRecalcTask(id)
const task = res.data || {}
const status = String(task.status || '').toUpperCase()
const sig = [status, task.percent, task.successCount, task.failCount, task.total].join('|')
if (typeof onProgress === 'function' && sig !== lastSig) {
lastSig = sig
onProgress(task)
}
if (status === 'SUCCESS') return { task }
if (status === 'CANCELLED') return { task, cancelled: true }
if (status === 'FAIL') {
const err = new Error(task.message || '费用重算失败')
err.task = task
throw err
}
await new Promise(resolve => setTimeout(resolve, hidden ? 2500 : 1000))
}
throw new Error('费用重算进度查询超时,请稍后在列表查看结果')
} finally {
if (payOrderRecalcPolls.get(id) === ctrl) payOrderRecalcPolls.delete(id)
}
}
@@ -175,22 +175,24 @@
</template> </template>
</el-dialog> </el-dialog>
<el-dialog v-model="batchBindOpen" title="批量绑定应收/应付产品" width="520px" append-to-body @closed="onBatchBindClosed"> <el-dialog v-model="batchBindOpen" title="批量绑定应收/应付服务商渠道" width="560px" append-to-body @closed="onBatchBindClosed">
<el-form label-width="100px"> <el-form class="batch-bind-form" label-width="132px">
<el-form-item label="已选渠道"> <el-form-item label="已选渠道">
<span>{{ batchBindIds.length }} 个</span> <span class="batch-bind-count">{{ batchBindIds.length }} 个</span>
</el-form-item> </el-form-item>
<el-form-item label="应付产品"> <el-form-item label="应付服务商渠道">
<el-select v-model="batchApId" filterable clearable placeholder="可选,不选则不改应付绑定" style="width: 100%"> <el-select v-model="batchApId" class="batch-bind-select" filterable clearable placeholder="可选,不选则不改应付绑定">
<el-option v-for="item in payOptions" :key="'ap-' + item.productId" :label="payOptionLabel(item)" :value="item.productId" /> <el-option v-for="item in payOptions" :key="'ap-' + item.productId" :label="payOptionLabel(item)" :value="item.productId" />
</el-select> </el-select>
</el-form-item> </el-form-item>
<el-form-item label="应收产品"> <!--
<el-select v-model="batchArId" filterable clearable placeholder="可选,不选则不改应收绑定" style="width: 100%"> <el-form-item label="应收服务商渠道">
<el-select v-model="batchArId" class="batch-bind-select" filterable clearable placeholder="可选,不选则不改应收绑定">
<el-option v-for="item in arOptions" :key="'ar-' + item.productId" :label="payOptionLabel(item)" :value="item.productId" /> <el-option v-for="item in arOptions" :key="'ar-' + item.productId" :label="payOptionLabel(item)" :value="item.productId" />
</el-select> </el-select>
</el-form-item> </el-form-item>
<div class="pay-tip">至少选择一个产品;将覆盖已选渠道对应收付类型的绑定。</div> -->
<div class="batch-bind-tip">至少选择一个服务商渠道;将覆盖已选渠道对应收付类型的绑定。</div>
</el-form> </el-form>
<template #footer> <template #footer>
<el-button @click="batchBindOpen = false">取消</el-button> <el-button @click="batchBindOpen = false">取消</el-button>
@@ -231,18 +233,18 @@ const batchArId = ref()
const payTip = computed(() => { const payTip = computed(() => {
if (viewing.value) { if (viewing.value) {
if (payProduct.value?.versionNo) return `已绑定第 ${payProduct.value.versionNo} 版。` if (payProduct.value?.versionNo) return `已绑定第 ${payProduct.value.versionNo} 版。`
return payOriginId.value ? '已绑定应付产品。' : '未绑定应付产品。' return payOriginId.value ? '已绑定应付服务商渠道。' : '未绑定应付服务商渠道。'
} }
if (!form.value?.id) return '先保存渠道,再选择应付产品。渠道绑定的是产品编号,更新价格不会换编号。' if (!form.value?.id) return '先保存渠道,再选择应付服务商渠道。渠道绑定的是产品编号,更新价格不会换编号。'
if (payProduct.value?.versionNo) return `当前按有效期使用第 ${payProduct.value.versionNo} 版。历史订单按下单或计费时间取当时的版本。` if (payProduct.value?.versionNo) return `当前按有效期使用第 ${payProduct.value.versionNo} 版。历史订单按下单或计费时间取当时的版本。`
return '选择产品后即绑定,按应付 AP 保存。' return '选择产品后即绑定,按应付 AP 保存。'
}) })
const arTip = computed(() => { const arTip = computed(() => {
if (viewing.value) { if (viewing.value) {
if (arProduct.value?.versionNo) return `已绑定第 ${arProduct.value.versionNo} 版。` if (arProduct.value?.versionNo) return `已绑定第 ${arProduct.value.versionNo} 版。`
return arOriginId.value ? '已绑定应收产品。' : '未绑定应收产品。' return arOriginId.value ? '已绑定应收服务商渠道。' : '未绑定应收服务商渠道。'
} }
if (!form.value?.id) return '先保存渠道,再选择应收产品。渠道绑定的是产品编号,更新价格不会换编号。' if (!form.value?.id) return '先保存渠道,再选择应收服务商渠道。渠道绑定的是服务商渠道编号,更新价格不会换编号。'
if (arProduct.value?.versionNo) return `当前按有效期使用第 ${arProduct.value.versionNo} 版。历史订单按下单或计费时间取当时的版本。` if (arProduct.value?.versionNo) return `当前按有效期使用第 ${arProduct.value.versionNo} 版。历史订单按下单或计费时间取当时的版本。`
return '选择产品后即绑定,按应收 AR 保存。' return '选择产品后即绑定,按应收 AR 保存。'
}) })
@@ -533,4 +535,32 @@ function submitBatchBind() {
font-size: 12px; font-size: 12px;
line-height: 1.5; line-height: 1.5;
} }
.batch-bind-form :deep(.el-form-item) {
align-items: center;
margin-bottom: 16px;
}
.batch-bind-form :deep(.el-form-item__label) {
height: 32px;
line-height: 32px;
white-space: nowrap;
align-items: center;
}
.batch-bind-form :deep(.el-form-item__content) {
line-height: 32px;
}
.batch-bind-count {
display: inline-flex;
align-items: center;
height: 32px;
line-height: 32px;
}
.batch-bind-select {
width: 100%;
}
.batch-bind-tip {
margin: 0 0 4px 132px;
color: var(--el-text-color-secondary);
font-size: 12px;
line-height: 1.5;
}
</style> </style>
@@ -1,5 +1,18 @@
<template> <template>
<div class="app-container"> <div class="app-container pay-order-page">
<div v-if="recalcFloatVisible" class="retry-status-float">
<el-tooltip :content="recalcFloatTooltip" placement="bottom">
<el-button class="retry-status-button" type="primary" plain size="small" @click="openRecalcProgress">
<span class="retry-progress-ring" :style="{ '--retry-progress': recalcProgressDegree + 'deg' }" aria-hidden="true">
<span class="retry-progress-value">{{ recalcProgressText }}</span>
</span>
<span class="retry-status-text">
<strong>{{ recalcFloatTitle }}</strong>
<small>{{ recalcFloatSummary }}</small>
</span>
</el-button>
</el-tooltip>
</div>
<el-form :inline="true" :model="query" class="mb8"> <el-form :inline="true" :model="query" class="mb8">
<el-form-item label="订单号"> <el-form-item label="订单号">
<el-input v-model="query.orderNo" type="textarea" :rows="2" clearable placeholder="多个订单号可用逗号、空格或换行分隔" style="width: 280px" /> <el-input v-model="query.orderNo" type="textarea" :rows="2" clearable placeholder="多个订单号可用逗号、空格或换行分隔" style="width: 280px" />
@@ -17,7 +30,7 @@
</el-form> </el-form>
<el-row class="mb8"> <el-row class="mb8">
<el-button type="primary" plain icon="RefreshRight" v-hasPermi="['price:payOrder:recalc']" @click="openRecalc">费用重算</el-button> <el-button type="primary" plain icon="RefreshRight" :loading="recalcRunning" v-hasPermi="['price:payOrder:recalc']" @click="openRecalc">费用重算</el-button>
</el-row> </el-row>
<el-table v-loading="loading" :data="rows" border> <el-table v-loading="loading" :data="rows" border>
@@ -43,10 +56,17 @@
<template #default="{ row }">{{ row.payCalcMsg || '-' }}</template> <template #default="{ row }">{{ row.payCalcMsg || '-' }}</template>
</el-table-column> </el-table-column>
<el-table-column prop="bizDate" label="计费时间" width="170" align="center" /> <el-table-column prop="bizDate" label="计费时间" width="170" align="center" />
<el-table-column label="操作" width="140" align="center" fixed="right"> <el-table-column prop="updateBy" label="更新人" width="110" show-overflow-tooltip>
<template #default="{ row }">{{ row.updateBy || '-' }}</template>
</el-table-column>
<el-table-column prop="updateTime" label="更新时间" width="170" align="center">
<template #default="{ row }">{{ row.updateTime || '-' }}</template>
</el-table-column>
<el-table-column label="操作" width="190" align="center" fixed="right">
<template #default="{ row }"> <template #default="{ row }">
<el-button link type="primary" v-hasPermi="['price:payOrder:query']" @click="openDetail(row)">详情</el-button> <el-button link type="primary" v-hasPermi="['price:payOrder:query']" @click="openDetail(row)">详情</el-button>
<el-button link type="primary" v-hasPermi="['price:payOrder:fee']" @click="openFees(row)">费用</el-button> <el-button link type="primary" v-hasPermi="['price:payOrder:fee']" @click="openFees(row)">费用</el-button>
<el-button link type="primary" v-hasPermi="['price:payOrder:log']" @click="openLogs(row)">日志</el-button>
</template> </template>
</el-table-column> </el-table-column>
</el-table> </el-table>
@@ -61,43 +81,43 @@
<div class="fee-tools"> <div class="fee-tools">
<el-button v-hasPermi="['price:payOrder:feeAdd']" type="primary" plain size="small" @click="addFeeRow(section)">增加费用</el-button> <el-button v-hasPermi="['price:payOrder:feeAdd']" type="primary" plain size="small" @click="addFeeRow(section)">增加费用</el-button>
</div> </div>
<el-table :data="section.fees" border empty-text="无"> <el-table class="fee-table" :data="section.fees" border table-layout="fixed" empty-text="无">
<el-table-column label="费用项" min-width="180"> <el-table-column label="费用项" min-width="1" header-align="center" show-overflow-tooltip>
<template #default="{ row }"> <template #default="{ row }">
<el-select v-if="row.editing" v-model="row.pick" filterable allow-create default-first-option placeholder="选择或输入" style="width: 100%" @change="pickFee(row)"> <el-select v-if="row.editing" v-model="row.pick" filterable allow-create default-first-option placeholder="选择或输入" @change="pickFee(row)">
<el-option v-for="item in (bms_fee_type || [])" :key="item.value" :label="item.label" :value="item.value" /> <el-option v-for="item in (bms_fee_type || [])" :key="item.value" :label="item.label" :value="item.value" />
</el-select> </el-select>
<span v-else>{{ row.feeName }}</span> <span v-else>{{ row.feeName }}</span>
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="金额" width="140" align="right"> <el-table-column label="金额" min-width="1" header-align="center" align="right" show-overflow-tooltip>
<template #default="{ row }"> <template #default="{ row }">
<el-input-number v-if="row.editing" v-model="row.amount" :precision="2" :controls="false" style="width: 100%" /> <el-input-number v-if="row.editing" v-model="row.amount" :precision="2" :controls="false" />
<span v-else>{{ row.amount }}</span> <span v-else>{{ row.amount }}</span>
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="币种" width="110" align="center"> <el-table-column label="币种" min-width="1" header-align="center" align="center" show-overflow-tooltip>
<template #default="{ row }"> <template #default="{ row }">
<el-select v-if="row.editing" v-model="row.currency" filterable style="width: 100%"> <el-select v-if="row.editing" v-model="row.currency" filterable>
<el-option v-for="item in (bms_currency || [])" :key="item.value" :label="item.label" :value="item.value" /> <el-option v-for="item in (bms_currency || [])" :key="item.value" :label="item.label" :value="item.value" />
</el-select> </el-select>
<span v-else>{{ row.currency }}</span> <span v-else>{{ row.currency }}</span>
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="说明" min-width="180"> <el-table-column label="说明" min-width="1" header-align="center" show-overflow-tooltip>
<template #default="{ row }"> <template #default="{ row }">
<el-input v-if="row.editing" v-model="row.remark" maxlength="200" /> <el-input v-if="row.editing" v-model="row.remark" maxlength="200" />
<span v-else>{{ row.remark }}</span> <span v-else>{{ row.remark }}</span>
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="来源" width="100" align="center"> <el-table-column label="来源" min-width="1" header-align="center" align="center" show-overflow-tooltip>
<template #default="{ row }">{{ sourceText(row.feeSource) }}</template> <template #default="{ row }">{{ sourceText(row.feeSource) }}</template>
</el-table-column> </el-table-column>
<el-table-column prop="createBy" label="创建人" width="100" show-overflow-tooltip /> <el-table-column prop="createBy" label="创建人" min-width="1" header-align="center" show-overflow-tooltip />
<el-table-column prop="createTime" label="创建时间" width="160" /> <el-table-column prop="createTime" label="创建时间" min-width="1" header-align="center" show-overflow-tooltip />
<el-table-column prop="updateBy" label="更新人" width="100" show-overflow-tooltip /> <el-table-column prop="updateBy" label="更新人" min-width="1" header-align="center" show-overflow-tooltip />
<el-table-column prop="updateTime" label="更新时间" width="160" /> <el-table-column prop="updateTime" label="更新时间" min-width="1" header-align="center" show-overflow-tooltip />
<el-table-column label="操作" width="130" align="center" fixed="right"> <el-table-column label="操作" min-width="1" header-align="center" align="center" class-name="fee-op">
<template #default="{ row }"> <template #default="{ row }">
<el-button v-if="row.editing" link type="primary" @click="saveFeeRow(section, row)">保存</el-button> <el-button v-if="row.editing" link type="primary" @click="saveFeeRow(section, row)">保存</el-button>
<el-button v-if="row.editing" link type="danger" @click="removeFeeRow(section, row)">删除</el-button> <el-button v-if="row.editing" link type="danger" @click="removeFeeRow(section, row)">删除</el-button>
@@ -106,55 +126,124 @@
</el-table-column> </el-table-column>
</el-table> </el-table>
</section> </section>
<section class="fee-section"> </div>
<div class="fee-head">费用日志</div> </el-dialog>
<el-table :data="feeLogs" border empty-text="无" max-height="280">
<el-table-column prop="feeName" label="费用项" min-width="160" show-overflow-tooltip /> <el-dialog v-model="logOpen" :title="logTitle" width="980px" append-to-body>
<el-table-column prop="amount" label="金额" width="120" align="right" /> <el-table v-loading="logLoading" class="fee-log-table" :data="logRows" border empty-text="无">
<el-table-column prop="currency" label="币种" width="90" align="center" /> <el-table-column label="变更前" min-width="200" header-align="center">
<el-table-column label="操作类型" width="120" align="center"> <template #default="{ row }">
<div v-if="logLines(row, 'before').length" class="log-change">
<div v-for="(line, index) in logLines(row, 'before')" :key="index">{{ line }}</div>
</div>
<span v-else class="log-empty">空</span>
</template>
</el-table-column>
<el-table-column label="变更后" min-width="200" header-align="center">
<template #default="{ row }">
<div v-if="logLines(row, 'after').length" class="log-change">
<div v-for="(line, index) in logLines(row, 'after')" :key="index">{{ line }}</div>
</div>
<span v-else class="log-empty">空</span>
</template>
</el-table-column>
<el-table-column prop="remark" label="备注" min-width="180" header-align="center" show-overflow-tooltip>
<template #default="{ row }">{{ row.remark || '-' }}</template>
</el-table-column>
<el-table-column label="操作类型" width="120" header-align="center" align="center">
<template #default="{ row }"> <template #default="{ row }">
<dict-tag :options="bms_pay_fee_log_type" :value="row.operationType" /> <dict-tag :options="bms_pay_fee_log_type" :value="row.operationType" />
</template> </template>
</el-table-column> </el-table-column>
<el-table-column prop="createBy" label="操作人" width="120" show-overflow-tooltip /> <el-table-column prop="createBy" label="操作人" width="120" header-align="center" show-overflow-tooltip />
<el-table-column prop="createTime" label="操作时间" width="170" align="center" /> <el-table-column prop="createTime" label="操作时间" width="170" header-align="center" align="center" />
</el-table> </el-table>
</section> <pagination v-show="logTotal > 0" :total="logTotal" v-model:page="logQuery.pageNum" v-model:limit="logQuery.pageSize" @pagination="loadLogs" />
</div>
</el-dialog> </el-dialog>
<el-dialog v-model="recalcOpen" title="费用重算" width="720px" append-to-body @closed="resetRecalc"> <el-dialog v-model="recalcOpen" title="费用重算" width="720px" append-to-body :close-on-click-modal="false">
<el-form label-width="90px"> <el-form label-width="90px">
<el-form-item label="重算方式"> <el-form-item label="重算方式">
<el-radio-group v-model="recalcForm.sourceType"> <el-radio-group v-model="recalcForm.sourceType" :disabled="recalcSaving">
<el-radio value="ORDER">订单号</el-radio> <el-radio value="ORDER">订单号</el-radio>
<el-radio value="LADING">提单号</el-radio> <el-radio value="LADING">提单号</el-radio>
</el-radio-group> </el-radio-group>
</el-form-item> </el-form-item>
<el-form-item :label="recalcForm.sourceType === 'LADING' ? '提单号' : '订单号'"> <el-form-item :label="recalcForm.sourceType === 'LADING' ? '提单号' : '订单号'">
<el-input v-model="recalcForm.text" type="textarea" :rows="6" :placeholder="recalcPlaceholder" /> <el-input v-model="recalcForm.text" type="textarea" :rows="6" :disabled="recalcSaving" :placeholder="recalcPlaceholder" />
</el-form-item> </el-form-item>
</el-form> </el-form>
<div v-if="recalcResult" class="recalc-result">
<span>成功 {{ recalcResult.successCount }} 票,失败 {{ recalcResult.failCount }} 票</span>
<el-table :data="recalcFails" border size="small" max-height="240" empty-text="没有失败记录">
<el-table-column prop="orderNo" label="订单号" min-width="140" show-overflow-tooltip />
<el-table-column prop="ladingNo" label="提单号" min-width="140" show-overflow-tooltip />
<el-table-column prop="message" label="原因" min-width="220" show-overflow-tooltip />
</el-table>
</div>
<template #footer> <template #footer>
<el-button @click="recalcOpen = false">关闭</el-button> <el-button @click="recalcOpen = false">关闭</el-button>
<el-button type="primary" :loading="recalcSaving" @click="submitRecalc">确认</el-button> <el-button type="primary" :loading="recalcSaving" @click="submitRecalc">确认</el-button>
</template> </template>
</el-dialog> </el-dialog>
<el-dialog
v-model="recalcProgressVisible"
:title="recalcDialogTitle"
width="560px"
append-to-body
:close-on-click-modal="false"
:close-on-press-escape="true"
:show-close="true"
>
<el-progress
:percentage="recalcProgressPercent"
:status="recalcProgressStatus"
:stroke-width="14"
striped
:striped-flow="recalcRunning"
/>
<div class="rebill-progress__msg">{{ recalcProgressMessage }}</div>
<div v-if="!recalcRunning && recalcFinished" class="rebill-result-stats">
<div class="rebill-result-stats__item">
<span class="rebill-result-stats__label">总数</span>
<strong>{{ recalcProgressTotal }}</strong>
</div>
<div class="rebill-result-stats__item is-success">
<span class="rebill-result-stats__label">成功</span>
<strong>{{ recalcProgressSuccess }}</strong>
</div>
<div class="rebill-result-stats__item is-fail">
<span class="rebill-result-stats__label">失败</span>
<strong>{{ recalcProgressFail }}</strong>
</div>
</div>
<div v-else class="rebill-progress__text">
总数 {{ recalcProgressTotal }}
/ 成功 {{ recalcProgressSuccess }}
/ 失败 {{ recalcProgressFail }}
</div>
<el-table v-if="!recalcRunning && recalcFails.length" :data="recalcFails" border size="small" max-height="220" class="rebill-progress__error" empty-text="没有失败记录">
<el-table-column prop="orderNo" label="订单号" min-width="140" show-overflow-tooltip />
<el-table-column prop="ladingNo" label="提单号" min-width="120" show-overflow-tooltip />
<el-table-column prop="message" label="原因" min-width="180" show-overflow-tooltip />
</el-table>
<p v-if="recalcRunning" class="rebill-progress__hint">重算在后台进行,可收起弹窗继续操作;请勿关闭或刷新本页</p>
<template #footer>
<el-button v-if="recalcRunning" @click="recalcProgressVisible = false">收起</el-button>
<el-button
v-if="recalcRunning"
v-hasPermi="['price:payOrder:recalc']"
type="danger"
plain
:loading="recalcCancelLoading"
@click="handleCancelRecalc"
>取消重算</el-button>
<template v-else>
<el-button v-if="recalcFails.length" v-hasPermi="['price:payOrder:recalc']" type="warning" plain @click="viewRecalcFailed">查看失败订单</el-button>
<el-button type="primary" @click="recalcProgressVisible = false">关闭</el-button>
</template>
</template>
</el-dialog>
</div> </div>
</template> </template>
<script setup name="PayOrderList"> <script setup name="PayOrderList">
import { getBill } from '@/api/price/billing' import { getBill } from '@/api/price/billing'
import { addPayOrderFee, listPayOrder, listPayOrderFees, recalcPayOrder, removePayOrderFee } from '@/api/price/payOrder' import { addPayOrderFee, cancelPayOrderRecalc, getPayOrderRecalcTask, listPayOrder, listPayOrderFeeLogs, listPayOrderFees, pollPayOrderRecalc, removePayOrderFee, submitPayOrderRecalc } from '@/api/price/payOrder'
import { ElMessage, ElMessageBox } from 'element-plus'
import BillDetail from '../components/BillDetail.vue' import BillDetail from '../components/BillDetail.vue'
const { proxy } = getCurrentInstance() const { proxy } = getCurrentInstance()
@@ -174,15 +263,55 @@ const feeLoading = ref(false)
const feeTitle = ref('应付费用') const feeTitle = ref('应付费用')
const feeBillId = ref('') const feeBillId = ref('')
const sections = ref([]) const sections = ref([])
const feeLogs = ref([]) const logOpen = ref(false)
const logLoading = ref(false)
const logTitle = ref('费用日志')
const logBillId = ref('')
const logRows = ref([])
const logTotal = ref(0)
const logQuery = reactive({ pageNum: 1, pageSize: 10 })
const recalcOpen = ref(false) const recalcOpen = ref(false)
const recalcSaving = ref(false) const recalcSaving = ref(false)
const recalcForm = reactive({ sourceType: 'ORDER', text: '' }) const recalcForm = reactive({ sourceType: 'ORDER', text: '' })
const recalcPlaceholder = computed(() => recalcForm.sourceType === 'LADING' const recalcPlaceholder = computed(() => recalcForm.sourceType === 'LADING'
? '多个提单号可用逗号、空格或换行分隔,一次最多10个' ? '多个提单号可用逗号、空格或换行分隔,一次最多10个'
: '多个订单号可用逗号、空格或换行分隔,一次最多500个') : '多个订单号可用逗号、空格或换行分隔,一次最多500个')
const recalcResult = ref(null) const recalcRunning = ref(false)
const recalcFails = computed(() => (recalcResult.value?.lines || []).filter(line => !line.success)) const recalcFinished = ref(false)
const recalcProgressVisible = ref(false)
const recalcProgressPercent = ref(0)
const recalcProgressMessage = ref('')
const recalcProgressStatus = ref(undefined)
const recalcProgressTotal = ref(0)
const recalcProgressSuccess = ref(0)
const recalcProgressFail = ref(0)
const recalcLines = ref([])
const recalcTaskId = ref('')
const recalcCancelLoading = ref(false)
let recalcFloatHideTimer = null
const RECALC_TASK_STORAGE_KEY = 'price:payOrder:recalcTaskId'
const recalcFails = computed(() => (recalcLines.value || []).filter(line => line && line.finished && !line.success))
const recalcFloatVisible = computed(() => recalcRunning.value || recalcFinished.value)
const recalcProgressDegree = computed(() => Math.round(((recalcProgressPercent.value || 0) / 100) * 360))
const recalcProgressText = computed(() => (recalcProgressPercent.value || 0) + '%')
const recalcDialogTitle = computed(() => {
if (recalcRunning.value) return '费用重算进行中'
if (recalcFinished.value) return '费用重算完成'
return '费用重算'
})
const recalcFloatTitle = computed(() => {
if (recalcRunning.value) return '费用重算中'
if (recalcProgressStatus.value === 'exception') return '费用重算失败'
if (recalcProgressStatus.value === 'warning' && String(recalcProgressMessage.value || '').includes('已取消')) return '费用重算已取消'
if (recalcFinished.value) return '费用重算完成'
return '费用重算'
})
const recalcFloatSummary = computed(() =>
'成功 ' + (recalcProgressSuccess.value || 0) +
' / 失败 ' + (recalcProgressFail.value || 0) +
' / 总数 ' + (recalcProgressTotal.value || 0)
)
const recalcFloatTooltip = computed(() => recalcProgressMessage.value || '点击查看详情')
const sources = { const sources = {
CALC: '尾程计算', CALC: '尾程计算',
@@ -194,6 +323,38 @@ function sourceText(value) {
return sources[value] || value || '-' return sources[value] || value || '-'
} }
function logLines(row, side) {
const name = row?.[side + 'FeeName']
const amount = row?.[side + 'Amount']
const currency = row?.[side + 'Currency']
const blank = (name == null || name === '') && (amount == null || amount === '') && (currency == null || currency === '')
if (blank) {
return []
}
return [
'费用项:' + (name || '空'),
'金额:' + (amount == null || amount === '' ? '空' : amount),
'币种:' + (currency || '空')
]
}
function loadLogPage(billId, query, rows, total, loading) {
if (!billId) {
rows.value = []
total.value = 0
return
}
loading.value = true
listPayOrderFeeLogs(billId, { pageNum: query.pageNum, pageSize: query.pageSize }).then(res => {
rows.value = res.rows || []
total.value = res.total || 0
}).catch(() => {
proxy.$modal.msgError('费用日志加载失败')
}).finally(() => {
loading.value = false
})
}
function search() { function search() {
query.pageNum = 1 query.pageNum = 1
loadList() loadList()
@@ -231,11 +392,23 @@ function openFees(row) {
feeTitle.value = (row.orderNo || '订单') + '的应付费用' feeTitle.value = (row.orderNo || '订单') + '的应付费用'
feeBillId.value = row.billId feeBillId.value = row.billId
sections.value = [] sections.value = []
feeLogs.value = []
feeOpen.value = true feeOpen.value = true
loadFees() loadFees()
} }
function openLogs(row) {
logTitle.value = (row.orderNo || '订单') + '的费用日志'
logBillId.value = row.billId
logQuery.pageNum = 1
logRows.value = []
logOpen.value = true
loadLogs()
}
function loadLogs() {
loadLogPage(logBillId.value, logQuery, logRows, logTotal, logLoading)
}
function loadFees() { function loadFees() {
if (!feeBillId.value) { if (!feeBillId.value) {
return return
@@ -243,7 +416,6 @@ function loadFees() {
feeLoading.value = true feeLoading.value = true
listPayOrderFees(feeBillId.value).then(res => { listPayOrderFees(feeBillId.value).then(res => {
sections.value = res.data?.sections || [] sections.value = res.data?.sections || []
feeLogs.value = res.data?.logs || []
}).catch(() => { }).catch(() => {
proxy.$modal.msgError('费用加载失败') proxy.$modal.msgError('费用加载失败')
}).finally(() => { }).finally(() => {
@@ -325,30 +497,273 @@ function removeFeeRow(section, row) {
}) })
} }
function saveRecalcTaskId(taskId) {
recalcTaskId.value = taskId ? String(taskId) : ''
try {
if (recalcTaskId.value) sessionStorage.setItem(RECALC_TASK_STORAGE_KEY, recalcTaskId.value)
else sessionStorage.removeItem(RECALC_TASK_STORAGE_KEY)
} catch (e) { /* 刷新后恢复不了进度,不影响重算本身 */ }
}
function clearRecalcTaskId() {
saveRecalcTaskId('')
}
function readStoredRecalcTaskId() {
try {
return String(sessionStorage.getItem(RECALC_TASK_STORAGE_KEY) || '').trim()
} catch (e) {
return ''
}
}
function openRecalcProgress() {
recalcProgressVisible.value = true
}
function scheduleHideRecalcFloat() {
if (recalcFloatHideTimer) {
clearTimeout(recalcFloatHideTimer)
recalcFloatHideTimer = null
}
recalcFloatHideTimer = window.setTimeout(() => {
if (!recalcRunning.value && recalcFinished.value) recalcFinished.value = false
recalcFloatHideTimer = null
}, 8000)
}
function applyRecalcProgress(task) {
const total = Number(task.total) || 0
const success = Number(task.successCount) || 0
const fail = Number(task.failCount) || 0
recalcProgressPercent.value = Math.min(100, Number(task.percent) || 0)
recalcProgressTotal.value = total
recalcProgressSuccess.value = success
recalcProgressFail.value = fail
recalcLines.value = Array.isArray(task.lines) ? task.lines : []
const status = String(task.status || '').toUpperCase()
if (status === 'PENDING') {
recalcProgressMessage.value = '排队中…'
} else if (status === 'RUNNING' && String(task.message || '').includes('取消')) {
recalcProgressMessage.value = '正在取消,等待当前订单结束… ' + (success + fail) + '/' + total
} else if (status === 'RUNNING') {
recalcProgressMessage.value = '正在重算 ' + (success + fail) + '/' + total + (fail ? ('(失败 ' + fail + ')') : '')
}
}
function finishRecalcFromTask(task, cancelled) {
const success = Number(task && task.successCount) || 0
const fail = Number(task && task.failCount) || 0
const total = Number(task && task.total) || recalcProgressTotal.value || 0
recalcProgressPercent.value = Math.min(100, Number(task && task.percent) || 100)
recalcProgressStatus.value = cancelled ? 'warning' : (fail > 0 ? 'warning' : 'success')
recalcProgressTotal.value = total
recalcProgressSuccess.value = success
recalcProgressFail.value = fail
recalcLines.value = task && Array.isArray(task.lines) ? task.lines : recalcLines.value
if (cancelled) {
recalcProgressMessage.value = '费用重算已取消:成功 ' + success + ' / 失败 ' + fail + ' / 总数 ' + total
} else if (fail > 0) {
recalcProgressMessage.value = '费用重算完成(含失败):成功 ' + success + ' / 失败 ' + fail + ' / 总数 ' + total
} else {
recalcProgressMessage.value = '费用重算完成:成功 ' + success + ' / 失败 ' + fail + ' / 总数 ' + total
}
recalcFinished.value = true
clearRecalcTaskId()
loadList()
recalcProgressVisible.value = true
if (cancelled) ElMessage.warning(recalcProgressMessage.value)
else if (fail > 0) ElMessage.warning(recalcProgressMessage.value)
else ElMessage.success(recalcProgressMessage.value)
scheduleHideRecalcFloat()
}
async function resumeRecalcTask(taskId) {
if (!taskId || recalcRunning.value) return
recalcRunning.value = true
recalcFinished.value = false
recalcCancelLoading.value = false
saveRecalcTaskId(taskId)
recalcProgressVisible.value = false
recalcProgressPercent.value = 0
recalcProgressStatus.value = undefined
recalcProgressMessage.value = '恢复进度中…'
recalcProgressTotal.value = 0
recalcProgressSuccess.value = 0
recalcProgressFail.value = 0
recalcLines.value = []
let superseded = false
try {
const result = await pollPayOrderRecalc(taskId, applyRecalcProgress)
finishRecalcFromTask(result && result.task, !!(result && result.cancelled))
} catch (e) {
if (e && e.superseded) {
superseded = true
return
}
failRecalc(e)
} finally {
if (!superseded) recalcRunning.value = false
}
}
function failRecalc(e) {
const task = e && e.task
recalcProgressStatus.value = 'exception'
recalcProgressMessage.value = (e && e.message) || '费用重算失败'
recalcFinished.value = true
if (task) {
recalcProgressPercent.value = Math.min(100, Number(task.percent) || 100)
recalcProgressTotal.value = Number(task.total) || 0
recalcProgressSuccess.value = Number(task.successCount) || 0
recalcProgressFail.value = Number(task.failCount) || 0
recalcLines.value = Array.isArray(task.lines) ? task.lines : []
loadList()
}
clearRecalcTaskId()
recalcProgressVisible.value = true
scheduleHideRecalcFloat()
}
async function tryRestoreRecalcProgress() {
const taskId = readStoredRecalcTaskId()
if (!taskId) return
try {
const res = await getPayOrderRecalcTask(taskId)
const task = (res && res.data) || {}
const status = String(task.status || '').toUpperCase()
if (status === 'PENDING' || status === 'RUNNING') {
applyRecalcProgress(task)
resumeRecalcTask(taskId)
return
}
clearRecalcTaskId()
} catch (e) {
clearRecalcTaskId()
}
}
async function runRecalc(payload) {
if (recalcRunning.value) {
openRecalcProgress()
return
}
if (recalcFloatHideTimer) {
clearTimeout(recalcFloatHideTimer)
recalcFloatHideTimer = null
}
recalcRunning.value = true
recalcFinished.value = false
recalcCancelLoading.value = false
clearRecalcTaskId()
recalcProgressVisible.value = true
recalcProgressPercent.value = 0
recalcProgressStatus.value = undefined
recalcProgressMessage.value = '任务提交中…'
recalcProgressTotal.value = 0
recalcProgressSuccess.value = 0
recalcProgressFail.value = 0
recalcLines.value = []
window.setTimeout(() => {
if (recalcRunning.value) recalcProgressVisible.value = false
}, 600)
let superseded = false
try {
const res = await submitPayOrderRecalc(payload)
const taskId = res.data && res.data.taskId
if (!taskId) throw new Error('没有拿到重算任务')
saveRecalcTaskId(taskId)
const result = await pollPayOrderRecalc(taskId, applyRecalcProgress)
finishRecalcFromTask(result && result.task, !!(result && result.cancelled))
} catch (e) {
if (e && e.superseded) {
superseded = true
return
}
failRecalc(e)
} finally {
if (!superseded) recalcRunning.value = false
}
}
function openRecalc() { function openRecalc() {
recalcResult.value = null if (recalcRunning.value) {
openRecalcProgress()
return
}
recalcForm.sourceType = 'ORDER'
recalcForm.text = ''
recalcOpen.value = true recalcOpen.value = true
} }
function resetRecalc() { async function submitRecalc() {
recalcForm.sourceType = 'ORDER' const text = String(recalcForm.text || '').trim()
recalcForm.text = '' if (!text) {
recalcResult.value = null
}
function submitRecalc() {
if (!recalcForm.text || !recalcForm.text.trim()) {
proxy.$modal.msgWarning(recalcForm.sourceType === 'LADING' ? '请填写提单号' : '请填写订单号') proxy.$modal.msgWarning(recalcForm.sourceType === 'LADING' ? '请填写提单号' : '请填写订单号')
return return
} }
recalcSaving.value = true if (recalcRunning.value) {
recalcPayOrder({ sourceType: recalcForm.sourceType, text: recalcForm.text }).then(res => { recalcOpen.value = false
recalcResult.value = res.data || { successCount: 0, failCount: 0, lines: [] } openRecalcProgress()
loadList() return
}).finally(() => {
recalcSaving.value = false
})
} }
const label = recalcForm.sourceType === 'LADING' ? '提单号' : '订单号'
const count = text.split(/[\s,,;;]+/).filter(Boolean).length
try {
await ElMessageBox.confirm('将按 ' + count + ' 个' + label + '重算应付费用,确认继续?', '二次确认', { type: 'warning' })
} catch (e) {
return
}
const payload = { sourceType: recalcForm.sourceType, text }
recalcOpen.value = false
runRecalc(payload)
}
async function handleCancelRecalc() {
if (!recalcRunning.value || !recalcTaskId.value || recalcCancelLoading.value) return
try {
await ElMessageBox.confirm('确认取消当前费用重算?已经算完的订单会保留,未开始的将停止。', '取消重算', { type: 'warning' })
} catch (e) {
return
}
recalcCancelLoading.value = true
try {
const res = await cancelPayOrderRecalc(recalcTaskId.value)
const task = (res && res.data) || {}
applyRecalcProgress(task)
recalcProgressMessage.value = '取消请求已提交,等待当前订单结束…'
ElMessage.success('已提交取消')
} catch (e) {
/* 全局拦截器会提示 */
} finally {
recalcCancelLoading.value = false
}
}
function viewRecalcFailed() {
recalcProgressVisible.value = false
const orderNos = [...new Set(recalcFails.value.map(item => item.orderNo).filter(Boolean))]
const ladingNos = [...new Set(recalcFails.value.map(item => item.ladingNo).filter(Boolean))]
if (orderNos.length) {
query.orderNo = orderNos.join('\n')
query.ladingNo = ''
} else if (ladingNos.length) {
query.orderNo = ''
query.ladingNo = ladingNos.join(',')
}
search()
}
onMounted(() => {
tryRestoreRecalcProgress()
})
onBeforeUnmount(() => {
if (recalcFloatHideTimer) {
clearTimeout(recalcFloatHideTimer)
recalcFloatHideTimer = null
}
})
loadList() loadList()
</script> </script>
@@ -356,6 +771,26 @@ loadList()
<style scoped> <style scoped>
.fee-board { max-height: 68vh; overflow: auto; } .fee-board { max-height: 68vh; overflow: auto; }
.fee-section { margin-bottom: 16px; } .fee-section { margin-bottom: 16px; }
.fee-table :deep(.cell) {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.fee-table :deep(.el-table__header .cell) {
text-align: center;
}
.fee-log-table :deep(.el-table__header .cell) {
text-align: center;
}
.fee-table :deep(.el-select),
.fee-table :deep(.el-input),
.fee-table :deep(.el-input-number) {
width: 100%;
}
.fee-table :deep(.fee-op .cell) {
overflow: visible;
text-overflow: clip;
}
.fee-head { .fee-head {
margin-bottom: 8px; margin-bottom: 8px;
padding: 8px 12px; padding: 8px 12px;
@@ -366,6 +801,34 @@ loadList()
border: 1px solid var(--el-border-color); border: 1px solid var(--el-border-color);
} }
.fee-tools { margin-bottom: 8px; text-align: right; } .fee-tools { margin-bottom: 8px; text-align: right; }
.recalc-result { margin-top: 8px; } .log-change { line-height: 1.6; }
.recalc-result > span { display: block; margin-bottom: 8px; } .log-empty { color: var(--el-text-color-secondary); }
.rebill-progress__msg { margin-top: 12px; color: var(--el-text-color-regular); }
.rebill-result-stats { display: flex; gap: 12px; margin-top: 14px; }
.rebill-result-stats__item { flex: 1; padding: 10px 12px; border-radius: 8px; background: var(--el-fill-color-light); text-align: center; }
.rebill-result-stats__item.is-success { background: var(--el-color-success-light-9); }
.rebill-result-stats__item.is-fail { background: var(--el-color-warning-light-9); }
.rebill-result-stats__label { display: block; font-size: 12px; color: var(--el-text-color-secondary); margin-bottom: 4px; }
.rebill-result-stats__item strong { font-size: 20px; line-height: 1.2; color: var(--el-text-color-primary); }
.rebill-progress__text { margin-top: 8px; font-size: 13px; color: var(--el-text-color-secondary); }
.rebill-progress__hint { margin-top: 12px; font-size: 12px; color: var(--el-color-warning); }
.rebill-progress__error { margin-top: 12px; }
.pay-order-page .retry-status-float { position: fixed; top: 92px; right: 24px; z-index: 3001; }
.pay-order-page .retry-status-button { display: inline-flex; align-items: center; gap: 10px; min-width: 200px; min-height: 68px; padding: 6px 16px 6px 7px; border-radius: 36px; }
.pay-order-page .retry-progress-ring {
position: relative;
display: inline-flex;
align-items: center;
justify-content: center;
flex: 0 0 54px;
width: 54px;
height: 54px;
border-radius: 50%;
background: conic-gradient(var(--el-color-primary) 0deg var(--retry-progress, 45deg), var(--el-color-primary-light-8) var(--retry-progress, 45deg) 360deg);
}
.pay-order-page .retry-progress-ring::after { position: absolute; inset: 5px; content: ''; border-radius: 50%; background: var(--el-bg-color); }
.pay-order-page .retry-progress-value { position: relative; z-index: 1; color: var(--el-color-primary); font-size: 12px; font-weight: 600; line-height: 1; }
.pay-order-page .retry-status-text { display: flex; flex-direction: column; align-items: flex-start; gap: 3px; line-height: 1.2; white-space: nowrap; }
.pay-order-page .retry-status-text strong { font-size: 14px; font-weight: 600; }
.pay-order-page .retry-status-text small { color: var(--el-text-color-secondary); font-size: 11px; }
</style> </style>