feat: 新增员工管理端 CRUD 并增强订单筛选

- /employee 管理端列表/新增/更新/启停用,/employee/me 供管理端判定陪诊员身份

- 订单列表补充支付状态、支付渠道、日期区间、关键词筛选与各页签计数

- 陪诊员订单复用统一列表查询,过滤与分页口径与管理员一致

- 管理员代客下单时订单归属以就诊人档案用户为准,无归属订单跳过未完成上限

- 管理员判定兼容 web-escort-admin 与重构后的 apps 成员视图
This commit is contained in:
lik
2026-11-06 19:47:42 +08:00
parent 420f379ce8
commit af9a1543ae
6 changed files with 492 additions and 96 deletions
+243
View File
@@ -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
View File
@@ -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);
+10
View File
@@ -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;
}