import type { Prisma, PrismaClient } from '@generated/prisma/client'; import type { Plan, PlanLimitsImpactDto, PlanLimitsImpactQuery, ProblemDetails, Result } from '@gruperly/shared'; import { ok } from '@gruperly/shared'; import prisma from '@/lib/prisma'; import { getGraceDays, proSubscriptionWhere } from '@/modules/billing/lib'; type PlanLimitsImpactDeps = { db?: Pick; graceDays?: number; now?: () => Date; }; /** * How many accounts on a plan would exceed new limits, i.e. become read only * as soon as they are saved (limits apply at once). Usage is the PlanGuard's: * groups owned, and people with at least one ACTIVE membership. */ export class PlanLimitsImpact { constructor(private readonly deps: PlanLimitsImpactDeps = {}) {} async execute(plan: Plan, query: PlanLimitsImpactQuery): Promise> { const db = this.deps.db ?? prisma; const now = this.deps.now?.() ?? new Date(); const graceDays = this.deps.graceDays ?? getGraceDays(); const [overGroups, overAttendees] = await Promise.all([ query.maxGroups === null ? [] : db.group.groupBy({ by: ['createdById'], having: { id: { _count: { gt: query.maxGroups } } }, }), query.maxAttendees === null ? [] : db.person.groupBy({ by: ['createdById'], where: { attendees: { some: { status: 'ACTIVE' } } }, having: { id: { _count: { gt: query.maxAttendees } } }, }), ]); const candidates = [...new Set([...overGroups, ...overAttendees].map((row) => row.createdById))]; if (candidates.length === 0) return ok({ affectedAccounts: 0 }); // Same split as the PlanGuard: anyone without a live Pro is held to Free. const isPro: Prisma.UserWhereInput = { subscription: { is: proSubscriptionWhere(now, graceDays) } }; const affectedAccounts = await db.user.count({ where: { id: { in: candidates }, ...(plan === 'PRO' ? isPro : { NOT: isPro }) }, }); return ok({ affectedAccounts }); } }