fix: harden PrestaShop automation jobs
This commit is contained in:
@@ -0,0 +1,190 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
|
||||
const {
|
||||
importOrdersForShop,
|
||||
paymentTransactionId,
|
||||
processPaymentMapping,
|
||||
syncPaymentsForShop,
|
||||
} = require('../src/automation-jobs');
|
||||
|
||||
const silentLog = { info() {}, warn() {}, error() {} };
|
||||
|
||||
function oldOrder(id, reference = `REF-${id}`) {
|
||||
return { id, reference, date_add: '2026-01-01 10:00:00' };
|
||||
}
|
||||
|
||||
test('first run safely starts at the newest order without backfilling history', async () => {
|
||||
const writes = [];
|
||||
const config = { _id: 'default', lastOrderId: null };
|
||||
const result = await importOrdersForShop(config, {
|
||||
makeRequest: async () => ({ orders: [{ id: '812' }] }),
|
||||
}, {
|
||||
setLastOrderId: async id => writes.push(id),
|
||||
Log: silentLog,
|
||||
});
|
||||
|
||||
assert.deepEqual(writes, [812]);
|
||||
assert.equal(config.lastOrderId, 812);
|
||||
assert.deepEqual(result, { status: 'initialized', cursor: 812, processed: 0 });
|
||||
});
|
||||
|
||||
test('cursor advances only through confirmed successes and stops before failed order', async () => {
|
||||
const writes = [];
|
||||
const imported = [];
|
||||
const config = { _id: 'default', lastOrderId: 10 };
|
||||
const api = { makeRequest: async () => ({ orders: [oldOrder(11), oldOrder(12), oldOrder(13)] }) };
|
||||
const result = await importOrdersForShop(config, api, {
|
||||
Core: { callModule: async () => ({ data: [] }) },
|
||||
PsOrder: {},
|
||||
importFromPSOrder: async id => {
|
||||
imported.push(id);
|
||||
if (id === 12) throw new Error('invalid order');
|
||||
return { status: 'imported', psOrderId: id, orbitoOrderId: `orbito-${id}` };
|
||||
},
|
||||
setLastOrderId: async id => writes.push(id),
|
||||
Log: silentLog,
|
||||
now: () => new Date('2026-01-02T00:00:00Z').getTime(),
|
||||
});
|
||||
|
||||
assert.deepEqual(imported, [11, 12]);
|
||||
assert.deepEqual(writes, [11]);
|
||||
assert.equal(config.lastOrderId, 11);
|
||||
assert.deepEqual(result, { status: 'processed', cursor: 11, processed: 1 });
|
||||
});
|
||||
|
||||
test('existing Orbito order repairs a missing mapping before advancing the cursor', async () => {
|
||||
const updates = [];
|
||||
const writes = [];
|
||||
const config = { _id: 'default', lastOrderId: 20 };
|
||||
const api = {
|
||||
makeRequest: async () => ({ orders: [oldOrder(21)] }),
|
||||
getOrder: async () => ({ id: 21, reference: 'REF-21', date_add: '2026-01-01 10:00:00', total_paid_real: '25.00' }),
|
||||
};
|
||||
const PsOrder = {
|
||||
findOne: async () => null,
|
||||
update: async (...args) => updates.push(args),
|
||||
};
|
||||
|
||||
await importOrdersForShop(config, api, {
|
||||
Core: { callModule: async () => ({ data: [{ _id: 'orbito-21', summary: { paid: 25 } }] }) },
|
||||
PsOrder,
|
||||
importFromPSOrder: async () => assert.fail('must not import an existing order'),
|
||||
setLastOrderId: async id => writes.push(id),
|
||||
Log: silentLog,
|
||||
now: () => new Date('2026-01-02T00:00:00Z').getTime(),
|
||||
});
|
||||
|
||||
assert.equal(updates.length, 1);
|
||||
assert.equal(updates[0][1].$set.orbitoOrderId, 'orbito-21');
|
||||
assert.equal(updates[0][1].$set.paymentTotalSynced, 25);
|
||||
assert.deepEqual(updates[0][2], { upsert: true });
|
||||
assert.deepEqual(writes, [21]);
|
||||
});
|
||||
|
||||
test('payment sync appends only the cumulative delta with a deterministic transaction id', async () => {
|
||||
const calls = [];
|
||||
const updates = [];
|
||||
const mapping = { _id: 'map-1', psOrderId: 44, orbitoOrderId: 'order-1', paymentTotalSynced: 20 };
|
||||
const config = { _id: 'shop-a' };
|
||||
const result = await processPaymentMapping(mapping, config, {
|
||||
getOrder: async () => ({ total_paid_real: '55.00', payment: 'Card', date_upd: '2026-01-02 12:00:00' }),
|
||||
}, {
|
||||
Core: { callModule: async (module, method, params) => {
|
||||
calls.push({ module, method, params });
|
||||
if (method === 'search') return { data: [{ summary: { paid: 20, gross: 100 } }] };
|
||||
return { success: true };
|
||||
} },
|
||||
PsOrder: { update: async (...args) => updates.push(args) },
|
||||
nowDate: new Date('2026-01-02T12:01:00Z'),
|
||||
nextCheckMs: 1000,
|
||||
retryCheckMs: 1000,
|
||||
Log: silentLog,
|
||||
});
|
||||
|
||||
assert.equal(result.amount, 35);
|
||||
assert.equal(calls[1].method, 'payments.upsert');
|
||||
assert.equal(calls[1].params.payment.amount, 35);
|
||||
assert.equal(calls[1].params.payment.transactionId, 'prestashop:shop-a:44:paid:5500');
|
||||
assert.equal(updates[0][1].$set.paymentTotalSynced, 55);
|
||||
});
|
||||
|
||||
test('legacy mapping establishes a conservative baseline instead of duplicating a payment', async () => {
|
||||
const methods = [];
|
||||
const updates = [];
|
||||
await processPaymentMapping({ _id: 'map-2', psOrderId: 45, orbitoOrderId: 'order-2' }, { _id: 'default' }, {
|
||||
getOrder: async () => ({ total_paid_real: '50.00' }),
|
||||
}, {
|
||||
Core: { callModule: async (_module, method) => {
|
||||
methods.push(method);
|
||||
return { data: [{ summary: { paid: 50, gross: 100 } }] };
|
||||
} },
|
||||
PsOrder: { update: async (...args) => updates.push(args) },
|
||||
nowDate: new Date(), nextCheckMs: 1000, retryCheckMs: 1000, Log: silentLog,
|
||||
});
|
||||
|
||||
assert.deepEqual(methods, ['search']);
|
||||
assert.equal(updates[0][1].$set.paymentTotalSynced, 50);
|
||||
});
|
||||
|
||||
test('a mapping write failure retries the same payment transaction id safely', async () => {
|
||||
const transactionIds = [];
|
||||
let failMappingWrite = true;
|
||||
const mapping = { _id: 'map-3', psOrderId: 46, orbitoOrderId: 'order-3', paymentTotalSynced: 10 };
|
||||
const dependencies = {
|
||||
Core: { callModule: async (_module, method, params) => {
|
||||
if (method === 'search') return { data: [{ summary: { paid: 10, gross: 100 } }] };
|
||||
transactionIds.push(params.payment.transactionId);
|
||||
return { success: true };
|
||||
} },
|
||||
PsOrder: { update: async (_query, update) => {
|
||||
if (update.$set.paymentTotalSynced !== undefined && failMappingWrite) {
|
||||
failMappingWrite = false;
|
||||
throw new Error('temporary DB failure');
|
||||
}
|
||||
} },
|
||||
nowDate: new Date(), nextCheckMs: 1000, retryCheckMs: 1000, Log: silentLog,
|
||||
};
|
||||
const api = { getOrder: async () => ({ total_paid_real: '30.00' }) };
|
||||
|
||||
const first = await processPaymentMapping(mapping, { _id: 'default' }, api, dependencies);
|
||||
const second = await processPaymentMapping(mapping, { _id: 'default' }, api, dependencies);
|
||||
|
||||
assert.equal(first.success, false);
|
||||
assert.equal(second.success, true);
|
||||
assert.deepEqual(transactionIds, [
|
||||
paymentTransactionId({ _id: 'default' }, 46, 30),
|
||||
paymentTransactionId({ _id: 'default' }, 46, 30),
|
||||
]);
|
||||
});
|
||||
|
||||
test('payment scheduler drains multiple pages and includes orders older than five days', async () => {
|
||||
const findQueries = [];
|
||||
let page = 0;
|
||||
const PsOrder = {
|
||||
find: async query => {
|
||||
findQueries.push(query);
|
||||
page += 1;
|
||||
if (page === 1) return [{ _id: 'a', psOrderId: 1, orbitoOrderId: 'o1', paymentTotalSynced: 0 }];
|
||||
if (page === 2) return [{ _id: 'b', psOrderId: 2, orbitoOrderId: 'o2', paymentTotalSynced: 0 }];
|
||||
return [];
|
||||
},
|
||||
update: async () => {},
|
||||
};
|
||||
const Core = { callModule: async (_module, method) => method === 'search'
|
||||
? { data: [{ summary: { paid: 0, gross: 10 } }] }
|
||||
: { success: true } };
|
||||
|
||||
const result = await syncPaymentsForShop(
|
||||
{ _id: 'default' },
|
||||
{ getOrder: async () => ({ total_paid_real: 0 }) },
|
||||
null,
|
||||
new Date('2026-01-10T00:00:00Z'),
|
||||
{ pageSize: 1, maxPages: 3 },
|
||||
{ Core, PsOrder, Log: silentLog, now: () => new Date('2026-01-10T01:00:00Z') }
|
||||
);
|
||||
|
||||
assert.equal(result.processed, 2);
|
||||
assert.equal(findQueries.length, 3);
|
||||
assert.deepEqual(findQueries[0].syncedAt, { $lt: new Date('2026-01-10T00:00:00Z') });
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { createJobRuntime } = require('../src/job-runtime');
|
||||
|
||||
test('lock is released after success and after failure', async () => {
|
||||
const released = [];
|
||||
const Core = {
|
||||
getLock: async name => name,
|
||||
extendLockTime: async () => true,
|
||||
releaseLock: async id => released.push(id),
|
||||
};
|
||||
const runtime = createJobRuntime(Core, { error() {}, warn() {} });
|
||||
|
||||
assert.equal(await runtime.withRenewedLock('ok', 5000, async valid => valid() && 7), 7);
|
||||
await assert.rejects(() => runtime.withRenewedLock('fail', 5000, async () => { throw new Error('boom'); }), /boom/);
|
||||
assert.deepEqual(released, ['ok', 'fail']);
|
||||
});
|
||||
|
||||
test('stop waits for tracked work and blocks subsequent runs until start', async () => {
|
||||
const runtime = createJobRuntime({}, console);
|
||||
let finish;
|
||||
const active = runtime.track(() => new Promise(resolve => { finish = resolve; }));
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
const stopping = runtime.stop();
|
||||
finish('done');
|
||||
await stopping;
|
||||
assert.equal(await active, 'done');
|
||||
assert.equal(await runtime.track(async () => 'blocked'), null);
|
||||
runtime.start();
|
||||
assert.equal(await runtime.track(async () => 'running'), 'running');
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const Module = require('node:module');
|
||||
const Core = { 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('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; });
|
||||
Core.fetch = async () => new Promise(() => {});
|
||||
const api = new PrestashopApi('https://shop.example', 'secret', true, {
|
||||
timeoutMs: 5, maxGetAttempts: 1,
|
||||
});
|
||||
|
||||
await assert.rejects(() => api.makeRequest('orders', 'GET'), /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 } });
|
||||
});
|
||||
Reference in New Issue
Block a user