Files

129 lines
5.2 KiB
JavaScript

const { Log, Core, Utils } = require('@orbito/api-lib');
const { CronJob } = require('cron');
const PsOrder = require('./src/models/PsOrder');
const PrestashopApi = require('./src/PrestaApi');
const { importFromPSOrder } = require('./src/OrderImporter');
const { isLegacyApi } = require('./src/utils');
const { loadConfig, 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 { ensureShopIcon } = require('./src/shop-icon');
const { registerStatusSyncHook, reconcileOrderStatuses } = require('./src/status-sync');
const NEW_ORDERS_WINDOW_MS = 20 * 60 * 1000;
// TTL locków cronowych w sekundach (jednostka oczekiwana przez Core.getLock/Core.extendLockTime).
const JOB_LOCK_TTL_SECONDS = 5 * 60;
const runtime = createJobRuntime(Core, Log);
Utils.loadMethods(__dirname + '/methods');
require('./src/register-contracts').registerContracts();
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 });
});
function apiFor(config) {
return new PrestashopApi(config.apiUrl, config.apiKey, isLegacyApi(config.versionCode));
}
registerStatusSyncHook({ Core, Log, PsOrder, loadConfig, apiFor }).catch(error => {
Log.error('PrestaShop: nie udało się zarejestrować synchronizacji statusów', { error: error?.message });
});
async function runOrdersPuller(isLockValid) {
const configs = await loadEnabledConfigs();
for (const config of configs) {
if (!isLockValid()) break;
try {
await importOrdersForShop(config, apiFor(config), {
Core, PsOrder, importFromPSOrder, setLastOrderId, Log, isLockValid,
});
} catch (error) {
Log.error('Error pulling orders for shop config', { shopConfigId: config._id, error: error.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 });
}
}
}
async function syncShopIcon() {
const configs = await loadEnabledConfigs();
for (const config of configs) {
await ensureShopIcon({
apiUrl: config.apiUrl,
shopName: config.shopName,
force: false,
});
}
}
const jobs = [
new CronJob('15 * * * * *', () => runtime.track(() =>
runtime.withRenewedLock('prestashop-status-reconciliation', JOB_LOCK_TTL_SECONDS, valid =>
reconcileOrderStatuses({ Core, Log, PsOrder, loadConfig, apiFor }, valid))
).catch(error => Log.error('PrestaShop status reconciliation worker failed', { error: error?.message }))),
new CronJob('0 * * * * *', () => runtime.track(() =>
runtime.withRenewedLock('prestashop-orders-puller', JOB_LOCK_TTL_SECONDS, runOrdersPuller)
)),
new CronJob('0 */3 * * * *', () => runtime.track(() =>
runtime.withRenewedLock('prestashop-payments-sync', JOB_LOCK_TTL_SECONDS, valid => runPaymentSync('recent', valid))
)),
new CronJob('30 */30 * * * *', () => runtime.track(() =>
runtime.withRenewedLock('prestashop-payments-sync', JOB_LOCK_TTL_SECONDS, 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();
syncShopIcon().catch(error => {
Log.warn('PrestaShop favicon: startup synchronization failed', { error: error?.message });
});
Core.onEnabled(async () => {
startJobs();
await syncShopIcon().catch(error => {
Log.warn('PrestaShop favicon: enable synchronization failed', { error: error?.message });
});
Log.info('Module enabled');
});
Core.onDisabled(async () => {
await stopJobs();
Log.info('Module disabled; PrestaShop cron jobs stopped');
});
module.exports = { startJobs, stopJobs, runOrdersPuller, runPaymentSync, syncShopIcon };