packServer/backend/test/app/controller/subject-order.test.js
liufumingren 3030f50cd3 续期改为选套餐下单,支付回调确认后才续期
数据库
- 新增 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>
2026-10-21 17:43:18 +08:00

265 lines
9.8 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
const { app, mock, assert } = require('egg-mock/bootstrap');
const crypto = require('crypto');
/** 假实例:update 时把字段同时合并回实例自身(present 读的是实例属性) */
const instance = data => {
const obj = {
toJSON: () => data,
update: async fields => {
Object.assign(data, fields);
Object.assign(obj, fields);
},
};
return Object.assign(obj, data);
};
const USER = { id: 1, username: 'admin', nickname: '管理员', status: 1 };
const SUBJECT_ID = 21;
/**
* 续期订单 + 支付回调
*
* 重点:
* - 下单只建单(待支付),不动期限;
* - 支付回调才续期,并**失效主体状态缓存**(设备心跳/上报立刻看到新期限);
* - 重复回调幂等(`duplicated: true`,不重复续期);
* - 配了回调密钥就校验签名。
*/
describe('test/app/controller/subject-order.test.js', () => {
const token = () => `Bearer ${app.createAnonymousContext().service.jwt.signUser(USER)}`;
const auth = () => ({ Authorization: token() });
const subjectRow = expireAt => instance({
id: SUBJECT_ID,
name: '测试主体',
adminUserId: 1,
status: 1,
expireAt,
});
const orderRow = (overrides = {}) => instance(Object.assign({
id: 100,
orderNo: 'SO20261020120000000001',
subjectId: SUBJECT_ID,
userId: 1,
days: 30,
amount: 99,
status: 0,
channel: 'mock',
transactionId: null,
paidAt: null,
expireBefore: new Date(Date.now() - 86400000),
expireAfter: null,
remark: null,
createdAt: new Date(),
}, overrides));
function fakeTransaction(log = []) {
return {
LOCK: { UPDATE: 'UPDATE' },
async commit() { log.push('commit'); },
async rollback() { log.push('rollback'); },
};
}
/** 套餐行(subject_plans):天数与定价都在库里,下单只认 planId */
const planRow = (overrides = {}) => instance(Object.assign({
id: 7,
code: 'p30',
name: '30 天',
days: 30,
price: 99,
originalPrice: null,
tag: null,
description: null,
sort: 10,
status: 1,
}, overrides));
function mockModels({ memberRole = 1, subject, order, plan, log } = {}) {
mock(app, 'model', {
User: { async findByPk() { return instance(Object.assign({}, USER)); } },
SubjectMember: {
async findOne() {
return instance({ id: 11, subjectId: SUBJECT_ID, userId: 1, name: '管理员', role: memberRole, status: 1 });
},
},
Subject: {
async findByPk() { return typeof subject === 'function' ? subject() : subject; },
},
SubjectPlan: {
async findOne() {
if (plan === undefined) return planRow();
return typeof plan === 'function' ? plan() : plan;
},
async findAll() { return [ planRow() ]; },
},
SubjectOrder: {
async create(fields) { return orderRow(Object.assign({ id: 101 }, fields)); },
async findOne() { return typeof order === 'function' ? order() : order; },
async findAndCountAll() { return { rows: [ orderRow() ], count: 1 }; },
},
transaction: async () => fakeTransaction(log),
});
}
beforeEach(() => {
app.createAnonymousContext().service.subjectState.clearLocalCache();
});
it('GET /api/web/subject-plans:返回上架套餐(含计算好的每天单价)', async () => {
mockModels();
const res = await app.httpRequest().get('/api/web/subject-plans').set(auth()).expect(200);
const list = res.body.data.list;
assert(list.length === 1, JSON.stringify(res.body));
assert(list[0].days === 30 && list[0].price === 99);
assert(list[0].pricePerDay === 3.3, `pricePerDay 应为 3.3,实际 ${list[0].pricePerDay}`);
});
it('POST /api/web/subjects/:id/orders:选套餐下单 → 201(待支付,不动期限,金额取套餐价)', async () => {
const subject = subjectRow(new Date(Date.now() - 86400000));
let subjectUpdated = 0;
const rawUpdate = subject.update;
subject.update = async (...args) => {
subjectUpdated++;
return rawUpdate(...args);
};
mockModels({ subject });
const res = await app.httpRequest().post(`/api/web/subjects/${SUBJECT_ID}/orders`)
.set(auth()).send({ planId: 7 }).expect(201);
assert(res.body.data.orderNo, JSON.stringify(res.body));
assert(res.body.data.status === 0 && res.body.data.days === 30);
assert(res.body.data.amount === 99, `金额应取套餐价 99,实际 ${res.body.data.amount}`);
assert(res.body.data.planId === 7 && res.body.data.planName === '30 天');
assert(subjectUpdated === 0, '下单不能改主体期限');
});
it('POST /api/web/subjects/:id/orders:前端传的金额被忽略(只认套餐价)', async () => {
mockModels({ subject: subjectRow(new Date(Date.now() + 86400000)) });
const res = await app.httpRequest().post(`/api/web/subjects/${SUBJECT_ID}/orders`)
.set(auth()).send({ planId: 7, amount: 0.01, days: 9999 }).expect(201);
assert(res.body.data.amount === 99, JSON.stringify(res.body));
assert(res.body.data.days === 30);
});
it('POST /api/web/subjects/:id/orders:普通成员不能下单(403)', async () => {
mockModels({
memberRole: 2,
subject: instance({ id: SUBJECT_ID, name: '别人的主体', adminUserId: 99, status: 1, expireAt: new Date(Date.now() + 86400000) }),
});
await app.httpRequest().post(`/api/web/subjects/${SUBJECT_ID}/orders`)
.set(auth()).send({ planId: 7 }).expect(403);
});
it('POST /api/web/subjects/:id/orders:没选套餐 / 套餐不存在 → 422', async () => {
mockModels({ subject: subjectRow(new Date(Date.now() + 86400000)) });
await app.httpRequest().post(`/api/web/subjects/${SUBJECT_ID}/orders`)
.set(auth()).send({}).expect(422);
mockModels({ subject: subjectRow(new Date(Date.now() + 86400000)), plan: null });
await app.httpRequest().post(`/api/web/subjects/${SUBJECT_ID}/orders`)
.set(auth()).send({ planId: 999 }).expect(422);
});
it('POST /api/web/subjects/:id/orders:套餐没配价格 → 422', async () => {
mockModels({
subject: subjectRow(new Date(Date.now() + 86400000)),
plan: planRow({ price: 0 }),
});
await app.httpRequest().post(`/api/web/subjects/${SUBJECT_ID}/orders`)
.set(auth()).send({ planId: 7 }).expect(422);
});
it('POST /api/pay/notify:支付成功后主体续期,且缓存失效(设备立刻看到新期限)', async () => {
const log = [];
const order = orderRow();
const subject = subjectRow(new Date(Date.now() - 86400000));
mockModels({ subject: () => subject, order: () => order, log });
// 先预热缓存:此刻是「已过期」
const before = await app.createAnonymousContext().service.subjectState.get(SUBJECT_ID);
assert(before.expired === true, JSON.stringify(before));
const res = await app.httpRequest().post('/api/pay/notify')
.send({ orderNo: order.orderNo, transactionId: 'TXN-1', amount: 99 })
.expect(200);
assert(res.body.data.duplicated === false, JSON.stringify(res.body));
assert(res.body.data.order.status === 1);
assert(log.includes('commit'));
const after = await app.createAnonymousContext().service.subjectState.get(SUBJECT_ID);
assert(after.expired === false, JSON.stringify(after));
assert(after.remainingSeconds > 29 * 86400, `续期 30 天后应剩余约 30 天,实际 ${after.remainingSeconds}`);
});
it('POST /api/pay/notify:重复回调幂等(不重复续期)', async () => {
const log = [];
const order = orderRow({ status: 1 });
mockModels({ subject: subjectRow(new Date(Date.now() + 86400000)), order: () => order, log });
const res = await app.httpRequest().post('/api/pay/notify')
.send({ orderNo: order.orderNo, amount: 99 })
.expect(200);
assert(res.body.data.duplicated === true, JSON.stringify(res.body));
assert(log.includes('rollback'), '已支付的订单应回滚事务,不做任何写入');
});
it('POST /api/pay/notify:金额不符 → 422;订单不存在 → 404', async () => {
mockModels({ subject: subjectRow(new Date(Date.now() + 86400000)), order: () => orderRow() });
await app.httpRequest().post('/api/pay/notify')
.send({ orderNo: 'SO20261020120000000001', amount: 1 })
.expect(422);
mockModels({ subject: subjectRow(new Date(Date.now() + 86400000)), order: () => null });
await app.httpRequest().post('/api/pay/notify')
.send({ orderNo: 'SO-NOT-EXIST' })
.expect(404);
});
it('POST /api/pay/notify:配了回调密钥必须带正确签名', async () => {
mock(app.config.pay, 'callbackSecret', 's3cret');
mock(app.config.pay, 'mock', false);
mockModels({ subject: subjectRow(new Date(Date.now() - 1000)), order: () => orderRow() });
await app.httpRequest().post('/api/pay/notify')
.send({ orderNo: 'SO20261020120000000001', transactionId: 'TXN-1', amount: 99 })
.expect(400);
const sign = crypto.createHmac('sha256', 's3cret')
.update('SO20261020120000000001\nTXN-1\n99')
.digest('hex');
await app.httpRequest().post('/api/pay/notify')
.set('X-Pay-Sign', sign)
.send({ orderNo: 'SO20261020120000000001', transactionId: 'TXN-1', amount: 99 })
.expect(200);
});
it('POST /api/internal/subject-orders/:orderNo/pay:运维模拟支付(内部令牌)', async () => {
mockModels({ subject: subjectRow(new Date(Date.now() - 1000)), order: () => orderRow() });
await app.httpRequest()
.post('/api/internal/subject-orders/SO20261020120000000001/pay')
.expect(401);
const res = await app.httpRequest()
.post('/api/internal/subject-orders/SO20261020120000000001/pay')
.set('X-Internal-Token', 'test-internal-token')
.expect(200);
assert(res.body.data.order.status === 1, JSON.stringify(res.body));
});
});