diff --git a/backend/app/lib/printPlatform/dxm.js b/backend/app/lib/printPlatform/dxm.js index 5a0fa7d..8235f94 100644 --- a/backend/app/lib/printPlatform/dxm.js +++ b/backend/app/lib/printPlatform/dxm.js @@ -21,6 +21,7 @@ const crypto = require('crypto'); const PrintPlatformService = require('./base'); +const { resolvePlatform } = require('../platformCode'); /** 平台配置未填链接时的默认站点 */ const DEFAULT_SITE_URL = 'https://www.dianxiaomi.com'; @@ -34,6 +35,12 @@ const LOGIN_PATH = '/user/userLoginNew2.json'; /** 工作台首页:未登录会 302 到登录页 */ const HOME_PATH = '/home.htm'; +/** 店铺列表:一个平台一个地址(/api/shop/list/.json) */ +const SHOP_LIST_PATH = '/api/shop/list'; + +/** 店铺列表页路径(accept/referer 用) */ +const SHOP_LIST_PAGE_PATH = '/web/shop/shopList'; + const REQUEST_TIMEOUT_MS = 30000; const USER_AGENT = @@ -99,6 +106,18 @@ function isLoginPage(finalUrl, html) { return /id=["']loginForm["']/.test(String(html || '')); } +/** + * 时间戳(毫秒)→ `YYYY-MM-DD HH:mm:ss`(北京时间),空值返回空串 + * @param {*} value 毫秒时间戳 + * @return {string} 格式化时间 + */ +function formatTime(value) { + const ts = Number(value); + if (!Number.isFinite(ts) || ts <= 0) return ''; + const date = new Date(ts + 8 * 3600 * 1000); + return date.toISOString().replace('T', ' ').slice(0, 19); +} + /** * 加密登录字段(账号/密码),与服务端约定的格式见文件头注释 * @param {string} value 明文 @@ -150,6 +169,158 @@ class DxmService extends PrintPlatformService { return withProtocol.replace(/\/+$/, ''); } + /** + * 调用平台 JSON 接口(带登录会话) + * @param {string} path 接口路径(以 / 开头) + * @param {Object} [options] 参数 + * @param {boolean} [options.auth] 是否要求已登录,默认 true + * @return {Promise} 平台 data 字段 + */ + async requestJson(path, { auth = true } = {}) { + if (auth && !this.cookie) { + throw new Error(`店小秘账号未登录:请先登录(${path})`); + } + const res = await this.request(`${this.siteUrl}${path}`, { + headers: { + ...AJAX_HEADERS, + referer: `${this.siteUrl}${SHOP_LIST_PAGE_PATH}`, + cookie: this.cookie, + }, + }); + const json = res.json; + if (!json) { + throw new Error(`店小秘接口返回异常(HTTP ${res.status}):${String(res.text || '').slice(0, 100)}`); + } + if (Number(json.code) !== 0) { + throw new Error(`店小秘接口失败:${json.msg || json.message || `code=${json.code}`}(${path})`); + } + return json.data || {}; + } + + /** + * 已授权店铺的平台标识列表 + * + * 各平台的店铺列表接口都会带 `authOfPlatform.authorizePlatform`, + * 这里用 `all` 探一次,拿到账号当前真正授权的平台,再逐个平台拉店铺。 + * @return {Promise} 平台标识列表(如 shopify / shopee) + */ + async listAuthorizedPlatforms() { + if (!this._authorizedPlatforms) { + this._authorizedPlatforms = (async () => { + const data = await this.requestJson(`${SHOP_LIST_PATH}/all.json`); + const list = data.authOfPlatform && data.authOfPlatform.authorizePlatform; + return Array.isArray(list) ? list.map(item => String(item).trim()).filter(Boolean) : []; + })(); + // 失败时清掉缓存,下一次调用重新探 + this._authorizedPlatforms.catch(() => { + this._authorizedPlatforms = null; + }); + } + return await this._authorizedPlatforms; + } + + /** + * 拉取某个平台下的全部店铺(一个平台一次请求) + * @param {string} platform 平台标识(如 shopify) + * @return {Promise<{platform: string, platformName: string, list: Array}>} 平台店铺 + */ + async fetchPlatformShops(platform) { + const data = await this.requestJson(`${SHOP_LIST_PATH}/${platform}.json`); + return { + platform, + platformName: String(data.platformZhName || data.platform || platform), + list: Array.isArray(data.list) ? data.list : [], + }; + } + + /** + * 拉取账号在所有已授权平台下的店铺,按统一结构返回 + * + * 店小秘把店铺按电商平台分组(`/api/shop/list/.json`),这里合并各平台结果, + * 关键词/状态/平台过滤与分页都在本地做(平台侧店铺数量不大,且单平台接口不分页)。 + * @param {Object} [options] 查询参数 + * @param {string} [options.source] 来源(本平台只有 shop) + * @param {number} [options.pageIndex] 页码,从 1 开始 + * @param {number} [options.pageSize] 每页条数 + * @param {string} [options.keyword] 关键词(店铺名 / 店铺域名 / 平台) + * @param {string} [options.status] 状态:'' 全部 / '1' 正常 / '0' 已过期或已删除 + * @param {string|string[]} [options.platformTypes] 平台过滤(如 shopify,逗号分隔) + * @return {Promise<{total: number, list: Array, source: string}>} 统一店铺列表 + */ + async listShops(options = {}) { + const platforms = await this.listAuthorizedPlatforms(); + const wanted = this.normalizePlatformFilter(options.platformTypes); + const targets = wanted.length ? platforms.filter(item => wanted.includes(item)) : platforms; + + const shops = []; + for (const platform of targets) { + const result = await this.fetchPlatformShops(platform); + for (const shop of result.list) shops.push(this.normalizeShop(shop, result)); + } + + const keyword = String(options.keyword || '').trim().toLowerCase(); + const status = String(options.status == null ? '' : options.status).trim(); + const filtered = shops.filter(item => { + if (status === '1' && item.status !== 1) return false; + if (status === '0' && item.status === 1) return false; + if (!keyword) return true; + return `${item.name} ${item.remark} ${item.platform_name} ${item.platform}`.toLowerCase().includes(keyword); + }); + + filtered.sort((a, b) => (a.platform_name || '').localeCompare(b.platform_name || '') || a.name.localeCompare(b.name)); + + 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 start = (pageIndex - 1) * pageSize; + + return { + total: filtered.length, + list: filtered.slice(start, start + pageSize), + source: String(options.source || (this.listShopSources()[0] || {}).code || 'shop'), + }; + } + + /** + * 平台过滤参数归一化(支持逗号分隔字符串 / 数组) + * @param {string|string[]} value 过滤值 + * @return {string[]} 平台标识列表(小写) + */ + normalizePlatformFilter(value) { + const raw = Array.isArray(value) ? value.join(',') : String(value || ''); + return raw.split(',').map(item => item.trim().toLowerCase()).filter(Boolean); + } + + /** + * 店小秘店铺 → 统一店铺结构(上层/前端只认这套字段) + * @param {Object} shop 平台店铺原始结构 + * @param {Object} platform 平台信息 { platform, platformName } + * @return {Object} 统一店铺结构 + */ + normalizeShop(shop, platform) { + const data = shop || {}; + const deleted = Number(data.isDel) === 1; + const expired = Number(data.isExpire) === 1 || Number(data.isNewExpire) === 1; + const preset = resolvePlatform(data.platform); + return { + source: 'shop', + external_id: String(data.id == null ? '' : data.id), + name: String(data.name || data.sellerLoginId || data.id || ''), + contact_name: '', + contact_phone: '', + status: deleted || expired ? 0 : 1, + status_label: deleted ? '已删除' : expired ? '授权过期' : '正常', + // 平台原始标识(如 shopify)与系统预设编码(跨境平台多为 OTHER),名字优先用平台给的中文名 + platform: String(data.platform || platform.platform || ''), + platform_code: preset.code, + platform_name: platform.platformName || preset.name, + auth_expired: expired, + service_expired: deleted, + auth_time: formatTime(data.authTime), + remark: String(data.sellerLoginId || ''), + raw: data, + }; + } + /** * 统一 JSON/文本请求入口(各实现可被测试替换) * @param {string} url 完整请求地址 diff --git a/backend/test/app/lib/printPlatformDxm.test.js b/backend/test/app/lib/printPlatformDxm.test.js index ef11bbe..d25b583 100644 --- a/backend/test/app/lib/printPlatformDxm.test.js +++ b/backend/test/app/lib/printPlatformDxm.test.js @@ -187,3 +187,111 @@ describe('printPlatform/dxm checkSession', () => { assert.match(result.message, /未保存会话/); }); }); + +describe('printPlatform/dxm listShops', () => { + const shopifyShop = (id, name, extra = {}) => ({ + id: String(id), + name, + platform: 'shopify', + sellerLoginId: `${name}.myshopify.com`, + authTime: Date.UTC(2026, 10, 4, 0, 0, 0), + isDel: 0, + isExpire: 0, + ...extra, + }); + + function createShopService() { + const { service } = createService({ account: { cookie: 'JSESSIONID=ok' } }); + service.listAuthorizedPlatforms = async () => [ 'shopify', 'shopee' ]; + service.fetchPlatformShops = async platform => { + if (platform === 'shopify') { + return { + platform, + platformName: 'Shopify', + list: [ + shopifyShop(1, 'aaa-store'), + shopifyShop(2, 'bbb-store', { isExpire: 1 }), + shopifyShop(3, 'ccc-store', { isDel: 1 }), + ], + }; + } + return { + platform, + platformName: 'Shopee', + list: [{ id: '9', name: 'sp-store', platform: 'shopee', isDel: 0, isExpire: 0 }], + }; + }; + return { service }; + } + + it('合并各平台店铺并归一化为统一结构', async () => { + const { service } = createShopService(); + const result = await service.listShops({ pageIndex: 1, pageSize: 20 }); + + assert.strictEqual(result.total, 4); + assert.strictEqual(result.source, 'shop'); + const byId = new Map(result.list.map(item => [ item.external_id, item ])); + assert.deepStrictEqual( + (({ name, platform, platform_name, status, status_label }) => ({ name, platform, platform_name, status, status_label }))(byId.get('1')), + { name: 'aaa-store', platform: 'shopify', platform_name: 'Shopify', status: 1, status_label: '正常' } + ); + assert.strictEqual(byId.get('2').status, 0); + assert.strictEqual(byId.get('2').status_label, '授权过期'); + assert.strictEqual(byId.get('3').status_label, '已删除'); + assert.strictEqual(byId.get('9').platform_name, 'Shopee'); + assert.strictEqual(byId.get('1').auth_time, '2026-11-04 08:00:00'); + assert.strictEqual(byId.get('1').remark, 'aaa-store.myshopify.com'); + }); + + it('支持关键词 / 状态 / 平台过滤与本地分页', async () => { + const { service } = createShopService(); + + const abnormal = await service.listShops({ status: '0', pageSize: 20 }); + assert.deepStrictEqual(abnormal.list.map(item => item.external_id).sort(), [ '2', '3' ]); + + const keyword = await service.listShops({ keyword: 'sp-store', pageSize: 20 }); + assert.deepStrictEqual(keyword.list.map(item => item.external_id), [ '9' ]); + + const onlyShopify = await service.listShops({ platformTypes: 'shopify', pageSize: 20 }); + assert.strictEqual(onlyShopify.total, 3); + + const page2 = await service.listShops({ pageIndex: 2, pageSize: 3 }); + assert.strictEqual(page2.total, 4); + assert.strictEqual(page2.list.length, 1); + }); + + it('先取已授权平台再逐平台拉取;平台返回失败时报可读错误', async () => { + const { service } = createService({ account: { cookie: 'JSESSIONID=ok' } }); + const calls = []; + service.request = async url => { + calls.push(url); + if (url.endsWith('/api/shop/list/all.json')) { + return { + status: 200, + json: { code: 0, msg: 'Successful', data: { authOfPlatform: { authorizePlatform: [ 'shopify' ] } } }, + text: '', + }; + } + return { + status: 200, + json: { code: 0, data: { platformZhName: 'Shopify', list: [ shopifyShop(1, 'only-one') ] } }, + text: '', + }; + }; + + const result = await service.listShops({ pageSize: 20 }); + assert.strictEqual(result.total, 1); + assert.deepStrictEqual(calls.map(url => url.replace('https://www.dianxiaomi.com', '')), [ + '/api/shop/list/all.json', + '/api/shop/list/shopify.json', + ]); + + service.request = async () => ({ status: 200, json: { code: 1, msg: '登录失效' }, text: '' }); + await assert.rejects(service.requestJson('/api/shop/list/all.json'), /店小秘接口失败:登录失效/); + }); + + it('未登录时直接提示先登录', async () => { + const { service } = createService({ account: { cookie: '' } }); + await assert.rejects(service.listShops({}), /未登录/); + }); +}); diff --git a/店小秘接入.md b/店小秘接入.md index 181485e..5d3ec49 100644 --- a/店小秘接入.md +++ b/店小秘接入.md @@ -58,14 +58,58 @@ --- -## 3. 待接入 +## 3. 店铺列表 -`dxm.js` 目前只实现 `getLoginCaptcha / login / checkSession / listShopSources`, +一个平台一个接口,请求与响应结构一致(实测 2026-11-23): + +``` +GET /api/shop/list/all.json # 仅用来拿「已授权平台」清单 +GET /api/shop/list/.json # 如 shopify / shopee / amazon +``` + +```jsonc +{ + "code": 0, "msg": "Successful", + "data": { + "platform": "shopify", + "platformZhName": "Shopify", + "shopCount": 10, // 平台侧统计值,与 list 长度不等,不要当分页总数用 + "authOfPlatform": { "authorizePlatform": ["shopify"], "unauthorizePlatform": [ ... ] }, + "list": [{ + "id": "9139394", // 店铺ID(字符串) + "name": "c1eqfe-0a", // 店铺名 + "sellerLoginId": "c1eqfe-0a.myshopify.com", + "platform": "shopify", + "authTime": 1787039321000, // 授权时间(毫秒) + "updateTime": 1795433768000, + "isDel": 0, "isExpire": 0, "isNewExpire": 0, + "accessToken": "shpat_...", // 平台侧凭据,仅原样留痕,不要外传 + "uniqueKey": "...", "marketplaceIds": "..." + }] + } +} +``` + +OMS 实现(`dxm.js#listShops`): + +1. `GET /api/shop/list/all.json` 取 `authOfPlatform.authorizePlatform`,拿到账号真正授权的平台; +2. 逐平台 `GET /api/shop/list/.json` 合并店铺; +3. 归一化为统一店铺结构(`external_id` = 店铺ID、`name`、`platform` 原始标识、 + `platform_code` 走 `platformCode.resolvePlatform`、`platform_name` 用平台给的中文名、 + `auth_time` 取 `authTime`、`status` 由 `isDel/isExpire` 决定); +4. 关键词 / 状态 / 平台过滤与分页都在本地做(单平台接口不分页,店铺量不大)。 + +> 注意:`shopCount` 不是该平台店铺数(实测 3 家店铺时它返回 10),总数只用 `list.length`。 + +--- + +## 4. 待接入 + +`dxm.js` 目前实现 `getLoginCaptcha / login / checkSession / listShopSources / listShops`, 其余方法继承基类会明确报「未实现」。后续按以下顺序补: -1. 店铺列表(授权店铺)→ `listShops` -2. 店铺商品快照 → `listProducts` -3. 订单列表(含明細)→ `listOrders` -4. 取号 / 打单 / 发货回传 → `fetchWaybillNo` / `print` +1. 店铺商品快照 → `listProducts` +2. 订单列表(含明细)→ `listOrders` +3. 取号 / 打单 / 发货回传 → `fetchWaybillNo` / `print` 每补一个接口,先抓真实报文确认字段口径,再补 `backend/test/app/lib/printPlatformDxm.test.js` 用例。