- 主体状态缓存(Redis 优先、进程内兜底):设备心跳与上报判断不再查库,续期/停用后主动失效 - 上报写接口按缓存校验期限:过期 403 subject_expired、停用 subject_disabled、主体缺失 subject_missing - 心跳与 /api/scanner/me 返回 subject 状态,桌面端据此暂停推送并在续期后自动补传积压 - 新增续期订单(subject_orders)与接口,支付回调 POST /api/pay/notify 幂等、支持 HMAC 签名, 另提供内部令牌模拟支付用于联调 - 顺带提交工作区中已完成的「登录协议」后端改动(agreement):与本次改动共用 router.js / config.default.js Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
192 lines
7.0 KiB
JavaScript
192 lines
7.0 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()` 成功才续期;
|
||
* - **幂等**:同一订单重复回调只续期一次(第二次返回 `duplicated: true`);
|
||
* - 续期基数与 `service.subject.update` 一致:未过期在原到期时间上顺延,已过期从当前时间起算。
|
||
*/
|
||
class SubjectOrderService extends Service {
|
||
get Order() {
|
||
return this.app.model.SubjectOrder;
|
||
}
|
||
|
||
get Subject() {
|
||
return this.app.model.Subject;
|
||
}
|
||
|
||
/** 创建订单(管理员):只建单,不动期限 */
|
||
async create({ subjectId, userId, days, amount, remark, channel = 'mock' } = {}) {
|
||
const { subject } = await this.ctx.service.subject.ensureAdmin(subjectId, userId);
|
||
|
||
const grantDays = Number(days);
|
||
if (!Number.isInteger(grantDays) || grantDays <= 0 || grantDays > 3650) {
|
||
this.ctx.throw(422, '续期天数必须是 1~3650 的整数');
|
||
}
|
||
|
||
const payCfg = this.config.pay || {};
|
||
const perDay = Number(payCfg.amountPerDay || 0);
|
||
let price = null;
|
||
if (amount !== undefined && amount !== null && amount !== '') {
|
||
price = Number(amount);
|
||
if (!Number.isFinite(price) || price < 0) this.ctx.throw(422, '金额不合法');
|
||
} else if (perDay > 0) {
|
||
price = Math.round(perDay * grantDays * 100) / 100;
|
||
}
|
||
|
||
const order = await this.Order.create({
|
||
orderNo: generateOrderNo(),
|
||
subjectId: Number(subject.id),
|
||
userId: Number(userId),
|
||
days: grantDays,
|
||
amount: price,
|
||
status: 0,
|
||
channel: channel || 'mock',
|
||
expireBefore: subject.expireAt,
|
||
remark: remark || null,
|
||
});
|
||
|
||
this.ctx.logger.info('[order] 用户 %s 为主体 %s 创建续期订单 %s(%s 天,金额 %s)',
|
||
userId, subject.id, order.orderNo, grantDays, price);
|
||
|
||
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),
|
||
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)] || '未知',
|
||
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;
|