feat: 订单获取链路收尾:管理端指派、接单开关与用户指定陪诊师

This commit is contained in:
lik
2026-11-10 15:13:48 +08:00
parent 78138a417b
commit b160102f12
8 changed files with 725 additions and 32 deletions
+275
View File
@@ -0,0 +1,275 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { DBModel } from "../models/index.js";
import { HandlerEscortRecord } from "../handler/escort_record.js";
import { HandlerEmployee } from "../handler/employee.js";
const RECORD_ID = "64b000000000000000000010";
const OWNER_ID = "64b000000000000000000001";
const ADMIN_ID = "64b000000000000000000009";
const EMPLOYEE_ID = "64b000000000000000000033";
const EMPLOYEE_USER_ID = "64b000000000000000000003";
const INTERN_EMPLOYEE_ID = "64b000000000000000000022";
function buildRecord(overrides = {}) {
return {
_id: RECORD_ID,
userId: OWNER_ID,
status: "pending",
cancelStatus: "none",
patient: { name: "张三", mobile: "13800138000" },
escort: { serviceId: 1, serviceName: "全天陪诊" },
hospital: { name: "北京协和医院", address: "北京市东城区" },
schedule: { date: new Date("2026-12-01T00:00:00.000Z"), startTime: "08:00", endTime: "17:00" },
payment: { totalFee: 500, paidFee: 0, status: "unpaid" },
attendant: { id: null, name: "", sharedWith: [] },
...overrides,
};
}
function buildEmployee(overrides = {}) {
return {
_id: EMPLOYEE_ID,
userId: EMPLOYEE_USER_ID,
role: "attendant",
status: "active",
profile: { name: "李四", sex: "male", phone: "13700137000" },
attendantInfo: { stage: "certified", grade: "bronze", isOnline: false, orderCount: 3 },
...overrides,
};
}
function createCtx({ body = {}, user = { _id: ADMIN_ID }, params = { id: RECORD_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;
});
}
function employeeFindOneStub(employee, overrides = {}) {
const query = { lean: () => ({ exec: async () => employee }) };
return {
findOne: () => ({
...query,
select: () => query,
}),
incrementOrderCount: async () => {},
...overrides,
};
}
async function runAssign({ employee = buildEmployee(), record = buildRecord(), updated } = {}) {
const calls = { accepted: null, bumped: null };
const employeeStub = employeeFindOneStub(employee, {
incrementOrderCount: async (id) => {
calls.bumped = id;
},
});
const recordStub = {
findById: async () => record,
acceptRecord: async (id, attendant) => {
calls.accepted = attendant;
return updated === undefined
? { ...record, attendant: { id: attendant.id, name: attendant.name, sharedWith: [] } }
: updated;
},
};
const ctx = createCtx({ body: { employeeId: EMPLOYEE_ID } });
await withModel("Employee", employeeStub, () =>
withModel("EscortRecord", recordStub, () => new HandlerEscortRecord().assignRecord(ctx))
);
return { ctx, calls };
}
test("管理员指派成功:写入陪诊师快照并累加接单数", async () => {
const { ctx, calls } = await runAssign();
assert.equal(ctx.body.code, 0);
assert.equal(calls.accepted.id, EMPLOYEE_USER_ID);
assert.equal(calls.accepted.name, "李四");
assert.equal(calls.accepted.sex, "male");
assert.equal(calls.accepted.mobile, "13700137000");
assert.equal(calls.bumped, EMPLOYEE_ID);
});
test("指派参数校验:非法记录 ID 或陪诊师 ID 返回 400", async () => {
const badRecordCtx = createCtx({ body: { employeeId: EMPLOYEE_ID }, params: { id: "bad-id" } });
await new HandlerEscortRecord().assignRecord(badRecordCtx);
assert.equal(badRecordCtx.body.code, 400);
const badEmployeeCtx = createCtx({ body: { employeeId: "bad-id" } });
await new HandlerEscortRecord().assignRecord(badEmployeeCtx);
assert.equal(badEmployeeCtx.body.code, 400);
});
test("订单已分配时指派返回 409,不重复写库也不累加", async () => {
const { ctx, calls } = await runAssign({
record: buildRecord({ attendant: { id: OWNER_ID, name: "张三", sharedWith: [] } }),
});
assert.equal(ctx.body.code, 409);
assert.equal(calls.accepted, null);
assert.equal(calls.bumped, null);
});
test("并发下订单已被接走:条件更新失败返回 409 且不累加", async () => {
const { ctx, calls } = await runAssign({ updated: null });
assert.equal(ctx.body.code, 409);
assert.notEqual(calls.accepted, null);
assert.equal(calls.bumped, null);
});
test("实习陪诊师不能被指派", async () => {
const { ctx, calls } = await runAssign({
employee: buildEmployee({
_id: INTERN_EMPLOYEE_ID,
attendantInfo: { stage: "intern", grade: "bronze" },
}),
});
assert.equal(ctx.body.code, 400);
assert.equal(calls.accepted, null);
assert.equal(calls.bumped, null);
});
test("非在职陪诊师不能被指派", async () => {
const { ctx, calls } = await runAssign({ employee: null });
assert.equal(ctx.body.code, 400);
assert.equal(calls.accepted, null);
});
test("未绑定登录账号的陪诊师不能被指派", async () => {
const { ctx, calls } = await runAssign({
employee: buildEmployee({ userId: null }),
});
assert.equal(ctx.body.code, 400);
assert.equal(calls.accepted, null);
});
test("取消中或已取消订单不能指派", async () => {
const { ctx: requestedCtx } = await runAssign({
record: buildRecord({ cancelStatus: "requested" }),
});
assert.equal(requestedCtx.body.code, 409);
const { ctx: cancelledCtx } = await runAssign({
record: buildRecord({ status: "cancelled" }),
});
assert.equal(cancelledCtx.body.code, 409);
});
test("接单开关:正式陪诊师切换后落库并返回最新状态", async () => {
let saved = null;
const employee = buildEmployee();
const stub = {
findOne: () => ({
select: () => ({
lean: () => ({ exec: async () => ({ attendantInfo: employee.attendantInfo }) }),
}),
}),
setOnlineByUserId: async (userId, isOnline) => {
saved = { userId, isOnline };
return { ...employee, attendantInfo: { ...employee.attendantInfo, isOnline } };
},
};
const ctx = createCtx({ body: { isOnline: true } });
await withModel("Employee", stub, () => new HandlerEmployee().updateMyOnlineStatus(ctx));
assert.equal(ctx.body.code, 0);
assert.deepEqual(saved, { userId: ADMIN_ID, isOnline: true });
assert.equal(ctx.body.data.employee.attendantInfo.isOnline, true);
assert.equal(ctx.body.data.employee.canAcceptOrder, true);
});
test("接单开关:实习陪诊师返回 403 且不写库", async () => {
let called = false;
const stub = {
findOne: () => ({
select: () => ({
lean: () => ({ exec: async () => ({ attendantInfo: { stage: "intern" } }) }),
}),
}),
setOnlineByUserId: async () => {
called = true;
return null;
},
};
const ctx = createCtx({ body: { isOnline: true } });
await withModel("Employee", stub, () => new HandlerEmployee().updateMyOnlineStatus(ctx));
assert.equal(ctx.body.code, 403);
assert.equal(called, false);
});
test("接单开关:非陪诊师账号返回 403,参数非布尔返回 400", async () => {
const noEmployeeStub = {
findOne: () => ({
select: () => ({
lean: () => ({ exec: async () => null }),
}),
}),
};
const forbiddenCtx = createCtx({ body: { isOnline: true } });
await withModel("Employee", noEmployeeStub, () =>
new HandlerEmployee().updateMyOnlineStatus(forbiddenCtx)
);
assert.equal(forbiddenCtx.body.code, 403);
const badRequestCtx = createCtx({ body: { isOnline: "yes" } });
await new HandlerEmployee().updateMyOnlineStatus(badRequestCtx);
assert.equal(badRequestCtx.body.code, 400);
});
test("公示列表输出累计接单并按服务年限、接单数排序", async () => {
let capturedSort = null;
const employee = {
_id: EMPLOYEE_ID,
profile: { name: "李四" },
work: { workYears: 5 },
attendantInfo: { orderCount: 12, specialties: ["陪诊"] },
};
const stub = {
find: () => ({
sort: (sort) => {
capturedSort = sort;
return {
skip: () => ({
limit: () => ({ exec: async () => [employee] }),
}),
};
},
}),
};
const ctx = createCtx({ user: null });
await withModel("Employee", stub, () => new HandlerEmployee().getAttendants(ctx));
assert.equal(ctx.body.code, 0);
assert.equal(ctx.body.data.attendants[0].orderCount, 12);
assert.deepEqual(capturedSort, {
"work.workYears": -1,
"attendantInfo.orderCount": -1,
});
});
+23 -12
View File
@@ -61,13 +61,15 @@ function createCtx({ body = {}, query = {}, user, params = { id: RECORD_ID } } =
};
}
function employeeFindOneStub(employee) {
function employeeFindOneStub(employee, overrides = {}) {
return {
findOne: () => ({
select: () => ({
lean: () => ({ exec: async () => employee }),
}),
}),
incrementOrderCount: async () => {},
...overrides,
};
}
@@ -186,6 +188,7 @@ test("实习陪诊师不能接单", async () => {
test("正式陪诊师接单写入陪诊师快照,不校验支付状态", async () => {
let payload = null;
let bumped = null;
const record = buildRecord();
const recordStub = {
findById: async () => record,
@@ -198,18 +201,26 @@ test("正式陪诊师接单写入陪诊师快照,不校验支付状态", async
},
};
await withModel("Employee", employeeFindOneStub(buildEmployee()), () =>
withModel("EscortRecord", recordStub, async () => {
const ctx = createCtx({ user: { _id: CERT_USER_ID } });
await new HandlerEscortRecord().acceptRecord(ctx);
await withModel(
"Employee",
employeeFindOneStub(buildEmployee(), {
incrementOrderCount: async (employeeId) => {
bumped = employeeId;
},
}),
() =>
withModel("EscortRecord", recordStub, async () => {
const ctx = createCtx({ user: { _id: CERT_USER_ID } });
await new HandlerEscortRecord().acceptRecord(ctx);
assert.equal(ctx.body.code, 0);
assert.equal(payload.id, CERT_USER_ID);
assert.equal(payload.name, "李四");
assert.equal(payload.sex, "male");
assert.equal(payload.mobile, "13700137000");
assert.equal(ctx.body.data.record.attendantAssignedToMe, true);
})
assert.equal(ctx.body.code, 0);
assert.equal(payload.id, CERT_USER_ID);
assert.equal(payload.name, "李四");
assert.equal(payload.sex, "male");
assert.equal(payload.mobile, "13700137000");
assert.equal(ctx.body.data.record.attendantAssignedToMe, true);
assert.equal(bumped, CERT_EMPLOYEE_ID);
})
);
});
+167
View File
@@ -0,0 +1,167 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { DBModel } from "../models/index.js";
import { HandlerEscortRecord } from "../handler/escort_record.js";
const USER_ID = "64b000000000000000000101";
const PROFILE_ID = "64b000000000000000000102";
const EMPLOYEE_ID = "64b000000000000000000103";
const EMPLOYEE_USER_ID = "64b000000000000000000104";
const RECORD_ID = "64b000000000000000000105";
function futureDate(days) {
const date = new Date();
date.setDate(date.getDate() + days);
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(
date.getDate()
).padStart(2, "0")}`;
}
function buildProfile() {
return {
_id: PROFILE_ID,
userId: USER_ID,
profile: { name: "张三", mobile: "13800138000", sex: "male", birth: "1990-01-01" },
};
}
function buildEmployee(overrides = {}) {
return {
_id: EMPLOYEE_ID,
userId: EMPLOYEE_USER_ID,
role: "attendant",
status: "active",
profile: { name: "李四", sex: "female", phone: "13700137000" },
attendantInfo: { stage: "certified", grade: "silver" },
...overrides,
};
}
function buildBody(attendant) {
return {
healthProfileId: PROFILE_ID,
escort: { serviceId: 1, sexRequirement: "none" },
hospital: { province: "北京市", name: "北京协和医院" },
schedule: { date: futureDate(3), startTime: "08:00" },
payment: { payChannel: "offline" },
...(attendant ? { attendant } : {}),
};
}
function createCtx(body) {
return {
request: { query: {}, body },
params: {},
state: { user: { _id: USER_ID } },
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;
});
}
function employeeFindOneStub(employee, overrides = {}) {
const query = { lean: () => ({ exec: async () => employee }) };
return {
findOne: () => ({
...query,
select: () => query,
}),
incrementOrderCount: async () => {},
...overrides,
};
}
async function runCreate({ attendant, employee = buildEmployee() } = {}) {
const calls = { payload: null, bumped: null };
const recordStub = {
findByIdempotencyKey: async () => null,
countDocuments: async () => 0,
createRecord: async (payload) => {
calls.payload = payload;
return { _id: RECORD_ID, ...payload };
},
};
const employeeStub = employeeFindOneStub(employee, {
incrementOrderCount: async (id) => {
calls.bumped = id;
},
});
const ctx = createCtx(buildBody(attendant));
await withModel("HealthProfile", { findProfileById: async () => buildProfile() }, () =>
withModel("EscortRecord", recordStub, () =>
withModel("Employee", employeeStub, () => new HandlerEscortRecord().createRecord(ctx))
)
);
return { ctx, calls };
}
test("用户下单指定陪诊师:服务端回填快照并累加接单数", async () => {
const { ctx, calls } = await runCreate({
// 客户端伪造的姓名 / 电话必须被服务端档案覆盖
attendant: { employeeId: EMPLOYEE_ID, name: "伪造姓名", mobile: "10000000000" },
});
assert.equal(ctx.body.code, 0);
assert.deepEqual(calls.payload.attendant, {
id: EMPLOYEE_USER_ID,
name: "李四",
sex: "female",
mobile: "13700137000",
sharedWith: [],
});
assert.equal(calls.bumped, EMPLOYEE_ID);
});
test("用户不指定陪诊师:订单进入公共池,不写陪诊师、不累加接单数", async () => {
const { ctx, calls } = await runCreate({ attendant: null });
assert.equal(ctx.body.code, 0);
assert.equal(calls.payload.attendant, undefined);
assert.equal(calls.bumped, null);
});
test("指定实习陪诊师或不在职陪诊师返回 400 且不创建订单", async () => {
const intern = await runCreate({
attendant: { employeeId: EMPLOYEE_ID },
employee: buildEmployee({ attendantInfo: { stage: "intern" } }),
});
assert.equal(intern.ctx.body.code, 400);
assert.equal(intern.calls.payload, null);
const inactive = await runCreate({
attendant: { employeeId: EMPLOYEE_ID },
employee: null,
});
assert.equal(inactive.ctx.body.code, 400);
assert.equal(inactive.calls.payload, null);
});
test("指定未绑定登录账号的陪诊师返回 400", async () => {
const { ctx, calls } = await runCreate({
attendant: { employeeId: EMPLOYEE_ID },
employee: buildEmployee({ userId: null }),
});
assert.equal(ctx.body.code, 400);
assert.equal(calls.payload, null);
});
test("陪诊师 ID 不合法返回 400", async () => {
const { ctx, calls } = await runCreate({ attendant: { employeeId: "bad-id" } });
assert.equal(ctx.body.code, 400);
assert.equal(calls.payload, null);
});