Use hook-backed outbound status mapping

This commit is contained in:
fatequod
2026-09-30 11:49:04 +02:00
parent 599a7b9863
commit 1f79463f51
9 changed files with 392 additions and 169 deletions
+1
View File
@@ -32,6 +32,7 @@ test('saving a valid shop connection refreshes the persisted source icon', async
if (request === './status-mapper') return { extractPsStateName: value => value };
if (request === './module-config') {
return {
initializeOutboundMapping: async () => {},
setPsStates: async value => { savedStates = value; },
loadPsStates: async () => [],
};
+161 -51
View File
@@ -5,86 +5,157 @@ const test = require('node:test');
const registerConfigPath = path.resolve(__dirname, '../src/register-config.js');
function loadConfigModule({ states, cachedStates = [] }) {
const { registerContract } = require('../src/hook-contract');
const { readStatusMapping, resolvePsStateId } = require('../src/status-mapper');
const STATUS_A = '507f191e810c19729de860ea';
const STATUS_B = '507f191e810c19729de860eb';
function loadConfigModule({ states = [], cachedStates = [], saved = {}, providers = 1, failPs = false, failOrbito = false } = {}) {
let blocks;
let savedStates;
const store = {
'connection.apiUrl': 'https://shop.test',
'connection.apiKey': 'secret',
'connection.versionCode': '8',
'runtime.psStates': cachedStates,
...saved,
};
const hooks = new Map();
const requests = [];
for (let i = 0; i < providers; i++) {
registerContract({
getInstanceId: () => `order-provider-${i}`,
getModuleInfo: () => ({ code: 'alternative/orders' }),
registerHook: (name, handler) => hooks.set(name, [...(hooks.get(name) || []), handler]),
}, 'orders.status.search', async () => {
if (failOrbito) throw new Error('Status service offline');
return { results: [{ _id: STATUS_A, name: 'Do nadania' }, { _id: STATUS_B, name: 'Wysłane' }] };
});
}
const Config = {
PropertyType: { INFO: 'info', STRING: 'string' },
DisplayFormat: { URL: 'url', SECRET: 'secret' },
registerConfigBlocks: async value => { blocks = value; },
get: async (key, fallback) => Object.hasOwn(store, key) ? store[key] : fallback,
getAll: async () => ({ ...store }),
set: async (key, value) => { store[key] = value; },
};
const originalLoad = Module._load;
Module._load = function(request, parent, isMain) {
if (request === '@orbito/api-lib') {
return {
Config: {
PropertyType: { INFO: 'info', STRING: 'string' },
DisplayFormat: { URL: 'url', SECRET: 'secret' },
registerConfigBlocks: async value => { blocks = value; },
get: async (key, fallback) => ({
'connection.apiUrl': 'https://shop.test',
'connection.apiKey': 'secret',
'connection.versionCode': '8',
}[key] ?? fallback),
},
Log: { info() {}, warn() {} },
};
}
if (request === './PrestaApi') {
return class PrestashopApi {
async getStatuses() { return states; }
};
}
if (request === '@orbito/api-lib') return {
Config,
Core: { execHook: async (name, request) => {
requests.push({ name, request });
return Promise.all((hooks.get(name) || []).map(handler => handler.call({
caller: { moduleCode: 'core/prestashop', instanceId: 'shop-instance' },
}, request)));
} },
Log: { info() {}, warn() {} },
};
if (request === './PrestaApi') return class PrestashopApi {
async getStatuses() {
if (failPs) throw new Error('Shop offline');
return states;
}
};
if (request === './utils') return { isLegacyApi: () => false };
if (request === './module-config') {
return {
setPsStates: async value => { savedStates = value; },
loadPsStates: async () => cachedStates,
};
}
if (request === './shop-icon') return { ensureShopIcon: async () => {} };
return originalLoad.call(this, request, parent, isMain);
};
delete require.cache[registerConfigPath];
let loaded;
for (const file of ['../src/register-config', '../src/status-config', '../src/module-config']) {
delete require.cache[require.resolve(file)];
}
let loaded, loadConfig, initializeOutboundMapping;
try {
loaded = require(registerConfigPath);
} finally {
Module._load = originalLoad;
}
({ loadConfig, initializeOutboundMapping } = require('../src/module-config'));
} finally { Module._load = originalLoad; }
return {
...loaded,
...loaded, store, requests, loadConfig, initializeOutboundMapping, Config,
register: async () => {
await loaded.registerPrestashopConfigBlocks();
return blocks;
},
getSavedStates: () => savedStates,
};
}
test('opening the mapping block fetches and persists current PrestaShop state names', async () => {
test('mapping rows are Orbito statuses, with fresh local PrestaShop options obtained through the selected hook provider', async () => {
const module = loadConfigModule({
cachedStates: [{ id: 2, name: 'Stara nazwa', color: '#000000' }],
states: [{ id: '2', name: 'Nowa nazwa', color: '#00ff00', deleted: '0' }],
saved: { 'mapping.state_2': STATUS_A },
});
const blocks = await module.register();
const schema = await blocks.mapping.schema();
assert.equal(schema.state_2.name.pl, 'Nowa nazwa (PS #2)');
assert.deepEqual(module.getSavedStates(), [{ id: 2, name: 'Nowa nazwa', color: '#00ff00' }]);
assert.equal(schema[`orbito_${STATUS_A}`].name.pl, 'Do nadania');
assert.equal(module.store[`mapping.orbito_${STATUS_A}`], '2');
assert.deepEqual(schema[`orbito_${STATUS_A}`].options, { values: [{ id: '2', label: 'Nowa nazwa (PS #2)' }] });
assert.equal(schema.state_2, undefined);
assert.deepEqual(module.store['runtime.psStates'], [{ id: 2, name: 'Nowa nazwa', color: '#00ff00' }]);
assert.equal(module.requests[1].request.targetInstanceId, 'order-provider-0');
assert.equal(module.store['mapping.state_2'], STATUS_A);
assert.equal(module.store[`mapping.orbito_${STATUS_A}`], '2');
});
test('mapping validation prevents two PrestaShop states from sharing one Orbito status', async () => {
const module = loadConfigModule({ states: [] });
const statusId = '507f191e810c19729de860ea';
test('two Orbito statuses can be saved and loaded with the same PrestaShop target without changing legacy data', async () => {
const module = loadConfigModule({ saved: { 'mapping.state_2': STATUS_A } });
const params = { [`orbito_${STATUS_A}`]: '2', [`orbito_${STATUS_B}`]: '2' };
const errors = [];
module.validateOutboundMapping(params, { addError: (...args) => errors.push(args) });
assert.deepEqual(errors, []);
for (const [field, value] of Object.entries(params)) module.store[`mapping.${field}`] = value;
const config = await module.loadConfig();
assert.equal(resolvePsStateId(STATUS_A, config.statusMapping), 2);
assert.equal(resolvePsStateId(STATUS_B, config.statusMapping), 2);
assert.equal(module.store['mapping.state_2'], STATUS_A);
});
module.validateOutboundMapping({
state_2: statusId,
state_3: statusId,
state_4: '507f191e810c19729de860eb',
}, {
addError: (field, message) => errors.push({ field, message }),
test('missing shop statuses and missing Orbito statuses retain their assignments and visible IDs', async () => {
const missingId = '507f191e810c19729de860ec';
const module = loadConfigModule({ saved: { 'mapping.state_99': missingId } });
const schema = await (await module.register()).mapping.schema();
assert.match(schema[`orbito_${missingId}`].name.pl, new RegExp(missingId));
assert.equal(module.store[`mapping.orbito_${missingId}`], '99');
assert.ok(schema[`orbito_${missingId}`].options.values.some(option => option.id === '99'));
assert.equal(resolvePsStateId(missingId, (await module.loadConfig()).statusMapping), 99);
});
for (const options of [{ providers: 0 }, { providers: 2 }, { failOrbito: true }]) {
test(`unavailable or ambiguous status provider is visible and preserves mapping: ${JSON.stringify(options)}`, async () => {
const module = loadConfigModule({ ...options, saved: { 'mapping.state_2': STATUS_A, 'import.orderStatus': STATUS_A } });
const blocks = await module.register();
const schema = await blocks.mapping.schema();
assert.match(schema.statusWarning.name.pl, /Nie udało się pobrać/);
assert.equal(module.store[`mapping.orbito_${STATUS_A}`], '2');
if (options.providers !== undefined) assert.ok(module.requests.every(request => request.name.endsWith('.providers')));
const importSchema = await blocks.import.schema();
assert.match(importSchema.statusWarning.name.pl, /Nie udało się pobrać/);
assert.equal(importSchema.orderStatus.options.values[0].id, STATUS_A);
assert.equal(module.store['mapping.state_2'], STATUS_A);
});
}
assert.deepEqual(errors.map(error => error.field), ['state_2', 'state_3']);
test('a shop outage shows cached names and never clears the mapping', async () => {
const module = loadConfigModule({ failPs: true, cachedStates: [{ id: 2, name: 'Oczekujące' }], saved: { 'mapping.state_2': STATUS_A } });
const schema = await (await module.register()).mapping.schema();
assert.match(schema.refreshWarning.name.pl, /Shop offline/);
assert.equal(module.store[`mapping.orbito_${STATUS_A}`], '2');
assert.equal(schema[`orbito_${STATUS_A}`].options.values[0].label, 'Oczekujące (PS #2)');
});
test('legacy conflicts keep every target and require an explicit choice before save', async () => {
const module = loadConfigModule({ saved: { 'mapping.state_2': STATUS_A, 'mapping.state_3': STATUS_A } });
const schema = await (await module.register()).mapping.schema();
const field = `orbito_${STATUS_A}`;
assert.equal(module.store[`mapping.${field}`], 'legacy_conflict');
assert.match(schema[field].options.values[0].label, /#2, #3/);
const errors = [];
module.validateOutboundMapping({ [field]: module.store[`mapping.${field}`] }, { addError: (...args) => errors.push(args) });
assert.equal(errors[0][0], field);
assert.throws(() => resolvePsStateId(STATUS_A, readStatusMapping(module.store)), /kilku statusów/);
module.store[`mapping.${field}`] = '3';
assert.equal(resolvePsStateId(STATUS_A, (await module.loadConfig()).statusMapping), 3);
assert.equal(module.store['mapping.state_2'], STATUS_A);
assert.equal(module.store['mapping.state_3'], STATUS_A);
});
test('connection validates the shop time zone and defaults to Europe/Warsaw', async () => {
@@ -108,6 +179,7 @@ test('config loading applies Warsaw to existing installations and passes a saved
const originalLoad = Module._load;
Module._load = function(request, parent, isMain) {
if (request === '@orbito/api-lib') return { Config: {
getAll: async () => ({}),
get: async (key, fallback) => key === 'connection.timeZone' ? savedTimeZone ?? fallback : fallback,
} };
return originalLoad.call(this, request, parent, isMain);
@@ -123,3 +195,41 @@ test('config loading applies Warsaw to existing installations and passes a saved
savedTimeZone = ' Europe/London ';
assert.equal((await loadConfig()).timeZone, 'Europe/London');
});
test('additive migration resumes after a failed write, preserves empty overrides and is idempotent', async () => {
const module = loadConfigModule({ saved: { 'mapping.state_2': STATUS_A, 'mapping.state_7': STATUS_B } });
const originalSet = module.Config.set;
let writes = 0;
module.Config.set = async (key, value) => {
if (++writes === 2) throw new Error('Interrupted write');
return originalSet(key, value);
};
await assert.rejects(module.initializeOutboundMapping, /Interrupted write/);
assert.equal(module.store[`mapping.orbito_${STATUS_A}`], '2');
assert.equal(Object.hasOwn(module.store, `mapping.orbito_${STATUS_B}`), false);
module.store[`mapping.orbito_${STATUS_A}`] = '';
module.Config.set = originalSet;
await module.initializeOutboundMapping();
assert.equal(module.store[`mapping.orbito_${STATUS_A}`], '');
assert.equal(module.store[`mapping.orbito_${STATUS_B}`], '7');
const saved = structuredClone(module.store);
await module.initializeOutboundMapping();
assert.deepEqual(module.store, saved);
const schema = await (await module.register()).mapping.schema();
assert.equal(schema[`orbito_${STATUS_A}`].default, undefined);
assert.equal(resolvePsStateId(STATUS_A, (await module.loadConfig()).statusMapping), null);
});
test('separate shop instances keep their own target IDs and options', async () => {
const a = loadConfigModule({ states: [{ id: 2, name: 'Sklep A' }], saved: { 'mapping.state_2': STATUS_A } });
const blocksA = await a.register();
const b = loadConfigModule({ states: [{ id: 7, name: 'Sklep B' }], saved: { 'mapping.state_7': STATUS_A } });
const blocksB = await b.register();
const schemaA = await blocksA.mapping.schema();
const schemaB = await blocksB.mapping.schema();
assert.deepEqual(schemaA[`orbito_${STATUS_A}`].options.values, [{ id: '2', label: 'Sklep A (PS #2)' }]);
assert.deepEqual(schemaB[`orbito_${STATUS_A}`].options.values, [{ id: '7', label: 'Sklep B (PS #7)' }]);
assert.equal(a.store[`mapping.orbito_${STATUS_A}`], '2');
assert.equal(b.store[`mapping.orbito_${STATUS_A}`], '7');
});
+27 -1
View File
@@ -1,7 +1,7 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { resolvePsStateId } = require('../src/status-mapper');
const { resolvePsStateId, readStatusMapping } = require('../src/status-mapper');
const STATUS_A = '507f191e810c19729de860ea';
const STATUS_B = '507f191e810c19729de860eb';
@@ -22,3 +22,29 @@ test('rejects an ambiguous outbound status mapping', () => {
{ psStateId: 3, orbitoStatusId: STATUS_A },
]), /kilku statusów PrestaShop/);
});
test('an outbound override affects only its Orbito status and preserves all other legacy assignments', () => {
const config = { 'mapping.state_2': STATUS_A, 'mapping.state_7': STATUS_B, [`mapping.orbito_${STATUS_A}`]: '7' };
const mapping = readStatusMapping(config);
assert.equal(resolvePsStateId(STATUS_A, mapping), 7);
assert.equal(resolvePsStateId(STATUS_B, mapping), 7);
assert.equal(config['mapping.state_2'], STATUS_A);
});
test('clearing an outbound field never resurrects its legacy mapping', () => {
for (const empty of ['', null]) {
const mapping = readStatusMapping({
'mapping.state_2': STATUS_A,
'mapping.state_7': STATUS_B,
[`mapping.orbito_${STATUS_A}`]: empty,
});
assert.equal(resolvePsStateId(STATUS_A, mapping), null);
assert.equal(resolvePsStateId(STATUS_B, mapping), 7);
}
});
test('invalid saved outbound state fails safely instead of sending a truncated state ID', () => {
for (const value of ['2foo', '-2', '0', '2.5']) {
assert.throws(() => readStatusMapping({ [`mapping.orbito_${STATUS_A}`]: value }), /Niepoprawny status/);
}
});
+30
View File
@@ -68,6 +68,36 @@ test('syncs the current Orbito status to the mapped PrestaShop state', async ()
assert.equal(result.synced, true);
});
test('different Orbito statuses both synchronize to their shared PrestaShop state', async () => {
const { registerContract } = require('../src/hook-contract');
const { readStatusMapping } = require('../src/status-mapper');
const { deps, calls } = dependencies();
let statusId = OLD_STATUS;
const hooks = new Map();
registerContract({
getInstanceId: () => 'alternative-orders-instance',
getModuleInfo: () => ({ code: 'alternative/orders' }),
registerHook: (name, handler) => hooks.set(name, handler),
}, 'orders.search', async () => ({ data: [{
_id: ORDER_ID, statusId,
source: { moduleCode: 'core/prestashop', moduleId: deps.Core.getInstanceId(), sourceId: '21' },
}] }));
deps.Core.execHook = async (name, request) => [await hooks.get(name).call({
caller: { moduleCode: 'core/prestashop', instanceId: deps.Core.getInstanceId() },
}, request)];
deps.loadConfig = async () => ({
apiUrl: 'https://shop.test', apiKey: 'secret',
statusMapping: readStatusMapping({
[`mapping.orbito_${OLD_STATUS}`]: '7',
[`mapping.orbito_${CURRENT_STATUS}`]: '7',
}),
});
await syncOrderStatusToPrestashop({ orderId: ORDER_ID }, deps);
statusId = CURRENT_STATUS;
await syncOrderStatusToPrestashop({ orderId: ORDER_ID }, deps);
assert.deepEqual(calls.setOrderState, [[21, 7], [21, 7]]);
});
test('ignores status events for an order owned by another PrestaShop instance', async () => {
const { deps, calls } = dependencies();
deps.Core.callModule = async () => ({ data: [{