Files
api_health/test/attendant_application.test.js
lik cd3b109730 feat(attendant): 入驻免身份证材料、城市单选、材料后补与订单池同城过滤
入驻申请只收基本信息(身份证选填、材料全可空),服务城市改为单选白名单(北京/上海/天津/西安,默认北京);新增 POST /attendant-application/mine/materials 材料后补与 PATCH /employee/me/service-area 改城市接口;订单池按陪诊师服务城市过滤(本人已接/被共享不限城市),接单与详情二次校验;appId wxapp-escort-admin 更名为 wxapp_companion。
2026-11-10 16:33:47 +08:00

634 lines
21 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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.data, previous.materials.healthCertificate.data);
assert.equal(result.value.materials.healthCertificate.expireDate, undefined);
});
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_companion", 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 () => {
let capturedUpdate = null;
const stub = {
findOne: () => ({
select: () => ({ lean: () => ({ exec: async () => ({ role: "attendant" }) }) }),
}),
findOneAndUpdate: (filter, update) => {
capturedUpdate = update;
return { exec: async () => ({ _id: OWNER_ID }) };
},
};
await withModel("Employee", stub, async () => {
await HandlerAttendantApplication.ensureEmployee({
userId: OWNER_ID,
applicant: { name: "张三" },
materials: {},
});
// 只在插入时给实习身份;$set 不能带 stage,否则重新审批会把已转正的人降回实习
assert.equal(capturedUpdate.$setOnInsert["attendantInfo.stage"], "intern");
assert.equal(capturedUpdate.$set["attendantInfo.stage"], undefined);
});
});
test("公示口径排除实习陪诊师,存量无阶段字段仍视为正式", () => {
const filter = HandlerEmployee.publicAttendantFilter();
assert.equal(filter.role, "attendant");
assert.equal(filter.status, "active");
// $ne 对缺失字段同样成立,历史档案不会被误排除
assert.deepEqual(filter["attendantInfo.stage"], { $ne: "intern" });
});
test("/employee/me 对存量档案按正式陪诊师归一化并允许接单", async () => {
const stub = {
findOne: () => ({
select: () => ({
lean: () => ({ exec: async () => ({ _id: OWNER_ID, role: "attendant", status: "active" }) }),
}),
}),
};
await withModel("Employee", stub, async () => {
const ctx = createCtx({ user: { _id: OWNER_ID } });
await new HandlerEmployee().getMyEmployee(ctx);
assert.equal(ctx.body.code, 0);
assert.equal(ctx.body.data.employee.attendantInfo.stage, "certified");
assert.equal(ctx.body.data.employee.attendantInfo.grade, "bronze");
assert.equal(ctx.body.data.employee.canAcceptOrder, true);
});
});
test("/employee/me 实习陪诊师不可接单,非钻石等级星级归零", async () => {
const stub = {
findOne: () => ({
select: () => ({
lean: () => ({
exec: async () => ({
_id: OWNER_ID,
role: "attendant",
status: "active",
attendantInfo: { stage: "intern", grade: "silver", star: 3 },
}),
}),
}),
}),
};
await withModel("Employee", stub, async () => {
const ctx = createCtx({ user: { _id: OWNER_ID } });
await new HandlerEmployee().getMyEmployee(ctx);
assert.equal(ctx.body.code, 0);
assert.equal(ctx.body.data.employee.attendantInfo.stage, "intern");
assert.equal(ctx.body.data.employee.attendantInfo.star, 0);
assert.equal(ctx.body.data.employee.canAcceptOrder, false);
});
});
/** Employee.findById 链式 stub + updateEmployee 记录 */
function levelStub(employee) {
const calls = { update: null };
return {
calls,
findById: () => ({
select: () => ({ lean: () => ({ exec: async () => employee }) }),
}),
updateEmployee: async (id, flat) => {
calls.update = flat;
return { _id: id };
},
};
}
test("管理员可把实习陪诊师转正并调级", async () => {
const stub = levelStub({ role: "attendant", attendantInfo: { stage: "intern", grade: "bronze" } });
await withModel("Employee", stub, async () => {
const ctx = createCtx({
params: { id: OWNER_ID },
body: { stage: "certified", grade: "silver" },
});
await new HandlerEmployee().updateEmployeeLevel(ctx);
assert.equal(ctx.body.code, 0);
assert.deepEqual(stub.calls.update, {
"attendantInfo.stage": "certified",
"attendantInfo.grade": "silver",
});
});
});
test("非钻石等级不能设置星级", async () => {
const stub = levelStub({ role: "attendant", attendantInfo: { grade: "gold" } });
await withModel("Employee", stub, async () => {
const ctx = createCtx({ params: { id: OWNER_ID }, body: { star: 3 } });
await new HandlerEmployee().updateEmployeeLevel(ctx);
assert.equal(ctx.body.code, 400);
assert.equal(stub.calls.update, null);
});
});
test("离开钻石等级时星级自动归零", async () => {
const stub = levelStub({ role: "attendant", attendantInfo: { grade: "diamond", star: 4 } });
await withModel("Employee", stub, async () => {
const ctx = createCtx({ params: { id: OWNER_ID }, body: { grade: "gold" } });
await new HandlerEmployee().updateEmployeeLevel(ctx);
assert.equal(ctx.body.code, 0);
assert.equal(stub.calls.update["attendantInfo.star"], 0);
});
});
test("非陪诊师岗位不能设置阶段与等级", async () => {
const stub = levelStub({ role: "nurse" });
await withModel("Employee", stub, async () => {
const ctx = createCtx({ params: { id: OWNER_ID }, body: { grade: "gold" } });
await new HandlerEmployee().updateEmployeeLevel(ctx);
assert.equal(ctx.body.code, 400);
assert.equal(stub.calls.update, null);
});
});
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, /已绑定陪诊师/);
});
});
});
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, /仅在职陪诊师/);
});
});