Release PrestaShop 1.2.0: use hook contracts

This commit is contained in:
fatequod
2026-09-30 08:26:55 +02:00
parent 6b5e03246e
commit 599a7b9863
25 changed files with 276 additions and 62 deletions
+12 -11
View File
@@ -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' },
+50
View File
@@ -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 };
+5 -4
View File
@@ -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;
+3 -2
View File
@@ -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',
+3 -2
View File
@@ -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,
+3 -2
View File
@@ -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 = {
+2 -1
View File
@@ -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() {} } };
+6 -5
View File
@@ -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(
'<link rel="icon" href="https://cdn.test/icon.png"><link rel="apple-touch-icon" href="/touch.png">',
'https://shop.test/catalog/'
+3 -2
View File
@@ -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() {} },