fix(agent): 医院工具切换至 hospital 集合并补齐支付约束
hospital_info_list/query/set 改为读写 hospital 集合,适配 entityName/nicknames/fudanRank;医院子代理与提示词同步字段口径;health_profile_set 更新启用 schema 校验;escort_record_set 限制线下收款方式,存在未支付流水时禁止改价。
This commit is contained in:
@@ -62,7 +62,7 @@ class EscortAdminPrompts {
|
|||||||
# 工具对应
|
# 工具对应
|
||||||
- 陪诊单查询 escort_record_query(患者名/手机号/状态/陪诊员ID/日期范围,日期用 YYYY-MM-DD);改单 escort_record_set
|
- 陪诊单查询 escort_record_query(患者名/手机号/状态/陪诊员ID/日期范围,日期用 YYYY-MM-DD);改单 escort_record_set
|
||||||
- 患者健康档案:patient-record 子代理(查询与写入)
|
- 患者健康档案:patient-record 子代理(查询与写入)
|
||||||
- 医院信息:hospital-info 子代理(查询与维护)
|
- 医院基础信息(地址/电话/等级/科室名称):hospital-info 子代理(查询与维护);医生出诊、挂号/就诊指南库中没有,用 web_search / web_fetch
|
||||||
- 陪诊员档案 employee_query(姓名/工号/角色/状态);评价 employee_review_query
|
- 陪诊员档案 employee_query(姓名/工号/角色/状态);评价 employee_review_query
|
||||||
- 天气、路线、日期、节假日;网页信息用 web_search / web_fetch
|
- 天气、路线、日期、节假日;网页信息用 web_search / web_fetch
|
||||||
|
|
||||||
@@ -104,7 +104,7 @@ ${buildReference(userInfo, "管理员")}`;
|
|||||||
- 我的订单:escort_record_query(患者名/状态/日期范围 YYYY-MM-DD)
|
- 我的订单:escort_record_query(患者名/状态/日期范围 YYYY-MM-DD)
|
||||||
- 开始/完成服务、写陪诊备注:escort_record_set
|
- 开始/完成服务、写陪诊备注:escort_record_set
|
||||||
- 本人档案:employee_query
|
- 本人档案:employee_query
|
||||||
- 医院信息(科室楼层、电话、挂号/就诊指南、医生出诊):hospital-info 子代理(只读)
|
- 医院基础信息(地址、电话、等级、科室名称):hospital-info 子代理(只读);医生出诊、挂号/就诊指南库中没有,用 web_search / web_fetch
|
||||||
- 天气、路线、日期、节假日:http_get / get_calendar_info / get_year_holidays;网页信息用 web_search / web_fetch
|
- 天气、路线、日期、节假日:http_get / get_calendar_info / get_year_holidays;网页信息用 web_search / web_fetch
|
||||||
|
|
||||||
# 严谨边界
|
# 严谨边界
|
||||||
|
|||||||
@@ -134,7 +134,29 @@ const escortRecordSetTool = tool(
|
|||||||
} else if (payment.status !== undefined && !["unpaid", "paid"].includes(payment.status)) {
|
} else if (payment.status !== undefined && !["unpaid", "paid"].includes(payment.status)) {
|
||||||
return { success: false, error: "未收款订单只能标记为 unpaid 或 paid" };
|
return { success: false, error: "未收款订单只能标记为 unpaid 或 paid" };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 收款方式只允许线下现金/转账;线上微信由支付回调写入,手工标记会没有支付流水
|
||||||
|
if (payment.method !== undefined) {
|
||||||
|
if (!["offline_cash", "offline_transfer"].includes(payment.method)) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "收款方式只允许 offline_cash(现金)或 offline_transfer(转账);线上微信由支付回调写入",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
update["payment.method"] = payment.method;
|
||||||
|
}
|
||||||
|
|
||||||
if (payment.totalFee !== undefined) {
|
if (payment.totalFee !== undefined) {
|
||||||
|
// 存在未支付流水时禁止改价:微信侧金额与本地流水错位会导致对账失败
|
||||||
|
if (Number(payment.totalFee) !== (Number(effectivePay.totalFee) || 0)) {
|
||||||
|
const openPayment = await DBModel.PaymentRecord.findOne({
|
||||||
|
recordId: orderId,
|
||||||
|
status: "created",
|
||||||
|
});
|
||||||
|
if (openPayment) {
|
||||||
|
return { success: false, error: "订单存在未支付流水,请先在用户端关闭支付后再修改金额" };
|
||||||
|
}
|
||||||
|
}
|
||||||
update["payment.totalFee"] = payment.totalFee;
|
update["payment.totalFee"] = payment.totalFee;
|
||||||
}
|
}
|
||||||
if (payment.paidFee !== undefined) {
|
if (payment.paidFee !== undefined) {
|
||||||
@@ -202,7 +224,7 @@ const escortRecordSetTool = tool(
|
|||||||
{
|
{
|
||||||
name: "escort_record_set",
|
name: "escort_record_set",
|
||||||
description:
|
description:
|
||||||
"Update escort record fields by record ID (_id). Supports updating service status, cancel status (none/requested/cancelled), notes (patientNote, escortNote, medicalSummary), inquiry (medicalHistory, demand), and payment (totalFee, paidFee, status). Only provided fields will be updated.",
|
"Update escort record fields by record ID (_id). Supports updating service status, cancel status (none/requested/cancelled), notes (patientNote, escortNote, medicalSummary), inquiry (medicalHistory, demand), and payment (totalFee, paidFee, status, method). Only provided fields will be updated. Online WeChat payment can only be written by the payment callback; use offline_cash/offline_transfer for manual collection.",
|
||||||
schema: z.object({
|
schema: z.object({
|
||||||
orderId: z
|
orderId: z
|
||||||
.string()
|
.string()
|
||||||
@@ -242,6 +264,12 @@ const escortRecordSetTool = tool(
|
|||||||
.enum(["unpaid", "partial", "paid", "refunding", "refunded"])
|
.enum(["unpaid", "partial", "paid", "refunding", "refunded"])
|
||||||
.optional()
|
.optional()
|
||||||
.describe("Payment status: unpaid, partial, paid, refunding, refunded"),
|
.describe("Payment status: unpaid, partial, paid, refunding, refunded"),
|
||||||
|
method: z
|
||||||
|
.enum(["offline_cash", "offline_transfer"])
|
||||||
|
.optional()
|
||||||
|
.describe(
|
||||||
|
"Actual collection method for manual/offline payments: offline_cash (现金), offline_transfer (线下转账). Online WeChat is written by the payment callback."
|
||||||
|
),
|
||||||
})
|
})
|
||||||
.optional()
|
.optional()
|
||||||
.describe("Payment information to update"),
|
.describe("Payment information to update"),
|
||||||
|
|||||||
@@ -106,10 +106,11 @@ const healthProfileSetTool = tool(
|
|||||||
}
|
}
|
||||||
update["meta.updatetime"] = new Date();
|
update["meta.updatetime"] = new Date();
|
||||||
|
|
||||||
|
// 与接口层一致:身高/体重范围、性别枚举等 schema 约束必须在更新时生效
|
||||||
const updated = await DBModel.HealthProfile.findByIdAndUpdate(
|
const updated = await DBModel.HealthProfile.findByIdAndUpdate(
|
||||||
profileId,
|
profileId,
|
||||||
{ $set: update },
|
{ $set: update },
|
||||||
{ new: true }
|
{ new: true, runValidators: true }
|
||||||
);
|
);
|
||||||
if (!updated) {
|
if (!updated) {
|
||||||
return { success: false, error: `未找到 ID 为 ${profileId} 的健康档案` };
|
return { success: false, error: `未找到 ID 为 ${profileId} 的健康档案` };
|
||||||
|
|||||||
@@ -1,42 +1,37 @@
|
|||||||
import { tool } from "@langchain/core/tools";
|
import { tool } from "@langchain/core/tools";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { DBModel } from "../../../../../models/index.js";
|
import { DBModel } from "../../../../../models/index.js";
|
||||||
import { escapeRegex, parseObjectId } from "../utils.js";
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 医院列表工具
|
||||||
|
*
|
||||||
|
* 数据源统一为 hospital 集合(老 organization 集合已不再维护医院基础信息)。
|
||||||
|
* 分院/院区是独立医院记录,通过 entityName 归到同一主体。
|
||||||
|
*/
|
||||||
const hospitalInfoListTool = tool(
|
const hospitalInfoListTool = tool(
|
||||||
async ({ keyword, parentId }) => {
|
async ({ keyword, entityName, page = 1, pageSize = 50 }) => {
|
||||||
try {
|
try {
|
||||||
// 只列可用医院;分院/院区也是医院,用 parentId 区分归属
|
const result = await DBModel.Hospital.findHospitals({
|
||||||
const filter = { type: "hospital", status: "active" };
|
page,
|
||||||
if (parentId) {
|
pageSize,
|
||||||
const id = parseObjectId(parentId);
|
keyword,
|
||||||
if (!id) return { success: false, error: `Invalid parent ID: ${parentId}` };
|
entityName,
|
||||||
filter.parentId = id;
|
});
|
||||||
}
|
|
||||||
if (keyword) {
|
|
||||||
const re = { $regex: escapeRegex(keyword), $options: "i" };
|
|
||||||
filter.$or = [{ name: re }, { shortName: re }, { pinyin: re }, { pinyinFL: re }];
|
|
||||||
}
|
|
||||||
|
|
||||||
// 轻量列表:只取定位所需字段,再按 id 查详情
|
|
||||||
const [total, orgs] = await Promise.all([
|
|
||||||
DBModel.Organization.countDocuments(filter),
|
|
||||||
DBModel.Organization.find(filter)
|
|
||||||
.sort({ name: 1 })
|
|
||||||
.limit(1000)
|
|
||||||
.select("name shortName parentId address.city")
|
|
||||||
.lean(),
|
|
||||||
]);
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
total,
|
total: result.total,
|
||||||
data: orgs.map((o) => ({
|
page: result.page,
|
||||||
id: o._id,
|
pageSize: result.pageSize,
|
||||||
name: o.name,
|
data: result.list.map((hospital) => ({
|
||||||
shortName: o.shortName ?? "",
|
id: hospital._id,
|
||||||
parentId: o.parentId ?? null,
|
name: hospital.name ?? "",
|
||||||
city: o.address?.city ?? "",
|
entityName: hospital.entityName ?? "",
|
||||||
|
province: hospital.province ?? "",
|
||||||
|
city: hospital.city ?? "",
|
||||||
|
address: hospital.address ?? "",
|
||||||
|
phone: hospital.phone ?? "",
|
||||||
|
level: hospital.level ?? "",
|
||||||
})),
|
})),
|
||||||
};
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -46,10 +41,24 @@ const hospitalInfoListTool = tool(
|
|||||||
{
|
{
|
||||||
name: "hospital_info_list",
|
name: "hospital_info_list",
|
||||||
description:
|
description:
|
||||||
"获取医院(名称、id)对列表,支持按名称/简称/拼音关键词过滤。传 parentId 只列该院的分院/院区;不传则列全部可用医院,parentId 为空的是总院。",
|
"获取医院(名称、id)对列表,支持按名称/主体名称/拼音/拼音首字母/昵称关键词过滤。传 entityName 只列该主体的分院/院区;不传则按复旦榜档位排序列出全部医院。",
|
||||||
schema: z.object({
|
schema: z.object({
|
||||||
keyword: z.string().optional().describe("医院名称/简称/拼音/拼音首字母关键词(如 协和、xiehe),不传返回全部"),
|
keyword: z
|
||||||
parentId: z.string().optional().describe("总院 id:提供时只返回该院的分院/院区"),
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe("医院名称/主体名称/拼音/拼音首字母/昵称关键词(如 协和、xiehe、bjxhyy),不传返回全部"),
|
||||||
|
entityName: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe("主体名称:提供时只返回该主体下的医院(含本院与分院/院区)"),
|
||||||
|
page: z.number().int().min(1).optional().describe("页码,从 1 开始"),
|
||||||
|
pageSize: z
|
||||||
|
.number()
|
||||||
|
.int()
|
||||||
|
.min(1)
|
||||||
|
.max(200)
|
||||||
|
.optional()
|
||||||
|
.describe("每页数量(1-200),默认 50"),
|
||||||
}),
|
}),
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,108 +1,73 @@
|
|||||||
import { tool } from "@langchain/core/tools";
|
import { tool } from "@langchain/core/tools";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { DBModel } from "../../../../../models/index.js";
|
import { DBModel } from "../../../../../models/index.js";
|
||||||
import { escapeRegex, parseObjectId } from "../utils.js";
|
import { parseObjectId } from "../utils.js";
|
||||||
|
|
||||||
// 只返回就医需要的字段,避免把历史遗留字段整文档带出
|
// 医院基础信息字段:新 hospital 集合没有 overview/doctors/guides/photos
|
||||||
const HOSPITAL_FIELDS = [
|
function toHospitalView(hospital) {
|
||||||
"name", "shortName", "parentId", "level", "nature", "address", "contact", "status",
|
|
||||||
"overview", "photos", "departments", "doctors", "guides", "infoUpdatedAt", "infoUpdatedBy",
|
|
||||||
].join(" ");
|
|
||||||
|
|
||||||
function toHospitalView(org, parentName = "") {
|
|
||||||
return {
|
return {
|
||||||
_id: org._id,
|
id: hospital._id,
|
||||||
name: org.name,
|
name: hospital.name ?? "",
|
||||||
shortName: org.shortName ?? "",
|
entityName: hospital.entityName ?? "",
|
||||||
parentId: org.parentId ?? null,
|
nicknames: hospital.nicknames ?? [],
|
||||||
parentName,
|
province: hospital.province ?? "",
|
||||||
level: org.level ?? "",
|
city: hospital.city ?? "",
|
||||||
nature: org.nature ?? "",
|
address: hospital.address ?? "",
|
||||||
address: org.address ?? {},
|
phone: hospital.phone ?? "",
|
||||||
contact: org.contact ?? {},
|
level: hospital.level ?? "",
|
||||||
status: org.status ?? "",
|
departments: hospital.departments ?? [],
|
||||||
overview: org.overview ?? "",
|
fudanRank: hospital.fudanRank ?? null,
|
||||||
photos: org.photos ?? [],
|
updatedAt: hospital.meta?.updatetime ?? null,
|
||||||
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 获取);
|
* - 传 hospitalId:返回该院完整档案(id 可先用 hospital_info_list 获取);
|
||||||
* - 传 hospitalName:按名称/简称/拼音模糊查询,并可按科室 / 医生名过滤,返回面向上层展示的精简字段。
|
* - 传 hospitalName:按名称/主体名称/拼音/昵称模糊查询,并可按科室名过滤。
|
||||||
*/
|
*/
|
||||||
const hospitalInfoQueryTool = tool(
|
const hospitalInfoQueryTool = tool(
|
||||||
async ({ hospitalId, hospitalName, department, doctorName }) => {
|
async ({ hospitalId, hospitalName, department }) => {
|
||||||
try {
|
try {
|
||||||
if (hospitalId) {
|
if (hospitalId) {
|
||||||
const id = parseObjectId(hospitalId);
|
const id = parseObjectId(hospitalId);
|
||||||
if (!id) {
|
if (!id) {
|
||||||
return { success: false, error: `Invalid hospital ID: ${hospitalId}` };
|
return { success: false, error: `Invalid hospital ID: ${hospitalId}` };
|
||||||
}
|
}
|
||||||
const org = await DBModel.Organization.findOne({ _id: id, type: "hospital" })
|
const hospital = await DBModel.Hospital.findHospitalById(id);
|
||||||
.select(HOSPITAL_FIELDS)
|
if (!hospital) {
|
||||||
.lean();
|
|
||||||
if (!org) {
|
|
||||||
return { success: false, error: `未找到 id 为「${hospitalId}」的医院` };
|
return { success: false, error: `未找到 id 为「${hospitalId}」的医院` };
|
||||||
}
|
}
|
||||||
const parents = await getParentNames([org]);
|
return { success: true, total: 1, data: [toHospitalView(hospital)] };
|
||||||
return { success: true, total: 1, data: [toHospitalView(org, parents.get(String(org.parentId)) ?? "")] };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!hospitalName) {
|
if (!hospitalName) {
|
||||||
return { success: false, error: "请提供 hospitalId 或 hospitalName" };
|
return { success: false, error: "请提供 hospitalId 或 hospitalName" };
|
||||||
}
|
}
|
||||||
|
|
||||||
const re = { $regex: escapeRegex(hospitalName), $options: "i" };
|
// 医院总量有限,一次最多取 10 家,命中过多时由调用方细化名称
|
||||||
const filter = {
|
const result = await DBModel.Hospital.findHospitals({
|
||||||
type: "hospital",
|
page: 1,
|
||||||
$or: [{ name: re }, { shortName: re }, { pinyin: re }, { pinyinFL: re }],
|
pageSize: 10,
|
||||||
};
|
keyword: hospitalName,
|
||||||
// 医院总量小,一次最多取 10 家,命中过多时由调用方细化名称
|
});
|
||||||
const [total, orgs] = await Promise.all([
|
if (result.total === 0) {
|
||||||
DBModel.Organization.countDocuments(filter),
|
|
||||||
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 keyword = String(department ?? "").trim();
|
||||||
const data = orgs.map((org) => {
|
const data = result.list.map((hospital) => {
|
||||||
let departments = org.departments ?? [];
|
const view = toHospitalView(hospital);
|
||||||
let doctors = org.doctors ?? [];
|
if (!keyword) return view;
|
||||||
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 {
|
return {
|
||||||
...toHospitalView(org, parents.get(String(org.parentId)) ?? ""),
|
...view,
|
||||||
departments,
|
departments: view.departments.filter((name) => String(name).includes(keyword)),
|
||||||
doctors,
|
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
return { success: true, total, data };
|
return { success: true, total: result.total, data };
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return { success: false, error: error.message };
|
return { success: false, error: error.message };
|
||||||
}
|
}
|
||||||
@@ -110,15 +75,17 @@ const hospitalInfoQueryTool = tool(
|
|||||||
{
|
{
|
||||||
name: "hospital_info_query",
|
name: "hospital_info_query",
|
||||||
description:
|
description:
|
||||||
"查询医院就医信息。传 hospitalId 返回该院完整档案;传 hospitalName 按名称/简称/拼音模糊查询,可再按科室、医生名过滤,返回医院总览(门诊/挂号/缴费/医保/交通)、科室(位置/电话/就诊提示)、医生(职称/擅长/号别/坐班)、场景指南、照片。分院/院区会返回 parentName。最多返回 10 家医院。",
|
"查询医院基础信息(省市、地址、电话、等级、科室名称列表、复旦榜档位与昵称)。传 hospitalId 返回该院完整档案;传 hospitalName 按名称/主体名称/拼音/昵称模糊查询,可再按科室名过滤;最多返回 10 家医院。资料库不含医生出诊、挂号流程与就医指南,问到这些需说明库中没有并用 web_search / web_fetch 查官方信息。",
|
||||||
schema: z.object({
|
schema: z.object({
|
||||||
hospitalId: z
|
hospitalId: z
|
||||||
.string()
|
.string()
|
||||||
.optional()
|
.optional()
|
||||||
.describe("医院 id(MongoDB ObjectId,来自 hospital_info_list),提供时忽略其他查询条件"),
|
.describe("医院 id(MongoDB ObjectId,来自 hospital_info_list),提供时忽略其他查询条件"),
|
||||||
hospitalName: z.string().optional().describe("医院名称/简称,支持模糊匹配(如 协和、协和西院)"),
|
hospitalName: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe("医院名称/主体名称/拼音/昵称,支持模糊匹配(如 协和、xiehe、陆总)"),
|
||||||
department: z.string().optional().describe("科室名称过滤(如 风湿免疫科、放射科)"),
|
department: z.string().optional().describe("科室名称过滤(如 风湿免疫科、放射科)"),
|
||||||
doctorName: z.string().optional().describe("医生姓名过滤"),
|
|
||||||
}),
|
}),
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,176 +1,126 @@
|
|||||||
import { tool } from "@langchain/core/tools";
|
import { tool } from "@langchain/core/tools";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { DBModel } from "../../../../../models/index.js";
|
import { DBModel } from "../../../../../models/index.js";
|
||||||
import { escapeRegex, parseObjectId } from "../utils.js";
|
import { parseObjectId } from "../utils.js";
|
||||||
|
|
||||||
|
const TEXT_FIELDS = ["name", "entityName", "province", "city", "address", "phone", "level"];
|
||||||
|
|
||||||
|
function toHospitalView(hospital) {
|
||||||
|
return {
|
||||||
|
id: hospital._id,
|
||||||
|
name: hospital.name ?? "",
|
||||||
|
entityName: hospital.entityName ?? "",
|
||||||
|
nicknames: hospital.nicknames ?? [],
|
||||||
|
province: hospital.province ?? "",
|
||||||
|
city: hospital.city ?? "",
|
||||||
|
address: hospital.address ?? "",
|
||||||
|
phone: hospital.phone ?? "",
|
||||||
|
level: hospital.level ?? "",
|
||||||
|
departments: hospital.departments ?? [],
|
||||||
|
fudanRank: hospital.fudanRank ?? null,
|
||||||
|
updatedAt: hospital.meta?.updatetime ?? null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 医院基础信息维护工具
|
||||||
|
*
|
||||||
|
* 只维护 hospital 集合的基础字段;名称/主体变化时用模型静态方法,
|
||||||
|
* 由服务端同步拼音、昵称与复旦榜档位,避免手写派生字段。
|
||||||
|
*/
|
||||||
const hospitalInfoSetTool = tool(
|
const hospitalInfoSetTool = tool(
|
||||||
async ({ hospitalId, hospitalName, section, action, content, guides, entry, entryName, updatedBy }) => {
|
async ({ hospitalId, hospitalName, name, entityName, province, city, address, phone, departments, level }) => {
|
||||||
try {
|
try {
|
||||||
// 优先按 id 定位;名称只允许唯一命中,分院/院区多命中时返回候选让上层确认
|
// 优先按 id 定位;只用名称时必须唯一命中,多命中返回候选让上层确认
|
||||||
let org = null;
|
let hospital = null;
|
||||||
|
|
||||||
if (hospitalId) {
|
if (hospitalId) {
|
||||||
const id = parseObjectId(hospitalId);
|
const id = parseObjectId(hospitalId);
|
||||||
if (!id) {
|
if (!id) {
|
||||||
return { success: false, error: `Invalid hospital ID: ${hospitalId}` };
|
return { success: false, error: `Invalid hospital ID: ${hospitalId}` };
|
||||||
}
|
}
|
||||||
org = await DBModel.Organization.findOne({ _id: id, type: "hospital" }).exec();
|
hospital = await DBModel.Hospital.findHospitalById(id);
|
||||||
if (!org) {
|
if (!hospital) {
|
||||||
return { success: false, error: `未找到 id 为「${hospitalId}」的医院` };
|
return { success: false, error: `未找到 id 为「${hospitalId}」的医院` };
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if (!hospitalName) {
|
if (!hospitalName) {
|
||||||
return { success: false, error: "请提供 hospitalId 或 hospitalName" };
|
return { success: false, error: "请提供 hospitalId 或 hospitalName" };
|
||||||
}
|
}
|
||||||
const re = { $regex: escapeRegex(hospitalName), $options: "i" };
|
const result = await DBModel.Hospital.findHospitals({
|
||||||
const orgs = await DBModel.Organization.find({
|
page: 1,
|
||||||
type: "hospital",
|
pageSize: 10,
|
||||||
$or: [{ name: re }, { shortName: re }, { pinyin: re }, { pinyinFL: re }],
|
keyword: hospitalName,
|
||||||
}).exec();
|
});
|
||||||
if (orgs.length === 0) {
|
if (result.total === 0) {
|
||||||
return { success: false, error: `未找到名称包含「${hospitalName}」的医院,请确认名称后重试` };
|
return { success: false, error: `未找到名称包含「${hospitalName}」的医院,请确认名称后重试` };
|
||||||
}
|
}
|
||||||
if (orgs.length > 1) {
|
if (result.total > 1) {
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: `名称包含「${hospitalName}」的医院有 ${orgs.length} 家,请改用 hospitalId 精确写入`,
|
error: `名称包含「${hospitalName}」的医院有 ${result.total} 家,请改用 hospitalId 精确写入`,
|
||||||
candidates: orgs.map((o) => ({
|
candidates: result.list.map((item) => ({
|
||||||
id: o._id,
|
id: item._id,
|
||||||
name: o.name,
|
name: item.name,
|
||||||
shortName: o.shortName ?? "",
|
entityName: item.entityName ?? "",
|
||||||
parentId: o.parentId ?? null,
|
city: item.city ?? "",
|
||||||
city: o.address?.city ?? "",
|
|
||||||
})),
|
})),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
org = orgs[0];
|
hospital = result.list[0];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const input = { name, entityName, province, city, address, phone, level };
|
||||||
const update = {};
|
const update = {};
|
||||||
|
for (const key of TEXT_FIELDS) {
|
||||||
if (section === "overview") {
|
const value = input[key];
|
||||||
// 文本块全量替换
|
if (value === undefined) continue;
|
||||||
if (typeof content !== "string") {
|
const text = String(value ?? "").trim();
|
||||||
return { success: false, error: "overview 需要提供 content 文本(写入前请先查询现有内容并合并)" };
|
if (key === "name" && !text) {
|
||||||
|
return { success: false, error: "医院名称不能为空" };
|
||||||
}
|
}
|
||||||
update.overview = content;
|
update[key] = text;
|
||||||
} else if (section === "guides") {
|
|
||||||
// 场景键值对浅合并,值为 null 表示删除该场景
|
|
||||||
if (!guides || typeof guides !== "object" || Array.isArray(guides)) {
|
|
||||||
return { success: false, error: "guides 需要提供对象,键为场景名,值为文本(值为 null 表示删除该场景)" };
|
|
||||||
}
|
|
||||||
const merged = { ...(org.guides ?? {}) };
|
|
||||||
for (const [key, value] of Object.entries(guides)) {
|
|
||||||
if (value === null) {
|
|
||||||
delete merged[key];
|
|
||||||
} else {
|
|
||||||
merged[key] = value;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
update.guides = merged;
|
|
||||||
} else if (section === "photos" || section === "departments" || section === "doctors") {
|
|
||||||
// 列表区块:按锚点 upsert(新增或整条替换)/ remove
|
|
||||||
const list = [...(org[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[section] = list;
|
|
||||||
} else if (action === "remove") {
|
|
||||||
if (!entryName) {
|
|
||||||
return {
|
|
||||||
success: false,
|
|
||||||
error: `remove 需要提供 entryName(${section === "photos" ? "照片url" : section === "doctors" ? "医生姓名" : "科室名称"})`,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
if (section === "photos") {
|
|
||||||
update[section] = list.filter((p) => p.url !== entryName);
|
|
||||||
} else {
|
|
||||||
update[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.infoUpdatedAt = new Date();
|
if (departments !== undefined) {
|
||||||
if (updatedBy) {
|
if (!Array.isArray(departments)) {
|
||||||
update.infoUpdatedBy = updatedBy;
|
return { success: false, error: "科室需为字符串数组" };
|
||||||
|
}
|
||||||
|
update.departments = departments.map((item) => String(item ?? "").trim()).filter(Boolean);
|
||||||
}
|
}
|
||||||
|
|
||||||
const updated = await DBModel.Organization.findByIdAndUpdate(org._id, { $set: update }, { new: true }).exec();
|
if (Object.keys(update).length === 0) {
|
||||||
return {
|
return { success: false, error: "未提供任何要更新的字段" };
|
||||||
success: true,
|
}
|
||||||
data: {
|
|
||||||
overview: updated.overview ?? "",
|
const updated = await DBModel.Hospital.updateHospitalById(hospital._id, update);
|
||||||
photos: updated.photos ?? [],
|
if (!updated) {
|
||||||
departments: updated.departments ?? [],
|
return { success: false, error: `未找到 id 为「${hospital._id}」的医院` };
|
||||||
doctors: updated.doctors ?? [],
|
}
|
||||||
guides: updated.guides ?? {},
|
|
||||||
infoUpdatedAt: updated.infoUpdatedAt ?? null,
|
return { success: true, data: toHospitalView(updated) };
|
||||||
infoUpdatedBy: updated.infoUpdatedBy ?? "",
|
|
||||||
},
|
|
||||||
};
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
if (error?.code === 11000) {
|
||||||
|
return { success: false, error: "医院名称已存在,请使用「主体名称-分院名称」格式避免重名" };
|
||||||
|
}
|
||||||
return { success: false, error: error.message };
|
return { success: false, error: error.message };
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "hospital_info_set",
|
name: "hospital_info_set",
|
||||||
description:
|
description:
|
||||||
"录入/更新医院就医信息。优先用 hospitalId 定位;只用 hospitalName 时必须唯一命中,分院/院区多命中会返回 candidates,需改用 hospitalId。按区块维护:overview(医院级文本,全量替换,先查后改避免丢失)、guides(场景指南键值对,浅合并)、photos/departments/doctors(列表,按锚点 upsert 或 remove)。",
|
"录入/更新医院基础信息。优先用 hospitalId 定位;只用 hospitalName 时必须唯一命中,多命中会返回 candidates,需改用 hospitalId。可更新 name、entityName、province、city、address、phone、departments(科室名称数组,整体替换)、level。名称是唯一键,改名会自动同步拼音、昵称与复旦榜档位;分院/院区是独立记录,名称约定为「主体名称-分院名称」。",
|
||||||
schema: z.object({
|
schema: z.object({
|
||||||
hospitalId: z.string().optional().describe("医院 id(MongoDB ObjectId,来自 hospital_info_list),优先使用"),
|
hospitalId: z.string().optional().describe("医院 id(MongoDB ObjectId,来自 hospital_info_list),优先使用"),
|
||||||
hospitalName: z.string().optional().describe("医院名称/简称(仅在唯一命中时可用,分院/院区建议改用 hospitalId)"),
|
hospitalName: z.string().optional().describe("医院名称/主体名称/拼音/昵称(仅在唯一命中时可用)"),
|
||||||
section: z
|
name: z.string().optional().describe("医院名称;分院/院区用「主体名称-分院名称」"),
|
||||||
.enum(["overview", "photos", "departments", "doctors", "guides"])
|
entityName: z.string().optional().describe("主体名称;留空时由名称自动派生"),
|
||||||
.describe("要更新的区块"),
|
province: z.string().optional().describe("省份,如 北京市"),
|
||||||
action: z
|
city: z.string().optional().describe("城市,如 北京市"),
|
||||||
.enum(["set", "upsert", "remove"])
|
address: z.string().optional().describe("医院地址"),
|
||||||
.optional()
|
phone: z.string().optional().describe("联系电话"),
|
||||||
.describe("操作类型:overview/guides 用 set;photos/departments/doctors 用 upsert 或 remove"),
|
departments: z.array(z.string()).optional().describe("科室名称数组,整体替换"),
|
||||||
content: z.string().optional().describe("overview 区块的完整文本(全量替换)"),
|
level: z.string().optional().describe("医院等级,如 三级甲等"),
|
||||||
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或姓名),用于审计"),
|
|
||||||
}),
|
}),
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -4,23 +4,22 @@ import {
|
|||||||
hospitalInfoSetTool,
|
hospitalInfoSetTool,
|
||||||
} from "../infra/tools/index.js";
|
} from "../infra/tools/index.js";
|
||||||
|
|
||||||
// 医院就医信息查询与维护(医生资料/坐班、科室、看病指南等)
|
// 医院基础信息查询与维护(名称/主体/院区、省市地址、电话、等级、科室名称、复旦榜档位)
|
||||||
|
|
||||||
const QUERY_PROMPT = `查询:
|
const QUERY_PROMPT = `查询:
|
||||||
- 先用 hospital_info_list 拿到医院(名称、id)列表定位医院,再用 hospital_info_query 传 hospitalId 获取完整信息。
|
- 先用 hospital_info_list 拿到医院(名称、id)列表定位医院,再用 hospital_info_query 传 hospitalId 获取完整信息。
|
||||||
- 列表结果里 parentId 为空的是总院,非空的是分院/院区;可用 hospital_info_list 的 parentId 参数只列某院院区。
|
- 分院/院区是独立医院记录,与本院共享 entityName;可用 hospital_info_list 的 entityName 参数只列同一主体下的医院。
|
||||||
- 需要按医院名称、简称、科室、医生名过滤时,直接用 hospital_info_query(hospitalName/department/doctorName)。
|
- 需要按名称、主体名、拼音、昵称或科室名过滤时,直接用 hospital_info_query(hospitalName/department)。
|
||||||
- 出诊信息等时效性数据必须注明信息更新时间,并提示用户以医院最新公告为准。
|
- 资料库只有医院基础信息(省市、地址、电话、等级、科室名称列表、复旦榜档位与昵称),不含医生出诊、挂号流程和就医指南;问到这些要如实说明库中没有,不能编造。
|
||||||
|
- 电话、地址等可能变动,回答时提示以医院最新公告为准。
|
||||||
- 查不到的信息如实告知,禁止编造。`;
|
- 查不到的信息如实告知,禁止编造。`;
|
||||||
|
|
||||||
const MAINTAIN_PROMPT = `维护:
|
const MAINTAIN_PROMPT = `维护:
|
||||||
- 写入优先用 hospitalId 定位;只用名称时必须唯一命中,多命中会返回 candidates,先确认 id 再写。
|
- 写入优先用 hospitalId 定位;只用名称时必须唯一命中,多命中会返回 candidates,先确认 id 再写。
|
||||||
- overview:医院级文本全量替换,写入前先查询现有内容,合并整理后整体写入,不得丢失原有信息。
|
- 只维护基础字段:name、entityName、province、city、address、phone、departments(科室名称数组,整体替换)、level。
|
||||||
- guides:场景键值对浅合并,新增场景直接传键值对;删除场景将值置为 null。
|
- 名称是唯一键;改名会自动同步拼音、昵称与复旦榜档位,不要手写 pinyin/nicknames/fudanRank。
|
||||||
- photos/departments/doctors:列表按锚点操作,锚点为 照片=url、科室=name、医生=name+department;upsert 新增或整条更新,remove 删除。
|
- 分院/院区是独立医院记录,名称约定为「主体名称-分院名称」,不要写到总院上。
|
||||||
- 科室、医生、就医信息都写入具体院区,不要写到总院再指望分院自动继承。
|
- 资料库不维护医生出诊、挂号流程与就医指南,不要尝试写入这些内容。`;
|
||||||
- doctors 的 detail 包含职称、擅长方向、号别(普通/专家/特需)、坐班与停诊安排。
|
|
||||||
- 尽量提供 updatedBy 记录操作人。图片只存 URL 链接,不负责图片上传。`;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {Object} model
|
* @param {Object} model
|
||||||
@@ -30,9 +29,9 @@ const MAINTAIN_PROMPT = `维护:
|
|||||||
export const createHospitalInfoSubagent = (model, { allowWrite = false } = {}) => ({
|
export const createHospitalInfoSubagent = (model, { allowWrite = false } = {}) => ({
|
||||||
name: "hospital-info-subagent",
|
name: "hospital-info-subagent",
|
||||||
description: allowWrite
|
description: allowWrite
|
||||||
? "查询和维护医院基本资料及就医信息:医院电话、医生资料、出诊信息、科室位置与电话、看病指南(门诊/挂号/医保/住院/检查须知)等"
|
? "查询和维护医院基础信息:医院名称与院区、省市地址、联系电话、医院等级、科室名称列表、复旦榜档位与常用昵称"
|
||||||
: "查询医院基本资料及就医信息:医院电话、医生资料、出诊信息、科室位置与电话、看病指南(门诊/挂号/医保/住院/检查须知)等",
|
: "查询医院基础信息:医院名称与院区、省市地址、联系电话、医院等级、科室名称列表、复旦榜档位与常用昵称",
|
||||||
systemPrompt: `你负责医院就医信息的查询${allowWrite ? "、维护、更新、核验" : ""}。
|
systemPrompt: `你负责医院基础信息的查询${allowWrite ? "、维护、更新、核验" : ""}。
|
||||||
|
|
||||||
${QUERY_PROMPT}${allowWrite ? `\n\n${MAINTAIN_PROMPT}` : ""}`,
|
${QUERY_PROMPT}${allowWrite ? `\n\n${MAINTAIN_PROMPT}` : ""}`,
|
||||||
model,
|
model,
|
||||||
|
|||||||
+133
-88
@@ -12,135 +12,180 @@ import {
|
|||||||
const MAIN_ID = "64b000000000000000000101";
|
const MAIN_ID = "64b000000000000000000101";
|
||||||
const BRANCH_ID = "64b000000000000000000102";
|
const BRANCH_ID = "64b000000000000000000102";
|
||||||
const MAIN_NAME = "中国医学科学院北京协和医院";
|
const MAIN_NAME = "中国医学科学院北京协和医院";
|
||||||
const BRANCH_NAME = "中国医学科学院北京协和医院西单院区";
|
const BRANCH_NAME = "中国医学科学院北京协和医院-西单院区";
|
||||||
|
|
||||||
const main = {
|
const main = {
|
||||||
_id: new mongoose.Types.ObjectId(MAIN_ID),
|
_id: new mongoose.Types.ObjectId(MAIN_ID),
|
||||||
name: MAIN_NAME,
|
name: MAIN_NAME,
|
||||||
shortName: "北京协和医院",
|
entityName: MAIN_NAME,
|
||||||
parentId: null,
|
nicknames: ["协和", "北京协和"],
|
||||||
type: "hospital",
|
pinyin: "zhongguoyixuekexueyuanbeijingxieheyiyuan",
|
||||||
status: "active",
|
pinyinFL: "zgyxkxybjxhyy",
|
||||||
address: { city: "北京" },
|
province: "北京市",
|
||||||
overview: "总院就医信息",
|
city: "北京市",
|
||||||
departments: [{ name: "心内科", detail: "总院心内科" }],
|
address: "东城区帅府园1号",
|
||||||
doctors: [],
|
phone: "010-69151188",
|
||||||
photos: [],
|
level: "三级甲等",
|
||||||
guides: {},
|
departments: ["心内科", "风湿免疫科"],
|
||||||
|
fudanRank: { rank: 1, grade: "A+++++", order: 1 },
|
||||||
|
meta: { updatetime: new Date("2026-11-05T00:00:00.000Z") },
|
||||||
};
|
};
|
||||||
|
|
||||||
const branch = {
|
const branch = {
|
||||||
|
...main,
|
||||||
_id: new mongoose.Types.ObjectId(BRANCH_ID),
|
_id: new mongoose.Types.ObjectId(BRANCH_ID),
|
||||||
name: BRANCH_NAME,
|
name: BRANCH_NAME,
|
||||||
shortName: "协和西院",
|
address: "西城区大木仓胡同41号",
|
||||||
parentId: main._id,
|
departments: ["妇科内分泌与生殖医学中心"],
|
||||||
type: "hospital",
|
|
||||||
status: "active",
|
|
||||||
address: { city: "北京" },
|
|
||||||
overview: "西单院区就医信息",
|
|
||||||
departments: [{ name: "妇科内分泌与生殖医学中心", detail: "西单院区" }],
|
|
||||||
doctors: [],
|
|
||||||
photos: [],
|
|
||||||
guides: {},
|
|
||||||
// 历史遗留字段不应再被工具读取
|
|
||||||
forAgent: { overview: "旧字段", departments: [{ name: "旧科室" }] },
|
|
||||||
};
|
};
|
||||||
|
|
||||||
function parseResult(result) {
|
function parseResult(result) {
|
||||||
return typeof result === "string" ? JSON.parse(result) : result;
|
return typeof result === "string" ? JSON.parse(result) : result;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Mongoose Query 链式调用的最小桩
|
/**
|
||||||
function createQuery(docs, calls, method, filter) {
|
* hospital 模型桩:工具通过模型静态方法读写,桩直接记录调用参数
|
||||||
calls.push({ method, filter });
|
*/
|
||||||
return {
|
function createHospitalStub({ list = [], total = list.length, one = null } = {}) {
|
||||||
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 = [];
|
const calls = [];
|
||||||
return {
|
return {
|
||||||
calls,
|
calls,
|
||||||
countDocuments(filter) {
|
findHospitals(options) {
|
||||||
calls.push({ method: "countDocuments", filter });
|
calls.push({ method: "findHospitals", options });
|
||||||
return Promise.resolve(count);
|
return Promise.resolve({
|
||||||
|
list,
|
||||||
|
total,
|
||||||
|
page: options.page ?? 1,
|
||||||
|
pageSize: options.pageSize ?? 20,
|
||||||
|
});
|
||||||
},
|
},
|
||||||
find(filter) {
|
findHospitalById(id) {
|
||||||
return createQuery(list, calls, "find", filter);
|
calls.push({ method: "findHospitalById", id });
|
||||||
|
return Promise.resolve(one);
|
||||||
},
|
},
|
||||||
findOne(filter) {
|
updateHospitalById(id, update) {
|
||||||
return createQuery(one, calls, "findOne", filter);
|
calls.push({ method: "updateHospitalById", id, update });
|
||||||
},
|
return Promise.resolve({
|
||||||
findByIdAndUpdate(id, update) {
|
...one,
|
||||||
calls.push({ method: "findByIdAndUpdate", id, update });
|
...update,
|
||||||
return {
|
// 模拟模型静态方法自动补派生字段
|
||||||
exec() {
|
pinyin: "paiban",
|
||||||
return Promise.resolve({ ...one, ...update.$set });
|
fudanRank: { rank: 1, grade: "A+++++", order: 1 },
|
||||||
},
|
});
|
||||||
};
|
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function withOrganization(stub, fn) {
|
function withHospital(stub, fn) {
|
||||||
const previous = DBModel.Organization;
|
const previous = DBModel.Hospital;
|
||||||
DBModel.Organization = stub;
|
DBModel.Hospital = stub;
|
||||||
return Promise.resolve(fn()).finally(() => {
|
return Promise.resolve(fn()).finally(() => {
|
||||||
DBModel.Organization = previous;
|
DBModel.Hospital = previous;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
test("医院列表只查可用医院,并可按 parentId 列院区", async () => {
|
test("医院列表走 hospital 集合,并支持关键词与主体名称过滤", async () => {
|
||||||
const stub = createOrganizationStub({ list: [main, branch], count: 2 });
|
const stub = createHospitalStub({ list: [main, branch], total: 2 });
|
||||||
await withOrganization(stub, async () => {
|
await withHospital(stub, async () => {
|
||||||
const byKeyword = parseResult(await hospitalInfoListTool.invoke({ keyword: "协和" }));
|
const byKeyword = parseResult(await hospitalInfoListTool.invoke({ keyword: "协和" }));
|
||||||
assert.equal(byKeyword.success, true);
|
assert.equal(byKeyword.success, true);
|
||||||
assert.equal(byKeyword.data.length, 2);
|
assert.equal(byKeyword.total, 2);
|
||||||
assert.equal(byKeyword.data[1].parentId.toHexString(), MAIN_ID);
|
assert.equal(byKeyword.data[0].entityName, MAIN_NAME);
|
||||||
assert.equal(stub.calls[0].filter.type, "hospital");
|
assert.equal(byKeyword.data[0].phone, "010-69151188");
|
||||||
assert.equal(stub.calls[0].filter.status, "active");
|
assert.equal(stub.calls[0].options.keyword, "协和");
|
||||||
assert.ok(stub.calls[0].filter.$or.some((item) => "shortName" in item));
|
|
||||||
|
|
||||||
const byParent = parseResult(await hospitalInfoListTool.invoke({ parentId: MAIN_ID }));
|
const byEntity = parseResult(
|
||||||
assert.equal(byParent.success, true);
|
await hospitalInfoListTool.invoke({ entityName: MAIN_NAME })
|
||||||
assert.equal(stub.calls.at(-2).filter.parentId.toHexString(), MAIN_ID);
|
);
|
||||||
|
assert.equal(byEntity.success, true);
|
||||||
|
assert.equal(stub.calls.at(-1).options.entityName, MAIN_NAME);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
test("按分院 id 查询返回平铺字段和总院名称", async () => {
|
test("按 id 查询返回 hospital 基础信息与派生字段", async () => {
|
||||||
const stub = createOrganizationStub({ list: [main], one: branch });
|
const stub = createHospitalStub({ one: branch });
|
||||||
await withOrganization(stub, async () => {
|
await withHospital(stub, async () => {
|
||||||
const result = parseResult(await hospitalInfoQueryTool.invoke({ hospitalId: BRANCH_ID }));
|
const result = parseResult(await hospitalInfoQueryTool.invoke({ hospitalId: BRANCH_ID }));
|
||||||
assert.equal(result.success, true);
|
assert.equal(result.success, true);
|
||||||
assert.equal(result.data[0].name, BRANCH_NAME);
|
assert.equal(result.data[0].name, BRANCH_NAME);
|
||||||
assert.equal(result.data[0].parentName, MAIN_NAME);
|
assert.equal(result.data[0].entityName, MAIN_NAME);
|
||||||
assert.equal(result.data[0].overview, "西单院区就医信息");
|
assert.deepEqual(result.data[0].nicknames, ["协和", "北京协和"]);
|
||||||
assert.equal(result.data[0].departments[0].name, "妇科内分泌与生殖医学中心");
|
assert.equal(result.data[0].fudanRank.grade, "A+++++");
|
||||||
|
assert.deepEqual(result.data[0].departments, ["妇科内分泌与生殖医学中心"]);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
test("名称命中多家时返回候选,改用 id 后写入顶层字段", async () => {
|
test("按名称查询可按科室过滤,科室为字符串数组", async () => {
|
||||||
const stub = createOrganizationStub({ list: [main, branch], one: branch, count: 2 });
|
const stub = createHospitalStub({ list: [main, branch], total: 2 });
|
||||||
await withOrganization(stub, async () => {
|
await withHospital(stub, async () => {
|
||||||
const ambiguous = parseResult(await hospitalInfoSetTool.invoke({ hospitalName: "协和", section: "overview", content: "x" }));
|
const result = parseResult(
|
||||||
assert.equal(ambiguous.success, false);
|
await hospitalInfoQueryTool.invoke({ hospitalName: "协和", department: "风湿" })
|
||||||
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(result.success, true);
|
||||||
assert.equal(set.data.overview, "新就医信息");
|
assert.equal(result.total, 2);
|
||||||
assert.ok(set.data.infoUpdatedAt);
|
assert.deepEqual(result.data[0].departments, ["风湿免疫科"]);
|
||||||
|
assert.deepEqual(result.data[1].departments, []);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
const update = stub.calls.at(-1).update.$set;
|
test("查询缺少 id 与名称时明确报错", async () => {
|
||||||
assert.equal(update.overview, "新就医信息");
|
const stub = createHospitalStub();
|
||||||
assert.equal("forAgent.overview" in update, false);
|
await withHospital(stub, async () => {
|
||||||
|
const result = parseResult(await hospitalInfoQueryTool.invoke({}));
|
||||||
|
assert.equal(result.success, false);
|
||||||
|
assert.match(result.error, /hospitalId 或 hospitalName/);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test("写入时名称命中多家返回候选,不落库", async () => {
|
||||||
|
const stub = createHospitalStub({ list: [main, branch], total: 2, one: branch });
|
||||||
|
await withHospital(stub, async () => {
|
||||||
|
const result = parseResult(
|
||||||
|
await hospitalInfoSetTool.invoke({ hospitalName: "协和", phone: "010-12345678" })
|
||||||
|
);
|
||||||
|
assert.equal(result.success, false);
|
||||||
|
assert.equal(result.candidates.length, 2);
|
||||||
|
assert.ok(result.candidates.every((item) => item.id));
|
||||||
|
assert.equal(stub.calls.filter((call) => call.method === "updateHospitalById").length, 0);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test("按 id 写入只提交基础字段,派生字段由模型同步", async () => {
|
||||||
|
const stub = createHospitalStub({ one: branch });
|
||||||
|
await withHospital(stub, async () => {
|
||||||
|
const result = parseResult(
|
||||||
|
await hospitalInfoSetTool.invoke({
|
||||||
|
hospitalId: BRANCH_ID,
|
||||||
|
phone: " 010-12345678 ",
|
||||||
|
departments: ["心内科", " ", "风湿免疫科"],
|
||||||
|
})
|
||||||
|
);
|
||||||
|
assert.equal(result.success, true);
|
||||||
|
|
||||||
|
const updateCall = stub.calls.find((call) => call.method === "updateHospitalById");
|
||||||
|
assert.equal(String(updateCall.id), BRANCH_ID);
|
||||||
|
assert.equal(updateCall.update.phone, "010-12345678");
|
||||||
|
assert.deepEqual(updateCall.update.departments, ["心内科", "风湿免疫科"]);
|
||||||
|
// 拼音/昵称/复旦榜档位不允许手写
|
||||||
|
assert.equal("pinyin" in updateCall.update, false);
|
||||||
|
assert.equal("nicknames" in updateCall.update, false);
|
||||||
|
assert.equal("fudanRank" in updateCall.update, false);
|
||||||
|
assert.equal(result.data.phone, "010-12345678");
|
||||||
|
assert.deepEqual(result.data.departments, ["心内科", "风湿免疫科"]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test("写入未提供字段或名称为空时拒绝", async () => {
|
||||||
|
const stub = createHospitalStub({ one: branch });
|
||||||
|
await withHospital(stub, async () => {
|
||||||
|
const empty = parseResult(await hospitalInfoSetTool.invoke({ hospitalId: BRANCH_ID }));
|
||||||
|
assert.equal(empty.success, false);
|
||||||
|
assert.match(empty.error, /未提供任何要更新的字段/);
|
||||||
|
|
||||||
|
const emptyName = parseResult(
|
||||||
|
await hospitalInfoSetTool.invoke({ hospitalId: BRANCH_ID, name: " " })
|
||||||
|
);
|
||||||
|
assert.equal(emptyName.success, false);
|
||||||
|
assert.match(emptyName.error, /医院名称不能为空/);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user