Files
gruperly/apps/backend/test/payments-webhook.test.ts
Jose Selesan aac142d324 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>
2026-11-11 07:50:14 -03:00

104 lines
3.7 KiB
TypeScript

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);
});
});