feat(billing): planes Free/Pro con Suscripciones de Mercado Pago
- Módulo billing: suscripción Pro mensual vía /preapproval con credenciales de plataforma por país, webhook firmado y reconciliación por polling. - PlanGuard en los use-cases que crean grupos/alumnos, cobran con MP o activan automatizaciones (402 plan_limit_reached / plan_feature_required / plan_read_only), detrás de BILLING_ENFORCEMENT. - Onboarding: paso Plan obligatorio (POST /onboarding/plan); con Free se saltean Cobros y WhatsApp. - Web: pantalla /billing, aviso de Pro desde el MutationCache. - Migración billing_subscriptions y docs/billing.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -32,6 +32,17 @@ MP_REDIRECT_URI=""
|
||||
# Generar con: openssl rand -base64 32
|
||||
TOKEN_ENCRYPTION_KEY=""
|
||||
|
||||
# Suscripción a Gruperly Pro (Suscripciones de Mercado Pago, ver docs/billing.md).
|
||||
# Credenciales de las cuentas de MP **de Gruperly**, una por país (MP no cobra
|
||||
# entre países). No son las del OAuth del profesor. Un país sin las dos queda
|
||||
# con Pro "no disponible" (503). Códigos: AR, BR, CL, CO, MX, PE, UY.
|
||||
MP_PLATFORM_ACCESS_TOKEN_AR=""
|
||||
MP_PLATFORM_WEBHOOK_SECRET_AR=""
|
||||
# on = aplica los límites del plan Free. Cualquier otro valor (o vacío): todos Pro.
|
||||
BILLING_ENFORCEMENT="off"
|
||||
# Días que un Pro vencido (cancelado o con el cobro rechazado) sigue funcionando.
|
||||
BILLING_GRACE_DAYS="7"
|
||||
|
||||
# WhatsApp: recordatorios de pago y reenganche semanales (ver docs/whatsapp.md).
|
||||
# Proveedor: openwa (MVP, gateway self-hosted con QR) | kapso (API oficial de Meta).
|
||||
WHATSAPP_PROVIDER="openwa"
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "SubscriptionStatus" AS ENUM ('PENDING', 'AUTHORIZED', 'PAUSED', 'CANCELLED');
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "users" ADD COLUMN "plan_selected_at" TIMESTAMP(3);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "billing_subscriptions" (
|
||||
"id" TEXT NOT NULL,
|
||||
"user_id" TEXT NOT NULL,
|
||||
"country_code" TEXT NOT NULL,
|
||||
"currency" TEXT NOT NULL,
|
||||
"amount" DECIMAL(12,2) NOT NULL,
|
||||
"payer_email" TEXT NOT NULL,
|
||||
"mp_preapproval_id" TEXT,
|
||||
"status" "SubscriptionStatus" NOT NULL DEFAULT 'PENDING',
|
||||
"requested_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"authorized_at" TIMESTAMP(3),
|
||||
"next_payment_date" TIMESTAMP(3),
|
||||
"paid_through" TIMESTAMP(3),
|
||||
"last_synced_at" TIMESTAMP(3),
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "billing_subscriptions_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "billing_charges" (
|
||||
"id" TEXT NOT NULL,
|
||||
"subscription_id" TEXT NOT NULL,
|
||||
"mp_authorized_payment_id" TEXT NOT NULL,
|
||||
"amount" DECIMAL(12,2) NOT NULL,
|
||||
"currency" TEXT NOT NULL,
|
||||
"status" TEXT NOT NULL,
|
||||
"paid_at" TIMESTAMP(3),
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "billing_charges_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "billing_webhook_events" (
|
||||
"country_code" TEXT NOT NULL,
|
||||
"dedupe_key" TEXT NOT NULL,
|
||||
"received_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "billing_webhook_events_pkey" PRIMARY KEY ("country_code","dedupe_key")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "billing_subscriptions_userId_key" ON "billing_subscriptions"("user_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "billing_subscriptions_mpPreapprovalId_key" ON "billing_subscriptions"("mp_preapproval_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "billing_subscriptions_status_lastSyncedAt_idx" ON "billing_subscriptions"("status", "last_synced_at");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "billing_charges_mpAuthorizedPaymentId_key" ON "billing_charges"("mp_authorized_payment_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "billing_charges_subscriptionId_createdAt_idx" ON "billing_charges"("subscription_id", "created_at");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "billing_webhook_events_receivedAt_idx" ON "billing_webhook_events"("received_at");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "billing_subscriptions" ADD CONSTRAINT "billing_subscriptions_userId_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "billing_charges" ADD CONSTRAINT "billing_charges_subscriptionId_fkey" FOREIGN KEY ("subscription_id") REFERENCES "billing_subscriptions"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
@@ -1,26 +1,29 @@
|
||||
// Auth (Better Auth) - required tables
|
||||
|
||||
model User {
|
||||
id String @id @default(cuid())
|
||||
id String @id @default(cuid())
|
||||
name String
|
||||
email String @unique
|
||||
emailVerified Boolean @default(false) @map("email_verified")
|
||||
email String @unique
|
||||
emailVerified Boolean @default(false) @map("email_verified")
|
||||
image String?
|
||||
onboardingCompleted Boolean @default(false) @map("onboarding_completed")
|
||||
country String? @map("country_code")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
onboardingCompleted Boolean @default(false) @map("onboarding_completed")
|
||||
country String? @map("country_code")
|
||||
// When the professor chose Free or Pro in the onboarding (mandatory step).
|
||||
planSelectedAt DateTime? @map("plan_selected_at")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
accounts Account[]
|
||||
sessions Session[]
|
||||
passkeys Passkey[]
|
||||
groupsMember GroupMember[]
|
||||
groupsOwner Group[] @relation("OwnerGroups")
|
||||
groupsOwner Group[] @relation("OwnerGroups")
|
||||
orgMemberships Member[]
|
||||
orgInvitations Invitation[] @relation("InvitedBy")
|
||||
orgInvitations Invitation[] @relation("InvitedBy")
|
||||
waitlist WaitlistEntry[]
|
||||
mpAccount MpAccount?
|
||||
whatsappAccount WhatsappAccount?
|
||||
subscription BillingSubscription?
|
||||
|
||||
@@map("users")
|
||||
}
|
||||
|
||||
70
apps/backend/prisma/models/billing.prisma
Normal file
70
apps/backend/prisma/models/billing.prisma
Normal file
@@ -0,0 +1,70 @@
|
||||
// Gruperly's own billing: the professor pays a monthly Pro subscription through
|
||||
// Mercado Pago Subscriptions (preapproval), collected by Gruperly's account in
|
||||
// the professor's country. Not to be confused with `Payment`, which is what
|
||||
// students pay the professor.
|
||||
|
||||
enum SubscriptionStatus {
|
||||
PENDING
|
||||
AUTHORIZED
|
||||
PAUSED
|
||||
CANCELLED
|
||||
}
|
||||
|
||||
model BillingSubscription {
|
||||
id String @id @default(cuid())
|
||||
userId String @unique(map: "billing_subscriptions_userId_key") @map("user_id")
|
||||
country String @map("country_code")
|
||||
currency String
|
||||
amount Decimal @db.Decimal(12, 2)
|
||||
payerEmail String @map("payer_email")
|
||||
// Null between creating the row and Mercado Pago answering.
|
||||
mpPreapprovalId String? @unique(map: "billing_subscriptions_mpPreapprovalId_key") @map("mp_preapproval_id")
|
||||
status SubscriptionStatus @default(PENDING)
|
||||
// When the current attempt started: re-subscribing reuses the row.
|
||||
requestedAt DateTime @default(now()) @map("requested_at")
|
||||
authorizedAt DateTime? @map("authorized_at")
|
||||
nextPaymentDate DateTime? @map("next_payment_date")
|
||||
// Last day covered by an approved charge. Pro lasts until then plus the grace
|
||||
// period, even after a cancellation or a failed renewal.
|
||||
paidThrough DateTime? @map("paid_through")
|
||||
lastSyncedAt DateTime? @map("last_synced_at")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade, map: "billing_subscriptions_userId_fkey")
|
||||
charges BillingCharge[]
|
||||
|
||||
// The reconciliation job walks PENDING and stale AUTHORIZED rows.
|
||||
@@index([status, lastSyncedAt], map: "billing_subscriptions_status_lastSyncedAt_idx")
|
||||
@@map("billing_subscriptions")
|
||||
}
|
||||
|
||||
// One Mercado Pago "authorized payment" (a monthly invoice) of a subscription.
|
||||
model BillingCharge {
|
||||
id String @id @default(cuid())
|
||||
subscriptionId String @map("subscription_id")
|
||||
mpAuthorizedPaymentId String @unique(map: "billing_charges_mpAuthorizedPaymentId_key") @map("mp_authorized_payment_id")
|
||||
amount Decimal @db.Decimal(12, 2)
|
||||
currency String
|
||||
// Mercado Pago's own status of the charge (e.g. approved, rejected).
|
||||
status String
|
||||
paidAt DateTime? @map("paid_at")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
subscription BillingSubscription @relation(fields: [subscriptionId], references: [id], onDelete: Cascade, map: "billing_charges_subscriptionId_fkey")
|
||||
|
||||
@@index([subscriptionId, createdAt], map: "billing_charges_subscriptionId_createdAt_idx")
|
||||
@@map("billing_charges")
|
||||
}
|
||||
|
||||
// Deduplication of Mercado Pago webhook deliveries, per country account.
|
||||
model BillingWebhookEvent {
|
||||
country String @map("country_code")
|
||||
dedupeKey String @map("dedupe_key")
|
||||
receivedAt DateTime @default(now()) @map("received_at")
|
||||
|
||||
@@id([country, dedupeKey], map: "billing_webhook_events_pkey")
|
||||
@@index([receivedAt], map: "billing_webhook_events_receivedAt_idx")
|
||||
@@map("billing_webhook_events")
|
||||
}
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
} from './modules/analytics';
|
||||
import { attendeesRoutes } from './modules/attendees';
|
||||
import { authRoutes } from './modules/auth';
|
||||
import { billingRoutes, planReadOnlyMiddleware } from './modules/billing';
|
||||
import { classesRoutes } from './modules/classes';
|
||||
import { groupsRoutes } from './modules/groups';
|
||||
import { healthCheckRoutes } from './modules/health-check';
|
||||
@@ -40,6 +41,13 @@ const api = app.basePath('/api/v1');
|
||||
|
||||
api.use('*', sessionAuthMiddleware);
|
||||
|
||||
// Read-only accounts (Free over its limits) cannot write domain data. Billing,
|
||||
// onboarding and the MP/WhatsApp links stay open: that is how they get out of it.
|
||||
const planReadOnly = planReadOnlyMiddleware();
|
||||
for (const prefix of ['/groups', '/attendees', '/payments', '/classes', '/students', '/waitlist']) {
|
||||
api.use(`${prefix}/*`, planReadOnly);
|
||||
}
|
||||
|
||||
api.route('/auth', authRoutes);
|
||||
api.route('/health', healthCheckRoutes);
|
||||
api.route('/invitations', invitationsRoutes);
|
||||
@@ -50,6 +58,7 @@ api.route('/mp', mpRoutes);
|
||||
api.route('/whatsapp', whatsappRoutes);
|
||||
api.route('/attendees', attendeesRoutes);
|
||||
api.route('/payments', paymentsRoutes);
|
||||
api.route('/billing', billingRoutes);
|
||||
api.route('/waitlist', waitlistRoutes);
|
||||
api.route('/classes', classesRoutes);
|
||||
api.route('/students', studentStatusRoutes);
|
||||
|
||||
@@ -215,4 +215,89 @@ export function noAttendeesToBillProblem(): ProblemDetails {
|
||||
detail: 'No hay miembros activos con un cobro pendiente para este grupo.',
|
||||
code: 'no_attendees_to_bill',
|
||||
});
|
||||
}
|
||||
}
|
||||
function paymentRequiredProblem(params: { detail: string; code: string }): ProblemDetails {
|
||||
return {
|
||||
type: `${PROBLEM_DOMAIN}/problems/plan`,
|
||||
title: 'Payment Required',
|
||||
status: 402,
|
||||
detail: params.detail,
|
||||
code: params.code,
|
||||
};
|
||||
}
|
||||
|
||||
export type PlanLimitKind = 'groups' | 'attendees';
|
||||
|
||||
/** The Free plan does not allow one more group or attendee. */
|
||||
export function planLimitReachedProblem(limit: PlanLimitKind, max: number): ProblemDetails {
|
||||
return paymentRequiredProblem({
|
||||
detail:
|
||||
limit === 'groups'
|
||||
? `El plan Free permite hasta ${max} ${max === 1 ? 'grupo' : 'grupos'}. Pasate a Pro para crear más.`
|
||||
: `El plan Free permite hasta ${max} alumnos activos. Pasate a Pro para sumar más.`,
|
||||
code: 'plan_limit_reached',
|
||||
});
|
||||
}
|
||||
|
||||
/** A Pro-only feature: charging students with Mercado Pago or WhatsApp automations. */
|
||||
export function planFeatureRequiredProblem(feature: 'mpCharges' | 'whatsappAutomations'): ProblemDetails {
|
||||
return paymentRequiredProblem({
|
||||
detail:
|
||||
feature === 'mpCharges'
|
||||
? 'Cobrar con Mercado Pago está disponible en el plan Pro.'
|
||||
: 'Los mensajes automáticos de WhatsApp están disponibles en el plan Pro.',
|
||||
code: 'plan_feature_required',
|
||||
});
|
||||
}
|
||||
|
||||
/** Free plan with more usage than its limits: only reads and deletes. */
|
||||
export function planReadOnlyProblem(): ProblemDetails {
|
||||
return paymentRequiredProblem({
|
||||
detail:
|
||||
'Tu cuenta está en solo lectura porque superás los límites del plan Free. Pasate a Pro o reducí el uso para volver a editar.',
|
||||
code: 'plan_read_only',
|
||||
});
|
||||
}
|
||||
|
||||
/** Gruperly has no Mercado Pago account configured for the professor's country. */
|
||||
export function billingNotAvailableProblem(): ProblemDetails {
|
||||
return {
|
||||
type: `${PROBLEM_DOMAIN}/problems/billing-not-available`,
|
||||
title: 'Service Unavailable',
|
||||
status: 503,
|
||||
detail: 'La suscripción a Pro todavía no está disponible en tu país.',
|
||||
code: 'billing_not_available',
|
||||
};
|
||||
}
|
||||
|
||||
/** Mercado Pago refused the subscription request, or could not be reached. */
|
||||
export function billingProviderErrorProblem(): ProblemDetails {
|
||||
return {
|
||||
type: `${PROBLEM_DOMAIN}/problems/billing-provider-error`,
|
||||
title: 'Bad Gateway',
|
||||
status: 502,
|
||||
detail: 'No pudimos comunicarnos con Mercado Pago. Intentá de nuevo en unos minutos.',
|
||||
code: 'billing_provider_error',
|
||||
};
|
||||
}
|
||||
|
||||
export function subscriptionAlreadyActiveProblem(): ProblemDetails {
|
||||
return conflictProblem({
|
||||
detail: 'Ya tenés una suscripción a Pro activa.',
|
||||
code: 'subscription_already_active',
|
||||
});
|
||||
}
|
||||
|
||||
export function noActiveSubscriptionProblem(): ProblemDetails {
|
||||
return conflictProblem({
|
||||
detail: 'No tenés una suscripción para cancelar.',
|
||||
code: 'no_active_subscription',
|
||||
});
|
||||
}
|
||||
|
||||
export function planNotSelectedProblem(): ProblemDetails {
|
||||
return conflictProblem({
|
||||
detail: 'Elegí un plan antes de crear tu primer grupo.',
|
||||
code: 'plan_not_selected',
|
||||
});
|
||||
}
|
||||
|
||||
@@ -42,6 +42,11 @@ export function isPublicApiRequest(method: string, path: string): boolean {
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
// Mercado Pago notifications about Pro subscriptions, one URL per country:
|
||||
// no session, authenticated by Mercado Pago's `x-signature`.
|
||||
if (method === 'POST' && /^\/api\/v1\/billing\/webhooks\/mp\/[a-z]{2}$/i.test(normalizedPath)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return (
|
||||
normalizedPath === '/api/v1/health'
|
||||
|
||||
@@ -8,10 +8,12 @@ import type {
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { noGroupAccessProblem, notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { PlanGuard } from '@/modules/billing/lib/entitlements';
|
||||
import { type AttendeeRecord, normalizePhone, toAttendeeDto } from '../../lib/helpers';
|
||||
|
||||
type BulkCreateAttendeesDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee'>;
|
||||
planGuard?: Pick<PlanGuard, 'canAddAttendees'>;
|
||||
};
|
||||
|
||||
export class BulkCreateAttendeesUseCase {
|
||||
@@ -88,6 +90,16 @@ export class BulkCreateAttendeesUseCase {
|
||||
});
|
||||
}
|
||||
|
||||
// All or nothing: a partial import that stops at the limit is harder to
|
||||
// reason about than a clear "your plan allows N".
|
||||
const allowed = await (this.deps.planGuard ?? new PlanGuard()).canAddAttendees(
|
||||
group.createdById,
|
||||
toCreateData.length,
|
||||
);
|
||||
if (!allowed.ok) {
|
||||
return allowed;
|
||||
}
|
||||
|
||||
const createdRecords: AttendeeRecord[] = [];
|
||||
for (const data of toCreateData) {
|
||||
const record = await db.attendee.create({ data });
|
||||
|
||||
@@ -9,10 +9,12 @@ import {
|
||||
notFoundResourceProblem,
|
||||
} from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { PlanGuard } from '@/modules/billing/lib/entitlements';
|
||||
import { type AttendeeRecord, normalizePhone, toAttendeeDto } from '../../lib/helpers';
|
||||
|
||||
type CreateAttendeeDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee' | 'groupWaitlistEntry'>;
|
||||
planGuard?: Pick<PlanGuard, 'canAddAttendees'>;
|
||||
};
|
||||
|
||||
type CreateAttendeeOptions = {
|
||||
@@ -106,6 +108,12 @@ export class CreateAttendeeUseCase {
|
||||
}
|
||||
}
|
||||
|
||||
// The owner's plan pays for the attendee, whoever adds it.
|
||||
const allowed = await (this.deps.planGuard ?? new PlanGuard()).canAddAttendees(group.createdById);
|
||||
if (!allowed.ok) {
|
||||
return allowed;
|
||||
}
|
||||
|
||||
const attendee = await db.attendee.create({
|
||||
data: {
|
||||
groupId,
|
||||
|
||||
15
apps/backend/src/modules/billing/features/cancel/route.ts
Normal file
15
apps/backend/src/modules/billing/features/cancel/route.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { CancelSubscription } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.post('/cancel', async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
|
||||
const result = await new CancelSubscription().execute(user.id);
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
50
apps/backend/src/modules/billing/features/cancel/use-case.ts
Normal file
50
apps/backend/src/modules/billing/features/cancel/use-case.ts
Normal file
@@ -0,0 +1,50 @@
|
||||
import type { PrismaClient, SubscriptionStatus } from '@generated/prisma/client';
|
||||
import type { CountryCode, ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { billingProviderErrorProblem, noActiveSubscriptionProblem } from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { getPlatformCredentials, mpPreapprovalClient, type PreapprovalClient } from '../../lib';
|
||||
|
||||
type CancelSubscriptionDeps = {
|
||||
db?: Pick<PrismaClient, 'billingSubscription'>;
|
||||
client?: PreapprovalClient;
|
||||
credentials?: typeof getPlatformCredentials;
|
||||
};
|
||||
|
||||
/**
|
||||
* Stops the monthly charge. `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?.mpPreapprovalId || subscription.status === 'CANCELLED') {
|
||||
return err(noActiveSubscriptionProblem());
|
||||
}
|
||||
|
||||
const credentials = (this.deps.credentials ?? getPlatformCredentials)(
|
||||
subscription.country as CountryCode,
|
||||
);
|
||||
if (!credentials.ok) return credentials;
|
||||
|
||||
try {
|
||||
await (this.deps.client ?? mpPreapprovalClient).cancelPreapproval(
|
||||
credentials.value.accessToken,
|
||||
subscription.mpPreapprovalId,
|
||||
);
|
||||
} catch {
|
||||
return err(billingProviderErrorProblem());
|
||||
}
|
||||
|
||||
await db.billingSubscription.update({
|
||||
where: { id: subscription.id },
|
||||
data: { status: 'CANCELLED', nextPaymentDate: null },
|
||||
});
|
||||
|
||||
return ok({ status: 'CANCELLED' });
|
||||
}
|
||||
}
|
||||
19
apps/backend/src/modules/billing/features/charges/route.ts
Normal file
19
apps/backend/src/modules/billing/features/charges/route.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import type { BillingChargesQuery } from '@gruperly/shared';
|
||||
import { BillingChargesQuerySchema } from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { validate } from '@/http/validate';
|
||||
import { ListBillingCharges } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.get('/charges', validate.query(BillingChargesQuerySchema), async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
|
||||
const query = c.req.valid('query') as BillingChargesQuery;
|
||||
const result = await new ListBillingCharges().execute(query, user.id);
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
@@ -0,0 +1,36 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { BillingChargeList, BillingChargesQuery, ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { ok } from '@gruperly/shared';
|
||||
import { getPaginationMetadata, getPaginationOffset } from '@/lib/pagination';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { toBillingChargeDto } from '../../lib';
|
||||
|
||||
type ListBillingChargesDeps = { db?: Pick<PrismaClient, 'billingCharge'> };
|
||||
|
||||
/** The professor's own Pro charges, newest first. */
|
||||
export class ListBillingCharges {
|
||||
constructor(private readonly deps: ListBillingChargesDeps = {}) {}
|
||||
|
||||
async execute(
|
||||
query: BillingChargesQuery,
|
||||
userId: string,
|
||||
): Promise<Result<BillingChargeList, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const where = { subscription: { userId } };
|
||||
|
||||
const [charges, total] = await Promise.all([
|
||||
db.billingCharge.findMany({
|
||||
where,
|
||||
orderBy: { createdAt: 'desc' },
|
||||
skip: getPaginationOffset(query),
|
||||
take: query.pageSize,
|
||||
}),
|
||||
db.billingCharge.count({ where }),
|
||||
]);
|
||||
|
||||
return ok({
|
||||
data: charges.map(toBillingChargeDto),
|
||||
pagination: getPaginationMetadata(query, total),
|
||||
});
|
||||
}
|
||||
}
|
||||
15
apps/backend/src/modules/billing/features/status/route.ts
Normal file
15
apps/backend/src/modules/billing/features/status/route.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { GetBillingStatus } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.get('/status', async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
|
||||
const result = await new GetBillingStatus().execute(user.id);
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
71
apps/backend/src/modules/billing/features/status/use-case.ts
Normal file
71
apps/backend/src/modules/billing/features/status/use-case.ts
Normal file
@@ -0,0 +1,71 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { BillingStatusDto, ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { COUNTRY_CURRENCY, err, ok, PRO_PRICE_BY_COUNTRY } from '@gruperly/shared';
|
||||
import { notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { countryOf, getPlatformCredentials, PlanGuard, SyncSubscription } from '../../lib';
|
||||
|
||||
/** 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'>;
|
||||
credentials?: typeof getPlatformCredentials;
|
||||
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 Mercado Pago, the webhook may not have arrived yet (or
|
||||
// may never arrive in local dev): ask Mercado Pago directly, throttled.
|
||||
if (
|
||||
subscription?.status === 'PENDING'
|
||||
&& subscription.mpPreapprovalId
|
||||
&& (!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;
|
||||
|
||||
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,
|
||||
availableInCountry: (this.deps.credentials ?? getPlatformCredentials)(country).ok,
|
||||
enforced: entitlements.enforced,
|
||||
usage: entitlements.usage,
|
||||
limits: entitlements.limits,
|
||||
});
|
||||
}
|
||||
}
|
||||
21
apps/backend/src/modules/billing/features/subscribe/route.ts
Normal file
21
apps/backend/src/modules/billing/features/subscribe/route.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import type { SubscribeInput } from '@gruperly/shared';
|
||||
import { SubscribeInputSchema } from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { validate } from '@/http/validate';
|
||||
import { Subscribe } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
// Returns `{ checkoutUrl }`: the browser navigates there to authorize the
|
||||
// subscription in Mercado Pago, the same way `/mp/connect` works.
|
||||
route.post('/subscribe', validate.json(SubscribeInputSchema), async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
|
||||
const input = c.req.valid('json') as SubscribeInput;
|
||||
const result = await new Subscribe().execute(user.id, input);
|
||||
return resultJson(c, result, { status: 201 });
|
||||
});
|
||||
|
||||
export default route;
|
||||
118
apps/backend/src/modules/billing/features/subscribe/use-case.ts
Normal file
118
apps/backend/src/modules/billing/features/subscribe/use-case.ts
Normal file
@@ -0,0 +1,118 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { ProblemDetails, Result, SubscribeInput, SubscribeResultDto } from '@gruperly/shared';
|
||||
import { COUNTRY_CURRENCY, err, ok, PRO_PRICE_BY_COUNTRY } from '@gruperly/shared';
|
||||
import {
|
||||
billingProviderErrorProblem,
|
||||
notFoundResourceProblem,
|
||||
subscriptionAlreadyActiveProblem,
|
||||
} from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { logger } from '@/logger';
|
||||
import { getWebOrigin } from '@/modules/mp/lib';
|
||||
import {
|
||||
buildSubscriptionBackUrl,
|
||||
countryOf,
|
||||
getPlatformCredentials,
|
||||
mpPreapprovalClient,
|
||||
type PreapprovalClient,
|
||||
} from '../../lib';
|
||||
|
||||
type SubscribeDeps = {
|
||||
db?: Pick<PrismaClient, 'user' | 'billingSubscription'>;
|
||||
client?: PreapprovalClient;
|
||||
credentials?: typeof getPlatformCredentials;
|
||||
webOrigin?: string;
|
||||
now?: () => Date;
|
||||
};
|
||||
|
||||
const SUBSCRIPTION_REASON = 'Gruperly Pro';
|
||||
|
||||
/**
|
||||
* Starts a monthly Pro subscription in Gruperly's Mercado Pago account of the
|
||||
* professor's country and returns where the browser goes to authorize it.
|
||||
*
|
||||
* The row is written PENDING before calling Mercado Pago (it is the source of
|
||||
* truth, like `Payment` rows in the batch). A previous subscription that was
|
||||
* never authorized is cancelled first, so the professor can fix the payer
|
||||
* email by simply 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 client = this.deps.client ?? mpPreapprovalClient;
|
||||
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 credentials = (this.deps.credentials ?? getPlatformCredentials)(country);
|
||||
if (!credentials.ok) return credentials;
|
||||
const token = credentials.value.accessToken;
|
||||
|
||||
const existing = await db.billingSubscription.findUnique({ where: { userId } });
|
||||
if (existing?.status === 'AUTHORIZED') {
|
||||
return err(subscriptionAlreadyActiveProblem());
|
||||
}
|
||||
|
||||
if (existing?.mpPreapprovalId && existing.status !== 'CANCELLED') {
|
||||
try {
|
||||
await client.cancelPreapproval(token, existing.mpPreapprovalId);
|
||||
} catch {
|
||||
// A stale PENDING preapproval that cannot be cancelled is harmless: it
|
||||
// was never authorized, and its notifications no longer match our row.
|
||||
logger.warn({ userId }, 'Could not cancel the previous Mercado Pago preapproval');
|
||||
}
|
||||
}
|
||||
|
||||
const amount = PRO_PRICE_BY_COUNTRY[country];
|
||||
const currency = COUNTRY_CURRENCY[country];
|
||||
const fields = { country, currency, amount, payerEmail: input.payerEmail };
|
||||
|
||||
const row = await db.billingSubscription.upsert({
|
||||
where: { userId },
|
||||
create: { userId, ...fields, status: 'PENDING', requestedAt: now },
|
||||
update: {
|
||||
...fields,
|
||||
status: 'PENDING',
|
||||
requestedAt: now,
|
||||
mpPreapprovalId: 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 preapproval: Awaited<ReturnType<PreapprovalClient['createPreapproval']>>;
|
||||
try {
|
||||
preapproval = await client.createPreapproval(token, {
|
||||
reason: SUBSCRIPTION_REASON,
|
||||
externalReference: userId,
|
||||
payerEmail: input.payerEmail,
|
||||
amount,
|
||||
currencyId: currency,
|
||||
backUrl: buildSubscriptionBackUrl(this.deps.webOrigin ?? getWebOrigin(), input.returnTo),
|
||||
startDate,
|
||||
});
|
||||
} catch {
|
||||
return err(billingProviderErrorProblem());
|
||||
}
|
||||
|
||||
if (!preapproval.initPoint) {
|
||||
logger.error({ userId }, 'Mercado Pago preapproval came back without init_point');
|
||||
return err(billingProviderErrorProblem());
|
||||
}
|
||||
|
||||
await db.billingSubscription.update({
|
||||
where: { id: row.id },
|
||||
data: { mpPreapprovalId: preapproval.id, lastSyncedAt: now },
|
||||
});
|
||||
|
||||
return ok({ checkoutUrl: preapproval.initPoint });
|
||||
}
|
||||
}
|
||||
36
apps/backend/src/modules/billing/features/webhook/route.ts
Normal file
36
apps/backend/src/modules/billing/features/webhook/route.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
import { Hono } from 'hono';
|
||||
import { logger } from '@/logger';
|
||||
import { HandleBillingWebhook } from './use-case';
|
||||
|
||||
/**
|
||||
* Public endpoint (see `isPublicApiRequest`): Mercado Pago calls it, not the
|
||||
* browser, so there is no session. One URL per country, because each country
|
||||
* is a different Gruperly account with its own webhook secret.
|
||||
*/
|
||||
const route = new Hono();
|
||||
|
||||
route.post('/webhooks/mp/:country', async (c) => {
|
||||
const result = await new HandleBillingWebhook().execute({
|
||||
country: c.req.param('country'),
|
||||
rawBody: await c.req.text(),
|
||||
headers: c.req.raw.headers,
|
||||
query: new URL(c.req.url).searchParams,
|
||||
});
|
||||
|
||||
if (!result.ok) {
|
||||
logger.warn({ reason: result.error }, 'Mercado Pago billing webhook rejected');
|
||||
const status =
|
||||
result.error === 'invalid_signature'
|
||||
? 401
|
||||
: result.error === 'unknown_country'
|
||||
? 404
|
||||
: result.error === 'not_configured'
|
||||
? 503
|
||||
: 500;
|
||||
return c.body(null, status);
|
||||
}
|
||||
|
||||
return c.json({ received: true, duplicate: result.value.duplicate });
|
||||
});
|
||||
|
||||
export default route;
|
||||
136
apps/backend/src/modules/billing/features/webhook/use-case.ts
Normal file
136
apps/backend/src/modules/billing/features/webhook/use-case.ts
Normal file
@@ -0,0 +1,136 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { CountryCode, Result } from '@gruperly/shared';
|
||||
import { countryCodeSchema, err, ok } from '@gruperly/shared';
|
||||
import prisma from '@/lib/prisma';
|
||||
import {
|
||||
getPlatformCredentials,
|
||||
mpPreapprovalClient,
|
||||
type PreapprovalClient,
|
||||
SyncSubscription,
|
||||
verifyMpSignature,
|
||||
} from '../../lib';
|
||||
|
||||
type HandleBillingWebhookDeps = {
|
||||
db?: Pick<PrismaClient, 'billingWebhookEvent'>;
|
||||
client?: PreapprovalClient;
|
||||
credentials?: typeof getPlatformCredentials;
|
||||
sync?: Pick<SyncSubscription, 'byPreapprovalId'>;
|
||||
};
|
||||
|
||||
export type BillingWebhookFailure =
|
||||
| 'unknown_country'
|
||||
| 'not_configured'
|
||||
| 'invalid_signature'
|
||||
| 'sync_failed';
|
||||
|
||||
/** Prisma's unique-constraint violation: this delivery was already processed. */
|
||||
const UNIQUE_VIOLATION = 'P2002';
|
||||
|
||||
export type BillingWebhookRequest = {
|
||||
country: string;
|
||||
rawBody: string;
|
||||
headers: Headers;
|
||||
query: URLSearchParams;
|
||||
};
|
||||
|
||||
/**
|
||||
* Applies one Mercado Pago notification about a Pro subscription.
|
||||
*
|
||||
* The notification is only a hint: after checking its signature, the resource
|
||||
* is fetched again from Mercado Pago and synced (`SyncSubscription`). The body
|
||||
* is never trusted for a status. If syncing fails the dedupe key is removed, so
|
||||
* Mercado Pago's retry gets another chance (same rule as the WhatsApp webhook).
|
||||
*/
|
||||
export class HandleBillingWebhook {
|
||||
constructor(private readonly deps: HandleBillingWebhookDeps = {}) {}
|
||||
|
||||
async execute(
|
||||
request: BillingWebhookRequest,
|
||||
): Promise<Result<{ duplicate: boolean; applied: boolean }, BillingWebhookFailure>> {
|
||||
const parsedCountry = countryCodeSchema.safeParse(request.country.toUpperCase());
|
||||
if (!parsedCountry.success) return err('unknown_country');
|
||||
const country: CountryCode = parsedCountry.data;
|
||||
|
||||
const credentials = (this.deps.credentials ?? getPlatformCredentials)(country);
|
||||
if (!credentials.ok) return err('not_configured');
|
||||
|
||||
const body = parseBody(request.rawBody);
|
||||
const dataId = request.query.get('data.id') ?? request.query.get('id') ?? body.dataId;
|
||||
const type = request.query.get('type') ?? request.query.get('topic') ?? body.type;
|
||||
const requestId = request.headers.get('x-request-id');
|
||||
|
||||
const valid = verifyMpSignature({
|
||||
signature: request.headers.get('x-signature'),
|
||||
requestId,
|
||||
dataId,
|
||||
secret: credentials.value.webhookSecret,
|
||||
});
|
||||
if (!valid) return err('invalid_signature');
|
||||
|
||||
if (!dataId || !isSubscriptionTopic(type)) {
|
||||
return ok({ duplicate: false, applied: false });
|
||||
}
|
||||
|
||||
const db = this.deps.db ?? prisma;
|
||||
const dedupe = requestId ? { country, dedupeKey: requestId } : 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: { country_dedupeKey: dedupe } })
|
||||
.catch(() => undefined);
|
||||
};
|
||||
|
||||
try {
|
||||
let preapprovalId = dataId;
|
||||
if (type === 'subscription_authorized_payment') {
|
||||
const invoice = await (this.deps.client ?? mpPreapprovalClient).getAuthorizedPayment(
|
||||
credentials.value.accessToken,
|
||||
dataId,
|
||||
);
|
||||
preapprovalId = invoice.preapprovalId;
|
||||
}
|
||||
|
||||
const synced = await (this.deps.sync ?? new SyncSubscription()).byPreapprovalId(
|
||||
country,
|
||||
preapprovalId,
|
||||
);
|
||||
if (!synced.ok) {
|
||||
await unburn();
|
||||
return err('sync_failed');
|
||||
}
|
||||
return ok({ duplicate: false, applied: synced.value.synced });
|
||||
} catch {
|
||||
await unburn();
|
||||
return err('sync_failed');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function isSubscriptionTopic(
|
||||
type: string | null,
|
||||
): type is 'subscription_preapproval' | 'subscription_authorized_payment' {
|
||||
return type === 'subscription_preapproval' || type === 'subscription_authorized_payment';
|
||||
}
|
||||
|
||||
function parseBody(rawBody: string): { dataId: string | null; type: string | null } {
|
||||
try {
|
||||
const payload = JSON.parse(rawBody) as { type?: unknown; data?: { id?: unknown } } | null;
|
||||
return {
|
||||
dataId: payload?.data?.id == null ? null : String(payload.data.id),
|
||||
type: typeof payload?.type === 'string' ? payload.type : null,
|
||||
};
|
||||
} catch {
|
||||
return { dataId: null, type: null };
|
||||
}
|
||||
}
|
||||
4
apps/backend/src/modules/billing/index.ts
Normal file
4
apps/backend/src/modules/billing/index.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
export { startBillingJobs } from './jobs';
|
||||
export { PlanGuard } from './lib/entitlements';
|
||||
export { planReadOnlyMiddleware } from './lib/read-only-middleware';
|
||||
export { default as billingRoutes } from './routes';
|
||||
2
apps/backend/src/modules/billing/jobs/index.ts
Normal file
2
apps/backend/src/modules/billing/jobs/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export { ReconcileSubscriptions, type ReconcileTotals } from './reconcile-subscriptions';
|
||||
export { startBillingJobs } from './schedule';
|
||||
@@ -0,0 +1,67 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { SyncSubscription } from '../lib';
|
||||
|
||||
const BATCH_SIZE = 50;
|
||||
const DAY_MS = 24 * 60 * 60 * 1000;
|
||||
/** A subscription nobody authorized within this window is given up. */
|
||||
const PENDING_TTL_MS = 7 * DAY_MS;
|
||||
/** Authorized subscriptions are re-checked at least daily (renewals, cancellations in MP). */
|
||||
const AUTHORIZED_STALE_MS = DAY_MS;
|
||||
|
||||
type ReconcileSubscriptionsDeps = {
|
||||
db?: Pick<PrismaClient, 'billingSubscription'>;
|
||||
sync?: Pick<SyncSubscription, 'execute'>;
|
||||
now?: () => Date;
|
||||
};
|
||||
|
||||
export type ReconcileTotals = { checked: number; synced: number; failed: number; expired: number };
|
||||
|
||||
/**
|
||||
* Polling fallback for the billing webhook: the webhook can be lost, and in
|
||||
* local dev it usually never arrives. Every sync is idempotent, so the webhook
|
||||
* and this job racing over the same row is harmless.
|
||||
*/
|
||||
export class ReconcileSubscriptions {
|
||||
constructor(private readonly deps: ReconcileSubscriptionsDeps = {}) {}
|
||||
|
||||
async execute(): Promise<ReconcileTotals> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const sync = this.deps.sync ?? new SyncSubscription();
|
||||
const now = this.deps.now?.() ?? new Date();
|
||||
const totals: ReconcileTotals = { checked: 0, synced: 0, failed: 0, expired: 0 };
|
||||
|
||||
const pendingCutoff = new Date(now.getTime() - PENDING_TTL_MS);
|
||||
const expired = await db.billingSubscription.updateMany({
|
||||
where: { status: 'PENDING', requestedAt: { lt: pendingCutoff } },
|
||||
data: { status: 'CANCELLED' },
|
||||
});
|
||||
totals.expired = expired.count;
|
||||
|
||||
const staleCutoff = new Date(now.getTime() - AUTHORIZED_STALE_MS);
|
||||
const rows = await db.billingSubscription.findMany({
|
||||
where: {
|
||||
mpPreapprovalId: { not: null },
|
||||
OR: [
|
||||
{ status: 'PENDING' },
|
||||
{
|
||||
status: { in: ['AUTHORIZED', 'PAUSED'] },
|
||||
OR: [{ lastSyncedAt: null }, { lastSyncedAt: { lt: staleCutoff } }],
|
||||
},
|
||||
],
|
||||
},
|
||||
select: { id: true },
|
||||
orderBy: { lastSyncedAt: { sort: 'asc', nulls: 'first' } },
|
||||
take: BATCH_SIZE,
|
||||
});
|
||||
|
||||
for (const row of rows) {
|
||||
totals.checked += 1;
|
||||
const result = await sync.execute(row.id);
|
||||
if (result.ok && result.value.synced) totals.synced += 1;
|
||||
else if (!result.ok) totals.failed += 1;
|
||||
}
|
||||
|
||||
return totals;
|
||||
}
|
||||
}
|
||||
24
apps/backend/src/modules/billing/jobs/schedule.ts
Normal file
24
apps/backend/src/modules/billing/jobs/schedule.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import { logger } from '@/logger';
|
||||
import { ReconcileSubscriptions } from './reconcile-subscriptions';
|
||||
|
||||
const RECONCILE_CRON = '*/30 * * * *';
|
||||
|
||||
/**
|
||||
* Registers the billing background jobs. Called once from `server.ts`, with the
|
||||
* same guards as `startPaymentJobs`: a rejected promise inside Bun's cron would
|
||||
* crash the process, and `unref` keeps the job from holding it alive.
|
||||
*/
|
||||
export function startBillingJobs(): void {
|
||||
Bun.cron(
|
||||
RECONCILE_CRON,
|
||||
async () => {
|
||||
try {
|
||||
const totals = await new ReconcileSubscriptions().execute();
|
||||
logger.info(totals, 'Pro subscriptions reconciliation finished');
|
||||
} catch (error) {
|
||||
logger.error({ err: error }, 'Pro subscriptions reconciliation failed');
|
||||
}
|
||||
},
|
||||
{ tz: 'UTC' },
|
||||
).unref();
|
||||
}
|
||||
47
apps/backend/src/modules/billing/lib/config.ts
Normal file
47
apps/backend/src/modules/billing/lib/config.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import type { CountryCode, ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { billingNotAvailableProblem } from '@/http/problem-builders';
|
||||
|
||||
export type PlatformCredentials = {
|
||||
/** Access token of Gruperly's own Mercado Pago account in that country. */
|
||||
accessToken: string;
|
||||
/** Secret of the webhook configured in that account's panel. */
|
||||
webhookSecret: string;
|
||||
};
|
||||
|
||||
const DEFAULT_GRACE_DAYS = 7;
|
||||
|
||||
/**
|
||||
* Gruperly's Mercado Pago credentials for one country. Mercado Pago does not
|
||||
* charge across countries, so each country has its own account; a country
|
||||
* without both variables cannot subscribe to Pro (503, not a deployment crash:
|
||||
* rolling out country by country is expected).
|
||||
*
|
||||
* These are platform credentials, never the professor's OAuth token.
|
||||
*/
|
||||
export function getPlatformCredentials(
|
||||
country: CountryCode,
|
||||
env: Record<string, string | undefined> = process.env,
|
||||
): Result<PlatformCredentials, ProblemDetails> {
|
||||
const accessToken = env[`MP_PLATFORM_ACCESS_TOKEN_${country}`]?.trim();
|
||||
const webhookSecret = env[`MP_PLATFORM_WEBHOOK_SECRET_${country}`]?.trim();
|
||||
if (!accessToken || !webhookSecret) {
|
||||
return err(billingNotAvailableProblem());
|
||||
}
|
||||
return ok({ accessToken, webhookSecret });
|
||||
}
|
||||
|
||||
/**
|
||||
* Plan limits only apply with `BILLING_ENFORCEMENT=on`. Anything else (unset
|
||||
* included) treats everyone as Pro, so the module can ship before the existing
|
||||
* professors are moved to a plan.
|
||||
*/
|
||||
export function isBillingEnforced(env: Record<string, string | undefined> = process.env): boolean {
|
||||
return env.BILLING_ENFORCEMENT?.trim().toLowerCase() === 'on';
|
||||
}
|
||||
|
||||
/** Days a lapsed Pro keeps working after its last paid period. */
|
||||
export function getGraceDays(env: Record<string, string | undefined> = process.env): number {
|
||||
const value = Number(env.BILLING_GRACE_DAYS);
|
||||
return Number.isInteger(value) && value >= 0 ? value : DEFAULT_GRACE_DAYS;
|
||||
}
|
||||
158
apps/backend/src/modules/billing/lib/entitlements.ts
Normal file
158
apps/backend/src/modules/billing/lib/entitlements.ts
Normal file
@@ -0,0 +1,158 @@
|
||||
import type { PrismaClient, SubscriptionStatus } from '@generated/prisma/client';
|
||||
import type { Plan, PlanFeature, PlanLimits, ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { err, ok, PLAN_LIMITS } from '@gruperly/shared';
|
||||
import {
|
||||
planFeatureRequiredProblem,
|
||||
planLimitReachedProblem,
|
||||
planReadOnlyProblem,
|
||||
} from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { getGraceDays, isBillingEnforced } from './config';
|
||||
|
||||
const DAY_MS = 24 * 60 * 60 * 1000;
|
||||
|
||||
export type SubscriptionSnapshot = {
|
||||
status: SubscriptionStatus;
|
||||
authorizedAt: Date | null;
|
||||
paidThrough: Date | null;
|
||||
};
|
||||
|
||||
export type PlanResolution = {
|
||||
plan: Plan;
|
||||
/** Set while Pro survives a lapse (failed renewal or cancellation) on grace. */
|
||||
graceUntil: Date | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Pro lasts while a charge covers today, plus the grace period after the last
|
||||
* paid day. That one rule covers a cancelled subscription (Pro until the end of
|
||||
* what was paid) and a failed renewal (Mercado Pago keeps retrying meanwhile).
|
||||
*
|
||||
* An AUTHORIZED subscription with no approved charge yet is Pro too, for the
|
||||
* grace period after the authorization: the first charge is in flight.
|
||||
*/
|
||||
export function resolvePlan(
|
||||
subscription: SubscriptionSnapshot | null,
|
||||
now: Date,
|
||||
graceDays: number,
|
||||
): PlanResolution {
|
||||
if (!subscription) return { plan: 'FREE', graceUntil: null };
|
||||
const graceMs = graceDays * DAY_MS;
|
||||
|
||||
if (subscription.paidThrough) {
|
||||
if (subscription.paidThrough > now) return { plan: 'PRO', graceUntil: null };
|
||||
const graceUntil = new Date(subscription.paidThrough.getTime() + graceMs);
|
||||
return graceUntil > now ? { plan: 'PRO', graceUntil } : { plan: 'FREE', graceUntil: null };
|
||||
}
|
||||
|
||||
if (subscription.status === 'AUTHORIZED' && subscription.authorizedAt) {
|
||||
const graceUntil = new Date(subscription.authorizedAt.getTime() + graceMs);
|
||||
if (graceUntil > now) return { plan: 'PRO', graceUntil: null };
|
||||
}
|
||||
|
||||
return { plan: 'FREE', graceUntil: null };
|
||||
}
|
||||
|
||||
export type PlanUsage = { groups: number; attendees: number };
|
||||
|
||||
export function exceedsLimits(limits: PlanLimits, usage: PlanUsage): boolean {
|
||||
return (
|
||||
(limits.maxGroups !== null && usage.groups > limits.maxGroups)
|
||||
|| (limits.maxAttendees !== null && usage.attendees > limits.maxAttendees)
|
||||
);
|
||||
}
|
||||
|
||||
export type Entitlements = PlanResolution & {
|
||||
limits: PlanLimits;
|
||||
usage: PlanUsage;
|
||||
/** Free with more usage than its limits. Always false when not enforced. */
|
||||
readOnly: boolean;
|
||||
enforced: boolean;
|
||||
};
|
||||
|
||||
type PlanGuardDeps = {
|
||||
db?: Pick<PrismaClient, 'billingSubscription' | 'group' | 'attendee'>;
|
||||
enforced?: boolean;
|
||||
graceDays?: number;
|
||||
now?: () => Date;
|
||||
};
|
||||
|
||||
/**
|
||||
* What a professor's plan allows. Every check is about the **owner** of the
|
||||
* group (`group.createdById`): an ADMIN acting on someone else's group spends
|
||||
* the owner's plan, not their own.
|
||||
*
|
||||
* With enforcement off the checks pass without touching the database.
|
||||
*/
|
||||
export class PlanGuard {
|
||||
constructor(private readonly deps: PlanGuardDeps = {}) {}
|
||||
|
||||
private get enforced(): boolean {
|
||||
return this.deps.enforced ?? isBillingEnforced();
|
||||
}
|
||||
|
||||
async getEntitlements(ownerId: string): Promise<Entitlements> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const now = this.deps.now?.() ?? new Date();
|
||||
|
||||
const [subscription, groups, attendees] = await Promise.all([
|
||||
db.billingSubscription.findUnique({
|
||||
where: { userId: ownerId },
|
||||
select: { status: true, authorizedAt: true, paidThrough: true },
|
||||
}),
|
||||
db.group.count({ where: { createdById: ownerId } }),
|
||||
db.attendee.count({ where: { status: 'ACTIVE', group: { createdById: ownerId } } }),
|
||||
]);
|
||||
|
||||
const resolution = resolvePlan(subscription, now, this.deps.graceDays ?? getGraceDays());
|
||||
const limits = PLAN_LIMITS[resolution.plan];
|
||||
const usage = { groups, attendees };
|
||||
const enforced = this.enforced;
|
||||
|
||||
return {
|
||||
...resolution,
|
||||
limits,
|
||||
usage,
|
||||
readOnly: enforced && exceedsLimits(limits, usage),
|
||||
enforced,
|
||||
};
|
||||
}
|
||||
|
||||
async requireWritable(ownerId: string): Promise<Result<void, ProblemDetails>> {
|
||||
if (!this.enforced) return ok(undefined);
|
||||
const entitlements = await this.getEntitlements(ownerId);
|
||||
return entitlements.readOnly ? err(planReadOnlyProblem()) : ok(undefined);
|
||||
}
|
||||
|
||||
async canCreateGroup(ownerId: string): Promise<Result<void, ProblemDetails>> {
|
||||
if (!this.enforced) return ok(undefined);
|
||||
const { readOnly, limits, usage } = await this.getEntitlements(ownerId);
|
||||
if (readOnly) return err(planReadOnlyProblem());
|
||||
if (limits.maxGroups !== null && usage.groups + 1 > limits.maxGroups) {
|
||||
return err(planLimitReachedProblem('groups', limits.maxGroups));
|
||||
}
|
||||
return ok(undefined);
|
||||
}
|
||||
|
||||
async canAddAttendees(ownerId: string, count = 1): Promise<Result<void, ProblemDetails>> {
|
||||
if (!this.enforced || count <= 0) return ok(undefined);
|
||||
const { readOnly, limits, usage } = await this.getEntitlements(ownerId);
|
||||
if (readOnly) return err(planReadOnlyProblem());
|
||||
if (limits.maxAttendees !== null && usage.attendees + count > limits.maxAttendees) {
|
||||
return err(planLimitReachedProblem('attendees', limits.maxAttendees));
|
||||
}
|
||||
return ok(undefined);
|
||||
}
|
||||
|
||||
async requireFeature(ownerId: string, feature: PlanFeature): Promise<Result<void, ProblemDetails>> {
|
||||
return (await this.hasFeature(ownerId, feature))
|
||||
? ok(undefined)
|
||||
: err(planFeatureRequiredProblem(feature));
|
||||
}
|
||||
|
||||
async hasFeature(ownerId: string, feature: PlanFeature): Promise<boolean> {
|
||||
if (!this.enforced) return true;
|
||||
const { limits } = await this.getEntitlements(ownerId);
|
||||
return limits[feature];
|
||||
}
|
||||
}
|
||||
27
apps/backend/src/modules/billing/lib/helpers.ts
Normal file
27
apps/backend/src/modules/billing/lib/helpers.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import type { BillingCharge, BillingSubscription } from '@generated/prisma/client';
|
||||
import type { BillingChargeDto, BillingReturnTo, CountryCode } from '@gruperly/shared';
|
||||
import { countryCodeSchema, DEFAULT_COUNTRY } from '@gruperly/shared';
|
||||
|
||||
export function toBillingChargeDto(charge: BillingCharge): BillingChargeDto {
|
||||
return {
|
||||
id: charge.id,
|
||||
amount: Number(charge.amount.toString()),
|
||||
currency: charge.currency,
|
||||
status: charge.status,
|
||||
paidAt: charge.paidAt?.toISOString() ?? null,
|
||||
createdAt: charge.createdAt.toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
/** The professor's country as stored on the user; Argentina until they pick one. */
|
||||
export function countryOf(user: { country: string | null } | null): CountryCode {
|
||||
const parsed = countryCodeSchema.safeParse(user?.country);
|
||||
return parsed.success ? parsed.data : DEFAULT_COUNTRY;
|
||||
}
|
||||
|
||||
/** Where Mercado Pago sends the professor after authorizing (or abandoning). */
|
||||
export function buildSubscriptionBackUrl(webOrigin: string, returnTo: BillingReturnTo): string {
|
||||
return `${webOrigin}/${returnTo === 'onboarding' ? 'onboarding' : 'billing'}?sub=return`;
|
||||
}
|
||||
|
||||
export type SubscriptionRecord = BillingSubscription;
|
||||
19
apps/backend/src/modules/billing/lib/index.ts
Normal file
19
apps/backend/src/modules/billing/lib/index.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
export { getGraceDays, getPlatformCredentials, isBillingEnforced, type PlatformCredentials } from './config';
|
||||
export {
|
||||
type Entitlements,
|
||||
exceedsLimits,
|
||||
PlanGuard,
|
||||
type PlanResolution,
|
||||
type PlanUsage,
|
||||
resolvePlan,
|
||||
type SubscriptionSnapshot,
|
||||
} from './entitlements';
|
||||
export { buildSubscriptionBackUrl, countryOf, toBillingChargeDto } from './helpers';
|
||||
export {
|
||||
type MpAuthorizedPayment,
|
||||
type MpPreapproval,
|
||||
mpPreapprovalClient,
|
||||
type PreapprovalClient,
|
||||
} from './mp-preapproval';
|
||||
export { coveredUntil, SyncSubscription, type SyncSubscriptionDeps } from './sync';
|
||||
export { verifyMpSignature } from './webhook-signature';
|
||||
180
apps/backend/src/modules/billing/lib/mp-preapproval.ts
Normal file
180
apps/backend/src/modules/billing/lib/mp-preapproval.ts
Normal file
@@ -0,0 +1,180 @@
|
||||
import { logger } from '@/logger';
|
||||
import { MP_API_URL, MpApiError } from '@/modules/mp/lib';
|
||||
|
||||
// Mercado Pago Subscriptions (preapproval), called with Gruperly's own
|
||||
// platform token of the professor's country. Plain `fetch`, like `mp-http.ts`.
|
||||
|
||||
export type MpPreapprovalStatus = 'pending' | 'authorized' | 'paused' | 'cancelled';
|
||||
|
||||
export type CreatePreapprovalInput = {
|
||||
reason: string;
|
||||
/** Our user id: the only thing that ties the subscription back to a professor. */
|
||||
externalReference: string;
|
||||
/** Mercado Pago requires the payer to log in with this exact email. */
|
||||
payerEmail: string;
|
||||
amount: number;
|
||||
currencyId: string;
|
||||
backUrl: string;
|
||||
/** First charge date; omitted means right after the professor authorizes. */
|
||||
startDate?: Date;
|
||||
};
|
||||
|
||||
export type MpPreapproval = {
|
||||
id: string;
|
||||
status: MpPreapprovalStatus | string;
|
||||
externalReference: string | null;
|
||||
initPoint: string | null;
|
||||
nextPaymentDate: string | null;
|
||||
};
|
||||
|
||||
export type MpAuthorizedPayment = {
|
||||
id: string;
|
||||
preapprovalId: string;
|
||||
/** Status of the invoice itself: scheduled, processed, recycling, cancelled. */
|
||||
status: string;
|
||||
/** Status of the payment Mercado Pago attempted for it, e.g. approved/rejected. */
|
||||
paymentStatus: string | null;
|
||||
amount: number;
|
||||
currencyId: string;
|
||||
/** When the charge was debited (or attempted), ISO. */
|
||||
debitDate: string | null;
|
||||
createdAt: string | null;
|
||||
};
|
||||
|
||||
async function request(
|
||||
accessToken: string,
|
||||
path: string,
|
||||
init: { method?: string; body?: unknown } = {},
|
||||
): Promise<Record<string, unknown>> {
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetch(`${MP_API_URL}${path}`, {
|
||||
method: init.method ?? 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: 'application/json',
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
},
|
||||
body: init.body === undefined ? undefined : JSON.stringify(init.body),
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error({ err: error, path: path.split('?')[0] }, 'Mercado Pago subscriptions unreachable');
|
||||
throw new MpApiError(0, null);
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
const payload = (await response.json().catch(() => null)) as Record<string, unknown> | null;
|
||||
const reason = typeof payload?.message === 'string' ? payload.message : null;
|
||||
// The path carries ids, never tokens or emails; the body is not logged.
|
||||
logger.error(
|
||||
{ status: response.status, reason, path: path.split('?')[0] },
|
||||
'Mercado Pago subscriptions request failed',
|
||||
);
|
||||
throw new MpApiError(response.status, reason);
|
||||
}
|
||||
|
||||
return (await response.json()) as Record<string, unknown>;
|
||||
}
|
||||
|
||||
function toPreapproval(payload: Record<string, unknown>): MpPreapproval {
|
||||
return {
|
||||
id: String(payload.id),
|
||||
status: String(payload.status),
|
||||
externalReference:
|
||||
typeof payload.external_reference === 'string' ? payload.external_reference : null,
|
||||
initPoint: typeof payload.init_point === 'string' ? payload.init_point : null,
|
||||
nextPaymentDate:
|
||||
typeof payload.next_payment_date === 'string' ? payload.next_payment_date : null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a monthly subscription waiting for the professor's authorization.
|
||||
* Nothing is charged until they log in to Mercado Pago through `initPoint`.
|
||||
*/
|
||||
export async function createPreapproval(
|
||||
accessToken: string,
|
||||
input: CreatePreapprovalInput,
|
||||
): Promise<MpPreapproval> {
|
||||
const payload = await request(accessToken, '/preapproval', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
reason: input.reason,
|
||||
external_reference: input.externalReference,
|
||||
payer_email: input.payerEmail,
|
||||
back_url: input.backUrl,
|
||||
status: 'pending',
|
||||
auto_recurring: {
|
||||
frequency: 1,
|
||||
frequency_type: 'months',
|
||||
transaction_amount: input.amount,
|
||||
currency_id: input.currencyId,
|
||||
...(input.startDate ? { start_date: input.startDate.toISOString() } : {}),
|
||||
},
|
||||
},
|
||||
});
|
||||
return toPreapproval(payload);
|
||||
}
|
||||
|
||||
export async function getPreapproval(accessToken: string, id: string): Promise<MpPreapproval> {
|
||||
return toPreapproval(await request(accessToken, `/preapproval/${encodeURIComponent(id)}`));
|
||||
}
|
||||
|
||||
export async function cancelPreapproval(accessToken: string, id: string): Promise<MpPreapproval> {
|
||||
return toPreapproval(
|
||||
await request(accessToken, `/preapproval/${encodeURIComponent(id)}`, {
|
||||
method: 'PUT',
|
||||
body: { status: 'cancelled' },
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function toAuthorizedPayment(payload: Record<string, unknown>): MpAuthorizedPayment {
|
||||
const payment = (payload.payment ?? null) as Record<string, unknown> | null;
|
||||
return {
|
||||
id: String(payload.id),
|
||||
preapprovalId: String(payload.preapproval_id),
|
||||
status: String(payload.status),
|
||||
paymentStatus: typeof payment?.status === 'string' ? payment.status : null,
|
||||
amount: Number(payload.transaction_amount ?? 0),
|
||||
currencyId: String(payload.currency_id ?? ''),
|
||||
debitDate: typeof payload.debit_date === 'string' ? payload.debit_date : null,
|
||||
createdAt: typeof payload.date_created === 'string' ? payload.date_created : null,
|
||||
};
|
||||
}
|
||||
|
||||
export async function getAuthorizedPayment(
|
||||
accessToken: string,
|
||||
id: string,
|
||||
): Promise<MpAuthorizedPayment> {
|
||||
return toAuthorizedPayment(
|
||||
await request(accessToken, `/authorized_payments/${encodeURIComponent(id)}`),
|
||||
);
|
||||
}
|
||||
|
||||
/** The invoices of one subscription, newest first as Mercado Pago returns them. */
|
||||
export async function searchAuthorizedPayments(
|
||||
accessToken: string,
|
||||
preapprovalId: string,
|
||||
): Promise<MpAuthorizedPayment[]> {
|
||||
const query = new URLSearchParams({ preapproval_id: preapprovalId, limit: '50' });
|
||||
const payload = await request(accessToken, `/authorized_payments/search?${query}`);
|
||||
const results = Array.isArray(payload.results) ? (payload.results as Record<string, unknown>[]) : [];
|
||||
return results.map(toAuthorizedPayment);
|
||||
}
|
||||
|
||||
export type PreapprovalClient = {
|
||||
createPreapproval: typeof createPreapproval;
|
||||
getPreapproval: typeof getPreapproval;
|
||||
cancelPreapproval: typeof cancelPreapproval;
|
||||
getAuthorizedPayment: typeof getAuthorizedPayment;
|
||||
searchAuthorizedPayments: typeof searchAuthorizedPayments;
|
||||
};
|
||||
|
||||
export const mpPreapprovalClient: PreapprovalClient = {
|
||||
createPreapproval,
|
||||
getPreapproval,
|
||||
cancelPreapproval,
|
||||
getAuthorizedPayment,
|
||||
searchAuthorizedPayments,
|
||||
};
|
||||
29
apps/backend/src/modules/billing/lib/read-only-middleware.ts
Normal file
29
apps/backend/src/modules/billing/lib/read-only-middleware.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import type { MiddlewareHandler } from 'hono';
|
||||
import type { BackendEnv } from '@/http/env';
|
||||
import { problemJson } from '@/http/problem-details';
|
||||
import { PlanGuard } from './entitlements';
|
||||
|
||||
const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
|
||||
|
||||
/**
|
||||
* Blocks writes while the professor's account is read-only (Free with more
|
||||
* usage than its limits). DELETE stays open: removing attendees is how they get
|
||||
* back under the limits without paying.
|
||||
*
|
||||
* It checks the signed-in user. The create paths (groups, attendees) check the
|
||||
* group **owner** on their own, so an ADMIN cannot add to a read-only owner's group.
|
||||
*/
|
||||
export function planReadOnlyMiddleware(guard: PlanGuard = new PlanGuard()): MiddlewareHandler<BackendEnv> {
|
||||
return async (c, next) => {
|
||||
const user = c.get('user');
|
||||
if (!user || SAFE_METHODS.has(c.req.method) || c.req.method === 'DELETE') {
|
||||
await next();
|
||||
return;
|
||||
}
|
||||
|
||||
const writable = await guard.requireWritable(user.id);
|
||||
if (!writable.ok) return problemJson(c, writable.error);
|
||||
|
||||
await next();
|
||||
};
|
||||
}
|
||||
157
apps/backend/src/modules/billing/lib/sync.ts
Normal file
157
apps/backend/src/modules/billing/lib/sync.ts
Normal file
@@ -0,0 +1,157 @@
|
||||
import type { PrismaClient, SubscriptionStatus } from '@generated/prisma/client';
|
||||
import type { CountryCode, ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { billingProviderErrorProblem } from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { logger } from '@/logger';
|
||||
import { getPlatformCredentials } from './config';
|
||||
import { type MpPreapproval, mpPreapprovalClient, type PreapprovalClient } from './mp-preapproval';
|
||||
|
||||
const MP_STATUS: Record<string, SubscriptionStatus> = {
|
||||
pending: 'PENDING',
|
||||
authorized: 'AUTHORIZED',
|
||||
paused: 'PAUSED',
|
||||
cancelled: 'CANCELLED',
|
||||
};
|
||||
|
||||
/** One approved monthly charge covers one month from the day it was debited. */
|
||||
export function coveredUntil(paidAt: Date): Date {
|
||||
const until = new Date(paidAt);
|
||||
until.setUTCMonth(until.getUTCMonth() + 1);
|
||||
return until;
|
||||
}
|
||||
|
||||
export type SyncSubscriptionDeps = {
|
||||
db?: Pick<PrismaClient, 'billingSubscription' | 'billingCharge'>;
|
||||
client?: PreapprovalClient;
|
||||
credentials?: typeof getPlatformCredentials;
|
||||
now?: () => Date;
|
||||
};
|
||||
|
||||
export type SyncOutcome = { synced: boolean; status: SubscriptionStatus | null };
|
||||
|
||||
/**
|
||||
* Brings one subscription row in line with Mercado Pago. Shared by the webhook,
|
||||
* the reconciliation job and the status endpoint (on read, while PENDING).
|
||||
*
|
||||
* Never trusts what a notification says: it asks Mercado Pago for the
|
||||
* preapproval and its invoices, checks that the preapproval is ours
|
||||
* (`external_reference` is the user id) and only then writes. Re-running it is
|
||||
* harmless; every write is an upsert or a monotonic `paidThrough`.
|
||||
*/
|
||||
export class SyncSubscription {
|
||||
constructor(private readonly deps: SyncSubscriptionDeps = {}) {}
|
||||
|
||||
async execute(subscriptionId: string): Promise<Result<SyncOutcome, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const subscription = await db.billingSubscription.findUnique({ where: { id: subscriptionId } });
|
||||
if (!subscription?.mpPreapprovalId) {
|
||||
return ok({ synced: false, status: subscription?.status ?? null });
|
||||
}
|
||||
|
||||
const credentials = (this.deps.credentials ?? getPlatformCredentials)(
|
||||
subscription.country as CountryCode,
|
||||
);
|
||||
if (!credentials.ok) return credentials;
|
||||
|
||||
const client = this.deps.client ?? mpPreapprovalClient;
|
||||
const token = credentials.value.accessToken;
|
||||
|
||||
let preapproval: MpPreapproval;
|
||||
let invoices: Awaited<ReturnType<PreapprovalClient['searchAuthorizedPayments']>>;
|
||||
try {
|
||||
preapproval = await client.getPreapproval(token, subscription.mpPreapprovalId);
|
||||
invoices = await client.searchAuthorizedPayments(token, subscription.mpPreapprovalId);
|
||||
} catch {
|
||||
return err(billingProviderErrorProblem());
|
||||
}
|
||||
|
||||
if (preapproval.externalReference !== subscription.userId) {
|
||||
logger.warn({ subscriptionId }, 'Mercado Pago preapproval does not belong to this subscription');
|
||||
return ok({ synced: false, status: subscription.status });
|
||||
}
|
||||
|
||||
const now = this.deps.now?.() ?? new Date();
|
||||
let paidThrough = subscription.paidThrough;
|
||||
|
||||
for (const invoice of invoices) {
|
||||
if (invoice.preapprovalId !== subscription.mpPreapprovalId) continue;
|
||||
const approved = invoice.paymentStatus === 'approved';
|
||||
const debitedAt = invoice.debitDate ?? invoice.createdAt;
|
||||
const paidAt = approved && debitedAt ? new Date(debitedAt) : null;
|
||||
|
||||
await db.billingCharge.upsert({
|
||||
where: { mpAuthorizedPaymentId: invoice.id },
|
||||
create: {
|
||||
subscriptionId: subscription.id,
|
||||
mpAuthorizedPaymentId: invoice.id,
|
||||
amount: invoice.amount,
|
||||
currency: invoice.currencyId || subscription.currency,
|
||||
status: invoice.paymentStatus ?? invoice.status,
|
||||
paidAt,
|
||||
},
|
||||
update: { status: invoice.paymentStatus ?? invoice.status, paidAt },
|
||||
});
|
||||
|
||||
if (paidAt) {
|
||||
const until = coveredUntil(paidAt);
|
||||
if (!paidThrough || until > paidThrough) paidThrough = until;
|
||||
}
|
||||
}
|
||||
|
||||
const status = MP_STATUS[preapproval.status] ?? subscription.status;
|
||||
await db.billingSubscription.update({
|
||||
where: { id: subscription.id },
|
||||
data: {
|
||||
status,
|
||||
authorizedAt: status === 'AUTHORIZED' && !subscription.authorizedAt ? now : undefined,
|
||||
nextPaymentDate: preapproval.nextPaymentDate ? new Date(preapproval.nextPaymentDate) : null,
|
||||
paidThrough,
|
||||
lastSyncedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
return ok({ synced: true, status });
|
||||
}
|
||||
|
||||
/**
|
||||
* Same as `execute`, starting from a Mercado Pago preapproval id (webhooks).
|
||||
* A notification can beat our own write of `mpPreapprovalId` (the professor
|
||||
* authorizes faster than our request returns), so an unknown id falls back to
|
||||
* the `external_reference` once Mercado Pago confirms it.
|
||||
*/
|
||||
async byPreapprovalId(
|
||||
country: CountryCode,
|
||||
preapprovalId: string,
|
||||
): Promise<Result<SyncOutcome, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const known = await db.billingSubscription.findUnique({ where: { mpPreapprovalId: preapprovalId } });
|
||||
if (known) return this.execute(known.id);
|
||||
|
||||
const credentials = (this.deps.credentials ?? getPlatformCredentials)(country);
|
||||
if (!credentials.ok) return credentials;
|
||||
|
||||
let preapproval: MpPreapproval;
|
||||
try {
|
||||
preapproval = await (this.deps.client ?? mpPreapprovalClient).getPreapproval(
|
||||
credentials.value.accessToken,
|
||||
preapprovalId,
|
||||
);
|
||||
} catch {
|
||||
return err(billingProviderErrorProblem());
|
||||
}
|
||||
// A cancelled one is a previous attempt being replaced, never the new one.
|
||||
if (!preapproval.externalReference || preapproval.status === 'cancelled') {
|
||||
return ok({ synced: false, status: null });
|
||||
}
|
||||
|
||||
const claimed = await db.billingSubscription.updateMany({
|
||||
where: { userId: preapproval.externalReference, country, mpPreapprovalId: null },
|
||||
data: { mpPreapprovalId: preapprovalId },
|
||||
});
|
||||
if (claimed.count === 0) return ok({ synced: false, status: null });
|
||||
|
||||
const row = await db.billingSubscription.findUnique({ where: { mpPreapprovalId: preapprovalId } });
|
||||
return row ? this.execute(row.id) : ok({ synced: false, status: null });
|
||||
}
|
||||
}
|
||||
40
apps/backend/src/modules/billing/lib/webhook-signature.ts
Normal file
40
apps/backend/src/modules/billing/lib/webhook-signature.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
import { createHmac, timingSafeEqual } from 'node:crypto';
|
||||
|
||||
/**
|
||||
* Checks Mercado Pago's `x-signature` header (`ts=<ts>,v1=<hex>`).
|
||||
*
|
||||
* Mercado Pago does not sign the body: it signs a manifest built from the
|
||||
* notified resource id (the `data.id` query parameter, lower-cased when it is
|
||||
* alphanumeric), the `x-request-id` header and the timestamp. Parts that did
|
||||
* not come in the request are left out of the manifest.
|
||||
*/
|
||||
export function verifyMpSignature(params: {
|
||||
signature: string | null;
|
||||
requestId: string | null;
|
||||
dataId: string | null;
|
||||
secret: string;
|
||||
}): boolean {
|
||||
if (!params.signature) return false;
|
||||
|
||||
let ts: string | null = null;
|
||||
let v1: string | null = null;
|
||||
for (const part of params.signature.split(',')) {
|
||||
const [key, value] = part.split('=', 2).map((piece) => piece.trim());
|
||||
if (key === 'ts') ts = value ?? null;
|
||||
if (key === 'v1') v1 = value ?? null;
|
||||
}
|
||||
if (!ts || !v1) return false;
|
||||
|
||||
const dataId = params.dataId && /^[a-z0-9]+$/i.test(params.dataId)
|
||||
? params.dataId.toLowerCase()
|
||||
: params.dataId;
|
||||
|
||||
let manifest = '';
|
||||
if (dataId) manifest += `id:${dataId};`;
|
||||
if (params.requestId) manifest += `request-id:${params.requestId};`;
|
||||
manifest += `ts:${ts};`;
|
||||
|
||||
const expected = Buffer.from(createHmac('sha256', params.secret).update(manifest).digest('hex'));
|
||||
const received = Buffer.from(v1);
|
||||
return received.length === expected.length && timingSafeEqual(received, expected);
|
||||
}
|
||||
16
apps/backend/src/modules/billing/routes.ts
Normal file
16
apps/backend/src/modules/billing/routes.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { Hono } from 'hono';
|
||||
import cancelRoute from './features/cancel/route';
|
||||
import chargesRoute from './features/charges/route';
|
||||
import statusRoute from './features/status/route';
|
||||
import subscribeRoute from './features/subscribe/route';
|
||||
import webhookRoute from './features/webhook/route';
|
||||
|
||||
const routes = new Hono();
|
||||
|
||||
routes.route('/', statusRoute);
|
||||
routes.route('/', subscribeRoute);
|
||||
routes.route('/', cancelRoute);
|
||||
routes.route('/', chargesRoute);
|
||||
routes.route('/', webhookRoute);
|
||||
|
||||
export default routes;
|
||||
@@ -7,6 +7,7 @@ import type {
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { conflictProblem, notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import { default as prisma, UnitOfWork } from '@/lib/prisma';
|
||||
import { PlanGuard } from '@/modules/billing/lib/entitlements';
|
||||
import {
|
||||
findGroupOwnedByUser,
|
||||
type GroupWaitlistEntryRecord,
|
||||
@@ -18,6 +19,7 @@ import { type GroupPreRegistrationRecord } from '../../lib/helpers';
|
||||
type ApproveGroupPreRegistrationDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'groupPreRegistration'>;
|
||||
unitOfWork?: UnitOfWork;
|
||||
planGuard?: Pick<PlanGuard, 'canAddAttendees'>;
|
||||
};
|
||||
|
||||
export class ApproveGroupPreRegistration {
|
||||
@@ -51,6 +53,11 @@ export class ApproveGroupPreRegistration {
|
||||
);
|
||||
}
|
||||
|
||||
const allowed = await (this.deps.planGuard ?? new PlanGuard()).canAddAttendees(userId);
|
||||
if (!allowed.ok) {
|
||||
return allowed;
|
||||
}
|
||||
|
||||
const record = entry as unknown as GroupPreRegistrationRecord;
|
||||
|
||||
return unitOfWork.executeResult(
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { ProblemDetails, PromoteGroupWaitlistEntryResult, Result } from '@g
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import { default as prisma, UnitOfWork } from '@/lib/prisma';
|
||||
import { PlanGuard } from '@/modules/billing/lib/entitlements';
|
||||
import {
|
||||
findGroupOwnedByUser,
|
||||
type GroupWaitlistEntryRecord,
|
||||
@@ -12,6 +13,7 @@ import { promoteWaitlistEntryRecord } from '../../lib/promote';
|
||||
type PromoteGroupWaitlistEntryDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee' | 'groupWaitlistEntry'>;
|
||||
unitOfWork?: UnitOfWork;
|
||||
planGuard?: Pick<PlanGuard, 'canAddAttendees'>;
|
||||
};
|
||||
|
||||
export class PromoteGroupWaitlistEntry {
|
||||
@@ -37,6 +39,11 @@ export class PromoteGroupWaitlistEntry {
|
||||
return err(notFoundResourceProblem('GroupWaitlistEntry', entryId));
|
||||
}
|
||||
|
||||
const allowed = await (this.deps.planGuard ?? new PlanGuard()).canAddAttendees(userId);
|
||||
if (!allowed.ok) {
|
||||
return allowed;
|
||||
}
|
||||
|
||||
return unitOfWork.executeResult(
|
||||
async (tx: Prisma.TransactionClient) => {
|
||||
const promoteResult = await promoteWaitlistEntryRecord(
|
||||
|
||||
@@ -8,10 +8,12 @@ import type {
|
||||
} from '@gruperly/shared';
|
||||
import { ok } from '@gruperly/shared';
|
||||
import { default as prisma, UnitOfWork } from '@/lib/prisma';
|
||||
import { PlanGuard } from '@/modules/billing/lib/entitlements';
|
||||
import { type GroupRecord, toGroupDto } from '../../lib';
|
||||
|
||||
type CreateGroupDeps = {
|
||||
unitOfWork?: UnitOfWork;
|
||||
planGuard?: Pick<PlanGuard, 'canCreateGroup'>;
|
||||
};
|
||||
|
||||
export class CreateGroup {
|
||||
@@ -23,6 +25,11 @@ export class CreateGroup {
|
||||
): Promise<Result<CreateGroupResult, ProblemDetails>> {
|
||||
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma);
|
||||
|
||||
const allowed = await (this.deps.planGuard ?? new PlanGuard()).canCreateGroup(userId);
|
||||
if (!allowed.ok) {
|
||||
return allowed;
|
||||
}
|
||||
|
||||
const transaction = unitOfWork.executeResult(
|
||||
async (tx: Prisma.TransactionClient) => {
|
||||
const created = await tx.group.create({
|
||||
|
||||
@@ -7,14 +7,16 @@ import type {
|
||||
Result,
|
||||
} from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { onboardingAlreadyCompletedProblem } from '@/http/problem-builders';
|
||||
import { onboardingAlreadyCompletedProblem, planNotSelectedProblem } from '@/http/problem-builders';
|
||||
import { problemDetails } from '@/http/problem-details';
|
||||
import { default as prisma, UnitOfWork } from '@/lib/prisma';
|
||||
import { PlanGuard } from '@/modules/billing/lib/entitlements';
|
||||
import { toOnboardingGroupDto } from '../../lib';
|
||||
|
||||
type CreateFirstGroupDeps = {
|
||||
db?: Pick<PrismaClient, 'user'>;
|
||||
unitOfWork?: UnitOfWork;
|
||||
planGuard?: Pick<PlanGuard, 'canCreateGroup'>;
|
||||
};
|
||||
|
||||
export class CreateFirstGroup {
|
||||
@@ -34,6 +36,15 @@ export class CreateFirstGroup {
|
||||
if (user.onboardingCompleted) {
|
||||
return err(onboardingAlreadyCompletedProblem());
|
||||
}
|
||||
// The "Plan" step is mandatory; this is its server-side half.
|
||||
if (!user.planSelectedAt) {
|
||||
return err(planNotSelectedProblem());
|
||||
}
|
||||
|
||||
const allowed = await (this.deps.planGuard ?? new PlanGuard()).canCreateGroup(userId);
|
||||
if (!allowed.ok) {
|
||||
return allowed;
|
||||
}
|
||||
|
||||
const transaction = unitOfWork.executeResult(
|
||||
async (tx: Prisma.TransactionClient) => {
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import type { SelectPlanInput } from '@gruperly/shared';
|
||||
import { SelectPlanInputSchema } from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { validate } from '@/http/validate';
|
||||
import { SelectPlan } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.post('/', validate.json(SelectPlanInputSchema), async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
|
||||
const input = c.req.valid('json') as SelectPlanInput;
|
||||
const result = await new SelectPlan().execute(user.id, input);
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
@@ -0,0 +1,78 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { ProblemDetails, Result, SelectPlanInput, SelectPlanResultDto } from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import {
|
||||
notFoundResourceProblem,
|
||||
onboardingAlreadyCompletedProblem,
|
||||
subscriptionAlreadyActiveProblem,
|
||||
} from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { CancelSubscription } from '@/modules/billing/features/cancel/use-case';
|
||||
import { Subscribe } from '@/modules/billing/features/subscribe/use-case';
|
||||
|
||||
type SelectPlanDeps = {
|
||||
db?: Pick<PrismaClient, 'user' | 'billingSubscription'>;
|
||||
subscribe?: Pick<Subscribe, 'execute'>;
|
||||
cancel?: Pick<CancelSubscription, 'execute'>;
|
||||
now?: () => Date;
|
||||
};
|
||||
|
||||
/**
|
||||
* The mandatory "Plan" step of the onboarding.
|
||||
*
|
||||
* It stores the country first: until now it was only saved with the first
|
||||
* group, and Pro needs it to pick the price and Gruperly's Mercado Pago account.
|
||||
* Free is immediate; Pro starts the subscription and returns where the browser
|
||||
* goes to authorize it, coming back to `/onboarding?sub=return`.
|
||||
*/
|
||||
export class SelectPlan {
|
||||
constructor(private readonly deps: SelectPlanDeps = {}) {}
|
||||
|
||||
async execute(
|
||||
userId: string,
|
||||
input: SelectPlanInput,
|
||||
): Promise<Result<SelectPlanResultDto, 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));
|
||||
if (user.onboardingCompleted) return err(onboardingAlreadyCompletedProblem());
|
||||
|
||||
await db.user.update({ where: { id: userId }, data: { country: input.country } });
|
||||
const subscription = await db.billingSubscription.findUnique({ where: { userId } });
|
||||
|
||||
if (input.plan === 'FREE') {
|
||||
// A paid subscription is never dropped from here; that is "Cancelar" in /billing.
|
||||
if (subscription?.status === 'AUTHORIZED') return err(subscriptionAlreadyActiveProblem());
|
||||
|
||||
// Going back to Free after abandoning Mercado Pago: the attempt is void.
|
||||
if (subscription && subscription.status !== 'CANCELLED') {
|
||||
const cancelled = await (this.deps.cancel ?? new CancelSubscription()).execute(userId);
|
||||
if (!cancelled.ok) {
|
||||
await db.billingSubscription.update({
|
||||
where: { id: subscription.id },
|
||||
data: { status: 'CANCELLED', nextPaymentDate: null },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
await db.user.update({ where: { id: userId }, data: { planSelectedAt: now } });
|
||||
return ok({ plan: 'FREE', checkoutUrl: null });
|
||||
}
|
||||
|
||||
if (subscription?.status === 'AUTHORIZED') {
|
||||
await db.user.update({ where: { id: userId }, data: { planSelectedAt: now } });
|
||||
return ok({ plan: 'PRO', checkoutUrl: null });
|
||||
}
|
||||
|
||||
const started = await (this.deps.subscribe ?? new Subscribe()).execute(userId, {
|
||||
payerEmail: input.payerEmail,
|
||||
returnTo: 'onboarding',
|
||||
});
|
||||
if (!started.ok) return started;
|
||||
|
||||
await db.user.update({ where: { id: userId }, data: { planSelectedAt: now } });
|
||||
return ok({ plan: 'PRO', checkoutUrl: started.value.checkoutUrl });
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,12 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { OnboardingStatusDto, ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import type { OnboardingStatusDto, Plan, ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { countryCodeSchema, err, ok } from '@gruperly/shared';
|
||||
import { problemDetails } from '@/http/problem-details';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { isWhatsappAccountUsable } from '@/modules/whatsapp/lib/account';
|
||||
|
||||
type GetOnboardingStatusDeps = {
|
||||
db?: Pick<PrismaClient, 'user' | 'mpAccount' | 'whatsappAccount'>;
|
||||
db?: Pick<PrismaClient, 'user' | 'mpAccount' | 'whatsappAccount' | 'billingSubscription'>;
|
||||
};
|
||||
|
||||
export class GetOnboardingStatus {
|
||||
@@ -30,8 +30,23 @@ export class GetOnboardingStatus {
|
||||
const whatsappAccount = await db.whatsappAccount.findUnique({ where: { ownerId: userId } });
|
||||
const whatsappConnected = isWhatsappAccountUsable(whatsappAccount);
|
||||
|
||||
// The "Plan" step: PRO as soon as the professor chose it (a subscription
|
||||
// that is not cancelled, even if Mercado Pago has not authorized it yet).
|
||||
const subscription = await db.billingSubscription.findUnique({ where: { userId } });
|
||||
const planSelected = user.planSelectedAt != null;
|
||||
const selectedPlan: Plan | null = planSelected
|
||||
? subscription && subscription.status !== 'CANCELLED' ? 'PRO' : 'FREE'
|
||||
: null;
|
||||
const country = countryCodeSchema.safeParse(user.country);
|
||||
const plan = {
|
||||
planSelected,
|
||||
selectedPlan,
|
||||
subscriptionStatus: subscription?.status ?? null,
|
||||
country: country.success ? country.data : null,
|
||||
};
|
||||
|
||||
if (user.onboardingCompleted) {
|
||||
return ok({ step: 'COMPLETED', paymentConnected: true, whatsappConnected, completed: true });
|
||||
return ok({ step: 'COMPLETED', paymentConnected: true, whatsappConnected, completed: true, ...plan });
|
||||
}
|
||||
|
||||
// Linking Mercado Pago is optional, so `paymentConnected` here only resumes
|
||||
@@ -44,9 +59,16 @@ export class GetOnboardingStatus {
|
||||
paymentConnected: true,
|
||||
whatsappConnected,
|
||||
completed: false,
|
||||
...plan,
|
||||
});
|
||||
}
|
||||
|
||||
return ok({ step: 'NOT_STARTED', paymentConnected: false, whatsappConnected, completed: false });
|
||||
return ok({
|
||||
step: 'NOT_STARTED',
|
||||
paymentConnected: false,
|
||||
whatsappConnected,
|
||||
completed: false,
|
||||
...plan,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { Hono } from 'hono';
|
||||
import firstGroupRoute from './features/first-group/route';
|
||||
import selectPlanRoute from './features/select-plan/route';
|
||||
import statusRoute from './features/status/route';
|
||||
|
||||
const routes = new Hono();
|
||||
|
||||
routes.route('/status', statusRoute);
|
||||
routes.route('/first-group', firstGroupRoute);
|
||||
routes.route('/plan', selectPlanRoute);
|
||||
|
||||
export default routes;
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
} from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { logger } from '@/logger';
|
||||
import { PlanGuard } from '@/modules/billing/lib/entitlements';
|
||||
import { getMpAccessToken } from '@/modules/mp';
|
||||
import { createCheckoutPreference, getWebOrigin, MpApiError } from '@/modules/mp/lib';
|
||||
|
||||
@@ -24,6 +25,7 @@ type BatchDeps = {
|
||||
createPreference?: typeof createCheckoutPreference;
|
||||
getToken?: typeof getMpAccessToken;
|
||||
webOrigin?: string;
|
||||
planGuard?: Pick<PlanGuard, 'requireFeature'>;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -60,6 +62,14 @@ export class CreatePaymentBatch {
|
||||
return err(noGroupAccessProblem());
|
||||
}
|
||||
|
||||
const allowed = await (this.deps.planGuard ?? new PlanGuard()).requireFeature(
|
||||
group.createdById,
|
||||
'mpCharges',
|
||||
);
|
||||
if (!allowed.ok) {
|
||||
return allowed;
|
||||
}
|
||||
|
||||
if (group.price == null) {
|
||||
return err(groupWithoutPriceProblem());
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
} from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { logger } from '@/logger';
|
||||
import { PlanGuard } from '@/modules/billing/lib/entitlements';
|
||||
import { getMpAccessToken } from '@/modules/mp';
|
||||
import { createCheckoutPreference, getWebOrigin } from '@/modules/mp/lib';
|
||||
import { type PaymentRecord, toPaymentDto } from '../../lib';
|
||||
@@ -18,6 +19,7 @@ type RenewDeps = {
|
||||
createPreference?: typeof createCheckoutPreference;
|
||||
getToken?: typeof getMpAccessToken;
|
||||
webOrigin?: string;
|
||||
planGuard?: Pick<PlanGuard, 'requireFeature'>;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -59,6 +61,14 @@ export class RenewPaymentLink {
|
||||
return ok(toPaymentDto(payment as unknown as PaymentRecord));
|
||||
}
|
||||
|
||||
const allowed = await (this.deps.planGuard ?? new PlanGuard()).requireFeature(
|
||||
payment.group.createdById,
|
||||
'mpCharges',
|
||||
);
|
||||
if (!allowed.ok) {
|
||||
return allowed;
|
||||
}
|
||||
|
||||
if (payment.group.price == null) {
|
||||
return err(groupWithoutPriceProblem());
|
||||
}
|
||||
|
||||
@@ -8,8 +8,12 @@ import type {
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { forbiddenProblem, notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { PlanGuard } from '@/modules/billing/lib/entitlements';
|
||||
|
||||
type UpdateGroupAutomationsDeps = { db?: Pick<PrismaClient, 'group'> };
|
||||
type UpdateGroupAutomationsDeps = {
|
||||
db?: Pick<PrismaClient, 'group'>;
|
||||
planGuard?: Pick<PlanGuard, 'requireFeature'>;
|
||||
};
|
||||
|
||||
/**
|
||||
* Turns the group's weekly WhatsApp automations on or off. Only the owner can:
|
||||
@@ -42,6 +46,15 @@ export class UpdateGroupAutomationsUseCase {
|
||||
);
|
||||
}
|
||||
|
||||
// Turning them off always works, so a Free professor can clean up.
|
||||
if (input.autoPaymentReminders === true || input.autoReengagement === true) {
|
||||
const allowed = await (this.deps.planGuard ?? new PlanGuard()).requireFeature(
|
||||
userId,
|
||||
'whatsappAutomations',
|
||||
);
|
||||
if (!allowed.ok) return allowed;
|
||||
}
|
||||
|
||||
const updated = await db.group.update({
|
||||
where: { id: groupId },
|
||||
data: {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { CountryCode, WhatsappMessageKind } from '@gruperly/shared';
|
||||
import { countryCodeSchema } from '@gruperly/shared';
|
||||
import { PlanGuard } from '@/modules/billing/lib/entitlements';
|
||||
import type { MessagingProvider, WhatsappAccountRecord } from '../providers/messaging-provider';
|
||||
|
||||
export type EligibleGroup = { id: string; name: string };
|
||||
@@ -16,13 +17,15 @@ type AutomationFlag = 'autoPaymentReminders' | 'autoReengagement';
|
||||
/**
|
||||
* Groups with the automation on, bundled by owner, keeping only owners whose
|
||||
* WhatsApp is linked with the active provider and ready to send this kind of
|
||||
* message (for Kapso: the template is approved).
|
||||
* message (for Kapso: the template is approved) and whose plan includes the
|
||||
* automations (Pro). A Free owner keeps the flag on but nothing goes out.
|
||||
*/
|
||||
export async function findEligibleAccounts(
|
||||
db: Pick<PrismaClient, 'group'>,
|
||||
provider: MessagingProvider,
|
||||
flag: AutomationFlag,
|
||||
kind: WhatsappMessageKind,
|
||||
planGuard: Pick<PlanGuard, 'hasFeature'> = new PlanGuard(),
|
||||
): Promise<EligibleAccount[]> {
|
||||
const groups = await db.group.findMany({
|
||||
where: {
|
||||
@@ -52,7 +55,8 @@ export async function findEligibleAccounts(
|
||||
}
|
||||
|
||||
const eligible: EligibleAccount[] = [];
|
||||
for (const entry of byOwner.values()) {
|
||||
for (const [ownerId, entry] of byOwner) {
|
||||
if (!(await planGuard.hasFeature(ownerId, 'whatsappAutomations'))) continue;
|
||||
if ((await provider.readiness(entry.account, kind)) === 'ready') eligible.push(entry);
|
||||
}
|
||||
return eligible;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import app from '@/app';
|
||||
import { getPrismaClient } from '@/lib/prisma';
|
||||
import { logger } from '@/logger';
|
||||
import { startBillingJobs } from '@/modules/billing';
|
||||
import { startMpJobs } from '@/modules/mp';
|
||||
import { startPaymentJobs } from '@/modules/payments';
|
||||
import { startWhatsappJobs } from '@/modules/whatsapp';
|
||||
@@ -17,6 +18,7 @@ const server = Bun.serve({
|
||||
startMpJobs();
|
||||
startPaymentJobs();
|
||||
startWhatsappJobs();
|
||||
startBillingJobs();
|
||||
|
||||
async function shutdown(): Promise<void> {
|
||||
server.stop(true);
|
||||
|
||||
116
apps/backend/test/billing-entitlements.test.ts
Normal file
116
apps/backend/test/billing-entitlements.test.ts
Normal file
@@ -0,0 +1,116 @@
|
||||
import { describe, expect, it, mock } from 'bun:test';
|
||||
import { PlanGuard, resolvePlan } from '@/modules/billing/lib/entitlements';
|
||||
|
||||
const now = new Date('2026-10-22T12:00:00.000Z');
|
||||
const days = (n: number) => new Date(now.getTime() + n * 24 * 60 * 60 * 1000);
|
||||
|
||||
function makeDb(params: {
|
||||
subscription?: Record<string, unknown> | null;
|
||||
groups?: number;
|
||||
attendees?: number;
|
||||
}) {
|
||||
return {
|
||||
billingSubscription: { findUnique: mock(async () => params.subscription ?? null) },
|
||||
group: { count: mock(async () => params.groups ?? 0) },
|
||||
attendee: { count: mock(async () => params.attendees ?? 0) },
|
||||
};
|
||||
}
|
||||
|
||||
function makeGuard(db: ReturnType<typeof makeDb>, enforced = true) {
|
||||
return new PlanGuard({ db: db as never, enforced, graceDays: 7, now: () => now });
|
||||
}
|
||||
|
||||
describe('resolvePlan', () => {
|
||||
it('is Free without a subscription', () => {
|
||||
expect(resolvePlan(null, now, 7)).toEqual({ plan: 'FREE', graceUntil: null });
|
||||
});
|
||||
|
||||
it('is Pro while a charge covers today', () => {
|
||||
const plan = resolvePlan({ status: 'AUTHORIZED', authorizedAt: days(-20), paidThrough: days(10) }, now, 7);
|
||||
expect(plan).toEqual({ plan: 'PRO', graceUntil: null });
|
||||
});
|
||||
|
||||
it('keeps Pro on grace after the paid period, then drops to Free', () => {
|
||||
const onGrace = resolvePlan({ status: 'AUTHORIZED', authorizedAt: days(-40), paidThrough: days(-2) }, now, 7);
|
||||
expect(onGrace).toEqual({ plan: 'PRO', graceUntil: days(5) });
|
||||
|
||||
const lapsed = resolvePlan({ status: 'AUTHORIZED', authorizedAt: days(-40), paidThrough: days(-8) }, now, 7);
|
||||
expect(lapsed).toEqual({ plan: 'FREE', graceUntil: null });
|
||||
});
|
||||
|
||||
it('keeps Pro until the end of what was paid after a cancellation', () => {
|
||||
const plan = resolvePlan({ status: 'CANCELLED', authorizedAt: days(-20), paidThrough: days(10) }, now, 7);
|
||||
expect(plan.plan).toBe('PRO');
|
||||
});
|
||||
|
||||
it('is Pro right after authorizing, while the first charge is in flight', () => {
|
||||
const plan = resolvePlan({ status: 'AUTHORIZED', authorizedAt: days(-1), paidThrough: null }, now, 7);
|
||||
expect(plan.plan).toBe('PRO');
|
||||
});
|
||||
|
||||
it('is Free for a subscription that was never authorized', () => {
|
||||
const plan = resolvePlan({ status: 'PENDING', authorizedAt: null, paidThrough: null }, now, 7);
|
||||
expect(plan.plan).toBe('FREE');
|
||||
});
|
||||
});
|
||||
|
||||
describe('PlanGuard', () => {
|
||||
it('lets everything through without touching the database when not enforced', async () => {
|
||||
const db = makeDb({ groups: 50, attendees: 500 });
|
||||
const guard = makeGuard(db, false);
|
||||
|
||||
expect((await guard.canCreateGroup('user-1')).ok).toBe(true);
|
||||
expect((await guard.canAddAttendees('user-1', 10)).ok).toBe(true);
|
||||
expect((await guard.requireFeature('user-1', 'mpCharges')).ok).toBe(true);
|
||||
expect((await guard.requireWritable('user-1')).ok).toBe(true);
|
||||
expect(db.group.count).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('stops a Free professor at the group limit', async () => {
|
||||
const result = await makeGuard(makeDb({ groups: 1 })).canCreateGroup('user-1');
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) expect(result.error).toMatchObject({ status: 402, code: 'plan_limit_reached' });
|
||||
});
|
||||
|
||||
it('counts a whole import against the attendee limit', async () => {
|
||||
const guard = makeGuard(makeDb({ groups: 1, attendees: 10 }));
|
||||
|
||||
expect((await guard.canAddAttendees('user-1', 5)).ok).toBe(true);
|
||||
const tooMany = await guard.canAddAttendees('user-1', 6);
|
||||
expect(tooMany.ok).toBe(false);
|
||||
if (!tooMany.ok) expect(tooMany.error.code).toBe('plan_limit_reached');
|
||||
});
|
||||
|
||||
it('keeps Pro-only features off for Free', async () => {
|
||||
const result = await makeGuard(makeDb({})).requireFeature('user-1', 'whatsappAutomations');
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) expect(result.error).toMatchObject({ status: 402, code: 'plan_feature_required' });
|
||||
});
|
||||
|
||||
it('puts a Free account over its limits in read-only', async () => {
|
||||
const guard = makeGuard(makeDb({ groups: 3, attendees: 40 }));
|
||||
|
||||
const entitlements = await guard.getEntitlements('user-1');
|
||||
expect(entitlements.readOnly).toBe(true);
|
||||
const writable = await guard.requireWritable('user-1');
|
||||
expect(writable.ok).toBe(false);
|
||||
if (!writable.ok) expect(writable.error.code).toBe('plan_read_only');
|
||||
});
|
||||
|
||||
it('gives Pro no limits', async () => {
|
||||
const guard = makeGuard(
|
||||
makeDb({
|
||||
subscription: { status: 'AUTHORIZED', authorizedAt: days(-5), paidThrough: days(25) },
|
||||
groups: 12,
|
||||
attendees: 300,
|
||||
}),
|
||||
);
|
||||
|
||||
expect((await guard.canCreateGroup('user-1')).ok).toBe(true);
|
||||
expect((await guard.canAddAttendees('user-1', 100)).ok).toBe(true);
|
||||
expect((await guard.requireFeature('user-1', 'mpCharges')).ok).toBe(true);
|
||||
expect((await guard.getEntitlements('user-1')).readOnly).toBe(false);
|
||||
});
|
||||
});
|
||||
86
apps/backend/test/billing-plan-guards.test.ts
Normal file
86
apps/backend/test/billing-plan-guards.test.ts
Normal file
@@ -0,0 +1,86 @@
|
||||
import { describe, expect, it, mock } from 'bun:test';
|
||||
import { err } from '@gruperly/shared';
|
||||
import {
|
||||
planFeatureRequiredProblem,
|
||||
planLimitReachedProblem,
|
||||
} from '@/http/problem-builders';
|
||||
import { BulkCreateAttendeesUseCase } from '@/modules/attendees/features/bulk-create/use-case';
|
||||
import { CreateGroup } from '@/modules/groups/features/create/use-case';
|
||||
import { CreatePaymentBatch } from '@/modules/payments/features/create-batch/use-case';
|
||||
import { UpdateGroupAutomationsUseCase } from '@/modules/whatsapp/features/update-automations/use-case';
|
||||
|
||||
const ownerId = 'owner-1';
|
||||
|
||||
describe('plan guards in the use cases', () => {
|
||||
it('does not create a group past the Free limit', async () => {
|
||||
const unitOfWork = { executeResult: mock() };
|
||||
const planGuard = { canCreateGroup: mock(async () => err(planLimitReachedProblem('groups', 1))) };
|
||||
|
||||
const result = await new CreateGroup({ unitOfWork: unitOfWork as never, planGuard }).execute(
|
||||
{} as never,
|
||||
ownerId,
|
||||
);
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) expect(result.error).toMatchObject({ status: 402, code: 'plan_limit_reached' });
|
||||
expect(unitOfWork.executeResult).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('checks a bulk import against the group owner, with the number of new attendees', async () => {
|
||||
const db = {
|
||||
group: { findUnique: mock(async () => ({ id: 'g1', createdById: ownerId, members: [{ userId: 'admin-1' }] })) },
|
||||
attendee: { findMany: mock(async () => [{ phone: '1111' }]), create: mock() },
|
||||
};
|
||||
const planGuard = { canAddAttendees: mock(async () => err(planLimitReachedProblem('attendees', 15))) };
|
||||
|
||||
const result = await new BulkCreateAttendeesUseCase({ db: db as never, planGuard }).execute('g1', 'admin-1', {
|
||||
attendees: [
|
||||
{ fullName: 'Ana', phone: '2222' },
|
||||
{ fullName: 'Beto', phone: '3333' },
|
||||
{ fullName: 'Repetido', phone: '1111' },
|
||||
],
|
||||
} as never);
|
||||
|
||||
expect(planGuard.canAddAttendees).toHaveBeenCalledWith(ownerId, 2);
|
||||
expect(result.ok).toBe(false);
|
||||
expect(db.attendee.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps charging with Mercado Pago for Pro', async () => {
|
||||
const db = {
|
||||
group: { findUnique: mock(async () => ({ id: 'g1', createdById: ownerId, price: 100, members: [] })) },
|
||||
attendee: { findMany: mock() },
|
||||
payment: { create: mock() },
|
||||
user: { findUnique: mock() },
|
||||
};
|
||||
const planGuard = { requireFeature: mock(async () => err(planFeatureRequiredProblem('mpCharges'))) };
|
||||
|
||||
const result = await new CreatePaymentBatch({ db: db as never, planGuard }).execute('g1', ownerId, {
|
||||
dueDate: '2026-11-05T12:00:00.000Z',
|
||||
});
|
||||
|
||||
expect(planGuard.requireFeature).toHaveBeenCalledWith(ownerId, 'mpCharges');
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) expect(result.error).toMatchObject({ status: 402, code: 'plan_feature_required' });
|
||||
expect(db.attendee.findMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('blocks turning automations on for Free, but lets them be turned off', async () => {
|
||||
const db = {
|
||||
group: {
|
||||
findUnique: mock(async () => ({ id: 'g1', createdById: ownerId })),
|
||||
update: mock(async () => ({ autoPaymentReminders: false, autoReengagement: false })),
|
||||
},
|
||||
};
|
||||
const planGuard = { requireFeature: mock(async () => err(planFeatureRequiredProblem('whatsappAutomations'))) };
|
||||
const useCase = new UpdateGroupAutomationsUseCase({ db: db as never, planGuard });
|
||||
|
||||
const on = await useCase.execute('g1', ownerId, { autoPaymentReminders: true });
|
||||
expect(on.ok).toBe(false);
|
||||
expect(db.group.update).not.toHaveBeenCalled();
|
||||
|
||||
const off = await useCase.execute('g1', ownerId, { autoPaymentReminders: false });
|
||||
expect(off.ok).toBe(true);
|
||||
expect(db.group.update).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
182
apps/backend/test/billing-subscribe.test.ts
Normal file
182
apps/backend/test/billing-subscribe.test.ts
Normal file
@@ -0,0 +1,182 @@
|
||||
import { beforeEach, describe, expect, it, mock } from 'bun:test';
|
||||
import { ok } from '@gruperly/shared';
|
||||
import { billingNotAvailableProblem } from '@/http/problem-builders';
|
||||
import { CancelSubscription } from '@/modules/billing/features/cancel/use-case';
|
||||
import { Subscribe } from '@/modules/billing/features/subscribe/use-case';
|
||||
import type { PreapprovalClient } from '@/modules/billing/lib';
|
||||
|
||||
const userId = 'user-1';
|
||||
const now = new Date('2026-10-22T12:00:00.000Z');
|
||||
const credentials = () => ok({ accessToken: 'platform-token', webhookSecret: 'secret' });
|
||||
|
||||
let calls: string[] = [];
|
||||
|
||||
function makeDb(existing: Record<string, unknown> | null, country: string | null = 'MX') {
|
||||
return {
|
||||
user: { findUnique: mock(async () => ({ id: userId, country })) },
|
||||
billingSubscription: {
|
||||
findUnique: mock(async () => existing),
|
||||
upsert: mock(async (args: { create: Record<string, unknown> }) => {
|
||||
calls.push('upsert');
|
||||
return { id: 'sub-1', paidThrough: existing?.paidThrough ?? null, ...args.create };
|
||||
}),
|
||||
update: mock(async () => {
|
||||
calls.push('update');
|
||||
return {};
|
||||
}),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function makeClient(): PreapprovalClient {
|
||||
return {
|
||||
createPreapproval: mock(async () => {
|
||||
calls.push('createPreapproval');
|
||||
return { id: 'pre-1', status: 'pending', externalReference: userId, initPoint: 'https://mp/checkout', nextPaymentDate: null };
|
||||
}),
|
||||
cancelPreapproval: mock(async () => {
|
||||
calls.push('cancelPreapproval');
|
||||
return { id: 'old', status: 'cancelled', externalReference: userId, initPoint: null, nextPaymentDate: null };
|
||||
}),
|
||||
getPreapproval: mock(),
|
||||
getAuthorizedPayment: mock(),
|
||||
searchAuthorizedPayments: mock(),
|
||||
} as unknown as PreapprovalClient;
|
||||
}
|
||||
|
||||
function subscribe(db: ReturnType<typeof makeDb>, client = makeClient()) {
|
||||
return {
|
||||
client,
|
||||
run: (returnTo: 'billing' | 'onboarding' = 'billing') =>
|
||||
new Subscribe({ db: db as never, client, credentials, webOrigin: 'http://web', now: () => now }).execute(
|
||||
userId,
|
||||
{ payerEmail: 'profe@mail.com', returnTo },
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
describe('Subscribe', () => {
|
||||
beforeEach(() => {
|
||||
calls = [];
|
||||
});
|
||||
|
||||
it('writes the PENDING row before asking Mercado Pago, in the country currency', async () => {
|
||||
const db = makeDb(null);
|
||||
const { client, run } = subscribe(db);
|
||||
|
||||
const result = await run();
|
||||
|
||||
expect(result).toEqual({ ok: true, value: { checkoutUrl: 'https://mp/checkout' } });
|
||||
expect(calls).toEqual(['upsert', 'createPreapproval', 'update']);
|
||||
expect(client.createPreapproval).toHaveBeenCalledWith('platform-token', {
|
||||
reason: 'Gruperly Pro',
|
||||
externalReference: userId,
|
||||
payerEmail: 'profe@mail.com',
|
||||
amount: 199,
|
||||
currencyId: 'MXN',
|
||||
backUrl: 'http://web/billing?sub=return',
|
||||
startDate: undefined,
|
||||
});
|
||||
expect(db.billingSubscription.update).toHaveBeenCalledWith({
|
||||
where: { id: 'sub-1' },
|
||||
data: { mpPreapprovalId: 'pre-1', lastSyncedAt: now },
|
||||
});
|
||||
});
|
||||
|
||||
it('sends the onboarding back to its own step', async () => {
|
||||
const { client, run } = subscribe(makeDb(null));
|
||||
await run('onboarding');
|
||||
|
||||
expect((client.createPreapproval as ReturnType<typeof mock>).mock.calls[0]?.[1]).toMatchObject({
|
||||
backUrl: 'http://web/onboarding?sub=return',
|
||||
});
|
||||
});
|
||||
|
||||
it('refuses a second subscription while one is authorized', async () => {
|
||||
const { client, run } = subscribe(makeDb({ status: 'AUTHORIZED', mpPreapprovalId: 'pre-0' }));
|
||||
|
||||
const result = await run();
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) expect(result.error).toMatchObject({ status: 409, code: 'subscription_already_active' });
|
||||
expect(client.createPreapproval).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('cancels an abandoned attempt before starting a new one', async () => {
|
||||
const { run } = subscribe(makeDb({ status: 'PENDING', mpPreapprovalId: 'old' }));
|
||||
|
||||
await run();
|
||||
|
||||
expect(calls).toEqual(['cancelPreapproval', 'upsert', 'createPreapproval', 'update']);
|
||||
});
|
||||
|
||||
it('delays the first charge to the end of a period already paid', async () => {
|
||||
const paidThrough = new Date('2026-11-10T00:00:00.000Z');
|
||||
const { client, run } = subscribe(makeDb({ status: 'CANCELLED', mpPreapprovalId: 'old', paidThrough }));
|
||||
|
||||
await run();
|
||||
|
||||
expect(client.cancelPreapproval).not.toHaveBeenCalled();
|
||||
expect((client.createPreapproval as ReturnType<typeof mock>).mock.calls[0]?.[1]).toMatchObject({
|
||||
startDate: paidThrough,
|
||||
});
|
||||
});
|
||||
|
||||
it('answers 503 when Gruperly has no account in that country', async () => {
|
||||
const db = makeDb(null, 'PE');
|
||||
const client = makeClient();
|
||||
const result = await new Subscribe({
|
||||
db: db as never,
|
||||
client,
|
||||
credentials: () => ({ ok: false, error: billingNotAvailableProblem() }),
|
||||
}).execute(userId, { payerEmail: 'profe@mail.com', returnTo: 'billing' });
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) expect(result.error).toMatchObject({ status: 503, code: 'billing_not_available' });
|
||||
expect(db.billingSubscription.upsert).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reports a Mercado Pago failure as 502 and keeps the row', async () => {
|
||||
const client = makeClient();
|
||||
client.createPreapproval = mock(async () => {
|
||||
throw new Error('down');
|
||||
}) as never;
|
||||
const db = makeDb(null);
|
||||
|
||||
const result = await subscribe(db, client).run();
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) expect(result.error.status).toBe(502);
|
||||
expect(db.billingSubscription.upsert).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('CancelSubscription', () => {
|
||||
it('cancels in Mercado Pago and keeps what was paid', async () => {
|
||||
const db = {
|
||||
billingSubscription: {
|
||||
findUnique: mock(async () => ({ id: 'sub-1', status: 'AUTHORIZED', mpPreapprovalId: 'pre-1', country: 'AR' })),
|
||||
update: mock(async () => ({})),
|
||||
},
|
||||
};
|
||||
const client = makeClient();
|
||||
|
||||
const result = await new CancelSubscription({ db: db as never, client, credentials }).execute(userId);
|
||||
|
||||
expect(result).toEqual({ ok: true, value: { status: 'CANCELLED' } });
|
||||
expect(client.cancelPreapproval).toHaveBeenCalledWith('platform-token', 'pre-1');
|
||||
expect(db.billingSubscription.update).toHaveBeenCalledWith({
|
||||
where: { id: 'sub-1' },
|
||||
data: { status: 'CANCELLED', nextPaymentDate: null },
|
||||
});
|
||||
});
|
||||
|
||||
it('has nothing to cancel without a live subscription', async () => {
|
||||
const db = { billingSubscription: { findUnique: mock(async () => null), update: mock() } };
|
||||
|
||||
const result = await new CancelSubscription({ db: db as never, client: makeClient(), credentials }).execute(userId);
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) expect(result.error.code).toBe('no_active_subscription');
|
||||
});
|
||||
});
|
||||
162
apps/backend/test/billing-sync.test.ts
Normal file
162
apps/backend/test/billing-sync.test.ts
Normal file
@@ -0,0 +1,162 @@
|
||||
import { describe, expect, it, mock } from 'bun:test';
|
||||
import { ok } from '@gruperly/shared';
|
||||
import type { MpAuthorizedPayment, PreapprovalClient } from '@/modules/billing/lib';
|
||||
import { SyncSubscription } from '@/modules/billing/lib/sync';
|
||||
|
||||
const userId = 'user-1';
|
||||
const now = new Date('2026-10-22T12:00:00.000Z');
|
||||
const credentials = () => ok({ accessToken: 'platform-token', webhookSecret: 'secret' });
|
||||
|
||||
function subscription(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: 'sub-1',
|
||||
userId,
|
||||
country: 'AR',
|
||||
currency: 'ARS',
|
||||
status: 'PENDING',
|
||||
mpPreapprovalId: 'pre-1',
|
||||
authorizedAt: null,
|
||||
paidThrough: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function invoice(overrides: Partial<MpAuthorizedPayment> = {}): MpAuthorizedPayment {
|
||||
return {
|
||||
id: 'inv-1',
|
||||
preapprovalId: 'pre-1',
|
||||
status: 'processed',
|
||||
paymentStatus: 'approved',
|
||||
amount: 15000,
|
||||
currencyId: 'ARS',
|
||||
debitDate: '2026-10-20T10:00:00.000Z',
|
||||
createdAt: '2026-10-20T09:00:00.000Z',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function makeDb(row: Record<string, unknown> | null) {
|
||||
return {
|
||||
billingSubscription: {
|
||||
findUnique: mock(async () => row),
|
||||
update: mock(async () => ({})),
|
||||
updateMany: mock(async () => ({ count: 0 })),
|
||||
},
|
||||
billingCharge: { upsert: mock(async () => ({})) },
|
||||
};
|
||||
}
|
||||
|
||||
function makeClient(params: { status?: string; externalReference?: string | null; invoices?: MpAuthorizedPayment[] }) {
|
||||
return {
|
||||
getPreapproval: mock(async (_token: string, id: string) => ({
|
||||
id,
|
||||
status: params.status ?? 'authorized',
|
||||
externalReference: params.externalReference === undefined ? userId : params.externalReference,
|
||||
initPoint: null,
|
||||
nextPaymentDate: '2026-11-20T10:00:00.000Z',
|
||||
})),
|
||||
searchAuthorizedPayments: mock(async () => params.invoices ?? []),
|
||||
createPreapproval: mock(),
|
||||
cancelPreapproval: mock(),
|
||||
getAuthorizedPayment: mock(),
|
||||
} as unknown as PreapprovalClient;
|
||||
}
|
||||
|
||||
function sync(db: ReturnType<typeof makeDb>, client: PreapprovalClient) {
|
||||
return new SyncSubscription({ db: db as never, client, credentials, now: () => now });
|
||||
}
|
||||
|
||||
describe('SyncSubscription', () => {
|
||||
it('marks the subscription authorized and extends paidThrough one month from the debit', async () => {
|
||||
const db = makeDb(subscription());
|
||||
|
||||
const result = await sync(db, makeClient({ invoices: [invoice()] })).execute('sub-1');
|
||||
|
||||
expect(result).toEqual({ ok: true, value: { synced: true, status: 'AUTHORIZED' } });
|
||||
expect(db.billingCharge.upsert).toHaveBeenCalledWith({
|
||||
where: { mpAuthorizedPaymentId: 'inv-1' },
|
||||
create: {
|
||||
subscriptionId: 'sub-1',
|
||||
mpAuthorizedPaymentId: 'inv-1',
|
||||
amount: 15000,
|
||||
currency: 'ARS',
|
||||
status: 'approved',
|
||||
paidAt: new Date('2026-10-20T10:00:00.000Z'),
|
||||
},
|
||||
update: { status: 'approved', paidAt: new Date('2026-10-20T10:00:00.000Z') },
|
||||
});
|
||||
expect(db.billingSubscription.update).toHaveBeenCalledWith({
|
||||
where: { id: 'sub-1' },
|
||||
data: {
|
||||
status: 'AUTHORIZED',
|
||||
authorizedAt: now,
|
||||
nextPaymentDate: new Date('2026-11-20T10:00:00.000Z'),
|
||||
paidThrough: new Date('2026-11-20T10:00:00.000Z'),
|
||||
lastSyncedAt: now,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('records a rejected charge without extending what was paid', async () => {
|
||||
const paidThrough = new Date('2026-10-25T00:00:00.000Z');
|
||||
const db = makeDb(subscription({ status: 'AUTHORIZED', authorizedAt: now, paidThrough }));
|
||||
|
||||
await sync(db, makeClient({ invoices: [invoice({ paymentStatus: 'rejected' })] })).execute('sub-1');
|
||||
|
||||
const data = (db.billingSubscription.update.mock.calls[0] as unknown as [{ data: Record<string, unknown> }])[0].data;
|
||||
expect(data.paidThrough).toEqual(paidThrough);
|
||||
expect(data.authorizedAt).toBeUndefined();
|
||||
});
|
||||
|
||||
it('never moves paidThrough back', async () => {
|
||||
const paidThrough = new Date('2027-01-01T00:00:00.000Z');
|
||||
const db = makeDb(subscription({ status: 'AUTHORIZED', paidThrough }));
|
||||
|
||||
await sync(db, makeClient({ invoices: [invoice()] })).execute('sub-1');
|
||||
|
||||
const data = (db.billingSubscription.update.mock.calls[0] as unknown as [{ data: Record<string, unknown> }])[0].data;
|
||||
expect(data.paidThrough).toEqual(paidThrough);
|
||||
});
|
||||
|
||||
it('mirrors a cancellation done in Mercado Pago', async () => {
|
||||
const db = makeDb(subscription({ status: 'AUTHORIZED' }));
|
||||
|
||||
const result = await sync(db, makeClient({ status: 'cancelled' })).execute('sub-1');
|
||||
|
||||
expect(result.ok && result.value.status).toBe('CANCELLED');
|
||||
});
|
||||
|
||||
it('ignores a preapproval whose external_reference is not this user', async () => {
|
||||
const db = makeDb(subscription());
|
||||
|
||||
const result = await sync(db, makeClient({ externalReference: 'someone-else' })).execute('sub-1');
|
||||
|
||||
expect(result).toEqual({ ok: true, value: { synced: false, status: 'PENDING' } });
|
||||
expect(db.billingSubscription.update).not.toHaveBeenCalled();
|
||||
expect(db.billingCharge.upsert).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('claims a preapproval that beat our own write of its id', async () => {
|
||||
const db = makeDb(null);
|
||||
let lookups = 0;
|
||||
db.billingSubscription.findUnique = mock(async () => (++lookups === 1 ? null : subscription())) as never;
|
||||
db.billingSubscription.updateMany = mock(async () => ({ count: 1 }));
|
||||
|
||||
const result = await sync(db, makeClient({})).byPreapprovalId('AR', 'pre-1');
|
||||
|
||||
expect(db.billingSubscription.updateMany).toHaveBeenCalledWith({
|
||||
where: { userId, country: 'AR', mpPreapprovalId: null },
|
||||
data: { mpPreapprovalId: 'pre-1' },
|
||||
});
|
||||
expect(result.ok && result.value.synced).toBe(true);
|
||||
});
|
||||
|
||||
it('does not claim a cancelled preapproval (a replaced attempt)', async () => {
|
||||
const db = makeDb(null);
|
||||
|
||||
const result = await sync(db, makeClient({ status: 'cancelled' })).byPreapprovalId('AR', 'old');
|
||||
|
||||
expect(result).toEqual({ ok: true, value: { synced: false, status: null } });
|
||||
expect(db.billingSubscription.updateMany).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
136
apps/backend/test/billing-webhook.test.ts
Normal file
136
apps/backend/test/billing-webhook.test.ts
Normal file
@@ -0,0 +1,136 @@
|
||||
import { describe, expect, it, mock } from 'bun:test';
|
||||
import { createHmac } from 'node:crypto';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { billingProviderErrorProblem } from '@/http/problem-builders';
|
||||
import { isPublicApiRequest } from '@/http/session-auth';
|
||||
import { HandleBillingWebhook } from '@/modules/billing/features/webhook/use-case';
|
||||
import type { PreapprovalClient } from '@/modules/billing/lib';
|
||||
import { verifyMpSignature } from '@/modules/billing/lib/webhook-signature';
|
||||
|
||||
const secret = 'webhook-secret';
|
||||
const credentials = () => ok({ accessToken: 'platform-token', webhookSecret: secret });
|
||||
|
||||
function sign(dataId: string, requestId: string, ts = '1729600000') {
|
||||
const v1 = createHmac('sha256', secret).update(`id:${dataId};request-id:${requestId};ts:${ts};`).digest('hex');
|
||||
return `ts=${ts},v1=${v1}`;
|
||||
}
|
||||
|
||||
function request(params: { type: string; dataId: string; requestId?: string; signature?: string }) {
|
||||
const requestId = params.requestId ?? 'req-1';
|
||||
return {
|
||||
country: 'ar',
|
||||
rawBody: JSON.stringify({ type: params.type, data: { id: params.dataId } }),
|
||||
headers: new Headers({
|
||||
'x-request-id': requestId,
|
||||
'x-signature': params.signature ?? sign(params.dataId, requestId),
|
||||
}),
|
||||
query: new URLSearchParams({ 'data.id': params.dataId, type: params.type }),
|
||||
};
|
||||
}
|
||||
|
||||
function makeDeps(syncResult = ok({ synced: true, status: 'AUTHORIZED' as const })) {
|
||||
const db = {
|
||||
billingWebhookEvent: {
|
||||
create: mock(async () => ({})),
|
||||
delete: mock(async () => ({})),
|
||||
},
|
||||
};
|
||||
const sync = { byPreapprovalId: mock(async () => syncResult) };
|
||||
const client = {
|
||||
getAuthorizedPayment: mock(async () => ({ id: 'inv-1', preapprovalId: 'pre-9' })),
|
||||
} as unknown as PreapprovalClient;
|
||||
return { db, sync, client };
|
||||
}
|
||||
|
||||
function handler(deps: ReturnType<typeof makeDeps>) {
|
||||
return new HandleBillingWebhook({
|
||||
db: deps.db as never,
|
||||
sync: deps.sync as never,
|
||||
client: deps.client,
|
||||
credentials,
|
||||
});
|
||||
}
|
||||
|
||||
describe('verifyMpSignature', () => {
|
||||
it('accepts Mercado Pago signatures and lower-cases alphanumeric ids', () => {
|
||||
const signature = sign('abc123', 'req-1');
|
||||
expect(verifyMpSignature({ signature, requestId: 'req-1', dataId: 'ABC123', secret })).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects a tampered or missing signature', () => {
|
||||
expect(verifyMpSignature({ signature: sign('1', 'req-1'), requestId: 'req-1', dataId: '2', secret })).toBe(false);
|
||||
expect(verifyMpSignature({ signature: 'ts=1,v1=short', requestId: 'req-1', dataId: '1', secret })).toBe(false);
|
||||
expect(verifyMpSignature({ signature: null, requestId: 'req-1', dataId: '1', secret })).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('HandleBillingWebhook', () => {
|
||||
it('rejects a bad signature before touching anything', async () => {
|
||||
const deps = makeDeps();
|
||||
|
||||
const result = await handler(deps).execute(
|
||||
request({ type: 'subscription_preapproval', dataId: 'pre-1', signature: 'ts=1,v1=deadbeef' }),
|
||||
);
|
||||
|
||||
expect(result).toEqual(err('invalid_signature'));
|
||||
expect(deps.db.billingWebhookEvent.create).not.toHaveBeenCalled();
|
||||
expect(deps.sync.byPreapprovalId).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('re-fetches the preapproval instead of trusting the body', async () => {
|
||||
const deps = makeDeps();
|
||||
|
||||
const result = await handler(deps).execute(request({ type: 'subscription_preapproval', dataId: 'pre-1' }));
|
||||
|
||||
expect(result).toEqual(ok({ duplicate: false, applied: true }));
|
||||
expect(deps.sync.byPreapprovalId).toHaveBeenCalledWith('AR', 'pre-1');
|
||||
expect(deps.db.billingWebhookEvent.create).toHaveBeenCalledWith({ data: { country: 'AR', dedupeKey: 'req-1' } });
|
||||
});
|
||||
|
||||
it('resolves an invoice notification to its subscription', async () => {
|
||||
const deps = makeDeps();
|
||||
|
||||
await handler(deps).execute(request({ type: 'subscription_authorized_payment', dataId: 'inv-1' }));
|
||||
|
||||
expect(deps.client.getAuthorizedPayment).toHaveBeenCalledWith('platform-token', 'inv-1');
|
||||
expect(deps.sync.byPreapprovalId).toHaveBeenCalledWith('AR', 'pre-9');
|
||||
});
|
||||
|
||||
it('answers a repeated delivery as a duplicate', async () => {
|
||||
const deps = makeDeps();
|
||||
deps.db.billingWebhookEvent.create = mock(async () => {
|
||||
throw Object.assign(new Error('unique'), { code: 'P2002' });
|
||||
});
|
||||
|
||||
const result = await handler(deps).execute(request({ type: 'subscription_preapproval', dataId: 'pre-1' }));
|
||||
|
||||
expect(result).toEqual(ok({ duplicate: true, applied: false }));
|
||||
expect(deps.sync.byPreapprovalId).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('un-burns the dedupe key when syncing fails, so the retry gets in', async () => {
|
||||
const deps = makeDeps(err(billingProviderErrorProblem()) as never);
|
||||
|
||||
const result = await handler(deps).execute(request({ type: 'subscription_preapproval', dataId: 'pre-1' }));
|
||||
|
||||
expect(result).toEqual(err('sync_failed'));
|
||||
expect(deps.db.billingWebhookEvent.delete).toHaveBeenCalledWith({
|
||||
where: { country_dedupeKey: { country: 'AR', dedupeKey: 'req-1' } },
|
||||
});
|
||||
});
|
||||
|
||||
it('acknowledges topics it does not handle', async () => {
|
||||
const deps = makeDeps();
|
||||
|
||||
const result = await handler(deps).execute(request({ type: 'payment', dataId: '123' }));
|
||||
|
||||
expect(result).toEqual(ok({ duplicate: false, applied: false }));
|
||||
expect(deps.sync.byPreapprovalId).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('is reachable without a session, and only that path', () => {
|
||||
expect(isPublicApiRequest('POST', '/api/v1/billing/webhooks/mp/ar')).toBe(true);
|
||||
expect(isPublicApiRequest('GET', '/api/v1/billing/webhooks/mp/ar')).toBe(false);
|
||||
expect(isPublicApiRequest('POST', '/api/v1/billing/subscribe')).toBe(false);
|
||||
});
|
||||
});
|
||||
116
apps/backend/test/onboarding-select-plan.test.ts
Normal file
116
apps/backend/test/onboarding-select-plan.test.ts
Normal file
@@ -0,0 +1,116 @@
|
||||
import { describe, expect, it, mock } from 'bun:test';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { noActiveSubscriptionProblem } from '@/http/problem-builders';
|
||||
import { SelectPlan } from '@/modules/onboarding/features/select-plan/use-case';
|
||||
|
||||
const userId = 'user-1';
|
||||
const now = new Date('2026-10-22T12:00:00.000Z');
|
||||
|
||||
function makeDb(subscription: Record<string, unknown> | null, user: Record<string, unknown> = {}) {
|
||||
return {
|
||||
user: {
|
||||
findUnique: mock(async () => ({ id: userId, onboardingCompleted: false, ...user })),
|
||||
update: mock(async () => ({})),
|
||||
},
|
||||
billingSubscription: {
|
||||
findUnique: mock(async () => subscription),
|
||||
update: mock(async () => ({})),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function makeDeps(db: ReturnType<typeof makeDb>) {
|
||||
return {
|
||||
db: db as never,
|
||||
subscribe: { execute: mock(async () => ok({ checkoutUrl: 'https://mp/checkout' })) },
|
||||
cancel: { execute: mock(async () => ok({ status: 'CANCELLED' as const })) },
|
||||
now: () => now,
|
||||
};
|
||||
}
|
||||
|
||||
describe('SelectPlan (onboarding)', () => {
|
||||
it('stores the country first and marks Free as chosen', async () => {
|
||||
const db = makeDb(null);
|
||||
const deps = makeDeps(db);
|
||||
|
||||
const result = await new SelectPlan(deps).execute(userId, { plan: 'FREE', country: 'CL' });
|
||||
|
||||
expect(result).toEqual(ok({ plan: 'FREE', checkoutUrl: null }));
|
||||
expect(db.user.update).toHaveBeenNthCalledWith(1, { where: { id: userId }, data: { country: 'CL' } });
|
||||
expect(db.user.update).toHaveBeenNthCalledWith(2, { where: { id: userId }, data: { planSelectedAt: now } });
|
||||
expect(deps.subscribe.execute).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('voids an abandoned Pro attempt when switching to Free', async () => {
|
||||
const db = makeDb({ id: 'sub-1', status: 'PENDING', mpPreapprovalId: 'pre-1' });
|
||||
const deps = makeDeps(db);
|
||||
|
||||
await new SelectPlan(deps).execute(userId, { plan: 'FREE', country: 'AR' });
|
||||
|
||||
expect(deps.cancel.execute).toHaveBeenCalledWith(userId);
|
||||
});
|
||||
|
||||
it('voids it locally when Mercado Pago never got the attempt', async () => {
|
||||
const db = makeDb({ id: 'sub-1', status: 'PENDING', mpPreapprovalId: null });
|
||||
const deps = makeDeps(db);
|
||||
deps.cancel.execute = mock(async () => err(noActiveSubscriptionProblem())) as never;
|
||||
|
||||
await new SelectPlan(deps).execute(userId, { plan: 'FREE', country: 'AR' });
|
||||
|
||||
expect(db.billingSubscription.update).toHaveBeenCalledWith({
|
||||
where: { id: 'sub-1' },
|
||||
data: { status: 'CANCELLED', nextPaymentDate: null },
|
||||
});
|
||||
});
|
||||
|
||||
it('starts the subscription for Pro and comes back to the onboarding', async () => {
|
||||
const db = makeDb(null);
|
||||
const deps = makeDeps(db);
|
||||
|
||||
const result = await new SelectPlan(deps).execute(userId, {
|
||||
plan: 'PRO',
|
||||
country: 'AR',
|
||||
payerEmail: 'profe@mail.com',
|
||||
});
|
||||
|
||||
expect(result).toEqual(ok({ plan: 'PRO', checkoutUrl: 'https://mp/checkout' }));
|
||||
expect(deps.subscribe.execute).toHaveBeenCalledWith(userId, {
|
||||
payerEmail: 'profe@mail.com',
|
||||
returnTo: 'onboarding',
|
||||
});
|
||||
expect(db.user.update).toHaveBeenLastCalledWith({ where: { id: userId }, data: { planSelectedAt: now } });
|
||||
});
|
||||
|
||||
it('does not mark a plan when the subscription could not start', async () => {
|
||||
const db = makeDb(null);
|
||||
const deps = makeDeps(db);
|
||||
deps.subscribe.execute = mock(async () => err({ title: 'x', status: 503, code: 'billing_not_available' })) as never;
|
||||
|
||||
const result = await new SelectPlan(deps).execute(userId, {
|
||||
plan: 'PRO',
|
||||
country: 'PE',
|
||||
payerEmail: 'profe@mail.com',
|
||||
});
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
expect(db.user.update).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('never drops an authorized subscription from the onboarding', async () => {
|
||||
const db = makeDb({ id: 'sub-1', status: 'AUTHORIZED' });
|
||||
|
||||
const result = await new SelectPlan(makeDeps(db)).execute(userId, { plan: 'FREE', country: 'AR' });
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) expect(result.error.code).toBe('subscription_already_active');
|
||||
});
|
||||
|
||||
it('refuses once the onboarding is completed', async () => {
|
||||
const db = makeDb(null, { onboardingCompleted: true });
|
||||
|
||||
const result = await new SelectPlan(makeDeps(db)).execute(userId, { plan: 'FREE', country: 'AR' });
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) expect(result.error.code).toBe('onboarding_already_completed');
|
||||
});
|
||||
});
|
||||
@@ -12,6 +12,9 @@ const db = {
|
||||
whatsappAccount: {
|
||||
findUnique: mock(async () => null),
|
||||
},
|
||||
billingSubscription: {
|
||||
findUnique: mock(async () => null),
|
||||
},
|
||||
group: {
|
||||
create: mock(),
|
||||
},
|
||||
@@ -72,6 +75,9 @@ const firstGroupPayload = {
|
||||
country: 'AR',
|
||||
};
|
||||
|
||||
const noPlan = { planSelected: false, selectedPlan: null, subscriptionStatus: null, country: null };
|
||||
const planSelectedAt = new Date('2026-08-01T09:00:00.000Z');
|
||||
|
||||
describe('onboarding routes', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
@@ -90,6 +96,7 @@ describe('onboarding routes', () => {
|
||||
paymentConnected: false,
|
||||
whatsappConnected: false,
|
||||
completed: false,
|
||||
...noPlan,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -105,6 +112,7 @@ describe('onboarding routes', () => {
|
||||
paymentConnected: true,
|
||||
whatsappConnected: false,
|
||||
completed: false,
|
||||
...noPlan,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -124,6 +132,7 @@ describe('onboarding routes', () => {
|
||||
paymentConnected: false,
|
||||
whatsappConnected: false,
|
||||
completed: false,
|
||||
...noPlan,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -138,6 +147,27 @@ describe('onboarding routes', () => {
|
||||
paymentConnected: true,
|
||||
whatsappConnected: false,
|
||||
completed: true,
|
||||
...noPlan,
|
||||
});
|
||||
});
|
||||
|
||||
it('reports a chosen Pro plan while its subscription is still pending', async () => {
|
||||
prisma.user.findUnique.mockResolvedValue({
|
||||
id: userId,
|
||||
onboardingCompleted: false,
|
||||
planSelectedAt,
|
||||
country: 'MX',
|
||||
});
|
||||
prisma.mpAccount.findUnique.mockResolvedValue(null);
|
||||
prisma.billingSubscription.findUnique.mockResolvedValueOnce({ status: 'PENDING' });
|
||||
|
||||
const res = await makeApp({ id: userId }).request('/onboarding/status');
|
||||
|
||||
expect(await res.json()).toMatchObject({
|
||||
planSelected: true,
|
||||
selectedPlan: 'PRO',
|
||||
subscriptionStatus: 'PENDING',
|
||||
country: 'MX',
|
||||
});
|
||||
});
|
||||
|
||||
@@ -151,7 +181,7 @@ describe('onboarding routes', () => {
|
||||
|
||||
describe('POST /onboarding/first-group', () => {
|
||||
it('creates the first group and completes onboarding', async () => {
|
||||
prisma.user.findUnique.mockResolvedValue({ id: userId, onboardingCompleted: false });
|
||||
prisma.user.findUnique.mockResolvedValue({ id: userId, onboardingCompleted: false, planSelectedAt });
|
||||
prisma.group.create.mockResolvedValue(group);
|
||||
|
||||
const res = await makeApp({ id: userId }).request('/onboarding/first-group', {
|
||||
@@ -202,7 +232,7 @@ describe('onboarding routes', () => {
|
||||
});
|
||||
|
||||
it('creates the group without Mercado Pago linked, since that step is skippable', async () => {
|
||||
prisma.user.findUnique.mockResolvedValue({ id: userId, onboardingCompleted: false });
|
||||
prisma.user.findUnique.mockResolvedValue({ id: userId, onboardingCompleted: false, planSelectedAt });
|
||||
prisma.mpAccount.findUnique.mockResolvedValue(null);
|
||||
prisma.group.create.mockResolvedValue(group);
|
||||
|
||||
@@ -216,6 +246,20 @@ describe('onboarding routes', () => {
|
||||
expect(prisma.group.create).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects until a plan was chosen, since the Plan step is mandatory', async () => {
|
||||
prisma.user.findUnique.mockResolvedValue({ id: userId, onboardingCompleted: false, planSelectedAt: null });
|
||||
|
||||
const res = await makeApp({ id: userId }).request('/onboarding/first-group', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(firstGroupPayload),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
|
||||
expect(res.status).toBe(409);
|
||||
expect(await res.json()).toMatchObject({ code: 'plan_not_selected' });
|
||||
expect(prisma.group.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects when onboarding is already completed', async () => {
|
||||
prisma.user.findUnique.mockResolvedValue({ id: userId, onboardingCompleted: true });
|
||||
|
||||
|
||||
Reference in New Issue
Block a user