Files
gruperly/apps/backend/test/billing-entitlements.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

119 lines
4.9 KiB
TypeScript

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');
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) },
// People with an active membership: someone in two groups counts once.
person: { 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, catalog: staticPlanCatalog() });
}
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);
});
});