WMS_MAIN/app/service/systems/report/queries/sevenDayStockFlow.js

283 lines
11 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 { buildDayWindows, resolveWindowConfig } = require('../../../../lib/report/day_window');
const { avgDaysPerWeek, suggestWithCompensate, warnOf } = require('../../../../lib/report/formatters');
/**
* 库存变化以及补货报表查询器的静态字段清单(前端可读列元数据)。
* key 与查询器返回的行字段一一对应;computed=true 表示由查询器预计算、非原始表字段;
* asText=true 表示渲染层将该列落地为 Excel 文本单元格(长数字串防科学计数法);
* daily 为数组类型,children 描述每日出入库子字段。
* @type {Array<Object>}
*/
const FIELDS = Object.freeze([
{ key: 'stock_id', label: '库存ID', type: 'number' },
{ key: 'item_code', label: '商品编码', type: 'string', asText: true },
{ key: 'item_name', label: '商品名称', type: 'string' },
{ key: 'barcode', label: '条码', type: 'string', asText: true },
{
key: 'daily',
label: '每日出入库',
type: 'array',
children: [
{ key: 'ck', label: '出库数', type: 'number' },
{ key: 'rk', label: '入库数', type: 'number' },
],
},
{ key: 'ck_total', label: '出库合计', type: 'number' },
{ key: 'rk_total', label: '入库合计', type: 'number' },
{ key: 'available', label: '可用库存', type: 'number' },
{ key: 'total', label: '总库存', type: 'number' },
{ key: 'pending', label: '待出库存', type: 'number' },
{ key: 'locked', label: '锁定数', type: 'number' },
{ key: 'ck_avg', label: '出库日均(×10)', type: 'number', computed: true },
{ key: 'rk_avg', label: '入库日均(×10)', type: 'number', computed: true },
{ key: 'stock_days', label: '预计可售天数', type: 'number', computed: true },
{ key: 'suggest', label: '建议补货量', type: 'number', computed: true },
{ key: 'warn', label: '库存预警', type: 'boolean', computed: true },
]);
/**
* stockFlow 查询器缺省窗口参数(与旧 7 日出入库口径一致,可被 params 覆盖)。
* @type {{dayCount: number, cutoverHour: number}}
*/
const DEFAULT_WINDOW = Object.freeze({ dayCount: 7, cutoverHour: 7 });
/**
* 内置查询器:库存变化以及补货报表(旧 PHP《7日出入库数据》Wms.php putout_putin_storage7 口径)。
*
* 口径与假设(供测试复核):
* 1. 窗口:dayCount 个 [D cutoverHour:00, D+1 cutoverHour:00) 本地时区窗口
* (缺省 7 天、07:00 切点,可由 params.dayCount/cutoverHour 覆盖);
* 2. 流水:wms_stock_transaction,transaction_type IN (INBOUND, OUTBOUND),显式排除 LOCK/UNLOCK,
* 按 created_at 落入窗口,INBOUND→rk、OUTBOUND→ck;
* 3. 可用/总库存口径:wms_storage(库位级正品明细),inventory_type='ZP'、is_enabled=1、未删除,
* SUM(quantity)=总库存、SUM(available_quantity)=可用库存、SUM(locked_quantity)=锁定数,
* 待出库存=总库存-可用库存;与 wms_stock_warehouse 主表的 quantity/locked_quantity 可能存在口径差异;
* 4. 条码口径:wms_stock_barcodes 多值取字典序第一条(表内无主条码标志,旧 PHP 取 MIN(barcode) 语义);
* 5. 行范围:窗口内有流水 或 有正品库存 的 SKU 均出列,按 item_code 升序、stock_id 升序;
* 6. 日均口径:ck_avg/rk_avg = int(合计/天数×10)(formatters.avgDaysPerWeek);
* 7. 预计可售天数:出库日均>0 时 int(可用库存×10/出库日均×10),无出库时为 null;
* 8. suggest/warn 由 formatters 注册表计算(低库存补偿:available<20 且 rk_total<20)。
*
* @param {Object} args 查询器入参
* @param {Object} args.ctx Egg 上下文
* @param {number|null} args.storeId 货主ID(可选,<=0 时不按货主过滤)
* @param {number|null} args.warehouseId 仓库ID(必填)
* @param {Object} [args.params={}] 业务参数(dayCount/cutoverHour 窗口覆盖等)
* @return {Promise<{windows: Array<Object>, rows: Array<Object>, meta: Object}>} 查询结果
*/
async function sevenDayStockFlow({ ctx, storeId = null, warehouseId = null, params = {} }) {
const { app } = ctx;
const { Op } = app.Sequelize;
const { dayCount, cutoverHour } = resolveWindowConfig(params || {});
const windows = buildDayWindows({ dayCount, cutoverHour });
const normalizedWarehouseId = Number(warehouseId) || 0;
if (normalizedWarehouseId <= 0) {
throw new Error('stockFlow 查询器缺少仓库维度 warehouseId');
}
const normalizedStoreId = Number(storeId) || 0;
const windowStart = windows[0].start;
const windowEnd = windows[windows.length - 1].end;
// 1) 流水聚合(排除 LOCK/UNLOCK)
const transactionWhere = {
warehouse_id: normalizedWarehouseId,
transaction_type: { [Op.in]: [ 'INBOUND', 'OUTBOUND' ] },
created_at: {
[Op.gte]: new Date(windowStart),
[Op.lt]: new Date(windowEnd),
},
};
if (normalizedStoreId > 0) {
transactionWhere.store_id = normalizedStoreId;
}
const transactionRows = await ctx.model.StockTransaction.findAll({
where: transactionWhere,
attributes: [ 'stock_id', 'transaction_type', 'quantity', 'created_at' ],
raw: true,
});
// stockId → { daily: [{ck, rk}], ckTotal, rkTotal }
const flowMap = new Map();
const upsertSlot = stockId => {
if (!flowMap.has(stockId)) {
flowMap.set(stockId, {
daily: Array.from({ length: dayCount }, () => ({ ck: 0, rk: 0 })),
ckTotal: 0,
rkTotal: 0,
});
}
return flowMap.get(stockId);
};
for (const row of transactionRows) {
const stockId = Number(row.stock_id);
if (!Number.isInteger(stockId) || stockId <= 0) {
continue;
}
const quantity = Number(row.quantity) || 0;
const createdMs = new Date(row.created_at).getTime();
let windowIndex = -1;
for (let index = 0; index < windows.length; index += 1) {
if (createdMs >= windows[index].start && createdMs < windows[index].end) {
windowIndex = index;
break;
}
}
if (windowIndex < 0) {
continue;
}
const slot = upsertSlot(stockId);
if (row.transaction_type === 'OUTBOUND') {
slot.daily[windowIndex].ck += quantity;
slot.ckTotal += quantity;
} else {
slot.daily[windowIndex].rk += quantity;
slot.rkTotal += quantity;
}
}
// 2) 可用/总库存(正品库位明细聚合)
const storageWhere = {
warehouse_id: normalizedWarehouseId,
inventory_type: 'ZP',
is_enabled: 1,
};
if (normalizedStoreId > 0) {
storageWhere.store_id = normalizedStoreId;
}
const inventoryRows = await ctx.model.Storage.findAll({
where: storageWhere,
attributes: [
'stock_id',
[ app.Sequelize.fn('SUM', app.Sequelize.col('quantity')), 'total_quantity' ],
[ app.Sequelize.fn('SUM', app.Sequelize.col('locked_quantity')), 'total_locked' ],
[ app.Sequelize.fn('SUM', app.Sequelize.col('available_quantity')), 'total_available' ],
],
group: [ 'stock_id' ],
raw: true,
});
const inventoryMap = new Map();
for (const row of inventoryRows) {
const stockId = Number(row.stock_id);
if (!Number.isInteger(stockId) || stockId <= 0) {
continue;
}
const totalQuantity = Number(row.total_quantity) || 0;
const totalAvailable = Number(row.total_available) || 0;
inventoryMap.set(stockId, {
total: totalQuantity,
available: totalAvailable,
locked: Number(row.total_locked) || 0,
pending: totalQuantity - totalAvailable,
});
}
// 3) 商品资料与条码(条码多值取字典序第一条,假设:无主条码标志,等价旧 PHP MIN(barcode))
const stockIds = [ ...new Set([ ...flowMap.keys(), ...inventoryMap.keys() ]) ];
let stockRows = [];
let barcodeRows = [];
if (stockIds.length > 0) {
[ stockRows, barcodeRows ] = await Promise.all([
ctx.model.StockWarehouse.findAll({
where: { id: { [Op.in]: stockIds } },
attributes: [ 'id', 'item_code', 'item_name' ],
raw: true,
}),
ctx.model.StockBarcode.findAll({
where: { stock_id: { [Op.in]: stockIds } },
attributes: [ 'stock_id', 'barcode' ],
order: [[ 'barcode', 'ASC' ]],
raw: true,
}),
]);
}
const stockMap = new Map();
for (const row of stockRows) {
stockMap.set(Number(row.id), {
itemCode: String(row.item_code || '').trim(),
itemName: String(row.item_name || '').trim(),
});
}
const barcodeMap = new Map();
for (const row of barcodeRows) {
const stockId = Number(row.stock_id);
const barcode = String(row.barcode || '').trim();
// 查询已按 barcode 升序,首个即字典序第一条
if (!barcodeMap.has(stockId) && barcode) {
barcodeMap.set(stockId, barcode);
}
}
// 4) 组装数据行
const rows = stockIds.map(stockId => {
const flow = flowMap.get(stockId) || {
daily: Array.from({ length: dayCount }, () => ({ ck: 0, rk: 0 })),
ckTotal: 0,
rkTotal: 0,
};
const inventory = inventoryMap.get(stockId) || { total: 0, available: 0, locked: 0, pending: 0 };
const stock = stockMap.get(stockId) || { itemCode: '', itemName: '' };
const available = inventory.available;
const total = inventory.total;
const ckTotal = flow.ckTotal;
const rkTotal = flow.rkTotal;
const ckAvg = avgDaysPerWeek(ckTotal, dayCount);
const rkAvg = avgDaysPerWeek(rkTotal, dayCount);
// 预计可售天数:日均出库 = ckAvg/10,避免浮点误差改用 (available×10)/ckAvg 取整
const stockDays = ckAvg > 0 ? Math.floor((available * 10) / ckAvg) : null;
return {
stock_id: stockId,
item_code: stock.itemCode,
item_name: stock.itemName,
barcode: barcodeMap.get(stockId) || '',
daily: flow.daily,
ck_total: ckTotal,
rk_total: rkTotal,
available,
total,
pending: inventory.pending,
locked: inventory.locked,
ck_avg: ckAvg,
rk_avg: rkAvg,
stock_days: stockDays,
suggest: suggestWithCompensate(ckTotal, available, rkTotal),
warn: warnOf(ckTotal, available, rkTotal),
};
});
rows.sort((left, right) => {
if (left.item_code !== right.item_code) {
return left.item_code < right.item_code ? -1 : 1;
}
return left.stock_id - right.stock_id;
});
return {
windows,
rows,
meta: {
warehouseId: normalizedWarehouseId,
storeId: normalizedStoreId,
dayCount,
cutoverHour,
},
};
}
module.exports = sevenDayStockFlow;
// 静态字段清单挂到查询器模块上,供报表引擎与注册表 describe 读取(不执行真实数据查询)
module.exports.fields = FIELDS;
// 缺省窗口参数挂到查询器模块上,供注册表 describe 与 report.meta 读取
module.exports.defaultWindow = DEFAULT_WINDOW;