Migrate PrestaShop config to Config API blocks and add permissions.

Replace custom ShopConfig pages/models with registerConfigBlocks, load config from Config store, and enforce RBAC on methods.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
fatequod
2026-07-22 12:20:30 +02:00
co-authored by Cursor
parent 139ac5cb52
commit 5a1e6ffbdd
27 changed files with 341 additions and 1206 deletions
+1 -1
View File
@@ -122,7 +122,7 @@ async function importFromPSOrder(orderId, api, config) {
await Promise.all(
products
.filter(p => p.sourceId && p.name)
.map(p => Core.callModule( 'core/orders', 'product.upsert', {
.map(p => Core.callModule( 'core/products', 'upsert', {
sourceModule: 'core/prestashop',
sourceId: String(p.sourceId),
sku: p.sku || '',
-319
View File
@@ -1,319 +0,0 @@
const { parseStatusMapping } = require('./status-mapper');
// ID widoków OVE → nazwy pól (withData zbiera po id, metody oczekują name)
const VIEW_ID_ALIASES = {
psShopUrlInput: 'storeUrl',
psApiKeyInput: 'apiKey',
psVersionInput: 'versionCode',
psShopNameInput: 'shopName',
psShopPrefixInput: 'shopPrefix',
psOrderStatusInput: 'orderStatus'
};
/** 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 (po id widoku) + mapowanie (grupa form). */
const SAVE_WITH_DATA = [...CONNECTION_WITH_DATA, '#form'];
const EMPTY_FORM = {
storeUrl: '',
shopName: '',
shopPrefix: '',
versionCode: '',
orderStatus: '',
psStates: [],
statusMappingRows: [],
hasPsStates: false,
hasApiKey: false
};
function normalizeSelectValue(value) {
if (value == null || value === '') return '';
if (typeof value === 'object') {
return String(value.id ?? value.value ?? value._id ?? '').trim();
}
return String(value).trim();
}
function buildMappingRows(psStates, statusMapping) {
const mapping = Array.isArray(statusMapping) ? statusMapping : [];
const byPsId = new Map();
for (const entry of mapping) {
const psStateId = parseInt(entry.psStateId, 10);
if (Number.isNaN(psStateId)) continue;
byPsId.set(psStateId, normalizeSelectValue(entry.orbitoStatusId));
}
return (Array.isArray(psStates) ? psStates : []).map(state => {
const psStateId = parseInt(state.id ?? state.psStateId, 10);
return {
psStateId: String(psStateId),
psStateName: state.name ?? state.psStateName ?? `Status ${psStateId}`,
psStateColor: state.color ?? state.psStateColor ?? '#cccccc',
orbitoStatusId: byPsId.get(psStateId) || ''
};
});
}
function toFormResponse(doc) {
if (!doc) return { ...EMPTY_FORM };
const psStates = Array.isArray(doc.psStates) ? doc.psStates : [];
const statusMapping = Array.isArray(doc.statusMapping) ? doc.statusMapping : [];
return {
storeUrl: doc.apiUrl || doc.storeUrl || '',
shopName: doc.shopName || '',
shopPrefix: doc.shopPrefix || '',
versionCode: doc.versionCode || '',
orderStatus: doc.orderStatus?.toString?.() ?? doc.orderStatus ?? '',
psStates,
statusMappingRows: buildMappingRows(psStates, statusMapping),
hasPsStates: psStates.length > 0,
hasApiKey: Boolean(doc.apiKey)
};
}
function normalizeFormParams(params = {}) {
if (params == null || typeof params !== 'object') return {};
let flat = params;
if (Array.isArray(flat)) {
flat = flat.find(item => item && typeof item === 'object') || {};
}
if (flat.data && typeof flat.data === 'object' && !Array.isArray(flat.data)) {
flat = { ...flat, ...flat.data };
} else {
flat = { ...flat };
}
for (const [key, value] of Object.entries(flat)) {
if (value && typeof value === 'object' && !Array.isArray(value)) {
if ('value' in value) {
flat[key] = value.value;
} else if ('id' in value && (key === 'versionCode' || key === 'orderStatus' || key.endsWith('orbitoStatusId'))) {
flat[key] = value.id;
}
}
}
for (const [viewId, fieldName] of Object.entries(VIEW_ID_ALIASES)) {
if (Object.prototype.hasOwnProperty.call(flat, viewId) && !Object.prototype.hasOwnProperty.call(flat, fieldName)) {
flat[fieldName] = flat[viewId];
}
}
return flat;
}
function hasFormInput(input) {
const formKeys = ['storeUrl', 'apiUrl', 'shopName', 'shopPrefix', 'versionCode', 'orderStatus', 'apiKey'];
return formKeys.some(key => Object.prototype.hasOwnProperty.call(input, key)) || hasMappingInput(input);
}
function hasMappingInput(input) {
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)) {
return rows
.map(row => ({
psStateId: parseInt(row?.psStateId, 10),
orbitoStatusId: normalizeSelectValue(row?.orbitoStatusId)
}))
.filter(row => !Number.isNaN(row.psStateId) && row.orbitoStatusId);
}
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) && row.orbitoStatusId);
}
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) && row.orbitoStatusId);
}
function pickString(input, existing, inputKey, existingKey = inputKey) {
if (Object.prototype.hasOwnProperty.call(input, inputKey)) {
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() !== '') {
return String(prev).trim();
}
return '';
}
function buildSavePayload(params, existing) {
const input = normalizeFormParams(params);
// 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, existing, 'shopPrefix'),
shopName: pickString(input, existing, 'shopName'),
};
const versionCode = normalizeSelectValue(input.versionCode);
if (versionCode) {
data.versionCode = versionCode;
} else if (existing?.versionCode) {
data.versionCode = existing.versionCode;
}
const orderStatus = normalizeSelectValue(input.orderStatus);
if (orderStatus) {
data.orderStatus = orderStatus;
} else if (existing?.orderStatus) {
data.orderStatus = existing.orderStatus;
}
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) {
data.psStates = existing.psStates;
} else if (Array.isArray(input.psStates) && input.psStates.length) {
data.psStates = input.psStates;
}
return data;
}
module.exports = {
EMPTY_FORM,
VIEW_ID_ALIASES,
CONNECTION_WITH_DATA,
SAVE_WITH_DATA,
normalizeSelectValue,
buildMappingRows,
normalizeFormParams,
hasFormInput,
hasMappingInput,
extractStatusMappingRows,
extractAllStatusMappingRows,
mergeStatusMappingEntry,
mergeStatusMappingFromForm,
toFormResponse,
buildSavePayload
};
+2 -1
View File
@@ -1,7 +1,8 @@
const { DB } = require('@orbito/api-lib');
const schema = new DB.Schema('ps_orders', {
shopConfigId: { type: 'ObjectId' },
// Identyfikator sklepu z Config (SHOP_ID = 'default'); wcześniej ObjectId z ShopConfig.
shopConfigId: { type: 'string' },
psOrderId: { type: 'number' },
orbitoOrderId: { type: 'ObjectId', optional: true },
reference: { type: 'string', optional: true, default: '' },
-52
View File
@@ -1,52 +0,0 @@
const { DB } = require('@orbito/api-lib');
const { customAlphabet } = require('nanoid');
const alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const schema = new DB.Schema('shop_config', {
apiUrl: { type: 'string', optional: true },
apiKey: { type: 'string', optional: true },
shopName: { type: 'string', optional: true },
versionCode: { type: 'string', optional: true },
// shopPrefix: prefiks używany w uniqueId zamówienia (np. "PL" -> "PL:389218").
// Na razie tylko przechowywany; nie jest jeszcze wpinany w format uniqueId w imporcie.
shopPrefix: { type: 'string', optional: true },
// orderStatus: domyślny status gdy brak mapowania PS → Orbito
orderStatus: { type: 'ObjectId', optional: true },
// statusMapping: [{ psStateId: 2, orbitoStatusId: "..." }]
statusMapping: {
type: 'array',
items: { type: 'object' },
optional: true,
default: []
},
// Podgląd statusów PS (cache do formularza konfiguracji)
psStatesPreview: { type: 'string', optional: true, default: '' },
// Lista statusów PS pobrana z API (do UI mapowania)
psStates: {
type: 'array',
items: { type: 'object' },
optional: true,
default: []
},
lastOrderId: { type: 'number', optional: true },
createdAt: { type: 'date', default: () => new Date() },
isRemoved: { type: 'boolean', default: false }
});
// Pre-validate hook - calculate summary and update derived fields
schema.pre('validate', async function(data) {
});
schema.post('create', function(data) {
// Hook for post-create actions (e.g., emit events, notifications)
});
module.exports = schema;
+90
View File
@@ -0,0 +1,90 @@
const { Config } = require('@orbito/api-lib');
/** Stały identyfikator sklepu (jeden sklep na firmę) — używany w PsOrder.shopConfigId. */
const SHOP_ID = 'default';
function isConfigured(config) {
return !!(config && config.apiUrl && config.apiKey);
}
async function loadPsStates() {
const states = await Config.get('runtime.psStates', []);
return Array.isArray(states) ? states : [];
}
async function loadStatusMapping(psStates) {
const states = Array.isArray(psStates) ? psStates : await loadPsStates();
const statusMapping = [];
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) });
}
}));
return statusMapping;
}
// Shape kompatybilny z dotychczasowym użyciem (OrderImporter, CRON, PrestaApi).
async function loadConfig() {
const [
apiUrl,
apiKey,
shopName,
shopPrefix,
versionCode,
orderStatus,
lastOrderId,
psStates
] = await Promise.all([
Config.get('connection.apiUrl', ''),
Config.get('connection.apiKey', ''),
Config.get('connection.shopName', ''),
Config.get('connection.shopPrefix', ''),
Config.get('connection.versionCode', ''),
Config.get('import.orderStatus', ''),
Config.get('runtime.lastOrderId', null),
loadPsStates()
]);
const statusMapping = await loadStatusMapping(psStates);
return {
_id: SHOP_ID,
apiUrl: apiUrl || '',
apiKey: apiKey || '',
shopName: shopName || '',
shopPrefix: shopPrefix || '',
versionCode: versionCode || '',
orderStatus: orderStatus || '',
lastOrderId: lastOrderId == null ? null : Number(lastOrderId),
psStates,
statusMapping
};
}
async function loadEnabledConfigs() {
const config = await loadConfig();
return isConfigured(config) ? [config] : [];
}
async function setLastOrderId(lastOrderId) {
await Config.set('runtime.lastOrderId', Number(lastOrderId));
}
async function setPsStates(psStates) {
await Config.set('runtime.psStates', Array.isArray(psStates) ? psStates : []);
}
module.exports = {
SHOP_ID,
isConfigured,
loadConfig,
loadEnabledConfigs,
loadPsStates,
setLastOrderId,
setPsStates
};
+173
View File
@@ -0,0 +1,173 @@
const { Config, Log } = require('@orbito/api-lib');
const { PropertyType, DisplayFormat } = Config;
const PrestashopApi = require('./PrestaApi');
const { isLegacyApi } = require('./utils');
const { extractPsStateName } = require('./status-mapper');
const { setPsStates, loadPsStates } = require('./module-config');
const ORBITO_STATUS_OPTIONS = {
module: 'core/orders',
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();
return (Array.isArray(rawStates) ? rawStates : [])
.filter(s => !s.deleted || s.deleted === '0' || s.deleted === 0)
.map(s => ({
id: parseInt(s.id, 10),
name: extractPsStateName(s.name),
color: s.color || '#cccccc'
}))
.filter(s => !Number.isNaN(s.id));
}
async function registerPrestashopConfigBlocks() {
await Config.registerConfigBlocks({
connection: {
title: { pl: 'Połączenie ze sklepem', en: 'Shop connection' },
scope: 'global',
schema: {
hint: {
type: PropertyType.INFO,
name: {
pl: 'Uzupełnij dane dostępowe do Webservice API. Klucz wygenerujesz w panelu sklepu: Zaawansowane → Web Service. Po zapisie automatycznie pobierzemy statusy zamówień PrestaShop do mapowania.',
en: 'Enter Webservice API credentials. Generate the key in Advanced → Web Service. On save we fetch PrestaShop order states for status mapping.'
}
},
apiUrl: {
type: PropertyType.STRING,
format: DisplayFormat.URL,
name: { pl: 'URL sklepu', en: 'Shop URL' },
description: { pl: 'https://twoj-sklep.pl', en: 'https://your-shop.com' },
required: true
},
apiKey: {
type: PropertyType.STRING,
format: DisplayFormat.SECRET,
name: { pl: 'Klucz API', en: 'API key' },
required: true
},
versionCode: {
type: PropertyType.STRING,
name: { pl: 'Wersja sklepu', en: 'Shop version' },
options: {
values: [
{ 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' }
]
}
},
shopName: {
type: PropertyType.STRING,
name: { pl: 'Nazwa sklepu', en: 'Shop name' },
description: { pl: 'opcjonalnie, np. Sklep główny', en: 'optional, e.g. Main store' }
},
shopPrefix: {
type: PropertyType.STRING,
name: { pl: 'Prefix sklepu (uniqueId)', en: 'Shop prefix (uniqueId)' },
description: {
pl: 'Używany w uniqueId zamówienia, np. PL → PL:389218',
en: 'Used in order uniqueId, e.g. PL → PL:389218'
}
}
},
validate: async (params, raport) => {
const apiUrl = String(params.apiUrl || '').trim();
const apiKey = String(params.apiKey || '').trim();
if (!apiUrl) {
raport.addError('apiUrl', 'URL sklepu jest wymagany.');
return;
}
if (!apiKey) {
raport.addError('apiKey', 'Klucz API jest wymagany.');
return;
}
try {
const psStates = await fetchPsStates(apiUrl, apiKey, params.versionCode);
await setPsStates(psStates);
Log.info('PrestaShop config: połączenie OK, statusy pobrane', { count: psStates.length });
} catch (err) {
Log.warn('PrestaShop config validate failed', { error: err?.message });
raport.addError('apiKey', err?.message || 'Nie udało się połączyć z API PrestaShop');
}
}
},
import: {
title: { pl: 'Import zamówień', en: 'Order import' },
scope: 'global',
schema: {
hint: {
type: PropertyType.INFO,
name: {
pl: 'Domyślny status Orbito, gdy brak mapowania PS → Orbito. Lista pochodzi z modułu core/orders.',
en: 'Default Orbito status when there is no PS → Orbito mapping. List comes from core/orders.'
}
},
orderStatus: {
type: PropertyType.STRING,
name: { pl: 'Domyślny status po imporcie', en: 'Default status after import' },
options: ORBITO_STATUS_OPTIONS
}
}
},
mapping: {
title: { pl: 'Mapowanie statusów', en: 'Status mapping' },
scope: 'global',
schema: async () => {
const psStates = await loadPsStates();
if (!psStates.length) {
return {
hint: {
type: PropertyType.INFO,
name: {
pl: 'Brak statusów PrestaShop. Zapisz najpierw zakładkę „Połączenie ze sklepem” — statusy pobierzemy automatycznie przy zapisie.',
en: 'No PrestaShop states yet. Save the “Shop connection” tab first — states are fetched automatically on save.'
}
}
};
}
const schema = {
hint: {
type: PropertyType.INFO,
name: {
pl: 'Przypisz każdy status PrestaShop do odpowiednika w Orbito. Przy imporcie używane jest current_state z zamówienia PS.',
en: 'Map each PrestaShop state to an Orbito status. Import uses current_state from the PS order.'
}
}
};
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;
}
}
});
Log.info('PrestaShop: zarejestrowano bloki konfiguracji Config');
}
module.exports = { registerPrestashopConfigBlocks };
+29
View File
@@ -0,0 +1,29 @@
const { Core, Log } = require('@orbito/api-lib');
const PERMISSIONS = {
ORDERS_VIEW: 'orders.view',
ORDERS_IMPORT: 'orders.import',
};
async function registerPrestashopPermissions() {
await Core.registerPermission(PERMISSIONS.ORDERS_VIEW, 'Podgląd zamówień PrestaShop');
await Core.registerPermission(PERMISSIONS.ORDERS_IMPORT, 'Import zamówień z PrestaShop');
Log.info('PrestaShop: zarejestrowano uprawnienia');
}
/**
* Egzekwuje uprawnienie — rzuca PERMISSION_DENIED gdy brak dostępu.
* @param {string} code
* @param {{ permissions?: string[] }} ctx
*/
function requirePermission(code, ctx) {
if (!Core.hasPermission(code, ctx?.permissions)) {
throw new Error('PERMISSION_DENIED');
}
}
module.exports = {
PERMISSIONS,
registerPrestashopPermissions,
requirePermission,
};