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:
lik
2026-11-01 11:42:27 +08:00
parent 9825ac376f
commit f3a1ef89bc
22 changed files with 1031 additions and 207 deletions
@@ -0,0 +1,10 @@
import { buildEmployeeQueryTool } from "../query/employee_query.js";
/**
* 管理端员工查询工具
*
* 管理端身份已在接入层校验;工具开放跨用户查询、userId 筛选和完整员工档案。
*/
const employeeQueryTool = buildEmployeeQueryTool({ allowCrossUser: true });
export { employeeQueryTool };
@@ -0,0 +1,10 @@
import { buildEmployeeReviewQueryTool } from "../query/employee_review_query.js";
/**
* 管理端员工评价查询工具
*
* 管理端身份已在接入层校验;工具开放跨用户查询与评价人 userId 筛选。
*/
const employeeReviewQueryTool = buildEmployeeReviewQueryTool({ allowCrossUser: true });
export { employeeReviewQueryTool };
@@ -0,0 +1,11 @@
import { buildEscortRecordQueryTool } from "../query/escort_record_query.js";
/**
* 管理端陪诊记录查询工具
*
* 管理端身份已在接入层校验;工具开放跨用户查询,
* 并支持手机号、陪诊员 ID、排期日期范围等管理筛选。
*/
const escortRecordQueryTool = buildEscortRecordQueryTool({ allowMobile: true });
export { escortRecordQueryTool };
@@ -0,0 +1,140 @@
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";
const escortRecordSetTool = tool(
async ({ orderId, status, notes, payment }) => {
try {
if (!orderId) {
return {
success: false,
error: "Record ID (_id) is required as the lookup key",
};
}
if (!mongoose.Types.ObjectId.isValid(orderId)) {
return {
success: false,
error: `Invalid record ID: ${orderId}. A valid record _id is required.`,
};
}
const record = await DBModel.EscortRecord.findById(orderId);
if (!record) {
return {
success: false,
error: `No escort record found for order ID: ${orderId}`,
};
}
// 状态迁移必须与接口层同一套规则:否则 Agent 能把已完成订单改回进行中,
// 绕过状态机并造成费用/服务记录不一致
const update = {};
if (status !== undefined && status !== record.status) {
if (!canTransition(record.status, status)) {
const allowed = STATUS_TRANSITIONS[record.status] || [];
return {
success: false,
error: `Illegal status transition: ${record.status} -> ${status}. Allowed: ${
allowed.length ? allowed.join(", ") : "none (terminal state)"
}`,
};
}
update.status = status;
}
if (notes !== undefined) {
if (notes.patientNote !== undefined) {
update["notes.patientNote"] = notes.patientNote;
}
if (notes.escortNote !== undefined) {
update["notes.escortNote"] = notes.escortNote;
}
if (notes.medicalSummary !== undefined) {
update["notes.medicalSummary"] = notes.medicalSummary;
}
}
if (payment !== undefined) {
if (payment.totalFee !== undefined) {
update["payment.totalFee"] = payment.totalFee;
}
if (payment.paidFee !== undefined) {
update["payment.paidFee"] = payment.paidFee;
}
if (payment.status !== undefined) {
update["payment.status"] = payment.status;
}
}
update["meta.updatetime"] = Date.now();
// 以读取时的状态作为更新条件,避免并发下跳过中间状态;同时排除已软删除的订单
const filter = { _id: record._id, deletedAt: null };
if (status !== undefined && status !== record.status) filter.status = record.status;
const updatedRecord = await DBModel.EscortRecord.findOneAndUpdate(
filter,
{ $set: update },
{ new: true, runValidators: true }
);
if (!updatedRecord) {
return {
success: false,
error: "Record state changed while updating. Re-query the record and retry.",
};
}
return {
success: true,
data: updatedRecord,
};
} catch (error) {
return {
success: false,
error: error.message,
};
}
},
{
name: "escort_record_set",
description:
"Update escort record fields by record ID (_id). Supports updating status, notes (patientNote, escortNote, medicalSummary), and payment (totalFee, paidFee, status). Only provided fields will be updated.",
schema: z.object({
orderId: z
.string()
.describe("Record ID (_id) used as the lookup key"),
status: z
.enum(["pending", "confirmed", "in_progress", "completed", "cancelled"])
.optional()
.describe(
"Appointment status: pending (待确认), confirmed (已确认), in_progress (进行中), completed (已完成), cancelled (已取消)"
),
notes: z
.object({
patientNote: z.string().optional().describe("Patient remarks / special requirements"),
escortNote: z.string().optional().describe("Escort service notes"),
medicalSummary: z.string().optional().describe("Medical visit summary"),
})
.optional()
.describe("Notes information to update"),
payment: z
.object({
totalFee: z.number().optional().describe("Total service fee (RMB)"),
paidFee: z.number().optional().describe("Amount already paid (RMB)"),
status: z
.enum(["unpaid", "partial", "paid", "refunding", "refunded"])
.optional()
.describe("Payment status: unpaid, partial, paid, refunding, refunded"),
})
.optional()
.describe("Payment information to update"),
}),
}
);
export { escortRecordSetTool };
@@ -0,0 +1,10 @@
import { buildHealthProfileQueryTool } from "../query/health_profile_query.js";
/**
* 管理端健康档案查询工具
*
* 管理端身份已在接入层校验;工具开放跨用户查询与 userId 筛选。
*/
const healthProfileQueryTool = buildHealthProfileQueryTool({ allowCrossUser: true });
export { healthProfileQueryTool };
@@ -0,0 +1,140 @@
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";
const PROFILE_KEYS = ["name", "mobile", "sex", "birth", "idnumber"];
const LOCATION_KEYS = ["country", "province", "city", "district", "address"];
const HEALTH_KEYS = ["height", "weight", "bloodType", "remark"];
const profileSchema = z
.object({
name: z.string().optional().describe("患者姓名"),
mobile: z.string().optional().describe("患者电话"),
sex: z.enum(["male", "female"]).optional().describe("性别"),
birth: z.string().optional().describe("出生年月(YYYY-MM-DD)"),
idnumber: z.string().optional().describe("证件号(身份证/护照等)"),
})
.optional()
.describe("患者基本信息");
const locationSchema = z
.object({
country: z.string().optional().describe("国家(国外用户填国家,国内默认中国)"),
province: z.string().optional().describe("省"),
city: z.string().optional().describe("市"),
district: z.string().optional().describe("区/县"),
address: z.string().optional().describe("详细地址"),
})
.optional()
.describe("所在地信息");
const healthSchema = z
.object({
height: z.number().optional().describe("身高(cm)"),
weight: z.number().optional().describe("体重(kg)"),
bloodType: z.string().optional().describe("血型"),
remark: z.string().optional().describe("备注"),
})
.optional()
.describe("健康信息");
const healthProfileSetTool = tool(
async ({ action, profileId, userId, profile, location, health }) => {
try {
if (action === "create") {
if (!profile || (!profile.name && !profile.mobile)) {
return { success: false, error: "创建健康档案至少需要提供患者姓名或电话" };
}
const docData = {
profile: { ...profile },
location: { ...location },
health: { ...health },
meta: { createtime: new Date(), updatetime: new Date() },
};
if (userId) {
if (!mongoose.Types.ObjectId.isValid(userId)) {
return { success: false, error: `Invalid user ID: ${userId}` };
}
docData.userId = new mongoose.Types.ObjectId(userId);
}
const doc = await DBModel.HealthProfile.create(docData);
return { success: true, data: doc };
}
if (action === "update") {
if (!profileId) {
return { success: false, error: "更新健康档案必须提供 profileId(可先用 health_profile_query 查询定位)" };
}
if (!mongoose.Types.ObjectId.isValid(profileId)) {
return { success: false, error: `Invalid profile ID: ${profileId}` };
}
const update = {};
if (userId) {
if (!mongoose.Types.ObjectId.isValid(userId)) {
return { success: false, error: `Invalid user ID: ${userId}` };
}
update.userId = new mongoose.Types.ObjectId(userId);
}
if (profile) {
for (const key of PROFILE_KEYS) {
if (profile[key] !== undefined) update[`profile.${key}`] = profile[key];
}
// 更新姓名时同步拼音字段(findByIdAndUpdate 不触发 pre("save"))
if (profile.name !== undefined) {
update["profile.pinyin"] = genPinyin(profile.name);
update["profile.pinyinFL"] = genPinyinFL(profile.name);
}
}
if (location) {
for (const key of LOCATION_KEYS) {
if (location[key] !== undefined) update[`location.${key}`] = location[key];
}
}
if (health) {
for (const key of HEALTH_KEYS) {
if (health[key] !== undefined) update[`health.${key}`] = health[key];
}
}
if (Object.keys(update).length === 0) {
return { success: false, error: "未提供任何要更新的字段" };
}
update["meta.updatetime"] = new Date();
const updated = await DBModel.HealthProfile.findByIdAndUpdate(
profileId,
{ $set: update },
{ new: true }
);
if (!updated) {
return { success: false, error: `未找到 ID 为 ${profileId} 的健康档案` };
}
return { success: true, data: updated };
}
return { success: false, error: "未知的 action,可选值:create / update" };
} catch (error) {
return { success: false, error: error.message };
}
},
{
name: "health_profile_set",
description:
"创建或更新患者健康档案。create 新建档案(至少提供患者姓名或电话);update 按档案 ID 局部更新,仅修改提供的字段。更新前建议先用 health_profile_query 查询现有内容。",
schema: z.object({
action: z.enum(["create", "update"]).describe("操作类型:create 新建 / update 更新"),
profileId: z.string().optional().describe("健康档案 ID(_id),update 时必填"),
userId: z.string().optional().describe("所属用户ID(可选,用于关联小程序用户)"),
profile: profileSchema,
location: locationSchema,
health: healthSchema,
}),
}
);
export { healthProfileSetTool };
@@ -0,0 +1,36 @@
import { tool } from "@langchain/core/tools";
import { z } from "zod";
import { DBModel } from "../../../../../models/index.js";
import { escapeRegex } from "../utils.js";
const hospitalInfoListTool = tool(
async ({ keyword }) => {
try {
const filter = {};
if (keyword) {
const re = { $regex: escapeRegex(keyword), $options: "i" };
filter.$or = [{ name: re }, { pinyin: re }, { pinyinFL: re }];
}
// 轻量列表:只取 id+名称,用于先定位医院,再按 id 查详情
const [total, orgs] = await Promise.all([
DBModel.Organization.countDocuments(filter),
DBModel.Organization.find(filter).sort({ name: 1 }).limit(1000).select("name").lean(),
]);
return { success: true, total, data: orgs.map((o) => ({ id: o._id, name: o.name })) };
} catch (error) {
return { success: false, error: error.message };
}
},
{
name: "hospital_info_list",
description:
"获取医院(名称、id)对列表,支持按名称/拼音关键词过滤,不传关键词返回全部。",
schema: z.object({
keyword: z.string().optional().describe("医院名称/拼音/拼音首字母关键词(如 协和、xiehe),不传返回全部"),
}),
}
);
export { hospitalInfoListTool };
@@ -0,0 +1,88 @@
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";
/**
* 医院信息查询工具
*
* 两种用法:
* - 传 hospitalId:返回该院完整档案(id 可先用 hospital_info_list 获取);
* - 传 hospitalName:按名称模糊查询,并可按科室 / 医生名过滤,返回面向上层展示的精简字段。
*/
const hospitalInfoQueryTool = tool(
async ({ hospitalId, hospitalName, department, doctorName }) => {
try {
if (hospitalId) {
if (!mongoose.Types.ObjectId.isValid(hospitalId)) {
return { success: false, error: `Invalid hospital ID: ${hospitalId}` };
}
const org = await DBModel.Organization.findById(hospitalId).lean();
if (!org) {
return { success: false, error: `未找到 id 为「${hospitalId}」的机构` };
}
return { success: true, total: 1, data: [org] };
}
if (!hospitalName) {
return { success: false, error: "请提供 hospitalId 或 hospitalName" };
}
const filter = { name: { $regex: escapeRegex(hospitalName), $options: "i" } };
// 医院总量小,一次最多取 10 家,命中过多时由调用方细化名称
const [total, orgs] = await Promise.all([
DBModel.Organization.countDocuments(filter),
DBModel.Organization.find(filter).limit(10).lean(),
]);
if (total === 0) {
return { success: false, error: `未找到名称包含「${hospitalName}」的机构` };
}
const data = orgs.map((org) => {
const fa = org.forAgent ?? {};
let departments = fa.departments ?? [];
let doctors = fa.doctors ?? [];
if (department) {
departments = departments.filter((d) => d.name?.includes(department));
doctors = doctors.filter((d) => d.department?.includes(department));
}
if (doctorName) {
doctors = doctors.filter((d) => d.name?.includes(doctorName));
}
return {
_id: org._id,
name: org.name,
level: org.level ?? "",
address: org.address ?? {},
infoUpdatedAt: fa.updatedAt ?? null,
overview: fa.overview ?? "",
photos: fa.photos ?? [],
departments,
doctors,
guides: fa.guides ?? {},
};
});
return { success: true, total, data };
} catch (error) {
return { success: false, error: error.message };
}
},
{
name: "hospital_info_query",
description:
"查询医院就医信息。传 hospitalId 返回该院完整档案;传 hospitalName 按名称模糊查询,可再按科室、医生名过滤,返回医院总览(门诊/挂号/缴费/医保/交通)、科室(位置/电话/就诊提示)、医生(职称/擅长/号别/坐班)、场景指南、照片。最多返回 10 家医院。",
schema: z.object({
hospitalId: z
.string()
.optional()
.describe("医院 id(MongoDB ObjectId,来自 hospital_info_list),提供时忽略其他查询条件"),
hospitalName: z.string().optional().describe("医院名称,支持模糊匹配(如 协和)"),
department: z.string().optional().describe("科室名称过滤(如 风湿免疫科、放射科)"),
doctorName: z.string().optional().describe("医生姓名过滤"),
}),
}
);
export { hospitalInfoQueryTool };
@@ -0,0 +1,146 @@
import { tool } from "@langchain/core/tools";
import { z } from "zod";
import { DBModel } from "../../../../../models/index.js";
import { escapeRegex } from "../utils.js";
const hospitalInfoSetTool = tool(
async ({ hospitalName, section, action, content, guides, entry, entryName, updatedBy }) => {
try {
if (!hospitalName) {
return { success: false, error: "hospitalName 不能为空" };
}
// 定位医院:名称必须唯一命中;转义正则元字符,避免非法表达式与 ReDoS
const orgs = await DBModel.Organization.find({
name: { $regex: escapeRegex(hospitalName), $options: "i" },
}).exec();
if (orgs.length === 0) {
return { success: false, error: `未找到名称包含「${hospitalName}」的机构,请确认医院名称后重试` };
}
if (orgs.length > 1) {
return {
success: false,
error: `名称包含「${hospitalName}」的机构有 ${orgs.length} 家(${orgs.map((o) => o.name).join("、")}),请使用更精确的名称`,
};
}
const org = orgs[0];
const fa = org.forAgent ?? {};
const update = {};
if (section === "overview") {
// 文本块全量替换
if (typeof content !== "string") {
return { success: false, error: "overview 需要提供 content 文本(写入前请先查询现有内容并合并)" };
}
update["forAgent.overview"] = content;
} else if (section === "guides") {
// 场景键值对浅合并,值为 null 表示删除该场景
if (!guides || typeof guides !== "object" || Array.isArray(guides)) {
return { success: false, error: "guides 需要提供对象,键为场景名,值为文本(值为 null 表示删除该场景)" };
}
const merged = { ...(fa.guides ?? {}) };
for (const [key, value] of Object.entries(guides)) {
if (value === null) {
delete merged[key];
} else {
merged[key] = value;
}
}
update["forAgent.guides"] = merged;
} else if (section === "photos" || section === "departments" || section === "doctors") {
// 列表区块:按锚点 upsert(新增或整条替换)/ remove
const list = [...(fa[section] ?? [])];
if (action === "upsert") {
if (!entry || typeof entry !== "object") {
return { success: false, error: "upsert 需要提供 entry 对象" };
}
let idx = -1;
if (section === "photos") {
if (!entry.url) return { success: false, error: "photos 条目必须包含 url 作为锚点" };
idx = list.findIndex((p) => p.url === entry.url);
} else if (section === "doctors") {
if (!entry.name || !entry.department) {
return { success: false, error: "doctors 条目必须包含 name 和 department 作为锚点" };
}
idx = list.findIndex((d) => d.name === entry.name && d.department === entry.department);
} else {
if (!entry.name) return { success: false, error: "departments 条目必须包含 name 作为锚点" };
idx = list.findIndex((d) => d.name === entry.name);
}
if (idx >= 0) {
list[idx] = { ...list[idx], ...entry };
} else {
list.push(entry);
}
update[`forAgent.${section}`] = list;
} else if (action === "remove") {
if (!entryName) {
return {
success: false,
error: `remove 需要提供 entryName(${section === "photos" ? "照片url" : section === "doctors" ? "医生姓名" : "科室名称"})`,
};
}
if (section === "photos") {
update[`forAgent.${section}`] = list.filter((p) => p.url !== entryName);
} else {
update[`forAgent.${section}`] = list.filter((d) => d.name !== entryName);
}
} else {
return { success: false, error: "列表区块(photos/departments/doctors)需要指定 action: upsert 或 remove" };
}
} else {
return { success: false, error: "未知的 section,可选值:overview / photos / departments / doctors / guides" };
}
update["forAgent.updatedAt"] = new Date();
if (updatedBy) {
update["forAgent.updatedBy"] = updatedBy;
}
const updated = await DBModel.Organization.findByIdAndUpdate(org._id, { $set: update }, { new: true }).exec();
return { success: true, data: updated.forAgent };
} catch (error) {
return { success: false, error: error.message };
}
},
{
name: "hospital_info_set",
description:
"录入/更新医院就医信息。按区块维护:overview(医院级文本,全量替换,先查后改避免丢失)、guides(场景指南键值对,浅合并)、photos/departments/doctors(列表,按锚点 upsert 或 remove)。医院名称必须唯一命中。",
schema: z.object({
hospitalName: z.string().describe("医院名称(需唯一命中,如 北京协和医院)"),
section: z
.enum(["overview", "photos", "departments", "doctors", "guides"])
.describe("要更新的区块"),
action: z
.enum(["set", "upsert", "remove"])
.optional()
.describe("操作类型:overview/guides 用 set;photos/departments/doctors 用 upsert 或 remove"),
content: z.string().optional().describe("overview 区块的完整文本(全量替换)"),
guides: z
.record(z.string(), z.string().nullable())
.optional()
.describe('guides 区块的场景键值对,如 {"住院流程": "..."};值为 null 表示删除该场景'),
entry: z
.object({
name: z.string().optional().describe("科室名或医生名(锚点)"),
department: z.string().optional().describe("医生所属科室(医生锚点之一)"),
detail: z
.string()
.optional()
.describe("信息全文:科室(位置/电话/类型/提示)或医生(职称/擅长/号别/坐班停诊)"),
photo: z.string().optional().describe("照片链接"),
url: z.string().optional().describe("照片链接(photos 锚点)"),
caption: z.string().optional().describe("照片说明"),
})
.optional()
.describe("photos/departments/doctors 条目(upsert 时必填)"),
entryName: z.string().optional().describe("remove 的锚点:科室名称 / 医生姓名 / 照片url"),
updatedBy: z.string().optional().describe("操作人标识(用户ID或姓名),用于审计"),
}),
}
);
export { hospitalInfoSetTool };