import type { PrismaClient } from '@generated/prisma/client'; import type { ProblemDetails, Result, SelectPlanInput, SelectPlanResultDto } from '@gruperly/shared'; import { err, ok } from '@gruperly/shared'; import { notFoundResourceProblem, onboardingAlreadyCompletedProblem, subscriptionAlreadyActiveProblem, } from '@/http/problem-builders'; import prisma from '@/lib/prisma'; import { CancelSubscription } from '@/modules/billing/features/cancel/use-case'; import { Subscribe } from '@/modules/billing/features/subscribe/use-case'; type SelectPlanDeps = { db?: Pick; subscribe?: Pick; cancel?: Pick; now?: () => Date; }; /** * The mandatory "Plan" step of the onboarding. * * It stores the country first: until now it was only saved with the first * group, and Pro needs it to pick the price and Gruperly's Mercado Pago account. * Free is immediate; Pro starts the subscription and returns where the browser * goes to authorize it, coming back to `/onboarding?sub=return`. */ export class SelectPlan { constructor(private readonly deps: SelectPlanDeps = {}) {} async execute( userId: string, input: SelectPlanInput, ): Promise> { const db = this.deps.db ?? prisma; const now = this.deps.now?.() ?? new Date(); const user = await db.user.findUnique({ where: { id: userId } }); if (!user) return err(notFoundResourceProblem('User', userId)); if (user.onboardingCompleted) return err(onboardingAlreadyCompletedProblem()); await db.user.update({ where: { id: userId }, data: { country: input.country } }); const subscription = await db.billingSubscription.findUnique({ where: { userId } }); if (input.plan === 'FREE') { // A paid subscription is never dropped from here; that is "Cancelar" in /billing. if (subscription?.status === 'AUTHORIZED') return err(subscriptionAlreadyActiveProblem()); // Going back to Free after abandoning Mercado Pago: the attempt is void. if (subscription && subscription.status !== 'CANCELLED') { const cancelled = await (this.deps.cancel ?? new CancelSubscription()).execute(userId); if (!cancelled.ok) { await db.billingSubscription.update({ where: { id: subscription.id }, data: { status: 'CANCELLED', nextPaymentDate: null }, }); } } await db.user.update({ where: { id: userId }, data: { planSelectedAt: now } }); return ok({ plan: 'FREE', checkoutUrl: null }); } if (subscription?.status === 'AUTHORIZED') { await db.user.update({ where: { id: userId }, data: { planSelectedAt: now } }); return ok({ plan: 'PRO', checkoutUrl: null }); } const started = await (this.deps.subscribe ?? new Subscribe()).execute(userId, { payerEmail: input.payerEmail, returnTo: 'onboarding', }); if (!started.ok) return started; await db.user.update({ where: { id: userId }, data: { planSelectedAt: now } }); return ok({ plan: 'PRO', checkoutUrl: started.value.checkoutUrl }); } }