feat(sat): reporte diario de errores SAT por proxy
- Agrega tabla sat_proxy_errors con proxy_usado, error_code, stage, message. - sat-client.service.ts expone proxyInfo usado en cada conexión SAT. - sat.service.ts registra errores de bloqueo/devolución del SAT en sat_proxy_errors y guarda proxyUsed en sat_sync_jobs. - Nuevo job sat-proxy-report.job.ts: cron 8 AM CDMX, envía email a ADMIN_EMAIL con errores de las últimas 24h agrupados por proxy/error_code. - Template de email sat-proxy-report.ts y método sendSatProxyReport. - Registra el cron en src/index.ts. - Actualiza docs/SAT-SYNC-IMPLEMENTATION.md.
This commit is contained in:
144
apps/api/scripts/sync-daily-cyl-failed.ts
Normal file
144
apps/api/scripts/sync-daily-cyl-failed.ts
Normal file
@@ -0,0 +1,144 @@
|
||||
import { startSync } from '../src/services/sat/sat.service.js';
|
||||
import { prisma, tenantDb } from '../src/config/database.js';
|
||||
|
||||
const TENANT_ID = '49b60455-c501-4ca2-b4bc-36ea7f2951a2';
|
||||
const CONCURRENCY = 1;
|
||||
const POLL_INTERVAL_MS = 60_000;
|
||||
const FAILED_SINCE = '2026-07-21 19:00:00';
|
||||
|
||||
function sleep(ms: number) {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
async function waitForActiveSync(tenantId: string, contribuyenteId: string): Promise<'clean' | 'active'> {
|
||||
const active = await prisma.satSyncJob.findFirst({
|
||||
where: {
|
||||
tenantId,
|
||||
contribuyenteId,
|
||||
status: { in: ['pending', 'running'] },
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
if (!active) return 'clean';
|
||||
return 'active';
|
||||
}
|
||||
|
||||
async function waitForJob(jobId: string): Promise<{ status: string; error: string | null; found: number; inserted: number; updated: 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' || job.status === 'pending') {
|
||||
return {
|
||||
status: job.status,
|
||||
error: job.errorMessage,
|
||||
found: job.cfdisFound || 0,
|
||||
inserted: job.cfdisInserted || 0,
|
||||
updated: job.cfdisUpdated || 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<T>(items: T[], concurrency: number, fn: (item: T) => Promise<void>): Promise<void> {
|
||||
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: { id: TENANT_ID },
|
||||
select: { id: true, rfc: true, nombre: true, databaseName: true },
|
||||
});
|
||||
|
||||
if (!tenant) {
|
||||
console.error(`[C&L Failed] Tenant ${TENANT_ID} no encontrado`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log(`[C&L Failed] Tenant: ${tenant.nombre} (${tenant.rfc}) | DB: ${tenant.databaseName}`);
|
||||
|
||||
// Obtener contribuyentes que tuvieron al menos un job failed desde FAILED_SINCE
|
||||
const failedRows = await prisma.$queryRawUnsafe<Array<{ contribuyente_id: string }>>(`
|
||||
SELECT contribuyente_id
|
||||
FROM sat_sync_jobs
|
||||
WHERE tenant_id = '${TENANT_ID}'
|
||||
AND status = 'failed'
|
||||
AND created_at > '${FAILED_SINCE}'
|
||||
GROUP BY contribuyente_id
|
||||
`);
|
||||
|
||||
const failedIds = failedRows.map((r) => r.contribuyente_id);
|
||||
console.log(`[C&L Failed] Contribuyentes con fallos desde ${FAILED_SINCE}: ${failedIds.length}`);
|
||||
|
||||
if (failedIds.length === 0) {
|
||||
console.log('[C&L Failed] No hay contribuyentes para reintentar');
|
||||
return;
|
||||
}
|
||||
|
||||
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
|
||||
WHERE c.entidad_id = ANY($1::uuid[])
|
||||
ORDER BY eg.nombre
|
||||
`,
|
||||
[failedIds]
|
||||
);
|
||||
|
||||
console.log(`[C&L Failed] Contribuyentes resueltos: ${contribuyentes.length}`);
|
||||
|
||||
const errors: string[] = [];
|
||||
let completed = 0;
|
||||
|
||||
await runWithConcurrency(contribuyentes, CONCURRENCY, async (c: any) => {
|
||||
console.log(`\n[SYNC] === ${c.rfc} | ${c.nombre} ===`);
|
||||
try {
|
||||
const activeState = await waitForActiveSync(tenant.id, c.id);
|
||||
if (activeState === 'active') {
|
||||
console.log(`[SKIP] ${c.rfc} tiene sync activo/pendiente; se omite`);
|
||||
return;
|
||||
}
|
||||
|
||||
const jobId = await startSync(tenant.id, 'daily', undefined, undefined, 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}, updated=${result.updated}, progress=${result.progress}%`);
|
||||
if (result.status === 'completed') completed++;
|
||||
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 Failed] Proceso finalizado. Completados: ${completed}/${contribuyentes.length}`);
|
||||
if (errors.length > 0) {
|
||||
console.error(`[C&L Failed] Errores (${errors.length}):`);
|
||||
for (const e of errors) console.error(` - ${e}`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(async (err) => {
|
||||
console.error('[C&L Failed] Error fatal:', err);
|
||||
await prisma.$disconnect().catch(() => {});
|
||||
process.exit(1);
|
||||
});
|
||||
Reference in New Issue
Block a user