fix: harden PrestaShop automation jobs
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
const { Log, Core, Utils } = require('@orbito/api-lib');
|
||||
const CronJob = require('cron').CronJob;
|
||||
const { CronJob } = require('cron');
|
||||
const PsOrder = require('./src/models/PsOrder');
|
||||
const PrestashopApi = require('./src/PrestaApi');
|
||||
const { importFromPSOrder } = require('./src/OrderImporter');
|
||||
@@ -7,221 +7,92 @@ const { isLegacyApi } = require('./src/utils');
|
||||
const { loadEnabledConfigs, setLastOrderId } = require('./src/module-config');
|
||||
const { registerPrestashopConfigBlocks } = require('./src/register-config');
|
||||
const { registerPrestashopPermissions } = require('./src/register-permissions');
|
||||
const { importOrdersForShop, syncPaymentsForShop } = require('./src/automation-jobs');
|
||||
const { createJobRuntime } = require('./src/job-runtime');
|
||||
|
||||
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 }] };
|
||||
const runtime = createJobRuntime(Core, Log);
|
||||
|
||||
Utils.loadMethods(__dirname + '/methods');
|
||||
|
||||
registerPrestashopConfigBlocks().catch(err => {
|
||||
Log.error('PrestaShop: nie udało się zarejestrować bloków Config', { error: err?.message });
|
||||
registerPrestashopConfigBlocks().catch(error => {
|
||||
Log.error('PrestaShop: nie udało się zarejestrować bloków Config', { error: error?.message });
|
||||
});
|
||||
registerPrestashopPermissions().catch(error => {
|
||||
Log.error('PrestaShop: nie udało się zarejestrować uprawnień', { error: error?.message });
|
||||
});
|
||||
|
||||
registerPrestashopPermissions().catch(err => {
|
||||
Log.error('PrestaShop: nie udało się zarejestrować uprawnień', { error: err?.message });
|
||||
});
|
||||
function apiFor(config) {
|
||||
return new PrestashopApi(config.apiUrl, config.apiKey, isLegacyApi(config.versionCode));
|
||||
}
|
||||
|
||||
const ordersPuller = new CronJob("0 */5 * * * *", async () => {
|
||||
const lockId = await Core.getLock('prestashop-orders-puller', 290000);
|
||||
if (!lockId) return;
|
||||
|
||||
try {
|
||||
let enabledShops = [];
|
||||
async function runOrdersPuller(isLockValid) {
|
||||
const configs = await loadEnabledConfigs();
|
||||
for (const config of configs) {
|
||||
if (!isLockValid()) break;
|
||||
try {
|
||||
enabledShops = await loadEnabledConfigs();
|
||||
await importOrdersForShop(config, apiFor(config), {
|
||||
Core, PsOrder, importFromPSOrder, setLastOrderId, Log, isLockValid,
|
||||
});
|
||||
} 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 setLastOrderId(lastOrderId);
|
||||
config.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));
|
||||
}
|
||||
}
|
||||
|
||||
if (config.lastProcessedId) {
|
||||
await setLastOrderId(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 });
|
||||
Log.error('Error pulling orders for shop config', { shopConfigId: config._id, error: error.message });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const paymentsSyncNew = new CronJob('0 */3 * * * *', async () => {
|
||||
const lockId = await Core.getLock('prestashop-payments-new', 120000);
|
||||
if (!lockId) return;
|
||||
try {
|
||||
const configs = await loadEnabledConfigs();
|
||||
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 });
|
||||
}
|
||||
async function runPaymentSync(kind, isLockValid) {
|
||||
const configs = await loadEnabledConfigs();
|
||||
const now = Date.now();
|
||||
const recent = kind === 'recent';
|
||||
const since = recent ? new Date(now - NEW_ORDERS_WINDOW_MS) : null;
|
||||
const until = recent ? null : new Date(now - NEW_ORDERS_WINDOW_MS);
|
||||
for (const config of configs) {
|
||||
if (!isLockValid()) break;
|
||||
try {
|
||||
await syncPaymentsForShop(config, apiFor(config), since, until, {
|
||||
pageSize: 50,
|
||||
maxPages: recent ? 4 : 10,
|
||||
nextCheckMs: recent ? 3 * 60 * 1000 : 30 * 60 * 1000,
|
||||
retryCheckMs: recent ? 3 * 60 * 1000 : 10 * 60 * 1000,
|
||||
}, { Core, PsOrder, Log, isLockValid });
|
||||
} catch (error) {
|
||||
Log.warn(`CRON: PS payments-${kind} error`, { shopConfigId: config._id, error: error.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 loadEnabledConfigs();
|
||||
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();
|
||||
const jobs = [
|
||||
new CronJob('0 */5 * * * *', () => runtime.track(() =>
|
||||
runtime.withRenewedLock('prestashop-orders-puller', 5 * 60 * 1000, runOrdersPuller)
|
||||
)),
|
||||
new CronJob('0 */3 * * * *', () => runtime.track(() =>
|
||||
runtime.withRenewedLock('prestashop-payments-sync', 5 * 60 * 1000, valid => runPaymentSync('recent', valid))
|
||||
)),
|
||||
new CronJob('30 */30 * * * *', () => runtime.track(() =>
|
||||
runtime.withRenewedLock('prestashop-payments-sync', 5 * 60 * 1000, valid => runPaymentSync('older', valid))
|
||||
)),
|
||||
];
|
||||
|
||||
function startJobs() {
|
||||
runtime.start();
|
||||
for (const job of jobs) if (!job.isActive) job.start();
|
||||
}
|
||||
|
||||
async function stopJobs() {
|
||||
for (const job of jobs) job.stop();
|
||||
await runtime.stop();
|
||||
}
|
||||
|
||||
// Preserve the module's existing startup behavior; lifecycle callbacks make repeated
|
||||
// enable/disable transitions safe and ensure no cron remains active while disabled.
|
||||
startJobs();
|
||||
Core.onEnabled(async () => {
|
||||
startJobs();
|
||||
Log.info('Module enabled');
|
||||
});
|
||||
Core.onDisabled(async () => {
|
||||
await stopJobs();
|
||||
Log.info('Module disabled; PrestaShop cron jobs stopped');
|
||||
});
|
||||
|
||||
module.exports = { startJobs, stopJobs, runOrdersPuller, runPaymentSync };
|
||||
|
||||
Reference in New Issue
Block a user