From 98fae0f9d2c0781189940cb681eb6b79b0f30bed Mon Sep 17 00:00:00 2001 From: liufumingren Date: Thu, 29 Oct 2026 17:20:52 +0800 Subject: [PATCH] =?UTF-8?q?feat(=E9=A6=96=E9=A1=B5=E7=BB=9F=E8=AE=A1):=20?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E4=BB=8A=E6=97=A5/=E6=98=A8=E6=97=A5?= =?UTF-8?q?=E7=BB=B4=E5=BA=A6=EF=BC=8C=E4=BF=AE=E6=AD=A3=E7=BB=9F=E8=AE=A1?= =?UTF-8?q?=20SQL=20=E4=B8=8E=E5=8D=A1=E7=89=87=E9=AB=98=E5=BA=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - /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> --- backend/app/controller/web/stats.js | 45 ++- backend/app/service/scan.js | 241 +++++++++++++++- backend/test/app/controller/scan.test.js | 15 +- backend/test/app/controller/web.data.test.js | 142 ++++++++++ frontend/src/api/types.ts | 40 +++ frontend/src/api/web.ts | 94 ++++++- frontend/src/components/ScanTrendChart.vue | 126 +++++++++ .../src/components/WorkstationRankChart.vue | 129 +++++++++ frontend/src/views/HomeView.vue | 265 +++++++++++++++++- 9 files changed, 1073 insertions(+), 24 deletions(-) create mode 100644 frontend/src/components/ScanTrendChart.vue create mode 100644 frontend/src/components/WorkstationRankChart.vue diff --git a/backend/app/controller/web/stats.js b/backend/app/controller/web/stats.js index 9bf0dbf..30b7528 100644 --- a/backend/app/controller/web/stats.js +++ b/backend/app/controller/web/stats.js @@ -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, }, }; } diff --git a/backend/app/service/scan.js b/backend/app/service/scan.js index 983ae5e..227a0ee 100644 --- a/backend/app/service/scan.js +++ b/backend/app/service/scan.js @@ -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, 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({ diff --git a/backend/test/app/controller/scan.test.js b/backend/test/app/controller/scan.test.js index d6f20e9..6116737 100644 --- a/backend/test/app/controller/scan.test.js +++ b/backend/test/app/controller/scan.test.js @@ -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 () => { diff --git a/backend/test/app/controller/web.data.test.js b/backend/test/app/controller/web.data.test.js index 19c0bcd..c056030 100644 --- a/backend/test/app/controller/web.data.test.js +++ b/backend/test/app/controller/web.data.test.js @@ -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({ diff --git a/frontend/src/api/types.ts b/frontend/src/api/types.ts index 916c652..86461f2 100644 --- a/frontend/src/api/types.ts +++ b/frontend/src/api/types.ts @@ -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) */ diff --git a/frontend/src/api/web.ts b/frontend/src/api/web.ts index 5fb5850..bc4113b 100644 --- a/frontend/src/api/web.ts +++ b/frontend/src/api/web.ts @@ -15,9 +15,16 @@ import type { WechatCodeStatus, } from '@/api/types'; -/** 首页统计 */ -export function fetchStats(): Promise { - return api.get('/api/web/stats'); +/** + * 首页统计 + * + * @param params days:近 N 天(趋势 / 工作台榜的天数,后端限定 1~30,默认 7); + * period:`today` / `yesterday` 切到「今日 / 昨日」维度(趋势改成按小时) + */ +export function fetchStats(params: { days?: number; period?: '' | 'today' | 'yesterday' } = {}): Promise { + const query = new URLSearchParams({ days: String(params.days ?? 7) }); + if (params.period) query.set('period', params.period); + return api.get(`/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 { + return api.post('/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 { + const query = new URLSearchParams({ state }); + if (wait) query.set('wait', String(wait)); + return api.get(`/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 { + return api.post('/api/web/me/wechat/qrcode'); +} + +/** 长轮询绑定结果 */ +export interface WxBindStatus extends WxQrStatus { + binding?: WxBinding; +} + +export function fetchWechatBindStatus(state: string, wait = 0, signal?: AbortSignal): Promise { + const query = new URLSearchParams({ state }); + if (wait) query.set('wait', String(wait)); + return api.get(`/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}`); +} diff --git a/frontend/src/components/ScanTrendChart.vue b/frontend/src/components/ScanTrendChart.vue new file mode 100644 index 0000000..dc334ff --- /dev/null +++ b/frontend/src/components/ScanTrendChart.vue @@ -0,0 +1,126 @@ + + + + + diff --git a/frontend/src/components/WorkstationRankChart.vue b/frontend/src/components/WorkstationRankChart.vue new file mode 100644 index 0000000..b6d4595 --- /dev/null +++ b/frontend/src/components/WorkstationRankChart.vue @@ -0,0 +1,129 @@ + + + + + diff --git a/frontend/src/views/HomeView.vue b/frontend/src/views/HomeView.vue index 40e4eb8..b318ff8 100644 --- a/frontend/src/views/HomeView.vue +++ b/frontend/src/views/HomeView.vue @@ -1,8 +1,17 @@