- 新表 admin_members(user_id 唯一、name、role、status、remark,软删):平台级管理员, 与「主体管理员」完全分开;迁移会把内置管理员(username=admin,没有则 id=1)先入表 - 鉴权:middleware/platform_admin.js —— admin_members 启用行 **或** INTERNAL_ADMIN_IDS(内置/救急入口), 其余一律 403 not_platform_admin;接口挂在 /api/web/admin/* - 主体管理:GET 所有主体(成员数/管理员/是否过期)+ PUT 改授权到期时间 (直接设 expireAt 或 extendDays 顺延),改完失效 subjectState 缓存,设备心跳立刻生效 - 订单管理:GET 所有订单(主体名/下单人/续期前后)+ POST 确认订单 —— 复用支付回调的 payNotify()(标记已支付 + 主体顺延 + 失效缓存 + 幂等),渠道记 manual - 管理员:GET/POST/DELETE /api/web/admin/members(按账号加人、不能删自己/最后一个); 软删行仍占唯一键,查重带 paranoid:false + restore 复用 - 前端:左侧菜单新增「平台管理」组(只有平台管理员可见,路由 meta.platformAdmin 守卫、 不需要选主体),新增 AdminSubjectsView / AdminOrdersView / AdminMembersView - 顶栏右侧新增「下载桌面端 / 下载 Android 扫码台」两个按钮(与权限无关,所有人都显示), 版本号读 /download/version.json 与 /download/android_client/version.json,未发布则置灰提示 - 测试:admin.test.js 12 例(403/表内/内置/列表/添加/重复/删自己/主体列表/改期限/顺延/订单/确认幂等) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
453 lines
17 KiB
JavaScript
453 lines
17 KiB
JavaScript
'use strict';
|
||
|
||
const { app, mock, assert } = require('egg-mock/bootstrap');
|
||
|
||
/** 假实例:update 时把字段同时合并回实例自身(present 读的是实例属性) */
|
||
const instance = data => {
|
||
const obj = {
|
||
toJSON: () => data,
|
||
update: async fields => {
|
||
Object.assign(data, fields);
|
||
Object.assign(obj, fields);
|
||
},
|
||
restore: async () => { data.deletedAt = null; obj.deletedAt = null; },
|
||
destroy: async () => { data.deletedAt = new Date(); obj.deletedAt = data.deletedAt; },
|
||
};
|
||
return Object.assign(obj, data);
|
||
};
|
||
|
||
const ADMIN = { id: 1, username: 'admin', nickname: '管理员', status: 1 };
|
||
const OTHER = { id: 2, username: 'ops', nickname: '运维', email: 'ops@example.com', phone: null, avatar: '', status: 1 };
|
||
|
||
/**
|
||
* 平台管理员(`/api/web/admin/*`)
|
||
*
|
||
* 重点:
|
||
* - 鉴权:`admin_members` 里启用中的行 **或** `config.internal.adminIds`(内置/救急),其余一律 403;
|
||
* - 管理员成员:列表(内置的也露出来)、添加(按账号找用户、已在名单里 409)、移除(不能删自己);
|
||
* - 主体:所有主体都能看,能直接改授权到期时间(直接设 / 顺延);
|
||
* - 订单:所有订单都能看,能「确认订单」——走支付回调的同一套 `payNotify`,重复确认幂等。
|
||
*/
|
||
describe('test/app/controller/admin.test.js', () => {
|
||
const BEARER = 'Bearer';
|
||
const token = () => app.createAnonymousContext().service.jwt.signUser(ADMIN);
|
||
const auth = () => ({ Authorization: `${BEARER} ${token()}` });
|
||
|
||
/** 默认:`admin_members` 里没有行、内置名单里也没有这个人 → 不是平台管理员 */
|
||
function mockModels(overrides = {}) {
|
||
mock(app, 'model', Object.assign({
|
||
User: {
|
||
async findByPk() { return instance(Object.assign({}, ADMIN)); },
|
||
async findOne() { return null; },
|
||
async findAll() { return []; },
|
||
},
|
||
AdminMember: {
|
||
async findOne() { return null; },
|
||
async findAll() { return []; },
|
||
async count() { return 0; },
|
||
async findByPk() { return null; },
|
||
async create(fields) { return instance(Object.assign({ id: 9 }, fields)); },
|
||
},
|
||
Subject: {
|
||
async findByPk() { return null; },
|
||
async findAndCountAll() { return { rows: [], count: 0 }; },
|
||
async findAll() { return []; },
|
||
},
|
||
// 平台管理员的名单表里查到的那一行(启用)
|
||
SubjectMember: {
|
||
async count() { return 0; },
|
||
async findAll() { return []; },
|
||
async findOne() { return null; },
|
||
},
|
||
SubjectOrder: {
|
||
async findAndCountAll() { return { rows: [], count: 0 }; },
|
||
async findOne() { return null; },
|
||
},
|
||
transaction: async () => ({
|
||
LOCK: { UPDATE: 'UPDATE' },
|
||
async commit() {},
|
||
async rollback() {},
|
||
}),
|
||
}, overrides));
|
||
}
|
||
|
||
/** `admin_members` 里给 ADMIN 放一行(= 表里登记的平台管理员) */
|
||
const enabledRow = (overrides = {}) => instance(Object.assign({
|
||
id: 1,
|
||
userId: 1,
|
||
name: '管理员',
|
||
role: 1,
|
||
status: 1,
|
||
remark: null,
|
||
deletedAt: null,
|
||
createdAt: new Date(),
|
||
}, overrides));
|
||
|
||
let originAdminIds = [];
|
||
beforeEach(() => {
|
||
originAdminIds = app.config.internal.adminIds;
|
||
// 默认把内置名单清空,只让 `admin_members` 生效(每个用例自己决定要不要加)
|
||
app.config.internal.adminIds = [];
|
||
});
|
||
afterEach(() => {
|
||
app.config.internal.adminIds = originAdminIds;
|
||
});
|
||
|
||
/** 让 ADMIN 成为平台管理员(表里有一行) */
|
||
function grantByTable(overrides = {}) {
|
||
mockModels(Object.assign({
|
||
AdminMember: {
|
||
async findOne() { return enabledRow(); },
|
||
async findAll() { return [ enabledRow() ]; },
|
||
async count() { return 1; },
|
||
async findByPk() { return enabledRow(); },
|
||
async create(fields) { return instance(Object.assign({ id: 9 }, fields)); },
|
||
},
|
||
}, overrides));
|
||
}
|
||
|
||
it('不是平台管理员:/api/web/admin/* 一律 403', async () => {
|
||
mockModels();
|
||
|
||
const res = await app.httpRequest().get('/api/web/admin/subjects').set(auth()).expect(403);
|
||
assert(res.body.status === 'not_platform_admin', JSON.stringify(res.body));
|
||
|
||
await app.httpRequest().get('/api/web/admin/members').set(auth()).expect(403);
|
||
await app.httpRequest().get('/api/web/admin/orders').set(auth()).expect(403);
|
||
await app.httpRequest().post('/api/web/admin/orders/SO1/confirm').set(auth()).send({}).expect(403);
|
||
});
|
||
|
||
it('平台管理员(表里登记):GET /api/web/admin/me 返回 admin=true', async () => {
|
||
grantByTable();
|
||
|
||
const res = await app.httpRequest().get('/api/web/admin/me').set(auth()).expect(200);
|
||
assert(res.body.data.admin === true, JSON.stringify(res.body));
|
||
assert(res.body.data.builtin === false, '表里登记的不算内置');
|
||
});
|
||
|
||
it('内置管理员(INTERNAL_ADMIN_IDS):表里没有也算平台管理员', async () => {
|
||
mockModels();
|
||
app.config.internal.adminIds = [ 1 ];
|
||
|
||
const res = await app.httpRequest().get('/api/web/admin/me').set(auth()).expect(200);
|
||
assert(res.body.data.admin === true && res.body.data.builtin === true, JSON.stringify(res.body));
|
||
});
|
||
|
||
it('GET /api/web/admin/members:表里的 + 内置名单(表里没有的)都列出来', async () => {
|
||
mockModels();
|
||
app.config.internal.adminIds = [ 1 ];
|
||
mock(app, 'model', {
|
||
User: {
|
||
async findByPk() { return instance(Object.assign({}, ADMIN)); },
|
||
async findAll() { return [ instance(Object.assign({}, ADMIN)), instance(Object.assign({}, OTHER)) ]; },
|
||
},
|
||
AdminMember: {
|
||
async findOne() { return null; },
|
||
async findAll() {
|
||
return [ instance({ id: 5, userId: 2, name: '运维', role: 2, status: 1, remark: null, createdAt: new Date() }) ];
|
||
},
|
||
async count() { return 1; },
|
||
},
|
||
});
|
||
|
||
const res = await app.httpRequest().get('/api/web/admin/members').set(auth()).expect(200);
|
||
const list = res.body.data.list;
|
||
assert(list.length === 2, JSON.stringify(list));
|
||
const builtin = list.find(item => item.builtin === true);
|
||
assert(builtin && builtin.userId === 1 && builtin.id === null, '内置管理员要露出来(id=null)');
|
||
const normal = list.find(item => item.userId === 2);
|
||
assert(normal && normal.id === 5 && normal.user.username === 'ops', JSON.stringify(normal));
|
||
});
|
||
|
||
it('POST /api/web/admin/members:账号不存在 → 404', async () => {
|
||
grantByTable();
|
||
|
||
const res = await app.httpRequest().post('/api/web/admin/members')
|
||
.set(auth()).send({ account: 'nobody' }).expect(404);
|
||
assert(/账号不存在/.test(res.body.message), JSON.stringify(res.body));
|
||
});
|
||
|
||
it('POST /api/web/admin/members:已经是管理员 → 409', async () => {
|
||
grantByTable();
|
||
mock(app, 'model', {
|
||
User: {
|
||
async findByPk() { return instance(Object.assign({}, ADMIN)); },
|
||
async findOne() { return instance(Object.assign({}, OTHER)); },
|
||
async findAll() { return []; },
|
||
},
|
||
AdminMember: {
|
||
async findOne({ where } = {}) {
|
||
// isAdmin(1) → 启用行;按 userId=2 查重 → 也当作已存在(启用)
|
||
return enabledRow(where && Number(where.userId) === 2 ? { id: 6, userId: 2, status: 1 } : {});
|
||
},
|
||
async findAll() { return [ enabledRow() ]; },
|
||
async count() { return 2; },
|
||
},
|
||
});
|
||
|
||
const res = await app.httpRequest().post('/api/web/admin/members')
|
||
.set(auth()).send({ account: 'ops' }).expect(409);
|
||
assert(/已经是平台管理员/.test(res.body.message), JSON.stringify(res.body));
|
||
});
|
||
|
||
it('POST /api/web/admin/members:正常添加 → 201(带账号信息,角色可选)', async () => {
|
||
grantByTable();
|
||
let created = null;
|
||
mock(app, 'model', {
|
||
User: {
|
||
async findByPk() { return instance(Object.assign({}, ADMIN)); },
|
||
async findOne() { return instance(Object.assign({}, OTHER)); },
|
||
async findAll() { return []; },
|
||
},
|
||
AdminMember: {
|
||
async findOne({ where } = {}) {
|
||
return where && Number(where.userId) === 2 ? null : enabledRow();
|
||
},
|
||
async findAll() { return [ enabledRow() ]; },
|
||
async count() { return 1; },
|
||
async create(fields) {
|
||
created = fields;
|
||
return instance(Object.assign({ id: 7 }, fields));
|
||
},
|
||
},
|
||
});
|
||
|
||
const res = await app.httpRequest().post('/api/web/admin/members')
|
||
.set(auth()).send({ account: 'ops', role: 2 }).expect(201);
|
||
|
||
assert(created && created.userId === 2 && created.role === 2, JSON.stringify(created));
|
||
assert(res.body.data.user.username === 'ops', JSON.stringify(res.body.data));
|
||
assert(res.body.data.roleText === '管理员', JSON.stringify(res.body.data));
|
||
});
|
||
|
||
it('DELETE /api/web/admin/members/:id:不能移除自己 → 409;移除别人 → 200', async () => {
|
||
grantByTable();
|
||
mock(app, 'model', {
|
||
User: {
|
||
async findByPk() { return instance(Object.assign({}, ADMIN)); },
|
||
async findAll() { return []; },
|
||
},
|
||
AdminMember: {
|
||
async findOne() { return enabledRow(); },
|
||
async findAll() { return [ enabledRow() ]; },
|
||
async count() { return 2; },
|
||
async findByPk(id) {
|
||
return Number(id) === 1
|
||
? enabledRow()
|
||
: instance({ id: 6, userId: 2, name: '运维', role: 2, status: 1, deletedAt: null });
|
||
},
|
||
},
|
||
});
|
||
|
||
const self = await app.httpRequest().delete('/api/web/admin/members/1').set(auth()).expect(409);
|
||
assert(/不能移除自己/.test(self.body.message), JSON.stringify(self.body));
|
||
|
||
const other = await app.httpRequest().delete('/api/web/admin/members/6').set(auth()).expect(200);
|
||
assert(other.body.data.id === 6 && other.body.data.userId === 2, JSON.stringify(other.body));
|
||
});
|
||
|
||
it('GET /api/web/admin/subjects:所有主体(keyword 走主体名/备注模糊)', async () => {
|
||
grantByTable();
|
||
let seenWhere = null;
|
||
// Sequelize 的 count({ group, raw }) 返回的是 [{ subject_id, count }] 这样的数组
|
||
mock(app, 'model', {
|
||
User: {
|
||
async findByPk() { return instance(Object.assign({}, ADMIN)); },
|
||
async findAll() { return [ instance({ id: 42, username: 'owner', nickname: '老板' }) ]; },
|
||
},
|
||
AdminMember: {
|
||
async findOne() { return enabledRow(); },
|
||
async findAll() { return [ enabledRow() ]; },
|
||
async count() { return 1; },
|
||
},
|
||
SubjectMember: { async count() { return [ { subject_id: 8, count: 2 } ]; } },
|
||
Subject: {
|
||
async findAndCountAll(options) {
|
||
seenWhere = options.where;
|
||
return {
|
||
rows: [ instance({
|
||
id: 8,
|
||
name: '某某仓库',
|
||
adminUserId: 42,
|
||
expireAt: new Date(Date.now() + 86400000),
|
||
status: 1,
|
||
remark: null,
|
||
}) ],
|
||
count: 1,
|
||
};
|
||
},
|
||
async findAll() { return [ instance({ id: 42, username: 'owner', nickname: '老板' }) ]; },
|
||
},
|
||
});
|
||
|
||
const res = await app.httpRequest()
|
||
.get(`/api/web/admin/subjects?keyword=${encodeURIComponent('仓库')}&pageSize=5`)
|
||
.set(auth()).expect(200);
|
||
const data = res.body.data;
|
||
assert(data.total === 1 && data.list.length === 1, JSON.stringify(data));
|
||
assert(data.list[0].memberCount === 2, '要带成员数');
|
||
assert(data.list[0].adminUser && data.list[0].adminUser.username === 'owner', JSON.stringify(data.list[0]));
|
||
assert(seenWhere && Array.isArray(seenWhere[Object.getOwnPropertySymbols(seenWhere)[0]]), 'keyword 要走 OR 模糊匹配');
|
||
});
|
||
|
||
it('PUT /api/web/admin/subjects/:id:直接设到期时间 / 顺延 / 时间格式不对 → 422', async () => {
|
||
grantByTable();
|
||
const subject = instance({
|
||
id: 8,
|
||
name: '某某仓库',
|
||
adminUserId: 42,
|
||
expireAt: new Date(Date.now() + 86400000),
|
||
status: 1,
|
||
remark: null,
|
||
});
|
||
mock(app, 'model', {
|
||
User: {
|
||
async findByPk() { return instance(Object.assign({}, ADMIN)); },
|
||
async findAll() { return []; },
|
||
},
|
||
AdminMember: {
|
||
async findOne() { return enabledRow(); },
|
||
async findAll() { return [ enabledRow() ]; },
|
||
async count() { return 1; },
|
||
},
|
||
Subject: {
|
||
async findByPk() { return subject; },
|
||
async findAndCountAll() { return { rows: [], count: 0 }; },
|
||
async findAll() { return []; },
|
||
},
|
||
});
|
||
|
||
const set = await app.httpRequest().put('/api/web/admin/subjects/8')
|
||
.set(auth()).send({ expireAt: '2027-01-01T00:00:00+08:00' }).expect(200);
|
||
assert(new Date(set.body.data.expireAt).toISOString() === '2026-12-31T16:00:00.000Z', JSON.stringify(set.body.data));
|
||
|
||
// 顺延:未过期 → 在原到期时间上加天数
|
||
const before = new Date(subject.expireAt).getTime();
|
||
const extended = await app.httpRequest().put('/api/web/admin/subjects/8')
|
||
.set(auth()).send({ extendDays: 30 }).expect(200);
|
||
assert(
|
||
new Date(extended.body.data.expireAt).getTime() === before + 30 * 86400000,
|
||
`顺延应按原到期时间相加:${extended.body.data.expireAt}`,
|
||
);
|
||
|
||
await app.httpRequest().put('/api/web/admin/subjects/8')
|
||
.set(auth()).send({ expireAt: '不是时间' }).expect(422);
|
||
});
|
||
|
||
it('GET /api/web/admin/orders:带主体名与下单人', async () => {
|
||
grantByTable();
|
||
mock(app, 'model', {
|
||
User: {
|
||
async findByPk() { return instance(Object.assign({}, ADMIN)); },
|
||
async findAll() { return [ instance({ id: 3, username: 'boss', nickname: '老板' }) ]; },
|
||
},
|
||
AdminMember: {
|
||
async findOne() { return enabledRow(); },
|
||
async findAll() { return [ enabledRow() ]; },
|
||
async count() { return 1; },
|
||
},
|
||
Subject: {
|
||
async findAll() { return [ instance({ id: 8, name: '某某仓库', expireAt: new Date(), status: 1 }) ]; },
|
||
},
|
||
SubjectOrder: {
|
||
async findAndCountAll() {
|
||
return {
|
||
rows: [ instance({
|
||
id: 100,
|
||
orderNo: 'SO20261029120000000001',
|
||
subjectId: 8,
|
||
userId: 3,
|
||
days: 30,
|
||
amount: 99,
|
||
status: 0,
|
||
channel: null,
|
||
createdAt: new Date(),
|
||
}) ],
|
||
count: 1,
|
||
};
|
||
},
|
||
},
|
||
});
|
||
|
||
const res = await app.httpRequest().get('/api/web/admin/orders?status=0').set(auth()).expect(200);
|
||
const row = res.body.data.list[0];
|
||
assert(row.orderNo === 'SO20261029120000000001', JSON.stringify(row));
|
||
assert(row.subjectName === '某某仓库' && row.userName === '老板', JSON.stringify(row));
|
||
assert(row.pending === true && row.statusText === '待支付', JSON.stringify(row));
|
||
});
|
||
|
||
it('POST /api/web/admin/orders/:orderNo/confirm:与支付回调同一套动作(续期 + 幂等)', async () => {
|
||
grantByTable();
|
||
const order = instance({
|
||
id: 100,
|
||
orderNo: 'SO20261029120000000001',
|
||
subjectId: 8,
|
||
userId: 3,
|
||
days: 30,
|
||
amount: 99,
|
||
status: 0,
|
||
channel: null,
|
||
transactionId: null,
|
||
paidAt: null,
|
||
expireBefore: null,
|
||
expireAfter: null,
|
||
remark: null,
|
||
createdAt: new Date(),
|
||
});
|
||
const subject = instance({
|
||
id: 8,
|
||
name: '某某仓库',
|
||
adminUserId: 42,
|
||
expireAt: new Date(Date.now() + 86400000),
|
||
status: 1,
|
||
});
|
||
const log = [];
|
||
mock(app, 'model', {
|
||
User: {
|
||
async findByPk() { return instance(Object.assign({}, ADMIN)); },
|
||
async findAll() { return []; },
|
||
},
|
||
AdminMember: {
|
||
async findOne() { return enabledRow(); },
|
||
async findAll() { return [ enabledRow() ]; },
|
||
async count() { return 1; },
|
||
},
|
||
Subject: {
|
||
async findByPk() { return subject; },
|
||
async findAll() { return []; },
|
||
},
|
||
SubjectOrder: {
|
||
async findOne() { return order; },
|
||
async findAndCountAll() { return { rows: [], count: 0 }; },
|
||
},
|
||
transaction: async () => ({
|
||
LOCK: { UPDATE: 'UPDATE' },
|
||
async commit() { log.push('commit'); },
|
||
async rollback() { log.push('rollback'); },
|
||
}),
|
||
});
|
||
|
||
const before = new Date(subject.expireAt).getTime();
|
||
const res = await app.httpRequest().post('/api/web/admin/orders/SO20261029120000000001/confirm')
|
||
.set(auth()).send({}).expect(200);
|
||
|
||
assert(res.body.data.duplicated === false, JSON.stringify(res.body));
|
||
assert(res.body.data.order.status === 1, JSON.stringify(res.body.data.order));
|
||
assert(res.body.data.order.channel === 'manual', '手工确认要记成 manual,便于和真实渠道区分');
|
||
assert(
|
||
new Date(subject.expireAt).getTime() === before + 30 * 86400000,
|
||
`主体应顺延 30 天,实际 ${subject.expireAt}`,
|
||
);
|
||
assert(log.includes('commit'), '要提交事务');
|
||
|
||
// 再点一次:幂等(不重复续期)
|
||
const again = await app.httpRequest().post('/api/web/admin/orders/SO20261029120000000001/confirm')
|
||
.set(auth()).send({}).expect(200);
|
||
assert(again.body.data.duplicated === true, JSON.stringify(again.body));
|
||
assert(
|
||
new Date(subject.expireAt).getTime() === before + 30 * 86400000,
|
||
'重复确认不能再加天数',
|
||
);
|
||
});
|
||
});
|