'use strict'; 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?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); // 今日 = 现在这一刻所在的那天;昨日 = 往前推 24h 所在的那天 const at = period === 'yesterday' ? new Date(Date.now() - 86400000) : new Date(); const span = period ? 1 : days; // 「今日 / 昨日」两个数字要单独算,所以无论如何至少取 2 天 const trendDays = Math.max(span, 2); // 统计只认「绑定到未删除工作台的记录」,工作台 id 只查一次,下面几个聚合共用 const workstationIds = await ctx.service.scan.boundWorkstationIds(subjectId); 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, workstationIds }), ctx.service.scan.listRecords({ subjectId, page: 1, pageSize: 1, workstationIds }), ctx.service.scan.dailyCounts({ subjectId, days: trendDays, workstationIds }), ctx.service.scan.workstationCounts({ subjectId, days: span, endAt: at }), period ? ctx.service.scan.hourlyCounts({ subjectId, day: at, workstationIds }) : 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, data: { deviceCount, channelCount, recordCount, latestRecord: row ? { id: row.id, barcode: row.barcode, channelId: row.channelId, 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, }, }; } } module.exports = WebStatsController;