- 新增 attendant_application 表与 5 个接口:提交/我的申请/审核列表/ 材料大图/审批,/mine 注册在 /:id 之前 - 提交侧按员工档案岗位分支:在职陪诊师与管理员及其他岗位 409 拒绝, 转岗由管理员后台显式操作;停用陪诊师可重新申请 - 审批两步走不依赖事务:条件更新抢占 pending,ensureEmployee 单条 条件 upsert 幂等建档(只放行无档案或已有 attendant 档案), 失败靠 approvedEmployeeId 为空续跑 - 岗位冲突时申请单条件回滚为 pending,不卡死在"已通过但未建档" - employee.userId 加 partial unique 索引并移除 employeeNo 默认值, 附迁移与存量校验脚本;员工管理端绑定账号查重与 userIdSource 标记 - 证件照复用 parseImage(单张 3MB),入驻前缀放宽请求体上限; 索引创建失败改为记日志,避免启动即崩
573 lines
24 KiB
JavaScript
573 lines
24 KiB
JavaScript
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 };
|