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
+20 -11
View File
@@ -1,19 +1,26 @@
const { Log, Core, Utils, Pages, DB } = require('@orbito/api-lib');
const { Log, Core, Utils } = require('@orbito/api-lib');
const CronJob = require('cron').CronJob;
const ShopConfigSchema = require('./src/models/ShopConfig');
const PsOrder = require('./src/models/PsOrder');
const PrestashopApi = require('./src/PrestaApi');
const { importFromPSOrder } = require('./src/OrderImporter');
const { isLegacyApi } = require('./src/utils');
const { loadEnabledConfigs, setLastOrderId } = require('./src/module-config');
const { registerPrestashopConfigBlocks } = require('./src/register-config');
const { registerPrestashopPermissions } = require('./src/register-permissions');
const NEW_ORDERS_WINDOW_MS = 20 * 60 * 1000;
const OLDER_ORDERS_WINDOW_MS = 5 * 24 * 60 * 60 * 1000;
const unpaidFilter = { $or: [{ paymentSyncedAt: { $exists: false } }, { paymentSyncedAt: null }] };
Utils.loadMethods(__dirname + '/methods');
const configPage = require('./pages/config');
Pages.registerPage('/config', { en: "Configuration", pl: "Konfiguracja" }, configPage);
Pages.registerPage('/config/:_t', { en: "Configuration", pl: "Konfiguracja" }, configPage);
registerPrestashopConfigBlocks().catch(err => {
Log.error('PrestaShop: nie udało się zarejestrować bloków Config', { error: err?.message });
});
registerPrestashopPermissions().catch(err => {
Log.error('PrestaShop: nie udało się zarejestrować uprawnień', { error: err?.message });
});
const ordersPuller = new CronJob("0 */5 * * * *", async () => {
const lockId = await Core.getLock('prestashop-orders-puller', 290000);
@@ -22,8 +29,7 @@ const ordersPuller = new CronJob("0 */5 * * * *", async () => {
try {
let enabledShops = [];
try {
let shopConfigs = await ShopConfigSchema.find({ isRemoved: { $ne: true } });
enabledShops = shopConfigs.filter(config => config.apiUrl && config.apiKey);
enabledShops = await loadEnabledConfigs();
} catch (error) {
Log.error( 'Error fetching shop configs', { error: error.message });
}
@@ -41,7 +47,8 @@ const ordersPuller = new CronJob("0 */5 * * * *", async () => {
if (res.orders && res.orders.length > 0) {
const lastOrderId = parseInt(res.orders[0].id);
await ShopConfigSchema.update({ _id: config._id }, { lastOrderId: lastOrderId });
await setLastOrderId(lastOrderId);
config.lastOrderId = lastOrderId;
}
continue;
@@ -106,7 +113,9 @@ const ordersPuller = new CronJob("0 */5 * * * *", async () => {
}
}
await ShopConfigSchema.update({ _id: config._id }, { lastOrderId: config.lastProcessedId });
if (config.lastProcessedId) {
await setLastOrderId(config.lastProcessedId);
}
} catch (error) {
Log.error( 'Error pulling orders for shop config', { shopConfigId: config._id, error: error.message });
}
@@ -175,7 +184,7 @@ const paymentsSyncNew = new CronJob('0 */3 * * * *', async () => {
const lockId = await Core.getLock('prestashop-payments-new', 120000);
if (!lockId) return;
try {
const configs = (await ShopConfigSchema.find({ isRemoved: { $ne: true } })).filter(c => c.apiUrl && c.apiKey);
const configs = await loadEnabledConfigs();
const since = new Date(Date.now() - NEW_ORDERS_WINDOW_MS);
for (const config of configs) {
try {
@@ -195,7 +204,7 @@ const paymentsSyncOlder = new CronJob('0 */30 * * * *', async () => {
const lockId = await Core.getLock('prestashop-payments-older', 300000);
if (!lockId) return;
try {
const configs = (await ShopConfigSchema.find({ isRemoved: { $ne: true } })).filter(c => c.apiUrl && c.apiKey);
const configs = await loadEnabledConfigs();
const now = Date.now();
const since = new Date(now - OLDER_ORDERS_WINDOW_MS);
const until = new Date(now - NEW_ORDERS_WINDOW_MS);
-18
View File
@@ -1,18 +0,0 @@
const { Log } = require('@orbito/api-lib');
const ShopConfig = require('../../src/models/ShopConfig');
const { toFormResponse } = require('../../src/config-form');
module.exports = async function(params, ctx) {
const config = await ShopConfig.findOne({ isRemoved: { $ne: true } });
const form = toFormResponse(config);
Log.debug( 'config.get', {
found: Boolean(config),
storeUrl: form.storeUrl,
shopPrefix: form.shopPrefix,
hasApiKey: form.hasApiKey,
psStatesCount: form.psStates?.length ?? 0
});
return { data: form };
};
-60
View File
@@ -1,60 +0,0 @@
const { Log } = require('@orbito/api-lib');
const PrestashopApi = require('../../src/PrestaApi');
const ShopConfig = require('../../src/models/ShopConfig');
const { isLegacyApi } = require('../../src/utils');
const { extractPsStateName } = require('../../src/status-mapper');
const { normalizeFormParams } = require('../../src/config-form');
const { methodOk, methodFail } = require('../../src/method-result');
module.exports = async function(params, ctx) {
const existing = await ShopConfig.findOne({ isRemoved: { $ne: true } });
const input = normalizeFormParams(params);
const storeUrl = (input.storeUrl || existing?.apiUrl || '').trim();
const apiKey = (input.apiKey || '').trim() || existing?.apiKey || '';
const versionCode = input.versionCode ?? existing?.versionCode ?? '';
if (!storeUrl || !apiKey) {
return methodFail('Podaj URL sklepu i klucz API (zapisz konfigurację lub uzupełnij formularz)');
}
let api;
try {
api = new PrestashopApi(storeUrl, apiKey, isLegacyApi(versionCode));
} catch (e) {
return methodFail('Nieprawidłowy URL sklepu: ' + e.message);
}
try {
const rawStates = await api.getStatuses();
const psStates = (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'
}));
const payload = {
apiUrl: storeUrl,
apiKey,
psStates
};
if (existing) {
await ShopConfig.update({ _id: existing._id }, payload);
Log.info( 'PrestaShop order states saved', { configId: existing._id, count: psStates.length });
} else {
await ShopConfig.create({
...payload,
shopPrefix: (input.shopPrefix || '').trim()
});
Log.info( 'PrestaShop config created with order states', { count: psStates.length });
}
return methodOk({ count: psStates.length, psStates });
} catch (e) {
Log.warn( 'config.get_ps_states failed', { storeUrl, error: e.message });
return methodFail('Nie udało się pobrać statusów: ' + (e.message || 'błąd API PrestaShop'));
}
};
-13
View File
@@ -1,13 +0,0 @@
const ShopConfig = require('../../src/models/ShopConfig');
const { buildMappingRows } = require('../../src/config-form');
// Zwraca wiersze UI mapowania statusów PS → Orbito (tablica dla widoku type: list).
module.exports = async function(params, ctx) {
const config = await ShopConfig.findOne({ isRemoved: { $ne: true } });
if (!config) return [];
const psStates = Array.isArray(config.psStates) ? config.psStates : [];
const statusMapping = Array.isArray(config.statusMapping) ? config.statusMapping : [];
return buildMappingRows(psStates, statusMapping);
};
-14
View File
@@ -1,14 +0,0 @@
const { Log } = require('@orbito/api-lib');
const ShopConfig = require('../../src/models/ShopConfig');
const { methodOk } = require('../../src/method-result');
module.exports = async function(params, ctx) {
const configs = await ShopConfig.find({ isRemoved: { $ne: true } });
for (const config of configs) {
await ShopConfig.update({ _id: config._id }, { isRemoved: true });
}
Log.info( 'PrestaShop config reset', { removed: configs.length });
return methodOk({ removed: configs.length });
};
-43
View File
@@ -1,43 +0,0 @@
const { Log } = require('@orbito/api-lib');
const ShopConfig = require('../../src/models/ShopConfig');
const { toFormResponse, buildSavePayload, normalizeFormParams } = require('../../src/config-form');
const { methodOk, methodFail } = require('../../src/method-result');
module.exports = async function(params, ctx) {
try {
const input = normalizeFormParams(params);
const existing = await ShopConfig.findOne({ isRemoved: { $ne: true } });
Log.debug( 'config.save input', {
keys: Object.keys(input),
storeUrl: input.storeUrl,
shopPrefix: input.shopPrefix,
shopName: input.shopName
});
const data = buildSavePayload(input, existing);
if (!data.apiUrl) {
return methodFail('URL sklepu jest wymagany. Wpisz adres w polu „URL sklepu” i spróbuj ponownie.');
}
if (!data.apiKey) {
return methodFail('Klucz API jest wymagany. Wpisz klucz Webservice API lub zachowaj już zapisany.');
}
const payload = { ...data };
if (existing) {
await ShopConfig.update({ _id: existing._id }, payload);
Log.info( 'PrestaShop config updated', { configId: existing._id });
const updated = await ShopConfig.findOne({ _id: existing._id });
return methodOk({ data: toFormResponse(updated) });
}
const created = await ShopConfig.create(payload);
Log.info( 'PrestaShop config created', { configId: created._id });
return methodOk({ data: toFormResponse(created) });
} catch (err) {
Log.error( 'config.save failed', { error: err?.message });
return methodFail(err?.message || 'Nie udało się zapisać konfiguracji');
}
};
-41
View File
@@ -1,41 +0,0 @@
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');
}
};
-38
View File
@@ -1,38 +0,0 @@
const { Log } = require('@orbito/api-lib');
const PrestashopApi = require('../../src/PrestaApi');
const ShopConfig = require('../../src/models/ShopConfig');
const { isLegacyApi } = require('../../src/utils');
const { normalizeFormParams } = require('../../src/config-form');
const { methodOk, methodFail } = require('../../src/method-result');
module.exports = async function(params, ctx) {
const existing = await ShopConfig.findOne({ isRemoved: { $ne: true } });
const input = normalizeFormParams(params);
const storeUrl = (input.storeUrl || existing?.apiUrl || '').trim();
const apiKey = (input.apiKey || '').trim() || existing?.apiKey || '';
if (!storeUrl || !apiKey) {
return methodFail('Podaj URL sklepu oraz klucz API przed testem połączenia');
}
let api;
try {
api = new PrestashopApi(storeUrl, apiKey, isLegacyApi(input.versionCode ?? existing?.versionCode));
} catch (e) {
return methodFail('Nieprawidłowy URL sklepu: ' + e.message);
}
try {
const statuses = await api.getStatuses();
if (!statuses) {
return methodFail('API nie zwróciło danych (sprawdź klucz Webservice i uprawnienia)');
}
const count = Array.isArray(statuses) ? statuses.length : undefined;
Log.info( 'PrestaShop connection test OK', { storeUrl, statusesCount: count });
return methodOk({ statusesCount: count });
} catch (e) {
Log.warn( 'PrestaShop connection test failed', { storeUrl, error: e.message });
return methodFail('Połączenie nieudane: ' + (e.message || 'błąd API PrestaShop'));
}
};
-14
View File
@@ -1,14 +0,0 @@
const { DB, Utils, Log } = require('@orbito/api-lib');
const ShopConfigSchema = require('../src/models/ShopConfig');
module.exports = async function(params, ctx) {
const { _id } = params;
if (!_id) throw new Error('Missing _id');
const config = await ShopConfigSchema.findOne({ _id, isRemoved: { $ne: true } });
if (!config) throw new Error('Config not found');
await ShopConfigSchema.update({ _id }, { isRemoved: true });
return { success: true };
}
-30
View File
@@ -1,30 +0,0 @@
const { DB, Utils, Log } = require('@orbito/api-lib');
const ShopConfigSchema = require('../src/models/ShopConfig');
const PrestashopApi = require('../src/PrestaApi');
module.exports = async function(params, ctx) {
const page = parseInt(params.page) || 1;
const perPage = parseInt(params.perPage) || 10;
const skip = (page - 1) * perPage;
const query = { isRemoved: { $ne: true } };
const results = await ShopConfigSchema.find(query, perPage, skip, { createdAt: -1 });
const total = await ShopConfigSchema.count(query);
const resultsWithStatus = await Promise.all(results.map(async (config) => {
if (!config.apiUrl || !config.apiKey) {
return { ...config, connected: false };
}
try {
const api = new PrestashopApi(config.apiUrl, config.apiKey);
await api.getStatuses();
return { ...config, connected: true };
} catch (e) {
return { ...config, connected: false };
}
}));
return { results: resultsWithStatus, total, page, perPage };
}
+4 -1
View File
@@ -1,6 +1,9 @@
const { getFilters } = require('../../src/orders-filter-store');
const { PERMISSIONS, requirePermission } = require('../../src/register-permissions');
module.exports = async function(params, ctx) {
requirePermission(PERMISSIONS.ORDERS_VIEW, ctx);
module.exports = async function() {
const filters = await getFilters();
return {
page: parseInt(filters.page, 10) || 1,
+3
View File
@@ -2,8 +2,11 @@ const { Log } = require('@orbito/api-lib');
const { searchOrders } = require('../../src/orders-api');
const { normalizeFilterParams, FILTER_KEYS } = require('../../src/orders-filter-form');
const { getFilters, mergeFilters, clearFilters } = require('../../src/orders-filter-store');
const { PERMISSIONS, requirePermission } = require('../../src/register-permissions');
module.exports = async function(params, ctx) {
requirePermission(PERMISSIONS.ORDERS_VIEW, ctx);
const input = { ...(params || {}) };
if (input.clearFilters) {
+6 -4
View File
@@ -1,14 +1,16 @@
const ShopConfig = require('../../src/models/ShopConfig');
const PrestashopApi = require('../../src/PrestaApi');
const { isLegacyApi } = require('../../src/utils');
const { loadConfig, isConfigured } = require('../../src/module-config');
const { PERMISSIONS, requirePermission } = require('../../src/register-permissions');
module.exports = async function(params, ctx) {
requirePermission(PERMISSIONS.ORDERS_VIEW, ctx);
const productIds = Array.isArray(params?.productIds) ? params.productIds : [];
if (productIds.length === 0) return {};
const configs = await ShopConfig.find({ isRemoved: { $ne: true } });
const config = configs.find(c => c.apiUrl && c.apiKey);
if (!config) return {};
const config = await loadConfig();
if (!isConfigured(config)) return {};
const api = new PrestashopApi(config.apiUrl, config.apiKey, isLegacyApi(config.versionCode));
const result = {};
+2
View File
@@ -1,6 +1,8 @@
const { Core } = require('@orbito/api-lib');
const { PERMISSIONS, requirePermission } = require('../../src/register-permissions');
// Proxy do core/orders — statusy są współdzielone i zarządzane w core/orders.
module.exports = async function(params, ctx) {
requirePermission(PERMISSIONS.ORDERS_VIEW, ctx);
return Core.callModule('core/orders', 'status.get_with_counts', params || {});
};
+6 -11
View File
@@ -1,20 +1,15 @@
const { Core } = require('@orbito/api-lib');
const ShopConfig = require('../src/models/ShopConfig');
const PrestashopApi = require('../src/PrestaApi');
const { importFromPSOrder } = require('../src/OrderImporter');
const { isLegacyApi } = require('../src/utils');
const { loadConfig, isConfigured, setLastOrderId } = require('../src/module-config');
const { PERMISSIONS, requirePermission } = require('../src/register-permissions');
module.exports = async function(params, ctx) {
const configs = await ShopConfig.find({ isRemoved: { $ne: true } });
const active = configs.filter(c => c.apiUrl && c.apiKey);
requirePermission(PERMISSIONS.ORDERS_IMPORT, ctx);
if (active.length === 0) return { error: 'No active shop configs found' };
const config = params.configId
? active.find(c => String(c._id) === String(params.configId))
: active[0];
if (!config) return { error: 'Config not found' };
const config = await loadConfig();
if (!isConfigured(config)) return { error: 'No active shop configs found' };
const api = new PrestashopApi(config.apiUrl, config.apiKey, isLegacyApi(config.versionCode));
@@ -49,7 +44,7 @@ module.exports = async function(params, ctx) {
}
}
const maxId = Math.max(...orders.map(o => parseInt(o.id)));
await ShopConfig.update({ _id: config._id }, { lastOrderId: maxId });
await setLastOrderId(maxId);
return { shopName: config.shopName, imported, errors, newLastOrderId: maxId };
}
-25
View File
@@ -1,25 +0,0 @@
const { DB, Utils, Log } = require('@orbito/api-lib');
const ShopConfigSchema = require('../src/models/ShopConfig');
module.exports = async function(params, ctx) {
const editableFields = ['apiUrl', 'apiKey', 'shopName', 'versionCode', 'orderStatus'];
const dataToUpdate = {};
for (const field of editableFields) {
if (typeof params[field] !== 'undefined') {
dataToUpdate[field] = params[field];
}
}
// Jeśli podano _id – aktualizuj konkretny rekord
if (params._id) {
const config = await ShopConfigSchema.findOne({ _id: params._id, isRemoved: { $ne: true } });
if (!config) throw new Error('Config not found');
await ShopConfigSchema.update({ _id: config._id }, dataToUpdate);
return await ShopConfigSchema.findOne({ _id: config._id });
}
// Brak _id – twórz nowy rekord
const newConfig = await ShopConfigSchema.create(dataToUpdate);
return newConfig;
}
+4 -4
View File
@@ -9,7 +9,7 @@
"version": "1.0.0",
"license": "ISC",
"dependencies": {
"@orbito/api-lib": "^2.0.0",
"@orbito/api-lib": "^2.2.1",
"cron": "^4.4.0",
"dotenv": "^17.2.3",
"ejs": "^4.0.1",
@@ -20,9 +20,9 @@
}
},
"node_modules/@orbito/api-lib": {
"version": "2.0.0",
"resolved": "https://git.kozminski.net.pl/api/packages/orbito/npm/%40orbito%2Fapi-lib/-/2.0.0/api-lib-2.0.0.tgz",
"integrity": "sha512-KFdQuUB+3X1TkKLYTNGLcXdC6FlynLcTEJalxJyuJa1iVHBVuQuPRC2kUJN3HsizngIaEP2jJK3Bmi+jCqtPfQ==",
"version": "2.2.1",
"resolved": "https://git.kozminski.net.pl/api/packages/orbito/npm/%40orbito%2Fapi-lib/-/2.2.1/api-lib-2.2.1.tgz",
"integrity": "sha512-y0xFkU8IIObdniRiuEX9t4+gOxdwA3t6+a7xkJVvAogB4+4r+7Vlo9VNW9w6GABXX5xTrSIsPRkx/I1lnVdsVQ==",
"license": "ISC",
"dependencies": {
"bson": "^6.10.4",
+1 -1
View File
@@ -10,7 +10,7 @@
"author": "",
"license": "ISC",
"dependencies": {
"@orbito/api-lib": "^2.0.0",
"@orbito/api-lib": "^2.2.1",
"cron": "^4.4.0",
"dotenv": "^17.2.3",
"ejs": "^4.0.1",
-370
View File
@@ -1,370 +0,0 @@
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;');
}
-135
View File
@@ -1,135 +0,0 @@
const { Log, Core, Utils, Pages } = require('@orbito/api-lib');
const ShopConfig = require('../src/models/ShopConfig');
module.exports = async function(body, params) {
const configId = params.shopId;
const isEdit = !!configId;
let config = null;
if (isEdit) {
config = await ShopConfig.findOne({ _id: configId, isRemoved: { $ne: true } });
if (!config) throw new Error('Config not found');
}
const res = await Core.callModule( 'core/orders', 'status.search', {});
const orderStatuses = res.results || [];
return {
type: 'ove',
template: {
type: 'card',
title: isEdit ? `Edytuj konfigurację: ${config.shopName || configId}` : 'Nowa konfiguracja sklepu',
description: isEdit
? 'Zaktualizuj dane połączenia ze sklepem Prestashop.'
: 'Uzupełnij dane połączenia z nowym sklepem Prestashop.',
content: [
{
type: 'row',
cols: [
{
size: 6,
childs: [
{
type: 'input',
name: 'shopName',
inputType: 'text',
label: 'Nazwa sklepu',
value: config?.shopName || '',
groups: ['config-data']
}
]
},
{
size: 6,
childs: [
{
type: 'select',
name: 'versionCode',
label: 'Wersja sklepu',
value: config?.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: ['config-data']
}
]
},
{
size: 12,
childs: [
{
type: 'input',
name: 'apiUrl',
inputType: 'text',
label: 'API URL',
placeholder: 'https://sklep.pl/api',
value: config?.apiUrl || '',
groups: ['config-data']
},
{
type: 'input',
name: 'apiKey',
inputType: 'text',
label: 'API Key',
placeholder: 'Klucz API Prestashop',
value: config?.apiKey || '',
groups: ['config-data']
},
{
type: 'select',
name: 'orderStatus',
label: 'Domyślny status zamówienia po pobraniu z Prestashop',
value: config?.orderStatus || '',
options: orderStatuses.map(status => ({ id: status._id, label: status.name })),
groups: ['config-data']
}
]
}
]
}
],
footer: [
{
type: 'button',
label: 'Wróć do listy',
variant: 'secondary',
outline: true,
icon: 'arrow-left',
onClick: {
action: 'emit',
event: 'generatePage',
data: {
module: 'core/prestashop',
page: 'config'
}
}
},
{
type: 'button',
label: isEdit ? 'Zapisz zmiany' : 'Utwórz konfigurację',
variant: 'primary',
icon: 'device-floppy',
groups: ['config-data'],
onClick: {
action: 'callMethod',
module: 'core/prestashop',
method: 'updateConfig',
params: isEdit ? { _id: configId } : {},
withData: ['#config-data'],
then: {
action: 'emit',
event: 'generatePage',
data: {
module: 'core/prestashop',
page: 'config'
}
}
}
}
]
}
};
}
+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,
};