feat(首页统计): 增加今日/昨日维度,修正统计 SQL 与卡片高度
- /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>
This commit is contained in:
parent
08d9ea103b
commit
98fae0f9d2
@ -2,25 +2,56 @@
|
||||
|
||||
const { Controller } = require('egg');
|
||||
|
||||
/** 支持的时间维度:'' = 近 N 天,today = 今日,yesterday = 昨日 */
|
||||
const PERIODS = [ 'today', 'yesterday' ];
|
||||
|
||||
/** 把 ?period= 归一化(不认识的一律当「近 N 天」) */
|
||||
function parsePeriod(value) {
|
||||
const period = String(value || '').trim().toLowerCase();
|
||||
return PERIODS.includes(period) ? period : '';
|
||||
}
|
||||
|
||||
/**
|
||||
* web 主体端:首页统计(`/api/web/stats`)
|
||||
*
|
||||
* 只统计**当前主体**的数据(设备数 / 通道数 / 扫码记录数 + 最近一条扫码记录),
|
||||
* 以及两张图用的聚合:
|
||||
* - `scanTrend`:所选维度每天的扫码数量(`?days=7|14|30`,默认 7,缺的天补 0);
|
||||
* 切到 **今日 / 昨日**(`?period=today|yesterday`)时改为**按小时**的时段分布(`scanTrendUnit='hour'`)
|
||||
* - `workstationStats`:同一维度内每个工作台的打包数量(按数量倒序)
|
||||
* - `todayCount` / `yesterdayCount`:今日(0 点起)/ 昨日(昨天 0~24 点)的扫码数,与维度无关,KPI 直接用
|
||||
*
|
||||
* 与运维视角的统计(`service.user.count()` 那种全站数字)区分开。
|
||||
*/
|
||||
class WebStatsController extends Controller {
|
||||
/** GET /api/web/stats(需要 apiAuth + subjectAuth) */
|
||||
/** GET /api/web/stats?days=7&period=today(需要 apiAuth + subjectAuth) */
|
||||
async index() {
|
||||
const { ctx } = this;
|
||||
const subjectId = ctx.state.subjectId;
|
||||
const days = Math.min(Math.max(Number(ctx.query.days) || 7, 1), 30);
|
||||
const period = parsePeriod(ctx.query.period);
|
||||
|
||||
const [ deviceCount, channelCount, recordCount, latest ] = await Promise.all([
|
||||
// 今日 = 现在这一刻所在的那天;昨日 = 往前推 24h 所在的那天
|
||||
const at = period === 'yesterday' ? new Date(Date.now() - 86400000) : new Date();
|
||||
const span = period ? 1 : days;
|
||||
// 「今日 / 昨日」两个数字要单独算,所以无论如何至少取 2 天
|
||||
const trendDays = Math.max(span, 2);
|
||||
|
||||
const [ deviceCount, channelCount, recordCount, latest, trend, stations, hourly ] = await Promise.all([
|
||||
ctx.service.scanner.count({ subjectId }),
|
||||
ctx.service.scan.countChannels({ subjectId }),
|
||||
ctx.service.scan.countRecords({ subjectId }),
|
||||
ctx.service.scan.listRecords({ subjectId, page: 1, pageSize: 1 }),
|
||||
ctx.service.scan.dailyCounts({ subjectId, days: trendDays }),
|
||||
ctx.service.scan.workstationCounts({ subjectId, days: span, endAt: at }),
|
||||
period ? ctx.service.scan.hourlyCounts({ subjectId, day: at }) : null,
|
||||
]);
|
||||
|
||||
const dailyCounts = trend.list;
|
||||
const todayCount = dailyCounts[dailyCounts.length - 1].count;
|
||||
const yesterdayCount = dailyCounts[dailyCounts.length - 2].count;
|
||||
const trendPoints = period ? hourly.list : dailyCounts.slice(-span);
|
||||
|
||||
const row = latest.list[0] || null;
|
||||
ctx.body = {
|
||||
ok: true,
|
||||
@ -35,6 +66,16 @@ class WebStatsController extends Controller {
|
||||
deviceSn: row.scanner ? row.scanner.sn : null,
|
||||
scanTime: row.scanTime,
|
||||
} : null,
|
||||
// '' = 近 N 天(按天);today / yesterday = 按小时
|
||||
period,
|
||||
scanTrendUnit: period ? 'hour' : 'day',
|
||||
scanTrendDays: span,
|
||||
scanTrend: trendPoints,
|
||||
scanTrendTotal: trendPoints.reduce((sum, item) => sum + item.count, 0),
|
||||
todayCount,
|
||||
yesterdayCount,
|
||||
workstationStats: stations.list,
|
||||
workstationUnassigned: stations.unassigned,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@ -2,6 +2,7 @@
|
||||
|
||||
const { Service } = require('egg');
|
||||
const { Op } = require('sequelize');
|
||||
const { VIRTUAL_CHANNEL_PREFIX, isVirtualChannelId } = require('../lib/virtual-channel');
|
||||
|
||||
/** 单次上报的条数上限(防止一次请求塞太多) */
|
||||
const MAX_BATCH = 500;
|
||||
@ -10,6 +11,11 @@ const MAX_CHANNEL_ID = 64;
|
||||
const MAX_CHANNEL_NAME = 128;
|
||||
const MAX_BARCODE = 255;
|
||||
|
||||
/** 统计按天聚合用的时区偏移(与 config.sequelize.timezone 的 +08:00 保持一致) */
|
||||
const STATS_TZ_OFFSET_MS = 8 * 60 * 60 * 1000;
|
||||
/** 趋势图最多回溯天数(防止被传个超大值拖死数据库) */
|
||||
const TREND_MAX_DAYS = 30;
|
||||
|
||||
/**
|
||||
* 同一个运单号的**合并窗口**(现场要求:24 小时)。
|
||||
*
|
||||
@ -96,6 +102,35 @@ function toInt(value) {
|
||||
return Number.isFinite(num) ? num : null;
|
||||
}
|
||||
|
||||
/** 趋势统计的天数(默认 7,限定 1 ~ 30) */
|
||||
function clampDays(days) {
|
||||
return Math.min(Math.max(Number(days) || 7, 1), TREND_MAX_DAYS);
|
||||
}
|
||||
|
||||
/** 某个时刻在 +08:00 下的日期键(YYYY-MM-DD) */
|
||||
function dayKey(date) {
|
||||
return new Date(date.getTime() + STATS_TZ_OFFSET_MS).toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
/** 含「今天」在内、连续 span 天的日期键(升序) */
|
||||
function dayKeys(endAt, span) {
|
||||
const keys = [];
|
||||
for (let i = span - 1; i >= 0; i--) {
|
||||
keys.push(dayKey(new Date(endAt.getTime() - i * 86400000)));
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
|
||||
/** 日期键当天 00:00(+08:00)对应的时刻 */
|
||||
function dayStart(key) {
|
||||
return new Date(`${key}T00:00:00+08:00`);
|
||||
}
|
||||
|
||||
/** 某个时刻在 +08:00 下的小时(0~23) */
|
||||
function hourOf(date) {
|
||||
return new Date(date.getTime() + STATS_TZ_OFFSET_MS).getUTCHours();
|
||||
}
|
||||
|
||||
class ScanService extends Service {
|
||||
get ScanChannel() {
|
||||
return this.app.model.ScanChannel;
|
||||
@ -213,10 +248,15 @@ class ScanService extends Service {
|
||||
attributes: [ 'channelId' ],
|
||||
where: { scannerId: scanner.id },
|
||||
});
|
||||
const staleIds = current.map(row => row.channelId).filter(channelId => !keep.has(channelId));
|
||||
// 虚拟通道 `CAM-`(纯摄像头工作台)由服务端维护,设备端列表里永远不会有 → 必须豁免,否则每次上报都会被删
|
||||
const staleIds = current
|
||||
.map(row => row.channelId)
|
||||
.filter(channelId => !keep.has(channelId) && !isVirtualChannelId(channelId));
|
||||
|
||||
const linkWhere = { scannerId: scanner.id };
|
||||
linkWhere.channelId = ids.length ? { [Op.notIn]: ids } : { [Op.ne]: null };
|
||||
linkWhere.channelId = ids.length
|
||||
? { [Op.and]: [{ [Op.notIn]: ids }, { [Op.notLike]: `${VIRTUAL_CHANNEL_PREFIX}%` }] }
|
||||
: { [Op.notLike]: `${VIRTUAL_CHANNEL_PREFIX}%` };
|
||||
unbound = await this.LinkScanChannel.destroy({ where: linkWhere });
|
||||
|
||||
if (staleIds.length) {
|
||||
@ -338,6 +378,8 @@ class ScanService extends Service {
|
||||
}
|
||||
|
||||
// 24 小时合并规则:同一运单只留一条,时间以**最后一次扫描**为准
|
||||
// (活跃工作台要在合并**之前**记下来:被合并覆盖的那几条不会再出现在 `fresh` 里)
|
||||
const activeWorkstations = fresh.slice();
|
||||
if (fresh.length) {
|
||||
const merged = await this.mergeExisting(fresh, scanner);
|
||||
result.updated += merged.updated;
|
||||
@ -368,6 +410,8 @@ class ScanService extends Service {
|
||||
result.unknownChannels = await this.touchChannels(scanner, channelIds, now);
|
||||
// 有数据上报即视为中控在线,刷新心跳
|
||||
await this.ctx.service.scanner.heartbeat(scanner, this.ctx.ip);
|
||||
// 上报了条码 = 工作台活跃:刷新「最后活跃时间」,工作台的自动下线定时任务按它计时
|
||||
await this.touchWorkstations(activeWorkstations, now);
|
||||
|
||||
this.ctx.logger.info(
|
||||
'[scan] 扫码上报 %s: 收到 %d / 入库 %d / 覆盖 %d / 去重 %d / 旧上报 %d / 非法 %d',
|
||||
@ -542,6 +586,30 @@ class ScanService extends Service {
|
||||
return missing;
|
||||
}
|
||||
|
||||
/**
|
||||
* 刷新相关工作台的「最后活跃时间」
|
||||
*
|
||||
* 工作台的自动下线定时任务(`app/schedule/workstation_idle_offline.js`)按这个字段判断 inactivity;
|
||||
* 只有**入库成功**(含覆盖)的记录才带 `workstationId`,所以这里直接取这批。
|
||||
*
|
||||
* 失败不影响扫码入库本身(顶多晚一点自动下线)。
|
||||
*/
|
||||
async touchWorkstations(rows, at = new Date()) {
|
||||
const ids = [ ...new Set((rows || []).map(row => Number(row.workstationId)).filter(id => Number.isInteger(id) && id > 0)) ];
|
||||
if (!ids.length) return 0;
|
||||
|
||||
try {
|
||||
const [ affected ] = await this.app.model.Workstation.update(
|
||||
{ lastActiveAt: at },
|
||||
{ where: { id: { [Op.in]: ids } } },
|
||||
);
|
||||
return Number(affected) || 0;
|
||||
} catch (err) {
|
||||
this.ctx.logger.warn('[scan] 刷新工作台最后活跃时间失败:%s', err.message);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/** 通道列表(分页;可按中控 / 关键字过滤),带所属中控 */
|
||||
async listChannels({ page = 1, pageSize = 20, scannerId, scannerIds, subjectId, keyword, status } = {}) {
|
||||
const size = Math.min(Number(pageSize) || 20, 100);
|
||||
@ -632,6 +700,175 @@ class ScanService extends Service {
|
||||
return this.ScanRecord.count({ where });
|
||||
}
|
||||
|
||||
/**
|
||||
* 按天统计扫码数(首页「近日扫描数量」趋势图)
|
||||
*
|
||||
* 日期口径按 +08:00 切(与 Sequelize 的 timezone 一致),没有记录的日期补 0,
|
||||
* 保证前端拿到的是**连续**的 N 天,直接画图。
|
||||
*
|
||||
* @param {object} params { subjectId, days = 7, endAt = new Date() }
|
||||
* @return {Promise<{ list: Array<{ date: string, count: number }>, total: number }>}
|
||||
*/
|
||||
async dailyCounts({ subjectId, days = 7, endAt = new Date() } = {}) {
|
||||
const span = clampDays(days);
|
||||
const keys = dayKeys(endAt, span);
|
||||
const start = dayStart(keys[0]);
|
||||
// 上界取「明天 0 点」,把未来时间的异常记录排除在区间外
|
||||
const end = new Date(start.getTime() + span * 86400000);
|
||||
const where = { subjectId: Number(subjectId), scanTime: { [Op.gte]: start, [Op.lt]: end } };
|
||||
|
||||
const sequelize = this.ScanRecord.sequelize || this.app.Sequelize;
|
||||
const counts = new Map();
|
||||
|
||||
if (sequelize && typeof sequelize.fn === 'function') {
|
||||
// ⚠️ 列名不要写成 `scan_records.xxx`:Sequelize 会给表起别名(scanRecord),
|
||||
// 用表名限定会被 MySQL 当成「未知列」直接报错(首页统计 500)。单表查询用未限定列名即可。
|
||||
const dayExpr = sequelize.fn('DATE_FORMAT', sequelize.col('scan_time'), '%Y-%m-%d');
|
||||
const rows = await this.ScanRecord.findAll({
|
||||
attributes: [[ dayExpr, 'day' ], [ sequelize.fn('COUNT', sequelize.col('id')), 'count' ]],
|
||||
where,
|
||||
group: [ dayExpr ],
|
||||
raw: true,
|
||||
});
|
||||
for (const row of rows) counts.set(String(row.day), Number(row.count) || 0);
|
||||
} else {
|
||||
// 单测环境没有 sequelize(插件是关掉的):退化成内存聚合
|
||||
const rows = await this.ScanRecord.findAll({ attributes: [ 'scanTime' ], where, raw: true });
|
||||
for (const row of rows) {
|
||||
const at = new Date(row.scanTime || row.scan_time);
|
||||
if (Number.isNaN(at.getTime())) continue;
|
||||
const key = dayKey(at);
|
||||
counts.set(key, (counts.get(key) || 0) + 1);
|
||||
}
|
||||
}
|
||||
|
||||
const list = keys.map(date => ({ date, count: counts.get(date) || 0 }));
|
||||
return { list, total: list.reduce((sum, item) => sum + item.count, 0) };
|
||||
}
|
||||
|
||||
/**
|
||||
* 按小时统计某一天的扫码数(首页「今日 / 昨日」维度)
|
||||
*
|
||||
* 日期口径同上(+08:00 切日),固定返回 0~23 点共 24 个点(没有记录的小时补 0),
|
||||
* 前端直接画成时段分布图。
|
||||
*
|
||||
* @param {object} params { subjectId, day = new Date()(任意落在目标那天的时刻) }
|
||||
* @return {Promise<{ date: string, list: Array<{ date: string, label: string, count: number }>, total: number }>}
|
||||
*/
|
||||
async hourlyCounts({ subjectId, day = new Date() } = {}) {
|
||||
const key = dayKey(day);
|
||||
const start = dayStart(key);
|
||||
const end = new Date(start.getTime() + 86400000);
|
||||
const where = { subjectId: Number(subjectId), scanTime: { [Op.gte]: start, [Op.lt]: end } };
|
||||
|
||||
const sequelize = this.ScanRecord.sequelize || this.app.Sequelize;
|
||||
const counts = new Map();
|
||||
|
||||
if (sequelize && typeof sequelize.fn === 'function') {
|
||||
const hourExpr = sequelize.fn('HOUR', sequelize.col('scan_time'));
|
||||
const rows = await this.ScanRecord.findAll({
|
||||
attributes: [[ hourExpr, 'hour' ], [ sequelize.fn('COUNT', sequelize.col('id')), 'count' ]],
|
||||
where,
|
||||
group: [ hourExpr ],
|
||||
raw: true,
|
||||
});
|
||||
for (const row of rows) counts.set(Number(row.hour), Number(row.count) || 0);
|
||||
} else {
|
||||
const rows = await this.ScanRecord.findAll({ attributes: [ 'scanTime' ], where, raw: true });
|
||||
for (const row of rows) {
|
||||
const at = new Date(row.scanTime || row.scan_time);
|
||||
if (Number.isNaN(at.getTime())) continue;
|
||||
const hour = hourOf(at);
|
||||
counts.set(hour, (counts.get(hour) || 0) + 1);
|
||||
}
|
||||
}
|
||||
|
||||
const list = [];
|
||||
for (let hour = 0; hour < 24; hour++) {
|
||||
const label = `${String(hour).padStart(2, '0')}:00`;
|
||||
list.push({ date: `${key} ${label}`, label, count: counts.get(hour) || 0 });
|
||||
}
|
||||
return { date: key, list, total: list.reduce((sum, item) => sum + item.count, 0) };
|
||||
}
|
||||
|
||||
/**
|
||||
* 按工作台统计扫码(打包)数量(首页「每个工作台打包数量」图)
|
||||
*
|
||||
* 统计口径:区间内扫码记录上冻结的 `workstation_id`(工作台被删/改过也不影响历史计数)。
|
||||
* 没有关联工作台的记录数单独返回(`unassigned`),避免图上数字和总数对不上。
|
||||
* 工作台按数量倒序,数量相同按 id 升序;已删除的工作台也会返回(带 `deleted` 标记)。
|
||||
*
|
||||
* @param {object} params { subjectId, days = 7, endAt = new Date() }
|
||||
* @return {Promise<{ list: Array<object>, unassigned: number }>}
|
||||
*/
|
||||
async workstationCounts({ subjectId, days = 7, endAt = new Date() } = {}) {
|
||||
const span = clampDays(days);
|
||||
const keys = dayKeys(endAt, span);
|
||||
const start = dayStart(keys[0]);
|
||||
const end = new Date(start.getTime() + span * 86400000);
|
||||
const where = { subjectId: Number(subjectId), scanTime: { [Op.gte]: start, [Op.lt]: end } };
|
||||
|
||||
const sequelize = this.ScanRecord.sequelize || this.app.Sequelize;
|
||||
const counts = new Map();
|
||||
let unassigned = 0;
|
||||
|
||||
const add = (workstationId, count) => {
|
||||
const id = Number(workstationId);
|
||||
if (!Number.isInteger(id) || id <= 0) {
|
||||
unassigned += count;
|
||||
return;
|
||||
}
|
||||
counts.set(id, (counts.get(id) || 0) + count);
|
||||
};
|
||||
|
||||
let rows;
|
||||
if (sequelize && typeof sequelize.fn === 'function') {
|
||||
rows = await this.ScanRecord.findAll({
|
||||
attributes: [
|
||||
[ sequelize.col('workstation_id'), 'workstationId' ],
|
||||
[ sequelize.fn('COUNT', sequelize.col('id')), 'count' ],
|
||||
],
|
||||
where,
|
||||
group: [ sequelize.col('workstation_id') ],
|
||||
raw: true,
|
||||
});
|
||||
} else {
|
||||
rows = await this.ScanRecord.findAll({ attributes: [ 'workstationId' ], where, raw: true });
|
||||
}
|
||||
for (const row of rows) {
|
||||
const id = row.workstationId === undefined ? row.workstation_id : row.workstationId;
|
||||
add(id, sequelize && typeof sequelize.fn === 'function' ? (Number(row.count) || 0) : 1);
|
||||
}
|
||||
|
||||
const stations = await this.app.model.Workstation.findAll({
|
||||
where: { subjectId: Number(subjectId) },
|
||||
attributes: [ 'id', 'code', 'name', 'wsType', 'status', 'deletedAt' ],
|
||||
order: [[ 'id', 'ASC' ]],
|
||||
paranoid: false, // 历史记录可能挂到已删除的工作台上,统计要算进去
|
||||
});
|
||||
|
||||
const list = stations.map(station => {
|
||||
const id = Number(station.id);
|
||||
const count = counts.get(id) || 0;
|
||||
counts.delete(id);
|
||||
return {
|
||||
id,
|
||||
code: station.code,
|
||||
name: station.name || '',
|
||||
wsType: Number(station.wsType) || 1,
|
||||
status: Number(station.status) || 0,
|
||||
deleted: Boolean(station.deletedAt),
|
||||
count,
|
||||
};
|
||||
});
|
||||
|
||||
// 记录上挂的工作台已经不属于当前主体(理论上不会发生):同样算作「未关联」
|
||||
for (const count of counts.values()) unassigned += count;
|
||||
|
||||
list.sort((a, b) => (b.count - a.count) || (a.id - b.id));
|
||||
return { list, unassigned };
|
||||
}
|
||||
|
||||
/** 某中控的通道(上报后回显用) */
|
||||
async findChannelsByScanner(scannerId) {
|
||||
const rows = await this.ScanChannel.findAll({
|
||||
|
||||
@ -198,7 +198,7 @@ describe('test/app/controller/scan.test.js', () => {
|
||||
await app.httpRequest().post('/api/scan/channels').set('Authorization', token()).send({}).expect(422);
|
||||
});
|
||||
|
||||
it('POST /api/scan/channels replace=true:列表里没有的通道被软删并解绑工作台', async () => {
|
||||
it('POST /api/scan/channels replace=true:列表里没有的通道被软删并解绑工作台(虚拟通道豁免)', async () => {
|
||||
let channelDestroy = null;
|
||||
let linkDestroy = null;
|
||||
mock(app, 'model', {
|
||||
@ -208,7 +208,8 @@ describe('test/app/controller/scan.test.js', () => {
|
||||
async findAll(options) {
|
||||
// 第一次:按 channelId 查已存在;第二次:查本中控当前全部通道
|
||||
if (options && options.attributes) {
|
||||
return [ instance({ id: 1, channelId: '1' }), instance({ id: 2, channelId: '2' }) ];
|
||||
// CAM-3 = 面单摄像头用的虚拟通道(设备端列表里永远没有它)
|
||||
return [ instance({ id: 1, channelId: '1' }), instance({ id: 2, channelId: '2' }), instance({ id: 3, channelId: 'CAM-3' }) ];
|
||||
}
|
||||
return [ instance({ id: 1, scannerId: 1, channelId: '1', channelName: '旧名字', deletedAt: null }) ];
|
||||
},
|
||||
@ -236,11 +237,13 @@ describe('test/app/controller/scan.test.js', () => {
|
||||
|
||||
assert(res.body.data.updated === 1 && res.body.data.removed === 1 && res.body.data.unbound === 3);
|
||||
assert(channelDestroy.where.scannerId === 1);
|
||||
assert(channelDestroy.where.channelId[Op.in].join(',') === '2', '只删不在列表里的通道');
|
||||
assert(linkDestroy.where.channelId[Op.notIn].join(',') === '1', '解绑不在列表里的工作台绑定');
|
||||
assert(channelDestroy.where.channelId[Op.in].join(',') === '2', '只删不在列表里的真实通道');
|
||||
const linkAnd = linkDestroy.where.channelId[Op.and];
|
||||
assert(linkAnd[0][Op.notIn].join(',') === '1', '解绑不在列表里的工作台绑定');
|
||||
assert(linkAnd[1][Op.notLike] === 'CAM-%', '虚拟通道不参与对账(否则每次上报都会被删掉)');
|
||||
});
|
||||
|
||||
it('POST /api/scan/channels replace=true + 空列表:允许上报并清空全部通道', async () => {
|
||||
it('POST /api/scan/channels replace=true + 空列表:允许上报并清空全部通道(虚拟通道豁免)', async () => {
|
||||
let channelDestroy = null;
|
||||
let linkDestroy = null;
|
||||
mock(app, 'model', {
|
||||
@ -271,7 +274,7 @@ describe('test/app/controller/scan.test.js', () => {
|
||||
|
||||
assert(res.body.data.received === 0 && res.body.data.removed === 2 && res.body.data.unbound === 4);
|
||||
assert(channelDestroy.where.channelId[Op.in].sort().join(',') === '1,2', '两条都应被软删');
|
||||
assert(linkDestroy.where.channelId[Op.ne] === null, '空列表 = 解绑该中控全部工作台绑定');
|
||||
assert(linkDestroy.where.channelId[Op.notLike] === 'CAM-%', '空列表 = 解绑该中控全部真实绑定,虚拟通道保留');
|
||||
});
|
||||
|
||||
it('POST /api/scan/records 首次上报:入库并刷新通道/心跳', async () => {
|
||||
|
||||
@ -174,7 +174,9 @@ describe('test/app/controller/web.data.test.js', () => {
|
||||
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);
|
||||
@ -182,6 +184,146 @@ describe('test/app/controller/web.data.test.js', () => {
|
||||
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({
|
||||
|
||||
@ -56,6 +56,28 @@ export interface ScanRecord {
|
||||
deviceName?: string | null;
|
||||
}
|
||||
|
||||
/** 首页统计:近 N 天每天的扫码数 */
|
||||
export interface ScanTrendPoint {
|
||||
/** 按天:YYYY-MM-DD;按小时:`YYYY-MM-DD HH:00`(+08:00 口径) */
|
||||
date: string;
|
||||
/** 按小时维度才有:`HH:00`(画横轴用) */
|
||||
label?: string;
|
||||
count: number;
|
||||
}
|
||||
|
||||
/** 首页统计:近 N 天某个工作台的打包数量 */
|
||||
export interface WorkstationPackStat {
|
||||
id: number;
|
||||
code: string;
|
||||
name: string;
|
||||
/** 1 散单工作台 2 团购工作台 */
|
||||
wsType: number;
|
||||
status: number;
|
||||
/** 工作台已被删除(历史记录仍计入) */
|
||||
deleted: boolean;
|
||||
count: number;
|
||||
}
|
||||
|
||||
/** 首页统计 */
|
||||
export interface Stats {
|
||||
deviceCount: number;
|
||||
@ -68,6 +90,24 @@ export interface Stats {
|
||||
deviceSn?: string | null;
|
||||
scanTime: string;
|
||||
} | null;
|
||||
/** 所选时间维度:'' = 近 N 天(按天),'today' / 'yesterday' = 今日 / 昨日(按小时) */
|
||||
period: '' | 'today' | 'yesterday';
|
||||
/** 趋势粒度:按天 or 按小时 */
|
||||
scanTrendUnit: 'day' | 'hour';
|
||||
/** 趋势跨度(按天 = N;按小时 = 1) */
|
||||
scanTrendDays: number;
|
||||
/** 所选维度内的扫码分布(按天升序 / 按小时 0~23 点,缺的补 0) */
|
||||
scanTrend: ScanTrendPoint[];
|
||||
/** 所选维度内的扫码总数 */
|
||||
scanTrendTotal: number;
|
||||
/** 今日扫码(今天 0 点起,与所选维度无关) */
|
||||
todayCount: number;
|
||||
/** 昨日扫码(昨天 0~24 点,与所选维度无关) */
|
||||
yesterdayCount: number;
|
||||
/** 所选维度内每个工作台的打包数量(按数量倒序) */
|
||||
workstationStats: WorkstationPackStat[];
|
||||
/** 所选维度内没有关联工作台的扫码数 */
|
||||
workstationUnassigned: number;
|
||||
}
|
||||
|
||||
/** 测试页:模拟设备扫码登录的返回(设备信息 + 长期 JWT) */
|
||||
|
||||
@ -15,9 +15,16 @@ import type {
|
||||
WechatCodeStatus,
|
||||
} from '@/api/types';
|
||||
|
||||
/** 首页统计 */
|
||||
export function fetchStats(): Promise<Stats> {
|
||||
return api.get<Stats>('/api/web/stats');
|
||||
/**
|
||||
* 首页统计
|
||||
*
|
||||
* @param params days:近 N 天(趋势 / 工作台榜的天数,后端限定 1~30,默认 7);
|
||||
* period:`today` / `yesterday` 切到「今日 / 昨日」维度(趋势改成按小时)
|
||||
*/
|
||||
export function fetchStats(params: { days?: number; period?: '' | 'today' | 'yesterday' } = {}): Promise<Stats> {
|
||||
const query = new URLSearchParams({ days: String(params.days ?? 7) });
|
||||
if (params.period) query.set('period', params.period);
|
||||
return api.get<Stats>(`/api/web/stats?${query}`);
|
||||
}
|
||||
|
||||
/** 我的设备列表 */
|
||||
@ -112,3 +119,84 @@ export function confirmWechatLogin(codeOrSpm: string): Promise<{ status: string;
|
||||
const body = codeOrSpm.includes('.') ? { spm: codeOrSpm } : { code: codeOrSpm };
|
||||
return api.post<{ status: string; code: string; user: { id: number } }>('/api/wechat/confirm', body);
|
||||
}
|
||||
|
||||
// ---------------- 微信登录网关(扫码登录 / 绑定微信) ----------------
|
||||
// 二维码内容由网关下发(`pageUrl`),本地只负责画图(`qrUrl`)与长轮询结果。
|
||||
|
||||
/** 扫码二维码:`state` 是本地会话 id,用来长轮询结果 */
|
||||
export interface WxQrTicket {
|
||||
state: string;
|
||||
pageUrl: string;
|
||||
qrUrl: string;
|
||||
expiresIn: number;
|
||||
}
|
||||
|
||||
/** 扫码结果(长轮询) */
|
||||
export interface WxQrStatus {
|
||||
/** pending 还在等扫码 / confirmed 成功 / failed 失败(附 message)/ expired 二维码已过期 */
|
||||
status: 'pending' | 'confirmed' | 'failed' | 'expired';
|
||||
message?: string;
|
||||
}
|
||||
|
||||
/** 申请「登录」二维码(公开接口;没开通网关时后端返回 503) */
|
||||
export function createWechatLoginQr(): Promise<WxQrTicket> {
|
||||
return api.post<WxQrTicket>('/api/web/auth/wechat-gateway/qrcode', {}, { auth: false });
|
||||
}
|
||||
|
||||
/** 长轮询登录结果;确认后带 `token` + `user`(一份完整登录态) */
|
||||
export interface WxLoginStatus extends WxQrStatus {
|
||||
token?: string;
|
||||
tokenType?: string;
|
||||
expiresIn?: number | string;
|
||||
user?: {
|
||||
id: number;
|
||||
username: string;
|
||||
nickname?: string | null;
|
||||
email?: string | null;
|
||||
phone?: string | null;
|
||||
avatar?: string | null;
|
||||
};
|
||||
}
|
||||
|
||||
/** 长轮询登录结果(`wait` 秒内有人确认就立即返回) */
|
||||
export function fetchWechatLoginStatus(state: string, wait = 0, signal?: AbortSignal): Promise<WxLoginStatus> {
|
||||
const query = new URLSearchParams({ state });
|
||||
if (wait) query.set('wait', String(wait));
|
||||
return api.get<WxLoginStatus>(`/api/web/auth/wechat-gateway/login?${query.toString()}`, { auth: false, signal });
|
||||
}
|
||||
|
||||
/** 已绑定的微信 */
|
||||
export interface WxBinding {
|
||||
id: number;
|
||||
openid: string;
|
||||
unionid?: string | null;
|
||||
bindScene?: string | null;
|
||||
lastLoginAt?: string | null;
|
||||
createdAt?: string | null;
|
||||
}
|
||||
|
||||
/** 申请「绑定微信」二维码(需登录) */
|
||||
export function createWechatBindQr(): Promise<WxQrTicket> {
|
||||
return api.post<WxQrTicket>('/api/web/me/wechat/qrcode');
|
||||
}
|
||||
|
||||
/** 长轮询绑定结果 */
|
||||
export interface WxBindStatus extends WxQrStatus {
|
||||
binding?: WxBinding;
|
||||
}
|
||||
|
||||
export function fetchWechatBindStatus(state: string, wait = 0, signal?: AbortSignal): Promise<WxBindStatus> {
|
||||
const query = new URLSearchParams({ state });
|
||||
if (wait) query.set('wait', String(wait));
|
||||
return api.get<WxBindStatus>(`/api/web/me/wechat/status?${query.toString()}`, { signal });
|
||||
}
|
||||
|
||||
/** 当前账号绑定的微信(`enabled=false` 表示服务端没配网关) */
|
||||
export function fetchWechatBindings(): Promise<{ list: WxBinding[]; enabled: boolean }> {
|
||||
return api.get<{ list: WxBinding[]; enabled: boolean }>('/api/web/me/wechat/bindings');
|
||||
}
|
||||
|
||||
/** 解绑某个微信 */
|
||||
export function unbindWechat(id: number): Promise<{ id: number }> {
|
||||
return api.del<{ id: number }>(`/api/web/me/wechat/bindings/${id}`);
|
||||
}
|
||||
|
||||
126
frontend/src/components/ScanTrendChart.vue
Normal file
126
frontend/src/components/ScanTrendChart.vue
Normal file
@ -0,0 +1,126 @@
|
||||
<script setup lang="ts">
|
||||
/** 首页「近日扫描数量」柱状图(纯 CSS,不引图表库) */
|
||||
import { computed } from 'vue';
|
||||
import type { ScanTrendPoint } from '@/api/types';
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
points: ScanTrendPoint[];
|
||||
height?: number;
|
||||
}>(), { height: 180 });
|
||||
|
||||
const max = computed(() => Math.max(1, ...props.points.map(item => item.count)));
|
||||
/** 点数不多时直接显示数值;太多就只在最后一格和 hover 时显示 */
|
||||
const showValues = computed(() => props.points.length <= 10);
|
||||
/** 30 天 / 24 小时这类密集场景隔几格显示一个刻度,避免挤在一起 */
|
||||
const labelStep = computed(() => {
|
||||
const total = props.points.length;
|
||||
if (total >= 24) return 4;
|
||||
return total > 14 ? 5 : 1;
|
||||
});
|
||||
|
||||
const bars = computed(() => props.points.map((item, index) => ({
|
||||
date: item.date,
|
||||
count: item.count,
|
||||
label: item.label ?? item.date.slice(5).replace('-', '/'),
|
||||
isLast: index === props.points.length - 1,
|
||||
labelVisible: index === props.points.length - 1 || (props.points.length - 1 - index) % labelStep.value === 0,
|
||||
height: item.count > 0 ? Math.max((item.count / max.value) * 100, 2) : 0,
|
||||
})));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="trend-wrap">
|
||||
<div class="trend" :style="{ height: `${height}px` }">
|
||||
<div
|
||||
v-for="bar in bars"
|
||||
:key="bar.date"
|
||||
class="col"
|
||||
:class="{ 'is-last': bar.isLast }"
|
||||
:title="`${bar.date}:${bar.count} 条`"
|
||||
>
|
||||
<span
|
||||
v-if="bar.count > 0"
|
||||
class="value"
|
||||
:class="{ always: showValues }"
|
||||
:style="{ bottom: `calc(${bar.height}% + 4px)` }"
|
||||
>{{ bar.count }}</span>
|
||||
<span class="bar" :style="{ height: `${bar.height}%` }" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="axis">
|
||||
<span v-for="bar in bars" :key="bar.date" class="tick">
|
||||
{{ bar.labelVisible ? bar.label : '' }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.trend-wrap {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
.trend {
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
gap: 4px;
|
||||
padding: 0 2px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
background-image: linear-gradient(to top, rgba(37, 99, 235, 0.06), transparent 70%);
|
||||
border-radius: 6px 6px 0 0;
|
||||
}
|
||||
.col {
|
||||
position: relative;
|
||||
flex: 1 1 0;
|
||||
height: 100%;
|
||||
min-width: 0;
|
||||
}
|
||||
.bar {
|
||||
position: absolute;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
border-radius: 4px 4px 0 0;
|
||||
background: linear-gradient(to top, rgba(37, 99, 235, 0.45), rgba(37, 99, 235, 0.75));
|
||||
transition: height 0.25s ease, background 0.15s ease;
|
||||
}
|
||||
.col:hover .bar {
|
||||
background: linear-gradient(to top, var(--brand), #60a5fa);
|
||||
}
|
||||
.is-last .bar {
|
||||
background: linear-gradient(to top, var(--brand-dark), var(--brand));
|
||||
}
|
||||
.value {
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
font-size: 11px;
|
||||
color: var(--text-muted);
|
||||
white-space: nowrap;
|
||||
opacity: 0;
|
||||
transition: opacity 0.15s ease;
|
||||
}
|
||||
.value.always,
|
||||
.col:hover .value {
|
||||
opacity: 1;
|
||||
}
|
||||
.col.is-last .value {
|
||||
color: var(--brand);
|
||||
font-weight: 600;
|
||||
}
|
||||
.axis {
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
padding: 0 2px;
|
||||
}
|
||||
.tick {
|
||||
flex: 1 1 0;
|
||||
min-width: 0;
|
||||
text-align: center;
|
||||
font-size: 11px;
|
||||
color: var(--text-muted);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
}
|
||||
</style>
|
||||
129
frontend/src/components/WorkstationRankChart.vue
Normal file
129
frontend/src/components/WorkstationRankChart.vue
Normal file
@ -0,0 +1,129 @@
|
||||
<script setup lang="ts">
|
||||
/** 首页「每个工作台打包数量」排行榜(横向条形图,纯 CSS) */
|
||||
import { computed } from 'vue';
|
||||
import type { WorkstationPackStat } from '@/api/types';
|
||||
|
||||
interface Row {
|
||||
key: string;
|
||||
label: string;
|
||||
code?: string;
|
||||
count: number;
|
||||
deleted?: boolean;
|
||||
muted?: boolean;
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
items: WorkstationPackStat[];
|
||||
/** 区间内没有关联工作台的扫码数 */
|
||||
unassigned?: number;
|
||||
/** 最多显示几个工作台,其余合并成「其他」 */
|
||||
limit?: number;
|
||||
}>(), { unassigned: 0, limit: 8 });
|
||||
|
||||
const rows = computed<Row[]>(() => {
|
||||
const list: Row[] = props.items.slice(0, props.limit).map(item => ({
|
||||
key: `ws-${item.id}`,
|
||||
label: item.name || item.code,
|
||||
code: item.name ? item.code : '',
|
||||
count: item.count,
|
||||
deleted: item.deleted,
|
||||
}));
|
||||
|
||||
const rest = props.items.slice(props.limit);
|
||||
if (rest.length) {
|
||||
list.push({
|
||||
key: 'rest',
|
||||
label: `其他 ${rest.length} 个工作台`,
|
||||
count: rest.reduce((sum, item) => sum + item.count, 0),
|
||||
muted: true,
|
||||
});
|
||||
}
|
||||
if (props.unassigned > 0) {
|
||||
list.push({ key: 'unassigned', label: '未关联工作台', count: props.unassigned, muted: true });
|
||||
}
|
||||
return list;
|
||||
});
|
||||
|
||||
const max = computed(() => Math.max(1, ...rows.value.map(row => row.count)));
|
||||
const width = (count: number) => (count > 0 ? `${Math.max((count / max.value) * 100, 2)}%` : '0');
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ul class="rank">
|
||||
<li v-for="row in rows" :key="row.key" class="row">
|
||||
<span class="label" :title="row.label">
|
||||
<span class="name">{{ row.label }}</span>
|
||||
<span v-if="row.code" class="code">{{ row.code }}</span>
|
||||
<span v-if="row.deleted" class="tag">已删除</span>
|
||||
</span>
|
||||
<span class="track">
|
||||
<span class="fill" :class="{ muted: row.muted }" :style="{ width: width(row.count) }" />
|
||||
</span>
|
||||
<b class="count">{{ row.count }}</b>
|
||||
</li>
|
||||
</ul>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.rank {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
.row {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(96px, 150px) 1fr 48px;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
.label {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 6px;
|
||||
min-width: 0;
|
||||
font-size: 13px;
|
||||
}
|
||||
.name {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.code {
|
||||
color: var(--text-muted);
|
||||
font-size: 11px;
|
||||
flex: none;
|
||||
}
|
||||
.tag {
|
||||
flex: none;
|
||||
font-size: 10px;
|
||||
color: var(--danger);
|
||||
background: #fef2f2;
|
||||
border: 1px solid #fecaca;
|
||||
border-radius: 4px;
|
||||
padding: 0 4px;
|
||||
}
|
||||
.track {
|
||||
height: 10px;
|
||||
border-radius: 999px;
|
||||
background: #eef1f6;
|
||||
overflow: hidden;
|
||||
}
|
||||
.fill {
|
||||
display: block;
|
||||
height: 100%;
|
||||
border-radius: 999px;
|
||||
background: linear-gradient(to right, var(--brand), #60a5fa);
|
||||
transition: width 0.3s ease;
|
||||
}
|
||||
.fill.muted {
|
||||
background: #c7ccd6;
|
||||
}
|
||||
.count {
|
||||
text-align: right;
|
||||
font-size: 13px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
</style>
|
||||
@ -1,8 +1,17 @@
|
||||
<script setup lang="ts">
|
||||
/** 首页:只统计「当前主体」的数据(设备 / 通道 / 扫码记录 + 最近一次扫码) */
|
||||
/**
|
||||
* 首页:只统计「当前主体」的数据
|
||||
*
|
||||
* - KPI:设备 / 通道 / 扫码记录 / **今日扫码** / **昨日扫码**(后两张固定显示,与所选维度无关)
|
||||
* - 图表:近 N 天扫码趋势 + 每个工作台打包数量;维度可切 **今日 / 昨日 / 7 / 14 / 30 天**
|
||||
* (今日 / 昨日 换成**按小时**的时段分布,工作台榜也只统计那一天)
|
||||
* - 最近一次扫码
|
||||
*/
|
||||
import { computed, onMounted, ref } from 'vue';
|
||||
import { RouterLink, useRoute } from 'vue-router';
|
||||
import AppLayout from '@/components/AppLayout.vue';
|
||||
import ScanTrendChart from '@/components/ScanTrendChart.vue';
|
||||
import WorkstationRankChart from '@/components/WorkstationRankChart.vue';
|
||||
import { ApiError } from '@/api/client';
|
||||
import { fetchStats } from '@/api/web';
|
||||
import type { Stats } from '@/api/types';
|
||||
@ -11,9 +20,23 @@ import { formatTime, fromNow } from '@/utils/format';
|
||||
|
||||
const route = useRoute();
|
||||
|
||||
/** 可选的时间维度:今日 / 昨日(按小时)+ 近 N 天(按天) */
|
||||
const RANGE_OPTIONS = [
|
||||
{ key: 'today', label: '今日' },
|
||||
{ key: 'yesterday', label: '昨日' },
|
||||
{ key: '7', label: '7 天' },
|
||||
{ key: '14', label: '14 天' },
|
||||
{ key: '30', label: '30 天' },
|
||||
] as const;
|
||||
|
||||
type RangeKey = typeof RANGE_OPTIONS[number]['key'];
|
||||
|
||||
const stats = ref<Stats | null>(null);
|
||||
const error = ref('');
|
||||
const loading = ref(true);
|
||||
/** 切换维度时只做轻量 loading,避免整页闪回「加载中」 */
|
||||
const busy = ref(false);
|
||||
const range = ref<RangeKey>('7');
|
||||
const noSubject = ref(!hasSubject.value);
|
||||
/** 业务数据(设备 / 通道 / 扫码记录)只有主体管理员能看,普通成员首页只显示说明 */
|
||||
const isAdmin = isSubjectAdmin;
|
||||
@ -21,29 +44,88 @@ const isAdmin = isSubjectAdmin;
|
||||
const denied = ref(route.query.denied === '1');
|
||||
/** 当前主体名(成员视角的提示文案用) */
|
||||
const currentSubjectName = computed(() => currentSubject.value?.name || '当前主体');
|
||||
|
||||
/** 今日 / 昨日('today' | 'yesterday'),近 N 天时为 '' */
|
||||
const period = computed(() => (range.value === 'today' || range.value === 'yesterday' ? range.value : ''));
|
||||
/** 近 N 天的天数(今日 / 昨日 维度不参与) */
|
||||
const days = computed(() => (period.value ? 7 : Number(range.value)));
|
||||
|
||||
/** 当前维度是「按小时」还是「按天」 */
|
||||
const isHourly = computed(() => (stats.value?.scanTrendUnit ?? 'day') === 'hour');
|
||||
const hasScanTrend = computed(() => (stats.value?.scanTrendTotal ?? 0) > 0);
|
||||
const hasWorkstationStats = computed(() => Boolean(stats.value
|
||||
&& (stats.value.workstationStats.length > 0 || stats.value.workstationUnassigned > 0)));
|
||||
|
||||
/** 趋势图标题:跟着维度变(今日/昨日是按小时的时段分布) */
|
||||
const trendTitle = computed(() => {
|
||||
const current = stats.value?.period;
|
||||
if (current === 'today') return '今日扫码时段分布';
|
||||
if (current === 'yesterday') return '昨日扫码时段分布';
|
||||
return '近日扫描数量';
|
||||
});
|
||||
|
||||
/** 趋势图副标题:把「今日 / 昨日」两个同比数字一起给出来 */
|
||||
const trendHint = computed(() => {
|
||||
const data = stats.value;
|
||||
if (!data) return '';
|
||||
if (data.period === 'today') return `今天 0 点起共 ${data.scanTrendTotal} 条 · 昨日 ${data.yesterdayCount} 条`;
|
||||
if (data.period === 'yesterday') return `昨天 0~24 点共 ${data.scanTrendTotal} 条 · 今日 ${data.todayCount} 条`;
|
||||
return `近 ${data.scanTrendDays} 天共 ${data.scanTrendTotal} 条 · 今日 ${data.todayCount} 条 · 昨日 ${data.yesterdayCount} 条`;
|
||||
});
|
||||
|
||||
/** 工作台榜副标题 */
|
||||
const stationHint = computed(() => {
|
||||
const data = stats.value;
|
||||
if (!data) return '';
|
||||
if (data.period === 'today') return '今天 0 点起,按扫码记录统计';
|
||||
if (data.period === 'yesterday') return '昨天 0~24 点,按扫码记录统计';
|
||||
return `近 ${data.scanTrendDays} 天,按扫码记录统计`;
|
||||
});
|
||||
|
||||
/** 今日相对昨日的变化(昨日为 0 时只说条数,不算百分比) */
|
||||
const todayDelta = computed(() => {
|
||||
const data = stats.value;
|
||||
if (!data) return null;
|
||||
if (!data.yesterdayCount) return data.todayCount ? { text: '昨日 0 条', trend: 'up' as const } : null;
|
||||
|
||||
const pct = Math.round(((data.todayCount - data.yesterdayCount) / data.yesterdayCount) * 1000) / 10;
|
||||
if (pct === 0) return { text: '与昨日持平', trend: 'flat' as const };
|
||||
return { text: `较昨日 ${pct > 0 ? '+' : ''}${pct}%`, trend: pct > 0 ? 'up' as const : 'down' as const };
|
||||
});
|
||||
|
||||
/** 测试页只在开发构建里存在,所以生产环境的提示文案不再提它(编译期就折掉 dev 文案) */
|
||||
const emptyHint = import.meta.env.DEV
|
||||
? '还没有扫码记录。设备扫码登录后,用「测试页」可以模拟上报一条。'
|
||||
: '还没有扫码记录。设备扫码登录后会出现在这里。';
|
||||
|
||||
onMounted(async () => {
|
||||
if (noSubject.value) {
|
||||
loading.value = false;
|
||||
return;
|
||||
}
|
||||
/** 趋势图空态:今日 / 昨日 说的是「时段」,别提示去建设备 */
|
||||
const trendEmptyHint = computed(() => (isHourly.value ? '这个时段还没有扫码记录。' : emptyHint));
|
||||
|
||||
async function loadStats(): Promise<void> {
|
||||
// 普通成员没有业务数据权限:不去请求(否则 403)
|
||||
if (!isAdmin.value) {
|
||||
if (noSubject.value || !isAdmin.value) {
|
||||
loading.value = false;
|
||||
return;
|
||||
}
|
||||
try {
|
||||
stats.value = await fetchStats();
|
||||
stats.value = await fetchStats({ days: days.value, period: period.value });
|
||||
error.value = '';
|
||||
} catch (err) {
|
||||
error.value = err instanceof ApiError ? err.message : '加载失败';
|
||||
} finally {
|
||||
loading.value = false;
|
||||
busy.value = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function switchRange(value: RangeKey): void {
|
||||
if (value === range.value || busy.value) return;
|
||||
range.value = value;
|
||||
busy.value = true;
|
||||
loadStats();
|
||||
}
|
||||
|
||||
onMounted(loadStats);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@ -89,8 +171,67 @@ onMounted(async () => {
|
||||
<RouterLink class="card stat" to="/records">
|
||||
<span class="stat-label">扫码记录</span>
|
||||
<b class="stat-value">{{ stats.recordCount }}</b>
|
||||
<span class="stat-foot">条</span>
|
||||
<span class="stat-foot">条(全部)</span>
|
||||
</RouterLink>
|
||||
<RouterLink class="card stat" to="/records">
|
||||
<span class="stat-label">今日扫码</span>
|
||||
<b class="stat-value">{{ stats.todayCount }}</b>
|
||||
<span class="stat-foot">
|
||||
条(今天 0 点起)
|
||||
<em v-if="todayDelta" class="stat-delta" :class="`is-${todayDelta.trend}`">{{ todayDelta.text }}</em>
|
||||
</span>
|
||||
</RouterLink>
|
||||
<RouterLink class="card stat" to="/records">
|
||||
<span class="stat-label">昨日扫码</span>
|
||||
<b class="stat-value">{{ stats.yesterdayCount }}</b>
|
||||
<span class="stat-foot">条(昨天 0~24 点)</span>
|
||||
</RouterLink>
|
||||
</div>
|
||||
|
||||
<div class="charts" :class="{ 'is-busy': busy }">
|
||||
<div class="card chart-card">
|
||||
<div class="chart-head">
|
||||
<div>
|
||||
<h3>{{ trendTitle }}</h3>
|
||||
<p class="hint">{{ trendHint }}</p>
|
||||
</div>
|
||||
<div class="seg" role="group" aria-label="统计维度">
|
||||
<button
|
||||
v-for="option in RANGE_OPTIONS"
|
||||
:key="option.key"
|
||||
type="button"
|
||||
class="seg-btn"
|
||||
:class="{ 'is-active': range === option.key }"
|
||||
:disabled="busy"
|
||||
@click="switchRange(option.key)"
|
||||
>{{ option.label }}</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="chart-body">
|
||||
<ScanTrendChart v-if="hasScanTrend" :points="stats.scanTrend" />
|
||||
<p v-else class="hint chart-empty">{{ trendEmptyHint }}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card chart-card">
|
||||
<div class="chart-head">
|
||||
<div>
|
||||
<h3>每个工作台打包数量</h3>
|
||||
<p class="hint">{{ stationHint }}</p>
|
||||
</div>
|
||||
<RouterLink class="chart-link" to="/workstations">管理工作台 →</RouterLink>
|
||||
</div>
|
||||
<div class="chart-body">
|
||||
<WorkstationRankChart
|
||||
v-if="hasWorkstationStats"
|
||||
:items="stats.workstationStats"
|
||||
:unassigned="stats.workstationUnassigned"
|
||||
/>
|
||||
<p v-else class="hint chart-empty">
|
||||
{{ isHourly ? '这个时段还没有打包记录。' : '还没有工作台。创建并绑定扫码通道后,这里会显示每个工作台的打包数量。' }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
@ -124,9 +265,89 @@ onMounted(async () => {
|
||||
<style scoped>
|
||||
.stat-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
|
||||
/* auto-fit + 1fr 行高:一行放不下换行时,各行也保持同一高度 */
|
||||
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
|
||||
grid-auto-rows: 1fr;
|
||||
gap: 16px;
|
||||
}
|
||||
/*
|
||||
* ⚠️ 全局样式里有 `.card + .card { margin-top: 16px }`(给单列堆叠的卡片留间距),
|
||||
* 在网格里会把第 2 张之后的卡片整体往下推 16px,看起来就是「卡片高度/位置不一致」。
|
||||
* 网格内部靠 gap 排版,这里把那个外边距清掉。
|
||||
*/
|
||||
.stat-grid > .card,
|
||||
.charts > .card {
|
||||
margin-top: 0;
|
||||
}
|
||||
.charts {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(340px, 1fr));
|
||||
gap: 16px;
|
||||
margin: 16px 0;
|
||||
align-items: stretch;
|
||||
transition: opacity 0.15s ease;
|
||||
}
|
||||
.charts.is-busy {
|
||||
opacity: 0.55;
|
||||
}
|
||||
.chart-card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
}
|
||||
/* 两张图的正文区等高(卡片本身由 grid 拉齐,这里让内容也从同一高度开始) */
|
||||
.chart-body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
flex: 1 1 auto;
|
||||
min-height: 212px;
|
||||
}
|
||||
.chart-head {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.chart-head h3 {
|
||||
margin: 0 0 4px;
|
||||
}
|
||||
.chart-head .hint {
|
||||
margin: 0;
|
||||
}
|
||||
.chart-empty {
|
||||
margin: 4px 0;
|
||||
}
|
||||
.chart-link {
|
||||
font-size: 12px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.seg {
|
||||
display: inline-flex;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
overflow: hidden;
|
||||
background: #fff;
|
||||
}
|
||||
.seg-btn {
|
||||
border: 0;
|
||||
background: transparent;
|
||||
padding: 5px 10px;
|
||||
font-size: 12px;
|
||||
color: var(--text-muted);
|
||||
cursor: pointer;
|
||||
}
|
||||
.seg-btn + .seg-btn {
|
||||
border-left: 1px solid var(--border);
|
||||
}
|
||||
.seg-btn.is-active {
|
||||
background: var(--brand);
|
||||
color: #fff;
|
||||
}
|
||||
.seg-btn:disabled {
|
||||
cursor: progress;
|
||||
}
|
||||
.stat {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
@ -144,6 +365,28 @@ onMounted(async () => {
|
||||
color: var(--text-muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
.stat-delta {
|
||||
display: inline-block;
|
||||
margin-left: 6px;
|
||||
padding: 0 5px;
|
||||
border-radius: 999px;
|
||||
font-style: normal;
|
||||
font-size: 11px;
|
||||
line-height: 16px;
|
||||
vertical-align: 1px;
|
||||
}
|
||||
.stat-delta.is-up {
|
||||
color: #15803d;
|
||||
background: #f0fdf4;
|
||||
}
|
||||
.stat-delta.is-down {
|
||||
color: var(--danger);
|
||||
background: #fef2f2;
|
||||
}
|
||||
.stat-delta.is-flat {
|
||||
color: var(--text-muted);
|
||||
background: #f3f4f6;
|
||||
}
|
||||
h3 {
|
||||
margin: 0 0 12px;
|
||||
font-size: 15px;
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user