3163 lines
116 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 crypto = require('node:crypto');
const fs = require('node:fs');
const fsp = require('node:fs/promises');
const os = require('node:os');
const path = require('node:path');
const ExcelJS = require('exceljs');
const Service = require('egg').Service;
const { parseWhereConditions } = require('../../../lib/query_condition_parser');
const ENTRY_EXPORT_PAGE_SIZE = 200;
const ENTRY_ITEMS_FETCH_BATCH_SIZE = 100;
class EntryService extends Service {
/**
* 将费用记录筛选值归一化为 0/1。
* @param {unknown} rawValue 原始筛选值
* @return {number|null} 归一化结果,无法识别时返回 null
*/
normalizeExpenseRecordValue(rawValue) {
if (rawValue === true) return 1;
if (rawValue === false) return 0;
if (rawValue === 1 || rawValue === '1') return 1;
if (rawValue === 0 || rawValue === '0') return 0;
if (typeof rawValue === 'string') {
const normalized = rawValue.trim().toLowerCase();
if ([ 'true', 'yes', 'y' ].includes(normalized)) return 1;
if ([ 'false', 'no', 'n' ].includes(normalized)) return 0;
}
return null;
}
/**
* 归一化 expense_record 条件,兼容 eq/in/布尔值写法。
* @param {Object|number|string|boolean} condition 原始条件
* @return {Object|null} 标准化后的条件,无法识别时返回 null
*/
normalizeExpenseRecordCondition(condition) {
const isObjectCondition = condition && typeof condition === 'object' && !Array.isArray(condition);
if (!isObjectCondition) {
const normalizedValue = this.normalizeExpenseRecordValue(condition);
if (normalizedValue === null) {
return null;
}
return {
operator: 'eq',
value: normalizedValue,
};
}
const operator = String(condition.operator || 'eq').trim().toLowerCase();
const values = this.normalizeFilterValues(condition)
.map(item => this.normalizeExpenseRecordValue(item))
.filter(item => item !== null);
if (values.length === 0) {
return null;
}
if (operator === 'in') {
return {
operator: 'in',
value: [ ...new Set(values) ],
};
}
return {
operator: 'eq',
value: values[0],
};
}
/**
* 将筛选值归一化为数组。
* @param {Object} condition 条件对象
* @return {Array<unknown>} 归一化后的值数组
*/
normalizeFilterValues(condition = {}) {
const value = condition && Object.prototype.hasOwnProperty.call(condition, 'value')
? condition.value
: undefined;
if (Array.isArray(value)) {
return value;
}
if (value === undefined || value === null) {
return [];
}
return [ value ];
}
/**
* 构建入库单-库存流水 EXISTS 子查询条件。
* @param {string} fieldName 流水字段名
* @param {Object} condition 条件对象
* @return {Object|null} Sequelize.where 条件,无法构建时返回 null
*/
buildEntryStockTransactionExistsCondition(fieldName, condition = {}) {
const { app } = this;
const db = app.model;
const values = this.normalizeFilterValues(condition)
.map(item => (typeof item === 'string' ? item.trim() : item))
.filter(item => item !== '' && item !== undefined && item !== null);
if (values.length === 0) {
return null;
}
const operator = String(condition.operator || 'eq').trim().toLowerCase();
const escapedColumn = `st.${fieldName}`;
const escapedValues = values.map(item => db.escape(item));
let valueClause = '';
if (operator === 'in') {
valueClause = `${escapedColumn} IN (${escapedValues.join(',')})`;
} else if (operator === 'like' || operator === 'contains') {
const likeClauses = values.map(item => `${escapedColumn} LIKE ${db.escape(`%${String(item)}%`)}`);
valueClause = likeClauses.length === 1 ? likeClauses[0] : `(${likeClauses.join(' OR ')})`;
} else {
valueClause = `${escapedColumn} = ${escapedValues[0]}`;
}
const sql = `EXISTS (
SELECT 1
FROM wms_stock_transaction st
WHERE st.entry_order_id = wms_entry_order.id
AND ${valueClause}
)`;
return app.Sequelize.where(app.Sequelize.literal(sql), 1);
}
/**
* 预处理入库单列表筛选条件,兼容历史别名并构建扩展筛选。
* @param {Object} normalizedWhere 标准化后的 where 条件
* @return {{where: Object, extraConditions: Array<Object>, errorMessage: string}} 预处理结果
*/
/**
* 根据 hasReceiving 虚拟字段构建入库单 ID 筛选条件。
* @param {boolean} hasReceiving true=已绑定,false=未绑定
* @return {Promise<Object|null>} Sequelize where 条件,无需额外筛选时返回 null
*/
async buildHasReceivingCondition(hasReceiving) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
const bindings = await ctx.model.EntryOrderReceiving.findAll({
attributes: [[ app.Sequelize.fn('DISTINCT', app.Sequelize.col('entry_order_id')), 'entry_order_id' ]],
where: { deleted_at: null },
raw: true,
});
const boundIds = bindings.map(item => item.entry_order_id);
if (hasReceiving === true) {
if (boundIds.length === 0) {
return { id: { [Op.eq]: null } };
}
return { id: { [Op.in]: boundIds } };
}
if (boundIds.length === 0) {
return null;
}
return { id: { [Op.notIn]: boundIds } };
}
/**
* 预处理入库单列表筛选条件,兼容历史别名并构建扩展筛选。
* @param {Object} normalizedWhere 标准化后的 where 条件
* @return {Promise<{where: Object, extraConditions: Array<Object>, errorMessage: string}>} 预处理结果
*/
async preprocessEntryListWhere(normalizedWhere = {}) {
const { ctx } = this;
const whereForParse = normalizedWhere && typeof normalizedWhere === 'object'
? { ...normalizedWhere }
: {};
const extraConditions = [];
if (whereForParse.erp_remark && !whereForParse.remark) {
whereForParse.remark = whereForParse.erp_remark;
}
delete whereForParse.erp_remark;
const batchCondition = whereForParse.batch_no || whereForParse.batch;
if (batchCondition) {
const existsCondition = this.buildEntryStockTransactionExistsCondition('batch_no', batchCondition);
if (existsCondition) {
extraConditions.push(existsCondition);
}
}
delete whereForParse.batch_no;
delete whereForParse.batch;
if (whereForParse.operator_id) {
const existsCondition = this.buildEntryStockTransactionExistsCondition('operator_id', whereForParse.operator_id);
if (existsCondition) {
extraConditions.push(existsCondition);
}
}
delete whereForParse.operator_id;
// 处理虚拟字段 hasReceiving:从 where 中剥离,构建绑定/未绑定筛选条件
if (Object.prototype.hasOwnProperty.call(whereForParse, 'hasReceiving')) {
const rawHasReceiving = whereForParse.hasReceiving;
delete whereForParse.hasReceiving;
if (rawHasReceiving === true || rawHasReceiving === false) {
const receivingCondition = await this.buildHasReceivingCondition(rawHasReceiving);
if (receivingCondition) {
extraConditions.push(receivingCondition);
}
}
}
if (Object.prototype.hasOwnProperty.call(whereForParse, 'expense_record')) {
const hasExpenseRecordField = Boolean(
ctx.model
&& ctx.model.EntryOrder
&& ctx.model.EntryOrder.rawAttributes
&& ctx.model.EntryOrder.rawAttributes.expense_record
);
if (!hasExpenseRecordField) {
return {
where: {},
extraConditions: [],
errorMessage: '当前环境未提供 expense_record 字段,暂不支持该筛选条件,请先完成表结构升级',
};
}
const normalizedExpenseRecord = this.normalizeExpenseRecordCondition(whereForParse.expense_record);
if (normalizedExpenseRecord) {
whereForParse.expense_record = normalizedExpenseRecord;
} else {
delete whereForParse.expense_record;
}
}
return {
where: whereForParse,
extraConditions,
errorMessage: '',
};
}
/**
* 入库单列表查询,复用 where 解构工具。
* @param {Object} where 筛选条件对象
* @param {Object} pageParams 分页参数
* @param {Object} sortParams 排序参数
* @param {string} [mode='warehouse'] 查询模式:warehouse=仓库侧(按 warehouse_id 过滤),store=货主侧(按 store_id 过滤)
* @return {Promise<Object>} code/data/message 结构
*/
async list(where = {}, pageParams = {}, sortParams = {}, mode = 'warehouse') {
const { ctx, app } = this;
const { Sequelize } = app;
const { Op } = Sequelize;
const page = Math.max(Number(pageParams.page) || 1, 1);
const pageSize = Math.max(Number(pageParams.pageSize) || 20, 1);
const sortField = sortParams.sortField || 'created_at';
const sortOrder = String(sortParams.sortOrder || 'DESC').toUpperCase() === 'ASC' ? 'ASC' : 'DESC';
const validSortFields = [
'id',
'entry_order_code',
'order_type',
'order_status',
'order_create_time',
'created_at',
'updated_at',
'total_order_lines',
];
const actualSortField = validSortFields.includes(sortField) ? sortField : 'created_at';
const isStoreMode = String(mode).toLowerCase() === 'store';
// 参考 stock.report.search:从 ctx.user.store_id 提取主维度 ID,
// Number(undefined)=NaN(falsy),防止 Sequelize 静默剔除 undefined 键导致过滤失效
const rawPrimaryId = Number(ctx.user && ctx.user.store_id);
const storeId = isStoreMode ? rawPrimaryId : null;
const warehouseId = isStoreMode ? null : rawPrimaryId;
if (isStoreMode && !storeId) {
return {
code: 400,
message: '用户未绑定货主,无法查询货主侧入库单',
data: {
list: [],
pagination: { page, pageSize, total: 0, totalPages: 0, hasPrevious: false, hasNext: false },
summary: { total: 0, pending: 0, creating: 0, created: 0, completed: 0, cancelled: 0 },
},
};
}
if (!isStoreMode && !warehouseId) {
return {
code: 400,
message: '用户未绑定仓库,无法查询入库单',
data: {
list: [],
pagination: { page, pageSize, total: 0, totalPages: 0, hasPrevious: false, hasNext: false },
summary: { total: 0, pending: 0, creating: 0, created: 0, completed: 0, cancelled: 0 },
},
};
}
const baseWhere = isStoreMode
? { store_id: storeId, is_enabled: 1, deleted_at: null }
: { warehouse_id: warehouseId, is_enabled: 1, deleted_at: null };
const normalizedWhere = ctx.where && typeof ctx.where === 'object'
? { ...ctx.where }
: (where && typeof where === 'object' ? { ...where } : {});
const {
where: parsedSourceWhere,
extraConditions,
errorMessage,
} = await this.preprocessEntryListWhere(normalizedWhere);
if (errorMessage) {
return {
code: 400,
message: errorMessage,
data: {
list: [],
pagination: {
page,
pageSize,
total: 0,
totalPages: 0,
hasPrevious: false,
hasNext: false,
},
summary: {
total: 0,
pending: 0,
creating: 0,
created: 0,
completed: 0,
cancelled: 0,
},
},
};
}
const parsed = parseWhereConditions({
where: parsedSourceWhere,
app,
specialFieldMap: {
quickWhere: {
bucket: 'quick',
},
},
});
if (!parsed.ok) {
return {
code: 400,
message: `筛选条件解析失败: ${parsed.reason}`,
data: {
list: [],
pagination: {
page,
pageSize,
total: 0,
totalPages: 0,
hasPrevious: false,
hasNext: false,
},
summary: {
total: 0,
pending: 0,
creating: 0,
created: 0,
completed: 0,
cancelled: 0,
},
},
};
}
const parsedResult = parsed.result;
const quickWhereInput = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere)
|| parsedSourceWhere.quickWhere
|| null;
const quickWhereValue = quickWhereInput && typeof quickWhereInput === 'object'
? quickWhereInput.value
: null;
const andConditions = [ baseWhere ];
if (quickWhereValue !== undefined && quickWhereValue !== null && String(quickWhereValue).trim() !== '') {
const kw = String(quickWhereValue).trim();
const receivingDetailId = Number(kw);
const escapedKw = app.model.escape(`%${kw}%`);
const orConditions = [
{ entry_order_code: { [Op.like]: `%${kw}%` } },
{ purchase_order_code: { [Op.like]: `%${kw}%` } },
{ supplier_name: { [Op.like]: `%${kw}%` } },
{ store_name: { [Op.like]: `%${kw}%` } },
{ warehouse_name: { [Op.like]: `%${kw}%` } },
// 搜索收货单号(wms_receiving.receiving_number),通过绑定表关联
Sequelize.where(Sequelize.literal(
`EXISTS (
SELECT 1 FROM wms_entry_order_receiving eor
JOIN wms_receiving r ON r.id = eor.receiving_id
WHERE eor.entry_order_id = wms_entry_order.id
AND eor.deleted_at IS NULL
AND r.receiving_number LIKE ${escapedKw}
)`
), 1),
// 搜索收货单明细 ID(箱唛/托盘唛唯一编码,精确数字匹配);仅当 kw 是有效正数时追加 EXISTS
...(Number.isFinite(receivingDetailId) && receivingDetailId > 0 ? [
Sequelize.where(Sequelize.literal(
`EXISTS (
SELECT 1 FROM wms_entry_order_receiving eor
JOIN wms_receiving_detail rd ON rd.receiving_id = eor.receiving_id
WHERE eor.entry_order_id = wms_entry_order.id
AND eor.deleted_at IS NULL
AND rd.id = ${receivingDetailId}
)`
), 1),
] : []),
];
andConditions.push({ [Op.or]: orConditions });
}
const dynamicConditions = parsedResult.dynamicConditions || [];
if (dynamicConditions.length > 0) {
andConditions.push({ [Op.and]: dynamicConditions });
}
if (extraConditions.length > 0) {
andConditions.push({ [Op.and]: extraConditions });
}
const finalWhere = { [Op.and]: andConditions };
const include = [
{
model: ctx.model.Store,
as: 'warehouse',
attributes: [ 'id', 'company_name' ],
required: false,
},
{
model: ctx.model.Store,
as: 'store',
attributes: [ 'id', 'company_name' ],
required: false,
},
];
const { count, rows } = await ctx.model.EntryOrder.findAndCountAll({
where: finalWhere,
include,
order: [[ actualSortField, sortOrder ]],
limit: pageSize,
offset: (page - 1) * pageSize,
distinct: true,
});
// 批量查询收货单绑定信息
const entryOrderIds = rows.map(row => row.id);
/** @type {Map<number, Array<Object>>} */
const receivingBindingsMap = new Map();
if (entryOrderIds.length > 0) {
const allBindings = await ctx.model.EntryOrderReceiving.findAll({
where: { entry_order_id: { [Op.in]: entryOrderIds }, deleted_at: null },
include: [
{
model: ctx.model.Receiving,
as: 'receiving',
attributes: [ 'id', 'receiving_number', 'status', 'storage_status', 'created_at' ],
required: false,
},
],
order: [[ 'id', 'ASC' ]],
});
for (const binding of allBindings) {
const eid = binding.entry_order_id;
if (!receivingBindingsMap.has(eid)) {
receivingBindingsMap.set(eid, []);
}
receivingBindingsMap.get(eid).push(binding);
}
}
// 批量聚合当前页入库单的商品总数量(计划数)与已入库数量
/** @type {Map<number, {total_quantity: number, received_quantity: number}>} */
const quantityMap = new Map();
if (entryOrderIds.length > 0) {
const quantityRows = await ctx.model.EntryItems.findAll({
attributes: [
'order_id',
[ Sequelize.fn('SUM', Sequelize.col('count')), 'total_quantity' ],
[ Sequelize.fn('SUM', Sequelize.col('received_quantity')), 'received_quantity' ],
],
where: { order_id: { [Op.in]: entryOrderIds } },
group: [ 'order_id' ],
raw: true,
});
for (const item of quantityRows) {
quantityMap.set(Number(item.order_id), {
total_quantity: Number(item.total_quantity) || 0,
received_quantity: Number(item.received_quantity) || 0,
});
}
}
// 为每行附加收货单绑定信息与数量汇总
const enrichedRows = rows.map(row => {
const rowJSON = row.toJSON ? row.toJSON() : row;
const bindings = receivingBindingsMap.get(row.id) || [];
const quantity = quantityMap.get(row.id) || { total_quantity: 0, received_quantity: 0 };
return {
...rowJSON,
total_quantity: quantity.total_quantity,
received_quantity: quantity.received_quantity,
receivingBindings: bindings,
hasReceiving: bindings.length > 0,
};
});
const statusRows = await ctx.model.EntryOrder.findAll({
attributes: [
'order_status',
[ Sequelize.fn('COUNT', Sequelize.col('id')), 'count' ],
],
where: finalWhere,
group: [ 'order_status' ],
raw: true,
});
const summary = {
total: count,
pending: 0,
creating: 0,
created: 0,
completed: 0,
cancelled: 0,
};
statusRows.forEach(item => {
const statusKey = String(item.order_status || '').toLowerCase();
if (Object.prototype.hasOwnProperty.call(summary, statusKey)) {
summary[statusKey] = Number(item.count) || 0;
}
});
return {
code: 200,
message: '查询成功',
data: {
list: enrichedRows,
pagination: {
page,
pageSize,
total: count,
totalPages: Math.ceil(count / pageSize),
hasPrevious: page > 1,
hasNext: page < Math.ceil(count / pageSize),
},
summary,
},
};
}
/**
* 查询入库单详情(与原 storage.directInbound.getItems 输出格式一致)。
* 返回入库单基本信息、商品明细(含计划数量与已完成数量)、收货单绑定关系。
* @param {Object} data 请求参数
* @param {number} data.id 入库单主键 ID(必填)
* @param {string} [mode='warehouse'] 查询维度:'warehouse' 按仓库校验权限(默认),'store' 按货主校验权限
* @return {Promise<Object>} code/data/message 结构
* - data.entryOrder: { id, entry_order_code, order_status, total_order_lines, store_remask }
* - data.total_quantity: 应入库总数量(明细 planned 之和)
* - data.received_quantity: 已入库总数量(明细 completed 之和)
* - data.items: [{ id, stock_id, planned, completed, stock, bindings }]
* - data.receivingBindings: [{ id, receiving_id, receiving }]
*/
async get(data = {}, mode = 'warehouse') {
const { ctx, app } = this;
const id = Number(data.id || 0);
if (!id) {
return { code: 400, message: 'id 参数不能为空', data: null };
}
const entryOrder = await ctx.model.EntryOrder.findByPk(id, {
include: [
{
model: ctx.model.EntryItems,
as: 'items',
required: false,
include: [
{
model: ctx.model.StockWarehouse,
as: 'stock',
attributes: [ 'id', 'item_code', 'item_name', 'sku_property' ],
required: false,
},
],
},
{
model: ctx.model.EntryOrderReceiving,
as: 'receivingBindings',
required: false,
include: [
{
model: ctx.model.Receiving,
as: 'receiving',
attributes: [ 'id', 'receiving_number', 'status', 'storage_status', 'created_at' ],
required: false,
},
],
},
],
});
if (!entryOrder) {
return { code: 404, message: '入库单不存在', data: null };
}
const isStoreMode = String(mode).toLowerCase() === 'store';
const rawPrimaryId = Number(ctx.user && ctx.user.store_id);
// 校验权限:仓库模式校验 warehouse_id,货主模式校验 store_id
if (isStoreMode) {
if (entryOrder.store_id !== rawPrimaryId || !entryOrder.is_enabled) {
return { code: 404, message: '入库单不存在或无权访问', data: null };
}
} else {
if (entryOrder.warehouse_id !== rawPrimaryId || !entryOrder.is_enabled) {
return { code: 404, message: '入库单不存在或无权访问', data: null };
}
}
// 查询货主商家备注
const storeWarehouse = await ctx.model.StoreWarehouse.findOne({
where: { store_id: entryOrder.store_id, warehouse_id: entryOrder.warehouse_id },
attributes: [ 'store_remask' ],
raw: true,
});
// 查询该入库单下已有的导入/PDA 入库记录(显式过滤软删除,仅统计未删除记录)
const directLogs = await ctx.model.InboundDirectLog.findAll({
where: { entry_order_id: entryOrder.id, deleted_at: null },
order: [[ 'created_at', 'ASC' ]],
});
// 将直接入库记录按 entry_item_id 关联到明细
// 优先使用 entry_item_id 精确匹配(绑定模式),其次回退到 stock_id 匹配(非绑定模式)
const itemDirectLogs = {};
for (const log of directLogs) {
// 绑定模式下 entry_item_id 已设置,优先用它定位明细行
const itemByEntryItemId = log.entry_item_id
? entryOrder.items.find(i => String(i.id) === String(log.entry_item_id))
: null;
const item = itemByEntryItemId || entryOrder.items.find(
i => String(i.stock_id) === String(log.stock_id)
);
const key = item ? String(item.id) : `stock_${log.stock_id}`;
if (!itemDirectLogs[key]) itemDirectLogs[key] = [];
itemDirectLogs[key].push({
id: log.id,
stock_id: log.stock_id,
quantity: log.quantity,
inbound_type: log.inbound_type,
space_id: log.space_id,
remark: log.remark,
operator_id: log.operator_id,
operator_name: log.operator_name,
created_at: log.created_at,
});
}
// 将入库单层级的收货单绑定扁平化
const receivingBindings = (entryOrder.receivingBindings && entryOrder.receivingBindings.length > 0)
? entryOrder.receivingBindings.map(rb => ({
id: rb.id,
receiving_id: rb.receiving_id,
receiving: rb.receiving || null,
}))
: [];
// 收集所有 stock_id,通过 getStockDetails 批量获取带缓存的商品详情
const stockIds = [ ...new Set(
(entryOrder.items || [])
.map(item => Number(item.stock_id))
.filter(sid => sid && sid > 0)
) ];
/** @type {Map<number, Object>} */
const stockMap = new Map();
if (stockIds.length > 0) {
// 货主模式下传 null 跳过 warehouse 过滤,避免 store_id 误当 warehouse_id 导致查不到商品
const stockWarehouseId = isStoreMode ? null : rawPrimaryId;
const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(stockIds, { warehouseId: stockWarehouseId });
for (const detail of stockDetails) {
stockMap.set(detail.id, detail);
}
}
// 组装明细(精简字段,突出已入/总数)
const items = (entryOrder.items || []).map(item => {
const planQty = Number(item.count) || 0;
const logKey = String(item.id);
const logs = itemDirectLogs[logKey] || [];
const directInQty = logs.reduce((sum, l) => sum + Number(l.quantity), 0);
// 优先使用已持久化的 received_quantity(commit 后由系统写入),
// 若为 0 则回退到 InboundDirectLog 汇总(尚未提交时的导入量),
// 确保绑定收货明细场景下 completed 口径与 received_quantity 一致。
const receivedQty = Number(item.received_quantity) || 0;
const completed = receivedQty > 0 ? receivedQty : directInQty;
const stockDetail = stockMap.get(Number(item.stock_id));
const stock = stockDetail
? (s => { delete s.quantity; delete s.locked_quantity; return s; })({ ...stockDetail })
: null;
return {
id: item.id,
stock_id: item.stock_id,
planned: planQty,
completed,
stock,
};
});
// 收集所有 InboundDirectLog 中的 space_id,批量查询库位名称
/** @type {Map<number, string>} space_id -> space_name */
const spaceNameMap = new Map();
const allSpaceIds = [ ...new Set(
Object.values(itemDirectLogs)
.flat()
.map(log => log.space_id)
.filter(sid => sid != null)
) ];
if (allSpaceIds.length > 0) {
const spaces = await ctx.model.LocationSpace.findAll({
where: { id: { [app.Sequelize.Op.in]: allSpaceIds } },
attributes: [ 'id', 'custom_name', 'space_code' ],
raw: true,
});
for (const sp of spaces) {
spaceNameMap.set(sp.id, sp.custom_name || sp.space_code || '');
}
}
// 批量查询已绑定的收货明细列表
const entryItemIds = items.map(i => i.id).filter(Boolean);
/** @type {Map<number, Array<Object>>} 按 entry_item_id 分组 */
const bindingsMap = new Map();
if (entryItemIds.length > 0) {
const bindingRows = await ctx.model.InboundDirectLog.findAll({
where: {
entry_item_id: { [app.Sequelize.Op.in]: entryItemIds },
receiving_detail_id: { [app.Sequelize.Op.ne]: null },
deleted_at: null,
},
attributes: [ 'id', 'entry_item_id', 'receiving_detail_id', 'quantity', 'status' ],
raw: true,
});
if (bindingRows.length > 0) {
const detailIds = [ ...new Set(bindingRows.map(b => b.receiving_detail_id).filter(Boolean)) ];
const validDetailIds = new Set();
if (detailIds.length > 0) {
const details = await ctx.model.ReceivingDetail.findAll({
where: { id: { [app.Sequelize.Op.in]: detailIds } },
attributes: [ 'id' ],
raw: true,
});
for (const d of details) {
validDetailIds.add(d.id);
}
}
for (const b of bindingRows) {
const key = b.entry_item_id;
if (!bindingsMap.has(key)) {
bindingsMap.set(key, []);
}
bindingsMap.get(key).push({
detail_id: b.receiving_detail_id,
binding_id: b.id,
allocated_quantity: b.quantity || 0,
});
}
}
}
// 将 bindings 挂到对应 item,并补充库位信息
for (const item of items) {
const bindings = bindingsMap.get(item.id) || [];
const logKey = String(item.id);
const directLogsForItem = itemDirectLogs[logKey] || [];
if (bindings.length === 0 && directLogsForItem.length > 0) {
const firstWithSpace = directLogsForItem.find(l => l.space_id);
if (firstWithSpace) {
item.bindings = [{
space_id: firstWithSpace.space_id,
space_name: spaceNameMap.get(Number(firstWithSpace.space_id)) || '',
}];
} else {
item.bindings = [];
}
} else {
const firstWithSpace = directLogsForItem.find(l => l.space_id);
const sid = firstWithSpace ? firstWithSpace.space_id : null;
item.bindings = bindings.map(b => ({
...b,
space_id: sid,
space_name: sid != null ? (spaceNameMap.get(Number(sid)) || '') : '',
}));
}
}
return {
code: 200,
message: '查询成功',
data: {
entryOrder: {
id: entryOrder.id,
entry_order_code: entryOrder.entry_order_code,
order_status: entryOrder.order_status,
total_order_lines: entryOrder.total_order_lines,
store_remask: (storeWarehouse && storeWarehouse.store_remask) || '',
},
total_quantity: items.reduce((sum, item) => sum + (Number(item.planned) || 0), 0),
received_quantity: items.reduce((sum, item) => sum + (Number(item.completed) || 0), 0),
items,
receivingBindings,
},
};
}
/**
* 为 entry items 批量补充可匹配的收货单明细及剩余可用量。
* 匹配规则:entry_item.stock_id 即 wms_stock_warehouse.id,与 wms_receiving_detail.system_product_id 直接对应。
* 只返回收货单状态为未完成(status NOT IN ('completed','cancelled'))且未完全入库(storage_status IN ('none','partial'))的明细。
* @param {Object[]} items 扁平化后的 entry items 数组
* @param {number} warehouseId 仓库ID
* @return {Promise<Object[]>} 补充了 available_receiving_details 的 items
*/
async enrichItemsWithAvailableReceivingDetails(items, warehouseId) {
if (!Array.isArray(items) || items.length === 0) return items;
const { ctx } = this;
const stockIds = [ ...new Set(items.map(i => Number(i.stock_id)).filter(Boolean)) ];
if (stockIds.length === 0) return items;
// stock_id 即 wms_stock_warehouse.id
// wms_receiving_detail.system_product_id 也指向 wms_stock_warehouse.id
// 所以映射关系就是 id → id,只需确认 stock_warehouse 记录存在
const swRows = await ctx.model.StockWarehouse.findAll({
where: { id: { [ctx.app.Sequelize.Op.in]: stockIds }, warehouse_id: warehouseId },
attributes: [ 'id' ],
raw: true,
});
const stockIdToSystemProductId = new Map();
for (const row of swRows) {
stockIdToSystemProductId.set(Number(row.id), Number(row.id));
}
const systemProductIds = [ ...new Set(stockIdToSystemProductId.values()) ];
if (systemProductIds.length === 0) return items;
// 批量查询收货单明细可用量
const rows = await ctx.model.query(
`SELECT
rd.id AS receiving_detail_id,
rd.receiving_id,
rd.system_product_id,
r.receiving_number,
rd.actual_quantity,
COALESCE(SUM(erb.quantity), 0) AS allocated_quantity,
rd.actual_quantity - COALESCE(SUM(erb.quantity), 0) AS available_quantity
FROM wms_receiving_detail rd
INNER JOIN wms_receiving r ON r.id = rd.receiving_id AND r.is_deleted = false
LEFT JOIN wms_inbound_direct_log erb
ON erb.receiving_detail_id = rd.id
AND erb.status = 'committed'
AND erb.deleted_at IS NULL
WHERE rd.system_product_id IN (:systemProductIds)
AND r.status NOT IN ('completed', 'cancelled')
AND rd.storage_status IN ('none', 'partial')
GROUP BY rd.id, rd.receiving_id, rd.system_product_id, r.receiving_number, rd.actual_quantity
HAVING available_quantity > 0
ORDER BY rd.system_product_id, available_quantity DESC`,
{ replacements: { systemProductIds }, type: ctx.model.QueryTypes.SELECT }
);
// 按 system_product_id 分组
const mapBySystemProductId = new Map();
for (const row of rows) {
const spid = Number(row.system_product_id);
if (!mapBySystemProductId.has(spid)) mapBySystemProductId.set(spid, []);
mapBySystemProductId.get(spid).push({
receiving_id: Number(row.receiving_id),
receiving_number: String(row.receiving_number || '').trim(),
receiving_detail_id: Number(row.receiving_detail_id),
actual_quantity: Number(row.actual_quantity || 0),
allocated_quantity: Number(row.allocated_quantity || 0),
available_quantity: Number(row.available_quantity || 0),
});
}
// 为每个 item 挂载
return items.map(item => {
const sid = Number(item.stock_id);
const spid = stockIdToSystemProductId.get(sid) || 0;
return {
...item,
available_receiving_details: spid > 0 ? (mapBySystemProductId.get(spid) || []) : [],
};
});
}
/**
* 归一化作废入参中的入库单 ID 列表。
* 优先使用 ids;未传 ids 时回退到 id。
* @param {Object} data 请求体
* @return {{ ok: boolean, ids?: number[], code?: number, message?: string }} 归一化结果
*/
normalizeCancelEntryOrderIds(data = {}) {
const hasIdsField = Object.prototype.hasOwnProperty.call(data, 'ids');
const hasIdField = Object.prototype.hasOwnProperty.call(data, 'id');
if (!hasIdsField && !hasIdField) {
return {
ok: false,
code: 400,
message: 'id 或 ids 必填',
};
}
const rawIds = hasIdsField ? data.ids : [ data.id ];
if (hasIdsField) {
if (!Array.isArray(rawIds) || rawIds.length === 0) {
return {
ok: false,
code: 400,
message: 'ids 必须是非空数组',
};
}
} else if (!Number.isInteger(Number(rawIds[0])) || Number(rawIds[0]) <= 0) {
return {
ok: false,
code: 400,
message: 'id 必填且必须为正整数',
};
}
const normalizedIds = [];
for (const rawId of rawIds) {
const normalizedId = Number(rawId);
if (!Number.isInteger(normalizedId) || normalizedId <= 0) {
return {
ok: false,
code: 400,
message: 'ids 必须为正整数数组',
};
}
normalizedIds.push(normalizedId);
}
return {
ok: true,
ids: [ ...new Set(normalizedIds) ],
};
}
/**
* 查询当前仓库可访问的入库单。
* @param {number} id 入库单ID
* @return {Promise<Object|null>} 入库单实例
*/
async getOwnedEntryOrderById(id) {
const { ctx } = this;
return await ctx.model.EntryOrder.findOne({
where: {
id,
warehouse_id: ctx.user.store_id,
is_enabled: 1,
deleted_at: null,
},
});
}
/**
* 作废入库单。
* @param {Object} data 请求体
* @return {Promise<Object>} code/data/message 结构
*/
async cancel(data = {}) {
const { ctx } = this;
const normalizedResult = this.normalizeCancelEntryOrderIds(data);
if (!normalizedResult.ok) {
return {
code: normalizedResult.code || 400,
message: normalizedResult.message || '参数错误',
data: null,
};
}
const orderIds = normalizedResult.ids || [];
for (const orderId of orderIds) {
const entryOrder = await this.getOwnedEntryOrderById(orderId);
if (!entryOrder) {
return {
code: 404,
message: '入库单不存在或无权访问',
data: null,
};
}
// 6b: sync_status=SUCCESS 不可取消
if (entryOrder.sync_status === 'SUCCESS') {
return {
code: 400,
message: '入库单已完成回传,不可取消',
data: null,
};
}
if (entryOrder.order_status === 'COMPLETED') {
return {
code: 400,
message: '已完成入库单不允许作废',
data: null,
};
}
if (entryOrder.order_status === 'CANCELLED') {
return {
code: 400,
message: '入库单已作废',
data: null,
};
}
// 6a: QM 来源需发送取消同步
if (String(entryOrder.source_type) === 'QM') {
const entryItems = await ctx.model.EntryItems.findAll({
where: { order_id: entryOrder.id },
attributes: [ 'item_code', 'item_id', 'count', 'inventory_type', 'owner_code' ],
raw: true,
});
const orderLines = (entryItems || []).map((item, idx) => ({
orderLineNo: idx + 1,
ownerCode: item.owner_code || '',
itemCode: item.item_code || '',
itemId: item.item_id || '',
inventoryType: item.inventory_type || 'ZP',
planQty: item.count || 0,
actualQty: 0, // 全部为 0,通知 ERP 关闭
}));
const syncResult = await ctx.service.systems.inboundDirectLog.qimenEntrySync({
entryOrder,
orderLines,
outBizCode: `CANCEL_${Date.now()}`,
remark: '入库单取消',
operator: {
id: ctx.user?.employees_id || ctx.user?.id || '',
name: ctx.user?.employees_name || '',
},
});
if (!syncResult.success) {
return {
code: 500,
message: `取消失败: ${syncResult.message}`,
data: null,
};
}
}
// 更新状态
await entryOrder.update({
order_status: 'CANCELLED',
updated_at: new Date(),
});
// 回退关联收货单的入库状态,避免死锁
await this._rollbackReceivingStorageStatus(entryOrder.id);
// 写操作日志
await ctx.service.systems.operationLog.createOperationLog({
businessType: 'entry_order',
businessId: entryOrder.id,
operationCode: 'ENTRY_ORDER_CANCEL',
operator: {
id: ctx.user?.employees_id || ctx.user?.id || '',
name: ctx.user?.employees_name || '',
},
extras: {
warehouseId: entryOrder.warehouse_id,
message: '入库单已取消',
},
});
}
return {
code: 200,
message: '作废成功',
data: { ids: orderIds },
};
}
/**
* 回退入库单关联收货单的入库状态(入库单作废时调用)。
* 失败不阻塞主流程,仅打印日志。
* @param {number} entryOrderId 入库单ID
* @return {Promise<void>}
*/
async _rollbackReceivingStorageStatus(entryOrderId) {
const { ctx } = this;
try {
// 1. 查询关联的收货单ID列表
const bindings = await ctx.model.EntryOrderReceiving.findAll({
where: { entry_order_id: entryOrderId, deleted_at: null },
attributes: [ 'receiving_id' ],
raw: true,
});
const receivingIds = (bindings || [ ]).map(b => b.receiving_id).filter(Boolean);
if (receivingIds.length === 0) {
return;
}
// 2. 回退收货单主表 storage_status → 'none'
await ctx.model.Receiving.update(
{ storage_status: 'none', updated_at: new Date() },
{ where: { id: { [ctx.app.Sequelize.Op.in]: receivingIds } } }
);
// 3. 回退收货单明细 storage_status → 'none', stored_quantity → 0
await ctx.model.ReceivingDetail.update(
{ storage_status: 'none', stored_quantity: 0, updated_at: new Date() },
{ where: { receiving_id: { [ctx.app.Sequelize.Op.in]: receivingIds } } }
);
ctx.logger.info(
`[storage.entry.cancel] 入库单 ${entryOrderId} 作废,已回退收货单入库状态,receivingIds=[${receivingIds.join(',')}]`
);
} catch (err) {
ctx.logger.error(
`[storage.entry.cancel] 回退收货单入库状态失败,entryOrderId=${entryOrderId},err=${err.message}`
);
}
}
/**
* 按商品增量添加导入/PDA 直接入库记录(转发到 inboundDirectLog)。
* @param {Object} data 请求体
* @param {string} data.entry_order_code 入库单号
* @param {number} [data.stock_id] 商品SKU ID(单条模式)
* @param {number} [data.quantity] 本次入库数量(单条模式)
* @param {string} [data.inbound_type] 入库方式(单条模式)
* @param {Array} [data.items] 商品列表(批量模式)
* @return {Promise<Object>} code/data/message 结构
*/
async addItem(data = {}) {
const { ctx } = this;
return await ctx.service.systems.inboundDirectLog.addItem(data);
}
/**
* 提交确认完成导入/PDA 直接入库(转发到 inboundDirectLog)。
* @param {string} entryOrderCode 入库单号
* @return {Promise<Object>} code/data/message 结构
*/
async commit(entryOrderCode) {
const { ctx } = this;
return await ctx.service.systems.inboundDirectLog.commit(entryOrderCode);
}
/**
* 移除一条导入/PDA 直接入库记录(转发到 inboundDirectLog)。
* @param {Object} data 请求体
* @param {number} data.id 入库记录ID
* @return {Promise<Object>} code/data/message 结构
*/
async removeItem(data = {}) {
const { ctx } = this;
return await ctx.service.systems.inboundDirectLog.removeItem(data);
}
/**
* 查询入库单已绑定收货单中匹配指定 stock_id 的收货明细列表。
* 用于 PDA 导入时选择要绑定的收货明细。
* @param {Object} data 请求体
* @param {number} data.entry_order_id 入库单 ID
* @param {number} data.stock_id 商品 stock_id
* @return {Promise<Object>} { code, message, data: { list: [{ receiving_detail_id, receiving_id, receiving_number, actual_quantity, used_quantity, available_quantity, system_product_id }] } }
*/
async getReceivingDetailsForBind(data = {}) {
const { ctx, app } = this;
const entryOrderId = Number(data.entry_order_id);
const stockId = Number(data.stock_id);
if (!entryOrderId || !stockId) {
return { code: 400, message: 'entry_order_id 和 stock_id 必填', data: null };
}
// 1. 查入库单绑定的收货单 ID 列表
const orderReceivings = await ctx.model.EntryOrderReceiving.findAll({
where: { entry_order_id: entryOrderId, deleted_at: null },
attributes: [ 'receiving_id' ],
raw: true,
});
if (!orderReceivings.length) {
return { code: 200, message: 'ok', data: { list: [] } };
}
const receivingIds = orderReceivings.map(r => r.receiving_id);
// 2. 查收货明细(system_product_id = stockId,且收货单未取消/未删除)
const details = await ctx.model.ReceivingDetail.findAll({
where: {
system_product_id: stockId,
receiving_id: receivingIds,
deleted_at: null,
},
attributes: [ 'id', 'receiving_id', 'actual_quantity', 'system_product_id' ],
include: [{
model: ctx.model.Receiving,
as: 'receiving',
attributes: [ 'id', 'receiving_number', 'status' ],
where: { status: { [ app.Sequelize.Op.ne ]: 'cancelled' }, deleted_at: null },
required: true,
}],
raw: false,
});
// 3. 查每个明细的已占用数量(pending + committed)
const detailIds = details.map(d => d.id);
const usedMap = new Map();
if (detailIds.length > 0) {
const usedRows = await ctx.model.query(
`SELECT receiving_detail_id, COALESCE(SUM(quantity), 0) AS used_qty
FROM wms_inbound_direct_log
WHERE receiving_detail_id IN (:ids)
AND status IN ('pending', 'committed')
AND deleted_at IS NULL
GROUP BY receiving_detail_id`,
{
replacements: { ids: detailIds },
type: ctx.model.QueryTypes.SELECT,
}
);
for (const row of usedRows) {
usedMap.set(row.receiving_detail_id, Number(row.used_qty));
}
}
// 4. 组装返回
const list = details.map(d => {
const rid = d.id;
const used = usedMap.get(rid) || 0;
return {
receiving_detail_id: rid,
receiving_id: d.receiving_id,
receiving_number: d.receiving?.receiving_number || '',
actual_quantity: d.actual_quantity || 0,
used_quantity: used,
available_quantity: Math.max(0, (d.actual_quantity || 0) - used),
system_product_id: d.system_product_id,
};
});
return { code: 200, message: 'ok', data: { list } };
}
/**
* 拉取入库单绑定的收货单中,指定商品的可用容器列表(收货明细)。
* 用于 PDA 上架时选择容器。
* @param {Object} data 请求参数
* @param {number} data.entry_order_id 入库单ID
* @param {number} data.stock_id 商品stock_id
* @return {Promise<Object>} { code, message, data: { list, total } }
*/
async containerList(data = {}) {
const { ctx, app } = this;
const warehouseId = ctx.user?.store_id;
const entryOrderId = Number(data.entry_order_id);
const stockId = Number(data.stock_id);
// 参数校验
if (!warehouseId) {
return { code: 0, message: '用户未绑定仓库', data: null };
}
if (!entryOrderId || entryOrderId <= 0) {
return { code: 0, message: 'entry_order_id 不能为空', data: null };
}
if (!stockId || stockId <= 0) {
return { code: 0, message: 'stock_id 不能为空', data: null };
}
try {
// 1. 验证入库单存在且属于当前仓库
const entryOrder = await ctx.model.EntryOrder.findOne({
where: {
id: entryOrderId,
warehouse_id: warehouseId,
},
attributes: [ 'id' ],
raw: true,
});
if (!entryOrder) {
return { code: 0, message: '入库单不存在或无权访问', data: null };
}
// 2. 通过 wms_entry_order_receiving 查出关联的 receiving_id 列表
const entryReceivingRows = await ctx.model.EntryOrderReceiving.findAll({
where: { entry_order_id: entryOrderId, deleted_at: null },
attributes: [ 'receiving_id' ],
raw: true,
});
const receivingIds = entryReceivingRows.map(r => r.receiving_id).filter(Boolean);
if (receivingIds.length === 0) {
return { code: 200, message: 'ok', data: { list: [], total: 0 } };
}
// 3. 查询指定商品的所有收货明细(不再一刀切排除已绑定,改为按可用量过滤)
const details = await ctx.model.ReceivingDetail.findAll({
where: {
system_product_id: stockId,
receiving_id: { [app.Sequelize.Op.in]: receivingIds },
},
raw: true,
});
// 4. 查询每个明细的已入库数量(pending + committed,与 getReceivingDetailsForBind 一致)
const detailIds = details.map(d => d.id);
const usedMap = new Map();
if (detailIds.length > 0) {
const usedRows = await ctx.model.query(
`SELECT receiving_detail_id, COALESCE(SUM(quantity), 0) AS used_qty
FROM wms_inbound_direct_log
WHERE receiving_detail_id IN (:ids)
AND status IN ('pending', 'committed')
AND deleted_at IS NULL
GROUP BY receiving_detail_id`,
{
replacements: { ids: detailIds },
type: ctx.model.QueryTypes.SELECT,
}
);
for (const row of usedRows) {
usedMap.set(row.receiving_detail_id, Number(row.used_qty));
}
}
// 5. 收集所有明细的 system_product_id,批量获取 stock 详情
const stockIdSet = new Set();
for (const d of details) {
if (d.system_product_id != null) {
stockIdSet.add(Number(d.system_product_id));
}
}
const stockIds = [ ...stockIdSet ];
/** @type {Map<number, Object>} */
const stockDetailMap = new Map();
if (stockIds.length > 0) {
const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(stockIds, { warehouseId });
for (const sd of stockDetails) {
if (sd && sd.id != null) {
stockDetailMap.set(sd.id, sd);
}
}
}
// 6. 组装返回结果:actual_quantity 扣除已入库数量,只返回有可用量的明细
const list = details
.map(detail => {
const used = usedMap.get(detail.id) || 0;
const available = Math.max(0, (detail.actual_quantity || 0) - used);
return {
detail_id: detail.id,
receiving_id: detail.receiving_id,
barcode: detail.barcode || '',
product_name: detail.product_name || '',
actual_quantity: available,
receiving_status: detail.receiving_status || '',
stock: stockDetailMap.get(Number(detail.system_product_id)) || null,
};
})
.filter(detail => detail.actual_quantity > 0);
return {
code: 200,
message: 'ok',
data: {
list,
total: list.length,
},
};
} catch (error) {
ctx.logger.error('[storage.entry.containerList] 查询容器列表失败', error);
return { code: 500, message: `服务器错误: ${error.message}`, data: null };
}
}
/**
* 快捷直入后回写绑定收货单的明细已入库数量与入库状态(事务内)。
* 按 stock_id(=收货明细 system_product_id)把本次入库量依次分配到收货明细上,
* 每个明细最多分配其剩余可入数量(actual_quantity - stored_quantity),
* 分配后更新明细 stored_quantity/storage_status,并按各明细实际入库量
* (stored_quantity 与 actual_quantity 比较)汇总更新收货单主表 storage_status:
* 全部明细均已足量入库才置 all,否则有部分入库置 partial,全部未入库置 none。
* @param {Object} params 参数
* @param {Array<Object>} params.receivingDetailRows 收货明细快照 [{ id, receiving_id, system_product_id, actual_quantity, stored_quantity }]
* @param {Map<number, {inboundQty: number}>} params.stockInboundQtyMap stock_id -> 本次入库量
* @param {Object} params.transaction Sequelize 事务对象
* @return {Promise<void>}
*/
async _applyReceivingInboundUsage({ receivingDetailRows, stockInboundQtyMap, transaction }) {
const { ctx, app } = this;
if (!receivingDetailRows || receivingDetailRows.length === 0) return;
// 1. 事务内行锁重新读取收货明细,避免并发超额分配
const detailIds = receivingDetailRows.map(d => d.id);
const lockedDetails = await ctx.model.ReceivingDetail.findAll({
where: { id: { [app.Sequelize.Op.in]: detailIds } },
lock: transaction.LOCK.UPDATE,
order: [[ 'id', 'ASC' ]],
transaction,
raw: true,
});
// 2. 按 system_product_id(=stock_id)分组,同一商品多条明细按 id 升序依次分配
const detailsByStock = new Map();
for (const d of lockedDetails) {
const spid = Number(d.system_product_id);
if (!spid) continue;
if (!detailsByStock.has(spid)) detailsByStock.set(spid, []);
detailsByStock.get(spid).push(d);
}
const touchedReceivingIds = new Set();
// 3. 逐商品分配本次入库量:使用了多少就写多少
for (const [ stockId, plan ] of stockInboundQtyMap) {
let left = Number(plan.inboundQty) || 0;
const details = detailsByStock.get(Number(stockId)) || [];
for (const detail of details) {
if (left <= 0) break;
const actual = Number(detail.actual_quantity) || 0;
const stored = Number(detail.stored_quantity) || 0;
const remain = Math.max(0, actual - stored);
if (remain <= 0) continue;
const delta = Math.min(left, remain);
const newStored = stored + delta;
const storageStatus = newStored >= actual ? 'all' : 'partial';
await ctx.model.ReceivingDetail.update({
stored_quantity: newStored,
storage_status: storageStatus,
updated_at: new Date(),
}, {
where: { id: detail.id },
transaction,
});
touchedReceivingIds.add(Number(detail.receiving_id));
left -= delta;
}
}
// 4. 按实际入库量汇总更新收货单主表 storage_status:
// 全部明细均已足量入库(stored >= actual)→ all;存在部分入库 → partial;全部未入库 → none
for (const receivingId of touchedReceivingIds) {
const allDetails = await ctx.model.ReceivingDetail.findAll({
where: { receiving_id: receivingId },
attributes: [ 'actual_quantity', 'stored_quantity' ],
raw: true,
transaction,
});
let masterStatus = 'none';
const fullyStored = allDetails.length > 0
&& allDetails.every(d => (Number(d.stored_quantity) || 0) >= (Number(d.actual_quantity) || 0));
if (fullyStored) {
masterStatus = 'all';
} else if (allDetails.some(d => (Number(d.stored_quantity) || 0) > 0)) {
masterStatus = 'partial';
}
await ctx.model.Receiving.update({
storage_status: masterStatus,
updated_at: new Date(),
}, {
where: { id: receivingId },
transaction,
});
}
ctx.logger.info(
`[storage.entry] 已回写收货单入库状态,receivingIds=[${[ ...touchedReceivingIds ].join(',')}]`
);
}
/**
* 快捷直入/虚拟入库:将入库单明细直入到虚拟库位(space_id=2),跳过收货、质检等正常流程。
* 有绑定收货单时,只取收货单中与入库单明细有交集(按 stock_id 判断)且剩余可入数量的部分直入,
* 并回写收货单明细已入库数量;未绑定收货单时按明细计划数量全量直入。
* 有绑定收货单时回写 is_virtual_inbound=0(非虚拟入库),无绑定收货单时回写 is_virtual_inbound=1(虚拟入库)。
* 采用"先同步后写库"两段式:① 先发奇门/OpenAPI 回传,② 回传成功后再开启事务写库存。
* @param {Object} data 请求体
* @param {number} data.id 入库单ID
* @return {Promise<Object>} code/data/message 结构
*/
async quickInbound(data = {}) {
const { ctx, app } = this;
const orderId = Number(data.id || 0);
if (!orderId) {
return {
code: 400,
message: 'id 必填',
data: null,
};
}
// 1. 校验入库单
const entryOrder = await this.getOwnedEntryOrderById(orderId);
if (!entryOrder) {
return {
code: 404,
message: '入库单不存在或无权访问',
data: null,
};
}
if (entryOrder.order_status !== 'CREATED') {
if (entryOrder.order_status === 'CANCELLED') {
return {
code: 400,
message: '已作废入库单不允许快捷入库',
data: null,
};
}
if (entryOrder.order_status === 'COMPLETED') {
return {
code: 400,
message: '入库单已完成,请勿重复提交',
data: null,
};
}
return {
code: 400,
message: `入库单状态不允许快捷直入,当前状态:${entryOrder.order_status}`,
data: null,
};
}
// 2. 查询入库单所有明细
const entryItems = await ctx.model.EntryItems.findAll({
where: { order_id: entryOrder.id },
});
if (!entryItems.length) {
return {
code: 400,
message: '请先添加入库明细',
data: null,
};
}
// 2.1 查询绑定收货单("已绑定"状态),按 stock_id 聚合收货明细剩余可入数量
const bindings = await ctx.model.EntryOrderReceiving.findAll({
where: { entry_order_id: entryOrder.id, deleted_at: null },
attributes: [ 'receiving_id' ],
raw: true,
});
const receivingIds = [ ...new Set((bindings || []).map(b => Number(b.receiving_id)).filter(Boolean)) ];
// 收货明细快照(用于事务内行锁回写),stockRemainingMap: null=未绑定(全量直入)
let receivingDetailsSnapshot = [];
let stockRemainingMap = null;
if (receivingIds.length > 0) {
const boundDetails = await ctx.model.ReceivingDetail.findAll({
where: {
receiving_id: { [app.Sequelize.Op.in]: receivingIds },
system_product_id: { [app.Sequelize.Op.ne]: null },
},
attributes: [ 'id', 'receiving_id', 'system_product_id', 'actual_quantity', 'stored_quantity' ],
raw: true,
});
receivingDetailsSnapshot = boundDetails;
stockRemainingMap = new Map();
for (const d of boundDetails) {
const spid = Number(d.system_product_id);
const remaining = Math.max(0, (Number(d.actual_quantity) || 0) - (Number(d.stored_quantity) || 0));
stockRemainingMap.set(spid, (stockRemainingMap.get(spid) || 0) + remaining);
}
}
// 2.2 按入库单明细计算实际直入数量:有绑定时只取收货单中有交集(stock_id)且剩余可入的数量
const inboundPlans = entryItems.map(item => {
const planQty = Number(item.count) || 0;
let inboundQty = planQty;
if (stockRemainingMap) {
const stockId = Number(item.stock_id) || 0;
if (!stockId || !stockRemainingMap.has(stockId)) {
inboundQty = 0; // 收货单无交集商品,跳过
} else {
const remaining = stockRemainingMap.get(stockId) || 0;
inboundQty = Math.min(planQty, remaining);
stockRemainingMap.set(stockId, remaining - inboundQty);
}
}
return { item, planQty, inboundQty };
});
const effectivePlans = inboundPlans.filter(p => p.inboundQty > 0);
if (effectivePlans.length === 0) {
return {
code: 400,
message: stockRemainingMap
? '收货单中无交集商品或剩余可入数量不足,无法快捷直入'
: '入库明细数量均为0,无法快捷直入',
data: { id: entryOrder.id, entry_order_code: entryOrder.entry_order_code },
};
}
// 存在被截断/跳过的明细时按部分入库回传(confirmType=1, PARTFULFILLED)
const isPartialInbound = inboundPlans.some(p => p.inboundQty < p.planQty);
// ===== 阶段一 + 阶段二合并为统一调用 =====
const syncResult = await ctx.service.systems.inboundDirectLog.qimenEntrySync({
entryOrder,
orderLines: effectivePlans.map((plan, idx) => ({
orderLineNo: idx + 1,
ownerCode: plan.item.owner_code || '',
itemCode: plan.item.item_code || '',
itemId: plan.item.item_id || '',
inventoryType: plan.item.inventory_type || 'ZP',
planQty: plan.planQty,
actualQty: plan.inboundQty,
})),
isFin: !isPartialInbound,
outBizCode: `DIRECT_INBOUND_${Date.now()}`,
remark: '导入/PDA直接入库提交',
operator: {
id: ctx.user?.employees_id || ctx.user?.id,
name: ctx.user?.employees_name || '',
},
onSuccess: async eo => {
const warehouseId = eo.warehouse_id;
const storeId = eo.store_id;
const batchNo = eo.entry_order_code;
const hardcodedSpaceId = 2;
const transaction = await ctx.model.transaction();
const processedStockIds = new Set();
let totalInboundQty = 0;
let totalPlanQty = 0;
// 按 stock_id 汇总本次实际入库量与库存类型(有绑定收货单时实际入库量 ≤ 计划量)
const stockPlanMap = new Map();
for (const plan of inboundPlans) {
totalPlanQty += plan.planQty;
if (plan.inboundQty <= 0) continue;
const stockId = Number(plan.item.stock_id);
if (!stockId) continue;
const cur = stockPlanMap.get(stockId) || { inboundQty: 0, inventoryType: plan.item.inventory_type || 'ZP' };
cur.inboundQty += plan.inboundQty;
stockPlanMap.set(stockId, cur);
totalInboundQty += plan.inboundQty;
}
if (totalInboundQty <= 0) {
throw new Error('无有效可入明细,快捷直入失败');
}
try {
// 回写入库单明细:本次实际入库多少写多少(跳过明细写 0)
for (const plan of inboundPlans) {
await ctx.model.EntryItems.update({
received_quantity: plan.inboundQty,
}, {
where: { id: plan.item.id },
transaction,
});
}
for (const [ stockId, plan ] of stockPlanMap) {
const planQty = plan.inboundQty;
const inventoryType = plan.inventoryType;
const stockRecord = await ctx.model.StockWarehouse.findOne({
where: { id: stockId, is_valid: 'Y', deleted_at: null },
lock: transaction.LOCK.UPDATE,
transaction,
});
if (!stockRecord) {
throw new Error(`商品库存记录不存在或已失效,无法入库: stock_id=${stockId}`);
}
const beforeQuantity = Number(stockRecord.quantity) || 0;
const beforeLockedQuantity = Number(stockRecord.locked_quantity) || 0;
await stockRecord.increment('quantity', { by: planQty, transaction, silent: true });
await stockRecord.reload({ transaction });
// 负库存回填:按 SW 非负增量冲销 GAP 补建行挂账(平账,拦截锁定回归真实数据)
if (beforeQuantity <= 0) {
const nonNegativeDelta = Math.max(0, Number(stockRecord.quantity) || 0) - Math.max(0, beforeQuantity);
await ctx.service.systems.storage.index.offsetGapOnInbound(stockId, planQty, {
transaction,
maxOffset: nonNegativeDelta,
orderNo: eo.entry_order_code || 'QUICK_INBOUND',
orderId: eo.id,
operatorId: String(ctx.user?.employees_id || ctx.user?.id || ''),
operatorName: ctx.user?.employees_name || '',
});
}
const afterQuantity = Number(stockRecord.quantity) || 0;
const afterLockedQuantity = Number(stockRecord.locked_quantity) || 0;
await ctx.service.systems.stockTransaction.create({
transaction_type: 'INBOUND',
warehouse_id: warehouseId,
store_id: storeId,
stock_id: stockId,
quantity: planQty,
batch_no: batchNo,
order_type: eo.order_type,
order_no: eo.entry_order_code,
entry_order_id: eo.id,
operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''),
operator_name: ctx.user?.employees_name || '',
remark: '快捷直入/虚拟入库',
before_quantity: beforeQuantity,
after_quantity: afterQuantity,
before_locked_quantity: beforeLockedQuantity,
after_locked_quantity: afterLockedQuantity,
created_at: new Date(),
}, { transaction });
const storageRecord = await ctx.model.Storage.findOne({
where: {
space_id: hardcodedSpaceId,
stock_id: stockId,
batch_no: batchNo,
inventory_type: inventoryType,
is_enabled: 1,
delete_at: null,
},
lock: transaction.LOCK.UPDATE,
transaction,
});
let storageId = null;
let storageBeforeQty = 0;
let storageAfterQty = 0;
let storageBeforeLockedQty = 0;
let storageAfterLockedQty = 0;
let storageBeforeInterceptQty = 0;
let storageAfterInterceptQty = 0;
if (storageRecord) {
storageBeforeQty = Number(storageRecord.quantity) || 0;
storageAfterQty = storageBeforeQty + planQty;
storageBeforeLockedQty = Number(storageRecord.locked_quantity) || 0;
storageAfterLockedQty = storageBeforeLockedQty;
storageBeforeInterceptQty = Number(storageRecord.intercept_locked_quantity) || 0;
storageAfterInterceptQty = storageBeforeInterceptQty;
await ctx.model.Storage.update({
quantity: app.Sequelize.literal(`quantity + ${planQty}`),
available_quantity: app.Sequelize.literal(`available_quantity + ${planQty}`),
entry_order_id: eo.id,
inbound_time: new Date(),
inbound_order_no: eo.entry_order_code,
updated_at: new Date(),
}, {
where: { id: storageRecord.id },
transaction,
});
storageId = storageRecord.id;
} else {
storageBeforeQty = 0;
storageAfterQty = planQty;
storageBeforeLockedQty = 0;
storageAfterLockedQty = 0;
const createdStorage = await ctx.model.Storage.create({
warehouse_id: warehouseId,
store_id: storeId,
space_id: hardcodedSpaceId,
stock_id: stockId,
batch_no: batchNo,
inventory_type: inventoryType,
quantity: planQty,
locked_quantity: 0,
available_quantity: planQty,
inbound_time: new Date(),
inbound_order_no: eo.entry_order_code,
receiving_id: null,
entry_order_id: eo.id,
supplier_id: null,
supplier_batch_no: null,
is_enabled: 1,
created_at: new Date(),
updated_at: new Date(),
}, { transaction });
storageId = createdStorage.id;
}
// 写入库位维度库存流水
await ctx.model.StorageTransaction.create({
transaction_type: 'INBOUND',
warehouse_id: warehouseId,
store_id: storeId,
stock_id: stockId,
storage_id: storageId,
space_id: hardcodedSpaceId,
quantity: planQty,
before_quantity: storageBeforeQty,
after_quantity: storageAfterQty,
before_locked_quantity: storageBeforeLockedQty,
after_locked_quantity: storageAfterLockedQty,
before_intercept_locked_quantity: storageBeforeInterceptQty,
after_intercept_locked_quantity: storageAfterInterceptQty,
batch_no: batchNo,
inventory_type: inventoryType,
order_type: 'entry_order',
order_no: eo.entry_order_code,
order_id: eo.id,
operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''),
operator_name: ctx.user?.employees_name || '',
remark: '快捷直入/虚拟入库',
created_at: new Date(),
}, { transaction });
}
// 回写绑定收货单明细已入库数量与入库状态(有绑定收货单时)
if (receivingDetailsSnapshot.length > 0) {
await this._applyReceivingInboundUsage({
receivingDetailRows: receivingDetailsSnapshot,
stockInboundQtyMap: stockPlanMap,
transaction,
});
}
await eo.update({
order_status: 'COMPLETED',
sync_status: 'SUCCESS',
// 有绑定收货单 → 非虚拟入库(0);无绑定收货单 → 虚拟入库(1)
is_virtual_inbound: receivingIds.length > 0 ? 0 : 1,
sync_message: JSON.stringify({
completedAt: new Date(),
totalQuantity: totalInboundQty,
planQuantity: totalPlanQty,
itemCount: processedStockIds.size,
source: 'quick_inbound',
}),
updated_at: new Date(),
}, { transaction });
await ctx.service.systems.operationLog.createOperationLog({
businessType: 'entry_order',
businessId: eo.id,
operationCode: 'QUICK_INBOUND',
operator: {
id: ctx.user?.employees_id || ctx.user?.id,
name: ctx.user?.employees_name || '',
},
extras: {
warehouseId: eo.warehouse_id,
message: `快捷直入完成,共 ${processedStockIds.size} 种商品,总数量 ${totalInboundQty}`,
},
transaction,
});
await transaction.commit();
// 入库完成通知货主(失败不影响主流程)
try {
await ctx.service.systems.inboundDirectLog.notifyEntryOrderCompleted(eo);
} catch (noticeErr) {
ctx.logger.warn('[storage.entry.quickInbound] 入库完成通知货主失败,不影响业务', noticeErr);
}
} catch (error) {
if (transaction && typeof transaction.rollback === 'function') {
await transaction.rollback();
}
throw error;
}
},
});
if (!syncResult.success) {
return {
code: 500,
message: syncResult.message,
data: {
id: entryOrder.id,
entry_order_code: entryOrder.entry_order_code,
sync_status: 'FAILED',
},
};
}
return {
code: 200,
message: '快捷入库完成',
data: {
id: entryOrder.id,
entry_order_code: entryOrder.entry_order_code,
order_status: 'COMPLETED',
sync_status: 'SUCCESS',
items_count: effectivePlans.length,
total_quantity: effectivePlans.reduce((s, p) => s + p.inboundQty, 0),
plan_quantity: entryItems.reduce((s, item) => s + (Number(item.count) || 0), 0),
},
};
}
/**
* 入库单商品与收货单商品对照视图(支持多个收货单)。
* 以入库单明细为对比主体:多个收货单的明细先合并为一个整体,
* 再与入库单明细做一次对照,每个入库明细只输出一行,
* 避免多收货单时入库计划数量被重复展开。
*
* @param {Object} data 请求参数
* @param {number} data.entry_order_id 入库单ID
* @param {number[]} [data.receiving_ids] 收货单ID列表(优先使用)
* @param {number} [data.receiving_id] 单个收货单ID(向后兼容,receiving_ids 优先)
* @return {Promise<Object>} code/data/message 结构
*/
async receivingCompare(data = {}) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
const entryOrderId = Number(data.entry_order_id || 0);
const warehouseId = ctx.user.store_id;
// 入参处理:receiving_ids 优先,receiving_id 向后兼容
let receivingIds = data.receiving_ids;
if (!Array.isArray(receivingIds) || receivingIds.length === 0) {
const singleId = Number(data.receiving_id || 0);
if (singleId) {
receivingIds = [ singleId ];
} else {
return { code: 400, message: 'receiving_ids 或 receiving_id 必填', data: null };
}
}
receivingIds = [ ...new Set(receivingIds.map(id => Number(id)).filter(Boolean)) ];
if (!entryOrderId) {
return { code: 400, message: 'entry_order_id 必填', data: null };
}
// 1. 校验入库单存在性
const entryOrder = await this.getOwnedEntryOrderById(entryOrderId);
if (!entryOrder) {
return { code: 404, message: '入库单不存在或无权访问', data: null };
}
// 2. 查询入库单明细
const entryItems = await ctx.model.EntryItems.findAll({
where: { order_id: entryOrderId },
attributes: [ 'id', 'stock_id', 'count', 'received_quantity' ],
raw: true,
});
// 3. 批量校验收货单(同仓库、未删除),无效的进入 errors
const receivingOrders = await ctx.model.Receiving.findAll({
where: {
id: { [Op.in]: receivingIds },
warehouse_id: warehouseId,
is_deleted: false,
},
attributes: [ 'id', 'receiving_number' ],
raw: true,
});
const receivingOrderMap = new Map(receivingOrders.map(row => [ Number(row.id), row ]));
const errors = [];
for (const receivingId of receivingIds) {
if (!receivingOrderMap.has(receivingId)) {
errors.push({
receiving_id: receivingId,
status: 'error',
error_code: 'RECEIVING_NOT_FOUND',
error_message: '收货单不存在或无权访问',
});
}
}
const validReceivingIds = [ ...receivingOrderMap.keys() ];
// 4. 合并所有有效收货单的明细,再与入库单做一次对照
let receivingDetails = [];
if (validReceivingIds.length > 0) {
receivingDetails = await ctx.model.ReceivingDetail.findAll({
where: { receiving_id: { [Op.in]: validReceivingIds } },
attributes: [ 'id', 'receiving_id', 'system_product_id', 'actual_quantity', 'product_name' ],
raw: true,
});
}
const merged = await this._buildMergedComparison({
warehouseId,
entryItems,
receivingDetails,
receivingOrderMap,
});
return {
code: 200,
message: '查询成功',
data: {
entry_order_id: entryOrderId,
entry_order_code: entryOrder.entry_order_code,
comparison: merged.comparison,
receiving_only: merged.receivingOnly,
summary: merged.summary,
errors,
total_summary: {
total_receivings: receivingIds.length,
matched_count: validReceivingIds.length,
error_count: errors.length,
},
},
};
}
/**
* 将多个收货单的明细合并后,与入库单明细做一次对照。
* 每个入库明细只输出一行(matched/entry_only),匹配时合并各收货单数量,
* 并通过 receiving_sources 列出各收货单来源明细。
*
* @param {Object} params 参数
* @param {number} params.warehouseId 仓库ID
* @param {Object[]} params.entryItems 入库单明细列表
* @param {Object[]} params.receivingDetails 已合并的收货单明细列表
* @param {Map} params.receivingOrderMap 有效收货单 Map(id → 收货单记录)
* @return {Promise<Object>} { comparison, receivingOnly, summary }
*/
async _buildMergedComparison(params = {}) {
const { ctx, app } = this;
const { warehouseId, entryItems, receivingDetails, receivingOrderMap } = params;
// 收集所有 stock_id,批量查询商品信息
const entryStockIds = [ ...new Set(entryItems.map(item => Number(item.stock_id)).filter(Boolean)) ];
const receivingSystemProductIds = [ ...new Set(receivingDetails.map(d => Number(d.system_product_id)).filter(Boolean)) ];
const allStockIds = [ ...new Set([ ...entryStockIds, ...receivingSystemProductIds ]) ];
const stockDetailMap = new Map();
if (allStockIds.length > 0) {
const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(allStockIds, { warehouseId });
for (const detail of stockDetails) {
stockDetailMap.set(Number(detail.id), detail);
}
}
// 仓库范围内有效的入库商品 stock_id(与原逻辑一致:仅匹配本仓库库存记录)
const validEntryStockIds = new Set(entryStockIds);
if (entryStockIds.length > 0) {
const swRows = await ctx.model.StockWarehouse.findAll({
where: { id: { [app.Sequelize.Op.in]: entryStockIds }, warehouse_id: warehouseId },
attributes: [ 'id' ],
raw: true,
});
validEntryStockIds.clear();
for (const row of swRows) {
validEntryStockIds.add(Number(row.id));
}
}
// 查询已分配量(限定本入库单的 entry_items,避免全局绑定干扰)
const receivingDetailIds = receivingDetails.map(d => Number(d.id));
const entryItemIds = entryItems.map(ei => Number(ei.id));
const allocatedMap = new Map();
if (receivingDetailIds.length > 0 && entryItemIds.length > 0) {
const bindingRows = await ctx.model.InboundDirectLog.findAll({
attributes: [
'receiving_detail_id',
[ app.Sequelize.fn('SUM', app.Sequelize.col('quantity')), 'total_allocated' ],
],
where: {
entry_item_id: { [app.Sequelize.Op.in]: entryItemIds },
receiving_detail_id: { [app.Sequelize.Op.in]: receivingDetailIds },
status: { [app.Sequelize.Op.in]: [ 'pending', 'committed' ] },
deleted_at: null,
},
group: [ 'receiving_detail_id' ],
raw: true,
});
for (const row of bindingRows) {
allocatedMap.set(Number(row.receiving_detail_id), Number(row.total_allocated) || 0);
}
}
// 按 stock_id 索引收货明细,供合并匹配
const detailsByStockId = new Map();
for (const rd of receivingDetails) {
const stockId = Number(rd.system_product_id) || 0;
if (stockId <= 0) continue;
if (!detailsByStockId.has(stockId)) {
detailsByStockId.set(stockId, []);
}
detailsByStockId.get(stockId).push(rd);
}
// 组装单个收货明细的来源信息
const buildSource = rd => {
const rdStockDetail = (rd.system_product_id != null && stockDetailMap.get(Number(rd.system_product_id))) || null;
const allocated = allocatedMap.get(Number(rd.id)) || 0;
const quantity = Number(rd.actual_quantity) || 0;
return {
receiving_id: Number(rd.receiving_id),
receiving_number: (receivingOrderMap.get(Number(rd.receiving_id)) || {}).receiving_number || '',
receiving_detail_id: Number(rd.id),
receiving_product_code: (rdStockDetail && rdStockDetail.item_code) || '',
receiving_product_name: rd.product_name || (rdStockDetail && rdStockDetail.item_name) || '',
receiving_actual_quantity: quantity,
receiving_allocated: allocated,
receiving_available: Math.max(0, quantity - allocated),
};
};
// 构建对照视图:以入库单明细为主,每个入库明细只输出一行
const comparison = [];
const matchedReceivingDetailIds = new Set();
for (const entryItem of entryItems) {
const stockId = Number(entryItem.stock_id || 0);
const stockDetail = stockDetailMap.get(stockId) || null;
const matchedDetails = stockId > 0 && validEntryStockIds.has(stockId)
? (detailsByStockId.get(stockId) || [])
: [];
if (matchedDetails.length > 0) {
const sources = [];
for (const rd of matchedDetails) {
matchedReceivingDetailIds.add(Number(rd.id));
sources.push(buildSource(rd));
}
const mergedQuantity = sources.reduce((sum, source) => sum + source.receiving_actual_quantity, 0);
const mergedAllocated = sources.reduce((sum, source) => sum + source.receiving_allocated, 0);
comparison.push({
entry_item_id: Number(entryItem.id),
stock_id: stockId,
warehouse_item_code: (stockDetail && stockDetail.item_code) || '',
warehouse_item_name: (stockDetail && stockDetail.item_name) || '',
warehouse_item_spec: (stockDetail && stockDetail.sku_property) || '',
entry_count: Number(entryItem.count) || 0,
entry_received: Number(entryItem.received_quantity) || 0,
match_status: 'matched',
receiving_quantity: mergedQuantity,
receiving_allocated: mergedAllocated,
receiving_available: Math.max(0, mergedQuantity - mergedAllocated),
receiving_sources: sources,
});
} else {
comparison.push({
entry_item_id: Number(entryItem.id),
stock_id: stockId,
warehouse_item_code: (stockDetail && stockDetail.item_code) || '',
warehouse_item_name: (stockDetail && stockDetail.item_name) || '',
warehouse_item_spec: (stockDetail && stockDetail.sku_property) || '',
entry_count: Number(entryItem.count) || 0,
entry_received: Number(entryItem.received_quantity) || 0,
match_status: 'entry_only',
receiving_quantity: 0,
receiving_allocated: 0,
receiving_available: 0,
receiving_sources: [],
});
}
}
// 收货单中多余的商品(合并后仍未匹配到任何入库明细的收货明细,按商品合并)
const receivingOnlyMap = new Map();
for (const rd of receivingDetails) {
if (matchedReceivingDetailIds.has(Number(rd.id))) continue;
const stockId = rd.system_product_id != null ? Number(rd.system_product_id) : null;
const source = buildSource(rd);
const key = stockId === null || Number.isNaN(stockId) ? '__none__' : String(stockId);
if (receivingOnlyMap.has(key)) {
const existing = receivingOnlyMap.get(key);
existing.receiving_actual_quantity += source.receiving_actual_quantity;
existing.receiving_allocated += source.receiving_allocated;
existing.receiving_available = Math.max(0, existing.receiving_available + source.receiving_available);
if (!existing.receiving_product_name && source.receiving_product_name) {
existing.receiving_product_name = source.receiving_product_name;
}
existing.receiving_sources.push(source);
} else {
receivingOnlyMap.set(key, {
stock_id: stockId,
receiving_product_code: source.receiving_product_code,
receiving_product_name: source.receiving_product_name,
receiving_actual_quantity: source.receiving_actual_quantity,
receiving_allocated: source.receiving_allocated,
receiving_available: source.receiving_available,
receiving_sources: [ source ],
});
}
}
const receivingOnly = [ ...receivingOnlyMap.values() ];
// 汇总
const matchedItems = comparison.filter(c => c.match_status === 'matched').length;
const entryOnlyItems = comparison.filter(c => c.match_status === 'entry_only').length;
return {
comparison,
receivingOnly,
summary: {
total_entry_items: entryItems.length,
matched_items: matchedItems,
entry_only_items: entryOnlyItems,
receiving_only_items: receivingOnly.length,
},
};
}
/**
* 导出入库单列表及明细(两 Sheet)。
* Sheet1: 入库单列表(wms_entry_order 关键字段)
* Sheet2: 入库单明细(wms_entry_items + wms_stock_warehouse)
*
* @param {Object} options 导出参数
* @param {Object} [options.where] 筛选条件(与 list 一致)
* @param {Object} [options.sort] 排序参数
* @param {Function} [options.onProgress] 进度回调
* @return {Promise<Object>} 上传结果与统计信息
*/
async exportEntryOrders(options = {}) {
const { ctx, app } = this;
const { Sequelize } = app;
const { Op } = Sequelize;
const safeOptions = this.isPlainObject ? (this.isPlainObject(options) ? options : {}) : (options && typeof options === 'object' ? options : {});
const where = safeOptions.where && typeof safeOptions.where === 'object' ? { ...safeOptions.where } : {};
const sort = safeOptions.sort && typeof safeOptions.sort === 'object' ? { ...safeOptions.sort } : {};
const progressHandler = typeof safeOptions.onProgress === 'function'
? safeOptions.onProgress
: async () => {};
const warehouseId = Number(ctx.user && ctx.user.store_id);
if (!warehouseId) {
throw new Error('用户未绑定仓库,无法导出');
}
const sortField = sort.sortField || 'created_at';
const sortOrder = String(sort.sortOrder || 'DESC').toUpperCase() === 'ASC' ? 'ASC' : 'DESC';
const validSortFields = [
'id', 'entry_order_code', 'order_type', 'order_status',
'order_create_time', 'created_at', 'updated_at', 'total_order_lines',
];
const actualSortField = validSortFields.includes(sortField) ? sortField : 'created_at';
const baseWhere = { warehouse_id: warehouseId, is_enabled: 1, deleted_at: null };
// ---- 复用 list 的 where 构建逻辑 ----
const normalizedWhere = { ...where };
const {
where: parsedSourceWhere,
extraConditions,
errorMessage,
} = await this.preprocessEntryListWhere(normalizedWhere);
if (errorMessage) {
throw new Error(errorMessage);
}
const parsed = parseWhereConditions({
where: parsedSourceWhere,
app,
specialFieldMap: {
quickWhere: {
bucket: 'quick',
},
},
});
if (!parsed.ok) {
throw new Error(`筛选条件解析失败: ${parsed.reason}`);
}
const parsedResult = parsed.result;
const quickWhereInput = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere)
|| parsedSourceWhere.quickWhere
|| null;
const quickWhereValue = quickWhereInput && typeof quickWhereInput === 'object'
? quickWhereInput.value
: null;
const andConditions = [ baseWhere ];
if (quickWhereValue !== undefined && quickWhereValue !== null && String(quickWhereValue).trim() !== '') {
const kw = String(quickWhereValue).trim();
const receivingDetailId = Number(kw);
const escapedKw = app.model.escape(`%${kw}%`);
const orConditions = [
{ entry_order_code: { [Op.like]: `%${kw}%` } },
{ purchase_order_code: { [Op.like]: `%${kw}%` } },
{ supplier_name: { [Op.like]: `%${kw}%` } },
{ store_name: { [Op.like]: `%${kw}%` } },
{ warehouse_name: { [Op.like]: `%${kw}%` } },
Sequelize.where(Sequelize.literal(
`EXISTS (
SELECT 1 FROM wms_entry_order_receiving eor
JOIN wms_receiving r ON r.id = eor.receiving_id
WHERE eor.entry_order_id = wms_entry_order.id
AND eor.deleted_at IS NULL
AND r.receiving_number LIKE ${escapedKw}
)`
), 1),
...(Number.isFinite(receivingDetailId) && receivingDetailId > 0 ? [
Sequelize.where(Sequelize.literal(
`EXISTS (
SELECT 1 FROM wms_entry_order_receiving eor
JOIN wms_receiving_detail rd ON rd.receiving_id = eor.receiving_id
WHERE eor.entry_order_id = wms_entry_order.id
AND eor.deleted_at IS NULL
AND rd.id = ${receivingDetailId}
)`
), 1),
] : []),
];
andConditions.push({ [Op.or]: orConditions });
}
const dynamicConditions = parsedResult.dynamicConditions || [];
if (dynamicConditions.length > 0) {
andConditions.push({ [Op.and]: dynamicConditions });
}
if (extraConditions.length > 0) {
andConditions.push({ [Op.and]: extraConditions });
}
const finalWhere = { [Op.and]: andConditions };
// ---- 分页拉取入库单列表 ----
const pageSize = ENTRY_EXPORT_PAGE_SIZE;
const totalCount = await ctx.model.EntryOrder.count({ where: finalWhere });
await progressHandler({
status: 'running',
progress: totalCount > 0 ? 10 : 90,
message: totalCount > 0 ? `已命中 ${totalCount} 条入库单,开始导出` : '未命中数据,开始生成空文件',
});
// 收集所有入库单 ID,供后续批量查明细
const allEntryOrders = [];
let page = 1;
let fetchedCount = 0;
while (fetchedCount < totalCount) {
const rows = await ctx.model.EntryOrder.findAll({
where: finalWhere,
order: [[ actualSortField, sortOrder ]],
limit: pageSize,
offset: (page - 1) * pageSize,
raw: true,
});
if (!Array.isArray(rows) || rows.length === 0) {
break;
}
allEntryOrders.push(...rows);
fetchedCount += rows.length;
page += 1;
await progressHandler({
status: 'running',
progress: Math.min(30, 10 + Math.round((fetchedCount / Math.max(totalCount, 1)) * 20)),
message: `正在拉取入库单列表,已完成 ${fetchedCount}/${totalCount}`,
});
}
// 收集所有入库单 ID
const allEntryOrderIds = allEntryOrders.map(r => Number(r.id)).filter(Boolean);
// ---- 分批拉取入库单明细 ----
/** @type {Map<number, Array<Object>>} entry_order_id → items */
const itemsMap = new Map();
/** @type {Set<number>} 所有涉及的商品 stock_id */
const allStockIds = new Set();
if (allEntryOrderIds.length > 0) {
const batchSize = ENTRY_ITEMS_FETCH_BATCH_SIZE;
const totalBatches = Math.ceil(allEntryOrderIds.length / batchSize);
for (let batchIdx = 0; batchIdx < allEntryOrderIds.length; batchIdx += batchSize) {
const batchIds = allEntryOrderIds.slice(batchIdx, batchIdx + batchSize);
const items = await ctx.model.EntryItems.findAll({
where: { order_id: { [Op.in]: batchIds } },
order: [[ 'order_id', 'ASC' ], [ 'order_line_no', 'ASC' ]],
raw: true,
});
for (const item of items) {
const eid = Number(item.order_id);
if (!itemsMap.has(eid)) {
itemsMap.set(eid, []);
}
itemsMap.get(eid).push(item);
if (item.stock_id) {
allStockIds.add(Number(item.stock_id));
}
}
const currentBatch = Math.floor(batchIdx / batchSize) + 1;
await progressHandler({
status: 'running',
progress: Math.min(50, 30 + Math.round((currentBatch / totalBatches) * 20)),
message: `正在拉取入库单明细,已完成批次 ${currentBatch}/${totalBatches}`,
});
}
}
// ---- 批量查询商品名称(wms_stock_warehouse) ----
/** @type {Map<number, Object>} stock_id → { item_name, sku_property, item_code } */
const stockInfoMap = new Map();
if (allStockIds.size > 0) {
const stockIdsArr = [ ...allStockIds ];
try {
const stockRows = await ctx.model.StockWarehouse.findAll({
where: { id: { [Op.in]: stockIdsArr }, warehouse_id: warehouseId },
attributes: [ 'id', 'item_code', 'item_name', 'sku_property' ],
raw: true,
});
for (const s of stockRows) {
stockInfoMap.set(Number(s.id), {
item_code: s.item_code || '',
item_name: s.item_name || '',
sku_property: s.sku_property || '',
});
}
} catch (err) {
ctx.logger.warn(`[exportEntryOrders] 批量查询商品信息失败: ${err.message}`);
}
}
await progressHandler({
status: 'running',
progress: 55,
message: '正在生成 Excel 文件...',
});
// ---- 生成 Excel(流式写入,两个 Sheet) ----
const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'wms-entry-export-'));
const now = new Date();
const dateToken = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}`;
const filename = `入库单导出_${dateToken}.xlsx`;
const filePath = path.join(tempDir, filename);
const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({
filename: filePath,
useStyles: false,
useSharedStrings: false,
});
// Sheet 1: 入库单列表
const sheet1 = workbook.addWorksheet('入库单列表');
const entryOrderColumns = [
{ header: '入库单号', key: 'entry_order_code', width: 22 },
{ header: '业务类型', key: 'order_type', width: 10 },
{ header: '采购单号', key: 'purchase_order_code', width: 22 },
{ header: '订单状态', key: 'order_status', width: 12 },
{ header: '供应商编码', key: 'supplier_code', width: 16 },
{ header: '供应商名称', key: 'supplier_name', width: 24 },
{ header: '物流公司', key: 'logistics_name', width: 20 },
{ header: '运单号', key: 'express_code', width: 22 },
{ header: '货主', key: 'store_name', width: 24 },
{ header: '仓库', key: 'warehouse_name', width: 24 },
{ header: '总行数', key: 'total_order_lines', width: 10 },
{ header: '来源类型', key: 'source_type', width: 10 },
{ header: '状态', key: 'sync_status', width: 12 },
{ header: 'ERP备注', key: 'remark', width: 30 },
{ header: '费用记录', key: 'expense_record', width: 10 },
{ header: '预期到货时间', key: 'expect_start_time', width: 20 },
{ header: '最迟预期到货时间', key: 'expect_end_time', width: 20 },
{ header: '订单创建时间', key: 'order_create_time', width: 20 },
{ header: '创建时间', key: 'created_at', width: 20 },
{ header: '更新时间', key: 'updated_at', width: 20 },
];
sheet1.columns = entryOrderColumns;
const statusLabelMap = {
CREATING: '创建中',
CREATED: '已创建',
PENDING: '已审核',
COMPLETED: '已完成',
CANCELLED: '已作废',
};
const syncStatusLabelMap = {
PENDING: '待同步',
SUCCESS: '成功',
FAILED: '失败',
};
const normalizeCellValue = value => {
if (value === null || value === undefined) return '';
if (value instanceof Date) return app.formatDate ? app.formatDate(value) : value.toISOString();
return value;
};
const orderTypeLabelMap = {
SCRK: '收货入库',
LYRK: '领用入库',
CCRK: '残次入库',
CGRK: '采购入库',
DBRK: '调拨入库',
QTRK: '其他入库',
B2BRK: 'B2B入库',
XNRK: '虚拟入库',
SHRK: '损耗入库',
};
for (const row of allEntryOrders) {
sheet1.addRow({
entry_order_code: normalizeCellValue(row.entry_order_code),
order_type: orderTypeLabelMap[row.order_type] || row.order_type || '',
purchase_order_code: normalizeCellValue(row.purchase_order_code),
order_status: statusLabelMap[row.order_status] || row.order_status || '',
supplier_code: normalizeCellValue(row.supplier_code),
supplier_name: normalizeCellValue(row.supplier_name),
logistics_name: normalizeCellValue(row.logistics_name),
express_code: normalizeCellValue(row.express_code),
store_name: normalizeCellValue(row.store_name),
warehouse_name: normalizeCellValue(row.warehouse_name),
total_order_lines: row.total_order_lines,
source_type: normalizeCellValue(row.source_type),
sync_status: syncStatusLabelMap[row.sync_status] || row.sync_status || '',
remark: normalizeCellValue(row.remark),
expense_record: row.expense_record === 1 ? '是' : (row.expense_record === 0 ? '否' : ''),
expect_start_time: normalizeCellValue(row.expect_start_time),
expect_end_time: normalizeCellValue(row.expect_end_time),
order_create_time: normalizeCellValue(row.order_create_time),
created_at: normalizeCellValue(row.created_at),
updated_at: normalizeCellValue(row.updated_at),
}).commit();
}
sheet1.commit();
await progressHandler({
status: 'running',
progress: 70,
message: '正在写入入库单明细...',
});
// Sheet 2: 入库单明细
const sheet2 = workbook.addWorksheet('入库单明细');
const entryItemColumns = [
{ header: '入库单号', key: 'entry_order_code', width: 22 },
{ header: '入库单ID', key: 'entry_order_id', width: 12 },
{ header: '行号', key: 'order_line_no', width: 8 },
{ header: '商品编码', key: 'item_code', width: 20 },
{ header: '商品名称', key: 'item_name', width: 28 },
{ header: '商品规格', key: 'sku_property', width: 24 },
{ header: '计划入库数量', key: 'plan_quantity', width: 14 },
{ header: '已收货数量', key: 'received_quantity', width: 14 },
{ header: '已通知数量', key: 'confirm_quantity', width: 14 },
{ header: '库存类型', key: 'inventory_type', width: 14 },
{ header: '外部业务编码', key: 'out_biz_code', width: 24 },
{ header: '货主编码', key: 'owner_code', width: 16 },
{ header: '商品ID', key: 'item_id', width: 12 },
{ header: '商品SKU ID', key: 'stock_id', width: 12 },
];
sheet2.columns = entryItemColumns;
// 构建 entry_order_code 映射
const entryOrderCodeMap = new Map();
for (const row of allEntryOrders) {
entryOrderCodeMap.set(Number(row.id), row.entry_order_code || '');
}
// 按入库单分页写入明细
const itemBatchSize = ENTRY_ITEMS_FETCH_BATCH_SIZE;
let itemWrittenCount = 0;
const totalEntryOrders = allEntryOrderIds.length;
for (let batchIdx = 0; batchIdx < allEntryOrderIds.length; batchIdx += itemBatchSize) {
const batchIds = allEntryOrderIds.slice(batchIdx, batchIdx + itemBatchSize);
for (const eid of batchIds) {
const entryOrderCode = entryOrderCodeMap.get(eid) || '';
const items = itemsMap.get(eid) || [];
for (const item of items) {
const stockId = Number(item.stock_id || 0);
const stockInfo = stockInfoMap.get(stockId) || {};
sheet2.addRow({
entry_order_code: entryOrderCode,
entry_order_id: eid,
order_line_no: item.order_line_no ?? '',
item_code: stockInfo.item_code || item.item_code || '',
item_name: stockInfo.item_name || '',
sku_property: stockInfo.sku_property || '',
plan_quantity: item.count ?? 0,
received_quantity: item.received_quantity ?? 0,
confirm_quantity: item.confirm_quantity ?? 0,
inventory_type: normalizeCellValue(item.inventory_type),
out_biz_code: normalizeCellValue(item.out_biz_code),
owner_code: normalizeCellValue(item.owner_code),
item_id: normalizeCellValue(item.item_id),
stock_id: item.stock_id ?? '',
}).commit();
}
itemWrittenCount += 1;
}
const currentBatch = Math.floor(batchIdx / itemBatchSize) + 1;
const totalBatches = Math.ceil(totalEntryOrders / itemBatchSize);
await progressHandler({
status: 'running',
progress: Math.min(90, 70 + Math.round((currentBatch / totalBatches) * 20)),
message: `正在写入入库单明细,已完成 ${itemWrittenCount}/${totalEntryOrders} 条入库单`,
});
}
sheet2.commit();
await workbook.commit();
await progressHandler({
status: 'running',
progress: 92,
message: '正在上传文件...',
});
// ---- 上传文件 ----
const uploadService = ctx?.service?.systems?.upload;
if (!uploadService || typeof uploadService.uploadFile !== 'function') {
throw new Error('上传服务不可用');
}
const stat = await fsp.stat(filePath);
const randomToken = crypto.randomBytes(6).toString('hex');
const uploadKey = `exports/entry/${warehouseId}/${Date.now()}_${randomToken}.xlsx`;
const uploadStream = fs.createReadStream(filePath);
uploadStream.filename = filename;
uploadStream.mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
uploadStream.fileSize = stat.size;
const uploadResult = await uploadService.uploadFile(uploadStream, {
key: uploadKey,
category: 'document',
mimetype: 'xls,xlsx,csv',
});
let fileRecord = null;
if (typeof uploadService.uploadSuccessNotify === 'function') {
fileRecord = await uploadService.uploadSuccessNotify({
url: uploadResult.fileName,
fileKey: uploadResult.fileName,
fileName: filename,
fileType: 'document',
mimeType: uploadStream.mimeType,
fileSize: stat.size,
category: 'document',
businessType: 'entryExport',
businessId: `${warehouseId}`,
uploaderType: ctx?.user?.role || 'system_api',
uploaderDept: ctx?.user?.department || '',
});
}
const result = {
filename,
fileKey: uploadResult.fileName,
url: uploadResult.url || uploadResult.cdnUrl || uploadResult.cosUrl || '',
cdnUrl: uploadResult.cdnUrl || uploadResult.url || '',
cosUrl: uploadResult.cosUrl || '',
total_count: totalCount,
fileRecord: fileRecord?.data || fileRecord || null,
};
// 清理临时目录
await fsp.rm(tempDir, { recursive: true, force: true });
await progressHandler({
status: 'success',
progress: 100,
message: '导出完成',
result,
});
return result;
}
/**
* 导出货主侧入库单列表(双 sheet:入库单列表 + 入库单明细)。
* 复用 list 的筛选与排序语义,以货主维度(store_id)过滤,分页拉取全量数据后生成 Excel 并上传。
* @param {Object} options 导出选项
* @param {Object} [options.where] 筛选条件(与 listStore 一致)
* @param {Object} [options.sort] 排序参数
* @param {Function} [options.onProgress] 进度回调
* @return {Promise<Object>} 上传结果与统计信息
*/
async exportStoreEntryOrders(options = {}) {
const { ctx, app } = this;
const { Sequelize } = app;
const { Op } = Sequelize;
const safeOptions = options && typeof options === 'object' ? options : {};
const where = safeOptions.where && typeof safeOptions.where === 'object' ? { ...safeOptions.where } : {};
const sort = safeOptions.sort && typeof safeOptions.sort === 'object' ? { ...safeOptions.sort } : {};
const progressHandler = typeof safeOptions.onProgress === 'function'
? safeOptions.onProgress
: async () => {};
const storeId = Number(ctx.user && ctx.user.store_id);
if (!storeId) {
throw new Error('用户未绑定货主,无法导出');
}
const sortField = sort.sortField || 'created_at';
const sortOrder = String(sort.sortOrder || 'DESC').toUpperCase() === 'ASC' ? 'ASC' : 'DESC';
const validSortFields = [
'id', 'entry_order_code', 'order_type', 'order_status',
'order_create_time', 'created_at', 'updated_at', 'total_order_lines',
];
const actualSortField = validSortFields.includes(sortField) ? sortField : 'created_at';
const baseWhere = { store_id: storeId, is_enabled: 1, deleted_at: null };
// ---- 复用 listStore 的 where 构建逻辑 ----
const normalizedWhere = { ...where };
const {
where: parsedSourceWhere,
extraConditions,
errorMessage,
} = await this.preprocessEntryListWhere(normalizedWhere);
if (errorMessage) {
throw new Error(errorMessage);
}
const parsed = parseWhereConditions({
where: parsedSourceWhere,
app,
specialFieldMap: {
quickWhere: { bucket: 'quick' },
},
});
if (!parsed.ok) {
throw new Error(`筛选条件解析失败: ${parsed.reason}`);
}
const parsedResult = parsed.result;
const quickWhereInput = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere)
|| parsedSourceWhere.quickWhere
|| null;
const quickWhereValue = quickWhereInput && typeof quickWhereInput === 'object'
? quickWhereInput.value
: null;
const andConditions = [ baseWhere ];
if (quickWhereValue !== undefined && quickWhereValue !== null && String(quickWhereValue).trim() !== '') {
const kw = String(quickWhereValue).trim();
const receivingDetailId = Number(kw);
const escapedKw = app.model.escape(`%${kw}%`);
const orConditions = [
{ entry_order_code: { [Op.like]: `%${kw}%` } },
{ purchase_order_code: { [Op.like]: `%${kw}%` } },
{ supplier_name: { [Op.like]: `%${kw}%` } },
{ store_name: { [Op.like]: `%${kw}%` } },
{ warehouse_name: { [Op.like]: `%${kw}%` } },
Sequelize.where(Sequelize.literal(
`EXISTS (
SELECT 1 FROM wms_entry_order_receiving eor
JOIN wms_receiving r ON r.id = eor.receiving_id
WHERE eor.entry_order_id = wms_entry_order.id
AND eor.deleted_at IS NULL
AND r.receiving_number LIKE ${escapedKw}
)`
), 1),
...(Number.isFinite(receivingDetailId) && receivingDetailId > 0 ? [
Sequelize.where(Sequelize.literal(
`EXISTS (
SELECT 1 FROM wms_entry_order_receiving eor
JOIN wms_receiving_detail rd ON rd.receiving_id = eor.receiving_id
WHERE eor.entry_order_id = wms_entry_order.id
AND eor.deleted_at IS NULL
AND rd.id = ${receivingDetailId}
)`
), 1),
] : []),
];
andConditions.push({ [Op.or]: orConditions });
}
const dynamicConditions = parsedResult.dynamicConditions || [];
if (dynamicConditions.length > 0) {
andConditions.push({ [Op.and]: dynamicConditions });
}
if (extraConditions.length > 0) {
andConditions.push({ [Op.and]: extraConditions });
}
const finalWhere = { [Op.and]: andConditions };
// ---- 分页拉取入库单列表 ----
const pageSize = ENTRY_EXPORT_PAGE_SIZE;
const totalCount = await ctx.model.EntryOrder.count({ where: finalWhere });
await progressHandler({
status: 'running',
progress: totalCount > 0 ? 10 : 90,
message: totalCount > 0 ? `已命中 ${totalCount} 条货主侧入库单,开始导出` : '未命中数据,开始生成空文件',
});
const allEntryOrders = [];
let page = 1;
let fetchedCount = 0;
while (fetchedCount < totalCount) {
const rows = await ctx.model.EntryOrder.findAll({
where: finalWhere,
order: [[ actualSortField, sortOrder ]],
limit: pageSize,
offset: (page - 1) * pageSize,
raw: true,
});
if (!Array.isArray(rows) || rows.length === 0) {
break;
}
allEntryOrders.push(...rows);
fetchedCount += rows.length;
page += 1;
await progressHandler({
status: 'running',
progress: Math.min(30, 10 + Math.round((fetchedCount / Math.max(totalCount, 1)) * 20)),
message: `正在拉取货主侧入库单列表,已完成 ${fetchedCount}/${totalCount}`,
});
}
const allEntryOrderIds = allEntryOrders.map(r => Number(r.id)).filter(Boolean);
// ---- 分批拉取入库单明细 ----
/** @type {Map<number, Array<Object>>} */
const itemsMap = new Map();
/** @type {Set<number>} */
const allStockIds = new Set();
if (allEntryOrderIds.length > 0) {
const batchSize = ENTRY_ITEMS_FETCH_BATCH_SIZE;
const totalBatches = Math.ceil(allEntryOrderIds.length / batchSize);
for (let batchIdx = 0; batchIdx < allEntryOrderIds.length; batchIdx += batchSize) {
const batchIds = allEntryOrderIds.slice(batchIdx, batchIdx + batchSize);
const items = await ctx.model.EntryItems.findAll({
where: { order_id: { [Op.in]: batchIds } },
order: [[ 'order_id', 'ASC' ], [ 'order_line_no', 'ASC' ]],
raw: true,
});
for (const item of items) {
const eid = Number(item.order_id);
if (!itemsMap.has(eid)) {
itemsMap.set(eid, []);
}
itemsMap.get(eid).push(item);
if (item.stock_id) {
allStockIds.add(Number(item.stock_id));
}
}
const currentBatch = Math.floor(batchIdx / batchSize) + 1;
await progressHandler({
status: 'running',
progress: Math.min(50, 30 + Math.round((currentBatch / totalBatches) * 20)),
message: `正在拉取货主侧入库单明细,已完成批次 ${currentBatch}/${totalBatches}`,
});
}
}
// ---- 批量查询商品名称(按 store_id) ----
/** @type {Map<number, Object>} */
const stockInfoMap = new Map();
if (allStockIds.size > 0) {
const stockIdsArr = [ ...allStockIds ];
try {
const stockRows = await ctx.model.StockWarehouse.findAll({
where: { id: { [Op.in]: stockIdsArr }, store_id: storeId },
attributes: [ 'id', 'item_code', 'item_name', 'sku_property' ],
raw: true,
});
for (const s of stockRows) {
stockInfoMap.set(Number(s.id), {
item_code: s.item_code || '',
item_name: s.item_name || '',
sku_property: s.sku_property || '',
});
}
} catch (err) {
ctx.logger.warn(`[exportStoreEntryOrders] 批量查询商品信息失败: ${err.message}`);
}
}
await progressHandler({
status: 'running',
progress: 55,
message: '正在生成 Excel 文件...',
});
// ---- 生成 Excel ----
const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'wms-store-entry-export-'));
const now = new Date();
const dateToken = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}`;
const filename = `货主侧入库单导出_${dateToken}.xlsx`;
const filePath = path.join(tempDir, filename);
const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({
filename: filePath,
useStyles: false,
useSharedStrings: false,
});
const normalizeCellValue = value => {
if (value === null || value === undefined) return '';
if (value instanceof Date) return app.formatDate ? app.formatDate(value) : value.toISOString();
return value;
};
const statusLabelMap = {
CREATING: '创建中',
CREATED: '已创建',
PENDING: '已审核',
COMPLETED: '已完成',
CANCELLED: '已作废',
};
const syncStatusLabelMap = {
PENDING: '待同步',
SUCCESS: '成功',
FAILED: '失败',
};
const orderTypeLabelMap = {
SCRK: '收货入库',
LYRK: '领用入库',
CCRK: '残次入库',
CGRK: '采购入库',
DBRK: '调拨入库',
QTRK: '其他入库',
B2BRK: 'B2B入库',
XNRK: '虚拟入库',
SHRK: '损耗入库',
};
// Sheet 1: 入库单列表(货主侧,不显示仓库字段)
const sheet1 = workbook.addWorksheet('入库单列表');
const entryOrderColumns = [
{ header: '入库单号', key: 'entry_order_code', width: 22 },
{ header: '业务类型', key: 'order_type', width: 10 },
{ header: '采购单号', key: 'purchase_order_code', width: 22 },
{ header: '订单状态', key: 'order_status', width: 12 },
{ header: '供应商编码', key: 'supplier_code', width: 16 },
{ header: '供应商名称', key: 'supplier_name', width: 24 },
{ header: '物流公司', key: 'logistics_name', width: 20 },
{ header: '运单号', key: 'express_code', width: 22 },
{ header: '仓库', key: 'warehouse_name', width: 24 },
{ header: '总行数', key: 'total_order_lines', width: 10 },
{ header: '来源类型', key: 'source_type', width: 10 },
{ header: '状态', key: 'sync_status', width: 12 },
{ header: 'ERP备注', key: 'remark', width: 30 },
{ header: '费用记录', key: 'expense_record', width: 10 },
{ header: '预期到货时间', key: 'expect_start_time', width: 20 },
{ header: '最迟预期到货时间', key: 'expect_end_time', width: 20 },
{ header: '订单创建时间', key: 'order_create_time', width: 20 },
{ header: '创建时间', key: 'created_at', width: 20 },
{ header: '更新时间', key: 'updated_at', width: 20 },
];
sheet1.columns = entryOrderColumns;
for (const row of allEntryOrders) {
sheet1.addRow({
entry_order_code: normalizeCellValue(row.entry_order_code),
order_type: orderTypeLabelMap[row.order_type] || row.order_type || '',
purchase_order_code: normalizeCellValue(row.purchase_order_code),
order_status: statusLabelMap[row.order_status] || row.order_status || '',
supplier_code: normalizeCellValue(row.supplier_code),
supplier_name: normalizeCellValue(row.supplier_name),
logistics_name: normalizeCellValue(row.logistics_name),
express_code: normalizeCellValue(row.express_code),
warehouse_name: normalizeCellValue(row.warehouse_name),
total_order_lines: row.total_order_lines,
source_type: normalizeCellValue(row.source_type),
sync_status: syncStatusLabelMap[row.sync_status] || row.sync_status || '',
remark: normalizeCellValue(row.remark),
expense_record: row.expense_record === 1 ? '是' : (row.expense_record === 0 ? '否' : ''),
expect_start_time: normalizeCellValue(row.expect_start_time),
expect_end_time: normalizeCellValue(row.expect_end_time),
order_create_time: normalizeCellValue(row.order_create_time),
created_at: normalizeCellValue(row.created_at),
updated_at: normalizeCellValue(row.updated_at),
}).commit();
}
sheet1.commit();
await progressHandler({
status: 'running',
progress: 70,
message: '正在写入入库单明细...',
});
// Sheet 2: 入库单明细
const sheet2 = workbook.addWorksheet('入库单明细');
const entryItemColumns = [
{ header: '入库单号', key: 'entry_order_code', width: 22 },
{ header: '入库单ID', key: 'entry_order_id', width: 12 },
{ header: '行号', key: 'order_line_no', width: 8 },
{ header: '商品编码', key: 'item_code', width: 20 },
{ header: '商品名称', key: 'item_name', width: 28 },
{ header: '商品规格', key: 'sku_property', width: 24 },
{ header: '计划入库数量', key: 'plan_quantity', width: 14 },
{ header: '已收货数量', key: 'received_quantity', width: 14 },
{ header: '已通知数量', key: 'confirm_quantity', width: 14 },
{ header: '库存类型', key: 'inventory_type', width: 14 },
{ header: '外部业务编码', key: 'out_biz_code', width: 24 },
{ header: '货主编码', key: 'owner_code', width: 16 },
{ header: '商品ID', key: 'item_id', width: 12 },
{ header: '商品SKU ID', key: 'stock_id', width: 12 },
];
sheet2.columns = entryItemColumns;
const entryOrderCodeMap = new Map();
for (const row of allEntryOrders) {
entryOrderCodeMap.set(Number(row.id), row.entry_order_code || '');
}
const itemBatchSize = ENTRY_ITEMS_FETCH_BATCH_SIZE;
let itemWrittenCount = 0;
const totalEntryOrders = allEntryOrderIds.length;
for (let batchIdx = 0; batchIdx < allEntryOrderIds.length; batchIdx += itemBatchSize) {
const batchIds = allEntryOrderIds.slice(batchIdx, batchIdx + itemBatchSize);
for (const eid of batchIds) {
const entryOrderCode = entryOrderCodeMap.get(eid) || '';
const items = itemsMap.get(eid) || [];
for (const item of items) {
const stockId = Number(item.stock_id || 0);
const stockInfo = stockInfoMap.get(stockId) || {};
sheet2.addRow({
entry_order_code: entryOrderCode,
entry_order_id: eid,
order_line_no: item.order_line_no ?? '',
item_code: stockInfo.item_code || item.item_code || '',
item_name: stockInfo.item_name || '',
sku_property: stockInfo.sku_property || '',
plan_quantity: item.count ?? 0,
received_quantity: item.received_quantity ?? 0,
confirm_quantity: item.confirm_quantity ?? 0,
inventory_type: normalizeCellValue(item.inventory_type),
out_biz_code: normalizeCellValue(item.out_biz_code),
owner_code: normalizeCellValue(item.owner_code),
item_id: normalizeCellValue(item.item_id),
stock_id: item.stock_id ?? '',
}).commit();
}
itemWrittenCount += 1;
}
const currentBatch = Math.floor(batchIdx / itemBatchSize) + 1;
const totalBatches = Math.ceil(totalEntryOrders / itemBatchSize);
await progressHandler({
status: 'running',
progress: Math.min(90, 70 + Math.round((currentBatch / totalBatches) * 20)),
message: `正在写入入库单明细,已完成 ${itemWrittenCount}/${totalEntryOrders} 条入库单`,
});
}
sheet2.commit();
await workbook.commit();
await progressHandler({
status: 'running',
progress: 92,
message: '正在上传文件...',
});
// ---- 上传文件 ----
const uploadService = ctx?.service?.systems?.upload;
if (!uploadService || typeof uploadService.uploadFile !== 'function') {
throw new Error('上传服务不可用');
}
const stat = await fsp.stat(filePath);
const randomToken = crypto.randomBytes(6).toString('hex');
const uploadKey = `exports/entry/store/${storeId}/${Date.now()}_${randomToken}.xlsx`;
const uploadStream = fs.createReadStream(filePath);
uploadStream.filename = filename;
uploadStream.mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
uploadStream.fileSize = stat.size;
const uploadResult = await uploadService.uploadFile(uploadStream, {
key: uploadKey,
category: 'document',
mimetype: 'xls,xlsx,csv',
});
let fileRecord = null;
if (typeof uploadService.uploadSuccessNotify === 'function') {
fileRecord = await uploadService.uploadSuccessNotify({
url: uploadResult.fileName,
fileKey: uploadResult.fileName,
fileName: filename,
fileType: 'document',
mimeType: uploadStream.mimeType,
fileSize: stat.size,
userId: ctx.userId,
description: `货主侧入库单导出(货主${storeId}),共${totalCount}条入库单`,
});
}
// 清理临时文件
try { await fsp.rm(tempDir, { recursive: true, force: true }); } catch (_) { /* ignore */ }
const uploadInfo = fileRecord || uploadResult;
const fileUrl = typeof uploadInfo === 'object' && uploadInfo.url
? uploadInfo.url
: (typeof uploadResult === 'object' ? uploadResult.fileName : '');
await progressHandler({
status: 'running',
progress: 100,
message: '货主侧导出完成',
result: { url: fileUrl, fileKey: uploadKey },
});
return {
url: fileUrl,
fileKey: uploadKey,
total: totalCount,
totalDetails: allEntryOrderIds.reduce((sum, eid) => sum + (itemsMap.get(eid) || []).length, 0),
};
}
}
module.exports = EntryService;