712 lines
30 KiB
JavaScript
712 lines
30 KiB
JavaScript
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() {
|
|
}
|
|
|
|
// 白名单:只允许写入 schema 定义的顶层字段(兼容 'patient.name' 等点号路径)
|
|
static RECORD_FIELDS = [
|
|
"userId", "healthProfileId", "patient", "escort",
|
|
"attendant", "hospital", "schedule", "payment", "notes", "status",
|
|
"shippingAddress",
|
|
];
|
|
|
|
// 用户自助可改字段按订单状态区分(费用、状态、陪诊员分配、档案归属一律由平台控制):
|
|
// - 待支付/已支付:可改医院与排期(改期会写审计时间)
|
|
// - 进行中:服务已开始,仅可补充就诊人备注,排期与医院不允许用户单方变更
|
|
// - 终态:全部不可改
|
|
static OWNER_NOTE_FIELDS = ["notes.patientNote"];
|
|
static OWNER_BOOKING_FIELDS = [
|
|
"hospital.province", "hospital.name", "hospital.address", "hospital.department",
|
|
"hospital.doctor", "hospital.medicalRecordNo", "schedule.date", "schedule.startTime",
|
|
];
|
|
static OWNER_EDITABLE_BY_STATUS = {
|
|
pending: ["notes.patientNote", "payment.payChannel", ...HandlerEscortRecord.OWNER_BOOKING_FIELDS],
|
|
confirmed: ["notes.patientNote", "payment.payChannel", ...HandlerEscortRecord.OWNER_BOOKING_FIELDS],
|
|
in_progress: ["notes.patientNote"],
|
|
};
|
|
|
|
// 用户端只能发起取消,服务完成由平台确认,避免用户端重复写入终态。
|
|
// 「未确认且未收款」取消即物理删除;其余先进 cancel_requested,等陪诊师/管理员确认。
|
|
// 迁移规则集中在 utils/record_state.js,与管理端 Agent 工具共用
|
|
|
|
// 支付方式为平台受控枚举(与 schema 一致),空串表示清除/未记录
|
|
static PAYMENT_METHODS = ["", "online_wechat", "offline_cash", "offline_transfer"];
|
|
|
|
// 用户下单时可选择的支付渠道:线下支付不细分现金/转账,由平台收款时补记 method
|
|
static PAY_CHANNELS = ["online_wechat", "offline"];
|
|
|
|
// 单页最大条数,避免 pageSize 传超大值一次拖库
|
|
static MAX_PAGE_SIZE = 200;
|
|
|
|
/**
|
|
* 是否为管理端账号(与 WS 管理端 agent 的校验口径一致)
|
|
* @param {Object} user token 解析出的用户
|
|
*/
|
|
static isAdmin(user) {
|
|
return isAdminUser(user);
|
|
}
|
|
|
|
/**
|
|
* 用户端在当前状态下可自助修改的字段清单(白名单精确匹配,点号路径)
|
|
* @param {string} status 订单状态
|
|
* @returns {string[]}
|
|
*/
|
|
static ownerEditableFields(status) {
|
|
return HandlerEscortRecord.OWNER_EDITABLE_BY_STATUS[status] || [];
|
|
}
|
|
|
|
/**
|
|
* 就诊人快照:下单与更换档案共用,保证订单里的展示字段一致
|
|
* @param {Object} profile 健康档案文档
|
|
* @returns {Object}
|
|
*/
|
|
static buildPatientSnapshot(profile) {
|
|
const patient = {
|
|
name: profile.profile?.name || "",
|
|
mobile: profile.profile?.mobile || "",
|
|
birth: profile.profile?.birth || "",
|
|
};
|
|
if (["male", "female"].includes(profile.profile?.sex)) patient.sex = profile.profile.sex;
|
|
return patient;
|
|
}
|
|
|
|
/**
|
|
* 记录访问校验:仅记录所属用户本人或管理员可读写
|
|
* @param {Object} user 当前登录用户
|
|
* @param {Object} record 目标记录
|
|
*/
|
|
static canAccess(user, record) {
|
|
if (!record) return false;
|
|
if (HandlerEscortRecord.isAdmin(user)) return true;
|
|
if (String(record.userId) === String(user?._id)) return true;
|
|
// 陪诊师可访问自己名下的订单:管理端要据此处理取消申请与服务状态
|
|
return Boolean(record.attendant?.id)
|
|
&& 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 请求体
|
|
* @param {string[]} allowFields 允许的字段(支持点号路径)
|
|
* @param {boolean} exact 是否精确匹配;用户端用 true,防止 notes.patientNote.x 这类嵌套越界
|
|
*/
|
|
static pickFields(body, allowFields = HandlerEscortRecord.RECORD_FIELDS, exact = false) {
|
|
const picked = {};
|
|
for (const key of Object.keys(body || {})) {
|
|
const allowed = allowFields.some(
|
|
(f) => key === f || (!exact && key.startsWith(f + "."))
|
|
);
|
|
if (allowed) {
|
|
picked[key] = body[key];
|
|
}
|
|
}
|
|
return picked;
|
|
}
|
|
|
|
// 解析分页参数并夹紧上限,防止超大 pageSize 拖库
|
|
static parsePaging(query = {}) {
|
|
const page = Math.max(1, parseInt(query.page) || 1);
|
|
const rawSize = parseInt(query.pageSize) || 20;
|
|
const pageSize = Math.min(Math.max(1, rawSize), HandlerEscortRecord.MAX_PAGE_SIZE);
|
|
return { page, pageSize };
|
|
}
|
|
|
|
static formatDateOnly(value) {
|
|
if (!value) return "";
|
|
if (value instanceof Date) return value.toISOString().slice(0, 10);
|
|
return String(value).slice(0, 10);
|
|
}
|
|
|
|
static timeToMinutes(value) {
|
|
if (!/^([01]\d|2[0-3]):[0-5]\d$/.test(value || "")) return null;
|
|
const [hour, minute] = value.split(":").map(Number);
|
|
return hour * 60 + minute;
|
|
}
|
|
|
|
// 服务目录是预约规则与订单排期的唯一事实源,客户端提交的时长和结束时间一律忽略。
|
|
static buildSchedule(service, dateValue, startTime, now = new Date()) {
|
|
const date = HandlerEscortRecord.formatDateOnly(dateValue);
|
|
const parsedDate = new Date(`${date}T00:00:00.000Z`);
|
|
if (!/^\d{4}-\d{2}-\d{2}$/.test(date)
|
|
|| Number.isNaN(parsedDate.getTime())
|
|
|| parsedDate.toISOString().slice(0, 10) !== date) {
|
|
return { error: "预约日期格式不正确" };
|
|
}
|
|
const booking = service.booking;
|
|
if (!booking || !Array.isArray(booking.sessions) || booking.sessions.length === 0) {
|
|
return { error: "该服务暂未开放预约" };
|
|
}
|
|
const earliest = new Date(now);
|
|
earliest.setHours(0, 0, 0, 0);
|
|
earliest.setDate(earliest.getDate() + Number(booking.advanceDays || 0));
|
|
const earliestDate = `${earliest.getFullYear()}-${String(earliest.getMonth() + 1).padStart(2, "0")}-${String(earliest.getDate()).padStart(2, "0")}`;
|
|
if (date < earliestDate) {
|
|
return { error: `请至少提前${booking.advanceDays}天预约` };
|
|
}
|
|
|
|
const startMinutes = HandlerEscortRecord.timeToMinutes(startTime);
|
|
if (startMinutes === null) return { error: "预约时间格式不正确" };
|
|
const session = booking.sessions.find((item) => item.flexible
|
|
? startMinutes >= HandlerEscortRecord.timeToMinutes(item.start)
|
|
&& startMinutes + booking.durationMinutes <= HandlerEscortRecord.timeToMinutes(item.end)
|
|
: item.start === startTime);
|
|
if (!session) return { error: "所选时间不在该服务的可预约时段内" };
|
|
|
|
const endTime = session.flexible
|
|
? (() => {
|
|
const endMinutes = (startMinutes + booking.durationMinutes) % 1440;
|
|
return `${String(Math.floor(endMinutes / 60)).padStart(2, "0")}:${String(endMinutes % 60).padStart(2, "0")}`;
|
|
})()
|
|
: session.end;
|
|
return {
|
|
schedule: {
|
|
date,
|
|
startTime,
|
|
endTime,
|
|
duration: Number(booking.durationMinutes) || 0,
|
|
},
|
|
};
|
|
}
|
|
|
|
static buildShippingAddress(service, source, profile) {
|
|
const address = String(source?.address || "").trim();
|
|
if (service.booking?.requiresAddress && !address) {
|
|
return { error: "请填写完整收货地址" };
|
|
}
|
|
return {
|
|
shippingAddress: {
|
|
recipientName: profile.profile?.name || "",
|
|
mobile: profile.profile?.mobile || "",
|
|
address,
|
|
},
|
|
};
|
|
}
|
|
|
|
// 按条件查询记录(管理端,可查全部)
|
|
async getRecords(ctx) {
|
|
return this._listRecords(ctx, false);
|
|
}
|
|
|
|
// 查询"我的"记录:强制以登录用户身份查询,忽略 query 中的 userId
|
|
async getMyRecords(ctx) {
|
|
return this._listRecords(ctx, true);
|
|
}
|
|
|
|
async _listRecords(ctx, forceSelf) {
|
|
try {
|
|
const { status, userId, appointmentDate, healthProfileId } = ctx.request.query;
|
|
const { page, pageSize } = HandlerEscortRecord.parsePaging(ctx.request.query);
|
|
const effectiveUserId = forceSelf ? ctx.state.user?._id : userId;
|
|
|
|
// status解析成数组
|
|
let statusArray = null;
|
|
if (status && status.length > 0) {
|
|
statusArray = status.split(',')
|
|
}
|
|
|
|
if (statusArray && statusArray.some((item) => !Object.hasOwn(STATUS_TRANSITIONS, item))) {
|
|
return ResponseUtil.badRequest(ctx, "订单状态筛选值不正确");
|
|
}
|
|
|
|
const result = await DBModel.EscortRecord.findRecordPage({
|
|
page,
|
|
pageSize,
|
|
status: statusArray,
|
|
userId: effectiveUserId,
|
|
appointmentDate,
|
|
healthProfileId,
|
|
});
|
|
|
|
const records = result.records.map((record) => HandlerEscortRecord.withPaymentWindow(record));
|
|
return ResponseUtil.success(ctx, { ...result, records, page, pageSize }, "查询成功");
|
|
} catch (err) {
|
|
return ResponseUtil.internalError(ctx, err);
|
|
}
|
|
}
|
|
|
|
async getAttendantRecords(ctx) {
|
|
try {
|
|
// 只允许查询当前登录陪诊员自己的记录
|
|
const attendantId = ctx.state.user?._id;
|
|
if (!attendantId) {
|
|
return ResponseUtil.badRequest(ctx, "缺少陪诊员ID");
|
|
}
|
|
|
|
const { status } = ctx.request.query;
|
|
const { page, pageSize } = HandlerEscortRecord.parsePaging(ctx.request.query);
|
|
const records = await DBModel.EscortRecord.findRecordsByAttendant(attendantId, {
|
|
page,
|
|
pageSize,
|
|
status,
|
|
});
|
|
|
|
return ResponseUtil.success(ctx, { records }, "查询成功");
|
|
} catch (err) {
|
|
return ResponseUtil.internalError(ctx, err);
|
|
}
|
|
}
|
|
|
|
async getRecordById(ctx) {
|
|
try {
|
|
const { id } = ctx.params;
|
|
if (!id) {
|
|
return ResponseUtil.badRequest(ctx, "缺少记录ID");
|
|
}
|
|
|
|
const record = await DBModel.EscortRecord.findById(id);
|
|
if (!record) {
|
|
return ResponseUtil.error(ctx, "陪诊记录不存在", null, 404);
|
|
}
|
|
// 归属校验:非本人订单按无权限处理,避免凭 id 遍历他人订单
|
|
if (!HandlerEscortRecord.canAccess(ctx.state.user, record)) {
|
|
return ResponseUtil.forbidden(ctx, "无权访问该订单");
|
|
}
|
|
|
|
return ResponseUtil.success(ctx, { record: HandlerEscortRecord.withPaymentWindow(record) }, "查询成功");
|
|
} catch (err) {
|
|
return ResponseUtil.internalError(ctx, err);
|
|
}
|
|
}
|
|
|
|
async createRecord(ctx) {
|
|
try {
|
|
const body = ctx.request.body || {};
|
|
const userId = ctx.state.user?._id;
|
|
if (!userId) {
|
|
return ResponseUtil.unauthorized(ctx, "登录已失效");
|
|
}
|
|
const idempotencyKey = String(body.idempotencyKey || "").trim();
|
|
if (idempotencyKey && !/^[\w-]{8,80}$/.test(idempotencyKey)) {
|
|
return ResponseUtil.badRequest(ctx, "下单幂等标识格式不正确");
|
|
}
|
|
if (idempotencyKey) {
|
|
const existing = await DBModel.EscortRecord.findByIdempotencyKey(userId, idempotencyKey);
|
|
if (existing) return ResponseUtil.success(ctx, { record: existing }, "订单已创建");
|
|
}
|
|
|
|
// 订单必须关联就诊人:patient 是下单当刻的快照,healthProfileId 才是关联
|
|
if (!body.healthProfileId) {
|
|
return ResponseUtil.badRequest(ctx, "缺少就诊人档案ID");
|
|
}
|
|
|
|
// 就诊人档案必须属于当前登录用户,避免把订单挂到他人档案上
|
|
const profile = await DBModel.HealthProfile.findProfileById(body.healthProfileId);
|
|
if (!profile || String(profile.userId) !== String(userId)) {
|
|
return ResponseUtil.badRequest(ctx, "就诊人档案不存在");
|
|
}
|
|
|
|
// 服务项目、服务名称、区域、排期与价格均以服务端目录为准。
|
|
const service = services.find((s) => String(s.id) === String(body.escort?.serviceId));
|
|
if (!service) return ResponseUtil.badRequest(ctx, "服务项目不存在或已下架");
|
|
if (!service.areas.includes(body.hospital?.province)) {
|
|
return ResponseUtil.badRequest(ctx, "所选省份暂未开通服务");
|
|
}
|
|
// 科室为选填:用户可能尚未确定科室,可下单后在详情页补录
|
|
if (!String(body.hospital?.name || "").trim()) {
|
|
return ResponseUtil.badRequest(ctx, "请填写就诊医院");
|
|
}
|
|
const scheduleResult = HandlerEscortRecord.buildSchedule(
|
|
service,
|
|
body.schedule?.date,
|
|
body.schedule?.startTime
|
|
);
|
|
if (scheduleResult.error) return ResponseUtil.badRequest(ctx, scheduleResult.error);
|
|
const addressResult = HandlerEscortRecord.buildShippingAddress(service, body.shippingAddress, profile);
|
|
if (addressResult.error) return ResponseUtil.badRequest(ctx, addressResult.error);
|
|
|
|
const payload = HandlerEscortRecord.pickFields(body);
|
|
// 陪诊员分配由平台决定:用户下单时提交的 attendant 一律丢弃,防止自选/伪造陪诊员
|
|
if (!HandlerEscortRecord.isAdmin(ctx.state.user)) delete payload.attendant;
|
|
payload.userId = userId;
|
|
// healthProfileId 以校验通过的档案为准,覆盖客户端原值
|
|
payload.healthProfileId = profile._id;
|
|
payload.status = "pending";
|
|
payload.patient = HandlerEscortRecord.buildPatientSnapshot(profile);
|
|
payload.escort = {
|
|
serviceId: service.id,
|
|
serviceName: service.title,
|
|
sexRequirement: ["none", "male", "female"].includes(body.escort?.sexRequirement)
|
|
? body.escort.sexRequirement
|
|
: "none",
|
|
};
|
|
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;
|
|
}
|
|
|
|
try {
|
|
const newRecord = await DBModel.EscortRecord.createRecord(payload);
|
|
return ResponseUtil.success(ctx, { record: newRecord }, "创建成功");
|
|
} catch (err) {
|
|
// 并发重复提交由唯一索引兜底,后到的请求返回已创建订单。
|
|
if (err?.code === 11000 && idempotencyKey) {
|
|
const existing = await DBModel.EscortRecord.findByIdempotencyKey(userId, idempotencyKey);
|
|
if (existing) return ResponseUtil.success(ctx, { record: existing }, "订单已创建");
|
|
}
|
|
throw err;
|
|
}
|
|
} catch (err) {
|
|
return ResponseUtil.internalError(ctx, err);
|
|
}
|
|
}
|
|
|
|
async updateRecord(ctx) {
|
|
try {
|
|
const { id } = ctx.params;
|
|
const update = ctx.request.body;
|
|
|
|
if (!id) {
|
|
return ResponseUtil.badRequest(ctx, "缺少记录ID");
|
|
}
|
|
|
|
const existing = await DBModel.EscortRecord.findById(id);
|
|
if (!existing) {
|
|
return ResponseUtil.error(ctx, "陪诊记录不存在", null, 404);
|
|
}
|
|
if (!HandlerEscortRecord.canAccess(ctx.state.user, existing)) {
|
|
return ResponseUtil.forbidden(ctx, "无权修改该订单");
|
|
}
|
|
|
|
const isAdmin = HandlerEscortRecord.isAdmin(ctx.state.user);
|
|
// 非管理员的可改字段随订单状态收敛:终态无可改字段,进行中只剩就诊人备注
|
|
const allowFields = isAdmin
|
|
? HandlerEscortRecord.RECORD_FIELDS
|
|
: HandlerEscortRecord.ownerEditableFields(existing.status);
|
|
if (allowFields.length === 0) {
|
|
return ResponseUtil.forbidden(ctx, "已结束的订单不可修改");
|
|
}
|
|
|
|
// 非管理员只能改就诊信息类字段,费用/状态/归属/陪诊员分配不可自助修改
|
|
const payload = HandlerEscortRecord.pickFields(update, allowFields, !isAdmin);
|
|
if (Object.keys(payload).length === 0) {
|
|
// 例如进行中订单提交医院/排期:字段被状态规则过滤,明确告知而不是静默成功
|
|
return ResponseUtil.badRequest(ctx, "该订单当前状态不支持修改这些信息");
|
|
}
|
|
|
|
// 支付方式为受控枚举:管理端修改时校验,防止写入非法值
|
|
const paymentMethod = update["payment.method"] ?? update.payment?.method;
|
|
if (paymentMethod !== undefined && !HandlerEscortRecord.PAYMENT_METHODS.includes(paymentMethod)) {
|
|
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) {
|
|
const profile = await DBModel.HealthProfile.findProfileById(payload.healthProfileId);
|
|
if (!profile || String(profile.userId) !== String(existing.userId)) {
|
|
return ResponseUtil.badRequest(ctx, "就诊人档案不存在");
|
|
}
|
|
payload.patient = HandlerEscortRecord.buildPatientSnapshot(profile);
|
|
}
|
|
const service = services.find((item) => item.id === existing.escort?.serviceId);
|
|
if (!service) return ResponseUtil.badRequest(ctx, "订单关联的服务已下架");
|
|
|
|
const touchesSchedule = Object.keys(payload).some((key) => key === "schedule" || key.startsWith("schedule."));
|
|
if (touchesSchedule) {
|
|
const date = update["schedule.date"] || update.schedule?.date || existing.schedule?.date;
|
|
const startTime = update["schedule.startTime"] || update.schedule?.startTime || existing.schedule?.startTime;
|
|
const scheduleResult = HandlerEscortRecord.buildSchedule(service, date, startTime);
|
|
if (scheduleResult.error) return ResponseUtil.badRequest(ctx, scheduleResult.error);
|
|
for (const key of Object.keys(payload)) {
|
|
if (key.startsWith("schedule.")) delete payload[key];
|
|
}
|
|
// 已支付后的改期留审计时间,便于客服追溯谁在何时改过排期
|
|
if (existing.status !== "pending") {
|
|
scheduleResult.schedule.scheduleUpdatedAt = new Date();
|
|
}
|
|
payload.schedule = scheduleResult.schedule;
|
|
}
|
|
|
|
const touchesHospital = Object.keys(payload).some((key) => key === "hospital" || key.startsWith("hospital."));
|
|
if (touchesHospital) {
|
|
const province = update["hospital.province"] || update.hospital?.province || existing.hospital?.province;
|
|
if (!service.areas.includes(province)) return ResponseUtil.badRequest(ctx, "所选省份暂未开通服务");
|
|
}
|
|
|
|
const updatedRecord = await DBModel.EscortRecord.updateRecord(id, payload);
|
|
if (!updatedRecord) {
|
|
return ResponseUtil.error(ctx, "陪诊记录不存在", null, 404);
|
|
}
|
|
|
|
return ResponseUtil.success(ctx, { record: updatedRecord }, "更新成功");
|
|
} catch (err) {
|
|
return ResponseUtil.internalError(ctx, err);
|
|
}
|
|
}
|
|
|
|
async updateStatus(ctx) {
|
|
try {
|
|
const { id } = ctx.params;
|
|
const { status, reason } = ctx.request.body;
|
|
|
|
if (!id) {
|
|
return ResponseUtil.badRequest(ctx, "缺少记录ID");
|
|
}
|
|
if (!status) {
|
|
return ResponseUtil.badRequest(ctx, "缺少状态值");
|
|
}
|
|
|
|
const existing = await DBModel.EscortRecord.findById(id);
|
|
if (!existing) {
|
|
return ResponseUtil.error(ctx, "陪诊记录不存在", null, 404);
|
|
}
|
|
if (!HandlerEscortRecord.canAccess(ctx.state.user, existing)) {
|
|
return ResponseUtil.forbidden(ctx, "无权修改该订单");
|
|
}
|
|
|
|
const user = ctx.state.user;
|
|
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") {
|
|
// 用户端只能取消:未确认且未收款直接物理删除;已确认或已收款先进取消申请
|
|
if (status !== "cancelled" || !isOwner) {
|
|
return ResponseUtil.forbidden(ctx, "不支持的状态变更");
|
|
}
|
|
if (paymentStatus === "unpaid" && existing.status === "pending") {
|
|
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);
|
|
}
|
|
return ResponseUtil.success(ctx, { record: deletedRecord, deleted: true }, "订单已取消");
|
|
}
|
|
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)) {
|
|
return ResponseUtil.badRequest(ctx, "当前订单状态不允许此操作");
|
|
}
|
|
|
|
const update = { status: targetStatus };
|
|
if (targetStatus === "cancel_requested") {
|
|
if (!cancelReason) return ResponseUtil.badRequest(ctx, "请选择取消原因");
|
|
update.cancelReason = cancelReason;
|
|
update.cancelRequestedAt = new Date();
|
|
}
|
|
if (status === "cancelled") {
|
|
// 正式取消:保留申请原因;平台直接取消时补默认原因
|
|
if (cancelReason) update.cancelReason = cancelReason;
|
|
else if (role === "admin" && !existing.cancelReason) update.cancelReason = "平台取消";
|
|
update.cancelledAt = new Date();
|
|
// 已收款订单先进入退款中;线上支付随后自动原路退款,线下由平台人工核销
|
|
if (["partial", "paid"].includes(effectivePaymentStatus)) {
|
|
update["payment.status"] = "refunding";
|
|
}
|
|
}
|
|
|
|
const updatedRecord = await DBModel.EscortRecord.updateRecordStatus(id, existing.status, update);
|
|
if (!updatedRecord) {
|
|
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);
|
|
}
|
|
}
|
|
|
|
async deleteRecord(ctx) {
|
|
try {
|
|
const { id } = ctx.params;
|
|
|
|
if (!id) {
|
|
return ResponseUtil.badRequest(ctx, "缺少记录ID");
|
|
}
|
|
|
|
const existing = await DBModel.EscortRecord.findById(id);
|
|
if (!existing) {
|
|
return ResponseUtil.error(ctx, "陪诊记录不存在", null, 404);
|
|
}
|
|
|
|
// 用户端不再提供删除入口:未确认且未收款的取消已在 updateStatus 中直接物理删除。
|
|
// 这里只保留管理员的数据清理能力,且一律软删除,保留费用与服务审计链。
|
|
if (!HandlerEscortRecord.isAdmin(ctx.state.user)) {
|
|
return ResponseUtil.forbidden(ctx, "无权删除该订单");
|
|
}
|
|
|
|
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";
|
|
update.cancelReason = existing.cancelReason || "平台删除";
|
|
update.cancelledAt = update.deletedAt;
|
|
update["payment.status"] = "refunding";
|
|
}
|
|
const softDeleted = await DBModel.EscortRecord.updateRecord(id, update);
|
|
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);
|
|
}
|
|
}
|
|
}
|
|
|
|
export { HandlerEscortRecord };
|