Files
gruperly/apps/backend/test/attendee-update.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

141 lines
4.1 KiB
TypeScript

import { beforeEach, describe, expect, it, mock, vi } from 'bun:test'
import { Prisma } from '@generated/prisma/client'
import { Hono } from 'hono'
const db = {
group: { findUnique: mock() },
attendee: { findFirst: mock(), findUniqueOrThrow: mock() },
person: { update: mock() },
}
mock.module('@/lib/prisma', () => ({
default: db,
getPrismaClient: mock(),
UnitOfWork: class {},
}))
import updateAttendeeRoute from '@/modules/attendees/features/update/route'
const userId = 'user-1'
const person = {
id: 'person-1',
fullName: 'Ana Pérez',
email: null,
phone: null,
guardianName: null,
guardianPhone: null,
notes: 'Llega temprano',
}
const attendee = {
id: 'a-1',
groupId: 'group-1',
personId: 'person-1',
person,
notifyToken: 'token-1',
createdAt: new Date('2026-08-01T10:00:00.000Z'),
updatedAt: new Date('2026-10-01T12:00:00.000Z'),
}
function makeApp() {
const app = new Hono()
app.use('*', async (context, next) => {
context.set('user', { id: userId } as never)
await next()
})
app.route('/groups', updateAttendeeRoute)
return app
}
describe('PATCH /groups/:groupId/attendees/:attendeeId', () => {
beforeEach(() => {
vi.clearAllMocks()
db.group.findUnique.mockResolvedValue({
id: 'group-1',
name: 'Funcional',
createdById: userId,
members: [],
})
db.attendee.findFirst.mockResolvedValue(attendee)
})
it('actualiza el contacto de la persona y conserva los campos vacíos como null', async () => {
db.attendee.findUniqueOrThrow.mockResolvedValue({
...attendee,
person: { ...person, email: 'ana@example.com' },
})
const response = await makeApp().request('/groups/group-1/attendees/a-1', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email: 'ana@example.com', phone: '' }),
})
expect(response.status).toBe(200)
expect(await response.json()).toMatchObject({ id: 'a-1', personId: 'person-1', email: 'ana@example.com' })
// The person's row: the change shows in every group they are in.
expect(db.person.update).toHaveBeenCalledWith({
where: { id: 'person-1' },
data: { email: 'ana@example.com', phone: null },
})
})
it('normaliza el teléfono como el alta', async () => {
db.attendee.findUniqueOrThrow.mockResolvedValue(attendee)
await makeApp().request('/groups/group-1/attendees/a-1', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ phone: '11 2345-6789' }),
})
expect(db.person.update).toHaveBeenCalledWith({
where: { id: 'person-1' },
data: { phone: '1123456789' },
})
})
it('devuelve 409 si el teléfono ya es de otra persona del profe', async () => {
db.person.update.mockRejectedValueOnce(
new Prisma.PrismaClientKnownRequestError('Unique constraint failed', {
code: 'P2002',
clientVersion: 'test',
}),
)
const response = await makeApp().request('/groups/group-1/attendees/a-1', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ phone: '1123456789' }),
})
expect(response.status).toBe(409)
expect(await response.json()).toMatchObject({ code: 'person_phone_taken' })
})
it('actualiza una única nota', async () => {
db.attendee.findUniqueOrThrow.mockResolvedValue({ ...attendee, person: { ...person, notes: 'Traer colchoneta' } })
await makeApp().request('/groups/group-1/attendees/a-1', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ notes: 'Traer colchoneta' }),
})
expect(db.person.update).toHaveBeenCalledWith({
where: { id: 'person-1' },
data: { notes: 'Traer colchoneta' },
})
})
it('rechaza un email inválido', async () => {
const response = await makeApp().request('/groups/group-1/attendees/a-1', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email: 'sin-arroba' }),
})
expect(response.status).toBe(400)
expect(db.person.update).not.toHaveBeenCalled()
})
})