feat(system): 新增 getWarehousePanelData 仓库面板数据接口(增量缓存返回),平台白名单补 tv
This commit is contained in:
parent
879bfaccbe
commit
731bc8e9fb
@ -4,7 +4,7 @@ const Service = require('egg').Service;
|
||||
|
||||
const apiLogSink = require('../lib/api_log_sink');
|
||||
|
||||
const ALLOWED_PLATFORMS = new Set([ 'web', 'pda', 'app', 'wx', 'miniprogram', 'other', 'workerstation', 'workstation' ]);
|
||||
const ALLOWED_PLATFORMS = new Set([ 'web', 'pda', 'app', 'wx', 'miniprogram', 'other', 'tv', 'workerstation', 'workstation' ]);
|
||||
// project: all=全部, warehouse=仓库, store=货主, tms=物流
|
||||
const ALLOWED_PROJECTS = new Set([ 'all', 'warehouse', 'store', 'tms', 'wms', 'scm', 'other' ]);
|
||||
|
||||
|
||||
@ -1052,7 +1052,7 @@ function formatTbWaybillSearchResponse(responseData, expressNameMap = {}) {
|
||||
* 因此将通配符改为显式清单:本清单之外的新方法默认记录系统日志,
|
||||
* 新增方法如需免日志须在此登记。
|
||||
*/
|
||||
const INDEX_NO_NEED_LOG_METHODS = 'fastWhereTree,loadStores,loadWarehouses,loadExpressInterfaces,getCOSUploadConfig,getImages,uploadSuccessNotify,recognizeLicensePlate,ReferenceFile,getMessageDetail,test,getI18nMessage,putI18nCollect,extractModule,tryAutoTranslateNewKeys,searchSpace,searchSpaces,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,ensureShopPrintPlatformExists,buildShopPrintPlatformInclude,getShopList,requestPddWaybillSearch,requestPddStdTemplates,requestTbWaybillSearch,requestTbCainiaoStdTemplates,requestPolyStdTemplates,getShopExpressList,getCainiaoStfTemplates,normalizeTemplatePlatformCode,normalizeTemplateExpressCode,getExpressPlatformFieldName,getTemplateAllowedExpressCodeSet,filterPrintPlatformTemplateResponseData,getPrintPlatformTemplateCacheKey,requestPrintPlatformTemplateList,resolvePddTemplateWpCodeCandidates,requestPddTemplateSourceList,getPrintPlatformTemplateList,isPlatformOauthReservationDuplicateError,getPlatformOauthReservationCodePrefix,hasPlatformOauthReservationCodePrefix,normalizePlatformOauthReservationCode,generatePlatformOauthReservationCode,createPlatformOauthReservation,getPlatformOauthLink,listenPlatformOauthBind,loginToIm,polyapiAuthorizeUrl,toOrder,getWorkbenchBindCode,LoginWorkbenchByCode,queryUserByToken,parseWechatBadgeCode,queryUserByWechatBadge';
|
||||
const INDEX_NO_NEED_LOG_METHODS = 'fastWhereTree,loadStores,loadWarehouses,getWarehousePanelData,loadExpressInterfaces,getCOSUploadConfig,getImages,uploadSuccessNotify,recognizeLicensePlate,ReferenceFile,getMessageDetail,test,getI18nMessage,putI18nCollect,extractModule,tryAutoTranslateNewKeys,searchSpace,searchSpaces,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,ensureShopPrintPlatformExists,buildShopPrintPlatformInclude,getShopList,requestPddWaybillSearch,requestPddStdTemplates,requestTbWaybillSearch,requestTbCainiaoStdTemplates,requestPolyStdTemplates,getShopExpressList,getCainiaoStfTemplates,normalizeTemplatePlatformCode,normalizeTemplateExpressCode,getExpressPlatformFieldName,getTemplateAllowedExpressCodeSet,filterPrintPlatformTemplateResponseData,getPrintPlatformTemplateCacheKey,requestPrintPlatformTemplateList,resolvePddTemplateWpCodeCandidates,requestPddTemplateSourceList,getPrintPlatformTemplateList,isPlatformOauthReservationDuplicateError,getPlatformOauthReservationCodePrefix,hasPlatformOauthReservationCodePrefix,normalizePlatformOauthReservationCode,generatePlatformOauthReservationCode,createPlatformOauthReservation,getPlatformOauthLink,listenPlatformOauthBind,loginToIm,polyapiAuthorizeUrl,toOrder,getWorkbenchBindCode,LoginWorkbenchByCode,queryUserByToken,parseWechatBadgeCode,queryUserByWechatBadge';
|
||||
|
||||
class indexService extends MainService {
|
||||
/**
|
||||
@ -1063,9 +1063,9 @@ class indexService extends MainService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = 'getI18nMessage,putI18nCollect,test,getCainiaoStfTemplates,polyapiAuthorizeUrl,getWorkbenchBindCode,LoginWorkbenchByCode,queryUserByToken,uploadClientErrorLog';
|
||||
const _noNeedRight = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,loadWarehouses,loadExpressInterfaces,getImages,getCOSUploadConfig,uploadSuccessNotify,getMessageDetail,searchSpace,searchSpaces,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,getPlatformOauthLink,listenPlatformOauthBind,recognizeLicensePlate,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl,toOrder,getWorkbenchBindCode,LoginWorkbenchByCode,queryUserByToken,uploadClientErrorLog';
|
||||
const _noNeedRight = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,loadWarehouses,getWarehousePanelData,loadExpressInterfaces,getImages,getCOSUploadConfig,uploadSuccessNotify,getMessageDetail,searchSpace,searchSpaces,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,getPlatformOauthLink,listenPlatformOauthBind,recognizeLicensePlate,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl,toOrder,getWorkbenchBindCode,LoginWorkbenchByCode,queryUserByToken,uploadClientErrorLog';
|
||||
const _noNeedLog = INDEX_NO_NEED_LOG_METHODS;
|
||||
const _noNeedAuth = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,loadWarehouses,loadExpressInterfaces,getImages,getMessageDetail,searchSpace,searchSpaces,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,getPlatformOauthLink,listenPlatformOauthBind,recognizeLicensePlate,test,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl,toOrder,getWorkbenchBindCode,LoginWorkbenchByCode,queryUserByToken,uploadClientErrorLog';
|
||||
const _noNeedAuth = 'loginToIm,getI18nMessage,putI18nCollect,fastWhereTree,loadStores,loadWarehouses,getWarehousePanelData,loadExpressInterfaces,getImages,getMessageDetail,searchSpace,searchSpaces,listInterfaceTypes,getLocationTypeList,getQimenAppList,getExpressList,getExpressProductTypeList,getPlatformList,getPrintPlatformList,getPlatformOauthLink,listenPlatformOauthBind,recognizeLicensePlate,test,getCainiaoStfTemplates,getPrintPlatformTemplateList,polyapiAuthorizeUrl,toOrder,getWorkbenchBindCode,LoginWorkbenchByCode,queryUserByToken,uploadClientErrorLog';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
async fastWhereTree(data) {
|
||||
@ -1084,6 +1084,55 @@ class indexService extends MainService {
|
||||
const result = await service.systems.store.loadWarehouses();
|
||||
return this.success('ok', { warehouses: result, code: 200 });
|
||||
}
|
||||
/**
|
||||
* 获取仓库面板数据。
|
||||
*
|
||||
* 最后更新时间一般由外部驱动;缓存有最后更新时间时按增量返回:
|
||||
* is_change=false 时返回空 data(节约流量),is_change=true 时输出缓存数据;
|
||||
* 缓存中没有最后更新时间时才查库拉取数据并兜底设置最后更新时间。
|
||||
*
|
||||
* @param {Object} data 请求参数
|
||||
* @param {number|string} [data.last_change_at] 最后一次更改的时间戳(Unix 秒),force=false 时必填
|
||||
* @param {boolean|number|string} [data.force] 首次拉取兼容入参(true/1/'true'),当前仅影响 last_change_at 是否可缺省
|
||||
* @return {Promise<Object>} 返回 { is_change, last_change_at, data },其中 is_change=false 时 data 为空对象
|
||||
*/
|
||||
async getWarehousePanelData(data = {}) {
|
||||
const { ctx, service } = this;
|
||||
const warehouseId = ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : null;
|
||||
if (!warehouseId) {
|
||||
return this.fail('缺少仓库上下文');
|
||||
}
|
||||
|
||||
const force = data.force === true || data.force === 'true' || data.force === 1;
|
||||
|
||||
const rawLast = data && data.last_change_at;
|
||||
let lastChangeAt = 0;
|
||||
if (force) {
|
||||
// 首次拉取可不传时间戳,缺省视为 0;若传入则仍做格式校验
|
||||
if (rawLast !== undefined && rawLast !== null && String(rawLast).trim() !== '') {
|
||||
lastChangeAt = Number(rawLast);
|
||||
if (!Number.isFinite(lastChangeAt) || lastChangeAt < 0) {
|
||||
return this.fail('参数错误:last_change_at 必须为数字时间戳');
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (rawLast === undefined || rawLast === null || String(rawLast).trim() === '') {
|
||||
return this.fail('参数错误:last_change_at 不能为空');
|
||||
}
|
||||
lastChangeAt = Number(rawLast);
|
||||
if (!Number.isFinite(lastChangeAt) || lastChangeAt < 0) {
|
||||
return this.fail('参数错误:last_change_at 必须为数字时间戳');
|
||||
}
|
||||
}
|
||||
|
||||
const result = await service.systems.warehousePanel.getPanelData(warehouseId, { force, lastChangeAt });
|
||||
return this.success('ok', {
|
||||
is_change: result.is_change,
|
||||
last_change_at: result.last_change_at,
|
||||
data: result.data,
|
||||
code: 200,
|
||||
});
|
||||
}
|
||||
async loadExpressInterfaces(data = {}) {
|
||||
const { service } = this;
|
||||
const { systemExpressCode } = data;
|
||||
|
||||
702
app/service/systems/warehouse_panel.js
Normal file
702
app/service/systems/warehouse_panel.js
Normal file
@ -0,0 +1,702 @@
|
||||
'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' },
|
||||
];
|
||||
|
||||
// 今日订单趋势固定横轴(08:00-18:00 共 11 点)
|
||||
const TREND_HOURS = [ 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 ];
|
||||
|
||||
// 拣货任务活跃状态(排除 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}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取面板数据。
|
||||
*
|
||||
* 最后更新时间一般由外部驱动(业务数据变化时写入缓存键的 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<Object>} 组装后的面板数据(含 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<Object>} 组装后的面板数据(含 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());
|
||||
const tomorrowStart = new Date(todayStart.getTime() + 86400000);
|
||||
|
||||
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, pendingBase).catch(error => this.logBlockError('fulfillment', error)),
|
||||
this.queryStageOverview(warehouseId, currentModel, pendingBase, todayStart, tomorrowStart)
|
||||
.catch(error => this.logBlockError('stageOverview', error)),
|
||||
this.queryB2b(currentModel, dispatchModel, todayStart, tomorrowStart)
|
||||
.catch(error => this.logBlockError('b2b', error)),
|
||||
this.queryPickingBlock(warehouseId, currentTableName, dispatchTableName, [ 1, 5 ], todayStart, tomorrowStart)
|
||||
.catch(error => this.logBlockError('groupPicking', error)),
|
||||
this.queryPickingBlock(warehouseId, currentTableName, dispatchTableName, [ 2, 3, 4 ], todayStart, tomorrowStart)
|
||||
.catch(error => this.logBlockError('scatterPicking', error)),
|
||||
this.queryPackingPersonal(warehouseId, todayStart, tomorrowStart)
|
||||
.catch(error => this.logBlockError('packingRank', 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 data = {
|
||||
title: ctx.user?.store_name || '',
|
||||
fulfillment,
|
||||
stageOverview,
|
||||
b2b,
|
||||
groupPicking,
|
||||
scatterPicking,
|
||||
packingRank,
|
||||
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 个环节 × 未/已 + 分母。
|
||||
*
|
||||
* @param {Object} currentModel 常用分表模型
|
||||
* @param {Object} pendingBase 待处理基础过滤
|
||||
* @return {Promise<Object>} { total, items }
|
||||
*/
|
||||
async queryFulfillment(currentModel, pendingBase) {
|
||||
const { Op } = this.app.Sequelize;
|
||||
|
||||
const totalCountPromise = currentModel.count({ where: pendingBase });
|
||||
const stageCounts = await Promise.all(FULFILLMENT_STAGES.map(async stage => {
|
||||
const undone = await currentModel.count({
|
||||
where: {
|
||||
...pendingBase,
|
||||
[Op.or]: [
|
||||
{ [stage.field]: { [Op.ne]: 'fin' } },
|
||||
{ [stage.field]: { [Op.is]: null } },
|
||||
],
|
||||
},
|
||||
});
|
||||
const done = await currentModel.count({
|
||||
where: { ...pendingBase, [stage.field]: 'fin' },
|
||||
});
|
||||
return { undone, done };
|
||||
}));
|
||||
|
||||
const total = await totalCountPromise;
|
||||
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 });
|
||||
});
|
||||
|
||||
return { total: total || 0, items };
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行一条 count 原生 SQL 并返回计数。
|
||||
*
|
||||
* @param {string} sql SQL 文本
|
||||
* @param {Object} replacements 替换参数
|
||||
* @return {Promise<number>} 计数结果
|
||||
*/
|
||||
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} pendingBase 待处理基础过滤
|
||||
* @param {Date} todayStart 今日开始
|
||||
* @param {Date} tomorrowStart 明日开始
|
||||
* @return {Promise<Object>} { totalOrders, interceptOrders, stages }
|
||||
*/
|
||||
async queryStageOverview(warehouseId, currentModel, 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 }),
|
||||
currentModel.count({
|
||||
where: { step: 4, outbound_status: 'fin', status: { [Op.ne]: 'cancel' }, delivery_time: todayRange },
|
||||
}),
|
||||
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' ] } },
|
||||
}),
|
||||
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 }
|
||||
),
|
||||
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 } }),
|
||||
model.WaveBatch.count({
|
||||
where: {
|
||||
warehouse_id: warehouseId,
|
||||
recheck_start_time: { [Op.not]: null },
|
||||
wave_status: { [Op.in]: [ 3, 4 ] },
|
||||
},
|
||||
}),
|
||||
currentModel.count({ where: { ...pendingBase, recheck_status: 'error' } }),
|
||||
model.PackTask.count({ where: { warehouse_id: warehouseId, create_time: todayRange } }),
|
||||
model.PackTask.count({ where: { warehouse_id: warehouseId, status: 1 } }),
|
||||
model.PackTask.count({ where: { warehouse_id: warehouseId, status: 3 } }),
|
||||
]);
|
||||
|
||||
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<Object>} { 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),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 拣货统计块(团购 pick_mode=1,5;散单 pick_mode=2,3,4)。
|
||||
*
|
||||
* 窗口:今日创建(create_time 今日)且未取消的任务;
|
||||
* orders/wave 取任务快照(order_count/wave_count);
|
||||
* goods/sku 经 wms_wave_pick_task_order 关联订单分表快照(items_total/items_count)。
|
||||
*
|
||||
* @param {number} warehouseId 仓库 ID
|
||||
* @param {string} currentTableName 常用分表名
|
||||
* @param {string} dispatchTableName 配送分表名
|
||||
* @param {Array<number>} pickModes 拣货模式集合
|
||||
* @param {Date} todayStart 今日开始
|
||||
* @param {Date} tomorrowStart 明日开始
|
||||
* @return {Promise<Object>} { orders, goods, sku, wave, top }
|
||||
*/
|
||||
async queryPickingBlock(warehouseId, currentTableName, dispatchTableName, pickModes, todayStart, tomorrowStart) {
|
||||
const { model } = this.ctx;
|
||||
const { QueryTypes } = model;
|
||||
|
||||
const replacements = {
|
||||
warehouseId,
|
||||
pickModes,
|
||||
activeStatuses: PICK_TASK_ACTIVE_STATUSES,
|
||||
start: todayStart,
|
||||
end: tomorrowStart,
|
||||
};
|
||||
|
||||
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 }),
|
||||
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 [ goodsSkuRows, 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) });
|
||||
});
|
||||
|
||||
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: Number(summary.orders || 0),
|
||||
goods: Number(goodsSkuRows.goods || 0),
|
||||
sku: Number(goodsSkuRows.sku || 0),
|
||||
wave: Number(summary.waves || 0),
|
||||
top,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询拣货任务的 goods/sku(总量 + 按人分组),经任务订单关联表 join 订单分表。
|
||||
*
|
||||
* @param {string} currentTableName 常用分表名
|
||||
* @param {string} dispatchTableName 配送分表名
|
||||
* @param {string} taskWindowWhere 任务窗口 where 片段
|
||||
* @param {Object} replacements 替换参数
|
||||
* @return {Promise<Array<Object>>} [ 总量行, top 行数组 ]
|
||||
*/
|
||||
async queryPickingGoodsSku(currentTableName, dispatchTableName, taskWindowWhere, replacements) {
|
||||
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}\``);
|
||||
|
||||
const [ currentRows, dispatchRows ] = await Promise.all([
|
||||
model.query(goodsSkuSelect, { replacements, type: QueryTypes.SELECT }),
|
||||
model.query(goodsSkuSelectDispatch, { 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 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);
|
||||
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 })) ];
|
||||
}
|
||||
|
||||
/**
|
||||
* 打包个人排名(散单+团购任务合并,按打包员姓名聚合)。
|
||||
*
|
||||
* 口径:今日创建(create_time 今日)且非异常(status != 3)的任务;
|
||||
* 团购任务多人打包时同一任务计入多人(不折算)。
|
||||
*
|
||||
* @param {number} warehouseId 仓库 ID
|
||||
* @param {Date} todayStart 今日开始
|
||||
* @param {Date} tomorrowStart 明日开始
|
||||
* @return {Promise<Object>} { orders, goods, sku, wave, top }
|
||||
*/
|
||||
async queryPackingPersonal(warehouseId, todayStart, tomorrowStart) {
|
||||
const { model } = this.ctx;
|
||||
const { QueryTypes } = model;
|
||||
|
||||
const replacements = { warehouseId, start: todayStart, end: tomorrowStart };
|
||||
const taskWindowWhere = `
|
||||
pt.warehouse_id = :warehouseId 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,
|
||||
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(`
|
||||
SELECT pp.account_name AS name, COUNT(*) AS orders, 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
|
||||
`, { replacements, type: QueryTypes.SELECT }),
|
||||
]);
|
||||
|
||||
const summary = Array.isArray(summaryRows) && summaryRows.length > 0 ? summaryRows[0] : {};
|
||||
const top = (topRows || []).map((row, index) => ({
|
||||
rank: index + 1,
|
||||
name: row.name || '',
|
||||
orders: Number(row.orders || 0),
|
||||
goods: Number(row.goods || 0),
|
||||
sku: Number(row.sku || 0),
|
||||
wave: Number(row.wave || 0),
|
||||
}));
|
||||
|
||||
return {
|
||||
orders: Number(summary.orders || 0),
|
||||
goods: Number(summary.goods || 0),
|
||||
sku: Number(summary.sku || 0),
|
||||
wave: Number(summary.wave || 0),
|
||||
top,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 今日订单实时趋势(固定 08:00-18:00 共 11 点,按小时补零)。
|
||||
*
|
||||
* @param {Object} currentModel 常用分表模型
|
||||
* @param {Object} pendingBase 待处理基础过滤
|
||||
* @param {Date} todayStart 今日开始
|
||||
* @return {Promise<Object>} { max, points }
|
||||
*/
|
||||
async queryTrend(currentModel, pendingBase, todayStart) {
|
||||
const { Op, fn, col, literal } = this.app.Sequelize;
|
||||
const now = new Date();
|
||||
|
||||
const rows = await currentModel.findAll({
|
||||
attributes: [
|
||||
[ fn('HOUR', col('create_at')), 'hour' ],
|
||||
[ fn('COUNT', literal('*')), 'count' ],
|
||||
],
|
||||
where: { ...pendingBase, create_at: { [Op.gte]: todayStart, [Op.lt]: now } },
|
||||
group: [ 'hour' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
const hourMap = new Map();
|
||||
(rows || []).forEach(row => {
|
||||
hourMap.set(Number(row.hour), Number(row.count || 0));
|
||||
});
|
||||
|
||||
const points = TREND_HOURS.map(hour => ({
|
||||
label: `${String(hour).padStart(2, '0')}:00`,
|
||||
value: hourMap.get(hour) || 0,
|
||||
}));
|
||||
const peak = points.reduce((maxValue, point) => Math.max(maxValue, point.value), 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<Object>} { 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;
|
||||
Loading…
x
Reference in New Issue
Block a user