- 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>
50 lines
1.7 KiB
TypeScript
50 lines
1.7 KiB
TypeScript
import type { PrismaClient, SubscriptionStatus } from '@generated/prisma/client';
|
|
import type { ProblemDetails, Result } from '@gruperly/shared';
|
|
import { err, ok } from '@gruperly/shared';
|
|
import { noActiveSubscriptionProblem } from '@/http/problem-builders';
|
|
import prisma from '@/lib/prisma';
|
|
import { subscriptionRefOf } from '../../lib';
|
|
import { type BillingProviderResolver, getBillingProvider, toBillingProblem } from '../../providers';
|
|
|
|
type CancelSubscriptionDeps = {
|
|
db?: Pick<PrismaClient, 'billingSubscription'>;
|
|
providers?: BillingProviderResolver;
|
|
};
|
|
|
|
/**
|
|
* Stops the monthly charge with the provider that collects it. `paidThrough`
|
|
* stays: the professor keeps Pro until the end of what they already paid
|
|
* (plus the grace period).
|
|
*/
|
|
export class CancelSubscription {
|
|
constructor(private readonly deps: CancelSubscriptionDeps = {}) {}
|
|
|
|
async execute(userId: string): Promise<Result<{ status: SubscriptionStatus }, ProblemDetails>> {
|
|
const db = this.deps.db ?? prisma;
|
|
|
|
const subscription = await db.billingSubscription.findUnique({ where: { userId } });
|
|
if (
|
|
!subscription
|
|
|| (!subscription.externalId && !subscription.checkoutRef)
|
|
|| subscription.status === 'CANCELLED'
|
|
) {
|
|
return err(noActiveSubscriptionProblem());
|
|
}
|
|
|
|
try {
|
|
await (this.deps.providers ?? getBillingProvider)(subscription.provider).cancel(
|
|
subscriptionRefOf(subscription),
|
|
);
|
|
} catch (error) {
|
|
return err(toBillingProblem(error));
|
|
}
|
|
|
|
await db.billingSubscription.update({
|
|
where: { id: subscription.id },
|
|
data: { status: 'CANCELLED', nextPaymentDate: null },
|
|
});
|
|
|
|
return ok({ status: 'CANCELLED' });
|
|
}
|
|
}
|