From 599a7b9863b53a2155ac5691f1504f2af570cac1 Mon Sep 17 00:00:00 2001 From: fatequod Date: Wed, 30 Sep 2026 08:26:55 +0200 Subject: [PATCH] Release PrestaShop 1.2.0: use hook contracts --- AGENTS.md | 16 +++ index.js | 1 + methods/status/get_with_counts.js | 3 +- methods/status/search.js | 7 ++ methods/testPull.js | 3 +- module.json | 10 +- package-lock.json | 15 +-- package.json | 7 +- src/OrderImporter.js | 9 +- src/automation-jobs.js | 7 +- src/hook-contract.js | 120 +++++++++++++++++++ src/orders-api.js | 6 +- src/register-config.js | 2 +- src/register-contracts.js | 8 ++ src/shop-icon.js | 3 +- src/status-sync.js | 5 +- test/automation-jobs.test.js | 23 ++-- test/helpers/hook-fixtures.js | 50 ++++++++ test/job-runtime.test.js | 9 +- test/order-importer-customer-message.test.js | 5 +- test/order-importer-dates.test.js | 5 +- test/order-importer-metadata.test.js | 5 +- test/presta-api.test.js | 3 +- test/shop-icon.test.js | 11 +- test/status-sync.test.js | 5 +- 25 files changed, 276 insertions(+), 62 deletions(-) create mode 100644 AGENTS.md create mode 100644 methods/status/search.js create mode 100644 src/hook-contract.js create mode 100644 src/register-contracts.js create mode 100644 test/helpers/hook-fixtures.js diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..a40ac14 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,16 @@ +# Orbito — zasady modułu dla agentów AI + +Jeśli pracujesz w pełnym workspace Orbito, przed zmianami przeczytaj [../codex.md](../codex.md). W osobnym klonie repozytorium nadal obowiązują wszystkie poniższe reguły. + +1. **Komunikacja między modułami wyłącznie przez hooki. Jedyny wyjątek: `core/orders → core/products`.** Wyjątek jest jednostronny i nieprzechodni. +2. Nie dodawaj bezpośredniego RPC/HTTP do innego modułu, importów jego kodu lub danych, innych zależności `dependsOn` ani stałych obcych celów w UI. Wrapper, proxy lub dynamiczna nazwa nie stanowią obejścia tej reguły. +3. Nie wpisuj na sztywno konkretnego dostawcy ani klienta API. Zakazane jest np. zaufanie tylko do `core/packing` w orders. Sprawdzaj uwierzytelniony kontekst i uprawnienia. Własne identyfikatory, lokalne funkcje i SDK platformy są dozwolone. +4. Używaj istniejącego `src/hook-contract.js` i jawnych kontraktów domenowych. Brak kontraktu rozwiąż przez jego dodanie lub rozszerzenie, bez awaryjnego powrotu do RPC. Każda paczka ma działać samodzielnie. +5. Obsłuż zero, jednego i wielu dostawców oraz kilka kont jednego modułu. Komenda ma wskazywać jedną instancję przed efektem; nie wybieraj pierwszej odpowiedzi i nie ponawiaj automatycznie niepewnego efektu. Nie zgaduj właściciela danych historycznych. +6. Listy konfiguracji pobieraj hookiem w bieżącej instancji, np. jako `options.values` z `{ id, label }`. Nie zakładaj, że `options.module` adresuje właściwe konto. Zachowuj zapisane ID i pokazuj błąd niedostępnej listy. +7. Przy zmianach integracji uruchom testy modułu oraz, z katalogu pełnego workspace, `node --test --test-concurrency=1 --test-force-exit module-contracts/*.test.js`. Dodaj odpowiedni test regresji prawdziwej ścieżki hooków. Nie osłabiaj kontroli architektury. Jeżeli workspace lub testy są niedostępne, podaj ograniczenie zamiast deklarować pełną weryfikację. +8. **Nie modyfikuj `ordershub-backend` ani `ordershub-frontend`**, także przez zbiorcze polecenia. Zachowuj istniejące zmiany użytkownika. Ogólne polecenie naprawy lub publikacji nie zezwala na wyjątki od architektury. + +## Code Review Rules + +Zgłaszaj bezpośrednie powiązania między modułami także poza manifestem: zaszytego klienta API, obcy cel formularza, import modelu, fallback RPC i arbitralny wybór dostawcy. Sprawdź kontrakt, wybór instancji i test z alternatywnym dostawcą. diff --git a/index.js b/index.js index a885e19..29edab5 100644 --- a/index.js +++ b/index.js @@ -18,6 +18,7 @@ const JOB_LOCK_TTL_SECONDS = 5 * 60; const runtime = createJobRuntime(Core, Log); Utils.loadMethods(__dirname + '/methods'); +require('./src/register-contracts').registerContracts(); registerPrestashopConfigBlocks().catch(error => { Log.error('PrestaShop: nie udało się zarejestrować bloków Config', { error: error?.message }); diff --git a/methods/status/get_with_counts.js b/methods/status/get_with_counts.js index 024c1a7..d8aab36 100644 --- a/methods/status/get_with_counts.js +++ b/methods/status/get_with_counts.js @@ -1,8 +1,9 @@ +const { requestHook } = require('../../src/hook-contract'); const { Core } = require('@orbito/api-lib'); const { PERMISSIONS, requirePermission } = require('../../src/register-permissions'); // Proxy do core/orders — statusy są współdzielone i zarządzane w core/orders. module.exports = async function(params, ctx) { requirePermission(PERMISSIONS.ORDERS_VIEW, ctx); - return Core.callModule('core/orders', 'status.get_with_counts', params || {}); + return requestHook(Core, 'orders.status.get_with_counts', params || {}); }; diff --git a/methods/status/search.js b/methods/status/search.js new file mode 100644 index 0000000..4078bce --- /dev/null +++ b/methods/status/search.js @@ -0,0 +1,7 @@ +const { Core } = require('@orbito/api-lib'); +const { requestHook } = require('../../src/hook-contract'); +const { PERMISSIONS, requirePermission } = require('../../src/register-permissions'); +module.exports = { params: {}, async handler(params, ctx) { + requirePermission(PERMISSIONS.ORDERS_VIEW, ctx); + return requestHook(Core, 'orders.status.search', params || {}); +} }; diff --git a/methods/testPull.js b/methods/testPull.js index 53bb554..8b89aaa 100644 --- a/methods/testPull.js +++ b/methods/testPull.js @@ -1,3 +1,4 @@ +const { requestHook } = require('../src/hook-contract'); const { Core } = require('@orbito/api-lib'); const PrestashopApi = require('../src/PrestaApi'); const { importFromPSOrder } = require('../src/OrderImporter'); @@ -29,7 +30,7 @@ module.exports = async function(params, ctx) { const errors = []; for (const order of orders) { const uniqueId = order.reference + ':' + order.id; - const searchResult = await Core.callModule( 'core/orders', 'search', { + const searchResult = await requestHook(Core, 'orders.search', { // własny kod modułu bierzemy z core (po rejestracji), nie z hardcode'u source: { moduleCode: Core.getModuleInfo().code, uniqueId } }); diff --git a/module.json b/module.json index 5e302c3..18e90fc 100644 --- a/module.json +++ b/module.json @@ -1,9 +1,5 @@ { - "name": "core/prestashop", - "version": "1.1.15", - "singleton": false, - "dependsOn": [ - "core/orders", - "core/products" - ] + "name": "core/prestashop", + "version": "1.2.0", + "singleton": false } diff --git a/package-lock.json b/package-lock.json index 7a27df0..785bbc4 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,28 +1,29 @@ { "name": "core.prestashop", - "version": "1.1.15", + "version": "1.2.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "core.prestashop", - "version": "1.1.15", + "version": "1.2.0", "license": "ISC", "dependencies": { - "@orbito/api-lib": "^3.3.3", + "@orbito/api-lib": "^3.10.0", "cron": "^4.4.0", "dotenv": "^17.2.3", "ejs": "^4.0.1", "js2xmlparser": "^5.0.0", "nanoid": "^5.1.6", "node-cache": "^5.1.2", - "uuid": "^11.1.0" + "uuid": "^11.1.0", + "fastest-validator": "^1.19.1" } }, "node_modules/@orbito/api-lib": { - "version": "3.3.3", - "resolved": "https://git.kozminski.net.pl/api/packages/orbito/npm/%40orbito%2Fapi-lib/-/3.3.3/api-lib-3.3.3.tgz", - "integrity": "sha512-+YyN/FdLEoCCkKVcHzHopgB7/sFSXEn61l+Y+Jz/Ccb2oXe9EZ5MZ8+M1fWjA03sVzUO7HqDEWUOatgDdyikoQ==", + "version": "3.10.0", + "resolved": "https://git.kozminski.net.pl/api/packages/orbito/npm/%40orbito%2Fapi-lib/-/3.10.0/api-lib-3.10.0.tgz", + "integrity": "sha512-isA8AhISPW8NRRKuco4MByqnevpiiGZRcHP/CBuYg+XSUgbpF1gwqdThi3PzzT1pAtNhZVhQH2ti2RvLJjN3Yg==", "license": "ISC", "dependencies": { "bson": "^6.10.4", diff --git a/package.json b/package.json index 2b767d6..829a260 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "core.prestashop", - "version": "1.1.15", + "version": "1.2.0", "description": "Integracja zamówień i płatności PrestaShop", "main": "index.js", "scripts": { @@ -10,13 +10,14 @@ "author": "", "license": "ISC", "dependencies": { - "@orbito/api-lib": "^3.3.3", + "@orbito/api-lib": "^3.10.0", "cron": "^4.4.0", "dotenv": "^17.2.3", "ejs": "^4.0.1", "js2xmlparser": "^5.0.0", "nanoid": "^5.1.6", "node-cache": "^5.1.2", - "uuid": "^11.1.0" + "uuid": "^11.1.0", + "fastest-validator": "^1.19.1" } } diff --git a/src/OrderImporter.js b/src/OrderImporter.js index 5f296ee..55e6366 100644 --- a/src/OrderImporter.js +++ b/src/OrderImporter.js @@ -1,3 +1,4 @@ +const { requestHook } = require('./hook-contract'); const { Log, Core } = require("@orbito/api-lib"); const PsOrder = require('./models/PsOrder'); const { normalizeStatusId } = require('./status-mapper'); @@ -69,7 +70,7 @@ async function resolvePackItemTax(api, productId, combinationId, context) { } async function resolveImportStatusId(config) { - const statusResult = await Core.callModule( 'core/orders', 'status.search', {}); + const statusResult = await requestHook(Core, 'orders.status.search', {}); const statuses = statusResult?.results ?? []; const byId = new Map(); @@ -133,7 +134,7 @@ async function importFromPSOrder(orderId, api, config) { qty: parseFloat(product.product_quantity) }; // Jednorazowa migracja starej tożsamości produktu odbywa się już po - // stronie core/products przez synchroniczny kontrakt core/orders. + // stronie katalogu produktów przez synchroniczny kontrakt zamówieniach. p.previousSourceId = productId; const psProduct = await api.getProduct(productId); @@ -338,7 +339,7 @@ async function importFromPSOrder(orderId, api, config) { const customerNotes = await api.getCustomerNotes(order.id, order.id_cart, order.gift_message); - const coreOrder = await Core.callModule( 'core/orders', 'create', { + const coreOrder = await requestHook(Core, 'orders.create', { statusId: statusId, customer: { name: customer.firstname + " " + customer.lastname, @@ -391,7 +392,7 @@ async function importFromPSOrder(orderId, api, config) { }); if (!coreOrder?._id) { - throw new Error(`core/orders create did not return an id for PrestaShop order ${order.id}`); + throw new Error(`Order creation did not return an id for PrestaShop order ${order.id}`); } const now = new Date(); diff --git a/src/automation-jobs.js b/src/automation-jobs.js index 0ab30bd..7a5e35f 100644 --- a/src/automation-jobs.js +++ b/src/automation-jobs.js @@ -1,3 +1,4 @@ +const { requestHook } = require('./hook-contract'); const DEFAULT_PAGE_SIZE = 50; const DEFAULT_MAX_PAGES = 10; const { parsePrestashopDate } = require('./prestashop-date'); @@ -120,7 +121,7 @@ async function importOrdersForShop(config, api, dependencies = {}) { for (const order of orders) { if (!isLockValid()) throw new Error('PrestaShop orders lock was lost'); try { - const result = await Core.callModule('core/orders', 'search', { + const result = await requestHook(Core, 'orders.search', { source: { moduleCode: 'core/prestashop', uniqueId: orderUniqueId(order) }, }); const existingOrder = asOrders(result)[0]; @@ -171,7 +172,7 @@ function duePaymentsQuery(config, since, until, nowDate) { async function processPaymentMapping(mapping, config, api, dependencies) { const { Core, PsOrder, nowDate, nextCheckMs, retryCheckMs, Log = console } = dependencies; try { - const orderResult = await Core.callModule('core/orders', 'search', { _id: mapping.orbitoOrderId }); + const orderResult = await requestHook(Core, 'orders.search', { _id: mapping.orbitoOrderId }); const order = asOrders(orderResult)[0]; if (!order) throw new Error(`Orbito order ${mapping.orbitoOrderId} not found`); @@ -195,7 +196,7 @@ async function processPaymentMapping(mapping, config, api, dependencies) { if (amount > 0) { const transactionId = paymentTransactionId(config, mapping.psOrderId, psPaid); - await Core.callModule('core/orders', 'payments.upsert', { + await requestHook(Core, 'orders.payments.upsert', { orderId: String(mapping.orbitoOrderId), payment: { amount, diff --git a/src/hook-contract.js b/src/hook-contract.js new file mode 100644 index 0000000..81df153 --- /dev/null +++ b/src/hook-contract.js @@ -0,0 +1,120 @@ +'use strict'; + +// Distributed with each module: no runtime dependency on another package. +const PROTOCOL = 'orbito.contract/1'; +const INSTANCE_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/; + +function failure(code, message, details = {}) { + return Object.assign(new Error(message || code), { code, ...details }); +} + +function envelopes(value) { + return (Array.isArray(value) ? value.flat(Infinity) : [value]) + .filter(item => item && item.protocol === PROTOCOL); +} + +async function resolveProvider(Core, contract, target = {}) { + const discovered = envelopes(await Core.execHook(`${contract}.providers`, { + targetInstanceId: target.instanceId, targetModuleCode: target.moduleCode, + })); + const candidates = discovered.filter(provider => + INSTANCE_ID.test(provider.instanceId || '') + && (!target.instanceId || provider.instanceId === target.instanceId) + && (!target.moduleCode || provider.moduleCode === target.moduleCode)); + // Never choose an arbitrary installation, even when both have the same code. + if (candidates.length !== 1) { + const code = candidates.length ? 'HOOK_PROVIDER_AMBIGUOUS' : 'HOOK_PROVIDER_UNAVAILABLE'; + throw failure(code, `${code}: ${contract}`, { outcomeUncertain: false, retryable: true }); + } + return candidates[0]; +} + +async function requestHook(Core, contract, params = {}, target = {}) { + const provider = await resolveProvider(Core, contract, target); + let results; + try { + results = envelopes(await Core.execHook(contract, { + protocol: PROTOCOL, targetInstanceId: provider.instanceId, params, + })).filter(result => result.instanceId === provider.instanceId); + } catch (error) { + throw failure('HOOK_RESULT_UNCERTAIN', error?.message, { outcomeUncertain: true, retryable: false }); + } + if (results.length !== 1 || typeof results[0].ok !== 'boolean') { + throw failure('HOOK_RESULT_UNCERTAIN', `Brak jednoznacznego wyniku: ${contract}`, { + outcomeUncertain: true, retryable: false, + }); + } + const result = results[0]; + if (!result.ok) { + const { message, ...details } = result.error || {}; + throw failure(details.code || 'HOOK_OPERATION_FAILED', message, details); + } + return result.data; +} + +function serializeError(error) { + const result = { code: String(error?.code || 'HOOK_OPERATION_FAILED'), message: String(error?.message || error) }; + for (const key of ['outcomeUncertain', 'retryable', 'partialSuccess', 'externalId', 'status']) { + if (error?.[key] !== undefined) result[key] = error[key]; + } + return result; +} + +function requestProvider(Core, domain, provider, operation, params = {}) { + if (!/^[A-Za-z][A-Za-z0-9_.]*$/.test(operation || '')) { + return Promise.reject(failure('INVALID_PROVIDER_OPERATION')); + } + return requestHook(Core, `${domain}.${operation}`, params, { + instanceId: provider?.instanceId, + // Historical records may only have a module code. Discovery still + // requires exactly one installation before executing their operation. + moduleCode: provider?.moduleCode, + }); +} + +function internalContext(context) { + // Hooks document caller provenance, not the RPC-only system flag. The + // platform authenticates this identity from the module connection. Map + // that internal transport to the existing RPC context, preserving any + // explicit permission restriction supplied by the platform. Public UI + // entry points still check their user's permissions before emitting a hook. + if (context?.system === false || !INSTANCE_ID.test(context?.caller?.instanceId || '') + || typeof context?.caller?.moduleCode !== 'string' || !context.caller.moduleCode.trim()) { + throw failure('INTERNAL_CALL_REQUIRED', 'INTERNAL_CALL_REQUIRED', { outcomeUncertain: false }); + } + return { ...context, system: true, permissions: Array.isArray(context.permissions) ? context.permissions : ['*'] }; +} + +function registerContract(Core, contract, definition) { + const handler = typeof definition === 'function' ? definition : definition.handler; + if (typeof handler !== 'function') throw new TypeError(`Invalid contract handler: ${contract}`); + const validate = definition.params + ? new (require('fastest-validator'))({ useNewCustomCheckerFunction: true }).compile(definition.params) + : () => true; + Core.registerHook(`${contract}.providers`, function() { + return { protocol: PROTOCOL, instanceId: Core.getInstanceId(), moduleCode: Core.getModuleInfo().code }; + }); + Core.registerHook(contract, async function(request) { + const instanceId = Core.getInstanceId(); + // Ignore another installation's command before validation or side effects. + if (request?.protocol !== PROTOCOL || request.targetInstanceId !== instanceId) return null; + try { + const ctx = internalContext(this); + const params = request.params; + if (!params || typeof params !== 'object' || Array.isArray(params)) { + throw failure('INVALID_CONTRACT_PARAMS'); + } + for (const key of ['caller', 'permissions', 'userId', 'system']) { + if (Object.prototype.hasOwnProperty.call(params, key)) throw failure('CONTRACT_CONTEXT_OVERRIDE_FORBIDDEN'); + } + const valid = await validate(params); + if (valid !== true) throw failure('INVALID_CONTRACT_PARAMS', JSON.stringify(valid), { outcomeUncertain: false }); + return { protocol: PROTOCOL, instanceId, ok: true, data: await handler.call(ctx, params, ctx) }; + } catch (error) { + // SDK swallows thrown hook errors. Return them as protocol data. + return { protocol: PROTOCOL, instanceId, ok: false, error: serializeError(error) }; + } + }); +} + +module.exports = { PROTOCOL, requestHook, requestProvider, resolveProvider, registerContract, internalContext }; diff --git a/src/orders-api.js b/src/orders-api.js index 5dbaeb5..b97ffc3 100644 --- a/src/orders-api.js +++ b/src/orders-api.js @@ -1,9 +1,10 @@ +const { requestHook } = require('./hook-contract'); const { Core } = require('@orbito/api-lib'); // Helper proxy do modułu zamówień. Widoki PrestaShop (orders.search, // status.get_with_counts) nie trzymają własnych zamówień — odpytują core/orders. -const ORDERS_MODULE_ID = 'core/orders'; + // Własny kod modułu znamy dopiero po rejestracji w core, więc czytamy go leniwie // (moduł jest ładowany zanim połączenie zostanie nawiązane). @@ -20,7 +21,7 @@ function getModuleCodes() { } async function callOrdersModule(method, params) { - return Core.callModule(ORDERS_MODULE_ID, method, params); + return requestHook(Core, `orders.${method}`, params); } function normalizeSearchResult(raw) { @@ -157,7 +158,6 @@ async function getOrderStatuses() { module.exports = { getModuleCode, getModuleCodes, - ORDERS_MODULE_ID, callOrdersModule, normalizeSearchResult, buildSearchParams, diff --git a/src/register-config.js b/src/register-config.js index b9876f5..d565f05 100644 --- a/src/register-config.js +++ b/src/register-config.js @@ -8,7 +8,7 @@ const { ensureShopIcon } = require('./shop-icon'); const { DEFAULT_SHOP_TIME_ZONE, validateTimeZone } = require('./prestashop-date'); const ORBITO_STATUS_OPTIONS = { - module: 'core/orders', + module: 'core/prestashop', method: 'status.search', params: {}, responsePath: 'results', diff --git a/src/register-contracts.js b/src/register-contracts.js new file mode 100644 index 0000000..d07a80f --- /dev/null +++ b/src/register-contracts.js @@ -0,0 +1,8 @@ +const { Core } = require('@orbito/api-lib'); +const { registerContract } = require('./hook-contract'); + +function registerContracts() { + registerContract(Core, 'sources.product.get_metadata', require('../methods/product/get_metadata')); +} + +module.exports = { registerContracts }; diff --git a/src/shop-icon.js b/src/shop-icon.js index ace133b..14306f9 100644 --- a/src/shop-icon.js +++ b/src/shop-icon.js @@ -1,3 +1,4 @@ +const { requestHook } = require('./hook-contract'); const { Config, Core, Log } = require('@orbito/api-lib'); const CACHE_KEY = 'runtime.shopIcon'; @@ -176,7 +177,7 @@ async function downloadShopIcon(shopPageUrl) { async function registerSourceProfile(cache, shopName) { try { - await Core.callModule('core/orders', 'source.register', { + await requestHook(Core, 'orders.source.register', { name: String(shopName || '').trim() || new URL(cache.shopUrl).hostname, iconDataUrl: cache.dataUrl || '', iconSourceUrl: cache.sourceUrl || '', diff --git a/src/status-sync.js b/src/status-sync.js index f8ebdd5..8d25672 100644 --- a/src/status-sync.js +++ b/src/status-sync.js @@ -1,3 +1,4 @@ +const { requestHook } = require('./hook-contract'); const { resolvePsStateId } = require('./status-mapper'); const STATUS_SYNC_LOCK_TTL_SECONDS = 120; @@ -46,7 +47,7 @@ async function syncOrderStatusToPrestashop(payload, dependencies) { // Hook trafia do każdej instancji modułu w firmie. Odfiltrowujemy obce // sklepy przed lockiem, aby nie blokowały instancji będącej właścicielem. const [initialOrderResult, storedMapping] = await Promise.all([ - Core.callModule('core/orders', 'search', { _id: orderId }), + requestHook(Core, 'orders.search', { _id: orderId }), PsOrder.findOne({ orbitoOrderId: orderId }), ]); const initialOrder = asOrders(initialOrderResult)[0]; @@ -64,7 +65,7 @@ async function syncOrderStatusToPrestashop(payload, dependencies) { try { const [orderResult, config] = await Promise.all([ - Core.callModule('core/orders', 'search', { _id: orderId }), + requestHook(Core, 'orders.search', { _id: orderId }), loadConfig(), ]); const order = asOrders(orderResult)[0]; diff --git a/test/automation-jobs.test.js b/test/automation-jobs.test.js index f6c2ece..e13f43a 100644 --- a/test/automation-jobs.test.js +++ b/test/automation-jobs.test.js @@ -1,3 +1,4 @@ +const { withHookFixtures } = require('./helpers/hook-fixtures'); const test = require('node:test'); const assert = require('node:assert/strict'); @@ -36,7 +37,7 @@ test('a failed order leaves a retryable cursor gap while later orders are still 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: [] }) }, + Core: withHookFixtures({ callModule: async () => ({ data: [] }) }), PsOrder: {}, importFromPSOrder: async id => { imported.push(id); @@ -77,7 +78,7 @@ test('existing Orbito order repairs a missing mapping before advancing the curso }; await importOrdersForShop(config, api, { - Core: { callModule: async () => ({ data: [{ _id: 'orbito-21', summary: { paid: 25 } }] }) }, + 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), @@ -100,11 +101,11 @@ test('payment sync appends only the cumulative delta with a deterministic transa 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) => { + 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, @@ -130,7 +131,7 @@ test('import waits for the 30-second stability window using shop time without gu { id: 13, reference: 'R13', date_add: '2026-09-25 15:00:00' }, ] }), }, { - Core: { callModule: async () => ({ data: [] }) }, + 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'), @@ -148,10 +149,10 @@ test('legacy mapping establishes a conservative baseline instead of duplicating await processPaymentMapping({ _id: 'map-2', psOrderId: 45, orbitoOrderId: 'order-2' }, { _id: 'default' }, { getOrder: async () => ({ total_paid_real: '50.00' }), }, { - Core: { callModule: async (_module, method) => { + 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, }); @@ -165,11 +166,11 @@ test('a mapping write failure retries the same payment transaction id safely', a let failMappingWrite = true; const mapping = { _id: 'map-3', psOrderId: 46, orbitoOrderId: 'order-3', paymentTotalSynced: 10 }; const dependencies = { - Core: { callModule: async (_module, method, params) => { + 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; @@ -204,9 +205,9 @@ test('payment scheduler drains multiple pages and includes orders older than fiv }, update: async () => {}, }; - const Core = { callModule: async (_module, method) => method === 'search' + const Core = withHookFixtures({ callModule: async (_module, method) => method === 'search' ? { data: [{ summary: { paid: 0, gross: 10 } }] } - : { success: true } }; + : { success: true } }); const result = await syncPaymentsForShop( { _id: 'default' }, diff --git a/test/helpers/hook-fixtures.js b/test/helpers/hook-fixtures.js new file mode 100644 index 0000000..b4628a1 --- /dev/null +++ b/test/helpers/hook-fixtures.js @@ -0,0 +1,50 @@ +'use strict'; + +// Test-only bus: keep existing business fixtures while exercising the real +// request envelope, discovery and error propagation in src/hook-contract. +// Transport behavior and actual provider registration are tested separately. +function withHookFixtures(Core) { + if (Core.__hookFixtures) return Core; + Object.defineProperty(Core, '__hookFixtures', { value: true }); + const previousHook = Core.execHook?.bind(Core); + const identities = new Map(); + Core.getInstanceId ||= () => 'fixture-instance'; + Core.getModuleInfo ||= () => ({ code: 'test/module' }); + Core.execHook = async function(name, request) { + const contract = name.replace(/\.providers$/, ''); + const match = /^(orders|products|shipping|invoicing|printing|sources)\.(.+)$/.exec(contract); + if (!match) return previousHook ? previousHook(name, request) : []; + if (name.endsWith('.providers')) { + const moduleCode = request?.targetModuleCode || `core/${match[1]}`; + const instanceId = request?.targetInstanceId || `fixture:${moduleCode.replace('/', ':')}`; + identities.set(`${contract}:${instanceId}`, moduleCode); + return [{ protocol: 'orbito.contract/1', moduleCode, instanceId }]; + } + if (request?.protocol !== 'orbito.contract/1') return previousHook ? previousHook(name, request) : []; + const instanceId = request.targetInstanceId; + const moduleCode = identities.get(`${contract}:${instanceId}`); + try { + let data; + if (contract === 'orders.references') { + const page = `details/${request.params.orderId}`; + data = { + link: { module: 'core/orders', instanceId, path: page }, + relation: { module: 'core/orders', object: 'order', id: request.params.orderId }, + navigation: { action: 'navigate', module: 'core/orders', instanceId, page }, + approveFinancialData: { action: 'callMethod', module: 'core/orders', instanceId, method: 'import.approveFinancialData', params: { orderId: request.params.orderId, confirmed: true } }, + }; + } else if (/^(shipping\.carrier|printing\.provider)\./.test(contract)) { + data = await Core.callInstanceMethod(instanceId, match[2].replace(/^(carrier|provider)\./, ''), request.params); + } else { + data = await Core.callModule(moduleCode, match[2].replace(/^issuer\./, ''), request.params); + } + return [{ protocol: 'orbito.contract/1', instanceId, ok: true, data }]; + } catch (error) { + return [{ protocol: 'orbito.contract/1', instanceId, ok: false, + error: { message: error.message, code: error.code, outcomeUncertain: error.outcomeUncertain, retryable: error.retryable } }]; + } + }; + return Core; +} + +module.exports = { withHookFixtures }; diff --git a/test/job-runtime.test.js b/test/job-runtime.test.js index cc97286..1398f49 100644 --- a/test/job-runtime.test.js +++ b/test/job-runtime.test.js @@ -1,14 +1,15 @@ +const { withHookFixtures } = require('./helpers/hook-fixtures'); 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 = { + const Core = withHookFixtures({ 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', 5, async valid => valid() && 7), 7); @@ -34,11 +35,11 @@ test('lock TTL is forwarded to Core in seconds, without conversion', async t => t.mock.timers.enable({ apis: ['setInterval'] }); const getLockCalls = []; const extendCalls = []; - const Core = { + const Core = withHookFixtures({ getLock: async (name, ttl) => { getLockCalls.push([name, ttl]); return 'lock-1'; }, extendLockTime: async (id, ttl) => { extendCalls.push([id, ttl]); return true; }, releaseLock: async () => true, - }; + }); const runtime = createJobRuntime(Core, { error() {}, warn() {} }); let finish; diff --git a/test/order-importer-customer-message.test.js b/test/order-importer-customer-message.test.js index f4e96b9..7259842 100644 --- a/test/order-importer-customer-message.test.js +++ b/test/order-importer-customer-message.test.js @@ -1,3 +1,4 @@ +const { withHookFixtures } = require('./helpers/hook-fixtures'); const test = require('node:test'); const assert = require('node:assert/strict'); const Module = require('node:module'); @@ -21,7 +22,7 @@ function loadImporter(Core, PsOrder) { test('imports only public PrestaShop customer messages as customer_message notes', async () => { let createPayload; - const Core = { + const Core = withHookFixtures({ getModuleInfo: () => ({ code: 'core/prestashop' }), callModule: async (module, method, params) => { if (module === 'core/orders' && method === 'status.search') { @@ -34,7 +35,7 @@ test('imports only public PrestaShop customer messages as customer_message notes } throw new Error(`Unexpected core call: ${module}.${method}`); }, - }; + }); const { importFromPSOrder } = loadImporter(Core, { findOne: async () => null, update: async () => {} }); const order = { id: '1', id_cart: '15', reference: 'PS-1', current_state: '1', id_customer: '5', id_address_delivery: '6', diff --git a/test/order-importer-dates.test.js b/test/order-importer-dates.test.js index 1e23158..1541d08 100644 --- a/test/order-importer-dates.test.js +++ b/test/order-importer-dates.test.js @@ -1,3 +1,4 @@ +const { withHookFixtures } = require('./helpers/hook-fixtures'); const test = require('node:test'); const assert = require('node:assert/strict'); const Module = require('node:module'); @@ -8,7 +9,7 @@ test('order import sends the same corrected date to orders, initial payments and Module._load = function(request, parent, isMain) { if (request === '@orbito/api-lib') return { Log: { debug() {}, info() {}, warn() {} }, - Core: { + Core: withHookFixtures({ getModuleInfo: () => ({ code: 'core/prestashop' }), callModule: async (module, method, params) => { assert.equal(module, 'core/orders'); @@ -17,7 +18,7 @@ test('order import sends the same corrected date to orders, initial payments and created.push(params); return { _id: 'new-order' }; }, - }, + }), }; if (request === './models/PsOrder') return { findOne: async () => null, diff --git a/test/order-importer-metadata.test.js b/test/order-importer-metadata.test.js index 3abc9a3..f9d6ca6 100644 --- a/test/order-importer-metadata.test.js +++ b/test/order-importer-metadata.test.js @@ -1,3 +1,4 @@ +const { withHookFixtures } = require('./helpers/hook-fixtures'); const test = require('node:test'); const assert = require('node:assert/strict'); const Module = require('node:module'); @@ -22,7 +23,7 @@ function loadImporter(Core, PsOrder) { test('order import passes verified metadata and pack facts only through core/orders', async () => { const upserts = []; let createdOrder = null; - const Core = { + const Core = withHookFixtures({ getModuleInfo: () => ({ code: 'core/prestashop' }), callModule: async (module, method, params) => { if (module === 'core/orders' && method === 'status.search') return { results: [{ _id: '000000000000000000000001', positionInGroup: 1 }] }; @@ -36,7 +37,7 @@ test('order import passes verified metadata and pack facts only through core/ord } throw new Error(`Unexpected core call: ${module}.${method}`); }, - }; + }); const PsOrder = { findOne: async () => null, update: async () => {} }; const { importFromPSOrder } = loadImporter(Core, PsOrder); const order = { diff --git a/test/presta-api.test.js b/test/presta-api.test.js index 081c038..49fb21f 100644 --- a/test/presta-api.test.js +++ b/test/presta-api.test.js @@ -1,7 +1,8 @@ +const { withHookFixtures } = require('./helpers/hook-fixtures'); const test = require('node:test'); const assert = require('node:assert/strict'); const Module = require('node:module'); -const Core = { fetch: null }; +const Core = withHookFixtures({ fetch: null }); const originalLoad = Module._load; Module._load = function(request, parent, isMain) { if (request === '@orbito/api-lib') return { Core, Log: { warn() {} } }; diff --git a/test/shop-icon.test.js b/test/shop-icon.test.js index 39080be..e54bf76 100644 --- a/test/shop-icon.test.js +++ b/test/shop-icon.test.js @@ -1,3 +1,4 @@ +const { withHookFixtures } = require('./helpers/hook-fixtures'); const assert = require('node:assert/strict'); const Module = require('node:module'); const path = require('node:path'); @@ -33,7 +34,7 @@ test('discovers, downloads and persists a favicon once before registering the so get: async (key, fallback) => config.has(key) ? config.get(key) : fallback, set: async (key, value) => config.set(key, value), }, - Core: { + Core: withHookFixtures({ fetch: async url => { calls.push(url); if (url === 'https://shop.test/b2b/') { @@ -45,7 +46,7 @@ test('discovers, downloads and persists a favicon once before registering the so throw new Error(`Unexpected URL: ${url}`); }, callModule: async (...args) => registered.push(args), - }, + }), Log: { warn() {} }, }); @@ -89,10 +90,10 @@ test('a failed refresh retains the last icon for the same shop', async () => { get: async () => stored, set: async (key, value) => { stored = value; }, }, - Core: { + Core: withHookFixtures({ fetch: async () => ({ status: 503, data: Buffer.alloc(0), headers: {} }), callModule: async () => ({}), - }, + }), Log: { warn() {} }, }); @@ -108,7 +109,7 @@ test('a failed refresh retains the last icon for the same shop', async () => { }); test('favicon discovery rejects cross-host candidates and recognizes common binary formats', () => { - const shopIcon = loadShopIcon({ Config: {}, Core: {}, Log: { warn() {} } }); + const shopIcon = loadShopIcon({ Config: {}, Core: withHookFixtures({}), Log: { warn() {} } }); const candidates = shopIcon.faviconCandidates( '', 'https://shop.test/catalog/' diff --git a/test/status-sync.test.js b/test/status-sync.test.js index 40c0eed..843149a 100644 --- a/test/status-sync.test.js +++ b/test/status-sync.test.js @@ -1,3 +1,4 @@ +const { withHookFixtures } = require('./helpers/hook-fixtures'); const test = require('node:test'); const assert = require('node:assert/strict'); @@ -13,7 +14,7 @@ const CURRENT_STATUS = '507f191e810c19729de860e3'; function dependencies(overrides = {}) { const calls = { setOrderState: [], released: [], locks: [] }; - const Core = { + const Core = withHookFixtures({ getLock: async (name, ttl) => { calls.locks.push([name, ttl]); return 'status-lock'; @@ -31,7 +32,7 @@ function dependencies(overrides = {}) { }, }] }), registerHook: async () => true, - }; + }); const deps = { Core, Log: { info() {}, warn() {}, error() {} },