From 4ca6af82b027bf70272142a816243076ee56cce9 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sun, 11 Oct 2026 21:54:08 +0800 Subject: [PATCH] =?UTF-8?q?feat(panel):=20=E9=9D=A2=E6=9D=BF=E4=B8=9A?= =?UTF-8?q?=E5=8A=A1=E6=97=A5=E7=AA=97=E5=8F=A3=EF=BC=88day=5Fstart=5Ftime?= =?UTF-8?q?=EF=BC=89=EF=BC=8C=E6=89=93=E5=8C=85=E5=8D=A1=20today=20?= =?UTF-8?q?=E6=94=B9=E8=AE=A2=E5=8D=95=E6=95=B0=E5=8F=A3=E5=BE=84=EF=BC=88?= =?UTF-8?q?=E4=B8=8E=E5=B7=B2=E6=89=93=E5=8C=85=E4=B8=80=E8=87=B4=EF=BC=89?= =?UTF-8?q?=EF=BC=8Cfulfillment=20=E8=BF=BD=E5=8A=A0=E4=BB=8A=E6=97=A5?= =?UTF-8?q?=E9=80=80=E4=BB=B6/=E6=8B=86=E5=8C=85=EF=BC=8C=E9=80=80?= =?UTF-8?q?=E4=BB=B6=E8=A1=A8=E8=A1=A5=E5=88=9B=E5=BB=BA=E6=97=B6=E9=97=B4?= =?UTF-8?q?=E7=B4=A2=E5=BC=95=EF=BC=880.3.281=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/model/return_unpack.js | 1 + app/model/store.js | 20 + app/service/systems/setting/warehouse.js | 11 + app/service/systems/warehouse_panel.js | 456 ++++++++++++++++++----- methods/changes/system.json | 15 + methods/system.json | 5 +- 6 files changed, 412 insertions(+), 96 deletions(-) diff --git a/app/model/return_unpack.js b/app/model/return_unpack.js index 6772771..ab50212 100644 --- a/app/model/return_unpack.js +++ b/app/model/return_unpack.js @@ -130,6 +130,7 @@ module.exports = app => { indexes: [ { name: 'uk_unpack_no', unique: true, fields: [ 'unpack_no' ] }, { name: 'idx_warehouse_unpack_date', fields: [ 'warehouse_id', 'unpack_date' ] }, + { name: 'idx_warehouse_created_at', fields: [ 'warehouse_id', 'created_at' ] }, { name: 'idx_return_received_id', fields: [ 'return_received_id' ] }, { name: 'idx_waybill_code', fields: [ 'waybill_code' ] }, { name: 'idx_order_express_id', fields: [ 'order_express_id' ] }, diff --git a/app/model/store.js b/app/model/store.js index 4c20ee3..e2945f5 100644 --- a/app/model/store.js +++ b/app/model/store.js @@ -50,6 +50,10 @@ module.exports = app => { const DEFAULT_ALLOCATE_START_TIME = '08:00'; const ALLOCATE_START_TIME_MIN = '00:00'; const ALLOCATE_START_TIME_MAX = '23:59'; + // 自然日开始时间(业务日分界点):今日统计窗口 = [该时间点, 次日该时间点) + const DEFAULT_DAY_START_TIME = '06:00'; + const DAY_START_TIME_MIN = '00:00'; + const DAY_START_TIME_MAX = '23:59'; // 收货未入库提醒:默认关闭,开启后每天按 notice_time 扫描超时未入库的收货单 const DEFAULT_PENDING_RECEIVING_NOTICE_TIME = '08:30'; @@ -107,6 +111,7 @@ module.exports = app => { cutoff_order_enabled: 1, cutoff_order_time: DEFAULT_CUTOFF_ORDER_TIME, allocate_start_time: DEFAULT_ALLOCATE_START_TIME, + day_start_time: DEFAULT_DAY_START_TIME, receiving_pending_inbound_notice: DEFAULT_RECEIVING_PENDING_INBOUND_NOTICE, inbox_push_retry: DEFAULT_INBOX_PUSH_RETRY, }); @@ -693,6 +698,21 @@ module.exports = app => { normalized.allocate_start_time = DEFAULT_ALLOCATE_START_TIME; } + if (Object.prototype.hasOwnProperty.call(parsed, 'day_start_time')) { + const dayStartTime = normalizeSubjectConfigText(parsed.day_start_time, DEFAULT_DAY_START_TIME); + if (!/^([01]\d|2[0-3]):[0-5]\d$/.test(dayStartTime)) { + throw new Error('subject_config.day_start_time 格式必须为 HH:mm(如 06:00)'); + } + if (dayStartTime < DAY_START_TIME_MIN || dayStartTime > DAY_START_TIME_MAX) { + normalized.day_start_time = DEFAULT_DAY_START_TIME; + } else { + normalized.day_start_time = dayStartTime; + } + } else { + // 旧数据补齐默认自然日开始时间 + normalized.day_start_time = DEFAULT_DAY_START_TIME; + } + // 跨字段校验:仅当显式同时提交两个时间字段且相等时拒绝(自动分配窗口为空) if (Object.prototype.hasOwnProperty.call(parsed, 'allocate_start_time') && Object.prototype.hasOwnProperty.call(parsed, 'cutoff_order_time') diff --git a/app/service/systems/setting/warehouse.js b/app/service/systems/setting/warehouse.js index 62f3e95..494d2db 100644 --- a/app/service/systems/setting/warehouse.js +++ b/app/service/systems/setting/warehouse.js @@ -259,6 +259,17 @@ const WAREHOUSE_SETTING_FIELDS = Object.freeze([ max: '23:59', description: '开始自动分配时间,格式 HH:mm,如 08:00;早于该时间的订单与超过截单时间行为一致,不自动分配快递和储位,不自动加团;晚于截单时间时截单时间视为次日', }), + Object.freeze({ + key: 'day_start_time', + name: '自然日开始时间', + type: 'string', + default: '06:00', + required: false, + maxLength: 5, + min: '00:00', + max: '23:59', + description: '自然日开始时间(业务日分界点),格式 HH:mm,默认 06:00;今日统计窗口为 [该时间点, 次日该时间点),当前时间早于今日该时间点时窗口从昨日该时间点开始(昨日 06:00 后的订单视为今日)', + }), Object.freeze({ key: 'cutoff_order_time', name: '截单时间', diff --git a/app/service/systems/warehouse_panel.js b/app/service/systems/warehouse_panel.js index e75b41e..74c149b 100644 --- a/app/service/systems/warehouse_panel.js +++ b/app/service/systems/warehouse_panel.js @@ -34,6 +34,63 @@ class WarehousePanelService extends Service { return `${PANEL_CACHE_KEY_PREFIX}:lastChangeAt:${warehouseId}`; } + /** + * 读取仓库自然日开始时间(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) ]; + } + /** * 获取面板数据。 * @@ -101,7 +158,8 @@ class WarehousePanelService extends Service { const now = new Date(); const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate()); - const tomorrowStart = new Date(todayStart.getTime() + 86400000); + // 业务日窗口(仓库配置 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([ @@ -118,24 +176,27 @@ class WarehousePanelService extends Service { }; const blocks = await Promise.all([ - this.queryFulfillment(currentModel, pendingBase).catch(error => this.logBlockError('fulfillment', error)), - this.queryStageOverview(warehouseId, currentModel, pendingBase, todayStart, tomorrowStart) + 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, todayStart, tomorrowStart) + this.queryB2b(currentModel, dispatchModel, businessStart, businessEnd) .catch(error => this.logBlockError('b2b', error)), - this.queryPickingBlock(warehouseId, currentTableName, dispatchTableName, [ 1, 5 ], todayStart, tomorrowStart) + this.queryPickingBlock(warehouseId, currentTableName, dispatchTableName, true, businessStart, businessEnd) .catch(error => this.logBlockError('groupPicking', error)), - this.queryPickingBlock(warehouseId, currentTableName, dispatchTableName, [ 2, 3, 4 ], todayStart, tomorrowStart) + this.queryPickingBlock(warehouseId, currentTableName, dispatchTableName, false, businessStart, businessEnd) .catch(error => this.logBlockError('scatterPicking', error)), - this.queryPackingPersonal(warehouseId, todayStart, tomorrowStart) - .catch(error => this.logBlockError('packingRank', 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, pendingBase, todayStart) .catch(error => this.logBlockError('trend', error)), this.queryWeeklyIntercept(currentModel, dispatchModel, todayStart) .catch(error => this.logBlockError('weeklyEfficiency', error)), ]); - const [ fulfillment, stageOverview, b2b, groupPicking, scatterPicking, packingRank, trend, weeklyEfficiency ] = blocks; + const [ fulfillment, stageOverview, b2b, groupPicking, scatterPicking, groupPacking, scatterPacking, trend, weeklyEfficiency ] = blocks; const data = { title: ctx.user?.store_name || '', @@ -144,7 +205,8 @@ class WarehousePanelService extends Service { b2b, groupPicking, scatterPicking, - packingRank, + groupPacking, + scatterPacking, trend, weeklyEfficiency, }; @@ -168,41 +230,146 @@ class WarehousePanelService extends Service { } /** - * 订单履约链路:6 个环节 × 未/已 + 分母。 + * 订单履约链路: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 待处理基础过滤 - * @return {Promise} { total, items } + * @param {number} warehouseId 仓库 ID + * @param {Date} todayStart 今日开始 + * @param {Date} tomorrowStart 明日开始 + * @return {Promise} { total, items }(items 末尾追加今日退件/今日拆包两项) */ - async queryFulfillment(currentModel, pendingBase) { + 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 stageCounts = await Promise.all(FULFILLMENT_STAGES.map(async stage => { - const undone = await currentModel.count({ + const dispatchTodayCountPromise = dispatchModel.count({ where: dispatchTodayBase }); + // 今日打包任务订单数(pack_mode=2 团购模式按 pack_quantity 求和 + 散单每任务 1 单,与打包两块同口径), + // 用于打包环节已*(避免跨天打包出库窗口错位导致已打包与打包两块对不上) + const packTaskOrdersTodayPromise = model.query( + `SELECT COALESCE(SUM(CASE WHEN pack_mode = 2 THEN pack_quantity ELSE 1 END), 0) AS cnt + FROM wms_pack_task + WHERE warehouse_id = :warehouseId + AND create_time >= :start AND create_time < :end + AND status != 3 AND deleted_at IS NULL`, + { replacements: { warehouseId, start: todayStart, end: tomorrowStart }, type: model.QueryTypes.SELECT } + ).then(rows => { + const first = Array.isArray(rows) && rows.length > 0 ? rows[0] : null; + return Number(first && first.cnt || 0); + }); + // 各环节已* 口径:分配/打印/拣货从订单表状态获取(池内 fin + 配送表今日出库 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: { - ...pendingBase, - [Op.or]: [ - { [stage.field]: { [Op.ne]: 'fin' } }, - { [stage.field]: { [Op.is]: null } }, - ], + status: { [Op.ne]: 'cancel' }, + outbound_status: 'fin', + pick_status: 'fin', + delivery_time: todayRange, + dispatch_lane: { [Op.in]: [ 'm4', 'm5' ] }, }, - }); - const done = await currentModel.count({ - where: { ...pendingBase, [stage.field]: 'fin' }, - }); - return { undone, done }; + }), + ]).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, packTaskOrdersToday ] = 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, + packTaskOrdersTodayPromise, + ]); + // 已* 按环节取今日作业口径数据源;出库环节=今日出库数; + // 未* = 池内未完成 + 配送表今日出库未完成(真实状态) + const doneTodayMap = { + post_status: todayAlloc, + print_status: todayPrint, + pick_status: todayPick, + recheck_status: todayRecheck, + pack_status: packTaskOrdersToday, + outbound_status: dispatchTodayOutbound, + }; + const doneToday = doneTodayMap[stage.field] || 0; + return { + undone: undoneCurrent + (dispatchTodayOutbound - dispatchFin), + done: doneToday, + }; })); - const total = await totalCountPromise; + 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, items }; + return { total: (total || 0) + dispatchTodayOutbound, items }; } /** @@ -226,12 +393,13 @@ class WarehousePanelService extends Service { * * @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, pendingBase, todayStart, tomorrowStart) { + 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 }; @@ -254,9 +422,19 @@ class WarehousePanelService extends Service { packAbnormal, ] = await Promise.all([ currentModel.count({ where: pendingBase }), - currentModel.count({ - where: { step: 4, outbound_status: 'fin', status: { [Op.ne]: 'cancel' }, delivery_time: todayRange }, - }), + 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' } }, }), @@ -265,19 +443,34 @@ class WarehousePanelService extends Service { model.Receiving.count({ where: { warehouse_id: warehouseId, storage_status: { [Op.in]: [ 'waiting', 'partial' ] } }, }), - this.countSql( - `SELECT COUNT(*) AS cnt FROM wms_wave_pick_task - WHERE warehouse_id = :warehouseId AND status IN (:statuses) - AND finish_time >= :start AND finish_time < :end`, - { warehouseId, statuses: [ 2, 3 ], start: todayStart, end: tomorrowStart } - ), + 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), this.countSql( `SELECT COUNT(*) AS cnt FROM wms_wave_pick_task WHERE warehouse_id = :warehouseId AND status = 1`, { warehouseId } ), currentModel.count({ where: { ...pendingBase, pick_status: 'error' } }), - currentModel.count({ where: { status: { [Op.ne]: 'cancel' }, recheck_time: todayRange } }), + 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, @@ -286,7 +479,14 @@ class WarehousePanelService extends Service { }, }), currentModel.count({ where: { ...pendingBase, recheck_status: 'error' } }), - model.PackTask.count({ where: { warehouse_id: warehouseId, create_time: todayRange } }), + this.countSql( + `SELECT COALESCE(SUM(CASE WHEN pack_mode = 2 THEN pack_quantity ELSE 1 END), 0) AS cnt + FROM wms_pack_task + WHERE warehouse_id = :warehouseId + AND create_time >= :start AND create_time < :end + AND status != 3 AND deleted_at IS NULL`, + { warehouseId, start: todayStart, end: tomorrowStart } + ), model.PackTask.count({ where: { warehouse_id: warehouseId, status: 1 } }), model.PackTask.count({ where: { warehouse_id: warehouseId, status: 3 } }), ]); @@ -380,24 +580,26 @@ class WarehousePanelService extends Service { } /** - * 拣货统计块(团购 pick_mode=1,5;散单 pick_mode=2,3,4)。 + * 拣货统计块(团购 wave_scope IN (1,3);散单其余)。 * - * 窗口:今日创建(create_time 今日)且未取消的任务; - * orders/wave 取任务快照(order_count/wave_count); - * goods/sku 经 wms_wave_pick_task_order 关联订单分表快照(items_total/items_count)。 + * 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 {Array} pickModes 拣货模式集合 + * @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, pickModes, todayStart, tomorrowStart) { + 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, @@ -406,18 +608,33 @@ class WarehousePanelService extends Service { 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) `; - const [ summaryRows, topRows ] = await Promise.all([ - model.query(` - SELECT COUNT(*) AS task_count, COALESCE(SUM(order_count), 0) AS orders, COALESCE(SUM(wave_count), 0) AS waves - FROM wms_wave_pick_task t - WHERE ${taskWindowWhere} - `, { replacements, type: QueryTypes.SELECT }), + // 汇总:订单表状态口径(池内 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 @@ -429,11 +646,20 @@ class WarehousePanelService extends Service { `, { replacements, type: QueryTypes.SELECT }), ]); - const [ goodsSkuRows, topGoodsSkuRows ] = await this.queryPickingGoodsSku( + 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 summary = Array.isArray(summaryRows) && summaryRows.length > 0 ? summaryRows[0] : {}; const topGoodsSkuMap = new Map(); (topGoodsSkuRows || []).forEach(row => { topGoodsSkuMap.set(String(row.user_id), { goods: Number(row.goods || 0), sku: Number(row.sku || 0) }); @@ -452,10 +678,10 @@ class WarehousePanelService extends Service { }); return { - orders: Number(summary.orders || 0), - goods: Number(goodsSkuRows.goods || 0), - sku: Number(goodsSkuRows.sku || 0), - wave: Number(summary.waves || 0), + orders: summary.orders, + goods: summary.goods, + sku: summary.sku, + wave: summary.wave, top, }; } @@ -473,18 +699,50 @@ class WarehousePanelService extends Service { const { model } = this.ctx; const { QueryTypes } = model; - const goodsSkuSelect = ` - SELECT COALESCE(SUM(od.items_total), 0) AS goods, COALESCE(SUM(od.items_count), 0) AS sku - FROM wms_wave_pick_task t - JOIN wms_wave_pick_task_order pto ON pto.task_id = t.id - JOIN \`${currentTableName}\` od ON od.id = pto.order_id AND od.status != 'cancel' - WHERE ${taskWindowWhere} - `; - const goodsSkuSelectDispatch = goodsSkuSelect.replace(`\`${currentTableName}\``, `\`${dispatchTableName}\``); + // 任务订单关联表缺失的任务(如 pick_mode=1 团购任务,实测 60 个任务 3862 单无 pto 记录) + // 按 wave_id 从订单分表统计,避免 goods/sku 漏算;有 pto 记录的仍走 pto 精确统计 + const taskWindowWhere2 = taskWindowWhere.replace(/\bt\./g, 't2.'); - const [ currentRows, dispatchRows ] = await Promise.all([ - model.query(goodsSkuSelect, { replacements, type: QueryTypes.SELECT }), - model.query(goodsSkuSelectDispatch, { replacements, type: QueryTypes.SELECT }), + 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 + `; + + 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 pto.task_id AS task_id, od.items_total, od.items_count + FROM wms_wave_pick_task_order pto + JOIN \`${tableName}\` od ON od.id = pto.order_id AND od.status != 'cancel' + 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] : {}; @@ -494,21 +752,6 @@ class WarehousePanelService extends Service { sku: Number(current.sku || 0) + Number(dispatch.sku || 0), }; - const topGoodsSkuSelect = ` - SELECT t.pick_user_id AS user_id, COALESCE(SUM(od.items_total), 0) AS goods, COALESCE(SUM(od.items_count), 0) AS sku - FROM wms_wave_pick_task t - JOIN wms_wave_pick_task_order pto ON pto.task_id = t.id - JOIN \`${currentTableName}\` od ON od.id = pto.order_id AND od.status != 'cancel' - WHERE ${taskWindowWhere} - GROUP BY t.pick_user_id - `; - const topGoodsSkuSelectDispatch = topGoodsSkuSelect.replace(`\`${currentTableName}\``, `\`${dispatchTableName}\``); - - const [ topCurrentRows, topDispatchRows ] = await Promise.all([ - model.query(topGoodsSkuSelect, { replacements, type: QueryTypes.SELECT }), - model.query(topGoodsSkuSelectDispatch, { replacements, type: QueryTypes.SELECT }), - ]); - const topGoodsSkuMap = new Map(); [ ...(topCurrentRows || []), ...(topDispatchRows || []) ].forEach(row => { const key = String(row.user_id); @@ -523,36 +766,51 @@ class WarehousePanelService extends Service { } /** - * 打包个人排名(散单+团购任务合并,按打包员姓名聚合)。 + * 打包统计块(按波次范围区分:wave_scope 1 大团购/3 小团购为团购块,其余为散单块)。 * - * 口径:今日创建(create_time 今日)且非异常(status != 3)的任务; - * 团购任务多人打包时同一任务计入多人(不折算)。 + * 口径:今日创建(create_time 今日)且非异常(status != 3)且未删除的任务; + * 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 } */ - async queryPackingPersonal(warehouseId, todayStart, tomorrowStart) { + 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 pt.create_time >= :start AND pt.create_time < :end + pt.warehouse_id = :warehouseId AND ${scopeWhere} + AND pt.create_time >= :start AND pt.create_time < :end AND pt.status != 3 AND pt.deleted_at IS NULL `; - const [ summaryRows, topRows ] = await Promise.all([ - model.query(` - SELECT COUNT(*) AS orders, COALESCE(SUM(pt.item_quantity), 0) AS goods, + // 团购块按打包台聚合;散单块按打包员聚合 + 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} - `, { replacements, type: QueryTypes.SELECT }), - model.query(` - SELECT pp.account_name AS name, COUNT(*) AS orders, COALESCE(SUM(pt.item_quantity), 0) AS goods, + 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 @@ -561,7 +819,17 @@ class WarehousePanelService extends Service { 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] : {}; diff --git a/methods/changes/system.json b/methods/changes/system.json index 568e8bc..b0e4c9b 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,19 @@ [ + { + "version": "0.3.281", + "date": "2026-10-11", + "type": "updated", + "summary": "index.getWarehousePanelData stageOverview 打包卡 today 改今日打包订单数(与 fulfillment 已打包同口径),替代今日任务数(0.3.280 → 0.3.281)", + "methods": [ + "index.getWarehousePanelData" + ], + "notes": [ + "变更内容:stageOverview 打包卡 today 由今日创建打包任务数(PackTask create_time 窗口 count)改为今日打包任务订单数(SUM(CASE WHEN pack_mode=2 THEN pack_quantity ELSE 1 END),窗口内非异常未删除,与 fulfillment 已打包一致);doing(打包中任务数)/abnormal(异常任务数)保持任务维度。", + "原因:用户反馈 pack 卡数据错误——today 显示任务数(1928)与已打包订单数(12718)不一致,且与拣货/复核卡 today(订单数口径)不统一。", + "代码依据:app/service/systems/warehouse_panel.js#queryStageOverview(packToday 改 countSql 订单数统计);ESLint 0 错误;egg 直调 VERIFY_OK。", + "文档变更范围:methods/system.json 的 module=index 分组仅更新 index.getWarehousePanelData 一条(notes 补 pack 卡 today 口径);根版本 0.3.280 → 0.3.281、updatedAt 保持 2026-10-11;methods/changes/system.json 新增本条(插入数组首位)。" + ] + }, { "version": "0.3.280", "date": "2026-10-11", diff --git a/methods/system.json b/methods/system.json index 89c1254..2d2bf46 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1,7 +1,7 @@ { "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", - "version": "0.3.280", + "version": "0.3.281", "updatedAt": "2026-10-11", "headers": [ { @@ -2630,7 +2630,8 @@ "最后更新时间一般由外部驱动:业务数据变化时由外部写入缓存键的 last_change_at(只写时间戳即可,数据由本接口下次拉取时补入)", "未输出字段(数据源或口径未定):履约链路第 7 环节退件签收、stageOverview 质检卡、收货/上架卡的 today/abnormal、weeklyEfficiency 的 throughput/max", "口径:fulfillment 各环节未* = 常用表池内未完成 + 配送分表今日出库未完成(真实状态);已* 口径:分配/打印/拣货均从订单表状态获取(池内 fin + 配送表今日出库 fin,保证已分配≥已打印≥已拣货的流程约束),复核=今日复核时间(recheck_time 双表)、打包=今日打包任务订单数(pack_mode=2 按 pack_quantity 求和 + 散单每任务 1 单,与 groupPacking/scatterPacking 严格一致)、出库=今日出库数;出库环节未+已=total,其余环节已* 为状态/今日作业口径、未* 为真实状态口径;面板全部今日统计窗口按仓库配置自然日开始时间 day_start_time(默认 06:00)划分:今日=[当日06:00, 次日06:00),当前时间早于当日 06:00 时窗口为 [昨日06:00, 当日06:00)(昨日 06:00 后的订单视为今日);trend(08:00-18:00 小时趋势)与 weeklyEfficiency(7 日)仍按自然日;fulfillment 的 items 末尾两项(今日退件/今日拆包)按 wms_return_received/wms_return_unpack 的 warehouse_id 隔离 + created_at 今日 [00:00, 次日 00:00) 计数;", - "groupPicking/scatterPicking 汇总(orders/goods/sku/wave)按订单表状态口径:池内 pick fin + 配送表今日出库 pick fin,团购=wave_scope IN (1,3)、散单=NOT IN (1,3),团购+散单=已拣货;top 仍按今日创建任务(pick_mode 1,5 团购 / 2,3,4 散单)按人聚合(任务口径,订单表无拣货人);" + "groupPicking/scatterPicking 汇总(orders/goods/sku/wave)按订单表状态口径:池内 pick fin + 配送表今日出库 pick fin,团购=wave_scope IN (1,3)、散单=NOT IN (1,3),团购+散单=已拣货;top 仍按今日创建任务(pick_mode 1,5 团购 / 2,3,4 散单)按人聚合(任务口径,订单表无拣货人);", + "stageOverview 的 pack 卡 today 与 fulfillment 已打包同口径(今日打包任务订单数:pack_mode=2 按 pack_quantity 求和 + 散单每任务 1 单、窗口内非异常未删除),doing/abnormal 为任务数(打包中/异常任务);" ] } ]