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, /已绑定陪诊师/); }); }); });