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; let createPreference: ReturnType; 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 }); } 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', fullName: 'Juana' }, { id: 'att-2', 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`, }); }); 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', 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'] } }, }); }); 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', 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 }).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', 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); }); });