import type { PrismaClient } from '@generated/prisma/client'; import type { ProblemDetails, Result, SubscribeInput, SubscribeResultDto } from '@gruperly/shared'; import { billingProviderForCountry, COUNTRY_CURRENCY, err, ok, PRO_PRICE_BY_COUNTRY } from '@gruperly/shared'; import { billingNotAvailableProblem, notFoundResourceProblem, payerEmailRequiredProblem, subscriptionAlreadyActiveProblem, } from '@/http/problem-builders'; import prisma from '@/lib/prisma'; import { logger } from '@/logger'; import { getWebOrigin } from '@/modules/mp/lib'; import { buildSubscriptionBackUrl, countryOf, subscriptionRefOf } from '../../lib'; import { type BillingProviderResolver, getBillingProvider, toBillingProblem } from '../../providers'; type SubscribeDeps = { db?: Pick; providers?: BillingProviderResolver; webOrigin?: string; now?: () => Date; }; /** * Starts a monthly Pro subscription with the billing provider of the * professor's country and returns where the browser goes to authorize it. * * The row is written PENDING before calling the provider (it is the source of * truth, like `Payment` rows in the batch). A previous subscription that was * never authorized is voided first, with whichever provider it was created, so * the professor can fix the payer email (or switch country) by trying again. */ export class Subscribe { constructor(private readonly deps: SubscribeDeps = {}) {} async execute(userId: string, input: SubscribeInput): Promise> { const db = this.deps.db ?? prisma; const providers = this.deps.providers ?? getBillingProvider; 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); const provider = providers(billingProviderForCountry(country)); if (!provider.isAvailable(country)) return err(billingNotAvailableProblem()); if (provider.requiresPayerEmail && !input.payerEmail) return err(payerEmailRequiredProblem()); const existing = await db.billingSubscription.findUnique({ where: { userId } }); if (existing?.status === 'AUTHORIZED') { return err(subscriptionAlreadyActiveProblem()); } if ((existing?.externalId || existing?.checkoutRef) && existing.status !== 'CANCELLED') { try { await providers(existing.provider).cancel(subscriptionRefOf(existing)); } catch { // A stale attempt that cannot be voided is harmless: it was never // authorized, and its notifications no longer match our row. logger.warn({ userId }, 'Could not void the previous Pro subscription attempt'); } } const amount = PRO_PRICE_BY_COUNTRY[country]; const currency = COUNTRY_CURRENCY[country]; const fields = { country, currency, amount, provider: provider.id, // Stripe asks for the email in its checkout; the sync stores the real one. payerEmail: input.payerEmail ?? user.email, }; const row = await db.billingSubscription.upsert({ where: { userId }, create: { userId, ...fields, status: 'PENDING', requestedAt: now }, update: { ...fields, status: 'PENDING', requestedAt: now, externalId: null, checkoutRef: null, authorizedAt: null, nextPaymentDate: null, }, }); // Re-subscribing before the paid period ends: the first charge waits for it, // so nobody pays twice for the same month. const startDate = row.paidThrough && row.paidThrough > now ? row.paidThrough : undefined; let started: Awaited>; try { started = await provider.start({ userId, country, amount, currency, payerEmail: input.payerEmail ?? null, backUrl: buildSubscriptionBackUrl(this.deps.webOrigin ?? getWebOrigin(), input.returnTo), startDate, }); } catch (error) { logger.error({ userId, provider: provider.id }, 'Could not start the Pro subscription'); return err(toBillingProblem(error)); } await db.billingSubscription.update({ where: { id: row.id }, data: { externalId: started.externalId, checkoutRef: started.checkoutRef, lastSyncedAt: now }, }); return ok({ checkoutUrl: started.checkoutUrl }); } }