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

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
@@ -15,7 +15,4 @@ public class PayOrderFeeBoard
private String ladingNo;
private List<PayOrderFeeSection> sections = new ArrayList<>();
/** 这票订单的应付费用日志,新的在前 */
private List<PrcPayBillFeeLog> logs = new ArrayList<>();
}
@@ -6,10 +6,15 @@ import lombok.Data;
@Data
public class PayOrderRecalcLine
{
private String billId;
private String orderNo;
private String ladingNo;
/** 这一条是否已经处理完 */
private boolean finished;
/** 这一票是否已经生成应付费用 */
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 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;
}
@@ -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 */
@@ -61,4 +62,20 @@ public class PrcPayBillFee implements Serializable
@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;
}
@@ -25,9 +25,30 @@ public class PrcPayBillFeeLog implements Serializable
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;
@@ -1,12 +1,14 @@
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.PayOrderRecalcResult;
import com.bms.price.domain.PayOrderRecalcTask;
import com.bms.price.domain.PayOrderRow;
import com.bms.price.domain.PrcPayBillFeeLog;
/** 应付列表。 */
public interface IPayOrderListService
@@ -32,12 +34,42 @@ public interface IPayOrderListService
void removeFee(String feeId);
/**
* 按订单号或提单号批量重算尾程应付。一票失败不影响其他订单。
* 成功时应付主表记计费成功,应付总额按全部未删除明细重算。
* 失败时记计费失败和原因。已经进入应付账单的费用不覆盖。
* 提交应付费用重算。订单先放进 Redis,后台逐票计算,每票更新进度。
*
* @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.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;
@@ -140,7 +141,15 @@ public class PayBillFeeLogService
try
{
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)
{
@@ -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)
{
if (bucket == null || bucket.isEmpty())
@@ -193,7 +293,28 @@ public class PayBillFeeLogService
row.setFeeName(cut(nameOf(fee), 100));
row.setAmount(fee.getAmount());
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.setCreateBy(operator);
rows.add(row);
@@ -208,6 +329,10 @@ public class PayBillFeeLogService
{
return name;
}
if ("BASIC_FREIGHT".equals(fee.getFeeType()))
{
return "基础运费";
}
String type = fee.getFeeType() == null ? "" : fee.getFeeType().trim();
return type.isEmpty() ? "费用" : type;
}
@@ -168,6 +168,7 @@ public class PayOrderCostServiceImpl implements IPayOrderCostService
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;
}
@@ -654,7 +655,19 @@ public class PayOrderCostServiceImpl implements IPayOrderCostService
*/
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());
List<PrcPayBillFee> rows = new java.util.ArrayList<>();
long fallback = 1L;
@@ -666,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)
{
@@ -677,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())
@@ -687,31 +707,70 @@ public class PayOrderCostServiceImpl implements IPayOrderCostService
{
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);
}
/** 这票订单上还有没删除的计算费用。有则本次落库是重算,没有则是首次生成。 */
private boolean hasCalcFee(Long billId)
/** 计算费用,空来源按计算费用处理。 */
private static boolean calcFee(PrcPayBillFee fee)
{
List<PrcPayBillFee> current = payBillFeeMapper.selectByBillId(billId);
if (current == null)
if (fee == null)
{
return false;
}
for (PrcPayBillFee fee : current)
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())
{
if (fee == null)
{
continue;
}
String source = fee.getFeeSource();
if (source == null || source.isBlank() || "CALC".equals(source))
{
return true;
}
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。 */
@@ -9,11 +9,14 @@ 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;
@@ -22,7 +25,7 @@ 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.PayOrderRecalcResult;
import com.bms.price.domain.PayOrderRecalcTask;
import com.bms.price.domain.PayOrderRow;
import com.bms.price.domain.PrcPayBillFee;
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.IPayOrderListService;
import com.bms.price.service.IPrcPayBillFeeService;
import com.bms.price.task.PayOrderRecalcAsyncRunner;
@Service
public class PayOrderListServiceImpl implements IPayOrderListService
@@ -69,6 +73,10 @@ public class PayOrderListServiceImpl implements IPayOrderListService
@Autowired
private PayBillFeeLogService payBillFeeLogService;
@Autowired
@Lazy
private PayOrderRecalcAsyncRunner payOrderRecalcAsyncRunner;
@Override
public List<PayOrderRow> list(PayOrderQuery query)
{
@@ -92,13 +100,13 @@ public class PayOrderListServiceImpl implements IPayOrderListService
}
/**
* 按订单号或提单号逐票重算尾程应付。找不到的单号记失败,已经出账的费用不覆盖。
* 查出订单后放进 Redis,马上返回任务号。逐票计算在后台进行。
*
* @param command 重算方式和单号原文
* @return 成功数、失败数和明细
* @return 任务号
*/
@Override
public PayOrderRecalcResult recalc(PayOrderRecalcCommand command)
public String submitRecalc(PayOrderRecalcCommand command)
{
if (command == null || command.getSourceType() == null || command.getSourceType().isBlank())
{
@@ -133,92 +141,114 @@ public class PayOrderListServiceImpl implements IPayOrderListService
{
throw new ServiceException("一次最多重算" + MAX_ORDER_NOS + "票订单");
}
PayOrderRecalcResult result = new PayOrderRecalcResult();
List<PrcPayBillFeeLog> feeLogs = new ArrayList<>();
PayOrderRecalcTask task = new PayOrderRecalcTask();
task.setTaskId(IdUtils.fastSimpleUUID());
task.setStatus(PayOrderRecalcTask.PENDING);
task.setMessage("排队中");
LinkedHashSet<String> 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
{
for (PayOrderRow order : found)
if (payBillFeeMapper.countSettledCalc(billId) > 0)
{
if (order == null || order.getBillId() == null || order.getBillId().isBlank())
{
continue;
}
hit.add(byOrder ? order.getOrderNo() : order.getLadingNo());
PayOrderRecalcLine line = new PayOrderRecalcLine();
line.setOrderNo(order.getOrderNo());
line.setLadingNo(order.getLadingNo());
if (payBillFeeMapper.countSettledCalc(Long.valueOf(order.getBillId().trim())) > 0)
{
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);
throw new ServiceException("费用已进入应付账单,未重算");
}
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.setSuccess(false);
result.getLines().add(line);
result.setFailCount(result.getFailCount() + 1);
}
return result;
return payOrderCostService.generateIsolated(billId);
}
finally
catch (Exception ex)
{
if (!feeLogs.isEmpty())
String message = ex.getMessage() == null || ex.getMessage().isBlank() ? "应付费用生成失败" : ex.getMessage();
try
{
payBillFeeLogService.drain(feeLogs);
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
public PayOrderFeeBoard fees(String billId)
{
@@ -256,7 +286,6 @@ public class PayOrderListServiceImpl implements IPayOrderListService
board.setOrderNo(order.getOrderNo());
board.setLadingNo(order.getLadingNo());
board.setSections(List.copyOf(sections.values()));
board.setLogs(payBillFeeLogService.list(Long.valueOf(order.getBillId().trim())));
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,
b.pay_calc_status as payCalcStatus,
b.pay_calc_msg as payCalcMsg,
b.update_by as updateBy,
b.update_time as updateTime,
p.biz_date as bizDate
from prc_order_bill p
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="amount" column="amount" />
<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="remark" column="remark" />
<result property="createBy" column="create_by" />
<result property="createTime" column="create_time" />
</resultMap>
<insert id="insertBatch">
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
<foreach collection="list" item="item" separator=",">
(#{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>
</insert>
<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
where bill_id = #{billId}
order by log_id desc
@@ -28,10 +28,11 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<sql id="feeItemName">
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 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
else f.fee_type
end
@@ -40,7 +41,8 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<sql id="feeItemJoin">
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 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
</sql>
@@ -89,21 +91,21 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<insert id="insertPrcPayBillFee" parameterType="PrcPayBillFee">
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
) 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()
)
</insert>
<insert id="insertBatch" parameterType="java.util.List">
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
) values
<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.sourceId}, ifnull(#{item.isDeleted}, '0'), sysdate())
</foreach>