import type { SubscriptionStatus } from '@generated/prisma/client'; import type { BillingProviderId, CountryCode, ProblemDetails, Result } from '@gruperly/shared'; import { billingNotAvailableProblem, billingProviderErrorProblem } from '@/http/problem-builders'; /** * The port every Pro billing provider implements. The domain (subscribing, * cancelling, syncing, the webhook and the reconciliation job) only talks to * this interface; everything that knows about Mercado Pago or Stripe lives in * `providers//`. Same idea as WhatsApp's `MessagingProvider`. * * Calls that reach the provider throw on failure: `BillingProviderNotConfigured` * when Gruperly has no credentials for it, anything else when the provider * refused or could not be reached. `toBillingProblem` turns either into the * Problem Details the use-cases answer with. */ export type { BillingProviderId }; /** What identifies one subscription at its provider. */ export type SubscriptionRef = { /** Mercado Pago picks Gruperly's account by country; Stripe ignores it. */ country: CountryCode | null; /** The provider's subscription id, once it exists. */ externalId: string | null; /** A checkout started but not completed yet (Stripe Checkout Session). */ checkoutRef: string | null; }; export type StartSubscriptionInput = { /** Our user id: the only thing that ties the subscription back to a professor. */ userId: string; country: CountryCode; amount: number; currency: string; /** Mandatory when `requiresPayerEmail`; otherwise only a pre-fill. */ payerEmail: string | null; /** Where the provider sends the professor back, completed or not. */ backUrl: string; /** First charge date; omitted means right after the professor authorizes. */ startDate?: Date; }; export type StartedSubscription = { /** Where the browser goes to authorize the subscription. */ checkoutUrl: string; externalId: string | null; checkoutRef: string | null; }; export type ProviderSubscription = { externalId: string; /** Our user id as the provider holds it; checked before trusting anything. */ ownerUserId: string | null; /** `null` for a provider status we do not know: the row keeps its own. */ status: SubscriptionStatus | null; nextPaymentDate: Date | null; /** The email the professor actually paid with, when the provider asks for it. */ payerEmail: string | null; }; export type ChargeStatus = 'approved' | 'pending' | 'rejected'; /** One monthly invoice of a subscription. */ export type ProviderCharge = { externalId: string; amount: number; currency: string | null; status: ChargeStatus; paidAt: Date | null; /** Last day this charge pays for; null unless approved. */ coveredUntil: Date | null; }; export type BillingWebhookRequest = { /** The `:country` of `/webhooks/mp/:country`; null for Stripe. */ routeParam: string | null; rawBody: string; headers: Headers; query: URLSearchParams; }; export type BillingWebhookFailure = | 'unknown_country' | 'not_configured' | 'invalid_signature' | 'sync_failed'; /** What a verified notification points at. The body is never trusted for a status. */ export type BillingWebhookHint = { /** The sending account, for deduplication: `mp:` or `stripe`. */ source: string; dedupeKey: string | null; country: CountryCode | null; /** The subscription to sync; null for events that do not concern one. */ externalId: string | null; }; export interface BillingProvider { readonly id: BillingProviderId; /** Mercado Pago makes the payer log in with the email given up front. */ readonly requiresPayerEmail: boolean; /** Gruperly has credentials to collect Pro in that country. */ isAvailable(country: CountryCode): boolean; start(input: StartSubscriptionInput): Promise; /** `null` while the professor has not completed the checkout. */ fetch(ref: SubscriptionRef): Promise; listCharges(ref: SubscriptionRef & { externalId: string }): Promise; /** New monthly amount from the next charge on; what was already charged stays. */ updateAmount(ref: SubscriptionRef & { externalId: string }, amount: number, currency: string): Promise; /** Stops the monthly charge, or voids a checkout never completed. */ cancel(ref: SubscriptionRef): Promise; parseWebhook(request: BillingWebhookRequest): Promise>; } export class BillingProviderNotConfigured extends Error { constructor(provider: BillingProviderId) { super(`Billing provider ${provider} is not configured`); this.name = 'BillingProviderNotConfigured'; } } export function toBillingProblem(error: unknown): ProblemDetails { return error instanceof BillingProviderNotConfigured ? billingNotAvailableProblem() : billingProviderErrorProblem(); }