import { test } from "node:test"; import assert from "node:assert/strict"; import { DBModel } from "../models/index.js"; import { parseObjectId } from "../agent/infra/tools/db/utils.js"; import { createHealthProfileQueryTool } from "../agent/infra/tools/db/user/health_profile_query.js"; import { healthProfileQueryTool } from "../agent/infra/tools/db/admin/health_profile_query.js"; import { createEmployeeQueryTool } from "../agent/infra/tools/db/user/employee_query.js"; import { employeeQueryTool } from "../agent/infra/tools/db/admin/employee_query.js"; import { toSelfEmployee } from "../agent/infra/tools/db/query/employee_query.js"; import { createEmployeeReviewQueryTool } from "../agent/infra/tools/db/user/employee_review_query.js"; import { employeeReviewQueryTool } from "../agent/infra/tools/db/admin/employee_review_query.js"; import { createEscortRecordQueryTool } from "../agent/infra/tools/db/user/escort_record_query.js"; import { escortRecordQueryTool } from "../agent/infra/tools/db/admin/escort_record_query.js"; import { createAttendantEscortRecordQueryTool } from "../agent/infra/tools/db/attendant/escort_record_query.js"; import { buildAttendantEscortRecordSetTool } from "../agent/infra/tools/db/attendant/escort_record_set.js"; import { escortRecordSetTool } from "../agent/infra/tools/db/admin/escort_record_set.js"; import { HandlerPayment } from "../handler/payment.js"; import { resolveEscortAdminRole } from "../utils/permissions.js"; const OWNER_ID = "64b000000000000000000001"; const OTHER_ID = "64b000000000000000000002"; // LangChain 不同版本可能返回对象或 JSON 字符串,统一按对象消费 function parseResult(result) { return typeof result === "string" ? JSON.parse(result) : result; } /** * 只记录查询条件的 Mongoose 模型桩:验证工具把归属条件真正带进了查询 */ function createModelStub(docs = []) { const calls = []; const chain = { sort() { return this; }, skip() { return this; }, limit() { return this; }, select() { return this; }, lean() { return Promise.resolve(docs); }, }; return { calls, find(filter) { calls.push({ method: "find", filter }); return chain; }, countDocuments(filter) { calls.push({ method: "countDocuments", filter }); return Promise.resolve(docs.length); }, findOne(filter) { calls.push({ method: "findOne", filter }); return { select() { return this; }, lean() { return Promise.resolve(docs[0] ?? null); }, }; }, }; } function withModel(modelName, stub, fn) { const previous = DBModel[modelName]; DBModel[modelName] = stub; return Promise.resolve(fn()).finally(() => { DBModel[modelName] = previous; }); } /** * 陪诊员改单模型桩:findOne 返回固定记录,findOneAndUpdate 返回合并后的记录 */ function createRecordModelStub(record) { const calls = []; return { calls, findOne(filter) { calls.push({ method: "findOne", filter }); return Promise.resolve(record); }, findOneAndUpdate(filter, update, options) { calls.push({ method: "findOneAndUpdate", filter, update, options }); return Promise.resolve(record ? { ...record, ...update.$set } : null); }, }; } test("ObjectId 严格解析拒绝非法输入", () => { assert.equal(parseObjectId(OWNER_ID).toHexString(), OWNER_ID); assert.equal(parseObjectId(null), null); assert.equal(parseObjectId(""), null); assert.equal(parseObjectId("123"), null); assert.equal(parseObjectId("z".repeat(24)), null); }); test("用户端健康档案查询强制按登录用户隔离", async () => { const stub = createModelStub([]); await withModel("HealthProfile", stub, async () => { const tool = createHealthProfileQueryTool({ _id: OWNER_ID }); assert.equal("userId" in tool.schema.shape, false); const byId = parseResult(await tool.invoke({ profileId: OTHER_ID })); assert.equal(byId.success, false); assert.equal(stub.calls[0].filter.userId.toHexString(), OWNER_ID); assert.equal(stub.calls[0].filter._id.toHexString(), OTHER_ID); const list = parseResult(await tool.invoke({ name: "张三" })); assert.equal(list.success, true); for (const call of stub.calls) { assert.equal(call.filter.userId.toHexString(), OWNER_ID); } }); }); test("管理端健康档案查询允许按用户筛选", async () => { const stub = createModelStub([]); await withModel("HealthProfile", stub, async () => { assert.equal("userId" in healthProfileQueryTool.schema.shape, true); const result = parseResult(await healthProfileQueryTool.invoke({ userId: OTHER_ID })); assert.equal(result.success, true); assert.equal(stub.calls[0].filter.userId.toHexString(), OTHER_ID); }); }); test("用户端员工查询只取本人数据且不返回敏感字段", async () => { const stub = createModelStub([]); await withModel("Employee", stub, async () => { const tool = createEmployeeQueryTool({ _id: OWNER_ID }); assert.equal("userId" in tool.schema.shape, false); const result = parseResult(await tool.invoke({})); assert.equal(result.success, true); for (const call of stub.calls) { assert.equal(call.filter.userId.toHexString(), OWNER_ID); } }); }); test("管理端员工查询允许按用户筛选", async () => { const stub = createModelStub([]); await withModel("Employee", stub, async () => { assert.equal("userId" in employeeQueryTool.schema.shape, true); const result = parseResult(await employeeQueryTool.invoke({ userId: OTHER_ID })); assert.equal(result.success, true); assert.equal(stub.calls[0].filter.userId.toHexString(), OTHER_ID); }); }); test("用户端本人员工视图剔除联系方式、证件号与证书编号", () => { const raw = { employeeNo: "E001", userId: OWNER_ID, orgId: OTHER_ID, role: "attendant", profile: { name: "张三", mobile: "13800000000", email: "zhangsan@example.com", idNumber: "110101199001011234", birthday: new Date("1990-01-01"), avatar: "https://example.com/a.png", }, work: { department: "陪诊部", title: "陪诊员", qualification: "CERT-001", healthCertificate: { number: "HC-001", issueDate: new Date("2025-01-01"), expireDate: new Date("2026-01-01"), }, trainings: [{ title: "陪诊培训", org: "培训机构", date: new Date("2025-01-01") }], }, attendantInfo: { serviceAreas: ["北京"], specialties: ["陪诊"], languages: ["普通话"], rating: 5, orderCount: 10, isOnline: true, }, emergencyContact: { name: "李四", phone: "13900000000", relation: "朋友" }, remark: "内部备注", introduction: "简介", meta: { createtime: new Date("2025-01-01"), updatetime: new Date("2025-06-01") }, }; const safe = toSelfEmployee(raw); assert.equal(safe.profile.name, "张三"); assert.equal(safe.profile.mobile, undefined); assert.equal(safe.profile.email, undefined); assert.equal(safe.profile.idNumber, undefined); assert.equal(safe.work.qualification, undefined); assert.equal(safe.work.qualificationVerified, true); assert.equal(safe.work.healthCertificate.number, undefined); assert.equal(safe.emergencyContact, undefined); assert.equal(safe.remark, undefined); assert.equal(safe.attendantInfo.rating, undefined); assert.equal(safe.attendantInfo.orderCount, 10); }); test("用户端陪诊记录查询强制按登录用户隔离且不开放管理端筛选", async () => { const stub = createModelStub([]); await withModel("EscortRecord", stub, async () => { const tool = createEscortRecordQueryTool({ _id: OWNER_ID }); assert.equal("mobile" in tool.schema.shape, false); assert.equal("attendantId" in tool.schema.shape, false); assert.equal("dateFrom" in tool.schema.shape, false); const result = parseResult(await tool.invoke({ status: "completed", mobile: "13800000000" })); assert.equal(result.success, true); for (const call of stub.calls) { assert.equal(String(call.filter.userId), OWNER_ID); assert.equal(call.filter.deletedAt, null); // 管理端筛选参数即使被传入,也会被 schema 剥离 assert.equal(call.filter["patient.mobile"], undefined); } }); }); test("管理端陪诊记录查询开放跨用户与管理端筛选", async () => { const stub = createModelStub([]); await withModel("EscortRecord", stub, async () => { assert.equal("mobile" in escortRecordQueryTool.schema.shape, true); assert.equal("attendantId" in escortRecordQueryTool.schema.shape, true); assert.equal("dateFrom" in escortRecordQueryTool.schema.shape, true); const result = parseResult(await escortRecordQueryTool.invoke({ mobile: "13800000000" })); assert.equal(result.success, true); for (const call of stub.calls) { assert.equal(call.filter.userId, undefined); assert.equal(call.filter["patient.mobile"], "13800000000"); } }); }); test("用户端员工评价查询强制按评价人隔离", async () => { const stub = createModelStub([]); await withModel("EmployeeReview", stub, async () => { const tool = createEmployeeReviewQueryTool({ _id: OWNER_ID }); assert.equal("userId" in tool.schema.shape, false); const result = parseResult(await tool.invoke({ employeeId: OTHER_ID })); assert.equal(result.success, true); for (const call of stub.calls) { assert.equal(call.filter.userId.toHexString(), OWNER_ID); assert.equal(call.filter.employeeId.toHexString(), OTHER_ID); } }); }); test("管理端员工评价查询允许按评价人筛选", async () => { const stub = createModelStub([]); await withModel("EmployeeReview", stub, async () => { assert.equal("userId" in employeeReviewQueryTool.schema.shape, true); const result = parseResult(await employeeReviewQueryTool.invoke({ userId: OTHER_ID })); assert.equal(result.success, true); assert.equal(stub.calls[0].filter.userId.toHexString(), OTHER_ID); }); }); test("陪诊员端陪诊记录查询强制按本人归属", async () => { const stub = createModelStub([]); await withModel("EscortRecord", stub, async () => { const tool = createAttendantEscortRecordQueryTool({ _id: OWNER_ID }); // 手机号与陪诊员 ID 属管理端筛选,陪诊员侧不暴露 assert.equal("mobile" in tool.schema.shape, false); assert.equal("attendantId" in tool.schema.shape, false); // 日期范围用于查自己的排期,保留 assert.equal("dateFrom" in tool.schema.shape, true); const result = parseResult( await tool.invoke({ status: "confirmed", attendantId: OTHER_ID, mobile: "13800000000" }) ); assert.equal(result.success, true); for (const call of stub.calls) { assert.equal(call.filter["attendant.id"].toHexString(), OWNER_ID); assert.equal(call.filter.userId, undefined); // 越权参数即使被传入,也会被 schema 剥离 assert.equal(call.filter["patient.mobile"], undefined); } }); }); test("陪诊员端改单拒绝非本人订单", async () => { const record = { _id: OTHER_ID, status: "confirmed", attendant: { id: OTHER_ID }, notes: {}, }; const stub = createRecordModelStub(record); await withModel("EscortRecord", stub, async () => { const tool = buildAttendantEscortRecordSetTool({ attendantId: OWNER_ID }); const result = parseResult(await tool.invoke({ orderId: OTHER_ID, status: "in_progress" })); assert.equal(result.success, false); assert.match(result.error, /未分配给你/); // 越权时不应进入更新阶段 assert.equal(stub.calls.filter((call) => call.method === "findOneAndUpdate").length, 0); }); }); test("陪诊员端改单只允许服务进度与本人备注", async () => { const record = { _id: OWNER_ID, status: "confirmed", attendant: { id: OWNER_ID }, notes: {}, }; const stub = createRecordModelStub(record); await withModel("EscortRecord", stub, async () => { const tool = buildAttendantEscortRecordSetTool({ attendantId: OWNER_ID }); // 费用字段不暴露、也不允许写入 assert.equal("payment" in tool.schema.shape, false); const result = parseResult( await tool.invoke({ orderId: OWNER_ID, status: "in_progress", notes: { escortNote: "已到达医院", medicalSummary: "完成检查" }, }) ); assert.equal(result.success, true); const updateCall = stub.calls.find((call) => call.method === "findOneAndUpdate"); assert.ok(updateCall); assert.equal(updateCall.filter["attendant.id"].toHexString(), OWNER_ID); // 并发保护:以读取时的旧状态作为条件 assert.equal(updateCall.filter.status, "confirmed"); assert.equal(updateCall.update.$set.status, "in_progress"); assert.equal(updateCall.update.$set["notes.escortNote"], "已到达医院"); assert.equal(updateCall.update.$set["notes.medicalSummary"], "完成检查"); assert.equal(updateCall.update.$set.payment, undefined); }); }); test("陪诊员端改单拒绝跳步", async () => { const record = { _id: OWNER_ID, status: "confirmed", attendant: { id: OWNER_ID }, notes: {}, }; const stub = createRecordModelStub(record); await withModel("EscortRecord", stub, async () => { const tool = buildAttendantEscortRecordSetTool({ attendantId: OWNER_ID }); // confirmed 不能直接跳 completed;cancelled 也不在 schema 枚举内,模型无法提交 const skip = parseResult(await tool.invoke({ orderId: OWNER_ID, status: "completed" })); assert.equal(skip.success, false); assert.match(skip.error, /Illegal status transition/); assert.equal(stub.calls.filter((call) => call.method === "findOneAndUpdate").length, 0); }); }); test("管理端 Agent 角色以员工档案为准", async () => { const stub = createModelStub([{ role: "attendant" }]); await withModel("Employee", stub, async () => { const role = await resolveEscortAdminRole({ _id: OWNER_ID, app: { "wxapp_companion": { role: ["user"] } }, }); assert.equal(role, "attendant"); const filter = stub.calls[0].filter; assert.equal(filter.userId.toHexString(), OWNER_ID); assert.equal(filter.status, "active"); }); }); test("显式管理员不依赖员工档案", async () => { const stub = createModelStub([{ role: "attendant" }]); await withModel("Employee", stub, async () => { const admin = await resolveEscortAdminRole({ _id: OWNER_ID, app: { "wxapp_companion": { role: ["admin"] } }, }); assert.equal(admin, "admin"); assert.equal(stub.calls.length, 0); }); }); test("普通管理端账号无员工档案时拒绝", async () => { const stub = createModelStub([]); await withModel("Employee", stub, async () => { const outsider = await resolveEscortAdminRole({ _id: OWNER_ID, app: { "wxapp_companion": { role: ["user"] } }, }); assert.equal(outsider, null); }); }); test("历史管理员 role 缺失仍按管理员放行", async () => { const stub = createModelStub([]); await withModel("Employee", stub, async () => { const legacy = await resolveEscortAdminRole({ _id: OWNER_ID, app: { "wxapp_companion": { wxopenid: "o123" } }, }); assert.equal(legacy, "admin"); }); }); test("管理端订单工具拒绝组合状态更新前不会关闭在途支付", async () => { const previousClose = HandlerPayment.closeOpenPayRecords; let closeCalls = 0; HandlerPayment.closeOpenPayRecords = async () => { closeCalls += 1; return { closed: 0, paid: 0, unconfirmed: 0 }; }; const record = { _id: OWNER_ID, status: "confirmed", cancelStatus: "none", payment: { status: "unpaid", totalFee: 500, paidFee: 0 }, }; try { await withModel("EscortRecord", { findById: async () => record }, async () => { const result = parseResult(await escortRecordSetTool.invoke({ orderId: OWNER_ID, status: "in_progress", cancelStatus: "cancelled", })); assert.equal(result.success, false); assert.match(result.error, /Do not update service status and cancel status/); assert.equal(closeCalls, 0); }); } finally { HandlerPayment.closeOpenPayRecords = previousClose; } });