From 1f79463f5153741a7bbe23f7956c854d1e979970 Mon Sep 17 00:00:00 2001 From: fatequod Date: Wed, 30 Sep 2026 11:49:04 +0200 Subject: [PATCH] Use hook-backed outbound status mapping --- README.md | 16 +++ src/module-config.js | 36 +++-- src/register-config.js | 108 +------------- src/status-config.js | 95 +++++++++++++ src/status-mapper.js | 35 ++++- test/register-config-icon.test.js | 1 + test/register-config-status.test.js | 212 +++++++++++++++++++++------- test/status-mapper.test.js | 28 +++- test/status-sync.test.js | 30 ++++ 9 files changed, 392 insertions(+), 169 deletions(-) create mode 100644 src/status-config.js diff --git a/README.md b/README.md index 12a241c..0b0d833 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,22 @@ Zapisane mapowanie jest używane wyłącznie w kierunku Orbito → PrestaShop: - status niezmapowany nie jest wysyłany do sklepu; - jeden status Orbito może wskazywać tylko jeden status PrestaShop. +Formularz ma wiersz dla każdego statusu Orbito i listę statusów PrestaShop do +wyboru. Kilka statusów Orbito może wskazywać ten sam status PrestaShop. +Lista Orbito pochodzi z kontraktu `orders.status.search`; brak dostawcy, +niejednoznaczny dostawca lub błąd pobierania są widoczne w formularzu. + +Przed udostępnieniem formularza moduł uzupełnia nowe pola na podstawie starych +przypisań. Migracja jest addytywna: można ją wznowić po przerwaniu, a kolejne +uruchomienia nie nadpisują zapisanych wyborów ani celowo wyczyszczonych pól. +Stare klucze `mapping.state_` pozostają bez zmian. Nowe pola +`mapping.orbito_` mają pierwszeństwo tylko dla danego statusu Orbito; +dopóki pole nie zostało zapisane, synchronizacja odczytuje stare przypisanie. +Zapisanie pustego pola wyłącza wysyłkę, bez przywracania starego +przypisania. Odczyt obejmuje również statusy nieobecne już na listach — formularz +pokazuje ich zapisane ID. Konflikt starych przypisań nie wybiera celu automatycznie: +pokazuje wszystkie cele i wymaga wybrania jednego lub wyczyszczenia pola. + 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. diff --git a/src/module-config.js b/src/module-config.js index 3791d63..841c73f 100644 --- a/src/module-config.js +++ b/src/module-config.js @@ -1,5 +1,6 @@ const { Config } = require('@orbito/api-lib'); const { DEFAULT_SHOP_TIME_ZONE } = require('./prestashop-date'); +const { readStatusMapping, LEGACY_CONFLICT } = require('./status-mapper'); /** Stały identyfikator sklepu (jeden sklep na firmę) — używany w PsOrder.shopConfigId. */ const SHOP_ID = 'default'; @@ -13,20 +14,27 @@ async function loadPsStates() { return Array.isArray(states) ? states : []; } -async function loadStatusMapping(psStates) { - const states = Array.isArray(psStates) ? psStates : await loadPsStates(); - const statusMapping = []; +async function loadStatusMapping() { + return readStatusMapping(await Config.getAll()); +} - await Promise.all(states.map(async (state) => { - const id = parseInt(state.id ?? state.psStateId, 10); - if (Number.isNaN(id)) return; - const orbitoStatusId = await Config.get(`mapping.state_${id}`, ''); - if (orbitoStatusId) { - statusMapping.push({ psStateId: id, orbitoStatusId: String(orbitoStatusId) }); +// Additive, restart-safe migration before exposing the new form. The generic +// form renders saved values, not schema defaults. Never rewrite legacy keys or +// an existing outbound choice (including an explicitly cleared field). +async function initializeOutboundMapping() { + const config = await Config.getAll(); + const grouped = new Map(); + for (const entry of readStatusMapping(config)) { + const ids = grouped.get(entry.orbitoStatusId) || new Set(); + ids.add(String(entry.psStateId)); + grouped.set(entry.orbitoStatusId, ids); + } + for (const [id, targets] of grouped) { + const key = `mapping.orbito_${id}`; + if (!Object.hasOwn(config, key)) { + await Config.set(key, targets.size === 1 ? [...targets][0] : LEGACY_CONFLICT); } - })); - - return statusMapping.sort((a, b) => a.psStateId - b.psStateId); + } } // Shape kompatybilny z dotychczasowym użyciem (OrderImporter, CRON, PrestaApi). @@ -53,7 +61,7 @@ async function loadConfig() { loadPsStates() ]); - const statusMapping = await loadStatusMapping(psStates); + const statusMapping = await loadStatusMapping(); return { _id: SHOP_ID, @@ -89,6 +97,8 @@ module.exports = { loadConfig, loadEnabledConfigs, loadPsStates, + loadStatusMapping, + initializeOutboundMapping, setLastOrderId, setPsStates }; diff --git a/src/register-config.js b/src/register-config.js index d565f05..6aae5a9 100644 --- a/src/register-config.js +++ b/src/register-config.js @@ -2,20 +2,12 @@ const { Config, Log } = require('@orbito/api-lib'); const { PropertyType, DisplayFormat } = Config; const PrestashopApi = require('./PrestaApi'); const { isLegacyApi } = require('./utils'); -const { extractPsStateName, normalizeStatusId } = require('./status-mapper'); -const { setPsStates, loadPsStates } = require('./module-config'); +const { extractPsStateName } = require('./status-mapper'); +const { importStatusSchema, outboundMappingSchema, validateOutboundMapping } = require('./status-config'); +const { setPsStates, loadPsStates, initializeOutboundMapping } = require('./module-config'); const { ensureShopIcon } = require('./shop-icon'); const { DEFAULT_SHOP_TIME_ZONE, validateTimeZone } = require('./prestashop-date'); -const ORBITO_STATUS_OPTIONS = { - module: 'core/prestashop', - method: 'status.search', - params: {}, - responsePath: 'results', - idKey: '_id', - labelKey: 'name' -}; - async function fetchPsStates(apiUrl, apiKey, versionCode) { const api = new PrestashopApi(apiUrl, apiKey, isLegacyApi(versionCode)); const rawStates = await api.getStatuses(); @@ -60,31 +52,8 @@ async function refreshPsStatesForMapping() { } } -function validateOutboundMapping(params, raport) { - const assignments = Object.entries(params || {}) - .map(([field, value]) => ({ - field, - psStateId: /^state_(\d+)$/.exec(field)?.[1] || null, - orbitoStatusId: normalizeStatusId(value), - })) - .filter(entry => entry.psStateId && entry.orbitoStatusId); - - const fieldsByOrbitoStatus = new Map(); - for (const assignment of assignments) { - const fields = fieldsByOrbitoStatus.get(assignment.orbitoStatusId) || []; - fields.push(assignment.field); - fieldsByOrbitoStatus.set(assignment.orbitoStatusId, fields); - } - - for (const fields of fieldsByOrbitoStatus.values()) { - if (fields.length < 2) continue; - for (const field of fields) { - raport.addError(field, 'Jeden status Orbito może wskazywać tylko jeden status PrestaShop.'); - } - } -} - async function registerPrestashopConfigBlocks() { + await initializeOutboundMapping(); await Config.registerConfigBlocks({ connection: { title: { pl: 'Połączenie ze sklepem', en: 'Shop connection' }, @@ -184,78 +153,13 @@ async function registerPrestashopConfigBlocks() { import: { title: { pl: 'Import zamówień', en: 'Order import' }, scope: 'global', - schema: { - hint: { - type: PropertyType.INFO, - name: { - pl: 'Każde nowe zamówienie z PrestaShop otrzyma ten status. Status sklepu nigdy nie nadpisuje statusu w Orbito.', - en: 'Every new PrestaShop order receives this status. The shop state never overwrites the Orbito status.' - } - }, - orderStatus: { - type: PropertyType.STRING, - name: { pl: 'Domyślny status po imporcie', en: 'Default status after import' }, - options: ORBITO_STATUS_OPTIONS - } - } + schema: importStatusSchema, }, mapping: { title: { pl: 'Mapowanie statusów', en: 'Status mapping' }, scope: 'global', - schema: async () => { - const { states: psStates, refreshError } = await refreshPsStatesForMapping(); - - if (!psStates.length) { - return { - hint: { - type: PropertyType.INFO, - name: { - pl: refreshError - ? `Brak statusów PrestaShop. ${refreshError}` - : 'PrestaShop nie zwrócił żadnych aktywnych statusów.', - en: refreshError - ? `No PrestaShop states. ${refreshError}` - : 'PrestaShop returned no active order states.' - } - } - }; - } - - const schema = { - hint: { - type: PropertyType.INFO, - name: { - pl: 'Mapowanie steruje wyłącznie wysyłką Orbito → PrestaShop. Zmiana z PrestaShop nigdy nie nadpisuje statusu Orbito.', - en: 'Mapping controls Orbito → PrestaShop updates only. A PrestaShop change never overwrites the Orbito status.' - } - } - }; - - if (refreshError) { - schema.refreshWarning = { - type: PropertyType.INFO, - name: { - pl: `Nie udało się odświeżyć nazw statusów; pokazano ostatnio zapisane dane. ${refreshError}`, - en: `Could not refresh state names; showing the last saved data. ${refreshError}` - } - }; - } - - for (const state of psStates) { - const id = state.id; - schema[`state_${id}`] = { - type: PropertyType.STRING, - name: { - pl: `${state.name || `Status ${id}`} (PS #${id})`, - en: `${state.name || `State ${id}`} (PS #${id})` - }, - options: ORBITO_STATUS_OPTIONS - }; - } - - return schema; - }, + schema: () => outboundMappingSchema(refreshPsStatesForMapping), validate: validateOutboundMapping, } }); diff --git a/src/status-config.js b/src/status-config.js new file mode 100644 index 0000000..76e6809 --- /dev/null +++ b/src/status-config.js @@ -0,0 +1,95 @@ +const { Config, Core } = require('@orbito/api-lib'); +const { requestHook } = require('./hook-contract'); +const { normalizeStatusId, readStatusMapping, isPsStateId, LEGACY_CONFLICT } = require('./status-mapper'); + +function info(pl, en = pl) { + return { type: Config.PropertyType.INFO, name: { pl, en } }; +} + +async function loadOrbitoStatuses() { + try { + const response = await requestHook(Core, 'orders.status.search', {}); + if (!Array.isArray(response?.results)) throw new Error('Niepoprawna odpowiedź listy statusów.'); + return { statuses: response.results, error: null }; + } catch (error) { + return { statuses: [], error: `Nie udało się pobrać statusów Orbito. ${error.message}` }; + } +} + +async function importStatusSchema() { + const [{ statuses, error }, savedId] = await Promise.all([ + loadOrbitoStatuses(), Config.get('import.orderStatus', ''), + ]); + const values = statuses.map(status => ({ id: String(status._id), label: status.name })); + if (savedId && !values.some(value => value.id === String(savedId))) { + values.push({ id: String(savedId), label: `Zapisany status Orbito (${savedId}) — niedostępny na liście` }); + } + return { + hint: info( + 'Każde nowe zamówienie z PrestaShop otrzyma ten status. Status sklepu nigdy nie nadpisuje statusu w Orbito.', + 'Every new PrestaShop order receives this status. The shop state never overwrites the Orbito status.', + ), + ...(error ? { statusWarning: info(error) } : {}), + orderStatus: { + type: Config.PropertyType.STRING, + name: { pl: 'Domyślny status po imporcie', en: 'Default status after import' }, + options: { values }, + }, + }; +} + +async function outboundMappingSchema(refreshPsStates) { + const [config, { statuses, error }, { states, refreshError }] = await Promise.all([ + Config.getAll(), loadOrbitoStatuses(), refreshPsStates(), + ]); + const mapping = readStatusMapping(config); + const schema = { + hint: info( + 'Dla każdego statusu Orbito wybierz status PrestaShop. Kilka statusów Orbito może wskazywać ten sam status PrestaShop. Puste pole wyłącza wysyłkę tego statusu. Zmiany w sklepie nie nadpisują statusów Orbito.', + 'Choose a PrestaShop state for each Orbito status. Multiple Orbito statuses may use the same PrestaShop state. An empty field disables synchronization for that status. Shop changes never overwrite Orbito statuses.', + ), + }; + if (error) schema.statusWarning = info(error); + if (refreshError) schema.refreshWarning = info(`Nie udało się odświeżyć statusów PrestaShop; pokazano ostatnio zapisane dane. ${refreshError}`); + + const rows = new Map(statuses + .filter(status => normalizeStatusId(status._id)) + .map(status => [String(status._id), status.name || String(status._id)])); + const values = states.map(state => ({ id: String(state.id), label: `${state.name || 'Status'} (PS #${state.id})` })); + for (const entry of mapping) { + if (!rows.has(entry.orbitoStatusId)) rows.set(entry.orbitoStatusId, `Status Orbito ${entry.orbitoStatusId} — niedostępny na liście`); + if (!values.some(value => value.id === String(entry.psStateId))) { + values.push({ id: String(entry.psStateId), label: `Status PrestaShop #${entry.psStateId} — niedostępny na liście` }); + } + } + // Also keep explicitly cleared rows visible when their Orbito status disappears. + for (const key of Object.keys(config)) { + const id = /^mapping\.orbito_([a-f0-9]{24})$/i.exec(key)?.[1]; + if (id && !rows.has(id)) rows.set(id, `Status Orbito ${id} — niedostępny na liście`); + } + for (const [id, name] of rows) { + const matches = [...new Set(mapping.filter(entry => entry.orbitoStatusId === id).map(entry => String(entry.psStateId)))]; + const conflict = matches.length > 1; + schema[`orbito_${id}`] = { + type: Config.PropertyType.STRING, + name: { pl: name, en: name }, + options: { values: conflict + ? [{ id: LEGACY_CONFLICT, label: `Konflikt zapisanych przypisań: PS #${matches.join(', #')} — wybierz jeden status lub wyczyść` }, ...values] + : values }, + }; + } + return schema; +} + +function validateOutboundMapping(params, report) { + for (const [field, value] of Object.entries(params || {})) { + if (!/^orbito_[a-f0-9]{24}$/i.test(field) || value == null || value === '') continue; + if (value === LEGACY_CONFLICT) { + report.addError(field, 'Zachowano wszystkie stare przypisania. Wybierz jeden status PrestaShop lub wyczyść pole, aby wyłączyć wysyłkę.'); + } else if (!isPsStateId(value)) { + report.addError(field, 'Wybierz poprawny status PrestaShop.'); + } + } +} + +module.exports = { importStatusSchema, outboundMappingSchema, validateOutboundMapping }; diff --git a/src/status-mapper.js b/src/status-mapper.js index c71fe81..ac449d0 100644 --- a/src/status-mapper.js +++ b/src/status-mapper.js @@ -1,3 +1,5 @@ +const LEGACY_CONFLICT = 'legacy_conflict'; + function normalizeStatusId(value) { if (value == null || value === '') return null; if (typeof value === 'object' && value._id != null) { @@ -34,8 +36,7 @@ function resolveStatusId(psStateId, statusMapping, fallbackStatusId) { return normalizeStatusId(match?.orbitoStatusId) ?? normalizeStatusId(fallbackStatusId); } -// Mapowanie jest konfigurowane w wierszach PrestaShop -> Orbito, ale po -// zapisaniu służy wyłącznie do wysyłki statusu w przeciwnym kierunku. +// Kilka statusów Orbito może wskazywać ten sam status PrestaShop. // Jeden status Orbito nie może wskazywać kilku statusów PrestaShop, bo wtedy // wynik synchronizacji zależałby od kolejności pól formularza. function resolvePsStateId(orbitoStatusId, statusMapping) { @@ -54,6 +55,33 @@ function resolvePsStateId(orbitoStatusId, statusMapping) { return uniqueMatches[0] ?? null; } +// Legacy keys remain untouched. An explicitly saved empty outbound field +// disables its legacy assignment; a missing field inherits it. Read all keys, +// including states no longer returned by the shop, to avoid losing mappings. +function readStatusMapping(config) { + const legacy = []; + const outbound = new Map(); + for (const [key, value] of Object.entries(config)) { + const oldMatch = /^mapping\.state_(\d+)$/.exec(key); + const newMatch = /^mapping\.orbito_([a-f0-9]{24})$/i.exec(key); + if (oldMatch && normalizeStatusId(value)) { + legacy.push({ psStateId: Number(oldMatch[1]), orbitoStatusId: normalizeStatusId(value) }); + } + if (newMatch && value !== LEGACY_CONFLICT) outbound.set(newMatch[1], value); + } + const result = legacy.filter(entry => !outbound.has(entry.orbitoStatusId)); + for (const [orbitoStatusId, value] of outbound) { + if (value == null || value === '') continue; + if (!isPsStateId(value)) throw new Error(`Niepoprawny status PrestaShop dla statusu Orbito ${orbitoStatusId}`); + result.push({ orbitoStatusId, psStateId: Number(value) }); + } + return result.sort((a, b) => a.psStateId - b.psStateId); +} + +function isPsStateId(value) { + return /^\d+$/.test(String(value)) && Number.isSafeInteger(Number(value)) && Number(value) > 0; +} + function formatPsStatesPreview(states) { if (!Array.isArray(states) || !states.length) { return 'Brak statusów PrestaShop — najpierw przetestuj połączenie.'; @@ -76,6 +104,9 @@ function extractPsStateName(name) { } module.exports = { + LEGACY_CONFLICT, + readStatusMapping, + isPsStateId, normalizeStatusId, parseStatusMapping, resolveStatusId, diff --git a/test/register-config-icon.test.js b/test/register-config-icon.test.js index 328118b..2943212 100644 --- a/test/register-config-icon.test.js +++ b/test/register-config-icon.test.js @@ -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 () => [], }; diff --git a/test/register-config-status.test.js b/test/register-config-status.test.js index 55b00b8..6b81c16 100644 --- a/test/register-config-status.test.js +++ b/test/register-config-status.test.js @@ -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'); +}); diff --git a/test/status-mapper.test.js b/test/status-mapper.test.js index 0f4cb29..bb82d48 100644 --- a/test/status-mapper.test.js +++ b/test/status-mapper.test.js @@ -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/); + } +}); diff --git a/test/status-sync.test.js b/test/status-sync.test.js index 843149a..1100a3b 100644 --- a/test/status-sync.test.js +++ b/test/status-sync.test.js @@ -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: [{