import type { PrismaClient } from '@generated/prisma/client'; import type { AdminAccountDetail, ProblemDetails, Result } from '@gruperly/shared'; import { err, ok, PLAN_LIMITS } from '@gruperly/shared'; import { notFoundResourceProblem } from '@/http/problem-builders'; import prisma from '@/lib/prisma'; import { exceedsLimits, getGraceDays, isBillingEnforced, toBillingChargeDto } from '@/modules/billing/lib'; import { accountPlan, toAccountListItem } from '../../lib'; const RECENT_CHARGES = 12; type GetAccountDeps = { db?: Pick; enforced?: boolean; graceDays?: number; now?: () => Date; }; /** One professor's account: plan, links, groups and the latest Pro charges. */ export class GetAccount { constructor(private readonly deps: GetAccountDeps = {}) {} async execute(userId: string): Promise> { const db = this.deps.db ?? prisma; const context = { now: this.deps.now?.() ?? new Date(), graceDays: this.deps.graceDays ?? getGraceDays(), }; const user = await db.user.findUnique({ where: { id: userId }, include: { subscription: true, mpAccount: { select: { status: true } }, whatsappAccount: { select: { status: true } }, groupsOwner: { select: { id: true, name: true, createdAt: true, _count: { select: { attendees: { where: { status: 'ACTIVE' } } } }, }, orderBy: { createdAt: 'desc' }, }, }, }); if (!user) return err(notFoundResourceProblem('User', userId)); const charges = await db.billingCharge.findMany({ where: { subscription: { userId } }, orderBy: { createdAt: 'desc' }, take: RECENT_CHARGES, }); const groups = user.groupsOwner.map((group) => ({ id: group.id, name: group.name, createdAt: group.createdAt.toISOString(), attendeesCount: group._count.attendees, })); const usage = { groupsCount: groups.length, attendeesCount: groups.reduce((sum, group) => sum + group.attendeesCount, 0), }; const summary = toAccountListItem(user, usage, context); const { graceUntil } = accountPlan(user, context); const enforced = this.deps.enforced ?? isBillingEnforced(); const subscription = user.subscription; return ok({ ...summary, planSelectedAt: user.planSelectedAt?.toISOString() ?? null, graceUntil: graceUntil?.toISOString() ?? null, // Same rule as the PlanGuard: an account without a plan is held to Free. readOnly: enforced && exceedsLimits(PLAN_LIMITS[summary.plan ?? 'FREE'], { groups: usage.groupsCount, attendees: usage.attendeesCount, }), subscription: summary.subscription && subscription ? { ...summary.subscription, payerEmail: subscription.payerEmail, authorizedAt: subscription.authorizedAt?.toISOString() ?? null, requestedAt: subscription.requestedAt.toISOString(), } : null, mpStatus: user.mpAccount?.status ?? null, whatsappStatus: user.whatsappAccount?.status ?? null, groups, charges: charges.map(toBillingChargeDto), }); } }