Files
core-prestashop/test/presta-api.test.js

320 lines
16 KiB
JavaScript

const { withHookFixtures } = require('./helpers/hook-fixtures');
const test = require('node:test');
const assert = require('node:assert/strict');
const Module = require('node:module');
const Core = withHookFixtures({ fetch: null });
const originalLoad = Module._load;
Module._load = function(request, parent, isMain) {
if (request === '@orbito/api-lib') return { Core, Log: { warn() {} } };
return originalLoad.call(this, request, parent, isMain);
};
const PrestashopApi = require('../src/PrestaApi');
Module._load = originalLoad;
function response(status, body) {
return { status, text: () => typeof body === 'string' ? body : JSON.stringify(body) };
}
test('rejects HTTP errors and retries retryable GET responses', async t => {
const originalFetch = Core.fetch;
t.after(() => { Core.fetch = originalFetch; });
let calls = 0;
Core.fetch = async () => {
calls += 1;
return calls < 3 ? response(503, { error: 'busy' }) : response(200, { orders: [] });
};
const api = new PrestashopApi('https://shop.example', 'secret', true, {
maxGetAttempts: 3, retryBaseMs: 1, timeoutMs: 100,
});
assert.deepEqual(await api.makeRequest('orders', 'GET'), { orders: [] });
assert.equal(calls, 3);
});
test('does not retry mutating requests', async t => {
const originalFetch = Core.fetch;
t.after(() => { Core.fetch = originalFetch; });
let calls = 0;
Core.fetch = async () => { calls += 1; return response(500, { error: 'failed' }); };
const api = new PrestashopApi('https://shop.example', 'secret', true, { retryBaseMs: 1 });
await assert.rejects(() => api.makeRequest('orders/1', 'PATCH', { order: { id: 1 } }), /HTTP 500/);
assert.equal(calls, 1);
});
test('changes an order state by creating an idempotent PrestaShop order history', async t => {
const originalFetch = Core.fetch;
t.after(() => { Core.fetch = originalFetch; });
const requests = [];
Core.fetch = async (url, options) => {
requests.push({ url, options });
if (options.method === 'GET') {
return response(200, { order: { id: '21', current_state: '2' } });
}
return response(201, { order_history: { id: '99', id_order: '21', id_order_state: '7' } });
};
const api = new PrestashopApi('https://shop.example', 'secret', false, { maxGetAttempts: 1 });
const result = await api.setOrderState(21, 7);
assert.equal(result.unchanged, false);
assert.equal(requests.length, 2);
assert.match(requests[0].url, /\/api\/orders\/21\?/);
assert.equal(requests[1].options.method, 'POST');
assert.match(requests[1].url, /\/api\/order_histories\?output_format=JSON$/);
assert.match(requests[1].options.body, /<id_order_state>7<\/id_order_state>/);
assert.match(requests[1].options.body, /<id_order>21<\/id_order>/);
});
test('does not create a duplicate order history when PrestaShop already has the target state', async t => {
const originalFetch = Core.fetch;
t.after(() => { Core.fetch = originalFetch; });
let calls = 0;
Core.fetch = async () => {
calls += 1;
return response(200, { order: { id: '21', current_state: '7' } });
};
const api = new PrestashopApi('https://shop.example', 'secret', true, { maxGetAttempts: 1 });
const result = await api.setOrderState('21', '7');
assert.equal(result.unchanged, true);
assert.equal(calls, 1);
});
test('persists an attempt only before POST, and a persistence failure prevents POST', async t => {
const originalFetch = Core.fetch;
t.after(() => { Core.fetch = originalFetch; });
const steps = [];
Core.fetch = async (url, options) => {
steps.push(options.method);
return options.method === 'GET'
? response(200, { order: { id: '21', current_state: '2' } })
: response(201, { order_history: { id: '99', id_order: '21', id_order_state: '7' } });
};
const api = new PrestashopApi('https://shop.example', 'secret', true);
await api.setOrderState(21, 7, { beforeWrite: async () => steps.push('persist') });
assert.deepEqual(steps, ['GET', 'persist', 'POST']);
steps.length = 0;
await assert.rejects(api.setOrderState(21, 7, {
beforeWrite: async () => { throw new Error('database unavailable'); },
}), /database unavailable/);
assert.deepEqual(steps, ['GET']);
Core.fetch = async () => response(200, { order: { id: '21', current_state: '7' } });
await api.setOrderState(21, 7, { beforeWrite: async () => assert.fail('unnecessary attempt') });
});
test('uncertain status verification rejects a response for another order', async t => {
const originalFetch = Core.fetch;
t.after(() => { Core.fetch = originalFetch; });
Core.fetch = async () => response(200, { order: { id: '22', current_state: '7' } });
const api = new PrestashopApi('https://shop.example', 'secret', true);
await assert.rejects(api.getOrderState(21), /Invalid PrestaShop order state/);
await assert.rejects(api.setOrderState(21, 7, {
beforeWrite: async () => assert.fail('wrong order must not reach POST'),
}), /Invalid PrestaShop order state/);
});
test('rejects non-retryable 4xx and invalid JSON', async t => {
const originalFetch = Core.fetch;
t.after(() => { Core.fetch = originalFetch; });
const api = new PrestashopApi('https://shop.example', 'secret', true, { retryBaseMs: 1 });
Core.fetch = async () => response(401, { error: 'unauthorized' });
await assert.rejects(() => api.makeRequest('orders', 'GET'), /HTTP 401/);
Core.fetch = async () => response(200, '<html>not json</html>');
await assert.rejects(() => api.makeRequest('orders', 'GET'), /invalid JSON/);
});
test('times out stalled requests', async t => {
const originalFetch = Core.fetch;
t.after(() => { Core.fetch = originalFetch; });
// Timer timeoutu w fetchWithTimeout jest `unref`-owany, a Core.fetch nigdy się tu nie rozwiązuje,
// więc na prawdziwych timerach pętla zdarzeń pustoszeje i node:test anuluje ten test.
// Mockowany setTimeout pozwala wysterować timeout ręcznie przez tick().
t.mock.timers.enable({ apis: ['setTimeout'] });
Core.fetch = async () => new Promise(() => {});
const api = new PrestashopApi('https://shop.example', 'secret', true, {
timeoutMs: 5, maxGetAttempts: 1,
});
const pending = api.makeRequest('orders', 'GET');
await new Promise(resolve => setImmediate(resolve));
t.mock.timers.tick(10);
await assert.rejects(() => pending, /timed out/);
});
test('preserves the explicitly allowed product partial-success compatibility path', async t => {
const originalFetch = Core.fetch;
t.after(() => { Core.fetch = originalFetch; });
Core.fetch = async () => response(500, { product: { id: 1 } });
const api = new PrestashopApi('https://shop.example', 'secret', true, { maxGetAttempts: 1 });
assert.deepEqual(await api.makeRequest('products/1', 'GET', null, true), { product: { id: 1 } });
});
test('looks up combinations and stock locations with exact product filters', async t => {
const originalFetch = Core.fetch;
t.after(() => { Core.fetch = originalFetch; });
const urls = [];
Core.fetch = async url => {
urls.push(url);
if (url.includes('combinations')) return response(200, { combinations: [{ id: '10' }] });
return response(200, { stock_availables: [{ id: '20' }] });
};
const api = new PrestashopApi('https://shop.example', 'secret', true, { maxGetAttempts: 1 });
assert.deepEqual(await api.findProductCombinationsByReference('1', 'SKU-1'), [{ id: '10' }]);
assert.deepEqual(await api.getStockAvailabilities('1', '10'), [{ id: '20' }]);
assert.match(urls[0], /filter%5Bid_product%5D=%5B1%5D/);
assert.match(urls[0], /filter%5Breference%5D=%5BSKU-1%5D/);
assert.match(urls[1], /filter%5Bid_product_attribute%5D=%5B10%5D/);
});
test('does not turn an unsafe reference filter into an empty combination match', async t => {
const originalFetch = Core.fetch;
t.after(() => { Core.fetch = originalFetch; });
Core.fetch = async () => assert.fail('must not issue a broadened combination lookup');
const api = new PrestashopApi('https://shop.example', 'secret', true, { maxGetAttempts: 1 });
assert.equal(await api.findProductCombinationsByReference('1', 'SKU[1]'), null);
});
test('uses a combination image before the base product cover', async () => {
const api = new PrestashopApi('https://shop.example', 'secret', true, { maxGetAttempts: 1 });
api.getProduct = async () => assert.fail('base product must not be fetched when variant has an image');
const url = await api.getProductCoverImageUrl('1', {
associations: { images: [{ id: '55' }] },
});
assert.match(url, /images\/products\/1\/55\/home_default/);
assert.match(url, /ws_key=secret/);
});
test('derives a combination VAT rate from the base product tax calculation and caches it', async t => {
const originalFetch = Core.fetch;
t.after(() => { Core.fetch = originalFetch; });
const urls = [];
Core.fetch = async url => {
urls.push(url);
return response(200, { product: { orbito_price_net: '100.00', orbito_price_gross: '123.00' } });
};
const api = new PrestashopApi('https://shop.example', 'secret', true, { maxGetAttempts: 1 });
const context = { countryId: '1', stateId: '0', postcode: '00-001', currencyId: '2' };
assert.equal(await api.getProductTaxRate('20', '200', context), 0.23);
assert.equal(await api.getProductTaxRate('20', '200', context), 0.23);
assert.equal(urls.length, 1);
assert.match(urls[0], /products\/20\?/);
assert.match(urls[0], /price%5Borbito_price_net%5D%5Buse_tax%5D=0/);
assert.match(urls[0], /price%5Borbito_price_gross%5D%5Buse_tax%5D=1/);
assert.match(urls[0], /price%5Borbito_price_gross%5D%5Bproduct_attribute%5D=200/);
assert.match(urls[0], /price%5Borbito_price_gross%5D%5Bcountry%5D=1/);
assert.match(urls[0], /price%5Borbito_price_gross%5D%5Bpostcode%5D=00-001/);
});
test('returns no VAT rate when PrestaShop cannot provide comparable net and gross prices', async t => {
const originalFetch = Core.fetch;
t.after(() => { Core.fetch = originalFetch; });
Core.fetch = async () => response(200, {
product: { orbito_price_net: 'invalid', orbito_price_gross: '123.00' },
});
const api = new PrestashopApi('https://shop.example', 'secret', true, { maxGetAttempts: 1 });
assert.equal(await api.getProductTaxRate('20', '0', { countryId: '1' }), null);
});
test('collects public customer notes from order, cart and customer thread without cross-order leakage', async t => {
const originalFetch = Core.fetch;
t.after(() => { Core.fetch = originalFetch; });
const calls = [];
Core.fetch = async url => {
const parsed = new URL(url);
calls.push(parsed);
const orderId = parsed.searchParams.get('filter[id_order]');
const cartId = parsed.searchParams.get('filter[id_cart]');
const threadId = parsed.searchParams.get('filter[id_customer_thread]');
if (parsed.pathname.endsWith('/messages') && orderId === '[7]') return response(200, {
messages: [
{ id: '1', id_order: '7', id_cart: '11', private: '0', id_employee: '0', message: 'Dostawa rano' },
{ id: '2', id_order: '7', id_cart: '11', private: '1', id_employee: '0', message: 'Prywatna' },
{ id: '3', id_order: '7', id_cart: '11', private: '0', id_employee: '5', message: 'Pracownik' },
{ id: '4', id_order: '8', id_cart: '11', private: '0', id_employee: '0', message: 'Obce zamówienie' },
{ id: '7', id_order: '7', id_cart: '11', private: '0', id_employee: '0', message: 42 },
{ id: '8', id_order: '7', id_cart: '11', private: '0', id_employee: '0', message: {} },
{ id: '9', id_order: '7', id_cart: '11', private: '0', id_employee: '0', message: ' ' },
{ id: '10', id_order: '7', id_cart: '11', private: '0', id_employee: '0', message: 'Proszę o kontakt\r\npo 17:00' },
],
});
if (parsed.pathname.endsWith('/messages') && cartId === '[11]') return response(200, {
messages: [
{ id: '1', id_order: '7', id_cart: '11', private: '0', id_employee: '0', message: 'Dostawa rano' },
{ id: '5', id_order: '0', id_cart: '11', private: 'false', id_employee: '', message: 'Kod bramy: 1234' },
{ id: '6', id_order: '8', id_cart: '11', private: '0', id_employee: '0', message: 'Drugi order z koszyka' },
],
});
if (parsed.pathname.endsWith('/customer_threads')) return response(200, {
customer_threads: [{ id: '30', id_order: '7' }, { id: '31', id_order: '8' }],
});
if (parsed.pathname.endsWith('/customer_messages') && threadId === '[30]') return response(200, {
customer_messages: [
{ id: '40', id_customer_thread: '30', id_employee: '0', message: 'Dostawa rano' },
{ id: '41', id_customer_thread: '30', id_employee: '2', message: 'Odpowiedź pracownika' },
{ id: '42', id_customer_thread: '31', id_employee: '0', message: 'Obcy wątek' },
{ id: '43', id_customer_thread: '30', id_employee: '0', private: '2', message: 'Prywatny niestandardowy' },
{ id: '44', id_customer_thread: '30', id_employee: '0', message: 'Proszę o kontakt\npo 17:00' },
{ id: '45', id_customer_thread: '30', id_employee: '0', message: 'Dzwonek nie działa' },
],
});
assert.fail(`Unexpected endpoint: ${url}`);
};
const api = new PrestashopApi('https://shop.example', 'secret', true, { maxGetAttempts: 1 });
assert.deepEqual(await api.getCustomerNotes('7', '11', 'Dla Ani'), [
'Wiadomość dołączona do prezentu: Dla Ani',
'Dostawa rano',
'Proszę o kontakt\r\npo 17:00',
'Dzwonek nie działa',
'Kod bramy: 1234',
]);
assert.equal(calls.filter(call => call.pathname.endsWith('/customer_messages')).length, 1);
assert.equal(calls.filter(call => call.pathname.endsWith('/messages')).length, 2);
for (const call of calls.filter(call => call.pathname.endsWith('/messages')
|| call.pathname.endsWith('/customer_messages'))) {
assert.equal(call.searchParams.get('sort'), 'id_ASC');
}
});
test('keeps notes from available sources when one customer-note endpoint is forbidden', async t => {
const originalFetch = Core.fetch;
t.after(() => { Core.fetch = originalFetch; });
Core.fetch = async url => {
const parsed = new URL(url);
if (parsed.pathname.endsWith('/messages') && parsed.searchParams.get('filter[id_order]') === '[7]') {
return response(403, { errors: [] });
}
if (parsed.pathname.endsWith('/messages') && parsed.searchParams.get('filter[id_cart]') === '[11]') {
return response(200, { messages: [{ id_cart: '11', id_order: '0', private: '0', id_employee: '0', message: 'Checkout działa' }] });
}
if (parsed.pathname.endsWith('/customer_threads')) return response(200, { customer_threads: [] });
assert.fail(`Unexpected endpoint: ${url}`);
};
const api = new PrestashopApi('https://shop.example', 'secret', true, { maxGetAttempts: 1 });
assert.deepEqual(await api.getCustomerNotes('7', '11'), ['Checkout działa']);
});
test('retains gift_message when every customer-note endpoint is unavailable', async t => {
const originalFetch = Core.fetch;
t.after(() => { Core.fetch = originalFetch; });
Core.fetch = async () => response(403, { errors: [] });
const api = new PrestashopApi('https://shop.example', 'secret', true, { maxGetAttempts: 1 });
assert.deepEqual(await api.getCustomerNotes('7', '11', 'Dla Ani'), [
'Wiadomość dołączona do prezentu: Dla Ani',
]);
});