Files
gruperly/apps/backend/test/db/payment-review.db.test.ts
Jose Selesan d21e1c3730 feat: un miembro puede pertenecer a más de un grupo
- Nuevo modelo `Person` (`people`): contacto y notas por profe, con
  teléfono único (índice parcial `people_owner_phone_key`). `Attendee`
  pasa a ser la membresía (`group_id` + `person_id`, único por grupo).
- La cuenta de la app de alumnos se vincula a la persona
  (`student_account_people`): una sola cuenta ve todos sus grupos.
- Migración unifica attendees del mismo profe y teléfono, y fusiona sus
  cuentas de alumno (conserva la usada más recientemente).
- `POST /groups/:gid/attendees/:aid/add-to-group` y
  `GET /people/lookup` para detectar personas existentes al cargar;
  el alta responde `409 person_exists` y acepta `personId`. Bulk, lista
  de espera y preinscripciones vinculan solas.
- El límite del plan cuenta personas con al menos un grupo activo.
- Web: "Agregar a otro grupo", sección "También está en" en la ficha y
  aviso "Ya tenés a esta persona" en el alta individual.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 09:46:37 -03:00

148 lines
7.1 KiB
TypeScript

/* 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.person.create({ data: { id: `${ids.ana}-person`, createdById: ids.teacher, fullName: 'Ana' } });
await db.attendee.create({
data: { id: ids.ana, groupId: ids.group, personId: `${ids.ana}-person`, 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,
people: { create: { personId: `${ids.ana}-person` } },
},
});
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);
});
});