diff --git a/handler/employee.js b/handler/employee.js index 0a6a412..7aee92c 100644 --- a/handler/employee.js +++ b/handler/employee.js @@ -199,6 +199,54 @@ class HandlerEmployee { } } + // 共享候选名单:所有在职陪诊师(含实习),供接单陪诊师把订单共享出去。 + // 与公示接口不同:这里不做姓名脱敏,也不排除实习,但必须本人是在职陪诊师。 + async getShareableAttendants(ctx) { + try { + const userId = ctx.state.user?._id; + if (!userId) return ResponseUtil.unauthorized(ctx, "登录已失效"); + + const me = await DBModel.Employee.findOne({ userId, role: "attendant", status: "active" }) + .select("_id") + .lean() + .exec(); + if (!me) return ResponseUtil.forbidden(ctx, "仅在职陪诊师可查看共享名单"); + + const list = await DBModel.Employee.find({ role: "attendant", status: "active" }) + .select("profile.name attendantInfo.stage attendantInfo.grade attendantInfo.star") + .lean() + .exec(); + + const gradeOrder = { diamond: 0, gold: 1, silver: 2, bronze: 3 }; + const gradeLabels = { diamond: "钻石", gold: "黄金", silver: "白银", bronze: "青铜" }; + const attendants = list + .filter((item) => String(item._id) !== String(me._id)) + .map((item) => { + const level = HandlerEmployee.normalizeAttendantLevel(item.attendantInfo); + return { + employeeId: String(item._id), + name: item.profile?.name || "", + stage: level.stage, + grade: level.grade, + star: level.star, + stageText: level.stage === "intern" ? "实习陪诊师" : "正式陪诊师", + gradeText: `${gradeLabels[level.grade]}${level.grade === "diamond" && level.star + ? ` ${"★".repeat(level.star)}` + : ""}`, + }; + }) + .sort((a, b) => { + const stageDiff = (a.stage === "intern" ? 1 : 0) - (b.stage === "intern" ? 1 : 0); + if (stageDiff) return stageDiff; + return (gradeOrder[a.grade] ?? 9) - (gradeOrder[b.grade] ?? 9); + }); + + return ResponseUtil.success(ctx, { attendants }, "查询成功"); + } catch (err) { + return ResponseUtil.internalError(ctx, err); + } + } + // 当前登录账号的员工档案:登录即可访问,供管理端判定陪诊员身份。 // 只返回员工档案本身,不重复做管理员判定(管理员身份由管理端按登录响应的 apps 判定) async getMyEmployee(ctx) { diff --git a/handler/escort_record.js b/handler/escort_record.js index 0ef3168..ddec3c7 100644 --- a/handler/escort_record.js +++ b/handler/escort_record.js @@ -131,6 +131,105 @@ class HandlerEscortRecord { && String(record.attendant.id) === String(user?._id); } + /** + * 读取登录账号的在职陪诊师档案;非在职陪诊师返回 null + * @param {ObjectId} userId 登录用户ID + */ + static async loadAttendant(userId) { + if (!userId) return null; + const employee = await DBModel.Employee.findOne({ userId }) + .select("employeeNo userId role status profile.name profile.sex profile.phone attendantInfo") + .lean() + .exec(); + if (!employee || employee.role !== "attendant" || employee.status !== "active") return null; + return employee; + } + + // 阶段归一化:存量档案缺字段时按正式陪诊师处理 + static attendantStage(employee) { + return employee?.attendantInfo?.stage === "intern" ? "intern" : "certified"; + } + + /** + * 陪诊师能否查看订单详情:未分配订单、本人已接订单、被共享的订单 + * 实习陪诊师同样可以看到未分配订单,但接单会被 acceptRecord 拦截 + */ + static canAttendantViewRecord(record, employee, userId) { + if (!record || !employee) return false; + const employeeId = String(employee._id); + const sharedWith = Array.isArray(record.attendant?.sharedWith) ? record.attendant.sharedWith : []; + if (sharedWith.some((id) => String(id) === employeeId)) return true; + if (!record.attendant?.id) return true; + return String(record.attendant.id) === String(userId); + } + + // 手机号脱敏:保留前三后四,避免未接单前泄露完整联系方式 + static maskMobile(mobile) { + const text = String(mobile || ""); + if (!text) return ""; + if (text.length < 7) return "****"; + return `${text.slice(0, 3)}****${text.slice(-4)}`; + } + + // 姓名脱敏:未接单前只暴露姓 + static maskName(name) { + const text = String(name || ""); + return text ? `${text.slice(0, 1)}**` : ""; + } + + // 共享对象入参:兼容 employeeId 与 employeeIds,去重并过滤非法 ObjectId + static parseShareEmployeeIds(body = {}) { + const raw = body.employeeIds !== undefined ? body.employeeIds : body.employeeId; + const list = Array.isArray(raw) ? raw : [raw]; + const ids = list + .filter((id) => typeof id === "string" && /^[0-9a-fA-F]{24}$/.test(id)) + .map((id) => String(id)); + return [...new Set(ids)]; + } + + /** + * 陪诊师视角补充展示字段: + * - attendantAssignedToMe / attendantSharedToMe / isPoolOrder 供前端决定按钮 + * - 实习陪诊师看未分配订单时脱敏手机号、详细地址、病历号等 + * @param {Object} record 已转成普通对象的订单 + * @param {Object} employee 当前陪诊师档案 + */ + static decorateAttendantRecord(record, employee) { + if (!record) return record; + const employeeId = String(employee?._id || ""); + const sharedWith = Array.isArray(record.attendant?.sharedWith) + ? record.attendant.sharedWith.map((id) => String(id)) + : []; + const assignedToMe = Boolean(record.attendant?.id) + && String(record.attendant.id) === String(employee?.userId || ""); + const isPoolOrder = !record.attendant?.id; + + record.attendantAssignedToMe = assignedToMe; + record.attendantSharedToMe = employeeId ? sharedWith.includes(employeeId) : false; + record.attendantSharedEmployeeIds = sharedWith; + record.isPoolOrder = isPoolOrder; + // 共享名单是内部协作信息,不整体回传 + if (record.attendant) delete record.attendant.sharedWith; + + if (HandlerEscortRecord.attendantStage(employee) === "intern" && isPoolOrder) { + record.desensitized = true; + if (record.patient) { + record.patient.name = HandlerEscortRecord.maskName(record.patient.name); + record.patient.mobile = HandlerEscortRecord.maskMobile(record.patient.mobile); + } + if (record.hospital) { + if (record.hospital.address) record.hospital.address = "接单后可见"; + if (record.hospital.medicalRecordNo) record.hospital.medicalRecordNo = "接单后可见"; + } + if (record.shippingAddress) { + record.shippingAddress.mobile = HandlerEscortRecord.maskMobile(record.shippingAddress.mobile); + if (record.shippingAddress.address) record.shippingAddress.address = "接单后可见"; + } + if (record.inquiry?.medicalHistory) record.inquiry.medicalHistory = "接单后可见"; + } + return record; + } + /** * 输出给前端的订单视图:追加支付窗口终点,供列表/详情判断「支付已超时」。 * 只派生展示字段,不写库。 @@ -312,7 +411,23 @@ class HandlerEscortRecord { const effectiveUserId = mode === "self" ? loginUserId : (mode === "all" ? userId : undefined); - const attendantId = mode === "attendant" ? loginUserId : undefined; + let attendantId; + let attendantVisibility; + let attendantEmployee = null; + if (mode === "attendant") { + attendantEmployee = await HandlerEscortRecord.loadAttendant(loginUserId); + if (!attendantEmployee) { + return ResponseUtil.forbidden(ctx, "仅在职陪诊师可查看订单"); + } + const isIntern = HandlerEscortRecord.attendantStage(attendantEmployee) === "intern"; + // 可见范围由身份决定,前端传什么都会被忽略: + // 实习 = 未分配 + 被共享;正式 = 未分配 + 本人已接 + 被共享 + attendantVisibility = { + includeUnassigned: true, + userId: isIntern ? undefined : loginUserId, + employeeId: attendantEmployee._id, + }; + } // status解析成数组 let statusArray = null; @@ -360,6 +475,7 @@ class HandlerEscortRecord { includeCancelled: ["1", "true"].includes(String(includeCancelled)), userId: effectiveUserId, attendantId, + attendantVisibility, appointmentDate, healthProfileId, paymentStatus: paymentStatusArray, @@ -369,7 +485,13 @@ class HandlerEscortRecord { keyword, }); - const records = result.records.map((record) => HandlerEscortRecord.withPaymentWindow(record)); + const records = result.records.map((record) => { + const plain = HandlerEscortRecord.withPaymentWindow(record); + // 陪诊员列表:补充接单/共享标记,实习看未分配订单时脱敏 + return mode === "attendant" + ? HandlerEscortRecord.decorateAttendantRecord(plain, attendantEmployee) + : plain; + }); return ResponseUtil.success(ctx, { ...result, records, page, pageSize }, "查询成功"); } catch (err) { return ResponseUtil.internalError(ctx, err); @@ -388,12 +510,134 @@ class HandlerEscortRecord { if (!record) { return ResponseUtil.error(ctx, "陪诊记录不存在", null, 404); } - // 归属校验:非本人订单按无权限处理,避免凭 id 遍历他人订单 - if (!HandlerEscortRecord.canAccess(ctx.state.user, record)) { - return ResponseUtil.forbidden(ctx, "无权访问该订单"); + const user = ctx.state.user; + const isOwner = String(record.userId) === String(user?._id); + let employee = null; + if (!HandlerEscortRecord.isAdmin(user) && !isOwner) { + // 陪诊师:本人已接、被共享或未分配订单可查看,其余按无权限处理 + employee = await HandlerEscortRecord.loadAttendant(user?._id); + if (!HandlerEscortRecord.canAccess(user, record) + && !HandlerEscortRecord.canAttendantViewRecord(record, employee, user?._id)) { + return ResponseUtil.forbidden(ctx, "无权访问该订单"); + } } - return ResponseUtil.success(ctx, { record: HandlerEscortRecord.withPaymentWindow(record) }, "查询成功"); + const plain = HandlerEscortRecord.withPaymentWindow(record); + if (employee) HandlerEscortRecord.decorateAttendantRecord(plain, employee); + return ResponseUtil.success(ctx, { record: plain }, "查询成功"); + } catch (err) { + return ResponseUtil.internalError(ctx, err); + } + } + + /** + * 接单:正式陪诊师把未分配订单接到自己名下。 + * 与支付状态无关;条件更新保证并发下只有一人成功。 + */ + async acceptRecord(ctx) { + try { + const { id } = ctx.params; + if (!id) return ResponseUtil.badRequest(ctx, "缺少记录ID"); + + const userId = ctx.state.user?._id; + const employee = await HandlerEscortRecord.loadAttendant(userId); + if (!employee) return ResponseUtil.forbidden(ctx, "仅在职陪诊师可接单"); + if (HandlerEscortRecord.attendantStage(employee) === "intern") { + return ResponseUtil.forbidden(ctx, "实习陪诊师暂不能接单"); + } + + const record = await DBModel.EscortRecord.findById(id); + if (!record || record.deletedAt) return ResponseUtil.notFound(ctx, "陪诊记录不存在"); + if (record.attendant?.id) { + return ResponseUtil.error(ctx, "订单已被其他陪诊师接单", null, 409); + } + + const profile = employee.profile || {}; + const updated = await DBModel.EscortRecord.acceptRecord(id, { + id: userId, + name: profile.name || "", + sex: ["male", "female"].includes(profile.sex) ? profile.sex : "none", + mobile: profile.phone || "", + }); + // 并发下另一个陪诊师先接走:条件更新返回 null + if (!updated) { + return ResponseUtil.error(ctx, "订单已被其他陪诊师接单", null, 409); + } + + const plain = HandlerEscortRecord.withPaymentWindow(updated); + HandlerEscortRecord.decorateAttendantRecord(plain, employee); + return ResponseUtil.success(ctx, { record: plain }, "接单成功"); + } catch (err) { + return ResponseUtil.internalError(ctx, err); + } + } + + /** + * 共享订单:仅接单陪诊师本人可操作,共享对象为所有在职陪诊师(含实习) + */ + async shareRecord(ctx) { + try { + const { id } = ctx.params; + if (!id) return ResponseUtil.badRequest(ctx, "缺少记录ID"); + + const userId = ctx.state.user?._id; + const employee = await HandlerEscortRecord.loadAttendant(userId); + if (!employee) return ResponseUtil.forbidden(ctx, "仅在职陪诊师可共享订单"); + + const record = await DBModel.EscortRecord.findById(id); + if (!record) return ResponseUtil.notFound(ctx, "陪诊记录不存在"); + if (String(record.attendant?.id || "") !== String(userId)) { + return ResponseUtil.forbidden(ctx, "只有接单陪诊师可以共享该订单"); + } + + const requested = HandlerEscortRecord.parseShareEmployeeIds(ctx.request.body || {}); + if (requested.length === 0) return ResponseUtil.badRequest(ctx, "请选择要共享的陪诊师"); + + // 共享对象必须是在职陪诊师;不允许共享给自己 + const targets = await DBModel.Employee.find({ + _id: { $in: requested }, + role: "attendant", + status: "active", + }).select("_id").lean().exec(); + const employeeIds = targets + .map((item) => String(item._id)) + .filter((employeeId) => employeeId !== String(employee._id)); + if (employeeIds.length === 0) { + return ResponseUtil.badRequest(ctx, "共享对象不存在或不是在职陪诊师"); + } + + const updated = await DBModel.EscortRecord.addSharedWith(id, userId, employeeIds); + if (!updated) return ResponseUtil.forbidden(ctx, "只有接单陪诊师可以共享该订单"); + + const plain = HandlerEscortRecord.withPaymentWindow(updated); + HandlerEscortRecord.decorateAttendantRecord(plain, employee); + return ResponseUtil.success(ctx, { record: plain }, "共享成功"); + } catch (err) { + return ResponseUtil.internalError(ctx, err); + } + } + + /** + * 取消共享:仅接单陪诊师本人可操作 + */ + async unshareRecord(ctx) { + try { + const { id } = ctx.params; + if (!id) return ResponseUtil.badRequest(ctx, "缺少记录ID"); + + const userId = ctx.state.user?._id; + const employee = await HandlerEscortRecord.loadAttendant(userId); + if (!employee) return ResponseUtil.forbidden(ctx, "仅在职陪诊师可操作共享"); + + const employeeIds = HandlerEscortRecord.parseShareEmployeeIds(ctx.request.body || {}); + if (employeeIds.length === 0) return ResponseUtil.badRequest(ctx, "请选择要取消共享的陪诊师"); + + const updated = await DBModel.EscortRecord.removeSharedWith(id, userId, employeeIds); + if (!updated) return ResponseUtil.forbidden(ctx, "只有接单陪诊师可以取消共享"); + + const plain = HandlerEscortRecord.withPaymentWindow(updated); + HandlerEscortRecord.decorateAttendantRecord(plain, employee); + return ResponseUtil.success(ctx, { record: plain }, "已取消共享"); } catch (err) { return ResponseUtil.internalError(ctx, err); } diff --git a/models/schema/escort_record.js b/models/schema/escort_record.js index 49f7459..da74968 100644 --- a/models/schema/escort_record.js +++ b/models/schema/escort_record.js @@ -89,6 +89,13 @@ const EscortRecordSchema = mongoose.Schema( name: { type: String, default: "", comment: "陪诊员姓名" }, sex: { type: String, enum: ["none", "male", "female"], comment: "陪诊员性别" }, mobile: { type: String, default: "", comment: "陪诊员联系电话" }, + // 接单陪诊师把订单共享给其他陪诊师:存 employee._id(不是登录 userId), + // 这样展示共享对象时不依赖账号绑定关系 + sharedWith: [{ + type: mongoose.Schema.Types.ObjectId, + ref: "employee", + comment: "共享给其他陪诊师(employee._id)", + }], }, /** @@ -245,6 +252,7 @@ const EscortRecordSchema = mongoose.Schema( EscortRecordSchema.statics.buildRecordFilter = function (options = {}) { const { status, cancelStatus, userId, appointmentDate, healthProfileId, attendantId, + attendantVisibility, includeDeleted = false, includeCancelled = false, paymentStatus, payChannel, startDate, endDate, keyword, } = options; @@ -279,6 +287,19 @@ EscortRecordSchema.statics.buildRecordFilter = function (options = {}) { if (userId) filter.userId = userId; // 陪诊员列表:只查 assign 到本人的订单 if (attendantId) filter["attendant.id"] = attendantId; + // 陪诊师订单池:按身份合并可见范围,scope 由服务端计算,不接受前端传入。 + // - includeUnassigned:所有在职陪诊师都能看到未分配订单 + // - userId:正式陪诊师还能看到自己已接的订单(实习不能接单,故不传) + // - employeeId:被共享的订单 + if (attendantVisibility) { + const or = []; + if (attendantVisibility.includeUnassigned) or.push({ "attendant.id": null }); + if (attendantVisibility.userId) or.push({ "attendant.id": attendantVisibility.userId }); + if (attendantVisibility.employeeId) { + or.push({ "attendant.sharedWith": attendantVisibility.employeeId }); + } + if (or.length) andConditions.push({ $or: or }); + } if (healthProfileId) filter.healthProfileId = healthProfileId; // 支付状态 / 渠道:管理端按收款情况对账时使用 @@ -456,6 +477,53 @@ EscortRecordSchema.statics.findByIdempotencyKey = async function (userId, idempo return await this.findOne({ userId, idempotencyKey, deletedAt: null }).exec(); }; +// 接单:只有「未分配」的订单能被接走,条件更新保证并发下只有一个陪诊师成功。 +// 与支付状态无关:订单是否付款不影响接单。 +EscortRecordSchema.statics.acceptRecord = async function (id, attendant) { + return await this.findOneAndUpdate( + { + _id: id, + deletedAt: null, + "attendant.id": null, + cancelStatus: { $ne: "cancelled" }, + status: { $ne: "cancelled" }, + }, + { + $set: { + "attendant.id": attendant.id, + "attendant.name": attendant.name || "", + "attendant.sex": attendant.sex || "none", + "attendant.mobile": attendant.mobile || "", + "meta.updatetime": Date.now(), + }, + }, + { new: true, runValidators: true } + ); +}; + +// 共享 / 取消共享:只有当前接单陪诊师本人能操作 +EscortRecordSchema.statics.addSharedWith = async function (id, attendantId, employeeIds) { + return await this.findOneAndUpdate( + { _id: id, deletedAt: null, "attendant.id": attendantId }, + { + $addToSet: { "attendant.sharedWith": { $each: employeeIds } }, + $set: { "meta.updatetime": Date.now() }, + }, + { new: true, runValidators: true } + ); +}; + +EscortRecordSchema.statics.removeSharedWith = async function (id, attendantId, employeeIds) { + return await this.findOneAndUpdate( + { _id: id, deletedAt: null, "attendant.id": attendantId }, + { + $pull: { "attendant.sharedWith": { $in: employeeIds } }, + $set: { "meta.updatetime": Date.now() }, + }, + { new: true, runValidators: true } + ); +}; + /** * 根据ID查找陪诊记录 * diff --git a/routes/index.js b/routes/index.js index ec1b4b5..c61e1cc 100644 --- a/routes/index.js +++ b/routes/index.js @@ -107,6 +107,10 @@ function registerRoutes(app) { router.post("/escort-record/:id/refund/manual", requireAuth, requireAdmin, handlerPayment.completeManualRefund.bind(handlerPayment)); 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/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)); router.put("/escort-record/:id", requireAuth, updateLimit, handlerEscortRecord.updateRecord.bind(handlerEscortRecord)); router.patch("/escort-record/:id/status", requireAuth, updateLimit, handlerEscortRecord.updateStatus.bind(handlerEscortRecord)); @@ -137,6 +141,8 @@ function registerRoutes(app) { // 当前账号的员工档案:登录即可访问,供管理端判定陪诊员身份。 // 必须注册在 /employee 管理端路由之前,避免被更宽的路由抢占 + // 共享订单时的陪诊师候选:在职陪诊师(含实习)可访问,最多看到姓名与等级 + router.get("/employee/shareable-attendants", requireAuth, handlerEmployee.getShareableAttendants.bind(handlerEmployee)); router.get("/employee/me", requireAuth, handlerEmployee.getMyEmployee.bind(handlerEmployee)); // 员工(陪诊师)管理:管理端 CRUD,必须管理员。 diff --git a/test/attendant_order_pool.test.js b/test/attendant_order_pool.test.js new file mode 100644 index 0000000..d93e8a6 --- /dev/null +++ b/test/attendant_order_pool.test.js @@ -0,0 +1,319 @@ +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 RECORD_ID = "64b000000000000000000010"; +const OWNER_ID = "64b000000000000000000001"; +const INTERN_USER_ID = "64b000000000000000000002"; +const INTERN_EMPLOYEE_ID = "64b000000000000000000022"; +const CERT_USER_ID = "64b000000000000000000003"; +const CERT_EMPLOYEE_ID = "64b000000000000000000033"; +const OTHER_USER_ID = "64b000000000000000000004"; + +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: "北京市东城区", medicalRecordNo: "MR0001" }, + shippingAddress: { mobile: "13900139000", address: "北京市西城区" }, + inquiry: { medicalHistory: "高血压", demand: "陪同检查" }, + schedule: { + date: new Date("2026-12-01T00:00:00.000Z"), + startTime: "08:00", + endTime: "17:00", + duration: 480, + }, + payment: { totalFee: 500, paidFee: 0, status: "unpaid" }, + attendant: { id: null, name: "", sharedWith: [] }, + ...overrides, + }; +} + +function buildEmployee(overrides = {}) { + return { + _id: CERT_EMPLOYEE_ID, + userId: CERT_USER_ID, + role: "attendant", + status: "active", + profile: { name: "李四", sex: "male", phone: "13700137000" }, + attendantInfo: { stage: "certified", grade: "bronze" }, + ...overrides, + }; +} + +function createCtx({ body = {}, user, params = { id: RECORD_ID } } = {}) { + return { + request: { query: {}, body }, + params, + state: { user: user ?? { _id: CERT_USER_ID } }, + headers: {}, + status: 200, + body: null, + set(name, value) { + this.headers[name] = value; + }, + }; +} + +function employeeFindOneStub(employee) { + return { + findOne: () => ({ + select: () => ({ + lean: () => ({ exec: async () => employee }), + }), + }), + }; +} + +function withModel(modelName, stub, fn) { + const previous = DBModel[modelName]; + DBModel[modelName] = stub; + return Promise.resolve(fn()).finally(() => { + DBModel[modelName] = previous; + }); +} + +test("实习陪诊师看未分配订单:可见范围含未分配且按 employeeId 查共享", async () => { + const intern = buildEmployee({ + _id: INTERN_EMPLOYEE_ID, + userId: INTERN_USER_ID, + profile: { name: "王五", sex: "female", phone: "13600136000" }, + attendantInfo: { stage: "intern", grade: "bronze" }, + }); + let captured = null; + const recordStub = { + findRecordPage: async (options) => { + captured = options; + return { records: [buildRecord()], total: 1, counts: {} }; + }, + }; + + await withModel("Employee", employeeFindOneStub(intern), () => + withModel("EscortRecord", recordStub, async () => { + const ctx = createCtx({ user: { _id: INTERN_USER_ID } }); + await new HandlerEscortRecord().getAttendantRecords(ctx); + + assert.equal(ctx.body.code, 0); + assert.equal(captured.attendantVisibility.includeUnassigned, true); + assert.equal(captured.attendantVisibility.userId, undefined); + assert.equal(String(captured.attendantVisibility.employeeId), INTERN_EMPLOYEE_ID); + + const record = ctx.body.data.records[0]; + assert.equal(record.isPoolOrder, true); + assert.equal(record.desensitized, true); + assert.equal(record.patient.name, "张**"); + assert.equal(record.patient.mobile, "138****8000"); + assert.equal(record.hospital.address, "接单后可见"); + assert.equal(record.hospital.medicalRecordNo, "接单后可见"); + assert.equal(record.inquiry.medicalHistory, "接单后可见"); + }) + ); +}); + +test("正式陪诊师可见本人已接与被共享订单,未分配同样在内", async () => { + let captured = null; + const record = buildRecord({ + attendant: { id: OTHER_USER_ID, name: "赵六", sharedWith: [CERT_EMPLOYEE_ID] }, + }); + const recordStub = { + findRecordPage: async (options) => { + captured = options; + return { records: [record], total: 1, counts: {} }; + }, + }; + + await withModel("Employee", employeeFindOneStub(buildEmployee()), () => + withModel("EscortRecord", recordStub, async () => { + const ctx = createCtx({ user: { _id: CERT_USER_ID } }); + await new HandlerEscortRecord().getAttendantRecords(ctx); + + assert.equal(ctx.body.code, 0); + assert.equal(captured.attendantVisibility.includeUnassigned, true); + assert.equal(String(captured.attendantVisibility.userId), CERT_USER_ID); + + const item = ctx.body.data.records[0]; + assert.equal(item.attendantSharedToMe, true); + assert.deepEqual(item.attendantSharedEmployeeIds, [CERT_EMPLOYEE_ID]); + assert.equal(item.attendant.sharedWith, undefined); + assert.equal(item.desensitized, undefined); + assert.equal(item.patient.mobile, "13800138000"); + }) + ); +}); + +test("实习陪诊师不能接单", async () => { + const intern = buildEmployee({ + _id: INTERN_EMPLOYEE_ID, + userId: INTERN_USER_ID, + attendantInfo: { stage: "intern" }, + }); + let accepted = 0; + + await withModel("Employee", employeeFindOneStub(intern), () => + withModel("EscortRecord", { + findById: async () => buildRecord(), + acceptRecord: async () => { + accepted += 1; + return buildRecord(); + }, + }, async () => { + const ctx = createCtx({ user: { _id: INTERN_USER_ID } }); + await new HandlerEscortRecord().acceptRecord(ctx); + + assert.equal(ctx.body.code, 403); + assert.equal(accepted, 0); + }) + ); +}); + +test("正式陪诊师接单写入陪诊师快照,不校验支付状态", async () => { + let payload = null; + const record = buildRecord(); + const recordStub = { + findById: async () => record, + acceptRecord: async (id, attendant) => { + payload = attendant; + return { + ...record, + attendant: { id: attendant.id, name: attendant.name, sharedWith: [] }, + }; + }, + }; + + await withModel("Employee", employeeFindOneStub(buildEmployee()), () => + 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); + }) + ); +}); + +test("订单已被接走时返回 409 且不重复写库", async () => { + let accepted = 0; + const recordStub = { + findById: async () => buildRecord({ attendant: { id: OTHER_USER_ID, sharedWith: [] } }), + acceptRecord: async () => { + accepted += 1; + return null; + }, + }; + + await withModel("Employee", employeeFindOneStub(buildEmployee()), () => + withModel("EscortRecord", recordStub, async () => { + const ctx = createCtx({ user: { _id: CERT_USER_ID } }); + await new HandlerEscortRecord().acceptRecord(ctx); + + assert.equal(ctx.body.code, 409); + assert.equal(accepted, 0); + }) + ); +}); + +test("接单陪诊师可把订单共享给在职陪诊师(含实习)", async () => { + let sharedIds = null; + const record = buildRecord({ attendant: { id: CERT_USER_ID, name: "李四", sharedWith: [] } }); + const me = buildEmployee(); + const employeeStub = { + findOne: () => ({ + select: () => ({ lean: () => ({ exec: async () => me }) }), + }), + find: () => ({ + select: () => ({ + lean: () => ({ + exec: async () => [{ _id: INTERN_EMPLOYEE_ID }, { _id: OTHER_USER_ID }], + }), + }), + }), + }; + const recordStub = { + findById: async () => record, + addSharedWith: async (id, attendantId, employeeIds) => { + sharedIds = { id, attendantId, employeeIds }; + return { ...record, attendant: { ...record.attendant, sharedWith: employeeIds } }; + }, + }; + + await withModel("Employee", employeeStub, () => + withModel("EscortRecord", recordStub, async () => { + const ctx = createCtx({ + user: { _id: CERT_USER_ID }, + body: { employeeIds: [INTERN_EMPLOYEE_ID, OTHER_USER_ID] }, + }); + await new HandlerEscortRecord().shareRecord(ctx); + + assert.equal(ctx.body.code, 0); + assert.equal(sharedIds.attendantId, CERT_USER_ID); + assert.deepEqual(sharedIds.employeeIds, [INTERN_EMPLOYEE_ID, OTHER_USER_ID]); + assert.equal(ctx.body.data.record.attendantSharedEmployeeIds.length, 2); + }) + ); +}); + +test("非接单陪诊师不能共享订单", async () => { + let shared = 0; + const recordStub = { + findById: async () => buildRecord({ attendant: { id: OTHER_USER_ID, sharedWith: [] } }), + addSharedWith: async () => { + shared += 1; + return null; + }, + }; + + await withModel("Employee", employeeFindOneStub(buildEmployee()), () => + withModel("EscortRecord", recordStub, async () => { + const ctx = createCtx({ + user: { _id: CERT_USER_ID }, + body: { employeeIds: [INTERN_EMPLOYEE_ID] }, + }); + await new HandlerEscortRecord().shareRecord(ctx); + + assert.equal(ctx.body.code, 403); + assert.equal(shared, 0); + }) + ); +}); + +test("实习陪诊师可看未分配订单详情,但不能看他人已接且未共享的订单", async () => { + const intern = buildEmployee({ + _id: INTERN_EMPLOYEE_ID, + userId: INTERN_USER_ID, + attendantInfo: { stage: "intern" }, + }); + + await withModel("Employee", employeeFindOneStub(intern), () => + withModel("EscortRecord", { + findRecordById: async () => buildRecord(), + }, async () => { + const ctx = createCtx({ user: { _id: INTERN_USER_ID } }); + await new HandlerEscortRecord().getRecordById(ctx); + + assert.equal(ctx.body.code, 0); + assert.equal(ctx.body.data.record.desensitized, true); + assert.equal(ctx.body.data.record.patient.mobile, "138****8000"); + }) + ); + + await withModel("Employee", employeeFindOneStub(intern), () => + withModel("EscortRecord", { + findRecordById: async () => buildRecord({ attendant: { id: OTHER_USER_ID, sharedWith: [] } }), + }, async () => { + const ctx = createCtx({ user: { _id: INTERN_USER_ID } }); + await new HandlerEscortRecord().getRecordById(ctx); + + assert.equal(ctx.body.code, 403); + }) + ); +});