上一版只覆盖了整包 `Success:false + Message` 的形态,线上这条提示其实走的是**逐单**分支:
`{"Success":true,"Data":{"Orders":[{"IsSuccess":false,"ErrorMessage":"存在不是待发货的商品,发货失败;"}]}}`,
而逐单幂等正则要求「不是待发货状态」,少了「状态」两字没命中,于是照旧抛错重试。
用户看到的 `店管家发货同步失败:: 存在不是待发货…` 里的双冒号就是逐单分支 + 平台未回 LogicOrderId 造成的。
- 抽出 SEND_ALREADY_DONE_PATTERN(不是待发货 / 已发货 / 已取消 / 已关闭),整包与逐单共用
- 逐单失败且平台未回 LogicOrderId 时不再拼「: 」前缀,避免出现「失败:: xxx」
- 单测补 2 例(逐单幂等 / 无单号时不出现双冒号),共 5 例
- 文档补两种形态的报文明细
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
3411 lines
144 KiB
JavaScript
3411 lines
144 KiB
JavaScript
'use strict';
|
||
|
||
const PrintPlatformService = require('./base');
|
||
const { resolvePlatform } = require('../platformCode');
|
||
const { isPayloadRejected } = require('../platformError');
|
||
|
||
/** 店管家商家门户站点 */
|
||
const PORTAL_ORIGIN = 'https://tfxportal.dgjapp.com';
|
||
/** 门户登录页入口(用于登录前建立会话 cookie;未登录时访问会停在登录页) */
|
||
const PORTAL_URL = `${PORTAL_ORIGIN}/ffaccount`;
|
||
/** 登录前置接口:判断是否需要提示绑定微信 */
|
||
const BIND_WECHAT_PROMPT_URL = `${PORTAL_ORIGIN}/FFAccount/BindWeChatPrompt`;
|
||
/** 登录接口:返回 Token 与跳转地址,并通过 set-cookie 下发登录态 */
|
||
const LOGIN_URL = `${PORTAL_ORIGIN}/FFAccount/LoginPortal`;
|
||
|
||
/** 登录后的工作台域名(需同时带 token 与 cookie 才能打开) */
|
||
const WORKBENCH_HOST = 'fxali.dgjapp.com';
|
||
/** 工作台入口:?token=<登录接口返回的 Token> */
|
||
const WORKBENCH_URL = `https://${WORKBENCH_HOST}/GeneralizeIndex/`;
|
||
/** 工作台用户信息接口:返回当前登录账号的店铺/昵称等信息(需 token + cookie) */
|
||
const USER_INFO_URL = `https://${WORKBENCH_HOST}/api/user/GetUserInfo`;
|
||
/** 工作台分区信息接口:商家列表需要其中的 dbname;商品查询需要逐个分区(区)查询 */
|
||
const AREAS_INFO_PATH = '/api/user/GetAreasInfo';
|
||
/** 商家(即店管家侧的店铺)列表接口 */
|
||
const AGENT_LIST_URL = `https://${WORKBENCH_HOST}/Partner/LoadMyAgentList`;
|
||
|
||
/** 商品列表接口(按分区域名请求,路径固定) */
|
||
const PRODUCT_LIST_PATH = '/Product/LoadList';
|
||
|
||
/** 订单列表接口(按分区域名请求,路径固定) */
|
||
const ORDER_LIST_PATH = '/NewOrder/List';
|
||
|
||
/** 面单模板(快递接口)列表接口:按平台域名请求,返回当前分区下可用的快递面单模板 */
|
||
const TEMPLATE_LIST_PATH = '/TemplateSet/LoadTemplateListInOrderList';
|
||
|
||
/** 面单账号明细接口:查看单个模板对应的电子面单账号 / 网点明细 */
|
||
const TEMPLATE_DETAIL_PATH = '/TemplateSet/LoadWaybillAccountDetailInfo';
|
||
|
||
/** 取号前校验模板可用性 / 面单余额(只读,不消耗面单) */
|
||
const TEMPLATE_AVAILABLE_PATH = '/TemplateSet/CheckTemplateAvaliable';
|
||
|
||
/**
|
||
* 取号接口:一次调用即返回运单号与打印数据,**会真实消耗面单**。
|
||
* 默认开启;需要临时停用时把环境变量 DGJ_WAYBILL_ENABLE 置为 0/false/off。
|
||
*/
|
||
const EXPRESS_PRINT_PATH = '/NewOrder/ExpressPrint';
|
||
|
||
/**
|
||
* 通知平台发货接口(`POST /NewOrder/OnlineSend`,**不消耗面单**)。
|
||
*/
|
||
const ONLINE_SEND_PATH = '/NewOrder/OnlineSend';
|
||
|
||
/**
|
||
* 按打印记录重新拉取面单打印数据(**只读,不消耗面单**)。
|
||
*
|
||
* 取号返回的打印数据(params)只有 10 分钟有效期,WMS 真正打印前要再取一次:
|
||
* `POST /PrintHistory/LoadPrintData?dbname=...`,表单 `printHistoryIds[]=...&IsCustomerOrder=false&FxPageType=1`。
|
||
*/
|
||
const PRINT_HISTORY_DATA_PATH = '/PrintHistory/LoadPrintData';
|
||
|
||
/**
|
||
* 是否允许调用真实取号(默认开启)
|
||
*
|
||
* 平台配置 `fetch_waybill_no=1` 即表示要回打单平台取号,这里默认放行;
|
||
* 仅在需要「只读联调、绝不下单」时用 DGJ_WAYBILL_ENABLE=0 显式关闭。
|
||
* @return {boolean} 是否允许调用 ExpressPrint
|
||
*/
|
||
function isWaybillEnabled() {
|
||
const value = String(process.env.DGJ_WAYBILL_ENABLE == null ? '' : process.env.DGJ_WAYBILL_ENABLE).trim().toLowerCase();
|
||
return !(value === '0' || value === 'false' || value === 'off' || value === 'no');
|
||
}
|
||
|
||
/**
|
||
* 构造带平台原始返回的错误(供上层写入取号记录留痕)
|
||
* @param {string} message 错误提示
|
||
* @param {{status: number, json: Object|null, text: string}} res 平台响应
|
||
* @return {Error} 附带 rawResponse 的错误
|
||
*/
|
||
function buildPlatformError(message, res) {
|
||
const error = new Error(message);
|
||
error.rawResponse = res && res.json ? res.json : { httpStatus: res && res.status, text: res && res.text };
|
||
return error;
|
||
}
|
||
|
||
/**
|
||
* 单进程内相邻两次平台请求的最小间隔(毫秒)
|
||
*
|
||
* 店管家按服务商维度限流(实测配置 600 QPS),批量取号/发货时容易把突发打满,
|
||
* 这里平滑一下节奏;置 0 可关闭。默认 100ms(单进程约 10 请求/秒,远低于平台额度,
|
||
* 但足以削掉并发突发造成的瞬时峰值)。
|
||
* @return {number} 间隔毫秒
|
||
*/
|
||
function requestIntervalMs() {
|
||
return Math.max(0, Number(process.env.DGJ_REQUEST_INTERVAL_MS == null ? 100 : process.env.DGJ_REQUEST_INTERVAL_MS) || 0);
|
||
}
|
||
|
||
/**
|
||
* 被平台限流(isv.request-limited)时的自动重试次数
|
||
* @return {number} 重试次数
|
||
*/
|
||
function rateLimitRetryCount() {
|
||
return Math.max(0, Number(process.env.DGJ_RATE_LIMIT_RETRY == null ? 3 : process.env.DGJ_RATE_LIMIT_RETRY) || 0);
|
||
}
|
||
|
||
/**
|
||
* 限流退避基数(毫秒):第 n 次重试等待 base * 2^(n-1)
|
||
* @return {number} 退避毫秒
|
||
*/
|
||
function rateLimitBackoffMs() {
|
||
return Math.max(0, Number(process.env.DGJ_RATE_LIMIT_BACKOFF_MS || 1000) || 0);
|
||
}
|
||
|
||
/** 下一次允许发请求的时间戳(模块级,进程内共享) */
|
||
let nextRequestAt = 0;
|
||
|
||
/**
|
||
* 等待到本进程允许发下一条请求(平滑突发)
|
||
* @return {Promise<void>} 无返回值
|
||
*/
|
||
async function waitRequestTurn() {
|
||
const interval = requestIntervalMs();
|
||
if (!(interval > 0)) return;
|
||
const now = Date.now();
|
||
const startAt = Math.max(now, nextRequestAt);
|
||
nextRequestAt = startAt + interval;
|
||
if (startAt > now) await new Promise(resolve => setTimeout(resolve, startAt - now));
|
||
}
|
||
|
||
/**
|
||
* 平台返回是否为限流(服务商级 QPS 超限)
|
||
* @param {Object|null} json 平台响应
|
||
* @return {boolean} 是否限流
|
||
*/
|
||
function isRateLimited(json) {
|
||
if (!json) return false;
|
||
const text = `${json.Message == null ? '' : json.Message} ${json.ErrorCode == null ? '' : json.ErrorCode}`;
|
||
return /isv\.request-limited|请求太频繁|访问QPS|限流/i.test(text);
|
||
}
|
||
|
||
/**
|
||
* 「这一单平台侧已不是待发货」类提示:已发货/已取消/已关闭都算,属幂等(本地按已同步处理)
|
||
*
|
||
* 实测两种形态:整包 `{"Success":false,"Message":"存在不是待发货的商品,发货失败;"}`
|
||
* 与逐单 `Data.Orders[] IsSuccess=false + ErrorMessage="存在不是待发货的商品,发货失败;"`
|
||
* (后者 `LogicOrderId` 常为空,拼接出来就是「店管家发货同步失败:: 存在不是待发货的商品…」)。
|
||
*/
|
||
const SEND_ALREADY_DONE_PATTERN = /不是待发货|已发货|已取消|已关闭/;
|
||
|
||
/**
|
||
* 提取发货回传的逐单失败(平台是「整包 Success + Data.Orders[] 逐单结果」)
|
||
* @param {Object} json 平台响应
|
||
* @return {Array<{logicOrderId: string, message: string}>} 逐单失败
|
||
*/
|
||
function extractSendOrderFailures(json) {
|
||
const list = json && json.Data && Array.isArray(json.Data.Orders) ? json.Data.Orders : [];
|
||
const out = [];
|
||
for (const item of list) {
|
||
if (!item || typeof item !== 'object') continue;
|
||
if (item.IsSuccess === true || Number(item.IsSuccess) === 1) continue;
|
||
out.push({
|
||
logicOrderId: String(item.LogicOrderId || item.OrderCode || ''),
|
||
message: String(item.ErrorMessage || item.ErrorMsg || '平台未返回原因'),
|
||
});
|
||
}
|
||
return out;
|
||
}
|
||
|
||
/**
|
||
* 组装发货回传的单条订单报文(对齐平台「待打订单 → 发货」实际请求,2026-11-07 抓包)
|
||
* @param {Object} row 平台订单行(findPlatformOrderRow 的返回)
|
||
* @param {number} index 序号(0 基)
|
||
* @param {string} [expressCode] 快递编码兜底
|
||
* @return {Object} Orders[i]
|
||
*/
|
||
function buildSendOrder(row, index, expressCode = '') {
|
||
const subOrders = Array.isArray(row.SubOrders) ? row.SubOrders : [];
|
||
const waybills = Array.isArray(row.WaybillCodes) ? row.WaybillCodes : [];
|
||
const firstWaybill = waybills.find(code => code && code.WaybillCode) || {};
|
||
const items = subOrders.map(sub => ({
|
||
OrderItemId: sub.OrderItemId,
|
||
OrderItemCode: sub.OrderItemCode,
|
||
Quantity: '1',
|
||
SkuCode: sub.SkuCode,
|
||
ProductCode: sub.ProductID,
|
||
OrderItemIdStr: String(sub.OrderItemId == null ? '' : sub.OrderItemId),
|
||
}));
|
||
const orderItems = subOrders.map(sub => sub.OrderItemId);
|
||
return {
|
||
Id: row.Id,
|
||
Index: index + 1,
|
||
LogicOrderId: row.LogicOrderId,
|
||
PlatformOrderId: row.LogicOrderId,
|
||
PathFlowCode: row.PathFlowCode,
|
||
CustomerOrderId: row.PlatformOrderId,
|
||
ExpressPrintTime: row.ExpressPrintTime || '',
|
||
ShopId: row.ShopId,
|
||
ShopName: row.ShopName || '',
|
||
PlatformTypeName: row.PlatformTypeName || '',
|
||
PlatformType: row.PlatformType,
|
||
PlatformStatus: 'waitsellersend',
|
||
RefunStatus: '',
|
||
FxUserId: row.FxUserId,
|
||
BuyerRemark: row.BuyerRemark || '',
|
||
SellerRemark: row.SellerRemark || '',
|
||
NewSellerRemark: '',
|
||
NewPrintRemark: '',
|
||
// 分销场景 UpFxUserId(上游厂家)≠ FxUserId,直接透传平台值,别用 FxUserId 顶替
|
||
UpFxUserId: row.UpFxUserId,
|
||
IsPddCrossBorderOrder: row.IsPddCrossBorderOrder === true,
|
||
IsPddCourierDoorToDoorCollect: row.IsPddCourierDoorToDoorCollect === true,
|
||
ReceiverIsChange: row.ReceiverIsChange === true,
|
||
DataFlag: row.DataFlag,
|
||
PrintState: row.PrintState,
|
||
IsOfflineOrder: row.IsOfflineOrder === true,
|
||
OrderTags: Array.isArray(row.OrderTags) ? row.OrderTags : [],
|
||
PayTime: row.PayTime || '',
|
||
MergeredType: row.MergeredType == null ? 0 : row.MergeredType,
|
||
// 平台页面会把订单行里这个加密串原样带回,缺了可能被判报文不合法
|
||
ShippingType: row.ShippingType || '',
|
||
LogisticStatus: row.LogisticStatus == null ? 0 : row.LogisticStatus,
|
||
ExtField1: row.ExtField1 || '',
|
||
ExtField2: row.ExtField2 || '',
|
||
SellerRemarkFlagTag: row.SellerRemarkFlagTag || '',
|
||
IsSelectAllNotPrintedItem: 1,
|
||
WaybillCode: row.LastWaybillCode || firstWaybill.WaybillCode || '',
|
||
ExpressCompanyCode: firstWaybill.ExpressCpCode || expressCode || '',
|
||
weight: 0,
|
||
WaybillCodeUniqueKey: firstWaybill.UniqueKey || '',
|
||
SubOrders: subOrders,
|
||
WaybillCodes: waybills,
|
||
Items: items,
|
||
OrderItems: orderItems,
|
||
OrderItemStrList: orderItems,
|
||
Receiver: {
|
||
ToProvince: row.ToProvince,
|
||
ToCity: row.ToCity,
|
||
ToCounty: row.ToCounty,
|
||
ToMaskAddress: `${row.ToTown || ''}${row.ToAddress || ''}`,
|
||
ToName: row.ToName,
|
||
ToMobile: row.ToPhone,
|
||
ToAddress: row.ToFullAddress,
|
||
toFullName: row.ToName,
|
||
toArea: row.ToFullAddress,
|
||
},
|
||
Sender: { SenderCompany: '', CompanyName: '' },
|
||
ReceiverIsEmpty: 0,
|
||
PrintInfo: '',
|
||
NoPrintFlag: 'false',
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 收集发货回传响应里的逐单错误(各平台结构不统一,这里按常见字段兜底)
|
||
* @param {Object} json 平台响应
|
||
* @return {string[]} 可读错误文案
|
||
*/function describeSendErrors(json) {
|
||
const out = [];
|
||
const data = json && json.Data;
|
||
const list = Array.isArray(data) ? data : (data && Array.isArray(data.List) ? data.List : []);
|
||
for (const item of list) {
|
||
if (!item || typeof item !== 'object') continue;
|
||
const isError = item.IsError === true || Number(item.IsError) === 1;
|
||
const message = item.ErrorMsg || item.ErrMsg || item.Message || (isError ? '平台返回失败' : '');
|
||
if (!message) continue;
|
||
const code = item.LogicOrderId || item.OrderCode || item.PlatformOrderId || '';
|
||
out.push(code ? `${code}: ${message}` : message);
|
||
}
|
||
// 去重但保留顺序
|
||
return [ ...new Set(out) ].slice(0, 3);
|
||
}
|
||
|
||
/** 订单列表单页条数(平台允许 500) */
|
||
const ORDER_PAGE_SIZE = 500;
|
||
|
||
/** 订单查询的最大翻页数,防御平台分页异常 */
|
||
const ORDER_MAX_PAGES = 200;
|
||
|
||
/**
|
||
* 拉单时固定下发的订单状态过滤(平台订单页同口径:Filters ErpState == waitsellersend)。
|
||
* 不加这个条件会把窗口内历史已发货/已完成单全部拉回来再本地丢弃,请求量放大十几倍。
|
||
*/
|
||
const ORDER_ERP_STATE_PENDING = 'waitsellersend';
|
||
|
||
/**
|
||
* 老分区(不支持状态/商家过滤)退化拉取时的最大回看天数。
|
||
* 老分区只能按时间窗全量拉,「全部待处理」这类超大窗口会翻很多页,这里统一封顶(与平台页面默认 15 天一致),
|
||
* 用 DGJ_FALLBACK_MAX_DAYS 可覆盖。
|
||
*/
|
||
const ORDER_FALLBACK_MAX_DAYS = Number(process.env.DGJ_FALLBACK_MAX_DAYS || 15);
|
||
|
||
/** 分区是否支持「状态/商家」过滤的进程内缓存:key = host|dbname,避免每次都撞一次「服务器繁忙」 */
|
||
const AREA_FILTER_SUPPORT = new Map();
|
||
const AREA_FILTER_SUPPORT_TTL_MS = 60 * 60 * 1000;
|
||
|
||
/** 商家的分区 DbName -> 商品接口域名(toutiao=抖店、pinduoduo=拼多多、alibaba=精选、jingdong=京东) */
|
||
const AREA_PRODUCT_HOSTS = {
|
||
toutiao: 'fxdd.dgjapp.com',
|
||
pinduoduo: 'fxpdd.dgjapp.com',
|
||
alibaba: 'fxali.dgjapp.com',
|
||
jingdong: 'fxjd.dgjapp.com',
|
||
taobao: 'fxali.dgjapp.com',
|
||
kuaishou: 'fxali.dgjapp.com',
|
||
};
|
||
|
||
/** 商家没有可识别的分区时兜底查询的域名:宁可多查,避免漏商品 */
|
||
const FALLBACK_PRODUCT_HOSTS = [
|
||
'fxali.dgjapp.com',
|
||
'fxdd.dgjapp.com',
|
||
'fxpdd.dgjapp.com',
|
||
'fxjd.dgjapp.com',
|
||
'fxtk.dgjapp.com',
|
||
];
|
||
|
||
/**
|
||
* 面单模板(快递接口)接口按平台域名部署:分区 DbName → 模板接口域名 + PlatformType 写法。
|
||
* 平台新增分区时在此补充;未收录的分区按商品域名的同类映射兜底。
|
||
*/
|
||
const TEMPLATE_PLATFORMS = {
|
||
pinduoduo: { host: 'fxpdd.dgjapp.com', type: 'Pinduoduo' },
|
||
toutiao: { host: 'fxdd.dgjapp.com', type: 'TouTiao' },
|
||
douyin: { host: 'fxdd.dgjapp.com', type: 'TouTiao' },
|
||
doudian: { host: 'fxdd.dgjapp.com', type: 'TouTiao' },
|
||
wxvideo: { host: 'fxdd.dgjapp.com', type: 'WxVideo' },
|
||
alibaba: { host: 'fxali.dgjapp.com', type: 'Alibaba' },
|
||
taobao: { host: 'fxali.dgjapp.com', type: 'Taobao' },
|
||
tmall: { host: 'fxali.dgjapp.com', type: 'Tmall' },
|
||
jingdong: { host: 'fxjd.dgjapp.com', type: 'JingDong' },
|
||
kuaishou: { host: 'fxtk.dgjapp.com', type: 'KuaiShou' },
|
||
};
|
||
|
||
/** 只能识别出域名时的兜底 PlatformType(每个域名取一个代表平台) */
|
||
const TEMPLATE_HOST_TYPES = {
|
||
'fxpdd.dgjapp.com': [ 'Pinduoduo' ],
|
||
'fxdd.dgjapp.com': [ 'TouTiao' ],
|
||
'fxali.dgjapp.com': [ 'Alibaba' ],
|
||
'fxjd.dgjapp.com': [ 'JingDong' ],
|
||
'fxtk.dgjapp.com': [ 'KuaiShou' ],
|
||
};
|
||
|
||
/**
|
||
* 订单/取号接口域名:与模板域名不同!旧系统 `$this->pingtais` 的口径是
|
||
* 淘宝/1688/视频号/小红书/快手都走 fxali,抖店走 fxdd,拼多多走 fxpdd,京东走 fxjd。
|
||
* 取错域名会查不到订单(实测:视频号订单只在 fxali 能查到)。
|
||
*/
|
||
const ORDER_HOSTS = {
|
||
pinduoduo: 'fxpdd.dgjapp.com',
|
||
toutiao: 'fxdd.dgjapp.com',
|
||
douyin: 'fxdd.dgjapp.com',
|
||
doudian: 'fxdd.dgjapp.com',
|
||
jingdong: 'fxjd.dgjapp.com',
|
||
jd: 'fxjd.dgjapp.com',
|
||
};
|
||
/** 未命中映射时的订单域名兜底(淘宝/视频号/小红书/快手/1688 等) */
|
||
const ORDER_HOST_FALLBACK = 'fxali.dgjapp.com';
|
||
|
||
/** 商品列表单页条数(平台允许 200) */
|
||
const PRODUCT_PAGE_SIZE = 200;
|
||
|
||
/**
|
||
* 店管家 PlatformType -> 系统预设平台编码(硬编码,新增平台时在此补充)。
|
||
* 系统预设见 app/lib/platformCode.js;未收录的统一落到 OTHER(其他)。
|
||
*/
|
||
const PLATFORM_TYPE_PRESETS = {
|
||
pinduoduo: 'PDD',
|
||
toutiao: 'DYXD',
|
||
douyin: 'DYXD',
|
||
doudian: 'DYXD',
|
||
wxvideo: 'SPH',
|
||
alibaba: '1688',
|
||
1688: '1688',
|
||
taobao: 'TB',
|
||
tmall: 'TM',
|
||
jingdong: 'JD',
|
||
jd: 'JD',
|
||
kuaishou: 'KS',
|
||
xiaohongshu: 'XHS',
|
||
dewu: 'DW',
|
||
meituan: 'MTYYJK',
|
||
offline: 'OFFLINE',
|
||
};
|
||
|
||
/**
|
||
* 把店管家的 PlatformType 转成系统预设平台(编码 + 名称)
|
||
* @param {*} platformType 店管家 PlatformType(如 Pinduoduo / TouTiao / WxVideo)
|
||
* @return {{code: string, name: string}} 预设平台
|
||
*/
|
||
function resolveOrderPlatform(platformType) {
|
||
const key = String(platformType == null ? '' : platformType).trim().toLowerCase();
|
||
const presetCode = PLATFORM_TYPE_PRESETS[key];
|
||
return resolvePlatform(presetCode || platformType);
|
||
}
|
||
|
||
/**
|
||
* 按 PlatformType 反查面单模板接口域名(未收录时返回空字符串)
|
||
* @param {*} platformType 店管家 PlatformType(如 Pinduoduo)
|
||
* @return {string} 模板接口域名
|
||
*/
|
||
function resolveTemplateHost(platformType) {
|
||
const key = String(platformType == null ? '' : platformType).trim().toLowerCase();
|
||
for (const preset of Object.values(TEMPLATE_PLATFORMS)) {
|
||
if (preset.type.toLowerCase() === key) return preset.host;
|
||
}
|
||
return '';
|
||
}
|
||
|
||
/**
|
||
* 按 PlatformType 取订单 / 取号接口域名(与模板域名不同,见 ORDER_HOSTS 说明)
|
||
* @param {*} platformType 店管家 PlatformType(如 WxVideo)
|
||
* @return {string} 订单接口域名
|
||
*/
|
||
function resolveOrderHost(platformType) {
|
||
const key = String(platformType == null ? '' : platformType).trim().toLowerCase();
|
||
return ORDER_HOSTS[key] || ORDER_HOST_FALLBACK;
|
||
}
|
||
|
||
/**
|
||
* 平台侧「已发货 / 已终结」的订单状态(ErpState):
|
||
* sended=已发货、success=交易成功、close=交易关闭,其余为各平台交易状态的等价写法。
|
||
* 这些订单平台已自行处理完毕,不需要进本系统的待审核,拉取时直接跳过。
|
||
*/
|
||
const FINISHED_ORDER_STATES = [
|
||
'sended',
|
||
'sendsuccess',
|
||
'success',
|
||
'tradeclosed',
|
||
'close',
|
||
'closed',
|
||
'finished',
|
||
'delivered',
|
||
'refundsuccess',
|
||
'refunded',
|
||
];
|
||
|
||
/**
|
||
* 订单是否已在平台侧发货或已终结(不需要本系统再处理)。
|
||
* 判断依据(任一命中即为已处理):
|
||
* - ErpState 属于已发货/已终结状态
|
||
* - 有 OnlineSendTime(平台发货时间)
|
||
* - 面单里存在 IsSended=true 的包裹
|
||
* - LogisticStatus > 0(已进入物流流程)
|
||
* 注意:PrintState / ExpressPrintTime 只表示面单已打印,未发货的订单仍需要处理,故不作为判定依据。
|
||
* @param {Object} row 店管家订单原始结构
|
||
* @return {boolean} 是否已发货/已终结
|
||
*/
|
||
function isOrderFinished(row) {
|
||
return describeFinishedOrder(row).finished;
|
||
}
|
||
|
||
/**
|
||
* 平台是否拒绝了「状态/商家」过滤条件(旧系统分区不支持,统一返回「服务器繁忙」)
|
||
* @param {Error} err 请求异常
|
||
* @return {boolean} 是否需要退化为只按时间窗查询
|
||
*/
|
||
function isFilterUnsupportedError(err) {
|
||
return /服务器繁忙|系统繁忙|Server is busy/i.test(String((err && err.message) || ''));
|
||
}
|
||
|
||
/**
|
||
* 判定平台侧是否已发货/已终结,并给出**可读原因**(用于自动作废备注,便于区分具体依据)
|
||
* @param {Object} row 店管家订单原始结构
|
||
* @return {{finished: boolean, reason: string}} finished=是否已处理,reason=命中的具体依据
|
||
*/
|
||
function describeFinishedOrder(row) {
|
||
const data = row || {};
|
||
const state = String(data.ErpState || data.Status || '').trim();
|
||
const signals = [];
|
||
if (state && FINISHED_ORDER_STATES.includes(state.toLowerCase())) {
|
||
signals.push(`平台订单状态 ErpState=${state}`);
|
||
}
|
||
const sendTime = String(data.OnlineSendTime || '').trim();
|
||
if (sendTime) signals.push(`平台已有发货时间 ${sendTime}`);
|
||
const waybills = Array.isArray(data.WaybillCodes) ? data.WaybillCodes : [];
|
||
const sentCount = waybills.filter(code => code && code.IsSended === true).length;
|
||
if (sentCount > 0) signals.push(`${sentCount} 个面单包裹已发货`);
|
||
const logistic = Number(data.LogisticStatus);
|
||
if (logistic > 0) signals.push(`物流状态已推进(LogisticStatus=${logistic})`);
|
||
if (!signals.length) return { finished: false, reason: '' };
|
||
return { finished: true, reason: signals.join('、') };
|
||
}
|
||
|
||
/**
|
||
* 商品状态是否为在售:平台不同分区返回的状态值不统一(published / 1 / db_del / jdp_delete 等)
|
||
* @param {string|number|null} status 平台商品状态
|
||
* @return {boolean} 是否在售
|
||
*/
|
||
function isProductOnSale(status) {
|
||
const value = String(status == null ? '' : status).trim().toLowerCase();
|
||
return value === '1' || value === 'published' || value === 'online' || value === 'onsale' || value === 'on_sale';
|
||
}
|
||
|
||
/**
|
||
* 转数字,非法值按 0 处理
|
||
* @param {*} value 原始值
|
||
* @return {number} 数字
|
||
*/
|
||
function toNumber(value) {
|
||
const num = Number(value);
|
||
return Number.isFinite(num) ? num : 0;
|
||
}
|
||
|
||
/**
|
||
* 截断字符串,避免超出表字段长度
|
||
* @param {*} value 原始值
|
||
* @param {number} max 最大长度
|
||
* @return {string} 截断后的字符串
|
||
*/
|
||
function truncate(value, max) {
|
||
return String(value == null ? '' : value).slice(0, max);
|
||
}
|
||
|
||
/** 单次请求超时(毫秒) */
|
||
const REQUEST_TIMEOUT_MS = 15000;
|
||
|
||
/**
|
||
* 模拟 Chrome 访问 html 页面的请求头(取自真实抓包)。
|
||
* 说明:HTTP/2 伪头(:authority / :method / :path / :scheme)由客户端按 URL 自动生成,不能手动设置;
|
||
* accept-encoding 交给 fetch 自动协商并解压,手动声明会导致响应不解压。
|
||
*/
|
||
const BROWSER_HEADERS = {
|
||
accept:
|
||
'text/html,application/xhtml+xml,application/xml;q=0.9,image/jxl,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
|
||
'accept-language': 'zh-CN,zh;q=0.9',
|
||
'cache-control': 'max-age=0',
|
||
priority: 'u=0, i',
|
||
'sec-ch-ua': '"Not:A-Brand";v="8", "Chromium";v="156", "Google Chrome";v="156"',
|
||
'sec-ch-ua-mobile': '?0',
|
||
'sec-ch-ua-platform': '"Windows"',
|
||
'sec-fetch-dest': 'document',
|
||
'sec-fetch-mode': 'navigate',
|
||
'sec-fetch-site': 'none',
|
||
'sec-fetch-user': '?1',
|
||
'upgrade-insecure-requests': '1',
|
||
'user-agent':
|
||
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/156.0.0.0 Safari/537.36',
|
||
};
|
||
|
||
/** 模拟浏览器 ajax 表单提交的请求头(登录接口为同源 XHR) */
|
||
const AJAX_HEADERS = {
|
||
accept: 'application/json, text/javascript, */*; q=0.01',
|
||
'accept-language': 'zh-CN,zh;q=0.9',
|
||
'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
|
||
origin: PORTAL_ORIGIN,
|
||
referer: PORTAL_URL,
|
||
'sec-ch-ua': '"Not:A-Brand";v="8", "Chromium";v="156", "Google Chrome";v="156"',
|
||
'sec-ch-ua-mobile': '?0',
|
||
'sec-ch-ua-platform': '"Windows"',
|
||
'sec-fetch-dest': 'empty',
|
||
'sec-fetch-mode': 'cors',
|
||
'sec-fetch-site': 'same-origin',
|
||
'user-agent':
|
||
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/156.0.0.0 Safari/537.36',
|
||
'x-requested-with': 'XMLHttpRequest',
|
||
};
|
||
|
||
/** 模拟工作台 ajax(GET 接口)的请求头,Referer 指向工作台 */
|
||
const WORKBENCH_AJAX_HEADERS = {
|
||
accept: 'application/json, text/javascript, */*; q=0.01',
|
||
'accept-language': 'zh-CN,zh;q=0.9',
|
||
referer: WORKBENCH_URL,
|
||
'sec-ch-ua': '"Not:A-Brand";v="8", "Chromium";v="156", "Google Chrome";v="156"',
|
||
'sec-ch-ua-mobile': '?0',
|
||
'sec-ch-ua-platform': '"Windows"',
|
||
'user-agent':
|
||
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/156.0.0.0 Safari/537.36',
|
||
'x-requested-with': 'XMLHttpRequest',
|
||
};
|
||
|
||
/**
|
||
* 登录表单字段加密:店管家要求 IsEnc=1 时字段值做 base64(URLSearchParams 会再对 = 等字符做 URL 编码)
|
||
* @param {string} value 原始值
|
||
* @return {string} base64 值
|
||
*/
|
||
function encodeField(value) {
|
||
return Buffer.from(String(value), 'utf8').toString('base64');
|
||
}
|
||
|
||
/**
|
||
* 读取响应里的 set-cookie(兼容没有 getSetCookie 的运行时)
|
||
* @param {Response} res fetch 响应
|
||
* @return {string[]} set-cookie 列表
|
||
*/
|
||
function getSetCookies(res) {
|
||
if (typeof res.headers.getSetCookie === 'function') return res.headers.getSetCookie();
|
||
const raw = res.headers.get('set-cookie');
|
||
return raw ? [ raw ] : [];
|
||
}
|
||
|
||
/**
|
||
* 合并 set-cookie 到已有 cookie:同名覆盖,其余保留
|
||
* @param {string} cookie 已有 cookie
|
||
* @param {string[]} setCookies 响应头 set-cookie
|
||
* @return {string} 合并后的 cookie
|
||
*/
|
||
function mergeCookie(cookie, setCookies) {
|
||
const jar = new Map();
|
||
for (const item of String(cookie || '').split(';')) {
|
||
const kv = item.trim();
|
||
const idx = kv.indexOf('=');
|
||
if (idx > 0) jar.set(kv.slice(0, idx), kv.slice(idx + 1));
|
||
}
|
||
for (const raw of setCookies) {
|
||
const kv = String(raw).split(';')[0].trim();
|
||
const idx = kv.indexOf('=');
|
||
if (idx > 0) jar.set(kv.slice(0, idx), kv.slice(idx + 1));
|
||
}
|
||
return Array.from(jar, ([ key, value ]) => `${key}=${value}`).join('; ');
|
||
}
|
||
|
||
/**
|
||
* 组装登录失败提示
|
||
* @param {{status: number, json: Object|null}} res 接口响应
|
||
* @return {string} 失败原因
|
||
*/
|
||
function describeFailure(res) {
|
||
const json = (res && res.json) || {};
|
||
const message = json.Message || json.ErrorCode || '未知错误';
|
||
return `${message}(HTTP ${res ? res.status : '-'})`;
|
||
}
|
||
|
||
/**
|
||
* 日期格式化为店管家订单查询使用的时间字符串(yyyy-MM-dd HH:mm:ss)
|
||
* @param {Date|string} value 时间
|
||
* @return {string} 时间字符串
|
||
*/
|
||
function formatOrderTime(value) {
|
||
const date = value instanceof Date ? value : new Date(value);
|
||
if (Number.isNaN(date.getTime())) return '';
|
||
const pad = num => String(num).padStart(2, '0');
|
||
return (
|
||
`${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ` +
|
||
`${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
|
||
);
|
||
}
|
||
|
||
/**
|
||
* 解析平台时间字符串(店管家返回 yyyy-MM-dd HH:mm:ss),非法值返回 null
|
||
* @param {*} value 平台时间
|
||
* @return {Date|null} 时间
|
||
*/
|
||
function parseOrderTime(value) {
|
||
const text = String(value == null ? '' : value).trim();
|
||
if (!text) return null;
|
||
const date = new Date(text.replace(' ', 'T'));
|
||
return Number.isNaN(date.getTime()) ? null : date;
|
||
}
|
||
|
||
/**
|
||
* 订单明细的平台规格ID:不同平台字段口径不一致
|
||
* (抖店/淘宝用 SkuId 存规格ID,视频号则用 SkuCode 存规格ID、SkuId 存规格名称)
|
||
* @param {Object} data 明细原始结构
|
||
* @return {string} 平台规格ID,取不到时返回空字符串
|
||
*/
|
||
function resolveOrderSkuId(data) {
|
||
const looksLikeId = value => /^[0-9A-Za-z_-]{4,64}$/.test(value);
|
||
const candidates = [ data.SkuId, data.SkuCode ];
|
||
for (const item of candidates) {
|
||
const value = String(item == null ? '' : item).trim();
|
||
if (value && looksLikeId(value)) return value;
|
||
}
|
||
return '';
|
||
}
|
||
|
||
/**
|
||
* 递归收集打印数据里的运单号(旧系统口径:PrintDataList.task.documents[].documentID)
|
||
* @param {*} value 已解析的打印数据对象/数组
|
||
* @param {string[]} out 收集结果
|
||
* @return {void}
|
||
*/
|
||
function collectDocumentIds(value, out) {
|
||
if (!value || typeof value !== 'object') return;
|
||
if (Array.isArray(value)) {
|
||
for (const item of value) collectDocumentIds(item, out);
|
||
return;
|
||
}
|
||
for (const [ key, item ] of Object.entries(value)) {
|
||
if ((key === 'documentID' || key === 'DocumentID') && (typeof item === 'string' || typeof item === 'number')) {
|
||
const text = String(item).trim();
|
||
if (text) out.push(text);
|
||
continue;
|
||
}
|
||
collectDocumentIds(item, out);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 解析打印数据(字符串或对象),提取运单号
|
||
* @param {*} printInfo 打印数据
|
||
* @return {string[]} 运单号列表
|
||
*/
|
||
function extractWaybillsFromPrintInfo(printInfo) {
|
||
if (!printInfo) return [];
|
||
let parsed = printInfo;
|
||
if (typeof printInfo === 'string') {
|
||
try {
|
||
parsed = JSON.parse(printInfo);
|
||
} catch {
|
||
return [];
|
||
}
|
||
}
|
||
const out = [];
|
||
collectDocumentIds(parsed, out);
|
||
return out;
|
||
}
|
||
|
||
/**
|
||
* 从 ExpressPrint 响应的 Data.WaybillCode[] 里提取运单号
|
||
* 兼容:WaybillCode / LogisticCode / MailNo 字段、OrderInfo 嵌套、PrintInfo 里的 documentID
|
||
* @param {Array} items Data.WaybillCode 数组
|
||
* @return {string[]} 去重后的运单号
|
||
*/
|
||
function extractWaybillCodes(items) {
|
||
const out = [];
|
||
for (const item of Array.isArray(items) ? items : []) {
|
||
if (!item || typeof item !== 'object') continue;
|
||
for (const key of [ 'WaybillCode', 'LogisticCode', 'MailNo', 'WaybillNo' ]) {
|
||
const value = item[key];
|
||
if (typeof value === 'string' && value.trim()) out.push(value.trim());
|
||
}
|
||
const nested = item.OrderInfo && item.OrderInfo.OrderInfo;
|
||
if (nested && typeof nested === 'object') {
|
||
for (const key of [ 'WaybillCode', 'LastWaybillCode' ]) {
|
||
const value = nested[key];
|
||
if (typeof value === 'string' && value.trim()) out.push(value.trim());
|
||
}
|
||
}
|
||
for (const key of [ 'PrintInfo', 'PrintData' ]) {
|
||
out.push(...extractWaybillsFromPrintInfo(item[key]));
|
||
}
|
||
}
|
||
return [ ...new Set(out) ];
|
||
}
|
||
|
||
/**
|
||
* 从 ExpressPrint 响应的 Data.PrintHistoryIds[] 里提取打印记录
|
||
*
|
||
* 平台每打印一张面单就新增一条打印历史,`Id` 即打印记录ID(printHistoryId),
|
||
* 重打/作废/查打印记录(`PrintHistory/LoadPrintData`)都要用它。多包裹时数组长度 = 张数。
|
||
* @param {Object} printed ExpressPrint 响应
|
||
* @return {Array<{id: string, pid: string, waybill_code: string, batch_index: number|null}>} 打印记录
|
||
*/
|
||
function extractPrintHistoryIds(printed) {
|
||
const list = printed && printed.Data && printed.Data.PrintHistoryIds;
|
||
const out = [];
|
||
for (const item of Array.isArray(list) ? list : []) {
|
||
if (!item || typeof item !== 'object') continue;
|
||
const id = String(item.Id == null ? '' : item.Id).trim();
|
||
if (!id) continue;
|
||
out.push({
|
||
id,
|
||
pid: String(item.Pid == null ? '' : item.Pid).trim(),
|
||
waybill_code: String(item.WaybillCode == null ? '' : item.WaybillCode).trim(),
|
||
batch_index: item.BatchIndex == null ? null : Number(item.BatchIndex),
|
||
});
|
||
}
|
||
return out;
|
||
}
|
||
|
||
/**
|
||
* 取平台返回的打印单据(`Data.PrintDataList.task.documents[]`)
|
||
*
|
||
* 店管家的 `ExpressPrint` 返回里,运单号在 `Data.WaybillCode[]`,而**面单打印数据在
|
||
* `Data.PrintDataList.task.documents[]`**(`documentID` = 运单号,`printInfo` = 打印数据,
|
||
* `contents[]` = 需要加密打印的场景下的 encryptedData / signature / ver)。
|
||
* 一次请求可能返回多个 document(多包裹),这里按运单号匹配,匹配不到取第一个。
|
||
* @param {Object} printed ExpressPrint 响应
|
||
* @param {string} waybillCode 本次运单号
|
||
* @return {Object|null} document 对象,未找到为 null
|
||
*/
|
||
function firstPrintDocument(printed, waybillCode) {
|
||
const documents = printed && printed.Data && printed.Data.PrintDataList &&
|
||
printed.Data.PrintDataList.task && printed.Data.PrintDataList.task.documents;
|
||
const list = Array.isArray(documents) ? documents.filter(doc => doc && typeof doc === 'object') : [];
|
||
if (!list.length) return null;
|
||
const matched = waybillCode ? list.find(doc => String(doc.documentID || '').trim() === String(waybillCode).trim()) : null;
|
||
return matched || list[0];
|
||
}
|
||
|
||
/**
|
||
* 取第一条打印数据(字符串化,便于原样回传给打印端)
|
||
*
|
||
* 顺序:`Data.PrintDataList.task.documents[].printInfo`(店管家实际下发的打印数据,
|
||
* base64 编码的 URL-encoded JSON,WMS 打印端按原样塞进 `task.printInfo`)→
|
||
* `Data.WaybillCode[].PrintInfo / PrintData / PrintDataJson`(其它平台/旧版返回)。
|
||
* @param {Array} items Data.WaybillCode 数组
|
||
* @param {Object} printed ExpressPrint 响应
|
||
* @param {string} waybillCode 本次运单号
|
||
* @return {string} 打印数据,未找到为空串
|
||
*/
|
||
function firstPrintInfo(items, printed, waybillCode) {
|
||
const document = firstPrintDocument(printed, waybillCode);
|
||
if (document && document.printInfo) {
|
||
return typeof document.printInfo === 'string' ? document.printInfo : JSON.stringify(document.printInfo);
|
||
}
|
||
for (const item of Array.isArray(items) ? items : []) {
|
||
const value = item && (item.PrintInfo || item.PrintData || item.PrintDataJson);
|
||
if (!value) continue;
|
||
return typeof value === 'string' ? value : JSON.stringify(value);
|
||
}
|
||
return '';
|
||
}
|
||
|
||
/**
|
||
* 从 document 的 contents[0] 取打印附加信息(旧系统同口径)
|
||
*
|
||
* 旧系统 `Dianguanjia.php` 取的是
|
||
* `PrintDataList.task.documents[0].contents[0]` 的 `signature` / `encryptedData` / `ver`;
|
||
* 快手还会下发逐单加密密钥 `key`(base64,约 172 字符,与密文不同),打印端必需;
|
||
* 菜鸟系(淘宝/天猫等)另外下发主面单模板地址 `templateURL`(菜鸟打印必需)。
|
||
* 视频号等自定义模板场景平台不返回 `contents`,此时各值都为空串。
|
||
* @param {Object} document 打印单据
|
||
* @return {{signature: string, encryptprintinfo: string, key: string, template_url: string, ver: string}} 签名、加密打印数据、快手密钥、模板地址、版本
|
||
*/
|
||
function extractDocumentContents(document) {
|
||
const empty = { signature: '', encryptprintinfo: '', key: '', template_url: '', ver: '' };
|
||
const contents = document && document.contents;
|
||
const first = Array.isArray(contents) ? contents[0] : null;
|
||
if (!first || typeof first !== 'object') return empty;
|
||
return {
|
||
signature: typeof first.signature === 'string' ? first.signature : '',
|
||
encryptprintinfo: typeof first.encryptedData === 'string' ? first.encryptedData : '',
|
||
key: typeof first.key === 'string' ? first.key : '',
|
||
template_url: typeof first.templateURL === 'string' ? first.templateURL : '',
|
||
ver: first.ver == null ? '' : String(first.ver),
|
||
};
|
||
}
|
||
|
||
/** 菜鸟系平台(菜鸟打印只认 printinfo 整包 JSON,见 buildWaybillPrintFields) */
|
||
const CAINIAO_PLATFORM_CODES = new Set([ 'TB', 'TM', 'TGC', '1688' ]);
|
||
|
||
/**
|
||
* 组装回给 WMS 的面单打印字段(各平台口径不同)
|
||
*
|
||
* - 快手(KS):平台把加密面单放在 `contents[0].encryptedData`、逐单密钥放在 `contents[0].key`,
|
||
* 文档里的 `printInfo` 为空。菠萝派取号的做法是「密文 -> printinfo、密钥 -> encryptprintinfo」,
|
||
* WMS 快手打印按该口径取 encryptedData / key,这里对齐,并把 key 单独返回;
|
||
* - 菜鸟系(淘宝/天猫/淘工厂/1688):平台下发的 `printInfo` 为空,
|
||
* 菜鸟打印只认整包 JSON `{ encryptedData, signature, ver, templateURL }`,这里按该形态回拼;
|
||
* - 其它平台:`printinfo` 原样用平台下发的打印数据,`encryptprintinfo` 仍是 `contents[0].encryptedData`。
|
||
* @param {Object} options 参数
|
||
* @param {string} options.platformCode 系统预设平台编码(如 KS / TB)
|
||
* @param {Object} options.contents extractDocumentContents 的结果
|
||
* @param {string} [options.documentPrintInfo] 平台下发的打印数据(documents[].printInfo)
|
||
* @return {{printinfo: string, encryptprintinfo: string, key: string}} 打印字段
|
||
*/
|
||
function buildWaybillPrintFields({ platformCode, contents, documentPrintInfo = '' }) {
|
||
const code = String(platformCode || '').trim().toUpperCase();
|
||
const encryptedData = String((contents && contents.encryptprintinfo) || '');
|
||
const key = String((contents && contents.key) || '');
|
||
const printData = String(documentPrintInfo || '');
|
||
|
||
if (code === 'KS') {
|
||
return {
|
||
printinfo: encryptedData || printData,
|
||
encryptprintinfo: key,
|
||
key,
|
||
};
|
||
}
|
||
|
||
if (CAINIAO_PLATFORM_CODES.has(code) && !printData && encryptedData) {
|
||
const payload = { encryptedData };
|
||
const signature = String((contents && contents.signature) || '');
|
||
const version = String((contents && contents.ver) || '');
|
||
const templateUrl = String((contents && contents.template_url) || '');
|
||
if (signature) payload.signature = signature;
|
||
if (version) payload.ver = version;
|
||
if (templateUrl) payload.templateURL = templateUrl;
|
||
return {
|
||
printinfo: JSON.stringify(payload),
|
||
encryptprintinfo: encryptedData,
|
||
key,
|
||
};
|
||
}
|
||
|
||
return {
|
||
printinfo: printData,
|
||
encryptprintinfo: encryptedData,
|
||
key,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 构造 `Orders[0][WaybillCodes][]`(平台「新单号打印」请求里带的当前号清单)
|
||
*
|
||
* 平台前端在重新取号时会把这个订单已有的运单号(含 `WaybillCodeId` / `Pid`)一起回传,
|
||
* 平台据此分配**下一个**号(`WaybillCodePid` 的第二段自增)。不传时平台容易直接复用旧号。
|
||
* @param {Object} row 平台订单行(含 WaybillCodes / SubOrders)
|
||
* @param {string} templateId 面单模板ID
|
||
* @param {string} expressCode 快递编码
|
||
* @return {Array|string} 运单号清单;没有历史号时返回空串(表单里表现为空值)
|
||
*/
|
||
function buildWaybillCodesBlock(row, templateId, expressCode) {
|
||
const list = Array.isArray(row.WaybillCodes) ? row.WaybillCodes.filter(item => item && item.WaybillCode) : [];
|
||
if (!list.length) return '';
|
||
const subs = Array.isArray(row.SubOrders) ? row.SubOrders : [];
|
||
return list.map(entry => ({
|
||
TemplateId: String(entry.TemplateId || templateId || ''),
|
||
TemplateType: entry.TemplateType == null ? '' : entry.TemplateType,
|
||
ExpressCpCode: entry.ExpressCpCode || expressCode || '',
|
||
ExpressName: entry.ExpressName || '',
|
||
WaybillCode: entry.WaybillCode,
|
||
ChildWaybillCode: '',
|
||
ChildWaybillCodes: '',
|
||
CompanyCode: entry.CompanyCode || entry.ExpressCpCode || expressCode || '',
|
||
WaybillCodeId: entry.WaybillCodeId == null ? '' : entry.WaybillCodeId,
|
||
CreateDate: entry.CreateDate || '',
|
||
IsSended: entry.IsSended === true,
|
||
TotalWeight: 0,
|
||
SendType: 0,
|
||
Status: entry.Status == null ? 1 : entry.Status,
|
||
Pid: entry.Pid || '',
|
||
WaybillCodeOrderProducts: subs.map(sub => ({
|
||
MasterId: `${row.Id}_${entry.WaybillCode}_iD`,
|
||
OrderItemId: sub.OrderItemId,
|
||
OrderItemIdStr: sub.OrderItemId,
|
||
Quantity: 1,
|
||
OrderItemCode: sub.OrderItemCode,
|
||
WaybillCodeId: entry.WaybillCodeId == null ? '' : entry.WaybillCodeId,
|
||
})),
|
||
}));
|
||
}
|
||
|
||
/**
|
||
* 按 PHP `http_build_query` 口径把对象展开成表单
|
||
*
|
||
* 店管家(ASP.NET MVC)按 PHP 风格的嵌套键解析表单:数组元素是
|
||
* `orders[0][SourceShopId]=...`,**不是** `orders[0]={"SourceShopId":...}`。
|
||
* 用 JSON 字符串提交会被平台判为参数缺失(表现为「打印校验失败,系统异常」)。
|
||
*
|
||
* 取值口径与 PHP 一致:`null/undefined` → 空串;`true` → `1`;`false` → 空串;
|
||
* 空数组/空对象 → 空串;数字/字符串 → 原样。
|
||
* @param {Object} data 表单数据(可含嵌套对象/数组)
|
||
* @return {URLSearchParams} 可直接作为 x-www-form-urlencoded body
|
||
*/
|
||
function buildPhpForm(data) {
|
||
const form = new URLSearchParams();
|
||
|
||
/**
|
||
* 递归写入一个值
|
||
* @param {*} value 值
|
||
* @param {string} key 字段名(含嵌套括号)
|
||
* @return {void}
|
||
*/
|
||
const walk = (value, key) => {
|
||
if (value === null || value === undefined) {
|
||
form.append(key, '');
|
||
return;
|
||
}
|
||
if (typeof value === 'boolean') {
|
||
form.append(key, value ? '1' : '');
|
||
return;
|
||
}
|
||
if (Array.isArray(value)) {
|
||
if (!value.length) {
|
||
form.append(key, '');
|
||
return;
|
||
}
|
||
value.forEach((item, index) => walk(item, `${key}[${index}]`));
|
||
return;
|
||
}
|
||
if (typeof value === 'object') {
|
||
const keys = Object.keys(value);
|
||
if (!keys.length) {
|
||
form.append(key, '');
|
||
return;
|
||
}
|
||
for (const childKey of keys) walk(value[childKey], `${key}[${childKey}]`);
|
||
return;
|
||
}
|
||
form.append(key, String(value));
|
||
};
|
||
|
||
for (const [ key, value ] of Object.entries(data || {})) walk(value, key);
|
||
return form;
|
||
}
|
||
|
||
/**
|
||
* 店管家(dgj)外部打单平台服务。
|
||
*
|
||
* 平台记录:external_print_platforms.code = 'dgj'(名称「店管家」,fetch_waybill_no = 0 即不回平台取号)。
|
||
* 该平台的全部处理逻辑(登录、打单、取号等)都写在本文件里,不要散落到别处;
|
||
* 新增平台时同样新建 `<平台 code>.js`,并把 static code 改成对应平台标识。
|
||
*
|
||
* 登录流程(与浏览器一致):
|
||
* 1. GET /ffaccount 建立会话(拿到 WAF/ASP.NET 基础 cookie)
|
||
* 2. POST /FFAccount/BindWeChatPrompt(是否需要提示绑定微信)
|
||
* 3. POST /FFAccount/LoginPortal(返回 Token / RedirectUrl,并通过 set-cookie 下发登录态)
|
||
* 4. GET /api/user/GetUserInfo?token=<Token>(需同时带 cookie)确认登录态并拿账号信息
|
||
* 成功后把 token 与 cookie 一并写回账号表,后续检查/调用复用。
|
||
*
|
||
* 注意:店管家工作台同时依赖 token 与 cookie,仅保存 cookie 无法获取账号信息(返回 401)。
|
||
* 登录态检查走 GetUserInfo(轻量 JSON,避免每次拉取 500KB 的工作台页面)。
|
||
*/
|
||
class DgjService extends PrintPlatformService {
|
||
static get code() {
|
||
return 'dgj';
|
||
}
|
||
|
||
/**
|
||
* 店管家站点根地址(平台配置的链接未带协议时补 https://)
|
||
* @return {string} 站点根地址
|
||
*/
|
||
get siteUrl() {
|
||
const url = String(this.platform.url || '').trim();
|
||
if (!url) throw new Error('店管家平台未配置链接地址(external_print_platforms.url)');
|
||
return /^https?:\/\//i.test(url) ? url : `https://${url}`;
|
||
}
|
||
|
||
/**
|
||
* 统一平台请求入口(请求拦截器)。
|
||
* 平台接口返回 401 表示登录已失效,这里统一把账号登录状态记为 0;
|
||
* 其余状态交由调用方按业务判断。
|
||
* @param {string} url 完整请求地址
|
||
* @param {Object} [options] fetch 选项(method / headers / body 等)
|
||
* @return {Promise<{status: number, json: Object|null, text: string, setCookies: string[]}>} 响应
|
||
*/
|
||
async request(url, options = {}) {
|
||
// 全局限流:平台按服务商维度限流(实测 600 QPS),所有请求(取号/校验/发货/回读/商品)统一排队
|
||
await waitRequestTurn();
|
||
const res = await fetch(url, {
|
||
redirect: 'follow',
|
||
...options,
|
||
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
||
});
|
||
const text = await res.text();
|
||
let json = null;
|
||
try {
|
||
json = JSON.parse(text);
|
||
} catch {
|
||
json = null;
|
||
}
|
||
|
||
if (res.status === 401) {
|
||
await this.saveLoginStatus(0);
|
||
}
|
||
|
||
return { status: res.status, json, text, setCookies: getSetCookies(res) };
|
||
}
|
||
|
||
/**
|
||
* 拉取工作台当前登录账号信息(需 token + cookie,缺一不可)
|
||
* @param {string} [token] 登录 token,默认取账号已保存的 token
|
||
* @param {string} [cookie] 会话 cookie,默认取账号已保存的 cookie
|
||
* @return {Promise<{success: boolean, status: number, message: string, data: Object|null, setCookies: string[]}>} 账号信息
|
||
*/
|
||
async getUserInfo(token = this.token, cookie = this.cookie) {
|
||
const tk = String(token || '').trim();
|
||
if (!tk) throw new Error('店管家账号未保存登录 token,无法获取账号信息');
|
||
|
||
const query = new URLSearchParams({
|
||
traceId: '',
|
||
dbname: '',
|
||
dataFlag: '',
|
||
IsCustomerOrder: 'false',
|
||
FxPageType: '1',
|
||
_: String(Date.now()),
|
||
token: tk,
|
||
});
|
||
|
||
const headers = { ...WORKBENCH_AJAX_HEADERS };
|
||
if (cookie) headers.cookie = cookie;
|
||
|
||
const res = await this.request(`${USER_INFO_URL}?${query.toString()}`, { method: 'GET', headers });
|
||
|
||
const success = res.status === 200 && !!res.json && res.json.Success === true;
|
||
if (success) await this.saveLoginStatus(1);
|
||
|
||
return {
|
||
success,
|
||
status: res.status,
|
||
message: (res.json && res.json.Message) || '',
|
||
data: success && res.json.Data ? res.json.Data : null,
|
||
setCookies: res.setCookies,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 拉取工作台分区信息(商家列表接口需要其中的 DbName;商品接口需要按分区逐个查询)
|
||
* @param {string} [token] 登录 token,默认取账号已保存的 token
|
||
* @param {string} [cookie] 会话 cookie,默认取账号已保存的 cookie
|
||
* @param {string} [host] 分区信息所属域名,默认工作台域名
|
||
* @return {Promise<{success: boolean, status: number, message: string, data: Object|null}>} 分区信息
|
||
*/
|
||
async getAreasInfo(token = this.token, cookie = this.cookie, host = WORKBENCH_HOST) {
|
||
const tk = String(token || '').trim();
|
||
if (!tk) return { success: false, status: 0, message: '账号未保存登录 token', data: null };
|
||
|
||
const query = new URLSearchParams({ token: tk, dbname: '' });
|
||
const headers = { ...WORKBENCH_AJAX_HEADERS, referer: `https://${host}/` };
|
||
if (cookie) headers.cookie = cookie;
|
||
|
||
const res = await this.request(`https://${host}${AREAS_INFO_PATH}?${query.toString()}`, { method: 'GET', headers });
|
||
const success = res.status === 200 && !!res.json && res.json.Success === true;
|
||
|
||
return {
|
||
success,
|
||
status: res.status,
|
||
message: (res.json && res.json.Message) || '',
|
||
data: success && res.json.Data ? res.json.Data : null,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 拉取当前账号的商家列表(店管家的「商家」即 OMS 的店铺)。
|
||
* 返回统一结构,上层(控制器/前端)不直接依赖店管家字段。
|
||
* @param {Object} [options] 查询参数
|
||
* @param {number} [options.pageIndex] 页码,从 1 开始
|
||
* @param {number} [options.pageSize] 每页条数(最大 200)
|
||
* @param {string} [options.keyword] 关键词(商家名称/手机号)
|
||
* @return {Promise<{total: number, list: Array}>} 统一的店铺列表
|
||
*/
|
||
async listShops(options = {}) {
|
||
if (!this.token || !this.cookie) {
|
||
throw new Error('账号未登录:缺少 token 或 cookie,请先登录');
|
||
}
|
||
|
||
const pageIndex = Math.max(1, Number.parseInt(options.pageIndex, 10) || 1);
|
||
const pageSize = Math.min(200, Math.max(1, Number.parseInt(options.pageSize, 10) || 20));
|
||
const keyword = String(options.keyword || '');
|
||
|
||
// 商家列表接口需要 traceId 与 dbname,取不到时按空值请求
|
||
let traceId = '';
|
||
let dbName = '';
|
||
try {
|
||
const info = await this.getUserInfo();
|
||
traceId = (info.data && info.data.TraceId) || '';
|
||
const areas = await this.getAreasInfo();
|
||
dbName = (areas.data && areas.data.DbName) || '';
|
||
} catch {
|
||
// 忽略:上下文参数缺失不阻断列表查询
|
||
}
|
||
|
||
const query = new URLSearchParams({
|
||
token: this.token,
|
||
traceId,
|
||
dbname: dbName,
|
||
dataFlag: '',
|
||
key: keyword,
|
||
status: '0s',
|
||
pageIndex: String(pageIndex),
|
||
pageSize: String(pageSize),
|
||
IsCustomerOrder: 'false',
|
||
FxPageType: '1',
|
||
});
|
||
|
||
const headers = { ...WORKBENCH_AJAX_HEADERS };
|
||
if (this.cookie) headers.cookie = this.cookie;
|
||
|
||
const res = await this.request(`${AGENT_LIST_URL}?${query.toString()}`, { method: 'GET', headers });
|
||
if (res.status === 401) {
|
||
throw new Error(`店管家登录已失效:${(res.json && res.json.Message) || 'token is invalid'}`);
|
||
}
|
||
if (!res.json || res.json.Success !== true) {
|
||
const reason = (res.json && (res.json.Message || res.json.ErrorCode)) || `HTTP ${res.status}`;
|
||
throw new Error(`拉取店管家商家列表失败:${reason}`);
|
||
}
|
||
|
||
const data = res.json.Data || {};
|
||
const list = Array.isArray(data.List) ? data.List.map(item => this.normalizeShop(item)) : [];
|
||
return { total: Number(data.Total) || list.length, list };
|
||
}
|
||
|
||
/**
|
||
* 把店管家商家结构转换为统一的店铺结构(其他平台按同样结构返回即可)
|
||
* @param {Object} item 店管家商家原始结构
|
||
* @return {Object} 统一店铺结构
|
||
*/
|
||
normalizeShop(item) {
|
||
const data = item || {};
|
||
return {
|
||
external_id: String(data.Id == null ? '' : data.Id),
|
||
name: data.Remark || data.UserName || data.NickName || data.RemarkName || '',
|
||
contact_name: data.SenderName || data.Remark || '',
|
||
contact_phone: data.SenderMobile || data.Mobile || '',
|
||
status: Number(data.Status) === 0 ? 0 : 1,
|
||
remark: data.RemarkName || '',
|
||
raw: data,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 根据商家的分区信息确定要查询的商品域名。
|
||
* 商家在店管家的 DbAreas 里记录了所在分区(抖店/拼多多/精选/京东),
|
||
* 商品接口按分区域名部署;识别不出分区时兜底查询全部域名,避免漏商品。
|
||
* @param {Object} externalData 商家原始结构(shops.external_data)
|
||
* @return {string[]} 商品接口域名列表
|
||
*/
|
||
resolveProductHosts(externalData) {
|
||
const areas = Array.isArray(externalData && externalData.DbAreas) ? externalData.DbAreas : [];
|
||
const hosts = [];
|
||
for (const area of areas) {
|
||
const host = AREA_PRODUCT_HOSTS[String((area && area.DbName) || '').toLowerCase()];
|
||
if (host && !hosts.includes(host)) hosts.push(host);
|
||
}
|
||
return hosts.length ? hosts : FALLBACK_PRODUCT_HOSTS.slice();
|
||
}
|
||
|
||
/**
|
||
* 归纳商家的分区声明:每个平台域名下是否声明了「新系统分区 / 老分区」
|
||
*
|
||
* 商家结构里的 `DbAreas[]` 带 `IsNewSystem` 标志(如 toutiao 抖店-二区 true、toutiao 抖店 false),
|
||
* 平台页面的「所在区」就是它的 NickName。老分区只用来存放迁移前的历史单,
|
||
* 因此店铺没声明老分区时可以直接跳过该平台的老分区,不必每次都白拉一遍历史数据。
|
||
* @param {Object} externalData 商家原始结构(shops.external_data)
|
||
* @return {Object} host → { hasNew, hasLegacy }
|
||
*/
|
||
resolveAreaFlags(externalData) {
|
||
const areas = Array.isArray(externalData && externalData.DbAreas) ? externalData.DbAreas : [];
|
||
const flags = {};
|
||
for (const area of areas) {
|
||
const host = AREA_PRODUCT_HOSTS[String((area && area.DbName) || '').toLowerCase()];
|
||
if (!host) continue;
|
||
if (!flags[host]) flags[host] = { hasNew: false, hasLegacy: false };
|
||
if (area.IsNewSystem) flags[host].hasNew = true;
|
||
else flags[host].hasLegacy = true;
|
||
}
|
||
return flags;
|
||
}
|
||
|
||
/**
|
||
* 该分区是否支持「状态/商家」过滤(进程内缓存,避免每次同步都去撞一次「服务器繁忙」)
|
||
* @param {string} host 接口域名
|
||
* @param {string} dbname 分区库名
|
||
* @return {boolean|null} true=支持 false=不支持 null=未知
|
||
*/
|
||
filterSupported(host, dbname) {
|
||
const cached = AREA_FILTER_SUPPORT.get(`${host}|${dbname}`);
|
||
if (!cached) return null;
|
||
if (Date.now() - cached.at > AREA_FILTER_SUPPORT_TTL_MS) {
|
||
AREA_FILTER_SUPPORT.delete(`${host}|${dbname}`);
|
||
return null;
|
||
}
|
||
return cached.ok;
|
||
}
|
||
|
||
/**
|
||
* 记录分区是否支持「状态/商家」过滤
|
||
* @param {string} host 接口域名
|
||
* @param {string} dbname 分区库名
|
||
* @param {boolean} ok 是否支持
|
||
* @return {void} 无返回值
|
||
*/
|
||
rememberFilterSupport(host, dbname, ok) {
|
||
AREA_FILTER_SUPPORT.set(`${host}|${dbname}`, { ok, at: Date.now() });
|
||
}
|
||
|
||
/**
|
||
* 解析店铺需要拉取面单模板的目标(模板接口域名 + PlatformType + 分区库名)。
|
||
* 优先级:商家分区 DbAreas/DbArea 里的 DbName(如 pinduoduo)→ 展开该分区的全部库;
|
||
* 识别不出分区时按商品域名兜底,每个域名取一个代表 PlatformType。
|
||
* @param {Object} shop OMS 店铺记录(type=2,external_data 为商家原始结构)
|
||
* @return {Promise<Array<{host: string, platformType: string, dbname: string, areaName: string}>>} 目标列表
|
||
*/
|
||
async resolveTemplateTargets(shop) {
|
||
const data = (shop && shop.external_data) || {};
|
||
const areaRows = [
|
||
...(Array.isArray(data.DbAreas) ? data.DbAreas : []),
|
||
...(Array.isArray(data.DbArea) ? data.DbArea : []),
|
||
];
|
||
const presets = [];
|
||
for (const row of areaRows) {
|
||
const key = String((row && (row.DbName || row.Name)) || '').toLowerCase();
|
||
const preset = TEMPLATE_PLATFORMS[key];
|
||
if (!preset) continue;
|
||
if (!presets.some(item => item.host === preset.host && item.type === preset.type)) presets.push(preset);
|
||
}
|
||
if (!presets.length) {
|
||
for (const host of this.resolveProductHosts(data)) {
|
||
for (const type of TEMPLATE_HOST_TYPES[host] || []) {
|
||
if (!presets.some(item => item.host === host && item.type === type)) presets.push({ host, type });
|
||
}
|
||
}
|
||
}
|
||
|
||
const targets = [];
|
||
for (const preset of presets) {
|
||
const areas = await this.listProductAreas(preset.host);
|
||
for (const area of areas) {
|
||
targets.push({ host: preset.host, platformType: preset.type, dbname: area.dbname, areaName: area.name });
|
||
}
|
||
}
|
||
return targets;
|
||
}
|
||
|
||
/**
|
||
* 拉取一个平台域名 / 分区下的面单模板(快递接口)列表
|
||
* @param {string} host 模板接口域名
|
||
* @param {Object} options 查询参数
|
||
* @param {string} options.traceId 登录上下文 traceId
|
||
* @param {string} options.dbname 分区库名
|
||
* @param {string} options.platformType 店管家 PlatformType(如 Pinduoduo)
|
||
* @return {Promise<Array>} 平台原始模板列表
|
||
*/
|
||
async fetchTemplateList(host, { traceId, dbname, platformType }) {
|
||
const query = new URLSearchParams({
|
||
token: this.token,
|
||
traceId: traceId || '',
|
||
dbname: dbname || '',
|
||
dataFlag: '',
|
||
});
|
||
const form = new URLSearchParams({
|
||
platformType: platformType || '',
|
||
isDefault: 'false',
|
||
IsCustomerOrder: 'false',
|
||
FxPageType: '2',
|
||
});
|
||
const headers = {
|
||
accept: 'application/json, text/javascript, */*; q=0.01',
|
||
'accept-language': 'zh-CN,zh;q=0.9',
|
||
'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
|
||
referer: `https://${host}/NewOrder/WaitOrder`,
|
||
'user-agent': BROWSER_HEADERS['user-agent'],
|
||
'x-requested-with': 'XMLHttpRequest',
|
||
};
|
||
if (this.cookie) headers.cookie = this.cookie;
|
||
|
||
const res = await this.request(`https://${host}${TEMPLATE_LIST_PATH}?${query.toString()}`, {
|
||
method: 'POST',
|
||
headers,
|
||
body: form.toString(),
|
||
});
|
||
if (res.status === 401) {
|
||
throw new Error(`店管家登录已失效:${(res.json && res.json.Message) || 'token is invalid'}`);
|
||
}
|
||
if (!res.json || res.json.Success !== true) {
|
||
const reason = (res.json && (res.json.Message || res.json.ErrorCode)) || `HTTP ${res.status}`;
|
||
throw new Error(reason);
|
||
}
|
||
if (Array.isArray(res.json.Data)) return res.json.Data;
|
||
return Array.isArray(res.json.Data && res.json.Data.List) ? res.json.Data.List : [];
|
||
}
|
||
|
||
/**
|
||
* 把平台模板结构转换为统一结构(上层不直接依赖店管家字段)
|
||
* @param {Object} item 平台模板原始结构
|
||
* @param {Object} target 拉取目标(host / platformType / dbname)
|
||
* @return {Object} 统一模板结构
|
||
*/
|
||
normalizeExpressTemplate(item, target) {
|
||
const data = item || {};
|
||
// 平台归属优先取模板自身的 TemplateTypeShort(如小红书模板挂在抖店分区下,
|
||
// CloudPlatform / 分区 PlatformType 仍是 TouTiao),其次才用云端平台与分区类型兜底
|
||
const platformType = String(
|
||
data.TemplateTypeShort || data.CloudPlatform || data.PlatformType || target.platformType || ''
|
||
).trim();
|
||
const platform = resolveOrderPlatform(platformType);
|
||
return {
|
||
template_id: String(data.Id == null ? '' : data.Id),
|
||
template_name: truncate(data.TemplateName, 128),
|
||
platform_type: truncate(platformType, 32),
|
||
platform_code: platform.code,
|
||
platform_name: platform.name,
|
||
express_company_id: toNumber(data.ExpressCompanyId),
|
||
express_company_code: truncate(data.ExpressCompanyCode, 50),
|
||
express_company_name: truncate(data.ExpressCompanyName, 100),
|
||
shop_id: toNumber(data.ShopId),
|
||
shop_name: truncate(data.ShopName, 128),
|
||
dbname: truncate(target.dbname, 128),
|
||
// 菜鸟授权网点ID:同平台下不同授权网点取值不同,取号时随结果回给 WMS 便于分店/多网点归集
|
||
cai_niao_auth_info_id: toNumber(data.CaiNiaoAuthInfoId),
|
||
platform_updated_at: parseOrderTime(data.UpdateDate),
|
||
raw: data,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 拉取店铺关联的全部面单模板(快递接口):逐平台域名 / 分区查询后按模板ID去重。
|
||
* 单个分区失败不影响其它分区,错误随结果返回,供上层提示。
|
||
* @param {Object} shop OMS 店铺记录(type=2)
|
||
* @return {Promise<{list: Array, errors: Array<string>, targets: Array<string>}>} 模板列表与逐项错误
|
||
*/
|
||
async listExpressTemplates(shop) {
|
||
if (!this.token || !this.cookie) {
|
||
throw new Error('账号未登录:缺少 token 或 cookie,请先登录');
|
||
}
|
||
|
||
let traceId = '';
|
||
try {
|
||
const info = await this.getUserInfo();
|
||
traceId = (info.data && info.data.TraceId) || '';
|
||
} catch {
|
||
// 忽略:traceId 缺失不阻断模板查询
|
||
}
|
||
|
||
const targets = await this.resolveTemplateTargets(shop);
|
||
if (!targets.length) {
|
||
throw new Error('店铺缺少可识别的平台分区(DbAreas),无法确定快递接口所属平台');
|
||
}
|
||
|
||
const rows = new Map();
|
||
const errors = [];
|
||
const hitTargets = [];
|
||
for (const target of targets) {
|
||
const label = `${target.host} / ${target.platformType}${target.areaName ? `(${target.areaName})` : ''}`;
|
||
try {
|
||
const list = await this.fetchTemplateList(target.host, {
|
||
traceId,
|
||
dbname: target.dbname,
|
||
platformType: target.platformType,
|
||
});
|
||
for (const item of list) {
|
||
if (!item || !item.Id) continue;
|
||
// 平台标记为已删除的模板不落库:历史记录会在全量扫描后被标记失效
|
||
if (item.IsDeleted === true) continue;
|
||
rows.set(String(item.Id), this.normalizeExpressTemplate(item, target));
|
||
}
|
||
hitTargets.push(label);
|
||
} catch (err) {
|
||
errors.push(`${label}:${err.message}`);
|
||
}
|
||
}
|
||
return { list: [ ...rows.values() ], errors, targets: hitTargets };
|
||
}
|
||
|
||
/**
|
||
* 查看单个模板的电子面单账号 / 网点明细(平台单独接口)
|
||
* @param {Object} template 已落库的模板(template_id / platform_type / shop_id / dbname 等)
|
||
* @return {Promise<Object|null>} 平台返回的明细数据
|
||
*/
|
||
async fetchWaybillAccountDetail(template) {
|
||
const item = template || {};
|
||
const platformType = String(item.platform_type || '').trim();
|
||
const host = resolveTemplateHost(platformType);
|
||
if (!host) throw new Error(`暂不支持该平台类型的快递接口明细:${platformType || '-'}`);
|
||
|
||
let traceId = '';
|
||
try {
|
||
const info = await this.getUserInfo();
|
||
traceId = (info.data && info.data.TraceId) || '';
|
||
} catch {
|
||
// 忽略:traceId 缺失不阻断明细查询
|
||
}
|
||
|
||
const raw = item.raw && typeof item.raw === 'object' ? item.raw : {};
|
||
const query = new URLSearchParams({
|
||
token: this.token,
|
||
traceId,
|
||
dbname: item.dbname || '',
|
||
dataFlag: '',
|
||
});
|
||
const form = new URLSearchParams({
|
||
Id: String(item.template_id || ''),
|
||
TemplateId: String(item.template_id || ''),
|
||
ShopId: String(item.shop_id == null ? '' : item.shop_id),
|
||
ExpressCompanyId: String(item.express_company_id == null ? '' : item.express_company_id),
|
||
CaiNiaoAuthInfoId: String(raw.CaiNiaoAuthInfoId || (item.cai_niao_auth_info_id || '')),
|
||
platformType,
|
||
FxPageType: '2',
|
||
});
|
||
const headers = {
|
||
accept: 'application/json, text/javascript, */*; q=0.01',
|
||
'accept-language': 'zh-CN,zh;q=0.9',
|
||
'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
|
||
referer: `https://${host}/NewOrder/WaitOrder`,
|
||
'user-agent': BROWSER_HEADERS['user-agent'],
|
||
'x-requested-with': 'XMLHttpRequest',
|
||
};
|
||
if (this.cookie) headers.cookie = this.cookie;
|
||
|
||
const res = await this.request(`https://${host}${TEMPLATE_DETAIL_PATH}?${query.toString()}`, {
|
||
method: 'POST',
|
||
headers,
|
||
body: form.toString(),
|
||
});
|
||
if (res.status === 401) {
|
||
throw new Error(`店管家登录已失效:${(res.json && res.json.Message) || 'token is invalid'}`);
|
||
}
|
||
if (!res.json || res.json.Success !== true) {
|
||
const reason = (res.json && (res.json.Message || res.json.ErrorCode)) || `HTTP ${res.status}`;
|
||
throw new Error(reason);
|
||
}
|
||
return res.json.Data || null;
|
||
}
|
||
|
||
/**
|
||
* 组装商品列表查询表单(字段口径与店管家工作台一致)
|
||
* @param {string} agentId 商家 FxUserId(注意不是商家 Id);为空表示不限商家
|
||
* @param {number} pageIndex 页码,从 1 开始
|
||
* @param {number} pageSize 每页条数
|
||
* @param {Object} [filters] 单品查询条件
|
||
* @param {string} [filters.productId] 平台商品ID
|
||
* @param {string} [filters.skuId] 平台规格ID
|
||
* @return {URLSearchParams} 表单
|
||
*/
|
||
buildProductForm(agentId, pageIndex, pageSize, filters = {}) {
|
||
return new URLSearchParams({
|
||
PageIndex: String(pageIndex),
|
||
PageSize: String(pageSize),
|
||
SelectShopId: '',
|
||
SelectSupplierId: '',
|
||
SelectAgentId: agentId ? String(agentId) : '',
|
||
SelectPlatformType: '',
|
||
InputProductName: '',
|
||
ProductType: 'all',
|
||
ProductStatus: '0',
|
||
ProductCargoNumber: '',
|
||
ProductSkuName: '',
|
||
ProductShortTitle: '',
|
||
ProductSkuShortTitle: '',
|
||
IsSetShortTitle: '',
|
||
IsSetSkuShortTitle: '',
|
||
IsSetWeight: '',
|
||
IsSkuSetWeight: '',
|
||
ProductId: filters.productId || '',
|
||
SkuId: filters.skuId || '',
|
||
SkuCargoNumber: '',
|
||
IsDeleted: 'false',
|
||
IsRelationBaseProduct: '',
|
||
ActiveTimeDay: '-1',
|
||
StockCode: '',
|
||
IsExistStockCode: '',
|
||
IsCustomerOrder: 'false',
|
||
FxPageType: '1',
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 列出某个域名下账号可访问的分区(区)。
|
||
* 同一域名可能存在多个物理库(如「精选平台四区」「新系统区」),dbname 为空表示默认区;
|
||
* 商品必须逐区查询,否则会漏掉其它区的商品。
|
||
* @param {string} host 商品接口域名
|
||
* @return {Promise<Array<{dbname: string, name: string}>>} 分区列表(含默认区)
|
||
*/
|
||
async listProductAreas(host) {
|
||
const areas = await this.getAreasInfo(this.token, this.cookie, host);
|
||
const data = areas.data || {};
|
||
const list = [];
|
||
const push = (dbname, name) => {
|
||
const value = String(dbname || '');
|
||
if (!value || list.some(item => item.dbname === value)) return;
|
||
list.push({ dbname: value, name: name || '' });
|
||
};
|
||
|
||
// 当前分区 + 其它分区;dbname 为空等价于当前分区,这里统一用显式库名查询
|
||
const names = new Map();
|
||
for (const area of data.DbArea || []) {
|
||
if (area && area.DbName) names.set(String(area.DbName), area.NickName || '');
|
||
}
|
||
push(data.DbName, names.get(String(data.DbName || '')) || '当前分区');
|
||
for (const area of data.DbArea || []) push(area && area.DbName, area && area.NickName);
|
||
|
||
return list.length ? list : [{ dbname: '', name: '默认区' }];
|
||
}
|
||
|
||
/**
|
||
* 拉取一页商品
|
||
* @param {string} host 商品接口域名
|
||
* @param {Object} options 查询参数
|
||
* @param {string} [options.agentId] 商家 FxUserId,为空表示不限商家
|
||
* @param {string} options.traceId 登录上下文 traceId
|
||
* @param {string} [options.dbname] 分区库名,为空表示默认区
|
||
* @param {string} [options.productId] 平台商品ID(单品查询)
|
||
* @param {string} [options.skuId] 平台规格ID(单品查询)
|
||
* @param {number} options.pageIndex 页码
|
||
* @param {number} options.pageSize 每页条数
|
||
* @return {Promise<{rows: Array, total: number}>} 当页商品与总数
|
||
*/
|
||
async fetchProductPage(host, { agentId, traceId, dbname, productId, skuId, pageIndex, pageSize }) {
|
||
const query = new URLSearchParams({
|
||
token: this.token,
|
||
traceId: traceId || '',
|
||
dbname: dbname || '',
|
||
dataFlag: '',
|
||
});
|
||
const headers = {
|
||
accept: 'application/json, text/javascript, */*; q=0.01',
|
||
'accept-language': 'zh-CN,zh;q=0.9',
|
||
'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
|
||
referer: `https://${host}/`,
|
||
'user-agent': BROWSER_HEADERS['user-agent'],
|
||
'x-requested-with': 'XMLHttpRequest',
|
||
};
|
||
if (this.cookie) headers.cookie = this.cookie;
|
||
|
||
const res = await this.request(`https://${host}${PRODUCT_LIST_PATH}?${query.toString()}`, {
|
||
method: 'POST',
|
||
headers,
|
||
body: this.buildProductForm(agentId, pageIndex, pageSize, { productId, skuId }).toString(),
|
||
});
|
||
|
||
if (res.status === 401) {
|
||
throw new Error(`店管家登录已失效:${(res.json && res.json.Message) || 'token is invalid'}`);
|
||
}
|
||
if (!res.json || res.json.Success !== true) {
|
||
const reason = (res.json && (res.json.Message || res.json.ErrorCode)) || `HTTP ${res.status}`;
|
||
throw new Error(`拉取店管家商品列表失败(${host}):${reason}`);
|
||
}
|
||
|
||
const data = res.json.Data || {};
|
||
return {
|
||
rows: Array.isArray(data.Rows) ? data.Rows : [],
|
||
total: Number(data.Total) || 0,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 拉取某个域名下单个分区的全量商品快照。
|
||
* 逐页拉取并校验「去重后的商品数 = Total」,不一致时重试一次,
|
||
* 避免平台在分页过程中新增/删除商品导致漏拉或重复。
|
||
* @param {string} host 商品接口域名
|
||
* @param {Object} options 查询参数
|
||
* @param {string} options.agentId 商家 FxUserId
|
||
* @param {string} options.traceId 登录上下文 traceId
|
||
* @param {string} [options.dbname] 分区库名,为空表示默认区
|
||
* @param {string} [options.name] 分区名称
|
||
* @return {Promise<Object>} 分区商品快照
|
||
*/
|
||
async fetchAreaSnapshot(host, { agentId, traceId, dbname, name }) {
|
||
const maxAttempts = 2;
|
||
let snapshot = null;
|
||
|
||
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
||
const rows = [];
|
||
let total = 0;
|
||
let pages = 0;
|
||
|
||
// 上限 1000 页:防御平台分页异常(Total 与实际不符)时死循环
|
||
for (let pageIndex = 1; pageIndex <= 1000; pageIndex++) {
|
||
const page = await this.fetchProductPage(host, {
|
||
agentId,
|
||
traceId,
|
||
dbname,
|
||
pageIndex,
|
||
pageSize: PRODUCT_PAGE_SIZE,
|
||
});
|
||
pages++;
|
||
if (pages === 1) total = page.total;
|
||
rows.push(...page.rows);
|
||
if (!page.rows.length || rows.length >= total) break;
|
||
}
|
||
|
||
const unique = new Map();
|
||
for (const item of rows) {
|
||
const key = String((item && (item.Id != null ? item.Id : item.PlatformId)) || '');
|
||
if (key && !unique.has(key)) unique.set(key, item);
|
||
}
|
||
|
||
const candidate = {
|
||
host,
|
||
dbname: dbname || '',
|
||
name: name || '',
|
||
total,
|
||
uniqueCount: unique.size,
|
||
pages,
|
||
rows: Array.from(unique.values()),
|
||
verified: unique.size === total,
|
||
};
|
||
// 重试结果更差(例如瞬时返回空列表)时保留上一次快照,避免把商品误判为下架
|
||
if (!snapshot || candidate.verified || candidate.uniqueCount > snapshot.uniqueCount) {
|
||
snapshot = candidate;
|
||
}
|
||
if (snapshot.verified) break;
|
||
}
|
||
|
||
return snapshot;
|
||
}
|
||
|
||
/**
|
||
* 拉取某个域名下所有分区的商品快照并合并。
|
||
* 同一域名下可能有多个物理库(默认区 / 新系统区等),只查默认区会漏掉其它区的商品。
|
||
* @param {string} host 商品接口域名
|
||
* @param {Object} options 查询参数
|
||
* @param {string} options.agentId 商家 FxUserId
|
||
* @param {string} options.traceId 登录上下文 traceId
|
||
* @return {Promise<Object>} 域名商品快照(含各分区明细)
|
||
*/
|
||
async fetchProductSnapshot(host, { agentId, traceId }) {
|
||
const areas = await this.listProductAreas(host);
|
||
const snapshots = [];
|
||
for (const area of areas) {
|
||
snapshots.push(await this.fetchAreaSnapshot(host, {
|
||
agentId,
|
||
traceId,
|
||
dbname: area.dbname,
|
||
name: area.name,
|
||
}));
|
||
}
|
||
|
||
// 不同分区是独立库,正常不会重复;仍按商品ID去重,避免同一商品被写入两次
|
||
const rows = new Map();
|
||
for (const snapshot of snapshots) {
|
||
for (const item of snapshot.rows) {
|
||
const key = String((item && (item.Id != null ? item.Id : item.PlatformId)) || '');
|
||
if (key && !rows.has(key)) rows.set(key, item);
|
||
}
|
||
}
|
||
|
||
return {
|
||
host,
|
||
total: snapshots.reduce((sum, snapshot) => sum + snapshot.total, 0),
|
||
uniqueCount: rows.size,
|
||
pages: snapshots.reduce((sum, snapshot) => sum + snapshot.pages, 0),
|
||
rows: Array.from(rows.values()),
|
||
verified: snapshots.every(snapshot => snapshot.verified),
|
||
areas: snapshots.map(snapshot => ({
|
||
dbname: snapshot.dbname,
|
||
name: snapshot.name,
|
||
total: snapshot.total,
|
||
unique: snapshot.uniqueCount,
|
||
pages: snapshot.pages,
|
||
verified: snapshot.verified,
|
||
})),
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 拉取店铺商品全量快照:商家可能同时经营多个平台,
|
||
* 按其分区逐个域名拉取后合并,按「平台类型 + 平台商品ID + 平台规格ID」去重。
|
||
* @param {Object} shop OMS 店铺记录(type=2,external_data 为商家原始结构)
|
||
* @return {Promise<{total: number, verified: boolean, hosts: Array, list: Array}>} 商品快照
|
||
*/
|
||
async listProducts(shop) {
|
||
if (!this.token || !this.cookie) {
|
||
throw new Error('账号未登录:缺少 token 或 cookie,请先登录');
|
||
}
|
||
|
||
const data = (shop && shop.external_data) || {};
|
||
const agentId = String(data.FxUserId || '').trim();
|
||
if (!agentId) throw new Error('店铺缺少商家 FxUserId,无法拉取平台商品');
|
||
|
||
const hosts = this.resolveProductHosts(data);
|
||
let traceId = '';
|
||
try {
|
||
const info = await this.getUserInfo();
|
||
traceId = (info.data && info.data.TraceId) || '';
|
||
} catch {
|
||
// 忽略:traceId 缺失不阻断商品查询
|
||
}
|
||
|
||
const snapshots = [];
|
||
for (const host of hosts) {
|
||
snapshots.push(await this.fetchProductSnapshot(host, { agentId, traceId }));
|
||
}
|
||
|
||
// 店铺「所在区」声明过期(重新授权/换绑后不会自动同步)时,声明域名会一个商品都没有:
|
||
// 这时补查账号的其它域名,避免「店管家有商品、OMS 同步 0 条」(单品补拉一直是这么兜底的)
|
||
const supplementHosts = [];
|
||
const declaredEmpty = snapshots.every(snapshot => !snapshot.uniqueCount);
|
||
if (declaredEmpty) {
|
||
for (const host of FALLBACK_PRODUCT_HOSTS) {
|
||
if (hosts.includes(host)) continue;
|
||
snapshots.push(await this.fetchProductSnapshot(host, { agentId, traceId }));
|
||
supplementHosts.push(host);
|
||
}
|
||
if (supplementHosts.length && this.logger && typeof this.logger.warn === 'function') {
|
||
this.logger.warn(
|
||
'[dgj] 店铺声明的分区没有商品,已补查其它域名:%s(命中:%s)',
|
||
supplementHosts.join('、'),
|
||
snapshots.filter(snapshot => snapshot.uniqueCount).map(snapshot => snapshot.host).join('、') || '-'
|
||
);
|
||
}
|
||
}
|
||
|
||
const merged = new Map();
|
||
for (const snapshot of snapshots) {
|
||
for (const item of snapshot.rows) {
|
||
for (const row of this.normalizeProduct(item)) {
|
||
merged.set(`${row.platform_type}|${row.outer_item_id}|${row.outer_sku_id}`, row);
|
||
}
|
||
}
|
||
}
|
||
|
||
return {
|
||
total: snapshots.reduce((sum, snapshot) => sum + snapshot.total, 0),
|
||
verified: snapshots.every(snapshot => snapshot.verified),
|
||
// 声明分区没有商品时补查的域名(非空说明「店铺所在区」声明可能过期)
|
||
supplementHosts,
|
||
hosts: snapshots.map(snapshot => ({
|
||
host: snapshot.host,
|
||
total: snapshot.total,
|
||
unique: snapshot.uniqueCount,
|
||
pages: snapshot.pages,
|
||
verified: snapshot.verified,
|
||
areas: snapshot.areas,
|
||
})),
|
||
list: Array.from(merged.values()),
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 把店管家商品(含 SKU 列表)转换为店铺商品行的统一结构。
|
||
* 平台商品ID取商品级 PlatformId;平台规格ID统一取 SKU 的 `SkuId`
|
||
* (早期用过 `SpecId`,两者在部分平台/商品上不一致,统一后不再使用 SpecId;
|
||
* 另注意 SKU.PlatformId 是商品级平台ID,不能当规格ID),缺失时退化为店管家内部ID。
|
||
* 原样保留商品与 SKU 结构供后续使用。
|
||
* @param {Object} product 店管家商品原始结构
|
||
* @return {Array<Object>} 店铺商品行(一个 SKU 一行)
|
||
*/
|
||
normalizeProduct(product) {
|
||
const data = product || {};
|
||
const skus = Array.isArray(data.Skus) && data.Skus.length ? data.Skus : [ null ];
|
||
const productRaw = { ...data };
|
||
delete productRaw.Skus;
|
||
|
||
const platformType = resolveOrderPlatform(data.PlatformType).code;
|
||
const externalShopId = data.ShopId == null ? '' : truncate(data.ShopId, 64);
|
||
const status = isProductOnSale(data.Status) ? 1 : 0;
|
||
|
||
return skus.map(sku => {
|
||
const item = sku || {};
|
||
const ptInfo = item.PtProductInfo || {};
|
||
const attrs = [ item.AttributeValue1, item.AttributeValue2 ].filter(Boolean).join(' ');
|
||
return {
|
||
outer_item_id: String(data.PlatformId || ptInfo.PrductId || data.Id || ''),
|
||
outer_sku_id: String(item.SkuId || item.Id || ''),
|
||
title: truncate(data.Subject, 255),
|
||
outer_code: String(item.CargoNumber || item.SkuSelfCode || data.CargoNumber || data.ProductSelfCode || ''),
|
||
spec: truncate(item.Name || attrs, 255),
|
||
image: truncate(data.ImageUrl || item.ImgUrl, 255),
|
||
price: toNumber(item.SalePrice),
|
||
stock: Math.max(0, Math.trunc(toNumber(item.AvailableCount))),
|
||
status,
|
||
platform_type: platformType,
|
||
external_shop_id: externalShopId,
|
||
raw: { product: productRaw, sku: sku || null },
|
||
};
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 拉取店铺订单(按「待发货 + 商家」过滤,只返回仍需本系统处理的未发货订单)。
|
||
*
|
||
* 查询策略:
|
||
* 1. 新系统分区支持 `ErpState == waitsellersend` 与 `UpFxUserId in <FxUserId>` 过滤,带上过滤后单量极小;
|
||
* 2. 老分区(旧系统库)对这两个过滤返回「服务器繁忙」,只能按时间窗全量拉,窗口封顶最近 N 天;
|
||
* 3. 分区是否支持过滤用 AREA_FILTER_SUPPORT 缓存(1 小时),避免每次都先撞一次「服务器繁忙」;
|
||
* 4. 商家分区声明(external_data.DbAreas[].IsNewSystem)里没有老分区时,跳过该平台的老分区,
|
||
* 那些是迁移前遗留数据,避免每次白拉一遍历史单。
|
||
* 拉回来的行仍做两步本地校验:按 UpFxUserId 归属店铺、丢弃平台侧已发货/已终结的订单。
|
||
* 被丢弃的订单会通过 finished 返回,供上层把本地仍处于待审核的副本作废。
|
||
* @param {Object} shop OMS 店铺记录(type=2,external_data 为商家原始结构)
|
||
* @param {Object} [options] 查询参数
|
||
* @param {Date|string} [options.startTime] 平台下单时间起(含)
|
||
* @param {Date|string} [options.endTime] 平台下单时间止(含)
|
||
* @return {Promise<{total: number, list: Array, hosts: Array, skipped: number, finished: Array, fallbackHosts: Array, skippedLegacy: Array}>} 订单列表
|
||
*/
|
||
async listOrders(shop, options = {}) {
|
||
if (!this.token || !this.cookie) {
|
||
throw new Error('账号未登录:缺少 token 或 cookie,请先登录');
|
||
}
|
||
|
||
const data = (shop && shop.external_data) || {};
|
||
const merchantFxUserId = String(data.FxUserId || '').trim();
|
||
if (!merchantFxUserId) throw new Error('店铺缺少商家 FxUserId,无法拉取平台订单');
|
||
|
||
const end = options.endTime ? new Date(options.endTime) : new Date();
|
||
const start = options.startTime
|
||
? new Date(options.startTime)
|
||
// 未指定时间窗时按平台「待发货订单」页的默认范围(15 天)兜底
|
||
: new Date(end.getTime() - 15 * 24 * 3600 * 1000);
|
||
const hosts = this.resolveProductHosts(data);
|
||
|
||
let traceId = '';
|
||
try {
|
||
const info = await this.getUserInfo();
|
||
traceId = (info.data && info.data.TraceId) || '';
|
||
} catch {
|
||
// 忽略:traceId 缺失不阻断订单查询
|
||
}
|
||
|
||
const orders = new Map();
|
||
const finished = new Map();
|
||
const hitHosts = [];
|
||
// 平台实际出现的商家(UpFxUserId → 单量/店铺名),用于诊断「店铺声明的商家与平台不一致」
|
||
const seenMerchants = new Map();
|
||
// 不支持状态/商家过滤的老分区(旧系统库):退化为只按时间窗拉全量,本地过滤
|
||
const fallbackHosts = [];
|
||
// 店铺没有声明该平台的老分区(只有新系统分区)时,该平台的老分区属于迁移前遗留数据,跳过不拉
|
||
const skippedLegacy = [];
|
||
const areaFlags = this.resolveAreaFlags(data);
|
||
// 「所在区」声明里没有老分区时先跳过(迁移前遗留数据),但**拉到单之前不能就此收工**:
|
||
// 声明只写了「抖店-二区」而订单实际还在「抖店-186(一区)」的情况确实存在,
|
||
// 声明域名/新系统区都没单时再回头补扫这些老分区
|
||
const deferredLegacy = [];
|
||
/**
|
||
* 扫一个分区
|
||
* @param {string} host 订单接口域名
|
||
* @param {Object} area 分区(dbname / name)
|
||
* @param {boolean} legacyAllowed 是否允许走「不支持过滤 → 时间窗全量」兜底
|
||
* @return {Promise<void>} 无返回值
|
||
*/
|
||
const scanArea = async (host, area, legacyAllowed) => {
|
||
const areaLabel = `${host}(${area.name || area.dbname})`;
|
||
let fetched = null;
|
||
// 新系统分区支持「待发货 + 商家」过滤;已知不支持的老分区直接走下面的兜底分支
|
||
if (this.filterSupported(host, area.dbname) !== false) {
|
||
try {
|
||
fetched = await this.fetchOrderPages(host, {
|
||
traceId,
|
||
dbname: area.dbname,
|
||
startTime: start,
|
||
endTime: end,
|
||
erpState: ORDER_ERP_STATE_PENDING,
|
||
merchantFxUserId,
|
||
});
|
||
this.rememberFilterSupport(host, area.dbname, true);
|
||
} catch (err) {
|
||
if (!isFilterUnsupportedError(err)) throw err;
|
||
// 旧系统分区不支持 ErpState/UpFxUserId 过滤(平台返回「服务器繁忙」)
|
||
this.rememberFilterSupport(host, area.dbname, false);
|
||
fetched = null;
|
||
}
|
||
}
|
||
if (fetched === null) {
|
||
// 老分区:店铺没声明老分区时先挂起(迁移前遗留数据,避免每次白拉一遍历史单)
|
||
if (!legacyAllowed) {
|
||
deferredLegacy.push({ host, area, areaLabel });
|
||
return;
|
||
}
|
||
fallbackHosts.push(areaLabel);
|
||
// 老分区只能全量拉:超大窗口(「全部待处理」)会翻很多页,统一封顶到最近 N 天
|
||
const fallbackStart = new Date(Math.max(
|
||
start.getTime(),
|
||
end.getTime() - Math.max(1, ORDER_FALLBACK_MAX_DAYS) * 24 * 3600 * 1000
|
||
));
|
||
// 注意:平台「全量」列表不含待发货单,退化分支只能兜住已发货/已终结的核对,
|
||
// 拉待发货单必须靠「状态过滤」——所以这里留一条 warn,0 单时不会被误当成「平台没有单」
|
||
if (this.logger && typeof this.logger.warn === 'function') {
|
||
this.logger.warn('[dgj] %s 的 %s 不支持状态过滤,退化为时间窗全量拉取(可能漏掉待发货单)', host, areaLabel);
|
||
}
|
||
fetched = await this.fetchOrderPages(host, {
|
||
traceId,
|
||
dbname: area.dbname,
|
||
startTime: fallbackStart,
|
||
endTime: end,
|
||
});
|
||
}
|
||
if (!fetched.length) return;
|
||
hitHosts.push(areaLabel);
|
||
for (const row of fetched) {
|
||
const upFxUserId = String(row.UpFxUserId || '');
|
||
// 记录平台实际出现的商家:店铺声明的 FxUserId 过期时(重新授权/换绑),
|
||
// 按老 FxUserId 过滤永远是 0 条,这里留痕便于直接看出「该换成谁」
|
||
if (upFxUserId) {
|
||
const seen = seenMerchants.get(upFxUserId) || {
|
||
count: 0,
|
||
shopName: String(row.ShopName || row.AgentShopName || row.SelfShopName || ''),
|
||
};
|
||
seen.count += 1;
|
||
seenMerchants.set(upFxUserId, seen);
|
||
}
|
||
// 订单列表按账号维度返回,这里只保留当前商家的订单
|
||
if (upFxUserId !== merchantFxUserId) continue;
|
||
const order = this.normalizeOrder(row);
|
||
if (!order.external_order_id) continue;
|
||
// 平台已发货/已终结:不进待审核,只登记给上层用于作废本地未处理的副本
|
||
// (带上命中的具体依据,作废备注里直接写明「平台订单状态 ErpState=sended」之类)
|
||
const finishedDetail = describeFinishedOrder(row);
|
||
if (finishedDetail.finished) {
|
||
finished.set(order.external_order_id, {
|
||
external_order_id: order.external_order_id,
|
||
platform_order_no: order.platform_order_no,
|
||
platform_status: order.platform_status,
|
||
place_order_time: order.external_created_at,
|
||
reason: finishedDetail.reason,
|
||
});
|
||
continue;
|
||
}
|
||
orders.set(order.external_order_id, order);
|
||
}
|
||
};
|
||
/**
|
||
* 扫一个域名下的全部分区
|
||
* @param {string} host 订单接口域名
|
||
* @return {Promise<void>} 无返回值
|
||
*/
|
||
const scanHost = async host => {
|
||
// 商家分区声明里没有该平台的记录时,按「新旧分区都要查」处理,宁可多查也不漏单
|
||
const flags = areaFlags[host] || { hasNew: true, hasLegacy: true };
|
||
const areas = await this.listProductAreas(host);
|
||
for (const area of areas) await scanArea(host, area, flags.hasLegacy);
|
||
};
|
||
|
||
for (const host of hosts) await scanHost(host);
|
||
|
||
// 声明里没有老分区、但新分区一单都没有时,回头补扫这些老分区(如「抖店-186(一区)」)
|
||
const rescueHosts = [];
|
||
if (!orders.size && !finished.size && deferredLegacy.length) {
|
||
for (const item of deferredLegacy) {
|
||
await scanArea(item.host, item.area, true);
|
||
}
|
||
rescueHosts.push(...deferredLegacy.map(item => item.areaLabel));
|
||
if (this.logger && typeof this.logger.warn === 'function') {
|
||
this.logger.warn(
|
||
'[dgj] 声明分区没拉到单,已补扫老分区:%s(命中:%s)',
|
||
deferredLegacy.map(item => item.areaLabel).join('、'),
|
||
hitHosts.join('、') || '-'
|
||
);
|
||
}
|
||
} else {
|
||
skippedLegacy.push(...deferredLegacy.map(item => item.areaLabel));
|
||
}
|
||
|
||
// 店铺的「所在区」声明(external_data.DbAreas)可能过期:重新授权/换绑后不会自动同步,
|
||
// 声明域名一单都没有时再补查账号的其它域名,否则会出现「店管家 UI 有单、OMS 拉不到」
|
||
const supplementHosts = [];
|
||
if (!orders.size && !finished.size) {
|
||
const extraHosts = FALLBACK_PRODUCT_HOSTS.filter(host => !hosts.includes(host));
|
||
for (const host of extraHosts) {
|
||
await scanHost(host);
|
||
supplementHosts.push(host);
|
||
}
|
||
if (supplementHosts.length && this.logger && typeof this.logger.warn === 'function') {
|
||
this.logger.warn(
|
||
'[dgj] 店铺声明的分区没拉到单,已补查其它域名:%s(命中的分区:%s)',
|
||
supplementHosts.join('、'),
|
||
hitHosts.join('、') || '-'
|
||
);
|
||
}
|
||
}
|
||
|
||
return {
|
||
total: orders.size,
|
||
list: Array.from(orders.values()),
|
||
hosts: hitHosts,
|
||
// 店铺声明的域名(与 supplementHosts 对照即可看出「所在区」是否过期)
|
||
declaredHosts: hosts,
|
||
fallbackHosts,
|
||
skippedLegacy,
|
||
// 声明分区没拉到单时补查的域名(非空说明「店铺所在区」声明可能过期)
|
||
supplementHosts,
|
||
// 声明里没有老分区、但补扫了这些老分区(如「抖店-186(一区)」)
|
||
rescueHosts,
|
||
skipped: finished.size,
|
||
finished: Array.from(finished.values()),
|
||
// 店铺声明的商家在平台结果里是否出现过;没出现过通常是 FxUserId 过期(重新授权/换绑)
|
||
merchantSeen: seenMerchants.has(merchantFxUserId),
|
||
otherMerchants: Array.from(seenMerchants.entries())
|
||
.filter(([ fxUserId ]) => fxUserId !== merchantFxUserId)
|
||
.map(([ fxUserId, item ]) => ({ fx_user_id: fxUserId, shop_name: item.shopName, count: item.count }))
|
||
.sort((left, right) => right.count - left.count)
|
||
.slice(0, 5),
|
||
// 供上层做「按订单号精确核对」时复用本次登录上下文
|
||
traceId,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 按系统编号批量回读订单行(只做只读核对,不做归属过滤)
|
||
*
|
||
* 平台支持 `Filters[0][Name]=LogicOrderId & Contract=in & Value=id1,id2` 一次命中多单(实测有效),
|
||
* 用于核对本地待审核订单在平台的最新状态(是否已发货/已终结/已不存在)。
|
||
* @param {string} host 接口域名
|
||
* @param {Object} options 查询参数
|
||
* @param {string} [options.traceId] 登录上下文 traceId
|
||
* @param {string} [options.dbname] 分区库名
|
||
* @param {Array<string>} options.ids 系统编号(LogicOrderId)列表
|
||
* @return {Promise<Array>} 订单原始结构列表
|
||
*/
|
||
async fetchOrdersByIds(host, { traceId, dbname, ids }) {
|
||
const list = (ids || []).map(value => String(value || '').trim()).filter(Boolean);
|
||
if (!list.length) return [];
|
||
if (!this.token || !this.cookie) {
|
||
throw new Error('账号未登录:缺少 token 或 cookie,请先登录');
|
||
}
|
||
|
||
const query = new URLSearchParams({
|
||
token: this.token,
|
||
traceId: traceId || '',
|
||
dbname: dbname || '',
|
||
dataFlag: '',
|
||
});
|
||
|
||
const form = new URLSearchParams();
|
||
const fields = {
|
||
TableAlias: 'o',
|
||
FieldType: 'string',
|
||
TableName: 'LogicOrder',
|
||
Name: 'LogicOrderId',
|
||
Value: list.join(','),
|
||
Contract: 'in',
|
||
};
|
||
for (const [ key, value ] of Object.entries(fields)) form.append(`Filters[0][${key}]`, value);
|
||
form.set('IsOrderDesc', 'true');
|
||
form.set('OrderByField', 'o.CreateTime');
|
||
form.set('IsPdd', 'false');
|
||
form.set('PageSize', String(Math.max(50, list.length)));
|
||
form.set('PageIndex', '1');
|
||
form.set('isFilterDangerChar', 'false');
|
||
form.set('TarType', '');
|
||
form.set('requestUrl', `https://${host}/NewOrder/WaitOrder`);
|
||
form.set('IsCustomerOrder', 'false');
|
||
form.set('FxPageType', '2');
|
||
|
||
const headers = {
|
||
accept: 'application/json, text/javascript, */*; q=0.01',
|
||
'accept-language': 'zh-CN,zh;q=0.9',
|
||
'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
|
||
referer: `https://${host}/NewOrder/WaitOrder`,
|
||
'user-agent': BROWSER_HEADERS['user-agent'],
|
||
'x-requested-with': 'XMLHttpRequest',
|
||
};
|
||
if (this.cookie) headers.cookie = this.cookie;
|
||
|
||
const res = await this.request(`https://${host}${ORDER_LIST_PATH}?${query.toString()}`, {
|
||
method: 'POST',
|
||
headers,
|
||
body: form.toString(),
|
||
});
|
||
if (res.status === 401) {
|
||
throw new Error(`店管家登录已失效:${(res.json && res.json.Message) || 'token is invalid'}`);
|
||
}
|
||
if (!res.json || res.json.Success !== true) {
|
||
const reason = (res.json && (res.json.Message || res.json.ErrorCode)) || `HTTP ${res.status}`;
|
||
throw new Error(`核对店管家订单失败(${host}):${reason}`);
|
||
}
|
||
const data = res.json.Data || {};
|
||
return Array.isArray(data.Rows) ? data.Rows : [];
|
||
}
|
||
|
||
/**
|
||
* 按分页拉取订单列表(不归属过滤,交由调用方按商家过滤)
|
||
* @param {string} host 接口域名
|
||
* @param {Object} options 查询参数
|
||
* @param {string} options.traceId 登录上下文 traceId
|
||
* @param {string} options.dbname 分区库名
|
||
* @param {Date} options.startTime 下单时间起
|
||
* @param {Date} options.endTime 下单时间止
|
||
* @param {string} [options.erpState] 订单状态过滤(如 waitsellersend;不传则不限状态)
|
||
* @param {string} [options.merchantFxUserId] 商家 FxUserId(按商家过滤,不传则整账号)
|
||
* @return {Promise<Array>} 订单原始结构列表
|
||
*/
|
||
async fetchOrderPages(host, { traceId, dbname, startTime, endTime, erpState, merchantFxUserId }) {
|
||
const rows = [];
|
||
// 平台不保证返回 PageCount(实测多为 null),因此以 Total 和「本页是否满页」判断结束,
|
||
// 只依赖 PageCount 会在超过 500 条时静默截断
|
||
let total = Infinity;
|
||
|
||
for (let pageIndex = 1; pageIndex <= ORDER_MAX_PAGES; pageIndex++) {
|
||
const page = await this.fetchOrderPage(host, {
|
||
traceId,
|
||
dbname,
|
||
startTime,
|
||
endTime,
|
||
pageIndex,
|
||
erpState,
|
||
merchantFxUserId,
|
||
});
|
||
if (!page.rows.length) break;
|
||
rows.push(...page.rows);
|
||
if (Number(page.total) > 0) total = Number(page.total);
|
||
if (rows.length >= total) break;
|
||
if (page.rows.length < ORDER_PAGE_SIZE) break;
|
||
}
|
||
|
||
return rows;
|
||
}
|
||
|
||
/**
|
||
* 拉取一页订单
|
||
* @param {string} host 接口域名
|
||
* @param {Object} options 查询参数
|
||
* @param {string} options.traceId 登录上下文 traceId
|
||
* @param {string} options.dbname 分区库名
|
||
* @param {Date} options.startTime 下单时间起
|
||
* @param {Date} options.endTime 下单时间止
|
||
* @param {number} options.pageIndex 页码
|
||
* @param {string} [options.erpState] 订单状态过滤(如 waitsellersend;不传则不限状态)
|
||
* @param {string} [options.merchantFxUserId] 商家 FxUserId(按商家过滤,不传则整账号)
|
||
* @return {Promise<{rows: Array, total: number, pageCount: number}>} 当页订单
|
||
*/
|
||
async fetchOrderPage(host, { traceId, dbname, startTime, endTime, pageIndex, erpState, merchantFxUserId }) {
|
||
const query = new URLSearchParams({
|
||
token: this.token,
|
||
traceId: traceId || '',
|
||
dbname: dbname || '',
|
||
dataFlag: '',
|
||
});
|
||
|
||
const form = new URLSearchParams();
|
||
const filters = [
|
||
{
|
||
TableAlias: 'o',
|
||
FieldType: 'DateTime',
|
||
TableName: 'LogicOrder',
|
||
Name: 'CreateTime',
|
||
Value: formatOrderTime(startTime),
|
||
ExtValue: formatOrderTime(endTime),
|
||
Contract: 'between',
|
||
},
|
||
];
|
||
// 状态过滤:与平台「待发货订单」页同口径(ErpState == waitsellersend)
|
||
// ⚠️ Contract 必须是单个 `=`(浏览器抓包口径);写成 `==` 时抖店老分区会返回
|
||
// 「服务器繁忙,请稍会儿再试」,导致 6 单待发货被当成「该分区不支持过滤」
|
||
if (erpState) {
|
||
filters.push({
|
||
TableAlias: 'o',
|
||
FieldType: 'string',
|
||
TableName: 'LogicOrder',
|
||
Name: 'ErpState',
|
||
Value: String(erpState),
|
||
Contract: '=',
|
||
});
|
||
}
|
||
// 商家过滤:平台按 PathFlowNode.UpFxUserId 过滤(实测有效,一次只回该商家的单)
|
||
if (merchantFxUserId) {
|
||
filters.push({
|
||
TableAlias: 'pfn',
|
||
FieldType: 'int',
|
||
TableName: 'PathFlowNode',
|
||
Name: 'UpFxUserId',
|
||
Value: String(merchantFxUserId),
|
||
Contract: 'in',
|
||
});
|
||
}
|
||
filters.forEach((fields, index) => {
|
||
for (const [ key, value ] of Object.entries(fields)) form.append(`Filters[${index}][${key}]`, value);
|
||
});
|
||
form.set('IsOrderDesc', 'true');
|
||
form.set('OrderByField', 'o.CreateTime');
|
||
form.set('IsPdd', 'false');
|
||
form.set('PageSize', String(ORDER_PAGE_SIZE));
|
||
form.set('PageIndex', String(pageIndex));
|
||
form.set('isFilterDangerChar', 'false');
|
||
form.set('TarType', '');
|
||
form.set('requestUrl', `https://${host}/NewOrder/WaitOrder`);
|
||
form.set('IsCustomerOrder', 'false');
|
||
form.set('FxPageType', '2');
|
||
|
||
const headers = {
|
||
accept: 'application/json, text/javascript, */*; q=0.01',
|
||
'accept-language': 'zh-CN,zh;q=0.9',
|
||
'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
|
||
referer: `https://${host}/NewOrder/WaitOrder`,
|
||
'user-agent': BROWSER_HEADERS['user-agent'],
|
||
'x-requested-with': 'XMLHttpRequest',
|
||
};
|
||
if (this.cookie) headers.cookie = this.cookie;
|
||
|
||
const res = await this.request(`https://${host}${ORDER_LIST_PATH}?${query.toString()}`, {
|
||
method: 'POST',
|
||
headers,
|
||
body: form.toString(),
|
||
});
|
||
|
||
if (res.status === 401) {
|
||
throw new Error(`店管家登录已失效:${(res.json && res.json.Message) || 'token is invalid'}`);
|
||
}
|
||
if (!res.json || res.json.Success !== true) {
|
||
const reason = (res.json && (res.json.Message || res.json.ErrorCode)) || `HTTP ${res.status}`;
|
||
throw new Error(`拉取店管家订单失败(${host}):${reason}`);
|
||
}
|
||
|
||
const data = res.json.Data || {};
|
||
return {
|
||
rows: Array.isArray(data.Rows) ? data.Rows : [],
|
||
total: Number(data.Total) || 0,
|
||
pageCount: Number(data.PageCount) || 1,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 把店管家订单结构转换为统一结构(明细保留平台商品快照,不在此处做系统商品匹配)
|
||
* @param {Object} row 店管家订单原始结构
|
||
* @return {Object} 统一订单结构
|
||
*/
|
||
normalizeOrder(row) {
|
||
const data = row || {};
|
||
const subOrders = Array.isArray(data.SubOrders) ? data.SubOrders : [];
|
||
// 店管家「系统编号」LogicOrderId 全局唯一,作为来源订单号与去重键;
|
||
// 「订单编号」PlatformOrderId 是平台单号,可能存在重复(如同一平台单被拆成多条逻辑单),不能作为唯一标识
|
||
const logicOrderId = String(data.LogicOrderId || '').trim();
|
||
const platformOrderId = String(data.PlatformOrderId || '').trim();
|
||
const externalOrderId = logicOrderId || platformOrderId;
|
||
// 平台类型转系统预设编码(PDD / DYXD / SPH…),订单表与推 WMS 都用这一套
|
||
const platform = resolveOrderPlatform(data.PlatformType);
|
||
const distributeChannel = this.resolveOrderDistributeChannel(data);
|
||
// 硬规则(分销代发业务口径):1688 单不按 1688 出号,统一换算成实际取号渠道
|
||
// - 抖音分销单(OutChannel=douyin)→ 抖音小店(DYXD)
|
||
// - 其它分销渠道(OutChannel=未知值)→ 其他(OTHER),原始报文与渠道留痕,等待后续映射
|
||
// - 非分销单(无 OutChannel 标签)→ 淘宝(TB)
|
||
// 否则按 1688 永远匹配不到面单模板,取号必失败
|
||
let platformCode = platform.code;
|
||
let platformName = platform.name;
|
||
if (platform.code === '1688') {
|
||
let targetCode = 'TB';
|
||
if (distributeChannel === 'douyin') targetCode = 'DYXD';
|
||
else if (distributeChannel) targetCode = 'OTHER';
|
||
const target = resolvePlatform(targetCode);
|
||
platformCode = target.code;
|
||
platformName = target.name;
|
||
}
|
||
return {
|
||
external_order_id: externalOrderId,
|
||
// 平台单号保留下来展示/查询用(与外部环境对账时需要)
|
||
platform_order_no: platformOrderId || null,
|
||
external_shop_id: data.ShopId == null ? '' : String(data.ShopId),
|
||
external_shop_name: truncate(data.ShopName || data.AgentShopName || data.SelfShopName, 128),
|
||
// 原始值仅作留痕;落库用 platform_code / platform_name
|
||
platform_type: truncate(data.PlatformType, 32),
|
||
platform_code: platformCode,
|
||
platform_name: platformName,
|
||
// 分销渠道与原始平台:换算后仍可追溯「这单其实是 1688 分销到哪个渠道的」
|
||
distribute_channel: distributeChannel || null,
|
||
original_platform_code: platform.code,
|
||
original_platform_name: platform.name,
|
||
platform_status: truncate(data.ErpState || data.Status, 32),
|
||
order_no: externalOrderId,
|
||
total_amount: toNumber(data.TotalAmount),
|
||
pay_amount: toNumber(data.SumTotalAmount || data.TotalAmount),
|
||
// 店管家对收件人脱敏(明文仅打印组件可取):这里保留可用的省市区与脱敏明细地址
|
||
receiver: {
|
||
name: data.ToName || '',
|
||
phone: data.ToPhone || '',
|
||
address: data.ToAddress || '',
|
||
full_address: data.ToFullAddress || '',
|
||
province: data.ToProvince || '',
|
||
city: data.ToCity || '',
|
||
area: data.ToCounty || '',
|
||
town: data.ToTown || '',
|
||
masked: !!(data.ToName && /\*/.test(String(data.ToName))) || !!(data.ToAddress && /\*/.test(String(data.ToAddress))),
|
||
},
|
||
remark: truncate(data.BuyerRemark || data.SellerRemark, 255),
|
||
external_created_at: parseOrderTime(data.CreateTime),
|
||
external_updated_at: parseOrderTime(data.UpdateTime),
|
||
raw: data,
|
||
items: subOrders.map(item => this.normalizeOrderItem(item)),
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 取订单的分销渠道(Tags/OrderTags 里 `Tag=OutChannel` 的 `TagValue`)
|
||
*
|
||
* 1688 分销/代发采购单会带这个标签,值是对下游渠道的标识(实测 `douyin`、
|
||
* `chaoshibianli_plaintext`、`thyny_plaintext` 等)。分销单必须用下游渠道的电子面单,
|
||
* 所以「平台」要按下游渠道算,不能按 1688 算,否则取号永远匹配不到模板。
|
||
* @param {Object} data 店管家订单原始结构
|
||
* @return {string} 分销渠道标识(小写),无则空串
|
||
*/
|
||
resolveOrderDistributeChannel(data) {
|
||
const tags = [
|
||
...(Array.isArray(data && data.Tags) ? data.Tags : []),
|
||
...(Array.isArray(data && data.OrderTags) ? data.OrderTags : []),
|
||
];
|
||
for (const tag of tags) {
|
||
if (!tag || String(tag.Tag || '') !== 'OutChannel') continue;
|
||
const value = String(tag.TagValue || '').trim().toLowerCase();
|
||
if (value) return value;
|
||
}
|
||
return '';
|
||
}
|
||
|
||
/**
|
||
* 把店管家订单明细转换为统一结构:平台商品快照原样保留,
|
||
* 系统商品关联由上层按店铺商品绑定关系决定(未绑定时保持原样)
|
||
* @param {Object} item 店管家明细原始结构
|
||
* @return {Object} 统一明细结构
|
||
*/
|
||
normalizeOrderItem(item) {
|
||
const data = item || {};
|
||
const ptInfo = data.PtProductInfo || {};
|
||
const spec = data.Color || data.Size || ptInfo.PrductSpecs || '';
|
||
return {
|
||
external_item_id: data.OrderItemId == null ? '' : truncate(data.OrderItemId, 64),
|
||
outer_item_id: String(data.ProductID || ptInfo.PrductId || ''),
|
||
outer_sku_id: resolveOrderSkuId(data),
|
||
sku_code: truncate(data.CargoNumber || data.productCargoNumber || ptInfo.CargoNumber, 100),
|
||
name: truncate(data.ProductSubject || ptInfo.ProductSubject, 255),
|
||
spec: truncate(spec, 255),
|
||
image: truncate(data.ProductImgUrl || ptInfo.ProductImgUrl, 255),
|
||
quantity: toNumber(data.Count),
|
||
price: toNumber(data.Price),
|
||
total_amount: toNumber(data.ItemAmount),
|
||
// 店管家基准商品的关联状态(IsRelationBaseProduct=true 表示该明细已关联平台基础商品)
|
||
relation_base_product: !!data.IsRelationBaseProduct,
|
||
base_product: data.BaseProductInfo || null,
|
||
raw: data,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 登录:token + cookie 有效时直接复用;否则用账号密码登录,
|
||
* 成功后把 token 与 cookie 写回账号表,避免上下文丢失
|
||
* @return {Promise<{cookie: string, token: string|null, redirectUrl: string|null, reused: boolean}>} 登录结果
|
||
*/
|
||
async login() {
|
||
if (this.cookie && this.token) {
|
||
const status = await this.checkSession();
|
||
if (status.loggedIn) {
|
||
return { cookie: this.cookie, token: this.token, redirectUrl: null, reused: true, shopName: status.shopName || '' };
|
||
}
|
||
}
|
||
return this.loginByPassword();
|
||
}
|
||
|
||
/**
|
||
* 检查当前账号登录态:token/cookie 缺失视为未登录;
|
||
* 都有则打开工作台校验(未登录会被重定向回门户登录页)
|
||
* @return {Promise<{loggedIn: boolean, message: string, url: string}>} 登录态检查结果
|
||
*/
|
||
async checkSession() {
|
||
if (!this.token) {
|
||
await this.saveLoginStatus(0);
|
||
return { loggedIn: false, message: '账号未保存登录 token,尚未登录', url: USER_INFO_URL };
|
||
}
|
||
if (!this.cookie) {
|
||
await this.saveLoginStatus(0);
|
||
return { loggedIn: false, message: '账号未保存会话 cookie,尚未登录', url: USER_INFO_URL };
|
||
}
|
||
|
||
const info = await this.getUserInfo(this.token, this.cookie);
|
||
const loggedIn = info.success;
|
||
if (!loggedIn) await this.saveLoginStatus(0);
|
||
|
||
return {
|
||
loggedIn,
|
||
message: loggedIn ? '登录态有效' : `登录态已失效${info.message ? `(${info.message})` : ''}`,
|
||
url: USER_INFO_URL,
|
||
nickname: info.data ? info.data.FxUserNickName || info.data.NickName || '' : '',
|
||
shopName: info.data ? info.data.ShopName || '' : '',
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 账号密码登录(两次 POST:BindWeChatPrompt → LoginPortal)
|
||
* @return {Promise<{cookie: string, token: string|null, redirectUrl: string|null, reused: boolean}>} 登录结果
|
||
*/
|
||
async loginByPassword() {
|
||
const { account, password } = this.getCredentials();
|
||
let cookie = await this.bootstrapSession();
|
||
|
||
const prompt = await this.postForm(BIND_WECHAT_PROMPT_URL, this.buildLoginForm(account, password, false), cookie);
|
||
cookie = mergeCookie(cookie, prompt.setCookies);
|
||
if (!this.isSuccess(prompt)) {
|
||
throw new Error(`店管家登录前置校验失败:${describeFailure(prompt)}`);
|
||
}
|
||
|
||
const result = await this.postForm(LOGIN_URL, this.buildLoginForm(account, password, true), cookie);
|
||
cookie = mergeCookie(cookie, result.setCookies);
|
||
const data = result.json && result.json.Data;
|
||
if (!this.isSuccess(result) || !data || !data.Token) {
|
||
throw new Error(`店管家登录失败:${describeFailure(result)}`);
|
||
}
|
||
|
||
// 用登录返回的 token + cookie 拉取账号信息,确认登录态真正可用后再落库
|
||
const info = await this.getUserInfo(data.Token, cookie);
|
||
if (!info.success) {
|
||
throw new Error(`店管家登录后校验失败:${info.message || '获取账号信息失败'}`);
|
||
}
|
||
|
||
await this.saveCookie(cookie);
|
||
await this.saveToken(data.Token);
|
||
return {
|
||
cookie,
|
||
token: data.Token,
|
||
redirectUrl: data.RedirectUrl || null,
|
||
reused: false,
|
||
shopName: info.data ? info.data.ShopName || '' : '',
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 访问门户建立会话,拿到 WAF / ASP.NET 基础 cookie
|
||
* @return {Promise<string>} 新建的 cookie
|
||
*/
|
||
async bootstrapSession() {
|
||
const res = await fetch(PORTAL_URL, {
|
||
method: 'GET',
|
||
headers: BROWSER_HEADERS,
|
||
redirect: 'follow',
|
||
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
||
});
|
||
// 只需要响应头里的 set-cookie,正文丢弃
|
||
await res.arrayBuffer().catch(() => {});
|
||
return mergeCookie('', getSetCookies(res));
|
||
}
|
||
|
||
/**
|
||
* 组装登录表单(IsEnc=1:Mobile/Password 做 base64;LoginPortal 额外带空参数)
|
||
* @param {string} account 登录账号
|
||
* @param {string} password 登录密码
|
||
* @param {boolean} forPortal 是否为 LoginPortal 接口
|
||
* @return {URLSearchParams} 表单
|
||
*/
|
||
buildLoginForm(account, password, forPortal) {
|
||
const form = new URLSearchParams();
|
||
form.set('Mobile', encodeField(account));
|
||
form.set('Password', encodeField(password));
|
||
form.set('ValidCode', '');
|
||
form.set('IsEnc', '1');
|
||
form.set('NotUseAliyunCaptcha', 'true');
|
||
if (forPortal) {
|
||
form.set('ShopId', '');
|
||
form.set('From', '');
|
||
form.set('PlatformType', '');
|
||
}
|
||
return form;
|
||
}
|
||
|
||
/**
|
||
* 以浏览器 ajax 方式提交登录表单
|
||
* @param {string} url 接口地址
|
||
* @param {URLSearchParams} form 表单
|
||
* @param {string} cookie 会话 cookie
|
||
* @return {Promise<{status: number, json: Object|null, text: string, setCookies: string[]}>} 接口响应
|
||
*/
|
||
async postForm(url, form, cookie) {
|
||
const headers = { ...AJAX_HEADERS };
|
||
if (cookie) headers.cookie = cookie;
|
||
|
||
return this.request(url, {
|
||
method: 'POST',
|
||
headers,
|
||
body: form.toString(),
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 接口是否返回 Success = true
|
||
* @param {{json: Object|null}} res 接口响应
|
||
* @return {boolean} 是否成功
|
||
*/
|
||
isSuccess(res) {
|
||
return !!(res && res.json && res.json.Success === true);
|
||
}
|
||
|
||
/**
|
||
* 把订单推送到店管家打印
|
||
* @param {Object} order 订单数据(字段口径由店管家协议决定)
|
||
* @return {Promise<Object>} 平台响应
|
||
*/
|
||
async print(order) {
|
||
throw new Error(`店管家未实现 print(),订单:${order && order.id}`);
|
||
}
|
||
|
||
/**
|
||
* 店管家取号(Old 系统 Dianguanjia.php#ExpressPrint 同口径)
|
||
*
|
||
* 流程:回读平台订单行 → 已发货/已终结拦截 →
|
||
* CheckTemplateAvaliable(模板/余额)→ ExpressPrint(取号 + 打印数据)。
|
||
*
|
||
* **不做「平台已有运单号就复用」的判断**:是否算重复调用只由幂等表
|
||
* (`openapi_request_idempotency`,按 request_id)决定;平台订单行上的 `LastWaybillCode`
|
||
* 只用于诊断(判断是否真换了号),不参与取号决策。
|
||
* ⚠️ ExpressPrint 会真实消耗面单:默认开启,需要「只读联调」时用 DGJ_WAYBILL_ENABLE=0 关闭。
|
||
* @param {Object} order OMS 订单(order_no / parent_order_no / oaid_order_source_code / place_order_time)
|
||
* @param {Object} options 取号上下文
|
||
* @param {Object} options.template 已绑定的快递接口记录(template_id / platform_type / dbname / raw)
|
||
* @param {number} [options.packageIndex] 包裹序号(0 基):>0 目前不支持,会直接报错(见下)
|
||
* @param {number} [options.packageCount] 包裹张数(默认 1):>1 时同一次请求取多张面单
|
||
* @return {Promise<{waybill_code: string, waybill_codes: string[], printinfo: string, signature: string, encryptprintinfo: string, key: string, ver: string, previous_code: string, raw: Object}>} 取号结果
|
||
*/
|
||
async fetchWaybillNo(order, options = {}) {
|
||
if (!this.token || !this.cookie) throw new Error('店管家账号未登录:缺少 token 或 cookie,请先登录');
|
||
|
||
const template = options.template || {};
|
||
const templateId = String(template.template_id || (template.raw && template.raw.Id) || '').trim();
|
||
if (!templateId) throw new Error('取号缺少面单模板ID:请先在「外部打单平台 → 快递接口」为编码绑定模板');
|
||
|
||
// 订单/取号走「订单域名」,与模板域名不同(视频号订单只在 fxali 能查到)。
|
||
// 1688 分销单在 OMS 里被换算成抖音小店/淘宝(为了选对模板),但订单行仍在 Alibaba 分区,
|
||
// 域名必须按「订单原始平台」算,否则回读订单行会查错域名
|
||
const originalCode = String(options.originalPlatformCode || '').trim();
|
||
const originalPlatformType = originalCode ? DgjService.resolvePlatformType(originalCode) : '';
|
||
const host = resolveOrderHost(originalPlatformType || template.platform_type);
|
||
|
||
const traceId = await this.resolveTraceId();
|
||
|
||
// 分区:模板记录的分区优先,订单不一定同区(模板按账号同步、店铺可能迁区),命中会改写
|
||
let dbname = String(template.dbname || '').trim();
|
||
const logicalOrderId = String(order.parent_order_no || String(order.order_no || '').replace(/^[^-]+-/, '')).trim();
|
||
const platformOrderId = String((order.extend_props && order.extend_props.platform_order_no) || order.oaid_order_source_code || '').trim();
|
||
if (!logicalOrderId) throw new Error('订单缺少店管家系统编号(parent_order_no),无法取号');
|
||
|
||
const placeOrderTime = order.place_order_time || order.pay_time || order.created_at;
|
||
let row = await this.findPlatformOrderRow(host, { traceId, dbname, logicalOrderId, platformOrderId, placeOrderTime });
|
||
if (!row) {
|
||
// 模板分区里查不到时逐个分区回读(取号要用平台的订单行,分区不对就会「未找到订单」)
|
||
let areas = [];
|
||
try {
|
||
areas = await this.listProductAreas(host);
|
||
} catch {
|
||
areas = [];
|
||
}
|
||
for (const area of areas) {
|
||
const candidate = String((area && area.dbname) || '').trim();
|
||
if (!candidate || candidate === dbname) continue;
|
||
try {
|
||
row = await this.findPlatformOrderRow(host, {
|
||
traceId, dbname: candidate, logicalOrderId, platformOrderId, placeOrderTime,
|
||
});
|
||
} catch {
|
||
row = null;
|
||
}
|
||
if (row) {
|
||
dbname = candidate;
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
if (!row) throw new Error(`店管家未找到订单:系统编号 ${logicalOrderId}(域名 ${host},分区 ${dbname || '-'})`);
|
||
|
||
// 平台侧已发货/已终结:不能再取号,也不能把旧运单号当成取号成功(该单应作废/取消)
|
||
if (isOrderFinished(row)) {
|
||
const codeText = row.LastWaybillCode ? `,平台运单号 ${row.LastWaybillCode}` : '';
|
||
throw new Error(`订单在店管家已发货或已终结(ErpState=${row.ErpState || '-'}${codeText}),取号失败:请作废或取消该单,不要再发货`);
|
||
}
|
||
|
||
// 平台已取号但未发货:不再复用。重复调用是否要拦,由幂等表(request_id)负责;
|
||
// 这里只在结果里带上原来的号码,便于判断这次到底有没有换号。
|
||
const previousCode = String(row.LastWaybillCode || '').trim();
|
||
|
||
// 多包裹 / 子单:每次调用都走「新单号打印」,平台会分配一个新号,
|
||
// 所以 WMS 按包裹各调一次即可(packageIndex 无需下发给平台)。
|
||
if (!isWaybillEnabled()) {
|
||
throw new Error('店管家真实取号已关闭(DGJ_WAYBILL_ENABLE=0):当前只做只读校验,不会调用平台取号;需要真实取号请去掉该环境变量或置为 1');
|
||
}
|
||
|
||
const runPrint = async () => {
|
||
const check = await this.checkTemplateAvailable(host, { traceId, dbname, templateId, rows: [ row ] });
|
||
const balance = Number(check && check.Data && check.Data.Balance);
|
||
const needCount = Number(check && check.Data && check.Data.PrintCount);
|
||
if (Number.isFinite(balance) && Number.isFinite(needCount) && balance < needCount) {
|
||
throw new Error('店管家面单余额不足,请充值后再取号');
|
||
}
|
||
return await this.expressPrint(host, {
|
||
traceId,
|
||
dbname,
|
||
templateId,
|
||
rows: [ row ],
|
||
checkData: check && check.Data,
|
||
packageCount: Number(options.packageCount || 1),
|
||
expressCode: String(options.expressCode || '').trim(),
|
||
});
|
||
};
|
||
|
||
let printed;
|
||
try {
|
||
printed = await runPrint();
|
||
} catch (err) {
|
||
// 账号在别处重新登录会把这里的 token 顶掉(平台返回 401):重新登录后重试一次
|
||
if (!/登录已失效|登录信息过期/.test(String(err && err.message))) throw err;
|
||
await this.loginByPassword();
|
||
printed = await runPrint();
|
||
}
|
||
const items = Array.isArray(printed && printed.Data && printed.Data.WaybillCode) ? printed.Data.WaybillCode : [];
|
||
|
||
const errorItem = items.find(item => item && (item.IsError === true || Number(item.IsError) === 1));
|
||
if (errorItem) {
|
||
const reason = errorItem.ErrorMsg || errorItem.Message || (errorItem.OrderInfo && errorItem.OrderInfo.ErrorMsg) || '平台返回取号失败';
|
||
throw buildPlatformError(`店管家取号失败:${reason}`, { status: 200, json: printed, text: '' });
|
||
}
|
||
|
||
const waybillCodes = extractWaybillCodes(items);
|
||
if (!waybillCodes.length) {
|
||
throw buildPlatformError('店管家未返回运单号:请检查模板与订单状态,或查看原始响应', { status: 200, json: printed, text: '' });
|
||
}
|
||
|
||
const document = firstPrintDocument(printed, waybillCodes[0]);
|
||
const contents = extractDocumentContents(document);
|
||
// 模板上落的是 OMS 预设编码,优先用它判断平台;缺失时再按打单平台原始类型/调用方编码换算
|
||
const platformCode = String((template && template.platform_code) || '').trim().toUpperCase()
|
||
|| resolveOrderPlatform((template && template.platform_type) || options.platformCode).code;
|
||
const printFields = buildWaybillPrintFields({
|
||
platformCode,
|
||
contents,
|
||
documentPrintInfo: firstPrintInfo(items, printed, waybillCodes[0]),
|
||
});
|
||
return {
|
||
waybill_code: waybillCodes[0],
|
||
waybill_codes: waybillCodes,
|
||
// 打印记录ID(平台 PrintHistoryIds):重打/作废/查打印记录时平台按它回捞,仅本地留痕
|
||
print_history_ids: extractPrintHistoryIds(printed),
|
||
// 实际命中的分区库名:重取打印数据(PrintHistory/LoadPrintData)要带上同一个 dbname
|
||
dbname,
|
||
// 实际命中的订单域名:重取打印数据要发到同一个域名
|
||
host,
|
||
// 面单打印数据:原样透传(WMS 打印端直接塞进 task.printInfo)
|
||
printinfo: printFields.printinfo,
|
||
signature: contents.signature,
|
||
encryptprintinfo: printFields.encryptprintinfo,
|
||
// 快手逐单加密密钥(base64,约 172 字符),其余平台为空串
|
||
key: printFields.key,
|
||
ver: contents.ver,
|
||
// 取号前后对比用的旧号码(不参与判断,只用于提示「平台仍返回原运单号」)
|
||
previous_code: previousCode,
|
||
raw: printed,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 按系统编号 / 平台单号回读店管家订单行(取号请求需要完整的订单结构)
|
||
*
|
||
* 优先按字段精确过滤(实测 `LogicOrderId` 可直接命中),失败时按订单创建时间窗扫描
|
||
* (`NewOrder/List` 的 Filters 依赖平台内部查询实现,时间窗是更稳的兜底)。
|
||
* @param {string} host 订单接口域名
|
||
* @param {Object} options 查询参数
|
||
* @param {string} options.traceId 登录上下文 traceId
|
||
* @param {string} options.dbname 分区库名
|
||
* @param {string} options.logicalOrderId 店管家系统编号
|
||
* @param {string} [options.platformOrderId] 店管家订单编号
|
||
* @param {Date|string} [options.placeOrderTime] 订单下单时间(兜底扫描的时间窗基准)
|
||
* @return {Promise<Object|null>} 订单行,未找到为 null
|
||
*/
|
||
async findPlatformOrderRow(host, { traceId, dbname, logicalOrderId, platformOrderId, placeOrderTime }) {
|
||
const candidates = [];
|
||
if (logicalOrderId) candidates.push([ 'LogicOrderId', logicalOrderId, false ]);
|
||
if (platformOrderId && platformOrderId !== logicalOrderId) candidates.push([ 'PlatformOrderId', platformOrderId, true ]);
|
||
|
||
for (const [ field, value, customQuery ] of candidates) {
|
||
const rows = await this.fetchOrderRows(host, { traceId, dbname, field, value, customQuery });
|
||
if (!rows.length) continue;
|
||
const hit = rows.find(row => String(row.LogicOrderId || '') === String(logicalOrderId)) || rows[0];
|
||
return hit;
|
||
}
|
||
|
||
// 兜底:按下单时间窗口扫描(±2 天),再按系统编号匹配
|
||
const base = placeOrderTime ? new Date(placeOrderTime) : new Date();
|
||
if (Number.isNaN(base.getTime())) return null;
|
||
const startTime = new Date(base.getTime() - 2 * 24 * 3600 * 1000);
|
||
const endTime = new Date(base.getTime() + 2 * 24 * 3600 * 1000);
|
||
const rows = await this.fetchOrderPages(host, { traceId, dbname, startTime, endTime });
|
||
return rows.find(row => String(row.LogicOrderId || '') === String(logicalOrderId)) || null;
|
||
}
|
||
|
||
/**
|
||
* 按单个字段精确过滤订单列表
|
||
* @param {string} host 平台域名
|
||
* @param {Object} options 查询参数
|
||
* @param {string} options.traceId 登录上下文 traceId
|
||
* @param {string} options.dbname 分区库名
|
||
* @param {string} options.field 过滤字段(LogicOrderId / PlatformOrderId)
|
||
* @param {string} options.value 过滤值
|
||
* @param {boolean} [options.customQuery] 是否附加平台自定义查询(PlatformOrderId 需要)
|
||
* @return {Promise<Array>} 订单行
|
||
*/
|
||
async fetchOrderRows(host, { traceId, dbname, field, value, customQuery = false }) {
|
||
const query = new URLSearchParams({
|
||
token: this.token,
|
||
traceId: traceId || '',
|
||
dbname: dbname || '',
|
||
dataFlag: '',
|
||
});
|
||
|
||
const form = new URLSearchParams();
|
||
form.append('Filters[0][TableAlias]', 'o');
|
||
form.append('Filters[0][FieldType]', 'string');
|
||
form.append('Filters[0][TableName]', 'LogicOrder');
|
||
form.append('Filters[0][Name]', field);
|
||
form.append('Filters[0][Value]', String(value));
|
||
form.append('Filters[0][Contract]', 'in');
|
||
if (customQuery) form.append('Filters[0][CustomQuery]', 'PlatformOrderIdSearch');
|
||
form.set('IsOrderDesc', 'true');
|
||
form.set('OrderByField', 'o.CreateTime');
|
||
form.set('IsPdd', 'false');
|
||
form.set('PageSize', '20');
|
||
form.set('PageIndex', '1');
|
||
form.set('isFilterDangerChar', 'false');
|
||
form.set('TarType', '');
|
||
form.set('requestUrl', `https://${host}/NewOrder/WaitOrder`);
|
||
form.set('IsCustomerOrder', 'false');
|
||
form.set('FxPageType', '2');
|
||
|
||
const headers = {
|
||
accept: 'application/json, text/javascript, */*; q=0.01',
|
||
'accept-language': 'zh-CN,zh;q=0.9',
|
||
'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
|
||
referer: `https://${host}/NewOrder/WaitOrder`,
|
||
'user-agent': BROWSER_HEADERS['user-agent'],
|
||
'x-requested-with': 'XMLHttpRequest',
|
||
};
|
||
if (this.cookie) headers.cookie = this.cookie;
|
||
|
||
const res = await this.request(`https://${host}${ORDER_LIST_PATH}?${query.toString()}`, {
|
||
method: 'POST',
|
||
headers,
|
||
body: form.toString(),
|
||
});
|
||
if (res.status === 401) {
|
||
throw new Error(`店管家登录已失效:${(res.json && res.json.Message) || 'token is invalid'}`);
|
||
}
|
||
if (!res.json || res.json.Success !== true) {
|
||
const reason = (res.json && (res.json.Message || res.json.ErrorCode)) || `HTTP ${res.status}`;
|
||
throw new Error(`查询店管家订单失败:${reason}`);
|
||
}
|
||
const data = res.json.Data || {};
|
||
return Array.isArray(data.Rows) ? data.Rows : [];
|
||
}
|
||
|
||
/**
|
||
* 取登录上下文 traceId(实例级缓存)
|
||
*
|
||
* `getUserInfo` 也是一次平台请求,批量取号/重打时逐单调用会把请求量翻几倍,
|
||
* 容易被平台判成高频访问;同一实例内缓存 5 分钟足够(traceId 只用于串联日志)。
|
||
* @param {Object} [options] 参数
|
||
* @param {number} [options.ttlMs] 缓存时长(毫秒)
|
||
* @return {Promise<string>} traceId,取不到为空串
|
||
*/
|
||
async resolveTraceId({ ttlMs = 5 * 60 * 1000 } = {}) {
|
||
const now = Date.now();
|
||
if (this._traceCache && now - this._traceCache.at < ttlMs) return this._traceCache.value;
|
||
let value = '';
|
||
try {
|
||
const info = await this.getUserInfo();
|
||
value = (info.data && info.data.TraceId) || '';
|
||
} catch {
|
||
value = '';
|
||
}
|
||
this._traceCache = { value, at: now };
|
||
return value;
|
||
}
|
||
|
||
/**
|
||
* 取号前校验模板可用性与面单余额(只读,与旧系统 TemplateSet/CheckTemplateAvaliable 同口径)
|
||
* @param {string} host 平台域名
|
||
* @param {Object} options 参数
|
||
* @param {string} options.traceId 登录上下文 traceId
|
||
* @param {string} options.dbname 分区库名
|
||
* @param {string} options.templateId 面单模板ID
|
||
* @param {Array} options.rows 平台订单行
|
||
* @return {Promise<Object>} 平台响应(Data.DateNow / DayPrintBatchNumber / Branches / Balance / PrintCount)
|
||
*/
|
||
async checkTemplateAvailable(host, { traceId, dbname, templateId, rows }) {
|
||
const items = (rows || []).map(row => ({
|
||
SourceShopId: row.ShopId,
|
||
UpFxUserId: row.FxUserId,
|
||
SourceFxUserId: row.FxUserId,
|
||
LogicOrderId: row.LogicOrderId,
|
||
PlatformOrderId: row.LogicOrderId,
|
||
IsAllowNegativeStock: 'false',
|
||
SendType: row.SendState,
|
||
DataFlag: row.IsCold,
|
||
Items: (Array.isArray(row.SubOrders) ? row.SubOrders : []).map(sub => ({
|
||
OrderItemCode: sub.OrderItemCode,
|
||
LogicOrderItemId: sub.OrderItemId,
|
||
Quantity: '1',
|
||
})),
|
||
}));
|
||
|
||
const form = buildPhpForm({
|
||
templateId: String(templateId),
|
||
printCount: String(items.length),
|
||
needCheck: 'true',
|
||
orders: items,
|
||
isResend: '',
|
||
pirntMethod: 'Normal',
|
||
IsContinueForStock: 'false',
|
||
IsCustomerOrder: 'false',
|
||
FxPageType: '2',
|
||
});
|
||
|
||
const res = await this.postPlatformForm(host, TEMPLATE_AVAILABLE_PATH, form, traceId, dbname);
|
||
if (!res.json || res.json.Success !== true) {
|
||
const reason = (res.json && (res.json.Message || res.json.ErrorCode)) || `HTTP ${res.status}`;
|
||
// 附带平台原始返回,便于取号记录留痕与排错
|
||
throw buildPlatformError(`店管家模板校验失败:${reason}`, res);
|
||
}
|
||
return res.json;
|
||
}
|
||
|
||
/**
|
||
* 取号(同时返回打印数据):**真实消耗面单**,仅供 fetchWaybillNo 在开关打开后调用
|
||
* @param {string} host 平台域名
|
||
* @param {Object} options 参数
|
||
* @param {string} options.traceId 登录上下文 traceId
|
||
* @param {string} options.dbname 分区库名
|
||
* @param {string} options.templateId 面单模板ID
|
||
* @param {Array} options.rows 平台订单行
|
||
* @param {Object} [options.checkData] CheckTemplateAvaliable 返回的 Data(DateNow / DayPrintBatchNumber / Branches)
|
||
* @param {number} [options.packageCount] 包裹张数(默认 1):>1 时把同一订单行重复 N 份
|
||
* @param {string} [options.expressCode] 快递编码(仅用于回传 WaybillCodes 时补 ExpressCpCode)
|
||
* @param {boolean} [options.reuseWaybill] 复用平台已有运单号、只拉取打印数据(不分配新面单);拉 params 时用
|
||
* @return {Promise<Object>} 平台响应(Data.WaybillCode[] 含运单号与打印数据)
|
||
*/
|
||
async expressPrint(host, { traceId, dbname, templateId, rows, checkData, packageCount = 1, expressCode = '', reuseWaybill = false }) {
|
||
const data = checkData || {};
|
||
const repeat = Number.isFinite(Number(packageCount)) && Number(packageCount) > 1 ? Math.floor(Number(packageCount)) : 1;
|
||
const currentWaybillCode = (() => {
|
||
const row = (rows || [])[0] || {};
|
||
const list = Array.isArray(row.WaybillCodes) ? row.WaybillCodes.filter(item => item && item.WaybillCode) : [];
|
||
return String(row.LastWaybillCode || (list[list.length - 1] || {}).WaybillCode || '').trim();
|
||
})();
|
||
const branches = Array.isArray(data.Branches) ? data.Branches.map(branch => {
|
||
const copy = { ...branch };
|
||
for (const key of Object.keys(copy)) {
|
||
if (copy[key] === null) copy[key] = '';
|
||
else if (copy[key] === false) copy[key] = 'false';
|
||
else if (copy[key] === true) copy[key] = 'true';
|
||
}
|
||
return copy;
|
||
}) : '';
|
||
|
||
// 多包裹:同一订单行重复 N 份,Index 依次 1..N(平台按包裹各分配一个运单号)
|
||
const sourceRows = [];
|
||
for (let i = 0; i < repeat; i += 1) sourceRows.push(...(rows || []));
|
||
|
||
const orders = sourceRows.map((row, index) => {
|
||
const items = [];
|
||
const orderItems = [];
|
||
for (const sub of Array.isArray(row.SubOrders) ? row.SubOrders : []) {
|
||
items.push({
|
||
OrderItemId: sub.OrderItemId,
|
||
OrderItemCode: sub.OrderItemCode,
|
||
Quantity: '1',
|
||
ShortTitle: sub.ShortTitle,
|
||
SkuCode: sub.SkuCode,
|
||
ProductCode: sub.ProductCode,
|
||
});
|
||
orderItems.push(sub.OrderItemId);
|
||
}
|
||
return {
|
||
WaybillCodeId: '',
|
||
Index: index + 1,
|
||
Id: row.Id,
|
||
IdStr: row.Id,
|
||
PlatformOrderId: row.LogicOrderId,
|
||
LogicOrderId: row.LogicOrderId,
|
||
PathFlowCode: row.PathFlowCode,
|
||
CustomerOrderId: row.PlatformOrderId,
|
||
ShopId: row.ShopId,
|
||
// 与平台前端一致:PrintInfo 传 `[1];\n`(第 1 份)
|
||
PrintInfo: '[1];\n',
|
||
OrderItems: orderItems,
|
||
Items: items,
|
||
OrderItemStrList: orderItems,
|
||
// 新单号打印:把当前号(含 Pid/WaybillCodeId)带给平台,平台据此分配下一个号
|
||
WaybillCode: currentWaybillCode,
|
||
WaybillCodes: buildWaybillCodesBlock(row, templateId, expressCode),
|
||
NewSellerRemark: '',
|
||
PrintRemark: '',
|
||
NewPrintRemark: '',
|
||
SellerRemark: row.SellerRemark,
|
||
BuyerRemark: row.BuyerRemark,
|
||
FxUserId: row.FxUserId,
|
||
IsSelectAllNotPrintedItem: '1',
|
||
SendType: '0',
|
||
DataFlag: row.IsCold,
|
||
Receiver: {
|
||
toFullName: row.ToName,
|
||
toMobile: row.ToPhone,
|
||
toArea: row.ToFullAddress,
|
||
toProvince: row.ToProvince,
|
||
toCity: row.ToCity,
|
||
toCounty: row.ToCounty,
|
||
toMaskAddress: `${row.ToTown || ''}${row.ToAddress || ''}`,
|
||
},
|
||
Sender: { CompanyName: '' },
|
||
Buyer: { BuyerWangWang: row.ToName },
|
||
};
|
||
});
|
||
|
||
const form = buildPhpForm({
|
||
TemplateId: String(templateId),
|
||
PackageCount: String(repeat),
|
||
PackageDesc: '',
|
||
GoodsDesc: '',
|
||
// 「复用已有运单号」拉取打印数据:PrintMethod=Normal + IsIgnoreWaybillRepeat=true,
|
||
// 平台不再分配新面单,只把打印数据(抖店是 params)重新下发
|
||
PrintMethod: reuseWaybill ? 'Normal' : 'NewPrint',
|
||
IsIgnoreWaybillRepeat: reuseWaybill ? 'true' : 'false',
|
||
PrinterName: '默认打印机',
|
||
IsPreview: 'false',
|
||
IsContinueForStock: 'false',
|
||
PackageLength: '',
|
||
PackageWidth: '',
|
||
PackageHeight: '',
|
||
PackageType: '1',
|
||
ExpressSustenance: { name: '', desc: '' },
|
||
Branches: Array.isArray(branches) ? branches : '',
|
||
Orders: orders,
|
||
RequestBatchNumber: `1/1/${data.DateNow || ''}${data.DayPrintBatchNumber || ''}`,
|
||
IsCustomerOrder: 'false',
|
||
FxPageType: '2',
|
||
});
|
||
|
||
const res = await this.postPlatformForm(host, EXPRESS_PRINT_PATH, form, traceId, dbname);
|
||
if (!res.json || res.json.Success !== true) {
|
||
const reason = (res.json && (res.json.Message || res.json.ErrorCode)) || `HTTP ${res.status}`;
|
||
// 附带平台原始返回(含 PrintInfo / WaybillCode 等),便于取号记录留痕与排错
|
||
throw buildPlatformError(`店管家取号请求失败:${reason}`, res);
|
||
}
|
||
return res.json;
|
||
}
|
||
|
||
/**
|
||
* 拉取面单打印参数(抖店等需要 `params` 的平台;复用已有运单号,**不分配新面单**)
|
||
*
|
||
* 背景:抖店面单打印走的是一串带签名的 `params`
|
||
* (`access_token=…&method=logistics.getShopKey×tamp=…&sign=…`),**10 分钟过期**;
|
||
* 而 `PrintHistory/LoadPrintData` 只回放历史签名(实测不重签),拿不到新鲜串。
|
||
* 平台侧唯一能重新下发的入口是 `ExpressPrint`:
|
||
* `PrintMethod=Normal + IsIgnoreWaybillRepeat=true` → 复用订单已有运单号、只重新下发打印数据。
|
||
* 注意:这不是「重打」,只是把打印数据(params)重新取一次;真正的打印在打印端做。
|
||
* @param {string} host 平台域名
|
||
* @param {Object} options 参数
|
||
* @param {string} options.traceId 登录上下文 traceId
|
||
* @param {string} options.dbname 分区库名
|
||
* @param {string} options.templateId 面单模板ID
|
||
* @param {Object} options.row 平台订单行(findPlatformOrderRow 的返回)
|
||
* @param {string} [options.expressCode] 快递编码
|
||
* @return {Promise<{waybill_codes: string[], documents: Array<{documentID: string, params: string, template_url: string}>, raw: Object}>} 打印数据
|
||
*/
|
||
async fetchPrintParams(host, { traceId = '', dbname = '', templateId, row, expressCode = '' }) {
|
||
if (!row) throw new Error('拉取打印参数需要平台订单行');
|
||
// 必须带模板校验的返回一起提交:`RequestBatchNumber` 由 `DateNow + DayPrintBatchNumber` 拼成,
|
||
// 缺了就变成 `1/1/`,平台侧会抛空引用(「未将对象引用设置到对象的实例」)或回空打印数据(2026-11-07 实测)
|
||
const check = await this.checkTemplateAvailable(host, { traceId, dbname, templateId, rows: [ row ] });
|
||
const printed = await this.expressPrint(host, {
|
||
traceId,
|
||
dbname,
|
||
templateId,
|
||
rows: [ row ],
|
||
checkData: check && check.Data,
|
||
expressCode,
|
||
reuseWaybill: true,
|
||
});
|
||
|
||
const errorItem = (Array.isArray(printed && printed.Data && printed.Data.WaybillCode) ? printed.Data.WaybillCode : [])
|
||
.find(item => item && (item.IsError === true || Number(item.IsError) === 1));
|
||
if (errorItem) {
|
||
const reason = errorItem.ErrMsg || errorItem.ErrorMsg || '平台返回失败';
|
||
throw buildPlatformError(`店管家拉取打印参数失败:${reason}`, { status: 200, json: printed, text: '' });
|
||
}
|
||
|
||
const documents = [];
|
||
const docs = printed && printed.Data && printed.Data.PrintDataList && printed.Data.PrintDataList.task &&
|
||
printed.Data.PrintDataList.task.documents;
|
||
for (const doc of Array.isArray(docs) ? docs : []) {
|
||
const contents = Array.isArray(doc && doc.contents) ? doc.contents : [];
|
||
const content = contents.find(item => item && String(item.params || '').trim()) || contents[0] || {};
|
||
documents.push({
|
||
documentID: String((doc && doc.documentID) || ''),
|
||
params: String(content.params || ''),
|
||
template_url: String(content.templateURL || ''),
|
||
});
|
||
}
|
||
// 平台「成功」但没给打印数据(模板批次号不匹配/面单状态异常时会这样)也按失败处理,
|
||
// 让上层回退到按打印记录取
|
||
if (!documents.some(doc => doc.params)) {
|
||
throw buildPlatformError('店管家没有返回打印数据(params 为空)', { status: 200, json: printed, text: '' });
|
||
}
|
||
|
||
return {
|
||
waybill_codes: extractWaybillCodes(printed.Data && printed.Data.WaybillCode),
|
||
documents,
|
||
raw: printed,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 按打印记录重新拉取面单打印数据(只读,不消耗面单)
|
||
*
|
||
* 取号返回的打印数据(params)**只有 10 分钟有效期**,WMS 真正打印前要再用一次本接口换新的;
|
||
* 平台入参为打印记录ID(`PrintHistoryIds[].Id`)数组 + 分区 dbname。
|
||
* @param {string} host 平台域名
|
||
* @param {Object} options 参数
|
||
* @param {string} options.traceId 登录上下文 traceId
|
||
* @param {string} options.dbname 分区库名(取号时命中的那个)
|
||
* @param {Array<string|number>} options.printHistoryIds 打印记录ID数组
|
||
* @return {Promise<Array<{print_history_id: string, waybill_code: string, template_id: string, print_data: string, raw: Object}>>} 打印数据
|
||
*/
|
||
async loadPrintData(host, { traceId = '', dbname = '', printHistoryIds = [] }) {
|
||
const ids = (printHistoryIds || [])
|
||
.map(value => String(value == null ? '' : value).trim())
|
||
.filter(Boolean);
|
||
if (!ids.length) throw new Error('重新获取打印数据需要打印记录ID(printHistoryIds)');
|
||
if (!this.token || !this.cookie) {
|
||
throw new Error('店管家账号未登录:缺少 token 或 cookie,请先登录');
|
||
}
|
||
|
||
const form = buildPhpForm({
|
||
printHistoryIds: ids,
|
||
IsCustomerOrder: 'false',
|
||
FxPageType: '1',
|
||
});
|
||
const res = await this.postPlatformForm(host, PRINT_HISTORY_DATA_PATH, form, traceId, dbname);
|
||
if (!res.json || res.json.Success !== true) {
|
||
const reason = (res.json && (res.json.Message || res.json.ErrorCode)) || `HTTP ${res.status}`;
|
||
throw buildPlatformError(`店管家读取打印记录失败:${reason}`, res);
|
||
}
|
||
|
||
const rows = Array.isArray(res.json.Data) ? res.json.Data : [];
|
||
return rows.map(row => ({
|
||
print_history_id: String(row && row.ID == null ? '' : row.ID),
|
||
waybill_code: String((row && row.ExpressWaybillCode) || ''),
|
||
template_id: row && row.TemplateId == null ? '' : String(row.TemplateId),
|
||
// 平台原样返回的打印数据(params):WMS 打印端直接使用
|
||
print_data: String((row && row.PrintDataJson) || ''),
|
||
raw: row,
|
||
}));
|
||
}
|
||
|
||
/**
|
||
* 通知平台发货(对齐平台「待打订单 → 发货」的 `POST /NewOrder/OnlineSend`,2026-11-07 抓包)
|
||
*
|
||
* WMS 回传 `deliveryorder.confirm`、OMS 流转到「配送」后,需要把发货结果同步回店管家,
|
||
* 平台才会把订单状态推进为「已发货」。走**订单域名**(`fxali` / `fxdd` / `fxpdd` / `fxjd`)。
|
||
* @param {string} host 订单接口域名
|
||
* @param {Object} options 参数
|
||
* @param {string} options.traceId 登录上下文 traceId
|
||
* @param {string} options.dbname 分区库名
|
||
* @param {Array} options.rows 平台订单行(含 SubOrders / LastWaybillCode / WaybillCodes / ShippingType)
|
||
* @param {string} [options.templateId] 面单模板ID(平台页面会带上,缺了会被判「请先勾选要发货的订单」)
|
||
* @param {string|number} [options.expressCompanyId] 快递公司ID(同模板记录)
|
||
* @param {string} [options.expressCode] 快递编码兜底
|
||
* @return {Promise<Object>} 平台响应
|
||
*/
|
||
async sendOrders(host, { traceId, dbname, rows, templateId = '', expressCompanyId = '', expressCode = '' }) {
|
||
const orders = (rows || []).map((row, index) => buildSendOrder(row, index, expressCode));
|
||
const now = new Date();
|
||
const pad = value => String(value).padStart(2, '0');
|
||
const batchNo = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}${pad(now.getHours())}${pad(now.getMinutes())}` +
|
||
String(Date.now()).slice(-9) + Math.floor(Math.random() * 100000);
|
||
|
||
// 顶层参数按平台「待打订单 → 发货」实际请求对齐(2026-11-07 抓包):
|
||
// 少了 TemplateId / ExpressCompanyId 时平台会回「请先勾选要发货的订单」
|
||
const form = buildPhpForm({
|
||
Orders: orders,
|
||
TemplateId: String(templateId || (rows && rows[0] && rows[0].LastExpressPrintTemplateId) || ''),
|
||
ExpressCompanyId: String(expressCompanyId || ''),
|
||
ExcludeOrders: { productItemCount: 0, productCount: 0 },
|
||
NoLogisticsInfoModel: '',
|
||
IsSendPreCheck: 'true',
|
||
IsContinueForStock: 'false',
|
||
RequestBatchNumber: `1/1/${batchNo}`,
|
||
IsCustomerOrder: 'false',
|
||
FxPageType: '2',
|
||
});
|
||
|
||
const res = await this.postPlatformForm(host, ONLINE_SEND_PATH, form, traceId, dbname);
|
||
if (res.status === 401) {
|
||
throw buildPlatformError(`店管家登录已失效:${(res.json && res.json.Message) || 'token is invalid'}`, res);
|
||
}
|
||
// 单包裹发送时,平台整包回「存在不是待发货的商品,发货失败」= 这一单已经不在待发货
|
||
// (平台侧已发货/已取消),属于幂等:直接按成功返回,避免反复重试被打成「异常」
|
||
const topMessage = String((res.json && res.json.Message) || '');
|
||
if (res.json && res.json.Success !== true && orders.length === 1 && SEND_ALREADY_DONE_PATTERN.test(topMessage)) {
|
||
if (this.logger && typeof this.logger.info === 'function') {
|
||
this.logger.info('[dgj.sendOrders] 平台侧该单已不是待发货,按已同步处理:%s %s', orders[0].LogicOrderId, topMessage);
|
||
}
|
||
return res.json;
|
||
}
|
||
if (!res.json || res.json.Success !== true) {
|
||
const json = res.json || {};
|
||
const hints = [];
|
||
if (json.ErrorCode !== undefined && json.ErrorCode !== null && String(json.ErrorCode) !== '') {
|
||
hints.push(`ErrorCode=${json.ErrorCode}`);
|
||
}
|
||
hints.push(...describeSendErrors(json));
|
||
// 平台对「这一单还没运单号」只回一句「请先…」,补一句本地判断,避免只看到半句话
|
||
const missingWaybill = orders.filter(item => !String(item.WaybillCode || '').trim()).length;
|
||
if (missingWaybill) {
|
||
hints.push(`其中 ${missingWaybill} 单在店管家还没有运单号(可能未取号/未打印面单)`);
|
||
}
|
||
const reason = [
|
||
json.Message || `HTTP ${res.status}`,
|
||
...hints,
|
||
].filter(Boolean).join(';');
|
||
// 「请先勾选要发货的订单」= 平台没把提交的 Orders 当成有效选中项,
|
||
// 属于报文口径问题(不是业务状态问题),补一句指向文档的提示便于排查
|
||
const notSelected = /勾选/.test(String(json.Message || ''));
|
||
// 平台只回一串数字/服务器繁忙时不是业务原因,是它没能解析我们提交的订单行(多为 SubOrders 等字段缺失)
|
||
const payloadRejected = isPayloadRejected(json);
|
||
throw buildPlatformError(
|
||
`店管家发货同步失败:${reason}${notSelected ? '(平台未识别提交的订单报文,需核对 OnlineSendBatch 报文口径)' : ''}` +
|
||
`${payloadRejected ? '(平台未成功解析订单报文,将改用平台实时订单行重试)' : ''}`,
|
||
res
|
||
);
|
||
}
|
||
|
||
// 平台是「整包 Success + 逐单结果」:逐单失败要单独判,否则会把没发成功的单标成已同步。
|
||
// 例外:单子已经是已发货/已取消状态(平台早于我们手工/别处发货)视为幂等成功。
|
||
const failed = extractSendOrderFailures(res.json);
|
||
const realFailures = failed.filter(item => !SEND_ALREADY_DONE_PATTERN.test(item.message));
|
||
if (realFailures.length) {
|
||
// 风控/渠道不匹配:平台按「模板对应的电子面单渠道」校验运单号,模板与运单快递不一致就会拦截
|
||
const riskBlocked = realFailures.some(item =>
|
||
/CONSIGN_RISK_CONTROL_BLOCK|NOT_MATCH_SEGMENT_CHANNEL|风控拦截/.test(item.message));
|
||
const hint = riskBlocked
|
||
? '(运单号不是该平台渠道分配的面单:请确认发货模板与运单快递一致,并用「对应平台 + 该快递」的电子面单模板重新取号)'
|
||
: '';
|
||
// 平台有时不回 LogicOrderId,此时不要拼出「失败:: xxx」这种双冒号
|
||
const detail = realFailures
|
||
.map(item => (item.logicOrderId ? `${item.logicOrderId}: ${item.message}` : item.message))
|
||
.join(';');
|
||
throw buildPlatformError(`店管家发货同步失败:${detail}${hint}`, res);
|
||
}
|
||
if (failed.length && this.logger && typeof this.logger.info === 'function') {
|
||
for (const item of failed) {
|
||
this.logger.info('[dgj.sendOrders] 平台侧该单无需再发货:%s %s', item.logicOrderId, item.message);
|
||
}
|
||
}
|
||
return res.json;
|
||
}
|
||
|
||
/**
|
||
* 统一提交平台表单(token/traceId/dbname 走 query,表单走 body)
|
||
* @param {string} host 平台域名
|
||
* @param {string} path 接口路径
|
||
* @param {URLSearchParams} form 表单
|
||
* @param {string} traceId 登录上下文 traceId
|
||
* @param {string} dbname 分区库名
|
||
* @return {Promise<{status: number, json: Object|null, text: string}>} 响应
|
||
*/
|
||
async postPlatformForm(host, path, form, traceId, dbname) {
|
||
const query = new URLSearchParams({
|
||
token: this.token,
|
||
traceId: traceId || '',
|
||
dbname: dbname || '',
|
||
dataFlag: '',
|
||
});
|
||
const headers = {
|
||
accept: 'application/json, text/javascript, */*; q=0.01',
|
||
'accept-language': 'zh-CN,zh;q=0.9',
|
||
'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
|
||
referer: `https://${host}/NewOrder/WaitOrder`,
|
||
'user-agent': BROWSER_HEADERS['user-agent'],
|
||
'x-requested-with': 'XMLHttpRequest',
|
||
};
|
||
if (this.cookie) headers.cookie = this.cookie;
|
||
|
||
const url = `https://${host}${path}?${query.toString()}`;
|
||
const options = { method: 'POST', headers, body: form.toString() };
|
||
const retryCount = rateLimitRetryCount();
|
||
let res = await this.request(url, options);
|
||
// 服务商级 QPS 限流(isv.request-limited)属于瞬时拒绝,请求未被处理,可以安全退避重试
|
||
for (let attempt = 1; attempt <= retryCount; attempt += 1) {
|
||
if (res.status === 401 || !isRateLimited(res.json)) break;
|
||
const wait = rateLimitBackoffMs() * Math.pow(2, attempt - 1);
|
||
if (this.logger && typeof this.logger.warn === 'function') {
|
||
this.logger.warn('[dgj] %s 被平台限流,%dms 后第 %d 次重试', path, wait, attempt);
|
||
}
|
||
if (wait > 0) await new Promise(resolve => setTimeout(resolve, wait));
|
||
res = await this.request(url, options);
|
||
}
|
||
if (res.status === 401) {
|
||
throw new Error(`店管家登录已失效:${(res.json && res.json.Message) || 'token is invalid'}`);
|
||
}
|
||
if (isRateLimited(res.json)) {
|
||
const message = (res.json && res.json.Message) || '请求太频繁';
|
||
throw buildPlatformError(
|
||
`店管家接口限流:${message};已自动退避重试 ${retryCount} 次仍被限流,请稍后重试`,
|
||
res
|
||
);
|
||
}
|
||
return res;
|
||
}
|
||
|
||
/**
|
||
* 平台返回是否为限流(服务商级 QPS 超限)
|
||
* @param {Object|null} json 平台响应
|
||
* @return {boolean} 是否限流
|
||
*/
|
||
static isRateLimited(json) {
|
||
return isRateLimited(json);
|
||
}
|
||
|
||
/**
|
||
* 平台返回是否为「报文不被接受」类失败(供上层决定是否用实时订单行重发)
|
||
* @param {Object|null} json 平台响应
|
||
* @param {string} [message] 错误文案
|
||
* @return {boolean} 是否为报文类失败
|
||
*/
|
||
static isPayloadRejected(json, message = '') {
|
||
return isPayloadRejected(json, message);
|
||
}
|
||
|
||
/**
|
||
* 订单是否已在平台侧发货或已终结(供脚本/上层按落库的平台原始结构复用同一口径)
|
||
* @param {Object} row 店管家订单原始结构
|
||
* @return {boolean} 是否已发货/已终结
|
||
*/
|
||
static isOrderFinished(row) {
|
||
return isOrderFinished(row);
|
||
}
|
||
|
||
/**
|
||
* 店管家 PlatformType 转系统预设平台(供脚本迁移历史数据复用同一口径)
|
||
* @param {string} platformType 店管家 PlatformType
|
||
* @return {{code: string, name: string}} 预设平台
|
||
*/
|
||
static resolveOrderPlatform(platformType) {
|
||
return resolveOrderPlatform(platformType);
|
||
}
|
||
|
||
/**
|
||
* 判定平台订单是否已发货/已终结,并给出可读依据(供上层拼接自动作废备注)
|
||
* @param {Object} row 店管家订单原始结构
|
||
* @return {{finished: boolean, reason: string}} 判定结果与依据
|
||
*/
|
||
static describeFinishedOrder(row) {
|
||
return describeFinishedOrder(row);
|
||
}
|
||
|
||
/**
|
||
* 只读查询平台订单状态(审核前校验「平台是否已发货/已终结」、取号前回读订单行)
|
||
* @param {Object} params 参数
|
||
* @param {string} params.platformType 店管家 PlatformType(如 WxVideo)
|
||
* @param {string} [params.dbname] 分区库名,缺省按分区接口解析
|
||
* @param {string} params.logicalOrderId 店管家系统编号
|
||
* @param {string} [params.platformOrderId] 店管家订单编号
|
||
* @param {Date|string} [params.placeOrderTime] 下单时间(兜底扫描窗口)
|
||
* @return {Promise<Object|null>} 平台订单行
|
||
*/
|
||
async fetchPlatformOrder({ platformType, dbname, logicalOrderId, platformOrderId, placeOrderTime }) {
|
||
if (!logicalOrderId) return null;
|
||
const host = resolveOrderHost(platformType);
|
||
let traceId = '';
|
||
try {
|
||
const info = await this.getUserInfo();
|
||
traceId = (info.data && info.data.TraceId) || '';
|
||
} catch {
|
||
// 忽略:traceId 缺失不阻断查询
|
||
}
|
||
|
||
let area = String(dbname || '').trim();
|
||
if (!area) {
|
||
const areas = await this.listProductAreas(host);
|
||
area = (areas.find(item => item && item.dbname) || {}).dbname || '';
|
||
}
|
||
return await this.findPlatformOrderRow(host, { traceId, dbname: area, logicalOrderId, platformOrderId, placeOrderTime });
|
||
}
|
||
|
||
/**
|
||
* 按系统预设平台编码(SPH/TB/...)推断店管家 PlatformType
|
||
* @param {string} platformCode 系统预设平台编码
|
||
* @return {string} 店管家 PlatformType,未知返回空串
|
||
*/
|
||
static resolvePlatformType(platformCode) {
|
||
const map = {
|
||
SPH: 'WxVideo',
|
||
TB: 'Taobao',
|
||
TM: 'Tmall',
|
||
DYXD: 'TouTiao',
|
||
PDD: 'Pinduoduo',
|
||
JD: 'JingDong',
|
||
KS: 'KuaiShou',
|
||
XHS: 'XiaoHongShu',
|
||
1688: 'Alibaba',
|
||
};
|
||
return map[ String(platformCode || '').trim().toUpperCase() ] || '';
|
||
}
|
||
|
||
/**
|
||
* 店管家 PlatformType 对应的接口域名(供脚本/调试工具复用)
|
||
* @param {string} platformType 店管家 PlatformType(如 WxVideo / TouTiao)
|
||
* @return {string} 域名,未知返回空串
|
||
*/
|
||
static resolveTemplateHost(platformType) {
|
||
return resolveTemplateHost(platformType);
|
||
}
|
||
|
||
/**
|
||
* 店管家 PlatformType 对应的订单/取号域名(与模板域名不同)
|
||
* @param {string} platformType 店管家 PlatformType(如 WxVideo)
|
||
* @return {string} 域名
|
||
*/
|
||
static resolveOrderHost(platformType) {
|
||
return resolveOrderHost(platformType);
|
||
}
|
||
|
||
/**
|
||
* 是否允许真实取号(默认开启,DGJ_WAYBILL_ENABLE=0 关闭)
|
||
* @return {boolean} 是否允许
|
||
*/
|
||
static isWaybillEnabled() {
|
||
return isWaybillEnabled();
|
||
}
|
||
|
||
/**
|
||
* 从 ExpressPrint 响应里解析打印记录(`Data.PrintHistoryIds`)
|
||
* @param {Object} printed ExpressPrint 响应
|
||
* @return {Array<{id: string, pid: string, waybill_code: string, batch_index: number|null}>} 打印记录
|
||
*/
|
||
static extractPrintHistoryIds(printed) {
|
||
return extractPrintHistoryIds(printed);
|
||
}
|
||
|
||
/**
|
||
* 从打印单据里取 signature / encryptedData / key / ver(供脚本/单测复用同一口径)
|
||
* @param {Object} document 打印单据(`documents[]` 中的一项)
|
||
* @return {{signature: string, encryptprintinfo: string, key: string, ver: string}} 打印附加信息
|
||
*/
|
||
static extractDocumentContents(document) {
|
||
return extractDocumentContents(document);
|
||
}
|
||
|
||
/**
|
||
* 组装回给 WMS 的面单打印字段(快手口径与其它平台不同)
|
||
* @param {Object} options 参数
|
||
* @param {string} options.platformCode 系统预设平台编码(如 KS / TB)
|
||
* @param {Object} options.contents extractDocumentContents 的结果
|
||
* @param {string} [options.documentPrintInfo] 平台下发的打印数据
|
||
* @return {{printinfo: string, encryptprintinfo: string, key: string}} 打印字段
|
||
*/
|
||
static buildWaybillPrintFields(options) {
|
||
return buildWaybillPrintFields(options);
|
||
}
|
||
|
||
/**
|
||
* 组装发货回传单体报文(`Orders[i]`),供脚本/单测复用同一口径
|
||
* @param {Object} row 订单行(平台行或本地快照拼装结果)
|
||
* @param {number} index 序号(0 基)
|
||
* @param {string} [expressCode] 快递编码兜底
|
||
* @return {Object} Orders[i]
|
||
*/
|
||
static buildSendOrder(row, index, expressCode = '') {
|
||
return buildSendOrder(row, index, expressCode);
|
||
}
|
||
|
||
/**
|
||
* 构造店管家表单(PHP http_build_query 口径,嵌套用括号)
|
||
* @param {Object} data 表单数据
|
||
* @return {URLSearchParams} 表单
|
||
*/
|
||
static buildForm(data) {
|
||
return buildPhpForm(data);
|
||
}
|
||
}
|
||
|
||
module.exports = DgjService;
|