diff --git a/conf.json b/conf.json index 8be1cf3..482fd9d 100644 --- a/conf.json +++ b/conf.json @@ -2,7 +2,7 @@ "app": { "wxapp-escort": { }, - "wxapp-escort-admin": { + "wxapp_companion": { } }, "wechatpay": { diff --git a/handler/attendant_application.js b/handler/attendant_application.js index 87d6216..c43dc06 100644 --- a/handler/attendant_application.js +++ b/handler/attendant_application.js @@ -3,14 +3,14 @@ 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 AREA_MAX = 10; -const AREA_ITEM_MAX = 20; const MAX_PAGE_SIZE = 100; // 岗位中文名:仅用于冲突提示文案。岗位变更本身由管理员在后台显式操作, // 入驻审批不改写已有非陪诊师档案(产品口径:拒绝改写,走人工) @@ -96,17 +96,19 @@ class HandlerAttendantApplication { 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 (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, @@ -115,8 +117,8 @@ class HandlerAttendantApplication { ) : fallback?.qualification?.data ? { value: { data: fallback.qualification.data, mime: fallback.qualification.mime } } - : { error: "请上传资质证书照片" }; - if (qualification.error) return qualification; + : null; + if (qualification?.error) return qualification; const healthPhoto = body.materials?.healthCertificate ? HandlerTrainingApplication.parseImage( @@ -131,32 +133,45 @@ class HandlerAttendantApplication { mime: fallback.healthCertificate.mime, }, } - : { error: "请上传健康证明照片" }; - if (healthPhoto.error) return healthPhoto; + : null; + 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: "健康证明已过期,请更新后再提交" }; + 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: { name, mobile, idNumber, sex, serviceAreas, introduction }, - materials: { - qualification: qualification.value, - healthCertificate: { ...healthPhoto.value, expireDate }, - }, + applicant: applicantValue, + materials, }, }; } @@ -208,12 +223,13 @@ class HandlerAttendantApplication { "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 || "", }; + // 身份证选填:没填就不写,避免空串占用唯一索引 + if (doc.applicant?.idNumber) patch["profile.idNumber"] = doc.applicant.idNumber; const expireDate = doc.materials?.healthCertificate?.expireDate; if (expireDate) patch["work.healthCertificate.expireDate"] = expireDate; @@ -328,15 +344,15 @@ class HandlerAttendantApplication { ); } - // 弱校验:正常流程用户都从小程序进来,user 记录里会有 wxapp-escort-admin 条目。 + // 弱校验:正常流程用户都从小程序进来,user 记录里会有 wxapp_companion 条目。 // 缺失多半是历史账号或接口直调,只告警不阻断,避免误伤老用户 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"]); + (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-escort-admin 应用条目` + `[attendant-application] 用户 ${userId} 提交入驻申请,但其 user 记录没有 wxapp_companion 应用条目` ); } @@ -346,24 +362,28 @@ class HandlerAttendantApplication { 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 - ); + // 引导客服改绑;档案可能是任意岗位,文案按实际岗位区分,避免误导。 + // 未填写身份证时跳过(先收基本信息,后续补)。 + 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 { @@ -413,6 +433,97 @@ class HandlerAttendantApplication { } } + /** + * 证件材料后补 + * + * 入驻申请提交时材料可为空;审核通过后在个人资料页补传。 + * 只覆盖本次传入的字段,未传的保留原值;已驳回的申请不允许补, + * 驳回后应在入驻申请页修改并重新提交,避免绕开审核流程。 + */ + 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; diff --git a/handler/employee.js b/handler/employee.js index 2bb759a..330cdd8 100644 --- a/handler/employee.js +++ b/handler/employee.js @@ -2,6 +2,7 @@ import mongoose from "mongoose"; import { DBModel } from "../models/index.js"; import { MY_EMPLOYEE_SELECT } from "../models/schema/employee.js"; import ResponseUtil from "../utils/responseUtil.js"; +import { SERVICE_AREAS } from "../resource/services.js"; /** * 陪诊师公示:面向 C 端患者的公开信息展示 @@ -329,6 +330,50 @@ class HandlerEmployee { } } + /** + * 陪诊师本人修改服务城市 + * + * 只允许在职陪诊师操作;城市必须来自服务目录白名单(与入驻申请同一份)。 + * 变更只影响订单池可见范围,不改写入驻申请单里的历史快照。 + */ + async updateMyServiceArea(ctx) { + try { + const userId = ctx.state.user?._id; + if (!userId) { + return ResponseUtil.unauthorized(ctx, "登录已失效"); + } + + const serviceArea = String(ctx.request.body?.serviceArea || "").trim(); + if (!serviceArea) return ResponseUtil.badRequest(ctx, "请选择服务城市"); + if (!SERVICE_AREAS.includes(serviceArea)) { + return ResponseUtil.badRequest(ctx, "服务城市不在可选范围"); + } + + const updated = await DBModel.Employee.findOneAndUpdate( + { userId, role: "attendant", status: "active" }, + { + $set: { + "attendantInfo.serviceAreas": [serviceArea], + "meta.updatetime": Date.now(), + }, + }, + { new: true } + ) + .select(MY_EMPLOYEE_SELECT) + .lean() + .exec(); + if (!updated) return ResponseUtil.forbidden(ctx, "仅在职陪诊师可修改服务城市"); + + return ResponseUtil.success( + ctx, + { employee: HandlerEmployee.decorateMyEmployee(updated) }, + "服务城市已更新" + ); + } catch (err) { + return ResponseUtil.internalError(ctx, err); + } + } + // ==================== 管理端 CRUD ==================== // 与上面的公示接口完全分开:管理端要真实姓名、身份证号、证书编号等内部字段, // 但写入仍走白名单,避免 strict:false 的 schema 被塞入任意字段 diff --git a/handler/escort_record.js b/handler/escort_record.js index d73d9a5..ae96b2e 100644 --- a/handler/escort_record.js +++ b/handler/escort_record.js @@ -151,6 +151,37 @@ class HandlerEscortRecord { return employee?.attendantInfo?.stage === "intern" ? "intern" : "certified"; } + /** + * 服务城市匹配值 + * + * 入驻/个人资料写入的是「北京市」这类带「市」的值,历史手工数据可能不带「市」, + * 查询时同时兼容两种写法,避免存量档案匹配不到订单。 + */ + static cityVariants(areas) { + const set = new Set(); + for (const area of Array.isArray(areas) ? areas : []) { + const text = String(area || "").trim(); + if (!text) continue; + const stripped = text.replace(/市$/, ""); + set.add(text); + set.add(stripped); + if (stripped) set.add(`${stripped}市`); + } + return [...set]; + } + + /** + * 订单是否属于陪诊师的服务城市 + * 未配置城市的存量档案、未填省份的历史订单都保持可见,避免存量数据突然消失 + */ + static matchesServiceArea(record, employee) { + const variants = HandlerEscortRecord.cityVariants(employee?.attendantInfo?.serviceAreas); + if (!variants.length) return true; + const province = String(record?.hospital?.province || "").trim(); + if (!province) return true; + return variants.includes(province); + } + /** * 解析用户下单时选择的陪诊师。 * @@ -218,7 +249,10 @@ class HandlerEscortRecord { const employeeId = String(employee._id); const sharedWith = Array.isArray(record.attendant?.sharedWith) ? record.attendant.sharedWith : []; if (sharedWith.some((id) => String(id) === employeeId)) return true; - if (!record.attendant?.id) return true; + if (!record.attendant?.id) { + // 未分配订单:只有本服务城市的陪诊师可查看 + return HandlerEscortRecord.matchesServiceArea(record, employee); + } return String(record.attendant.id) === String(userId); } @@ -491,13 +525,17 @@ class HandlerEscortRecord { userId: isIntern ? undefined : loginUserId, employeeId: attendantEmployee._id, }; + // 订单池只展示本服务城市的订单;本人已接/被共享的订单不受城市限制 + const poolCities = HandlerEscortRecord.cityVariants( + attendantEmployee.attendantInfo?.serviceAreas + ); const scopeValue = String(scope || ""); if (scopeValue === "pool") { - attendantVisibility = { includeUnassigned: true }; + attendantVisibility = { includeUnassigned: true, poolCities }; } else if (scopeValue === "mine") { attendantVisibility = mineVisibility; } else { - attendantVisibility = { includeUnassigned: true, ...mineVisibility }; + attendantVisibility = { includeUnassigned: true, poolCities, ...mineVisibility }; } } @@ -643,6 +681,10 @@ class HandlerEscortRecord { if (record.attendant?.id) { return ResponseUtil.error(ctx, "订单已被其他陪诊师接单", null, 409); } + // 订单池只展示本城市订单;这里再挡一次,防止绕过列表直接调接口接单 + if (!HandlerEscortRecord.matchesServiceArea(record, employee)) { + return ResponseUtil.forbidden(ctx, "该订单不在你的服务城市"); + } const profile = employee.profile || {}; const updated = await DBModel.EscortRecord.acceptRecord(id, { @@ -1194,7 +1236,7 @@ class HandlerEscortRecord { // 用户端与管理端共用本接口,按调用方 app 区分取消流程: // appId 只用于收紧权限——即使账号同时带管理员角色,从用户端小程序发起的取消 // 也必须走取消申请,否则会在 C 端绕过「已确认订单需人工确认」直接退款。 - // 管理端固定带 appId=wxapp-escort-admin;未带 appId 的历史调用保持原角色判定。 + // 管理端固定带 appId=wxapp_companion;未带 appId 的历史调用保持原角色判定。 const requestAppId = String(ctx.request.body?.appId || ""); const isUserApp = requestAppId === "wxapp-escort"; const role = isUserApp ? null : await resolveEscortAdminRole(user); diff --git a/models/schema/attendant_application.js b/models/schema/attendant_application.js index df44d42..883e9bd 100644 --- a/models/schema/attendant_application.js +++ b/models/schema/attendant_application.js @@ -26,9 +26,10 @@ const ImageSchema = mongoose.Schema( 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: "健康证有效期至" }, + // 证件材料允许后补:照片与有效期都可能缺失,是否成对由 handler 校验 + data: { type: String, comment: "健康证照片 data URL" }, + mime: { type: String, enum: ["image/jpeg", "image/png"], comment: "图片类型" }, + expireDate: { type: Date, comment: "健康证有效期至" }, }, { _id: false } ); @@ -53,20 +54,20 @@ const AttendantApplicationSchema = mongoose.Schema( }, idNumber: { type: String, - required: true, trim: true, uppercase: true, match: /^\d{17}[\dX]$/, - comment: "身份证号", + 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: "健康证明" }, + qualification: { type: ImageSchema, comment: "资质证书照片" }, + healthCertificate: { type: HealthCertificateSchema, comment: "健康证明" }, }, /** diff --git a/models/schema/escort_record.js b/models/schema/escort_record.js index 01c99a3..56097c0 100644 --- a/models/schema/escort_record.js +++ b/models/schema/escort_record.js @@ -289,11 +289,23 @@ EscortRecordSchema.statics.buildRecordFilter = function (options = {}) { if (attendantId) filter["attendant.id"] = attendantId; // 陪诊师订单池:按身份合并可见范围,scope 由服务端计算,不接受前端传入。 // - includeUnassigned:所有在职陪诊师都能看到未分配订单 + // - poolCities:未分配订单只展示本服务城市(本人已接/被共享不受城市限制) // - userId:正式陪诊师还能看到自己已接的订单(实习不能接单,故不传) // - employeeId:被共享的订单 if (attendantVisibility) { const or = []; - if (attendantVisibility.includeUnassigned) or.push({ "attendant.id": null }); + if (attendantVisibility.includeUnassigned) { + const poolClause = { "attendant.id": null }; + const poolCities = attendantVisibility.poolCities; + if (Array.isArray(poolCities) && poolCities.length) { + // 历史订单可能没有省份:无法归属城市时仍保留在池中,避免存量订单消失 + poolClause.$or = [ + { "hospital.province": { $in: poolCities } }, + { "hospital.province": { $in: ["", null] } }, + ]; + } + or.push(poolClause); + } if (attendantVisibility.userId) or.push({ "attendant.id": attendantVisibility.userId }); if (attendantVisibility.employeeId) { or.push({ "attendant.sharedWith": attendantVisibility.employeeId }); diff --git a/resource/services.js b/resource/services.js index d70f163..e6095b1 100644 --- a/resource/services.js +++ b/resource/services.js @@ -14,7 +14,9 @@ * 说明:这些字段不得在前端另行硬编码,前端只读不写; * 后端以本目录为准派生订单的 schedule.duration / schedule.endTime 并校验预约时段。 */ -const SERVICE_AREAS = ['北京市', '天津市'] +// 服务城市白名单:入驻申请、下单校验与陪诊师同城订单过滤共用。 +// 值统一带「市」,与历史订单的 hospital.province 口径一致。 +const SERVICE_AREAS = ['北京市', '上海市', '天津市', '西安市'] const services = [ { @@ -615,4 +617,5 @@ for (const service of services) { service.areas = SERVICE_AREAS } +export { SERVICE_AREAS }; export default services; diff --git a/routes/index.js b/routes/index.js index 161ca96..6581a1f 100644 --- a/routes/index.js +++ b/routes/index.js @@ -148,6 +148,8 @@ function registerRoutes(app) { router.get("/employee/me", requireAuth, handlerEmployee.getMyEmployee.bind(handlerEmployee)); // 首页接单开关落库:仅在职正式陪诊师可切换 router.patch("/employee/me/online", requireAuth, updateLimit, handlerEmployee.updateMyOnlineStatus.bind(handlerEmployee)); + // 陪诊师本人修改服务城市:仅在职陪诊师,城市取值受服务目录白名单限制 + router.patch("/employee/me/service-area", requireAuth, updateLimit, handlerEmployee.updateMyServiceArea.bind(handlerEmployee)); // 员工(陪诊师)管理:管理端 CRUD,必须管理员。 // 与下方公开的 /attendant 公示接口分离:这里返回真实姓名等内部字段 @@ -162,6 +164,8 @@ function registerRoutes(app) { // /mine 必须注册在 /:id 之前,否则会被当成 id router.post("/attendant-application", requireAuth, createLimit, handlerAttendantApplication.createApplication.bind(handlerAttendantApplication)); router.get("/attendant-application/mine", requireAuth, handlerAttendantApplication.getMyApplication.bind(handlerAttendantApplication)); + // 证件材料后补:审核通过后仍可补传,必须注册在 /:id 路由之前 + router.post("/attendant-application/mine/materials", requireAuth, updateLimit, handlerAttendantApplication.updateMyMaterials.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)); diff --git a/test/attendant_application.test.js b/test/attendant_application.test.js index d243180..38d14bb 100644 --- a/test/attendant_application.test.js +++ b/test/attendant_application.test.js @@ -112,7 +112,10 @@ test("驳回后重新提交可沿用上一份证件照,无需重复上传", () 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); + // 照片沿用上一份,但健康证有效期不再继承:重提表单已无日期输入, + // 沿用旧日期会让过期的历史申请永远无法重新提交 + assert.equal(result.value.materials.healthCertificate.data, previous.materials.healthCertificate.data); + assert.equal(result.value.materials.healthCertificate.expireDate, undefined); }); test("入驻材料单张图片按 3MB 上限校验", () => { @@ -201,7 +204,7 @@ test("停用陪诊师重新申请不被岗位拦截,可正常提交", async () await withModel("AttendantApplication", applicationStub, async () => { const ctx = createCtx({ body: validPayload(), - user: { _id: OWNER_ID, apps: [{ appId: "wxapp-escort-admin", status: "active" }] }, + user: { _id: OWNER_ID, apps: [{ appId: "wxapp_companion", status: "active" }] }, }); await new HandlerAttendantApplication().createApplication(ctx); @@ -468,3 +471,163 @@ test("身份证被其他岗位档案占用时,查重文案按实际岗位提 }); }); }); + +test("证件材料全部可空,提交只校验基本信息与城市", () => { + const payload = validPayload(); + delete payload.materials; + delete payload.healthExpireDate; + + const result = HandlerAttendantApplication.parsePayload(payload); + assert.equal(result.error, undefined); + assert.deepEqual(result.value.materials, {}); + assert.deepEqual(result.value.applicant.serviceAreas, ["北京市"]); +}); + +test("身份证先不填也能提交,不落空串", () => { + const payload = validPayload(); + delete payload.applicant.idNumber; + delete payload.materials; + delete payload.healthExpireDate; + + const result = HandlerAttendantApplication.parsePayload(payload); + assert.equal(result.error, undefined); + assert.equal(Object.hasOwn(result.value.applicant, "idNumber"), false); +}); + +test("只补健康证有效期、不传照片也可通过校验", () => { + const payload = validPayload({ materials: {} }); + const result = HandlerAttendantApplication.parsePayload(payload); + + assert.equal(result.error, undefined); + assert.equal(result.value.materials.qualification, undefined); + assert.ok(result.value.materials.healthCertificate.expireDate instanceof Date); + assert.equal(result.value.materials.healthCertificate.data, undefined); +}); + +test("服务城市必须单选且在白名单内", () => { + const base = validPayload().applicant; + + const empty = HandlerAttendantApplication.parsePayload( + validPayload({ applicant: { ...base, serviceAreas: [] } }) + ); + assert.equal(empty.error, "请选择一个服务城市"); + + const multiple = HandlerAttendantApplication.parsePayload( + validPayload({ applicant: { ...base, serviceAreas: ["北京市", "上海市"] } }) + ); + assert.equal(multiple.error, "请选择一个服务城市"); + + const invalid = HandlerAttendantApplication.parsePayload( + validPayload({ applicant: { ...base, serviceAreas: ["广州市"] } }) + ); + assert.equal(invalid.error, "服务城市不在可选范围"); +}); + +test("材料后补:仅合并本次传入字段,不覆盖未提交的材料", async () => { + const application = { + _id: OWNER_ID, + status: "approved", + meta: {}, + }; + let capturedUpdate = null; + const applicationStub = { + findLatestByUser: async () => application, + findByIdAndUpdate: (id, update) => { + capturedUpdate = update; + return { exec: async () => ({ ...application, materials: { qualification: { data: "x" } } }) }; + }, + }; + const employeeStub = { updateOne: () => ({ exec: async () => ({}) }) }; + + await withModel("AttendantApplication", applicationStub, async () => { + await withModel("Employee", employeeStub, async () => { + const ctx = createCtx({ body: { qualification: jpegDataUrl() } }); + await new HandlerAttendantApplication().updateMyMaterials(ctx); + + assert.equal(ctx.body.code, 0); + assert.ok(capturedUpdate.$set["materials.qualification"]); + // 未传健康证明:不能顺带清空或改写 + assert.equal(capturedUpdate.$set["materials.healthCertificate"], undefined); + }); + }); +}); + +test("材料后补:已驳回的申请不允许补传", async () => { + const applicationStub = { + findLatestByUser: async () => ({ _id: OWNER_ID, status: "rejected" }), + }; + + await withModel("AttendantApplication", applicationStub, async () => { + const ctx = createCtx({ body: { qualification: jpegDataUrl() } }); + await new HandlerAttendantApplication().updateMyMaterials(ctx); + + assert.equal(ctx.body.code, 409); + assert.match(ctx.body.msg, /重新提交入驻申请/); + }); +}); + +test("陪诊师本人修改服务城市:在职落库为单城市数组", async () => { + let capturedFilter = null; + let capturedUpdate = null; + const stub = { + findOneAndUpdate: (filter, update) => { + capturedFilter = filter; + capturedUpdate = update; + return { + select: () => ({ + lean: () => ({ + exec: async () => ({ + _id: OWNER_ID, + role: "attendant", + status: "active", + attendantInfo: { stage: "certified", grade: "bronze", serviceAreas: ["上海市"] }, + }), + }), + }), + }; + }, + }; + + await withModel("Employee", stub, async () => { + const ctx = createCtx({ body: { serviceArea: "上海市" } }); + await new HandlerEmployee().updateMyServiceArea(ctx); + + assert.equal(ctx.body.code, 0); + assert.deepEqual(capturedFilter, { userId: OWNER_ID, role: "attendant", status: "active" }); + assert.deepEqual(capturedUpdate.$set["attendantInfo.serviceAreas"], ["上海市"]); + assert.equal(ctx.body.data.employee.attendantInfo.serviceAreas[0], "上海市"); + assert.equal(ctx.body.data.employee.canAcceptOrder, true); + }); +}); + +test("陪诊师本人修改服务城市:白名单外拒绝且不落库", async () => { + const stub = { + findOneAndUpdate: () => { + throw new Error("不应触发落库"); + }, + }; + + await withModel("Employee", stub, async () => { + const ctx = createCtx({ body: { serviceArea: "广州市" } }); + await new HandlerEmployee().updateMyServiceArea(ctx); + + assert.equal(ctx.body.code, 400); + assert.match(ctx.body.msg, /不在可选范围/); + }); +}); + +test("陪诊师本人修改服务城市:非在职陪诊师返回 403", async () => { + const stub = { + findOneAndUpdate: () => ({ + select: () => ({ lean: () => ({ exec: async () => null }) }), + }), + }; + + await withModel("Employee", stub, async () => { + const ctx = createCtx({ body: { serviceArea: "北京市" } }); + await new HandlerEmployee().updateMyServiceArea(ctx); + + assert.equal(ctx.body.code, 403); + assert.match(ctx.body.msg, /仅在职陪诊师/); + }); +}); diff --git a/test/attendant_order_pool.test.js b/test/attendant_order_pool.test.js index ccca0d5..80bb715 100644 --- a/test/attendant_order_pool.test.js +++ b/test/attendant_order_pool.test.js @@ -409,3 +409,60 @@ test("取消共享时订单不存在返回 404", async () => { }) ); }); + +test("订单池按服务城市过滤,scope=mine 不带城市条件", async () => { + const employee = buildEmployee({ + attendantInfo: { stage: "certified", grade: "bronze", serviceAreas: ["上海市"] }, + }); + let captured = null; + const recordStub = { + findRecordPage: async (options) => { + captured = options; + return { records: [], total: 0, counts: {} }; + }, + }; + + await withModel("Employee", employeeFindOneStub(employee), () => + withModel("EscortRecord", recordStub, async () => { + const poolCtx = createCtx({ user: { _id: CERT_USER_ID }, query: { scope: "pool" } }); + await new HandlerEscortRecord().getAttendantRecords(poolCtx); + + assert.equal(poolCtx.body.code, 0); + assert.deepEqual(captured.attendantVisibility.poolCities, ["上海市", "上海"]); + + const mineCtx = createCtx({ user: { _id: CERT_USER_ID }, query: { scope: "mine" } }); + await new HandlerEscortRecord().getAttendantRecords(mineCtx); + + assert.equal(mineCtx.body.code, 0); + // 本人已接订单不受城市限制 + assert.equal(captured.attendantVisibility.poolCities, undefined); + assert.equal(captured.attendantVisibility.includeUnassigned, undefined); + }) + ); +}); + +test("服务城市匹配兼容「市」后缀,未配置城市保持全部可见", () => { + assert.deepEqual(HandlerEscortRecord.cityVariants(["上海市"]), ["上海市", "上海"]); + assert.equal( + HandlerEscortRecord.matchesServiceArea( + { hospital: { province: "上海市" } }, + { attendantInfo: { serviceAreas: ["上海"] } } + ), + true + ); + assert.equal( + HandlerEscortRecord.matchesServiceArea( + { hospital: { province: "北京市" } }, + { attendantInfo: { serviceAreas: ["上海市"] } } + ), + false + ); + // 存量档案没配城市:保持原行为,不因城市过滤而看不到订单 + assert.equal( + HandlerEscortRecord.matchesServiceArea( + { hospital: { province: "北京市" } }, + { attendantInfo: {} } + ), + true + ); +}); diff --git a/test/db_tools.test.js b/test/db_tools.test.js index 56bd9e8..afaa192 100644 --- a/test/db_tools.test.js +++ b/test/db_tools.test.js @@ -368,7 +368,7 @@ test("管理端 Agent 角色以员工档案为准", async () => { await withModel("Employee", stub, async () => { const role = await resolveEscortAdminRole({ _id: OWNER_ID, - app: { "wxapp-escort-admin": { role: ["user"] } }, + app: { "wxapp_companion": { role: ["user"] } }, }); assert.equal(role, "attendant"); @@ -383,7 +383,7 @@ test("显式管理员不依赖员工档案", async () => { await withModel("Employee", stub, async () => { const admin = await resolveEscortAdminRole({ _id: OWNER_ID, - app: { "wxapp-escort-admin": { role: ["admin"] } }, + app: { "wxapp_companion": { role: ["admin"] } }, }); assert.equal(admin, "admin"); assert.equal(stub.calls.length, 0); @@ -395,7 +395,7 @@ test("普通管理端账号无员工档案时拒绝", async () => { await withModel("Employee", stub, async () => { const outsider = await resolveEscortAdminRole({ _id: OWNER_ID, - app: { "wxapp-escort-admin": { role: ["user"] } }, + app: { "wxapp_companion": { role: ["user"] } }, }); assert.equal(outsider, null); }); @@ -406,7 +406,7 @@ test("历史管理员 role 缺失仍按管理员放行", async () => { await withModel("Employee", stub, async () => { const legacy = await resolveEscortAdminRole({ _id: OWNER_ID, - app: { "wxapp-escort-admin": { wxopenid: "o123" } }, + app: { "wxapp_companion": { wxopenid: "o123" } }, }); assert.equal(legacy, "admin"); }); diff --git a/test/logic.test.js b/test/logic.test.js index 84a1add..c5d57f9 100644 --- a/test/logic.test.js +++ b/test/logic.test.js @@ -41,9 +41,9 @@ test("取消状态机独立于服务状态", () => { test("管理端身份要求显式 role=admin", () => { assert.equal(isAdmin(null), false); assert.equal(isAdmin({}), false); - assert.equal(isAdmin({ app: { "wxapp-escort-admin": { role: ["admin"] } } }), true); - assert.equal(isAdmin({ app: { "wxapp-escort-admin": { role: "admin" } } }), true); - assert.equal(isAdmin({ app: { "wxapp-escort-admin": { role: ["user"] } } }), false); + assert.equal(isAdmin({ app: { "wxapp_companion": { role: ["admin"] } } }), true); + assert.equal(isAdmin({ app: { "wxapp_companion": { role: "admin" } } }), true); + assert.equal(isAdmin({ app: { "wxapp_companion": { role: ["user"] } } }), false); }); test("关键词按字面量转义并截断", () => { diff --git a/test/order_permission.test.js b/test/order_permission.test.js index d726904..5cdd819 100644 --- a/test/order_permission.test.js +++ b/test/order_permission.test.js @@ -13,7 +13,7 @@ const PAYMENT_ID = "64b000000000000000000020"; const ADMIN_USER = { _id: ADMIN_ID, - app: { "wxapp-escort-admin": { role: ["admin"] } }, + app: { "wxapp_companion": { role: ["admin"] } }, }; function buildRecord(overrides = {}) { @@ -206,7 +206,7 @@ test("在职陪诊员不能确认未分配给自己的本人订单", async () => const ctx = createCtx({ user: { _id: OWNER_ID, - app: { "wxapp-escort-admin": { role: ["user"] } }, + app: { "wxapp_companion": { role: ["user"] } }, }, body: { status: "confirmed" }, }); diff --git a/utils/permissions.js b/utils/permissions.js index 3b3b1a3..8680800 100644 --- a/utils/permissions.js +++ b/utils/permissions.js @@ -1,7 +1,7 @@ import mongoose from "mongoose"; import { DBModel } from "../models/index.js"; -const ADMIN_APP = "wxapp-escort-admin"; +const ADMIN_APP = "wxapp_companion"; const WEB_ADMIN_APP = "web-escort-admin"; /** @@ -17,7 +17,7 @@ const ADMIN_APP_IDS = [ADMIN_APP, WEB_ADMIN_APP]; * 管理端 app 条目里的角色数组 * * 注意:普通账号首次登录管理端小程序时,user 服务会写入 role: ["user"], - * 所以「有 wxapp-escort-admin 条目」不等于陪诊员,陪诊员身份必须以 Employee 记录为准。 + * 所以「有 wxapp_companion 条目」不等于陪诊员,陪诊员身份必须以 Employee 记录为准。 * * @param {Object} user 登录用户 * @returns {string[]} @@ -32,11 +32,11 @@ function appRoles(user) { /** * 管理端身份判定:路由中间件、订单 handler、WebSocket 入口共用同一口径。 * - * 为什么不再用「app 里存在 wxapp-escort-admin 键」: + * 为什么不再用「app 里存在 wxapp_companion 键」: * 该键历史上可由 /user/register 的客户端入参写入,任何人都能据此自封管理员。 * 现在注册侧已拒绝客户端写 app,但库里可能残留历史账号, * 因此要求显式 role === 'admin';role 缺失的历史账号暂按管理员放行并打告警, - * 待库中补齐 app.wxapp-escort-admin.role = ['admin'] 后再收紧(见 doc/api-review-plan.md B1)。 + * 待库中补齐 app.wxapp_companion.role = ['admin'] 后再收紧(见 doc/api-review-plan.md B1)。 * * 用户模型重构后(doc/user-multi-app-plan.md),userInfo 响应会带只读数组 apps, * 此时优先按成员关系判定,status=disabled 的成员不再视为管理员。