- express/express_platform: 新增 OMS 回源取号(need_oms_waybill=1)与统一失败收尾, 失败时标记订单异常、写失败日志并清理未完成占位行;队列消费与手工分配共用同一口径 - order_print: 抖音打印按运单落库的 logistics_interface_id 精确命中取号接口配置, 临时 key 缓存键带店铺与 token 指纹,避免多店铺串用 token;打印前按 OMS 记录换新 params - order_express: 新增 print_history_id、cai_niao_auth_info_id 字段 - consume_waybill_allocate_queue / pendingOrder / delivery_order / order_async / printer_data_builder / order_delivery_table_schema: 配套调整 - migrations: 运单 wave_no 索引、OMS 打印字段 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2895 lines
104 KiB
JavaScript
2895 lines
104 KiB
JavaScript
'use strict';
|
||
|
||
const MainService = require('../main');
|
||
|
||
const CREATE_CHANNEL_QM = 'QM';
|
||
const CREATE_CHANNEL_MANUAL = 'MANUAL';
|
||
const CREATE_CHANNEL_API = 'API';
|
||
const CREATE_CHANNEL_STOCKOUT = 'STOCKOUT';
|
||
const RETRYABLE_DATABASE_ERROR_CODES = new Set([ 1205, 1213, 'ER_LOCK_WAIT_TIMEOUT', 'ER_LOCK_DEADLOCK' ]);
|
||
const TRANSACTION_LOCK_RETRY_MAX_ATTEMPTS = 3;
|
||
const TRANSACTION_LOCK_RETRY_BASE_DELAY_MS = 50;
|
||
const DISPATCH_BATCH_SIZE = 20;
|
||
const SYNC_ORDER_IDS_PROGRESS_CACHE_TTL = 7200;
|
||
|
||
// 订单同步通知合并去抖:最后一次同步后等待 3 分钟无新同步,再统一推送一条消息
|
||
const ORDER_SYNC_NOTICE_DEBOUNCE_MS = 3 * 60 * 1000;
|
||
const ORDER_SYNC_NOTICE_RETRY_MS = 2 * 60 * 1000;
|
||
const ORDER_SYNC_NOTICE_MAX_RETRIES = 5;
|
||
const ORDER_SYNC_NOTICE_KEY_PREFIX = 'order_sync_notice';
|
||
const ORDER_SYNC_NOTICE_FLUSH_BATCH_SIZE = 50;
|
||
const ORDER_SYNC_NOTICE_MAX_ORDER_LINES = 30;
|
||
const ORDER_SYNC_NOTICE_LIST_TTL_SECONDS = 24 * 60 * 60;
|
||
const ORDER_SYNC_NOTICE_LOCK_TTL_SECONDS = 120;
|
||
|
||
function getSyncOrderIdsProgressCacheKey(requestId) {
|
||
if (!requestId) return null;
|
||
return `order:pending:sync_order_ids:request:${String(requestId).trim()}`;
|
||
}
|
||
|
||
async function updateDispatchBatchProgress(service, cacheKey, batchSize) {
|
||
if (!cacheKey || !service || !service.app) return;
|
||
try {
|
||
const cached = await service.app.getCacheAsync(cacheKey);
|
||
if (cached && typeof cached === 'object') {
|
||
const total = Number(cached.total_count || 0);
|
||
const processed = Number(cached.processed_count || 0) + Number(batchSize || 0);
|
||
await service.app.setCacheAsync(cacheKey, {
|
||
...cached,
|
||
processed_count: processed,
|
||
progress: total > 0 ? Math.min(100, Math.round(processed / total * 100)) : 0,
|
||
update_time: Date.now(),
|
||
}, SYNC_ORDER_IDS_PROGRESS_CACHE_TTL);
|
||
}
|
||
} catch (err) {
|
||
// 进度更新失败不影响主流程
|
||
}
|
||
}
|
||
|
||
function normalizeDatabaseErrorCodeInternal(error) {
|
||
const code = error && (error.code
|
||
|| (error.parent && error.parent.code)
|
||
|| error.errno
|
||
|| (error.parent && error.parent.errno)
|
||
|| null);
|
||
|
||
return typeof code === 'number' ? code : String(code || '').trim() || null;
|
||
}
|
||
|
||
function isRetryableTransactionLockErrorInternal(error) {
|
||
const code = normalizeDatabaseErrorCodeInternal(error);
|
||
const message = String((error && error.message) || (error && error.parent && error.parent.message) || '').toLowerCase();
|
||
|
||
return RETRYABLE_DATABASE_ERROR_CODES.has(code)
|
||
|| message.includes('deadlock found when trying to get lock')
|
||
|| message.includes('lock wait timeout');
|
||
}
|
||
|
||
async function runTransactionWithLockRetryInternal(service, tag, callback, attempt = 1) {
|
||
try {
|
||
return await service.ctx.model.transaction(async transaction => {
|
||
return await callback(transaction);
|
||
});
|
||
} catch (error) {
|
||
const retryable = isRetryableTransactionLockErrorInternal(error);
|
||
if (!retryable || attempt >= TRANSACTION_LOCK_RETRY_MAX_ATTEMPTS) {
|
||
throw error;
|
||
}
|
||
|
||
const code = normalizeDatabaseErrorCodeInternal(error) || 'UNKNOWN';
|
||
const message = String((error && error.message) || (error && error.parent && error.parent.message) || '').trim();
|
||
service.ctx.logger.warn(`[OrderAsyncService.${tag}] transaction lock retry attempt=${attempt} maxAttempts=${TRANSACTION_LOCK_RETRY_MAX_ATTEMPTS} code=${code} message=${message}`);
|
||
await new Promise(resolve => setTimeout(resolve, TRANSACTION_LOCK_RETRY_BASE_DELAY_MS * attempt));
|
||
return await runTransactionWithLockRetryInternal(service, tag, callback, attempt + 1);
|
||
}
|
||
}
|
||
|
||
function normalizeQimenResponseInternal(xmlArray) {
|
||
if (!xmlArray || typeof xmlArray !== 'object') {
|
||
return {};
|
||
}
|
||
|
||
const response = xmlArray.response || xmlArray;
|
||
if (Array.isArray(response)) {
|
||
return response[0] && typeof response[0] === 'object' ? response[0] : {};
|
||
}
|
||
|
||
return response && typeof response === 'object' ? response : {};
|
||
}
|
||
|
||
function resolveQimenSyncItemQuantityInternal(orderItem = {}) {
|
||
const actualQty = Number(orderItem.actual_qty);
|
||
if (Number.isFinite(actualQty) && actualQty > 0) {
|
||
return actualQty;
|
||
}
|
||
|
||
const planQty = Number(orderItem.plan_qty);
|
||
if (Number.isFinite(planQty) && planQty > 0) {
|
||
return planQty;
|
||
}
|
||
|
||
return 0;
|
||
}
|
||
|
||
function resolveOrderWaybillCodeInternal(orderRow = {}) {
|
||
return String(
|
||
orderRow.waybill_code
|
||
|| orderRow.express_code
|
||
|| orderRow.invoice_no
|
||
|| ''
|
||
).trim();
|
||
}
|
||
|
||
function resolveOrderWaybillCodesInternal(orderRow = {}, waybillCodes = []) {
|
||
const normalizedCodes = Array.isArray(waybillCodes)
|
||
? waybillCodes
|
||
.map(code => String(code || '').trim())
|
||
.filter(code => !!code)
|
||
: [];
|
||
|
||
if (normalizedCodes.length > 0) {
|
||
return normalizedCodes;
|
||
}
|
||
|
||
const fallbackCode = resolveOrderWaybillCodeInternal(orderRow);
|
||
return fallbackCode ? [ fallbackCode ] : [];
|
||
}
|
||
|
||
/**
|
||
* 按订单ID批量构建运单号映射。
|
||
*
|
||
* 强制同仓校验:读取 wms_order_express 必须同时带订单ID与仓库ID,
|
||
* 禁止仅凭订单ID跨仓串读运单号;仓库ID缺失时返回空映射。
|
||
*
|
||
* @param {Object} service 订单异步服务实例。
|
||
* @param {Array<number>} orderIds 订单ID列表。
|
||
* @param {number|string|null|undefined} warehouseId 仓库ID,必须为订单所属仓库。
|
||
* @return {Promise<Map<number, string[]>>} order_id 到运单号数组的映射。
|
||
*/
|
||
async function buildOrderWaybillCodeMapInternal(service, orderIds = [], warehouseId = null) {
|
||
const normalizedOrderIds = Array.isArray(orderIds)
|
||
? orderIds.map(orderId => Number(orderId)).filter(orderId => Number.isFinite(orderId) && orderId > 0)
|
||
: [];
|
||
const waybillCodeMap = new Map();
|
||
|
||
const orderExpressModel = service.ctx.model && service.ctx.model.OrderExpress;
|
||
if (!orderExpressModel || typeof orderExpressModel.findAll !== 'function' || normalizedOrderIds.length === 0) {
|
||
return waybillCodeMap;
|
||
}
|
||
|
||
const normalizedWarehouseId = warehouseId !== null && warehouseId !== undefined && warehouseId !== ''
|
||
? Number(warehouseId)
|
||
: 0;
|
||
if (!Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0) {
|
||
return waybillCodeMap;
|
||
}
|
||
|
||
const { Op } = service.app.Sequelize;
|
||
const expressRows = await orderExpressModel.findAll({
|
||
where: {
|
||
order_id: {
|
||
[Op.in]: normalizedOrderIds,
|
||
},
|
||
warehouse_id: normalizedWarehouseId,
|
||
},
|
||
attributes: [ 'order_id', 'business_key', 'waybill_code' ],
|
||
order: [[ 'id', 'ASC' ]],
|
||
raw: true,
|
||
});
|
||
|
||
for (const expressRow of Array.isArray(expressRows) ? expressRows : []) {
|
||
const orderId = Number(expressRow && expressRow.order_id);
|
||
const waybillCode = String(expressRow && expressRow.waybill_code || '').trim();
|
||
if (!Number.isFinite(orderId) || orderId <= 0 || !waybillCode) {
|
||
continue;
|
||
}
|
||
|
||
if (!waybillCodeMap.has(orderId)) {
|
||
waybillCodeMap.set(orderId, []);
|
||
}
|
||
|
||
waybillCodeMap.get(orderId).push(waybillCode);
|
||
}
|
||
|
||
return waybillCodeMap;
|
||
}
|
||
|
||
async function buildQimenDeliveryOrderConfirmDataInternal(service, orderRow, orderItems, requestContext = {}) {
|
||
const app = service.app;
|
||
const now = app.formatDate(new Date());
|
||
const firstItemOwnerCode = Array.isArray(orderItems)
|
||
? String((orderItems.find(item => item && String(item.owner_code || '').trim()) || {}).owner_code || '').trim()
|
||
: '';
|
||
const appKey = String(
|
||
requestContext.appKey
|
||
|| orderRow.from_key
|
||
|| ''
|
||
).trim();
|
||
const warehouseCodeHint = String(
|
||
requestContext.qimenWarehouseCode
|
||
|| requestContext.warehouseCode
|
||
|| orderRow.warehouse_code
|
||
|| ''
|
||
).trim();
|
||
const ownerCodeHint = String(
|
||
requestContext.customerId
|
||
|| requestContext.qimenOwnerCode
|
||
|| firstItemOwnerCode
|
||
|| ''
|
||
).trim();
|
||
let qimenContract = null;
|
||
|
||
if (appKey && ownerCodeHint && warehouseCodeHint && typeof service.findQimenAppWithContract === 'function') {
|
||
try {
|
||
qimenContract = await service.findQimenAppWithContract(appKey, ownerCodeHint, warehouseCodeHint);
|
||
} catch (error) {
|
||
service.ctx.logger.warn('[OrderAsyncService.buildQimenDeliveryOrderConfirmData] 读取奇门合同缓存失败', {
|
||
appKey,
|
||
customerId: ownerCodeHint,
|
||
warehouseCode: warehouseCodeHint,
|
||
message: error.message,
|
||
});
|
||
}
|
||
}
|
||
|
||
const ownerCode = String(
|
||
requestContext.customerId
|
||
|| requestContext.qimenOwnerCode
|
||
|| firstItemOwnerCode
|
||
|| (qimenContract && qimenContract.qimen_customer_id)
|
||
|| ''
|
||
).trim();
|
||
const warehouseCode = String(
|
||
requestContext.qimenWarehouseCode
|
||
|| requestContext.warehouseCode
|
||
|| orderRow.warehouse_code
|
||
|| (qimenContract && qimenContract.qimen_warehouse_code)
|
||
|| ''
|
||
).trim();
|
||
const packageExpressCode = String(
|
||
requestContext.packageExpressCode
|
||
|| orderRow.express_code
|
||
|| orderRow.waybill_code
|
||
|| ''
|
||
).trim();
|
||
const packageExpressCodeList = resolveOrderWaybillCodesInternal(orderRow, requestContext.packageExpressCodes);
|
||
const deliveryOrderCode = String(orderRow.delivery_order_code || '').trim();
|
||
const packageCode = String(orderRow.package_code || '').trim() || deliveryOrderCode;
|
||
const invoiceNo = String(orderRow.invoice_no || '').trim();
|
||
const orderConfirmTime = now;
|
||
const orderLines = [];
|
||
|
||
for (const orderItem of Array.isArray(orderItems) ? orderItems : []) {
|
||
const quantity = resolveQimenSyncItemQuantityInternal(orderItem);
|
||
if (quantity <= 0) {
|
||
continue;
|
||
}
|
||
|
||
orderLines.push({
|
||
orderLineNo: String(orderItem.order_line_no || '').trim() || orderLines.length + 1,
|
||
orderSourceCode: String(orderItem.source_order_code || '').trim(),
|
||
subSourceCode: String(orderItem.sub_source_order_code || '').trim(),
|
||
ownerCode: String(orderItem.owner_code || ownerCode || '').trim(),
|
||
itemCode: String(orderItem.item_code || '').trim(),
|
||
itemId: Number(orderItem.item_id) || orderItem.item_id,
|
||
itemName: String(orderItem.item_name || '').trim(),
|
||
extCode: String(orderItem.ext_code || '').trim(),
|
||
planQty: Number(orderItem.plan_qty) || 0,
|
||
actualQty: quantity,
|
||
retailPrice: Number(orderItem.retail_price) || 0,
|
||
actualPrice: Number(orderItem.actual_price) || 0,
|
||
discountAmount: String(orderItem.discount_amount || '').trim(),
|
||
inventoryType: String(orderItem.inventory_type || '').trim(),
|
||
snList: Array.isArray(orderItem.sn_list) ? orderItem.sn_list.slice() : [],
|
||
qrCode: String(orderItem.qr_code || '').trim(),
|
||
});
|
||
}
|
||
|
||
return {
|
||
ownerCode,
|
||
warehouseCode,
|
||
request: {
|
||
deliveryOrder: {
|
||
totalOrderLines: orderLines.length,
|
||
deliveryOrderCode,
|
||
deliveryOrderId: Number(orderRow.id) || undefined,
|
||
warehouseCode,
|
||
orderType: String(orderRow.order_type || '').trim(),
|
||
status: 'DELIVERED',
|
||
outBizCode: deliveryOrderCode,
|
||
confirmType: 0,
|
||
orderConfirmTime,
|
||
operatorCode: '',
|
||
operatorName: '',
|
||
storageFee: String(orderRow.storage_fee || '').trim(),
|
||
operateTime: now,
|
||
},
|
||
packages: {
|
||
package: (packageExpressCodeList.length > 0 ? packageExpressCodeList : [ packageExpressCode ])
|
||
.filter(code => String(code || '').trim())
|
||
.map(expressCode => ({
|
||
logisticsCode: String(orderRow.logistics_code || '').trim(),
|
||
logisticsName: String(orderRow.logistics_name || '').trim(),
|
||
expressCode: String(expressCode || '').trim(),
|
||
packageCode,
|
||
invoiceNo,
|
||
items: Array.isArray(orderItems) ? orderItems
|
||
.filter(item => item && Number(item.plan_qty) > 0)
|
||
.map(item => ({
|
||
itemCode: String(item.item_code || '').trim(),
|
||
itemId: Number(item.item_id) || String(item.item_id || '').trim(),
|
||
quantity: Number(item.plan_qty) || 0,
|
||
})) : [],
|
||
})),
|
||
},
|
||
orderLines,
|
||
},
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 判断货主是否开启「手工单回传通知」。
|
||
* 读取货主-仓库签约策略 policy_config.notify_manual_sync,未配置默认否。
|
||
*
|
||
* @param {object} service 服务实例。
|
||
* @param {number} warehouseId 仓库 ID。
|
||
* @param {number} storeId 货主 ID。
|
||
* @return {Promise<boolean>} true=发送通知,false=不发送通知。
|
||
*/
|
||
async function isManualSyncNoticeEnabledInternal(service, warehouseId, storeId) {
|
||
const normalizedWarehouseId = Number(warehouseId || 0);
|
||
const normalizedStoreId = Number(storeId || 0);
|
||
if (normalizedWarehouseId <= 0 || normalizedStoreId <= 0) {
|
||
return false;
|
||
}
|
||
|
||
const storeWarehouseService = service
|
||
&& service.ctx
|
||
&& service.ctx.service
|
||
&& service.ctx.service.systems
|
||
&& service.ctx.service.systems.storeWarehouse;
|
||
|
||
if (!storeWarehouseService || typeof storeWarehouseService.getContractConfig !== 'function') {
|
||
service.ctx.logger.warn('[OrderAsyncService.isManualSyncNoticeEnabled] storeWarehouse 服务不可用,按默认否处理', {
|
||
warehouseId: normalizedWarehouseId,
|
||
storeId: normalizedStoreId,
|
||
});
|
||
return false;
|
||
}
|
||
|
||
try {
|
||
const contractConfig = await storeWarehouseService.getContractConfig(normalizedWarehouseId, normalizedStoreId);
|
||
const policyConfig = contractConfig && contractConfig.policy_config;
|
||
return !!(policyConfig && Number(policyConfig.notify_manual_sync) === 1);
|
||
} catch (error) {
|
||
service.ctx.logger.warn('[OrderAsyncService.isManualSyncNoticeEnabled] 读取合约策略失败,按默认否处理: %s', String((error && error.message) || error || '').trim());
|
||
return false;
|
||
}
|
||
}
|
||
|
||
async function sendManualSyncNoticeInternal(service, syncResult = {}, context = {}) {
|
||
const rawNoticeService = service && service.ctx && service.ctx.service && service.ctx.service.systems && service.ctx.service.systems.notice;
|
||
const noticeService = rawNoticeService && typeof rawNoticeService.send === 'function'
|
||
? rawNoticeService
|
||
: (rawNoticeService && rawNoticeService.index && typeof rawNoticeService.index.send === 'function'
|
||
? rawNoticeService.index
|
||
: null);
|
||
if (!noticeService || typeof noticeService.send !== 'function') {
|
||
service.ctx.logger.error('[OrderAsyncService.sendManualSyncNotice] 通知服务不可用,通知失败', {
|
||
warehouseId: Number(context.warehouseId || syncResult.warehouse_id || 0),
|
||
orderIds: Array.isArray(syncResult.order_ids) ? syncResult.order_ids : [],
|
||
});
|
||
|
||
return {
|
||
success: false,
|
||
message: '通知服务不可用,通知失败',
|
||
data: null,
|
||
};
|
||
}
|
||
|
||
const payload = buildManualSyncNoticePayloadInternal(syncResult, context);
|
||
|
||
service.ctx.logger.info('[OrderAsyncService.sendManualSyncNotice] 调用通知服务前', {
|
||
event: payload.event,
|
||
businessName: payload.businessName,
|
||
warehouseId: payload.warehouseId,
|
||
storeId: payload.storeId,
|
||
orderIds: Array.isArray(syncResult.order_ids) ? syncResult.order_ids : [],
|
||
status: payload.metadata && payload.metadata.status,
|
||
routeState: payload.metadata && payload.metadata.route_state,
|
||
});
|
||
|
||
const noticeResult = await noticeService.send(payload);
|
||
|
||
service.ctx.logger.info('[OrderAsyncService.sendManualSyncNotice] 通知服务返回结果', {
|
||
event: payload.event,
|
||
businessName: payload.businessName,
|
||
warehouseId: payload.warehouseId,
|
||
orderIds: Array.isArray(syncResult.order_ids) ? syncResult.order_ids : [],
|
||
success: !!(noticeResult && noticeResult.success),
|
||
message: noticeResult && noticeResult.message,
|
||
data: noticeResult && noticeResult.data,
|
||
});
|
||
|
||
return noticeResult;
|
||
}
|
||
|
||
async function syncManualOrdersInternal(service, groupedOrder = {}, context = {}) {
|
||
const orderIds = Array.isArray(groupedOrder.order_ids)
|
||
? groupedOrder.order_ids.map(orderId => Number(orderId)).filter(orderId => Number.isFinite(orderId) && orderId > 0)
|
||
: [];
|
||
const warehouseId = Number(context.warehouseId || 0);
|
||
|
||
if (orderIds.length === 0) {
|
||
return {
|
||
create_channel: CREATE_CHANNEL_MANUAL,
|
||
order_ids: [],
|
||
order_count: 0,
|
||
warehouse_id: warehouseId,
|
||
handler: 'syncManualOrders',
|
||
sync_target: 'internal',
|
||
orders: [],
|
||
sync_results: [],
|
||
route_state: 'rejected',
|
||
status: 'failed',
|
||
message: 'MANUAL 同步订单不能为空',
|
||
success_count: 0,
|
||
failed_count: 0,
|
||
};
|
||
}
|
||
|
||
if (warehouseId <= 0) {
|
||
return {
|
||
create_channel: CREATE_CHANNEL_MANUAL,
|
||
order_ids: orderIds,
|
||
order_count: Number.isFinite(Number(groupedOrder.order_count)) ? Number(groupedOrder.order_count) : orderIds.length,
|
||
warehouse_id: warehouseId,
|
||
handler: 'syncManualOrders',
|
||
sync_target: 'internal',
|
||
orders: Array.isArray(groupedOrder.orders) ? groupedOrder.orders.map(order => ({ ...order })) : [],
|
||
sync_results: [],
|
||
route_state: 'rejected',
|
||
status: 'failed',
|
||
message: '缺少仓库上下文',
|
||
success_count: 0,
|
||
failed_count: orderIds.length,
|
||
};
|
||
}
|
||
|
||
const orderModel = await service.ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId);
|
||
const orderItemsModel = await service.ctx.model.OrderItemsFactory.getCurrentModel(warehouseId);
|
||
const { Op } = service.app.Sequelize;
|
||
const orderRows = await orderModel.findAll({
|
||
where: {
|
||
id: {
|
||
[Op.in]: orderIds,
|
||
},
|
||
warehouse_id: warehouseId,
|
||
},
|
||
raw: true,
|
||
});
|
||
|
||
const orderMap = new Map();
|
||
for (const orderRow of Array.isArray(orderRows) ? orderRows : []) {
|
||
if (orderRow && Number(orderRow.id) > 0) {
|
||
// 分发前过滤:已同步完成的订单不再派发
|
||
if (String(orderRow.sync_status || '').trim() === 'fin') {
|
||
service.ctx.logger.info(`[syncManualOrders] 订单已完成同步,跳过派发 orderId=${orderRow.id}`);
|
||
continue;
|
||
}
|
||
orderMap.set(Number(orderRow.id), orderRow);
|
||
}
|
||
}
|
||
|
||
const waybillCodeMap = await buildOrderWaybillCodeMapInternal(service, orderIds, warehouseId);
|
||
|
||
// dispatch前最终去重,防止同一orderId在列表中重复导致并发双扣
|
||
const uniqueOrderIds = [ ...new Set(orderIds) ];
|
||
const progressCacheKey = getSyncOrderIdsProgressCacheKey(context.request_id);
|
||
const syncResults = [];
|
||
for (let i = 0; i < uniqueOrderIds.length; i += DISPATCH_BATCH_SIZE) {
|
||
const batch = uniqueOrderIds.slice(i, i + DISPATCH_BATCH_SIZE);
|
||
const batchResults = await Promise.all(batch.map(orderId => {
|
||
const dispathedOrderRow = orderMap.get(orderId);
|
||
if (!dispathedOrderRow) {
|
||
return { order_id: orderId, status: 'skipped', message: '订单已完成同步,跳过' };
|
||
}
|
||
return processManualOrderInternal(
|
||
service,
|
||
orderModel,
|
||
orderItemsModel,
|
||
orderId,
|
||
warehouseId,
|
||
orderMap.get(orderId),
|
||
context,
|
||
waybillCodeMap.get(orderId)
|
||
);
|
||
}));
|
||
syncResults.push(...batchResults);
|
||
await updateDispatchBatchProgress(service, progressCacheKey, batchResults.length);
|
||
}
|
||
|
||
const successCount = syncResults.filter(item => item.status === 'success').length;
|
||
const failedCount = syncResults.filter(item => item.status === 'failed').length;
|
||
const overallSuccess = failedCount === 0 && successCount === syncResults.length;
|
||
const firstFailedResult = syncResults.find(item => item.status === 'failed');
|
||
const aggregateNoticeResult = syncResults.length === 1
|
||
? syncResults[0] && syncResults[0].notice_result
|
||
: firstFailedResult && firstFailedResult.notice_result;
|
||
|
||
return {
|
||
create_channel: CREATE_CHANNEL_MANUAL,
|
||
order_ids: orderIds,
|
||
order_count: Number.isFinite(Number(groupedOrder.order_count)) ? Number(groupedOrder.order_count) : orderIds.length,
|
||
warehouse_id: warehouseId,
|
||
handler: 'syncManualOrders',
|
||
sync_target: 'internal',
|
||
orders: Array.isArray(groupedOrder.orders) ? groupedOrder.orders.map(order => ({ ...order })) : [],
|
||
sync_results: syncResults,
|
||
route_state: overallSuccess ? 'accepted' : 'rejected',
|
||
status: overallSuccess ? 'success' : 'failed',
|
||
message: overallSuccess ? 'MANUAL 同步成功' : String(firstFailedResult && firstFailedResult.message || 'MANUAL 同步失败').trim() || 'MANUAL 同步失败',
|
||
success_count: successCount,
|
||
failed_count: failedCount,
|
||
notice_result: aggregateNoticeResult,
|
||
};
|
||
}
|
||
|
||
async function markPendingExceptionInternal(service, orderModel, orderId, warehouseId, exceptionText) {
|
||
const normalizedText = String(exceptionText || '').trim() || '订单同步失败';
|
||
const orderPendingExceptionService = service.ctx.service && service.ctx.service.systems && service.ctx.service.systems.orderPendingException;
|
||
|
||
if (orderPendingExceptionService && typeof orderPendingExceptionService.markPendingException === 'function') {
|
||
try {
|
||
return await orderPendingExceptionService.markPendingException({
|
||
id: orderId,
|
||
warehouse_id: warehouseId,
|
||
exception_text: normalizedText,
|
||
});
|
||
} catch (error) {
|
||
service.ctx.logger.warn('[OrderAsyncService.markPendingException] 复用异常服务失败,回退到直接更新', {
|
||
orderId,
|
||
warehouseId,
|
||
message: error.message,
|
||
});
|
||
}
|
||
}
|
||
|
||
await orderModel.update({
|
||
inspection_status: 'error',
|
||
step: 3,
|
||
order_flag: normalizedText,
|
||
updated_at: new Date(),
|
||
}, {
|
||
where: {
|
||
id: orderId,
|
||
warehouse_id: warehouseId,
|
||
status: {
|
||
[service.app.Sequelize.Op.ne]: 'cancel',
|
||
},
|
||
},
|
||
});
|
||
|
||
return {
|
||
success: true,
|
||
exception_text: normalizedText,
|
||
order_flag: normalizedText,
|
||
};
|
||
}
|
||
|
||
async function finalizeSuccessfulQimenSyncInternal(service, orderModel, orderItemsModel, orderId, warehouseId, orderRow = null) {
|
||
const stockStoreService = service.ctx.service && service.ctx.service.systems && service.ctx.service.systems.stockStore;
|
||
|
||
if (!service.ctx.model || typeof service.ctx.model.transaction !== 'function') {
|
||
throw new Error('事务能力未初始化');
|
||
}
|
||
|
||
if (!stockStoreService || typeof stockStoreService.outbound !== 'function') {
|
||
throw new Error('库存出库服务未初始化');
|
||
}
|
||
|
||
await runTransactionWithLockRetryInternal(service, 'finalizeSuccessfulQimenSync', async transaction => {
|
||
let resolvedOrderRow = orderRow;
|
||
// 最小修复:始终执行 SELECT ... FOR UPDATE,不再因 orderRow 已传入而跳过
|
||
if (orderModel && typeof orderModel.findOne === 'function') {
|
||
resolvedOrderRow = await orderModel.findOne({
|
||
where: {
|
||
id: orderId,
|
||
warehouse_id: warehouseId,
|
||
},
|
||
attributes: [ 'id', 'delivery_order_code', 'order_type', 'source_order_codes', 'sync_status' ],
|
||
lock: transaction.LOCK.UPDATE,
|
||
raw: true,
|
||
transaction,
|
||
});
|
||
}
|
||
|
||
// 防重:如果订单已完成同步,跳过本次出库扣减
|
||
if (resolvedOrderRow && String(resolvedOrderRow.sync_status || '').trim() === 'fin') {
|
||
service.ctx.logger.info(`[order_async] 订单已完成同步,跳过重复出库 orderId=${orderId}`);
|
||
return;
|
||
}
|
||
|
||
const outboundMetaOrderId = Number(resolvedOrderRow && resolvedOrderRow.id) || Number(orderId) || null;
|
||
const outboundMetaOrderNo = String(resolvedOrderRow && resolvedOrderRow.delivery_order_code || '').trim() || null;
|
||
const freshOrderItems = await orderItemsModel.findAll({
|
||
where: {
|
||
order_id: orderId,
|
||
},
|
||
raw: true,
|
||
transaction,
|
||
});
|
||
|
||
for (const orderItem of Array.isArray(freshOrderItems) ? freshOrderItems : []) {
|
||
const itemId = Number(orderItem && orderItem.item_id);
|
||
const quantity = resolveQimenSyncItemQuantityInternal(orderItem);
|
||
|
||
if (!Number.isFinite(itemId) || itemId <= 0 || quantity <= 0) {
|
||
continue;
|
||
}
|
||
|
||
const outboundOrderItemId = Number(orderItem && (orderItem.id || orderItem.order_item_id)) || null;
|
||
const stockId = Number(orderItem && orderItem.stock_id) || 0;
|
||
const outboundResult = await stockStoreService.outbound(itemId, quantity, transaction, {
|
||
orderId: outboundMetaOrderId,
|
||
orderNo: outboundMetaOrderNo,
|
||
orderItemId: outboundOrderItemId,
|
||
sourceOrderCodes: String(resolvedOrderRow && resolvedOrderRow.source_order_codes || '').trim() || undefined,
|
||
}, { stockId: stockId > 0 ? stockId : undefined });
|
||
if (!outboundResult || outboundResult.success !== true) {
|
||
throw new Error(String(outboundResult && outboundResult.error || `订单${orderId}库存扣减失败`).trim());
|
||
}
|
||
}
|
||
|
||
await orderModel.update({
|
||
sync_status: 'fin',
|
||
inspection_status: 'padding',
|
||
step: 2,
|
||
order_flag: '',
|
||
updated_at: new Date(),
|
||
}, {
|
||
where: {
|
||
id: orderId,
|
||
warehouse_id: warehouseId,
|
||
status: {
|
||
[service.app.Sequelize.Op.ne]: 'cancel',
|
||
},
|
||
},
|
||
transaction,
|
||
});
|
||
});
|
||
}
|
||
|
||
async function processLocalChannelOrderInternal(service, createChannel, orderModel, orderItemsModel, orderId, warehouseId, orderRow) {
|
||
if (!orderRow) {
|
||
return {
|
||
order_id: orderId,
|
||
status: 'failed',
|
||
message: '发货单不存在',
|
||
};
|
||
}
|
||
|
||
try {
|
||
await runTransactionWithLockRetryInternal(service, 'processLocalChannelOrder', async transaction => {
|
||
// 防重:SELECT FOR UPDATE 锁定订单行并检查 sync_status,防止重复出库
|
||
const lockedOrderRow = await orderModel.findOne({
|
||
where: {
|
||
id: orderId,
|
||
warehouse_id: warehouseId,
|
||
},
|
||
attributes: [ 'id', 'sync_status' ],
|
||
lock: transaction.LOCK.UPDATE,
|
||
raw: true,
|
||
transaction,
|
||
});
|
||
|
||
if (lockedOrderRow && String(lockedOrderRow.sync_status || '').trim() === 'fin') {
|
||
service.ctx.logger.info(`[order_async] 订单已完成同步,跳过重复出库 orderId=${orderId}`);
|
||
return;
|
||
}
|
||
|
||
const freshOrderItems = await orderItemsModel.findAll({
|
||
where: {
|
||
order_id: orderId,
|
||
},
|
||
raw: true,
|
||
transaction,
|
||
});
|
||
|
||
for (const orderItem of Array.isArray(freshOrderItems) ? freshOrderItems : []) {
|
||
const itemId = Number(orderItem && orderItem.item_id);
|
||
const quantity = resolveQimenSyncItemQuantityInternal(orderItem);
|
||
|
||
if (!Number.isFinite(itemId) || itemId <= 0 || quantity <= 0) {
|
||
continue;
|
||
}
|
||
|
||
const outboundOrderItemId = Number(orderItem && (orderItem.id || orderItem.order_item_id)) || null;
|
||
const stockId = Number(orderItem && orderItem.stock_id) || 0;
|
||
const outboundResult = await service.ctx.service.systems.stockStore.outbound(itemId, quantity, transaction, {
|
||
orderId: Number(orderRow && orderRow.id) || Number(orderId) || null,
|
||
orderNo: String(orderRow && orderRow.delivery_order_code || '').trim() || null,
|
||
orderItemId: outboundOrderItemId,
|
||
sourceOrderCodes: String(orderRow && orderRow.source_order_codes || '').trim() || undefined,
|
||
}, { stockId: stockId > 0 ? stockId : undefined });
|
||
if (!outboundResult || outboundResult.success !== true) {
|
||
throw new Error(String(outboundResult && outboundResult.error || `订单${orderId}库存扣减失败`).trim());
|
||
}
|
||
}
|
||
|
||
await orderModel.update({
|
||
sync_status: 'fin',
|
||
inspection_status: 'padding',
|
||
step: 2,
|
||
order_flag: '',
|
||
updated_at: new Date(),
|
||
}, {
|
||
where: {
|
||
id: orderId,
|
||
warehouse_id: warehouseId,
|
||
status: {
|
||
[service.app.Sequelize.Op.ne]: 'cancel',
|
||
},
|
||
},
|
||
transaction,
|
||
});
|
||
});
|
||
|
||
return {
|
||
order_id: orderId,
|
||
delivery_order_code: String(orderRow.delivery_order_code || '').trim(),
|
||
status: 'success',
|
||
message: `${createChannel} 同步成功`,
|
||
};
|
||
} catch (error) {
|
||
await orderModel.update({
|
||
sync_status: 'error',
|
||
}, {
|
||
where: {
|
||
id: orderId,
|
||
warehouse_id: warehouseId,
|
||
},
|
||
});
|
||
|
||
await markPendingExceptionInternal(service, orderModel, orderId, warehouseId, error.message || `${createChannel} 同步后库存扣减失败`);
|
||
|
||
return {
|
||
order_id: orderId,
|
||
delivery_order_code: String(orderRow.delivery_order_code || '').trim(),
|
||
status: 'failed',
|
||
message: error.message || `${createChannel} 同步后库存扣减失败`,
|
||
error: error.message,
|
||
};
|
||
}
|
||
}
|
||
|
||
async function processManualOrderInternal(service, orderModel, orderItemsModel, orderId, warehouseId, orderRow, context = {}, waybillCodes = []) {
|
||
if (!orderRow) {
|
||
return {
|
||
order_id: orderId,
|
||
status: 'failed',
|
||
message: '发货单不存在',
|
||
};
|
||
}
|
||
|
||
const resolvedWaybillCodes = resolveOrderWaybillCodesInternal(orderRow, waybillCodes);
|
||
const noticeSyncResult = {
|
||
create_channel: CREATE_CHANNEL_MANUAL,
|
||
order_ids: [ orderId ],
|
||
order_count: 1,
|
||
delivery_order_code: String(orderRow.delivery_order_code || '').trim(),
|
||
store_id: Number(orderRow && orderRow.store_id) || 0,
|
||
waybill_code: resolvedWaybillCodes,
|
||
receiver_name: String(orderRow.name || '').trim(),
|
||
receiver_phone: String(orderRow.mobile || orderRow.tel || '').trim(),
|
||
warehouse_id: warehouseId,
|
||
handler: 'syncManualOrders',
|
||
sync_target: 'internal',
|
||
route_state: 'accepted',
|
||
status: 'success',
|
||
message: '订单同步通知已合并排队',
|
||
success_count: 1,
|
||
failed_count: 0,
|
||
};
|
||
|
||
const manualSyncNoticeEnabled = await isManualSyncNoticeEnabledInternal(
|
||
service,
|
||
warehouseId,
|
||
Number(orderRow && orderRow.store_id) || 0
|
||
);
|
||
let noticeResult;
|
||
if (!manualSyncNoticeEnabled) {
|
||
service.ctx.logger.info(`[OrderAsyncService.processManualOrder] 货主未开启手工单回传通知,跳过通知 orderId=${orderId}`);
|
||
noticeResult = {
|
||
success: true,
|
||
message: '货主未开启手工单回传通知,跳过通知',
|
||
data: {
|
||
mode: 'skipped',
|
||
warehouseId,
|
||
storeId: Number(orderRow && orderRow.store_id) || 0,
|
||
},
|
||
};
|
||
} else {
|
||
noticeResult = await enqueueOrderSyncNoticeInternal(service, noticeSyncResult, context);
|
||
}
|
||
|
||
if (!noticeResult || noticeResult.success !== true) {
|
||
const noticeMessage = String(noticeResult && noticeResult.message || '通知发送失败').trim() || '通知发送失败';
|
||
|
||
await orderModel.update({
|
||
sync_status: 'error',
|
||
}, {
|
||
where: {
|
||
id: orderId,
|
||
warehouse_id: warehouseId,
|
||
},
|
||
});
|
||
|
||
await markPendingExceptionInternal(service, orderModel, orderId, warehouseId, noticeMessage);
|
||
|
||
return {
|
||
order_id: orderId,
|
||
delivery_order_code: String(orderRow.delivery_order_code || '').trim(),
|
||
status: 'failed',
|
||
message: noticeMessage,
|
||
error: noticeMessage,
|
||
notice_result: noticeResult || {
|
||
success: false,
|
||
message: noticeMessage,
|
||
data: null,
|
||
},
|
||
};
|
||
}
|
||
|
||
const localSyncResult = await processLocalChannelOrderInternal(
|
||
service,
|
||
CREATE_CHANNEL_MANUAL,
|
||
orderModel,
|
||
orderItemsModel,
|
||
orderId,
|
||
warehouseId,
|
||
orderRow
|
||
);
|
||
|
||
return {
|
||
...localSyncResult,
|
||
notice_result: noticeResult,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 按订单货主合约反查可用的 OpenAPI 应用配置(ApiApp)。
|
||
*
|
||
* 口径与入库单回调 _sendOpenApiCallback 对齐:
|
||
* 先按 store_id + warehouse_id + auth_status=2 查 StoreWarehouse 授权关系,
|
||
* 再按 contract_id 查启用(is_enabled=1)且配置了 callback_url 的 ApiApp。
|
||
* 未找到授权关系 / 无可用 ApiApp 配置时返回 null 并记录 warn 日志。
|
||
*
|
||
* @param {Object} service 订单异步服务实例。
|
||
* @param {number|string} storeId 货主 ID。
|
||
* @param {number|string} warehouseId 仓库 ID。
|
||
* @return {Promise<Object|null>} { appKey, selfAppSecret, callbackUrl },未找到可用配置时返回 null。
|
||
*/
|
||
async function resolveOpenApiAppByStoreInternal(service, storeId, warehouseId) {
|
||
const normalizedStoreId = Number(storeId || 0);
|
||
const normalizedWarehouseId = Number(warehouseId || 0);
|
||
const storeWarehouseModel = service.ctx.model && service.ctx.model.StoreWarehouse;
|
||
const apiAppModel = service.ctx.model && service.ctx.model.ApiApp;
|
||
|
||
if (!Number.isFinite(normalizedStoreId) || normalizedStoreId <= 0
|
||
|| !Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0
|
||
|| !storeWarehouseModel || typeof storeWarehouseModel.findOne !== 'function'
|
||
|| !apiAppModel || typeof apiAppModel.findOne !== 'function') {
|
||
service.ctx.logger.warn('[OrderAsyncService.resolveOpenApiAppByStore] 缺少货主/仓库上下文或数据模型不可用,无法反查 ApiApp', {
|
||
storeId: normalizedStoreId,
|
||
warehouseId: normalizedWarehouseId,
|
||
});
|
||
return null;
|
||
}
|
||
|
||
const { Op } = service.app.Sequelize;
|
||
|
||
const storeWarehouse = await storeWarehouseModel.findOne({
|
||
where: {
|
||
store_id: normalizedStoreId,
|
||
warehouse_id: normalizedWarehouseId,
|
||
auth_status: 2,
|
||
},
|
||
attributes: [ 'id' ],
|
||
raw: true,
|
||
});
|
||
|
||
if (!storeWarehouse) {
|
||
service.ctx.logger.warn(`[OrderAsyncService] OpenAPI回调:未找到授权关系 storeId=${normalizedStoreId} warehouseId=${normalizedWarehouseId}`);
|
||
return null;
|
||
}
|
||
|
||
const apiApp = await apiAppModel.findOne({
|
||
where: {
|
||
contract_id: storeWarehouse.id,
|
||
is_enabled: 1,
|
||
callback_url: {
|
||
[Op.and]: [
|
||
{ [Op.ne]: null },
|
||
{ [Op.ne]: '' },
|
||
],
|
||
},
|
||
},
|
||
attributes: [ 'self_app_key', 'self_app_secret', 'callback_url' ],
|
||
raw: true,
|
||
});
|
||
|
||
if (!apiApp || !apiApp.callback_url) {
|
||
service.ctx.logger.warn(`[OrderAsyncService] OpenAPI回调:未找到有效ApiApp配置 storeId=${normalizedStoreId} warehouseId=${normalizedWarehouseId} contractId=${storeWarehouse.id}`);
|
||
return null;
|
||
}
|
||
|
||
return {
|
||
appKey: String(apiApp.self_app_key || '').trim(),
|
||
selfAppSecret: String(apiApp.self_app_secret || '').trim(),
|
||
callbackUrl: String(apiApp.callback_url || '').trim(),
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 将 API 渠道订单标记为同步失败(sync_status='error' + 待处理异常)。
|
||
*
|
||
* 与奇门渠道回传失败口径一致:失败不扣减库存、不置 'fin',
|
||
* 订单可被重新派发重试(分发前过滤仅跳过 'fin')。
|
||
*
|
||
* @param {Object} service 订单异步服务实例。
|
||
* @param {Object} orderModel 订单主模型。
|
||
* @param {number} orderId 订单 ID。
|
||
* @param {number} warehouseId 仓库 ID。
|
||
* @param {string} message 失败原因。
|
||
* @return {Promise<void>} 无返回值,写库失败仅记录 error 日志。
|
||
*/
|
||
async function markApiSyncFailedInternal(service, orderModel, orderId, warehouseId, message) {
|
||
try {
|
||
await orderModel.update({
|
||
sync_status: 'error',
|
||
}, {
|
||
where: {
|
||
id: orderId,
|
||
warehouse_id: warehouseId,
|
||
},
|
||
});
|
||
} catch (error) {
|
||
service.ctx.logger.error(`[OrderAsyncService.markApiSyncFailed] 更新 sync_status=error 失败 orderId=${orderId}`, {
|
||
message: String((error && error.message) || error || '').trim(),
|
||
});
|
||
}
|
||
|
||
try {
|
||
await markPendingExceptionInternal(service, orderModel, orderId, warehouseId, message);
|
||
} catch (error) {
|
||
service.ctx.logger.error(`[OrderAsyncService.markApiSyncFailed] 标记待处理异常失败 orderId=${orderId}`, {
|
||
message: String((error && error.message) || error || '').trim(),
|
||
});
|
||
}
|
||
}
|
||
|
||
/**
|
||
* API 渠道单订单同步:先回传 deliveryorder.confirm,回调成功后才本地扣减库存并置已同步。
|
||
*
|
||
* 与奇门渠道(processQmOrderInternal)口径对齐:
|
||
* ① 组装与奇门 taobao.qimen.deliveryorder.confirm 完全一致的 request 报文
|
||
* (缺奇门货主编码等组装数据时直接失败);
|
||
* ② 解析发送用 appKey:context.appKey 优先,其次订单来源键 from_key(与回 OMS 取号同口径,
|
||
* 从哪里来回哪里去),都缺失时按订单货主合约反查 ApiApp
|
||
* (同一批次按货主缓存,N 单 / M 货主 → 2M 次查询,无 N+1);
|
||
* API(OMS) 渠道的 deliveryorder.confirm 不校验 ownerCode,故不再要求奇门货主编码;
|
||
* ③ 发送回调(sendByAppKey,内部最多 4 次尝试),成功才算平台已确认;
|
||
* ④ 回调成功 → 扣减库存 + sync_status='fin';失败/异常 → sync_status='error'
|
||
* + 待处理异常,不扣减库存,可重新派发;
|
||
* 订单/回调配置缺失(无 store_id、无「启用且 callback_url 非空」的 ApiApp)按失败处理,
|
||
* 不再静默跳过,避免订单在平台未确认时被置为已同步。
|
||
*
|
||
* @param {Object} service 订单异步服务实例。
|
||
* @param {Object} orderModel 订单主模型。
|
||
* @param {Object} orderItemsModel 订单明细模型。
|
||
* @param {number} orderId 订单 ID。
|
||
* @param {number} warehouseId 仓库 ID。
|
||
* @param {Object} orderRow 订单主表记录。
|
||
* @param {Array<Object>} orderItems 订单明细记录。
|
||
* @param {Object} [context] 同步上下文(appKey 可选)。
|
||
* @param {Array<string>} [waybillCodes] 运单号列表。
|
||
* @param {Map<number, Object>} [appByStoreCache] 货主 → ApiApp 反查结果缓存(批内共享)。
|
||
* @return {Promise<Object>} 单订单同步结果(status / message / error 等)。
|
||
*/
|
||
async function processApiOrderInternal(service, orderModel, orderItemsModel, orderId, warehouseId, orderRow, orderItems, context = {}, waybillCodes = [], appByStoreCache = new Map()) {
|
||
if (!orderRow) {
|
||
return {
|
||
order_id: orderId,
|
||
status: 'failed',
|
||
message: '发货单不存在',
|
||
};
|
||
}
|
||
|
||
const deliveryOrderCode = String(orderRow.delivery_order_code || '').trim();
|
||
|
||
/**
|
||
* 统一失败出口:写 sync_status='error' + 待处理异常后返回失败结果。
|
||
* @param {string} message 失败原因。
|
||
* @param {Object} [extra] 附加返回字段。
|
||
* @return {Promise<Object>} 单订单失败结果。
|
||
*/
|
||
const failSync = async (message, extra = {}) => {
|
||
await markApiSyncFailedInternal(service, orderModel, orderId, warehouseId, message);
|
||
|
||
return {
|
||
order_id: orderId,
|
||
delivery_order_code: deliveryOrderCode,
|
||
status: 'failed',
|
||
message,
|
||
error: message,
|
||
...extra,
|
||
};
|
||
};
|
||
|
||
try {
|
||
// ① 组装回调报文
|
||
const requestData = await buildQimenDeliveryOrderConfirmDataInternal(service, orderRow, orderItems, {
|
||
...context,
|
||
packageExpressCode: Array.isArray(waybillCodes) ? waybillCodes[0] : '',
|
||
packageExpressCodes: waybillCodes,
|
||
});
|
||
|
||
if (!requestData || !requestData.request) {
|
||
service.ctx.logger.warn(`[OrderAsyncService.processApiOrder] 回调报文组装数据缺失 orderId=${orderId}`, {
|
||
deliveryOrderCode,
|
||
ownerCode: requestData && requestData.ownerCode,
|
||
});
|
||
|
||
return await failSync('发货单回传报文组装失败');
|
||
}
|
||
|
||
// ② 解析发送用 appKey:按订单来源键(from_key)回原通道,与回 OMS 取号口径一致。
|
||
// API(OMS) 渠道的 deliveryorder.confirm 不校验 ownerCode,故不再要求奇门货主编码。
|
||
const callbackService = service.ctx.service.openapi && service.ctx.service.openapi.callback;
|
||
if (!callbackService || typeof callbackService.sendByAppKey !== 'function') {
|
||
return await failSync('OpenAPI 回调服务未初始化');
|
||
}
|
||
|
||
const orderFromKey = String(orderRow.from_key || '').trim();
|
||
let resolvedAppKey = String(context.appKey || orderFromKey).trim();
|
||
if (!resolvedAppKey) {
|
||
const storeId = Number(orderRow.store_id) || 0;
|
||
if (storeId <= 0) {
|
||
service.ctx.logger.warn(`[OrderAsyncService.processApiOrder] 订单缺少货主 store_id orderId=${orderId}`, {
|
||
deliveryOrderCode,
|
||
});
|
||
|
||
return await failSync('发货单缺少货主 store_id,无法解析回传用 appKey');
|
||
}
|
||
|
||
if (!appByStoreCache.has(storeId)) {
|
||
appByStoreCache.set(storeId, await resolveOpenApiAppByStoreInternal(service, storeId, warehouseId));
|
||
}
|
||
|
||
const resolvedApp = appByStoreCache.get(storeId);
|
||
resolvedAppKey = String(resolvedApp && resolvedApp.appKey || '').trim();
|
||
|
||
if (!resolvedAppKey) {
|
||
service.ctx.logger.warn(`[OrderAsyncService.processApiOrder] 货主无可用 ApiApp 配置 orderId=${orderId} storeId=${storeId}`, {
|
||
deliveryOrderCode,
|
||
});
|
||
|
||
return await failSync('货主未配置可用的 OpenAPI 回调(wms_api_app 启用且 callback_url 非空)');
|
||
}
|
||
}
|
||
|
||
// ③ 发送回调:回调成功才继续本地出库扣减
|
||
let callbackResult = null;
|
||
try {
|
||
callbackResult = await callbackService.sendByAppKey({
|
||
appKey: resolvedAppKey,
|
||
event: 'deliveryorder.confirm',
|
||
request: requestData.request,
|
||
});
|
||
} catch (error) {
|
||
const message = `OpenAPI 回调确认异常: ${String((error && error.message) || error || '').trim() || '未知错误'}`;
|
||
|
||
service.ctx.logger.error(`[OrderAsyncService.processApiOrder] deliveryorder.confirm 回调异常 orderId=${orderId}`, {
|
||
appKey: resolvedAppKey,
|
||
deliveryOrderCode,
|
||
message,
|
||
});
|
||
|
||
return await failSync(message);
|
||
}
|
||
|
||
if (!callbackResult || callbackResult.success !== true) {
|
||
const callbackRetryCount = Number(callbackResult && callbackResult.retryCount) || 0;
|
||
const message = `OpenAPI 回调确认失败: ${String((callbackResult && callbackResult.error) || '回调失败').trim()}`;
|
||
|
||
service.ctx.logger.error(`[OrderAsyncService.processApiOrder] deliveryorder.confirm 回调失败 orderId=${orderId}`, {
|
||
appKey: resolvedAppKey,
|
||
deliveryOrderCode,
|
||
retryCount: callbackRetryCount,
|
||
error: callbackResult && callbackResult.error,
|
||
});
|
||
|
||
return await failSync(message, {
|
||
callback_retry_count: callbackRetryCount,
|
||
});
|
||
}
|
||
|
||
service.ctx.logger.info(`[OrderAsyncService.processApiOrder] deliveryorder.confirm 回调成功,开始本地出库扣减 orderId=${orderId}`, {
|
||
appKey: resolvedAppKey,
|
||
deliveryOrderCode,
|
||
retryCount: Number(callbackResult.retryCount) || 0,
|
||
});
|
||
|
||
// ④ 回调成功 → 扣减库存 + 置 sync_status='fin'
|
||
const localSyncResult = await processLocalChannelOrderInternal(
|
||
service,
|
||
CREATE_CHANNEL_API,
|
||
orderModel,
|
||
orderItemsModel,
|
||
orderId,
|
||
warehouseId,
|
||
orderRow
|
||
);
|
||
|
||
return {
|
||
...localSyncResult,
|
||
callback_retry_count: Number(callbackResult.retryCount) || 0,
|
||
};
|
||
} catch (error) {
|
||
const message = `API 渠道同步异常: ${String((error && error.message) || error || '').trim() || '未知错误'}`;
|
||
|
||
service.ctx.logger.error(`[OrderAsyncService.processApiOrder] 同步异常 orderId=${orderId}`, {
|
||
deliveryOrderCode,
|
||
message,
|
||
});
|
||
|
||
return await failSync(message);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 本地渠道(MANUAL / API)订单同步收尾:
|
||
* MANUAL:逐单锁定扣减库存并置 sync_status='fin';
|
||
* API:逐单先回传 deliveryorder.confirm,回调成功后才扣减库存并置 'fin',
|
||
* 回调失败/无可用回调配置则 sync_status='error' + 待处理异常(与奇门渠道口径一致),
|
||
* 最后统计成功/失败数量返回。
|
||
*
|
||
* @param {Object} service 订单异步服务实例。
|
||
* @param {string} createChannel 创建渠道(MANUAL / API)。
|
||
* @param {Object} [groupedOrder] 分组后的订单(含 order_ids / order_count / orders)。
|
||
* @param {Object} [context] 同步上下文(含 warehouseId / request_id;appKey 可选,缺失时按订单货主合约反查)。
|
||
* @param {string} [syncTarget] 同步目标(internal / api)。
|
||
* @return {Promise<Object>} 同步结果(含 success_count / failed_count / sync_results 等)。
|
||
*/
|
||
async function finalizeLocalChannelOrdersInternal(service, createChannel, groupedOrder = {}, context = {}, syncTarget = 'internal') {
|
||
const orderIds = Array.isArray(groupedOrder.order_ids)
|
||
? groupedOrder.order_ids.map(orderId => Number(orderId)).filter(orderId => Number.isFinite(orderId) && orderId > 0)
|
||
: [];
|
||
const warehouseId = Number(context.warehouseId || 0);
|
||
|
||
if (orderIds.length === 0) {
|
||
return {
|
||
create_channel: createChannel,
|
||
order_ids: [],
|
||
order_count: 0,
|
||
warehouse_id: warehouseId,
|
||
handler: createChannel === CREATE_CHANNEL_MANUAL ? 'syncManualOrders' : 'syncApiOrders',
|
||
sync_target: syncTarget,
|
||
orders: [],
|
||
sync_results: [],
|
||
route_state: 'rejected',
|
||
status: 'failed',
|
||
message: `${createChannel} 同步订单不能为空`,
|
||
success_count: 0,
|
||
failed_count: 0,
|
||
};
|
||
}
|
||
|
||
if (warehouseId <= 0) {
|
||
return {
|
||
create_channel: createChannel,
|
||
order_ids: orderIds,
|
||
order_count: Number.isFinite(Number(groupedOrder.order_count)) ? Number(groupedOrder.order_count) : orderIds.length,
|
||
warehouse_id: warehouseId,
|
||
handler: createChannel === CREATE_CHANNEL_MANUAL ? 'syncManualOrders' : 'syncApiOrders',
|
||
sync_target: syncTarget,
|
||
orders: Array.isArray(groupedOrder.orders) ? groupedOrder.orders.map(order => ({ ...order })) : [],
|
||
sync_results: [],
|
||
route_state: 'rejected',
|
||
status: 'failed',
|
||
message: '缺少仓库上下文',
|
||
success_count: 0,
|
||
failed_count: orderIds.length,
|
||
};
|
||
}
|
||
|
||
const orderModel = await service.ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId);
|
||
const orderItemsModel = await service.ctx.model.OrderItemsFactory.getCurrentModel(warehouseId);
|
||
const { Op } = service.app.Sequelize;
|
||
const [ orderRows, orderItemRows ] = await Promise.all([
|
||
orderModel.findAll({
|
||
where: {
|
||
id: {
|
||
[Op.in]: orderIds,
|
||
},
|
||
warehouse_id: warehouseId,
|
||
},
|
||
raw: true,
|
||
}),
|
||
orderItemsModel.findAll({
|
||
where: {
|
||
order_id: {
|
||
[Op.in]: orderIds,
|
||
},
|
||
},
|
||
raw: true,
|
||
}),
|
||
]);
|
||
|
||
const orderMap = new Map();
|
||
for (const orderRow of Array.isArray(orderRows) ? orderRows : []) {
|
||
if (orderRow && Number(orderRow.id) > 0) {
|
||
// 分发前过滤:已同步完成的订单不再派发
|
||
if (String(orderRow.sync_status || '').trim() === 'fin') {
|
||
service.ctx.logger.info(`[syncApiOrders] 订单已完成同步,跳过派发 orderId=${orderRow.id}`);
|
||
continue;
|
||
}
|
||
orderMap.set(Number(orderRow.id), orderRow);
|
||
}
|
||
}
|
||
|
||
// 订单明细按 order_id 建索引,供逐单回调组装奇门报文复用(与 syncQmOrdersInternal 一致)
|
||
const itemsByOrderId = new Map();
|
||
for (const orderItem of Array.isArray(orderItemRows) ? orderItemRows : []) {
|
||
const itemOrderId = Number(orderItem && orderItem.order_id);
|
||
if (!Number.isFinite(itemOrderId) || itemOrderId <= 0) {
|
||
continue;
|
||
}
|
||
|
||
if (!itemsByOrderId.has(itemOrderId)) {
|
||
itemsByOrderId.set(itemOrderId, []);
|
||
}
|
||
|
||
itemsByOrderId.get(itemOrderId).push(orderItem);
|
||
}
|
||
|
||
// API 渠道:一次性批量取运单号 + 批内共享货主 appKey 反查缓存,
|
||
// 供逐单「先回传 deliveryorder.confirm → 成功才扣减库存」复用(无逐单 N+1 查询)
|
||
const isApiChannel = createChannel === CREATE_CHANNEL_API;
|
||
const waybillCodeMap = isApiChannel
|
||
? await buildOrderWaybillCodeMapInternal(service, orderIds, warehouseId)
|
||
: new Map();
|
||
const appByStoreCache = new Map();
|
||
|
||
// dispatch前最终去重,防止同一orderId在列表中重复导致并发双扣
|
||
const uniqueOrderIds = [ ...new Set(orderIds) ];
|
||
const progressCacheKey = getSyncOrderIdsProgressCacheKey(context.request_id);
|
||
const syncResults = [];
|
||
for (let i = 0; i < uniqueOrderIds.length; i += DISPATCH_BATCH_SIZE) {
|
||
const batch = uniqueOrderIds.slice(i, i + DISPATCH_BATCH_SIZE);
|
||
const batchResults = await Promise.all(batch.map(orderId => {
|
||
const dispathedOrderRow = orderMap.get(orderId);
|
||
if (!dispathedOrderRow) {
|
||
return { order_id: orderId, status: 'skipped', message: '订单已完成同步,跳过' };
|
||
}
|
||
if (isApiChannel) {
|
||
return processApiOrderInternal(
|
||
service,
|
||
orderModel,
|
||
orderItemsModel,
|
||
orderId,
|
||
warehouseId,
|
||
dispathedOrderRow,
|
||
itemsByOrderId.get(orderId) || [],
|
||
context,
|
||
waybillCodeMap.get(orderId) || [],
|
||
appByStoreCache
|
||
);
|
||
}
|
||
return processLocalChannelOrderInternal(
|
||
service,
|
||
createChannel,
|
||
orderModel,
|
||
orderItemsModel,
|
||
orderId,
|
||
warehouseId,
|
||
orderMap.get(orderId)
|
||
);
|
||
}));
|
||
syncResults.push(...batchResults);
|
||
await updateDispatchBatchProgress(service, progressCacheKey, batchResults.length);
|
||
}
|
||
|
||
const successCount = syncResults.filter(item => item.status === 'success').length;
|
||
const failedCount = syncResults.filter(item => item.status === 'failed').length;
|
||
const overallSuccess = failedCount === 0 && successCount === syncResults.length;
|
||
|
||
return {
|
||
create_channel: createChannel,
|
||
order_ids: orderIds,
|
||
order_count: Number.isFinite(Number(groupedOrder.order_count)) ? Number(groupedOrder.order_count) : orderIds.length,
|
||
warehouse_id: warehouseId,
|
||
handler: createChannel === CREATE_CHANNEL_MANUAL ? 'syncManualOrders' : 'syncApiOrders',
|
||
sync_target: syncTarget,
|
||
orders: Array.isArray(groupedOrder.orders) ? groupedOrder.orders.map(order => ({ ...order })) : [],
|
||
sync_results: syncResults,
|
||
route_state: overallSuccess ? 'accepted' : 'rejected',
|
||
status: overallSuccess ? 'success' : 'failed',
|
||
message: overallSuccess ? `${createChannel} 同步成功` : `${createChannel} 同步失败`,
|
||
success_count: successCount,
|
||
failed_count: failedCount,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 构建出库单确认回传数据(taobao.qimen.stockout.confirm / OpenAPI 回调共用)。
|
||
*
|
||
* 快递信息取订单侧实际发货信息:物流编码优先订单 sys_logistics_code → logistics_code →
|
||
* 出库单 express_code;运单号来自 wms_order_express 表(waybillCodes)。
|
||
*
|
||
* @param {Object} service 服务实例
|
||
* @param {Object} stockoutOrder 出库单主表记录(raw)
|
||
* @param {Object} orderRow 订单主表记录(raw)
|
||
* @param {Array} stockoutItems 出库单明细(raw 数组)
|
||
* @param {Array} [waybillCodes] 运单号列表
|
||
* @return {Object} 出库单确认回传请求体
|
||
*/
|
||
function buildStockoutConfirmDataInternal(service, stockoutOrder, orderRow, stockoutItems, waybillCodes = []) {
|
||
const now = service.app.formatDate(new Date());
|
||
// STOCKOUT 渠道运单号只认 wms_order_express 表(分配快递号时写入),
|
||
// 不回退订单主表 express_code(该字段是面单号前置,不是完整运单号)
|
||
const normalizedWaybillCodes = (Array.isArray(waybillCodes) ? waybillCodes : [])
|
||
.map(code => String(code || '').trim())
|
||
.filter(code => !!code);
|
||
const expressCode = String(
|
||
orderRow.sys_logistics_code
|
||
|| orderRow.logistics_code
|
||
|| stockoutOrder.express_code
|
||
|| 'OTHER'
|
||
).trim();
|
||
const expressName = String(
|
||
orderRow.sys_logistics_name
|
||
|| orderRow.logistics_name
|
||
|| stockoutOrder.express_name
|
||
|| 'OTHER'
|
||
).trim();
|
||
const stockoutOrderCode = String(stockoutOrder.stockout_order_code || '').trim();
|
||
const packageCode = String(orderRow.package_code || '').trim() || stockoutOrderCode;
|
||
const orderLines = (Array.isArray(stockoutItems) ? stockoutItems : []).map(item => {
|
||
const planQty = Number(item.plan_qty) || 0;
|
||
const actualQty = Number(item.actual_qty) || planQty;
|
||
|
||
return {
|
||
orderLineNo: String(item.order_line_no || '').trim(),
|
||
ownerCode: String(item.owner_code || stockoutOrder.qimen_owner_code || '').trim(),
|
||
itemCode: String(item.item_code || '').trim(),
|
||
itemId: item.item_id,
|
||
itemName: String(item.item_name || '').trim(),
|
||
planQty,
|
||
actualQty,
|
||
inventoryType: String(item.inventory_type || 'ZP').trim(),
|
||
};
|
||
});
|
||
|
||
return {
|
||
deliveryOrder: {
|
||
totalOrderLines: Number(stockoutOrder.total_order_lines) || orderLines.length,
|
||
deliveryOrderCode: stockoutOrderCode,
|
||
deliveryOrderId: Number(stockoutOrder.id) || undefined,
|
||
warehouseCode: String(stockoutOrder.qimen_warehouse_code || '').trim(),
|
||
orderType: String(stockoutOrder.order_type || '').trim(),
|
||
status: 'DELIVERED',
|
||
outBizCode: stockoutOrderCode,
|
||
confirmType: 0,
|
||
orderConfirmTime: now,
|
||
operatorCode: '',
|
||
operatorName: '',
|
||
},
|
||
packages: {
|
||
package: normalizedWaybillCodes.map(waybillCode => ({
|
||
logisticsCode: expressCode,
|
||
logisticsName: expressName,
|
||
expressCode: waybillCode,
|
||
packageCode,
|
||
items: orderLines.map(line => ({
|
||
itemCode: line.itemCode,
|
||
itemId: line.itemId,
|
||
quantity: line.actualQty,
|
||
})),
|
||
})),
|
||
},
|
||
orderLines,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 通知外部出库单确认结果(按出库单 source_type 分流)。
|
||
*
|
||
* - QM:奇门 taobao.qimen.stockout.confirm,flag=success 视为成功;
|
||
* - API:OpenAPI 签名回调(event=stockout.confirm,报文为与奇门同层级的 request 节点);
|
||
* - 其他(WMS 等内部来源):无需通知外部,直接视为成功。
|
||
*
|
||
* @param {Object} service 服务实例
|
||
* @param {Object} stockoutOrder 出库单主表记录(raw)
|
||
* @param {Object} requestData 出库单确认回传请求体
|
||
* @param {Object} [context] 上下文(含 appKey)
|
||
* @return {Promise<{success: boolean, message: string}>} 通知结果
|
||
*/
|
||
async function notifyStockoutExternalInternal(service, stockoutOrder, requestData, context = {}) {
|
||
const { ctx, app } = service;
|
||
const sourceType = String(stockoutOrder.source_type || 'QM').trim().toUpperCase();
|
||
|
||
if (sourceType === 'QM') {
|
||
if (!app.qimenClient || typeof app.qimenClient.send !== 'function') {
|
||
return { success: false, message: '奇门客户端未初始化' };
|
||
}
|
||
|
||
if (!stockoutOrder.qimen_owner_code) {
|
||
return { success: false, message: '出库单缺少奇门货主编码' };
|
||
}
|
||
|
||
try {
|
||
const sendResult = await app.qimenClient.send(
|
||
'taobao.qimen.stockout.confirm',
|
||
stockoutOrder.qimen_owner_code,
|
||
requestData,
|
||
{ ctx }
|
||
);
|
||
const response = (sendResult && sendResult.xmlArray && sendResult.xmlArray.response)
|
||
? (Array.isArray(sendResult.xmlArray.response) ? sendResult.xmlArray.response[0] : sendResult.xmlArray.response)
|
||
: {};
|
||
const flag = String(response.flag || '').trim();
|
||
if (flag === 'success') {
|
||
return { success: true, message: '' };
|
||
}
|
||
|
||
return {
|
||
success: false,
|
||
message: `${response.code || ''} ${response.message || '奇门出库单确认失败'}`.trim(),
|
||
};
|
||
} catch (error) {
|
||
return { success: false, message: error.message || '奇门出库单确认异常' };
|
||
}
|
||
}
|
||
|
||
if (sourceType === 'API') {
|
||
const callbackService = ctx.service.openapi && ctx.service.openapi.callback;
|
||
const appKey = String(context.appKey || '').trim();
|
||
|
||
if (!callbackService || typeof callbackService.sendByAppKey !== 'function') {
|
||
return { success: false, message: 'OpenAPI 回调服务未初始化' };
|
||
}
|
||
|
||
if (!appKey) {
|
||
return { success: false, message: '缺少 appKey,无法回传出库单' };
|
||
}
|
||
|
||
try {
|
||
// requestData 即奇门 request 节点内容,OpenAPI 回调按同层级 request 发送
|
||
const callbackResult = await callbackService.sendByAppKey({
|
||
appKey,
|
||
event: 'stockout.confirm',
|
||
request: requestData,
|
||
});
|
||
|
||
if (callbackResult && callbackResult.success === true) {
|
||
return { success: true, message: '' };
|
||
}
|
||
|
||
return {
|
||
success: false,
|
||
message: String(callbackResult && callbackResult.error || 'OpenAPI 回传失败').trim(),
|
||
};
|
||
} catch (error) {
|
||
return { success: false, message: error.message || 'OpenAPI 回传异常' };
|
||
}
|
||
}
|
||
|
||
// WMS 等内部来源:无需通知外部
|
||
return { success: true, message: '' };
|
||
}
|
||
|
||
/**
|
||
* 出库单回传成功后的收尾:
|
||
* 同一事务内 ① 写回出库单快递信息并推进 COMPLETED/SUCCESS;
|
||
* ② 按订单明细扣减库存(outbound,自动释放订单锁定);③ 订单 sync_status=fin。
|
||
*
|
||
* @param {Object} service 服务实例
|
||
* @param {Object} orderModel 订单模型
|
||
* @param {Object} orderItemsModel 订单明细模型
|
||
* @param {number} orderId 订单ID
|
||
* @param {number} warehouseId 仓库ID
|
||
* @param {Object} stockoutOrder 出库单记录(raw)
|
||
* @param {Object} expressWriteback 出库单快递写回字段
|
||
* @param {Object} [orderRow] 订单记录(raw)
|
||
* @return {Promise<void>} 失败抛异常
|
||
*/
|
||
async function finalizeSuccessfulStockoutSyncInternal(service, orderModel, orderItemsModel, orderId, warehouseId, stockoutOrder, expressWriteback, orderRow = null) {
|
||
const stockStoreService = service.ctx.service && service.ctx.service.systems && service.ctx.service.systems.stockStore;
|
||
|
||
if (!service.ctx.model || typeof service.ctx.model.transaction !== 'function') {
|
||
throw new Error('事务能力未初始化');
|
||
}
|
||
|
||
if (!stockStoreService || typeof stockStoreService.outbound !== 'function') {
|
||
throw new Error('库存出库服务未初始化');
|
||
}
|
||
|
||
await runTransactionWithLockRetryInternal(service, 'finalizeSuccessfulStockoutSync', async transaction => {
|
||
let resolvedOrderRow = orderRow;
|
||
if (orderModel && typeof orderModel.findOne === 'function') {
|
||
resolvedOrderRow = await orderModel.findOne({
|
||
where: {
|
||
id: orderId,
|
||
warehouse_id: warehouseId,
|
||
},
|
||
attributes: [ 'id', 'delivery_order_code', 'order_type', 'source_order_codes', 'sync_status' ],
|
||
lock: transaction.LOCK.UPDATE,
|
||
raw: true,
|
||
transaction,
|
||
});
|
||
}
|
||
|
||
const stockoutUpdate = {
|
||
...expressWriteback,
|
||
order_status: 'COMPLETED',
|
||
sync_status: 'SUCCESS',
|
||
sync_message: '',
|
||
updated_at: new Date(),
|
||
};
|
||
|
||
// 防重:订单已完成同步(并发重试触发),仅补齐出库单写回后跳过扣减
|
||
if (resolvedOrderRow && String(resolvedOrderRow.sync_status || '').trim() === 'fin') {
|
||
await service.ctx.model.OrderStockout.update(stockoutUpdate, {
|
||
where: { id: stockoutOrder.id },
|
||
transaction,
|
||
});
|
||
service.ctx.logger.info(`[order_async] 订单已完成同步,跳过重复出库 orderId=${orderId}`);
|
||
return;
|
||
}
|
||
|
||
const freshOrderItems = await orderItemsModel.findAll({
|
||
where: { order_id: orderId },
|
||
raw: true,
|
||
transaction,
|
||
});
|
||
|
||
for (const orderItem of Array.isArray(freshOrderItems) ? freshOrderItems : []) {
|
||
const itemId = Number(orderItem && orderItem.item_id);
|
||
const quantity = resolveQimenSyncItemQuantityInternal(orderItem);
|
||
|
||
if (!Number.isFinite(itemId) || itemId <= 0 || quantity <= 0) {
|
||
continue;
|
||
}
|
||
|
||
const stockId = Number(orderItem && orderItem.stock_id) || 0;
|
||
const outboundResult = await stockStoreService.outbound(itemId, quantity, transaction, {
|
||
orderId: Number(resolvedOrderRow && resolvedOrderRow.id) || Number(orderId) || null,
|
||
orderNo: String(resolvedOrderRow && resolvedOrderRow.delivery_order_code || '').trim() || null,
|
||
orderItemId: Number(orderItem && (orderItem.id || orderItem.order_item_id)) || null,
|
||
sourceOrderCodes: String(resolvedOrderRow && resolvedOrderRow.source_order_codes || '').trim() || undefined,
|
||
}, { stockId: stockId > 0 ? stockId : undefined });
|
||
|
||
if (!outboundResult || outboundResult.success !== true) {
|
||
throw new Error(String(outboundResult && outboundResult.error || `订单${orderId}库存扣减失败`).trim());
|
||
}
|
||
}
|
||
|
||
// 写回出库单快递信息 + 状态推进
|
||
await service.ctx.model.OrderStockout.update(stockoutUpdate, {
|
||
where: { id: stockoutOrder.id },
|
||
transaction,
|
||
});
|
||
|
||
await orderModel.update({
|
||
sync_status: 'fin',
|
||
inspection_status: 'padding',
|
||
step: 2,
|
||
order_flag: '',
|
||
updated_at: new Date(),
|
||
}, {
|
||
where: {
|
||
id: orderId,
|
||
warehouse_id: warehouseId,
|
||
status: {
|
||
[service.app.Sequelize.Op.ne]: 'cancel',
|
||
},
|
||
},
|
||
transaction,
|
||
});
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 单个 STOCKOUT 订单回传处理:
|
||
* 反查出库单 → 收集订单实际快递信息 → 通知外部 → 成功后写回出库单并扣库存完成同步;
|
||
* 失败时订单 sync_status=error 并标记待处理异常,出库单 sync_status=FAILED 记录失败原因。
|
||
*
|
||
* @param {Object} service 服务实例
|
||
* @param {Object} orderModel 订单模型
|
||
* @param {Object} orderItemsModel 订单明细模型
|
||
* @param {number} orderId 订单ID
|
||
* @param {number} warehouseId 仓库ID
|
||
* @param {Object} orderRow 订单记录(raw)
|
||
* @param {Array} orderItems 订单明细(raw 数组)
|
||
* @param {Object} [context] 上下文
|
||
* @param {Array} [waybillCodes] 运单号列表
|
||
* @return {Promise<Object>} 处理结果
|
||
*/
|
||
async function processStockoutOrderInternal(service, orderModel, orderItemsModel, orderId, warehouseId, orderRow, orderItems, context = {}, waybillCodes = []) {
|
||
const { ctx } = service;
|
||
const deliveryOrderCode = String(orderRow && orderRow.delivery_order_code || '').trim();
|
||
const buildFailure = (message, extra = {}) => ({
|
||
order_id: orderId,
|
||
delivery_order_code: deliveryOrderCode,
|
||
status: 'failed',
|
||
message,
|
||
...extra,
|
||
});
|
||
|
||
if (!orderRow) {
|
||
return buildFailure('发货单不存在');
|
||
}
|
||
|
||
// 反查出库单:订单 source_order_codes 的首个来源单号(转订单时为出库单号),
|
||
// 兜底取订单明细 source_order_code
|
||
const sourceOrderCodes = String(orderRow.source_order_codes || '')
|
||
.split(',')
|
||
.map(code => String(code || '').trim())
|
||
.filter(code => !!code);
|
||
const sourceItem = Array.isArray(orderItems)
|
||
? orderItems.find(item => item && String(item.source_order_code || '').trim())
|
||
: null;
|
||
const itemSourceOrderCode = String(sourceItem && sourceItem.source_order_code || '').trim();
|
||
const stockoutOrderCode = String(sourceOrderCodes[0] || itemSourceOrderCode || '').trim();
|
||
|
||
if (!stockoutOrderCode) {
|
||
const message = '出库单转订单回传失败:未找到订单来源出库单号';
|
||
await markPendingExceptionInternal(service, orderModel, orderId, warehouseId, message);
|
||
return buildFailure(message);
|
||
}
|
||
|
||
const stockoutOrder = await ctx.model.OrderStockout.findOne({
|
||
where: {
|
||
stockout_order_code: stockoutOrderCode,
|
||
warehouse_id: warehouseId,
|
||
deleted_at: null,
|
||
},
|
||
raw: true,
|
||
});
|
||
|
||
if (!stockoutOrder) {
|
||
const message = `出库单转订单回传失败:出库单(${stockoutOrderCode})不存在`;
|
||
await markPendingExceptionInternal(service, orderModel, orderId, warehouseId, message);
|
||
return buildFailure(message);
|
||
}
|
||
|
||
// 幂等:出库单已完成同步(并发/重试场景),跳过外部通知,直接收尾
|
||
if (String(stockoutOrder.sync_status || '').trim() === 'SUCCESS') {
|
||
service.ctx.logger.info(`[syncStockoutOrders] 出库单已完成同步,跳过通知直接收尾 stockoutOrderCode=${stockoutOrderCode}`);
|
||
try {
|
||
await finalizeSuccessfulStockoutSyncInternal(service, orderModel, orderItemsModel, orderId, warehouseId, stockoutOrder, {}, orderRow);
|
||
return {
|
||
order_id: orderId,
|
||
delivery_order_code: deliveryOrderCode,
|
||
status: 'success',
|
||
message: '出库单已同步,订单收尾完成',
|
||
};
|
||
} catch (error) {
|
||
const message = `出库单回传后收尾失败:${error.message}`;
|
||
await orderModel.update({
|
||
sync_status: 'error',
|
||
order_flag: message,
|
||
updated_at: new Date(),
|
||
}, {
|
||
where: { id: orderId, warehouse_id: warehouseId },
|
||
});
|
||
await markPendingExceptionInternal(service, orderModel, orderId, warehouseId, message);
|
||
return buildFailure(message);
|
||
}
|
||
}
|
||
|
||
// 运单号校验:订单未分配运单号时无法回传出库单
|
||
// STOCKOUT 渠道运单号只认 wms_order_express 表,不回退订单主表 express_code(面单号前置)
|
||
const normalizedWaybillCodes = (Array.isArray(waybillCodes) ? waybillCodes : [])
|
||
.map(code => String(code || '').trim())
|
||
.filter(code => !!code);
|
||
if (normalizedWaybillCodes.length === 0) {
|
||
const message = '出库单转订单回传失败:订单未分配运单号';
|
||
await orderModel.update({
|
||
sync_status: 'error',
|
||
order_flag: message,
|
||
updated_at: new Date(),
|
||
}, {
|
||
where: { id: orderId, warehouse_id: warehouseId },
|
||
});
|
||
await markPendingExceptionInternal(service, orderModel, orderId, warehouseId, message);
|
||
return buildFailure(message);
|
||
}
|
||
|
||
const stockoutItems = await ctx.model.OrderStockoutItems.findAll({
|
||
where: { order_id: stockoutOrder.id },
|
||
order: [[ 'id', 'ASC' ]],
|
||
raw: true,
|
||
});
|
||
|
||
// 快递信息写回字段(回传成功落库):物流编码/名称 + 运单号列表(复数为准,单数为镜像)
|
||
const expressWriteback = {
|
||
waybill_code: normalizedWaybillCodes[0] || '',
|
||
waybill_codes: normalizedWaybillCodes,
|
||
express_code: String(
|
||
orderRow.sys_logistics_code
|
||
|| orderRow.logistics_code
|
||
|| stockoutOrder.express_code
|
||
|| ''
|
||
).trim(),
|
||
express_name: String(
|
||
orderRow.sys_logistics_name
|
||
|| orderRow.logistics_name
|
||
|| stockoutOrder.express_name
|
||
|| ''
|
||
).trim(),
|
||
};
|
||
|
||
// 通知外部(奇门 stockout.confirm / OpenAPI 回调,按出库单 source_type 分流)
|
||
const requestData = buildStockoutConfirmDataInternal(service, stockoutOrder, orderRow, stockoutItems, normalizedWaybillCodes);
|
||
const notifyResult = await notifyStockoutExternalInternal(service, stockoutOrder, requestData, {
|
||
...context,
|
||
appKey: String(context.appKey || orderRow.from_key || '').trim(),
|
||
});
|
||
|
||
if (!notifyResult || notifyResult.success !== true) {
|
||
const message = `出库单转订单回传失败:${String(notifyResult && notifyResult.message || '通知外部失败').trim()}`;
|
||
await orderModel.update({
|
||
sync_status: 'error',
|
||
order_flag: message,
|
||
updated_at: new Date(),
|
||
}, {
|
||
where: { id: orderId, warehouse_id: warehouseId },
|
||
});
|
||
await ctx.model.OrderStockout.update({
|
||
sync_status: 'FAILED',
|
||
sync_message: message,
|
||
updated_at: new Date(),
|
||
}, {
|
||
where: { id: stockoutOrder.id },
|
||
});
|
||
await markPendingExceptionInternal(service, orderModel, orderId, warehouseId, message);
|
||
return buildFailure(message);
|
||
}
|
||
|
||
try {
|
||
await finalizeSuccessfulStockoutSyncInternal(
|
||
service,
|
||
orderModel,
|
||
orderItemsModel,
|
||
orderId,
|
||
warehouseId,
|
||
stockoutOrder,
|
||
expressWriteback,
|
||
orderRow
|
||
);
|
||
} catch (error) {
|
||
const message = `出库单回传后库存扣减失败:${error.message}`;
|
||
await orderModel.update({
|
||
sync_status: 'error',
|
||
order_flag: message,
|
||
updated_at: new Date(),
|
||
}, {
|
||
where: { id: orderId, warehouse_id: warehouseId },
|
||
});
|
||
await markPendingExceptionInternal(service, orderModel, orderId, warehouseId, message);
|
||
return buildFailure(message);
|
||
}
|
||
|
||
service.ctx.logger.info(`[syncStockoutOrders] 出库单回传成功 stockoutOrderCode=${stockoutOrderCode} orderId=${orderId}`);
|
||
|
||
return {
|
||
order_id: orderId,
|
||
delivery_order_code: deliveryOrderCode,
|
||
status: 'success',
|
||
message: '出库单回传成功',
|
||
};
|
||
}
|
||
|
||
/**
|
||
* STOCKOUT 创建渠道订单同步入口。
|
||
*
|
||
* 从待处理订单同步入口(syncOrderIds)按 create_channel 分组路由到本函数:
|
||
* 反查对应出库单,把订单实际快递编码/运单号写回出库单并通知外部
|
||
* (QM→奇门 stockout.confirm,API→OpenAPI 回调),成功后才扣减库存完成同步。
|
||
*
|
||
* @param {Object} service 服务实例
|
||
* @param {Object} groupedOrder 分组后的订单
|
||
* @param {Object} context 上下文
|
||
* @return {Promise<Object>} 同步结果
|
||
*/
|
||
async function syncStockoutOrdersInternal(service, groupedOrder = {}, context = {}) {
|
||
const orderIds = Array.isArray(groupedOrder.order_ids)
|
||
? groupedOrder.order_ids.map(orderId => Number(orderId)).filter(orderId => Number.isFinite(orderId) && orderId > 0)
|
||
: [];
|
||
const warehouseId = Number(context.warehouseId || 0);
|
||
|
||
if (orderIds.length === 0) {
|
||
return {
|
||
create_channel: CREATE_CHANNEL_STOCKOUT,
|
||
order_ids: [],
|
||
order_count: 0,
|
||
warehouse_id: warehouseId,
|
||
handler: 'syncStockoutOrders',
|
||
sync_target: 'stockout',
|
||
orders: [],
|
||
sync_results: [],
|
||
route_state: 'rejected',
|
||
status: 'failed',
|
||
message: 'STOCKOUT 同步订单不能为空',
|
||
success_count: 0,
|
||
failed_count: 0,
|
||
};
|
||
}
|
||
|
||
if (warehouseId <= 0) {
|
||
return {
|
||
create_channel: CREATE_CHANNEL_STOCKOUT,
|
||
order_ids: orderIds,
|
||
order_count: Number.isFinite(Number(groupedOrder.order_count)) ? Number(groupedOrder.order_count) : orderIds.length,
|
||
warehouse_id: warehouseId,
|
||
handler: 'syncStockoutOrders',
|
||
sync_target: 'stockout',
|
||
orders: Array.isArray(groupedOrder.orders) ? groupedOrder.orders.map(order => ({ ...order })) : [],
|
||
sync_results: [],
|
||
route_state: 'rejected',
|
||
status: 'failed',
|
||
message: '缺少仓库上下文',
|
||
success_count: 0,
|
||
failed_count: orderIds.length,
|
||
};
|
||
}
|
||
|
||
const orderModel = await service.ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId);
|
||
const orderItemsModel = await service.ctx.model.OrderItemsFactory.getCurrentModel(warehouseId);
|
||
const { Op } = service.app.Sequelize;
|
||
const [ orderRows, orderItemRows ] = await Promise.all([
|
||
orderModel.findAll({
|
||
where: {
|
||
id: {
|
||
[Op.in]: orderIds,
|
||
},
|
||
warehouse_id: warehouseId,
|
||
},
|
||
raw: true,
|
||
}),
|
||
orderItemsModel.findAll({
|
||
where: {
|
||
order_id: {
|
||
[Op.in]: orderIds,
|
||
},
|
||
},
|
||
raw: true,
|
||
}),
|
||
]);
|
||
|
||
const orderMap = new Map();
|
||
for (const orderRow of Array.isArray(orderRows) ? orderRows : []) {
|
||
if (orderRow && Number(orderRow.id) > 0) {
|
||
if (String(orderRow.sync_status || '').trim() === 'fin') {
|
||
service.ctx.logger.info(`[syncStockoutOrders] 订单已完成同步,跳过派发 orderId=${orderRow.id}`);
|
||
continue;
|
||
}
|
||
orderMap.set(Number(orderRow.id), orderRow);
|
||
}
|
||
}
|
||
|
||
const waybillCodeMap = await buildOrderWaybillCodeMapInternal(service, orderIds, warehouseId);
|
||
|
||
const itemsByOrderId = new Map();
|
||
for (const orderItem of Array.isArray(orderItemRows) ? orderItemRows : []) {
|
||
const itemOrderId = Number(orderItem && orderItem.order_id);
|
||
if (!Number.isFinite(itemOrderId) || itemOrderId <= 0) {
|
||
continue;
|
||
}
|
||
|
||
if (!itemsByOrderId.has(itemOrderId)) {
|
||
itemsByOrderId.set(itemOrderId, []);
|
||
}
|
||
|
||
itemsByOrderId.get(itemOrderId).push(orderItem);
|
||
}
|
||
|
||
const progressCacheKey = getSyncOrderIdsProgressCacheKey(context.request_id);
|
||
const uniqueOrderIds = [ ...new Set(orderIds) ];
|
||
const syncResults = [];
|
||
for (let i = 0; i < uniqueOrderIds.length; i += DISPATCH_BATCH_SIZE) {
|
||
const batch = uniqueOrderIds.slice(i, i + DISPATCH_BATCH_SIZE);
|
||
const batchResults = await Promise.all(batch.map(orderId => {
|
||
const dispatchedOrderRow = orderMap.get(orderId);
|
||
if (!dispatchedOrderRow) {
|
||
service.ctx.logger.info(`[syncStockoutOrders] 订单已过滤,跳过 orderId=${orderId}`);
|
||
return { order_id: orderId, status: 'skipped', message: '订单已完成同步,跳过' };
|
||
}
|
||
|
||
return processStockoutOrderInternal(
|
||
service,
|
||
orderModel,
|
||
orderItemsModel,
|
||
orderId,
|
||
warehouseId,
|
||
dispatchedOrderRow,
|
||
itemsByOrderId.get(orderId) || [],
|
||
context,
|
||
waybillCodeMap.get(orderId)
|
||
);
|
||
}));
|
||
syncResults.push(...batchResults);
|
||
await updateDispatchBatchProgress(service, progressCacheKey, batchResults.length);
|
||
}
|
||
|
||
const successCount = syncResults.filter(item => item.status === 'success').length;
|
||
const failedCount = syncResults.filter(item => item.status === 'failed').length;
|
||
const overallSuccess = failedCount === 0 && successCount === syncResults.length;
|
||
|
||
return {
|
||
create_channel: CREATE_CHANNEL_STOCKOUT,
|
||
order_ids: orderIds,
|
||
order_count: Number.isFinite(Number(groupedOrder.order_count)) ? Number(groupedOrder.order_count) : orderIds.length,
|
||
warehouse_id: warehouseId,
|
||
handler: 'syncStockoutOrders',
|
||
sync_target: 'stockout',
|
||
orders: Array.isArray(groupedOrder.orders) ? groupedOrder.orders.map(order => ({ ...order })) : [],
|
||
sync_results: syncResults,
|
||
route_state: overallSuccess ? 'accepted' : 'rejected',
|
||
status: overallSuccess ? 'success' : 'failed',
|
||
message: overallSuccess ? '出库单回传成功' : '出库单回传失败',
|
||
success_count: successCount,
|
||
failed_count: failedCount,
|
||
};
|
||
}
|
||
|
||
function buildManualSyncNoticePayloadInternal(syncResult = {}, context = {}) {
|
||
const orderIds = Array.isArray(syncResult.order_ids)
|
||
? syncResult.order_ids.map(orderId => Number(orderId)).filter(orderId => Number.isFinite(orderId) && orderId > 0)
|
||
: [];
|
||
const warehouseId = Number(context.warehouseId || syncResult.warehouse_id || 0);
|
||
const noticeStatus = String(syncResult.status || '').trim() || 'success';
|
||
const deliveryOrderCode = String(syncResult.delivery_order_code || '').trim();
|
||
const receiverName = String(syncResult.receiver_name || '').trim() || '无';
|
||
const receiverPhone = String(syncResult.receiver_phone || '').trim() || '无';
|
||
const waybillCodeList = Array.isArray(syncResult.waybill_code)
|
||
? syncResult.waybill_code.map(code => String(code || '').trim()).filter(code => !!code)
|
||
: (Array.isArray(syncResult.waybill_code_list)
|
||
? syncResult.waybill_code_list.map(code => String(code || '').trim()).filter(code => !!code)
|
||
: (String(syncResult.waybill_code || '').trim() ? [ String(syncResult.waybill_code || '').trim() ] : []));
|
||
|
||
return {
|
||
event: 'order_sync_completed',
|
||
businessName: 'order',
|
||
warehouseId,
|
||
storeId: Number(syncResult.store_id || context.storeId || context.warehouseId || 0),
|
||
subject: {
|
||
id: warehouseId,
|
||
type: 'warehouse',
|
||
},
|
||
title: '订单同步完成',
|
||
message: [
|
||
`订单${deliveryOrderCode || '无'} 姓名:${receiverName} 电话:${receiverPhone} 运单号:${waybillCodeList.length > 0 ? waybillCodeList.join(',') : '无'}`,
|
||
].join('\n'),
|
||
metadata: {
|
||
create_channel: CREATE_CHANNEL_MANUAL,
|
||
sync_target: 'internal',
|
||
order_ids: orderIds,
|
||
delivery_order_code: deliveryOrderCode,
|
||
waybill_code: waybillCodeList,
|
||
order_count: Number.isFinite(Number(syncResult.order_count)) ? Number(syncResult.order_count) : orderIds.length,
|
||
status: noticeStatus,
|
||
route_state: String(syncResult.route_state || '').trim(),
|
||
success_count: Number(syncResult.success_count || 0),
|
||
failed_count: Number(syncResult.failed_count || 0),
|
||
},
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 解析订单同步通知合并维度中的货主 ID。
|
||
* 与 buildManualSyncNoticePayloadInternal 的 storeId 取值保持一致。
|
||
*
|
||
* @param {object} syncResult 单订单同步结果。
|
||
* @param {object} context 上下文。
|
||
* @return {number} 货主 ID。
|
||
*/
|
||
function resolveOrderSyncNoticeStoreIdInternal(syncResult = {}, context = {}) {
|
||
return Number(syncResult.store_id || context.storeId || context.warehouseId || 0);
|
||
}
|
||
|
||
/**
|
||
* 生成订单同步通知合并队列的成员标识。
|
||
* 按「仓库:货主」聚合,货主售后群按货主维度订阅。
|
||
*
|
||
* @param {number} warehouseId 仓库 ID。
|
||
* @param {number} storeId 货主 ID。
|
||
* @return {string} 队列成员标识。
|
||
*/
|
||
function buildOrderSyncNoticeMemberInternal(warehouseId, storeId) {
|
||
return `${warehouseId}:${storeId}`;
|
||
}
|
||
|
||
/**
|
||
* 解析订单同步通知合并队列的成员标识。
|
||
*
|
||
* @param {string} member 队列成员标识。
|
||
* @return {Object|null} 解析结果或 null。
|
||
*/
|
||
function parseOrderSyncNoticeMemberInternal(member) {
|
||
const normalized = String(member || '').trim();
|
||
if (!normalized) {
|
||
return null;
|
||
}
|
||
|
||
const [ warehousePart, storePart ] = normalized.split(':');
|
||
const warehouseId = Number(warehousePart);
|
||
const storeId = Number(storePart);
|
||
|
||
if (!Number.isFinite(warehouseId) || warehouseId <= 0 || !Number.isFinite(storeId)) {
|
||
return null;
|
||
}
|
||
|
||
return { warehouseId, storeId };
|
||
}
|
||
|
||
/**
|
||
* 生成订单同步通知合并相关的 Redis 键集合。
|
||
*
|
||
* @param {number} warehouseId 仓库 ID。
|
||
* @param {number} storeId 货主 ID。
|
||
* @return {Object} Redis 键集合。
|
||
*/
|
||
function buildOrderSyncNoticeKeysInternal(warehouseId, storeId) {
|
||
const member = buildOrderSyncNoticeMemberInternal(warehouseId, storeId);
|
||
|
||
return {
|
||
member,
|
||
queueKey: `${ORDER_SYNC_NOTICE_KEY_PREFIX}:queue`,
|
||
listKey: `${ORDER_SYNC_NOTICE_KEY_PREFIX}:list:${member}`,
|
||
retryKey: `${ORDER_SYNC_NOTICE_KEY_PREFIX}:retry:${member}`,
|
||
lockKey: `${ORDER_SYNC_NOTICE_KEY_PREFIX}:lock:${member}`,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 获取订单同步通知合并使用的 Redis 客户端。
|
||
*
|
||
* @param {object} service 服务实例。
|
||
* @return {Object|null} Redis 客户端或 null。
|
||
*/
|
||
function getOrderSyncNoticeRedisClientInternal(service) {
|
||
if (!service || !service.app || !service.app.redis || typeof service.app.redis.get !== 'function') {
|
||
return null;
|
||
}
|
||
|
||
try {
|
||
return service.app.redis.get('cache') || null;
|
||
} catch (error) {
|
||
return null;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 把单订单同步结果构建为合并队列条目。
|
||
*
|
||
* @param {object} syncResult 单订单同步结果。
|
||
* @return {Object} 合并队列条目。
|
||
*/
|
||
function buildOrderSyncNoticeEntryInternal(syncResult = {}) {
|
||
const orderIds = Array.isArray(syncResult.order_ids)
|
||
? syncResult.order_ids.map(orderId => Number(orderId)).filter(orderId => Number.isFinite(orderId) && orderId > 0)
|
||
: [];
|
||
const waybillCodes = Array.isArray(syncResult.waybill_code)
|
||
? syncResult.waybill_code.map(code => String(code || '').trim()).filter(code => !!code)
|
||
: (Array.isArray(syncResult.waybill_code_list)
|
||
? syncResult.waybill_code_list.map(code => String(code || '').trim()).filter(code => !!code)
|
||
: (String(syncResult.waybill_code || '').trim() ? [ String(syncResult.waybill_code || '').trim() ] : []));
|
||
|
||
return {
|
||
order_id: orderIds[0] || null,
|
||
delivery_order_code: String(syncResult.delivery_order_code || '').trim(),
|
||
receiver_name: String(syncResult.receiver_name || '').trim(),
|
||
receiver_phone: String(syncResult.receiver_phone || '').trim(),
|
||
waybill_codes: waybillCodes,
|
||
enqueue_at: Date.now(),
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 解析合并队列中的原始条目。
|
||
*
|
||
* @param {*} rawEntry 原始条目。
|
||
* @return {Object|null} 解析结果或 null。
|
||
*/
|
||
function parseOrderSyncNoticeEntryInternal(rawEntry) {
|
||
if (!rawEntry) {
|
||
return null;
|
||
}
|
||
|
||
try {
|
||
const entry = typeof rawEntry === 'string' ? JSON.parse(rawEntry) : rawEntry;
|
||
if (!entry || typeof entry !== 'object') {
|
||
return null;
|
||
}
|
||
|
||
const orderId = Number(entry.order_id);
|
||
|
||
return {
|
||
order_id: Number.isFinite(orderId) && orderId > 0 ? orderId : null,
|
||
delivery_order_code: String(entry.delivery_order_code || '').trim(),
|
||
receiver_name: String(entry.receiver_name || '').trim(),
|
||
receiver_phone: String(entry.receiver_phone || '').trim(),
|
||
waybill_codes: Array.isArray(entry.waybill_codes)
|
||
? entry.waybill_codes.map(code => String(code || '').trim()).filter(code => !!code)
|
||
: [],
|
||
enqueue_at: Number(entry.enqueue_at) || null,
|
||
};
|
||
} catch (error) {
|
||
return null;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 订单同步通知入队:把单订单通知合并到 Redis 队列,
|
||
* 等待 3 分钟去抖窗口结束后由定时任务统一推送。
|
||
* Redis 不可用或入队失败时回退为立即发送(保持原有行为)。
|
||
*
|
||
* @param {object} service 服务实例。
|
||
* @param {object} syncResult 单订单同步结果。
|
||
* @param {object} context 上下文。
|
||
* @return {Promise<Object>} 入队或回退发送结果。
|
||
*/
|
||
async function enqueueOrderSyncNoticeInternal(service, syncResult = {}, context = {}) {
|
||
const warehouseId = Number(context.warehouseId || syncResult.warehouse_id || 0);
|
||
const storeId = resolveOrderSyncNoticeStoreIdInternal(syncResult, context);
|
||
const redis = getOrderSyncNoticeRedisClientInternal(service);
|
||
|
||
if (!redis) {
|
||
service.ctx.logger.warn('[OrderAsyncService.enqueueOrderSyncNotice] Redis 不可用,回退立即发送通知', {
|
||
warehouseId,
|
||
storeId,
|
||
});
|
||
|
||
return await sendManualSyncNoticeInternal(service, syncResult, context);
|
||
}
|
||
|
||
const keys = buildOrderSyncNoticeKeysInternal(warehouseId, storeId);
|
||
const entry = buildOrderSyncNoticeEntryInternal(syncResult);
|
||
|
||
try {
|
||
const dueAtSeconds = Math.floor((Date.now() + ORDER_SYNC_NOTICE_DEBOUNCE_MS) / 1000);
|
||
await redis.rpush(keys.listKey, JSON.stringify(entry));
|
||
await redis.expire(keys.listKey, ORDER_SYNC_NOTICE_LIST_TTL_SECONDS);
|
||
await redis.zadd(keys.queueKey, dueAtSeconds, keys.member);
|
||
|
||
service.ctx.logger.info('[OrderAsyncService.enqueueOrderSyncNotice] 订单同步通知已入队,等待合并推送', {
|
||
warehouseId,
|
||
storeId,
|
||
orderId: entry.order_id,
|
||
dueAt: dueAtSeconds * 1000,
|
||
});
|
||
|
||
return {
|
||
success: true,
|
||
message: '订单同步通知已合并排队,3 分钟内无新同步将统一推送',
|
||
data: {
|
||
mode: 'deferred',
|
||
warehouseId,
|
||
storeId,
|
||
due_at: dueAtSeconds * 1000,
|
||
},
|
||
};
|
||
} catch (error) {
|
||
service.ctx.logger.warn('[OrderAsyncService.enqueueOrderSyncNotice] 合并入队失败,回退立即发送通知', {
|
||
warehouseId,
|
||
storeId,
|
||
error: String((error && error.message) || error || '').trim(),
|
||
});
|
||
|
||
return await sendManualSyncNoticeInternal(service, syncResult, context);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 构建合并后的订单同步通知载荷。
|
||
*
|
||
* @param {number} warehouseId 仓库 ID。
|
||
* @param {number} storeId 货主 ID。
|
||
* @param {Object[]} entries 合并队列条目。
|
||
* @return {Object} 通知载荷。
|
||
*/
|
||
function buildConsolidatedOrderSyncNoticePayloadInternal(warehouseId, storeId, entries = []) {
|
||
const normalizedEntries = (Array.isArray(entries) ? entries : []).filter(entry => !!entry);
|
||
const orderLines = normalizedEntries.map(entry => {
|
||
const code = String(entry.delivery_order_code || '').trim() || '无';
|
||
const name = String(entry.receiver_name || '').trim() || '无';
|
||
const phone = String(entry.receiver_phone || '').trim() || '无';
|
||
const waybillList = Array.isArray(entry.waybill_codes) ? entry.waybill_codes : [];
|
||
const waybill = waybillList.length > 0 ? waybillList.join(',') : '无';
|
||
|
||
return `订单${code} 姓名:${name} 电话:${phone} 运单号:${waybill}`;
|
||
});
|
||
|
||
const shownLines = orderLines.slice(0, ORDER_SYNC_NOTICE_MAX_ORDER_LINES);
|
||
const hiddenCount = orderLines.length - shownLines.length;
|
||
const lines = [
|
||
`订单同步完成(共 ${normalizedEntries.length} 单)`,
|
||
...shownLines,
|
||
];
|
||
|
||
if (hiddenCount > 0) {
|
||
lines.push(`……其余 ${hiddenCount} 单未列出`);
|
||
}
|
||
|
||
return {
|
||
event: 'order_sync_completed',
|
||
businessName: 'order',
|
||
warehouseId,
|
||
storeId,
|
||
subject: {
|
||
id: warehouseId,
|
||
type: 'warehouse',
|
||
},
|
||
title: '订单同步完成',
|
||
message: lines.join('\n'),
|
||
metadata: {
|
||
create_channel: CREATE_CHANNEL_MANUAL,
|
||
sync_target: 'internal',
|
||
order_ids: normalizedEntries.map(entry => entry.order_id).filter(orderId => orderId),
|
||
order_count: normalizedEntries.length,
|
||
status: 'success',
|
||
route_state: 'accepted',
|
||
success_count: normalizedEntries.length,
|
||
failed_count: 0,
|
||
debounced: true,
|
||
},
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 发送合并后的订单同步通知。
|
||
*
|
||
* @param {object} service 服务实例。
|
||
* @param {number} warehouseId 仓库 ID。
|
||
* @param {number} storeId 货主 ID。
|
||
* @param {Object[]} entries 合并队列条目。
|
||
* @return {Promise<Object>} 通知服务返回结果。
|
||
*/
|
||
async function sendConsolidatedOrderSyncNoticeInternal(service, warehouseId, storeId, entries = []) {
|
||
const rawNoticeService = service && service.ctx && service.ctx.service && service.ctx.service.systems && service.ctx.service.systems.notice;
|
||
const noticeService = rawNoticeService && typeof rawNoticeService.send === 'function'
|
||
? rawNoticeService
|
||
: (rawNoticeService && rawNoticeService.index && typeof rawNoticeService.index.send === 'function'
|
||
? rawNoticeService.index
|
||
: null);
|
||
if (!noticeService || typeof noticeService.send !== 'function') {
|
||
throw new Error('通知服务不可用');
|
||
}
|
||
|
||
const payload = buildConsolidatedOrderSyncNoticePayloadInternal(warehouseId, storeId, entries);
|
||
|
||
service.ctx.logger.info('[OrderAsyncService.flushDeferredOrderSyncNotices] 合并通知发送前', {
|
||
warehouseId,
|
||
storeId,
|
||
entryCount: entries.length,
|
||
});
|
||
|
||
const noticeResult = await noticeService.send(payload);
|
||
|
||
service.ctx.logger.info('[OrderAsyncService.flushDeferredOrderSyncNotices] 合并通知发送结果', {
|
||
warehouseId,
|
||
storeId,
|
||
entryCount: entries.length,
|
||
success: !!(noticeResult && noticeResult.success),
|
||
message: noticeResult && noticeResult.message,
|
||
});
|
||
|
||
return noticeResult;
|
||
}
|
||
|
||
/**
|
||
* 处理合并通知发送失败:放回队列并按重试策略推迟。
|
||
*
|
||
* @param {object} service 服务实例。
|
||
* @param {Object} redis Redis 客户端。
|
||
* @param {Object} keys 合并维度键集合。
|
||
* @param {string} queueKey 全局队列键。
|
||
* @param {string} member 队列成员。
|
||
* @param {Object[]} entries 合并队列条目。
|
||
* @return {Promise<void>} 无返回值。
|
||
*/
|
||
async function handleOrderSyncNoticeFlushFailureInternal(service, redis, keys, queueKey, member, entries) {
|
||
const retries = Number(await redis.incr(keys.retryKey)) || 1;
|
||
|
||
if (retries >= ORDER_SYNC_NOTICE_MAX_RETRIES) {
|
||
await redis.del(keys.listKey, keys.retryKey);
|
||
await redis.zrem(queueKey, member);
|
||
service.ctx.logger.error('[OrderAsyncService.flushDeferredOrderSyncNotices] 合并通知重试次数超限,放弃发送', {
|
||
member,
|
||
entryCount: entries.length,
|
||
retries,
|
||
});
|
||
|
||
return;
|
||
}
|
||
|
||
if (entries.length > 0) {
|
||
await redis.rpush(keys.listKey, ...entries.map(entry => JSON.stringify(entry)));
|
||
await redis.expire(keys.listKey, ORDER_SYNC_NOTICE_LIST_TTL_SECONDS);
|
||
}
|
||
|
||
await redis.zadd(queueKey, Math.floor((Date.now() + ORDER_SYNC_NOTICE_RETRY_MS) / 1000), member);
|
||
service.ctx.logger.warn('[OrderAsyncService.flushDeferredOrderSyncNotices] 合并通知发送失败,已重新排队', {
|
||
member,
|
||
entryCount: entries.length,
|
||
retries,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 冲刷合并的订单同步通知:把 3 分钟去抖窗口已到期的「仓库:货主」维度订单统一推送。
|
||
* 由定时任务调用。
|
||
*
|
||
* @param {object} service 服务实例。
|
||
* @return {Promise<Object>} 本轮冲刷结果。
|
||
*/
|
||
async function flushDeferredOrderSyncNoticesInternal(service) {
|
||
const redis = getOrderSyncNoticeRedisClientInternal(service);
|
||
if (!redis) {
|
||
service.ctx.logger.warn('[OrderAsyncService.flushDeferredOrderSyncNotices] Redis 不可用,跳过本轮合并通知');
|
||
|
||
return {
|
||
skipped: true,
|
||
reason: 'redis_unavailable',
|
||
flushedCount: 0,
|
||
failedCount: 0,
|
||
skippedCount: 0,
|
||
};
|
||
}
|
||
|
||
const queueKey = `${ORDER_SYNC_NOTICE_KEY_PREFIX}:queue`;
|
||
const nowSeconds = Math.floor(Date.now() / 1000);
|
||
let dueMembers = [];
|
||
|
||
try {
|
||
dueMembers = await redis.zrangebyscore(queueKey, '-inf', nowSeconds, 'LIMIT', 0, ORDER_SYNC_NOTICE_FLUSH_BATCH_SIZE);
|
||
} catch (error) {
|
||
service.ctx.logger.error('[OrderAsyncService.flushDeferredOrderSyncNotices] 读取到期队列失败', {
|
||
error: String((error && error.message) || error || '').trim(),
|
||
});
|
||
|
||
return {
|
||
skipped: true,
|
||
reason: 'queue_read_failed',
|
||
flushedCount: 0,
|
||
failedCount: 0,
|
||
skippedCount: 0,
|
||
};
|
||
}
|
||
|
||
if (!Array.isArray(dueMembers) || dueMembers.length === 0) {
|
||
return {
|
||
skipped: false,
|
||
flushedCount: 0,
|
||
failedCount: 0,
|
||
skippedCount: 0,
|
||
};
|
||
}
|
||
|
||
let flushedCount = 0;
|
||
let failedCount = 0;
|
||
let skippedCount = 0;
|
||
|
||
for (const member of dueMembers) {
|
||
const parsedMember = parseOrderSyncNoticeMemberInternal(member);
|
||
if (!parsedMember) {
|
||
skippedCount += 1;
|
||
continue;
|
||
}
|
||
|
||
const keys = buildOrderSyncNoticeKeysInternal(parsedMember.warehouseId, parsedMember.storeId);
|
||
let lockAcquired = false;
|
||
|
||
try {
|
||
const lockResult = await redis.set(keys.lockKey, String(process.pid || ''), 'EX', ORDER_SYNC_NOTICE_LOCK_TTL_SECONDS, 'NX');
|
||
lockAcquired = lockResult === 'OK';
|
||
} catch (lockError) {
|
||
service.ctx.logger.warn('[OrderAsyncService.flushDeferredOrderSyncNotices] 获取合并锁失败,跳过本轮', {
|
||
member,
|
||
error: String((lockError && lockError.message) || lockError || '').trim(),
|
||
});
|
||
continue;
|
||
}
|
||
|
||
if (!lockAcquired) {
|
||
skippedCount += 1;
|
||
continue;
|
||
}
|
||
|
||
try {
|
||
// 加锁期间可能又有新订单入队把到期时间推后,重新校验到期时间
|
||
const currentScore = await redis.zscore(queueKey, member);
|
||
if (Number(currentScore) > nowSeconds) {
|
||
skippedCount += 1;
|
||
continue;
|
||
}
|
||
|
||
const existsCount = Number(await redis.exists(keys.listKey)) || 0;
|
||
if (existsCount === 0) {
|
||
await redis.del(keys.listKey, keys.retryKey);
|
||
await redis.zrem(queueKey, member);
|
||
continue;
|
||
}
|
||
|
||
// 原子搬走列表,避免与并发新入队条目互相污染
|
||
const processingKey = `${keys.listKey}:processing`;
|
||
await redis.rename(keys.listKey, processingKey);
|
||
const rawEntries = await redis.lrange(processingKey, 0, -1);
|
||
await redis.del(processingKey);
|
||
|
||
const entries = (Array.isArray(rawEntries) ? rawEntries : [])
|
||
.map(rawEntry => parseOrderSyncNoticeEntryInternal(rawEntry))
|
||
.filter(entry => !!entry);
|
||
|
||
if (entries.length === 0) {
|
||
await redis.del(keys.retryKey);
|
||
await redis.zrem(queueKey, member);
|
||
continue;
|
||
}
|
||
|
||
const noticeResult = await sendConsolidatedOrderSyncNoticeInternal(
|
||
service,
|
||
parsedMember.warehouseId,
|
||
parsedMember.storeId,
|
||
entries
|
||
);
|
||
|
||
if (noticeResult && noticeResult.success === true) {
|
||
await redis.del(keys.retryKey);
|
||
await redis.zrem(queueKey, member);
|
||
flushedCount += 1;
|
||
} else {
|
||
await handleOrderSyncNoticeFlushFailureInternal(service, redis, keys, queueKey, member, entries);
|
||
failedCount += 1;
|
||
}
|
||
} catch (error) {
|
||
failedCount += 1;
|
||
service.ctx.logger.error('[OrderAsyncService.flushDeferredOrderSyncNotices] 冲刷合并通知失败', {
|
||
member,
|
||
error: String((error && error.message) || error || '').trim(),
|
||
});
|
||
|
||
try {
|
||
await redis.zadd(queueKey, Math.floor((Date.now() + ORDER_SYNC_NOTICE_RETRY_MS) / 1000), member);
|
||
} catch (reQueueError) {
|
||
// 重新排队失败仅记录日志
|
||
}
|
||
} finally {
|
||
try {
|
||
await redis.del(keys.lockKey);
|
||
} catch (lockReleaseError) {
|
||
// 释放锁失败仅记录日志
|
||
}
|
||
}
|
||
}
|
||
|
||
service.ctx.logger.info('[OrderAsyncService.flushDeferredOrderSyncNotices] 本轮合并通知冲刷完成', {
|
||
dueMemberCount: dueMembers.length,
|
||
flushedCount,
|
||
failedCount,
|
||
skippedCount,
|
||
});
|
||
|
||
return {
|
||
skipped: false,
|
||
flushedCount,
|
||
failedCount,
|
||
skippedCount,
|
||
};
|
||
}
|
||
|
||
|
||
async function processQmOrderInternal(service, orderModel, orderItemsModel, qimenClient, orderId, warehouseId, orderRow, orderItems, context, waybillCode) {
|
||
if (!orderRow) {
|
||
return {
|
||
order_id: orderId,
|
||
status: 'failed',
|
||
message: '发货单不存在',
|
||
qimen_flag: 'failure',
|
||
};
|
||
}
|
||
|
||
if (!qimenClient || typeof qimenClient.send !== 'function') {
|
||
await markPendingExceptionInternal(service, orderModel, orderId, warehouseId, '奇门客户端未初始化');
|
||
|
||
return {
|
||
order_id: orderId,
|
||
delivery_order_code: String(orderRow.delivery_order_code || '').trim(),
|
||
status: 'failed',
|
||
message: '奇门客户端未初始化',
|
||
qimen_flag: 'failure',
|
||
};
|
||
}
|
||
|
||
const requestData = await buildQimenDeliveryOrderConfirmDataInternal(service, orderRow, orderItems, {
|
||
...context,
|
||
packageExpressCode: Array.isArray(waybillCode) ? waybillCode[0] : (waybillCode || orderRow.express_code || ''),
|
||
packageExpressCodes: Array.isArray(waybillCode) ? waybillCode : [],
|
||
});
|
||
if (!requestData.ownerCode) {
|
||
await markPendingExceptionInternal(service, orderModel, orderId, warehouseId, '发货单缺少奇门货主编码');
|
||
|
||
return {
|
||
order_id: orderId,
|
||
delivery_order_code: String(orderRow.delivery_order_code || '').trim(),
|
||
status: 'failed',
|
||
message: '发货单缺少奇门货主编码',
|
||
qimen_flag: 'failure',
|
||
};
|
||
}
|
||
|
||
service.ctx.logger.info('[OrderAsyncService.syncQmOrders] 奇门请求参数', {
|
||
orderId,
|
||
deliveryOrderCode: String(orderRow.delivery_order_code || '').trim(),
|
||
ownerCode: requestData.ownerCode,
|
||
warehouseCode: requestData.warehouseCode,
|
||
totalOrderLines: requestData.request.deliveryOrder.totalOrderLines,
|
||
deliveryOrder: requestData.request.deliveryOrder,
|
||
package: requestData.request.packages,
|
||
orderLinesCount: Array.isArray(requestData.request.orderLines)
|
||
? requestData.request.orderLines.length
|
||
: 0,
|
||
});
|
||
|
||
let sendResult;
|
||
try {
|
||
sendResult = await qimenClient.send('taobao.qimen.deliveryorder.confirm', requestData.ownerCode, requestData.request, {
|
||
ctx: service.ctx,
|
||
});
|
||
} catch (error) {
|
||
await orderModel.update({
|
||
sync_status: 'error',
|
||
}, {
|
||
where: {
|
||
id: orderId,
|
||
warehouse_id: warehouseId,
|
||
},
|
||
});
|
||
|
||
await markPendingExceptionInternal(service, orderModel, orderId, warehouseId, error.message || '奇门发货单确认失败');
|
||
|
||
return {
|
||
order_id: orderId,
|
||
delivery_order_code: String(orderRow.delivery_order_code || '').trim(),
|
||
status: 'failed',
|
||
message: error.message || '奇门发货单确认失败',
|
||
qimen_flag: 'failure',
|
||
error: error.message,
|
||
};
|
||
}
|
||
|
||
const response = normalizeQimenResponseInternal(sendResult.xmlArray);
|
||
service.ctx.logger.info('[OrderAsyncService.syncQmOrders] 奇门返回结果', {
|
||
orderId,
|
||
deliveryOrderCode: String(orderRow.delivery_order_code || '').trim(),
|
||
qimenQueryId: sendResult.queryId || null,
|
||
rawXmlArray: sendResult.xmlArray,
|
||
normalizedResponse: response,
|
||
});
|
||
const isSuccess = String(response.flag || '').trim() === 'success';
|
||
|
||
if (isSuccess) {
|
||
try {
|
||
await finalizeSuccessfulQimenSyncInternal(service, orderModel, orderItemsModel, orderId, warehouseId, orderRow);
|
||
} catch (error) {
|
||
await orderModel.update({
|
||
sync_status: 'error',
|
||
}, {
|
||
where: {
|
||
id: orderId,
|
||
warehouse_id: warehouseId,
|
||
},
|
||
});
|
||
|
||
await markPendingExceptionInternal(service, orderModel, orderId, warehouseId, error.message || '奇门发货单确认后库存扣减失败');
|
||
|
||
return {
|
||
order_id: orderId,
|
||
delivery_order_code: String(orderRow.delivery_order_code || '').trim(),
|
||
status: 'failed',
|
||
message: error.message || '奇门发货单确认后库存扣减失败',
|
||
qimen_flag: 'failure',
|
||
qimen_code: 'LOCAL_STOCK_ERROR',
|
||
qimen_message: error.message || '奇门发货单确认后库存扣减失败',
|
||
qimen_query_id: sendResult.queryId || null,
|
||
};
|
||
}
|
||
} else {
|
||
await orderModel.update({
|
||
sync_status: 'error',
|
||
}, {
|
||
where: {
|
||
id: orderId,
|
||
warehouse_id: warehouseId,
|
||
},
|
||
});
|
||
}
|
||
|
||
const result = {
|
||
order_id: orderId,
|
||
delivery_order_code: String(orderRow.delivery_order_code || '').trim(),
|
||
status: isSuccess ? 'success' : 'failed',
|
||
message: String(response.message || '').trim() || (isSuccess ? '奇门发货单确认成功' : '奇门发货单确认失败'),
|
||
qimen_flag: String(response.flag || '').trim(),
|
||
qimen_code: String(response.code || '').trim(),
|
||
qimen_message: String(response.message || '').trim(),
|
||
qimen_query_id: sendResult.queryId || null,
|
||
};
|
||
|
||
if (!isSuccess) {
|
||
await markPendingExceptionInternal(
|
||
service,
|
||
orderModel,
|
||
orderId,
|
||
warehouseId,
|
||
String(response.message || response.code || '奇门发货单确认失败').trim() || '奇门发货单确认失败'
|
||
);
|
||
}
|
||
|
||
return result;
|
||
}
|
||
|
||
|
||
async function syncQmOrdersInternal(service, groupedOrder = {}, context = {}) {
|
||
const orderIds = Array.isArray(groupedOrder.order_ids)
|
||
? groupedOrder.order_ids.map(orderId => Number(orderId)).filter(orderId => Number.isFinite(orderId) && orderId > 0)
|
||
: [];
|
||
const warehouseId = Number(context.warehouseId || 0);
|
||
|
||
if (orderIds.length === 0) {
|
||
return {
|
||
create_channel: CREATE_CHANNEL_QM,
|
||
order_ids: [],
|
||
order_count: 0,
|
||
warehouse_id: warehouseId,
|
||
handler: 'syncQmOrders',
|
||
sync_target: 'qimen',
|
||
orders: [],
|
||
qimen_results: [],
|
||
route_state: 'rejected',
|
||
status: 'failed',
|
||
message: 'QM 同步订单不能为空',
|
||
};
|
||
}
|
||
|
||
if (warehouseId <= 0) {
|
||
return {
|
||
create_channel: CREATE_CHANNEL_QM,
|
||
order_ids: orderIds,
|
||
order_count: Number.isFinite(Number(groupedOrder.order_count)) ? Number(groupedOrder.order_count) : orderIds.length,
|
||
warehouse_id: warehouseId,
|
||
handler: 'syncQmOrders',
|
||
sync_target: 'qimen',
|
||
orders: Array.isArray(groupedOrder.orders) ? groupedOrder.orders.map(order => ({ ...order })) : [],
|
||
qimen_results: [],
|
||
route_state: 'rejected',
|
||
status: 'failed',
|
||
message: '缺少仓库上下文',
|
||
};
|
||
}
|
||
|
||
const orderModel = await service.ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId);
|
||
const orderItemsModel = await service.ctx.model.OrderItemsFactory.getCurrentModel(warehouseId);
|
||
const { Op } = service.app.Sequelize;
|
||
const [ orderRows, orderItemRows ] = await Promise.all([
|
||
orderModel.findAll({
|
||
where: {
|
||
id: {
|
||
[Op.in]: orderIds,
|
||
},
|
||
warehouse_id: warehouseId,
|
||
},
|
||
raw: true,
|
||
}),
|
||
orderItemsModel.findAll({
|
||
where: {
|
||
order_id: {
|
||
[Op.in]: orderIds,
|
||
},
|
||
},
|
||
raw: true,
|
||
}),
|
||
]);
|
||
|
||
const orderMap = new Map();
|
||
for (const orderRow of Array.isArray(orderRows) ? orderRows : []) {
|
||
if (orderRow && Number(orderRow.id) > 0) {
|
||
// 分发前过滤:已同步完成的订单不再派发,避免重复同步覆盖 error 等异常状态
|
||
if (String(orderRow.sync_status || '').trim() === 'fin') {
|
||
service.ctx.logger.info(`[syncQmOrders] 订单已完成同步,跳过派发 orderId=${orderRow.id}`);
|
||
continue;
|
||
}
|
||
orderMap.set(Number(orderRow.id), orderRow);
|
||
}
|
||
}
|
||
|
||
const waybillCodeMap = await buildOrderWaybillCodeMapInternal(service, orderIds, warehouseId);
|
||
|
||
const itemsByOrderId = new Map();
|
||
for (const orderItem of Array.isArray(orderItemRows) ? orderItemRows : []) {
|
||
const orderId = Number(orderItem && orderItem.order_id);
|
||
if (!Number.isFinite(orderId) || orderId <= 0) {
|
||
continue;
|
||
}
|
||
|
||
if (!itemsByOrderId.has(orderId)) {
|
||
itemsByOrderId.set(orderId, []);
|
||
}
|
||
|
||
itemsByOrderId.get(orderId).push(orderItem);
|
||
}
|
||
|
||
const qimenClient = service.app.qimenClient;
|
||
const progressCacheKey = getSyncOrderIdsProgressCacheKey(context.request_id);
|
||
// dispatch前最终去重,防止同一orderId在列表中重复导致并发双扣
|
||
const uniqueOrderIds = [ ...new Set(orderIds) ];
|
||
const qimenResults = [];
|
||
for (let i = 0; i < uniqueOrderIds.length; i += DISPATCH_BATCH_SIZE) {
|
||
const batch = uniqueOrderIds.slice(i, i + DISPATCH_BATCH_SIZE);
|
||
const batchResults = await Promise.all(batch.map(orderId => {
|
||
// 分发时二次检查:orderRow 不在 map 中则跳过
|
||
const dispathedOrderRow = orderMap.get(orderId);
|
||
if (!dispathedOrderRow) {
|
||
service.ctx.logger.info(`[syncQmOrders] 订单已过滤,跳过 orderId=${orderId}`);
|
||
return { order_id: orderId, status: 'skipped', message: '订单已完成同步,跳过' };
|
||
}
|
||
return processQmOrderInternal(
|
||
service,
|
||
orderModel,
|
||
orderItemsModel,
|
||
qimenClient,
|
||
orderId,
|
||
warehouseId,
|
||
dispathedOrderRow,
|
||
itemsByOrderId.get(orderId) || [],
|
||
context,
|
||
waybillCodeMap.get(orderId)
|
||
);
|
||
}));
|
||
qimenResults.push(...batchResults);
|
||
await updateDispatchBatchProgress(service, progressCacheKey, batchResults.length);
|
||
}
|
||
|
||
const successCount = qimenResults.filter(item => item.status === 'success').length;
|
||
const failedCount = qimenResults.filter(item => item.status === 'failed').length;
|
||
const overallSuccess = failedCount === 0 && successCount === qimenResults.length;
|
||
|
||
return {
|
||
create_channel: CREATE_CHANNEL_QM,
|
||
order_ids: orderIds,
|
||
order_count: Number.isFinite(Number(groupedOrder.order_count)) ? Number(groupedOrder.order_count) : orderIds.length,
|
||
warehouse_id: warehouseId,
|
||
handler: 'syncQmOrders',
|
||
sync_target: 'qimen',
|
||
orders: Array.isArray(groupedOrder.orders) ? groupedOrder.orders.map(order => ({ ...order })) : [],
|
||
qimen_results: qimenResults,
|
||
route_state: overallSuccess ? 'accepted' : 'rejected',
|
||
status: overallSuccess ? 'success' : 'failed',
|
||
message: overallSuccess ? '奇门发货单确认成功' : '奇门发货单确认失败',
|
||
success_count: successCount,
|
||
failed_count: failedCount,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 订单异步同步路由服务。
|
||
*/
|
||
class OrderAsyncService extends MainService {
|
||
async finalizeSuccessfulQimenSync(orderModel, orderItemsModel, orderId, warehouseId, orderRow = null) {
|
||
return await finalizeSuccessfulQimenSyncInternal(this, orderModel, orderItemsModel, orderId, warehouseId, orderRow);
|
||
}
|
||
|
||
|
||
/**
|
||
* QM 创建入口处理。
|
||
*
|
||
* @param {Object} groupedOrder 分组后的订单。
|
||
* @param {Object} context 上下文。
|
||
* @return {Promise<Object>} 处理结果。
|
||
*/
|
||
async syncQmOrders(groupedOrder = {}, context = {}) {
|
||
return await syncQmOrdersInternal(this, groupedOrder, context);
|
||
}
|
||
|
||
/**
|
||
* MANUAL 创建入口处理。
|
||
*
|
||
* @param {Object} groupedOrder 分组后的订单。
|
||
* @param {Object} context 上下文。
|
||
* @return {Promise<Object>} 处理结果。
|
||
*/
|
||
async syncManualOrders(groupedOrder = {}, context = {}) {
|
||
return await syncManualOrdersInternal(this, groupedOrder, context);
|
||
}
|
||
|
||
/**
|
||
* 冲刷合并的订单同步通知(由定时任务调用)。
|
||
* 把 3 分钟去抖窗口已到期的「仓库:货主」维度订单统一推送一条消息。
|
||
*
|
||
* @return {Promise<Object>} 本轮冲刷结果。
|
||
*/
|
||
async flushDeferredOrderSyncNotices() {
|
||
return await flushDeferredOrderSyncNoticesInternal(this);
|
||
}
|
||
|
||
/**
|
||
* API 创建入口处理。
|
||
*
|
||
* @param {Object} groupedOrder 分组后的订单。
|
||
* @param {Object} context 上下文。
|
||
* @return {Promise<Object>} 处理结果。
|
||
*/
|
||
async syncApiOrders(groupedOrder = {}, context = {}) {
|
||
return await finalizeLocalChannelOrdersInternal(this, CREATE_CHANNEL_API, groupedOrder, context, 'api');
|
||
}
|
||
|
||
/**
|
||
* STOCKOUT 创建入口处理(出库单转订单回传)。
|
||
*
|
||
* 回传时把订单实际快递编码/运单号写回出库单,并按出库单来源通知外部
|
||
* (QM→奇门 stockout.confirm,API→OpenAPI 回调),成功后才扣减库存完成同步。
|
||
*
|
||
* @param {Object} groupedOrder 分组后的订单。
|
||
* @param {Object} context 上下文。
|
||
* @return {Promise<Object>} 处理结果。
|
||
*/
|
||
async syncStockoutOrders(groupedOrder = {}, context = {}) {
|
||
return await syncStockoutOrdersInternal(this, groupedOrder, context);
|
||
}
|
||
|
||
/**
|
||
* 组装出库单确认回传报文(与奇门 request 节点同层级,OpenAPI 回调复用)。
|
||
*
|
||
* 供出库单转订单回传与出库单直出确认(storage.stockout.confirm)共用,
|
||
* 避免两处各写一份报文结构导致漂移。
|
||
*
|
||
* @param {Object} stockoutOrder 出库单记录(模型实例或 raw 对象)。
|
||
* @param {Object} orderRow 发货单记录(raw);直出确认无订单上下文时传空对象即可。
|
||
* @param {Array} stockoutItems 出库单明细数组。
|
||
* @param {Array<string>} [waybillCodes] 运单号列表。
|
||
* @return {Object} 出库单确认回传请求体。
|
||
*/
|
||
buildStockoutConfirmRequest(stockoutOrder, orderRow, stockoutItems, waybillCodes = []) {
|
||
return buildStockoutConfirmDataInternal(this, stockoutOrder, orderRow, stockoutItems, waybillCodes);
|
||
}
|
||
|
||
/**
|
||
* 按出库单 source_type 通知外部(QM→奇门,API→OpenAPI 回调,其他→无需通知直接成功)。
|
||
*
|
||
* @param {Object} stockoutOrder 出库单记录。
|
||
* @param {Object} requestData 出库单确认回传请求体。
|
||
* @param {Object} [context] 上下文(API 来源需传 appKey)。
|
||
* @return {Promise<{success: boolean, message: string}>} 通知结果。
|
||
*/
|
||
async notifyStockoutExternal(stockoutOrder, requestData, context = {}) {
|
||
return await notifyStockoutExternalInternal(this, stockoutOrder, requestData, context);
|
||
}
|
||
|
||
/**
|
||
* 按货主合约反查可用的 OpenAPI 应用配置(ApiApp),用于 API 来源出站回调。
|
||
*
|
||
* @param {number|string} storeId 货主 ID。
|
||
* @param {number|string} warehouseId 仓库 ID。
|
||
* @return {Promise<Object|null>} { appKey, selfAppSecret, callbackUrl },未找到时返回 null。
|
||
*/
|
||
async resolveOpenApiAppByStore(storeId, warehouseId) {
|
||
return await resolveOpenApiAppByStoreInternal(this, storeId, warehouseId);
|
||
}
|
||
}
|
||
|
||
module.exports = OrderAsyncService;
|