/* Teacher review of reported payments against a real Postgres (see student-access.db.test.ts): confirm/reject/undo, the overdue alert and access between teachers. */ import { afterAll, beforeAll, describe, expect, it } from 'bun:test'; import { Prisma, PrismaClient } from '@generated/prisma/client'; import { PrismaPg } from '@prisma/adapter-pg'; import { UnitOfWork } from '@/lib/prisma'; import type { FileStorage } from '@/lib/storage'; import { GetAttentionOverview } from '@/modules/attention/features/get-overview/use-case'; import { ReportedPayments } from '@/modules/payments/features/reported/use-case'; import { sendReviewNotification } from '@/modules/payments/lib/review-notifications'; import { ReportStudentPayment } from '@/modules/student-portal/features/payment-reports/use-case'; const url = process.env.DB_TESTS === '1' ? process.env.DATABASE_URL : undefined; const suffix = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`; const PNG = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13, 73, 72, 68, 82]); const storage: FileStorage = { put: async () => {}, signedUrl: (key, ttl) => `https://storage.test/${key}?ttl=${ttl}`, remove: async () => {}, }; describe.skipIf(!url)('payment review (real database)', () => { let db: PrismaClient; let unitOfWork: UnitOfWork; const notified: string[] = []; const ids = { teacher: `r-teacher-${suffix}`, other: `r-other-${suffix}`, group: `r-group-${suffix}`, ana: `r-ana-${suffix}`, account: `r-acc-${suffix}`, fee: `r-fee-${suffix}`, }; const NOW = new Date('2026-10-28T15:00:00.000Z'); const reviews = (now = NOW) => new ReportedPayments({ db, unitOfWork, storage, now, notify: (id) => void notified.push(id) }); const overdueFor = async () => { const overview = await new GetAttentionOverview({ db: db as never, now: NOW }).execute(ids.teacher); if (!overview.ok) throw new Error('overview failed'); const member = overview.value.groups.flatMap((group) => group.members).find((item) => item.attendeeId === ids.ana); return { alerts: member?.alerts.map((alert) => alert.tipo) ?? [], overdue: member?.overduePayments.length ?? 0 }; }; const report = async () => { const result = await new ReportStudentPayment({ db, unitOfWork, storage, now: NOW }).execute(ids.account, { attendeeId: ids.ana, paymentIds: [ids.fee], file: { name: 'captura.png', bytes: PNG }, }); if (!result.ok) throw new Error(result.error.detail); return result.value.id; }; beforeAll(async () => { db = new PrismaClient({ adapter: new PrismaPg({ connectionString: url as string }) }); unitOfWork = new UnitOfWork(db); await db.user.createMany({ data: [ { id: ids.teacher, name: 'Caro', email: `${ids.teacher}@test.local`, country: 'AR' }, { id: ids.other, name: 'Otro', email: `${ids.other}@test.local`, country: 'AR' }, ], }); await db.group.create({ data: { id: ids.group, name: 'Natación', createdById: ids.teacher } }); await db.attendee.create({ data: { id: ids.ana, groupId: ids.group, fullName: 'Ana', createdAt: new Date('2026-01-01T00:00:00Z') } }); await db.studentAccount.create({ data: { id: ids.account, name: 'Ana', createdById: ids.teacher, recoveryEmail: 'ana@test.local', recoveryEmailVerifiedAt: NOW, attendees: { create: { attendeeId: ids.ana } }, }, }); await db.payment.create({ data: { id: ids.fee, groupId: ids.group, attendeeId: ids.ana, amount: new Prisma.Decimal(15000), currency: 'ARS', status: 'OVERDUE', dueDate: new Date('2026-09-10T12:00:00Z') }, }); }); afterAll(async () => { await db.user.deleteMany({ where: { id: { in: [ids.teacher, ids.other] } } }); await db.$disconnect(); }); it('un pago informado saca la cuota de la alerta y otro profe no lo ve', async () => { expect(await overdueFor()).toEqual({ alerts: ['pago'], overdue: 1 }); const reportId = await report(); expect(await overdueFor()).toEqual({ alerts: [], overdue: 0 }); const mine = await reviews().list(ids.teacher); if (!mine.ok) throw new Error('list failed'); expect(mine.value.data.map((item) => item.id)).toEqual([reportId]); expect(mine.value.data[0]?.receipt.thumbnailUrl).toContain('ttl=300'); const theirs = await reviews().list(ids.other); expect(theirs).toEqual({ ok: true, value: { data: [] } }); const foreign = await reviews().confirm(ids.other, reportId); expect(!foreign.ok && foreign.error.status).toBe(404); const foreignReceipt = await reviews().receiptUrl(ids.other, reportId); expect(foreignReceipt.ok).toBe(false); }); it('rechazar devuelve la alerta y deshacer la vuelve a sacar', async () => { const reportId = (await db.reportedPayment.findFirstOrThrow({ where: { attendeeId: ids.ana, status: 'REPORTED' } })).id; const rejected = await reviews().reject(ids.teacher, reportId, 'No se ve el monto'); expect(rejected.ok && rejected.value.status).toBe('rejected'); expect(notified).toContain(reportId); expect(await overdueFor()).toEqual({ alerts: ['pago'], overdue: 1 }); const again = await reviews().confirm(ids.teacher, reportId); expect(!again.ok && again.error.status).toBe(409); const undone = await reviews().undo(ids.teacher, reportId); expect(undone.ok && undone.value.status).toBe('reported'); expect(await overdueFor()).toEqual({ alerts: [], overdue: 0 }); }); it('confirmar marca las cuotas como pagadas; deshacer las vuelve a vencidas', async () => { const reportId = (await db.reportedPayment.findFirstOrThrow({ where: { attendeeId: ids.ana, status: 'REPORTED' } })).id; const confirmed = await reviews().confirm(ids.teacher, reportId); expect(confirmed.ok && confirmed.value.status).toBe('confirmed'); expect(await db.payment.findUniqueOrThrow({ where: { id: ids.fee } })).toMatchObject({ status: 'PAID', paidAt: NOW }); // Email only if the review still stands. const sent: string[] = []; const email = { sendStudentPaymentReviewed: async (data: { email: string }) => void sent.push(data.email) }; expect(await sendReviewNotification(reportId, NOW, { db, email })).toBe(true); expect(sent).toEqual(['ana@test.local']); const undone = await reviews().undo(ids.teacher, reportId); expect(undone.ok).toBe(true); expect(await db.payment.findUniqueOrThrow({ where: { id: ids.fee } })).toMatchObject({ status: 'OVERDUE', paidAt: null }); expect(await sendReviewNotification(reportId, NOW, { db, email })).toBe(false); }); it('deshacer vence a los pocos minutos', async () => { const reportId = (await db.reportedPayment.findFirstOrThrow({ where: { attendeeId: ids.ana, status: 'REPORTED' } })).id; expect((await reviews().confirm(ids.teacher, reportId)).ok).toBe(true); const late = await reviews(new Date(NOW.getTime() + 11 * 60 * 1000)).undo(ids.teacher, reportId); expect(!late.ok && late.error.status).toBe(409); }); });