feat(attendant): 入驻免身份证材料、城市单选、材料后补与订单池同城过滤

入驻申请只收基本信息(身份证选填、材料全可空),服务城市改为单选白名单(北京/上海/天津/西安,默认北京);新增 POST /attendant-application/mine/materials 材料后补与 PATCH /employee/me/service-area 改城市接口;订单池按陪诊师服务城市过滤(本人已接/被共享不限城市),接单与详情二次校验;appId wxapp-escort-admin 更名为 wxapp_companion。
This commit is contained in:
lik
2026-11-10 16:33:47 +08:00
parent 3086a40b4c
commit cd3b109730
14 changed files with 522 additions and 84 deletions
+166 -55
View File
@@ -3,14 +3,14 @@ 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";
import { SERVICE_AREAS } from "../resource/services.js";
import logger from "../utils/logger.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;
// 岗位中文名:仅用于冲突提示文案。岗位变更本身由管理员在后台显式操作,
// 入驻审批不改写已有非陪诊师档案(产品口径:拒绝改写,走人工)
@@ -96,17 +96,19 @@ class HandlerAttendantApplication {
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 (idNumber && !ID_NUMBER_REGEX.test(idNumber)) {
return { error: "请填写 18 位身份证号,末位可为 X" };
}
if (sex && !["male", "female"].includes(sex)) return { error: "性别取值不正确" };
// 服务城市单选,且必须来自服务目录白名单
if (serviceAreas.length !== 1) return { error: "请选择一个服务城市" };
if (!SERVICE_AREAS.includes(serviceAreas[0])) return { error: "服务城市不在可选范围" };
if (introduction.length > INTRODUCTION_MAX) {
return { error: `个人简介不能超过 ${INTRODUCTION_MAX} 个字` };
}
// 证件材料允许后补:未上传时保留空值,有上一份材料则沿用
const qualification = body.materials?.qualification
? HandlerTrainingApplication.parseImage(
body.materials.qualification,
@@ -115,8 +117,8 @@ class HandlerAttendantApplication {
)
: fallback?.qualification?.data
? { value: { data: fallback.qualification.data, mime: fallback.qualification.mime } }
: { error: "请上传资质证书照片" };
if (qualification.error) return qualification;
: null;
if (qualification?.error) return qualification;
const healthPhoto = body.materials?.healthCertificate
? HandlerTrainingApplication.parseImage(
@@ -131,32 +133,45 @@ class HandlerAttendantApplication {
mime: fallback.healthCertificate.mime,
},
}
: { error: "请上传健康证明照片" };
if (healthPhoto.error) return healthPhoto;
: null;
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: "健康证明已过期,请更新后再提交" };
const inputExpireDate = HandlerAttendantApplication.parseDate(body.healthExpireDate);
if (body.healthExpireDate && !inputExpireDate) {
return { error: "健康证明有效期格式不正确" };
}
// 只校验本次提交的日期,不沿用上一份的健康证有效期:
// 驳回重提的表单已没有日期输入,沿用旧日期会让过期的历史申请永远无法重新提交;
// 照片仍沿用 fallback,日期可在审核通过后经材料补传接口更新
const expireDate = inputExpireDate;
if (expireDate) {
// 过期健康证无法支撑"公示有效期",填了就挡在提交环节。
// 到期当天仍算有效(与公示侧 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: "健康证明已过期,请更新后再提交" };
}
const materials = {};
if (qualification) materials.qualification = qualification.value;
if (healthPhoto || expireDate) {
materials.healthCertificate = {};
if (healthPhoto) Object.assign(materials.healthCertificate, healthPhoto.value);
if (expireDate) materials.healthCertificate.expireDate = expireDate;
}
const applicantValue = { name, mobile, sex, serviceAreas, introduction };
if (idNumber) applicantValue.idNumber = idNumber;
return {
value: {
applicant: { name, mobile, idNumber, sex, serviceAreas, introduction },
materials: {
qualification: qualification.value,
healthCertificate: { ...healthPhoto.value, expireDate },
},
applicant: applicantValue,
materials,
},
};
}
@@ -208,12 +223,13 @@ class HandlerAttendantApplication {
"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 || "",
};
// 身份证选填:没填就不写,避免空串占用唯一索引
if (doc.applicant?.idNumber) patch["profile.idNumber"] = doc.applicant.idNumber;
const expireDate = doc.materials?.healthCertificate?.expireDate;
if (expireDate) patch["work.healthCertificate.expireDate"] = expireDate;
@@ -328,15 +344,15 @@ class HandlerAttendantApplication {
);
}
// 弱校验:正常流程用户都从小程序进来,user 记录里会有 wxapp-escort-admin 条目。
// 弱校验:正常流程用户都从小程序进来,user 记录里会有 wxapp_companion 条目。
// 缺失多半是历史账号或接口直调,只告警不阻断,避免误伤老用户
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"]);
(Array.isArray(user?.apps) && user.apps.some((m) => m?.appId === "wxapp_companion")) ||
Boolean(user?.app?.["wxapp_companion"]);
if (!enteredAdminApp) {
console.warn(
`[attendant-application] 用户 ${userId} 提交入驻申请,但其 user 记录没有 wxapp-escort-admin 应用条目`
`[attendant-application] 用户 ${userId} 提交入驻申请,但其 user 记录没有 wxapp_companion 应用条目`
);
}
@@ -346,24 +362,28 @@ class HandlerAttendantApplication {
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
);
// 引导客服改绑;档案可能是任意岗位,文案按实际岗位区分,避免误导。
// 未填写身份证时跳过(先收基本信息,后续补)。
const idNumber = result.value.applicant.idNumber;
if (idNumber) {
const rebound = await DBModel.Employee.findOne({
"profile.idNumber": 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 {
@@ -413,6 +433,97 @@ class HandlerAttendantApplication {
}
}
/**
* 证件材料后补
*
* 入驻申请提交时材料可为空;审核通过后在个人资料页补传。
* 只覆盖本次传入的字段,未传的保留原值;已驳回的申请不允许补,
* 驳回后应在入驻申请页修改并重新提交,避免绕开审核流程。
*/
async updateMyMaterials(ctx) {
try {
const userId = ctx.state.user?._id;
if (!userId) return ResponseUtil.unauthorized(ctx, "登录已失效");
const body = ctx.request.body || {};
const hasQualification = Boolean(body.qualification);
const hasHealthPhoto = Boolean(body.healthCertificate);
const hasExpireDate = Boolean(body.healthExpireDate);
if (!hasQualification && !hasHealthPhoto && !hasExpireDate) {
return ResponseUtil.badRequest(ctx, "请选择要补充的证件材料");
}
const application = await DBModel.AttendantApplication.findLatestByUser(userId);
if (!application) return ResponseUtil.notFound(ctx, "没有可补充的入驻申请");
if (application.status === "rejected") {
return ResponseUtil.error(ctx, "申请已驳回,请重新提交入驻申请", null, 409);
}
const update = { "meta.updatetime": Date.now() };
if (hasQualification) {
const qualification = HandlerTrainingApplication.parseImage(
body.qualification,
"资质证书照片",
IMAGE_MAX_BYTES
);
if (qualification.error) return ResponseUtil.badRequest(ctx, qualification.error);
update["materials.qualification"] = qualification.value;
}
if (hasHealthPhoto) {
const healthPhoto = HandlerTrainingApplication.parseImage(
body.healthCertificate,
"健康证明照片",
IMAGE_MAX_BYTES
);
if (healthPhoto.error) return ResponseUtil.badRequest(ctx, healthPhoto.error);
update["materials.healthCertificate.data"] = healthPhoto.value.data;
update["materials.healthCertificate.mime"] = healthPhoto.value.mime;
}
let expireDate = null;
if (hasExpireDate) {
expireDate = HandlerAttendantApplication.parseDate(body.healthExpireDate);
if (!expireDate) return ResponseUtil.badRequest(ctx, "健康证明有效期格式不正确");
const endOfDay = Date.UTC(
expireDate.getUTCFullYear(),
expireDate.getUTCMonth(),
expireDate.getUTCDate(),
15, 59, 59, 999
);
if (endOfDay < Date.now()) {
return ResponseUtil.badRequest(ctx, "健康证明已过期,请更新后再提交");
}
update["materials.healthCertificate.expireDate"] = expireDate;
}
const updated = await DBModel.AttendantApplication.findByIdAndUpdate(
application._id,
{ $set: update },
{ new: true }
).exec();
// 已建档的陪诊师同步健康证到期日;同步失败不回滚材料,只记日志
if (expireDate) {
try {
await DBModel.Employee.updateOne(
{ userId, role: "attendant" },
{ $set: { "work.healthCertificate.expireDate": expireDate, "meta.updatetime": Date.now() } }
).exec();
} catch (err) {
logger.error(`[attendant-application] 同步健康证有效期失败 user=${userId}: ${err?.message || err}`);
}
}
return ResponseUtil.success(
ctx,
{ application: HandlerAttendantApplication.toReceipt(updated) },
"材料已补充"
);
} catch (err) {
return ResponseUtil.internalError(ctx, err);
}
}
async getApplications(ctx) {
try {
const { status, keyword } = ctx.request.query;
+45
View File
@@ -2,6 +2,7 @@ import mongoose from "mongoose";
import { DBModel } from "../models/index.js";
import { MY_EMPLOYEE_SELECT } from "../models/schema/employee.js";
import ResponseUtil from "../utils/responseUtil.js";
import { SERVICE_AREAS } from "../resource/services.js";
/**
* 陪诊师公示:面向 C 端患者的公开信息展示
@@ -329,6 +330,50 @@ class HandlerEmployee {
}
}
/**
* 陪诊师本人修改服务城市
*
* 只允许在职陪诊师操作;城市必须来自服务目录白名单(与入驻申请同一份)。
* 变更只影响订单池可见范围,不改写入驻申请单里的历史快照。
*/
async updateMyServiceArea(ctx) {
try {
const userId = ctx.state.user?._id;
if (!userId) {
return ResponseUtil.unauthorized(ctx, "登录已失效");
}
const serviceArea = String(ctx.request.body?.serviceArea || "").trim();
if (!serviceArea) return ResponseUtil.badRequest(ctx, "请选择服务城市");
if (!SERVICE_AREAS.includes(serviceArea)) {
return ResponseUtil.badRequest(ctx, "服务城市不在可选范围");
}
const updated = await DBModel.Employee.findOneAndUpdate(
{ userId, role: "attendant", status: "active" },
{
$set: {
"attendantInfo.serviceAreas": [serviceArea],
"meta.updatetime": Date.now(),
},
},
{ new: true }
)
.select(MY_EMPLOYEE_SELECT)
.lean()
.exec();
if (!updated) return ResponseUtil.forbidden(ctx, "仅在职陪诊师可修改服务城市");
return ResponseUtil.success(
ctx,
{ employee: HandlerEmployee.decorateMyEmployee(updated) },
"服务城市已更新"
);
} catch (err) {
return ResponseUtil.internalError(ctx, err);
}
}
// ==================== 管理端 CRUD ====================
// 与上面的公示接口完全分开:管理端要真实姓名、身份证号、证书编号等内部字段,
// 但写入仍走白名单,避免 strict:false 的 schema 被塞入任意字段
+46 -4
View File
@@ -151,6 +151,37 @@ class HandlerEscortRecord {
return employee?.attendantInfo?.stage === "intern" ? "intern" : "certified";
}
/**
* 服务城市匹配值
*
* 入驻/个人资料写入的是「北京市」这类带「市」的值,历史手工数据可能不带「市」,
* 查询时同时兼容两种写法,避免存量档案匹配不到订单。
*/
static cityVariants(areas) {
const set = new Set();
for (const area of Array.isArray(areas) ? areas : []) {
const text = String(area || "").trim();
if (!text) continue;
const stripped = text.replace(/市$/, "");
set.add(text);
set.add(stripped);
if (stripped) set.add(`${stripped}市`);
}
return [...set];
}
/**
* 订单是否属于陪诊师的服务城市
* 未配置城市的存量档案、未填省份的历史订单都保持可见,避免存量数据突然消失
*/
static matchesServiceArea(record, employee) {
const variants = HandlerEscortRecord.cityVariants(employee?.attendantInfo?.serviceAreas);
if (!variants.length) return true;
const province = String(record?.hospital?.province || "").trim();
if (!province) return true;
return variants.includes(province);
}
/**
* 解析用户下单时选择的陪诊师。
*
@@ -218,7 +249,10 @@ class HandlerEscortRecord {
const employeeId = String(employee._id);
const sharedWith = Array.isArray(record.attendant?.sharedWith) ? record.attendant.sharedWith : [];
if (sharedWith.some((id) => String(id) === employeeId)) return true;
if (!record.attendant?.id) return true;
if (!record.attendant?.id) {
// 未分配订单:只有本服务城市的陪诊师可查看
return HandlerEscortRecord.matchesServiceArea(record, employee);
}
return String(record.attendant.id) === String(userId);
}
@@ -491,13 +525,17 @@ class HandlerEscortRecord {
userId: isIntern ? undefined : loginUserId,
employeeId: attendantEmployee._id,
};
// 订单池只展示本服务城市的订单;本人已接/被共享的订单不受城市限制
const poolCities = HandlerEscortRecord.cityVariants(
attendantEmployee.attendantInfo?.serviceAreas
);
const scopeValue = String(scope || "");
if (scopeValue === "pool") {
attendantVisibility = { includeUnassigned: true };
attendantVisibility = { includeUnassigned: true, poolCities };
} else if (scopeValue === "mine") {
attendantVisibility = mineVisibility;
} else {
attendantVisibility = { includeUnassigned: true, ...mineVisibility };
attendantVisibility = { includeUnassigned: true, poolCities, ...mineVisibility };
}
}
@@ -643,6 +681,10 @@ class HandlerEscortRecord {
if (record.attendant?.id) {
return ResponseUtil.error(ctx, "订单已被其他陪诊师接单", null, 409);
}
// 订单池只展示本城市订单;这里再挡一次,防止绕过列表直接调接口接单
if (!HandlerEscortRecord.matchesServiceArea(record, employee)) {
return ResponseUtil.forbidden(ctx, "该订单不在你的服务城市");
}
const profile = employee.profile || {};
const updated = await DBModel.EscortRecord.acceptRecord(id, {
@@ -1194,7 +1236,7 @@ class HandlerEscortRecord {
// 用户端与管理端共用本接口,按调用方 app 区分取消流程:
// appId 只用于收紧权限——即使账号同时带管理员角色,从用户端小程序发起的取消
// 也必须走取消申请,否则会在 C 端绕过「已确认订单需人工确认」直接退款。
// 管理端固定带 appId=wxapp-escort-admin;未带 appId 的历史调用保持原角色判定。
// 管理端固定带 appId=wxapp_companion;未带 appId 的历史调用保持原角色判定。
const requestAppId = String(ctx.request.body?.appId || "");
const isUserApp = requestAppId === "wxapp-escort";
const role = isUserApp ? null : await resolveEscortAdminRole(user);