feat(org): 平铺就医信息并支持分院/院区

This commit is contained in:
lik
2026-11-03 16:59:52 +08:00
parent 47fdb91dbe
commit 07d4ce27bf
7 changed files with 390 additions and 101 deletions
@@ -1,24 +1,44 @@
import { tool } from "@langchain/core/tools";
import { z } from "zod";
import { DBModel } from "../../../../../models/index.js";
import { escapeRegex } from "../utils.js";
import { escapeRegex, parseObjectId } from "../utils.js";
const hospitalInfoListTool = tool(
async ({ keyword }) => {
async ({ keyword, parentId }) => {
try {
const filter = {};
// 只列可用医院;分院/院区也是医院,用 parentId 区分归属
const filter = { type: "hospital", status: "active" };
if (parentId) {
const id = parseObjectId(parentId);
if (!id) return { success: false, error: `Invalid parent ID: ${parentId}` };
filter.parentId = id;
}
if (keyword) {
const re = { $regex: escapeRegex(keyword), $options: "i" };
filter.$or = [{ name: re }, { pinyin: re }, { pinyinFL: re }];
filter.$or = [{ name: re }, { shortName: re }, { pinyin: re }, { pinyinFL: re }];
}
// 轻量列表:只取 id+名称,用于先定位医院,再按 id 查详情
// 轻量列表:只取定位所需字段,再按 id 查详情
const [total, orgs] = await Promise.all([
DBModel.Organization.countDocuments(filter),
DBModel.Organization.find(filter).sort({ name: 1 }).limit(1000).select("name").lean(),
DBModel.Organization.find(filter)
.sort({ name: 1 })
.limit(1000)
.select("name shortName parentId address.city")
.lean(),
]);
return { success: true, total, data: orgs.map((o) => ({ id: o._id, name: o.name })) };
return {
success: true,
total,
data: orgs.map((o) => ({
id: o._id,
name: o.name,
shortName: o.shortName ?? "",
parentId: o.parentId ?? null,
city: o.address?.city ?? "",
})),
};
} catch (error) {
return { success: false, error: error.message };
}
@@ -26,9 +46,10 @@ const hospitalInfoListTool = tool(
{
name: "hospital_info_list",
description:
"获取医院(名称、id)对列表,支持按名称/拼音关键词过滤,不传关键词返回全部。",
"获取医院(名称、id)对列表,支持按名称/简称/拼音关键词过滤。传 parentId 只列该院的分院/院区;不传则列全部可用医院,parentId 为空的是总院。",
schema: z.object({
keyword: z.string().optional().describe("医院名称/拼音/拼音首字母关键词(如 协和、xiehe),不传返回全部"),
keyword: z.string().optional().describe("医院名称/简称/拼音/拼音首字母关键词(如 协和、xiehe),不传返回全部"),
parentId: z.string().optional().describe("总院 id:提供时只返回该院的分院/院区"),
}),
}
);
@@ -1,48 +1,93 @@
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 { escapeRegex, parseObjectId } from "../utils.js";
// 只返回就医需要的字段,避免把历史遗留字段整文档带出
const HOSPITAL_FIELDS = [
"name", "shortName", "parentId", "level", "nature", "address", "contact", "status",
"overview", "photos", "departments", "doctors", "guides", "infoUpdatedAt", "infoUpdatedBy",
].join(" ");
function toHospitalView(org, parentName = "") {
return {
_id: org._id,
name: org.name,
shortName: org.shortName ?? "",
parentId: org.parentId ?? null,
parentName,
level: org.level ?? "",
nature: org.nature ?? "",
address: org.address ?? {},
contact: org.contact ?? {},
status: org.status ?? "",
overview: org.overview ?? "",
photos: org.photos ?? [],
departments: org.departments ?? [],
doctors: org.doctors ?? [],
guides: org.guides ?? {},
infoUpdatedAt: org.infoUpdatedAt ?? null,
infoUpdatedBy: org.infoUpdatedBy ?? "",
};
}
// 分院/院区返回总院名称,便于上层确认归属
async function getParentNames(orgs) {
const ids = orgs.map((o) => o.parentId).filter(Boolean);
if (ids.length === 0) return new Map();
const parents = await DBModel.Organization.find({ _id: { $in: ids } })
.select("name")
.lean();
return new Map(parents.map((p) => [String(p._id), p.name]));
}
/**
* 医院信息查询工具
*
* 两种用法:
* - 传 hospitalId:返回该院完整档案(id 可先用 hospital_info_list 获取);
* - 传 hospitalName:按名称模糊查询,并可按科室 / 医生名过滤,返回面向上层展示的精简字段。
* - 传 hospitalName:按名称/简称/拼音模糊查询,并可按科室 / 医生名过滤,返回面向上层展示的精简字段。
*/
const hospitalInfoQueryTool = tool(
async ({ hospitalId, hospitalName, department, doctorName }) => {
try {
if (hospitalId) {
if (!mongoose.Types.ObjectId.isValid(hospitalId)) {
const id = parseObjectId(hospitalId);
if (!id) {
return { success: false, error: `Invalid hospital ID: ${hospitalId}` };
}
const org = await DBModel.Organization.findById(hospitalId).lean();
const org = await DBModel.Organization.findOne({ _id: id, type: "hospital" })
.select(HOSPITAL_FIELDS)
.lean();
if (!org) {
return { success: false, error: `未找到 id 为「${hospitalId}」的机构` };
return { success: false, error: `未找到 id 为「${hospitalId}」的医院` };
}
return { success: true, total: 1, data: [org] };
const parents = await getParentNames([org]);
return { success: true, total: 1, data: [toHospitalView(org, parents.get(String(org.parentId)) ?? "")] };
}
if (!hospitalName) {
return { success: false, error: "请提供 hospitalId 或 hospitalName" };
}
const filter = { name: { $regex: escapeRegex(hospitalName), $options: "i" } };
const re = { $regex: escapeRegex(hospitalName), $options: "i" };
const filter = {
type: "hospital",
$or: [{ name: re }, { shortName: re }, { pinyin: re }, { pinyinFL: re }],
};
// 医院总量小,一次最多取 10 家,命中过多时由调用方细化名称
const [total, orgs] = await Promise.all([
DBModel.Organization.countDocuments(filter),
DBModel.Organization.find(filter).limit(10).lean(),
DBModel.Organization.find(filter).select(HOSPITAL_FIELDS).limit(10).lean(),
]);
if (total === 0) {
return { success: false, error: `未找到名称包含「${hospitalName}」的机构` };
return { success: false, error: `未找到名称包含「${hospitalName}」的医院` };
}
const parents = await getParentNames(orgs);
const data = orgs.map((org) => {
const fa = org.forAgent ?? {};
let departments = fa.departments ?? [];
let doctors = fa.doctors ?? [];
let departments = org.departments ?? [];
let doctors = org.doctors ?? [];
if (department) {
departments = departments.filter((d) => d.name?.includes(department));
doctors = doctors.filter((d) => d.department?.includes(department));
@@ -51,16 +96,9 @@ const hospitalInfoQueryTool = tool(
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 ?? [],
...toHospitalView(org, parents.get(String(org.parentId)) ?? ""),
departments,
doctors,
guides: fa.guides ?? {},
};
});
@@ -72,13 +110,13 @@ const hospitalInfoQueryTool = tool(
{
name: "hospital_info_query",
description:
"查询医院就医信息。传 hospitalId 返回该院完整档案;传 hospitalName 按名称模糊查询,可再按科室、医生名过滤,返回医院总览(门诊/挂号/缴费/医保/交通)、科室(位置/电话/就诊提示)、医生(职称/擅长/号别/坐班)、场景指南、照片。最多返回 10 家医院。",
"查询医院就医信息。传 hospitalId 返回该院完整档案;传 hospitalName 按名称/简称/拼音模糊查询,可再按科室、医生名过滤,返回医院总览(门诊/挂号/缴费/医保/交通)、科室(位置/电话/就诊提示)、医生(职称/擅长/号别/坐班)、场景指南、照片。分院/院区会返回 parentName。最多返回 10 家医院。",
schema: z.object({
hospitalId: z
.string()
.optional()
.describe("医院 id(MongoDB ObjectId,来自 hospital_info_list),提供时忽略其他查询条件"),
hospitalName: z.string().optional().describe("医院名称,支持模糊匹配(如 协和)"),
hospitalName: z.string().optional().describe("医院名称/简称,支持模糊匹配(如 协和、协和西院)"),
department: z.string().optional().describe("科室名称过滤(如 风湿免疫科、放射科)"),
doctorName: z.string().optional().describe("医生姓名过滤"),
}),
+63 -31
View File
@@ -1,30 +1,50 @@
import { tool } from "@langchain/core/tools";
import { z } from "zod";
import { DBModel } from "../../../../../models/index.js";
import { escapeRegex } from "../utils.js";
import { escapeRegex, parseObjectId } from "../utils.js";
const hospitalInfoSetTool = tool(
async ({ hospitalName, section, action, content, guides, entry, entryName, updatedBy }) => {
async ({ hospitalId, hospitalName, section, action, content, guides, entry, entryName, updatedBy }) => {
try {
if (!hospitalName) {
return { success: false, error: "hospitalName 不能为空" };
}
// 优先按 id 定位;名称只允许唯一命中,分院/院区多命中时返回候选让上层确认
let org = null;
// 定位医院:名称必须唯一命中;转义正则元字符,避免非法表达式与 ReDoS
const orgs = await DBModel.Organization.find({
name: { $regex: escapeRegex(hospitalName), $options: "i" },
}).exec();
if (orgs.length === 0) {
return { success: false, error: `未找到名称包含「${hospitalName}」的机构,请确认医院名称后重试` };
if (hospitalId) {
const id = parseObjectId(hospitalId);
if (!id) {
return { success: false, error: `Invalid hospital ID: ${hospitalId}` };
}
org = await DBModel.Organization.findOne({ _id: id, type: "hospital" }).exec();
if (!org) {
return { success: false, error: `未找到 id 为「${hospitalId}」的医院` };
}
} else {
if (!hospitalName) {
return { success: false, error: "请提供 hospitalId 或 hospitalName" };
}
const re = { $regex: escapeRegex(hospitalName), $options: "i" };
const orgs = await DBModel.Organization.find({
type: "hospital",
$or: [{ name: re }, { shortName: re }, { pinyin: re }, { pinyinFL: re }],
}).exec();
if (orgs.length === 0) {
return { success: false, error: `未找到名称包含「${hospitalName}」的医院,请确认名称后重试` };
}
if (orgs.length > 1) {
return {
success: false,
error: `名称包含「${hospitalName}」的医院有 ${orgs.length} 家,请改用 hospitalId 精确写入`,
candidates: orgs.map((o) => ({
id: o._id,
name: o.name,
shortName: o.shortName ?? "",
parentId: o.parentId ?? null,
city: o.address?.city ?? "",
})),
};
}
org = orgs[0];
}
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 = {};
@@ -33,13 +53,13 @@ const hospitalInfoSetTool = tool(
if (typeof content !== "string") {
return { success: false, error: "overview 需要提供 content 文本(写入前请先查询现有内容并合并)" };
}
update["forAgent.overview"] = content;
update.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 ?? {}) };
const merged = { ...(org.guides ?? {}) };
for (const [key, value] of Object.entries(guides)) {
if (value === null) {
delete merged[key];
@@ -47,10 +67,10 @@ const hospitalInfoSetTool = tool(
merged[key] = value;
}
}
update["forAgent.guides"] = merged;
update.guides = merged;
} else if (section === "photos" || section === "departments" || section === "doctors") {
// 列表区块:按锚点 upsert(新增或整条替换)/ remove
const list = [...(fa[section] ?? [])];
const list = [...(org[section] ?? [])];
if (action === "upsert") {
if (!entry || typeof entry !== "object") {
@@ -74,7 +94,7 @@ const hospitalInfoSetTool = tool(
} else {
list.push(entry);
}
update[`forAgent.${section}`] = list;
update[section] = list;
} else if (action === "remove") {
if (!entryName) {
return {
@@ -83,9 +103,9 @@ const hospitalInfoSetTool = tool(
};
}
if (section === "photos") {
update[`forAgent.${section}`] = list.filter((p) => p.url !== entryName);
update[section] = list.filter((p) => p.url !== entryName);
} else {
update[`forAgent.${section}`] = list.filter((d) => d.name !== entryName);
update[section] = list.filter((d) => d.name !== entryName);
}
} else {
return { success: false, error: "列表区块(photos/departments/doctors)需要指定 action: upsert 或 remove" };
@@ -94,13 +114,24 @@ const hospitalInfoSetTool = tool(
return { success: false, error: "未知的 section,可选值:overview / photos / departments / doctors / guides" };
}
update["forAgent.updatedAt"] = new Date();
update.infoUpdatedAt = new Date();
if (updatedBy) {
update["forAgent.updatedBy"] = updatedBy;
update.infoUpdatedBy = updatedBy;
}
const updated = await DBModel.Organization.findByIdAndUpdate(org._id, { $set: update }, { new: true }).exec();
return { success: true, data: updated.forAgent };
return {
success: true,
data: {
overview: updated.overview ?? "",
photos: updated.photos ?? [],
departments: updated.departments ?? [],
doctors: updated.doctors ?? [],
guides: updated.guides ?? {},
infoUpdatedAt: updated.infoUpdatedAt ?? null,
infoUpdatedBy: updated.infoUpdatedBy ?? "",
},
};
} catch (error) {
return { success: false, error: error.message };
}
@@ -108,9 +139,10 @@ const hospitalInfoSetTool = tool(
{
name: "hospital_info_set",
description:
"录入/更新医院就医信息。按区块维护:overview(医院级文本,全量替换,先查后改避免丢失)、guides(场景指南键值对,浅合并)、photos/departments/doctors(列表,按锚点 upsert 或 remove)。医院名称必须唯一命中。",
"录入/更新医院就医信息。优先用 hospitalId 定位;只用 hospitalName 时必须唯一命中,分院/院区多命中会返回 candidates,需改用 hospitalId。按区块维护:overview(医院级文本,全量替换,先查后改避免丢失)、guides(场景指南键值对,浅合并)、photos/departments/doctors(列表,按锚点 upsert 或 remove)。",
schema: z.object({
hospitalName: z.string().describe("医院名称(需唯一命中,如 北京协和医院)"),
hospitalId: z.string().optional().describe("医院 id(MongoDB ObjectId,来自 hospital_info_list),优先使用"),
hospitalName: z.string().optional().describe("医院名称/简称(仅在唯一命中时可用,分院/院区建议改用 hospitalId)"),
section: z
.enum(["overview", "photos", "departments", "doctors", "guides"])
.describe("要更新的区块"),
+4 -1
View File
@@ -8,14 +8,17 @@ import {
const QUERY_PROMPT = `查询:
- 先用 hospital_info_list 拿到医院(名称、id)列表定位医院,再用 hospital_info_query 传 hospitalId 获取完整信息。
- 需要按医院名称、科室、医生名过滤时,直接用 hospital_info_query(hospitalName/department/doctorName)。
- 列表结果里 parentId 为空的是总院,非空的是分院/院区;可用 hospital_info_list 的 parentId 参数只列某院院区。
- 需要按医院名称、简称、科室、医生名过滤时,直接用 hospital_info_query(hospitalName/department/doctorName)。
- 出诊信息等时效性数据必须注明信息更新时间,并提示用户以医院最新公告为准。
- 查不到的信息如实告知,禁止编造。`;
const MAINTAIN_PROMPT = `维护:
- 写入优先用 hospitalId 定位;只用名称时必须唯一命中,多命中会返回 candidates,先确认 id 再写。
- overview:医院级文本全量替换,写入前先查询现有内容,合并整理后整体写入,不得丢失原有信息。
- guides:场景键值对浅合并,新增场景直接传键值对;删除场景将值置为 null。
- photos/departments/doctors:列表按锚点操作,锚点为 照片=url、科室=name、医生=name+department;upsert 新增或整条更新,remove 删除。
- 科室、医生、就医信息都写入具体院区,不要写到总院再指望分院自动继承。
- doctors 的 detail 包含职称、擅长方向、号别(普通/专家/特需)、坐班与停诊安排。
- 尽量提供 updatedBy 记录操作人。图片只存 URL 链接,不负责图片上传。`;
+35 -37
View File
@@ -5,17 +5,27 @@ import { pinyin } from "pinyin-pro";
/**
* Organization Schema
* 组织/机构基础信息,支持医院、诊所、体检中心等多种机构类型
* 组织/机构基础信息,支持医院、诊所、体检中心等多种机构类型;
* 分院/院区用 parentId 指向总院,先只做一层,更多层级按需再加
*/
const OrganizationSchema = mongoose.Schema(
{
// 基础信息
name: { type: String, required: true, index: true, comment: "机构名称" },
shortName: { type: String, default: "", comment: "机构简称" },
name: { type: String, required: true, index: true, comment: "机构全称;分院/院区需带总院名,如 北京协和医院西单院区" },
shortName: { type: String, default: "", comment: "机构简称/别名,如 协和西院" },
pinyin: { type: String, default: "", index: true, comment: "机构名称全拼(小写无分隔,用于搜索)" },
pinyinFL: { type: String, default: "", index: true, comment: "机构名称拼音首字母(用于搜索)" },
code: { type: String, unique: true, sparse: true, comment: "机构编码(不填时字段缺省,避免与 unique sparse 索引冲突)" },
// 层级:分院/院区指向总院,总院为空。够用先只做一层,更多层级按需再加
parentId: {
type: mongoose.Schema.Types.ObjectId,
ref: "organization",
default: null,
index: true,
comment: "上级机构ID(分院/院区指向总院,总院为空)",
},
// 机构类型
type: {
type: String,
@@ -67,38 +77,26 @@ const OrganizationSchema = mongoose.Schema(
description: { type: String, default: "", comment: "机构简介" },
remark: { type: String, default: "", comment: "备注" },
// 就医信息(agent-first:少字段、大文本;由 AI 助手录入维护,供查询与看病指导)
forAgent: {
updatedAt: { type: Date, comment: "最近更新时间" },
updatedBy: { type: String, default: "", comment: "最近更新人" },
// 医院级总览:门诊时间、挂号渠道、缴费、医保、异地备案、交通停车,一个文本块全包含
overview: { type: String, default: "", comment: "医院级信息全文(门诊/挂号/缴费/医保/交通)" },
// 医院/导引照片
photos: [{
url: { type: String, default: "", comment: "图片链接" },
caption: { type: String, default: "", comment: "说明(医院照片/导引照片 + 描述)" },
}],
// 科室:name 是锚点;detail 包含位置/电话/临床还是医技/就诊提示全文
departments: [{
name: { type: String, comment: "科室名称(锚点)" },
detail: { type: String, default: "", comment: "科室信息全文(位置/电话/类型/就诊提示)" },
photo: { type: String, default: "", comment: "科室位置导引照片链接" },
}],
// 医生:name+department 是锚点;detail 包含职称/擅长/号别/坐班停诊全文
doctors: [{
name: { type: String, comment: "医生姓名(锚点)" },
department: { type: String, comment: "所属科室(锚点)" },
detail: { type: String, default: "", comment: "医生信息全文(职称/擅长/号别/坐班停诊)" },
photo: { type: String, default: "", comment: "医生照片链接" },
}],
// 场景指南:初诊/复诊/住院/检查须知/老人服务等,键为场景名,值为文本,结构自由演化
guides: { type: mongoose.Schema.Types.Mixed, comment: "场景指南(键为场景名,值为文本)" },
},
// 就医信息:agent-first,字段已平铺,先保留够用的部分,后续按需增加
overview: { type: String, default: "", comment: "医院级信息全文(门诊/挂号/缴费/医保/交通)" },
photos: [{
url: { type: String, default: "", comment: "图片链接" },
caption: { type: String, default: "", comment: "说明(医院照片/导引照片 + 描述)" },
}],
departments: [{
name: { type: String, comment: "科室名称(锚点)" },
detail: { type: String, default: "", comment: "科室信息全文(位置/电话/类型/就诊提示)" },
photo: { type: String, default: "", comment: "科室位置导引照片链接" },
}],
doctors: [{
name: { type: String, comment: "医生姓名(锚点)" },
department: { type: String, comment: "所属科室(锚点)" },
detail: { type: String, default: "", comment: "医生信息全文(职称/擅长/号别/坐班停诊)" },
photo: { type: String, default: "", comment: "医生照片链接" },
}],
guides: { type: mongoose.Schema.Types.Mixed, comment: "场景指南(键为场景名,值为文本)" },
infoUpdatedAt: { type: Date, comment: "就医信息最近更新时间" },
infoUpdatedBy: { type: String, default: "", comment: "就医信息最近更新人" },
// 元数据
meta: {
@@ -141,14 +139,14 @@ OrganizationSchema.pre("save", function (next) {
// ==================== 静态方法 ====================
/**
* 根据名称/拼音/拼音首字母模糊查询机构
* 根据名称/简称/拼音/拼音首字母模糊查询机构
*/
OrganizationSchema.statics.findByName = async function (name, options = {}) {
const { page = 1, pageSize = 20 } = options;
const skip = (page - 1) * pageSize;
const escaped = String(name).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const re = { $regex: escaped, $options: "i" };
return await this.find({ $or: [{ name: re }, { pinyin: re }, { pinyinFL: re }] })
return await this.find({ $or: [{ name: re }, { shortName: re }, { pinyin: re }, { pinyinFL: re }] })
.skip(skip)
.limit(pageSize)
.exec();
+51
View File
@@ -0,0 +1,51 @@
/**
* 一次性迁移:把 organization 里旧的 forAgent 嵌套字段平铺到顶层。
*
* 用法:在 api/health 下执行 `node scripts/migrate_organization_flat.js`
* 迁移后删除 forAgent,工具只读写顶层字段。
*/
import { DBModel } from "../models/index.js";
DBModel.init();
const conn = DBModel.dbConnection;
async function migrate() {
const result = await DBModel.Organization.updateMany(
{ forAgent: { $exists: true } },
[
{
$set: {
overview: { $ifNull: ["$overview", "$forAgent.overview"] },
photos: { $ifNull: ["$photos", "$forAgent.photos"] },
departments: { $ifNull: ["$departments", "$forAgent.departments"] },
doctors: { $ifNull: ["$doctors", "$forAgent.doctors"] },
guides: { $ifNull: ["$guides", "$forAgent.guides"] },
infoUpdatedAt: { $ifNull: ["$infoUpdatedAt", "$forAgent.updatedAt"] },
infoUpdatedBy: { $ifNull: ["$infoUpdatedBy", "$forAgent.updatedBy"] },
},
},
{ $unset: "forAgent" },
]
);
console.log(`migrated: matched=${result.matchedCount}, modified=${result.modifiedCount}`);
await conn.close();
}
if (conn.readyState === 1) {
migrate().catch((error) => {
console.error(error);
process.exit(1);
});
} else {
conn.once("connected", () => {
migrate().catch((error) => {
console.error(error);
process.exit(1);
});
});
conn.once("error", (error) => {
console.error(error);
process.exit(1);
});
}
+146
View File
@@ -0,0 +1,146 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import mongoose from "mongoose";
import { DBModel } from "../models/index.js";
import {
hospitalInfoListTool,
hospitalInfoQueryTool,
hospitalInfoSetTool,
} from "../agent/infra/tools/index.js";
const MAIN_ID = "64b000000000000000000101";
const BRANCH_ID = "64b000000000000000000102";
const MAIN_NAME = "中国医学科学院北京协和医院";
const BRANCH_NAME = "中国医学科学院北京协和医院西单院区";
const main = {
_id: new mongoose.Types.ObjectId(MAIN_ID),
name: MAIN_NAME,
shortName: "北京协和医院",
parentId: null,
type: "hospital",
status: "active",
address: { city: "北京" },
overview: "总院就医信息",
departments: [{ name: "心内科", detail: "总院心内科" }],
doctors: [],
photos: [],
guides: {},
};
const branch = {
_id: new mongoose.Types.ObjectId(BRANCH_ID),
name: BRANCH_NAME,
shortName: "协和西院",
parentId: main._id,
type: "hospital",
status: "active",
address: { city: "北京" },
overview: "西单院区就医信息",
departments: [{ name: "妇科内分泌与生殖医学中心", detail: "西单院区" }],
doctors: [],
photos: [],
guides: {},
// 历史遗留字段不应再被工具读取
forAgent: { overview: "旧字段", departments: [{ name: "旧科室" }] },
};
function parseResult(result) {
return typeof result === "string" ? JSON.parse(result) : result;
}
// Mongoose Query 链式调用的最小桩
function createQuery(docs, calls, method, filter) {
calls.push({ method, filter });
return {
sort() { return this; },
limit() { return this; },
select() { return this; },
lean() { return Promise.resolve(docs); },
exec() { return Promise.resolve(docs); },
};
}
function createOrganizationStub({ list = [], one = null, count = 0 } = {}) {
const calls = [];
return {
calls,
countDocuments(filter) {
calls.push({ method: "countDocuments", filter });
return Promise.resolve(count);
},
find(filter) {
return createQuery(list, calls, "find", filter);
},
findOne(filter) {
return createQuery(one, calls, "findOne", filter);
},
findByIdAndUpdate(id, update) {
calls.push({ method: "findByIdAndUpdate", id, update });
return {
exec() {
return Promise.resolve({ ...one, ...update.$set });
},
};
},
};
}
function withOrganization(stub, fn) {
const previous = DBModel.Organization;
DBModel.Organization = stub;
return Promise.resolve(fn()).finally(() => {
DBModel.Organization = previous;
});
}
test("医院列表只查可用医院,并可按 parentId 列院区", async () => {
const stub = createOrganizationStub({ list: [main, branch], count: 2 });
await withOrganization(stub, async () => {
const byKeyword = parseResult(await hospitalInfoListTool.invoke({ keyword: "协和" }));
assert.equal(byKeyword.success, true);
assert.equal(byKeyword.data.length, 2);
assert.equal(byKeyword.data[1].parentId.toHexString(), MAIN_ID);
assert.equal(stub.calls[0].filter.type, "hospital");
assert.equal(stub.calls[0].filter.status, "active");
assert.ok(stub.calls[0].filter.$or.some((item) => "shortName" in item));
const byParent = parseResult(await hospitalInfoListTool.invoke({ parentId: MAIN_ID }));
assert.equal(byParent.success, true);
assert.equal(stub.calls.at(-2).filter.parentId.toHexString(), MAIN_ID);
});
});
test("按分院 id 查询返回平铺字段和总院名称", async () => {
const stub = createOrganizationStub({ list: [main], one: branch });
await withOrganization(stub, async () => {
const result = parseResult(await hospitalInfoQueryTool.invoke({ hospitalId: BRANCH_ID }));
assert.equal(result.success, true);
assert.equal(result.data[0].name, BRANCH_NAME);
assert.equal(result.data[0].parentName, MAIN_NAME);
assert.equal(result.data[0].overview, "西单院区就医信息");
assert.equal(result.data[0].departments[0].name, "妇科内分泌与生殖医学中心");
});
});
test("名称命中多家时返回候选,改用 id 后写入顶层字段", async () => {
const stub = createOrganizationStub({ list: [main, branch], one: branch, count: 2 });
await withOrganization(stub, async () => {
const ambiguous = parseResult(await hospitalInfoSetTool.invoke({ hospitalName: "协和", section: "overview", content: "x" }));
assert.equal(ambiguous.success, false);
assert.equal(ambiguous.candidates.length, 2);
assert.ok(ambiguous.candidates.every((item) => item.id));
const set = parseResult(
await hospitalInfoSetTool.invoke({ hospitalId: BRANCH_ID, section: "overview", content: "新就医信息" })
);
assert.equal(set.success, true);
assert.equal(set.data.overview, "新就医信息");
assert.ok(set.data.infoUpdatedAt);
const update = stub.calls.at(-1).update.$set;
assert.equal(update.overview, "新就医信息");
assert.equal("forAgent.overview" in update, false);
});
});