From f3a1ef89bc3d751aded42860dbc1521a4627a5ef Mon Sep 17 00:00:00 2001 From: lik Date: Sun, 1 Nov 2026 11:42:27 +0800 Subject: [PATCH] =?UTF-8?q?feat(tools):=20=E6=95=B0=E6=8D=AE=E5=BA=93?= =?UTF-8?q?=E6=9F=A5=E8=AF=A2=E6=8C=89=E6=9D=83=E9=99=90=E6=8B=86=E5=88=86?= =?UTF-8?q?=E4=B8=BA=20user/admin=EF=BC=8C=E5=BC=BA=E5=88=B6=20userId=20?= =?UTF-8?q?=E9=9A=94=E7=A6=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - query/ 为内部实现,user/ 仅供 bot-escort(绑定登录用户、schema 不暴露 userId),admin/ 仅供 escort-admin(显式跨用户) - 新增 employee、employee_review 查询;health_profile 用户端补齐 userId 隔离,按 _id 精确查询也带归属条件 - organization 是公共数据且无 userId,不进用户端;机构与写入工具统一移入 admin/ - utils 增加严格 ObjectId 解析,避免 CastError 与畸形 ID 进入查询 - 用户端员工视图剔除手机号、证件号、证书编号、紧急联系人与内部备注 - 新增 test/db_tools.test.js,用模型桩断言查询条件确实带 userId --- agent/infra/tools/db/admin/employee_query.js | 10 + .../tools/db/admin/employee_review_query.js | 10 + .../tools/db/admin/escort_record_query.js | 11 + .../tools/db/{ => admin}/escort_record_set.js | 4 +- .../tools/db/admin/health_profile_query.js | 10 + .../db/{ => admin}/health_profile_set.js | 4 +- .../db/{ => admin}/hospital_info_list.js | 4 +- .../db/{ => admin}/hospital_info_query.js | 4 +- .../tools/db/{ => admin}/hospital_info_set.js | 4 +- agent/infra/tools/db/escort_record_query.js | 104 -------- agent/infra/tools/db/health_profile_query.js | 85 ------ agent/infra/tools/db/query/employee_query.js | 243 ++++++++++++++++++ .../tools/db/query/employee_review_query.js | 137 ++++++++++ .../tools/db/query/escort_record_query.js | 155 +++++++++++ .../tools/db/query/health_profile_query.js | 117 +++++++++ agent/infra/tools/db/user/employee_query.js | 12 + .../tools/db/user/employee_review_query.js | 12 + .../tools/db/user/escort_record_query.js | 12 + .../tools/db/user/health_profile_query.js | 12 + agent/infra/tools/db/utils.js | 20 +- agent/infra/tools/index.js | 25 +- test/db_tools.test.js | 243 ++++++++++++++++++ 22 files changed, 1031 insertions(+), 207 deletions(-) create mode 100644 agent/infra/tools/db/admin/employee_query.js create mode 100644 agent/infra/tools/db/admin/employee_review_query.js create mode 100644 agent/infra/tools/db/admin/escort_record_query.js rename agent/infra/tools/db/{ => admin}/escort_record_set.js (96%) create mode 100644 agent/infra/tools/db/admin/health_profile_query.js rename agent/infra/tools/db/{ => admin}/health_profile_set.js (97%) rename agent/infra/tools/db/{ => admin}/hospital_info_list.js (92%) rename agent/infra/tools/db/{ => admin}/hospital_info_query.js (97%) rename agent/infra/tools/db/{ => admin}/hospital_info_set.js (98%) delete mode 100644 agent/infra/tools/db/escort_record_query.js delete mode 100644 agent/infra/tools/db/health_profile_query.js create mode 100644 agent/infra/tools/db/query/employee_query.js create mode 100644 agent/infra/tools/db/query/employee_review_query.js create mode 100644 agent/infra/tools/db/query/escort_record_query.js create mode 100644 agent/infra/tools/db/query/health_profile_query.js create mode 100644 agent/infra/tools/db/user/employee_query.js create mode 100644 agent/infra/tools/db/user/employee_review_query.js create mode 100644 agent/infra/tools/db/user/escort_record_query.js create mode 100644 agent/infra/tools/db/user/health_profile_query.js create mode 100644 test/db_tools.test.js diff --git a/agent/infra/tools/db/admin/employee_query.js b/agent/infra/tools/db/admin/employee_query.js new file mode 100644 index 0000000..72c1fa6 --- /dev/null +++ b/agent/infra/tools/db/admin/employee_query.js @@ -0,0 +1,10 @@ +import { buildEmployeeQueryTool } from "../query/employee_query.js"; + +/** + * 管理端员工查询工具 + * + * 管理端身份已在接入层校验;工具开放跨用户查询、userId 筛选和完整员工档案。 + */ +const employeeQueryTool = buildEmployeeQueryTool({ allowCrossUser: true }); + +export { employeeQueryTool }; diff --git a/agent/infra/tools/db/admin/employee_review_query.js b/agent/infra/tools/db/admin/employee_review_query.js new file mode 100644 index 0000000..ab68199 --- /dev/null +++ b/agent/infra/tools/db/admin/employee_review_query.js @@ -0,0 +1,10 @@ +import { buildEmployeeReviewQueryTool } from "../query/employee_review_query.js"; + +/** + * 管理端员工评价查询工具 + * + * 管理端身份已在接入层校验;工具开放跨用户查询与评价人 userId 筛选。 + */ +const employeeReviewQueryTool = buildEmployeeReviewQueryTool({ allowCrossUser: true }); + +export { employeeReviewQueryTool }; diff --git a/agent/infra/tools/db/admin/escort_record_query.js b/agent/infra/tools/db/admin/escort_record_query.js new file mode 100644 index 0000000..a607acd --- /dev/null +++ b/agent/infra/tools/db/admin/escort_record_query.js @@ -0,0 +1,11 @@ +import { buildEscortRecordQueryTool } from "../query/escort_record_query.js"; + +/** + * 管理端陪诊记录查询工具 + * + * 管理端身份已在接入层校验;工具开放跨用户查询, + * 并支持手机号、陪诊员 ID、排期日期范围等管理筛选。 + */ +const escortRecordQueryTool = buildEscortRecordQueryTool({ allowMobile: true }); + +export { escortRecordQueryTool }; diff --git a/agent/infra/tools/db/escort_record_set.js b/agent/infra/tools/db/admin/escort_record_set.js similarity index 96% rename from agent/infra/tools/db/escort_record_set.js rename to agent/infra/tools/db/admin/escort_record_set.js index c987fb8..189af8b 100644 --- a/agent/infra/tools/db/escort_record_set.js +++ b/agent/infra/tools/db/admin/escort_record_set.js @@ -1,8 +1,8 @@ import { tool } from "@langchain/core/tools"; import { z } from "zod"; import mongoose from "mongoose"; -import { DBModel } from "../../../../models/index.js"; -import { canTransition, STATUS_TRANSITIONS } from "../../../../utils/record_state.js"; +import { DBModel } from "../../../../../models/index.js"; +import { canTransition, STATUS_TRANSITIONS } from "../../../../../utils/record_state.js"; const escortRecordSetTool = tool( async ({ orderId, status, notes, payment }) => { diff --git a/agent/infra/tools/db/admin/health_profile_query.js b/agent/infra/tools/db/admin/health_profile_query.js new file mode 100644 index 0000000..0816649 --- /dev/null +++ b/agent/infra/tools/db/admin/health_profile_query.js @@ -0,0 +1,10 @@ +import { buildHealthProfileQueryTool } from "../query/health_profile_query.js"; + +/** + * 管理端健康档案查询工具 + * + * 管理端身份已在接入层校验;工具开放跨用户查询与 userId 筛选。 + */ +const healthProfileQueryTool = buildHealthProfileQueryTool({ allowCrossUser: true }); + +export { healthProfileQueryTool }; diff --git a/agent/infra/tools/db/health_profile_set.js b/agent/infra/tools/db/admin/health_profile_set.js similarity index 97% rename from agent/infra/tools/db/health_profile_set.js rename to agent/infra/tools/db/admin/health_profile_set.js index 2843e12..9dc2644 100644 --- a/agent/infra/tools/db/health_profile_set.js +++ b/agent/infra/tools/db/admin/health_profile_set.js @@ -1,8 +1,8 @@ import { tool } from "@langchain/core/tools"; import { z } from "zod"; import mongoose from "mongoose"; -import { DBModel } from "../../../../models/index.js"; -import { genPinyin, genPinyinFL } from "../../../../models/schema/health_profile.js"; +import { DBModel } from "../../../../../models/index.js"; +import { genPinyin, genPinyinFL } from "../../../../../models/schema/health_profile.js"; const PROFILE_KEYS = ["name", "mobile", "sex", "birth", "idnumber"]; const LOCATION_KEYS = ["country", "province", "city", "district", "address"]; diff --git a/agent/infra/tools/db/hospital_info_list.js b/agent/infra/tools/db/admin/hospital_info_list.js similarity index 92% rename from agent/infra/tools/db/hospital_info_list.js rename to agent/infra/tools/db/admin/hospital_info_list.js index 1e8965b..59af4bd 100644 --- a/agent/infra/tools/db/hospital_info_list.js +++ b/agent/infra/tools/db/admin/hospital_info_list.js @@ -1,7 +1,7 @@ import { tool } from "@langchain/core/tools"; import { z } from "zod"; -import { DBModel } from "../../../../models/index.js"; -import { escapeRegex } from "./utils.js"; +import { DBModel } from "../../../../../models/index.js"; +import { escapeRegex } from "../utils.js"; const hospitalInfoListTool = tool( async ({ keyword }) => { diff --git a/agent/infra/tools/db/hospital_info_query.js b/agent/infra/tools/db/admin/hospital_info_query.js similarity index 97% rename from agent/infra/tools/db/hospital_info_query.js rename to agent/infra/tools/db/admin/hospital_info_query.js index 3eb673d..1cff4ab 100644 --- a/agent/infra/tools/db/hospital_info_query.js +++ b/agent/infra/tools/db/admin/hospital_info_query.js @@ -1,8 +1,8 @@ import { tool } from "@langchain/core/tools"; import { z } from "zod"; import mongoose from "mongoose"; -import { DBModel } from "../../../../models/index.js"; -import { escapeRegex } from "./utils.js"; +import { DBModel } from "../../../../../models/index.js"; +import { escapeRegex } from "../utils.js"; /** * 医院信息查询工具 diff --git a/agent/infra/tools/db/hospital_info_set.js b/agent/infra/tools/db/admin/hospital_info_set.js similarity index 98% rename from agent/infra/tools/db/hospital_info_set.js rename to agent/infra/tools/db/admin/hospital_info_set.js index 14ef918..fa068ec 100644 --- a/agent/infra/tools/db/hospital_info_set.js +++ b/agent/infra/tools/db/admin/hospital_info_set.js @@ -1,7 +1,7 @@ import { tool } from "@langchain/core/tools"; import { z } from "zod"; -import { DBModel } from "../../../../models/index.js"; -import { escapeRegex } from "./utils.js"; +import { DBModel } from "../../../../../models/index.js"; +import { escapeRegex } from "../utils.js"; const hospitalInfoSetTool = tool( async ({ hospitalName, section, action, content, guides, entry, entryName, updatedBy }) => { diff --git a/agent/infra/tools/db/escort_record_query.js b/agent/infra/tools/db/escort_record_query.js deleted file mode 100644 index 1ce59af..0000000 --- a/agent/infra/tools/db/escort_record_query.js +++ /dev/null @@ -1,104 +0,0 @@ -import { tool } from "@langchain/core/tools"; -import { z } from "zod"; -import { DBModel } from "../../../../models/index.js"; -import { escapeRegex } from "./utils.js"; - -const STATUS_VALUES = ["pending", "confirmed", "in_progress", "completed", "cancelled"]; -const STATUS_DESC = - "Appointment status: pending (待确认), confirmed (已确认), in_progress (进行中), completed (已完成), cancelled (已取消)"; - -/** - * 陪诊记录查询工具 - * - * 用户端与管理端共用同一套查询实现,差异只有两处: - * - 用户端强制按 userId 隔离,且不暴露手机号筛选; - * - 管理端可跨用户查询,并支持按患者手机号精确筛选。 - * 两端不会出现在同一个 Agent 中,因此可以共用工具名 escort_record_query。 - */ -function buildEscortRecordQueryTool({ userId = null, allowMobile = false } = {}) { - const shape = { - patientName: z.string().optional().describe("Patient name for fuzzy search"), - status: z.enum(STATUS_VALUES).optional().describe(STATUS_DESC), - page: z.number().int().min(1).optional().describe("Page number, starting from 1"), - pageSize: z - .number() - .int() - .min(1) - .max(50) - .optional() - .describe("Records per page (1-50), default 20"), - }; - - if (allowMobile) { - shape.mobile = z.string().optional().describe("Patient mobile phone number for exact match"); - } - - return tool( - async ({ patientName, mobile, status, page = 1, pageSize = 20 }) => { - try { - if (!userId && !allowMobile) { - return { success: false, error: "用户未登录,无法查询陪诊记录" }; - } - - const filter = { deletedAt: null }; - - if (patientName) { - filter["patient.name"] = { $regex: escapeRegex(patientName), $options: "i" }; - } - - if (allowMobile && mobile) { - filter["patient.mobile"] = mobile; - } - - if (status) { - filter.status = status; - } - - // 用户端按订单归属过滤;不能用手机号作为隔离键(手机号可由用户自行修改) - if (userId) { - filter.userId = userId; - } - - const skip = (page - 1) * pageSize; - - const [records, total] = await Promise.all([ - DBModel.EscortRecord.find(filter) - .sort({ "schedule.date": -1 }) - .skip(skip) - .limit(pageSize) - .lean(), - DBModel.EscortRecord.countDocuments(filter), - ]); - - return { - success: true, - data: records, - total, - page, - pageSize, - }; - } catch (error) { - return { - success: false, - error: error.message, - }; - } - }, - { - name: "escort_record_query", - description: allowMobile - ? "Query all escort records (admin scope). Supports filtering by patient name, mobile phone number, and appointment status. Returns paginated results sorted by appointment date in descending order." - : "Query escort records of the current logged-in user. Supports filtering by patient name and appointment status. Returns paginated results sorted by appointment date in descending order. The query is automatically scoped to the current user.", - schema: z.object(shape), - } - ); -} - -/** 用户端:按当前登录用户隔离 */ -const createEscortRecordQueryTool = (userInfo) => - buildEscortRecordQueryTool({ userId: userInfo?._id }); - -/** 管理端:跨用户查询,支持手机号 */ -const escortRecordQueryTool = buildEscortRecordQueryTool({ allowMobile: true }); - -export { createEscortRecordQueryTool, escortRecordQueryTool }; diff --git a/agent/infra/tools/db/health_profile_query.js b/agent/infra/tools/db/health_profile_query.js deleted file mode 100644 index 347da7d..0000000 --- a/agent/infra/tools/db/health_profile_query.js +++ /dev/null @@ -1,85 +0,0 @@ -import { tool } from "@langchain/core/tools"; -import { z } from "zod"; -import mongoose from "mongoose"; -import { DBModel } from "../../../../models/index.js"; -import { escapeRegex } from "./utils.js"; - -const healthProfileQueryTool = tool( - async ({ profileId, userId, name, mobile, page = 1, pageSize = 20 }) => { - try { - // 按档案 _id 精确查询单条 - if (profileId) { - if (!mongoose.Types.ObjectId.isValid(profileId)) { - return { success: false, error: `Invalid profile ID: ${profileId}` }; - } - const doc = await DBModel.HealthProfile.findById(profileId).lean(); - if (!doc) { - return { success: false, error: `未找到 ID 为 ${profileId} 的健康档案` }; - } - return { success: true, data: [doc], total: 1 }; - } - - const filter = {}; - - if (userId) { - if (!mongoose.Types.ObjectId.isValid(userId)) { - return { success: false, error: `Invalid user ID: ${userId}` }; - } - filter.userId = new mongoose.Types.ObjectId(userId); - } - if (name) { - // 转义正则特殊字符,避免查询报错或 ReDoS;姓名支持中文、全拼、拼音首字母匹配 - const re = { $regex: escapeRegex(name), $options: "i" }; - filter.$or = [{ "profile.name": re }, { "profile.pinyin": re }, { "profile.pinyinFL": re }]; - } - if (mobile) { - filter["profile.mobile"] = mobile; - } - - const skip = (page - 1) * pageSize; - - const [list, total] = await Promise.all([ - DBModel.HealthProfile.find(filter) - .sort({ "meta.createtime": -1 }) - .skip(skip) - .limit(pageSize) - .lean(), - DBModel.HealthProfile.countDocuments(filter), - ]); - - return { - success: true, - data: list, - total, - page, - pageSize, - }; - } catch (error) { - return { success: false, error: error.message }; - } - }, - { - name: "health_profile_query", - description: - "查询患者健康档案。支持按档案 ID 精确查询,或按用户 ID、患者姓名(模糊)、患者电话筛选,返回分页结果。", - schema: z.object({ - profileId: z - .string() - .optional() - .describe("健康档案 ID(_id),提供时精确查询单条,忽略其他筛选条件"), - userId: z.string().optional().describe("所属用户ID(精确匹配)"), - name: z.string().optional().describe("患者姓名(支持中文模糊、全拼、拼音首字母匹配,如 张三/zhangsan/zs)"), - mobile: z.string().optional().describe("患者电话(精确匹配)"), - page: z.number().int().min(1).optional().describe("页码,从 1 开始"), - pageSize: z - .number() - .int() - .min(1) - .max(50) - .optional() - .describe("每页数量(1-50),默认 20"), - }), - } -); - -export { healthProfileQueryTool }; diff --git a/agent/infra/tools/db/query/employee_query.js b/agent/infra/tools/db/query/employee_query.js new file mode 100644 index 0000000..ba5c657 --- /dev/null +++ b/agent/infra/tools/db/query/employee_query.js @@ -0,0 +1,243 @@ +import { tool } from "@langchain/core/tools"; +import { z } from "zod"; +import { DBModel } from "../../../../../models/index.js"; +import { escapeRegex, parseObjectId } from "../utils.js"; + +const ROLE_VALUES = ["attendant", "nurse", "doctor", "admin", "operator", "other"]; +const ROLE_DESC = + "Employee role: attendant (陪诊员), nurse (护士), doctor (医生), admin (管理员), operator (运营), other (其他)"; +const STATUS_VALUES = ["active", "inactive", "resigned", "suspended"]; +const STATUS_DESC = "Employee status: active (在职), inactive (停用), resigned (离职), suspended (暂停)"; + +// 管理端白名单:只取 schema 已定义字段,避免未来新增/遗留字段被整文档带出 +const ADMIN_EMPLOYEE_FIELDS = [ + "employeeNo", "userId", "orgId", "role", + "profile", "work", "attendantInfo", "emergencyContact", + "status", "introduction", "remark", "meta", +].join(" "); + +// 用户端本人白名单:不返回身份证、手机号、邮箱、紧急联系人、证书编号等敏感信息 +const SELF_EMPLOYEE_FIELDS = [ + "employeeNo", "role", "orgId", "status", + "profile.name", "profile.sex", "profile.birthday", "profile.avatar", + "work.department", "work.title", "work.entryDate", "work.workYears", + "work.qualification", + "work.healthCertificate.issueDate", "work.healthCertificate.expireDate", + "work.trainings.title", "work.trainings.org", "work.trainings.date", + "attendantInfo.serviceAreas", "attendantInfo.specialties", "attendantInfo.languages", + "attendantInfo.orderCount", "attendantInfo.isOnline", + "introduction", "meta.createtime", "meta.updatetime", +].join(" "); + +/** + * 用户端本人视图:显式字段挑选,避免 employee 文档内的敏感字段随查询泄漏 + */ +function toSelfEmployee(employee) { + const profile = employee.profile ?? {}; + const work = employee.work ?? {}; + const info = employee.attendantInfo ?? {}; + const healthCertificate = work.healthCertificate ?? {}; + + return { + _id: employee._id, + employeeNo: employee.employeeNo ?? "", + role: employee.role ?? "", + status: employee.status ?? "", + orgId: employee.orgId ?? null, + profile: { + name: profile.name ?? "", + sex: profile.sex ?? "", + birthday: profile.birthday ?? null, + avatar: profile.avatar ?? "", + }, + work: { + department: work.department ?? "", + title: work.title ?? "", + entryDate: work.entryDate ?? null, + workYears: work.workYears ?? 0, + // 证书编号不外泄,只告诉是否已核验 + qualificationVerified: Boolean(work.qualification), + healthCertificate: { + issueDate: healthCertificate.issueDate ?? null, + expireDate: healthCertificate.expireDate ?? null, + }, + trainings: Array.isArray(work.trainings) + ? work.trainings.map((item) => ({ + title: item.title ?? "", + org: item.org ?? "", + date: item.date ?? null, + })) + : [], + }, + attendantInfo: { + serviceAreas: info.serviceAreas ?? [], + specialties: info.specialties ?? [], + languages: info.languages ?? [], + orderCount: info.orderCount ?? 0, + isOnline: Boolean(info.isOnline), + }, + introduction: employee.introduction ?? "", + meta: { + createtime: employee.meta?.createtime ?? null, + updatetime: employee.meta?.updatetime ?? null, + }, + }; +} + +/** + * 员工信息查询内部实现 + * + * 仅供 db/user 与 db/admin 下的工具包装使用,不直接暴露给 Agent: + * - 用户端包装只传 userId,强制按当前登录用户隔离,并只输出非敏感字段; + * - 管理端包装传 allowCrossUser,才允许跨用户查询完整员工档案。 + */ +function buildEmployeeQueryTool({ userId = null, allowCrossUser = false } = {}) { + const boundUserId = allowCrossUser ? null : parseObjectId(userId); + + const shape = { + page: z.number().int().min(1).optional().describe("Page number, starting from 1"), + pageSize: z + .number() + .int() + .min(1) + .max(50) + .optional() + .describe("Records per page (1-50), default 20"), + }; + + if (allowCrossUser) { + shape.employeeId = z + .string() + .optional() + .describe("Employee ID (_id) for exact lookup; when provided, other filters are ignored"); + shape.keyword = z + .string() + .optional() + .describe("Fuzzy keyword matching name, pinyin, employee number or phone (e.g. 张三/zhangsan/zs/E001)"); + shape.name = z + .string() + .optional() + .describe("Employee name for fuzzy match (supports Chinese, full pinyin and pinyin initials)"); + shape.employeeNo = z.string().optional().describe("Employee number for exact match"); + shape.role = z.enum(ROLE_VALUES).optional().describe(ROLE_DESC); + shape.status = z.enum(STATUS_VALUES).optional().describe(STATUS_DESC); + shape.orgId = z.string().optional().describe("Organization ID (_id) for exact match"); + shape.userId = z.string().optional().describe("Linked login user ID for exact match"); + } + + return tool( + async ({ employeeId, keyword, name, employeeNo, role, status, orgId, userId: queryUserId, page = 1, pageSize = 20 }) => { + try { + if (!allowCrossUser && !boundUserId) { + return { success: false, error: "用户未登录,无法查询员工信息" }; + } + + // 用户端强制归属过滤,所有分支(含按 ID 精确查询)都带 userId + const scope = boundUserId ? { userId: boundUserId } : {}; + const projection = allowCrossUser ? ADMIN_EMPLOYEE_FIELDS : SELF_EMPLOYEE_FIELDS; + + if (allowCrossUser && employeeId) { + const employeeObjectId = parseObjectId(employeeId); + if (!employeeObjectId) { + return { success: false, error: `Invalid employee ID: ${employeeId}` }; + } + const doc = await DBModel.Employee.findOne({ _id: employeeObjectId }) + .select(projection) + .lean(); + if (!doc) { + return { success: false, error: `No employee found for ID: ${employeeId}` }; + } + return { success: true, data: [doc], total: 1, page: 1, pageSize: 1 }; + } + + const filter = { ...scope }; + + if (allowCrossUser && queryUserId) { + const ownerId = parseObjectId(queryUserId); + if (!ownerId) { + return { success: false, error: `Invalid user ID: ${queryUserId}` }; + } + filter.userId = ownerId; + } + if (allowCrossUser && orgId) { + const organizationId = parseObjectId(orgId); + if (!organizationId) { + return { success: false, error: `Invalid organization ID: ${orgId}` }; + } + filter.orgId = organizationId; + } + if (allowCrossUser && employeeNo) { + filter.employeeNo = employeeNo; + } + // 姓名/工号/手机号既可用 keyword 一起搜,也可用 name 单独模糊匹配 + const orGroups = []; + if (allowCrossUser && keyword) { + // 转义正则特殊字符,避免查询报错或 ReDoS + const re = { $regex: escapeRegex(keyword), $options: "i" }; + orGroups.push({ + $or: [ + { "profile.name": re }, + { "profile.pinyin": re }, + { "profile.pinyinFL": re }, + { employeeNo: re }, + { "profile.phone": re }, + ], + }); + } + if (allowCrossUser && name) { + const re = { $regex: escapeRegex(name), $options: "i" }; + orGroups.push({ + $or: [ + { "profile.name": re }, + { "profile.pinyin": re }, + { "profile.pinyinFL": re }, + ], + }); + } + if (orGroups.length === 1) { + Object.assign(filter, orGroups[0]); + } else if (orGroups.length > 1) { + filter.$and = orGroups; + } + if (allowCrossUser && role) { + filter.role = role; + } + if (allowCrossUser && status) { + filter.status = status; + } + + const skip = (page - 1) * pageSize; + + const [docs, total] = await Promise.all([ + DBModel.Employee.find(filter) + .select(projection) + .sort({ "meta.createtime": -1 }) + .skip(skip) + .limit(pageSize) + .lean(), + DBModel.Employee.countDocuments(filter), + ]); + + return { + success: true, + data: allowCrossUser ? docs : docs.map(toSelfEmployee), + total, + page, + pageSize, + }; + } catch (error) { + return { success: false, error: error.message }; + } + }, + { + name: "employee_query", + description: allowCrossUser + ? "Query employee records across all users (admin scope). Supports exact employee ID lookup, or filters by keyword (name/pinyin/employee number/phone), name, employee number, role, status, organization ID and linked user ID. Returns paginated full employee profiles, including sensitive fields such as phone and ID number; use only when necessary." + : "Query the current logged-in user's own employee record. The query is automatically scoped to the current user ID and only returns the user's own non-sensitive profile fields (contact details, ID number, emergency contact and certificate numbers are excluded).", + schema: z.object(shape), + } + ); +} + +/** 内部实现:由 db/user 与 db/admin 包装后暴露给对应 Agent */ +export { buildEmployeeQueryTool, toSelfEmployee }; diff --git a/agent/infra/tools/db/query/employee_review_query.js b/agent/infra/tools/db/query/employee_review_query.js new file mode 100644 index 0000000..780e276 --- /dev/null +++ b/agent/infra/tools/db/query/employee_review_query.js @@ -0,0 +1,137 @@ +import { tool } from "@langchain/core/tools"; +import { z } from "zod"; +import { DBModel } from "../../../../../models/index.js"; +import { parseObjectId } from "../utils.js"; + +const STATUS_VALUES = ["published", "hidden"]; +const STATUS_DESC = "Review status: published (已发布,计入评分), hidden (已隐藏,不计入评分)"; + +// 白名单投影:只返回 schema 已定义字段,避免未来新增字段被整文档带出 +const REVIEW_FIELDS = "recordId employeeId userId score content status meta"; + +/** + * 员工评价查询内部实现 + * + * 仅供 db/user 与 db/admin 下的工具包装使用,不直接暴露给 Agent: + * - 用户端包装只传 userId,强制按评价人隔离,只返回当前登录用户自己提交的评价; + * - 管理端包装传 allowCrossUser,才允许跨用户查询。 + */ +function buildEmployeeReviewQueryTool({ userId = null, allowCrossUser = false } = {}) { + const boundUserId = allowCrossUser ? null : parseObjectId(userId); + + const shape = { + reviewId: z + .string() + .optional() + .describe("Review ID (_id) for exact lookup; when provided, other filters are ignored"), + employeeId: z.string().optional().describe("Reviewed employee ID (_id) for exact match"), + recordId: z.string().optional().describe("Related escort record ID (_id) for exact match"), + score: z.number().int().min(1).max(5).optional().describe("Rating score (1-5)"), + status: z.enum(STATUS_VALUES).optional().describe(STATUS_DESC), + page: z.number().int().min(1).optional().describe("Page number, starting from 1"), + pageSize: z + .number() + .int() + .min(1) + .max(50) + .optional() + .describe("Records per page (1-50), default 20"), + }; + + if (allowCrossUser) { + shape.userId = z.string().optional().describe("Reviewer user ID (_id) for exact match"); + } + + return tool( + async ({ reviewId, employeeId, recordId, userId: queryUserId, score, status, page = 1, pageSize = 20 }) => { + try { + if (!allowCrossUser && !boundUserId) { + return { success: false, error: "用户未登录,无法查询员工评价" }; + } + + // 用户端强制评价人归属;按评价 ID 精确查询时同样并入该条件 + const scope = boundUserId ? { userId: boundUserId } : {}; + + if (reviewId) { + const reviewObjectId = parseObjectId(reviewId); + if (!reviewObjectId) { + return { success: false, error: `Invalid review ID: ${reviewId}` }; + } + const doc = await DBModel.EmployeeReview.findOne({ _id: reviewObjectId, ...scope }) + .select(REVIEW_FIELDS) + .lean(); + if (!doc) { + // 用户端不区分「不存在」与「不属于本人」,避免凭 ID 探测他人评价 + return { + success: false, + error: allowCrossUser ? `No review found for ID: ${reviewId}` : "未找到对应的员工评价", + }; + } + return { success: true, data: [doc], total: 1, page: 1, pageSize: 1 }; + } + + const filter = { ...scope }; + + if (allowCrossUser && queryUserId) { + const reviewerId = parseObjectId(queryUserId); + if (!reviewerId) { + return { success: false, error: `Invalid user ID: ${queryUserId}` }; + } + filter.userId = reviewerId; + } + if (employeeId) { + const employeeObjectId = parseObjectId(employeeId); + if (!employeeObjectId) { + return { success: false, error: `Invalid employee ID: ${employeeId}` }; + } + filter.employeeId = employeeObjectId; + } + if (recordId) { + const recordObjectId = parseObjectId(recordId); + if (!recordObjectId) { + return { success: false, error: `Invalid record ID: ${recordId}` }; + } + filter.recordId = recordObjectId; + } + if (score !== undefined) { + filter.score = score; + } + if (status) { + filter.status = status; + } + + const skip = (page - 1) * pageSize; + + const [list, total] = await Promise.all([ + DBModel.EmployeeReview.find(filter) + .select(REVIEW_FIELDS) + .sort({ "meta.createtime": -1 }) + .skip(skip) + .limit(pageSize) + .lean(), + DBModel.EmployeeReview.countDocuments(filter), + ]); + + return { + success: true, + data: list, + total, + page, + pageSize, + }; + } catch (error) { + return { success: false, error: error.message }; + } + }, + { + name: "employee_review_query", + description: allowCrossUser + ? "Query employee reviews across all users (admin scope). Supports exact review ID lookup, or filters by employee ID, escort record ID, reviewer user ID, score and status. Returns paginated results sorted by creation time in descending order." + : "Query employee reviews submitted by the current logged-in user. The query is automatically scoped to the current user ID and never returns reviews submitted by other users. Supports filtering by employee ID, escort record ID, score and status.", + schema: z.object(shape), + } + ); +} + +/** 内部实现:由 db/user 与 db/admin 包装后暴露给对应 Agent */ +export { buildEmployeeReviewQueryTool }; diff --git a/agent/infra/tools/db/query/escort_record_query.js b/agent/infra/tools/db/query/escort_record_query.js new file mode 100644 index 0000000..3d30922 --- /dev/null +++ b/agent/infra/tools/db/query/escort_record_query.js @@ -0,0 +1,155 @@ +import { tool } from "@langchain/core/tools"; +import { z } from "zod"; +import { DBModel } from "../../../../../models/index.js"; +import { escapeRegex, parseObjectId } from "../utils.js"; + +const STATUS_VALUES = ["pending", "confirmed", "in_progress", "completed", "cancelled"]; +const STATUS_DESC = + "Appointment status: pending (待确认), confirmed (已确认), in_progress (进行中), completed (已完成), cancelled (已取消)"; + +/** + * 严格解析 YYYY-MM-DD(东八区零点) + * Date 会把 2026-02-30 静默进位成 3 月 2 日,这里回算一次日期,拒绝非法日期 + */ +function parseDay(value) { + if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return null; + const [year, month, day] = value.split("-").map(Number); + const check = new Date(Date.UTC(year, month - 1, day)); + if ( + check.getUTCFullYear() !== year || + check.getUTCMonth() !== month - 1 || + check.getUTCDate() !== day + ) { + return null; + } + return new Date(`${value}T00:00:00+08:00`); +} + +/** + * 陪诊记录查询内部实现 + * + * 仅供 db/user 与 db/admin 下的工具包装使用,不直接暴露给 Agent: + * - 用户端包装只传 userId,强制按当前登录用户隔离; + * - 管理端包装传 allowMobile,才开放跨用户查询与手机号/陪诊员/日期筛选。 + */ +function buildEscortRecordQueryTool({ userId = null, allowMobile = false } = {}) { + const shape = { + patientName: z.string().optional().describe("Patient name for fuzzy search"), + status: z.enum(STATUS_VALUES).optional().describe(STATUS_DESC), + page: z.number().int().min(1).optional().describe("Page number, starting from 1"), + pageSize: z + .number() + .int() + .min(1) + .max(50) + .optional() + .describe("Records per page (1-50), default 20"), + }; + + if (allowMobile) { + shape.mobile = z.string().optional().describe("Patient mobile phone number for exact match"); + shape.attendantId = z + .string() + .optional() + .describe("Attendant (escort staff) user ID (_id) for exact match"); + shape.dateFrom = z + .string() + .optional() + .describe("Schedule date range start, inclusive, format YYYY-MM-DD"); + shape.dateTo = z + .string() + .optional() + .describe("Schedule date range end, inclusive, format YYYY-MM-DD"); + } + + return tool( + async ({ patientName, mobile, attendantId, dateFrom, dateTo, status, page = 1, pageSize = 20 }) => { + try { + if (!userId && !allowMobile) { + return { success: false, error: "用户未登录,无法查询陪诊记录" }; + } + + const filter = { deletedAt: null }; + + if (patientName) { + filter["patient.name"] = { $regex: escapeRegex(patientName), $options: "i" }; + } + + if (allowMobile && mobile) { + filter["patient.mobile"] = mobile; + } + + if (allowMobile && attendantId) { + const attendantObjectId = parseObjectId(attendantId); + if (!attendantObjectId) { + return { success: false, error: `Invalid attendant ID: ${attendantId}` }; + } + filter["attendant.id"] = attendantObjectId; + } + + // 日期按东八区自然日解释,dateTo 含当天 + if (allowMobile && (dateFrom || dateTo)) { + const range = {}; + if (dateFrom) { + const from = parseDay(dateFrom); + if (!from) { + return { success: false, error: `Invalid dateFrom: ${dateFrom}, expected YYYY-MM-DD` }; + } + range.$gte = from; + } + if (dateTo) { + const to = parseDay(dateTo); + if (!to) { + return { success: false, error: `Invalid dateTo: ${dateTo}, expected YYYY-MM-DD` }; + } + range.$lt = new Date(to.getTime() + 24 * 60 * 60 * 1000); + } + filter["schedule.date"] = range; + } + + if (status) { + filter.status = status; + } + + // 用户端按订单归属过滤;不能用手机号作为隔离键(手机号可由用户自行修改) + if (userId) { + filter.userId = userId; + } + + const skip = (page - 1) * pageSize; + + const [records, total] = await Promise.all([ + DBModel.EscortRecord.find(filter) + .sort({ "schedule.date": -1 }) + .skip(skip) + .limit(pageSize) + .lean(), + DBModel.EscortRecord.countDocuments(filter), + ]); + + return { + success: true, + data: records, + total, + page, + pageSize, + }; + } catch (error) { + return { + success: false, + error: error.message, + }; + } + }, + { + name: "escort_record_query", + description: allowMobile + ? "Query all escort records (admin scope). Supports filtering by patient name, mobile phone number, attendant ID, schedule date range (YYYY-MM-DD, inclusive), and appointment status. Returns paginated results sorted by appointment date in descending order." + : "Query escort records of the current logged-in user. Supports filtering by patient name and appointment status. Returns paginated results sorted by appointment date in descending order. The query is automatically scoped to the current user.", + schema: z.object(shape), + } + ); +} + +/** 内部实现:由 db/user 与 db/admin 包装后暴露给对应 Agent */ +export { buildEscortRecordQueryTool }; diff --git a/agent/infra/tools/db/query/health_profile_query.js b/agent/infra/tools/db/query/health_profile_query.js new file mode 100644 index 0000000..36c9a2e --- /dev/null +++ b/agent/infra/tools/db/query/health_profile_query.js @@ -0,0 +1,117 @@ +import { tool } from "@langchain/core/tools"; +import { z } from "zod"; +import { DBModel } from "../../../../../models/index.js"; +import { escapeRegex, parseObjectId } from "../utils.js"; + +/** + * 健康档案查询内部实现 + * + * 仅供 db/user 与 db/admin 下的工具包装使用,不直接暴露给 Agent: + * - 用户端包装只传 userId,强制按当前登录用户隔离,且不暴露 userId 筛选; + * - 管理端包装传 allowCrossUser,才允许跨用户查询。 + */ +function buildHealthProfileQueryTool({ userId = null, allowCrossUser = false } = {}) { + // 用户端只认调用方绑定的登录用户,管理端不绑定归属 + const boundUserId = allowCrossUser ? null : parseObjectId(userId); + + const shape = { + profileId: z + .string() + .optional() + .describe("健康档案 ID(_id),提供时精确查询单条,忽略其他筛选条件"), + name: z.string().optional().describe("患者姓名(支持中文模糊、全拼、拼音首字母匹配,如 张三/zhangsan/zs)"), + mobile: z.string().optional().describe("患者电话(精确匹配)"), + page: z.number().int().min(1).optional().describe("页码,从 1 开始"), + pageSize: z + .number() + .int() + .min(1) + .max(50) + .optional() + .describe("每页数量(1-50),默认 20"), + }; + + if (allowCrossUser) { + shape.userId = z.string().optional().describe("所属用户ID(精确匹配,仅管理端可用)"); + } + + return tool( + async ({ profileId, userId: queryUserId, name, mobile, page = 1, pageSize = 20 }) => { + try { + // 用户端未登录/身份异常时直接拒绝,绝不回落到跨用户查询 + if (!allowCrossUser && !boundUserId) { + return { success: false, error: "用户未登录,无法查询健康档案" }; + } + + // 用户端把归属条件强制并入所有查询(包括按档案 ID 精确查询) + const scope = boundUserId ? { userId: boundUserId } : {}; + + // 按档案 _id 精确查询单条 + if (profileId) { + const profileObjectId = parseObjectId(profileId); + if (!profileObjectId) { + return { success: false, error: `Invalid profile ID: ${profileId}` }; + } + const doc = await DBModel.HealthProfile.findOne({ _id: profileObjectId, ...scope }).lean(); + if (!doc) { + // 用户端不区分「不存在」与「不属于本人」,避免凭 ID 探测他人档案 + return { + success: false, + error: allowCrossUser ? `未找到 ID 为 ${profileId} 的健康档案` : "未找到对应的健康档案", + }; + } + return { success: true, data: [doc], total: 1, page: 1, pageSize: 1 }; + } + + const filter = { ...scope }; + + if (allowCrossUser && queryUserId) { + const ownerId = parseObjectId(queryUserId); + if (!ownerId) { + return { success: false, error: `Invalid user ID: ${queryUserId}` }; + } + filter.userId = ownerId; + } + if (name) { + // 转义正则特殊字符,避免查询报错或 ReDoS;姓名支持中文、全拼、拼音首字母匹配 + const re = { $regex: escapeRegex(name), $options: "i" }; + filter.$or = [{ "profile.name": re }, { "profile.pinyin": re }, { "profile.pinyinFL": re }]; + } + if (mobile) { + filter["profile.mobile"] = mobile; + } + + const skip = (page - 1) * pageSize; + + const [list, total] = await Promise.all([ + DBModel.HealthProfile.find(filter) + .sort({ "meta.createtime": -1 }) + .skip(skip) + .limit(pageSize) + .lean(), + DBModel.HealthProfile.countDocuments(filter), + ]); + + return { + success: true, + data: list, + total, + page, + pageSize, + }; + } catch (error) { + return { success: false, error: error.message }; + } + }, + { + name: "health_profile_query", + description: allowCrossUser + ? "查询患者健康档案(管理端)。支持按档案 ID 精确查询,或按用户 ID、患者姓名(模糊)、患者电话筛选,返回分页结果。" + : "查询当前登录用户本人的健康档案。支持按档案 ID 精确查询,或按患者姓名(模糊)、患者电话筛选,返回分页结果。查询自动限定为当前登录用户,不会返回他人档案。", + schema: z.object(shape), + } + ); +} + +/** 内部实现:由 db/user 与 db/admin 包装后暴露给对应 Agent */ +export { buildHealthProfileQueryTool }; diff --git a/agent/infra/tools/db/user/employee_query.js b/agent/infra/tools/db/user/employee_query.js new file mode 100644 index 0000000..9af9098 --- /dev/null +++ b/agent/infra/tools/db/user/employee_query.js @@ -0,0 +1,12 @@ +import { buildEmployeeQueryTool } from "../query/employee_query.js"; + +/** + * 用户端员工查询工具 + * + * 只传入当前登录用户的 userId,schema 不暴露 userId 参数; + * 查询强制按 userId 隔离,并只输出本人员工档案的非敏感字段。 + */ +const createEmployeeQueryTool = (userInfo) => + buildEmployeeQueryTool({ userId: userInfo?._id }); + +export { createEmployeeQueryTool }; diff --git a/agent/infra/tools/db/user/employee_review_query.js b/agent/infra/tools/db/user/employee_review_query.js new file mode 100644 index 0000000..1de16b0 --- /dev/null +++ b/agent/infra/tools/db/user/employee_review_query.js @@ -0,0 +1,12 @@ +import { buildEmployeeReviewQueryTool } from "../query/employee_review_query.js"; + +/** + * 用户端员工评价查询工具 + * + * 只传入当前登录用户的 userId,schema 不暴露 userId 参数; + * 查询强制按评价人 userId 隔离,只返回本人提交的评价。 + */ +const createEmployeeReviewQueryTool = (userInfo) => + buildEmployeeReviewQueryTool({ userId: userInfo?._id }); + +export { createEmployeeReviewQueryTool }; diff --git a/agent/infra/tools/db/user/escort_record_query.js b/agent/infra/tools/db/user/escort_record_query.js new file mode 100644 index 0000000..56a1a6c --- /dev/null +++ b/agent/infra/tools/db/user/escort_record_query.js @@ -0,0 +1,12 @@ +import { buildEscortRecordQueryTool } from "../query/escort_record_query.js"; + +/** + * 用户端陪诊记录查询工具 + * + * 只传入当前登录用户的 userId,不开放管理端的手机号/陪诊员/日期筛选。 + * 未登录或身份非法时,工具执行会直接拒绝,不会回落到跨用户查询。 + */ +const createEscortRecordQueryTool = (userInfo) => + buildEscortRecordQueryTool({ userId: userInfo?._id }); + +export { createEscortRecordQueryTool }; diff --git a/agent/infra/tools/db/user/health_profile_query.js b/agent/infra/tools/db/user/health_profile_query.js new file mode 100644 index 0000000..508737a --- /dev/null +++ b/agent/infra/tools/db/user/health_profile_query.js @@ -0,0 +1,12 @@ +import { buildHealthProfileQueryTool } from "../query/health_profile_query.js"; + +/** + * 用户端健康档案查询工具 + * + * 只传入当前登录用户的 userId,schema 不暴露 userId 参数; + * 未登录或身份非法时直接拒绝,不会回落到跨用户查询。 + */ +const createHealthProfileQueryTool = (userInfo) => + buildHealthProfileQueryTool({ userId: userInfo?._id }); + +export { createHealthProfileQueryTool }; diff --git a/agent/infra/tools/db/utils.js b/agent/infra/tools/db/utils.js index e3f5e85..31f183b 100644 --- a/agent/infra/tools/db/utils.js +++ b/agent/infra/tools/db/utils.js @@ -2,6 +2,8 @@ * 数据库工具的公共小工具 */ +import mongoose from "mongoose"; + /** * 转义正则元字符,用于把用户/模型输入当作字面量做模糊匹配 * @@ -19,4 +21,20 @@ function escapeRegex(input, maxLength = 64) { .replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } -export { escapeRegex }; +/** + * 严格解析 ObjectId + * + * 用固定 24 位十六进制格式校验,而不是 isValid(后者对部分非标准字符串也返回 true)。 + * 非法值返回 null,供工具提前返回错误,避免 Mongoose CastError 或把字符串直接带进查询。 + * + * @param {*} value 待解析的 ID + * @returns {mongoose.Types.ObjectId|null} + */ +function parseObjectId(value) { + if (value === null || value === undefined) return null; + const raw = typeof value === "string" ? value.trim() : String(value); + if (!/^[0-9a-fA-F]{24}$/.test(raw)) return null; + return new mongoose.Types.ObjectId(raw); +} + +export { escapeRegex, parseObjectId }; diff --git a/agent/infra/tools/index.js b/agent/infra/tools/index.js index d21b7a9..72fe264 100644 --- a/agent/infra/tools/index.js +++ b/agent/infra/tools/index.js @@ -9,10 +9,21 @@ export { getCalendarInfoTool } from './calendar/calendar_info.js'; export { getYearHolidaysTool } from './calendar/year_holidays.js'; // 数据库工具 -export { createEscortRecordQueryTool, escortRecordQueryTool } from './db/escort_record_query.js'; -export { escortRecordSetTool } from './db/escort_record_set.js'; -export { healthProfileQueryTool } from './db/health_profile_query.js'; -export { healthProfileSetTool } from './db/health_profile_set.js'; -export { hospitalInfoListTool } from './db/hospital_info_list.js'; -export { hospitalInfoQueryTool } from './db/hospital_info_query.js'; -export { hospitalInfoSetTool } from './db/hospital_info_set.js'; +// 用户端查询:只允许当前登录用户本人的数据(强制 userId 隔离) +export { createEscortRecordQueryTool } from './db/user/escort_record_query.js'; +export { createHealthProfileQueryTool } from './db/user/health_profile_query.js'; +export { createEmployeeQueryTool } from './db/user/employee_query.js'; +export { createEmployeeReviewQueryTool } from './db/user/employee_review_query.js'; + +// 管理端查询:仅注入 escort-admin,可跨用户查询 +export { escortRecordQueryTool } from './db/admin/escort_record_query.js'; +export { healthProfileQueryTool } from './db/admin/health_profile_query.js'; +export { employeeQueryTool } from './db/admin/employee_query.js'; +export { employeeReviewQueryTool } from './db/admin/employee_review_query.js'; + +// 管理端写入工具与机构(公共服务)工具 +export { escortRecordSetTool } from './db/admin/escort_record_set.js'; +export { healthProfileSetTool } from './db/admin/health_profile_set.js'; +export { hospitalInfoListTool } from './db/admin/hospital_info_list.js'; +export { hospitalInfoQueryTool } from './db/admin/hospital_info_query.js'; +export { hospitalInfoSetTool } from './db/admin/hospital_info_set.js'; diff --git a/test/db_tools.test.js b/test/db_tools.test.js new file mode 100644 index 0000000..91fa9f0 --- /dev/null +++ b/test/db_tools.test.js @@ -0,0 +1,243 @@ +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"; + +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; + }); +} + +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); + }); +});