feat(agent): 管理端 agent 支持陪诊员并按角色收敛工具
陪诊员身份以 Employee 在职档案为准,显式管理员优先;管理端小程序首次登录会写入 role:['user'],不能据此判断。管理员保留跨用户查询与医院资料写入,陪诊员只开放本人订单查询/改单(归属校验、状态与字段白名单、并发保护)与本人档案,患者档案与财务操作不可用。
This commit is contained in:
@@ -18,8 +18,11 @@ import { createHospitalInfoSubagent } from "../../subagent/hospital_info.js";
|
|||||||
import {
|
import {
|
||||||
webFetchTool, webSearchTool, getCalendarInfoTool, getYearHolidaysTool,
|
webFetchTool, webSearchTool, getCalendarInfoTool, getYearHolidaysTool,
|
||||||
httpGetTool, escortRecordQueryTool, escortRecordSetTool,
|
httpGetTool, escortRecordQueryTool, escortRecordSetTool,
|
||||||
employeeQueryTool, employeeReviewQueryTool
|
employeeQueryTool, employeeReviewQueryTool,
|
||||||
|
createAttendantEscortRecordQueryTool, buildAttendantEscortRecordSetTool,
|
||||||
|
createAttendantEmployeeQueryTool
|
||||||
} from "../../infra/tools/index.js";
|
} from "../../infra/tools/index.js";
|
||||||
|
import { resolveEscortAdminRole } from "../../../utils/permissions.js";
|
||||||
|
|
||||||
export default class EscortAdminAgent {
|
export default class EscortAdminAgent {
|
||||||
constructor(options = {}) {
|
constructor(options = {}) {
|
||||||
@@ -39,11 +42,18 @@ export default class EscortAdminAgent {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// msg: { agent: 'escort-admin', type: 'chat', ts: "2023-08-01 10:00:00", content: "你好" }
|
// msg: { agent: 'escort-admin', type: 'chat', ts: "2023-08-01 10:00:00", content: "你好" }
|
||||||
async streamChat(userInfo, msgs, callback) {
|
// role: 入口已解析的 admin / attendant;不传时在这里兜底解析,避免绕过入口直接调用
|
||||||
|
async streamChat(userInfo, msgs, callback, role = null) {
|
||||||
if (!msgs.length) {
|
if (!msgs.length) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const effectiveRole = role ?? await resolveEscortAdminRole(userInfo);
|
||||||
|
if (!effectiveRole) {
|
||||||
|
callback("main", "ai", "当前账号未绑定在职陪诊员档案,请联系管理员开通。", msgs[0]?.id);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const userId = userInfo._id;
|
const userId = userInfo._id;
|
||||||
|
|
||||||
// LRU:按用户取会话,并更新使用顺序
|
// LRU:按用户取会话,并更新使用顺序
|
||||||
@@ -78,21 +88,23 @@ export default class EscortAdminAgent {
|
|||||||
// 长会话下工具结果会挤占上下文,按完整轮次裁剪,避免上下文溢出与"忘记"前文
|
// 长会话下工具结果会挤占上下文,按完整轮次裁剪,避免上下文溢出与"忘记"前文
|
||||||
session.messages = trimHistory(session.messages, this.maxHistoryChars);
|
session.messages = trimHistory(session.messages, this.maxHistoryChars);
|
||||||
|
|
||||||
// 用户资料变更后需重建 agent,否则 systemPrompt 仍是旧资料
|
// 用户资料或角色变更后需重建 agent,否则 systemPrompt 与工具集仍是旧的
|
||||||
const fingerprint = this._userFingerprint(userInfo);
|
const fingerprint = this._userFingerprint(userInfo, effectiveRole);
|
||||||
if (session.agent && session.fingerprint !== fingerprint) {
|
if (session.agent && (session.fingerprint !== fingerprint || session.role !== effectiveRole)) {
|
||||||
session.agent = null;
|
session.agent = null;
|
||||||
}
|
}
|
||||||
session.fingerprint = fingerprint;
|
session.fingerprint = fingerprint;
|
||||||
|
session.role = effectiveRole;
|
||||||
|
|
||||||
const agent = session.agent ?? this._genAgent(userInfo);
|
const agent = session.agent ?? this._genAgent(userInfo, effectiveRole);
|
||||||
session.agent = agent;
|
session.agent = agent;
|
||||||
|
|
||||||
// 输出护栏:禁用词(身份泄露/空泛客套/越界承诺)拦截;
|
// 输出护栏:禁用词(身份泄露/空泛客套/越界承诺)拦截;
|
||||||
// 长度上限只作用于主回答,子代理输出会单独展示,不受主回答篇幅约束
|
// 长度上限只作用于主回答,子代理输出会单独展示,不受主回答篇幅约束
|
||||||
|
const guardLabel = effectiveRole === "attendant" ? "escort-admin:attendant" : "escort-admin:admin";
|
||||||
const guards = {
|
const guards = {
|
||||||
main: new OutputGuard({ label: "admin", maxChars: this.maxOutputChars }),
|
main: new OutputGuard({ label: guardLabel, maxChars: this.maxOutputChars }),
|
||||||
subagent: new OutputGuard({ label: "admin:subagent", maxChars: Infinity }),
|
subagent: new OutputGuard({ label: `${guardLabel}:subagent`, maxChars: Infinity }),
|
||||||
};
|
};
|
||||||
const lastAiId = { main: "", subagent: "" };
|
const lastAiId = { main: "", subagent: "" };
|
||||||
|
|
||||||
@@ -167,13 +179,43 @@ export default class EscortAdminAgent {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 用户资料指纹:姓名/手机号/角色变化时需重建 agent,否则 systemPrompt 仍是旧资料
|
// 用户资料指纹:姓名/手机号/角色变化时需重建 agent,否则 systemPrompt 仍是旧资料
|
||||||
_userFingerprint(userInfo) {
|
_userFingerprint(userInfo, role = "admin") {
|
||||||
if (!userInfo) return "anonymous";
|
if (!userInfo) return "anonymous";
|
||||||
const profile = userInfo.profile ?? {};
|
const profile = userInfo.profile ?? {};
|
||||||
return JSON.stringify([profile.name, profile.mobile, userInfo.app]);
|
return JSON.stringify([profile.name, profile.mobile, userInfo.app, role]);
|
||||||
}
|
}
|
||||||
|
|
||||||
_genAgent(userInfo) {
|
// 公共安全工具:天气、路线、日期、节假日与网页检索,不涉及业务数据
|
||||||
|
_commonTools() {
|
||||||
|
return [webFetchTool, webSearchTool, httpGetTool, getCalendarInfoTool, getYearHolidaysTool];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 管理端工具集
|
||||||
|
* 仅显式管理员或员工档案为管理员时开放:跨用户查询、患者档案、医院资料维护等
|
||||||
|
*/
|
||||||
|
_adminTools() {
|
||||||
|
return [
|
||||||
|
...this._commonTools(),
|
||||||
|
escortRecordQueryTool, escortRecordSetTool,
|
||||||
|
employeeQueryTool, employeeReviewQueryTool
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 陪诊员工具集
|
||||||
|
* 只给本人订单与本人档案,禁止跨用户查询、财务字段与医院资料写入
|
||||||
|
*/
|
||||||
|
_attendantTools(userInfo) {
|
||||||
|
return [
|
||||||
|
...this._commonTools(),
|
||||||
|
createAttendantEscortRecordQueryTool(userInfo),
|
||||||
|
buildAttendantEscortRecordSetTool({ attendantId: userInfo?._id }),
|
||||||
|
createAttendantEmployeeQueryTool(userInfo)
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
_genAgent(userInfo, role = "admin") {
|
||||||
const rootDir = process.cwd();
|
const rootDir = process.cwd();
|
||||||
// 受限后端:锁定沙箱根并禁止读取 conf.json/.env/logs 及用户数据目录
|
// 受限后端:锁定沙箱根并禁止读取 conf.json/.env/logs 及用户数据目录
|
||||||
const backend = createRestrictedBackend({ rootDir, dataDir: config.agent.dataDir });
|
const backend = createRestrictedBackend({ rootDir, dataDir: config.agent.dataDir });
|
||||||
@@ -184,17 +226,23 @@ export default class EscortAdminAgent {
|
|||||||
temperature: this.temperature
|
temperature: this.temperature
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const isAdminRole = role === "admin";
|
||||||
|
const subagents = isAdminRole
|
||||||
|
? [
|
||||||
|
createPatientRecordSubagent(this.flashModel),
|
||||||
|
// 医院资料维护只给管理员;陪诊员只读
|
||||||
|
createHospitalInfoSubagent(this.flashModel, { allowWrite: true }),
|
||||||
|
]
|
||||||
|
: [createHospitalInfoSubagent(this.flashModel, { allowWrite: false })];
|
||||||
|
|
||||||
return createDeepAgent({
|
return createDeepAgent({
|
||||||
name: "deep-agent",
|
name: "deep-agent",
|
||||||
model: this.flashModel,
|
model: this.flashModel,
|
||||||
systemPrompt: EscortAdminPrompts.buildSystemPrompt(userInfo),
|
systemPrompt: EscortAdminPrompts.buildSystemPrompt(userInfo, role),
|
||||||
backend,
|
backend,
|
||||||
middleware: [todoListMiddleware()], // deepagents 1.12 起 todo 计划工具改为显式开启,多步记录操作用
|
middleware: [todoListMiddleware()], // deepagents 1.12 起 todo 计划工具改为显式开启,多步记录操作用
|
||||||
tools: [webFetchTool, webSearchTool, httpGetTool,
|
tools: isAdminRole ? this._adminTools() : this._attendantTools(userInfo),
|
||||||
getCalendarInfoTool, getYearHolidaysTool,
|
subagents,
|
||||||
escortRecordQueryTool, escortRecordSetTool,
|
|
||||||
employeeQueryTool, employeeReviewQueryTool],
|
|
||||||
subagents: [createPatientRecordSubagent(this.flashModel), createHospitalInfoSubagent(this.flashModel, { allowWrite: true })],
|
|
||||||
skills: ["./agent/infra/skills/"],
|
skills: ["./agent/infra/skills/"],
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import { buildEmployeeQueryTool } from "../query/employee_query.js";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 陪诊员端员工查询工具
|
||||||
|
*
|
||||||
|
* 只允许查本人档案:强制按当前登录用户 ID 隔离,schema 不暴露 userId;
|
||||||
|
* 输出走用户端白名单,不返回身份证、手机号、证书编号等敏感字段。
|
||||||
|
*/
|
||||||
|
const createAttendantEmployeeQueryTool = (userInfo) =>
|
||||||
|
buildEmployeeQueryTool({ userId: userInfo?._id });
|
||||||
|
|
||||||
|
export { createAttendantEmployeeQueryTool };
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import { buildEscortRecordQueryTool } from "../query/escort_record_query.js";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 陪诊员端陪诊记录查询工具
|
||||||
|
*
|
||||||
|
* 只传入当前登录陪诊员的用户 ID,作为「我的订单」强制归属条件:
|
||||||
|
* - schema 不暴露手机号、陪诊员 ID 等跨用户筛选;
|
||||||
|
* - 所有查询(含日期范围)都自动限定为 attendant.id = 当前用户。
|
||||||
|
*/
|
||||||
|
const createAttendantEscortRecordQueryTool = (userInfo) =>
|
||||||
|
buildEscortRecordQueryTool({ boundAttendantId: userInfo?._id });
|
||||||
|
|
||||||
|
export { createAttendantEscortRecordQueryTool };
|
||||||
@@ -0,0 +1,159 @@
|
|||||||
|
import { tool } from "@langchain/core/tools";
|
||||||
|
import { z } from "zod";
|
||||||
|
import { DBModel } from "../../../../../models/index.js";
|
||||||
|
import { canTransition, STATUS_TRANSITIONS } from "../../../../../utils/record_state.js";
|
||||||
|
import { parseObjectId } from "../utils.js";
|
||||||
|
|
||||||
|
// 陪诊员只能推进自己订单的服务进度,确认/取消/改期/改金额都属于平台管理员
|
||||||
|
const ALLOWED_STATUS_VALUES = ["in_progress", "completed"];
|
||||||
|
const ALLOWED_STATUS_DESC =
|
||||||
|
"Service progress: in_progress (开始服务), completed (服务完成)";
|
||||||
|
// 未确认、已取消的订单不允许陪诊员写入任何内容
|
||||||
|
const EDITABLE_RECORD_STATUS = ["confirmed", "in_progress", "completed"];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 陪诊员端订单更新工具
|
||||||
|
*
|
||||||
|
* 与管理端 escort_record_set 的差异(防止陪诊员越权):
|
||||||
|
* - 只能改分配给本人的订单(attendant.id 必须等于当前用户);
|
||||||
|
* - 只能 confirmed -> in_progress、in_progress -> completed;
|
||||||
|
* - 只能写陪诊备注与就诊小结,不能改患者备注、费用、排班、陪诊员归属。
|
||||||
|
*
|
||||||
|
* @param {Object} [options]
|
||||||
|
* @param {string} [options.attendantId] 当前登录陪诊员的用户 ID
|
||||||
|
*/
|
||||||
|
function buildAttendantEscortRecordSetTool({ attendantId = null } = {}) {
|
||||||
|
const boundAttendantId = parseObjectId(attendantId);
|
||||||
|
|
||||||
|
return tool(
|
||||||
|
async ({ orderId, status, notes }) => {
|
||||||
|
try {
|
||||||
|
if (!boundAttendantId) {
|
||||||
|
return { success: false, error: "陪诊员身份无效,无法修改订单" };
|
||||||
|
}
|
||||||
|
|
||||||
|
const recordObjectId = parseObjectId(orderId);
|
||||||
|
if (!recordObjectId) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: `Invalid record ID: ${orderId}. A valid record _id is required.`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const record = await DBModel.EscortRecord.findOne({
|
||||||
|
_id: recordObjectId,
|
||||||
|
deletedAt: null,
|
||||||
|
});
|
||||||
|
if (!record) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: `No escort record found for order ID: ${orderId}`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// 归属校验:不属于本人一律按无权处理,不透露订单内容
|
||||||
|
if (String(record.attendant?.id ?? "") !== String(boundAttendantId)) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "无权操作该订单:该订单未分配给你。",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!EDITABLE_RECORD_STATUS.includes(record.status)) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error:
|
||||||
|
record.status === "pending"
|
||||||
|
? "订单还未确认,不能操作,请联系管理员确认。"
|
||||||
|
: "订单已取消,不能修改。",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const update = {};
|
||||||
|
|
||||||
|
if (status !== undefined && status !== record.status) {
|
||||||
|
if (!ALLOWED_STATUS_VALUES.includes(status)) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error:
|
||||||
|
"陪诊员只能把订单从 confirmed 改为 in_progress(开始服务),或从 in_progress 改为 completed(服务完成)。确认、取消、改期、退款请联系管理员。",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
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.escortNote !== undefined) {
|
||||||
|
update["notes.escortNote"] = notes.escortNote;
|
||||||
|
}
|
||||||
|
if (notes.medicalSummary !== undefined) {
|
||||||
|
update["notes.medicalSummary"] = notes.medicalSummary;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Object.keys(update).length === 0) {
|
||||||
|
return { success: true, data: record, message: "No fields to update" };
|
||||||
|
}
|
||||||
|
|
||||||
|
update["meta.updatetime"] = Date.now();
|
||||||
|
|
||||||
|
// 以读取时的状态作为更新条件,避免并发下跳过中间状态;
|
||||||
|
// 同时再次绑定陪诊员归属,防止更新期间订单被改派
|
||||||
|
const filter = {
|
||||||
|
_id: record._id,
|
||||||
|
deletedAt: null,
|
||||||
|
"attendant.id": boundAttendantId,
|
||||||
|
};
|
||||||
|
if (update.status !== undefined) 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 one of the current attendant's assigned escort records by record ID (_id). Only orders assigned to the current attendant can be updated. Supports advancing status (confirmed -> in_progress, in_progress -> completed) and writing the attendant's service notes (escortNote, medicalSummary). Payment, rebooking, cancellation and patient notes are not editable.",
|
||||||
|
schema: z.object({
|
||||||
|
orderId: z.string().describe("Record ID (_id) used as the lookup key"),
|
||||||
|
status: z
|
||||||
|
.enum(ALLOWED_STATUS_VALUES)
|
||||||
|
.optional()
|
||||||
|
.describe(ALLOWED_STATUS_DESC),
|
||||||
|
notes: z
|
||||||
|
.object({
|
||||||
|
escortNote: z.string().optional().describe("Escort service notes"),
|
||||||
|
medicalSummary: z.string().optional().describe("Medical visit summary"),
|
||||||
|
})
|
||||||
|
.optional()
|
||||||
|
.describe("Service notes to update"),
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export { buildAttendantEscortRecordSetTool };
|
||||||
@@ -28,11 +28,16 @@ function parseDay(value) {
|
|||||||
/**
|
/**
|
||||||
* 陪诊记录查询内部实现
|
* 陪诊记录查询内部实现
|
||||||
*
|
*
|
||||||
* 仅供 db/user 与 db/admin 下的工具包装使用,不直接暴露给 Agent:
|
* 仅供 db/user、db/attendant 与 db/admin 下的工具包装使用,不直接暴露给 Agent:
|
||||||
* - 用户端包装只传 userId,强制按当前登录用户隔离;
|
* - 用户端包装只传 userId,强制按当前登录用户隔离;
|
||||||
* - 管理端包装传 allowMobile,才开放跨用户查询与手机号/陪诊员/日期筛选。
|
* - 陪诊员端包装传 boundAttendantId,强制按陪诊员归属隔离;
|
||||||
|
* - 管理端包装传 allowMobile,才开放跨用户查询与手机号/陪诊员筛选。
|
||||||
*/
|
*/
|
||||||
function buildEscortRecordQueryTool({ userId = null, allowMobile = false } = {}) {
|
function buildEscortRecordQueryTool({ userId = null, allowMobile = false, boundAttendantId = null } = {}) {
|
||||||
|
const attendantObjectId = boundAttendantId ? parseObjectId(boundAttendantId) : null;
|
||||||
|
const attendantScope = Boolean(attendantObjectId);
|
||||||
|
const allowDateRange = allowMobile || attendantScope;
|
||||||
|
|
||||||
const shape = {
|
const shape = {
|
||||||
patientName: z.string().optional().describe("Patient name for fuzzy search"),
|
patientName: z.string().optional().describe("Patient name for fuzzy search"),
|
||||||
status: z.enum(STATUS_VALUES).optional().describe(STATUS_DESC),
|
status: z.enum(STATUS_VALUES).optional().describe(STATUS_DESC),
|
||||||
@@ -52,6 +57,9 @@ function buildEscortRecordQueryTool({ userId = null, allowMobile = false } = {})
|
|||||||
.string()
|
.string()
|
||||||
.optional()
|
.optional()
|
||||||
.describe("Attendant (escort staff) user ID (_id) for exact match");
|
.describe("Attendant (escort staff) user ID (_id) for exact match");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (allowDateRange) {
|
||||||
shape.dateFrom = z
|
shape.dateFrom = z
|
||||||
.string()
|
.string()
|
||||||
.optional()
|
.optional()
|
||||||
@@ -65,7 +73,7 @@ function buildEscortRecordQueryTool({ userId = null, allowMobile = false } = {})
|
|||||||
return tool(
|
return tool(
|
||||||
async ({ patientName, mobile, attendantId, dateFrom, dateTo, status, page = 1, pageSize = 20 }) => {
|
async ({ patientName, mobile, attendantId, dateFrom, dateTo, status, page = 1, pageSize = 20 }) => {
|
||||||
try {
|
try {
|
||||||
if (!userId && !allowMobile) {
|
if (!userId && !allowMobile && !attendantScope) {
|
||||||
return { success: false, error: "用户未登录,无法查询陪诊记录" };
|
return { success: false, error: "用户未登录,无法查询陪诊记录" };
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -79,16 +87,21 @@ function buildEscortRecordQueryTool({ userId = null, allowMobile = false } = {})
|
|||||||
filter["patient.mobile"] = mobile;
|
filter["patient.mobile"] = mobile;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (allowMobile && attendantId) {
|
// 陪诊员只能看到分配给自己的订单:模型侧不暴露该筛选,条件在服务端强制绑定
|
||||||
const attendantObjectId = parseObjectId(attendantId);
|
if (attendantScope) {
|
||||||
if (!attendantObjectId) {
|
|
||||||
return { success: false, error: `Invalid attendant ID: ${attendantId}` };
|
|
||||||
}
|
|
||||||
filter["attendant.id"] = attendantObjectId;
|
filter["attendant.id"] = attendantObjectId;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (allowMobile && attendantId) {
|
||||||
|
const queryAttendantId = parseObjectId(attendantId);
|
||||||
|
if (!queryAttendantId) {
|
||||||
|
return { success: false, error: `Invalid attendant ID: ${attendantId}` };
|
||||||
|
}
|
||||||
|
filter["attendant.id"] = queryAttendantId;
|
||||||
|
}
|
||||||
|
|
||||||
// 日期按东八区自然日解释,dateTo 含当天
|
// 日期按东八区自然日解释,dateTo 含当天
|
||||||
if (allowMobile && (dateFrom || dateTo)) {
|
if (allowDateRange && (dateFrom || dateTo)) {
|
||||||
const range = {};
|
const range = {};
|
||||||
if (dateFrom) {
|
if (dateFrom) {
|
||||||
const from = parseDay(dateFrom);
|
const from = parseDay(dateFrom);
|
||||||
@@ -145,6 +158,8 @@ function buildEscortRecordQueryTool({ userId = null, allowMobile = false } = {})
|
|||||||
name: "escort_record_query",
|
name: "escort_record_query",
|
||||||
description: allowMobile
|
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 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."
|
||||||
|
: attendantScope
|
||||||
|
? "Query escort records assigned to the current attendant. Supports filtering by patient name, appointment status and schedule date range (YYYY-MM-DD, inclusive). Returns paginated results sorted by appointment date in descending order. The query is automatically scoped to the current attendant."
|
||||||
: "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.",
|
: "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),
|
schema: z.object(shape),
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,6 +15,11 @@ export { createHealthProfileQueryTool } from './db/user/health_profile_query.js'
|
|||||||
export { createEmployeeQueryTool } from './db/user/employee_query.js';
|
export { createEmployeeQueryTool } from './db/user/employee_query.js';
|
||||||
export { createEmployeeReviewQueryTool } from './db/user/employee_review_query.js';
|
export { createEmployeeReviewQueryTool } from './db/user/employee_review_query.js';
|
||||||
|
|
||||||
|
// 陪诊员端:只允许查/改分配给本人的订单与本人档案
|
||||||
|
export { createAttendantEscortRecordQueryTool } from './db/attendant/escort_record_query.js';
|
||||||
|
export { buildAttendantEscortRecordSetTool } from './db/attendant/escort_record_set.js';
|
||||||
|
export { createAttendantEmployeeQueryTool } from './db/attendant/employee_query.js';
|
||||||
|
|
||||||
// 管理端查询:仅注入 escort-admin,可跨用户查询
|
// 管理端查询:仅注入 escort-admin,可跨用户查询
|
||||||
export { escortRecordQueryTool } from './db/admin/escort_record_query.js';
|
export { escortRecordQueryTool } from './db/admin/escort_record_query.js';
|
||||||
export { healthProfileQueryTool } from './db/admin/health_profile_query.js';
|
export { healthProfileQueryTool } from './db/admin/health_profile_query.js';
|
||||||
|
|||||||
+77
-3
@@ -1,3 +1,24 @@
|
|||||||
|
import mongoose from "mongoose";
|
||||||
|
import { DBModel } from "../models/index.js";
|
||||||
|
|
||||||
|
const ADMIN_APP = "wxapp-escort-admin";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 管理端 app 条目里的角色数组
|
||||||
|
*
|
||||||
|
* 注意:普通账号首次登录管理端小程序时,user 服务会写入 role: ["user"],
|
||||||
|
* 所以「有 wxapp-escort-admin 条目」不等于陪诊员,陪诊员身份必须以 Employee 记录为准。
|
||||||
|
*
|
||||||
|
* @param {Object} user 登录用户
|
||||||
|
* @returns {string[]}
|
||||||
|
*/
|
||||||
|
function appRoles(user) {
|
||||||
|
const entry = user?.app?.[ADMIN_APP];
|
||||||
|
if (!entry) return [];
|
||||||
|
if (Array.isArray(entry.role)) return entry.role;
|
||||||
|
return entry.role ? [entry.role] : [];
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 管理端身份判定:路由中间件、订单 handler、WebSocket 入口共用同一口径。
|
* 管理端身份判定:路由中间件、订单 handler、WebSocket 入口共用同一口径。
|
||||||
*
|
*
|
||||||
@@ -8,10 +29,10 @@
|
|||||||
* 待库中补齐 app.wxapp-escort-admin.role = ['admin'] 后再收紧(见 doc/api-review-plan.md B1)。
|
* 待库中补齐 app.wxapp-escort-admin.role = ['admin'] 后再收紧(见 doc/api-review-plan.md B1)。
|
||||||
*/
|
*/
|
||||||
function isAdmin(user) {
|
function isAdmin(user) {
|
||||||
const entry = user?.app?.["wxapp-escort-admin"];
|
const entry = user?.app?.[ADMIN_APP];
|
||||||
if (!entry) return false;
|
if (!entry) return false;
|
||||||
|
|
||||||
const roles = Array.isArray(entry.role) ? entry.role : [entry.role].filter(Boolean);
|
const roles = appRoles(user);
|
||||||
if (roles.includes("admin")) return true;
|
if (roles.includes("admin")) return true;
|
||||||
|
|
||||||
if (entry.role === undefined) {
|
if (entry.role === undefined) {
|
||||||
@@ -23,4 +44,57 @@ function isAdmin(user) {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
export { isAdmin };
|
/**
|
||||||
|
* 陪诊员身份判定:以 Employee 记录为唯一可信来源
|
||||||
|
*
|
||||||
|
* @param {ObjectId|string} userId 登录用户 ID
|
||||||
|
* @returns {Promise<Object|null>} 在职员工档案(只含 role/employeeNo)
|
||||||
|
*/
|
||||||
|
async function findActiveEmployee(userId) {
|
||||||
|
const raw = typeof userId === "string" ? userId.trim() : String(userId ?? "");
|
||||||
|
if (!/^[0-9a-fA-F]{24}$/.test(raw)) return null;
|
||||||
|
try {
|
||||||
|
return await DBModel.Employee.findOne({
|
||||||
|
userId: new mongoose.Types.ObjectId(raw),
|
||||||
|
status: "active",
|
||||||
|
})
|
||||||
|
.select("role employeeNo")
|
||||||
|
.lean();
|
||||||
|
} catch (err) {
|
||||||
|
// 员工库查询失败不能把管理员一起拒之门外:返回 null 后仍走 app role 判定
|
||||||
|
console.warn("[permissions] 查询员工档案失败:", err.message);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 管理端 Agent 的使用角色
|
||||||
|
*
|
||||||
|
* - admin:显式管理员,或员工档案为管理员;
|
||||||
|
* - attendant:员工档案为在职陪诊员(app role 一般为 ["user"],不能据此判断);
|
||||||
|
* - null:无权使用。
|
||||||
|
*
|
||||||
|
* 先查员工档案再看 app role:历史账号 role 缺失时 isAdmin 会兼容放行,
|
||||||
|
* 若该账号同时也是在职陪诊员,必须收敛为陪诊员权限,不能拿到管理员级工具。
|
||||||
|
*
|
||||||
|
* @param {Object} user 登录用户
|
||||||
|
* @returns {Promise<"admin"|"attendant"|null>}
|
||||||
|
*/
|
||||||
|
async function resolveEscortAdminRole(user) {
|
||||||
|
if (!user) return null;
|
||||||
|
|
||||||
|
const roles = appRoles(user);
|
||||||
|
// 显式管理员优先,避免为管理员多查一次员工库
|
||||||
|
if (roles.includes("admin")) return "admin";
|
||||||
|
|
||||||
|
const employee = await findActiveEmployee(user._id);
|
||||||
|
if (employee?.role === "admin") return "admin";
|
||||||
|
if (employee?.role === "attendant") return "attendant";
|
||||||
|
|
||||||
|
// 兼容历史管理员(role 缺失);普通管理端账号 role 为 ["user"],不会走到这里
|
||||||
|
if (isAdmin(user)) return "admin";
|
||||||
|
if (roles.includes("attendant")) return "attendant";
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export { isAdmin, resolveEscortAdminRole };
|
||||||
|
|||||||
+7
-5
@@ -4,7 +4,7 @@ import { DBModel } from "./models/index.js";
|
|||||||
import { chatTask } from "./agent/bots/bot-escort/task.js";
|
import { chatTask } from "./agent/bots/bot-escort/task.js";
|
||||||
import { adminAgent } from "./agent/bots/bot-escort-admin/agent.js"
|
import { adminAgent } from "./agent/bots/bot-escort-admin/agent.js"
|
||||||
import { getUserByToken } from "./utils/user_service.js";
|
import { getUserByToken } from "./utils/user_service.js";
|
||||||
import { isAdmin } from "./utils/permissions.js";
|
import { resolveEscortAdminRole } from "./utils/permissions.js";
|
||||||
import logger from "./utils/logger.js";
|
import logger from "./utils/logger.js";
|
||||||
import { createUserLimiter } from "./middleware/ratelimit.js";
|
import { createUserLimiter } from "./middleware/ratelimit.js";
|
||||||
import {
|
import {
|
||||||
@@ -201,14 +201,16 @@ export default class WebSocketServerManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (msg.agent === 'escort-admin') {
|
if (msg.agent === 'escort-admin') {
|
||||||
// 管理端 agent 含写库/环境变量等高危工具,必须校验管理员角色,防止普通用户越权
|
// 管理端 agent 按角色收敛工具:管理员可跨用户/写库,陪诊员只能看本人订单。
|
||||||
if (!isAdmin(userInfo)) {
|
// 身份以 Employee 记录为准,普通 C 端账号不能借 agent 升级权限。
|
||||||
send('system', 'error', '无管理员权限', msg.id);
|
const role = await resolveEscortAdminRole(userInfo);
|
||||||
|
if (!role) {
|
||||||
|
send('system', 'error', '当前账号未绑定在职陪诊员档案,请联系管理员开通', msg.id);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
await adminAgent.streamChat(userInfo, [msg], (source, type, content, id) => {
|
await adminAgent.streamChat(userInfo, [msg], (source, type, content, id) => {
|
||||||
send(source, type, content, id);
|
send(source, type, content, id);
|
||||||
});
|
}, role);
|
||||||
} else {
|
} else {
|
||||||
await chatTask.streamChat(userInfo, msg, (source, type, content, id) => {
|
await chatTask.streamChat(userInfo, msg, (source, type, content, id) => {
|
||||||
send(source, type, content, id);
|
send(source, type, content, id);
|
||||||
|
|||||||
Reference in New Issue
Block a user