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( '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( '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(order.id, api, config); config.lastProcessedId = Math.max(config.lastProcessedId || 0, parseInt(order.id)); } catch (orderErr) { 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( '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 syncedAtRange = until ? { $gte: since, $lt: until } : { $gte: since }; const mappings = await PsOrder.find( { 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( '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( '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( 'CRON: PS payment synced', { psOrderId: m.psOrderId, amount: paidAmount }); } await PsOrder.update({ _id: m._id }, { $set: { paymentSyncedAt: new Date() } }); } catch (err) { Log.warn( '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) { Log.warn('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) { Log.warn('CRON: PS payments-older error', { error: err.message }); } } } finally { await Core.releaseLock(lockId); } }); paymentsSyncOlder.start(); Core.onEnabled(async () => { Log.info('Module enabled'); });