1) 报表导出列重构为 9 组列(产品名称/条码/外部编码/每日出入库/待处理订单占用数/可用库存/7日总出库数量/推荐采购量/是否触发预警),外部编码 stock_store 优先 fallback,新增 pending_occupy 取仓库主表锁定数量;2) 投递货主隔离修复(上传目录按货主/仓库隔离、投递与通知幂等键含 storeId、processOne 货主维度强校验);3) 文档与 methods 变更记录同步。
306 lines
12 KiB
JavaScript
306 lines
12 KiB
JavaScript
'use strict';
|
||
|
||
const { buildDayWindows, resolveWindowConfig } = require('../../../../lib/report/day_window');
|
||
const { avgDaysPerWeek, suggestWithCompensate, warnOf } = require('../../../../lib/report/formatters');
|
||
|
||
/**
|
||
* 库存变化以及补货报表查询器的静态字段清单(前端可读列元数据,决定导出列顺序)。
|
||
* 仅保留以下 9 组导出列:产品名称/条码/外部编码/每日出入库/待处理订单占用数/
|
||
* 可用库存/7日总出库数量/推荐采购量/是否触发预警。
|
||
* key 与查询器返回的行字段一一对应;computed=true 表示由查询器预计算、非原始表字段;
|
||
* asText=true 表示渲染层将该列落地为 Excel 文本单元格(长数字串防科学计数法);
|
||
* daily 为数组类型,children 描述每日出入库子字段;
|
||
* item_code 列复用原“商品编码”key 以兼容既有报表定义的 fields 勾选,label 改为“外部编码”。
|
||
* @type {Array<Object>}
|
||
*/
|
||
const FIELDS = Object.freeze([
|
||
{ key: 'item_name', label: '产品名称', type: 'string' },
|
||
{ key: 'barcode', label: '条码', type: 'string', asText: true },
|
||
{ key: 'item_code', label: '外部编码', type: 'string', asText: true },
|
||
{
|
||
key: 'daily',
|
||
label: '每日出入库',
|
||
type: 'array',
|
||
children: [
|
||
{ key: 'ck', label: '出库数', type: 'number' },
|
||
{ key: 'rk', label: '入库数', type: 'number' },
|
||
],
|
||
},
|
||
{ key: 'pending_occupy', label: '待处理订单占用数', type: 'number' },
|
||
{ key: 'available', label: '可用库存', type: 'number' },
|
||
{ key: 'ck_total', label: '7日总出库数量', type: 'number' },
|
||
{ 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(available_quantity)=可用库存(行内 available 列);
|
||
* SUM(quantity)/SUM(locked_quantity)/待出库存等仅保留为行内内部计算字段,已不在导出列清单中;
|
||
* 4. 条码口径:wms_stock_barcodes 多值取字典序第一条(表内无主条码标志,旧 PHP 取 MIN(barcode) 语义);
|
||
* 5. 外部编码口径:优先 wms_stock_store.item_code(按 stock_id 关联 wms_stock_warehouse.id,
|
||
* stock_store 同 stock_id 多条时按 id 升序取第一条非空 item_code,stock_id 为空的记录不参与匹配),
|
||
* 未匹配则回落 wms_stock_warehouse.item_code,再无则留空;
|
||
* 6. 待处理订单占用数口径:取 wms_stock_warehouse.locked_quantity(仓库商品主表锁定数量,
|
||
* 不是 wms_storage 聚合的 locked_quantity 口径);
|
||
* 7. 行范围:窗口内有流水 或 有正品库存 的 SKU 均出列,按 item_code 升序、stock_id 升序;
|
||
* 8. suggest/warn 由 formatters 注册表计算(低库存补偿:available<20 且 rk_total<20),
|
||
* 内部仍计算 rk_total/日均/预计可售天数等字段供判定与复核,但不进入导出列清单。
|
||
*
|
||
* @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 stockStoreRows = [];
|
||
let barcodeRows = [];
|
||
if (stockIds.length > 0) {
|
||
[ stockRows, stockStoreRows, barcodeRows ] = await Promise.all([
|
||
ctx.model.StockWarehouse.findAll({
|
||
where: { id: { [Op.in]: stockIds } },
|
||
attributes: [ 'id', 'item_code', 'item_name', 'locked_quantity' ],
|
||
raw: true,
|
||
}),
|
||
ctx.model.StockStore.findAll({
|
||
where: { stock_id: { [Op.in]: stockIds } },
|
||
attributes: [ 'id', 'stock_id', 'item_code' ],
|
||
order: [[ 'id', 'ASC' ]],
|
||
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(),
|
||
lockedQuantity: Number(row.locked_quantity) || 0,
|
||
});
|
||
}
|
||
|
||
// 外部编码映射:同 stock_id 多条记录时按 id 升序取第一条非空 item_code(stock_id 为空记录不参与)
|
||
const externalCodeMap = new Map();
|
||
for (const row of stockStoreRows) {
|
||
const stockId = Number(row.stock_id);
|
||
if (!Number.isInteger(stockId) || stockId <= 0) {
|
||
continue;
|
||
}
|
||
const itemCode = String(row.item_code || '').trim();
|
||
if (!externalCodeMap.has(stockId) && itemCode) {
|
||
externalCodeMap.set(stockId, itemCode);
|
||
}
|
||
}
|
||
|
||
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: '', lockedQuantity: 0 };
|
||
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,
|
||
// 外部编码:优先 stock_store.item_code,未匹配则回落 stock_warehouse.item_code,再无则留空
|
||
item_code: externalCodeMap.get(stockId) || 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,
|
||
pending_occupy: stock.lockedQuantity,
|
||
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.definition.typeList 读取
|
||
module.exports.defaultWindow = DEFAULT_WINDOW;
|