225 lines
9.4 KiB
JavaScript
225 lines
9.4 KiB
JavaScript
const { withHookFixtures } = require('./helpers/hook-fixtures');
|
|
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('a failed order leaves a retryable cursor gap while later orders are still inspected', async () => {
|
|
const writes = [];
|
|
const imported = [];
|
|
const errors = [];
|
|
const config = { _id: 'default', lastOrderId: 10 };
|
|
const api = { makeRequest: async () => ({ orders: [oldOrder(11), oldOrder(12), oldOrder(13)] }) };
|
|
const result = await importOrdersForShop(config, api, {
|
|
Core: withHookFixtures({ 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, error: (message, details) => errors.push({ message, details }) },
|
|
now: () => new Date('2026-01-02T00:00:00Z').getTime(),
|
|
});
|
|
|
|
assert.deepEqual(imported, [11, 12, 13]);
|
|
assert.deepEqual(writes, [11]);
|
|
assert.equal(config.lastOrderId, 11);
|
|
assert.deepEqual(result, { status: 'processed', cursor: 11, processed: 2 });
|
|
assert.deepEqual(errors, [{
|
|
message: 'Failed to import PS order; keeping cursor before the gap and continuing',
|
|
details: {
|
|
orderId: 12,
|
|
previousCursor: 11,
|
|
cursor: 11,
|
|
error: 'invalid order',
|
|
},
|
|
}]);
|
|
});
|
|
|
|
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: withHookFixtures({ 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: withHookFixtures({ 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.date.toISOString(), '2026-01-02T11:00:00.000Z');
|
|
assert.equal(calls[1].params.payment.transactionId, 'prestashop:shop-a:44:paid:5500');
|
|
assert.equal(updates[0][1].$set.paymentTotalSynced, 55);
|
|
});
|
|
|
|
test('import waits for the 30-second stability window using shop time without guessing an offset', async () => {
|
|
for (const [timeZone, localHour] of [['Europe/Warsaw', '11'], ['UTC', '09']]) {
|
|
const imported = [], cursors = [];
|
|
const result = await importOrdersForShop({ _id: 'default', lastOrderId: 10, timeZone }, {
|
|
makeRequest: async () => ({ orders: [
|
|
{ id: 11, reference: 'R11', date_add: `2026-09-25 ${localHour}:00:29` },
|
|
{ id: 12, reference: 'R12', date_add: `2026-09-25 ${localHour}:00:45` },
|
|
{ id: 13, reference: 'R13', date_add: '2026-09-25 15:00:00' },
|
|
] }),
|
|
}, {
|
|
Core: withHookFixtures({ callModule: async () => ({ data: [] }) }),
|
|
importFromPSOrder: async id => { imported.push(id); return { status: 'imported' }; },
|
|
setLastOrderId: async id => cursors.push(id),
|
|
now: () => Date.parse('2026-09-25T09:01:00Z'),
|
|
Log: silentLog,
|
|
});
|
|
assert.deepEqual(imported, [11]);
|
|
assert.deepEqual(cursors, [11]);
|
|
assert.equal(result.cursor, 11);
|
|
}
|
|
});
|
|
|
|
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: withHookFixtures({ 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: withHookFixtures({ 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 = withHookFixtures({ 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') });
|
|
});
|