店小秘接入:拉取店铺商品

- 新增 listProducts:按 /api/<platform>Product/pageList.json 分页拉取,一个规格展开一行
- 字段口径:平台商品ID/规格ID/规格编码、规格名、售价、库存、上下架状态
- 单测覆盖分页、规格展开、未拉全标记、缺少店铺标识报错;补接入文档

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
liufumingren 2026-11-23 23:56:56 +08:00
parent e584adaf9a
commit a586e3f18b
3 changed files with 293 additions and 9 deletions

View File

@ -41,6 +41,13 @@ const SHOP_LIST_PATH = '/api/shop/list';
/** 店铺列表页路径(accept/referer 用) */
const SHOP_LIST_PAGE_PATH = '/web/shop/shopList';
/** 商品列表:一个平台一个接口(/api/<platform>Product/pageList.json) */
const PRODUCT_LIST_PAGE_PATH = '/web/shopifyProduct/productList';
/** 商品分页拉取:每页条数 / 最多页数 */
const PRODUCT_PAGE_SIZE = 100;
const PRODUCT_MAX_PAGES = 100;
const REQUEST_TIMEOUT_MS = 30000;
const USER_AGENT =
@ -106,6 +113,16 @@ function isLoginPage(finalUrl, html) {
return /id=["']loginForm["']/.test(String(html || ''));
}
/**
* 数字转换:非法/空值按 0,返回值保留原精度
* @param {*} value 原值
* @return {number} 数字
*/
function toNumber(value) {
const num = Number(value);
return Number.isFinite(num) ? num : 0;
}
/**
* 时间戳(毫秒)→ `YYYY-MM-DD HH:mm:ss`(北京时间),空值返回空串
* @param {*} value 毫秒时间戳
@ -171,19 +188,20 @@ class DxmService extends PrintPlatformService {
/**
* 调用平台 JSON 接口(带登录会话)
* @param {string} path 接口路径(以 / 开头)
* @param {string} path 接口路径(以 / 开头,可带查询串)
* @param {Object} [options] 参数
* @param {boolean} [options.auth] 是否要求已登录,默认 true
* @param {string} [options.referer] Referer 页面路径(默认店铺列表页)
* @return {Promise<Object>} 平台 data 字段
*/
async requestJson(path, { auth = true } = {}) {
async requestJson(path, { auth = true, referer = SHOP_LIST_PAGE_PATH } = {}) {
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}`,
referer: `${this.siteUrl}${referer}`,
cookie: this.cookie,
},
});
@ -280,6 +298,132 @@ class DxmService extends PrintPlatformService {
};
}
/**
* 拉取店铺商品(全量快照),一个 SKU 一行
*
* 店小秘按平台分接口:`/api/<platform>Product/pageList.json`(实测 shopify),
* 参数与页面一致,`shopId` 为平台店铺ID,分页由 `data.page.totalPage` 决定。
* @param {Object} shop OMS 店铺记录(external_data 为平台店铺原始结构)
* @return {Promise<{total: number, verified: boolean, hosts: Array, list: Array}>} 商品快照
*/
async listProducts(shop) {
const data = (shop && shop.external_data) || {};
const shopId = String(data.id || data.Id || '').trim();
const platform = String(data.platform || '').trim();
if (!shopId) throw new Error('店铺缺少平台店铺ID,无法拉取平台商品');
if (!platform) throw new Error('店铺缺少平台标识,无法拉取平台商品');
const rows = [];
let fetched = 0;
let totalPage = 1;
let totalSize = 0;
let pages = 0;
for (let pageNo = 1; pageNo <= Math.min(totalPage, PRODUCT_MAX_PAGES); pageNo += 1) {
const page = await this.fetchProductPage(platform, shopId, pageNo);
pages += 1;
totalPage = page.totalPage || pageNo;
totalSize = page.totalSize || totalSize;
fetched += page.list.length;
for (const product of page.list) rows.push(...this.normalizeProduct(product));
if (!page.list.length) break;
}
// 平台按商品返回总数,本地按 SKU 展开,所以「拉全」用商品级计数判断
const verified = totalSize === 0 ? rows.length === 0 : fetched >= totalSize;
return {
total: rows.length,
verified,
hosts: [{
host: new URL(this.siteUrl).host,
total: totalSize,
unique: rows.length,
pages,
verified,
areas: [],
}],
list: rows,
};
}
/**
* 拉取一页商品
* @param {string} platform 平台标识(如 shopify)
* @param {string} shopId 平台店铺ID
* @param {number} pageNo 页码(1 基)
* @return {Promise<{list: Array, pageNo: number, pageSize: number, totalPage: number, totalSize: number}>} 分页结果
*/
async fetchProductPage(platform, shopId, pageNo = 1) {
const query = new URLSearchParams({
sortName: '2',
pageNo: String(pageNo),
pageSize: String(PRODUCT_PAGE_SIZE),
total: '',
sortValue: '0',
searchType: '1',
searchValue: '',
productSearchType: '0',
sellType: '0',
listingStatus: 'Active',
shopId,
dxmState: 'online',
dxmOfflineState: '',
fullCid: '',
});
const data = await this.requestJson(`/api/${platform}Product/pageList.json?${query.toString()}`, {
referer: PRODUCT_LIST_PAGE_PATH,
});
const page = data.page || {};
return {
list: Array.isArray(page.list) ? page.list : [],
pageNo: Number(page.pageNo) || pageNo,
pageSize: Number(page.pageSize) || PRODUCT_PAGE_SIZE,
totalPage: Number(page.totalPage) || 1,
totalSize: Number(page.totalSize) || 0,
};
}
/**
* 店小秘商品(含规格)→ 店铺商品行(一个规格一行)
*
* `outer_item_id` 用平台商品ID(shopifyProductId),`outer_sku_id` 用平台规格ID(shopifyVariantId),
* `outer_sku_code` 用规格 SKU 编码(可为空,订单明细匹配时按它兜底)。
* @param {Object} product 平台商品原始结构
* @return {Array<Object>} 店铺商品行
*/
normalizeProduct(product) {
const data = product || {};
const variants = Array.isArray(data.variants) && data.variants.length ? data.variants : [ null ];
const productRaw = { ...data };
delete productRaw.variants;
const platformType = resolvePlatform(data.platform).code;
const title = String(data.title || '').slice(0, 255);
const image = String(data.mainImage || '').slice(0, 255);
const status = String(data.dxmState || '') === 'offline' ? 0 : 1;
const externalShopId = String(data.shopId || '').slice(0, 64);
return variants.map(variant => {
const item = variant || {};
const options = [ item.option1, item.option2, item.option3 ].map(value => String(value || '').trim()).filter(Boolean);
const skuCode = String(item.sku || '').trim();
return {
outer_item_id: String(data.shopifyProductId || data.id || ''),
outer_sku_id: String(item.shopifyVariantId || item.id || ''),
outer_sku_code: skuCode ? skuCode.slice(0, 64) : null,
title,
outer_code: String(item.barcode || skuCode || '').slice(0, 100),
spec: options.join(' / ').slice(0, 255),
image: String(item.imageUrl || image).slice(0, 255),
price: toNumber(item.price),
stock: Math.max(0, Math.trunc(toNumber(item.inventoryQuantity))),
status,
platform_type: platformType,
external_shop_id: externalShopId,
raw: { product: productRaw, variant: variant || null },
};
});
}
/**
* 平台过滤参数归一化(支持逗号分隔字符串 / 数组)
* @param {string|string[]} value 过滤值

View File

@ -188,8 +188,98 @@ describe('printPlatform/dxm checkSession', () => {
});
});
describe('printPlatform/dxm listProducts', () => {
const shop = { external_data: { id: '9139394', platform: 'shopify', name: 'c1eqfe-0a' } };
const product = {
id: '184807708987825769',
shopId: '9139394',
shopifyProductId: '9116758048958',
title: 'Dried Dragon Fruit',
mainImage: 'https://cdn.example.com/main.png',
dxmState: 'online',
variants: [
{
id: '184807708701793891',
shopifyVariantId: '49533728391358',
sku: 'SKU-1',
option1: 'Buy 1 Get 1 FREE',
option2: '',
price: 49.9,
inventoryQuantity: 9999,
barcode: null,
imageUrl: null,
},
],
};
function createProductService(pages) {
const { service } = createService({ account: { cookie: 'JSESSIONID=ok' } });
const calls = [];
service.requestJson = async (path, options) => {
calls.push({ path, options });
const pageNo = Number((path.match(/pageNo=(\d+)/) || [])[1] || 1);
return { page: pages[pageNo - 1] || { list: [], pageNo, totalPage: pages.length, totalSize: 0 } };
};
return { service, calls };
}
it('分页拉取商品并按规格展开为店铺商品行', async () => {
const { service, calls } = createProductService([
{ list: [ product ], pageNo: 1, totalPage: 2, totalSize: 2 },
{ list: [{ ...product, id: '2', shopifyProductId: '9116758048959', dxmState: 'offline', variants: [] }], pageNo: 2, totalPage: 2, totalSize: 2 },
]);
const snapshot = await service.listProducts(shop);
assert.strictEqual(calls.length, 2);
assert.match(calls[0].path, /^\/api\/shopifyProduct\/pageList\.json\?/);
assert.match(calls[0].path, /shopId=9139394/);
assert.strictEqual(calls[0].options.referer, '/web/shopifyProduct/productList');
assert.strictEqual(snapshot.verified, true);
assert.strictEqual(snapshot.total, 2);
assert.strictEqual(snapshot.hosts[0].total, 2);
const [ row, noVariant ] = snapshot.list;
assert.deepStrictEqual(
(({ outer_item_id, outer_sku_id, outer_sku_code, spec, price, stock, status, platform_type, external_shop_id }) => ({
outer_item_id, outer_sku_id, outer_sku_code, spec, price, stock, status, platform_type, external_shop_id,
}))(row),
{
outer_item_id: '9116758048958',
outer_sku_id: '49533728391358',
outer_sku_code: 'SKU-1',
spec: 'Buy 1 Get 1 FREE',
price: 49.9,
stock: 9999,
status: 1,
platform_type: 'OTHER',
external_shop_id: '9139394',
}
);
// 没有规格的商品也保留一行,规格ID退化为商品内部ID
assert.strictEqual(noVariant.outer_item_id, '9116758048959');
assert.strictEqual(noVariant.status, 0);
});
it('平台商品数与实际拉取不一致时标记未完整', async () => {
const { service } = createProductService([
{ list: [ product ], pageNo: 1, totalPage: 1, totalSize: 3 },
]);
const snapshot = await service.listProducts(shop);
assert.strictEqual(snapshot.verified, false);
});
it('店铺缺少平台店铺ID / 平台标识时直接报错', async () => {
const { service } = createService({ account: { cookie: 'JSESSIONID=ok' } });
await assert.rejects(service.listProducts({ external_data: { platform: 'shopify' } }), /缺少平台店铺ID/);
await assert.rejects(service.listProducts({ external_data: { id: '1' } }), /缺少平台标识/);
});
});
describe('printPlatform/dxm listShops', () => {
const shopifyShop = (id, name, extra = {}) => ({
const shopifyShop = (id, name, extra = { }) => ({
id: String(id),
name,
platform: 'shopify',

View File

@ -103,13 +103,63 @@ OMS 实现(`dxm.js#listShops`):
---
## 4. 待接入
## 4. 店铺商品
`dxm.js` 目前实现 `getLoginCaptcha / login / checkSession / listShopSources / listShops`,
按平台分接口,参数与页面「商品列表」一致(实测 shopify,2026-11-23):
```
GET /api/<platform>Product/pageList.json
?sortName=2&pageNo=1&pageSize=100&total=&sortValue=0&searchType=1&searchValue=
&productSearchType=0&sellType=0&listingStatus=Active&shopId=<店铺ID>
&dxmState=online&dxmOfflineState=&fullCid=
```
```jsonc
{
"code": 0, "msg": "Successful",
"data": {
"page": {
"list": [{
"id": "184807708987825769", // 店小秘内部商品ID
"shopifyProductId": "9116758048958", // 平台商品ID(OMS 的 outer_item_id)
"shopId": "9139394",
"title": "…", "mainImage": "https://cdn.shopify.com/…",
"dxmState": "online", // 上下架(online / offline)
"variants": [{
"id": "184807708701793891",
"shopifyVariantId": "49533728391358", // 平台规格ID(OMS 的 outer_sku_id)
"sku": null, // 规格编码(OMS 的 outer_sku_code)
"option1": "Buy 1 Get 1 FREE", "option2": "", "option3": "",
"price": 49.9, "compareAtPrice": 129.9,
"inventoryQuantity": 9999,
"barcode": null, "imageUrl": null
}]
}],
"pageNo": 1, "pageSize": 100, "totalPage": 1, "totalSize": 78
}
}
}
```
OMS 实现(`dxm.js#listProducts`):
- 按 `totalPage` 逐页拉(每页 100),一个**规格**展开成一行(78 个商品 → 179 行);
- 字段口径:`outer_item_id` = `shopifyProductId`、`outer_sku_id` = `shopifyVariantId`、
`outer_sku_code` = 规格 `sku`、`outer_code` = `barcode` || `sku`、`spec` = `option1/2/3` 拼接、
`price` = 规格 `price`、`stock` = `inventoryQuantity`、`status` 由 `dxmState` 决定;
- `verified` 用商品数与平台 `totalSize` 比较(本地行数是 SKU 数,不能直接比)。
> 注意:接口路径里的平台名是 `<platform>Product`(如 `shopifyProduct`、`shopeeProduct`),
> 其它平台是否同名未验证,接入新平台时先抓包确认。
---
## 5. 待接入
`dxm.js` 目前实现 `getLoginCaptcha / login / checkSession / listShopSources / listShops / listProducts`,
其余方法继承基类会明确报「未实现」。后续按以下顺序补:
1. 店铺商品快照 → `listProducts`
2. 订单列表(含明细)→ `listOrders`
3. 取号 / 打单 / 发货回传 → `fetchWaybillNo` / `print`
1. 订单列表(含明细)→ `listOrders`
2. 取号 / 打单 / 发货回传 → `fetchWaybillNo` / `print`
每补一个接口,先抓真实报文确认字段口径,再补 `backend/test/app/lib/printPlatformDxm.test.js` 用例。