feat: add country selection during onboarding and implement payment management features
- Introduced CountryStep component for selecting the country during onboarding, affecting payment currency. - Updated FirstGroupStep to include country information. - Enhanced PaymentsProvider to manage payment states and renewals. - Created PaymentRow component for displaying individual payment details. - Implemented PaymentsView for listing and filtering payments by group and status. - Added API endpoints for fetching and creating payments, including batch processing. - Defined payment schemas for validation and data handling. - Updated GroupHeader and GroupDetailView to include charging functionality for group members.
This commit is contained in:
@@ -64,6 +64,7 @@ const firstGroupPayload = {
|
||||
price: group.price,
|
||||
billingType: group.billingType,
|
||||
dueDay: group.dueDay,
|
||||
country: 'AR',
|
||||
};
|
||||
|
||||
describe('onboarding routes', () => {
|
||||
@@ -185,7 +186,7 @@ describe('onboarding routes', () => {
|
||||
});
|
||||
expect(prisma.user.update).toHaveBeenCalledWith({
|
||||
where: { id: userId },
|
||||
data: { onboardingCompleted: true },
|
||||
data: { onboardingCompleted: true, country: 'AR' },
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
247
apps/backend/test/payments-batch.test.ts
Normal file
247
apps/backend/test/payments-batch.test.ts
Normal file
@@ -0,0 +1,247 @@
|
||||
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 });
|
||||
}
|
||||
|
||||
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}/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);
|
||||
});
|
||||
});
|
||||
43
apps/backend/test/payments-overdue.test.ts
Normal file
43
apps/backend/test/payments-overdue.test.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
import { beforeEach, describe, expect, it, mock, vi } from 'bun:test';
|
||||
|
||||
const db = {
|
||||
payment: {
|
||||
updateMany: mock(),
|
||||
},
|
||||
};
|
||||
|
||||
mock.module('@/lib/prisma', () => ({
|
||||
default: db,
|
||||
getPrismaClient: mock(),
|
||||
UnitOfWork: class {},
|
||||
}));
|
||||
|
||||
import prisma from '@/lib/prisma';
|
||||
import { MarkOverduePayments } from '@/modules/payments/jobs';
|
||||
|
||||
describe('mark overdue payments', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('marks PENDING payments whose due date passed more than a day ago', async () => {
|
||||
prisma.payment.updateMany.mockResolvedValue({ count: 3 });
|
||||
const now = new Date('2026-10-08T12:00:00.000Z');
|
||||
|
||||
const result = await new MarkOverduePayments({ now }).execute();
|
||||
|
||||
expect(result).toEqual({ marked: 3 });
|
||||
expect(prisma.payment.updateMany).toHaveBeenCalledWith({
|
||||
where: { status: 'PENDING', dueDate: { lt: new Date('2026-10-07T12:00:00.000Z') } },
|
||||
data: { status: 'OVERDUE' },
|
||||
});
|
||||
});
|
||||
|
||||
it('leaves payments inside the grace period alone', async () => {
|
||||
prisma.payment.updateMany.mockResolvedValue({ count: 0 });
|
||||
|
||||
const result = await new MarkOverduePayments({ now: new Date() }).execute();
|
||||
|
||||
expect(result).toEqual({ marked: 0 });
|
||||
});
|
||||
});
|
||||
129
apps/backend/test/payments-reconcile.test.ts
Normal file
129
apps/backend/test/payments-reconcile.test.ts
Normal file
@@ -0,0 +1,129 @@
|
||||
import { beforeEach, describe, expect, it, mock, vi } from 'bun:test';
|
||||
|
||||
const db = {
|
||||
payment: {
|
||||
findMany: mock(),
|
||||
update: mock(),
|
||||
},
|
||||
};
|
||||
|
||||
mock.module('@/lib/prisma', () => ({
|
||||
default: db,
|
||||
getPrismaClient: mock(),
|
||||
UnitOfWork: class {},
|
||||
}));
|
||||
|
||||
import prisma from '@/lib/prisma';
|
||||
import { MpApiError } from '@/modules/mp/lib/mp-oauth';
|
||||
import { ReconcilePayments } from '@/modules/payments/jobs';
|
||||
|
||||
const ownerId = 'user-1';
|
||||
const pendingPayment = (id: string, overrides: Record<string, unknown> = {}) => ({
|
||||
id,
|
||||
groupId: 'group-1',
|
||||
status: 'PENDING',
|
||||
checkoutUrl: 'https://mp.link/pay',
|
||||
createdAt: new Date(Date.now() - 10 * 60 * 1000),
|
||||
group: { createdById: ownerId },
|
||||
...overrides,
|
||||
});
|
||||
|
||||
function okAccount() {
|
||||
return {
|
||||
ok: true,
|
||||
value: { accountId: 'acc-1', accessToken: 'token-1', expiresAt: new Date() },
|
||||
};
|
||||
}
|
||||
|
||||
describe('reconcile payments', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('marks an approved Mercado Pago payment as PAID', async () => {
|
||||
prisma.payment.findMany.mockResolvedValue([pendingPayment('pay-1')]);
|
||||
const getToken = mock(async () => okAccount());
|
||||
const search = mock(async () => ({
|
||||
id: '999999999',
|
||||
status: 'approved',
|
||||
externalReference: 'pay-1',
|
||||
liveMode: true,
|
||||
dateApproved: '2026-10-01T12:30:00.000Z',
|
||||
}));
|
||||
|
||||
const result = await new ReconcilePayments({ getToken, search }).execute();
|
||||
|
||||
expect(result).toEqual({ paid: 1, skipped: 0, failed: 0 });
|
||||
expect(prisma.payment.update).toHaveBeenCalledWith({
|
||||
where: { id: 'pay-1' },
|
||||
data: {
|
||||
status: 'PAID',
|
||||
mpPaymentId: '999999999',
|
||||
paidAt: new Date('2026-10-01T12:30:00.000Z'),
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('skips a payment that is still pending in Mercado Pago', async () => {
|
||||
prisma.payment.findMany.mockResolvedValue([pendingPayment('pay-1')]);
|
||||
const getToken = mock(async () => okAccount());
|
||||
const search = mock(async () => ({
|
||||
id: '999999999',
|
||||
status: 'pending',
|
||||
externalReference: 'pay-1',
|
||||
liveMode: true,
|
||||
dateApproved: null,
|
||||
}));
|
||||
|
||||
const result = await new ReconcilePayments({ getToken, search }).execute();
|
||||
|
||||
expect(result).toEqual({ paid: 0, skipped: 0, failed: 0 });
|
||||
expect(prisma.payment.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('skips rows when the owner has no usable token', async () => {
|
||||
prisma.payment.findMany.mockResolvedValue([pendingPayment('pay-1')]);
|
||||
const getToken = mock(async () => ({
|
||||
ok: false,
|
||||
error: { type: 'x', title: 'Conflict', status: 409, detail: 'x', code: 'mp_not_connected' },
|
||||
}));
|
||||
const search = mock(async () => {
|
||||
throw new Error('should not be called');
|
||||
});
|
||||
|
||||
const result = await new ReconcilePayments({ getToken, search }).execute();
|
||||
|
||||
expect(result).toEqual({ paid: 0, skipped: 1, failed: 0 });
|
||||
expect(search).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('counts an unreachable Mercado Pago as failed and leaves the row pending', async () => {
|
||||
prisma.payment.findMany.mockResolvedValue([pendingPayment('pay-1')]);
|
||||
const getToken = mock(async () => okAccount());
|
||||
const search = mock(async () => {
|
||||
throw new MpApiError(0, null);
|
||||
});
|
||||
|
||||
const result = await new ReconcilePayments({ getToken, search }).execute();
|
||||
|
||||
expect(result).toEqual({ paid: 0, skipped: 0, failed: 1 });
|
||||
expect(prisma.payment.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('only reconciles payments linked for at least five minutes', async () => {
|
||||
prisma.payment.findMany.mockResolvedValue([]);
|
||||
const now = new Date('2026-10-01T12:00:00.000Z');
|
||||
|
||||
await new ReconcilePayments({ now }).execute();
|
||||
|
||||
expect(prisma.payment.findMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: {
|
||||
status: 'PENDING',
|
||||
checkoutUrl: { not: null },
|
||||
createdAt: { lt: new Date('2026-10-01T11:55:00.000Z') },
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
158
apps/backend/test/payments-renew.test.ts
Normal file
158
apps/backend/test/payments-renew.test.ts
Normal file
@@ -0,0 +1,158 @@
|
||||
import { beforeEach, describe, expect, it, mock, vi } from 'bun:test';
|
||||
import { Hono } from 'hono';
|
||||
|
||||
const db = {
|
||||
payment: {
|
||||
findUnique: mock(),
|
||||
update: mock(),
|
||||
},
|
||||
user: {
|
||||
findUnique: mock(),
|
||||
},
|
||||
};
|
||||
|
||||
mock.module('@/lib/prisma', () => ({
|
||||
default: db,
|
||||
getPrismaClient: mock(),
|
||||
UnitOfWork: class {},
|
||||
}));
|
||||
|
||||
import prisma from '@/lib/prisma';
|
||||
import { paymentsRoutes } from '@/modules/payments';
|
||||
import { RenewPaymentLink } from '@/modules/payments/features/renew/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('/payments', paymentsRoutes);
|
||||
return app;
|
||||
}
|
||||
|
||||
function paymentWithoutLink(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: 'pay-1',
|
||||
groupId: 'group-1',
|
||||
attendeeId: 'att-1',
|
||||
amount: { toString: () => '120.00' } as { toString(): string },
|
||||
currency: 'ARS',
|
||||
status: 'PENDING',
|
||||
description: null,
|
||||
checkoutUrl: null,
|
||||
mpPreferenceId: null,
|
||||
dueDate: new Date('2026-10-05T12:00:00.000Z'),
|
||||
paidAt: null,
|
||||
createdAt: new Date('2026-10-01T10:00:00.000Z'),
|
||||
updatedAt: new Date('2026-10-01T10:00:00.000Z'),
|
||||
attendee: { fullName: 'Juana Pérez' },
|
||||
group: {
|
||||
name: 'Vinyasa',
|
||||
price: { toString: () => '120.00' },
|
||||
createdById: userId,
|
||||
members: [],
|
||||
},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('renew payment link', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('creates a new link for a payment that lost it and returns the payment', async () => {
|
||||
prisma.payment.findUnique.mockResolvedValue(paymentWithoutLink());
|
||||
prisma.user.findUnique.mockResolvedValue({ id: userId, country: 'AR' });
|
||||
prisma.payment.update.mockResolvedValue({
|
||||
...paymentWithoutLink(),
|
||||
checkoutUrl: 'https://mp.link/pay-1',
|
||||
group: { name: 'Vinyasa', price: { toString: () => '120.00' } },
|
||||
});
|
||||
const getToken = mock(async () => ({
|
||||
ok: true,
|
||||
value: { accountId: 'acc-1', accessToken: 'token-1', expiresAt: new Date() },
|
||||
}));
|
||||
const createPreference = mock(async () => ({
|
||||
id: 'pref-new',
|
||||
initPoint: 'https://mp.link/pay-1',
|
||||
sandboxInitPoint: null,
|
||||
}));
|
||||
|
||||
const result = await new RenewPaymentLink({ getToken, createPreference, webOrigin }).execute(
|
||||
'pay-1',
|
||||
userId,
|
||||
);
|
||||
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) throw new Error('expected ok');
|
||||
expect(result.value).toMatchObject({
|
||||
id: 'pay-1',
|
||||
groupName: 'Vinyasa',
|
||||
attendeeName: 'Juana Pérez',
|
||||
checkoutUrl: 'https://mp.link/pay-1',
|
||||
});
|
||||
expect(createPreference).toHaveBeenCalledWith('token-1', {
|
||||
title: 'Vinyasa',
|
||||
unitPrice: 120,
|
||||
currencyId: 'ARS',
|
||||
externalReference: 'pay-1',
|
||||
backUrl: `${webOrigin}/payments`,
|
||||
});
|
||||
expect(prisma.payment.update).toHaveBeenCalledWith({
|
||||
where: { id: 'pay-1' },
|
||||
data: { checkoutUrl: 'https://mp.link/pay-1', mpPreferenceId: 'pref-new' },
|
||||
include: {
|
||||
attendee: { select: { fullName: true } },
|
||||
group: { select: { name: true, price: true } },
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps an existing link: idempotent, no Mercado Pago call', async () => {
|
||||
prisma.payment.findUnique.mockResolvedValue(
|
||||
paymentWithoutLink({ checkoutUrl: 'https://mp.link/pay-1' }),
|
||||
);
|
||||
|
||||
const res = await makeApp({ id: userId }).request('/payments/pay-1/renew', { method: 'POST' });
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(prisma.payment.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('answers 409 when the owner has no linked account', async () => {
|
||||
prisma.payment.findUnique.mockResolvedValue(paymentWithoutLink());
|
||||
prisma.user.findUnique.mockResolvedValue({ id: userId, country: 'AR' });
|
||||
const getToken = mock(async () => ({
|
||||
ok: false,
|
||||
error: { type: 'x', title: 'Conflict', status: 409, detail: 'x', code: 'mp_not_connected' },
|
||||
}));
|
||||
|
||||
const result = await new RenewPaymentLink({ getToken }).execute('pay-1', userId);
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
expect(prisma.payment.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects a payment of a group the user has no access to', async () => {
|
||||
prisma.payment.findUnique.mockResolvedValue(
|
||||
paymentWithoutLink({
|
||||
group: {
|
||||
name: 'Vinyasa',
|
||||
price: { toString: () => '120.00' },
|
||||
createdById: 'someone-else',
|
||||
members: [],
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const res = await makeApp({ id: userId }).request('/payments/pay-1/renew', { method: 'POST' });
|
||||
|
||||
expect(res.status).toBe(403);
|
||||
expect(prisma.payment.update).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,13 +1,18 @@
|
||||
import { beforeEach, describe, expect, it, mock, vi } from 'bun:test';
|
||||
import { Hono } from 'hono';
|
||||
|
||||
mock.module('@/lib/prisma', () => ({
|
||||
default: {
|
||||
payment: {
|
||||
findMany: mock(),
|
||||
count: mock(),
|
||||
},
|
||||
const db = {
|
||||
group: {
|
||||
findMany: mock(),
|
||||
},
|
||||
payment: {
|
||||
findMany: mock(),
|
||||
count: mock(),
|
||||
},
|
||||
};
|
||||
|
||||
mock.module('@/lib/prisma', () => ({
|
||||
default: db,
|
||||
getPrismaClient: mock(),
|
||||
UnitOfWork: class {},
|
||||
}));
|
||||
@@ -15,43 +20,61 @@ mock.module('@/lib/prisma', () => ({
|
||||
import prisma from '@/lib/prisma';
|
||||
import { paymentsRoutes } from '@/modules/payments';
|
||||
|
||||
const app = new Hono();
|
||||
app.route('/payments', paymentsRoutes);
|
||||
const userId = 'user-1';
|
||||
|
||||
const payment = {
|
||||
id: 'payment-1',
|
||||
groupId: 'group-1',
|
||||
attendeeId: 'attendee-1',
|
||||
groupId: 'group-1',
|
||||
attendeeId: 'attendee-1',
|
||||
amount: { toString: () => '150.50' } as { toString(): string },
|
||||
currency: 'MXN',
|
||||
status: 'pending',
|
||||
currency: 'ARS',
|
||||
status: 'PENDING',
|
||||
description: 'Mensualidad de Septiembre',
|
||||
checkoutUrl: 'https://mercadopago.com/checkout/payment-1',
|
||||
dueDate: new Date('2026-09-01T10:00:00.000Z'),
|
||||
paidAt: null,
|
||||
createdAt: new Date('2026-08-01T10:00:00.000Z'),
|
||||
updatedAt: new Date('2026-08-01T10:00:00.000Z'),
|
||||
group: { name: 'Cuadrilla Alfa', price: 150.5 },
|
||||
attendee: { fullName: 'Juana Pérez' },
|
||||
};
|
||||
|
||||
function makeApp(userValue: unknown) {
|
||||
const app = new Hono();
|
||||
app.use('*', async (c, next) => {
|
||||
c.set('user', userValue as never);
|
||||
await next();
|
||||
});
|
||||
app.route('/payments', paymentsRoutes);
|
||||
return app;
|
||||
}
|
||||
|
||||
describe('payments routes', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('lists payments with pagination and converts Decimal amounts', async () => {
|
||||
it('lists payments scoped to the user, with attendee and group names', async () => {
|
||||
prisma.group.findMany.mockResolvedValue([{ id: 'group-1' }]);
|
||||
prisma.payment.findMany.mockResolvedValue([payment]);
|
||||
prisma.payment.count.mockResolvedValue(1);
|
||||
|
||||
const res = await app.request('/payments');
|
||||
const res = await makeApp({ id: userId }).request('/payments');
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(await res.json()).toEqual({
|
||||
data: [
|
||||
{
|
||||
id: 'payment-1',
|
||||
groupId: 'group-1',
|
||||
attendeeId: 'attendee-1',
|
||||
groupId: 'group-1',
|
||||
groupName: 'Cuadrilla Alfa',
|
||||
attendeeId: 'attendee-1',
|
||||
attendeeName: 'Juana Pérez',
|
||||
amount: 150.5,
|
||||
currency: 'MXN',
|
||||
status: 'pending',
|
||||
currency: 'ARS',
|
||||
status: 'PENDING',
|
||||
description: 'Mensualidad de Septiembre',
|
||||
checkoutUrl: payment.checkoutUrl,
|
||||
dueDate: payment.dueDate.toISOString(),
|
||||
paidAt: null,
|
||||
createdAt: payment.createdAt.toISOString(),
|
||||
@@ -60,15 +83,49 @@ groupId: 'group-1',
|
||||
],
|
||||
pagination: { page: 1, pageSize: 10, total: 1, totalPages: 1 },
|
||||
});
|
||||
expect(prisma.group.findMany).toHaveBeenCalledWith({
|
||||
where: {
|
||||
OR: [{ createdById: userId }, { members: { some: { userId } } }],
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
expect(prisma.payment.findMany).toHaveBeenCalledWith({
|
||||
where: { groupId: { in: ['group-1'] } },
|
||||
include: {
|
||||
group: { select: { name: true, price: true } },
|
||||
attendee: { select: { fullName: true } },
|
||||
},
|
||||
skip: 0,
|
||||
take: 10,
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
});
|
||||
|
||||
it('filters payments by group and status', async () => {
|
||||
prisma.group.findMany.mockResolvedValue([{ id: 'group-1' }]);
|
||||
prisma.payment.findMany.mockResolvedValue([]);
|
||||
prisma.payment.count.mockResolvedValue(0);
|
||||
|
||||
const res = await makeApp({ id: userId }).request(
|
||||
'/payments?groupId=group-1&status=OVERDUE',
|
||||
);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(prisma.payment.findMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: { groupId: 'group-1', status: 'OVERDUE' },
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects requests without a session user', async () => {
|
||||
const res = await makeApp(null).request('/payments');
|
||||
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it('rejects invalid pagination query parameters', async () => {
|
||||
const res = await app.request('/payments?pageSize=101');
|
||||
const res = await makeApp({ id: userId }).request('/payments?pageSize=101');
|
||||
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user