Compare commits
5
Commits
7bd2590d1f
...
af9a1543ae
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
af9a1543ae | ||
|
|
420f379ce8 | ||
|
|
f13af01a95 | ||
|
|
9ab2a39d08 | ||
|
|
623ecf2651 |
@@ -62,7 +62,7 @@ class EscortAdminPrompts {
|
||||
# 工具对应
|
||||
- 陪诊单查询 escort_record_query(患者名/手机号/状态/陪诊员ID/日期范围,日期用 YYYY-MM-DD);改单 escort_record_set
|
||||
- 患者健康档案:patient-record 子代理(查询与写入)
|
||||
- 医院信息:hospital-info 子代理(查询与维护)
|
||||
- 医院基础信息(地址/电话/等级/科室名称):hospital-info 子代理(查询与维护);医生出诊、挂号/就诊指南库中没有,用 web_search / web_fetch
|
||||
- 陪诊员档案 employee_query(姓名/工号/角色/状态);评价 employee_review_query
|
||||
- 天气、路线、日期、节假日;网页信息用 web_search / web_fetch
|
||||
|
||||
@@ -104,7 +104,7 @@ ${buildReference(userInfo, "管理员")}`;
|
||||
- 我的订单:escort_record_query(患者名/状态/日期范围 YYYY-MM-DD)
|
||||
- 开始/完成服务、写陪诊备注:escort_record_set
|
||||
- 本人档案:employee_query
|
||||
- 医院信息(科室楼层、电话、挂号/就诊指南、医生出诊):hospital-info 子代理(只读)
|
||||
- 医院基础信息(地址、电话、等级、科室名称):hospital-info 子代理(只读);医生出诊、挂号/就诊指南库中没有,用 web_search / web_fetch
|
||||
- 天气、路线、日期、节假日:http_get / get_calendar_info / get_year_holidays;网页信息用 web_search / web_fetch
|
||||
|
||||
# 严谨边界
|
||||
|
||||
@@ -8,6 +8,8 @@ import {
|
||||
STATUS_TRANSITIONS,
|
||||
CANCEL_STATUS_VALUES,
|
||||
} from "../../../../../utils/record_state.js";
|
||||
import { HandlerPayment } from "../../../../../handler/payment.js";
|
||||
import logger from "../../../../../utils/logger.js";
|
||||
|
||||
const escortRecordSetTool = tool(
|
||||
async ({ orderId, status, cancelStatus, notes, inquiry, payment }) => {
|
||||
@@ -37,6 +39,7 @@ const escortRecordSetTool = tool(
|
||||
// 状态迁移必须与接口层同一套规则:否则 Agent 能把已完成订单改回进行中,
|
||||
// 绕过状态机并造成费用/服务记录不一致
|
||||
const update = {};
|
||||
let effectivePay = record.payment || {};
|
||||
// 兼容旧数据:取消曾存放在 status 中
|
||||
const currentCancel = record.status === "cancelled"
|
||||
? "cancelled"
|
||||
@@ -50,9 +53,16 @@ const escortRecordSetTool = tool(
|
||||
error: `Illegal cancel status transition: ${currentCancel} -> ${cancelStatus}`,
|
||||
};
|
||||
}
|
||||
if (cancelStatus === "cancelled" && record.status === "completed") {
|
||||
return { success: false, error: "已完成订单不可取消,请走线下售后处理" };
|
||||
}
|
||||
update.cancelStatus = cancelStatus;
|
||||
if (cancelStatus === "requested") update.cancelRequestedAt = new Date();
|
||||
if (cancelStatus === "cancelled") update.cancelledAt = new Date();
|
||||
// 与接口层一致:先关闭在途预付单,否则取消后旧 prepay 仍可完成支付
|
||||
await HandlerPayment.closeOpenPayRecords(orderId);
|
||||
const fresh = await DBModel.EscortRecord.findById(orderId);
|
||||
effectivePay = fresh?.payment || effectivePay;
|
||||
}
|
||||
|
||||
if (status !== undefined && status !== record.status) {
|
||||
@@ -102,8 +112,51 @@ const escortRecordSetTool = tool(
|
||||
}
|
||||
}
|
||||
|
||||
// 已收款订单不能反向改支付状态/实收金额:否则可把退款中订单改回未支付并再次收款
|
||||
const currentPayStatus = effectivePay.status || "unpaid";
|
||||
if (payment !== undefined) {
|
||||
if (["partial", "paid", "refunding", "refunded"].includes(currentPayStatus)) {
|
||||
// 取消已收款订单时允许 paid → refunding,其余反向改动一律拒绝
|
||||
const enterRefundOnCancel = update.cancelStatus === "cancelled"
|
||||
&& currentPayStatus === "paid"
|
||||
&& payment.status === "refunding";
|
||||
if (payment.status !== undefined && payment.status !== currentPayStatus && !enterRefundOnCancel) {
|
||||
return { success: false, error: "已收款订单不可修改支付状态,如需退款请走取消流程" };
|
||||
}
|
||||
if (payment.paidFee !== undefined
|
||||
&& Number(payment.paidFee) !== (Number(effectivePay.paidFee) || 0)) {
|
||||
return { success: false, error: "已收款订单不可修改实收金额" };
|
||||
}
|
||||
if (payment.totalFee !== undefined
|
||||
&& Number(payment.totalFee) !== (Number(effectivePay.totalFee) || 0)) {
|
||||
return { success: false, error: "已收款订单不可修改金额,如需调整请先退款" };
|
||||
}
|
||||
} else if (payment.status !== undefined && !["unpaid", "paid"].includes(payment.status)) {
|
||||
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 (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;
|
||||
}
|
||||
if (payment.paidFee !== undefined) {
|
||||
@@ -114,6 +167,14 @@ const escortRecordSetTool = tool(
|
||||
}
|
||||
}
|
||||
|
||||
// 取消已收款订单:与接口层一致,先进入退款中,落库后再发起原路退款
|
||||
if (update.cancelStatus === "cancelled" && ["partial", "paid"].includes(currentPayStatus)) {
|
||||
if (payment?.status !== undefined && payment.status !== "refunding") {
|
||||
return { success: false, error: "取消已收款订单时支付状态必须进入 refunding" };
|
||||
}
|
||||
update["payment.status"] = "refunding";
|
||||
}
|
||||
|
||||
update["meta.updatetime"] = Date.now();
|
||||
|
||||
// 以读取时的状态作为更新条件,避免并发下跳过中间状态;同时排除已软删除的订单
|
||||
@@ -138,6 +199,17 @@ const escortRecordSetTool = tool(
|
||||
};
|
||||
}
|
||||
|
||||
// 已取消且进入退款中的线上订单:落库后触发原路退款(失败只记日志,由管理端查询兜底)
|
||||
if (updatedRecord.cancelStatus === "cancelled"
|
||||
&& updatedRecord.payment?.status === "refunding"
|
||||
&& updatedRecord.payment?.method === "online_wechat") {
|
||||
HandlerPayment.createRefundForRecord(updatedRecord, {
|
||||
reason: updatedRecord.cancelReason || "平台取消",
|
||||
}).catch((err) => {
|
||||
logger.error(`[escort-agent] 取消订单自动退款失败 recordId=${orderId}: ${err?.message || err}`);
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: updatedRecord,
|
||||
@@ -152,7 +224,7 @@ const escortRecordSetTool = tool(
|
||||
{
|
||||
name: "escort_record_set",
|
||||
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({
|
||||
orderId: z
|
||||
.string()
|
||||
@@ -192,6 +264,12 @@ const escortRecordSetTool = tool(
|
||||
.enum(["unpaid", "partial", "paid", "refunding", "refunded"])
|
||||
.optional()
|
||||
.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()
|
||||
.describe("Payment information to update"),
|
||||
|
||||
@@ -106,10 +106,11 @@ const healthProfileSetTool = tool(
|
||||
}
|
||||
update["meta.updatetime"] = new Date();
|
||||
|
||||
// 与接口层一致:身高/体重范围、性别枚举等 schema 约束必须在更新时生效
|
||||
const updated = await DBModel.HealthProfile.findByIdAndUpdate(
|
||||
profileId,
|
||||
{ $set: update },
|
||||
{ new: true }
|
||||
{ new: true, runValidators: true }
|
||||
);
|
||||
if (!updated) {
|
||||
return { success: false, error: `未找到 ID 为 ${profileId} 的健康档案` };
|
||||
|
||||
@@ -1,42 +1,37 @@
|
||||
import { tool } from "@langchain/core/tools";
|
||||
import { z } from "zod";
|
||||
import { DBModel } from "../../../../../models/index.js";
|
||||
import { escapeRegex, parseObjectId } from "../utils.js";
|
||||
|
||||
/**
|
||||
* 医院列表工具
|
||||
*
|
||||
* 数据源统一为 hospital 集合(老 organization 集合已不再维护医院基础信息)。
|
||||
* 分院/院区是独立医院记录,通过 entityName 归到同一主体。
|
||||
*/
|
||||
const hospitalInfoListTool = tool(
|
||||
async ({ keyword, parentId }) => {
|
||||
async ({ keyword, entityName, page = 1, pageSize = 50 }) => {
|
||||
try {
|
||||
// 只列可用医院;分院/院区也是医院,用 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 }, { 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(),
|
||||
]);
|
||||
const result = await DBModel.Hospital.findHospitals({
|
||||
page,
|
||||
pageSize,
|
||||
keyword,
|
||||
entityName,
|
||||
});
|
||||
|
||||
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 ?? "",
|
||||
total: result.total,
|
||||
page: result.page,
|
||||
pageSize: result.pageSize,
|
||||
data: result.list.map((hospital) => ({
|
||||
id: hospital._id,
|
||||
name: hospital.name ?? "",
|
||||
entityName: hospital.entityName ?? "",
|
||||
province: hospital.province ?? "",
|
||||
city: hospital.city ?? "",
|
||||
address: hospital.address ?? "",
|
||||
phone: hospital.phone ?? "",
|
||||
level: hospital.level ?? "",
|
||||
})),
|
||||
};
|
||||
} catch (error) {
|
||||
@@ -46,10 +41,24 @@ const hospitalInfoListTool = tool(
|
||||
{
|
||||
name: "hospital_info_list",
|
||||
description:
|
||||
"获取医院(名称、id)对列表,支持按名称/简称/拼音关键词过滤。传 parentId 只列该院的分院/院区;不传则列全部可用医院,parentId 为空的是总院。",
|
||||
"获取医院(名称、id)对列表,支持按名称/主体名称/拼音/拼音首字母/昵称关键词过滤。传 entityName 只列该主体的分院/院区;不传则按复旦榜档位排序列出全部医院。",
|
||||
schema: z.object({
|
||||
keyword: z.string().optional().describe("医院名称/简称/拼音/拼音首字母关键词(如 协和、xiehe),不传返回全部"),
|
||||
parentId: z.string().optional().describe("总院 id:提供时只返回该院的分院/院区"),
|
||||
keyword: z
|
||||
.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 { z } from "zod";
|
||||
import { DBModel } from "../../../../../models/index.js";
|
||||
import { escapeRegex, parseObjectId } from "../utils.js";
|
||||
import { 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 = "") {
|
||||
// 医院基础信息字段:新 hospital 集合没有 overview/doctors/guides/photos
|
||||
function toHospitalView(hospital) {
|
||||
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 ?? "",
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
// 分院/院区返回总院名称,便于上层确认归属
|
||||
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 }) => {
|
||||
async ({ hospitalId, hospitalName, department }) => {
|
||||
try {
|
||||
if (hospitalId) {
|
||||
const id = parseObjectId(hospitalId);
|
||||
if (!id) {
|
||||
return { success: false, error: `Invalid hospital ID: ${hospitalId}` };
|
||||
}
|
||||
const org = await DBModel.Organization.findOne({ _id: id, type: "hospital" })
|
||||
.select(HOSPITAL_FIELDS)
|
||||
.lean();
|
||||
if (!org) {
|
||||
const hospital = await DBModel.Hospital.findHospitalById(id);
|
||||
if (!hospital) {
|
||||
return { success: false, error: `未找到 id 为「${hospitalId}」的医院` };
|
||||
}
|
||||
const parents = await getParentNames([org]);
|
||||
return { success: true, total: 1, data: [toHospitalView(org, parents.get(String(org.parentId)) ?? "")] };
|
||||
return { success: true, total: 1, data: [toHospitalView(hospital)] };
|
||||
}
|
||||
|
||||
if (!hospitalName) {
|
||||
return { success: false, error: "请提供 hospitalId 或 hospitalName" };
|
||||
}
|
||||
|
||||
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).select(HOSPITAL_FIELDS).limit(10).lean(),
|
||||
]);
|
||||
if (total === 0) {
|
||||
// 医院总量有限,一次最多取 10 家,命中过多时由调用方细化名称
|
||||
const result = await DBModel.Hospital.findHospitals({
|
||||
page: 1,
|
||||
pageSize: 10,
|
||||
keyword: hospitalName,
|
||||
});
|
||||
if (result.total === 0) {
|
||||
return { success: false, error: `未找到名称包含「${hospitalName}」的医院` };
|
||||
}
|
||||
|
||||
const parents = await getParentNames(orgs);
|
||||
const data = orgs.map((org) => {
|
||||
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));
|
||||
}
|
||||
if (doctorName) {
|
||||
doctors = doctors.filter((d) => d.name?.includes(doctorName));
|
||||
}
|
||||
const keyword = String(department ?? "").trim();
|
||||
const data = result.list.map((hospital) => {
|
||||
const view = toHospitalView(hospital);
|
||||
if (!keyword) return view;
|
||||
return {
|
||||
...toHospitalView(org, parents.get(String(org.parentId)) ?? ""),
|
||||
departments,
|
||||
doctors,
|
||||
...view,
|
||||
departments: view.departments.filter((name) => String(name).includes(keyword)),
|
||||
};
|
||||
});
|
||||
|
||||
return { success: true, total, data };
|
||||
return { success: true, total: result.total, data };
|
||||
} catch (error) {
|
||||
return { success: false, error: error.message };
|
||||
}
|
||||
@@ -110,15 +75,17 @@ const hospitalInfoQueryTool = tool(
|
||||
{
|
||||
name: "hospital_info_query",
|
||||
description:
|
||||
"查询医院就医信息。传 hospitalId 返回该院完整档案;传 hospitalName 按名称/简称/拼音模糊查询,可再按科室、医生名过滤,返回医院总览(门诊/挂号/缴费/医保/交通)、科室(位置/电话/就诊提示)、医生(职称/擅长/号别/坐班)、场景指南、照片。分院/院区会返回 parentName。最多返回 10 家医院。",
|
||||
"查询医院基础信息(省市、地址、电话、等级、科室名称列表、复旦榜档位与昵称)。传 hospitalId 返回该院完整档案;传 hospitalName 按名称/主体名称/拼音/昵称模糊查询,可再按科室名过滤;最多返回 10 家医院。资料库不含医生出诊、挂号流程与就医指南,问到这些需说明库中没有并用 web_search / web_fetch 查官方信息。",
|
||||
schema: z.object({
|
||||
hospitalId: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe("医院 id(MongoDB ObjectId,来自 hospital_info_list),提供时忽略其他查询条件"),
|
||||
hospitalName: z.string().optional().describe("医院名称/简称,支持模糊匹配(如 协和、协和西院)"),
|
||||
hospitalName: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe("医院名称/主体名称/拼音/昵称,支持模糊匹配(如 协和、xiehe、陆总)"),
|
||||
department: z.string().optional().describe("科室名称过滤(如 风湿免疫科、放射科)"),
|
||||
doctorName: z.string().optional().describe("医生姓名过滤"),
|
||||
}),
|
||||
}
|
||||
);
|
||||
|
||||
@@ -1,176 +1,126 @@
|
||||
import { tool } from "@langchain/core/tools";
|
||||
import { z } from "zod";
|
||||
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(
|
||||
async ({ hospitalId, hospitalName, section, action, content, guides, entry, entryName, updatedBy }) => {
|
||||
async ({ hospitalId, hospitalName, name, entityName, province, city, address, phone, departments, level }) => {
|
||||
try {
|
||||
// 优先按 id 定位;名称只允许唯一命中,分院/院区多命中时返回候选让上层确认
|
||||
let org = null;
|
||||
// 优先按 id 定位;只用名称时必须唯一命中,多命中返回候选让上层确认
|
||||
let hospital = null;
|
||||
|
||||
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) {
|
||||
hospital = await DBModel.Hospital.findHospitalById(id);
|
||||
if (!hospital) {
|
||||
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) {
|
||||
const result = await DBModel.Hospital.findHospitals({
|
||||
page: 1,
|
||||
pageSize: 10,
|
||||
keyword: hospitalName,
|
||||
});
|
||||
if (result.total === 0) {
|
||||
return { success: false, error: `未找到名称包含「${hospitalName}」的医院,请确认名称后重试` };
|
||||
}
|
||||
if (orgs.length > 1) {
|
||||
if (result.total > 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 ?? "",
|
||||
error: `名称包含「${hospitalName}」的医院有 ${result.total} 家,请改用 hospitalId 精确写入`,
|
||||
candidates: result.list.map((item) => ({
|
||||
id: item._id,
|
||||
name: item.name,
|
||||
entityName: item.entityName ?? "",
|
||||
city: item.city ?? "",
|
||||
})),
|
||||
};
|
||||
}
|
||||
org = orgs[0];
|
||||
hospital = result.list[0];
|
||||
}
|
||||
|
||||
const input = { name, entityName, province, city, address, phone, level };
|
||||
const update = {};
|
||||
|
||||
if (section === "overview") {
|
||||
// 文本块全量替换
|
||||
if (typeof content !== "string") {
|
||||
return { success: false, error: "overview 需要提供 content 文本(写入前请先查询现有内容并合并)" };
|
||||
for (const key of TEXT_FIELDS) {
|
||||
const value = input[key];
|
||||
if (value === undefined) continue;
|
||||
const text = String(value ?? "").trim();
|
||||
if (key === "name" && !text) {
|
||||
return { success: false, error: "医院名称不能为空" };
|
||||
}
|
||||
update.overview = content;
|
||||
} 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[key] = text;
|
||||
}
|
||||
|
||||
update.infoUpdatedAt = new Date();
|
||||
if (updatedBy) {
|
||||
update.infoUpdatedBy = updatedBy;
|
||||
if (departments !== undefined) {
|
||||
if (!Array.isArray(departments)) {
|
||||
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();
|
||||
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 ?? "",
|
||||
},
|
||||
};
|
||||
if (Object.keys(update).length === 0) {
|
||||
return { success: false, error: "未提供任何要更新的字段" };
|
||||
}
|
||||
|
||||
const updated = await DBModel.Hospital.updateHospitalById(hospital._id, update);
|
||||
if (!updated) {
|
||||
return { success: false, error: `未找到 id 为「${hospital._id}」的医院` };
|
||||
}
|
||||
|
||||
return { success: true, data: toHospitalView(updated) };
|
||||
} catch (error) {
|
||||
if (error?.code === 11000) {
|
||||
return { success: false, error: "医院名称已存在,请使用「主体名称-分院名称」格式避免重名" };
|
||||
}
|
||||
return { success: false, error: error.message };
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "hospital_info_set",
|
||||
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({
|
||||
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("要更新的区块"),
|
||||
action: z
|
||||
.enum(["set", "upsert", "remove"])
|
||||
.optional()
|
||||
.describe("操作类型:overview/guides 用 set;photos/departments/doctors 用 upsert 或 remove"),
|
||||
content: z.string().optional().describe("overview 区块的完整文本(全量替换)"),
|
||||
guides: z
|
||||
.record(z.string(), z.string().nullable())
|
||||
.optional()
|
||||
.describe('guides 区块的场景键值对,如 {"住院流程": "..."};值为 null 表示删除该场景'),
|
||||
entry: z
|
||||
.object({
|
||||
name: z.string().optional().describe("科室名或医生名(锚点)"),
|
||||
department: z.string().optional().describe("医生所属科室(医生锚点之一)"),
|
||||
detail: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe("信息全文:科室(位置/电话/类型/提示)或医生(职称/擅长/号别/坐班停诊)"),
|
||||
photo: z.string().optional().describe("照片链接"),
|
||||
url: z.string().optional().describe("照片链接(photos 锚点)"),
|
||||
caption: z.string().optional().describe("照片说明"),
|
||||
})
|
||||
.optional()
|
||||
.describe("photos/departments/doctors 条目(upsert 时必填)"),
|
||||
entryName: z.string().optional().describe("remove 的锚点:科室名称 / 医生姓名 / 照片url"),
|
||||
updatedBy: z.string().optional().describe("操作人标识(用户ID或姓名),用于审计"),
|
||||
hospitalName: z.string().optional().describe("医院名称/主体名称/拼音/昵称(仅在唯一命中时可用)"),
|
||||
name: z.string().optional().describe("医院名称;分院/院区用「主体名称-分院名称」"),
|
||||
entityName: z.string().optional().describe("主体名称;留空时由名称自动派生"),
|
||||
province: z.string().optional().describe("省份,如 北京市"),
|
||||
city: z.string().optional().describe("城市,如 北京市"),
|
||||
address: z.string().optional().describe("医院地址"),
|
||||
phone: z.string().optional().describe("联系电话"),
|
||||
departments: z.array(z.string()).optional().describe("科室名称数组,整体替换"),
|
||||
level: z.string().optional().describe("医院等级,如 三级甲等"),
|
||||
}),
|
||||
}
|
||||
);
|
||||
|
||||
@@ -4,23 +4,22 @@ import {
|
||||
hospitalInfoSetTool,
|
||||
} from "../infra/tools/index.js";
|
||||
|
||||
// 医院就医信息查询与维护(医生资料/坐班、科室、看病指南等)
|
||||
// 医院基础信息查询与维护(名称/主体/院区、省市地址、电话、等级、科室名称、复旦榜档位)
|
||||
|
||||
const QUERY_PROMPT = `查询:
|
||||
- 先用 hospital_info_list 拿到医院(名称、id)列表定位医院,再用 hospital_info_query 传 hospitalId 获取完整信息。
|
||||
- 列表结果里 parentId 为空的是总院,非空的是分院/院区;可用 hospital_info_list 的 parentId 参数只列某院院区。
|
||||
- 需要按医院名称、简称、科室、医生名过滤时,直接用 hospital_info_query(hospitalName/department/doctorName)。
|
||||
- 出诊信息等时效性数据必须注明信息更新时间,并提示用户以医院最新公告为准。
|
||||
- 分院/院区是独立医院记录,与本院共享 entityName;可用 hospital_info_list 的 entityName 参数只列同一主体下的医院。
|
||||
- 需要按名称、主体名、拼音、昵称或科室名过滤时,直接用 hospital_info_query(hospitalName/department)。
|
||||
- 资料库只有医院基础信息(省市、地址、电话、等级、科室名称列表、复旦榜档位与昵称),不含医生出诊、挂号流程和就医指南;问到这些要如实说明库中没有,不能编造。
|
||||
- 电话、地址等可能变动,回答时提示以医院最新公告为准。
|
||||
- 查不到的信息如实告知,禁止编造。`;
|
||||
|
||||
const MAINTAIN_PROMPT = `维护:
|
||||
- 写入优先用 hospitalId 定位;只用名称时必须唯一命中,多命中会返回 candidates,先确认 id 再写。
|
||||
- overview:医院级文本全量替换,写入前先查询现有内容,合并整理后整体写入,不得丢失原有信息。
|
||||
- guides:场景键值对浅合并,新增场景直接传键值对;删除场景将值置为 null。
|
||||
- photos/departments/doctors:列表按锚点操作,锚点为 照片=url、科室=name、医生=name+department;upsert 新增或整条更新,remove 删除。
|
||||
- 科室、医生、就医信息都写入具体院区,不要写到总院再指望分院自动继承。
|
||||
- doctors 的 detail 包含职称、擅长方向、号别(普通/专家/特需)、坐班与停诊安排。
|
||||
- 尽量提供 updatedBy 记录操作人。图片只存 URL 链接,不负责图片上传。`;
|
||||
- 只维护基础字段:name、entityName、province、city、address、phone、departments(科室名称数组,整体替换)、level。
|
||||
- 名称是唯一键;改名会自动同步拼音、昵称与复旦榜档位,不要手写 pinyin/nicknames/fudanRank。
|
||||
- 分院/院区是独立医院记录,名称约定为「主体名称-分院名称」,不要写到总院上。
|
||||
- 资料库不维护医生出诊、挂号流程与就医指南,不要尝试写入这些内容。`;
|
||||
|
||||
/**
|
||||
* @param {Object} model
|
||||
@@ -30,9 +29,9 @@ const MAINTAIN_PROMPT = `维护:
|
||||
export const createHospitalInfoSubagent = (model, { allowWrite = false } = {}) => ({
|
||||
name: "hospital-info-subagent",
|
||||
description: allowWrite
|
||||
? "查询和维护医院基本资料及就医信息:医院电话、医生资料、出诊信息、科室位置与电话、看病指南(门诊/挂号/医保/住院/检查须知)等"
|
||||
: "查询医院基本资料及就医信息:医院电话、医生资料、出诊信息、科室位置与电话、看病指南(门诊/挂号/医保/住院/检查须知)等",
|
||||
systemPrompt: `你负责医院就医信息的查询${allowWrite ? "、维护、更新、核验" : ""}。
|
||||
? "查询和维护医院基础信息:医院名称与院区、省市地址、联系电话、医院等级、科室名称列表、复旦榜档位与常用昵称"
|
||||
: "查询医院基础信息:医院名称与院区、省市地址、联系电话、医院等级、科室名称列表、复旦榜档位与常用昵称",
|
||||
systemPrompt: `你负责医院基础信息的查询${allowWrite ? "、维护、更新、核验" : ""}。
|
||||
|
||||
${QUERY_PROMPT}${allowWrite ? `\n\n${MAINTAIN_PROMPT}` : ""}`,
|
||||
model,
|
||||
|
||||
@@ -175,6 +175,249 @@ class HandlerEmployee {
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
}
|
||||
|
||||
// 当前登录账号的员工档案:登录即可访问,供管理端判定陪诊员身份。
|
||||
// 只返回员工档案本身,不重复做管理员判定(管理员身份由管理端按登录响应的 apps 判定)
|
||||
async getMyEmployee(ctx) {
|
||||
try {
|
||||
const userId = ctx.state.user?._id;
|
||||
if (!userId) {
|
||||
return ResponseUtil.unauthorized(ctx, "登录已失效");
|
||||
}
|
||||
|
||||
const employee = await DBModel.Employee.findOne({ userId })
|
||||
.select("employeeNo role status profile.name profile.sex profile.phone profile.avatar")
|
||||
.lean()
|
||||
.exec();
|
||||
|
||||
// 无员工档案不是错误:管理员账号通常没有 Employee 记录
|
||||
return ResponseUtil.success(ctx, { employee: employee || null }, "查询成功");
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== 管理端 CRUD ====================
|
||||
// 与上面的公示接口完全分开:管理端要真实姓名、身份证号、证书编号等内部字段,
|
||||
// 但写入仍走白名单,避免 strict:false 的 schema 被塞入任意字段
|
||||
|
||||
static ROLES = ["attendant", "nurse", "doctor", "admin", "operator", "other"];
|
||||
static STATUSES = ["active", "inactive", "resigned", "suspended"];
|
||||
|
||||
static FIELD_PATHS = [
|
||||
"employeeNo", "userId", "orgId", "role", "status", "introduction", "remark",
|
||||
"profile.name", "profile.sex", "profile.birthday", "profile.idNumber",
|
||||
"profile.phone", "profile.email", "profile.avatar",
|
||||
"work.department", "work.title", "work.entryDate", "work.workYears", "work.qualification",
|
||||
"work.healthCertificate.number", "work.healthCertificate.org",
|
||||
"work.healthCertificate.issueDate", "work.healthCertificate.expireDate",
|
||||
"work.trainings",
|
||||
"attendantInfo.serviceAreas", "attendantInfo.specialties", "attendantInfo.languages",
|
||||
"attendantInfo.isOnline", "attendantInfo.orderCount",
|
||||
"emergencyContact.name", "emergencyContact.phone", "emergencyContact.relation",
|
||||
];
|
||||
|
||||
/**
|
||||
* 把请求体摊平成白名单内的点号路径
|
||||
*
|
||||
* 摊平而不是整块透传:updateEmployee 用 $set 更新,整块传 profile 会把未提交的
|
||||
* 子字段一起覆盖掉;点号路径只改实际提交的字段
|
||||
*/
|
||||
static pickFields(body, prefix = "", out = {}) {
|
||||
if (!body || typeof body !== "object") return out;
|
||||
for (const [key, value] of Object.entries(body)) {
|
||||
const path = prefix ? `${prefix}.${key}` : key;
|
||||
// 数组(如 trainings)和日期是叶子值,直接按路径收;普通对象继续下钻
|
||||
const isPlainObject =
|
||||
value !== null && typeof value === "object" &&
|
||||
!Array.isArray(value) && !(value instanceof Date);
|
||||
if (isPlainObject) {
|
||||
HandlerEmployee.pickFields(value, path, out);
|
||||
} else if (HandlerEmployee.FIELD_PATHS.includes(path)) {
|
||||
out[path] = value;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// 点号路径 → 嵌套对象,供 createEmployee 使用(构造器不认 "profile.name")
|
||||
static setPath(target, path, value) {
|
||||
const parts = path.split(".");
|
||||
let cur = target;
|
||||
for (let i = 0; i < parts.length - 1; i++) {
|
||||
if (!cur[parts[i]] || typeof cur[parts[i]] !== "object") cur[parts[i]] = {};
|
||||
cur = cur[parts[i]];
|
||||
}
|
||||
cur[parts[parts.length - 1]] = value;
|
||||
return target;
|
||||
}
|
||||
|
||||
// 管理端列表:不做姓名脱敏,支持角色/状态/关键词筛选
|
||||
async getEmployees(ctx) {
|
||||
try {
|
||||
const { role, status, keyword } = ctx.request.query;
|
||||
const page = Math.max(1, parseInt(ctx.request.query.page) || 1);
|
||||
const rawSize = parseInt(ctx.request.query.pageSize) || 20;
|
||||
const pageSize = Math.min(Math.max(1, rawSize), 100);
|
||||
|
||||
const filter = {};
|
||||
if (role) {
|
||||
if (!HandlerEmployee.ROLES.includes(role)) {
|
||||
return ResponseUtil.badRequest(ctx, "角色筛选值不正确");
|
||||
}
|
||||
filter.role = role;
|
||||
}
|
||||
if (status) {
|
||||
if (!HandlerEmployee.STATUSES.includes(status)) {
|
||||
return ResponseUtil.badRequest(ctx, "状态筛选值不正确");
|
||||
}
|
||||
filter.status = status;
|
||||
}
|
||||
if (keyword && String(keyword).trim()) {
|
||||
// 关键词转义,避免用户输入的括号等字符被当成正则
|
||||
const safe = String(keyword).trim().replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
const reg = new RegExp(safe, "i");
|
||||
filter.$or = [
|
||||
{ "profile.name": reg },
|
||||
{ "profile.phone": reg },
|
||||
{ employeeNo: reg },
|
||||
{ "profile.pinyin": reg },
|
||||
];
|
||||
}
|
||||
|
||||
const [employees, total] = await Promise.all([
|
||||
DBModel.Employee.find(filter)
|
||||
.sort({ "meta.createtime": -1 })
|
||||
.skip((page - 1) * pageSize)
|
||||
.limit(pageSize)
|
||||
.lean()
|
||||
.exec(),
|
||||
DBModel.Employee.countDocuments(filter).exec(),
|
||||
]);
|
||||
|
||||
return ResponseUtil.success(ctx, { employees, total, page, pageSize }, "查询成功");
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
}
|
||||
|
||||
async createEmployee(ctx) {
|
||||
try {
|
||||
const flat = HandlerEmployee.pickFields(ctx.request.body);
|
||||
|
||||
const invalid = HandlerEmployee.validateEmployee(flat, true);
|
||||
if (invalid) {
|
||||
return ResponseUtil.badRequest(ctx, invalid);
|
||||
}
|
||||
|
||||
const data = {};
|
||||
for (const [path, value] of Object.entries(flat)) {
|
||||
HandlerEmployee.setPath(data, path, value);
|
||||
}
|
||||
|
||||
const employee = await DBModel.Employee.createEmployee(data);
|
||||
return ResponseUtil.success(ctx, { employee }, "创建成功");
|
||||
} catch (err) {
|
||||
// employeeNo 唯一索引冲突:给出可读提示,而不是「服务器繁忙」
|
||||
if (err?.code === 11000) {
|
||||
return ResponseUtil.badRequest(ctx, "工号已存在");
|
||||
}
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
}
|
||||
|
||||
async updateEmployee(ctx) {
|
||||
try {
|
||||
const { id } = ctx.params;
|
||||
if (!mongoose.Types.ObjectId.isValid(id)) {
|
||||
return ResponseUtil.badRequest(ctx, "员工ID不合法");
|
||||
}
|
||||
|
||||
const flat = HandlerEmployee.pickFields(ctx.request.body);
|
||||
if (!Object.keys(flat).length) {
|
||||
return ResponseUtil.badRequest(ctx, "没有可更新的字段");
|
||||
}
|
||||
|
||||
const invalid = HandlerEmployee.validateEmployee(flat, false);
|
||||
if (invalid) {
|
||||
return ResponseUtil.badRequest(ctx, invalid);
|
||||
}
|
||||
|
||||
const employee = await DBModel.Employee.updateEmployee(id, flat);
|
||||
if (!employee) {
|
||||
return ResponseUtil.notFound(ctx, "员工不存在");
|
||||
}
|
||||
return ResponseUtil.success(ctx, { employee }, "更新成功");
|
||||
} catch (err) {
|
||||
if (err?.code === 11000) {
|
||||
return ResponseUtil.badRequest(ctx, "工号已存在");
|
||||
}
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
}
|
||||
|
||||
// 启停用独立入口:只改 status,避免误改其他字段
|
||||
async updateEmployeeStatus(ctx) {
|
||||
try {
|
||||
const { id } = ctx.params;
|
||||
if (!mongoose.Types.ObjectId.isValid(id)) {
|
||||
return ResponseUtil.badRequest(ctx, "员工ID不合法");
|
||||
}
|
||||
|
||||
const { status } = ctx.request.body || {};
|
||||
if (!HandlerEmployee.STATUSES.includes(status)) {
|
||||
return ResponseUtil.badRequest(ctx, "状态值不正确");
|
||||
}
|
||||
|
||||
const employee = await DBModel.Employee.updateEmployee(id, { status });
|
||||
if (!employee) {
|
||||
return ResponseUtil.notFound(ctx, "员工不存在");
|
||||
}
|
||||
return ResponseUtil.success(ctx, { employee }, "状态已更新");
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入校验
|
||||
*
|
||||
* @param {Object} flat 摊平后的白名单字段
|
||||
* @param {boolean} isCreate true 时姓名必填
|
||||
*/
|
||||
static validateEmployee(flat, isCreate) {
|
||||
if (isCreate || flat["profile.name"] !== undefined) {
|
||||
const name = String(flat["profile.name"] ?? "").trim();
|
||||
if (!name) return "姓名不能为空";
|
||||
}
|
||||
|
||||
if (flat.role !== undefined && !HandlerEmployee.ROLES.includes(flat.role)) {
|
||||
return "角色值不正确";
|
||||
}
|
||||
if (flat.status !== undefined && !HandlerEmployee.STATUSES.includes(flat.status)) {
|
||||
return "状态值不正确";
|
||||
}
|
||||
|
||||
// userId / orgId 允许为空串表示解绑,给了值就必须是合法 ObjectId
|
||||
for (const key of ["userId", "orgId"]) {
|
||||
const value = flat[key];
|
||||
if (value !== undefined && value !== "" && !mongoose.Types.ObjectId.isValid(value)) {
|
||||
return `${key === "userId" ? "关联用户ID" : "所属机构ID"}不合法`;
|
||||
}
|
||||
}
|
||||
|
||||
if (flat["profile.phone"] !== undefined && flat["profile.phone"] !== "") {
|
||||
if (!/^1[3-9]\d{9}$/.test(String(flat["profile.phone"]))) {
|
||||
return "手机号格式不正确";
|
||||
}
|
||||
}
|
||||
|
||||
if (flat["work.trainings"] !== undefined && !Array.isArray(flat["work.trainings"])) {
|
||||
return "培训记录必须是数组";
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export { HandlerEmployee };
|
||||
|
||||
+174
-75
@@ -48,6 +48,12 @@ class HandlerEscortRecord {
|
||||
// 用户下单时可选择的支付渠道:线下支付不细分现金/转账,由平台收款时补记 method
|
||||
static PAY_CHANNELS = ["online_wechat", "offline"];
|
||||
|
||||
// 支付状态枚举,与 schema payment.status 一致
|
||||
static PAYMENT_STATUSES = ["unpaid", "partial", "paid", "refunding", "refunded"];
|
||||
|
||||
// 日期筛选格式:只接受 YYYY-MM-DD,避免把任意字符串丢给 Date 解析
|
||||
static DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
|
||||
|
||||
// 单页最大条数,避免 pageSize 传超大值一次拖库
|
||||
static MAX_PAGE_SIZE = 200;
|
||||
|
||||
@@ -232,19 +238,41 @@ class HandlerEscortRecord {
|
||||
|
||||
// 按条件查询记录(管理端,可查全部)
|
||||
async getRecords(ctx) {
|
||||
return this._listRecords(ctx, false);
|
||||
return this._listRecords(ctx, "all");
|
||||
}
|
||||
|
||||
// 查询"我的"记录:强制以登录用户身份查询,忽略 query 中的 userId
|
||||
async getMyRecords(ctx) {
|
||||
return this._listRecords(ctx, true);
|
||||
return this._listRecords(ctx, "self");
|
||||
}
|
||||
|
||||
async _listRecords(ctx, forceSelf) {
|
||||
// 陪诊员本人名下订单:强制以登录用户为陪诊员,忽略 query 中的 userId。
|
||||
// 过滤、分页、计数与支付窗口口径与管理员列表保持一致
|
||||
async getAttendantRecords(ctx) {
|
||||
return this._listRecords(ctx, "attendant");
|
||||
}
|
||||
|
||||
/**
|
||||
* 列表统一入口
|
||||
* @param {Object} ctx Koa 上下文
|
||||
* @param {"all"|"self"|"attendant"} mode all=管理员全量;self=订单所属用户本人;attendant=陪诊员本人名下
|
||||
*/
|
||||
async _listRecords(ctx, mode) {
|
||||
try {
|
||||
const { status, userId, appointmentDate, healthProfileId, cancelStatus, includeCancelled } = ctx.request.query;
|
||||
const {
|
||||
status, userId, appointmentDate, healthProfileId, cancelStatus, includeCancelled,
|
||||
paymentStatus, payChannel, startDate, endDate, keyword,
|
||||
} = ctx.request.query;
|
||||
const { page, pageSize } = HandlerEscortRecord.parsePaging(ctx.request.query);
|
||||
const effectiveUserId = forceSelf ? ctx.state.user?._id : userId;
|
||||
const loginUserId = ctx.state.user?._id;
|
||||
if (!loginUserId) {
|
||||
return ResponseUtil.unauthorized(ctx, "登录已失效");
|
||||
}
|
||||
// 陪诊员模式不允许通过 query 改查他人订单;管理员模式保留按 userId 筛选
|
||||
const effectiveUserId = mode === "self"
|
||||
? loginUserId
|
||||
: (mode === "all" ? userId : undefined);
|
||||
const attendantId = mode === "attendant" ? loginUserId : undefined;
|
||||
|
||||
// status解析成数组
|
||||
let statusArray = null;
|
||||
@@ -265,6 +293,25 @@ class HandlerEscortRecord {
|
||||
}
|
||||
}
|
||||
|
||||
// 支付状态筛选:unpaid / partial / paid / refunding / refunded
|
||||
let paymentStatusArray = null;
|
||||
if (paymentStatus && String(paymentStatus).length > 0) {
|
||||
paymentStatusArray = String(paymentStatus).split(',').filter(Boolean);
|
||||
if (paymentStatusArray.some((item) => !HandlerEscortRecord.PAYMENT_STATUSES.includes(item))) {
|
||||
return ResponseUtil.badRequest(ctx, "支付状态筛选值不正确");
|
||||
}
|
||||
}
|
||||
|
||||
if (payChannel && !HandlerEscortRecord.PAY_CHANNELS.includes(payChannel)) {
|
||||
return ResponseUtil.badRequest(ctx, "支付渠道筛选值不正确");
|
||||
}
|
||||
|
||||
for (const [name, value] of [["startDate", startDate], ["endDate", endDate], ["appointmentDate", appointmentDate]]) {
|
||||
if (value && !HandlerEscortRecord.DATE_PATTERN.test(String(value))) {
|
||||
return ResponseUtil.badRequest(ctx, `${name === "appointmentDate" ? "预约日期" : name === "startDate" ? "开始日期" : "结束日期"}格式应为 YYYY-MM-DD`);
|
||||
}
|
||||
}
|
||||
|
||||
const result = await DBModel.EscortRecord.findRecordPage({
|
||||
page,
|
||||
pageSize,
|
||||
@@ -272,8 +319,14 @@ class HandlerEscortRecord {
|
||||
cancelStatus: cancelStatusArray,
|
||||
includeCancelled: ["1", "true"].includes(String(includeCancelled)),
|
||||
userId: effectiveUserId,
|
||||
attendantId,
|
||||
appointmentDate,
|
||||
healthProfileId,
|
||||
paymentStatus: paymentStatusArray,
|
||||
payChannel,
|
||||
startDate,
|
||||
endDate,
|
||||
keyword,
|
||||
});
|
||||
|
||||
const records = result.records.map((record) => HandlerEscortRecord.withPaymentWindow(record));
|
||||
@@ -283,28 +336,6 @@ class HandlerEscortRecord {
|
||||
}
|
||||
}
|
||||
|
||||
async getAttendantRecords(ctx) {
|
||||
try {
|
||||
// 只允许查询当前登录陪诊员自己的记录
|
||||
const attendantId = ctx.state.user?._id;
|
||||
if (!attendantId) {
|
||||
return ResponseUtil.badRequest(ctx, "缺少陪诊员ID");
|
||||
}
|
||||
|
||||
const { status } = ctx.request.query;
|
||||
const { page, pageSize } = HandlerEscortRecord.parsePaging(ctx.request.query);
|
||||
const records = await DBModel.EscortRecord.findRecordsByAttendant(attendantId, {
|
||||
page,
|
||||
pageSize,
|
||||
status,
|
||||
});
|
||||
|
||||
return ResponseUtil.success(ctx, { records }, "查询成功");
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
}
|
||||
|
||||
async getRecordById(ctx) {
|
||||
try {
|
||||
const { id } = ctx.params;
|
||||
@@ -338,21 +369,29 @@ class HandlerEscortRecord {
|
||||
if (idempotencyKey && !/^[\w-]{8,80}$/.test(idempotencyKey)) {
|
||||
return ResponseUtil.badRequest(ctx, "下单幂等标识格式不正确");
|
||||
}
|
||||
if (idempotencyKey) {
|
||||
const existing = await DBModel.EscortRecord.findByIdempotencyKey(userId, idempotencyKey);
|
||||
if (existing) return ResponseUtil.success(ctx, { record: existing }, "订单已创建");
|
||||
}
|
||||
|
||||
// 订单必须关联就诊人:patient 是下单当刻的快照,healthProfileId 才是关联
|
||||
if (!body.healthProfileId) {
|
||||
return ResponseUtil.badRequest(ctx, "缺少就诊人档案ID");
|
||||
}
|
||||
|
||||
// 就诊人档案必须属于当前登录用户,避免把订单挂到他人档案上
|
||||
// 档案锚定归属:订单归属取档案的 userId。
|
||||
// 管理员代客下单不传 userId(传了也忽略),档案无归属时订单 userId 留空,后期可在订单编辑中补录;
|
||||
// 非管理员仍要求档案属于本人,避免把订单挂到他人档案上
|
||||
const isAdmin = HandlerEscortRecord.isAdmin(ctx.state.user);
|
||||
const profile = await DBModel.HealthProfile.findProfileById(body.healthProfileId);
|
||||
if (!profile || String(profile.userId) !== String(userId)) {
|
||||
if (!profile) {
|
||||
return ResponseUtil.badRequest(ctx, "就诊人档案不存在");
|
||||
}
|
||||
if (!isAdmin && String(profile.userId || "") !== String(userId)) {
|
||||
return ResponseUtil.badRequest(ctx, "就诊人档案不存在");
|
||||
}
|
||||
const orderUserId = profile.userId || null;
|
||||
|
||||
if (idempotencyKey) {
|
||||
const existing = await DBModel.EscortRecord.findByIdempotencyKey(orderUserId, idempotencyKey);
|
||||
if (existing) return ResponseUtil.success(ctx, { record: existing }, "订单已创建");
|
||||
}
|
||||
|
||||
// 服务项目、服务名称、区域、排期与价格均以服务端目录为准。
|
||||
const service = services.find((s) => String(s.id) === String(body.escort?.serviceId));
|
||||
@@ -374,8 +413,9 @@ class HandlerEscortRecord {
|
||||
|
||||
const payload = HandlerEscortRecord.pickFields(body);
|
||||
// 陪诊员分配由平台决定:用户下单时提交的 attendant 一律丢弃,防止自选/伪造陪诊员
|
||||
if (!HandlerEscortRecord.isAdmin(ctx.state.user)) delete payload.attendant;
|
||||
payload.userId = userId;
|
||||
if (!isAdmin) delete payload.attendant;
|
||||
// 归属以档案为准:管理员传入的 userId 一律忽略,无归属档案留空
|
||||
payload.userId = orderUserId;
|
||||
// healthProfileId 以校验通过的档案为准,覆盖客户端原值
|
||||
payload.healthProfileId = profile._id;
|
||||
payload.status = "pending";
|
||||
@@ -398,7 +438,7 @@ class HandlerEscortRecord {
|
||||
return ResponseUtil.badRequest(ctx, "支付方式不正确");
|
||||
}
|
||||
let payChannel;
|
||||
if (HandlerEscortRecord.isAdmin(ctx.state.user)) {
|
||||
if (isAdmin) {
|
||||
payChannel = HandlerEscortRecord.PAY_CHANNELS.includes(requestedChannel)
|
||||
? requestedChannel
|
||||
: (body.payment?.method === "online_wechat" ? "online_wechat" : "offline");
|
||||
@@ -413,18 +453,21 @@ class HandlerEscortRecord {
|
||||
payChannel,
|
||||
};
|
||||
// 实际收款方式由平台在收款时补记:仅管理员代客下单时可指定,用户端提交一律丢弃
|
||||
if (HandlerEscortRecord.isAdmin(ctx.state.user)
|
||||
if (isAdmin
|
||||
&& HandlerEscortRecord.PAYMENT_METHODS.includes(body.payment?.method)) {
|
||||
payload.payment.method = body.payment.method;
|
||||
}
|
||||
|
||||
// 每个用户同时最多 3 个未完成预约,超出则不再允许新增
|
||||
const unfinishedCount = await HandlerEscortRecord.countUnfinishedRecords(userId);
|
||||
if (unfinishedCount >= HandlerEscortRecord.MAX_UNFINISHED_RECORDS) {
|
||||
return ResponseUtil.badRequest(
|
||||
ctx,
|
||||
`每个用户最多同时保留${HandlerEscortRecord.MAX_UNFINISHED_RECORDS}个未完成的预约,请先完成或取消已有预约后再下单`
|
||||
);
|
||||
// 每个用户同时最多 3 个未完成预约,超出则不再允许新增。
|
||||
// 无归属订单(代客下单且档案未关联客户)跳过:否则会按全部无主订单全局误拦
|
||||
if (orderUserId) {
|
||||
const unfinishedCount = await HandlerEscortRecord.countUnfinishedRecords(orderUserId);
|
||||
if (unfinishedCount >= HandlerEscortRecord.MAX_UNFINISHED_RECORDS) {
|
||||
return ResponseUtil.badRequest(
|
||||
ctx,
|
||||
`每个用户最多同时保留${HandlerEscortRecord.MAX_UNFINISHED_RECORDS}个未完成的预约,请先完成或取消已有预约后再下单`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -433,7 +476,7 @@ class HandlerEscortRecord {
|
||||
} catch (err) {
|
||||
// 并发重复提交由唯一索引兜底,后到的请求返回已创建订单。
|
||||
if (err?.code === 11000 && idempotencyKey) {
|
||||
const existing = await DBModel.EscortRecord.findByIdempotencyKey(userId, idempotencyKey);
|
||||
const existing = await DBModel.EscortRecord.findByIdempotencyKey(orderUserId, idempotencyKey);
|
||||
if (existing) return ResponseUtil.success(ctx, { record: existing }, "订单已创建");
|
||||
}
|
||||
throw err;
|
||||
@@ -483,6 +526,38 @@ class HandlerEscortRecord {
|
||||
return ResponseUtil.badRequest(ctx, "该订单当前状态不支持修改这些信息");
|
||||
}
|
||||
|
||||
// 已收款订单一律锁定支付状态与实收金额:否则编辑退款中的订单会把它改回未支付,
|
||||
// 用户可再次支付造成重复扣款;金额改动也会与 payment_record 对不上
|
||||
const currentPayStatus = existing.payment?.status || "unpaid";
|
||||
const settledPayStatus = ["partial", "paid", "refunding", "refunded"].includes(currentPayStatus);
|
||||
const nextPayStatus = payload["payment.status"] ?? payload.payment?.status;
|
||||
const nextPaidFee = payload["payment.paidFee"] ?? payload.payment?.paidFee;
|
||||
if (settledPayStatus) {
|
||||
if (nextPayStatus !== undefined && nextPayStatus !== currentPayStatus) {
|
||||
return ResponseUtil.badRequest(ctx, "已收款订单不可修改支付状态,如需退款请走取消流程");
|
||||
}
|
||||
if (nextPaidFee !== undefined && Number(nextPaidFee) !== (Number(existing.payment?.paidFee) || 0)) {
|
||||
return ResponseUtil.badRequest(ctx, "已收款订单不可修改实收金额");
|
||||
}
|
||||
const nextTotalFee = payload["payment.totalFee"] ?? payload.payment?.totalFee;
|
||||
if (nextTotalFee !== undefined
|
||||
&& Number(nextTotalFee) !== (Number(existing.payment?.totalFee) || 0)) {
|
||||
return ResponseUtil.badRequest(ctx, "已收款订单不可修改金额,如需调整请先退款");
|
||||
}
|
||||
}
|
||||
|
||||
// 线上微信收款只能由支付回调写入:手工标记会没有支付流水,取消时无法原路退款
|
||||
const nextPaymentMethod = payload["payment.method"] ?? payload.payment?.method;
|
||||
if (nextPaymentMethod === "online_wechat" && nextPayStatus === "paid") {
|
||||
const paidPayment = await DBModel.PaymentRecord.findOne({
|
||||
recordId: id,
|
||||
status: { $in: ["pay_success", "refunding", "refunded"] },
|
||||
});
|
||||
if (!paidPayment) {
|
||||
return ResponseUtil.badRequest(ctx, "线上微信收款只能由支付回调写入,请选择线下现金或转账");
|
||||
}
|
||||
}
|
||||
|
||||
// 支付方式为受控枚举:管理端修改时校验,防止写入非法值
|
||||
const paymentMethod = update["payment.method"] ?? update.payment?.method;
|
||||
if (paymentMethod !== undefined && !HandlerEscortRecord.PAYMENT_METHODS.includes(paymentMethod)) {
|
||||
@@ -507,13 +582,9 @@ class HandlerEscortRecord {
|
||||
if (requestedChannel === "offline") {
|
||||
const closeResult = await HandlerPayment.closeOpenPayRecords(id);
|
||||
if (closeResult.paid) {
|
||||
const fresh = await DBModel.EscortRecord.findById(id);
|
||||
HandlerPayment.createRefundForRecord(fresh || existing, {
|
||||
reason: "用户切换支付方式",
|
||||
}).catch((err) => {
|
||||
logger.error(`[escort] 切换支付方式后自动退款失败 recordId=${id}: ${err?.message || err}`);
|
||||
});
|
||||
return ResponseUtil.error(ctx, "订单已支付,已为您发起退款", null, 409);
|
||||
// 已支付不能改渠道:这里只提示刷新,不主动退款。
|
||||
// 否则会得到一张「仍在履约、款项已退」的死单,用户既不能再付也不能切线下
|
||||
return ResponseUtil.error(ctx, "订单已支付,请刷新页面查看最新状态", null, 409);
|
||||
}
|
||||
payload["payment.paymentRecordId"] = null;
|
||||
}
|
||||
@@ -547,10 +618,12 @@ class HandlerEscortRecord {
|
||||
}
|
||||
|
||||
// 档案归属校验:档案必须属于订单所属用户,避免把订单挂到他人档案上;
|
||||
// 通过后同步刷新订单里的就诊人快照
|
||||
// 通过后同步刷新订单里的就诊人快照。
|
||||
// 空值等价比较:无归属订单(userId 为空)可以关联无归属档案
|
||||
if (payload.healthProfileId) {
|
||||
const profile = await DBModel.HealthProfile.findProfileById(payload.healthProfileId);
|
||||
if (!profile || String(profile.userId) !== String(existing.userId)) {
|
||||
const sameOwner = (a, b) => String(a || "") === String(b || "");
|
||||
if (!profile || !sameOwner(profile.userId, existing.userId)) {
|
||||
return ResponseUtil.badRequest(ctx, "就诊人档案不存在");
|
||||
}
|
||||
payload.patient = HandlerEscortRecord.buildPatientSnapshot(profile);
|
||||
@@ -612,7 +685,13 @@ class HandlerEscortRecord {
|
||||
}
|
||||
|
||||
const user = ctx.state.user;
|
||||
const role = await resolveEscortAdminRole(user);
|
||||
// 用户端与管理端共用本接口,按调用方 app 区分取消流程:
|
||||
// appId 只用于收紧权限——即使账号同时带管理员角色,从用户端小程序发起的取消
|
||||
// 也必须走取消申请,否则会在 C 端绕过「已确认订单需人工确认」直接退款。
|
||||
// 管理端固定带 appId=wxapp-escort-admin;未带 appId 的历史调用保持原角色判定。
|
||||
const requestAppId = String(ctx.request.body?.appId || "");
|
||||
const isUserApp = requestAppId === "wxapp-escort";
|
||||
const role = isUserApp ? null : await resolveEscortAdminRole(user);
|
||||
const isOwner = String(existing.userId) === String(user?._id);
|
||||
const paymentStatus = existing.payment?.status || "unpaid";
|
||||
const cancelReason = String(reason || "").trim().slice(0, 200);
|
||||
@@ -629,7 +708,7 @@ class HandlerEscortRecord {
|
||||
}
|
||||
|
||||
if (role !== "admin" && role !== "attendant") {
|
||||
// 用户端只能取消:未确认且未收款直接物理删除;其余提交取消申请
|
||||
// 用户端只能取消:未确认订单直接取消(未收款删除、已收款退款);已确认订单提交取消申请
|
||||
if (status !== "cancelled" || !isOwner) {
|
||||
return ResponseUtil.forbidden(ctx, "不支持的状态变更");
|
||||
}
|
||||
@@ -641,30 +720,46 @@ class HandlerEscortRecord {
|
||||
}
|
||||
if (!cancelReason) return ResponseUtil.badRequest(ctx, "请选择取消原因");
|
||||
|
||||
if (paymentStatus === "unpaid" && existing.status === "pending") {
|
||||
// 删除前必须先关单,否则旧 prepay 仍可支付一张已不存在的订单
|
||||
if (existing.status === "pending") {
|
||||
// 未确认订单:陪诊师尚未接单,取消直接生效,无需人工确认。
|
||||
// 取消前先关单,否则旧 prepay 仍可支付一张已不存在的订单
|
||||
const closeResult = await HandlerPayment.closeOpenPayRecords(id);
|
||||
let payStatus = paymentStatus;
|
||||
let pay = existing.payment || {};
|
||||
if (closeResult.paid) {
|
||||
// 关单后发现钱已到账:不能删除,转待取消并等待确认后退款
|
||||
const updated = await DBModel.EscortRecord.updateRecordCancel(id, cancelStatus, {
|
||||
cancelStatus: "requested",
|
||||
cancelReason,
|
||||
cancelRequestedAt: new Date(),
|
||||
});
|
||||
if (!updated) {
|
||||
return ResponseUtil.error(ctx, "订单状态已变化,请刷新后重试", null, 409);
|
||||
const fresh = await DBModel.EscortRecord.findById(id);
|
||||
payStatus = fresh?.payment?.status || "paid";
|
||||
pay = fresh?.payment || pay;
|
||||
}
|
||||
if (payStatus === "unpaid") {
|
||||
const deletedRecord = await DBModel.EscortRecord.deleteRecord(id);
|
||||
if (!deletedRecord) {
|
||||
return ResponseUtil.error(ctx, "陪诊记录不存在", null, 404);
|
||||
}
|
||||
return ResponseUtil.success(
|
||||
ctx,
|
||||
{ record: HandlerEscortRecord.withPaymentWindow(updated), deleted: false },
|
||||
"订单已支付,取消申请已提交"
|
||||
);
|
||||
return ResponseUtil.success(ctx, { record: deletedRecord, deleted: true }, "订单已取消");
|
||||
}
|
||||
const deletedRecord = await DBModel.EscortRecord.deleteRecord(id);
|
||||
if (!deletedRecord) {
|
||||
return ResponseUtil.error(ctx, "陪诊记录不存在", null, 404);
|
||||
// 已收款:直接转已取消并进入退款;线上微信自动原路退款,线下由平台人工核销
|
||||
const updatedRecord = await DBModel.EscortRecord.updateRecordCancel(id, cancelStatus, {
|
||||
cancelStatus: "cancelled",
|
||||
cancelReason,
|
||||
cancelledAt: new Date(),
|
||||
...(["partial", "paid"].includes(payStatus) ? { "payment.status": "refunding" } : {}),
|
||||
});
|
||||
if (!updatedRecord) {
|
||||
return ResponseUtil.error(ctx, "订单状态已变化,请刷新后重试", null, 409);
|
||||
}
|
||||
return ResponseUtil.success(ctx, { record: deletedRecord, deleted: true }, "订单已取消");
|
||||
if (pay.method === "online_wechat" && ["partial", "paid"].includes(payStatus)) {
|
||||
HandlerPayment.createRefundForRecord(updatedRecord, {
|
||||
reason: cancelReason || "订单取消",
|
||||
}).catch((err) => {
|
||||
logger.error(`[escort] 未确认订单取消自动退款失败 recordId=${id}: ${err?.message || err}`);
|
||||
});
|
||||
}
|
||||
return ResponseUtil.success(
|
||||
ctx,
|
||||
{ record: HandlerEscortRecord.withPaymentWindow(updatedRecord) },
|
||||
"订单已取消,退款已发起"
|
||||
);
|
||||
}
|
||||
|
||||
// 申请取消前先关闭未支付的 prepay,避免等待确认期间又被支付
|
||||
@@ -710,6 +805,10 @@ class HandlerEscortRecord {
|
||||
if (!canCancelTransition(cancelStatus, "cancelled")) {
|
||||
return ResponseUtil.badRequest(ctx, "当前订单不允许取消");
|
||||
}
|
||||
// 已完成是终态:服务已交付,取消/退款需走线下售后,不能由接口直接改状态
|
||||
if (existing.status === "completed") {
|
||||
return ResponseUtil.badRequest(ctx, "已完成订单不可取消,请走线下售后处理");
|
||||
}
|
||||
|
||||
// 取消前先关单:未支付订单可能仍有旧 prepay 在途,关单后发现已支付则按已收款走退款
|
||||
const closeResult = await HandlerPayment.closeOpenPayRecords(id);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import mongoose from "mongoose";
|
||||
import { DBModel } from "../models/index.js";
|
||||
import ResponseUtil from "../utils/responseUtil.js";
|
||||
|
||||
@@ -51,6 +52,15 @@ class HandlerHealthProfile {
|
||||
if (weight !== undefined && (Number(weight) < 0 || Number(weight) > 500)) {
|
||||
return "体重需在 0-500kg 之间";
|
||||
}
|
||||
|
||||
// 归属用户:管理端代客建档时传入,必须是合法 ObjectId。
|
||||
// 空串/不传表示未绑定(历史数据),C 端 /mine 系列不走这里,其 userId 取自 token
|
||||
if (body.userId !== undefined && body.userId !== null && body.userId !== "") {
|
||||
if (!mongoose.Types.ObjectId.isValid(body.userId)) {
|
||||
return "归属用户ID不合法";
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
+66
-6
@@ -209,8 +209,9 @@ class HandlerPayment {
|
||||
if (!record || record.deletedAt) {
|
||||
return { payment, record: null, cancelled: true };
|
||||
}
|
||||
// 取消与 status 解耦:已申请取消或已取消的订单都不再回刷 paid(兼容旧数据 status=cancelled)
|
||||
if ((record.cancelStatus || "none") !== "none" || record.status === "cancelled") {
|
||||
// 只有正式取消才退款(兼容旧数据 status=cancelled);
|
||||
// 仅「待取消」时钱已到账仍按已支付如实记账,等陪诊师/平台确认取消时再退
|
||||
if ((record.cancelStatus || "none") === "cancelled" || record.status === "cancelled") {
|
||||
return { payment, record, cancelled: true };
|
||||
}
|
||||
// 已进入退款阶段的流水不再回刷 paid,避免快照倒退
|
||||
@@ -268,7 +269,14 @@ class HandlerPayment {
|
||||
const trade = await wxpay.queryOrder(payment.outTradeNo);
|
||||
if (trade.trade_state === "SUCCESS") {
|
||||
HandlerPayment.verifyTrade(trade, payment);
|
||||
await HandlerPayment.applyPaymentSuccess(payment, HandlerPayment.mapTransaction(trade));
|
||||
const applied = await HandlerPayment.applyPaymentSuccess(payment, HandlerPayment.mapTransaction(trade));
|
||||
if (applied.cancelled) {
|
||||
HandlerPayment.createRefundForRecord(applied.record || { _id: payment.recordId }, {
|
||||
reason: DEFAULT_REFUND_REASON,
|
||||
}).catch((refundErr) => {
|
||||
logger.error(`[payment] 关单时发现已支付且订单已取消,退款失败 recordId=${payment.recordId}: ${refundErr?.message || refundErr}`);
|
||||
});
|
||||
}
|
||||
result.paid += 1;
|
||||
} else {
|
||||
await HandlerPayment.setPaymentStatus(payment._id, "closed_unconfirmed", {
|
||||
@@ -347,7 +355,11 @@ class HandlerPayment {
|
||||
recordId,
|
||||
status: { $in: ["pay_success", "refunding"] },
|
||||
}).sort({ paidAt: -1, createdAt: -1 });
|
||||
if (!payment) return { skipped: true };
|
||||
if (!payment) {
|
||||
// 手工标记的「线上微信已收款」没有支付流水,无法原路退款;留 refunding 交人工核对
|
||||
logger.error(`[payment] 退款未发起:缺少成功支付流水 recordId=${recordId},请人工核对收款方式`);
|
||||
return { skipped: true, reason: "no_payment_record" };
|
||||
}
|
||||
|
||||
const outRefundNo = `${recordId}-R1`;
|
||||
const existing = await DBModel.RefundRecord.findOne({ outRefundNo });
|
||||
@@ -517,10 +529,17 @@ class HandlerPayment {
|
||||
const trade = await wxpay.queryOrder(unconfirmed.outTradeNo);
|
||||
if (trade.trade_state === "SUCCESS") {
|
||||
HandlerPayment.verifyTrade(trade, unconfirmed);
|
||||
await HandlerPayment.applyPaymentSuccess(
|
||||
const applied = await HandlerPayment.applyPaymentSuccess(
|
||||
unconfirmed,
|
||||
HandlerPayment.mapTransaction(trade)
|
||||
);
|
||||
if (applied.cancelled) {
|
||||
HandlerPayment.createRefundForRecord(applied.record || { _id: unconfirmed.recordId }, {
|
||||
reason: DEFAULT_REFUND_REASON,
|
||||
}).catch((refundErr) => {
|
||||
logger.error(`[payment] 发起支付时发现旧流水已支付且订单已取消,退款失败 recordId=${unconfirmed.recordId}: ${refundErr?.message || refundErr}`);
|
||||
});
|
||||
}
|
||||
return ResponseUtil.badRequest(ctx, "订单已支付,请勿重复支付");
|
||||
}
|
||||
} catch (err) {
|
||||
@@ -737,7 +756,14 @@ class HandlerPayment {
|
||||
const trade = await wxpay.queryOrder(payment.outTradeNo);
|
||||
if (trade.trade_state === "SUCCESS") {
|
||||
HandlerPayment.verifyTrade(trade, payment);
|
||||
await HandlerPayment.applyPaymentSuccess(payment, HandlerPayment.mapTransaction(trade));
|
||||
const applied = await HandlerPayment.applyPaymentSuccess(payment, HandlerPayment.mapTransaction(trade));
|
||||
if (applied.cancelled) {
|
||||
HandlerPayment.createRefundForRecord(applied.record || { _id: payment.recordId }, {
|
||||
reason: DEFAULT_REFUND_REASON,
|
||||
}).catch((refundErr) => {
|
||||
logger.error(`[payment] 逾期关单时发现已支付且订单已取消,退款失败 recordId=${payment.recordId}: ${refundErr?.message || refundErr}`);
|
||||
});
|
||||
}
|
||||
} else {
|
||||
await HandlerPayment.setPaymentStatus(payment._id, "closed_unconfirmed", {
|
||||
closeUnconfirmed: true,
|
||||
@@ -902,6 +928,40 @@ class HandlerPayment {
|
||||
return ResponseUtil.error(ctx, "查询退款结果失败,请稍后重试", null, 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /escort-record/:id/refund/manual (管理端)
|
||||
* 线下收款或缺少线上流水的订单,由平台人工退款后在此核销
|
||||
*/
|
||||
async completeManualRefund(ctx) {
|
||||
try {
|
||||
const id = ctx.params.id;
|
||||
if (!isValidObjectId(id)) return ResponseUtil.badRequest(ctx, "缺少记录ID");
|
||||
const record = await DBModel.EscortRecord.findById(id);
|
||||
if (!record || record.deletedAt) return ResponseUtil.error(ctx, "陪诊记录不存在", null, 404);
|
||||
if ((record.payment?.status || "unpaid") !== "refunding") {
|
||||
return ResponseUtil.badRequest(ctx, "当前订单不在退款中");
|
||||
}
|
||||
// 线上退款单还在处理中时不允许人工核销,必须先查询退款结果
|
||||
const processingRefund = await DBModel.RefundRecord.findOne({
|
||||
recordId: record._id,
|
||||
status: "processing",
|
||||
});
|
||||
if (processingRefund) {
|
||||
return ResponseUtil.badRequest(ctx, "存在处理中的线上退款,请先查询退款结果");
|
||||
}
|
||||
|
||||
const updatedRecord = await DBModel.EscortRecord.updateRecord(id, {
|
||||
"payment.status": "refunded",
|
||||
});
|
||||
if (!updatedRecord) return ResponseUtil.error(ctx, "陪诊记录不存在", null, 404);
|
||||
logger.info(`[payment] 人工核销退款完成 recordId=${id} method=${record.payment?.method || ""}`);
|
||||
return ResponseUtil.success(ctx, { record: updatedRecord }, "已标记为退款完成");
|
||||
} catch (err) {
|
||||
logger.error(`[payment] 人工核销退款失败 recordId=${ctx.params.id}: ${err?.message || err}`);
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== 后台巡检查单 ====================
|
||||
|
||||
@@ -233,11 +233,15 @@ const EscortRecordSchema = mongoose.Schema(
|
||||
*/
|
||||
EscortRecordSchema.statics.buildRecordFilter = function (options = {}) {
|
||||
const {
|
||||
status, cancelStatus, userId, appointmentDate, healthProfileId,
|
||||
status, cancelStatus, userId, appointmentDate, healthProfileId, attendantId,
|
||||
includeDeleted = false, includeCancelled = false,
|
||||
paymentStatus, payChannel, startDate, endDate, keyword,
|
||||
} = options;
|
||||
const filter = {};
|
||||
|
||||
// 多个 $or 条件(取消状态兼容、关键词)不能互相覆盖,统一收进 $and
|
||||
const andConditions = [];
|
||||
|
||||
// 软删除的订单默认不进入列表:数据库里保留审计,界面上视为已删除
|
||||
if (!includeDeleted) filter.deletedAt = null;
|
||||
|
||||
@@ -248,9 +252,13 @@ EscortRecordSchema.statics.buildRecordFilter = function (options = {}) {
|
||||
if (cancelStatus && Array.isArray(cancelStatus) && cancelStatus.length > 0) {
|
||||
if (cancelStatus.length === 1 && cancelStatus[0] === "cancelled") {
|
||||
// 兼容旧数据:取消曾存放在 status 中
|
||||
filter.$or = [{ cancelStatus: "cancelled" }, { status: "cancelled" }];
|
||||
andConditions.push({ $or: [{ cancelStatus: "cancelled" }, { status: "cancelled" }] });
|
||||
} else {
|
||||
filter.cancelStatus = { $in: cancelStatus };
|
||||
// 历史数据缺 cancelStatus 字段时按 none 处理
|
||||
const values = cancelStatus.includes("none")
|
||||
? [...cancelStatus, null]
|
||||
: cancelStatus;
|
||||
filter.cancelStatus = { $in: values };
|
||||
}
|
||||
} else if (!includeCancelled) {
|
||||
// 历史数据没有 cancelStatus 字段,按未取消处理;旧数据仍可能把 cancelled 存在 status 里
|
||||
@@ -258,13 +266,58 @@ EscortRecordSchema.statics.buildRecordFilter = function (options = {}) {
|
||||
if (!filter.status) filter.status = { $ne: "cancelled" };
|
||||
}
|
||||
if (userId) filter.userId = userId;
|
||||
// 陪诊员列表:只查 assign 到本人的订单
|
||||
if (attendantId) filter["attendant.id"] = attendantId;
|
||||
if (healthProfileId) filter.healthProfileId = healthProfileId;
|
||||
if (appointmentDate) {
|
||||
const start = new Date(`${appointmentDate}T00:00:00.000Z`);
|
||||
const end = new Date(start);
|
||||
end.setUTCDate(end.getUTCDate() + 1);
|
||||
filter["schedule.date"] = { $gte: start, $lt: end };
|
||||
|
||||
// 支付状态 / 渠道:管理端按收款情况对账时使用
|
||||
if (paymentStatus && Array.isArray(paymentStatus) && paymentStatus.length > 0) {
|
||||
filter["payment.status"] = { $in: paymentStatus };
|
||||
}
|
||||
if (payChannel) filter["payment.payChannel"] = payChannel;
|
||||
|
||||
// 预约日期:单日(appointmentDate)与区间(startDate/endDate)可并存,
|
||||
// 都按 UTC 日界换算,与历史口径保持一致
|
||||
const parseDay = (value) => {
|
||||
const date = new Date(`${value}T00:00:00.000Z`);
|
||||
return Number.isNaN(date.getTime()) ? null : date;
|
||||
};
|
||||
if (appointmentDate) {
|
||||
const start = parseDay(appointmentDate);
|
||||
if (start) {
|
||||
const end = new Date(start);
|
||||
end.setUTCDate(end.getUTCDate() + 1);
|
||||
filter["schedule.date"] = { $gte: start, $lt: end };
|
||||
}
|
||||
} else if (startDate || endDate) {
|
||||
const range = {};
|
||||
const start = startDate ? parseDay(startDate) : null;
|
||||
const end = endDate ? parseDay(endDate) : null;
|
||||
if (start) range.$gte = start;
|
||||
if (end) {
|
||||
end.setUTCDate(end.getUTCDate() + 1); // 含结束日当天
|
||||
range.$lt = end;
|
||||
}
|
||||
if (Object.keys(range).length) filter["schedule.date"] = range;
|
||||
}
|
||||
|
||||
// 关键词:就诊人姓名/电话、陪诊员姓名、医院名称,以及订单ID
|
||||
if (keyword && String(keyword).trim()) {
|
||||
const text = String(keyword).trim();
|
||||
const safe = text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
const reg = new RegExp(safe, "i");
|
||||
const or = [
|
||||
{ "patient.name": reg },
|
||||
{ "patient.mobile": reg },
|
||||
{ "attendant.name": reg },
|
||||
{ "hospital.name": reg },
|
||||
];
|
||||
if (/^[0-9a-fA-F]{24}$/.test(text)) or.push({ _id: text });
|
||||
andConditions.push({ $or: or });
|
||||
}
|
||||
|
||||
if (andConditions.length) filter.$and = andConditions;
|
||||
|
||||
return filter;
|
||||
};
|
||||
|
||||
@@ -281,50 +334,53 @@ EscortRecordSchema.statics.findRecords = async function (options = {}, cb) {
|
||||
};
|
||||
|
||||
// 列表记录、筛选总数和各页签计数一次返回,避免前端按当前页过滤或统计。
|
||||
// 计数只受非状态筛选(关键词/日期/支付/归属/陪诊员)影响,不受当前页签的 status/cancelStatus 影响
|
||||
EscortRecordSchema.statics.findRecordPage = async function (options = {}) {
|
||||
const { page = 1, pageSize = 20 } = options;
|
||||
const filter = this.buildRecordFilter(options);
|
||||
const baseFilter = this.buildRecordFilter({ ...options, status: null });
|
||||
const countBase = this.buildRecordFilter({
|
||||
...options,
|
||||
status: null,
|
||||
cancelStatus: null,
|
||||
includeCancelled: true,
|
||||
});
|
||||
// 生命周期页签只统计未申请取消的订单,避免同一单同时出现在「待确认」与「待取消」
|
||||
const activeBase = { ...countBase, cancelStatus: { $in: ["none", null] } };
|
||||
// 兼容历史数据:取消曾存放在 status 中
|
||||
const cancelledFilter = {
|
||||
...countBase,
|
||||
$and: [
|
||||
...(countBase.$and || []),
|
||||
{ $or: [{ cancelStatus: "cancelled" }, { status: "cancelled" }] },
|
||||
],
|
||||
};
|
||||
const skip = (page - 1) * pageSize;
|
||||
const [records, total, all, ongoing] = await Promise.all([
|
||||
|
||||
const [
|
||||
records, total, all, ongoing,
|
||||
pending, cancelRequested, confirmed, inProgress, completed, cancelled,
|
||||
] = await Promise.all([
|
||||
this.find(filter).sort({ "schedule.date": -1 }).skip(skip).limit(pageSize).exec(),
|
||||
this.countDocuments(filter).exec(),
|
||||
this.countDocuments(baseFilter).exec(),
|
||||
this.countDocuments(countBase).exec(),
|
||||
this.countDocuments({
|
||||
...baseFilter,
|
||||
...countBase,
|
||||
status: { $in: ["pending", "confirmed", "in_progress"] },
|
||||
cancelStatus: { $ne: "cancelled" },
|
||||
}).exec(),
|
||||
this.countDocuments({ ...activeBase, status: "pending" }).exec(),
|
||||
this.countDocuments({ ...countBase, cancelStatus: "requested" }).exec(),
|
||||
this.countDocuments({ ...activeBase, status: "confirmed" }).exec(),
|
||||
this.countDocuments({ ...activeBase, status: "in_progress" }).exec(),
|
||||
this.countDocuments({ ...activeBase, status: "completed" }).exec(),
|
||||
this.countDocuments(cancelledFilter).exec(),
|
||||
]);
|
||||
return { records, total, counts: { all, ongoing } };
|
||||
};
|
||||
|
||||
/**
|
||||
* 查找陪诊员的陪诊记录
|
||||
*
|
||||
* @param {ObjectId|string} attendantId - 陪诊员用户ID
|
||||
* @param {Object} options - 查询选项
|
||||
* @param {number} [options.page=1] - 页码
|
||||
* @param {number} [options.pageSize=20] - 每页数量
|
||||
* @param {string} [options.status] - 状态筛选(可选)
|
||||
* @param {Function} [cb] - 可选的回调函数
|
||||
* @returns {Promise<Array>} 陪诊记录列表(按预约日期倒序)
|
||||
*/
|
||||
EscortRecordSchema.statics.findRecordsByAttendant = async function (attendantId, options = {}, cb) {
|
||||
const { page = 1, pageSize = 20, status } = options;
|
||||
const filter = { "attendant.id": attendantId };
|
||||
|
||||
if (status) {
|
||||
filter.status = status;
|
||||
}
|
||||
|
||||
const skip = (page - 1) * pageSize;
|
||||
|
||||
return await this.find(filter)
|
||||
.sort({ "schedule.date": -1 })
|
||||
.skip(skip)
|
||||
.limit(pageSize)
|
||||
.exec(cb);
|
||||
return {
|
||||
records,
|
||||
total,
|
||||
counts: { all, ongoing, pending, cancelRequested, confirmed, inProgress, completed, cancelled },
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -5,14 +5,15 @@ import { pinyin } from "pinyin-pro";
|
||||
|
||||
/**
|
||||
* Organization Schema
|
||||
* 组织/机构基础信息,支持医院、诊所、体检中心等多种机构类型;
|
||||
* 组织/机构基础信息,支持诊所、体检中心等机构类型;
|
||||
* 医院基础信息统一在 hospital 集合(schema/hospital.js),此处不再维护。
|
||||
* 分院/院区用 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 索引冲突)" },
|
||||
@@ -29,18 +30,12 @@ const OrganizationSchema = mongoose.Schema(
|
||||
// 机构类型
|
||||
type: {
|
||||
type: String,
|
||||
enum: ["hospital", "clinic", "checkup_center", "other"],
|
||||
default: "hospital",
|
||||
comment: "机构类型:医院、诊所、体检中心、其他",
|
||||
enum: ["clinic", "checkup_center", "other"],
|
||||
default: "clinic",
|
||||
comment: "机构类型:诊所、体检中心、其他(医院在 hospital 集合)",
|
||||
},
|
||||
|
||||
// 等级/性质
|
||||
level: {
|
||||
type: String,
|
||||
enum: ["三级甲等", "三级乙等", "二级甲等", "二级乙等", "一级", "未定级", ""],
|
||||
default: "",
|
||||
comment: "医院等级",
|
||||
},
|
||||
// 性质
|
||||
nature: {
|
||||
type: String,
|
||||
enum: ["public", "private", "joint", "other", ""],
|
||||
@@ -77,27 +72,6 @@ const OrganizationSchema = mongoose.Schema(
|
||||
description: { type: String, default: "", comment: "机构简介" },
|
||||
remark: { type: String, default: "", 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: {
|
||||
createtime: { type: Date, default: Date.now, comment: "创建时间" },
|
||||
|
||||
@@ -99,6 +99,8 @@ function registerRoutes(app) {
|
||||
router.post("/escort-record/:id/pay", requireAuth, createLimit, handlerPayment.createPayment.bind(handlerPayment));
|
||||
router.get("/escort-record/:id/pay/status", requireAuth, handlerPayment.queryPayment.bind(handlerPayment));
|
||||
router.post("/escort-record/:id/refund/query", requireAuth, requireAdmin, handlerPayment.queryRefundResult.bind(handlerPayment));
|
||||
// 线下/人工退款核销:由平台确认已退款后把订单置为 refunded
|
||||
router.post("/escort-record/:id/refund/manual", requireAuth, requireAdmin, handlerPayment.completeManualRefund.bind(handlerPayment));
|
||||
|
||||
router.get("/escort-record/:id", requireAuth, handlerEscortRecord.getRecordById.bind(handlerEscortRecord));
|
||||
router.post("/escort-record", requireAuth, createLimit, handlerEscortRecord.createRecord.bind(handlerEscortRecord));
|
||||
@@ -127,6 +129,17 @@ function registerRoutes(app) {
|
||||
router.put("/health-profile/:id", requireAuth, requireAdmin, handlerHealthProfile.updateProfile.bind(handlerHealthProfile));
|
||||
router.delete("/health-profile/:id", requireAuth, requireAdmin, handlerHealthProfile.deleteProfile.bind(handlerHealthProfile));
|
||||
|
||||
// 当前账号的员工档案:登录即可访问,供管理端判定陪诊员身份。
|
||||
// 必须注册在 /employee 管理端路由之前,避免被更宽的路由抢占
|
||||
router.get("/employee/me", requireAuth, handlerEmployee.getMyEmployee.bind(handlerEmployee));
|
||||
|
||||
// 员工(陪诊师)管理:管理端 CRUD,必须管理员。
|
||||
// 与下方公开的 /attendant 公示接口分离:这里返回真实姓名等内部字段
|
||||
router.get("/employee", requireAuth, requireAdmin, handlerEmployee.getEmployees.bind(handlerEmployee));
|
||||
router.post("/employee", requireAuth, requireAdmin, createLimit, handlerEmployee.createEmployee.bind(handlerEmployee));
|
||||
router.put("/employee/:id", requireAuth, requireAdmin, updateLimit, handlerEmployee.updateEmployee.bind(handlerEmployee));
|
||||
router.patch("/employee/:id/status", requireAuth, requireAdmin, updateLimit, handlerEmployee.updateEmployeeStatus.bind(handlerEmployee));
|
||||
|
||||
// 医院基础信息:列表/详情公开,写接口仅管理员
|
||||
router.get("/hospital", handlerHospital.getHospitals.bind(handlerHospital));
|
||||
router.get("/hospital/:id", handlerHospital.getHospitalById.bind(handlerHospital));
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
/**
|
||||
* 只读体检:对比 models/schema 定义与实际 MongoDB,不做任何写操作。
|
||||
*
|
||||
* 检查项:
|
||||
* 1. 实际集合 vs 已注册模型(多出的集合 / 缺失的集合)
|
||||
* 2. 每个模型:schema 声明的索引 vs 数据库实际索引(缺的 / 多的)
|
||||
* 3. 各集合文档数
|
||||
* 4. 跨集合孤儿引用(删除订单后的 payment/refund 残留、employee.orgId、healthProfileId 等)
|
||||
* 5. 明显脏数据(旧式 status=cancelled、缺失 cancelStatus、organization 残留医院字段)
|
||||
*
|
||||
* 用法(在 api/health 下):node scripts/check_db_schema_sync.js
|
||||
*/
|
||||
import { DBModel } from "../models/index.js";
|
||||
import mongoose from "mongoose";
|
||||
|
||||
DBModel.init();
|
||||
const conn = DBModel.dbConnection;
|
||||
|
||||
const report = (title, rows) => {
|
||||
console.log(`\n===== ${title} =====`);
|
||||
if (!rows.length) {
|
||||
console.log(" (none)");
|
||||
return;
|
||||
}
|
||||
rows.forEach((row) => console.log(` ${row}`));
|
||||
};
|
||||
|
||||
const keyOf = (indexDef) => JSON.stringify(indexDef);
|
||||
|
||||
async function main() {
|
||||
const db = conn.db;
|
||||
|
||||
// ---------- 1. 集合 vs 模型 ----------
|
||||
const collections = (await db.listCollections().toArray()).map((c) => c.name);
|
||||
const modelNames = conn.modelNames(); // 小写 collection 名
|
||||
report("1. collections in DB but no model", collections.filter((c) => !modelNames.includes(c)));
|
||||
report("1. models without collection in DB", modelNames.filter((m) => !collections.includes(m)));
|
||||
|
||||
// ---------- 2/3. 索引与文档数 ----------
|
||||
for (const name of modelNames) {
|
||||
const model = conn.model(name);
|
||||
const actual = await db.collection(name).indexes();
|
||||
// schema.indexes() 返回 [ [indexDef, options], ... ],第一个元素才是键定义
|
||||
const expected = [{ key: { _id: 1 } }, ...model.schema.indexes().map(([def]) => ({ key: def }))];
|
||||
const actualKeys = new Set(actual.map((idx) => keyOf(idx.key)));
|
||||
|
||||
// 模型里声明的但库里没有的
|
||||
const missing = expected.filter((idx) => !actualKeys.has(keyOf(idx.key)));
|
||||
// 额外声明:unique/sparse/partial 选项差异只提示名字,人工确认
|
||||
const expectedKeys = new Set(expected.map((idx) => keyOf(idx.key)));
|
||||
const extra = actual.filter((idx) => !expectedKeys.has(keyOf(idx.key)));
|
||||
|
||||
const count = await db.collection(name).countDocuments({});
|
||||
console.log(`\n===== ${name} =====`);
|
||||
console.log(` docs: ${count}`);
|
||||
if (missing.length) console.log(` MISSING indexes (in schema, not in DB): ${missing.map((m) => keyOf(m.key)).join(", ")}`);
|
||||
if (extra.length) console.log(` EXTRA indexes (in DB, not in schema): ${extra.map((e) => `${keyOf(e.key)}${e.unique ? " [unique]" : ""}${e.sparse ? " [sparse]" : ""}${e.partialFilterExpression ? " [partial]" : ""}`).join(", ")}`);
|
||||
if (!missing.length && !extra.length) console.log(" indexes: in sync");
|
||||
}
|
||||
|
||||
// ---------- 4. 孤儿引用 ----------
|
||||
const orphans = async (label, fromColl, fromField, toColl, detail = null) => {
|
||||
const rows = await db.collection(fromColl).aggregate([
|
||||
{ $match: { [fromField]: { $ne: null } } },
|
||||
{ $group: { _id: `$${fromField}` } },
|
||||
{ $lookup: { from: toColl, localField: "_id", foreignField: "_id", as: "hit" } },
|
||||
{ $match: { hit: { $size: 0 } } },
|
||||
{ $count: "n" },
|
||||
]).toArray();
|
||||
if (!rows.length) {
|
||||
report(`4. orphan ${fromColl}.${fromField} -> ${toColl}`, []);
|
||||
return;
|
||||
}
|
||||
let lines = [` ${rows[0].n} distinct missing refs`];
|
||||
if (detail) {
|
||||
const missingIds = await db.collection(fromColl).aggregate([
|
||||
{ $match: { [fromField]: { $ne: null } } },
|
||||
{ $group: { _id: `$${fromField}` } },
|
||||
{ $lookup: { from: toColl, localField: "_id", foreignField: "_id", as: "hit" } },
|
||||
{ $match: { hit: { $size: 0 } } },
|
||||
{ $project: { _id: 1 } },
|
||||
]).toArray();
|
||||
const idSet = new Set(missingIds.map((d) => String(d._id)));
|
||||
const docs = await db.collection(fromColl).find({ [fromField]: { $in: [...idSet] } }).toArray();
|
||||
lines = lines.concat(docs.map((d) => detail(d)));
|
||||
}
|
||||
report(`4. orphan ${fromColl}.${fromField} -> ${toColl}`, lines);
|
||||
};
|
||||
await orphans(
|
||||
"payment_record.recordId", "payment_record", "recordId", "escort_record",
|
||||
(d) => ` ${d._id} outTradeNo=${d.outTradeNo} status=${d.status} totalFee=${d.totalFee} createdAt=${d.createdAt?.toISOString?.() ?? d.createdAt}`
|
||||
);
|
||||
await orphans("refund_record.recordId", "refund_record", "recordId", "escort_record");
|
||||
await orphans("refund_record.paymentId", "refund_record", "paymentId", "payment_record");
|
||||
await orphans("escort_record.healthProfileId", "escort_record", "healthProfileId", "health_profile");
|
||||
await orphans("employee.orgId", "employee", "orgId", "organization");
|
||||
await orphans("employee_review.recordId", "employee_review", "recordId", "escort_record");
|
||||
await orphans("employee_review.employeeId", "employee_review", "employeeId", "employee");
|
||||
await orphans("escort_record.paymentRecordId", "escort_record", "paymentRecordId", "payment_record");
|
||||
|
||||
// ---------- 5. 脏数据 ----------
|
||||
const dirty = [];
|
||||
const cnt = async (label, filter, coll) => {
|
||||
const n = await db.collection(coll).countDocuments(filter);
|
||||
if (n > 0) dirty.push(`${coll}: ${label} = ${n}`);
|
||||
};
|
||||
await cnt("status=cancelled(旧式取消写法)", { status: "cancelled" }, "escort_record");
|
||||
await cnt("缺少 cancelStatus 字段", { cancelStatus: { $exists: false } }, "escort_record");
|
||||
await cnt("type=hospital(应已清理)", { type: "hospital" }, "organization");
|
||||
await cnt("残留 forAgent 字段", { forAgent: { $exists: true } }, "organization");
|
||||
|
||||
// hospital name 唯一索引是否真生效:查重复名
|
||||
const dupNames = await db.collection("hospital").aggregate([
|
||||
{ $group: { _id: "$name", n: { $sum: 1 } } },
|
||||
{ $match: { n: { $gt: 1 } } },
|
||||
{ $limit: 10 },
|
||||
]).toArray();
|
||||
if (dupNames.length) dirty.push(`hospital: 重复 name = ${dupNames.map((d) => `${d._id}(${d.n})`).join(", ")}`);
|
||||
|
||||
// organization 残留医院专属字段
|
||||
const orgHospitalFields = await db.collection("organization").countDocuments({
|
||||
$or: [
|
||||
{ overview: { $exists: true } }, { photos: { $exists: true } },
|
||||
{ departments: { $exists: true } }, { doctors: { $exists: true } },
|
||||
{ guides: { $exists: true } }, { level: { $exists: true } },
|
||||
],
|
||||
});
|
||||
if (orgHospitalFields > 0) dirty.push(`organization: 残留医院字段文档 = ${orgHospitalFields}`);
|
||||
|
||||
// user 集合存在性(多模型 ref user)
|
||||
if (!collections.includes("user")) dirty.push("user 集合不存在,但多张表 ref user");
|
||||
|
||||
report("5. dirty/stale data", dirty.map((d) => d.replace(/^/, "")));
|
||||
|
||||
console.log("\n(check done, read-only)");
|
||||
}
|
||||
|
||||
if (conn.readyState === 1) {
|
||||
main().catch((e) => { console.error(e); process.exitCode = 1; }).finally(() => conn.close());
|
||||
} else {
|
||||
conn.once("connected", () => main().catch((e) => { console.error(e); process.exitCode = 1; }).finally(() => conn.close()));
|
||||
conn.once("error", (e) => { console.error(e); process.exit(1); });
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* 只读补查:孤儿 payment_record 明细 + user/users 集合归属确认。
|
||||
* 用法(在 api/health 下):node scripts/check_orphan_payments.js
|
||||
*/
|
||||
import { DBModel } from "../models/index.js";
|
||||
|
||||
DBModel.init();
|
||||
const conn = DBModel.dbConnection;
|
||||
|
||||
async function main() {
|
||||
const db = conn.db;
|
||||
|
||||
// 找出 recordId 在 escort_record 中不存在的 payment_record
|
||||
const orphanPayments = await db.collection("payment_record").aggregate([
|
||||
{ $match: { recordId: { $ne: null } } },
|
||||
{ $lookup: { from: "escort_record", localField: "recordId", foreignField: "_id", as: "hit" } },
|
||||
{ $match: { hit: { $size: 0 } } },
|
||||
]).toArray();
|
||||
|
||||
console.log(`orphan payment_record docs: ${orphanPayments.length}`);
|
||||
for (const p of orphanPayments) {
|
||||
console.log(` ${p._id} outTradeNo=${p.outTradeNo} status=${p.status} totalFee=${p.totalFee} payerTotal=${p.payerTotal} userId=${p.userId} createdAt=${p.createdAt?.toISOString?.() ?? p.createdAt}`);
|
||||
const refunds = await db.collection("refund_record").find({ paymentId: p._id }).toArray();
|
||||
refunds.forEach((r) => console.log(` refund: ${r._id} outRefundNo=${r.outRefundNo} status=${r.status} amount=${r.refundAmount}`));
|
||||
}
|
||||
|
||||
// user / users 集合情况
|
||||
for (const name of ["user", "users"]) {
|
||||
const exists = await db.listCollections({ name }).hasNext();
|
||||
if (!exists) {
|
||||
console.log(`\ncollection ${name}: NOT EXIST`);
|
||||
continue;
|
||||
}
|
||||
const n = await db.collection(name).countDocuments({});
|
||||
const sample = await db.collection(name).findOne({}, { projection: { mobile: 1, phone: 1, name: 1, nickname: 1, createdAt: 1, "meta.createtime": 1 } });
|
||||
console.log(`\ncollection ${name}: ${n} docs, sample=${JSON.stringify(sample)}`);
|
||||
}
|
||||
|
||||
// 现存 escort_record 的 userId 是否在 users 里能对上
|
||||
const records = await db.collection("escort_record").find({}, { projection: { userId: 1 } }).toArray();
|
||||
for (const r of records) {
|
||||
const inUsers = r.userId ? await db.collection("users").countDocuments({ _id: r.userId }) : 0;
|
||||
console.log(`escort_record ${r._id} userId=${r.userId} in users: ${inUsers}`);
|
||||
}
|
||||
|
||||
console.log("\n(check done, read-only)");
|
||||
}
|
||||
|
||||
if (conn.readyState === 1) {
|
||||
main().catch((e) => { console.error(e); process.exitCode = 1; }).finally(() => conn.close());
|
||||
} else {
|
||||
conn.once("connected", () => main().catch((e) => { console.error(e); process.exitCode = 1; }).finally(() => conn.close()));
|
||||
conn.once("error", (e) => { console.error(e); process.exit(1); });
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
/**
|
||||
* 一次性清理:物理删除 escort_record(陪诊订单)里 2026-11-01 之前创建的记录。
|
||||
*
|
||||
* 注意:已确认要全删(含已支付/已完成订单),不受「已收款订单需留存审计」的常规约束。
|
||||
* 时间口径:meta.createtime < 2026-11-01 00:00:00(Asia/Shanghai)。
|
||||
*
|
||||
* 用法(在 api/health 下):
|
||||
* node scripts/delete_escort_records_before_202611.js # 仅统计,不删除
|
||||
* node scripts/delete_escort_records_before_202611.js --apply # 实际删除
|
||||
*/
|
||||
import { DBModel } from "../models/index.js";
|
||||
|
||||
DBModel.init();
|
||||
const conn = DBModel.dbConnection;
|
||||
const apply = process.argv.includes("--apply");
|
||||
|
||||
// 东八区 2026-11-01 00:00:00,避免服务器时区差异
|
||||
const CUTOFF = new Date("2026-11-01T00:00:00+08:00");
|
||||
const filter = { "meta.createtime": { $lt: CUTOFF } };
|
||||
|
||||
async function cleanup() {
|
||||
const matched = await DBModel.EscortRecord.countDocuments(filter).exec();
|
||||
const byStatus = await DBModel.EscortRecord.aggregate([
|
||||
{ $match: filter },
|
||||
{ $group: { _id: "$status", count: { $sum: 1 } } },
|
||||
]).exec();
|
||||
|
||||
console.log(`cutoff=${CUTOFF.toISOString()} (2026-11-01 00:00:00 +08:00)`);
|
||||
console.log(`matched escort records created before cutoff: ${matched}`);
|
||||
byStatus.forEach((row) => console.log(` status=${row._id ?? "none"}: ${row.count}`));
|
||||
|
||||
if (!apply) {
|
||||
console.log("dry-run only. re-run with --apply to delete.");
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await DBModel.EscortRecord.deleteMany(filter);
|
||||
console.log(`deleted: ${result.deletedCount}`);
|
||||
}
|
||||
|
||||
cleanup()
|
||||
.catch((error) => {
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
})
|
||||
.finally(() => {
|
||||
conn.close();
|
||||
});
|
||||
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* 一次性清理:删除 organization 集合里医院相关的记录。
|
||||
*
|
||||
* 医院基础信息已统一迁移到 hospital 集合(schema/hospital.js),
|
||||
* organization 集合不再维护医院数据;本脚本删除 type=hospital 的记录。
|
||||
*
|
||||
* 用法:在 api/health 下执行 `node scripts/delete_organization_hospitals.js`
|
||||
*/
|
||||
import { DBModel } from "../models/index.js";
|
||||
|
||||
DBModel.init();
|
||||
const conn = DBModel.dbConnection;
|
||||
|
||||
async function cleanup() {
|
||||
// 非医院记录(历史数据里可能有未填 type 的)统一保留,只删明确标记为医院的
|
||||
const filter = { type: "hospital" };
|
||||
const matched = await DBModel.Organization.countDocuments(filter).exec();
|
||||
const result = await DBModel.Organization.deleteMany(filter);
|
||||
|
||||
console.log(`deleted: matched=${matched}, deletedCount=${result.deletedCount}`);
|
||||
const remaining = await DBModel.Organization.countDocuments({}).exec();
|
||||
console.log(`remaining organizations: ${remaining}`);
|
||||
await conn.close();
|
||||
}
|
||||
|
||||
if (conn.readyState === 1) {
|
||||
cleanup().catch((error) => {
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
});
|
||||
} else {
|
||||
conn.once("connected", () => {
|
||||
cleanup().catch((error) => {
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
});
|
||||
});
|
||||
conn.once("error", (error) => {
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
/**
|
||||
* 一次性清理:
|
||||
* 1. 删除数据库里 schema 已不再声明的旧索引
|
||||
* - hospital: basic.name / location.city+basic.level / service.isEnabled / fudanRank / fudanOrder
|
||||
* - employee: name
|
||||
* 2. 删除指向已不存在订单的孤儿 payment_record(均为 closed 未实付,无关联退款)
|
||||
*
|
||||
* 用法(在 api/health 下):
|
||||
* node scripts/drop_stale_indexes_and_orphan_payments.js # 仅检查,不执行
|
||||
* node scripts/drop_stale_indexes_and_orphan_payments.js --apply # 实际执行
|
||||
*/
|
||||
import { DBModel } from "../models/index.js";
|
||||
|
||||
DBModel.init();
|
||||
const conn = DBModel.dbConnection;
|
||||
const apply = process.argv.includes("--apply");
|
||||
|
||||
// 键定义 -> 索引名。dropIndex 既可按名也可按键,这里按名删,避免键顺序歧义
|
||||
const STALE_INDEXES = [
|
||||
{ coll: "hospital", key: { "basic.name": 1 } },
|
||||
{ coll: "hospital", key: { "location.city": 1, "basic.level": 1 } },
|
||||
{ coll: "hospital", key: { "service.isEnabled": 1 } },
|
||||
{ coll: "hospital", key: { fudanRank: 1 } },
|
||||
{ coll: "hospital", key: { fudanOrder: 1 } },
|
||||
{ coll: "employee", key: { name: 1 } },
|
||||
];
|
||||
|
||||
async function main() {
|
||||
const db = conn.db;
|
||||
// ---------- 1. 旧索引 ----------
|
||||
for (const { coll, key } of STALE_INDEXES) {
|
||||
const indexes = await db.collection(coll).indexes();
|
||||
// 匹配键定义完全一致的索引(忽略 _id 之类附加字段)
|
||||
const hit = indexes.find(
|
||||
(idx) => JSON.stringify(idx.key) === JSON.stringify(key)
|
||||
);
|
||||
if (!hit) {
|
||||
console.log(`index ${coll} ${JSON.stringify(key)}: not found (already dropped)`);
|
||||
continue;
|
||||
}
|
||||
if (!apply) {
|
||||
console.log(`index ${coll} ${JSON.stringify(key)}: found as "${hit.name}" (dry-run)`);
|
||||
continue;
|
||||
}
|
||||
await db.collection(coll).dropIndex(hit.name);
|
||||
console.log(`index ${coll} ${JSON.stringify(key)}: dropped "${hit.name}"`);
|
||||
}
|
||||
|
||||
// ---------- 2. 孤儿 payment_record ----------
|
||||
const orphans = await db.collection("payment_record").aggregate([
|
||||
{ $match: { recordId: { $ne: null } } },
|
||||
{ $lookup: { from: "escort_record", localField: "recordId", foreignField: "_id", as: "hit" } },
|
||||
{ $match: { hit: { $size: 0 } } },
|
||||
]).toArray();
|
||||
|
||||
console.log(`\norphan payment_record docs: ${orphans.length}`);
|
||||
for (const p of orphans) {
|
||||
console.log(` ${p._id} outTradeNo=${p.outTradeNo} status=${p.status} payerTotal=${p.payerTotal}`);
|
||||
|
||||
// 安全阀:只删 closed 且未实付、无关联退款的流水,其余跳过人工处理
|
||||
const refunds = await db.collection("refund_record").countDocuments({ paymentId: p._id });
|
||||
if (p.status !== "closed" || p.payerTotal > 0 || refunds > 0) {
|
||||
console.log(` skipped (status/paid/refund safety check failed)`);
|
||||
continue;
|
||||
}
|
||||
if (!apply) continue;
|
||||
await db.collection("payment_record").deleteOne({ _id: p._id });
|
||||
console.log(` deleted`);
|
||||
}
|
||||
|
||||
if (!apply) console.log("\ndry-run only. re-run with --apply to execute.");
|
||||
}
|
||||
|
||||
if (conn.readyState === 1) {
|
||||
main().catch((e) => { console.error(e); process.exitCode = 1; }).finally(() => conn.close());
|
||||
} else {
|
||||
conn.once("connected", () => main().catch((e) => { console.error(e); process.exitCode = 1; }).finally(() => conn.close()));
|
||||
conn.once("error", (e) => { console.error(e); process.exit(1); });
|
||||
}
|
||||
+134
-89
@@ -12,135 +12,180 @@ import {
|
||||
const MAIN_ID = "64b000000000000000000101";
|
||||
const BRANCH_ID = "64b000000000000000000102";
|
||||
const MAIN_NAME = "中国医学科学院北京协和医院";
|
||||
const BRANCH_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: {},
|
||||
entityName: MAIN_NAME,
|
||||
nicknames: ["协和", "北京协和"],
|
||||
pinyin: "zhongguoyixuekexueyuanbeijingxieheyiyuan",
|
||||
pinyinFL: "zgyxkxybjxhyy",
|
||||
province: "北京市",
|
||||
city: "北京市",
|
||||
address: "东城区帅府园1号",
|
||||
phone: "010-69151188",
|
||||
level: "三级甲等",
|
||||
departments: ["心内科", "风湿免疫科"],
|
||||
fudanRank: { rank: 1, grade: "A+++++", order: 1 },
|
||||
meta: { updatetime: new Date("2026-11-05T00:00:00.000Z") },
|
||||
};
|
||||
|
||||
const branch = {
|
||||
...main,
|
||||
_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: "旧科室" }] },
|
||||
address: "西城区大木仓胡同41号",
|
||||
departments: ["妇科内分泌与生殖医学中心"],
|
||||
};
|
||||
|
||||
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 } = {}) {
|
||||
/**
|
||||
* hospital 模型桩:工具通过模型静态方法读写,桩直接记录调用参数
|
||||
*/
|
||||
function createHospitalStub({ list = [], total = list.length, one = null } = {}) {
|
||||
const calls = [];
|
||||
return {
|
||||
calls,
|
||||
countDocuments(filter) {
|
||||
calls.push({ method: "countDocuments", filter });
|
||||
return Promise.resolve(count);
|
||||
findHospitals(options) {
|
||||
calls.push({ method: "findHospitals", options });
|
||||
return Promise.resolve({
|
||||
list,
|
||||
total,
|
||||
page: options.page ?? 1,
|
||||
pageSize: options.pageSize ?? 20,
|
||||
});
|
||||
},
|
||||
find(filter) {
|
||||
return createQuery(list, calls, "find", filter);
|
||||
findHospitalById(id) {
|
||||
calls.push({ method: "findHospitalById", id });
|
||||
return Promise.resolve(one);
|
||||
},
|
||||
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 });
|
||||
},
|
||||
};
|
||||
updateHospitalById(id, update) {
|
||||
calls.push({ method: "updateHospitalById", id, update });
|
||||
return Promise.resolve({
|
||||
...one,
|
||||
...update,
|
||||
// 模拟模型静态方法自动补派生字段
|
||||
pinyin: "paiban",
|
||||
fudanRank: { rank: 1, grade: "A+++++", order: 1 },
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function withOrganization(stub, fn) {
|
||||
const previous = DBModel.Organization;
|
||||
DBModel.Organization = stub;
|
||||
function withHospital(stub, fn) {
|
||||
const previous = DBModel.Hospital;
|
||||
DBModel.Hospital = stub;
|
||||
return Promise.resolve(fn()).finally(() => {
|
||||
DBModel.Organization = previous;
|
||||
DBModel.Hospital = previous;
|
||||
});
|
||||
}
|
||||
|
||||
test("医院列表只查可用医院,并可按 parentId 列院区", async () => {
|
||||
const stub = createOrganizationStub({ list: [main, branch], count: 2 });
|
||||
await withOrganization(stub, async () => {
|
||||
test("医院列表走 hospital 集合,并支持关键词与主体名称过滤", async () => {
|
||||
const stub = createHospitalStub({ list: [main, branch], total: 2 });
|
||||
await withHospital(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));
|
||||
assert.equal(byKeyword.total, 2);
|
||||
assert.equal(byKeyword.data[0].entityName, MAIN_NAME);
|
||||
assert.equal(byKeyword.data[0].phone, "010-69151188");
|
||||
assert.equal(stub.calls[0].options.keyword, "协和");
|
||||
|
||||
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);
|
||||
const byEntity = parseResult(
|
||||
await hospitalInfoListTool.invoke({ entityName: MAIN_NAME })
|
||||
);
|
||||
assert.equal(byEntity.success, true);
|
||||
assert.equal(stub.calls.at(-1).options.entityName, MAIN_NAME);
|
||||
});
|
||||
});
|
||||
|
||||
test("按分院 id 查询返回平铺字段和总院名称", async () => {
|
||||
const stub = createOrganizationStub({ list: [main], one: branch });
|
||||
await withOrganization(stub, async () => {
|
||||
test("按 id 查询返回 hospital 基础信息与派生字段", async () => {
|
||||
const stub = createHospitalStub({ one: branch });
|
||||
await withHospital(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, "妇科内分泌与生殖医学中心");
|
||||
assert.equal(result.data[0].entityName, MAIN_NAME);
|
||||
assert.deepEqual(result.data[0].nicknames, ["协和", "北京协和"]);
|
||||
assert.equal(result.data[0].fudanRank.grade, "A+++++");
|
||||
assert.deepEqual(result.data[0].departments, ["妇科内分泌与生殖医学中心"]);
|
||||
});
|
||||
});
|
||||
|
||||
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: "新就医信息" })
|
||||
test("按名称查询可按科室过滤,科室为字符串数组", async () => {
|
||||
const stub = createHospitalStub({ list: [main, branch], total: 2 });
|
||||
await withHospital(stub, async () => {
|
||||
const result = parseResult(
|
||||
await hospitalInfoQueryTool.invoke({ hospitalName: "协和", department: "风湿" })
|
||||
);
|
||||
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);
|
||||
assert.equal(result.success, true);
|
||||
assert.equal(result.total, 2);
|
||||
assert.deepEqual(result.data[0].departments, ["风湿免疫科"]);
|
||||
assert.deepEqual(result.data[1].departments, []);
|
||||
});
|
||||
});
|
||||
|
||||
test("查询缺少 id 与名称时明确报错", async () => {
|
||||
const stub = createHospitalStub();
|
||||
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, /医院名称不能为空/);
|
||||
});
|
||||
});
|
||||
|
||||
+40
-9
@@ -2,6 +2,16 @@ import mongoose from "mongoose";
|
||||
import { DBModel } from "../models/index.js";
|
||||
|
||||
const ADMIN_APP = "wxapp-escort-admin";
|
||||
const WEB_ADMIN_APP = "web-escort-admin";
|
||||
|
||||
/**
|
||||
* 管理端应用清单:传统管理小程序 + Web 后台
|
||||
*
|
||||
* 两者在 user_app 里是彼此独立的成员关系,这里并列是过渡期兼容写法——
|
||||
* 任一应用内 role=admin 即视为管理员。等 user 服务重构完成、token 能带出
|
||||
* 应用维度后,改为按请求来源应用分别校验
|
||||
*/
|
||||
const ADMIN_APP_IDS = [ADMIN_APP, WEB_ADMIN_APP];
|
||||
|
||||
/**
|
||||
* 管理端 app 条目里的角色数组
|
||||
@@ -27,20 +37,41 @@ function appRoles(user) {
|
||||
* 现在注册侧已拒绝客户端写 app,但库里可能残留历史账号,
|
||||
* 因此要求显式 role === 'admin';role 缺失的历史账号暂按管理员放行并打告警,
|
||||
* 待库中补齐 app.wxapp-escort-admin.role = ['admin'] 后再收紧(见 doc/api-review-plan.md B1)。
|
||||
*
|
||||
* 用户模型重构后(doc/user-multi-app-plan.md),userInfo 响应会带只读数组 apps,
|
||||
* 此时优先按成员关系判定,status=disabled 的成员不再视为管理员。
|
||||
*/
|
||||
function isAdmin(user) {
|
||||
const entry = user?.app?.[ADMIN_APP];
|
||||
if (!entry) return false;
|
||||
if (!user) return false;
|
||||
|
||||
const roles = appRoles(user);
|
||||
if (roles.includes("admin")) return true;
|
||||
|
||||
if (entry.role === undefined) {
|
||||
console.warn(
|
||||
"[permissions] 管理员账号缺少 role 字段,请补齐 app.wxapp-escort-admin.role = ['admin']"
|
||||
// 重构后的只读视图:apps: [{ appId, roles, status }]
|
||||
if (Array.isArray(user.apps)) {
|
||||
return user.apps.some(
|
||||
(m) =>
|
||||
ADMIN_APP_IDS.includes(m?.appId) &&
|
||||
m.status !== "disabled" &&
|
||||
Array.isArray(m.roles) &&
|
||||
m.roles.includes("admin")
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
// 过渡期:仍读 user.app
|
||||
for (const appId of ADMIN_APP_IDS) {
|
||||
const entry = user.app?.[appId];
|
||||
if (!entry) continue;
|
||||
|
||||
const roles = Array.isArray(entry.role) ? entry.role : [entry.role].filter(Boolean);
|
||||
if (roles.includes("admin")) return true;
|
||||
|
||||
// 历史兼容:role 缺失时按管理员放行并告警
|
||||
if (entry.role === undefined) {
|
||||
console.warn(
|
||||
`[permissions] 管理员账号缺少 role 字段,请补齐 app.${appId}.role = ['admin']`
|
||||
);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user