1471 lines
65 KiB
JavaScript
1471 lines
65 KiB
JavaScript
import mongoose from "mongoose";
|
||
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,
|
||
canCancelTransition,
|
||
STATUS_TRANSITIONS,
|
||
CANCEL_STATUS_VALUES,
|
||
} 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", "inquiry", "status",
|
||
"shippingAddress",
|
||
];
|
||
|
||
// 用户自助可改字段按订单状态区分(费用、状态、陪诊员分配、档案归属一律由平台控制):
|
||
// - 待支付/已支付:可改医院与排期(改期会写审计时间)
|
||
// - 进行中:服务已开始,仅可补充病历与诉求,排期与医院不允许用户单方变更
|
||
// - 终态:全部不可改
|
||
static OWNER_NOTE_FIELDS = ["notes.patientNote", "inquiry.medicalHistory", "inquiry.demand"];
|
||
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: [...HandlerEscortRecord.OWNER_NOTE_FIELDS, "payment.payChannel", ...HandlerEscortRecord.OWNER_BOOKING_FIELDS],
|
||
confirmed: [...HandlerEscortRecord.OWNER_NOTE_FIELDS, "payment.payChannel", ...HandlerEscortRecord.OWNER_BOOKING_FIELDS],
|
||
in_progress: [...HandlerEscortRecord.OWNER_NOTE_FIELDS],
|
||
};
|
||
|
||
// 陪诊员只能写服务备注与就诊小结:改期、换医院、改患者备注、改支付渠道都属于
|
||
// 订单主人或平台管理员的权限(与 Agent 侧陪诊员工具口径一致)
|
||
static ATTENDANT_NOTE_FIELDS = ["notes.escortNote", "notes.medicalSummary"];
|
||
static ATTENDANT_EDITABLE_STATUSES = ["confirmed", "in_progress", "completed"];
|
||
|
||
// 管理端可能以嵌套对象提交这些子文档;整块 $set 会抹掉未提交字段,
|
||
// 与点号路径混用还会触发 Mongo 路径冲突,写入前统一摊平
|
||
static NESTED_OBJECT_FIELDS = ["patient", "hospital", "payment", "notes", "inquiry", "shippingAddress"];
|
||
|
||
// 用户端只能发起取消,服务完成由平台确认,避免用户端重复写入终态。
|
||
// 取消与 status 解耦:cancelStatus 为 requested 表示待确认,cancelled 表示已取消。
|
||
// 「未确认且未收款」取消即物理删除;其余先置 requested,等陪诊师/管理员确认。
|
||
// 迁移规则集中在 utils/record_state.js,与管理端 Agent 工具共用
|
||
|
||
// 支付方式为平台受控枚举(与 schema 一致),空串表示清除/未记录
|
||
static PAYMENT_METHODS = ["", "online_wechat", "offline_cash", "offline_transfer"];
|
||
|
||
// 用户下单时可选择的支付渠道:线下支付不细分现金/转账,由平台收款时补记 method
|
||
static PAY_CHANNELS = ["online_wechat", "offline"];
|
||
|
||
// 支付状态枚举,与 schema payment.status 一致
|
||
static PAYMENT_STATUSES = ["unpaid", "partial", "paid", "refunding", "refunded"];
|
||
|
||
// 日期筛选格式:只接受 YYYY-MM-DD,避免把任意字符串丢给 Date 解析
|
||
static DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
|
||
|
||
// 单页最大条数,避免 pageSize 传超大值一次拖库
|
||
static MAX_PAGE_SIZE = 200;
|
||
|
||
// 每个用户同时未完成的预约上限:超出后不允许再下单
|
||
static MAX_UNFINISHED_RECORDS = 3;
|
||
static UNFINISHED_STATUSES = ["pending", "confirmed", "in_progress"];
|
||
|
||
/**
|
||
* 统计用户当前未完成的预约数
|
||
* 未完成 = 服务未结束(待确认/已确认/进行中),且未取消、未软删除
|
||
* @param {ObjectId} userId 订单所属用户
|
||
* @returns {Promise<number>}
|
||
*/
|
||
static countUnfinishedRecords(userId) {
|
||
return DBModel.EscortRecord.countDocuments({
|
||
userId,
|
||
status: { $in: HandlerEscortRecord.UNFINISHED_STATUSES },
|
||
cancelStatus: { $ne: "cancelled" },
|
||
deletedAt: null,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 是否为管理端账号(与 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);
|
||
}
|
||
|
||
/**
|
||
* 读取登录账号的在职陪诊师档案;非在职陪诊师返回 null
|
||
* @param {ObjectId} userId 登录用户ID
|
||
*/
|
||
static async loadAttendant(userId) {
|
||
if (!userId) return null;
|
||
const employee = await DBModel.Employee.findOne({ userId })
|
||
.select("employeeNo userId role status profile.name profile.sex profile.phone attendantInfo")
|
||
.lean()
|
||
.exec();
|
||
if (!employee || employee.role !== "attendant" || employee.status !== "active") return null;
|
||
return employee;
|
||
}
|
||
|
||
// 阶段归一化:存量档案缺字段时按正式陪诊师处理
|
||
static attendantStage(employee) {
|
||
return employee?.attendantInfo?.stage === "intern" ? "intern" : "certified";
|
||
}
|
||
|
||
/**
|
||
* 服务城市匹配值
|
||
*
|
||
* 入驻/个人资料写入的是「北京市」这类带「市」的值,历史手工数据可能不带「市」,
|
||
* 查询时同时兼容两种写法,避免存量档案匹配不到订单。
|
||
*/
|
||
static cityVariants(areas) {
|
||
const set = new Set();
|
||
for (const area of Array.isArray(areas) ? areas : []) {
|
||
const text = String(area || "").trim();
|
||
if (!text) continue;
|
||
const stripped = text.replace(/市$/, "");
|
||
set.add(text);
|
||
set.add(stripped);
|
||
if (stripped) set.add(`${stripped}市`);
|
||
}
|
||
return [...set];
|
||
}
|
||
|
||
/**
|
||
* 订单是否属于陪诊师的服务城市
|
||
* 未配置城市的存量档案、未填省份的历史订单都保持可见,避免存量数据突然消失
|
||
*/
|
||
static matchesServiceArea(record, employee) {
|
||
const variants = HandlerEscortRecord.cityVariants(employee?.attendantInfo?.serviceAreas);
|
||
if (!variants.length) return true;
|
||
const province = String(record?.hospital?.province || "").trim();
|
||
if (!province) return true;
|
||
return variants.includes(province);
|
||
}
|
||
|
||
/**
|
||
* 解析用户下单时选择的陪诊师。
|
||
*
|
||
* 客户端只允许传 employeeId;姓名、电话等快照字段一律以服务端档案为准,
|
||
* 防止用户伪造陪诊师信息。未选择时返回 { employee: null },订单进入公共订单池。
|
||
* @param {Object} input 客户端提交的 attendant
|
||
* @returns {Promise<{ employee?: Object, snapshot?: Object, error?: string }>}
|
||
*/
|
||
static async resolveSelectedAttendant(input) {
|
||
const employeeId = input?.employeeId;
|
||
if (!employeeId) return { employee: null };
|
||
|
||
if (!mongoose.Types.ObjectId.isValid(employeeId)) {
|
||
return { error: "所选陪诊师ID不合法" };
|
||
}
|
||
|
||
const employee = await DBModel.Employee.findOne({
|
||
_id: employeeId,
|
||
role: "attendant",
|
||
status: "active",
|
||
}).lean().exec();
|
||
if (!employee) return { error: "所选陪诊师不存在或已不在职" };
|
||
// 与用户选择、管理端指派的口径一致:实习陪诊师不可被指定
|
||
if (HandlerEscortRecord.attendantStage(employee) === "intern") {
|
||
return { error: "实习陪诊师暂不能被指定" };
|
||
}
|
||
if (!employee.userId) {
|
||
return { error: "所选陪诊师暂不可接单,请选择其他陪诊师" };
|
||
}
|
||
|
||
const profile = employee.profile || {};
|
||
return {
|
||
employee,
|
||
snapshot: {
|
||
id: employee.userId,
|
||
name: profile.name || "",
|
||
sex: ["male", "female"].includes(profile.sex) ? profile.sex : "none",
|
||
mobile: profile.phone || "",
|
||
},
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 回写陪诊师累计接单数。
|
||
*
|
||
* 只在订单成功归属到陪诊师之后调用;写失败不回滚已完成的接单,
|
||
* 只记日志,避免陪诊师明明接到了单却被接口报成失败。
|
||
* @param {ObjectId} employeeId 员工档案ID(不是登录 userId)
|
||
*/
|
||
static async bumpAttendantOrderCount(employeeId) {
|
||
if (!employeeId) return;
|
||
try {
|
||
await DBModel.Employee.incrementOrderCount(employeeId);
|
||
} catch (err) {
|
||
logger.error(`[escort] 回写陪诊师接单数失败 employeeId=${employeeId}: ${err?.message || err}`);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 陪诊师能否查看订单详情:未分配订单、本人已接订单、被共享的订单
|
||
* 实习陪诊师同样可以看到未分配订单,但接单会被 acceptRecord 拦截
|
||
*/
|
||
static canAttendantViewRecord(record, employee, userId) {
|
||
if (!record || !employee) return false;
|
||
const employeeId = String(employee._id);
|
||
const sharedWith = Array.isArray(record.attendant?.sharedWith) ? record.attendant.sharedWith : [];
|
||
if (sharedWith.some((id) => String(id) === employeeId)) return true;
|
||
if (!record.attendant?.id) {
|
||
// 未分配订单:只有本服务城市的陪诊师可查看
|
||
return HandlerEscortRecord.matchesServiceArea(record, employee);
|
||
}
|
||
return String(record.attendant.id) === String(userId);
|
||
}
|
||
|
||
// 手机号脱敏:保留前三后四,避免未接单前泄露完整联系方式
|
||
static maskMobile(mobile) {
|
||
const text = String(mobile || "");
|
||
if (!text) return "";
|
||
if (text.length < 7) return "****";
|
||
return `${text.slice(0, 3)}****${text.slice(-4)}`;
|
||
}
|
||
|
||
// 姓名脱敏:未接单前只暴露姓
|
||
static maskName(name) {
|
||
const text = String(name || "");
|
||
return text ? `${text.slice(0, 1)}**` : "";
|
||
}
|
||
|
||
// 共享对象入参:兼容 employeeId 与 employeeIds,去重并过滤非法 ObjectId
|
||
static parseShareEmployeeIds(body = {}) {
|
||
const raw = body.employeeIds !== undefined ? body.employeeIds : body.employeeId;
|
||
const list = Array.isArray(raw) ? raw : [raw];
|
||
const ids = list
|
||
.filter((id) => typeof id === "string" && /^[0-9a-fA-F]{24}$/.test(id))
|
||
.map((id) => String(id));
|
||
return [...new Set(ids)];
|
||
}
|
||
|
||
/**
|
||
* 陪诊师视角补充展示字段:
|
||
* - attendantAssignedToMe / attendantSharedToMe / isPoolOrder 供前端决定按钮
|
||
* - 实习陪诊师看未分配订单时脱敏手机号、详细地址、病历号等
|
||
* @param {Object} record 已转成普通对象的订单
|
||
* @param {Object} employee 当前陪诊师档案
|
||
*/
|
||
static decorateAttendantRecord(record, employee) {
|
||
if (!record) return record;
|
||
const employeeId = String(employee?._id || "");
|
||
const sharedWith = Array.isArray(record.attendant?.sharedWith)
|
||
? record.attendant.sharedWith.map((id) => String(id))
|
||
: [];
|
||
const assignedToMe = Boolean(record.attendant?.id)
|
||
&& String(record.attendant.id) === String(employee?.userId || "");
|
||
const isPoolOrder = !record.attendant?.id;
|
||
|
||
record.attendantAssignedToMe = assignedToMe;
|
||
record.attendantSharedToMe = employeeId ? sharedWith.includes(employeeId) : false;
|
||
record.attendantSharedEmployeeIds = sharedWith;
|
||
record.isPoolOrder = isPoolOrder;
|
||
// 共享名单是内部协作信息,不整体回传
|
||
if (record.attendant) delete record.attendant.sharedWith;
|
||
|
||
if (HandlerEscortRecord.attendantStage(employee) === "intern" && isPoolOrder) {
|
||
record.desensitized = true;
|
||
if (record.patient) {
|
||
record.patient.name = HandlerEscortRecord.maskName(record.patient.name);
|
||
record.patient.mobile = HandlerEscortRecord.maskMobile(record.patient.mobile);
|
||
}
|
||
if (record.hospital) {
|
||
if (record.hospital.address) record.hospital.address = "接单后可见";
|
||
if (record.hospital.medicalRecordNo) record.hospital.medicalRecordNo = "接单后可见";
|
||
}
|
||
if (record.shippingAddress) {
|
||
record.shippingAddress.recipientName = HandlerEscortRecord.maskName(record.shippingAddress.recipientName);
|
||
record.shippingAddress.mobile = HandlerEscortRecord.maskMobile(record.shippingAddress.mobile);
|
||
if (record.shippingAddress.address) record.shippingAddress.address = "接单后可见";
|
||
}
|
||
if (record.inquiry?.medicalHistory) record.inquiry.medicalHistory = "接单后可见";
|
||
// 诉求是用户自由文本,可能夹带联系方式,一并脱敏
|
||
if (record.inquiry?.demand) record.inquiry.demand = "接单后可见";
|
||
}
|
||
return record;
|
||
}
|
||
|
||
/**
|
||
* 输出给前端的订单视图:追加支付窗口终点,供列表/详情判断「支付已超时」。
|
||
* 只派生展示字段,不写库。
|
||
* @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;
|
||
}
|
||
|
||
/**
|
||
* 把嵌套子文档摊平成点号路径,并与现值合并。
|
||
*
|
||
* 两个问题一起解决:
|
||
* 1. 整块 $set payment 会抹掉未提交的 status / paymentRecordId / refundNo;
|
||
* 2. $set 同时出现 payment 与 payment.payChannel 会触发 Mongo 路径冲突。
|
||
*
|
||
* @param {Object} payload 待写入字段
|
||
* @param {Object} existing 数据库中的当前订单
|
||
* @returns {Object}
|
||
*/
|
||
static flattenNestedFields(payload, existing) {
|
||
for (const field of HandlerEscortRecord.NESTED_OBJECT_FIELDS) {
|
||
const incoming = payload[field];
|
||
if (!incoming || typeof incoming !== "object" || Array.isArray(incoming)) continue;
|
||
|
||
const current = existing?.[field];
|
||
const merged = {
|
||
...(current && typeof current === "object" ? current : {}),
|
||
...incoming,
|
||
};
|
||
for (const [key, value] of Object.entries(merged)) {
|
||
const path = `${field}.${key}`;
|
||
// 请求里显式提交的点号路径优先,不被嵌套对象覆盖
|
||
if (payload[path] === undefined) payload[path] = value;
|
||
}
|
||
delete payload[field];
|
||
}
|
||
return payload;
|
||
}
|
||
|
||
// 解析分页参数并夹紧上限,防止超大 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);
|
||
}
|
||
|
||
// 预约开始时间的最晚档位:所有服务统一可约到 23:30(整点/半点)
|
||
static LATEST_START_MINUTES = 23 * 60 + 30;
|
||
|
||
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: "预约时间格式不正确" };
|
||
// 与原班次起点一致时沿用该班次;其余开始时刻从服务最早时段起、统一放宽到 23:30
|
||
const session = booking.sessions.find((item) => item.start === startTime)
|
||
|| booking.sessions.find((item) => startMinutes >= HandlerEscortRecord.timeToMinutes(item.start)
|
||
&& startMinutes <= HandlerEscortRecord.LATEST_START_MINUTES);
|
||
if (!session) return { error: "所选时间不在该服务的可预约时段内" };
|
||
|
||
// 非原班次起点:结束时刻按服务时长顺延,跨天按 24 小时取模
|
||
const endTime = session.start === startTime
|
||
? session.end
|
||
: (() => {
|
||
const endMinutes = (startMinutes + booking.durationMinutes) % 1440;
|
||
return `${String(Math.floor(endMinutes / 60)).padStart(2, "0")}:${String(endMinutes % 60).padStart(2, "0")}`;
|
||
})();
|
||
return {
|
||
schedule: {
|
||
date,
|
||
startTime,
|
||
endTime,
|
||
duration: Number(booking.durationMinutes) || 0,
|
||
},
|
||
};
|
||
}
|
||
|
||
static buildShippingAddress(source, profile) {
|
||
// 地址选填:跑腿/买药未填时由客服线下确认,仅保存快照
|
||
const address = String(source?.address || "").trim();
|
||
return {
|
||
shippingAddress: {
|
||
recipientName: profile.profile?.name || "",
|
||
mobile: profile.profile?.mobile || "",
|
||
address,
|
||
},
|
||
};
|
||
}
|
||
|
||
// 按条件查询记录(管理端,可查全部)
|
||
async getRecords(ctx) {
|
||
return this._listRecords(ctx, "all");
|
||
}
|
||
|
||
// 查询"我的"记录:强制以登录用户身份查询,忽略 query 中的 userId
|
||
async getMyRecords(ctx) {
|
||
return this._listRecords(ctx, "self");
|
||
}
|
||
|
||
// 陪诊员本人名下订单:强制以登录用户为陪诊员,忽略 query 中的 userId。
|
||
// 过滤、分页、计数与支付窗口口径与管理员列表保持一致
|
||
async getAttendantRecords(ctx) {
|
||
return this._listRecords(ctx, "attendant");
|
||
}
|
||
|
||
/**
|
||
* 列表统一入口
|
||
* @param {Object} ctx Koa 上下文
|
||
* @param {"all"|"self"|"attendant"} mode all=管理员全量;self=订单所属用户本人;attendant=陪诊员本人名下
|
||
*/
|
||
async _listRecords(ctx, mode) {
|
||
try {
|
||
const {
|
||
status, userId, appointmentDate, healthProfileId, cancelStatus, includeCancelled,
|
||
paymentStatus, payChannel, startDate, endDate, keyword, scope,
|
||
} = ctx.request.query;
|
||
const { page, pageSize } = HandlerEscortRecord.parsePaging(ctx.request.query);
|
||
const loginUserId = ctx.state.user?._id;
|
||
if (!loginUserId) {
|
||
return ResponseUtil.unauthorized(ctx, "登录已失效");
|
||
}
|
||
// 陪诊员模式不允许通过 query 改查他人订单;管理员模式保留按 userId 筛选
|
||
const effectiveUserId = mode === "self"
|
||
? loginUserId
|
||
: (mode === "all" ? userId : undefined);
|
||
let attendantId;
|
||
let attendantVisibility;
|
||
let attendantEmployee = null;
|
||
let isInternAttendant = false;
|
||
if (mode === "attendant") {
|
||
attendantEmployee = await HandlerEscortRecord.loadAttendant(loginUserId);
|
||
if (!attendantEmployee) {
|
||
return ResponseUtil.forbidden(ctx, "仅在职陪诊师可查看订单");
|
||
}
|
||
const isIntern = HandlerEscortRecord.attendantStage(attendantEmployee) === "intern";
|
||
isInternAttendant = isIntern;
|
||
// 可见范围由身份决定,前端传什么都会被忽略:
|
||
// 实习 = 未分配 + 被共享;正式 = 未分配 + 本人已接 + 被共享
|
||
// scope 只用于在已授权的可见范围内收窄(pool=未分配 / mine=我的),不扩大范围
|
||
const mineVisibility = {
|
||
userId: isIntern ? undefined : loginUserId,
|
||
employeeId: attendantEmployee._id,
|
||
};
|
||
// 订单池只展示本服务城市的订单;本人已接/被共享的订单不受城市限制
|
||
const poolCities = HandlerEscortRecord.cityVariants(
|
||
attendantEmployee.attendantInfo?.serviceAreas
|
||
);
|
||
const scopeValue = String(scope || "");
|
||
if (scopeValue === "pool") {
|
||
attendantVisibility = { includeUnassigned: true, poolCities };
|
||
} else if (scopeValue === "mine") {
|
||
attendantVisibility = mineVisibility;
|
||
} else {
|
||
attendantVisibility = { includeUnassigned: true, poolCities, ...mineVisibility };
|
||
}
|
||
}
|
||
|
||
// 管理端订单页同样按「未分配 / 我的」分栏:
|
||
// pool=只看未分配,mine=只看指派给当前账号的订单,不传保持全量
|
||
if (mode === "all") {
|
||
const scopeValue = String(scope || "");
|
||
if (scopeValue === "pool") {
|
||
attendantVisibility = { includeUnassigned: true };
|
||
} else if (scopeValue === "mine") {
|
||
attendantId = loginUserId;
|
||
}
|
||
}
|
||
|
||
// 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, "订单状态筛选值不正确");
|
||
}
|
||
|
||
// 取消状态筛选:none / requested / cancelled
|
||
let cancelStatusArray = null;
|
||
if (cancelStatus && String(cancelStatus).length > 0) {
|
||
cancelStatusArray = String(cancelStatus).split(',').filter(Boolean);
|
||
if (cancelStatusArray.some((item) => !CANCEL_STATUS_VALUES.includes(item))) {
|
||
return ResponseUtil.badRequest(ctx, "订单取消状态筛选值不正确");
|
||
}
|
||
}
|
||
|
||
// 支付状态筛选:unpaid / partial / paid / refunding / refunded
|
||
let paymentStatusArray = null;
|
||
if (paymentStatus && String(paymentStatus).length > 0) {
|
||
paymentStatusArray = String(paymentStatus).split(',').filter(Boolean);
|
||
if (paymentStatusArray.some((item) => !HandlerEscortRecord.PAYMENT_STATUSES.includes(item))) {
|
||
return ResponseUtil.badRequest(ctx, "支付状态筛选值不正确");
|
||
}
|
||
}
|
||
|
||
if (payChannel && !HandlerEscortRecord.PAY_CHANNELS.includes(payChannel)) {
|
||
return ResponseUtil.badRequest(ctx, "支付渠道筛选值不正确");
|
||
}
|
||
|
||
for (const [name, value] of [["startDate", startDate], ["endDate", endDate], ["appointmentDate", appointmentDate]]) {
|
||
if (value && !HandlerEscortRecord.DATE_PATTERN.test(String(value))) {
|
||
return ResponseUtil.badRequest(ctx, `${name === "appointmentDate" ? "预约日期" : name === "startDate" ? "开始日期" : "结束日期"}格式应为 YYYY-MM-DD`);
|
||
}
|
||
}
|
||
|
||
const result = await DBModel.EscortRecord.findRecordPage({
|
||
page,
|
||
pageSize,
|
||
status: statusArray,
|
||
cancelStatus: cancelStatusArray,
|
||
includeCancelled: ["1", "true"].includes(String(includeCancelled)),
|
||
userId: effectiveUserId,
|
||
attendantId,
|
||
attendantVisibility,
|
||
appointmentDate,
|
||
healthProfileId,
|
||
paymentStatus: paymentStatusArray,
|
||
payChannel,
|
||
startDate,
|
||
endDate,
|
||
// 实习看池订单只有脱敏展示,keyword 仍按原文匹配手机号/姓名会形成
|
||
// 「确认某手机号存在订单」的侧信道,直接忽略其搜索词
|
||
keyword: mode === "attendant" && isInternAttendant ? undefined : keyword,
|
||
});
|
||
|
||
const records = result.records.map((record) => {
|
||
const plain = HandlerEscortRecord.withPaymentWindow(record);
|
||
// 陪诊员列表:补充接单/共享标记,实习看未分配订单时脱敏
|
||
return mode === "attendant"
|
||
? HandlerEscortRecord.decorateAttendantRecord(plain, attendantEmployee)
|
||
: plain;
|
||
});
|
||
return ResponseUtil.success(ctx, { ...result, records, page, pageSize }, "查询成功");
|
||
} 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.findRecordById(id);
|
||
if (!record) {
|
||
return ResponseUtil.error(ctx, "陪诊记录不存在", null, 404);
|
||
}
|
||
const user = ctx.state.user;
|
||
const isOwner = String(record.userId) === String(user?._id);
|
||
let employee = null;
|
||
if (!HandlerEscortRecord.isAdmin(user) && !isOwner) {
|
||
// 陪诊师:本人已接、被共享或未分配订单可查看,其余按无权限处理
|
||
employee = await HandlerEscortRecord.loadAttendant(user?._id);
|
||
if (!HandlerEscortRecord.canAccess(user, record)
|
||
&& !HandlerEscortRecord.canAttendantViewRecord(record, employee, user?._id)) {
|
||
return ResponseUtil.forbidden(ctx, "无权访问该订单");
|
||
}
|
||
}
|
||
|
||
const plain = HandlerEscortRecord.withPaymentWindow(record);
|
||
if (employee) HandlerEscortRecord.decorateAttendantRecord(plain, employee);
|
||
return ResponseUtil.success(ctx, { record: plain }, "查询成功");
|
||
} catch (err) {
|
||
return ResponseUtil.internalError(ctx, err);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 接单:正式陪诊师把未分配订单接到自己名下。
|
||
* 与支付状态无关;条件更新保证并发下只有一人成功。
|
||
*/
|
||
async acceptRecord(ctx) {
|
||
try {
|
||
const { id } = ctx.params;
|
||
if (!id) return ResponseUtil.badRequest(ctx, "缺少记录ID");
|
||
|
||
const userId = ctx.state.user?._id;
|
||
const employee = await HandlerEscortRecord.loadAttendant(userId);
|
||
if (!employee) return ResponseUtil.forbidden(ctx, "仅在职陪诊师可接单");
|
||
if (HandlerEscortRecord.attendantStage(employee) === "intern") {
|
||
return ResponseUtil.forbidden(ctx, "实习陪诊师暂不能接单");
|
||
}
|
||
|
||
const record = await DBModel.EscortRecord.findById(id);
|
||
if (!record || record.deletedAt) return ResponseUtil.notFound(ctx, "陪诊记录不存在");
|
||
// 取消中/已取消的订单不进入接单:取消一旦被确认,刚接单的陪诊师会直接失去订单
|
||
if (record.cancelStatus === "cancelled" || record.status === "cancelled") {
|
||
return ResponseUtil.error(ctx, "订单已取消,无法接单", null, 409);
|
||
}
|
||
if (record.cancelStatus === "requested") {
|
||
return ResponseUtil.error(ctx, "订单取消申请确认中,暂不能接单", null, 409);
|
||
}
|
||
if (record.attendant?.id) {
|
||
return ResponseUtil.error(ctx, "订单已被其他陪诊师接单", null, 409);
|
||
}
|
||
// 订单池只展示本城市订单;这里再挡一次,防止绕过列表直接调接口接单
|
||
if (!HandlerEscortRecord.matchesServiceArea(record, employee)) {
|
||
return ResponseUtil.forbidden(ctx, "该订单不在你的服务城市");
|
||
}
|
||
|
||
const profile = employee.profile || {};
|
||
const updated = await DBModel.EscortRecord.acceptRecord(id, {
|
||
id: userId,
|
||
name: profile.name || "",
|
||
sex: ["male", "female"].includes(profile.sex) ? profile.sex : "none",
|
||
mobile: profile.phone || "",
|
||
});
|
||
// 并发下另一个陪诊师先接走:条件更新返回 null
|
||
if (!updated) {
|
||
return ResponseUtil.error(ctx, "订单已被其他陪诊师接单", null, 409);
|
||
}
|
||
|
||
await HandlerEscortRecord.bumpAttendantOrderCount(employee._id);
|
||
|
||
const plain = HandlerEscortRecord.withPaymentWindow(updated);
|
||
HandlerEscortRecord.decorateAttendantRecord(plain, employee);
|
||
return ResponseUtil.success(ctx, { record: plain }, "接单成功");
|
||
} catch (err) {
|
||
return ResponseUtil.internalError(ctx, err);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 管理员指派:把未分配订单指派给在职正式陪诊师。
|
||
* 与陪诊师抢单共用条件更新,保证并发下只有一次归属成功。
|
||
*/
|
||
async assignRecord(ctx) {
|
||
try {
|
||
const { id } = ctx.params;
|
||
if (!id) return ResponseUtil.badRequest(ctx, "缺少记录ID");
|
||
if (!mongoose.Types.ObjectId.isValid(id)) {
|
||
return ResponseUtil.badRequest(ctx, "记录ID不合法");
|
||
}
|
||
|
||
const employeeId = String(ctx.request.body?.employeeId || "");
|
||
if (!mongoose.Types.ObjectId.isValid(employeeId)) {
|
||
return ResponseUtil.badRequest(ctx, "请选择陪诊师");
|
||
}
|
||
|
||
const employee = await DBModel.Employee.findOne({
|
||
_id: employeeId,
|
||
role: "attendant",
|
||
status: "active",
|
||
}).lean().exec();
|
||
if (!employee) {
|
||
return ResponseUtil.badRequest(ctx, "陪诊师不存在或已不在职");
|
||
}
|
||
// 实习陪诊师不可被指派,与用户选择、系统派单的口径一致
|
||
if (HandlerEscortRecord.attendantStage(employee) === "intern") {
|
||
return ResponseUtil.badRequest(ctx, "实习陪诊师暂不能被指派");
|
||
}
|
||
// 指派写入的是登录 userId,未绑定账号的档案指派后无法在小程序看到订单
|
||
if (!employee.userId) {
|
||
return ResponseUtil.badRequest(ctx, "该陪诊师未绑定登录账号,无法指派");
|
||
}
|
||
|
||
const record = await DBModel.EscortRecord.findById(id);
|
||
if (!record || record.deletedAt) return ResponseUtil.notFound(ctx, "陪诊记录不存在");
|
||
if (record.cancelStatus === "cancelled" || record.status === "cancelled") {
|
||
return ResponseUtil.error(ctx, "订单已取消,无法指派", null, 409);
|
||
}
|
||
if (record.cancelStatus === "requested") {
|
||
return ResponseUtil.error(ctx, "订单取消申请确认中,暂不能指派", null, 409);
|
||
}
|
||
if (record.attendant?.id) {
|
||
return ResponseUtil.error(ctx, "订单已分配陪诊师", null, 409);
|
||
}
|
||
|
||
const profile = employee.profile || {};
|
||
const updated = await DBModel.EscortRecord.acceptRecord(id, {
|
||
id: employee.userId,
|
||
name: profile.name || "",
|
||
sex: ["male", "female"].includes(profile.sex) ? profile.sex : "none",
|
||
mobile: profile.phone || "",
|
||
});
|
||
// 并发下已被陪诊师接走或另一管理员先指派
|
||
if (!updated) {
|
||
return ResponseUtil.error(ctx, "订单已分配陪诊师", null, 409);
|
||
}
|
||
|
||
await HandlerEscortRecord.bumpAttendantOrderCount(employee._id);
|
||
|
||
return ResponseUtil.success(
|
||
ctx,
|
||
{ record: HandlerEscortRecord.withPaymentWindow(updated) },
|
||
"指派成功"
|
||
);
|
||
} catch (err) {
|
||
return ResponseUtil.internalError(ctx, err);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 共享订单:仅接单陪诊师本人可操作,共享对象为所有在职陪诊师(含实习)
|
||
*/
|
||
async shareRecord(ctx) {
|
||
try {
|
||
const { id } = ctx.params;
|
||
if (!id) return ResponseUtil.badRequest(ctx, "缺少记录ID");
|
||
|
||
const userId = ctx.state.user?._id;
|
||
const employee = await HandlerEscortRecord.loadAttendant(userId);
|
||
if (!employee) return ResponseUtil.forbidden(ctx, "仅在职陪诊师可共享订单");
|
||
|
||
const record = await DBModel.EscortRecord.findById(id);
|
||
if (!record) return ResponseUtil.notFound(ctx, "陪诊记录不存在");
|
||
if (record.cancelStatus === "cancelled" || record.status === "cancelled") {
|
||
return ResponseUtil.error(ctx, "订单已取消,无法共享", null, 409);
|
||
}
|
||
if (String(record.attendant?.id || "") !== String(userId)) {
|
||
return ResponseUtil.forbidden(ctx, "只有接单陪诊师可以共享该订单");
|
||
}
|
||
|
||
const requested = HandlerEscortRecord.parseShareEmployeeIds(ctx.request.body || {});
|
||
if (requested.length === 0) return ResponseUtil.badRequest(ctx, "请选择要共享的陪诊师");
|
||
|
||
// 共享对象必须是在职陪诊师;不允许共享给自己
|
||
const targets = await DBModel.Employee.find({
|
||
_id: { $in: requested },
|
||
role: "attendant",
|
||
status: "active",
|
||
}).select("_id").lean().exec();
|
||
const employeeIds = targets
|
||
.map((item) => String(item._id))
|
||
.filter((employeeId) => employeeId !== String(employee._id));
|
||
if (employeeIds.length === 0) {
|
||
return ResponseUtil.badRequest(ctx, "共享对象不存在或不是在职陪诊师");
|
||
}
|
||
|
||
const updated = await DBModel.EscortRecord.addSharedWith(id, userId, employeeIds);
|
||
if (!updated) return ResponseUtil.forbidden(ctx, "只有接单陪诊师可以共享该订单");
|
||
|
||
const plain = HandlerEscortRecord.withPaymentWindow(updated);
|
||
HandlerEscortRecord.decorateAttendantRecord(plain, employee);
|
||
return ResponseUtil.success(ctx, { record: plain }, "共享成功");
|
||
} catch (err) {
|
||
return ResponseUtil.internalError(ctx, err);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 取消共享:仅接单陪诊师本人可操作
|
||
*/
|
||
async unshareRecord(ctx) {
|
||
try {
|
||
const { id } = ctx.params;
|
||
if (!id) return ResponseUtil.badRequest(ctx, "缺少记录ID");
|
||
|
||
const userId = ctx.state.user?._id;
|
||
const employee = await HandlerEscortRecord.loadAttendant(userId);
|
||
if (!employee) return ResponseUtil.forbidden(ctx, "仅在职陪诊师可操作共享");
|
||
|
||
// 与 shareRecord 对齐:订单不存在按 404,已取消不允许再操作共享名单
|
||
const record = await DBModel.EscortRecord.findById(id);
|
||
if (!record) return ResponseUtil.notFound(ctx, "陪诊记录不存在");
|
||
if (record.cancelStatus === "cancelled" || record.status === "cancelled") {
|
||
return ResponseUtil.error(ctx, "订单已取消,无法操作共享", null, 409);
|
||
}
|
||
|
||
const employeeIds = HandlerEscortRecord.parseShareEmployeeIds(ctx.request.body || {});
|
||
if (employeeIds.length === 0) return ResponseUtil.badRequest(ctx, "请选择要取消共享的陪诊师");
|
||
|
||
const updated = await DBModel.EscortRecord.removeSharedWith(id, userId, employeeIds);
|
||
if (!updated) return ResponseUtil.forbidden(ctx, "只有接单陪诊师可以取消共享");
|
||
|
||
const plain = HandlerEscortRecord.withPaymentWindow(updated);
|
||
HandlerEscortRecord.decorateAttendantRecord(plain, employee);
|
||
return ResponseUtil.success(ctx, { record: plain }, "已取消共享");
|
||
} 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, "下单幂等标识格式不正确");
|
||
}
|
||
|
||
// 订单必须关联就诊人:patient 是下单当刻的快照,healthProfileId 才是关联
|
||
if (!body.healthProfileId) {
|
||
return ResponseUtil.badRequest(ctx, "缺少就诊人档案ID");
|
||
}
|
||
|
||
// 档案锚定归属:订单归属取档案的 userId。
|
||
// 管理员代客下单不传 userId(传了也忽略),档案无归属时订单 userId 留空,后期可在订单编辑中补录;
|
||
// 非管理员仍要求档案属于本人,避免把订单挂到他人档案上
|
||
const isAdmin = HandlerEscortRecord.isAdmin(ctx.state.user);
|
||
const profile = await DBModel.HealthProfile.findProfileById(body.healthProfileId);
|
||
if (!profile) {
|
||
return ResponseUtil.badRequest(ctx, "就诊人档案不存在");
|
||
}
|
||
if (!isAdmin && String(profile.userId || "") !== String(userId)) {
|
||
return ResponseUtil.badRequest(ctx, "就诊人档案不存在");
|
||
}
|
||
const orderUserId = profile.userId || null;
|
||
|
||
if (idempotencyKey) {
|
||
const existing = await DBModel.EscortRecord.findByIdempotencyKey(orderUserId, idempotencyKey);
|
||
if (existing) return ResponseUtil.success(ctx, { record: existing }, "订单已创建");
|
||
}
|
||
|
||
// 服务项目、服务名称、区域、排期与价格均以服务端目录为准。
|
||
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(body.shippingAddress, profile);
|
||
|
||
const payload = HandlerEscortRecord.pickFields(body);
|
||
// 下单时指定陪诊师:只认 employeeId,快照字段由服务端回填。
|
||
// 管理员用用户端下单也要走这条解析:否则会把客户端原样的 { employeeId }
|
||
// 落库(name/mobile 走默认空串、id 缺失),详情页会误显示「待分配」。
|
||
// 未指定则清空,订单进入公共订单池等待抢单或管理端指派。
|
||
let selectedEmployee = null;
|
||
if (body.attendant?.employeeId) {
|
||
const selected = await HandlerEscortRecord.resolveSelectedAttendant(body.attendant);
|
||
if (selected.error) return ResponseUtil.badRequest(ctx, selected.error);
|
||
selectedEmployee = selected.employee;
|
||
payload.attendant = { ...selected.snapshot, sharedWith: [] };
|
||
} else if (!isAdmin) {
|
||
// 用户端不接受客户端自带的姓名 / 电话快照
|
||
delete payload.attendant;
|
||
}
|
||
// 归属以档案为准:管理员传入的 userId 一律忽略,无归属档案留空
|
||
payload.userId = orderUserId;
|
||
// 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 (isAdmin) {
|
||
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 (isAdmin
|
||
&& HandlerEscortRecord.PAYMENT_METHODS.includes(body.payment?.method)) {
|
||
payload.payment.method = body.payment.method;
|
||
}
|
||
|
||
// 每个用户同时最多 3 个未完成预约,超出则不再允许新增。
|
||
// 无归属订单(代客下单且档案未关联客户)跳过:否则会按全部无主订单全局误拦
|
||
if (orderUserId) {
|
||
const unfinishedCount = await HandlerEscortRecord.countUnfinishedRecords(orderUserId);
|
||
if (unfinishedCount >= HandlerEscortRecord.MAX_UNFINISHED_RECORDS) {
|
||
return ResponseUtil.badRequest(
|
||
ctx,
|
||
`每个用户最多同时保留${HandlerEscortRecord.MAX_UNFINISHED_RECORDS}个未完成的预约,请先完成或取消已有预约后再下单`
|
||
);
|
||
}
|
||
}
|
||
|
||
try {
|
||
const newRecord = await DBModel.EscortRecord.createRecord(payload);
|
||
// 用户指定陪诊师即视为接单成功,累计接单数按同一口径回写
|
||
if (selectedEmployee) {
|
||
await HandlerEscortRecord.bumpAttendantOrderCount(selectedEmployee._id);
|
||
}
|
||
return ResponseUtil.success(ctx, { record: newRecord }, "创建成功");
|
||
} catch (err) {
|
||
// 并发重复提交由唯一索引兜底,后到的请求返回已创建订单。
|
||
if (err?.code === 11000 && idempotencyKey) {
|
||
const existing = await DBModel.EscortRecord.findByIdempotencyKey(orderUserId, 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 isOwner = String(existing.userId || "") === String(ctx.state.user?._id || "");
|
||
// 兼容旧数据:取消曾存放在 status 中
|
||
const cancelStatus = existing.status === "cancelled"
|
||
? "cancelled"
|
||
: (existing.cancelStatus || "none");
|
||
// 可改字段按角色收敛:
|
||
// - 管理员:全字段(状态仍需过状态机)
|
||
// - 订单主人:按订单状态收敛,终态/取消中一律冻结
|
||
// - 陪诊员(canAccess 已保证非管理员非主人时只能是该单陪诊员):仅服务备注与就诊小结
|
||
let allowFields;
|
||
if (isAdmin) {
|
||
allowFields = HandlerEscortRecord.RECORD_FIELDS;
|
||
} else if (isOwner) {
|
||
allowFields = cancelStatus !== "none"
|
||
? []
|
||
: HandlerEscortRecord.ownerEditableFields(existing.status);
|
||
} else {
|
||
allowFields = cancelStatus === "none"
|
||
&& HandlerEscortRecord.ATTENDANT_EDITABLE_STATUSES.includes(existing.status)
|
||
? HandlerEscortRecord.ATTENDANT_NOTE_FIELDS
|
||
: [];
|
||
}
|
||
if (allowFields.length === 0) {
|
||
return ResponseUtil.forbidden(
|
||
ctx,
|
||
cancelStatus !== "none" ? "订单取消中或已取消,不可修改" : "该订单当前状态不支持修改"
|
||
);
|
||
}
|
||
|
||
// 非管理员只能改就诊信息类字段,费用/状态/归属/陪诊员分配不可自助修改;
|
||
// 陪诊员的 allowFields 已收敛为备注字段
|
||
const payload = HandlerEscortRecord.pickFields(update, allowFields, !isAdmin);
|
||
if (Object.keys(payload).length === 0) {
|
||
// 例如进行中订单提交医院/排期:字段被状态规则过滤,明确告知而不是静默成功
|
||
return ResponseUtil.badRequest(ctx, "该订单当前状态不支持修改这些信息");
|
||
}
|
||
|
||
// 状态迁移必须走状态机:通用更新接口此前可直接把 completed 改回 in_progress
|
||
if (payload.status !== undefined && payload.status !== existing.status) {
|
||
if (cancelStatus !== "none") {
|
||
return ResponseUtil.badRequest(ctx, "订单取消中或已取消,不能修改服务状态");
|
||
}
|
||
if (!canTransition(existing.status, payload.status)) {
|
||
return ResponseUtil.badRequest(ctx, "当前订单状态不允许此操作");
|
||
}
|
||
}
|
||
|
||
// 嵌套子文档摊平为点号路径,避免整块覆盖与路径冲突
|
||
HandlerEscortRecord.flattenNestedFields(payload, existing);
|
||
|
||
// 已收款订单一律锁定支付状态与实收金额:否则编辑退款中的订单会把它改回未支付,
|
||
// 用户可再次支付造成重复扣款;金额改动也会与 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)) {
|
||
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 (cancelStatus !== "none") {
|
||
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) {
|
||
// 已支付不能改渠道:这里只提示刷新,不主动退款。
|
||
// 否则会得到一张「仍在履约、款项已退」的死单,用户既不能再付也不能切线下
|
||
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, "订单存在未支付流水,请先关闭或取消后再修改金额");
|
||
}
|
||
}
|
||
}
|
||
|
||
// 档案归属校验:档案必须属于订单所属用户,避免把订单挂到他人档案上;
|
||
// 通过后同步刷新订单里的就诊人快照。
|
||
// 空值等价比较:无归属订单(userId 为空)可以关联无归属档案
|
||
if (payload.healthProfileId) {
|
||
const profile = await DBModel.HealthProfile.findProfileById(payload.healthProfileId);
|
||
const sameOwner = (a, b) => String(a || "") === String(b || "");
|
||
if (!profile || !sameOwner(profile.userId, existing.userId)) {
|
||
return ResponseUtil.badRequest(ctx, "就诊人档案不存在");
|
||
}
|
||
// 快照整体覆盖前清掉摊平后的 patient.*,避免与 patient 对象路径冲突
|
||
for (const key of Object.keys(payload)) {
|
||
if (key === "patient" || key.startsWith("patient.")) delete payload[key];
|
||
}
|
||
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;
|
||
// 用户端与管理端共用本接口,按调用方 app 区分取消流程:
|
||
// appId 只用于收紧权限——即使账号同时带管理员角色,从用户端小程序发起的取消
|
||
// 也必须走取消申请,否则会在 C 端绕过「已确认订单需人工确认」直接退款。
|
||
// 管理端固定带 appId=wxapp_companion;未带 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 isAssignedAttendant = role === "attendant"
|
||
&& String(existing.attendant?.id || "") === String(user?._id || "");
|
||
// 陪诊员身份只赋予其名下订单的管理权。订单主人即使同时是在职陪诊员,
|
||
// 对未分配给自己的订单也只能走用户取消流程,不能自行确认或完成服务。
|
||
const canManageOrder = role === "admin" || isAssignedAttendant;
|
||
const paymentStatus = existing.payment?.status || "unpaid";
|
||
const cancelReason = String(reason || "").trim().slice(0, 200);
|
||
let effectivePaymentStatus = paymentStatus;
|
||
let effectivePayment = existing.payment || {};
|
||
|
||
// 兼容旧数据:取消曾存放在 status 中
|
||
const cancelStatus = existing.status === "cancelled"
|
||
? "cancelled"
|
||
: (existing.cancelStatus || "none");
|
||
|
||
if (cancelStatus === "cancelled") {
|
||
return ResponseUtil.badRequest(ctx, "订单已取消,不能再次操作");
|
||
}
|
||
|
||
if (!canManageOrder) {
|
||
// 用户端只能取消:未确认订单直接取消(未收款删除、已收款退款);已确认订单提交取消申请
|
||
if (status !== "cancelled" || !isOwner) {
|
||
return ResponseUtil.forbidden(ctx, "不支持的状态变更");
|
||
}
|
||
if (cancelStatus === "requested") {
|
||
return ResponseUtil.badRequest(ctx, "取消申请已提交,请等待确认");
|
||
}
|
||
if (!["pending", "confirmed"].includes(existing.status)) {
|
||
return ResponseUtil.badRequest(ctx, "当前订单状态不允许此操作");
|
||
}
|
||
if (!cancelReason) return ResponseUtil.badRequest(ctx, "请选择取消原因");
|
||
|
||
if (existing.status === "pending") {
|
||
// 未确认订单:陪诊师尚未接单,取消直接生效,无需人工确认。
|
||
// 取消前先关单,否则旧 prepay 仍可支付一张已不存在的订单
|
||
const closeResult = await HandlerPayment.closeOpenPayRecords(id);
|
||
let payStatus = paymentStatus;
|
||
let pay = existing.payment || {};
|
||
if (closeResult.paid) {
|
||
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: deletedRecord, deleted: true }, "订单已取消");
|
||
}
|
||
// 已收款:直接转已取消并进入退款;线上微信自动原路退款,线下由平台人工核销
|
||
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);
|
||
}
|
||
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,避免等待确认期间又被支付
|
||
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 (!canCancelTransition(cancelStatus, "requested")) {
|
||
return ResponseUtil.badRequest(ctx, "当前订单不允许取消");
|
||
}
|
||
const updatedRecord = await DBModel.EscortRecord.updateRecordCancel(id, cancelStatus, {
|
||
cancelStatus: "requested",
|
||
cancelReason,
|
||
cancelRequestedAt: new Date(),
|
||
});
|
||
if (!updatedRecord) {
|
||
return ResponseUtil.error(ctx, "订单状态已变化,请刷新后重试", null, 409);
|
||
}
|
||
return ResponseUtil.success(
|
||
ctx,
|
||
{ record: HandlerEscortRecord.withPaymentWindow(updatedRecord) },
|
||
"取消申请已提交"
|
||
);
|
||
}
|
||
|
||
// 管理端/陪诊师:普通状态推进,或确认取消申请 / 直接取消
|
||
if (status !== "cancelled") {
|
||
if (cancelStatus === "requested") {
|
||
return ResponseUtil.badRequest(ctx, "用户已申请取消,请先处理取消申请");
|
||
}
|
||
if (!canTransition(existing.status, status)) {
|
||
return ResponseUtil.badRequest(ctx, "当前订单状态不允许此操作");
|
||
}
|
||
const updatedRecord = await DBModel.EscortRecord.updateRecordStatus(id, existing.status, { status });
|
||
if (!updatedRecord) {
|
||
return ResponseUtil.error(ctx, "订单状态已变化,请刷新后重试", null, 409);
|
||
}
|
||
return ResponseUtil.success(ctx, { record: updatedRecord }, "状态更新成功");
|
||
}
|
||
|
||
if (!canCancelTransition(cancelStatus, "cancelled")) {
|
||
return ResponseUtil.badRequest(ctx, "当前订单不允许取消");
|
||
}
|
||
// 已完成是终态:服务已交付,取消/退款需走线下售后,不能由接口直接改状态
|
||
if (existing.status === "completed") {
|
||
return ResponseUtil.badRequest(ctx, "已完成订单不可取消,请走线下售后处理");
|
||
}
|
||
|
||
// 取消前先关单:未支付订单可能仍有旧 prepay 在途,关单后发现已支付则按已收款走退款
|
||
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 (effectivePaymentStatus === "unpaid" && existing.status === "pending") {
|
||
const deletedRecord = await DBModel.EscortRecord.deleteRecord(id);
|
||
if (!deletedRecord) {
|
||
return ResponseUtil.error(ctx, "陪诊记录不存在", null, 404);
|
||
}
|
||
return ResponseUtil.success(ctx, { record: deletedRecord, deleted: true }, "订单已取消");
|
||
}
|
||
|
||
const update = {
|
||
cancelStatus: "cancelled",
|
||
cancelledAt: new Date(),
|
||
// 已收款订单先进入退款中;线上支付随后自动原路退款,线下由平台人工核销
|
||
...(["partial", "paid"].includes(effectivePaymentStatus) ? { "payment.status": "refunding" } : {}),
|
||
};
|
||
// 正式取消:保留申请原因;平台直接取消时补默认原因
|
||
if (cancelReason) update.cancelReason = cancelReason;
|
||
else if (role === "admin" && !existing.cancelReason) update.cancelReason = "平台取消";
|
||
|
||
const updatedRecord = await DBModel.EscortRecord.updateRecordCancel(id, cancelStatus, update);
|
||
if (!updatedRecord) {
|
||
return ResponseUtil.error(ctx, "订单状态已变化,请刷新后重试", null, 409);
|
||
}
|
||
|
||
// 已支付的线上订单:取消落库后再发起原路全额退款
|
||
if (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.cancelStatus = "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.cancelStatus === "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 };
|