feat: add attendee detail and stats features
- Implemented API endpoints to fetch attendee details and statistics. - Created new route for fetching attendee by ID and their attendance stats. - Added schemas for attendee statistics. - Developed frontend components to display attendee details and attendance statistics. - Integrated attendee detail provider to manage state and data fetching. - Added tests for attendee retrieval and statistics calculation.
This commit is contained in:
@@ -0,0 +1,20 @@
|
|||||||
|
import { Hono } from 'hono';
|
||||||
|
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||||
|
import { GetAttendee } from './use-case';
|
||||||
|
|
||||||
|
const route = new Hono();
|
||||||
|
|
||||||
|
route.get('/:groupId/attendees/:attendeeId', async (c) => {
|
||||||
|
const user = c.get('user');
|
||||||
|
if (!user) {
|
||||||
|
return problemJson(c, unauthorizedProblem(c.req.path));
|
||||||
|
}
|
||||||
|
const groupId = c.req.param('groupId');
|
||||||
|
const attendeeId = c.req.param('attendeeId');
|
||||||
|
const useCase = new GetAttendee();
|
||||||
|
const result = await useCase.execute(groupId, attendeeId, user.id);
|
||||||
|
|
||||||
|
return resultJson(c, result);
|
||||||
|
});
|
||||||
|
|
||||||
|
export default route;
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import type { PrismaClient } from '@generated/prisma/client';
|
||||||
|
import type { AttendeeDto, ProblemDetails, Result } from '@gruperly/shared';
|
||||||
|
import { err, ok } from '@gruperly/shared';
|
||||||
|
import { notFoundResourceProblem } from '@/http/problem-builders';
|
||||||
|
import prisma from '@/lib/prisma';
|
||||||
|
import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers';
|
||||||
|
|
||||||
|
import { toAttendeeDto } from '../../lib/helpers';
|
||||||
|
|
||||||
|
type GetAttendeeDeps = {
|
||||||
|
db?: Pick<PrismaClient, 'group' | 'attendee'>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export class GetAttendee {
|
||||||
|
constructor(private readonly deps: GetAttendeeDeps = {}) {}
|
||||||
|
|
||||||
|
async execute(
|
||||||
|
groupId: string,
|
||||||
|
attendeeId: string,
|
||||||
|
userId: string,
|
||||||
|
): Promise<Result<AttendeeDto, ProblemDetails>> {
|
||||||
|
const db = this.deps.db ?? prisma;
|
||||||
|
|
||||||
|
const access = await findGroupForUser(db, groupId, userId);
|
||||||
|
if (!access.ok) {
|
||||||
|
return access;
|
||||||
|
}
|
||||||
|
|
||||||
|
const attendee = await db.attendee.findFirst({ where: { id: attendeeId, groupId } });
|
||||||
|
if (!attendee) {
|
||||||
|
return err(notFoundResourceProblem('Attendee', attendeeId));
|
||||||
|
}
|
||||||
|
|
||||||
|
return ok(toAttendeeDto(attendee));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import { Hono } from 'hono';
|
||||||
|
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||||
|
import { GetAttendeeStats } from './use-case';
|
||||||
|
|
||||||
|
const route = new Hono();
|
||||||
|
|
||||||
|
route.get('/:groupId/attendees/:attendeeId/stats', async (c) => {
|
||||||
|
const user = c.get('user');
|
||||||
|
if (!user) {
|
||||||
|
return problemJson(c, unauthorizedProblem(c.req.path));
|
||||||
|
}
|
||||||
|
const groupId = c.req.param('groupId');
|
||||||
|
const attendeeId = c.req.param('attendeeId');
|
||||||
|
const useCase = new GetAttendeeStats();
|
||||||
|
const result = await useCase.execute(groupId, attendeeId, user.id);
|
||||||
|
|
||||||
|
return resultJson(c, result);
|
||||||
|
});
|
||||||
|
|
||||||
|
export default route;
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
import type { AttendanceStatus, PrismaClient } from '@generated/prisma/client';
|
||||||
|
import type { AttendeeStats, ProblemDetails, Result } from '@gruperly/shared';
|
||||||
|
import { err, ok } from '@gruperly/shared';
|
||||||
|
import { notFoundResourceProblem } from '@/http/problem-builders';
|
||||||
|
import prisma from '@/lib/prisma';
|
||||||
|
import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers';
|
||||||
|
|
||||||
|
type GetAttendeeStatsDeps = {
|
||||||
|
db?: Pick<PrismaClient, 'group' | 'attendee' | 'attendance'>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export class GetAttendeeStats {
|
||||||
|
constructor(private readonly deps: GetAttendeeStatsDeps = {}) {}
|
||||||
|
|
||||||
|
async execute(
|
||||||
|
groupId: string,
|
||||||
|
attendeeId: string,
|
||||||
|
userId: string,
|
||||||
|
): Promise<Result<AttendeeStats, ProblemDetails>> {
|
||||||
|
const db = this.deps.db ?? prisma;
|
||||||
|
|
||||||
|
const access = await findGroupForUser(db, groupId, userId);
|
||||||
|
if (!access.ok) {
|
||||||
|
return access;
|
||||||
|
}
|
||||||
|
|
||||||
|
const attendee = await db.attendee.findFirst({
|
||||||
|
where: { id: attendeeId, groupId },
|
||||||
|
select: { id: true },
|
||||||
|
});
|
||||||
|
if (!attendee) {
|
||||||
|
return err(notFoundResourceProblem('Attendee', attendeeId));
|
||||||
|
}
|
||||||
|
|
||||||
|
const rows = await db.attendance.groupBy({
|
||||||
|
by: ['status'],
|
||||||
|
where: { attendeeId },
|
||||||
|
_count: { _all: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
const countByStatus = (status: AttendanceStatus): number =>
|
||||||
|
rows.find((row) => row.status === status)?._count._all ?? 0;
|
||||||
|
|
||||||
|
const presentCount = countByStatus('PRESENT');
|
||||||
|
const absentCount = countByStatus('ABSENT');
|
||||||
|
const excusedCount = countByStatus('EXCUSED');
|
||||||
|
const totalMarked = presentCount + absentCount + excusedCount;
|
||||||
|
|
||||||
|
return ok({
|
||||||
|
attendeeId,
|
||||||
|
groupId,
|
||||||
|
presentCount,
|
||||||
|
absentCount,
|
||||||
|
excusedCount,
|
||||||
|
totalMarked,
|
||||||
|
attendanceRate: totalMarked > 0 ? Math.round((presentCount / totalMarked) * 100) : 0,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,6 +3,8 @@ import analyticsRoutes from '../analytics/routes';
|
|||||||
import addToGroupWaitlistRoute from '../attendees/features/add-to-waitlist/route';
|
import addToGroupWaitlistRoute from '../attendees/features/add-to-waitlist/route';
|
||||||
import bulkCreateAttendeesRoute from '../attendees/features/bulk-create/route';
|
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 getAttendeeStatsRoute from '../attendees/features/get-stats/route';
|
||||||
import removeAttendeeRoute from '../attendees/features/remove/route';
|
import removeAttendeeRoute from '../attendees/features/remove/route';
|
||||||
import groupWaitlistRoutes from '../group-waitlist/routes';
|
import groupWaitlistRoutes from '../group-waitlist/routes';
|
||||||
import createGroupRoute from './features/create/route';
|
import createGroupRoute from './features/create/route';
|
||||||
@@ -23,6 +25,8 @@ routes.route('/', getByIdRoute);
|
|||||||
routes.route('/', addToGroupWaitlistRoute);
|
routes.route('/', addToGroupWaitlistRoute);
|
||||||
routes.route('/', groupWaitlistRoutes);
|
routes.route('/', groupWaitlistRoutes);
|
||||||
routes.route('/', analyticsRoutes);
|
routes.route('/', analyticsRoutes);
|
||||||
|
routes.route('/', getAttendeeRoute);
|
||||||
|
routes.route('/', getAttendeeStatsRoute);
|
||||||
routes.route('/', removeAttendeeRoute);
|
routes.route('/', removeAttendeeRoute);
|
||||||
|
|
||||||
export default routes;
|
export default routes;
|
||||||
@@ -12,7 +12,6 @@ const at = (offsetDays: number) => new Date(Date.now() - offsetDays * day);
|
|||||||
function entry(status: 'PRESENT' | 'ABSENT' | 'EXCUSED', offsetDays: number) {
|
function entry(status: 'PRESENT' | 'ABSENT' | 'EXCUSED', offsetDays: number) {
|
||||||
return { status, occurredAt: at(offsetDays) };
|
return { status, occurredAt: at(offsetDays) };
|
||||||
}
|
}
|
||||||
|
|
||||||
describe('trailingAbsentStreak', () => {
|
describe('trailingAbsentStreak', () => {
|
||||||
it('devuelve 0 sin registros', () => {
|
it('devuelve 0 sin registros', () => {
|
||||||
expect(trailingAbsentStreak([])).toBe(0);
|
expect(trailingAbsentStreak([])).toBe(0);
|
||||||
@@ -34,13 +33,14 @@ describe('trailingAbsentStreak', () => {
|
|||||||
|
|
||||||
describe('lastAttendedAt', () => {
|
describe('lastAttendedAt', () => {
|
||||||
it('devuelve la clase PRESENT más reciente', () => {
|
it('devuelve la clase PRESENT más reciente', () => {
|
||||||
|
const now = Date.now();
|
||||||
const result = lastAttendedAt([
|
const result = lastAttendedAt([
|
||||||
entry('PRESENT', 0),
|
{ status: 'PRESENT', occurredAt: new Date(now) },
|
||||||
entry('ABSENT', 7),
|
entry('ABSENT', 7),
|
||||||
entry('ABSENT', 14),
|
entry('ABSENT', 14),
|
||||||
]);
|
]);
|
||||||
expect(result).not.toBeNull();
|
expect(result).not.toBeNull();
|
||||||
expect(result?.getTime()).toBe(at(0).getTime());
|
expect(result?.getTime()).toBe(now);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('devuelve null si nunca asistió', () => {
|
it('devuelve null si nunca asistió', () => {
|
||||||
|
|||||||
105
apps/backend/test/attendee-get-by-id.test.ts
Normal file
105
apps/backend/test/attendee-get-by-id.test.ts
Normal file
@@ -0,0 +1,105 @@
|
|||||||
|
import { beforeEach, describe, expect, it, mock, vi } from 'bun:test';
|
||||||
|
import { Hono } from 'hono';
|
||||||
|
|
||||||
|
const db = {
|
||||||
|
group: {
|
||||||
|
findUnique: mock(),
|
||||||
|
},
|
||||||
|
attendee: {
|
||||||
|
findFirst: mock(),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
mock.module('@/lib/prisma', () => ({
|
||||||
|
default: db,
|
||||||
|
getPrismaClient: mock(),
|
||||||
|
UnitOfWork: class {},
|
||||||
|
}));
|
||||||
|
|
||||||
|
import prisma from '@/lib/prisma';
|
||||||
|
import getAttendeeRoute from '@/modules/attendees/features/get-by-id/route';
|
||||||
|
|
||||||
|
const userId = 'user-1';
|
||||||
|
|
||||||
|
function makeApp(userValue: unknown) {
|
||||||
|
const app = new Hono();
|
||||||
|
app.use('*', async (c, next) => {
|
||||||
|
c.set('user', userValue as never);
|
||||||
|
await next();
|
||||||
|
});
|
||||||
|
app.route('/groups', getAttendeeRoute);
|
||||||
|
return app;
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeGroup(overrides: Record<string, unknown> = {}) {
|
||||||
|
return { id: 'group-1', name: 'Funcional', createdById: userId, members: [], ...overrides };
|
||||||
|
}
|
||||||
|
|
||||||
|
const attendee = {
|
||||||
|
id: 'a-1',
|
||||||
|
groupId: 'group-1',
|
||||||
|
fullName: 'Ana Pérez',
|
||||||
|
email: 'ana@example.com',
|
||||||
|
phone: '5512345678',
|
||||||
|
guardianName: 'Luis Pérez',
|
||||||
|
guardianPhone: null,
|
||||||
|
notes: null,
|
||||||
|
notifyToken: 'token-1',
|
||||||
|
createdAt: new Date('2026-08-01T10:00:00.000Z'),
|
||||||
|
updatedAt: new Date('2026-08-01T10:00:00.000Z'),
|
||||||
|
};
|
||||||
|
|
||||||
|
describe('GET /groups/:groupId/attendees/:attendeeId', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('devuelve el participante del grupo', async () => {
|
||||||
|
prisma.group.findUnique.mockResolvedValue(makeGroup());
|
||||||
|
prisma.attendee.findFirst.mockResolvedValue(attendee);
|
||||||
|
|
||||||
|
const res = await makeApp({ id: userId }).request('/groups/group-1/attendees/a-1');
|
||||||
|
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(await res.json()).toEqual({
|
||||||
|
id: 'a-1',
|
||||||
|
groupId: 'group-1',
|
||||||
|
fullName: 'Ana Pérez',
|
||||||
|
email: 'ana@example.com',
|
||||||
|
phone: '5512345678',
|
||||||
|
guardianName: 'Luis Pérez',
|
||||||
|
guardianPhone: null,
|
||||||
|
notes: null,
|
||||||
|
notifyToken: 'token-1',
|
||||||
|
createdAt: '2026-08-01T10:00:00.000Z',
|
||||||
|
updatedAt: '2026-08-01T10:00:00.000Z',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('devuelve 404 si el participante no pertenece al grupo', async () => {
|
||||||
|
prisma.group.findUnique.mockResolvedValue(makeGroup());
|
||||||
|
prisma.attendee.findFirst.mockResolvedValue(null);
|
||||||
|
|
||||||
|
const res = await makeApp({ id: userId }).request('/groups/group-1/attendees/nope');
|
||||||
|
|
||||||
|
expect(res.status).toBe(404);
|
||||||
|
expect(await res.json()).toMatchObject({ code: 'not_found' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('devuelve 403 si el usuario no tiene acceso al grupo', async () => {
|
||||||
|
prisma.group.findUnique.mockResolvedValue(
|
||||||
|
makeGroup({ createdById: 'otro-user', members: [] }),
|
||||||
|
);
|
||||||
|
|
||||||
|
const res = await makeApp({ id: userId }).request('/groups/group-1/attendees/a-1');
|
||||||
|
|
||||||
|
expect(res.status).toBe(403);
|
||||||
|
expect(await res.json()).toMatchObject({ code: 'group_access_denied' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('devuelve 401 si no hay sesión', async () => {
|
||||||
|
const res = await makeApp(undefined).request('/groups/group-1/attendees/a-1');
|
||||||
|
|
||||||
|
expect(res.status).toBe(401);
|
||||||
|
});
|
||||||
|
});
|
||||||
126
apps/backend/test/attendee-stats.test.ts
Normal file
126
apps/backend/test/attendee-stats.test.ts
Normal file
@@ -0,0 +1,126 @@
|
|||||||
|
import { beforeEach, describe, expect, it, mock, vi } from 'bun:test';
|
||||||
|
import { Hono } from 'hono';
|
||||||
|
|
||||||
|
const db = {
|
||||||
|
group: {
|
||||||
|
findUnique: mock(),
|
||||||
|
},
|
||||||
|
attendee: {
|
||||||
|
findFirst: mock(),
|
||||||
|
},
|
||||||
|
attendance: {
|
||||||
|
groupBy: mock(),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
mock.module('@/lib/prisma', () => ({
|
||||||
|
default: db,
|
||||||
|
getPrismaClient: mock(),
|
||||||
|
UnitOfWork: class {},
|
||||||
|
}));
|
||||||
|
|
||||||
|
import prisma from '@/lib/prisma';
|
||||||
|
import getAttendeeStatsRoute from '@/modules/attendees/features/get-stats/route';
|
||||||
|
|
||||||
|
const userId = 'user-1';
|
||||||
|
|
||||||
|
function makeApp(userValue: unknown) {
|
||||||
|
const app = new Hono();
|
||||||
|
app.use('*', async (c, next) => {
|
||||||
|
c.set('user', userValue as never);
|
||||||
|
await next();
|
||||||
|
});
|
||||||
|
app.route('/groups', getAttendeeStatsRoute);
|
||||||
|
return app;
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeGroup(overrides: Record<string, unknown> = {}) {
|
||||||
|
return { id: 'group-1', name: 'Funcional', createdById: userId, members: [], ...overrides };
|
||||||
|
}
|
||||||
|
|
||||||
|
function countRow(status: string, count: number) {
|
||||||
|
return { status, _count: { _all: count } };
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('GET /groups/:groupId/attendees/:attendeeId/stats', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('cuenta asistencias, ausencias y justificadas con su porcentaje', async () => {
|
||||||
|
prisma.group.findUnique.mockResolvedValue(makeGroup());
|
||||||
|
prisma.attendee.findFirst.mockResolvedValue({ id: 'a-1' });
|
||||||
|
prisma.attendance.groupBy.mockResolvedValue([
|
||||||
|
countRow('PRESENT', 17),
|
||||||
|
countRow('ABSENT', 2),
|
||||||
|
countRow('EXCUSED', 1),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const res = await makeApp({ id: userId }).request(
|
||||||
|
'/groups/group-1/attendees/a-1/stats',
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(await res.json()).toEqual({
|
||||||
|
attendeeId: 'a-1',
|
||||||
|
groupId: 'group-1',
|
||||||
|
presentCount: 17,
|
||||||
|
absentCount: 2,
|
||||||
|
excusedCount: 1,
|
||||||
|
totalMarked: 20,
|
||||||
|
attendanceRate: 85,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('devuelve conteos en cero cuando el participante no tiene registros', async () => {
|
||||||
|
prisma.group.findUnique.mockResolvedValue(makeGroup());
|
||||||
|
prisma.attendee.findFirst.mockResolvedValue({ id: 'a-1' });
|
||||||
|
prisma.attendance.groupBy.mockResolvedValue([]);
|
||||||
|
|
||||||
|
const res = await makeApp({ id: userId }).request(
|
||||||
|
'/groups/group-1/attendees/a-1/stats',
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(await res.json()).toEqual({
|
||||||
|
attendeeId: 'a-1',
|
||||||
|
groupId: 'group-1',
|
||||||
|
presentCount: 0,
|
||||||
|
absentCount: 0,
|
||||||
|
excusedCount: 0,
|
||||||
|
totalMarked: 0,
|
||||||
|
attendanceRate: 0,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('devuelve 404 si el participante no pertenece al grupo', async () => {
|
||||||
|
prisma.group.findUnique.mockResolvedValue(makeGroup());
|
||||||
|
prisma.attendee.findFirst.mockResolvedValue(null);
|
||||||
|
|
||||||
|
const res = await makeApp({ id: userId }).request(
|
||||||
|
'/groups/group-1/attendees/nope/stats',
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(res.status).toBe(404);
|
||||||
|
expect(await res.json()).toMatchObject({ code: 'not_found' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('devuelve 403 si el usuario no tiene acceso al grupo', async () => {
|
||||||
|
prisma.group.findUnique.mockResolvedValue(
|
||||||
|
makeGroup({ createdById: 'otro-user', members: [] }),
|
||||||
|
);
|
||||||
|
|
||||||
|
const res = await makeApp({ id: userId }).request(
|
||||||
|
'/groups/group-1/attendees/a-1/stats',
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(res.status).toBe(403);
|
||||||
|
expect(await res.json()).toMatchObject({ code: 'group_access_denied' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('devuelve 401 si no hay sesión', async () => {
|
||||||
|
const res = await makeApp(undefined).request('/groups/group-1/attendees/a-1/stats');
|
||||||
|
|
||||||
|
expect(res.status).toBe(401);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -76,6 +76,7 @@ export function AttendanceProvider({ sessionId, children }: { sessionId: string;
|
|||||||
toast.success('Asistencia guardada correctamente.', 'Listo')
|
toast.success('Asistencia guardada correctamente.', 'Listo')
|
||||||
void queryClient.invalidateQueries({ queryKey: ['classes-today'] })
|
void queryClient.invalidateQueries({ queryKey: ['classes-today'] })
|
||||||
void queryClient.invalidateQueries({ queryKey: ['class-students', sessionId] })
|
void queryClient.invalidateQueries({ queryKey: ['class-students', sessionId] })
|
||||||
|
void queryClient.invalidateQueries({ queryKey: ['attendee-stats'] })
|
||||||
},
|
},
|
||||||
onError: (error: Error) => {
|
onError: (error: Error) => {
|
||||||
toast.error(error.message || 'No pudimos guardar la asistencia.')
|
toast.error(error.message || 'No pudimos guardar la asistencia.')
|
||||||
|
|||||||
106
apps/web/src/features/groups/detail/AttendeeAttendanceStats.tsx
Normal file
106
apps/web/src/features/groups/detail/AttendeeAttendanceStats.tsx
Normal file
@@ -0,0 +1,106 @@
|
|||||||
|
import { Loader2 } from 'lucide-react'
|
||||||
|
import { cn } from '../../../lib/utils'
|
||||||
|
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
||||||
|
|
||||||
|
type RateTone = 'good' | 'mid' | 'low' | 'none'
|
||||||
|
|
||||||
|
function rateTone(rate: number, totalMarked: number): RateTone {
|
||||||
|
if (totalMarked === 0) return 'none'
|
||||||
|
if (rate >= 75) return 'good'
|
||||||
|
if (rate >= 50) return 'mid'
|
||||||
|
return 'low'
|
||||||
|
}
|
||||||
|
|
||||||
|
const barTone: Record<RateTone, string> = {
|
||||||
|
good: 'bg-success',
|
||||||
|
mid: 'bg-warning',
|
||||||
|
low: 'bg-danger',
|
||||||
|
none: 'bg-border',
|
||||||
|
}
|
||||||
|
|
||||||
|
const valueTone: Record<RateTone, string> = {
|
||||||
|
good: 'text-success',
|
||||||
|
mid: 'text-warning',
|
||||||
|
low: 'text-danger',
|
||||||
|
none: 'text-foreground/40',
|
||||||
|
}
|
||||||
|
|
||||||
|
export function AttendeeAttendanceStats() {
|
||||||
|
const { attendeeStats, attendeeStatsPending, attendeeStatsFailed } = useAttendeeDetail()
|
||||||
|
|
||||||
|
if (attendeeStatsPending) {
|
||||||
|
return (
|
||||||
|
<div className="flex items-center justify-center rounded-xl border border-border bg-primary-soft/30 py-8">
|
||||||
|
<Loader2 className="size-5 animate-spin text-accent" />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (attendeeStatsFailed || !attendeeStats) {
|
||||||
|
return (
|
||||||
|
<div className="rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">
|
||||||
|
No pudimos cargar la asistencia de este participante.
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const { presentCount, absentCount, excusedCount, totalMarked, attendanceRate } = attendeeStats
|
||||||
|
const tone = rateTone(attendanceRate, totalMarked)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-3 rounded-xl border border-border bg-primary-soft/30 p-3 sm:p-4">
|
||||||
|
<div className="flex items-end justify-between gap-3">
|
||||||
|
<div className="min-w-0">
|
||||||
|
<p className="text-[11px] font-medium uppercase tracking-wide text-foreground/50">
|
||||||
|
Asistencia
|
||||||
|
</p>
|
||||||
|
<p className="text-xs text-foreground/50">
|
||||||
|
{totalMarked > 0
|
||||||
|
? `Sobre ${totalMarked} clases registradas`
|
||||||
|
: 'Sin clases registradas todavía'}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<p className={cn('text-2xl font-bold tabular-nums', valueTone[tone])}>
|
||||||
|
{totalMarked > 0 ? `${attendanceRate}%` : '—'}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div
|
||||||
|
className="h-1.5 overflow-hidden rounded-full bg-border"
|
||||||
|
role="presentation"
|
||||||
|
aria-hidden="true"
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
'h-full rounded-full transition-[width] duration-500 ease-out',
|
||||||
|
barTone[tone],
|
||||||
|
)}
|
||||||
|
style={{ width: `${attendanceRate}%` }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<dl className="grid grid-cols-3 gap-1.5 sm:gap-2">
|
||||||
|
<StatCounter value={presentCount} label="Clases asistidas" valueClass="text-success" />
|
||||||
|
<StatCounter value={absentCount} label="Clases ausentes" valueClass="text-danger" />
|
||||||
|
<StatCounter value={excusedCount} label="Avisó ausencia" valueClass="text-warning" />
|
||||||
|
</dl>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function StatCounter({
|
||||||
|
value,
|
||||||
|
label,
|
||||||
|
valueClass,
|
||||||
|
}: {
|
||||||
|
value: number
|
||||||
|
label: string
|
||||||
|
valueClass: string
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<div className="min-w-0 rounded-lg bg-surface px-2 py-2">
|
||||||
|
<dt className="text-[11px] font-medium uppercase leading-tight text-foreground/50">{label}</dt>
|
||||||
|
<dd className={cn('text-lg font-bold tabular-nums', valueClass)}>{value}</dd>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -1,150 +0,0 @@
|
|||||||
import { Copy, Mail, MessageCircle, Phone, ShieldCheck, StickyNote, UserMinus } from 'lucide-react'
|
|
||||||
import { Button, Modal } from '../../../components/ui'
|
|
||||||
import { DetailRow } from './DetailRow'
|
|
||||||
import { useGroupDetail } from './GroupDetailProvider'
|
|
||||||
|
|
||||||
export function AttendeeDetailModal() {
|
|
||||||
const { selectedAttendee, setSelectedAttendee, requestRemoveAttendee, copyAbsenceNotifyUrl } =
|
|
||||||
useGroupDetail()
|
|
||||||
const absenceNotifyUrl = selectedAttendee?.notifyToken
|
|
||||||
? `${window.location.origin}/report-absence/${selectedAttendee.notifyToken}`
|
|
||||||
: null
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Modal
|
|
||||||
isOpen={selectedAttendee !== null}
|
|
||||||
onClose={() => setSelectedAttendee(null)}
|
|
||||||
title="Detalle del Participante"
|
|
||||||
maxWidth="sm"
|
|
||||||
>
|
|
||||||
{selectedAttendee ? (
|
|
||||||
<div className="space-y-5">
|
|
||||||
<div className="flex items-center gap-3">
|
|
||||||
<div className="flex size-12 items-center justify-center rounded-full bg-accent/10 text-lg font-bold text-accent">
|
|
||||||
{selectedAttendee.fullName.charAt(0).toUpperCase()}
|
|
||||||
</div>
|
|
||||||
<div className="min-w-0">
|
|
||||||
<p className="truncate text-lg font-semibold text-primary">{selectedAttendee.fullName}</p>
|
|
||||||
<p className="text-xs text-foreground/50">
|
|
||||||
Incorporado el{' '}
|
|
||||||
{new Date(selectedAttendee.createdAt).toLocaleDateString('es-ES', {
|
|
||||||
day: 'numeric',
|
|
||||||
month: 'long',
|
|
||||||
year: 'numeric',
|
|
||||||
})}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-1 divide-y divide-border rounded-xl border border-border bg-primary-soft/30">
|
|
||||||
<DetailRow icon={<Phone className="size-4 text-accent" />} label="Teléfono">
|
|
||||||
{selectedAttendee.phone ? (
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<span className="text-primary">{selectedAttendee.phone}</span>
|
|
||||||
<a
|
|
||||||
href={`https://wa.me/${selectedAttendee.phone.replace(/\D/g, '')}`}
|
|
||||||
target="_blank"
|
|
||||||
rel="noopener noreferrer"
|
|
||||||
className="inline-flex items-center gap-1 text-xs font-medium text-success transition-colors hover:text-success/80"
|
|
||||||
>
|
|
||||||
<MessageCircle className="size-3.5" />
|
|
||||||
<span>WhatsApp</span>
|
|
||||||
</a>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<span className="text-foreground/40">Sin teléfono</span>
|
|
||||||
)}
|
|
||||||
</DetailRow>
|
|
||||||
|
|
||||||
<DetailRow icon={<Mail className="size-4 text-accent" />} label="Email">
|
|
||||||
{selectedAttendee.email ? (
|
|
||||||
<a
|
|
||||||
href={`mailto:${selectedAttendee.email}`}
|
|
||||||
className="text-primary transition-colors hover:text-accent"
|
|
||||||
>
|
|
||||||
{selectedAttendee.email}
|
|
||||||
</a>
|
|
||||||
) : (
|
|
||||||
<span className="text-foreground/40">Sin email</span>
|
|
||||||
)}
|
|
||||||
</DetailRow>
|
|
||||||
|
|
||||||
{selectedAttendee.guardianName || selectedAttendee.guardianPhone ? (
|
|
||||||
<>
|
|
||||||
<DetailRow icon={<ShieldCheck className="size-4 text-accent" />} label="Responsable">
|
|
||||||
<span className="text-primary">
|
|
||||||
{selectedAttendee.guardianName || <span className="text-foreground/40">—</span>}
|
|
||||||
</span>
|
|
||||||
</DetailRow>
|
|
||||||
{selectedAttendee.guardianPhone ? (
|
|
||||||
<DetailRow icon={<Phone className="size-4 text-accent" />} label="Tel. Responsable">
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<span className="text-primary">{selectedAttendee.guardianPhone}</span>
|
|
||||||
<a
|
|
||||||
href={`https://wa.me/${selectedAttendee.guardianPhone.replace(/\D/g, '')}`}
|
|
||||||
target="_blank"
|
|
||||||
rel="noopener noreferrer"
|
|
||||||
className="inline-flex items-center gap-1 text-xs font-medium text-success transition-colors hover:text-success/80"
|
|
||||||
>
|
|
||||||
<MessageCircle className="size-3.5" />
|
|
||||||
</a>
|
|
||||||
</div>
|
|
||||||
</DetailRow>
|
|
||||||
) : null}
|
|
||||||
</>
|
|
||||||
) : null}
|
|
||||||
|
|
||||||
<DetailRow icon={<StickyNote className="size-4 text-accent" />} label="Notas">
|
|
||||||
{selectedAttendee.notes ? (
|
|
||||||
<span className="text-xs leading-relaxed text-primary">{selectedAttendee.notes}</span>
|
|
||||||
) : (
|
|
||||||
<span className="text-foreground/40">Sin notas</span>
|
|
||||||
)}
|
|
||||||
</DetailRow>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{absenceNotifyUrl ? (
|
|
||||||
<div className="space-y-2 border-t border-border pt-4">
|
|
||||||
<p className="text-xs font-medium text-foreground/60">Link para avisar ausencias</p>
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<code className="min-w-0 flex-1 truncate rounded-lg bg-primary-soft px-2 py-1.5 text-xs text-primary">
|
|
||||||
{absenceNotifyUrl}
|
|
||||||
</code>
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
size="sm"
|
|
||||||
onClick={() => copyAbsenceNotifyUrl(absenceNotifyUrl)}
|
|
||||||
>
|
|
||||||
<Copy className="size-3.5" />
|
|
||||||
Copiar
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
{selectedAttendee.phone ? (
|
|
||||||
<a
|
|
||||||
href={`https://wa.me/${selectedAttendee.phone.replace(/\D/g, '')}?text=${encodeURIComponent(`Hola ${selectedAttendee.fullName.split(' ')[0]}, desde este link podés avisar tus ausencias en ${absenceNotifyUrl}`)}`}
|
|
||||||
target="_blank"
|
|
||||||
rel="noopener noreferrer"
|
|
||||||
className="inline-flex items-center gap-1 text-xs font-medium text-success transition-colors hover:text-success/80"
|
|
||||||
>
|
|
||||||
<MessageCircle className="size-3.5" />
|
|
||||||
<span>Enviar por WhatsApp</span>
|
|
||||||
</a>
|
|
||||||
) : null}
|
|
||||||
</div>
|
|
||||||
) : null}
|
|
||||||
|
|
||||||
<div className="border-t border-border pt-2">
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
onClick={() => requestRemoveAttendee(selectedAttendee)}
|
|
||||||
className="w-full gap-2 border border-danger/20 text-danger hover:bg-danger/10 hover:text-danger"
|
|
||||||
>
|
|
||||||
<UserMinus className="size-4" />
|
|
||||||
Quitar del grupo
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
) : null}
|
|
||||||
</Modal>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
212
apps/web/src/features/groups/detail/AttendeeDetailPage.tsx
Normal file
212
apps/web/src/features/groups/detail/AttendeeDetailPage.tsx
Normal file
@@ -0,0 +1,212 @@
|
|||||||
|
import { Link, useNavigate } from '@tanstack/react-router'
|
||||||
|
import {
|
||||||
|
ArrowLeft,
|
||||||
|
Copy,
|
||||||
|
Loader2,
|
||||||
|
Mail,
|
||||||
|
MessageCircle,
|
||||||
|
Phone,
|
||||||
|
ShieldCheck,
|
||||||
|
StickyNote,
|
||||||
|
UserMinus,
|
||||||
|
} from 'lucide-react'
|
||||||
|
import { Button } from '../../../components/ui'
|
||||||
|
import { AttendeeAttendanceStats } from './AttendeeAttendanceStats'
|
||||||
|
import { useAttendeeDetail } from './AttendeeDetailProvider'
|
||||||
|
import { DetailRow } from './DetailRow'
|
||||||
|
import { RemoveAttendeeModal } from './RemoveAttendeeModal'
|
||||||
|
|
||||||
|
export function AttendeeDetailPage() {
|
||||||
|
const {
|
||||||
|
groupId,
|
||||||
|
groupName,
|
||||||
|
attendee,
|
||||||
|
attendeePending,
|
||||||
|
attendeeFailed,
|
||||||
|
openRemoveModal,
|
||||||
|
isRemoveModalOpen,
|
||||||
|
closeRemoveModal,
|
||||||
|
confirmRemoveAttendee,
|
||||||
|
firstWaitlistEntry,
|
||||||
|
waitlistTotal,
|
||||||
|
waitlistPending,
|
||||||
|
isSubmittingRemoval,
|
||||||
|
copyAbsenceNotifyUrl,
|
||||||
|
} = useAttendeeDetail()
|
||||||
|
const navigate = useNavigate()
|
||||||
|
|
||||||
|
if (attendeePending) {
|
||||||
|
return (
|
||||||
|
<div className="flex items-center justify-center py-20">
|
||||||
|
<Loader2 className="size-8 animate-spin text-accent" />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (attendeeFailed || !attendee) {
|
||||||
|
return (
|
||||||
|
<div className="rounded-xl border border-danger/20 bg-danger-soft p-6 text-danger">
|
||||||
|
<h2 className="text-lg font-semibold">Participante no encontrado</h2>
|
||||||
|
<p className="mt-2 text-sm">No se pudo cargar la información de este participante.</p>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
className="mt-4"
|
||||||
|
onClick={() => void navigate({ to: '/groups/$groupId', params: { groupId } })}
|
||||||
|
>
|
||||||
|
Volver al grupo
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const absenceNotifyUrl = attendee.notifyToken
|
||||||
|
? `${window.location.origin}/report-absence/${attendee.notifyToken}`
|
||||||
|
: null
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section className="animate-fade-in space-y-5">
|
||||||
|
<Link
|
||||||
|
to="/groups/$groupId"
|
||||||
|
params={{ groupId }}
|
||||||
|
className="hidden items-center gap-1 text-sm text-foreground/60 transition-colors hover:text-primary lg:inline-flex"
|
||||||
|
>
|
||||||
|
<ArrowLeft className="size-4" />
|
||||||
|
<span>Volver al grupo</span>
|
||||||
|
</Link>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<div className="flex size-14 shrink-0 items-center justify-center rounded-full bg-accent/10 text-xl font-bold text-accent">
|
||||||
|
{attendee.fullName.charAt(0).toUpperCase()}
|
||||||
|
</div>
|
||||||
|
<div className="min-w-0">
|
||||||
|
<h1 className="truncate text-xl font-bold text-primary">{attendee.fullName}</h1>
|
||||||
|
<p className="text-xs text-foreground/50">
|
||||||
|
{groupName ? `${groupName} · ` : ''}Incorporado el{' '}
|
||||||
|
{new Date(attendee.createdAt).toLocaleDateString('es-ES', {
|
||||||
|
day: 'numeric',
|
||||||
|
month: 'long',
|
||||||
|
year: 'numeric',
|
||||||
|
})}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<AttendeeAttendanceStats />
|
||||||
|
|
||||||
|
<div className="space-y-1 divide-y divide-border rounded-xl border border-border bg-primary-soft/30">
|
||||||
|
<DetailRow icon={<Phone className="size-4 text-accent" />} label="Teléfono">
|
||||||
|
{attendee.phone ? (
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span className="text-primary">{attendee.phone}</span>
|
||||||
|
<a
|
||||||
|
href={`https://wa.me/${attendee.phone.replace(/\D/g, '')}`}
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener noreferrer"
|
||||||
|
className="inline-flex items-center gap-1 text-xs font-medium text-success transition-colors hover:text-success/80"
|
||||||
|
>
|
||||||
|
<MessageCircle className="size-3.5" />
|
||||||
|
<span>WhatsApp</span>
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<span className="text-foreground/40">Sin teléfono</span>
|
||||||
|
)}
|
||||||
|
</DetailRow>
|
||||||
|
|
||||||
|
<DetailRow icon={<Mail className="size-4 text-accent" />} label="Email">
|
||||||
|
{attendee.email ? (
|
||||||
|
<a
|
||||||
|
href={`mailto:${attendee.email}`}
|
||||||
|
className="text-primary transition-colors hover:text-accent"
|
||||||
|
>
|
||||||
|
{attendee.email}
|
||||||
|
</a>
|
||||||
|
) : (
|
||||||
|
<span className="text-foreground/40">Sin email</span>
|
||||||
|
)}
|
||||||
|
</DetailRow>
|
||||||
|
|
||||||
|
{attendee.guardianName || attendee.guardianPhone ? (
|
||||||
|
<>
|
||||||
|
<DetailRow icon={<ShieldCheck className="size-4 text-accent" />} label="Responsable">
|
||||||
|
<span className="text-primary">
|
||||||
|
{attendee.guardianName || <span className="text-foreground/40">—</span>}
|
||||||
|
</span>
|
||||||
|
</DetailRow>
|
||||||
|
{attendee.guardianPhone ? (
|
||||||
|
<DetailRow icon={<Phone className="size-4 text-accent" />} label="Tel. Responsable">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span className="text-primary">{attendee.guardianPhone}</span>
|
||||||
|
<a
|
||||||
|
href={`https://wa.me/${attendee.guardianPhone.replace(/\D/g, '')}`}
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener noreferrer"
|
||||||
|
className="inline-flex items-center gap-1 text-xs font-medium text-success transition-colors hover:text-success/80"
|
||||||
|
>
|
||||||
|
<MessageCircle className="size-3.5" />
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</DetailRow>
|
||||||
|
) : null}
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<DetailRow icon={<StickyNote className="size-4 text-accent" />} label="Notas">
|
||||||
|
{attendee.notes ? (
|
||||||
|
<span className="text-xs leading-relaxed text-primary">{attendee.notes}</span>
|
||||||
|
) : (
|
||||||
|
<span className="text-foreground/40">Sin notas</span>
|
||||||
|
)}
|
||||||
|
</DetailRow>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{absenceNotifyUrl ? (
|
||||||
|
<div className="space-y-2 rounded-xl border border-border p-4">
|
||||||
|
<p className="text-xs font-medium text-foreground/60">Link para avisar ausencias</p>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<code className="min-w-0 flex-1 truncate rounded-lg bg-primary-soft px-2 py-1.5 text-xs text-primary">
|
||||||
|
{absenceNotifyUrl}
|
||||||
|
</code>
|
||||||
|
<Button variant="outline" size="sm" onClick={() => copyAbsenceNotifyUrl(absenceNotifyUrl)}>
|
||||||
|
<Copy className="size-3.5" />
|
||||||
|
Copiar
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
{attendee.phone ? (
|
||||||
|
<a
|
||||||
|
href={`https://wa.me/${attendee.phone.replace(/\D/g, '')}?text=${encodeURIComponent(`Hola ${attendee.fullName.split(' ')[0]}, desde este link podés avisar tus ausencias en ${absenceNotifyUrl}`)}`}
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener noreferrer"
|
||||||
|
className="inline-flex items-center gap-1 text-xs font-medium text-success transition-colors hover:text-success/80"
|
||||||
|
>
|
||||||
|
<MessageCircle className="size-3.5" />
|
||||||
|
<span>Enviar por WhatsApp</span>
|
||||||
|
</a>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<div className="border-t border-border pt-2">
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
onClick={openRemoveModal}
|
||||||
|
className="w-full gap-2 border border-danger/20 text-danger hover:bg-danger/10 hover:text-danger"
|
||||||
|
>
|
||||||
|
<UserMinus className="size-4" />
|
||||||
|
Quitar del grupo
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<RemoveAttendeeModal
|
||||||
|
attendee={isRemoveModalOpen ? attendee : null}
|
||||||
|
groupName={groupName}
|
||||||
|
firstWaitlistEntry={firstWaitlistEntry}
|
||||||
|
waitlistTotal={waitlistTotal}
|
||||||
|
isResolvingWaitlist={isRemoveModalOpen && waitlistPending}
|
||||||
|
isSubmitting={isSubmittingRemoval}
|
||||||
|
onCancel={closeRemoveModal}
|
||||||
|
onConfirm={confirmRemoveAttendee}
|
||||||
|
/>
|
||||||
|
</section>
|
||||||
|
)
|
||||||
|
}
|
||||||
119
apps/web/src/features/groups/detail/AttendeeDetailProvider.tsx
Normal file
119
apps/web/src/features/groups/detail/AttendeeDetailProvider.tsx
Normal file
@@ -0,0 +1,119 @@
|
|||||||
|
import { createContext, useContext, useState } from 'react'
|
||||||
|
import type { ReactNode } from 'react'
|
||||||
|
import { useQuery } from '@tanstack/react-query'
|
||||||
|
import { useNavigate } from '@tanstack/react-router'
|
||||||
|
import type { AttendeeDto, AttendeeStats, GroupWaitlistEntryDto } from '@gruperly/shared'
|
||||||
|
import { useToast } from '../../../components/ui'
|
||||||
|
import { getAttendeeStats, getGroup, getGroupAttendee, getGroupWaitlist } from '../../../lib/api'
|
||||||
|
import { useRemoveAttendee } from './useRemoveAttendee'
|
||||||
|
|
||||||
|
type AttendeeDetailContextValue = {
|
||||||
|
groupId: string
|
||||||
|
groupName: string | undefined
|
||||||
|
attendee: AttendeeDto | undefined
|
||||||
|
attendeePending: boolean
|
||||||
|
attendeeFailed: boolean
|
||||||
|
attendeeStats: AttendeeStats | undefined
|
||||||
|
attendeeStatsPending: boolean
|
||||||
|
attendeeStatsFailed: boolean
|
||||||
|
firstWaitlistEntry: GroupWaitlistEntryDto | null
|
||||||
|
waitlistTotal: number
|
||||||
|
waitlistPending: boolean
|
||||||
|
isRemoveModalOpen: boolean
|
||||||
|
openRemoveModal: () => void
|
||||||
|
closeRemoveModal: () => void
|
||||||
|
confirmRemoveAttendee: (promoteFromWaitlist: boolean) => void
|
||||||
|
isSubmittingRemoval: boolean
|
||||||
|
copyAbsenceNotifyUrl: (url: string) => void
|
||||||
|
}
|
||||||
|
|
||||||
|
const AttendeeDetailContext = createContext<AttendeeDetailContextValue | null>(null)
|
||||||
|
|
||||||
|
export function AttendeeDetailProvider({
|
||||||
|
groupId,
|
||||||
|
attendeeId,
|
||||||
|
children,
|
||||||
|
}: {
|
||||||
|
groupId: string
|
||||||
|
attendeeId: string
|
||||||
|
children: ReactNode
|
||||||
|
}) {
|
||||||
|
const toast = useToast()
|
||||||
|
const navigate = useNavigate()
|
||||||
|
const [isRemoveModalOpen, setIsRemoveModalOpen] = useState(false)
|
||||||
|
|
||||||
|
const groupQuery = useQuery({
|
||||||
|
queryKey: ['group', groupId],
|
||||||
|
queryFn: () => getGroup(groupId),
|
||||||
|
enabled: Boolean(groupId),
|
||||||
|
})
|
||||||
|
|
||||||
|
const attendeeQuery = useQuery({
|
||||||
|
queryKey: ['group-attendee', groupId, attendeeId],
|
||||||
|
queryFn: () => getGroupAttendee(groupId, attendeeId),
|
||||||
|
enabled: Boolean(groupId && attendeeId),
|
||||||
|
})
|
||||||
|
|
||||||
|
const attendeeStatsQuery = useQuery({
|
||||||
|
queryKey: ['attendee-stats', groupId, attendeeId],
|
||||||
|
queryFn: () => getAttendeeStats(groupId, attendeeId),
|
||||||
|
enabled: Boolean(groupId && attendeeId),
|
||||||
|
})
|
||||||
|
|
||||||
|
const waitlistQuery = useQuery({
|
||||||
|
queryKey: ['group-waitlist', groupId],
|
||||||
|
queryFn: () => getGroupWaitlist(groupId, 1, 100),
|
||||||
|
enabled: Boolean(groupId && isRemoveModalOpen),
|
||||||
|
})
|
||||||
|
|
||||||
|
const waitlistEntries = waitlistQuery.data?.data ?? []
|
||||||
|
const firstWaitlistEntry = waitlistEntries[0] ?? null
|
||||||
|
const waitlistTotal = waitlistQuery.data?.pagination?.total ?? waitlistEntries.length
|
||||||
|
|
||||||
|
const { removeAttendee, isRemovingAttendee } = useRemoveAttendee({
|
||||||
|
groupId,
|
||||||
|
onRemoved: () => {
|
||||||
|
setIsRemoveModalOpen(false)
|
||||||
|
void navigate({ to: '/groups/$groupId', params: { groupId } })
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const copyAbsenceNotifyUrl = (url: string) => {
|
||||||
|
void navigator.clipboard.writeText(url).then(() => {
|
||||||
|
toast.success('Link copiado al portapapeles.')
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const value: AttendeeDetailContextValue = {
|
||||||
|
groupId,
|
||||||
|
groupName: groupQuery.data?.name,
|
||||||
|
attendee: attendeeQuery.data,
|
||||||
|
attendeePending: attendeeQuery.isPending,
|
||||||
|
attendeeFailed: attendeeQuery.isError,
|
||||||
|
attendeeStats: attendeeStatsQuery.data,
|
||||||
|
attendeeStatsPending: attendeeStatsQuery.isPending,
|
||||||
|
attendeeStatsFailed: attendeeStatsQuery.isError,
|
||||||
|
firstWaitlistEntry,
|
||||||
|
waitlistTotal,
|
||||||
|
waitlistPending: waitlistQuery.isPending,
|
||||||
|
isRemoveModalOpen,
|
||||||
|
openRemoveModal: () => setIsRemoveModalOpen(true),
|
||||||
|
closeRemoveModal: () => setIsRemoveModalOpen(false),
|
||||||
|
confirmRemoveAttendee: (promoteFromWaitlist) => {
|
||||||
|
if (!attendeeQuery.data) return
|
||||||
|
removeAttendee({ attendee: attendeeQuery.data, promoteFromWaitlist })
|
||||||
|
},
|
||||||
|
isSubmittingRemoval: isRemovingAttendee,
|
||||||
|
copyAbsenceNotifyUrl,
|
||||||
|
}
|
||||||
|
|
||||||
|
return <AttendeeDetailContext.Provider value={value}>{children}</AttendeeDetailContext.Provider>
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useAttendeeDetail() {
|
||||||
|
const context = useContext(AttendeeDetailContext)
|
||||||
|
if (!context) {
|
||||||
|
throw new Error('useAttendeeDetail debe usarse dentro de <AttendeeDetailProvider>')
|
||||||
|
}
|
||||||
|
return context
|
||||||
|
}
|
||||||
@@ -24,9 +24,9 @@ import {
|
|||||||
getGroupWaitlist,
|
getGroupWaitlist,
|
||||||
getInviteToken,
|
getInviteToken,
|
||||||
promoteGroupWaitlistEntry,
|
promoteGroupWaitlistEntry,
|
||||||
removeGroupAttendee,
|
|
||||||
removeGroupWaitlistEntry,
|
removeGroupWaitlistEntry,
|
||||||
} from '../../../lib/api'
|
} from '../../../lib/api'
|
||||||
|
import { useRemoveAttendee } from './useRemoveAttendee'
|
||||||
|
|
||||||
export type BulkAttendeeRow = {
|
export type BulkAttendeeRow = {
|
||||||
firstName: string
|
firstName: string
|
||||||
@@ -68,8 +68,6 @@ type GroupDetailContextValue = {
|
|||||||
isAddAttendeeModalOpen: boolean
|
isAddAttendeeModalOpen: boolean
|
||||||
openAddAttendeeModal: () => void
|
openAddAttendeeModal: () => void
|
||||||
closeAddAttendeeModal: () => void
|
closeAddAttendeeModal: () => void
|
||||||
selectedAttendee: AttendeeDto | null
|
|
||||||
setSelectedAttendee: (attendee: AttendeeDto | null) => void
|
|
||||||
attendeeToRemove: AttendeeDto | null
|
attendeeToRemove: AttendeeDto | null
|
||||||
requestRemoveAttendee: (attendee: AttendeeDto) => void
|
requestRemoveAttendee: (attendee: AttendeeDto) => void
|
||||||
cancelRemoveAttendee: () => void
|
cancelRemoveAttendee: () => void
|
||||||
@@ -111,7 +109,6 @@ type GroupDetailContextValue = {
|
|||||||
copyInviteLink: () => Promise<void>
|
copyInviteLink: () => Promise<void>
|
||||||
copyWhatsappMessage: () => Promise<void>
|
copyWhatsappMessage: () => Promise<void>
|
||||||
openWhatsapp: () => Promise<void>
|
openWhatsapp: () => Promise<void>
|
||||||
copyAbsenceNotifyUrl: (url: string) => void
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const GroupDetailContext = createContext<GroupDetailContextValue | null>(null)
|
const GroupDetailContext = createContext<GroupDetailContextValue | null>(null)
|
||||||
@@ -122,7 +119,6 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch
|
|||||||
|
|
||||||
const [isInviteModalOpen, setIsInviteModalOpen] = useState(false)
|
const [isInviteModalOpen, setIsInviteModalOpen] = useState(false)
|
||||||
const [isAddAttendeeModalOpen, setIsAddAttendeeModalOpen] = useState(false)
|
const [isAddAttendeeModalOpen, setIsAddAttendeeModalOpen] = useState(false)
|
||||||
const [selectedAttendee, setSelectedAttendee] = useState<AttendeeDto | null>(null)
|
|
||||||
const [activeTab, setActiveTab] = useState<AddAttendeeTab>('quick')
|
const [activeTab, setActiveTab] = useState<AddAttendeeTab>('quick')
|
||||||
const [listSection, setListSection] = useState<ListSection>('members')
|
const [listSection, setListSection] = useState<ListSection>('members')
|
||||||
const [attendeeToRemove, setAttendeeToRemove] = useState<AttendeeDto | null>(null)
|
const [attendeeToRemove, setAttendeeToRemove] = useState<AttendeeDto | null>(null)
|
||||||
@@ -290,30 +286,9 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch
|
|||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
const removeAttendeeMutation = useMutation({
|
const removeAttendeeMutation = useRemoveAttendee({
|
||||||
mutationFn: (payload: { attendeeId: string; promoteFromWaitlist: boolean }) =>
|
groupId,
|
||||||
removeGroupAttendee(groupId, payload.attendeeId, { promoteFromWaitlist: payload.promoteFromWaitlist }),
|
onRemoved: () => setAttendeeToRemove(null),
|
||||||
onSuccess: (result, payload) => {
|
|
||||||
const removedName = attendees.find((a) => a.id === payload.attendeeId)?.fullName ?? 'El miembro'
|
|
||||||
if (result.promoted) {
|
|
||||||
toast.success(
|
|
||||||
`${removedName} fue quitado del grupo y ${result.promoted.fullName} pasó de la lista de espera al grupo.`,
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
toast.success(`${removedName} fue quitado del grupo.`)
|
|
||||||
}
|
|
||||||
invalidateGroupQueries()
|
|
||||||
setSelectedAttendee(null)
|
|
||||||
setAttendeeToRemove(null)
|
|
||||||
},
|
|
||||||
onError: (err: Error) => {
|
|
||||||
if (err instanceof ApiError && err.problem?.code === 'attendee_has_payments') {
|
|
||||||
toast.error(err.problem.detail ?? 'Este miembro tiene cobros asociados.')
|
|
||||||
} else {
|
|
||||||
toast.error(err.message || 'Error al quitar al miembro del grupo.')
|
|
||||||
}
|
|
||||||
setAttendeeToRemove(null)
|
|
||||||
},
|
|
||||||
})
|
})
|
||||||
|
|
||||||
const promoteWaitlistMutation = useMutation({
|
const promoteWaitlistMutation = useMutation({
|
||||||
@@ -384,12 +359,6 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch
|
|||||||
window.open(whatsappShareUrl, '_blank', 'noopener,noreferrer')
|
window.open(whatsappShareUrl, '_blank', 'noopener,noreferrer')
|
||||||
}
|
}
|
||||||
|
|
||||||
const copyAbsenceNotifyUrl = (url: string) => {
|
|
||||||
void navigator.clipboard.writeText(url).then(() => {
|
|
||||||
toast.success('Link copiado al portapapeles.')
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
const validRows: BulkAttendeeRow[] = useMemo(
|
const validRows: BulkAttendeeRow[] = useMemo(
|
||||||
() =>
|
() =>
|
||||||
parsedContacts
|
parsedContacts
|
||||||
@@ -453,17 +422,12 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch
|
|||||||
isAddAttendeeModalOpen,
|
isAddAttendeeModalOpen,
|
||||||
openAddAttendeeModal: () => setIsAddAttendeeModalOpen(true),
|
openAddAttendeeModal: () => setIsAddAttendeeModalOpen(true),
|
||||||
closeAddAttendeeModal: () => setIsAddAttendeeModalOpen(false),
|
closeAddAttendeeModal: () => setIsAddAttendeeModalOpen(false),
|
||||||
selectedAttendee,
|
|
||||||
setSelectedAttendee,
|
|
||||||
attendeeToRemove,
|
attendeeToRemove,
|
||||||
requestRemoveAttendee: (attendee) => setAttendeeToRemove(attendee),
|
requestRemoveAttendee: (attendee) => setAttendeeToRemove(attendee),
|
||||||
cancelRemoveAttendee: () => setAttendeeToRemove(null),
|
cancelRemoveAttendee: () => setAttendeeToRemove(null),
|
||||||
confirmRemoveAttendee: (promoteFromWaitlist) => {
|
confirmRemoveAttendee: (promoteFromWaitlist) => {
|
||||||
if (!attendeeToRemove) return
|
if (!attendeeToRemove) return
|
||||||
removeAttendeeMutation.mutate({
|
removeAttendeeMutation.removeAttendee({ attendee: attendeeToRemove, promoteFromWaitlist })
|
||||||
attendeeId: attendeeToRemove.id,
|
|
||||||
promoteFromWaitlist,
|
|
||||||
})
|
|
||||||
},
|
},
|
||||||
selectedWaitlistEntry,
|
selectedWaitlistEntry,
|
||||||
setSelectedWaitlistEntry,
|
setSelectedWaitlistEntry,
|
||||||
@@ -490,7 +454,7 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch
|
|||||||
isSubmittingForcedAttendee: createAttendeeForceMutation.isPending,
|
isSubmittingForcedAttendee: createAttendeeForceMutation.isPending,
|
||||||
isSubmittingWaitlistEntry: addToWaitlistMutation.isPending,
|
isSubmittingWaitlistEntry: addToWaitlistMutation.isPending,
|
||||||
isSubmittingBulkImport: bulkImportMutation.isPending,
|
isSubmittingBulkImport: bulkImportMutation.isPending,
|
||||||
isSubmittingRemoval: removeAttendeeMutation.isPending,
|
isSubmittingRemoval: removeAttendeeMutation.isRemovingAttendee,
|
||||||
isSubmittingPromotion: promoteWaitlistMutation.isPending,
|
isSubmittingPromotion: promoteWaitlistMutation.isPending,
|
||||||
isSubmittingWaitlistRemoval: removeWaitlistEntryMutation.isPending,
|
isSubmittingWaitlistRemoval: removeWaitlistEntryMutation.isPending,
|
||||||
isRegeneratingInvite: regenerateTokenMutation.isPending,
|
isRegeneratingInvite: regenerateTokenMutation.isPending,
|
||||||
@@ -522,7 +486,6 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch
|
|||||||
copyInviteLink,
|
copyInviteLink,
|
||||||
copyWhatsappMessage,
|
copyWhatsappMessage,
|
||||||
openWhatsapp,
|
openWhatsapp,
|
||||||
copyAbsenceNotifyUrl,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return <GroupDetailContext.Provider value={value}>{children}</GroupDetailContext.Provider>
|
return <GroupDetailContext.Provider value={value}>{children}</GroupDetailContext.Provider>
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ import { useNavigate } from '@tanstack/react-router'
|
|||||||
import { Loader2 } from 'lucide-react'
|
import { Loader2 } from 'lucide-react'
|
||||||
import { Button } from '../../../components/ui'
|
import { Button } from '../../../components/ui'
|
||||||
import { AddAttendeeModal } from './AddAttendeeModal'
|
import { AddAttendeeModal } from './AddAttendeeModal'
|
||||||
import { AttendeeDetailModal } from './AttendeeDetailModal'
|
|
||||||
import { BulkCapacityModal } from './BulkCapacityModal'
|
import { BulkCapacityModal } from './BulkCapacityModal'
|
||||||
import { CapacityModal } from './CapacityModal'
|
import { CapacityModal } from './CapacityModal'
|
||||||
import { GroupHeader } from './GroupHeader'
|
import { GroupHeader } from './GroupHeader'
|
||||||
@@ -14,7 +13,16 @@ import { useGroupDetail } from './GroupDetailProvider'
|
|||||||
import { WaitlistEntryDetailModal } from './WaitlistEntryDetailModal'
|
import { WaitlistEntryDetailModal } from './WaitlistEntryDetailModal'
|
||||||
|
|
||||||
export function GroupDetailView() {
|
export function GroupDetailView() {
|
||||||
const { group, groupQueryPending } = useGroupDetail()
|
const {
|
||||||
|
group,
|
||||||
|
groupQueryPending,
|
||||||
|
attendeeToRemove,
|
||||||
|
cancelRemoveAttendee,
|
||||||
|
confirmRemoveAttendee,
|
||||||
|
firstWaitlistEntry,
|
||||||
|
waitlistTotal,
|
||||||
|
isSubmittingRemoval,
|
||||||
|
} = useGroupDetail()
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
|
|
||||||
if (groupQueryPending) {
|
if (groupQueryPending) {
|
||||||
@@ -47,8 +55,16 @@ export function GroupDetailView() {
|
|||||||
<AddAttendeeModal />
|
<AddAttendeeModal />
|
||||||
<CapacityModal />
|
<CapacityModal />
|
||||||
<BulkCapacityModal />
|
<BulkCapacityModal />
|
||||||
<AttendeeDetailModal />
|
<RemoveAttendeeModal
|
||||||
<RemoveAttendeeModal />
|
attendee={attendeeToRemove}
|
||||||
|
groupName={group?.name}
|
||||||
|
firstWaitlistEntry={firstWaitlistEntry}
|
||||||
|
waitlistTotal={waitlistTotal}
|
||||||
|
isResolvingWaitlist={false}
|
||||||
|
isSubmitting={isSubmittingRemoval}
|
||||||
|
onCancel={cancelRemoveAttendee}
|
||||||
|
onConfirm={confirmRemoveAttendee}
|
||||||
|
/>
|
||||||
<WaitlistEntryDetailModal />
|
<WaitlistEntryDetailModal />
|
||||||
</section>
|
</section>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,9 +1,15 @@
|
|||||||
import type { AttendeeDto } from '@gruperly/shared'
|
import type { AttendeeDto } from '@gruperly/shared'
|
||||||
|
import { useNavigate } from '@tanstack/react-router'
|
||||||
import { ChevronRight } from 'lucide-react'
|
import { ChevronRight } from 'lucide-react'
|
||||||
import { useGroupDetail } from './GroupDetailProvider'
|
import { useGroupDetail } from './GroupDetailProvider'
|
||||||
|
|
||||||
export function MembersTable({ attendees }: { attendees: AttendeeDto[] }) {
|
export function MembersTable({ attendees }: { attendees: AttendeeDto[] }) {
|
||||||
const { setSelectedAttendee } = useGroupDetail()
|
const { groupId } = useGroupDetail()
|
||||||
|
const navigate = useNavigate()
|
||||||
|
|
||||||
|
const openAttendee = (attendeeId: string) => {
|
||||||
|
void navigate({ to: '/groups/$groupId/attendees/$attendeeId', params: { groupId, attendeeId } })
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="overflow-x-auto">
|
<div className="overflow-x-auto">
|
||||||
@@ -20,7 +26,7 @@ export function MembersTable({ attendees }: { attendees: AttendeeDto[] }) {
|
|||||||
<tr
|
<tr
|
||||||
key={attendee.id}
|
key={attendee.id}
|
||||||
className="cursor-pointer transition-colors hover:bg-primary-soft/50"
|
className="cursor-pointer transition-colors hover:bg-primary-soft/50"
|
||||||
onClick={() => setSelectedAttendee(attendee)}
|
onClick={() => openAttendee(attendee.id)}
|
||||||
>
|
>
|
||||||
<td className="px-3 py-3">
|
<td className="px-3 py-3">
|
||||||
<div className="flex items-center gap-2.5">
|
<div className="flex items-center gap-2.5">
|
||||||
|
|||||||
@@ -1,37 +1,51 @@
|
|||||||
|
import type { AttendeeDto, GroupWaitlistEntryDto } from '@gruperly/shared'
|
||||||
import { Clock, Loader2, Trash2, UserCheck, UserMinus } from 'lucide-react'
|
import { Clock, Loader2, Trash2, UserCheck, UserMinus } from 'lucide-react'
|
||||||
import { Button, Modal } from '../../../components/ui'
|
import { Button, Modal } from '../../../components/ui'
|
||||||
import { useGroupDetail } from './GroupDetailProvider'
|
|
||||||
|
|
||||||
export function RemoveAttendeeModal() {
|
type RemoveAttendeeModalProps = {
|
||||||
const {
|
attendee: AttendeeDto | null
|
||||||
attendeeToRemove,
|
groupName: string | undefined
|
||||||
cancelRemoveAttendee,
|
firstWaitlistEntry: GroupWaitlistEntryDto | null
|
||||||
confirmRemoveAttendee,
|
waitlistTotal: number
|
||||||
group,
|
isResolvingWaitlist: boolean
|
||||||
firstWaitlistEntry,
|
isSubmitting: boolean
|
||||||
waitlistTotal,
|
onCancel: () => void
|
||||||
isSubmittingRemoval,
|
onConfirm: (promoteFromWaitlist: boolean) => void
|
||||||
} = useGroupDetail()
|
}
|
||||||
|
|
||||||
|
export function RemoveAttendeeModal({
|
||||||
|
attendee,
|
||||||
|
groupName,
|
||||||
|
firstWaitlistEntry,
|
||||||
|
waitlistTotal,
|
||||||
|
isResolvingWaitlist,
|
||||||
|
isSubmitting,
|
||||||
|
onCancel,
|
||||||
|
onConfirm,
|
||||||
|
}: RemoveAttendeeModalProps) {
|
||||||
return (
|
return (
|
||||||
<Modal
|
<Modal
|
||||||
isOpen={attendeeToRemove !== null}
|
isOpen={attendee !== null}
|
||||||
onClose={cancelRemoveAttendee}
|
onClose={onCancel}
|
||||||
title="Quitar del grupo"
|
title="Quitar del grupo"
|
||||||
maxWidth="md"
|
maxWidth="md"
|
||||||
>
|
>
|
||||||
{attendeeToRemove ? (
|
{attendee ? (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<p className="text-sm text-foreground/70">
|
<p className="text-sm text-foreground/70">
|
||||||
{attendeeToRemove.fullName} dejará de ser miembro del grupo{' '}
|
{attendee.fullName} dejará de ser miembro del grupo{' '}
|
||||||
<strong className="text-primary">{group?.name}</strong>
|
<strong className="text-primary">{groupName}</strong>
|
||||||
{firstWaitlistEntry ? ' y el cupo quedará libre.' : '.'}
|
{firstWaitlistEntry ? ' y el cupo quedará libre.' : '.'}
|
||||||
{attendeeToRemove.phone ? (
|
{attendee.phone ? (
|
||||||
<span className="mt-1 block text-xs text-foreground/50">Teléfono: {attendeeToRemove.phone}</span>
|
<span className="mt-1 block text-xs text-foreground/50">Teléfono: {attendee.phone}</span>
|
||||||
) : null}
|
) : null}
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
{firstWaitlistEntry ? (
|
{isResolvingWaitlist ? (
|
||||||
|
<div className="flex items-center justify-center py-6">
|
||||||
|
<Loader2 className="size-5 animate-spin text-accent" />
|
||||||
|
</div>
|
||||||
|
) : firstWaitlistEntry ? (
|
||||||
<div className="space-y-3 rounded-xl border border-accent/20 bg-accent-soft p-4">
|
<div className="space-y-3 rounded-xl border border-accent/20 bg-accent-soft p-4">
|
||||||
<div className="flex items-center gap-2 text-xs font-semibold text-primary">
|
<div className="flex items-center gap-2 text-xs font-semibold text-primary">
|
||||||
<Clock className="size-4 text-accent" />
|
<Clock className="size-4 text-accent" />
|
||||||
@@ -46,11 +60,11 @@ export function RemoveAttendeeModal() {
|
|||||||
<div className="flex flex-col gap-2.5 pt-1">
|
<div className="flex flex-col gap-2.5 pt-1">
|
||||||
<Button
|
<Button
|
||||||
variant="primary"
|
variant="primary"
|
||||||
onClick={() => confirmRemoveAttendee(true)}
|
onClick={() => onConfirm(true)}
|
||||||
disabled={isSubmittingRemoval}
|
disabled={isSubmitting}
|
||||||
className="gap-2"
|
className="gap-2"
|
||||||
>
|
>
|
||||||
{isSubmittingRemoval ? (
|
{isSubmitting ? (
|
||||||
<Loader2 className="size-4 animate-spin" />
|
<Loader2 className="size-4 animate-spin" />
|
||||||
) : (
|
) : (
|
||||||
<UserCheck className="size-4" />
|
<UserCheck className="size-4" />
|
||||||
@@ -59,11 +73,11 @@ export function RemoveAttendeeModal() {
|
|||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
variant="outline"
|
variant="outline"
|
||||||
onClick={() => confirmRemoveAttendee(false)}
|
onClick={() => onConfirm(false)}
|
||||||
disabled={isSubmittingRemoval}
|
disabled={isSubmitting}
|
||||||
className="gap-2"
|
className="gap-2"
|
||||||
>
|
>
|
||||||
{isSubmittingRemoval ? (
|
{isSubmitting ? (
|
||||||
<Loader2 className="size-4 animate-spin" />
|
<Loader2 className="size-4 animate-spin" />
|
||||||
) : (
|
) : (
|
||||||
<UserMinus className="size-4" />
|
<UserMinus className="size-4" />
|
||||||
@@ -74,16 +88,16 @@ export function RemoveAttendeeModal() {
|
|||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="flex items-center justify-end gap-2.5 border-t border-border pt-2">
|
<div className="flex items-center justify-end gap-2.5 border-t border-border pt-2">
|
||||||
<Button variant="ghost" onClick={cancelRemoveAttendee}>
|
<Button variant="ghost" onClick={onCancel}>
|
||||||
Cancelar
|
Cancelar
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
variant="primary"
|
variant="primary"
|
||||||
onClick={() => confirmRemoveAttendee(false)}
|
onClick={() => onConfirm(false)}
|
||||||
disabled={isSubmittingRemoval}
|
disabled={isSubmitting}
|
||||||
className="gap-2"
|
className="gap-2"
|
||||||
>
|
>
|
||||||
{isSubmittingRemoval ? (
|
{isSubmitting ? (
|
||||||
<Loader2 className="size-4 animate-spin" />
|
<Loader2 className="size-4 animate-spin" />
|
||||||
) : (
|
) : (
|
||||||
<Trash2 className="size-4" />
|
<Trash2 className="size-4" />
|
||||||
|
|||||||
49
apps/web/src/features/groups/detail/useRemoveAttendee.ts
Normal file
49
apps/web/src/features/groups/detail/useRemoveAttendee.ts
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||||
|
import type { AttendeeDto, RemoveAttendeeResult } from '@gruperly/shared'
|
||||||
|
import { useToast } from '../../../components/ui'
|
||||||
|
import { ApiError, removeGroupAttendee } from '../../../lib/api'
|
||||||
|
|
||||||
|
type RemoveAttendeePayload = {
|
||||||
|
attendee: AttendeeDto
|
||||||
|
promoteFromWaitlist: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
type UseRemoveAttendeeOptions = {
|
||||||
|
groupId: string
|
||||||
|
onRemoved?: (result: RemoveAttendeeResult) => void
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useRemoveAttendee({ groupId, onRemoved }: UseRemoveAttendeeOptions) {
|
||||||
|
const queryClient = useQueryClient()
|
||||||
|
const toast = useToast()
|
||||||
|
|
||||||
|
const mutation = useMutation({
|
||||||
|
mutationFn: ({ attendee, promoteFromWaitlist }: RemoveAttendeePayload) =>
|
||||||
|
removeGroupAttendee(groupId, attendee.id, { promoteFromWaitlist }),
|
||||||
|
onSuccess: (result, { attendee }) => {
|
||||||
|
if (result.promoted) {
|
||||||
|
toast.success(
|
||||||
|
`${attendee.fullName} fue quitado del grupo y ${result.promoted.fullName} pasó de la lista de espera al grupo.`,
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
toast.success(`${attendee.fullName} fue quitado del grupo.`)
|
||||||
|
}
|
||||||
|
void queryClient.invalidateQueries({ queryKey: ['group-attendees', groupId] })
|
||||||
|
void queryClient.invalidateQueries({ queryKey: ['group-waitlist', groupId] })
|
||||||
|
void queryClient.invalidateQueries({ queryKey: ['group', groupId] })
|
||||||
|
onRemoved?.(result)
|
||||||
|
},
|
||||||
|
onError: (err: Error) => {
|
||||||
|
if (err instanceof ApiError && err.problem?.code === 'attendee_has_payments') {
|
||||||
|
toast.error(err.problem.detail ?? 'Este miembro tiene cobros asociados.')
|
||||||
|
} else {
|
||||||
|
toast.error(err.message || 'Error al quitar al miembro del grupo.')
|
||||||
|
}
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
return {
|
||||||
|
removeAttendee: (payload: RemoveAttendeePayload) => mutation.mutate(payload),
|
||||||
|
isRemovingAttendee: mutation.isPending,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ import type {
|
|||||||
AttendeeDto,
|
AttendeeDto,
|
||||||
AttendeeHistory,
|
AttendeeHistory,
|
||||||
AttendeeList,
|
AttendeeList,
|
||||||
|
AttendeeStats,
|
||||||
AttendeeStatus,
|
AttendeeStatus,
|
||||||
BulkCreateAttendees,
|
BulkCreateAttendees,
|
||||||
BulkCreateAttendeesResult,
|
BulkCreateAttendeesResult,
|
||||||
@@ -163,6 +164,9 @@ export const bulkCreateAttendees = (groupId: string, payload: BulkCreateAttendee
|
|||||||
export const getGroupAttendees = (groupId: string, page = 1, pageSize = 20) =>
|
export const getGroupAttendees = (groupId: string, page = 1, pageSize = 20) =>
|
||||||
apiFetch<AttendeeList>(`/api/v1/groups/${groupId}/attendees?page=${page}&pageSize=${pageSize}`)
|
apiFetch<AttendeeList>(`/api/v1/groups/${groupId}/attendees?page=${page}&pageSize=${pageSize}`)
|
||||||
|
|
||||||
|
export const getGroupAttendee = (groupId: string, attendeeId: string) =>
|
||||||
|
apiFetch<AttendeeDto>(`/api/v1/groups/${groupId}/attendees/${attendeeId}`)
|
||||||
|
|
||||||
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}`)
|
||||||
|
|
||||||
@@ -230,6 +234,9 @@ export const getGroupsRiskOverview = () => apiFetch<GroupsRiskOverview>('/api/v1
|
|||||||
export const getAttendeeHistory = (groupId: string, attendeeId: string) =>
|
export const getAttendeeHistory = (groupId: string, attendeeId: string) =>
|
||||||
apiFetch<AttendeeHistory>(`/api/v1/groups/${groupId}/attendees/${attendeeId}/history`)
|
apiFetch<AttendeeHistory>(`/api/v1/groups/${groupId}/attendees/${attendeeId}/history`)
|
||||||
|
|
||||||
|
export const getAttendeeStats = (groupId: string, attendeeId: string) =>
|
||||||
|
apiFetch<AttendeeStats>(`/api/v1/groups/${groupId}/attendees/${attendeeId}/stats`)
|
||||||
|
|
||||||
export const updateAttendeeStatus = (attendeeId: string, status: AttendeeStatus) =>
|
export const updateAttendeeStatus = (attendeeId: string, status: AttendeeStatus) =>
|
||||||
apiFetch<UpdateStudentStatusResult>(`/api/v1/students/${attendeeId}/status`, {
|
apiFetch<UpdateStudentStatusResult>(`/api/v1/students/${attendeeId}/status`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ import { Route as AuthenticatedGroupsNewRouteImport } from './routes/_authentica
|
|||||||
import { Route as AuthenticatedClassSessionIdAttendanceRouteImport } from './routes/_authenticated/class/$sessionId/attendance'
|
import { Route as AuthenticatedClassSessionIdAttendanceRouteImport } from './routes/_authenticated/class/$sessionId/attendance'
|
||||||
import { Route as AuthenticatedGroupsGroupIdIndexRouteImport } from './routes/_authenticated/groups/$groupId/index'
|
import { Route as AuthenticatedGroupsGroupIdIndexRouteImport } from './routes/_authenticated/groups/$groupId/index'
|
||||||
import { Route as AuthenticatedGroupsGroupIdAnalyticsRouteImport } from './routes/_authenticated/groups/$groupId/analytics'
|
import { Route as AuthenticatedGroupsGroupIdAnalyticsRouteImport } from './routes/_authenticated/groups/$groupId/analytics'
|
||||||
|
import { Route as AuthenticatedGroupsGroupIdAttendeesAttendeeIdRouteImport } from './routes/_authenticated/groups/$groupId/attendees/$attendeeId'
|
||||||
|
|
||||||
const AuthenticatedRoute = AuthenticatedRouteImport.update({
|
const AuthenticatedRoute = AuthenticatedRouteImport.update({
|
||||||
id: '/_authenticated',
|
id: '/_authenticated',
|
||||||
@@ -115,6 +116,12 @@ const AuthenticatedGroupsGroupIdAnalyticsRoute =
|
|||||||
path: '/groups/$groupId/analytics',
|
path: '/groups/$groupId/analytics',
|
||||||
getParentRoute: () => AuthenticatedRoute,
|
getParentRoute: () => AuthenticatedRoute,
|
||||||
} as any)
|
} as any)
|
||||||
|
const AuthenticatedGroupsGroupIdAttendeesAttendeeIdRoute =
|
||||||
|
AuthenticatedGroupsGroupIdAttendeesAttendeeIdRouteImport.update({
|
||||||
|
id: '/groups/$groupId/attendees/$attendeeId',
|
||||||
|
path: '/groups/$groupId/attendees/$attendeeId',
|
||||||
|
getParentRoute: () => AuthenticatedRoute,
|
||||||
|
} as any)
|
||||||
|
|
||||||
export interface FileRoutesByFullPath {
|
export interface FileRoutesByFullPath {
|
||||||
'/': typeof AuthenticatedIndexRoute
|
'/': typeof AuthenticatedIndexRoute
|
||||||
@@ -133,6 +140,7 @@ export interface FileRoutesByFullPath {
|
|||||||
'/class/$sessionId/attendance': typeof AuthenticatedClassSessionIdAttendanceRoute
|
'/class/$sessionId/attendance': typeof AuthenticatedClassSessionIdAttendanceRoute
|
||||||
'/groups/$groupId/analytics': typeof AuthenticatedGroupsGroupIdAnalyticsRoute
|
'/groups/$groupId/analytics': typeof AuthenticatedGroupsGroupIdAnalyticsRoute
|
||||||
'/groups/$groupId/': typeof AuthenticatedGroupsGroupIdIndexRoute
|
'/groups/$groupId/': typeof AuthenticatedGroupsGroupIdIndexRoute
|
||||||
|
'/groups/$groupId/attendees/$attendeeId': typeof AuthenticatedGroupsGroupIdAttendeesAttendeeIdRoute
|
||||||
}
|
}
|
||||||
export interface FileRoutesByTo {
|
export interface FileRoutesByTo {
|
||||||
'/login': typeof LoginRoute
|
'/login': typeof LoginRoute
|
||||||
@@ -151,6 +159,7 @@ export interface FileRoutesByTo {
|
|||||||
'/class/$sessionId/attendance': typeof AuthenticatedClassSessionIdAttendanceRoute
|
'/class/$sessionId/attendance': typeof AuthenticatedClassSessionIdAttendanceRoute
|
||||||
'/groups/$groupId/analytics': typeof AuthenticatedGroupsGroupIdAnalyticsRoute
|
'/groups/$groupId/analytics': typeof AuthenticatedGroupsGroupIdAnalyticsRoute
|
||||||
'/groups/$groupId': typeof AuthenticatedGroupsGroupIdIndexRoute
|
'/groups/$groupId': typeof AuthenticatedGroupsGroupIdIndexRoute
|
||||||
|
'/groups/$groupId/attendees/$attendeeId': typeof AuthenticatedGroupsGroupIdAttendeesAttendeeIdRoute
|
||||||
}
|
}
|
||||||
export interface FileRoutesById {
|
export interface FileRoutesById {
|
||||||
__root__: typeof rootRouteImport
|
__root__: typeof rootRouteImport
|
||||||
@@ -171,6 +180,7 @@ export interface FileRoutesById {
|
|||||||
'/_authenticated/class/$sessionId/attendance': typeof AuthenticatedClassSessionIdAttendanceRoute
|
'/_authenticated/class/$sessionId/attendance': typeof AuthenticatedClassSessionIdAttendanceRoute
|
||||||
'/_authenticated/groups/$groupId/analytics': typeof AuthenticatedGroupsGroupIdAnalyticsRoute
|
'/_authenticated/groups/$groupId/analytics': typeof AuthenticatedGroupsGroupIdAnalyticsRoute
|
||||||
'/_authenticated/groups/$groupId/': typeof AuthenticatedGroupsGroupIdIndexRoute
|
'/_authenticated/groups/$groupId/': typeof AuthenticatedGroupsGroupIdIndexRoute
|
||||||
|
'/_authenticated/groups/$groupId/attendees/$attendeeId': typeof AuthenticatedGroupsGroupIdAttendeesAttendeeIdRoute
|
||||||
}
|
}
|
||||||
export interface FileRouteTypes {
|
export interface FileRouteTypes {
|
||||||
fileRoutesByFullPath: FileRoutesByFullPath
|
fileRoutesByFullPath: FileRoutesByFullPath
|
||||||
@@ -191,6 +201,7 @@ export interface FileRouteTypes {
|
|||||||
| '/class/$sessionId/attendance'
|
| '/class/$sessionId/attendance'
|
||||||
| '/groups/$groupId/analytics'
|
| '/groups/$groupId/analytics'
|
||||||
| '/groups/$groupId/'
|
| '/groups/$groupId/'
|
||||||
|
| '/groups/$groupId/attendees/$attendeeId'
|
||||||
fileRoutesByTo: FileRoutesByTo
|
fileRoutesByTo: FileRoutesByTo
|
||||||
to:
|
to:
|
||||||
| '/login'
|
| '/login'
|
||||||
@@ -209,6 +220,7 @@ export interface FileRouteTypes {
|
|||||||
| '/class/$sessionId/attendance'
|
| '/class/$sessionId/attendance'
|
||||||
| '/groups/$groupId/analytics'
|
| '/groups/$groupId/analytics'
|
||||||
| '/groups/$groupId'
|
| '/groups/$groupId'
|
||||||
|
| '/groups/$groupId/attendees/$attendeeId'
|
||||||
id:
|
id:
|
||||||
| '__root__'
|
| '__root__'
|
||||||
| '/_authenticated'
|
| '/_authenticated'
|
||||||
@@ -228,6 +240,7 @@ export interface FileRouteTypes {
|
|||||||
| '/_authenticated/class/$sessionId/attendance'
|
| '/_authenticated/class/$sessionId/attendance'
|
||||||
| '/_authenticated/groups/$groupId/analytics'
|
| '/_authenticated/groups/$groupId/analytics'
|
||||||
| '/_authenticated/groups/$groupId/'
|
| '/_authenticated/groups/$groupId/'
|
||||||
|
| '/_authenticated/groups/$groupId/attendees/$attendeeId'
|
||||||
fileRoutesById: FileRoutesById
|
fileRoutesById: FileRoutesById
|
||||||
}
|
}
|
||||||
export interface RootRouteChildren {
|
export interface RootRouteChildren {
|
||||||
@@ -361,6 +374,13 @@ declare module '@tanstack/react-router' {
|
|||||||
preLoaderRoute: typeof AuthenticatedGroupsGroupIdAnalyticsRouteImport
|
preLoaderRoute: typeof AuthenticatedGroupsGroupIdAnalyticsRouteImport
|
||||||
parentRoute: typeof AuthenticatedRoute
|
parentRoute: typeof AuthenticatedRoute
|
||||||
}
|
}
|
||||||
|
'/_authenticated/groups/$groupId/attendees/$attendeeId': {
|
||||||
|
id: '/_authenticated/groups/$groupId/attendees/$attendeeId'
|
||||||
|
path: '/groups/$groupId/attendees/$attendeeId'
|
||||||
|
fullPath: '/groups/$groupId/attendees/$attendeeId'
|
||||||
|
preLoaderRoute: typeof AuthenticatedGroupsGroupIdAttendeesAttendeeIdRouteImport
|
||||||
|
parentRoute: typeof AuthenticatedRoute
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -375,6 +395,7 @@ interface AuthenticatedRouteChildren {
|
|||||||
AuthenticatedClassSessionIdAttendanceRoute: typeof AuthenticatedClassSessionIdAttendanceRoute
|
AuthenticatedClassSessionIdAttendanceRoute: typeof AuthenticatedClassSessionIdAttendanceRoute
|
||||||
AuthenticatedGroupsGroupIdAnalyticsRoute: typeof AuthenticatedGroupsGroupIdAnalyticsRoute
|
AuthenticatedGroupsGroupIdAnalyticsRoute: typeof AuthenticatedGroupsGroupIdAnalyticsRoute
|
||||||
AuthenticatedGroupsGroupIdIndexRoute: typeof AuthenticatedGroupsGroupIdIndexRoute
|
AuthenticatedGroupsGroupIdIndexRoute: typeof AuthenticatedGroupsGroupIdIndexRoute
|
||||||
|
AuthenticatedGroupsGroupIdAttendeesAttendeeIdRoute: typeof AuthenticatedGroupsGroupIdAttendeesAttendeeIdRoute
|
||||||
}
|
}
|
||||||
|
|
||||||
const AuthenticatedRouteChildren: AuthenticatedRouteChildren = {
|
const AuthenticatedRouteChildren: AuthenticatedRouteChildren = {
|
||||||
@@ -390,6 +411,8 @@ const AuthenticatedRouteChildren: AuthenticatedRouteChildren = {
|
|||||||
AuthenticatedGroupsGroupIdAnalyticsRoute:
|
AuthenticatedGroupsGroupIdAnalyticsRoute:
|
||||||
AuthenticatedGroupsGroupIdAnalyticsRoute,
|
AuthenticatedGroupsGroupIdAnalyticsRoute,
|
||||||
AuthenticatedGroupsGroupIdIndexRoute: AuthenticatedGroupsGroupIdIndexRoute,
|
AuthenticatedGroupsGroupIdIndexRoute: AuthenticatedGroupsGroupIdIndexRoute,
|
||||||
|
AuthenticatedGroupsGroupIdAttendeesAttendeeIdRoute:
|
||||||
|
AuthenticatedGroupsGroupIdAttendeesAttendeeIdRoute,
|
||||||
}
|
}
|
||||||
|
|
||||||
const AuthenticatedRouteWithChildren = AuthenticatedRoute._addFileChildren(
|
const AuthenticatedRouteWithChildren = AuthenticatedRoute._addFileChildren(
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import { useParams } from '@tanstack/react-router'
|
||||||
|
import { createFileRoute } from '@tanstack/react-router'
|
||||||
|
import { AttendeeDetailPage } from '../../../../../features/groups/detail/AttendeeDetailPage'
|
||||||
|
import { AttendeeDetailProvider } from '../../../../../features/groups/detail/AttendeeDetailProvider'
|
||||||
|
|
||||||
|
export const Route = createFileRoute('/_authenticated/groups/$groupId/attendees/$attendeeId')({
|
||||||
|
component: () => {
|
||||||
|
const { groupId, attendeeId } = useParams({
|
||||||
|
from: '/_authenticated/groups/$groupId/attendees/$attendeeId',
|
||||||
|
})
|
||||||
|
return (
|
||||||
|
<AttendeeDetailProvider groupId={groupId} attendeeId={attendeeId}>
|
||||||
|
<AttendeeDetailPage />
|
||||||
|
</AttendeeDetailProvider>
|
||||||
|
)
|
||||||
|
},
|
||||||
|
})
|
||||||
@@ -22,6 +22,18 @@ export const AttendeeDtoSchema = z.object({
|
|||||||
});
|
});
|
||||||
export type AttendeeDto = z.output<typeof AttendeeDtoSchema>;
|
export type AttendeeDto = z.output<typeof AttendeeDtoSchema>;
|
||||||
|
|
||||||
|
export const AttendeeStatsSchema = z.object({
|
||||||
|
attendeeId: z.string(),
|
||||||
|
groupId: z.string(),
|
||||||
|
presentCount: z.number().int().min(0),
|
||||||
|
absentCount: z.number().int().min(0),
|
||||||
|
excusedCount: z.number().int().min(0),
|
||||||
|
totalMarked: z.number().int().min(0),
|
||||||
|
attendanceRate: z.number().min(0).max(100),
|
||||||
|
});
|
||||||
|
export type AttendeeStats = z.output<typeof AttendeeStatsSchema>;
|
||||||
|
export type AttendeeStatsDto = AttendeeStats;
|
||||||
|
|
||||||
export const AttendeeQuerySchema = z.object({
|
export const AttendeeQuerySchema = z.object({
|
||||||
page: pageSchema,
|
page: pageSchema,
|
||||||
pageSize: pageSizeSchema,
|
pageSize: pageSizeSchema,
|
||||||
|
|||||||
Reference in New Issue
Block a user