问题:之前用 /api/pddkjInventory/printExpressNote.json?id=<包裹ID> 取面单, 那是「拼多多跨境备货单」的标签接口,传订单包裹ID 会返回一张解压后文字为 「发货单不存在」的 PDF(同样以 %PDF 开头,只看前缀查不出来)。 修正:改用服务端打印页 printMb.htm GET /printMb.htm?packageIds=<包裹ID>&authId=<店铺授权ID>&isCos=1 → 302 https://print.dianxiaomi.com/<日期>/<uuid>.pdf → 200 application/pdf - 新增 requestPdf(手动处理跳转,跨域那一跳不带 OMS 账号 cookie) - fetchPrintPdf 改走 printMb.htm;仍保留 checkPrint 取面单格式/校验 - 单测改为验证两跳链路(打印页带 cookie、跨域 PDF 不带 cookie),补 302 缺 location 的用例 - 文档 6/6.1 更新下载方式,并记下 printExpressNote 的坑 实测(包裹 184804424061188407 / 运单 3CAB6112200001): 面单 base64 150,136 字符,解码文字含收件人 Daniel Puccio / 92223 / +19515057679; 取号记录 pdf_base64 落库 150,136、result_data 仅 417 字节。 本地已清掉两条用错误接口生成的取号记录与幂等记录。 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
700 lines
28 KiB
JavaScript
700 lines
28 KiB
JavaScript
'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,
|
||
agentProviderName: '跨源速递-元驿MetaHub-普货',
|
||
agentTrackNum: '3CAB6112100007',
|
||
authId: '182586000431422845',
|
||
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, 'SHOPIFY');
|
||
// 物流商(agentProviderName)→ 快递公司字典编码,渠道名原样留痕
|
||
assert.strictEqual(order.logistics_code, 'KJKYSD');
|
||
assert.strictEqual(order.logistics_name, '跨源速递');
|
||
assert.strictEqual(order.logistics_provider_name, '跨源速递-元驿MetaHub-普货');
|
||
// 平台运单号与店铺授权ID(取打印数据用)
|
||
assert.strictEqual(order.waybill_code, '3CAB6112100007');
|
||
assert.strictEqual(order.platform_auth_id, '182586000431422845');
|
||
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('没有物流商(agentProviderName)时不落快递公司', async () => {
|
||
const { service } = createOrderService([
|
||
{ list: [ packageRow('1', { agentProviderName: null }) ], totalPage: 1, totalSize: 1 },
|
||
]);
|
||
const result = await service.listOrders(shop);
|
||
const order = result.list[0];
|
||
assert.strictEqual(order.logistics_code, null);
|
||
assert.strictEqual(order.logistics_name, null);
|
||
assert.strictEqual(order.logistics_provider_name, null);
|
||
});
|
||
|
||
it('未在映射表内的物流商按默认快递公司(跨源速递 KJKYSD)落库', async () => {
|
||
const { service } = createOrderService([
|
||
{ list: [ packageRow('1', { agentProviderName: 'YYEXPRESS-普货' }) ], totalPage: 1, totalSize: 1 },
|
||
]);
|
||
const result = await service.listOrders(shop);
|
||
assert.strictEqual(result.list[0].logistics_code, 'KJKYSD');
|
||
assert.strictEqual(result.list[0].logistics_provider_name, 'YYEXPRESS-普货');
|
||
});
|
||
|
||
it('店铺缺少平台店铺ID时报错', async () => {
|
||
const { service } = createService({ account: { cookie: 'JSESSIONID=ok' } });
|
||
await assert.rejects(service.listOrders({ external_data: {} }), /缺少平台店铺ID/);
|
||
});
|
||
});
|
||
|
||
describe('printPlatform/dxm fetchWaybillNo', () => {
|
||
it('直接读取拉单存下的平台运单号(agentTrackNum),并带回面单 PDF(base64)', async () => {
|
||
const { service } = createService({ account: { cookie: 'JSESSIONID=ok' } });
|
||
const calls = [];
|
||
service.fetchPrintPdf = async params => {
|
||
calls.push(params);
|
||
return { mime: 'application/pdf', base64: 'JVBERi0xLjQ=', meta: { fileName: 'singleCache/a.pdf', printFormat: '标签纸' } };
|
||
};
|
||
|
||
const result = await service.fetchWaybillNo({
|
||
order_no: 'dxm-184804424059302467',
|
||
extend_props: { platform_waybill_code: '3CAB6112100007', platform_auth_id: '182586000431422845' },
|
||
});
|
||
|
||
assert.deepStrictEqual(calls, [{ authId: '182586000431422845', packageId: '184804424059302467' }]);
|
||
assert.strictEqual(result.waybill_code, '3CAB6112100007');
|
||
assert.deepStrictEqual(result.waybill_codes, [ '3CAB6112100007' ]);
|
||
// 面单 PDF 用 pdf_base64 返回(纯 base64,不带 data: 前缀)
|
||
assert.strictEqual(result.pdf_base64, 'JVBERi0xLjQ=');
|
||
assert.strictEqual(result.raw.print.file_name, 'singleCache/a.pdf');
|
||
assert.strictEqual(result.raw.print_error, undefined);
|
||
});
|
||
|
||
it('面单 PDF 拉取失败不影响运单号返回', async () => {
|
||
const { service } = createService({ account: { cookie: 'JSESSIONID=ok' } });
|
||
service.fetchPrintPdf = async () => {
|
||
throw new Error('店小秘取面单文件失败:HTTP 500');
|
||
};
|
||
const result = await service.fetchWaybillNo({
|
||
order_no: 'dxm-1',
|
||
extend_props: { platform_waybill_code: 'YT123456' },
|
||
});
|
||
assert.strictEqual(result.waybill_code, 'YT123456');
|
||
assert.strictEqual(result.pdf_base64, '');
|
||
assert.match(result.raw.print_error, /HTTP 500/);
|
||
});
|
||
|
||
it('订单上没有平台运单号时提示先出号再拉单', async () => {
|
||
const { service } = createService({ account: { cookie: 'JSESSIONID=ok' } });
|
||
await assert.rejects(
|
||
service.fetchWaybillNo({ order_no: 'dxm-1', extend_props: {} }),
|
||
/还没有平台运单号/
|
||
);
|
||
});
|
||
});
|
||
|
||
describe('printPlatform/dxm fetchPrintPdf', () => {
|
||
it('先 checkPrint 校验,再走 printMb.htm 拿 PDF(302 后跟到 print 域名)', async () => {
|
||
const { service } = createService({ account: { cookie: 'JSESSIONID=ok' } });
|
||
const forms = [];
|
||
service.requestForm = async (path, form) => {
|
||
forms.push({ path, authId: form.get('authId'), packageIds: form.get('packageIds') });
|
||
return { fileName: 'singleCache/x.pdf', printFormat: '标签纸(10*10厘米)+标签(PDF)' };
|
||
};
|
||
const requests = [];
|
||
service.requestPdf = async (url, options) => {
|
||
requests.push({ url, cookie: (options && options.headers && options.headers.cookie) || '' });
|
||
if (requests.length === 1) {
|
||
return { status: 302, buffer: Buffer.alloc(0), contentType: '', location: 'https://print.dianxiaomi.com/2026-11-24/abc.pdf' };
|
||
}
|
||
return { status: 200, buffer: Buffer.from('%PDF-1.4 test'), contentType: 'application/pdf', location: '' };
|
||
};
|
||
|
||
const result = await service.fetchPrintPdf({ authId: '182586000431422845', packageId: '184804424061188407' });
|
||
|
||
assert.deepStrictEqual(forms, [{ path: '/api/checkPrint.json', authId: '182586000431422845', packageIds: '184804424061188407' }]);
|
||
// 第一跳打打印页(带账号 cookie),第二跳取跨域 PDF(不带账号 cookie)
|
||
assert.match(requests[0].url, /\/printMb\.htm\?packageIds=184804424061188407&isCos=1&authId=182586000431422845$/);
|
||
assert.match(requests[0].cookie, /JSESSIONID=ok/);
|
||
assert.strictEqual(requests[1].url, 'https://print.dianxiaomi.com/2026-11-24/abc.pdf');
|
||
assert.strictEqual(requests[1].cookie, '');
|
||
assert.strictEqual(result.mime, 'application/pdf');
|
||
assert.strictEqual(Buffer.from(result.base64, 'base64').toString('utf8'), '%PDF-1.4 test');
|
||
assert.strictEqual(result.meta.printFormat, '标签纸(10*10厘米)+标签(PDF)');
|
||
});
|
||
|
||
it('没有 authId 时跳过 checkPrint,直接打打印页', async () => {
|
||
const { service } = createService({ account: { cookie: 'JSESSIONID=ok' } });
|
||
service.requestForm = async () => {
|
||
throw new Error('不该调用 checkPrint');
|
||
};
|
||
service.requestPdf = async () => ({ status: 200, buffer: Buffer.from('%PDF'), contentType: 'application/pdf', location: '' });
|
||
const result = await service.fetchPrintPdf({ packageId: '123' });
|
||
assert.deepStrictEqual(result.meta, {});
|
||
});
|
||
|
||
it('返回不是 PDF 时报可读错误', async () => {
|
||
const { service } = createService({ account: { cookie: 'JSESSIONID=ok' } });
|
||
service.requestPdf = async () => ({ status: 200, buffer: Buffer.from('<html>err</html>'), contentType: 'text/html', location: '' });
|
||
await assert.rejects(service.fetchPrintPdf({ packageId: '123' }), /返回的不是 PDF/);
|
||
});
|
||
|
||
it('跳转目标缺失时按 HTTP 状态报错', async () => {
|
||
const { service } = createService({ account: { cookie: 'JSESSIONID=ok' } });
|
||
service.requestPdf = async () => ({ status: 302, buffer: Buffer.alloc(0), contentType: '', location: '' });
|
||
await assert.rejects(service.fetchPrintPdf({ packageId: '123' }), /HTTP 302/);
|
||
});
|
||
});
|
||
|
||
describe('printPlatform/dxm 打印状态', () => {
|
||
it('markPrinted 用 packageId 调 setPrint', async () => {
|
||
const { service } = createService({ account: { cookie: 'JSESSIONID=ok' } });
|
||
const calls = [];
|
||
service.requestForm = async (path, form) => {
|
||
calls.push({ path, packageId: form.get('packageId') });
|
||
return {};
|
||
};
|
||
await service.markPrinted('184804423849770579');
|
||
assert.deepStrictEqual(calls, [{ path: '/api/package/setPrint.json', packageId: '184804423849770579' }]);
|
||
});
|
||
|
||
it('print 取 PDF 并回写已打印面单', async () => {
|
||
const { service } = createService({ account: { cookie: 'JSESSIONID=ok' } });
|
||
service.fetchPrintPdf = async () => ({ mime: 'application/pdf', base64: 'JVBERi0xLjQK', meta: { fileName: 'a.pdf' } });
|
||
const marked = [];
|
||
service.markPrinted = async id => {
|
||
marked.push(id);
|
||
};
|
||
|
||
const result = await service.print({
|
||
order_no: 'dxm-184804423849770579',
|
||
parent_order_no: '184804423849770579',
|
||
extend_props: { platform_auth_id: '182586000431423103' },
|
||
});
|
||
|
||
assert.strictEqual(result.pdf_base64, 'JVBERi0xLjQK');
|
||
assert.strictEqual(result.print_marked, true);
|
||
assert.deepStrictEqual(marked, [ '184804423849770579' ]);
|
||
});
|
||
|
||
it('标记打印状态失败时仍然返回 PDF', async () => {
|
||
const { service } = createService({ account: { cookie: 'JSESSIONID=ok' } });
|
||
service.fetchPrintPdf = async () => ({ mime: 'application/pdf', base64: 'JVBERi0xLjQK', meta: {} });
|
||
service.markPrinted = async () => {
|
||
throw new Error('该订单不存在!');
|
||
};
|
||
|
||
const result = await service.print({ parent_order_no: '123', extend_props: {} });
|
||
assert.strictEqual(result.print_marked, false);
|
||
assert.match(result.print_error, /该订单不存在/);
|
||
assert.strictEqual(result.pdf_base64, 'JVBERi0xLjQK');
|
||
});
|
||
});
|
||
|
||
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({}), /未登录/);
|
||
});
|
||
});
|