WMS_MAIN/app/lib/printer_data_builder.js
liufumingren 025184904a 1
2026-06-14 19:03:58 +08:00

2416 lines
79 KiB
JavaScript
Raw 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';
/**
* 打印数据中间态组装器。
*
* 入参说明(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<string, {name: string, aliases: string[], template_file: string}>}
*/
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<string, string>}
*/
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';
/**
* 小红书自定义区默认模板地址。
* @type {string}
*/
const DEFAULT_XHS_CUSTOM_TEMPLATE_URL = 'https://cloudprint.xiaohongshu.com/template/standard/7/2';
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<Object>} 商品列表。
*/
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) {
const isNoiseQuantityOnlyText = value => {
const sample = String(value || '').trim();
if (!sample) {
return true;
}
return /^(?:\[?\s*\d+(?:\.\d+)?\s*\]?|【\s*\d+(?:\.\d+)?\s*】)(?:\s+0+)?$/.test(sample);
};
const 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<Object>} 商品列表。
*/
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<string>} 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<Object>} items 商品列表。
* @param {Object} policyConfig 策略配置。
* @param {Object} options 附加选项。
* @param {string} [options.waveNo] 波次号。
* @param {number} [options.wave_total_orders] 波次总订单数。
* @param {number} [options.wave_index] 当前波次内序号。
* @param {number} [options.platforms_index] 平台内序号。
* @param {string} [options.expressInterfaceName] 快递渠道显示名。
* @param {number} [options.fallbackTotalQty] 兜底商品总数。
* @return {Array<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);
void platformsIndex;
const hasWaveCustomPrefix = waveTotalOrders > 0
&& waveIndex > 0
&& Boolean(waveNo);
const waveHeaderText = hasWaveCustomPrefix
? `${waveNo} [${finalTotalQty}-${waveIndex}]`
: waveNo;
const headerParts = [ waveHeaderText, expressInterfaceName ].filter(Boolean);
const headerLine = headerParts.join(' ');
if (detailLines.length === 0) {
return [ headerLine ];
}
return [ headerLine, ...detailLines ];
}
/**
* 将自定义文本行按平台换行符合并为字符串。
* @param {Array<string>} 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 '';
}
/**
* 从菜鸟模板样例中提取自定义区模板地址。
*
* 优先扫描 template_sample.task.documents,其次扫描 template_sample.documents 和 template_sample.taskList,
* 找到第一个 data.CustomControl 字段对应的内容对象后返回其 templateURL。
*
* @param {Object} templateSample 模板样例对象。
* @return {string} 自定义区模板地址。
*/
function resolveCainiaoCustomControlTemplateURL(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.data)) {
continue;
}
if (!Object.prototype.hasOwnProperty.call(content.data, 'CustomControl')) {
continue;
}
if (Object.prototype.hasOwnProperty.call(content, 'templateURL')) {
return toTrimmedString(content.templateURL);
}
}
}
}
return '';
}
/**
* 深拷贝普通对象/数组,避免直接复用上游引用。
*
* @param {any} value 原始值。
* @return {any} 拷贝后的值。
*/
function cloneStructuredValue(value) {
if (Array.isArray(value)) {
return value.map(item => cloneStructuredValue(item));
}
if (!isPlainObject(value)) {
return value;
}
const cloned = {};
for (const key of Object.keys(value)) {
cloned[key] = cloneStructuredValue(value[key]);
}
return cloned;
}
/**
* 将可能为 JSON 字符串的值解析为对象。
*
* 仅在值为字符串时尝试解析;解析失败时按需记录警告。
*
* @param {any} value 原始值。
* @param {string[]} [warnings=[]] 风险提示列表。
* @param {boolean} [warnOnFailure=false] 解析失败时是否记录警告。
* @return {Object|null} 解析后的对象;非对象或解析失败返回 null。
*/
function parseCainiaoPrintinfoObject(value, warnings = [], warnOnFailure = false) {
const safeWarnings = Array.isArray(warnings) ? warnings : [];
let payload = value;
if (typeof payload === 'string') {
const text = payload.trim();
if (!text) {
return null;
}
try {
payload = JSON.parse(text);
} catch (error) {
if (warnOnFailure) {
safeWarnings.push('菜鸟 printinfo JSON 解析失败,已回退模板骨架');
}
return null;
}
}
return isPlainObject(payload) ? payload : null;
}
/**
* 将候选值归一化为菜鸟主面单 content。
*
* 支持三类输入:
* - 主 content 对象:{ templateURL, data, signature, ... }
* - 纯主 content 对象:{ encryptedData, signature, templateURL, ver, ... }
* - 旧 data 对象:{ cpCode, recipient, waybillCode, ... }
*
* 同时兼容 `data` 为 JSON 字符串的场景,仅解析一层。
*
* @param {any} candidate 候选值。
* @return {Object|null} 归一化后的主面单 content;无法识别返回 null。
*/
function normalizeCainiaoMainContentCandidate(candidate) {
const normalizedCandidate = parseCainiaoPrintinfoObject(candidate);
if (!normalizedCandidate) {
return null;
}
const normalizeTemplateUrlField = value => {
if (!Object.prototype.hasOwnProperty.call(value, 'templateURL')
&& Object.prototype.hasOwnProperty.call(value, 'templateUrl')) {
value.templateURL = toTrimmedString(value.templateUrl);
delete value.templateUrl;
}
return value;
};
const candidateData = parseCainiaoPrintinfoObject(normalizedCandidate.data) || normalizedCandidate.data;
if (isPlainObject(candidateData) && Object.keys(candidateData).length > 0) {
const normalizedContent = cloneStructuredValue(normalizedCandidate);
normalizedContent.data = cloneStructuredValue(candidateData);
return normalizeTemplateUrlField(normalizedContent);
}
if (Object.keys(normalizedCandidate).length === 0) {
return null;
}
const directContentFieldList = [ 'templateURL', 'templateUrl', 'encryptedData', 'signature', 'ver', 'addData' ];
const hasDirectContent = directContentFieldList.some(field => {
return Object.prototype.hasOwnProperty.call(normalizedCandidate, field);
});
if (hasDirectContent) {
return normalizeTemplateUrlField(cloneStructuredValue(normalizedCandidate));
}
const directDataFieldList = [ 'cpCode', 'recipient', 'waybillCode' ];
const hasDirectData = directDataFieldList.some(field => {
return Object.prototype.hasOwnProperty.call(normalizedCandidate, field);
});
if (!hasDirectData) {
return null;
}
const normalizedData = cloneStructuredValue(normalizedCandidate);
const normalizedContent = {};
if (Object.prototype.hasOwnProperty.call(normalizedData, 'templateURL')) {
normalizedContent.templateURL = toTrimmedString(normalizedData.templateURL);
delete normalizedData.templateURL;
}
if (Object.prototype.hasOwnProperty.call(normalizedData, 'templateUrl')) {
normalizedContent.templateURL = toTrimmedString(normalizedData.templateUrl);
delete normalizedData.templateUrl;
}
normalizedContent.data = normalizedData;
return normalizedContent;
}
/**
* 收集菜鸟 printinfo 中可能承载主面单的候选值。
*
* 仅按已知包装路径做有限展开,避免过度泛化:
* - payload 本身
* - payload.data(若可解析为对象)
* - payload.contents[0]
* - payload.documents[0].contents[0]
* - payload.task.documents[0].contents[0]
*
* @param {Object} payload 顶层 printinfo 对象。
* @return {Array<any>} 候选值列表。
*/
function collectCainiaoMainContentCandidates(payload) {
const candidateList = [];
const pushCandidate = value => {
if (value === undefined || value === null) {
return;
}
candidateList.push(value);
};
const rootDataPayload = parseCainiaoPrintinfoObject(payload.data);
const rootPayloadList = [ payload ];
if (rootDataPayload) {
rootPayloadList.push(rootDataPayload);
}
for (const currentPayload of rootPayloadList) {
if (!isPlainObject(currentPayload)) {
continue;
}
pushCandidate(currentPayload);
if (Array.isArray(currentPayload.contents)) {
pushCandidate(currentPayload.contents[0]);
}
if (Array.isArray(currentPayload.documents) && isPlainObject(currentPayload.documents[0])) {
pushCandidate(currentPayload.documents[0].contents && currentPayload.documents[0].contents[0]);
}
if (isPlainObject(currentPayload.task)
&& Array.isArray(currentPayload.task.documents)
&& isPlainObject(currentPayload.task.documents[0])) {
pushCandidate(currentPayload.task.documents[0].contents && currentPayload.task.documents[0].contents[0]);
}
}
return candidateList;
}
/**
* 解析菜鸟 printinfo 并归一化主面单 content。
*
* 兼容以下形态:
* - 形态 A:主 content 对象:{ templateURL, data, signature, ... }
* - 形态 B:纯主 content 对象:{ encryptedData, signature, templateURL, ver, ... }
* - 形态 C:旧 data 对象:{ cpCode, recipient, waybillCode, ... }
* - 形态 D:包装对象:{ contents: [ { templateURL, data, ... } ] }
* - 形态 E:包装对象:{ documents: [ { contents: [ ... ] } ] }
* - 形态 F:包装对象:{ task: { documents: [ { contents: [ ... ] } ] } }
* - 形态 G:`data` 为 JSON 字符串时解析一层
*
* @param {any} printinfo 原始 printinfo。
* @param {string[]} warnings 风险提示列表。
* @return {Object|null} 解析后的主面单 content;失败返回 null。
*/
function resolveCainiaoMainContentFromPrintinfo(printinfo, warnings = []) {
const payload = parseCainiaoPrintinfoObject(printinfo, warnings, true);
if (!payload) {
return null;
}
const candidateList = collectCainiaoMainContentCandidates(payload);
for (const candidate of candidateList) {
const resolvedContent = normalizeCainiaoMainContentCandidate(candidate);
if (resolvedContent) {
return resolvedContent;
}
}
return null;
}
/**
* 清洗菜鸟主面单 data 中的模板占位符,避免将 `__SAMPLE__` 原样下发。
*
* @param {any} value 原始主面单 data。
* @return {any} 清洗后的主面单 data。
*/
function sanitizeCainiaoMainDataPlaceholders(value) {
if (Array.isArray(value)) {
return value.map(item => sanitizeCainiaoMainDataPlaceholders(item));
}
if (isPlainObject(value)) {
const result = {};
for (const key of Object.keys(value)) {
result[key] = sanitizeCainiaoMainDataPlaceholders(value[key]);
}
return result;
}
if (typeof value === 'string') {
const text = toTrimmedString(value);
return text === '__SAMPLE__' ? '' : text;
}
return value;
}
/**
* 解析菜鸟主面单使用的快递公司编码。
*
* 优先使用上游补齐的菜鸟编码;缺失时再回退到原有物流编码来源,保持兼容。
*
* @param {Object} orderExpress 快递单对象。
* @param {Object} orderDelivery 订单对象。
* @return {string} 菜鸟快递公司编码。
*/
function resolveCainiaoCpCode(orderExpress, orderDelivery) {
const safeOrderExpress = isPlainObject(orderExpress) ? orderExpress : {};
const safeOrderDelivery = isPlainObject(orderDelivery) ? orderDelivery : {};
return toTrimmedString(
safeOrderExpress.cainiao_cp_code
|| safeOrderExpress.logistics_code
|| safeOrderDelivery.logistics_code
|| safeOrderDelivery.sys_logistics_code
);
}
/**
* 解析菜鸟主面单模板地址。
*
* 仅主面单使用该来源,自定义区模板地址仍沿用原有样例解析逻辑。
*
* @param {Object} orderExpress 快递单对象。
* @return {string} 主面单模板地址。
*/
function resolveCainiaoMainTemplateURL(orderExpress) {
const safeOrderExpress = isPlainObject(orderExpress) ? orderExpress : {};
return toTrimmedString(safeOrderExpress.cainiao_template_url);
}
/**
* 解析拼多多主面单模板地址。
*
* @param {Object} orderExpress 快递单对象。
* @return {string} 拼多多主面单模板地址。
*/
function resolvePddMainTemplateURL(orderExpress) {
const safeOrderExpress = isPlainObject(orderExpress) ? orderExpress : {};
return toTrimmedString(safeOrderExpress.pdd_template_url);
}
/**
* 解析抖音主面单模板地址。
*
* 兼容 dy 与 douyin 两种字段命名,优先读取 dy_template_url。
*
* @param {Object} orderExpress 快递单对象。
* @return {string} 抖音主面单模板地址。
*/
function resolveDouyinMainTemplateURL(orderExpress) {
const safeOrderExpress = isPlainObject(orderExpress) ? orderExpress : {};
return toTrimmedString(safeOrderExpress.dy_template_url || safeOrderExpress.douyin_template_url);
}
/**
* 当菜鸟 printinfo 缺失或无效时,仅基于模板骨架构建最小主面单 data。
*
* 不再使用订单、策略等业务字段回填 sender/recipient/packageInfo 等主面单信息。
*
* @param {Object} templateMainData 模板主面单 data。
* @return {Object} 清洗占位符后的最小主面单 data。
*/
function buildCainiaoFallbackMainData(templateMainData) {
return isPlainObject(templateMainData)
? sanitizeCainiaoMainDataPlaceholders(templateMainData)
: {};
}
/**
* 固定菜鸟主面单 data 来源标记。
*
* @param {Object} mainData 菜鸟主面单 data。
* @param {string} source 数据来源标记。
* @return {Object} 已补齐 `_dataFrom` 的主面单 data。
*/
function ensureCainiaoMainDataSource(mainData, source) {
const normalizedMainData = isPlainObject(mainData) ? mainData : {};
normalizedMainData._dataFrom = toTrimmedString(source) || 'printinfo';
return normalizedMainData;
}
/**
* 归一化签约策略配置。
* @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<Object>, 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 警告列表。
* @param {string} [currentKey=''] 当前字段名。
* @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 {Object} orderDelivery 订单对象。
* @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 version = toTrimmedString(safeOrderExpress.ver);
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__';
if (version) {
content.ver = version;
}
}
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.encryptprintinfo -> encryptedData
* - wms_order_express.signature -> signature
* - policy_config 面单发货信息 -> content.addData.sender
*
* 仅在平台为 pdd 时生效,避免影响其他平台。
*
* @param {string} platform 归一化平台编码。
* @param {Object} skeleton 打印请求骨架。
* @param {Object} orderExpress 快递单对象。
* @param {Object} orderDelivery 订单对象。
* @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.encryptprintinfo);
const signature = toTrimmedString(safeOrderExpress.signature);
const version = toTrimmedString(safeOrderExpress.ver);
const waybillCode = toTrimmedString(safeOrderExpress.waybill_code);
const pddMainTemplateURL = resolvePddMainTemplateURL(safeOrderExpress);
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 = [];
}
if (!isPlainObject(document.contents[0])) {
document.contents[0] = {};
}
if (pddMainTemplateURL) {
document.contents[0].templateURL = pddMainTemplateURL;
}
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;
if (version) {
content.ver = version;
}
}
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());
}
}
}
/**
* 获取抖音 params(从预取的 dy_params 字段读取)。
*
* @param {Object} orderExpress 快递单对象。
* @return {string} params 字符串。
*/
// eslint-disable-next-line no-unused-vars
function resolveDouyinParams(orderExpress) {
const safeOrderExpress = isPlainObject(orderExpress) ? orderExpress : {};
return toTrimmedString(safeOrderExpress.dy_params) || '';
}
/**
* 抖音平台主面单模板地址、密文、发件人地址与自定义区字段回填。
*
* 规则:
* - wms_order_express.signature -> signature(签名)
* - wms_order_express.encryptprintinfo -> encryptedData(加密面单数据)
* - params 不赋值,保留模板占位符(由上游平台适配器另算)
* - wms_order_express.dy_template_url / douyin_template_url -> templateURL
* - 发件人地址优先从 policyConfig 读取(province_name / city_name / district_name / sender_address),
* 其次从 orderDelivery 读取;countryCode 固定为 CHN
* - 自定义区(contents[1])根据拣货信息填充 productInfo
*
* 仅在平台为 douyin 时生效。
*
* @param {string} platform 归一化平台编码。
* @param {Object} skeleton 打印请求骨架。
* @param {Object} orderExpress 快递单对象。
* @param {Object} orderDelivery 订单对象。
* @param {Object} policyConfig 策略配置对象。
*/
function applyDouyinExpressFieldMapping(platform, skeleton, orderExpress, orderDelivery, policyConfig) {
if (platform !== 'douyin') {
return;
}
const safeSkeleton = isPlainObject(skeleton) ? skeleton : {};
const safeOrderExpress = isPlainObject(orderExpress) ? orderExpress : {};
const safeOrderDelivery = isPlainObject(orderDelivery) ? orderDelivery : {};
const safePolicyConfig = isPlainObject(policyConfig) ? policyConfig : {};
const douyinMainTemplateURL = resolveDouyinMainTemplateURL(safeOrderExpress);
const documents = safeSkeleton.task && Array.isArray(safeSkeleton.task.documents)
? safeSkeleton.task.documents
: [];
if (documents.length === 0) {
return;
}
// 密文回填
const encryptPrintinfo = toTrimmedString(safeOrderExpress.encryptprintinfo);
const signature = toTrimmedString(safeOrderExpress.signature);
// 发件人信息 — 优先从 policyConfig 读取,其次从 orderDelivery
const senderName = toTrimmedString(safePolicyConfig.sender_name);
const senderTel = toTrimmedString(safePolicyConfig.sender_tel);
const senderProvince = toTrimmedString(safePolicyConfig.province_name || safeOrderDelivery.province_name);
const senderCity = toTrimmedString(safePolicyConfig.city_name || safeOrderDelivery.city_name);
const senderDistrict = toTrimmedString(safePolicyConfig.district_name || safeOrderDelivery.district_name);
const senderAddress = toTrimmedString(safePolicyConfig.sender_address || safePolicyConfig.address);
// 自定义区拣货信息
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: '\n' });
for (const document of documents) {
if (!isPlainObject(document)) {
continue;
}
if (!Array.isArray(document.contents)) {
document.contents = [];
}
const contents = document.contents;
// 主面单(contents[0])回填
const mainContent = contents[0];
if (isPlainObject(mainContent)) {
if (douyinMainTemplateURL) {
mainContent.templateURL = douyinMainTemplateURL;
}
if (encryptPrintinfo) {
mainContent.encryptedData = encryptPrintinfo;
}
if (signature) {
mainContent.signature = signature;
}
// senderInfo
mainContent.addData = isPlainObject(mainContent.addData) ? mainContent.addData : {};
mainContent.addData.senderInfo = isPlainObject(mainContent.addData.senderInfo)
? mainContent.addData.senderInfo : {};
if (senderName) {
mainContent.addData.senderInfo.contact = isPlainObject(mainContent.addData.senderInfo.contact)
? mainContent.addData.senderInfo.contact : {};
mainContent.addData.senderInfo.contact.name = senderName;
}
if (senderTel) {
mainContent.addData.senderInfo.contact = isPlainObject(mainContent.addData.senderInfo.contact)
? mainContent.addData.senderInfo.contact : {};
mainContent.addData.senderInfo.contact.mobile = senderTel;
}
mainContent.addData.senderInfo.address = isPlainObject(mainContent.addData.senderInfo.address)
? mainContent.addData.senderInfo.address : {};
if (senderProvince) mainContent.addData.senderInfo.address.provinceName = senderProvince;
if (senderCity) mainContent.addData.senderInfo.address.cityName = senderCity;
if (senderDistrict) mainContent.addData.senderInfo.address.districtName = senderDistrict;
if (senderAddress) mainContent.addData.senderInfo.address.detailAddress = senderAddress;
mainContent.addData.senderInfo.address.countryCode = 'CHN';
// params 占位实现 — 调试:无条件覆盖
mainContent.params = resolveDouyinParams(safeOrderExpress);
}
// 自定义区 — 模板构建时 contents 被 buildArraySkeleton 截断为 1 个元素,需手动重建
if (contents.length < 2) {
contents.push({});
}
const customContent = contents[1];
if (!toTrimmedString(customContent.templateURL)) {
customContent.templateURL = 'http://www.ye4s.com/mb/douyin1.xml';
}
customContent.data = isPlainObject(customContent.data) ? customContent.data : {};
customContent.data.productInfo = customProductInfo || '无拣货信息';
}
}
/**
* 菜鸟平台主面单与自定义区字段回填。
*
* 规则:
* - wms_order_express.printinfo(字符串/对象)解析后直接回填主 contents[0]
* - documentID 使用 wms_order_express.waybill_code
* - 若模板样例存在 data.CustomControl 对应模板地址,则补充菜鸟自定义区内容
*
* 仅在平台为 cainiao 时生效;主面单优先直接使用 printinfo 解析结果,解析失败时仅回退模板骨架。
*
* @param {string} platform 归一化平台编码。
* @param {Object} skeleton 打印请求骨架。
* @param {Object} orderExpress 快递单对象。
* @param {Object} orderDelivery 订单对象。
* @param {Object} policyConfig 策略配置对象。
* @param {string} customControlTemplateURL 菜鸟自定义区模板地址。
* @param {string[]} warnings 风险提示列表。
*/
function applyCainiaoExpressFieldMapping(
platform,
skeleton,
orderExpress,
orderDelivery,
policyConfig,
customControlTemplateURL,
warnings
) {
if (platform !== 'cainiao') {
return;
}
const safeSkeleton = isPlainObject(skeleton) ? skeleton : {};
const safeOrderExpress = isPlainObject(orderExpress) ? orderExpress : {};
const safeOrderDelivery = isPlainObject(orderDelivery) ? orderDelivery : {};
const safePolicyConfig = isPlainObject(policyConfig) ? policyConfig : {};
const documents = safeSkeleton.task && Array.isArray(safeSkeleton.task.documents)
? safeSkeleton.task.documents
: [];
if (documents.length === 0) {
return;
}
const cainiaoMainContent = resolveCainiaoMainContentFromPrintinfo(safeOrderExpress.printinfo, warnings);
const hasPrintinfoMainContent = isPlainObject(cainiaoMainContent);
const waybillCode = toTrimmedString(safeOrderExpress.waybill_code);
const cainiaoCpCode = resolveCainiaoCpCode(safeOrderExpress, safeOrderDelivery);
const cainiaoMainTemplateURL = resolveCainiaoMainTemplateURL(safeOrderExpress);
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 customControlText = mergeWaybillCustomLines(customProductInfoLines, {
lineBreak: LINE_BREAK_MAP.CR,
});
for (const document of documents) {
if (!isPlainObject(document)) {
continue;
}
if (waybillCode) {
document.documentID = waybillCode;
}
if (!Array.isArray(document.contents)) {
document.contents = [];
}
const contents = document.contents;
let mainContent = contents[0];
if (!isPlainObject(mainContent)) {
mainContent = {};
if (contents.length === 0) {
contents.push(mainContent);
} else {
contents[0] = mainContent;
}
}
if (hasPrintinfoMainContent) {
mainContent = cloneStructuredValue(cainiaoMainContent);
contents[0] = mainContent;
} else {
mainContent = cloneStructuredValue(mainContent);
contents[0] = mainContent;
}
if (hasPrintinfoMainContent) {
if (isPlainObject(mainContent.data)) {
mainContent.data = ensureCainiaoMainDataSource(mainContent.data, 'printinfo');
}
} else {
mainContent.data = ensureCainiaoMainDataSource(
buildCainiaoFallbackMainData(mainContent.data),
'template'
);
}
if (cainiaoCpCode && isPlainObject(mainContent.data)) {
mainContent.data.cpCode = cainiaoCpCode;
mainContent.data.realCpCode = cainiaoCpCode;
}
if (cainiaoMainTemplateURL) {
mainContent.templateURL = cainiaoMainTemplateURL;
}
if (!toTrimmedString(customControlTemplateURL) || !customControlText) {
continue;
}
const customControlContent = contents.find(content => {
return isPlainObject(content)
&& isPlainObject(content.data)
&& Object.prototype.hasOwnProperty.call(content.data, 'CustomControl');
});
if (customControlContent) {
customControlContent.templateURL = toTrimmedString(customControlTemplateURL);
customControlContent.data.CustomControl = customControlText;
} else {
contents.push({
templateURL: toTrimmedString(customControlTemplateURL),
data: {
CustomControl: customControlText,
},
});
}
}
}
/**
* 解析小红书主面单 content。
*
* 支持 printinfo 为 JSON 字符串或对象,并兼容以下包装结构:
* - contents[0]
* - documents[0].contents[0]
* - task.documents[0].contents[0]
*
* 若不命中包装结构,则回退为 printinfo 顶层对象本身。
*
* @param {any} printinfo 原始 printinfo。
* @param {string[]} [warnings=[]] 风险提示列表。
* @return {Object|null} 主面单 content;无法解析返回 null。
*/
function resolveXhsMainContentFromPrintinfo(printinfo, warnings = []) {
const safeWarnings = Array.isArray(warnings) ? warnings : [];
let payload = printinfo;
if (typeof payload === 'string') {
const text = payload.trim();
if (!text) {
return null;
}
try {
payload = JSON.parse(text);
} catch (error) {
safeWarnings.push('小红书 printinfo JSON 解析失败,已回退模板骨架');
return null;
}
}
if (!isPlainObject(payload)) {
return null;
}
if (!payload) {
return null;
}
const wrapperCandidates = [
payload.contents && payload.contents[0],
payload.documents && payload.documents[0] && payload.documents[0].contents && payload.documents[0].contents[0],
payload.task
&& payload.task.documents
&& payload.task.documents[0]
&& payload.task.documents[0].contents
&& payload.task.documents[0].contents[0],
];
for (const candidate of wrapperCandidates) {
if (isPlainObject(candidate)) {
return cloneStructuredValue(candidate);
}
}
return cloneStructuredValue(payload);
}
/**
* 小红书平台主面单与自定义区字段回填。
*
* 规则:
* - 主面单 contents[0] 直接使用 wms_order_express.printinfo(支持字符串/对象及包装结构)
* - 自定义区按模板结构处理,仅填充 contents[1].data.order[0]
*
* 仅在平台为 xhs 时生效。
*
* @param {string} platform 归一化平台编码。
* @param {Object} skeleton 打印请求骨架。
* @param {Object} orderExpress 快递单对象。
* @param {Object} orderDelivery 订单对象。
* @param {Object} policyConfig 策略配置对象。
* @param {string[]} warnings 风险提示列表。
*/
function applyXhsExpressFieldMapping(
platform,
skeleton,
orderExpress,
orderDelivery,
policyConfig,
warnings
) {
if (platform !== 'xhs') {
return;
}
const safeSkeleton = isPlainObject(skeleton) ? skeleton : {};
const safeOrderExpress = isPlainObject(orderExpress) ? orderExpress : {};
const safeOrderDelivery = isPlainObject(orderDelivery) ? orderDelivery : {};
const safePolicyConfig = isPlainObject(policyConfig) ? policyConfig : {};
const safeWarnings = Array.isArray(warnings) ? warnings : [];
const documents = safeSkeleton.task && Array.isArray(safeSkeleton.task.documents)
? safeSkeleton.task.documents
: [];
if (documents.length === 0) {
return;
}
const xhsMainContent = resolveXhsMainContentFromPrintinfo(safeOrderExpress.printinfo, safeWarnings);
const hasXhsMainContent = isPlainObject(xhsMainContent);
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 (!Array.isArray(document.contents)) {
document.contents = [];
}
const contents = document.contents;
if (hasXhsMainContent) {
contents[0] = cloneStructuredValue(xhsMainContent);
}
if (!isPlainObject(contents[1])) {
contents[1] = {};
}
const customContent = contents[1];
if (!toTrimmedString(customContent.templateURL)) {
customContent.templateURL = DEFAULT_XHS_CUSTOM_TEMPLATE_URL;
}
customContent.data = isPlainObject(customContent.data) ? customContent.data : {};
customContent.data.order = Array.isArray(customContent.data.order) ? customContent.data.order : [];
customContent.data.order[0] = customProductInfo;
}
}
/**
* 视频号平台 taskList 字段回填。
*
* 规则:
* - 仅在平台为 sph 时生效
* - 基于 skeleton.taskList[0] 回填,不改模板默认的结构控制字段
* - taskList[0].printInfo 使用 order_express.printinfo(非空时)
* - taskList[0].printNum.sumNum 使用 wave_total_orders,curNum 保持模板值,缺失时默认 1
* - taskList[0].customInfo.data.description 使用现有商品汇总文本并按 <br> 拼接
* - taskList[0].extendData.sender 使用 policy_config 发件人信息
* - taskList[0].taskID 优先沿用 buildPlatformRequestSkeleton 现有 taskId
*
* @param {string} platform 归一化平台编码。
* @param {Object} skeleton 打印请求骨架。
* @param {Object} orderExpress 快递单对象。
* @param {Object} orderDelivery 订单对象。
* @param {Object} policyConfig 策略配置对象。
*/
function applySphExpressFieldMapping(
platform,
skeleton,
orderExpress,
orderDelivery,
policyConfig
) {
if (platform !== 'sph') {
return;
}
const safeSkeleton = isPlainObject(skeleton) ? skeleton : {};
const safeOrderExpress = isPlainObject(orderExpress) ? orderExpress : {};
const safeOrderDelivery = isPlainObject(orderDelivery) ? orderDelivery : {};
const safePolicyConfig = isPlainObject(policyConfig) ? policyConfig : {};
const taskList = Array.isArray(safeSkeleton.taskList) ? safeSkeleton.taskList : [];
if (!isPlainObject(taskList[0])) {
return;
}
const task = taskList[0];
const printinfo = toTrimmedString(safeOrderExpress.printinfo);
if (printinfo) {
task.printInfo = printinfo;
}
task.printNum = isPlainObject(task.printNum) ? task.printNum : {};
const currentCurNum = toNumber(task.printNum.curNum, 0);
task.printNum.curNum = currentCurNum > 0 ? currentCurNum : 1;
task.printNum.sumNum = toNumber(
safeOrderDelivery.wave_total_orders,
toNumber(task.printNum.sumNum, 0)
);
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,
}).replace(/\n/g, '<br>');
task.customInfo = isPlainObject(task.customInfo) ? task.customInfo : {};
task.customInfo.data = isPlainObject(task.customInfo.data) ? task.customInfo.data : {};
task.customInfo.data.description = customProductInfo;
task.extendData = isPlainObject(task.extendData) ? task.extendData : {};
task.extendData.sender = isPlainObject(task.extendData.sender) ? task.extendData.sender : {};
task.extendData.sender.address = isPlainObject(task.extendData.sender.address)
? task.extendData.sender.address
: {};
task.extendData.sender.address.provinceName = toTrimmedString(safePolicyConfig.province_name);
task.extendData.sender.address.cityName = toTrimmedString(safePolicyConfig.city_name);
task.extendData.sender.address.countyName = toTrimmedString(safePolicyConfig.district_name);
task.extendData.sender.address.detailInfo = toTrimmedString(safePolicyConfig.address);
task.extendData.sender.userName = toTrimmedString(safePolicyConfig.sender_name);
task.extendData.sender.telNumber = toTrimmedString(safePolicyConfig.sender_tel);
const existingTaskId = toTrimmedString(safeSkeleton.task && safeSkeleton.task.taskID);
if (existingTaskId) {
task.taskID = existingTaskId;
}
}
/**
* 从京东模板样例中提取主面单 content 原型。
*
* 优先使用 input.template_sample.parameters.contents[0],
* 缺失时回退为 {},避免影响骨架构建流程。
*
* @param {Object} templateSample 模板样例对象。
* @return {Object} 主面单 content 原型。
*/
function resolveJdTemplateContentPrototype(templateSample) {
const sample = isPlainObject(templateSample) ? templateSample : {};
if (!isPlainObject(sample.parameters) || !Array.isArray(sample.parameters.contents)) {
return {};
}
const firstContent = sample.parameters.contents[0];
return isPlainObject(firstContent) ? cloneStructuredValue(firstContent) : {};
}
/**
* 读取京东主模板地址。
*
* @param {Object} orderExpress 快递单对象。
* @return {string} 京东主模板地址。
*/
function resolveJdTemplateUrlFromOrderExpress(orderExpress) {
const safeOrderExpress = isPlainObject(orderExpress) ? orderExpress : {};
return toTrimmedString(safeOrderExpress.jd_template_url);
}
/**
* 京东平台主面单字段回填。
*
* 规则:
* - 仅在平台为 jd 时生效
* - 主面单原型来源于 template_sample.parameters.contents[0]
* - 保证 skeleton.task.documents[0] 存在并回填 documentID、contents[0]
* - order_express.printinfo 回填 contents[0].printData
* - policy_config 发件人信息回填到 contents[0].addData.sender
* - 自定义区商品信息写入 contents[0].customData.GoodsInfo
*
* @param {string} platform 归一化平台编码。
* @param {Object} skeleton 打印请求骨架。
* @param {Object} orderExpress 快递单对象。
* @param {Object} orderDelivery 订单对象。
* @param {Object} policyConfig 策略配置对象。
* @param {Object} templateSample 模板样例对象。
* @param {string[]} warnings 风险提示列表。
*/
function applyJdExpressFieldMapping(
platform,
skeleton,
orderExpress,
orderDelivery,
policyConfig,
templateSample,
warnings
) {
if (platform !== 'jd') {
return;
}
const safeSkeleton = isPlainObject(skeleton) ? skeleton : {};
const safeOrderExpress = isPlainObject(orderExpress) ? orderExpress : {};
const safeOrderDelivery = isPlainObject(orderDelivery) ? orderDelivery : {};
const safePolicyConfig = isPlainObject(policyConfig) ? policyConfig : {};
const safeWarnings = Array.isArray(warnings) ? warnings : [];
const contentPrototype = resolveJdTemplateContentPrototype(templateSample);
safeSkeleton.task = isPlainObject(safeSkeleton.task) ? safeSkeleton.task : {};
safeSkeleton.task.documents = Array.isArray(safeSkeleton.task.documents)
? safeSkeleton.task.documents
: [];
if (!isPlainObject(safeSkeleton.task.documents[0])) {
if (safeSkeleton.task.documents.length === 0) {
safeSkeleton.task.documents.push({});
} else {
safeSkeleton.task.documents[0] = {};
}
}
const document = safeSkeleton.task.documents[0];
const waybillCode = toTrimmedString(safeOrderExpress.waybill_code);
if (waybillCode) {
document.documentID = waybillCode;
}
document.contents = Array.isArray(document.contents) ? document.contents : [];
document.contents[0] = cloneStructuredValue(contentPrototype);
const content = isPlainObject(document.contents[0]) ? document.contents[0] : {};
document.contents[0] = content;
const jdTemplateUrl = resolveJdTemplateUrlFromOrderExpress(safeOrderExpress);
if (jdTemplateUrl) {
content.tempUrl = jdTemplateUrl;
}
const printinfo = toTrimmedString(safeOrderExpress.printinfo);
if (printinfo) {
content.printData = printinfo;
} else {
safeWarnings.push('京东 printinfo 为空,已保留模板 printData 默认值');
}
const senderAddress = [
toTrimmedString(safePolicyConfig.province_name),
toTrimmedString(safePolicyConfig.city_name),
toTrimmedString(safePolicyConfig.district_name),
toTrimmedString(safePolicyConfig.town_name),
toTrimmedString(safePolicyConfig.address),
].filter(Boolean).join('');
content.addData = isPlainObject(content.addData) ? content.addData : {};
content.addData.sender = isPlainObject(content.addData.sender) ? content.addData.sender : {};
content.addData.sender.name = toTrimmedString(safePolicyConfig.sender_name);
content.addData.sender.mobile = toTrimmedString(safePolicyConfig.sender_tel);
content.addData.sender.address = senderAddress;
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,
trailingLineBreak: true,
});
content.customData = isPlainObject(content.customData) ? content.customData : {};
content.customData.GoodsInfo = customProductInfo;
}
/**
* 构建平台请求骨架。
* @param {Object} input 输入对象。
* @return {{platform: string, platform_meta: Object|null, base_data: Object, request_skeleton: Object, missing_fields: Array<Object>, 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 cainiaoCustomControlTemplateURL = resolveCainiaoCustomControlTemplateURL(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 数组');
}
applyCainiaoExpressFieldMapping(
normalized.platform,
skeleton,
orderExpressForCompose,
orderDeliveryForCompose,
policyConfig,
cainiaoCustomControlTemplateURL,
warnings
);
applyKuaishouExpressFieldMapping(
normalized.platform,
skeleton,
orderExpressForCompose,
orderDeliveryForCompose,
warnings,
policyConfig,
customDataTemplateURL
);
applyPddExpressFieldMapping(
normalized.platform,
skeleton,
orderExpressForCompose,
orderDeliveryForCompose,
policyConfig
);
applyDouyinExpressFieldMapping(
normalized.platform,
skeleton,
orderExpressForCompose,
orderDeliveryForCompose,
policyConfig
);
applyJdExpressFieldMapping(
normalized.platform,
skeleton,
orderExpressForCompose,
orderDeliveryForCompose,
policyConfig,
templateSample,
warnings
);
applyXhsExpressFieldMapping(
normalized.platform,
skeleton,
orderExpressForCompose,
orderDeliveryForCompose,
policyConfig,
warnings
);
applySphExpressFieldMapping(
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<string, string>} 换行符映射对象。
*/
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<Object>, 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<Object>, warnings: string[]}} 组装结果。
*/
static buildPlatformRequestSkeleton(input = {}) {
return buildPlatformRequestSkeleton(input);
}
}
module.exports = PrinterDataBuilder;