- 新增 attendant_application 表与 5 个接口:提交/我的申请/审核列表/ 材料大图/审批,/mine 注册在 /:id 之前 - 提交侧按员工档案岗位分支:在职陪诊师与管理员及其他岗位 409 拒绝, 转岗由管理员后台显式操作;停用陪诊师可重新申请 - 审批两步走不依赖事务:条件更新抢占 pending,ensureEmployee 单条 条件 upsert 幂等建档(只放行无档案或已有 attendant 档案), 失败靠 approvedEmployeeId 为空续跑 - 岗位冲突时申请单条件回滚为 pending,不卡死在"已通过但未建档" - employee.userId 加 partial unique 索引并移除 employeeNo 默认值, 附迁移与存量校验脚本;员工管理端绑定账号查重与 userIdSource 标记 - 证件照复用 parseImage(单张 3MB),入驻前缀放宽请求体上限; 索引创建失败改为记日志,避免启动即崩
458 lines
18 KiB
JavaScript
458 lines
18 KiB
JavaScript
import mongoose from "mongoose";
|
||
import { DBModel } from "../models/index.js";
|
||
import ResponseUtil from "../utils/responseUtil.js";
|
||
|
||
/**
|
||
* 陪诊师公示:面向 C 端患者的公开信息展示
|
||
*
|
||
* 依据 GB/T 47801—2026 4.2.1.5「陪同人员信息公示机制」组织字段:
|
||
* 基本信息 —— 健康证明有效期、培训记录、服务年限、累计服务次数
|
||
* 专业技能 —— 擅长服务场景、特殊技能(语言)
|
||
*
|
||
* 两条红线:
|
||
* 1. 白名单式输出,绝不返回手机号 / 身份证号 / 证书编号原文;
|
||
* 「资质已核验」与健康证明都只对外给布尔值 / 有效期,不给编号。
|
||
* birthday 是这条规则下唯一的例外:年龄改由前端换算,故按 YYYY-MM-DD
|
||
* 下发(精确到日、不含时分秒),不随响应带出任何时刻信息
|
||
* 2. 评分只来自 employee_review 的真实评价聚合,且条数达
|
||
* MIN_PUBLIC_REVIEW_COUNT 才输出。attendantInfo.rating 恒为默认 5.0,
|
||
* 任何分支都不得读它——那是无依据背书
|
||
*/
|
||
|
||
/**
|
||
* 评价对外公示的最低条数
|
||
*
|
||
* 少于这个条数时平均分不具备参考性:一条 5 分就等于满分,展示反而误导用户。
|
||
* 故未达阈值时只回条数、分数给 null,由前端显示"暂不显示评分"
|
||
*/
|
||
const MIN_PUBLIC_REVIEW_COUNT = 5;
|
||
|
||
class HandlerEmployee {
|
||
// 公示列表单页上限:避免一次请求把整张表拖出来
|
||
static MAX_PAGE_SIZE = 50;
|
||
// 姓名脱敏:只留姓 + 「陪诊师」,不给全名,降低私下联系(跳单)的可能
|
||
static maskName(name) {
|
||
const trimmed = String(name || "").trim();
|
||
if (!trimmed) return "陪诊师";
|
||
return trimmed.slice(0, 1) + "陪诊师";
|
||
}
|
||
|
||
// 日期 → YYYY-MM-DD;无值或非法值返回空串,前端按空串隐藏该行
|
||
static formatDate(value) {
|
||
if (!value) return "";
|
||
const date = new Date(value);
|
||
if (Number.isNaN(date.getTime())) return "";
|
||
const month = String(date.getMonth() + 1).padStart(2, "0");
|
||
const day = String(date.getDate()).padStart(2, "0");
|
||
return `${date.getFullYear()}-${month}-${day}`;
|
||
}
|
||
|
||
// 健康证明是否在有效期内。
|
||
// 没登到期日一律判为"不有效"——不能默认有效,那等于无依据背书(同 rating 的处理)。
|
||
// 到期当天仍算有效,故与当天 24:00 比较
|
||
static isHealthCertificateValid(expireDate) {
|
||
if (!expireDate) return false;
|
||
const endOfDay = new Date(expireDate);
|
||
if (Number.isNaN(endOfDay.getTime())) return false;
|
||
endOfDay.setHours(23, 59, 59, 999);
|
||
return endOfDay.getTime() >= Date.now();
|
||
}
|
||
|
||
// 培训记录:只公示培训名称 / 机构 / 结业日期,内部备注一类不外泄
|
||
static toPublicTrainings(work) {
|
||
const list = Array.isArray(work.trainings) ? work.trainings : [];
|
||
return list
|
||
.map((item) => ({
|
||
title: item.title || "",
|
||
org: item.org || "",
|
||
date: HandlerEmployee.formatDate(item.date),
|
||
}))
|
||
// 没有名称的条目是脏数据,公示出去只是一行空白
|
||
.filter((item) => item.title);
|
||
}
|
||
|
||
// 白名单式脱敏:逐字段挑选,避免 employee 文档整体外泄
|
||
static toPublicAttendant(employee) {
|
||
const profile = employee.profile || {};
|
||
const work = employee.work || {};
|
||
const info = employee.attendantInfo || {};
|
||
|
||
return {
|
||
id: employee._id,
|
||
name: HandlerEmployee.maskName(profile.name),
|
||
avatar: profile.avatar || "",
|
||
sex: profile.sex || "",
|
||
// 年龄由前端换算,这里只下发原料。刻意走 formatDate 而不是原始 Date:
|
||
// 一是含 T/Z 的 ISO 串在小程序 iOS 上会解析成 Invalid Date,
|
||
// 二是未登记时给空串,前端有一个明确的哨兵值可判(不是 undefined / null 混用)
|
||
birthday: HandlerEmployee.formatDate(profile.birthday),
|
||
workYears: work.workYears || 0,
|
||
qualificationVerified: !!work.qualification,
|
||
// 健康证明:4.2.1.5 要求公示的是「有效期」,
|
||
// 只给是否在有效期内 + 到期日,编号与发证机构不外泄(同 qualification)
|
||
healthCertificate: {
|
||
valid: HandlerEmployee.isHealthCertificateValid(work.healthCertificate?.expireDate),
|
||
expireDate: HandlerEmployee.formatDate(work.healthCertificate?.expireDate),
|
||
},
|
||
specialties: info.specialties || [],
|
||
serviceAreas: info.serviceAreas || [],
|
||
languages: info.languages || [],
|
||
orderCount: info.orderCount || 0,
|
||
introduction: employee.introduction || "",
|
||
};
|
||
}
|
||
|
||
// 公开的陪诊师列表。
|
||
// 与 /service、/agreement 等公示类资源一致,不加 requireAuth——
|
||
// 公示信息本身不敏感,且避免登录态异常导致页面空白
|
||
async getAttendants(ctx) {
|
||
try {
|
||
// 分页参数夹紧:pageSize 未上限时可用一个请求把整表拖出来
|
||
const page = Math.max(1, parseInt(ctx.request.query.page) || 1);
|
||
const rawSize = parseInt(ctx.request.query.pageSize) || 50;
|
||
const pageSize = Math.min(Math.max(1, rawSize), HandlerEmployee.MAX_PAGE_SIZE);
|
||
|
||
// 只取在职陪诊员。
|
||
// 排序不按 attendantInfo.rating(无可信来源),改按服务年限 / 累计接单数
|
||
const list = await DBModel.Employee.find({
|
||
role: "attendant",
|
||
status: "active",
|
||
})
|
||
.sort({ "work.workYears": -1, "attendantInfo.orderCount": -1 })
|
||
.skip((page - 1) * pageSize)
|
||
.limit(pageSize)
|
||
.exec();
|
||
|
||
return ResponseUtil.success(
|
||
ctx,
|
||
{ attendants: list.map(HandlerEmployee.toPublicAttendant) },
|
||
"查询成功"
|
||
);
|
||
} catch (err) {
|
||
return ResponseUtil.internalError(ctx, err);
|
||
}
|
||
}
|
||
|
||
// 单个陪诊师的公开详情。
|
||
// 与列表共用同一套白名单——详情页不因为"多进一层"就多给字段,
|
||
// 手机号 / 身份证号 / 证书编号在这个分支里同样不出现。
|
||
// 筛选条件也照抄列表:只认在职陪诊员,否则列表里看不到的人却能按 ID 查到
|
||
async getAttendantById(ctx) {
|
||
try {
|
||
const id = ctx.params.id;
|
||
|
||
// 非法 ObjectId 会让 mongoose 抛 CastError,先挡掉,也避免把驱动栈信息带出去
|
||
if (!mongoose.Types.ObjectId.isValid(id)) {
|
||
return ResponseUtil.badRequest(ctx, "陪诊师ID不合法");
|
||
}
|
||
|
||
const employee = await DBModel.Employee.findOne({
|
||
_id: id,
|
||
role: "attendant",
|
||
status: "active",
|
||
}).exec();
|
||
|
||
if (!employee) {
|
||
return ResponseUtil.notFound(ctx, "陪诊师不存在或已下架");
|
||
}
|
||
|
||
const attendant = HandlerEmployee.toPublicAttendant(employee);
|
||
|
||
// 详情比列表多两块:
|
||
// 1) 培训记录——它是数组、体积不确定,列表接口不带
|
||
attendant.trainings = HandlerEmployee.toPublicTrainings(employee.work || {});
|
||
|
||
// 2) 评价聚合——多一次查询,只有详情这一个入口需要
|
||
const review = await DBModel.EmployeeReview.statsByEmployee(id);
|
||
attendant.review = {
|
||
count: review.count,
|
||
// 未达阈值不给分数:条数太少时平均分不具备参考性
|
||
score: review.count >= MIN_PUBLIC_REVIEW_COUNT ? review.score : null,
|
||
};
|
||
|
||
return ResponseUtil.success(ctx, { attendant }, "查询成功");
|
||
} catch (err) {
|
||
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);
|
||
}
|
||
}
|
||
|
||
// userId 绑定查重:一个账号只能绑一条员工档案(与 employee.userId 的
|
||
// partial unique 索引同一规则,应用层先挡可给出可读提示而非 500)
|
||
static async assertUserIdAvailable(userId, excludeId = null) {
|
||
if (!userId || typeof userId !== "string" || !mongoose.Types.ObjectId.isValid(userId)) {
|
||
return null;
|
||
}
|
||
const filter = { userId: new mongoose.Types.ObjectId(userId) };
|
||
if (excludeId) filter._id = { $ne: new mongoose.Types.ObjectId(excludeId) };
|
||
const existing = await DBModel.Employee.findOne(filter).select("_id profile.name").lean().exec();
|
||
if (!existing) return null;
|
||
return `该账号已绑定员工「${existing.profile?.name || existing._id}」,一个账号只能关联一条员工档案`;
|
||
}
|
||
|
||
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 conflict = await HandlerEmployee.assertUserIdAvailable(flat.userId);
|
||
if (conflict) {
|
||
return ResponseUtil.error(ctx, conflict, null, 409);
|
||
}
|
||
|
||
const data = {};
|
||
for (const [path, value] of Object.entries(flat)) {
|
||
HandlerEmployee.setPath(data, path, value);
|
||
}
|
||
if (data.userId) data.userIdSource = "manual";
|
||
|
||
const employee = await DBModel.Employee.createEmployee(data);
|
||
return ResponseUtil.success(ctx, { employee }, "创建成功");
|
||
} catch (err) {
|
||
// employeeNo / userId 唯一索引冲突:给出可读提示,而不是「服务器繁忙」
|
||
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 conflict = await HandlerEmployee.assertUserIdAvailable(flat.userId, id);
|
||
if (conflict) {
|
||
return ResponseUtil.error(ctx, conflict, null, 409);
|
||
}
|
||
|
||
// 换了绑定账号 = 人工改绑,来源改写为 manual(可与入驻自动绑定区分)
|
||
if (flat.userId) {
|
||
flat.userIdSource = "manual";
|
||
} else if (flat.userId === "") {
|
||
// 解绑:userId 是 ObjectId 路径,写空串会触发 CastError,
|
||
// 必须转成 null 才能真正解绑(partial unique 索引不约束 null)
|
||
flat.userId = null;
|
||
flat.userIdSource = "";
|
||
}
|
||
|
||
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 };
|