feat(billing): configurable plans from the backoffice and MP payment notifications

Plans:
- Plan limits and Pro prices per country live in the database
  (plan_configs, plan_prices, seeded with the previous constants) and are
  read through PlanCatalog (30 s cache, defaults as fallback).
- /admin/plans edits limits (with the count of accounts that would become
  read-only) and prices, optionally pushing the new price to live
  subscriptions from their next charge (MP preapproval amount, Stripe item
  without proration) via the ApplyPriceChanges job, with an email and a
  notice on /billing.
- GET /billing/plans feeds the onboarding and the billing screen.

Mercado Pago:
- The Pro checkout returns through GET /billing/return on API_PUBLIC_URL,
  since MP refuses a back_url on localhost.
- The OAuth callback bounces from the tunnel to BETTER_AUTH_URL to find the
  session, requires the session to own the state, and redirects instead of
  answering JSON on unexpected errors.
- Checkout Pro links skip auto_return off public HTTPS and carry a
  notification_url to POST /payments/webhooks/mp/:paymentId, which confirms
  the payment with the owner's token (same rule as the polling job, which
  stays as fallback). The search now prefers the approved attempt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Jose Selesan
2026-11-11 07:50:14 -03:00
parent abb18f1815
commit aac142d324
90 changed files with 2642 additions and 104 deletions

View File

@@ -114,6 +114,25 @@ describe('admin access', () => {
expect(db.user.findUnique).not.toHaveBeenCalled();
});
it('forbids the plans to anyone outside the allowlist', async () => {
const app = makeApp('profe@gmail.com');
expect((await app.request('/admin/plans')).status).toBe(403);
expect((await app.request('/admin/plans/FREE/impact?maxGroups=1')).status).toBe(403);
const json = { 'Content-Type': 'application/json' };
const limits = await app.request('/admin/plans/FREE/limits', {
method: 'PUT',
headers: json,
body: JSON.stringify({ maxGroups: 1, maxAttendees: 1, whatsappAutomations: false, mpCharges: false }),
});
expect(limits.status).toBe(403);
const price = await app.request('/admin/plans/prices/AR', {
method: 'PUT',
headers: json,
body: JSON.stringify({ amount: 1, applyToExisting: true }),
});
expect(price.status).toBe(403);
});
it('asks for a session without a user', async () => {
const response = await makeApp(null).request('/admin/accounts');
expect(response.status).toBe(401);

View File

@@ -1,4 +1,5 @@
import { describe, expect, it, mock } from 'bun:test';
import { staticPlanCatalog } from '@/modules/billing/lib/catalog';
import { PlanGuard, resolvePlan } from '@/modules/billing/lib/entitlements';
const now = new Date('2026-10-22T12:00:00.000Z');
@@ -18,7 +19,7 @@ function makeDb(params: {
}
function makeGuard(db: ReturnType<typeof makeDb>, enforced = true) {
return new PlanGuard({ db: db as never, enforced, graceDays: 7, now: () => now });
return new PlanGuard({ db: db as never, enforced, graceDays: 7, now: () => now, catalog: staticPlanCatalog() });
}
describe('resolvePlan', () => {

View File

@@ -0,0 +1,266 @@
import { describe, expect, it, mock } from 'bun:test';
import { PLAN_LIMITS, PRO_PRICE_BY_COUNTRY } from '@gruperly/shared';
import { UpdatePlanPrice } from '@/modules/admin/features/update-plan-price/use-case';
import { ApplyPriceChanges } from '@/modules/billing/jobs/apply-price-changes';
import { defaultPlanCatalog, PlanCatalog, PlanGuard, staticPlanCatalog } from '@/modules/billing/lib';
import { MercadoPagoBillingProvider } from '@/modules/billing/providers/mercado-pago';
import { StripeBillingProvider } from '@/modules/billing/providers/stripe';
const decimal = (value: number) => ({ toString: () => String(value) });
function catalogDb(configs: unknown[] = [], prices: unknown[] = []) {
return {
planConfig: { findMany: mock(async () => configs) },
planPrice: { findMany: mock(async () => prices) },
};
}
describe('PlanCatalog', () => {
it('falls back to the shared defaults when the tables are empty', async () => {
const catalog = new PlanCatalog({ db: catalogDb() as never });
expect(await catalog.getLimits('FREE')).toEqual(PLAN_LIMITS.FREE);
expect(await catalog.getProPrice('AR')).toBe(PRO_PRICE_BY_COUNTRY.AR);
});
it('reads the limits and prices edited from the backoffice', async () => {
const db = catalogDb(
[{ plan: 'FREE', maxGroups: 2, maxAttendees: 30, whatsappAutomations: true, mpCharges: false }],
[{ country: 'AR', amount: decimal(18000) }, { country: 'XX', amount: decimal(1) }],
);
const catalog = new PlanCatalog({ db: db as never });
expect(await catalog.getLimits('FREE')).toEqual({
maxGroups: 2,
maxAttendees: 30,
whatsappAutomations: true,
mpCharges: false,
});
expect(await catalog.getLimits('PRO')).toEqual(PLAN_LIMITS.PRO);
expect(await catalog.getProPrice('AR')).toBe(18000);
expect(await catalog.getProPrice('MX')).toBe(PRO_PRICE_BY_COUNTRY.MX);
});
it('caches within the TTL until invalidated', async () => {
let clock = 0;
const db = catalogDb();
const catalog = new PlanCatalog({ db: db as never, ttlMs: 1000, now: () => clock });
await catalog.snapshot();
clock = 500;
await catalog.snapshot();
expect(db.planConfig.findMany).toHaveBeenCalledTimes(1);
catalog.invalidate();
await catalog.snapshot();
expect(db.planConfig.findMany).toHaveBeenCalledTimes(2);
clock = 2000;
await catalog.snapshot();
expect(db.planConfig.findMany).toHaveBeenCalledTimes(3);
});
it('keeps working on the defaults if the database fails, without caching them', async () => {
const db = {
planConfig: { findMany: mock(async () => Promise.reject(new Error('down'))) },
planPrice: { findMany: mock(async () => []) },
};
const catalog = new PlanCatalog({ db: db as never });
expect(await catalog.getLimits('FREE')).toEqual(PLAN_LIMITS.FREE);
await catalog.snapshot();
expect(db.planConfig.findMany).toHaveBeenCalledTimes(2);
});
it('feeds the PlanGuard', async () => {
const snapshot = defaultPlanCatalog();
snapshot.limits.FREE = { ...snapshot.limits.FREE, maxGroups: 3 };
const guard = new PlanGuard({
enforced: true,
catalog: staticPlanCatalog(snapshot),
db: {
billingSubscription: { findUnique: async () => null },
group: { count: async () => 2 },
person: { count: async () => 0 },
} as never,
});
expect((await guard.canCreateGroup('owner-1')).ok).toBe(true);
});
});
function priceTx(updated = 3) {
const tx = {
planPrice: { upsert: mock(async () => ({})) },
planPriceChange: { create: mock(async () => ({ id: 'change-1' })), update: mock(async () => ({})) },
billingSubscription: { updateMany: mock(async () => ({ count: updated })) },
};
const db = { $transaction: mock(async (run: (client: typeof tx) => unknown) => run(tx)) };
return { tx, db };
}
describe('UpdatePlanPrice', () => {
const catalog = { invalidate: mock(), getProPrice: mock(async () => 15000) };
it('queues the live subscriptions of the country and kicks the job', async () => {
const { tx, db } = priceTx(3);
const applyQueued = mock(async () => {});
const result = await new UpdatePlanPrice({ db: db as never, catalog, applyQueued }).execute(
'AR',
{ amount: 18000, applyToExisting: true },
'staff-1',
);
expect(result).toEqual({ ok: true, value: { country: 'AR', amount: 18000, queued: 3 } });
expect(tx.planPrice.upsert).toHaveBeenCalled();
expect(tx.planPriceChange.create.mock.calls[0]?.[0]).toMatchObject({
data: { country: 'AR', previousAmount: 15000, newAmount: 18000, currency: 'ARS', applyToExisting: true },
});
expect(tx.billingSubscription.updateMany.mock.calls[0]?.[0]).toMatchObject({
where: {
country: 'AR',
status: { in: ['AUTHORIZED', 'PAUSED'] },
externalId: { not: null },
},
});
expect(tx.planPriceChange.update).toHaveBeenCalledWith({ where: { id: 'change-1' }, data: { queued: 3 } });
expect(catalog.invalidate).toHaveBeenCalled();
expect(applyQueued).toHaveBeenCalledTimes(1);
});
it('only changes the price for new subscriptions when not applied to existing ones', async () => {
const { tx, db } = priceTx();
const applyQueued = mock(async () => {});
const result = await new UpdatePlanPrice({ db: db as never, catalog, applyQueued }).execute(
'AR',
{ amount: 18000, applyToExisting: false },
'staff-1',
);
expect(result.ok && result.value.queued).toBe(0);
expect(tx.billingSubscription.updateMany).not.toHaveBeenCalled();
expect(applyQueued).not.toHaveBeenCalled();
});
});
function row(overrides: Record<string, unknown> = {}) {
return {
id: 'sub-1',
country: 'AR',
currency: 'ARS',
provider: 'MERCADO_PAGO',
status: 'AUTHORIZED',
externalId: 'pre-1',
checkoutRef: null,
amount: decimal(15000),
pendingAmount: decimal(18000),
nextPaymentDate: new Date('2026-12-05T12:00:00.000Z'),
user: { name: 'Ana', email: 'ana@gruperly.test', country: 'AR' },
...overrides,
};
}
function applyHarness(rows: unknown[], { fail = false, moved = 1 } = {}) {
const db = {
billingSubscription: {
findMany: mock(async () => rows),
updateMany: mock(async () => ({ count: moved })),
},
};
const provider = {
updateAmount: mock(async () => {
if (fail) throw new Error('boom');
}),
};
const email = { sendProPriceChanged: mock(async () => {}) };
const job = new ApplyPriceChanges({
db: db as never,
providers: () => provider as never,
email,
webOrigin: 'http://web',
});
return { db, provider, email, job };
}
describe('ApplyPriceChanges', () => {
it('pushes the price to the provider, moves it to amount and emails the professor', async () => {
const pending = row();
const { db, provider, email, job } = applyHarness([pending]);
expect(await job.execute()).toEqual({ applied: 1, failed: 0, dropped: 0 });
expect(provider.updateAmount).toHaveBeenCalledWith(
{ country: 'AR', externalId: 'pre-1', checkoutRef: null },
18000,
'ARS',
);
expect(db.billingSubscription.updateMany).toHaveBeenCalledWith({
where: { id: 'sub-1', pendingAmount: pending.pendingAmount },
data: { amount: pending.pendingAmount, pendingAmount: null, priceChangeAttempts: 0, priceChangeError: null },
});
expect(email.sendProPriceChanged).toHaveBeenCalledTimes(1);
const sent = (email.sendProPriceChanged.mock.calls[0] as unknown[])[0] as Record<string, string>;
expect(sent).toMatchObject({ email: 'ana@gruperly.test', name: 'Ana', billingUrl: 'http://web/billing' });
expect(sent.amount).toContain('18.000');
});
it('counts a refusal as an attempt and keeps the change queued', async () => {
const { db, email, job } = applyHarness([row()], { fail: true });
expect(await job.execute()).toEqual({ applied: 0, failed: 1, dropped: 0 });
expect(db.billingSubscription.updateMany.mock.calls[0]?.[0]).toMatchObject({
data: { priceChangeAttempts: { increment: 1 }, priceChangeError: 'provider_error' },
});
expect(email.sendProPriceChanged).not.toHaveBeenCalled();
});
it('drops the change of a subscription cancelled meanwhile', async () => {
const { provider, job } = applyHarness([row({ status: 'CANCELLED' })]);
expect(await job.execute()).toEqual({ applied: 0, failed: 0, dropped: 1 });
expect(provider.updateAmount).not.toHaveBeenCalled();
});
it('does not email twice when another instance already applied it', async () => {
const { email, job } = applyHarness([row()], { moved: 0 });
expect(await job.execute()).toEqual({ applied: 0, failed: 0, dropped: 0 });
expect(email.sendProPriceChanged).not.toHaveBeenCalled();
});
});
describe('updateAmount', () => {
it('Mercado Pago changes the preapproval amount', async () => {
const client = { updatePreapprovalAmount: mock(async () => ({})) };
const provider = new MercadoPagoBillingProvider({
client: client as never,
credentials: () => ({ accessToken: 'platform-token', webhookSecret: 'secret' }),
});
await provider.updateAmount({ country: 'AR', externalId: 'pre-1', checkoutRef: null }, 18000, 'ARS');
expect(client.updatePreapprovalAmount).toHaveBeenCalledWith('platform-token', 'pre-1', {
amount: 18000,
currencyId: 'ARS',
});
});
it('Stripe reprices the item on its product without proration', async () => {
const calls: { method: string; path: string; body: URLSearchParams | null }[] = [];
const fetch = mock(async (input: string, init: RequestInit) => {
const method = init.method ?? 'GET';
calls.push({
method,
path: new URL(input).pathname,
body: init.body ? new URLSearchParams(String(init.body)) : null,
});
return new Response(
JSON.stringify({ id: 'sub_1', items: { data: [{ id: 'si_1', price: { product: 'prod_1' } }] } }),
);
});
const provider = new StripeBillingProvider({
config: () => ({ secretKey: 'sk_test', webhookSecret: 'whsec' }),
fetch: fetch as never,
});
await provider.updateAmount({ country: 'MX', externalId: 'sub_1', checkoutRef: null }, 249, 'MXN');
expect(calls.map((call) => `${call.method} ${call.path}`)).toEqual([
'GET /v1/subscriptions/sub_1',
'POST /v1/subscriptions/sub_1',
]);
const body = calls[1]?.body;
expect(body?.get('proration_behavior')).toBe('none');
expect(body?.get('items[0][id]')).toBe('si_1');
expect(body?.get('items[0][price_data][product]')).toBe('prod_1');
expect(body?.get('items[0][price_data][unit_amount]')).toBe('24900');
expect(body?.get('items[0][price_data][currency]')).toBe('mxn');
expect(body?.get('items[0][price_data][recurring][interval]')).toBe('month');
});
});

View File

@@ -0,0 +1,55 @@
import { afterEach, describe, expect, it } from 'bun:test';
import { Hono } from 'hono';
import { isPublicApiRequest } from '@/http/session-auth';
import returnRoute from '@/modules/billing/features/return/route';
import { getApiPublicOrigin } from '@/modules/billing/lib';
const previousWebUrl = process.env.WEB_URL;
function makeApp() {
return new Hono().basePath('/api/v1').route('/billing', returnRoute);
}
describe('GET /billing/return', () => {
afterEach(() => {
process.env.WEB_URL = previousWebUrl;
});
it('bounces the browser to the billing screen of the web', async () => {
process.env.WEB_URL = 'https://app.example.com';
const res = await makeApp().request('/api/v1/billing/return?to=billing&preapproval_id=pre-1');
expect(res.status).toBe(302);
expect(res.headers.get('location')).toBe('https://app.example.com/billing?sub=return');
});
it('goes back to the onboarding step when it started there', async () => {
process.env.WEB_URL = 'https://app.example.com';
const res = await makeApp().request('/api/v1/billing/return?to=onboarding');
expect(res.headers.get('location')).toBe('https://app.example.com/onboarding?sub=return');
});
it('never redirects anywhere but the web', async () => {
process.env.WEB_URL = 'https://app.example.com';
const res = await makeApp().request('/api/v1/billing/return?to=https://evil.example');
expect(res.headers.get('location')).toBe('https://app.example.com/billing?sub=return');
});
it('is reachable without a session', () => {
expect(isPublicApiRequest('GET', '/api/v1/billing/return')).toBe(true);
expect(isPublicApiRequest('POST', '/api/v1/billing/return')).toBe(false);
});
});
describe('getApiPublicOrigin', () => {
it('prefers API_PUBLIC_URL, then BETTER_AUTH_URL, then localhost', () => {
expect(
getApiPublicOrigin({ API_PUBLIC_URL: 'https://x.ngrok-free.app/', BETTER_AUTH_URL: 'http://localhost:4000' }),
).toBe('https://x.ngrok-free.app');
expect(getApiPublicOrigin({ BETTER_AUTH_URL: 'https://app.example.com' })).toBe('https://app.example.com');
expect(getApiPublicOrigin({})).toBe('http://localhost:4000');
expect(getApiPublicOrigin({ API_PUBLIC_URL: 'not a url' })).toBe('http://localhost:4000');
});
});

View File

@@ -1,6 +1,7 @@
import { beforeEach, describe, expect, it, mock } from 'bun:test';
import { CancelSubscription } from '@/modules/billing/features/cancel/use-case';
import { Subscribe } from '@/modules/billing/features/subscribe/use-case';
import { staticPlanCatalog } from '@/modules/billing/lib/catalog';
import type { BillingProvider } from '@/modules/billing/providers';
import { MercadoPagoBillingProvider, type PreapprovalClient } from '@/modules/billing/providers/mercado-pago';
@@ -53,7 +54,7 @@ function subscribe(db: ReturnType<typeof makeDb>, client = makeClient()) {
return {
client,
run: (returnTo: 'billing' | 'onboarding' = 'billing') =>
new Subscribe({ db: db as never, providers: () => provider, webOrigin: 'http://web', now: () => now }).execute(
new Subscribe({ catalog: staticPlanCatalog(), db: db as never, providers: () => provider, apiOrigin: 'https://api', now: () => now }).execute(
userId,
{ payerEmail: 'profe@mail.com', returnTo },
),
@@ -79,7 +80,7 @@ describe('Subscribe', () => {
payerEmail: 'profe@mail.com',
amount: 15000,
currencyId: 'ARS',
backUrl: 'http://web/billing?sub=return',
backUrl: 'https://api/api/v1/billing/return?to=billing',
startDate: undefined,
});
expect(db.billingSubscription.update).toHaveBeenCalledWith({
@@ -93,7 +94,7 @@ describe('Subscribe', () => {
await run('onboarding');
expect((client.createPreapproval as ReturnType<typeof mock>).mock.calls[0]?.[1]).toMatchObject({
backUrl: 'http://web/onboarding?sub=return',
backUrl: 'https://api/api/v1/billing/return?to=onboarding',
});
});
@@ -131,7 +132,7 @@ describe('Subscribe', () => {
const db = makeDb(null, 'AR');
const client = makeClient();
const provider = new MercadoPagoBillingProvider({ client, credentials: () => null });
const result = await new Subscribe({ db: db as never, providers: () => provider }).execute(userId, {
const result = await new Subscribe({ catalog: staticPlanCatalog(), db: db as never, providers: () => provider }).execute(userId, {
payerEmail: 'profe@mail.com',
returnTo: 'billing',
});
@@ -224,13 +225,13 @@ describe('Subscribe outside Argentina (Stripe)', () => {
const stripe = fakeStripe();
const resolved: string[] = [];
const result = await new Subscribe({
const result = await new Subscribe({ catalog: staticPlanCatalog(),
db: db as never,
providers: (id) => {
resolved.push(id);
return stripe;
},
webOrigin: 'http://web',
apiOrigin: 'https://api',
now: () => now,
}).execute(userId, { returnTo: 'billing' });
@@ -242,7 +243,7 @@ describe('Subscribe outside Argentina (Stripe)', () => {
amount: 199,
currency: 'MXN',
payerEmail: null,
backUrl: 'http://web/billing?sub=return',
backUrl: 'https://api/api/v1/billing/return?to=billing',
startDate: undefined,
});
expect((db.billingSubscription.upsert.mock.calls[0] as unknown as [{ create: Record<string, unknown> }])[0].create).toMatchObject({
@@ -261,10 +262,10 @@ describe('Subscribe outside Argentina (Stripe)', () => {
const mp = mpProvider(client);
const stripe = fakeStripe();
await new Subscribe({
await new Subscribe({ catalog: staticPlanCatalog(),
db: db as never,
providers: (id) => (id === 'MERCADO_PAGO' ? mp : stripe),
webOrigin: 'http://web',
apiOrigin: 'https://api',
now: () => now,
}).execute(userId, { returnTo: 'billing' });
@@ -275,7 +276,7 @@ describe('Subscribe outside Argentina (Stripe)', () => {
const db = makeDb(null, 'CL');
const stripe = fakeStripe({ isAvailable: () => false });
const result = await new Subscribe({ db: db as never, providers: () => stripe }).execute(userId, {
const result = await new Subscribe({ catalog: staticPlanCatalog(), db: db as never, providers: () => stripe }).execute(userId, {
returnTo: 'billing',
});
@@ -288,7 +289,7 @@ describe('Subscribe outside Argentina (Stripe)', () => {
const db = makeDb(null, 'AR');
const provider = mpProvider(makeClient());
const result = await new Subscribe({ db: db as never, providers: () => provider }).execute(userId, {
const result = await new Subscribe({ catalog: staticPlanCatalog(), db: db as never, providers: () => provider }).execute(userId, {
returnTo: 'billing',
});

View File

@@ -0,0 +1,78 @@
import { afterEach, describe, expect, it } from 'bun:test';
import { createCheckoutPreference, isPublicHttpsUrl, searchMpPaymentByExternalReference } from '@/modules/mp/lib/mp-http';
describe('isPublicHttpsUrl', () => {
it('only asks Mercado Pago for the automatic return on public HTTPS', () => {
expect(isPublicHttpsUrl('https://app.gruperly.com/student/payments')).toBe(true);
expect(isPublicHttpsUrl('http://localhost:6173/student/payments')).toBe(false);
expect(isPublicHttpsUrl('https://localhost:6173/student/payments')).toBe(false);
expect(isPublicHttpsUrl('http://app.gruperly.com/student/payments')).toBe(false);
expect(isPublicHttpsUrl('not a url')).toBe(false);
});
});
describe('createCheckoutPreference', () => {
const realFetch = globalThis.fetch;
afterEach(() => {
globalThis.fetch = realFetch;
});
async function sentBody(input: { backUrl: string; notificationUrl?: string }) {
let body: Record<string, unknown> = {};
globalThis.fetch = (async (_url: string, init: RequestInit) => {
body = JSON.parse(String(init.body));
return new Response(JSON.stringify({ id: 'pref-1', init_point: 'https://mp/pay' }), { status: 201 });
}) as unknown as typeof fetch;
await createCheckoutPreference('token', {
title: 'Octubre',
unitPrice: 100,
currencyId: 'ARS',
externalReference: 'pay-1',
...input,
});
return body;
}
it('asks for the automatic return and the notification on public HTTPS', async () => {
const body = await sentBody({
backUrl: 'https://app.gruperly.com/student/payments',
notificationUrl: 'https://app.gruperly.com/api/v1/payments/webhooks/mp/pay-1?source_news=webhooks',
});
expect(body.auto_return).toBe('approved');
expect(body.notification_url).toBe(
'https://app.gruperly.com/api/v1/payments/webhooks/mp/pay-1?source_news=webhooks',
);
});
it('leaves both out on localhost, which Mercado Pago refuses', async () => {
const body = await sentBody({
backUrl: 'http://localhost:6173/student/payments',
notificationUrl: 'http://localhost:4000/api/v1/payments/webhooks/mp/pay-1',
});
expect(body).not.toHaveProperty('auto_return');
expect(body).not.toHaveProperty('notification_url');
});
});
describe('searchMpPaymentByExternalReference', () => {
const realFetch = globalThis.fetch;
afterEach(() => {
globalThis.fetch = realFetch;
});
it('prefers the approved attempt over an earlier rejected one', async () => {
globalThis.fetch = (async () =>
new Response(
JSON.stringify({
results: [
{ id: 1, status: 'rejected', external_reference: 'pay-1' },
{ id: 2, status: 'approved', external_reference: 'pay-1', date_approved: '2026-11-11T03:00:00.000Z' },
],
}),
{ status: 200 },
)) as unknown as typeof fetch;
const found = await searchMpPaymentByExternalReference('token', 'pay-1');
expect(found).toMatchObject({ id: '2', status: 'approved' });
});
});

View File

@@ -27,6 +27,7 @@ import prisma from '@/lib/prisma';
import { getMpAccessToken, mpRoutes } from '@/modules/mp';
import { RefreshExpiringMpTokens } from '@/modules/mp/jobs/refresh-expiring-mp-tokens';
import { RefreshMpAccount } from '@/modules/mp/jobs/refresh-mp-account';
import { mpCallbackBounceUrl } from '@/modules/mp/lib/callback-origin';
import { codeChallengeFromVerifier, openToken, sealToken } from '@/modules/mp/lib/crypto';
import { MpApiError } from '@/modules/mp/lib/mp-oauth';
@@ -579,6 +580,17 @@ describe('modules/mp', () => {
expect(location.href).not.toContain(storedState.codeVerifier);
});
it('refuses a state started by another teacher, without spending it', async () => {
prisma.mpOAuthState.findUnique.mockResolvedValue({ ...storedState, ownerId: otherOwnerId });
const res = await makeApp({ id: ownerId }).request(callbackUrl('?code=auth-code-123&state=state-abc'));
expect(res.status).toBe(302);
expect(locationOf(res).searchParams.get('reason')).toBe('invalid_state');
expect(prisma.mpOAuthState.deleteMany).not.toHaveBeenCalled();
expect(prisma.mpAccount.upsert).not.toHaveBeenCalled();
});
it('sends a teacher without a session to the login screen', async () => {
const res = await makeApp(null).request(callbackUrl('?code=code&state=state-abc'));
@@ -1040,3 +1052,30 @@ describe('modules/mp RefreshExpiringMpTokens', () => {
expect(totals).toEqual({ refreshed: 1, requiresReauth: 1, failed: 1 });
});
});
describe('mpCallbackBounceUrl', () => {
const env = {
MP_REDIRECT_URI: 'https://tunnel.ngrok-free.app/api/v1/mp/callback',
BETTER_AUTH_URL: 'http://localhost:4000',
};
const url = 'https://tunnel.ngrok-free.app/api/v1/mp/callback?code=c&state=s';
it('replays a callback that came through the tunnel on the origin with the session', () => {
expect(mpCallbackBounceUrl(url, 'tunnel.ngrok-free.app', env)).toBe(
'http://localhost:4000/api/v1/mp/callback?code=c&state=s',
);
});
it('leaves it alone once it is on the session origin', () => {
expect(mpCallbackBounceUrl('http://localhost:4000/api/v1/mp/callback?code=c', 'localhost:4000', env)).toBeNull();
});
it('never fires when the redirect and the session share a host (production)', () => {
const prod = {
MP_REDIRECT_URI: 'https://app.gruperly.com/api/v1/mp/callback',
BETTER_AUTH_URL: 'https://app.gruperly.com',
};
expect(mpCallbackBounceUrl('http://api:4000/api/v1/mp/callback?code=c', 'app.gruperly.com', prod)).toBeNull();
expect(mpCallbackBounceUrl('http://api:4000/api/v1/mp/callback?code=c', 'api:4000', prod)).toBeNull();
});
});

View File

@@ -69,7 +69,7 @@ function batchUseCase() {
initPoint: 'https://mp.link/pay-1',
sandboxInitPoint: null,
}));
return new CreatePaymentBatch({ getToken, createPreference, webOrigin });
return new CreatePaymentBatch({ getToken, createPreference, webOrigin, apiOrigin: 'https://api' });
}
describe('create payments batch', () => {
@@ -143,6 +143,7 @@ describe('create payments batch', () => {
currencyId: 'ARS',
externalReference: 'pay-1',
backUrl: `${webOrigin}/student/payments`,
notificationUrl: 'https://api/api/v1/payments/webhooks/mp/pay-1?source_news=webhooks',
});
});
@@ -191,7 +192,7 @@ describe('create payments batch', () => {
throw new Error('should not be called');
});
const result = await new CreatePaymentBatch({ getToken, createPreference, webOrigin }).execute(
const result = await new CreatePaymentBatch({ getToken, createPreference, webOrigin, apiOrigin: 'https://api' }).execute(
'group-1',
userId,
{ dueDate: '2026-10-05T12:00:00.000Z' },

View File

@@ -83,7 +83,7 @@ describe('renew payment link', () => {
sandboxInitPoint: null,
}));
const result = await new RenewPaymentLink({ getToken, createPreference, webOrigin }).execute(
const result = await new RenewPaymentLink({ getToken, createPreference, webOrigin, apiOrigin: 'https://api' }).execute(
'pay-1',
userId,
);
@@ -102,6 +102,7 @@ describe('renew payment link', () => {
currencyId: 'ARS',
externalReference: 'pay-1',
backUrl: `${webOrigin}/student/payments`,
notificationUrl: 'https://api/api/v1/payments/webhooks/mp/pay-1?source_news=webhooks',
});
expect(prisma.payment.update).toHaveBeenCalledWith({
where: { id: 'pay-1' },

View File

@@ -0,0 +1,103 @@
import { describe, expect, it, mock } from 'bun:test';
import { isPublicApiRequest } from '@/http/session-auth';
import { MpApiError } from '@/modules/mp/lib/mp-oauth';
import { HandleMpPaymentNotification } from '@/modules/payments/features/webhook/use-case';
import { paymentNotificationUrl } from '@/modules/payments/lib';
const ownerId = 'user-1';
const tokenOk = () =>
mock(async () => ({ ok: true, value: { accountId: 'acc-1', accessToken: 'token-1', expiresAt: new Date() } }));
function makeDb(row: unknown) {
return {
payment: {
findFirst: mock(async () => row),
update: mock(async () => ({})),
},
};
}
const linked = { id: 'pay-1', group: { createdById: ownerId } };
describe('HandleMpPaymentNotification', () => {
it('marks the payment PAID once the owner account confirms it was approved', async () => {
const db = makeDb(linked);
const getToken = tokenOk();
const search = mock(async () => ({
id: '999',
status: 'approved',
externalReference: 'pay-1',
liveMode: true,
dateApproved: '2026-11-11T03:00:00.000Z',
}));
const result = await new HandleMpPaymentNotification({ db: db as never, getToken, search }).execute('pay-1');
expect(result).toEqual({ ok: true, value: { outcome: 'paid' } });
expect(getToken).toHaveBeenCalledWith(ownerId);
expect(search).toHaveBeenCalledWith('token-1', 'pay-1');
expect(db.payment.update).toHaveBeenCalledWith({
where: { id: 'pay-1' },
data: { status: 'PAID', mpPaymentId: '999', paidAt: new Date('2026-11-11T03:00:00.000Z') },
});
expect(db.payment.findFirst).toHaveBeenCalledWith(
expect.objectContaining({
where: { id: 'pay-1', status: { in: ['PENDING', 'OVERDUE'] }, checkoutUrl: { not: null } },
}),
);
});
it('changes nothing while the payment is not approved', async () => {
const db = makeDb(linked);
const search = mock(async () => ({
id: '999',
status: 'rejected',
externalReference: 'pay-1',
liveMode: true,
dateApproved: null,
}));
const result = await new HandleMpPaymentNotification({ db: db as never, getToken: tokenOk(), search }).execute(
'pay-1',
);
expect(result).toEqual({ ok: true, value: { outcome: 'unpaid' } });
expect(db.payment.update).not.toHaveBeenCalled();
});
it('ignores an unknown, already paid or link-less payment without asking Mercado Pago', async () => {
const db = makeDb(null);
const search = mock(async () => null);
const result = await new HandleMpPaymentNotification({ db: db as never, getToken: tokenOk(), search }).execute(
'pay-x',
);
expect(result).toEqual({ ok: true, value: { outcome: 'ignored' } });
expect(search).not.toHaveBeenCalled();
});
it('answers an error when Mercado Pago cannot be asked, so it retries', async () => {
const db = makeDb(linked);
const search = mock(async () => {
throw new MpApiError(503, null);
});
const result = await new HandleMpPaymentNotification({ db: db as never, getToken: tokenOk(), search }).execute(
'pay-1',
);
expect(result.ok).toBe(false);
expect(db.payment.update).not.toHaveBeenCalled();
});
});
describe('payment notification URL', () => {
it('points at the public payment webhook, which needs no session', () => {
const url = paymentNotificationUrl('https://x.ngrok-free.app', 'cmabc123');
expect(url).toBe('https://x.ngrok-free.app/api/v1/payments/webhooks/mp/cmabc123?source_news=webhooks');
expect(isPublicApiRequest('POST', new URL(url).pathname)).toBe(true);
expect(isPublicApiRequest('GET', new URL(url).pathname)).toBe(false);
expect(isPublicApiRequest('POST', '/api/v1/payments/webhooks/mp/a/b')).toBe(false);
});
});