feat(sat): add scheduled cron job for daily sync (Phase 6)
- Add sat-sync.job.ts with scheduled daily sync at 3:00 AM - Automatic detection of tenants with active FIEL - Initial sync (10 years) for new tenants, daily for existing - Concurrent processing with configurable batch size - Integration with app startup for production environment - Install node-cron dependency Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
@@ -27,6 +27,7 @@
|
||||
"fast-xml-parser": "^5.3.3",
|
||||
"helmet": "^8.0.0",
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"node-cron": "^4.2.1",
|
||||
"node-forge": "^1.3.3",
|
||||
"zod": "^3.23.0"
|
||||
},
|
||||
@@ -37,6 +38,7 @@
|
||||
"@types/express": "^5.0.0",
|
||||
"@types/jsonwebtoken": "^9.0.7",
|
||||
"@types/node": "^22.0.0",
|
||||
"@types/node-cron": "^3.0.11",
|
||||
"@types/node-forge": "^1.3.14",
|
||||
"prisma": "^5.22.0",
|
||||
"tsx": "^4.19.0",
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
import { app } from './app.js';
|
||||
import { env } from './config/env.js';
|
||||
import { startSatSyncJob } from './jobs/sat-sync.job.js';
|
||||
|
||||
const PORT = parseInt(env.PORT, 10);
|
||||
|
||||
app.listen(PORT, '0.0.0.0', () => {
|
||||
console.log(`🚀 API Server running on http://0.0.0.0:${PORT}`);
|
||||
console.log(`📊 Environment: ${env.NODE_ENV}`);
|
||||
console.log(`API Server running on http://0.0.0.0:${PORT}`);
|
||||
console.log(`Environment: ${env.NODE_ENV}`);
|
||||
|
||||
// Iniciar job de sincronización SAT
|
||||
if (env.NODE_ENV === 'production') {
|
||||
startSatSyncJob();
|
||||
}
|
||||
});
|
||||
|
||||
162
apps/api/src/jobs/sat-sync.job.ts
Normal file
162
apps/api/src/jobs/sat-sync.job.ts
Normal file
@@ -0,0 +1,162 @@
|
||||
import cron from 'node-cron';
|
||||
import { prisma } from '../config/database.js';
|
||||
import { startSync, getSyncStatus } from '../services/sat/sat.service.js';
|
||||
import { hasFielConfigured } from '../services/fiel.service.js';
|
||||
|
||||
const SYNC_CRON_SCHEDULE = '0 3 * * *'; // 3:00 AM todos los días
|
||||
const CONCURRENT_SYNCS = 3; // Máximo de sincronizaciones simultáneas
|
||||
|
||||
let isRunning = false;
|
||||
|
||||
/**
|
||||
* Obtiene los tenants que tienen FIEL configurada y activa
|
||||
*/
|
||||
async function getTenantsWithFiel(): Promise<string[]> {
|
||||
const tenants = await prisma.tenant.findMany({
|
||||
where: { active: true },
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
const tenantsWithFiel: string[] = [];
|
||||
|
||||
for (const tenant of tenants) {
|
||||
const hasFiel = await hasFielConfigured(tenant.id);
|
||||
if (hasFiel) {
|
||||
tenantsWithFiel.push(tenant.id);
|
||||
}
|
||||
}
|
||||
|
||||
return tenantsWithFiel;
|
||||
}
|
||||
|
||||
/**
|
||||
* Verifica si un tenant necesita sincronización inicial
|
||||
*/
|
||||
async function needsInitialSync(tenantId: string): Promise<boolean> {
|
||||
const completedSync = await prisma.satSyncJob.findFirst({
|
||||
where: {
|
||||
tenantId,
|
||||
type: 'initial',
|
||||
status: 'completed',
|
||||
},
|
||||
});
|
||||
|
||||
return !completedSync;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ejecuta sincronización para un tenant
|
||||
*/
|
||||
async function syncTenant(tenantId: string): Promise<void> {
|
||||
try {
|
||||
// Verificar si hay sync activo
|
||||
const status = await getSyncStatus(tenantId);
|
||||
if (status.hasActiveSync) {
|
||||
console.log(`[SAT Cron] Tenant ${tenantId} ya tiene sync activo, omitiendo`);
|
||||
return;
|
||||
}
|
||||
|
||||
// Determinar tipo de sync
|
||||
const needsInitial = await needsInitialSync(tenantId);
|
||||
const syncType = needsInitial ? 'initial' : 'daily';
|
||||
|
||||
console.log(`[SAT Cron] Iniciando sync ${syncType} para tenant ${tenantId}`);
|
||||
const jobId = await startSync(tenantId, syncType);
|
||||
console.log(`[SAT Cron] Job ${jobId} iniciado para tenant ${tenantId}`);
|
||||
} catch (error: any) {
|
||||
console.error(`[SAT Cron] Error sincronizando tenant ${tenantId}:`, error.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ejecuta el job de sincronización para todos los tenants
|
||||
*/
|
||||
async function runSyncJob(): Promise<void> {
|
||||
if (isRunning) {
|
||||
console.log('[SAT Cron] Job ya en ejecución, omitiendo');
|
||||
return;
|
||||
}
|
||||
|
||||
isRunning = true;
|
||||
console.log('[SAT Cron] Iniciando job de sincronización diaria');
|
||||
|
||||
try {
|
||||
const tenantIds = await getTenantsWithFiel();
|
||||
console.log(`[SAT Cron] ${tenantIds.length} tenants con FIEL configurada`);
|
||||
|
||||
if (tenantIds.length === 0) {
|
||||
console.log('[SAT Cron] No hay tenants para sincronizar');
|
||||
return;
|
||||
}
|
||||
|
||||
// Procesar en lotes para no saturar
|
||||
for (let i = 0; i < tenantIds.length; i += CONCURRENT_SYNCS) {
|
||||
const batch = tenantIds.slice(i, i + CONCURRENT_SYNCS);
|
||||
await Promise.all(batch.map(syncTenant));
|
||||
|
||||
// Pequeña pausa entre lotes
|
||||
if (i + CONCURRENT_SYNCS < tenantIds.length) {
|
||||
await new Promise(resolve => setTimeout(resolve, 5000));
|
||||
}
|
||||
}
|
||||
|
||||
console.log('[SAT Cron] Job de sincronización completado');
|
||||
} catch (error: any) {
|
||||
console.error('[SAT Cron] Error en job:', error.message);
|
||||
} finally {
|
||||
isRunning = false;
|
||||
}
|
||||
}
|
||||
|
||||
let scheduledTask: ReturnType<typeof cron.schedule> | null = null;
|
||||
|
||||
/**
|
||||
* Inicia el job programado
|
||||
*/
|
||||
export function startSatSyncJob(): void {
|
||||
if (scheduledTask) {
|
||||
console.log('[SAT Cron] Job ya está programado');
|
||||
return;
|
||||
}
|
||||
|
||||
// Validar expresión cron
|
||||
if (!cron.validate(SYNC_CRON_SCHEDULE)) {
|
||||
console.error('[SAT Cron] Expresión cron inválida:', SYNC_CRON_SCHEDULE);
|
||||
return;
|
||||
}
|
||||
|
||||
scheduledTask = cron.schedule(SYNC_CRON_SCHEDULE, runSyncJob, {
|
||||
timezone: 'America/Mexico_City',
|
||||
});
|
||||
|
||||
console.log(`[SAT Cron] Job programado para: ${SYNC_CRON_SCHEDULE} (America/Mexico_City)`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Detiene el job programado
|
||||
*/
|
||||
export function stopSatSyncJob(): void {
|
||||
if (scheduledTask) {
|
||||
scheduledTask.stop();
|
||||
scheduledTask = null;
|
||||
console.log('[SAT Cron] Job detenido');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ejecuta el job manualmente (para testing o ejecución forzada)
|
||||
*/
|
||||
export async function runSatSyncJobManually(): Promise<void> {
|
||||
await runSyncJob();
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtiene información del próximo job programado
|
||||
*/
|
||||
export function getJobInfo(): { scheduled: boolean; expression: string; timezone: string } {
|
||||
return {
|
||||
scheduled: scheduledTask !== null,
|
||||
expression: SYNC_CRON_SCHEDULE,
|
||||
timezone: 'America/Mexico_City',
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user