Files
api_health/models/schema/escort_record.js
T
lik bcdf17f51b feat(escort): 订单取消改为两级确认
未确认且未收款的订单取消后直接删除;已确认或已收款转 cancel_requested,由名下陪诊师或管理员确认后正式取消,避免用户单方取消已履约订单。DELETE 接口收紧为仅管理员软删除。
2026-11-05 12:43:06 +08:00

402 lines
14 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(患者备注、陪诊记录、就诊摘要)
* - 状态信息: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: "完整收货地址" },
},
/**
* 陪诊员信息 - 为患者提供服务的陪诊员
*/
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: "陪诊员联系电话" },
},
/**
* 就诊信息 - 医院和科室相关信息
*/
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: "支付方式:线上微信、线下现金、线下转账",
},
status: {
type: String,
enum: ["unpaid", "partial", "paid", "refunding", "refunded"],
default: "unpaid",
comment: "支付状态:未支付、部分支付、已支付、退款中、已退款",
},
},
/**
* 备注信息 - 陪诊过程中的记录
*/
notes: {
patientNote: { type: String, default: "", comment: "患者备注/特殊需求" },
escortNote: { type: String, default: "", comment: "陪诊员服务记录" },
medicalSummary: { type: String, default: "", comment: "就诊摘要" },
},
/**
* 陪诊状态
* - pending: 待确认 - 订单已创建,等待确认
* - confirmed: 已确认 - 订单已确认,等待服务
* - cancel_requested: 待取消 - 用户已申请取消,等待陪诊师或管理员确认
* - in_progress: 进行中 - 陪诊服务正在进行
* - completed: 已完成 - 陪诊服务已完成
* - cancelled: 已取消 - 订单已取消
*/
status: {
type: String,
enum: ["pending", "confirmed", "cancel_requested", "in_progress", "completed", "cancelled"],
default: "pending",
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, userId, appointmentDate, healthProfileId, includeDeleted = false } = options;
const filter = {};
// 软删除的订单默认不进入列表:数据库里保留审计,界面上视为已删除
if (!includeDeleted) filter.deletedAt = null;
if (status && Array.isArray(status) && status.length > 0) {
filter.status = { $in: status };
}
if (userId) filter.userId = userId;
if (healthProfileId) filter.healthProfileId = healthProfileId;
if (appointmentDate) {
const start = new Date(`${appointmentDate}T00:00:00.000Z`);
const end = new Date(start);
end.setUTCDate(end.getUTCDate() + 1);
filter["schedule.date"] = { $gte: start, $lt: end };
}
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);
};
// 列表记录、筛选总数和各页签计数一次返回,避免前端按当前页过滤或统计。
EscortRecordSchema.statics.findRecordPage = async function (options = {}) {
const { page = 1, pageSize = 20 } = options;
const filter = this.buildRecordFilter(options);
const baseFilter = this.buildRecordFilter({ ...options, status: null });
const skip = (page - 1) * pageSize;
const [records, total, all, ongoing] = await Promise.all([
this.find(filter).sort({ "schedule.date": -1 }).skip(skip).limit(pageSize).exec(),
this.countDocuments(filter).exec(),
this.countDocuments(baseFilter).exec(),
this.countDocuments({ ...baseFilter, status: { $in: ["pending", "confirmed", "in_progress"] } }).exec(),
]);
return { records, total, counts: { all, ongoing } };
};
/**
* 查找陪诊员的陪诊记录
*
* @param {ObjectId|string} attendantId - 陪诊员用户ID
* @param {Object} options - 查询选项
* @param {number} [options.page=1] - 页码
* @param {number} [options.pageSize=20] - 每页数量
* @param {string} [options.status] - 状态筛选(可选)
* @param {Function} [cb] - 可选的回调函数
* @returns {Promise<Array>} 陪诊记录列表(按预约日期倒序)
*/
EscortRecordSchema.statics.findRecordsByAttendant = async function (attendantId, options = {}, cb) {
const { page = 1, pageSize = 20, status } = options;
const filter = { "attendant.id": attendantId };
if (status) {
filter.status = status;
}
const skip = (page - 1) * pageSize;
return await this.find(filter)
.sort({ "schedule.date": -1 })
.skip(skip)
.limit(pageSize)
.exec(cb);
};
/**
* 创建陪诊记录
*
* @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 }
);
};
EscortRecordSchema.statics.findByIdempotencyKey = async function (userId, idempotencyKey) {
return await this.findOne({ userId, idempotencyKey, deletedAt: null }).exec();
};
/**
* 根据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 };