Files
api_health/handler/employee.js
T
lik d60a160180 feat(attendant): 订单池按身份合并可见范围并支持接单与共享
实习可见未分配与被共享订单但不可接单并脱敏患者联系方式;正式可接未被分配的订单,接单不校验支付状态;接单本人可共享给任意在职陪诊师。
2026-11-10 12:27:59 +08:00

606 lines
24 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.
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;
// 陪诊师阶段与等级:等级只做展示/排序,权限只看 stage
static STAGES = ["intern", "certified"];
static GRADES = ["bronze", "silver", "gold", "diamond"];
// 公示口径:实习陪诊师不对外展示(不能被用户选择)。
// stage 用 $ne 而非 $eq:存量档案没有该字段,一律视为正式
static publicAttendantFilter() {
return {
role: "attendant",
status: "active",
"attendantInfo.stage": { $ne: "intern" },
};
}
// 阶段/等级归一化:存量档案缺字段时按 certified + bronze 处理
static normalizeAttendantLevel(info = {}) {
const stage = HandlerEmployee.STAGES.includes(info.stage) ? info.stage : "certified";
const grade = HandlerEmployee.GRADES.includes(info.grade) ? info.grade : "bronze";
const rawStar = Number(info.star);
const star = grade === "diamond" && Number.isFinite(rawStar)
? Math.min(Math.max(Math.trunc(rawStar), 0), 5)
: 0;
return { stage, grade, star };
}
// 姓名脱敏:只留姓 + 「陪诊师」,不给全名,降低私下联系(跳单)的可能
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 || [],
// 注:GB/T 4.2.1.5 要求公示的「累计服务次数」暂缺——orderCount 全项目无写入点(恒 0),
// 展示恒 0 反而误导,已从公示输出摘除;待 plan.md B8 补写入点后恢复
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 / orderCount(均无可信来源),暂只按服务年限
const list = await DBModel.Employee.find(HandlerEmployee.publicAttendantFilter())
.sort({ "work.workYears": -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,
...HandlerEmployee.publicAttendantFilter(),
}).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);
}
}
// 共享候选名单:所有在职陪诊师(含实习),供接单陪诊师把订单共享出去。
// 与公示接口不同:这里不做姓名脱敏,也不排除实习,但必须本人是在职陪诊师。
async getShareableAttendants(ctx) {
try {
const userId = ctx.state.user?._id;
if (!userId) return ResponseUtil.unauthorized(ctx, "登录已失效");
const me = await DBModel.Employee.findOne({ userId, role: "attendant", status: "active" })
.select("_id")
.lean()
.exec();
if (!me) return ResponseUtil.forbidden(ctx, "仅在职陪诊师可查看共享名单");
const list = await DBModel.Employee.find({ role: "attendant", status: "active" })
.select("profile.name attendantInfo.stage attendantInfo.grade attendantInfo.star")
.lean()
.exec();
const gradeOrder = { diamond: 0, gold: 1, silver: 2, bronze: 3 };
const gradeLabels = { diamond: "钻石", gold: "黄金", silver: "白银", bronze: "青铜" };
const attendants = list
.filter((item) => String(item._id) !== String(me._id))
.map((item) => {
const level = HandlerEmployee.normalizeAttendantLevel(item.attendantInfo);
return {
employeeId: String(item._id),
name: item.profile?.name || "",
stage: level.stage,
grade: level.grade,
star: level.star,
stageText: level.stage === "intern" ? "实习陪诊师" : "正式陪诊师",
gradeText: `${gradeLabels[level.grade]}${level.grade === "diamond" && level.star
? ` ${"★".repeat(level.star)}`
: ""}`,
};
})
.sort((a, b) => {
const stageDiff = (a.stage === "intern" ? 1 : 0) - (b.stage === "intern" ? 1 : 0);
if (stageDiff) return stageDiff;
return (gradeOrder[a.grade] ?? 9) - (gradeOrder[b.grade] ?? 9);
});
return ResponseUtil.success(ctx, { attendants }, "查询成功");
} 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 attendantInfo")
.lean()
.exec();
// 无员工档案不是错误:管理员账号通常没有 Employee 记录
if (!employee) {
return ResponseUtil.success(ctx, { employee: null }, "查询成功");
}
// 阶段/等级归一化后随档案返回,小程序据此展示身份文案与只读提示。
// canAcceptOrder 只由 stage 决定,等级不参与鉴权
const level = HandlerEmployee.normalizeAttendantLevel(employee.attendantInfo);
employee.attendantInfo = { ...(employee.attendantInfo || {}), ...level };
employee.canAcceptOrder = level.stage === "certified";
return ResponseUtil.success(ctx, { employee }, "查询成功");
} 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);
}
}
/**
* 陪诊师阶段/等级调整:实习转正、青铜~钻石调级、钻石设星
*
* 独立入口而不是并入通用 PUT:等级只做展示与排序、不参与鉴权,
* 单独收口可避免误改档案其他字段
*/
async updateEmployeeLevel(ctx) {
try {
const { id } = ctx.params;
if (!mongoose.Types.ObjectId.isValid(id)) {
return ResponseUtil.badRequest(ctx, "员工ID不合法");
}
const body = ctx.request.body || {};
const flat = {};
if (body.stage !== undefined) {
if (!HandlerEmployee.STAGES.includes(body.stage)) {
return ResponseUtil.badRequest(ctx, "陪诊师阶段取值不正确");
}
flat["attendantInfo.stage"] = body.stage;
}
if (body.grade !== undefined) {
if (!HandlerEmployee.GRADES.includes(body.grade)) {
return ResponseUtil.badRequest(ctx, "陪诊师等级取值不正确");
}
flat["attendantInfo.grade"] = body.grade;
}
if (body.star !== undefined) {
const star = Number(body.star);
if (!Number.isInteger(star) || star < 0 || star > 5) {
return ResponseUtil.badRequest(ctx, "星级必须是 0-5 的整数");
}
flat["attendantInfo.star"] = star;
}
if (!Object.keys(flat).length) {
return ResponseUtil.badRequest(ctx, "没有可更新的字段");
}
const employee = await DBModel.Employee.findById(id)
.select("role attendantInfo")
.lean()
.exec();
if (!employee) {
return ResponseUtil.notFound(ctx, "员工不存在");
}
if (employee.role !== "attendant") {
return ResponseUtil.badRequest(ctx, "只有陪诊师可设置阶段与等级");
}
const current = HandlerEmployee.normalizeAttendantLevel(employee.attendantInfo);
const nextGrade = flat["attendantInfo.grade"] || current.grade;
if (flat["attendantInfo.star"] !== undefined && nextGrade !== "diamond") {
return ResponseUtil.badRequest(ctx, "只有钻石等级可以设置星级");
}
// 离开钻石时星级归零,避免展示残留的星星
if (flat["attendantInfo.grade"] && current.grade === "diamond" && nextGrade !== "diamond") {
flat["attendantInfo.star"] = 0;
}
const updated = await DBModel.Employee.updateEmployee(id, flat);
return ResponseUtil.success(ctx, { employee: updated }, "等级已更新");
} 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 };