'use strict'; /** * 打印数据中间态组装器。 * * 入参说明(buildPlatformRequestSkeleton): * - input.platform: 平台标识,支持 cainiao、douyin、jd、kuaishou、pdd、sph、xhs 及其常见别名。 * - input.order_express: 订单快递对象(建议来自 wms_order_express)。 * - input.order_delivery: 订单对象(建议来自 wms_order_delivery_xxxxxx 分表模型查询结果)。 * - input.store_contract / input.policy_config: 货主-仓库签约配置,至少应包含 policy_config。 * - input.template_sample: 平台模板样例对象(建议读取 printer_data_template/*.json 后传入)。 * - input.options: 可选配置,如 requestId/taskId/documentId/printer/preview。 * * 出参说明: * - platform: 归一化后的平台编码。 * - platform_meta: 平台映射元信息(名称、别名、模板文件名等)。 * - base_data: 通用打印基础数据(sender/receiver/items/channel/template)。 * - request_skeleton: 平台请求骨架(中间态,不直接可发)。 * - missing_fields: 缺失字段列表(按 path 标注)。 * - warnings: 风险与提示信息列表。 * * 哪些信息“足够”: * - 收发件人基础字段、订单商品、运单号、平台编码、模板 URL(若样例里存在)通常足够构建中间态骨架。 * * 哪些信息“不足”: * - encryptedData / signature / sign / encryptedtoken / encryptprintinfo 等平台私有密文或签名字段, * 无法仅靠订单与模板样例安全生成,必须由上游平台适配器(持有密钥/签名算法)补齐。 */ /** * 平台硬编码映射。 * @type {Object} */ const PLATFORM_MAP = Object.freeze({ cainiao: Object.freeze({ name: '菜鸟', aliases: [ 'cn', 'cainiao', 'taobao', 'tb' ], template_file: 'cainiao.json', }), douyin: Object.freeze({ name: '抖音', aliases: [ 'douyin', 'dy', 'tiktok' ], template_file: 'douyin.json', }), jd: Object.freeze({ name: '京东', aliases: [ 'jd', 'jingdong' ], template_file: 'jd.json', }), kuaishou: Object.freeze({ name: '快手', aliases: [ 'kuaishou', 'ks' ], template_file: 'kuaishou.json', }), pdd: Object.freeze({ name: '拼多多', aliases: [ 'pdd', 'pinduoduo' ], template_file: 'pdd.json', }), sph: Object.freeze({ name: '视频号', aliases: [ 'sph', 'shipinhao', 'wechatvideo' ], template_file: 'sph.json', }), xhs: Object.freeze({ name: '小红书', aliases: [ 'xhs', 'xiaohongshu', 'red' ], template_file: 'xhs.json', }), }); const PRIVATE_PAYLOAD_FIELDS = Object.freeze([ 'encryptedData', 'signature', 'sign', 'encryptedtoken', 'encryptprintinfo', ]); /** * 换行符映射,供不同平台分支复用。 * @type {Object} */ const LINE_BREAK_MAP = Object.freeze({ LF: '\n', CR: '\r', CRLF: '\r\n', }); /** * 拼多多自定义区默认模板地址。 * @type {string} */ const DEFAULT_PDD_CUSTOM_TEMPLATE_URL = 'http://www.ye4s.com/mb/pdd.xml'; const WAYBILL_CUSTOM_DISPLAY_FIELD = 'waybill_custom_display_type'; const WAYBILL_CUSTOM_DISPLAY_TYPES = Object.freeze({ HIDE: '1', ITEM_NAME_QTY: '2', PICK_LOCATION_BARCODE_QTY: '3', PICK_LOCATION_BARCODE_LAST5_QTY: '4', PICK_LOCATION_NAME_BARCODE_QTY: '5', }); const ARRAY_STYLE_KEYS = new Set([ 'documents', 'taskList', 'contents', ]); const TEMPLATE_LEAF_KEEP_KEYS = Object.freeze(new Set([ 'cmd', 'command', 'orderType', 'requestID', 'requetID', 'version', 'taskID', 'documentID', 'printer', 'preview', 'templateURL', 'templateUrl', 'tempUrl', 'customTempUrl', 'templateId', 'templateID', 'key', 'ERPId', 'userid', 'userId', 'ver', 'printType', ])); /** * 判断值是否为普通对象。 * @param {any} value 待判断值。 * @return {boolean} 是否普通对象。 */ function isPlainObject(value) { return Object.prototype.toString.call(value) === '[object Object]'; } /** * 统一换行符表示。 * * @param {any} value 原始值。 * @param {string} [lineBreak=LINE_BREAK_MAP.LF] 目标换行符。 * @return {string} 规范化后的字符串。 */ function normalizeLineBreak(value, lineBreak = LINE_BREAK_MAP.LF) { const text = String(value === undefined || value === null ? '' : value); if (lineBreak === LINE_BREAK_MAP.CRLF) { return text.replace(/\r\n|\r|\n/g, LINE_BREAK_MAP.CRLF); } if (lineBreak === LINE_BREAK_MAP.CR) { return text.replace(/\r\n|\r|\n/g, LINE_BREAK_MAP.CR); } return text.replace(/\r\n|\r/g, LINE_BREAK_MAP.LF); } /** * 安全转换字符串并去空白。 * @param {any} value 原始值。 * @return {string} 转换后的字符串。 */ function toTrimmedString(value) { return normalizeLineBreak(value).trim(); } /** * 安全转换数值。 * @param {any} value 原始值。 * @param {number} fallback 默认值。 * @return {number} 转换后的数值。 */ function toNumber(value, fallback = 0) { const parsed = Number(value); return Number.isFinite(parsed) ? parsed : fallback; } /** * 规范化平台别名。 * @param {string} inputPlatform 入参平台。 * @return {{platform: string, meta: Object|null, raw: string}} 规范化结果。 */ function normalizePlatformAlias(inputPlatform) { const raw = toTrimmedString(inputPlatform).toLowerCase(); if (!raw) { return { platform: '', meta: null, raw }; } for (const platform of Object.keys(PLATFORM_MAP)) { const meta = PLATFORM_MAP[platform]; if (platform === raw || meta.aliases.includes(raw)) { return { platform, meta, raw }; } } return { platform: raw, meta: null, raw }; } /** * 解析订单商品数据。 * @param {any} rawItems 原始 items 字段(字符串或数组)。 * @return {Array} 商品列表。 */ function parseItems(rawItems) { if (Array.isArray(rawItems)) { return rawItems; } if (isPlainObject(rawItems)) { for (const key of Object.keys(rawItems)) { if (Array.isArray(rawItems[key])) { return rawItems[key]; } } const candidates = [ rawItems.items, rawItems.list, rawItems.goods, rawItems.products, rawItems.product_list, rawItems.rows, ]; for (const candidate of candidates) { if (Array.isArray(candidate)) { return candidate; } } return []; } if (typeof rawItems === 'string') { const text = rawItems.trim(); if (!text) { return []; } try { const parsed = JSON.parse(text); return parseItems(parsed); } catch (error) { function isNoiseQuantityOnlyText(value) { const sample = String(value || '').trim(); if (!sample) { return true; } return /^(?:\[?\s*\d+(?:\.\d+)?\s*\]?|【\s*\d+(?:\.\d+)?\s*】)(?:\s+0+)?$/.test(sample); } function parseLooseItemText(rawText) { const normalizedText = String(rawText || '').replace(/[;;]+$/g, '').trim(); if (!normalizedText || isNoiseQuantityOnlyText(normalizedText)) { return null; } let quantity = '1'; let workingText = normalizedText; const qtyBracketMatch = workingText.match(/【\s*(\d+(?:\.\d+)?)\s*】/); if (qtyBracketMatch) { quantity = String(qtyBracketMatch[1] || '1').trim() || '1'; workingText = workingText.replace(qtyBracketMatch[0], ' ').trim(); } else { const qtyTailMatch = workingText.match(/(?:[xX×*]\s*(\d+(?:\.\d+)?))\s*$/); if (qtyTailMatch) { quantity = String(qtyTailMatch[1] || '1').trim() || '1'; workingText = workingText.slice(0, qtyTailMatch.index).trim(); } } const barcodeMatch = workingText.match(/(?:^|[;;\s])(\d{5,})(?!\d)/); const barcode = barcodeMatch ? String(barcodeMatch[1] || '').trim() : ''; let pickLocation = ''; let itemName = workingText; const locationMatch = workingText.match(/^([^\s;;]+(?:[-_][^\s;;]+)*)\s+/); if (locationMatch) { pickLocation = String(locationMatch[1] || '').trim(); itemName = workingText.slice(locationMatch[0].length).trim(); } if (barcode) { itemName = itemName.replace(new RegExp(`(?:^|[;;\\s])${barcode}(?:$|[;;\\s])`), ' ').trim(); } itemName = itemName.replace(/[;;]+/g, ' ').trim(); if (isNoiseQuantityOnlyText(itemName)) { itemName = ''; } return { pick_location: pickLocation, item_name: itemName || workingText, barcode, quantity, raw_text: normalizedText, }; } const itemTextList = text .split(/\||\r\n|\n|\r/) .map(part => String(part || '').trim()) .filter(Boolean); if (itemTextList.length === 0) { return []; } const parsedItems = itemTextList .map(itemText => parseLooseItemText(itemText)) .filter(item => isPlainObject(item)); return parsedItems; } } return []; } /** * 解析自定义区商品来源,优先兼容 order_delivery 与 order_express 双来源。 * @param {Object} orderExpress 快递单对象。 * @param {Object} orderDelivery 订单对象。 * @return {Array} 商品列表。 */ function resolveCustomComposeItems(orderExpress, orderDelivery) { const safeOrderExpress = isPlainObject(orderExpress) ? orderExpress : {}; const safeOrderDelivery = isPlainObject(orderDelivery) ? orderDelivery : {}; const deliveryItems = parseItems(safeOrderDelivery.items); if (deliveryItems.length > 0) { return deliveryItems; } return parseItems(safeOrderExpress.items); } /** * 在候选键中读取首个非空字段。 * @param {Object} item 商品对象。 * @param {Array} keyList 候选键列表。 * @return {string} 文本值。 */ function getFirstNonEmptyText(item, keyList = []) { if (!isPlainObject(item)) { return ''; } for (const key of keyList) { const value = item[key]; if (value === undefined || value === null) { continue; } const text = String(value).trim(); if (text) { return text; } } return ''; } /** * 读取条码文本,支持数组与多种命名。 * @param {Object} item 商品对象。 * @return {string} 条码文本。 */ function resolveItemBarcodeText(item) { if (!isPlainObject(item)) { return ''; } const barcodeList = []; const arrayBarcodes = [ item.barcodes, item.barcode_list ]; for (const barcodes of arrayBarcodes) { if (!Array.isArray(barcodes)) { continue; } for (const code of barcodes) { const codeText = String(code === undefined || code === null ? '' : code).trim(); if (codeText) { barcodeList.push(codeText); } } } if (barcodeList.length > 0) { return barcodeList.join(';'); } return getFirstNonEmptyText(item, [ 'barcode', 'bar_code', 'item_barcode', 'item_code', 'sku_code', 'sku', ]); } /** * 读取数量文本。 * @param {Object} item 商品对象。 * @return {{qtyText: string, qtyNumber: number}} 数量文本与数值。 */ function resolveItemQuantity(item) { if (!isPlainObject(item)) { return { qtyText: '0', qtyNumber: 0 }; } const qtyKeyList = [ 'quantity', 'qty', 'num', 'plan_qty', 'actual_quantity', 'buy_amount', ]; for (const key of qtyKeyList) { if (!Object.prototype.hasOwnProperty.call(item, key)) { continue; } const rawValue = item[key]; const qtyText = String(rawValue === undefined || rawValue === null ? '' : rawValue).trim(); if (!qtyText) { continue; } const qtyNumber = Number(qtyText); return { qtyText, qtyNumber: Number.isFinite(qtyNumber) ? qtyNumber : 0, }; } return { qtyText: '0', qtyNumber: 0 }; } /** * 根据货主配置构建面单自定义区商品信息。 * @param {Array} items 商品列表。 * @param {Object} policyConfig 策略配置。 * @param {string} lineBreak 换行符。 * @return {string} 自定义区文本。 */ function buildWaybillCustomProductInfoLines(items, policyConfig = {}, options = {}) { const safeItems = Array.isArray(items) ? items : []; const safePolicyConfig = isPlainObject(policyConfig) ? policyConfig : {}; const safeOptions = isPlainObject(options) ? options : {}; const hasDisplayType = Object.prototype.hasOwnProperty.call(safePolicyConfig, WAYBILL_CUSTOM_DISPLAY_FIELD); const displayType = hasDisplayType ? String(safePolicyConfig[WAYBILL_CUSTOM_DISPLAY_FIELD] || '').trim() : WAYBILL_CUSTOM_DISPLAY_TYPES.PICK_LOCATION_NAME_BARCODE_QTY; if (displayType === WAYBILL_CUSTOM_DISPLAY_TYPES.HIDE) { return []; } const detailLines = []; let totalQty = 0; for (const item of safeItems) { if (!isPlainObject(item)) { continue; } const itemName = getFirstNonEmptyText(item, [ 'item_name', 'product_name', 'name', 'title' ]); const pickLocation = getFirstNonEmptyText(item, [ 'pick_location', 'pick_location_code', 'location_code', 'space_code', 'bin_code', 'storage_code', ]); const barcode = resolveItemBarcodeText(item); const { qtyText, qtyNumber } = resolveItemQuantity(item); totalQty += qtyNumber; let line = ''; switch (displayType) { case WAYBILL_CUSTOM_DISPLAY_TYPES.ITEM_NAME_QTY: line = `${itemName} 【${qtyText}】`.trim(); break; case WAYBILL_CUSTOM_DISPLAY_TYPES.PICK_LOCATION_BARCODE_QTY: line = `${pickLocation} ${barcode} 【${qtyText}】`.trim(); break; case WAYBILL_CUSTOM_DISPLAY_TYPES.PICK_LOCATION_BARCODE_LAST5_QTY: { const barcodeLast5 = barcode ? barcode.slice(-5) : ''; if (!pickLocation && !barcodeLast5) { line = ''; break; } line = `${pickLocation} ${barcodeLast5} 【${qtyText}】`.trim(); break; } case WAYBILL_CUSTOM_DISPLAY_TYPES.PICK_LOCATION_NAME_BARCODE_QTY: line = `${pickLocation} ${itemName} ${barcode} 【${qtyText}】`.trim(); break; default: line = ''; break; } if (line) { detailLines.push(line.replace(/\s{2,}/g, ' ')); } } const waveNo = String(safeOptions.waveNo || '').trim(); const waveTotalOrders = toNumber(safeOptions.wave_total_orders, 0); const waveIndex = toNumber(safeOptions.wave_index, 0); const platformsIndex = toNumber(safeOptions.platforms_index, 0); const expressInterfaceName = String(safeOptions.expressInterfaceName || '').trim(); const fallbackTotalQtyRaw = Number(safeOptions.fallbackTotalQty); const finalTotalQty = totalQty > 0 ? totalQty : (Number.isFinite(fallbackTotalQtyRaw) && fallbackTotalQtyRaw > 0 ? fallbackTotalQtyRaw : 0); const hasWaveCustomPrefix = waveTotalOrders > 0 && waveIndex > 0 && platformsIndex > 0 && Boolean(waveNo); const waveHeaderText = hasWaveCustomPrefix ? `【${waveTotalOrders}】${waveNo}_${waveIndex}_${platformsIndex}` : waveNo; const headerParts = [ waveHeaderText, expressInterfaceName ].filter(Boolean); headerParts.push(`商品数量【${finalTotalQty}】`); const headerLine = headerParts.join(' '); if (detailLines.length === 0) { return [ headerLine ]; } return [ headerLine, ...detailLines ]; } /** * 将自定义文本行按平台换行符合并为字符串。 * @param {Array} lines 文本行数组。 * @param {Object} options 合并选项。 * @param {string} [options.lineBreak=LINE_BREAK_MAP.LF] 换行符。 * @param {boolean} [options.trailingLineBreak=false] 是否追加末尾换行。 * @return {string} 合并后的文本。 */ function mergeWaybillCustomLines(lines = [], options = {}) { const safeLines = Array.isArray(lines) ? lines.filter(line => String(line || '').trim() !== '') : []; if (safeLines.length === 0) { return ''; } const safeOptions = isPlainObject(options) ? options : {}; const lineBreak = safeOptions.lineBreak || LINE_BREAK_MAP.LF; const trailingLineBreak = Boolean(safeOptions.trailingLineBreak); let text = normalizeLineBreak(safeLines.join(LINE_BREAK_MAP.LF), lineBreak); if (trailingLineBreak) { text += lineBreak; } return text; } /** * 构建数组字段的精简骨架。 * * @param {any} value 原始字段值。 * @param {string[]} warnings 警告列表。 * @param {string} currentKey 当前字段名。 * @return {Array<*>} 数组骨架。 */ function buildArraySkeleton(value, warnings, currentKey) { if (Array.isArray(value)) { if (!value.length) { return []; } return [ sanitizeTemplatePrivateFields(value[0], warnings, currentKey) ]; } if (value === undefined || value === null) { return []; } return [ sanitizeTemplatePrivateFields(value, warnings, currentKey) ]; } /** * 从快手模板样例中提取自定义区默认模板地址。 * * 优先扫描 template_sample.task.documents,其次扫描 template_sample.documents 和 template_sample.taskList, * 找到第一个同时包含 customData 与 templateURL 的内容对象后返回其 templateURL。 * * @param {Object} templateSample 模板样例对象。 * @return {string} 默认模板地址。 */ function resolveKuaishouCustomDataTemplateURL(templateSample) { const sample = isPlainObject(templateSample) ? templateSample : {}; const documentGroups = [ sample.task && sample.task.documents, sample.documents, sample.taskList, ]; for (const documents of documentGroups) { if (!Array.isArray(documents) || documents.length === 0) { continue; } for (const document of documents) { if (!isPlainObject(document) || !Array.isArray(document.contents)) { continue; } for (const content of document.contents) { if (!isPlainObject(content) || !isPlainObject(content.customData)) { continue; } if (Object.prototype.hasOwnProperty.call(content, 'templateURL')) { return toTrimmedString(content.templateURL); } } } } return ''; } /** * 归一化签约策略配置。 * @param {Object} input 入参对象。 * @return {Object} 统一 policy_config 对象。 */ function resolvePolicyConfig(input) { if (isPlainObject(input.policy_config)) { return input.policy_config; } if (isPlainObject(input.store_contract) && isPlainObject(input.store_contract.policy_config)) { return input.store_contract.policy_config; } return {}; } /** * 构建基础数据中间态。 * @param {Object} input 输入对象。 * @param {string} platform 归一化平台。 * @param {Object|null} platformMeta 平台元信息。 * @return {{base_data: Object, missing_fields: Array, warnings: string[]}} 组装结果。 */ function buildBaseData(input, platform, platformMeta) { const orderExpress = isPlainObject(input.order_express) ? input.order_express : {}; const orderDelivery = isPlainObject(input.order_delivery) ? input.order_delivery : {}; const policyConfig = resolvePolicyConfig(input); const templateSample = isPlainObject(input.template_sample) ? input.template_sample : {}; const sender = { name: toTrimmedString(policyConfig.sender_name), tel: toTrimmedString(policyConfig.sender_tel), province: toTrimmedString(policyConfig.province_name), city: toTrimmedString(policyConfig.city_name), district: toTrimmedString(policyConfig.district_name), town: toTrimmedString(policyConfig.town_name), address: toTrimmedString(policyConfig.address), }; const receiver = { name: toTrimmedString(orderDelivery.name), mobile: toTrimmedString(orderDelivery.mobile), tel: toTrimmedString(orderDelivery.tel), province: toTrimmedString(orderDelivery.province), city: toTrimmedString(orderDelivery.city), district: toTrimmedString(orderDelivery.area), town: toTrimmedString(orderDelivery.town), address: toTrimmedString(orderDelivery.detail_address), zip_code: toTrimmedString(orderDelivery.zip_code), }; const items = parseItems(orderDelivery.items); const channel = { platform, source_platform_code: toTrimmedString(orderDelivery.source_platform_code || orderExpress.platform_code), sys_platform_code: toTrimmedString(orderDelivery.sys_platform_code), logistics_code: toTrimmedString(orderExpress.logistics_code || orderDelivery.logistics_code), logistics_name: toTrimmedString(orderExpress.logistics_name || orderDelivery.logistics_name), waybill_code: toTrimmedString(orderExpress.waybill_code), business_key: toNumber(orderExpress.business_key, 0), }; const template = { file: platformMeta ? platformMeta.template_file : '', cmd: toTrimmedString(templateSample.cmd), version: toTrimmedString(templateSample.version), request_id: toTrimmedString(templateSample.requetID || templateSample.requestID), }; const missingFields = []; const warnings = []; const requiredChecks = [ { path: 'sender.name', value: sender.name, reason: '缺少发件人姓名(policy_config.sender_name)' }, { path: 'sender.tel', value: sender.tel, reason: '缺少发件人电话(policy_config.sender_tel)' }, { path: 'sender.address', value: sender.address, reason: '缺少发件详细地址(policy_config.address)' }, { path: 'receiver.name', value: receiver.name, reason: '缺少收件人姓名(order_delivery.name)' }, { path: 'receiver.mobile|tel', value: receiver.mobile || receiver.tel, reason: '缺少收件联系方式(order_delivery.mobile/tel)' }, { path: 'receiver.address', value: receiver.address, reason: '缺少收件详细地址(order_delivery.detail_address)' }, { path: 'channel.waybill_code', value: channel.waybill_code, reason: '缺少运单号(order_express.waybill_code)' }, ]; for (const check of requiredChecks) { if (!check.value) { missingFields.push({ path: check.path, reason: check.reason }); } } if (!items.length) { warnings.push('order_delivery.items 为空或解析失败,已输出空商品列表'); } if (!platformMeta) { warnings.push(`平台 ${platform || '(empty)'} 未命中硬编码映射,已按原值输出`); } return { base_data: { sender, receiver, items, channel, template, }, missing_fields: missingFields, warnings, }; } /** * 清洗模板样例,保留结构并裁切样例噪声。 * @param {any} value 原始对象。 * @param {string[]} warnings 警告列表。 * @return {any} 清洗后的对象。 */ function sanitizeTemplatePrivateFields(value, warnings, currentKey = '') { if (Array.isArray(value)) { if (ARRAY_STYLE_KEYS.has(currentKey)) { return buildArraySkeleton(value, warnings, currentKey); } return value.map(item => sanitizeTemplatePrivateFields(item, warnings, currentKey)); } if (!isPlainObject(value)) { if (ARRAY_STYLE_KEYS.has(currentKey)) { return buildArraySkeleton(value, warnings, currentKey); } if (TEMPLATE_LEAF_KEEP_KEYS.has(currentKey)) { if (typeof value === 'string') { return toTrimmedString(value); } return value; } if (typeof value === 'string') { const text = toTrimmedString(value); return text ? '__SAMPLE__' : ''; } if (typeof value === 'number') { return Number.isFinite(value) ? 0 : value; } if (typeof value === 'boolean') { return value; } return value; } const result = {}; for (const key of Object.keys(value)) { const current = value[key]; if (PRIVATE_PAYLOAD_FIELDS.includes(key)) { result[key] = '__UPSTREAM_REQUIRED__'; warnings.push(`模板字段 ${key} 为平台私有密文字段,已替换为占位符`); continue; } result[key] = sanitizeTemplatePrivateFields(current, warnings, key); } return result; } /** * 快手平台密文字段回填。 * * 规则: * - wms_order_express.printinfo -> encryptedData * - wms_order_express.signature -> signature * - wms_order_express.encryptprintinfo -> key * * 仅在平台为 kuaishou 时生效,避免影响其他平台。 * * @param {string} platform 归一化平台编码。 * @param {Object} skeleton 打印请求骨架。 * @param {Object} orderExpress 快递单对象。 * @param {string[]} warnings 风险提示列表。 * @param {Object} policyConfig 策略配置对象。 * @param {string} customDataTemplateURL 自定义区模板地址默认值。 */ function applyKuaishouExpressFieldMapping(platform, skeleton, orderExpress, orderDelivery, warnings, policyConfig, customDataTemplateURL) { if (platform !== 'kuaishou') { return; } const safeSkeleton = isPlainObject(skeleton) ? skeleton : {}; const safeOrderExpress = isPlainObject(orderExpress) ? orderExpress : {}; const safePolicyConfig = isPlainObject(policyConfig) ? policyConfig : {}; const documents = safeSkeleton.task && Array.isArray(safeSkeleton.task.documents) ? safeSkeleton.task.documents : []; if (documents.length === 0) { return; } const encryptedData = toTrimmedString(safeOrderExpress.printinfo); const signature = toTrimmedString(safeOrderExpress.signature); const key = toTrimmedString(safeOrderExpress.encryptprintinfo); const waybillCode = toTrimmedString(safeOrderExpress.waybill_code); const safeOrderDelivery = isPlainObject(orderDelivery) ? orderDelivery : {}; const composeItems = resolveCustomComposeItems(safeOrderExpress, safeOrderDelivery); const customProductInfoLines = buildWaybillCustomProductInfoLines( composeItems, safePolicyConfig, { waveNo: toTrimmedString(safeOrderDelivery.wave_no), wave_total_orders: Number(safeOrderDelivery.wave_total_orders || 0), wave_index: Number(safeOrderDelivery.wave_index || 0), platforms_index: Number(safeOrderDelivery.platforms_index || 0), expressInterfaceName: toTrimmedString( safeOrderExpress.logistics_interface_name || safeOrderExpress.logistics_name || safeOrderDelivery.logistics_interface_name || safeOrderDelivery.logistics_name ), fallbackTotalQty: Number(safeOrderDelivery.items_count || safeOrderDelivery.items_total || 0), } ); const customProductInfo = mergeWaybillCustomLines(customProductInfoLines, { lineBreak: LINE_BREAK_MAP.LF, }); for (const document of documents) { if (!isPlainObject(document)) { continue; } if (waybillCode) { document.documentID = waybillCode; document.waybillCode = waybillCode; } if (!Array.isArray(document.contents)) { document.contents = []; } const contents = document.contents; for (const content of contents) { if (!isPlainObject(content)) { continue; } // 快手发件信息回填,确保对象结构存在后再覆盖策略字段。 content.addData = isPlainObject(content.addData) ? content.addData : {}; content.addData.senderInfo = isPlainObject(content.addData.senderInfo) ? content.addData.senderInfo : {}; content.addData.senderInfo.address = isPlainObject(content.addData.senderInfo.address) ? content.addData.senderInfo.address : {}; content.addData.senderInfo.contact = isPlainObject(content.addData.senderInfo.contact) ? content.addData.senderInfo.contact : {}; content.addData.senderInfo.address.provinceName = toTrimmedString(safePolicyConfig.province_name); content.addData.senderInfo.address.cityName = toTrimmedString(safePolicyConfig.city_name); content.addData.senderInfo.address.districtName = toTrimmedString(safePolicyConfig.district_name); content.addData.senderInfo.address.detailAddress = toTrimmedString(safePolicyConfig.address); content.addData.senderInfo.address.countryCode = 'CHN'; content.addData.senderInfo.contact.name = toTrimmedString(safePolicyConfig.sender_name); content.addData.senderInfo.contact.mobile = toTrimmedString(safePolicyConfig.sender_tel); const hasKuaishouEncryptedPayloadField = ( Object.prototype.hasOwnProperty.call(content, 'encryptedData') || Object.prototype.hasOwnProperty.call(content, 'signature') || Object.prototype.hasOwnProperty.call(content, 'key') ); if (!hasKuaishouEncryptedPayloadField) { continue; } content.encryptedData = encryptedData || '__UPSTREAM_REQUIRED__'; content.signature = signature || '__UPSTREAM_REQUIRED__'; content.key = key || '__UPSTREAM_REQUIRED__'; } const customDataContent = contents.find(content => { return isPlainObject(content) && isPlainObject(content.customData); }); if (customDataContent) { if (!Object.prototype.hasOwnProperty.call(customDataContent, 'templateURL')) { customDataContent.templateURL = customDataTemplateURL || ''; } customDataContent.customData.productInfo = customProductInfo; } else { contents.push({ templateURL: customDataTemplateURL || '', customData: { productInfo: customProductInfo, }, }); } } if (!encryptedData) { warnings.push('快手模板字段 encryptedData 缺失映射源(order_express.printinfo)'); } if (!signature) { warnings.push('快手模板字段 signature 缺失映射源(order_express.signature)'); } if (!key) { warnings.push('快手模板字段 key 缺失映射源(order_express.encryptprintinfo)'); } } /** * 拼多多平台密文字段回填。 * * 规则: * - wms_order_express.printinfo -> encryptedData * - wms_order_express.signature -> signature * - policy_config 面单发货信息 -> content.addData.sender * * 仅在平台为 pdd 时生效,避免影响其他平台。 * * @param {string} platform 归一化平台编码。 * @param {Object} skeleton 打印请求骨架。 * @param {Object} orderExpress 快递单对象。 * @param {Object} policyConfig 策略配置对象。 */ function applyPddExpressFieldMapping(platform, skeleton, orderExpress, orderDelivery, policyConfig) { if (platform !== 'pdd') { return; } const safeSkeleton = isPlainObject(skeleton) ? skeleton : {}; const safeOrderExpress = isPlainObject(orderExpress) ? orderExpress : {}; const safePolicyConfig = isPlainObject(policyConfig) ? policyConfig : {}; const documents = safeSkeleton.task && Array.isArray(safeSkeleton.task.documents) ? safeSkeleton.task.documents : []; if (documents.length === 0) { return; } const encryptedData = toTrimmedString(safeOrderExpress.printinfo); const signature = toTrimmedString(safeOrderExpress.signature); const waybillCode = toTrimmedString(safeOrderExpress.waybill_code); const safeOrderDelivery = isPlainObject(orderDelivery) ? orderDelivery : {}; const composeItems = resolveCustomComposeItems(safeOrderExpress, safeOrderDelivery); const customProductInfoLines = buildWaybillCustomProductInfoLines( composeItems, safePolicyConfig, { waveNo: toTrimmedString(safeOrderDelivery.wave_no), wave_total_orders: Number(safeOrderDelivery.wave_total_orders || 0), wave_index: Number(safeOrderDelivery.wave_index || 0), platforms_index: Number(safeOrderDelivery.platforms_index || 0), expressInterfaceName: toTrimmedString( safeOrderExpress.logistics_interface_name || safeOrderExpress.logistics_name || safeOrderDelivery.logistics_interface_name || safeOrderDelivery.logistics_name ), fallbackTotalQty: Number(safeOrderDelivery.items_count || safeOrderDelivery.items_total || 0), } ); const customProductInfo = mergeWaybillCustomLines(customProductInfoLines, { lineBreak: LINE_BREAK_MAP.CR, trailingLineBreak: true, }); /** * 判断内容对象是否属于拼多多自定义区。 * * @param {Object} content 内容对象。 * @return {boolean} 是否为自定义区内容对象。 */ function isPddCustomContent(content) { if (!isPlainObject(content)) { return false; } return Boolean( isPlainObject(content.customData) || (isPlainObject(content.data) && Array.isArray(content.data.list)) ); } /** * 构建拼多多默认自定义区内容对象。 * * @param {string} templateURL 自定义模板地址。 * @return {Object} 默认自定义区内容对象。 */ function buildPddDefaultCustomContent(templateURL) { return { templateURL: toTrimmedString(templateURL || DEFAULT_PDD_CUSTOM_TEMPLATE_URL), data: { height: 240, list: [ { fontSize: 28, left: 2.08, text: customProductInfo, top: 2.08, width: 550, } ], waterdata: { text: '', }, width: 560, }, }; } for (const document of documents) { if (!isPlainObject(document)) { continue; } document.documentID = waybillCode; if (!Array.isArray(document.contents)) { document.contents = []; } for (const content of document.contents) { if (!isPlainObject(content)) { continue; } content.addData = isPlainObject(content.addData) ? content.addData : {}; content.addData.sender = isPlainObject(content.addData.sender) ? content.addData.sender : {}; content.addData.sender.address = isPlainObject(content.addData.sender.address) ? content.addData.sender.address : {}; content.addData.sender.address.province = toTrimmedString(safePolicyConfig.province_name); content.addData.sender.address.city = toTrimmedString(safePolicyConfig.city_name); content.addData.sender.address.district = toTrimmedString(safePolicyConfig.district_name); content.addData.sender.address.detail = toTrimmedString(safePolicyConfig.address); content.addData.sender.mobile = toTrimmedString(safePolicyConfig.sender_tel); content.addData.sender.name = toTrimmedString(safePolicyConfig.sender_name); content.encryptedData = encryptedData; content.signature = signature; } const customContent = document.contents.find(isPddCustomContent); if (customContent) { if (!toTrimmedString(customContent.templateURL)) { customContent.templateURL = DEFAULT_PDD_CUSTOM_TEMPLATE_URL; } if (isPlainObject(customContent.data) && Array.isArray(customContent.data.list) && customContent.data.list[0]) { customContent.data.list[0].text = customProductInfo; } } else { document.contents.push(buildPddDefaultCustomContent()); } } } /** * 构建平台请求骨架。 * @param {Object} input 输入对象。 * @return {{platform: string, platform_meta: Object|null, base_data: Object, request_skeleton: Object, missing_fields: Array, warnings: string[]}} 中间态结果。 */ function buildPlatformRequestSkeleton(input = {}) { const normalized = normalizePlatformAlias( input.platform || (isPlainObject(input.order_express) ? input.order_express.platform_code : '') || (isPlainObject(input.order_delivery) ? input.order_delivery.source_platform_code : '') ); const baseResult = buildBaseData(input, normalized.platform, normalized.meta); const options = isPlainObject(input.options) ? input.options : {}; const policyConfig = resolvePolicyConfig(input); const orderExpressForCompose = isPlainObject(input.order_express) ? { ...input.order_express } : {}; const orderDeliveryForCompose = isPlainObject(input.order_delivery) ? input.order_delivery : {}; if (!orderExpressForCompose.items && orderDeliveryForCompose.items) { orderExpressForCompose.items = orderDeliveryForCompose.items; } const templateSample = isPlainObject(input.template_sample) ? input.template_sample : {}; const warnings = [ ...baseResult.warnings ]; const cleanedTemplateSample = sanitizeTemplatePrivateFields(templateSample, warnings); const customDataTemplateURL = resolveKuaishouCustomDataTemplateURL(templateSample); const requestId = toTrimmedString(options.requestId || templateSample.requetID || templateSample.requestID); const taskId = toTrimmedString(options.taskId || requestId); const sampleDocumentSources = [ templateSample.task && templateSample.task.documents, templateSample.documents, templateSample.taskList, ]; let sampleDocumentId = ''; for (const documents of sampleDocumentSources) { if (!Array.isArray(documents) || documents.length === 0) { continue; } const firstDocument = documents[0]; if (isPlainObject(firstDocument) && firstDocument.documentID) { sampleDocumentId = firstDocument.documentID; break; } } const documentId = toTrimmedString( options.documentId || sampleDocumentId ); const sampleTaskDocuments = cleanedTemplateSample.task && Object.prototype.hasOwnProperty.call(cleanedTemplateSample.task, 'documents') ? buildArraySkeleton(cleanedTemplateSample.task.documents, warnings, 'documents') : []; const skeleton = { cmd: toTrimmedString(templateSample.cmd || 'print'), requestID: requestId, version: toTrimmedString(templateSample.version || '1.0'), task: { taskID: taskId, preview: options.preview === undefined ? false : !!options.preview, printer: toTrimmedString(options.printer), }, }; if (sampleTaskDocuments.length > 0) { skeleton.task.documents = sampleTaskDocuments; if (skeleton.task.documents[0] && isPlainObject(skeleton.task.documents[0])) { if (documentId) { skeleton.task.documents[0].documentID = toTrimmedString(documentId); } if (!Array.isArray(skeleton.task.documents[0].contents)) { skeleton.task.documents[0].contents = []; } } } else if (cleanedTemplateSample.task && Object.prototype.hasOwnProperty.call(cleanedTemplateSample.task, 'documents')) { skeleton.task.documents = []; } if (Object.prototype.hasOwnProperty.call(cleanedTemplateSample, 'documents')) { skeleton.documents = buildArraySkeleton(cleanedTemplateSample.documents, warnings, 'documents'); } if (Object.prototype.hasOwnProperty.call(cleanedTemplateSample, 'taskList')) { skeleton.taskList = buildArraySkeleton(cleanedTemplateSample.taskList, warnings, 'taskList'); } if (cleanedTemplateSample.task && Object.prototype.hasOwnProperty.call(cleanedTemplateSample.task, 'documents') && sampleTaskDocuments.length === 0) { warnings.push('template_sample.task.documents 为空或未能解析,已输出空 documents 数组'); } applyKuaishouExpressFieldMapping( normalized.platform, skeleton, orderExpressForCompose, orderDeliveryForCompose, warnings, policyConfig, customDataTemplateURL ); applyPddExpressFieldMapping( normalized.platform, skeleton, orderExpressForCompose, orderDeliveryForCompose, policyConfig ); return { platform: normalized.platform, platform_meta: normalized.meta, base_data: baseResult.base_data, request_skeleton: skeleton, missing_fields: baseResult.missing_fields, warnings, }; } class PrinterDataBuilder { /** * 获取平台硬编码映射。 * @return {Object} 平台映射对象。 */ static getPlatformMap() { return PLATFORM_MAP; } /** * 获取换行符映射。 * @return {Object} 换行符映射对象。 */ static getLineBreakMap() { return LINE_BREAK_MAP; } /** * 平台别名归一化。 * @param {string} platform 平台别名。 * @return {{platform: string, meta: Object|null, raw: string}} 归一化结果。 */ static normalizePlatformAlias(platform) { return normalizePlatformAlias(platform); } /** * 组装基础打印数据。 * @param {Object} input 输入对象。 * @return {{base_data: Object, missing_fields: Array, warnings: string[]}} 组装结果。 */ static buildBaseData(input = {}) { const normalized = normalizePlatformAlias( input.platform || (isPlainObject(input.order_express) ? input.order_express.platform_code : '') || (isPlainObject(input.order_delivery) ? input.order_delivery.source_platform_code : '') ); return buildBaseData(input, normalized.platform, normalized.meta); } /** * 组装平台请求骨架(中间态)。 * @param {Object} input 输入对象。 * @return {{platform: string, platform_meta: Object|null, base_data: Object, request_skeleton: Object, missing_fields: Array, warnings: string[]}} 组装结果。 */ static buildPlatformRequestSkeleton(input = {}) { return buildPlatformRequestSkeleton(input); } } module.exports = PrinterDataBuilder;