From 3eb0f33f3bf916d3f66981bd49e7dea0ea0ab661 Mon Sep 17 00:00:00 2001 From: Horux Dev Date: Tue, 28 Apr 2026 15:35:05 +0000 Subject: [PATCH] feat(timbres): 50 timbres mensuales auto para tenants plan custom --- apps/api/src/jobs/sat-sync.job.ts | 2 +- apps/api/src/services/facturapi.service.ts | 63 +++++++++++++++++++++- 2 files changed, 62 insertions(+), 3 deletions(-) diff --git a/apps/api/src/jobs/sat-sync.job.ts b/apps/api/src/jobs/sat-sync.job.ts index 1e0bafc..0ad94b5 100644 --- a/apps/api/src/jobs/sat-sync.job.ts +++ b/apps/api/src/jobs/sat-sync.job.ts @@ -390,7 +390,7 @@ export function startSatSyncJob(): void { } } - console.log(`[Subscription Cron] pending aplicados: ${pending.applied} (${pending.errors} errores), trials expirados: ${trials.expired}, timbres reseteados: ${timbres.reset}, declaraciones >5 años borradas: ${declsBorradas}, CSFs >5 años borradas: ${csfsBorradas}`); + console.log(`[Subscription Cron] pending aplicados: ${pending.applied} (${pending.errors} errores), trials expirados: ${trials.expired}, timbres reseteados: ${timbres.reset}, timbres custom creados: ${timbres.customCreated}, declaraciones >5 años borradas: ${declsBorradas}, CSFs >5 años borradas: ${csfsBorradas}`); } catch (error: any) { console.error('[Subscription Cron] Error:', error.message); } diff --git a/apps/api/src/services/facturapi.service.ts b/apps/api/src/services/facturapi.service.ts index 6151c92..dd5168e 100644 --- a/apps/api/src/services/facturapi.service.ts +++ b/apps/api/src/services/facturapi.service.ts @@ -643,12 +643,18 @@ export async function refundTimbre( * resetea `timbresUsados=0` y avanza la ventana un mes (tipo='mensual') o un año * (tipo='anual'). Usado por cron diario. Idempotente: si no hay vencidas, no-op. * + * Además, tenants con plan 'custom' reciben 50 timbres mensuales + * automáticamente. Si no tienen TimbreSuscripcion, se les crea; si tienen una + * vencida, se resetea; si tienen una vigente, no se toca. + * * Los paquetes adicionales NO se tocan aquí — su vigencia es 1 año fijo desde * la compra y el filtro `expiraEn > now` los excluye automáticamente cuando * caducan. */ -export async function resetExpiredMonthlyTimbres(): Promise<{ reset: number }> { +export async function resetExpiredMonthlyTimbres(): Promise<{ reset: number; customCreated: number }> { const now = new Date(); + + // 1) Resetear suscripciones vencidas (comportamiento original) const vencidas = await prisma.timbreSuscripcion.findMany({ where: { periodoFin: { lt: now } }, }); @@ -678,7 +684,60 @@ export async function resetExpiredMonthlyTimbres(): Promise<{ reset: number }> { console.log(`[Timbres] Reset mensual tenant ${s.tenantId}: nuevo periodo ${nextInicio.toISOString().split('T')[0]} → ${nextFin.toISOString().split('T')[0]}`); } - return { reset: count }; + // 2) Garantizar 50 timbres mensuales para tenants con plan 'custom' + const customTenants = await prisma.tenant.findMany({ + where: { plan: 'custom', active: true }, + select: { id: true }, + }); + + let customCreated = 0; + for (const t of customTenants) { + const existing = await prisma.timbreSuscripcion.findUnique({ + where: { tenantId: t.id }, + }); + + if (!existing) { + // Crear suscripción mensual de 50 timbres + const inicio = new Date(); + const fin = new Date(inicio); + fin.setMonth(fin.getMonth() + 1); + fin.setDate(fin.getDate() - 1); + + await prisma.timbreSuscripcion.create({ + data: { + tenantId: t.id, + tipo: 'mensual', + timbresLimite: 50, + timbresUsados: 0, + periodoInicio: inicio, + periodoFin: fin, + }, + }); + customCreated++; + console.log(`[Timbres] Custom tenant ${t.id}: creada suscripción de 50 timbres mensuales`); + } else if (existing.periodoFin < now) { + // Vencida: resetear con nuevo periodo mensual + const inicio = new Date(); + const fin = new Date(inicio); + fin.setMonth(fin.getMonth() + 1); + fin.setDate(fin.getDate() - 1); + + await prisma.timbreSuscripcion.update({ + where: { id: existing.id }, + data: { + timbresUsados: 0, + periodoInicio: inicio, + periodoFin: fin, + }, + }); + count++; + customCreated++; + console.log(`[Timbres] Custom tenant ${t.id}: reseteada suscripción de 50 timbres mensuales`); + } + // Si existing.periodoFin >= now, está vigente — no se toca + } + + return { reset: count, customCreated }; } // ============================================