'use strict'; const Service = require('egg').Service; // 面板数据缓存 TTL(秒):缓存期内直接复用;过期视为无最后更新时间,重新聚合并兜底设置 const PANEL_CACHE_TTL_SECONDS = 300; // 缓存键前缀(按仓库存储:{prefix}:lastChangeAt:{warehouseId}) const PANEL_CACHE_KEY_PREFIX = 'index:warehousePanel'; // 订单履约链路环节定义(每环节按未/已两个数值输出;field 为订单分表状态字段) const FULFILLMENT_STAGES = [ { key: 'alloc', icon: 'alloc', undone: '未分配', done: '已分配', field: 'post_status' }, { key: 'print', icon: 'print', undone: '未打印', done: '已打印', field: 'print_status' }, { key: 'pick', icon: 'pick', undone: '未拣货', done: '已拣货', field: 'pick_status' }, { key: 'recheck', icon: 'recheck', undone: '未复核', done: '已复核', field: 'recheck_status' }, { key: 'pack', icon: 'pack', undone: '未打包', done: '已打包', field: 'pack_status' }, { key: 'ship', icon: 'ship', undone: '待出库', done: '已出库', field: 'outbound_status' }, ]; // 拣货任务活跃状态(排除 9=已取消) const PICK_TASK_ACTIVE_STATUSES = [ 0, 1, 2, 3 ]; class WarehousePanelService extends Service { /** * 面板缓存键(按仓库存储)。 * * @param {number|string} warehouseId 仓库 ID * @return {string} 缓存键 */ getPanelCacheKey(warehouseId) { return `${PANEL_CACHE_KEY_PREFIX}:lastChangeAt:${warehouseId}`; } /** * 通知面板数据已变化(公共方法):更新对应仓库的最后更新时间戳,供大屏增量轮询感知新数据。 * 只写时间戳(整值替换,data 自然失效),面板接口下次拉取时会查库重建数据。 * 供拣货完成/复核完成/打包完成等业务写路径调用;失败仅告警不影响主流程。 * * @param {number|string} warehouseId 仓库 ID * @return {Promise} 写入的时间戳(Unix 秒);失败返回 0 */ async touchLastChangeAt(warehouseId) { try { const key = this.getPanelCacheKey(Number(warehouseId)); const nowTs = Math.floor(Date.now() / 1000); await this.app.setCacheAsync(key, { last_change_at: nowTs }, PANEL_CACHE_TTL_SECONDS); return nowTs; } catch (error) { const logger = this.ctx.logger; if (logger && typeof logger.warn === 'function') { logger.warn(`[WarehousePanel] 更新最后更新时间失败 warehouseId=${warehouseId}: ${error && error.message}`); } return 0; } } /** * 读取仓库自然日开始时间(wms_store.subject_config.day_start_time)。 * * 配置缺失/非法/查询异常时回退默认 06:00。 * * @param {number} warehouseId 仓库 ID * @return {Promise} HH:mm 格式时间(如 06:00) */ async getWarehouseDayStartTime(warehouseId) { try { const store = await this.ctx.model.Store.findOne({ where: { id: warehouseId, project: 'warehouse' }, attributes: [ 'subject_config' ], raw: true, }); let config = store && store.subject_config ? store.subject_config : {}; if (typeof config === 'string') { try { config = JSON.parse(config); } catch (parseError) { config = {}; } } const raw = config.day_start_time; if (typeof raw === 'string' && /^([01]\d|2[0-3]):[0-5]\d$/.test(raw)) { return raw; } return '06:00'; } catch (error) { const logger = this.ctx.logger; if (logger && typeof logger.warn === 'function') { logger.warn(`[WarehousePanel] 读取自然日开始时间失败,回退 06:00: ${error.message}`); } return '06:00'; } } /** * 解析业务日窗口 [businessStart, businessEnd)。 * * 业务日从配置的 day_start_time 开始持续 24 小时;当前时间早于今日该时间点时, * 窗口从昨日该时间点开始(昨日该时间点后的订单视为今日)。 * * @param {number} warehouseId 仓库 ID * @param {Date} now 当前时间 * @return {Promise>} [ 业务日开始, 业务日结束 ] */ async resolveBusinessDayRange(warehouseId, now) { const dayStartTime = await this.getWarehouseDayStartTime(warehouseId); const [ hh, mm ] = dayStartTime.split(':').map(Number); let businessStart = new Date(now.getFullYear(), now.getMonth(), now.getDate(), hh, mm, 0, 0); if (now < businessStart) { businessStart = new Date(businessStart.getTime() - 86400000); } return [ businessStart, new Date(businessStart.getTime() + 86400000) ]; } /** * 获取面板数据。 * * 最后更新时间一般由外部驱动(业务数据变化时写入缓存键的 last_change_at); * 本方法仅在缓存中没有最后更新时间时,才查库拉取数据并兜底设置最后更新时间。 * * 拉取逻辑: * - 缓存有最后更新时间:is_change=false(传入时间戳不小于缓存时间戳)时返回空 data(节约流量); * is_change=true 时优先输出缓存数据;缓存无数据(外部只驱动了时间戳)则查库补数据并保留外部时间戳; * - 缓存无最后更新时间(未命中/过期):查库拉数据并设置最后更新时间。 * * is_change 语义:传入时间戳小于缓存最后更改时间戳时为 true。 * * @param {number} warehouseId 仓库 ID * @param {Object} [options] 选项 * @param {number} [options.lastChangeAt=0] 客户端持有的最后更改时间戳 * @return {Promise} 组装后的面板数据(含 title/fulfillment/stageOverview 等数据块) */ async getPanelData(warehouseId, options = {}) { const lastChangeAt = Number(options.lastChangeAt || 0); const cacheKey = this.getPanelCacheKey(warehouseId); const cached = await this.app.getCacheAsync(cacheKey); // 缓存有最后更新时间 if (cached && cached.last_change_at) { const cachedTs = Number(cached.last_change_at); const isChange = lastChangeAt < cachedTs; // 未变化:空 data 节约流量,不查库 if (!isChange) { return { is_change: false, last_change_at: cachedTs, data: {} }; } // 已有缓存数据:直接输出,不查库 if (cached.data) { return { is_change: true, last_change_at: cachedTs, data: cached.data }; } // 外部只驱动了最后更新时间(无缓存数据):查库拉数据补入缓存,保留外部时间戳 const data = await this.buildPanelData(warehouseId); await this.app.setCacheAsync(cacheKey, { last_change_at: cachedTs, data }, PANEL_CACHE_TTL_SECONDS); return { is_change: true, last_change_at: cachedTs, data }; } // 缓存无最后更新时间:查库拉数据并设置最后更新时间 const data = await this.buildPanelData(warehouseId); const nowTs = Math.floor(Date.now() / 1000); await this.app.setCacheAsync(cacheKey, { last_change_at: nowTs, data }, PANEL_CACHE_TTL_SECONDS); return { is_change: true, last_change_at: nowTs, data }; } /** * 聚合全部面板数据块。 * * 各数据块独立容错:单块查询失败时该块返回 null(前端按字段缺失处理),不影响其他块。 * * @param {number} warehouseId 仓库 ID * @return {Promise} 组装后的面板数据(含 title/fulfillment/stageOverview 等数据块) */ async buildPanelData(warehouseId) { const { ctx } = this; const { model } = ctx; const { Op } = this.app.Sequelize; const now = new Date(); const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate()); // 业务日窗口(仓库配置 day_start_time,默认 06:00):昨日 06:00 后的订单视为今日 const [ businessStart, businessEnd ] = await this.resolveBusinessDayRange(warehouseId, now); const factory = model.OrderDeliveryFactory; const [ currentModel, dispatchModel ] = await Promise.all([ factory.getCurrentModel(warehouseId), factory.getDispatchModel(warehouseId), ]); const currentTableName = currentModel.getTableName(); const dispatchTableName = dispatchModel.getTableName(); const pendingBase = { step: { [Op.in]: [ 1, 2, 3 ] }, outbound_status: { [Op.ne]: 'padding' }, status: { [Op.ne]: 'cancel' }, }; const blocks = await Promise.all([ this.queryFulfillment(currentModel, dispatchModel, pendingBase, warehouseId, businessStart, businessEnd) .catch(error => this.logBlockError('fulfillment', error)), this.queryStageOverview(warehouseId, currentModel, dispatchModel, pendingBase, businessStart, businessEnd) .catch(error => this.logBlockError('stageOverview', error)), this.queryB2b(currentModel, dispatchModel, businessStart, businessEnd) .catch(error => this.logBlockError('b2b', error)), this.queryPickingBlock(warehouseId, currentTableName, dispatchTableName, true, businessStart, businessEnd) .catch(error => this.logBlockError('groupPicking', error)), this.queryPickingBlock(warehouseId, currentTableName, dispatchTableName, false, businessStart, businessEnd) .catch(error => this.logBlockError('scatterPicking', error)), this.queryPackingBlock(warehouseId, businessStart, businessEnd, true) .catch(error => this.logBlockError('groupPacking', error)), this.queryPackingBlock(warehouseId, businessStart, businessEnd, false) .catch(error => this.logBlockError('scatterPacking', error)), this.queryTrend(currentModel, dispatchModel, pendingBase, businessStart, businessEnd) .catch(error => this.logBlockError('trend', error)), this.queryWeeklyIntercept(currentModel, dispatchModel, todayStart) .catch(error => this.logBlockError('weeklyEfficiency', error)), ]); const [ fulfillment, stageOverview, b2b, groupPicking, scatterPicking, groupPacking, scatterPacking, trend, weeklyEfficiency ] = blocks; // 趋势补充总单量字段(与 fulfillment.total 同口径:待处理订单池 + 配送表今日出库; // fulfillment 块失败时兜底 0) if (trend) { trend.total = fulfillment ? (fulfillment.total || 0) : 0; } const data = { title: ctx.user?.store_name || '', fulfillment, stageOverview, b2b, groupPicking, scatterPicking, groupPacking, scatterPacking, trend, weeklyEfficiency, }; return data; } /** * 记录数据块聚合失败日志(返回 null,前端按字段缺失处理)。 * * @param {string} blockName 数据块名 * @param {Error} error 异常 * @return {null} 恒返回 null(调用方将对应数据块置空) */ logBlockError(blockName, error) { const logger = this.ctx.logger; if (logger && typeof logger.warn === 'function') { logger.warn(`[WarehousePanel] 数据块聚合失败,已跳过: ${blockName}`, error.message); } return null; } /** * 订单履约链路:6 个环节 × 未/已 + 分母 + 今日退回指标。 * * 配送表补数:已出库订单会从常用表迁移到配送分表(outbound_status=fin); * 各环节未* = 池内未完成 + 配送表今日出库未完成(真实状态); * 各环节已* 口径:分配/打印/拣货/打包从订单表状态获取(池内 fin + 配送表今日出库 fin, * 保证已分配≥已打印≥已拣货≥已复核≥已打包的流程约束), * 复核=今日复核时间(recheck_time)双表、出库=今日出库数。 * * 今日退回收件数/今日拆包件数:按 wms_return_received / wms_return_unpack * 的 created_at 落在今日(含今天 00:00)且仓库匹配统计,以两项追加在 * items 数组末尾(label/icon/value 与环节项同构)。 * * @param {Object} currentModel 常用分表模型 * @param {Object} dispatchModel 配送分表模型 * @param {Object} pendingBase 待处理基础过滤 * @param {number} warehouseId 仓库 ID * @param {Date} todayStart 今日开始 * @param {Date} tomorrowStart 明日开始 * @return {Promise} { total, items }(items 末尾追加今日退件/今日拆包两项) */ async queryFulfillment(currentModel, dispatchModel, pendingBase, warehouseId, todayStart, tomorrowStart) { const { model } = this.ctx; const { Op } = this.app.Sequelize; const todayRange = { [Op.gte]: todayStart, [Op.lt]: tomorrowStart }; // 配送表今日出库且未取消:出库环节已*(今日出库数)与总数叠加(已迁移订单) const dispatchTodayBase = { status: { [Op.ne]: 'cancel' }, outbound_status: 'fin', delivery_time: todayRange, dispatch_lane: { [Op.in]: [ 'm4', 'm5' ] }, }; const totalCountPromise = currentModel.count({ where: pendingBase }); const dispatchTodayCountPromise = dispatchModel.count({ where: dispatchTodayBase }); // 各环节已* 口径:分配/打印/拣货/打包均从订单表状态获取(池内 fin + 配送表今日出库 fin), // 保证已分配 ≥ 已打印 ≥ 已拣货 ≥ 已复核 ≥ 已打包 的流程约束; // 注:打包环节此前用「今日打包任务订单数」口径,会大于已复核(打包任务快照含未复核/重复计入), // 已改回订单状态存量口径(pack_status=fin);复核=今日复核时间、出库=今日出库数 const todayAllocOrdersPromise = Promise.all([ currentModel.count({ where: { ...pendingBase, post_status: 'fin' } }), dispatchModel.count({ where: { ...dispatchTodayBase, post_status: 'fin' } }), ]).then(([ currentCount, dispatchCount ]) => currentCount + dispatchCount); const todayPrintOrdersPromise = Promise.all([ currentModel.count({ where: { ...pendingBase, print_status: 'fin' } }), dispatchModel.count({ where: { ...dispatchTodayBase, print_status: 'fin' } }), ]).then(([ currentCount, dispatchCount ]) => currentCount + dispatchCount); const todayPickOrdersPromise = Promise.all([ currentModel.count({ where: { ...pendingBase, pick_status: 'fin' } }), dispatchModel.count({ where: { status: { [Op.ne]: 'cancel' }, outbound_status: 'fin', pick_status: 'fin', delivery_time: todayRange, dispatch_lane: { [Op.in]: [ 'm4', 'm5' ] }, }, }), ]).then(([ currentCount, dispatchCount ]) => currentCount + dispatchCount); const todayPackOrdersPromise = Promise.all([ currentModel.count({ where: { ...pendingBase, pack_status: 'fin' } }), dispatchModel.count({ where: { ...dispatchTodayBase, pack_status: 'fin' } }), ]).then(([ currentCount, dispatchCount ]) => currentCount + dispatchCount); const todayRecheckOrdersPromise = Promise.all([ currentModel.count({ where: { status: { [Op.ne]: 'cancel' }, recheck_time: todayRange } }), dispatchModel.count({ where: { status: { [Op.ne]: 'cancel' }, recheck_time: todayRange, dispatch_lane: { [Op.in]: [ 'm4', 'm5' ] }, }, }), ]).then(([ currentCount, dispatchCount ]) => currentCount + dispatchCount); const returnReceivedTodayPromise = model.ReturnReceived.count({ where: { warehouse_id: warehouseId, created_at: todayRange }, }); const returnUnpackTodayPromise = model.ReturnUnpack.count({ where: { warehouse_id: warehouseId, created_at: todayRange }, }); const stageCounts = await Promise.all(FULFILLMENT_STAGES.map(async stage => { const [ undoneCurrent, dispatchFin, dispatchTodayOutbound, todayAlloc, todayPrint, todayPick, todayRecheck, todayPack ] = await Promise.all([ currentModel.count({ where: { ...pendingBase, [Op.or]: [ { [stage.field]: { [Op.ne]: 'fin' } }, { [stage.field]: { [Op.is]: null } }, ], }, }), dispatchModel.count({ where: { ...dispatchTodayBase, [stage.field]: 'fin' }, }), dispatchTodayCountPromise, todayAllocOrdersPromise, todayPrintOrdersPromise, todayPickOrdersPromise, todayRecheckOrdersPromise, todayPackOrdersPromise, ]); // 已* 按环节取今日作业口径数据源;出库环节=今日出库数; // 未* = 池内未完成 + 配送表今日出库未完成(真实状态) const doneTodayMap = { post_status: todayAlloc, print_status: todayPrint, pick_status: todayPick, recheck_status: todayRecheck, pack_status: todayPack, outbound_status: dispatchTodayOutbound, }; const doneToday = doneTodayMap[stage.field] || 0; return { undone: undoneCurrent + (dispatchTodayOutbound - dispatchFin), done: doneToday, }; })); const [ total, dispatchTodayOutbound, returnReceivedToday, returnUnpackToday ] = await Promise.all([ totalCountPromise, dispatchTodayCountPromise, returnReceivedTodayPromise, returnUnpackTodayPromise, ]); const items = []; FULFILLMENT_STAGES.forEach((stage, index) => { const counts = stageCounts[index] || { undone: 0, done: 0 }; items.push({ label: stage.undone, icon: stage.icon, value: counts.undone || 0 }); items.push({ label: stage.done, icon: stage.icon, value: counts.done || 0 }); }); items.push({ label: '今日退件', icon: 'returnReceived', value: returnReceivedToday || 0 }); items.push({ label: '今日拆包', icon: 'returnUnpack', value: returnUnpackToday || 0 }); return { total: (total || 0) + dispatchTodayOutbound, items }; } /** * 执行一条 count 原生 SQL 并返回计数。 * * @param {string} sql SQL 文本 * @param {Object} replacements 替换参数 * @return {Promise} 计数结果 */ async countSql(sql, replacements) { const rows = await this.ctx.model.query(sql, { replacements, type: this.ctx.model.QueryTypes.SELECT, }); const first = Array.isArray(rows) && rows.length > 0 ? rows[0] : null; return Number(first && first.cnt || 0); } /** * 作业环节概览:总量 + 拦截 + 5 张环节卡(缺数据源的字段不写入)。 * * @param {number} warehouseId 仓库 ID * @param {Object} currentModel 常用分表模型 * @param {Object} dispatchModel 配送分表模型(已出库订单迁移目标,今日出库双表合计) * @param {Object} pendingBase 待处理基础过滤 * @param {Date} todayStart 今日开始 * @param {Date} tomorrowStart 明日开始 * @return {Promise} { totalOrders, interceptOrders, stages } */ async queryStageOverview(warehouseId, currentModel, dispatchModel, pendingBase, todayStart, tomorrowStart) { const { model } = this.ctx; const { Op } = this.app.Sequelize; const todayRange = { [Op.gte]: todayStart, [Op.lt]: tomorrowStart }; const [ totalPending, todayOutbound, interceptOrders, receivingToday, receivingDoing, shelfDoing, pickToday, pickDoing, pickAbnormal, recheckToday, recheckDoing, recheckAbnormal, packToday, packDoing, packAbnormal, ] = await Promise.all([ currentModel.count({ where: pendingBase }), Promise.all([ currentModel.count({ where: { step: 4, outbound_status: 'fin', status: { [Op.ne]: 'cancel' }, delivery_time: todayRange }, }), dispatchModel.count({ where: { status: { [Op.ne]: 'cancel' }, outbound_status: 'fin', delivery_time: todayRange, dispatch_lane: { [Op.in]: [ 'm4', 'm5' ] }, }, }), ]).then(([ currentCount, dispatchCount ]) => currentCount + dispatchCount), currentModel.count({ where: { ...pendingBase, intercept_status: { [Op.not]: null, [Op.ne]: 'none' } }, }), model.Receiving.count({ where: { warehouse_id: warehouseId, created_at: todayRange } }), model.Receiving.count({ where: { warehouse_id: warehouseId, status: 'receiving' } }), model.Receiving.count({ where: { warehouse_id: warehouseId, storage_status: { [Op.in]: [ 'waiting', 'partial' ] } }, }), Promise.all([ currentModel.count({ where: { ...pendingBase, pick_status: 'fin' } }), dispatchModel.count({ where: { status: { [Op.ne]: 'cancel' }, outbound_status: 'fin', pick_status: 'fin', delivery_time: todayRange, dispatch_lane: { [Op.in]: [ 'm4', 'm5' ] }, }, }), ]).then(([ currentCount, dispatchCount ]) => currentCount + dispatchCount), // 拣货中订单数:订单表 pick_status='padding'(池内 + 配送表今日出库,与已拣货同源订单表口径) Promise.all([ currentModel.count({ where: { ...pendingBase, pick_status: 'padding' } }), dispatchModel.count({ where: { status: { [Op.ne]: 'cancel' }, outbound_status: 'fin', pick_status: 'padding', delivery_time: todayRange, dispatch_lane: { [Op.in]: [ 'm4', 'm5' ] }, }, }), ]).then(([ currentCount, dispatchCount ]) => currentCount + dispatchCount), Promise.all([ currentModel.count({ where: { ...pendingBase, pick_status: 'error' } }), dispatchModel.count({ where: { status: { [Op.ne]: 'cancel' }, outbound_status: 'fin', pick_status: 'error', delivery_time: todayRange, dispatch_lane: { [Op.in]: [ 'm4', 'm5' ] }, }, }), ]).then(([ currentCount, dispatchCount ]) => currentCount + dispatchCount), Promise.all([ currentModel.count({ where: { status: { [Op.ne]: 'cancel' }, recheck_time: todayRange } }), dispatchModel.count({ where: { status: { [Op.ne]: 'cancel' }, recheck_time: todayRange, dispatch_lane: { [Op.in]: [ 'm4', 'm5' ] }, }, }), ]).then(([ currentCount, dispatchCount ]) => currentCount + dispatchCount), model.WaveBatch.count({ where: { warehouse_id: warehouseId, recheck_start_time: { [Op.not]: null }, wave_status: { [Op.in]: [ 3, 4 ] }, }, }), Promise.all([ currentModel.count({ where: { ...pendingBase, recheck_status: 'error' } }), dispatchModel.count({ where: { status: { [Op.ne]: 'cancel' }, outbound_status: 'fin', recheck_status: 'error', delivery_time: todayRange, dispatch_lane: { [Op.in]: [ 'm4', 'm5' ] }, }, }), ]).then(([ currentCount, dispatchCount ]) => currentCount + dispatchCount), this.countSql( `SELECT (SELECT COUNT(*) FROM wms_pack_task WHERE warehouse_id = :warehouseId AND create_time >= :start AND create_time < :end AND status = 2 AND deleted_at IS NULL AND pack_mode != 2) + (SELECT COUNT(*) FROM wms_order_wave_index WHERE wave_id IN ( SELECT DISTINCT wave_id FROM wms_pack_task WHERE warehouse_id = :warehouseId AND create_time >= :start AND create_time < :end AND status = 2 AND deleted_at IS NULL AND pack_mode = 2 )) AS cnt`, { warehouseId, start: todayStart, end: tomorrowStart } ), // 打包中订单数:订单表 pack_status='padding'(池内 + 配送表今日出库,与未打包/已打包同源订单表口径) Promise.all([ currentModel.count({ where: { ...pendingBase, pack_status: 'padding' } }), dispatchModel.count({ where: { status: { [Op.ne]: 'cancel' }, outbound_status: 'fin', pack_status: 'padding', delivery_time: todayRange, dispatch_lane: { [Op.in]: [ 'm4', 'm5' ] }, }, }), ]).then(([ currentCount, dispatchCount ]) => currentCount + dispatchCount), // 打包异常订单数:订单表 pack_status='error'(池内 + 配送表今日出库,与打包中同源订单表口径) Promise.all([ currentModel.count({ where: { ...pendingBase, pack_status: 'error' } }), dispatchModel.count({ where: { status: { [Op.ne]: 'cancel' }, outbound_status: 'fin', pack_status: 'error', delivery_time: todayRange, dispatch_lane: { [Op.in]: [ 'm4', 'm5' ] }, }, }), ]).then(([ currentCount, dispatchCount ]) => currentCount + dispatchCount), ]); const stages = [ { key: 'receiving', name: '收货', icon: 'car', tone: 'green', today: receivingToday, doing: receivingDoing, }, { key: 'shelf', name: '上架', icon: 'rack', tone: 'amber', doing: shelfDoing, }, { key: 'pick', name: '拣货', icon: 'cart', tone: 'blue', today: pickToday, doing: pickDoing, abnormal: pickAbnormal, }, { key: 'recheck', name: '复核', icon: 'scan', tone: 'violet', today: recheckToday, doing: recheckDoing, abnormal: recheckAbnormal, }, { key: 'pack', name: '打包', icon: 'box', tone: 'cyan', today: packToday, doing: packDoing, abnormal: packAbnormal, }, ]; return { totalOrders: totalPending + todayOutbound, interceptOrders, stages, }; } /** * B2B 今日出库统计(常用表 + 配送表双表聚合)。 * * @param {Object} currentModel 常用分表模型 * @param {Object} dispatchModel 配送分表模型 * @param {Date} todayStart 今日开始 * @param {Date} tomorrowStart 明日开始 * @return {Promise} { orders, goods, sku } */ async queryB2b(currentModel, dispatchModel, todayStart, tomorrowStart) { const { Op, fn, col, literal } = this.app.Sequelize; const todayRange = { [Op.gte]: todayStart, [Op.lt]: tomorrowStart }; const where = { is_b2b: 'Y', status: { [Op.ne]: 'cancel' }, outbound_status: 'fin', delivery_time: todayRange, }; const attrs = [ [ fn('COUNT', literal('*')), 'orders' ], [ fn('SUM', col('items_total')), 'goods' ], [ fn('SUM', col('items_count')), 'sku' ], ]; const [ currentAgg, dispatchAgg ] = await Promise.all([ currentModel.findOne({ attributes: attrs, where, raw: true }), dispatchModel.findOne({ attributes: attrs, where, raw: true }), ]); return { orders: Number(currentAgg?.orders || 0) + Number(dispatchAgg?.orders || 0), goods: Number(currentAgg?.goods || 0) + Number(dispatchAgg?.goods || 0), sku: Number(currentAgg?.sku || 0) + Number(dispatchAgg?.sku || 0), }; } /** * 拣货统计块(团购 wave_scope IN (1,3);散单其余)。 * * orders/goods/sku/wave 汇总按订单表状态口径(池内 pick fin + 配送表今日出库 pick fin, * 与 fulfillment 已拣货一致,保证团购+散单=已拣货); * top 按今日创建任务(pick_mode 1,5 团购 / 2,3,4 散单)按人聚合(任务口径)。 * * @param {number} warehouseId 仓库 ID * @param {string} currentTableName 常用分表名 * @param {string} dispatchTableName 配送分表名 * @param {boolean} isGroup true=团购(wave_scope 1/3);false=散单(其余) * @param {Date} todayStart 今日开始 * @param {Date} tomorrowStart 明日开始 * @return {Promise} { orders, goods, sku, wave, top } */ async queryPickingBlock(warehouseId, currentTableName, dispatchTableName, isGroup, todayStart, tomorrowStart) { const { model } = this.ctx; const { QueryTypes } = model; const scopeWhere = isGroup ? 'wave_scope IN (1, 3)' : 'wave_scope NOT IN (1, 3)'; const pickModes = isGroup ? [ 1, 5 ] : [ 2, 3, 4 ]; const replacements = { warehouseId, pickModes, activeStatuses: PICK_TASK_ACTIVE_STATUSES, start: todayStart, end: tomorrowStart, }; // top:今日创建任务按人聚合(任务口径) const taskWindowWhere = ` t.warehouse_id = :warehouseId AND t.pick_mode IN (:pickModes) AND t.create_time >= :start AND t.create_time < :end AND t.status IN (:activeStatuses) `; // 汇总:订单表状态口径(池内 pick fin + 配送表今日出库 pick fin,与已拣货一致) const summarySql = (tableName, whereFragment) => ` SELECT COUNT(*) AS orders, COALESCE(SUM(items_total), 0) AS goods, COALESCE(SUM(items_count), 0) AS sku, COUNT(DISTINCT CASE WHEN wave_id > 0 THEN wave_id END) AS wave FROM \`${tableName}\` WHERE ${whereFragment} `; const poolWhere = ` step IN (1, 2, 3) AND outbound_status != 'padding' AND status != 'cancel' AND pick_status = 'fin' AND ${scopeWhere} `; const dispatchWhere = ` status != 'cancel' AND outbound_status = 'fin' AND pick_status = 'fin' AND dispatch_lane IN ('m4', 'm5') AND delivery_time >= :start AND delivery_time < :end AND ${scopeWhere} `; const [ currentRows, dispatchRows, topRows ] = await Promise.all([ model.query(summarySql(currentTableName, poolWhere), { replacements, type: QueryTypes.SELECT }), model.query(summarySql(dispatchTableName, dispatchWhere), { replacements, type: QueryTypes.SELECT }), model.query(` SELECT t.pick_user_id AS user_id, t.pick_user_name AS name, COALESCE(SUM(t.order_count), 0) AS orders, COALESCE(SUM(t.wave_count), 0) AS waves FROM wms_wave_pick_task t WHERE ${taskWindowWhere} GROUP BY t.pick_user_id, t.pick_user_name ORDER BY orders DESC LIMIT 5 `, { replacements, type: QueryTypes.SELECT }), ]); const current = Array.isArray(currentRows) && currentRows.length > 0 ? currentRows[0] : {}; const dispatch = Array.isArray(dispatchRows) && dispatchRows.length > 0 ? dispatchRows[0] : {}; const summary = { orders: Number(current.orders || 0) + Number(dispatch.orders || 0), goods: Number(current.goods || 0) + Number(dispatch.goods || 0), sku: Number(current.sku || 0) + Number(dispatch.sku || 0), wave: Number(current.wave || 0) + Number(dispatch.wave || 0), }; // top 的 goods/sku 仍按任务口径(订单表无拣货人,无法按人拆分) const [ , topGoodsSkuRows ] = await this.queryPickingGoodsSku( currentTableName, dispatchTableName, taskWindowWhere, replacements ); const topGoodsSkuMap = new Map(); (topGoodsSkuRows || []).forEach(row => { topGoodsSkuMap.set(String(row.user_id), { goods: Number(row.goods || 0), sku: Number(row.sku || 0) }); }); const top = (topRows || []).map((row, index) => { const goodsSku = topGoodsSkuMap.get(String(row.user_id)) || { goods: 0, sku: 0 }; return { rank: index + 1, name: row.name || '', orders: Number(row.orders || 0), goods: goodsSku.goods, sku: goodsSku.sku, wave: Number(row.waves || 0), }; }); return { orders: summary.orders, goods: summary.goods, sku: summary.sku, wave: summary.wave, top, }; } /** * 查询拣货任务的 goods/sku(总量 + 按人分组),经任务订单关联表 join 订单分表。 * * @param {string} currentTableName 常用分表名 * @param {string} dispatchTableName 配送分表名 * @param {string} taskWindowWhere 任务窗口 where 片段 * @param {Object} replacements 替换参数 * @return {Promise>} [ 总量行, top 行数组 ] */ async queryPickingGoodsSku(currentTableName, dispatchTableName, taskWindowWhere, replacements) { const { model } = this.ctx; const { QueryTypes } = model; // 任务订单关联表缺失的任务(如 pick_mode=1 团购任务,实测 60 个任务 3862 单无 pto 记录) // 按 wave_id 从订单分表统计,避免 goods/sku 漏算;有 pto 记录的仍走 pto 精确统计 const taskWindowWhere2 = taskWindowWhere.replace(/\bt\./g, 't2.'); const goodsSkuSelect = tableName => ` SELECT COALESCE(SUM(x.items_total), 0) AS goods, COALESCE(SUM(x.items_count), 0) AS sku FROM ( SELECT od.items_total, od.items_count FROM wms_wave_pick_task t JOIN wms_wave_pick_task_order pto ON pto.task_id = t.id JOIN \`${tableName}\` od ON od.id = pto.order_id AND od.status != 'cancel' WHERE ${taskWindowWhere} UNION ALL SELECT od2.items_total, od2.items_count FROM wms_wave_pick_task t2 JOIN \`${tableName}\` od2 ON od2.wave_id = t2.wave_id AND od2.status != 'cancel' WHERE ${taskWindowWhere2} AND t2.wave_id > 0 AND NOT EXISTS (SELECT 1 FROM wms_wave_pick_task_order pto2 WHERE pto2.task_id = t2.id) ) x `; // 第一分支必须限定今日任务窗口(同 goodsSkuSelect):否则 pto 全历史关联订单分表, // 派生子查询 g 物化扫描百万行(生产慢日志实测 1.75M 行 / 9.4s 超时) const taskWindowWhereTp = taskWindowWhere.replace(/\bt\./g, 'tp.'); const topGoodsSkuSelect = tableName => ` SELECT t.pick_user_id AS user_id, COALESCE(SUM(g.items_total), 0) AS goods, COALESCE(SUM(g.items_count), 0) AS sku FROM wms_wave_pick_task t JOIN ( SELECT tp.id AS task_id, od.items_total, od.items_count FROM wms_wave_pick_task tp JOIN wms_wave_pick_task_order pto ON pto.task_id = tp.id JOIN \`${tableName}\` od ON od.id = pto.order_id AND od.status != 'cancel' WHERE ${taskWindowWhereTp} UNION ALL SELECT t2.id AS task_id, od2.items_total, od2.items_count FROM wms_wave_pick_task t2 JOIN \`${tableName}\` od2 ON od2.wave_id = t2.wave_id AND od2.status != 'cancel' WHERE ${taskWindowWhere2} AND t2.wave_id > 0 AND NOT EXISTS (SELECT 1 FROM wms_wave_pick_task_order pto2 WHERE pto2.task_id = t2.id) ) g ON g.task_id = t.id WHERE ${taskWindowWhere} GROUP BY t.pick_user_id `; const [ currentRows, dispatchRows, topCurrentRows, topDispatchRows ] = await Promise.all([ model.query(goodsSkuSelect(currentTableName), { replacements, type: QueryTypes.SELECT }), model.query(goodsSkuSelect(dispatchTableName), { replacements, type: QueryTypes.SELECT }), model.query(topGoodsSkuSelect(currentTableName), { replacements, type: QueryTypes.SELECT }), model.query(topGoodsSkuSelect(dispatchTableName), { replacements, type: QueryTypes.SELECT }), ]); const current = Array.isArray(currentRows) && currentRows.length > 0 ? currentRows[0] : {}; const dispatch = Array.isArray(dispatchRows) && dispatchRows.length > 0 ? dispatchRows[0] : {}; const totalGoodsSku = { goods: Number(current.goods || 0) + Number(dispatch.goods || 0), sku: Number(current.sku || 0) + Number(dispatch.sku || 0), }; const topGoodsSkuMap = new Map(); [ ...(topCurrentRows || []), ...(topDispatchRows || []) ].forEach(row => { const key = String(row.user_id); const prev = topGoodsSkuMap.get(key) || { goods: 0, sku: 0 }; topGoodsSkuMap.set(key, { goods: prev.goods + Number(row.goods || 0), sku: prev.sku + Number(row.sku || 0), }); }); return [ totalGoodsSku, [ ...topGoodsSkuMap.entries() ].map(([ user_id, item ]) => ({ user_id, ...item })) ]; } /** * 打包统计块(按波次范围区分:wave_scope 1 大团购/3 小团购为团购块,其余为散单块)。 * * 口径:今日创建(create_time 今日)且已完成(status = 2)且未删除的任务 * (打包中 status=1 不计入,见 stageOverview doing 打包中任务数); * orders 按打包模式统计——pack_mode=2(团购模式)按 pack_quantity(波次订单数快照) * 求和,pack_mode=1 散单每任务 1 单; * 团购块 top 按打包台(wms_workbench.name)聚合;散单块 top 按打包员 * (pack_task_packer.account_name)聚合。 * * @param {number} warehouseId 仓库 ID * @param {Date} todayStart 今日开始 * @param {Date} tomorrowStart 明日开始 * @param {boolean} isGroup true=团购(wave_scope 1/3,top 按打包台);false=散单(wave_scope 非 1/3,top 按打包员) * @return {Promise} 团购 { orders, goods, sku, wave, top };散单 { orders, goods, sku, top }(无 wave) */ async queryPackingBlock(warehouseId, todayStart, tomorrowStart, isGroup) { const { model } = this.ctx; const { QueryTypes } = model; const scopeWhere = isGroup ? 'pt.wave_scope IN (1, 3)' : 'pt.wave_scope NOT IN (1, 3)'; // 订单数口径:pack_mode=2(团购模式,含 wave_scope=3 小团购)按 pack_quantity 求和;散单每任务 1 单 const ordersExpr = 'SUM(CASE WHEN pt.pack_mode = 2 THEN pt.pack_quantity ELSE 1 END) AS orders'; const replacements = { warehouseId, start: todayStart, end: tomorrowStart }; const taskWindowWhere = ` pt.warehouse_id = :warehouseId AND ${scopeWhere} AND pt.create_time >= :start AND pt.create_time < :end AND pt.status = 2 AND pt.deleted_at IS NULL `; // 团购块按打包台聚合;散单块按打包员聚合 const topSql = isGroup ? ` SELECT COALESCE(w.name, '未指定打包台') AS name, ${ordersExpr}, COALESCE(SUM(pt.item_quantity), 0) AS goods, COALESCE(SUM(pt.sku_count), 0) AS sku, COUNT(DISTINCT CASE WHEN pt.wave_id > 0 THEN pt.wave_id END) AS wave FROM wms_pack_task pt LEFT JOIN wms_workbench w ON w.id = pt.workbench_id AND w.deleted_at IS NULL WHERE ${taskWindowWhere} GROUP BY pt.workbench_id, w.name ORDER BY orders DESC LIMIT 5 ` : ` SELECT pp.account_name AS name, ${ordersExpr}, COALESCE(SUM(pt.item_quantity), 0) AS goods, COALESCE(SUM(pt.sku_count), 0) AS sku, COUNT(DISTINCT CASE WHEN pt.wave_id > 0 THEN pt.wave_id END) AS wave FROM wms_pack_task pt JOIN wms_pack_task_packer pp ON pp.pack_task_id = pt.id AND pp.deleted_at IS NULL WHERE ${taskWindowWhere} GROUP BY pp.account_name ORDER BY orders DESC LIMIT 5 `; const [ summaryRows, topRows ] = await Promise.all([ model.query(` SELECT ${ordersExpr}, COALESCE(SUM(pt.item_quantity), 0) AS goods, COALESCE(SUM(pt.sku_count), 0) AS sku, COUNT(DISTINCT CASE WHEN pt.wave_id > 0 THEN pt.wave_id END) AS wave FROM wms_pack_task pt WHERE ${taskWindowWhere} `, { replacements, type: QueryTypes.SELECT }), model.query(topSql, { replacements, type: QueryTypes.SELECT }), ]); const summary = Array.isArray(summaryRows) && summaryRows.length > 0 ? summaryRows[0] : {}; const top = (topRows || []).map((row, index) => { const item = { rank: index + 1, name: row.name || '', orders: Number(row.orders || 0), goods: Number(row.goods || 0), sku: Number(row.sku || 0), }; // 仅团购块输出波次数(散单块无波次语义) if (isGroup) { item.wave = Number(row.wave || 0); } return item; }); const result = { orders: Number(summary.orders || 0), goods: Number(summary.goods || 0), sku: Number(summary.sku || 0), top, }; if (isGroup) { result.wave = Number(summary.wave || 0); } return result; } /** * 今日订单实时趋势(业务日窗口 24 点,label 从仓库自然日开始时间起每小时一点,到次日自然日开始时间)。 * created_count:业务日窗口内下单量(池内待处理 + 配送表今日出库订单,按订单创建时间落桶) * 按小时累计(最后一点=业务日内下单总量);窗口即业务日:未到次日自然日开始时间时 * 为 [今日自然日开始时间, 次日自然日开始时间),凌晨(已过零点)时为 [昨日自然日开始时间, 今日自然日开始时间)。 * * @param {Object} currentModel 常用分表模型 * @param {Object} dispatchModel 配送分表模型 * @param {Object} pendingBase 待处理基础过滤 * @param {Date} todayStart 业务日开始时间(仓库自然日 day_start_time) * @param {Date} tomorrowStart 业务日结束时间(次日自然日开始时间) * @return {Promise} { max, points },points 每项 { label, created_count } */ async queryTrend(currentModel, dispatchModel, pendingBase, todayStart, tomorrowStart) { const { Op, fn, col, literal } = this.app.Sequelize; // 横轴 24 点:从自然日开始时间起每小时一点(跨天,label=桶起点 HH:00) const points = []; const bucketByHour = new Map(); for (let index = 0; index < 24; index++) { const bucketStart = new Date(todayStart.getTime() + index * 3600000); bucketByHour.set(bucketStart.getHours(), index); points.push({ label: `${String(bucketStart.getHours()).padStart(2, '0')}:00`, created_count: 0, }); } const bucketIndexOf = hour => { const bucket = bucketByHour.get(Number(hour)); return bucket === undefined ? 0 : bucket; }; // 下单量按创建时间落桶(池内待处理 + 配送表今日出库,窗口=业务日 [todayStart, tomorrowStart)) const dispatchTodayBase = { status: { [Op.ne]: 'cancel' }, outbound_status: 'fin', delivery_time: { [Op.gte]: todayStart, [Op.lt]: tomorrowStart }, dispatch_lane: { [Op.in]: [ 'm4', 'm5' ] }, }; const [ createdRows, dispatchCreatedRows, ] = await Promise.all([ currentModel.findAll({ attributes: [ [ fn('HOUR', col('create_at')), 'hour' ], [ fn('COUNT', literal('*')), 'count' ], ], where: { ...pendingBase, create_at: { [Op.gte]: todayStart, [Op.lt]: tomorrowStart } }, group: [ 'hour' ], raw: true, }), dispatchModel.findAll({ attributes: [ [ fn('HOUR', col('create_at')), 'hour' ], [ fn('COUNT', literal('*')), 'count' ], ], where: { ...dispatchTodayBase, create_at: { [Op.gte]: todayStart, [Op.lt]: tomorrowStart } }, group: [ 'hour' ], raw: true, }), ]); [ ...(createdRows || []), ...(dispatchCreatedRows || []) ].forEach(row => { points[bucketIndexOf(row.hour)].created_count += Number(row.count || 0); }); // 累计口径:每点为截至该小时结束的累计总数(最后一点=业务日内下单总量) for (let index = 1; index < points.length; index++) { points[index].created_count += points[index - 1].created_count; } const peak = points.reduce( (maxValue, point) => Math.max(maxValue, point.created_count), 0 ); const max = Math.max(Math.ceil(peak / 10) * 10, 10); return { max, points }; } /** * 近 7 日拦截量按天统计(时间锚点:intercept_time,为空时回落 create_at)。 * * 吞吐量(throughput)口径未定义,暂不输出;仅输出 days[].intercept。 * * @param {Object} currentModel 常用分表模型 * @param {Object} dispatchModel 配送分表模型 * @param {Date} todayStart 今日开始 * @return {Promise} { days } */ async queryWeeklyIntercept(currentModel, dispatchModel, todayStart) { const { Op, fn, col, literal } = this.app.Sequelize; const sevenDaysAgo = new Date(todayStart.getTime() - 6 * 86400000); const tomorrowStart = new Date(todayStart.getTime() + 86400000); const anchor = fn('COALESCE', col('intercept_time'), col('create_at')); const where = { [Op.and]: [ { intercept_status: { [Op.not]: null, [Op.ne]: 'none' } }, this.app.Sequelize.where(anchor, { [Op.gte]: sevenDaysAgo, [Op.lt]: tomorrowStart }), ], }; const attributes = [ [ fn('DATE', anchor), 'day' ], [ fn('COUNT', literal('*')), 'count' ], ]; const [ currentRows, dispatchRows ] = await Promise.all([ currentModel.findAll({ attributes, where, group: [ 'day' ], raw: true }), dispatchModel.findAll({ attributes, where, group: [ 'day' ], raw: true }), ]); const dayMap = new Map(); [ ...(currentRows || []), ...(dispatchRows || []) ].forEach(row => { const dayKey = this.normalizeDayKey(row.day); if (!dayKey) { return; } dayMap.set(dayKey, (dayMap.get(dayKey) || 0) + Number(row.count || 0)); }); const days = []; for (let offset = 6; offset >= 0; offset--) { const day = new Date(todayStart.getTime() - offset * 86400000); const dayKey = this.formatDateKey(day); const label = `${String(day.getMonth() + 1).padStart(2, '0')}-${String(day.getDate()).padStart(2, '0')}`; days.push({ label, intercept: dayMap.get(dayKey) || 0 }); } return { days }; } /** * 归一化日期分组键(DATE() 结果可能为 Date 对象或 'YYYY-MM-DD' 字符串)。 * * @param {*} value 分组值 * @return {string} 'YYYY-MM-DD' */ normalizeDayKey(value) { if (!value) { return ''; } if (value instanceof Date) { return this.formatDateKey(value); } const text = String(value); return text.length >= 10 ? text.slice(0, 10) : text; } /** * 格式化为本地日期键 'YYYY-MM-DD'。 * * @param {Date} date 日期 * @return {string} 'YYYY-MM-DD' */ formatDateKey(date) { return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`; } } module.exports = WarehousePanelService;