feat(tools): 数据库查询按权限拆分为 user/admin,强制 userId 隔离
- 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
This commit is contained in:
@@ -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 };
|
||||
@@ -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 };
|
||||
@@ -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 };
|
||||
@@ -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 };
|
||||
Reference in New Issue
Block a user