3204 lines
126 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
const { randomBytes } = require('node:crypto');
// 打印相关 Service
const MainService = require('../main');
const {
ExpressPrintPayloadBuilder,
RequestScopedPrintIdGenerator,
} = require('../../lib/express_print_payload_builder');
const {
INTERCEPT_STATUS_NONE,
isInterceptedOrderStatus,
} = require('../../lib/intercept_guard');
/**
* 打印 Service
* 参考 indexService 初始化方式,后续可扩展具体业务函数
*/
class PrintService extends MainService {
constructor(ctx) {
super(ctx);
// 初始化免登录、免权限、免日志、免认证等配置
const _noNeedLogin = '';
const _noNeedRight = '*';
const _noNeedLog = 'notifyLock,notify_lock';
const _noNeedAuth = '*';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
this.defaultComponents = [
{ name: '抖音', port: '13888' },
{ name: '拼多多', port: '5000' },
{ name: '快手', port: '16888/ks/printer' },
{ name: '京东', port: '9113' },
{ name: '菜鸟', port: '13528' },
{ name: '视频号', port: '12705' },
{ name: '小红书', port: '10818' },
{ name: 'LODOP', port: '8000' },
];
}
/**
* 构建 print.send 入参摘要,避免打印超大对象。
* @param {Object} payload 原始入参。
* @return {Object} 安全摘要信息。
*/
buildPrintSendInputSummary(payload = {}) {
const normalizedPayload = payload && typeof payload === 'object' ? payload : {};
const data = normalizedPayload.data && typeof normalizedPayload.data === 'object' ? normalizedPayload.data : {};
const waveGroups = Array.isArray(data.waveGroups) ? data.waveGroups : [];
const firstWavePlatforms = Array.isArray(waveGroups[0] && waveGroups[0].platforms) ? waveGroups[0].platforms : [];
const firstPlatformOrders = Array.isArray(firstWavePlatforms[0] && firstWavePlatforms[0].orders)
? firstWavePlatforms[0].orders
: [];
return {
type: normalizedPayload.type || '',
printer: normalizedPayload.printer || '',
computerId: normalizedPayload.computerId || '',
printStationId: normalizedPayload.printStationId || '',
hasTemplate: Boolean(normalizedPayload.template),
requestCode: normalizedPayload.requestCode ? String(normalizedPayload.requestCode) : '',
waveGroupsCount: waveGroups.length,
firstWavePlatformsCount: firstWavePlatforms.length,
firstGroupOrdersCount: firstPlatformOrders.length,
dataKeys: Object.keys(data).slice(0, 20),
};
}
/**
* 统计快递 payload 摘要,避免输出完整文档对象。
* @param {Object} payload 快递发送 payload。
* @return {{documentCount:number}} 文档数量摘要。
*/
summarizeExpressPayload(payload = {}) {
const normalizedPayload = payload && typeof payload === 'object' ? payload : {};
let documentCount = 0;
if (normalizedPayload.task && Array.isArray(normalizedPayload.task.documents)) {
documentCount = normalizedPayload.task.documents.length;
} else if (Array.isArray(normalizedPayload.documents)) {
documentCount = normalizedPayload.documents.length;
} else if (Array.isArray(normalizedPayload.document_list)) {
documentCount = normalizedPayload.document_list.length;
} else if (Array.isArray(normalizedPayload.data)) {
documentCount = normalizedPayload.data.length;
} else if (normalizedPayload.document || normalizedPayload.print_data) {
documentCount = 1;
}
return { documentCount };
}
/**
* 从快递打印 payload 中提取任务编码。
* @param {Object} payload 快递打印 payload。
* @return {string} 任务编码,提取失败时返回空字符串。
*/
extractExpressTaskCodeFromPayload(payload = {}) {
const normalizedPayload = payload && typeof payload === 'object' ? payload : {};
const task = normalizedPayload.task && typeof normalizedPayload.task === 'object'
? normalizedPayload.task
: {};
return String(task.taskID || '').trim();
}
/**
* 构建打印记录可持久化的任务编码字段。
* @param {Array<string>} taskCodes 任务编码列表。
* @return {string|null} 可持久化任务编码串,无有效编码时返回 null。
*/
buildPrintTaskCodeForRecord(taskCodes = []) {
const normalizedTaskCodes = Array.isArray(taskCodes)
? taskCodes.map(taskCode => String(taskCode || '').trim()).filter(Boolean)
: [];
if (normalizedTaskCodes.length === 0) {
return null;
}
return Array.from(new Set(normalizedTaskCodes)).join(',');
}
/**
* 构建打印记录初始化字段,统一发送状态初始值。
* @param {Object} payload 业务字段。
* @return {Object} 可直接用于创建打印记录的字段。
*/
buildPendingPrintRecordPayload(payload = {}) {
const normalizedPayload = payload && typeof payload === 'object' ? payload : {};
return {
...normalizedPayload,
status: 'pending',
send_status: 'pending',
print_status: 'unknown',
};
}
/**
* 构建打印记录发送成功后的状态字段。
* @param {Object} [payload] 扩展字段。
* @param {Date|string|null} [payload.sentTime] 发送时间,为空时使用当前时间。
* @return {Object} 可直接用于更新打印记录的字段。
*/
buildSentPrintRecordUpdatePayload(payload = {}) {
const normalizedPayload = payload && typeof payload === 'object' ? payload : {};
const sentTime = normalizedPayload.sentTime || new Date();
return {
status: 'sent',
send_status: 'sent',
print_status: 'unknown',
sent_time: sentTime,
print_time: sentTime,
fail_code: null,
error_message: null,
};
}
/**
* 构建打印记录发送失败后的状态字段。
* @param {Object} [payload] 扩展字段。
* @param {string} [payload.errorMessage] 失败信息。
* @param {string} [payload.failCode] 失败编码。
* @return {Object} 可直接用于更新打印记录的字段。
*/
buildSendFailedPrintRecordUpdatePayload(payload = {}) {
const normalizedPayload = payload && typeof payload === 'object' ? payload : {};
const errorMessage = normalizedPayload.errorMessage
? String(normalizedPayload.errorMessage)
: null;
const failCode = normalizedPayload.failCode
? String(normalizedPayload.failCode)
: 'SEND_FAILED';
return {
status: 'failed',
send_status: 'send_failed',
print_status: 'unknown',
fail_code: failCode,
error_message: errorMessage,
};
}
/**
* 规范化订单ID数组,过滤非法值并去重。
* @param {Array<number|string>} orderIds 原始订单ID数组。
* @return {Array<number>} 规范化后的订单ID数组。
*/
normalizeOrderIds(orderIds = []) {
if (!Array.isArray(orderIds)) {
return [];
}
return Array.from(new Set(orderIds
.map(orderId => Number(orderId || 0))
.filter(orderId => Number.isInteger(orderId) && orderId > 0)));
}
/**
* 从单个平台分组提取订单ID列表。
* 优先读取平台透出的 order_ids,并补充 orders[*].order_id。
* @param {Object} platformGroup 平台分组数据。
* @param {Array<Object>} [ordersOverride] 指定订单列表(用于分批场景)。
* @return {Array<number>} 去重后的订单ID列表。
*/
collectOrderIdsFromPlatformGroup(platformGroup = {}, ordersOverride = null) {
const normalizedPlatformGroup = platformGroup && typeof platformGroup === 'object' ? platformGroup : {};
const orderIdSet = new Set(this.normalizeOrderIds(normalizedPlatformGroup.order_ids));
const orders = Array.isArray(ordersOverride)
? ordersOverride
: (Array.isArray(normalizedPlatformGroup.orders) ? normalizedPlatformGroup.orders : []);
for (const order of orders) {
const normalizedOrderId = Number(order && order.order_id || 0);
if (Number.isInteger(normalizedOrderId) && normalizedOrderId > 0) {
orderIdSet.add(normalizedOrderId);
}
}
return Array.from(orderIdSet);
}
/**
* 从自定义打印数据中提取订单ID列表。
* 支持 order_ids / orderIds 数组以及单个 order_id / orderId 字段。
* @param {Object} customData 自定义打印数据对象。
* @return {Array<number>} 去重后的订单ID列表。
*/
collectOrderIdsFromCustomizeData(customData = {}) {
const normalizedData = customData && typeof customData === 'object' ? customData : {};
const orderIdSet = new Set();
// 尝试读取 order_ids 数组
if (Array.isArray(normalizedData.order_ids)) {
for (const id of normalizedData.order_ids) {
const num = Number(id || 0);
if (Number.isInteger(num) && num > 0) {
orderIdSet.add(num);
}
}
}
// 尝试读取 orderIds 数组
if (Array.isArray(normalizedData.orderIds)) {
for (const id of normalizedData.orderIds) {
const num = Number(id || 0);
if (Number.isInteger(num) && num > 0) {
orderIdSet.add(num);
}
}
}
// 尝试读取单个 order_id / orderId
const singleId = Number(normalizedData.order_id || normalizedData.orderId || 0);
if (Number.isInteger(singleId) && singleId > 0) {
orderIdSet.add(singleId);
}
return Array.from(orderIdSet);
}
/**
* 规范化快递打印平台编码,兼容常见别名。
* @param {Object} payload 入参。
* @param {string} payload.platformCode 原始平台编码。
* @param {Object} [payload.payloadBuilder] 快递 payload 组装器。
* @return {string} 规范化平台编码。
*/
normalizeExpressPlatformCode(payload = {}) {
const normalizedPayload = payload && typeof payload === 'object' ? payload : {};
const platformCode = String(normalizedPayload.platformCode || '').trim();
const payloadBuilder = normalizedPayload.payloadBuilder;
if (payloadBuilder && typeof payloadBuilder.normalizePlatform === 'function') {
try {
const normalizedPlatformCode = String(payloadBuilder.normalizePlatform(platformCode) || '').trim().toLowerCase();
if (normalizedPlatformCode) {
return normalizedPlatformCode;
}
} catch (error) {
this.ctx.logger.warn('[print.send] 平台编码归一化失败,回退本地策略', {
platformCode,
reason: error && error.message ? error.message : `${error}`,
});
}
}
const lowerPlatformCode = platformCode.toLowerCase();
if ([ 'shipinhao', 'wechatvideo' ].includes(lowerPlatformCode)) {
return 'sph';
}
if (lowerPlatformCode === 'ks') {
return 'kuaishou';
}
return lowerPlatformCode;
}
/**
* 从打印记录 data 中提取订单ID列表。
* 兼容 data 为对象或 JSON 字符串,无法识别时返回空数组。
* @param {Object|string} printRecordData 打印记录 data 字段。
* @return {Array<number>} 订单ID列表。
*/
extractOrderIdsFromPrintRecordData(printRecordData) {
let normalizedRecordData = printRecordData;
if (typeof normalizedRecordData === 'string') {
try {
normalizedRecordData = JSON.parse(normalizedRecordData);
} catch (error) {
return [];
}
}
if (!normalizedRecordData || typeof normalizedRecordData !== 'object' || Array.isArray(normalizedRecordData)) {
return [];
}
return this.normalizeOrderIds(normalizedRecordData.order_ids);
}
/**
* 更新订单主表打印状态。
* 仅在可识别订单ID时更新,failed 场景附加 print_status=none 条件避免覆盖已完成状态。
* @param {Object} payload 更新参数。
* @param {number|string} payload.warehouseId 仓库ID。
* @param {Array<number|string>} payload.orderIds 订单ID列表。
* @param {'success'|'failed'} payload.result 回执结果。
* @return {Promise<{success:boolean,affectedRows:number,skipped:boolean,errorMessage:string}>} 更新结果。
*/
async updateOrderPrintStatusByCallback(payload = {}) {
const normalizedPayload = payload && typeof payload === 'object' ? payload : {};
const warehouseId = Number(normalizedPayload.warehouseId || 0);
const orderIds = this.normalizeOrderIds(normalizedPayload.orderIds);
const callbackResult = String(normalizedPayload.result || '').trim().toLowerCase();
if (!Number.isInteger(warehouseId) || warehouseId <= 0 || orderIds.length === 0) {
return {
success: true,
affectedRows: 0,
skipped: true,
errorMessage: '',
};
}
try {
const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory;
if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') {
return {
success: false,
affectedRows: 0,
skipped: false,
errorMessage: 'OrderDeliveryFactory 不可用',
};
}
const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(warehouseId);
if (!orderDeliveryModel || typeof orderDeliveryModel.update !== 'function') {
return {
success: false,
affectedRows: 0,
skipped: false,
errorMessage: 'OrderDeliveryModel 不可用',
};
}
const updatePayload = callbackResult === 'success'
? { print_status: 'fin' }
: { print_status: 'error' };
const where = {
id: orderIds,
intercept_status: 'none',
};
if (callbackResult === 'failed') {
where.print_status = 'none';
}
const updateResult = await orderDeliveryModel.update(updatePayload, {
where,
});
const affectedRows = Number(Array.isArray(updateResult) ? updateResult[0] : updateResult) || 0;
return {
success: true,
affectedRows: affectedRows > 0 ? affectedRows : 0,
skipped: false,
errorMessage: '',
};
} catch (error) {
return {
success: false,
affectedRows: 0,
skipped: false,
errorMessage: error && error.message ? error.message : `${error}`,
};
}
}
/**
* 获取打印任务编码冲突重试配置。
* @return {{maxRetries:number,baseDelayMs:number,jitterMs:number}} 归一化后的重试配置。
*/
getPrintTaskCodeRetryConfig() {
const retryConfig = this.app && this.app.config && this.app.config.printTaskCodeRetry
? this.app.config.printTaskCodeRetry
: {};
const maxRetries = Number.parseInt(retryConfig.maxRetries, 10);
const baseDelayMs = Number.parseInt(retryConfig.baseDelayMs, 10);
const jitterMs = Number.parseInt(retryConfig.jitterMs, 10);
return {
maxRetries: Number.isInteger(maxRetries) && maxRetries > 0 ? maxRetries : 5,
baseDelayMs: Number.isInteger(baseDelayMs) && baseDelayMs >= 0 ? baseDelayMs : 50,
jitterMs: Number.isInteger(jitterMs) && jitterMs >= 0 ? jitterMs : 30,
};
}
/**
* 获取打印任务编码回写重试配置。
* @return {{maxRetries:number,baseDelayMs:number,jitterMs:number}} 归一化后的回写重试配置。
*/
getPrintTaskCodeWritebackRetryConfig() {
const retryConfig = this.app && this.app.config && this.app.config.printTaskCodeWritebackRetry
? this.app.config.printTaskCodeWritebackRetry
: {};
const maxRetries = Number.parseInt(retryConfig.maxRetries, 10);
const baseDelayMs = Number.parseInt(retryConfig.baseDelayMs, 10);
const jitterMs = Number.parseInt(retryConfig.jitterMs, 10);
return {
maxRetries: Number.isInteger(maxRetries) && maxRetries > 0 ? maxRetries : 3,
baseDelayMs: Number.isInteger(baseDelayMs) && baseDelayMs >= 0 ? baseDelayMs : 50,
jitterMs: Number.isInteger(jitterMs) && jitterMs >= 0 ? jitterMs : 30,
};
}
/**
* 生成可排序且高熵的打印任务编码。
* 格式:PRT{yyyyMMddHHmmss}{processIdHex}{random8hex}
* @return {string} 打印任务编码。
*/
generateAtomicPrintTaskCode() {
const now = new Date();
const datePart = [
now.getFullYear(),
String(now.getMonth() + 1).padStart(2, '0'),
String(now.getDate()).padStart(2, '0'),
String(now.getHours()).padStart(2, '0'),
String(now.getMinutes()).padStart(2, '0'),
String(now.getSeconds()).padStart(2, '0'),
].join('');
const processIdHex = Number(process.pid || 0)
.toString(16)
.padStart(4, '0')
.slice(-4);
const randomHex = randomBytes(4).toString('hex');
return `PRT${datePart}${processIdHex}${randomHex}`;
}
/**
* 判断是否为唯一索引冲突错误。
* @param {Error} error 异常对象。
* @return {boolean} 是否为唯一约束冲突。
*/
isDuplicateKeyError(error) {
if (!error || typeof error !== 'object') {
return false;
}
const errorName = String(error.name || '');
const errorCode = String(error.code || error.parent && error.parent.code || '');
const errno = Number(error.errno || error.parent && error.parent.errno || 0);
return errorName === 'SequelizeUniqueConstraintError'
|| errorCode === 'ER_DUP_ENTRY'
|| errno === 1062;
}
/**
* 计算指数退避等待时长,并叠加随机抖动。
* @param {number} attempt 当前尝试次数(从 1 开始)。
* @param {number} baseDelayMs 基础等待毫秒。
* @param {number} jitterMs 抖动毫秒上限。
* @return {number} 需要等待的毫秒数。
*/
calculateBackoffDelayMs(attempt, baseDelayMs, jitterMs) {
const normalizedAttempt = Number.isInteger(attempt) && attempt > 0 ? attempt : 1;
const normalizedBase = Number.isFinite(baseDelayMs) && baseDelayMs >= 0 ? baseDelayMs : 0;
const normalizedJitter = Number.isFinite(jitterMs) && jitterMs >= 0 ? jitterMs : 0;
const backoff = normalizedBase * (2 ** Math.max(0, normalizedAttempt - 1));
const jitter = normalizedJitter > 0 ? Math.floor(Math.random() * (normalizedJitter + 1)) : 0;
return backoff + jitter;
}
/**
* 异步等待指定毫秒数。
* @param {number} delayMs 等待毫秒。
* @return {Promise<void>} 无返回值。
*/
async sleep(delayMs) {
const waitMs = Number.isFinite(delayMs) && delayMs > 0 ? Math.floor(delayMs) : 0;
if (waitMs <= 0) {
return;
}
await new Promise(resolve => setTimeout(resolve, waitMs));
}
/**
* 原子预占打印任务编码:依赖唯一索引插入映射表并处理冲突重试。
* @return {Promise<string>} 预占成功的任务编码。
*/
async reserveUniquePrintTaskCode() {
const { maxRetries, baseDelayMs, jitterMs } = this.getPrintTaskCodeRetryConfig();
for (let attempt = 1; attempt <= maxRetries; attempt++) {
const taskCode = this.generateAtomicPrintTaskCode();
try {
await this.ctx.model.PrintTaskMap.create({
task_code: taskCode,
print_record_id: null,
provider: null,
});
return taskCode;
} catch (error) {
if (!this.isDuplicateKeyError(error)) {
throw error;
}
if (attempt >= maxRetries) {
throw new Error(`打印任务编码生成冲突,重试 ${maxRetries} 次后失败`);
}
const waitMs = this.calculateBackoffDelayMs(attempt, baseDelayMs, jitterMs);
this.ctx.logger.warn('[print.send] 打印任务编码冲突,准备重试', {
attempt,
maxRetries,
waitMs,
});
await this.sleep(waitMs);
}
}
throw new Error('打印任务编码生成失败');
}
/**
* 通过事务(若可用)回写打印任务编码映射与打印记录。
* 单条打印记录仅允许绑定一个 task_code,重复回写同 task_code 可重入。
* @param {Object} payload 回写参数。
* @param {number|string} payload.printRecordId 打印记录ID。
* @param {string} payload.taskCode 任务编码。
* @param {string} [payload.provider] provider 返回任务ID。
* @return {Promise<void>} 无返回值。
*/
async bindTaskCodeToPrintRecord(payload = {}) {
const printRecordId = Number(payload.printRecordId || 0);
const taskCode = String(payload.taskCode || '').trim();
const provider = String(payload.provider || '').trim();
if (!printRecordId || !taskCode) {
throw new Error('回写任务编码失败:printRecordId 或 taskCode 缺失');
}
const runBinding = async transaction => {
const mapUpdatePayload = {
print_record_id: printRecordId,
};
if (provider) {
mapUpdatePayload.provider = provider;
}
await this.ctx.model.PrintTaskMap.update(mapUpdatePayload, {
where: { task_code: taskCode },
transaction,
});
const lockOption = transaction && transaction.LOCK ? { lock: transaction.LOCK.UPDATE } : {};
const printRecord = await this.ctx.model.PrintRecord.findOne({
where: { id: printRecordId },
transaction,
...lockOption,
raw: true,
});
if (!printRecord) {
throw new Error(`打印记录不存在,id=${printRecordId}`);
}
const existingTaskCode = String(printRecord.print_task_code || '').trim();
if (existingTaskCode && existingTaskCode !== taskCode) {
throw new Error(`打印记录已绑定其他任务编码,id=${printRecordId}`);
}
const needWriteTaskCode = existingTaskCode !== taskCode;
const normalizedStatus = String(printRecord.status || '').trim();
const normalizedSendStatus = String(printRecord.send_status || '').trim();
const normalizedPrintStatus = String(printRecord.print_status || '').trim();
const needUpdateStatus = normalizedStatus !== 'sent'
|| normalizedSendStatus !== 'sent'
|| normalizedPrintStatus !== 'printed'
|| !printRecord.sent_time;
if (!needWriteTaskCode && !needUpdateStatus) {
return;
}
const printRecordUpdatePayload = needUpdateStatus
? this.buildSentPrintRecordUpdatePayload({ sentTime: printRecord.sent_time || new Date() })
: {};
if (needWriteTaskCode) {
printRecordUpdatePayload.print_task_code = taskCode;
}
await this.ctx.model.PrintRecord.update(printRecordUpdatePayload, {
where: { id: printRecordId },
transaction,
});
};
if (this.ctx.model && typeof this.ctx.model.transaction === 'function') {
await this.ctx.model.transaction(async transaction => {
await runBinding(transaction);
});
return;
}
await runBinding(null);
}
/**
* 回写任务编码并支持失败重试,保证 provider 成功后写回可重试。
* @param {Object} payload 回写参数。
* @param {number|string} payload.printRecordId 打印记录ID。
* @param {string} payload.taskCode 任务编码。
* @param {string} [payload.provider] provider 返回任务ID。
* @return {Promise<void>} 无返回值。
*/
async bindTaskCodeToPrintRecordWithRetry(payload = {}) {
const { maxRetries, baseDelayMs, jitterMs } = this.getPrintTaskCodeWritebackRetryConfig();
let lastError = null;
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
await this.bindTaskCodeToPrintRecord(payload);
return;
} catch (error) {
lastError = error;
const errorMessage = error && error.message ? error.message : `${error}`;
this.ctx.logger.error('[print.send] 打印任务编码回写失败', {
attempt,
maxRetries,
printRecordId: payload.printRecordId,
taskCode: payload.taskCode,
error: errorMessage,
});
if (attempt >= maxRetries) {
break;
}
const waitMs = this.calculateBackoffDelayMs(attempt, baseDelayMs, jitterMs);
await this.sleep(waitMs);
}
}
throw new Error(`打印任务编码回写失败,可重试。原因:${lastError && lastError.message ? lastError.message : `${lastError}`}`);
}
/**
* 发送打印任务到打印电脑。
* 本方法不做打印锁状态校验,不阻止重复打印请求。
* 仅在 type=customize 时要求 printer、template、page_width、page_height、template_content。
* @param {Object} _data 打印请求参数
* @param {string} [_data.printer] 打印机名称(type=customize 必填,type=express 忽略)
* @param {string} _data.type 打印类型,支持 customize/express
* @param {Object} [_data.template] 打印模板对象(customize 必填)
* @param {Object} _data.data 打印业务数据(express 场景要求 data.waveGroups)
* @param {string|number} [_data.printStationId] 打印台 ID(express 必填)
* @param {string} [_data.requestCode] 请求参数码(express 必填,用于本次请求内 ID 唯一化)
* @param {string} [_data.computerId] 打印电脑 ID(customize 必填,express 忽略)
* @param {string} [_data.timestamp] 业务时间戳(express 忽略)
* @param {number} [_data.count] 打印份数(express 忽略)
* @return {Promise<Object>} 统一返回结构
*/
async send(_data) {
const { ctx } = this;
const warehouseId = ctx.user.store_id;
const {
printer,
type,
template,
data,
computerId,
timestamp,
count,
printStationId,
requestCode,
} = _data;
this.ctx.logger.info('[print.send] 入参接收', {
warehouseId,
inputSummary: this.buildPrintSendInputSummary(_data),
});
this.ctx.logger.info('[print.send] 分支判定', {
warehouseId,
type,
isExpress: type === 'express',
isCustomize: type === 'customize',
});
if (type === 'express') {
const expressValidationResult = this.validateExpressSendInput({ data, printStationId, requestCode });
if (expressValidationResult) {
this.ctx.logger.warn('[print.send] express 参数校验失败', {
warehouseId,
printStationId,
requestCode: requestCode ? String(requestCode) : '',
waveGroupsCount: Array.isArray(data && data.waveGroups) ? data.waveGroups.length : 0,
});
this.ctx.logger.error('[print.send] 最终返回 failure', {
warehouseId,
type,
reason: 'express 参数校验失败',
});
return expressValidationResult;
}
this.ctx.logger.info('[print.send] express 参数校验通过', {
warehouseId,
printStationId,
waveGroupsCount: Array.isArray(data && data.waveGroups) ? data.waveGroups.length : 0,
});
}
// 从自定义打印数据中尝试提取关联的配送订单ID,用于后续同步 print_status
const customizeOrderIds = type !== 'express' ? this.collectOrderIdsFromCustomizeData(data) : [];
let printRecord = null;
if (type !== 'express') {
// 生成打印编号并记录到数据库
try {
const printRecordData = { template, data };
if (customizeOrderIds.length > 0) {
printRecordData.order_ids = customizeOrderIds;
}
printRecord = await ctx.model.PrintRecord.create(this.buildPendingPrintRecordPayload({
warehouse_id: warehouseId,
computer_id: computerId,
printer,
type,
data: printRecordData,
}));
this.ctx.logger.info('[print.send] PrintRecord 创建成功', {
warehouseId,
type,
printId: printRecord.id,
computerId,
printer,
});
} catch (error) {
this.ctx.logger.error('[print.send] PrintRecord 创建失败', {
warehouseId,
type,
computerId,
printer,
error: error && error.message ? error.message : `${error}`,
stack: error && error.stack ? error.stack : '',
});
throw error;
}
}
// 处理后的数据
let processedData = {};
switch (type) {
case 'customize': {
if (printer === undefined || printer === null || printer === '') {
this.ctx.logger.warn('[print.send] customize 参数校验失败-printer 为空', {
warehouseId,
type,
});
this.ctx.logger.error('[print.send] 最终返回 failure', {
warehouseId,
type,
reason: 'printer 参数不能为空',
});
return this.fail('type=customize 时 printer 参数不能为空', { code: 400 });
}
if (!template || typeof template !== 'object' || Array.isArray(template)) {
this.ctx.logger.warn('[print.send] customize 参数校验失败-template 非对象', {
warehouseId,
type,
});
this.ctx.logger.error('[print.send] 最终返回 failure', {
warehouseId,
type,
reason: 'template 参数不合法',
});
return this.fail('type=customize 时 template 参数不能为空', { code: 400 });
}
const { page_width, page_height, template_content } = template;
if (page_width === undefined || page_width === null || page_width === '') {
this.ctx.logger.warn('[print.send] customize 参数校验失败-page_width 为空', {
warehouseId,
type,
});
this.ctx.logger.error('[print.send] 最终返回 failure', {
warehouseId,
type,
reason: 'page_width 参数不能为空',
});
return this.fail('type=customize 时 page_width 参数不能为空', { code: 400 });
}
if (page_height === undefined || page_height === null || page_height === '') {
this.ctx.logger.warn('[print.send] customize 参数校验失败-page_height 为空', {
warehouseId,
type,
});
this.ctx.logger.error('[print.send] 最终返回 failure', {
warehouseId,
type,
reason: 'page_height 参数不能为空',
});
return this.fail('type=customize 时 page_height 参数不能为空', { code: 400 });
}
if (!Array.isArray(template_content)) {
this.ctx.logger.warn('[print.send] customize 参数校验失败-template_content 非数组', {
warehouseId,
type,
});
this.ctx.logger.error('[print.send] 最终返回 failure', {
warehouseId,
type,
reason: 'template_content 参数不合法',
});
return this.fail('type=customize 时 template_content 必须是数组', { code: 400 });
}
let htm = `<body style="position:relative; width:${page_width}mm; height:${page_height}mm;margin:0; padding:0;overflow:hidden;">`;
for (const item of template_content) {
let content = item.content;
for (const key in data) {
if (String(item.field_code) === key) {
content = data[key];
}
}
switch (item.type) {
case 'text':
htm += `<div style="
position:absolute;
width:${item.width}mm;
height:${item.height}mm;
left:${item.left}mm;
top:${item.top}mm;
font-size:${item.fontSize}pt;
font-weight:${item.bold ? 'bold' : 'normal'};
font-style:${item.italic ? 'italic' : 'normal'};
text-decoration:${item.underline ? 'underline' : 'none'};
text-align:${item.textAlign};
transform: rotate(${item.rotate}deg);
line-height: ${item.lineHeight}mm;
};
">${content}</div>`;
break;
case 'image':
htm += `<img src="${content}" style="position:absolute;
left:${item.left}mm;
top:${item.top}mm;
width:${item.width}mm;
height:${item.height}mm;" />`;
break;
case 'barcode':
htm += `<div style="
position:absolute;
left:${item.left}mm;
top:${item.top}mm;
width:${item.width}mm;
height:${item.height}mm;
"><img style="width:100%; height:100%;" src="https://ye4s.wms.gztbyc.com/barcode/build?text=${content.slice(-13)}&type=C128&foreground=%23000000&width=2&height=${parseInt(item.height / 25.4 * 96)}" /></div>`;
break;
case 'qrcode': {
let toUrl = `https://ye4s.wms.gztbyc.com/to/${content}`;
// 转换成urlencode
toUrl = encodeURIComponent(toUrl);
const url = `https://ye4s.wms.gztbyc.com/qrcode/build?text=${toUrl}`;
htm += `<div style="
position:absolute;
left:${item.left}mm;
top:${item.top}mm;
width:${item.width}mm;
height:${item.height}mm;
"><img style="width:100%; height:100%;" src="${url}" /></div>`;
break;
}
case 'line':
htm += `<div style="
position:absolute;
left:${item.left}mm;
top:${item.top}mm;
width:${item.width}mm;
height:${item.height}mm;
border-top: ${item.line_width}px ${item.line_style} ${item.line_color};
"></div>`;
break;
case 'rectangle':
htm += `<div style="
position:absolute;
left:${item.left}mm;
top:${item.top}mm;
width:${item.width}mm;
height:${item.height}mm;
border: ${item.line_width}px ${item.line_style} ${item.line_color};
"></div>`;
break;
case 'table': {
let tableHtml = `<table style="position:absolute; left:${item.left}mm; top:${item.top}mm; border-collapse: collapse;">`;
for (let i = 0; i < item.rows; i++) {
tableHtml += '<tr>';
for (let j = 0; j < item.columns; j++) {
let cellContent = item.content[i] && item.content[i][j] ? item.content[i][j] : '';
// 解析单元格字段码为实际数据,与 text 类型保持一致的解析逻辑
for (const key in data) {
if (String(cellContent) === key) {
cellContent = data[key];
}
}
tableHtml += `<td style="border: ${item.line_width}px ${item.line_style} ${item.line_color}; width:${item.width / item.columns}mm; height:${item.height / item.rows}mm;">${cellContent}</td>`;
} tableHtml += '</tr>';
} tableHtml += '</table>';
htm += tableHtml;
break;
}
default:
break;
}
}
htm += '</body>';
processedData = {
pageWidth: page_width,
pageHeight: page_height,
htm,
lodopkey: [ '', '13528A153BAEE3A0254B9507DCDE2839', 'EDE92F75B6A3D917F65910', 'D60BC84D7CF2DE18156A6F88987304CB6D8' ],
};
this.ctx.logger.info('[print.send] customize payload 组装完成', {
warehouseId,
type,
pageWidth: page_width,
pageHeight: page_height,
templateItemCount: template_content.length,
});
break;
}
case 'express': {
const expressPrintStation = await this.loadExpressPrintStation({ printStationId, warehouseId });
if (!expressPrintStation.success) {
this.ctx.logger.error('[print.send] 最终返回 failure', {
warehouseId,
type,
reason: expressPrintStation.error,
});
return this.fail(expressPrintStation.error, { code: 400 });
}
const expressRecordFields = this.buildExpressPrintRecordFields(expressPrintStation.data);
if (!expressRecordFields.success) {
this.ctx.logger.error('[print.send] 最终返回 failure', {
warehouseId,
type,
reason: expressRecordFields.error,
});
return this.fail(expressRecordFields.error, { code: 400 });
}
const platformCodes = this.collectExpressPlatformCodes(data.waveGroups);
const platformComponentsResult = await this.loadExpressPlatformComponents({ platformCodes });
if (!platformComponentsResult.success) {
this.ctx.logger.error('[print.send] 最终返回 failure', {
warehouseId,
type,
reason: platformComponentsResult.error,
});
return this.fail(platformComponentsResult.error, { code: 400 });
}
const componentOnlineResult = await this.validateExpressComponentsOnline({
computerId: expressRecordFields.data.computer_id,
platformComponents: platformComponentsResult.data,
});
if (!componentOnlineResult.success) {
this.ctx.logger.error('[print.send] 最终返回 failure', {
warehouseId,
type,
reason: componentOnlineResult.error,
});
return this.fail(componentOnlineResult.error, { code: 400 });
}
const payloadBuilder = new ExpressPrintPayloadBuilder({ baseDir: this.app.baseDir });
const idGenerator = new RequestScopedPrintIdGenerator(requestCode);
const expressSendResult = await this.sendExpressWaveGroups({
warehouseId,
waveGroups: data.waveGroups,
requestCode,
printStation: expressPrintStation.data,
payloadBuilder,
idGenerator,
expressRecordFields: expressRecordFields.data,
platformComponents: platformComponentsResult.data,
type,
template,
data,
});
if (!expressSendResult.success) {
this.ctx.logger.error('[print.send] 最终返回 failure', {
warehouseId,
type,
printId: expressSendResult.printId || 0,
reason: expressSendResult.error,
});
return this.fail(expressSendResult.error, {
code: 504,
printId: expressSendResult.printId || 0,
printIds: Array.isArray(expressSendResult.printIds) ? expressSendResult.printIds : [],
});
}
// 异步检查是否需要解绑拣货车(不阻塞返回)
const expressWaveIds = this.extractUniqueWaveIds(data.waveGroups);
for (const wid of expressWaveIds) {
this.tryUnbindCartAfterPrintComplete(wid).catch(err => {
this.ctx.logger.error('[print.send] 异步解绑车标异常', {
waveId: wid,
warehouseId,
error: err && err.message ? err.message : `${err}`,
});
});
}
this.ctx.logger.info('[print.send] 最终返回 success', {
warehouseId,
type,
printId: expressSendResult.printId || 0,
printIdsCount: Array.isArray(expressSendResult.printIds) ? expressSendResult.printIds.length : 0,
});
return this.success('发送打印任务成功', {
code: 200,
printId: expressSendResult.printId || 0,
printIds: Array.isArray(expressSendResult.printIds) ? expressSendResult.printIds : [],
});
}
default:
this.ctx.logger.error('[print.send] 最终返回 failure', {
warehouseId,
type,
reason: '不支持的打印类型',
});
return this.fail('不支持的打印类型', 1001);
}
const printData = {
printer,
type,
template,
data: processedData,
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 });
const sendDurationMs = Date.now() - sendStartAt;
if (res.status === 'success') {
this.ctx.logger.info('[print.send] sendToComputer 调用成功', {
warehouseId,
type,
printId: printRecord.id,
computerId,
durationMs: sendDurationMs,
});
} else {
this.ctx.logger.error('[print.send] sendToComputer 调用失败', {
warehouseId,
type,
printId: printRecord.id,
computerId,
durationMs: sendDurationMs,
error: res && res.error ? res.error : '打印服务返回失败',
});
}
// 发送成功后更新打印记录状态
if (res.status === 'success') {
await printRecord.update(this.buildSentPrintRecordUpdatePayload());
// 同步更新关联配送订单的 print_status 为 'fin'
if (customizeOrderIds.length > 0) {
const updateResult = await this.updateOrderPrintStatusByCallback({
warehouseId,
orderIds: customizeOrderIds,
result: 'success',
});
if (!updateResult.success) {
this.ctx.logger.error('[print.send] 同步订单 print_status 失败', {
warehouseId,
type,
orderIdsCount: customizeOrderIds.length,
reason: updateResult.errorMessage,
});
}
}
this.ctx.logger.info('[print.send] 最终返回 success', {
warehouseId,
type,
printId: printRecord.id,
});
return this.success('发送打印任务成功', { code: 200, printId: printRecord.id });
}
await printRecord.update(this.buildSendFailedPrintRecordUpdatePayload({
errorMessage: res.error || '打印服务返回失败',
}));
this.ctx.logger.error('[print.send] 最终返回 failure', {
warehouseId,
type,
printId: printRecord.id,
reason: res.error || '打印服务返回失败',
});
return this.fail(res.error, { code: 504, printId: printRecord.id });
}
/**
* 校验快递打印请求的必要参数。
* @param {Object} payload 校验参数。
* @param {Object} payload.data 请求 data。
* @param {number|string} payload.printStationId 打印台 ID。
* @param {string} payload.requestCode 请求参数码。
* @return {Object|null} 失败时返回 fail 响应,成功返回 null。
*/
validateExpressSendInput(payload = {}) {
const requestData = payload && typeof payload === 'object' ? payload : {};
const waveGroups = Array.isArray(requestData.data && requestData.data.waveGroups)
? requestData.data.waveGroups
: [];
if (waveGroups.length === 0) {
this.ctx.logger.warn('[print.send] express 参数校验失败-data.waveGroups 为空', {
printStationId: requestData.printStationId || '',
requestCode: requestData.requestCode ? String(requestData.requestCode) : '',
});
return this.fail('type=express 时 data.waveGroups 必须是非空数组', { code: 400 });
}
const normalizedPrintStationId = String(requestData.printStationId || '').trim();
if (!normalizedPrintStationId) {
this.ctx.logger.warn('[print.send] express 参数校验失败-printStationId 为空', {
requestCode: requestData.requestCode ? String(requestData.requestCode) : '',
waveGroupsCount: waveGroups.length,
});
return this.fail('type=express 时 printStationId 参数不能为空', { code: 400 });
}
const normalizedRequestCode = String(requestData.requestCode || '').trim();
if (!normalizedRequestCode) {
this.ctx.logger.warn('[print.send] express 参数校验失败-requestCode 为空', {
printStationId: normalizedPrintStationId,
waveGroupsCount: waveGroups.length,
});
return this.fail('type=express 时 requestCode 参数不能为空', { code: 400 });
}
return null;
}
/**
* 查询并校验快递打印台。
* @param {Object} payload 查询参数。
* @param {number|string} payload.printStationId 打印台 ID。
* @param {number|string} payload.warehouseId 仓库 ID。
* @return {Promise<{success:boolean,data?:Object,error?:string}>} 查询结果。
*/
async loadExpressPrintStation(payload = {}) {
const { ctx } = this;
const normalizedPayload = payload && typeof payload === 'object' ? payload : {};
const printStation = await ctx.model.PrintStations.findOne({
where: {
id: normalizedPayload.printStationId,
warehouse_id: normalizedPayload.warehouseId,
deleted: 0,
},
raw: true,
});
if (!printStation) {
this.ctx.logger.warn('[print.send] 打印台查询失败', {
printStationId: normalizedPayload.printStationId,
warehouseId: normalizedPayload.warehouseId,
});
return {
success: false,
error: '打印台不存在',
};
}
this.ctx.logger.info('[print.send] 打印台查询成功', {
printStationId: printStation.id,
warehouseId: normalizedPayload.warehouseId,
computerId: printStation.computer_id || '',
defaultPrinterName: printStation.default_printer_name || '',
});
return {
success: true,
data: printStation,
};
}
/**
* 组装快递打印记录的必填字段,避免写入 null。
* @param {Object} printStation 打印台配置。
* @return {{success:boolean,data?:{computer_id:string,printer:string},error?:string}} 组装结果。
*/
buildExpressPrintRecordFields(printStation = {}) {
const normalizedStation = printStation && typeof printStation === 'object' ? printStation : {};
const computerId = String(normalizedStation.computer_id || '').trim();
if (!computerId) {
return {
success: false,
error: '打印台未配置打印电脑',
};
}
const defaultPrinterName = String(normalizedStation.default_printer_name || '').trim();
return {
success: true,
data: {
computer_id: computerId,
printer: defaultPrinterName || 'EXPRESS_DYNAMIC_PRINTER',
},
};
}
/**
* 收集 express 请求中涉及的平台编码列表。
* @param {Array<Object>} waveGroups 波次分组数据。
* @return {Array<string>} 去重后的平台编码列表。
*/
collectExpressPlatformCodes(waveGroups = []) {
const normalizedWaveGroups = Array.isArray(waveGroups) ? waveGroups : [];
const platformCodeSet = new Set();
for (const waveGroup of normalizedWaveGroups) {
const platforms = Array.isArray(waveGroup && waveGroup.platforms) ? waveGroup.platforms : [];
for (const platformGroup of platforms) {
const orders = Array.isArray(platformGroup && platformGroup.orders) ? platformGroup.orders : [];
if (orders.length === 0) {
continue;
}
const platformCode = String(platformGroup && platformGroup.platform ? platformGroup.platform : '').trim();
if (platformCode) {
platformCodeSet.add(platformCode);
}
}
}
return Array.from(platformCodeSet);
}
/**
* 从 waveGroups 中提取去重后的 wave_id 列表。
* @param {Array<Object>} waveGroups 波次分组数据。
* @return {Array<number>} 去重后的波次ID列表。
*/
extractUniqueWaveIds(waveGroups = []) {
const normalizedWaveGroups = Array.isArray(waveGroups) ? waveGroups : [];
const waveIdSet = new Set();
for (const waveGroup of normalizedWaveGroups) {
const waveId = Number(waveGroup && waveGroup.wave_id || 0);
if (Number.isInteger(waveId) && waveId > 0) {
waveIdSet.add(waveId);
}
}
return Array.from(waveIdSet);
}
/**
* 从波次平台数据中提取订单ID列表。
*
* 优先使用平台分组透出的 order_ids;若缺失则回退读取 orders[*].order_id。
*
* @param {Array<Object>} waveGroups 波次平台分组。
* @return {Array<number>} 去重后的订单ID列表。
*/
collectOrderIdsFromWaveGroups(waveGroups = []) {
const normalizedWaveGroups = Array.isArray(waveGroups) ? waveGroups : [];
const orderIdSet = new Set();
for (const waveGroup of normalizedWaveGroups) {
const platforms = Array.isArray(waveGroup && waveGroup.platforms) ? waveGroup.platforms : [];
for (const platformGroup of platforms) {
const platformOrderIds = Array.isArray(platformGroup && platformGroup.order_ids)
? platformGroup.order_ids
: [];
for (const orderId of platformOrderIds) {
const normalizedOrderId = Number(orderId || 0);
if (Number.isInteger(normalizedOrderId) && normalizedOrderId > 0) {
orderIdSet.add(normalizedOrderId);
}
}
const orders = Array.isArray(platformGroup && platformGroup.orders) ? platformGroup.orders : [];
for (const order of orders) {
const normalizedOrderId = Number(order && order.order_id || 0);
if (Number.isInteger(normalizedOrderId) && normalizedOrderId > 0) {
orderIdSet.add(normalizedOrderId);
}
}
}
}
return Array.from(orderIdSet);
}
/**
* 从通知锁定入参中提取订单ID。
*
* 优先使用 order_ids/orderIds;为空时回退使用 waveGroups 提取。
*
* @param {Object} payload 通知锁定入参。
* @param {Array<number|string>} [payload.order_ids] 订单ID列表(推荐)。
* @param {Array<number|string>} [payload.orderIds] 兼容驼峰订单ID列表。
* @param {Array<Object>} [payload.waveGroups] 波次分组。
* @param {Object} [payload.data] 兼容 print.send 结构的数据体。
* @return {{orderIds:Array<number>,orderIdsCount:number,waveGroupsCount:number,source:string}} 提取结果。
*/
extractOrderIdsFromNotifyLockPayload(payload = {}) {
const normalizedPayload = payload && typeof payload === 'object' ? payload : {};
const data = normalizedPayload.data && typeof normalizedPayload.data === 'object' ? normalizedPayload.data : {};
const directOrderIds = this.normalizeOrderIds(Array.isArray(normalizedPayload.order_ids)
? normalizedPayload.order_ids
: (Array.isArray(normalizedPayload.orderIds) ? normalizedPayload.orderIds : []));
const waveGroups = Array.isArray(normalizedPayload.waveGroups)
? normalizedPayload.waveGroups
: (Array.isArray(data.waveGroups) ? data.waveGroups : []);
const waveGroupOrderIds = this.collectOrderIdsFromWaveGroups(waveGroups);
const hasDirectOrderIds = directOrderIds.length > 0;
const orderIds = hasDirectOrderIds ? directOrderIds : waveGroupOrderIds;
return {
orderIds,
orderIdsCount: orderIds.length,
waveGroupsCount: waveGroups.length,
source: hasDirectOrderIds ? 'order_ids' : 'waveGroups',
};
}
/**
* 构建 notifyLock 的轻量日志摘要,避免落库超大对象。
*
* @param {Object} payload notifyLock 原始入参。
* @param {Object} extracted 已提取摘要信息。
* @param {Array<number>} [extracted.orderIds] 订单ID列表。
* @param {number} [extracted.orderIdsCount] 订单数量。
* @param {number} [extracted.waveGroupsCount] 波次数量。
* @param {string} [extracted.source] 订单来源标识。
* @return {Object} 轻量可落库摘要。
*/
buildNotifyLockInputSummary(payload = {}, extracted = {}) {
const normalizedPayload = payload && typeof payload === 'object' ? payload : {};
const data = normalizedPayload.data && typeof normalizedPayload.data === 'object' ? normalizedPayload.data : {};
const orderIds = Array.isArray(extracted.orderIds) ? extracted.orderIds : [];
const orderIdsCount = Number(extracted.orderIdsCount || orderIds.length || 0);
const waveGroupsCount = Number(extracted.waveGroupsCount || 0);
const source = String(extracted.source || '').trim();
const requestCode = normalizedPayload.requestCode
? String(normalizedPayload.requestCode).slice(0, 128)
: (normalizedPayload.request_code ? String(normalizedPayload.request_code).slice(0, 128) : '');
return {
action: 'notifyLock',
source,
order_ids_count: orderIdsCount,
order_ids_sample: orderIds.slice(0, 100),
wave_groups_count: waveGroupsCount,
request_code: requestCode,
payload_keys: Object.keys(normalizedPayload).slice(0, 20),
data_keys: Object.keys(data).slice(0, 20),
has_data: Object.keys(data).length > 0,
};
}
/**
* 获取打印相关订单操作日志的操作人信息。
*
* 取值优先级:ctx.state.user -> ctx.user,字段优先尝试 employees/operator/id 与 name。
*
* @return {{id:string|null,name:string}} 操作人信息。
*/
getPrintOrderOperationOperator() {
const stateUser = this.ctx && this.ctx.state && this.ctx.state.user && typeof this.ctx.state.user === 'object'
? this.ctx.state.user
: null;
const ctxUser = this.ctx && this.ctx.user && typeof this.ctx.user === 'object'
? this.ctx.user
: null;
const user = stateUser || ctxUser || {};
const rawOperatorId = user.employees_id ?? user.operator_id ?? user.id;
const rawOperatorName = user.employees_name
?? user.operator_name
?? user.real_name
?? user.name;
const operatorId = rawOperatorId === undefined || rawOperatorId === null
? null
: (String(rawOperatorId).trim() || null);
const operatorName = rawOperatorName === undefined || rawOperatorName === null
? 'system'
: (String(rawOperatorName).trim() || 'system');
return {
id: operatorId,
name: operatorName,
};
}
/**
* 按订单ID批量写入打印相关订单操作日志。
*
* 日志写入失败不会中断主流程,仅记录 warn/error。
*
* @param {Object} payload 写入参数。
* @param {Array<number|string>} payload.orderIds 订单ID列表。
* @param {string} payload.source 来源标识(如 print.send/print.notifyLock)。
* @param {string} payload.message 日志消息。
* @param {string} [payload.operationCode='ORDER_PRINT'] 操作编码。
* @return {Promise<void>} 无返回值。
*/
async writePrintOrderOperationLogsByOrderIds(payload = {}) {
const normalizedPayload = payload && typeof payload === 'object' ? payload : {};
const orderIds = this.normalizeOrderIds(normalizedPayload.orderIds);
if (orderIds.length === 0) {
return;
}
const source = String(normalizedPayload.source || '').trim() || 'print.send';
const message = String(normalizedPayload.message || '').trim() || `${source} 执行完成`;
const operationCode = String(normalizedPayload.operationCode || '').trim() || 'ORDER_PRINT';
const warehouseId = Number(this.ctx && this.ctx.user && this.ctx.user.store_id || 0);
const operationLogService = this.ctx
&& this.ctx.service
&& this.ctx.service.systems
&& this.ctx.service.systems.operationLog;
if (!operationLogService || typeof operationLogService.createOperationLogs !== 'function') {
this.ctx.logger.warn('[print.operationLog] operationLog 批量写入服务不可用,跳过日志写入', {
source,
orderIdsCount: orderIds.length,
});
return;
}
const operator = this.getPrintOrderOperationOperator();
const payloads = orderIds.map(orderId => ({
businessType: 'order',
businessId: orderId,
operationCode,
operator,
extras: {
warehouseId,
message,
},
}));
try {
const results = await operationLogService.createOperationLogs(payloads);
if (!Array.isArray(results)) {
return;
}
for (let index = 0; index < payloads.length; index++) {
if (results[index]) {
continue;
}
this.ctx.logger.warn('[print.operationLog] 订单操作日志写入失败,不影响主流程', {
source,
orderId: payloads[index].businessId,
operationCode,
});
}
} catch (error) {
this.ctx.logger.error('[print.operationLog] 批量写入订单操作日志异常,不影响主流程', {
source,
orderIdsCount: orderIds.length,
error: error && error.message ? error.message : `${error}`,
});
}
}
/**
* 通知锁定接口:仅执行订单锁定流程,不发送打印任务。
*
* @param {Object} data 入参。
* @param {Array<number|string>} [data.order_ids] 订单ID列表(推荐)。
* @param {Array<number|string>} [data.orderIds] 兼容驼峰订单ID列表。
* @param {Array<Object>} [data.waveGroups] 波次分组(兼容 print.send 轻量版本)。
* @param {Object} [data.data] 兼容 print.send 的 data 包装。
* @return {Promise<Object>} 统一 success/fail 返回结构。
*/
async notifyLock(data = {}) {
const warehouseId = Number(this.ctx && this.ctx.user && this.ctx.user.store_id || 0);
const {
orderIds,
orderIdsCount,
waveGroupsCount,
source,
} = this.extractOrderIdsFromNotifyLockPayload(data);
const notifyLockInputSummary = this.buildNotifyLockInputSummary(data, {
orderIds,
orderIdsCount,
waveGroupsCount,
source,
});
let printRecord = null;
try {
printRecord = await this.ctx.model.PrintRecord.create(this.buildPendingPrintRecordPayload({
warehouse_id: warehouseId,
computer_id: 0,
printer: 'notifyLock',
type: 'notify_lock',
data: notifyLockInputSummary,
request_code: notifyLockInputSummary.request_code || null,
}));
} catch (error) {
this.ctx.logger.error('[print.notifyLock] PrintRecord 创建失败', {
warehouseId,
error: error && error.message ? error.message : `${error}`,
stack: error && error.stack ? error.stack : '',
});
}
if (orderIdsCount === 0) {
if (printRecord && typeof printRecord.update === 'function') {
try {
await printRecord.update(this.buildSendFailedPrintRecordUpdatePayload({
errorMessage: '未提取到有效订单ID,请传入 order_ids 或 waveGroups',
failCode: 'NOTIFY_LOCK_INVALID_INPUT',
}));
} catch (error) {
this.ctx.logger.error('[print.notifyLock] PrintRecord 更新失败', {
warehouseId,
printId: printRecord.id,
error: error && error.message ? error.message : `${error}`,
stack: error && error.stack ? error.stack : '',
});
}
}
return this.fail('未提取到有效订单ID,请传入 order_ids 或 waveGroups', {
code: 400,
locked_count: 0,
order_ids_count: 0,
wave_groups_count: waveGroupsCount,
});
}
const lockResult = await this.lockOrderDeliveryAfterPrintSentSuccess({
warehouseId,
orderIds,
});
if (!lockResult.success) {
await this.writePrintOrderOperationLogsByOrderIds({
orderIds,
source: 'print.notifyLock',
message: `通知锁定执行失败,原因=${lockResult.errorMessage || '未知错误'}`,
});
if (printRecord && typeof printRecord.update === 'function') {
try {
await printRecord.update(this.buildSendFailedPrintRecordUpdatePayload({
errorMessage: lockResult.errorMessage || '未知错误',
failCode: 'NOTIFY_LOCK_FAILED',
}));
} catch (error) {
this.ctx.logger.error('[print.notifyLock] PrintRecord 更新失败', {
warehouseId,
printId: printRecord.id,
error: error && error.message ? error.message : `${error}`,
stack: error && error.stack ? error.stack : '',
});
}
}
return this.fail(`订单锁定失败:${lockResult.errorMessage || '未知错误'}`, {
code: 500,
locked_count: 0,
order_ids_count: orderIdsCount,
order_ids: orderIds,
});
}
if (printRecord && typeof printRecord.update === 'function') {
try {
await printRecord.update(this.buildSentPrintRecordUpdatePayload());
} catch (error) {
this.ctx.logger.error('[print.notifyLock] PrintRecord 更新失败', {
warehouseId,
printId: printRecord.id,
error: error && error.message ? error.message : `${error}`,
stack: error && error.stack ? error.stack : '',
});
}
}
await this.writePrintOrderOperationLogsByOrderIds({
orderIds,
source: 'print.notifyLock',
message: `通知锁定执行成功,locked_count=${lockResult.lockedCount}`,
});
return this.success('ok', {
code: 0,
locked_count: lockResult.lockedCount,
order_ids_count: orderIdsCount,
order_ids: orderIds,
source,
});
}
/**
* notifyLock 的 snake_case 兼容别名。
*
* @param {Object} data 入参。
* @return {Promise<Object>} 与 notifyLock 一致的返回结构。
*/
async notify_lock(data = {}) {
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' },
intercept_status: 'none',
},
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 });
}
}
/**
* 波次确认打印:扫描波次内任一订单的面单号,将波次下全部已打印且非拦截的订单
* 批量标记 confirm_print_status='fin',记录「打印完成后真实扫描面单确认」。
*
* 约束:
* - 仅当前仓库下的订单可确认(面单定位强制 warehouse_id 隔离);
* - 波次下存在未打印订单(print_status != 'fin',拦截订单除外)时阻断;
* - 拦截订单跳过(不确认、不阻断);
* - 全部已确认时重复扫描返回 already_confirmed,不重复写日志。
*
* @param {Object} data 入参。
* @param {string} data.waybill_no 面单号/运单号(必填)。
* @return {Promise<Object>} 统一返回结构。
*/
async confirmWavePrint(data = {}) {
const { ctx } = this;
const requestData = data && typeof data === 'object' && !Array.isArray(data) ? data : {};
const waybillNo = String(requestData.waybill_no || requestData.waybillNo || '').trim();
if (!waybillNo) {
return this.fail('waybill_no 必填(面单号/运单号)', {}, 400);
}
// --- 仓库上下文 ---
const userWarehouseId = ctx && ctx.user ? ctx.user.store_id : undefined;
const stateWarehouseId = ctx && ctx.state && ctx.state.user ? ctx.state.user.store_id : undefined;
const warehouseId = Number(userWarehouseId || stateWarehouseId || 0);
if (!Number.isInteger(warehouseId) || warehouseId <= 0) {
return this.fail('缺少当前用户仓库上下文 store_id', {}, 400);
}
// --- 1. 面单号定位订单 ---
const orderExpress = await ctx.model.OrderExpress.findOne({
where: {
warehouse_id: warehouseId,
waybill_code: waybillNo,
},
attributes: [ 'order_id' ],
raw: true,
});
const matchedOrderId = Number(orderExpress && orderExpress.order_id || 0);
if (!(matchedOrderId > 0)) {
return this.fail('未查询到该面单号对应的订单,无记录', {}, 404);
}
// --- 2. 订单定位波次 ---
const orderDeliveryFactory = ctx.model && ctx.model.OrderDeliveryFactory;
if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') {
return this.fail('OrderDeliveryFactory 不可用', {}, 500);
}
let orderModel = null;
try {
orderModel = await orderDeliveryFactory.getCurrentModel(warehouseId);
} catch (error) {
return this.fail(error && error.message ? error.message : '订单模型不可用', {}, 500);
}
const order = await orderModel.findOne({
where: {
id: matchedOrderId,
warehouse_id: warehouseId,
},
attributes: [ 'id', 'wave_id', 'wave_no' ],
raw: true,
});
if (!order) {
return this.fail('订单不在待处理订单表,无记录', {}, 404);
}
const orderWaveId = Number(order.wave_id || 0);
const orderWaveNo = String(order.wave_no || '').trim();
if (!(orderWaveId > 0 || orderWaveNo)) {
return this.fail('运单对应订单未分配波次', {}, 400);
}
// --- 3. 查询波次下全部订单 ---
const waveOrderWhere = { warehouse_id: warehouseId };
if (orderWaveId > 0) {
waveOrderWhere.wave_id = orderWaveId;
} else {
waveOrderWhere.wave_no = orderWaveNo;
}
const waveOrderRows = await orderModel.findAll({
where: waveOrderWhere,
attributes: [ 'id', 'print_status', 'confirm_print_status', 'intercept_status' ],
raw: true,
});
const waveOrders = Array.isArray(waveOrderRows) ? waveOrderRows : [];
if (waveOrders.length === 0) {
return this.fail('波次下无可用订单', {}, 400);
}
// --- 4. 统计与校验(拦截订单跳过,未打印阻断) ---
const interceptedWaveOrderIds = new Set(waveOrders
.filter(item => isInterceptedOrderStatus(item && item.intercept_status))
.map(item => Number(item && item.id || 0))
.filter(id => Number.isInteger(id) && id > 0));
const unprintedOrderIds = [ ...new Set(waveOrders
.filter(item => String(item && item.print_status || '') !== 'fin'
&& !interceptedWaveOrderIds.has(Number(item && item.id || 0)))
.map(item => Number(item && item.id || 0))
.filter(id => Number.isInteger(id) && id > 0)) ];
if (unprintedOrderIds.length > 0) {
return this.fail('波次存在未打印订单,禁止确认打印', {
waybill_no: waybillNo,
matched_order_id: matchedOrderId,
wave_id: orderWaveId,
wave_no: orderWaveNo,
unprinted_order_count: unprintedOrderIds.length,
}, 400);
}
const pendingOrderIds = [ ...new Set(waveOrders
.filter(item => String(item && item.print_status || '') === 'fin'
&& String(item && item.confirm_print_status || '') !== 'fin'
&& !interceptedWaveOrderIds.has(Number(item && item.id || 0)))
.map(item => Number(item && item.id || 0))
.filter(id => Number.isInteger(id) && id > 0)) ];
const confirmedOrderIds = [ ...new Set(waveOrders
.filter(item => String(item && item.confirm_print_status || '') === 'fin'
&& !interceptedWaveOrderIds.has(Number(item && item.id || 0)))
.map(item => Number(item && item.id || 0))
.filter(id => Number.isInteger(id) && id > 0)) ];
const baseResponse = {
waybill_no: waybillNo,
matched_order_id: matchedOrderId,
wave_id: orderWaveId,
wave_no: orderWaveNo,
total_order_count: waveOrders.length,
intercepted_order_count: interceptedWaveOrderIds.size,
};
if (pendingOrderIds.length === 0) {
return this.success('ok', {
code: 200,
data: {
...baseResponse,
confirmed_order_count: confirmedOrderIds.length,
status: 'already_confirmed',
tip: '该波次订单均已确认打印,无需重复确认',
},
});
}
// --- 5. 事务批量确认并写订单操作日志 ---
const operationLogService = ctx.service
&& ctx.service.systems
&& ctx.service.systems.operationLog;
const operator = this.getPrintOrderOperationOperator();
const transaction = await ctx.model.transaction();
try {
const updateResult = await orderModel.update({
confirm_print_status: 'fin',
}, {
where: {
id: { [this.app.Sequelize.Op.in]: pendingOrderIds },
warehouse_id: warehouseId,
print_status: 'fin',
},
transaction,
});
const affectedRows = Number(Array.isArray(updateResult) ? updateResult[0] : updateResult) || 0;
if (operationLogService && typeof operationLogService.createOperationLogs === 'function') {
await operationLogService.createOperationLogs(pendingOrderIds.map(orderId => ({
businessType: 'order',
businessId: `${orderId}`,
operationCode: 'ORDER_CONFIRM_PRINT',
operator,
operationAction: 'UPDATE',
extras: {
warehouseId,
message: `确认打印(扫描面单 ${waybillNo},波次 ${orderWaveNo})`,
},
})), { transaction });
}
await transaction.commit();
// 驱动确认打印未领单波次统计长轮询:递增版本号,等待中的查询立即返回新值
try {
const waveService = ctx.service
&& ctx.service.systemMethods
&& ctx.service.systemMethods.order
&& ctx.service.systemMethods.order.wave;
if (waveService && typeof waveService.bumpConfirmPrintUnclaimedWaveVersion === 'function') {
await waveService.bumpConfirmPrintUnclaimedWaveVersion(warehouseId);
}
} catch (error) {
this.ctx.logger.warn('[print.confirmWavePrint] 统计版本号递增失败', {
warehouseId,
error: error && error.message ? error.message : `${error}`,
});
}
this.ctx.logger.info('[print.confirmWavePrint] 波次确认打印完成 warehouse_id=%d wave_id=%d affected=%d/%d',
warehouseId, orderWaveId, affectedRows, pendingOrderIds.length);
return this.success('ok', {
code: 200,
data: {
...baseResponse,
confirmed_order_count: confirmedOrderIds.length + affectedRows,
newly_confirmed_order_count: affectedRows,
status: 'confirmed',
tip: `波次确认打印完成,本次确认 ${affectedRows} 个订单`,
},
});
} catch (error) {
await transaction.rollback();
this.ctx.logger.error('[print.confirmWavePrint] 波次确认打印失败 warehouse_id=%d wave_id=%d reason=%s',
warehouseId, orderWaveId, error && error.message ? error.message : `${error}`);
return this.fail('确认打印失败', {}, 500);
}
}
/**
* 在打印发送成功后批量锁定订单。
*
* 仅将 print_lock_status=none 的订单更新为 warehouse,避免覆盖既有锁定状态。
*
* @param {Object} payload 锁定参数。
* @param {number|string} payload.warehouseId 仓库ID。
* @param {Array<number|string>} payload.orderIds 订单ID数组。
* @return {Promise<{success:boolean,lockedCount:number,errorMessage:string}>} 锁定结果。
*/
async lockOrderDeliveryAfterPrintSentSuccess(payload = {}) {
const normalizedPayload = payload && typeof payload === 'object' ? payload : {};
const warehouseId = Number(normalizedPayload.warehouseId || 0);
const orderIds = Array.isArray(normalizedPayload.orderIds)
? Array.from(new Set(normalizedPayload.orderIds
.map(orderId => Number(orderId || 0))
.filter(orderId => Number.isInteger(orderId) && orderId > 0)))
: [];
if (!Number.isInteger(warehouseId) || warehouseId <= 0 || orderIds.length === 0) {
return {
success: true,
lockedCount: 0,
errorMessage: '',
};
}
try {
const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory;
if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') {
return {
success: false,
lockedCount: 0,
errorMessage: 'OrderDeliveryFactory 不可用',
};
}
const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(warehouseId);
if (!orderDeliveryModel || typeof orderDeliveryModel.update !== 'function') {
return {
success: false,
lockedCount: 0,
errorMessage: 'OrderDeliveryModel 不可用',
};
}
const updateResult = await orderDeliveryModel.update({
print_lock_status: 'warehouse',
print_status: 'fin',
}, {
where: {
id: orderIds,
intercept_status: 'none',
},
});
const lockedCount = Number(Array.isArray(updateResult) ? updateResult[0] : updateResult) || 0;
return {
success: true,
lockedCount: lockedCount > 0 ? lockedCount : 0,
errorMessage: '',
};
} catch (error) {
return {
success: false,
lockedCount: 0,
errorMessage: error && error.message ? error.message : `${error}`,
};
}
}
/**
* 加载并校验 express 请求涉及平台的打印组件配置。
*
* 解析顺序:
* 1. 直接按 `wms_print_platform.platform_code` 匹配(快递接口透出的打印平台编码,
* 如 CAINIAO/DY/JD/KS/PDD/SPH/XHS);
* 2. 未匹配的编码视为系统平台编码(如 TB/TM/1688/TGC),经
* `wms_platform.code -> print_platform_id -> wms_print_platform.platform_name`
* 回退解析对应打印组件。
*
* @param {Object} payload 查询参数。
* @param {Array<string>} payload.platformCodes 平台编码列表。
* @return {Promise<{success:boolean,data?:Object,error?:string}>} 查询与校验结果。
*/
async loadExpressPlatformComponents(payload = {}) {
const normalizedPayload = payload && typeof payload === 'object' ? payload : {};
const platformCodes = Array.isArray(normalizedPayload.platformCodes)
? normalizedPayload.platformCodes.filter(item => String(item || '').trim())
: [];
if (platformCodes.length === 0) {
return {
success: false,
error: 'type=express 时未识别到有效平台编码',
};
}
const printPlatformModel = this.ctx && this.ctx.model && this.ctx.model.PrintPlatform;
const platformModel = this.ctx && this.ctx.model && this.ctx.model.Platform;
const platformComponentMap = {};
// 1) 优先按打印平台编码直接匹配
if (printPlatformModel && typeof printPlatformModel.findAll === 'function') {
const platformRows = await printPlatformModel.findAll({
attributes: [ 'id', 'platform_code', 'platform_name' ],
where: {
platform_code: platformCodes,
},
raw: true,
});
for (const row of Array.isArray(platformRows) ? platformRows : []) {
const platformCode = String(row && row.platform_code ? row.platform_code : '').trim();
if (!platformCode) {
continue;
}
platformComponentMap[platformCode] = String(row && row.platform_name ? row.platform_name : '').trim();
}
}
// 2) 未匹配编码按系统平台编码回退解析(TB/TM/1688 等经 print_platform_id 关联)
const unresolvedCodes = platformCodes.filter(platformCode => {
return !String(platformComponentMap[platformCode] || '').trim();
});
if (unresolvedCodes.length > 0
&& printPlatformModel && typeof printPlatformModel.findAll === 'function'
&& platformModel && typeof platformModel.findAll === 'function') {
const systemPlatformRows = await platformModel.findAll({
attributes: [ 'code', 'print_platform_id' ],
where: {
code: unresolvedCodes,
},
raw: true,
});
const codeListByPrintPlatformIdMap = new Map();
for (const row of Array.isArray(systemPlatformRows) ? systemPlatformRows : []) {
const platformCode = String(row && row.code ? row.code : '').trim();
const printPlatformId = Number(row && row.print_platform_id || 0);
if (!platformCode || !Number.isInteger(printPlatformId) || printPlatformId <= 0) {
continue;
}
if (!codeListByPrintPlatformIdMap.has(printPlatformId)) {
codeListByPrintPlatformIdMap.set(printPlatformId, []);
}
codeListByPrintPlatformIdMap.get(printPlatformId).push(platformCode);
}
if (codeListByPrintPlatformIdMap.size > 0) {
const printPlatformRows = await printPlatformModel.findAll({
attributes: [ 'id', 'platform_name' ],
where: {
id: Array.from(codeListByPrintPlatformIdMap.keys()),
},
raw: true,
});
const componentNameByPrintPlatformIdMap = new Map();
for (const row of Array.isArray(printPlatformRows) ? printPlatformRows : []) {
const printPlatformId = Number(row && row.id || 0);
const componentName = String(row && row.platform_name ? row.platform_name : '').trim();
if (!Number.isInteger(printPlatformId) || printPlatformId <= 0) {
continue;
}
componentNameByPrintPlatformIdMap.set(printPlatformId, componentName);
}
for (const [ printPlatformId, codeList ] of codeListByPrintPlatformIdMap) {
const componentName = componentNameByPrintPlatformIdMap.get(printPlatformId) || '';
for (const platformCode of codeList) {
platformComponentMap[platformCode] = componentName;
}
}
}
}
for (const platformCode of platformCodes) {
const component = String(platformComponentMap[platformCode] || '').trim();
if (!component) {
return {
success: false,
error: `平台 ${platformCode} 未配置打印组件`,
};
}
}
this.ctx.logger.info('[print.send] express 平台打印组件解析完成', {
platformComponents: platformComponentMap,
});
return {
success: true,
data: platformComponentMap,
};
}
/**
* 校验 express 请求涉及组件是否全部在线。
* @param {Object} payload 校验参数。
* @param {string} payload.computerId 打印电脑 ID。
* @param {Object} payload.platformComponents 平台到组件映射。
* @return {Promise<{success:boolean,error?:string}>} 校验结果。
*/
async validateExpressComponentsOnline(payload = {}) {
const normalizedPayload = payload && typeof payload === 'object' ? payload : {};
const computerId = String(normalizedPayload.computerId || '').trim();
const platformComponents = normalizedPayload.platformComponents && typeof normalizedPayload.platformComponents === 'object'
? normalizedPayload.platformComponents
: {};
if (!computerId) {
return {
success: false,
error: '打印台未配置打印电脑',
};
}
const redisPrinter = this.app.redis.get('printer');
const entries = Object.entries(platformComponents);
for (const entry of entries) {
const platformCode = String(entry[0] || '').trim();
const component = String(entry[1] || '').trim();
const statusKey = `printer:${computerId}:name:${component}:status`;
const componentStatus = await redisPrinter.get(statusKey);
if (componentStatus !== 'connected') {
return {
success: false,
error: `平台 ${platformCode} 打印组件 ${component} 未在线`,
};
}
}
return { success: true };
}
/**
* 根据平台快递编码解析打印机名称。
* @param {Object} payload 解析参数。
* @param {Object} payload.printStation 打印台配置。
* @param {string} payload.sysLogisticsCode 系统快递编码。
* @return {{success:boolean,data?:string,error?:string}} 解析结果。
*/
resolveExpressPrinterName(payload = {}) {
const normalizedPayload = payload && typeof payload === 'object' ? payload : {};
const printStation = normalizedPayload.printStation && typeof normalizedPayload.printStation === 'object'
? normalizedPayload.printStation
: {};
let subjectConfig = printStation.subject_config;
if (typeof subjectConfig === 'string') {
try {
subjectConfig = JSON.parse(subjectConfig);
} catch (error) {
subjectConfig = {};
}
}
if (!subjectConfig || typeof subjectConfig !== 'object' || Array.isArray(subjectConfig)) {
subjectConfig = {};
}
const expressBindPrinter = Array.isArray(subjectConfig.express_bind_printer)
? subjectConfig.express_bind_printer
: [];
const sysLogisticsCode = String(normalizedPayload.sysLogisticsCode || '').trim();
const matchedPrinter = expressBindPrinter.find(item => {
const sourceItem = item && typeof item === 'object' ? item : {};
return String(sourceItem.express_code || '').trim() === sysLogisticsCode;
});
const printerName = String(
matchedPrinter && matchedPrinter.printer_name
? matchedPrinter.printer_name
: (printStation.default_printer_name || '')
).trim();
if (!printerName) {
return {
success: false,
error: '打印台未配置默认打印机',
};
}
this.ctx.logger.info('[print.send] resolveExpressPrinterName 成功', {
sysLogisticsCode,
printerName,
matched: Boolean(matchedPrinter),
matchSource: matchedPrinter ? '命中快递绑定' : '回退默认打印机',
});
return {
success: true,
data: printerName,
};
}
/**
* 串行发送快递打印任务(波次 -> 平台快递组)。
* @param {Object} payload 发送参数。
* @param {number|string} payload.warehouseId 仓库 ID。
* @param {Array<Object>} payload.waveGroups 波次分组。
* @param {string} payload.requestCode 请求参数码。
* @param {Object} payload.printStation 打印台配置。
* @param {Object} payload.payloadBuilder 快递模板组装器。
* @param {Object} payload.idGenerator 本次请求 ID 生成器。
* @param {Object} payload.expressRecordFields 快递打印记录字段。
* @param {Object} payload.platformComponents 平台到打印组件映射。
* @param {string} payload.type 打印类型。
* @param {Object|null} payload.template 模板数据。
* @param {Object} payload.data 业务数据。
* @return {Promise<{success:boolean,error?:string,taskCodes?:Array<string>,printId:number,printIds:Array<number>}>} 发送结果。
*/
async sendExpressWaveGroups(payload = {}) {
const normalizedPayload = payload && typeof payload === 'object' ? payload : {};
const waveGroups = Array.isArray(normalizedPayload.waveGroups)
? normalizedPayload.waveGroups
: [];
const generatedTaskCodes = [];
const createdPrintRecordIds = [];
for (const waveGroup of waveGroups) {
const platforms = Array.isArray(waveGroup && waveGroup.platforms) ? waveGroup.platforms : [];
for (const platformGroup of platforms) {
const orders = Array.isArray(platformGroup && platformGroup.orders) ? platformGroup.orders : [];
if (orders.length === 0) {
continue;
}
const groupSummary = {
waveNo: waveGroup && waveGroup.wave_no ? waveGroup.wave_no : '',
platform: platformGroup && platformGroup.platform ? platformGroup.platform : '',
sysLogisticsCode: platformGroup && platformGroup.sys_logistics_code ? platformGroup.sys_logistics_code : '',
ordersCount: orders.length,
};
const requestCode = String(normalizedPayload.requestCode || '').trim() || null;
const rawWaveId = waveGroup && waveGroup.wave_id;
const normalizedWaveId = rawWaveId === null || rawWaveId === undefined || String(rawWaveId).trim() === ''
? null
: Number(rawWaveId);
const waveId = Number.isFinite(normalizedWaveId)
? normalizedWaveId
: null;
const waveNo = String(waveGroup && waveGroup.wave_no ? waveGroup.wave_no : '').trim() || null;
const platformCodeForRecord = String(platformGroup && platformGroup.platform ? platformGroup.platform : '').trim() || null;
const platformName = String(platformGroup && platformGroup.platform_name ? platformGroup.platform_name : '').trim() || null;
const sysLogisticsCode = String(platformGroup && platformGroup.sys_logistics_code ? platformGroup.sys_logistics_code : '').trim() || null;
const sysLogisticsName = String(platformGroup && platformGroup.sys_logistics_name ? platformGroup.sys_logistics_name : '').trim() || null;
this.ctx.logger.info('[print.send] 平台快递组发送开始', groupSummary);
const platformCode = String(platformGroup && platformGroup.platform ? platformGroup.platform : '').trim();
const component = String(
normalizedPayload.platformComponents
&& normalizedPayload.platformComponents[platformCode]
? normalizedPayload.platformComponents[platformCode]
: ''
).trim();
if (!component) {
this.ctx.logger.error('[print.send] 平台快递组发送失败-打印组件缺失', {
...groupSummary,
reason: `平台 ${platformCode} 未配置打印组件`,
});
this.ctx.logger.error('[print.send] 平台快递组发送结束', {
...groupSummary,
status: 'failure',
reason: `平台 ${platformCode} 未配置打印组件`,
});
return {
success: false,
error: `平台 ${platformCode} 未配置打印组件`,
printId: createdPrintRecordIds[0] || 0,
printIds: createdPrintRecordIds,
};
}
const printerNameResult = this.resolveExpressPrinterName({
printStation: normalizedPayload.printStation,
sysLogisticsCode: platformGroup && platformGroup.sys_logistics_code,
});
if (!printerNameResult.success) {
this.ctx.logger.error('[print.send] 平台快递组发送失败-打印机解析失败', {
...groupSummary,
reason: printerNameResult.error,
});
this.ctx.logger.error('[print.send] 平台快递组发送结束', {
...groupSummary,
status: 'failure',
reason: printerNameResult.error,
});
return {
success: false,
error: printerNameResult.error,
printId: createdPrintRecordIds[0] || 0,
printIds: createdPrintRecordIds,
};
}
const normalizedPlatformCode = this.normalizeExpressPlatformCode({
platformCode: platformGroup && platformGroup.platform ? platformGroup.platform : '',
payloadBuilder: normalizedPayload.payloadBuilder,
});
const isKuaishouPlatform = normalizedPlatformCode === 'kuaishou';
const orderBatches = [];
if (isKuaishouPlatform) {
for (let index = 0; index < orders.length; index += 10) {
orderBatches.push(orders.slice(index, index + 10));
}
} else {
orderBatches.push(orders);
}
const totalDocumentCount = orders.length;
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,
batchIndex: batchIndex + 1,
batchCount: orderBatches.length,
batchOrdersCount: batchOrders.length,
};
let requestPayload;
let currentTaskCode = '';
try {
requestPayload = normalizedPayload.payloadBuilder.buildPayload({
platform: platformGroup && platformGroup.platform,
printerName: printerNameResult.data,
orders: batchOrders,
idGenerator: normalizedPayload.idGenerator,
});
if (isKuaishouPlatform && requestPayload && requestPayload.task && typeof requestPayload.task === 'object' && !Array.isArray(requestPayload.task)) {
requestPayload.task.firstDocumentNumber = batchIndex * 10 + 1;
requestPayload.task.totalDocumentCount = totalDocumentCount;
}
currentTaskCode = await this.reserveUniquePrintTaskCode();
if (requestPayload.task && typeof requestPayload.task === 'object' && !Array.isArray(requestPayload.task)) {
requestPayload.task.taskID = currentTaskCode;
}
if (currentTaskCode && !generatedTaskCodes.includes(currentTaskCode)) {
generatedTaskCodes.push(currentTaskCode);
}
const payloadSummary = this.summarizeExpressPayload(requestPayload);
this.ctx.logger.info('[print.send] 组装 payload 成功', {
...batchSummary,
platform: platformGroup && platformGroup.platform ? platformGroup.platform : '',
ordersCount: batchOrders.length,
documentCount: payloadSummary.documentCount,
});
} catch (error) {
this.ctx.logger.error('[print.send] 组装 payload 失败', {
...batchSummary,
platform: platformGroup && platformGroup.platform ? platformGroup.platform : '',
ordersCount: batchOrders.length,
reason: error && error.message ? error.message : '快递打印任务组装失败',
});
this.ctx.logger.error('[print.send] 平台快递组发送结束', {
...batchSummary,
status: 'failure',
reason: error && error.message ? error.message : '快递打印任务组装失败',
});
return {
success: false,
error: error && error.message ? error.message : '快递打印任务组装失败',
printId: createdPrintRecordIds[0] || 0,
printIds: createdPrintRecordIds,
};
}
let currentPrintRecord;
try {
currentPrintRecord = await this.ctx.model.PrintRecord.create(this.buildPendingPrintRecordPayload({
warehouse_id: normalizedPayload.warehouseId,
computer_id: normalizedPayload.expressRecordFields.computer_id,
printer: currentPrinterName,
type: normalizedPayload.type,
request_code: requestCode,
wave_id: waveId,
wave_no: waveNo,
platform_code: platformCodeForRecord,
platform_name: platformName,
sys_logistics_code: sysLogisticsCode,
sys_logistics_name: sysLogisticsName,
data: {
printer: currentPrinterName,
component,
type: 'express',
order_ids: batchOrderIds,
data: requestPayload,
},
}));
createdPrintRecordIds.push(currentPrintRecord.id);
this.ctx.logger.info('[print.send] PrintRecord 创建成功', {
...batchSummary,
printId: currentPrintRecord.id,
computerId: normalizedPayload.expressRecordFields.computer_id,
printer: currentPrinterName,
});
} catch (error) {
this.ctx.logger.error('[print.send] PrintRecord 创建失败', {
...batchSummary,
computerId: normalizedPayload.expressRecordFields.computer_id,
printer: currentPrinterName,
error: error && error.message ? error.message : `${error}`,
stack: error && error.stack ? error.stack : '',
});
return {
success: false,
error: error && error.message ? error.message : '打印记录创建失败',
printId: createdPrintRecordIds[0] || 0,
printIds: createdPrintRecordIds,
};
}
const printData = {
printer: currentPrinterName,
component,
type: 'express',
order_ids: batchOrderIds,
data: requestPayload,
printId: currentPrintRecord.id,
};
const sendStartAt = Date.now();
let sendResult;
try {
sendResult = await this.service.systems.print.index.sendToComputer({
warehouse: normalizedPayload.warehouseId,
computerId: normalizedPayload.printStation.computer_id,
data: printData,
});
} catch (error) {
const sendDurationMs = Date.now() - sendStartAt;
await this.writePrintOrderOperationLogsByOrderIds({
orderIds: batchOrderIds,
source: 'print.send',
message: `批次发送失败,原因=${error && error.message ? error.message : `${error}`}`,
});
this.ctx.logger.error('[print.send] sendToComputer 调用失败', {
...batchSummary,
printId: currentPrintRecord.id,
computerId: normalizedPayload.printStation.computer_id,
durationMs: sendDurationMs,
reason: error && error.message ? error.message : `${error}`,
});
await currentPrintRecord.update(this.buildSendFailedPrintRecordUpdatePayload({
errorMessage: error && error.message ? error.message : `${error}`,
}));
this.ctx.logger.error('[print.send] 平台快递组发送结束', {
...batchSummary,
printId: currentPrintRecord.id,
computerId: normalizedPayload.printStation.computer_id,
status: 'failure',
reason: error && error.message ? error.message : `${error}`,
});
return {
success: false,
error: error && error.message ? error.message : '打印服务调用失败',
printId: createdPrintRecordIds[0] || 0,
printIds: createdPrintRecordIds,
};
}
const sendDurationMs = Date.now() - sendStartAt;
if (sendResult.status !== 'success') {
await this.writePrintOrderOperationLogsByOrderIds({
orderIds: batchOrderIds,
source: 'print.send',
message: `批次发送失败,原因=${sendResult.error || '打印服务返回失败'}`,
});
this.ctx.logger.error('[print.send] sendToComputer 调用失败', {
...batchSummary,
printId: currentPrintRecord.id,
computerId: normalizedPayload.printStation.computer_id,
durationMs: sendDurationMs,
reason: sendResult.error || '打印服务返回失败',
});
await currentPrintRecord.update(this.buildSendFailedPrintRecordUpdatePayload({
errorMessage: sendResult.error || '打印服务返回失败',
}));
this.ctx.logger.error('[print.send] 平台快递组发送结束', {
...batchSummary,
printId: currentPrintRecord.id,
computerId: normalizedPayload.printStation.computer_id,
status: 'failure',
reason: sendResult.error || '打印服务返回失败',
});
} else {
this.ctx.logger.info('[print.send] sendToComputer 调用成功', {
...batchSummary,
computerId: normalizedPayload.printStation.computer_id,
durationMs: sendDurationMs,
});
}
if (sendResult.status !== 'success') {
return {
success: false,
error: sendResult.error || '打印服务返回失败',
printId: createdPrintRecordIds[0] || 0,
printIds: createdPrintRecordIds,
};
}
const providerTaskId = String(
sendResult && (sendResult.taskId || sendResult.task_id || sendResult.providerTaskId || sendResult.id)
? (sendResult.taskId || sendResult.task_id || sendResult.providerTaskId || sendResult.id)
: ''
).trim();
try {
await this.bindTaskCodeToPrintRecordWithRetry({
printRecordId: currentPrintRecord.id,
taskCode: currentTaskCode,
provider: providerTaskId,
});
} catch (error) {
await this.writePrintOrderOperationLogsByOrderIds({
orderIds: batchOrderIds,
source: 'print.send',
message: `批次发送失败,原因=${error && error.message ? error.message : `${error}`}`,
});
await currentPrintRecord.update(this.buildSendFailedPrintRecordUpdatePayload({
errorMessage: error && error.message ? error.message : `${error}`,
}));
this.ctx.logger.error('[print.send] 平台快递组发送成功但回写失败', {
...batchSummary,
printId: currentPrintRecord.id,
taskCode: currentTaskCode,
providerTaskId,
reason: error && error.message ? error.message : `${error}`,
});
return {
success: false,
error: `打印任务发送成功但回写失败:${error && error.message ? error.message : '未知错误'}`,
printId: createdPrintRecordIds[0] || 0,
printIds: createdPrintRecordIds,
};
}
const lockResult = await this.lockOrderDeliveryAfterPrintSentSuccess({
warehouseId: normalizedPayload.warehouseId,
orderIds: batchOrderIds,
});
if (!lockResult.success) {
this.ctx.logger.error('[print.send] 批次发送成功后锁定订单失败', {
...batchSummary,
warehouseId: normalizedPayload.warehouseId,
orderIdsCount: batchOrderIds.length,
reason: lockResult.errorMessage,
});
}
const orderPrintStatusUpdateResult = await this.updateOrderPrintStatusByCallback({
warehouseId: normalizedPayload.warehouseId,
orderIds: batchOrderIds,
result: 'success',
});
if (!orderPrintStatusUpdateResult.success) {
this.ctx.logger.error('[print.send] 批次发送成功后同步订单主表 print_status 失败', {
...batchSummary,
warehouseId: normalizedPayload.warehouseId,
orderIdsCount: batchOrderIds.length,
reason: orderPrintStatusUpdateResult.errorMessage,
});
}
await this.writePrintOrderOperationLogsByOrderIds({
orderIds: batchOrderIds,
source: 'print.send',
message: `批次发送结束成功,print_id=${currentPrintRecord.id},order_count=${batchOrderIds.length}`,
});
this.ctx.logger.info('[print.send] 平台快递组发送结束', {
...batchSummary,
printId: currentPrintRecord.id,
computerId: normalizedPayload.printStation.computer_id,
status: 'success',
});
}
}
}
return {
success: true,
taskCodes: generatedTaskCodes,
printId: createdPrintRecordIds[0] || 0,
printIds: createdPrintRecordIds,
};
}
/**
* 解析打印回执时间,解析失败时回退当前时间。
* @param {string|Date|number} callbackTime 回执时间。
* @return {Date} 归一化后的打印时间。
*/
parsePrintCallbackTime(callbackTime) {
if (callbackTime instanceof Date && !Number.isNaN(callbackTime.getTime())) {
return callbackTime;
}
if (callbackTime === undefined || callbackTime === null || callbackTime === '') {
return new Date();
}
const parsedDate = new Date(callbackTime);
if (Number.isNaN(parsedDate.getTime())) {
return new Date();
}
return parsedDate;
}
/**
* 处理打印结果回执,按 print_task_code 更新打印记录并保证幂等。
* @param {Object} data 回执参数。
* @param {string} data.print_task_code 打印任务编码。
* @param {string} data.result 回执结果,仅支持 success/failed。
* @param {string} [data.error_message] 失败原因。
* @param {string} [data.fail_code] 失败编码。
* @param {string} [data.printer] 打印机标识。
* @param {string|Date|number} [data.callback_time] 回执时间。
* @return {Promise<Object>} 统一回执处理结果。
*/
async handlePrintCallback(data = {}) {
const requestData = data && typeof data === 'object' ? data : {};
const {
print_task_code: printTaskCode,
result,
error_message: errorMessage,
fail_code: failCode,
printer,
callback_time: callbackTime,
} = requestData;
const normalizedPrintTaskCode = String(printTaskCode || '').trim();
if (!normalizedPrintTaskCode) {
return this.fail('print_task_code 参数不能为空', { code: 400 });
}
const normalizedResult = String(result || '').trim().toLowerCase();
if (![ 'success', 'failed' ].includes(normalizedResult)) {
return this.fail('result 参数不合法,仅支持 success/failed', { code: 400 });
}
const printTaskMap = await this.ctx.model.PrintTaskMap.findOne({
where: {
task_code: normalizedPrintTaskCode,
},
raw: true,
});
if (!printTaskMap || !printTaskMap.print_record_id) {
return this.fail('打印任务映射不存在', {
code: 404,
result: 'not_found',
print_task_code: normalizedPrintTaskCode,
});
}
const printRecordId = Number(printTaskMap.print_record_id || 0);
const printRecord = await this.ctx.model.PrintRecord.findOne({
where: { id: printRecordId },
raw: true,
});
if (!printRecord) {
return this.fail('打印记录不存在', {
code: 404,
result: 'not_found',
print_task_code: normalizedPrintTaskCode,
print_record_id: printRecordId,
});
}
const currentPrintStatus = String(printRecord.print_status || '').trim();
if (normalizedResult === 'success' && currentPrintStatus === 'printed') {
return this.success('打印回执已处理', {
code: 0,
result: 'idempotent',
print_task_code: normalizedPrintTaskCode,
print_record_id: printRecordId,
print_status: 'unknown',
});
}
if (normalizedResult === 'failed' && currentPrintStatus === 'printed') {
return this.success('已打印成功,忽略失败回执', {
code: 0,
result: 'ignored',
print_task_code: normalizedPrintTaskCode,
print_record_id: printRecordId,
print_status: 'unknown',
});
}
const normalizedPrintTime = this.parsePrintCallbackTime(callbackTime);
const orderIds = this.extractOrderIdsFromPrintRecordData(printRecord.data);
const warehouseId = Number(printRecord.warehouse_id || 0);
const updatePayload = normalizedResult === 'success'
? {
status: 'sent',
print_status: 'unknown',
error_message: null,
fail_code: null,
print_time: normalizedPrintTime,
}
: {
print_status: 'print_failed',
error_message: errorMessage ? String(errorMessage) : null,
fail_code: failCode ? String(failCode) : 'PRINT_CALLBACK_FAILED',
print_time: normalizedPrintTime,
};
await this.ctx.model.PrintRecord.update(updatePayload, {
where: { id: printRecordId },
});
const orderPrintStatusUpdateResult = await this.updateOrderPrintStatusByCallback({
warehouseId,
orderIds,
result: normalizedResult,
});
if (!orderPrintStatusUpdateResult.success) {
this.ctx.logger.error('[print.callback] 同步订单主表 print_status 失败', {
printTaskCode: normalizedPrintTaskCode,
printRecordId,
result: normalizedResult,
orderIdsCount: orderIds.length,
reason: orderPrintStatusUpdateResult.errorMessage,
});
}
this.ctx.logger.info('[print.callback] 回执处理完成', {
printTaskCode: normalizedPrintTaskCode,
printRecordId,
result: normalizedResult,
printer: printer ? String(printer) : '',
});
return this.success('打印回执处理成功', {
code: 0,
result: 'updated',
print_task_code: normalizedPrintTaskCode,
print_record_id: printRecordId,
print_status: 'unknown',
});
}
/**
* 查询单条打印结果。
* @param {Object} data 入参。
* @param {number|string} data.printId 打印记录ID。
* @return {Promise<Object>} 查询结果。
*/
async getPrintResult(data) {
const { ctx } = this;
const warehouseId = ctx.user.store_id;
const { printId } = data;
if (!printId) return this.fail('参数错误', 1001);
const record = await ctx.model.PrintRecord.findOne({ where: { id: printId, warehouse_id: warehouseId }, raw: true });
if (!record) return this.fail('打印记录不存在', 1002);
return this.success('success', { ...record, code: 0 });
}
/**
* 查询单条打印记录详情。
* @param {Object} data 入参。
* @param {number|string} data.id 打印记录ID。
* @return {Promise<Object>} 查询结果。
*/
async getPrintRecordItem(data) {
const { ctx } = this;
const warehouseId = ctx.user.store_id;
const { id } = data;
if (!id) return this.fail('参数错误', 1001);
const item = await ctx.model.PrintRecord.findOne({ where: { id, warehouse_id: warehouseId }, raw: true });
if (!item) return this.fail('打印记录不存在', 1002);
return this.success('success', { ...item, code: 0 });
}
/**
* 1. 查询打印台列表
* @param {Object} data { page, pageSize, where }
*/
async getList(data) {
const { ctx } = this;
const warehouse_id = ctx.user.store_id;
const requestData = data && typeof data === 'object' ? data : {};
const { whereValue } = this.prepareWhereContext(requestData);
const { page = 1, pageSize = 20 } = requestData;
// 字段过滤
const filter = {};
[ 'id', 'name', 'computer_id', 'custom_barcode' ].forEach(key => {
const value = whereValue[key];
if (value !== undefined && value !== null && value !== '') filter[key] = value;
});
filter.warehouse_id = warehouse_id;
filter.deleted = 0;
// 查询总数
const total = await ctx.model.PrintStations.count({ where: filter });
// 查询分页数据
const list = await ctx.model.PrintStations.findAll({
where: filter,
offset: (page - 1) * pageSize,
limit: pageSize,
order: [[ 'create_at', 'DESC' ]],
raw: true,
});
const computers = list.map(item => {
const computer = {
id: item.computer_id,
is_online: 0,
components: this.defaultComponents.map(component => ({
name: component.name,
is_online: 0,
})),
};
return computer;
});
// 动态属性处理(如 is_online、components)
for (let i = 0; i < computers.length; i++) {
const key = `warehouse:${warehouse_id}:printer:${computers[i].id}`;
const computerInfo = await this.app.redis.get('printer').get(key);
if (computerInfo) {
computers[i].is_online = 1;
computers[i].components = await Promise.all(computers[i].components.map(async component => {
const componentKey = `printer:${computers[i].id}:name:${component.name}:status`;
const componentInfo = await this.app.redis.get('printer').get(componentKey);
if (componentInfo && componentInfo === 'connected') {
component.is_online = 1;
}
return component;
}));
}
}
for (const item of list) {
const computer = computers.find(c => c.id === item.computer_id);
item.is_online = computer ? computer.is_online : 0;
item.components = computer ? computer.components : this.defaultComponents.map(component => ({
name: component.name,
is_online: 0,
}));
}
const result = {
code: 200,
data: {
list,
pagination: {
hasNext: page * pageSize < total,
hasPrevious: page > 1,
page,
pageSize,
total,
totalPages: Math.ceil(total / pageSize),
},
queryInfo: {
conditions: this.ctx.where || {},
hasBarcodeSearch: false,
sortField: 'id',
sortOrder: 'DESC',
},
summary: {
total_available: total,
total_items: pageSize,
total_locked: 0,
total_quantity: 0,
},
},
};
return this.success('success', result);
}
/**
* 2. 获取单个打印台
* @param {Object} data { id }
* @return {Promise<Object>} 返回打印台详情(不包含 warehouse_id)
*/
async getItem(data) {
const { ctx } = this;
const { id } = data;
if (!id) return this.fail('参数错误', 1001);
const item = await ctx.model.PrintStations.findOne({ where: { id }, raw: true });
if (!item) return this.fail('打印台不存在', 1002);
const rest = { ...item };
delete rest.warehouse_id;
return this.success('success', { ...rest, code: 0 });
}
/**
* 3. 添加打印台
* @param {Object} data { id, name, computer_id, custom_barcode }
* @return {Promise<Object>} 返回新增结果。
*/
async add(data) {
const { ctx } = this;
const warehouse_id = ctx.user.store_id;
const { name, computer_id, custom_barcode, subject_config } = data;
if (!name || !computer_id) return this.fail('参数错误', 1001);
const createPayload = {
warehouse_id,
name,
computer_id,
custom_barcode,
creator_id: ctx.user?.employees_id || '',
creator_name: ctx.user?.employees_name || '',
default_printer_name: data.default_printer_name || '',
create_at: new Date(),
update_at: new Date(),
deleted: 0,
};
if (Object.prototype.hasOwnProperty.call(data, 'subject_config')) {
try {
createPayload.subject_config = ctx.model.PrintStations.normalizeSubjectConfig(subject_config);
} catch (error) {
return this.fail(error.message, 1001);
}
}
const newItem = await ctx.model.PrintStations.create(createPayload);
return this.success('添加打印台成功', { data: newItem, code: 0 });
}
async hasName(data) {
const { ctx } = this;
const warehouse_id = ctx.user.store_id;
const { name, id } = data;
if (!name) return this.fail('参数错误', 1001);
const item = await ctx.model.PrintStations.findOne({ where: { name, warehouse_id, id: { [ctx.model.Sequelize.Op.ne]: id } }, raw: true });
return this.success('success', { exists: !!item, code: 0 });
}
/**
* 3. 修改打印台
* @param {Object} data { id, name, computer_id, custom_barcode }
* @return {Promise<Object>} 返回更新结果。
*/
async updateItem(data) {
const { ctx } = this;
const { id, name, computer_id, custom_barcode, subject_config } = data;
if (!id) return this.fail('参数错误', 1001);
const item = await ctx.model.PrintStations.findOne({ where: { id } });
if (!item) return this.fail('打印台不存在', 1002);
// 只更新允许字段
if (name !== undefined) item.name = name;
if (computer_id !== undefined) item.computer_id = computer_id;
if (custom_barcode !== undefined) item.custom_barcode = custom_barcode;
if (Object.prototype.hasOwnProperty.call(data, 'subject_config')) {
try {
item.subject_config = ctx.model.PrintStations.normalizeSubjectConfig(subject_config);
} catch (error) {
return this.fail(error.message, 1001);
}
}
await item.save();
return this.success('success', { data: null, code: 0 });
}
/**
* 4. 删除打印台
* @param {Object} data { ids }
*/
async del(data) {
const { ctx } = this;
const { ids } = data;
if (!Array.isArray(ids) || ids.length === 0) return this.fail('参数错误', 1001);
// 软删除
await ctx.model.PrintStations.update({ deleted: 1 }, { where: { id: ids } });
// TODO: 检查 result 是否成功
return this.success('success', { data: null, code: 0 });
}
/**
* 5. 获取打印电脑列表
*/
async getComputer() {
const { ctx } = this;
// TODO: 打印电脑状态需根据实际业务实现
const warehouseId = ctx.user.store_id;
const list = await ctx.model.PrintComputer.findAll({ raw: true, where: { status: 1, warehouse_id: warehouseId } });
return this.success('success', { data: list, code: 0 });
}
/**
* 7. 获取打印电脑的所有打印机
* @param {Object} data { id }
*/
async getComputerPrinter(data) {
const { id } = data;
if (!id) return this.fail('参数错误', 1001);
const printerListResult = await this.app.redis.get('printer').get(`printer:${id}:printerList`);
const printerList = JSON.parse(printerListResult);
let printers = [];
if (!printerList || !printerList.data || printerList.data.length === 0) {
printers = [];
} else {
printers = printerList.data;
}
return this.success('success', { data: printers, code: 0 });
}
/**
* 8. 保存打印台的默认打印机与快递绑定打印机配置。
* @param {Object} data 请求参数。
* @param {string} data.defaultPrinter 默认打印机名称,必填。
* @param {Array<Object>} data.express 快递绑定数组,必填。
* @param {number|string} data.print_station_id 打印台 ID,必填。
* @return {Promise<Object>} 保存结果。
*/
async savePrinters(data) {
const { ctx } = this;
const { defaultPrinter, express, print_station_id } = data;
if (!defaultPrinter || !Array.isArray(express) || !print_station_id) return this.fail('参数错误', { code: 1001 });
const item = await ctx.model.PrintStations.findOne({
where: {
id: print_station_id,
deleted: 0,
},
});
if (!item) return this.fail('打印台不存在', { code: 1002 });
const expressBindPrinter = express.map(expressItem => {
const sourceItem = expressItem && typeof expressItem === 'object' ? expressItem : {};
return {
printer_name: sourceItem.printer_name || sourceItem.name || defaultPrinter,
express_code: sourceItem.express_code || sourceItem.express_id,
};
});
const rawSubjectConfig = item.subject_config && typeof item.subject_config === 'object' && !Array.isArray(item.subject_config)
? item.subject_config
: {};
const mergedSubjectConfig = {
...rawSubjectConfig,
express_bind_printer: expressBindPrinter,
};
try {
item.subject_config = ctx.model.PrintStations.normalizeSubjectConfig(mergedSubjectConfig);
} catch (error) {
return this.fail(error.message, { code: 1001 });
}
item.default_printer_name = defaultPrinter;
item.update_at = new Date();
await item.save();
return this.success('success', { data: null, code: 0 });
}
async tryUnbindCartAfterPrintComplete(waveId, warehouseId) {
const { ctx } = this;
const resolvedWarehouseId = Number(warehouseId || ctx.user && ctx.user.store_id || 0);
let taskId = 0;
let waveType = 0;
try {
const waveBatch = await ctx.model.WaveBatch.findOne({ where: { wave_id: waveId }, attributes: [ 'wave_type' ], raw: true });
if (!waveBatch) return;
waveType = Number(waveBatch.wave_type);
if (![ 1, 2 ].includes(waveType)) return;
const taskWaveRows = await ctx.model.query(
'SELECT task_id FROM wms_wave_pick_task_wave WHERE wave_id = :waveId AND warehouse_id = :warehouseId LIMIT 1',
{ replacements: { waveId, warehouseId: resolvedWarehouseId }, type: ctx.model.QueryTypes.SELECT }
);
const taskWave = Array.isArray(taskWaveRows) && taskWaveRows.length > 0 ? taskWaveRows[0] : null;
if (!taskWave || !taskWave.task_id) return;
taskId = Number(taskWave.task_id);
if (!taskId) return;
const orderDeliveryFactory = ctx.model && ctx.model.OrderDeliveryFactory;
if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') {
this.ctx.logger.warn('[print.unbindCart] OrderDeliveryFactory 不可用,跳过检查');
return;
}
const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(resolvedWarehouseId);
// 查询任务主表:团购模式校验、任务结束状态兜底解绑均需要
const taskRows = await ctx.model.query(
'SELECT pick_mode, status FROM wms_wave_pick_task WHERE id = :taskId LIMIT 1',
{ replacements: { taskId }, type: ctx.model.QueryTypes.SELECT }
);
const task = Array.isArray(taskRows) && taskRows.length > 0 ? taskRows[0] : null;
if (!task) return;
const pickMode = Number(task.pick_mode || 0);
const taskStatus = Number(task.status || 0);
// 拦截订单不可打印(打印清单剔除 + 打印回执更新排除拦截订单),print_status 永远停留在 none。
// 解绑判定的「未打印」统计必须排除拦截订单,与打印剔除、复核打印统计口径保持一致,
// 避免波次内存在拦截订单时车永远无法解绑。
const nonInterceptedWhere = { [ctx.model.Sequelize.Op.in]: [ INTERCEPT_STATUS_NONE, null ] };
const unbindCart = async reason => {
const operator = this.getPrintOrderOperationOperator();
const unbindUserId = operator.id || null;
await ctx.model.query(
'UPDATE wms_pick_task_cart_binding SET is_active = 0, unbind_user_id = :unbindUserId, unbind_time = NOW(), update_time = NOW() WHERE task_id = :taskId AND is_active = 1',
{ replacements: { taskId, unbindUserId } }
);
this.ctx.logger.info('[print.unbindCart] 车标解绑成功', { waveId, warehouseId: resolvedWarehouseId, taskId, waveType, waveTypeLabel: waveType === 1 ? '团购' : '散单', reason, unbindUserId });
};
let totalOrderCount = 0;
let unprintedCount = 0;
if (waveType === 1) {
// 团购波次:仅团购拣货模式(pick_mode=1 小团购 / pick_mode=5 大团购)参与解绑判断
if (![ 1, 5 ].includes(pickMode)) return;
// 团购任务订单不写入 wms_wave_pick_task_order,改为按任务关联的全部波次统计:
// 任务下所有波次的非拦截订单均已打印时才解绑
const taskWaveIdRows = await ctx.model.query(
'SELECT DISTINCT wave_id FROM wms_wave_pick_task_wave WHERE task_id = :taskId AND warehouse_id = :warehouseId',
{ replacements: { taskId, warehouseId: resolvedWarehouseId }, type: ctx.model.QueryTypes.SELECT }
);
const waveIds = (Array.isArray(taskWaveIdRows) ? taskWaveIdRows : [])
.map(r => Number(r && r.wave_id))
.filter(id => id > 0);
if (waveIds.length === 0) {
// 任务无波次关联:仅任务已结束(待复核/完成/取消)时兜底解绑,避免车残留
if ([ 2, 3, 9 ].includes(taskStatus)) await unbindCart('task_no_wave_ended');
return;
}
unprintedCount = await orderDeliveryModel.count({
where: {
warehouse_id: resolvedWarehouseId,
wave_id: { [ctx.model.Sequelize.Op.in]: waveIds },
print_status: 'none',
intercept_status: nonInterceptedWhere,
},
});
totalOrderCount = await orderDeliveryModel.count({
where: {
warehouse_id: resolvedWarehouseId,
wave_id: { [ctx.model.Sequelize.Op.in]: waveIds },
intercept_status: nonInterceptedWhere,
},
});
} else {
// 散单波次:按任务订单维度检查,任务下所有非拦截订单均已打印时才解绑
const taskOrders = await ctx.model.query(
'SELECT DISTINCT order_id FROM wms_wave_pick_task_order WHERE task_id = :taskId',
{ replacements: { taskId }, type: ctx.model.QueryTypes.SELECT }
);
const orderIds = (Array.isArray(taskOrders) ? taskOrders : []).map(r => Number(r && r.order_id)).filter(id => id > 0);
if (orderIds.length === 0) {
// 任务订单关联为空(如拦截订单被提交拣货移除):任务已结束时兜底解绑,避免车残留
if ([ 2, 3, 9 ].includes(taskStatus)) await unbindCart('task_no_orders_ended');
return;
}
unprintedCount = await orderDeliveryModel.count({
where: {
id: { [ctx.model.Sequelize.Op.in]: orderIds },
print_status: 'none',
intercept_status: nonInterceptedWhere,
},
});
totalOrderCount = await orderDeliveryModel.count({
where: {
id: { [ctx.model.Sequelize.Op.in]: orderIds },
intercept_status: nonInterceptedWhere,
},
});
}
if (unprintedCount > 0) {
this.ctx.logger.info('[print.unbindCart] 尚有未打印订单,跳过解绑', { waveId, warehouseId, taskId, waveType, waveTypeLabel: waveType === 1 ? '团购' : '散单', totalOrders: totalOrderCount, unprintedCount });
return;
}
await unbindCart('all_printed');
} catch (error) {
this.ctx.logger.error('[print.unbindCart] 解绑车标检查异常', { waveId, warehouseId: resolvedWarehouseId, taskId, waveType, error: error && error.message ? error.message : String(error) });
}
}
}
module.exports = PrintService;