oms/backend/test/app/lib/printPlatformDxm.test.js
liufumingren aa01d292c2 店小秘订单收件人:补国家/邮编/邮箱
- 平台地址里的 country/zip/email 原样带进统一收件人结构
- 订单落待审核时写入 country_code / zip_code / email(推 WMS receiverInfo 会用)
- 省市区仍按平台原值透传(州/市原样,跨境单 district 常为空)

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-24 00:31:41 +08:00

525 lines
20 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 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 listOrders', () => {
const shop = { name: 'c1eqfe-0a', external_data: { id: '9139394', platform: 'shopify', name: 'c1eqfe-0a' } };
const packageRow = (id, extra = {}) => ({
id,
orderId: `9139394-${id.slice(-4)}`,
shopId: '9139394',
platform: 'shopify',
orderState: 'allocated_has',
orderStatePlatform: 'paid_fulfilled',
orderAmount: 54.9,
shipAmount: 6.9,
orderCreateTime: Date.UTC(2026, 10, 4, 0, 0, 0),
updateTime: Date.UTC(2026, 10, 5, 0, 0, 0),
dxmPackageAddr: {
contactPerson: 'Dave Fohne',
phoneNumber: '+16183430668',
countryCh: '美国',
province: 'Illinois',
city: 'Collinsville',
district: '',
detailAddress: '620 E Church St',
hasAsterisk: false,
},
productList: [
{
id: `item-${id}`,
productId: '49366194192574',
productSubSku: '49366194192574',
productName: 'Alaskan Red King Crab Legs',
oriProductImg: 'https://cdn.example.com/p.png',
attrList: [{ pName: 'Variants', pValue: 'Buy 1 Get 1 Free' }],
quantity: 1,
price: 54.9,
cancelFlag: false,
},
{
id: `gift-${id}`,
productId: '999',
productName: 'Canceled gift',
quantity: 1,
price: 1,
cancelFlag: true,
},
],
...extra,
});
function createOrderService(pages) {
const { service } = createService({ account: { cookie: 'JSESSIONID=ok' } });
const calls = [];
service.requestForm = async (path, form, options) => {
calls.push({ path, form, options });
const pageNo = Number(form.get('pageNo'));
return { page: pages[pageNo - 1] || { list: [], totalPage: pages.length, totalSize: 0 } };
};
return { service, calls };
}
it('只拉「有货」(allocated_has)队列并归一化订单/明细', async () => {
const { service, calls } = createOrderService([
{ list: [ packageRow('184804423947346433') ], totalPage: 1, totalSize: 1 },
]);
const result = await service.listOrders(shop);
assert.strictEqual(calls.length, 1);
assert.strictEqual(calls[0].path, '/api/package/list.json');
assert.strictEqual(calls[0].form.get('state'), 'allocated_has');
assert.strictEqual(calls[0].form.get('shopId'), '9139394');
assert.strictEqual(result.total, 1);
assert.strictEqual(result.skipped, 0);
assert.deepStrictEqual(result.finished, []);
assert.strictEqual(result.hosts[0].verified, true);
const order = result.list[0];
assert.strictEqual(order.external_order_id, '184804423947346433');
assert.strictEqual(order.platform_order_no, '9139394-6433');
assert.strictEqual(order.external_shop_id, '9139394');
assert.strictEqual(order.external_shop_name, 'c1eqfe-0a');
assert.strictEqual(order.platform_status, 'allocated_has');
assert.strictEqual(order.platform_code, 'OTHER');
assert.strictEqual(order.total_amount, 61.8);
assert.strictEqual(order.pay_amount, 61.8);
assert.deepStrictEqual(order.receiver, {
name: 'Dave Fohne',
phone: '+16183430668',
address: '620 E Church St',
full_address: '美国, Illinois, Collinsville, 620 E Church St',
country_code: '',
zip_code: '',
email: '',
province: 'Illinois',
city: 'Collinsville',
area: '',
town: '',
masked: false,
});
// 取消的明细不下发
assert.strictEqual(order.items.length, 1);
assert.deepStrictEqual(
(({ external_item_id, outer_item_id, outer_sku_id, sku_code, name, spec, price, quantity, total_amount }) => ({
external_item_id, outer_item_id, outer_sku_id, sku_code, name, spec, price, quantity, total_amount,
}))(order.items[0]),
{
external_item_id: 'item-184804423947346433',
// 店小秘明细只给规格ID,商品ID留空由店铺商品匹配回填
outer_item_id: '',
outer_sku_id: '49366194192574',
sku_code: null,
name: 'Alaskan Red King Crab Legs',
spec: 'Variants:Buy 1 Get 1 Free',
price: 54.9,
quantity: 1,
total_amount: 54.9,
}
);
assert.strictEqual(order.external_created_at.getTime(), Date.UTC(2026, 10, 4, 0, 0, 0));
});
it('按 totalPage 逐页拉取', async () => {
const { service, calls } = createOrderService([
{ list: [ packageRow('1') ], totalPage: 2, totalSize: 2 },
{ list: [ packageRow('2') ], totalPage: 2, totalSize: 2 },
]);
const result = await service.listOrders(shop);
assert.strictEqual(calls.length, 2);
assert.strictEqual(result.total, 2);
});
it('店铺缺少平台店铺ID时报错', async () => {
const { service } = createService({ account: { cookie: 'JSESSIONID=ok' } });
await assert.rejects(service.listOrders({ external_data: {} }), /缺少平台店铺ID/);
});
});
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({}), /未登录/);
});
});