WMS_MAIN/app/service/systems/receiving_entry_match.js
liufumingren 77435aeb79 1
2026-06-23 18:48:33 +08:00

883 lines
31 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;
/** @type {number} 收货单缓存过期时间(秒) */
const RECEIVING_CACHE_TTL = 300;
/** @type {number} 收货单查询天数范围 */
const RECEIVING_LOOKBACK_DAYS = 3;
/** @type {string} 收货单列表缓存键前缀 */
const RECEIVING_CACHE_KEY_PREFIX = 'cache:receiving_orders:warehouse:';
/**
* 入库单创建后异步匹配收货单并写入绑定关系服务。
*
* 职责:
* 1. 缓存仓库下近 3 天的收货单列表(Redis,TTL 300s)
* 2. 根据入库单 remark 匹配收货单号
* 3. 对比入库单明细与收货单明细(SKU + 数量)
* 4. 匹配成功后写入 wms_entry_order_receiving 绑定关系,CREATED 状态转 PENDING
* 5. 覆盖场景标记收货单为"部分入库"
*/
class ReceivingEntryMatchService extends Service {
/**
* 入库单创建后的异步匹配入口:根据备注匹配收货单,写入绑定关系并在必要时转换状态。
* 匹配到收货单后写入 wms_entry_order_receiving 绑定关系;
* 如果入库单当前状态为 CREATED,同步更新为 PENDING。
* 不阻塞主流程,所有错误仅记录日志。
*
* @param {number} entryOrderId 入库单 ID
* @return {Promise<void>}
*/
async matchAfterEntryCompleted(entryOrderId) {
const { ctx } = this;
try {
// 1. 加载入库单及其明细
const entryOrder = await ctx.model.EntryOrder.findOne({
where: { id: entryOrderId, is_enabled: 1, deleted_at: null },
include: [{
model: ctx.model.EntryItems,
as: 'items',
required: false,
attributes: [ 'id', 'item_code', 'stock_id', 'count', 'received_quantity', 'inventory_type' ],
}],
});
if (!entryOrder) {
ctx.logger.warn(`[ReceivingEntryMatch] 入库单不存在,跳过匹配 entryOrderId=${entryOrderId}`);
return;
}
const remark = (entryOrder.remark || '').trim();
if (!remark) {
ctx.logger.info(`[ReceivingEntryMatch] 入库单无备注,跳过匹配 entryOrderId=${entryOrderId}`);
return;
}
const warehouseId = entryOrder.warehouse_id;
// 2. 获取近 3 天的收货单列表(带缓存)
const receivingOrders = await this._getRecentReceivingOrders(warehouseId);
if (!receivingOrders || receivingOrders.length === 0) {
ctx.logger.info(`[ReceivingEntryMatch] 仓库无近期收货单,跳过匹配 warehouseId=${warehouseId}`);
return;
}
// 3. 从 remark 中提取可能匹配的收货单号
const matchedReceiving = await this._findReceivingByRemark(remark, receivingOrders, warehouseId);
if (!matchedReceiving) {
ctx.logger.info(`[ReceivingEntryMatch] remark 中未匹配到收货单号 entryOrderId=${entryOrderId} remark="${remark}"`);
return;
}
ctx.logger.info(
`[ReceivingEntryMatch] 匹配到收货单 entryOrderId=${entryOrderId} ` +
`receivingId=${matchedReceiving.id} receivingNumber=${matchedReceiving.receiving_number}`
);
// 4. 对比明细
const entryItems = (entryOrder.items || []).map(item => ({
stockId: item.stock_id,
itemCode: item.item_code,
count: item.count || 0,
receivedQuantity: item.received_quantity || 0,
inventoryType: item.inventory_type || 'ZP',
}));
const comparisonResult = this._compareDetails(entryItems, matchedReceiving.details || []);
// 5. 根据对比结果写入绑定关系
if (comparisonResult.type === 'full_match' || comparisonResult.type === 'receiving_covers_entry') {
// 匹配成功 → 写入 wms_entry_order_receiving 绑定关系
await this._bindEntryOrderReceiving(entryOrderId, matchedReceiving.id);
// 若入库单当前状态是 CREATED,更新为 PENDING
if (entryOrder.order_status === 'CREATED') {
await ctx.model.EntryOrder.update(
{ order_status: 'PENDING', updated_at: new Date() },
{ where: { id: entryOrderId, order_status: 'CREATED' } }
);
ctx.logger.info(
`[ReceivingEntryMatch] 入库单状态 CREATED → PENDING entryOrderId=${entryOrderId} ` +
`receivingId=${matchedReceiving.id}`
);
}
// receipting_covers_entry 场景额外标记收货单为部分入库
if (comparisonResult.type === 'receiving_covers_entry') {
await this._markReceivingPartialStorage(matchedReceiving.id, comparisonResult, warehouseId);
}
} else {
// 其他情况(entry 有 receiving 没有的明细,或完全不匹配)→ 不做处理
ctx.logger.info(
`[ReceivingEntryMatch] 明细对比结果为 ${comparisonResult.type},不触发绑定 ` +
`entryOrderId=${entryOrderId} receivingId=${matchedReceiving.id}`
);
}
} catch (error) {
ctx.logger.error(
`[ReceivingEntryMatch] 异步匹配异常 entryOrderId=${entryOrderId}: ${error.message}`,
error.stack
);
}
}
/**
* 写入入库单与收货单的主表级绑定关系。
* 使用 upsert 策略避免重复写入;绑定记录为软删除模型,已删除的历史记录会被恢复。
*
* @param {number} entryOrderId 入库单 ID
* @param {number} receivingId 收货单 ID
* @return {Promise<void>}
*/
async _bindEntryOrderReceiving(entryOrderId, receivingId) {
const { ctx } = this;
try {
// 先检查是否已存在未删除的绑定记录
const existing = await ctx.model.EntryOrderReceiving.findOne({
where: { entry_order_id: entryOrderId, receiving_id: receivingId },
paranoid: false,
});
if (existing) {
if (existing.deleted_at) {
// 已软删除的记录,恢复它
await existing.restore();
ctx.logger.info(
`[ReceivingEntryMatch] 恢复已删除的绑定关系 entryOrderId=${entryOrderId} receivingId=${receivingId}`
);
} else {
ctx.logger.info(
`[ReceivingEntryMatch] 绑定关系已存在,跳过 entryOrderId=${entryOrderId} receivingId=${receivingId}`
);
}
return;
}
await ctx.model.EntryOrderReceiving.create({
entry_order_id: entryOrderId,
receiving_id: receivingId,
});
ctx.logger.info(
`[ReceivingEntryMatch] 写入绑定关系成功 entryOrderId=${entryOrderId} receivingId=${receivingId}`
);
} catch (error) {
// 唯一索引冲突时忽略(并发场景)
if (error.name === 'SequelizeUniqueConstraintError') {
ctx.logger.warn(
`[ReceivingEntryMatch] 绑定关系已存在(并发写入) entryOrderId=${entryOrderId} receivingId=${receivingId}`
);
return;
}
ctx.logger.error(
`[ReceivingEntryMatch] 写入绑定关系失败 entryOrderId=${entryOrderId} receivingId=${receivingId}: ${error.message}`,
error.stack
);
}
}
/**
* 获取仓库近 3 天的收货单列表(优先从 Redis 缓存读取)。
*
* @param {number} warehouseId 仓库 ID
* @return {Promise<Array<Object>>} 收货单列表(含明细)
*/
async _getRecentReceivingOrders(warehouseId) {
const { ctx, app } = this;
const cacheKey = `${RECEIVING_CACHE_KEY_PREFIX}${warehouseId}`;
try {
// 先尝试从缓存读取
const cached = await app.getCacheAsync(cacheKey);
if (cached) {
ctx.logger.info(`[ReceivingEntryMatch] 命中收货单缓存 warehouseId=${warehouseId}`);
return cached;
}
} catch (cacheErr) {
ctx.logger.warn(`[ReceivingEntryMatch] 读取缓存失败,回退到数据库查询: ${cacheErr.message}`);
}
// 缓存未命中,从数据库查询
const threeDaysAgo = new Date(Date.now() - RECEIVING_LOOKBACK_DAYS * 24 * 60 * 60 * 1000);
const receivingOrders = await ctx.model.Receiving.findAll({
where: {
warehouse_id: warehouseId,
is_deleted: false,
status: [ 'receiving', 'completed' ],
created_at: { [app.Sequelize.Op.gte]: threeDaysAgo },
},
attributes: [ 'id', 'receiving_number', 'status', 'storage_status' ],
include: [{
model: ctx.model.ReceivingDetail,
as: 'details',
required: false,
attributes: [
'id', 'system_product_id', 'product_name', 'actual_quantity',
'storage_status', 'stored_quantity',
],
}],
order: [[ 'created_at', 'DESC' ]],
});
const result = receivingOrders.map(order => {
const plain = typeof order.toJSON === 'function' ? order.toJSON() : order;
return {
id: plain.id,
receiving_number: plain.receiving_number,
status: plain.status,
storage_status: plain.storage_status,
details: (plain.details || []).map(d => ({
id: d.id,
system_product_id: d.system_product_id,
product_name: d.product_name,
actual_quantity: d.actual_quantity,
storage_status: d.storage_status,
stored_quantity: d.stored_quantity || 0,
})),
};
});
// 写入缓存
try {
await app.setCacheAsync(cacheKey, result, RECEIVING_CACHE_TTL);
ctx.logger.info(`[ReceivingEntryMatch] 收货单缓存已写入 warehouseId=${warehouseId} count=${result.length}`);
} catch (cacheErr) {
ctx.logger.warn(`[ReceivingEntryMatch] 写入缓存失败: ${cacheErr.message}`);
}
return result;
}
/**
* 从入库单备注中查找匹配的收货单号。
* 遍历缓存的收货单号列表,检查 remark 是否包含收货单号。
* 若匹配到多个,返回最近创建的那一个。
*
* @param {string} remark 入库单备注
* @param {Array<Object>} receivingOrders 收货单列表
* @param {number} warehouseId 仓库 ID
* @return {Promise<Object|null>} 匹配到的收货单(含明细),未匹配返回 null
*/
async _findReceivingByRemark(remark, receivingOrders, warehouseId) {
const { ctx } = this;
// 按字符串包含匹配
const matchedOrders = [];
for (const order of receivingOrders) {
if (remark.includes(order.receiving_number)) {
matchedOrders.push(order);
}
}
if (matchedOrders.length === 0) {
return null;
}
// 多个匹配时取第一个(列表已按 created_at DESC 排序,即最新)
const matched = matchedOrders[0];
// 如果缓存的收货单没有 details(可能为空),重新加载
if (!matched.details || matched.details.length === 0) {
const fullOrder = await ctx.model.Receiving.findOne({
where: { id: matched.id, warehouse_id: warehouseId },
attributes: [ 'id', 'receiving_number', 'status', 'storage_status' ],
include: [{
model: ctx.model.ReceivingDetail,
as: 'details',
required: false,
attributes: [
'id', 'system_product_id', 'product_name', 'actual_quantity',
'storage_status', 'stored_quantity',
],
}],
});
if (!fullOrder) return null;
const plain = typeof fullOrder.toJSON === 'function' ? fullOrder.toJSON() : fullOrder;
return {
id: plain.id,
receiving_number: plain.receiving_number,
status: plain.status,
storage_status: plain.storage_status,
details: (plain.details || []).map(d => ({
id: d.id,
system_product_id: d.system_product_id,
product_name: d.product_name,
actual_quantity: d.actual_quantity,
storage_status: d.storage_status,
stored_quantity: d.stored_quantity || 0,
})),
};
}
return matched;
}
/**
* 对比入库单明细与收货单明细。
*
* 判断规则:
* - full_match:两者 SKU 与数量完全一致
* - receiving_covers_entry:收货单包含入库单所有明细(SKU 匹配),
* 且收货单至少有一个 SKU 数量多于入库单
* - entry_exceeds_receiving:入库单有收货单没有的 SKU 或数量超出
* - no_match:SKU 完全没有交集
*
* @param {Array<Object>} entryItems 入库单明细 [{ stockId, itemCode, count, receivedQuantity, inventoryType }]
* @param {Array<Object>} receivingDetails 收货单明细 [{ id, system_product_id, actual_quantity, ... }]
* @return {{ type: string, matchedDetails?: Array, uncoveredDetails?: Array, overageDetails?: Array }} 对比结果对象
*/
_compareDetails(entryItems, receivingDetails) {
// 构建收货单明细 Map:system_product_id → { actual_quantity, ... }
const receivingMap = new Map();
for (const detail of receivingDetails) {
const productId = detail.system_product_id;
if (!productId) continue;
const existing = receivingMap.get(productId);
if (existing) {
existing.actual_quantity += (detail.actual_quantity || 0);
} else {
receivingMap.set(productId, {
detailId: detail.id,
system_product_id: productId,
actual_quantity: detail.actual_quantity || 0,
stored_quantity: detail.stored_quantity || 0,
});
}
}
// 构建入库单明细 Map:stock_id → { count, receivedQuantity }
const entryMap = new Map();
for (const item of entryItems) {
const stockId = item.stockId;
if (!stockId) continue;
const existing = entryMap.get(stockId);
if (existing) {
existing.count += (item.count || 0);
existing.receivedQuantity += (item.receivedQuantity || 0);
} else {
entryMap.set(stockId, {
stockId,
itemCode: item.itemCode,
count: item.count || 0,
receivedQuantity: item.receivedQuantity || 0,
inventoryType: item.inventoryType,
});
}
}
if (entryMap.size === 0 || receivingMap.size === 0) {
return { type: 'no_match' };
}
// 检查入库单每个 SKU 是否在收货单中且数量 ≤ 收货单数量
let allEntryItemsCovered = true;
let hasReceivingOverage = false;
const matchedDetails = []; // 匹配到的收货单明细
const uncoveredDetails = []; // 入库单中有但收货单没有/不足的
for (const [ stockId, entryItem ] of entryMap) {
const receivingItem = receivingMap.get(stockId);
if (!receivingItem) {
// 入库单有,收货单没有 → 入库单超出
allEntryItemsCovered = false;
uncoveredDetails.push({
stockId,
itemCode: entryItem.itemCode,
entryCount: entryItem.count,
receivingCount: 0,
reason: 'missing_in_receiving',
});
continue;
}
if (entryItem.count > receivingItem.actual_quantity) {
// 入库单数量 > 收货单数量 → 入库单超出
allEntryItemsCovered = false;
uncoveredDetails.push({
stockId,
itemCode: entryItem.itemCode,
entryCount: entryItem.count,
receivingCount: receivingItem.actual_quantity,
reason: 'entry_exceeds_receiving',
});
} else if (entryItem.count < receivingItem.actual_quantity) {
// 收货单数量 > 入库单数量 → 存在覆盖余量
hasReceivingOverage = true;
matchedDetails.push({
...receivingItem,
entryCount: entryItem.count,
overage: receivingItem.actual_quantity - entryItem.count,
});
} else {
// 数量完全相等
matchedDetails.push({
...receivingItem,
entryCount: entryItem.count,
overage: 0,
});
}
}
// 检查收货单是否有入库单没有的 SKU
const receivingOnlyItems = [];
for (const [ productId ] of receivingMap) {
if (!entryMap.has(productId)) {
receivingOnlyItems.push(productId);
}
}
if (!allEntryItemsCovered) {
return {
type: 'entry_exceeds_receiving',
uncoveredDetails,
receivingOnlyItems,
};
}
if (hasReceivingOverage || receivingOnlyItems.length > 0) {
return {
type: 'receiving_covers_entry',
matchedDetails,
overageDetails: matchedDetails.filter(d => d.overage > 0),
receivingOnlyItems,
};
}
// 所有入库单 SKU 都在收货单中,且数量完全相等,且收货单无额外 SKU
return {
type: 'full_match',
matchedDetails,
};
}
/**
* 根据入库单来源发送回传。
* - QM(奇门)→ 调用奇门入库单确认接口回传
* - API(OpenAPI)→ 查询 ApiApp 回调地址并 POST 回传
*
* @param {Object} entryOrder 入库单实例
* @param {Object} receivingOrder 匹配到的收货单
* @param {string} [matchType='auto_match'] 匹配类型标识,手动匹配时传入 'manual_match'
* @return {Promise<{success: boolean, sourceType: string, detail: Object}>} 回传结果
*/
async _sendCallback(entryOrder, receivingOrder, matchType = 'auto_match') {
const { ctx } = this;
const sourceType = String(entryOrder.source_type || '').toUpperCase();
ctx.logger.info(
`[ReceivingEntryMatch] 准备回传 entryOrderId=${entryOrder.id} ` +
`sourceType=${sourceType} receivingNumber=${receivingOrder.receiving_number}`
);
if (sourceType === 'QM') {
const detail = await this._sendQimenCallback(entryOrder, receivingOrder);
return { success: detail.success, sourceType, detail };
} else if (sourceType === 'API') {
const detail = await this._sendOpenApiCallback(entryOrder, receivingOrder, matchType);
return { success: detail.success, sourceType, detail };
}
ctx.logger.info(
`[ReceivingEntryMatch] 来源类型 ${sourceType} 不支持回传 entryOrderId=${entryOrder.id}`
);
return { success: false, sourceType, detail: { success: false, error: `来源类型 ${sourceType} 不支持回传` } };
}
/**
* 奇门回传:复用现有奇门入库单确认接口。
*
* @param {Object} entryOrder 入库单实例
* @param {Object} receivingOrder 匹配到的收货单
* @return {Promise<{success: boolean, error?: string}>} 回传结果
*/
async _sendQimenCallback(entryOrder, receivingOrder) {
const { ctx, app } = this;
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(`[ReceivingEntryMatch] 奇门回传:入库单无明细 entryOrderId=${entryOrder.id}`);
return { success: false, error: '入库单无明细' };
}
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,
}));
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: `RECEIVING_MATCH_${Date.now()}`,
confirmType: 0, // 0 = 最终确认
status: 'FULFILLED',
freight: 0,
operateTime: app.formatDate(new Date()),
remark: `匹配收货单${receivingOrder.receiving_number}自动回传`,
},
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(
`[ReceivingEntryMatch] 奇门回传成功 entryOrderId=${entryOrder.id} ` +
`receivingNumber=${receivingOrder.receiving_number}`
);
return { success: true };
}
ctx.logger.warn(
`[ReceivingEntryMatch] 奇门回传失败 entryOrderId=${entryOrder.id} ` +
`message=${qimenResult?.message || '未知错误'}`
);
return { success: false, error: qimenResult?.message || '未知错误' };
} catch (error) {
ctx.logger.error(
`[ReceivingEntryMatch] 奇门回传异常 entryOrderId=${entryOrder.id}: ${error.message}`,
error.stack
);
return { success: false, error: error.message };
}
}
/**
* OpenAPI 回传:查询 ApiApp 回调地址,通过签名鉴权 POST 回传。
*
* @param {Object} entryOrder 入库单实例
* @param {Object} receivingOrder 匹配到的收货单
* @param {string} [matchType='auto_match'] 匹配类型标识
* @return {Promise<{success: boolean, error?: string, retryCount?: number}>} 回传结果
*/
async _sendOpenApiCallback(entryOrder, receivingOrder, matchType = 'auto_match') {
const { ctx, app } = this;
try {
// 通过 store_warehouse 查找 ApiApp
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(
'[ReceivingEntryMatch] OpenAPI回传:未找到授权关系 ' +
`entryOrderId=${entryOrder.id} storeId=${entryOrder.store_id} warehouseId=${entryOrder.warehouse_id}`
);
return { success: false, error: '未找到授权关系' };
}
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(
'[ReceivingEntryMatch] OpenAPI回传:未找到有效ApiApp配置 ' +
`entryOrderId=${entryOrder.id} contractId=${storeWarehouse.id}`
);
return { success: false, error: '未找到有效ApiApp配置' };
}
// 构建回传数据
const callbackData = {
entryOrderId: entryOrder.id,
entryOrderCode: entryOrder.entry_order_code,
receivingNumber: receivingOrder.receiving_number,
receivingId: receivingOrder.id,
matchType,
completedAt: new Date().toISOString(),
};
// 使用 OpenAPI 回调服务发送
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_receiving_matched',
data: callbackData,
metadata: {
source: 'receiving_entry_match',
entryOrderId: entryOrder.id,
receivingId: receivingOrder.id,
},
});
if (result.success) {
ctx.logger.info(
`[ReceivingEntryMatch] OpenAPI回传成功 entryOrderId=${entryOrder.id} ` +
`callbackUrl=${apiApp.callback_url} retryCount=${result.retryCount}`
);
return { success: true, retryCount: result.retryCount };
}
ctx.logger.warn(
`[ReceivingEntryMatch] OpenAPI回传失败 entryOrderId=${entryOrder.id} ` +
`error=${result.error} retryCount=${result.retryCount}`
);
return { success: false, error: result.error, retryCount: result.retryCount };
} catch (error) {
ctx.logger.error(
`[ReceivingEntryMatch] OpenAPI回传异常 entryOrderId=${entryOrder.id}: ${error.message}`,
error.stack
);
return { success: false, error: error.message };
}
}
/**
* 标记收货单为"部分入库"。
* 更新收货单 storage_status 为 'partial',并更新明细的 storage_status 和 stored_quantity。
*
* @param {number} receivingId 收货单 ID
* @param {Object} comparisonResult 对比结果
* @param {number} warehouseId 仓库 ID
* @return {Promise<{success: boolean, error?: string}>} 标记结果
*/
async _markReceivingPartialStorage(receivingId, comparisonResult, warehouseId) {
const { ctx } = this;
try {
const receiving = await ctx.model.Receiving.findOne({
where: { id: receivingId, warehouse_id: warehouseId, is_deleted: false },
});
if (!receiving) {
ctx.logger.warn(`[ReceivingEntryMatch] 标记部分入库:收货单不存在 receivingId=${receivingId}`);
return { success: false, error: '收货单不存在' };
}
// 更新收货单主表的入库状态
await receiving.update({
storage_status: 'partial',
updated_at: new Date(),
});
// 更新匹配到的明细:标记为"全部入库",stored_quantity = entryCount
if (comparisonResult.matchedDetails && comparisonResult.matchedDetails.length > 0) {
for (const matched of comparisonResult.matchedDetails) {
await ctx.model.ReceivingDetail.update(
{
storage_status: 'all',
stored_quantity: matched.entryCount || matched.actual_quantity || 0,
updated_at: new Date(),
},
{ where: { id: matched.detailId, receiving_id: receivingId } }
);
}
}
// 更新超量明细:标记为"部分入库",stored_quantity = entryCount
if (comparisonResult.overageDetails && comparisonResult.overageDetails.length > 0) {
for (const overage of comparisonResult.overageDetails) {
await ctx.model.ReceivingDetail.update(
{
storage_status: 'partial',
stored_quantity: overage.entryCount || 0,
updated_at: new Date(),
},
{ where: { id: overage.detailId, receiving_id: receivingId } }
);
}
}
ctx.logger.info(
`[ReceivingEntryMatch] 收货单已标记为部分入库 receivingId=${receivingId} ` +
`receivingNumber=${receiving.receiving_number}`
);
return { success: true };
} catch (error) {
ctx.logger.error(
`[ReceivingEntryMatch] 标记部分入库失败 receivingId=${receivingId}: ${error.message}`,
error.stack
);
return { success: false, error: error.message };
}
}
/**
* 手动匹配入库单与收货单。
*
* 同步执行明细对比并触发回传,返回结构化匹配结果。
* 适用场景:运营人员手动指定收货单与入库单进行匹配并回传。
*
* 匹配规则(复用 _compareDetails):
* - full_match:两者 SKU 与数量完全一致 → 按来源回传
* - receiving_covers_entry:收货单覆盖入库单 → 回传 + 标记部分入库
* - entry_exceeds_receiving / no_match → 仅返回对比结果,不触发回传
*
* @param {number} receivingId 收货单 ID
* @param {number} entryOrderId 入库单 ID
* @return {Promise<Object>} 匹配结果对象
* @return {string} return.matchType 匹配类型:full_match / receiving_covers_entry / entry_exceeds_receiving / no_match
* @return {Object} return.comparisonResult 明细对比结果
* @return {boolean} return.callbackSent 是否已发送回传
* @return {Object|null} return.callbackResult 回传结果(未发送时为 null)
* @return {boolean} return.partialStorageMarked 是否已标记部分入库
* @return {Object} return.entryOrder 入库单摘要
* @return {Object} return.receivingOrder 收货单摘要
*/
async manualMatch(receivingId, entryOrderId) {
const { ctx } = this;
// 1. 加载入库单及其明细
const entryOrder = await ctx.model.EntryOrder.findOne({
where: { id: entryOrderId, is_enabled: 1, deleted_at: null },
include: [{
model: ctx.model.EntryItems,
as: 'items',
required: false,
attributes: [ 'id', 'item_code', 'stock_id', 'count', 'received_quantity', 'inventory_type' ],
}],
});
if (!entryOrder) {
throw new Error(`入库单不存在:${entryOrderId}`);
}
// 2. 加载收货单及其明细
const receivingOrder = await ctx.model.Receiving.findOne({
where: { id: receivingId, is_deleted: false },
include: [{
model: ctx.model.ReceivingDetail,
as: 'details',
required: false,
attributes: [
'id', 'system_product_id', 'product_name', 'actual_quantity',
'storage_status', 'stored_quantity',
],
}],
});
if (!receivingOrder) {
throw new Error(`收货单不存在:${receivingId}`);
}
// 3. 校验同仓库
if (entryOrder.warehouse_id !== receivingOrder.warehouse_id) {
throw new Error(
`入库单仓库(${entryOrder.warehouse_id})与收货单仓库(${receivingOrder.warehouse_id})不一致`
);
}
// 4. 构建入库单明细
const entryItems = (entryOrder.items || []).map(item => ({
stockId: item.stock_id,
itemCode: item.item_code,
count: item.count || 0,
receivedQuantity: item.received_quantity || 0,
inventoryType: item.inventory_type || 'ZP',
}));
// 5. 构建收货单明细
const receivingPlain = typeof receivingOrder.toJSON === 'function'
? receivingOrder.toJSON()
: receivingOrder;
const receivingDetails = (receivingPlain.details || []).map(d => ({
id: d.id,
system_product_id: d.system_product_id,
product_name: d.product_name,
actual_quantity: d.actual_quantity,
storage_status: d.storage_status,
stored_quantity: d.stored_quantity || 0,
}));
// 6. 对比明细
const comparisonResult = this._compareDetails(entryItems, receivingDetails);
const result = {
matchType: comparisonResult.type,
comparisonResult,
callbackSent: false,
callbackResult: null,
partialStorageMarked: false,
entryOrder: {
id: entryOrder.id,
entry_order_code: entryOrder.entry_order_code,
source_type: entryOrder.source_type,
warehouse_id: entryOrder.warehouse_id,
status: entryOrder.status,
},
receivingOrder: {
id: receivingOrder.id,
receiving_number: receivingOrder.receiving_number,
status: receivingOrder.status,
storage_status: receivingOrder.storage_status,
},
};
// 7. 根据对比结果处理
if (comparisonResult.type === 'full_match') {
const callbackResult = await this._sendCallback(entryOrder, receivingOrder, 'manual_match');
result.callbackSent = true;
result.callbackResult = callbackResult;
} else if (comparisonResult.type === 'receiving_covers_entry') {
const callbackResult = await this._sendCallback(entryOrder, receivingOrder, 'manual_match');
result.callbackSent = true;
result.callbackResult = callbackResult;
const markResult = await this._markReceivingPartialStorage(
receivingOrder.id,
comparisonResult,
receivingOrder.warehouse_id
);
result.partialStorageMarked = markResult.success;
}
// entry_exceeds_receiving / no_match → 不触发回传
return result;
}
}
module.exports = ReceivingEntryMatchService;