feat(timbres): 50 timbres mensuales auto para tenants plan custom

This commit is contained in:
Horux Dev
2026-04-28 15:35:05 +00:00
parent ee9c76612e
commit 3eb0f33f3b
2 changed files with 62 additions and 3 deletions

View File

@@ -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) { } catch (error: any) {
console.error('[Subscription Cron] Error:', error.message); console.error('[Subscription Cron] Error:', error.message);
} }

View File

@@ -643,12 +643,18 @@ export async function refundTimbre(
* resetea `timbresUsados=0` y avanza la ventana un mes (tipo='mensual') o un año * 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. * (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 * 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 * la compra y el filtro `expiraEn > now` los excluye automáticamente cuando
* caducan. * caducan.
*/ */
export async function resetExpiredMonthlyTimbres(): Promise<{ reset: number }> { export async function resetExpiredMonthlyTimbres(): Promise<{ reset: number; customCreated: number }> {
const now = new Date(); const now = new Date();
// 1) Resetear suscripciones vencidas (comportamiento original)
const vencidas = await prisma.timbreSuscripcion.findMany({ const vencidas = await prisma.timbreSuscripcion.findMany({
where: { periodoFin: { lt: now } }, 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]}`); 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 };
} }
// ============================================ // ============================================