Files
core-prestashop/pages/config.js
T
fatequodandCursor 139ac5cb52 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 <cursoragent@cursor.com>
2026-07-15 09:19:53 +02:00

371 lines
15 KiB
JavaScript

const { Log, Core } = require('@orbito/api-lib');
const ShopConfig = require('../src/models/ShopConfig');
const { toFormResponse, CONNECTION_WITH_DATA } = require('../src/config-form');
const PAGE_TARGET = 'psConfigPageRoot';
function refreshPage() {
return {
action: 'emit',
event: 'generatePage',
data: {
module: 'core/prestashop',
page: `config/${Date.now()}`,
target: PAGE_TARGET
}
};
}
function successToast(title, content) {
return {
action: 'toast',
type: 'success',
title,
content
};
}
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_<psStateId>). 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: `<span class="badge" style="background-color:${escapeHtml(row.psStateColor)};min-width:12px">&nbsp;</span>`
},
{
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',
gap: 3,
childs: [
{
type: 'card',
title: 'Konfiguracja PrestaShop',
content: [{
type: 'flex',
direction: 'column',
gap: 3,
childs: [
{
type: 'text',
content: 'Połączenie z Webservice API',
className: 'fw-bold'
},
{
type: 'text',
content: 'Uzupełnij dane dostępowe do sklepu PrestaShop. Klucz wygenerujesz w panelu sklepu w sekcji Zaawansowane → Web Service.',
className: 'text-muted small'
},
{
type: 'input',
id: 'psShopUrlInput',
name: 'storeUrl',
inputType: 'text',
label: 'URL sklepu',
placeholder: 'https://twoj-sklep.pl',
value: form.storeUrl || '',
groups: ['form']
},
{
type: 'input',
id: 'psApiKeyInput',
name: 'apiKey',
inputType: 'password',
label: 'Klucz API',
placeholder: hasApiKey
? 'Zostaw puste, aby zachować zapisany klucz'
: 'Wklej klucz Webservice API',
value: '',
groups: ['form']
},
...(hasApiKey ? [{
type: 'text',
content: '<span class="text-muted small">Zapisany klucz API jest już skonfigurowany. Wpisz nowy tylko jeśli chcesz go zmienić.</span>'
}] : []),
{
type: 'select',
id: 'psVersionInput',
name: 'versionCode',
label: 'Wersja sklepu',
placeholder: 'Wybierz wersję PrestaShop',
value: form.versionCode || '',
options: [
{ id: '9', label: 'PrestaShop 9' },
{ id: '8', label: 'PrestaShop 8' },
{ id: '1.7', label: 'PrestaShop 1.7' },
{ id: '1.6', label: 'PrestaShop 1.6 lub starsze' }
],
groups: ['form']
},
{
type: 'input',
id: 'psShopNameInput',
name: 'shopName',
inputType: 'text',
label: 'Nazwa sklepu (opcjonalnie)',
placeholder: 'np. Sklep główny',
value: form.shopName || '',
groups: ['form']
},
{
type: 'input',
id: 'psShopPrefixInput',
name: 'shopPrefix',
inputType: 'text',
label: 'Prefix sklepu (uniqueId)',
placeholder: 'np. PL',
value: form.shopPrefix || '',
groups: ['form']
},
{
type: 'text',
content: 'Prefix jest używany w <code>uniqueId</code> zamówienia, np. <code>PL:389218</code>. Przed zapisaniem przetestuj połączenie z API.',
style: { color: '#667085' }
},
{
type: 'text',
content: 'Status zamówienia',
className: 'fw-bold mt-2'
},
{
type: 'text',
content: 'Domyślny status Orbito, gdy brak mapowania PS → Orbito. Lista statusów pochodzi z modułu <strong>core/orders</strong>.',
className: 'text-muted small'
},
{
type: 'select',
id: 'psOrderStatusInput',
name: 'orderStatus',
label: 'Domyślny status po imporcie',
placeholder: 'Wybierz status zamówienia',
value: form.orderStatus || '',
optionsSource: {
module: 'core/orders',
method: 'status.search',
params: {},
labelKey: 'name',
idKey: '_id',
responsePath: 'results'
},
groups: ['form']
}
]
}],
footer: [
{
type: 'button',
label: 'Resetuj',
variant: 'danger',
outline: true,
icon: 'trash',
onClick: {
action: 'confirm',
type: 'alert',
title: 'Reset konfiguracji',
description: 'Czy na pewno chcesz usunąć aktualną konfigurację modułu PrestaShop?',
yesLabel: 'Resetuj',
noLabel: 'Anuluj',
onYes: {
action: 'callMethod',
module: 'core/prestashop',
method: 'config.reset_all',
then: [
refreshPage(),
successToast('Konfiguracja zresetowana', 'Dane konfiguracji zostały usunięte.')
]
}
}
},
{
type: 'button',
label: 'Testuj połączenie',
variant: 'info',
outline: true,
icon: 'plug-connected',
onClick: {
action: 'callMethod',
module: 'core/prestashop',
method: 'config.test_connection',
withData: CONNECTION_WITH_DATA,
then: successToast('Połączenie działa', 'Połączenie z API PrestaShop zostało poprawnie przetestowane.')
}
},
{
type: 'button',
label: 'Zapisz konfigurację',
variant: 'primary',
icon: 'device-floppy',
onClick: {
action: 'callMethod',
module: 'core/prestashop',
method: 'config.save',
withData: saveWithData,
then: successToast('Zapisano konfigurację', 'Konfiguracja modułu PrestaShop została zapisana.')
}
}
]
},
{
type: 'card',
title: 'Mapowanie statusów PrestaShop → Orbito',
content: [{
type: 'flex',
direction: 'column',
gap: 3,
childs: [
{
type: 'text',
content: 'Pobierz statusy ze sklepu, a następnie przypisz każdy status PrestaShop do odpowiednika w Orbito. Przy imporcie używane jest <code>current_state</code> z zamówienia PS.',
className: 'text-muted small'
},
{
type: 'button',
label: 'Pobierz statusy PrestaShop',
variant: 'secondary',
outline: true,
icon: 'list',
onClick: {
action: 'callMethod',
module: 'core/prestashop',
method: 'config.get_ps_states',
withData: CONNECTION_WITH_DATA,
then: [
refreshPage(),
successToast('Statusy pobrane', 'Lista statusów PrestaShop została załadowana.')
]
}
},
{
type: 'flex',
direction: 'column',
gap: 2,
childs: buildMappingRowViews(form, orbitoStatusOptions)
}
]
}]
}
]
};
}
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, orbitoStatusOptions)
};
} catch (err) {
Log.error( 'pages/config failed', { error: err?.message, stack: err?.stack });
return {
type: 'ove',
template: {
type: 'card',
title: 'Konfiguracja PrestaShop',
content: [{
type: 'text',
content: `<div class="alert alert-danger">Nie udało się załadować konfiguracji: ${escapeHtml(err?.message || 'nieznany błąd')}</div>`
}]
}
};
}
};
function escapeHtml(str) {
return String(str)
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;');
}