200 lines
8.8 KiB
JavaScript
200 lines
8.8 KiB
JavaScript
const test = require('node:test');
|
|
const assert = require('node:assert/strict');
|
|
const { registerContract } = require('../src/hook-contract');
|
|
const { reconcileOrderStatuses, registerStatusSyncHook, syncOrderStatusToPrestashop } = require('../src/status-sync');
|
|
|
|
const ORDER_ID = '6ac74c9146601f810995d104';
|
|
const STATUS_ID = '6a706a2a51bb5be41a1b43c0';
|
|
const SHOP_INSTANCE = 'aaaaaaaaaaaaaaaaaaaaaaaa';
|
|
|
|
function fixture() {
|
|
const hooks = new Map();
|
|
const order = {
|
|
_id: ORDER_ID, statusId: STATUS_ID, previousStatusId: '6a706a2a51bb5be41a1b43be',
|
|
statusDate: '2026-10-08T08:18:57.788Z',
|
|
source: { moduleCode: 'core/prestashop', moduleId: SHOP_INSTANCE, sourceId: '4856' },
|
|
};
|
|
const mapping = { _id: 'bbbbbbbbbbbbbbbbbbbbbbbb', orbitoOrderId: ORDER_ID, psOrderId: 4856 };
|
|
const calls = { posts: 0, reads: 0, logs: [], locks: new Set() };
|
|
registerContract({
|
|
getInstanceId: () => 'other-author-orders',
|
|
getModuleInfo: () => ({ code: 'other-author/orders' }),
|
|
registerHook: (name, handler) => hooks.set(name, handler),
|
|
}, 'orders.search', async params => ({ data: params._id === ORDER_ID ? [order] : [] }));
|
|
const deps = {
|
|
Core: {
|
|
getInstanceId: () => SHOP_INSTANCE,
|
|
getModuleInfo: () => ({ code: 'core/prestashop' }),
|
|
registerHook: async (name, handler) => hooks.set(name, handler),
|
|
execHook: async (name, request) => {
|
|
const handler = hooks.get(name);
|
|
return handler ? [await handler.call({
|
|
caller: { instanceId: SHOP_INSTANCE, moduleCode: 'core/prestashop' },
|
|
}, request)] : [];
|
|
},
|
|
getLock: async name => {
|
|
if (calls.locks.has(name)) return null;
|
|
calls.locks.add(name);
|
|
return name;
|
|
},
|
|
releaseLock: async name => calls.locks.delete(name),
|
|
},
|
|
PsOrder: {
|
|
find: async () => [structuredClone(mapping)],
|
|
findOne: async () => structuredClone(mapping),
|
|
update: async (key, update) => {
|
|
Object.assign(mapping, structuredClone(update.$set || {}));
|
|
for (const field of Object.keys(update.$unset || {})) delete mapping[field];
|
|
return { matchedCount: 1 };
|
|
},
|
|
},
|
|
Log: Object.fromEntries(['info', 'warn', 'error'].map(level => [level,
|
|
(...args) => calls.logs.push([level, ...args])])),
|
|
loadConfig: async () => ({ apiUrl: 'https://shop.test', apiKey: 'test-key',
|
|
statusMapping: [{ orbitoStatusId: STATUS_ID, psStateId: 16 }] }),
|
|
apiFor: () => api,
|
|
};
|
|
const api = {
|
|
state: 12, loseResponse: false,
|
|
getOrderState: async () => { calls.reads++; return api.state; },
|
|
setOrderState: async (id, state, { beforeWrite }) => {
|
|
assert.equal(id, 4856);
|
|
if (api.state === state) return { unchanged: true };
|
|
await beforeWrite();
|
|
assert.equal(mapping.statusSyncAttempt.psStateId, state);
|
|
calls.posts++;
|
|
if (api.loseResponse) throw new Error('lost POST response');
|
|
api.state = state;
|
|
return { unchanged: false };
|
|
},
|
|
};
|
|
return { deps, order, mapping, calls, api, hooks };
|
|
}
|
|
|
|
test('recovers a missed status event through a real alternative-provider hook and persists confirmation', async () => {
|
|
const { deps, mapping, calls, api } = fixture();
|
|
await reconcileOrderStatuses(deps);
|
|
assert.equal(api.state, 16);
|
|
assert.equal(calls.posts, 1);
|
|
assert.equal(mapping.statusSyncConfirmed.orbitoStatusId, STATUS_ID);
|
|
assert.ok(mapping.statusSyncCheckedAt instanceof Date);
|
|
await reconcileOrderStatuses(deps);
|
|
assert.equal(calls.posts, 1);
|
|
});
|
|
|
|
test('lost POST response survives another run and blocks a second write until an external read confirms it', async () => {
|
|
const { deps, mapping, calls, api } = fixture();
|
|
api.loseResponse = true;
|
|
await reconcileOrderStatuses(deps);
|
|
assert.equal(calls.posts, 1);
|
|
assert.ok(mapping.statusSyncAttempt);
|
|
await reconcileOrderStatuses(deps);
|
|
assert.equal(calls.posts, 1);
|
|
assert.equal(calls.reads, 1);
|
|
assert.equal(mapping.statusSyncConfirmed, undefined);
|
|
assert.ok(calls.logs.some(row => /requires verification/.test(row[1])));
|
|
// PrestaShop did commit the earlier request. Read confirmation requires no POST.
|
|
api.state = 16;
|
|
await reconcileOrderStatuses(deps);
|
|
assert.equal(calls.posts, 1);
|
|
assert.equal(mapping.statusSyncAttempt, undefined);
|
|
assert.equal(mapping.statusSyncConfirmed.psStateId, 16);
|
|
});
|
|
|
|
test('failure before POST can be checked again without recording an uncertain mutation', async () => {
|
|
const { deps, mapping, calls, api } = fixture();
|
|
const write = api.setOrderState;
|
|
api.setOrderState = async () => { throw new Error('GET unavailable'); };
|
|
await reconcileOrderStatuses(deps);
|
|
assert.equal(mapping.statusSyncAttempt, undefined);
|
|
api.setOrderState = write;
|
|
await reconcileOrderStatuses(deps);
|
|
assert.equal(calls.posts, 1);
|
|
});
|
|
|
|
test('a crash while saving success is recovered by GET without a second history', async () => {
|
|
const { deps, mapping, calls } = fixture();
|
|
const save = deps.PsOrder.update;
|
|
let failConfirmation = true;
|
|
deps.PsOrder.update = async (key, update) => {
|
|
if (update.$set?.statusSyncConfirmed && failConfirmation) {
|
|
failConfirmation = false;
|
|
throw new Error('confirmation storage unavailable');
|
|
}
|
|
return save(key, update);
|
|
};
|
|
await reconcileOrderStatuses(deps);
|
|
assert.equal(calls.posts, 1);
|
|
assert.ok(mapping.statusSyncAttempt);
|
|
await reconcileOrderStatuses(deps);
|
|
assert.equal(calls.reads, 1);
|
|
assert.equal(calls.posts, 1);
|
|
assert.equal(mapping.statusSyncAttempt, undefined);
|
|
assert.equal(mapping.statusSyncConfirmed.psStateId, 16);
|
|
});
|
|
|
|
test('does not synchronize another installation or an initial import through polling', async () => {
|
|
const { deps, order, calls } = fixture();
|
|
order.source.moduleId = 'cccccccccccccccccccccccc';
|
|
await reconcileOrderStatuses(deps);
|
|
assert.equal(calls.posts, 0);
|
|
order.source.moduleId = SHOP_INSTANCE;
|
|
delete order.previousStatusId;
|
|
await reconcileOrderStatuses(deps);
|
|
assert.equal(calls.posts, 0);
|
|
// An explicit event still works without a historical previousStatusId field.
|
|
await syncOrderStatusToPrestashop({ orderId: ORDER_ID }, deps);
|
|
assert.equal(calls.posts, 1);
|
|
});
|
|
|
|
test('logs silent skip reasons and provider failures from the registered event handler', async () => {
|
|
const { deps, calls, hooks } = fixture();
|
|
await registerStatusSyncHook(deps);
|
|
const handler = hooks.get('event:order:status_changed');
|
|
await handler({ orderId: 'bad-id' });
|
|
assert.ok(calls.logs.some(row => row[2]?.reason === 'invalid_order_id'));
|
|
hooks.delete('orders.search.providers');
|
|
await assert.rejects(handler({ orderId: ORDER_ID }), /HOOK_PROVIDER_UNAVAILABLE/);
|
|
assert.ok(calls.logs.some(row => /status event failed/.test(row[1])));
|
|
assert.equal(calls.posts, 0);
|
|
});
|
|
|
|
test('lost attempt record prevents POST and a subsequent status change creates one new history', async () => {
|
|
const { deps, order, calls } = fixture();
|
|
const save = deps.PsOrder.update;
|
|
deps.PsOrder.update = async (key, update) => update.$set?.statusSyncAttempt
|
|
? { matchedCount: 0 } : save(key, update);
|
|
await assert.rejects(syncOrderStatusToPrestashop({ orderId: ORDER_ID }, deps), /Cannot persist/);
|
|
assert.equal(calls.posts, 0);
|
|
deps.PsOrder.update = save;
|
|
await reconcileOrderStatuses(deps);
|
|
order.statusDate = '2026-10-08T09:00:00Z';
|
|
const config = await deps.loadConfig();
|
|
config.statusMapping[0].psStateId = 4;
|
|
deps.loadConfig = async () => config;
|
|
await reconcileOrderStatuses(deps);
|
|
assert.equal(calls.posts, 2);
|
|
});
|
|
|
|
test('an unavailable or ambiguous provider cannot cause writes and still advances the scan', async () => {
|
|
const { deps, hooks, calls, mapping } = fixture();
|
|
hooks.delete('orders.search.providers');
|
|
await reconcileOrderStatuses(deps);
|
|
assert.equal(calls.posts, 0);
|
|
assert.ok(mapping.statusSyncCheckedAt);
|
|
deps.Core.execHook = async () => [
|
|
{ protocol: 'orbito.contract/1', instanceId: 'first-instance' },
|
|
{ protocol: 'orbito.contract/1', instanceId: 'second-instance' },
|
|
];
|
|
await reconcileOrderStatuses(deps);
|
|
assert.equal(calls.posts, 0);
|
|
assert.ok(calls.logs.some(row => /HOOK_PROVIDER_AMBIGUOUS/.test(row[2]?.error)));
|
|
});
|
|
|
|
test('reconciliation stops before reading any order when the worker loses its lock', async () => {
|
|
const { deps, calls, mapping } = fixture();
|
|
await reconcileOrderStatuses(deps, () => false);
|
|
assert.equal(calls.posts, 0);
|
|
assert.equal(mapping.statusSyncCheckedAt, undefined);
|
|
});
|