2660 lines
91 KiB
JavaScript
2660 lines
91 KiB
JavaScript
'use strict';
|
||
|
||
const fs = require('node:fs');
|
||
const path = require('node:path');
|
||
const { Op } = require('sequelize');
|
||
const OrderBaseService = require('../systemMethods/order/base');
|
||
const PrinterDataBuilder = require('../../lib/printer_data_builder');
|
||
|
||
class OrderPrintSystemService extends OrderBaseService {
|
||
/**
|
||
* 判断订单是否处于锁定状态。
|
||
*
|
||
* 当前约定 print_lock_status=none 表示未锁定,其余值均视为锁定。
|
||
*
|
||
* @param {Object} orderRow 订单行。
|
||
* @return {boolean} 是否锁定。
|
||
*/
|
||
isOrderLocked(orderRow = {}) {
|
||
const lockStatus = String(orderRow && orderRow.print_lock_status || 'none').trim() || 'none';
|
||
return lockStatus !== 'none';
|
||
}
|
||
|
||
/**
|
||
* 构建波次平台打印“已锁定”短路返回。
|
||
*
|
||
* @param {Object} payload 聚合入参。
|
||
* @param {Array<Object>} payload.lockedOrders 已锁定订单列表。
|
||
* @param {Array<number>} payload.validWaveIds 命中的有效波次ID。
|
||
* @param {Array<number>} payload.missingWaveIds 未命中波次ID。
|
||
* @param {Array<Object>} payload.filteredWaveIds 被过滤波次及原因。
|
||
* @return {Object} 锁定短路返回结构。
|
||
*/
|
||
buildLockedWavePlatformResult(payload = {}) {
|
||
const requestPayload = this.isPlainObject(payload) ? payload : {};
|
||
const lockedOrders = Array.isArray(requestPayload.lockedOrders) ? requestPayload.lockedOrders : [];
|
||
const validWaveIds = Array.isArray(requestPayload.validWaveIds) ? requestPayload.validWaveIds : [];
|
||
const missingWaveIds = Array.isArray(requestPayload.missingWaveIds) ? requestPayload.missingWaveIds : [];
|
||
const filteredWaveIds = Array.isArray(requestPayload.filteredWaveIds) ? requestPayload.filteredWaveIds : [];
|
||
|
||
return {
|
||
summary: {
|
||
total_waves: 0,
|
||
total_orders: 0,
|
||
total_platforms: 0,
|
||
locked_count: lockedOrders.length,
|
||
},
|
||
waveGroups: [],
|
||
wave_ids: validWaveIds,
|
||
locked_count: lockedOrders.length,
|
||
locked_orders: lockedOrders,
|
||
ext: {
|
||
missing_wave_ids: missingWaveIds,
|
||
filtered_wave_ids: filteredWaveIds,
|
||
},
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 组装单订单“已锁定”平台打印中间态结果(轻量对象)。
|
||
*
|
||
* @param {Object} payload 聚合入参。
|
||
* @param {Object} payload.orderRow 订单行。
|
||
* @param {string} payload.platformCode 平台编码。
|
||
* @return {Object} 锁定订单中间态。
|
||
*/
|
||
buildLockedOrderPlatformPrintItem(payload = {}) {
|
||
const requestPayload = this.isPlainObject(payload) ? payload : {};
|
||
const orderRow = this.isPlainObject(requestPayload.orderRow) ? requestPayload.orderRow : {};
|
||
const platformCode = String(requestPayload.platformCode || '').trim();
|
||
const normalizedPlatform = PrinterDataBuilder.normalizePlatformAlias(platformCode);
|
||
const orderId = Number(orderRow.id || 0);
|
||
|
||
return {
|
||
wave_id: Number(orderRow.wave_id || 0),
|
||
wave_no: String(orderRow.wave_no || '').trim(),
|
||
order_id: orderId,
|
||
order_no: String(orderRow.delivery_order_code || orderRow.source_order_codes || '').trim(),
|
||
store_id: Number(orderRow.store_id || 0),
|
||
warehouse_id: Number(orderRow.warehouse_id || 0),
|
||
platform: platformCode,
|
||
platform_name: normalizedPlatform.meta && normalizedPlatform.meta.name
|
||
? String(normalizedPlatform.meta.name).trim()
|
||
: '',
|
||
sys_logistics_code: String(orderRow.sys_logistics_code || '').trim(),
|
||
sys_logistics_name: String(orderRow.sys_logistics_name || '').trim(),
|
||
waybill_code: '',
|
||
print_data: {
|
||
order_id: orderId,
|
||
order_no: String(orderRow.delivery_order_code || orderRow.source_order_codes || '').trim(),
|
||
wave_id: Number(orderRow.wave_id || 0),
|
||
wave_no: String(orderRow.wave_no || '').trim(),
|
||
platform: platformCode,
|
||
platform_name: normalizedPlatform.meta && normalizedPlatform.meta.name
|
||
? String(normalizedPlatform.meta.name).trim()
|
||
: '',
|
||
status: 'locked',
|
||
status_text: '已锁定',
|
||
print_lock_status: String(orderRow.print_lock_status || '').trim() || 'none',
|
||
},
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 判断当前配置是否需要补查拣货明细。
|
||
*
|
||
* 未配置时默认按类型5处理,因此也需要补查。
|
||
*
|
||
* @param {Object} policyConfig 策略配置。
|
||
* @return {boolean} 是否需要补查拣货明细。
|
||
*/
|
||
shouldLoadPickingDetails(policyConfig = {}) {
|
||
const config = this.isPlainObject(policyConfig) ? policyConfig : {};
|
||
const displayType = Object.prototype.hasOwnProperty.call(config, 'waybill_custom_display_type')
|
||
? String(config.waybill_custom_display_type || '').trim()
|
||
: '5';
|
||
|
||
return [ '2', '3', '4', '5' ].includes(displayType);
|
||
}
|
||
|
||
/**
|
||
* 归一化商品快照,兼容 JSON 字符串。
|
||
*
|
||
* @param {*} rawSnapshot 原始商品快照。
|
||
* @return {Object} 快照对象。
|
||
*/
|
||
normalizeItemSnapshot(rawSnapshot) {
|
||
if (this.isPlainObject(rawSnapshot)) {
|
||
return rawSnapshot;
|
||
}
|
||
|
||
if (typeof rawSnapshot === 'string') {
|
||
const text = rawSnapshot.trim();
|
||
if (!text) {
|
||
return {};
|
||
}
|
||
|
||
try {
|
||
const parsed = JSON.parse(text);
|
||
return this.isPlainObject(parsed) ? parsed : {};
|
||
} catch (error) {
|
||
return {};
|
||
}
|
||
}
|
||
|
||
return {};
|
||
}
|
||
|
||
/**
|
||
* 从候选字段中读取首个非空文本。
|
||
*
|
||
* @param {Object} source 源对象。
|
||
* @param {Array<string>} keys 候选键。
|
||
* @return {string} 首个非空文本。
|
||
*/
|
||
getFirstNonEmptyFieldText(source, keys = []) {
|
||
if (!this.isPlainObject(source)) {
|
||
return '';
|
||
}
|
||
|
||
for (const key of keys) {
|
||
const value = source[key];
|
||
if (value === undefined || value === null) {
|
||
continue;
|
||
}
|
||
|
||
const text = String(value).trim();
|
||
if (text) {
|
||
return text;
|
||
}
|
||
}
|
||
|
||
return '';
|
||
}
|
||
|
||
/**
|
||
* 批量补查打印所需的拣货明细。
|
||
*
|
||
* 优先使用 wms_picking.space_name,只有缺失时才查询库位表,减少额外 SQL。
|
||
*
|
||
* @param {Array<Object>} orderRows 订单列表。
|
||
* @param {number} warehouseId 仓库ID。
|
||
* @return {Promise<Map<number, Object>>} 订单ID到补齐后订单对象的映射。
|
||
*/
|
||
async buildPrintOrderRowMapWithPicking(orderRows = [], warehouseId) {
|
||
const rows = Array.isArray(orderRows) ? orderRows : [];
|
||
const orderIds = Array.from(new Set(rows
|
||
.map(row => Number(row && row.id || 0))
|
||
.filter(orderId => Number.isInteger(orderId) && orderId > 0)));
|
||
const resultMap = new Map();
|
||
|
||
if (orderIds.length === 0) {
|
||
return resultMap;
|
||
}
|
||
|
||
const pickingModel = this.ctx.model && this.ctx.model.Picking;
|
||
if (!pickingModel || typeof pickingModel.findAll !== 'function') {
|
||
return resultMap;
|
||
}
|
||
|
||
const pickingRows = await pickingModel.findAll({
|
||
where: {
|
||
order_id: {
|
||
[Op.in]: orderIds,
|
||
},
|
||
status: {
|
||
[Op.ne]: 'cancel',
|
||
},
|
||
},
|
||
attributes: [ 'id', 'order_id', 'order_item_id', 'quantity', 'space_id', 'space_name', 'status' ],
|
||
order: [[ 'order_id', 'ASC' ], [ 'id', 'ASC' ]],
|
||
raw: true,
|
||
});
|
||
|
||
const normalizedPickingRows = Array.isArray(pickingRows) ? pickingRows : [];
|
||
if (normalizedPickingRows.length === 0) {
|
||
return resultMap;
|
||
}
|
||
|
||
const orderItemIds = Array.from(new Set(normalizedPickingRows
|
||
.map(row => Number(row && row.order_item_id || 0))
|
||
.filter(orderItemId => Number.isInteger(orderItemId) && orderItemId > 0)));
|
||
|
||
const orderItemModelFactory = this.ctx.model && this.ctx.model.OrderItemsFactory;
|
||
const orderItemModel = orderItemModelFactory && typeof orderItemModelFactory.getCurrentModel === 'function'
|
||
? await orderItemModelFactory.getCurrentModel(warehouseId)
|
||
: null;
|
||
|
||
const orderItemRows = orderItemModel && typeof orderItemModel.findAll === 'function' && orderItemIds.length > 0
|
||
? await orderItemModel.findAll({
|
||
where: {
|
||
id: {
|
||
[Op.in]: orderItemIds,
|
||
},
|
||
},
|
||
attributes: [ 'id', 'order_id', 'item_code', 'item_name', 'plan_qty', 'item_snapshot' ],
|
||
raw: true,
|
||
})
|
||
: [];
|
||
|
||
const orderItemMap = new Map();
|
||
for (const row of Array.isArray(orderItemRows) ? orderItemRows : []) {
|
||
const orderItemId = Number(row && row.id || 0);
|
||
if (orderItemId > 0) {
|
||
orderItemMap.set(orderItemId, row);
|
||
}
|
||
}
|
||
|
||
const locationFallbackSpaceIds = Array.from(new Set(normalizedPickingRows
|
||
.filter(row => !String(row && row.space_name || '').trim())
|
||
.map(row => Number(row && row.space_id || 0))
|
||
.filter(spaceId => Number.isInteger(spaceId) && spaceId > 0)));
|
||
const locationModel = this.ctx.model && this.ctx.model.LocationSpace;
|
||
const locationRows = locationModel
|
||
&& typeof locationModel.findAll === 'function'
|
||
&& locationFallbackSpaceIds.length > 0
|
||
? await locationModel.findAll({
|
||
where: {
|
||
id: {
|
||
[Op.in]: locationFallbackSpaceIds,
|
||
},
|
||
warehouse_id: warehouseId,
|
||
},
|
||
attributes: [ 'id', 'space_code', 'custom_name', 'custom_barcode' ],
|
||
raw: true,
|
||
})
|
||
: [];
|
||
const locationMap = new Map((Array.isArray(locationRows) ? locationRows : [])
|
||
.map(row => [ Number(row && row.id || 0), row ]));
|
||
|
||
const pickingRowsByOrderId = new Map();
|
||
for (const row of normalizedPickingRows) {
|
||
const orderId = Number(row && row.order_id || 0);
|
||
if (orderId <= 0) {
|
||
continue;
|
||
}
|
||
|
||
const list = pickingRowsByOrderId.get(orderId) || [];
|
||
list.push(row);
|
||
pickingRowsByOrderId.set(orderId, list);
|
||
}
|
||
|
||
for (const orderRow of rows) {
|
||
const orderId = Number(orderRow && orderRow.id || 0);
|
||
const pickingList = pickingRowsByOrderId.get(orderId) || [];
|
||
if (pickingList.length === 0) {
|
||
continue;
|
||
}
|
||
|
||
const printItems = pickingList.map(pickingRow => {
|
||
const orderItemId = Number(pickingRow && pickingRow.order_item_id || 0);
|
||
const orderItemRow = orderItemMap.get(orderItemId) || {};
|
||
const itemSnapshot = this.normalizeItemSnapshot(orderItemRow.item_snapshot);
|
||
const locationRow = locationMap.get(Number(pickingRow && pickingRow.space_id || 0)) || {};
|
||
const pickLocation = this.getFirstNonEmptyFieldText({
|
||
space_name: pickingRow && pickingRow.space_name,
|
||
space_code: locationRow.space_code,
|
||
custom_name: locationRow.custom_name,
|
||
custom_barcode: locationRow.custom_barcode,
|
||
}, [ 'space_name', 'space_code', 'custom_name', 'custom_barcode' ]);
|
||
const itemName = this.getFirstNonEmptyFieldText({
|
||
snapshot_item_name: itemSnapshot.item_name,
|
||
snapshot_name: itemSnapshot.name,
|
||
snapshot_title: itemSnapshot.title,
|
||
item_name: orderItemRow.item_name,
|
||
}, [ 'snapshot_item_name', 'snapshot_name', 'snapshot_title', 'item_name' ]);
|
||
const barcode = this.getFirstNonEmptyFieldText({
|
||
barcode: itemSnapshot.barcode,
|
||
item_barcode: itemSnapshot.item_barcode,
|
||
bar_code: itemSnapshot.bar_code,
|
||
item_code: orderItemRow.item_code,
|
||
sku_code: itemSnapshot.sku_code,
|
||
sku: itemSnapshot.sku,
|
||
}, [ 'barcode', 'item_barcode', 'bar_code', 'item_code', 'sku_code', 'sku' ]);
|
||
const quantity = Number(pickingRow && pickingRow.quantity || orderItemRow.plan_qty || 0);
|
||
|
||
return {
|
||
order_item_id: orderItemId,
|
||
item_name: itemName,
|
||
barcode,
|
||
quantity: quantity > 0 ? quantity : 0,
|
||
pick_location: pickLocation,
|
||
};
|
||
}).filter(item => {
|
||
return String(item.item_name || '').trim()
|
||
|| String(item.barcode || '').trim()
|
||
|| String(item.pick_location || '').trim();
|
||
});
|
||
|
||
if (printItems.length === 0) {
|
||
continue;
|
||
}
|
||
|
||
resultMap.set(orderId, {
|
||
...orderRow,
|
||
items: JSON.stringify(printItems),
|
||
});
|
||
}
|
||
|
||
return resultMap;
|
||
}
|
||
|
||
/**
|
||
* 归一化签约策略配置,兼容缓存中的字符串形态。
|
||
*
|
||
* @param {*} rawPolicyConfig 原始策略配置。
|
||
* @return {Object} 归一化后的策略配置对象。
|
||
*/
|
||
normalizeContractPolicyConfig(rawPolicyConfig) {
|
||
if (this.isPlainObject(rawPolicyConfig)) {
|
||
return rawPolicyConfig;
|
||
}
|
||
|
||
if (typeof rawPolicyConfig === 'string') {
|
||
const text = rawPolicyConfig.trim();
|
||
if (!text) {
|
||
return {};
|
||
}
|
||
|
||
try {
|
||
const parsed = JSON.parse(text);
|
||
return this.isPlainObject(parsed) ? parsed : {};
|
||
} catch (error) {
|
||
this.ctx.logger.warn('[orderPrint.normalizeContractPolicyConfig] policy_config 解析失败: %s', error.message);
|
||
}
|
||
}
|
||
|
||
return {};
|
||
}
|
||
|
||
/**
|
||
* 获取波次打印数据。
|
||
*
|
||
* @param {Object} params 请求参数。
|
||
* @param {Array<number|string>} params.waveIds 波次ID数组。
|
||
* @param {number|string} params.warehouseId 仓库ID。
|
||
* @return {Promise<Object>} 通用打印数据结构。
|
||
*/
|
||
async getWavePrintData(params = {}) {
|
||
const requestParams = this.isPlainObject(params) ? params : {};
|
||
const {
|
||
waveIds,
|
||
warehouseId,
|
||
} = requestParams;
|
||
|
||
const normalizedWaveIds = this.normalizeWaveIds(waveIds);
|
||
if (normalizedWaveIds.length === 0) {
|
||
throw new Error('wave_ids 必填,且必须为非空数组');
|
||
}
|
||
|
||
const normalizedWarehouseId = this.resolveWarehouseId(warehouseId);
|
||
const waveRows = await this.queryWavesByIds(normalizedWarehouseId, normalizedWaveIds);
|
||
if (waveRows.length === 0) {
|
||
return this.buildEmptyResult(normalizedWaveIds);
|
||
}
|
||
|
||
const hitWaveIdSet = new Set(waveRows.map(row => Number(row.wave_id)));
|
||
const missingWaveIds = normalizedWaveIds.filter(waveId => !hitWaveIdSet.has(waveId));
|
||
const hitWaveIds = normalizedWaveIds.filter(waveId => hitWaveIdSet.has(waveId));
|
||
const orderRows = await this.queryOrdersByWaveIds(hitWaveIds, normalizedWarehouseId);
|
||
const {
|
||
validWaveIds,
|
||
filteredWaveIds,
|
||
} = this.filterFullyAssignedExpressWaves(hitWaveIds, orderRows);
|
||
|
||
return this.buildWavePrintResult({
|
||
waveRows,
|
||
orderRows,
|
||
hitWaveIds: validWaveIds,
|
||
missingWaveIds,
|
||
filteredWaveIds,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 获取波次平台打印数据中间态。
|
||
*
|
||
* 输出以波次分组为主结构(waveGroups),并在波次内按平台分组,
|
||
* 便于上游按「波次 -> 平台 -> 订单」层级批量发起打印。
|
||
*
|
||
* @param {Object} params 请求参数。
|
||
* @param {Array<number|string>} params.waveIds 波次ID数组。
|
||
* @param {number|string} params.warehouseId 仓库ID。
|
||
* @return {Promise<Object>} 平台打印中间态结果。
|
||
*/
|
||
async getWavePlatformPrintData(params = {}) {
|
||
const requestParams = this.isPlainObject(params) ? params : {};
|
||
const {
|
||
waveIds,
|
||
warehouseId,
|
||
} = requestParams;
|
||
|
||
const normalizedWaveIds = this.normalizeWaveIds(waveIds);
|
||
if (normalizedWaveIds.length === 0) {
|
||
throw new Error('wave_ids 必填,且必须为非空数组');
|
||
}
|
||
|
||
const normalizedWarehouseId = this.resolveWarehouseId(warehouseId);
|
||
const waveRows = await this.queryWavesByIds(normalizedWarehouseId, normalizedWaveIds);
|
||
if (waveRows.length === 0) {
|
||
return {
|
||
summary: {
|
||
total_waves: 0,
|
||
total_orders: 0,
|
||
total_platforms: 0,
|
||
locked_count: 0,
|
||
total_locked_orders: 0,
|
||
},
|
||
waveGroups: [],
|
||
locked_wave_groups: [],
|
||
wave_ids: [],
|
||
locked_count: 0,
|
||
locked_orders: [],
|
||
ext: {
|
||
missing_wave_ids: normalizedWaveIds,
|
||
filtered_wave_ids: [],
|
||
},
|
||
};
|
||
}
|
||
|
||
const hitWaveIdSet = new Set(waveRows.map(row => Number(row.wave_id)));
|
||
const missingWaveIds = normalizedWaveIds.filter(waveId => !hitWaveIdSet.has(waveId));
|
||
const hitWaveIds = normalizedWaveIds.filter(waveId => hitWaveIdSet.has(waveId));
|
||
const orderRows = await this.queryOrdersByWaveIds(hitWaveIds, normalizedWarehouseId);
|
||
const {
|
||
validWaveIds,
|
||
filteredWaveIds,
|
||
} = this.filterFullyAssignedExpressWaves(hitWaveIds, orderRows);
|
||
const validWaveIdSet = new Set(validWaveIds);
|
||
const validOrderRows = orderRows.filter(order => validWaveIdSet.has(Number(order && order.wave_id || 0)));
|
||
const lockedOrderRows = validOrderRows.filter(orderRow => this.isOrderLocked(orderRow));
|
||
const unlockedOrderRows = validOrderRows.filter(orderRow => !this.isOrderLocked(orderRow));
|
||
const lockedOrders = lockedOrderRows
|
||
.map(orderRow => ({
|
||
order_id: Number(orderRow && orderRow.id || 0),
|
||
order_no: String(orderRow && (orderRow.delivery_order_code || orderRow.source_order_codes) || '').trim(),
|
||
wave_id: Number(orderRow && orderRow.wave_id || 0),
|
||
wave_no: String(orderRow && orderRow.wave_no || '').trim(),
|
||
print_lock_status: String(orderRow && orderRow.print_lock_status || '').trim() || 'none',
|
||
status: 'locked',
|
||
status_text: '已锁定',
|
||
}));
|
||
|
||
const lockedWaveIds = Array.from(new Set(lockedOrderRows
|
||
.map(row => Number(row && row.wave_id || 0))
|
||
.filter(waveId => Number.isInteger(waveId) && waveId > 0)));
|
||
const lockedOrderPrintList = lockedOrderRows.map(orderRow => {
|
||
const platformCode = this.resolvePrintPlatformCode(orderRow, {});
|
||
return this.buildLockedOrderPlatformPrintItem({
|
||
orderRow,
|
||
platformCode,
|
||
});
|
||
});
|
||
const lockedWaveGroups = this.groupOrderPrintItemsByWaveAndPlatform({
|
||
waveRows,
|
||
hitWaveIds: lockedWaveIds,
|
||
orderPrintList: lockedOrderPrintList,
|
||
});
|
||
|
||
const validOrderWaveIds = Array.from(new Set(unlockedOrderRows
|
||
.map(row => Number(row && row.wave_id || 0))
|
||
.filter(waveId => Number.isInteger(waveId) && waveId > 0)));
|
||
|
||
if (unlockedOrderRows.length === 0) {
|
||
return {
|
||
summary: {
|
||
total_waves: 0,
|
||
total_orders: 0,
|
||
total_platforms: 0,
|
||
locked_count: lockedOrders.length,
|
||
total_locked_orders: lockedOrders.length,
|
||
},
|
||
waveGroups: [],
|
||
locked_wave_groups: lockedWaveGroups,
|
||
wave_ids: validWaveIds,
|
||
locked_count: lockedOrders.length,
|
||
locked_orders: lockedOrders,
|
||
ext: {
|
||
missing_wave_ids: missingWaveIds,
|
||
filtered_wave_ids: filteredWaveIds,
|
||
},
|
||
};
|
||
}
|
||
|
||
const orderIds = unlockedOrderRows
|
||
.map(row => Number(row && row.id || 0))
|
||
.filter(orderId => Number.isInteger(orderId) && orderId > 0);
|
||
const orderExpressRows = await this.queryOrderExpressByOrderIds(orderIds);
|
||
this.assertBusinessWaybillCompleteness(orderIds, orderExpressRows);
|
||
const cainiaoEnrichedOrderExpressRows = await this.enrichCainiaoOrderExpressRows(
|
||
unlockedOrderRows,
|
||
orderExpressRows,
|
||
normalizedWarehouseId
|
||
);
|
||
const jdEnrichedOrderExpressRows = await this.enrichJdOrderExpressRows(
|
||
unlockedOrderRows,
|
||
cainiaoEnrichedOrderExpressRows,
|
||
normalizedWarehouseId
|
||
);
|
||
const enrichedOrderExpressRows = await this.enrichPddDyOrderExpressRows(
|
||
unlockedOrderRows,
|
||
jdEnrichedOrderExpressRows,
|
||
normalizedWarehouseId
|
||
);
|
||
const orderExpressMap = this.buildOrderExpressMap(enrichedOrderExpressRows);
|
||
const policyConfigMap = await this.getPolicyConfigMapByStore(unlockedOrderRows, normalizedWarehouseId);
|
||
const pickingCandidateRows = unlockedOrderRows.filter(orderRow => {
|
||
const storeId = Number(orderRow && orderRow.store_id || 0);
|
||
const policyConfig = policyConfigMap.get(storeId) || {};
|
||
return this.shouldLoadPickingDetails(policyConfig);
|
||
});
|
||
const printOrderRowMap = await this.buildPrintOrderRowMapWithPicking(pickingCandidateRows, normalizedWarehouseId);
|
||
const waveOrderIndexMap = await this.queryWaveOrderIndexMapByOrderIds(
|
||
orderIds,
|
||
normalizedWarehouseId,
|
||
validOrderWaveIds
|
||
);
|
||
const waveIdsForCount = validOrderWaveIds;
|
||
const waveTotalOrderCountMap = await this.queryWaveTotalOrderCountMap(waveIdsForCount, normalizedWarehouseId);
|
||
const templateSampleCache = new Map();
|
||
const orderPrintList = [];
|
||
|
||
for (const orderRow of unlockedOrderRows) {
|
||
const orderId = Number(orderRow && orderRow.id || 0);
|
||
if (!Number.isInteger(orderId) || orderId <= 0) {
|
||
continue;
|
||
}
|
||
|
||
const orderExpress = orderExpressMap.get(orderId) || {};
|
||
const effectiveOrderRow = printOrderRowMap.get(orderId) || orderRow;
|
||
const waveOrderIndexInfo = waveOrderIndexMap.get(orderId) || {};
|
||
const waveIdForCount = Number(effectiveOrderRow.wave_id || orderRow.wave_id || waveOrderIndexInfo.wave_id || 0);
|
||
const waveTotalOrders = Number(waveTotalOrderCountMap.get(waveIdForCount) || 0);
|
||
const waveIndex = Number(waveOrderIndexInfo.wave_index || 0);
|
||
const platformsIndex = Number(waveOrderIndexInfo.platforms_index || 0);
|
||
const effectiveOrderRowWithWaveIndex = {
|
||
...effectiveOrderRow,
|
||
wave_total_orders: waveTotalOrders > 0 ? waveTotalOrders : 0,
|
||
wave_index: waveIndex > 0 ? waveIndex : 0,
|
||
platforms_index: platformsIndex > 0 ? platformsIndex : 0,
|
||
};
|
||
const storeId = Number(orderRow && orderRow.store_id || 0);
|
||
const policyConfig = policyConfigMap.get(storeId) || {};
|
||
const platformCode = this.resolvePrintPlatformCode(effectiveOrderRow, orderExpress);
|
||
const templateSample = this.loadTemplateSampleByPlatform(platformCode, templateSampleCache);
|
||
|
||
orderPrintList.push(this.buildOrderPlatformPrintItem({
|
||
orderRow: effectiveOrderRowWithWaveIndex,
|
||
orderExpress,
|
||
policyConfig,
|
||
platformCode,
|
||
templateSample,
|
||
}));
|
||
}
|
||
|
||
const waveGroups = this.groupOrderPrintItemsByWaveAndPlatform({
|
||
waveRows,
|
||
hitWaveIds: validOrderWaveIds,
|
||
orderPrintList,
|
||
});
|
||
const totalPlatforms = waveGroups.reduce((sum, waveGroup) => {
|
||
return sum + Number(waveGroup && waveGroup.platforms && waveGroup.platforms.length || 0);
|
||
}, 0);
|
||
|
||
return {
|
||
summary: {
|
||
total_waves: waveGroups.length,
|
||
total_orders: orderPrintList.length,
|
||
total_platforms: totalPlatforms,
|
||
locked_count: lockedOrders.length,
|
||
total_locked_orders: lockedOrders.length,
|
||
},
|
||
waveGroups,
|
||
locked_wave_groups: lockedWaveGroups,
|
||
wave_ids: validWaveIds,
|
||
locked_count: lockedOrders.length,
|
||
locked_orders: lockedOrders,
|
||
ext: {
|
||
missing_wave_ids: missingWaveIds,
|
||
filtered_wave_ids: filteredWaveIds,
|
||
},
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 规范化“按分组解锁”规则。
|
||
*
|
||
* @param {Object} payload 规则入参。
|
||
* @param {Array<Object>} payload.groups 分组条件原始列表。
|
||
* @param {string} payload.groupType 分组类型。
|
||
* @param {string} payload.unlockScope 解锁范围。
|
||
* @param {Array<number>} payload.validWaveIds 有效波次ID列表。
|
||
* @return {Array<Object>} 规范化后的分组规则列表。
|
||
*/
|
||
normalizeUnlockGroupRules(payload = {}) {
|
||
const requestPayload = this.isPlainObject(payload) ? payload : {};
|
||
const groups = Array.isArray(requestPayload.groups) ? requestPayload.groups : [];
|
||
const groupType = String(requestPayload.groupType || '').trim();
|
||
const unlockScope = String(requestPayload.unlockScope || 'group').trim();
|
||
const validWaveIds = Array.isArray(requestPayload.validWaveIds) ? requestPayload.validWaveIds : [];
|
||
const validWaveIdSet = new Set(validWaveIds.map(waveId => Number(waveId || 0)));
|
||
const normalizedRules = [];
|
||
const dedupeKeySet = new Set();
|
||
|
||
for (const rawGroup of groups) {
|
||
if (!this.isPlainObject(rawGroup)) {
|
||
continue;
|
||
}
|
||
|
||
const rawWaveId = rawGroup.wave_id ?? rawGroup.waveId;
|
||
const waveId = Number(String(rawWaveId ?? '').trim());
|
||
if (!Number.isInteger(waveId) || waveId <= 0 || !validWaveIdSet.has(waveId)) {
|
||
continue;
|
||
}
|
||
|
||
const rawPlatform = String(rawGroup.platform ?? rawGroup.group_key ?? rawGroup.groupKey ?? '').trim();
|
||
const normalizedPlatformAlias = PrinterDataBuilder.normalizePlatformAlias(rawPlatform);
|
||
const platform = String(normalizedPlatformAlias && normalizedPlatformAlias.platform || rawPlatform).trim().toLowerCase();
|
||
const sysLogisticsCode = String(rawGroup.sys_logistics_code ?? rawGroup.sysLogisticsCode ?? '').trim().toLowerCase();
|
||
const orderIdSet = new Set(Array.isArray(rawGroup.order_ids || rawGroup.orderIds)
|
||
? (rawGroup.order_ids || rawGroup.orderIds)
|
||
.map(orderId => Number(String(orderId ?? '').trim()))
|
||
.filter(orderId => Number.isInteger(orderId) && orderId > 0)
|
||
: []);
|
||
|
||
if (unlockScope !== 'wave') {
|
||
if (groupType === 'platform' && !platform) {
|
||
continue;
|
||
}
|
||
|
||
if (groupType === 'platform_express' && (!platform || !sysLogisticsCode)) {
|
||
continue;
|
||
}
|
||
|
||
if (groupType === 'order' && orderIdSet.size === 0) {
|
||
continue;
|
||
}
|
||
}
|
||
|
||
const dedupeKey = `${waveId}@@${groupType}@@${unlockScope}@@${platform}@@${sysLogisticsCode}@@${Array.from(orderIdSet).sort((a, b) => a - b).join(',')}`;
|
||
if (dedupeKeySet.has(dedupeKey)) {
|
||
continue;
|
||
}
|
||
|
||
dedupeKeySet.add(dedupeKey);
|
||
normalizedRules.push({
|
||
waveId,
|
||
platform,
|
||
sysLogisticsCode,
|
||
orderIdSet,
|
||
});
|
||
}
|
||
|
||
return normalizedRules;
|
||
}
|
||
|
||
/**
|
||
* 判断订单是否命中“按分组解锁”规则。
|
||
*
|
||
* @param {Object} payload 匹配入参。
|
||
* @param {Object} payload.orderRow 订单行。
|
||
* @param {Object} payload.rule 分组规则。
|
||
* @param {string} payload.groupType 分组类型。
|
||
* @param {string} payload.unlockScope 解锁范围。
|
||
* @return {boolean} 是否命中规则。
|
||
*/
|
||
isOrderMatchedByUnlockGroupRule(payload = {}) {
|
||
const requestPayload = this.isPlainObject(payload) ? payload : {};
|
||
const orderRow = this.isPlainObject(requestPayload.orderRow) ? requestPayload.orderRow : {};
|
||
const rule = this.isPlainObject(requestPayload.rule) ? requestPayload.rule : {};
|
||
const groupType = String(requestPayload.groupType || '').trim();
|
||
const unlockScope = String(requestPayload.unlockScope || 'group').trim();
|
||
|
||
const orderWaveId = Number(orderRow && orderRow.wave_id || 0);
|
||
const ruleWaveId = Number(rule && rule.waveId || 0);
|
||
if (!Number.isInteger(orderWaveId) || orderWaveId <= 0 || orderWaveId !== ruleWaveId) {
|
||
return false;
|
||
}
|
||
|
||
if (unlockScope === 'wave') {
|
||
return true;
|
||
}
|
||
|
||
const orderId = Number(orderRow && orderRow.id || 0);
|
||
const orderIdSet = rule.orderIdSet instanceof Set ? rule.orderIdSet : new Set();
|
||
if (groupType === 'order') {
|
||
return orderIdSet.has(orderId);
|
||
}
|
||
|
||
const orderPlatformAlias = PrinterDataBuilder.normalizePlatformAlias(this.resolvePrintPlatformCode(orderRow, {}));
|
||
const orderPlatform = String(orderPlatformAlias && orderPlatformAlias.platform || '').trim().toLowerCase();
|
||
if (orderPlatform !== String(rule.platform || '').trim().toLowerCase()) {
|
||
return false;
|
||
}
|
||
|
||
if (groupType === 'platform_express') {
|
||
const orderSysLogisticsCode = String(orderRow && orderRow.sys_logistics_code || '').trim().toLowerCase();
|
||
if (!orderSysLogisticsCode || orderSysLogisticsCode !== String(rule.sysLogisticsCode || '').trim().toLowerCase()) {
|
||
return false;
|
||
}
|
||
}
|
||
|
||
if (orderIdSet.size > 0 && !orderIdSet.has(orderId)) {
|
||
return false;
|
||
}
|
||
|
||
return true;
|
||
}
|
||
|
||
/**
|
||
* 按分组解锁波次平台打印锁。
|
||
*
|
||
* @param {Object} params 请求参数。
|
||
* @param {Array<number|string>} params.waveIds 波次ID数组。
|
||
* @param {number|string} params.warehouseId 仓库ID。
|
||
* @param {string} params.groupType 分组类型。
|
||
* @param {string} params.unlockScope 解锁范围。
|
||
* @param {Array<Object>} params.groups 分组条件。
|
||
* @return {Promise<Object>} 解锁结果。
|
||
*/
|
||
async unlockWavePlatformPrintDataByGroup(params = {}) {
|
||
const requestParams = this.isPlainObject(params) ? params : {};
|
||
const {
|
||
waveIds,
|
||
warehouseId,
|
||
groupType,
|
||
unlockScope,
|
||
groups,
|
||
} = requestParams;
|
||
|
||
const normalizedWaveIds = this.normalizeWaveIds(waveIds);
|
||
if (normalizedWaveIds.length === 0) {
|
||
throw new Error('wave_ids 必填,且必须为非空数组');
|
||
}
|
||
|
||
const normalizedWarehouseId = this.resolveWarehouseId(warehouseId);
|
||
const waveRows = await this.queryWavesByIds(normalizedWarehouseId, normalizedWaveIds);
|
||
if (waveRows.length === 0) {
|
||
return {
|
||
summary: {
|
||
total_waves: 0,
|
||
total_locked_orders: 0,
|
||
matched_group_orders: 0,
|
||
unlocked_count: 0,
|
||
},
|
||
wave_ids: [],
|
||
unlocked_order_ids: [],
|
||
ext: {
|
||
missing_wave_ids: normalizedWaveIds,
|
||
filtered_wave_ids: [],
|
||
},
|
||
};
|
||
}
|
||
|
||
const hitWaveIdSet = new Set(waveRows.map(row => Number(row.wave_id)));
|
||
const missingWaveIds = normalizedWaveIds.filter(waveId => !hitWaveIdSet.has(waveId));
|
||
const hitWaveIds = normalizedWaveIds.filter(waveId => hitWaveIdSet.has(waveId));
|
||
const orderRows = await this.queryOrdersByWaveIds(hitWaveIds, normalizedWarehouseId);
|
||
const {
|
||
validWaveIds,
|
||
filteredWaveIds,
|
||
} = this.filterFullyAssignedExpressWaves(hitWaveIds, orderRows);
|
||
const validWaveIdSet = new Set(validWaveIds);
|
||
|
||
const lockedOrderRows = orderRows.filter(orderRow => {
|
||
const orderWaveId = Number(orderRow && orderRow.wave_id || 0);
|
||
return validWaveIdSet.has(orderWaveId) && this.isOrderLocked(orderRow);
|
||
});
|
||
|
||
if (lockedOrderRows.length === 0) {
|
||
return {
|
||
summary: {
|
||
total_waves: validWaveIds.length,
|
||
total_locked_orders: 0,
|
||
matched_group_orders: 0,
|
||
unlocked_count: 0,
|
||
},
|
||
wave_ids: validWaveIds,
|
||
unlocked_order_ids: [],
|
||
ext: {
|
||
missing_wave_ids: missingWaveIds,
|
||
filtered_wave_ids: filteredWaveIds,
|
||
},
|
||
};
|
||
}
|
||
|
||
const normalizedRules = this.normalizeUnlockGroupRules({
|
||
groups,
|
||
groupType,
|
||
unlockScope,
|
||
validWaveIds,
|
||
});
|
||
if (normalizedRules.length === 0) {
|
||
throw new Error('groups 未匹配到有效的分组解锁条件');
|
||
}
|
||
|
||
const matchedOrderRows = lockedOrderRows.filter(orderRow => {
|
||
return normalizedRules.some(rule => this.isOrderMatchedByUnlockGroupRule({
|
||
orderRow,
|
||
rule,
|
||
groupType,
|
||
unlockScope,
|
||
}));
|
||
});
|
||
const matchedOrderIds = Array.from(new Set(matchedOrderRows
|
||
.map(orderRow => Number(orderRow && orderRow.id || 0))
|
||
.filter(orderId => Number.isInteger(orderId) && orderId > 0)));
|
||
|
||
if (matchedOrderIds.length === 0) {
|
||
return {
|
||
summary: {
|
||
total_waves: validWaveIds.length,
|
||
total_locked_orders: lockedOrderRows.length,
|
||
matched_group_orders: 0,
|
||
unlocked_count: 0,
|
||
},
|
||
wave_ids: validWaveIds,
|
||
unlocked_order_ids: [],
|
||
ext: {
|
||
missing_wave_ids: missingWaveIds,
|
||
filtered_wave_ids: filteredWaveIds,
|
||
},
|
||
};
|
||
}
|
||
|
||
const orderModel = await this.getOrderModel('order', normalizedWarehouseId);
|
||
const updateResult = await orderModel.update({
|
||
print_lock_status: 'none',
|
||
}, {
|
||
where: {
|
||
id: {
|
||
[Op.in]: matchedOrderIds,
|
||
},
|
||
print_lock_status: {
|
||
[Op.ne]: 'none',
|
||
},
|
||
},
|
||
});
|
||
|
||
const unlockedCount = Number(Array.isArray(updateResult) ? updateResult[0] : updateResult) || 0;
|
||
// 尝试写入操作日志(非阻塞,不影响主流程)
|
||
try {
|
||
const operationLogService = this.service && this.service.systems && this.service.systems.operationLog;
|
||
const operator = this.getOrderLogOperator();
|
||
const warehouseIdForLog = this.getOrderLogWarehouseId(normalizedWarehouseId) || normalizedWarehouseId;
|
||
|
||
const rawGroupsText = (() => {
|
||
try {
|
||
return JSON.stringify(Array.isArray(groups) ? groups : []);
|
||
} catch (e) {
|
||
return '';
|
||
}
|
||
})();
|
||
|
||
// 截断 groups 描述为合理长度,避免 message 过长
|
||
const truncatedGroups = String(rawGroupsText || '').slice(0, 200);
|
||
const baseNote = `按分组解锁 groupType=${String(groupType || '')} groups=${truncatedGroups}`;
|
||
|
||
const payloads = matchedOrderRows.map(orderRow => {
|
||
const orderId = Number(orderRow && orderRow.id || 0);
|
||
const waveId = Number(orderRow && orderRow.wave_id || 0);
|
||
const waveNo = String(orderRow && orderRow.wave_no || '').trim();
|
||
|
||
const note = `${baseNote} wave_id=${waveId} wave_no=${waveNo}`;
|
||
|
||
return {
|
||
businessType: 'order',
|
||
businessId: orderId,
|
||
operationCode: 'unlock_by_group',
|
||
operator: {
|
||
id: operator && operator.id ? operator.id : (this.ctx.state?.user?.id || this.ctx.user?.id || 0),
|
||
name: operator && operator.name ? operator.name : (this.ctx.state?.user?.real_name || this.ctx.user?.name || 'system'),
|
||
},
|
||
extras: {
|
||
warehouseId: warehouseIdForLog,
|
||
externalLogType: 'REQUEST',
|
||
externalLogId: null,
|
||
// 额外信息放入 message 中以便在表中检索;表结构暂无专门 trace 字段
|
||
message: JSON.stringify({
|
||
source: 'order.print.unlockWavePlatformPrintDataByGroup',
|
||
trace_id: this.ctx.requestId || this.ctx.traceId || null,
|
||
note,
|
||
}),
|
||
},
|
||
beforeChanges: null,
|
||
};
|
||
}).filter(item => item && Number(item.businessId) > 0);
|
||
|
||
if (operationLogService && typeof operationLogService.createOperationLogs === 'function' && payloads.length > 0) {
|
||
// 为性能考虑,若太多则分批(每批 100 条)并发写入
|
||
const BATCH_SIZE = 100;
|
||
for (let i = 0; i < payloads.length; i += BATCH_SIZE) {
|
||
const batch = payloads.slice(i, i + BATCH_SIZE);
|
||
// 不等待所有批次顺序完成,改为并发触发但捕获错误
|
||
// 这里仍然 await,以保证在单请求内完成写入,但不会抛出影响主逻辑的异常
|
||
try {
|
||
await operationLogService.createOperationLogs(batch);
|
||
} catch (err) {
|
||
this.ctx.logger.warn('[orderPrint.unlockWavePlatformPrintDataByGroup] 写入操作日志失败,不影响业务', err);
|
||
}
|
||
}
|
||
}
|
||
} catch (logErr) {
|
||
this.ctx.logger.warn('[orderPrint.unlockWavePlatformPrintDataByGroup] 写入操作日志失败(全局捕获),不影响业务', logErr);
|
||
}
|
||
|
||
return {
|
||
summary: {
|
||
total_waves: validWaveIds.length,
|
||
total_locked_orders: lockedOrderRows.length,
|
||
matched_group_orders: matchedOrderIds.length,
|
||
unlocked_count: unlockedCount > 0 ? unlockedCount : 0,
|
||
},
|
||
wave_ids: validWaveIds,
|
||
unlocked_order_ids: matchedOrderIds,
|
||
unlocked_orders: matchedOrderRows.map(orderRow => ({
|
||
order_id: Number(orderRow && orderRow.id || 0),
|
||
wave_id: Number(orderRow && orderRow.wave_id || 0),
|
||
wave_no: String(orderRow && orderRow.wave_no || '').trim(),
|
||
order_no: String(orderRow && (orderRow.delivery_order_code || orderRow.source_order_codes) || '').trim(),
|
||
})),
|
||
ext: {
|
||
missing_wave_ids: missingWaveIds,
|
||
filtered_wave_ids: filteredWaveIds,
|
||
},
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 规范化波次ID数组(去重与数字化)。
|
||
*
|
||
* @param {Array<number|string>} waveIds 原始波次ID数组。
|
||
* @return {Array<number>} 规范化后的波次ID数组。
|
||
*/
|
||
normalizeWaveIds(waveIds = []) {
|
||
if (!Array.isArray(waveIds)) {
|
||
return [];
|
||
}
|
||
|
||
const normalizedSet = new Set();
|
||
|
||
for (const rawId of waveIds) {
|
||
const normalizedId = Number(String(rawId ?? '').trim());
|
||
if (Number.isInteger(normalizedId) && normalizedId > 0) {
|
||
normalizedSet.add(normalizedId);
|
||
}
|
||
}
|
||
|
||
return Array.from(normalizedSet);
|
||
}
|
||
|
||
/**
|
||
* 解析并校验仓库ID。
|
||
*
|
||
* @param {number|string} warehouseId 入参仓库ID。
|
||
* @return {number} 规范化后的仓库ID。
|
||
*/
|
||
resolveWarehouseId(warehouseId) {
|
||
const contextWarehouseId = Number(this.getWarehouseId() || 0);
|
||
if (!Number.isInteger(contextWarehouseId) || contextWarehouseId <= 0) {
|
||
throw new Error('缺少当前用户仓库上下文 store_id');
|
||
}
|
||
|
||
const normalizedWarehouseId = Number(String(warehouseId ?? '').trim());
|
||
if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) {
|
||
throw new Error('warehouse_id 必填且必须为正整数');
|
||
}
|
||
|
||
if (normalizedWarehouseId !== contextWarehouseId) {
|
||
throw new Error('warehouse_id 必须与当前用户上下文 store_id 保持一致');
|
||
}
|
||
|
||
return normalizedWarehouseId;
|
||
}
|
||
|
||
/**
|
||
* 按波次ID批量查询波次信息。
|
||
*
|
||
* @param {number} warehouseId 仓库ID。
|
||
* @param {Array<number>} waveIds 波次ID数组。
|
||
* @return {Promise<Array<Object>>} 波次基础信息。
|
||
*/
|
||
async queryWavesByIds(warehouseId, waveIds = []) {
|
||
if (!Array.isArray(waveIds) || waveIds.length === 0) {
|
||
return [];
|
||
}
|
||
|
||
const querySql = `
|
||
SELECT wave_id, wave_no
|
||
FROM wms_wave_batch
|
||
WHERE warehouse_id = :warehouseId
|
||
AND wave_id IN (:waveIds)
|
||
AND wave_status <> -1
|
||
`;
|
||
|
||
const rows = await this.ctx.model.query(querySql, {
|
||
replacements: {
|
||
warehouseId,
|
||
waveIds,
|
||
},
|
||
type: this.ctx.model.QueryTypes.SELECT,
|
||
});
|
||
|
||
return Array.isArray(rows) ? rows : [];
|
||
}
|
||
|
||
/**
|
||
* 按波次ID批量查询订单明细。
|
||
*
|
||
* @param {Array<number>} waveIds 波次ID数组。
|
||
* @param {number} warehouseId 仓库ID。
|
||
* @return {Promise<Array<Object>>} 订单明细列表。
|
||
*/
|
||
async queryOrdersByWaveIds(waveIds = [], warehouseId) {
|
||
if (!Array.isArray(waveIds) || waveIds.length === 0) {
|
||
return [];
|
||
}
|
||
|
||
const orderModel = await this.getOrderModel('order', warehouseId);
|
||
const rows = await orderModel.findAll({
|
||
attributes: [
|
||
'id',
|
||
'delivery_order_code',
|
||
'source_order_codes',
|
||
'warehouse_id',
|
||
'store_id',
|
||
'wave_id',
|
||
'wave_no',
|
||
'name',
|
||
'tel',
|
||
'mobile',
|
||
'province',
|
||
'city',
|
||
'area',
|
||
'town',
|
||
'detail_address',
|
||
'zip_code',
|
||
'items',
|
||
'source_platform_code',
|
||
'sys_platform_code',
|
||
'sys_platform_name',
|
||
'logistics_code',
|
||
'logistics_name',
|
||
'sys_logistics_code',
|
||
'sys_logistics_name',
|
||
'post_status',
|
||
'status',
|
||
'outbound_status',
|
||
'print_status',
|
||
'lock_status',
|
||
'print_lock_status',
|
||
'items_count',
|
||
'items_total',
|
||
'items_weight',
|
||
'freight',
|
||
'create_at',
|
||
'pay_time',
|
||
],
|
||
where: {
|
||
wave_id: {
|
||
[Op.in]: waveIds,
|
||
},
|
||
},
|
||
order: [[ 'wave_id', 'ASC' ], [ 'id', 'ASC' ]],
|
||
raw: true,
|
||
});
|
||
|
||
return Array.isArray(rows) ? rows : [];
|
||
}
|
||
|
||
/**
|
||
* 按订单ID批量查询快递单信息。
|
||
*
|
||
* @param {Array<number>} orderIds 订单ID数组。
|
||
* @return {Promise<Array<Object>>} 快递单信息列表。
|
||
*/
|
||
/**
|
||
* 根据订单 ID 列表批量查询运单记录。
|
||
* 返回 business_key=1 的主运单,按 order_id、business_key、id 升序排列。
|
||
*
|
||
* @param {number[]} orderIds 订单 ID 列表。
|
||
* @returns {Promise<Array<Object>>} 匹配的运单记录数组,字段包含 id、order_id、business_key、waybill_code、
|
||
* logistics_code、logistics_name、logistics_interface_id、logistics_interface_name、platform_code、
|
||
* warehouse_id、printinfo、signature、encryptprintinfo、ver。
|
||
*/
|
||
async queryOrderExpressByOrderIds(orderIds = []) {
|
||
if (!Array.isArray(orderIds) || orderIds.length === 0) {
|
||
return [];
|
||
}
|
||
|
||
const normalizedOrderIds = Array.from(new Set(orderIds
|
||
.map(id => Number(id))
|
||
.filter(id => Number.isInteger(id) && id > 0)));
|
||
if (normalizedOrderIds.length === 0) {
|
||
return [];
|
||
}
|
||
|
||
const rows = await this.ctx.model.OrderExpress.findAll({
|
||
attributes: [
|
||
'id',
|
||
'order_id',
|
||
'business_key',
|
||
'waybill_code',
|
||
'logistics_code',
|
||
'logistics_name',
|
||
'logistics_interface_id',
|
||
'logistics_interface_name',
|
||
'platform_code',
|
||
'warehouse_id',
|
||
'printinfo',
|
||
'signature',
|
||
'encryptprintinfo',
|
||
'ver',
|
||
],
|
||
where: {
|
||
order_id: {
|
||
[Op.in]: normalizedOrderIds,
|
||
},
|
||
business_key: 1,
|
||
},
|
||
order: [[ 'order_id', 'ASC' ], [ 'business_key', 'ASC' ], [ 'id', 'ASC' ]],
|
||
raw: true,
|
||
});
|
||
|
||
return Array.isArray(rows) ? rows : [];
|
||
}
|
||
|
||
/**
|
||
* 按订单ID批量查询波次顺序信息。
|
||
*
|
||
* 数据来源:wms_order_wave_index。
|
||
* 当 query 能力不可用、SQL 执行失败或无数据时,优雅降级返回空映射。
|
||
*
|
||
* @param {Array<number>} orderIds 订单ID数组。
|
||
* @param {number} warehouseId 仓库ID。
|
||
* @param {Array<number>} [waveIds] 可选波次ID数组,用于限制查询范围。
|
||
* @return {Promise<Map<number, {wave_id:number, wave_index:number, platforms_index:number}>>} 订单顺序映射。
|
||
*/
|
||
async queryWaveOrderIndexMapByOrderIds(orderIds = [], warehouseId, waveIds = []) {
|
||
const resultMap = new Map();
|
||
const normalizedOrderIds = Array.from(new Set((Array.isArray(orderIds) ? orderIds : [])
|
||
.map(id => Number(id))
|
||
.filter(id => Number.isInteger(id) && id > 0)));
|
||
const normalizedWaveIds = Array.from(new Set((Array.isArray(waveIds) ? waveIds : [])
|
||
.map(id => Number(id))
|
||
.filter(id => Number.isInteger(id) && id > 0)));
|
||
|
||
if (normalizedOrderIds.length === 0) {
|
||
return resultMap;
|
||
}
|
||
|
||
const queryMethod = this.ctx.model && this.ctx.model.query;
|
||
if (typeof queryMethod !== 'function') {
|
||
return resultMap;
|
||
}
|
||
|
||
const waveFilterSql = normalizedWaveIds.length > 0
|
||
? ' AND wave_id IN (:waveIds)\n'
|
||
: '';
|
||
const querySql = `
|
||
SELECT order_id, wave_id, wave_index, platforms_index
|
||
FROM wms_order_wave_index
|
||
WHERE warehouse_id = :warehouseId
|
||
AND order_id IN (:orderIds)
|
||
${waveFilterSql}
|
||
`;
|
||
|
||
try {
|
||
const rows = await queryMethod.call(this.ctx.model, querySql, {
|
||
replacements: {
|
||
warehouseId,
|
||
orderIds: normalizedOrderIds,
|
||
...(normalizedWaveIds.length > 0 ? { waveIds: normalizedWaveIds } : {}),
|
||
},
|
||
type: this.ctx.model.QueryTypes && this.ctx.model.QueryTypes.SELECT,
|
||
});
|
||
|
||
for (const row of Array.isArray(rows) ? rows : []) {
|
||
const orderId = Number(row && row.order_id || 0);
|
||
if (!Number.isInteger(orderId) || orderId <= 0) {
|
||
continue;
|
||
}
|
||
|
||
resultMap.set(orderId, {
|
||
wave_id: Number(row && row.wave_id || 0),
|
||
wave_index: Number(row && row.wave_index || 0),
|
||
platforms_index: Number(row && row.platforms_index || 0),
|
||
});
|
||
}
|
||
} catch (error) {
|
||
this.ctx.logger.warn(
|
||
`[orderPrint.queryWaveOrderIndexMapByOrderIds] 查询失败 warehouseId=${warehouseId} message=${error.message}`
|
||
);
|
||
}
|
||
|
||
return resultMap;
|
||
}
|
||
|
||
/**
|
||
* 按波次ID批量查询波次总订单数。
|
||
*
|
||
* 数据来源:wms_order_wave_index。
|
||
* 当 query 能力不可用、SQL 执行失败或无数据时,优雅降级返回空映射。
|
||
*
|
||
* @param {Array<number>} waveIds 波次ID数组。
|
||
* @param {number} warehouseId 仓库ID。
|
||
* @return {Promise<Map<number, number>>} 波次ID到总订单数映射。
|
||
*/
|
||
async queryWaveTotalOrderCountMap(waveIds = [], warehouseId) {
|
||
const resultMap = new Map();
|
||
const normalizedWaveIds = Array.from(new Set((Array.isArray(waveIds) ? waveIds : [])
|
||
.map(id => Number(id))
|
||
.filter(id => Number.isInteger(id) && id > 0)));
|
||
|
||
if (normalizedWaveIds.length === 0) {
|
||
return resultMap;
|
||
}
|
||
|
||
const queryMethod = this.ctx.model && this.ctx.model.query;
|
||
if (typeof queryMethod !== 'function') {
|
||
return resultMap;
|
||
}
|
||
|
||
const querySql = `
|
||
SELECT wave_id, COUNT(1) AS total_orders
|
||
FROM wms_order_wave_index
|
||
WHERE warehouse_id = :warehouseId
|
||
AND wave_id IN (:waveIds)
|
||
GROUP BY wave_id
|
||
`;
|
||
|
||
try {
|
||
const rows = await queryMethod.call(this.ctx.model, querySql, {
|
||
replacements: {
|
||
warehouseId,
|
||
waveIds: normalizedWaveIds,
|
||
},
|
||
type: this.ctx.model.QueryTypes && this.ctx.model.QueryTypes.SELECT,
|
||
});
|
||
|
||
for (const row of Array.isArray(rows) ? rows : []) {
|
||
const waveId = Number(row && row.wave_id || 0);
|
||
if (!Number.isInteger(waveId) || waveId <= 0) {
|
||
continue;
|
||
}
|
||
|
||
const totalOrders = Number(row && row.total_orders || 0);
|
||
resultMap.set(waveId, totalOrders > 0 ? totalOrders : 0);
|
||
}
|
||
} catch (error) {
|
||
this.ctx.logger.warn(
|
||
`[orderPrint.queryWaveTotalOrderCountMap] 查询失败 warehouseId=${warehouseId} message=${error.message}`
|
||
);
|
||
}
|
||
|
||
return resultMap;
|
||
}
|
||
|
||
/**
|
||
* 校验业务ID为1的运单号数据完整性。
|
||
*
|
||
* @param {Array<number>} orderIds 订单ID数组。
|
||
* @param {Array<Object>} orderExpressRows 快递单查询结果。
|
||
*/
|
||
assertBusinessWaybillCompleteness(orderIds = [], orderExpressRows = []) {
|
||
const normalizedOrderIds = Array.from(new Set((Array.isArray(orderIds) ? orderIds : [])
|
||
.map(id => Number(id))
|
||
.filter(id => Number.isInteger(id) && id > 0)));
|
||
if (normalizedOrderIds.length === 0) {
|
||
return;
|
||
}
|
||
|
||
const validOrderIdSet = new Set();
|
||
const rows = Array.isArray(orderExpressRows) ? orderExpressRows : [];
|
||
for (const row of rows) {
|
||
const orderId = Number(row && row.order_id || 0);
|
||
if (!Number.isInteger(orderId) || orderId <= 0) {
|
||
continue;
|
||
}
|
||
|
||
const waybillCode = String(row && row.waybill_code || '').trim();
|
||
if (!waybillCode) {
|
||
continue;
|
||
}
|
||
|
||
validOrderIdSet.add(orderId);
|
||
}
|
||
|
||
const missingOrderIds = normalizedOrderIds.filter(orderId => !validOrderIdSet.has(orderId));
|
||
if (missingOrderIds.length > 0) {
|
||
throw new Error(`业务id为1的运单号数据缺失,缺失 order_id: ${missingOrderIds.join(',')}`);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 按订单ID构建快递信息映射,优先保留带运单号的记录。
|
||
*
|
||
* @param {Array<Object>} rows 快递数据行。
|
||
* @return {Map<number, Object>} 订单到快递信息的映射。
|
||
*/
|
||
buildOrderExpressMap(rows = []) {
|
||
const expressMap = new Map();
|
||
|
||
for (const row of rows) {
|
||
const orderId = Number(row && row.order_id || 0);
|
||
if (!Number.isInteger(orderId) || orderId <= 0) {
|
||
continue;
|
||
}
|
||
|
||
const previousRow = expressMap.get(orderId);
|
||
if (!previousRow) {
|
||
expressMap.set(orderId, row);
|
||
continue;
|
||
}
|
||
|
||
const previousWaybillCode = String(previousRow.waybill_code || '').trim();
|
||
const currentWaybillCode = String(row && row.waybill_code || '').trim();
|
||
if (!previousWaybillCode && currentWaybillCode) {
|
||
expressMap.set(orderId, row);
|
||
}
|
||
}
|
||
|
||
return expressMap;
|
||
}
|
||
|
||
/**
|
||
* 判断平台编码是否归一化为菜鸟。
|
||
*
|
||
* @param {string} platformCode 平台编码。
|
||
* @return {boolean} 是否为菜鸟平台。
|
||
*/
|
||
isCainiaoPlatformCode(platformCode = '') {
|
||
return PrinterDataBuilder.normalizePlatformAlias(platformCode).platform === 'cainiao';
|
||
}
|
||
|
||
/**
|
||
* 判断平台编码是否归一化为京东。
|
||
*
|
||
* @param {string} platformCode 平台编码。
|
||
* @return {boolean} 是否为京东平台。
|
||
*/
|
||
isJdPlatformCode(platformCode = '') {
|
||
return PrinterDataBuilder.normalizePlatformAlias(platformCode).platform === 'jd';
|
||
}
|
||
|
||
/**
|
||
* 判断平台编码是否归一化为拼多多。
|
||
*
|
||
* @param {string} platformCode 平台编码。
|
||
* @return {boolean} 是否为拼多多平台。
|
||
*/
|
||
isPddPlatformCode(platformCode = '') {
|
||
return PrinterDataBuilder.normalizePlatformAlias(platformCode).platform === 'pdd';
|
||
}
|
||
|
||
/**
|
||
* 判断平台编码是否归一化为抖音。
|
||
*
|
||
* @param {string} platformCode 平台编码。
|
||
* @return {boolean} 是否为抖音平台。
|
||
*/
|
||
isDouyinPlatformCode(platformCode = '') {
|
||
return PrinterDataBuilder.normalizePlatformAlias(platformCode).platform === 'douyin';
|
||
}
|
||
|
||
/**
|
||
* 收集菜鸟编码映射可能命中的快递编码候选项。
|
||
*
|
||
* 优先使用系统快递编码,其次兼容订单/运单上的物流编码,避免遗漏历史数据。
|
||
*
|
||
* @param {Object} orderRow 订单行。
|
||
* @param {Object} orderExpress 快递行。
|
||
* @return {Array<string>} 去重后的快递编码候选列表。
|
||
*/
|
||
collectCainiaoExpressLookupCodes(orderRow = {}, orderExpress = {}) {
|
||
const codeList = [];
|
||
const appendCode = value => {
|
||
const normalizedCode = String(value || '').trim();
|
||
if (!normalizedCode || codeList.includes(normalizedCode)) {
|
||
return;
|
||
}
|
||
|
||
codeList.push(normalizedCode);
|
||
};
|
||
|
||
appendCode(orderRow && orderRow.sys_logistics_code);
|
||
appendCode(orderExpress && orderExpress.logistics_code);
|
||
appendCode(orderRow && orderRow.logistics_code);
|
||
|
||
return codeList;
|
||
}
|
||
|
||
/**
|
||
* 批量查询快递基础资料中的菜鸟编码映射。
|
||
*
|
||
* @param {Array<string>} expressCodes 快递编码列表。
|
||
* @return {Promise<Map<string, string>>} 快递编码到菜鸟编码的映射。
|
||
*/
|
||
async queryCainiaoCpCodeMap(expressCodes = []) {
|
||
const expressModel = this.ctx.model && this.ctx.model.Express;
|
||
const normalizedCodes = Array.from(new Set((Array.isArray(expressCodes) ? expressCodes : [])
|
||
.map(code => String(code || '').trim())
|
||
.filter(Boolean)));
|
||
const cpCodeMap = new Map();
|
||
|
||
if (!expressModel || typeof expressModel.findAll !== 'function' || normalizedCodes.length === 0) {
|
||
return cpCodeMap;
|
||
}
|
||
|
||
const rows = await expressModel.findAll({
|
||
attributes: [ 'code', 'CAINIAO' ],
|
||
where: {
|
||
code: {
|
||
[Op.in]: normalizedCodes,
|
||
},
|
||
},
|
||
raw: true,
|
||
});
|
||
|
||
for (const row of Array.isArray(rows) ? rows : []) {
|
||
const code = String(row && row.code || '').trim();
|
||
const cainiaoCode = String(row && row.CAINIAO || '').trim();
|
||
if (!code || !cainiaoCode) {
|
||
continue;
|
||
}
|
||
|
||
cpCodeMap.set(code, cainiaoCode);
|
||
}
|
||
|
||
return cpCodeMap;
|
||
}
|
||
|
||
/**
|
||
* 读取仓库下菜鸟平台的快递接口配置列表。
|
||
*
|
||
* @param {number} warehouseId 仓库ID。
|
||
* @return {Promise<Array<Object>>} 接口配置列表。
|
||
*/
|
||
async queryCainiaoExpressInterfaceList(warehouseId) {
|
||
const expressInterfaceService = this.service
|
||
&& this.service.systems
|
||
&& this.service.systems.setting
|
||
&& this.service.systems.setting.expressInterface;
|
||
|
||
if (!expressInterfaceService || typeof expressInterfaceService.listByWarehousePlatformCode !== 'function') {
|
||
return [];
|
||
}
|
||
|
||
const result = await expressInterfaceService.listByWarehousePlatformCode({
|
||
warehouseId,
|
||
platformCode: 'CAINIAO',
|
||
});
|
||
|
||
return Array.isArray(result && result.data) ? result.data : [];
|
||
}
|
||
|
||
/**
|
||
* 读取仓库下京东平台的快递接口表配置列表。
|
||
*
|
||
* @param {number} warehouseId 仓库ID。
|
||
* @return {Promise<Array<Object>>} 接口配置列表。
|
||
*/
|
||
async queryJdExpressInterfaceList(warehouseId) {
|
||
const expressInterfaceService = this.service
|
||
&& this.service.systems
|
||
&& this.service.systems.setting
|
||
&& this.service.systems.setting.expressInterface;
|
||
|
||
if (!expressInterfaceService || typeof expressInterfaceService.listByWarehousePlatformCode !== 'function') {
|
||
return [];
|
||
}
|
||
|
||
const result = await expressInterfaceService.listByWarehousePlatformCode({
|
||
warehouseId,
|
||
platformCode: 'JD',
|
||
});
|
||
|
||
return Array.isArray(result && result.data) ? result.data : [];
|
||
}
|
||
|
||
/**
|
||
* 读取仓库下拼多多平台的快递接口表配置列表。
|
||
*
|
||
* @param {number} warehouseId 仓库ID。
|
||
* @return {Promise<Array<Object>>} 接口配置列表。
|
||
*/
|
||
async queryPddExpressInterfaceList(warehouseId) {
|
||
const expressInterfaceService = this.service
|
||
&& this.service.systems
|
||
&& this.service.systems.setting
|
||
&& this.service.systems.setting.expressInterface;
|
||
|
||
if (!expressInterfaceService || typeof expressInterfaceService.listByWarehousePlatformCode !== 'function') {
|
||
return [];
|
||
}
|
||
|
||
const result = await expressInterfaceService.listByWarehousePlatformCode({
|
||
warehouseId,
|
||
platformCode: 'PDD',
|
||
});
|
||
|
||
return Array.isArray(result && result.data) ? result.data : [];
|
||
}
|
||
|
||
/**
|
||
* 读取仓库下抖音平台的快递接口表配置列表。
|
||
*
|
||
* @param {number} warehouseId 仓库ID。
|
||
* @return {Promise<Array<Object>>} 接口配置列表。
|
||
*/
|
||
async queryDouyinExpressInterfaceList(warehouseId) {
|
||
const expressInterfaceService = this.service
|
||
&& this.service.systems
|
||
&& this.service.systems.setting
|
||
&& this.service.systems.setting.expressInterface;
|
||
|
||
if (!expressInterfaceService || typeof expressInterfaceService.listByWarehousePlatformCode !== 'function') {
|
||
return [];
|
||
}
|
||
|
||
const result = await expressInterfaceService.listByWarehousePlatformCode({
|
||
warehouseId,
|
||
platformCode: 'DY',
|
||
});
|
||
const dyList = Array.isArray(result && result.data) ? result.data : [];
|
||
if (dyList.length > 0) {
|
||
return dyList;
|
||
}
|
||
|
||
const fallbackResult = await expressInterfaceService.listByWarehousePlatformCode({
|
||
warehouseId,
|
||
platformCode: 'DOUYIN',
|
||
});
|
||
|
||
return Array.isArray(fallbackResult && fallbackResult.data) ? fallbackResult.data : [];
|
||
}
|
||
|
||
/**
|
||
* 按订单物流编码匹配菜鸟主面单接口配置。
|
||
*
|
||
* 优先复用快递服务里的既有匹配规则;若运行上下文未注入该能力,则使用同语义的最小兜底实现。
|
||
*
|
||
* @param {Array<Object>} interfaceList 接口配置列表。
|
||
* @param {Object} orderRow 订单行。
|
||
* @param {Object} orderExpress 快递行。
|
||
* @return {Object|null} 命中的接口配置。
|
||
*/
|
||
pickCainiaoExpressInterface(interfaceList = [], orderRow = {}, orderExpress = {}) {
|
||
const logisticsCode = String(
|
||
orderExpress && orderExpress.logistics_code
|
||
|| orderRow && orderRow.logistics_code
|
||
|| orderRow && orderRow.sys_logistics_code
|
||
|| ''
|
||
).trim();
|
||
if (!logisticsCode) {
|
||
return null;
|
||
}
|
||
|
||
const expressService = this.service && this.service.systems && this.service.systems.express;
|
||
if (expressService && typeof expressService.pickWaybillExpressInterface === 'function') {
|
||
return expressService.pickWaybillExpressInterface(
|
||
interfaceList,
|
||
{
|
||
options: {
|
||
logistics_code: logisticsCode,
|
||
sys_platform_code: 'CAINIAO',
|
||
},
|
||
},
|
||
{ code: 'CAINIAO' }
|
||
);
|
||
}
|
||
|
||
const normalizedLogisticsCode = logisticsCode.toLowerCase();
|
||
for (const item of Array.isArray(interfaceList) ? interfaceList : []) {
|
||
if (!this.isPlainObject(item)) {
|
||
continue;
|
||
}
|
||
|
||
const candidateCodes = [
|
||
String(item.sys_express_code || '').trim().toLowerCase(),
|
||
String(item.express_code || '').trim().toLowerCase(),
|
||
];
|
||
const expressMap = this.isPlainObject(item.express) ? item.express : {};
|
||
candidateCodes.push(String(expressMap.CAINIAO || '').trim().toLowerCase());
|
||
|
||
if (candidateCodes.some(code => code && code === normalizedLogisticsCode)) {
|
||
return item;
|
||
}
|
||
}
|
||
|
||
return null;
|
||
}
|
||
|
||
/**
|
||
* 按订单物流编码匹配京东主面单接口表配置。
|
||
*
|
||
* 优先复用快递服务里的既有匹配规则;若运行上下文未注入该能力,则使用同语义的最小兜底实现。
|
||
*
|
||
* @param {Array<Object>} interfaceList 接口配置列表。
|
||
* @param {Object} orderRow 订单行。
|
||
* @param {Object} orderExpress 快递行。
|
||
* @return {Object|null} 命中的接口配置。
|
||
*/
|
||
pickJdExpressInterface(interfaceList = [], orderRow = {}, orderExpress = {}) {
|
||
const logisticsCode = String(
|
||
orderExpress && orderExpress.logistics_code
|
||
|| orderRow && orderRow.logistics_code
|
||
|| orderRow && orderRow.sys_logistics_code
|
||
|| ''
|
||
).trim();
|
||
if (!logisticsCode) {
|
||
return null;
|
||
}
|
||
|
||
const expressService = this.service && this.service.systems && this.service.systems.express;
|
||
if (expressService && typeof expressService.pickWaybillExpressInterface === 'function') {
|
||
const matchedInterface = expressService.pickWaybillExpressInterface(
|
||
interfaceList,
|
||
{
|
||
options: {
|
||
logistics_code: logisticsCode,
|
||
sys_platform_code: 'JD',
|
||
},
|
||
},
|
||
{ code: 'JD' }
|
||
);
|
||
if (matchedInterface) {
|
||
return matchedInterface;
|
||
}
|
||
}
|
||
|
||
const normalizedLogisticsCode = logisticsCode.toLowerCase();
|
||
for (const item of Array.isArray(interfaceList) ? interfaceList : []) {
|
||
if (!this.isPlainObject(item)) {
|
||
continue;
|
||
}
|
||
|
||
const candidateCodes = [
|
||
String(item.sys_express_code || '').trim().toLowerCase(),
|
||
String(item.express_code || '').trim().toLowerCase(),
|
||
];
|
||
const expressMap = this.isPlainObject(item.express) ? item.express : {};
|
||
candidateCodes.push(String(expressMap.JD || '').trim().toLowerCase());
|
||
|
||
if (candidateCodes.some(code => code && code === normalizedLogisticsCode)) {
|
||
return item;
|
||
}
|
||
}
|
||
|
||
return null;
|
||
}
|
||
|
||
/**
|
||
* 按订单物流编码匹配拼多多主面单接口表配置。
|
||
*
|
||
* 优先复用快递服务里的既有匹配规则;若运行上下文未注入该能力,则使用同语义的最小兜底实现。
|
||
*
|
||
* @param {Array<Object>} interfaceList 接口配置列表。
|
||
* @param {Object} orderRow 订单行。
|
||
* @param {Object} orderExpress 快递行。
|
||
* @return {Object|null} 命中的接口配置。
|
||
*/
|
||
pickPddExpressInterface(interfaceList = [], orderRow = {}, orderExpress = {}) {
|
||
const logisticsCode = String(
|
||
orderExpress && orderExpress.logistics_code
|
||
|| orderRow && orderRow.logistics_code
|
||
|| orderRow && orderRow.sys_logistics_code
|
||
|| ''
|
||
).trim();
|
||
if (!logisticsCode) {
|
||
return null;
|
||
}
|
||
|
||
const expressService = this.service && this.service.systems && this.service.systems.express;
|
||
if (expressService && typeof expressService.pickWaybillExpressInterface === 'function') {
|
||
const matchedInterface = expressService.pickWaybillExpressInterface(
|
||
interfaceList,
|
||
{
|
||
options: {
|
||
logistics_code: logisticsCode,
|
||
sys_platform_code: 'PDD',
|
||
print_platform_code: 'PDD',
|
||
},
|
||
},
|
||
{ code: 'PDD' }
|
||
);
|
||
if (matchedInterface) {
|
||
return matchedInterface;
|
||
}
|
||
}
|
||
|
||
const normalizedLogisticsCode = logisticsCode.toLowerCase();
|
||
for (const item of Array.isArray(interfaceList) ? interfaceList : []) {
|
||
if (!this.isPlainObject(item)) {
|
||
continue;
|
||
}
|
||
|
||
const candidateCodes = [
|
||
String(item.sys_express_code || '').trim().toLowerCase(),
|
||
String(item.express_code || '').trim().toLowerCase(),
|
||
];
|
||
const expressMap = this.isPlainObject(item.express) ? item.express : {};
|
||
candidateCodes.push(String(expressMap.PDD || '').trim().toLowerCase());
|
||
|
||
if (candidateCodes.some(code => code && code === normalizedLogisticsCode)) {
|
||
return item;
|
||
}
|
||
}
|
||
|
||
return null;
|
||
}
|
||
|
||
/**
|
||
* 按订单物流编码匹配抖音主面单接口表配置。
|
||
*
|
||
* 优先复用快递服务里的既有匹配规则;若运行上下文未注入该能力,则使用同语义的最小兜底实现。
|
||
*
|
||
* @param {Array<Object>} interfaceList 接口配置列表。
|
||
* @param {Object} orderRow 订单行。
|
||
* @param {Object} orderExpress 快递行。
|
||
* @return {Object|null} 命中的接口配置。
|
||
*/
|
||
pickDouyinExpressInterface(interfaceList = [], orderRow = {}, orderExpress = {}) {
|
||
const logisticsCode = String(
|
||
orderExpress && orderExpress.logistics_code
|
||
|| orderRow && orderRow.logistics_code
|
||
|| orderRow && orderRow.sys_logistics_code
|
||
|| ''
|
||
).trim();
|
||
if (!logisticsCode) {
|
||
return null;
|
||
}
|
||
|
||
const expressService = this.service && this.service.systems && this.service.systems.express;
|
||
if (expressService && typeof expressService.pickWaybillExpressInterface === 'function') {
|
||
const matchedInterface = expressService.pickWaybillExpressInterface(
|
||
interfaceList,
|
||
{
|
||
options: {
|
||
logistics_code: logisticsCode,
|
||
sys_platform_code: 'DY',
|
||
print_platform_code: 'DY',
|
||
},
|
||
},
|
||
{ code: 'DY' }
|
||
);
|
||
if (matchedInterface) {
|
||
return matchedInterface;
|
||
}
|
||
}
|
||
|
||
const normalizedLogisticsCode = logisticsCode.toLowerCase();
|
||
for (const item of Array.isArray(interfaceList) ? interfaceList : []) {
|
||
if (!this.isPlainObject(item)) {
|
||
continue;
|
||
}
|
||
|
||
const candidateCodes = [
|
||
String(item.sys_express_code || '').trim().toLowerCase(),
|
||
String(item.express_code || '').trim().toLowerCase(),
|
||
];
|
||
const expressMap = this.isPlainObject(item.express) ? item.express : {};
|
||
candidateCodes.push(String(expressMap.DY || '').trim().toLowerCase());
|
||
candidateCodes.push(String(expressMap.DOUYIN || '').trim().toLowerCase());
|
||
|
||
if (candidateCodes.some(code => code && code === normalizedLogisticsCode)) {
|
||
return item;
|
||
}
|
||
}
|
||
|
||
return null;
|
||
}
|
||
|
||
/**
|
||
* 为菜鸟打印订单补齐主面单专用来源字段。
|
||
*
|
||
* 仅对打印平台归一化为菜鸟的订单生效;补齐失败时保留原始运单数据,避免影响其他平台打印。
|
||
*
|
||
* @param {Array<Object>} orderRows 订单列表。
|
||
* @param {Array<Object>} orderExpressRows 快递单列表。
|
||
* @param {number} warehouseId 仓库ID。
|
||
* @return {Promise<Array<Object>>} 补齐后的快递单列表。
|
||
*/
|
||
async enrichCainiaoOrderExpressRows(orderRows = [], orderExpressRows = [], warehouseId) {
|
||
const normalizedOrderRows = Array.isArray(orderRows) ? orderRows : [];
|
||
const normalizedOrderExpressRows = Array.isArray(orderExpressRows) ? orderExpressRows : [];
|
||
if (normalizedOrderRows.length === 0 || normalizedOrderExpressRows.length === 0) {
|
||
return normalizedOrderExpressRows;
|
||
}
|
||
|
||
const orderRowMap = new Map(normalizedOrderRows.map(row => [ Number(row && row.id || 0), row ]));
|
||
const cainiaoOrderIds = [];
|
||
const expressLookupCodes = [];
|
||
|
||
for (const row of normalizedOrderExpressRows) {
|
||
const orderId = Number(row && row.order_id || 0);
|
||
const orderRow = orderRowMap.get(orderId) || {};
|
||
const platformCode = this.resolvePrintPlatformCode(orderRow, row);
|
||
if (!this.isCainiaoPlatformCode(platformCode)) {
|
||
continue;
|
||
}
|
||
|
||
cainiaoOrderIds.push(orderId);
|
||
expressLookupCodes.push(...this.collectCainiaoExpressLookupCodes(orderRow, row));
|
||
}
|
||
|
||
if (cainiaoOrderIds.length === 0) {
|
||
return normalizedOrderExpressRows;
|
||
}
|
||
|
||
let cainiaoCpCodeMap = new Map();
|
||
try {
|
||
cainiaoCpCodeMap = await this.queryCainiaoCpCodeMap(expressLookupCodes);
|
||
} catch (error) {
|
||
this.ctx.logger.warn(
|
||
`[orderPrint.enrichCainiaoOrderExpressRows] 查询菜鸟快递编码失败 warehouseId=${warehouseId} message=${error.message}`
|
||
);
|
||
}
|
||
|
||
let interfaceList = [];
|
||
try {
|
||
interfaceList = await this.queryCainiaoExpressInterfaceList(warehouseId);
|
||
} catch (error) {
|
||
this.ctx.logger.warn(
|
||
`[orderPrint.enrichCainiaoOrderExpressRows] 查询菜鸟快递接口失败 warehouseId=${warehouseId} message=${error.message}`
|
||
);
|
||
}
|
||
|
||
const cainiaoOrderIdSet = new Set(cainiaoOrderIds);
|
||
return normalizedOrderExpressRows.map(row => {
|
||
const orderId = Number(row && row.order_id || 0);
|
||
if (!cainiaoOrderIdSet.has(orderId)) {
|
||
return row;
|
||
}
|
||
|
||
const orderRow = orderRowMap.get(orderId) || {};
|
||
const matchedCpCode = this.collectCainiaoExpressLookupCodes(orderRow, row)
|
||
.map(code => cainiaoCpCodeMap.get(code) || '')
|
||
.find(Boolean) || '';
|
||
const matchedInterface = this.pickCainiaoExpressInterface(interfaceList, orderRow, row);
|
||
const matchedTemplateUrl = String(matchedInterface && matchedInterface.template_url || '').trim();
|
||
|
||
if (!matchedCpCode && !matchedTemplateUrl) {
|
||
return row;
|
||
}
|
||
|
||
return {
|
||
...row,
|
||
...(matchedCpCode ? { cainiao_cp_code: matchedCpCode } : {}),
|
||
...(matchedTemplateUrl ? { cainiao_template_url: matchedTemplateUrl } : {}),
|
||
};
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 为京东打印订单补齐主面单模板来源字段。
|
||
*
|
||
* 仅对打印平台归一化为京东的订单生效;补齐失败时保留原始运单数据,避免影响其他平台打印。
|
||
*
|
||
* @param {Array<Object>} orderRows 订单列表。
|
||
* @param {Array<Object>} orderExpressRows 快递单列表。
|
||
* @param {number} warehouseId 仓库ID。
|
||
* @return {Promise<Array<Object>>} 补齐后的快递单列表。
|
||
*/
|
||
async enrichJdOrderExpressRows(orderRows = [], orderExpressRows = [], warehouseId) {
|
||
const normalizedOrderRows = Array.isArray(orderRows) ? orderRows : [];
|
||
const normalizedOrderExpressRows = Array.isArray(orderExpressRows) ? orderExpressRows : [];
|
||
if (normalizedOrderRows.length === 0 || normalizedOrderExpressRows.length === 0) {
|
||
return normalizedOrderExpressRows;
|
||
}
|
||
|
||
const orderRowMap = new Map(normalizedOrderRows.map(row => [ Number(row && row.id || 0), row ]));
|
||
const jdOrderIds = [];
|
||
|
||
for (const row of normalizedOrderExpressRows) {
|
||
const orderId = Number(row && row.order_id || 0);
|
||
const orderRow = orderRowMap.get(orderId) || {};
|
||
const platformCode = this.resolvePrintPlatformCode(orderRow, row);
|
||
if (!this.isJdPlatformCode(platformCode)) {
|
||
continue;
|
||
}
|
||
|
||
jdOrderIds.push(orderId);
|
||
}
|
||
|
||
if (jdOrderIds.length === 0) {
|
||
return normalizedOrderExpressRows;
|
||
}
|
||
|
||
let interfaceList = [];
|
||
try {
|
||
interfaceList = await this.queryJdExpressInterfaceList(warehouseId);
|
||
} catch (error) {
|
||
this.ctx.logger.warn(
|
||
`[orderPrint.enrichJdOrderExpressRows] 查询京东快递接口表失败 warehouseId=${warehouseId} message=${error.message}`
|
||
);
|
||
}
|
||
|
||
if (!Array.isArray(interfaceList) || interfaceList.length === 0) {
|
||
return normalizedOrderExpressRows;
|
||
}
|
||
|
||
const jdOrderIdSet = new Set(jdOrderIds);
|
||
return normalizedOrderExpressRows.map(row => {
|
||
const orderId = Number(row && row.order_id || 0);
|
||
if (!jdOrderIdSet.has(orderId)) {
|
||
return row;
|
||
}
|
||
|
||
const orderRow = orderRowMap.get(orderId) || {};
|
||
const matchedInterface = this.pickJdExpressInterface(interfaceList, orderRow, row);
|
||
const matchedTemplateUrl = String(matchedInterface && matchedInterface.template_url || '').trim();
|
||
if (!matchedTemplateUrl) {
|
||
return row;
|
||
}
|
||
|
||
return {
|
||
...row,
|
||
jd_template_url: matchedTemplateUrl,
|
||
};
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 为拼多多与抖音打印订单补齐主面单模板来源字段。
|
||
*
|
||
* 仅对打印平台归一化为拼多多/抖音的订单生效;补齐失败时保留原始运单数据,避免影响其他平台打印。
|
||
*
|
||
* @param {Array<Object>} orderRows 订单列表。
|
||
* @param {Array<Object>} orderExpressRows 快递单列表。
|
||
* @param {number} warehouseId 仓库ID。
|
||
* @return {Promise<Array<Object>>} 补齐后的快递单列表。
|
||
*/
|
||
async enrichPddDyOrderExpressRows(orderRows = [], orderExpressRows = [], warehouseId) {
|
||
const normalizedOrderRows = Array.isArray(orderRows) ? orderRows : [];
|
||
const normalizedOrderExpressRows = Array.isArray(orderExpressRows) ? orderExpressRows : [];
|
||
if (normalizedOrderRows.length === 0 || normalizedOrderExpressRows.length === 0) {
|
||
return normalizedOrderExpressRows;
|
||
}
|
||
|
||
const orderRowMap = new Map(normalizedOrderRows.map(row => [ Number(row && row.id || 0), row ]));
|
||
const pddOrderIds = [];
|
||
const douyinOrderIds = [];
|
||
|
||
for (const row of normalizedOrderExpressRows) {
|
||
const orderId = Number(row && row.order_id || 0);
|
||
const orderRow = orderRowMap.get(orderId) || {};
|
||
const platformCode = this.resolvePrintPlatformCode(orderRow, row);
|
||
if (this.isPddPlatformCode(platformCode)) {
|
||
pddOrderIds.push(orderId);
|
||
continue;
|
||
}
|
||
|
||
if (this.isDouyinPlatformCode(platformCode)) {
|
||
douyinOrderIds.push(orderId);
|
||
}
|
||
}
|
||
|
||
if (pddOrderIds.length === 0 && douyinOrderIds.length === 0) {
|
||
return normalizedOrderExpressRows;
|
||
}
|
||
|
||
this.ctx.logger.info('[enrichPddDyOrderExpressRows] douyin 分支入口', {
|
||
douyinOrderCount: douyinOrderIds.length,
|
||
douyinOrderIds: douyinOrderIds.slice(0, 10),
|
||
});
|
||
|
||
let pddInterfaceList = [];
|
||
if (pddOrderIds.length > 0) {
|
||
try {
|
||
pddInterfaceList = await this.queryPddExpressInterfaceList(warehouseId);
|
||
} catch (error) {
|
||
this.ctx.logger.warn(
|
||
`[orderPrint.enrichPddDyOrderExpressRows] 查询拼多多快递接口表失败 warehouseId=${warehouseId} message=${error.message}`
|
||
);
|
||
}
|
||
}
|
||
|
||
let douyinInterfaceList = [];
|
||
if (douyinOrderIds.length > 0) {
|
||
try {
|
||
douyinInterfaceList = await this.queryDouyinExpressInterfaceList(warehouseId);
|
||
this.ctx.logger.info('[enrichPddDyOrderExpressRows] douyin 接口列表查询结果', {
|
||
interfaceCount: douyinInterfaceList.length,
|
||
});
|
||
} catch (error) {
|
||
this.ctx.logger.warn(
|
||
`[orderPrint.enrichPddDyOrderExpressRows] 查询抖音快递接口表失败 warehouseId=${warehouseId} message=${error.message}`
|
||
);
|
||
}
|
||
}
|
||
|
||
const pddOrderIdSet = new Set(pddOrderIds);
|
||
const douyinOrderIdSet = new Set(douyinOrderIds);
|
||
return Promise.all(normalizedOrderExpressRows.map(async row => {
|
||
const orderId = Number(row && row.order_id || 0);
|
||
const orderRow = orderRowMap.get(orderId) || {};
|
||
|
||
if (pddOrderIdSet.has(orderId)) {
|
||
const matchedInterface = this.pickPddExpressInterface(pddInterfaceList, orderRow, row);
|
||
const matchedTemplateUrl = String(matchedInterface && matchedInterface.template_url || '').trim();
|
||
if (!matchedTemplateUrl) {
|
||
return row;
|
||
}
|
||
|
||
return {
|
||
...row,
|
||
pdd_template_url: matchedTemplateUrl,
|
||
};
|
||
}
|
||
|
||
if (douyinOrderIdSet.has(orderId)) {
|
||
const matchedInterface = this.pickDouyinExpressInterface(douyinInterfaceList, orderRow, row);
|
||
const matchedTemplateUrl = String(matchedInterface && matchedInterface.template_url || '').trim();
|
||
this.ctx.logger.info('[enrichPddDyOrderExpressRows] douyin 单笔匹配结果', {
|
||
orderId,
|
||
hasMatchedInterface: !!matchedInterface,
|
||
matchedTemplateUrl,
|
||
sysLogisticsCode: orderRow.sys_logistics_code,
|
||
logisticsCode: row.logistics_code,
|
||
});
|
||
if (!matchedTemplateUrl) {
|
||
return row;
|
||
}
|
||
|
||
// 获取菠萝派 API 请求参数
|
||
let dyParams = '';
|
||
try {
|
||
if (matchedInterface) {
|
||
const cacheKey = `douyin:params:${orderRow.sys_logistics_code || orderRow.logistics_code || ''}:${row.logistics_interface_id || ''}`;
|
||
|
||
// 菠萝派配置:appkey/app_secret 来自项目 config.poloApi,token 来自快递接口
|
||
const poloConfig = this.config.poloApi || {};
|
||
|
||
// 先查 Redis 缓存
|
||
if (this.app && typeof this.app.getCacheAsync === 'function') {
|
||
const cached = await this.app.getCacheAsync(cacheKey);
|
||
if (cached && typeof cached === 'string') {
|
||
dyParams = cached;
|
||
}
|
||
}
|
||
// 缓存未命中,调菠萝派
|
||
if (!dyParams) {
|
||
const PoloApiClient = require('../../lib/polo_api_client');
|
||
const poloClient = new PoloApiClient(this.ctx);
|
||
const result = await poloClient.request({
|
||
method: 'Differ.JH.Business.GetPlatApiRequestInfo',
|
||
bizcontent: { platMethod: '/logistics/getShopKey' },
|
||
config: {
|
||
interface_url: 'https://api.polyapi.com/openapi/do',
|
||
appkey: poloConfig.appKey || '',
|
||
app_secret: poloConfig.appSecret || '',
|
||
platid: 126,
|
||
version: '1.5',
|
||
token: matchedInterface.token || '',
|
||
},
|
||
token: matchedInterface.token || '',
|
||
});
|
||
|
||
this.ctx.logger.info('[DouyinParams] 菠萝派 GetPlatApiRequestInfo 响应:', JSON.stringify(result));
|
||
dyParams = result.requestinfo || JSON.stringify(result);
|
||
|
||
if (this.app && typeof this.app.setCacheAsync === 'function') {
|
||
await this.app.setCacheAsync(cacheKey, dyParams, 270);
|
||
}
|
||
}
|
||
}
|
||
} catch (err) {
|
||
this.ctx.logger.warn('[enrichPddDyOrderExpressRows] 获取 Douyin params 失败: %s', err.message);
|
||
}
|
||
|
||
return {
|
||
...row,
|
||
dy_template_url: matchedTemplateUrl,
|
||
dy_params: dyParams,
|
||
};
|
||
}
|
||
|
||
return row;
|
||
}));
|
||
}
|
||
|
||
/**
|
||
* 获取波次订单对应货主的签约策略映射。
|
||
*
|
||
* @param {Array<Object>} orderRows 订单行。
|
||
* @param {number} warehouseId 仓库ID。
|
||
* @return {Promise<Map<number, Object>>} 货主策略映射。
|
||
*/
|
||
async getPolicyConfigMapByStore(orderRows = [], warehouseId) {
|
||
const storeIds = Array.from(new Set(orderRows
|
||
.map(row => Number(row && row.store_id || 0))
|
||
.filter(storeId => Number.isInteger(storeId) && storeId > 0)));
|
||
const policyMap = new Map();
|
||
|
||
if (storeIds.length === 0) {
|
||
return policyMap;
|
||
}
|
||
|
||
const storeWarehouseService = this.ctx.service
|
||
&& this.ctx.service.systems
|
||
&& this.ctx.service.systems.storeWarehouse;
|
||
if (!storeWarehouseService || typeof storeWarehouseService.getContractConfig !== 'function') {
|
||
return policyMap;
|
||
}
|
||
|
||
await Promise.all(storeIds.map(async storeId => {
|
||
try {
|
||
const contractConfig = await storeWarehouseService.getContractConfig(warehouseId, storeId);
|
||
const policyConfig = this.normalizeContractPolicyConfig(contractConfig && contractConfig.policy_config);
|
||
policyMap.set(storeId, policyConfig);
|
||
} catch (error) {
|
||
this.ctx.logger.warn(
|
||
`[orderPrint.getPolicyConfigMapByStore] 读取签约策略失败 warehouseId=${warehouseId} storeId=${storeId} message=${error.message}`
|
||
);
|
||
policyMap.set(storeId, {});
|
||
}
|
||
}));
|
||
|
||
return policyMap;
|
||
}
|
||
|
||
/**
|
||
* 解析订单平台编码,保留原始平台值(仅去首尾空白)。
|
||
*
|
||
* @param {Object} orderRow 订单行。
|
||
* @param {Object} orderExpress 快递行。
|
||
* @return {string} 打印平台编码。
|
||
*/
|
||
resolvePrintPlatformCode(orderRow = {}, orderExpress = {}) {
|
||
const candidates = [
|
||
orderExpress && orderExpress.platform_code,
|
||
orderRow && orderRow.sys_platform_code,
|
||
orderRow && orderRow.source_platform_code,
|
||
];
|
||
|
||
for (const candidate of candidates) {
|
||
const rawCandidate = String(candidate || '').trim();
|
||
if (!rawCandidate) {
|
||
continue;
|
||
}
|
||
|
||
return rawCandidate;
|
||
}
|
||
|
||
return '';
|
||
}
|
||
|
||
/**
|
||
* 按平台加载打印模板样例。
|
||
*
|
||
* @param {string} platformCode 平台编码。
|
||
* @param {Map<string, Object>} cache 模板缓存。
|
||
* @return {Object} 模板样例对象。
|
||
*/
|
||
loadTemplateSampleByPlatform(platformCode, cache) {
|
||
const normalized = PrinterDataBuilder.normalizePlatformAlias(platformCode);
|
||
const cacheKey = normalized.meta && normalized.meta.template_file
|
||
? normalized.meta.template_file
|
||
: `platform:${normalized.platform || 'unknown'}`;
|
||
if (cache.has(cacheKey)) {
|
||
return cache.get(cacheKey);
|
||
}
|
||
|
||
if (!normalized.meta || !normalized.meta.template_file) {
|
||
cache.set(cacheKey, {});
|
||
return {};
|
||
}
|
||
|
||
const templatePath = path.join(this.app.baseDir, 'printer_data_template', normalized.meta.template_file);
|
||
try {
|
||
const fileContent = fs.readFileSync(templatePath, 'utf8');
|
||
const parsedTemplate = JSON.parse(fileContent);
|
||
const templateSample = this.isPlainObject(parsedTemplate) ? parsedTemplate : {};
|
||
cache.set(cacheKey, templateSample);
|
||
return templateSample;
|
||
} catch (error) {
|
||
this.ctx.logger.warn(`[orderPrint.loadTemplateSampleByPlatform] 模板读取失败 template=${templatePath} message=${error.message}`);
|
||
cache.set(cacheKey, {});
|
||
return {};
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 组装单订单平台打印中间态结果。
|
||
*
|
||
* @param {Object} payload 聚合入参。
|
||
* @param {Object} payload.orderRow 订单行。
|
||
* @param {Object} payload.orderExpress 快递行。
|
||
* @param {Object} payload.policyConfig 策略配置。
|
||
* @param {string} payload.platformCode 平台编码。
|
||
* @param {Object} payload.templateSample 模板样例。
|
||
* @return {Object} 逐单打印中间态。
|
||
*/
|
||
buildOrderPlatformPrintItem(payload = {}) {
|
||
const requestPayload = this.isPlainObject(payload) ? payload : {};
|
||
const orderRow = this.isPlainObject(requestPayload.orderRow) ? requestPayload.orderRow : {};
|
||
const orderExpress = this.isPlainObject(requestPayload.orderExpress) ? requestPayload.orderExpress : {};
|
||
const policyConfig = this.isPlainObject(requestPayload.policyConfig) ? requestPayload.policyConfig : {};
|
||
const templateSample = this.isPlainObject(requestPayload.templateSample) ? requestPayload.templateSample : {};
|
||
const platformCode = String(requestPayload.platformCode || '').trim();
|
||
|
||
const orderId = Number(orderRow.id || 0);
|
||
const waveId = Number(orderRow.wave_id || 0);
|
||
const requestId = `wave_${waveId}_order_${orderId}`;
|
||
const waybillCode = String(orderExpress.waybill_code || '').trim();
|
||
const orderSysLogisticsCode = String(orderRow.sys_logistics_code || '').trim();
|
||
const orderSysLogisticsName = String(orderRow.sys_logistics_name || '').trim();
|
||
const expressSysLogisticsCode = String(orderExpress.sys_logistics_code || '').trim();
|
||
const expressSysLogisticsName = String(orderExpress.sys_logistics_name || '').trim();
|
||
const documentId = waybillCode || `doc_${orderId}`;
|
||
const printPayload = PrinterDataBuilder.buildPlatformRequestSkeleton({
|
||
platform: platformCode,
|
||
order_express: orderExpress,
|
||
order_delivery: orderRow,
|
||
store_contract: {
|
||
policy_config: policyConfig,
|
||
},
|
||
policy_config: policyConfig,
|
||
template_sample: templateSample,
|
||
options: {
|
||
requestId,
|
||
taskId: requestId,
|
||
documentId,
|
||
},
|
||
});
|
||
const printData = this.extractSinglePlatformPrintData(printPayload);
|
||
return {
|
||
wave_id: waveId,
|
||
wave_no: String(orderRow.wave_no || '').trim(),
|
||
order_id: orderId,
|
||
order_no: String(orderRow.delivery_order_code || orderRow.source_order_codes || '').trim(),
|
||
store_id: Number(orderRow.store_id || 0),
|
||
warehouse_id: Number(orderRow.warehouse_id || 0),
|
||
platform: platformCode,
|
||
platform_name: printPayload.platform_meta && printPayload.platform_meta.name
|
||
? String(printPayload.platform_meta.name).trim()
|
||
: '',
|
||
sys_logistics_code: orderSysLogisticsCode || expressSysLogisticsCode,
|
||
sys_logistics_name: orderSysLogisticsName || expressSysLogisticsName,
|
||
waybill_code: String(orderExpress.waybill_code || '').trim(),
|
||
print_data: printData,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 提取单个打印文档对象。
|
||
*
|
||
* @param {Object} printPayload 打印载荷。
|
||
* @return {Object} 单个文档对象;未命中时返回空对象。
|
||
*/
|
||
extractSinglePlatformPrintData(printPayload = {}) {
|
||
const requestSkeleton = this.isPlainObject(printPayload)
|
||
? printPayload.request_skeleton
|
||
: null;
|
||
if (!this.isPlainObject(requestSkeleton)) {
|
||
return {};
|
||
}
|
||
|
||
const taskDocuments = requestSkeleton.task && Array.isArray(requestSkeleton.task.documents)
|
||
? requestSkeleton.task.documents
|
||
: [];
|
||
if (taskDocuments.length > 0 && this.isPlainObject(taskDocuments[0])) {
|
||
return taskDocuments[0];
|
||
}
|
||
|
||
if (Array.isArray(requestSkeleton.documents) && this.isPlainObject(requestSkeleton.documents[0])) {
|
||
return requestSkeleton.documents[0];
|
||
}
|
||
|
||
const taskListEntry = Array.isArray(requestSkeleton.taskList)
|
||
? requestSkeleton.taskList.find(item => Array.isArray(item && item.documents) && item.documents.length > 0)
|
||
: null;
|
||
if (taskListEntry && this.isPlainObject(taskListEntry.documents[0])) {
|
||
return taskListEntry.documents[0];
|
||
}
|
||
|
||
if (Array.isArray(requestSkeleton.taskList) && this.isPlainObject(requestSkeleton.taskList[0])) {
|
||
return requestSkeleton.taskList[0];
|
||
}
|
||
|
||
return {};
|
||
}
|
||
|
||
/**
|
||
* 将逐单打印中间态按平台分组。
|
||
*
|
||
* @param {Array<Object>} orderPrintList 逐单打印中间态列表。
|
||
* @return {Array<Object>} 平台分组列表。
|
||
*/
|
||
groupOrderPrintItemsByPlatform(orderPrintList = []) {
|
||
const groupedPlatformMap = new Map();
|
||
|
||
for (const item of orderPrintList) {
|
||
const platform = String(item && item.platform || '').trim() || 'unknown';
|
||
const group = groupedPlatformMap.get(platform) || {
|
||
platform,
|
||
platform_name: String(item && item.platform_name || '').trim(),
|
||
order_count: 0,
|
||
orders: [],
|
||
};
|
||
|
||
group.orders.push(this.isPlainObject(item && item.print_data) ? item.print_data : {});
|
||
group.order_count = group.orders.length;
|
||
groupedPlatformMap.set(platform, group);
|
||
}
|
||
|
||
const groups = Array.from(groupedPlatformMap.values());
|
||
groups.sort((a, b) => String(a.platform || '').localeCompare(String(b.platform || '')));
|
||
return groups;
|
||
}
|
||
|
||
/**
|
||
* 将逐单打印中间态按波次分组,并在波次内按平台+系统快递分组。
|
||
*
|
||
* @param {Object} payload 聚合输入。
|
||
* @param {Array<Object>} payload.waveRows 波次元数据列表。
|
||
* @param {Array<number>} payload.hitWaveIds 命中的波次ID数组(已过滤)。
|
||
* @param {Array<Object>} payload.orderPrintList 逐单打印中间态列表。
|
||
* @return {Array<Object>} 波次平台分组结果(platforms 为扁平平台+系统快递项)。
|
||
*/
|
||
groupOrderPrintItemsByWaveAndPlatform(payload = {}) {
|
||
const {
|
||
waveRows = [],
|
||
hitWaveIds = [],
|
||
orderPrintList = [],
|
||
} = this.isPlainObject(payload) ? payload : {};
|
||
|
||
const waveMetaMap = new Map();
|
||
for (const row of waveRows) {
|
||
const waveId = Number(row && row.wave_id || 0);
|
||
if (!Number.isInteger(waveId) || waveId <= 0) {
|
||
continue;
|
||
}
|
||
|
||
waveMetaMap.set(waveId, {
|
||
wave_id: waveId,
|
||
wave_no: String(row && row.wave_no || '').trim(),
|
||
});
|
||
}
|
||
|
||
const waveGroupMap = new Map();
|
||
const wavePlatformMap = new Map();
|
||
for (const waveId of hitWaveIds) {
|
||
const normalizedWaveId = Number(waveId);
|
||
if (!Number.isInteger(normalizedWaveId) || normalizedWaveId <= 0) {
|
||
continue;
|
||
}
|
||
|
||
const waveMeta = waveMetaMap.get(normalizedWaveId) || {
|
||
wave_id: normalizedWaveId,
|
||
wave_no: '',
|
||
};
|
||
waveGroupMap.set(normalizedWaveId, {
|
||
wave_id: waveMeta.wave_id,
|
||
wave_no: waveMeta.wave_no,
|
||
order_count: 0,
|
||
platforms: [],
|
||
});
|
||
wavePlatformMap.set(normalizedWaveId, new Map());
|
||
}
|
||
|
||
for (const item of orderPrintList) {
|
||
const waveId = Number(item && item.wave_id || 0);
|
||
const waveGroup = waveGroupMap.get(waveId);
|
||
if (!waveGroup) {
|
||
continue;
|
||
}
|
||
|
||
const platform = String(item && item.platform || '').trim() || 'unknown';
|
||
const normalizedSysLogisticsCode = String(item && item.sys_logistics_code || '').trim();
|
||
const normalizedSysLogisticsName = String(item && item.sys_logistics_name || '').trim();
|
||
const normalizedSysLogisticsIdentity = normalizedSysLogisticsCode || normalizedSysLogisticsName || 'unknown';
|
||
const platformSysKey = `${platform}@@${normalizedSysLogisticsIdentity}`;
|
||
const platformMap = wavePlatformMap.get(waveId) || new Map();
|
||
const platformGroup = platformMap.get(platformSysKey) || {
|
||
platform,
|
||
platform_name: String(item && item.platform_name || '').trim(),
|
||
sys_logistics_code: normalizedSysLogisticsCode || 'unknown',
|
||
sys_logistics_name: normalizedSysLogisticsName || 'unknown',
|
||
order_count: 0,
|
||
order_ids: [],
|
||
orders: [],
|
||
};
|
||
|
||
const orderId = Number(item && item.order_id || 0);
|
||
if (Number.isInteger(orderId) && orderId > 0) {
|
||
platformGroup.order_ids.push(orderId);
|
||
}
|
||
platformGroup.orders.push(this.isPlainObject(item && item.print_data) ? item.print_data : {});
|
||
platformGroup.order_ids = Array.from(new Set(platformGroup.order_ids));
|
||
platformGroup.order_count = platformGroup.orders.length;
|
||
|
||
platformMap.set(platformSysKey, platformGroup);
|
||
wavePlatformMap.set(waveId, platformMap);
|
||
}
|
||
|
||
const waveGroups = Array.from(waveGroupMap.values());
|
||
for (const waveGroup of waveGroups) {
|
||
const platformMap = wavePlatformMap.get(Number(waveGroup.wave_id)) || new Map();
|
||
const platforms = Array.from(platformMap.values());
|
||
platforms.sort((a, b) => {
|
||
const platformCompare = String(a.platform || '').localeCompare(String(b.platform || ''));
|
||
if (platformCompare !== 0) {
|
||
return platformCompare;
|
||
}
|
||
|
||
const sysCodeCompare = String(a.sys_logistics_code || '').localeCompare(String(b.sys_logistics_code || ''));
|
||
if (sysCodeCompare !== 0) {
|
||
return sysCodeCompare;
|
||
}
|
||
|
||
return String(a.sys_logistics_name || '').localeCompare(String(b.sys_logistics_name || ''));
|
||
});
|
||
waveGroup.platforms = platforms;
|
||
waveGroup.order_count = platforms.reduce((sum, platformGroup) => {
|
||
return sum + Number(platformGroup && platformGroup.order_count || 0);
|
||
}, 0);
|
||
}
|
||
|
||
waveGroups.sort((a, b) => {
|
||
const waveNoCompare = String(a.wave_no || '').localeCompare(String(b.wave_no || ''));
|
||
if (waveNoCompare !== 0) {
|
||
return waveNoCompare;
|
||
}
|
||
|
||
return Number(a.wave_id || 0) - Number(b.wave_id || 0);
|
||
});
|
||
|
||
return waveGroups;
|
||
}
|
||
|
||
/**
|
||
* 过滤快递未完全分配的波次。
|
||
*
|
||
* 规则:仅当波次下全部订单的 post_status 都为 fin 时,才视为快递已完全分配。
|
||
*
|
||
* @param {Array<number>} hitWaveIds 命中的波次ID数组。
|
||
* @param {Array<Object>} orderRows 波次订单列表。
|
||
* @return {{ validWaveIds: Array<number>, filteredWaveIds: Array<Object> }} 过滤结果。
|
||
*/
|
||
filterFullyAssignedExpressWaves(hitWaveIds = [], orderRows = []) {
|
||
const statsMap = new Map();
|
||
for (const waveId of hitWaveIds) {
|
||
statsMap.set(Number(waveId), {
|
||
total: 0,
|
||
fin: 0,
|
||
});
|
||
}
|
||
|
||
for (const row of orderRows) {
|
||
const waveId = Number(row && row.wave_id || 0);
|
||
const stats = statsMap.get(waveId);
|
||
if (!stats) {
|
||
continue;
|
||
}
|
||
|
||
const postStatus = String(row && row.post_status || '').trim();
|
||
stats.total += 1;
|
||
if (postStatus === 'fin') {
|
||
stats.fin += 1;
|
||
}
|
||
}
|
||
|
||
const validWaveIds = [];
|
||
const filteredWaveIds = [];
|
||
for (const waveId of hitWaveIds) {
|
||
const stats = statsMap.get(waveId) || { total: 0, fin: 0 };
|
||
const isFullyAssigned = stats.total > 0 && stats.fin === stats.total;
|
||
if (isFullyAssigned) {
|
||
validWaveIds.push(waveId);
|
||
} else {
|
||
filteredWaveIds.push({
|
||
wave_id: waveId,
|
||
reason: '快递未完全分配',
|
||
});
|
||
}
|
||
}
|
||
|
||
return {
|
||
validWaveIds,
|
||
filteredWaveIds,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 生成空结果结构。
|
||
*
|
||
* @param {Array<number>} normalizedWaveIds 规范化后的波次ID数组。
|
||
* @return {Object} 空结果。
|
||
*/
|
||
buildEmptyResult(normalizedWaveIds = []) {
|
||
return {
|
||
summary: {
|
||
total_waves: 0,
|
||
total_orders: 0,
|
||
},
|
||
wave_list: [],
|
||
ext: {
|
||
missing_wave_ids: normalizedWaveIds,
|
||
filtered_wave_ids: [],
|
||
},
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 组装通用波次打印返回结构。
|
||
*
|
||
* @param {Object} payload 聚合输入。
|
||
* @param {Array<Object>} payload.waveRows 波次列表。
|
||
* @param {Array<Object>} payload.orderRows 订单列表。
|
||
* @param {Array<number>} payload.hitWaveIds 命中的波次ID数组。
|
||
* @param {Array<number>} payload.missingWaveIds 未命中的波次ID数组。
|
||
* @param {Array<Object>} payload.filteredWaveIds 被过滤的波次及原因。
|
||
* @return {Object} 波次打印返回结果。
|
||
*/
|
||
buildWavePrintResult(payload = {}) {
|
||
const {
|
||
waveRows = [],
|
||
orderRows = [],
|
||
hitWaveIds = [],
|
||
missingWaveIds = [],
|
||
filteredWaveIds = [],
|
||
} = this.isPlainObject(payload) ? payload : {};
|
||
|
||
const waveMetaMap = new Map();
|
||
for (const row of waveRows) {
|
||
const waveId = Number(row && row.wave_id || 0);
|
||
if (!Number.isInteger(waveId) || waveId <= 0) {
|
||
continue;
|
||
}
|
||
|
||
waveMetaMap.set(waveId, {
|
||
wave_id: waveId,
|
||
wave_no: String(row && row.wave_no || '').trim(),
|
||
});
|
||
}
|
||
|
||
const groupedWaveMap = new Map();
|
||
for (const waveId of hitWaveIds) {
|
||
const waveMeta = waveMetaMap.get(waveId);
|
||
if (!waveMeta) {
|
||
continue;
|
||
}
|
||
|
||
groupedWaveMap.set(waveId, {
|
||
wave_id: waveMeta.wave_id,
|
||
wave_no: waveMeta.wave_no,
|
||
order_count: 0,
|
||
orders: [],
|
||
});
|
||
}
|
||
|
||
for (const order of orderRows) {
|
||
const waveId = Number(order && order.wave_id || 0);
|
||
const groupedWave = groupedWaveMap.get(waveId);
|
||
if (!groupedWave) {
|
||
continue;
|
||
}
|
||
|
||
groupedWave.orders.push({
|
||
order_id: Number(order && order.id || 0),
|
||
order_no: String(order && (order.delivery_order_code || order.source_order_codes) || '').trim(),
|
||
wave_id: waveId,
|
||
wave_no: String(order && order.wave_no || '').trim() || groupedWave.wave_no,
|
||
receiver: {
|
||
name: String(order && order.name || '').trim(),
|
||
mobile: String(order && order.mobile || '').trim(),
|
||
tel: String(order && order.tel || '').trim(),
|
||
province: String(order && order.province || '').trim(),
|
||
city: String(order && order.city || '').trim(),
|
||
area: String(order && order.area || '').trim(),
|
||
town: String(order && order.town || '').trim(),
|
||
detail_address: String(order && order.detail_address || '').trim(),
|
||
},
|
||
channel: {
|
||
sys_platform_code: String(order && order.sys_platform_code || '').trim(),
|
||
sys_platform_name: String(order && order.sys_platform_name || '').trim(),
|
||
logistics_name: String(order && order.logistics_name || '').trim(),
|
||
},
|
||
status: {
|
||
order_status: String(order && order.status || '').trim(),
|
||
outbound_status: String(order && order.outbound_status || '').trim(),
|
||
print_status: String(order && order.print_status || '').trim(),
|
||
},
|
||
metrics: {
|
||
items_count: Number(order && order.items_count || 0),
|
||
items_total: Number(order && order.items_total || 0),
|
||
items_weight: Number(order && order.items_weight || 0),
|
||
},
|
||
times: {
|
||
create_at: order && order.create_at || null,
|
||
pay_time: order && order.pay_time || null,
|
||
},
|
||
});
|
||
}
|
||
|
||
const waveList = Array.from(groupedWaveMap.values());
|
||
waveList.sort((a, b) => String(a.wave_no || '').localeCompare(String(b.wave_no || '')));
|
||
let totalOrders = 0;
|
||
for (const wave of waveList) {
|
||
wave.order_count = wave.orders.length;
|
||
totalOrders += wave.order_count;
|
||
}
|
||
|
||
return {
|
||
summary: {
|
||
total_waves: waveList.length,
|
||
total_orders: totalOrders,
|
||
},
|
||
wave_list: waveList,
|
||
ext: {
|
||
missing_wave_ids: missingWaveIds,
|
||
filtered_wave_ids: filteredWaveIds,
|
||
},
|
||
};
|
||
}
|
||
}
|
||
|
||
module.exports = OrderPrintSystemService;
|