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>
249 lines
7.8 KiB
TypeScript
249 lines
7.8 KiB
TypeScript
import { beforeEach, describe, expect, it, mock, vi } from 'bun:test';
|
|
import { Hono } from 'hono';
|
|
|
|
const db = {
|
|
mpAccount: {
|
|
findUnique: mock(),
|
|
},
|
|
group: {
|
|
findUnique: mock(),
|
|
},
|
|
attendee: {
|
|
findMany: mock(),
|
|
},
|
|
payment: {
|
|
create: mock(),
|
|
update: mock(),
|
|
},
|
|
user: {
|
|
findUnique: mock(),
|
|
},
|
|
};
|
|
|
|
mock.module('@/lib/prisma', () => ({
|
|
default: db,
|
|
getPrismaClient: mock(),
|
|
UnitOfWork: class {},
|
|
}));
|
|
|
|
import prisma from '@/lib/prisma';
|
|
import { groupsRoutes } from '@/modules/groups';
|
|
import { MpApiError } from '@/modules/mp/lib/mp-oauth';
|
|
import { CreatePaymentBatch } from '@/modules/payments/features/create-batch/use-case';
|
|
|
|
const userId = 'user-1';
|
|
const webOrigin = 'http://localhost:6173';
|
|
|
|
function makeApp(userValue: unknown) {
|
|
const app = new Hono();
|
|
app.use('*', async (c, next) => {
|
|
c.set('user', userValue as never);
|
|
await next();
|
|
});
|
|
app.route('/groups', groupsRoutes);
|
|
return app;
|
|
}
|
|
|
|
function okAccount() {
|
|
return {
|
|
ok: true,
|
|
value: { accountId: 'acc-1', accessToken: 'token-1', expiresAt: new Date() },
|
|
};
|
|
}
|
|
|
|
const groupOwner = {
|
|
id: 'group-1',
|
|
name: 'Vinyasa',
|
|
createdById: userId,
|
|
price: { toString: () => '120.00' } as { toString(): string },
|
|
members: [],
|
|
};
|
|
|
|
let getToken: ReturnType<typeof mock>;
|
|
let createPreference: ReturnType<typeof mock>;
|
|
|
|
function batchUseCase() {
|
|
getToken = mock(async () => okAccount());
|
|
createPreference = mock(async () => ({
|
|
id: 'pref-1',
|
|
initPoint: 'https://mp.link/pay-1',
|
|
sandboxInitPoint: null,
|
|
}));
|
|
return new CreatePaymentBatch({ getToken, createPreference, webOrigin, apiOrigin: 'https://api' });
|
|
}
|
|
|
|
describe('create payments batch', () => {
|
|
beforeEach(() => {
|
|
vi.clearAllMocks();
|
|
});
|
|
|
|
it('creates one link per active attendee; keeps going when one preference fails', async () => {
|
|
prisma.group.findUnique.mockResolvedValue(groupOwner);
|
|
prisma.user.findUnique.mockResolvedValue({ id: userId, country: 'AR' });
|
|
prisma.attendee.findMany.mockResolvedValue([
|
|
{ id: 'att-1', person: { fullName: 'Juana' } },
|
|
{ id: 'att-2', person: { fullName: 'Pedro' } },
|
|
]);
|
|
prisma.payment.create
|
|
.mockResolvedValueOnce({ id: 'pay-1' })
|
|
.mockResolvedValueOnce({ id: 'pay-2' });
|
|
const useCase = batchUseCase();
|
|
createPreference.mockResolvedValueOnce({
|
|
id: 'pref-1',
|
|
initPoint: 'https://mp.link/pay-1',
|
|
sandboxInitPoint: null,
|
|
});
|
|
createPreference.mockRejectedValue(new MpApiError(502, 'bad_gateway'));
|
|
|
|
const result = await useCase.execute('group-1', userId, {
|
|
dueDate: '2026-10-05T12:00:00.000Z',
|
|
description: 'Octubre',
|
|
});
|
|
|
|
expect(result.ok).toBe(true);
|
|
if (!result.ok) throw new Error('expected ok');
|
|
expect(result.value).toEqual({
|
|
groupId: 'group-1',
|
|
total: 2,
|
|
linked: 1,
|
|
failed: 1,
|
|
items: [
|
|
{
|
|
paymentId: 'pay-1',
|
|
attendeeId: 'att-1',
|
|
attendeeName: 'Juana',
|
|
amount: 120,
|
|
currency: 'ARS',
|
|
checkoutUrl: 'https://mp.link/pay-1',
|
|
outcome: 'LINKED',
|
|
reason: null,
|
|
},
|
|
{
|
|
paymentId: 'pay-2',
|
|
attendeeId: 'att-2',
|
|
attendeeName: 'Pedro',
|
|
amount: 120,
|
|
currency: 'ARS',
|
|
checkoutUrl: null,
|
|
outcome: 'FAILED',
|
|
reason: 'mp_provider_error',
|
|
},
|
|
],
|
|
});
|
|
|
|
expect(prisma.payment.create).toHaveBeenCalledTimes(2);
|
|
expect(prisma.payment.update).toHaveBeenCalledTimes(1);
|
|
expect(prisma.payment.update).toHaveBeenCalledWith({
|
|
where: { id: 'pay-1' },
|
|
data: { checkoutUrl: 'https://mp.link/pay-1', mpPreferenceId: 'pref-1' },
|
|
});
|
|
expect(createPreference).toHaveBeenNthCalledWith(1, 'token-1', {
|
|
title: 'Octubre',
|
|
unitPrice: 120,
|
|
currencyId: 'ARS',
|
|
externalReference: 'pay-1',
|
|
backUrl: `${webOrigin}/student/payments`,
|
|
notificationUrl: 'https://api/api/v1/payments/webhooks/mp/pay-1?source_news=webhooks',
|
|
});
|
|
});
|
|
|
|
it('derives the currency from the owner country and defaults when there is none', async () => {
|
|
prisma.group.findUnique.mockResolvedValue({ ...groupOwner, price: { toString: () => '80.00' } });
|
|
prisma.user.findUnique.mockResolvedValue({ id: userId, country: null });
|
|
prisma.attendee.findMany.mockResolvedValue([{ id: 'att-2', person: { fullName: 'Pedro' } }]);
|
|
prisma.payment.create.mockResolvedValueOnce({ id: 'pay-2' });
|
|
const useCase = batchUseCase();
|
|
createPreference.mockResolvedValueOnce({
|
|
id: 'pref-2',
|
|
initPoint: 'https://mp.link/pay-2',
|
|
sandboxInitPoint: null,
|
|
});
|
|
|
|
const result = await useCase.execute('group-1', userId, {
|
|
dueDate: '2026-10-05T12:00:00.000Z',
|
|
attendeeIds: ['att-2'],
|
|
});
|
|
|
|
expect(result.ok).toBe(true);
|
|
if (!result.ok) throw new Error('expected ok');
|
|
expect(result.value.items).toHaveLength(1);
|
|
expect(result.value.items[0]).toMatchObject({ attendeeId: 'att-2', currency: 'ARS' });
|
|
expect(prisma.attendee.findMany).toHaveBeenCalledWith({
|
|
where: { groupId: 'group-1', status: 'ACTIVE', id: { in: ['att-2'] } },
|
|
include: { person: { select: { fullName: true } } },
|
|
});
|
|
});
|
|
|
|
it('propagates the not-connected problem and creates no rows', async () => {
|
|
prisma.group.findUnique.mockResolvedValue(groupOwner);
|
|
prisma.user.findUnique.mockResolvedValue({ id: userId, country: 'AR' });
|
|
prisma.attendee.findMany.mockResolvedValue([{ id: 'att-1', person: { fullName: 'Juana' } }]);
|
|
getToken = mock(async () => ({
|
|
ok: false,
|
|
error: {
|
|
type: 'https://gruperly.app/problems/conflict',
|
|
title: 'Conflict',
|
|
status: 409,
|
|
detail: 'No tenés una cuenta de Mercado Pago vinculada.',
|
|
code: 'mp_not_connected',
|
|
},
|
|
}));
|
|
const createPreference = mock(async () => {
|
|
throw new Error('should not be called');
|
|
});
|
|
|
|
const result = await new CreatePaymentBatch({ getToken, createPreference, webOrigin, apiOrigin: 'https://api' }).execute(
|
|
'group-1',
|
|
userId,
|
|
{ dueDate: '2026-10-05T12:00:00.000Z' },
|
|
);
|
|
|
|
expect(result.ok).toBe(false);
|
|
expect(prisma.payment.create).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it('answers 409 over HTTP when the owner has no linked account', async () => {
|
|
prisma.group.findUnique.mockResolvedValue(groupOwner);
|
|
prisma.user.findUnique.mockResolvedValue({ id: userId, country: 'AR' });
|
|
prisma.attendee.findMany.mockResolvedValue([{ id: 'att-1', person: { fullName: 'Juana' } }]);
|
|
prisma.mpAccount.findUnique.mockResolvedValue(null);
|
|
|
|
const res = await makeApp({ id: userId }).request('/groups/group-1/payments/batch', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ dueDate: '2026-10-05T12:00:00.000Z' }),
|
|
});
|
|
|
|
expect(res.status).toBe(409);
|
|
expect(prisma.payment.create).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it('rejects a group without price', async () => {
|
|
prisma.group.findUnique.mockResolvedValue({ ...groupOwner, price: null });
|
|
|
|
const res = await makeApp({ id: userId }).request('/groups/group-1/payments/batch', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ dueDate: '2026-10-05T12:00:00.000Z' }),
|
|
});
|
|
|
|
expect(res.status).toBe(409);
|
|
expect(prisma.attendee.findMany).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it('rejects a group the user has no access to', async () => {
|
|
prisma.group.findUnique.mockResolvedValue({
|
|
...groupOwner,
|
|
createdById: 'someone-else',
|
|
members: [],
|
|
});
|
|
|
|
const res = await makeApp({ id: userId }).request('/groups/group-1/payments/batch', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ dueDate: '2026-10-05T12:00:00.000Z' }),
|
|
});
|
|
|
|
expect(res.status).toBe(403);
|
|
});
|
|
}); |