Files
api_health/test/attendant_application.test.js
T
lik 67f2962574 feat(attendant): 入驻默认实习阶段并新增阶段等级调整接口
- employee.attendantInfo 增加 stage/grade/star,存量档案按正式青铜归一化

- 入驻审批仅在新建档案时写 intern,重新激活保留原阶段

- /employee/me 返回阶段等级与 canAcceptOrder

- C 端公示列表与详情排除实习陪诊师

- 新增 PATCH /employee/:id/level:转正、调级、钻石设星
2026-11-10 12:02:07 +08:00

471 lines
16 KiB
JavaScript
Raw 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.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 () => {
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, /已绑定陪诊师/);
});
});
});