feat: 订单获取链路收尾:管理端指派、接单开关与用户指定陪诊师
This commit is contained in:
+62
-11
@@ -1,5 +1,6 @@
|
||||
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";
|
||||
|
||||
/**
|
||||
@@ -123,8 +124,8 @@ class HandlerEmployee {
|
||||
specialties: info.specialties || [],
|
||||
serviceAreas: info.serviceAreas || [],
|
||||
languages: info.languages || [],
|
||||
// 注:GB/T 4.2.1.5 要求公示的「累计服务次数」暂缺——orderCount 全项目无写入点(恒 0),
|
||||
// 展示恒 0 反而误导,已从公示输出摘除;待 plan.md B8 补写入点后恢复
|
||||
// 累计接单数由陪诊师接单 / 管理员指派成功时回写,可用于公示排序
|
||||
orderCount: info.orderCount || 0,
|
||||
introduction: employee.introduction || "",
|
||||
};
|
||||
}
|
||||
@@ -140,9 +141,9 @@ class HandlerEmployee {
|
||||
const pageSize = Math.min(Math.max(1, rawSize), HandlerEmployee.MAX_PAGE_SIZE);
|
||||
|
||||
// 只取在职且已转正的陪诊员,实习不对外公示。
|
||||
// 排序不按 attendantInfo.rating / orderCount(均无可信来源),暂只按服务年限
|
||||
// 排序:服务年限优先,累计接单数次之;rating 无写入点,不参与排序
|
||||
const list = await DBModel.Employee.find(HandlerEmployee.publicAttendantFilter())
|
||||
.sort({ "work.workYears": -1 })
|
||||
.sort({ "work.workYears": -1, "attendantInfo.orderCount": -1 })
|
||||
.skip((page - 1) * pageSize)
|
||||
.limit(pageSize)
|
||||
.exec();
|
||||
@@ -247,6 +248,15 @@ class HandlerEmployee {
|
||||
}
|
||||
}
|
||||
|
||||
// 阶段/等级归一化后随档案返回,小程序据此展示身份文案与只读提示。
|
||||
// canAcceptOrder 只由 stage 决定,等级不参与鉴权
|
||||
static decorateMyEmployee(employee) {
|
||||
const level = HandlerEmployee.normalizeAttendantLevel(employee.attendantInfo);
|
||||
employee.attendantInfo = { ...(employee.attendantInfo || {}), ...level };
|
||||
employee.canAcceptOrder = level.stage === "certified";
|
||||
return employee;
|
||||
}
|
||||
|
||||
// 当前登录账号的员工档案:登录即可访问,供管理端判定陪诊员身份。
|
||||
// 只返回员工档案本身,不重复做管理员判定(管理员身份由管理端按登录响应的 apps 判定)
|
||||
async getMyEmployee(ctx) {
|
||||
@@ -257,7 +267,7 @@ class HandlerEmployee {
|
||||
}
|
||||
|
||||
const employee = await DBModel.Employee.findOne({ userId })
|
||||
.select("employeeNo role status profile.name profile.sex profile.phone profile.avatar attendantInfo")
|
||||
.select(MY_EMPLOYEE_SELECT)
|
||||
.lean()
|
||||
.exec();
|
||||
|
||||
@@ -266,13 +276,54 @@ class HandlerEmployee {
|
||||
return ResponseUtil.success(ctx, { employee: null }, "查询成功");
|
||||
}
|
||||
|
||||
// 阶段/等级归一化后随档案返回,小程序据此展示身份文案与只读提示。
|
||||
// canAcceptOrder 只由 stage 决定,等级不参与鉴权
|
||||
const level = HandlerEmployee.normalizeAttendantLevel(employee.attendantInfo);
|
||||
employee.attendantInfo = { ...(employee.attendantInfo || {}), ...level };
|
||||
employee.canAcceptOrder = level.stage === "certified";
|
||||
return ResponseUtil.success(
|
||||
ctx,
|
||||
{ employee: HandlerEmployee.decorateMyEmployee(employee) },
|
||||
"查询成功"
|
||||
);
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
}
|
||||
|
||||
return ResponseUtil.success(ctx, { employee }, "查询成功");
|
||||
// 首页接单开关落库:只允许在职且已转正的陪诊师切换
|
||||
async updateMyOnlineStatus(ctx) {
|
||||
try {
|
||||
const userId = ctx.state.user?._id;
|
||||
if (!userId) {
|
||||
return ResponseUtil.unauthorized(ctx, "登录已失效");
|
||||
}
|
||||
|
||||
const isOnline = ctx.request.body?.isOnline;
|
||||
if (typeof isOnline !== "boolean") {
|
||||
return ResponseUtil.badRequest(ctx, "接单状态必须为布尔值");
|
||||
}
|
||||
|
||||
const employee = await DBModel.Employee.findOne({
|
||||
userId,
|
||||
role: "attendant",
|
||||
status: "active",
|
||||
})
|
||||
.select("attendantInfo.stage")
|
||||
.lean()
|
||||
.exec();
|
||||
if (!employee) {
|
||||
return ResponseUtil.forbidden(ctx, "仅在职陪诊师可切换接单状态");
|
||||
}
|
||||
if (HandlerEmployee.normalizeAttendantLevel(employee.attendantInfo).stage === "intern") {
|
||||
return ResponseUtil.forbidden(ctx, "实习陪诊师暂不能接单");
|
||||
}
|
||||
|
||||
const updated = await DBModel.Employee.setOnlineByUserId(userId, isOnline);
|
||||
if (!updated) {
|
||||
return ResponseUtil.forbidden(ctx, "仅在职陪诊师可切换接单状态");
|
||||
}
|
||||
|
||||
return ResponseUtil.success(
|
||||
ctx,
|
||||
{ employee: HandlerEmployee.decorateMyEmployee(updated) },
|
||||
isOnline ? "已开启接单" : "已暂停接单"
|
||||
);
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
|
||||
+148
-2
@@ -1,3 +1,4 @@
|
||||
import mongoose from "mongoose";
|
||||
import { DBModel } from "../models/index.js";
|
||||
import services from "../resource/services.js";
|
||||
import ResponseUtil from "../utils/responseUtil.js";
|
||||
@@ -150,6 +151,64 @@ class HandlerEscortRecord {
|
||||
return employee?.attendantInfo?.stage === "intern" ? "intern" : "certified";
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析用户下单时选择的陪诊师。
|
||||
*
|
||||
* 客户端只允许传 employeeId;姓名、电话等快照字段一律以服务端档案为准,
|
||||
* 防止用户伪造陪诊师信息。未选择时返回 { employee: null },订单进入公共订单池。
|
||||
* @param {Object} input 客户端提交的 attendant
|
||||
* @returns {Promise<{ employee?: Object, snapshot?: Object, error?: string }>}
|
||||
*/
|
||||
static async resolveSelectedAttendant(input) {
|
||||
const employeeId = input?.employeeId;
|
||||
if (!employeeId) return { employee: null };
|
||||
|
||||
if (!mongoose.Types.ObjectId.isValid(employeeId)) {
|
||||
return { error: "所选陪诊师ID不合法" };
|
||||
}
|
||||
|
||||
const employee = await DBModel.Employee.findOne({
|
||||
_id: employeeId,
|
||||
role: "attendant",
|
||||
status: "active",
|
||||
}).lean().exec();
|
||||
if (!employee) return { error: "所选陪诊师不存在或已不在职" };
|
||||
// 与用户选择、管理端指派的口径一致:实习陪诊师不可被指定
|
||||
if (HandlerEscortRecord.attendantStage(employee) === "intern") {
|
||||
return { error: "实习陪诊师暂不能被指定" };
|
||||
}
|
||||
if (!employee.userId) {
|
||||
return { error: "所选陪诊师暂不可接单,请选择其他陪诊师" };
|
||||
}
|
||||
|
||||
const profile = employee.profile || {};
|
||||
return {
|
||||
employee,
|
||||
snapshot: {
|
||||
id: employee.userId,
|
||||
name: profile.name || "",
|
||||
sex: ["male", "female"].includes(profile.sex) ? profile.sex : "none",
|
||||
mobile: profile.phone || "",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 回写陪诊师累计接单数。
|
||||
*
|
||||
* 只在订单成功归属到陪诊师之后调用;写失败不回滚已完成的接单,
|
||||
* 只记日志,避免陪诊师明明接到了单却被接口报成失败。
|
||||
* @param {ObjectId} employeeId 员工档案ID(不是登录 userId)
|
||||
*/
|
||||
static async bumpAttendantOrderCount(employeeId) {
|
||||
if (!employeeId) return;
|
||||
try {
|
||||
await DBModel.Employee.incrementOrderCount(employeeId);
|
||||
} catch (err) {
|
||||
logger.error(`[escort] 回写陪诊师接单数失败 employeeId=${employeeId}: ${err?.message || err}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 陪诊师能否查看订单详情:未分配订单、本人已接订单、被共享的订单
|
||||
* 实习陪诊师同样可以看到未分配订单,但接单会被 acceptRecord 拦截
|
||||
@@ -578,6 +637,8 @@ class HandlerEscortRecord {
|
||||
return ResponseUtil.error(ctx, "订单已被其他陪诊师接单", null, 409);
|
||||
}
|
||||
|
||||
await HandlerEscortRecord.bumpAttendantOrderCount(employee._id);
|
||||
|
||||
const plain = HandlerEscortRecord.withPaymentWindow(updated);
|
||||
HandlerEscortRecord.decorateAttendantRecord(plain, employee);
|
||||
return ResponseUtil.success(ctx, { record: plain }, "接单成功");
|
||||
@@ -586,6 +647,76 @@ class HandlerEscortRecord {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 管理员指派:把未分配订单指派给在职正式陪诊师。
|
||||
* 与陪诊师抢单共用条件更新,保证并发下只有一次归属成功。
|
||||
*/
|
||||
async assignRecord(ctx) {
|
||||
try {
|
||||
const { id } = ctx.params;
|
||||
if (!id) return ResponseUtil.badRequest(ctx, "缺少记录ID");
|
||||
if (!mongoose.Types.ObjectId.isValid(id)) {
|
||||
return ResponseUtil.badRequest(ctx, "记录ID不合法");
|
||||
}
|
||||
|
||||
const employeeId = String(ctx.request.body?.employeeId || "");
|
||||
if (!mongoose.Types.ObjectId.isValid(employeeId)) {
|
||||
return ResponseUtil.badRequest(ctx, "请选择陪诊师");
|
||||
}
|
||||
|
||||
const employee = await DBModel.Employee.findOne({
|
||||
_id: employeeId,
|
||||
role: "attendant",
|
||||
status: "active",
|
||||
}).lean().exec();
|
||||
if (!employee) {
|
||||
return ResponseUtil.badRequest(ctx, "陪诊师不存在或已不在职");
|
||||
}
|
||||
// 实习陪诊师不可被指派,与用户选择、系统派单的口径一致
|
||||
if (HandlerEscortRecord.attendantStage(employee) === "intern") {
|
||||
return ResponseUtil.badRequest(ctx, "实习陪诊师暂不能被指派");
|
||||
}
|
||||
// 指派写入的是登录 userId,未绑定账号的档案指派后无法在小程序看到订单
|
||||
if (!employee.userId) {
|
||||
return ResponseUtil.badRequest(ctx, "该陪诊师未绑定登录账号,无法指派");
|
||||
}
|
||||
|
||||
const record = await DBModel.EscortRecord.findById(id);
|
||||
if (!record || record.deletedAt) return ResponseUtil.notFound(ctx, "陪诊记录不存在");
|
||||
if (record.cancelStatus === "cancelled" || record.status === "cancelled") {
|
||||
return ResponseUtil.error(ctx, "订单已取消,无法指派", null, 409);
|
||||
}
|
||||
if (record.cancelStatus === "requested") {
|
||||
return ResponseUtil.error(ctx, "订单取消申请确认中,暂不能指派", null, 409);
|
||||
}
|
||||
if (record.attendant?.id) {
|
||||
return ResponseUtil.error(ctx, "订单已分配陪诊师", null, 409);
|
||||
}
|
||||
|
||||
const profile = employee.profile || {};
|
||||
const updated = await DBModel.EscortRecord.acceptRecord(id, {
|
||||
id: employee.userId,
|
||||
name: profile.name || "",
|
||||
sex: ["male", "female"].includes(profile.sex) ? profile.sex : "none",
|
||||
mobile: profile.phone || "",
|
||||
});
|
||||
// 并发下已被陪诊师接走或另一管理员先指派
|
||||
if (!updated) {
|
||||
return ResponseUtil.error(ctx, "订单已分配陪诊师", null, 409);
|
||||
}
|
||||
|
||||
await HandlerEscortRecord.bumpAttendantOrderCount(employee._id);
|
||||
|
||||
return ResponseUtil.success(
|
||||
ctx,
|
||||
{ record: HandlerEscortRecord.withPaymentWindow(updated) },
|
||||
"指派成功"
|
||||
);
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 共享订单:仅接单陪诊师本人可操作,共享对象为所有在职陪诊师(含实习)
|
||||
*/
|
||||
@@ -721,8 +852,19 @@ class HandlerEscortRecord {
|
||||
const addressResult = HandlerEscortRecord.buildShippingAddress(body.shippingAddress, profile);
|
||||
|
||||
const payload = HandlerEscortRecord.pickFields(body);
|
||||
// 陪诊员分配由平台决定:用户下单时提交的 attendant 一律丢弃,防止自选/伪造陪诊员
|
||||
if (!isAdmin) delete payload.attendant;
|
||||
// 用户可在下单时指定陪诊师:只认 employeeId,快照字段由服务端回填。
|
||||
// 未指定则清空,订单进入公共订单池等待抢单或管理端指派。
|
||||
let selectedEmployee = null;
|
||||
if (!isAdmin) {
|
||||
const selected = await HandlerEscortRecord.resolveSelectedAttendant(body.attendant);
|
||||
if (selected.error) return ResponseUtil.badRequest(ctx, selected.error);
|
||||
if (selected.employee) {
|
||||
selectedEmployee = selected.employee;
|
||||
payload.attendant = { ...selected.snapshot, sharedWith: [] };
|
||||
} else {
|
||||
delete payload.attendant;
|
||||
}
|
||||
}
|
||||
// 归属以档案为准:管理员传入的 userId 一律忽略,无归属档案留空
|
||||
payload.userId = orderUserId;
|
||||
// healthProfileId 以校验通过的档案为准,覆盖客户端原值
|
||||
@@ -781,6 +923,10 @@ class HandlerEscortRecord {
|
||||
|
||||
try {
|
||||
const newRecord = await DBModel.EscortRecord.createRecord(payload);
|
||||
// 用户指定陪诊师即视为接单成功,累计接单数按同一口径回写
|
||||
if (selectedEmployee) {
|
||||
await HandlerEscortRecord.bumpAttendantOrderCount(selectedEmployee._id);
|
||||
}
|
||||
return ResponseUtil.success(ctx, { record: newRecord }, "创建成功");
|
||||
} catch (err) {
|
||||
// 并发重复提交由唯一索引兜底,后到的请求返回已创建订单。
|
||||
|
||||
@@ -3,6 +3,10 @@
|
||||
import mongoose from "mongoose";
|
||||
import { pinyin } from "pinyin-pro";
|
||||
|
||||
// /employee/me 与接单开关返回的公共字段
|
||||
const MY_EMPLOYEE_SELECT =
|
||||
"employeeNo role status profile.name profile.sex profile.phone profile.avatar attendantInfo";
|
||||
|
||||
/**
|
||||
* 培训记录子文档
|
||||
*
|
||||
@@ -122,7 +126,8 @@ const EmployeeSchema = mongoose.Schema(
|
||||
// 对外评级一律由 employee_review 真实评价聚合得出(employee_review.js),
|
||||
// 达阈值才展示,详见 doc/architecture-overview.html 第 10 节「陪诊师成长与资金闭环」
|
||||
rating: { type: Number, default: 5.0, min: 1, max: 5, comment: "评分(无写入点,勿用于公示)" },
|
||||
orderCount: { type: Number, default: 0, comment: "接单数量(无写入点恒 0,公示/后台展示已摘除,勿用于排序)" },
|
||||
// 累计接单数:陪诊师接单 / 管理员指派成功时 +1;取消不扣减
|
||||
orderCount: { type: Number, default: 0, comment: "累计接单数量" },
|
||||
isOnline: { type: Boolean, default: false, comment: "是否在线" },
|
||||
},
|
||||
|
||||
@@ -256,8 +261,8 @@ EmployeeSchema.statics.updateEmployee = async function (id, update) {
|
||||
/**
|
||||
* 查询在线陪诊员列表
|
||||
*
|
||||
* 排序口径与 handler/employee.js 的公示列表保持一致:只按服务年限。
|
||||
* 曾按 attendantInfo.rating / orderCount 排,但两者均无写入点,等于没排序
|
||||
* 排序口径与 handler/employee.js 的公示列表保持一致:服务年限优先,累计接单数次之。
|
||||
* rating 仍无写入点,不参与排序。
|
||||
*/
|
||||
EmployeeSchema.statics.findOnlineAttendants = async function (options = {}) {
|
||||
const { page = 1, pageSize = 20 } = options;
|
||||
@@ -267,12 +272,46 @@ EmployeeSchema.statics.findOnlineAttendants = async function (options = {}) {
|
||||
status: "active",
|
||||
"attendantInfo.isOnline": true,
|
||||
})
|
||||
.sort({ "work.workYears": -1 })
|
||||
.sort({ "work.workYears": -1, "attendantInfo.orderCount": -1 })
|
||||
.skip(skip)
|
||||
.limit(pageSize)
|
||||
.exec();
|
||||
};
|
||||
|
||||
/**
|
||||
* 累计接单数原子加一(接单 / 管理员指派成功后调用)
|
||||
*/
|
||||
EmployeeSchema.statics.incrementOrderCount = async function (employeeId) {
|
||||
if (!employeeId) return null;
|
||||
return await this.updateOne(
|
||||
{ _id: employeeId },
|
||||
{
|
||||
$inc: { "attendantInfo.orderCount": 1 },
|
||||
$set: { "meta.updatetime": Date.now() },
|
||||
}
|
||||
).exec();
|
||||
};
|
||||
|
||||
/**
|
||||
* 按登录账号更新接单开关(仅在职陪诊师)
|
||||
*/
|
||||
EmployeeSchema.statics.setOnlineByUserId = async function (userId, isOnline) {
|
||||
if (!userId) return null;
|
||||
return await this.findOneAndUpdate(
|
||||
{ userId, role: "attendant", status: "active" },
|
||||
{
|
||||
$set: {
|
||||
"attendantInfo.isOnline": Boolean(isOnline),
|
||||
"meta.updatetime": Date.now(),
|
||||
},
|
||||
},
|
||||
{ new: true }
|
||||
)
|
||||
.select(MY_EMPLOYEE_SELECT)
|
||||
.lean()
|
||||
.exec();
|
||||
};
|
||||
|
||||
// ==================== 索引定义 ====================
|
||||
|
||||
EmployeeSchema.index({ "profile.name": 1 });
|
||||
@@ -291,5 +330,5 @@ EmployeeSchema.index(
|
||||
);
|
||||
|
||||
// genPinyin/genPinyinFL 一并导出:handler 层走 findOneAndUpdate 时绕过了 pre("save"),
|
||||
// 需要自行同步拼音字段
|
||||
export { EmployeeSchema, genPinyin, genPinyinFL };
|
||||
// 需要自行同步拼音字段。MY_EMPLOYEE_SELECT 供 handler 复用,避免字段清单两处漂移
|
||||
export { EmployeeSchema, genPinyin, genPinyinFL, MY_EMPLOYEE_SELECT };
|
||||
|
||||
@@ -10,7 +10,7 @@ import mongoose from "mongoose";
|
||||
* 但表本身按「员工」建,不绑死陪诊师——后期护士 / 医生等角色接评价时直接复用,
|
||||
* 不必再建一张平行的表(这也是它叫 employee_review 而不是 attendant_review 的原因)。
|
||||
*
|
||||
* 设计前提(见 .trae/documents/陪诊师公示与指定陪诊师.md):
|
||||
* 设计前提(见 doc/architecture-overview.html 第 07/10 节):
|
||||
* - 一次服务最多产生一条评价,故 recordId 建唯一索引,从数据层断掉刷分
|
||||
* - 评级不由 employee.attendantInfo.rating 提供——那个字段没有任何写入点
|
||||
* - 只有 status 为 published 的评价计入评分,运营隐藏掉的不参与
|
||||
|
||||
@@ -109,6 +109,8 @@ function registerRoutes(app) {
|
||||
router.get("/escort-record/:id", requireAuth, handlerEscortRecord.getRecordById.bind(handlerEscortRecord));
|
||||
// 陪诊师接单 / 共享:身份与可见范围全部由服务端判定
|
||||
router.post("/escort-record/:id/accept", requireAuth, updateLimit, handlerEscortRecord.acceptRecord.bind(handlerEscortRecord));
|
||||
// 管理端指派:仅未分配订单,目标须在职正式陪诊师,条件更新防并发
|
||||
router.post("/escort-record/:id/assign", requireAuth, requireAdmin, updateLimit, handlerEscortRecord.assignRecord.bind(handlerEscortRecord));
|
||||
router.post("/escort-record/:id/share", requireAuth, updateLimit, handlerEscortRecord.shareRecord.bind(handlerEscortRecord));
|
||||
router.post("/escort-record/:id/unshare", requireAuth, updateLimit, handlerEscortRecord.unshareRecord.bind(handlerEscortRecord));
|
||||
router.post("/escort-record", requireAuth, createLimit, handlerEscortRecord.createRecord.bind(handlerEscortRecord));
|
||||
@@ -144,6 +146,8 @@ function registerRoutes(app) {
|
||||
// 共享订单时的陪诊师候选:在职陪诊师(含实习)可访问,最多看到姓名与等级
|
||||
router.get("/employee/shareable-attendants", requireAuth, handlerEmployee.getShareableAttendants.bind(handlerEmployee));
|
||||
router.get("/employee/me", requireAuth, handlerEmployee.getMyEmployee.bind(handlerEmployee));
|
||||
// 首页接单开关落库:仅在职正式陪诊师可切换
|
||||
router.patch("/employee/me/online", requireAuth, updateLimit, handlerEmployee.updateMyOnlineStatus.bind(handlerEmployee));
|
||||
|
||||
// 员工(陪诊师)管理:管理端 CRUD,必须管理员。
|
||||
// 与下方公开的 /attendant 公示接口分离:这里返回真实姓名等内部字段
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
});
|
||||
@@ -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,7 +201,14 @@ test("正式陪诊师接单写入陪诊师快照,不校验支付状态", async
|
||||
},
|
||||
};
|
||||
|
||||
await withModel("Employee", employeeFindOneStub(buildEmployee()), () =>
|
||||
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);
|
||||
@@ -209,6 +219,7 @@ test("正式陪诊师接单写入陪诊师快照,不校验支付状态", async
|
||||
assert.equal(payload.sex, "male");
|
||||
assert.equal(payload.mobile, "13700137000");
|
||||
assert.equal(ctx.body.data.record.attendantAssignedToMe, true);
|
||||
assert.equal(bumped, CERT_EMPLOYEE_ID);
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
Reference in New Issue
Block a user