894 lines
30 KiB
JavaScript
894 lines
30 KiB
JavaScript
'use strict';
|
||
|
||
const Service = require('egg').Service;
|
||
|
||
/**
|
||
* 非收货单途径入库直接记录服务(导入/PDA入库)。
|
||
*
|
||
* 职责:
|
||
* 1. 根据入库单号获取入库明细(含已记录的导入/PDA 入库记录)
|
||
* 2. 按商品增量添加导入/PDA 入库记录,超计划数量时拒绝
|
||
* 3. 提交确认完成入库,写入库存并触发奇门/API 回传
|
||
*/
|
||
class InboundDirectLogService extends Service {
|
||
|
||
/**
|
||
* 获取入库单的受控入库信息。
|
||
* 返回入库单基本信息、明细列表,以及每项明细已有的导入/PDA 入库记录。
|
||
* @param {string} entryOrderCode 入库单号
|
||
* @return {Promise<Object>} code/data/message 结构
|
||
*/
|
||
async getItems(entryOrderCode) {
|
||
const { ctx } = this;
|
||
const code = String(entryOrderCode || '').trim();
|
||
|
||
if (!code) {
|
||
return { code: 400, message: 'entry_order_code 必填', data: null };
|
||
}
|
||
|
||
const entryOrder = await ctx.model.EntryOrder.findOne({
|
||
where: {
|
||
entry_order_code: code,
|
||
warehouse_id: ctx.user.store_id,
|
||
is_enabled: 1,
|
||
deleted_at: null,
|
||
},
|
||
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 };
|
||
}
|
||
|
||
// 查询该入库单下已有的导入/PDA 入库记录
|
||
const directLogs = await ctx.model.InboundDirectLog.findAll({
|
||
where: { entry_order_id: entryOrder.id },
|
||
order: [[ 'created_at', 'ASC' ]],
|
||
});
|
||
|
||
// 按 stock_id 汇总已入库数量
|
||
const logSummary = {};
|
||
for (const log of directLogs) {
|
||
const key = String(log.stock_id);
|
||
if (!logSummary[key]) {
|
||
logSummary[key] = 0;
|
||
}
|
||
logSummary[key] += Number(log.quantity);
|
||
}
|
||
|
||
// 将直接入库记录按 entry_item_id 关联到明细
|
||
const itemDirectLogs = {};
|
||
for (const log of directLogs) {
|
||
const item = 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,
|
||
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,
|
||
}))
|
||
: [];
|
||
|
||
// 组装明细
|
||
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);
|
||
// 入库进度使用已收货数量 + 导入/PDA 已入库数量
|
||
const totalInboundQty = directInQty + Number(item.received_quantity || 0);
|
||
|
||
return {
|
||
id: item.id,
|
||
stock_id: item.stock_id,
|
||
count: planQty,
|
||
received_quantity: Number(item.received_quantity) || 0,
|
||
item_code: item.item_code,
|
||
warehouse_item_code: (item.stock && item.stock.item_code) || '',
|
||
warehouse_item_name: (item.stock && item.stock.item_name) || '',
|
||
warehouse_item_spec: (item.stock && item.stock.sku_property) || '',
|
||
direct_inbound_quantity: directInQty,
|
||
remaining_quantity: Math.max(0, planQty - totalInboundQty),
|
||
direct_logs: logs,
|
||
};
|
||
});
|
||
|
||
return {
|
||
code: 200,
|
||
message: '查询成功',
|
||
data: {
|
||
entryOrder: {
|
||
id: entryOrder.id,
|
||
entry_order_code: entryOrder.entry_order_code,
|
||
order_type: entryOrder.order_type,
|
||
order_status: entryOrder.order_status,
|
||
source_type: entryOrder.source_type,
|
||
warehouse_id: entryOrder.warehouse_id,
|
||
store_id: entryOrder.store_id,
|
||
remark: entryOrder.remark,
|
||
},
|
||
items,
|
||
direct_logs: directLogs,
|
||
receivingBindings,
|
||
summary: {
|
||
total_items: items.length,
|
||
total_planned: items.reduce((s, i) => s + i.count, 0),
|
||
total_direct_inbound: items.reduce((s, i) => s + i.direct_inbound_quantity, 0),
|
||
total_import: directLogs.filter(l => l.inbound_type === 'import').reduce((s, l) => s + Number(l.quantity), 0),
|
||
total_pda: directLogs.filter(l => l.inbound_type === 'pda').reduce((s, l) => s + Number(l.quantity), 0),
|
||
},
|
||
},
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 单条校验并写入一条导入/PDA 入库记录。
|
||
* @param {Object} ctx
|
||
* @param {Object} entryOrder 入库单实例
|
||
* @param {Object} item { stock_id, quantity, inbound_type, remark }
|
||
* @return {Promise<{ok: boolean, log?: Object, error?: Object}>}
|
||
*/
|
||
async _addSingleItem(ctx, entryOrder, item, transaction) {
|
||
const stockId = Number(item.stock_id || 0);
|
||
const quantity = Number(item.quantity || 0);
|
||
const inboundType = String(item.inbound_type || '').trim().toLowerCase();
|
||
const remark = item.remark ? String(item.remark).trim() : '';
|
||
const spaceId = item.space_id ? Number(item.space_id) : null;
|
||
|
||
if (!stockId) {
|
||
return { ok: false, error: { code: 400, message: 'items[].stock_id 必填' } };
|
||
}
|
||
if (!quantity || quantity <= 0 || !Number.isFinite(quantity)) {
|
||
return { ok: false, error: { code: 400, message: 'items[].quantity 必须为正整数' } };
|
||
}
|
||
if (![ 'import', 'pda' ].includes(inboundType)) {
|
||
return { ok: false, error: { code: 400, message: 'items[].inbound_type 必须为 import 或 pda' } };
|
||
}
|
||
|
||
// 查找入库单中该 stock_id 对应的所有明细,累加计划数量
|
||
const entryItems = await ctx.model.EntryItems.findAll({
|
||
where: { order_id: entryOrder.id, stock_id: stockId },
|
||
...(transaction ? { transaction } : {}),
|
||
});
|
||
|
||
if (!entryItems || entryItems.length === 0) {
|
||
return { ok: false, error: { code: 400, message: `入库单中不存在 stock_id=${stockId} 的商品` } };
|
||
}
|
||
|
||
const totalPlanQty = entryItems.reduce((sum, item) => sum + (Number(item.count) || 0), 0);
|
||
|
||
// 计算该 stock_id 在该入库单下已有的导入/PDA 入库总量
|
||
const logWhere = { entry_order_id: entryOrder.id, stock_id: stockId };
|
||
const existingLogs = await ctx.model.InboundDirectLog.findAll({
|
||
where: logWhere,
|
||
attributes: [ 'quantity' ],
|
||
raw: true,
|
||
...(transaction ? { transaction } : {}),
|
||
});
|
||
const existingTotal = existingLogs.reduce((sum, log) => sum + Number(log.quantity), 0);
|
||
|
||
const newTotal = existingTotal + quantity;
|
||
|
||
if (newTotal > totalPlanQty) {
|
||
return {
|
||
ok: false,
|
||
error: {
|
||
code: 400,
|
||
message: `入库数量超过计划:商品计划 ${totalPlanQty},已入库 ${existingTotal},本次 ${quantity},合计 ${newTotal}`,
|
||
data: {
|
||
stock_id: stockId,
|
||
plan_quantity: totalPlanQty,
|
||
existing_quantity: existingTotal,
|
||
requested_quantity: quantity,
|
||
exceeded_by: newTotal - totalPlanQty,
|
||
},
|
||
},
|
||
};
|
||
}
|
||
|
||
// 写入记录
|
||
const createOpts = transaction ? { transaction } : {};
|
||
const log = await ctx.model.InboundDirectLog.create({
|
||
warehouse_id: entryOrder.warehouse_id,
|
||
store_id: entryOrder.store_id,
|
||
stock_id: stockId,
|
||
quantity,
|
||
inbound_type: inboundType,
|
||
entry_order_id: entryOrder.id,
|
||
entry_order_code: entryOrder.entry_order_code,
|
||
space_id: spaceId,
|
||
remark,
|
||
operator_id: ctx.user?.employees_id || ctx.user?.id || null,
|
||
operator_name: ctx.user?.employees_name || '',
|
||
created_at: new Date(),
|
||
});
|
||
|
||
return {
|
||
ok: true,
|
||
log: {
|
||
id: log.id,
|
||
stock_id: stockId,
|
||
quantity,
|
||
inbound_type: inboundType,
|
||
space_id: spaceId,
|
||
plan_quantity: totalPlanQty,
|
||
existing_before: existingTotal,
|
||
existing_after: newTotal,
|
||
remaining: Math.max(0, totalPlanQty - newTotal),
|
||
},
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 按商品增量添加导入/PDA 入库记录(支持单条和批量)。
|
||
*
|
||
* 单条模式(兼容旧调用):
|
||
* { entry_order_code, stock_id, quantity, inbound_type, remark }
|
||
*
|
||
* 批量模式(推荐):
|
||
* { entry_order_code, items: [{ stock_id, quantity, inbound_type, remark }] }
|
||
*
|
||
* 批量模式下所有商品共享同一个入库单状态校验,任一商品校验失败整批拒绝。
|
||
* 若该商品在当前入库单中的累计入库量超过计划数量则拒绝。
|
||
* @param {Object} params
|
||
* @param {string} params.entry_order_code 入库单号
|
||
* @param {number} [params.stock_id] 商品SKU ID(单条模式)
|
||
* @param {number} [params.quantity] 本次入库数量(单条模式)
|
||
* @param {string} [params.inbound_type] 入库方式(单条模式)
|
||
* @param {Array} [params.items] 商品列表(批量模式)
|
||
* @param {string} [params.remark] 备注(单条模式)
|
||
* @return {Promise<Object>} code/data/message 结构
|
||
*/
|
||
async addItem(params) {
|
||
const { ctx } = this;
|
||
const entryOrderCode = String(params.entry_order_code || '').trim();
|
||
|
||
if (!entryOrderCode) {
|
||
return { code: 400, message: 'entry_order_code 必填', data: null };
|
||
}
|
||
|
||
// 判断批量/单条模式
|
||
const isBatch = Array.isArray(params.items) && params.items.length > 0;
|
||
const items = isBatch ? params.items : [{
|
||
stock_id: params.stock_id,
|
||
quantity: params.quantity,
|
||
inbound_type: params.inbound_type,
|
||
remark: params.remark,
|
||
}];
|
||
|
||
// 查找入库单
|
||
const entryOrder = await ctx.model.EntryOrder.findOne({
|
||
where: {
|
||
entry_order_code: entryOrderCode,
|
||
warehouse_id: ctx.user.store_id,
|
||
is_enabled: 1,
|
||
deleted_at: null,
|
||
},
|
||
});
|
||
|
||
if (!entryOrder) {
|
||
return { code: 404, message: '入库单不存在或无权访问', data: null };
|
||
}
|
||
|
||
// 检查入库单状态
|
||
if (entryOrder.order_status === 'CANCELLED') {
|
||
return { code: 400, message: '已作废入库单不允许操作', data: null };
|
||
}
|
||
if (entryOrder.order_status === 'COMPLETED') {
|
||
return { code: 400, message: '已完成的入库单不允许操作', data: null };
|
||
}
|
||
|
||
// 批量模式下用事务包裹,任一失败整批回退
|
||
const useTransaction = isBatch;
|
||
const txn = useTransaction ? await ctx.model.transaction() : null;
|
||
|
||
try {
|
||
const results = [];
|
||
for (const item of items) {
|
||
const result = await this._addSingleItem(ctx, entryOrder, item, txn);
|
||
if (!result.ok) {
|
||
if (txn) await txn.rollback();
|
||
return result.error;
|
||
}
|
||
results.push(result.log);
|
||
}
|
||
|
||
if (txn) await txn.commit();
|
||
|
||
// 非阻塞记录操作日志(批量模式只记一条汇总)
|
||
if (results.length > 0) {
|
||
const totalQty = results.reduce((s, r) => s + r.quantity, 0);
|
||
const types = [ ...new Set(results.map(r => r.inbound_type)) ].join(',');
|
||
setImmediate(() => {
|
||
ctx.service.systems.operationLog.createOperationLog({
|
||
businessType: 'entry_order',
|
||
businessId: entryOrder.id,
|
||
operationCode: 'DIRECT_INBOUND_ADD',
|
||
operator: {
|
||
id: ctx.user?.employees_id || ctx.user?.id,
|
||
name: ctx.user?.employees_name || '',
|
||
},
|
||
extras: {
|
||
warehouseId: entryOrder.warehouse_id,
|
||
message: `导入/PDA入库添加 ${results.length} 种商品,总数量 ${totalQty},方式 ${types}`,
|
||
},
|
||
}).catch(err => {
|
||
ctx.logger.error(`[InboundDirectLog] 记录操作日志失败: ${err.message}`);
|
||
});
|
||
});
|
||
}
|
||
|
||
if (!isBatch) {
|
||
const r = results[0];
|
||
return {
|
||
code: 200,
|
||
message: '添加成功',
|
||
data: { ...r },
|
||
};
|
||
}
|
||
|
||
return {
|
||
code: 200,
|
||
message: `添加成功,共 ${results.length} 项`,
|
||
data: {
|
||
count: results.length,
|
||
total_quantity: results.reduce((s, r) => s + r.quantity, 0),
|
||
items: results,
|
||
},
|
||
};
|
||
} catch (error) {
|
||
if (txn && typeof txn.rollback === 'function') {
|
||
await txn.rollback();
|
||
}
|
||
throw error;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 移除一条导入/PDA 入库记录(仅限未提交的入库单)。
|
||
* @param {Object} params
|
||
* @param {number} params.id 入库记录ID(wms_inbound_direct_log.id)
|
||
* @return {Promise<Object>} code/data/message 结构
|
||
*/
|
||
async removeItem(params) {
|
||
const { ctx } = this;
|
||
const logId = Number(params.id || 0);
|
||
|
||
if (!logId) {
|
||
return { code: 400, message: 'id 必填', data: null };
|
||
}
|
||
|
||
const log = await ctx.model.InboundDirectLog.findByPk(logId);
|
||
if (!log) {
|
||
return { code: 404, message: '入库记录不存在', data: null };
|
||
}
|
||
|
||
// 检查所属入库单状态
|
||
const entryOrder = await ctx.model.EntryOrder.findOne({
|
||
where: {
|
||
id: log.entry_order_id,
|
||
warehouse_id: ctx.user.store_id,
|
||
is_enabled: 1,
|
||
deleted_at: null,
|
||
},
|
||
});
|
||
|
||
if (!entryOrder) {
|
||
return { code: 404, message: '关联入库单不存在或无权访问', data: null };
|
||
}
|
||
|
||
if (entryOrder.order_status === 'CANCELLED') {
|
||
return { code: 400, message: '已作废入库单不允许操作', data: null };
|
||
}
|
||
if (entryOrder.order_status === 'COMPLETED') {
|
||
return { code: 400, message: '已完成的入库单不允许移除记录', data: null };
|
||
}
|
||
|
||
// 软删除该记录
|
||
await log.destroy();
|
||
|
||
// 非阻塞记录操作日志
|
||
setImmediate(() => {
|
||
ctx.service.systems.operationLog.createOperationLog({
|
||
businessType: 'entry_order',
|
||
businessId: entryOrder.id,
|
||
operationCode: 'DIRECT_INBOUND_REMOVE',
|
||
operator: {
|
||
id: ctx.user?.employees_id || ctx.user?.id,
|
||
name: ctx.user?.employees_name || '',
|
||
},
|
||
extras: {
|
||
warehouseId: entryOrder.warehouse_id,
|
||
message: `移除导入/PDA入库记录 id=${logId},stock_id=${log.stock_id},数量 ${log.quantity},方式 ${log.inbound_type}`,
|
||
},
|
||
}).catch(err => {
|
||
ctx.logger.error(`[InboundDirectLog] 记录操作日志失败: ${err.message}`);
|
||
});
|
||
});
|
||
|
||
return {
|
||
code: 200,
|
||
message: '移除成功',
|
||
data: {
|
||
id: logId,
|
||
stock_id: log.stock_id,
|
||
quantity: log.quantity,
|
||
inbound_type: log.inbound_type,
|
||
},
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 提交确认完成入库,将导入/PDA 入库记录写入库存,并触发奇门/API 回传。
|
||
* @param {string} entryOrderCode 入库单号
|
||
* @return {Promise<Object>} code/data/message 结构
|
||
*/
|
||
async commit(entryOrderCode) {
|
||
const { ctx, app } = this;
|
||
const code = String(entryOrderCode || '').trim();
|
||
|
||
if (!code) {
|
||
return { code: 400, message: 'entry_order_code 必填', data: null };
|
||
}
|
||
|
||
const entryOrder = await ctx.model.EntryOrder.findOne({
|
||
where: {
|
||
entry_order_code: code,
|
||
warehouse_id: ctx.user.store_id,
|
||
is_enabled: 1,
|
||
deleted_at: null,
|
||
},
|
||
});
|
||
|
||
if (!entryOrder) {
|
||
return { code: 404, message: '入库单不存在或无权访问', data: null };
|
||
}
|
||
|
||
if (entryOrder.order_status === 'CANCELLED') {
|
||
return { code: 400, message: '已作废入库单不允许完成', data: null };
|
||
}
|
||
if (entryOrder.order_status === 'COMPLETED') {
|
||
return { code: 400, message: '入库单已完成,请勿重复提交', data: null };
|
||
}
|
||
|
||
// 查询该入库单下所有导入/PDA 入库记录
|
||
const directLogs = await ctx.model.InboundDirectLog.findAll({
|
||
where: { entry_order_id: entryOrder.id },
|
||
});
|
||
|
||
if (!directLogs || directLogs.length === 0) {
|
||
return { code: 400, message: '暂无导入/PDA 入库记录,请先添加商品', data: null };
|
||
}
|
||
|
||
// 按 stock_id 汇总入库数量
|
||
const stockSummary = {};
|
||
for (const log of directLogs) {
|
||
const key = String(log.stock_id);
|
||
if (!stockSummary[key]) stockSummary[key] = 0;
|
||
stockSummary[key] += Number(log.quantity);
|
||
}
|
||
|
||
// 查询入库单所有明细
|
||
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 transaction = await ctx.model.transaction();
|
||
|
||
try {
|
||
// 记录已处理过的 stock_id,避免同 stock_id 多明细重复写库存
|
||
const processedStockIds = new Set();
|
||
|
||
// 逐商品写入库存
|
||
for (const item of entryItems) {
|
||
const stockId = item.stock_id;
|
||
if (!stockId) continue;
|
||
|
||
const inboundQty = stockSummary[String(stockId)] || 0;
|
||
if (inboundQty <= 0) continue;
|
||
|
||
// 更新入库明细的 received_quantity(按该明细的计划占比分配)
|
||
const planQty = Number(item.count) || 0;
|
||
const itemReceivedQty = planQty > 0 ? Math.min(planQty, inboundQty) : inboundQty;
|
||
await ctx.model.EntryItems.update({
|
||
received_quantity: itemReceivedQty,
|
||
}, {
|
||
where: { id: item.id },
|
||
transaction,
|
||
});
|
||
|
||
// 同一 stock_id 只写一次库存
|
||
if (processedStockIds.has(String(stockId))) continue;
|
||
processedStockIds.add(String(stockId));
|
||
|
||
// 使用入库单号作为批次号
|
||
const batchNo = entryOrder.entry_order_code;
|
||
const inventoryType = item.inventory_type || 'ZP';
|
||
|
||
// 从该 stock_id 的入库记录中取第一个非空 space_id,兜底 1
|
||
const logForSpace = directLogs.find(l => String(l.stock_id) === String(stockId) && l.space_id);
|
||
const spaceId = logForSpace ? Number(logForSpace.space_id) : 1;
|
||
|
||
// 锁定并更新 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: inboundQty, 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: inboundQty,
|
||
batch_no: batchNo,
|
||
inventory_type: inventoryType,
|
||
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: '导入/PDA直接入库提交',
|
||
before_quantity: beforeQuantity,
|
||
after_quantity: afterQuantity,
|
||
before_locked_quantity: beforeLockedQuantity,
|
||
after_locked_quantity: afterLockedQuantity,
|
||
created_at: new Date(),
|
||
}, { transaction });
|
||
}
|
||
|
||
// 创建/更新 Storage 库位库存
|
||
const storageRecord = await ctx.model.Storage.findOne({
|
||
where: {
|
||
space_id: spaceId,
|
||
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 + ${inboundQty}`),
|
||
available_quantity: app.Sequelize.literal(`available_quantity + ${inboundQty}`),
|
||
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: spaceId,
|
||
stock_id: stockId,
|
||
batch_no: batchNo,
|
||
inventory_type: inventoryType,
|
||
quantity: inboundQty,
|
||
locked_quantity: 0,
|
||
available_quantity: inboundQty,
|
||
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 });
|
||
}
|
||
}
|
||
|
||
// 更新入库单状态为 COMPLETED
|
||
await entryOrder.update({
|
||
order_status: 'COMPLETED',
|
||
sync_status: 'SUCCESS',
|
||
sync_message: JSON.stringify({
|
||
completedAt: new Date(),
|
||
totalQuantity: Object.values(stockSummary).reduce((s, q) => s + q, 0),
|
||
itemCount: processedStockIds.size,
|
||
source: 'direct_inbound',
|
||
}),
|
||
updated_at: new Date(),
|
||
}, { transaction });
|
||
|
||
// 记录操作日志(事务内)
|
||
const totalQty = Object.values(stockSummary).reduce((s, q) => s + q, 0);
|
||
await ctx.service.systems.operationLog.createOperationLog({
|
||
businessType: 'entry_order',
|
||
businessId: entryOrder.id,
|
||
operationCode: 'DIRECT_INBOUND_COMMIT',
|
||
operator: {
|
||
id: ctx.user?.employees_id || ctx.user?.id,
|
||
name: ctx.user?.employees_name || '',
|
||
},
|
||
extras: {
|
||
warehouseId: entryOrder.warehouse_id,
|
||
message: `导入/PDA入库提交完成,共 ${processedStockIds.size} 种商品,总数量 ${totalQty}`,
|
||
},
|
||
transaction,
|
||
});
|
||
|
||
await transaction.commit();
|
||
} catch (error) {
|
||
if (transaction && typeof transaction.rollback === 'function') {
|
||
await transaction.rollback();
|
||
}
|
||
throw error;
|
||
}
|
||
|
||
// 事务外:异步触发奇门/API 回传
|
||
setImmediate(() => {
|
||
this._sendCallback(entryOrder).catch(err => {
|
||
ctx.logger.error(`[InboundDirectLog] 回传异常 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: Object.values(stockSummary).reduce((s, q) => s + q, 0),
|
||
},
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 根据入库单来源异步回传(奇门 / OpenAPI)。
|
||
* @param {Object} entryOrder 入库单实例
|
||
* @return {Promise<void>}
|
||
*/
|
||
async _sendCallback(entryOrder) {
|
||
const { ctx } = this;
|
||
const sourceType = String(entryOrder.source_type || '').toUpperCase();
|
||
|
||
ctx.logger.info(
|
||
`[InboundDirectLog] 准备回传 entryOrderId=${entryOrder.id} sourceType=${sourceType}`
|
||
);
|
||
|
||
try {
|
||
const items = await ctx.model.EntryItems.findAll({
|
||
where: { order_id: entryOrder.id },
|
||
attributes: [ 'item_code', 'item_id', 'count', 'inventory_type', 'owner_code', 'received_quantity' ],
|
||
raw: true,
|
||
});
|
||
|
||
if (!items || items.length === 0) {
|
||
ctx.logger.warn(`[InboundDirectLog] 回传:入库单无明细 entryOrderId=${entryOrder.id}`);
|
||
return;
|
||
}
|
||
|
||
const orderLines = items.map((item, index) => ({
|
||
orderLineNo: index + 1,
|
||
ownerCode: item.owner_code || '',
|
||
itemCode: item.item_code || '',
|
||
itemId: item.item_id || '',
|
||
inventoryType: item.inventory_type || 'ZP',
|
||
planQty: item.count || 0,
|
||
actualQty: item.received_quantity || 0,
|
||
}));
|
||
|
||
if (sourceType === 'QM') {
|
||
await this._sendQimenCallback(entryOrder, orderLines);
|
||
} else if (sourceType === 'API') {
|
||
await this._sendOpenApiCallback(entryOrder);
|
||
} else {
|
||
ctx.logger.info(`[InboundDirectLog] 来源类型 ${sourceType} 不支持回传`);
|
||
}
|
||
} catch (error) {
|
||
ctx.logger.error(`[InboundDirectLog] _sendCallback 异常: ${error.message}`, error.stack);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 奇门回传:调用 taobao.qimen.entryorder.confirm。
|
||
* @param {Object} entryOrder 入库单
|
||
* @param {Array} orderLines 明细行
|
||
* @return {Promise<void>}
|
||
*/
|
||
async _sendQimenCallback(entryOrder, orderLines) {
|
||
const { ctx, app } = this;
|
||
|
||
try {
|
||
const queryData = {
|
||
request: {
|
||
entryOrder: {
|
||
entryOrderCode: entryOrder.entry_order_code,
|
||
ownerCode: entryOrder.qimen_owner_code || '',
|
||
warehouseCode: entryOrder.qimen_warehouse_code || '',
|
||
entryOrderId: entryOrder.id,
|
||
entryOrderType: entryOrder.order_type,
|
||
outBizCode: `DIRECT_INBOUND_${Date.now()}`,
|
||
confirmType: 0,
|
||
status: 'FULFILLED',
|
||
freight: 0,
|
||
operateTime: app.formatDate(new Date()),
|
||
remark: '导入/PDA直接入库提交',
|
||
},
|
||
orderLines,
|
||
},
|
||
};
|
||
|
||
const result = await app.qimenClient.send(
|
||
'taobao.qimen.entryorder.confirm',
|
||
entryOrder.qimen_owner_code,
|
||
queryData,
|
||
{ ctx }
|
||
);
|
||
|
||
const qimenResult = result && result.xmlArray && result.xmlArray.response;
|
||
if (qimenResult && String(qimenResult.flag) === 'success') {
|
||
ctx.logger.info(`[InboundDirectLog] 奇门回传成功 entryOrderId=${entryOrder.id}`);
|
||
} else {
|
||
ctx.logger.warn(
|
||
`[InboundDirectLog] 奇门回传失败 entryOrderId=${entryOrder.id} ` +
|
||
`message=${qimenResult?.message || '未知错误'}`
|
||
);
|
||
}
|
||
} catch (error) {
|
||
ctx.logger.error(`[InboundDirectLog] 奇门回传异常: ${error.message}`, error.stack);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* OpenAPI 回传:查询 ApiApp 回调地址并 POST 回传。
|
||
* @param {Object} entryOrder 入库单
|
||
* @return {Promise<void>}
|
||
*/
|
||
async _sendOpenApiCallback(entryOrder) {
|
||
const { ctx, app } = this;
|
||
|
||
try {
|
||
const storeWarehouse = await ctx.model.StoreWarehouse.findOne({
|
||
where: {
|
||
store_id: entryOrder.store_id,
|
||
warehouse_id: entryOrder.warehouse_id,
|
||
auth_status: 2,
|
||
},
|
||
attributes: [ 'id' ],
|
||
raw: true,
|
||
});
|
||
|
||
if (!storeWarehouse) {
|
||
ctx.logger.warn(
|
||
'[InboundDirectLog] OpenAPI回传:未找到授权关系 ' +
|
||
`entryOrderId=${entryOrder.id}`
|
||
);
|
||
return;
|
||
}
|
||
|
||
const apiApp = await ctx.model.ApiApp.findOne({
|
||
where: {
|
||
contract_id: storeWarehouse.id,
|
||
is_enabled: 1,
|
||
callback_url: {
|
||
[ app.Sequelize.Op.and ]: [
|
||
{ [ app.Sequelize.Op.ne ]: null },
|
||
{ [ app.Sequelize.Op.ne ]: '' },
|
||
],
|
||
},
|
||
},
|
||
attributes: [ 'self_app_key', 'self_app_secret', 'callback_url' ],
|
||
raw: true,
|
||
});
|
||
|
||
if (!apiApp || !apiApp.callback_url) {
|
||
ctx.logger.warn(
|
||
'[InboundDirectLog] OpenAPI回传:未找到有效ApiApp配置 ' +
|
||
`entryOrderId=${entryOrder.id}`
|
||
);
|
||
return;
|
||
}
|
||
|
||
const callbackData = {
|
||
entryOrderId: entryOrder.id,
|
||
entryOrderCode: entryOrder.entry_order_code,
|
||
completedAt: new Date().toISOString(),
|
||
inboundType: 'direct',
|
||
};
|
||
|
||
const result = await ctx.service.openapi.callback.sendWithRetry({
|
||
callbackUrl: apiApp.callback_url,
|
||
appKey: apiApp.self_app_key,
|
||
selfAppSecret: apiApp.self_app_secret || '',
|
||
event: 'entry_order_direct_inbound_completed',
|
||
data: callbackData,
|
||
metadata: {
|
||
source: 'inbound_direct_log',
|
||
entryOrderId: entryOrder.id,
|
||
},
|
||
});
|
||
|
||
if (result.success) {
|
||
ctx.logger.info(
|
||
`[InboundDirectLog] OpenAPI回传成功 entryOrderId=${entryOrder.id} ` +
|
||
`callbackUrl=${apiApp.callback_url}`
|
||
);
|
||
} else {
|
||
ctx.logger.warn(
|
||
`[InboundDirectLog] OpenAPI回传失败 entryOrderId=${entryOrder.id} ` +
|
||
`error=${result.error}`
|
||
);
|
||
}
|
||
} catch (error) {
|
||
ctx.logger.error(`[InboundDirectLog] OpenAPI回传异常: ${error.message}`, error.stack);
|
||
}
|
||
}
|
||
}
|
||
|
||
module.exports = InboundDirectLogService;
|