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"; import { SERVICE_AREAS } from "../resource/services.js"; import logger from "../utils/logger.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 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 (idNumber && !ID_NUMBER_REGEX.test(idNumber)) { return { error: "请填写 18 位身份证号,末位可为 X" }; } if (sex && !["male", "female"].includes(sex)) return { error: "性别取值不正确" }; // 服务城市单选,且必须来自服务目录白名单 if (serviceAreas.length !== 1) return { error: "请选择一个服务城市" }; if (!SERVICE_AREAS.includes(serviceAreas[0])) return { error: "服务城市不在可选范围" }; 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 } } : null; 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, }, } : null; if (healthPhoto?.error) return healthPhoto; const inputExpireDate = HandlerAttendantApplication.parseDate(body.healthExpireDate); if (body.healthExpireDate && !inputExpireDate) { return { error: "健康证明有效期格式不正确" }; } // 只校验本次提交的日期,不沿用上一份的健康证有效期: // 驳回重提的表单已没有日期输入,沿用旧日期会让过期的历史申请永远无法重新提交; // 照片仍沿用 fallback,日期可在审核通过后经材料补传接口更新 const expireDate = inputExpireDate; if (expireDate) { // 过期健康证无法支撑"公示有效期",填了就挡在提交环节。 // 到期当天仍算有效(与公示侧 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: "健康证明已过期,请更新后再提交" }; } const materials = {}; if (qualification) materials.qualification = qualification.value; if (healthPhoto || expireDate) { materials.healthCertificate = {}; if (healthPhoto) Object.assign(materials.healthCertificate, healthPhoto.value); if (expireDate) materials.healthCertificate.expireDate = expireDate; } const applicantValue = { name, mobile, sex, serviceAreas, introduction }; if (idNumber) applicantValue.idNumber = idNumber; return { value: { applicant: applicantValue, materials, }, }; } // 点号路径 → 嵌套对象,构造器不认 "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.pinyin": genPinyin(name), "profile.pinyinFL": genPinyinFL(name), "attendantInfo.serviceAreas": doc.applicant?.serviceAreas || [], introduction: doc.applicant?.introduction || "", }; // 身份证选填:没填就不写,避免空串占用唯一索引 if (doc.applicant?.idNumber) patch["profile.idNumber"] = doc.applicant.idNumber; 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(), // 入驻通过只给实习身份:可查看订单但不能接单,由管理员人工转正。 // 只在新建时写入,停用档案重新激活保留原有阶段,避免转正后被降回实习 "attendantInfo.stage": "intern", }, }, { 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_companion 条目。 // 缺失多半是历史账号或接口直调,只告警不阻断,避免误伤老用户 const user = ctx.state.user; const enteredAdminApp = (Array.isArray(user?.apps) && user.apps.some((m) => m?.appId === "wxapp_companion")) || Boolean(user?.app?.["wxapp_companion"]); if (!enteredAdminApp) { console.warn( `[attendant-application] 用户 ${userId} 提交入驻申请,但其 user 记录没有 wxapp_companion 应用条目` ); } // 驳回后重新提交:允许不重传证件照,沿用上一份的材料 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 idNumber = result.value.applicant.idNumber; if (idNumber) { const rebound = await DBModel.Employee.findOne({ "profile.idNumber": 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); } } /** * 待审核期间修改基本信息 * * 只允许 pending 状态修改姓名/手机号/性别/服务城市/个人简介; * 证件材料、状态与审核信息不经过本接口,避免绕开审核流程。 */ async updateMyApplication(ctx) { try { const userId = ctx.state.user?._id; if (!userId) return ResponseUtil.unauthorized(ctx, "登录已失效"); const application = await DBModel.AttendantApplication.findLatestByUser(userId); if (!application) return ResponseUtil.notFound(ctx, "没有可修改的入驻申请"); if (application.status !== "pending") { return ResponseUtil.error( ctx, application.status === "approved" ? "申请已通过审核,资料不可修改" : "申请已驳回,请修改后重新提交", null, 409 ); } // 复用提交时的校验;材料部分不参与本次更新,只取 applicant const result = HandlerAttendantApplication.parsePayload(ctx.request.body); if (result.error) return ResponseUtil.badRequest(ctx, result.error); const applicant = result.value.applicant; // 条件更新兜底并发审核:提交后管理员恰好先审完,这里不会覆盖已通过的申请 const updated = await DBModel.AttendantApplication.findOneAndUpdate( { _id: application._id, status: "pending" }, { $set: { "applicant.name": applicant.name, "applicant.mobile": applicant.mobile, "applicant.sex": applicant.sex, "applicant.serviceAreas": applicant.serviceAreas, "applicant.introduction": applicant.introduction, "meta.updatetime": Date.now(), }, }, { new: true } ).exec(); if (!updated) { return ResponseUtil.error(ctx, "申请状态已变更,请刷新后重试", null, 409); } return ResponseUtil.success( ctx, { application: HandlerAttendantApplication.toReceipt(updated) }, "个人信息已更新" ); } catch (err) { return ResponseUtil.internalError(ctx, err); } } /** * 证件材料后补 * * 入驻申请提交时材料可为空;审核通过后在个人资料页补传。 * 只覆盖本次传入的字段,未传的保留原值;已驳回的申请不允许补, * 驳回后应在入驻申请页修改并重新提交,避免绕开审核流程。 */ async updateMyMaterials(ctx) { try { const userId = ctx.state.user?._id; if (!userId) return ResponseUtil.unauthorized(ctx, "登录已失效"); const body = ctx.request.body || {}; const hasQualification = Boolean(body.qualification); const hasHealthPhoto = Boolean(body.healthCertificate); const hasExpireDate = Boolean(body.healthExpireDate); if (!hasQualification && !hasHealthPhoto && !hasExpireDate) { return ResponseUtil.badRequest(ctx, "请选择要补充的证件材料"); } const application = await DBModel.AttendantApplication.findLatestByUser(userId); if (!application) return ResponseUtil.notFound(ctx, "没有可补充的入驻申请"); if (application.status === "rejected") { return ResponseUtil.error(ctx, "申请已驳回,请重新提交入驻申请", null, 409); } const update = { "meta.updatetime": Date.now() }; if (hasQualification) { const qualification = HandlerTrainingApplication.parseImage( body.qualification, "资质证书照片", IMAGE_MAX_BYTES ); if (qualification.error) return ResponseUtil.badRequest(ctx, qualification.error); update["materials.qualification"] = qualification.value; } if (hasHealthPhoto) { const healthPhoto = HandlerTrainingApplication.parseImage( body.healthCertificate, "健康证明照片", IMAGE_MAX_BYTES ); if (healthPhoto.error) return ResponseUtil.badRequest(ctx, healthPhoto.error); update["materials.healthCertificate.data"] = healthPhoto.value.data; update["materials.healthCertificate.mime"] = healthPhoto.value.mime; } let expireDate = null; if (hasExpireDate) { expireDate = HandlerAttendantApplication.parseDate(body.healthExpireDate); if (!expireDate) return ResponseUtil.badRequest(ctx, "健康证明有效期格式不正确"); const endOfDay = Date.UTC( expireDate.getUTCFullYear(), expireDate.getUTCMonth(), expireDate.getUTCDate(), 15, 59, 59, 999 ); if (endOfDay < Date.now()) { return ResponseUtil.badRequest(ctx, "健康证明已过期,请更新后再提交"); } update["materials.healthCertificate.expireDate"] = expireDate; } const updated = await DBModel.AttendantApplication.findByIdAndUpdate( application._id, { $set: update }, { new: true } ).exec(); // 已建档的陪诊师同步健康证到期日;同步失败不回滚材料,只记日志 if (expireDate) { try { await DBModel.Employee.updateOne( { userId, role: "attendant" }, { $set: { "work.healthCertificate.expireDate": expireDate, "meta.updatetime": Date.now() } } ).exec(); } catch (err) { logger.error(`[attendant-application] 同步健康证有效期失败 user=${userId}: ${err?.message || err}`); } } return ResponseUtil.success( ctx, { application: HandlerAttendantApplication.toReceipt(updated) }, "材料已补充" ); } 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 };