import { startSync } from '../src/services/sat/sat.service.js'; import { prisma, tenantDb } from '../src/config/database.js'; const TENANT_RFC = 'DESPACHO_MPG95QP7_XZVFF'; const CONCURRENCY = 6; const POLL_INTERVAL_MS = 60_000; function getYesterdayEnd(): Date { const now = new Date(); // Fecha de ayer a mediodía UTC. Se usa UTC para evitar que Prisma @db.Date // desplace el día al convertir de local a UTC (el servidor corre en UTC). return new Date(Date.UTC(now.getFullYear(), now.getMonth(), now.getDate() - 1, 12, 0, 0)); } function sleep(ms: number) { return new Promise((resolve) => setTimeout(resolve, ms)); } async function waitForActiveSync(tenantId: string, contribuyenteId: string): Promise { while (true) { const active = await prisma.satSyncJob.findFirst({ where: { tenantId, contribuyenteId, status: { in: ['pending', 'running'] }, }, }); if (!active) return; console.log(`[WAIT] Sync activo para ${contribuyenteId}. Esperando 60s...`); await sleep(POLL_INTERVAL_MS); } } async function waitForJob(jobId: string): Promise<{ status: string; error: string | null; found: number; inserted: number; progress: number }> { while (true) { const job = await prisma.satSyncJob.findUnique({ where: { id: jobId } }); if (!job) throw new Error(`Job ${jobId} no encontrado`); if (job.status === 'completed' || job.status === 'failed') { return { status: job.status, error: job.errorMessage, found: job.cfdisFound || 0, inserted: job.cfdisInserted || 0, progress: job.progressPercent || 0, }; } console.log(`[WAIT] Job ${jobId} status=${job.status}, progress=${job.progressPercent}%. Esperando 60s...`); await sleep(POLL_INTERVAL_MS); } } async function runWithConcurrency(items: T[], concurrency: number, fn: (item: T) => Promise): Promise { let index = 0; async function worker() { while (index < items.length) { const item = items[index++]; await fn(item); } } const workers = Array.from({ length: concurrency }, () => worker()); await Promise.all(workers); } async function main() { const tenant = await prisma.tenant.findUnique({ where: { rfc: TENANT_RFC }, select: { id: true, rfc: true, nombre: true, databaseName: true }, }); if (!tenant) { console.error(`[C&L] Tenant con RFC ${TENANT_RFC} no encontrado`); process.exit(1); } console.log(`[C&L] Tenant: ${tenant.nombre} (${tenant.rfc}) | DB: ${tenant.databaseName} | ID: ${tenant.id}`); const pool = await tenantDb.getPool(tenant.id, tenant.databaseName); const { rows: contribuyentes } = await pool.query(` SELECT c.entidad_id AS id, c.rfc, eg.nombre FROM contribuyentes c JOIN entidades_gestionadas eg ON eg.id = c.entidad_id JOIN fiel_contribuyente f ON f.contribuyente_id = c.entidad_id WHERE f.is_active = true AND f.valid_until >= NOW() ORDER BY eg.nombre `); console.log(`[C&L] Contribuyentes con FIEL activa: ${contribuyentes.length}`); const pendientes = []; for (const c of contribuyentes) { const hasInitial = await prisma.satSyncJob.findFirst({ where: { tenantId: tenant.id, contribuyenteId: c.id, type: 'initial', status: { in: ['completed', 'running'] }, }, }); if (!hasInitial) { pendientes.push(c); } else { console.log(`[SKIP] ${c.rfc} (${c.nombre}) ya tiene sync inicial iniciada o completada`); } } console.log(`[C&L] Contribuyentes a sincronizar: ${pendientes.length}`); for (const c of pendientes) { console.log(` - ${c.rfc} | ${c.nombre} | ${c.id}`); } if (pendientes.length === 0) { console.log('[C&L] Nada que sincronizar'); return; } const dateTo = getYesterdayEnd(); const errors: string[] = []; await runWithConcurrency(pendientes, CONCURRENCY, async (c: any) => { console.log(`\n[SYNC] === ${c.rfc} | ${c.nombre} ===`); try { await waitForActiveSync(tenant.id, c.id); const jobId = await startSync(tenant.id, 'initial', undefined, dateTo, c.id); console.log(`[SYNC] Job iniciado: ${jobId} para ${c.rfc}`); const result = await waitForJob(jobId); console.log(`[SYNC] ${c.rfc} finalizado: status=${result.status}, found=${result.found}, inserted=${result.inserted}, progress=${result.progress}%`); if (result.error) { console.error(`[SYNC] Error en ${c.rfc}: ${result.error}`); errors.push(`${c.rfc}: ${result.error}`); } } catch (error: any) { console.error(`[SYNC] Error lanzando sync para ${c.rfc}:`, error.message || error); errors.push(`${c.rfc}: ${error.message || error}`); } }); console.log('\n[C&L] Proceso finalizado'); if (errors.length > 0) { console.error(`[C&L] Errores (${errors.length}):`); for (const e of errors) console.error(` - ${e}`); process.exit(1); } } main().catch(async (err) => { console.error('[C&L] Error fatal:', err); await prisma.$disconnect().catch(() => {}); process.exit(1); });