fix(agent): 订单工具取消时延后关单并复核支付状态

关单有外部副作用,原实现放在取消分支里,参数校验失败也会先关单;
且取消已收款订单时用的是关单前的旧支付状态。改为全部确定性校验
通过后再关单,关单发现已付款时以库中最新状态复核金额与实收输入,
并把正式取消收敛到退款中。
This commit is contained in:
lik
2026-11-08 12:07:47 +08:00
parent 503c4b52e9
commit fc993a7761
@@ -59,10 +59,7 @@ const escortRecordSetTool = tool(
update.cancelStatus = cancelStatus;
if (cancelStatus === "requested") update.cancelRequestedAt = new Date();
if (cancelStatus === "cancelled") update.cancelledAt = new Date();
// 与接口层一致:先关闭在途预付单,否则取消后旧 prepay 仍可完成支付
await HandlerPayment.closeOpenPayRecords(orderId);
const fresh = await DBModel.EscortRecord.findById(orderId);
effectivePay = fresh?.payment || effectivePay;
// 关单有外部副作用,延后到全部入参校验通过之后执行。
}
if (status !== undefined && status !== record.status) {
@@ -175,6 +172,30 @@ const escortRecordSetTool = tool(
update["payment.status"] = "refunding";
}
// 所有确定性校验通过后才关闭在途预付单。关单期间若支付成功,
// 以刷新后的支付状态复核金额/实收输入,并把正式取消收敛到退款中。
if (update.cancelStatus) {
await HandlerPayment.closeOpenPayRecords(orderId);
const fresh = await DBModel.EscortRecord.findById(orderId);
effectivePay = fresh?.payment || effectivePay;
const refreshedPayStatus = effectivePay.status || "unpaid";
if (["partial", "paid", "refunding", "refunded"].includes(refreshedPayStatus)) {
const invalidStatus = payment?.status !== undefined
&& payment.status !== refreshedPayStatus
&& !(update.cancelStatus === "cancelled" && payment.status === "refunding");
const invalidPaidFee = payment?.paidFee !== undefined
&& Number(payment.paidFee) !== (Number(effectivePay.paidFee) || 0);
const invalidTotalFee = payment?.totalFee !== undefined
&& Number(payment.totalFee) !== (Number(effectivePay.totalFee) || 0);
if (invalidStatus || invalidPaidFee || invalidTotalFee) {
return { success: false, error: "Record payment state changed while updating. Re-query and retry." };
}
}
if (update.cancelStatus === "cancelled" && ["partial", "paid"].includes(refreshedPayStatus)) {
update["payment.status"] = "refunding";
}
}
update["meta.updatetime"] = Date.now();
// 以读取时的状态作为更新条件,避免并发下跳过中间状态;同时排除已软删除的订单