数据库
- 新增 subject_plans(天数 + 定价):迁移内置三档
30 天 ¥99 / 180 天 ¥499(推荐,划线 594)/ 365 天 ¥899(最划算,划线 1204)
- subject_orders 增加 plan_id / plan_code / plan_name 快照
后端
- GET /api/web/subject-plans:上架套餐(含 pricePerDay)
- POST /api/web/subjects/:id/orders 改为 { planId }:金额只认套餐价,
前端传的 amount/days 一律忽略;套餐不存在/下架/未配价格 → 422
- 新增 GET /api/web/subjects/:id/orders/:orderNo(轮询支付状态)、
POST .../orders/:orderNo/close(关闭待支付订单)
- 下单仍然只建单不动期限;续期只发生在 POST /api/pay/notify(渠道回调)成功之后
前端
- 续期不再 prompt 输入天数:弹窗展示套餐卡片(天数/价格/划线价/角标/折合每天),
点「生成订单(¥xxx)」→ 显示订单号、金额、状态(待支付)
- 每 2s 轮询订单状态,回调确认后自动刷新主体列表并提示新到期时间;
待支付时可「关闭订单」,避免留下悬挂单
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
234 lines
8.7 KiB
JavaScript
234 lines
8.7 KiB
JavaScript
'use strict';
|
||
|
||
const { Service } = require('egg');
|
||
const crypto = require('crypto');
|
||
|
||
const DAY_MS = 24 * 3600 * 1000;
|
||
const STATUS_TEXT = { 0: '待支付', 1: '已支付', 2: '已关闭' };
|
||
|
||
/**
|
||
* 主体续期订单 service
|
||
*
|
||
* 流程:`create()` 选套餐下单(待支付)→ 支付渠道回调 `payNotify()` → 标记已支付 + 主体顺延 + 清状态缓存。
|
||
*
|
||
* 关键约定:
|
||
* - **支付靠回调驱动**:下单不改变期限,只有 `payNotify()` 成功才续期;
|
||
* - **价格只认套餐**:下单只收 `planId`,金额取库里的 `subject_plans.price`,不信前端传的金额;
|
||
* - **幂等**:同一订单重复回调只续期一次(第二次返回 `duplicated: true`);
|
||
* - 续期基数与 `service.subject.update` 一致:未过期在原到期时间上顺延,已过期从当前时间起算。
|
||
*/
|
||
class SubjectOrderService extends Service {
|
||
get Order() {
|
||
return this.app.model.SubjectOrder;
|
||
}
|
||
|
||
get Subject() {
|
||
return this.app.model.Subject;
|
||
}
|
||
|
||
/**
|
||
* 创建订单(管理员):选套餐 → 只建单,不动期限
|
||
*
|
||
* @param {object} params { subjectId, userId, planId, remark }
|
||
*/
|
||
async create({ subjectId, userId, planId, remark } = {}) {
|
||
const { subject } = await this.ctx.service.subject.ensureAdmin(subjectId, userId);
|
||
|
||
const plan = await this.ctx.service.subjectPlan.findActive(planId);
|
||
const grantDays = Number(plan.days);
|
||
const price = Number(plan.price);
|
||
|
||
if (!Number.isFinite(grantDays) || grantDays <= 0 || grantDays > 3650) {
|
||
this.ctx.throw(422, '套餐天数不合法,请联系管理员');
|
||
}
|
||
if (!Number.isFinite(price) || price <= 0) {
|
||
this.ctx.throw(422, '该套餐未设置价格,请联系管理员');
|
||
}
|
||
|
||
const order = await this.Order.create({
|
||
orderNo: generateOrderNo(),
|
||
subjectId: Number(subject.id),
|
||
userId: Number(userId),
|
||
planId: Number(plan.id),
|
||
planCode: plan.code,
|
||
planName: plan.name,
|
||
days: grantDays,
|
||
amount: Math.round(price * 100) / 100,
|
||
status: 0,
|
||
channel: 'mock',
|
||
expireBefore: subject.expireAt,
|
||
remark: remark || null,
|
||
});
|
||
|
||
this.ctx.logger.info('[order] 用户 %s 为主体 %s 创建续期订单 %s(套餐 %s,%s 天,金额 %s)',
|
||
userId, subject.id, order.orderNo, plan.code, grantDays, price);
|
||
|
||
return this.present(order);
|
||
}
|
||
|
||
/** 单个订单(续期弹窗轮询支付状态用;必须是该主体成员) */
|
||
async detail({ subjectId, userId, orderNo } = {}) {
|
||
await this.ctx.service.subject.findForUser(subjectId, userId);
|
||
|
||
const no = String(orderNo || '').trim();
|
||
if (!no) this.ctx.throw(400, 'orderNo 不能为空');
|
||
|
||
const order = await this.Order.findOne({
|
||
where: { orderNo: no, subjectId: Number(subjectId) },
|
||
});
|
||
if (!order) this.ctx.throw(404, '订单不存在');
|
||
return this.present(order);
|
||
}
|
||
|
||
/** 关闭待支付订单(用户取消 / 重新下单前清理) */
|
||
async close({ subjectId, userId, orderNo } = {}) {
|
||
await this.ctx.service.subject.ensureAdmin(subjectId, userId);
|
||
|
||
const no = String(orderNo || '').trim();
|
||
if (!no) this.ctx.throw(400, 'orderNo 不能为空');
|
||
|
||
const order = await this.Order.findOne({
|
||
where: { orderNo: no, subjectId: Number(subjectId) },
|
||
});
|
||
if (!order) this.ctx.throw(404, '订单不存在');
|
||
if (Number(order.status) === 1) this.ctx.throw(409, '订单已支付,不能关闭');
|
||
if (Number(order.status) === 2) return this.present(order);
|
||
|
||
await order.update({ status: 2 });
|
||
this.ctx.logger.info('[order] 用户 %s 关闭订单 %s', userId, no);
|
||
return this.present(order);
|
||
}
|
||
|
||
/** 某主体的订单列表(成员可见) */
|
||
async list({ subjectId, userId, page = 1, pageSize = 20 } = {}) {
|
||
await this.ctx.service.subject.findForUser(subjectId, userId);
|
||
|
||
const size = Math.min(Math.max(Number(pageSize) || 20, 1), 100);
|
||
const current = Math.max(Number(page) || 1, 1);
|
||
const result = await this.Order.findAndCountAll({
|
||
where: { subjectId: Number(subjectId) },
|
||
order: [[ 'id', 'DESC' ]],
|
||
limit: size,
|
||
offset: (current - 1) * size,
|
||
});
|
||
|
||
return {
|
||
total: result.count,
|
||
page: current,
|
||
pageSize: size,
|
||
list: result.rows.map(row => this.present(row)),
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 支付通知(渠道回调):标记已支付 + 主体续期 + 失效状态缓存
|
||
*
|
||
* @param {object} params { orderNo, transactionId?, amount?, channel?, paidAt? }
|
||
* @return {Promise<object>} { duplicated, order }
|
||
*/
|
||
async payNotify({ orderNo, transactionId, amount, channel, paidAt } = {}) {
|
||
const no = String(orderNo || '').trim();
|
||
if (!no) this.ctx.throw(422, 'orderNo 不能为空');
|
||
if (no.length > 32) this.ctx.throw(422, 'orderNo 不合法');
|
||
|
||
const transaction = await this.app.model.transaction();
|
||
try {
|
||
const order = await this.Order.findOne({
|
||
where: { orderNo: no },
|
||
transaction,
|
||
lock: transaction.LOCK.UPDATE,
|
||
});
|
||
if (!order) this.ctx.throw(404, '订单不存在');
|
||
|
||
// 已支付:幂等返回(重复回调不重复续期)
|
||
if (Number(order.status) === 1) {
|
||
await transaction.rollback();
|
||
return { duplicated: true, order: this.present(order) };
|
||
}
|
||
if (Number(order.status) !== 0) this.ctx.throw(409, '订单状态不允许支付');
|
||
|
||
const paid = amount === undefined || amount === null || amount === '' ? null : Number(amount);
|
||
if (paid !== null) {
|
||
if (!Number.isFinite(paid) || paid < 0) this.ctx.throw(422, '支付金额不合法');
|
||
if (order.amount !== null && order.amount !== undefined && Math.abs(paid - Number(order.amount)) > 0.001) {
|
||
this.ctx.throw(422, '支付金额与订单金额不一致');
|
||
}
|
||
}
|
||
|
||
const subject = await this.Subject.findByPk(Number(order.subjectId), {
|
||
transaction,
|
||
lock: transaction.LOCK.UPDATE,
|
||
});
|
||
if (!subject) this.ctx.throw(404, '订单对应的主体不存在');
|
||
|
||
const beforeMs = subject.expireAt ? new Date(subject.expireAt).getTime() : Date.now();
|
||
const baseMs = beforeMs <= Date.now() ? Date.now() : beforeMs;
|
||
const expireAfter = new Date(baseMs + Number(order.days) * DAY_MS);
|
||
|
||
await subject.update({ expireAt: expireAfter }, { transaction });
|
||
await order.update({
|
||
status: 1,
|
||
channel: channel || order.channel || null,
|
||
transactionId: transactionId ? String(transactionId).slice(0, 64) : null,
|
||
paidAt: paidAt ? new Date(paidAt) : new Date(),
|
||
expireBefore: order.expireBefore || new Date(beforeMs),
|
||
expireAfter,
|
||
}, { transaction });
|
||
|
||
await transaction.commit();
|
||
|
||
// 续期后必须失效缓存:否则设备心跳/上报会继续看到「已过期」,最多延迟一个 TTL
|
||
await this.ctx.service.subjectState.invalidate(order.subjectId);
|
||
|
||
this.ctx.logger.info('[order] 订单 %s 已支付,主体 %s 续期 %s 天:%s → %s',
|
||
order.orderNo, order.subjectId, order.days,
|
||
new Date(beforeMs).toISOString(), expireAfter.toISOString());
|
||
|
||
return { duplicated: false, order: this.present(order) };
|
||
} catch (err) {
|
||
try {
|
||
await transaction.rollback();
|
||
} catch (_) {
|
||
// 忽略:事务可能已经被上面的分支回滚过
|
||
}
|
||
throw err;
|
||
}
|
||
}
|
||
|
||
present(order, extra = {}) {
|
||
return Object.assign({
|
||
id: Number(order.id),
|
||
orderNo: order.orderNo,
|
||
subjectId: Number(order.subjectId),
|
||
userId: Number(order.userId),
|
||
planId: order.planId === null || order.planId === undefined ? null : Number(order.planId),
|
||
planCode: order.planCode || null,
|
||
planName: order.planName || null,
|
||
days: Number(order.days),
|
||
amount: order.amount === null || order.amount === undefined ? null : Number(order.amount),
|
||
status: Number(order.status),
|
||
statusText: STATUS_TEXT[Number(order.status)] || '未知',
|
||
/** 前端据此判断要不要继续轮询 */
|
||
pending: Number(order.status) === 0,
|
||
channel: order.channel || null,
|
||
transactionId: order.transactionId || null,
|
||
paidAt: order.paidAt || null,
|
||
expireBefore: order.expireBefore || null,
|
||
expireAfter: order.expireAfter || null,
|
||
remark: order.remark || null,
|
||
createdAt: order.createdAt || null,
|
||
}, extra);
|
||
}
|
||
}
|
||
|
||
/** 订单号:SO + 年月日时分秒 + 6 位随机(32 位以内) */
|
||
function generateOrderNo() {
|
||
const now = new Date();
|
||
const pad = num => String(num).padStart(2, '0');
|
||
const stamp = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}`
|
||
+ `${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;
|
||
return `SO${stamp}${String(crypto.randomInt(0, 1000000)).padStart(6, '0')}`;
|
||
}
|
||
|
||
module.exports = SubjectOrderService;
|