liufumingren e7fcd2549e 20260625
2026-06-25 02:01:59 +08:00

1372 lines
44 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

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

'use strict';
const Service = require('egg').Service;
const { parseWhereConditions } = require('../../../lib/query_condition_parser');
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 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 => app.Sequelize.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 ${app.Sequelize.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}} 预处理结果
*/
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;
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 排序参数
* @return {Promise<Object>} code/data/message 结构
*/
async list(where = {}, pageParams = {}, sortParams = {}) {
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 baseWhere = {
warehouse_id: ctx.user.store_id,
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,
} = 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();
andConditions.push({
[Op.or]: [
{ 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}%` } },
],
});
}
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 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: rows,
pagination: {
page,
pageSize,
total: count,
totalPages: Math.ceil(count / pageSize),
hasPrevious: page > 1,
hasNext: page < Math.ceil(count / pageSize),
},
summary,
},
};
}
/**
* 查询入库单详情。
* @param {Object} data 请求体
* @return {Promise<Object>} code/data/message 结构
*/
/**
* 查询入库单详情,含商品信息、条码、入库进度。
* @param {Object} data 请求参数
* @param {number} [data.id] 入库单主键 ID
* @param {string} [data.entry_order_code] 入库单号
* @return {Promise<Object>} code/data/message 结构,data.entryOrder 为扁平化后的入库单详情
*/
async get(data = {}) {
const { ctx } = this;
const id = Number(data.id || 0);
const entryOrderCode = data.entry_order_code ? String(data.entry_order_code).trim() : '';
const warehouseId = ctx.user.store_id;
if (!id && !entryOrderCode) {
return {
code: 400,
message: 'id 或 entry_order_code 至少传一个',
data: null,
};
}
const where = {
warehouse_id: warehouseId,
is_enabled: 1,
deleted_at: null,
};
if (id) {
where.id = id;
} else {
where.entry_order_code = entryOrderCode;
}
const entryOrder = await ctx.model.EntryOrder.findOne({
where,
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,
},
{
model: ctx.model.EntryItems,
as: 'items',
attributes: [ 'id', 'order_id', 'out_biz_code', 'order_line_no', 'owner_code', 'item_code', 'item_id', 'count', 'inventory_type', 'stock_id', 'received_quantity', 'confirm_quantity' ],
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: 0,
message: '入库单不存在或无权访问',
data: null,
};
}
const entryOrderJSON = entryOrder.toJSON();
// 收集所有 stock_id,通过 getStockDetails 获取带缓存的商品详情
const stockIdSet = new Set();
if (entryOrderJSON.items && Array.isArray(entryOrderJSON.items)) {
for (const item of entryOrderJSON.items) {
if (item.stock_id != null) {
stockIdSet.add(Number(item.stock_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 detail of stockDetails) {
stockDetailMap.set(detail.id, detail);
}
}
// 查询该入库单所有商品的直接入库进度(非收货单途径)
const directInboundMap = {};
if (stockIds.length > 0) {
const directLogRows = await ctx.model.InboundDirectLog.findAll({
attributes: [
'stock_id',
[ ctx.app.Sequelize.fn('SUM', ctx.app.Sequelize.col('quantity')), 'total_quantity' ],
],
where: {
entry_order_code: entryOrderJSON.entry_order_code,
stock_id: { [ctx.app.Sequelize.Op.in]: stockIds },
},
group: [ 'stock_id' ],
raw: true,
});
for (const row of directLogRows) {
directInboundMap[row.stock_id] = Number(row.total_quantity) || 0;
}
}
// 扁平化 items:用 getStockDetails 返回的商品详情替换原有的 stock + barcodes
let flattenedItems;
if (entryOrderJSON.items && Array.isArray(entryOrderJSON.items)) {
flattenedItems = entryOrderJSON.items.map(item => {
const { item_code, item_id, stock_id: itemStockId, ...rest } = item;
const stockDetail = itemStockId != null ? stockDetailMap.get(Number(itemStockId)) || null : null;
const directInboundQty = (stockDetail && directInboundMap[stockDetail.id]) || 0;
const receivedQty = Number(rest.received_quantity) || 0;
const totalCount = Number(rest.count) || 0;
const remaining = Math.max(0, totalCount - receivedQty);
return {
...rest,
stock_id: itemStockId,
external_item_code: item_code,
external_item_id: item_id,
warehouse_item_code: (stockDetail && stockDetail.item_code) || '',
warehouse_item_name: (stockDetail && stockDetail.item_name) || '',
warehouse_item_spec: (stockDetail && stockDetail.sku_property) || '',
warehouse_quantity: (stockDetail && stockDetail.quantity != null) ? stockDetail.quantity : null,
warehouse_locked_quantity: (stockDetail && stockDetail.locked_quantity != null) ? stockDetail.locked_quantity : null,
warehouse_is_batch_mgmt: (stockDetail && stockDetail.is_batch_mgmt != null) ? stockDetail.is_batch_mgmt : null,
warehouse_is_shelf_life_mgmt: (stockDetail && stockDetail.is_shelf_life_mgmt != null) ? stockDetail.is_shelf_life_mgmt : null,
warehouse_image_url: (stockDetail && stockDetail.is_images === 'Y') ? '' : '',
warehouse_is_images: (stockDetail && stockDetail.is_images != null) ? stockDetail.is_images : null,
barcodes: (stockDetail && stockDetail.barcodes) || [],
direct_inbound_quantity: directInboundQty,
remaining_quantity: remaining,
};
});
} else {
flattenedItems = entryOrderJSON.items || [];
}
// 为每个 item 补充可匹配的收货单明细及剩余可用量
const enrichedItems = await this.enrichItemsWithAvailableReceivingDetails(flattenedItems, warehouseId);
entryOrderJSON.items = enrichedItems;
return {
code: 200,
message: '查询成功',
data: {
entryOrder: entryOrderJSON,
},
};
}
/**
* 为 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.allocated_quantity), 0) AS allocated_quantity,
rd.actual_quantity - COALESCE(SUM(erb.allocated_quantity), 0) AS available_quantity
FROM wms_receiving_detail rd
INNER JOIN wms_receiving r ON r.id = rd.receiving_id AND r.deleted_at IS NULL
LEFT JOIN wms_entry_receiving_binding 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 || [];
const entryOrders = [];
for (const orderId of orderIds) {
const entryOrder = await this.getOwnedEntryOrderById(orderId);
if (!entryOrder) {
return {
code: 404,
message: '入库单不存在或无权访问',
data: null,
};
}
if (entryOrder.order_status === 'COMPLETED') {
return {
code: 400,
message: '已完成入库单不允许作废',
data: null,
};
}
entryOrders.push(entryOrder);
}
const transaction = ctx.model && typeof ctx.model.transaction === 'function'
? await ctx.model.transaction()
: null;
try {
const updatedAt = new Date();
for (const entryOrder of entryOrders) {
await entryOrder.update({
order_status: 'CANCELLED',
updated_at: updatedAt,
}, transaction ? {
transaction,
} : undefined);
}
if (transaction && typeof transaction.commit === 'function') {
await transaction.commit();
}
} catch (error) {
if (transaction && typeof transaction.rollback === 'function') {
await transaction.rollback();
}
throw error;
}
return {
code: 200,
message: '作废成功',
data: {
[orderIds.length === 1 ? 'id' : 'ids']: orderIds.length === 1 ? entryOrders[0].id : orderIds,
},
};
}
/**
* 完成入库单。
* @param {Object} data 请求体
* @return {Promise<Object>} code/data/message 结构
*/
async completeEntry(data = {}) {
const { ctx } = this;
const orderId = Number(data.id || 0);
if (!orderId) {
return {
code: 400,
message: 'id 必填',
data: null,
};
}
const entryOrder = await this.getOwnedEntryOrderById(orderId);
if (!entryOrder) {
return {
code: 404,
message: '入库单不存在或无权访问',
data: null,
};
}
if (entryOrder.order_status === 'CANCELLED') {
return {
code: 400,
message: '已作废入库单不允许完成',
data: null,
};
}
if (![ 'PENDING' ].includes(entryOrder.order_status)) {
return {
code: 400,
message: `当前入库单状态为 ${entryOrder.order_status},仅 PENDING 状态可完成入库`,
data: null,
};
}
const detailCount = await ctx.model.EntryItems.count({ where: { order_id: orderId } });
if (detailCount <= 0) {
return {
code: 400,
message: '请先添加入库明细',
data: null,
};
}
await entryOrder.update({
order_status: 'COMPLETED',
updated_at: new Date(),
});
return {
code: 200,
message: '完成成功',
data: {
id: entryOrder.id,
},
};
}
/**
* 获取入库单的导入/PDA 直接入库信息(转发到 inboundDirectLog)。
* @param {string} entryOrderCode 入库单号
* @return {Promise<Object>} code/data/message 结构
*/
async getDirectInboundItems(entryOrderCode) {
const { ctx } = this;
return await ctx.service.systems.inboundDirectLog.getItems(entryOrderCode);
}
/**
* 按商品增量添加导入/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 addDirectInboundItem(data = {}) {
const { ctx } = this;
return await ctx.service.systems.inboundDirectLog.addItem(data);
}
/**
* 提交确认完成导入/PDA 直接入库(转发到 inboundDirectLog)。
* @param {string} entryOrderCode 入库单号
* @return {Promise<Object>} code/data/message 结构
*/
async commitDirectInbound(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 removeDirectInboundItem(data = {}) {
const { ctx } = this;
return await ctx.service.systems.inboundDirectLog.removeItem(data);
}
/**
* 快捷直入/虚拟入库:将入库单的所有商品按明细数量全部直入到虚拟库位(space_id=2),跳过收货、质检等正常流程。
* @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,
};
}
const warehouseId = entryOrder.warehouse_id;
const storeId = entryOrder.store_id;
const batchNo = entryOrder.entry_order_code;
const hardcodedSpaceId = 2;
const transaction = await ctx.model.transaction();
const processedStockIds = new Set();
let totalInboundQty = 0;
try {
// 3. 逐商品写入库存
for (const item of entryItems) {
const stockId = item.stock_id;
if (!stockId) continue;
const planQty = Number(item.count) || 0;
if (planQty <= 0) continue;
const inventoryType = item.inventory_type || 'ZP';
// 更新入库明细的 received_quantity 为计划数量(全部入库)
await ctx.model.EntryItems.update({
received_quantity: planQty,
}, {
where: { id: item.id },
transaction,
});
// 同一 stock_id 只写一次库存
if (processedStockIds.has(String(stockId))) continue;
processedStockIds.add(String(stockId));
totalInboundQty += planQty;
// 锁定并更新 StockWarehouse 总库存
const stockRecord = await ctx.model.StockWarehouse.findOne({
where: { id: stockId, is_valid: 'Y', deleted_at: null },
lock: transaction.LOCK.UPDATE,
transaction,
});
if (stockRecord) {
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 });
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: entryOrder.order_type,
order_no: entryOrder.entry_order_code,
entry_order_id: entryOrder.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 });
}
// 创建/更新 Storage 库位库存(space_id 硬编码为 2)
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,
});
if (storageRecord) {
await ctx.model.Storage.update({
quantity: app.Sequelize.literal(`quantity + ${planQty}`),
available_quantity: app.Sequelize.literal(`available_quantity + ${planQty}`),
entry_order_id: entryOrder.id,
inbound_time: new Date(),
inbound_order_no: entryOrder.entry_order_code,
updated_at: new Date(),
}, {
where: { id: storageRecord.id },
transaction,
});
} else {
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: entryOrder.entry_order_code,
receiving_id: null,
entry_order_id: entryOrder.id,
supplier_id: null,
supplier_batch_no: null,
is_enabled: 1,
created_at: new Date(),
updated_at: new Date(),
}, { transaction });
}
}
// 4. 更新入库单状态为 COMPLETED
await entryOrder.update({
order_status: 'COMPLETED',
sync_status: 'SUCCESS',
sync_message: JSON.stringify({
completedAt: new Date(),
totalQuantity: totalInboundQty,
itemCount: processedStockIds.size,
source: 'quick_inbound',
}),
updated_at: new Date(),
}, { transaction });
// 记录操作日志(事务内)
await ctx.service.systems.operationLog.createOperationLog({
businessType: 'entry_order',
businessId: entryOrder.id,
operationCode: 'QUICK_INBOUND',
operator: {
id: ctx.user?.employees_id || ctx.user?.id,
name: ctx.user?.employees_name || '',
},
extras: {
warehouseId: entryOrder.warehouse_id,
message: `快捷直入完成,共 ${processedStockIds.size} 种商品,总数量 ${totalInboundQty}`,
},
transaction,
});
await transaction.commit();
} catch (error) {
if (transaction && typeof transaction.rollback === 'function') {
await transaction.rollback();
}
throw error;
}
// 事务外:异步触发奇门/API 回传(复用 inboundDirectLog 的回传逻辑)
setImmediate(() => {
ctx.service.systems.inboundDirectLog._sendCallback(entryOrder).catch(err => {
ctx.logger.error(`[quickInbound] 回传异常 entryOrderId=${entryOrder.id}: ${err.message}`, err.stack);
});
});
return {
code: 200,
message: '快捷入库完成',
data: {
id: entryOrder.id,
entry_order_code: entryOrder.entry_order_code,
order_status: 'COMPLETED',
sync_status: 'SUCCESS',
items_count: entryItems.length,
total_quantity: totalInboundQty,
},
};
}
/**
* 入库单商品与收货单商品逐行对照视图。
* 以入库单明细为主,按 stock_id ↔ system_product_id 匹配收货单明细,
* 返回匹配/未匹配/收货单多余的对照结果。
*
* @param {Object} data 请求参数
* @param {number} data.entry_order_id 入库单ID
* @param {number} data.receiving_id 收货单ID
* @return {Promise<Object>} code/data/message 结构
*/
async receivingCompare(data = {}) {
const { ctx, app } = this;
const entryOrderId = Number(data.entry_order_id || 0);
const receivingId = Number(data.receiving_id || 0);
const warehouseId = ctx.user.store_id;
if (!entryOrderId) {
return { code: 400, message: 'entry_order_id 必填', data: null };
}
if (!receivingId) {
return { code: 400, message: 'receiving_id 必填', data: null };
}
// 1. 校验收货单存在性
const receivingOrder = await ctx.model.Receiving.findOne({
where: {
id: receivingId,
warehouse_id: warehouseId,
is_deleted: false,
},
attributes: [ 'id', 'receiving_number', 'status', 'storage_status' ],
raw: true,
});
if (!receivingOrder) {
return { code: 404, message: '收货单不存在或无权访问', data: null };
}
// 2. 校验收货单存在性(复用 getOwnedEntryOrderById)
const entryOrder = await this.getOwnedEntryOrderById(entryOrderId);
if (!entryOrder) {
return { code: 404, message: '入库单不存在或无权访问', data: null };
}
// 3. 查询入库单明细
const entryItems = await ctx.model.EntryItems.findAll({
where: { order_id: entryOrderId },
attributes: [ 'id', 'stock_id', 'count', 'received_quantity' ],
raw: true,
});
// 4. 查询收货单明细
const receivingDetails = await ctx.model.ReceivingDetail.findAll({
where: { receiving_id: receivingId },
attributes: [ 'id', 'system_product_id', 'actual_quantity', 'product_name' ],
raw: true,
});
// 5. 收集所有 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)) ];
// 6. 批量查询 wms_stock_warehouse — 入库单商品(按 stock_id)和收货单商品(按 system_product_id = id)
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(detail.id, detail);
}
}
// stock_id 即 wms_stock_warehouse.id,与 wms_receiving_detail.system_product_id 直接对应
// 只需确认 stock_warehouse 记录存在即可构建映射
const stockIdToSystemProductId = new Map();
const systemProductIdToEntryStockIds = new Map();
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,
});
for (const row of swRows) {
const stockId = Number(row.id);
stockIdToSystemProductId.set(stockId, stockId);
if (!systemProductIdToEntryStockIds.has(stockId)) {
systemProductIdToEntryStockIds.set(stockId, []);
}
systemProductIdToEntryStockIds.get(stockId).push(stockId);
}
}
// 7. 查询已分配量(从 wms_entry_receiving_binding)
const receivingDetailIds = receivingDetails.map(d => d.id);
const allocatedMap = new Map();
if (receivingDetailIds.length > 0) {
const bindingRows = await ctx.model.EntryReceivingBinding.findAll({
attributes: [
'receiving_detail_id',
[ app.Sequelize.fn('SUM', app.Sequelize.col('allocated_quantity')), 'total_allocated' ],
],
where: {
receiving_detail_id: { [app.Sequelize.Op.in]: receivingDetailIds },
status: '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);
}
}
// 8. 构建对照视图:以入库单明细为主
const comparison = [];
const matchedReceivingDetailIds = new Set();
for (const entryItem of entryItems) {
const stockId = Number(entryItem.stock_id || 0);
const systemProductId = stockIdToSystemProductId.get(stockId) || 0;
const stockDetail = stockDetailMap.get(stockId) || null;
// 找到同 system_product_id 的收货单明细
const matchedReceiving = systemProductId > 0
? receivingDetails.filter(rd => Number(rd.system_product_id) === systemProductId)
: [];
if (matchedReceiving.length > 0) {
// 有匹配的收货明细
for (const rd of matchedReceiving) {
matchedReceivingDetailIds.add(rd.id);
const rdStockDetail = (rd.system_product_id != null && stockDetailMap.get(Number(rd.system_product_id))) || null;
const allocated = allocatedMap.get(Number(rd.id)) || 0;
const available = Math.max(0, (Number(rd.actual_quantity) || 0) - allocated);
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,
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: Number(rd.actual_quantity) || 0,
receiving_allocated: allocated,
receiving_available: available,
match_status: 'matched',
});
}
} 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,
receiving_detail_id: null,
receiving_product_code: null,
receiving_product_name: null,
receiving_actual_quantity: null,
receiving_allocated: null,
receiving_available: null,
match_status: 'entry_only',
});
}
}
// 9. 收货单中多余的商品(未被任何入库单明细匹配的)
const receivingOnly = [];
for (const rd of receivingDetails) {
if (!matchedReceivingDetailIds.has(Number(rd.id))) {
const rdStockDetail = (rd.system_product_id != null && stockDetailMap.get(Number(rd.system_product_id))) || null;
const allocated = allocatedMap.get(Number(rd.id)) || 0;
const available = Math.max(0, (Number(rd.actual_quantity) || 0) - allocated);
receivingOnly.push({
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: Number(rd.actual_quantity) || 0,
receiving_allocated: allocated,
receiving_available: available,
});
}
}
// 10. 汇总
const matchedItems = comparison.filter(c => c.match_status === 'matched').length;
const entryOnlyItems = comparison.filter(c => c.match_status === 'entry_only').length;
return {
code: 200,
message: '查询成功',
data: {
entry_order_id: entryOrderId,
entry_order_code: entryOrder.entry_order_code,
receiving_id: receivingId,
receiving_number: receivingOrder.receiving_number,
comparison,
receiving_only: receivingOnly,
summary: {
total_entry_items: entryItems.length,
matched_items: matchedItems,
entry_only_items: entryOnlyItems,
receiving_only_items: receivingOnly.length,
},
},
};
}
}
module.exports = EntryService;