'use strict'; const PrintPlatformService = require('./base'); /** 店管家商家门户站点 */ 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'; /** 订单列表单页条数(平台允许 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', ]; /** 商品列表单页条数(平台允许 200) */ const PRODUCT_PAGE_SIZE = 200; /** * 商品状态是否为在售:平台不同分区返回的状态值不统一(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(); } /** * 组装商品列表查询表单(字段口径与店管家工作台一致) * @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 = truncate(data.PlatformType, 32); 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 过滤会返回服务器繁忙), * 因此按时间窗 + 分区域名拉取全量后,在本地按订单的 UpFxUserId 归属到店铺。 * @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}>} 订单列表 */ 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 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) orders.set(order.external_order_id, order); } } } return { total: orders.size, list: Array.from(orders.values()), hosts: hitHosts }; } /** * 按分页拉取订单列表(不归属过滤,交由调用方按商家过滤) * @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 = []; let pageCount = 1; for (let pageIndex = 1; pageIndex <= ORDER_MAX_PAGES; pageIndex++) { const page = await this.fetchOrderPage(host, { traceId, dbname, startTime, endTime, pageIndex, }); rows.push(...page.rows); pageCount = page.pageCount || pageCount; if (page.rows.length < ORDER_PAGE_SIZE || pageIndex >= pageCount) 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 : []; return { external_order_id: String(data.PlatformOrderId || data.LogicOrderId || ''), external_shop_id: data.ShopId == null ? '' : String(data.ShopId), external_shop_name: truncate(data.ShopName || data.AgentShopName || data.SelfShopName, 128), platform_type: truncate(data.PlatformType, 32), platform_status: truncate(data.ErpState || data.Status, 32), order_no: String(data.PlatformOrderId || data.LogicOrderId || ''), 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),调用即视为错误 * @return {Promise} 固定抛错 */ async fetchWaybillNo() { throw new Error('店管家不回平台取号(fetch_waybill_no=0),不应调用 fetchWaybillNo()'); } } module.exports = DgjService;