diff --git a/agent/infra/tools/db/admin/escort_record_set.js b/agent/infra/tools/db/admin/escort_record_set.js index 5124595..e250926 100644 --- a/agent/infra/tools/db/admin/escort_record_set.js +++ b/agent/infra/tools/db/admin/escort_record_set.js @@ -8,6 +8,8 @@ import { STATUS_TRANSITIONS, CANCEL_STATUS_VALUES, } from "../../../../../utils/record_state.js"; +import { HandlerPayment } from "../../../../../handler/payment.js"; +import logger from "../../../../../utils/logger.js"; const escortRecordSetTool = tool( async ({ orderId, status, cancelStatus, notes, inquiry, payment }) => { @@ -37,6 +39,7 @@ const escortRecordSetTool = tool( // 状态迁移必须与接口层同一套规则:否则 Agent 能把已完成订单改回进行中, // 绕过状态机并造成费用/服务记录不一致 const update = {}; + let effectivePay = record.payment || {}; // 兼容旧数据:取消曾存放在 status 中 const currentCancel = record.status === "cancelled" ? "cancelled" @@ -50,9 +53,16 @@ const escortRecordSetTool = tool( error: `Illegal cancel status transition: ${currentCancel} -> ${cancelStatus}`, }; } + if (cancelStatus === "cancelled" && record.status === "completed") { + return { success: false, error: "已完成订单不可取消,请走线下售后处理" }; + } 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) { @@ -102,7 +112,28 @@ const escortRecordSetTool = tool( } } + // 已收款订单不能反向改支付状态/实收金额:否则可把退款中订单改回未支付并再次收款 + const currentPayStatus = effectivePay.status || "unpaid"; if (payment !== undefined) { + if (["partial", "paid", "refunding", "refunded"].includes(currentPayStatus)) { + // 取消已收款订单时允许 paid → refunding,其余反向改动一律拒绝 + const enterRefundOnCancel = update.cancelStatus === "cancelled" + && currentPayStatus === "paid" + && payment.status === "refunding"; + if (payment.status !== undefined && payment.status !== currentPayStatus && !enterRefundOnCancel) { + return { success: false, error: "已收款订单不可修改支付状态,如需退款请走取消流程" }; + } + if (payment.paidFee !== undefined + && Number(payment.paidFee) !== (Number(effectivePay.paidFee) || 0)) { + return { success: false, error: "已收款订单不可修改实收金额" }; + } + if (payment.totalFee !== undefined + && Number(payment.totalFee) !== (Number(effectivePay.totalFee) || 0)) { + return { success: false, error: "已收款订单不可修改金额,如需调整请先退款" }; + } + } else if (payment.status !== undefined && !["unpaid", "paid"].includes(payment.status)) { + return { success: false, error: "未收款订单只能标记为 unpaid 或 paid" }; + } if (payment.totalFee !== undefined) { update["payment.totalFee"] = payment.totalFee; } @@ -114,6 +145,14 @@ const escortRecordSetTool = tool( } } + // 取消已收款订单:与接口层一致,先进入退款中,落库后再发起原路退款 + if (update.cancelStatus === "cancelled" && ["partial", "paid"].includes(currentPayStatus)) { + if (payment?.status !== undefined && payment.status !== "refunding") { + return { success: false, error: "取消已收款订单时支付状态必须进入 refunding" }; + } + update["payment.status"] = "refunding"; + } + update["meta.updatetime"] = Date.now(); // 以读取时的状态作为更新条件,避免并发下跳过中间状态;同时排除已软删除的订单 @@ -138,6 +177,17 @@ const escortRecordSetTool = tool( }; } + // 已取消且进入退款中的线上订单:落库后触发原路退款(失败只记日志,由管理端查询兜底) + if (updatedRecord.cancelStatus === "cancelled" + && updatedRecord.payment?.status === "refunding" + && updatedRecord.payment?.method === "online_wechat") { + HandlerPayment.createRefundForRecord(updatedRecord, { + reason: updatedRecord.cancelReason || "平台取消", + }).catch((err) => { + logger.error(`[escort-agent] 取消订单自动退款失败 recordId=${orderId}: ${err?.message || err}`); + }); + } + return { success: true, data: updatedRecord, diff --git a/handler/escort_record.js b/handler/escort_record.js index 89c7ad5..daf9d1c 100644 --- a/handler/escort_record.js +++ b/handler/escort_record.js @@ -483,6 +483,38 @@ class HandlerEscortRecord { return ResponseUtil.badRequest(ctx, "该订单当前状态不支持修改这些信息"); } + // 已收款订单一律锁定支付状态与实收金额:否则编辑退款中的订单会把它改回未支付, + // 用户可再次支付造成重复扣款;金额改动也会与 payment_record 对不上 + const currentPayStatus = existing.payment?.status || "unpaid"; + const settledPayStatus = ["partial", "paid", "refunding", "refunded"].includes(currentPayStatus); + const nextPayStatus = payload["payment.status"] ?? payload.payment?.status; + const nextPaidFee = payload["payment.paidFee"] ?? payload.payment?.paidFee; + if (settledPayStatus) { + if (nextPayStatus !== undefined && nextPayStatus !== currentPayStatus) { + return ResponseUtil.badRequest(ctx, "已收款订单不可修改支付状态,如需退款请走取消流程"); + } + if (nextPaidFee !== undefined && Number(nextPaidFee) !== (Number(existing.payment?.paidFee) || 0)) { + return ResponseUtil.badRequest(ctx, "已收款订单不可修改实收金额"); + } + const nextTotalFee = payload["payment.totalFee"] ?? payload.payment?.totalFee; + if (nextTotalFee !== undefined + && Number(nextTotalFee) !== (Number(existing.payment?.totalFee) || 0)) { + return ResponseUtil.badRequest(ctx, "已收款订单不可修改金额,如需调整请先退款"); + } + } + + // 线上微信收款只能由支付回调写入:手工标记会没有支付流水,取消时无法原路退款 + const nextPaymentMethod = payload["payment.method"] ?? payload.payment?.method; + if (nextPaymentMethod === "online_wechat" && nextPayStatus === "paid") { + const paidPayment = await DBModel.PaymentRecord.findOne({ + recordId: id, + status: { $in: ["pay_success", "refunding", "refunded"] }, + }); + if (!paidPayment) { + return ResponseUtil.badRequest(ctx, "线上微信收款只能由支付回调写入,请选择线下现金或转账"); + } + } + // 支付方式为受控枚举:管理端修改时校验,防止写入非法值 const paymentMethod = update["payment.method"] ?? update.payment?.method; if (paymentMethod !== undefined && !HandlerEscortRecord.PAYMENT_METHODS.includes(paymentMethod)) { @@ -507,13 +539,9 @@ class HandlerEscortRecord { if (requestedChannel === "offline") { const closeResult = await HandlerPayment.closeOpenPayRecords(id); if (closeResult.paid) { - const fresh = await DBModel.EscortRecord.findById(id); - HandlerPayment.createRefundForRecord(fresh || existing, { - reason: "用户切换支付方式", - }).catch((err) => { - logger.error(`[escort] 切换支付方式后自动退款失败 recordId=${id}: ${err?.message || err}`); - }); - return ResponseUtil.error(ctx, "订单已支付,已为您发起退款", null, 409); + // 已支付不能改渠道:这里只提示刷新,不主动退款。 + // 否则会得到一张「仍在履约、款项已退」的死单,用户既不能再付也不能切线下 + return ResponseUtil.error(ctx, "订单已支付,请刷新页面查看最新状态", null, 409); } payload["payment.paymentRecordId"] = null; } @@ -612,7 +640,13 @@ class HandlerEscortRecord { } const user = ctx.state.user; - const role = await resolveEscortAdminRole(user); + // 用户端与管理端共用本接口,按调用方 app 区分取消流程: + // appId 只用于收紧权限——即使账号同时带管理员角色,从用户端小程序发起的取消 + // 也必须走取消申请,否则会在 C 端绕过「已确认订单需人工确认」直接退款。 + // 管理端固定带 appId=wxapp-escort-admin;未带 appId 的历史调用保持原角色判定。 + const requestAppId = String(ctx.request.body?.appId || ""); + const isUserApp = requestAppId === "wxapp-escort"; + const role = isUserApp ? null : await resolveEscortAdminRole(user); const isOwner = String(existing.userId) === String(user?._id); const paymentStatus = existing.payment?.status || "unpaid"; const cancelReason = String(reason || "").trim().slice(0, 200); @@ -629,7 +663,7 @@ class HandlerEscortRecord { } if (role !== "admin" && role !== "attendant") { - // 用户端只能取消:未确认且未收款直接物理删除;其余提交取消申请 + // 用户端只能取消:未确认订单直接取消(未收款删除、已收款退款);已确认订单提交取消申请 if (status !== "cancelled" || !isOwner) { return ResponseUtil.forbidden(ctx, "不支持的状态变更"); } @@ -641,30 +675,46 @@ class HandlerEscortRecord { } if (!cancelReason) return ResponseUtil.badRequest(ctx, "请选择取消原因"); - if (paymentStatus === "unpaid" && existing.status === "pending") { - // 删除前必须先关单,否则旧 prepay 仍可支付一张已不存在的订单 + if (existing.status === "pending") { + // 未确认订单:陪诊师尚未接单,取消直接生效,无需人工确认。 + // 取消前先关单,否则旧 prepay 仍可支付一张已不存在的订单 const closeResult = await HandlerPayment.closeOpenPayRecords(id); + let payStatus = paymentStatus; + let pay = existing.payment || {}; if (closeResult.paid) { - // 关单后发现钱已到账:不能删除,转待取消并等待确认后退款 - const updated = await DBModel.EscortRecord.updateRecordCancel(id, cancelStatus, { - cancelStatus: "requested", - cancelReason, - cancelRequestedAt: new Date(), - }); - if (!updated) { - return ResponseUtil.error(ctx, "订单状态已变化,请刷新后重试", null, 409); + const fresh = await DBModel.EscortRecord.findById(id); + payStatus = fresh?.payment?.status || "paid"; + pay = fresh?.payment || pay; + } + if (payStatus === "unpaid") { + const deletedRecord = await DBModel.EscortRecord.deleteRecord(id); + if (!deletedRecord) { + return ResponseUtil.error(ctx, "陪诊记录不存在", null, 404); } - return ResponseUtil.success( - ctx, - { record: HandlerEscortRecord.withPaymentWindow(updated), deleted: false }, - "订单已支付,取消申请已提交" - ); + return ResponseUtil.success(ctx, { record: deletedRecord, deleted: true }, "订单已取消"); } - const deletedRecord = await DBModel.EscortRecord.deleteRecord(id); - if (!deletedRecord) { - return ResponseUtil.error(ctx, "陪诊记录不存在", null, 404); + // 已收款:直接转已取消并进入退款;线上微信自动原路退款,线下由平台人工核销 + const updatedRecord = await DBModel.EscortRecord.updateRecordCancel(id, cancelStatus, { + cancelStatus: "cancelled", + cancelReason, + cancelledAt: new Date(), + ...(["partial", "paid"].includes(payStatus) ? { "payment.status": "refunding" } : {}), + }); + if (!updatedRecord) { + return ResponseUtil.error(ctx, "订单状态已变化,请刷新后重试", null, 409); } - return ResponseUtil.success(ctx, { record: deletedRecord, deleted: true }, "订单已取消"); + if (pay.method === "online_wechat" && ["partial", "paid"].includes(payStatus)) { + HandlerPayment.createRefundForRecord(updatedRecord, { + reason: cancelReason || "订单取消", + }).catch((err) => { + logger.error(`[escort] 未确认订单取消自动退款失败 recordId=${id}: ${err?.message || err}`); + }); + } + return ResponseUtil.success( + ctx, + { record: HandlerEscortRecord.withPaymentWindow(updatedRecord) }, + "订单已取消,退款已发起" + ); } // 申请取消前先关闭未支付的 prepay,避免等待确认期间又被支付 @@ -710,6 +760,10 @@ class HandlerEscortRecord { if (!canCancelTransition(cancelStatus, "cancelled")) { return ResponseUtil.badRequest(ctx, "当前订单不允许取消"); } + // 已完成是终态:服务已交付,取消/退款需走线下售后,不能由接口直接改状态 + if (existing.status === "completed") { + return ResponseUtil.badRequest(ctx, "已完成订单不可取消,请走线下售后处理"); + } // 取消前先关单:未支付订单可能仍有旧 prepay 在途,关单后发现已支付则按已收款走退款 const closeResult = await HandlerPayment.closeOpenPayRecords(id); diff --git a/handler/payment.js b/handler/payment.js index 0f1e5f2..77f6c9e 100644 --- a/handler/payment.js +++ b/handler/payment.js @@ -209,8 +209,9 @@ class HandlerPayment { if (!record || record.deletedAt) { return { payment, record: null, cancelled: true }; } - // 取消与 status 解耦:已申请取消或已取消的订单都不再回刷 paid(兼容旧数据 status=cancelled) - if ((record.cancelStatus || "none") !== "none" || record.status === "cancelled") { + // 只有正式取消才退款(兼容旧数据 status=cancelled); + // 仅「待取消」时钱已到账仍按已支付如实记账,等陪诊师/平台确认取消时再退 + if ((record.cancelStatus || "none") === "cancelled" || record.status === "cancelled") { return { payment, record, cancelled: true }; } // 已进入退款阶段的流水不再回刷 paid,避免快照倒退 @@ -268,7 +269,14 @@ class HandlerPayment { const trade = await wxpay.queryOrder(payment.outTradeNo); if (trade.trade_state === "SUCCESS") { HandlerPayment.verifyTrade(trade, payment); - await HandlerPayment.applyPaymentSuccess(payment, HandlerPayment.mapTransaction(trade)); + const applied = await HandlerPayment.applyPaymentSuccess(payment, HandlerPayment.mapTransaction(trade)); + if (applied.cancelled) { + HandlerPayment.createRefundForRecord(applied.record || { _id: payment.recordId }, { + reason: DEFAULT_REFUND_REASON, + }).catch((refundErr) => { + logger.error(`[payment] 关单时发现已支付且订单已取消,退款失败 recordId=${payment.recordId}: ${refundErr?.message || refundErr}`); + }); + } result.paid += 1; } else { await HandlerPayment.setPaymentStatus(payment._id, "closed_unconfirmed", { @@ -347,7 +355,11 @@ class HandlerPayment { recordId, status: { $in: ["pay_success", "refunding"] }, }).sort({ paidAt: -1, createdAt: -1 }); - if (!payment) return { skipped: true }; + if (!payment) { + // 手工标记的「线上微信已收款」没有支付流水,无法原路退款;留 refunding 交人工核对 + logger.error(`[payment] 退款未发起:缺少成功支付流水 recordId=${recordId},请人工核对收款方式`); + return { skipped: true, reason: "no_payment_record" }; + } const outRefundNo = `${recordId}-R1`; const existing = await DBModel.RefundRecord.findOne({ outRefundNo }); @@ -517,10 +529,17 @@ class HandlerPayment { const trade = await wxpay.queryOrder(unconfirmed.outTradeNo); if (trade.trade_state === "SUCCESS") { HandlerPayment.verifyTrade(trade, unconfirmed); - await HandlerPayment.applyPaymentSuccess( + const applied = await HandlerPayment.applyPaymentSuccess( unconfirmed, HandlerPayment.mapTransaction(trade) ); + if (applied.cancelled) { + HandlerPayment.createRefundForRecord(applied.record || { _id: unconfirmed.recordId }, { + reason: DEFAULT_REFUND_REASON, + }).catch((refundErr) => { + logger.error(`[payment] 发起支付时发现旧流水已支付且订单已取消,退款失败 recordId=${unconfirmed.recordId}: ${refundErr?.message || refundErr}`); + }); + } return ResponseUtil.badRequest(ctx, "订单已支付,请勿重复支付"); } } catch (err) { @@ -737,7 +756,14 @@ class HandlerPayment { const trade = await wxpay.queryOrder(payment.outTradeNo); if (trade.trade_state === "SUCCESS") { HandlerPayment.verifyTrade(trade, payment); - await HandlerPayment.applyPaymentSuccess(payment, HandlerPayment.mapTransaction(trade)); + const applied = await HandlerPayment.applyPaymentSuccess(payment, HandlerPayment.mapTransaction(trade)); + if (applied.cancelled) { + HandlerPayment.createRefundForRecord(applied.record || { _id: payment.recordId }, { + reason: DEFAULT_REFUND_REASON, + }).catch((refundErr) => { + logger.error(`[payment] 逾期关单时发现已支付且订单已取消,退款失败 recordId=${payment.recordId}: ${refundErr?.message || refundErr}`); + }); + } } else { await HandlerPayment.setPaymentStatus(payment._id, "closed_unconfirmed", { closeUnconfirmed: true, @@ -902,6 +928,40 @@ class HandlerPayment { return ResponseUtil.error(ctx, "查询退款结果失败,请稍后重试", null, 500); } } + + /** + * POST /escort-record/:id/refund/manual (管理端) + * 线下收款或缺少线上流水的订单,由平台人工退款后在此核销 + */ + async completeManualRefund(ctx) { + try { + const id = ctx.params.id; + if (!isValidObjectId(id)) return ResponseUtil.badRequest(ctx, "缺少记录ID"); + const record = await DBModel.EscortRecord.findById(id); + if (!record || record.deletedAt) return ResponseUtil.error(ctx, "陪诊记录不存在", null, 404); + if ((record.payment?.status || "unpaid") !== "refunding") { + return ResponseUtil.badRequest(ctx, "当前订单不在退款中"); + } + // 线上退款单还在处理中时不允许人工核销,必须先查询退款结果 + const processingRefund = await DBModel.RefundRecord.findOne({ + recordId: record._id, + status: "processing", + }); + if (processingRefund) { + return ResponseUtil.badRequest(ctx, "存在处理中的线上退款,请先查询退款结果"); + } + + const updatedRecord = await DBModel.EscortRecord.updateRecord(id, { + "payment.status": "refunded", + }); + if (!updatedRecord) return ResponseUtil.error(ctx, "陪诊记录不存在", null, 404); + logger.info(`[payment] 人工核销退款完成 recordId=${id} method=${record.payment?.method || ""}`); + return ResponseUtil.success(ctx, { record: updatedRecord }, "已标记为退款完成"); + } catch (err) { + logger.error(`[payment] 人工核销退款失败 recordId=${ctx.params.id}: ${err?.message || err}`); + return ResponseUtil.internalError(ctx, err); + } + } } // ==================== 后台巡检查单 ==================== diff --git a/routes/index.js b/routes/index.js index 047c6ee..9984afc 100644 --- a/routes/index.js +++ b/routes/index.js @@ -99,6 +99,8 @@ function registerRoutes(app) { router.post("/escort-record/:id/pay", requireAuth, createLimit, handlerPayment.createPayment.bind(handlerPayment)); router.get("/escort-record/:id/pay/status", requireAuth, handlerPayment.queryPayment.bind(handlerPayment)); router.post("/escort-record/:id/refund/query", requireAuth, requireAdmin, handlerPayment.queryRefundResult.bind(handlerPayment)); + // 线下/人工退款核销:由平台确认已退款后把订单置为 refunded + router.post("/escort-record/:id/refund/manual", requireAuth, requireAdmin, handlerPayment.completeManualRefund.bind(handlerPayment)); router.get("/escort-record/:id", requireAuth, handlerEscortRecord.getRecordById.bind(handlerEscortRecord)); router.post("/escort-record", requireAuth, createLimit, handlerEscortRecord.createRecord.bind(handlerEscortRecord));