Files
api_health/models/schema/escort_record.js
T
lik b293540ba2 refactor(agreement): 统一协议命名与服务口径
免责协议更名为《陪诊服务免责协议》,覆盖全部服务而非单一服务名;服务时长改为半天/全天口径,挂号引导改为建档取号引导,避免与「不代为挂号」冲突;两份协议页脚统一引用 GB/T 47801—2026 并同步更新日期;下单校验文案同步更名。
2026-11-13 17:09:04 +08:00

625 lines
23 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use strict";
import mongoose from "mongoose";
/**
* 陪诊记录Schema定义
*
* 用于记录和管理陪诊服务全流程数据,包含以下主要分类:
* - 基础信息:userId(订单提交用户)、healthProfileId(关联健康档案ID)
* - 患者信息:patient(名单字段快照:姓名、电话、性别、出生年月)
* - 陪诊服务:escort(服务ID、服务名称)
* - 就诊信息:hospital(医院省份、名称、地址、科室、医生、病历号)
* - 时间安排:schedule(预约时间、开始时间、结束时间、时长)
* - 陪诊员信息:attendant(陪诊员ID、姓名)
* - 费用信息:payment(总费用、已支付、支付方式、支付状态)
* - 备注信息:notes(患者备注、陪诊记录、就诊摘要)
* - 问诊信息:inquiry(病历、诉求)
* - 状态信息:status(陪诊状态)
* - 元数据:meta(创建时间、更新时间)
*/
const EscortRecordSchema = mongoose.Schema(
{
/**
* 提交订单的用户ID(订单创建者)
* @type {ObjectId}
* @ref user
*/
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: "user",
index: true,
comment: "提交订单用户ID"
},
/**
* 关联健康档案ID(下单必填:订单必须关联就诊人)
* @type {ObjectId}
* @ref health_profile
*/
healthProfileId: {
type: mongoose.Schema.Types.ObjectId,
ref: "health_profile",
default: null,
comment: "关联健康档案ID"
},
/**
* 患者信息 - 下单当刻从健康档案拷贝的「名单字段」快照(仅姓名/电话/性别/出生年月)。
* 档案可随时编辑或删除,历史订单至少需要认出"是谁、怎么联系",故名单快照与 healthProfileId 并存:
* 展示时以档案最新数据为准,档案缺失时回落到这份快照。
* 体征(身高/体重)与证件号不进快照——它们只有详情页兜底在用,详情页本来就实时拉档案
*/
patient: {
name: { type: String, default: "", comment: "患者姓名" },
mobile: { type: String, default: "", index: true, comment: "患者联系电话" },
sex: { type: String, enum: ["male", "female"], comment: "患者性别" },
birth: { type: String, default: "", comment: "患者出生年月(YYYY-MM-DD)" },
},
/**
* 陪诊服务信息 - 选择的陪诊服务配置
*/
escort: {
serviceId: { type: Number, default: -1, comment: "陪诊服务ID" },
serviceName: { type: String, default: "", comment: "陪诊服务名称" },
sexRequirement: { type: String, enum: ["none", "male", "female"], comment: "陪诊员性别要求" },
},
// 下单幂等键:同一用户重复提交同一键时返回原订单,不重复创建。
idempotencyKey: {
type: String,
comment: "用户端下单幂等标识"
},
// 收货信息是下单当刻的快照,不随用户资料或地址变化。
shippingAddress: {
recipientName: { type: String, default: "", comment: "收货人姓名" },
mobile: { type: String, default: "", comment: "收货联系电话" },
address: { type: String, default: "", comment: "完整收货地址" },
},
// 下单时用户对《陪诊服务免责协议》的确认快照,作为电子服务合同凭据留存。
// 管理员 / 陪诊师端代客下单可不带该字段,历史订单默认未确认。
agreement: {
accepted: { type: Boolean, default: false, comment: "是否已阅读并同意免责协议" },
version: { type: String, default: "", comment: "用户确认的协议版本" },
acceptedAt: { type: Date, default: null, comment: "用户确认时间" },
},
/**
* 陪诊员信息 - 为患者提供服务的陪诊员
*/
attendant: {
id: {
type: mongoose.Schema.Types.ObjectId, index: true, comment: "陪诊员用户ID"
},
name: { type: String, default: "", comment: "陪诊员姓名" },
sex: { type: String, enum: ["none", "male", "female"], comment: "陪诊员性别" },
mobile: { type: String, default: "", comment: "陪诊员联系电话" },
// 接单陪诊师把订单共享给其他陪诊师:存 employee._id(不是登录 userId),
// 这样展示共享对象时不依赖账号绑定关系
sharedWith: [{
type: mongoose.Schema.Types.ObjectId,
ref: "employee",
comment: "共享给其他陪诊师(employee._id)",
}],
},
/**
* 就诊信息 - 医院和科室相关信息
*/
hospital: {
province: { type: String, default: "", comment: "就诊医院省份" },
name: { type: String, default: "", comment: "就诊医院名称" },
address: { type: String, default: "", comment: "医院详细地址" },
department: { type: String, default: "", comment: "就诊科室" },
doctor: { type: String, default: "", comment: "就诊医生" },
medicalRecordNo: { type: String, default: "", comment: "病历号" },
},
/**
* 时间信息 - 陪诊服务的时间安排
*/
schedule: {
date: { type: Date, default: Date.now, comment: "预约就诊日期" },
startTime: { type: String, default: "", comment: "陪诊实际开始时间" },
endTime: { type: String, default: "", comment: "陪诊实际结束时间" },
duration: { type: Number, default: 60, comment: "陪诊时长(分钟)" },
},
/**
* 费用信息 - 服务费用相关
*/
payment: {
totalFee: { type: Number, default: 0, comment: "陪诊服务总费用(元)" },
paidFee: { type: Number, default: 0, comment: "已支付费用(元)" },
// 支付由客服协助完成,方式由平台在收款时补记;空串表示未记录(历史订单兼容)
method: {
type: String,
enum: ["", "online_wechat", "offline_cash", "offline_transfer"],
default: "",
comment: "实际收款方式:线上微信、线下现金、线下转账",
},
// 用户选择的支付渠道;历史订单缺失该字段时展示层按 offline 解释
payChannel: {
type: String,
enum: ["online_wechat", "offline"],
comment: "用户选择的支付渠道",
},
// 当前有效支付流水;历史流水保留在 payment_record 中审计
paymentRecordId: {
type: mongoose.Schema.Types.ObjectId,
default: null,
comment: "当前有效支付流水",
},
status: {
type: String,
enum: ["unpaid", "partial", "paid", "refunding", "refunded"],
default: "unpaid",
comment: "支付状态:未支付、部分支付、已支付、退款中、已退款",
},
// 退款流水号:线上退款回填微信退款单号,人工核销由管理员录入
refundNo: {
type: String,
default: "",
comment: "退款流水号",
},
refundedAt: {
type: Date,
default: null,
comment: "退款完成时间",
},
},
/**
* 备注信息 - 陪诊过程中的记录
*/
notes: {
patientNote: { type: String, default: "", comment: "患者备注/特殊需求" },
escortNote: { type: String, default: "", comment: "陪诊员服务记录" },
medicalSummary: { type: String, default: "", comment: "就诊摘要" },
},
/**
* 问诊信息 - 就诊人补充的病历与诉求,与下单备注分开
*/
inquiry: {
medicalHistory: { type: String, default: "", comment: "病历" },
demand: { type: String, default: "", comment: "诉求" },
},
/**
* 陪诊状态(只描述服务生命周期,不含取消)
* - pending: 待确认 - 订单已创建,等待确认
* - confirmed: 已确认 - 订单已确认,等待服务
* - in_progress: 进行中 - 陪诊服务正在进行
* - completed: 已完成 - 陪诊服务已完成
*
* 取消单独用 cancelStatus 表达,取消后 status 保留取消前的服务状态。
*/
status: {
type: String,
enum: ["pending", "confirmed", "in_progress", "completed"],
default: "pending",
comment: "陪诊状态:待确认、已确认、进行中、已完成",
},
/**
* 取消状态(与 status 解耦)
* - none: 未取消
* - requested: 用户已申请取消,等待陪诊师/管理员确认
* - cancelled: 已取消
*/
cancelStatus: {
type: String,
enum: ["none", "requested", "cancelled"],
default: "none",
index: true,
comment: "取消状态:无、待取消、已取消",
},
cancelReason: { type: String, default: "", comment: "订单取消原因" },
cancelRequestedAt: { type: Date, default: null, comment: "用户申请取消时间" },
cancelledAt: { type: Date, default: null, comment: "订单取消时间" },
/**
* 软删除标记:已支付/进行中/已完成的订单不允许物理删除(费用与服务记录需留存审计),
* 管理员删除时打此标记,列表与详情默认过滤,历史数据不受影响
*/
deletedAt: { type: Date, default: null, comment: "软删除时间" },
/**
* 元数据 - 系统管理信息
*/
meta: {
createtime: { type: Date, default: Date.now, comment: "创建时间" },
updatetime: { type: Date, default: Date.now, comment: "更新时间" },
},
},
{
minimize: false,
strict: false,
collection: "escort_record",
timestamps: false,
}
);
/**
* 查找陪诊记录(支持多条件筛选)
*
* @param {Object} options - 查询选项
* @param {number} [options.page=1] - 页码
* @param {number} [options.pageSize=20] - 每页数量
* @param {Array<string>} options.status - 状态筛选(必需,数组)
* @param {ObjectId} [options.userId] - 订单提交用户ID(可选)
* @param {string} [options.appointmentDate] - 预约日期筛选(可选,格式 YYYY-MM-DD)
* @param {Function} [cb] - 可选的回调函数
* @returns {Promise<Array>} 陪诊记录列表(按预约日期倒序)
*/
EscortRecordSchema.statics.buildRecordFilter = function (options = {}) {
const {
status, cancelStatus, userId, appointmentDate, healthProfileId, attendantId,
attendantVisibility,
includeDeleted = false, includeCancelled = false,
paymentStatus, payChannel, startDate, endDate, keyword,
} = options;
const filter = {};
// 多个 $or 条件(取消状态兼容、关键词)不能互相覆盖,统一收进 $and
const andConditions = [];
// 软删除的订单默认不进入列表:数据库里保留审计,界面上视为已删除
if (!includeDeleted) filter.deletedAt = null;
if (status && Array.isArray(status) && status.length > 0) {
filter.status = { $in: status };
}
// 取消状态与 status 解耦:默认隐藏已取消订单,显式指定 cancelStatus 或 includeCancelled 时放开
if (cancelStatus && Array.isArray(cancelStatus) && cancelStatus.length > 0) {
if (cancelStatus.length === 1 && cancelStatus[0] === "cancelled") {
// 兼容旧数据:取消曾存放在 status 中
andConditions.push({ $or: [{ cancelStatus: "cancelled" }, { status: "cancelled" }] });
} else {
// 历史数据缺 cancelStatus 字段时按 none 处理
const values = cancelStatus.includes("none")
? [...cancelStatus, null]
: cancelStatus;
filter.cancelStatus = { $in: values };
}
} else if (!includeCancelled) {
// 历史数据没有 cancelStatus 字段,按未取消处理;旧数据仍可能把 cancelled 存在 status 里
filter.cancelStatus = { $ne: "cancelled" };
if (!filter.status) filter.status = { $ne: "cancelled" };
}
if (userId) filter.userId = userId;
// 陪诊员列表:只查 assign 到本人的订单
if (attendantId) filter["attendant.id"] = attendantId;
// 陪诊师订单池:按身份合并可见范围,scope 由服务端计算,不接受前端传入。
// - includeUnassigned:所有在职陪诊师都能看到未分配订单
// - poolCities:未分配订单只展示本服务城市(本人已接/被共享不受城市限制)
// - userId:正式陪诊师还能看到自己已接的订单(实习不能接单,故不传)
// - employeeId:被共享的订单
if (attendantVisibility) {
const or = [];
if (attendantVisibility.includeUnassigned) {
const poolClause = { "attendant.id": null };
const poolCities = attendantVisibility.poolCities;
if (Array.isArray(poolCities) && poolCities.length) {
// 历史订单可能没有省份:无法归属城市时仍保留在池中,避免存量订单消失
poolClause.$or = [
{ "hospital.province": { $in: poolCities } },
{ "hospital.province": { $in: ["", null] } },
];
}
or.push(poolClause);
}
if (attendantVisibility.userId) or.push({ "attendant.id": attendantVisibility.userId });
if (attendantVisibility.employeeId) {
or.push({ "attendant.sharedWith": attendantVisibility.employeeId });
}
if (or.length) andConditions.push({ $or: or });
}
if (healthProfileId) filter.healthProfileId = healthProfileId;
// 支付状态 / 渠道:管理端按收款情况对账时使用
if (paymentStatus && Array.isArray(paymentStatus) && paymentStatus.length > 0) {
filter["payment.status"] = { $in: paymentStatus };
}
if (payChannel) filter["payment.payChannel"] = payChannel;
// 预约日期:单日(appointmentDate)与区间(startDate/endDate)可并存,
// 都按 UTC 日界换算,与历史口径保持一致
const parseDay = (value) => {
const date = new Date(`${value}T00:00:00.000Z`);
return Number.isNaN(date.getTime()) ? null : date;
};
if (appointmentDate) {
const start = parseDay(appointmentDate);
if (start) {
const end = new Date(start);
end.setUTCDate(end.getUTCDate() + 1);
filter["schedule.date"] = { $gte: start, $lt: end };
}
} else if (startDate || endDate) {
const range = {};
const start = startDate ? parseDay(startDate) : null;
const end = endDate ? parseDay(endDate) : null;
if (start) range.$gte = start;
if (end) {
end.setUTCDate(end.getUTCDate() + 1); // 含结束日当天
range.$lt = end;
}
if (Object.keys(range).length) filter["schedule.date"] = range;
}
// 关键词:就诊人姓名/电话、陪诊员姓名、医院名称,以及订单ID
if (keyword && String(keyword).trim()) {
const text = String(keyword).trim();
const safe = text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const reg = new RegExp(safe, "i");
const or = [
{ "patient.name": reg },
{ "patient.mobile": reg },
{ "attendant.name": reg },
{ "hospital.name": reg },
];
if (/^[0-9a-fA-F]{24}$/.test(text)) or.push({ _id: text });
andConditions.push({ $or: or });
}
if (andConditions.length) filter.$and = andConditions;
return filter;
};
EscortRecordSchema.statics.findRecords = async function (options = {}, cb) {
const { page = 1, pageSize = 20 } = options;
const filter = this.buildRecordFilter(options);
const skip = (page - 1) * pageSize;
return await this.find(filter)
.sort({ "schedule.date": -1 })
.skip(skip)
.limit(pageSize)
.exec(cb);
};
// 列表记录、筛选总数和各页签计数一次返回,避免前端按当前页过滤或统计。
// 计数只受非状态筛选(关键词/日期/支付/归属/陪诊员)影响,不受当前页签的 status/cancelStatus 影响
EscortRecordSchema.statics.findRecordPage = async function (options = {}) {
const { page = 1, pageSize = 20 } = options;
const filter = this.buildRecordFilter(options);
const countBase = this.buildRecordFilter({
...options,
status: null,
cancelStatus: null,
includeCancelled: true,
});
// 生命周期页签只统计未申请取消的订单,避免同一单同时出现在「待确认」与「待取消」
const activeBase = { ...countBase, cancelStatus: { $in: ["none", null] } };
// 兼容历史数据:取消曾存放在 status 中
const cancelledFilter = {
...countBase,
$and: [
...(countBase.$and || []),
{ $or: [{ cancelStatus: "cancelled" }, { status: "cancelled" }] },
],
};
const skip = (page - 1) * pageSize;
const [
records, total, all, ongoing,
pending, cancelRequested, confirmed, inProgress, completed, cancelled,
] = await Promise.all([
this.find(filter).sort({ "schedule.date": -1 }).skip(skip).limit(pageSize).exec(),
this.countDocuments(filter).exec(),
this.countDocuments(countBase).exec(),
this.countDocuments({
...countBase,
status: { $in: ["pending", "confirmed", "in_progress"] },
cancelStatus: { $ne: "cancelled" },
}).exec(),
this.countDocuments({ ...activeBase, status: "pending" }).exec(),
this.countDocuments({ ...countBase, cancelStatus: "requested" }).exec(),
this.countDocuments({ ...activeBase, status: "confirmed" }).exec(),
this.countDocuments({ ...activeBase, status: "in_progress" }).exec(),
this.countDocuments({ ...activeBase, status: "completed" }).exec(),
this.countDocuments(cancelledFilter).exec(),
]);
return {
records,
total,
counts: { all, ongoing, pending, cancelRequested, confirmed, inProgress, completed, cancelled },
};
};
/**
* 创建陪诊记录
*
* @param {Object} record - 陪诊记录对象
* @param {Function} [cb] - 可选的回调函数
* @returns {Promise<Object>} 创建的陪诊记录
*/
EscortRecordSchema.statics.createRecord = async function (record, cb) {
record.meta = {
createtime: Date.now(),
updatetime: Date.now(),
};
const newRecord = new this(record);
return await newRecord.save(cb);
};
/**
* 更新陪诊记录
*
* @param {ObjectId} id - 记录ID
* @param {Object} update - 要更新的字段
* @param {Function} [cb] - 可选的回调函数
* @returns {Promise<Object|null>} 更新后的记录,失败返回null
*/
EscortRecordSchema.statics.updateRecord = async function (id, update, cb) {
const $set = { ...update, "meta.updatetime": Date.now() };
// 已软删除的订单不可再被修改
return await this.findOneAndUpdate(
{ _id: id, deletedAt: null },
{ $set },
{ new: true, runValidators: true },
cb
);
};
// 状态迁移必须仍以读取时的状态为条件,避免并发请求重复取消或跨过服务阶段。
EscortRecordSchema.statics.updateRecordStatus = async function (id, fromStatus, update) {
return await this.findOneAndUpdate(
{ _id: id, status: fromStatus, deletedAt: null },
{ $set: { ...update, "meta.updatetime": Date.now() } },
{ new: true, runValidators: true }
);
};
// 取消状态迁移以读取时的 cancelStatus 为条件;历史数据缺字段时按 none 处理。
EscortRecordSchema.statics.updateRecordCancel = async function (id, fromCancelStatus, update) {
const from = fromCancelStatus || "none";
const cancelFilter = from === "none"
? { cancelStatus: { $in: ["none", null] } }
: { cancelStatus: from };
return await this.findOneAndUpdate(
{ _id: id, deletedAt: null, ...cancelFilter },
{ $set: { ...update, "meta.updatetime": Date.now() } },
{ new: true, runValidators: true }
);
};
EscortRecordSchema.statics.findByIdempotencyKey = async function (userId, idempotencyKey) {
return await this.findOne({ userId, idempotencyKey, deletedAt: null }).exec();
};
// 接单:只有「未分配」的订单能被接走,条件更新保证并发下只有一个陪诊师成功。
// 与支付状态无关:订单是否付款不影响接单;取消中(requested)与已取消订单不可接。
EscortRecordSchema.statics.acceptRecord = async function (id, attendant) {
return await this.findOneAndUpdate(
{
_id: id,
deletedAt: null,
"attendant.id": null,
cancelStatus: { $nin: ["cancelled", "requested"] },
status: { $ne: "cancelled" },
},
{
$set: {
"attendant.id": attendant.id,
"attendant.name": attendant.name || "",
"attendant.sex": attendant.sex || "none",
"attendant.mobile": attendant.mobile || "",
"meta.updatetime": Date.now(),
},
},
{ new: true, runValidators: true }
);
};
// 共享 / 取消共享:只有当前接单陪诊师本人能操作,已取消订单不再变动共享名单
EscortRecordSchema.statics.addSharedWith = async function (id, attendantId, employeeIds) {
return await this.findOneAndUpdate(
{ _id: id, deletedAt: null, "attendant.id": attendantId, cancelStatus: { $ne: "cancelled" }, status: { $ne: "cancelled" } },
{
$addToSet: { "attendant.sharedWith": { $each: employeeIds } },
$set: { "meta.updatetime": Date.now() },
},
{ new: true, runValidators: true }
);
};
EscortRecordSchema.statics.removeSharedWith = async function (id, attendantId, employeeIds) {
return await this.findOneAndUpdate(
{ _id: id, deletedAt: null, "attendant.id": attendantId, cancelStatus: { $ne: "cancelled" }, status: { $ne: "cancelled" } },
{
$pull: { "attendant.sharedWith": { $in: employeeIds } },
$set: { "meta.updatetime": Date.now() },
},
{ new: true, runValidators: true }
);
};
/**
* 根据ID查找陪诊记录
*
* @param {ObjectId} id - 记录ID
* @param {Function} [cb] - 可选的回调函数
* @returns {Promise<Object|null>} 陪诊记录,不存在返回null
*/
EscortRecordSchema.statics.findRecordById = async function (id, cb) {
// 软删除的订单按不存在处理
return await this.findOne({ _id: id, deletedAt: null }).exec(cb);
};
/**
* 根据状态查找陪诊记录
*
* @param {string} status - 状态
* @param {Object} options - 查询选项
* @param {number} [options.page=1] - 页码
* @param {number} [options.pageSize=20] - 每页数量
* @param {Function} [cb] - 可选的回调函数
* @returns {Promise<Array>} 陪诊记录列表
*/
EscortRecordSchema.statics.findRecordsByStatus = async function (status, options = {}, cb) {
const { page = 1, pageSize = 20 } = options;
const skip = (page - 1) * pageSize;
return await this.find({ status })
.sort({ "schedule.date": -1 })
.skip(skip)
.limit(pageSize)
.exec(cb);
};
/**
* 删除陪诊记录
*
* @param {ObjectId} id - 记录ID
* @param {Function} [cb] - 可选的回调函数
* @returns {Promise<Object|null>} 删除的记录,失败返回null
*/
EscortRecordSchema.statics.deleteRecord = async function (id, cb) {
return await this.findByIdAndDelete(id, cb);
};
// ==================== 索引定义 ====================
/**
* 用户ID索引 - 用于快速查询用户的陪诊记录
*/
EscortRecordSchema.index({ userId: 1, "schedule.date": -1 });
// 仅带幂等键的新订单参与唯一约束,历史订单不受影响。
EscortRecordSchema.index(
{ userId: 1, idempotencyKey: 1 },
{ unique: true, sparse: true }
);
/**
* 健康档案ID索引 - 稀疏索引,用于快速按健康档案筛选记录
*/
EscortRecordSchema.index({ healthProfileId: 1 }, { sparse: true });
/**
* 陪诊员ID索引 - 用于快速查询陪诊员的服务记录
*/
EscortRecordSchema.index({ "attendant.id": 1, status: 1, "schedule.date": -1 });
/**
* 状态索引 - 用于快速按状态筛选记录
*/
EscortRecordSchema.index({ status: 1 });
/**
* 医院名称索引 - 用于快速按医院筛选记录
*/
EscortRecordSchema.index({ "hospital.name": 1 });
export { EscortRecordSchema };