Compare commits
3
Commits
7498ec83db
...
18cfc8e1b2
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
18cfc8e1b2 | ||
|
|
83ef5c2960 | ||
|
|
3f3dd07a2a |
@@ -90,7 +90,7 @@ export default class EscortAgent {
|
||||
recursion_limit: 50,
|
||||
streamMode: ["updates", "messages", "custom"], subgraphs: true,
|
||||
configurable: {
|
||||
thread_id: msgs[0].userId || msgs[0].appId
|
||||
thread_id: msgs[0].userId
|
||||
}
|
||||
})) {
|
||||
const isSubagent = namespace.some(s => s.startsWith("tools:"));
|
||||
|
||||
@@ -16,7 +16,7 @@ class ChatTask {
|
||||
}
|
||||
|
||||
async streamChat(userInfo, message, callback) {
|
||||
const userId = userInfo ? userInfo._id : message.appId;
|
||||
const userId = userInfo?._id;
|
||||
|
||||
let agent = this.agents.get(userId);
|
||||
if (agent) {
|
||||
|
||||
+185
-20
@@ -10,6 +10,7 @@ class HandlerEscortRecord {
|
||||
static RECORD_FIELDS = [
|
||||
"userId", "healthProfileId", "patient", "escort",
|
||||
"attendant", "hospital", "schedule", "payment", "notes", "status",
|
||||
"shippingAddress",
|
||||
];
|
||||
|
||||
// 用户端可自助修改的字段:费用、状态、陪诊员分配等一律由平台控制
|
||||
@@ -17,8 +18,15 @@ class HandlerEscortRecord {
|
||||
"patient", "healthProfileId", "hospital", "schedule", "notes",
|
||||
];
|
||||
|
||||
// 用户端可自助触发的状态(取消/确认完成),其余状态由平台流转
|
||||
static OWNER_ALLOWED_STATUS = ["cancelled", "completed"];
|
||||
// 用户端只能取消;服务完成由平台确认,避免用户端重复写入终态。
|
||||
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;
|
||||
@@ -63,6 +71,77 @@ class HandlerEscortRecord {
|
||||
return { page, pageSize };
|
||||
}
|
||||
|
||||
static formatDateOnly(value) {
|
||||
if (!value) return "";
|
||||
if (value instanceof Date) return value.toISOString().slice(0, 10);
|
||||
return String(value).slice(0, 10);
|
||||
}
|
||||
|
||||
static timeToMinutes(value) {
|
||||
if (!/^([01]\d|2[0-3]):[0-5]\d$/.test(value || "")) return null;
|
||||
const [hour, minute] = value.split(":").map(Number);
|
||||
return hour * 60 + minute;
|
||||
}
|
||||
|
||||
// 服务目录是预约规则与订单排期的唯一事实源,客户端提交的时长和结束时间一律忽略。
|
||||
static buildSchedule(service, dateValue, startTime, now = new Date()) {
|
||||
const date = HandlerEscortRecord.formatDateOnly(dateValue);
|
||||
const parsedDate = new Date(`${date}T00:00:00.000Z`);
|
||||
if (!/^\d{4}-\d{2}-\d{2}$/.test(date)
|
||||
|| Number.isNaN(parsedDate.getTime())
|
||||
|| parsedDate.toISOString().slice(0, 10) !== date) {
|
||||
return { error: "预约日期格式不正确" };
|
||||
}
|
||||
const booking = service.booking;
|
||||
if (!booking || !Array.isArray(booking.sessions) || booking.sessions.length === 0) {
|
||||
return { error: "该服务暂未开放预约" };
|
||||
}
|
||||
const earliest = new Date(now);
|
||||
earliest.setHours(0, 0, 0, 0);
|
||||
earliest.setDate(earliest.getDate() + Number(booking.advanceDays || 0));
|
||||
const earliestDate = `${earliest.getFullYear()}-${String(earliest.getMonth() + 1).padStart(2, "0")}-${String(earliest.getDate()).padStart(2, "0")}`;
|
||||
if (date < earliestDate) {
|
||||
return { error: `请至少提前${booking.advanceDays}天预约` };
|
||||
}
|
||||
|
||||
const startMinutes = HandlerEscortRecord.timeToMinutes(startTime);
|
||||
if (startMinutes === null) return { error: "预约时间格式不正确" };
|
||||
const session = booking.sessions.find((item) => item.flexible
|
||||
? startMinutes >= HandlerEscortRecord.timeToMinutes(item.start)
|
||||
&& startMinutes + booking.durationMinutes <= HandlerEscortRecord.timeToMinutes(item.end)
|
||||
: item.start === startTime);
|
||||
if (!session) return { error: "所选时间不在该服务的可预约时段内" };
|
||||
|
||||
const endTime = session.flexible
|
||||
? (() => {
|
||||
const endMinutes = (startMinutes + booking.durationMinutes) % 1440;
|
||||
return `${String(Math.floor(endMinutes / 60)).padStart(2, "0")}:${String(endMinutes % 60).padStart(2, "0")}`;
|
||||
})()
|
||||
: session.end;
|
||||
return {
|
||||
schedule: {
|
||||
date,
|
||||
startTime,
|
||||
endTime,
|
||||
duration: Number(booking.durationMinutes) || 0,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
static buildShippingAddress(service, source, profile) {
|
||||
const address = String(source?.address || "").trim();
|
||||
if (service.booking?.requiresAddress && !address) {
|
||||
return { error: "请填写完整收货地址" };
|
||||
}
|
||||
return {
|
||||
shippingAddress: {
|
||||
recipientName: profile.profile?.name || "",
|
||||
mobile: profile.profile?.mobile || "",
|
||||
address,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// 按条件查询记录(管理端,可查全部)
|
||||
async getRecords(ctx) {
|
||||
return this._listRecords(ctx, false);
|
||||
@@ -85,7 +164,11 @@ class HandlerEscortRecord {
|
||||
statusArray = status.split(',')
|
||||
}
|
||||
|
||||
const records = await DBModel.EscortRecord.findRecords({
|
||||
if (statusArray && statusArray.some((item) => !Object.hasOwn(HandlerEscortRecord.STATUS_TRANSITIONS, item))) {
|
||||
return ResponseUtil.badRequest(ctx, "订单状态筛选值不正确");
|
||||
}
|
||||
|
||||
const result = await DBModel.EscortRecord.findRecordPage({
|
||||
page,
|
||||
pageSize,
|
||||
status: statusArray,
|
||||
@@ -94,7 +177,7 @@ class HandlerEscortRecord {
|
||||
healthProfileId,
|
||||
});
|
||||
|
||||
return ResponseUtil.success(ctx, { records }, "查询成功");
|
||||
return ResponseUtil.success(ctx, { ...result, page, pageSize }, "查询成功");
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err.message);
|
||||
}
|
||||
@@ -151,6 +234,15 @@ class HandlerEscortRecord {
|
||||
if (!userId) {
|
||||
return ResponseUtil.unauthorized(ctx, "登录已失效");
|
||||
}
|
||||
const idempotencyKey = String(body.idempotencyKey || "").trim();
|
||||
if (idempotencyKey && !/^[\w-]{8,80}$/.test(idempotencyKey)) {
|
||||
return ResponseUtil.badRequest(ctx, "下单幂等标识格式不正确");
|
||||
}
|
||||
if (idempotencyKey) {
|
||||
const existing = await DBModel.EscortRecord.findByIdempotencyKey(userId, idempotencyKey);
|
||||
if (existing) return ResponseUtil.success(ctx, { record: existing }, "订单已创建");
|
||||
}
|
||||
|
||||
// 订单必须关联就诊人:patient 是下单当刻的快照,healthProfileId 才是关联
|
||||
if (!body.healthProfileId) {
|
||||
return ResponseUtil.badRequest(ctx, "缺少就诊人档案ID");
|
||||
@@ -162,24 +254,60 @@ class HandlerEscortRecord {
|
||||
return ResponseUtil.badRequest(ctx, "就诊人档案不存在");
|
||||
}
|
||||
|
||||
// 服务项目与价格以服务端 services.js 为准,客户端提交的价格一律忽略
|
||||
// 服务项目、服务名称、区域、排期与价格均以服务端目录为准。
|
||||
const service = services.find((s) => String(s.id) === String(body.escort?.serviceId));
|
||||
if (!service) {
|
||||
return ResponseUtil.badRequest(ctx, "服务项目不存在");
|
||||
if (!service) return ResponseUtil.badRequest(ctx, "服务项目不存在或已下架");
|
||||
if (!service.areas.includes(body.hospital?.province)) {
|
||||
return ResponseUtil.badRequest(ctx, "所选省份暂未开通服务");
|
||||
}
|
||||
if (!String(body.hospital?.name || "").trim() || !String(body.hospital?.department || "").trim()) {
|
||||
return ResponseUtil.badRequest(ctx, "请填写就诊医院和科室");
|
||||
}
|
||||
const scheduleResult = HandlerEscortRecord.buildSchedule(
|
||||
service,
|
||||
body.schedule?.date,
|
||||
body.schedule?.startTime
|
||||
);
|
||||
if (scheduleResult.error) return ResponseUtil.badRequest(ctx, scheduleResult.error);
|
||||
const addressResult = HandlerEscortRecord.buildShippingAddress(service, body.shippingAddress, profile);
|
||||
if (addressResult.error) return ResponseUtil.badRequest(ctx, addressResult.error);
|
||||
|
||||
const payload = HandlerEscortRecord.pickFields(body);
|
||||
// 归属、状态、费用全部由服务端决定
|
||||
payload.userId = userId;
|
||||
payload.status = "pending";
|
||||
payload.patient = {
|
||||
name: profile.profile?.name || "",
|
||||
mobile: profile.profile?.mobile || "",
|
||||
birth: profile.profile?.birth || "",
|
||||
};
|
||||
if (["male", "female"].includes(profile.profile?.sex)) payload.patient.sex = profile.profile.sex;
|
||||
payload.escort = {
|
||||
serviceId: service.id,
|
||||
serviceName: service.title,
|
||||
sexRequirement: ["none", "male", "female"].includes(body.escort?.sexRequirement)
|
||||
? body.escort.sexRequirement
|
||||
: "none",
|
||||
};
|
||||
payload.schedule = scheduleResult.schedule;
|
||||
payload.shippingAddress = addressResult.shippingAddress;
|
||||
if (idempotencyKey) payload.idempotencyKey = idempotencyKey;
|
||||
payload.payment = {
|
||||
totalFee: Number(service.price) || 0,
|
||||
paidFee: 0,
|
||||
status: "unpaid",
|
||||
};
|
||||
|
||||
const newRecord = await DBModel.EscortRecord.createRecord(payload);
|
||||
return ResponseUtil.success(ctx, { record: newRecord }, "创建成功");
|
||||
try {
|
||||
const newRecord = await DBModel.EscortRecord.createRecord(payload);
|
||||
return ResponseUtil.success(ctx, { record: newRecord }, "创建成功");
|
||||
} catch (err) {
|
||||
// 并发重复提交由唯一索引兜底,后到的请求返回已创建订单。
|
||||
if (err?.code === 11000 && idempotencyKey) {
|
||||
const existing = await DBModel.EscortRecord.findByIdempotencyKey(userId, idempotencyKey);
|
||||
if (existing) return ResponseUtil.success(ctx, { record: existing }, "订单已创建");
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
} catch (err) {
|
||||
return ResponseUtil.internalError(ctx, err.message);
|
||||
}
|
||||
@@ -202,12 +330,38 @@ class HandlerEscortRecord {
|
||||
return ResponseUtil.forbidden(ctx, "无权修改该订单");
|
||||
}
|
||||
|
||||
const isAdmin = HandlerEscortRecord.isAdmin(ctx.state.user);
|
||||
if (!isAdmin && ["completed", "cancelled"].includes(existing.status)) {
|
||||
return ResponseUtil.forbidden(ctx, "已结束的订单不可修改");
|
||||
}
|
||||
|
||||
// 非管理员只能改就诊信息类字段,费用/状态/归属/陪诊员分配不可自助修改
|
||||
const allowFields = HandlerEscortRecord.isAdmin(ctx.state.user)
|
||||
const allowFields = isAdmin
|
||||
? HandlerEscortRecord.RECORD_FIELDS
|
||||
: HandlerEscortRecord.OWNER_UPDATE_FIELDS;
|
||||
const payload = HandlerEscortRecord.pickFields(update, allowFields);
|
||||
const service = services.find((item) => item.id === existing.escort?.serviceId);
|
||||
if (!service) return ResponseUtil.badRequest(ctx, "订单关联的服务已下架");
|
||||
|
||||
const updatedRecord = await DBModel.EscortRecord.updateRecord(id, HandlerEscortRecord.pickFields(update, allowFields));
|
||||
const touchesSchedule = Object.keys(payload).some((key) => key === "schedule" || key.startsWith("schedule."));
|
||||
if (touchesSchedule) {
|
||||
const date = update["schedule.date"] || update.schedule?.date || existing.schedule?.date;
|
||||
const startTime = update["schedule.startTime"] || update.schedule?.startTime || existing.schedule?.startTime;
|
||||
const scheduleResult = HandlerEscortRecord.buildSchedule(service, date, startTime);
|
||||
if (scheduleResult.error) return ResponseUtil.badRequest(ctx, scheduleResult.error);
|
||||
for (const key of Object.keys(payload)) {
|
||||
if (key.startsWith("schedule.")) delete payload[key];
|
||||
}
|
||||
payload.schedule = scheduleResult.schedule;
|
||||
}
|
||||
|
||||
const touchesHospital = Object.keys(payload).some((key) => key === "hospital" || key.startsWith("hospital."));
|
||||
if (touchesHospital) {
|
||||
const province = update["hospital.province"] || update.hospital?.province || existing.hospital?.province;
|
||||
if (!service.areas.includes(province)) return ResponseUtil.badRequest(ctx, "所选省份暂未开通服务");
|
||||
}
|
||||
|
||||
const updatedRecord = await DBModel.EscortRecord.updateRecord(id, payload);
|
||||
if (!updatedRecord) {
|
||||
return ResponseUtil.error(ctx, "陪诊记录不存在", null, 404);
|
||||
}
|
||||
@@ -221,7 +375,7 @@ class HandlerEscortRecord {
|
||||
async updateStatus(ctx) {
|
||||
try {
|
||||
const { id } = ctx.params;
|
||||
const { status } = ctx.request.body;
|
||||
const { status, reason } = ctx.request.body;
|
||||
|
||||
if (!id) {
|
||||
return ResponseUtil.badRequest(ctx, "缺少记录ID");
|
||||
@@ -238,18 +392,29 @@ class HandlerEscortRecord {
|
||||
return ResponseUtil.forbidden(ctx, "无权修改该订单");
|
||||
}
|
||||
|
||||
// 用户端只允许「取消」与「确认完成」,其余状态由平台流转
|
||||
if (!HandlerEscortRecord.isAdmin(ctx.state.user)
|
||||
&& !HandlerEscortRecord.OWNER_ALLOWED_STATUS.includes(status)) {
|
||||
const isAdmin = HandlerEscortRecord.isAdmin(ctx.state.user);
|
||||
if (!isAdmin && !HandlerEscortRecord.OWNER_ALLOWED_STATUS.includes(status)) {
|
||||
return ResponseUtil.forbidden(ctx, "不支持的状态变更");
|
||||
}
|
||||
if (!HandlerEscortRecord.STATUS_TRANSITIONS[existing.status]?.includes(status)) {
|
||||
return ResponseUtil.badRequest(ctx, "当前订单状态不允许此操作");
|
||||
}
|
||||
|
||||
const updatedRecord = await DBModel.EscortRecord.updateRecord(id, {
|
||||
"status": status,
|
||||
});
|
||||
const update = { status };
|
||||
if (status === "cancelled") {
|
||||
const cancelReason = String(reason || (isAdmin ? "平台取消" : "")).trim();
|
||||
if (!cancelReason) return ResponseUtil.badRequest(ctx, "请选择取消原因");
|
||||
update.cancelReason = cancelReason.slice(0, 200);
|
||||
update.cancelledAt = new Date();
|
||||
// 客服协助支付没有线上自动退款能力:已收款订单先进入退款中,退款完成再由平台核销。
|
||||
if (["partial", "paid"].includes(existing.payment?.status)) {
|
||||
update["payment.status"] = "refunding";
|
||||
}
|
||||
}
|
||||
|
||||
const updatedRecord = await DBModel.EscortRecord.updateRecordStatus(id, existing.status, update);
|
||||
if (!updatedRecord) {
|
||||
return ResponseUtil.error(ctx, "陪诊记录不存在", null, 404);
|
||||
return ResponseUtil.error(ctx, "订单状态已变化,请刷新后重试", null, 409);
|
||||
}
|
||||
|
||||
return ResponseUtil.success(ctx, { record: updatedRecord }, "状态更新成功");
|
||||
|
||||
@@ -65,6 +65,19 @@ const EscortRecordSchema = mongoose.Schema(
|
||||
sexRequirement: { type: String, enum: ["none", "male", "female"], comment: "陪诊员性别要求" },
|
||||
},
|
||||
|
||||
// 下单幂等键:同一用户重复提交同一键时返回原订单,不重复创建。
|
||||
idempotencyKey: {
|
||||
type: String,
|
||||
comment: "用户端下单幂等标识"
|
||||
},
|
||||
|
||||
// 收货信息是下单当刻的快照,不随用户资料或地址变化。
|
||||
shippingAddress: {
|
||||
recipientName: { type: String, default: "", comment: "收货人姓名" },
|
||||
mobile: { type: String, default: "", comment: "收货联系电话" },
|
||||
address: { type: String, default: "", comment: "完整收货地址" },
|
||||
},
|
||||
|
||||
/**
|
||||
* 陪诊员信息 - 为患者提供服务的陪诊员
|
||||
*/
|
||||
@@ -107,9 +120,9 @@ const EscortRecordSchema = mongoose.Schema(
|
||||
paidFee: { type: Number, default: 0, comment: "已支付费用(元)" },
|
||||
status: {
|
||||
type: String,
|
||||
enum: ["unpaid", "partial", "paid", "refunded"],
|
||||
enum: ["unpaid", "partial", "paid", "refunding", "refunded"],
|
||||
default: "unpaid",
|
||||
comment: "支付状态:未支付、部分支付、已支付、已退款",
|
||||
comment: "支付状态:未支付、部分支付、已支付、退款中、已退款",
|
||||
},
|
||||
},
|
||||
|
||||
@@ -137,6 +150,9 @@ const EscortRecordSchema = mongoose.Schema(
|
||||
comment: "陪诊状态:待确认、已确认、进行中、已完成、已取消",
|
||||
},
|
||||
|
||||
cancelReason: { type: String, default: "", comment: "订单取消原因" },
|
||||
cancelledAt: { type: Date, default: null, comment: "订单取消时间" },
|
||||
|
||||
/**
|
||||
* 元数据 - 系统管理信息
|
||||
*/
|
||||
@@ -165,29 +181,27 @@ const EscortRecordSchema = mongoose.Schema(
|
||||
* @param {Function} [cb] - 可选的回调函数
|
||||
* @returns {Promise<Array>} 陪诊记录列表(按预约日期倒序)
|
||||
*/
|
||||
EscortRecordSchema.statics.findRecords = async function (options = {}, cb) {
|
||||
const { page = 1, pageSize = 20, status, userId, appointmentDate, healthProfileId } = options;
|
||||
EscortRecordSchema.statics.buildRecordFilter = function (options = {}) {
|
||||
const { status, userId, appointmentDate, healthProfileId } = options;
|
||||
const filter = {};
|
||||
|
||||
if (status && Array.isArray(status) && status.length > 0) {
|
||||
filter.status = { $in: status };
|
||||
}
|
||||
|
||||
if (userId) {
|
||||
filter.userId = userId;
|
||||
}
|
||||
|
||||
if (healthProfileId) {
|
||||
filter.healthProfileId = healthProfileId;
|
||||
}
|
||||
|
||||
if (userId) filter.userId = userId;
|
||||
if (healthProfileId) filter.healthProfileId = healthProfileId;
|
||||
if (appointmentDate) {
|
||||
const start = new Date(appointmentDate);
|
||||
const start = new Date(`${appointmentDate}T00:00:00.000Z`);
|
||||
const end = new Date(start);
|
||||
end.setDate(end.getDate() + 1);
|
||||
end.setUTCDate(end.getUTCDate() + 1);
|
||||
filter["schedule.date"] = { $gte: start, $lt: end };
|
||||
}
|
||||
return filter;
|
||||
};
|
||||
|
||||
EscortRecordSchema.statics.findRecords = async function (options = {}, cb) {
|
||||
const { page = 1, pageSize = 20 } = options;
|
||||
const filter = this.buildRecordFilter(options);
|
||||
const skip = (page - 1) * pageSize;
|
||||
|
||||
return await this.find(filter)
|
||||
@@ -197,6 +211,21 @@ EscortRecordSchema.statics.findRecords = async function (options = {}, cb) {
|
||||
.exec(cb);
|
||||
};
|
||||
|
||||
// 列表记录、筛选总数和各页签计数一次返回,避免前端按当前页过滤或统计。
|
||||
EscortRecordSchema.statics.findRecordPage = async function (options = {}) {
|
||||
const { page = 1, pageSize = 20 } = options;
|
||||
const filter = this.buildRecordFilter(options);
|
||||
const baseFilter = this.buildRecordFilter({ ...options, status: null });
|
||||
const skip = (page - 1) * pageSize;
|
||||
const [records, total, all, ongoing] = await Promise.all([
|
||||
this.find(filter).sort({ "schedule.date": -1 }).skip(skip).limit(pageSize).exec(),
|
||||
this.countDocuments(filter).exec(),
|
||||
this.countDocuments(baseFilter).exec(),
|
||||
this.countDocuments({ ...baseFilter, status: { $in: ["pending", "confirmed", "in_progress"] } }).exec(),
|
||||
]);
|
||||
return { records, total, counts: { all, ongoing } };
|
||||
};
|
||||
|
||||
/**
|
||||
* 查找陪诊员的陪诊记录
|
||||
*
|
||||
@@ -252,7 +281,20 @@ 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 }, cb);
|
||||
return await this.findByIdAndUpdate(id, { $set }, { new: true, runValidators: true }, cb);
|
||||
};
|
||||
|
||||
// 状态迁移必须仍以读取时的状态为条件,避免并发请求重复取消或跨过服务阶段。
|
||||
EscortRecordSchema.statics.updateRecordStatus = async function (id, fromStatus, update) {
|
||||
return await this.findOneAndUpdate(
|
||||
{ _id: id, status: fromStatus },
|
||||
{ $set: { ...update, "meta.updatetime": Date.now() } },
|
||||
{ new: true, runValidators: true }
|
||||
);
|
||||
};
|
||||
|
||||
EscortRecordSchema.statics.findByIdempotencyKey = async function (userId, idempotencyKey) {
|
||||
return await this.findOne({ userId, idempotencyKey }).exec();
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -305,6 +347,12 @@ EscortRecordSchema.statics.deleteRecord = async function (id, cb) {
|
||||
*/
|
||||
EscortRecordSchema.index({ userId: 1, "schedule.date": -1 });
|
||||
|
||||
// 仅带幂等键的新订单参与唯一约束,历史订单不受影响。
|
||||
EscortRecordSchema.index(
|
||||
{ userId: 1, idempotencyKey: 1 },
|
||||
{ unique: true, sparse: true }
|
||||
);
|
||||
|
||||
/**
|
||||
* 健康档案ID索引 - 稀疏索引,用于快速按健康档案筛选记录
|
||||
*/
|
||||
|
||||
+78
-8
@@ -1,3 +1,20 @@
|
||||
/**
|
||||
* 服务目录 —— 小程序端服务项的唯一事实源。
|
||||
*
|
||||
* 每个服务除公示文案(subtitle / description / flow / notices)外,
|
||||
* 另有一段机读配置 booking,供前端渲染选择器、后端派生订单字段并做校验:
|
||||
* - advanceDays:至少提前预约的天数,与 notices 公示的「请提前1天预约」保持同一口径;
|
||||
* - durationMinutes:标准服务时长(分钟),0 表示不预设时长(如按实际进程结束的代办类);
|
||||
* - sessions:可预约时段列表。
|
||||
* · 非 flexible:起止时刻固定,用户选的是「班次」,order 的 start/end 直接取该时段;
|
||||
* · flexible=true:开始时刻可在区间内选择,结束时刻由 durationMinutes 推算。
|
||||
* - requiresAddress:是否需要填写收货地址,后端据此强制校验地址快照。
|
||||
*
|
||||
* 说明:这些字段不得在前端另行硬编码,前端只读不写;
|
||||
* 后端以本目录为准派生订单的 schedule.duration / schedule.endTime 并校验预约时段。
|
||||
*/
|
||||
const SERVICE_AREAS = ['北京市', '天津市']
|
||||
|
||||
const services = [
|
||||
{
|
||||
id: 1,
|
||||
@@ -8,6 +25,14 @@ const services = [
|
||||
image: '/images/pz1.jpg',
|
||||
icon: 'user-business',
|
||||
tag: '',
|
||||
// 机读预约配置:前端据此渲染选择器,后端据此派生订单时长与结束时刻并校验
|
||||
booking: {
|
||||
advanceDays: 1, // 至少提前 1 天预约(与 notices 同口径)
|
||||
durationMinutes: 480, // 八小时服务(12:00—13:00 午休不计服务时长)
|
||||
sessions: [
|
||||
{ start: '08:00', end: '17:00' } // 固定班次:起止时刻由公示时段决定
|
||||
]
|
||||
},
|
||||
// 只讲服务对象,不重复 subtitle 已写的时长与陪同方式(详情页两段紧挨着显示)
|
||||
// 三类人群对应 GB/T 47801—2026 3.3 服务对象的「行动、认知、地域差异」三种成因;
|
||||
// 原「需要专业指导」会被读成医疗指导,触及 8.2「不应提供医疗建议」
|
||||
@@ -24,7 +49,7 @@ const services = [
|
||||
},
|
||||
{
|
||||
title: '支付费用',
|
||||
desc: '通过微信支付服务费用'
|
||||
desc: '联系客服协助支付服务费用'
|
||||
},
|
||||
{
|
||||
title: '准备资料',
|
||||
@@ -67,6 +92,14 @@ const services = [
|
||||
image: '/images/pz1.jpg',
|
||||
icon: 'usergroup',
|
||||
tag: '热门',
|
||||
booking: {
|
||||
advanceDays: 1,
|
||||
durationMinutes: 240,
|
||||
sessions: [
|
||||
{ start: '08:00', end: '12:00' },
|
||||
{ start: '13:00', end: '17:00' }
|
||||
]
|
||||
},
|
||||
// 服务对象句与 id 1 一致(同属陪同就医,对象成因相同);首句用「项目较少、半天内完成」
|
||||
// 与 id 1 的「项目较多、耗时长」形成对照,避免两个详情页读起来没有区分度
|
||||
description: '适合就诊项目较少、预计半天内能完成的情况。主要服务行动不便、认知或沟通不便、异地就医不熟悉医院的用户。',
|
||||
@@ -81,7 +114,7 @@ const services = [
|
||||
},
|
||||
{
|
||||
title: '支付费用',
|
||||
desc: '通过微信支付服务费用'
|
||||
desc: '联系客服协助支付服务费用'
|
||||
},
|
||||
{
|
||||
title: '准备资料',
|
||||
@@ -124,6 +157,11 @@ const services = [
|
||||
image: '/images/wz1.jpg',
|
||||
icon: 'heart',
|
||||
tag: '',
|
||||
booking: {
|
||||
advanceDays: 1,
|
||||
durationMinutes: 60,
|
||||
sessions: [{ start: '08:00', end: '18:00', flexible: true }]
|
||||
},
|
||||
// 4.2.2.2 收集与使用服务对象信息须经授权同意,本项全程由他人代为出行,前提必须写明;
|
||||
// 末句对应 8.2 第 4 条「不应代替服务对象或其家属选择或同意治疗方案」
|
||||
description: '代问诊服务适用于无法亲自到医院的用户。经您同意并授权后,陪诊师携带您的病历资料,代您向医生陈述病情、转达就诊诉求,如实记录医嘱并完整转达给您。涉及检查、用药与治疗方案的选择,由医生直接与您或家人沟通,陪诊师不代为决定。',
|
||||
@@ -137,7 +175,7 @@ const services = [
|
||||
},
|
||||
{
|
||||
title: '支付费用',
|
||||
desc: '通过微信支付服务费用'
|
||||
desc: '联系客服协助支付服务费用'
|
||||
},
|
||||
{
|
||||
title: '准备资料',
|
||||
@@ -189,6 +227,11 @@ const services = [
|
||||
image: '/images/qbg1.jpg',
|
||||
icon: 'chart-bar',
|
||||
tag: '',
|
||||
booking: {
|
||||
advanceDays: 1,
|
||||
durationMinutes: 60,
|
||||
sessions: [{ start: '08:00', end: '18:00', flexible: true }]
|
||||
},
|
||||
// 去「我们」(全站统一用「陪诊师」),并补服务对象句,结构对齐 id 1/2/7;
|
||||
// 原名「核磁共振(MRI)」与副标题的「磁共振」是同一项检查的两个名字,统一为「磁共振(MRI)」;
|
||||
// 原文首句「检查预约服务帮助您预约…」是把标题复述一遍,改为直接说可约项目
|
||||
@@ -213,7 +256,7 @@ const services = [
|
||||
},
|
||||
{
|
||||
title: '支付费用',
|
||||
desc: '通过微信支付服务费用'
|
||||
desc: '联系客服协助支付服务费用'
|
||||
},
|
||||
{
|
||||
// 原「预约办理」+「确认通知」合为一步
|
||||
@@ -258,6 +301,11 @@ const services = [
|
||||
image: '/images/yy.jpg',
|
||||
icon: 'user-checked',
|
||||
tag: '',
|
||||
booking: {
|
||||
advanceDays: 1,
|
||||
durationMinutes: 60,
|
||||
sessions: [{ start: '08:00', end: '18:00', flexible: true }]
|
||||
},
|
||||
// 4.2.2.2 办理出入院要收集身份证、医保卡信息,须经授权同意;首句补服务对象,
|
||||
// 与 id 1/2/3/4 一致;原末句「让您或家人能够更专注于治疗本身」是宣传腔,删
|
||||
description: '经您授权同意后,陪诊师代您办理入院登记、医保手续、出院结算等出入院手续。',
|
||||
@@ -275,7 +323,7 @@ const services = [
|
||||
},
|
||||
{
|
||||
title: '支付费用',
|
||||
desc: '通过微信支付服务费用'
|
||||
desc: '联系客服协助支付服务费用'
|
||||
},
|
||||
{
|
||||
// 原「准备身份证、医保卡、押金等相关资料」把押金当成资料;押金是钱,不是材料
|
||||
@@ -322,6 +370,12 @@ const services = [
|
||||
image: '/images/pt.jpg',
|
||||
icon: 'usergroup',
|
||||
tag: '',
|
||||
booking: {
|
||||
advanceDays: 1,
|
||||
durationMinutes: 120,
|
||||
requiresAddress: true,
|
||||
sessions: [{ start: '08:00', end: '18:00', flexible: true }]
|
||||
},
|
||||
// 称谓由「客户」改为「用户」,与 id 1-5/7/8 统一;补服务对象句,结构对齐 id 1/2/7;
|
||||
// 原末句「让您足不出户即可完成医院相关事务」是宣传腔,且与首句同义,删;
|
||||
// 「代买药」同步改为「代取药品」——与 id 8 同一动作只留一个说法;
|
||||
@@ -341,7 +395,7 @@ const services = [
|
||||
},
|
||||
{
|
||||
title: '支付费用',
|
||||
desc: '通过微信支付服务费用'
|
||||
desc: '联系客服协助支付服务费用'
|
||||
},
|
||||
{
|
||||
title: '准备资料',
|
||||
@@ -390,6 +444,11 @@ const services = [
|
||||
image: '/images/pz1.jpg',
|
||||
icon: 'user-business',
|
||||
tag: '',
|
||||
booking: {
|
||||
advanceDays: 1,
|
||||
durationMinutes: 240,
|
||||
sessions: [{ start: '20:00', end: '00:00' }]
|
||||
},
|
||||
// 称谓由「客户」改为「用户」,与 id 1-5 统一;结构对齐 id 1(服务对象句 + 适用情形句),
|
||||
// 原句把 flow 里的环节又叙述一遍,且「让夜间就医也能更省心」是宣传腔,一并删
|
||||
description: '主要服务行动不便、认知或沟通不便、异地就医不熟悉医院的用户。夜间就诊、不便独自前往或家属不便陪同时,建议选择本服务。',
|
||||
@@ -407,7 +466,7 @@ const services = [
|
||||
},
|
||||
{
|
||||
title: '支付费用',
|
||||
desc: '通过微信支付服务费用'
|
||||
desc: '联系客服协助支付服务费用'
|
||||
},
|
||||
{
|
||||
title: '医院集合',
|
||||
@@ -447,6 +506,12 @@ const services = [
|
||||
image: '/images/pt.jpg',
|
||||
icon: 'usergroup',
|
||||
tag: '',
|
||||
booking: {
|
||||
advanceDays: 1,
|
||||
durationMinutes: 60,
|
||||
requiresAddress: true,
|
||||
sessions: [{ start: '08:00', end: '18:00', flexible: true }]
|
||||
},
|
||||
// 称谓由「客户」改为「用户」、去「我们」,与 id 1-5/7 统一;
|
||||
// 结构对齐 id 1/2/7(服务对象句 + 适用情形句),原句又把 flow 叙述了一遍
|
||||
description: '主要服务不便出门或异地取药的用户。经您同意并授权后,陪诊师携带您的取药凭证代取药品,妥善包装后通过快递寄送到家。',
|
||||
@@ -463,7 +528,7 @@ const services = [
|
||||
},
|
||||
{
|
||||
title: '支付费用',
|
||||
desc: '通过微信支付服务费用'
|
||||
desc: '联系客服协助支付服务费用'
|
||||
},
|
||||
{
|
||||
title: '准备资料',
|
||||
@@ -501,4 +566,9 @@ const services = [
|
||||
}
|
||||
]
|
||||
|
||||
// 服务区域由目录统一注入,前端选择器与后端校验共用同一份配置。
|
||||
for (const service of services) {
|
||||
service.areas = SERVICE_AREAS
|
||||
}
|
||||
|
||||
export default services;
|
||||
|
||||
+24
-11
@@ -5,6 +5,19 @@ import { chatTask } from "./agent/bots/bot-escort/task.js";
|
||||
import { adminAgent } from "./agent/bots/bot-escort-admin/agent.js"
|
||||
import { getUserByToken } from "./utils/user_service.js";
|
||||
|
||||
let systemMessageSequence = 0;
|
||||
|
||||
// 所有下行帧保持同一结构,调用方无需按消息类型猜测字段。
|
||||
const sendFrame = (ws, source, type, content = '', id = '') => {
|
||||
if (ws.readyState !== WebSocket.OPEN) return;
|
||||
ws.send(JSON.stringify({
|
||||
source,
|
||||
type,
|
||||
content,
|
||||
id: id || `system_${Date.now()}_${++systemMessageSequence}`
|
||||
}));
|
||||
};
|
||||
|
||||
export default class WebSocketServerManager {
|
||||
constructor(port = 8080) {
|
||||
this.port = port;
|
||||
@@ -44,7 +57,7 @@ export default class WebSocketServerManager {
|
||||
if (path === '/chat') {
|
||||
this._handleChatConnection(ws);
|
||||
} else {
|
||||
ws.send(JSON.stringify({ type: 'system', content: 'Unknown path' }));
|
||||
sendFrame(ws, 'system', 'error', 'Unknown path');
|
||||
ws.close(1000, 'Unknown path');
|
||||
}
|
||||
});
|
||||
@@ -55,7 +68,7 @@ export default class WebSocketServerManager {
|
||||
}
|
||||
|
||||
_handleChatConnection(ws) {
|
||||
ws.send(JSON.stringify({ type: 'system', content: 'Connected to chat server' }));
|
||||
sendFrame(ws, 'system', 'connected', 'Connected to chat server');
|
||||
|
||||
ws.on('message', (data) => this._handleMessage(ws, data));
|
||||
|
||||
@@ -77,7 +90,7 @@ export default class WebSocketServerManager {
|
||||
console.log('Received message type:', msg.type);
|
||||
|
||||
if (msg.type === 'ping') {
|
||||
ws.send(JSON.stringify({ type: 'pong' }));
|
||||
sendFrame(ws, 'system', 'pong', '', msg.id);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -86,26 +99,24 @@ export default class WebSocketServerManager {
|
||||
if (ws.readyState !== WebSocket.OPEN) return;
|
||||
|
||||
const send = (source, type, content, id) => {
|
||||
if (ws.readyState === WebSocket.OPEN) {
|
||||
ws.send(JSON.stringify({ source, type, content, id }));
|
||||
}
|
||||
sendFrame(ws, source, type, content, id);
|
||||
};
|
||||
|
||||
try {
|
||||
// 身份只认 token:不再接受凭 userId 明文接入,防止冒充他人聊天
|
||||
if (!msg.token) {
|
||||
ws.send(JSON.stringify({ type: 'error', content: '缺少登录凭证,请重新登录' }));
|
||||
send('system', 'error', '请先登录', msg.id);
|
||||
return;
|
||||
}
|
||||
const userInfo = await getUserByToken(msg.token);
|
||||
if (!userInfo) {
|
||||
ws.send(JSON.stringify({ type: 'error', content: '登录已失效' }));
|
||||
send('system', 'error', '请先登录', msg.id);
|
||||
return;
|
||||
}
|
||||
if (msg.agent === 'escort-admin') {
|
||||
// 管理端 agent 含写库/环境变量等高危工具,必须校验管理员角色,防止普通用户越权
|
||||
if (!userInfo.app || !("wxapp-escort-admin" in userInfo.app)) {
|
||||
ws.send(JSON.stringify({ type: 'error', content: '无管理员权限' }));
|
||||
send('system', 'error', '无管理员权限', msg.id);
|
||||
return;
|
||||
}
|
||||
await adminAgent.streamChat(userInfo, [msg], (source, type, content, id) => {
|
||||
@@ -116,9 +127,11 @@ export default class WebSocketServerManager {
|
||||
send(source, type, content, id);
|
||||
});
|
||||
}
|
||||
// 流式 chunk 可能携带不同的模型消息 ID,结束帧统一关联本次客户端请求。
|
||||
send('system', 'end', '', msg.id);
|
||||
} catch (err) {
|
||||
console.error('streamChat error:', err);
|
||||
send('system', 'error', '处理消息失败');
|
||||
send('system', 'error', '处理消息失败,请稍后重试', msg.id);
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -131,7 +144,7 @@ export default class WebSocketServerManager {
|
||||
console.log('[Unknown message type]', msg.type);
|
||||
} catch (e) {
|
||||
console.error('Message parse error:', e);
|
||||
ws.send(JSON.stringify({ type: 'error', content: 'Invalid JSON' }));
|
||||
sendFrame(ws, 'system', 'error', '消息格式错误');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user