'use strict'; const PrintPlatformService = require('./base'); const { resolvePlatform } = require('../platformCode'); /** 店管家商家门户站点 */ 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'; /** 订单列表单页条数(平台允许 500) */ const ORDER_PAGE_SIZE = 500; /** 订单查询的最大翻页数,防御平台分页异常 */ const ORDER_MAX_PAGES = 200; /** 商家的分区 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' ], }; /** 商品列表单页条数(平台允许 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 ''; } /** * 平台侧「已发货 / 已终结」的订单状态(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) { const data = row || {}; const state = String(data.ErpState || data.Status || '').trim().toLowerCase(); if (state && FINISHED_ORDER_STATES.includes(state)) return true; if (String(data.OnlineSendTime || '').trim()) return true; const waybills = Array.isArray(data.WaybillCodes) ? data.WaybillCodes : []; if (waybills.some(code => code && code.IsSended === true)) return true; return Number(data.LogisticStatus) > 0; } /** * 商品状态是否为在售:平台不同分区返回的状态值不统一(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 ''; } /** * 店管家(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=(需同时带 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 = {}) { 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(); } /** * 解析店铺需要拉取面单模板的目标(模板接口域名 + PlatformType + 分区库名)。 * 优先级:商家分区 DbAreas/DbArea 里的 DbName(如 pinduoduo)→ 展开该分区的全部库; * 识别不出分区时按商品域名兜底,每个域名取一个代表 PlatformType。 * @param {Object} shop OMS 店铺记录(type=2,external_data 为商家原始结构) * @return {Promise>} 目标列表 */ 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} 平台原始模板列表 */ 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), platform_updated_at: parseOrderTime(data.UpdateDate), raw: data, }; } /** * 拉取店铺关联的全部面单模板(快递接口):逐平台域名 / 分区查询后按模板ID去重。 * 单个分区失败不影响其它分区,错误随结果返回,供上层提示。 * @param {Object} shop OMS 店铺记录(type=2) * @return {Promise<{list: Array, errors: Array, targets: Array}>} 模板列表与逐项错误 */ 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} 平台返回的明细数据 */ 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 || ''), 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>} 分区列表(含默认区) */ 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} 分区商品快照 */ 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} 域名商品快照(含各分区明细) */ 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 })); } 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), 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()), }; } /** * 按平台商品ID(可选规格ID)单独拉取商品,用于订单明细匹配不到店铺商品时按需补拉。 * 单品查询不传 SelectAgentId:商品可能属于同一账号下的其它商家,按商品ID更容易命中; * 域名与分区按「店铺所属分区优先、其余域名兜底」的顺序逐个尝试,命中即停止。 * @param {Object} shop OMS 店铺记录(type=2,external_data 为商家原始结构) * @param {Array<{outer_item_id: string, outer_sku_id?: string}>} items 待补拉的商品 * @return {Promise<{list: Array, missing: Array, hosts: Array}>} 命中的店铺商品行与未命中的商品 */ async listProductsByIds(shop, items = []) { if (!this.token || !this.cookie) { throw new Error('账号未登录:缺少 token 或 cookie,请先登录'); } const data = (shop && shop.external_data) || {}; const hosts = []; for (const host of [ ...this.resolveProductHosts(data), ...FALLBACK_PRODUCT_HOSTS ]) { if (!hosts.includes(host)) hosts.push(host); } let traceId = ''; try { const info = await this.getUserInfo(); traceId = (info.data && info.data.TraceId) || ''; } catch { // 忽略:traceId 缺失不阻断单品查询 } const areaCache = new Map(); const list = []; const missing = []; const hitHosts = new Set(); for (const item of items) { const productId = String((item && item.outer_item_id) || '').trim(); const skuId = String((item && item.outer_sku_id) || '').trim(); if (!productId) { missing.push({ outer_item_id: productId, outer_sku_id: skuId, reason: '缺少平台商品ID' }); continue; } let matched = []; for (const host of hosts) { if (!areaCache.has(host)) areaCache.set(host, await this.listProductAreas(host)); for (const area of areaCache.get(host)) { const page = await this.fetchProductPage(host, { traceId, dbname: area.dbname, productId, skuId, pageIndex: 1, pageSize: 20, }); if (!page.rows.length) continue; for (const product of page.rows) { const rows = this.normalizeProduct(product); // 带规格ID时只保留该规格(平台可能返回整个商品的全部规格) const picked = skuId ? rows.filter(row => row.outer_sku_id === skuId) : rows; matched = matched.concat(picked); } if (matched.length) { hitHosts.add(`${host}(${area.name || area.dbname})`); break; } } if (matched.length) break; } if (matched.length) list.push(...matched); else missing.push({ outer_item_id: productId, outer_sku_id: skuId, reason: '平台未查询到该商品' }); } return { list, missing, hosts: Array.from(hitHosts) }; } /** * 把店管家商品(含 SKU 列表)转换为店铺商品行的统一结构。 * 平台商品ID取商品级 PlatformId;平台规格ID取 SKU 的 SpecId/SkuId * (注意 SKU.PlatformId 是商品级平台ID,不能当作规格ID),缺失时退化为店管家内部ID。 * 原样保留商品与 SKU 结构供后续使用。 * @param {Object} product 店管家商品原始结构 * @return {Array} 店铺商品行(一个 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.SpecId || 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 }, }; }); } /** * 拉取店铺订单(按商家 FxUserId 过滤,只返回仍需本系统处理的未发货订单)。 * 店管家订单列表不提供商家维度的过滤参数(UpFxUserId 过滤会返回服务器繁忙), * 也不提供发货状态过滤,因此按时间窗 + 分区域名拉取全量后,在本地做两步过滤: * 1. 按订单的 UpFxUserId 归属到店铺 * 2. 丢弃平台侧已发货/已终结的订单(见 isOrderFinished),只留未发货的 * 被丢弃的订单号会通过 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}>} 订单列表 */ 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) : new Date(end.getTime() - 7 * 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 = []; for (const host of hosts) { const areas = await this.listProductAreas(host); for (const area of areas) { const fetched = await this.fetchOrderPages(host, { traceId, dbname: area.dbname, startTime: start, endTime: end, }); if (fetched.length) hitHosts.push(`${host}(${area.name || area.dbname})`); for (const row of fetched) { // 订单列表按账号维度返回,这里只保留当前商家的订单 if (String(row.UpFxUserId || '') !== merchantFxUserId) continue; const order = this.normalizeOrder(row); if (!order.external_order_id) continue; // 平台已发货/已终结:不进待审核,只登记给上层用于作废本地未处理的副本 if (isOrderFinished(row)) { finished.set(order.external_order_id, { external_order_id: order.external_order_id, platform_status: order.platform_status, }); continue; } orders.set(order.external_order_id, order); } } } return { total: orders.size, list: Array.from(orders.values()), hosts: hitHosts, skipped: finished.size, finished: Array.from(finished.values()), }; } /** * 按分页拉取订单列表(不归属过滤,交由调用方按商家过滤) * @param {string} host 接口域名 * @param {Object} options 查询参数 * @param {string} options.traceId 登录上下文 traceId * @param {string} options.dbname 分区库名 * @param {Date} options.startTime 下单时间起 * @param {Date} options.endTime 下单时间止 * @return {Promise} 订单原始结构列表 */ async fetchOrderPages(host, { traceId, dbname, startTime, endTime }) { 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, }); 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 页码 * @return {Promise<{rows: Array, total: number, pageCount: number}>} 当页订单 */ async fetchOrderPage(host, { traceId, dbname, startTime, endTime, pageIndex }) { const query = new URLSearchParams({ token: this.token, traceId: traceId || '', dbname: dbname || '', dataFlag: '', }); const form = new URLSearchParams(); const filter = (index, fields) => { for (const [ key, value ] of Object.entries(fields)) form.append(`Filters[${index}][${key}]`, value); }; filter(0, { TableAlias: 'o', FieldType: 'DateTime', TableName: 'LogicOrder', Name: 'CreateTime', Value: formatOrderTime(startTime), ExtValue: formatOrderTime(endTime), Contract: 'between', }); 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); 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: platform.code, 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)), }; } /** * 把店管家订单明细转换为统一结构:平台商品快照原样保留, * 系统商品关联由上层按店铺商品绑定关系决定(未绑定时保持原样) * @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} 新建的 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} 平台响应 */ async print(order) { throw new Error(`店管家未实现 print(),订单:${order && order.id}`); } /** * 店管家取号尚未接入:平台配置 fetch_waybill_no = 0,等待平台取号接口确认后实现 * @param {Object} order 订单数据 * @param {Object} [options] 取号上下文(template / expressCode / platformCode) * @return {Promise} 固定抛错 */ async fetchWaybillNo(order, options = {}) { // eslint-disable-line no-unused-vars throw new Error('店管家取号未接入(fetch_waybill_no=0),请先确认平台取号接口'); } /** * 订单是否已在平台侧发货或已终结(供脚本/上层按落库的平台原始结构复用同一口径) * @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); } } module.exports = DgjService;