Compare commits
6 Commits
b1eaf41681
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
63908f9e9d | ||
|
|
ed6cfed312 | ||
|
|
ab6b76fcb8 | ||
|
|
b52ff875be | ||
|
|
66d68c652c | ||
|
|
d3b326e78c |
@@ -9,8 +9,10 @@ import { resetExpiredMonthlyTimbres } from '../services/facturapi.service.js';
|
||||
import { purgeDeclaracionesAntiguas } from '../services/declaraciones.service.js';
|
||||
import { consultarConstancia, purgeConstanciasAntiguas } from '../services/constancia.service.js';
|
||||
import { tenantDb } from '../config/database.js';
|
||||
import type { Pool } from 'pg';
|
||||
|
||||
const SYNC_CRON_SCHEDULE = '0 3 * * *'; // 3:00 AM todos los días
|
||||
const RECOVERY_CRON_SCHEDULE = '0 10 * * *'; // 10:00 AM todos los días
|
||||
const CONCURRENT_SYNCS = 3; // Máximo de sincronizaciones simultáneas
|
||||
const OPINION_CRON_SCHEDULE = '0 4 * * 0'; // Sundays 4:00 AM
|
||||
const CSF_CRON_SCHEDULE = '0 4 1 * *'; // Día 1 de cada mes 04:00 AM (CSF mensual)
|
||||
@@ -20,6 +22,7 @@ const EXPIRY_REMINDERS_CRON = '0 9 * * *'; // 9:00 AM diario — avisos p
|
||||
|
||||
let isRunning = false;
|
||||
let isIncrementalRunning = false;
|
||||
let isRecoveryRunning = false;
|
||||
|
||||
/**
|
||||
* Verifica si un tenant tiene FIEL a nivel tenant (legacy Horux 360)
|
||||
@@ -388,8 +391,147 @@ async function runCsfJob(): Promise<void> {
|
||||
console.log(`[CSF Cron] Completado — éxito: ${success}, fallidos: ${failed}, sin FIEL: ${skipped}`);
|
||||
}
|
||||
|
||||
function getYesterdayEnd(): Date {
|
||||
const now = new Date();
|
||||
return new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1, 23, 59, 59);
|
||||
}
|
||||
|
||||
async function hasIncompleteCfdis(pool: Pool, contribuyenteId: string): Promise<boolean> {
|
||||
const { rows } = await pool.query<{ count: string }>(`
|
||||
SELECT COUNT(*)::text as count
|
||||
FROM cfdis
|
||||
WHERE contribuyente_id = $1
|
||||
AND status = 'Vigente'
|
||||
AND tipo_comprobante IN ('I', 'E')
|
||||
AND xml_original IS NULL
|
||||
`, [contribuyenteId]);
|
||||
return Number(rows[0]?.count || 0) > 0;
|
||||
}
|
||||
|
||||
async function getOldestIncompleteCfdiDate(pool: Pool, contribuyenteId: string): Promise<Date | null> {
|
||||
const { rows } = await pool.query<{ fecha_emision: Date | null }>(`
|
||||
SELECT MIN(fecha_emision) as fecha_emision
|
||||
FROM cfdis
|
||||
WHERE contribuyente_id = $1
|
||||
AND status = 'Vigente'
|
||||
AND tipo_comprobante IN ('I', 'E')
|
||||
AND xml_original IS NULL
|
||||
`, [contribuyenteId]);
|
||||
return rows[0]?.fecha_emision || null;
|
||||
}
|
||||
|
||||
async function waitForRecoveryJob(jobId: string): Promise<void> {
|
||||
while (true) {
|
||||
const job = await prisma.satSyncJob.findUnique({ where: { id: jobId } });
|
||||
if (!job || job.status === 'completed' || job.status === 'failed') {
|
||||
return;
|
||||
}
|
||||
await new Promise(resolve => setTimeout(resolve, 60000));
|
||||
}
|
||||
}
|
||||
|
||||
async function recoverContribuyente(tenantId: string, databaseName: string, contribuyenteId: string): Promise<void> {
|
||||
try {
|
||||
const status = await getSyncStatus(tenantId, contribuyenteId);
|
||||
if (status.hasActiveSync) {
|
||||
console.log(`[SAT Recovery] ${contribuyenteId} tiene sync activo, omitiendo`);
|
||||
return;
|
||||
}
|
||||
|
||||
const pool = await tenantDb.getPool(tenantId, databaseName);
|
||||
const hasIncomplete = await hasIncompleteCfdis(pool, contribuyenteId);
|
||||
|
||||
const lastDaily = await prisma.satSyncJob.findFirst({
|
||||
where: { tenantId, contribuyenteId, type: 'daily' },
|
||||
orderBy: { startedAt: 'desc' },
|
||||
});
|
||||
|
||||
if (!hasIncomplete && lastDaily?.status !== 'failed') {
|
||||
return;
|
||||
}
|
||||
|
||||
const dateTo = getYesterdayEnd();
|
||||
let dateFrom = new Date(dateTo.getFullYear() - 1, dateTo.getMonth(), dateTo.getDate());
|
||||
|
||||
if (hasIncomplete) {
|
||||
const oldest = await getOldestIncompleteCfdiDate(pool, contribuyenteId);
|
||||
if (oldest) {
|
||||
dateFrom = new Date(oldest.getFullYear(), oldest.getMonth(), 1);
|
||||
dateFrom.setMonth(dateFrom.getMonth() - 1);
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`[SAT Recovery] Recuperando ${contribuyenteId}: ${dateFrom.toISOString()} → ${dateTo.toISOString()}`);
|
||||
const jobId = await startSync(tenantId, 'initial', dateFrom, dateTo, contribuyenteId);
|
||||
console.log(`[SAT Recovery] Job ${jobId} iniciado`);
|
||||
|
||||
await waitForRecoveryJob(jobId);
|
||||
} catch (error: any) {
|
||||
console.error(`[SAT Recovery] Error recuperando ${contribuyenteId}:`, error.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function recoverTenant(tenantId: string): Promise<void> {
|
||||
const tenant = await prisma.tenant.findUnique({
|
||||
where: { id: tenantId },
|
||||
select: { databaseName: true },
|
||||
});
|
||||
if (!tenant?.databaseName) return;
|
||||
|
||||
const pool = await tenantDb.getPool(tenantId, tenant.databaseName);
|
||||
const { rows } = await pool.query<{ entidad_id: string }>('SELECT entidad_id FROM contribuyentes');
|
||||
const contribuyenteIds = rows.map(r => r.entidad_id);
|
||||
|
||||
if (contribuyenteIds.length === 0) {
|
||||
const status = await getSyncStatus(tenantId);
|
||||
if (status.hasActiveSync) return;
|
||||
const lastDaily = await prisma.satSyncJob.findFirst({
|
||||
where: { tenantId, contribuyenteId: null, type: 'daily' },
|
||||
orderBy: { startedAt: 'desc' },
|
||||
});
|
||||
if (lastDaily?.status === 'failed') {
|
||||
const dateTo = getYesterdayEnd();
|
||||
const dateFrom = new Date(dateTo.getFullYear() - 1, dateTo.getMonth(), dateTo.getDate());
|
||||
console.log(`[SAT Recovery] Recuperando tenant legacy ${tenantId}`);
|
||||
const jobId = await startSync(tenantId, 'initial', dateFrom, dateTo);
|
||||
await waitForRecoveryJob(jobId);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
for (const contribuyenteId of contribuyenteIds) {
|
||||
await recoverContribuyente(tenantId, tenant.databaseName, contribuyenteId);
|
||||
}
|
||||
}
|
||||
|
||||
async function runRecoverySyncJob(): Promise<void> {
|
||||
if (isRecoveryRunning) {
|
||||
console.log('[SAT Recovery] Ya en ejecución, omitiendo');
|
||||
return;
|
||||
}
|
||||
|
||||
isRecoveryRunning = true;
|
||||
console.log('[SAT Recovery] Iniciando job de recuperación');
|
||||
|
||||
try {
|
||||
const tenantIds = await getTenantsWithFiel();
|
||||
console.log(`[SAT Recovery] ${tenantIds.length} tenants con FIEL`);
|
||||
|
||||
for (const tenantId of tenantIds) {
|
||||
await recoverTenant(tenantId);
|
||||
}
|
||||
|
||||
console.log('[SAT Recovery] Job de recuperación completado');
|
||||
} catch (error: any) {
|
||||
console.error('[SAT Recovery] Error:', error.message);
|
||||
} finally {
|
||||
isRecoveryRunning = false;
|
||||
}
|
||||
}
|
||||
|
||||
let scheduledTask: ReturnType<typeof cron.schedule> | null = null;
|
||||
let retryTask: ReturnType<typeof cron.schedule> | null = null;
|
||||
let recoveryTask: ReturnType<typeof cron.schedule> | null = null;
|
||||
let opinionTask: ReturnType<typeof cron.schedule> | null = null;
|
||||
let csfTask: ReturnType<typeof cron.schedule> | null = null;
|
||||
let incrementalTask: ReturnType<typeof cron.schedule> | null = null;
|
||||
@@ -430,6 +572,19 @@ export function startSatSyncJob(): void {
|
||||
timezone: 'America/Mexico_City',
|
||||
});
|
||||
|
||||
// Cron de recuperación: 10:00 AM diario. Revisa si el sync diario falló o si
|
||||
// hay CFDIs vigentes sin XML, y relanza un sync `initial` con rango extendido
|
||||
// para completar los XML faltantes.
|
||||
recoveryTask = cron.schedule(RECOVERY_CRON_SCHEDULE, async () => {
|
||||
try {
|
||||
await runRecoverySyncJob();
|
||||
} catch (error: any) {
|
||||
console.error('[SAT Recovery Cron] Error:', error.message);
|
||||
}
|
||||
}, {
|
||||
timezone: 'America/Mexico_City',
|
||||
});
|
||||
|
||||
// Cron watchdog: cada 2h marca como `failed` los jobs que quedaron stale
|
||||
// (pending con nextRetryAt > 12h atrás, running con startedAt > 4h atrás).
|
||||
// Thresholds sobreescribibles vía env (STALE_PENDING_HOURS / STALE_RUNNING_HOURS)
|
||||
@@ -535,6 +690,7 @@ export function startSatSyncJob(): void {
|
||||
|
||||
console.log(`[SAT Cron] Job programado para: ${SYNC_CRON_SCHEDULE} (America/Mexico_City)`);
|
||||
console.log(`[SAT Cron] Retry programado cada hora`);
|
||||
console.log(`[SAT Recovery Cron] Programado para: ${RECOVERY_CRON_SCHEDULE} (America/Mexico_City)`);
|
||||
console.log(`[Opinion Cron] Programado para: ${OPINION_CRON_SCHEDULE} (America/Mexico_City)`);
|
||||
console.log(`[CSF Cron] Programado para: ${CSF_CRON_SCHEDULE} (America/Mexico_City)`);
|
||||
console.log(`[SAT Cron Inc] Incremental Enterprise programado para: ${INCREMENTAL_CRON_SCHEDULE} (America/Mexico_City)`);
|
||||
@@ -554,6 +710,10 @@ export function stopSatSyncJob(): void {
|
||||
retryTask.stop();
|
||||
retryTask = null;
|
||||
}
|
||||
if (recoveryTask) {
|
||||
recoveryTask.stop();
|
||||
recoveryTask = null;
|
||||
}
|
||||
if (opinionTask) {
|
||||
opinionTask.stop();
|
||||
opinionTask = null;
|
||||
|
||||
@@ -1107,10 +1107,21 @@ export async function getKpis(
|
||||
const ctx = await resolveContribuyenteContext(pool, tenantId, contribuyenteId);
|
||||
const esEmisor = ctx.esEmisor;
|
||||
const esReceptor = ctx.esReceptor;
|
||||
const ingresosData = await calcularIngresosPorRegimen(pool, tenantId, fechaInicio, fechaFin, undefined, undefined, conciliacion, contribuyenteId);
|
||||
const egresosData = await calcularEgresosPorRegimen(pool, tenantId, fechaInicio, fechaFin, undefined, undefined, conciliacion, contribuyenteId);
|
||||
const adquisicionData = await calcularAdquisicionesMercancias(pool, tenantId, fechaInicio, fechaFin, conciliacion, contribuyenteId);
|
||||
const ivaData = await calcularIvaBalancePorRegimen(pool, tenantId, fechaInicio, fechaFin, undefined, undefined, conciliacion, contribuyenteId);
|
||||
const [
|
||||
ingresosData,
|
||||
egresosData,
|
||||
adquisicionData,
|
||||
ivaData,
|
||||
ncsEmitidasData,
|
||||
ncsRecibidasData,
|
||||
] = await Promise.all([
|
||||
calcularIngresosPorRegimen(pool, tenantId, fechaInicio, fechaFin, undefined, undefined, conciliacion, contribuyenteId),
|
||||
calcularEgresosPorRegimen(pool, tenantId, fechaInicio, fechaFin, undefined, undefined, conciliacion, contribuyenteId),
|
||||
calcularAdquisicionesMercancias(pool, tenantId, fechaInicio, fechaFin, conciliacion, contribuyenteId),
|
||||
calcularIvaBalancePorRegimen(pool, tenantId, fechaInicio, fechaFin, undefined, undefined, conciliacion, contribuyenteId),
|
||||
calcularNcsEmitidasPorRegimen(pool, tenantId, fechaInicio, fechaFin, undefined, undefined, conciliacion, contribuyenteId),
|
||||
calcularNcsRecibidasPorRegimen(pool, tenantId, fechaInicio, fechaFin, undefined, undefined, conciliacion, contribuyenteId),
|
||||
]);
|
||||
|
||||
// IVA a favor año actual: desde enero del año en curso
|
||||
const ivaAFavorAcumulado = await calcularIvaAFavorAcumulado(pool, tenantId, fechaFin, undefined, conciliacion, contribuyenteId);
|
||||
@@ -1163,6 +1174,10 @@ export async function getKpis(
|
||||
cfdisEmitidosPorRegimen: emitidosPorRegimen,
|
||||
cfdisRecibidos: recibidosPorRegimen.reduce((s: number, r: any) => s + r.total, 0),
|
||||
cfdisRecibidosPorRegimen: recibidosPorRegimen,
|
||||
ncsEmitidas: ncsEmitidasData.total,
|
||||
ncsEmitidasPorRegimen: ncsEmitidasData.porRegimen,
|
||||
ncsRecibidas: ncsRecibidasData.total,
|
||||
ncsRecibidasPorRegimen: ncsRecibidasData.porRegimen,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -19,6 +19,8 @@ import {
|
||||
AlertTriangle,
|
||||
ShoppingCart,
|
||||
CheckSquare,
|
||||
FileMinus,
|
||||
FilePlus,
|
||||
} from 'lucide-react';
|
||||
import { cn } from '@horux/shared-ui';
|
||||
import { FiscalDisclaimer } from '@/components/fiscal-disclaimer';
|
||||
@@ -118,6 +120,15 @@ export default function DashboardPage() {
|
||||
? kpis?.ivaBalancePorRegimen?.find(r => r.regimenClave === regimenSeleccionado)?.monto || 0
|
||||
: kpis?.ivaBalance || 0;
|
||||
|
||||
// Notas de crédito
|
||||
const ncsEmitidasDisplay = regimenSeleccionado
|
||||
? kpis?.ncsEmitidasPorRegimen?.find(r => r.regimenClave === regimenSeleccionado)?.monto || 0
|
||||
: kpis?.ncsEmitidas || 0;
|
||||
|
||||
const ncsRecibidasDisplay = regimenSeleccionado
|
||||
? kpis?.ncsRecibidasPorRegimen?.find(r => r.regimenClave === regimenSeleccionado)?.monto || 0
|
||||
: kpis?.ncsRecibidas || 0;
|
||||
|
||||
const ivaAnterior = regimenSeleccionado
|
||||
? kpisAnterior?.ivaBalancePorRegimen?.find(r => r.regimenClave === regimenSeleccionado)?.monto || 0
|
||||
: kpisAnterior?.ivaBalance || 0;
|
||||
@@ -126,9 +137,15 @@ export default function DashboardPage() {
|
||||
? Math.round(((ivaDisplay - ivaAnterior) / Math.abs(ivaAnterior)) * 10000) / 100
|
||||
: null;
|
||||
|
||||
const utilidadDisplay = ingresosDisplay - egresosDisplay;
|
||||
const margenDisplay = ingresosDisplay > 0
|
||||
? Math.round((utilidadDisplay / ingresosDisplay) * 10000) / 100
|
||||
// Utilidad ajustada por notas de crédito:
|
||||
// Ingresos netos = Ingresos − NCs emitidas
|
||||
// Egresos netos = Gastos − NCs recibidas
|
||||
// Utilidad neta = Ingresos netos − Egresos netos
|
||||
const ingresosNetosDisplay = ingresosDisplay - ncsEmitidasDisplay;
|
||||
const egresosNetosDisplay = egresosDisplay - ncsRecibidasDisplay;
|
||||
const utilidadDisplay = ingresosNetosDisplay - egresosNetosDisplay;
|
||||
const margenDisplay = ingresosNetosDisplay > 0
|
||||
? Math.round((utilidadDisplay / ingresosNetosDisplay) * 10000) / 100
|
||||
: 0;
|
||||
|
||||
const formatCurrency = (value: number) =>
|
||||
@@ -203,7 +220,7 @@ export default function DashboardPage() {
|
||||
</div>
|
||||
|
||||
{/* KPIs */}
|
||||
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
|
||||
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
|
||||
<KpiCard
|
||||
title={regimenSeleccionado ? `Ingresos del Mes (${regimenSeleccionado})` : 'Ingresos del Mes'}
|
||||
value={ingresosDisplay}
|
||||
@@ -216,6 +233,13 @@ export default function DashboardPage() {
|
||||
}
|
||||
href={drillUrl('Ingresos del Mes - CFDIs', { bucket: 'ingresos' })}
|
||||
/>
|
||||
<KpiCard
|
||||
title={regimenSeleccionado ? `NCs Emitidas (${regimenSeleccionado})` : 'NCs Emitidas'}
|
||||
value={ncsEmitidasDisplay}
|
||||
icon={<FileMinus className="h-4 w-4" />}
|
||||
trend="neutral"
|
||||
trendValue="Notas de crédito emitidas"
|
||||
/>
|
||||
<KpiCard
|
||||
title={regimenSeleccionado ? `Gastos del Mes (${regimenSeleccionado})` : 'Gastos del Mes'}
|
||||
value={egresosDisplay}
|
||||
@@ -229,11 +253,18 @@ export default function DashboardPage() {
|
||||
href={drillUrl('Gastos del Mes - CFDIs', { bucket: 'gastos' })}
|
||||
/>
|
||||
<KpiCard
|
||||
title="Utilidad"
|
||||
title={regimenSeleccionado ? `NCs Recibidas (${regimenSeleccionado})` : 'NCs Recibidas'}
|
||||
value={ncsRecibidasDisplay}
|
||||
icon={<FilePlus className="h-4 w-4" />}
|
||||
trend="neutral"
|
||||
trendValue="Notas de crédito recibidas"
|
||||
/>
|
||||
<KpiCard
|
||||
title={regimenSeleccionado ? `Utilidad Neta (${regimenSeleccionado})` : 'Utilidad Neta'}
|
||||
value={utilidadDisplay}
|
||||
icon={<Wallet className="h-4 w-4" />}
|
||||
trend={utilidadDisplay > 0 ? 'up' : 'down'}
|
||||
trendValue={`${margenDisplay}% margen`}
|
||||
trendValue={`${margenDisplay}% margen · incluye NCs`}
|
||||
/>
|
||||
<KpiCard
|
||||
title={regimenSeleccionado ? `Balance IVA (${regimenSeleccionado})` : 'Balance IVA'}
|
||||
@@ -252,7 +283,7 @@ export default function DashboardPage() {
|
||||
|
||||
{/* Desglose por régimen */}
|
||||
{!regimenSeleccionado && kpis && (
|
||||
(kpis.ingresosPorRegimen.length > 1 || kpis.egresosPorRegimen.length > 1 || kpis.ivaBalancePorRegimen.length > 1) && (
|
||||
(kpis.ingresosPorRegimen.length > 1 || kpis.egresosPorRegimen.length > 1 || kpis.ivaBalancePorRegimen.length > 1 || kpis.ncsEmitidasPorRegimen.length > 1 || kpis.ncsRecibidasPorRegimen.length > 1) && (
|
||||
<div className="grid gap-4 md:grid-cols-2 3xl:grid-cols-3">
|
||||
{kpis.ingresosPorRegimen.length > 1 && (
|
||||
<Card>
|
||||
@@ -316,6 +347,46 @@ export default function DashboardPage() {
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
{kpis.ncsEmitidasPorRegimen.length > 1 && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base font-medium">NCs Emitidas por Regimen</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-2">
|
||||
{kpis.ncsEmitidasPorRegimen.map((r) => (
|
||||
<div key={r.regimenClave} className="flex items-center justify-between py-2 border-b last:border-0">
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="text-xs font-mono font-bold bg-muted px-2 py-1 rounded">{r.regimenClave}</span>
|
||||
<span className="text-sm">{r.regimenDescripcion}</span>
|
||||
</div>
|
||||
<span className="text-sm font-semibold">{formatCurrency(r.monto)}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
{kpis.ncsRecibidasPorRegimen.length > 1 && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base font-medium">NCs Recibidas por Regimen</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-2">
|
||||
{kpis.ncsRecibidasPorRegimen.map((r) => (
|
||||
<div key={r.regimenClave} className="flex items-center justify-between py-2 border-b last:border-0">
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="text-xs font-mono font-bold bg-muted px-2 py-1 rounded">{r.regimenClave}</span>
|
||||
<span className="text-sm">{r.regimenDescripcion}</span>
|
||||
</div>
|
||||
<span className="text-sm font-semibold">{formatCurrency(r.monto)}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
|
||||
|
||||
@@ -33,6 +33,10 @@ export interface KpiData {
|
||||
cfdisEmitidosPorRegimen: { regimen: string; total: number }[];
|
||||
cfdisRecibidos: number;
|
||||
cfdisRecibidosPorRegimen: { regimen: string; total: number }[];
|
||||
ncsEmitidas: number;
|
||||
ncsEmitidasPorRegimen: IngresoRegimen[];
|
||||
ncsRecibidas: number;
|
||||
ncsRecibidasPorRegimen: IngresoRegimen[];
|
||||
}
|
||||
|
||||
export interface IngresosEgresosData {
|
||||
|
||||
Reference in New Issue
Block a user