- /api/web/stats 支持 ?period=today|yesterday:趋势改成按小时(0~23 点补零),
工作台榜只统计那一天;新增与维度无关的 todayCount / yesterdayCount(KPI 直接用)
- service/scan.hourlyCounts():MySQL 走 HOUR(scan_time) 分组,单测环境退化成内存聚合
- 修复首页统计 500:sequelize.col('scan_records.xxx') 在 FROM ... AS scanRecord 时会被 MySQL 判「未知列」,
单表查询改用未限定列名
- 前端首页:KPI 加「昨日扫码」(带较昨日环比)、图表维度切 今日/昨日/7/14/30 天,
新增 ScanTrendChart / WorkstationRankChart 两个纯 CSS 图表组件
- 卡片高度不一致修复:全局 .card + .card 的 margin-top 漏进网格容器,把第 2 张之后的卡片下推 16px;
网格内清零并加 grid-auto-rows: 1fr,图表正文区等高
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
392 lines
17 KiB
JavaScript
392 lines
17 KiB
JavaScript
'use strict';
|
||
|
||
const { app, mock, assert } = require('egg-mock/bootstrap');
|
||
const { Op } = require('sequelize');
|
||
|
||
/** 伪造的 sequelize 实例(toJSON + update 直接改同一份数据) */
|
||
const instance = (data) => Object.assign(
|
||
{
|
||
toJSON: () => data,
|
||
update: async (fields) => Object.assign(data, fields),
|
||
},
|
||
data,
|
||
);
|
||
|
||
/**
|
||
* web 主体端的数据接口:设备 / 扫码记录 / 首页统计 / 测试页模拟接口
|
||
*
|
||
* 重点断言:**范围一定限定在当前主体下**(前端传的 userId / subjectId 一律忽略),
|
||
* 别的数据一律 404(不泄露存在性)。
|
||
*
|
||
* 主体上下文由 `middleware/subject_auth.js` 解析 `X-Subject-Id`,
|
||
* 它要查 `SubjectMember.findOne` + `Subject.findByPk`,所以 mockModels 默认把这两个也备上。
|
||
*/
|
||
describe('test/app/controller/web.data.test.js', () => {
|
||
const me = { id: 1, username: 'admin', nickname: '管理员', status: 1 };
|
||
const SUBJECT_ID = 5;
|
||
|
||
const token = () => `Bearer ${app.createAnonymousContext().service.jwt.signUser(me)}`;
|
||
/** 带上令牌 + 主体 header */
|
||
const setAuth = (req) => req.set('Authorization', token()).set('X-Subject-Id', String(SUBJECT_ID));
|
||
|
||
/** 只替换用到的模型,User / 主体相关的固定返回当前用户与当前主体 */
|
||
function mockModels(models = {}) {
|
||
mock(app, 'model', Object.assign({
|
||
User: { async findByPk() { return instance(me); } },
|
||
SubjectMember: {
|
||
async findOne() {
|
||
return instance({ id: 11, subjectId: SUBJECT_ID, userId: 1, name: '管理员', role: 1, status: 1 });
|
||
},
|
||
},
|
||
Subject: {
|
||
async findByPk() {
|
||
return instance({
|
||
id: SUBJECT_ID,
|
||
name: '测试主体',
|
||
adminUserId: 1,
|
||
status: 1,
|
||
expireAt: new Date(Date.now() + 86400000),
|
||
});
|
||
},
|
||
},
|
||
}, models));
|
||
}
|
||
|
||
it('GET /api/web/devices:只列本主体的设备(忽略前端传的 userId / subjectId)', async () => {
|
||
mockModels({
|
||
Scanner: {
|
||
async findAndCountAll(options) {
|
||
assert(options.where.subjectId === SUBJECT_ID, '必须按当前主体过滤');
|
||
return { rows: [ instance({ id: 7, sn: 'SN-7', subjectId: SUBJECT_ID }) ], count: 1 };
|
||
},
|
||
},
|
||
});
|
||
|
||
const res = await setAuth(app.httpRequest().get('/api/web/devices?userId=2&subjectId=99')).expect(200);
|
||
assert(res.body.data.total === 1 && res.body.data.list[0].sn === 'SN-7', JSON.stringify(res.body));
|
||
|
||
// 没令牌 → 401
|
||
await app.httpRequest().get('/api/web/devices').expect(401);
|
||
// 有令牌没主体 → 400 subject_required
|
||
const missing = await app.httpRequest().get('/api/web/devices').set('Authorization', token()).expect(400);
|
||
assert(missing.body.status === 'subject_required', JSON.stringify(missing.body));
|
||
});
|
||
|
||
it('GET /api/web/devices/:id:别的主体的设备返回 404(不暴露存在性)', async () => {
|
||
mockModels({
|
||
Scanner: { async findByPk() { return instance({ id: 9, sn: 'SN-9', subjectId: 999 }); } },
|
||
});
|
||
|
||
await setAuth(app.httpRequest().get('/api/web/devices/9')).expect(404);
|
||
await setAuth(app.httpRequest().delete('/api/web/devices/9')).expect(404);
|
||
await setAuth(app.httpRequest().post('/api/web/devices/9/unbind')).expect(404);
|
||
});
|
||
|
||
it('GET /api/web/devices/:id/channels:看本主体设备的通道', async () => {
|
||
let queriedId = 0;
|
||
mockModels({
|
||
Scanner: { async findByPk() { return instance({ id: 9, sn: 'SN-9', subjectId: SUBJECT_ID }); } },
|
||
ScanChannel: {
|
||
async findAll(options) {
|
||
queriedId = options.where.scannerId;
|
||
return [ instance({ channelId: 'CH-1', channelName: '通道一' }) ];
|
||
},
|
||
},
|
||
});
|
||
|
||
const res = await setAuth(app.httpRequest().get('/api/web/devices/9/channels')).expect(200);
|
||
assert(queriedId === 9 && res.body.data.list[0].channelId === 'CH-1', JSON.stringify(res.body));
|
||
});
|
||
|
||
it('POST /api/web/devices/:id/unbind:解绑本主体的设备(清掉归属)', async () => {
|
||
let updated = null;
|
||
mockModels({
|
||
Scanner: {
|
||
async findByPk() {
|
||
return instance({
|
||
id: 9,
|
||
sn: 'SN-9',
|
||
subjectId: SUBJECT_ID,
|
||
update: async fields => { updated = fields; },
|
||
});
|
||
},
|
||
},
|
||
});
|
||
|
||
await setAuth(app.httpRequest().post('/api/web/devices/9/unbind')).expect(200);
|
||
assert(updated && updated.userId === null, JSON.stringify(updated));
|
||
});
|
||
|
||
it('DELETE /api/web/devices/:id:删除本主体的设备(软删除)', async () => {
|
||
let destroyed = 0;
|
||
mockModels({
|
||
Scanner: {
|
||
async findByPk() { return instance({ id: 9, sn: 'SN-9', subjectId: SUBJECT_ID }); },
|
||
async destroy({ where }) { destroyed = where.id; return 1; },
|
||
},
|
||
});
|
||
|
||
await setAuth(app.httpRequest().delete('/api/web/devices/9')).expect(200);
|
||
assert(destroyed === 9);
|
||
});
|
||
|
||
it('GET /api/web/records:只查本主体设备的记录(deviceId 越权 404)', async () => {
|
||
let seenWhere = null;
|
||
mockModels({
|
||
Scanner: {
|
||
async findAll() { return [ { id: 1 }, { id: 2 } ]; },
|
||
},
|
||
ScanRecord: {
|
||
async findAndCountAll(options) {
|
||
seenWhere = options.where;
|
||
return {
|
||
rows: [ instance({ id: 5, barcode: '6901', channelId: 'CH-1', scanTime: new Date(), scanner: { sn: 'SN-1' } }) ],
|
||
count: 1,
|
||
};
|
||
},
|
||
},
|
||
});
|
||
|
||
const res = await setAuth(app.httpRequest().get('/api/web/records?barcode=6901')).expect(200);
|
||
assert(seenWhere.subjectId === SUBJECT_ID, '应限定在当前主体范围内');
|
||
assert(res.body.data.list[0].deviceSn === 'SN-1', JSON.stringify(res.body.data.list[0]));
|
||
|
||
// 只查其中一台(本主体的)→ 范围收窄成那一台
|
||
await setAuth(app.httpRequest().get('/api/web/records?deviceId=2')).expect(200);
|
||
assert(seenWhere.scannerId[Op.in].join(',') === '2', '指定本主体设备时应只查这一台');
|
||
|
||
// 不属于本主体的设备 id(100)→ 404
|
||
await setAuth(app.httpRequest().get('/api/web/records?deviceId=100')).expect(404);
|
||
});
|
||
|
||
it('GET /api/web/stats:设备/通道/记录数都限定在当前主体范围内', async () => {
|
||
const wanted = [];
|
||
mockModels({
|
||
Scanner: {
|
||
async count({ where }) {
|
||
assert(where.subjectId === SUBJECT_ID);
|
||
return 2;
|
||
},
|
||
},
|
||
ScanChannel: {
|
||
async count({ where }) { wanted.push(where.subjectId); return 5; },
|
||
},
|
||
ScanRecord: {
|
||
async count({ where }) { wanted.push(where.subjectId); return 9; },
|
||
async findAndCountAll() { return { rows: [], count: 0 }; },
|
||
async findAll() { return []; },
|
||
},
|
||
Workstation: { async findAll() { return []; } },
|
||
});
|
||
|
||
const res = await setAuth(app.httpRequest().get('/api/web/stats')).expect(200);
|
||
assert(res.body.data.deviceCount === 2 && res.body.data.channelCount === 5 && res.body.data.recordCount === 9, JSON.stringify(res.body));
|
||
assert(wanted.every(item => item === SUBJECT_ID), `统计范围应限定在当前主体: ${wanted.join('|')}`);
|
||
});
|
||
|
||
it('GET /api/web/stats:近 N 天趋势补零 + 工作台打包数量(含未关联)', async () => {
|
||
const now = new Date();
|
||
const yesterday = new Date(now.getTime() - 86400000);
|
||
|
||
mockModels({
|
||
Scanner: { async count() { return 1; } },
|
||
ScanChannel: { async count() { return 1; } },
|
||
ScanRecord: {
|
||
async count() { return 6; },
|
||
async findAndCountAll() { return { rows: [], count: 0 }; },
|
||
async findAll(options) {
|
||
const attr = String(options.attributes[0]);
|
||
if (attr === 'scanTime') {
|
||
assert(options.where.subjectId === SUBJECT_ID, '趋势统计也必须限定当前主体');
|
||
return [
|
||
{ scanTime: now },
|
||
{ scanTime: now },
|
||
{ scanTime: yesterday },
|
||
];
|
||
}
|
||
if (attr === 'workstationId') {
|
||
assert(options.where.subjectId === SUBJECT_ID, '工作台统计也必须限定当前主体');
|
||
return [
|
||
{ workstationId: 3 },
|
||
{ workstationId: 3 },
|
||
{ workstationId: null },
|
||
{ workstationId: 99 }, // 不属于本主体的工作台 → 算「未关联」
|
||
];
|
||
}
|
||
throw new Error(`未预期的查询: ${attr}`);
|
||
},
|
||
},
|
||
Workstation: {
|
||
async findAll(options) {
|
||
assert(options.where.subjectId === SUBJECT_ID, '只统计本主体的工作台');
|
||
return [
|
||
instance({ id: 3, code: 'WS-3', name: '3号工作台', wsType: 1, status: 1, deletedAt: null }),
|
||
instance({ id: 4, code: 'WS-4', name: '4号工作台', wsType: 2, status: 1, deletedAt: null }),
|
||
];
|
||
},
|
||
},
|
||
});
|
||
|
||
const res = await setAuth(app.httpRequest().get('/api/web/stats?days=3')).expect(200);
|
||
const data = res.body.data;
|
||
|
||
assert(data.scanTrendDays === 3 && data.scanTrend.length === 3, JSON.stringify(data.scanTrend));
|
||
assert(data.scanTrend[2].count === 2 && data.scanTrend[1].count === 1 && data.scanTrend[0].count === 0, JSON.stringify(data.scanTrend));
|
||
assert(data.scanTrendTotal === 3, JSON.stringify(data.scanTrendTotal));
|
||
assert(
|
||
new Date(`${data.scanTrend[2].date}T00:00:00Z`) - new Date(`${data.scanTrend[1].date}T00:00:00Z`) === 86400000,
|
||
'日期应连续升序',
|
||
);
|
||
|
||
assert(data.workstationStats.length === 2, JSON.stringify(data.workstationStats));
|
||
assert(data.workstationStats[0].id === 3 && data.workstationStats[0].count === 2, JSON.stringify(data.workstationStats));
|
||
assert(data.workstationStats[1].id === 4 && data.workstationStats[1].count === 0, JSON.stringify(data.workstationStats));
|
||
assert(data.workstationUnassigned === 2, JSON.stringify(data.workstationUnassigned));
|
||
assert(data.period === '' && data.scanTrendUnit === 'day', JSON.stringify(data.period));
|
||
assert(data.todayCount === 2 && data.yesterdayCount === 1, `今日/昨日应单独给出:${data.todayCount}/${data.yesterdayCount}`);
|
||
});
|
||
|
||
it('GET /api/web/stats?period=today:今日按小时分布 + 今日/昨日两个数字', async () => {
|
||
const now = new Date();
|
||
const yesterday = new Date(now.getTime() - 86400000);
|
||
const records = [ { scanTime: now }, { scanTime: now }, { scanTime: yesterday } ];
|
||
|
||
mockModels({
|
||
Scanner: { async count() { return 1; } },
|
||
ScanChannel: { async count() { return 1; } },
|
||
ScanRecord: {
|
||
async count() { return 6; },
|
||
async findAndCountAll() { return { rows: [], count: 0 }; },
|
||
async findAll(options) {
|
||
const attr = String(options.attributes[0]);
|
||
if (attr === 'scanTime') {
|
||
assert(options.where.subjectId === SUBJECT_ID, '统计也必须限定当前主体');
|
||
// 按请求的时间窗过滤(今日按小时只该数到今天那几条)
|
||
const from = new Date(options.where.scanTime[Op.gte]).getTime();
|
||
const to = new Date(options.where.scanTime[Op.lt]).getTime();
|
||
return records.filter(row => row.scanTime.getTime() >= from && row.scanTime.getTime() < to);
|
||
}
|
||
if (attr === 'workstationId') {
|
||
return [ { workstationId: 3 }, { workstationId: 3 } ];
|
||
}
|
||
throw new Error(`未预期的查询: ${attr}`);
|
||
},
|
||
},
|
||
Workstation: {
|
||
async findAll() {
|
||
return [ instance({ id: 3, code: 'WS-3', name: '3号工作台', wsType: 1, status: 1, deletedAt: null }) ];
|
||
},
|
||
},
|
||
});
|
||
|
||
const res = await setAuth(app.httpRequest().get('/api/web/stats?period=today')).expect(200);
|
||
const data = res.body.data;
|
||
|
||
assert(data.period === 'today' && data.scanTrendUnit === 'hour', JSON.stringify(data.period));
|
||
assert(data.scanTrend.length === 24, `今天应有 24 个时段:${data.scanTrend.length}`);
|
||
assert(data.scanTrend[0].label === '00:00' && data.scanTrend[23].label === '23:00', JSON.stringify(data.scanTrend[0]));
|
||
assert(data.scanTrendTotal === 2, `今日维度只算今天:${data.scanTrendTotal}`);
|
||
assert(data.todayCount === 2 && data.yesterdayCount === 1, `${data.todayCount}/${data.yesterdayCount}`);
|
||
assert(data.workstationStats.length === 1 && data.workstationStats[0].count === 2, JSON.stringify(data.workstationStats));
|
||
});
|
||
|
||
it('GET /api/web/stats?period=yesterday:昨天按小时分布,今日/昨日数字不变', async () => {
|
||
const now = new Date();
|
||
const yesterday = new Date(now.getTime() - 86400000);
|
||
const records = [ { scanTime: now }, { scanTime: now }, { scanTime: yesterday } ];
|
||
|
||
mockModels({
|
||
Scanner: { async count() { return 1; } },
|
||
ScanChannel: { async count() { return 1; } },
|
||
ScanRecord: {
|
||
async count() { return 3; },
|
||
async findAndCountAll() { return { rows: [], count: 0 }; },
|
||
async findAll(options) {
|
||
const attr = String(options.attributes[0]);
|
||
if (attr === 'scanTime') {
|
||
const from = new Date(options.where.scanTime[Op.gte]).getTime();
|
||
const to = new Date(options.where.scanTime[Op.lt]).getTime();
|
||
return records.filter(row => row.scanTime.getTime() >= from && row.scanTime.getTime() < to);
|
||
}
|
||
if (attr === 'workstationId') return [];
|
||
throw new Error(`未预期的查询: ${attr}`);
|
||
},
|
||
},
|
||
Workstation: { async findAll() { return []; } },
|
||
});
|
||
|
||
const res = await setAuth(app.httpRequest().get('/api/web/stats?period=yesterday')).expect(200);
|
||
const data = res.body.data;
|
||
|
||
assert(data.period === 'yesterday' && data.scanTrendUnit === 'hour', JSON.stringify(data.period));
|
||
assert(data.scanTrend.length === 24, JSON.stringify(data.scanTrend.length));
|
||
assert(data.scanTrendTotal === 1, `昨日维度只算昨天:${data.scanTrendTotal}`);
|
||
assert(data.todayCount === 2 && data.yesterdayCount === 1, `${data.todayCount}/${data.yesterdayCount}`);
|
||
});
|
||
|
||
it('POST /api/web/test/device-login:以当前用户为确认人建/取设备并发长期令牌', async () => {
|
||
let created = null;
|
||
mockModels({
|
||
Scanner: {
|
||
async findOne() { return null; },
|
||
async create(data) {
|
||
created = data;
|
||
return instance(Object.assign({ id: 11 }, data));
|
||
},
|
||
async findByPk() {
|
||
return instance({ id: 11, sn: 'SN-TEST-01', userId: 1, subjectId: SUBJECT_ID, tokenJti: 'j-1', status: 1 });
|
||
},
|
||
},
|
||
});
|
||
|
||
const res = await setAuth(app.httpRequest().post('/api/web/test/device-login'))
|
||
.send({ sn: 'SN-TEST-01', name: '测试中控', vendor: 'ACME' })
|
||
.expect(200);
|
||
|
||
assert(created.userId === 1 && created.subjectId === SUBJECT_ID, '设备要挂到当前主体');
|
||
assert(created.sn === 'SN-TEST-01' && created.vendor === 'ACME', JSON.stringify(created));
|
||
assert(res.body.data.firstTime === true && res.body.data.tokenType === 'Bearer' && res.body.data.token, JSON.stringify(res.body.data));
|
||
const payload = app.createAnonymousContext().service.jwt.verifyScanner(res.body.data.token);
|
||
assert(payload.typ === 'scanner' && Number(payload.sub) === 11, JSON.stringify(payload));
|
||
});
|
||
|
||
it('POST /api/web/test/scan:用设备 SN + 长期 JWT 走完整校验(含 jti 比对)', async () => {
|
||
const sign = (extra = {}) => app.createAnonymousContext().service.jwt.signScanner(
|
||
{ id: 11, sn: 'SN-TEST-01' }, Object.assign({ jti: 'j-1' }, extra),
|
||
);
|
||
const scannerRow = () => instance({
|
||
id: 11, sn: 'SN-TEST-01', userId: 1, subjectId: SUBJECT_ID, status: 1, tokenJti: 'j-1',
|
||
});
|
||
let inserted = 0;
|
||
mockModels({
|
||
Scanner: { async findByPk() { return scannerRow(); } },
|
||
ScanChannel: {
|
||
async findAll() { return []; },
|
||
async create({ channelId, channelName }) { return instance({ id: 3, channelId, channelName }); },
|
||
async bulkCreate() {},
|
||
async update() {},
|
||
},
|
||
ScanRecord: {
|
||
async findAll() { return []; },
|
||
async bulkCreate(rows) { inserted = rows.length; },
|
||
},
|
||
});
|
||
|
||
const res = await setAuth(app.httpRequest().post('/api/web/test/scan'))
|
||
.send({ sn: 'SN-TEST-01', token: sign(), channelId: 'CH-9', barcode: '6901234567892' })
|
||
.expect(200);
|
||
|
||
assert(inserted === 1 && res.body.data.inserted === 1, JSON.stringify(res.body));
|
||
|
||
// SN 对不上 → 401;jti 过期(重新登录过)→ 401
|
||
await setAuth(app.httpRequest().post('/api/web/test/scan'))
|
||
.send({ sn: 'SN-OTHER', token: sign(), channelId: 'CH-9', barcode: 'x' }).expect(401);
|
||
await setAuth(app.httpRequest().post('/api/web/test/scan'))
|
||
.send({ sn: 'SN-TEST-01', token: sign({ jti: 'j-old' }), channelId: 'CH-9', barcode: 'x' }).expect(401);
|
||
|
||
// 用户令牌不能当设备令牌用
|
||
await setAuth(app.httpRequest().post('/api/web/test/scan'))
|
||
.send({ sn: 'SN-TEST-01', token: token().replace('Bearer ', ''), channelId: 'CH-9', barcode: 'x' }).expect(401);
|
||
});
|
||
});
|