development #14
24
apps/backend/src/modules/attendees/features/move/route.ts
Normal file
24
apps/backend/src/modules/attendees/features/move/route.ts
Normal file
@@ -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;
|
||||||
76
apps/backend/src/modules/attendees/features/move/use-case.ts
Normal file
76
apps/backend/src/modules/attendees/features/move/use-case.ts
Normal file
@@ -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<PrismaClient, 'group' | 'attendee'>;
|
||||||
|
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<Result<AttendeeDto, ProblemDetails>> {
|
||||||
|
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<Result<AttendeeDto, ProblemDetails>> => {
|
||||||
|
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));
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -23,11 +23,14 @@ export async function findFirstPendingWaitlistEntry(
|
|||||||
return record as GroupWaitlistEntryRecord | null;
|
return record as GroupWaitlistEntryRecord | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function promoteWaitlistEntryRecord(
|
/* Whether someone can join `group`: free capacity (ACTIVE members) and no
|
||||||
db: PromoteDb,
|
member there with the same phone. Shared by the waitlist promotion and the
|
||||||
|
member move between groups. */
|
||||||
|
export async function checkCanJoinGroup(
|
||||||
|
db: Pick<PrismaClient, 'attendee'>,
|
||||||
group: PromoteGroup,
|
group: PromoteGroup,
|
||||||
entry: GroupWaitlistEntryRecord,
|
phone: string | null,
|
||||||
): Promise<Result<AttendeeDto, ProblemDetails>> {
|
): Promise<Result<void, ProblemDetails>> {
|
||||||
if (group.capacity !== null) {
|
if (group.capacity !== null) {
|
||||||
const currentCount = await db.attendee.count({
|
const currentCount = await db.attendee.count({
|
||||||
where: { groupId: group.id, status: 'ACTIVE' },
|
where: { groupId: group.id, status: 'ACTIVE' },
|
||||||
@@ -37,16 +40,31 @@ export async function promoteWaitlistEntryRecord(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const existing = await db.attendee.findFirst({
|
if (phone) {
|
||||||
where: { groupId: group.id, phone: entry.phone },
|
const existing = await db.attendee.findFirst({
|
||||||
});
|
where: { groupId: group.id, phone },
|
||||||
if (existing) {
|
});
|
||||||
return err(
|
if (existing) {
|
||||||
conflictProblem({
|
return err(
|
||||||
detail: 'Ya existe un alumno registrado con este número de teléfono en este grupo.',
|
conflictProblem({
|
||||||
code: 'attendee_already_registered',
|
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<Result<AttendeeDto, ProblemDetails>> {
|
||||||
|
const canJoin = await checkCanJoinGroup(db, group, entry.phone);
|
||||||
|
if (!canJoin.ok) {
|
||||||
|
return canJoin;
|
||||||
}
|
}
|
||||||
|
|
||||||
const attendee = await db.attendee.create({
|
const attendee = await db.attendee.create({
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import bulkCreateAttendeesRoute from '../attendees/features/bulk-create/route';
|
|||||||
import createAttendeeRoute from '../attendees/features/create/route';
|
import createAttendeeRoute from '../attendees/features/create/route';
|
||||||
import getAttendeeRoute from '../attendees/features/get-by-id/route';
|
import getAttendeeRoute from '../attendees/features/get-by-id/route';
|
||||||
import getAttendeeStatsRoute from '../attendees/features/get-stats/route';
|
import getAttendeeStatsRoute from '../attendees/features/get-stats/route';
|
||||||
|
import moveAttendeeRoute from '../attendees/features/move/route';
|
||||||
import removeAttendeeRoute from '../attendees/features/remove/route';
|
import removeAttendeeRoute from '../attendees/features/remove/route';
|
||||||
import updateAttendeeRoute from '../attendees/features/update/route';
|
import updateAttendeeRoute from '../attendees/features/update/route';
|
||||||
import groupPreRegistrationRoutes from '../group-preregistrations/routes';
|
import groupPreRegistrationRoutes from '../group-preregistrations/routes';
|
||||||
@@ -37,6 +38,7 @@ routes.route('/', getAttendeeRoute);
|
|||||||
routes.route('/', updateAttendeeRoute);
|
routes.route('/', updateAttendeeRoute);
|
||||||
routes.route('/', getAttendeeStatsRoute);
|
routes.route('/', getAttendeeStatsRoute);
|
||||||
routes.route('/', removeAttendeeRoute);
|
routes.route('/', removeAttendeeRoute);
|
||||||
|
routes.route('/', moveAttendeeRoute);
|
||||||
routes.route('/', studentAccessRoutes);
|
routes.route('/', studentAccessRoutes);
|
||||||
|
|
||||||
export default routes;
|
export default routes;
|
||||||
|
|||||||
211
apps/backend/test/attendee-move.test.ts
Normal file
211
apps/backend/test/attendee-move.test.ts
Normal file
@@ -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<unknown>) => cb(db));
|
||||||
|
execute = mock(async (cb: (tx: unknown) => Promise<unknown>) => cb(db));
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
import prisma from '@/lib/prisma';
|
||||||
|
import { groupsRoutes } from '@/modules/groups';
|
||||||
|
|
||||||
|
const teacherId = 'teacher-1';
|
||||||
|
const group = (overrides: Record<string, unknown> = {}) => ({
|
||||||
|
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<string, unknown> = {}) =>
|
||||||
|
group({ id: 'group-2', name: 'Taller de Cerámica', ...overrides });
|
||||||
|
|
||||||
|
const attendee = (overrides: Record<string, unknown> = {}) => ({
|
||||||
|
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);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -15,7 +15,7 @@ export function AttendeeActionsMenu({
|
|||||||
* when it closes. */
|
* when it closes. */
|
||||||
triggerRef: RefObject<HTMLButtonElement | null>
|
triggerRef: RefObject<HTMLButtonElement | null>
|
||||||
}) {
|
}) {
|
||||||
const { beginContactEdit, openRemoveDialog } = useAttendeeDetail()
|
const { beginContactEdit, openRemoveDialog, openChangeGroupDialog } = useAttendeeDetail()
|
||||||
const toast = useToast()
|
const toast = useToast()
|
||||||
const [isOpen, setIsOpen] = useState(false)
|
const [isOpen, setIsOpen] = useState(false)
|
||||||
const menuRef = useRef<HTMLDivElement>(null)
|
const menuRef = useRef<HTMLDivElement>(null)
|
||||||
@@ -69,12 +69,6 @@ export function AttendeeActionsMenu({
|
|||||||
items[next]?.focus()
|
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 = () => {
|
const showPendingPause = () => {
|
||||||
close()
|
close()
|
||||||
// TODO(miembros): conectar la pausa cuando se defina su efecto sobre cupos y cobros.
|
// TODO(miembros): conectar la pausa cuando se defina su efecto sobre cupos y cobros.
|
||||||
@@ -110,7 +104,10 @@ export function AttendeeActionsMenu({
|
|||||||
type="button"
|
type="button"
|
||||||
role="menuitem"
|
role="menuitem"
|
||||||
className={ITEM_CLASS}
|
className={ITEM_CLASS}
|
||||||
onClick={showPendingChangeGroup}
|
onClick={() => {
|
||||||
|
close()
|
||||||
|
openChangeGroupDialog()
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
<MoveRight className="size-4 shrink-0 text-secondary" aria-hidden="true" />
|
<MoveRight className="size-4 shrink-0 text-secondary" aria-hidden="true" />
|
||||||
Cambiar de grupo
|
Cambiar de grupo
|
||||||
|
|||||||
@@ -5,14 +5,19 @@ import { useNavigate } from '@tanstack/react-router'
|
|||||||
import type {
|
import type {
|
||||||
AttendeeDetailDto,
|
AttendeeDetailDto,
|
||||||
AttendeeHistory,
|
AttendeeHistory,
|
||||||
|
GroupListItem,
|
||||||
GroupWaitlistEntryDto,
|
GroupWaitlistEntryDto,
|
||||||
UpdateAttendee,
|
UpdateAttendee,
|
||||||
} from '@gruperly/shared'
|
} from '@gruperly/shared'
|
||||||
|
import { useToast } from '../../components/ui'
|
||||||
import {
|
import {
|
||||||
|
ApiError,
|
||||||
getAttendeeHistory,
|
getAttendeeHistory,
|
||||||
getGroup,
|
getGroup,
|
||||||
getGroupAttendee,
|
getGroupAttendee,
|
||||||
|
getGroups,
|
||||||
getGroupWaitlist,
|
getGroupWaitlist,
|
||||||
|
moveGroupAttendee,
|
||||||
updateGroupAttendee,
|
updateGroupAttendee,
|
||||||
} from '../../lib/api'
|
} from '../../lib/api'
|
||||||
import { useRemoveAttendee } from '../groups/detail/useRemoveAttendee'
|
import { useRemoveAttendee } from '../groups/detail/useRemoveAttendee'
|
||||||
@@ -39,6 +44,14 @@ type AttendeeDetailContextValue = {
|
|||||||
closeRemoveDialog: () => void
|
closeRemoveDialog: () => void
|
||||||
confirmRemoveAttendee: (promoteFromWaitlist: boolean) => void
|
confirmRemoveAttendee: (promoteFromWaitlist: boolean) => void
|
||||||
isSubmittingRemoval: boolean
|
isSubmittingRemoval: boolean
|
||||||
|
isChangeGroupDialogOpen: boolean
|
||||||
|
openChangeGroupDialog: () => void
|
||||||
|
closeChangeGroupDialog: () => void
|
||||||
|
/** Grupos del profe (incluye el actual); se piden al abrir el diálogo. */
|
||||||
|
groups: GroupListItem[]
|
||||||
|
groupsPending: boolean
|
||||||
|
moveToGroup: (targetGroupId: string) => void
|
||||||
|
isMovingAttendee: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
const AttendeeDetailContext = createContext<AttendeeDetailContextValue | null>(null)
|
const AttendeeDetailContext = createContext<AttendeeDetailContextValue | null>(null)
|
||||||
@@ -54,7 +67,9 @@ export function AttendeeDetailProvider({
|
|||||||
}) {
|
}) {
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient()
|
||||||
|
const toast = useToast()
|
||||||
const [isRemoveDialogOpen, setIsRemoveDialogOpen] = useState(false)
|
const [isRemoveDialogOpen, setIsRemoveDialogOpen] = useState(false)
|
||||||
|
const [isChangeGroupDialogOpen, setIsChangeGroupDialogOpen] = useState(false)
|
||||||
const [isEditingContact, setIsEditingContact] = useState(false)
|
const [isEditingContact, setIsEditingContact] = useState(false)
|
||||||
|
|
||||||
const groupQuery = useQuery({
|
const groupQuery = useQuery({
|
||||||
@@ -108,6 +123,46 @@ export function AttendeeDetailProvider({
|
|||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// Misma key que Grupos y Cobros: el diálogo reusa el caché si ya está.
|
||||||
|
const groupsQuery = useQuery({
|
||||||
|
queryKey: ['groups'],
|
||||||
|
queryFn: getGroups,
|
||||||
|
enabled: isChangeGroupDialogOpen,
|
||||||
|
})
|
||||||
|
const groups = groupsQuery.data?.data ?? []
|
||||||
|
|
||||||
|
const moveMutation = useMutation({
|
||||||
|
mutationFn: (targetGroupId: string) => moveGroupAttendee(groupId, attendeeId, targetGroupId),
|
||||||
|
onSuccess: (moved, targetGroupId) => {
|
||||||
|
const targetName = groups.find((group) => group.id === targetGroupId)?.name ?? 'otro grupo'
|
||||||
|
toast.success(`${moved.fullName} pasó a ${targetName}.`)
|
||||||
|
for (const id of [groupId, targetGroupId]) {
|
||||||
|
void queryClient.invalidateQueries({ queryKey: ['group-attendees', id] })
|
||||||
|
void queryClient.invalidateQueries({ queryKey: ['group', id] })
|
||||||
|
}
|
||||||
|
void queryClient.invalidateQueries({ queryKey: ['groups'] })
|
||||||
|
void queryClient.invalidateQueries({ queryKey: ['attention'] })
|
||||||
|
setIsChangeGroupDialogOpen(false)
|
||||||
|
// La ficha vive bajo el grupo: pasa a la URL del grupo nuevo sin dejar la
|
||||||
|
// vieja en el historial (ya no existe).
|
||||||
|
void navigate({
|
||||||
|
to: '/groups/$groupId/attendees/$attendeeId',
|
||||||
|
params: { groupId: targetGroupId, attendeeId },
|
||||||
|
replace: true,
|
||||||
|
})
|
||||||
|
},
|
||||||
|
onError: (err: Error) => {
|
||||||
|
const code = err instanceof ApiError ? err.problem?.code : undefined
|
||||||
|
if (code === 'group_capacity_reached') {
|
||||||
|
toast.error('Ese grupo alcanzó su cupo. Elegí otro o liberá un lugar primero.')
|
||||||
|
} else if (code === 'attendee_already_registered') {
|
||||||
|
toast.error('En ese grupo ya hay un miembro con el mismo teléfono.')
|
||||||
|
} else {
|
||||||
|
toast.error(err.message || 'No se pudo cambiar de grupo.')
|
||||||
|
}
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
const value: AttendeeDetailContextValue = {
|
const value: AttendeeDetailContextValue = {
|
||||||
groupId,
|
groupId,
|
||||||
groupName: groupQuery.data?.name,
|
groupName: groupQuery.data?.name,
|
||||||
@@ -135,6 +190,13 @@ export function AttendeeDetailProvider({
|
|||||||
removeAttendee({ attendee: attendeeQuery.data, promoteFromWaitlist })
|
removeAttendee({ attendee: attendeeQuery.data, promoteFromWaitlist })
|
||||||
},
|
},
|
||||||
isSubmittingRemoval: isRemovingAttendee,
|
isSubmittingRemoval: isRemovingAttendee,
|
||||||
|
isChangeGroupDialogOpen,
|
||||||
|
openChangeGroupDialog: () => setIsChangeGroupDialogOpen(true),
|
||||||
|
closeChangeGroupDialog: () => setIsChangeGroupDialogOpen(false),
|
||||||
|
groups,
|
||||||
|
groupsPending: groupsQuery.isPending,
|
||||||
|
moveToGroup: (targetGroupId) => moveMutation.mutate(targetGroupId),
|
||||||
|
isMovingAttendee: moveMutation.isPending,
|
||||||
}
|
}
|
||||||
|
|
||||||
return <AttendeeDetailContext.Provider value={value}>{children}</AttendeeDetailContext.Provider>
|
return <AttendeeDetailContext.Provider value={value}>{children}</AttendeeDetailContext.Provider>
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import { AttendeeContactSection } from './AttendeeContactSection'
|
|||||||
import { AttendeeNotesSection } from './AttendeeNotesSection'
|
import { AttendeeNotesSection } from './AttendeeNotesSection'
|
||||||
import { AttendeePaymentsSection } from './AttendeePaymentsSection'
|
import { AttendeePaymentsSection } from './AttendeePaymentsSection'
|
||||||
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
||||||
|
import { ChangeGroupDialog } from './ChangeGroupDialog'
|
||||||
import { ConfirmRemoveAttendeeDialog } from './ConfirmRemoveAttendeeDialog'
|
import { ConfirmRemoveAttendeeDialog } from './ConfirmRemoveAttendeeDialog'
|
||||||
import { formatMemberSince } from './attendance'
|
import { formatMemberSince } from './attendance'
|
||||||
import { paymentPresentation } from './detail'
|
import { paymentPresentation } from './detail'
|
||||||
@@ -97,6 +98,7 @@ export function AttendeeDetailView() {
|
|||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
<ConfirmRemoveAttendeeDialog returnFocusRef={menuTriggerRef} />
|
<ConfirmRemoveAttendeeDialog returnFocusRef={menuTriggerRef} />
|
||||||
|
<ChangeGroupDialog returnFocusRef={menuTriggerRef} />
|
||||||
</section>
|
</section>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
143
apps/web/src/features/attendee-detail/ChangeGroupDialog.tsx
Normal file
143
apps/web/src/features/attendee-detail/ChangeGroupDialog.tsx
Normal file
@@ -0,0 +1,143 @@
|
|||||||
|
import { useEffect, useRef, useState } from 'react'
|
||||||
|
import type { RefObject } from 'react'
|
||||||
|
import type { GroupListItem } from '@gruperly/shared'
|
||||||
|
import type { LucideIcon } from 'lucide-react'
|
||||||
|
import { CalendarX, History, Loader2, MoveRight, Wallet } from 'lucide-react'
|
||||||
|
import { Button, Modal } from '../../components/ui'
|
||||||
|
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
||||||
|
|
||||||
|
type Consequence = { key: string; icon: LucideIcon; text: string }
|
||||||
|
|
||||||
|
function isFull(group: GroupListItem): boolean {
|
||||||
|
return group.capacity != null && group.attendeesCount >= group.capacity
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ChangeGroupDialog({
|
||||||
|
returnFocusRef,
|
||||||
|
}: {
|
||||||
|
/** The element focus returns to when it closes (the "⋯" button). */
|
||||||
|
returnFocusRef: RefObject<HTMLButtonElement | null>
|
||||||
|
}) {
|
||||||
|
const {
|
||||||
|
groupId,
|
||||||
|
attendee,
|
||||||
|
groupName,
|
||||||
|
groups,
|
||||||
|
groupsPending,
|
||||||
|
isChangeGroupDialogOpen,
|
||||||
|
closeChangeGroupDialog,
|
||||||
|
moveToGroup,
|
||||||
|
isMovingAttendee,
|
||||||
|
} = useAttendeeDetail()
|
||||||
|
|
||||||
|
const [targetGroupId, setTargetGroupId] = useState('')
|
||||||
|
const wasOpen = useRef(false)
|
||||||
|
|
||||||
|
// Cada apertura arranca sin destino elegido; al cerrar, el foco vuelve al "⋯".
|
||||||
|
useEffect(() => {
|
||||||
|
if (isChangeGroupDialogOpen) {
|
||||||
|
wasOpen.current = true
|
||||||
|
setTargetGroupId('')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (!wasOpen.current) return
|
||||||
|
wasOpen.current = false
|
||||||
|
returnFocusRef.current?.focus()
|
||||||
|
}, [isChangeGroupDialogOpen, returnFocusRef])
|
||||||
|
|
||||||
|
if (!attendee) return null
|
||||||
|
|
||||||
|
const otherGroups = groups.filter((group) => group.id !== groupId)
|
||||||
|
const currentName = groupName ?? 'el grupo actual'
|
||||||
|
|
||||||
|
const consequences: Consequence[] = [
|
||||||
|
{
|
||||||
|
key: 'historial',
|
||||||
|
icon: History,
|
||||||
|
text: 'Conserva su historial, sus cuotas y su acceso a la app de alumnos.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'cuotas',
|
||||||
|
icon: Wallet,
|
||||||
|
text: `Las cuotas pendientes de ${currentName} siguen vigentes.`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'faltas',
|
||||||
|
icon: CalendarX,
|
||||||
|
text: `Se cancelan las faltas avisadas para clases futuras de ${currentName}.`,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Modal
|
||||||
|
isOpen={isChangeGroupDialogOpen}
|
||||||
|
onClose={closeChangeGroupDialog}
|
||||||
|
title="Cambiar de grupo"
|
||||||
|
description={`${attendee.fullName}${groupName ? ` · ${groupName}` : ''}`}
|
||||||
|
maxWidth="sm"
|
||||||
|
>
|
||||||
|
<div className="space-y-4">
|
||||||
|
{groupsPending ? (
|
||||||
|
<div className="flex justify-center py-4">
|
||||||
|
<Loader2 className="size-5 animate-spin text-foreground/60" aria-label="Cargando grupos" />
|
||||||
|
</div>
|
||||||
|
) : otherGroups.length === 0 ? (
|
||||||
|
<p className="rounded-xl border border-border bg-primary-soft/30 px-4 py-3 text-sm text-foreground/70">
|
||||||
|
No tenés otros grupos. Creá uno para poder mover a este miembro.
|
||||||
|
</p>
|
||||||
|
) : (
|
||||||
|
<label className="block">
|
||||||
|
<span className="mb-1.5 block text-sm font-medium text-primary">Mover a</span>
|
||||||
|
<select
|
||||||
|
autoFocus
|
||||||
|
value={targetGroupId}
|
||||||
|
onChange={(event) => setTargetGroupId(event.target.value)}
|
||||||
|
className="h-10 w-full rounded-xl border border-border bg-surface px-3 text-base text-primary sm:text-sm focus:border-accent focus:outline-none focus:ring-2 focus:ring-accent/30"
|
||||||
|
>
|
||||||
|
<option value="" disabled>
|
||||||
|
Elegí un grupo
|
||||||
|
</option>
|
||||||
|
{otherGroups.map((group) => {
|
||||||
|
const full = isFull(group)
|
||||||
|
return (
|
||||||
|
<option key={group.id} value={group.id} disabled={full}>
|
||||||
|
{group.name}
|
||||||
|
{full ? ' (sin cupo)' : ''}
|
||||||
|
</option>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<ul className="space-y-2.5">
|
||||||
|
{consequences.map(({ icon: Icon, key, text }) => (
|
||||||
|
<li key={key} className="flex items-start gap-2.5 text-sm text-foreground">
|
||||||
|
<Icon className="mt-0.5 size-4 shrink-0" aria-hidden="true" />
|
||||||
|
<span>{text}</span>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
<div className="flex flex-col-reverse gap-2.5 border-t border-border pt-3 sm:flex-row sm:justify-end">
|
||||||
|
<Button variant="ghost" onClick={closeChangeGroupDialog}>
|
||||||
|
Cancelar
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="primary"
|
||||||
|
onClick={() => moveToGroup(targetGroupId)}
|
||||||
|
disabled={!targetGroupId || isMovingAttendee}
|
||||||
|
className="gap-2"
|
||||||
|
>
|
||||||
|
{isMovingAttendee ? (
|
||||||
|
<Loader2 className="size-4 animate-spin" />
|
||||||
|
) : (
|
||||||
|
<MoveRight className="size-4" />
|
||||||
|
)}
|
||||||
|
<span>Cambiar de grupo</span>
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -316,6 +316,13 @@ export const updateGroupAttendee = (
|
|||||||
body: JSON.stringify(payload),
|
body: JSON.stringify(payload),
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// Mueve al miembro a otro grupo del profe; devuelve el attendee con su nuevo `groupId`.
|
||||||
|
export const moveGroupAttendee = (groupId: string, attendeeId: string, targetGroupId: string) =>
|
||||||
|
apiFetch<AttendeeDto>(`/api/v1/groups/${groupId}/attendees/${attendeeId}/move`, {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ targetGroupId }),
|
||||||
|
})
|
||||||
|
|
||||||
export const getGroupWaitlist = (groupId: string, page = 1, pageSize = 100) =>
|
export const getGroupWaitlist = (groupId: string, page = 1, pageSize = 100) =>
|
||||||
apiFetch<GroupWaitlistList>(`/api/v1/groups/${groupId}/waitlist?page=${page}&pageSize=${pageSize}`)
|
apiFetch<GroupWaitlistList>(`/api/v1/groups/${groupId}/waitlist?page=${page}&pageSize=${pageSize}`)
|
||||||
|
|
||||||
|
|||||||
@@ -168,6 +168,13 @@ export const PromoteGroupWaitlistEntrySchema = z.object({
|
|||||||
});
|
});
|
||||||
export type PromoteGroupWaitlistEntry = z.output<typeof PromoteGroupWaitlistEntrySchema>;
|
export type PromoteGroupWaitlistEntry = z.output<typeof PromoteGroupWaitlistEntrySchema>;
|
||||||
|
|
||||||
|
// Moves a member to another group of the same teacher. History, fees and the
|
||||||
|
// student app access go with them (it is the same attendee).
|
||||||
|
export const MoveAttendeeSchema = z.object({
|
||||||
|
targetGroupId: z.string().min(1),
|
||||||
|
});
|
||||||
|
export type MoveAttendee = z.output<typeof MoveAttendeeSchema>;
|
||||||
|
|
||||||
export const PromoteGroupWaitlistEntryResultSchema = z.object({
|
export const PromoteGroupWaitlistEntryResultSchema = z.object({
|
||||||
attendee: AttendeeDtoSchema,
|
attendee: AttendeeDtoSchema,
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user