From f1829fb5a9a33a54774e33d58b6a34fcd1a32ff6 Mon Sep 17 00:00:00 2001 From: Jose Selesan Date: Mon, 2 Nov 2026 16:21:32 -0300 Subject: [PATCH] feat: cambiar a un miembro de grupo MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - `POST /groups/:gid/attendees/:aid/move` mueve al mismo attendee a otro grupo del profesor: conserva historial, cuotas (siguen del grupo anterior) y acceso a la app de alumnos. Cancela las faltas avisadas y libera lo reservado en clases futuras del grupo anterior. - Cupo y teléfono duplicado se validan con `checkCanJoinGroup`, compartido con el paso desde la lista de espera. - Ficha del miembro: "Cambiar de grupo" abre un diálogo con el selector de grupo destino y navega a la ficha en el grupo nuevo. Co-Authored-By: Claude Opus 5.5 --- .../modules/attendees/features/move/route.ts | 24 ++ .../attendees/features/move/use-case.ts | 76 +++++++ .../src/modules/group-waitlist/lib/promote.ts | 46 ++-- apps/backend/src/modules/groups/routes.ts | 2 + apps/backend/test/attendee-move.test.ts | 211 ++++++++++++++++++ .../attendee-detail/AttendeeActionsMenu.tsx | 13 +- .../AttendeeDetailProvider.tsx | 62 +++++ .../attendee-detail/AttendeeDetailView.tsx | 2 + .../attendee-detail/ChangeGroupDialog.tsx | 143 ++++++++++++ apps/web/src/lib/api.ts | 7 + packages/shared/src/schemas/attendees.ts | 7 + 11 files changed, 571 insertions(+), 22 deletions(-) create mode 100644 apps/backend/src/modules/attendees/features/move/route.ts create mode 100644 apps/backend/src/modules/attendees/features/move/use-case.ts create mode 100644 apps/backend/test/attendee-move.test.ts create mode 100644 apps/web/src/features/attendee-detail/ChangeGroupDialog.tsx diff --git a/apps/backend/src/modules/attendees/features/move/route.ts b/apps/backend/src/modules/attendees/features/move/route.ts new file mode 100644 index 0000000..2b74ba0 --- /dev/null +++ b/apps/backend/src/modules/attendees/features/move/route.ts @@ -0,0 +1,24 @@ +import type { MoveAttendee as MoveAttendeeBody } from '@gruperly/shared'; +import { MoveAttendeeSchema } from '@gruperly/shared'; +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { validate } from '@/http/validate'; +import { MoveAttendee } from './use-case'; + +const route = new Hono(); + +route.post('/:groupId/attendees/:attendeeId/move', validate.json(MoveAttendeeSchema), async (c) => { + const user = c.get('user'); + if (!user) return problemJson(c, unauthorizedProblem(c.req.path)); + + const useCase = new MoveAttendee(); + const result = await useCase.execute({ + groupId: c.req.param('groupId'), + attendeeId: c.req.param('attendeeId'), + userId: user.id, + targetGroupId: (c.req.valid('json') as MoveAttendeeBody).targetGroupId, + }); + return resultJson(c, result); +}); + +export default route; diff --git a/apps/backend/src/modules/attendees/features/move/use-case.ts b/apps/backend/src/modules/attendees/features/move/use-case.ts new file mode 100644 index 0000000..54a625b --- /dev/null +++ b/apps/backend/src/modules/attendees/features/move/use-case.ts @@ -0,0 +1,76 @@ +import type { Prisma, PrismaClient } from '@generated/prisma/client'; +import type { AttendeeDto, ProblemDetails, Result } from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { conflictProblem, notFoundResourceProblem } from '@/http/problem-builders'; +import { default as prisma, UnitOfWork } from '@/lib/prisma'; +import { findGroupOwnedByUser } from '@/modules/group-waitlist/lib/helpers'; +import { checkCanJoinGroup } from '@/modules/group-waitlist/lib/promote'; +import { type AttendeeRecord, toAttendeeDto } from '../../lib/helpers'; + +type MoveAttendeeDeps = { + db?: Pick; + unitOfWork?: UnitOfWork; + now?: () => Date; +}; + +type MoveAttendeeCommand = { + groupId: string; + attendeeId: string; + userId: string; + targetGroupId: string; +}; + +/* Moves a member to another group of the same teacher. It is the same attendee + with another `groupId`: past attendance, fees (they stay owed to the old + group) and the student app access go with them. Only what was booked for + the old group's future classes is undone: absence notices, the EXCUSED rows + they left and the released slots. */ +export class MoveAttendee { + constructor(private readonly deps: MoveAttendeeDeps = {}) {} + + async execute(command: MoveAttendeeCommand): Promise> { + const { groupId, attendeeId, userId, targetGroupId } = command; + const db = this.deps.db ?? prisma; + const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma); + const now = this.deps.now?.() ?? new Date(); + + const sourceResult = await findGroupOwnedByUser(db, groupId, userId); + if (!sourceResult.ok) return sourceResult; + + const attendee = await db.attendee.findFirst({ where: { id: attendeeId, groupId } }); + if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId)); + + if (targetGroupId === groupId) { + return err( + conflictProblem({ + detail: 'El miembro ya pertenece a este grupo.', + code: 'attendee_same_group', + }), + ); + } + + const targetResult = await findGroupOwnedByUser(db, targetGroupId, userId); + if (!targetResult.ok) return targetResult; + + return unitOfWork.executeResult( + async (tx: Prisma.TransactionClient): Promise> => { + const canJoin = await checkCanJoinGroup(tx, targetResult.value, attendee.phone); + if (!canJoin.ok) return canJoin; + + const futureOldClasses = { classSession: { groupId, startsAt: { gt: now } } }; + await tx.absenceNotice.updateMany({ + where: { attendeeId, cancelledAt: null, ...futureOldClasses }, + data: { cancelledAt: now }, + }); + await tx.attendance.deleteMany({ where: { attendeeId, ...futureOldClasses } }); + await tx.slotRelease.deleteMany({ where: { attendeeId, isClaimed: false, ...futureOldClasses } }); + + const moved = await tx.attendee.update({ + where: { id: attendeeId }, + data: { groupId: targetGroupId }, + }); + return ok(toAttendeeDto(moved as unknown as AttendeeRecord)); + }, + ); + } +} diff --git a/apps/backend/src/modules/group-waitlist/lib/promote.ts b/apps/backend/src/modules/group-waitlist/lib/promote.ts index 8bd233d..fb72812 100644 --- a/apps/backend/src/modules/group-waitlist/lib/promote.ts +++ b/apps/backend/src/modules/group-waitlist/lib/promote.ts @@ -23,11 +23,14 @@ export async function findFirstPendingWaitlistEntry( return record as GroupWaitlistEntryRecord | null; } -export async function promoteWaitlistEntryRecord( - db: PromoteDb, +/* Whether someone can join `group`: free capacity (ACTIVE members) and no + member there with the same phone. Shared by the waitlist promotion and the + member move between groups. */ +export async function checkCanJoinGroup( + db: Pick, group: PromoteGroup, - entry: GroupWaitlistEntryRecord, -): Promise> { + phone: string | null, +): Promise> { if (group.capacity !== null) { const currentCount = await db.attendee.count({ where: { groupId: group.id, status: 'ACTIVE' }, @@ -37,16 +40,31 @@ export async function promoteWaitlistEntryRecord( } } - const existing = await db.attendee.findFirst({ - where: { groupId: group.id, phone: entry.phone }, - }); - if (existing) { - return err( - conflictProblem({ - detail: 'Ya existe un alumno registrado con este número de teléfono en este grupo.', - code: 'attendee_already_registered', - }), - ); + if (phone) { + const existing = await db.attendee.findFirst({ + where: { groupId: group.id, phone }, + }); + if (existing) { + return err( + conflictProblem({ + detail: 'Ya existe un alumno registrado con este número de teléfono en este grupo.', + code: 'attendee_already_registered', + }), + ); + } + } + + return ok(undefined); +} + +export async function promoteWaitlistEntryRecord( + db: PromoteDb, + group: PromoteGroup, + entry: GroupWaitlistEntryRecord, +): Promise> { + const canJoin = await checkCanJoinGroup(db, group, entry.phone); + if (!canJoin.ok) { + return canJoin; } const attendee = await db.attendee.create({ diff --git a/apps/backend/src/modules/groups/routes.ts b/apps/backend/src/modules/groups/routes.ts index 7c874a0..cee0eeb 100644 --- a/apps/backend/src/modules/groups/routes.ts +++ b/apps/backend/src/modules/groups/routes.ts @@ -5,6 +5,7 @@ import bulkCreateAttendeesRoute from '../attendees/features/bulk-create/route'; import createAttendeeRoute from '../attendees/features/create/route'; import getAttendeeRoute from '../attendees/features/get-by-id/route'; import getAttendeeStatsRoute from '../attendees/features/get-stats/route'; +import moveAttendeeRoute from '../attendees/features/move/route'; import removeAttendeeRoute from '../attendees/features/remove/route'; import updateAttendeeRoute from '../attendees/features/update/route'; import groupPreRegistrationRoutes from '../group-preregistrations/routes'; @@ -37,6 +38,7 @@ routes.route('/', getAttendeeRoute); routes.route('/', updateAttendeeRoute); routes.route('/', getAttendeeStatsRoute); routes.route('/', removeAttendeeRoute); +routes.route('/', moveAttendeeRoute); routes.route('/', studentAccessRoutes); export default routes; diff --git a/apps/backend/test/attendee-move.test.ts b/apps/backend/test/attendee-move.test.ts new file mode 100644 index 0000000..220d9e7 --- /dev/null +++ b/apps/backend/test/attendee-move.test.ts @@ -0,0 +1,211 @@ +import { beforeEach, describe, expect, it, mock, vi } from 'bun:test'; +import { Hono } from 'hono'; + +const db = { + group: { + findUnique: mock(), + }, + attendee: { + findFirst: mock(), + count: mock(), + update: mock(), + }, + absenceNotice: { + updateMany: mock(), + }, + attendance: { + deleteMany: mock(), + }, + slotRelease: { + deleteMany: mock(), + }, +}; + +mock.module('@/lib/prisma', () => ({ + default: db, + getPrismaClient: mock(), + UnitOfWork: class { + executeResult = mock(async (cb: (tx: unknown) => Promise) => cb(db)); + execute = mock(async (cb: (tx: unknown) => Promise) => cb(db)); + }, +})); + +import prisma from '@/lib/prisma'; +import { groupsRoutes } from '@/modules/groups'; + +const teacherId = 'teacher-1'; +const group = (overrides: Record = {}) => ({ + id: 'group-1', + name: 'Taller de Pintura', + description: null, + createdById: teacherId, + inviteToken: null, + createdAt: new Date('2026-09-01T10:00:00.000Z'), + updatedAt: new Date('2026-09-01T10:00:00.000Z'), + days: ['MONDAY'], + time: '18:00', + capacity: 20, + price: 1500, + billingType: 'MONTHLY', + dueDay: 10, + ...overrides, +}); +const targetGroup = (overrides: Record = {}) => + group({ id: 'group-2', name: 'Taller de Cerámica', ...overrides }); + +const attendee = (overrides: Record = {}) => ({ + id: 'att-1', + groupId: 'group-1', + fullName: 'Martín Gómez', + phone: '+5491133445566', + email: null, + guardianName: null, + guardianPhone: null, + notes: null, + notifyToken: 'notify-1', + status: 'ACTIVE', + createdAt: new Date('2026-09-18T10:00:00.000Z'), + updatedAt: new Date('2026-09-18T10:00:00.000Z'), + ...overrides, +}); + +function moveRequest(targetGroupId: string, userId = teacherId, attendeeId = 'att-1') { + const app = new Hono(); + app.use('*', async (c, next) => { + c.set('user', { id: userId } as never); + await next(); + }); + app.route('/groups', groupsRoutes); + return app.request(`/groups/group-1/attendees/${attendeeId}/move`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ targetGroupId }), + }); +} + +describe('POST /groups/:groupId/attendees/:attendeeId/move', () => { + beforeEach(() => { + vi.clearAllMocks(); + prisma.group.findUnique.mockReset(); + }); + + it('moves the member to the target group and undoes the old group future bookings', async () => { + prisma.group.findUnique + .mockResolvedValueOnce(group() as never) + .mockResolvedValueOnce(targetGroup() as never); + prisma.attendee.findFirst.mockResolvedValueOnce(attendee() as never).mockResolvedValueOnce(null); + prisma.attendee.count.mockResolvedValue(3); + prisma.attendee.update.mockResolvedValue(attendee({ groupId: 'group-2' }) as never); + + const res = await moveRequest('group-2'); + + expect(res.status).toBe(200); + const body = await res.json(); + expect(body.groupId).toBe('group-2'); + expect(prisma.attendee.update).toHaveBeenCalledWith({ + where: { id: 'att-1' }, + data: { groupId: 'group-2' }, + }); + const futureOldClasses = { + classSession: { groupId: 'group-1', startsAt: { gt: expect.any(Date) } }, + }; + expect(prisma.absenceNotice.updateMany).toHaveBeenCalledWith({ + where: { attendeeId: 'att-1', cancelledAt: null, ...futureOldClasses }, + data: { cancelledAt: expect.any(Date) }, + }); + expect(prisma.attendance.deleteMany).toHaveBeenCalledWith({ + where: { attendeeId: 'att-1', ...futureOldClasses }, + }); + expect(prisma.slotRelease.deleteMany).toHaveBeenCalledWith({ + where: { attendeeId: 'att-1', isClaimed: false, ...futureOldClasses }, + }); + }); + + it('rejects moving to the same group', async () => { + prisma.group.findUnique.mockResolvedValue(group() as never); + prisma.attendee.findFirst.mockResolvedValue(attendee() as never); + + const res = await moveRequest('group-1'); + + expect(res.status).toBe(409); + expect((await res.json()).code).toBe('attendee_same_group'); + expect(prisma.attendee.update).not.toHaveBeenCalled(); + }); + + it('rejects a target group owned by another teacher', async () => { + prisma.group.findUnique + .mockResolvedValueOnce(group() as never) + .mockResolvedValueOnce(targetGroup({ createdById: 'other-user' }) as never); + prisma.attendee.findFirst.mockResolvedValue(attendee() as never); + + const res = await moveRequest('group-2'); + + expect(res.status).toBe(403); + expect(prisma.attendee.update).not.toHaveBeenCalled(); + }); + + it('returns 404 when the target group does not exist', async () => { + prisma.group.findUnique.mockResolvedValueOnce(group() as never).mockResolvedValueOnce(null); + prisma.attendee.findFirst.mockResolvedValue(attendee() as never); + + const res = await moveRequest('group-missing'); + + expect(res.status).toBe(404); + expect(prisma.attendee.update).not.toHaveBeenCalled(); + }); + + it('rejects with 409 when the target group reached its capacity', async () => { + prisma.group.findUnique + .mockResolvedValueOnce(group() as never) + .mockResolvedValueOnce(targetGroup({ capacity: 5 }) as never); + prisma.attendee.findFirst.mockResolvedValue(attendee() as never); + prisma.attendee.count.mockResolvedValue(5); + + const res = await moveRequest('group-2'); + + expect(res.status).toBe(409); + expect((await res.json()).code).toBe('group_capacity_reached'); + expect(prisma.attendee.update).not.toHaveBeenCalled(); + expect(prisma.absenceNotice.updateMany).not.toHaveBeenCalled(); + }); + + it('rejects with 409 when the phone already belongs to a member of the target group', async () => { + prisma.group.findUnique + .mockResolvedValueOnce(group() as never) + .mockResolvedValueOnce(targetGroup() as never); + prisma.attendee.findFirst + .mockResolvedValueOnce(attendee() as never) + .mockResolvedValueOnce({ id: 'att-existing' } as never); + prisma.attendee.count.mockResolvedValue(3); + + const res = await moveRequest('group-2'); + + expect(res.status).toBe(409); + expect((await res.json()).code).toBe('attendee_already_registered'); + expect(prisma.attendee.update).not.toHaveBeenCalled(); + }); + + it('returns 404 when the member is not in the group', async () => { + prisma.group.findUnique.mockResolvedValue(group() as never); + prisma.attendee.findFirst.mockResolvedValue(null); + + const res = await moveRequest('group-2', teacherId, 'att-missing'); + + expect(res.status).toBe(404); + }); + + it('rejects a non-owner user', async () => { + prisma.group.findUnique.mockResolvedValue(group() as never); + + const res = await moveRequest('group-2', 'other-user'); + + expect(res.status).toBe(403); + expect(prisma.attendee.update).not.toHaveBeenCalled(); + }); + + it('returns 400 without a target group', async () => { + const res = await moveRequest(''); + + expect(res.status).toBe(400); + }); +}); diff --git a/apps/web/src/features/attendee-detail/AttendeeActionsMenu.tsx b/apps/web/src/features/attendee-detail/AttendeeActionsMenu.tsx index 5f5bae8..c3d7e6f 100644 --- a/apps/web/src/features/attendee-detail/AttendeeActionsMenu.tsx +++ b/apps/web/src/features/attendee-detail/AttendeeActionsMenu.tsx @@ -15,7 +15,7 @@ export function AttendeeActionsMenu({ * when it closes. */ triggerRef: RefObject }) { - const { beginContactEdit, openRemoveDialog } = useAttendeeDetail() + const { beginContactEdit, openRemoveDialog, openChangeGroupDialog } = useAttendeeDetail() const toast = useToast() const [isOpen, setIsOpen] = useState(false) const menuRef = useRef(null) @@ -69,12 +69,6 @@ export function AttendeeActionsMenu({ items[next]?.focus() } - const showPendingChangeGroup = () => { - close() - // TODO(miembros): navegar al selector cuando se confirmen las reglas y exista el endpoint. - toast.info('Cambiar de grupo estará disponible cuando se confirme el flujo de traspaso.') - } - const showPendingPause = () => { close() // TODO(miembros): conectar la pausa cuando se defina su efecto sobre cupos y cobros. @@ -110,7 +104,10 @@ export function AttendeeActionsMenu({ type="button" role="menuitem" className={ITEM_CLASS} - onClick={showPendingChangeGroup} + onClick={() => { + close() + openChangeGroupDialog() + }} >