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
+5
View File
@@ -0,0 +1,5 @@
node_modules/
*.zip
.env
.DS_Store
npm-debug.log
+2
View File
@@ -0,0 +1,2 @@
@orbito:registry=https://git.kozminski.net.pl/api/packages/orbito/npm/
//git.kozminski.net.pl/api/packages/orbito/npm/:_authToken=a81c893232d822dce45bd73dfecf3e48f4e1976d
+222
View File
@@ -0,0 +1,222 @@
const { Log, Core, Utils, Pages, DB } = 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 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);
const ordersPuller = new CronJob("0 */5 * * * *", async () => {
const lockId = await Core.getLock('prestashop-orders-puller', 290000);
if (!lockId) return;
try {
let enabledShops = [];
try {
let shopConfigs = await ShopConfigSchema.find({ isRemoved: { $ne: true } });
enabledShops = shopConfigs.filter(config => config.apiUrl && config.apiKey);
} catch (error) {
Log.error(null, 'Error fetching shop configs', { error: error.message });
}
for (const config of enabledShops) {
try {
const api = new PrestashopApi(config.apiUrl, config.apiKey, isLegacyApi(config.versionCode));
if (!config.lastOrderId) {
const res = await api.makeRequest('orders', 'GET', {
display: '[id]',
sort: 'id_DESC',
limit: 1,
output_format: "JSON"
});
if (res.orders && res.orders.length > 0) {
const lastOrderId = parseInt(res.orders[0].id);
await ShopConfigSchema.update({ _id: config._id }, { lastOrderId: lastOrderId });
}
continue;
}
let queryParams = {
display: '[id, reference, date_add]',
sort: 'id_ASC',
limit: 50,
output_format: "JSON",
'filter[id]': `[${config.lastOrderId + 1},999999999]`
};
let res = await api.makeRequest('orders', 'GET', queryParams);
if (!res.orders || res.orders.length == 0) {
continue;
}
const nowMs = Date.now();
const thirtySecondsAgo = new Date(nowMs - 30 * 1000);
const newestDateStr = res.orders[res.orders.length - 1]?.date_add;
let offsetMs = 0;
if (newestDateStr) {
const parsedNewest = new Date(newestDateStr.replace(' ', 'T'));
const drift = parsedNewest.getTime() - nowMs;
if (drift > 60000) {
offsetMs = Math.round(drift / 3600000) * 3600000;
}
}
res.orders = res.orders.filter(order => {
const parsed = new Date(order.date_add.replace(' ', 'T'));
const corrected = new Date(parsed.getTime() - offsetMs);
return corrected < thirtySecondsAgo;
});
if (!res.orders || res.orders.length == 0) {
continue;
}
for (const order of res.orders) {
try {
const searchResult = await Core.callModule(config.companyId, 'core/orders', 'search', {
source: {
moduleCode: 'core/prestashop',
uniqueId: order.reference + ':' + order.id
}
});
if (searchResult?.data?.length > 0) {
config.lastProcessedId = Math.max(config.lastProcessedId || 0, parseInt(order.id));
continue;
}
await importFromPSOrder(config.companyId, order.id, api, config);
config.lastProcessedId = Math.max(config.lastProcessedId || 0, parseInt(order.id));
} catch (orderErr) {
Log.error(config.companyId, 'Failed to import PS order', { orderId: order.id, error: orderErr.message });
config.lastProcessedId = Math.max(config.lastProcessedId || 0, parseInt(order.id));
}
}
await ShopConfigSchema.update({ _id: config._id }, { lastOrderId: config.lastProcessedId });
} catch (error) {
Log.error(config.companyId, 'Error pulling orders for shop config', { shopConfigId: config._id, error: error.message });
}
}
} finally {
await Core.releaseLock(lockId);
}
});
ordersPuller.start();
async function syncPaymentsForShop(config, api, since, until, limit = 30) {
const companyId = config.companyId?.toString?.() ?? config.companyId;
const syncedAtRange = until ? { $gte: since, $lt: until } : { $gte: since };
const mappings = await PsOrder.find(
{
companyId: new DB.ObjectId(companyId),
shopConfigId: config._id,
orbitoOrderId: { $exists: true, $ne: null },
syncedAt: syncedAtRange,
...unpaidFilter,
},
limit, 0, { syncedAt: -1 }
);
if (!mappings?.length) return;
for (const m of mappings) {
try {
const orderRes = await Core.callModule(companyId, 'core/orders', 'search', { _id: m.orbitoOrderId });
const orders = Array.isArray(orderRes) ? orderRes : (orderRes?.data ?? []);
const order = orders[0];
if (order?.isPaid) {
await PsOrder.update({ _id: m._id }, { $set: { paymentSyncedAt: new Date() } });
continue;
}
const psOrder = await api.getOrder(m.psOrderId);
if (!psOrder) continue;
const totalPaidReal = parseFloat(psOrder.total_paid_real) || 0;
if (totalPaidReal <= 0) continue;
const currentPaid = order?.summary?.paid ?? 0;
const gross = order?.summary?.gross ?? totalPaidReal;
const remaining = Math.round((gross - currentPaid) * 100) / 100;
if (remaining > 0) {
const paidAmount = Math.min(remaining, Math.round(totalPaidReal * 100) / 100);
await Core.callModule(companyId, 'core/orders', 'order.payments_add', {
orderId: m.orbitoOrderId?.toString?.() ?? m.orbitoOrderId,
payment: {
amount: paidAmount,
method: psOrder.payment || 'PrestaShop',
date: new Date(psOrder.date_add),
},
});
Log.info(companyId, 'CRON: PS payment synced', { psOrderId: m.psOrderId, amount: paidAmount });
}
await PsOrder.update({ _id: m._id }, { $set: { paymentSyncedAt: new Date() } });
} catch (err) {
Log.warn(companyId, 'CRON: PS payment sync failed', { psOrderId: m.psOrderId, error: err.message });
}
}
}
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 since = new Date(Date.now() - NEW_ORDERS_WINDOW_MS);
for (const config of configs) {
try {
const api = new PrestashopApi(config.apiUrl, config.apiKey, isLegacyApi(config.versionCode));
await syncPaymentsForShop(config, api, since, null, 50);
} catch (err) {
const cid = config.companyId?.toString?.() ?? config.companyId;
Log.warn(cid, 'CRON: PS payments-new error', { error: err.message });
}
}
} finally {
await Core.releaseLock(lockId);
}
});
paymentsSyncNew.start();
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 now = Date.now();
const since = new Date(now - OLDER_ORDERS_WINDOW_MS);
const until = new Date(now - NEW_ORDERS_WINDOW_MS);
for (const config of configs) {
try {
const api = new PrestashopApi(config.apiUrl, config.apiKey, isLegacyApi(config.versionCode));
await syncPaymentsForShop(config, api, since, until, 50);
} catch (err) {
const cid = config.companyId?.toString?.() ?? config.companyId;
Log.warn(cid, 'CRON: PS payments-older error', { error: err.message });
}
}
} finally {
await Core.releaseLock(lockId);
}
});
paymentsSyncOlder.start();
Core.onEnabled(async (companyId, instanceId) => {
Log.info('Module enabled', { companyId, instanceId });
});
Executable
+35
View File
@@ -0,0 +1,35 @@
#!/bin/bash
set -euo pipefail
cd "$(dirname "$0")"
PACKAGE_NAME=$(node -p "require('./package.json').name")
if [ -z "$PACKAGE_NAME" ]; then
echo "Błąd: Nie można odczytać nazwy z package.json"
exit 1
fi
ZIP_FILE="${PACKAGE_NAME}.zip"
if [ -f "$ZIP_FILE" ]; then
rm "$ZIP_FILE"
echo "Usunięto stary plik: $ZIP_FILE"
fi
echo "Tworzenie archiwum: $ZIP_FILE"
zip -r "$ZIP_FILE" \
package.json \
index.js \
.npmrc \
src/ \
methods/ \
pages/
if [ $? -eq 0 ]; then
echo "✓ Sukces! Utworzono: $ZIP_FILE"
echo "Zawartość archiwum:"
zip -sf "$ZIP_FILE"
else
echo "✗ Błąd podczas tworzenia archiwum"
exit 1
fi
+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;
}
+22
View File
@@ -0,0 +1,22 @@
{
"name": "prestashop-module",
"version": "1.0.0",
"description": "Sample orbito module",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "node dev-server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"@orbito/api-lib": "^1.1.6",
"cron": "^4.4.0",
"dotenv": "^17.2.3",
"ejs": "^4.0.1",
"js2xmlparser": "^5.0.0",
"nanoid": "^5.1.6",
"node-cache": "^5.1.2",
"uuid": "^11.1.0"
}
}
+345
View File
@@ -0,0 +1,345 @@
const { Log } = require('@orbito/api-lib');
const ShopConfig = require('../src/models/ShopConfig');
const { toFormResponse, CONNECTION_WITH_DATA, SAVE_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 buildTemplate(form) {
const hasApiKey = Boolean(form.hasApiKey);
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: SAVE_WITH_DATA,
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: [
{ action: 'reload', target: 'statusMappingList' },
successToast('Statusy pobrane', 'Lista statusów PrestaShop została załadowana.')
]
}
},
{
type: 'list',
id: 'statusMappingList',
module: 'core/prestashop',
method: 'config.get_status_mapping',
emptyMessage: 'Brak statusów PrestaShop — kliknij „Pobierz statusy PrestaShop”.',
loadingMessage: 'Ładowanie mapowania statusów...',
template: {
type: 'row',
cols: [
{
size: 5,
childs: [{
type: 'flex',
direction: 'row',
align: 'center',
gap: 2,
childs: [
{
type: 'html',
content: '<span class="badge" style="background-color:{{ statusMappingList.$.psStateColor }};min-width:12px">&nbsp;</span>'
},
{
type: 'flex',
direction: 'column',
gap: 0,
childs: [
{
type: 'text',
content: '{{ statusMappingList.$.psStateName }}',
className: 'fw-semibold'
},
{
type: 'text',
content: 'ID PrestaShop: {{ statusMappingList.$.psStateId }}',
className: 'text-muted small'
}
]
}
]
}]
},
{
size: 7,
childs: [
{
type: 'input',
name: 'statusMappingRows.$.psStateId',
inputType: 'hidden',
value: '{{ statusMappingList.$.psStateId }}',
groups: ['form']
},
{
type: 'select',
name: 'statusMappingRows.$.orbitoStatusId',
label: 'Status Orbito',
placeholder: 'Wybierz status Orbito',
value: '{{ statusMappingList.$.orbitoStatusId }}',
allowClear: true,
optionsSource: {
module: 'core/orders',
method: 'status.search',
params: {},
labelKey: 'name',
idKey: '_id',
responsePath: 'results'
},
groups: ['form']
}
]
}
]
}
}
]
}]
}
]
};
}
module.exports = async function(companyId, instanceId, body, params) {
try {
const config = await ShopConfig.findOne({ companyId, isRemoved: { $ne: true } });
const form = toFormResponse(config);
return {
type: 'ove',
template: buildTemplate(form)
};
} catch (err) {
Log.error(companyId, '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
@@ -0,0 +1,135 @@
const { Log, Core, Utils, Pages } = require('@orbito/api-lib');
const ShopConfig = require('../src/models/ShopConfig');
module.exports = async function(companyId, instanceId, body, params) {
const configId = params.shopId;
const isEdit = !!configId;
let config = null;
if (isEdit) {
config = await ShopConfig.findOne({ _id: configId, companyId, isRemoved: { $ne: true } });
if (!config) throw new Error('Config not found');
}
const res = await Core.callModule(companyId, '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'
}
}
}
}
]
}
};
}
+323
View File
@@ -0,0 +1,323 @@
const { Log, Core, DB } = require("@orbito/api-lib");
const PsOrder = require('./models/PsOrder');
const { resolveStatusId, normalizeStatusId } = require('./status-mapper');
function getPSMultiLangField(param, langId) {
if (Array.isArray(param)) {
if (param.length === 0) return '';
if (langId) {
let lang = param.find(l => l.id == langId);
if (lang) {
return lang.value;
}
}
return param[0].value;
}
return param;
}
async function resolveImportStatusId(companyId, config) {
const statusResult = await Core.callModule(companyId, 'core/orders', 'status.search', {});
const statuses = statusResult?.results ?? [];
const byId = new Map();
for (const status of statuses) {
const id = normalizeStatusId(status._id);
if (id) byId.set(id, status);
}
const configured = normalizeStatusId(config.orderStatus);
if (configured && byId.has(configured)) {
return configured;
}
const sorted = [...statuses].sort(
(a, b) => (a.positionInGroup ?? 0) - (b.positionInGroup ?? 0)
);
return normalizeStatusId(sorted[0]?._id);
}
async function importFromPSOrder(companyId, orderId, api, config) {
Log.debug(companyId, "Checking if BL is supported", { orderId });
let blSupported = await api.isBLSupported();
let endpoint = blSupported ? 'bl_order' : 'orders';
Log.debug(companyId, "Fetching order details", { endpoint: endpoint + '/' + orderId });
let { order } = await api.makeRequest(endpoint + '/' + orderId, 'GET', { output_format: "JSON" });
if (!order) {
Log.error(companyId, "Order not found", orderId);
return;
}
Log.info(companyId, "Importing order: " + order.reference);
let products = [];
for (let product of order.associations.order_rows) {
let unitPriceNet = parseFloat(product.unit_price_tax_excl); // jednak cen nie możemy zaokrąglać, bo presta pracuje w cenach brutto
let unitPriceGross = parseFloat(product.unit_price_tax_incl);
let taxRate = unitPriceNet ? (unitPriceGross - unitPriceNet) / unitPriceNet : 0;
const p = {
name: product.product_name,
sourceId: product.product_id,
sku: product.product_reference,
ean: product.product_ean13,
unitPrice: unitPriceNet,
tax: taxRate ? Math.round(taxRate * 100) / 100 : 0,
qty: parseFloat(product.product_quantity)
};
const psProduct = await api.getProduct(product.product_id);
Log.debug(companyId, "Fetched product details: " + getPSMultiLangField(psProduct.name));
p.weight = parseFloat(psProduct.weight);
try {
const imgUrl = await api.getProductCoverImageUrl(product.product_id);
if (imgUrl) p.coverImageUrl = imgUrl;
} catch (_) { /* no image available */ }
if (parseInt(product.product_attribute_id) > 0) {
const combination = await api.getProductCombination(product.product_attribute_id);
if (combination) {
const w = parseFloat(combination.weight);
if (!isNaN(w)) p.weight = w;
}
}
if (psProduct.type == "pack" && psProduct.associations.product_bundle) {
p.isPack = true;
p.pack = [];
for (const packItem of psProduct.associations.product_bundle) {
const psItem = await api.getProduct(packItem.id);
const pData = {
name: getPSMultiLangField(psItem.name),
sourceId: psItem.id,
sku: psItem.reference,
ean: psItem.ean13,
weight: parseFloat(psItem.weight),
qty: parseFloat(packItem.quantity)
};
if (parseInt(packItem.id_product_attribute) > 0) {
const combination = await api.getProductCombination(packItem.id_product_attribute);
if (combination) {
const w = parseFloat(combination.weight);
if (!isNaN(w)) pData.weight = w;
pData.sku = combination.reference || pData.sku;
}
}
try {
const imgUrl = await api.getProductCoverImageUrl(packItem.id);
if (imgUrl) pData.coverImageUrl = imgUrl;
} catch (_) { /* no image */ }
p.pack.push(pData);
}
}
products.push(p);
}
await Promise.all(
products
.filter(p => p.sourceId && p.name)
.map(p => Core.callModule(companyId, 'core/orders', 'product.upsert', {
sourceModule: 'core/prestashop',
sourceId: String(p.sourceId),
sku: p.sku || '',
name: p.name,
unitPrice: p.unitPrice,
ean: p.ean,
coverImageUrl: p.coverImageUrl || undefined,
}).catch(() => {}))
);
const fallbackStatusId = await resolveImportStatusId(companyId, config);
if (!fallbackStatusId) {
Log.error(companyId, 'Cannot import order — no valid order status configured', { orderId });
return;
}
const statusMapping = Array.isArray(config.statusMapping) ? config.statusMapping : [];
const statusId = resolveStatusId(order.current_state, statusMapping, fallbackStatusId);
if (!statusId) {
Log.error(companyId, 'Cannot import order — could not resolve status', {
orderId,
psStateId: order.current_state
});
return;
}
Log.info(companyId, 'Resolved order status', {
orderId,
psStateId: order.current_state,
orbitoStatusId: statusId
});
let res = await api.makeRequest('customers/' + order.id_customer, 'GET', { output_format: "JSON" });
const customer = res.customer;
Log.debug(companyId, "Fetched customer details", { email: customer.email, name: customer.firstname + " " + customer.lastname });
res = await api.makeRequest('addresses/' + order.id_address_delivery, 'GET', { output_format: "JSON" });
const address = res.address;
let carrierName = "Brak wybranej dostawy";
if (order.id_carrier) {
try {
const carrier = await api.getCarrier(order.id_carrier);
if (carrier) {
carrierName = carrier.name || "Brak nazwy";
}
} catch (e) {
Log.warn(companyId, "Error fetching carrier for order", orderId, e.message);
}
}
const currency = await api.getCurrency(order.id_currency);
const country = await api.getCountry(address.id_country);
const hasVatAndCompany = address.vat_number && address.company && address.vat_number.trim() != '' && address.company.trim() != '';
let invoiceDataForOrder = { isNeeded: false };
if ((order.id_address_invoice && order.id_address_invoice !== '0' && String(order.id_address_invoice) !== String(order.id_address_delivery)) || hasVatAndCompany) {
try {
const resInvoiceAddr = await api.makeRequest('addresses/' + order.id_address_invoice, 'GET', { output_format: "JSON" });
const invoiceAddress = resInvoiceAddr.address;
if (invoiceAddress) {
const invoiceCountry = await api.getCountry(invoiceAddress.id_country);
invoiceDataForOrder = {
isNeeded: true,
company: invoiceAddress.company || '',
taxNo: invoiceAddress.vat_number || '',
address: (invoiceAddress.address1 || '') + (invoiceAddress.address2 ? " " + invoiceAddress.address2 : ""),
city: invoiceAddress.city || '',
postCode: invoiceAddress.postcode || '',
country: invoiceCountry ? invoiceCountry.iso_code : ''
};
// Opcjonalnie: można dodać imię i nazwisko z adresu faktury, jeśli są inne i potrzebne
// invoiceDataForOrder.naturalPerson = (invoiceAddress.firstname || '') + ' ' + (invoiceAddress.lastname || '');
} else {
Log.warn(companyId, `Could not fetch invoice address details for address ID: ${order.id_address_invoice}, order ID: ${orderId}`);
}
} catch (e) {
Log.error(companyId, `Error fetching invoice address for order ID ${orderId}, address ID ${order.id_address_invoice}: ${e.message}`);
// W przypadku błędu, invoiceDataForOrder pozostaje { isNeeded: false }
}
}
const pickupPoint = {};
if (order.bl_delivery_point_id || order.bl_delivery_point_name) {
let name = order.bl_delivery_point_name;
let zipCode = order.bl_delivery_point_postcode;
let city = order.bl_delivery_point_city;
let street = order.bl_delivery_point_address;
// punkty odbioru od DPD są zapisywane jako jeden string w address
if (order.bl_delivery_point_address && !order.bl_delivery_point_postcode) {
const addressParts = order.bl_delivery_point_address.split(',', 2);
name = addressParts[0];
street = addressParts[0];
zipCode = addressParts.length > 1 ? addressParts[1].trim().split(" ")[0] : '';
city = addressParts.length > 1 ? (addressParts[1].trim().split(" ")[1] || '') : '';
}
pickupPoint.id = order.bl_delivery_point_id || order.bl_delivery_point_name;
pickupPoint.name = name;
pickupPoint.address = { street, zipCode, city };
}
const discounts = [];
if (parseFloat(order.total_discounts)) {
let net = parseFloat(order.total_discounts_tax_excl);
let gross = parseFloat(order.total_discounts_tax_incl);
let tax = net ? (gross - net) / net : 0;
discounts.push({
name: "Rabat",
amount: Math.round(net * 100) / 100,
gross: Math.round(gross * 100) / 100,
tax: Math.round(tax * 100) / 100
});
}
const totalPaidReal = parseFloat(order.total_paid_real) || 0;
const payments = [];
if (totalPaidReal > 0) {
payments.push({
amount: Math.round(totalPaidReal * 100) / 100,
method: order.payment || 'PrestaShop',
date: new Date(order.date_add),
});
}
const coreOrder = await Core.callModule(companyId, 'core/orders', 'create', {
statusId: statusId,
customer: {
name: customer.firstname + " " + customer.lastname,
email: customer.email,
phone: address.phone || address.phone_mobile
},
source: {
name: "Prestashop",
moduleCode: 'core/prestashop',
sourceId: order.id,
uniqueId: order.reference + ':' + order.id,
},
paymentMethod: order.payment,
currency: currency.iso_code,
delivery: {
type: "carrier",
carrierName: carrierName,
address: {
firstname: address.firstname,
lastname: address.lastname,
company: address.company,
street: address.address1 + (address.address2 ? " " + address.address2 : ""),
city: address.city,
postCode: address.postcode,
country: country.iso_code,
phone: address.phone || address.phone_mobile
},
pickupPoint,
cost: {
amount: parseFloat(order.total_shipping_tax_excl),
},
isCod: (order.payment + "").toLowerCase().includes("pobranie")
},
products,
payments,
discounts,
invoice: invoiceDataForOrder,
createdAt: new Date(order.date_add),
});
if (coreOrder?._id) {
const alreadyPaid = totalPaidReal > 0 && payments.length > 0;
try {
await PsOrder.create({
companyId: new DB.ObjectId(companyId),
shopConfigId: config._id,
psOrderId: parseInt(order.id),
orbitoOrderId: coreOrder._id,
reference: order.reference || '',
syncedAt: new Date(),
paymentSyncedAt: alreadyPaid ? new Date() : undefined,
});
} catch (e) {
Log.warn(companyId, 'PS order mapping save failed', { psOrderId: order.id, error: e.message });
}
}
}
module.exports = { importFromPSOrder };
module.exports = { importFromPSOrder };
+271
View File
@@ -0,0 +1,271 @@
const { Core, Log } = require('@orbito/api-lib');
const js2xmlparser = require("js2xmlparser");
const NodeCache = require("node-cache");
module.exports = class PrestashopApi {
constructor(shopUrl, apiKey, legacy = true) {
this.shopUrl = new URL(shopUrl);
this.apiKey = apiKey;
this.cache = new NodeCache({ stdTTL: 600, checkperiod: 100 });
this.legacy = legacy; // czy używać legacy API (dla PrestaShop < 8)
}
getUrl(endpoint = "") {
if (endpoint.startsWith('/')) {
endpoint = endpoint.slice(1);
}
if (this.shopUrl.pathname == '/') {
return this.shopUrl.origin + '/api/' + endpoint;
}
if (this.shopUrl.pathname.endsWith('api') || this.shopUrl.pathname.endsWith('api/')) {
return this.shopUrl.href.endsWith('/') ? this.shopUrl.href + endpoint : this.shopUrl.href + '/' + endpoint;
}
// pozostałe przypadki kiedy sklep znajduje sie w folderze np https://nanocor.eu/b2b
let href = this.shopUrl.href;
if (href.endsWith('/')) {
return href + 'api/' + endpoint;
} else {
return href + '/api/' + endpoint;
}
}
async makeRequest(endpoint, metod, data, allowPartialSuccess = false) {
// @todo przemyśleć czy nie dodac tutaj na sztywno do kazdego zapytania output_format=JSON
let url = this.getUrl(endpoint);
let options = {
method: metod,
headers: {
"Authorization": "Basic " + Buffer.from(this.apiKey + ":").toString("base64"),
'content-type': 'application/xml',
'accept': 'application/json'
}
};
if (data) {
if (metod.toLowerCase() === 'get') {
const params = new URLSearchParams(data);
url += (url.includes('?') ? '&' : '?') + params.toString();
} else {
options.body = js2xmlparser.parse("prestashop", data, {
format: {
doubleQuotes: true,
pretty: false
}
});
}
}
try {
let r = await Core.fetch(url, options);
return r.json();
} catch (error) {
// Jeśli allowPartialSuccess jest true i mamy błąd 500, sprawdź czy odpowiedź zawiera użyteczne dane
if (allowPartialSuccess && error.statusCode === 500 && error.response && error.response.body) {
try {
let parsedResponse = JSON.parse(error.response.body);
// Jeśli odpowiedź zawiera dane mimo błędu, zwróć je
if (parsedResponse && typeof parsedResponse === 'object') {
return parsedResponse;
}
} catch (parseError) {
// Jeśli nie można sparsować odpowiedzi, rzuć oryginalny błąd
}
}
throw error;
}
}
async isBLSupported() {
let cacheKey = "bl_supported";
let blSupported = this.cache.get(cacheKey);
if (typeof blSupported == 'undefined') {
try {
let res = await this.makeRequest('bl_order', 'GET', { limit: 1, output_format: "JSON" });
blSupported = res.orders && res.orders.length > 0;
} catch (e) {
blSupported = false;
}
this.cache.set(cacheKey, blSupported);
}
return blSupported;
}
async getCountry(countryId) {
let cacheKey = "country_" + countryId;
let country = this.cache.get(cacheKey);
if (!country) {
let res = await this.makeRequest('countries/' + countryId, 'GET', { output_format: "JSON" });
country = res.country;
this.cache.set(cacheKey, country);
}
return country;
}
async getCarrier(orderId) {
let cacheKey = "carrier_" + orderId;
let carrier = this.cache.get(cacheKey);
if (!carrier) {
let res = await this.makeRequest('carriers/' + orderId, 'GET', { output_format: "JSON" });
carrier = res.carrier;
this.cache.set(cacheKey, carrier);
}
return carrier;
}
async getCurrency(currencyId) {
let cacheKey = "currency_" + currencyId;
let currency = this.cache.get(cacheKey);
if (!currency) {
let res = await this.makeRequest('currencies/' + currencyId, 'GET', { output_format: "JSON" });
currency = res.currency;
this.cache.set(cacheKey, currency);
}
return currency;
}
async getProduct(productId) {
let cacheKey = "product_" + productId;
let product = this.cache.get(cacheKey);
if (!product) {
let res = await this.makeRequest('products/' + productId, 'GET', { output_format: "JSON" }, true);
if (res.product) {
product = res.product;
this.cache.set(cacheKey, product);
} else {
throw new Error("Product data not found in response");
}
}
return product;
}
async getProductCombination(combinationId) {
let cacheKey = "product_combination_" + combinationId;
let combination = this.cache.get(cacheKey);
if (!combination) {
let res = await this.makeRequest('combinations/' + combinationId, 'GET', { output_format: "JSON" });
combination = res.combination;
this.cache.set(cacheKey, combination);
}
return combination;
}
async getStatuses() {
let cacheKey = "statuses";
let statuses = this.cache.get(cacheKey);
if (!statuses) {
let res = await this.makeRequest('order_states', 'GET', { output_format: "JSON", display: '[id,name,color,deleted]' });
statuses = res.order_states;
this.cache.set(cacheKey, statuses);
}
return statuses;
}
async getOrder(orderId) {
const blSupported = await this.isBLSupported();
const endpoint = blSupported ? 'bl_order' : 'orders';
const res = await this.makeRequest(endpoint + '/' + orderId, 'GET', { output_format: 'JSON' });
return res?.order || null;
}
async getOrderPayments(orderReference) {
const res = await this.makeRequest('order_payments', 'GET', {
output_format: 'JSON',
display: 'full',
'filter[order_reference]': orderReference,
});
return res?.order_payments || [];
}
async setOrderState(orderId, stateId) {
if (this.legacy) {
return await this.updateOrderLegacy(orderId, {
current_state: stateId
});
}
return await this.updateOrder(orderId, {
current_state: stateId
});
}
async updateOrder(orderId, data) {
let res = await this.makeRequest('orders?output_format=JSON', 'PATCH', {
order: {
id: orderId,
...data
}
});
if (res && res.order && res.order.id) {
return res.order;
} else {
throw new Error("Failed to set order state");
}
}
async updateOrderLegacy(orderId, data) {
// in legacy API, we need to use PUT instead of PATCH
// and we need to sent the whole order data, not just the fields we want to update
// so we need to fetch the current order data first
let currentOrder = await this.makeRequest('orders/' + orderId + '?output_format=JSON', 'GET');
if (!currentOrder || !currentOrder.order || !currentOrder.order.id) {
throw new Error("Order not found");
}
// merge current order data with the new data
data = {
...currentOrder.order,
...data
};
let res = await this.makeRequest('orders/' + orderId + '?output_format=JSON', 'PUT', {
order: data
});
if (res && res.order && res.order.id) {
return res.order;
} else {
throw new Error("Failed to set order state");
}
}
getProductImageUrl(productId, imageId) {
const url = this.getUrl('images/products/' + productId + '/' + imageId);
const sep = url.includes('?') ? '&' : '?';
return url + sep + 'ws_key=' + encodeURIComponent(this.apiKey);
}
async getProductCoverImageUrl(productId) {
const product = await this.getProduct(productId);
const defaultImageId = product.id_default_image;
if (defaultImageId && defaultImageId !== '0' && defaultImageId !== '') {
return this.getProductImageUrl(productId, defaultImageId);
}
if (product.associations?.images?.length > 0) {
return this.getProductImageUrl(productId, product.associations.images[0].id);
}
return null;
}
async getProductImageBuffer(productId, imageId) {
let r = await Request({
url: this.getUrl('images/products/' + productId + '/' + imageId),
encoding: null,
headers : { "Authorization" : "Basic " + Buffer.from(this.apiKey + ":").toString("base64") }
});
return r;
}
};
+235
View File
@@ -0,0 +1,235 @@
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 + mapowanie statusów z listy. */
const SAVE_WITH_DATA = [...CONNECTION_WITH_DATA, 'statusMappingList'];
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 (input.statusMappingRows != null) return true;
return Object.keys(input).some(key => key.startsWith('statusMappingRows.'));
}
function extractStatusMappingRows(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) && 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)) {
return String(input[inputKey] ?? '').trim();
}
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);
const hasConnectionInput = ['storeUrl', 'apiUrl', 'apiKey', 'shopPrefix', 'shopName', 'versionCode', 'orderStatus']
.some(key => Object.prototype.hasOwnProperty.call(input, key));
const storeUrl = pickString(input, hasConnectionInput ? null : existing, 'storeUrl', 'apiUrl');
const apiKey = Object.prototype.hasOwnProperty.call(input, 'apiKey')
? ((input.apiKey || '').trim() || existing?.apiKey || '')
: (hasConnectionInput ? '' : (existing?.apiKey || ''));
const data = {
apiUrl: storeUrl,
apiKey,
shopPrefix: pickString(input, hasConnectionInput ? null : existing, 'shopPrefix'),
shopName: pickString(input, hasConnectionInput ? null : existing, 'shopName'),
};
const versionCode = normalizeSelectValue(input.versionCode);
if (versionCode || Object.prototype.hasOwnProperty.call(input, 'versionCode')) {
data.versionCode = versionCode;
} else if (existing?.versionCode) {
data.versionCode = existing.versionCode;
}
const orderStatus = normalizeSelectValue(input.orderStatus);
if (orderStatus || Object.prototype.hasOwnProperty.call(input, 'orderStatus')) {
data.orderStatus = orderStatus || null;
} else if (existing?.orderStatus) {
data.orderStatus = existing.orderStatus;
}
const mappingRows = extractStatusMappingRows(input);
if (mappingRows.length) {
data.statusMapping = mappingRows;
} else if (hasMappingInput(input)) {
data.statusMapping = [];
} else if (typeof input.statusMappingJson !== 'undefined' || typeof input.statusMapping !== 'undefined') {
data.statusMapping = parseStatusMapping(input.statusMapping ?? input.statusMappingJson);
} else if (existing?.statusMapping) {
data.statusMapping = existing.statusMapping;
}
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,
toFormResponse,
buildSavePayload
};
+13
View File
@@ -0,0 +1,13 @@
function methodOk(data = {}) {
return { success: true, ...data };
}
function methodFail(error, extra = {}) {
return {
success: false,
error: String(error || 'Nieznany błąd'),
...extra
};
}
module.exports = { methodOk, methodFail };
+11
View File
@@ -0,0 +1,11 @@
const { DB } = require('@orbito/api-lib');
const schema = new DB.Schema('prestashop_orders_list_state', {
companyId: { type: 'ObjectId' },
filters: { type: 'object', optional: true, default: {} },
updatedAt: { type: 'date', default: () => new Date() },
});
DB.createIndex('prestashop_orders_list_state', { companyId: 1 }, { unique: true });
module.exports = schema;
+20
View File
@@ -0,0 +1,20 @@
const { DB } = require('@orbito/api-lib');
const schema = new DB.Schema('ps_orders', {
companyId: { type: 'ObjectId' },
shopConfigId: { type: 'ObjectId' },
psOrderId: { type: 'number' },
orbitoOrderId: { type: 'ObjectId', optional: true },
reference: { type: 'string', optional: true, default: '' },
syncedAt: { type: 'date', optional: true, default: () => new Date() },
paymentSyncedAt: { type: 'date', optional: true },
});
schema.pre('validate', function (data) {});
schema.post('create', function (data) {});
DB.createIndex('ps_orders', { companyId: 1, psOrderId: 1, shopConfigId: 1 }, { unique: true });
DB.createIndex('ps_orders', { companyId: 1, orbitoOrderId: 1 });
DB.createIndex('ps_orders', { companyId: 1, syncedAt: -1 });
module.exports = schema;
+55
View File
@@ -0,0 +1,55 @@
const { DB } = require('@orbito/api-lib');
const { customAlphabet } = require('nanoid');
const alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const schema = new DB.Schema('shop_config', {
companyId: { type: 'ObjectId' },
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)
});
DB.createIndex('shop_config', { companyId: 1 });
module.exports = schema;
+163
View File
@@ -0,0 +1,163 @@
const { Core } = require('@orbito/api-lib');
// Helper proxy do modułu zamówień. Widoki PrestaShop (orders.search,
// status.get_with_counts) nie trzymają własnych zamówień — odpytują core/orders.
// MODULE_CODE musi pokrywać się z source.moduleCode ustawianym w OrderImporter
// podczas importu zamówień z PrestaShop ('core/prestashop'), inaczej filtr
// po źródle nie zwróci żadnych zamówień.
const MODULE_CODE = 'core/prestashop';
// Starsze importy mogły zapisać source.moduleCode jako 'prestashop'.
const MODULE_CODES = ['core/prestashop', 'prestashop'];
const ORDERS_MODULE_ID = 'core/orders';
async function callOrdersModule(companyId, method, params) {
return Core.callModule(companyId, ORDERS_MODULE_ID, method, params);
}
// Sprowadza różne kształty odpowiedzi core/orders do { data, pagination }.
function normalizeSearchResult(raw) {
if (!raw) {
return { data: [], pagination: { page: 1, perPage: 20, total: 0 } };
}
if (Array.isArray(raw)) {
return {
data: raw,
pagination: { page: 1, perPage: raw.length, total: raw.length }
};
}
const data = raw.data ?? raw.items ?? raw.results ?? [];
const pagination = raw.pagination ?? {
page: raw.page ?? 1,
perPage: raw.perPage ?? data.length,
total: raw.total ?? data.length
};
return { data, pagination };
}
function isUsableParam(value) {
const trimmed = String(value ?? '').trim();
if (!trimmed) return false;
if (trimmed.startsWith('#')) return false;
if (trimmed.startsWith('$page.')) return false;
if (trimmed.includes('{{') || trimmed.includes('}}')) return false;
return true;
}
function normalizeLegacySearchParams(params = {}) {
const normalized = { ...params };
if (!normalized.query && normalized.searchQuery) {
normalized.query = normalized.searchQuery;
}
if (normalized.isPaid === undefined && normalized.paidOnly === true) {
normalized.isPaid = true;
}
if (normalized.pagination && typeof normalized.pagination === 'object') {
const pagination = normalized.pagination;
if (pagination.page != null && normalized.page == null) {
normalized.page = pagination.page;
}
if (pagination.limit != null && normalized.perPage == null) {
normalized.perPage = pagination.limit;
}
if (pagination.sort && typeof pagination.sort === 'object' && !normalized.sortBy) {
const sortKeys = Object.keys(pagination.sort);
if (sortKeys.length > 0) {
normalized.sortBy = sortKeys[0];
normalized.sortDirection = pagination.sort[sortKeys[0]] >= 0 ? 'asc' : 'desc';
}
}
}
if (!normalized.statusId && Array.isArray(normalized.statuses) && normalized.statuses.length > 0) {
normalized.statusId = normalized.statuses[0];
}
if (!normalized.sortDirection && normalized.sortDir != null && normalized.sortDir !== '') {
const raw = String(normalized.sortDir).trim();
normalized.sortDirection = (raw === '-1' || raw.toLowerCase() === 'desc') ? 'desc' : 'asc';
}
return normalized;
}
// Mapuje parametry z datatable na parametry metody core/orders 'search',
// wymuszając filtr po źródle = zamówienia PrestaShop.
function buildSearchParams(params = {}) {
const cleanParams = normalizeLegacySearchParams({ ...params });
// OVE emit dołącza sourceId widoku — nie jest parametrem wyszukiwania
if (cleanParams.sourceId && !/^[a-f0-9]{24}$/i.test(String(cleanParams.sourceId))) {
delete cleanParams.sourceId;
}
const searchParams = {
page: parseInt(cleanParams.page, 10) || 1,
perPage: parseInt(cleanParams.perPage, 10) || 20,
source: {
moduleCode: MODULE_CODE,
_moduleCodes: MODULE_CODES
}
};
const sortBy = cleanParams.sortBy || cleanParams.sort;
const sortDirection = cleanParams.sortDirection || cleanParams.sortDir;
if (sortBy) searchParams.sortBy = sortBy;
if (sortDirection) searchParams.sortDirection = sortDirection;
if (cleanParams.statusId && isUsableParam(cleanParams.statusId)) searchParams.statusId = cleanParams.statusId;
if (cleanParams._id) searchParams._id = cleanParams._id;
// Pozwól nadpisać/rozszerzyć filtr źródła (np. konkretny shopPrefix w przyszłości).
if (cleanParams.source && typeof cleanParams.source === 'object') {
searchParams.source = { ...searchParams.source, ...cleanParams.source };
}
if (cleanParams.query && isUsableParam(cleanParams.query)) {
searchParams.query = String(cleanParams.query).trim();
}
const passthroughKeys = [
'dateFrom', 'dateTo', 'statusDateFrom', 'statusDateTo',
'orderReference', 'customer', 'customerEmail', 'customerPhone',
'carrierName', 'city', 'postCode', 'country',
'paymentMethod', 'currency', 'note',
'productName', 'productSku', 'productEan',
'priceFrom', 'priceTo', 'isPaid',
];
for (const key of passthroughKeys) {
const value = cleanParams[key];
if (value !== undefined && value !== null && isUsableParam(value)) {
searchParams[key] = value;
}
}
return searchParams;
}
async function searchOrders(companyId, params) {
const searchParams = buildSearchParams(params);
const raw = await callOrdersModule(companyId, 'search', searchParams);
return normalizeSearchResult(raw);
}
async function getOrderStatuses(companyId) {
const raw = await callOrdersModule(companyId, 'status.search', {});
return raw?.results ?? raw?.data ?? (Array.isArray(raw) ? raw : []);
}
module.exports = {
MODULE_CODE,
MODULE_CODES,
ORDERS_MODULE_ID,
callOrdersModule,
normalizeSearchResult,
buildSearchParams,
searchOrders,
getOrderStatuses
};
+125
View File
@@ -0,0 +1,125 @@
// ID widoków OVE → nazwy pól API (withData zbiera po id, jak w config-form.js)
const VIEW_ID_ALIASES = {
filterDateFrom: 'dateFrom',
filterDateTo: 'dateTo',
filterStatusDateFrom: 'statusDateFrom',
filterStatusDateTo: 'statusDateTo',
filterOrderReference: 'orderReference',
filterCustomer: 'customer',
filterCustomerEmail: 'customerEmail',
filterCustomerPhone: 'customerPhone',
filterCarrier: 'carrierName',
filterCity: 'city',
filterPostCode: 'postCode',
filterCountry: 'country',
filterProductName: 'productName',
filterProductSku: 'productSku',
filterProductEan: 'productEan',
filterPaymentMethod: 'paymentMethod',
filterCurrency: 'currency',
filterNote: 'note',
filterPriceFrom: 'priceFrom',
filterPriceTo: 'priceTo',
filterIsPaid: 'isPaid',
ordersSearchInput: 'query',
};
/** Pola filtrów — używaj w withData na przycisku Filtruj (zbiór po id widoku). */
const FILTER_VIEW_WITH_DATA = Object.keys(VIEW_ID_ALIASES);
const FILTER_KEYS = [
...new Set([...Object.values(VIEW_ID_ALIASES), 'statusId', 'sortBy', 'sortDirection', 'sortDir', 'page', 'perPage']),
];
const DEFAULT_SORT = {
sortBy: 'createdAt',
sortDirection: 'desc',
};
function normalizeScalar(value) {
if (value == null) return '';
if (typeof value === 'object') {
if ('value' in value) return normalizeScalar(value.value);
if ('id' in value) return normalizeScalar(value.id);
return '';
}
return String(value).trim();
}
function normalizeSortDirection(sortDirection, sortDir) {
if (sortDirection) {
const dir = String(sortDirection).toLowerCase();
if (dir === 'asc' || dir === 'desc') return dir;
}
if (sortDir != null && sortDir !== '') {
const raw = String(sortDir).trim();
if (raw === '-1' || raw.toLowerCase() === 'desc') return 'desc';
if (raw === '1' || raw.toLowerCase() === 'asc') return 'asc';
}
return DEFAULT_SORT.sortDirection;
}
function normalizeFilterParams(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 };
}
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];
}
}
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) flat[key] = value.id;
}
}
const normalized = {};
for (const key of FILTER_KEYS) {
if (!Object.prototype.hasOwnProperty.call(flat, key)) continue;
normalized[key] = normalizeScalar(flat[key]);
}
normalized.sortBy = normalized.sortBy || DEFAULT_SORT.sortBy;
normalized.sortDirection = normalizeSortDirection(normalized.sortDirection, normalized.sortDir);
delete normalized.sortDir;
return normalized;
}
function buildListPageQuery(filters = {}) {
const normalized = normalizeFilterParams(filters);
const parts = [];
for (const [key, value] of Object.entries(normalized)) {
if (!value) continue;
if (key === 'page' || key === 'perPage') continue;
parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`);
}
return parts.join('&');
}
function buildListPagePath(filters = {}) {
const query = buildListPageQuery(filters);
return query ? `list?${query}` : 'list';
}
module.exports = {
VIEW_ID_ALIASES,
FILTER_VIEW_WITH_DATA,
FILTER_KEYS,
DEFAULT_SORT,
normalizeFilterParams,
buildListPageQuery,
buildListPagePath,
};
+86
View File
@@ -0,0 +1,86 @@
const { DB } = require('@orbito/api-lib');
const { normalizeFilterParams } = require('./orders-filter-form');
const OrdersListState = require('./models/OrdersListState');
// Cache w pamięci — przyspiesza powtórne odczyty w tym samym procesie.
const memoryCache = new Map();
function storageKey(companyId) {
return String(companyId || '');
}
function companyObjectId(companyId) {
if (!companyId) return null;
try {
return new DB.ObjectId(companyId);
} catch (e) {
return null;
}
}
async function getFilters(companyId, instanceId) {
const key = storageKey(companyId);
if (memoryCache.has(key)) {
return { ...(memoryCache.get(key) || {}) };
}
const companyOid = companyObjectId(companyId);
if (!companyOid) return {};
const doc = await OrdersListState.findOne({ companyId: companyOid });
const filters = doc?.filters && typeof doc.filters === 'object' ? { ...doc.filters } : {};
memoryCache.set(key, filters);
return filters;
}
async function mergeFilters(companyId, instanceId, params = {}) {
const incoming = normalizeFilterParams(params);
const current = await getFilters(companyId, instanceId);
const merged = { ...current };
for (const [key, value] of Object.entries(incoming)) {
if (value === '') {
delete merged[key];
} else {
merged[key] = value;
}
}
const key = storageKey(companyId);
memoryCache.set(key, merged);
const companyOid = companyObjectId(companyId);
if (companyOid) {
const existing = await OrdersListState.findOne({ companyId: companyOid });
if (existing) {
await OrdersListState.update(
{ _id: existing._id },
{ filters: merged, updatedAt: new Date() }
);
} else {
await OrdersListState.create({
companyId: companyOid,
filters: merged,
updatedAt: new Date(),
});
}
}
return merged;
}
async function clearFilters(companyId, instanceId) {
const key = storageKey(companyId);
memoryCache.delete(key);
const companyOid = companyObjectId(companyId);
if (companyOid) {
await OrdersListState.delete({ companyId: companyOid });
}
}
module.exports = {
getFilters,
mergeFilters,
clearFilters,
};
+64
View File
@@ -0,0 +1,64 @@
function normalizeStatusId(value) {
if (value == null || value === '') return null;
if (typeof value === 'object' && value._id != null) {
return normalizeStatusId(value._id);
}
const str = String(value).trim();
return /^[a-f0-9]{24}$/i.test(str) ? str : null;
}
function parseStatusMapping(raw) {
if (!raw) return [];
if (Array.isArray(raw)) return raw;
if (typeof raw === 'string') {
const trimmed = raw.trim();
if (!trimmed) return [];
try {
const parsed = JSON.parse(trimmed);
return Array.isArray(parsed) ? parsed : [];
} catch (_) {
throw new Error('statusMapping musi być poprawną tablicą JSON');
}
}
return [];
}
// Mapuje PrestaShop order.current_state (psStateId) na orbitoStatusId.
function resolveStatusId(psStateId, statusMapping, fallbackStatusId) {
const stateId = parseInt(psStateId, 10);
if (!Array.isArray(statusMapping) || Number.isNaN(stateId)) {
return normalizeStatusId(fallbackStatusId);
}
const match = statusMapping.find(entry => parseInt(entry.psStateId, 10) === stateId);
return normalizeStatusId(match?.orbitoStatusId) ?? normalizeStatusId(fallbackStatusId);
}
function formatPsStatesPreview(states) {
if (!Array.isArray(states) || !states.length) {
return 'Brak statusów PrestaShop — najpierw przetestuj połączenie.';
}
return states
.map(s => {
const id = s.id ?? s.psStateId;
const name = extractPsStateName(s.name);
return `${id} — ${name}`;
})
.join('\n');
}
function extractPsStateName(name) {
if (Array.isArray(name)) {
return name[0]?.value ?? name[0] ?? '';
}
return name ?? '';
}
module.exports = {
normalizeStatusId,
parseStatusMapping,
resolveStatusId,
formatPsStatesPreview,
extractPsStateName
};
+18
View File
@@ -0,0 +1,18 @@
const codSuggestionPhrases = [
'cash on delivery',
'cod',
'pobranie',
];
module.exports = {
isLegacyApi: function(versionCode = "") {
// PrestaShop 1.7 and older versions use legacy API
return versionCode.trim() == '1.6' || versionCode.trim() == '1.7';
},
isNameSuggetsCOD: function(name) {
if (!name) return false;
const lowerName = name.toLowerCase();
return codSuggestionPhrases.some(phrase => lowerName.includes(phrase));
}
};