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>
267 lines
11 KiB
TypeScript
267 lines
11 KiB
TypeScript
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');
|
|
});
|
|
});
|