feat: 订单可改字段按角色收敛并修复嵌套字段覆盖
- 陪诊员只能写服务备注与就诊小结;订单主人按状态收敛, 取消中/已取消一律冻结 - 更新前把嵌套子文档摊平成点号路径并与现值合并: 整块 $set 会抹掉未提交字段,与点号路径混用还会触发 Mongo 路径冲突 - 通用更新接口的状态迁移改走状态机,软删除订单按不存在处理
This commit is contained in:
@@ -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);
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
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("健康档案更新把嵌套对象摊平成点号路径", () => {
|
||||
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);
|
||||
});
|
||||
Reference in New Issue
Block a user