Migrate to @orbito/api-lib 2.0.0 for single-company container model.

Remove companyId from handlers, models, cron jobs, and cross-module calls to match the v2 one-module-one-company architecture.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
fatequod
2026-07-08 11:21:35 +02:00
co-authored by Cursor
parent f163100ad4
commit 1a6a978a21
25 changed files with 365 additions and 189 deletions
+13 -17
View File
@@ -25,7 +25,7 @@ const ordersPuller = new CronJob("0 */5 * * * *", async () => {
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 });
Log.error( 'Error fetching shop configs', { error: error.message });
}
for (const config of enabledShops) {
@@ -86,7 +86,7 @@ const ordersPuller = new CronJob("0 */5 * * * *", async () => {
for (const order of res.orders) {
try {
const searchResult = await Core.callModule(config.companyId, 'core/orders', 'search', {
const searchResult = await Core.callModule( 'core/orders', 'search', {
source: {
moduleCode: 'core/prestashop',
uniqueId: order.reference + ':' + order.id
@@ -98,17 +98,17 @@ const ordersPuller = new CronJob("0 */5 * * * *", async () => {
continue;
}
await importFromPSOrder(config.companyId, order.id, api, config);
await importFromPSOrder(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 });
Log.error( '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 });
Log.error( 'Error pulling orders for shop config', { shopConfigId: config._id, error: error.message });
}
}
} finally {
@@ -119,12 +119,10 @@ 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,
@@ -136,7 +134,7 @@ async function syncPaymentsForShop(config, api, since, until, limit = 30) {
for (const m of mappings) {
try {
const orderRes = await Core.callModule(companyId, 'core/orders', 'search', { _id: m.orbitoOrderId });
const orderRes = await Core.callModule( 'core/orders', 'search', { _id: m.orbitoOrderId });
const orders = Array.isArray(orderRes) ? orderRes : (orderRes?.data ?? []);
const order = orders[0];
if (order?.isPaid) {
@@ -156,7 +154,7 @@ async function syncPaymentsForShop(config, api, since, until, limit = 30) {
if (remaining > 0) {
const paidAmount = Math.min(remaining, Math.round(totalPaidReal * 100) / 100);
await Core.callModule(companyId, 'core/orders', 'order.payments_add', {
await Core.callModule( 'core/orders', 'order.payments_add', {
orderId: m.orbitoOrderId?.toString?.() ?? m.orbitoOrderId,
payment: {
amount: paidAmount,
@@ -164,11 +162,11 @@ async function syncPaymentsForShop(config, api, since, until, limit = 30) {
date: new Date(psOrder.date_add),
},
});
Log.info(companyId, 'CRON: PS payment synced', { psOrderId: m.psOrderId, amount: paidAmount });
Log.info( '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 });
Log.warn( 'CRON: PS payment sync failed', { psOrderId: m.psOrderId, error: err.message });
}
}
}
@@ -184,8 +182,7 @@ const paymentsSyncNew = new CronJob('0 */3 * * * *', async () => {
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 });
Log.warn('CRON: PS payments-new error', { error: err.message });
}
}
} finally {
@@ -207,8 +204,7 @@ const paymentsSyncOlder = new CronJob('0 */30 * * * *', async () => {
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 });
Log.warn('CRON: PS payments-older error', { error: err.message });
}
}
} finally {
@@ -217,6 +213,6 @@ const paymentsSyncOlder = new CronJob('0 */30 * * * *', async () => {
});
paymentsSyncOlder.start();
Core.onEnabled(async (companyId, instanceId) => {
Log.info('Module enabled', { companyId, instanceId });
Core.onEnabled(async () => {
Log.info('Module enabled');
});
+3 -3
View File
@@ -2,11 +2,11 @@ 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 } });
module.exports = async function(params, ctx) {
const config = await ShopConfig.findOne({ isRemoved: { $ne: true } });
const form = toFormResponse(config);
Log.debug(companyId, 'config.get', {
Log.debug( 'config.get', {
found: Boolean(config),
storeUrl: form.storeUrl,
shopPrefix: form.shopPrefix,
+5 -6
View File
@@ -6,8 +6,8 @@ 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 } });
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();
@@ -43,19 +43,18 @@ module.exports = async function(companyId, instanceId, params, ctx) {
if (existing) {
await ShopConfig.update({ _id: existing._id }, payload);
Log.info(companyId, 'PrestaShop order states saved', { configId: existing._id, count: psStates.length });
Log.info( '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 });
Log.info( '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 });
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'));
}
};
+2 -2
View File
@@ -2,8 +2,8 @@ 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 } });
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 : [];
+3 -3
View File
@@ -2,13 +2,13 @@ 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 } });
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(companyId, 'PrestaShop config reset', { removed: configs.length });
Log.info( 'PrestaShop config reset', { removed: configs.length });
return methodOk({ removed: configs.length });
};
+7 -7
View File
@@ -3,12 +3,12 @@ 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) {
module.exports = async function(params, ctx) {
try {
const input = normalizeFormParams(params);
const existing = await ShopConfig.findOne({ companyId, isRemoved: { $ne: true } });
const existing = await ShopConfig.findOne({ isRemoved: { $ne: true } });
Log.debug(companyId, 'config.save input', {
Log.debug( 'config.save input', {
keys: Object.keys(input),
storeUrl: input.storeUrl,
shopPrefix: input.shopPrefix,
@@ -24,20 +24,20 @@ module.exports = async function(companyId, instanceId, params, ctx) {
return methodFail('Klucz API jest wymagany. Wpisz klucz Webservice API lub zachowaj już zapisany.');
}
const payload = { companyId, ...data };
const payload = { ...data };
if (existing) {
await ShopConfig.update({ _id: existing._id }, payload);
Log.info(companyId, 'PrestaShop config updated', { configId: existing._id });
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(companyId, 'PrestaShop config created', { configId: created._id });
Log.info( 'PrestaShop config created', { configId: created._id });
return methodOk({ data: toFormResponse(created) });
} catch (err) {
Log.error(companyId, 'config.save failed', { error: err?.message });
Log.error( 'config.save failed', { error: err?.message });
return methodFail(err?.message || 'Nie udało się zapisać konfiguracji');
}
};
+4 -4
View File
@@ -5,8 +5,8 @@ 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 } });
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();
@@ -29,10 +29,10 @@ module.exports = async function(companyId, instanceId, params, ctx) {
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 });
Log.info( 'PrestaShop connection test OK', { storeUrl, statusesCount: count });
return methodOk({ statusesCount: count });
} catch (e) {
Log.warn(companyId, 'PrestaShop connection test failed', { storeUrl, error: e.message });
Log.warn( 'PrestaShop connection test failed', { storeUrl, error: e.message });
return methodFail('Połączenie nieudane: ' + (e.message || 'błąd API PrestaShop'));
}
};
+2 -2
View File
@@ -1,11 +1,11 @@
const { DB, Utils, Log } = require('@orbito/api-lib');
const ShopConfigSchema = require('../src/models/ShopConfig');
module.exports = async function(companyId, instanceId, params, ctx) {
module.exports = async function(params, ctx) {
const { _id } = params;
if (!_id) throw new Error('Missing _id');
const config = await ShopConfigSchema.findOne({ _id, companyId, isRemoved: { $ne: true } });
const config = await ShopConfigSchema.findOne({ _id, isRemoved: { $ne: true } });
if (!config) throw new Error('Config not found');
await ShopConfigSchema.update({ _id }, { isRemoved: true });
+2 -2
View File
@@ -2,12 +2,12 @@ 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) {
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 = { companyId, isRemoved: { $ne: true } };
const query = { isRemoved: { $ne: true } };
const results = await ShopConfigSchema.find(query, perPage, skip, { createdAt: -1 });
const total = await ShopConfigSchema.count(query);
+2 -3
View File
@@ -1,8 +1,7 @@
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);
module.exports = async function() {
const filters = await getFilters();
return {
page: parseInt(filters.page, 10) || 1,
perPage: parseInt(filters.perPage, 10) || 20,
+8 -17
View File
@@ -3,32 +3,25 @@ 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) {
module.exports = async function(params, ctx) {
const input = { ...(params || {}) };
if (input.clearFilters) {
clearFilters(companyId, instanceId);
await clearFilters();
delete input.clearFilters;
Log.info(companyId, 'orders.search clearFilters', { instanceId });
Log.info('orders.search clearFilters');
}
if (input.saveFilters) {
await mergeFilters(companyId, instanceId, input);
await mergeFilters(input);
delete input.saveFilters;
Log.info(companyId, 'orders.search saveFilters', { instanceId, filters: await getFilters(companyId, instanceId) });
Log.info('orders.search saveFilters', { filters: await getFilters() });
}
const stored = await getFilters(companyId, instanceId);
const stored = await getFilters();
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];
@@ -41,16 +34,14 @@ module.exports = async function(companyId, instanceId, params, ctx) {
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);
const result = await searchOrders(finalParams);
await mergeFilters(companyId, instanceId, {
await mergeFilters({
page: String(finalParams.page || 1),
perPage: String(finalParams.perPage || 20),
});
+2 -2
View File
@@ -2,11 +2,11 @@ const ShopConfig = require('../../src/models/ShopConfig');
const PrestashopApi = require('../../src/PrestaApi');
const { isLegacyApi } = require('../../src/utils');
module.exports = async function (companyId, instanceId, params, ctx) {
module.exports = async function(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 configs = await ShopConfig.find({ isRemoved: { $ne: true } });
const config = configs.find(c => c.apiUrl && c.apiKey);
if (!config) return {};
+6 -9
View File
@@ -1,25 +1,22 @@
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;
const CACHE_KEY = 'default';
module.exports = async function(companyId, instanceId, params, ctx) {
const key = companyId?.toString?.() ?? companyId;
module.exports = async function(params, ctx) {
const now = Date.now();
const cached = cache.get(key);
const cached = cache.get(CACHE_KEY);
if (cached && now - cached.ts < CACHE_TTL) {
return { data: cached.data };
}
const statuses = await getOrderStatuses(companyId);
const statuses = await getOrderStatuses();
const data = [];
for (const status of statuses) {
const statusId = status._id?.toString?.() ?? status._id;
const result = await searchOrders(companyId, {
const result = await searchOrders({
statusId,
page: 1,
perPage: 1
@@ -36,6 +33,6 @@ module.exports = async function(companyId, instanceId, params, ctx) {
data.sort((a, b) => (a.positionInGroup ?? 0) - (b.positionInGroup ?? 0));
cache.set(key, { ts: now, data });
cache.set(CACHE_KEY, { ts: now, data });
return { data };
};
+4 -4
View File
@@ -4,8 +4,8 @@ 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 } });
module.exports = async function(params, ctx) {
const configs = await ShopConfig.find({ isRemoved: { $ne: true } });
const active = configs.filter(c => c.apiUrl && c.apiKey);
if (active.length === 0) return { error: 'No active shop configs found' };
@@ -34,7 +34,7 @@ module.exports = async function (companyId, instanceId, params, ctx) {
const errors = [];
for (const order of orders) {
const uniqueId = order.reference + ':' + order.id;
const searchResult = await Core.callModule(companyId, 'core/orders', 'search', {
const searchResult = await Core.callModule( 'core/orders', 'search', {
source: { moduleCode: 'core/prestashop', uniqueId }
});
if (searchResult?.data?.length > 0) {
@@ -42,7 +42,7 @@ module.exports = async function (companyId, instanceId, params, ctx) {
continue;
}
try {
await importFromPSOrder(companyId, order.id, api, config);
await importFromPSOrder(order.id, api, config);
imported.push({ id: order.id, status: 'imported' });
} catch (e) {
errors.push({ id: order.id, error: e.message });
+3 -3
View File
@@ -1,9 +1,9 @@
const { DB, Utils, Log } = require('@orbito/api-lib');
const ShopConfigSchema = require('../src/models/ShopConfig');
module.exports = async function(companyId, instanceId, params, ctx) {
module.exports = async function(params, ctx) {
const editableFields = ['apiUrl', 'apiKey', 'shopName', 'versionCode', 'orderStatus'];
const dataToUpdate = { companyId };
const dataToUpdate = {};
for (const field of editableFields) {
if (typeof params[field] !== 'undefined') {
dataToUpdate[field] = params[field];
@@ -12,7 +12,7 @@ module.exports = async function(companyId, instanceId, params, ctx) {
// Jeśli podano _id – aktualizuj konkretny rekord
if (params._id) {
const config = await ShopConfigSchema.findOne({ _id: params._id, companyId, isRemoved: { $ne: true } });
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);
+239
View File
@@ -0,0 +1,239 @@
{
"name": "prestashop-module",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "prestashop-module",
"version": "1.0.0",
"license": "ISC",
"dependencies": {
"@orbito/api-lib": "^2.0.0",
"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"
}
},
"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==",
"license": "ISC",
"dependencies": {
"bson": "^6.10.4",
"fastest-validator": "^1.19.1"
}
},
"node_modules/@types/luxon": {
"version": "3.7.2",
"resolved": "https://registry.npmjs.org/@types/luxon/-/luxon-3.7.2.tgz",
"integrity": "sha512-gW+Oib+vUtGJBtNC8V9Reww0oIpusw+4m81uncg9REGZAJfqOQHfo/nkabnc7w0QReXyPqjrbWMJk6NuAkiX3Q==",
"license": "MIT"
},
"node_modules/async": {
"version": "3.2.6",
"resolved": "https://registry.npmjs.org/async/-/async-3.2.6.tgz",
"integrity": "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==",
"license": "MIT"
},
"node_modules/balanced-match": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
"integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
"license": "MIT"
},
"node_modules/brace-expansion": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.2.tgz",
"integrity": "sha512-w5JZcKgdhDOgOwm8H+KgbosopHMuGcl6qbulwjtz3SM7I7P3yW1eAjzMPLrIE+NQ9vjgANKHWeMHnrT0OXW1oA==",
"license": "MIT",
"dependencies": {
"balanced-match": "^1.0.0"
}
},
"node_modules/bson": {
"version": "6.10.4",
"resolved": "https://registry.npmjs.org/bson/-/bson-6.10.4.tgz",
"integrity": "sha512-WIsKqkSC0ABoBJuT1LEX+2HEvNmNKKgnTAyd0fL8qzK4SH2i9NXg+t08YtdZp/V9IZ33cxe3iV4yM0qg8lMQng==",
"license": "Apache-2.0",
"engines": {
"node": ">=16.20.1"
}
},
"node_modules/clone": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/clone/-/clone-2.1.2.tgz",
"integrity": "sha512-3Pe/CF1Nn94hyhIYpjtiLhdCoEoz0DqQ+988E9gmeEdQZlojxnOb74wctFyuwWQHzqyf9X7C7MG8juUpqBJT8w==",
"license": "MIT",
"engines": {
"node": ">=0.8"
}
},
"node_modules/cron": {
"version": "4.4.0",
"resolved": "https://registry.npmjs.org/cron/-/cron-4.4.0.tgz",
"integrity": "sha512-fkdfq+b+AHI4cKdhZlppHveI/mgz2qpiYxcm+t5E5TsxX7QrLS1VE0+7GENEk9z0EeGPcpSciGv6ez24duWhwQ==",
"license": "MIT",
"dependencies": {
"@types/luxon": "~3.7.0",
"luxon": "~3.7.0"
},
"engines": {
"node": ">=18.x"
},
"funding": {
"type": "ko-fi",
"url": "https://ko-fi.com/intcreator"
}
},
"node_modules/dotenv": {
"version": "17.4.2",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.4.2.tgz",
"integrity": "sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw==",
"license": "BSD-2-Clause",
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://dotenvx.com"
}
},
"node_modules/ejs": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/ejs/-/ejs-4.0.1.tgz",
"integrity": "sha512-krvQtxc0btwSm/nvnt1UpnaFDFVJpJ0fdckmALpCgShsr/iGYHTnJiUliZTgmzq/UxTX33TtOQVKaNigMQp/6Q==",
"license": "Apache-2.0",
"dependencies": {
"jake": "^10.9.1"
},
"bin": {
"ejs": "bin/cli.js"
},
"engines": {
"node": ">=0.12.18"
}
},
"node_modules/fastest-validator": {
"version": "1.19.1",
"resolved": "https://registry.npmjs.org/fastest-validator/-/fastest-validator-1.19.1.tgz",
"integrity": "sha512-eXiPCYOsuS5OWI+OVH9whu4LDGqO4cE7jUnZyQ8jV3rXfmC0OghQACOtYjTDxsVnblzvXIHGuizjFg0csiLE6g==",
"license": "MIT"
},
"node_modules/filelist": {
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/filelist/-/filelist-1.0.6.tgz",
"integrity": "sha512-5giy2PkLYY1cP39p17Ech+2xlpTRL9HLspOfEgm0L6CwBXBTgsK5ou0JtzYuepxkaQ/tvhCFIJ5uXo0OrM2DxA==",
"license": "Apache-2.0",
"dependencies": {
"minimatch": "^5.0.1"
}
},
"node_modules/jake": {
"version": "10.9.4",
"resolved": "https://registry.npmjs.org/jake/-/jake-10.9.4.tgz",
"integrity": "sha512-wpHYzhxiVQL+IV05BLE2Xn34zW1S223hvjtqk0+gsPrwd/8JNLXJgZZM/iPFsYc1xyphF+6M6EvdE5E9MBGkDA==",
"license": "Apache-2.0",
"dependencies": {
"async": "^3.2.6",
"filelist": "^1.0.4",
"picocolors": "^1.1.1"
},
"bin": {
"jake": "bin/cli.js"
},
"engines": {
"node": ">=10"
}
},
"node_modules/js2xmlparser": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/js2xmlparser/-/js2xmlparser-5.0.0.tgz",
"integrity": "sha512-ckXs0Fzd6icWurbeAXuqo+3Mhq2m8pOPygsQjTPh8K5UWgKaUgDSHrdDxAfexmT11xvBKOQ6sgYwPkYc5RW/bg==",
"license": "Apache-2.0",
"dependencies": {
"xmlcreate": "^2.0.4"
}
},
"node_modules/luxon": {
"version": "3.7.2",
"resolved": "https://registry.npmjs.org/luxon/-/luxon-3.7.2.tgz",
"integrity": "sha512-vtEhXh/gNjI9Yg1u4jX/0YVPMvxzHuGgCm6tC5kZyb08yjGWGnqAjGJvcXbqQR2P3MyMEFnRbpcdFS6PBcLqew==",
"license": "MIT",
"engines": {
"node": ">=12"
}
},
"node_modules/minimatch": {
"version": "5.1.9",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.9.tgz",
"integrity": "sha512-7o1wEA2RyMP7Iu7GNba9vc0RWWGACJOCZBJX2GJWip0ikV+wcOsgVuY9uE8CPiyQhkGFSlhuSkZPavN7u1c2Fw==",
"license": "ISC",
"dependencies": {
"brace-expansion": "^2.0.1"
},
"engines": {
"node": ">=10"
}
},
"node_modules/nanoid": {
"version": "5.1.16",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-5.1.16.tgz",
"integrity": "sha512-kVrnsrJqMR8+oLJnGEmSWw9BivK5mt7H3FZatVRjrc5wGqFYuBxX1yG7+A7Gi5AefkX6t/oCkizcQgpu0cY1dQ==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/ai"
}
],
"license": "MIT",
"bin": {
"nanoid": "bin/nanoid.js"
},
"engines": {
"node": "^18 || >=20"
}
},
"node_modules/node-cache": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/node-cache/-/node-cache-5.1.2.tgz",
"integrity": "sha512-t1QzWwnk4sjLWaQAS8CHgOJ+RAfmHpxFWmc36IWTiWHQfs0w5JDMBS1b1ZxQteo0vVVuWJvIUKHDkkeK7vIGCg==",
"license": "MIT",
"dependencies": {
"clone": "2.x"
},
"engines": {
"node": ">= 8.0.0"
}
},
"node_modules/picocolors": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
"integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
"license": "ISC"
},
"node_modules/uuid": {
"version": "11.1.1",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-11.1.1.tgz",
"integrity": "sha512-vIYxrBCC/N/K+Js3qSN88go7kIfNPssr/hHCesKCQNAjmgvYS2oqr69kIufEG+O4+PfezOH4EbIeHCfFov8ZgQ==",
"funding": [
"https://github.com/sponsors/broofa",
"https://github.com/sponsors/ctavan"
],
"license": "MIT",
"bin": {
"uuid": "dist/esm/bin/uuid"
}
},
"node_modules/xmlcreate": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/xmlcreate/-/xmlcreate-2.0.4.tgz",
"integrity": "sha512-nquOebG4sngPmGPICTS5EnxqhKbCmz5Ox5hsszI2T6U5qdrJizBc+0ilYSEjTSzU0yZcmvppztXe/5Al5fUwdg==",
"license": "Apache-2.0"
}
}
}
+1 -1
View File
@@ -10,7 +10,7 @@
"author": "",
"license": "ISC",
"dependencies": {
"@orbito/api-lib": "^1.1.6",
"@orbito/api-lib": "^2.0.0",
"cron": "^4.4.0",
"dotenv": "^17.2.3",
"ejs": "^4.0.1",
+3 -3
View File
@@ -311,9 +311,9 @@ function buildTemplate(form) {
};
}
module.exports = async function(companyId, instanceId, body, params) {
module.exports = async function(body, params) {
try {
const config = await ShopConfig.findOne({ companyId, isRemoved: { $ne: true } });
const config = await ShopConfig.findOne({ isRemoved: { $ne: true } });
const form = toFormResponse(config);
return {
@@ -321,7 +321,7 @@ module.exports = async function(companyId, instanceId, body, params) {
template: buildTemplate(form)
};
} catch (err) {
Log.error(companyId, 'pages/config failed', { error: err?.message, stack: err?.stack });
Log.error( 'pages/config failed', { error: err?.message, stack: err?.stack });
return {
type: 'ove',
template: {
+3 -3
View File
@@ -1,17 +1,17 @@
const { Log, Core, Utils, Pages } = require('@orbito/api-lib');
const ShopConfig = require('../src/models/ShopConfig');
module.exports = async function(companyId, instanceId, body, params) {
module.exports = async function(body, params) {
const configId = params.shopId;
const isEdit = !!configId;
let config = null;
if (isEdit) {
config = await ShopConfig.findOne({ _id: configId, companyId, isRemoved: { $ne: true } });
config = await ShopConfig.findOne({ _id: configId, isRemoved: { $ne: true } });
if (!config) throw new Error('Config not found');
}
const res = await Core.callModule(companyId, 'core/orders', 'status.search', {});
const res = await Core.callModule( 'core/orders', 'status.search', {});
const orderStatuses = res.results || [];
return {
+19 -23
View File
@@ -17,8 +17,8 @@ function getPSMultiLangField(param, langId) {
return param;
}
async function resolveImportStatusId(companyId, config) {
const statusResult = await Core.callModule(companyId, 'core/orders', 'status.search', {});
async function resolveImportStatusId(config) {
const statusResult = await Core.callModule( 'core/orders', 'status.search', {});
const statuses = statusResult?.results ?? [];
const byId = new Map();
@@ -38,19 +38,19 @@ async function resolveImportStatusId(companyId, config) {
return normalizeStatusId(sorted[0]?._id);
}
async function importFromPSOrder(companyId, orderId, api, config) {
Log.debug(companyId, "Checking if BL is supported", { orderId });
async function importFromPSOrder(orderId, api, config) {
Log.debug( "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 });
Log.debug( "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);
Log.error( "Order not found", orderId);
return;
}
Log.info(companyId, "Importing order: " + order.reference);
Log.info( "Importing order: " + order.reference);
let products = [];
for (let product of order.associations.order_rows) {
@@ -68,7 +68,7 @@ async function importFromPSOrder(companyId, orderId, api, config) {
};
const psProduct = await api.getProduct(product.product_id);
Log.debug(companyId, "Fetched product details: " + getPSMultiLangField(psProduct.name));
Log.debug( "Fetched product details: " + getPSMultiLangField(psProduct.name));
p.weight = parseFloat(psProduct.weight);
try {
@@ -122,7 +122,7 @@ async function importFromPSOrder(companyId, orderId, api, config) {
await Promise.all(
products
.filter(p => p.sourceId && p.name)
.map(p => Core.callModule(companyId, 'core/orders', 'product.upsert', {
.map(p => Core.callModule( 'core/orders', 'product.upsert', {
sourceModule: 'core/prestashop',
sourceId: String(p.sourceId),
sku: p.sku || '',
@@ -133,23 +133,23 @@ async function importFromPSOrder(companyId, orderId, api, config) {
}).catch(() => {}))
);
const fallbackStatusId = await resolveImportStatusId(companyId, config);
const fallbackStatusId = await resolveImportStatusId(config);
if (!fallbackStatusId) {
Log.error(companyId, 'Cannot import order — no valid order status configured', { orderId });
Log.error( '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', {
Log.error( 'Cannot import order — could not resolve status', {
orderId,
psStateId: order.current_state
});
return;
}
Log.info(companyId, 'Resolved order status', {
Log.info( 'Resolved order status', {
orderId,
psStateId: order.current_state,
orbitoStatusId: statusId
@@ -157,7 +157,7 @@ async function importFromPSOrder(companyId, orderId, api, config) {
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 });
Log.debug( "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;
@@ -170,7 +170,7 @@ async function importFromPSOrder(companyId, orderId, api, config) {
carrierName = carrier.name || "Brak nazwy";
}
} catch (e) {
Log.warn(companyId, "Error fetching carrier for order", orderId, e.message);
Log.warn( "Error fetching carrier for order", orderId, e.message);
}
}
@@ -197,10 +197,10 @@ async function importFromPSOrder(companyId, orderId, api, config) {
// 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}`);
Log.warn( `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}`);
Log.error( `Error fetching invoice address for order ID ${orderId}, address ID ${order.id_address_invoice}: ${e.message}`);
// W przypadku błędu, invoiceDataForOrder pozostaje { isNeeded: false }
}
}
@@ -249,7 +249,7 @@ async function importFromPSOrder(companyId, orderId, api, config) {
});
}
const coreOrder = await Core.callModule(companyId, 'core/orders', 'create', {
const coreOrder = await Core.callModule( 'core/orders', 'create', {
statusId: statusId,
customer: {
name: customer.firstname + " " + customer.lastname,
@@ -303,7 +303,6 @@ async function importFromPSOrder(companyId, orderId, api, config) {
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,
@@ -312,12 +311,9 @@ async function importFromPSOrder(companyId, orderId, api, config) {
paymentSyncedAt: alreadyPaid ? new Date() : undefined,
});
} catch (e) {
Log.warn(companyId, 'PS order mapping save failed', { psOrderId: order.id, error: e.message });
Log.warn( 'PS order mapping save failed', { psOrderId: order.id, error: e.message });
}
}
}
module.exports = { importFromPSOrder };
module.exports = { importFromPSOrder };
-2
View File
@@ -1,11 +1,9 @@
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;
+3 -4
View File
@@ -1,7 +1,6 @@
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 },
@@ -13,8 +12,8 @@ const schema = new DB.Schema('ps_orders', {
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 });
DB.createIndex('ps_orders', { psOrderId: 1, shopConfigId: 1 }, { unique: true });
DB.createIndex('ps_orders', { orbitoOrderId: 1 });
DB.createIndex('ps_orders', { syncedAt: -1 });
module.exports = schema;
-3
View File
@@ -3,8 +3,6 @@ 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 },
@@ -50,6 +48,5 @@ schema.post('create', function(data) {
// Hook for post-create actions (e.g., emit events, notifications)
});
DB.createIndex('shop_config', { companyId: 1 });
module.exports = schema;
+6 -15
View File
@@ -3,19 +3,14 @@ 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);
async function callOrdersModule(method, params) {
return Core.callModule(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 } };
@@ -87,11 +82,8 @@ function normalizeLegacySearchParams(params = {}) {
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;
}
@@ -113,7 +105,6 @@ function buildSearchParams(params = {}) {
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 };
}
@@ -140,14 +131,14 @@ function buildSearchParams(params = {}) {
return searchParams;
}
async function searchOrders(companyId, params) {
async function searchOrders(params) {
const searchParams = buildSearchParams(params);
const raw = await callOrdersModule(companyId, 'search', searchParams);
const raw = await callOrdersModule('search', searchParams);
return normalizeSearchResult(raw);
}
async function getOrderStatuses(companyId) {
const raw = await callOrdersModule(companyId, 'status.search', {});
async function getOrderStatuses() {
const raw = await callOrdersModule('status.search', {});
return raw?.results ?? raw?.data ?? (Array.isArray(raw) ? raw : []);
}
+25 -51
View File
@@ -2,40 +2,23 @@ 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();
const memoryCache = { filters: null };
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) || {}) };
async function getFilters() {
if (memoryCache.filters) {
return { ...memoryCache.filters };
}
const companyOid = companyObjectId(companyId);
if (!companyOid) return {};
const doc = await OrdersListState.findOne({ companyId: companyOid });
const docs = await OrdersListState.find({}, 1, 0, { updatedAt: -1 });
const doc = docs[0];
const filters = doc?.filters && typeof doc.filters === 'object' ? { ...doc.filters } : {};
memoryCache.set(key, filters);
memoryCache.filters = filters;
return filters;
}
async function mergeFilters(companyId, instanceId, params = {}) {
async function mergeFilters(params = {}) {
const incoming = normalizeFilterParams(params);
const current = await getFilters(companyId, instanceId);
const current = await getFilters();
const merged = { ...current };
for (const [key, value] of Object.entries(incoming)) {
@@ -46,37 +29,28 @@ async function mergeFilters(companyId, instanceId, params = {}) {
}
}
const key = storageKey(companyId);
memoryCache.set(key, merged);
memoryCache.filters = 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(),
});
}
const docs = await OrdersListState.find({}, 1, 0, { updatedAt: -1 });
const existing = docs[0];
if (existing) {
await OrdersListState.update(
{ _id: existing._id },
{ filters: merged, updatedAt: new Date() }
);
} else {
await OrdersListState.create({
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 });
}
async function clearFilters() {
memoryCache.filters = null;
await OrdersListState.delete({});
}
module.exports = {