refactor(print): 打印模块重构
- 新增 systems/order_print.js 订单打印业务层(getPrintDataByWaybillCodes 等) - print.js 删除 retry 补偿相关代码(normalizeRetrySendPayload/getRetryEligibility) - order/print.js 新增 getPrintDataByWaybillCodes 方法 - printer_data_builder.js 新增 appendExtraCustomLines + extraCustomLines 参数支持 - polo_api_client.js 添加调试缓存 - 删除 print_retry_compensation 定时任务测试
This commit is contained in:
parent
3736d306bd
commit
5378fcd137
@ -49,6 +49,9 @@ class PoloApiClient {
|
||||
.map(key => `${key}=${encodeURIComponent(signMap[key])}`)
|
||||
.join('&');
|
||||
console.log('查询菠萝派平台数据,接口URL:', config.interface_url, '入参bizcontent:', JSON.stringify(bizcontent));
|
||||
|
||||
await this.ctx.app.setCacheAsync('PoloApiquery', '查询菠萝派平台数据,接口URL:' + config.interface_url + ',入参bizcontent:' + formBody, 3600);
|
||||
|
||||
const response = await this.ctx.curl(String(config.interface_url || ''), {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
|
||||
@ -556,6 +556,23 @@ function buildWaybillCustomProductInfoLines(items, policyConfig = {}, options =
|
||||
return [ headerLine, ...detailLines ];
|
||||
}
|
||||
|
||||
/**
|
||||
* 向已有的自定义区文本追加额外行。
|
||||
* @param {string} customText 已有的自定义区文本。
|
||||
* @param {Array<string>} extraLines 额外文本行数组。
|
||||
* @param {string} [lineBreak='\n'] 换行符。
|
||||
* @return {string} 追加后的文本。
|
||||
*/
|
||||
function appendExtraCustomLines(customText, extraLines, lineBreak = '\n') {
|
||||
const safeLines = Array.isArray(extraLines) ? extraLines.filter(line => String(line || '').trim() !== '') : [];
|
||||
if (safeLines.length === 0) {
|
||||
return customText;
|
||||
}
|
||||
const prefix = safeLines.join(lineBreak);
|
||||
const base = String(customText || '').trim();
|
||||
return base ? `${prefix}${lineBreak}${base}` : prefix;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将自定义文本行按平台换行符合并为字符串。
|
||||
* @param {Array<string>} lines 文本行数组。
|
||||
@ -1237,7 +1254,7 @@ function sanitizeTemplatePrivateFields(value, warnings, currentKey = '') {
|
||||
* @param {Object} policyConfig 策略配置对象。
|
||||
* @param {string} customDataTemplateURL 自定义区模板地址默认值。
|
||||
*/
|
||||
function applyKuaishouExpressFieldMapping(platform, skeleton, orderExpress, orderDelivery, warnings, policyConfig, customDataTemplateURL) {
|
||||
function applyKuaishouExpressFieldMapping(platform, skeleton, orderExpress, orderDelivery, warnings, policyConfig, customDataTemplateURL, extraCustomLines = []) {
|
||||
if (platform !== 'kuaishou') {
|
||||
return;
|
||||
}
|
||||
@ -1278,9 +1295,13 @@ function applyKuaishouExpressFieldMapping(platform, skeleton, orderExpress, orde
|
||||
fallbackTotalQty: Number(safeOrderDelivery.items_count || safeOrderDelivery.items_total || 0),
|
||||
}
|
||||
);
|
||||
const customProductInfo = mergeWaybillCustomLines(customProductInfoLines, {
|
||||
lineBreak: LINE_BREAK_MAP.LF,
|
||||
});
|
||||
const customProductInfo = appendExtraCustomLines(
|
||||
mergeWaybillCustomLines(customProductInfoLines, {
|
||||
lineBreak: LINE_BREAK_MAP.LF,
|
||||
}),
|
||||
extraCustomLines,
|
||||
LINE_BREAK_MAP.LF
|
||||
);
|
||||
|
||||
for (const document of documents) {
|
||||
if (!isPlainObject(document)) {
|
||||
@ -1382,7 +1403,7 @@ function applyKuaishouExpressFieldMapping(platform, skeleton, orderExpress, orde
|
||||
* @param {Object} orderDelivery 订单对象。
|
||||
* @param {Object} policyConfig 策略配置对象。
|
||||
*/
|
||||
function applyPddExpressFieldMapping(platform, skeleton, orderExpress, orderDelivery, policyConfig) {
|
||||
function applyPddExpressFieldMapping(platform, skeleton, orderExpress, orderDelivery, policyConfig, extraCustomLines = []) {
|
||||
if (platform !== 'pdd') {
|
||||
return;
|
||||
}
|
||||
@ -1423,10 +1444,14 @@ function applyPddExpressFieldMapping(platform, skeleton, orderExpress, orderDeli
|
||||
fallbackTotalQty: Number(safeOrderDelivery.items_count || safeOrderDelivery.items_total || 0),
|
||||
}
|
||||
);
|
||||
const customProductInfo = mergeWaybillCustomLines(customProductInfoLines, {
|
||||
lineBreak: LINE_BREAK_MAP.CR,
|
||||
trailingLineBreak: true,
|
||||
});
|
||||
const customProductInfo = appendExtraCustomLines(
|
||||
mergeWaybillCustomLines(customProductInfoLines, {
|
||||
lineBreak: LINE_BREAK_MAP.CR,
|
||||
trailingLineBreak: true,
|
||||
}),
|
||||
extraCustomLines,
|
||||
LINE_BREAK_MAP.CR
|
||||
);
|
||||
|
||||
/**
|
||||
* 判断内容对象是否属于拼多多自定义区。
|
||||
@ -1560,7 +1585,7 @@ function resolveDouyinParams(orderExpress) {
|
||||
* @param {Object} orderDelivery 订单对象。
|
||||
* @param {Object} policyConfig 策略配置对象。
|
||||
*/
|
||||
function applyDouyinExpressFieldMapping(platform, skeleton, orderExpress, orderDelivery, policyConfig) {
|
||||
function applyDouyinExpressFieldMapping(platform, skeleton, orderExpress, orderDelivery, policyConfig, extraCustomLines = []) {
|
||||
if (platform !== 'douyin') {
|
||||
return;
|
||||
}
|
||||
@ -1610,7 +1635,11 @@ function applyDouyinExpressFieldMapping(platform, skeleton, orderExpress, orderD
|
||||
fallbackTotalQty: Number(safeOrderDelivery.items_count || safeOrderDelivery.items_total || 0),
|
||||
}
|
||||
);
|
||||
const customProductInfo = mergeWaybillCustomLines(customProductInfoLines, { lineBreak: '\n' });
|
||||
const customProductInfo = appendExtraCustomLines(
|
||||
mergeWaybillCustomLines(customProductInfoLines, { lineBreak: '\n' }),
|
||||
extraCustomLines,
|
||||
'\n'
|
||||
);
|
||||
|
||||
for (const document of documents) {
|
||||
if (!isPlainObject(document)) {
|
||||
@ -1700,7 +1729,8 @@ function applyCainiaoExpressFieldMapping(
|
||||
orderDelivery,
|
||||
policyConfig,
|
||||
customControlTemplateURL,
|
||||
warnings
|
||||
warnings,
|
||||
extraCustomLines = []
|
||||
) {
|
||||
if (platform !== 'cainiao') {
|
||||
return;
|
||||
@ -1743,9 +1773,13 @@ function applyCainiaoExpressFieldMapping(
|
||||
fallbackTotalQty: Number(safeOrderDelivery.items_count || safeOrderDelivery.items_total || 0),
|
||||
}
|
||||
);
|
||||
const customControlText = mergeWaybillCustomLines(customProductInfoLines, {
|
||||
lineBreak: LINE_BREAK_MAP.CR,
|
||||
});
|
||||
const customControlText = appendExtraCustomLines(
|
||||
mergeWaybillCustomLines(customProductInfoLines, {
|
||||
lineBreak: LINE_BREAK_MAP.CR,
|
||||
}),
|
||||
extraCustomLines,
|
||||
LINE_BREAK_MAP.CR
|
||||
);
|
||||
|
||||
for (const document of documents) {
|
||||
if (!isPlainObject(document)) {
|
||||
@ -1904,7 +1938,8 @@ function applyXhsExpressFieldMapping(
|
||||
orderExpress,
|
||||
orderDelivery,
|
||||
policyConfig,
|
||||
warnings
|
||||
warnings,
|
||||
extraCustomLines = []
|
||||
) {
|
||||
if (platform !== 'xhs') {
|
||||
return;
|
||||
@ -1944,9 +1979,13 @@ function applyXhsExpressFieldMapping(
|
||||
fallbackTotalQty: Number(safeOrderDelivery.items_count || safeOrderDelivery.items_total || 0),
|
||||
}
|
||||
);
|
||||
const customProductInfo = mergeWaybillCustomLines(customProductInfoLines, {
|
||||
lineBreak: LINE_BREAK_MAP.LF,
|
||||
});
|
||||
const customProductInfo = appendExtraCustomLines(
|
||||
mergeWaybillCustomLines(customProductInfoLines, {
|
||||
lineBreak: LINE_BREAK_MAP.LF,
|
||||
}),
|
||||
extraCustomLines,
|
||||
LINE_BREAK_MAP.LF
|
||||
);
|
||||
|
||||
for (const document of documents) {
|
||||
if (!isPlainObject(document)) {
|
||||
@ -2000,7 +2039,8 @@ function applySphExpressFieldMapping(
|
||||
skeleton,
|
||||
orderExpress,
|
||||
orderDelivery,
|
||||
policyConfig
|
||||
policyConfig,
|
||||
extraCustomLines = []
|
||||
) {
|
||||
if (platform !== 'sph') {
|
||||
return;
|
||||
@ -2054,9 +2094,13 @@ function applySphExpressFieldMapping(
|
||||
fallbackTotalQty: Number(safeOrderDelivery.items_count || safeOrderDelivery.items_total || 0),
|
||||
}
|
||||
);
|
||||
const customProductInfo = mergeWaybillCustomLines(customProductInfoLines, {
|
||||
lineBreak: LINE_BREAK_MAP.LF,
|
||||
}).replace(/\n/g, '<br>');
|
||||
const customProductInfo = appendExtraCustomLines(
|
||||
mergeWaybillCustomLines(customProductInfoLines, {
|
||||
lineBreak: LINE_BREAK_MAP.LF,
|
||||
}).replace(/\n/g, '<br>'),
|
||||
extraCustomLines,
|
||||
'<br>'
|
||||
);
|
||||
|
||||
task.customInfo = isPlainObject(task.customInfo) ? task.customInfo : {};
|
||||
task.customInfo.data = isPlainObject(task.customInfo.data) ? task.customInfo.data : {};
|
||||
@ -2137,7 +2181,8 @@ function applyJdExpressFieldMapping(
|
||||
orderDelivery,
|
||||
policyConfig,
|
||||
templateSample,
|
||||
warnings
|
||||
warnings,
|
||||
extraCustomLines = []
|
||||
) {
|
||||
if (platform !== 'jd') {
|
||||
return;
|
||||
@ -2220,10 +2265,14 @@ function applyJdExpressFieldMapping(
|
||||
fallbackTotalQty: Number(safeOrderDelivery.items_count || safeOrderDelivery.items_total || 0),
|
||||
}
|
||||
);
|
||||
const customProductInfo = mergeWaybillCustomLines(customProductInfoLines, {
|
||||
lineBreak: LINE_BREAK_MAP.LF,
|
||||
trailingLineBreak: true,
|
||||
});
|
||||
const customProductInfo = appendExtraCustomLines(
|
||||
mergeWaybillCustomLines(customProductInfoLines, {
|
||||
lineBreak: LINE_BREAK_MAP.LF,
|
||||
trailingLineBreak: true,
|
||||
}),
|
||||
extraCustomLines,
|
||||
LINE_BREAK_MAP.LF
|
||||
);
|
||||
|
||||
content.customData = isPlainObject(content.customData) ? content.customData : {};
|
||||
content.customData.GoodsInfo = customProductInfo;
|
||||
@ -2243,6 +2292,7 @@ function buildPlatformRequestSkeleton(input = {}) {
|
||||
|
||||
const baseResult = buildBaseData(input, normalized.platform, normalized.meta);
|
||||
const options = isPlainObject(input.options) ? input.options : {};
|
||||
const extraCustomLines = Array.isArray(options.extraCustomLines) ? options.extraCustomLines : [];
|
||||
const policyConfig = resolvePolicyConfig(input);
|
||||
const orderExpressForCompose = isPlainObject(input.order_express)
|
||||
? { ...input.order_express }
|
||||
@ -2335,7 +2385,8 @@ function buildPlatformRequestSkeleton(input = {}) {
|
||||
orderDeliveryForCompose,
|
||||
policyConfig,
|
||||
cainiaoCustomControlTemplateURL,
|
||||
warnings
|
||||
warnings,
|
||||
extraCustomLines
|
||||
);
|
||||
|
||||
applyKuaishouExpressFieldMapping(
|
||||
@ -2345,7 +2396,8 @@ function buildPlatformRequestSkeleton(input = {}) {
|
||||
orderDeliveryForCompose,
|
||||
warnings,
|
||||
policyConfig,
|
||||
customDataTemplateURL
|
||||
customDataTemplateURL,
|
||||
extraCustomLines
|
||||
);
|
||||
|
||||
applyPddExpressFieldMapping(
|
||||
@ -2353,7 +2405,8 @@ function buildPlatformRequestSkeleton(input = {}) {
|
||||
skeleton,
|
||||
orderExpressForCompose,
|
||||
orderDeliveryForCompose,
|
||||
policyConfig
|
||||
policyConfig,
|
||||
extraCustomLines
|
||||
);
|
||||
|
||||
applyDouyinExpressFieldMapping(
|
||||
@ -2361,7 +2414,8 @@ function buildPlatformRequestSkeleton(input = {}) {
|
||||
skeleton,
|
||||
orderExpressForCompose,
|
||||
orderDeliveryForCompose,
|
||||
policyConfig
|
||||
policyConfig,
|
||||
extraCustomLines
|
||||
);
|
||||
|
||||
applyJdExpressFieldMapping(
|
||||
@ -2371,7 +2425,8 @@ function buildPlatformRequestSkeleton(input = {}) {
|
||||
orderDeliveryForCompose,
|
||||
policyConfig,
|
||||
templateSample,
|
||||
warnings
|
||||
warnings,
|
||||
extraCustomLines
|
||||
);
|
||||
|
||||
applyXhsExpressFieldMapping(
|
||||
@ -2380,7 +2435,8 @@ function buildPlatformRequestSkeleton(input = {}) {
|
||||
orderExpressForCompose,
|
||||
orderDeliveryForCompose,
|
||||
policyConfig,
|
||||
warnings
|
||||
warnings,
|
||||
extraCustomLines
|
||||
);
|
||||
|
||||
applySphExpressFieldMapping(
|
||||
@ -2388,7 +2444,8 @@ function buildPlatformRequestSkeleton(input = {}) {
|
||||
skeleton,
|
||||
orderExpressForCompose,
|
||||
orderDeliveryForCompose,
|
||||
policyConfig
|
||||
policyConfig,
|
||||
extraCustomLines
|
||||
);
|
||||
|
||||
return {
|
||||
|
||||
@ -11,9 +11,9 @@ class OrderPrintService extends OrderBaseService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = '';
|
||||
const _noNeedRight = 'getWavePrintData,getWavePlatformPrintData,unlockWavePlatformPrintDataByGroup,getOrderPrintData';
|
||||
const _noNeedLog = 'getWavePrintData,unlockWavePlatformPrintDataByGroup,getOrderPrintData';
|
||||
const _noNeedAuth = 'getWavePrintData,getWavePlatformPrintData,unlockWavePlatformPrintDataByGroup,getOrderPrintData';
|
||||
const _noNeedRight = 'getWavePrintData,getWavePlatformPrintData,unlockWavePlatformPrintDataByGroup,getOrderPrintData,getPrintDataByWaybillCodes';
|
||||
const _noNeedLog = 'getWavePrintData,unlockWavePlatformPrintDataByGroup,getOrderPrintData,getPrintDataByWaybillCodes';
|
||||
const _noNeedAuth = 'getWavePrintData,getWavePlatformPrintData,unlockWavePlatformPrintDataByGroup,getOrderPrintData,getPrintDataByWaybillCodes';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
@ -120,6 +120,36 @@ class OrderPrintService extends OrderBaseService {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 按运单号数组拉取平台打印中间态数据。
|
||||
*
|
||||
* method 层仅负责参数解构与边界校验,具体业务查询与打印数据组装由 systems 层实现。
|
||||
* 仓库ID统一从当前上下文获取,无需调用方传入。
|
||||
*
|
||||
* @param {Object} data 请求体。
|
||||
* @param {Array<string>} data.waybill_codes 运单号数组。
|
||||
* @return {Promise<Object>} 统一 success 包装的平台打印中间态结果。
|
||||
*/
|
||||
async getPrintDataByWaybillCodes(data = {}) {
|
||||
const requestData = this.isPlainObject(data) ? data : {};
|
||||
const {
|
||||
waybill_codes: waybillCodes,
|
||||
} = requestData;
|
||||
|
||||
if (!Array.isArray(waybillCodes) || waybillCodes.length === 0) {
|
||||
throw new Error('waybill_codes 必填,且必须为非空数组');
|
||||
}
|
||||
|
||||
const result = await this.service.systems.orderPrint.getPrintDataByWaybillCodes({
|
||||
waybillCodes,
|
||||
});
|
||||
|
||||
return this.success('ok', {
|
||||
data: result,
|
||||
code: 200,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 按分组解锁波次平台打印锁。
|
||||
*
|
||||
|
||||
@ -138,7 +138,7 @@ class PrintService extends MainService {
|
||||
return {
|
||||
status: 'sent',
|
||||
send_status: 'sent',
|
||||
print_status: 'printed',
|
||||
print_status: 'unknown',
|
||||
sent_time: sentTime,
|
||||
print_time: sentTime,
|
||||
fail_code: null,
|
||||
@ -170,55 +170,6 @@ class PrintService extends MainService {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范化补打所需的已落库发送数据。
|
||||
* @param {Object|string} recordData 打印记录 data 字段。
|
||||
* @return {{success:boolean,data?:Object,error?:string}} 解析结果。
|
||||
*/
|
||||
normalizeRetrySendPayload(recordData) {
|
||||
let normalizedRecordData = recordData;
|
||||
if (typeof normalizedRecordData === 'string') {
|
||||
try {
|
||||
normalizedRecordData = JSON.parse(normalizedRecordData);
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: '打印记录 data 不是有效 JSON',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (!normalizedRecordData || typeof normalizedRecordData !== 'object' || Array.isArray(normalizedRecordData)) {
|
||||
return {
|
||||
success: false,
|
||||
error: '打印记录 data 结构不合法',
|
||||
};
|
||||
}
|
||||
|
||||
const printer = String(normalizedRecordData.printer || '').trim();
|
||||
const component = String(normalizedRecordData.component || '').trim();
|
||||
const type = String(normalizedRecordData.type || '').trim();
|
||||
const payloadData = normalizedRecordData.data;
|
||||
const orderIds = this.normalizeOrderIds(normalizedRecordData.order_ids);
|
||||
if (!printer || !type || !payloadData || typeof payloadData !== 'object' || Array.isArray(payloadData)) {
|
||||
return {
|
||||
success: false,
|
||||
error: '打印记录 data 缺少 printer/type/data',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
printer,
|
||||
component,
|
||||
type,
|
||||
order_ids: orderIds,
|
||||
data: JSON.parse(JSON.stringify(payloadData)),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范化订单ID数组,过滤非法值并去重。
|
||||
* @param {Array<number|string>} orderIds 原始订单ID数组。
|
||||
@ -421,39 +372,6 @@ class PrintService extends MainService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断记录是否满足失败补打条件。
|
||||
* @param {Object} record 打印记录。
|
||||
* @param {boolean} force 是否强制补打(最小实现默认不放宽规则)。
|
||||
* @return {{canRetry:boolean,reason:string}} 判断结果。
|
||||
*/
|
||||
getRetryEligibility(record = {}, force = false) {
|
||||
const normalizedRecord = record && typeof record === 'object' ? record : {};
|
||||
const status = String(normalizedRecord.status || '').trim();
|
||||
const printStatus = String(normalizedRecord.print_status || '').trim();
|
||||
|
||||
if (status === 'sent' && [ 'unknown', 'printed' ].includes(printStatus)) {
|
||||
return {
|
||||
canRetry: false,
|
||||
reason: `状态为 sent/${printStatus},按规则跳过`,
|
||||
};
|
||||
}
|
||||
|
||||
const canRetry = status === 'failed' || [ 'print_failed', 'timeout' ].includes(printStatus);
|
||||
if (canRetry) {
|
||||
return {
|
||||
canRetry: true,
|
||||
reason: '',
|
||||
};
|
||||
}
|
||||
|
||||
const forceTip = force ? '(force 已开启,当前最小实现仍不放宽状态限制)' : '';
|
||||
return {
|
||||
canRetry: false,
|
||||
reason: `状态不允许补打:status=${status || 'unknown'},print_status=${printStatus || 'unknown'}${forceTip}`,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取打印任务编码冲突重试配置。
|
||||
* @return {{maxRetries:number,baseDelayMs:number,jitterMs:number}} 归一化后的重试配置。
|
||||
@ -1082,6 +1000,7 @@ class PrintService extends MainService {
|
||||
timestamp,
|
||||
count,
|
||||
printId: printRecord.id,
|
||||
...(customizeOrderIds.length > 0 ? { order_ids: customizeOrderIds } : {}),
|
||||
};
|
||||
const sendStartAt = Date.now();
|
||||
const res = await this.service.systems.print.index.sendToComputer({ warehouse: warehouseId, computerId, data: printData });
|
||||
@ -1142,175 +1061,6 @@ class PrintService extends MainService {
|
||||
return this.fail(res.error, { code: 504, printId: printRecord.id });
|
||||
}
|
||||
|
||||
/**
|
||||
* 失败项补打:仅重试失败记录,原记录保持不变。
|
||||
* @param {Object} data 补打参数。
|
||||
* @param {Array<number|string>} data.print_ids 需要补打的打印记录 ID 列表。
|
||||
* @param {boolean} [data.force=false] 是否强制补打(最小实现默认不放宽状态规则)。
|
||||
* @param {number|string} [data.warehouse_id] 显式指定仓库 ID(用于定时任务等无登录上下文场景)。
|
||||
* @return {Promise<Object>} 统一返回结构。
|
||||
*/
|
||||
async retryFailed(data = {}) {
|
||||
const { ctx } = this;
|
||||
const requestData = data && typeof data === 'object' ? data : {};
|
||||
const {
|
||||
print_ids: rawPrintIds,
|
||||
force = false,
|
||||
warehouse_id: rawWarehouseId,
|
||||
} = requestData;
|
||||
|
||||
const normalizedWarehouseId = Number(rawWarehouseId);
|
||||
const userWarehouseId = Number(ctx.user && ctx.user.store_id);
|
||||
const warehouseId = Number.isInteger(normalizedWarehouseId) && normalizedWarehouseId > 0
|
||||
? normalizedWarehouseId
|
||||
: (Number.isInteger(userWarehouseId) && userWarehouseId > 0 ? userWarehouseId : 0);
|
||||
|
||||
if (!warehouseId) {
|
||||
return this.fail('warehouse_id 参数缺失,且当前上下文无可用仓库信息', { code: 400 });
|
||||
}
|
||||
|
||||
if (!Array.isArray(rawPrintIds) || rawPrintIds.length === 0) {
|
||||
return this.fail('print_ids 参数不能为空数组', { code: 400 });
|
||||
}
|
||||
|
||||
const printIds = Array.from(new Set(rawPrintIds
|
||||
.map(item => Number(item))
|
||||
.filter(item => Number.isInteger(item) && item > 0)));
|
||||
if (printIds.length === 0) {
|
||||
return this.fail('print_ids 参数不合法,必须包含正整数 ID', { code: 400 });
|
||||
}
|
||||
|
||||
const sourceRecords = await ctx.model.PrintRecord.findAll({
|
||||
where: {
|
||||
id: printIds,
|
||||
warehouse_id: warehouseId,
|
||||
},
|
||||
raw: true,
|
||||
});
|
||||
const sourceRecordMap = new Map(sourceRecords.map(item => [ Number(item.id), item ]));
|
||||
|
||||
const retried = [];
|
||||
const skipped = [];
|
||||
let successCount = 0;
|
||||
let failedCount = 0;
|
||||
|
||||
for (const printId of printIds) {
|
||||
const sourceRecord = sourceRecordMap.get(printId);
|
||||
if (!sourceRecord) {
|
||||
skipped.push({
|
||||
print_id: printId,
|
||||
reason: '记录不存在或不属于当前仓库',
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
const eligibility = this.getRetryEligibility(sourceRecord, Boolean(force));
|
||||
if (!eligibility.canRetry) {
|
||||
skipped.push({
|
||||
print_id: printId,
|
||||
reason: eligibility.reason,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
const payloadResult = this.normalizeRetrySendPayload(sourceRecord.data);
|
||||
if (!payloadResult.success) {
|
||||
skipped.push({
|
||||
print_id: printId,
|
||||
reason: payloadResult.error,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
const sendPayload = payloadResult.data;
|
||||
const taskCode = await this.reserveUniquePrintTaskCode();
|
||||
if (sendPayload.data.task && typeof sendPayload.data.task === 'object' && !Array.isArray(sendPayload.data.task)) {
|
||||
sendPayload.data.task.taskID = taskCode;
|
||||
}
|
||||
|
||||
const newPrintRecord = await ctx.model.PrintRecord.create(this.buildPendingPrintRecordPayload({
|
||||
warehouse_id: sourceRecord.warehouse_id,
|
||||
computer_id: sourceRecord.computer_id,
|
||||
printer: sourceRecord.printer,
|
||||
type: sourceRecord.type,
|
||||
request_code: sourceRecord.request_code,
|
||||
wave_id: sourceRecord.wave_id,
|
||||
wave_no: sourceRecord.wave_no,
|
||||
platform_code: sourceRecord.platform_code,
|
||||
platform_name: sourceRecord.platform_name,
|
||||
sys_logistics_code: sourceRecord.sys_logistics_code,
|
||||
sys_logistics_name: sourceRecord.sys_logistics_name,
|
||||
retry_of_print_id: sourceRecord.id,
|
||||
data: sendPayload,
|
||||
}));
|
||||
|
||||
try {
|
||||
const sendResult = await this.service.systems.print.index.sendToComputer({
|
||||
warehouse: warehouseId,
|
||||
computerId: sourceRecord.computer_id,
|
||||
data: {
|
||||
...sendPayload,
|
||||
printId: newPrintRecord.id,
|
||||
},
|
||||
});
|
||||
if (sendResult.status !== 'success') {
|
||||
const failedMessage = sendResult.error || '打印服务返回失败';
|
||||
await newPrintRecord.update(this.buildSendFailedPrintRecordUpdatePayload({
|
||||
errorMessage: failedMessage,
|
||||
failCode: 'SEND_FAILED',
|
||||
}));
|
||||
retried.push({
|
||||
source_print_id: sourceRecord.id,
|
||||
new_print_id: newPrintRecord.id,
|
||||
task_code: taskCode,
|
||||
status: 'failed',
|
||||
});
|
||||
failedCount += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
const providerTaskId = String(
|
||||
sendResult && (sendResult.taskId || sendResult.task_id || sendResult.providerTaskId || sendResult.id)
|
||||
? (sendResult.taskId || sendResult.task_id || sendResult.providerTaskId || sendResult.id)
|
||||
: ''
|
||||
).trim();
|
||||
await this.bindTaskCodeToPrintRecordWithRetry({
|
||||
printRecordId: newPrintRecord.id,
|
||||
taskCode,
|
||||
provider: providerTaskId,
|
||||
});
|
||||
retried.push({
|
||||
source_print_id: sourceRecord.id,
|
||||
new_print_id: newPrintRecord.id,
|
||||
task_code: taskCode,
|
||||
status: 'sent',
|
||||
});
|
||||
successCount += 1;
|
||||
} catch (error) {
|
||||
await newPrintRecord.update(this.buildSendFailedPrintRecordUpdatePayload({
|
||||
errorMessage: error && error.message ? error.message : `${error}`,
|
||||
failCode: 'SEND_FAILED',
|
||||
}));
|
||||
retried.push({
|
||||
source_print_id: sourceRecord.id,
|
||||
new_print_id: newPrintRecord.id,
|
||||
task_code: taskCode,
|
||||
status: 'failed',
|
||||
});
|
||||
failedCount += 1;
|
||||
}
|
||||
}
|
||||
|
||||
return this.success('失败项补打处理完成', {
|
||||
code: 200,
|
||||
success_count: successCount,
|
||||
failed_count: failedCount,
|
||||
skipped_count: skipped.length,
|
||||
retried,
|
||||
skipped,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验快递打印请求的必要参数。
|
||||
* @param {Object} payload 校验参数。
|
||||
@ -1797,6 +1547,142 @@ class PrintService extends MainService {
|
||||
return this.notifyLock(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 当 batchOrderIds 为空时,尝试通过 wave_id 从数据库反查订单 ID 列表作为兜底。
|
||||
*
|
||||
* 适用于前端未回传 order_ids 的场景(如团购打印),确保打印成功后仍能标记订单为已打印。
|
||||
*
|
||||
* @param {Object} payload 查询参数。
|
||||
* @param {number|string} payload.warehouseId 仓库ID。
|
||||
* @param {number|null} payload.waveId 波次ID。
|
||||
* @return {Promise<Array<number>>} 订单ID列表;查询失败或参数无效时返回空数组。
|
||||
*/
|
||||
async resolveBatchOrderIdsByWaveFallback(payload = {}) {
|
||||
const normalizedPayload = payload && typeof payload === 'object' ? payload : {};
|
||||
const warehouseId = Number(normalizedPayload.warehouseId || 0);
|
||||
const waveId = Number(normalizedPayload.waveId || 0);
|
||||
|
||||
if (!Number.isInteger(warehouseId) || warehouseId <= 0 || !Number.isInteger(waveId) || waveId <= 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory;
|
||||
if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') {
|
||||
this.ctx.logger.warn('[print.markWavePrintStatus] OrderDeliveryFactory 不可用');
|
||||
return [];
|
||||
}
|
||||
|
||||
const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(warehouseId);
|
||||
if (!orderDeliveryModel || typeof orderDeliveryModel.findAll !== 'function') {
|
||||
this.ctx.logger.warn('[print.markWavePrintStatus] orderDeliveryModel 不可用');
|
||||
return [];
|
||||
}
|
||||
|
||||
const rows = await orderDeliveryModel.findAll({
|
||||
attributes: [ 'id' ],
|
||||
where: {
|
||||
wave_id: waveId,
|
||||
warehouse_id: warehouseId,
|
||||
status: { [this.app.Sequelize.Op.ne]: 'cancel' },
|
||||
},
|
||||
raw: true,
|
||||
});
|
||||
|
||||
const orderIds = (Array.isArray(rows) ? rows : [])
|
||||
.map(row => Number(row && row.id))
|
||||
.filter(id => Number.isInteger(id) && id > 0);
|
||||
|
||||
if (orderIds.length > 0) {
|
||||
this.ctx.logger.info('[print.markWavePrintStatus] wave_id=%d 查询到 %d 个订单', waveId, orderIds.length);
|
||||
}
|
||||
|
||||
return orderIds;
|
||||
} catch (error) {
|
||||
this.ctx.logger.warn('[print.markWavePrintStatus] 查询失败 wave_id=%d reason=%s',
|
||||
waveId, error && error.message ? error.message : `${error}`);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 标记/取消标记整个波次的订单打印状态。
|
||||
*
|
||||
* 仅操作当前仓库下、状态非取消的订单。
|
||||
* 仓库隔离:从 ctx.user.store_id 获取仓库 ID。
|
||||
*
|
||||
* @param {Object} data 入参。
|
||||
* @param {number|string} data.wave_id 波次ID(必填)。
|
||||
* @param {string} [data.status='printed'] 目标状态:'printed' 标记已打印,'unprinted' 取消已打印标记。
|
||||
* @return {Promise<Object>} 统一返回结构。
|
||||
*/
|
||||
async markWavePrintStatus(data = {}) {
|
||||
const { ctx } = this;
|
||||
const requestData = data && typeof data === 'object' ? data : {};
|
||||
const waveId = Number(requestData.wave_id || 0);
|
||||
const targetStatus = String(requestData.status || 'printed').trim().toLowerCase();
|
||||
|
||||
if (!Number.isInteger(waveId) || waveId <= 0) {
|
||||
return this.fail('wave_id 参数必填,且必须为正整数', { code: 400 });
|
||||
}
|
||||
|
||||
if (![ 'printed', 'unprinted' ].includes(targetStatus)) {
|
||||
return this.fail('status 参数不合法,仅支持 printed / unprinted', { code: 400 });
|
||||
}
|
||||
|
||||
const warehouseId = Number(ctx.user && ctx.user.store_id || 0);
|
||||
if (!Number.isInteger(warehouseId) || warehouseId <= 0) {
|
||||
return this.fail('无法获取当前仓库ID,请确认已登录', { code: 400 });
|
||||
}
|
||||
|
||||
const orderIds = await this.resolveBatchOrderIdsByWaveFallback({ warehouseId, waveId });
|
||||
if (orderIds.length === 0) {
|
||||
return this.fail(`波次 ${waveId} 在当前仓库下没有可操作的订单`, { code: 404 });
|
||||
}
|
||||
|
||||
const printStatus = targetStatus === 'printed' ? 'fin' : 'none';
|
||||
try {
|
||||
const orderDeliveryFactory = ctx.model && ctx.model.OrderDeliveryFactory;
|
||||
if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') {
|
||||
return this.fail('OrderDeliveryFactory 不可用', { code: 500 });
|
||||
}
|
||||
|
||||
const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(warehouseId);
|
||||
if (!orderDeliveryModel || typeof orderDeliveryModel.update !== 'function') {
|
||||
return this.fail('OrderDeliveryModel 不可用', { code: 500 });
|
||||
}
|
||||
|
||||
const updateResult = await orderDeliveryModel.update({
|
||||
print_status: printStatus,
|
||||
updated_at: new Date(),
|
||||
}, {
|
||||
where: {
|
||||
id: { [this.app.Sequelize.Op.in]: orderIds },
|
||||
warehouse_id: warehouseId,
|
||||
status: { [this.app.Sequelize.Op.ne]: 'cancel' },
|
||||
},
|
||||
});
|
||||
|
||||
const affectedRows = Number(Array.isArray(updateResult) ? updateResult[0] : updateResult) || 0;
|
||||
this.ctx.logger.info('[print.markWavePrintStatus] 波次打印状态标记完成 wave_id=%d target=%s affected=%d/%d',
|
||||
waveId, targetStatus, affectedRows, orderIds.length);
|
||||
|
||||
return this.success('ok', {
|
||||
code: 0,
|
||||
wave_id: waveId,
|
||||
status: targetStatus,
|
||||
print_status: printStatus,
|
||||
total_orders: orderIds.length,
|
||||
affected_orders: affectedRows,
|
||||
order_ids: orderIds,
|
||||
});
|
||||
} catch (error) {
|
||||
this.ctx.logger.error('[print.markWavePrintStatus] 更新失败 wave_id=%d reason=%s',
|
||||
waveId, error && error.message ? error.message : `${error}`);
|
||||
return this.fail(`波次打印状态更新失败:${error && error.message ? error.message : '未知错误'}`, { code: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 在打印发送成功后批量锁定订单。
|
||||
*
|
||||
@ -2129,6 +2015,16 @@ class PrintService extends MainService {
|
||||
for (let batchIndex = 0; batchIndex < orderBatches.length; batchIndex++) {
|
||||
const batchOrders = orderBatches[batchIndex];
|
||||
const batchOrderIds = this.collectOrderIdsFromPlatformGroup(platformGroup, batchOrders);
|
||||
// 兜底:前端未回传 order_ids 时,通过 wave_id 反查当前波次全部订单ID
|
||||
if (batchOrderIds.length === 0 && waveId) {
|
||||
const fallbackIds = await this.resolveBatchOrderIdsByWaveFallback({
|
||||
warehouseId: normalizedPayload.warehouseId,
|
||||
waveId,
|
||||
});
|
||||
if (fallbackIds.length > 0) {
|
||||
batchOrderIds.push(...fallbackIds);
|
||||
}
|
||||
}
|
||||
const currentPrinterName = printerNameResult.data;
|
||||
const batchSummary = {
|
||||
...groupSummary,
|
||||
@ -2487,7 +2383,7 @@ class PrintService extends MainService {
|
||||
result: 'idempotent',
|
||||
print_task_code: normalizedPrintTaskCode,
|
||||
print_record_id: printRecordId,
|
||||
print_status: 'printed',
|
||||
print_status: 'unknown',
|
||||
});
|
||||
}
|
||||
|
||||
@ -2497,7 +2393,7 @@ class PrintService extends MainService {
|
||||
result: 'ignored',
|
||||
print_task_code: normalizedPrintTaskCode,
|
||||
print_record_id: printRecordId,
|
||||
print_status: 'printed',
|
||||
print_status: 'unknown',
|
||||
});
|
||||
}
|
||||
|
||||
@ -2507,7 +2403,7 @@ class PrintService extends MainService {
|
||||
const updatePayload = normalizedResult === 'success'
|
||||
? {
|
||||
status: 'sent',
|
||||
print_status: 'printed',
|
||||
print_status: 'unknown',
|
||||
error_message: null,
|
||||
fail_code: null,
|
||||
print_time: normalizedPrintTime,
|
||||
@ -2550,7 +2446,7 @@ class PrintService extends MainService {
|
||||
result: 'updated',
|
||||
print_task_code: normalizedPrintTaskCode,
|
||||
print_record_id: printRecordId,
|
||||
print_status: updatePayload.print_status,
|
||||
print_status: 'unknown',
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@ -890,6 +890,344 @@ class OrderPrintSystemService extends OrderBaseService {
|
||||
* @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 },
|
||||
waveGroups: [],
|
||||
wave_ids: [],
|
||||
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 },
|
||||
waveGroups: [],
|
||||
wave_ids: [],
|
||||
ext: {
|
||||
missing_waybill_codes: missingWaybillCodes,
|
||||
filtered_waybill_codes: invalidWaybillCodes,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// 3. 过滤 post_status !== 'fin' 的订单
|
||||
const validOrderIdSet = new Set(
|
||||
orderRows
|
||||
.filter(row => String(row.post_status || '').trim() === 'fin')
|
||||
.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: '关联订单快递未完全分配',
|
||||
}));
|
||||
|
||||
if (finalWaybillRows.length === 0) {
|
||||
return {
|
||||
summary: { total_waves: 0, total_orders: 0, total_platforms: 0 },
|
||||
waveGroups: [],
|
||||
wave_ids: [],
|
||||
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,
|
||||
},
|
||||
waveGroups,
|
||||
wave_ids: validOrderWaveIds,
|
||||
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 : [];
|
||||
@ -1527,6 +1865,7 @@ class OrderPrintSystemService extends OrderBaseService {
|
||||
* 返回 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。
|
||||
@ -2648,6 +2987,7 @@ ${waveFilterSql}
|
||||
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 = '';
|
||||
@ -2714,9 +3054,17 @@ ${waveFilterSql}
|
||||
taskId: requestId,
|
||||
documentId,
|
||||
packageMaterialName: suggestedPackageMaterialName,
|
||||
extraCustomLines,
|
||||
},
|
||||
});
|
||||
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(),
|
||||
|
||||
@ -1,255 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const assert = require('node:assert/strict');
|
||||
const schedule = require('../../../app/schedule/print_retry_compensation');
|
||||
|
||||
describe('test/app/schedule/print_retry_compensation.test.js', () => {
|
||||
it('should scan retryable records and invoke retryFailed grouped by warehouse', async () => {
|
||||
assert.equal(schedule.schedule.interval, '30s');
|
||||
assert.equal(schedule.schedule.type, 'worker');
|
||||
assert.equal(schedule.schedule.immediate, false);
|
||||
|
||||
const Op = {
|
||||
and: Symbol('and'),
|
||||
or: Symbol('or'),
|
||||
in: Symbol('in'),
|
||||
lte: Symbol('lte'),
|
||||
lt: Symbol('lt'),
|
||||
};
|
||||
|
||||
const retryCalls = [];
|
||||
const ctx = {
|
||||
app: {
|
||||
_printRetryCompensationRunning: false,
|
||||
_printRetryCompensationLastRunAt: 0,
|
||||
config: {
|
||||
printRetryCompensation: {
|
||||
enable: true,
|
||||
intervalMs: 0,
|
||||
batchSize: 50,
|
||||
force: false,
|
||||
},
|
||||
},
|
||||
Sequelize: {
|
||||
Op,
|
||||
col(fieldName) {
|
||||
return `col:${fieldName}`;
|
||||
},
|
||||
},
|
||||
},
|
||||
logger: {
|
||||
info() {},
|
||||
warn() {},
|
||||
error() {},
|
||||
},
|
||||
model: {
|
||||
PrintRecord: {
|
||||
async findAll(options) {
|
||||
assert.equal(options.limit, 50);
|
||||
assert.equal(options.raw, true);
|
||||
return [
|
||||
{ id: 101, warehouse_id: 1 },
|
||||
{ id: 102, warehouse_id: 1 },
|
||||
{ id: 201, warehouse_id: 2 },
|
||||
];
|
||||
},
|
||||
},
|
||||
},
|
||||
service: {
|
||||
systemMethods: {
|
||||
print: {
|
||||
async retryFailed(data) {
|
||||
retryCalls.push(data);
|
||||
return {
|
||||
flag: 'success',
|
||||
success_count: data.print_ids.length,
|
||||
failed_count: 0,
|
||||
skipped_count: 0,
|
||||
};
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
await schedule.task(ctx);
|
||||
assert.equal(retryCalls.length, 2);
|
||||
|
||||
const firstCall = retryCalls[0];
|
||||
const secondCall = retryCalls[1];
|
||||
assert.deepEqual(firstCall, {
|
||||
print_ids: [ 101, 102 ],
|
||||
warehouse_id: 1,
|
||||
force: false,
|
||||
});
|
||||
assert.deepEqual(secondCall, {
|
||||
print_ids: [ 201 ],
|
||||
warehouse_id: 2,
|
||||
force: false,
|
||||
});
|
||||
assert.equal(ctx.app._printRetryCompensationRunning, false);
|
||||
});
|
||||
|
||||
it('should skip when disabled or already running', async () => {
|
||||
let findAllCount = 0;
|
||||
const ctx = {
|
||||
app: {
|
||||
_printRetryCompensationRunning: false,
|
||||
_printRetryCompensationLastRunAt: 0,
|
||||
config: {
|
||||
printRetryCompensation: {
|
||||
enable: false,
|
||||
intervalMs: 60000,
|
||||
batchSize: 10,
|
||||
},
|
||||
},
|
||||
Sequelize: {
|
||||
Op: {},
|
||||
col(fieldName) {
|
||||
return `col:${fieldName}`;
|
||||
},
|
||||
},
|
||||
},
|
||||
logger: {
|
||||
info() {},
|
||||
warn() {},
|
||||
error() {},
|
||||
},
|
||||
model: {
|
||||
PrintRecord: {
|
||||
async findAll() {
|
||||
findAllCount += 1;
|
||||
return [];
|
||||
},
|
||||
},
|
||||
},
|
||||
service: {
|
||||
systemMethods: {
|
||||
print: {
|
||||
async retryFailed() {
|
||||
throw new Error('should not reach');
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
await schedule.task(ctx);
|
||||
assert.equal(findAllCount, 0);
|
||||
|
||||
ctx.app.config.printRetryCompensation.enable = true;
|
||||
ctx.app._printRetryCompensationRunning = true;
|
||||
await schedule.task(ctx);
|
||||
assert.equal(findAllCount, 0);
|
||||
});
|
||||
|
||||
it('should include retry_count < max_retry_count in where clause', async () => {
|
||||
const Op = {
|
||||
and: Symbol('and'),
|
||||
or: Symbol('or'),
|
||||
in: Symbol('in'),
|
||||
lte: Symbol('lte'),
|
||||
lt: Symbol('lt'),
|
||||
};
|
||||
let whereClause;
|
||||
const ctx = {
|
||||
app: {
|
||||
_printRetryCompensationRunning: false,
|
||||
_printRetryCompensationLastRunAt: 0,
|
||||
config: { printRetryCompensation: { enable: true, intervalMs: 0, batchSize: 50 } },
|
||||
Sequelize: { Op, col: fieldName => `col:${fieldName}` },
|
||||
},
|
||||
logger: { info() {}, warn() {}, error() {} },
|
||||
model: {
|
||||
PrintRecord: {
|
||||
async findAll(options) {
|
||||
whereClause = options.where;
|
||||
return [];
|
||||
},
|
||||
},
|
||||
},
|
||||
service: { systemMethods: { print: { async retryFailed() {} } } },
|
||||
};
|
||||
|
||||
await schedule.task(ctx);
|
||||
const andConditions = whereClause[Op.and];
|
||||
assert(Array.isArray(andConditions), 'where[Op.and] should be an array');
|
||||
const retryCountCondition = andConditions.find(condition => condition && condition.retry_count);
|
||||
assert(retryCountCondition, 'retry_count condition should exist in where[Op.and]');
|
||||
assert.deepStrictEqual(retryCountCondition.retry_count, { [Op.lt]: 'col:max_retry_count' });
|
||||
});
|
||||
|
||||
it('should include next_retry_at <= now in where clause', async () => {
|
||||
const Op = {
|
||||
and: Symbol('and'),
|
||||
or: Symbol('or'),
|
||||
in: Symbol('in'),
|
||||
lte: Symbol('lte'),
|
||||
lt: Symbol('lt'),
|
||||
};
|
||||
let whereClause;
|
||||
const ctx = {
|
||||
app: {
|
||||
_printRetryCompensationRunning: false,
|
||||
_printRetryCompensationLastRunAt: 0,
|
||||
config: { printRetryCompensation: { enable: true, intervalMs: 0, batchSize: 50 } },
|
||||
Sequelize: { Op, col: () => {} },
|
||||
},
|
||||
logger: { info() {}, warn() {}, error() {} },
|
||||
model: {
|
||||
PrintRecord: {
|
||||
async findAll(options) {
|
||||
whereClause = options.where;
|
||||
return [];
|
||||
},
|
||||
},
|
||||
},
|
||||
service: { systemMethods: { print: { async retryFailed() {} } } },
|
||||
};
|
||||
|
||||
await schedule.task(ctx);
|
||||
const andConditions = whereClause[Op.and];
|
||||
assert(Array.isArray(andConditions), 'where[Op.and] should be an array');
|
||||
const nextRetryAtCondition = andConditions.find(condition => condition && condition.next_retry_at);
|
||||
assert(nextRetryAtCondition, 'next_retry_at condition should exist in where[Op.and]');
|
||||
assert(nextRetryAtCondition.next_retry_at[Op.lte], 'should use lte operator');
|
||||
assert(nextRetryAtCondition.next_retry_at[Op.lte] instanceof Date, 'should compare with a Date object');
|
||||
});
|
||||
|
||||
it('should skip invalid records and not trigger retryFailed', async () => {
|
||||
let retryFailedCalled = false;
|
||||
const ctx = {
|
||||
app: {
|
||||
_printRetryCompensationRunning: false,
|
||||
_printRetryCompensationLastRunAt: 0,
|
||||
config: { printRetryCompensation: { enable: true, intervalMs: 0, batchSize: 50 } },
|
||||
Sequelize: { Op: {}, col: () => {} },
|
||||
},
|
||||
logger: { info() {}, warn() {}, error() {} },
|
||||
model: {
|
||||
PrintRecord: {
|
||||
async findAll() {
|
||||
return [
|
||||
{ id: 0, warehouse_id: 1 },
|
||||
{ id: 1, warehouse_id: 0 },
|
||||
{ id: -1, warehouse_id: 1 },
|
||||
{ id: 1, warehouse_id: -1 },
|
||||
];
|
||||
},
|
||||
},
|
||||
},
|
||||
service: {
|
||||
systemMethods: {
|
||||
print: {
|
||||
async retryFailed() {
|
||||
retryFailedCalled = true;
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
await schedule.task(ctx);
|
||||
assert.equal(retryFailedCalled, false, 'retryFailed should not be called for invalid records');
|
||||
});
|
||||
});
|
||||
@ -1187,203 +1187,6 @@ describe('test/app/service/systemMethods/print.send.test.js', () => {
|
||||
assert.equal(calls.sendToComputerPayloads.length, 0);
|
||||
});
|
||||
|
||||
it('retryFailed 应补打 failed 记录并创建新记录', async () => {
|
||||
const sourceRecordId = 12001;
|
||||
const { ctx, calls, state } = createContext({
|
||||
initialPrintRecords: [
|
||||
{
|
||||
id: sourceRecordId,
|
||||
warehouse_id: 100000,
|
||||
computer_id: 'PC-STATION-001',
|
||||
printer: 'PRN-STO',
|
||||
type: 'express',
|
||||
status: 'failed',
|
||||
send_status: 'send_failed',
|
||||
print_status: 'unknown',
|
||||
data: {
|
||||
printer: 'PRN-STO',
|
||||
component: '菜鸟',
|
||||
type: 'express',
|
||||
data: {
|
||||
task: {
|
||||
taskID: 'OLD_TASK_ID',
|
||||
documents: [],
|
||||
},
|
||||
},
|
||||
},
|
||||
request_code: 'REQ-RETRY-001',
|
||||
wave_id: 11,
|
||||
wave_no: 'WAVE-11',
|
||||
platform_code: 'cainiao',
|
||||
platform_name: '菜鸟平台',
|
||||
sys_logistics_code: 'STO',
|
||||
sys_logistics_name: '申通',
|
||||
},
|
||||
],
|
||||
sendToComputer: async payload => {
|
||||
calls.sendToComputerPayloads.push(payload);
|
||||
return { status: 'success' };
|
||||
},
|
||||
});
|
||||
const service = new PrintService(ctx);
|
||||
|
||||
const result = await service.retryFailed({
|
||||
print_ids: [ sourceRecordId ],
|
||||
});
|
||||
|
||||
assert.equal(result.flag, 'success');
|
||||
assert.equal(result.success_count, 1);
|
||||
assert.equal(result.failed_count, 0);
|
||||
assert.equal(result.skipped_count, 0);
|
||||
assert.equal(result.retried.length, 1);
|
||||
assert.equal(result.retried[0].source_print_id, sourceRecordId);
|
||||
assert.equal(result.retried[0].status, 'sent');
|
||||
assert.equal(calls.printRecordCreatePayloads.length, 1);
|
||||
assert.equal(calls.sendToComputerPayloads.length, 1);
|
||||
assert.equal(calls.printRecordCreatePayloads[0].retry_of_print_id, sourceRecordId);
|
||||
|
||||
const newRecordId = result.retried[0].new_print_id;
|
||||
const newRecord = state.printRecordsById[newRecordId];
|
||||
assert.ok(newRecord);
|
||||
assert.equal(newRecord.retry_of_print_id, sourceRecordId);
|
||||
assert.equal(newRecord.status, 'sent');
|
||||
assert.equal(newRecord.send_status, 'sent');
|
||||
assert.equal(newRecord.print_status, 'printed');
|
||||
assert.notEqual(newRecord.data.data.task.taskID, 'OLD_TASK_ID');
|
||||
assert.equal(newRecord.data.data.task.taskID, result.retried[0].task_code);
|
||||
assert.equal(state.printRecordsById[sourceRecordId].status, 'failed');
|
||||
});
|
||||
|
||||
it('retryFailed 应跳过 sent/printed 记录', async () => {
|
||||
const sourceRecordId = 12002;
|
||||
const { ctx, calls } = createContext({
|
||||
initialPrintRecords: [
|
||||
{
|
||||
id: sourceRecordId,
|
||||
warehouse_id: 100000,
|
||||
computer_id: 'PC-STATION-001',
|
||||
printer: 'PRN-STO',
|
||||
type: 'express',
|
||||
status: 'sent',
|
||||
send_status: 'sent',
|
||||
print_status: 'printed',
|
||||
data: {
|
||||
printer: 'PRN-STO',
|
||||
component: '菜鸟',
|
||||
type: 'express',
|
||||
data: {
|
||||
task: {
|
||||
taskID: 'TASK-SENT-001',
|
||||
documents: [],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
const service = new PrintService(ctx);
|
||||
|
||||
const result = await service.retryFailed({
|
||||
print_ids: [ sourceRecordId ],
|
||||
});
|
||||
|
||||
assert.equal(result.flag, 'success');
|
||||
assert.equal(result.success_count, 0);
|
||||
assert.equal(result.failed_count, 0);
|
||||
assert.equal(result.skipped_count, 1);
|
||||
assert.equal(result.skipped[0].print_id, sourceRecordId);
|
||||
assert.match(result.skipped[0].reason, /跳过|不允许补打/);
|
||||
assert.equal(calls.printRecordCreatePayloads.length, 0);
|
||||
assert.equal(calls.sendToComputerPayloads.length, 0);
|
||||
});
|
||||
|
||||
it('retryFailed 部分成功时应返回正确统计', async () => {
|
||||
const sourceSuccessId = 12003;
|
||||
const sourceFailId = 12004;
|
||||
const sourceSkipId = 12005;
|
||||
const { ctx, calls, state } = createContext({
|
||||
initialPrintRecords: [
|
||||
{
|
||||
id: sourceSuccessId,
|
||||
warehouse_id: 100000,
|
||||
computer_id: 'PC-STATION-001',
|
||||
printer: 'PRN-STO',
|
||||
type: 'express',
|
||||
status: 'failed',
|
||||
send_status: 'send_failed',
|
||||
print_status: 'unknown',
|
||||
data: {
|
||||
printer: 'PRN-STO',
|
||||
component: '菜鸟',
|
||||
type: 'express',
|
||||
data: { task: { taskID: 'TASK-OLD-SUCCESS', documents: [] } },
|
||||
},
|
||||
},
|
||||
{
|
||||
id: sourceFailId,
|
||||
warehouse_id: 100000,
|
||||
computer_id: 'PC-STATION-001',
|
||||
printer: 'PRN-YTO',
|
||||
type: 'express',
|
||||
status: 'failed',
|
||||
send_status: 'send_failed',
|
||||
print_status: 'unknown',
|
||||
data: {
|
||||
printer: 'PRN-YTO',
|
||||
component: '拼多多',
|
||||
type: 'express',
|
||||
data: { task: { taskID: 'TASK-OLD-FAIL', documents: [] } },
|
||||
},
|
||||
},
|
||||
{
|
||||
id: sourceSkipId,
|
||||
warehouse_id: 100000,
|
||||
computer_id: 'PC-STATION-001',
|
||||
printer: 'PRN-STO',
|
||||
type: 'express',
|
||||
status: 'sent',
|
||||
send_status: 'sent',
|
||||
print_status: 'unknown',
|
||||
data: {
|
||||
printer: 'PRN-STO',
|
||||
component: '菜鸟',
|
||||
type: 'express',
|
||||
data: { task: { taskID: 'TASK-SKIP', documents: [] } },
|
||||
},
|
||||
},
|
||||
],
|
||||
sendToComputer: async payload => {
|
||||
calls.sendToComputerPayloads.push(payload);
|
||||
if (calls.sendToComputerPayloads.length === 2) {
|
||||
return {
|
||||
status: 'failure',
|
||||
error: '发送失败-模拟',
|
||||
};
|
||||
}
|
||||
return { status: 'success' };
|
||||
},
|
||||
});
|
||||
const service = new PrintService(ctx);
|
||||
|
||||
const result = await service.retryFailed({
|
||||
print_ids: [ sourceSuccessId, sourceFailId, sourceSkipId ],
|
||||
});
|
||||
|
||||
assert.equal(result.flag, 'success');
|
||||
assert.equal(result.success_count, 1);
|
||||
assert.equal(result.failed_count, 1);
|
||||
assert.equal(result.skipped_count, 1);
|
||||
assert.equal(result.retried.length, 2);
|
||||
assert.equal(calls.printRecordCreatePayloads.length, 2);
|
||||
assert.equal(calls.sendToComputerPayloads.length, 2);
|
||||
assert.equal(state.printRecordsById[sourceSuccessId].status, 'failed');
|
||||
assert.equal(state.printRecordsById[sourceFailId].status, 'failed');
|
||||
assert.equal(state.printRecordsById[sourceSkipId].status, 'sent');
|
||||
const failedRetryItem = result.retried.find(item => item.source_print_id === sourceFailId);
|
||||
assert.ok(failedRetryItem);
|
||||
assert.equal(failedRetryItem.status, 'failed');
|
||||
});
|
||||
|
||||
it('handlePrintCallback success 回调应更新为 printed', async () => {
|
||||
const { ctx, state, calls } = createContext();
|
||||
const service = new PrintService(ctx);
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user