Compare commits

...
13 Commits
Author SHA1 Message Date
lik fc993a7761 fix(agent): 订单工具取消时延后关单并复核支付状态
关单有外部副作用,原实现放在取消分支里,参数校验失败也会先关单;
且取消已收款订单时用的是关单前的旧支付状态。改为全部确定性校验
通过后再关单,关单发现已付款时以库中最新状态复核金额与实收输入,
并把正式取消收敛到退款中。
2026-11-08 12:07:47 +08:00
lik 503c4b52e9 fix(payment): 关单失败时中止本次支付发起
改价后重新发起支付时,旧 prepay 关单失败却继续放行,会让同一订单
同时存在两张可支付流水。改为关单失败直接返回 409 并提示稍后重试。
2026-11-08 12:05:22 +08:00
lik 5198830edb fix(escort): 陪诊员仅可管理分配给自己的订单
在职陪诊员此前对任意订单都能执行状态流转,订单主人只要同时是陪诊员
就能自行确认或完成服务。改为只有订单上指派的陪诊员才具备管理权,
其余情况一律走用户取消流程。
2026-11-08 12:05:17 +08:00
lik a281fa2a64 test(payment): 补充退款迟到结果不回退支付与订单状态的用例 2026-11-08 12:05:12 +08:00
lik ad7773a39d fix: 退款非成功结果不回退已成功的状态
创建/查询退款响应可能晚于成功回调到达:RefundRecord 与
PaymentRecord 均加 status 前置条件,迟到的 PROCESSING
不再把 success/refunded 回退成 processing/refunding
2026-11-08 12:01:07 +08:00
lik 4c2db2b6df feat: 陪诊师入驻申请与审核链路
- 新增 attendant_application 表与 5 个接口:提交/我的申请/审核列表/
  材料大图/审批,/mine 注册在 /:id 之前
- 提交侧按员工档案岗位分支:在职陪诊师与管理员及其他岗位 409 拒绝,
  转岗由管理员后台显式操作;停用陪诊师可重新申请
- 审批两步走不依赖事务:条件更新抢占 pending,ensureEmployee 单条
  条件 upsert 幂等建档(只放行无档案或已有 attendant 档案),
  失败靠 approvedEmployeeId 为空续跑
- 岗位冲突时申请单条件回滚为 pending,不卡死在"已通过但未建档"
- employee.userId 加 partial unique 索引并移除 employeeNo 默认值,
  附迁移与存量校验脚本;员工管理端绑定账号查重与 userIdSource 标记
- 证件照复用 parseImage(单张 3MB),入驻前缀放宽请求体上限;
  索引创建失败改为记日志,避免启动即崩
2026-11-08 12:00:32 +08:00
lik 47393adde0 feat: Agent 工具日志结构化描述
工具结果与 custom 流事件改用 describeToolResult/describeStreamPayload
输出摘要,替代截断 200 字符的原始内容;thread_id 取 userInfo._id
2026-11-08 12:00:27 +08:00
lik 9a1242ffbc fix: 限流分桶按路由模式归一并统一清理过期计数
- 分桶键用路由模式(如 /health/escort-record/:id)而非真实 path,
  防止换订单 ID 绕开额度
- 计数桶统一登记、单定时器清理,windowMs 写入记录供过期判断
2026-11-08 12:00:26 +08:00
lik b0b706a1c4 feat: WebSocket 实时识别帧改走独立队列
asr 分片只与同一轮识别串行,不再排在在途模型生成后面,
避免用户边等回复边说话时 PCM 整段堆积;ping 心跳也立即应答
2026-11-08 12:00:26 +08:00
lik 70699cf36d feat: 微信查单加短 TTL 缓存并允许 closed 终态回写
- queryPayment 高频轮询加短 TTL 缓存 + 同单号并发合并,
  避免把支付页轮询放大成微信侧流量;失败不缓存
- closed 也允许回写流水:关单与支付成功存在竞态,
  以微信侧明确终结的交易状态收敛本地流水
2026-11-08 12:00:26 +08:00
lik b386dc469f fix: 健康档案更新摊平嵌套对象避免 Mongo 路径冲突
$set 同时出现 profile 与 profile.pinyin 会触发路径冲突,
整块覆盖嵌套对象又绕开 pre("save") 丢拼音字段;
pickFields 支持 flatten 递归摊平后按点号路径写入
2026-11-08 12:00:25 +08:00
lik 5878520707 feat: 订单可改字段按角色收敛并修复嵌套字段覆盖
- 陪诊员只能写服务备注与就诊小结;订单主人按状态收敛,
  取消中/已取消一律冻结
- 更新前把嵌套子文档摊平成点号路径并与现值合并:
  整块 $set 会抹掉未提交字段,与点号路径混用还会触发 Mongo 路径冲突
- 通用更新接口的状态迁移改走状态机,软删除订单按不存在处理
2026-11-08 11:59:53 +08:00
lik ffa6d8c1e3 fix: 统一错误出口并把 user 服务非 2xx 视为故障
- 新增最外层错误中间件:body-parser 的 400/413 等也转成约定 JSON,
  客户端只收通用文案,5xx 详情仅进日志
- token 校验对 user 服务非 2xx 抛错而非按未登录处理,
  避免服务抖动时在线用户被负缓存 60 秒踢回登录页
2026-11-08 11:59:31 +08:00
27 changed files with 2558 additions and 76 deletions
+3 -2
View File
@@ -7,6 +7,7 @@ import config from '../../../config.js';
import logger from '../../../utils/logger.js';
import { createRestrictedBackend } from "../../infra/restricted_fs_backend.js";
import { appendToolMessage, trimHistory } from "../../infra/history.js";
import { describeToolResult, describeStreamPayload } from "../../infra/tool_log.js";
import { OutputGuard, OUTPUT_MAX_CHARS } from "../../infra/guard.js";
// 密钥由 conf.json 统一提供;百度地图 token 由 http_get 按域名在服务端注入
@@ -130,7 +131,7 @@ export default class EscortAdminAgent {
for (const msg of data_.messages ?? []) {
if (msg.type === "tool") {
appendToolMessage(session.messages, msg);
logger.info(`Tool complete: ${msg.name}, Result: ${String(msg.content).slice(0, 200)}`);
logger.info(`Tool complete: ${msg.name}`, describeToolResult(msg.content));
}
}
} else if (nodeName === "model_request") {
@@ -165,7 +166,7 @@ export default class EscortAdminAgent {
callback(source, "tool", message.text, message.id);
}
} else if (mode === "custom") {
logger.info("custom: ", data);
logger.info("custom event", describeStreamPayload(data));
}
}
+4 -3
View File
@@ -15,6 +15,7 @@ process.env.BAIDU_MAP_AUTH_TOKEN ??= config.agent.baiduMap?.authToken;
import Prompts from "./prompts.js";
import { createRestrictedBackend } from "../../infra/restricted_fs_backend.js";
import { appendToolMessage, trimHistory } from "../../infra/history.js";
import { describeToolResult, describeStreamPayload } from "../../infra/tool_log.js";
import { OutputGuard, OUTPUT_MAX_CHARS } from "../../infra/guard.js";
import {
webFetchTool, webSearchTool, getCalendarInfoTool, getYearHolidaysTool,
@@ -103,7 +104,7 @@ export default class EscortAgent {
recursion_limit: 50,
streamMode: ["updates", "messages", "custom"], subgraphs: true,
configurable: {
thread_id: msgs[0].userId
thread_id: String(userInfo?._id ?? "")
}
})) {
const isSubagent = namespace.some(s => s.startsWith("tools:"));
@@ -119,7 +120,7 @@ export default class EscortAgent {
for (const msg of data_.messages ?? []) {
if (msg.type === "tool") {
appendToolMessage(this.messages, msg);
logger.info(`Tool complete: ${msg.name}, Result: ${String(msg.content).slice(0, 200)}`);
logger.info(`Tool complete: ${msg.name}`, describeToolResult(msg.content));
}
}
} else if (nodeName === "model_request") {
@@ -157,7 +158,7 @@ export default class EscortAgent {
callback(source, "tool", message.text, message.id);
}
} else if (mode === "custom") {
logger.info("custom: ", data);
logger.info("custom event", describeStreamPayload(data));
}
}
+47
View File
@@ -0,0 +1,47 @@
/**
* 工具结果 / 流事件的安全日志摘要
*
* 工具返回里可能包含患者姓名、手机号、健康档案、订单地址等健康数据,
* 直接记录正文(即使只截前 200 字)也会把这些信息落盘。
* 这里只提取排障需要的元信息:长度、success 标记、字段名。
*/
/**
* 工具结果摘要
* @param {*} content 工具返回内容(通常是 JSON 字符串)
* @returns {{chars: number, success?: boolean, errorCode?: string}}
*/
export function describeToolResult(content) {
const text = typeof content === "string" ? content : "";
const info = { chars: text.length };
if (!text) return info;
try {
const parsed = JSON.parse(text);
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
if (typeof parsed.success === "boolean") info.success = parsed.success;
// 只接受短错误码;错误文案可能包含用户输入的姓名/手机号,不记录
if (typeof parsed.errorCode === "string" && parsed.errorCode.length <= 64) {
info.errorCode = parsed.errorCode;
}
}
} catch {
// 纯文本或截断后的 JSON 不解析,也不记录正文
}
return info;
}
/**
* 流事件摘要:只记录数据类型/字段名,不记录字段值
* @param {*} data custom 流事件数据
* @returns {{type?: string, chars?: number, items?: number, keys?: string[]}}
*/
export function describeStreamPayload(data) {
if (typeof data === "string") return { type: "string", chars: data.length };
if (Array.isArray(data)) return { type: "array", items: data.length };
if (data && typeof data === "object") {
return { type: "object", keys: Object.keys(data).slice(0, 10) };
}
return { type: typeof data };
}
@@ -59,10 +59,7 @@ const escortRecordSetTool = tool(
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) {
@@ -175,6 +172,30 @@ const escortRecordSetTool = tool(
update["payment.status"] = "refunding";
}
// 所有确定性校验通过后才关闭在途预付单。关单期间若支付成功,
// 以刷新后的支付状态复核金额/实收输入,并把正式取消收敛到退款中。
if (update.cancelStatus) {
await HandlerPayment.closeOpenPayRecords(orderId);
const fresh = await DBModel.EscortRecord.findById(orderId);
effectivePay = fresh?.payment || effectivePay;
const refreshedPayStatus = effectivePay.status || "unpaid";
if (["partial", "paid", "refunding", "refunded"].includes(refreshedPayStatus)) {
const invalidStatus = payment?.status !== undefined
&& payment.status !== refreshedPayStatus
&& !(update.cancelStatus === "cancelled" && payment.status === "refunding");
const invalidPaidFee = payment?.paidFee !== undefined
&& Number(payment.paidFee) !== (Number(effectivePay.paidFee) || 0);
const invalidTotalFee = payment?.totalFee !== undefined
&& Number(payment.totalFee) !== (Number(effectivePay.totalFee) || 0);
if (invalidStatus || invalidPaidFee || invalidTotalFee) {
return { success: false, error: "Record payment state changed while updating. Re-query and retry." };
}
}
if (update.cancelStatus === "cancelled" && ["partial", "paid"].includes(refreshedPayStatus)) {
update["payment.status"] = "refunding";
}
}
update["meta.updatetime"] = Date.now();
// 以读取时的状态作为更新条件,避免并发下跳过中间状态;同时排除已软删除的订单
+50 -2
View File
@@ -11,9 +11,9 @@ import ResponseUtil from './utils/responseUtil.js';
const STATIC_DIR = fileURLToPath(new URL('./statics', import.meta.url));
// 语音/图片识别与培训报名材料走 base64 JSON,单请求体可能达到数 MB;
// 语音/图片识别、培训报名材料与陪诊师入驻证件照走 base64 JSON,单请求体可能达到数 MB;
// 只对这些前缀放宽解析上限,其余接口维持 1MB,避免全局放大内存占用
const LARGE_BODY_PREFIXES = ['/health/ai/', '/health/training-application'];
const LARGE_BODY_PREFIXES = ['/health/ai/', '/health/training-application', '/health/attendant-application'];
const DEFAULT_BODY_LIMIT = '1mb';
const LARGE_BODY_LIMIT = '20mb';
const defaultBodyParser = bodyParser({
@@ -27,6 +27,51 @@ const largeBodyParser = bodyParser({
textLimit: LARGE_BODY_LIMIT,
});
// 客户端错误只回通用文案:body-parser / 框架的原始 message 可能带内部字段名
const CLIENT_ERROR_MESSAGES = {
400: "请求参数格式不正确",
401: "未授权",
403: "禁止访问",
404: "资源不存在",
405: "请求方法不支持",
413: "请求体过大",
415: "不支持的请求格式",
429: "操作过于频繁,请稍后再试",
};
/**
* 统一错误出口
*
* 业务 handler 内部已各自 catch,这里兜住中间件层的异常:
* 非法 JSON、请求体超限、静态资源异常等。所有响应仍走 body.code 约定,
* HTTP 状态保持 200,避免客户端因 413/400 直接拿到非 JSON 文本。
*
* @returns {Function} Koa 中间件
*/
export function createErrorMiddleware() {
return async (ctx, next) => {
try {
await next();
} catch (err) {
// 响应已开始发送时无法再改 body,交给 Koa 默认处理
if (ctx.headerSent) throw err;
const status = Number(err?.status || err?.statusCode) || 500;
if (status >= 400 && status < 500) {
ResponseUtil.error(
ctx,
CLIENT_ERROR_MESSAGES[status] || "请求处理失败",
null,
status
);
return;
}
// 5xx 的详细原因只进日志,不回传堆栈/连接串等内部信息
ResponseUtil.internalError(ctx, err);
}
};
}
class APP {
constructor() {
this.app = new Koa();
@@ -46,6 +91,9 @@ class APP {
this.app.proxy = true;
this.app.proxyIpHeader = "X-Real-IP";
// 统一错误出口必须在最外层:body-parser 的 400/413 也要转成约定 JSON
this.app.use(createErrorMiddleware());
// 线上 nginx 只代理 /health 与 /user;保留 /static 供本机访问,
// 同时提供 /health/static,避免独立 /static 请求落到其他服务的默认响应
this.app.use(mount('/health/static', serve(STATIC_DIR)));
+572
View File
@@ -0,0 +1,572 @@
import mongoose from "mongoose";
import ResponseUtil from "../utils/responseUtil.js";
import { DBModel } from "../models/index.js";
import { genPinyin, genPinyinFL } from "../models/schema/employee.js";
import { HandlerTrainingApplication } from "./training_application.js";
const MOBILE_REGEX = /^1[3-9]\d{9}$/;
const ID_NUMBER_REGEX = /^\d{17}[\dXx]$/;
const NAME_MAX = 20;
const INTRODUCTION_MAX = 200;
const REJECT_REASON_MAX = 200;
const AREA_MAX = 10;
const AREA_ITEM_MAX = 20;
const MAX_PAGE_SIZE = 100;
// 岗位中文名:仅用于冲突提示文案。岗位变更本身由管理员在后台显式操作,
// 入驻审批不改写已有非陪诊师档案(产品口径:拒绝改写,走人工)
const ROLE_LABELS = { nurse: "护士", doctor: "医生", operator: "运营", other: "其他" };
// 入驻申请会同时存资质证书与健康证明两张原图,base64 后体积约为原图 1.33 倍。
// 单张压到 3MB,两张合计仍能稳定落在 Mongo 单文档 16MB 上限内。
const IMAGE_MAX_BYTES = 3 * 1024 * 1024;
const KEYWORD_MAX = 64;
/**
* 陪诊师入驻申请
*
* 与 employee 的关系:本 handler 只写申请单,审核通过时才由 ensureEmployee
* 幂等地创建/激活员工档案。员工建档的字段白名单沿用 HandlerEmployee 的口径,
* 这里不重复维护一份完整字段表,只写审批必须同步的那几项。
*/
class HandlerAttendantApplication {
/**
* 提交回执:给申请人看自己的资料,不含图片(体积大且无回显必要)
* 身份证号属于本人提交的数据,回填表单需要,故保留
*/
static toReceipt(doc) {
if (!doc) return null;
return {
id: doc._id,
applicant: {
name: doc.applicant?.name || "",
mobile: doc.applicant?.mobile || "",
idNumber: doc.applicant?.idNumber || "",
sex: doc.applicant?.sex || "",
serviceAreas: doc.applicant?.serviceAreas || [],
introduction: doc.applicant?.introduction || "",
},
healthExpireDate: HandlerAttendantApplication.formatDate(
doc.materials?.healthCertificate?.expireDate
),
hasQualification: !!doc.materials?.qualification?.data,
hasHealthCertificate: !!doc.materials?.healthCertificate?.data,
status: doc.status || "pending",
rejectReason: doc.review?.rejectReason || "",
reviewedAt: doc.review?.reviewedAt || null,
createtime: doc.meta?.createtime || null,
};
}
static formatDate(value) {
if (!value) return "";
const date = new Date(value);
if (Number.isNaN(date.getTime())) return "";
const month = String(date.getMonth() + 1).padStart(2, "0");
const day = String(date.getDate()).padStart(2, "0");
return `${date.getFullYear()}-${month}-${day}`;
}
static parseDate(value) {
if (!value) return null;
const date = new Date(`${String(value).slice(0, 10)}T00:00:00.000Z`);
return Number.isNaN(date.getTime()) ? null : date;
}
/**
* 入参校验
*
* 图片复用培训报名的 parseImage:那里已经做了 data URL 前缀、base64 合法性、
* 5MB 上限和 JPEG/PNG 文件头校验,不另写一份容易走样的实现
*
* @param {Object} body 请求体
* @param {Object|null} previous 被驳回的上一份申请,未重新上传材料时沿用其图片,
* 避免用户重新提交还要再传一次几 MB 的证件照
*/
static parsePayload(body = {}, previous = null) {
const fallback = previous?.materials || null;
const applicant = body.applicant || {};
const name = String(applicant.name || "").trim();
const mobile = String(applicant.mobile || "").trim();
const idNumber = String(applicant.idNumber || "").trim().toUpperCase();
const sex = String(applicant.sex || "").trim();
const introduction = String(applicant.introduction || "").trim();
const serviceAreas = Array.isArray(applicant.serviceAreas)
? applicant.serviceAreas.map((item) => String(item || "").trim()).filter(Boolean)
: [];
if (!name) return { error: "请填写姓名" };
if (name.length > NAME_MAX) return { error: `姓名不能超过 ${NAME_MAX} 个字` };
if (!MOBILE_REGEX.test(mobile)) return { error: "请填写正确的 11 位手机号" };
if (!ID_NUMBER_REGEX.test(idNumber)) return { error: "请填写 18 位身份证号,末位可为 X" };
if (sex && !["male", "female"].includes(sex)) return { error: "性别取值不正确" };
if (!serviceAreas.length) return { error: "请至少选择一个服务城市" };
if (serviceAreas.length > AREA_MAX) return { error: `服务城市最多 ${AREA_MAX} 个` };
if (serviceAreas.some((item) => item.length > AREA_ITEM_MAX)) {
return { error: `单个服务城市不能超过 ${AREA_ITEM_MAX} 个字` };
}
if (introduction.length > INTRODUCTION_MAX) {
return { error: `个人简介不能超过 ${INTRODUCTION_MAX} 个字` };
}
const qualification = body.materials?.qualification
? HandlerTrainingApplication.parseImage(
body.materials.qualification,
"资质证书照片",
IMAGE_MAX_BYTES
)
: fallback?.qualification?.data
? { value: { data: fallback.qualification.data, mime: fallback.qualification.mime } }
: { error: "请上传资质证书照片" };
if (qualification.error) return qualification;
const healthPhoto = body.materials?.healthCertificate
? HandlerTrainingApplication.parseImage(
body.materials.healthCertificate,
"健康证明照片",
IMAGE_MAX_BYTES
)
: fallback?.healthCertificate?.data
? {
value: {
data: fallback.healthCertificate.data,
mime: fallback.healthCertificate.mime,
},
}
: { error: "请上传健康证明照片" };
if (healthPhoto.error) return healthPhoto;
const expireDate =
HandlerAttendantApplication.parseDate(body.healthExpireDate) ||
fallback?.healthCertificate?.expireDate ||
null;
if (!expireDate) return { error: "请填写健康证明有效期" };
// 过期健康证无法支撑"公示有效期",直接挡在提交环节。
// 到期当天仍算有效(与公示侧 isHealthCertificateValid 同口径):
// parseDate 是 UTC 零点,换算到东八区当天 23:59:59.999 再比较
const endOfDay = Date.UTC(
expireDate.getUTCFullYear(),
expireDate.getUTCMonth(),
expireDate.getUTCDate(),
15, 59, 59, 999
);
if (endOfDay < Date.now()) return { error: "健康证明已过期,请更新后再提交" };
return {
value: {
applicant: { name, mobile, idNumber, sex, serviceAreas, introduction },
materials: {
qualification: qualification.value,
healthCertificate: { ...healthPhoto.value, expireDate },
},
},
};
}
// 点号路径 → 嵌套对象,构造器不认 "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;
}
/**
* 生成工号
*
* employeeNo 是 unique + sparse:sparse 只跳过"字段不存在"的文档,
* 所以工号必须显式生成且不能为空串,否则多条无工号档案会互相撞唯一索引
*/
static generateEmployeeNo() {
const now = new Date();
const stamp = [
now.getFullYear(),
String(now.getMonth() + 1).padStart(2, "0"),
String(now.getDate()).padStart(2, "0"),
].join("");
const rand = String(Math.floor(Math.random() * 10000)).padStart(4, "0");
return `ATT${stamp}${rand}`;
}
/**
* 幂等建档:已有陪诊师档案时激活并同步资料,没有才新建;
* 其他岗位(admin/nurse/doctor/operator/other)档案拒绝改写,
* 岗位变更由管理员在后台显式操作
*
* 单条条件 upsert 原子完成"激活或建"(userId 有 partial unique 索引兜底),
* 消除先 findOne 再 create 之间的并发窗口;插入撞 employeeNo 唯一索引时换号重试。
* 不使用 Mongo 事务:本项目没有副本集事务的使用先例,
* 改为"先抢占申请状态,再调用本方法",失败后管理员重按"通过"即可续跑
*
* 注意:这里绕过了 EmployeeSchema 的 pre("save"),拼音字段必须手动同步
*/
static async ensureEmployee(doc) {
const name = doc.applicant?.name || "";
const patch = {
"profile.name": name,
"profile.sex": doc.applicant?.sex || "",
"profile.phone": doc.applicant?.mobile || "",
"profile.idNumber": doc.applicant?.idNumber || "",
"profile.pinyin": genPinyin(name),
"profile.pinyinFL": genPinyinFL(name),
"attendantInfo.serviceAreas": doc.applicant?.serviceAreas || [],
introduction: doc.applicant?.introduction || "",
};
const expireDate = doc.materials?.healthCertificate?.expireDate;
if (expireDate) patch["work.healthCertificate.expireDate"] = expireDate;
// 非陪诊师岗位档案不允许被入驻审批改写(提交侧已拦,这里再防一手):
// 直接报错而不是让 upsert 走插入分支撞 userId 唯一索引
const existing = await DBModel.Employee.findOne({ userId: doc.userId })
.select("role")
.lean()
.exec();
if (existing && existing.role !== "attendant") {
const err = new Error(
existing.role === "admin"
? "该账号已绑定管理员员工档案,无法按陪诊师开通"
: "该账号已绑定其他岗位的员工档案,请先由管理员确认岗位后再审核"
);
err.code = existing.role === "admin" ? "ADMIN_EMPLOYEE" : "ROLE_CONFLICT";
throw err;
}
// 命中已有档案时只更新 attendant 记录(停用/离职的陪诊师重新激活走这里);
// 其他岗位档案上方已拒绝,并发窗口里刚被建档的极端情形由 E11000 分支兜底
for (let i = 0; i < 5; i++) {
try {
const employee = await DBModel.Employee.findOneAndUpdate(
{ userId: doc.userId, role: "attendant" },
{
$set: {
...patch,
role: "attendant",
status: "active",
userIdSource: "application",
"meta.updatetime": Date.now(),
},
// 只在插入时写入。注意不能写成 $setOnInsert: { meta: {...} }:
// 那是 meta 的父路径,与 $set 里的 meta.updatetime 构成路径冲突,
// MongoDB 会报 "Updating the path 'meta' would create a conflict at 'meta'"
$setOnInsert: {
employeeNo: HandlerAttendantApplication.generateEmployeeNo(),
"meta.createtime": Date.now(),
},
},
{ new: true, upsert: true }
).exec();
return employee;
} catch (err) {
if (err?.code !== 11000) throw err;
// employeeNo 撞号:换号重试。
// userId 撞唯一索引发生在"并发下另一请求刚建档"的窗口:
// attendant 档案下一轮走更新分支自然收敛;非 attendant 档案重试永远不会命中,
// 重查确认后直接报可读错误,避免空转 5 次抛「生成工号失败」
if (err.keyValue && Object.prototype.hasOwnProperty.call(err.keyValue, "userId")) {
const raced = await DBModel.Employee.findOne({ userId: doc.userId })
.select("role")
.lean()
.exec();
if (raced && raced.role !== "attendant") {
const conflict = new Error("该账号已绑定其他岗位的员工档案,请先由管理员确认岗位后再审核");
conflict.code = "ROLE_CONFLICT";
throw conflict;
}
}
}
}
throw new Error("生成工号失败");
}
/**
* 提交申请
*
* 在职陪诊师、已有待审核申请都直接返回结果,不报错——用户重复点击时看到的是结果;
* 管理员与其他岗位档案返回 409,避免审批把岗位改写。
*/
async createApplication(ctx) {
try {
const userId = ctx.state.user?._id;
if (!userId) return ResponseUtil.unauthorized(ctx, "登录已失效");
// 已有员工档案的账号:在职陪诊师无需申请;管理员与其他岗位(护士/医生/运营)
// 一律拒绝——审批会把 role 改写为 attendant,岗位变更应由管理员在后台显式操作
const existingEmployee = await DBModel.Employee.findOne({ userId })
.select("role status")
.lean()
.exec();
if (existingEmployee) {
if (existingEmployee.role === "attendant" && existingEmployee.status === "active") {
return ResponseUtil.error(ctx, "你已是陪诊师,无需重复申请", { isAttendant: true }, 409);
}
if (existingEmployee.role === "admin") {
return ResponseUtil.error(ctx, "当前账号已是管理员,无需申请陪诊师", null, 409);
}
if (existingEmployee.role !== "attendant") {
const label = ROLE_LABELS[existingEmployee.role] || existingEmployee.role;
return ResponseUtil.error(
ctx,
`该账号已绑定「${label}」员工档案,如需转岗陪诊师请联系客服在后台变更`,
null,
409
);
}
// attendant 但已停用/离职/暂停:允许重新申请,审批通过时激活原档案
}
const latest = await DBModel.AttendantApplication.findLatestByUser(userId);
if (latest && latest.status === "pending") {
return ResponseUtil.success(
ctx,
{ application: HandlerAttendantApplication.toReceipt(latest), duplicated: true },
"申请已提交,请等待审核"
);
}
// 弱校验:正常流程用户都从小程序进来,user 记录里会有 wxapp-escort-admin 条目。
// 缺失多半是历史账号或接口直调,只告警不阻断,避免误伤老用户
const user = ctx.state.user;
const enteredAdminApp =
(Array.isArray(user?.apps) && user.apps.some((m) => m?.appId === "wxapp-escort-admin")) ||
Boolean(user?.app?.["wxapp-escort-admin"]);
if (!enteredAdminApp) {
console.warn(
`[attendant-application] 用户 ${userId} 提交入驻申请,但其 user 记录没有 wxapp-escort-admin 应用条目`
);
}
// 驳回后重新提交:允许不重传证件照,沿用上一份的材料
const previous = latest && latest.status === "rejected" ? latest : null;
const result = HandlerAttendantApplication.parsePayload(ctx.request.body, previous);
if (result.error) return ResponseUtil.badRequest(ctx, result.error);
// 换微信号场景:同身份证号已绑在其他员工档案上时不新建第二条,
// 引导客服改绑;档案可能是任意岗位,文案按实际岗位区分,避免误导
const rebound = await DBModel.Employee.findOne({
"profile.idNumber": result.value.applicant.idNumber,
userId: { $ne: userId },
})
.select("role profile.name")
.lean()
.exec();
if (rebound) {
const label = ROLE_LABELS[rebound.role] || rebound.role;
return ResponseUtil.error(
ctx,
rebound.role === "attendant"
? `该身份证号已绑定陪诊师「${rebound.profile?.name || ""}」,如已更换微信请联系客服改绑`
: `该身份证号已绑定「${label}」员工档案,如需转岗陪诊师请联系客服处理`,
{ reboundRequired: true },
409
);
}
try {
const application = await DBModel.AttendantApplication.createApplication({
userId,
...result.value,
});
return ResponseUtil.success(
ctx,
{ application: HandlerAttendantApplication.toReceipt(application) },
"申请已提交"
);
} catch (err) {
// 并发双击:唯一索引兜底,回落到已存在的那条申请
if (err?.code === 11000) {
const current = await DBModel.AttendantApplication.findPendingByUser(userId);
return ResponseUtil.success(
ctx,
{
application: HandlerAttendantApplication.toReceipt(current),
duplicated: true,
},
"申请已提交,请等待审核"
);
}
throw err;
}
} catch (err) {
return ResponseUtil.internalError(ctx, err);
}
}
// 当前账号最新一条申请,供小程序申请页判断展示哪个视图
async getMyApplication(ctx) {
try {
const userId = ctx.state.user?._id;
if (!userId) return ResponseUtil.unauthorized(ctx, "登录已失效");
const application = await DBModel.AttendantApplication.findLatestByUser(userId);
return ResponseUtil.success(
ctx,
{ application: HandlerAttendantApplication.toReceipt(application) },
"查询成功"
);
} catch (err) {
return ResponseUtil.internalError(ctx, err);
}
}
async getApplications(ctx) {
try {
const { status, keyword } = ctx.request.query;
// all = 不限状态(回看历史);缺省仍按 pending,与审核台默认页签一致
if (status && !["all", "pending", "approved", "rejected"].includes(status)) {
return ResponseUtil.badRequest(ctx, "审核状态筛选值不正确");
}
const page = Math.max(parseInt(ctx.request.query.page, 10) || 1, 1);
const pageSize = Math.min(
Math.max(parseInt(ctx.request.query.pageSize, 10) || 20, 1),
MAX_PAGE_SIZE
);
const result = await DBModel.AttendantApplication.findApplicationPage({
page,
pageSize,
status: status && status !== "all" ? status : status === "all" ? "" : "pending",
// 关键词可能以数组形式传入(?keyword=a&keyword=b),统一收敛成字符串
keyword: String(keyword || "").trim().slice(0, KEYWORD_MAX),
});
return ResponseUtil.success(ctx, { ...result, page, pageSize }, "查询成功");
} catch (err) {
return ResponseUtil.internalError(ctx, err);
}
}
// 材料大图单独取:只在管理员点开弹窗时加载,避免列表接口承担图片体积。
// 身份证号一并在此返回(列表刻意排除),审核人需要核对
async getApplicationMaterials(ctx) {
try {
const { id } = ctx.params;
if (!mongoose.Types.ObjectId.isValid(id)) {
return ResponseUtil.badRequest(ctx, "申请ID不合法");
}
const application = await DBModel.AttendantApplication.findById(id)
.select("applicant.name applicant.idNumber materials")
.lean()
.exec();
if (!application) return ResponseUtil.notFound(ctx, "申请不存在");
return ResponseUtil.success(
ctx,
{
applicantName: application.applicant?.name || "",
// 审核人需要核对身份证号:列表刻意不返回,在这个管理员专用接口里给全
applicantIdNumber: application.applicant?.idNumber || "",
qualification: application.materials?.qualification || null,
healthCertificate: application.materials?.healthCertificate || null,
},
"查询成功"
);
} catch (err) {
return ResponseUtil.internalError(ctx, err);
}
}
/**
* 审核
*
* 两步走,不依赖事务:
* 1. 条件更新抢占 pending → approved/rejected,并发审批只有一个成功
* 2. 幂等建档;若第二步失败,管理员重按"通过"时靠 approvedEmployeeId 为空续跑
*/
async reviewApplication(ctx) {
try {
const { id } = ctx.params;
const { action, reason } = ctx.request.body || {};
if (!mongoose.Types.ObjectId.isValid(id)) {
return ResponseUtil.badRequest(ctx, "申请ID不合法");
}
if (!["approve", "reject"].includes(action)) {
return ResponseUtil.badRequest(ctx, "审核动作不正确");
}
const reviewerId = ctx.state.user?._id;
if (action === "reject") {
const rejectReason = String(reason || "").trim();
if (!rejectReason) return ResponseUtil.badRequest(ctx, "请填写驳回原因");
if (rejectReason.length > REJECT_REASON_MAX) {
return ResponseUtil.badRequest(ctx, `驳回原因不能超过 ${REJECT_REASON_MAX} 个字`);
}
const rejected = await DBModel.AttendantApplication.findOneAndUpdate(
{ _id: id, status: "pending" },
{ $set: { status: "rejected", review: { reviewerId, reviewedAt: Date.now(), rejectReason }, "meta.updatetime": Date.now() } },
{ new: true }
).exec();
if (!rejected) {
const exists = await DBModel.AttendantApplication.findById(id).select("status").lean().exec();
if (!exists) return ResponseUtil.notFound(ctx, "申请不存在");
return ResponseUtil.error(ctx, "该申请已处理,请刷新列表", null, 409);
}
return ResponseUtil.success(
ctx,
{ application: HandlerAttendantApplication.toReceipt(rejected) },
"已驳回"
);
}
let doc = await DBModel.AttendantApplication.findOneAndUpdate(
{ _id: id, status: "pending" },
{ $set: { status: "approved", review: { reviewerId, reviewedAt: Date.now() }, "meta.updatetime": Date.now() } },
{ new: true }
).exec();
if (!doc) {
doc = await DBModel.AttendantApplication.findById(id).exec();
if (!doc) return ResponseUtil.notFound(ctx, "申请不存在");
if (doc.status !== "approved") {
return ResponseUtil.error(ctx, "该申请已处理,请刷新列表", null, 409);
}
// 已通过且已建档:重复点击按成功返回,避免管理员误以为是失败
if (doc.approvedEmployeeId) {
return ResponseUtil.success(
ctx,
{ application: HandlerAttendantApplication.toReceipt(doc), employeeId: doc.approvedEmployeeId },
"该申请已通过"
);
}
}
let employee = null;
try {
// 岗位冲突(管理员档案或其他岗位档案)由 ensureEmployee 统一拦截
employee = await HandlerAttendantApplication.ensureEmployee(doc);
} catch (err) {
if (err?.code === "ADMIN_EMPLOYEE" || err?.code === "ROLE_CONFLICT") {
// 抢占步骤已把单据置为 approved,直接返回 409 会让它卡死在
// "已通过但未建档":reject 只认 pending,管理员既无法驳回也无法重审。
// 条件回滚为 pending,转岗处理完后管理员可重新审核或驳回;
// 并发下另一管理员若已再次抢占,条件不匹配,回滚无副作用
await DBModel.AttendantApplication.updateOne(
{ _id: doc._id, status: "approved", approvedEmployeeId: null },
{ $set: { status: "pending", review: {}, "meta.updatetime": Date.now() } }
).exec();
return ResponseUtil.error(ctx, err.message, null, 409);
}
throw err;
}
await DBModel.AttendantApplication.updateOne(
{ _id: doc._id },
{ $set: { approvedEmployeeId: employee._id, "meta.updatetime": Date.now() } }
).exec();
return ResponseUtil.success(
ctx,
{ application: HandlerAttendantApplication.toReceipt(doc), employeeId: employee._id },
"审核通过,已开通陪诊师权限"
);
} catch (err) {
return ResponseUtil.internalError(ctx, err);
}
}
}
export { HandlerAttendantApplication };
+37 -3
View File
@@ -301,6 +301,19 @@ class HandlerEmployee {
}
}
// userId 绑定查重:一个账号只能绑一条员工档案(与 employee.userId 的
// partial unique 索引同一规则,应用层先挡可给出可读提示而非 500)
static async assertUserIdAvailable(userId, excludeId = null) {
if (!userId || typeof userId !== "string" || !mongoose.Types.ObjectId.isValid(userId)) {
return null;
}
const filter = { userId: new mongoose.Types.ObjectId(userId) };
if (excludeId) filter._id = { $ne: new mongoose.Types.ObjectId(excludeId) };
const existing = await DBModel.Employee.findOne(filter).select("_id profile.name").lean().exec();
if (!existing) return null;
return `该账号已绑定员工「${existing.profile?.name || existing._id}」,一个账号只能关联一条员工档案`;
}
async createEmployee(ctx) {
try {
const flat = HandlerEmployee.pickFields(ctx.request.body);
@@ -310,17 +323,23 @@ class HandlerEmployee {
return ResponseUtil.badRequest(ctx, invalid);
}
const conflict = await HandlerEmployee.assertUserIdAvailable(flat.userId);
if (conflict) {
return ResponseUtil.error(ctx, conflict, null, 409);
}
const data = {};
for (const [path, value] of Object.entries(flat)) {
HandlerEmployee.setPath(data, path, value);
}
if (data.userId) data.userIdSource = "manual";
const employee = await DBModel.Employee.createEmployee(data);
return ResponseUtil.success(ctx, { employee }, "创建成功");
} catch (err) {
// employeeNo 唯一索引冲突:给出可读提示,而不是「服务器繁忙」
// employeeNo / userId 唯一索引冲突:给出可读提示,而不是「服务器繁忙」
if (err?.code === 11000) {
return ResponseUtil.badRequest(ctx, "工号已存在");
return ResponseUtil.badRequest(ctx, "工号已存在,或该账号已绑定其他员工档案");
}
return ResponseUtil.internalError(ctx, err);
}
@@ -343,6 +362,21 @@ class HandlerEmployee {
return ResponseUtil.badRequest(ctx, invalid);
}
const conflict = await HandlerEmployee.assertUserIdAvailable(flat.userId, id);
if (conflict) {
return ResponseUtil.error(ctx, conflict, null, 409);
}
// 换了绑定账号 = 人工改绑,来源改写为 manual(可与入驻自动绑定区分)
if (flat.userId) {
flat.userIdSource = "manual";
} else if (flat.userId === "") {
// 解绑:userId 是 ObjectId 路径,写空串会触发 CastError,
// 必须转成 null 才能真正解绑(partial unique 索引不约束 null)
flat.userId = null;
flat.userIdSource = "";
}
const employee = await DBModel.Employee.updateEmployee(id, flat);
if (!employee) {
return ResponseUtil.notFound(ctx, "员工不存在");
@@ -350,7 +384,7 @@ class HandlerEmployee {
return ResponseUtil.success(ctx, { employee }, "更新成功");
} catch (err) {
if (err?.code === 11000) {
return ResponseUtil.badRequest(ctx, "工号已存在");
return ResponseUtil.badRequest(ctx, "工号已存在,或该账号已绑定其他员工档案");
}
return ResponseUtil.internalError(ctx, err);
}
+87 -9
View File
@@ -37,6 +37,15 @@ class HandlerEscortRecord {
in_progress: [...HandlerEscortRecord.OWNER_NOTE_FIELDS],
};
// 陪诊员只能写服务备注与就诊小结:改期、换医院、改患者备注、改支付渠道都属于
// 订单主人或平台管理员的权限(与 Agent 侧陪诊员工具口径一致)
static ATTENDANT_NOTE_FIELDS = ["notes.escortNote", "notes.medicalSummary"];
static ATTENDANT_EDITABLE_STATUSES = ["confirmed", "in_progress", "completed"];
// 管理端可能以嵌套对象提交这些子文档;整块 $set 会抹掉未提交字段,
// 与点号路径混用还会触发 Mongo 路径冲突,写入前统一摊平
static NESTED_OBJECT_FIELDS = ["patient", "hospital", "payment", "notes", "inquiry", "shippingAddress"];
// 用户端只能发起取消,服务完成由平台确认,避免用户端重复写入终态。
// 取消与 status 解耦:cancelStatus 为 requested 表示待确认,cancelled 表示已取消。
// 「未确认且未收款」取消即物理删除;其余先置 requested,等陪诊师/管理员确认。
@@ -155,6 +164,37 @@ class HandlerEscortRecord {
return picked;
}
/**
* 把嵌套子文档摊平成点号路径,并与现值合并。
*
* 两个问题一起解决:
* 1. 整块 $set payment 会抹掉未提交的 status / paymentRecordId / refundNo;
* 2. $set 同时出现 payment 与 payment.payChannel 会触发 Mongo 路径冲突。
*
* @param {Object} payload 待写入字段
* @param {Object} existing 数据库中的当前订单
* @returns {Object}
*/
static flattenNestedFields(payload, existing) {
for (const field of HandlerEscortRecord.NESTED_OBJECT_FIELDS) {
const incoming = payload[field];
if (!incoming || typeof incoming !== "object" || Array.isArray(incoming)) continue;
const current = existing?.[field];
const merged = {
...(current && typeof current === "object" ? current : {}),
...incoming,
};
for (const [key, value] of Object.entries(merged)) {
const path = `${field}.${key}`;
// 请求里显式提交的点号路径优先,不被嵌套对象覆盖
if (payload[path] === undefined) payload[path] = value;
}
delete payload[field];
}
return payload;
}
// 解析分页参数并夹紧上限,防止超大 pageSize 拖库
static parsePaging(query = {}) {
const page = Math.max(1, parseInt(query.page) || 1);
@@ -343,7 +383,8 @@ class HandlerEscortRecord {
return ResponseUtil.badRequest(ctx, "缺少记录ID");
}
const record = await DBModel.EscortRecord.findById(id);
// 软删除的订单按不存在处理,与列表口径保持一致
const record = await DBModel.EscortRecord.findRecordById(id);
if (!record) {
return ResponseUtil.error(ctx, "陪诊记录不存在", null, 404);
}
@@ -504,28 +545,56 @@ class HandlerEscortRecord {
}
const isAdmin = HandlerEscortRecord.isAdmin(ctx.state.user);
const isOwner = String(existing.userId || "") === String(ctx.state.user?._id || "");
// 兼容旧数据:取消曾存放在 status 中
const cancelStatus = existing.status === "cancelled"
? "cancelled"
: (existing.cancelStatus || "none");
// 非管理员的可改字段随订单状态收敛:终态无可改字段,进行中只剩就诊人备注;
// 已申请取消或已取消的订单一律冻结,等待平台处理
const allowFields = isAdmin
? HandlerEscortRecord.RECORD_FIELDS
: cancelStatus !== "none"
// 可改字段按角色收敛:
// - 管理员:全字段(状态仍需过状态机)
// - 订单主人:按订单状态收敛,终态/取消中一律冻结
// - 陪诊员(canAccess 已保证非管理员非主人时只能是该单陪诊员):仅服务备注与就诊小结
let allowFields;
if (isAdmin) {
allowFields = HandlerEscortRecord.RECORD_FIELDS;
} else if (isOwner) {
allowFields = cancelStatus !== "none"
? []
: HandlerEscortRecord.ownerEditableFields(existing.status);
} else {
allowFields = cancelStatus === "none"
&& HandlerEscortRecord.ATTENDANT_EDITABLE_STATUSES.includes(existing.status)
? HandlerEscortRecord.ATTENDANT_NOTE_FIELDS
: [];
}
if (allowFields.length === 0) {
return ResponseUtil.forbidden(ctx, "已结束的订单不可修改");
return ResponseUtil.forbidden(
ctx,
cancelStatus !== "none" ? "订单取消中或已取消,不可修改" : "该订单当前状态不支持修改"
);
}
// 非管理员只能改就诊信息类字段,费用/状态/归属/陪诊员分配不可自助修改
// 非管理员只能改就诊信息类字段,费用/状态/归属/陪诊员分配不可自助修改;
// 陪诊员的 allowFields 已收敛为备注字段
const payload = HandlerEscortRecord.pickFields(update, allowFields, !isAdmin);
if (Object.keys(payload).length === 0) {
// 例如进行中订单提交医院/排期:字段被状态规则过滤,明确告知而不是静默成功
return ResponseUtil.badRequest(ctx, "该订单当前状态不支持修改这些信息");
}
// 状态迁移必须走状态机:通用更新接口此前可直接把 completed 改回 in_progress
if (payload.status !== undefined && payload.status !== existing.status) {
if (cancelStatus !== "none") {
return ResponseUtil.badRequest(ctx, "订单取消中或已取消,不能修改服务状态");
}
if (!canTransition(existing.status, payload.status)) {
return ResponseUtil.badRequest(ctx, "当前订单状态不允许此操作");
}
}
// 嵌套子文档摊平为点号路径,避免整块覆盖与路径冲突
HandlerEscortRecord.flattenNestedFields(payload, existing);
// 已收款订单一律锁定支付状态与实收金额:否则编辑退款中的订单会把它改回未支付,
// 用户可再次支付造成重复扣款;金额改动也会与 payment_record 对不上
const currentPayStatus = existing.payment?.status || "unpaid";
@@ -626,6 +695,10 @@ class HandlerEscortRecord {
if (!profile || !sameOwner(profile.userId, existing.userId)) {
return ResponseUtil.badRequest(ctx, "就诊人档案不存在");
}
// 快照整体覆盖前清掉摊平后的 patient.*,避免与 patient 对象路径冲突
for (const key of Object.keys(payload)) {
if (key === "patient" || key.startsWith("patient.")) delete payload[key];
}
payload.patient = HandlerEscortRecord.buildPatientSnapshot(profile);
}
const service = services.find((item) => item.id === existing.escort?.serviceId);
@@ -693,6 +766,11 @@ class HandlerEscortRecord {
const isUserApp = requestAppId === "wxapp-escort";
const role = isUserApp ? null : await resolveEscortAdminRole(user);
const isOwner = String(existing.userId) === String(user?._id);
const isAssignedAttendant = role === "attendant"
&& String(existing.attendant?.id || "") === String(user?._id || "");
// 陪诊员身份只赋予其名下订单的管理权。订单主人即使同时是在职陪诊员,
// 对未分配给自己的订单也只能走用户取消流程,不能自行确认或完成服务。
const canManageOrder = role === "admin" || isAssignedAttendant;
const paymentStatus = existing.payment?.status || "unpaid";
const cancelReason = String(reason || "").trim().slice(0, 200);
let effectivePaymentStatus = paymentStatus;
@@ -707,7 +785,7 @@ class HandlerEscortRecord {
return ResponseUtil.badRequest(ctx, "订单已取消,不能再次操作");
}
if (role !== "admin" && role !== "attendant") {
if (!canManageOrder) {
// 用户端只能取消:未确认订单直接取消(未收款删除、已收款退款);已确认订单提交取消申请
if (status !== "cancelled" || !isOwner) {
return ResponseUtil.forbidden(ctx, "不支持的状态变更");
+30 -9
View File
@@ -66,18 +66,36 @@ class HandlerHealthProfile {
/**
* 按白名单挑选字段(支持 "profile.name" 这类点号路径)
*
* flatten=true 时把嵌套对象摊平成点号路径,供更新接口使用:
* $set 同时出现 profile 与 profile.pinyin 会触发 Mongo 路径冲突,
* 而整块覆盖 profile 又会绕开 pre("save") 导致拼音字段丢失。
*
* @param {Object} body 请求体
* @param {Object} [options]
* @param {boolean} [options.flatten] 是否摊平嵌套对象
* @returns {Object}
*/
static pickFields(body) {
static pickFields(body, { flatten = false } = {}) {
const picked = {};
for (const key of Object.keys(body || {})) {
const allowed = HandlerHealthProfile.PROFILE_FIELDS.some(
(f) => key === f || key.startsWith(f + ".")
);
if (allowed) {
picked[key] = body[key];
const allowed = (path) => HandlerHealthProfile.PROFILE_FIELDS.some(
(f) => path === f || path.startsWith(f + ".")
);
const walk = (value, path) => {
if (!allowed(path)) return;
const isPlainObject = value !== null && typeof value === "object"
&& !Array.isArray(value) && !(value instanceof Date);
if (flatten && isPlainObject) {
for (const [key, child] of Object.entries(value)) {
walk(child, `${path}.${key}`);
}
return;
}
picked[path] = value;
};
for (const [key, value] of Object.entries(body || {})) {
walk(value, key);
}
return picked;
}
@@ -236,7 +254,7 @@ class HandlerHealthProfile {
return ResponseUtil.notFound(ctx, "健康档案不存在");
}
const update = HandlerHealthProfile.pickFields(ctx.request.body);
const update = HandlerHealthProfile.pickFields(ctx.request.body, { flatten: true });
delete update.userId; // 不允许通过请求转移档案归属
const invalid = HandlerHealthProfile.validateProfileInput(update);
@@ -319,7 +337,10 @@ class HandlerHealthProfile {
return ResponseUtil.badRequest(ctx, "缺少档案ID");
}
const updatedProfile = await DBModel.HealthProfile.updateProfileById(id, HandlerHealthProfile.pickFields(update));
const updatedProfile = await DBModel.HealthProfile.updateProfileById(
id,
HandlerHealthProfile.pickFields(update, { flatten: true })
);
if (!updatedProfile) {
return ResponseUtil.notFound(ctx, "健康档案不存在");
}
+112 -16
View File
@@ -39,6 +39,76 @@ function toDate(value) {
return Number.isNaN(date.getTime()) ? null : date;
}
// 支付页轮询会高频触发查单:短 TTL 缓存 + 同号合并,避免把前端轮询放大成微信侧流量。
// 只用于 queryPayment,后台巡检/关单仍直接查微信,保证收敛判断拿到最新状态
const ORDER_QUERY_TTL = 3000;
const ORDER_QUERY_CACHE_MAX = 1000;
/**
* 创建查单缓存
*
* - TTL 内重复查询直接复用结果;
* - 同一 outTradeNo 的并发请求共享同一次上游调用;
* - 查询失败不缓存,下一轮仍会重试。
*
* @param {Object} [options]
* @param {number} [options.ttl] 缓存毫秒数
* @param {number} [options.maxSize] 最大缓存条数
* @param {Function} [options.query] 实际查单函数
* @param {Function} [options.now] 时钟(测试注入)
* @returns {Function} (outTradeNo, { force }?) => Promise<Object>
*/
export function createOrderQueryCache({
ttl = ORDER_QUERY_TTL,
maxSize = ORDER_QUERY_CACHE_MAX,
query = (outTradeNo) => wxpay.queryOrder(outTradeNo),
now = nowMs,
} = {}) {
const cache = new Map();
const inFlight = new Map();
const prune = () => {
const time = now();
for (const [key, entry] of cache) {
if (entry.expiresAt <= time) cache.delete(key);
}
while (cache.size > maxSize) {
cache.delete(cache.keys().next().value);
}
};
return async function queryOrderCached(outTradeNo, { force = false } = {}) {
if (!outTradeNo) return query(outTradeNo);
if (!force) {
const hit = cache.get(outTradeNo);
if (hit && hit.expiresAt > now()) return hit.trade;
}
const running = inFlight.get(outTradeNo);
if (running) return running;
const task = Promise.resolve()
.then(() => query(outTradeNo))
.then((trade) => {
cache.set(outTradeNo, { trade, expiresAt: now() + ttl });
prune();
return trade;
})
.finally(() => {
inFlight.delete(outTradeNo);
});
inFlight.set(outTradeNo, task);
return task;
};
}
const queryOrderForPolling = createOrderQueryCache();
// 微信侧已明确终结的交易状态:可以直接把本地流水收敛为 closed
const CLOSED_TRADE_STATES = ["CLOSED", "PAYERROR", "REFUND", "REVOKED"];
function replySuccess(ctx) {
// 官方约定:验签通过应答 200/204,无需返回应答报文
ctx.status = 200;
@@ -198,8 +268,11 @@ class HandlerPayment {
const transactionId = transaction.transactionId || paymentRecord.transactionId;
if (transactionId) setFields.transactionId = transactionId;
// closed 也允许回写:关单与支付成功存在竞态(关单瞬间用户完成支付),
// 流水可能已被置为 closed,但微信侧确实是 SUCCESS。
// 不允许恢复就会丢 transactionId,退款时找不到 pay_success 流水只能人工核对
const updated = await DBModel.PaymentRecord.findOneAndUpdate(
{ _id: paymentRecord._id, status: { $in: ACTIVE_PAYMENT_STATUS } },
{ _id: paymentRecord._id, status: { $in: [...ACTIVE_PAYMENT_STATUS, "closed"] } },
{ $set: setFields },
{ new: true }
);
@@ -316,12 +389,11 @@ class HandlerPayment {
const refundId = result.refund_id || refundRecord.refundId;
if (refundId) setFields.refundId = refundId;
await DBModel.RefundRecord.updateOne(
{ _id: refundRecord._id },
{ $set: setFields }
);
if (status === "success") {
await DBModel.RefundRecord.updateOne(
{ _id: refundRecord._id },
{ $set: setFields }
);
const recordSet = { "payment.status": "refunded", "meta.updatetime": nowMs() };
if (refundId) {
recordSet["payment.refundNo"] = refundId;
@@ -336,12 +408,21 @@ class HandlerPayment {
{ $set: recordSet }
);
} else {
// 创建/查询响应可能晚于成功回调返回。非成功结果只能在退款尚未成功时落库,
// 否则迟到的 PROCESSING 会把 success/refunded 回退成 processing/refunding。
const updated = await DBModel.RefundRecord.updateOne(
{ _id: refundRecord._id, status: { $ne: "success" } },
{ $set: setFields }
);
const matched = updated?.matchedCount ?? updated?.n;
if (matched === 0) return "success";
await DBModel.PaymentRecord.updateOne(
{ _id: refundRecord.paymentId },
{ _id: refundRecord.paymentId, status: { $ne: "refunded" } },
{ $set: { status: "refunding", "meta.updatetime": nowMs() } }
);
await DBModel.EscortRecord.updateOne(
{ _id: refundRecord.recordId },
{ _id: refundRecord.recordId, "payment.status": { $ne: "refunded" } },
{ $set: { "payment.status": "refunding", "meta.updatetime": nowMs() } }
);
}
@@ -569,13 +650,15 @@ class HandlerPayment {
}).sort({ createdAt: -1 });
}
// 已有在途流水但金额与当前订单不一致(如被绕过改价):先关单再换新号
// 已有在途流水但金额与当前订单不一致(如被绕过改价):先关单再换新号。
// 关单失败时旧 prepay 可能仍可支付,必须停止本次发起,不能同时放出两张有效订单。
if (payment && Number(payment.totalFee) !== totalFeeFen) {
try {
await wxpay.closeOrder(payment.outTradeNo);
await HandlerPayment.setPaymentStatus(payment._id, "closed", { closedAt: new Date() });
} catch (err) {
await HandlerPayment.markPaymentError(payment._id, err, "close");
return ResponseUtil.error(ctx, "原支付订单正在确认关闭结果,请稍后重试", null, 409);
}
payment = null;
}
@@ -704,7 +787,8 @@ class HandlerPayment {
if (payment && ACTIVE_PAYMENT_STATUS.includes(payment.status) && wxpay.isConfigured()) {
try {
const trade = await wxpay.queryOrder(payment.outTradeNo);
// 轮询复用短 TTL 查单结果,避免前端每次刷新都打一次微信
const trade = await queryOrderForPolling(payment.outTradeNo);
tradeState = trade.trade_state || null;
if (trade.trade_state === "SUCCESS") {
HandlerPayment.verifyTrade(trade, payment);
@@ -723,11 +807,17 @@ class HandlerPayment {
}
} else {
const expireAt = toDate(payment.timeExpireAt);
if (payment.status === "created" && trade.trade_state === "NOTPAY"
if (CLOSED_TRADE_STATES.includes(trade.trade_state)) {
await HandlerPayment.setPaymentStatus(payment._id, "closed", { closedAt: new Date() });
} else if (payment.status === "created" && trade.trade_state === "NOTPAY"
&& expireAt && nowMs() > expireAt.getTime()) {
await HandlerPayment.closeExpiredPayment(payment);
} else if (payment.status === "closed_unconfirmed") {
await HandlerPayment.setPaymentStatus(payment._id, "closed", { closedAt: new Date() });
} else if (payment.status === "closed_unconfirmed"
&& trade.trade_state === "NOTPAY"
&& expireAt && nowMs() > expireAt.getTime()) {
// 关单结果不确定时不能仅凭 NOTPAY 就落 closed:微信侧旧单在过期前仍可能支付。
// 已过期则补一次关单,失败保持 closed_unconfirmed 交给巡检继续收敛
await HandlerPayment.closeExpiredPayment(payment);
}
}
} catch (err) {
@@ -1067,13 +1157,19 @@ async function sweepPayment(payment) {
return;
}
if (payment.status === "closed_unconfirmed") {
// 微信侧已明确终结:无需再关单,直接收敛
if (CLOSED_TRADE_STATES.includes(state)) {
await HandlerPayment.setPaymentStatus(payment._id, "closed", { closedAt: new Date() });
return;
}
if (["CLOSED", "PAYERROR", "REFUND", "REVOKED"].includes(state)) {
await HandlerPayment.setPaymentStatus(payment._id, "closed", { closedAt: new Date() });
// 关单结果不确定时不能仅凭 NOTPAY 就落 closed:微信侧旧单在过期前仍可能支付。
// 未过期保持 closed_unconfirmed 交给下一轮继续收敛;已过期才补一次关单
if (payment.status === "closed_unconfirmed") {
if (state === "NOTPAY" && payment.timeExpireAt
&& nowMs() > new Date(payment.timeExpireAt).getTime()) {
await HandlerPayment.closeExpiredPayment(payment);
}
return;
}
+3 -3
View File
@@ -40,15 +40,15 @@ class HandlerTrainingApplication {
// 只接受 jpeg/png 的 data URL;同时检查文件签名和原始大小,
// 防止把任意 base64 文本当作报名材料写入数据库
static parseImage(input, label) {
static parseImage(input, label, maxBytes = MAX_IMAGE_BYTES) {
const raw = String(input || "").trim();
const match = raw.match(/^data:(image\/(?:jpeg|png));base64,([A-Za-z0-9+/]+={0,2})$/);
if (!match) return { error: `请上传${label}(JPG/PNG)` };
const mime = match[1];
const buffer = Buffer.from(match[2], "base64");
if (!buffer.length || buffer.length > MAX_IMAGE_BYTES) {
return { error: `${label}不能超过 5MB` };
if (!buffer.length || buffer.length > maxBytes) {
return { error: `${label}不能超过 ${Math.round(maxBytes / 1024 / 1024)}MB` };
}
const isJpeg = buffer.length > 2 && buffer[0] === 0xff && buffer[1] === 0xd8;
+52 -10
View File
@@ -10,16 +10,57 @@ import ResponseUtil from "../utils/responseUtil.js";
* 说明:单进程内存计数,多实例部署时每个实例各自计数(当前为单机部署,
* 若后续横向扩容需换成 Redis 之类的共享计数)。
*/
const store = new Map();
const cleanupInterval = 60_000;
const cleanupTimer = setInterval(() => {
const now = Date.now();
for (const [key, record] of store.entries()) {
if (now - record.resetAt > record.windowMs) store.delete(key);
// 所有计数桶统一登记,由一个定时器清理,避免为每个 limiter 各起一个 timer
const stores = new Set();
function registerStore(buckets) {
stores.add(buckets);
return buckets;
}
/**
* 清理所有过期计数(社区版只做内存回收,不影响限流语义:
* 访问时本身也会按窗口重置)
* @param {number} [now] 当前时间(测试可注入)
* @returns {number} 清理的条目数
*/
function sweepRateLimitStores(now = Date.now()) {
let removed = 0;
for (const buckets of stores) {
for (const [key, record] of buckets) {
if (now - record.resetAt > record.windowMs) {
buckets.delete(key);
removed += 1;
}
}
}
}, 60_000);
return removed;
}
const cleanupTimer = setInterval(() => sweepRateLimitStores(), cleanupInterval);
cleanupTimer.unref();
// 路径里可能带订单 ID;路由没匹配到模式时(理论上不该发生)兜底归一
const OBJECT_ID_SEGMENT = /\/[0-9a-fA-F]{24}(?=\/|$)/g;
function normalizeDynamicPath(path) {
return String(path || "").replace(OBJECT_ID_SEGMENT, "/:id");
}
/**
* 限流分桶键
*
* 用路由模式(如 /health/escort-record/:id)而不是真实 path:
* 否则同一用户在不同订单上各有一份额度,换个 ID 就能绕过限流。
*/
function resolveBucketPath(ctx) {
return ctx.routerPath || ctx._matchedRoute || normalizeDynamicPath(ctx.path);
}
const store = registerStore(new Map());
/**
* 创建限流中间件
* @param {number} max 窗口内最大请求数
@@ -28,7 +69,7 @@ cleanupTimer.unref();
function rateLimit(max, windowMs = 60_000) {
return async (ctx, next) => {
const identity = ctx.state.user?._id ? `u:${ctx.state.user._id}` : `ip:${ctx.ip}`;
const key = `${identity}:${ctx.method}:${ctx.path}`;
const key = `${identity}:${ctx.method}:${resolveBucketPath(ctx)}`;
const now = Date.now();
let record = store.get(key);
@@ -58,13 +99,14 @@ function rateLimit(max, windowMs = 60_000) {
* @returns {(identity: string) => {allowed: boolean, retryAfter: number}}
*/
function createUserLimiter(max, windowMs = 60_000) {
const buckets = new Map();
// windowMs 写进记录,供统一清理逻辑判断过期
const buckets = registerStore(new Map());
return (identity) => {
const now = Date.now();
let record = buckets.get(identity);
if (!record || now - record.resetAt > windowMs) {
record = { count: 0, resetAt: now };
record = { count: 0, resetAt: now, windowMs };
buckets.set(identity, record);
}
record.count++;
@@ -78,4 +120,4 @@ function createUserLimiter(max, windowMs = 60_000) {
};
}
export { rateLimit, createUserLimiter };
export { rateLimit, createUserLimiter, sweepRateLimitStores, normalizeDynamicPath };
+14 -1
View File
@@ -8,6 +8,7 @@ import { HospitalSchema } from "./schema/hospital.js"
import { EmployeeSchema } from "./schema/employee.js"
import { EmployeeReviewSchema } from "./schema/employee_review.js"
import { TrainingApplicationSchema } from "./schema/training_application.js"
import { AttendantApplicationSchema } from "./schema/attendant_application.js"
import { PaymentRecordSchema } from "./schema/payment_record.js"
import { RefundRecordSchema } from "./schema/refund_record.js"
import config from '../config.js';
@@ -16,7 +17,6 @@ import logger from '../utils/logger.js';
class MongoDBSchema {
constructor() {
this.dbConnection = null;
this.User = null;
this.EscortRecord = null;
this.Organization = null;
this.Hospital = null;
@@ -24,6 +24,7 @@ class MongoDBSchema {
this.HealthProfile = null;
this.EmployeeReview = null;
this.TrainingApplication = null;
this.AttendantApplication = null;
this.PaymentRecord = null;
this.RefundRecord = null;
}
@@ -58,8 +59,20 @@ class MongoDBSchema {
this.Employee = this.dbConnection.model('employee', EmployeeSchema)
this.EmployeeReview = this.dbConnection.model('employee_review', EmployeeReviewSchema)
this.TrainingApplication = this.dbConnection.model('training_application', TrainingApplicationSchema)
this.AttendantApplication = this.dbConnection.model('attendant_application', AttendantApplicationSchema)
this.PaymentRecord = this.dbConnection.model('payment_record', PaymentRecordSchema)
this.RefundRecord = this.dbConnection.model('refund_record', RefundRecordSchema)
// 索引创建失败(如唯一索引遇到存量重复)时 mongoose 会 emit('error'),
// 而 EventEmitter 对没有监听器的 'error' 事件会直接抛未捕获异常,
// 导致整个服务启动即崩。这里统一监听并记日志,把问题留给索引脚本处理
for (const model of Object.values(this)) {
if (model && typeof model.on === "function" && model.schema) {
model.on("error", (err) => {
logger.error(`[mongo] ${model.modelName} 索引/初始化失败: ${err?.message || err}`);
});
}
}
}
}
+166
View File
@@ -0,0 +1,166 @@
"use strict";
import mongoose from "mongoose";
/**
* AttendantApplication Schema
* 陪诊师入驻申请
*
* 与 employee 分离存放:employee 只保存审核通过的真实员工,
* 申请单独立成表,驳回原因与历史提交都能留存,也不会让"申请中"的人
* 混进员工列表和陪诊师公示。
*
* 材料图片以 data URL 入参,服务端限制单张 3MB(见 handler 的 IMAGE_MAX_BYTES);
* 驳回后重新提交且未重传照片时,会复制上一份的 data URL 到新申请文档,
* 保留审计痕迹的代价是每次重提交图片存储翻倍,需由留存/清理策略覆盖。
* 审核通过后只把结构化字段(健康证到期日等)同步到 employee,
* 原图留在本表做审计,不复制进员工表。
*/
const ImageSchema = mongoose.Schema(
{
data: { type: String, required: true, comment: "data URL" },
mime: { type: String, enum: ["image/jpeg", "image/png"], required: true, comment: "图片类型" },
},
{ _id: false }
);
const HealthCertificateSchema = mongoose.Schema(
{
data: { type: String, required: true, comment: "健康证照片 data URL" },
mime: { type: String, enum: ["image/jpeg", "image/png"], required: true, comment: "图片类型" },
expireDate: { type: Date, required: true, comment: "健康证有效期至" },
},
{ _id: false }
);
const AttendantApplicationSchema = mongoose.Schema(
{
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: "user",
required: true,
comment: "申请用户ID",
},
applicant: {
name: { type: String, required: true, trim: true, maxlength: 20, comment: "姓名" },
mobile: {
type: String,
required: true,
trim: true,
match: /^1[3-9]\d{9}$/,
comment: "手机号",
},
idNumber: {
type: String,
required: true,
trim: true,
uppercase: true,
match: /^\d{17}[\dX]$/,
comment: "身份证号",
},
sex: { type: String, enum: ["male", "female", ""], default: "", comment: "性别" },
serviceAreas: { type: [String], default: [], comment: "服务区域/城市列表" },
introduction: { type: String, default: "", maxlength: 200, comment: "个人简介" },
},
materials: {
qualification: { type: ImageSchema, required: true, comment: "资质证书照片" },
healthCertificate: { type: HealthCertificateSchema, required: true, comment: "健康证明" },
},
/**
* pending 待审核 / approved 已通过 / rejected 已驳回
* v1 不提供用户主动撤回,避免出现没有入口的空状态
*/
status: {
type: String,
enum: ["pending", "approved", "rejected"],
default: "pending",
comment: "审核状态",
},
review: {
reviewerId: { type: mongoose.Schema.Types.ObjectId, comment: "审核人用户ID" },
reviewedAt: { type: Number, comment: "审核时间" },
rejectReason: { type: String, default: "", maxlength: 200, comment: "驳回原因" },
},
// 通过后回填,用于第二步失败时的续跑判断(先改状态,再幂等建档)
approvedEmployeeId: {
type: mongoose.Schema.Types.ObjectId,
default: null,
comment: "审核通过后生成的员工ID",
},
meta: {
createtime: { type: Number, default: () => Date.now(), comment: "创建时间" },
updatetime: { type: Number, default: () => Date.now(), comment: "更新时间" },
},
},
{
minimize: false,
strict: true,
collection: "attendant_application",
timestamps: false,
}
);
AttendantApplicationSchema.statics.createApplication = async function (data) {
data.meta = { createtime: Date.now(), updatetime: Date.now() };
const doc = new this(data);
return await doc.save();
};
AttendantApplicationSchema.statics.findLatestByUser = async function (userId) {
return await this.findOne({ userId }).sort({ "meta.createtime": -1 }).exec();
};
AttendantApplicationSchema.statics.findPendingByUser = async function (userId) {
return await this.findOne({ userId, status: "pending" }).exec();
};
/**
* 管理端审核列表
* 默认不返回 materials:一遍列表带几十张 data URL,响应体会直接失控
*/
AttendantApplicationSchema.statics.findApplicationPage = async function (options = {}) {
const { page = 1, pageSize = 20, status = "pending", keyword } = options;
const filter = {};
if (status) filter.status = status;
if (keyword && String(keyword).trim()) {
const safe = String(keyword).trim().replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const reg = new RegExp(safe, "i");
filter.$or = [{ "applicant.name": reg }, { "applicant.mobile": reg }];
}
const skip = (page - 1) * pageSize;
const [applications, total] = await Promise.all([
this.find(filter)
.select("-materials -applicant.idNumber")
.sort({ "meta.createtime": -1 })
.skip(skip)
.limit(pageSize)
.lean()
.exec(),
this.countDocuments(filter).exec(),
]);
return { applications, total };
};
/**
* 同一用户同时只允许一条待审核申请
*
* 只靠 handler 先查后插挡不住并发双击,这里用部分唯一索引兜底;
* 已通过/已驳回的历史申请不受约束,用户可以重新提交。
*/
AttendantApplicationSchema.index(
{ userId: 1 },
{ unique: true, partialFilterExpression: { status: "pending" } }
);
// 查"我的最新申请"与审核列表各一条复合索引,不再单独给 userId / status 建单字段索引
AttendantApplicationSchema.index({ userId: 1, "meta.createtime": -1 });
AttendantApplicationSchema.index({ status: 1, "meta.createtime": -1 });
export { AttendantApplicationSchema };
+24 -4
View File
@@ -25,16 +25,26 @@ const TrainingSchema = mongoose.Schema(
const EmployeeSchema = mongoose.Schema(
{
// 工号(业务雇佣标识)
employeeNo: { type: String, default: "", unique: true, sparse: true, comment: "工号" },
// 不设默认值:唯一索引是 sparse 的,只跳过"字段缺失"的文档;
// 若默认写成空串,多条无工号的档案会共享 "" 而互相撞唯一索引
employeeNo: { type: String, unique: true, sparse: true, comment: "工号" },
// 登录账号(关联用户体系)
// 一个 user 只允许绑定一条员工档案(partial unique 索引兜底,见文件末尾)。
// userIdSource 记录绑定来源:manual=管理员在后台手动绑定,application=入驻审批自动绑定
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: "user",
index: true,
comment: "关联用户ID",
},
userIdSource: {
type: String,
enum: ["manual", "application", ""],
default: "",
comment: "userId 绑定来源:后台手动 / 入驻审批",
},
// 所属机构
orgId: {
type: mongoose.Schema.Types.ObjectId,
@@ -249,10 +259,20 @@ EmployeeSchema.statics.findOnlineAttendants = async function (options = {}) {
// ==================== 索引定义 ====================
EmployeeSchema.index({ "profile.name": 1 });
// 注意:employeeNo(unique+sparse)与 userId 的索引在字段定义处声明,勿在此重复声明
// 注意:employeeNo(unique+sparse)在字段定义处声明,勿在此重复声明
EmployeeSchema.index({ orgId: 1, role: 1, status: 1 });
EmployeeSchema.index({ role: 1, status: 1 });
EmployeeSchema.index({ "profile.phone": 1 });
EmployeeSchema.index({ status: 1 });
export { EmployeeSchema };
// 一个账号只能绑一条员工档案。
// partial 而非 sparse:历史档案可能存在 userId:null 的显式空值,sparse 挡不住多条 null;
// 上索引前先跑 scripts/check_employee_binding.js 确认无存量重复
EmployeeSchema.index(
{ userId: 1 },
{ unique: true, partialFilterExpression: { userId: { $type: "objectId" } } }
);
// genPinyin/genPinyinFL 一并导出:handler 层走 findOneAndUpdate 时绕过了 pre("save"),
// 需要自行同步拼音字段
export { EmployeeSchema, genPinyin, genPinyinFL };
+10
View File
@@ -4,6 +4,7 @@ import { HandlerPayment } from "../handler/payment.js";
import { HandlerHealthProfile } from "../handler/health_profile.js";
import { HandlerResource } from "../handler/resource.js";
import { HandlerEmployee } from "../handler/employee.js";
import { HandlerAttendantApplication } from "../handler/attendant_application.js";
import { HandlerAIMedia } from "../handler/ai_media.js";
import { HandlerTrainingApplication } from "../handler/training_application.js";
import { HandlerHospital } from "../handler/hospital.js";
@@ -80,6 +81,7 @@ function registerRoutes(app) {
const handlerHealthProfile = new HandlerHealthProfile();
const handlerResource = new HandlerResource();
const handlerEmployee = new HandlerEmployee();
const handlerAttendantApplication = new HandlerAttendantApplication();
const handlerAIMedia = new HandlerAIMedia();
const handlerTrainingApplication = new HandlerTrainingApplication();
const handlerHospital = new HandlerHospital();
@@ -144,6 +146,14 @@ function registerRoutes(app) {
router.put("/employee/:id", requireAuth, requireAdmin, updateLimit, handlerEmployee.updateEmployee.bind(handlerEmployee));
router.patch("/employee/:id/status", requireAuth, requireAdmin, updateLimit, handlerEmployee.updateEmployeeStatus.bind(handlerEmployee));
// 陪诊师入驻申请:提交与查询本人申请只要求登录;审核相关必须管理员。
// /mine 必须注册在 /:id 之前,否则会被当成 id
router.post("/attendant-application", requireAuth, createLimit, handlerAttendantApplication.createApplication.bind(handlerAttendantApplication));
router.get("/attendant-application/mine", requireAuth, handlerAttendantApplication.getMyApplication.bind(handlerAttendantApplication));
router.get("/attendant-application", requireAuth, requireAdmin, handlerAttendantApplication.getApplications.bind(handlerAttendantApplication));
router.get("/attendant-application/:id/materials", requireAuth, requireAdmin, handlerAttendantApplication.getApplicationMaterials.bind(handlerAttendantApplication));
router.post("/attendant-application/:id/review", requireAuth, requireAdmin, updateLimit, handlerAttendantApplication.reviewApplication.bind(handlerAttendantApplication));
// 医院基础信息:列表/详情公开,写接口仅管理员
router.get("/hospital", handlerHospital.getHospitals.bind(handlerHospital));
router.get("/hospital/:id", handlerHospital.getHospitalById.bind(handlerHospital));
+93
View File
@@ -0,0 +1,93 @@
/**
* 只读体检:扫描 employee.userId 重复绑定,以及 profile.idNumber 重复。
*
* 上 unique 索引前必须先跑这个:库里已有重复时索引创建会直接失败,
* 且重复档案需要人工裁决保留哪条(脚本只报告,不做任何写操作)。
*
* 用法(在 api/health 下):node scripts/check_employee_binding.js
*/
import { DBModel } from "../models/index.js";
DBModel.init();
const conn = DBModel.dbConnection;
async function main() {
const employees = conn.collection("employee");
// ---------- userId 重复 ----------
const userDupes = await employees
.aggregate([
{ $match: { userId: { $ne: null } } },
{ $group: { _id: "$userId", n: { $sum: 1 }, ids: { $push: "$_id" } } },
{ $match: { n: { $gt: 1 } } },
])
.toArray();
console.log(`\n===== employee.userId 重复绑定 =====`);
if (!userDupes.length) {
console.log(" (none) 可安全创建 unique 索引");
}
for (const dupe of userDupes) {
console.log(` userId=${dupe._id} 共 ${dupe.n} 条:${dupe.ids.join(", ")}`);
// 列出每条的裁决参考信息:保留建议 = status=active 且 createtime 最新
const docs = await employees
.find({ userId: dupe._id })
.project({
role: 1,
status: 1,
name: "$profile.name",
employeeNo: 1,
createtime: "$meta.createtime",
})
.toArray();
for (const doc of docs) {
console.log(
` - ${doc._id} role=${doc.role} status=${doc.status} name=${doc.name || "-"} no=${doc.employeeNo || "-"} created=${doc.createtime || "-"}`
);
}
}
// ---------- 身份证号重复(申请查重的数据前提) ----------
const idDupes = await employees
.aggregate([
{ $match: { "profile.idNumber": { $exists: true, $ne: "" } } },
{ $group: { _id: "$profile.idNumber", n: { $sum: 1 }, ids: { $push: "$_id" } } },
{ $match: { n: { $gt: 1 } } },
])
.toArray();
console.log(`\n===== employee.profile.idNumber 重复 =====`);
if (!idDupes.length) {
console.log(" (none)");
}
for (const dupe of idDupes) {
console.log(` idNumber=${dupe._id} 共 ${dupe.n} 条:${dupe.ids.join(", ")}`);
}
// ---------- userId 为空串的脏数据 ----------
// 字段定义无默认值,正常不该出现空串;有的话 unique partial 索引会漏掉它们
const emptyUserId = await employees.countDocuments({ userId: "" });
console.log(`\n===== userId 为空串的文档数 =====`);
console.log(` ${emptyUserId}`);
console.log("\n(脚本只读,未做任何修改)");
}
function run() {
main()
.catch((e) => {
console.error(e);
process.exitCode = 1;
})
.finally(() => conn.close());
}
if (conn.readyState === 1) {
run();
} else {
conn.once("connected", run);
conn.once("error", (e) => {
console.error(e);
process.exit(1);
});
}
@@ -0,0 +1,115 @@
/**
* employee.userId 唯一索引迁移。
*
* 背景:employee.userId 之前是普通索引(字段级 index: true),同名索引 userId_1
* 已经在库里。现在 schema 改成 partial unique,MongoDB 不允许同一个键模式
* 同时存在不同选项的索引(IndexOptionsConflict / IndexKeySpecsConflict),
* 必须先删旧索引再建新索引,否则 autoIndex 每次启动都会失败。
*
* 步骤:
* 1. 扫存量重复(userId 重复则中止,交人工裁决)
* 2. 删除键模式为 { userId: 1 } 的旧索引(不论是否唯一)
* 3. 建 { userId: 1 } 的 partial unique 索引(partial: userId 为 objectId,
* 让历史 userId 为 null/缺失/字符串的脏数据不受约束)
*
* 用法(在 api/health 下):
* node scripts/migrate_employee_userid_unique_index.js # 仅检查,不执行
* node scripts/migrate_employee_userid_unique_index.js --apply # 实际执行
*/
import { DBModel } from "../models/index.js";
DBModel.init();
const conn = DBModel.dbConnection;
const apply = process.argv.includes("--apply");
const INDEX_NAME = "userId_1";
const PARTIAL = { userId: { $type: "objectId" } };
async function main() {
const db = conn.db;
const employees = db.collection("employee");
// ---------- 1. 存量重复检查 ----------
const dupes = await employees
.aggregate([
{ $match: { userId: { $ne: null } } },
{ $group: { _id: "$userId", n: { $sum: 1 }, ids: { $push: "$_id" } } },
{ $match: { n: { $gt: 1 } } },
])
.toArray();
if (dupes.length) {
console.log(`发现 ${dupes.length} 组 userId 重复,无法建唯一索引,请先人工处理:`);
for (const dupe of dupes) {
const docs = await employees
.find({ userId: dupe._id })
.project({ role: 1, status: 1, name: "$profile.name", createtime: "$meta.createtime" })
.toArray();
console.log(` userId=${dupe._id} x${dupe.n}`);
for (const doc of docs) {
console.log(
` - ${doc._id} role=${doc.role} status=${doc.status} name=${doc.name || "-"} created=${doc.createtime || "-"}`
);
}
}
console.log("\n处理建议:保留 status=active 且创建时间最新的一条,其余改 userId: null 或删除。");
return;
}
console.log("userId 重复检查:无重复,可安全建唯一索引");
// ---------- 2. 删除旧索引 ----------
const indexes = await employees.indexes();
const old = indexes.find(
(idx) => JSON.stringify(idx.key) === JSON.stringify({ userId: 1 })
);
if (old) {
const isTarget =
old.unique === true &&
JSON.stringify(old.partialFilterExpression) === JSON.stringify(PARTIAL);
if (isTarget) {
console.log(`索引 ${old.name} 已是目标形态(partial unique),无需变更`);
return;
}
console.log(
`待删除旧索引 ${old.name}(unique=${!!old.unique}, partial=${JSON.stringify(old.partialFilterExpression || null)})`
);
if (!apply) {
console.log("dry-run:加 --apply 执行删除");
return;
}
await employees.dropIndex(old.name);
console.log(`已删除 ${old.name}`);
} else {
console.log("未发现 { userId: 1 } 旧索引,跳过删除");
}
// ---------- 3. 建 partial unique ----------
if (!apply) {
console.log("dry-run:加 --apply 创建 partial unique 索引");
return;
}
await employees.createIndex({ userId: 1 }, { unique: true, partialFilterExpression: PARTIAL, name: INDEX_NAME });
console.log(`已创建 ${INDEX_NAME}:{ userId: 1 } unique + partial(userId 为 objectId)`);
}
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);
});
}
+74
View File
@@ -0,0 +1,74 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { createErrorMiddleware } from "../app.js";
function createCtx() {
return {
method: "POST",
path: "/health/test",
headerSent: false,
status: 200,
body: null,
headers: {},
set(name, value) {
this.headers[name] = value;
},
};
}
test("非法 JSON 等 4xx 异常统一转成业务码", async () => {
const ctx = createCtx();
const err = new Error("invalid JSON, only supports object and array");
err.status = 400;
err.type = "entity.parse.failed";
await createErrorMiddleware()(ctx, async () => {
throw err;
});
assert.equal(ctx.status, 200);
assert.equal(ctx.body.code, 400);
assert.equal(ctx.body.msg, "请求参数格式不正确");
assert.equal(ctx.headers["X-Biz-Code"], "400");
});
test("请求体超限转成 413 业务码", async () => {
const ctx = createCtx();
const err = new Error("request entity too large");
err.status = 413;
await createErrorMiddleware()(ctx, async () => {
throw err;
});
assert.equal(ctx.body.code, 413);
assert.equal(ctx.body.msg, "请求体过大");
});
test("未预期异常收敛为 500,且不把内部信息回传客户端", async () => {
const ctx = createCtx();
const err = new Error("mongodb://user:pass@host/db connect failed");
await createErrorMiddleware()(ctx, async () => {
throw err;
});
assert.equal(ctx.body.code, 500);
assert.equal(ctx.body.msg, "服务器繁忙,请稍后重试");
assert.equal(ctx.body.data, null);
assert.equal(JSON.stringify(ctx.body).includes("mongodb://"), false);
});
test("响应已开始发送时不再改写响应体", async () => {
const ctx = createCtx();
ctx.headerSent = true;
await assert.rejects(
createErrorMiddleware()(ctx, async () => {
throw new Error("late failure");
}),
/late failure/
);
assert.equal(ctx.body, null);
});
+321
View File
@@ -0,0 +1,321 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { DBModel } from "../models/index.js";
import { HandlerAttendantApplication } from "../handler/attendant_application.js";
import { HandlerTrainingApplication } from "../handler/training_application.js";
import { HandlerEmployee } from "../handler/employee.js";
const OWNER_ID = "64b000000000000000000001";
/** 合法 JPEG data URL:只需文件头前缀,parseImage 不解析图片内容 */
function jpegDataUrl(extraBytes = 64) {
const buffer = Buffer.concat([Buffer.from([0xff, 0xd8, 0xff]), Buffer.alloc(extraBytes)]);
return `data:image/jpeg;base64,${buffer.toString("base64")}`;
}
/** 一年后的 YYYY-MM-DD,避免测试随时间失效 */
function futureDate() {
const date = new Date(Date.now() + 365 * 24 * 60 * 60 * 1000);
const month = String(date.getUTCMonth() + 1).padStart(2, "0");
const day = String(date.getUTCDate()).padStart(2, "0");
return `${date.getUTCFullYear()}-${month}-${day}`;
}
function validPayload(overrides = {}) {
return {
applicant: {
name: "张三",
mobile: "13800138000",
idNumber: "110101199001011234",
sex: "male",
serviceAreas: ["北京市"],
introduction: "有三年陪诊经验",
},
materials: {
qualification: jpegDataUrl(),
healthCertificate: jpegDataUrl(),
},
healthExpireDate: futureDate(),
...overrides,
};
}
/** 最小 Koa ctx:ResponseUtil 只会用到 status / set / body */
function createCtx({ query = {}, body = {}, params = {}, user = { _id: OWNER_ID } } = {}) {
return {
request: { query, body },
params,
state: { user },
headers: {},
status: 200,
body: null,
set(name, value) {
this.headers[name] = value;
},
};
}
function withModel(modelName, stub, fn) {
const previous = DBModel[modelName];
DBModel[modelName] = stub;
return Promise.resolve(fn()).finally(() => {
DBModel[modelName] = previous;
});
}
test("入驻申请列表把 keyword 透传给查询层且不再抛 ReferenceError", async () => {
const calls = [];
const stub = {
findApplicationPage: async (options) => {
calls.push(options);
return { applications: [], total: 0 };
},
};
await withModel("AttendantApplication", stub, async () => {
const ctx = createCtx({
query: { status: "all", keyword: " 张三 ", page: "2", pageSize: "10" },
});
await new HandlerAttendantApplication().getApplications(ctx);
assert.equal(ctx.body.code, 0);
assert.equal(calls.length, 1);
assert.equal(calls[0].keyword, "张三");
assert.equal(calls[0].status, "");
assert.equal(calls[0].page, 2);
assert.equal(calls[0].pageSize, 10);
});
});
test("入驻申请列表拒绝非法状态值", async () => {
const ctx = createCtx({ query: { status: "unknown" } });
await new HandlerAttendantApplication().getApplications(ctx);
assert.equal(ctx.body.code, 400);
assert.equal(ctx.body.msg, "审核状态筛选值不正确");
});
test("驳回后重新提交可沿用上一份证件照,无需重复上传", () => {
const expireDate = new Date(`${futureDate()}T00:00:00.000Z`);
const previous = {
materials: {
qualification: { data: jpegDataUrl(), mime: "image/jpeg" },
healthCertificate: { data: jpegDataUrl(), mime: "image/jpeg", expireDate },
},
};
const payload = validPayload();
delete payload.materials;
delete payload.healthExpireDate;
const result = HandlerAttendantApplication.parsePayload(payload, previous);
assert.equal(result.error, undefined);
assert.equal(result.value.materials.qualification.mime, "image/jpeg");
assert.equal(result.value.materials.healthCertificate.expireDate, expireDate);
});
test("入驻材料单张图片按 3MB 上限校验", () => {
const oversized = Buffer.concat([
Buffer.from([0xff, 0xd8, 0xff]),
Buffer.alloc(3 * 1024 * 1024),
]);
const result = HandlerTrainingApplication.parseImage(
`data:image/jpeg;base64,${oversized.toString("base64")}`,
"资质证书照片",
3 * 1024 * 1024
);
assert.match(result.error, /不能超过 3MB/);
});
test("健康证明到期日按东八区当天末判断,已过期直接拒绝", () => {
const result = HandlerAttendantApplication.parsePayload(
validPayload({ healthExpireDate: "2020-01-01" })
);
assert.equal(result.error, "健康证明已过期,请更新后再提交");
});
test("员工解绑账号时同步清空 userIdSource", async () => {
let received = null;
const stub = {
updateEmployee: async (id, flat) => {
received = flat;
return { _id: id };
},
};
await withModel("Employee", stub, async () => {
const ctx = createCtx({ params: { id: OWNER_ID }, body: { userId: "" } });
await new HandlerEmployee().updateEmployee(ctx);
assert.equal(ctx.body.code, 0);
assert.equal(received.userId, null);
assert.equal(received.userIdSource, "");
});
});
/** Employee.findOne 链式 stub:按 filter 区分按账号查与按身份证查重 */
function employeeFindOneStub(handler) {
return {
findOne: (filter) => ({
select: () => ({
lean: () => ({ exec: async () => handler(filter) }),
}),
}),
};
}
test("已有其他岗位档案的账号提交入驻被拒绝,提示走人工转岗", async () => {
const stub = employeeFindOneStub(() => ({ role: "nurse", status: "active", profile: { name: "李护士" } }));
await withModel("Employee", stub, async () => {
const ctx = createCtx({ body: validPayload() });
await new HandlerAttendantApplication().createApplication(ctx);
assert.equal(ctx.body.code, 409);
assert.match(ctx.body.msg, /护士/);
assert.match(ctx.body.msg, /联系客服/);
});
});
test("停用陪诊师重新申请不被岗位拦截,可正常提交", async () => {
const employeeStub = employeeFindOneStub((filter) => {
// 按账号查:停用陪诊师;按身份证号查重:无冲突
if (filter["profile.idNumber"]) return null;
return { role: "attendant", status: "suspended", profile: { name: "张三" } };
});
const applicationStub = {
findLatestByUser: async () => null,
createApplication: async (data) => ({
_id: OWNER_ID,
status: "pending",
applicant: data.applicant,
materials: data.materials,
meta: { createtime: Date.now() },
}),
};
await withModel("Employee", employeeStub, async () => {
await withModel("AttendantApplication", applicationStub, async () => {
const ctx = createCtx({
body: validPayload(),
user: { _id: OWNER_ID, apps: [{ appId: "wxapp-escort-admin", status: "active" }] },
});
await new HandlerAttendantApplication().createApplication(ctx);
assert.equal(ctx.body.code, 0);
assert.equal(ctx.body.data.application.status, "pending");
});
});
});
test("审批建档遇到非陪诊师岗位档案时拒绝改写", async () => {
const stub = employeeFindOneStub(() => ({ role: "doctor" }));
await withModel("Employee", stub, async () => {
await assert.rejects(
() =>
HandlerAttendantApplication.ensureEmployee({
userId: OWNER_ID,
applicant: { name: "张三" },
materials: {},
}),
(err) => err.code === "ROLE_CONFLICT"
);
});
});
test("停用陪诊师审批通过时复用原档案并激活", async () => {
let capturedFilter = null;
let capturedUpdate = null;
const stub = {
findOne: () => ({
select: () => ({ lean: () => ({ exec: async () => ({ role: "attendant" }) }) }),
}),
findOneAndUpdate: (filter, update) => {
capturedFilter = filter;
capturedUpdate = update;
return { exec: async () => ({ _id: OWNER_ID, role: "attendant", status: "active" }) };
},
};
await withModel("Employee", stub, async () => {
const employee = await HandlerAttendantApplication.ensureEmployee({
userId: OWNER_ID,
applicant: {
name: "张三",
sex: "male",
mobile: "13800138000",
idNumber: "110101199001011234",
serviceAreas: ["北京市"],
introduction: "",
},
materials: {},
});
assert.equal(employee._id, OWNER_ID);
// 过滤条件只认 attendant,命中已有档案后走更新分支(不新建)
assert.equal(capturedFilter.role, "attendant");
assert.equal(capturedUpdate.$set.role, "attendant");
assert.equal(capturedUpdate.$set.status, "active");
assert.equal(capturedUpdate.$set.userIdSource, "application");
});
});
test("审批遇岗位冲突时申请单回滚为 pending,不卡死在 approved", async () => {
const approvedDoc = {
_id: OWNER_ID,
status: "approved",
approvedEmployeeId: null,
applicant: { name: "张三", mobile: "13800138000", idNumber: "110101199001011234" },
materials: { healthCertificate: { expireDate: new Date("2030-01-01") } },
meta: { createtime: Date.now() },
};
let rollbackFilter = null;
let rollbackUpdate = null;
const applicationStub = {
findOneAndUpdate: () => ({ exec: async () => approvedDoc }),
updateOne: (filter, update) => {
rollbackFilter = filter;
rollbackUpdate = update;
return { exec: async () => ({}) };
},
};
const employeeStub = employeeFindOneStub(() => ({ role: "doctor" }));
await withModel("AttendantApplication", applicationStub, async () => {
await withModel("Employee", employeeStub, async () => {
const ctx = createCtx({ params: { id: OWNER_ID }, body: { action: "approve" } });
await new HandlerAttendantApplication().reviewApplication(ctx);
assert.equal(ctx.body.code, 409);
assert.match(ctx.body.msg, /确认岗位/);
// 只回滚"已抢占但未建档"的单据,回滚目标状态是 pending
assert.equal(rollbackFilter.status, "approved");
assert.equal(rollbackFilter.approvedEmployeeId, null);
assert.equal(rollbackUpdate.$set.status, "pending");
});
});
});
test("身份证被其他岗位档案占用时,查重文案按实际岗位提示", async () => {
const employeeStub = employeeFindOneStub((filter) => {
// 按账号查:本账号无档案;按身份证查重:命中护士档案
if (filter["profile.idNumber"]) return { role: "nurse", profile: { name: "李护士" } };
return null;
});
const applicationStub = { findLatestByUser: async () => null };
await withModel("Employee", employeeStub, async () => {
await withModel("AttendantApplication", applicationStub, async () => {
const ctx = createCtx({ body: validPayload() });
await new HandlerAttendantApplication().createApplication(ctx);
assert.equal(ctx.body.code, 409);
assert.match(ctx.body.msg, /已绑定「护士」员工档案/);
assert.doesNotMatch(ctx.body.msg, /已绑定陪诊师/);
});
});
});
+240
View File
@@ -0,0 +1,240 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { DBModel } from "../models/index.js";
import { HandlerEscortRecord } from "../handler/escort_record.js";
import { HandlerHealthProfile } from "../handler/health_profile.js";
const RECORD_ID = "64b000000000000000000010";
const OWNER_ID = "64b000000000000000000001";
const ATTENDANT_ID = "64b000000000000000000002";
const ADMIN_ID = "64b000000000000000000003";
const PAYMENT_ID = "64b000000000000000000020";
const ADMIN_USER = {
_id: ADMIN_ID,
app: { "wxapp-escort-admin": { role: ["admin"] } },
};
function buildRecord(overrides = {}) {
return {
_id: RECORD_ID,
userId: OWNER_ID,
status: "confirmed",
cancelStatus: "none",
escort: { serviceId: 1, serviceName: "全天陪诊" },
hospital: { province: "北京市", name: "北京协和医院" },
schedule: {
date: new Date("2026-12-01T00:00:00.000Z"),
startTime: "08:00",
endTime: "17:00",
duration: 480,
},
payment: {
totalFee: 500,
paidFee: 0,
status: "unpaid",
payChannel: "online_wechat",
paymentRecordId: PAYMENT_ID,
},
notes: { patientNote: "患者原备注", escortNote: "原服务记录", medicalSummary: "" },
attendant: { id: ATTENDANT_ID, name: "李四" },
...overrides,
};
}
function createCtx({ body = {}, user, params = { id: RECORD_ID } } = {}) {
return {
request: { query: {}, body },
params,
state: { user: user ?? { _id: OWNER_ID } },
headers: {},
status: 200,
body: null,
set(name, value) {
this.headers[name] = value;
},
};
}
function createRecordStub(record) {
const calls = { update: null, count: 0 };
return {
calls,
findById: async () => record,
updateRecord: async (id, payload) => {
calls.update = payload;
calls.count += 1;
return { ...record, ...payload };
},
};
}
function withModel(modelName, stub, fn) {
const previous = DBModel[modelName];
DBModel[modelName] = stub;
return Promise.resolve(fn()).finally(() => {
DBModel[modelName] = previous;
});
}
test("陪诊员只能写服务备注,医院与患者备注被过滤", async () => {
const stub = createRecordStub(buildRecord());
await withModel("EscortRecord", stub, async () => {
const ctx = createCtx({
user: { _id: ATTENDANT_ID },
body: {
"hospital.name": "被篡改的医院",
"notes.patientNote": "被篡改的患者备注",
"notes.escortNote": "已完成陪同",
},
});
await new HandlerEscortRecord().updateRecord(ctx);
assert.equal(ctx.body.code, 0);
assert.deepEqual(stub.calls.update, { "notes.escortNote": "已完成陪同" });
});
});
test("陪诊员在待确认订单上不能写入", async () => {
const stub = createRecordStub(buildRecord({ status: "pending" }));
await withModel("EscortRecord", stub, async () => {
const ctx = createCtx({
user: { _id: ATTENDANT_ID },
body: { "notes.escortNote": "提前写" },
});
await new HandlerEscortRecord().updateRecord(ctx);
assert.equal(ctx.body.code, 403);
assert.equal(stub.calls.count, 0);
});
});
test("订单主人仍可修改医院等预约字段", async () => {
const stub = createRecordStub(buildRecord());
await withModel("EscortRecord", stub, async () => {
const ctx = createCtx({ body: { "hospital.name": "北京协和医院东院" } });
await new HandlerEscortRecord().updateRecord(ctx);
assert.equal(ctx.body.code, 0);
assert.equal(stub.calls.update["hospital.name"], "北京协和医院东院");
});
});
test("管理员通用更新不能绕过状态机回退状态", async () => {
const stub = createRecordStub(buildRecord({ status: "completed" }));
await withModel("EscortRecord", stub, async () => {
const ctx = createCtx({ user: ADMIN_USER, body: { status: "in_progress" } });
await new HandlerEscortRecord().updateRecord(ctx);
assert.equal(ctx.body.code, 400);
assert.equal(stub.calls.count, 0);
});
});
test("管理员合法状态流转仍可通过", async () => {
const stub = createRecordStub(buildRecord({ status: "pending" }));
await withModel("EscortRecord", stub, async () => {
const ctx = createCtx({ user: ADMIN_USER, body: { status: "confirmed" } });
await new HandlerEscortRecord().updateRecord(ctx);
assert.equal(ctx.body.code, 0);
assert.equal(stub.calls.update.status, "confirmed");
});
});
test("管理员只提交部分 payment 字段时保留中间支付状态", async () => {
const stub = createRecordStub(buildRecord());
const paymentStub = { findOne: async () => null };
await withModel("EscortRecord", stub, () =>
withModel("PaymentRecord", paymentStub, async () => {
const ctx = createCtx({ user: ADMIN_USER, body: { payment: { totalFee: 600 } } });
await new HandlerEscortRecord().updateRecord(ctx);
assert.equal(ctx.body.code, 0);
assert.equal(stub.calls.update["payment.totalFee"], 600);
assert.equal(stub.calls.update["payment.status"], "unpaid");
assert.equal(stub.calls.update["payment.paymentRecordId"], PAYMENT_ID);
assert.equal(stub.calls.update["payment.payChannel"], "online_wechat");
// 嵌套对象必须摊平,不能与点号路径同时出现在 $set 里
assert.equal(stub.calls.update.payment, undefined);
})
);
});
test("切换支付渠道时嵌套 payment 摊平后不会产生路径冲突", async () => {
const stub = createRecordStub(buildRecord());
const paymentStub = {
findOne: async () => null,
find: async () => [],
};
await withModel("EscortRecord", stub, () =>
withModel("PaymentRecord", paymentStub, async () => {
const ctx = createCtx({ user: ADMIN_USER, body: { payment: { payChannel: "offline" } } });
await new HandlerEscortRecord().updateRecord(ctx);
assert.equal(ctx.body.code, 0);
assert.equal(stub.calls.update.payment, undefined);
assert.equal(stub.calls.update["payment.payChannel"], "offline");
assert.equal(stub.calls.update["payment.paymentRecordId"], null);
})
);
});
test("在职陪诊员不能确认未分配给自己的本人订单", async () => {
const record = buildRecord({ status: "pending" });
let statusUpdates = 0;
const recordStub = {
...createRecordStub(record),
updateRecordStatus: async () => {
statusUpdates += 1;
return record;
},
};
const employeeStub = {
findOne: () => ({
select: () => ({
lean: async () => ({ role: "attendant" }),
}),
}),
};
await withModel("EscortRecord", recordStub, () =>
withModel("Employee", employeeStub, async () => {
const ctx = createCtx({
user: {
_id: OWNER_ID,
app: { "wxapp-escort-admin": { role: ["user"] } },
},
body: { status: "confirmed" },
});
await new HandlerEscortRecord().updateStatus(ctx);
assert.equal(ctx.body.code, 403);
assert.equal(statusUpdates, 0);
})
);
});
test("健康档案更新把嵌套对象摊平成点号路径", () => {
const picked = HandlerHealthProfile.pickFields(
{
profile: { name: "李四", sex: "male" },
health: { height: 170, weight: 60 },
userId: OWNER_ID,
},
{ flatten: true }
);
assert.deepEqual(picked, {
"profile.name": "李四",
"profile.sex": "male",
"health.height": 170,
"health.weight": 60,
userId: OWNER_ID,
});
assert.equal(picked.profile, undefined);
assert.equal(picked.health, undefined);
});
+113
View File
@@ -11,6 +11,8 @@ import {
verifyMessageSignature,
decryptAesGcm,
} from "../utils/wechatpay.js";
import { createOrderQueryCache, HandlerPayment } from "../handler/payment.js";
import { DBModel } from "../models/index.js";
test("元转分按小数点拆位,不经过浮点", () => {
assert.equal(yuanToFen("500.00"), 50000);
@@ -100,3 +102,114 @@ test("AES-256-GCM 解密与 authTag 校验", () => {
apiV3Key: key,
}));
});
test("轮询查单在 TTL 内复用结果,过期后重新查询", async () => {
let calls = 0;
let current = 1000;
const query = createOrderQueryCache({
ttl: 3000,
now: () => current,
query: async (outTradeNo) => {
calls += 1;
return { outTradeNo, trade_state: "NOTPAY" };
},
});
const first = await query("T1");
current = 1500;
const second = await query("T1");
assert.equal(first, second);
assert.equal(calls, 1);
current = 4001;
await query("T1");
assert.equal(calls, 2);
});
test("同一订单的并发轮询共享一次上游查单", async () => {
let calls = 0;
let release;
const query = createOrderQueryCache({
query: () => {
calls += 1;
return new Promise((resolve) => {
release = () => resolve({ trade_state: "NOTPAY" });
});
},
});
const first = query("T2");
const second = query("T2");
await new Promise((resolve) => setImmediate(resolve));
assert.equal(calls, 1);
release();
const [a, b] = await Promise.all([first, second]);
assert.equal(a, b);
});
test("查单失败不写缓存,下一次仍会重试", async () => {
let calls = 0;
const query = createOrderQueryCache({
query: async () => {
calls += 1;
if (calls === 1) throw new Error("network down");
return { trade_state: "NOTPAY" };
},
});
await assert.rejects(query("T3"), /network down/);
await query("T3");
assert.equal(calls, 2);
});
test("force 可绕过轮询缓存", async () => {
let calls = 0;
const query = createOrderQueryCache({
ttl: 60_000,
query: async () => {
calls += 1;
return { trade_state: "NOTPAY" };
},
});
await query("T4");
await query("T4", { force: true });
assert.equal(calls, 2);
});
test("退款成功后的迟到处理中结果不会回退支付与订单状态", async () => {
const previous = {
RefundRecord: DBModel.RefundRecord,
PaymentRecord: DBModel.PaymentRecord,
EscortRecord: DBModel.EscortRecord,
};
let refundFilter = null;
let downstreamWrites = 0;
DBModel.RefundRecord = {
updateOne: async (filter) => {
refundFilter = filter;
return { matchedCount: 0 };
},
};
DBModel.PaymentRecord = {
updateOne: async () => { downstreamWrites += 1; },
};
DBModel.EscortRecord = {
updateOne: async () => { downstreamWrites += 1; },
};
try {
const status = await HandlerPayment.applyRefundResult(
{ _id: "r1", paymentId: "p1", recordId: "o1", status: "success" },
{ status: "PROCESSING" }
);
assert.equal(status, "success");
assert.deepEqual(refundFilter.status, { $ne: "success" });
assert.equal(downstreamWrites, 0);
} finally {
Object.assign(DBModel, previous);
}
});
+122
View File
@@ -0,0 +1,122 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import {
rateLimit,
createUserLimiter,
sweepRateLimitStores,
normalizeDynamicPath,
} from "../middleware/ratelimit.js";
const ID_A = "64b000000000000000000001";
const ID_B = "64b000000000000000000002";
function unique(prefix) {
return `${prefix}-${Date.now()}-${Math.random()}`;
}
function createCtx({
userId = null,
method = "PUT",
path = "/health/test",
routerPath = undefined,
ip = "203.0.113.9",
} = {}) {
return {
state: { user: userId ? { _id: userId } : null },
method,
path,
routerPath,
ip,
headers: {},
status: 200,
body: null,
set(name, value) {
this.headers[name] = value;
},
};
}
test("限流按路由模式分桶,换订单 ID 不能绕过", async () => {
const user = unique("route");
const middleware = rateLimit(1, 60_000);
const first = createCtx({
userId: user,
path: `/health/escort-record/${ID_A}`,
routerPath: "/health/escort-record/:id",
});
const second = createCtx({
userId: user,
path: `/health/escort-record/${ID_B}`,
routerPath: "/health/escort-record/:id",
});
await middleware(first, async () => {});
await middleware(second, async () => {});
assert.equal(first.body, null);
assert.equal(second.body.code, 429);
assert.ok(Number(second.headers["Retry-After"]) > 0);
});
test("拿不到路由模式时把 ObjectId 路径段归一成 :id", async () => {
const user = unique("fallback");
const middleware = rateLimit(1, 60_000);
const first = createCtx({ userId: user, path: `/health/escort-record/${ID_A}` });
const second = createCtx({ userId: user, path: `/health/escort-record/${ID_B}` });
await middleware(first, async () => {});
await middleware(second, async () => {});
assert.equal(first.body, null);
assert.equal(second.body.code, 429);
assert.equal(
normalizeDynamicPath(`/health/escort-record/${ID_A}/pay`),
"/health/escort-record/:id/pay"
);
});
test("不同路由各自独立计数", async () => {
const user = unique("separate");
const middleware = rateLimit(1, 60_000);
const recordRoute = createCtx({
userId: user,
path: `/health/escort-record/${ID_A}`,
routerPath: "/health/escort-record/:id",
});
const profileRoute = createCtx({
userId: user,
path: `/health/health-profile/${ID_A}`,
routerPath: "/health/health-profile/:id",
});
await middleware(recordRoute, async () => {});
await middleware(profileRoute, async () => {});
assert.equal(recordRoute.body, null);
assert.equal(profileRoute.body, null);
});
test("按用户限流在窗口内生效,过期后可重新计数", () => {
const limiter = createUserLimiter(2, 60_000);
const userId = unique("ws");
assert.equal(limiter(userId).allowed, true);
assert.equal(limiter(userId).allowed, true);
assert.equal(limiter(userId).allowed, false);
// 推进到窗口之外,清理后重新计数
sweepRateLimitStores(Date.now() + 120_000);
assert.equal(limiter(userId).allowed, true);
});
test("统一清理会回收用户限流的过期桶", () => {
const limiter = createUserLimiter(5, 1000);
limiter(unique("sweep"));
const removed = sweepRateLimitStores(Date.now() + 5000);
assert.ok(removed >= 1);
});
+61
View File
@@ -0,0 +1,61 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { describeToolResult, describeStreamPayload } from "../agent/infra/tool_log.js";
test("工具结果日志只保留长度与 success,不落患者信息", () => {
const content = JSON.stringify({
success: true,
data: {
patient: { name: "张三", mobile: "13800138000" },
address: "北京市东城区某小区 1 号楼",
},
});
const summary = describeToolResult(content);
assert.deepEqual(summary, { chars: content.length, success: true });
const logged = JSON.stringify(summary);
assert.equal(logged.includes("张三"), false);
assert.equal(logged.includes("13800138000"), false);
assert.equal(logged.includes("北京市"), false);
});
test("工具失败只记录 errorCode,不记录可能带姓名的错误文案", () => {
const content = JSON.stringify({
success: false,
error: "未找到患者张三的订单",
errorCode: "NOT_FOUND",
});
const summary = describeToolResult(content);
assert.deepEqual(summary, {
chars: content.length,
success: false,
errorCode: "NOT_FOUND",
});
assert.equal(JSON.stringify(summary).includes("张三"), false);
});
test("纯文本或截断后的工具结果只记录长度", () => {
assert.deepEqual(describeToolResult("患者张三,手机号 13800138000"), {
chars: 20,
});
assert.deepEqual(describeToolResult(""), { chars: 0 });
});
test("custom 流事件只记录类型/字段名,不记录字段值", () => {
const summary = describeStreamPayload({
type: "progress",
content: "正在读取张三的健康档案",
});
assert.deepEqual(summary, {
type: "object",
keys: ["type", "content"],
});
assert.equal(JSON.stringify(summary).includes("张三"), false);
assert.deepEqual(describeStreamPayload("张三的订单"), { type: "string", chars: 5 });
assert.deepEqual(describeStreamPayload([1, 2, 3]), { type: "array", items: 3 });
});
+127
View File
@@ -0,0 +1,127 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import WebSocketServerManager from "../websocket.js";
function createWs() {
const sent = [];
return {
readyState: 1,
sent,
send(payload) {
sent.push(JSON.parse(payload));
},
};
}
function frame(payload) {
return Buffer.from(JSON.stringify(payload));
}
test("ASR 分片不等待在途的聊天生成", async () => {
const manager = new WebSocketServerManager(0);
const ws = createWs();
const order = [];
let releaseChat;
manager._handleMessage = async (ws, msg) => {
if (msg.type === "chat") {
order.push("chat-start");
await new Promise((resolve) => {
releaseChat = resolve;
});
order.push("chat-end");
return;
}
if (msg.type === "asr_chunk") {
order.push("asr-chunk");
}
};
const chat = manager._dispatchMessage(ws, frame({ type: "chat", content: "你好" }));
const asr = manager._dispatchMessage(ws, frame({ type: "asr_chunk", audio: "x" }));
await asr;
// 聊天还卡在生成中,ASR 分片已经处理完
assert.deepEqual(order, ["chat-start", "asr-chunk"]);
releaseChat();
await chat;
assert.deepEqual(order, ["chat-start", "asr-chunk", "chat-end"]);
});
test("ASR 帧之间保持串行,不会乱序", async () => {
const manager = new WebSocketServerManager(0);
const ws = createWs();
const order = [];
let releaseFirst;
manager._handleMessage = async (ws, msg) => {
if (msg.id === "1") {
order.push("start-1");
await new Promise((resolve) => {
releaseFirst = resolve;
});
order.push("end-1");
return;
}
order.push("start-2");
};
const first = manager._dispatchMessage(ws, frame({ type: "asr_start", id: "1" }));
const second = manager._dispatchMessage(ws, frame({ type: "asr_start", id: "2" }));
await new Promise((resolve) => setImmediate(resolve));
assert.deepEqual(order, ["start-1"]);
releaseFirst();
await first;
await second;
assert.deepEqual(order, ["start-1", "end-1", "start-2"]);
});
test("ping 立即应答,不排在长回复后面", async () => {
const manager = new WebSocketServerManager(0);
const ws = createWs();
let release;
manager._handleMessage = async () => new Promise((resolve) => {
release = resolve;
});
const chat = manager._dispatchMessage(ws, frame({ type: "chat", content: "长问题" }));
manager._dispatchMessage(ws, frame({ type: "ping", id: "p1" }));
assert.equal(ws.sent.at(-1).type, "pong");
assert.equal(ws.sent.at(-1).id, "p1");
await new Promise((resolve) => setImmediate(resolve));
release();
await chat;
});
test("非法 JSON 帧回错误帧而不是抛异常", () => {
const manager = new WebSocketServerManager(0);
const ws = createWs();
manager._dispatchMessage(ws, Buffer.from("{"));
assert.equal(ws.sent.length, 1);
assert.equal(ws.sent[0].type, "error");
assert.equal(ws.sent[0].content, "消息格式错误");
});
test("null / 数组等非对象帧同样按消息格式错误处理", () => {
const manager = new WebSocketServerManager(0);
const ws = createWs();
manager._dispatchMessage(ws, Buffer.from("null"));
manager._dispatchMessage(ws, Buffer.from("[]"));
manager._dispatchMessage(ws, Buffer.from("123"));
assert.equal(ws.sent.length, 3);
for (const item of ws.sent) {
assert.equal(item.type, "error");
assert.equal(item.content, "消息格式错误");
}
});
+5
View File
@@ -36,6 +36,11 @@ async function lookup(body) {
body: JSON.stringify(body),
signal: AbortSignal.timeout(LOOKUP_TIMEOUT),
});
// 非 2xx 视为服务故障而不是「token 无效」:曾把 5xx 当作未登录,
// 在线用户会被负缓存 60 秒,表现为莫名被踢回登录页
if (!res.ok) {
throw new Error(`user service responded ${res.status}`);
}
const data = await res.json();
return data?.data?.user || null;
}
+51 -10
View File
@@ -38,6 +38,10 @@ const ASR_LIMITS = {
sniffBytes: 16 * 1024
};
// 实时识别帧走独立队列:识别分片不能被在途的模型生成阻塞,
// 否则用户一边等回复一边说话时,PCM 会整段堆到回复结束才被处理
const ASR_FRAME_TYPES = new Set(['asr_start', 'asr_chunk', 'asr_stop', 'asr_cancel']);
/**
* WebM 解码出的 PCM 采样率归一
*
@@ -112,13 +116,13 @@ export default class WebSocketServerManager {
_handleChatConnection(ws) {
sendFrame(ws, 'system', 'connected', 'Connected to chat server');
// 同一连接的消息串行处理:agent 的 messages 数组是共享状态,
// 并发跑同一个 agent 会让上下文交错、回复错乱
// 两条独立队列:
// - messageQueue:chat/clear/format,agent 的 messages 是共享状态,必须串行
// - asrQueue:实时识别分片只与同一轮识别串行,不能被在途的模型生成堵住
ws.messageQueue = Promise.resolve();
ws.asrQueue = Promise.resolve();
ws.on('message', (data) => {
ws.messageQueue = ws.messageQueue
.then(() => this._handleMessage(ws, data))
.catch((err) => console.error('WebSocket message handling error:', err));
this._dispatchMessage(ws, data);
});
ws.on('close', () => {
@@ -126,6 +130,7 @@ export default class WebSocketServerManager {
this._abortAsrSession(ws);
// 断开后释放队列引用,避免连接对象被闭包长期持有
ws.messageQueue = null;
ws.asrQueue = null;
console.log('Chat client disconnected');
});
@@ -134,11 +139,47 @@ export default class WebSocketServerManager {
});
}
async _handleMessage(ws, data) {
/**
* 帧分发:先解析,再按类型放入对应队列
*
* asr_* 入识别队列,其余聊天帧入聊天队列;ping 立即应答,
* 不排在模型生成后面,避免长回复期间心跳超时。
*
* @param {Object} ws 连接
* @param {Buffer|string} data 原始帧
* @returns {Promise} 当前帧所在队列的完成 Promise
*/
_dispatchMessage(ws, data) {
let msg;
try {
const raw = data.toString();
msg = JSON.parse(data.toString());
} catch (err) {
sendFrame(ws, 'system', 'error', '消息格式错误');
return Promise.resolve();
}
const msg = JSON.parse(raw);
// JSON.parse("null") / 数组 / 标量都能成功解析,但不是合法帧
if (!msg || typeof msg !== 'object' || Array.isArray(msg)) {
sendFrame(ws, 'system', 'error', '消息格式错误');
return Promise.resolve();
}
if (msg.type === 'ping') {
sendFrame(ws, 'system', 'pong', '', msg.id);
return Promise.resolve();
}
const queueKey = ASR_FRAME_TYPES.has(msg.type) ? 'asrQueue' : 'messageQueue';
const previous = ws[queueKey] || Promise.resolve();
const current = previous
.then(() => this._handleMessage(ws, msg))
.catch((err) => console.error('WebSocket message handling error:', err));
ws[queueKey] = current;
return current;
}
async _handleMessage(ws, msg) {
try {
// 只记录消息类型:正文含健康描述、token/userId 属敏感信息,不进日志。
// 实时识别的分片按秒级频率到达,逐帧打日志会把日志刷满,这里跳过
if (msg.type !== 'asr_chunk') {
@@ -233,8 +274,8 @@ export default class WebSocketServerManager {
console.log('[Unknown message type]', msg.type);
} catch (e) {
console.error('Message parse error:', e);
sendFrame(ws, 'system', 'error', '消息格式错误');
console.error('WebSocket message handling error:', e);
sendFrame(ws, 'system', 'error', '处理消息失败,请稍后重试');
}
}