oms/backend/test/app/lib/printPlatformDxm.test.js
liufumingren e584adaf9a 店小秘接入:拉取店铺列表
- 新增 listShops:先取已授权平台(/api/shop/list/all.json),再逐平台拉店铺
- 店铺按统一结构归一化(店铺ID/名称/平台/授权时间/状态),支持关键词、状态、平台过滤与本地分页
- 补单测(合并、过滤、分页、未登录、平台报错)与接入文档

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-23 23:47:39 +08:00

298 lines
12 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
const { assert } = require('egg-mock/bootstrap');
const crypto = require('crypto'); // eslint-disable-line no-restricted-modules
const DxmService = require('../../../app/lib/printPlatform/dxm');
/**
* 解出 encryptLoginField 的明文,验证加密格式与服务端约定一致
* @param {string} value 加密串
* @return {string} 明文
*/
function decryptLoginField(value) {
const body = String(value);
assert.strictEqual(body[0], '0');
const iv = Buffer.from(body.slice(5, 37), 'hex');
const key = Buffer.from(body.slice(37, 69), 'hex');
const data = Buffer.from(body.slice(69), 'hex');
const decipher = crypto.createDecipheriv('aes-128-cbc', key, iv);
return Buffer.concat([ decipher.update(data), decipher.final() ]).toString('utf8');
}
function createService(overrides = {}) {
const platform = { code: 'dxm', name: '店小秘', url: '', ...overrides.platform };
const account = { id: 1, account: 'user@example.com', password: 'secret', cookie: '' };
const saved = { cookie: '', status: null };
const service = new DxmService({
platform,
account: { ...account, ...overrides.account },
saveCookie: async cookie => {
saved.cookie = cookie;
},
saveLoginStatus: async status => {
saved.status = status;
},
});
return { service, saved };
}
describe('printPlatform/dxm encryptLoginField', () => {
it('格式为 0 + 随机串 + IV + Key + 密文,且可还原明文', () => {
const encrypted = DxmService.encryptLoginField('user@example.com');
assert.match(encrypted, /^0[0-9a-f]{4}[0-9a-f]{32}[0-9a-f]{32}[0-9a-f]+$/);
assert.strictEqual(decryptLoginField(encrypted), 'user@example.com');
});
});
describe('printPlatform/dxm getLoginCaptcha', () => {
it('返回 data URL,并带上验证码绑定会话', async () => {
const { service } = createService();
service.requestBinary = async () => ({
status: 200,
buffer: Buffer.from('jpeg-bytes'),
contentType: 'image/jpeg;charset=UTF-8',
setCookies: [ 'JSESSIONID=abc123; Path=/; HttpOnly', 'dxm_vc=token456; Path=/; HttpOnly' ],
});
const result = await service.getLoginCaptcha();
assert.strictEqual(result.image, `data:image/jpeg;base64,${Buffer.from('jpeg-bytes').toString('base64')}`);
assert.strictEqual(result.session, 'JSESSIONID=abc123; dxm_vc=token456');
});
it('验证码接口失败时抛错', async () => {
const { service } = createService();
service.requestBinary = async () => ({ status: 500, buffer: Buffer.alloc(0), contentType: '', setCookies: [] });
await assert.rejects(service.getLoginCaptcha(), /获取验证码失败/);
});
});
describe('printPlatform/dxm loginByPassword', () => {
it('没有验证码 / 验证码会话时直接提示', async () => {
const { service } = createService();
await assert.rejects(service.login({ session: 'JSESSIONID=abc' }), /需要图形验证码/);
await assert.rejects(service.login({ captcha: '1234' }), /验证码已过期/);
});
it('提交加密账号密码与验证码,成功后保存会话并校验登录态', async () => {
const { service, saved } = createService();
const calls = [];
service.request = async (url, options) => {
calls.push({ url, options });
if (url.endsWith('/user/userLoginNew2.json')) {
const form = new URLSearchParams(options.body);
assert.strictEqual(form.get('dxmVerify'), '1234');
assert.strictEqual(decryptLoginField(form.get('account')), 'user@example.com');
assert.strictEqual(decryptLoginField(form.get('password')), 'secret');
assert.match(options.headers.cookie, /dxm_vc=token456/);
return {
status: 200,
json: { code: 0, url: '/home.htm' },
text: '',
setCookies: [ 'JSESSIONID=logged-in; Path=/' ],
};
}
assert.match(url, /\/home\.htm$/);
assert.match(options.headers.cookie, /JSESSIONID=logged-in/);
return { status: 200, json: null, text: '', setCookies: [] };
};
// 登录后工作台会 302 到 ERP 后台 /web/home,由 followGet 跟随
service.followGet = async (url, cookie) => {
calls.push({ url, cookie });
return {
status: 200,
finalUrl: 'https://www.dianxiaomi.com/web/home',
html: '<title>店小秘--免费的跨境电商ERP</title>',
cookie: `${cookie}; dxm_i=user-1`,
};
};
const result = await service.login({ captcha: '1234', session: 'JSESSIONID=abc; dxm_vc=token456' });
assert.strictEqual(result.reused, false);
assert.strictEqual(result.cookie, 'JSESSIONID=logged-in; dxm_vc=token456; dxm_i=user-1');
assert.strictEqual(saved.cookie, result.cookie);
assert.strictEqual(saved.status, 1);
assert.strictEqual(calls.length, 2);
});
it('登录成功但工作台仍回到登录页时提示校验失败', async () => {
const { service } = createService();
service.request = async () => ({ status: 200, json: { code: 0, url: '/home.htm' }, text: '', setCookies: [] });
service.followGet = async () => ({
status: 200,
finalUrl: 'https://www.dianxiaomi.com/index.htm',
html: '<form id="loginForm">',
cookie: '',
});
await assert.rejects(
service.login({ captcha: '1234', session: 'JSESSIONID=abc; dxm_vc=token456' }),
/登录后校验失败/
);
});
it('平台返回验证码错误时抛出可读原因且不保存会话', async () => {
const { service, saved } = createService();
service.request = async () => ({
status: 200,
json: { code: -1, error: '验证码填写错误' },
text: '',
setCookies: [],
});
await assert.rejects(
service.login({ captcha: '0000', session: 'JSESSIONID=abc; dxm_vc=token456' }),
/店小秘登录失败:验证码填写错误/
);
assert.strictEqual(saved.cookie, '');
});
});
describe('printPlatform/dxm checkSession', () => {
it('工作台 302 到 ERP 后台时视为已登录,并保存新下发的 cookie', async () => {
const { service, saved } = createService({ account: { cookie: 'JSESSIONID=ok' } });
service.followGet = async () => ({
status: 200,
finalUrl: 'https://www.dianxiaomi.com/web/home',
html: '<title>店小秘--免费的跨境电商ERP</title>',
cookie: 'JSESSIONID=ok; dxm_i=user-1',
});
const result = await service.checkSession();
assert.strictEqual(result.loggedIn, true);
assert.strictEqual(saved.status, 1);
assert.strictEqual(saved.cookie, 'JSESSIONID=ok; dxm_i=user-1');
assert.strictEqual(result.url, 'https://www.dianxiaomi.com/web/home');
});
it('最终落到登录页时标记未登录', async () => {
const { service, saved } = createService({ account: { cookie: 'JSESSIONID=expired' } });
service.followGet = async () => ({
status: 200,
finalUrl: 'https://www.dianxiaomi.com/index.htm',
html: '<form id="loginForm">',
cookie: 'JSESSIONID=expired',
});
const result = await service.checkSession();
assert.strictEqual(result.loggedIn, false);
assert.strictEqual(saved.status, 0);
assert.match(result.message, /重定向到登录页/);
});
it('没有 cookie 时直接返回未登录', async () => {
const { service } = createService();
const result = await service.checkSession();
assert.strictEqual(result.loggedIn, false);
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({}), /未登录/);
});
});