- Puerto BillingProvider con adaptadores de Mercado Pago (/preapproval) y Stripe (Checkout en modo suscripción, fetch plano). El país elige proveedor solo para suscripciones nuevas; sync, cancel y webhook usan row.provider. - Migración add_billing_providers (provider, checkout_ref, ids genéricos). - fix: /authorized_payments/search respondía 400 "Invalid value for limit"; se pagina por offset sin limit. - fix: si falla la consulta de cobros, la sync guarda igual el estado de la suscripción (ya no queda PENDING tras autorizar) y reintenta los cobros. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
116 lines
4.4 KiB
TypeScript
116 lines
4.4 KiB
TypeScript
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<PrismaClient, 'user' | 'billingSubscription'>;
|
|
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<Result<SubscribeResultDto, ProblemDetails>> {
|
|
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<ReturnType<typeof provider.start>>;
|
|
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 });
|
|
}
|
|
}
|