fix: 订单与档案接口收敛错误细节与写入校验
internalError 只把通用文案回给前端、详情进日志;状态迁移规则抽到 utils/record_state.js 单点维护;档案更新开 runValidators 并补姓名/手机号/身高体重校验与每人档案上限;已支付订单改为软删除保留审计。
This commit is contained in:
+27
-18
@@ -2,6 +2,7 @@ import { DBModel } from "../models/index.js";
|
||||
import services from "../resource/services.js";
|
||||
import ResponseUtil from "../utils/responseUtil.js";
|
||||
import { isAdmin as isAdminUser } from "../utils/permissions.js";
|
||||
import { canTransition, STATUS_TRANSITIONS } from "../utils/record_state.js";
|
||||
|
||||
class HandlerEscortRecord {
|
||||
constructor() {
|
||||
@@ -30,14 +31,8 @@ class HandlerEscortRecord {
|
||||
};
|
||||
|
||||
// 用户端只能取消;服务完成由平台确认,避免用户端重复写入终态。
|
||||
// 迁移规则集中在 utils/record_state.js,与管理端 Agent 工具共用
|
||||
static OWNER_ALLOWED_STATUS = ["cancelled"];
|
||||
static STATUS_TRANSITIONS = {
|
||||
pending: ["confirmed", "cancelled"],
|
||||
confirmed: ["in_progress", "cancelled"],
|
||||
in_progress: ["completed"],
|
||||
completed: [],
|
||||
cancelled: [],
|
||||
};
|
||||
|
||||
// 单页最大条数,避免 pageSize 传超大值一次拖库
|
||||
static MAX_PAGE_SIZE = 200;
|
||||
@@ -205,7 +200,7 @@ class HandlerEscortRecord {
|
||||
statusArray = status.split(',')
|
||||
}
|
||||
|
||||
if (statusArray && statusArray.some((item) => !Object.hasOwn(HandlerEscortRecord.STATUS_TRANSITIONS, item))) {
|
||||
if (statusArray && statusArray.some((item) => !Object.hasOwn(STATUS_TRANSITIONS, item))) {
|
||||
return ResponseUtil.badRequest(ctx, "订单状态筛选值不正确");
|
||||
}
|
||||
|
||||
@@ -455,7 +450,7 @@ class HandlerEscortRecord {
|
||||
if (!isAdmin && !HandlerEscortRecord.OWNER_ALLOWED_STATUS.includes(status)) {
|
||||
return ResponseUtil.forbidden(ctx, "不支持的状态变更");
|
||||
}
|
||||
if (!HandlerEscortRecord.STATUS_TRANSITIONS[existing.status]?.includes(status)) {
|
||||
if (!canTransition(existing.status, status)) {
|
||||
return ResponseUtil.badRequest(ctx, "当前订单状态不允许此操作");
|
||||
}
|
||||
|
||||
@@ -498,22 +493,36 @@ class HandlerEscortRecord {
|
||||
return ResponseUtil.forbidden(ctx, "无权删除该订单");
|
||||
}
|
||||
|
||||
// 与前端口径一致:仅「未支付且未进入服务阶段」的订单可删。
|
||||
// 已支付/进行中/已完成的订单承载服务与费用记录,不能只靠前端隐藏按钮来保护
|
||||
// 删除口径(与产品确认一致):
|
||||
// - 未支付且未进入服务阶段:物理删除,允许用户/管理员清理误建订单;
|
||||
// - 其他(已支付/进行中/已完成):仅管理员可「软删除」,
|
||||
// 状态置为已取消并打 deletedAt 标记,保留费用与服务审计链,列表默认不再展示
|
||||
const paymentStatus = existing.payment?.status || "unpaid";
|
||||
const deletable = paymentStatus === "unpaid"
|
||||
const hardDeletable = paymentStatus === "unpaid"
|
||||
&& ["pending", "confirmed", "cancelled"].includes(existing.status);
|
||||
if (!HandlerEscortRecord.isAdmin(ctx.state.user) && !deletable) {
|
||||
|
||||
if (hardDeletable) {
|
||||
const deletedRecord = await DBModel.EscortRecord.deleteRecord(id);
|
||||
if (!deletedRecord) {
|
||||
return ResponseUtil.error(ctx, "陪诊记录不存在", null, 404);
|
||||
}
|
||||
return ResponseUtil.success(ctx, { record: deletedRecord }, "删除成功");
|
||||
}
|
||||
|
||||
if (!HandlerEscortRecord.isAdmin(ctx.state.user)) {
|
||||
return ResponseUtil.forbidden(ctx, "该订单不可删除");
|
||||
}
|
||||
|
||||
const deletedRecord = await DBModel.EscortRecord.deleteRecord(id);
|
||||
|
||||
if (!deletedRecord) {
|
||||
const softDeleted = await DBModel.EscortRecord.updateRecord(id, {
|
||||
status: "cancelled",
|
||||
cancelReason: "平台删除",
|
||||
cancelledAt: new Date(),
|
||||
deletedAt: new Date(),
|
||||
});
|
||||
if (!softDeleted) {
|
||||
return ResponseUtil.error(ctx, "陪诊记录不存在", null, 404);
|
||||
}
|
||||
|
||||
return ResponseUtil.success(ctx, { record: deletedRecord }, "删除成功");
|
||||
return ResponseUtil.success(ctx, { record: softDeleted }, "删除成功");
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err.message);
|
||||
}
|
||||
|
||||
@@ -11,6 +11,12 @@ class HandlerHealthProfile {
|
||||
// 单页最大条数,避免 pageSize 传超大值一次拖库
|
||||
static MAX_PAGE_SIZE = 200;
|
||||
|
||||
// 单个账号可添加的就诊人数量上限
|
||||
static MAX_PROFILES_PER_USER = 20;
|
||||
|
||||
// 手机号:11 位大陆手机号
|
||||
static MOBILE_PATTERN = /^1[3-9]\d{9}$/;
|
||||
|
||||
// 解析分页参数并夹紧上限
|
||||
static parsePaging(query = {}) {
|
||||
const page = Math.max(1, parseInt(query.page) || 1);
|
||||
@@ -19,6 +25,40 @@ class HandlerHealthProfile {
|
||||
return { page, pageSize };
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验就诊人基本信息(只校验请求中出现的字段,未出现的沿用原值)
|
||||
* @param {Object} body 已按白名单挑出的请求体
|
||||
* @param {boolean} requireBase 新增时要求姓名与手机号必填
|
||||
* @returns {string|null} 不合规时返回提示文案
|
||||
*/
|
||||
static validateProfileInput(body, requireBase = false) {
|
||||
const name = body["profile.name"] ?? body.profile?.name;
|
||||
const mobile = body["profile.mobile"] ?? body.profile?.mobile;
|
||||
|
||||
if (requireBase || name !== undefined) {
|
||||
if (!String(name || "").trim()) return "请填写就诊人姓名";
|
||||
}
|
||||
if (requireBase || mobile !== undefined) {
|
||||
const value = String(mobile || "").trim();
|
||||
if (!HandlerHealthProfile.MOBILE_PATTERN.test(value)) return "请填写正确的就诊人手机号";
|
||||
}
|
||||
|
||||
const height = body["health.height"] ?? body.health?.height;
|
||||
if (height !== undefined && (Number(height) < 0 || Number(height) > 300)) {
|
||||
return "身高需在 0-300cm 之间";
|
||||
}
|
||||
const weight = body["health.weight"] ?? body.health?.weight;
|
||||
if (weight !== undefined && (Number(weight) < 0 || Number(weight) > 500)) {
|
||||
return "体重需在 0-500kg 之间";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按白名单挑选字段(支持 "profile.name" 这类点号路径)
|
||||
* @param {Object} body 请求体
|
||||
* @returns {Object}
|
||||
*/
|
||||
static pickFields(body) {
|
||||
const picked = {};
|
||||
for (const key of Object.keys(body || {})) {
|
||||
@@ -32,6 +72,18 @@ class HandlerHealthProfile {
|
||||
return picked;
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验失败统一转成 400:schema 校验错误直接抛给前端会暴露字段名与内部实现
|
||||
* @param {Object} ctx Koa 上下文
|
||||
* @param {Error} err 捕获到的异常
|
||||
*/
|
||||
static handleWriteError(ctx, err) {
|
||||
if (err?.name === "ValidationError") {
|
||||
return ResponseUtil.badRequest(ctx, "填写内容不合法,请检查身高、体重、性别等字段");
|
||||
}
|
||||
return ResponseUtil.internalError(ctx, err);
|
||||
}
|
||||
|
||||
async getProfiles(ctx) {
|
||||
try {
|
||||
const { userId, name, mobile, sortBy } = ctx.request.query;
|
||||
@@ -99,10 +151,24 @@ class HandlerHealthProfile {
|
||||
const body = HandlerHealthProfile.pickFields(ctx.request.body);
|
||||
body.userId = ctx.state.user?._id;
|
||||
|
||||
const invalid = HandlerHealthProfile.validateProfileInput(body, true);
|
||||
if (invalid) {
|
||||
return ResponseUtil.badRequest(ctx, invalid);
|
||||
}
|
||||
|
||||
// 每账号档案数量上限:防止被当作无限存储使用
|
||||
const count = await DBModel.HealthProfile.countDocuments({ userId: body.userId });
|
||||
if (count >= HandlerHealthProfile.MAX_PROFILES_PER_USER) {
|
||||
return ResponseUtil.badRequest(
|
||||
ctx,
|
||||
`最多可添加 ${HandlerHealthProfile.MAX_PROFILES_PER_USER} 位就诊人`
|
||||
);
|
||||
}
|
||||
|
||||
const newProfile = await DBModel.HealthProfile.createProfile(body);
|
||||
return ResponseUtil.success(ctx, { profile: newProfile }, "创建成功");
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err.message);
|
||||
return HandlerHealthProfile.handleWriteError(ctx, err);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -124,10 +190,15 @@ class HandlerHealthProfile {
|
||||
const update = HandlerHealthProfile.pickFields(ctx.request.body);
|
||||
delete update.userId; // 不允许通过请求转移档案归属
|
||||
|
||||
const invalid = HandlerHealthProfile.validateProfileInput(update);
|
||||
if (invalid) {
|
||||
return ResponseUtil.badRequest(ctx, invalid);
|
||||
}
|
||||
|
||||
const updatedProfile = await DBModel.HealthProfile.updateProfileById(id, update);
|
||||
return ResponseUtil.success(ctx, { profile: updatedProfile }, "更新成功");
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err.message);
|
||||
return HandlerHealthProfile.handleWriteError(ctx, err);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -153,6 +153,12 @@ const EscortRecordSchema = mongoose.Schema(
|
||||
cancelReason: { type: String, default: "", comment: "订单取消原因" },
|
||||
cancelledAt: { type: Date, default: null, comment: "订单取消时间" },
|
||||
|
||||
/**
|
||||
* 软删除标记:已支付/进行中/已完成的订单不允许物理删除(费用与服务记录需留存审计),
|
||||
* 管理员删除时打此标记,列表与详情默认过滤,历史数据不受影响
|
||||
*/
|
||||
deletedAt: { type: Date, default: null, comment: "软删除时间" },
|
||||
|
||||
/**
|
||||
* 元数据 - 系统管理信息
|
||||
*/
|
||||
@@ -182,9 +188,12 @@ const EscortRecordSchema = mongoose.Schema(
|
||||
* @returns {Promise<Array>} 陪诊记录列表(按预约日期倒序)
|
||||
*/
|
||||
EscortRecordSchema.statics.buildRecordFilter = function (options = {}) {
|
||||
const { status, userId, appointmentDate, healthProfileId } = options;
|
||||
const { status, userId, appointmentDate, healthProfileId, includeDeleted = false } = options;
|
||||
const filter = {};
|
||||
|
||||
// 软删除的订单默认不进入列表:数据库里保留审计,界面上视为已删除
|
||||
if (!includeDeleted) filter.deletedAt = null;
|
||||
|
||||
if (status && Array.isArray(status) && status.length > 0) {
|
||||
filter.status = { $in: status };
|
||||
}
|
||||
@@ -281,20 +290,26 @@ EscortRecordSchema.statics.createRecord = async function (record, cb) {
|
||||
*/
|
||||
EscortRecordSchema.statics.updateRecord = async function (id, update, cb) {
|
||||
const $set = { ...update, "meta.updatetime": Date.now() };
|
||||
return await this.findByIdAndUpdate(id, { $set }, { new: true, runValidators: true }, cb);
|
||||
// 已软删除的订单不可再被修改
|
||||
return await this.findOneAndUpdate(
|
||||
{ _id: id, deletedAt: null },
|
||||
{ $set },
|
||||
{ new: true, runValidators: true },
|
||||
cb
|
||||
);
|
||||
};
|
||||
|
||||
// 状态迁移必须仍以读取时的状态为条件,避免并发请求重复取消或跨过服务阶段。
|
||||
EscortRecordSchema.statics.updateRecordStatus = async function (id, fromStatus, update) {
|
||||
return await this.findOneAndUpdate(
|
||||
{ _id: id, status: fromStatus },
|
||||
{ _id: id, status: fromStatus, deletedAt: null },
|
||||
{ $set: { ...update, "meta.updatetime": Date.now() } },
|
||||
{ new: true, runValidators: true }
|
||||
);
|
||||
};
|
||||
|
||||
EscortRecordSchema.statics.findByIdempotencyKey = async function (userId, idempotencyKey) {
|
||||
return await this.findOne({ userId, idempotencyKey }).exec();
|
||||
return await this.findOne({ userId, idempotencyKey, deletedAt: null }).exec();
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -305,7 +320,8 @@ EscortRecordSchema.statics.findByIdempotencyKey = async function (userId, idempo
|
||||
* @returns {Promise<Object|null>} 陪诊记录,不存在返回null
|
||||
*/
|
||||
EscortRecordSchema.statics.findRecordById = async function (id, cb) {
|
||||
return await this.findById(id).exec(cb);
|
||||
// 软删除的订单按不存在处理
|
||||
return await this.findOne({ _id: id, deletedAt: null }).exec(cb);
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -39,8 +39,9 @@ const HealthProfileSchema = mongoose.Schema(
|
||||
|
||||
// 健康信息
|
||||
health: {
|
||||
height: { type: Number, default: 0, comment: "身高(cm)" },
|
||||
weight: { type: Number, default: 0, comment: "体重(kg)" },
|
||||
// 范围校验:0 表示未填写;非法值(负数、超大值)以前会被静默写入并影响下单展示
|
||||
height: { type: Number, min: 0, max: 300, default: 0, comment: "身高(cm)" },
|
||||
weight: { type: Number, min: 0, max: 500, default: 0, comment: "体重(kg)" },
|
||||
bloodType: { type: String, default: "", comment: "血型" },
|
||||
remark: { type: String, default: "", comment: "备注" },
|
||||
},
|
||||
@@ -165,11 +166,13 @@ HealthProfileSchema.statics.createProfile = async function (data) {
|
||||
|
||||
/**
|
||||
* 根据ID更新健康档案(更新姓名时同步拼音字段)
|
||||
* runValidators: 更新时同样校验 schema 约束(性别枚举、身高体重范围),
|
||||
* 否则非法值会绕过校验被静默写入
|
||||
*/
|
||||
HealthProfileSchema.statics.updateProfileById = async function (id, update) {
|
||||
syncPinyinOnUpdate(update);
|
||||
update["meta.updatetime"] = Date.now();
|
||||
return await this.findByIdAndUpdate(id, { $set: update }, { new: true }).exec();
|
||||
return await this.findByIdAndUpdate(id, { $set: update }, { new: true, runValidators: true }).exec();
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -178,7 +181,7 @@ HealthProfileSchema.statics.updateProfileById = async function (id, update) {
|
||||
HealthProfileSchema.statics.updateProfile = async function (userId, update) {
|
||||
syncPinyinOnUpdate(update);
|
||||
update["meta.updatetime"] = Date.now();
|
||||
return await this.findOneAndUpdate({ userId }, { $set: update }, { new: true }).exec();
|
||||
return await this.findOneAndUpdate({ userId }, { $set: update }, { new: true, runValidators: true }).exec();
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* 陪诊订单状态机(HTTP 接口与管理端 Agent 工具共用同一份规则)
|
||||
*
|
||||
* 之前 Agent 的 escort_record_set 直接改 status,绕过了接口层的迁移校验,
|
||||
* 可以把已完成订单改回进行中。规则集中在这里,任何入口都必须走 canTransition。
|
||||
*/
|
||||
|
||||
// 允许的状态迁移;终态不可再变
|
||||
const STATUS_TRANSITIONS = {
|
||||
pending: ["confirmed", "cancelled"],
|
||||
confirmed: ["in_progress", "cancelled"],
|
||||
in_progress: ["completed"],
|
||||
completed: [],
|
||||
cancelled: [],
|
||||
};
|
||||
|
||||
/**
|
||||
* 判断状态迁移是否允许
|
||||
* @param {string} from 当前状态
|
||||
* @param {string} to 目标状态
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function canTransition(from, to) {
|
||||
return (STATUS_TRANSITIONS[from] || []).includes(to);
|
||||
}
|
||||
|
||||
export { STATUS_TRANSITIONS, canTransition };
|
||||
+19
-3
@@ -1,6 +1,11 @@
|
||||
import logger from "./logger.js";
|
||||
|
||||
/**
|
||||
* 响应工具类
|
||||
* 提供统一的响应格式
|
||||
*
|
||||
* 约定(与小程序端保持一致):业务状态一律走 body.code,HTTP 状态码固定 200;
|
||||
* 同时把 code 写进 X-Biz-Code 响应头,便于 nginx/监控按业务码告警而不必解析响应体。
|
||||
*/
|
||||
class ResponseUtil {
|
||||
/**
|
||||
@@ -11,6 +16,7 @@ class ResponseUtil {
|
||||
*/
|
||||
static success(ctx, data, message = '操作成功') {
|
||||
ctx.status = 200;
|
||||
ctx.set('X-Biz-Code', '0');
|
||||
ctx.body = {
|
||||
code: 0,
|
||||
msg: message,
|
||||
@@ -28,6 +34,7 @@ class ResponseUtil {
|
||||
static error(ctx, message, data = null, errorCode = 500) {
|
||||
// 根据规则,只要进入controller,http状态码都是200
|
||||
ctx.status = 200;
|
||||
ctx.set('X-Biz-Code', String(errorCode));
|
||||
ctx.body = {
|
||||
code: errorCode,
|
||||
msg: message,
|
||||
@@ -74,11 +81,20 @@ class ResponseUtil {
|
||||
|
||||
/**
|
||||
* 服务器内部错误响应
|
||||
*
|
||||
* 详细原因只进日志:err.message 可能包含 Mongo 连接串、字段名、堆栈等内部信息,
|
||||
* 直接回传等于把服务端实现细节暴露给前端/攻击者。
|
||||
*
|
||||
* @param {Object} ctx - Koa上下文对象
|
||||
* @param {string} message - 错误消息
|
||||
* @param {string|Error} detail - 内部错误详情(仅用于日志)
|
||||
* @param {Object} data - 附加数据
|
||||
*/
|
||||
static internalError(ctx, message = '服务器内部错误', data = null) {
|
||||
return ResponseUtil.error(ctx, message, data, 500);
|
||||
static internalError(ctx, detail = null, data = null) {
|
||||
if (detail) {
|
||||
const text = detail instanceof Error ? detail.stack : String(detail);
|
||||
logger.error(`[internal] ${ctx.method} ${ctx.path}: ${text}`);
|
||||
}
|
||||
return ResponseUtil.error(ctx, '服务器繁忙,请稍后重试', data, 500);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user