packServer/backend/test/app/controller/subject-order.test.js
liufumingren 4704e10777 feat(首页/订单): 实时看板 + 待支付订单 2 小时自动失效
- 首页改成深色实时看板:今日/昨日维度、每 30 秒静默刷新(后台标签页跳过)、
  切维度/切回前台立刻刷;工作台榜按「占比」出条并同时给条数与百分比;
  支持原生全屏,`AppLayout :immersive` 隐藏左侧菜单与顶栏占满整屏
- 待支付订单 2 小时自动失效(`config.pay.orderTtl` / `PAY_ORDER_TTL`,默认 7200 秒):
  定时任务 `app/schedule/subject_order_expire.js` 每分钟扫一次,
  详情/列表/平台订单列表读到超时订单就地关单,支付回调入口再兜一层;
  超时后的渠道回调与手工确认一律 409;`present()` 下发 `payExpireAt / expired / pending`,
  前端展示支付截止时间、超时后停止轮询、平台端隐藏「确认订单」按钮
- 文档同步:根 README 与 backend/README(订单 TTL、看板刷新策略、全屏降级)

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-30 23:05:26 +08:00

319 lines
12 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;
const ORDER_TTL_MS = 2 * 3600 * 1000;
/**
* 续期订单 + 支付回调
*
* 重点:
* - 下单只建单(待支付),不动期限;
* - 支付回调才续期,并**失效主体状态缓存**(设备心跳/上报立刻看到新期限);
* - 重复回调幂等(`duplicated: true`,不重复续期);
* - 配了回调密钥就校验签名。
*/
describe('test/app/controller/subject-order.test.js', () => {
const token = () => `Bearer ${app.createAnonymousContext().service.jwt.signUser(USER)}`;
const auth = () => ({ Authorization: token() });
/** 记录 `SubjectOrder.update()` 的调用(超时关单) */
let orderUpdates = [];
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 }; },
async update(fields, options) {
orderUpdates.push({ fields, options });
return [ 1 ];
},
},
transaction: async () => fakeTransaction(log),
});
}
beforeEach(() => {
orderUpdates = [];
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/web/subjects/:id/orders:返回 2 小时支付截止时间(payExpireAt)', 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 }).expect(201);
const data = res.body.data;
const ttl = new Date(data.payExpireAt).getTime() - new Date(data.createdAt).getTime();
assert(ttl === ORDER_TTL_MS, `支付截止时间应为下单后 2 小时,实际 ${ttl}ms`);
assert(data.expired === false && data.pending === true, JSON.stringify(data));
});
it('GET /api/web/subjects/:id/orders/:orderNo:超过 2 小时未支付 → 自动关闭', async () => {
const order = orderRow({ createdAt: new Date(Date.now() - 3 * 3600 * 1000) });
mockModels({ subject: subjectRow(new Date(Date.now() + 86400000)), order: () => order });
const res = await app.httpRequest()
.get(`/api/web/subjects/${SUBJECT_ID}/orders/${order.orderNo}`)
.set(auth()).expect(200);
assert(res.body.data.status === 2, JSON.stringify(res.body));
assert(res.body.data.pending === false, JSON.stringify(res.body));
assert(orderUpdates.some(item => item.fields.status === 2), JSON.stringify(orderUpdates));
});
it('POST /api/pay/notify:超过 2 小时未支付 → 409,订单被关闭', async () => {
const order = orderRow({ createdAt: new Date(Date.now() - 3 * 3600 * 1000) });
mockModels({ subject: subjectRow(new Date(Date.now() + 86400000)), order: () => order });
await app.httpRequest().post('/api/pay/notify')
.send({ orderNo: order.orderNo, amount: 99 })
.expect(409);
assert(orderUpdates.some(item => item.fields.status === 2), JSON.stringify(orderUpdates));
});
it('定时任务 sweepExpired():批量关闭超时未支付订单', async () => {
mockModels({});
const closed = await app.createAnonymousContext().service.subjectOrder.sweepExpired();
assert(closed === 1, `应关闭 1 笔,实际 ${closed}`);
assert(orderUpdates.length === 1 && orderUpdates[0].fields.status === 2, JSON.stringify(orderUpdates));
assert(orderUpdates[0].options.where.status === 0, JSON.stringify(orderUpdates[0].options));
});
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));
});
});