- 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>
79 lines
3.4 KiB
TypeScript
79 lines
3.4 KiB
TypeScript
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<PrismaClient, 'user' | 'billingSubscription'>;
|
|
guard?: PlanGuard;
|
|
sync?: Pick<SyncSubscription, 'execute'>;
|
|
providers?: BillingProviderResolver;
|
|
now?: () => Date;
|
|
};
|
|
|
|
export class GetBillingStatus {
|
|
constructor(private readonly deps: GetBillingStatusDeps = {}) {}
|
|
|
|
async execute(userId: string): Promise<Result<BillingStatusDto, ProblemDetails>> {
|
|
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,
|
|
});
|
|
}
|
|
}
|