Compare commits
1
Commits
420f379ce8
...
af9a1543ae
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
af9a1543ae |
@@ -175,6 +175,249 @@ class HandlerEmployee {
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
}
|
||||
|
||||
// 当前登录账号的员工档案:登录即可访问,供管理端判定陪诊员身份。
|
||||
// 只返回员工档案本身,不重复做管理员判定(管理员身份由管理端按登录响应的 apps 判定)
|
||||
async getMyEmployee(ctx) {
|
||||
try {
|
||||
const userId = ctx.state.user?._id;
|
||||
if (!userId) {
|
||||
return ResponseUtil.unauthorized(ctx, "登录已失效");
|
||||
}
|
||||
|
||||
const employee = await DBModel.Employee.findOne({ userId })
|
||||
.select("employeeNo role status profile.name profile.sex profile.phone profile.avatar")
|
||||
.lean()
|
||||
.exec();
|
||||
|
||||
// 无员工档案不是错误:管理员账号通常没有 Employee 记录
|
||||
return ResponseUtil.success(ctx, { employee: employee || null }, "查询成功");
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== 管理端 CRUD ====================
|
||||
// 与上面的公示接口完全分开:管理端要真实姓名、身份证号、证书编号等内部字段,
|
||||
// 但写入仍走白名单,避免 strict:false 的 schema 被塞入任意字段
|
||||
|
||||
static ROLES = ["attendant", "nurse", "doctor", "admin", "operator", "other"];
|
||||
static STATUSES = ["active", "inactive", "resigned", "suspended"];
|
||||
|
||||
static FIELD_PATHS = [
|
||||
"employeeNo", "userId", "orgId", "role", "status", "introduction", "remark",
|
||||
"profile.name", "profile.sex", "profile.birthday", "profile.idNumber",
|
||||
"profile.phone", "profile.email", "profile.avatar",
|
||||
"work.department", "work.title", "work.entryDate", "work.workYears", "work.qualification",
|
||||
"work.healthCertificate.number", "work.healthCertificate.org",
|
||||
"work.healthCertificate.issueDate", "work.healthCertificate.expireDate",
|
||||
"work.trainings",
|
||||
"attendantInfo.serviceAreas", "attendantInfo.specialties", "attendantInfo.languages",
|
||||
"attendantInfo.isOnline", "attendantInfo.orderCount",
|
||||
"emergencyContact.name", "emergencyContact.phone", "emergencyContact.relation",
|
||||
];
|
||||
|
||||
/**
|
||||
* 把请求体摊平成白名单内的点号路径
|
||||
*
|
||||
* 摊平而不是整块透传:updateEmployee 用 $set 更新,整块传 profile 会把未提交的
|
||||
* 子字段一起覆盖掉;点号路径只改实际提交的字段
|
||||
*/
|
||||
static pickFields(body, prefix = "", out = {}) {
|
||||
if (!body || typeof body !== "object") return out;
|
||||
for (const [key, value] of Object.entries(body)) {
|
||||
const path = prefix ? `${prefix}.${key}` : key;
|
||||
// 数组(如 trainings)和日期是叶子值,直接按路径收;普通对象继续下钻
|
||||
const isPlainObject =
|
||||
value !== null && typeof value === "object" &&
|
||||
!Array.isArray(value) && !(value instanceof Date);
|
||||
if (isPlainObject) {
|
||||
HandlerEmployee.pickFields(value, path, out);
|
||||
} else if (HandlerEmployee.FIELD_PATHS.includes(path)) {
|
||||
out[path] = value;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// 点号路径 → 嵌套对象,供 createEmployee 使用(构造器不认 "profile.name")
|
||||
static setPath(target, path, value) {
|
||||
const parts = path.split(".");
|
||||
let cur = target;
|
||||
for (let i = 0; i < parts.length - 1; i++) {
|
||||
if (!cur[parts[i]] || typeof cur[parts[i]] !== "object") cur[parts[i]] = {};
|
||||
cur = cur[parts[i]];
|
||||
}
|
||||
cur[parts[parts.length - 1]] = value;
|
||||
return target;
|
||||
}
|
||||
|
||||
// 管理端列表:不做姓名脱敏,支持角色/状态/关键词筛选
|
||||
async getEmployees(ctx) {
|
||||
try {
|
||||
const { role, status, keyword } = ctx.request.query;
|
||||
const page = Math.max(1, parseInt(ctx.request.query.page) || 1);
|
||||
const rawSize = parseInt(ctx.request.query.pageSize) || 20;
|
||||
const pageSize = Math.min(Math.max(1, rawSize), 100);
|
||||
|
||||
const filter = {};
|
||||
if (role) {
|
||||
if (!HandlerEmployee.ROLES.includes(role)) {
|
||||
return ResponseUtil.badRequest(ctx, "角色筛选值不正确");
|
||||
}
|
||||
filter.role = role;
|
||||
}
|
||||
if (status) {
|
||||
if (!HandlerEmployee.STATUSES.includes(status)) {
|
||||
return ResponseUtil.badRequest(ctx, "状态筛选值不正确");
|
||||
}
|
||||
filter.status = status;
|
||||
}
|
||||
if (keyword && String(keyword).trim()) {
|
||||
// 关键词转义,避免用户输入的括号等字符被当成正则
|
||||
const safe = String(keyword).trim().replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
const reg = new RegExp(safe, "i");
|
||||
filter.$or = [
|
||||
{ "profile.name": reg },
|
||||
{ "profile.phone": reg },
|
||||
{ employeeNo: reg },
|
||||
{ "profile.pinyin": reg },
|
||||
];
|
||||
}
|
||||
|
||||
const [employees, total] = await Promise.all([
|
||||
DBModel.Employee.find(filter)
|
||||
.sort({ "meta.createtime": -1 })
|
||||
.skip((page - 1) * pageSize)
|
||||
.limit(pageSize)
|
||||
.lean()
|
||||
.exec(),
|
||||
DBModel.Employee.countDocuments(filter).exec(),
|
||||
]);
|
||||
|
||||
return ResponseUtil.success(ctx, { employees, total, page, pageSize }, "查询成功");
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
}
|
||||
|
||||
async createEmployee(ctx) {
|
||||
try {
|
||||
const flat = HandlerEmployee.pickFields(ctx.request.body);
|
||||
|
||||
const invalid = HandlerEmployee.validateEmployee(flat, true);
|
||||
if (invalid) {
|
||||
return ResponseUtil.badRequest(ctx, invalid);
|
||||
}
|
||||
|
||||
const data = {};
|
||||
for (const [path, value] of Object.entries(flat)) {
|
||||
HandlerEmployee.setPath(data, path, value);
|
||||
}
|
||||
|
||||
const employee = await DBModel.Employee.createEmployee(data);
|
||||
return ResponseUtil.success(ctx, { employee }, "创建成功");
|
||||
} catch (err) {
|
||||
// employeeNo 唯一索引冲突:给出可读提示,而不是「服务器繁忙」
|
||||
if (err?.code === 11000) {
|
||||
return ResponseUtil.badRequest(ctx, "工号已存在");
|
||||
}
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
}
|
||||
|
||||
async updateEmployee(ctx) {
|
||||
try {
|
||||
const { id } = ctx.params;
|
||||
if (!mongoose.Types.ObjectId.isValid(id)) {
|
||||
return ResponseUtil.badRequest(ctx, "员工ID不合法");
|
||||
}
|
||||
|
||||
const flat = HandlerEmployee.pickFields(ctx.request.body);
|
||||
if (!Object.keys(flat).length) {
|
||||
return ResponseUtil.badRequest(ctx, "没有可更新的字段");
|
||||
}
|
||||
|
||||
const invalid = HandlerEmployee.validateEmployee(flat, false);
|
||||
if (invalid) {
|
||||
return ResponseUtil.badRequest(ctx, invalid);
|
||||
}
|
||||
|
||||
const employee = await DBModel.Employee.updateEmployee(id, flat);
|
||||
if (!employee) {
|
||||
return ResponseUtil.notFound(ctx, "员工不存在");
|
||||
}
|
||||
return ResponseUtil.success(ctx, { employee }, "更新成功");
|
||||
} catch (err) {
|
||||
if (err?.code === 11000) {
|
||||
return ResponseUtil.badRequest(ctx, "工号已存在");
|
||||
}
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
}
|
||||
|
||||
// 启停用独立入口:只改 status,避免误改其他字段
|
||||
async updateEmployeeStatus(ctx) {
|
||||
try {
|
||||
const { id } = ctx.params;
|
||||
if (!mongoose.Types.ObjectId.isValid(id)) {
|
||||
return ResponseUtil.badRequest(ctx, "员工ID不合法");
|
||||
}
|
||||
|
||||
const { status } = ctx.request.body || {};
|
||||
if (!HandlerEmployee.STATUSES.includes(status)) {
|
||||
return ResponseUtil.badRequest(ctx, "状态值不正确");
|
||||
}
|
||||
|
||||
const employee = await DBModel.Employee.updateEmployee(id, { status });
|
||||
if (!employee) {
|
||||
return ResponseUtil.notFound(ctx, "员工不存在");
|
||||
}
|
||||
return ResponseUtil.success(ctx, { employee }, "状态已更新");
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入校验
|
||||
*
|
||||
* @param {Object} flat 摊平后的白名单字段
|
||||
* @param {boolean} isCreate true 时姓名必填
|
||||
*/
|
||||
static validateEmployee(flat, isCreate) {
|
||||
if (isCreate || flat["profile.name"] !== undefined) {
|
||||
const name = String(flat["profile.name"] ?? "").trim();
|
||||
if (!name) return "姓名不能为空";
|
||||
}
|
||||
|
||||
if (flat.role !== undefined && !HandlerEmployee.ROLES.includes(flat.role)) {
|
||||
return "角色值不正确";
|
||||
}
|
||||
if (flat.status !== undefined && !HandlerEmployee.STATUSES.includes(flat.status)) {
|
||||
return "状态值不正确";
|
||||
}
|
||||
|
||||
// userId / orgId 允许为空串表示解绑,给了值就必须是合法 ObjectId
|
||||
for (const key of ["userId", "orgId"]) {
|
||||
const value = flat[key];
|
||||
if (value !== undefined && value !== "" && !mongoose.Types.ObjectId.isValid(value)) {
|
||||
return `${key === "userId" ? "关联用户ID" : "所属机构ID"}不合法`;
|
||||
}
|
||||
}
|
||||
|
||||
if (flat["profile.phone"] !== undefined && flat["profile.phone"] !== "") {
|
||||
if (!/^1[3-9]\d{9}$/.test(String(flat["profile.phone"]))) {
|
||||
return "手机号格式不正确";
|
||||
}
|
||||
}
|
||||
|
||||
if (flat["work.trainings"] !== undefined && !Array.isArray(flat["work.trainings"])) {
|
||||
return "培训记录必须是数组";
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export { HandlerEmployee };
|
||||
|
||||
+92
-47
@@ -48,6 +48,12 @@ class HandlerEscortRecord {
|
||||
// 用户下单时可选择的支付渠道:线下支付不细分现金/转账,由平台收款时补记 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;
|
||||
|
||||
@@ -232,19 +238,41 @@ class HandlerEscortRecord {
|
||||
|
||||
// 按条件查询记录(管理端,可查全部)
|
||||
async getRecords(ctx) {
|
||||
return this._listRecords(ctx, false);
|
||||
return this._listRecords(ctx, "all");
|
||||
}
|
||||
|
||||
// 查询"我的"记录:强制以登录用户身份查询,忽略 query 中的 userId
|
||||
async getMyRecords(ctx) {
|
||||
return this._listRecords(ctx, true);
|
||||
return this._listRecords(ctx, "self");
|
||||
}
|
||||
|
||||
async _listRecords(ctx, forceSelf) {
|
||||
// 陪诊员本人名下订单:强制以登录用户为陪诊员,忽略 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 } = ctx.request.query;
|
||||
const {
|
||||
status, userId, appointmentDate, healthProfileId, cancelStatus, includeCancelled,
|
||||
paymentStatus, payChannel, startDate, endDate, keyword,
|
||||
} = ctx.request.query;
|
||||
const { page, pageSize } = HandlerEscortRecord.parsePaging(ctx.request.query);
|
||||
const effectiveUserId = forceSelf ? ctx.state.user?._id : userId;
|
||||
const loginUserId = ctx.state.user?._id;
|
||||
if (!loginUserId) {
|
||||
return ResponseUtil.unauthorized(ctx, "登录已失效");
|
||||
}
|
||||
// 陪诊员模式不允许通过 query 改查他人订单;管理员模式保留按 userId 筛选
|
||||
const effectiveUserId = mode === "self"
|
||||
? loginUserId
|
||||
: (mode === "all" ? userId : undefined);
|
||||
const attendantId = mode === "attendant" ? loginUserId : undefined;
|
||||
|
||||
// status解析成数组
|
||||
let statusArray = null;
|
||||
@@ -265,6 +293,25 @@ class HandlerEscortRecord {
|
||||
}
|
||||
}
|
||||
|
||||
// 支付状态筛选: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,
|
||||
@@ -272,8 +319,14 @@ class HandlerEscortRecord {
|
||||
cancelStatus: cancelStatusArray,
|
||||
includeCancelled: ["1", "true"].includes(String(includeCancelled)),
|
||||
userId: effectiveUserId,
|
||||
attendantId,
|
||||
appointmentDate,
|
||||
healthProfileId,
|
||||
paymentStatus: paymentStatusArray,
|
||||
payChannel,
|
||||
startDate,
|
||||
endDate,
|
||||
keyword,
|
||||
});
|
||||
|
||||
const records = result.records.map((record) => HandlerEscortRecord.withPaymentWindow(record));
|
||||
@@ -283,28 +336,6 @@ class HandlerEscortRecord {
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
@@ -338,21 +369,29 @@ class HandlerEscortRecord {
|
||||
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");
|
||||
}
|
||||
|
||||
// 就诊人档案必须属于当前登录用户,避免把订单挂到他人档案上
|
||||
// 档案锚定归属:订单归属取档案的 userId。
|
||||
// 管理员代客下单不传 userId(传了也忽略),档案无归属时订单 userId 留空,后期可在订单编辑中补录;
|
||||
// 非管理员仍要求档案属于本人,避免把订单挂到他人档案上
|
||||
const isAdmin = HandlerEscortRecord.isAdmin(ctx.state.user);
|
||||
const profile = await DBModel.HealthProfile.findProfileById(body.healthProfileId);
|
||||
if (!profile || String(profile.userId) !== String(userId)) {
|
||||
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));
|
||||
@@ -374,8 +413,9 @@ class HandlerEscortRecord {
|
||||
|
||||
const payload = HandlerEscortRecord.pickFields(body);
|
||||
// 陪诊员分配由平台决定:用户下单时提交的 attendant 一律丢弃,防止自选/伪造陪诊员
|
||||
if (!HandlerEscortRecord.isAdmin(ctx.state.user)) delete payload.attendant;
|
||||
payload.userId = userId;
|
||||
if (!isAdmin) delete payload.attendant;
|
||||
// 归属以档案为准:管理员传入的 userId 一律忽略,无归属档案留空
|
||||
payload.userId = orderUserId;
|
||||
// healthProfileId 以校验通过的档案为准,覆盖客户端原值
|
||||
payload.healthProfileId = profile._id;
|
||||
payload.status = "pending";
|
||||
@@ -398,7 +438,7 @@ class HandlerEscortRecord {
|
||||
return ResponseUtil.badRequest(ctx, "支付方式不正确");
|
||||
}
|
||||
let payChannel;
|
||||
if (HandlerEscortRecord.isAdmin(ctx.state.user)) {
|
||||
if (isAdmin) {
|
||||
payChannel = HandlerEscortRecord.PAY_CHANNELS.includes(requestedChannel)
|
||||
? requestedChannel
|
||||
: (body.payment?.method === "online_wechat" ? "online_wechat" : "offline");
|
||||
@@ -413,18 +453,21 @@ class HandlerEscortRecord {
|
||||
payChannel,
|
||||
};
|
||||
// 实际收款方式由平台在收款时补记:仅管理员代客下单时可指定,用户端提交一律丢弃
|
||||
if (HandlerEscortRecord.isAdmin(ctx.state.user)
|
||||
if (isAdmin
|
||||
&& HandlerEscortRecord.PAYMENT_METHODS.includes(body.payment?.method)) {
|
||||
payload.payment.method = body.payment.method;
|
||||
}
|
||||
|
||||
// 每个用户同时最多 3 个未完成预约,超出则不再允许新增
|
||||
const unfinishedCount = await HandlerEscortRecord.countUnfinishedRecords(userId);
|
||||
if (unfinishedCount >= HandlerEscortRecord.MAX_UNFINISHED_RECORDS) {
|
||||
return ResponseUtil.badRequest(
|
||||
ctx,
|
||||
`每个用户最多同时保留${HandlerEscortRecord.MAX_UNFINISHED_RECORDS}个未完成的预约,请先完成或取消已有预约后再下单`
|
||||
);
|
||||
// 每个用户同时最多 3 个未完成预约,超出则不再允许新增。
|
||||
// 无归属订单(代客下单且档案未关联客户)跳过:否则会按全部无主订单全局误拦
|
||||
if (orderUserId) {
|
||||
const unfinishedCount = await HandlerEscortRecord.countUnfinishedRecords(orderUserId);
|
||||
if (unfinishedCount >= HandlerEscortRecord.MAX_UNFINISHED_RECORDS) {
|
||||
return ResponseUtil.badRequest(
|
||||
ctx,
|
||||
`每个用户最多同时保留${HandlerEscortRecord.MAX_UNFINISHED_RECORDS}个未完成的预约,请先完成或取消已有预约后再下单`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -433,7 +476,7 @@ class HandlerEscortRecord {
|
||||
} catch (err) {
|
||||
// 并发重复提交由唯一索引兜底,后到的请求返回已创建订单。
|
||||
if (err?.code === 11000 && idempotencyKey) {
|
||||
const existing = await DBModel.EscortRecord.findByIdempotencyKey(userId, idempotencyKey);
|
||||
const existing = await DBModel.EscortRecord.findByIdempotencyKey(orderUserId, idempotencyKey);
|
||||
if (existing) return ResponseUtil.success(ctx, { record: existing }, "订单已创建");
|
||||
}
|
||||
throw err;
|
||||
@@ -575,10 +618,12 @@ class HandlerEscortRecord {
|
||||
}
|
||||
|
||||
// 档案归属校验:档案必须属于订单所属用户,避免把订单挂到他人档案上;
|
||||
// 通过后同步刷新订单里的就诊人快照
|
||||
// 通过后同步刷新订单里的就诊人快照。
|
||||
// 空值等价比较:无归属订单(userId 为空)可以关联无归属档案
|
||||
if (payload.healthProfileId) {
|
||||
const profile = await DBModel.HealthProfile.findProfileById(payload.healthProfileId);
|
||||
if (!profile || String(profile.userId) !== String(existing.userId)) {
|
||||
const sameOwner = (a, b) => String(a || "") === String(b || "");
|
||||
if (!profile || !sameOwner(profile.userId, existing.userId)) {
|
||||
return ResponseUtil.badRequest(ctx, "就诊人档案不存在");
|
||||
}
|
||||
payload.patient = HandlerEscortRecord.buildPatientSnapshot(profile);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import mongoose from "mongoose";
|
||||
import { DBModel } from "../models/index.js";
|
||||
import ResponseUtil from "../utils/responseUtil.js";
|
||||
|
||||
@@ -51,6 +52,15 @@ class HandlerHealthProfile {
|
||||
if (weight !== undefined && (Number(weight) < 0 || Number(weight) > 500)) {
|
||||
return "体重需在 0-500kg 之间";
|
||||
}
|
||||
|
||||
// 归属用户:管理端代客建档时传入,必须是合法 ObjectId。
|
||||
// 空串/不传表示未绑定(历史数据),C 端 /mine 系列不走这里,其 userId 取自 token
|
||||
if (body.userId !== undefined && body.userId !== null && body.userId !== "") {
|
||||
if (!mongoose.Types.ObjectId.isValid(body.userId)) {
|
||||
return "归属用户ID不合法";
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -233,11 +233,15 @@ const EscortRecordSchema = mongoose.Schema(
|
||||
*/
|
||||
EscortRecordSchema.statics.buildRecordFilter = function (options = {}) {
|
||||
const {
|
||||
status, cancelStatus, userId, appointmentDate, healthProfileId,
|
||||
status, cancelStatus, userId, appointmentDate, healthProfileId, attendantId,
|
||||
includeDeleted = false, includeCancelled = false,
|
||||
paymentStatus, payChannel, startDate, endDate, keyword,
|
||||
} = options;
|
||||
const filter = {};
|
||||
|
||||
// 多个 $or 条件(取消状态兼容、关键词)不能互相覆盖,统一收进 $and
|
||||
const andConditions = [];
|
||||
|
||||
// 软删除的订单默认不进入列表:数据库里保留审计,界面上视为已删除
|
||||
if (!includeDeleted) filter.deletedAt = null;
|
||||
|
||||
@@ -248,9 +252,13 @@ EscortRecordSchema.statics.buildRecordFilter = function (options = {}) {
|
||||
if (cancelStatus && Array.isArray(cancelStatus) && cancelStatus.length > 0) {
|
||||
if (cancelStatus.length === 1 && cancelStatus[0] === "cancelled") {
|
||||
// 兼容旧数据:取消曾存放在 status 中
|
||||
filter.$or = [{ cancelStatus: "cancelled" }, { status: "cancelled" }];
|
||||
andConditions.push({ $or: [{ cancelStatus: "cancelled" }, { status: "cancelled" }] });
|
||||
} else {
|
||||
filter.cancelStatus = { $in: cancelStatus };
|
||||
// 历史数据缺 cancelStatus 字段时按 none 处理
|
||||
const values = cancelStatus.includes("none")
|
||||
? [...cancelStatus, null]
|
||||
: cancelStatus;
|
||||
filter.cancelStatus = { $in: values };
|
||||
}
|
||||
} else if (!includeCancelled) {
|
||||
// 历史数据没有 cancelStatus 字段,按未取消处理;旧数据仍可能把 cancelled 存在 status 里
|
||||
@@ -258,13 +266,58 @@ EscortRecordSchema.statics.buildRecordFilter = function (options = {}) {
|
||||
if (!filter.status) filter.status = { $ne: "cancelled" };
|
||||
}
|
||||
if (userId) filter.userId = userId;
|
||||
// 陪诊员列表:只查 assign 到本人的订单
|
||||
if (attendantId) filter["attendant.id"] = attendantId;
|
||||
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 };
|
||||
|
||||
// 支付状态 / 渠道:管理端按收款情况对账时使用
|
||||
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;
|
||||
};
|
||||
|
||||
@@ -281,50 +334,53 @@ EscortRecordSchema.statics.findRecords = async function (options = {}, cb) {
|
||||
};
|
||||
|
||||
// 列表记录、筛选总数和各页签计数一次返回,避免前端按当前页过滤或统计。
|
||||
// 计数只受非状态筛选(关键词/日期/支付/归属/陪诊员)影响,不受当前页签的 status/cancelStatus 影响
|
||||
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 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] = await Promise.all([
|
||||
|
||||
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(baseFilter).exec(),
|
||||
this.countDocuments(countBase).exec(),
|
||||
this.countDocuments({
|
||||
...baseFilter,
|
||||
...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 } };
|
||||
};
|
||||
|
||||
/**
|
||||
* 查找陪诊员的陪诊记录
|
||||
*
|
||||
* @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);
|
||||
return {
|
||||
records,
|
||||
total,
|
||||
counts: { all, ongoing, pending, cancelRequested, confirmed, inProgress, completed, cancelled },
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -129,6 +129,17 @@ function registerRoutes(app) {
|
||||
router.put("/health-profile/:id", requireAuth, requireAdmin, handlerHealthProfile.updateProfile.bind(handlerHealthProfile));
|
||||
router.delete("/health-profile/:id", requireAuth, requireAdmin, handlerHealthProfile.deleteProfile.bind(handlerHealthProfile));
|
||||
|
||||
// 当前账号的员工档案:登录即可访问,供管理端判定陪诊员身份。
|
||||
// 必须注册在 /employee 管理端路由之前,避免被更宽的路由抢占
|
||||
router.get("/employee/me", requireAuth, handlerEmployee.getMyEmployee.bind(handlerEmployee));
|
||||
|
||||
// 员工(陪诊师)管理:管理端 CRUD,必须管理员。
|
||||
// 与下方公开的 /attendant 公示接口分离:这里返回真实姓名等内部字段
|
||||
router.get("/employee", requireAuth, requireAdmin, handlerEmployee.getEmployees.bind(handlerEmployee));
|
||||
router.post("/employee", requireAuth, requireAdmin, createLimit, handlerEmployee.createEmployee.bind(handlerEmployee));
|
||||
router.put("/employee/:id", requireAuth, requireAdmin, updateLimit, handlerEmployee.updateEmployee.bind(handlerEmployee));
|
||||
router.patch("/employee/:id/status", requireAuth, requireAdmin, updateLimit, handlerEmployee.updateEmployeeStatus.bind(handlerEmployee));
|
||||
|
||||
// 医院基础信息:列表/详情公开,写接口仅管理员
|
||||
router.get("/hospital", handlerHospital.getHospitals.bind(handlerHospital));
|
||||
router.get("/hospital/:id", handlerHospital.getHospitalById.bind(handlerHospital));
|
||||
|
||||
+40
-9
@@ -2,6 +2,16 @@ import mongoose from "mongoose";
|
||||
import { DBModel } from "../models/index.js";
|
||||
|
||||
const ADMIN_APP = "wxapp-escort-admin";
|
||||
const WEB_ADMIN_APP = "web-escort-admin";
|
||||
|
||||
/**
|
||||
* 管理端应用清单:传统管理小程序 + Web 后台
|
||||
*
|
||||
* 两者在 user_app 里是彼此独立的成员关系,这里并列是过渡期兼容写法——
|
||||
* 任一应用内 role=admin 即视为管理员。等 user 服务重构完成、token 能带出
|
||||
* 应用维度后,改为按请求来源应用分别校验
|
||||
*/
|
||||
const ADMIN_APP_IDS = [ADMIN_APP, WEB_ADMIN_APP];
|
||||
|
||||
/**
|
||||
* 管理端 app 条目里的角色数组
|
||||
@@ -27,20 +37,41 @@ function appRoles(user) {
|
||||
* 现在注册侧已拒绝客户端写 app,但库里可能残留历史账号,
|
||||
* 因此要求显式 role === 'admin';role 缺失的历史账号暂按管理员放行并打告警,
|
||||
* 待库中补齐 app.wxapp-escort-admin.role = ['admin'] 后再收紧(见 doc/api-review-plan.md B1)。
|
||||
*
|
||||
* 用户模型重构后(doc/user-multi-app-plan.md),userInfo 响应会带只读数组 apps,
|
||||
* 此时优先按成员关系判定,status=disabled 的成员不再视为管理员。
|
||||
*/
|
||||
function isAdmin(user) {
|
||||
const entry = user?.app?.[ADMIN_APP];
|
||||
if (!entry) return false;
|
||||
if (!user) return false;
|
||||
|
||||
const roles = appRoles(user);
|
||||
if (roles.includes("admin")) return true;
|
||||
|
||||
if (entry.role === undefined) {
|
||||
console.warn(
|
||||
"[permissions] 管理员账号缺少 role 字段,请补齐 app.wxapp-escort-admin.role = ['admin']"
|
||||
// 重构后的只读视图:apps: [{ appId, roles, status }]
|
||||
if (Array.isArray(user.apps)) {
|
||||
return user.apps.some(
|
||||
(m) =>
|
||||
ADMIN_APP_IDS.includes(m?.appId) &&
|
||||
m.status !== "disabled" &&
|
||||
Array.isArray(m.roles) &&
|
||||
m.roles.includes("admin")
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
// 过渡期:仍读 user.app
|
||||
for (const appId of ADMIN_APP_IDS) {
|
||||
const entry = user.app?.[appId];
|
||||
if (!entry) continue;
|
||||
|
||||
const roles = Array.isArray(entry.role) ? entry.role : [entry.role].filter(Boolean);
|
||||
if (roles.includes("admin")) return true;
|
||||
|
||||
// 历史兼容:role 缺失时按管理员放行并告警
|
||||
if (entry.role === undefined) {
|
||||
console.warn(
|
||||
`[permissions] 管理员账号缺少 role 字段,请补齐 app.${appId}.role = ['admin']`
|
||||
);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user