WMS_MAIN/app/service/systems/warehouse_panel.js

703 lines
26 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'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;