import type { PrismaClient } from '@generated/prisma/client'; import type { BillingStatusDto, ProblemDetails, Result } from '@gruperly/shared'; import { billingProviderForCountry, COUNTRY_CURRENCY, err, ok, PRO_PRICE_BY_COUNTRY } from '@gruperly/shared'; import { notFoundResourceProblem } from '@/http/problem-builders'; import prisma from '@/lib/prisma'; import { countryOf, PlanGuard, SyncSubscription } from '../../lib'; import { type BillingProviderResolver, getBillingProvider } from '../../providers'; /** A PENDING subscription is re-read from Mercado Pago at most this often. */ const PENDING_SYNC_INTERVAL_MS = 30 * 1000; type GetBillingStatusDeps = { db?: Pick; guard?: PlanGuard; sync?: Pick; providers?: BillingProviderResolver; now?: () => Date; }; export class GetBillingStatus { constructor(private readonly deps: GetBillingStatusDeps = {}) {} async execute(userId: string): 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)); const country = countryOf(user); let subscription = await db.billingSubscription.findUnique({ where: { userId } }); // Coming back from the provider's checkout, the webhook may not have // arrived yet (or may never arrive in local dev): ask directly, throttled. if ( subscription?.status === 'PENDING' && (subscription.externalId || subscription.checkoutRef) && (!subscription.lastSyncedAt || now.getTime() - subscription.lastSyncedAt.getTime() > PENDING_SYNC_INTERVAL_MS) ) { const synced = await (this.deps.sync ?? new SyncSubscription()).execute(subscription.id); if (synced.ok && synced.value.synced) { subscription = await db.billingSubscription.findUnique({ where: { userId } }); } } const entitlements = await (this.deps.guard ?? new PlanGuard()).getEntitlements(userId); // A live subscription keeps the price it was created with; otherwise the // current price of the country is what subscribing would cost. const live = subscription && subscription.status !== 'CANCELLED' ? subscription : null; // An authorized subscription stays with its provider; a new attempt (or // retrying a PENDING one) goes to the country's current provider. const provider = (this.deps.providers ?? getBillingProvider)( live && live.status !== 'PENDING' ? live.provider : billingProviderForCountry(country), ); return ok({ plan: entitlements.plan, status: subscription?.status ?? null, readOnly: entitlements.readOnly, graceUntil: entitlements.graceUntil?.toISOString() ?? null, paidThrough: subscription?.paidThrough?.toISOString() ?? null, nextPaymentDate: subscription?.status === 'AUTHORIZED' ? (subscription.nextPaymentDate?.toISOString() ?? null) : null, payerEmail: subscription?.payerEmail ?? null, priceAmount: live ? Number(live.amount.toString()) : PRO_PRICE_BY_COUNTRY[country], currency: live ? live.currency : COUNTRY_CURRENCY[country], country, provider: provider.id, availableInCountry: provider.isAvailable(country), enforced: entitlements.enforced, usage: entitlements.usage, limits: entitlements.limits, }); } }