packServer/backend/test/app/controller/subject-order.test.js
liufumingren 7b11f7052d feat(subject): 主体到期暂停设备上报,新增续期订单与支付回调
- 主体状态缓存(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>
2026-10-20 18:55:57 +08:00

203 lines
7.5 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'); },
};
}
function mockModels({ memberRole = 1, subject, order, 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; },
},
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('POST /api/web/subjects/:id/orders:管理员下单 → 201(待支付,不动期限)', async () => {
mockModels({ subject: subjectRow(new Date(Date.now() - 86400000)) });
const res = await app.httpRequest().post(`/api/web/subjects/${SUBJECT_ID}/orders`)
.set(auth()).send({ days: 30, amount: 99 }).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);
});
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({ days: 30 }).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({ days: 0 }).expect(422);
await app.httpRequest().post(`/api/web/subjects/${SUBJECT_ID}/orders`)
.set(auth()).send({ days: 3651 }).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));
});
});