From 139ac5cb52e7d61286bbaf40f9fc3d06dbcd1ae9 Mon Sep 17 00:00:00 2001 From: fatequod Date: Wed, 15 Jul 2026 09:19:53 +0200 Subject: [PATCH] Improve config form UI and add mapping row save endpoint. Refactor status counts and config pages for the updated PrestaShop integration workflow. Co-authored-by: Cursor --- methods/config/save_mapping_row.js | 41 +++++++ methods/status/get_with_counts.js | 38 +----- pages/config.js | 181 ++++++++++++++++------------- src/config-form.js | 136 +++++++++++++++++----- 4 files changed, 257 insertions(+), 139 deletions(-) create mode 100644 methods/config/save_mapping_row.js diff --git a/methods/config/save_mapping_row.js b/methods/config/save_mapping_row.js new file mode 100644 index 0000000..4ea30f1 --- /dev/null +++ b/methods/config/save_mapping_row.js @@ -0,0 +1,41 @@ +const { Log } = require('@orbito/api-lib'); +const ShopConfig = require('../../src/models/ShopConfig'); +const { normalizeFormParams, normalizeSelectValue, mergeStatusMappingEntry } = require('../../src/config-form'); +const { methodOk, methodFail } = require('../../src/method-result'); + +function extractOrbitoStatusId(input) { + for (const [key, value] of Object.entries(input)) { + if (/^psMapStatus[._]\d+$/.test(key)) { + return normalizeSelectValue(value); + } + } + return normalizeSelectValue(input.orbitoStatusId ?? input.value ?? ''); +} + +module.exports = async function(params, ctx) { + try { + const existing = await ShopConfig.findOne({ isRemoved: { $ne: true } }); + if (!existing) { + return methodFail('Najpierw zapisz konfigurację połączenia ze sklepem.'); + } + + const input = normalizeFormParams(params); + const psStateId = parseInt(input.psStateId ?? params.psStateId, 10); + if (Number.isNaN(psStateId)) { + return methodFail('Brak ID statusu PrestaShop.'); + } + + const orbitoStatusId = normalizeSelectValue( + input.orbitoStatusId ?? params.orbitoStatusId ?? extractOrbitoStatusId(input) + ); + const statusMapping = mergeStatusMappingEntry(existing.statusMapping, psStateId, orbitoStatusId); + + await ShopConfig.update({ _id: existing._id }, { statusMapping }); + Log.debug('config.save_mapping_row', { psStateId, orbitoStatusId: orbitoStatusId || null }); + + return methodOk({ psStateId, orbitoStatusId, statusMapping }); + } catch (err) { + Log.error('config.save_mapping_row failed', { error: err?.message }); + return methodFail(err?.message || 'Nie udało się zapisać mapowania statusu'); + } +}; diff --git a/methods/status/get_with_counts.js b/methods/status/get_with_counts.js index 3c62476..73ff58d 100644 --- a/methods/status/get_with_counts.js +++ b/methods/status/get_with_counts.js @@ -1,38 +1,6 @@ -const { getOrderStatuses, searchOrders } = require('../../src/orders-api'); - -const cache = new Map(); -const CACHE_TTL = 5000; -const CACHE_KEY = 'default'; +const { Core } = require('@orbito/api-lib'); +// Proxy do core/orders — statusy są współdzielone i zarządzane w core/orders. module.exports = async function(params, ctx) { - const now = Date.now(); - const cached = cache.get(CACHE_KEY); - if (cached && now - cached.ts < CACHE_TTL) { - return { data: cached.data }; - } - - const statuses = await getOrderStatuses(); - const data = []; - - for (const status of statuses) { - const statusId = status._id?.toString?.() ?? status._id; - const result = await searchOrders({ - statusId, - page: 1, - perPage: 1 - }); - - data.push({ - _id: statusId, - name: status.name ?? '', - color: status.color ?? 'secondary', - positionInGroup: status.positionInGroup ?? 0, - count: result.pagination?.total ?? 0 - }); - } - - data.sort((a, b) => (a.positionInGroup ?? 0) - (b.positionInGroup ?? 0)); - - cache.set(CACHE_KEY, { ts: now, data }); - return { data }; + return Core.callModule('core/orders', 'status.get_with_counts', params || {}); }; diff --git a/pages/config.js b/pages/config.js index befc04f..de31142 100644 --- a/pages/config.js +++ b/pages/config.js @@ -1,6 +1,6 @@ -const { Log } = require('@orbito/api-lib'); +const { Log, Core } = require('@orbito/api-lib'); const ShopConfig = require('../src/models/ShopConfig'); -const { toFormResponse, CONNECTION_WITH_DATA, SAVE_WITH_DATA } = require('../src/config-form'); +const { toFormResponse, CONNECTION_WITH_DATA } = require('../src/config-form'); const PAGE_TARGET = 'psConfigPageRoot'; @@ -25,9 +25,90 @@ function successToast(title, content) { }; } -function buildTemplate(form) { +function buildMappingRowViews(form, orbitoStatusOptions) { + const rows = Array.isArray(form.statusMappingRows) ? form.statusMappingRows : []; + + if (!rows.length) { + return [{ + type: 'text', + content: 'Brak statusów PrestaShop — kliknij „Pobierz statusy PrestaShop”.', + className: 'text-muted' + }]; + } + + // Wiersze renderujemy po stronie serwera, aby każdy select miał LITERALNE, + // unikalne id (psMapStatus_). Handlebars nie działa w polu `id`, + // a `#form` nie zbiera danych przy renderze przez generatePage+target — dlatego + // zapis (przycisk oraz onChange) odwołuje się do konkretnych id widoków. + return rows.map(row => { + const selectId = `psMapStatus_${row.psStateId}`; + return { + type: 'row', + cols: [ + { + size: 5, + childs: [{ + type: 'flex', + direction: 'row', + align: 'center', + gap: 2, + childs: [ + { + type: 'html', + content: ` ` + }, + { + type: 'flex', + direction: 'column', + gap: 0, + childs: [ + { + type: 'text', + content: row.psStateName, + className: 'fw-semibold' + }, + { + type: 'text', + content: `ID PrestaShop: ${row.psStateId}`, + className: 'text-muted small' + } + ] + } + ] + }] + }, + { + size: 7, + childs: [{ + type: 'select', + id: selectId, + name: selectId, + label: 'Status Orbito', + placeholder: 'Wybierz status Orbito', + value: row.orbitoStatusId || '', + allowClear: true, + options: orbitoStatusOptions, + onChange: { + action: 'callMethod', + module: 'core/prestashop', + method: 'config.save_mapping_row', + params: { psStateId: row.psStateId }, + withData: [selectId] + } + }] + } + ] + }; + }); +} + +function buildTemplate(form, orbitoStatusOptions) { const hasApiKey = Boolean(form.hasApiKey); + const mappingSelectIds = (Array.isArray(form.statusMappingRows) ? form.statusMappingRows : []) + .map(row => `psMapStatus_${row.psStateId}`); + const saveWithData = [...CONNECTION_WITH_DATA, ...mappingSelectIds]; + return { type: 'flex', direction: 'column', @@ -194,7 +275,7 @@ function buildTemplate(form) { action: 'callMethod', module: 'core/prestashop', method: 'config.save', - withData: SAVE_WITH_DATA, + withData: saveWithData, then: successToast('Zapisano konfigurację', 'Konfiguracja modułu PrestaShop została zapisana.') } } @@ -225,84 +306,16 @@ function buildTemplate(form) { method: 'config.get_ps_states', withData: CONNECTION_WITH_DATA, then: [ - { action: 'reload', target: 'statusMappingList' }, + refreshPage(), successToast('Statusy pobrane', 'Lista statusów PrestaShop została załadowana.') ] } }, { - type: 'list', - id: 'statusMappingList', - module: 'core/prestashop', - method: 'config.get_status_mapping', - emptyMessage: 'Brak statusów PrestaShop — kliknij „Pobierz statusy PrestaShop”.', - loadingMessage: 'Ładowanie mapowania statusów...', - template: { - type: 'row', - cols: [ - { - size: 5, - childs: [{ - type: 'flex', - direction: 'row', - align: 'center', - gap: 2, - childs: [ - { - type: 'html', - content: ' ' - }, - { - type: 'flex', - direction: 'column', - gap: 0, - childs: [ - { - type: 'text', - content: '{{ statusMappingList.$.psStateName }}', - className: 'fw-semibold' - }, - { - type: 'text', - content: 'ID PrestaShop: {{ statusMappingList.$.psStateId }}', - className: 'text-muted small' - } - ] - } - ] - }] - }, - { - size: 7, - childs: [ - { - type: 'input', - name: 'statusMappingRows.$.psStateId', - inputType: 'hidden', - value: '{{ statusMappingList.$.psStateId }}', - groups: ['form'] - }, - { - type: 'select', - name: 'statusMappingRows.$.orbitoStatusId', - label: 'Status Orbito', - placeholder: 'Wybierz status Orbito', - value: '{{ statusMappingList.$.orbitoStatusId }}', - allowClear: true, - optionsSource: { - module: 'core/orders', - method: 'status.search', - params: {}, - labelKey: 'name', - idKey: '_id', - responsePath: 'results' - }, - groups: ['form'] - } - ] - } - ] - } + type: 'flex', + direction: 'column', + gap: 2, + childs: buildMappingRowViews(form, orbitoStatusOptions) } ] }] @@ -311,14 +324,26 @@ function buildTemplate(form) { }; } +async function loadOrbitoStatusOptions() { + try { + const res = await Core.callModule('core/orders', 'status.search', {}); + const results = res?.results || res?.data?.results || []; + return results.map(status => ({ id: String(status._id), label: status.name })); + } catch (err) { + Log.warn('pages/config: nie udało się pobrać statusów Orbito', { error: err?.message }); + return []; + } +} + module.exports = async function(body, params) { try { const config = await ShopConfig.findOne({ isRemoved: { $ne: true } }); const form = toFormResponse(config); + const orbitoStatusOptions = await loadOrbitoStatusOptions(); return { type: 'ove', - template: buildTemplate(form) + template: buildTemplate(form, orbitoStatusOptions) }; } catch (err) { Log.error( 'pages/config failed', { error: err?.message, stack: err?.stack }); diff --git a/src/config-form.js b/src/config-form.js index 2968111..3a2e910 100644 --- a/src/config-form.js +++ b/src/config-form.js @@ -13,8 +13,8 @@ const VIEW_ID_ALIASES = { /** Pola połączenia — używaj w withData zamiast #form (nie działa w generatePage+target). */ const CONNECTION_WITH_DATA = Object.keys(VIEW_ID_ALIASES); -/** Pełny zapis: połączenie + mapowanie statusów z listy. */ -const SAVE_WITH_DATA = [...CONNECTION_WITH_DATA, 'statusMappingList']; +/** Pełny zapis: połączenie (po id widoku) + mapowanie (grupa form). */ +const SAVE_WITH_DATA = [...CONNECTION_WITH_DATA, '#form']; const EMPTY_FORM = { storeUrl: '', @@ -115,11 +115,89 @@ function hasFormInput(input) { } function hasMappingInput(input) { - if (input.statusMappingRows != null) return true; - return Object.keys(input).some(key => key.startsWith('statusMappingRows.')); + if (Array.isArray(input.statusMappingRows) && input.statusMappingRows.length) return true; + if (input.statusMappingRows && typeof input.statusMappingRows === 'object' && Object.keys(input.statusMappingRows).length) { + return true; + } + return Object.keys(input).some(key => + key.startsWith('statusMappingRows.') || /^psMapStatus[._]\d+$/.test(key)); +} + +function mergeStatusMappingEntry(existing, psStateId, orbitoStatusId) { + const list = Array.isArray(existing) ? existing.map(entry => ({ ...entry })) : []; + const idx = list.findIndex(entry => parseInt(entry.psStateId, 10) === psStateId); + + if (!orbitoStatusId) { + if (idx >= 0) list.splice(idx, 1); + return list; + } + + const entry = { psStateId, orbitoStatusId }; + if (idx >= 0) list[idx] = entry; + else list.push(entry); + return list; +} + +function extractAllStatusMappingRows(input) { + const rows = input.statusMappingRows; + + if (Array.isArray(rows)) { + return rows + .map(row => ({ + psStateId: parseInt(row?.psStateId, 10), + orbitoStatusId: normalizeSelectValue(row?.orbitoStatusId) + })) + .filter(row => !Number.isNaN(row.psStateId)); + } + + if (rows && typeof rows === 'object') { + return Object.values(rows) + .map(row => ({ + psStateId: parseInt(row?.psStateId, 10), + orbitoStatusId: normalizeSelectValue(row?.orbitoStatusId) + })) + .filter(row => !Number.isNaN(row.psStateId)); + } + + const indexed = {}; + for (const [key, value] of Object.entries(input)) { + const match = key.match(/^statusMappingRows\.(\d+)\.(psStateId|orbitoStatusId)$/); + if (!match) continue; + indexed[match[1]] = indexed[match[1]] || {}; + indexed[match[1]][match[2]] = value; + } + + return Object.values(indexed) + .map(row => ({ + psStateId: parseInt(row.psStateId, 10), + orbitoStatusId: normalizeSelectValue(row.orbitoStatusId) + })) + .filter(row => !Number.isNaN(row.psStateId)); +} + +function mergeStatusMappingFromForm(existing, formRows) { + let merged = Array.isArray(existing) ? existing.map(entry => ({ ...entry })) : []; + for (const row of formRows) { + merged = mergeStatusMappingEntry(merged, row.psStateId, row.orbitoStatusId); + } + return merged; } function extractStatusMappingRows(input) { + const byViewId = []; + let sawMappingSelect = false; + for (const [key, value] of Object.entries(input)) { + const match = key.match(/^psMapStatus[._](\d+)$/); + if (!match) continue; + sawMappingSelect = true; + const psStateId = parseInt(match[1], 10); + const orbitoStatusId = normalizeSelectValue(value); + if (!Number.isNaN(psStateId) && orbitoStatusId) { + byViewId.push({ psStateId, orbitoStatusId }); + } + } + if (sawMappingSelect) return byViewId; + const rows = input.statusMappingRows; if (Array.isArray(rows)) { @@ -158,7 +236,10 @@ function extractStatusMappingRows(input) { function pickString(input, existing, inputKey, existingKey = inputKey) { if (Object.prototype.hasOwnProperty.call(input, inputKey)) { - return String(input[inputKey] ?? '').trim(); + const value = String(input[inputKey] ?? '').trim(); + // Pola wstępnie wypełnione, których użytkownik nie ruszył, potrafią wrócić + // puste ze zbierania withData — nie nadpisujemy nimi zapisanej wartości. + if (value !== '') return value; } const prev = existing?.[existingKey]; if (prev !== undefined && prev !== null && String(prev).trim() !== '') { @@ -170,44 +251,44 @@ function pickString(input, existing, inputKey, existingKey = inputKey) { function buildSavePayload(params, existing) { const input = normalizeFormParams(params); - const hasConnectionInput = ['storeUrl', 'apiUrl', 'apiKey', 'shopPrefix', 'shopName', 'versionCode', 'orderStatus'] - .some(key => Object.prototype.hasOwnProperty.call(input, key)); - - const storeUrl = pickString(input, hasConnectionInput ? null : existing, 'storeUrl', 'apiUrl'); - const apiKey = Object.prototype.hasOwnProperty.call(input, 'apiKey') - ? ((input.apiKey || '').trim() || existing?.apiKey || '') - : (hasConnectionInput ? '' : (existing?.apiKey || '')); + // Zawsze przekazujemy `existing` do pickString: puste pole formularza (np. URL, + // którego użytkownik nie edytował) nie kasuje zapisanej wartości. + const storeUrl = pickString(input, existing, 'storeUrl', 'apiUrl'); + const apiKey = (input.apiKey || '').trim() || existing?.apiKey || ''; const data = { apiUrl: storeUrl, apiKey, - shopPrefix: pickString(input, hasConnectionInput ? null : existing, 'shopPrefix'), - shopName: pickString(input, hasConnectionInput ? null : existing, 'shopName'), + shopPrefix: pickString(input, existing, 'shopPrefix'), + shopName: pickString(input, existing, 'shopName'), }; const versionCode = normalizeSelectValue(input.versionCode); - if (versionCode || Object.prototype.hasOwnProperty.call(input, 'versionCode')) { + if (versionCode) { data.versionCode = versionCode; } else if (existing?.versionCode) { data.versionCode = existing.versionCode; } const orderStatus = normalizeSelectValue(input.orderStatus); - if (orderStatus || Object.prototype.hasOwnProperty.call(input, 'orderStatus')) { - data.orderStatus = orderStatus || null; + if (orderStatus) { + data.orderStatus = orderStatus; } else if (existing?.orderStatus) { data.orderStatus = existing.orderStatus; } - const mappingRows = extractStatusMappingRows(input); - if (mappingRows.length) { - data.statusMapping = mappingRows; - } else if (hasMappingInput(input)) { - data.statusMapping = []; - } else if (typeof input.statusMappingJson !== 'undefined' || typeof input.statusMapping !== 'undefined') { - data.statusMapping = parseStatusMapping(input.statusMapping ?? input.statusMappingJson); - } else if (existing?.statusMapping) { - data.statusMapping = existing.statusMapping; + const formMappingRows = extractAllStatusMappingRows(input); + if (formMappingRows.length) { + data.statusMapping = mergeStatusMappingFromForm(existing?.statusMapping, formMappingRows); + } else { + const mappingRows = extractStatusMappingRows(input); + if (mappingRows.length) { + data.statusMapping = mappingRows; + } else if (typeof input.statusMappingJson !== 'undefined' || typeof input.statusMapping !== 'undefined') { + data.statusMapping = parseStatusMapping(input.statusMapping ?? input.statusMappingJson); + } else if (existing?.statusMapping) { + data.statusMapping = existing.statusMapping; + } } if (Array.isArray(existing?.psStates) && existing.psStates.length) { @@ -230,6 +311,9 @@ module.exports = { hasFormInput, hasMappingInput, extractStatusMappingRows, + extractAllStatusMappingRows, + mergeStatusMappingEntry, + mergeStatusMappingFromForm, toFormResponse, buildSavePayload };