feat: 陪诊师入驻申请与审核链路
- 新增 attendant_application 表与 5 个接口:提交/我的申请/审核列表/ 材料大图/审批,/mine 注册在 /:id 之前 - 提交侧按员工档案岗位分支:在职陪诊师与管理员及其他岗位 409 拒绝, 转岗由管理员后台显式操作;停用陪诊师可重新申请 - 审批两步走不依赖事务:条件更新抢占 pending,ensureEmployee 单条 条件 upsert 幂等建档(只放行无档案或已有 attendant 档案), 失败靠 approvedEmployeeId 为空续跑 - 岗位冲突时申请单条件回滚为 pending,不卡死在"已通过但未建档" - employee.userId 加 partial unique 索引并移除 employeeNo 默认值, 附迁移与存量校验脚本;员工管理端绑定账号查重与 userIdSource 标记 - 证件照复用 parseImage(单张 3MB),入驻前缀放宽请求体上限; 索引创建失败改为记日志,避免启动即崩
This commit is contained in:
@@ -11,9 +11,9 @@ import ResponseUtil from './utils/responseUtil.js';
|
||||
|
||||
const STATIC_DIR = fileURLToPath(new URL('./statics', import.meta.url));
|
||||
|
||||
// 语音/图片识别与培训报名材料走 base64 JSON,单请求体可能达到数 MB;
|
||||
// 语音/图片识别、培训报名材料与陪诊师入驻证件照走 base64 JSON,单请求体可能达到数 MB;
|
||||
// 只对这些前缀放宽解析上限,其余接口维持 1MB,避免全局放大内存占用
|
||||
const LARGE_BODY_PREFIXES = ['/health/ai/', '/health/training-application'];
|
||||
const LARGE_BODY_PREFIXES = ['/health/ai/', '/health/training-application', '/health/attendant-application'];
|
||||
const DEFAULT_BODY_LIMIT = '1mb';
|
||||
const LARGE_BODY_LIMIT = '20mb';
|
||||
const defaultBodyParser = bodyParser({
|
||||
|
||||
@@ -0,0 +1,572 @@
|
||||
import mongoose from "mongoose";
|
||||
import ResponseUtil from "../utils/responseUtil.js";
|
||||
import { DBModel } from "../models/index.js";
|
||||
import { genPinyin, genPinyinFL } from "../models/schema/employee.js";
|
||||
import { HandlerTrainingApplication } from "./training_application.js";
|
||||
|
||||
const MOBILE_REGEX = /^1[3-9]\d{9}$/;
|
||||
const ID_NUMBER_REGEX = /^\d{17}[\dXx]$/;
|
||||
const NAME_MAX = 20;
|
||||
const INTRODUCTION_MAX = 200;
|
||||
const REJECT_REASON_MAX = 200;
|
||||
const AREA_MAX = 10;
|
||||
const AREA_ITEM_MAX = 20;
|
||||
const MAX_PAGE_SIZE = 100;
|
||||
// 岗位中文名:仅用于冲突提示文案。岗位变更本身由管理员在后台显式操作,
|
||||
// 入驻审批不改写已有非陪诊师档案(产品口径:拒绝改写,走人工)
|
||||
const ROLE_LABELS = { nurse: "护士", doctor: "医生", operator: "运营", other: "其他" };
|
||||
// 入驻申请会同时存资质证书与健康证明两张原图,base64 后体积约为原图 1.33 倍。
|
||||
// 单张压到 3MB,两张合计仍能稳定落在 Mongo 单文档 16MB 上限内。
|
||||
const IMAGE_MAX_BYTES = 3 * 1024 * 1024;
|
||||
const KEYWORD_MAX = 64;
|
||||
|
||||
/**
|
||||
* 陪诊师入驻申请
|
||||
*
|
||||
* 与 employee 的关系:本 handler 只写申请单,审核通过时才由 ensureEmployee
|
||||
* 幂等地创建/激活员工档案。员工建档的字段白名单沿用 HandlerEmployee 的口径,
|
||||
* 这里不重复维护一份完整字段表,只写审批必须同步的那几项。
|
||||
*/
|
||||
class HandlerAttendantApplication {
|
||||
/**
|
||||
* 提交回执:给申请人看自己的资料,不含图片(体积大且无回显必要)
|
||||
* 身份证号属于本人提交的数据,回填表单需要,故保留
|
||||
*/
|
||||
static toReceipt(doc) {
|
||||
if (!doc) return null;
|
||||
return {
|
||||
id: doc._id,
|
||||
applicant: {
|
||||
name: doc.applicant?.name || "",
|
||||
mobile: doc.applicant?.mobile || "",
|
||||
idNumber: doc.applicant?.idNumber || "",
|
||||
sex: doc.applicant?.sex || "",
|
||||
serviceAreas: doc.applicant?.serviceAreas || [],
|
||||
introduction: doc.applicant?.introduction || "",
|
||||
},
|
||||
healthExpireDate: HandlerAttendantApplication.formatDate(
|
||||
doc.materials?.healthCertificate?.expireDate
|
||||
),
|
||||
hasQualification: !!doc.materials?.qualification?.data,
|
||||
hasHealthCertificate: !!doc.materials?.healthCertificate?.data,
|
||||
status: doc.status || "pending",
|
||||
rejectReason: doc.review?.rejectReason || "",
|
||||
reviewedAt: doc.review?.reviewedAt || null,
|
||||
createtime: doc.meta?.createtime || null,
|
||||
};
|
||||
}
|
||||
|
||||
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}`;
|
||||
}
|
||||
|
||||
static parseDate(value) {
|
||||
if (!value) return null;
|
||||
const date = new Date(`${String(value).slice(0, 10)}T00:00:00.000Z`);
|
||||
return Number.isNaN(date.getTime()) ? null : date;
|
||||
}
|
||||
|
||||
/**
|
||||
* 入参校验
|
||||
*
|
||||
* 图片复用培训报名的 parseImage:那里已经做了 data URL 前缀、base64 合法性、
|
||||
* 5MB 上限和 JPEG/PNG 文件头校验,不另写一份容易走样的实现
|
||||
*
|
||||
* @param {Object} body 请求体
|
||||
* @param {Object|null} previous 被驳回的上一份申请,未重新上传材料时沿用其图片,
|
||||
* 避免用户重新提交还要再传一次几 MB 的证件照
|
||||
*/
|
||||
static parsePayload(body = {}, previous = null) {
|
||||
const fallback = previous?.materials || null;
|
||||
const applicant = body.applicant || {};
|
||||
const name = String(applicant.name || "").trim();
|
||||
const mobile = String(applicant.mobile || "").trim();
|
||||
const idNumber = String(applicant.idNumber || "").trim().toUpperCase();
|
||||
const sex = String(applicant.sex || "").trim();
|
||||
const introduction = String(applicant.introduction || "").trim();
|
||||
const serviceAreas = Array.isArray(applicant.serviceAreas)
|
||||
? applicant.serviceAreas.map((item) => String(item || "").trim()).filter(Boolean)
|
||||
: [];
|
||||
|
||||
if (!name) return { error: "请填写姓名" };
|
||||
if (name.length > NAME_MAX) return { error: `姓名不能超过 ${NAME_MAX} 个字` };
|
||||
if (!MOBILE_REGEX.test(mobile)) return { error: "请填写正确的 11 位手机号" };
|
||||
if (!ID_NUMBER_REGEX.test(idNumber)) return { error: "请填写 18 位身份证号,末位可为 X" };
|
||||
if (sex && !["male", "female"].includes(sex)) return { error: "性别取值不正确" };
|
||||
if (!serviceAreas.length) return { error: "请至少选择一个服务城市" };
|
||||
if (serviceAreas.length > AREA_MAX) return { error: `服务城市最多 ${AREA_MAX} 个` };
|
||||
if (serviceAreas.some((item) => item.length > AREA_ITEM_MAX)) {
|
||||
return { error: `单个服务城市不能超过 ${AREA_ITEM_MAX} 个字` };
|
||||
}
|
||||
if (introduction.length > INTRODUCTION_MAX) {
|
||||
return { error: `个人简介不能超过 ${INTRODUCTION_MAX} 个字` };
|
||||
}
|
||||
|
||||
const qualification = body.materials?.qualification
|
||||
? HandlerTrainingApplication.parseImage(
|
||||
body.materials.qualification,
|
||||
"资质证书照片",
|
||||
IMAGE_MAX_BYTES
|
||||
)
|
||||
: fallback?.qualification?.data
|
||||
? { value: { data: fallback.qualification.data, mime: fallback.qualification.mime } }
|
||||
: { error: "请上传资质证书照片" };
|
||||
if (qualification.error) return qualification;
|
||||
|
||||
const healthPhoto = body.materials?.healthCertificate
|
||||
? HandlerTrainingApplication.parseImage(
|
||||
body.materials.healthCertificate,
|
||||
"健康证明照片",
|
||||
IMAGE_MAX_BYTES
|
||||
)
|
||||
: fallback?.healthCertificate?.data
|
||||
? {
|
||||
value: {
|
||||
data: fallback.healthCertificate.data,
|
||||
mime: fallback.healthCertificate.mime,
|
||||
},
|
||||
}
|
||||
: { error: "请上传健康证明照片" };
|
||||
if (healthPhoto.error) return healthPhoto;
|
||||
|
||||
const expireDate =
|
||||
HandlerAttendantApplication.parseDate(body.healthExpireDate) ||
|
||||
fallback?.healthCertificate?.expireDate ||
|
||||
null;
|
||||
if (!expireDate) return { error: "请填写健康证明有效期" };
|
||||
// 过期健康证无法支撑"公示有效期",直接挡在提交环节。
|
||||
// 到期当天仍算有效(与公示侧 isHealthCertificateValid 同口径):
|
||||
// parseDate 是 UTC 零点,换算到东八区当天 23:59:59.999 再比较
|
||||
const endOfDay = Date.UTC(
|
||||
expireDate.getUTCFullYear(),
|
||||
expireDate.getUTCMonth(),
|
||||
expireDate.getUTCDate(),
|
||||
15, 59, 59, 999
|
||||
);
|
||||
if (endOfDay < Date.now()) return { error: "健康证明已过期,请更新后再提交" };
|
||||
|
||||
return {
|
||||
value: {
|
||||
applicant: { name, mobile, idNumber, sex, serviceAreas, introduction },
|
||||
materials: {
|
||||
qualification: qualification.value,
|
||||
healthCertificate: { ...healthPhoto.value, expireDate },
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// 点号路径 → 嵌套对象,构造器不认 "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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成工号
|
||||
*
|
||||
* employeeNo 是 unique + sparse:sparse 只跳过"字段不存在"的文档,
|
||||
* 所以工号必须显式生成且不能为空串,否则多条无工号档案会互相撞唯一索引
|
||||
*/
|
||||
static generateEmployeeNo() {
|
||||
const now = new Date();
|
||||
const stamp = [
|
||||
now.getFullYear(),
|
||||
String(now.getMonth() + 1).padStart(2, "0"),
|
||||
String(now.getDate()).padStart(2, "0"),
|
||||
].join("");
|
||||
const rand = String(Math.floor(Math.random() * 10000)).padStart(4, "0");
|
||||
return `ATT${stamp}${rand}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 幂等建档:已有陪诊师档案时激活并同步资料,没有才新建;
|
||||
* 其他岗位(admin/nurse/doctor/operator/other)档案拒绝改写,
|
||||
* 岗位变更由管理员在后台显式操作
|
||||
*
|
||||
* 单条条件 upsert 原子完成"激活或建"(userId 有 partial unique 索引兜底),
|
||||
* 消除先 findOne 再 create 之间的并发窗口;插入撞 employeeNo 唯一索引时换号重试。
|
||||
* 不使用 Mongo 事务:本项目没有副本集事务的使用先例,
|
||||
* 改为"先抢占申请状态,再调用本方法",失败后管理员重按"通过"即可续跑
|
||||
*
|
||||
* 注意:这里绕过了 EmployeeSchema 的 pre("save"),拼音字段必须手动同步
|
||||
*/
|
||||
static async ensureEmployee(doc) {
|
||||
const name = doc.applicant?.name || "";
|
||||
const patch = {
|
||||
"profile.name": name,
|
||||
"profile.sex": doc.applicant?.sex || "",
|
||||
"profile.phone": doc.applicant?.mobile || "",
|
||||
"profile.idNumber": doc.applicant?.idNumber || "",
|
||||
"profile.pinyin": genPinyin(name),
|
||||
"profile.pinyinFL": genPinyinFL(name),
|
||||
"attendantInfo.serviceAreas": doc.applicant?.serviceAreas || [],
|
||||
introduction: doc.applicant?.introduction || "",
|
||||
};
|
||||
const expireDate = doc.materials?.healthCertificate?.expireDate;
|
||||
if (expireDate) patch["work.healthCertificate.expireDate"] = expireDate;
|
||||
|
||||
// 非陪诊师岗位档案不允许被入驻审批改写(提交侧已拦,这里再防一手):
|
||||
// 直接报错而不是让 upsert 走插入分支撞 userId 唯一索引
|
||||
const existing = await DBModel.Employee.findOne({ userId: doc.userId })
|
||||
.select("role")
|
||||
.lean()
|
||||
.exec();
|
||||
if (existing && existing.role !== "attendant") {
|
||||
const err = new Error(
|
||||
existing.role === "admin"
|
||||
? "该账号已绑定管理员员工档案,无法按陪诊师开通"
|
||||
: "该账号已绑定其他岗位的员工档案,请先由管理员确认岗位后再审核"
|
||||
);
|
||||
err.code = existing.role === "admin" ? "ADMIN_EMPLOYEE" : "ROLE_CONFLICT";
|
||||
throw err;
|
||||
}
|
||||
|
||||
// 命中已有档案时只更新 attendant 记录(停用/离职的陪诊师重新激活走这里);
|
||||
// 其他岗位档案上方已拒绝,并发窗口里刚被建档的极端情形由 E11000 分支兜底
|
||||
for (let i = 0; i < 5; i++) {
|
||||
try {
|
||||
const employee = await DBModel.Employee.findOneAndUpdate(
|
||||
{ userId: doc.userId, role: "attendant" },
|
||||
{
|
||||
$set: {
|
||||
...patch,
|
||||
role: "attendant",
|
||||
status: "active",
|
||||
userIdSource: "application",
|
||||
"meta.updatetime": Date.now(),
|
||||
},
|
||||
// 只在插入时写入。注意不能写成 $setOnInsert: { meta: {...} }:
|
||||
// 那是 meta 的父路径,与 $set 里的 meta.updatetime 构成路径冲突,
|
||||
// MongoDB 会报 "Updating the path 'meta' would create a conflict at 'meta'"
|
||||
$setOnInsert: {
|
||||
employeeNo: HandlerAttendantApplication.generateEmployeeNo(),
|
||||
"meta.createtime": Date.now(),
|
||||
},
|
||||
},
|
||||
{ new: true, upsert: true }
|
||||
).exec();
|
||||
return employee;
|
||||
} catch (err) {
|
||||
if (err?.code !== 11000) throw err;
|
||||
// employeeNo 撞号:换号重试。
|
||||
// userId 撞唯一索引发生在"并发下另一请求刚建档"的窗口:
|
||||
// attendant 档案下一轮走更新分支自然收敛;非 attendant 档案重试永远不会命中,
|
||||
// 重查确认后直接报可读错误,避免空转 5 次抛「生成工号失败」
|
||||
if (err.keyValue && Object.prototype.hasOwnProperty.call(err.keyValue, "userId")) {
|
||||
const raced = await DBModel.Employee.findOne({ userId: doc.userId })
|
||||
.select("role")
|
||||
.lean()
|
||||
.exec();
|
||||
if (raced && raced.role !== "attendant") {
|
||||
const conflict = new Error("该账号已绑定其他岗位的员工档案,请先由管理员确认岗位后再审核");
|
||||
conflict.code = "ROLE_CONFLICT";
|
||||
throw conflict;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
throw new Error("生成工号失败");
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交申请
|
||||
*
|
||||
* 在职陪诊师、已有待审核申请都直接返回结果,不报错——用户重复点击时看到的是结果;
|
||||
* 管理员与其他岗位档案返回 409,避免审批把岗位改写。
|
||||
*/
|
||||
async createApplication(ctx) {
|
||||
try {
|
||||
const userId = ctx.state.user?._id;
|
||||
if (!userId) return ResponseUtil.unauthorized(ctx, "登录已失效");
|
||||
|
||||
// 已有员工档案的账号:在职陪诊师无需申请;管理员与其他岗位(护士/医生/运营)
|
||||
// 一律拒绝——审批会把 role 改写为 attendant,岗位变更应由管理员在后台显式操作
|
||||
const existingEmployee = await DBModel.Employee.findOne({ userId })
|
||||
.select("role status")
|
||||
.lean()
|
||||
.exec();
|
||||
if (existingEmployee) {
|
||||
if (existingEmployee.role === "attendant" && existingEmployee.status === "active") {
|
||||
return ResponseUtil.error(ctx, "你已是陪诊师,无需重复申请", { isAttendant: true }, 409);
|
||||
}
|
||||
if (existingEmployee.role === "admin") {
|
||||
return ResponseUtil.error(ctx, "当前账号已是管理员,无需申请陪诊师", null, 409);
|
||||
}
|
||||
if (existingEmployee.role !== "attendant") {
|
||||
const label = ROLE_LABELS[existingEmployee.role] || existingEmployee.role;
|
||||
return ResponseUtil.error(
|
||||
ctx,
|
||||
`该账号已绑定「${label}」员工档案,如需转岗陪诊师请联系客服在后台变更`,
|
||||
null,
|
||||
409
|
||||
);
|
||||
}
|
||||
// attendant 但已停用/离职/暂停:允许重新申请,审批通过时激活原档案
|
||||
}
|
||||
|
||||
const latest = await DBModel.AttendantApplication.findLatestByUser(userId);
|
||||
if (latest && latest.status === "pending") {
|
||||
return ResponseUtil.success(
|
||||
ctx,
|
||||
{ application: HandlerAttendantApplication.toReceipt(latest), duplicated: true },
|
||||
"申请已提交,请等待审核"
|
||||
);
|
||||
}
|
||||
|
||||
// 弱校验:正常流程用户都从小程序进来,user 记录里会有 wxapp-escort-admin 条目。
|
||||
// 缺失多半是历史账号或接口直调,只告警不阻断,避免误伤老用户
|
||||
const user = ctx.state.user;
|
||||
const enteredAdminApp =
|
||||
(Array.isArray(user?.apps) && user.apps.some((m) => m?.appId === "wxapp-escort-admin")) ||
|
||||
Boolean(user?.app?.["wxapp-escort-admin"]);
|
||||
if (!enteredAdminApp) {
|
||||
console.warn(
|
||||
`[attendant-application] 用户 ${userId} 提交入驻申请,但其 user 记录没有 wxapp-escort-admin 应用条目`
|
||||
);
|
||||
}
|
||||
|
||||
// 驳回后重新提交:允许不重传证件照,沿用上一份的材料
|
||||
const previous = latest && latest.status === "rejected" ? latest : null;
|
||||
const result = HandlerAttendantApplication.parsePayload(ctx.request.body, previous);
|
||||
if (result.error) return ResponseUtil.badRequest(ctx, result.error);
|
||||
|
||||
// 换微信号场景:同身份证号已绑在其他员工档案上时不新建第二条,
|
||||
// 引导客服改绑;档案可能是任意岗位,文案按实际岗位区分,避免误导
|
||||
const rebound = await DBModel.Employee.findOne({
|
||||
"profile.idNumber": result.value.applicant.idNumber,
|
||||
userId: { $ne: userId },
|
||||
})
|
||||
.select("role profile.name")
|
||||
.lean()
|
||||
.exec();
|
||||
if (rebound) {
|
||||
const label = ROLE_LABELS[rebound.role] || rebound.role;
|
||||
return ResponseUtil.error(
|
||||
ctx,
|
||||
rebound.role === "attendant"
|
||||
? `该身份证号已绑定陪诊师「${rebound.profile?.name || ""}」,如已更换微信请联系客服改绑`
|
||||
: `该身份证号已绑定「${label}」员工档案,如需转岗陪诊师请联系客服处理`,
|
||||
{ reboundRequired: true },
|
||||
409
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const application = await DBModel.AttendantApplication.createApplication({
|
||||
userId,
|
||||
...result.value,
|
||||
});
|
||||
return ResponseUtil.success(
|
||||
ctx,
|
||||
{ application: HandlerAttendantApplication.toReceipt(application) },
|
||||
"申请已提交"
|
||||
);
|
||||
} catch (err) {
|
||||
// 并发双击:唯一索引兜底,回落到已存在的那条申请
|
||||
if (err?.code === 11000) {
|
||||
const current = await DBModel.AttendantApplication.findPendingByUser(userId);
|
||||
return ResponseUtil.success(
|
||||
ctx,
|
||||
{
|
||||
application: HandlerAttendantApplication.toReceipt(current),
|
||||
duplicated: true,
|
||||
},
|
||||
"申请已提交,请等待审核"
|
||||
);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
}
|
||||
|
||||
// 当前账号最新一条申请,供小程序申请页判断展示哪个视图
|
||||
async getMyApplication(ctx) {
|
||||
try {
|
||||
const userId = ctx.state.user?._id;
|
||||
if (!userId) return ResponseUtil.unauthorized(ctx, "登录已失效");
|
||||
|
||||
const application = await DBModel.AttendantApplication.findLatestByUser(userId);
|
||||
return ResponseUtil.success(
|
||||
ctx,
|
||||
{ application: HandlerAttendantApplication.toReceipt(application) },
|
||||
"查询成功"
|
||||
);
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
}
|
||||
|
||||
async getApplications(ctx) {
|
||||
try {
|
||||
const { status, keyword } = ctx.request.query;
|
||||
// all = 不限状态(回看历史);缺省仍按 pending,与审核台默认页签一致
|
||||
if (status && !["all", "pending", "approved", "rejected"].includes(status)) {
|
||||
return ResponseUtil.badRequest(ctx, "审核状态筛选值不正确");
|
||||
}
|
||||
|
||||
const page = Math.max(parseInt(ctx.request.query.page, 10) || 1, 1);
|
||||
const pageSize = Math.min(
|
||||
Math.max(parseInt(ctx.request.query.pageSize, 10) || 20, 1),
|
||||
MAX_PAGE_SIZE
|
||||
);
|
||||
const result = await DBModel.AttendantApplication.findApplicationPage({
|
||||
page,
|
||||
pageSize,
|
||||
status: status && status !== "all" ? status : status === "all" ? "" : "pending",
|
||||
// 关键词可能以数组形式传入(?keyword=a&keyword=b),统一收敛成字符串
|
||||
keyword: String(keyword || "").trim().slice(0, KEYWORD_MAX),
|
||||
});
|
||||
return ResponseUtil.success(ctx, { ...result, page, pageSize }, "查询成功");
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
}
|
||||
|
||||
// 材料大图单独取:只在管理员点开弹窗时加载,避免列表接口承担图片体积。
|
||||
// 身份证号一并在此返回(列表刻意排除),审核人需要核对
|
||||
async getApplicationMaterials(ctx) {
|
||||
try {
|
||||
const { id } = ctx.params;
|
||||
if (!mongoose.Types.ObjectId.isValid(id)) {
|
||||
return ResponseUtil.badRequest(ctx, "申请ID不合法");
|
||||
}
|
||||
|
||||
const application = await DBModel.AttendantApplication.findById(id)
|
||||
.select("applicant.name applicant.idNumber materials")
|
||||
.lean()
|
||||
.exec();
|
||||
if (!application) return ResponseUtil.notFound(ctx, "申请不存在");
|
||||
|
||||
return ResponseUtil.success(
|
||||
ctx,
|
||||
{
|
||||
applicantName: application.applicant?.name || "",
|
||||
// 审核人需要核对身份证号:列表刻意不返回,在这个管理员专用接口里给全
|
||||
applicantIdNumber: application.applicant?.idNumber || "",
|
||||
qualification: application.materials?.qualification || null,
|
||||
healthCertificate: application.materials?.healthCertificate || null,
|
||||
},
|
||||
"查询成功"
|
||||
);
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 审核
|
||||
*
|
||||
* 两步走,不依赖事务:
|
||||
* 1. 条件更新抢占 pending → approved/rejected,并发审批只有一个成功
|
||||
* 2. 幂等建档;若第二步失败,管理员重按"通过"时靠 approvedEmployeeId 为空续跑
|
||||
*/
|
||||
async reviewApplication(ctx) {
|
||||
try {
|
||||
const { id } = ctx.params;
|
||||
const { action, reason } = ctx.request.body || {};
|
||||
if (!mongoose.Types.ObjectId.isValid(id)) {
|
||||
return ResponseUtil.badRequest(ctx, "申请ID不合法");
|
||||
}
|
||||
if (!["approve", "reject"].includes(action)) {
|
||||
return ResponseUtil.badRequest(ctx, "审核动作不正确");
|
||||
}
|
||||
|
||||
const reviewerId = ctx.state.user?._id;
|
||||
|
||||
if (action === "reject") {
|
||||
const rejectReason = String(reason || "").trim();
|
||||
if (!rejectReason) return ResponseUtil.badRequest(ctx, "请填写驳回原因");
|
||||
if (rejectReason.length > REJECT_REASON_MAX) {
|
||||
return ResponseUtil.badRequest(ctx, `驳回原因不能超过 ${REJECT_REASON_MAX} 个字`);
|
||||
}
|
||||
|
||||
const rejected = await DBModel.AttendantApplication.findOneAndUpdate(
|
||||
{ _id: id, status: "pending" },
|
||||
{ $set: { status: "rejected", review: { reviewerId, reviewedAt: Date.now(), rejectReason }, "meta.updatetime": Date.now() } },
|
||||
{ new: true }
|
||||
).exec();
|
||||
|
||||
if (!rejected) {
|
||||
const exists = await DBModel.AttendantApplication.findById(id).select("status").lean().exec();
|
||||
if (!exists) return ResponseUtil.notFound(ctx, "申请不存在");
|
||||
return ResponseUtil.error(ctx, "该申请已处理,请刷新列表", null, 409);
|
||||
}
|
||||
|
||||
return ResponseUtil.success(
|
||||
ctx,
|
||||
{ application: HandlerAttendantApplication.toReceipt(rejected) },
|
||||
"已驳回"
|
||||
);
|
||||
}
|
||||
|
||||
let doc = await DBModel.AttendantApplication.findOneAndUpdate(
|
||||
{ _id: id, status: "pending" },
|
||||
{ $set: { status: "approved", review: { reviewerId, reviewedAt: Date.now() }, "meta.updatetime": Date.now() } },
|
||||
{ new: true }
|
||||
).exec();
|
||||
|
||||
if (!doc) {
|
||||
doc = await DBModel.AttendantApplication.findById(id).exec();
|
||||
if (!doc) return ResponseUtil.notFound(ctx, "申请不存在");
|
||||
if (doc.status !== "approved") {
|
||||
return ResponseUtil.error(ctx, "该申请已处理,请刷新列表", null, 409);
|
||||
}
|
||||
// 已通过且已建档:重复点击按成功返回,避免管理员误以为是失败
|
||||
if (doc.approvedEmployeeId) {
|
||||
return ResponseUtil.success(
|
||||
ctx,
|
||||
{ application: HandlerAttendantApplication.toReceipt(doc), employeeId: doc.approvedEmployeeId },
|
||||
"该申请已通过"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let employee = null;
|
||||
try {
|
||||
// 岗位冲突(管理员档案或其他岗位档案)由 ensureEmployee 统一拦截
|
||||
employee = await HandlerAttendantApplication.ensureEmployee(doc);
|
||||
} catch (err) {
|
||||
if (err?.code === "ADMIN_EMPLOYEE" || err?.code === "ROLE_CONFLICT") {
|
||||
// 抢占步骤已把单据置为 approved,直接返回 409 会让它卡死在
|
||||
// "已通过但未建档":reject 只认 pending,管理员既无法驳回也无法重审。
|
||||
// 条件回滚为 pending,转岗处理完后管理员可重新审核或驳回;
|
||||
// 并发下另一管理员若已再次抢占,条件不匹配,回滚无副作用
|
||||
await DBModel.AttendantApplication.updateOne(
|
||||
{ _id: doc._id, status: "approved", approvedEmployeeId: null },
|
||||
{ $set: { status: "pending", review: {}, "meta.updatetime": Date.now() } }
|
||||
).exec();
|
||||
return ResponseUtil.error(ctx, err.message, null, 409);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
|
||||
await DBModel.AttendantApplication.updateOne(
|
||||
{ _id: doc._id },
|
||||
{ $set: { approvedEmployeeId: employee._id, "meta.updatetime": Date.now() } }
|
||||
).exec();
|
||||
return ResponseUtil.success(
|
||||
ctx,
|
||||
{ application: HandlerAttendantApplication.toReceipt(doc), employeeId: employee._id },
|
||||
"审核通过,已开通陪诊师权限"
|
||||
);
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export { HandlerAttendantApplication };
|
||||
+37
-3
@@ -301,6 +301,19 @@ class HandlerEmployee {
|
||||
}
|
||||
}
|
||||
|
||||
// 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);
|
||||
@@ -310,17 +323,23 @@ class HandlerEmployee {
|
||||
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 唯一索引冲突:给出可读提示,而不是「服务器繁忙」
|
||||
// employeeNo / userId 唯一索引冲突:给出可读提示,而不是「服务器繁忙」
|
||||
if (err?.code === 11000) {
|
||||
return ResponseUtil.badRequest(ctx, "工号已存在");
|
||||
return ResponseUtil.badRequest(ctx, "工号已存在,或该账号已绑定其他员工档案");
|
||||
}
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
@@ -343,6 +362,21 @@ class HandlerEmployee {
|
||||
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, "员工不存在");
|
||||
@@ -350,7 +384,7 @@ class HandlerEmployee {
|
||||
return ResponseUtil.success(ctx, { employee }, "更新成功");
|
||||
} catch (err) {
|
||||
if (err?.code === 11000) {
|
||||
return ResponseUtil.badRequest(ctx, "工号已存在");
|
||||
return ResponseUtil.badRequest(ctx, "工号已存在,或该账号已绑定其他员工档案");
|
||||
}
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
|
||||
@@ -40,15 +40,15 @@ class HandlerTrainingApplication {
|
||||
|
||||
// 只接受 jpeg/png 的 data URL;同时检查文件签名和原始大小,
|
||||
// 防止把任意 base64 文本当作报名材料写入数据库
|
||||
static parseImage(input, label) {
|
||||
static parseImage(input, label, maxBytes = MAX_IMAGE_BYTES) {
|
||||
const raw = String(input || "").trim();
|
||||
const match = raw.match(/^data:(image\/(?:jpeg|png));base64,([A-Za-z0-9+/]+={0,2})$/);
|
||||
if (!match) return { error: `请上传${label}(JPG/PNG)` };
|
||||
|
||||
const mime = match[1];
|
||||
const buffer = Buffer.from(match[2], "base64");
|
||||
if (!buffer.length || buffer.length > MAX_IMAGE_BYTES) {
|
||||
return { error: `${label}不能超过 5MB` };
|
||||
if (!buffer.length || buffer.length > maxBytes) {
|
||||
return { error: `${label}不能超过 ${Math.round(maxBytes / 1024 / 1024)}MB` };
|
||||
}
|
||||
|
||||
const isJpeg = buffer.length > 2 && buffer[0] === 0xff && buffer[1] === 0xd8;
|
||||
|
||||
+14
-1
@@ -8,6 +8,7 @@ import { HospitalSchema } from "./schema/hospital.js"
|
||||
import { EmployeeSchema } from "./schema/employee.js"
|
||||
import { EmployeeReviewSchema } from "./schema/employee_review.js"
|
||||
import { TrainingApplicationSchema } from "./schema/training_application.js"
|
||||
import { AttendantApplicationSchema } from "./schema/attendant_application.js"
|
||||
import { PaymentRecordSchema } from "./schema/payment_record.js"
|
||||
import { RefundRecordSchema } from "./schema/refund_record.js"
|
||||
import config from '../config.js';
|
||||
@@ -16,7 +17,6 @@ import logger from '../utils/logger.js';
|
||||
class MongoDBSchema {
|
||||
constructor() {
|
||||
this.dbConnection = null;
|
||||
this.User = null;
|
||||
this.EscortRecord = null;
|
||||
this.Organization = null;
|
||||
this.Hospital = null;
|
||||
@@ -24,6 +24,7 @@ class MongoDBSchema {
|
||||
this.HealthProfile = null;
|
||||
this.EmployeeReview = null;
|
||||
this.TrainingApplication = null;
|
||||
this.AttendantApplication = null;
|
||||
this.PaymentRecord = null;
|
||||
this.RefundRecord = null;
|
||||
}
|
||||
@@ -58,8 +59,20 @@ class MongoDBSchema {
|
||||
this.Employee = this.dbConnection.model('employee', EmployeeSchema)
|
||||
this.EmployeeReview = this.dbConnection.model('employee_review', EmployeeReviewSchema)
|
||||
this.TrainingApplication = this.dbConnection.model('training_application', TrainingApplicationSchema)
|
||||
this.AttendantApplication = this.dbConnection.model('attendant_application', AttendantApplicationSchema)
|
||||
this.PaymentRecord = this.dbConnection.model('payment_record', PaymentRecordSchema)
|
||||
this.RefundRecord = this.dbConnection.model('refund_record', RefundRecordSchema)
|
||||
|
||||
// 索引创建失败(如唯一索引遇到存量重复)时 mongoose 会 emit('error'),
|
||||
// 而 EventEmitter 对没有监听器的 'error' 事件会直接抛未捕获异常,
|
||||
// 导致整个服务启动即崩。这里统一监听并记日志,把问题留给索引脚本处理
|
||||
for (const model of Object.values(this)) {
|
||||
if (model && typeof model.on === "function" && model.schema) {
|
||||
model.on("error", (err) => {
|
||||
logger.error(`[mongo] ${model.modelName} 索引/初始化失败: ${err?.message || err}`);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
"use strict";
|
||||
|
||||
import mongoose from "mongoose";
|
||||
|
||||
/**
|
||||
* AttendantApplication Schema
|
||||
* 陪诊师入驻申请
|
||||
*
|
||||
* 与 employee 分离存放:employee 只保存审核通过的真实员工,
|
||||
* 申请单独立成表,驳回原因与历史提交都能留存,也不会让"申请中"的人
|
||||
* 混进员工列表和陪诊师公示。
|
||||
*
|
||||
* 材料图片以 data URL 入参,服务端限制单张 3MB(见 handler 的 IMAGE_MAX_BYTES);
|
||||
* 驳回后重新提交且未重传照片时,会复制上一份的 data URL 到新申请文档,
|
||||
* 保留审计痕迹的代价是每次重提交图片存储翻倍,需由留存/清理策略覆盖。
|
||||
* 审核通过后只把结构化字段(健康证到期日等)同步到 employee,
|
||||
* 原图留在本表做审计,不复制进员工表。
|
||||
*/
|
||||
const ImageSchema = mongoose.Schema(
|
||||
{
|
||||
data: { type: String, required: true, comment: "data URL" },
|
||||
mime: { type: String, enum: ["image/jpeg", "image/png"], required: true, comment: "图片类型" },
|
||||
},
|
||||
{ _id: false }
|
||||
);
|
||||
|
||||
const HealthCertificateSchema = mongoose.Schema(
|
||||
{
|
||||
data: { type: String, required: true, comment: "健康证照片 data URL" },
|
||||
mime: { type: String, enum: ["image/jpeg", "image/png"], required: true, comment: "图片类型" },
|
||||
expireDate: { type: Date, required: true, comment: "健康证有效期至" },
|
||||
},
|
||||
{ _id: false }
|
||||
);
|
||||
|
||||
const AttendantApplicationSchema = mongoose.Schema(
|
||||
{
|
||||
userId: {
|
||||
type: mongoose.Schema.Types.ObjectId,
|
||||
ref: "user",
|
||||
required: true,
|
||||
comment: "申请用户ID",
|
||||
},
|
||||
|
||||
applicant: {
|
||||
name: { type: String, required: true, trim: true, maxlength: 20, comment: "姓名" },
|
||||
mobile: {
|
||||
type: String,
|
||||
required: true,
|
||||
trim: true,
|
||||
match: /^1[3-9]\d{9}$/,
|
||||
comment: "手机号",
|
||||
},
|
||||
idNumber: {
|
||||
type: String,
|
||||
required: true,
|
||||
trim: true,
|
||||
uppercase: true,
|
||||
match: /^\d{17}[\dX]$/,
|
||||
comment: "身份证号",
|
||||
},
|
||||
sex: { type: String, enum: ["male", "female", ""], default: "", comment: "性别" },
|
||||
serviceAreas: { type: [String], default: [], comment: "服务区域/城市列表" },
|
||||
introduction: { type: String, default: "", maxlength: 200, comment: "个人简介" },
|
||||
},
|
||||
|
||||
materials: {
|
||||
qualification: { type: ImageSchema, required: true, comment: "资质证书照片" },
|
||||
healthCertificate: { type: HealthCertificateSchema, required: true, comment: "健康证明" },
|
||||
},
|
||||
|
||||
/**
|
||||
* pending 待审核 / approved 已通过 / rejected 已驳回
|
||||
* v1 不提供用户主动撤回,避免出现没有入口的空状态
|
||||
*/
|
||||
status: {
|
||||
type: String,
|
||||
enum: ["pending", "approved", "rejected"],
|
||||
default: "pending",
|
||||
comment: "审核状态",
|
||||
},
|
||||
|
||||
review: {
|
||||
reviewerId: { type: mongoose.Schema.Types.ObjectId, comment: "审核人用户ID" },
|
||||
reviewedAt: { type: Number, comment: "审核时间" },
|
||||
rejectReason: { type: String, default: "", maxlength: 200, comment: "驳回原因" },
|
||||
},
|
||||
|
||||
// 通过后回填,用于第二步失败时的续跑判断(先改状态,再幂等建档)
|
||||
approvedEmployeeId: {
|
||||
type: mongoose.Schema.Types.ObjectId,
|
||||
default: null,
|
||||
comment: "审核通过后生成的员工ID",
|
||||
},
|
||||
|
||||
meta: {
|
||||
createtime: { type: Number, default: () => Date.now(), comment: "创建时间" },
|
||||
updatetime: { type: Number, default: () => Date.now(), comment: "更新时间" },
|
||||
},
|
||||
},
|
||||
{
|
||||
minimize: false,
|
||||
strict: true,
|
||||
collection: "attendant_application",
|
||||
timestamps: false,
|
||||
}
|
||||
);
|
||||
|
||||
AttendantApplicationSchema.statics.createApplication = async function (data) {
|
||||
data.meta = { createtime: Date.now(), updatetime: Date.now() };
|
||||
const doc = new this(data);
|
||||
return await doc.save();
|
||||
};
|
||||
|
||||
AttendantApplicationSchema.statics.findLatestByUser = async function (userId) {
|
||||
return await this.findOne({ userId }).sort({ "meta.createtime": -1 }).exec();
|
||||
};
|
||||
|
||||
AttendantApplicationSchema.statics.findPendingByUser = async function (userId) {
|
||||
return await this.findOne({ userId, status: "pending" }).exec();
|
||||
};
|
||||
|
||||
/**
|
||||
* 管理端审核列表
|
||||
* 默认不返回 materials:一遍列表带几十张 data URL,响应体会直接失控
|
||||
*/
|
||||
AttendantApplicationSchema.statics.findApplicationPage = async function (options = {}) {
|
||||
const { page = 1, pageSize = 20, status = "pending", keyword } = options;
|
||||
const filter = {};
|
||||
if (status) filter.status = status;
|
||||
if (keyword && String(keyword).trim()) {
|
||||
const safe = String(keyword).trim().replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
const reg = new RegExp(safe, "i");
|
||||
filter.$or = [{ "applicant.name": reg }, { "applicant.mobile": reg }];
|
||||
}
|
||||
|
||||
const skip = (page - 1) * pageSize;
|
||||
const [applications, total] = await Promise.all([
|
||||
this.find(filter)
|
||||
.select("-materials -applicant.idNumber")
|
||||
.sort({ "meta.createtime": -1 })
|
||||
.skip(skip)
|
||||
.limit(pageSize)
|
||||
.lean()
|
||||
.exec(),
|
||||
this.countDocuments(filter).exec(),
|
||||
]);
|
||||
|
||||
return { applications, total };
|
||||
};
|
||||
|
||||
/**
|
||||
* 同一用户同时只允许一条待审核申请
|
||||
*
|
||||
* 只靠 handler 先查后插挡不住并发双击,这里用部分唯一索引兜底;
|
||||
* 已通过/已驳回的历史申请不受约束,用户可以重新提交。
|
||||
*/
|
||||
AttendantApplicationSchema.index(
|
||||
{ userId: 1 },
|
||||
{ unique: true, partialFilterExpression: { status: "pending" } }
|
||||
);
|
||||
// 查"我的最新申请"与审核列表各一条复合索引,不再单独给 userId / status 建单字段索引
|
||||
AttendantApplicationSchema.index({ userId: 1, "meta.createtime": -1 });
|
||||
AttendantApplicationSchema.index({ status: 1, "meta.createtime": -1 });
|
||||
|
||||
export { AttendantApplicationSchema };
|
||||
@@ -25,16 +25,26 @@ const TrainingSchema = mongoose.Schema(
|
||||
const EmployeeSchema = mongoose.Schema(
|
||||
{
|
||||
// 工号(业务雇佣标识)
|
||||
employeeNo: { type: String, default: "", unique: true, sparse: true, comment: "工号" },
|
||||
// 不设默认值:唯一索引是 sparse 的,只跳过"字段缺失"的文档;
|
||||
// 若默认写成空串,多条无工号的档案会共享 "" 而互相撞唯一索引
|
||||
employeeNo: { type: String, unique: true, sparse: true, comment: "工号" },
|
||||
|
||||
// 登录账号(关联用户体系)
|
||||
// 一个 user 只允许绑定一条员工档案(partial unique 索引兜底,见文件末尾)。
|
||||
// userIdSource 记录绑定来源:manual=管理员在后台手动绑定,application=入驻审批自动绑定
|
||||
userId: {
|
||||
type: mongoose.Schema.Types.ObjectId,
|
||||
ref: "user",
|
||||
index: true,
|
||||
comment: "关联用户ID",
|
||||
},
|
||||
|
||||
userIdSource: {
|
||||
type: String,
|
||||
enum: ["manual", "application", ""],
|
||||
default: "",
|
||||
comment: "userId 绑定来源:后台手动 / 入驻审批",
|
||||
},
|
||||
|
||||
// 所属机构
|
||||
orgId: {
|
||||
type: mongoose.Schema.Types.ObjectId,
|
||||
@@ -249,10 +259,20 @@ EmployeeSchema.statics.findOnlineAttendants = async function (options = {}) {
|
||||
// ==================== 索引定义 ====================
|
||||
|
||||
EmployeeSchema.index({ "profile.name": 1 });
|
||||
// 注意:employeeNo(unique+sparse)与 userId 的索引在字段定义处声明,勿在此重复声明
|
||||
// 注意:employeeNo(unique+sparse)在字段定义处声明,勿在此重复声明
|
||||
EmployeeSchema.index({ orgId: 1, role: 1, status: 1 });
|
||||
EmployeeSchema.index({ role: 1, status: 1 });
|
||||
EmployeeSchema.index({ "profile.phone": 1 });
|
||||
EmployeeSchema.index({ status: 1 });
|
||||
|
||||
export { EmployeeSchema };
|
||||
// 一个账号只能绑一条员工档案。
|
||||
// partial 而非 sparse:历史档案可能存在 userId:null 的显式空值,sparse 挡不住多条 null;
|
||||
// 上索引前先跑 scripts/check_employee_binding.js 确认无存量重复
|
||||
EmployeeSchema.index(
|
||||
{ userId: 1 },
|
||||
{ unique: true, partialFilterExpression: { userId: { $type: "objectId" } } }
|
||||
);
|
||||
|
||||
// genPinyin/genPinyinFL 一并导出:handler 层走 findOneAndUpdate 时绕过了 pre("save"),
|
||||
// 需要自行同步拼音字段
|
||||
export { EmployeeSchema, genPinyin, genPinyinFL };
|
||||
|
||||
@@ -4,6 +4,7 @@ import { HandlerPayment } from "../handler/payment.js";
|
||||
import { HandlerHealthProfile } from "../handler/health_profile.js";
|
||||
import { HandlerResource } from "../handler/resource.js";
|
||||
import { HandlerEmployee } from "../handler/employee.js";
|
||||
import { HandlerAttendantApplication } from "../handler/attendant_application.js";
|
||||
import { HandlerAIMedia } from "../handler/ai_media.js";
|
||||
import { HandlerTrainingApplication } from "../handler/training_application.js";
|
||||
import { HandlerHospital } from "../handler/hospital.js";
|
||||
@@ -80,6 +81,7 @@ function registerRoutes(app) {
|
||||
const handlerHealthProfile = new HandlerHealthProfile();
|
||||
const handlerResource = new HandlerResource();
|
||||
const handlerEmployee = new HandlerEmployee();
|
||||
const handlerAttendantApplication = new HandlerAttendantApplication();
|
||||
const handlerAIMedia = new HandlerAIMedia();
|
||||
const handlerTrainingApplication = new HandlerTrainingApplication();
|
||||
const handlerHospital = new HandlerHospital();
|
||||
@@ -144,6 +146,14 @@ function registerRoutes(app) {
|
||||
router.put("/employee/:id", requireAuth, requireAdmin, updateLimit, handlerEmployee.updateEmployee.bind(handlerEmployee));
|
||||
router.patch("/employee/:id/status", requireAuth, requireAdmin, updateLimit, handlerEmployee.updateEmployeeStatus.bind(handlerEmployee));
|
||||
|
||||
// 陪诊师入驻申请:提交与查询本人申请只要求登录;审核相关必须管理员。
|
||||
// /mine 必须注册在 /:id 之前,否则会被当成 id
|
||||
router.post("/attendant-application", requireAuth, createLimit, handlerAttendantApplication.createApplication.bind(handlerAttendantApplication));
|
||||
router.get("/attendant-application/mine", requireAuth, handlerAttendantApplication.getMyApplication.bind(handlerAttendantApplication));
|
||||
router.get("/attendant-application", requireAuth, requireAdmin, handlerAttendantApplication.getApplications.bind(handlerAttendantApplication));
|
||||
router.get("/attendant-application/:id/materials", requireAuth, requireAdmin, handlerAttendantApplication.getApplicationMaterials.bind(handlerAttendantApplication));
|
||||
router.post("/attendant-application/:id/review", requireAuth, requireAdmin, updateLimit, handlerAttendantApplication.reviewApplication.bind(handlerAttendantApplication));
|
||||
|
||||
// 医院基础信息:列表/详情公开,写接口仅管理员
|
||||
router.get("/hospital", handlerHospital.getHospitals.bind(handlerHospital));
|
||||
router.get("/hospital/:id", handlerHospital.getHospitalById.bind(handlerHospital));
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
/**
|
||||
* 只读体检:扫描 employee.userId 重复绑定,以及 profile.idNumber 重复。
|
||||
*
|
||||
* 上 unique 索引前必须先跑这个:库里已有重复时索引创建会直接失败,
|
||||
* 且重复档案需要人工裁决保留哪条(脚本只报告,不做任何写操作)。
|
||||
*
|
||||
* 用法(在 api/health 下):node scripts/check_employee_binding.js
|
||||
*/
|
||||
import { DBModel } from "../models/index.js";
|
||||
|
||||
DBModel.init();
|
||||
const conn = DBModel.dbConnection;
|
||||
|
||||
async function main() {
|
||||
const employees = conn.collection("employee");
|
||||
|
||||
// ---------- userId 重复 ----------
|
||||
const userDupes = await employees
|
||||
.aggregate([
|
||||
{ $match: { userId: { $ne: null } } },
|
||||
{ $group: { _id: "$userId", n: { $sum: 1 }, ids: { $push: "$_id" } } },
|
||||
{ $match: { n: { $gt: 1 } } },
|
||||
])
|
||||
.toArray();
|
||||
|
||||
console.log(`\n===== employee.userId 重复绑定 =====`);
|
||||
if (!userDupes.length) {
|
||||
console.log(" (none) 可安全创建 unique 索引");
|
||||
}
|
||||
for (const dupe of userDupes) {
|
||||
console.log(` userId=${dupe._id} 共 ${dupe.n} 条:${dupe.ids.join(", ")}`);
|
||||
// 列出每条的裁决参考信息:保留建议 = status=active 且 createtime 最新
|
||||
const docs = await employees
|
||||
.find({ userId: dupe._id })
|
||||
.project({
|
||||
role: 1,
|
||||
status: 1,
|
||||
name: "$profile.name",
|
||||
employeeNo: 1,
|
||||
createtime: "$meta.createtime",
|
||||
})
|
||||
.toArray();
|
||||
for (const doc of docs) {
|
||||
console.log(
|
||||
` - ${doc._id} role=${doc.role} status=${doc.status} name=${doc.name || "-"} no=${doc.employeeNo || "-"} created=${doc.createtime || "-"}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 身份证号重复(申请查重的数据前提) ----------
|
||||
const idDupes = await employees
|
||||
.aggregate([
|
||||
{ $match: { "profile.idNumber": { $exists: true, $ne: "" } } },
|
||||
{ $group: { _id: "$profile.idNumber", n: { $sum: 1 }, ids: { $push: "$_id" } } },
|
||||
{ $match: { n: { $gt: 1 } } },
|
||||
])
|
||||
.toArray();
|
||||
|
||||
console.log(`\n===== employee.profile.idNumber 重复 =====`);
|
||||
if (!idDupes.length) {
|
||||
console.log(" (none)");
|
||||
}
|
||||
for (const dupe of idDupes) {
|
||||
console.log(` idNumber=${dupe._id} 共 ${dupe.n} 条:${dupe.ids.join(", ")}`);
|
||||
}
|
||||
|
||||
// ---------- userId 为空串的脏数据 ----------
|
||||
// 字段定义无默认值,正常不该出现空串;有的话 unique partial 索引会漏掉它们
|
||||
const emptyUserId = await employees.countDocuments({ userId: "" });
|
||||
console.log(`\n===== userId 为空串的文档数 =====`);
|
||||
console.log(` ${emptyUserId}`);
|
||||
|
||||
console.log("\n(脚本只读,未做任何修改)");
|
||||
}
|
||||
|
||||
function run() {
|
||||
main()
|
||||
.catch((e) => {
|
||||
console.error(e);
|
||||
process.exitCode = 1;
|
||||
})
|
||||
.finally(() => conn.close());
|
||||
}
|
||||
|
||||
if (conn.readyState === 1) {
|
||||
run();
|
||||
} else {
|
||||
conn.once("connected", run);
|
||||
conn.once("error", (e) => {
|
||||
console.error(e);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
/**
|
||||
* employee.userId 唯一索引迁移。
|
||||
*
|
||||
* 背景:employee.userId 之前是普通索引(字段级 index: true),同名索引 userId_1
|
||||
* 已经在库里。现在 schema 改成 partial unique,MongoDB 不允许同一个键模式
|
||||
* 同时存在不同选项的索引(IndexOptionsConflict / IndexKeySpecsConflict),
|
||||
* 必须先删旧索引再建新索引,否则 autoIndex 每次启动都会失败。
|
||||
*
|
||||
* 步骤:
|
||||
* 1. 扫存量重复(userId 重复则中止,交人工裁决)
|
||||
* 2. 删除键模式为 { userId: 1 } 的旧索引(不论是否唯一)
|
||||
* 3. 建 { userId: 1 } 的 partial unique 索引(partial: userId 为 objectId,
|
||||
* 让历史 userId 为 null/缺失/字符串的脏数据不受约束)
|
||||
*
|
||||
* 用法(在 api/health 下):
|
||||
* node scripts/migrate_employee_userid_unique_index.js # 仅检查,不执行
|
||||
* node scripts/migrate_employee_userid_unique_index.js --apply # 实际执行
|
||||
*/
|
||||
import { DBModel } from "../models/index.js";
|
||||
|
||||
DBModel.init();
|
||||
const conn = DBModel.dbConnection;
|
||||
const apply = process.argv.includes("--apply");
|
||||
|
||||
const INDEX_NAME = "userId_1";
|
||||
const PARTIAL = { userId: { $type: "objectId" } };
|
||||
|
||||
async function main() {
|
||||
const db = conn.db;
|
||||
const employees = db.collection("employee");
|
||||
|
||||
// ---------- 1. 存量重复检查 ----------
|
||||
const dupes = await employees
|
||||
.aggregate([
|
||||
{ $match: { userId: { $ne: null } } },
|
||||
{ $group: { _id: "$userId", n: { $sum: 1 }, ids: { $push: "$_id" } } },
|
||||
{ $match: { n: { $gt: 1 } } },
|
||||
])
|
||||
.toArray();
|
||||
|
||||
if (dupes.length) {
|
||||
console.log(`发现 ${dupes.length} 组 userId 重复,无法建唯一索引,请先人工处理:`);
|
||||
for (const dupe of dupes) {
|
||||
const docs = await employees
|
||||
.find({ userId: dupe._id })
|
||||
.project({ role: 1, status: 1, name: "$profile.name", createtime: "$meta.createtime" })
|
||||
.toArray();
|
||||
console.log(` userId=${dupe._id} x${dupe.n}`);
|
||||
for (const doc of docs) {
|
||||
console.log(
|
||||
` - ${doc._id} role=${doc.role} status=${doc.status} name=${doc.name || "-"} created=${doc.createtime || "-"}`
|
||||
);
|
||||
}
|
||||
}
|
||||
console.log("\n处理建议:保留 status=active 且创建时间最新的一条,其余改 userId: null 或删除。");
|
||||
return;
|
||||
}
|
||||
console.log("userId 重复检查:无重复,可安全建唯一索引");
|
||||
|
||||
// ---------- 2. 删除旧索引 ----------
|
||||
const indexes = await employees.indexes();
|
||||
const old = indexes.find(
|
||||
(idx) => JSON.stringify(idx.key) === JSON.stringify({ userId: 1 })
|
||||
);
|
||||
if (old) {
|
||||
const isTarget =
|
||||
old.unique === true &&
|
||||
JSON.stringify(old.partialFilterExpression) === JSON.stringify(PARTIAL);
|
||||
if (isTarget) {
|
||||
console.log(`索引 ${old.name} 已是目标形态(partial unique),无需变更`);
|
||||
return;
|
||||
}
|
||||
console.log(
|
||||
`待删除旧索引 ${old.name}(unique=${!!old.unique}, partial=${JSON.stringify(old.partialFilterExpression || null)})`
|
||||
);
|
||||
if (!apply) {
|
||||
console.log("dry-run:加 --apply 执行删除");
|
||||
return;
|
||||
}
|
||||
await employees.dropIndex(old.name);
|
||||
console.log(`已删除 ${old.name}`);
|
||||
} else {
|
||||
console.log("未发现 { userId: 1 } 旧索引,跳过删除");
|
||||
}
|
||||
|
||||
// ---------- 3. 建 partial unique ----------
|
||||
if (!apply) {
|
||||
console.log("dry-run:加 --apply 创建 partial unique 索引");
|
||||
return;
|
||||
}
|
||||
await employees.createIndex({ userId: 1 }, { unique: true, partialFilterExpression: PARTIAL, name: INDEX_NAME });
|
||||
console.log(`已创建 ${INDEX_NAME}:{ userId: 1 } unique + partial(userId 为 objectId)`);
|
||||
}
|
||||
|
||||
if (conn.readyState === 1) {
|
||||
main()
|
||||
.catch((e) => {
|
||||
console.error(e);
|
||||
process.exitCode = 1;
|
||||
})
|
||||
.finally(() => conn.close());
|
||||
} else {
|
||||
conn.once("connected", () =>
|
||||
main()
|
||||
.catch((e) => {
|
||||
console.error(e);
|
||||
process.exitCode = 1;
|
||||
})
|
||||
.finally(() => conn.close())
|
||||
);
|
||||
conn.once("error", (e) => {
|
||||
console.error(e);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,321 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
import { DBModel } from "../models/index.js";
|
||||
import { HandlerAttendantApplication } from "../handler/attendant_application.js";
|
||||
import { HandlerTrainingApplication } from "../handler/training_application.js";
|
||||
import { HandlerEmployee } from "../handler/employee.js";
|
||||
|
||||
const OWNER_ID = "64b000000000000000000001";
|
||||
|
||||
/** 合法 JPEG data URL:只需文件头前缀,parseImage 不解析图片内容 */
|
||||
function jpegDataUrl(extraBytes = 64) {
|
||||
const buffer = Buffer.concat([Buffer.from([0xff, 0xd8, 0xff]), Buffer.alloc(extraBytes)]);
|
||||
return `data:image/jpeg;base64,${buffer.toString("base64")}`;
|
||||
}
|
||||
|
||||
/** 一年后的 YYYY-MM-DD,避免测试随时间失效 */
|
||||
function futureDate() {
|
||||
const date = new Date(Date.now() + 365 * 24 * 60 * 60 * 1000);
|
||||
const month = String(date.getUTCMonth() + 1).padStart(2, "0");
|
||||
const day = String(date.getUTCDate()).padStart(2, "0");
|
||||
return `${date.getUTCFullYear()}-${month}-${day}`;
|
||||
}
|
||||
|
||||
function validPayload(overrides = {}) {
|
||||
return {
|
||||
applicant: {
|
||||
name: "张三",
|
||||
mobile: "13800138000",
|
||||
idNumber: "110101199001011234",
|
||||
sex: "male",
|
||||
serviceAreas: ["北京市"],
|
||||
introduction: "有三年陪诊经验",
|
||||
},
|
||||
materials: {
|
||||
qualification: jpegDataUrl(),
|
||||
healthCertificate: jpegDataUrl(),
|
||||
},
|
||||
healthExpireDate: futureDate(),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
/** 最小 Koa ctx:ResponseUtil 只会用到 status / set / body */
|
||||
function createCtx({ query = {}, body = {}, params = {}, user = { _id: OWNER_ID } } = {}) {
|
||||
return {
|
||||
request: { query, body },
|
||||
params,
|
||||
state: { user },
|
||||
headers: {},
|
||||
status: 200,
|
||||
body: null,
|
||||
set(name, value) {
|
||||
this.headers[name] = value;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function withModel(modelName, stub, fn) {
|
||||
const previous = DBModel[modelName];
|
||||
DBModel[modelName] = stub;
|
||||
return Promise.resolve(fn()).finally(() => {
|
||||
DBModel[modelName] = previous;
|
||||
});
|
||||
}
|
||||
|
||||
test("入驻申请列表把 keyword 透传给查询层且不再抛 ReferenceError", async () => {
|
||||
const calls = [];
|
||||
const stub = {
|
||||
findApplicationPage: async (options) => {
|
||||
calls.push(options);
|
||||
return { applications: [], total: 0 };
|
||||
},
|
||||
};
|
||||
|
||||
await withModel("AttendantApplication", stub, async () => {
|
||||
const ctx = createCtx({
|
||||
query: { status: "all", keyword: " 张三 ", page: "2", pageSize: "10" },
|
||||
});
|
||||
await new HandlerAttendantApplication().getApplications(ctx);
|
||||
|
||||
assert.equal(ctx.body.code, 0);
|
||||
assert.equal(calls.length, 1);
|
||||
assert.equal(calls[0].keyword, "张三");
|
||||
assert.equal(calls[0].status, "");
|
||||
assert.equal(calls[0].page, 2);
|
||||
assert.equal(calls[0].pageSize, 10);
|
||||
});
|
||||
});
|
||||
|
||||
test("入驻申请列表拒绝非法状态值", async () => {
|
||||
const ctx = createCtx({ query: { status: "unknown" } });
|
||||
await new HandlerAttendantApplication().getApplications(ctx);
|
||||
|
||||
assert.equal(ctx.body.code, 400);
|
||||
assert.equal(ctx.body.msg, "审核状态筛选值不正确");
|
||||
});
|
||||
|
||||
test("驳回后重新提交可沿用上一份证件照,无需重复上传", () => {
|
||||
const expireDate = new Date(`${futureDate()}T00:00:00.000Z`);
|
||||
const previous = {
|
||||
materials: {
|
||||
qualification: { data: jpegDataUrl(), mime: "image/jpeg" },
|
||||
healthCertificate: { data: jpegDataUrl(), mime: "image/jpeg", expireDate },
|
||||
},
|
||||
};
|
||||
|
||||
const payload = validPayload();
|
||||
delete payload.materials;
|
||||
delete payload.healthExpireDate;
|
||||
|
||||
const result = HandlerAttendantApplication.parsePayload(payload, previous);
|
||||
assert.equal(result.error, undefined);
|
||||
assert.equal(result.value.materials.qualification.mime, "image/jpeg");
|
||||
assert.equal(result.value.materials.healthCertificate.expireDate, expireDate);
|
||||
});
|
||||
|
||||
test("入驻材料单张图片按 3MB 上限校验", () => {
|
||||
const oversized = Buffer.concat([
|
||||
Buffer.from([0xff, 0xd8, 0xff]),
|
||||
Buffer.alloc(3 * 1024 * 1024),
|
||||
]);
|
||||
const result = HandlerTrainingApplication.parseImage(
|
||||
`data:image/jpeg;base64,${oversized.toString("base64")}`,
|
||||
"资质证书照片",
|
||||
3 * 1024 * 1024
|
||||
);
|
||||
|
||||
assert.match(result.error, /不能超过 3MB/);
|
||||
});
|
||||
|
||||
test("健康证明到期日按东八区当天末判断,已过期直接拒绝", () => {
|
||||
const result = HandlerAttendantApplication.parsePayload(
|
||||
validPayload({ healthExpireDate: "2020-01-01" })
|
||||
);
|
||||
|
||||
assert.equal(result.error, "健康证明已过期,请更新后再提交");
|
||||
});
|
||||
|
||||
test("员工解绑账号时同步清空 userIdSource", async () => {
|
||||
let received = null;
|
||||
const stub = {
|
||||
updateEmployee: async (id, flat) => {
|
||||
received = flat;
|
||||
return { _id: id };
|
||||
},
|
||||
};
|
||||
|
||||
await withModel("Employee", stub, async () => {
|
||||
const ctx = createCtx({ params: { id: OWNER_ID }, body: { userId: "" } });
|
||||
await new HandlerEmployee().updateEmployee(ctx);
|
||||
|
||||
assert.equal(ctx.body.code, 0);
|
||||
assert.equal(received.userId, null);
|
||||
assert.equal(received.userIdSource, "");
|
||||
});
|
||||
});
|
||||
|
||||
/** Employee.findOne 链式 stub:按 filter 区分按账号查与按身份证查重 */
|
||||
function employeeFindOneStub(handler) {
|
||||
return {
|
||||
findOne: (filter) => ({
|
||||
select: () => ({
|
||||
lean: () => ({ exec: async () => handler(filter) }),
|
||||
}),
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
test("已有其他岗位档案的账号提交入驻被拒绝,提示走人工转岗", async () => {
|
||||
const stub = employeeFindOneStub(() => ({ role: "nurse", status: "active", profile: { name: "李护士" } }));
|
||||
|
||||
await withModel("Employee", stub, async () => {
|
||||
const ctx = createCtx({ body: validPayload() });
|
||||
await new HandlerAttendantApplication().createApplication(ctx);
|
||||
|
||||
assert.equal(ctx.body.code, 409);
|
||||
assert.match(ctx.body.msg, /护士/);
|
||||
assert.match(ctx.body.msg, /联系客服/);
|
||||
});
|
||||
});
|
||||
|
||||
test("停用陪诊师重新申请不被岗位拦截,可正常提交", async () => {
|
||||
const employeeStub = employeeFindOneStub((filter) => {
|
||||
// 按账号查:停用陪诊师;按身份证号查重:无冲突
|
||||
if (filter["profile.idNumber"]) return null;
|
||||
return { role: "attendant", status: "suspended", profile: { name: "张三" } };
|
||||
});
|
||||
const applicationStub = {
|
||||
findLatestByUser: async () => null,
|
||||
createApplication: async (data) => ({
|
||||
_id: OWNER_ID,
|
||||
status: "pending",
|
||||
applicant: data.applicant,
|
||||
materials: data.materials,
|
||||
meta: { createtime: Date.now() },
|
||||
}),
|
||||
};
|
||||
|
||||
await withModel("Employee", employeeStub, async () => {
|
||||
await withModel("AttendantApplication", applicationStub, async () => {
|
||||
const ctx = createCtx({
|
||||
body: validPayload(),
|
||||
user: { _id: OWNER_ID, apps: [{ appId: "wxapp-escort-admin", status: "active" }] },
|
||||
});
|
||||
await new HandlerAttendantApplication().createApplication(ctx);
|
||||
|
||||
assert.equal(ctx.body.code, 0);
|
||||
assert.equal(ctx.body.data.application.status, "pending");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test("审批建档遇到非陪诊师岗位档案时拒绝改写", async () => {
|
||||
const stub = employeeFindOneStub(() => ({ role: "doctor" }));
|
||||
|
||||
await withModel("Employee", stub, async () => {
|
||||
await assert.rejects(
|
||||
() =>
|
||||
HandlerAttendantApplication.ensureEmployee({
|
||||
userId: OWNER_ID,
|
||||
applicant: { name: "张三" },
|
||||
materials: {},
|
||||
}),
|
||||
(err) => err.code === "ROLE_CONFLICT"
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
test("停用陪诊师审批通过时复用原档案并激活", async () => {
|
||||
let capturedFilter = null;
|
||||
let capturedUpdate = null;
|
||||
const stub = {
|
||||
findOne: () => ({
|
||||
select: () => ({ lean: () => ({ exec: async () => ({ role: "attendant" }) }) }),
|
||||
}),
|
||||
findOneAndUpdate: (filter, update) => {
|
||||
capturedFilter = filter;
|
||||
capturedUpdate = update;
|
||||
return { exec: async () => ({ _id: OWNER_ID, role: "attendant", status: "active" }) };
|
||||
},
|
||||
};
|
||||
|
||||
await withModel("Employee", stub, async () => {
|
||||
const employee = await HandlerAttendantApplication.ensureEmployee({
|
||||
userId: OWNER_ID,
|
||||
applicant: {
|
||||
name: "张三",
|
||||
sex: "male",
|
||||
mobile: "13800138000",
|
||||
idNumber: "110101199001011234",
|
||||
serviceAreas: ["北京市"],
|
||||
introduction: "",
|
||||
},
|
||||
materials: {},
|
||||
});
|
||||
|
||||
assert.equal(employee._id, OWNER_ID);
|
||||
// 过滤条件只认 attendant,命中已有档案后走更新分支(不新建)
|
||||
assert.equal(capturedFilter.role, "attendant");
|
||||
assert.equal(capturedUpdate.$set.role, "attendant");
|
||||
assert.equal(capturedUpdate.$set.status, "active");
|
||||
assert.equal(capturedUpdate.$set.userIdSource, "application");
|
||||
});
|
||||
});
|
||||
|
||||
test("审批遇岗位冲突时申请单回滚为 pending,不卡死在 approved", async () => {
|
||||
const approvedDoc = {
|
||||
_id: OWNER_ID,
|
||||
status: "approved",
|
||||
approvedEmployeeId: null,
|
||||
applicant: { name: "张三", mobile: "13800138000", idNumber: "110101199001011234" },
|
||||
materials: { healthCertificate: { expireDate: new Date("2030-01-01") } },
|
||||
meta: { createtime: Date.now() },
|
||||
};
|
||||
let rollbackFilter = null;
|
||||
let rollbackUpdate = null;
|
||||
const applicationStub = {
|
||||
findOneAndUpdate: () => ({ exec: async () => approvedDoc }),
|
||||
updateOne: (filter, update) => {
|
||||
rollbackFilter = filter;
|
||||
rollbackUpdate = update;
|
||||
return { exec: async () => ({}) };
|
||||
},
|
||||
};
|
||||
const employeeStub = employeeFindOneStub(() => ({ role: "doctor" }));
|
||||
|
||||
await withModel("AttendantApplication", applicationStub, async () => {
|
||||
await withModel("Employee", employeeStub, async () => {
|
||||
const ctx = createCtx({ params: { id: OWNER_ID }, body: { action: "approve" } });
|
||||
await new HandlerAttendantApplication().reviewApplication(ctx);
|
||||
|
||||
assert.equal(ctx.body.code, 409);
|
||||
assert.match(ctx.body.msg, /确认岗位/);
|
||||
// 只回滚"已抢占但未建档"的单据,回滚目标状态是 pending
|
||||
assert.equal(rollbackFilter.status, "approved");
|
||||
assert.equal(rollbackFilter.approvedEmployeeId, null);
|
||||
assert.equal(rollbackUpdate.$set.status, "pending");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test("身份证被其他岗位档案占用时,查重文案按实际岗位提示", async () => {
|
||||
const employeeStub = employeeFindOneStub((filter) => {
|
||||
// 按账号查:本账号无档案;按身份证查重:命中护士档案
|
||||
if (filter["profile.idNumber"]) return { role: "nurse", profile: { name: "李护士" } };
|
||||
return null;
|
||||
});
|
||||
const applicationStub = { findLatestByUser: async () => null };
|
||||
|
||||
await withModel("Employee", employeeStub, async () => {
|
||||
await withModel("AttendantApplication", applicationStub, async () => {
|
||||
const ctx = createCtx({ body: validPayload() });
|
||||
await new HandlerAttendantApplication().createApplication(ctx);
|
||||
|
||||
assert.equal(ctx.body.code, 409);
|
||||
assert.match(ctx.body.msg, /已绑定「护士」员工档案/);
|
||||
assert.doesNotMatch(ctx.body.msg, /已绑定陪诊师/);
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user