Files
gruperly/apps/backend/test/payments-renew.test.ts
Jose Selesan ac98495a6e feat(payments): automatic monthly charges with combined links per payer
- Teacher picks a day of the month in Settings; an hourly job creates the
  fees of all monthly groups on that day in the teacher's time zone
  (one run per teacher and month, partial unique index per attendee/period).
- One Mercado Pago link per payer (PaymentCheckout): the adult in charge
  bundles their kids and their own fees; external_reference chk_<id>,
  dedicated webhook and reconciliation mark every fee PAID at once.
- Person.payWithMercadoPago toggle (default on): off creates the fee
  without a link so the student pays by transfer.
- A fee paid some other way supersedes its combined link and expires the
  preference; renewing rebuilds the combined link or a single one.
- Optional WhatsApp delivery (PAYMENT_LINK kind, new Kapso template);
  weekly reminders now go once per combined link.
- Web: auto charge settings card, per-student toggle, combined link label
  in Cobros and "Pay all" in the student app, in the four locales.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 15:08:48 -03:00

160 lines
4.9 KiB
TypeScript

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: { person: { 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, apiOrigin: 'https://api' }).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}/student/payments`,
notificationUrl: 'https://api/api/v1/payments/webhooks/mp/pay-1?source_news=webhooks',
});
expect(prisma.payment.update).toHaveBeenCalledWith({
where: { id: 'pay-1' },
data: { checkoutUrl: 'https://mp.link/pay-1', mpPreferenceId: 'pref-new', checkoutId: null },
include: {
attendee: { select: { person: { select: { fullName: true } } } },
group: { select: { name: true, price: true } },
checkout: { select: { _count: { select: { payments: 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();
});
});