Initial commit: core-prestashop module v1.1.1

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
fatequod
2026-07-07 14:30:30 +02:00
co-authored by Cursor
commit f163100ad4
33 changed files with 2605 additions and 0 deletions
+18
View File
@@ -0,0 +1,18 @@
const { Log } = require('@orbito/api-lib');
const ShopConfig = require('../../src/models/ShopConfig');
const { toFormResponse } = require('../../src/config-form');
module.exports = async function(companyId, instanceId, params, ctx) {
const config = await ShopConfig.findOne({ companyId, isRemoved: { $ne: true } });
const form = toFormResponse(config);
Log.debug(companyId, 'config.get', {
found: Boolean(config),
storeUrl: form.storeUrl,
shopPrefix: form.shopPrefix,
hasApiKey: form.hasApiKey,
psStatesCount: form.psStates?.length ?? 0
});
return { data: form };
};
+61
View File
@@ -0,0 +1,61 @@
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(companyId, instanceId, params, ctx) {
const existing = await ShopConfig.findOne({ companyId, 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(companyId, 'PrestaShop order states saved', { configId: existing._id, count: psStates.length });
} else {
await ShopConfig.create({
companyId,
...payload,
shopPrefix: (input.shopPrefix || '').trim()
});
Log.info(companyId, 'PrestaShop config created with order states', { count: psStates.length });
}
return methodOk({ count: psStates.length, psStates });
} catch (e) {
Log.warn(companyId, '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
@@ -0,0 +1,13 @@
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(companyId, instanceId, params, ctx) {
const config = await ShopConfig.findOne({ companyId, 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
@@ -0,0 +1,14 @@
const { Log } = require('@orbito/api-lib');
const ShopConfig = require('../../src/models/ShopConfig');
const { methodOk } = require('../../src/method-result');
module.exports = async function(companyId, instanceId, params, ctx) {
const configs = await ShopConfig.find({ companyId, isRemoved: { $ne: true } });
for (const config of configs) {
await ShopConfig.update({ _id: config._id }, { isRemoved: true });
}
Log.info(companyId, 'PrestaShop config reset', { removed: configs.length });
return methodOk({ removed: configs.length });
};
+43
View File
@@ -0,0 +1,43 @@
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(companyId, instanceId, params, ctx) {
try {
const input = normalizeFormParams(params);
const existing = await ShopConfig.findOne({ companyId, isRemoved: { $ne: true } });
Log.debug(companyId, '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 = { companyId, ...data };
if (existing) {
await ShopConfig.update({ _id: existing._id }, payload);
Log.info(companyId, '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(companyId, 'PrestaShop config created', { configId: created._id });
return methodOk({ data: toFormResponse(created) });
} catch (err) {
Log.error(companyId, 'config.save failed', { error: err?.message });
return methodFail(err?.message || 'Nie udało się zapisać konfiguracji');
}
};
+38
View File
@@ -0,0 +1,38 @@
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(companyId, instanceId, params, ctx) {
const existing = await ShopConfig.findOne({ companyId, 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(companyId, 'PrestaShop connection test OK', { storeUrl, statusesCount: count });
return methodOk({ statusesCount: count });
} catch (e) {
Log.warn(companyId, 'PrestaShop connection test failed', { storeUrl, error: e.message });
return methodFail('Połączenie nieudane: ' + (e.message || 'błąd API PrestaShop'));
}
};
+14
View File
@@ -0,0 +1,14 @@
const { DB, Utils, Log } = require('@orbito/api-lib');
const ShopConfigSchema = require('../src/models/ShopConfig');
module.exports = async function(companyId, instanceId, params, ctx) {
const { _id } = params;
if (!_id) throw new Error('Missing _id');
const config = await ShopConfigSchema.findOne({ _id, companyId, isRemoved: { $ne: true } });
if (!config) throw new Error('Config not found');
await ShopConfigSchema.update({ _id }, { isRemoved: true });
return { success: true };
}
+30
View File
@@ -0,0 +1,30 @@
const { DB, Utils, Log } = require('@orbito/api-lib');
const ShopConfigSchema = require('../src/models/ShopConfig');
const PrestashopApi = require('../src/PrestaApi');
module.exports = async function(companyId, instanceId, params, ctx) {
const page = parseInt(params.page) || 1;
const perPage = parseInt(params.perPage) || 10;
const skip = (page - 1) * perPage;
const query = { companyId, 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 };
}
+11
View File
@@ -0,0 +1,11 @@
const { getFilters } = require('../../src/orders-filter-store');
// Zwraca zapisaną paginację / filtry listy zamówień (np. przed powrotem ze szczegółów).
module.exports = async function(companyId, instanceId) {
const filters = await getFilters(companyId, instanceId);
return {
page: parseInt(filters.page, 10) || 1,
perPage: parseInt(filters.perPage, 10) || 20,
filters,
};
};
+59
View File
@@ -0,0 +1,59 @@
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');
// orders.search — proxy do core/orders 'search' (tylko PrestaShop).
// Akceptuje stary format: { searchQuery, paidOnly, pagination: { page, limit, sort } }
// oraz pola filtrów (city, customerEmail lub filterCity, filterCustomerEmail z withData).
// saveFilters: true — zapisuje filtry z żądania (np. przycisk Filtruj), żeby reload tabeli je zachował.
// clearFilters: true — czyści zapisane filtry.
module.exports = async function(companyId, instanceId, params, ctx) {
const input = { ...(params || {}) };
if (input.clearFilters) {
clearFilters(companyId, instanceId);
delete input.clearFilters;
Log.info(companyId, 'orders.search clearFilters', { instanceId });
}
if (input.saveFilters) {
await mergeFilters(companyId, instanceId, input);
delete input.saveFilters;
Log.info(companyId, 'orders.search saveFilters', { instanceId, filters: await getFilters(companyId, instanceId) });
}
const stored = await getFilters(companyId, instanceId);
const normalizedInput = normalizeFilterParams(input);
const merged = { ...stored, ...normalizedInput };
// Puste pola filtrów z żądania datatable (reload) nie mogą skasować
// filtrów zapisanych przez saveFilters.
for (const key of FILTER_KEYS) {
if (normalizedInput[key] === '' && stored[key]) {
merged[key] = stored[key];
}
}
const explicitPage = input.explicitPage === true || input.explicitPage === 'true';
delete merged.explicitPage;
const storedPage = parseInt(stored.page, 10) || 1;
const incomingPage = parseInt(merged.page, 10) || 1;
// Po powrocie ze szczegółów datatable startuje z page=1 — przywróć zapisaną stronę.
// explicitPage=true oznacza świadomą zmianę strony w pagerze (nie nadpisuj).
if (!explicitPage && !input.saveFilters && storedPage > 1 && incomingPage === 1) {
merged.page = String(storedPage);
}
const finalParams = normalizeFilterParams(merged);
const result = await searchOrders(companyId, finalParams);
await mergeFilters(companyId, instanceId, {
page: String(finalParams.page || 1),
perPage: String(finalParams.perPage || 20),
});
return result;
};
+24
View File
@@ -0,0 +1,24 @@
const ShopConfig = require('../../src/models/ShopConfig');
const PrestashopApi = require('../../src/PrestaApi');
const { isLegacyApi } = require('../../src/utils');
module.exports = async function (companyId, instanceId, params, ctx) {
const productIds = Array.isArray(params?.productIds) ? params.productIds : [];
if (productIds.length === 0) return {};
const configs = await ShopConfig.find({ companyId, isRemoved: { $ne: true } });
const config = configs.find(c => c.apiUrl && c.apiKey);
if (!config) return {};
const api = new PrestashopApi(config.apiUrl, config.apiKey, isLegacyApi(config.versionCode));
const result = {};
for (const productId of productIds) {
try {
const url = await api.getProductCoverImageUrl(productId);
if (url) result[String(productId)] = url;
} catch (_) { /* product not found or no image */ }
}
return result;
};
+41
View File
@@ -0,0 +1,41 @@
const { getOrderStatuses, searchOrders } = require('../../src/orders-api');
// status.get_with_counts — lista statusów zamówień (z core/orders) wraz z liczbą
// zamówień PrestaShop w każdym statusie. Wynik krótko cache'owany per firma,
// bo zlicza N zapytań (po jednym na status).
const cache = new Map();
const CACHE_TTL = 5000;
module.exports = async function(companyId, instanceId, params, ctx) {
const key = companyId?.toString?.() ?? companyId;
const now = Date.now();
const cached = cache.get(key);
if (cached && now - cached.ts < CACHE_TTL) {
return { data: cached.data };
}
const statuses = await getOrderStatuses(companyId);
const data = [];
for (const status of statuses) {
const statusId = status._id?.toString?.() ?? status._id;
const result = await searchOrders(companyId, {
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(key, { ts: now, data });
return { data };
};
+64
View File
@@ -0,0 +1,64 @@
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');
module.exports = async function (companyId, instanceId, params, ctx) {
const configs = await ShopConfig.find({ companyId, isRemoved: { $ne: true } });
const active = configs.filter(c => c.apiUrl && c.apiKey);
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 api = new PrestashopApi(config.apiUrl, config.apiKey, isLegacyApi(config.versionCode));
const queryParams = {
display: '[id, reference, date_add]',
sort: 'id_ASC',
limit: 50,
output_format: 'JSON',
'filter[id]': `[${(config.lastOrderId || 0) + 1},999999999]`,
};
const raw = await api.makeRequest('orders', 'GET', queryParams);
const orders = raw?.orders || [];
if (params.import && orders.length > 0) {
const imported = [];
const errors = [];
for (const order of orders) {
const uniqueId = order.reference + ':' + order.id;
const searchResult = await Core.callModule(companyId, 'core/orders', 'search', {
source: { moduleCode: 'core/prestashop', uniqueId }
});
if (searchResult?.data?.length > 0) {
imported.push({ id: order.id, status: 'already_exists' });
continue;
}
try {
await importFromPSOrder(companyId, order.id, api, config);
imported.push({ id: order.id, status: 'imported' });
} catch (e) {
errors.push({ id: order.id, error: e.message });
}
}
const maxId = Math.max(...orders.map(o => parseInt(o.id)));
await ShopConfig.update({ _id: config._id }, { lastOrderId: maxId });
return { shopName: config.shopName, imported, errors, newLastOrderId: maxId };
}
return {
shopName: config.shopName,
lastOrderId: config.lastOrderId,
filterFrom: (config.lastOrderId || 0) + 1,
apiResponse: raw,
ordersCount: orders.length,
hint: 'Add "import": true to params to import these orders',
};
};
+25
View File
@@ -0,0 +1,25 @@
const { DB, Utils, Log } = require('@orbito/api-lib');
const ShopConfigSchema = require('../src/models/ShopConfig');
module.exports = async function(companyId, instanceId, params, ctx) {
const editableFields = ['apiUrl', 'apiKey', 'shopName', 'versionCode', 'orderStatus'];
const dataToUpdate = { companyId };
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, companyId, 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;
}