Files
gruperly/apps/backend/src/modules/billing/features/webhook/use-case.ts
Jose Selesan 9617447e05 feat(billing): proveedores intercambiables (Mercado Pago en AR, Stripe en el resto)
- 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>
2026-10-26 17:01:07 -03:00

83 lines
2.7 KiB
TypeScript

import type { PrismaClient } from '@generated/prisma/client';
import type { BillingProviderId, Result } from '@gruperly/shared';
import { err, ok } from '@gruperly/shared';
import prisma from '@/lib/prisma';
import { SyncSubscription } from '../../lib';
import {
type BillingProviderResolver,
type BillingWebhookFailure,
type BillingWebhookRequest,
getBillingProvider,
} from '../../providers';
export type { BillingWebhookFailure, BillingWebhookRequest } from '../../providers';
type HandleBillingWebhookDeps = {
db?: Pick<PrismaClient, 'billingWebhookEvent'>;
providers?: BillingProviderResolver;
sync?: Pick<SyncSubscription, 'byExternalId'>;
};
/** Prisma's unique-constraint violation: this delivery was already processed. */
const UNIQUE_VIOLATION = 'P2002';
/**
* Applies one provider notification about a Pro subscription.
*
* The provider adapter checks the signature and says which subscription the
* notification is about; the subscription is then fetched again from the
* provider and synced (`SyncSubscription`). The body is never trusted for a
* status. If syncing fails the dedupe key is removed, so the provider's retry
* gets another chance (same rule as the WhatsApp webhook).
*/
export class HandleBillingWebhook {
constructor(private readonly deps: HandleBillingWebhookDeps = {}) {}
async execute(
providerId: BillingProviderId,
request: BillingWebhookRequest,
): Promise<Result<{ duplicate: boolean; applied: boolean }, BillingWebhookFailure>> {
const parsed = await (this.deps.providers ?? getBillingProvider)(providerId).parseWebhook(request);
if (!parsed.ok) return parsed;
const hint = parsed.value;
if (!hint.externalId) return ok({ duplicate: false, applied: false });
const db = this.deps.db ?? prisma;
const dedupe = hint.dedupeKey ? { source: hint.source, dedupeKey: hint.dedupeKey } : null;
if (dedupe) {
try {
await db.billingWebhookEvent.create({ data: dedupe });
} catch (error) {
if ((error as { code?: string }).code === UNIQUE_VIOLATION) {
return ok({ duplicate: true, applied: false });
}
throw error;
}
}
const unburn = async () => {
if (!dedupe) return;
await db.billingWebhookEvent
.delete({ where: { source_dedupeKey: dedupe } })
.catch(() => undefined);
};
try {
const synced = await (this.deps.sync ?? new SyncSubscription()).byExternalId(
providerId,
hint.externalId,
hint.country,
);
if (!synced.ok) {
await unburn();
return err('sync_failed');
}
return ok({ duplicate: false, applied: synced.value.synced });
} catch {
await unburn();
return err('sync_failed');
}
}
}