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:
+19
-23
@@ -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 };
|
||||
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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,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
@@ -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
@@ -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 = {
|
||||
|
||||
Reference in New Issue
Block a user