import mongoose from "mongoose"; import { DBModel } from "../models/index.js"; import ResponseUtil from "../utils/responseUtil.js"; class HandlerHealthProfile { constructor() { } // 白名单:只允许写入 schema 定义的顶层字段(兼容 'profile.name' 等点号路径) static PROFILE_FIELDS = ["userId", "profile", "location", "health"]; // 单页最大条数,避免 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); const rawSize = parseInt(query.pageSize) || 20; const pageSize = Math.min(Math.max(1, rawSize), HandlerHealthProfile.MAX_PAGE_SIZE); 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 之间"; } // 归属用户:管理端代客建档时传入,必须是合法 ObjectId。 // 空串/不传表示未绑定(历史数据),C 端 /mine 系列不走这里,其 userId 取自 token if (body.userId !== undefined && body.userId !== null && body.userId !== "") { if (!mongoose.Types.ObjectId.isValid(body.userId)) { return "归属用户ID不合法"; } } return null; } /** * 按白名单挑选字段(支持 "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, { flatten = false } = {}) { const picked = {}; 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; } /** * 校验失败统一转成 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; const { page, pageSize } = HandlerHealthProfile.parsePaging(ctx.request.query); const result = await DBModel.HealthProfile.findProfiles({ page, pageSize, userId, name, mobile, sortBy, }); return ResponseUtil.success(ctx, result, "查询成功"); } catch (err) { return ResponseUtil.internalError(ctx, err); } } /** * 管理端批量统计就诊人数量 * * 用户列表页一屏最多 200 个用户,逐个查会产生 N+1; * 这里按 userIds 一次聚合,未建档用户返回 0。 */ async getProfileCounts(ctx) { try { const raw = String(ctx.request.query.userIds || ""); const ids = [...new Set(raw.split(",").map((id) => id.trim()).filter(Boolean))]; if (ids.length > HandlerHealthProfile.MAX_PAGE_SIZE) { return ResponseUtil.badRequest(ctx, `单次最多查询 ${HandlerHealthProfile.MAX_PAGE_SIZE} 位用户`); } if (!ids.length) { return ResponseUtil.success(ctx, { counts: {} }, "查询成功"); } const invalid = ids.filter((id) => !mongoose.Types.ObjectId.isValid(id)); if (invalid.length) { return ResponseUtil.badRequest(ctx, "用户ID不合法"); } const rows = await DBModel.HealthProfile.aggregate([ { $match: { userId: { $in: ids.map((id) => new mongoose.Types.ObjectId(id)) } } }, { $group: { _id: "$userId", count: { $sum: 1 } } }, ]).exec(); const counts = Object.fromEntries(ids.map((id) => [id, 0])); for (const row of rows) { counts[String(row._id)] = row.count; } return ResponseUtil.success(ctx, { counts }, "查询成功"); } catch (err) { return ResponseUtil.internalError(ctx, err); } } // 查询"我的"健康档案列表:强制以登录用户身份查询,忽略请求中的 userId async getMyProfiles(ctx) { try { const { name, mobile, sortBy } = ctx.request.query; const { page, pageSize } = HandlerHealthProfile.parsePaging(ctx.request.query); const userId = ctx.state.user?._id; const result = await DBModel.HealthProfile.findProfiles({ page, pageSize, userId, name, mobile, sortBy, }); return ResponseUtil.success(ctx, result, "查询成功"); } catch (err) { return ResponseUtil.internalError(ctx, err); } } // 查询"我的"单个健康档案:非本人档案一律按不存在处理 async getMyProfileById(ctx) { try { const { id } = ctx.params; if (!id) { return ResponseUtil.badRequest(ctx, "缺少档案ID"); } const profile = await HandlerHealthProfile.findOwnProfile(ctx, id); if (!profile) { return ResponseUtil.notFound(ctx, "健康档案不存在"); } return ResponseUtil.success(ctx, { profile }, "查询成功"); } catch (err) { return ResponseUtil.internalError(ctx, err); } } // 新增"我的"健康档案:userId 以 token 为准,避免写到他人名下 async createMyProfile(ctx) { try { 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 HandlerHealthProfile.handleWriteError(ctx, err); } } // 更新"我的"健康档案:先校验归属,再更新 // 注意:入参使用 "profile.name" 这类点号路径, // 因为 schema 在更新姓名时会额外写入 "profile.pinyin",与整体替换 profile 对象会冲突 async updateMyProfile(ctx) { try { const { id } = ctx.params; if (!id) { return ResponseUtil.badRequest(ctx, "缺少档案ID"); } const profile = await HandlerHealthProfile.findOwnProfile(ctx, id); if (!profile) { return ResponseUtil.notFound(ctx, "健康档案不存在"); } const update = HandlerHealthProfile.pickFields(ctx.request.body, { flatten: true }); 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 HandlerHealthProfile.handleWriteError(ctx, err); } } // 删除"我的"健康档案:先校验归属,再删除 async deleteMyProfile(ctx) { try { const { id } = ctx.params; if (!id) { return ResponseUtil.badRequest(ctx, "缺少档案ID"); } const profile = await HandlerHealthProfile.findOwnProfile(ctx, id); if (!profile) { return ResponseUtil.notFound(ctx, "健康档案不存在"); } await DBModel.HealthProfile.deleteProfileById(id); return ResponseUtil.success(ctx, { profile }, "删除成功"); } catch (err) { return ResponseUtil.internalError(ctx, err); } } // 按 id 查找档案并校验归属,非本人档案返回 null static async findOwnProfile(ctx, id) { const profile = await DBModel.HealthProfile.findProfileById(id); const userId = ctx.state.user?._id; if (!profile || String(profile.userId) !== String(userId)) { return null; } return profile; } async getProfileById(ctx) { try { const { id } = ctx.params; if (!id) { return ResponseUtil.badRequest(ctx, "缺少档案ID"); } const profile = await DBModel.HealthProfile.findProfileById(id); if (!profile) { return ResponseUtil.notFound(ctx, "健康档案不存在"); } return ResponseUtil.success(ctx, { profile }, "查询成功"); } catch (err) { return ResponseUtil.internalError(ctx, err); } } async createProfile(ctx) { try { const body = ctx.request.body; const newProfile = await DBModel.HealthProfile.createProfile(HandlerHealthProfile.pickFields(body)); return ResponseUtil.success(ctx, { profile: newProfile }, "创建成功"); } catch (err) { return ResponseUtil.internalError(ctx, err); } } async updateProfile(ctx) { try { const { id } = ctx.params; const update = ctx.request.body; if (!id) { return ResponseUtil.badRequest(ctx, "缺少档案ID"); } const updatedProfile = await DBModel.HealthProfile.updateProfileById( id, HandlerHealthProfile.pickFields(update, { flatten: true }) ); if (!updatedProfile) { return ResponseUtil.notFound(ctx, "健康档案不存在"); } return ResponseUtil.success(ctx, { profile: updatedProfile }, "更新成功"); } catch (err) { return ResponseUtil.internalError(ctx, err); } } async deleteProfile(ctx) { try { const { id } = ctx.params; if (!id) { return ResponseUtil.badRequest(ctx, "缺少档案ID"); } const deletedProfile = await DBModel.HealthProfile.deleteProfileById(id); if (!deletedProfile) { return ResponseUtil.notFound(ctx, "健康档案不存在"); } return ResponseUtil.success(ctx, { profile: deletedProfile }, "删除成功"); } catch (err) { return ResponseUtil.internalError(ctx, err); } } } export { HandlerHealthProfile };