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:
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