- 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.
109 lines
4.9 KiB
TypeScript
109 lines
4.9 KiB
TypeScript
import { startSync } from '../src/services/sat/sat.service.js';
|
|
import { prisma } from '../src/config/database.js';
|
|
|
|
interface ContribuyenteSync {
|
|
tenantId: string;
|
|
contribuyenteId: string;
|
|
rfc: string;
|
|
nombre: string;
|
|
dateFrom: string;
|
|
dateTo: string;
|
|
}
|
|
|
|
// Fecha final = ayer (el SAT rechaza fechas futuras y posiblemente hoy por zona horaria)
|
|
function getYesterdayEnd(): Date {
|
|
const now = new Date();
|
|
return new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1, 23, 59, 59);
|
|
}
|
|
|
|
const CONTRIBUYENTES: ContribuyenteSync[] = [
|
|
{ tenantId: '81116985-03cd-4843-97ba-05e8be9917c6', contribuyenteId: 'bb921e1d-ed49-4139-bb6f-bca28980050f', rfc: 'AUZA640701TI9', nombre: 'AARON AHUMADA ZEPEDA', dateFrom: '2026-01-01T00:00:00' },
|
|
{ tenantId: '45ddd745-5037-4325-b3ec-1a85cbf7b849', contribuyenteId: 'a75fd2aa-b1c9-427a-b2e0-8a449a216f09', rfc: 'TORA0007099R6', nombre: 'ALEXA GUADALUPE TORRES ROMERO', dateFrom: '2026-01-01T00:00:00' },
|
|
{ tenantId: 'c52c2f5d-b1ae-45c6-8cc8-b11c9611618a', contribuyenteId: '4a1d6014-f705-424b-b185-7740be6a80c6', rfc: 'TORC9611214CA', nombre: 'CARLOS HUSBERTO TORRES ROMERO', dateFrom: '2026-01-01T00:00:00' },
|
|
{ tenantId: 'c52c2f5d-b1ae-45c6-8cc8-b11c9611618a', contribuyenteId: '300fb54b-e3c2-4cdc-9f4d-3893f83d74b5', rfc: 'TORC9611214CB', nombre: 'CARLOS DEMO', dateFrom: '2024-01-01T00:00:00' },
|
|
{ tenantId: 'bcffc3ce-e5f5-4a66-b6bf-28da47bf7a41', contribuyenteId: '75a26067-66b2-4b5c-9dde-9ecc628a1e03', rfc: 'ROEM691011EZ4', nombre: 'MIGUEL ANGEL ROMERO ESTRADA', dateFrom: '2026-01-01T00:00:00' },
|
|
{ tenantId: '49b60455-c501-4ca2-b4bc-36ea7f2951a2', contribuyenteId: '3e0fdfe6-21b4-4f21-b14c-5ff5a67e7e49', rfc: 'AAG191008HS0', nombre: 'ACTIVO AGRICOLA', dateFrom: '2022-01-01T00:00:00' },
|
|
{ tenantId: '49b60455-c501-4ca2-b4bc-36ea7f2951a2', contribuyenteId: '8c9a714f-df72-4e97-b796-ed0d415a3829', rfc: 'DDA130507L51', nombre: 'DESARROLLO DE ALTO VALOR', dateFrom: '2026-01-01T00:00:00' },
|
|
{ tenantId: '49b60455-c501-4ca2-b4bc-36ea7f2951a2', contribuyenteId: '41ae59e0-1945-4d9a-90bb-69e577ce8c38', rfc: 'BME0710245XA', nombre: 'BRATECH MEXICO', dateFrom: '2023-01-01T00:00:00' },
|
|
{ tenantId: '49b60455-c501-4ca2-b4bc-36ea7f2951a2', contribuyenteId: '36b43d67-3b92-4307-95a6-c8e4053e0140', rfc: 'GCC080208478', nombre: 'GRUPO CORPORATIVO C&L Y ASOCIADOS, S.C.', dateFrom: '2022-01-01T00:00:00' },
|
|
];
|
|
|
|
const DATE_TO = getYesterdayEnd();
|
|
|
|
const POLL_INTERVAL_MS = 60000; // 1 minuto
|
|
|
|
function sleep(ms: number) {
|
|
return new Promise(resolve => setTimeout(resolve, ms));
|
|
}
|
|
|
|
async function waitForActiveSync(tenantId: string, contribuyenteId: string): Promise<void> {
|
|
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; downloaded: 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') {
|
|
return {
|
|
status: job.status,
|
|
error: job.errorMessage,
|
|
found: job.cfdisFound || 0,
|
|
downloaded: job.cfdisDownloaded || 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 main() {
|
|
console.log('[SYNC ALL] Iniciando syncs secuenciales con rangos optimizados');
|
|
|
|
for (const c of CONTRIBUYENTES) {
|
|
console.log(`\n[SYNC ALL] === ${c.nombre} (${c.rfc}) | ${c.dateFrom} → ${DATE_TO.toISOString()} ===`);
|
|
|
|
await waitForActiveSync(c.tenantId, c.contribuyenteId);
|
|
|
|
try {
|
|
const jobId = await startSync(
|
|
c.tenantId,
|
|
'initial',
|
|
new Date(c.dateFrom),
|
|
DATE_TO,
|
|
c.contribuyenteId,
|
|
);
|
|
console.log(`[SYNC ALL] Job iniciado: ${jobId}`);
|
|
|
|
const result = await waitForJob(jobId);
|
|
console.log(`[SYNC ALL] Job ${jobId} finalizado: status=${result.status}, found=${result.found}, downloaded=${result.downloaded}, inserted=${result.inserted}, updated=${result.updated}, progress=${result.progress}%`);
|
|
if (result.error) {
|
|
console.error(`[SYNC ALL] Error en job: ${result.error}`);
|
|
}
|
|
} catch (error: any) {
|
|
console.error(`[SYNC ALL] Error lanzando sync para ${c.rfc}:`, error.message || error);
|
|
}
|
|
}
|
|
|
|
console.log('\n[SYNC ALL] Todos los syncs completados');
|
|
}
|
|
|
|
main().catch(err => {
|
|
console.error('[SYNC ALL] Error fatal:', err);
|
|
process.exit(1);
|
|
});
|