- 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
244 lines
9.3 KiB
JavaScript
244 lines
9.3 KiB
JavaScript
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 };
|