- express.js: createWaybillCode 优先使用传入的 warehouse_id,修复 setImmediate 后 ctx.user 丢失导致 wms_order_express.warehouse_id 外键约束失败 - delivery_order.js: asyncProcessOrderCreated 中平台/快递解析逻辑修正 - recheckOrder.js: 复核单快递分配状态判断优化 - express_platform.js: 快递平台自动同步回传链路修正 - order_async.js: 奇门异步下单上下文增强 - polo_api_client.js: PolyAPI 客户端微调
1309 lines
46 KiB
JavaScript
1309 lines
46 KiB
JavaScript
'use strict';
|
||
|
||
const MainService = require('../main');
|
||
|
||
const CREATE_CHANNEL_QM = 'QM';
|
||
const CREATE_CHANNEL_MANUAL = 'MANUAL';
|
||
const CREATE_CHANNEL_API = 'API';
|
||
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;
|
||
|
||
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 ] : [];
|
||
}
|
||
|
||
async function buildOrderWaybillCodeMapInternal(service, orderIds = []) {
|
||
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 { Op } = service.app.Sequelize;
|
||
const expressRows = await orderExpressModel.findAll({
|
||
where: {
|
||
order_id: {
|
||
[Op.in]: normalizedOrderIds,
|
||
},
|
||
},
|
||
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,
|
||
},
|
||
};
|
||
}
|
||
|
||
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);
|
||
|
||
// 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,
|
||
warehouse_id: warehouseId,
|
||
handler: 'syncManualOrders',
|
||
sync_target: 'internal',
|
||
route_state: 'accepted',
|
||
status: 'success',
|
||
message: '订单同步通知已发送',
|
||
success_count: 1,
|
||
failed_count: 0,
|
||
};
|
||
const noticeResult = await sendManualSyncNoticeInternal(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,
|
||
};
|
||
}
|
||
|
||
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);
|
||
}
|
||
}
|
||
|
||
void orderItemRows;
|
||
|
||
// 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 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;
|
||
|
||
// 同步成功后触发 OpenAPI 回调通知(fire-and-forget,不阻塞主流程)
|
||
if (createChannel === CREATE_CHANNEL_API && successCount > 0) {
|
||
try {
|
||
const callbackService = service.ctx.service.openapi && service.ctx.service.openapi.callback;
|
||
|
||
if (callbackService && typeof callbackService.sendByAppKey === 'function') {
|
||
const appKey = String(context.appKey || '').trim();
|
||
|
||
if (appKey) {
|
||
callbackService.sendByAppKey({
|
||
appKey,
|
||
event: 'order_completed',
|
||
data: {
|
||
orderIds,
|
||
status: 'completed',
|
||
successCount,
|
||
failedCount,
|
||
},
|
||
metadata: {
|
||
warehouseId,
|
||
createChannel,
|
||
syncTarget,
|
||
},
|
||
}).catch(err => {
|
||
service.ctx.logger.warn(`[OrderAsyncService] OpenAPI 回调忽略失败: ${err.message}`);
|
||
});
|
||
}
|
||
}
|
||
} catch (err) {
|
||
service.ctx.logger.warn(`[OrderAsyncService] 触发回调异常,不影响主流程: ${err.message}`);
|
||
}
|
||
}
|
||
|
||
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,
|
||
};
|
||
}
|
||
|
||
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 noticeMessage = String(syncResult.message || '').trim() || '订单同步完成';
|
||
const noticeStatus = String(syncResult.status || '').trim() || 'success';
|
||
const deliveryOrderCode = String(syncResult.delivery_order_code || '').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: [
|
||
`仓库ID:${warehouseId || '未知'}`,
|
||
`订单ID:${orderIds.join(',') || '无'}`,
|
||
`发货单号:${deliveryOrderCode || '无'}`,
|
||
`运单号:${waybillCodeList.length > 0 ? waybillCodeList.join(',') : '无'}`,
|
||
`消息:${noticeMessage}`,
|
||
].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),
|
||
},
|
||
};
|
||
}
|
||
|
||
|
||
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);
|
||
|
||
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);
|
||
}
|
||
|
||
/**
|
||
* API 创建入口处理。
|
||
*
|
||
* @param {Object} groupedOrder 分组后的订单。
|
||
* @param {Object} context 上下文。
|
||
* @return {Promise<Object>} 处理结果。
|
||
*/
|
||
async syncApiOrders(groupedOrder = {}, context = {}) {
|
||
return await finalizeLocalChannelOrdersInternal(this, CREATE_CHANNEL_API, groupedOrder, context, 'api');
|
||
}
|
||
}
|
||
|
||
module.exports = OrderAsyncService;
|