diff --git a/app.js b/app.js index f6890e1..c43d258 100644 --- a/app.js +++ b/app.js @@ -1,25 +1,30 @@ import Koa from 'koa'; import bodyParser from 'koa-bodyparser'; import cors from 'koa-cors'; +import mount from 'koa-mount'; +import serve from 'koa-static'; import http from 'http'; +import { fileURLToPath } from 'url'; import { DBModel } from './models/index.js'; import registerRoutes from './routes/index.js'; import ResponseUtil from './utils/responseUtil.js'; -// 语音/图片识别走 base64 JSON,单请求体可能达到数 MB; -// 只对该前缀放宽解析上限,其余接口维持 1MB,避免全局放大内存占用 -const MEDIA_ROUTE_PREFIX = '/health/ai/'; +const STATIC_DIR = fileURLToPath(new URL('./statics', import.meta.url)); + +// 语音/图片识别与培训报名材料走 base64 JSON,单请求体可能达到数 MB; +// 只对这些前缀放宽解析上限,其余接口维持 1MB,避免全局放大内存占用 +const LARGE_BODY_PREFIXES = ['/health/ai/', '/health/training-application']; const DEFAULT_BODY_LIMIT = '1mb'; -const MEDIA_BODY_LIMIT = '20mb'; +const LARGE_BODY_LIMIT = '20mb'; const defaultBodyParser = bodyParser({ jsonLimit: DEFAULT_BODY_LIMIT, formLimit: DEFAULT_BODY_LIMIT, textLimit: DEFAULT_BODY_LIMIT, }); -const mediaBodyParser = bodyParser({ - jsonLimit: MEDIA_BODY_LIMIT, - formLimit: MEDIA_BODY_LIMIT, - textLimit: MEDIA_BODY_LIMIT, +const largeBodyParser = bodyParser({ + jsonLimit: LARGE_BODY_LIMIT, + formLimit: LARGE_BODY_LIMIT, + textLimit: LARGE_BODY_LIMIT, }); class APP { @@ -41,10 +46,11 @@ class APP { this.app.proxy = true; this.app.proxyIpHeader = "X-Real-IP"; + this.app.use(mount('/static', serve(STATIC_DIR))); this.app.use(cors()); this.app.use((ctx, next) => { - const parser = ctx.path.startsWith(MEDIA_ROUTE_PREFIX) - ? mediaBodyParser + const parser = LARGE_BODY_PREFIXES.some((prefix) => ctx.path.startsWith(prefix)) + ? largeBodyParser : defaultBodyParser; return parser(ctx, next); }); diff --git a/handler/training_application.js b/handler/training_application.js new file mode 100644 index 0000000..35582ba --- /dev/null +++ b/handler/training_application.js @@ -0,0 +1,164 @@ +import ResponseUtil from "../utils/responseUtil.js"; +import { DBModel } from "../models/index.js"; + +const EDUCATION_OPTIONS = ["初中及以下", "高中/中专", "大专", "本科", "硕士及以上"]; +const MOBILE_REGEX = /^1[3-9]\d{9}$/; +const ID_NUMBER_REGEX = /^\d{17}[\dXx]$/; +const EXAM_MONTH_REGEX = /^2026-(0[1-9]|1[0-2])$/; +const MAX_IMAGE_BYTES = 5 * 1024 * 1024; +const DUPLICATE_WINDOW_MS = 24 * 60 * 60 * 1000; +const STATUS_VALUES = ["pending", "contacted", "enrolled", "cancelled"]; +const MAX_PAGE_SIZE = 200; + +const COURSE = { + name: "医疗陪诊顾问(高级)", + issuer: "国家开放大学培训中心", +}; + +class HandlerTrainingApplication { + // 报名回执不携带身份证号与图片,避免在客户端重复暴露敏感信息 + static toPublic(doc) { + if (!doc) return null; + const year = Number(doc.exam?.year) || 2026; + const month = Number(doc.exam?.month) || 0; + return { + id: doc._id, + applicant: { + name: doc.applicant?.name || "", + mobile: doc.applicant?.mobile || "", + education: doc.applicant?.education || "", + }, + examMonth: month ? `${year}-${String(month).padStart(2, "0")}` : "", + course: { + name: doc.course?.name || COURSE.name, + issuer: doc.course?.issuer || COURSE.issuer, + }, + status: doc.status || "pending", + createtime: doc.meta?.createtime || null, + }; + } + + // 只接受 jpeg/png 的 data URL;同时检查文件签名和原始大小, + // 防止把任意 base64 文本当作报名材料写入数据库 + static parseImage(input, label) { + 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` }; + } + + const isJpeg = buffer.length > 2 && buffer[0] === 0xff && buffer[1] === 0xd8; + const isPng = buffer.length > 8 && buffer.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])); + if ((mime === "image/jpeg" && !isJpeg) || (mime === "image/png" && !isPng)) { + return { error: `${label}格式不正确` }; + } + + return { value: { data: raw, mime } }; + } + + static parsePayload(body = {}) { + const applicant = body.applicant || {}; + const name = String(applicant.name || "").trim(); + const idNumber = String(applicant.idNumber || "").trim().toUpperCase(); + const mobile = String(applicant.mobile || "").trim(); + const education = String(applicant.education || "").trim(); + const examMonth = String(body.examMonth || "").trim(); + + if (!name) return { error: "请填写姓名" }; + if (name.length > 20) return { error: "姓名不能超过 20 个字" }; + if (!ID_NUMBER_REGEX.test(idNumber)) return { error: "请填写 18 位身份证号,末位可为 X" }; + if (!MOBILE_REGEX.test(mobile)) return { error: "请填写正确的 11 位手机号" }; + if (!EDUCATION_OPTIONS.includes(education)) return { error: "请选择学历" }; + if (!EXAM_MONTH_REGEX.test(examMonth)) return { error: "请选择 2026 年的考试月份" }; + + const photo = HandlerTrainingApplication.parseImage(body.materials?.photo, "2寸蓝底照片"); + if (photo.error) return photo; + const idCard = HandlerTrainingApplication.parseImage(body.materials?.idCard, "身份证电子版"); + if (idCard.error) return idCard; + + return { + value: { + applicant: { name, idNumber, mobile, education }, + exam: { year: 2026, month: Number(examMonth.slice(5)) }, + materials: { photo: photo.value, idCard: idCard.value }, + course: { ...COURSE }, + }, + }; + } + + async createApplication(ctx) { + try { + const userId = ctx.state.user?._id; + if (!userId) return ResponseUtil.unauthorized(ctx, "登录已失效"); + + const result = HandlerTrainingApplication.parsePayload(ctx.request.body); + if (result.error) return ResponseUtil.badRequest(ctx, result.error); + + const existing = await DBModel.TrainingApplication.findRecentActiveByUser( + userId, + Date.now() - DUPLICATE_WINDOW_MS + ); + if (existing) { + return ResponseUtil.success( + ctx, + { application: HandlerTrainingApplication.toPublic(existing), duplicated: true }, + "你已提交过报名,客服会尽快联系你" + ); + } + + const application = await DBModel.TrainingApplication.createApplication({ + userId, + ...result.value, + }); + + return ResponseUtil.success( + ctx, + { application: HandlerTrainingApplication.toPublic(application) }, + "报名提交成功" + ); + } 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.TrainingApplication.findLatestByUser(userId); + return ResponseUtil.success( + ctx, + { application: HandlerTrainingApplication.toPublic(application) }, + "查询成功" + ); + } catch (err) { + return ResponseUtil.internalError(ctx, err); + } + } + + async getApplications(ctx) { + try { + const { status } = ctx.request.query; + if (status && !STATUS_VALUES.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.TrainingApplication.findApplicationPage({ page, pageSize, status }); + return ResponseUtil.success(ctx, { ...result, page, pageSize }, "查询成功"); + } catch (err) { + return ResponseUtil.internalError(ctx, err); + } + } +} + +export { HandlerTrainingApplication }; diff --git a/models/index.js b/models/index.js index ab41e90..dc93773 100644 --- a/models/index.js +++ b/models/index.js @@ -6,6 +6,7 @@ import { HealthProfileSchema } from "./schema/health_profile.js" import { OrganizationSchema } from "./schema/organization.js" import { EmployeeSchema } from "./schema/employee.js" import { EmployeeReviewSchema } from "./schema/employee_review.js" +import { TrainingApplicationSchema } from "./schema/training_application.js" import config from '../config.js'; import logger from '../utils/logger.js'; @@ -18,6 +19,7 @@ class MongoDBSchema { this.Employee = null; this.HealthProfile = null; this.EmployeeReview = null; + this.TrainingApplication = null; } init() { @@ -48,6 +50,7 @@ class MongoDBSchema { this.Organization = this.dbConnection.model('organization', OrganizationSchema) this.Employee = this.dbConnection.model('employee', EmployeeSchema) this.EmployeeReview = this.dbConnection.model('employee_review', EmployeeReviewSchema) + this.TrainingApplication = this.dbConnection.model('training_application', TrainingApplicationSchema) } } diff --git a/models/schema/training_application.js b/models/schema/training_application.js new file mode 100644 index 0000000..f08aa5f --- /dev/null +++ b/models/schema/training_application.js @@ -0,0 +1,134 @@ +"use strict"; + +import mongoose from "mongoose"; + +/** + * TrainingApplication Schema + * 2026 年国开培训中心「医疗陪诊(高级)」考位报名。 + * + * 证书口径:颁发主体是国家开放大学培训中心,本报名只采集考位信息, + * 不表示职业资格证书或就业承诺。照片与身份证电子版仅用于报名和办证, + * 查询列表时默认不返回,避免在列表接口中反复传输敏感大图。 + */ +const TrainingApplicationSchema = mongoose.Schema( + { + userId: { + type: mongoose.Schema.Types.ObjectId, + ref: "user", + required: true, + index: true, + comment: "报名用户ID", + }, + + applicant: { + name: { type: String, required: true, trim: true, maxlength: 20, comment: "姓名" }, + idNumber: { + type: String, + required: true, + trim: true, + uppercase: true, + match: /^\d{17}[\dX]$/, + comment: "身份证号", + }, + mobile: { type: String, required: true, trim: true, comment: "手机号" }, + education: { + type: String, + required: true, + enum: ["初中及以下", "高中/中专", "大专", "本科", "硕士及以上"], + comment: "学历", + }, + }, + + // 2026 年考位:前端只允许选择 2026-01 至 2026-12 + exam: { + year: { type: Number, default: 2026, min: 2026, max: 2026, comment: "考试年份" }, + month: { type: Number, required: true, min: 1, max: 12, comment: "考试月份" }, + }, + + // 图片以 data URL 落库;每张原图服务端限制 5MB。 + // 列表查询使用 .select('-materials'),只有后续确需办证查看时才单独读取 + materials: { + photo: { + data: { type: String, required: true, comment: "2寸蓝底照片 data URL" }, + mime: { type: String, enum: ["image/jpeg", "image/png"], required: true }, + }, + idCard: { + data: { type: String, required: true, comment: "身份证电子版 data URL" }, + mime: { type: String, enum: ["image/jpeg", "image/png"], required: true }, + }, + }, + + course: { + name: { type: String, default: "医疗陪诊顾问(高级)", comment: "报考项目" }, + issuer: { type: String, default: "国家开放大学培训中心", comment: "颁发机构" }, + }, + + status: { + type: String, + enum: ["pending", "contacted", "enrolled", "cancelled"], + default: "pending", + index: true, + comment: "pending 待审核 / contacted 已联系 / enrolled 已入班 / cancelled 已取消", + }, + + meta: { + createtime: { type: Number, default: () => Date.now(), comment: "创建时间" }, + updatetime: { type: Number, default: () => Date.now(), comment: "更新时间" }, + }, + }, + { + minimize: false, + strict: true, + collection: "training_application", + timestamps: false, + } +); + +TrainingApplicationSchema.statics.createApplication = async function (data) { + data.meta = { createtime: Date.now(), updatetime: Date.now() }; + const doc = new this(data); + return await doc.save(); +}; + +TrainingApplicationSchema.statics.findLatestByUser = async function (userId) { + return await this.findOne({ userId }) + .select("-materials") + .sort({ "meta.createtime": -1 }) + .exec(); +}; + +// 拦截短时间内的重复提交;已取消的报名不阻挡用户重新报名 +TrainingApplicationSchema.statics.findRecentActiveByUser = async function (userId, since) { + return await this.findOne({ + userId, + status: { $ne: "cancelled" }, + "meta.createtime": { $gte: since }, + }) + .select("-materials") + .sort({ "meta.createtime": -1 }) + .exec(); +}; + +TrainingApplicationSchema.statics.findApplicationPage = async function (options = {}) { + const { page = 1, pageSize = 20, status } = options; + const filter = {}; + if (status) filter.status = status; + + const skip = (page - 1) * pageSize; + const [applications, total] = await Promise.all([ + this.find(filter) + .select("-materials") + .sort({ "meta.createtime": -1 }) + .skip(skip) + .limit(pageSize) + .exec(), + this.countDocuments(filter).exec(), + ]); + + return { applications, total }; +}; + +TrainingApplicationSchema.index({ userId: 1, "meta.createtime": -1 }); +TrainingApplicationSchema.index({ status: 1, "meta.createtime": -1 }); + +export { TrainingApplicationSchema }; diff --git a/package-lock.json b/package-lock.json index b5dea4a..136c677 100644 --- a/package-lock.json +++ b/package-lock.json @@ -22,7 +22,9 @@ "koa": "^2.16.4", "koa-bodyparser": "^4.4.1", "koa-cors": "^0.0.16", + "koa-mount": "^4.2.0", "koa-router": "^12.0.1", + "koa-static": "^5.0.0", "langchain": "^1.5.10", "lodash": "^4.18.1", "lunar-javascript": "^1.7.7", @@ -1918,6 +1920,19 @@ "integrity": "sha512-s15knPxe3AJBi2I/ZMPL0pSqU+PLYLO6k5tI0AqClkzavowvocPlSdFUwaHNqtjHMhsGmiq2tiX/25iILJx9YA==", "license": "MIT" }, + "node_modules/koa-mount": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/koa-mount/-/koa-mount-4.2.0.tgz", + "integrity": "sha512-2iHQc7vbA9qLeVq5gKAYh3m5DOMMlMfIKjW/REPAS18Mf63daCJHHVXY9nbu7ivrnYn5PiPC4CE523Tf5qvjeQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.0.1", + "koa-compose": "^4.1.0" + }, + "engines": { + "node": ">= 7.6.0" + } + }, "node_modules/koa-router": { "version": "12.0.1", "resolved": "https://registry.npmmirror.com/koa-router/-/koa-router-12.0.1.tgz", @@ -1964,6 +1979,42 @@ "node": ">= 0.8" } }, + "node_modules/koa-send": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/koa-send/-/koa-send-5.0.1.tgz", + "integrity": "sha512-tmcyQ/wXXuxpDxyNXv5yNNkdAMdFRqwtegBXUaowiQzUKqJehttS0x2j0eOZDQAyloAth5w6wwBImnFzkUz3pQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.1.1", + "http-errors": "^1.7.3", + "resolve-path": "^1.4.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/koa-static": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/koa-static/-/koa-static-5.0.0.tgz", + "integrity": "sha512-UqyYyH5YEXaJrf9S8E23GoJFQZXkBVJ9zYYMPGz919MSX1KuvAcycIuS0ci150HCoPf4XQVhQ84Qf8xRPWxFaQ==", + "license": "MIT", + "dependencies": { + "debug": "^3.1.0", + "koa-send": "^5.0.0" + }, + "engines": { + "node": ">= 7.6.0" + } + }, + "node_modules/koa-static/node_modules/debug": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", + "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.1" + } + }, "node_modules/kuler": { "version": "2.0.0", "resolved": "https://registry.npmmirror.com/kuler/-/kuler-2.0.0.tgz", @@ -2752,6 +2803,55 @@ "node": ">=8.10.0" } }, + "node_modules/resolve-path": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/resolve-path/-/resolve-path-1.4.0.tgz", + "integrity": "sha512-i1xevIst/Qa+nA9olDxLWnLk8YZbi8R/7JPbCMcgyWaFR6bKWaexgJgEB5oc2PKMjYdrHynyz0NY+if+H98t1w==", + "license": "MIT", + "dependencies": { + "http-errors": "~1.6.2", + "path-is-absolute": "1.0.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/resolve-path/node_modules/depd": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz", + "integrity": "sha512-7emPTl6Dpo6JRXOXjLRxck+FlLRX5847cLKEn00PLAgc3g2hTZZgr+e4c2v6QpSmLeFP3n5yUo7ft6avBK/5jQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/resolve-path/node_modules/http-errors": { + "version": "1.6.3", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.6.3.tgz", + "integrity": "sha512-lks+lVC8dgGyh97jxvxeYTWQFvh4uw4yC12gVl63Cg30sjPX4wuGcdkICVXDAESr6OJGjqGA8Iz5mkeN6zlD7A==", + "license": "MIT", + "dependencies": { + "depd": "~1.1.2", + "inherits": "2.0.3", + "setprototypeof": "1.1.0", + "statuses": ">= 1.4.0 < 2" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/resolve-path/node_modules/inherits": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", + "integrity": "sha512-x00IRNXNy63jwGkJmzPigoySHbaqpNuzKbBOmzK+g2OdZpQ9w+sxCN+VSB3ja7IAge2OP2qpfxTjeNcyjmW1uw==", + "license": "ISC" + }, + "node_modules/resolve-path/node_modules/setprototypeof": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.1.0.tgz", + "integrity": "sha512-BvE/TwpZX4FXExxOxZyRGQQv651MSwmWKZGqvmPcRIjDqWub67kTKuIMx43cZZrS/cBBzwBcNDWoFxt2XEFIpQ==", + "license": "ISC" + }, "node_modules/reusify": { "version": "1.1.0", "resolved": "https://registry.npmmirror.com/reusify/-/reusify-1.1.0.tgz", diff --git a/package.json b/package.json index a374a24..8975f6d 100644 --- a/package.json +++ b/package.json @@ -24,7 +24,9 @@ "koa": "^2.16.4", "koa-bodyparser": "^4.4.1", "koa-cors": "^0.0.16", + "koa-mount": "^4.2.0", "koa-router": "^12.0.1", + "koa-static": "^5.0.0", "langchain": "^1.5.10", "lodash": "^4.18.1", "lunar-javascript": "^1.7.7", diff --git a/routes/index.js b/routes/index.js index caff390..fbf30fd 100644 --- a/routes/index.js +++ b/routes/index.js @@ -4,6 +4,7 @@ import { HandlerHealthProfile } from "../handler/health_profile.js"; import { HandlerResource } from "../handler/resource.js"; import { HandlerEmployee } from "../handler/employee.js"; import { HandlerAIMedia } from "../handler/ai_media.js"; +import { HandlerTrainingApplication } from "../handler/training_application.js"; import ResponseUtil from "../utils/responseUtil.js"; import { getUserByToken } from "../utils/user_service.js"; import { isAdmin } from "../utils/permissions.js"; @@ -77,6 +78,7 @@ function registerRoutes(app) { const handlerResource = new HandlerResource(); const handlerEmployee = new HandlerEmployee(); const handlerAIMedia = new HandlerAIMedia(); + const handlerTrainingApplication = new HandlerTrainingApplication(); // 敏感数据路由需要登录后访问 router.get("/escort-record/my", requireAuth, handlerEscortRecord.getMyRecords.bind(handlerEscortRecord)); @@ -96,6 +98,13 @@ function registerRoutes(app) { router.put("/health-profile/mine/:id", requireAuth, updateLimit, handlerHealthProfile.updateMyProfile.bind(handlerHealthProfile)); router.delete("/health-profile/mine/:id", requireAuth, deleteLimit, handlerHealthProfile.deleteMyProfile.bind(handlerHealthProfile)); + // 陪诊师培训考证报名:C 端只能给自己报名,userId 取自 token; + // 写接口与下单共用 createLimit,避免重复提交刷出多条报名 + router.post("/training-application", requireAuth, createLimit, handlerTrainingApplication.createApplication.bind(handlerTrainingApplication)); + router.get("/training-application/mine", requireAuth, handlerTrainingApplication.getMyApplication.bind(handlerTrainingApplication)); + // 管理端报名列表必须管理员 + router.get("/training-application", requireAuth, requireAdmin, handlerTrainingApplication.getApplications.bind(handlerTrainingApplication)); + // 以下为管理端档案接口(C 端一律走 /mine),必须管理员 router.get("/health-profile", requireAuth, requireAdmin, handlerHealthProfile.getProfiles.bind(handlerHealthProfile)); router.get("/health-profile/:id", requireAuth, requireAdmin, handlerHealthProfile.getProfileById.bind(handlerHealthProfile)); diff --git a/statics/certificate_sample.jpg b/statics/certificate_sample.jpg new file mode 100644 index 0000000..10c48e8 Binary files /dev/null and b/statics/certificate_sample.jpg differ