const DEFAULT_PAGE_SIZE = 50; const DEFAULT_MAX_PAGES = 10; function money(value) { const number = Number(value); return Number.isFinite(number) ? Math.round(number * 100) / 100 : 0; } function asOrders(result) { if (Array.isArray(result)) return result; if (Array.isArray(result?.data)) return result.data; if (Array.isArray(result?.results)) return result.results; return []; } function paymentTransactionId(config, psOrderId, cumulativeTotal) { const shopId = String(config?._id || 'default').replace(/[^a-zA-Z0-9_.-]/g, '_'); return `prestashop:${shopId}:${psOrderId}:paid:${Math.round(money(cumulativeTotal) * 100)}`; } function orderUniqueId(order) { return `${order.reference}:${order.id}`; } function parsePrestashopDate(value, fallback = new Date()) { if (!value) return fallback; const parsed = new Date(String(value).replace(' ', 'T')); return Number.isNaN(parsed.getTime()) ? fallback : parsed; } async function upsertMapping(PsOrder, data) { const key = { shopConfigId: String(data.shopConfigId), psOrderId: Number(data.psOrderId), }; const existing = await PsOrder.findOne(key); const set = { orbitoOrderId: data.orbitoOrderId, reference: data.reference || existing?.reference || '', syncedAt: data.syncedAt || existing?.syncedAt || new Date(), }; for (const field of ['paymentTotalSynced', 'paymentSyncedAt', 'paymentCheckedAt', 'nextPaymentCheckAt']) { if (data[field] !== undefined) set[field] = data[field]; } await PsOrder.update(key, { $set: set }, { upsert: true }); return { ...existing, ...key, ...set }; } async function ensureExistingOrderMapping({ config, api, psOrderSummary, orbitoOrder, PsOrder }) { const key = { shopConfigId: String(config._id), psOrderId: Number(psOrderSummary.id) }; const existing = await PsOrder.findOne(key); if (existing?.orbitoOrderId) return existing; // A create may have succeeded while saving the mapping failed. Establish a conservative // baseline from both systems so replay cannot append the same cumulative payment twice. const psOrder = await api.getOrder(psOrderSummary.id); if (!psOrder) throw new Error(`PrestaShop order ${psOrderSummary.id} not found while restoring mapping`); const psPaid = money(psOrder.total_paid_real); const orbitoPaid = money(orbitoOrder?.summary?.paid); return upsertMapping(PsOrder, { ...key, orbitoOrderId: orbitoOrder._id, reference: psOrderSummary.reference || psOrder.reference || '', syncedAt: parsePrestashopDate(psOrder.date_add), paymentTotalSynced: Math.min(psPaid, orbitoPaid), paymentCheckedAt: new Date(), nextPaymentCheckAt: new Date(), }); } function stableOrders(orders, nowMs = Date.now()) { const cutoff = nowMs - 30 * 1000; const newestDate = orders[orders.length - 1]?.date_add; let offsetMs = 0; if (newestDate) { const drift = parsePrestashopDate(newestDate).getTime() - nowMs; if (drift > 60000) offsetMs = Math.round(drift / 3600000) * 3600000; } const stable = []; for (const order of orders) { // Only return a contiguous prefix. Skipping a still-changing order and // advancing to a later id would make that skipped id unreachable by the cursor. if (parsePrestashopDate(order.date_add).getTime() - offsetMs >= cutoff) break; stable.push(order); } return stable; } async function importOrdersForShop(config, api, dependencies = {}) { const { Core, PsOrder, importFromPSOrder, setLastOrderId, Log = console, now = () => Date.now(), isLockValid = () => true, } = dependencies; if (config.lastOrderId == null || !Number.isFinite(Number(config.lastOrderId))) { const response = await api.makeRequest('orders', 'GET', { display: '[id]', sort: 'id_DESC', limit: 1, output_format: 'JSON', }); const latestId = Number(response?.orders?.[0]?.id); if (Number.isFinite(latestId)) { await setLastOrderId(latestId); config.lastOrderId = latestId; Log.info('PrestaShop import initialized at the newest order; historical orders were not backfilled', { shopConfigId: config._id, lastOrderId: latestId, }); } return { status: 'initialized', cursor: config.lastOrderId ?? null, processed: 0 }; } const startingCursor = Number(config.lastOrderId); const response = await api.makeRequest('orders', 'GET', { display: '[id, reference, date_add]', sort: 'id_ASC', limit: DEFAULT_PAGE_SIZE, output_format: 'JSON', 'filter[id]': `[${startingCursor + 1},999999999]`, }); const orders = stableOrders(Array.isArray(response?.orders) ? response.orders : [], now()); let cursor = startingCursor; let processed = 0; for (const order of orders) { if (!isLockValid()) throw new Error('PrestaShop orders lock was lost'); try { const result = await Core.callModule('core/orders', 'search', { source: { moduleCode: 'core/prestashop', uniqueId: orderUniqueId(order) }, }); const existingOrder = asOrders(result)[0]; if (existingOrder) { await ensureExistingOrderMapping({ config, api, psOrderSummary: order, orbitoOrder: existingOrder, PsOrder }); } else { const importResult = await importFromPSOrder(order.id, api, config); if (!importResult || !['imported', 'existing'].includes(importResult.status)) { throw new Error(`Importer returned an invalid result for order ${order.id}`); } } cursor = Number(order.id); processed += 1; } catch (error) { Log.error('Failed to import PS order; cursor remains before this order', { orderId: order.id, cursor, error: error.message, }); break; } } if (cursor > startingCursor) { await setLastOrderId(cursor); config.lastOrderId = cursor; } return { status: 'processed', cursor, processed }; } function duePaymentsQuery(config, since, until, nowDate) { const syncedAt = since && until ? { $gte: since, $lt: until } : (since ? { $gte: since } : { $lt: until }); return { shopConfigId: String(config._id), orbitoOrderId: { $exists: true, $ne: null }, syncedAt, $or: [ { nextPaymentCheckAt: { $exists: false } }, { nextPaymentCheckAt: null }, { nextPaymentCheckAt: { $lte: nowDate } }, ], }; } async function processPaymentMapping(mapping, config, api, dependencies) { const { Core, PsOrder, nowDate, nextCheckMs, retryCheckMs, Log = console } = dependencies; try { const orderResult = await Core.callModule('core/orders', 'search', { _id: mapping.orbitoOrderId }); const order = asOrders(orderResult)[0]; if (!order) throw new Error(`Orbito order ${mapping.orbitoOrderId} not found`); const psOrder = await api.getOrder(mapping.psOrderId); if (!psOrder) throw new Error(`PrestaShop order ${mapping.psOrderId} not found`); const psPaid = money(psOrder.total_paid_real); const currentPaid = money(order?.summary?.paid); const gross = money(order?.summary?.gross); let recorded = Number(mapping.paymentTotalSynced); if (!Number.isFinite(recorded)) { // Legacy rows did not record their PS payment baseline. Never guess that an // already-present Orbito payment should be appended again. recorded = Math.min(psPaid, currentPaid); } const delta = money(psPaid - recorded); const remaining = Math.max(0, money(gross - currentPaid)); const amount = Math.min(delta, remaining); if (amount > 0) { const transactionId = paymentTransactionId(config, mapping.psOrderId, psPaid); await Core.callModule('core/orders', 'payments.upsert', { orderId: String(mapping.orbitoOrderId), payment: { amount, method: psOrder.payment || 'PrestaShop', date: parsePrestashopDate(psOrder.date_upd || psOrder.date_add, nowDate), transactionId, }, }); Log.info('CRON: PS payment delta synced', { psOrderId: mapping.psOrderId, amount, cumulativeTotal: psPaid, transactionId, }); } await PsOrder.update({ _id: mapping._id }, { $set: { // PrestaShop may temporarily report a lower total during refund/update // processing. This integration does not create negative payments, so its // confirmed high-water mark must not move backwards and duplicate money later. paymentTotalSynced: Math.max(recorded, psPaid), paymentSyncedAt: nowDate, paymentCheckedAt: nowDate, nextPaymentCheckAt: new Date(nowDate.getTime() + nextCheckMs), } }); return { success: true, amount }; } catch (error) { await PsOrder.update({ _id: mapping._id }, { $set: { paymentCheckedAt: nowDate, nextPaymentCheckAt: new Date(nowDate.getTime() + retryCheckMs), } }).catch(() => {}); Log.warn('CRON: PS payment sync failed', { psOrderId: mapping.psOrderId, error: error.message }); return { success: false, error }; } } async function syncPaymentsForShop(config, api, since, until, options = {}, dependencies = {}) { const { PsOrder, now = () => new Date(), isLockValid = () => true, } = dependencies; const pageSize = options.pageSize || DEFAULT_PAGE_SIZE; const maxPages = options.maxPages || DEFAULT_MAX_PAGES; const nextCheckMs = options.nextCheckMs || 30 * 60 * 1000; const retryCheckMs = options.retryCheckMs || 5 * 60 * 1000; let processed = 0; let failures = 0; for (let page = 0; page < maxPages; page += 1) { if (!isLockValid()) throw new Error('PrestaShop payments lock was lost'); const nowDate = now(); const mappings = await PsOrder.find( duePaymentsQuery(config, since, until, nowDate), pageSize, 0, { nextPaymentCheckAt: 1, syncedAt: 1, _id: 1 } ); if (!mappings?.length) break; for (const mapping of mappings) { if (!isLockValid()) throw new Error('PrestaShop payments lock was lost'); const result = await processPaymentMapping(mapping, config, api, { ...dependencies, nowDate: now(), nextCheckMs, retryCheckMs, }); processed += 1; if (!result.success) failures += 1; } if (mappings.length < pageSize) break; } return { processed, failures }; } module.exports = { money, asOrders, paymentTransactionId, parsePrestashopDate, upsertMapping, importOrdersForShop, syncPaymentsForShop, processPaymentMapping, duePaymentsQuery, };