diff --git a/README.md b/README.md index 0b0d833..feadc80 100644 --- a/README.md +++ b/README.md @@ -50,6 +50,22 @@ Klucz Webservice wymaga co najmniej odczytu `order_states` i `orders` oraz prawa POST do `order_histories`. Synchronizacja nie używa `sendemail=1`, więc sama zmiana z Orbito nie zleca PrestaShop wysłania wiadomości statusowej do klienta. +Oprócz hooka zmiany statusu integracja co minutę sprawdza maksymalnie 50 +najdawniej sprawdzanych mapowań z własnej bazy. Odczytuje aktualny status przez +kontrakt `orders.search` i uzupełnia zgubione zdarzenia. Po przejściu partii +sprawdza kolejne zamówienia; pełny obieg może trwać kilka minut. Kontrola +okresowa obejmuje zamówienia z `previousStatusId`, czyli po zmianie statusu, +aby nie wysyłać do sklepu początkowego statusu importu. + +Potwierdzony status, jego datę i docelowy status PrestaShop zapisuje lokalnie. +Przed POST utrwala osobny znacznik próby. Jeśli odpowiedź zginie albo kontener +zostanie przerwany, przy następnym sprawdzeniu wykonuje wyłącznie GET. Zgodny +stan sklepu potwierdza poprzednią próbę; niezgodny blokuje dalsze zapisy i +generuje ostrzeżenie `previous write outcome is uncertain`. Taki przypadek +wymaga ręcznej weryfikacji historii i stanu zamówienia przed wznowieniem; +integracja nie ponawia samodzielnie niepewnego POST. Błąd przed utrwaleniem +próby można sprawdzić ponownie. Pominięcia i błędy obsługi zdarzeń są logowane. + Każda kombinacja PrestaShop jest zapisywana w `core/products` jako osobny produkt. Tożsamość źródłowa ma postać `product::combination:`; dla produktu bez kombinacji diff --git a/index.js b/index.js index 29edab5..4037d4f 100644 --- a/index.js +++ b/index.js @@ -10,7 +10,7 @@ const { registerPrestashopPermissions } = require('./src/register-permissions'); const { importOrdersForShop, syncPaymentsForShop } = require('./src/automation-jobs'); const { createJobRuntime } = require('./src/job-runtime'); const { ensureShopIcon } = require('./src/shop-icon'); -const { registerStatusSyncHook } = require('./src/status-sync'); +const { registerStatusSyncHook, reconcileOrderStatuses } = require('./src/status-sync'); const NEW_ORDERS_WINDOW_MS = 20 * 60 * 1000; // TTL locków cronowych w sekundach (jednostka oczekiwana przez Core.getLock/Core.extendLockTime). @@ -82,6 +82,10 @@ async function syncShopIcon() { } const jobs = [ + new CronJob('15 * * * * *', () => runtime.track(() => + runtime.withRenewedLock('prestashop-status-reconciliation', JOB_LOCK_TTL_SECONDS, valid => + reconcileOrderStatuses({ Core, Log, PsOrder, loadConfig, apiFor }, valid)) + ).catch(error => Log.error('PrestaShop status reconciliation worker failed', { error: error?.message }))), new CronJob('0 * * * * *', () => runtime.track(() => runtime.withRenewedLock('prestashop-orders-puller', JOB_LOCK_TTL_SECONDS, runOrdersPuller) )), diff --git a/module.json b/module.json index 0742ca9..23a8734 100644 --- a/module.json +++ b/module.json @@ -1,5 +1,5 @@ { "name": "core/prestashop", - "version": "1.2.1", + "version": "1.2.2", "singleton": false } diff --git a/package-lock.json b/package-lock.json index d802588..0cb73be 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "core.prestashop", - "version": "1.2.1", + "version": "1.2.2", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "core.prestashop", - "version": "1.2.1", + "version": "1.2.2", "license": "ISC", "dependencies": { "@orbito/api-lib": "^3.10.0", diff --git a/package.json b/package.json index f58a19e..f4eb349 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "core.prestashop", - "version": "1.2.1", + "version": "1.2.2", "description": "Integracja zamówień i płatności PrestaShop", "main": "index.js", "scripts": { diff --git a/src/PrestaApi.js b/src/PrestaApi.js index e4e30d7..36dc9d7 100644 --- a/src/PrestaApi.js +++ b/src/PrestaApi.js @@ -14,6 +14,10 @@ module.exports = class PrestashopApi { this.retryBaseMs = requestOptions.retryBaseMs || 250; } + close() { + this.cache.close(); + } + getUrl(endpoint = "") { if (endpoint.startsWith('/')) { endpoint = endpoint.slice(1); @@ -431,31 +435,49 @@ module.exports = class PrestashopApi { return messages; } - async setOrderState(orderId, stateId) { + async getOrderState(orderId) { + const id = String(orderId ?? '').trim(); + if (!/^\d+$/.test(id)) throw new Error('Invalid PrestaShop order id'); + const current = await this.makeRequest(`orders/${id}`, 'GET', { output_format: 'JSON' }); + if (String(current?.order?.id) !== id || !/^\d+$/.test(String(current.order.current_state))) { + throw new Error(`Invalid PrestaShop order state response for ${id}`); + } + return Number(current.order.current_state); + } + + async setOrderState(orderId, stateId, { beforeWrite } = {}) { const normalizedOrderId = String(orderId ?? '').trim(); const normalizedStateId = String(stateId ?? '').trim(); if (!/^\d+$/.test(normalizedOrderId) || !/^\d+$/.test(normalizedStateId)) { throw new Error('Invalid PrestaShop order or state id'); } - // Odczyt przed zapisem zapewnia idempotencję retry hooka. Status zmieniamy + // Odczyt przed zapisem pomija zbędny wpis historii. Status zmieniamy // przez order_histories (zamiast bezpośredniej edycji current_state), aby // PrestaShop wykonał standardowe skutki uboczne przejścia statusu. const current = await this.makeRequest(`orders/${normalizedOrderId}`, 'GET', { output_format: 'JSON' }); - if (!current?.order?.id) throw new Error(`PrestaShop order ${normalizedOrderId} not found`); + if (String(current?.order?.id) !== normalizedOrderId + || !/^\d+$/.test(String(current?.order?.current_state))) { + throw new Error(`Invalid PrestaShop order state response for ${normalizedOrderId}`); + } if (String(current.order.current_state) === normalizedStateId) { return { order: current.order, unchanged: true }; } + // Konsument utrwala próbę PRZED efektem. Awaria zapisu lokalnego + // blokuje POST, a utrata odpowiedzi po POST nie pozwala go ponowić. + if (beforeWrite) await beforeWrite(); const response = await this.makeRequest('order_histories?output_format=JSON', 'POST', { order_history: { id_order_state: normalizedStateId, id_order: normalizedOrderId } }); - if (!response?.order_history?.id) { + if (!response?.order_history?.id + || String(response.order_history.id_order) !== normalizedOrderId + || String(response.order_history.id_order_state) !== normalizedStateId) { throw new Error('Failed to set PrestaShop order state'); } return { orderHistory: response.order_history, unchanged: false }; diff --git a/src/models/PsOrder.js b/src/models/PsOrder.js index 9f1cdfe..a721c1e 100644 --- a/src/models/PsOrder.js +++ b/src/models/PsOrder.js @@ -11,6 +11,9 @@ const schema = new DB.Schema('ps_orders', { // Ostatnia kumulatywna kwota total_paid_real potwierdzona w core/orders. paymentTotalSynced: { type: 'number', optional: true }, paymentCheckedAt: { type: 'date', optional: true }, + statusSyncCheckedAt: { type: 'date', optional: true }, + statusSyncAttempt: { type: 'object', optional: true }, + statusSyncConfirmed: { type: 'object', optional: true }, nextPaymentCheckAt: { type: 'date', optional: true }, }); @@ -21,5 +24,6 @@ DB.createIndex('ps_orders', { psOrderId: 1, shopConfigId: 1 }, { unique: true }) DB.createIndex('ps_orders', { orbitoOrderId: 1 }); DB.createIndex('ps_orders', { syncedAt: -1 }); DB.createIndex('ps_orders', { shopConfigId: 1, nextPaymentCheckAt: 1, syncedAt: 1 }); +DB.createIndex('ps_orders', { statusSyncCheckedAt: 1, _id: 1 }); module.exports = schema; diff --git a/src/status-sync.js b/src/status-sync.js index 8d25672..03c5515 100644 --- a/src/status-sync.js +++ b/src/status-sync.js @@ -14,6 +14,20 @@ function text(value) { return value == null ? '' : String(value).trim(); } +function statusVersion(order, psStateId) { + const date = order.statusDate ? new Date(order.statusDate) : null; + return { + orbitoStatusId: text(order.statusId), + statusDate: date && Number.isFinite(date.getTime()) ? date.toISOString() : '', + psStateId, + }; +} + +function sameVersion(left, right) { + return left?.orbitoStatusId === right.orbitoStatusId + && left.statusDate === right.statusDate && left.psStateId === right.psStateId; +} + function sourceOwnershipError(order, storedMapping, Core) { const ownModuleCode = text(Core.getModuleInfo?.().code) || 'core/prestashop'; if (text(order?.source?.moduleCode) !== ownModuleCode) return 'different_source_module'; @@ -58,15 +72,17 @@ async function syncOrderStatusToPrestashop(payload, dependencies) { const lockName = `prestashop-status-sync:${orderId}`; const lockId = await Core.getLock(lockName, STATUS_SYNC_LOCK_TTL_SECONDS); if (!lockId) { - // Równoległe zdarzenie zostaje w outboxie core/orders. Przy ponowieniu - // odczyta najnowszy status Orbito, więc starszy event nie cofnie sklepu. + // Kontrola okresowa wróci do zamówienia. SDK hooków może przechwycić + // wyjątek, więc nie polegamy na ponowieniu po stronie nadawcy. throw new Error(`PrestaShop status sync is already running for order ${orderId}`); } + let api; try { - const [orderResult, config] = await Promise.all([ + const [orderResult, config, currentMapping] = await Promise.all([ requestHook(Core, 'orders.search', { _id: orderId }), loadConfig(), + PsOrder.findOne({ orbitoOrderId: orderId }), ]); const order = asOrders(orderResult)[0]; if (!order) return { skipped: true, reason: 'order_not_found' }; @@ -77,6 +93,12 @@ async function syncOrderStatusToPrestashop(payload, dependencies) { return { skipped: true, reason: 'shop_not_configured' }; } + // Polling uzupełnia zmiany statusów, nie wysyła początkowego statusu + // importu. Rzeczywiste zdarzenie zawsze może uruchomić synchronizację. + if (payload.reconcile && !order.previousStatusId) { + return { skipped: true, reason: 'status_not_changed' }; + } + // Zawsze czytamy bieżący status zamówienia, a nie status ze zdarzenia. // Dzięki temu opóźniony retry może tylko doprowadzić sklep do aktualnego // stanu Orbito, nigdy cofnąć go do starszego statusu. @@ -86,12 +108,56 @@ async function syncOrderStatusToPrestashop(payload, dependencies) { return { skipped: true, reason: 'status_not_mapped' }; } - const psOrderId = Number(storedMapping?.psOrderId ?? order.source?.sourceId); + const psOrderId = Number(currentMapping?.psOrderId ?? order.source?.sourceId); if (!Number.isSafeInteger(psOrderId) || psOrderId <= 0) { throw new Error(`Cannot resolve PrestaShop order id for Orbito order ${orderId}`); } - const result = await apiFor(config).setOrderState(psOrderId, psStateId); + let mapping = currentMapping; + if (!mapping) { + await PsOrder.create({ shopConfigId: String(config._id || 'default'), psOrderId, orbitoOrderId: orderId }); + mapping = await PsOrder.findOne({ orbitoOrderId: orderId }); + if (!mapping) throw new Error(`Cannot persist PrestaShop status mapping for ${orderId}`); + } + const mappingKey = mapping._id ? { _id: mapping._id } : { orbitoOrderId: orderId }; + const version = statusVersion(order, psStateId); + if (!mapping.statusSyncAttempt && sameVersion(mapping.statusSyncConfirmed, version)) { + return { synced: true, unchanged: true, orderId, psOrderId, orbitoStatusId, psStateId }; + } + api = apiFor(config); + + if (mapping.statusSyncAttempt) { + // Po timeoutcie lub restarcie wyłącznie odczyt. Niezgodny stan + // wymaga weryfikacji operatora, nigdy automatycznego drugiego POST. + const actualStateId = await api.getOrderState(psOrderId); + if (actualStateId !== mapping.statusSyncAttempt.psStateId) { + Log.warn('PrestaShop status sync requires verification; previous write outcome is uncertain', { + orderId, psOrderId, actualStateId, expectedStateId: mapping.statusSyncAttempt.psStateId, + }); + return { skipped: true, reason: 'outcome_uncertain', orderId, psOrderId }; + } + mapping.statusSyncConfirmed = mapping.statusSyncAttempt; + await PsOrder.update(mappingKey, { + $set: { statusSyncConfirmed: mapping.statusSyncConfirmed }, + $unset: { statusSyncAttempt: '' }, + }); + } + if (sameVersion(mapping.statusSyncConfirmed, version)) { + return { synced: true, unchanged: true, orderId, psOrderId, orbitoStatusId, psStateId }; + } + + const result = await api.setOrderState(psOrderId, psStateId, { + beforeWrite: async () => { + const saved = await PsOrder.update(mappingKey, { + $set: { statusSyncAttempt: { ...version, attemptedAt: new Date() } }, + }); + if (saved?.matchedCount !== 1) throw new Error('Cannot persist PrestaShop status write attempt'); + }, + }); + await PsOrder.update(mappingKey, { + $set: { statusSyncConfirmed: version }, + $unset: { statusSyncAttempt: '' }, + }); Log.info('PrestaShop order status synchronized from Orbito', { orderId, psOrderId, @@ -114,6 +180,7 @@ async function syncOrderStatusToPrestashop(payload, dependencies) { }); throw error; } finally { + api?.close?.(); await Core.releaseLock(lockId).catch(error => { Log.warn('PrestaShop status sync lock release failed', { orderId, @@ -125,15 +192,48 @@ async function syncOrderStatusToPrestashop(payload, dependencies) { } function registerStatusSyncHook(dependencies) { - return dependencies.Core.registerHook('event:order:status_changed', payload => ( - syncOrderStatusToPrestashop(payload, dependencies) - )); + return dependencies.Core.registerHook('event:order:status_changed', async payload => { + try { + const result = await syncOrderStatusToPrestashop(payload, dependencies); + if (result.skipped) dependencies.Log?.info('PrestaShop status event skipped', { + orderId: text(payload?.orderId), reason: result.reason, + }); + return result; + } catch (error) { + // Obejmuje też błędy wyszukania dostawcy przed uzyskaniem locka. + dependencies.Log?.error('PrestaShop status event failed', { + orderId: text(payload?.orderId), error: error?.message, + }); + throw error; + } + }); +} + +async function reconcileOrderStatuses(dependencies, isLockValid = () => true) { + const { PsOrder, Log = console } = dependencies; + // Najdawniej sprawdzane rekordy pierwsze; znacznik zapewnia rotację, + // także gdy kilka starych zamówień usunięto lub wymaga ręcznej weryfikacji. + const mappings = await PsOrder.find({ orbitoOrderId: { $exists: true, $ne: null } }, + 50, 0, { statusSyncCheckedAt: 1, _id: 1 }); + for (const mapping of mappings) { + if (!isLockValid()) break; + try { + await syncOrderStatusToPrestashop({ orderId: text(mapping.orbitoOrderId), reconcile: true }, dependencies); + } catch (error) { + Log.warn('PrestaShop status reconciliation failed', { + orderId: text(mapping.orbitoOrderId), psOrderId: mapping.psOrderId, error: error?.message, + }); + } finally { + await PsOrder.update({ _id: mapping._id }, { $set: { statusSyncCheckedAt: new Date() } }); + } + } } module.exports = { STATUS_SYNC_LOCK_TTL_SECONDS, asOrders, registerStatusSyncHook, + reconcileOrderStatuses, sourceOwnershipError, syncOrderStatusToPrestashop, }; diff --git a/test/presta-api.test.js b/test/presta-api.test.js index 49fb21f..2b9bf28 100644 --- a/test/presta-api.test.js +++ b/test/presta-api.test.js @@ -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; }); diff --git a/test/status-reconciliation.test.js b/test/status-reconciliation.test.js new file mode 100644 index 0000000..0ee832f --- /dev/null +++ b/test/status-reconciliation.test.js @@ -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); +}); diff --git a/test/status-sync.test.js b/test/status-sync.test.js index 1100a3b..4de0630 100644 --- a/test/status-sync.test.js +++ b/test/status-sync.test.js @@ -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 }; }, }),