feat:增加微信支付功能
This commit is contained in:
+158
-11
@@ -1,8 +1,10 @@
|
||||
import { DBModel } from "../models/index.js";
|
||||
import services from "../resource/services.js";
|
||||
import ResponseUtil from "../utils/responseUtil.js";
|
||||
import logger from "../utils/logger.js";
|
||||
import { isAdmin as isAdminUser, resolveEscortAdminRole } from "../utils/permissions.js";
|
||||
import { canTransition, STATUS_TRANSITIONS } from "../utils/record_state.js";
|
||||
import { HandlerPayment } from "./payment.js";
|
||||
|
||||
class HandlerEscortRecord {
|
||||
constructor() {
|
||||
@@ -25,8 +27,8 @@ class HandlerEscortRecord {
|
||||
"hospital.doctor", "hospital.medicalRecordNo", "schedule.date", "schedule.startTime",
|
||||
];
|
||||
static OWNER_EDITABLE_BY_STATUS = {
|
||||
pending: ["notes.patientNote", ...HandlerEscortRecord.OWNER_BOOKING_FIELDS],
|
||||
confirmed: ["notes.patientNote", ...HandlerEscortRecord.OWNER_BOOKING_FIELDS],
|
||||
pending: ["notes.patientNote", "payment.payChannel", ...HandlerEscortRecord.OWNER_BOOKING_FIELDS],
|
||||
confirmed: ["notes.patientNote", "payment.payChannel", ...HandlerEscortRecord.OWNER_BOOKING_FIELDS],
|
||||
in_progress: ["notes.patientNote"],
|
||||
};
|
||||
|
||||
@@ -37,6 +39,9 @@ class HandlerEscortRecord {
|
||||
// 支付方式为平台受控枚举(与 schema 一致),空串表示清除/未记录
|
||||
static PAYMENT_METHODS = ["", "online_wechat", "offline_cash", "offline_transfer"];
|
||||
|
||||
// 用户下单时可选择的支付渠道:线下支付不细分现金/转账,由平台收款时补记 method
|
||||
static PAY_CHANNELS = ["online_wechat", "offline"];
|
||||
|
||||
// 单页最大条数,避免 pageSize 传超大值一次拖库
|
||||
static MAX_PAGE_SIZE = 200;
|
||||
|
||||
@@ -86,6 +91,20 @@ class HandlerEscortRecord {
|
||||
&& String(record.attendant.id) === String(user?._id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 输出给前端的订单视图:追加支付窗口终点,供列表/详情判断「支付已超时」。
|
||||
* 只派生展示字段,不写库。
|
||||
* @param {Object} record mongoose 文档
|
||||
* @returns {Object}
|
||||
*/
|
||||
static withPaymentWindow(record) {
|
||||
if (!record) return record;
|
||||
const plain = record.toObject ? record.toObject() : { ...record };
|
||||
const end = HandlerPayment.getPayWindowEnd(plain);
|
||||
plain.paymentWindowEnd = end ? end.toISOString() : null;
|
||||
return plain;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从入参中挑出白名单字段
|
||||
* @param {Object} body 请求体
|
||||
@@ -219,7 +238,8 @@ class HandlerEscortRecord {
|
||||
healthProfileId,
|
||||
});
|
||||
|
||||
return ResponseUtil.success(ctx, { ...result, page, pageSize }, "查询成功");
|
||||
const records = result.records.map((record) => HandlerEscortRecord.withPaymentWindow(record));
|
||||
return ResponseUtil.success(ctx, { ...result, records, page, pageSize }, "查询成功");
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
@@ -263,7 +283,7 @@ class HandlerEscortRecord {
|
||||
return ResponseUtil.forbidden(ctx, "无权访问该订单");
|
||||
}
|
||||
|
||||
return ResponseUtil.success(ctx, { record }, "查询成功");
|
||||
return ResponseUtil.success(ctx, { record: HandlerEscortRecord.withPaymentWindow(record) }, "查询成功");
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
@@ -333,12 +353,29 @@ class HandlerEscortRecord {
|
||||
payload.schedule = scheduleResult.schedule;
|
||||
payload.shippingAddress = addressResult.shippingAddress;
|
||||
if (idempotencyKey) payload.idempotencyKey = idempotencyKey;
|
||||
|
||||
// 支付渠道:用户端只可选微信支付 / 线下支付;管理员代下单可按 method 推导
|
||||
const requestedChannel = body.payment?.payChannel;
|
||||
if (requestedChannel !== undefined
|
||||
&& !HandlerEscortRecord.PAY_CHANNELS.includes(requestedChannel)) {
|
||||
return ResponseUtil.badRequest(ctx, "支付方式不正确");
|
||||
}
|
||||
let payChannel;
|
||||
if (HandlerEscortRecord.isAdmin(ctx.state.user)) {
|
||||
payChannel = HandlerEscortRecord.PAY_CHANNELS.includes(requestedChannel)
|
||||
? requestedChannel
|
||||
: (body.payment?.method === "online_wechat" ? "online_wechat" : "offline");
|
||||
} else {
|
||||
payChannel = requestedChannel || "online_wechat";
|
||||
}
|
||||
|
||||
payload.payment = {
|
||||
totalFee: Number(service.price) || 0,
|
||||
paidFee: 0,
|
||||
status: "unpaid",
|
||||
payChannel,
|
||||
};
|
||||
// 支付方式由平台在收款时补记:仅管理员代客下单时可指定,用户端提交一律丢弃
|
||||
// 实际收款方式由平台在收款时补记:仅管理员代客下单时可指定,用户端提交一律丢弃
|
||||
if (HandlerEscortRecord.isAdmin(ctx.state.user)
|
||||
&& HandlerEscortRecord.PAYMENT_METHODS.includes(body.payment?.method)) {
|
||||
payload.payment.method = body.payment.method;
|
||||
@@ -399,6 +436,60 @@ class HandlerEscortRecord {
|
||||
return ResponseUtil.badRequest(ctx, "支付方式不正确");
|
||||
}
|
||||
|
||||
// 支付渠道:用户端仅在待支付期间可切换;切到线下前必须先关单
|
||||
const requestedChannel = update["payment.payChannel"] ?? update.payment?.payChannel;
|
||||
if (requestedChannel !== undefined) {
|
||||
if (!HandlerEscortRecord.PAY_CHANNELS.includes(requestedChannel)) {
|
||||
return ResponseUtil.badRequest(ctx, "支付方式不正确");
|
||||
}
|
||||
if ((existing.payment?.status || "unpaid") !== "unpaid") {
|
||||
return ResponseUtil.forbidden(ctx, "已收款订单不可修改支付方式");
|
||||
}
|
||||
if (!["pending", "confirmed"].includes(existing.status)) {
|
||||
return ResponseUtil.badRequest(ctx, "当前订单状态不允许修改支付方式");
|
||||
}
|
||||
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);
|
||||
}
|
||||
payload["payment.paymentRecordId"] = null;
|
||||
}
|
||||
// 避免管理端提交嵌套 payment 对象时整体覆盖:统一写成点路径
|
||||
if (payload["payment.payChannel"] === undefined) {
|
||||
payload["payment.payChannel"] = requestedChannel;
|
||||
if (payload.payment) {
|
||||
const nested = { ...payload.payment };
|
||||
delete nested.payChannel;
|
||||
if (Object.keys(nested).length === 0) delete payload.payment;
|
||||
else payload.payment = nested;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 存在未支付流水时禁止改价:微信侧金额与本地流水错位会对账不上
|
||||
const nextTotalFee = update["payment.totalFee"] ?? update.payment?.totalFee;
|
||||
const touchesTotalFee = payload["payment.totalFee"] !== undefined
|
||||
|| (payload.payment && payload.payment.totalFee !== undefined);
|
||||
if (nextTotalFee !== undefined && touchesTotalFee) {
|
||||
const currentTotalFee = Number(existing.payment?.totalFee) || 0;
|
||||
if (Number(nextTotalFee) !== currentTotalFee) {
|
||||
const openPayment = await DBModel.PaymentRecord.findOne({
|
||||
recordId: id,
|
||||
status: "created",
|
||||
});
|
||||
if (openPayment) {
|
||||
return ResponseUtil.badRequest(ctx, "订单存在未支付流水,请先关闭或取消后再修改金额");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 档案归属校验:档案必须属于订单所属用户,避免把订单挂到他人档案上;
|
||||
// 通过后同步刷新订单里的就诊人快照
|
||||
if (payload.healthProfileId) {
|
||||
@@ -468,6 +559,9 @@ class HandlerEscortRecord {
|
||||
const role = 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);
|
||||
let effectivePaymentStatus = paymentStatus;
|
||||
let effectivePayment = existing.payment || {};
|
||||
|
||||
let targetStatus = status;
|
||||
if (role !== "admin" && role !== "attendant") {
|
||||
@@ -476,7 +570,25 @@ class HandlerEscortRecord {
|
||||
return ResponseUtil.forbidden(ctx, "不支持的状态变更");
|
||||
}
|
||||
if (paymentStatus === "unpaid" && existing.status === "pending") {
|
||||
// 接入微信支付后:删除前必须先关单,否则旧 prepay 仍可支付一张已不存在的订单
|
||||
if (!cancelReason) return ResponseUtil.badRequest(ctx, "请选择取消原因");
|
||||
// 删除前必须先关单,否则旧 prepay 仍可支付一张已不存在的订单
|
||||
const closeResult = await HandlerPayment.closeOpenPayRecords(id);
|
||||
if (closeResult.paid) {
|
||||
// 关单后发现钱已到账:不能删除,转待取消并等待确认后退款
|
||||
const updated = await DBModel.EscortRecord.updateRecordStatus(id, "pending", {
|
||||
status: "cancel_requested",
|
||||
cancelReason,
|
||||
cancelRequestedAt: new Date(),
|
||||
});
|
||||
if (!updated) {
|
||||
return ResponseUtil.error(ctx, "订单状态已变化,请刷新后重试", null, 409);
|
||||
}
|
||||
return ResponseUtil.success(
|
||||
ctx,
|
||||
{ record: HandlerEscortRecord.withPaymentWindow(updated), deleted: false },
|
||||
"订单已支付,取消申请已提交"
|
||||
);
|
||||
}
|
||||
const deletedRecord = await DBModel.EscortRecord.deleteRecord(id);
|
||||
if (!deletedRecord) {
|
||||
return ResponseUtil.error(ctx, "陪诊记录不存在", null, 404);
|
||||
@@ -486,7 +598,17 @@ class HandlerEscortRecord {
|
||||
if (!["pending", "confirmed"].includes(existing.status)) {
|
||||
return ResponseUtil.badRequest(ctx, "当前订单状态不允许此操作");
|
||||
}
|
||||
// 申请取消前先关闭未支付的 prepay,避免等待确认期间又被支付
|
||||
await HandlerPayment.closeOpenPayRecords(id);
|
||||
targetStatus = "cancel_requested";
|
||||
} else if (targetStatus === "cancelled" && paymentStatus === "unpaid") {
|
||||
// 平台直接取消待支付订单,同样先关单;关单后发现已支付则按已收款走退款
|
||||
const closeResult = await HandlerPayment.closeOpenPayRecords(id);
|
||||
if (closeResult.paid) {
|
||||
const fresh = await DBModel.EscortRecord.findById(id);
|
||||
effectivePaymentStatus = fresh?.payment?.status || "paid";
|
||||
effectivePayment = fresh?.payment || effectivePayment;
|
||||
}
|
||||
}
|
||||
|
||||
if (!canTransition(existing.status, targetStatus)) {
|
||||
@@ -494,10 +616,8 @@ class HandlerEscortRecord {
|
||||
}
|
||||
|
||||
const update = { status: targetStatus };
|
||||
const cancelReason = String(reason || "").trim().slice(0, 200);
|
||||
if (targetStatus === "cancel_requested") {
|
||||
if (!cancelReason) return ResponseUtil.badRequest(ctx, "请选择取消原因");
|
||||
// 接入微信支付后:此处应关闭未支付的 prepay,避免申请取消期间又被支付
|
||||
update.cancelReason = cancelReason;
|
||||
update.cancelRequestedAt = new Date();
|
||||
}
|
||||
@@ -506,8 +626,8 @@ class HandlerEscortRecord {
|
||||
if (cancelReason) update.cancelReason = cancelReason;
|
||||
else if (role === "admin" && !existing.cancelReason) update.cancelReason = "平台取消";
|
||||
update.cancelledAt = new Date();
|
||||
// 客服协助支付没有线上自动退款能力:已收款订单先进入退款中,退款完成再由平台核销。
|
||||
if (["partial", "paid"].includes(paymentStatus)) {
|
||||
// 已收款订单先进入退款中;线上支付随后自动原路退款,线下由平台人工核销
|
||||
if (["partial", "paid"].includes(effectivePaymentStatus)) {
|
||||
update["payment.status"] = "refunding";
|
||||
}
|
||||
}
|
||||
@@ -517,6 +637,17 @@ class HandlerEscortRecord {
|
||||
return ResponseUtil.error(ctx, "订单状态已变化,请刷新后重试", null, 409);
|
||||
}
|
||||
|
||||
// 已支付的线上订单:状态落库后再发起原路全额退款
|
||||
if (targetStatus === "cancelled"
|
||||
&& effectivePayment?.method === "online_wechat"
|
||||
&& ["partial", "paid"].includes(effectivePaymentStatus)) {
|
||||
HandlerPayment.createRefundForRecord(updatedRecord, {
|
||||
reason: updatedRecord.cancelReason || cancelReason || "订单取消",
|
||||
}).catch((err) => {
|
||||
logger.error(`[escort] 取消订单自动退款失败 recordId=${id}: ${err?.message || err}`);
|
||||
});
|
||||
}
|
||||
|
||||
return ResponseUtil.success(ctx, { record: updatedRecord }, "状态更新成功");
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
@@ -542,7 +673,16 @@ class HandlerEscortRecord {
|
||||
return ResponseUtil.forbidden(ctx, "无权删除该订单");
|
||||
}
|
||||
|
||||
const paymentStatus = existing.payment?.status || "unpaid";
|
||||
let paymentStatus = existing.payment?.status || "unpaid";
|
||||
let paymentMethod = existing.payment?.method || "";
|
||||
// 软删除前先关单:否则已软删除的订单仍可能被旧 prepay 支付
|
||||
const closeResult = await HandlerPayment.closeOpenPayRecords(id);
|
||||
if (closeResult.paid) {
|
||||
const fresh = await DBModel.EscortRecord.findById(id);
|
||||
paymentStatus = fresh?.payment?.status || "paid";
|
||||
paymentMethod = fresh?.payment?.method || "online_wechat";
|
||||
}
|
||||
|
||||
const update = { deletedAt: new Date() };
|
||||
if (["partial", "paid"].includes(paymentStatus)) {
|
||||
update.status = "cancelled";
|
||||
@@ -554,6 +694,13 @@ class HandlerEscortRecord {
|
||||
if (!softDeleted) {
|
||||
return ResponseUtil.error(ctx, "陪诊记录不存在", null, 404);
|
||||
}
|
||||
if (update.status === "cancelled" && paymentMethod === "online_wechat") {
|
||||
HandlerPayment.createRefundForRecord(softDeleted, {
|
||||
reason: softDeleted.cancelReason || "平台删除",
|
||||
}).catch((err) => {
|
||||
logger.error(`[escort] 删除订单自动退款失败 recordId=${id}: ${err?.message || err}`);
|
||||
});
|
||||
}
|
||||
return ResponseUtil.success(ctx, { record: softDeleted }, "删除成功");
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
|
||||
Reference in New Issue
Block a user