Release 1.2.2: recover missed PrestaShop status changes
This commit is contained in:
@@ -82,6 +82,39 @@ test('does not create a duplicate order history when PrestaShop already has the
|
||||
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; });
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
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);
|
||||
});
|
||||
@@ -36,7 +36,10 @@ function dependencies(overrides = {}) {
|
||||
const deps = {
|
||||
Core,
|
||||
Log: { info() {}, warn() {}, error() {} },
|
||||
PsOrder: { findOne: async () => ({ psOrderId: 21, orbitoOrderId: ORDER_ID }) },
|
||||
PsOrder: {
|
||||
findOne: async () => ({ psOrderId: 21, orbitoOrderId: ORDER_ID }),
|
||||
update: async () => ({ matchedCount: 1 }),
|
||||
},
|
||||
loadConfig: async () => ({
|
||||
apiUrl: 'https://shop.test',
|
||||
apiKey: 'secret',
|
||||
@@ -44,7 +47,8 @@ function dependencies(overrides = {}) {
|
||||
}),
|
||||
apiFor: () => ({
|
||||
setOrderState: async (...args) => {
|
||||
calls.setOrderState.push(args);
|
||||
calls.setOrderState.push(args.slice(0, 2));
|
||||
await args[2]?.beforeWrite();
|
||||
return { unchanged: false };
|
||||
},
|
||||
}),
|
||||
|
||||
Reference in New Issue
Block a user