- 聚合键由库位改为 库位+stock_id 复合键, 仅同库位同商品合并数量 - stock_id 缺失时依次回退 order_item_id、商品名称+条码, 无法识别商品身份时不再跨行合并
3420 lines
120 KiB
JavaScript
3420 lines
120 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 '';
|
||
}
|
||
|
||
/**
|
||
* 构建打印项聚合键。
|
||
*
|
||
* 同一库位下的拣货行只有商品身份一致时才允许合并:
|
||
* - 优先 stock_id(>0):同一库位同一商品合并数量;
|
||
* - stock_id 缺失时回退 order_item_id(同一订单商品行);
|
||
* - 再缺失时回退 商品名称+条码 兜底;
|
||
* - 均无法识别时不做跨行合并(每行独立)。
|
||
*
|
||
* @param {Object} item 打印项。
|
||
* @return {string} 聚合键。
|
||
*/
|
||
buildPrintItemAggregationKey(item = {}) {
|
||
const source = this.isPlainObject(item) ? item : {};
|
||
const location = String(source.pick_location || '').trim();
|
||
const stockId = Number(source.stock_id || 0);
|
||
if (stockId > 0) {
|
||
return `${location}::stock:${stockId}`;
|
||
}
|
||
|
||
const orderItemId = Number(source.order_item_id || 0);
|
||
if (orderItemId > 0) {
|
||
return `${location}::order_item:${orderItemId}`;
|
||
}
|
||
|
||
const name = String(source.item_name || '').trim();
|
||
const barcode = String(source.barcode || '').trim();
|
||
if (name || barcode) {
|
||
return `${location}::name:${name}|${barcode}`;
|
||
}
|
||
|
||
return `${location}::id:${Math.random()}`;
|
||
}
|
||
|
||
/**
|
||
* 批量补查打印所需的拣货明细,并注入商品多条码。
|
||
*
|
||
* 优先使用 wms_picking.space_name,只有缺失时才查询库位表,减少额外 SQL。
|
||
* 同时从 wms_stock_barcodes 表批量查询每个 stock_id 对应的全部条码,
|
||
* 注入到打印项的 barcodes 数组中,供 resolveItemBarcodeText 优先读取。
|
||
*
|
||
* 商品信息(item_name / barcode / stock_id / quantity)全部从 wms_picking
|
||
* 直读,不再反查 order_items 表,彻底消除因订单迁移导致 order_item_id
|
||
* 错配的风险。
|
||
*
|
||
* @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,
|
||
},
|
||
warehouse_id: warehouseId,
|
||
status: {
|
||
[Op.ne]: 'cancel',
|
||
},
|
||
},
|
||
attributes: [ 'id', 'order_id', 'order_item_id', 'quantity', 'space_id', 'space_name', 'status', 'stock_id' ],
|
||
order: [[ 'order_id', 'ASC' ], [ 'id', 'ASC' ]],
|
||
raw: true,
|
||
});
|
||
|
||
const normalizedPickingRows = Array.isArray(pickingRows) ? pickingRows : [];
|
||
if (normalizedPickingRows.length === 0) {
|
||
return resultMap;
|
||
}
|
||
|
||
// 库位兜底:space_name 为空时通过 space_id 补查 location_space 表
|
||
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 ]));
|
||
|
||
// 按 order_id 分组 picking 行
|
||
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);
|
||
}
|
||
|
||
// 阶段一:从 picking.stock_id 收集所有 stock_id
|
||
const allStockIds = new Set();
|
||
for (const row of normalizedPickingRows) {
|
||
const stockId = Number(row && row.stock_id || 0);
|
||
if (stockId > 0) {
|
||
allStockIds.add(stockId);
|
||
}
|
||
}
|
||
const uniqueStockIds = Array.from(allStockIds);
|
||
|
||
// 阶段二:批量查询 wms_stock_warehouse 获取商品编码与名称
|
||
const stockWarehouseMap = new Map();
|
||
if (uniqueStockIds.length > 0) {
|
||
const stockWarehouseModel = this.ctx.model && this.ctx.model.StockWarehouse;
|
||
if (stockWarehouseModel && typeof stockWarehouseModel.findAll === 'function') {
|
||
const stockRows = await stockWarehouseModel.findAll({
|
||
where: {
|
||
id: { [Op.in]: uniqueStockIds },
|
||
is_valid: 'Y',
|
||
},
|
||
attributes: [ 'id', 'item_code', 'item_name' ],
|
||
raw: true,
|
||
});
|
||
for (const row of Array.isArray(stockRows) ? stockRows : []) {
|
||
stockWarehouseMap.set(Number(row.id), row);
|
||
}
|
||
}
|
||
}
|
||
|
||
// 阶段三:构建所有打印项(全部从 picking + stock_warehouse 直取)
|
||
const printItemsByOrderId = new Map();
|
||
|
||
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 stockId = Number(pickingRow && pickingRow.stock_id || 0);
|
||
const stockInfo = stockId > 0 ? stockWarehouseMap.get(stockId) : null;
|
||
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 quantity = Number(pickingRow && pickingRow.quantity || 0);
|
||
|
||
return {
|
||
order_item_id: Number(pickingRow && pickingRow.order_item_id || 0),
|
||
item_name: stockInfo ? String(stockInfo.item_name || '').trim() : '',
|
||
barcode: stockInfo ? String(stockInfo.item_code || '').trim() : '',
|
||
quantity: quantity > 0 ? quantity : 0,
|
||
pick_location: pickLocation,
|
||
stock_id: stockId > 0 ? stockId : undefined,
|
||
};
|
||
}).filter(item => {
|
||
return String(item.item_name || '').trim()
|
||
|| String(item.barcode || '').trim()
|
||
|| String(item.pick_location || '').trim();
|
||
});
|
||
|
||
if (printItems.length === 0) {
|
||
continue;
|
||
}
|
||
|
||
printItemsByOrderId.set(orderId, printItems);
|
||
}
|
||
|
||
// 阶段四:批量查询 wms_stock_barcodes 获取所有条码
|
||
const barcodeMap = new Map();
|
||
|
||
if (uniqueStockIds.length > 0) {
|
||
const stockBarcodeModel = this.ctx.model && this.ctx.model.StockBarcode;
|
||
|
||
if (stockBarcodeModel && typeof stockBarcodeModel.findAll === 'function') {
|
||
const barcodeRows = await stockBarcodeModel.findAll({
|
||
where: {
|
||
stock_id: {
|
||
[Op.in]: uniqueStockIds,
|
||
},
|
||
},
|
||
attributes: [ 'stock_id', 'barcode' ],
|
||
raw: true,
|
||
});
|
||
|
||
for (const item of Array.isArray(barcodeRows) ? barcodeRows : []) {
|
||
const stockId = Number(item && item.stock_id || 0);
|
||
const code = String(item && item.barcode || '').trim();
|
||
|
||
if (!stockId || !code) {
|
||
continue;
|
||
}
|
||
|
||
if (!barcodeMap.has(stockId)) {
|
||
barcodeMap.set(stockId, []);
|
||
}
|
||
|
||
barcodeMap.get(stockId).push(code);
|
||
}
|
||
}
|
||
}
|
||
|
||
// 阶段五:注入条码并构建结果映射
|
||
for (const orderRow of rows) {
|
||
const orderId = Number(orderRow && orderRow.id || 0);
|
||
const printItems = printItemsByOrderId.get(orderId);
|
||
|
||
if (!printItems) {
|
||
continue;
|
||
}
|
||
|
||
// 为每条打印项注入 barcodes 数组,供 resolveItemBarcodeText 优先读取
|
||
for (const item of printItems) {
|
||
const stockId = Number(item.stock_id || 0);
|
||
item.stock_id = stockId > 0 ? stockId : 0;
|
||
|
||
if (stockId > 0 && barcodeMap.has(stockId)) {
|
||
item.barcodes = barcodeMap.get(stockId);
|
||
}
|
||
}
|
||
|
||
// 按「库位 + 商品(stock_id)」聚合:同一库位的同一商品合并为一行,
|
||
// 同一库位的不同商品保持独立行,避免数量、条码被错误合并。
|
||
const aggregatedMap = new Map();
|
||
for (const item of printItems) {
|
||
const key = this.buildPrintItemAggregationKey(item);
|
||
const existing = aggregatedMap.get(key);
|
||
if (existing) {
|
||
// 累加数量
|
||
existing.quantity += item.quantity;
|
||
// 合并 item_name(用 、 拼接去重)
|
||
if (item.item_name && !existing.item_name.split('、').includes(item.item_name)) {
|
||
existing.item_name = `${existing.item_name}、${item.item_name}`;
|
||
}
|
||
// 合并 barcode(用 ; 拼接去重)
|
||
if (item.barcode && !existing.barcode.split(';').includes(item.barcode)) {
|
||
existing.barcode = `${existing.barcode};${item.barcode}`;
|
||
}
|
||
// 合并 barcodes 数组(Set 去重)
|
||
if (item.barcodes && item.barcodes.length > 0) {
|
||
const merged = new Set([ ...(existing.barcodes || []), ...item.barcodes ]);
|
||
existing.barcodes = Array.from(merged);
|
||
}
|
||
} else {
|
||
aggregatedMap.set(key, { ...item });
|
||
}
|
||
}
|
||
const mergedPrintItems = Array.from(aggregatedMap.values());
|
||
|
||
// 聚合完成后清理内部字段,避免污染 JSON 输出
|
||
for (const item of mergedPrintItems) {
|
||
delete item.stock_id;
|
||
}
|
||
|
||
// 为聚合后的商品行添加序号(从 1 开始)
|
||
for (let i = 0; i < mergedPrintItems.length; i++) {
|
||
mergedPrintItems[i].seq_no = i + 1;
|
||
}
|
||
|
||
resultMap.set(orderId, {
|
||
...orderRow,
|
||
items: JSON.stringify(mergedPrintItems),
|
||
});
|
||
}
|
||
|
||
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 {};
|
||
}
|
||
|
||
/**
|
||
* 获取波次平台打印数据中间态。
|
||
*
|
||
* 输出以波次分组为主结构(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,
|
||
intercepted_count: 0,
|
||
},
|
||
waveGroups: [],
|
||
locked_wave_groups: [],
|
||
wave_ids: [],
|
||
locked_count: 0,
|
||
locked_orders: [],
|
||
intercepted_count: 0,
|
||
intercepted_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 interceptedOrderRows = validOrderRows.filter(
|
||
orderRow => this.isInterceptedOrderStatus(orderRow && orderRow.intercept_status)
|
||
);
|
||
const lockedOrderRows = validOrderRows.filter(orderRow => this.isOrderLocked(orderRow));
|
||
const unlockedOrderRows = validOrderRows.filter(
|
||
orderRow => !this.isOrderLocked(orderRow)
|
||
&& !this.isInterceptedOrderStatus(orderRow && orderRow.intercept_status)
|
||
);
|
||
const interceptedOrders = interceptedOrderRows
|
||
.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(),
|
||
intercept_status: String(orderRow && orderRow.intercept_status || '').trim() || 'none',
|
||
status: 'intercepted',
|
||
status_text: '已拦截',
|
||
}));
|
||
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,
|
||
intercepted_count: interceptedOrders.length,
|
||
},
|
||
waveGroups: [],
|
||
locked_wave_groups: lockedWaveGroups,
|
||
wave_ids: validWaveIds,
|
||
locked_count: lockedOrders.length,
|
||
locked_orders: lockedOrders,
|
||
intercepted_count: interceptedOrders.length,
|
||
intercepted_orders: interceptedOrders,
|
||
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, normalizedWarehouseId);
|
||
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(await 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,
|
||
intercepted_count: interceptedOrders.length,
|
||
},
|
||
waveGroups,
|
||
locked_wave_groups: lockedWaveGroups,
|
||
wave_ids: validWaveIds,
|
||
locked_count: lockedOrders.length,
|
||
locked_orders: lockedOrders,
|
||
intercepted_count: interceptedOrders.length,
|
||
intercepted_orders: interceptedOrders,
|
||
ext: {
|
||
missing_wave_ids: missingWaveIds,
|
||
filtered_wave_ids: filteredWaveIds,
|
||
},
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 按订单ID拉取平台打印中间态数据。
|
||
*
|
||
* 与 getWavePlatformPrintData 输出完全相同的结构,但入参由波次ID改为订单ID。
|
||
* 跳过了波次查询步骤,直接从订单ID入手,其余打印数据组装、锁定/未锁定分离、
|
||
* 波次平台分组等逻辑与 getWavePlatformPrintData 保持一致。
|
||
* 仓库ID统一从当前上下文获取,不再接受调用方传入。
|
||
*
|
||
* @param {Object} params 请求参数。
|
||
* @param {Array<number|string>} params.orderIds 订单ID数组。
|
||
* @return {Promise<Object>} 平台打印中间态结果。
|
||
*/
|
||
async getOrderPrintData(params = {}) {
|
||
const requestParams = this.isPlainObject(params) ? params : {};
|
||
const {
|
||
orderIds,
|
||
} = requestParams;
|
||
|
||
const normalizedOrderIds = this.normalizeOrderIds(orderIds);
|
||
if (normalizedOrderIds.length === 0) {
|
||
throw new Error('order_ids 必填,且必须为非空数组');
|
||
}
|
||
|
||
const normalizedWarehouseId = this.getContextWarehouseId();
|
||
const orderRows = await this.queryOrdersByIds(normalizedOrderIds, normalizedWarehouseId);
|
||
if (orderRows.length === 0) {
|
||
return {
|
||
summary: {
|
||
total_waves: 0,
|
||
total_orders: 0,
|
||
total_platforms: 0,
|
||
intercepted_count: 0,
|
||
},
|
||
waveGroups: [],
|
||
wave_ids: [],
|
||
intercepted_count: 0,
|
||
intercepted_orders: [],
|
||
ext: {
|
||
missing_order_ids: normalizedOrderIds,
|
||
filtered_order_ids: [],
|
||
},
|
||
};
|
||
}
|
||
|
||
const hitOrderIdSet = new Set(orderRows.map(row => Number(row.id)));
|
||
const missingOrderIds = normalizedOrderIds.filter(orderId => !hitOrderIdSet.has(orderId));
|
||
|
||
// 订单级过滤:仅保留 post_status === 'fin' 的订单(等价于波次级的快递完全分配检查)
|
||
const postFinOrderRows = orderRows.filter(row => String(row && row.post_status || '').trim() === 'fin');
|
||
// 拦截订单从打印清单中剔除
|
||
const interceptedOrderRows = postFinOrderRows.filter(
|
||
row => this.isInterceptedOrderStatus(row && row.intercept_status)
|
||
);
|
||
const interceptedOrders = interceptedOrderRows.map(row => ({
|
||
order_id: Number(row && row.id || 0),
|
||
order_no: String(row && (row.delivery_order_code || row.source_order_codes) || '').trim(),
|
||
wave_id: Number(row && row.wave_id || 0),
|
||
wave_no: String(row && row.wave_no || '').trim(),
|
||
intercept_status: String(row && row.intercept_status || '').trim() || 'none',
|
||
status: 'intercepted',
|
||
status_text: '已拦截',
|
||
}));
|
||
const validOrderRows = postFinOrderRows.filter(
|
||
row => !this.isInterceptedOrderStatus(row && row.intercept_status)
|
||
);
|
||
const filteredOrderIds = orderRows
|
||
.filter(row => String(row && row.post_status || '').trim() !== 'fin')
|
||
.map(row => ({
|
||
order_id: Number(row && row.id || 0),
|
||
reason: '快递未完全分配',
|
||
}))
|
||
.concat(interceptedOrderRows.map(row => ({
|
||
order_id: Number(row && row.id || 0),
|
||
reason: '已拦截',
|
||
})));
|
||
|
||
if (validOrderRows.length === 0) {
|
||
return {
|
||
summary: {
|
||
total_waves: 0,
|
||
total_orders: 0,
|
||
total_platforms: 0,
|
||
intercepted_count: interceptedOrders.length,
|
||
},
|
||
waveGroups: [],
|
||
wave_ids: [],
|
||
intercepted_count: interceptedOrders.length,
|
||
intercepted_orders: interceptedOrders,
|
||
ext: {
|
||
missing_order_ids: missingOrderIds,
|
||
filtered_order_ids: filteredOrderIds,
|
||
},
|
||
};
|
||
}
|
||
|
||
const validOrderWaveIds = Array.from(new Set(validOrderRows
|
||
.map(row => Number(row && row.wave_id || 0))
|
||
.filter(waveId => Number.isInteger(waveId) && waveId > 0)));
|
||
|
||
const waveRows = await this.queryWavesByIds(normalizedWarehouseId, validOrderWaveIds);
|
||
|
||
const orderIdsForExpress = validOrderRows
|
||
.map(row => Number(row && row.id || 0))
|
||
.filter(orderId => Number.isInteger(orderId) && orderId > 0);
|
||
const orderExpressRows = await this.queryOrderExpressByOrderIds(orderIdsForExpress, normalizedWarehouseId);
|
||
this.assertBusinessWaybillCompleteness(orderIdsForExpress, orderExpressRows);
|
||
const cainiaoEnrichedOrderExpressRows = await this.enrichCainiaoOrderExpressRows(
|
||
validOrderRows,
|
||
orderExpressRows,
|
||
normalizedWarehouseId
|
||
);
|
||
const jdEnrichedOrderExpressRows = await this.enrichJdOrderExpressRows(
|
||
validOrderRows,
|
||
cainiaoEnrichedOrderExpressRows,
|
||
normalizedWarehouseId
|
||
);
|
||
const enrichedOrderExpressRows = await this.enrichPddDyOrderExpressRows(
|
||
validOrderRows,
|
||
jdEnrichedOrderExpressRows,
|
||
normalizedWarehouseId
|
||
);
|
||
const orderExpressMap = this.buildOrderExpressMap(enrichedOrderExpressRows);
|
||
const policyConfigMap = await this.getPolicyConfigMapByStore(validOrderRows, normalizedWarehouseId);
|
||
const pickingCandidateRows = validOrderRows.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(
|
||
orderIdsForExpress,
|
||
normalizedWarehouseId,
|
||
validOrderWaveIds
|
||
);
|
||
const waveIdsForCount = validOrderWaveIds;
|
||
const waveTotalOrderCountMap = await this.queryWaveTotalOrderCountMap(waveIdsForCount, normalizedWarehouseId);
|
||
const templateSampleCache = new Map();
|
||
const orderPrintList = [];
|
||
|
||
for (const orderRow of validOrderRows) {
|
||
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(await 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,
|
||
intercepted_count: interceptedOrders.length,
|
||
},
|
||
waveGroups,
|
||
wave_ids: validOrderWaveIds,
|
||
intercepted_count: interceptedOrders.length,
|
||
intercepted_orders: interceptedOrders,
|
||
ext: {
|
||
missing_order_ids: missingOrderIds,
|
||
filtered_order_ids: filteredOrderIds,
|
||
},
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 规范化“按分组解锁”规则。
|
||
*
|
||
* @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>} 规范化后的分组规则列表。
|
||
*/
|
||
/**
|
||
* 按运单号数组拉取平台打印中间态数据。
|
||
*
|
||
* 与 getOrderPrintData 输出相同的 waveGroups 结构,但入参改为运单号数组。
|
||
* 支持子单号(business_key > 1):
|
||
* - 主面单:与现有逻辑一致
|
||
* - 子面单:使用主订单的订单数据构建打印数据,但在自定义区追加 "子单号【{business_key}】-{主单号}" 行
|
||
*
|
||
* 仓库ID统一从当前上下文获取。
|
||
*
|
||
* @param {Object} params 请求参数。
|
||
* @param {Array<string>} params.waybillCodes 运单号数组。
|
||
* @return {Promise<Object>} 平台打印中间态结果。
|
||
*/
|
||
async getPrintDataByWaybillCodes(params = {}) {
|
||
const requestParams = this.isPlainObject(params) ? params : {};
|
||
const { waybillCodes } = requestParams;
|
||
|
||
if (!Array.isArray(waybillCodes) || waybillCodes.length === 0) {
|
||
throw new Error('waybill_codes 必填,且必须为非空数组');
|
||
}
|
||
|
||
const normalizedWaybillCodes = Array.from(new Set(
|
||
waybillCodes.map(code => String(code || '').trim()).filter(Boolean)
|
||
));
|
||
if (normalizedWaybillCodes.length === 0) {
|
||
throw new Error('waybill_codes 必填,且必须为非空数组');
|
||
}
|
||
|
||
const normalizedWarehouseId = this.getContextWarehouseId();
|
||
|
||
// 1. 按运单号查询运单记录(不限制 business_key,支持子单号)
|
||
const waybillRows = await this.queryWaybillsByCodes(normalizedWaybillCodes, normalizedWarehouseId);
|
||
if (waybillRows.length === 0) {
|
||
return {
|
||
summary: {
|
||
total_waves: 0,
|
||
total_orders: 0,
|
||
total_platforms: 0,
|
||
intercepted_count: 0,
|
||
},
|
||
waveGroups: [],
|
||
wave_ids: [],
|
||
intercepted_count: 0,
|
||
intercepted_orders: [],
|
||
ext: {
|
||
missing_waybill_codes: normalizedWaybillCodes,
|
||
filtered_waybill_codes: [],
|
||
},
|
||
};
|
||
}
|
||
|
||
const foundWaybillCodeSet = new Set(waybillRows.map(r => String(r.waybill_code || '').trim()));
|
||
const missingWaybillCodes = normalizedWaybillCodes.filter(code => !foundWaybillCodeSet.has(code));
|
||
|
||
// 2. 提取所有涉及的订单ID,查询订单
|
||
const orderIdSet = new Set(waybillRows.map(r => Number(r.order_id)).filter(id => id > 0));
|
||
const orderIds = Array.from(orderIdSet);
|
||
const orderRows = await this.queryOrdersByIds(orderIds, normalizedWarehouseId);
|
||
const orderRowMap = new Map(orderRows.map(row => [ Number(row.id), row ]));
|
||
|
||
// 过滤未找到订单的运单
|
||
const validWaybillRows = waybillRows.filter(row => orderRowMap.has(Number(row.order_id)));
|
||
const invalidWaybillCodes = waybillRows
|
||
.filter(row => !orderRowMap.has(Number(row.order_id)))
|
||
.map(row => ({
|
||
waybill_code: String(row.waybill_code || '').trim(),
|
||
reason: '关联订单未找到或不属于当前仓库',
|
||
}));
|
||
|
||
if (validWaybillRows.length === 0) {
|
||
return {
|
||
summary: {
|
||
total_waves: 0,
|
||
total_orders: 0,
|
||
total_platforms: 0,
|
||
intercepted_count: 0,
|
||
},
|
||
waveGroups: [],
|
||
wave_ids: [],
|
||
intercepted_count: 0,
|
||
intercepted_orders: [],
|
||
ext: {
|
||
missing_waybill_codes: missingWaybillCodes,
|
||
filtered_waybill_codes: invalidWaybillCodes,
|
||
},
|
||
};
|
||
}
|
||
|
||
// 3. 过滤 post_status !== 'fin' 或进入拦截流程的订单
|
||
const interceptedOrderRows = orderRows.filter(
|
||
row => this.isInterceptedOrderStatus(row && row.intercept_status)
|
||
);
|
||
const interceptedOrderIdSet = new Set(interceptedOrderRows.map(row => Number(row.id)));
|
||
const interceptedOrders = interceptedOrderRows.map(row => ({
|
||
order_id: Number(row && row.id || 0),
|
||
order_no: String(row && (row.delivery_order_code || row.source_order_codes) || '').trim(),
|
||
wave_id: Number(row && row.wave_id || 0),
|
||
wave_no: String(row && row.wave_no || '').trim(),
|
||
intercept_status: String(row && row.intercept_status || '').trim() || 'none',
|
||
status: 'intercepted',
|
||
status_text: '已拦截',
|
||
}));
|
||
const validOrderIdSet = new Set(
|
||
orderRows
|
||
.filter(row => String(row.post_status || '').trim() === 'fin'
|
||
&& !this.isInterceptedOrderStatus(row && row.intercept_status))
|
||
.map(row => Number(row.id))
|
||
);
|
||
const finalWaybillRows = validWaybillRows.filter(row => validOrderIdSet.has(Number(row.order_id)));
|
||
const filteredWaybillCodes = validWaybillRows
|
||
.filter(row => !validOrderIdSet.has(Number(row.order_id)))
|
||
.map(row => ({
|
||
waybill_code: String(row.waybill_code || '').trim(),
|
||
reason: interceptedOrderIdSet.has(Number(row.order_id))
|
||
? '关联订单已被拦截'
|
||
: '关联订单快递未完全分配',
|
||
}));
|
||
|
||
if (finalWaybillRows.length === 0) {
|
||
return {
|
||
summary: {
|
||
total_waves: 0,
|
||
total_orders: 0,
|
||
total_platforms: 0,
|
||
intercepted_count: interceptedOrders.length,
|
||
},
|
||
waveGroups: [],
|
||
wave_ids: [],
|
||
intercepted_count: interceptedOrders.length,
|
||
intercepted_orders: interceptedOrders,
|
||
ext: {
|
||
missing_waybill_codes: missingWaybillCodes,
|
||
filtered_waybill_codes: [ ...invalidWaybillCodes, ...filteredWaybillCodes ],
|
||
},
|
||
};
|
||
}
|
||
|
||
// 4. 收集有效订单行
|
||
const validOrderRows = Array.from(
|
||
new Map(orderRows.filter(row => validOrderIdSet.has(Number(row.id))).map(row => [ Number(row.id), row ])).values()
|
||
);
|
||
|
||
// 4b. 对命中的所有运单行做平台增强(主单和子单各自走自己的增强,密文/签名/参数按运单独立)
|
||
const waybillRowsForEnrich = finalWaybillRows.map(row => ({ ...row }));
|
||
const cainiaoEnrichedWaybillRows = await this.enrichCainiaoOrderExpressRows(
|
||
validOrderRows, waybillRowsForEnrich, normalizedWarehouseId
|
||
);
|
||
const jdEnrichedWaybillRows = await this.enrichJdOrderExpressRows(
|
||
validOrderRows, cainiaoEnrichedWaybillRows, normalizedWarehouseId
|
||
);
|
||
const enrichedWaybillRows = await this.enrichPddDyOrderExpressRows(
|
||
validOrderRows, jdEnrichedWaybillRows, normalizedWarehouseId
|
||
);
|
||
// 构建 order_id → 增强后运单列表的映射(同一订单可能有多个运单)
|
||
const enrichedWaybillMap = new Map();
|
||
for (const row of enrichedWaybillRows) {
|
||
const oid = Number(row.order_id);
|
||
if (!enrichedWaybillMap.has(oid)) {
|
||
enrichedWaybillMap.set(oid, []);
|
||
}
|
||
enrichedWaybillMap.get(oid).push(row);
|
||
}
|
||
|
||
// 4c. 获取每个订单的主运单(business_key=1),用于子面单自定义区追加主运单号
|
||
const mainWaybillMap = await this.getMainWaybillMapByOrderIds(orderIds, normalizedWarehouseId);
|
||
|
||
// 5. 获取策略配置
|
||
const policyConfigMap = await this.getPolicyConfigMapByStore(validOrderRows, normalizedWarehouseId);
|
||
|
||
// 6. 拣货明细、波次序号等辅助数据
|
||
const pickingCandidateRows = validOrderRows.filter(orderRow => {
|
||
const storeId = Number(orderRow.store_id || 0);
|
||
const policyConfig = policyConfigMap.get(storeId) || {};
|
||
return this.shouldLoadPickingDetails(policyConfig);
|
||
});
|
||
const printOrderRowMap = await this.buildPrintOrderRowMapWithPicking(pickingCandidateRows, normalizedWarehouseId);
|
||
|
||
const validOrderWaveIds = Array.from(new Set(validOrderRows
|
||
.map(row => Number(row.wave_id || 0))
|
||
.filter(waveId => Number.isInteger(waveId) && waveId > 0)));
|
||
const waveRows = await this.queryWavesByIds(normalizedWarehouseId, validOrderWaveIds);
|
||
|
||
const orderIdsForIndex = validOrderRows.map(row => Number(row.id)).filter(id => id > 0);
|
||
const waveOrderIndexMap = await this.queryWaveOrderIndexMapByOrderIds(
|
||
orderIdsForIndex, normalizedWarehouseId, validOrderWaveIds
|
||
);
|
||
const waveTotalOrderCountMap = await this.queryWaveTotalOrderCountMap(validOrderWaveIds, normalizedWarehouseId);
|
||
const templateSampleCache = new Map();
|
||
|
||
// 7. 为每个运单构建打印数据
|
||
const orderPrintList = [];
|
||
for (const enrichedRow of enrichedWaybillRows) {
|
||
const orderId = Number(enrichedRow.order_id);
|
||
const orderRow = orderRowMap.get(orderId);
|
||
if (!orderRow) continue;
|
||
|
||
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.store_id || 0);
|
||
const policyConfig = policyConfigMap.get(storeId) || {};
|
||
const platformCode = this.resolvePrintPlatformCode(effectiveOrderRow, enrichedRow);
|
||
const templateSample = this.loadTemplateSampleByPlatform(platformCode, templateSampleCache);
|
||
|
||
// 子面单:自定义区首行追加子单号标识
|
||
const businessKey = Number(enrichedRow.business_key || 1);
|
||
const mainWaybill = mainWaybillMap.get(orderId);
|
||
const mainWaybillCode = mainWaybill ? String(mainWaybill.waybill_code || '').trim() : '';
|
||
const isChildWaybill = businessKey > 1 && mainWaybillCode;
|
||
|
||
const extraCustomLines = isChildWaybill
|
||
? [ `子单号【${businessKey}】-${mainWaybillCode}` ]
|
||
: [];
|
||
|
||
orderPrintList.push(await this.buildOrderPlatformPrintItem({
|
||
orderRow: effectiveOrderRowWithWaveIndex,
|
||
orderExpress: enrichedRow,
|
||
policyConfig,
|
||
platformCode,
|
||
templateSample,
|
||
extraCustomLines,
|
||
}));
|
||
}
|
||
|
||
// 8. 分组输出
|
||
// 分离有波次和无波次的打印条目
|
||
const wavedItems = orderPrintList.filter(item => Number(item && item.wave_id || 0) > 0);
|
||
const noWaveItems = orderPrintList.filter(item => Number(item && item.wave_id || 0) === 0);
|
||
|
||
const waveGroups = this.groupOrderPrintItemsByWaveAndPlatform({
|
||
waveRows,
|
||
hitWaveIds: validOrderWaveIds,
|
||
orderPrintList: wavedItems,
|
||
});
|
||
|
||
// 无波次条目按平台直接分组
|
||
if (noWaveItems.length > 0) {
|
||
const noWavePlatforms = this.groupOrderPrintItemsByPlatform(noWaveItems);
|
||
waveGroups.push({
|
||
wave_id: 0,
|
||
wave_no: '',
|
||
order_count: noWaveItems.length,
|
||
platforms: noWavePlatforms,
|
||
});
|
||
// 将 0 加入 wave_ids 表示有无波次条目
|
||
if (!validOrderWaveIds.includes(0)) {
|
||
validOrderWaveIds.push(0);
|
||
}
|
||
}
|
||
|
||
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,
|
||
intercepted_count: interceptedOrders.length,
|
||
},
|
||
waveGroups,
|
||
wave_ids: validOrderWaveIds,
|
||
intercepted_count: interceptedOrders.length,
|
||
intercepted_orders: interceptedOrders,
|
||
ext: {
|
||
missing_waybill_codes: missingWaybillCodes,
|
||
filtered_waybill_codes: [ ...invalidWaybillCodes, ...filteredWaybillCodes ],
|
||
},
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 按运单号数组查询运单记录(不限制 business_key,支持子单号)。
|
||
*
|
||
* @param {string[]} waybillCodes 运单号数组。
|
||
* @param {number} warehouseId 仓库ID。
|
||
* @return {Promise<Array<Object>>} 运单记录数组。
|
||
*/
|
||
async queryWaybillsByCodes(waybillCodes = [], warehouseId) {
|
||
if (!Array.isArray(waybillCodes) || waybillCodes.length === 0) {
|
||
return [];
|
||
}
|
||
|
||
const normalizedCodes = Array.from(new Set(
|
||
waybillCodes.map(code => String(code || '').trim()).filter(Boolean)
|
||
));
|
||
if (normalizedCodes.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: {
|
||
waybill_code: {
|
||
[Op.in]: normalizedCodes,
|
||
},
|
||
warehouse_id: warehouseId,
|
||
},
|
||
order: [[ 'order_id', 'ASC' ], [ 'business_key', 'ASC' ], [ 'id', 'ASC' ]],
|
||
raw: true,
|
||
});
|
||
|
||
return Array.isArray(rows) ? rows : [];
|
||
}
|
||
|
||
/**
|
||
* 按订单ID列表获取主运单映射(business_key=1)。
|
||
*
|
||
* @param {number[]} orderIds 订单ID数组。
|
||
* @param {number} warehouseId 仓库ID。
|
||
* @return {Promise<Map<number, Object>>} order_id → 主运单记录。
|
||
*/
|
||
async getMainWaybillMapByOrderIds(orderIds = [], warehouseId) {
|
||
const map = new Map();
|
||
if (!Array.isArray(orderIds) || orderIds.length === 0) {
|
||
return map;
|
||
}
|
||
|
||
const normalizedOrderIds = Array.from(new Set(
|
||
orderIds.map(id => Number(id)).filter(id => Number.isInteger(id) && id > 0)
|
||
));
|
||
if (normalizedOrderIds.length === 0) {
|
||
return map;
|
||
}
|
||
|
||
const rows = await this.ctx.model.OrderExpress.findAll({
|
||
attributes: [ 'id', 'order_id', 'business_key', 'waybill_code' ],
|
||
where: {
|
||
order_id: { [Op.in]: normalizedOrderIds },
|
||
warehouse_id: warehouseId,
|
||
business_key: 1,
|
||
},
|
||
raw: true,
|
||
});
|
||
|
||
for (const row of rows) {
|
||
map.set(Number(row.order_id), row);
|
||
}
|
||
return map;
|
||
}
|
||
|
||
/**
|
||
* 规范化"按分组解锁"规则。
|
||
*
|
||
* @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 {Array<number|string>} orderIds 订单ID数组。
|
||
* @return {Array<number>} 规范化后的订单ID数组。
|
||
*/
|
||
normalizeOrderIds(orderIds = []) {
|
||
if (!Array.isArray(orderIds)) {
|
||
return [];
|
||
}
|
||
|
||
const normalizedSet = new Set();
|
||
|
||
for (const rawId of orderIds) {
|
||
const normalizedId = Number(String(rawId ?? '').trim());
|
||
if (Number.isInteger(normalizedId) && normalizedId > 0) {
|
||
normalizedSet.add(normalizedId);
|
||
}
|
||
}
|
||
|
||
return Array.from(normalizedSet);
|
||
}
|
||
|
||
/**
|
||
* 从当前上下文获取仓库ID。
|
||
*
|
||
* 用于不再接受调用方传入 warehouseId 的场景,直接从登录态/上下文读取。
|
||
*
|
||
* @return {number} 当前上下文中的仓库ID。
|
||
*/
|
||
getContextWarehouseId() {
|
||
const contextWarehouseId = Number(this.getWarehouseId() || 0);
|
||
if (!Number.isInteger(contextWarehouseId) || contextWarehouseId <= 0) {
|
||
throw new Error('缺少当前用户仓库上下文 store_id');
|
||
}
|
||
return contextWarehouseId;
|
||
}
|
||
|
||
/**
|
||
* 解析并校验仓库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',
|
||
'intercept_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批量查询订单明细。
|
||
*
|
||
* 与 queryOrdersByWaveIds 返回相同的字段结构,但按订单 ID 列表直接查询。
|
||
*
|
||
* @param {Array<number>} orderIds 订单ID数组。
|
||
* @param {number} warehouseId 仓库ID。
|
||
* @return {Promise<Array<Object>>} 订单明细列表。
|
||
*/
|
||
async queryOrdersByIds(orderIds = [], warehouseId) {
|
||
if (!Array.isArray(orderIds) || orderIds.length === 0) {
|
||
return [];
|
||
}
|
||
|
||
// 公共查询字段:current 表与 dispatch 表使用相同字段选择
|
||
const sharedAttributes = [
|
||
'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',
|
||
'intercept_status',
|
||
'items_count',
|
||
'items_total',
|
||
'items_weight',
|
||
'freight',
|
||
'create_at',
|
||
'pay_time',
|
||
];
|
||
|
||
// 第一步:查询 current 主表(wms_order_delivery_{warehouseId})
|
||
const orderModel = await this.getOrderModel('order', warehouseId);
|
||
const rows = await orderModel.findAll({
|
||
attributes: sharedAttributes,
|
||
where: {
|
||
id: {
|
||
[Op.in]: orderIds,
|
||
},
|
||
},
|
||
order: [[ 'wave_id', 'ASC' ], [ 'id', 'ASC' ]],
|
||
raw: true,
|
||
});
|
||
|
||
const currentRows = Array.isArray(rows) ? rows : [];
|
||
|
||
// 第二步:若 current 表未命中全部订单,计算缺失 ID 并兜底查询 dispatch 表
|
||
if (currentRows.length < orderIds.length) {
|
||
const foundIds = new Set(currentRows.map(row => row.id));
|
||
const missingIds = orderIds.filter(id => !foundIds.has(id));
|
||
|
||
try {
|
||
// 获取 dispatch 分表模型,表可能不存在(返回 null)
|
||
const dispatchModel = await this.getOrderModelByTableType('dispatch', warehouseId);
|
||
if (dispatchModel) {
|
||
const dispatchRows = await dispatchModel.findAll({
|
||
attributes: sharedAttributes,
|
||
where: {
|
||
id: {
|
||
[Op.in]: missingIds,
|
||
},
|
||
},
|
||
order: [[ 'wave_id', 'ASC' ], [ 'id', 'ASC' ]],
|
||
raw: true,
|
||
});
|
||
|
||
if (Array.isArray(dispatchRows) && dispatchRows.length > 0) {
|
||
// 合并 current 表与 dispatch 表结果,按 wave_id、id 升序排列
|
||
const mergedRows = [ ...currentRows, ...dispatchRows ].sort((a, b) => {
|
||
const waveDiff = (a.wave_id || 0) - (b.wave_id || 0);
|
||
if (waveDiff !== 0) return waveDiff;
|
||
return (a.id || 0) - (b.id || 0);
|
||
});
|
||
return mergedRows;
|
||
}
|
||
}
|
||
} catch (err) {
|
||
// dispatch 表查询失败时仅记录日志,不影响 current 表已查到的结果
|
||
this.ctx.logger.warn(
|
||
`[queryOrdersByIds] dispatch 兜底查询失败,将仅返回 current 表结果:${err.message}`
|
||
);
|
||
}
|
||
}
|
||
|
||
return currentRows;
|
||
}
|
||
|
||
/**
|
||
* 按订单ID批量查询快递单信息。
|
||
*
|
||
* @param {Array<number>} orderIds 订单ID数组。
|
||
* @return {Promise<Array<Object>>} 快递单信息列表。
|
||
*/
|
||
/**
|
||
* 根据订单 ID 列表批量查询运单记录。
|
||
* 返回 business_key=1 的主运单,按 order_id、business_key、id 升序排列。
|
||
*
|
||
* @param {number[]} orderIds 订单 ID 列表。
|
||
* @param warehouseId
|
||
* @return {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 = [], warehouseId) {
|
||
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,
|
||
},
|
||
warehouse_id: warehouseId,
|
||
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 {Promise<Object>} 逐单打印中间态。
|
||
*/
|
||
async 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 extraCustomLines = Array.isArray(requestPayload.extraCustomLines) ? requestPayload.extraCustomLines : [];
|
||
|
||
// 查最匹配的包材名称(基于 items_hash)
|
||
let suggestedPackageMaterialName = '';
|
||
const itemsHash = String(orderRow.items_hash || '').trim();
|
||
const itemsCrc = Number(orderRow.items_crc || 0);
|
||
if (itemsHash) {
|
||
const relationModel = this.ctx.model && this.ctx.model.PackageMaterialItemRelation;
|
||
if (relationModel) {
|
||
const topMatch = await relationModel.findOne({
|
||
where: {
|
||
warehouse_id: Number(orderRow.warehouse_id || 0),
|
||
items_hash: itemsHash,
|
||
items_crc: itemsCrc,
|
||
is_active: 1,
|
||
delete_at: null,
|
||
},
|
||
order: [[ 'bind_count', 'DESC' ]],
|
||
attributes: [ 'package_material_name' ],
|
||
raw: true,
|
||
});
|
||
if (topMatch && topMatch.package_material_name) {
|
||
suggestedPackageMaterialName = String(topMatch.package_material_name).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}`;
|
||
|
||
// 查询仓库 subject_config 用于发件人兜底
|
||
const warehouseId = Number(orderRow.warehouse_id || 0);
|
||
let subjectConfig = {};
|
||
if (warehouseId > 0) {
|
||
const storeRow = await this.ctx.model.Store.findByPk(warehouseId, {
|
||
attributes: [ 'subject_config' ],
|
||
raw: true,
|
||
});
|
||
if (storeRow && storeRow.subject_config) {
|
||
subjectConfig = this.isPlainObject(storeRow.subject_config)
|
||
? storeRow.subject_config
|
||
: {};
|
||
}
|
||
}
|
||
|
||
const printPayload = PrinterDataBuilder.buildPlatformRequestSkeleton({
|
||
platform: platformCode,
|
||
order_express: orderExpress,
|
||
order_delivery: orderRow,
|
||
store_contract: {
|
||
policy_config: policyConfig,
|
||
},
|
||
policy_config: policyConfig,
|
||
subject_config: subjectConfig,
|
||
template_sample: templateSample,
|
||
options: {
|
||
requestId,
|
||
taskId: requestId,
|
||
documentId,
|
||
packageMaterialName: suggestedPackageMaterialName,
|
||
extraCustomLines,
|
||
customAreaBaseUrl: this.ctx.app.config.customAreaBaseUrl || '',
|
||
},
|
||
});
|
||
const printData = this.extractSinglePlatformPrintData(printPayload);
|
||
// 子面单场景:同一运单号可能对应多个 business_key,注入 business_key 到返回文档中供调用方区分
|
||
if (printData && typeof printData === 'object' && !Array.isArray(printData)) {
|
||
const expressBusinessKey = Number(orderExpress.business_key || 1);
|
||
if (expressBusinessKey > 1) {
|
||
printData.business_key = expressBusinessKey;
|
||
}
|
||
}
|
||
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,
|
||
};
|
||
}
|
||
|
||
}
|
||
|
||
module.exports = OrderPrintSystemService;
|