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 };