import { describe, expect, it, mock } from 'bun:test'; import { GenerateMonthlyCharges } from '@/modules/payments/features/auto-charge/generate-monthly-charges'; import { isAutoChargeDue, nextAutoChargeDate } from '@/modules/payments/lib/auto-charge-schedule'; import { paymentLinkDetail } from '@/modules/whatsapp/jobs/send-payment-links'; const ownerId = 'owner-1'; const BA = 'America/Argentina/Buenos_Aires'; // 2026-12-05 12:00 in Buenos Aires (UTC-3). const NOW = new Date('2026-12-05T15:00:00.000Z'); type PersonRow = { id: string; payWithMercadoPago: boolean; guardian?: { id: string } }; type AttendeeRow = { id: string; groupId: string; person: PersonRow }; const decimal = (value: number) => ({ toString: () => String(value) }); /** In-memory stand-in for the Prisma calls the generator makes. */ function fakeDb(input: { groups: { id: string; name: string; price: number }[]; attendees: AttendeeRow[]; people: Record; settings?: { dueInDays: number; sendWhatsapp: boolean } | null; runExists?: boolean; }) { const payments: Record[] = []; const checkouts: Record[] = []; const runs: Record[] = []; let seq = 0; const groupName = (id: string) => input.groups.find((group) => group.id === id)?.name ?? ''; const attendeeById = (id: string) => input.attendees.find((attendee) => attendee.id === id) as AttendeeRow; const client = { payments, checkouts, runs, user: { findUnique: mock(async () => ({ country: 'AR', autoCharge: input.settings === null ? null : { enabled: true, chargeDay: 5, dueInDays: 10, sendWhatsapp: false, ...input.settings }, })), }, paymentRun: { create: mock(async ({ data }: { data: Record }) => { if (input.runExists) throw Object.assign(new Error('unique'), { code: 'P2002' }); const run = { id: `run-${++seq}`, ...data }; runs.push(run); return run; }), update: mock(async ({ data }: { data: Record }) => Object.assign(runs[0] ?? {}, data)), }, group: { findMany: mock(async () => input.groups.map((group) => ({ id: group.id, price: decimal(group.price) }))), }, attendee: { findMany: mock(async () => input.attendees.map((attendee) => ({ id: attendee.id, groupId: attendee.groupId, person: { id: attendee.person.id, payWithMercadoPago: attendee.person.payWithMercadoPago, guardians: attendee.person.guardian ? [{ guardian: { id: attendee.person.guardian.id, fullName: '', phone: null, email: null } }] : [], }, })), ), }, paymentCheckout: { create: mock(async ({ data }: { data: Record }) => { const checkout = { id: `chk-${++seq}`, status: 'OPEN', ...data }; checkouts.push(checkout); return { id: checkout.id }; }), findUnique: mock(async ({ where }: { where: { id: string } }) => { const checkout = checkouts.find((row) => row.id === where.id); if (!checkout) return null; return { ...checkout, payments: payments .filter((payment) => payment.checkoutId === checkout.id) .map((payment) => ({ id: payment.id, amount: payment.amount, group: { name: groupName(payment.groupId as string) }, attendee: { person: { fullName: input.people[attendeeById(payment.attendeeId as string).person.id] } }, })), }; }), update: mock(async ({ where, data }: { where: { id: string }; data: Record }) => Object.assign(checkouts.find((row) => row.id === where.id) ?? {}, data), ), }, payment: { create: mock(async ({ data }: { data: Record }) => { const payment = { id: `pay-${++seq}`, ...data }; payments.push(payment); return payment; }), updateMany: mock(async ({ where, data }: { where: { id: { in: string[] } }; data: Record }) => { for (const payment of payments) if (where.id.in.includes(payment.id as string)) Object.assign(payment, data); return { count: where.id.in.length }; }), }, $transaction: mock(async (callback: (tx: unknown) => Promise) => callback(client)), }; return client; } const okToken = mock(async () => ({ ok: true as const, value: { accountId: 'acc', accessToken: 'token', expiresAt: new Date() } })); const allowAll = { hasFeature: mock(async () => true) }; function generator(db: ReturnType, overrides: Record = {}) { let preference = 0; const createPreference = mock(async () => ({ id: `pref-${++preference}`, initPoint: `https://mp.link/${preference}`, sandboxInitPoint: null })); const sendLinks = mock(async (_owner: string, ids: string[]) => ids.length); const instance = new GenerateMonthlyCharges({ db: db as never, getToken: okToken as never, createPreference, planGuard: allowAll, sendLinks, webOrigin: 'https://app', apiOrigin: 'https://api', now: NOW, ...overrides, }); return { instance, createPreference, sendLinks }; } // A mother (guardian g-1) with two kids in two groups; she also takes Pilates herself. // An adult (p-4) alone. A kid (p-5) of another adult (g-2) who pays by transfer. const family = { groups: [ { id: 'swim', name: 'Natación', price: 20000 }, { id: 'yoga', name: 'Yoga', price: 15000 }, { id: 'pilates', name: 'Pilates', price: 10000 }, ], people: { 'p-1': 'Juan Gómez', 'p-2': 'Ana Gómez', 'g-1': 'Laura Gómez', 'p-4': 'Carlos Ruiz', 'p-5': 'Tomás Díaz' }, attendees: [ { id: 'a-1', groupId: 'swim', person: { id: 'p-1', payWithMercadoPago: true, guardian: { id: 'g-1' } } }, { id: 'a-2', groupId: 'yoga', person: { id: 'p-2', payWithMercadoPago: true, guardian: { id: 'g-1' } } }, { id: 'a-3', groupId: 'pilates', person: { id: 'g-1', payWithMercadoPago: true } }, { id: 'a-4', groupId: 'yoga', person: { id: 'p-4', payWithMercadoPago: true } }, { id: 'a-5', groupId: 'swim', person: { id: 'p-5', payWithMercadoPago: false, guardian: { id: 'g-2' } } }, ], }; describe('automatic monthly charges', () => { it('bundles the fees of each payer into one Mercado Pago link with the total', async () => { const db = fakeDb(family); const { instance, createPreference } = generator(db); const result = await instance.execute(ownerId); expect(result).toEqual({ outcome: 'done', fees: 5, checkouts: 2, linked: 2, failed: 0, sent: 0 }); expect(db.payments).toHaveLength(5); expect(db.payments.every((payment) => payment.periodKey === '2026-12')).toBe(true); // Due 10 days after the local charge date. expect(db.payments[0]?.dueDate).toEqual(new Date('2026-12-15T12:00:00.000Z')); const [mother, adult] = db.checkouts; expect(mother).toMatchObject({ payerPersonId: 'g-1', amount: 45000, currency: 'ARS', checkoutUrl: 'https://mp.link/1' }); expect(adult).toMatchObject({ payerPersonId: 'p-4', amount: 15000 }); expect(createPreference).toHaveBeenCalledWith('token', { title: 'Natación · Juan Gómez', unitPrice: 45000, items: [ { title: 'Natación · Juan Gómez', unitPrice: 20000 }, { title: 'Yoga · Ana Gómez', unitPrice: 15000 }, { title: 'Pilates · Laura Gómez', unitPrice: 10000 }, ], currencyId: 'ARS', externalReference: `chk_${mother?.id}`, backUrl: 'https://app/student/payments', notificationUrl: `https://api/api/v1/payments/webhooks/mp/checkout/${mother?.id}?source_news=webhooks`, }); // Each fee carries the shared link. const motherFees = db.payments.filter((payment) => payment.checkoutId === mother?.id); expect(motherFees.map((payment) => payment.checkoutUrl)).toEqual(Array(3).fill('https://mp.link/1')); }); it('creates the fee without a link for someone who pays by transfer', async () => { const db = fakeDb(family); await generator(db).instance.execute(ownerId); const transfer = db.payments.find((payment) => payment.attendeeId === 'a-5'); expect(transfer).toMatchObject({ status: 'PENDING', checkoutId: null, periodKey: '2026-12' }); expect(transfer?.checkoutUrl).toBeUndefined(); // The other adult has nobody paying with Mercado Pago: no checkout for them. expect(db.checkouts.some((checkout) => checkout.payerPersonId === 'g-2')).toBe(false); }); it('sends the generated links by WhatsApp only when the teacher turned it on', async () => { const off = fakeDb(family); const quiet = generator(off); await quiet.instance.execute(ownerId); expect(quiet.sendLinks).not.toHaveBeenCalled(); const on = fakeDb({ ...family, settings: { dueInDays: 10, sendWhatsapp: true } }); const loud = generator(on); const result = await loud.instance.execute(ownerId); expect(loud.sendLinks).toHaveBeenCalledWith(ownerId, on.checkouts.map((checkout) => checkout.id)); expect(result).toMatchObject({ outcome: 'done', sent: 2 }); }); it('is a no-op the second time in the same month', async () => { const db = fakeDb({ ...family, runExists: true }); const { instance, createPreference } = generator(db); expect(await instance.execute(ownerId)).toEqual({ outcome: 'already_ran' }); expect(db.payments).toHaveLength(0); expect(createPreference).not.toHaveBeenCalled(); }); it('skips the month when Mercado Pago is not linked', async () => { const db = fakeDb(family); const getToken = mock(async () => ({ ok: false as const, error: { status: 409, code: 'mp_not_connected' } })); const result = await generator(db, { getToken }).instance.execute(ownerId); expect(result).toEqual({ outcome: 'skipped', reason: 'mp_not_connected' }); expect(db.runs[0]).toMatchObject({ status: 'SKIPPED', skipReason: 'mp_not_connected' }); expect(db.payments).toHaveLength(0); }); it('skips the month without the Mercado Pago charges plan feature', async () => { const db = fakeDb(family); const result = await generator(db, { planGuard: { hasFeature: mock(async () => false) } }).instance.execute(ownerId); expect(result).toEqual({ outcome: 'skipped', reason: 'plan_feature_required' }); }); it('keeps going when one link fails: its checkout stays without a link', async () => { const db = fakeDb(family); let calls = 0; const createPreference = mock(async () => { calls += 1; if (calls === 1) throw new (await import('@/modules/mp/lib/mp-oauth')).MpApiError(500, null); return { id: 'pref-2', initPoint: 'https://mp.link/2', sandboxInitPoint: null }; }); const result = await generator(db, { createPreference }).instance.execute(ownerId); expect(result).toMatchObject({ outcome: 'done', checkouts: 2, linked: 1, failed: 1 }); expect(db.checkouts[0]?.checkoutUrl).toBeUndefined(); expect(db.checkouts[1]?.checkoutUrl).toBe('https://mp.link/2'); }); }); describe('auto charge schedule', () => { const settings = { chargeDay: 5, enabledAt: new Date('2026-11-01T12:00:00.000Z') }; it('is due from 9 a.m. local on the day, and for a few days after', () => { expect(isAutoChargeDue(settings, new Date('2026-12-05T11:00:00.000Z'), BA)).toBe(false); // 8 a.m. expect(isAutoChargeDue(settings, new Date('2026-12-05T12:00:00.000Z'), BA)).toBe(true); // 9 a.m. expect(isAutoChargeDue(settings, new Date('2026-12-08T02:00:00.000Z'), BA)).toBe(true); // 7th, 11 p.m. expect(isAutoChargeDue(settings, new Date('2026-12-09T12:00:00.000Z'), BA)).toBe(false); expect(isAutoChargeDue(settings, new Date('2026-12-04T12:00:00.000Z'), BA)).toBe(false); }); it('uses the teacher clock: 1 a.m. UTC on the 6th is still the 5th in Buenos Aires', () => { const lateEnabled = { chargeDay: 6, enabledAt: null }; expect(isAutoChargeDue(lateEnabled, new Date('2026-12-06T01:00:00.000Z'), BA)).toBe(false); }); it('does not bill a month whose day had passed when it was turned on', () => { const late = { chargeDay: 5, enabledAt: new Date('2026-12-06T12:00:00.000Z') }; expect(isAutoChargeDue(late, new Date('2026-12-07T12:00:00.000Z'), BA)).toBe(false); expect(nextAutoChargeDate(late, new Date('2026-12-07T12:00:00.000Z'), BA, false)).toBe('2027-01-05'); }); it('tells the next run date', () => { expect(nextAutoChargeDate(settings, new Date('2026-12-02T12:00:00.000Z'), BA, false)).toBe('2026-12-05'); expect(nextAutoChargeDate(settings, new Date('2026-12-06T12:00:00.000Z'), BA, true)).toBe('2027-01-05'); expect(nextAutoChargeDate(settings, new Date('2026-12-20T12:00:00.000Z'), BA, false)).toBe('2027-01-05'); }); }); describe('payment link detail', () => { it('names each kid and leaves the payer own group bare', () => { expect( paymentLinkDetail('g-1', [ { groupName: 'Natación', personId: 'p-1', fullName: 'Juan Gómez' }, { groupName: 'Yoga', personId: 'p-2', fullName: 'Ana Gómez' }, { groupName: 'Pilates', personId: 'g-1', fullName: 'Laura Gómez' }, ]), ).toBe('Natación (Juan), Yoga (Ana) y Pilates'); expect(paymentLinkDetail('p-4', [{ groupName: 'Yoga', personId: 'p-4', fullName: 'Carlos Ruiz' }])).toBe('Yoga'); }); });