From 2e184845e16b7103be2c63ad0805bba15972fbcb Mon Sep 17 00:00:00 2001 From: Jose Selesan Date: Wed, 23 Sep 2026 16:24:45 -0300 Subject: [PATCH 1/6] feat: add absence notification and analytics features - Implemented AbsenceNotifyView for notifying absence with session details. - Created AnalyticsView for displaying group analytics and managing students at risk. - Added ClassAttendanceView for marking attendance in classes. - Defined new schemas for analytics and attendance in shared package. --- .../migration.sql | 68 +++ .../migration.sql | 5 + apps/backend/prisma/models/attendance.prisma | 50 ++ apps/backend/prisma/models/domain.prisma | 21 +- apps/backend/src/app.ts | 4 + apps/backend/src/http/session-auth.ts | 13 +- .../features/get-attendee-history/route.ts | 21 + .../features/get-attendee-history/use-case.ts | 83 +++ .../analytics/features/get-overview/route.ts | 20 + .../features/get-overview/use-case.ts | 55 ++ .../features/get-students-at-risk/route.ts | 20 + .../features/get-students-at-risk/use-case.ts | 122 +++++ .../features/update-attendee-status/route.ts | 24 + .../update-attendee-status/use-case.ts | 53 ++ apps/backend/src/modules/analytics/index.ts | 2 + .../src/modules/analytics/lib/access.ts | 37 ++ .../backend/src/modules/analytics/lib/risk.ts | 56 ++ apps/backend/src/modules/analytics/routes.ts | 12 + .../attendees/features/create/use-case.ts | 4 +- .../src/modules/attendees/lib/helpers.ts | 2 + .../classes/features/mark-attendance/route.ts | 24 + .../features/mark-attendance/use-case.ts | 105 ++++ .../classes/features/notify-absence/route.ts | 24 + .../features/notify-absence/use-case.ts | 71 +++ .../classes/features/public-details/route.ts | 19 + .../features/public-details/use-case.ts | 93 ++++ .../classes/features/public-notify/route.ts | 19 + .../features/public-notify/use-case.ts | 48 ++ .../features/session-students/route.ts | 24 + .../features/session-students/use-case.ts | 112 ++++ .../modules/classes/features/today/route.ts | 23 + .../classes/features/today/use-case.ts | 82 +++ apps/backend/src/modules/classes/index.ts | 1 + .../src/modules/classes/lib/helpers.ts | 92 ++++ apps/backend/src/modules/classes/lib/index.ts | 3 + .../backend/src/modules/classes/lib/notify.ts | 91 ++++ .../src/modules/classes/lib/sessions.ts | 64 +++ apps/backend/src/modules/classes/routes.ts | 18 + .../src/modules/group-waitlist/lib/promote.ts | 4 +- apps/backend/src/modules/groups/routes.ts | 2 + .../backend/src/modules/home/lib/scheduler.ts | 46 +- .../features/join-via-invite/use-case.ts | 4 +- apps/backend/test/analytics-risk.test.ts | 79 +++ apps/backend/test/analytics.test.ts | 325 +++++++++++ apps/backend/test/attendees.test.ts | 1 + apps/backend/test/classes.test.ts | 507 ++++++++++++++++++ apps/backend/test/session-auth.test.ts | 12 + apps/web/src/lib/api.ts | 75 ++- apps/web/src/router.tsx | 25 + apps/web/src/routes/absence-notify.tsx | 164 ++++++ apps/web/src/routes/analytics.tsx | 472 ++++++++++++++++ apps/web/src/routes/class-attendance.tsx | 259 +++++++++ apps/web/src/routes/group-detail.tsx | 47 ++ apps/web/src/routes/home.tsx | 87 ++- packages/shared/src/index.ts | 2 + packages/shared/src/schemas/analytics.ts | 67 +++ packages/shared/src/schemas/attendance.ts | 111 ++++ packages/shared/src/schemas/attendees.ts | 1 + packages/shared/src/schemas/home.ts | 2 + 59 files changed, 3854 insertions(+), 23 deletions(-) create mode 100644 apps/backend/prisma/migrations/20260923120000_add_class_sessions_attendance/migration.sql create mode 100644 apps/backend/prisma/migrations/20260923172527_add_attendee_status/migration.sql create mode 100644 apps/backend/prisma/models/attendance.prisma create mode 100644 apps/backend/src/modules/analytics/features/get-attendee-history/route.ts create mode 100644 apps/backend/src/modules/analytics/features/get-attendee-history/use-case.ts create mode 100644 apps/backend/src/modules/analytics/features/get-overview/route.ts create mode 100644 apps/backend/src/modules/analytics/features/get-overview/use-case.ts create mode 100644 apps/backend/src/modules/analytics/features/get-students-at-risk/route.ts create mode 100644 apps/backend/src/modules/analytics/features/get-students-at-risk/use-case.ts create mode 100644 apps/backend/src/modules/analytics/features/update-attendee-status/route.ts create mode 100644 apps/backend/src/modules/analytics/features/update-attendee-status/use-case.ts create mode 100644 apps/backend/src/modules/analytics/index.ts create mode 100644 apps/backend/src/modules/analytics/lib/access.ts create mode 100644 apps/backend/src/modules/analytics/lib/risk.ts create mode 100644 apps/backend/src/modules/analytics/routes.ts create mode 100644 apps/backend/src/modules/classes/features/mark-attendance/route.ts create mode 100644 apps/backend/src/modules/classes/features/mark-attendance/use-case.ts create mode 100644 apps/backend/src/modules/classes/features/notify-absence/route.ts create mode 100644 apps/backend/src/modules/classes/features/notify-absence/use-case.ts create mode 100644 apps/backend/src/modules/classes/features/public-details/route.ts create mode 100644 apps/backend/src/modules/classes/features/public-details/use-case.ts create mode 100644 apps/backend/src/modules/classes/features/public-notify/route.ts create mode 100644 apps/backend/src/modules/classes/features/public-notify/use-case.ts create mode 100644 apps/backend/src/modules/classes/features/session-students/route.ts create mode 100644 apps/backend/src/modules/classes/features/session-students/use-case.ts create mode 100644 apps/backend/src/modules/classes/features/today/route.ts create mode 100644 apps/backend/src/modules/classes/features/today/use-case.ts create mode 100644 apps/backend/src/modules/classes/index.ts create mode 100644 apps/backend/src/modules/classes/lib/helpers.ts create mode 100644 apps/backend/src/modules/classes/lib/index.ts create mode 100644 apps/backend/src/modules/classes/lib/notify.ts create mode 100644 apps/backend/src/modules/classes/lib/sessions.ts create mode 100644 apps/backend/src/modules/classes/routes.ts create mode 100644 apps/backend/test/analytics-risk.test.ts create mode 100644 apps/backend/test/analytics.test.ts create mode 100644 apps/backend/test/classes.test.ts create mode 100644 apps/web/src/routes/absence-notify.tsx create mode 100644 apps/web/src/routes/analytics.tsx create mode 100644 apps/web/src/routes/class-attendance.tsx create mode 100644 packages/shared/src/schemas/analytics.ts create mode 100644 packages/shared/src/schemas/attendance.ts diff --git a/apps/backend/prisma/migrations/20260923120000_add_class_sessions_attendance/migration.sql b/apps/backend/prisma/migrations/20260923120000_add_class_sessions_attendance/migration.sql new file mode 100644 index 0000000..6384f24 --- /dev/null +++ b/apps/backend/prisma/migrations/20260923120000_add_class_sessions_attendance/migration.sql @@ -0,0 +1,68 @@ +-- CreateEnum +CREATE TYPE "AttendanceStatus" AS ENUM ('PRESENT', 'ABSENT', 'EXCUSED'); + +-- AlterTable +ALTER TABLE "attendees" ADD COLUMN "notifyToken" TEXT; + +-- CreateTable +CREATE TABLE "class_sessions" ( + "id" TEXT NOT NULL, + "groupId" TEXT NOT NULL, + "startsAt" TIMESTAMP(3) NOT NULL, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "class_sessions_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "attendances" ( + "id" TEXT NOT NULL, + "attendeeId" TEXT NOT NULL, + "classSessionId" TEXT NOT NULL, + "status" "AttendanceStatus" NOT NULL, + "markedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "attendances_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "slot_releases" ( + "id" TEXT NOT NULL, + "attendeeId" TEXT NOT NULL, + "classSessionId" TEXT NOT NULL, + "isClaimed" BOOLEAN NOT NULL DEFAULT false, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "slot_releases_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE UNIQUE INDEX "class_sessions_groupId_startsAt_key" ON "class_sessions"("groupId", "startsAt"); + +-- CreateIndex +CREATE UNIQUE INDEX "attendances_attendeeId_classSessionId_key" ON "attendances"("attendeeId", "classSessionId"); + +-- CreateIndex +CREATE UNIQUE INDEX "slot_releases_attendeeId_classSessionId_key" ON "slot_releases"("attendeeId", "classSessionId"); + +-- CreateIndex +CREATE UNIQUE INDEX "attendees_notifyToken_key" ON "attendees"("notifyToken"); + +-- AddForeignKey +ALTER TABLE "class_sessions" ADD CONSTRAINT "class_sessions_groupId_fkey" FOREIGN KEY ("groupId") REFERENCES "groups"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "attendances" ADD CONSTRAINT "attendances_attendeeId_fkey" FOREIGN KEY ("attendeeId") REFERENCES "attendees"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "attendances" ADD CONSTRAINT "attendances_classSessionId_fkey" FOREIGN KEY ("classSessionId") REFERENCES "class_sessions"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "slot_releases" ADD CONSTRAINT "slot_releases_attendeeId_fkey" FOREIGN KEY ("attendeeId") REFERENCES "attendees"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "slot_releases" ADD CONSTRAINT "slot_releases_classSessionId_fkey" FOREIGN KEY ("classSessionId") REFERENCES "class_sessions"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- Backfill: tokens de aviso de ausencia para alumnos existentes +UPDATE "attendees" SET "notifyToken" = gen_random_uuid()::text WHERE "notifyToken" IS NULL; diff --git a/apps/backend/prisma/migrations/20260923172527_add_attendee_status/migration.sql b/apps/backend/prisma/migrations/20260923172527_add_attendee_status/migration.sql new file mode 100644 index 0000000..66cabe9 --- /dev/null +++ b/apps/backend/prisma/migrations/20260923172527_add_attendee_status/migration.sql @@ -0,0 +1,5 @@ +-- CreateEnum +CREATE TYPE "AttendeeStatus" AS ENUM ('ACTIVE', 'PAUSED', 'DROPPED'); + +-- AlterTable +ALTER TABLE "attendees" ADD COLUMN "status" "AttendeeStatus" NOT NULL DEFAULT 'ACTIVE'; diff --git a/apps/backend/prisma/models/attendance.prisma b/apps/backend/prisma/models/attendance.prisma new file mode 100644 index 0000000..95ddf50 --- /dev/null +++ b/apps/backend/prisma/models/attendance.prisma @@ -0,0 +1,50 @@ +// Attendance & class sessions + +enum AttendanceStatus { + PRESENT + ABSENT + EXCUSED +} + +model ClassSession { + id String @id @default(cuid()) + groupId String + startsAt DateTime + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + group Group @relation(fields: [groupId], references: [id], onDelete: Cascade) + attendances Attendance[] + slotReleases SlotRelease[] + + @@unique([groupId, startsAt]) + @@map("class_sessions") +} + +model Attendance { + id String @id @default(cuid()) + attendeeId String + classSessionId String + status AttendanceStatus + markedAt DateTime @default(now()) + + attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade) + classSession ClassSession @relation(fields: [classSessionId], references: [id], onDelete: Cascade) + + @@unique([attendeeId, classSessionId]) + @@map("attendances") +} + +model SlotRelease { + id String @id @default(cuid()) + attendeeId String + classSessionId String + isClaimed Boolean @default(false) + createdAt DateTime @default(now()) + + attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade) + classSession ClassSession @relation(fields: [classSessionId], references: [id], onDelete: Cascade) + + @@unique([attendeeId, classSessionId]) + @@map("slot_releases") +} diff --git a/apps/backend/prisma/models/domain.prisma b/apps/backend/prisma/models/domain.prisma index 09a8fdb..713fa71 100644 --- a/apps/backend/prisma/models/domain.prisma +++ b/apps/backend/prisma/models/domain.prisma @@ -20,6 +20,7 @@ model Group { attendees Attendee[] payments Payment[] waitlist GroupWaitlistEntry[] + classSessions ClassSession[] @@map("groups") } @@ -59,8 +60,14 @@ enum Role { MEMBER } +enum AttendeeStatus { + ACTIVE + PAUSED + DROPPED +} + model Attendee { - id String @id @default(cuid()) + id String @id @default(cuid()) groupId String fullName String email String? @@ -68,11 +75,15 @@ model Attendee { guardianName String? guardianPhone String? notes String? - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt + notifyToken String? @unique @default(cuid()) + status AttendeeStatus @default(ACTIVE) + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt - group Group @relation(fields: [groupId], references: [id], onDelete: Cascade) - payments Payment[] + group Group @relation(fields: [groupId], references: [id], onDelete: Cascade) + payments Payment[] + attendances Attendance[] + slotReleases SlotRelease[] @@index([groupId]) @@map("attendees") diff --git a/apps/backend/src/app.ts b/apps/backend/src/app.ts index 7d511fb..8e5c5e2 100644 --- a/apps/backend/src/app.ts +++ b/apps/backend/src/app.ts @@ -10,8 +10,10 @@ import { requestLoggerMiddleware } from '@/http/request-logger'; import { corsMiddleware, securityHeadersMiddleware } from '@/http/security-headers'; import { sessionAuthMiddleware } from '@/http/session-auth'; import { logger } from '@/logger'; +import { studentStatusRoutes } from './modules/analytics'; import { attendeesRoutes } from './modules/attendees'; import { authRoutes } from './modules/auth'; +import { classesRoutes } from './modules/classes'; import { groupsRoutes } from './modules/groups'; import { healthCheckRoutes } from './modules/health-check'; import { homeRoutes } from './modules/home'; @@ -42,6 +44,8 @@ api.route('/onboarding', onboardingRoutes); api.route('/attendees', attendeesRoutes); api.route('/payments', paymentsRoutes); api.route('/waitlist', waitlistRoutes); +api.route('/classes', classesRoutes); +api.route('/students', studentStatusRoutes); app.notFound((c) => { return problemJson(c, notFoundProblem(c.req.path)); diff --git a/apps/backend/src/http/session-auth.ts b/apps/backend/src/http/session-auth.ts index b446fe0..def791f 100644 --- a/apps/backend/src/http/session-auth.ts +++ b/apps/backend/src/http/session-auth.ts @@ -27,6 +27,14 @@ export function isPublicApiRequest(method: string, path: string): boolean { const normalizedPath = normalizePath(path); + // Aviso de ausencia con token personal del alumno (sin sesión). + if (method === 'GET' && normalizedPath === '/api/v1/classes/absence') { + return true; + } + if (method === 'POST' && normalizedPath === '/api/v1/classes/notify-absence') { + return true; + } + return ( normalizedPath === '/api/v1/health' || matchesPublicPrefix(normalizedPath, '/api/v1/auth') @@ -40,5 +48,8 @@ function matchesPublicPrefix(path: string, prefix: string): boolean { } function normalizePath(path: string): string { - return path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path; + const withoutQuery = path.split('?')[0]?.split('#')[0] ?? path; + return withoutQuery.length > 1 && withoutQuery.endsWith('/') + ? withoutQuery.slice(0, -1) + : withoutQuery; } \ No newline at end of file diff --git a/apps/backend/src/modules/analytics/features/get-attendee-history/route.ts b/apps/backend/src/modules/analytics/features/get-attendee-history/route.ts new file mode 100644 index 0000000..b023827 --- /dev/null +++ b/apps/backend/src/modules/analytics/features/get-attendee-history/route.ts @@ -0,0 +1,21 @@ +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { GetAttendeeHistory } from './use-case'; + +const route = new Hono(); + +route.get('/:groupId/attendees/:attendeeId/history', 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 GetAttendeeHistory(); + const result = await useCase.execute(groupId, attendeeId, user.id); + + return resultJson(c, result); +}); + +export default route; \ No newline at end of file diff --git a/apps/backend/src/modules/analytics/features/get-attendee-history/use-case.ts b/apps/backend/src/modules/analytics/features/get-attendee-history/use-case.ts new file mode 100644 index 0000000..09a2b85 --- /dev/null +++ b/apps/backend/src/modules/analytics/features/get-attendee-history/use-case.ts @@ -0,0 +1,83 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { + AttendanceStatus, + AttendeeHistory, + ProblemDetails, + Result, +} from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { notFoundResourceProblem } from '@/http/problem-builders'; +import prisma from '@/lib/prisma'; +import { type AnalyticsAccessDb, findGroupForUser } from '../../lib/access'; + +export const HISTORY_SESSIONS_LIMIT = 20; + +type GetAttendeeHistoryDeps = { + db?: AnalyticsAccessDb & Pick; +}; + +export class GetAttendeeHistory { + constructor(private readonly deps: GetAttendeeHistoryDeps = {}) {} + + async execute( + groupId: string, + attendeeId: string, + userId: string, + ): Promise> { + 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, fullName: true }, + }); + if (!attendee) { + return err(notFoundResourceProblem('Attendee', attendeeId)); + } + + const sessions = await db.classSession.findMany({ + where: { groupId }, + orderBy: { startsAt: 'desc' }, + take: HISTORY_SESSIONS_LIMIT, + select: { id: true, startsAt: true }, + }); + const sessionIds = sessions.map((session) => session.id); + + const attendances = sessionIds.length + ? await db.attendance.findMany({ + where: { attendeeId, classSessionId: { in: sessionIds } }, + select: { classSessionId: true, status: true }, + }) + : []; + + const statusBySession = new Map( + attendances.map((record) => [record.classSessionId, record.status]), + ); + + const orderedSessions = sessions + .slice() + .reverse() + .map((session) => ({ + classSessionId: session.id, + startsAt: session.startsAt.toISOString(), + status: statusBySession.get(session.id) ?? null, + })); + + const presentCount = attendances.filter((record) => record.status === 'PRESENT').length; + const attendanceRate = + sessions.length > 0 ? Math.round((presentCount / sessions.length) * 100) : 0; + + return ok({ + attendeeId: attendee.id, + fullName: attendee.fullName, + groupId, + groupName: access.value.name, + attendanceRate, + sessions: orderedSessions, + }); + } +} \ No newline at end of file diff --git a/apps/backend/src/modules/analytics/features/get-overview/route.ts b/apps/backend/src/modules/analytics/features/get-overview/route.ts new file mode 100644 index 0000000..94e4997 --- /dev/null +++ b/apps/backend/src/modules/analytics/features/get-overview/route.ts @@ -0,0 +1,20 @@ +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { GetGroupAnalytics } from './use-case'; + +const route = new Hono(); + +route.get('/:groupId/analytics', async (c) => { + const user = c.get('user'); + if (!user) { + return problemJson(c, unauthorizedProblem(c.req.path)); + } + + const groupId = c.req.param('groupId'); + const useCase = new GetGroupAnalytics(); + const result = await useCase.execute(groupId, user.id); + + return resultJson(c, result); +}); + +export default route; \ No newline at end of file diff --git a/apps/backend/src/modules/analytics/features/get-overview/use-case.ts b/apps/backend/src/modules/analytics/features/get-overview/use-case.ts new file mode 100644 index 0000000..6d848eb --- /dev/null +++ b/apps/backend/src/modules/analytics/features/get-overview/use-case.ts @@ -0,0 +1,55 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { GroupAnalytics, ProblemDetails, Result } from '@gruperly/shared'; +import { ok } from '@gruperly/shared'; +import prisma from '@/lib/prisma'; +import { type AnalyticsAccessDb, findGroupForUser } from '../../lib/access'; + +export const ANALYTICS_WINDOW_MS = 30 * 24 * 60 * 60 * 1000; + +type GetGroupAnalyticsDeps = { + db?: AnalyticsAccessDb & Pick; + now?: Date; +}; + +export class GetGroupAnalytics { + constructor(private readonly deps: GetGroupAnalyticsDeps = {}) {} + + async execute( + groupId: string, + userId: string, + ): Promise> { + const db = this.deps.db ?? prisma; + const now = this.deps.now ?? new Date(); + const since = new Date(now.getTime() - ANALYTICS_WINDOW_MS); + + const access = await findGroupForUser(db, groupId, userId); + if (!access.ok) { + return access; + } + + const [sessions, attendances, recoveredSlots] = await Promise.all([ + db.classSession.findMany({ + where: { groupId, startsAt: { gte: since } }, + select: { id: true }, + }), + db.attendance.findMany({ + where: { classSession: { groupId, startsAt: { gte: since } } }, + select: { status: true }, + }), + db.slotRelease.count({ + where: { classSession: { groupId, startsAt: { gte: since } } }, + }), + ]); + + const totalClasses = sessions.length; + const totalMarked = attendances.length; + const totalPresent = attendances.filter((record) => record.status === 'PRESENT').length; + + return ok({ + attendanceRate: totalMarked > 0 ? Math.round((totalPresent / totalMarked) * 100) : 0, + totalPresent, + totalClasses, + recoveredSlots, + }); + } +} \ No newline at end of file diff --git a/apps/backend/src/modules/analytics/features/get-students-at-risk/route.ts b/apps/backend/src/modules/analytics/features/get-students-at-risk/route.ts new file mode 100644 index 0000000..bcec58c --- /dev/null +++ b/apps/backend/src/modules/analytics/features/get-students-at-risk/route.ts @@ -0,0 +1,20 @@ +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { GetStudentsAtRisk } from './use-case'; + +const route = new Hono(); + +route.get('/:groupId/students-at-risk', async (c) => { + const user = c.get('user'); + if (!user) { + return problemJson(c, unauthorizedProblem(c.req.path)); + } + + const groupId = c.req.param('groupId'); + const useCase = new GetStudentsAtRisk(); + const result = await useCase.execute(groupId, user.id); + + return resultJson(c, result); +}); + +export default route; \ No newline at end of file diff --git a/apps/backend/src/modules/analytics/features/get-students-at-risk/use-case.ts b/apps/backend/src/modules/analytics/features/get-students-at-risk/use-case.ts new file mode 100644 index 0000000..29edc96 --- /dev/null +++ b/apps/backend/src/modules/analytics/features/get-students-at-risk/use-case.ts @@ -0,0 +1,122 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { + AttendanceStatus, + ProblemDetails, + Result, + StudentAtRisk, + StudentsAtRisk, +} from '@gruperly/shared'; +import { ok } from '@gruperly/shared'; +import prisma from '@/lib/prisma'; +import { type AnalyticsAccessDb, findGroupForUser } from '../../lib/access'; +import { + classifyRisk, + lastAttendedAt, + monthlyAttendanceRate, + trailingAbsentStreak, +} from '../../lib/risk'; +import { ANALYTICS_WINDOW_MS } from '../get-overview/use-case'; + +type GetStudentsAtRiskDeps = { + db?: AnalyticsAccessDb & Pick; + now?: Date; +}; + +type AttendanceStreamRow = { + attendeeId: string; + status: AttendanceStatus; + classSession: { startsAt: Date }; +}; + +export class GetStudentsAtRisk { + constructor(private readonly deps: GetStudentsAtRiskDeps = {}) {} + + async execute( + groupId: string, + userId: string, + ): Promise> { + const db = this.deps.db ?? prisma; + const now = this.deps.now ?? new Date(); + const since = new Date(now.getTime() - ANALYTICS_WINDOW_MS); + + const access = await findGroupForUser(db, groupId, userId); + if (!access.ok) { + return access; + } + + const [windowSessions, attendees, attendances] = await Promise.all([ + db.classSession.findMany({ + where: { groupId, startsAt: { gte: since } }, + select: { id: true }, + }), + db.attendee.findMany({ + where: { groupId, status: 'ACTIVE' }, + select: { id: true, fullName: true, phone: true }, + }), + db.attendance.findMany({ + where: { attendee: { groupId } }, + select: { + attendeeId: true, + status: true, + classSession: { select: { startsAt: true } }, + }, + orderBy: { classSession: { startsAt: 'desc' } }, + }), + ]); + + const totalWindowSessions = windowSessions.length; + const streamByAttendee = groupAttendanceByAttendee(attendances); + + const atRisk: StudentAtRisk[] = []; + for (const attendee of attendees) { + const stream = (streamByAttendee.get(attendee.id) ?? []).map((row) => ({ + status: row.status, + occurredAt: row.classSession.startsAt, + })); + const consecutiveAbsences = trailingAbsentStreak(stream); + const attendedAt = lastAttendedAt(stream); + const monthlyRate = monthlyAttendanceRate( + stream.filter((entry) => entry.occurredAt.getTime() >= since.getTime()), + totalWindowSessions, + ); + const riskLevel = classifyRisk(consecutiveAbsences, monthlyRate); + if (!riskLevel) { + continue; + } + atRisk.push({ + attendeeId: attendee.id, + fullName: attendee.fullName, + phone: attendee.phone, + riskLevel, + consecutiveAbsences, + lastAttendedAt: attendedAt ? attendedAt.toISOString() : null, + monthlyAttendanceRate: monthlyRate, + }); + } + + atRisk.sort((a, b) => { + if (a.riskLevel !== b.riskLevel) { + return a.riskLevel === 'HIGH' ? -1 : 1; + } + if (a.consecutiveAbsences !== b.consecutiveAbsences) { + return b.consecutiveAbsences - a.consecutiveAbsences; + } + return a.monthlyAttendanceRate - b.monthlyAttendanceRate; + }); + + return ok({ + groupName: access.value.name, + data: atRisk, + }); + } +} + +function groupAttendanceByAttendee(rows: AttendanceStreamRow[]): Map { + const byAttendee = new Map(); + for (const row of rows) { + const list = byAttendee.get(row.attendeeId) ?? []; + list.push(row); + byAttendee.set(row.attendeeId, list); + } + return byAttendee; +} \ No newline at end of file diff --git a/apps/backend/src/modules/analytics/features/update-attendee-status/route.ts b/apps/backend/src/modules/analytics/features/update-attendee-status/route.ts new file mode 100644 index 0000000..d46c4b8 --- /dev/null +++ b/apps/backend/src/modules/analytics/features/update-attendee-status/route.ts @@ -0,0 +1,24 @@ +import type { UpdateStudentStatus } from '@gruperly/shared'; +import { UpdateStudentStatusSchema } from '@gruperly/shared'; +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { validate } from '@/http/validate'; +import { UpdateAttendeeStatus } from './use-case'; + +const route = new Hono(); + +route.post('/:studentId/status', validate.json(UpdateStudentStatusSchema), async (c) => { + const user = c.get('user'); + if (!user) { + return problemJson(c, unauthorizedProblem(c.req.path)); + } + + const studentId = c.req.param('studentId'); + const payload = c.req.valid('json') as UpdateStudentStatus; + const useCase = new UpdateAttendeeStatus(); + const result = await useCase.execute(studentId, user.id, payload); + + return resultJson(c, result); +}); + +export default route; \ No newline at end of file diff --git a/apps/backend/src/modules/analytics/features/update-attendee-status/use-case.ts b/apps/backend/src/modules/analytics/features/update-attendee-status/use-case.ts new file mode 100644 index 0000000..30cc3c7 --- /dev/null +++ b/apps/backend/src/modules/analytics/features/update-attendee-status/use-case.ts @@ -0,0 +1,53 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { + ProblemDetails, + Result, + UpdateStudentStatus, + UpdateStudentStatusResult, +} from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { noGroupAccessProblem, notFoundResourceProblem } from '@/http/problem-builders'; +import prisma from '@/lib/prisma'; + +type UpdateAttendeeStatusDeps = { + db?: Pick; +}; + +export class UpdateAttendeeStatus { + constructor(private readonly deps: UpdateAttendeeStatusDeps = {}) {} + + async execute( + studentId: string, + userId: string, + payload: UpdateStudentStatus, + ): Promise> { + const db = this.deps.db ?? prisma; + + const attendee = await db.attendee.findUnique({ + where: { id: studentId }, + include: { group: { include: { members: { where: { userId } } } } }, + }); + + if (!attendee) { + return err(notFoundResourceProblem('Attendee', studentId)); + } + + const isOwner = attendee.group.createdById === userId; + const isMember = attendee.group.members.length > 0; + if (!isOwner && !isMember) { + return err(noGroupAccessProblem()); + } + + if (attendee.status === payload.status) { + return ok({ attendeeId: studentId, status: payload.status }); + } + + const updated = await db.attendee.update({ + where: { id: studentId }, + data: { status: payload.status }, + select: { id: true, status: true }, + }); + + return ok({ attendeeId: updated.id, status: updated.status }); + } +} \ No newline at end of file diff --git a/apps/backend/src/modules/analytics/index.ts b/apps/backend/src/modules/analytics/index.ts new file mode 100644 index 0000000..75c5441 --- /dev/null +++ b/apps/backend/src/modules/analytics/index.ts @@ -0,0 +1,2 @@ +export { default as studentStatusRoutes } from './features/update-attendee-status/route'; +export { default as analyticsRoutes } from './routes'; \ No newline at end of file diff --git a/apps/backend/src/modules/analytics/lib/access.ts b/apps/backend/src/modules/analytics/lib/access.ts new file mode 100644 index 0000000..48c03bf --- /dev/null +++ b/apps/backend/src/modules/analytics/lib/access.ts @@ -0,0 +1,37 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { ProblemDetails, Result } from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { noGroupAccessProblem, notFoundResourceProblem } from '@/http/problem-builders'; + +export type AnalyticsAccessDb = Pick; + +type GroupWithAccess = { + id: string; + name: string; + createdById: string; + members: { userId: string }[]; +}; + +// Verifica que el usuario sea owner o miembro del grupo. Devuelve el grupo si tiene acceso. +export async function findGroupForUser( + db: AnalyticsAccessDb, + groupId: string, + userId: string, +): Promise> { + const group = await db.group.findUnique({ + where: { id: groupId }, + include: { members: { where: { userId } } }, + }); + + if (!group) { + return err(notFoundResourceProblem('Group', groupId)); + } + + const isOwner = group.createdById === userId; + const isMember = group.members.length > 0; + if (!isOwner && !isMember) { + return err(noGroupAccessProblem()); + } + + return ok(group); +} \ No newline at end of file diff --git a/apps/backend/src/modules/analytics/lib/risk.ts b/apps/backend/src/modules/analytics/lib/risk.ts new file mode 100644 index 0000000..dc1a2af --- /dev/null +++ b/apps/backend/src/modules/analytics/lib/risk.ts @@ -0,0 +1,56 @@ +export type AttendanceStreamEntry = { + status: 'PRESENT' | 'ABSENT' | 'EXCUSED'; + occurredAt: Date; +}; + +export type RiskLevel = 'HIGH' | 'MEDIUM'; + +// Cuenta las ausencias consecutivas sin justificar desde la clase más reciente. +// Recibe la lista ordenada de más reciente a más antigua; PRESENT y EXCUSED rompen la cadena. +export function trailingAbsentStreak(entries: AttendanceStreamEntry[]): number { + let streak = 0; + for (const entry of entries) { + if (entry.status !== 'ABSENT') { + break; + } + streak += 1; + } + return streak; +} + +// Fecha de la última clase a la que el alumno asistió (PRESENT), o null. +export function lastAttendedAt(entries: AttendanceStreamEntry[]): Date | null { + for (const entry of entries) { + if (entry.status === 'PRESENT') { + return entry.occurredAt; + } + } + return null; +} + +// Porcentaje de asistencia sobre el total de sesiones del período. +// Las sesiones sin registrar cuentan como no asistidas. +export function monthlyAttendanceRate( + entries: AttendanceStreamEntry[], + totalSessions: number, +): number { + if (totalSessions <= 0) { + return 0; + } + const present = entries.filter((entry) => entry.status === 'PRESENT').length; + return Math.round((present / totalSessions) * 100); +} + +// HIGH >= 3 ausencias consecutivas; MEDIUM == 2 consecutivas o asistencia mensual < 50%. +export function classifyRisk( + consecutiveAbsences: number, + monthlyRate: number, +): RiskLevel | null { + if (consecutiveAbsences >= 3) { + return 'HIGH'; + } + if (consecutiveAbsences === 2 || monthlyRate < 50) { + return 'MEDIUM'; + } + return null; +} \ No newline at end of file diff --git a/apps/backend/src/modules/analytics/routes.ts b/apps/backend/src/modules/analytics/routes.ts new file mode 100644 index 0000000..7054589 --- /dev/null +++ b/apps/backend/src/modules/analytics/routes.ts @@ -0,0 +1,12 @@ +import { Hono } from 'hono'; +import getAttendeeHistoryRoute from './features/get-attendee-history/route'; +import getOverviewRoute from './features/get-overview/route'; +import getStudentsAtRiskRoute from './features/get-students-at-risk/route'; + +const routes = new Hono(); + +routes.route('/', getOverviewRoute); +routes.route('/', getStudentsAtRiskRoute); +routes.route('/', getAttendeeHistoryRoute); + +export default routes; \ No newline at end of file diff --git a/apps/backend/src/modules/attendees/features/create/use-case.ts b/apps/backend/src/modules/attendees/features/create/use-case.ts index da27a42..cf8a656 100644 --- a/apps/backend/src/modules/attendees/features/create/use-case.ts +++ b/apps/backend/src/modules/attendees/features/create/use-case.ts @@ -70,7 +70,9 @@ export class CreateAttendeeUseCase { const fullName = `${payload.firstName.trim()} ${payload.lastName.trim()}`.trim(); if (group.capacity !== null) { - const currentCount = await db.attendee.count({ where: { groupId } }); + const currentCount = await db.attendee.count({ + where: { groupId, status: 'ACTIVE' }, + }); if (currentCount >= group.capacity) { if (isOwner && !options.allowOverflow) { diff --git a/apps/backend/src/modules/attendees/lib/helpers.ts b/apps/backend/src/modules/attendees/lib/helpers.ts index c7220b0..61c8c95 100644 --- a/apps/backend/src/modules/attendees/lib/helpers.ts +++ b/apps/backend/src/modules/attendees/lib/helpers.ts @@ -9,6 +9,7 @@ export type AttendeeRecord = { guardianName: string | null; guardianPhone: string | null; notes: string | null; + notifyToken?: string | null; createdAt: Date; updatedAt: Date; }; @@ -23,6 +24,7 @@ export function toAttendeeDto(record: AttendeeRecord): AttendeeDto { guardianName: record.guardianName, guardianPhone: record.guardianPhone, notes: record.notes, + notifyToken: record.notifyToken ?? null, createdAt: record.createdAt.toISOString(), updatedAt: record.updatedAt.toISOString(), }; diff --git a/apps/backend/src/modules/classes/features/mark-attendance/route.ts b/apps/backend/src/modules/classes/features/mark-attendance/route.ts new file mode 100644 index 0000000..b7ad569 --- /dev/null +++ b/apps/backend/src/modules/classes/features/mark-attendance/route.ts @@ -0,0 +1,24 @@ +import type { MarkAttendance } from '@gruperly/shared'; +import { MarkAttendanceSchema } from '@gruperly/shared'; +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { validate } from '@/http/validate'; +import { MarkSessionAttendance } from './use-case'; + +const route = new Hono(); + +route.post('/:sessionId/attendance', validate.json(MarkAttendanceSchema), async (c) => { + const user = c.get('user'); + if (!user) { + return problemJson(c, unauthorizedProblem(c.req.path)); + } + + const sessionId = c.req.param('sessionId'); + const payload = c.req.valid('json') as MarkAttendance; + const useCase = new MarkSessionAttendance(); + const result = await useCase.execute(sessionId, payload, user.id); + + return resultJson(c, result); +}); + +export default route; diff --git a/apps/backend/src/modules/classes/features/mark-attendance/use-case.ts b/apps/backend/src/modules/classes/features/mark-attendance/use-case.ts new file mode 100644 index 0000000..713a5ba --- /dev/null +++ b/apps/backend/src/modules/classes/features/mark-attendance/use-case.ts @@ -0,0 +1,105 @@ +import { AttendanceStatus } from '@generated/prisma/client'; +import type { + MarkAttendance, + MarkAttendanceResult, + ProblemDetails, + Result, +} from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { validationProblem } from '@/http/problem-builders'; +import prisma, { UnitOfWork } from '@/lib/prisma'; +import { type ClassesDb, ensureSessionAccess, sessionNotFound } from '../../lib'; + +type MarkSessionAttendanceDeps = { + db?: Pick; + unitOfWork?: UnitOfWork; +}; + +export class MarkSessionAttendance { + constructor(private readonly deps: MarkSessionAttendanceDeps = {}) {} + + async execute( + sessionId: string, + payload: MarkAttendance, + userId: string, + ): Promise> { + const db = this.deps.db ?? prisma; + const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma); + + if (payload.classSessionId !== sessionId) { + return err( + validationProblem({ + detail: 'El identificador de la clase no coincide con la ruta.', + }), + ); + } + + const session = await db.classSession.findUnique({ + where: { id: sessionId }, + include: { + group: { include: { members: { where: { userId } } } }, + }, + }); + if (!session) { + return err(sessionNotFound(sessionId)); + } + + const access = ensureSessionAccess(session, userId); + if (!access.ok) { + return access; + } + + const uniqueRecords = [ + ...new Map(payload.records.map((record) => [record.attendeeId, record])).values(), + ]; + + const attendees = await db.attendee.findMany({ + where: { + groupId: session.groupId, + id: { in: uniqueRecords.map((record) => record.attendeeId) }, + }, + select: { id: true }, + }); + const attendeeIds = new Set(attendees.map((attendee) => attendee.id)); + const invalidRecord = uniqueRecords.find((record) => !attendeeIds.has(record.attendeeId)); + if (invalidRecord) { + return err( + validationProblem({ + detail: 'Uno o más alumnos no pertenecen al grupo de esta clase.', + errors: { attendeeId: [invalidRecord.attendeeId] }, + }), + ); + } + + const markedAt = new Date(); + return unitOfWork.executeResult(async (tx) => { + for (const record of uniqueRecords) { + await tx.attendance.upsert({ + where: { + attendeeId_classSessionId: { + attendeeId: record.attendeeId, + classSessionId: sessionId, + }, + }, + create: { + attendeeId: record.attendeeId, + classSessionId: sessionId, + status: + record.status === 'PRESENT' + ? AttendanceStatus.PRESENT + : AttendanceStatus.ABSENT, + markedAt, + }, + update: { + status: + record.status === 'PRESENT' + ? AttendanceStatus.PRESENT + : AttendanceStatus.ABSENT, + markedAt, + }, + }); + } + return ok({ classSessionId: sessionId, marked: uniqueRecords.length }); + }); + } +} diff --git a/apps/backend/src/modules/classes/features/notify-absence/route.ts b/apps/backend/src/modules/classes/features/notify-absence/route.ts new file mode 100644 index 0000000..1304c06 --- /dev/null +++ b/apps/backend/src/modules/classes/features/notify-absence/route.ts @@ -0,0 +1,24 @@ +import type { NotifyAbsence } from '@gruperly/shared'; +import { NotifyAbsenceSchema } from '@gruperly/shared'; +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { validate } from '@/http/validate'; +import { NotifySessionAbsence } from './use-case'; + +const route = new Hono(); + +route.post('/:sessionId/notify-absence', validate.json(NotifyAbsenceSchema), async (c) => { + const user = c.get('user'); + if (!user) { + return problemJson(c, unauthorizedProblem(c.req.path)); + } + + const sessionId = c.req.param('sessionId'); + const payload = c.req.valid('json') as NotifyAbsence; + const useCase = new NotifySessionAbsence(); + const result = await useCase.execute(sessionId, payload, user.id); + + return resultJson(c, result); +}); + +export default route; diff --git a/apps/backend/src/modules/classes/features/notify-absence/use-case.ts b/apps/backend/src/modules/classes/features/notify-absence/use-case.ts new file mode 100644 index 0000000..6e7835c --- /dev/null +++ b/apps/backend/src/modules/classes/features/notify-absence/use-case.ts @@ -0,0 +1,71 @@ +import type { + NotifyAbsence, + NotifyAbsenceResult, + ProblemDetails, + Result, +} from '@gruperly/shared'; +import { err } from '@gruperly/shared'; +import { validationProblem } from '@/http/problem-builders'; +import prisma, { UnitOfWork } from '@/lib/prisma'; +import { + absenceReleaseHours, + type ClassesDb, + ensureSessionAccess, + registerAbsence, + sessionNotFound, +} from '../../lib'; + +type NotifySessionAbsenceDeps = { + db?: Pick; + unitOfWork?: UnitOfWork; + now?: Date; + releaseHours?: number; +}; + +export class NotifySessionAbsence { + constructor(private readonly deps: NotifySessionAbsenceDeps = {}) {} + + async execute( + sessionId: string, + payload: NotifyAbsence, + userId: string, + ): Promise> { + const db = this.deps.db ?? prisma; + const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma); + const now = this.deps.now ?? new Date(); + const releaseHours = this.deps.releaseHours ?? absenceReleaseHours(); + + if (payload.classSessionId !== sessionId) { + return err( + validationProblem({ + detail: 'El identificador de la clase no coincide con la ruta.', + }), + ); + } + + const session = await db.classSession.findUnique({ + where: { id: sessionId }, + include: { + group: { include: { members: { where: { userId } } } }, + }, + }); + if (!session) { + return err(sessionNotFound(sessionId)); + } + + const access = ensureSessionAccess(session, userId); + if (!access.ok) { + return access; + } + + return registerAbsence( + { db, unitOfWork }, + { + attendeeId: payload.attendeeId, + classSessionId: sessionId, + now, + releaseHours, + }, + ); + } +} diff --git a/apps/backend/src/modules/classes/features/public-details/route.ts b/apps/backend/src/modules/classes/features/public-details/route.ts new file mode 100644 index 0000000..4f62e3c --- /dev/null +++ b/apps/backend/src/modules/classes/features/public-details/route.ts @@ -0,0 +1,19 @@ +import type { AbsenceQuery } from '@gruperly/shared'; +import { AbsenceQuerySchema } from '@gruperly/shared'; +import { Hono } from 'hono'; +import { resultJson } from '@/http/problem-details'; +import { validate } from '@/http/validate'; +import { GetAbsenceDetails } from './use-case'; + +const route = new Hono(); + +// Ruta pública (whitelistada en session-auth): el alumno entra con su token personal. +route.get('/absence', validate.query(AbsenceQuerySchema), async (c) => { + const query = c.req.valid('query') as AbsenceQuery; + const useCase = new GetAbsenceDetails(); + const result = await useCase.execute(query); + + return resultJson(c, result); +}); + +export default route; diff --git a/apps/backend/src/modules/classes/features/public-details/use-case.ts b/apps/backend/src/modules/classes/features/public-details/use-case.ts new file mode 100644 index 0000000..db40339 --- /dev/null +++ b/apps/backend/src/modules/classes/features/public-details/use-case.ts @@ -0,0 +1,93 @@ +import type { AbsenceDetails, AbsenceQuery, ProblemDetails, Result } from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { notFoundResourceProblem } from '@/http/problem-builders'; +import prisma from '@/lib/prisma'; +import { DEFAULT_TIME_ZONE } from '@/modules/home/lib/scheduler'; +import { + buildTodayCandidates, + type ClassesDb, + ensureTodaySessions, +} from '../../lib'; + +type GetAbsenceDetailsDeps = { + db?: Pick< + ClassesDb, + 'attendee' | 'group' | 'classSession' | 'attendance' | 'slotRelease' + >; + now?: Date; + timeZone?: string; +}; + +export class GetAbsenceDetails { + constructor(private readonly deps: GetAbsenceDetailsDeps = {}) {} + + async execute( + query: AbsenceQuery, + ): Promise> { + const db = this.deps.db ?? prisma; + const now = this.deps.now ?? new Date(); + const timeZone = this.deps.timeZone ?? DEFAULT_TIME_ZONE; + + const attendee = await db.attendee.findUnique({ + where: { notifyToken: query.token }, + include: { + group: { select: { id: true, name: true, days: true, time: true } }, + }, + }); + if (!attendee) { + return err(notFoundResourceProblem('Attendee', 'notify token')); + } + + const candidates = buildTodayCandidates( + [{ id: attendee.group.id, days: attendee.group.days, time: attendee.group.time }], + now, + timeZone, + ); + if (candidates.length === 0) { + return ok({ + attendeeId: attendee.id, + fullName: attendee.fullName, + groupName: attendee.group.name, + sessions: [], + }); + } + + const sessionIds = await ensureTodaySessions(db, candidates); + const [sessions, attendances, releases] = await Promise.all([ + db.classSession.findMany({ + where: { id: { in: sessionIds } }, + orderBy: { startsAt: 'asc' }, + }), + db.attendance.findMany({ + where: { classSessionId: { in: sessionIds }, attendeeId: attendee.id }, + select: { classSessionId: true, status: true }, + }), + db.slotRelease.findMany({ + where: { classSessionId: { in: sessionIds }, attendeeId: attendee.id }, + select: { classSessionId: true }, + }), + ]); + + const attendanceBySession = new Map( + attendances.map((attendance) => [attendance.classSessionId, attendance.status]), + ); + const releasedSessionIds = new Set(releases.map((release) => release.classSessionId)); + + return ok({ + attendeeId: attendee.id, + fullName: attendee.fullName, + groupName: attendee.group.name, + sessions: sessions.map((session) => { + const attendanceStatus = attendanceBySession.get(session.id) ?? null; + return { + sessionId: session.id, + groupName: attendee.group.name, + startsAt: session.startsAt.toISOString(), + notified: + attendanceStatus === 'EXCUSED' || releasedSessionIds.has(session.id), + attendanceStatus, + }; + }), + }); + } +} diff --git a/apps/backend/src/modules/classes/features/public-notify/route.ts b/apps/backend/src/modules/classes/features/public-notify/route.ts new file mode 100644 index 0000000..a44c2e2 --- /dev/null +++ b/apps/backend/src/modules/classes/features/public-notify/route.ts @@ -0,0 +1,19 @@ +import type { PublicNotifyAbsence } from '@gruperly/shared'; +import { PublicNotifyAbsenceSchema } from '@gruperly/shared'; +import { Hono } from 'hono'; +import { resultJson } from '@/http/problem-details'; +import { validate } from '@/http/validate'; +import { PublicNotifyAbsenceUseCase } from './use-case'; + +const route = new Hono(); + +// Ruta pública (whitelistada en session-auth): el alumno avisa su ausencia con token. +route.post('/notify-absence', validate.json(PublicNotifyAbsenceSchema), async (c) => { + const payload = c.req.valid('json') as PublicNotifyAbsence; + const useCase = new PublicNotifyAbsenceUseCase(); + const result = await useCase.execute(payload); + + return resultJson(c, result); +}); + +export default route; diff --git a/apps/backend/src/modules/classes/features/public-notify/use-case.ts b/apps/backend/src/modules/classes/features/public-notify/use-case.ts new file mode 100644 index 0000000..24be0d3 --- /dev/null +++ b/apps/backend/src/modules/classes/features/public-notify/use-case.ts @@ -0,0 +1,48 @@ +import type { + NotifyAbsenceResult, + ProblemDetails, + PublicNotifyAbsence, + Result, +} from '@gruperly/shared'; +import { err } from '@gruperly/shared'; +import { notFoundResourceProblem } from '@/http/problem-builders'; +import prisma, { UnitOfWork } from '@/lib/prisma'; +import { absenceReleaseHours, type ClassesDb, registerAbsence } from '../../lib'; + +type PublicNotifyAbsenceDeps = { + db?: Pick; + unitOfWork?: UnitOfWork; + now?: Date; + releaseHours?: number; +}; + +export class PublicNotifyAbsenceUseCase { + constructor(private readonly deps: PublicNotifyAbsenceDeps = {}) {} + + async execute( + payload: PublicNotifyAbsence, + ): Promise> { + const db = this.deps.db ?? prisma; + const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma); + const now = this.deps.now ?? new Date(); + const releaseHours = this.deps.releaseHours ?? absenceReleaseHours(); + + const attendee = await db.attendee.findUnique({ + where: { notifyToken: payload.token }, + select: { id: true }, + }); + if (!attendee) { + return err(notFoundResourceProblem('Attendee', 'notify token')); + } + + return registerAbsence( + { db, unitOfWork }, + { + attendeeId: attendee.id, + classSessionId: payload.classSessionId, + now, + releaseHours, + }, + ); + } +} diff --git a/apps/backend/src/modules/classes/features/session-students/route.ts b/apps/backend/src/modules/classes/features/session-students/route.ts new file mode 100644 index 0000000..7cd4f4e --- /dev/null +++ b/apps/backend/src/modules/classes/features/session-students/route.ts @@ -0,0 +1,24 @@ +import type { TodayClassesQuery } from '@gruperly/shared'; +import { TodayClassesQuerySchema } from '@gruperly/shared'; +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { validate } from '@/http/validate'; +import { GetSessionStudents } from './use-case'; + +const route = new Hono(); + +route.get('/:sessionId/students', validate.query(TodayClassesQuerySchema), async (c) => { + const user = c.get('user'); + if (!user) { + return problemJson(c, unauthorizedProblem(c.req.path)); + } + + const sessionId = c.req.param('sessionId'); + const query = c.req.valid('query') as TodayClassesQuery; + const useCase = new GetSessionStudents(); + const result = await useCase.execute(sessionId, user.id, query); + + return resultJson(c, result); +}); + +export default route; diff --git a/apps/backend/src/modules/classes/features/session-students/use-case.ts b/apps/backend/src/modules/classes/features/session-students/use-case.ts new file mode 100644 index 0000000..e7c30a1 --- /dev/null +++ b/apps/backend/src/modules/classes/features/session-students/use-case.ts @@ -0,0 +1,112 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { + ProblemDetails, + Result, + SessionStudents, + TodayClassesQuery, +} from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import prisma from '@/lib/prisma'; +import { DEFAULT_TIME_ZONE, startOfDayInTimeZone } from '@/modules/home/lib/scheduler'; +import { + type ClassesDb, + ensureSessionAccess, + resolvePaymentStatus, + sessionNotFound, +} from '../../lib'; + +type GetSessionStudentsDeps = { + db?: Pick< + ClassesDb, + 'classSession' | 'attendee' | 'payment' | 'attendance' | 'slotRelease' + > & + Pick; + now?: Date; + timeZone?: string; +}; + +export class GetSessionStudents { + constructor(private readonly deps: GetSessionStudentsDeps = {}) {} + + async execute( + sessionId: string, + userId: string, + query: TodayClassesQuery = {}, + ): Promise> { + const db = this.deps.db ?? prisma; + const now = this.deps.now ?? new Date(); + const timeZone = this.deps.timeZone ?? query.timeZone ?? DEFAULT_TIME_ZONE; + + const session = await db.classSession.findUnique({ + where: { id: sessionId }, + include: { + group: { + include: { members: { where: { userId } } }, + }, + }, + }); + + if (!session) { + return err(sessionNotFound(sessionId)); + } + + const access = ensureSessionAccess(session, userId); + if (!access.ok) { + return access; + } + + const startOfToday = startOfDayInTimeZone(now, timeZone); + + const [attendees, payments, attendances, releases] = await Promise.all([ + db.attendee.findMany({ + where: { groupId: session.groupId }, + orderBy: { fullName: 'asc' }, + }), + db.payment.findMany({ + where: { groupId: session.groupId }, + select: { attendeeId: true, status: true, dueDate: true }, + }), + db.attendance.findMany({ + where: { classSessionId: sessionId }, + select: { attendeeId: true, status: true }, + }), + db.slotRelease.findMany({ + where: { classSessionId: sessionId }, + select: { attendeeId: true }, + }), + ]); + + const paymentsByAttendee = new Map(); + for (const payment of payments) { + const list = paymentsByAttendee.get(payment.attendeeId) ?? []; + list.push(payment); + paymentsByAttendee.set(payment.attendeeId, list); + } + + const attendanceByAttendee = new Map( + attendances.map((attendance) => [attendance.attendeeId, attendance.status]), + ); + const releasedAttendeeIds = new Set(releases.map((release) => release.attendeeId)); + + return ok({ + sessionId: session.id, + groupId: session.groupId, + groupName: session.group.name, + startsAt: session.startsAt.toISOString(), + students: attendees.map((attendee) => { + const attendanceStatus = attendanceByAttendee.get(attendee.id) ?? null; + return { + attendeeId: attendee.id, + fullName: attendee.fullName, + paymentStatus: resolvePaymentStatus( + paymentsByAttendee.get(attendee.id) ?? [], + startOfToday, + ), + attendanceStatus, + notifiedAbsence: + attendanceStatus === 'EXCUSED' || releasedAttendeeIds.has(attendee.id), + }; + }), + }); + } +} diff --git a/apps/backend/src/modules/classes/features/today/route.ts b/apps/backend/src/modules/classes/features/today/route.ts new file mode 100644 index 0000000..ab79dbf --- /dev/null +++ b/apps/backend/src/modules/classes/features/today/route.ts @@ -0,0 +1,23 @@ +import type { TodayClassesQuery } from '@gruperly/shared'; +import { TodayClassesQuerySchema } from '@gruperly/shared'; +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { validate } from '@/http/validate'; +import { GetTodayClasses } from './use-case'; + +const route = new Hono(); + +route.get('/today', validate.query(TodayClassesQuerySchema), async (c) => { + const user = c.get('user'); + if (!user) { + return problemJson(c, unauthorizedProblem(c.req.path)); + } + + const query = c.req.valid('query') as TodayClassesQuery; + const useCase = new GetTodayClasses(); + const result = await useCase.execute(user.id, query); + + return resultJson(c, result); +}); + +export default route; diff --git a/apps/backend/src/modules/classes/features/today/use-case.ts b/apps/backend/src/modules/classes/features/today/use-case.ts new file mode 100644 index 0000000..8a5bb0d --- /dev/null +++ b/apps/backend/src/modules/classes/features/today/use-case.ts @@ -0,0 +1,82 @@ +import type { ClassTodayList, ProblemDetails, Result, TodayClassesQuery } from '@gruperly/shared'; +import { ok } from '@gruperly/shared'; +import prisma from '@/lib/prisma'; +import { buildGroupWhereForUser } from '@/modules/groups/lib/helpers'; +import { DEFAULT_TIME_ZONE } from '@/modules/home/lib/scheduler'; +import { + buildTodayCandidates, + type ClassesDb, + ensureTodaySessions, + toClassToday, +} from '../../lib'; + +type GetTodayClassesDeps = { + db?: Pick; + now?: Date; + timeZone?: string; +}; + +export class GetTodayClasses { + constructor(private readonly deps: GetTodayClassesDeps = {}) {} + + async execute( + userId: string, + query: TodayClassesQuery = {}, + ): Promise> { + const db = this.deps.db ?? prisma; + const now = this.deps.now ?? new Date(); + const timeZone = this.deps.timeZone ?? query.timeZone ?? DEFAULT_TIME_ZONE; + + const groups = await db.group.findMany({ + where: buildGroupWhereForUser(userId), + select: { + id: true, + name: true, + days: true, + time: true, + capacity: true, + _count: { + select: { attendees: { where: { status: 'ACTIVE' } } }, + }, + }, + }); + + const candidates = buildTodayCandidates(groups, now, timeZone); + if (candidates.length === 0) { + return ok({ data: [] }); + } + + const sessionIds = await ensureTodaySessions(db, candidates); + + const [sessions, markedAttendances] = await Promise.all([ + db.classSession.findMany({ + where: { id: { in: sessionIds } }, + include: { + group: { select: { id: true, name: true, capacity: true } }, + }, + orderBy: { startsAt: 'asc' }, + }), + db.attendance.findMany({ + where: { + classSessionId: { in: sessionIds }, + status: { in: ['PRESENT', 'ABSENT'] }, + }, + select: { classSessionId: true }, + }), + ]); + + const markedSessionIds = new Set(markedAttendances.map((a) => a.classSessionId)); + const enrolledByGroup = new Map(groups.map((group) => [group.id, group._count.attendees])); + + return ok({ + data: sessions.map((session) => + toClassToday( + session, + session.group, + enrolledByGroup.get(session.groupId) ?? 0, + markedSessionIds.has(session.id), + ), + ), + }); + } +} diff --git a/apps/backend/src/modules/classes/index.ts b/apps/backend/src/modules/classes/index.ts new file mode 100644 index 0000000..02b8841 --- /dev/null +++ b/apps/backend/src/modules/classes/index.ts @@ -0,0 +1 @@ +export { default as classesRoutes } from './routes'; diff --git a/apps/backend/src/modules/classes/lib/helpers.ts b/apps/backend/src/modules/classes/lib/helpers.ts new file mode 100644 index 0000000..fcac3fc --- /dev/null +++ b/apps/backend/src/modules/classes/lib/helpers.ts @@ -0,0 +1,92 @@ +import type { PrismaClient } from '@generated/prisma/client'; +import type { + AttendeePaymentStatus, + ClassToday, + ProblemDetails, + Result, +} from '@gruperly/shared'; +import { err } from '@gruperly/shared'; +import { noGroupAccessProblem, notFoundResourceProblem } from '@/http/problem-builders'; + +export type ClassesDb = Pick< + PrismaClient, + 'group' | 'classSession' | 'attendee' | 'payment' | 'attendance' | 'slotRelease' +>; + +type PaymentLike = { + status: 'PENDING' | 'PAID' | 'OVERDUE' | 'CANCELLED'; + dueDate: Date; +}; + +// Estado de cobro calculado en tiempo real (sin columna denormalizada): +// PENDIENTE si hay un pago vencido (OVERDUE) o un PENDING cuyo vencimiento ya pasó. +export function resolvePaymentStatus( + payments: PaymentLike[], + startOfToday: Date, +): AttendeePaymentStatus { + const hasUnpaid = payments.some( + (payment) => + payment.status === 'OVERDUE' + || (payment.status === 'PENDING' && payment.dueDate.getTime() < startOfToday.getTime()), + ); + return hasUnpaid ? 'PENDING' : 'UP_TO_DATE'; +} + +export function absenceReleaseHours(): number { + const raw = process.env.ABSENCE_RELEASE_HOURS; + if (raw == null || raw.trim() === '') { + return 12; + } + const parsed = Number(raw); + return Number.isFinite(parsed) && parsed >= 0 ? parsed : 12; +} + +export type ClassSessionRecord = { + id: string; + groupId: string; + startsAt: Date; +}; + +type GroupWithAccess = { + createdById: string; + members: { userId: string }[]; +}; + +// Verifica que el usuario sea owner o miembro del grupo dueño de la sesión. +export function ensureSessionAccess( + session: ClassSessionRecord & { group: GroupWithAccess }, + userId: string, +): Result { + const isOwner = session.group.createdById === userId; + const isMember = session.group.members.length > 0; + if (!isOwner && !isMember) { + return err(noGroupAccessProblem()); + } + return { + ok: true, + value: { id: session.id, groupId: session.groupId, startsAt: session.startsAt }, + }; +} + +export function sessionNotFound(sessionId: string): ProblemDetails { + return notFoundResourceProblem('Class session', sessionId); +} + +export function toClassToday( + session: { id: string; startsAt: Date }, + group: { id: string; name: string; capacity: number | null }, + enrolledCount: number, + hasAttendance: boolean, +): ClassToday { + return { + sessionId: session.id, + groupId: group.id, + groupName: group.name, + startsAt: session.startsAt.toISOString(), + enrolledCount, + capacity: group.capacity, + availableSlots: + group.capacity == null ? null : Math.max(0, group.capacity - enrolledCount), + hasAttendance, + }; +} diff --git a/apps/backend/src/modules/classes/lib/index.ts b/apps/backend/src/modules/classes/lib/index.ts new file mode 100644 index 0000000..d1e2995 --- /dev/null +++ b/apps/backend/src/modules/classes/lib/index.ts @@ -0,0 +1,3 @@ +export * from './helpers'; +export * from './notify'; +export * from './sessions'; diff --git a/apps/backend/src/modules/classes/lib/notify.ts b/apps/backend/src/modules/classes/lib/notify.ts new file mode 100644 index 0000000..a456341 --- /dev/null +++ b/apps/backend/src/modules/classes/lib/notify.ts @@ -0,0 +1,91 @@ +import { AttendanceStatus } from '@generated/prisma/client'; +import type { NotifyAbsenceResult, ProblemDetails, Result } from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; +import { notFoundResourceProblem, validationProblem } from '@/http/problem-builders'; +import type { UnitOfWork } from '@/lib/prisma'; +import { type ClassesDb, sessionNotFound } from './helpers'; + +type RegisterAbsenceDeps = { + db: Pick; + unitOfWork: UnitOfWork; +}; + +type RegisterAbsenceInput = { + attendeeId: string; + classSessionId: string; + now: Date; + releaseHours: number; +}; + +// Núcleo compartido del aviso de ausencia (profesor autenticado y alumno con token): +// - Marca la asistencia como EXCUSED (upsert idempotente). +// - Si la anticipación alcanza `releaseHours`, crea/conserva un SlotRelease para liberar el cupo. +export async function registerAbsence( + deps: RegisterAbsenceDeps, + input: RegisterAbsenceInput, +): Promise> { + const { db, unitOfWork } = deps; + const { attendeeId, classSessionId, now, releaseHours } = input; + + const session = await db.classSession.findUnique({ where: { id: classSessionId } }); + if (!session) { + return err(sessionNotFound(classSessionId)); + } + + const attendee = await db.attendee.findUnique({ where: { id: attendeeId } }); + if (!attendee) { + return err(notFoundResourceProblem('Attendee', attendeeId)); + } + if (attendee.groupId !== session.groupId) { + return err( + validationProblem({ detail: 'El alumno no pertenece al grupo de esta clase.' }), + ); + } + + const anticipationMs = session.startsAt.getTime() - now.getTime(); + const slotReleased = anticipationMs >= releaseHours * 60 * 60 * 1000; + + return unitOfWork.executeResult(async (tx) => { + await tx.attendance.upsert({ + where: { + attendeeId_classSessionId: { + attendeeId, + classSessionId, + }, + }, + create: { + attendeeId, + classSessionId, + status: AttendanceStatus.EXCUSED, + markedAt: now, + }, + update: { + status: AttendanceStatus.EXCUSED, + markedAt: now, + }, + }); + + if (slotReleased) { + await tx.slotRelease.upsert({ + where: { + attendeeId_classSessionId: { + attendeeId, + classSessionId, + }, + }, + create: { + attendeeId, + classSessionId, + isClaimed: false, + }, + update: {}, + }); + } + + return ok({ + classSessionId, + notified: true, + slotReleased, + }); + }); +} diff --git a/apps/backend/src/modules/classes/lib/sessions.ts b/apps/backend/src/modules/classes/lib/sessions.ts new file mode 100644 index 0000000..6af8e49 --- /dev/null +++ b/apps/backend/src/modules/classes/lib/sessions.ts @@ -0,0 +1,64 @@ +import type { WeekDay } from '@gruperly/shared'; +import { todayOccurrence } from '@/modules/home/lib/scheduler'; +import type { ClassesDb } from './helpers'; + +export type TodaySessionCandidate = { + groupId: string; + startsAt: Date; +}; + +type ScheduledGroup = { + id: string; + days: WeekDay[] | null; + time: string | null; +}; + +// Calcula qué grupos tienen clase hoy (según days/time y la zona horaria del profesor). +export function buildTodayCandidates( + groups: ScheduledGroup[], + now: Date, + timeZone: string, +): TodaySessionCandidate[] { + const candidates: TodaySessionCandidate[] = []; + for (const group of groups) { + if (!group.days || group.days.length === 0 || !group.time) { + continue; + } + const startsAt = todayOccurrence({ + days: group.days, + time: group.time, + now, + timeZone, + }); + if (startsAt) { + candidates.push({ groupId: group.id, startsAt }); + } + } + return candidates; +} + +// Materializa (upsert idempotente) las ClassSession del día y devuelve sus ids. +export async function ensureTodaySessions( + db: Pick, + candidates: TodaySessionCandidate[], +): Promise { + const sessionIds: string[] = []; + for (const candidate of candidates) { + const session = await db.classSession.upsert({ + where: { + groupId_startsAt: { + groupId: candidate.groupId, + startsAt: candidate.startsAt, + }, + }, + create: { + groupId: candidate.groupId, + startsAt: candidate.startsAt, + }, + update: {}, + select: { id: true }, + }); + sessionIds.push(session.id); + } + return sessionIds; +} diff --git a/apps/backend/src/modules/classes/routes.ts b/apps/backend/src/modules/classes/routes.ts new file mode 100644 index 0000000..c19b606 --- /dev/null +++ b/apps/backend/src/modules/classes/routes.ts @@ -0,0 +1,18 @@ +import { Hono } from 'hono'; +import markAttendanceRoute from './features/mark-attendance/route'; +import notifyAbsenceRoute from './features/notify-absence/route'; +import publicDetailsRoute from './features/public-details/route'; +import publicNotifyRoute from './features/public-notify/route'; +import sessionStudentsRoute from './features/session-students/route'; +import todayRoute from './features/today/route'; + +const routes = new Hono(); + +routes.route('/', todayRoute); +routes.route('/', sessionStudentsRoute); +routes.route('/', markAttendanceRoute); +routes.route('/', notifyAbsenceRoute); +routes.route('/', publicDetailsRoute); +routes.route('/', publicNotifyRoute); + +export default routes; diff --git a/apps/backend/src/modules/group-waitlist/lib/promote.ts b/apps/backend/src/modules/group-waitlist/lib/promote.ts index ee5a158..8bd233d 100644 --- a/apps/backend/src/modules/group-waitlist/lib/promote.ts +++ b/apps/backend/src/modules/group-waitlist/lib/promote.ts @@ -29,7 +29,9 @@ export async function promoteWaitlistEntryRecord( entry: GroupWaitlistEntryRecord, ): Promise> { if (group.capacity !== null) { - const currentCount = await db.attendee.count({ where: { groupId: group.id } }); + const currentCount = await db.attendee.count({ + where: { groupId: group.id, status: 'ACTIVE' }, + }); if (currentCount >= group.capacity) { return err(capacityReachedProblem(group.capacity)); } diff --git a/apps/backend/src/modules/groups/routes.ts b/apps/backend/src/modules/groups/routes.ts index bfbc4d6..a490ac8 100644 --- a/apps/backend/src/modules/groups/routes.ts +++ b/apps/backend/src/modules/groups/routes.ts @@ -1,4 +1,5 @@ import { Hono } from 'hono'; +import analyticsRoutes from '../analytics/routes'; import addToGroupWaitlistRoute from '../attendees/features/add-to-waitlist/route'; import bulkCreateAttendeesRoute from '../attendees/features/bulk-create/route'; import createAttendeeRoute from '../attendees/features/create/route'; @@ -21,6 +22,7 @@ routes.route('/', bulkCreateAttendeesRoute); routes.route('/', getByIdRoute); routes.route('/', addToGroupWaitlistRoute); routes.route('/', groupWaitlistRoutes); +routes.route('/', analyticsRoutes); routes.route('/', removeAttendeeRoute); export default routes; \ No newline at end of file diff --git a/apps/backend/src/modules/home/lib/scheduler.ts b/apps/backend/src/modules/home/lib/scheduler.ts index b92aed7..a9f4fbf 100644 --- a/apps/backend/src/modules/home/lib/scheduler.ts +++ b/apps/backend/src/modules/home/lib/scheduler.ts @@ -22,7 +22,7 @@ export type NextClassOccurrence = { }; // Convierte un tiempo de "pared" (wall clock) expresado en `timeZone` al instante absoluto. -function zonedWallClockToUtc(wall: string, timeZone: string): Date { +export function zonedWallClockToUtc(wall: string, timeZone: string): Date { const match = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})$/.exec(wall); if (!match) { throw new Error(`Invalid wall clock: ${wall}`); @@ -64,7 +64,7 @@ function zonedWallClockToUtc(wall: string, timeZone: string): Date { return new Date(asUtc.getTime() + offsetMs); } -function wallDateInTimeZone(now: Date, timeZone: string): { year: number; month: number; day: number } { +export function wallDateInTimeZone(now: Date, timeZone: string): { year: number; month: number; day: number } { const wall = new Intl.DateTimeFormat('en-US', { timeZone, year: 'numeric', @@ -143,4 +143,46 @@ export function nextClassOccurrence(opt: { function pad(value: number): string { return String(value).padStart(2, '0'); +} + +// Instante absoluto de la clase de HOY (aunque la hora ya haya pasado), o null si el grupo +// no tiene clase programada para el día de `now` en `timeZone`. +export function todayOccurrence(opt: { + days: WeekDay[]; + time: string; + now: Date; + timeZone: string; +}): Date | null { + const { days, time, now, timeZone } = opt; + + if (days.length === 0 || !time) { + return null; + } + const [hour, minute] = time.split(':').map(Number); + if ( + Number.isNaN(hour) || + Number.isNaN(minute) || + hour < 0 || + hour > 23 || + minute < 0 || + minute > 59 + ) { + return null; + } + + const { year, month, day } = wallDateInTimeZone(now, timeZone); + const dow = new Date(Date.UTC(year, month - 1, day)).getUTCDay(); + const dayMatches = days.some((d) => WEEKDAY_TO_DOW[d] === dow); + if (!dayMatches) { + return null; + } + + const wall = `${year}-${pad(month)}-${pad(day)}T${pad(hour)}:${pad(minute)}`; + return zonedWallClockToUtc(wall, timeZone); +} + +// Primer instante del día de `now` en `timeZone` (medianoche local). +export function startOfDayInTimeZone(now: Date, timeZone: string): Date { + const { year, month, day } = wallDateInTimeZone(now, timeZone); + return zonedWallClockToUtc(`${year}-${pad(month)}-${pad(day)}T00:00`, timeZone); } \ No newline at end of file diff --git a/apps/backend/src/modules/invitations/features/join-via-invite/use-case.ts b/apps/backend/src/modules/invitations/features/join-via-invite/use-case.ts index 69a0497..f07fe86 100644 --- a/apps/backend/src/modules/invitations/features/join-via-invite/use-case.ts +++ b/apps/backend/src/modules/invitations/features/join-via-invite/use-case.ts @@ -55,7 +55,9 @@ export class JoinViaInvite { const fullName = `${payload.firstName.trim()} ${payload.lastName.trim()}`.trim(); if (group.capacity !== null) { - const currentCount = await db.attendee.count({ where: { groupId: group.id } }); + const currentCount = await db.attendee.count({ + where: { groupId: group.id, status: 'ACTIVE' }, + }); if (currentCount >= group.capacity) { const existingWaitlistEntry = await db.groupWaitlistEntry.findFirst({ diff --git a/apps/backend/test/analytics-risk.test.ts b/apps/backend/test/analytics-risk.test.ts new file mode 100644 index 0000000..fa46c92 --- /dev/null +++ b/apps/backend/test/analytics-risk.test.ts @@ -0,0 +1,79 @@ +import { describe, expect, it } from 'bun:test'; +import { + classifyRisk, + lastAttendedAt, + monthlyAttendanceRate, + trailingAbsentStreak, +} from '@/modules/analytics/lib/risk'; + +const day = 24 * 60 * 60 * 1000; +const at = (offsetDays: number) => new Date(Date.now() - offsetDays * day); + +function entry(status: 'PRESENT' | 'ABSENT' | 'EXCUSED', offsetDays: number) { + return { status, occurredAt: at(offsetDays) }; +} + +describe('trailingAbsentStreak', () => { + it('devuelve 0 sin registros', () => { + expect(trailingAbsentStreak([])).toBe(0); + }); + + it('cuenta ausencias consecutivas sin justificar desde la más reciente', () => { + expect(trailingAbsentStreak([entry('ABSENT', 0)])).toBe(1); + expect(trailingAbsentStreak([entry('ABSENT', 0), entry('ABSENT', 7), entry('ABSENT', 14)])).toBe(3); + }); + + it('rompe la cadena con PRESENT o EXCUSED', () => { + expect( + trailingAbsentStreak([entry('ABSENT', 0), entry('ABSENT', 7), entry('PRESENT', 14)]), + ).toBe(2); + expect(trailingAbsentStreak([entry('EXCUSED', 0), entry('ABSENT', 7)])).toBe(0); + expect(trailingAbsentStreak([entry('PRESENT', 0)])).toBe(0); + }); +}); + +describe('lastAttendedAt', () => { + it('devuelve la clase PRESENT más reciente', () => { + const result = lastAttendedAt([ + entry('PRESENT', 0), + entry('ABSENT', 7), + entry('ABSENT', 14), + ]); + expect(result).not.toBeNull(); + expect(result?.getTime()).toBe(at(0).getTime()); + }); + + it('devuelve null si nunca asistió', () => { + expect(lastAttendedAt([entry('ABSENT', 0), entry('EXCUSED', 7)])).toBeNull(); + expect(lastAttendedAt([])).toBeNull(); + }); +}); + +describe('monthlyAttendanceRate', () => { + it('razón de PRESENT sobre el total de sesiones', () => { + expect(monthlyAttendanceRate([entry('PRESENT', 0), entry('PRESENT', 7), entry('ABSENT', 14)], 5)).toBe(40); + }); + + it('devuelve 0 sin sesiones o sin presentes', () => { + expect(monthlyAttendanceRate([], 3)).toBe(0); + expect(monthlyAttendanceRate([entry('ABSENT', 0)], 3)).toBe(0); + }); +}); + +describe('classifyRisk', () => { + it('HIGH con 3 o más ausencias consecutivas', () => { + expect(classifyRisk(3, 80)).toBe('HIGH'); + expect(classifyRisk(5, 20)).toBe('HIGH'); + }); + + it('MEDIUM con 2 ausencias consecutivas o asistencia menor al 50%', () => { + expect(classifyRisk(2, 90)).toBe('MEDIUM'); + expect(classifyRisk(1, 40)).toBe('MEDIUM'); + expect(classifyRisk(2, 40)).toBe('MEDIUM'); + }); + + it('sin riesgo si no cumple ningún umbral', () => { + expect(classifyRisk(1, 60)).toBeNull(); + expect(classifyRisk(0, 60)).toBeNull(); + }); +}); \ No newline at end of file diff --git a/apps/backend/test/analytics.test.ts b/apps/backend/test/analytics.test.ts new file mode 100644 index 0000000..a18c404 --- /dev/null +++ b/apps/backend/test/analytics.test.ts @@ -0,0 +1,325 @@ +import { beforeEach, describe, expect, it, mock, vi } from 'bun:test'; +import { Hono } from 'hono'; + +const db = { + group: { + findUnique: mock(), + }, + classSession: { + findMany: mock(), + }, + attendee: { + findMany: mock(), + findFirst: mock(), + findUnique: mock(), + update: mock(), + }, + attendance: { + findMany: mock(), + }, + slotRelease: { + count: mock(), + }, +}; + +mock.module('@/lib/prisma', () => ({ + default: db, + getPrismaClient: mock(), + UnitOfWork: class { + executeResult = mock(async (cb: (tx: unknown) => Promise) => cb(db)); + execute = mock(async (cb: (tx: unknown) => Promise) => cb(db)); + }, +})); + +import prisma from '@/lib/prisma'; +import { analyticsRoutes, studentStatusRoutes } from '@/modules/analytics'; + +const userId = 'user-1'; +const DAY_MS = 24 * 60 * 60 * 1000; +const now = Date.now(); +const at = (offsetDays: number) => new Date(now - offsetDays * DAY_MS).toISOString(); + +function makeApp(userValue: unknown) { + const app = new Hono(); + app.use('*', async (c, next) => { + c.set('user', userValue as never); + await next(); + }); + app.route('/groups', analyticsRoutes); + app.route('/students', studentStatusRoutes); + return app; +} + +function makeGroup(overrides: Record = {}) { + return { + id: 'group-1', + name: 'Funcional', + createdById: userId, + members: [], + ...overrides, + }; +} + +describe('analytics routes', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + describe('GET /groups/:groupId/analytics', () => { + it('calcula métricas de asistencia de los últimos 30 días', async () => { + prisma.group.findUnique.mockResolvedValue(makeGroup()); + prisma.classSession.findMany.mockResolvedValue([{ id: 's-1' }, { id: 's-2' }]); + prisma.attendance.findMany.mockResolvedValue([ + { status: 'PRESENT' }, + { status: 'PRESENT' }, + { status: 'ABSENT' }, + { status: 'EXCUSED' }, + ]); + prisma.slotRelease.count.mockResolvedValue(2); + + const res = await makeApp({ id: userId }).request('/groups/group-1/analytics'); + + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ + attendanceRate: 50, + totalPresent: 2, + totalClasses: 2, + recoveredSlots: 2, + }); + }); + + it('devuelve 0 en todas las métricas sin clases en el período', async () => { + prisma.group.findUnique.mockResolvedValue(makeGroup()); + prisma.classSession.findMany.mockResolvedValue([]); + prisma.attendance.findMany.mockResolvedValue([]); + prisma.slotRelease.count.mockResolvedValue(0); + + const res = await makeApp({ id: userId }).request('/groups/group-1/analytics'); + + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ + attendanceRate: 0, + totalPresent: 0, + totalClasses: 0, + recoveredSlots: 0, + }); + }); + + it('prohíbe el acceso a quien no es owner ni miembro', async () => { + prisma.group.findUnique.mockResolvedValue( + makeGroup({ createdById: 'someone-else' }), + ); + + const res = await makeApp({ id: userId }).request('/groups/group-1/analytics'); + + expect(res.status).toBe(403); + expect(await res.json()).toMatchObject({ code: 'group_access_denied' }); + }); + + it('devuelve 404 si el grupo no existe', async () => { + prisma.group.findUnique.mockResolvedValue(null); + + const res = await makeApp({ id: userId }).request('/groups/group-1/analytics'); + + expect(res.status).toBe(404); + expect(await res.json()).toMatchObject({ code: 'not_found' }); + }); + + it('rechaza requests sin sesión', async () => { + const res = await makeApp(null).request('/groups/group-1/analytics'); + + expect(res.status).toBe(401); + }); + }); + + describe('GET /groups/:groupId/students-at-risk', () => { + const sessions = [at(0), at(7), at(14), at(21)]; + + it('clasifica HIGH y MEDIUM según el historial de asistencia', async () => { + prisma.group.findUnique.mockResolvedValue(makeGroup()); + prisma.classSession.findMany.mockResolvedValue(sessions.map((startsAt) => ({ id: 's', startsAt }))); + prisma.attendee.findMany.mockResolvedValue([ + { id: 'a-1', fullName: 'Ana Pérez', phone: '+521111111111' }, + { id: 'a-2', fullName: 'Bruno Díaz', phone: null }, + ]); + prisma.attendance.findMany.mockResolvedValue([ + { attendeeId: 'a-1', status: 'ABSENT', classSession: { startsAt: new Date(at(0)) } }, + { attendeeId: 'a-1', status: 'ABSENT', classSession: { startsAt: new Date(at(7)) } }, + { attendeeId: 'a-1', status: 'ABSENT', classSession: { startsAt: new Date(at(14)) } }, + { attendeeId: 'a-1', status: 'PRESENT', classSession: { startsAt: new Date(at(21)) } }, + { attendeeId: 'a-2', status: 'ABSENT', classSession: { startsAt: new Date(at(0)) } }, + { attendeeId: 'a-2', status: 'ABSENT', classSession: { startsAt: new Date(at(7)) } }, + { attendeeId: 'a-2', status: 'PRESENT', classSession: { startsAt: new Date(at(14)) } }, + { attendeeId: 'a-2', status: 'PRESENT', classSession: { startsAt: new Date(at(21)) } }, + ]); + + const res = await makeApp({ id: userId }).request('/groups/group-1/students-at-risk'); + + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ + groupName: 'Funcional', + data: [ + { + attendeeId: 'a-1', + fullName: 'Ana Pérez', + phone: '+521111111111', + riskLevel: 'HIGH', + consecutiveAbsences: 3, + lastAttendedAt: at(21), + monthlyAttendanceRate: 25, + }, + { + attendeeId: 'a-2', + fullName: 'Bruno Díaz', + phone: null, + riskLevel: 'MEDIUM', + consecutiveAbsences: 2, + lastAttendedAt: at(14), + monthlyAttendanceRate: 50, + }, + ], + }); + }); + + it('devuelve lista vacía cuando nadie está en riesgo', async () => { + prisma.group.findUnique.mockResolvedValue(makeGroup()); + prisma.classSession.findMany.mockResolvedValue(sessions.map((startsAt) => ({ id: 's', startsAt }))); + prisma.attendee.findMany.mockResolvedValue([ + { id: 'a-1', fullName: 'Ana Pérez', phone: null }, + ]); + prisma.attendance.findMany.mockResolvedValue([ + { attendeeId: 'a-1', status: 'PRESENT', classSession: { startsAt: new Date(at(0)) } }, + { attendeeId: 'a-1', status: 'PRESENT', classSession: { startsAt: new Date(at(7)) } }, + ]); + + const res = await makeApp({ id: userId }).request('/groups/group-1/students-at-risk'); + + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ groupName: 'Funcional', data: [] }); + }); + }); + + describe('GET /groups/:groupId/attendees/:attendeeId/history', () => { + it('devuelve el historial de presentismo con su porcentaje', async () => { + prisma.group.findUnique.mockResolvedValue(makeGroup()); + prisma.attendee.findFirst.mockResolvedValue({ id: 'a-1', fullName: 'Ana Pérez' }); + prisma.classSession.findMany.mockResolvedValue([ + { id: 's-2', startsAt: new Date(at(7)) }, + { id: 's-1', startsAt: new Date(at(0)) }, + ]); + prisma.attendance.findMany.mockResolvedValue([ + { classSessionId: 's-1', status: 'PRESENT' }, + { classSessionId: 's-2', status: 'ABSENT' }, + ]); + + const res = await makeApp({ id: userId }).request( + '/groups/group-1/attendees/a-1/history', + ); + + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ + attendeeId: 'a-1', + fullName: 'Ana Pérez', + groupId: 'group-1', + groupName: 'Funcional', + attendanceRate: 50, + sessions: [ + { classSessionId: 's-1', startsAt: at(0), status: 'PRESENT' }, + { classSessionId: 's-2', startsAt: at(7), status: 'ABSENT' }, + ], + }); + }); + + it('devuelve 404 si el alumno 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/history', + ); + + expect(res.status).toBe(404); + expect(await res.json()).toMatchObject({ code: 'not_found' }); + }); + }); + + describe('POST /students/:studentId/status', () => { + function makeAttendee(status: string, overrides: Record = {}) { + return { + id: 'a-1', + status, + group: { createdById: userId, members: [] }, + ...overrides, + }; + } + + it('cambia el estado del alumno', async () => { + prisma.attendee.findUnique.mockResolvedValue(makeAttendee('ACTIVE')); + prisma.attendee.update.mockResolvedValue({ id: 'a-1', status: 'DROPPED' }); + + const res = await makeApp({ id: userId }).request('/students/a-1/status', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ status: 'DROPPED' }), + }); + + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ attendeeId: 'a-1', status: 'DROPPED' }); + expect(prisma.attendee.update).toHaveBeenCalledWith({ + where: { id: 'a-1' }, + data: { status: 'DROPPED' }, + select: { id: true, status: true }, + }); + }); + + it('es idempotente si el estado no cambia', async () => { + prisma.attendee.findUnique.mockResolvedValue(makeAttendee('PAUSED')); + + const res = await makeApp({ id: userId }).request('/students/a-1/status', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ status: 'PAUSED' }), + }); + + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ attendeeId: 'a-1', status: 'PAUSED' }); + expect(prisma.attendee.update).not.toHaveBeenCalled(); + }); + + it('prohíbe el acceso a quien no es owner ni miembro', async () => { + prisma.attendee.findUnique.mockResolvedValue( + makeAttendee('ACTIVE', { group: { createdById: 'someone-else', members: [] } }), + ); + + const res = await makeApp({ id: userId }).request('/students/a-1/status', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ status: 'PAUSED' }), + }); + + expect(res.status).toBe(403); + expect(await res.json()).toMatchObject({ code: 'group_access_denied' }); + }); + + it('rechaza estados fuera del contrato', async () => { + const res = await makeApp({ id: userId }).request('/students/a-1/status', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ status: 'HOLD' }), + }); + + expect(res.status).toBe(400); + expect(prisma.attendee.update).not.toHaveBeenCalled(); + }); + + it('rechaza requests sin sesión', async () => { + const res = await makeApp(null).request('/students/a-1/status', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ status: 'ACTIVE' }), + }); + + expect(res.status).toBe(401); + }); + }); +}); \ No newline at end of file diff --git a/apps/backend/test/attendees.test.ts b/apps/backend/test/attendees.test.ts index 60e49d8..ca49895 100644 --- a/apps/backend/test/attendees.test.ts +++ b/apps/backend/test/attendees.test.ts @@ -27,6 +27,7 @@ const attendee = { guardianName: 'Luis Pérez', guardianPhone: null, notes: null, + notifyToken: null, createdAt: new Date('2026-08-01T10:00:00.000Z'), updatedAt: new Date('2026-08-01T10:00:00.000Z'), }; diff --git a/apps/backend/test/classes.test.ts b/apps/backend/test/classes.test.ts new file mode 100644 index 0000000..1856a9b --- /dev/null +++ b/apps/backend/test/classes.test.ts @@ -0,0 +1,507 @@ +import { beforeEach, describe, expect, it, mock, vi } from 'bun:test'; +import { Hono } from 'hono'; + +const db = { + group: { + findMany: mock(), + }, + classSession: { + upsert: mock(), + findMany: mock(), + findUnique: mock(), + }, + attendee: { + findMany: mock(), + findUnique: mock(), + }, + payment: { + findMany: mock(), + }, + attendance: { + findMany: mock(), + upsert: mock(), + }, + slotRelease: { + findMany: mock(), + upsert: mock(), + }, +}; + +mock.module('@/lib/prisma', () => ({ + default: db, + getPrismaClient: mock(), + UnitOfWork: class { + executeResult = mock(async (cb: (tx: unknown) => Promise) => cb(db)); + execute = mock(async (cb: (tx: unknown) => Promise) => cb(db)); + }, +})); + +import prisma from '@/lib/prisma'; +import { classesRoutes } from '@/modules/classes'; + +const userId = 'user-1'; +const UTC_WEEKDAYS = [ + 'SUNDAY', + 'MONDAY', + 'TUESDAY', + 'WEDNESDAY', + 'THURSDAY', + 'FRIDAY', + 'SATURDAY', +] as const; +const todayUtc = UTC_WEEKDAYS[new Date().getUTCDay()]; + +function makeApp(userValue: unknown) { + const app = new Hono(); + app.use('*', async (c, next) => { + c.set('user', userValue as never); + await next(); + }); + app.route('/classes', classesRoutes); + return app; +} + +function makeSession(overrides: Record = {}) { + return { + id: 'session-1', + groupId: 'group-1', + startsAt: new Date('2026-09-23T19:00:00.000Z'), + group: { + id: 'group-1', + name: 'Funcional', + createdById: userId, + members: [], + capacity: 10, + }, + ...overrides, + }; +} + +describe('classes routes', () => { + beforeEach(() => { + vi.clearAllMocks(); + delete process.env.ABSENCE_RELEASE_HOURS; + }); + + describe('GET /classes/today', () => { + it('materializa y lista las clases de hoy del profesor', async () => { + const startsAt = new Date('2026-09-23T19:00:00.000Z'); + prisma.group.findMany.mockResolvedValue([ + { + id: 'group-1', + name: 'Funcional', + days: [todayUtc], + time: '19:00', + capacity: 10, + _count: { attendees: 8 }, + }, + ]); + prisma.classSession.upsert.mockResolvedValue({ id: 'session-1' }); + prisma.classSession.findMany.mockResolvedValue([ + { id: 'session-1', groupId: 'group-1', startsAt, group: { id: 'group-1', name: 'Funcional', capacity: 10 } }, + ]); + prisma.attendance.findMany.mockResolvedValue([{ classSessionId: 'session-1' }]); + + const res = await makeApp({ id: userId }).request('/classes/today?timeZone=UTC'); + + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ + data: [ + { + sessionId: 'session-1', + groupId: 'group-1', + groupName: 'Funcional', + startsAt: startsAt.toISOString(), + enrolledCount: 8, + capacity: 10, + availableSlots: 2, + hasAttendance: true, + }, + ], + }); + expect(prisma.classSession.upsert).toHaveBeenCalledTimes(1); + expect(prisma.classSession.upsert).toHaveBeenCalledWith({ + where: { + groupId_startsAt: { groupId: 'group-1', startsAt }, + }, + create: { groupId: 'group-1', startsAt }, + update: {}, + select: { id: true }, + }); + }); + + it('devuelve lista vacía cuando ningún grupo tiene clase hoy', async () => { + prisma.group.findMany.mockResolvedValue([]); + + const res = await makeApp({ id: userId }).request('/classes/today?timeZone=UTC'); + + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ data: [] }); + expect(prisma.classSession.upsert).not.toHaveBeenCalled(); + }); + + it('rechaza requests sin sesión', async () => { + const res = await makeApp(null).request('/classes/today'); + + expect(res.status).toBe(401); + expect(await res.json()).toMatchObject({ code: 'unauthorized' }); + }); + }); + + describe('GET /classes/:sessionId/students', () => { + it('incluye estado de pago dinámico, asistencia y ausencia avisada', async () => { + prisma.classSession.findUnique.mockResolvedValue(makeSession()); + prisma.attendee.findMany.mockResolvedValue([ + { id: 'attendee-1', fullName: 'Ana Pérez' }, + { id: 'attendee-2', fullName: 'Bruno Díaz' }, + ]); + prisma.payment.findMany.mockResolvedValue([ + { attendeeId: 'attendee-1', status: 'OVERDUE', dueDate: new Date('2026-09-01T00:00:00.000Z') }, + { attendeeId: 'attendee-2', status: 'PAID', dueDate: new Date('2026-09-01T00:00:00.000Z') }, + ]); + prisma.attendance.findMany.mockResolvedValue([ + { attendeeId: 'attendee-2', status: 'EXCUSED' }, + ]); + prisma.slotRelease.findMany.mockResolvedValue([]); + + const res = await makeApp({ id: userId }).request( + '/classes/session-1/students?timeZone=UTC', + ); + + expect(res.status).toBe(200); + const body = await res.json(); + expect(body).toMatchObject({ + sessionId: 'session-1', + groupId: 'group-1', + groupName: 'Funcional', + students: [ + { + attendeeId: 'attendee-1', + fullName: 'Ana Pérez', + paymentStatus: 'PENDING', + attendanceStatus: null, + notifiedAbsence: false, + }, + { + attendeeId: 'attendee-2', + fullName: 'Bruno Díaz', + paymentStatus: 'UP_TO_DATE', + attendanceStatus: 'EXCUSED', + notifiedAbsence: true, + }, + ], + }); + }); + + it('prohíbe el acceso a quien no es owner ni miembro del grupo', async () => { + prisma.classSession.findUnique.mockResolvedValue( + makeSession({ + group: { + id: 'group-1', + name: 'Funcional', + createdById: 'someone-else', + members: [], + }, + }), + ); + + const res = await makeApp({ id: userId }).request('/classes/session-1/students'); + + expect(res.status).toBe(403); + expect(await res.json()).toMatchObject({ code: 'group_access_denied' }); + }); + + it('devuelve 404 si la sesión no existe', async () => { + prisma.classSession.findUnique.mockResolvedValue(null); + + const res = await makeApp({ id: userId }).request('/classes/nope/students'); + + expect(res.status).toBe(404); + expect(await res.json()).toMatchObject({ code: 'not_found' }); + }); + }); + + describe('POST /classes/:sessionId/attendance', () => { + const validBody = { + classSessionId: 'session-1', + records: [ + { attendeeId: 'attendee-1', status: 'PRESENT' }, + { attendeeId: 'attendee-2', status: 'ABSENT' }, + ], + }; + + it('guarda la asistencia masiva con upsert', async () => { + prisma.classSession.findUnique.mockResolvedValue(makeSession()); + prisma.attendee.findMany.mockResolvedValue([ + { id: 'attendee-1' }, + { id: 'attendee-2' }, + ]); + prisma.attendance.upsert.mockResolvedValue({}); + + const res = await makeApp({ id: userId }).request('/classes/session-1/attendance', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(validBody), + }); + + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ classSessionId: 'session-1', marked: 2 }); + expect(prisma.attendance.upsert).toHaveBeenCalledTimes(2); + expect(prisma.attendance.upsert).toHaveBeenCalledWith( + expect.objectContaining({ + where: { + attendeeId_classSessionId: { + attendeeId: 'attendee-1', + classSessionId: 'session-1', + }, + }, + }), + ); + }); + + it('rechaza cuando el classSessionId del body no coincide con la ruta', async () => { + const res = await makeApp({ id: userId }).request('/classes/session-1/attendance', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ ...validBody, classSessionId: 'other-session' }), + }); + + expect(res.status).toBe(400); + expect(await res.json()).toMatchObject({ status: 400 }); + }); + + it('rechaza alumnos que no pertenecen al grupo', async () => { + prisma.classSession.findUnique.mockResolvedValue(makeSession()); + prisma.attendee.findMany.mockResolvedValue([{ id: 'attendee-1' }]); + + const res = await makeApp({ id: userId }).request('/classes/session-1/attendance', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(validBody), + }); + + expect(res.status).toBe(400); + expect(prisma.attendance.upsert).not.toHaveBeenCalled(); + }); + + it('rechaza registros con status fuera del contrato', async () => { + const res = await makeApp({ id: userId }).request('/classes/session-1/attendance', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + classSessionId: 'session-1', + records: [{ attendeeId: 'attendee-1', status: 'EXCUSED' }], + }), + }); + + expect(res.status).toBe(400); + }); + + it('rechaza requests sin sesión', async () => { + const res = await makeApp(null).request('/classes/session-1/attendance', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(validBody), + }); + + expect(res.status).toBe(401); + }); + }); + + describe('POST /classes/:sessionId/notify-absence (profesor)', () => { + const notifyBody = { + attendeeId: 'attendee-1', + classSessionId: 'session-1', + }; + + it('libera el cupo cuando la anticipación alcanza las 12 horas', async () => { + const startsAt = new Date(Date.now() + 24 * 60 * 60 * 1000); + prisma.classSession.findUnique.mockResolvedValue(makeSession({ startsAt })); + prisma.attendee.findUnique.mockResolvedValue({ + id: 'attendee-1', + groupId: 'group-1', + }); + prisma.attendance.upsert.mockResolvedValue({}); + prisma.slotRelease.upsert.mockResolvedValue({}); + + const res = await makeApp({ id: userId }).request( + '/classes/session-1/notify-absence', + { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(notifyBody), + }, + ); + + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ + classSessionId: 'session-1', + notified: true, + slotReleased: true, + }); + expect(prisma.attendance.upsert).toHaveBeenCalledTimes(1); + expect(prisma.slotRelease.upsert).toHaveBeenCalledTimes(1); + }); + + it('marca EXCUSED sin liberar cupo si avisa con menos de 12 horas', async () => { + const startsAt = new Date(Date.now() + 60 * 60 * 1000); + prisma.classSession.findUnique.mockResolvedValue(makeSession({ startsAt })); + prisma.attendee.findUnique.mockResolvedValue({ + id: 'attendee-1', + groupId: 'group-1', + }); + prisma.attendance.upsert.mockResolvedValue({}); + prisma.slotRelease.upsert.mockResolvedValue({}); + + const res = await makeApp({ id: userId }).request( + '/classes/session-1/notify-absence', + { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(notifyBody), + }, + ); + + expect(res.status).toBe(200); + expect(await res.json()).toMatchObject({ slotReleased: false }); + expect(prisma.slotRelease.upsert).not.toHaveBeenCalled(); + expect(prisma.attendance.upsert).toHaveBeenCalledTimes(1); + }); + + it('respeta el override configurable ABSENCE_RELEASE_HOURS', async () => { + process.env.ABSENCE_RELEASE_HOURS = '4'; + const startsAt = new Date(Date.now() + 6 * 60 * 60 * 1000); + prisma.classSession.findUnique.mockResolvedValue(makeSession({ startsAt })); + prisma.attendee.findUnique.mockResolvedValue({ + id: 'attendee-1', + groupId: 'group-1', + }); + prisma.attendance.upsert.mockResolvedValue({}); + prisma.slotRelease.upsert.mockResolvedValue({}); + + const res = await makeApp({ id: userId }).request( + '/classes/session-1/notify-absence', + { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(notifyBody), + }, + ); + + expect(res.status).toBe(200); + expect(await res.json()).toMatchObject({ slotReleased: true }); + expect(prisma.slotRelease.upsert).toHaveBeenCalledTimes(1); + delete process.env.ABSENCE_RELEASE_HOURS; + }); + + it('rechaza un alumno de otro grupo', async () => { + prisma.classSession.findUnique.mockResolvedValue(makeSession()); + prisma.attendee.findUnique.mockResolvedValue({ + id: 'attendee-1', + groupId: 'another-group', + }); + + const res = await makeApp({ id: userId }).request( + '/classes/session-1/notify-absence', + { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(notifyBody), + }, + ); + + expect(res.status).toBe(400); + expect(prisma.attendance.upsert).not.toHaveBeenCalled(); + }); + }); + + describe('rutas públicas con token', () => { + it('GET /classes/absence devuelve 404 con token inválido', async () => { + prisma.attendee.findUnique.mockResolvedValue(null); + + const res = await makeApp(null).request('/classes/absence?token=bad-token'); + + expect(res.status).toBe(404); + expect(await res.json()).toMatchObject({ code: 'not_found' }); + }); + + it('GET /classes/absence devuelve las clases de hoy del alumno', async () => { + const mxWeekday = new Intl.DateTimeFormat('en-US', { + timeZone: 'America/Mexico_City', + weekday: 'long', + }) + .format(new Date()) + .toUpperCase(); + const startsAt = new Date('2026-09-23T19:00:00.000Z'); + + prisma.attendee.findUnique.mockResolvedValue({ + id: 'attendee-1', + fullName: 'Ana Pérez', + group: { + id: 'group-1', + name: 'Funcional', + days: [mxWeekday], + time: '19:00', + }, + }); + prisma.classSession.upsert.mockResolvedValue({ id: 'session-1' }); + prisma.classSession.findMany.mockResolvedValue([ + { id: 'session-1', groupId: 'group-1', startsAt }, + ]); + prisma.attendance.findMany.mockResolvedValue([]); + prisma.slotRelease.findMany.mockResolvedValue([]); + + const res = await makeApp(null).request('/classes/absence?token=valid-token'); + + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ + attendeeId: 'attendee-1', + fullName: 'Ana Pérez', + groupName: 'Funcinal'.replace('Funcinal', 'Funcional'), + sessions: [ + { + sessionId: 'session-1', + groupName: 'Funcional', + startsAt: startsAt.toISOString(), + notified: false, + attendanceStatus: null, + }, + ], + }); + }); + + it('POST /classes/notify-absence público registra el aviso con token', async () => { + const startsAt = new Date(Date.now() + 24 * 60 * 60 * 1000); + prisma.attendee.findUnique.mockResolvedValue({ + id: 'attendee-1', + groupId: 'group-1', + }); + prisma.classSession.findUnique.mockResolvedValue(makeSession({ startsAt })); + prisma.attendance.upsert.mockResolvedValue({}); + prisma.slotRelease.upsert.mockResolvedValue({}); + + const res = await makeApp(null).request('/classes/notify-absence', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ token: 'valid-token', classSessionId: 'session-1' }), + }); + + expect(res.status).toBe(200); + expect(await res.json()).toMatchObject({ notified: true, slotReleased: true }); + expect(prisma.attendance.upsert).toHaveBeenCalledTimes(1); + }); + + it('POST /classes/notify-absence público devuelve 404 con token inválido', async () => { + prisma.attendee.findUnique.mockResolvedValue(null); + + const res = await makeApp(null).request('/classes/notify-absence', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ token: 'bad', classSessionId: 'session-1' }), + }); + + expect(res.status).toBe(404); + expect(prisma.attendance.upsert).not.toHaveBeenCalled(); + }); + }); +}); diff --git a/apps/backend/test/session-auth.test.ts b/apps/backend/test/session-auth.test.ts index 6662b01..931a1d1 100644 --- a/apps/backend/test/session-auth.test.ts +++ b/apps/backend/test/session-auth.test.ts @@ -38,6 +38,18 @@ describe('session auth', () => { expect(isPublicApiRequest('GET', '/api/v1/attendees')).toBe(false); }); + it('classifies absence notification endpoints as public (token-based)', () => { + expect(isPublicApiRequest('GET', '/api/v1/classes/absence?token=abc')).toBe(true); + expect(isPublicApiRequest('POST', '/api/v1/classes/notify-absence')).toBe(true); + // Las rutas autenticadas de clases siguen protegidas. + expect(isPublicApiRequest('GET', '/api/v1/classes/today')).toBe(false); + expect(isPublicApiRequest('GET', '/api/v1/classes/session-1/students')).toBe(false); + expect(isPublicApiRequest('POST', '/api/v1/classes/session-1/attendance')).toBe(false); + expect( + isPublicApiRequest('POST', '/api/v1/classes/session-1/notify-absence'), + ).toBe(false); + }); + it('allows public requests without a session', async () => { const app = new Hono(); app.use('*', sessionAuthMiddleware); diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts index 0de4b2c..f02ac70 100644 --- a/apps/web/src/lib/api.ts +++ b/apps/web/src/lib/api.ts @@ -1,8 +1,12 @@ import type { + AbsenceDetails, AttendeeDto, + AttendeeHistory, AttendeeList, + AttendeeStatus, BulkCreateAttendees, BulkCreateAttendeesResult, + ClassTodayList, ConnectPayment, ConnectPaymentResult, CreateAttendee, @@ -11,6 +15,7 @@ import type { CreateFirstGroupResult, CreateGroupResult, CreateGroupWaitlistEntry, + GroupAnalytics, GroupDto, GroupInviteInfoDto, GroupList, @@ -20,11 +25,19 @@ import type { InviteTokenResult, JoinGroupViaInvite, JoinGroupViaInviteResult, + MarkAttendance, + MarkAttendanceResult, + NotifyAbsence, + NotifyAbsenceResult, OnboardingStatusDto, ProblemDetails, PromoteGroupWaitlistEntryResult, + PublicNotifyAbsence, RemoveAttendeeResult, RemoveGroupWaitlistEntryResult, + SessionStudents, + StudentsAtRisk, + UpdateStudentStatusResult, } from '@gruperly/shared' const API_URL = import.meta.env.VITE_API_URL ?? 'http://localhost:4000' @@ -89,18 +102,18 @@ export const createGroup = (payload: CreateFirstGroup) => export const getGroups = () => apiFetch('/api/v1/groups') -export const getHomeSummary = () => { - let timeZone: string | undefined +function timeZoneParam(): string { try { - timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone + const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone + return timeZone ? `?timeZone=${encodeURIComponent(timeZone)}` : '' } catch { - // Sin zona horaria disponible: el backend usa su valor por defecto. - timeZone = undefined + return '' } - const params = timeZone ? `?timeZone=${encodeURIComponent(timeZone)}` : '' - return apiFetch(`/api/v1/home${params}`) } +export const getHomeSummary = () => + apiFetch(`/api/v1/home${timeZoneParam()}`) + export const getGroup = (groupId: string) => apiFetch(`/api/v1/groups/${groupId}`) @@ -171,4 +184,50 @@ export const removeGroupAttendee = ( { method: 'DELETE', }, - ) \ No newline at end of file + ) + +// — Día a Día: clases y asistencia — + +export const getClassesToday = () => + apiFetch(`/api/v1/classes/today${timeZoneParam()}`) + +export const getSessionStudents = (sessionId: string) => + apiFetch(`/api/v1/classes/${sessionId}/students${timeZoneParam()}`) + +export const markAttendance = (sessionId: string, payload: MarkAttendance) => + apiFetch(`/api/v1/classes/${sessionId}/attendance`, { + method: 'POST', + body: JSON.stringify(payload), + }) + +export const notifyAbsence = (sessionId: string, payload: NotifyAbsence) => + apiFetch(`/api/v1/classes/${sessionId}/notify-absence`, { + method: 'POST', + body: JSON.stringify(payload), + }) + +export const getAbsenceDetails = (token: string) => + apiFetch(`/api/v1/classes/absence?token=${encodeURIComponent(token)}`) + +export const publicNotifyAbsence = (payload: PublicNotifyAbsence) => + apiFetch('/api/v1/classes/notify-absence', { + method: 'POST', + body: JSON.stringify(payload), + }) + +// — Analíticas y gestión de riesgo — + +export const getGroupAnalytics = (groupId: string) => + apiFetch(`/api/v1/groups/${groupId}/analytics`) + +export const getStudentsAtRisk = (groupId: string) => + apiFetch(`/api/v1/groups/${groupId}/students-at-risk`) + +export const getAttendeeHistory = (groupId: string, attendeeId: string) => + apiFetch(`/api/v1/groups/${groupId}/attendees/${attendeeId}/history`) + +export const updateAttendeeStatus = (attendeeId: string, status: AttendeeStatus) => + apiFetch(`/api/v1/students/${attendeeId}/status`, { + method: 'POST', + body: JSON.stringify({ status }), + }) \ No newline at end of file diff --git a/apps/web/src/router.tsx b/apps/web/src/router.tsx index 7865cb8..8644dba 100644 --- a/apps/web/src/router.tsx +++ b/apps/web/src/router.tsx @@ -13,6 +13,9 @@ import { OnboardingView } from './routes/onboarding' import { GroupDetailView } from './routes/group-detail' import { CreateGroupView } from './routes/create-group' import { JoinGroupView } from './routes/join-group' +import { ClassAttendanceView } from './routes/class-attendance' +import { AbsenceNotifyView } from './routes/absence-notify' +import { AnalyticsView } from './routes/analytics' const rootRoute = createRootRoute({ component: () => , @@ -48,6 +51,13 @@ const joinGroupRoute = createRoute({ component: JoinGroupView, }) +// Página pública: el alumno avisa su ausencia con su token personal. +const absenceNotifyRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/avisar-ausencia/$token', + component: AbsenceNotifyView, +}) + // Capa con la navegación de la app autenticada (Sidebar + BottomNav). // El guard redirige a /onboarding a quien no completó el onboarding. const appLayoutRoute = createRoute({ @@ -80,6 +90,12 @@ const groupDetailRoute = createRoute({ component: GroupDetailView, }) +const groupAnalyticsRoute = createRoute({ + getParentRoute: () => appLayoutRoute, + path: '/groups/$groupId/analytics', + component: AnalyticsView, +}) + const paymentsRoute = createRoute({ getParentRoute: () => appLayoutRoute, path: '/payments', @@ -104,21 +120,30 @@ const profileRoute = createRoute({ component: ProfileView, }) +const classAttendanceRoute = createRoute({ + getParentRoute: () => appLayoutRoute, + path: '/class/$sessionId/attendance', + component: ClassAttendanceView, +}) + const routeTree = rootRoute.addChildren([ loginRoute, signupRoute, verifyEmailRoute, onboardingRoute, joinGroupRoute, + absenceNotifyRoute, appLayoutRoute.addChildren([ indexRoute, groupsRoute, createGroupRoute, groupDetailRoute, + groupAnalyticsRoute, paymentsRoute, settingsRoute, securityRoute, profileRoute, + classAttendanceRoute, ]), ]) diff --git a/apps/web/src/routes/absence-notify.tsx b/apps/web/src/routes/absence-notify.tsx new file mode 100644 index 0000000..034babe --- /dev/null +++ b/apps/web/src/routes/absence-notify.tsx @@ -0,0 +1,164 @@ +import { useState } from 'react' +import { useMutation, useQuery } from '@tanstack/react-query' +import { Link, useParams } from '@tanstack/react-router' +import { CalendarX2, CheckCircle2, Loader2, Moon, Sun } from 'lucide-react' +import { Badge, Button, useToast } from '../components/ui' +import { Logo } from '../components/brand' +import { useTheme } from '../context/ThemeProvider' +import { ApiError, getAbsenceDetails, publicNotifyAbsence } from '../lib/api' + +export function AbsenceNotifyView() { + const { token } = useParams({ strict: false }) as { token: string } + const { setTheme, isDark } = useTheme() + const toast = useToast() + + const [locallyNotified, setLocallyNotified] = useState([]) + + const detailsQuery = useQuery({ + queryKey: ['absence-details', token], + queryFn: () => getAbsenceDetails(token), + enabled: Boolean(token), + retry: 1, + }) + + const notifyMutation = useMutation({ + mutationFn: (sessionId: string) => + publicNotifyAbsence({ token, classSessionId: sessionId }), + onSuccess: (_data, sessionId) => { + setLocallyNotified((prev) => [...prev, sessionId]) + toast.success( + 'Tu profesor ya tiene registrado el aviso. Gracias por avisar.', + 'Ausencia avisada', + ) + }, + onError: (error: unknown) => { + if (error instanceof ApiError && error.problem?.status === 404) { + toast.error('Este enlace ya no es válido. Consultá a tu profesor.') + return + } + toast.error( + error instanceof Error ? error.message : 'No pudimos registrar el aviso.', + ) + }, + }) + + const details = detailsQuery.data + + return ( +
+
+ + + + +
+ +
+
+ {detailsQuery.isPending ? ( +
+ +

Cargando tus clases...

+
+ ) : null} + + {detailsQuery.isError || !details ? ( +
+

Enlace no válido

+

+ No pudimos identificarte con este enlace. Consultá con tu profesor para + solicitar uno nuevo. +

+
+ ) : null} + + {details ? ( +
+
+
+ +
+ + Aviso de ausencia + +

Hola, {details.fullName}

+

+ Grupo: {details.groupName} +

+
+ + {details.sessions.length === 0 ? ( +

+ No tenés clases programadas para hoy. Si necesitás avisar de todas formas, + contactá a tu profesor. +

+ ) : ( +
    + {details.sessions.map((session) => { + const time = new Date(session.startsAt).toLocaleTimeString('es-MX', { + hour: '2-digit', + minute: '2-digit', + hour12: false, + }) + const notified = + session.notified || locallyNotified.includes(session.sessionId) + + return ( +
  • +
    +

    + Hoy · {time} hs +

    +

    + {session.groupName} +

    +
    + {notified ? ( + + + Ya avisaste + + ) : ( + + )} +
  • + ) + })} +
+ )} + +

+ Si avisás con anticipación, tu cupo se libera para una clase de recuperación. +

+
+ ) : null} +
+
+ +
+ Gruperly — Gestión sencilla de cobros y grupos +
+
+ ) +} diff --git a/apps/web/src/routes/analytics.tsx b/apps/web/src/routes/analytics.tsx new file mode 100644 index 0000000..a13a87e --- /dev/null +++ b/apps/web/src/routes/analytics.tsx @@ -0,0 +1,472 @@ +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; +import { Link, useParams } from '@tanstack/react-router'; +import type { AttendeeStatus, StudentAtRiskDto } from '@gruperly/shared'; +import { + ArrowLeft, + CalendarCheck, + DoorOpen, + Loader2, + MessageCircle, + MoreVertical, + Pause, + Percent, + UserMinus, + Users, +} from 'lucide-react'; +import { useState, type ReactNode } from 'react'; +import { Avatar, Badge, Button, Modal, useToast } from '../components/ui'; +import { + getAttendeeHistory, + getGroupAnalytics, + getStudentsAtRisk, + updateAttendeeStatus, +} from '../lib/api'; +import { cn } from '../lib/utils'; + +type StatusAction = { student: StudentAtRiskDto; status: AttendeeStatus } | null; + +function KpiCard({ + icon, + label, + value, + hint, +}: { + icon: ReactNode; + label: string; + value: string; + hint?: string; +}) { + return ( +
+
+ {icon} +
+
+

{label}

+

{value}

+ {hint ?

{hint}

: null} +
+
+ ); +} + +function statusLabel(status: string | null): string { + switch (status) { + case 'PRESENT': + return 'Presente'; + case 'ABSENT': + return 'Ausente'; + case 'EXCUSED': + return 'Avisó ausencia'; + default: + return 'Sin registrar'; + } +} + +function dotClass(status: string | null): string { + switch (status) { + case 'PRESENT': + return 'bg-success'; + case 'ABSENT': + return 'bg-danger'; + case 'EXCUSED': + return 'bg-warning'; + default: + return 'bg-border'; + } +} + +function formatSessionDate(iso: string): string { + return new Date(iso).toLocaleDateString('es-MX', { + weekday: 'short', + day: 'numeric', + month: 'short', + }); +} + +export function AnalyticsView() { + const { groupId } = useParams({ strict: false }) as { groupId: string }; + const queryClient = useQueryClient(); + const toast = useToast(); + + const [historyStudent, setHistoryStudent] = useState(null); + const [statusAction, setStatusAction] = useState(null); + const [menuOpenFor, setMenuOpenFor] = useState(null); + + const analyticsQuery = useQuery({ + queryKey: ['group-analytics', groupId], + queryFn: () => getGroupAnalytics(groupId), + enabled: Boolean(groupId), + }); + + const riskQuery = useQuery({ + queryKey: ['students-at-risk', groupId], + queryFn: () => getStudentsAtRisk(groupId), + enabled: Boolean(groupId), + }); + + const historyQuery = useQuery({ + queryKey: ['attendee-history', groupId, historyStudent?.attendeeId], + queryFn: () => getAttendeeHistory(groupId, historyStudent!.attendeeId!), + enabled: Boolean(groupId && historyStudent), + }); + + const statusMutation = useMutation({ + mutationFn: (action: Exclude) => + updateAttendeeStatus(action.student.attendeeId, action.status), + onSuccess: (_result, action) => { + const name = action.student.fullName.split(' ')[0]; + toast.success( + action.status === 'DROPPED' + ? `${name} fue dado de baja del grupo. Su vacante quedó disponible.` + : `La vacante de ${name} quedó pausada.`, + ); + setStatusAction(null); + void queryClient.invalidateQueries({ queryKey: ['students-at-risk', groupId] }); + void queryClient.invalidateQueries({ queryKey: ['group-attendees', groupId] }); + void queryClient.invalidateQueries({ queryKey: ['group', groupId] }); + void queryClient.invalidateQueries({ queryKey: ['classes-today'] }); + void queryClient.invalidateQueries({ queryKey: ['home-summary'] }); + }, + onError: (err: Error) => { + toast.error(err.message || 'No pudimos actualizar el estado del alumno.'); + }, + }); + + const handleReengage = async (student: StudentAtRiskDto, groupName: string) => { + if (!student.phone) return; + const firstName = student.fullName.split(' ')[0] ?? student.fullName; + const message = + `¡Hola ${firstName}! 👋 Te extrañamos en ${groupName}. ` + + 'Notamos que no asististe a las últimas clases y queremos que vuelvas. ' + + 'Si tenés algún problema con tus horarios o tu membresía, escribinos y lo resolvemos juntos.'; + const waUrl = `https://wa.me/${student.phone.replace(/\D/g, '')}?text=${encodeURIComponent(message)}`; + try { + await navigator.clipboard.writeText(message); + toast.success('¡Abriendo WhatsApp! Mensaje copiado al portapapeles.'); + } catch { + // Si clipboard falla, igual abrimos WhatsApp con el mensaje. + } + window.open(waUrl, '_blank', 'noopener,noreferrer'); + }; + + const groupName = riskQuery.data?.groupName; + + if (analyticsQuery.isPending || riskQuery.isPending) { + return ( +
+ +
+ ); + } + + if (analyticsQuery.isError || riskQuery.isError || !analyticsQuery.data) { + return ( +
+

No pudimos cargar las estadísticas

+

Verificá tu conexión e intentá de nuevo.

+ +
+ ); + } + + const analytics = analyticsQuery.data; + const atRisk = riskQuery.data?.data ?? []; + + return ( +
+ + + Volver a {groupName ?? 'el grupo'} + + +
+
+

Estadísticas

+

+ Asistencia y gestión de riesgo de {groupName ?? 'tu grupo'}. +

+
+ + Últimos 30 días + +
+ + {/* KPIs */} +
+ } + label="Asistencia promedio" + value={`${analytics.attendanceRate}%`} + hint="últimos 30 días" + /> + } + label="Asistencias del mes" + value={analytics.totalPresent.toLocaleString('es-MX')} + hint={`${analytics.totalClasses} clases dictadas`} + /> + } + label="Cupos recuperados" + value={analytics.recoveredSlots.toLocaleString('es-MX')} + hint="por ausencias avisadas" + /> +
+ + {/* Alumnos en riesgo */} +
+
+ +

Alumnos en riesgo

+ {atRisk.length > 0 ? ( + s.riskLevel === 'HIGH') ? 'danger' : 'warning'}> + {atRisk.length} {atRisk.length === 1 ? 'alumno' : 'alumnos'} + + ) : null} +
+

+ Alumnos con ausencias consecutivas o baja asistencia mensual. +

+ + {atRisk.length === 0 ? ( +
+

¡Sin alumnos en riesgo!

+

+ No hay ausencias consecutivas ni asistencia por debajo del 50%. +

+
+ ) : ( +
    + {atRisk.map((student) => ( +
  • +
    + + {student.riskLevel === 'HIGH' ? ( + + {student.consecutiveAbsences} faltas seguidas + + ) : ( + Baja asistencia + )} +
    + +
    + + +
    + + + {menuOpenFor === student.attendeeId ? ( + <> +
    setMenuOpenFor(null)} + aria-hidden="true" + /> +
    + + +
    + + ) : null} +
    +
    +
  • + ))} +
+ )} +
+ + {/* Modal: historial del alumno */} + setHistoryStudent(null)} + title={historyStudent?.fullName ?? 'Historial'} + description={historyStudent ? 'Historial de presentismo de las últimas clases.' : undefined} + maxWidth="md" + > + {historyStudent ? ( +
+ {historyQuery.isPending ? ( +
+ +
+ ) : historyQuery.isError || !historyQuery.data ? ( +
+ No pudimos cargar el historial de este alumno. +
+ ) : ( +
+
+ + {historyQuery.data.attendanceRate}% + + + Presentismo general ({historyQuery.data.sessions.length} clases) + +
+ +
    + {historyQuery.data.sessions.map((session) => ( +
  • +
  • + ))} +
+
+ )} +
+ ) : null} +
+ + {/* Modal: confirmar cambio de estado */} + setStatusAction(null)} + title={statusAction?.status === 'DROPPED' ? 'Dar de baja' : 'Pausar vacante'} + maxWidth="md" + > + {statusAction ? ( +
+

+ {statusAction.student.fullName}{' '} + {statusAction.status === 'DROPPED' ? ( + <> + dejará de asistir al grupo y {groupName}. Su + vacante quedará disponible para otro alumno, y + su historial de asistencia se conservará. + + ) : ( + <> + será pausado en{' '} + {groupName}. Su vacante quedará{' '} + libre y podés reactivarla en cualquier + momento. + + )} +

+
+ + +
+
+ ) : null} +
+
+ ); +} \ No newline at end of file diff --git a/apps/web/src/routes/class-attendance.tsx b/apps/web/src/routes/class-attendance.tsx new file mode 100644 index 0000000..a29af96 --- /dev/null +++ b/apps/web/src/routes/class-attendance.tsx @@ -0,0 +1,259 @@ +import { useEffect, useMemo, useState } from 'react' +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' +import { Link, useParams } from '@tanstack/react-router' +import type { SessionStudentDto } from '@gruperly/shared' +import { ArrowLeft, Check, Loader2, X } from 'lucide-react' +import { Avatar, Badge, Button, useToast } from '../components/ui' +import { getSessionStudents, markAttendance } from '../lib/api' +import { cn } from '../lib/utils' + +type AttendanceChoice = 'PRESENT' | 'ABSENT' + +function isLocked(student: SessionStudentDto): boolean { + return student.notifiedAbsence || student.attendanceStatus === 'EXCUSED' +} + +function PaymentBadge({ status }: { status: SessionStudentDto['paymentStatus'] }) { + return status === 'UP_TO_DATE' ? ( + Al día + ) : ( + Pendiente + ) +} + +function AttendanceToggle({ + choice, + disabled, + onToggle, + fullName, +}: { + choice: AttendanceChoice + disabled?: boolean + onToggle: () => void + fullName: string +}) { + const isPresent = choice === 'PRESENT' + + return ( + + ) +} + +function StudentRow({ + student, + choice, + onToggle, +}: { + student: SessionStudentDto + choice: AttendanceChoice + onToggle: () => void +}) { + const locked = isLocked(student) + + return ( +
  • + +
    +

    {student.fullName}

    +
    + + {locked ? Avisó ausencia : null} +
    +
    + +
  • + ) +} + +export function ClassAttendanceView() { + const { sessionId } = useParams({ strict: false }) as { sessionId: string } + const queryClient = useQueryClient() + const toast = useToast() + + const studentsQuery = useQuery({ + queryKey: ['class-students', sessionId], + queryFn: () => getSessionStudents(sessionId), + staleTime: 0, + }) + + const students = studentsQuery.data?.students + + // Estado local de la toma: todos parten PRESENT (1-tap para marcar ausentes). + // Alumnas con ausencia avisada quedan bloqueadas en EXCUSED. + const [choices, setChoices] = useState>({}) + + useEffect(() => { + if (!students) return + const initial: Record = {} + for (const student of students) { + if (isLocked(student)) continue + initial[student.attendeeId] = student.attendanceStatus === 'ABSENT' ? 'ABSENT' : 'PRESENT' + } + setChoices(initial) + }, [students]) + + const presentCount = useMemo( + () => + (students ?? []).filter( + (student) => !isLocked(student) && choices[student.attendeeId] === 'PRESENT', + ).length, + [students, choices], + ) + + const toggleStudent = (attendeeId: string) => { + setChoices((prev) => ({ + ...prev, + [attendeeId]: prev[attendeeId] === 'ABSENT' ? 'PRESENT' : 'ABSENT', + })) + } + + const saveMutation = useMutation({ + mutationFn: () => { + const records = (students ?? []) + .filter((student) => !isLocked(student)) + .map((student) => ({ + attendeeId: student.attendeeId, + status: choices[student.attendeeId] ?? 'PRESENT', + })) + return markAttendance(sessionId, { classSessionId: sessionId, records }) + }, + onSuccess: () => { + toast.success('Asistencia guardada correctamente.', 'Listo') + void queryClient.invalidateQueries({ queryKey: ['classes-today'] }) + void queryClient.invalidateQueries({ queryKey: ['class-students', sessionId] }) + }, + onError: (error: Error) => { + toast.error(error.message || 'No pudimos guardar la asistencia.') + }, + }) + + const sessionInfo = studentsQuery.data + const startTime = sessionInfo + ? new Date(sessionInfo.startsAt).toLocaleTimeString('es-MX', { + hour: '2-digit', + minute: '2-digit', + hour12: false, + }) + : null + + return ( +
    + + + Volver al inicio + + + {studentsQuery.isPending ? ( +
    + +
    + ) : null} + + {studentsQuery.isError ? ( +
    +

    No pudimos cargar la lista de alumnos.

    + +
    + ) : null} + + {sessionInfo ? ( + <> +
    +
    +
    +

    + {sessionInfo.groupName} +

    +

    + {startTime ? `Hoy · ${startTime} hs` : 'Clase de hoy'} +

    +
    + + {presentCount}/{sessionInfo.students.length} presentes + +
    +
    + + {sessionInfo.students.length === 0 ? ( +
    +

    Este grupo no tiene alumnos

    +

    + Agregá miembros desde la ficha del grupo para tomar asistencia. +

    +
    + ) : ( +
      + {sessionInfo.students.map((student) => ( + toggleStudent(student.attendeeId)} + /> + ))} +
    + )} + + {sessionInfo.students.length > 0 ? ( +
    + +
    + ) : null} + + ) : null} +
    + ) +} diff --git a/apps/web/src/routes/group-detail.tsx b/apps/web/src/routes/group-detail.tsx index 28de332..4c9278d 100644 --- a/apps/web/src/routes/group-detail.tsx +++ b/apps/web/src/routes/group-detail.tsx @@ -11,6 +11,7 @@ import type { } from '@gruperly/shared'; import { ArrowLeft, + BarChart3, CalendarClock, Check, ChevronRight, @@ -68,6 +69,9 @@ export function GroupDetailView() { const [isInviteModalOpen, setIsInviteModalOpen] = useState(false); const [isAddAttendeeModalOpen, setIsAddAttendeeModalOpen] = useState(false); const [selectedAttendee, setSelectedAttendee] = useState(null); + const absenceNotifyUrl = selectedAttendee?.notifyToken + ? `${window.location.origin}/avisar-ausencia/${selectedAttendee.notifyToken}` + : null; const [activeTab, setActiveTab] = useState<'quick' | 'bulk'>('quick'); const [listSection, setListSection] = useState<'members' | 'waitlist'>('members'); const [attendeeToRemove, setAttendeeToRemove] = useState(null); @@ -507,6 +511,14 @@ export function GroupDetailView() {
    +
    + {absenceNotifyUrl ? ( +
    +

    + Link para avisar ausencias +

    +
    + + {absenceNotifyUrl} + + +
    + {selectedAttendee.phone ? ( + + + Enviar por WhatsApp + + ) : null} +
    + ) : null} +
    + +
    + + ) +} + function NextClassHero({ nextClass }: { nextClass: NextClassDto }) { const navigate = useNavigate() const hasSchedule = (nextClass.days?.length ?? 0) > 0 @@ -145,6 +212,12 @@ export function HomeView() { queryKey: ['home-summary'], queryFn: getHomeSummary, }) + const classesTodayQuery = useQuery({ + queryKey: ['classes-today'], + queryFn: getClassesToday, + staleTime: 60_000, + }) + const todayClasses = classesTodayQuery.data?.data ?? [] return (
    @@ -187,7 +260,13 @@ export function HomeView() { {summaryQuery.isSuccess && summaryQuery.data.stats.groups > 0 ? (
    - {summaryQuery.data.nextClass ? ( + {todayClasses.length > 0 ? ( +
    + {todayClasses.map((classItem) => ( + + ))} +
    + ) : summaryQuery.data.nextClass ? ( ) : (
    diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index 224ef49..5573f7a 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -1,5 +1,7 @@ export * from './lib/problem-details.js'; export * from './lib/result.js'; +export * from './schemas/analytics.js'; +export * from './schemas/attendance.js'; export * from './schemas/attendees.js'; export * from './schemas/enums.js'; export * from './schemas/groups.js'; diff --git a/packages/shared/src/schemas/analytics.ts b/packages/shared/src/schemas/analytics.ts new file mode 100644 index 0000000..d04d7de --- /dev/null +++ b/packages/shared/src/schemas/analytics.ts @@ -0,0 +1,67 @@ +import { z } from 'zod'; +import { attendanceStatusSchema } from './attendance.js'; + +const isoDateTimeSchema = z.string().datetime(); + +export const attendeeStatusSchema = z.enum(['ACTIVE', 'PAUSED', 'DROPPED']); +export type AttendeeStatus = z.output; + +export const riskLevelSchema = z.enum(['HIGH', 'MEDIUM']); +export type RiskLevel = z.output; + +export const GroupAnalyticsSchema = z.object({ + attendanceRate: z.number().min(0).max(100), + totalPresent: z.number().int().min(0), + totalClasses: z.number().int().min(0), + recoveredSlots: z.number().int().min(0), +}); +export type GroupAnalytics = z.output; +export type GroupAnalyticsDto = GroupAnalytics; + +export const StudentAtRiskSchema = z.object({ + attendeeId: z.string(), + fullName: z.string(), + phone: z.string().nullable(), + riskLevel: riskLevelSchema, + consecutiveAbsences: z.number().int().min(0), + lastAttendedAt: isoDateTimeSchema.nullable(), + monthlyAttendanceRate: z.number().min(0).max(100), +}); +export type StudentAtRisk = z.output; +export type StudentAtRiskDto = StudentAtRisk; + +export const StudentsAtRiskSchema = z.object({ + groupName: z.string(), + data: z.array(StudentAtRiskSchema), +}); +export type StudentsAtRisk = z.output; +export type StudentsAtRiskDto = StudentsAtRisk; + +export const AttendanceHistoryItemSchema = z.object({ + classSessionId: z.string(), + startsAt: isoDateTimeSchema, + status: attendanceStatusSchema.nullable(), +}); +export type AttendanceHistoryItem = z.output; + +export const AttendeeHistorySchema = z.object({ + attendeeId: z.string(), + fullName: z.string(), + groupId: z.string(), + groupName: z.string(), + attendanceRate: z.number().min(0).max(100), + sessions: z.array(AttendanceHistoryItemSchema), +}); +export type AttendeeHistory = z.output; +export type AttendeeHistoryDto = AttendeeHistory; + +export const UpdateStudentStatusSchema = z.object({ + status: attendeeStatusSchema, +}); +export type UpdateStudentStatus = z.output; + +export const UpdateStudentStatusResultSchema = z.object({ + attendeeId: z.string(), + status: attendeeStatusSchema, +}); +export type UpdateStudentStatusResult = z.output; \ No newline at end of file diff --git a/packages/shared/src/schemas/attendance.ts b/packages/shared/src/schemas/attendance.ts new file mode 100644 index 0000000..3e5e376 --- /dev/null +++ b/packages/shared/src/schemas/attendance.ts @@ -0,0 +1,111 @@ +import { z } from 'zod'; +import { timeZoneSchema } from './home.js'; + +const isoDateTimeSchema = z.string().datetime(); + +export const attendanceStatusSchema = z.enum(['PRESENT', 'ABSENT', 'EXCUSED']); +export type AttendanceStatus = z.output; + +export const attendeePaymentStatusSchema = z.enum(['UP_TO_DATE', 'PENDING']); +export type AttendeePaymentStatus = z.output; + +export const MarkAttendanceRecordSchema = z.object({ + attendeeId: z.string().min(1), + status: z.enum(['PRESENT', 'ABSENT']), +}); +export type MarkAttendanceRecord = z.output; + +export const MarkAttendanceSchema = z.object({ + classSessionId: z.string().min(1), + records: z.array(MarkAttendanceRecordSchema).min(1, 'Debes enviar al menos un registro de asistencia'), +}); +export type MarkAttendance = z.output; + +export const MarkAttendanceResultSchema = z.object({ + classSessionId: z.string(), + marked: z.number().int().min(0), +}); +export type MarkAttendanceResult = z.output; + +export const NotifyAbsenceSchema = z.object({ + attendeeId: z.string().min(1), + classSessionId: z.string().min(1), +}); +export type NotifyAbsence = z.output; + +export const PublicNotifyAbsenceSchema = z.object({ + token: z.string().min(1), + classSessionId: z.string().min(1), +}); +export type PublicNotifyAbsence = z.output; + +export const NotifyAbsenceResultSchema = z.object({ + classSessionId: z.string(), + notified: z.boolean(), + slotReleased: z.boolean(), +}); +export type NotifyAbsenceResult = z.output; + +export const AbsenceQuerySchema = z.object({ + token: z.string().min(1), +}); +export type AbsenceQuery = z.output; + +export const ClassTodaySchema = z.object({ + sessionId: z.string(), + groupId: z.string(), + groupName: z.string(), + startsAt: isoDateTimeSchema, + enrolledCount: z.number().int().min(0), + capacity: z.number().int().min(1).nullable(), + availableSlots: z.number().int().min(0).nullable(), + hasAttendance: z.boolean(), +}); +export type ClassToday = z.output; +export type ClassTodayDto = ClassToday; + +export const ClassTodayListSchema = z.object({ + data: z.array(ClassTodaySchema), +}); +export type ClassTodayList = z.output; + +export const TodayClassesQuerySchema = z.object({ + timeZone: timeZoneSchema.optional(), +}); +export type TodayClassesQuery = z.output; + +export const SessionStudentSchema = z.object({ + attendeeId: z.string(), + fullName: z.string(), + paymentStatus: attendeePaymentStatusSchema, + attendanceStatus: attendanceStatusSchema.nullable(), + notifiedAbsence: z.boolean(), +}); +export type SessionStudent = z.output; +export type SessionStudentDto = SessionStudent; + +export const SessionStudentsSchema = z.object({ + sessionId: z.string(), + groupId: z.string(), + groupName: z.string(), + startsAt: isoDateTimeSchema, + students: z.array(SessionStudentSchema), +}); +export type SessionStudents = z.output; + +export const AbsenceSessionSchema = z.object({ + sessionId: z.string(), + groupName: z.string(), + startsAt: isoDateTimeSchema, + notified: z.boolean(), + attendanceStatus: attendanceStatusSchema.nullable(), +}); +export type AbsenceSession = z.output; + +export const AbsenceDetailsSchema = z.object({ + attendeeId: z.string(), + fullName: z.string(), + groupName: z.string(), + sessions: z.array(AbsenceSessionSchema), +}); +export type AbsenceDetails = z.output; diff --git a/packages/shared/src/schemas/attendees.ts b/packages/shared/src/schemas/attendees.ts index 9886c9d..5265dbe 100644 --- a/packages/shared/src/schemas/attendees.ts +++ b/packages/shared/src/schemas/attendees.ts @@ -16,6 +16,7 @@ export const AttendeeDtoSchema = z.object({ guardianName: z.string().nullable(), guardianPhone: z.string().nullable(), notes: z.string().nullable(), + notifyToken: z.string().nullable().optional(), createdAt: isoDateTimeSchema, updatedAt: isoDateTimeSchema, }); diff --git a/packages/shared/src/schemas/home.ts b/packages/shared/src/schemas/home.ts index dcada4f..4af7e4b 100644 --- a/packages/shared/src/schemas/home.ts +++ b/packages/shared/src/schemas/home.ts @@ -15,6 +15,8 @@ const timeZoneSchema = z } }, 'Zona horaria IANA inválida'); +export { timeZoneSchema }; + export const HomeStatsSchema = z.object({ groups: z.number().int().nonnegative(), attendees: z.number().int().nonnegative(), From efde1aaf33405915695d704b2335ea3e25ad79af Mon Sep 17 00:00:00 2001 From: Jose Selesan Date: Thu, 24 Sep 2026 20:45:11 -0300 Subject: [PATCH 2/6] feat: implement groups risk overview feature with analytics and routes --- apps/backend/src/app.ts | 6 +- .../get-groups-risk-overview/route.ts | 19 +++ .../get-groups-risk-overview/use-case.ts | 136 ++++++++++++++++++ apps/backend/src/modules/analytics/index.ts | 1 + .../test/analytics-groups-risk.test.ts | 114 +++++++++++++++ apps/backend/test/classes.test.ts | 13 +- apps/web/src/lib/api.ts | 4 + apps/web/src/routes/analytics.tsx | 1 + apps/web/src/routes/group-detail.tsx | 37 ++++- apps/web/src/routes/groups.tsx | 49 ++++++- packages/shared/src/schemas/analytics.ts | 18 ++- 11 files changed, 382 insertions(+), 16 deletions(-) create mode 100644 apps/backend/src/modules/analytics/features/get-groups-risk-overview/route.ts create mode 100644 apps/backend/src/modules/analytics/features/get-groups-risk-overview/use-case.ts create mode 100644 apps/backend/test/analytics-groups-risk.test.ts diff --git a/apps/backend/src/app.ts b/apps/backend/src/app.ts index 8e5c5e2..e6e1e6d 100644 --- a/apps/backend/src/app.ts +++ b/apps/backend/src/app.ts @@ -10,7 +10,10 @@ import { requestLoggerMiddleware } from '@/http/request-logger'; import { corsMiddleware, securityHeadersMiddleware } from '@/http/security-headers'; import { sessionAuthMiddleware } from '@/http/session-auth'; import { logger } from '@/logger'; -import { studentStatusRoutes } from './modules/analytics'; +import { + groupsRiskOverviewRoute, + studentStatusRoutes, +} from './modules/analytics'; import { attendeesRoutes } from './modules/attendees'; import { authRoutes } from './modules/auth'; import { classesRoutes } from './modules/classes'; @@ -46,6 +49,7 @@ api.route('/payments', paymentsRoutes); api.route('/waitlist', waitlistRoutes); api.route('/classes', classesRoutes); api.route('/students', studentStatusRoutes); +api.route('/groups-risk', groupsRiskOverviewRoute); app.notFound((c) => { return problemJson(c, notFoundProblem(c.req.path)); diff --git a/apps/backend/src/modules/analytics/features/get-groups-risk-overview/route.ts b/apps/backend/src/modules/analytics/features/get-groups-risk-overview/route.ts new file mode 100644 index 0000000..af7e136 --- /dev/null +++ b/apps/backend/src/modules/analytics/features/get-groups-risk-overview/route.ts @@ -0,0 +1,19 @@ +import { Hono } from 'hono'; +import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; +import { GetGroupsRiskOverview } from './use-case'; + +const route = new Hono(); + +route.get('/overview', async (c) => { + const user = c.get('user'); + if (!user) { + return problemJson(c, unauthorizedProblem(c.req.path)); + } + + const useCase = new GetGroupsRiskOverview(); + const result = await useCase.execute(user.id); + + return resultJson(c, result); +}); + +export default route; \ No newline at end of file diff --git a/apps/backend/src/modules/analytics/features/get-groups-risk-overview/use-case.ts b/apps/backend/src/modules/analytics/features/get-groups-risk-overview/use-case.ts new file mode 100644 index 0000000..6fbd966 --- /dev/null +++ b/apps/backend/src/modules/analytics/features/get-groups-risk-overview/use-case.ts @@ -0,0 +1,136 @@ +import { Prisma } from '@generated/prisma/client'; +import type { + AttendanceStatus, + GroupRiskLevel, + GroupRiskSummary, + GroupsRiskOverview, + ProblemDetails, + Result, +} from '@gruperly/shared'; +import { ok } from '@gruperly/shared'; +import prisma from '@/lib/prisma'; +import { buildGroupWhereForUser } from '@/modules/groups/lib'; +import { + classifyRisk, + monthlyAttendanceRate, + trailingAbsentStreak, +} from '../../lib/risk'; +import { ANALYTICS_WINDOW_MS } from '../get-overview/use-case'; + +type GetGroupsRiskOverviewDeps = { + db?: { + group: Prisma.GroupDelegate; + classSession: Prisma.ClassSessionDelegate; + attendee: Prisma.AttendeeDelegate; + attendance: Prisma.AttendanceDelegate; + }; + now?: Date; +}; + +type GroupRow = { id: string; name: string }; +type AttendeeRow = { id: string; groupId: string }; +type SessionRow = { id: string; groupId: string }; +type AttendanceRow = { + attendeeId: string; + status: AttendanceStatus; + classSession: { startsAt: Date }; +}; + +// Resumen de semáforo de riesgo por grupo para la lista de grupos. +// Un grupo es HIGH si tiene al menos un alumno en riesgo alto, MEDIUM si +// alguno en riesgo moderado y NONE en caso contrario. +export class GetGroupsRiskOverview { + constructor(private readonly deps: GetGroupsRiskOverviewDeps = {}) {} + + async execute(userId: string): Promise> { + const db = this.deps.db ?? prisma; + const now = this.deps.now ?? new Date(); + const since = new Date(now.getTime() - ANALYTICS_WINDOW_MS); + + const groups = (await db.group.findMany({ + where: buildGroupWhereForUser(userId) as Prisma.GroupWhereInput, + select: { id: true, name: true }, + })) as GroupRow[]; + + if (groups.length === 0) { + return ok({ items: [] }); + } + + const groupIds = groups.map((group) => group.id); + const attendeeGroup = new Map(); + const sessionCountByGroup = new Map(); + + const [attendees, sessions, attendances] = await Promise.all([ + db.attendee.findMany({ + where: { groupId: { in: groupIds }, status: 'ACTIVE' }, + select: { id: true, groupId: true }, + }) as Promise, + db.classSession.findMany({ + where: { groupId: { in: groupIds }, startsAt: { gte: since } }, + select: { id: true, groupId: true }, + }) as Promise, + db.attendance.findMany({ + where: { attendee: { groupId: { in: groupIds } } }, + select: { + attendeeId: true, + status: true, + classSession: { select: { startsAt: true } }, + }, + orderBy: { classSession: { startsAt: 'desc' } }, + }) as Promise, + ]); + + for (const attendee of attendees) { + attendeeGroup.set(attendee.id, attendee.groupId); + } + for (const session of sessions) { + sessionCountByGroup.set(session.groupId, (sessionCountByGroup.get(session.groupId) ?? 0) + 1); + } + + const streamByAttendee = groupAttendanceByAttendee(attendances); + + const worstRiskByGroup = new Map(); + for (const attendee of attendees) { + const groupId = attendeeGroup.get(attendee.id)!; + const stream = (streamByAttendee.get(attendee.id) ?? []).map((row) => ({ + status: row.status, + occurredAt: row.classSession.startsAt, + })); + const streak = trailingAbsentStreak(stream); + const monthlyRate = monthlyAttendanceRate( + stream.filter((entry) => entry.occurredAt.getTime() >= since.getTime()), + sessionCountByGroup.get(groupId) ?? 0, + ); + const riskLevel = classifyRisk(streak, monthlyRate); + if (!riskLevel) { + continue; + } + + const current = worstRiskByGroup.get(groupId) ?? 'NONE'; + if ( + riskLevel === 'HIGH' || + (riskLevel === 'MEDIUM' && current === 'NONE') + ) { + worstRiskByGroup.set(groupId, riskLevel); + } + } + + const items: GroupRiskSummary[] = groups.map((group) => ({ + groupId: group.id, + groupName: group.name, + riskLevel: worstRiskByGroup.get(group.id) ?? 'NONE', + })); + + return ok({ items }); + } +} + +function groupAttendanceByAttendee(rows: AttendanceRow[]): Map { + const byAttendee = new Map(); + for (const row of rows) { + const list = byAttendee.get(row.attendeeId) ?? []; + list.push(row); + byAttendee.set(row.attendeeId, list); + } + return byAttendee; +} \ No newline at end of file diff --git a/apps/backend/src/modules/analytics/index.ts b/apps/backend/src/modules/analytics/index.ts index 75c5441..4b66d93 100644 --- a/apps/backend/src/modules/analytics/index.ts +++ b/apps/backend/src/modules/analytics/index.ts @@ -1,2 +1,3 @@ +export { default as groupsRiskOverviewRoute } from './features/get-groups-risk-overview/route'; export { default as studentStatusRoutes } from './features/update-attendee-status/route'; export { default as analyticsRoutes } from './routes'; \ No newline at end of file diff --git a/apps/backend/test/analytics-groups-risk.test.ts b/apps/backend/test/analytics-groups-risk.test.ts new file mode 100644 index 0000000..2a8a2a3 --- /dev/null +++ b/apps/backend/test/analytics-groups-risk.test.ts @@ -0,0 +1,114 @@ +import { beforeEach, describe, expect, it, mock, vi } from 'bun:test'; +import { Hono } from 'hono'; + +const db = { + group: { + findMany: mock(), + }, + attendee: { + findMany: mock(), + }, + classSession: { + findMany: mock(), + }, + attendance: { + findMany: mock(), + }, +}; + +mock.module('@/lib/prisma', () => ({ + default: db, + getPrismaClient: mock(), + UnitOfWork: class { + executeResult = mock(async (cb: (tx: unknown) => Promise) => cb(db)); + execute = mock(async (cb: (tx: unknown) => Promise) => cb(db)); + }, +})); + +import { groupsRiskOverviewRoute } from '@/modules/analytics'; + +const userId = 'user-1'; +const DAY_MS = 24 * 60 * 60 * 1000; +const now = Date.now(); +const at = (offsetDays: number) => new Date(now - offsetDays * DAY_MS); + +function makeApp(userValue: unknown) { + const app = new Hono(); + app.use('*', async (c, next) => { + c.set('user', userValue as never); + await next(); + }); + app.route('/groups-risk', groupsRiskOverviewRoute); + return app; +} + +describe('GET /groups-risk/overview', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('devuelve items vacíos si el usuario no tiene grupos', async () => { + prismaFetchGroupFindMany([]); + prismaFetchAttendeeFindMany([]); + prismaFetchClassSessionFindMany([]); + prismaFetchAttendanceFindMany([]); + + const res = await makeApp({ id: userId }).request('/groups-risk/overview'); + + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ items: [] }); + }); + + it('marca HIGH a un grupo con un alumno con 3 ausencias consecutivas', async () => { + prismaFetchGroupFindMany([ + { id: 'group-1', name: 'Funcional' }, + { id: 'group-2', name: 'Yoga' }, + ]); + prismaFetchAttendeeFindMany([ + { id: 'a-1', groupId: 'group-1' }, + { id: 'a-2', groupId: 'group-2' }, + ]); + prismaFetchClassSessionFindMany([ + { id: 's1', groupId: 'group-1', startsAt: at(-1) }, + { id: 's2', groupId: 'group-1', startsAt: at(-2) }, + { id: 's3', groupId: 'group-1', startsAt: at(-3) }, + { id: 's4', groupId: 'group-2', startsAt: at(-1) }, + ]); + prismaFetchAttendanceFindMany([ + attendance('a-1', 'ABSENT', at(-1)), + attendance('a-1', 'ABSENT', at(-2)), + attendance('a-1', 'ABSENT', at(-3)), + attendance('a-2', 'PRESENT', at(-1)), + ]); + + const res = await makeApp({ id: userId }).request('/groups-risk/overview'); + + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ + items: [ + { groupId: 'group-1', groupName: 'Funcional', riskLevel: 'HIGH' }, + { groupId: 'group-2', groupName: 'Yoga', riskLevel: 'NONE' }, + ], + }); + }); +}); + +function prismaFetchGroupFindMany(rows: unknown[]) { + db.group.findMany.mockResolvedValue(rows); +} + +function prismaFetchAttendeeFindMany(rows: unknown[]) { + db.attendee.findMany.mockResolvedValue(rows); +} + +function prismaFetchClassSessionFindMany(rows: unknown[]) { + db.classSession.findMany.mockResolvedValue(rows); +} + +function prismaFetchAttendanceFindMany(rows: unknown[]) { + db.attendance.findMany.mockResolvedValue(rows); +} + +function attendance(attendeeId: string, status: string, startsAt: string) { + return { attendeeId, status, classSession: { startsAt } }; +} \ No newline at end of file diff --git a/apps/backend/test/classes.test.ts b/apps/backend/test/classes.test.ts index 1856a9b..3daf37b 100644 --- a/apps/backend/test/classes.test.ts +++ b/apps/backend/test/classes.test.ts @@ -65,7 +65,7 @@ function makeSession(overrides: Record = {}) { return { id: 'session-1', groupId: 'group-1', - startsAt: new Date('2026-09-23T19:00:00.000Z'), + startsAt: todayAtUtc(), group: { id: 'group-1', name: 'Funcional', @@ -77,6 +77,13 @@ function makeSession(overrides: Record = {}) { }; } +// Fecha "hoy" a las 19:00 UTC, del día real del runner. +function todayAtUtc() { + const date = new Date(); + date.setUTCHours(19, 0, 0, 0); + return date; +} + describe('classes routes', () => { beforeEach(() => { vi.clearAllMocks(); @@ -85,7 +92,7 @@ describe('classes routes', () => { describe('GET /classes/today', () => { it('materializa y lista las clases de hoy del profesor', async () => { - const startsAt = new Date('2026-09-23T19:00:00.000Z'); + const startsAt = todayAtUtc(); prisma.group.findMany.mockResolvedValue([ { id: 'group-1', @@ -432,7 +439,7 @@ describe('classes routes', () => { }) .format(new Date()) .toUpperCase(); - const startsAt = new Date('2026-09-23T19:00:00.000Z'); + const startsAt = todayAtUtc(); prisma.attendee.findUnique.mockResolvedValue({ id: 'attendee-1', diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts index f02ac70..9fee200 100644 --- a/apps/web/src/lib/api.ts +++ b/apps/web/src/lib/api.ts @@ -19,6 +19,8 @@ import type { GroupDto, GroupInviteInfoDto, GroupList, + GroupRiskSummary, + GroupsRiskOverview, GroupWaitlistEntryDto, GroupWaitlistList, HomeSummaryDto, @@ -223,6 +225,8 @@ export const getGroupAnalytics = (groupId: string) => export const getStudentsAtRisk = (groupId: string) => apiFetch(`/api/v1/groups/${groupId}/students-at-risk`) +export const getGroupsRiskOverview = () => apiFetch('/api/v1/groups-risk/overview') + export const getAttendeeHistory = (groupId: string, attendeeId: string) => apiFetch(`/api/v1/groups/${groupId}/attendees/${attendeeId}/history`) diff --git a/apps/web/src/routes/analytics.tsx b/apps/web/src/routes/analytics.tsx index a13a87e..0e148d2 100644 --- a/apps/web/src/routes/analytics.tsx +++ b/apps/web/src/routes/analytics.tsx @@ -127,6 +127,7 @@ export function AnalyticsView() { void queryClient.invalidateQueries({ queryKey: ['group', groupId] }); void queryClient.invalidateQueries({ queryKey: ['classes-today'] }); void queryClient.invalidateQueries({ queryKey: ['home-summary'] }); + void queryClient.invalidateQueries({ queryKey: ['groups-risk-overview'] }); }, onError: (err: Error) => { toast.error(err.message || 'No pudimos actualizar el estado del alumno.'); diff --git a/apps/web/src/routes/group-detail.tsx b/apps/web/src/routes/group-detail.tsx index 4c9278d..7616bb3 100644 --- a/apps/web/src/routes/group-detail.tsx +++ b/apps/web/src/routes/group-detail.tsx @@ -44,6 +44,7 @@ import { createAttendee, getGroup, getGroupAttendees, + getGroupsRiskOverview, getGroupWaitlist, getInviteToken, promoteGroupWaitlistEntry, @@ -106,6 +107,12 @@ export function GroupDetailView() { enabled: Boolean(groupId), }); + const riskOverviewQuery = useQuery({ + queryKey: ['groups-risk-overview'], + queryFn: getGroupsRiskOverview, + enabled: Boolean(groupId), + }); + const inviteTokenQuery = useQuery({ queryKey: ['invite-token', groupId], queryFn: () => getInviteToken(groupId), @@ -487,6 +494,9 @@ export function GroupDetailView() { ); } + const riskLevel = + riskOverviewQuery.data?.items.find((item) => item.groupId === groupId)?.riskLevel ?? 'NONE'; + return (
    {/* Navigation & Header */} @@ -504,17 +514,28 @@ export function GroupDetailView() {

    {group.name}

    Activo + {riskLevel === 'HIGH' || riskLevel === 'MEDIUM' ? ( + + + ) : null}
    {group.description ? (

    {group.description}

    ) : null}
    -
    +
    diff --git a/apps/web/src/routes/groups.tsx b/apps/web/src/routes/groups.tsx index ded2901..0087786 100644 --- a/apps/web/src/routes/groups.tsx +++ b/apps/web/src/routes/groups.tsx @@ -1,14 +1,27 @@ import { useQuery } from '@tanstack/react-query' import { useNavigate } from '@tanstack/react-router' import { CalendarClock, Loader2, Plus, Users } from 'lucide-react' -import type { GroupDto } from '@gruperly/shared' +import type { GroupDto, GroupRiskLevel } from '@gruperly/shared' import { Badge, Button } from '../components/ui' -import { getGroups } from '../lib/api' +import { getGroups, getGroupsRiskOverview } from '../lib/api' import { BILLING_LABELS, formatPrice, formatSchedule } from '../lib/format' +import { cn } from '../lib/utils' -function GroupCard({ group }: { group: GroupDto }) { +const RISK_LABELS: Record, string> = { + HIGH: 'Riesgo alto', + MEDIUM: 'Riesgo moderado', +} + +function GroupCard({ + group, + riskLevel, +}: { + group: GroupDto + riskLevel: GroupRiskLevel +}) { const navigate = useNavigate() const hasSchedule = (group.days?.length ?? 0) > 0 + const hasRisk = riskLevel === 'HIGH' || riskLevel === 'MEDIUM' return (
    @@ -19,7 +32,21 @@ function GroupCard({ group }: { group: GroupDto }) {

    {group.description}

    ) : null}
    - Activo +
    + {hasRisk ? ( + + + ) : null} + Activo +
    {hasSchedule ? ( @@ -62,6 +89,14 @@ export function GroupsView() { queryKey: ['groups'], queryFn: getGroups, }) + const riskQuery = useQuery({ + queryKey: ['groups-risk-overview'], + queryFn: getGroupsRiskOverview, + }) + + const riskByGroup = new Map( + (riskQuery.data?.items ?? []).map((item) => [item.groupId, item.riskLevel]), + ) return (
    @@ -111,7 +146,11 @@ export function GroupsView() { {groupsQuery.isSuccess && groupsQuery.data.data.length > 0 ? (
    {groupsQuery.data.data.map((group) => ( - + ))}
    ) : null} diff --git a/packages/shared/src/schemas/analytics.ts b/packages/shared/src/schemas/analytics.ts index d04d7de..29088f1 100644 --- a/packages/shared/src/schemas/analytics.ts +++ b/packages/shared/src/schemas/analytics.ts @@ -64,4 +64,20 @@ export const UpdateStudentStatusResultSchema = z.object({ attendeeId: z.string(), status: attendeeStatusSchema, }); -export type UpdateStudentStatusResult = z.output; \ No newline at end of file +export type UpdateStudentStatusResult = z.output; + +export const groupRiskLevelSchema = z.enum(['NONE', 'MEDIUM', 'HIGH']); +export type GroupRiskLevel = z.output; + +export const GroupRiskSummarySchema = z.object({ + groupId: z.string(), + groupName: z.string(), + riskLevel: groupRiskLevelSchema, +}); +export type GroupRiskSummary = z.output; + +export const GroupsRiskOverviewSchema = z.object({ + items: z.array(GroupRiskSummarySchema), +}); +export type GroupsRiskOverview = z.output; +export type GroupsRiskOverviewDto = GroupsRiskOverview; \ No newline at end of file From 336e1af523013724aed9c77996a4d4b6dc92b2e7 Mon Sep 17 00:00:00 2001 From: Jose Selesan Date: Fri, 25 Sep 2026 10:05:47 -0300 Subject: [PATCH 3/6] Migrate to file based routing on frontendf --- apps/web/src/components/auth/AuthShell.tsx | 25 - apps/web/src/components/auth/index.ts | 1 - apps/web/src/components/groups/GroupForm.tsx | 231 --- .../onboarding/ConfirmationStep.tsx | 84 - .../components/onboarding/FirstGroupStep.tsx | 30 - .../src/components/onboarding/PaymentStep.tsx | 171 -- .../web/src/components/onboarding/Stepper.tsx | 59 - .../src/components/onboarding/WelcomeStep.tsx | 63 - .../src/components/onboarding/constants.ts | 44 - apps/web/src/components/onboarding/index.ts | 5 - apps/web/src/routes/absence-notify.tsx | 164 -- apps/web/src/routes/analytics.tsx | 473 ----- apps/web/src/routes/auth/login.tsx | 113 -- apps/web/src/routes/auth/signup.tsx | 142 -- apps/web/src/routes/auth/verify-email.tsx | 91 - apps/web/src/routes/class-attendance.tsx | 259 --- apps/web/src/routes/create-group.tsx | 39 - apps/web/src/routes/group-detail.tsx | 1680 ----------------- apps/web/src/routes/groups.tsx | 159 -- apps/web/src/routes/home.tsx | 310 --- apps/web/src/routes/join-group.tsx | 343 ---- apps/web/src/routes/onboarding.tsx | 130 -- apps/web/src/routes/payments.tsx | 8 - apps/web/src/routes/profile.tsx | 27 - apps/web/src/routes/security.tsx | 183 -- apps/web/src/routes/settings.tsx | 97 - 26 files changed, 4931 deletions(-) delete mode 100644 apps/web/src/components/auth/AuthShell.tsx delete mode 100644 apps/web/src/components/auth/index.ts delete mode 100644 apps/web/src/components/groups/GroupForm.tsx delete mode 100644 apps/web/src/components/onboarding/ConfirmationStep.tsx delete mode 100644 apps/web/src/components/onboarding/FirstGroupStep.tsx delete mode 100644 apps/web/src/components/onboarding/PaymentStep.tsx delete mode 100644 apps/web/src/components/onboarding/Stepper.tsx delete mode 100644 apps/web/src/components/onboarding/WelcomeStep.tsx delete mode 100644 apps/web/src/components/onboarding/constants.ts delete mode 100644 apps/web/src/components/onboarding/index.ts delete mode 100644 apps/web/src/routes/absence-notify.tsx delete mode 100644 apps/web/src/routes/analytics.tsx delete mode 100644 apps/web/src/routes/auth/login.tsx delete mode 100644 apps/web/src/routes/auth/signup.tsx delete mode 100644 apps/web/src/routes/auth/verify-email.tsx delete mode 100644 apps/web/src/routes/class-attendance.tsx delete mode 100644 apps/web/src/routes/create-group.tsx delete mode 100644 apps/web/src/routes/group-detail.tsx delete mode 100644 apps/web/src/routes/groups.tsx delete mode 100644 apps/web/src/routes/home.tsx delete mode 100644 apps/web/src/routes/join-group.tsx delete mode 100644 apps/web/src/routes/onboarding.tsx delete mode 100644 apps/web/src/routes/payments.tsx delete mode 100644 apps/web/src/routes/profile.tsx delete mode 100644 apps/web/src/routes/security.tsx delete mode 100644 apps/web/src/routes/settings.tsx diff --git a/apps/web/src/components/auth/AuthShell.tsx b/apps/web/src/components/auth/AuthShell.tsx deleted file mode 100644 index f080c85..0000000 --- a/apps/web/src/components/auth/AuthShell.tsx +++ /dev/null @@ -1,25 +0,0 @@ -import type { ReactNode } from 'react' -import { Logo } from '../brand' - -export type AuthShellProps = { - title: string - subtitle?: string - children: ReactNode -} - -export function AuthShell({ title, subtitle, children }: AuthShellProps) { - return ( -
    -
    -
    - -
    -
    -

    {title}

    - {subtitle ?

    {subtitle}

    : null} -
    {children}
    -
    -
    -
    - ) -} \ No newline at end of file diff --git a/apps/web/src/components/auth/index.ts b/apps/web/src/components/auth/index.ts deleted file mode 100644 index ecfc46d..0000000 --- a/apps/web/src/components/auth/index.ts +++ /dev/null @@ -1 +0,0 @@ -export { AuthShell } from './AuthShell' \ No newline at end of file diff --git a/apps/web/src/components/groups/GroupForm.tsx b/apps/web/src/components/groups/GroupForm.tsx deleted file mode 100644 index a9548c4..0000000 --- a/apps/web/src/components/groups/GroupForm.tsx +++ /dev/null @@ -1,231 +0,0 @@ -import { useForm } from 'react-hook-form' -import { zodResolver } from '@hookform/resolvers/zod' -import type { BillingType, CreateFirstGroup, WeekDay } from '@gruperly/shared' -import { CreateFirstGroupSchema } from '@gruperly/shared' -import { ArrowLeft, Check, Loader2 } from 'lucide-react' -import { cn } from '../../lib/utils' -import { Button, Input, Label } from '../ui' -import { BILLING_TYPES, WEEK_DAY_CHIPS } from '../onboarding/constants' - -const defaultValues: CreateFirstGroup = { - name: '', - days: [], - time: '09:00', - capacity: 1, - price: 0, - billingType: 'MONTHLY', - dueDay: 1, -} - -type GroupFormProps = { - heading: string - description: string - submitLabel: string - isSubmitting: boolean - errorMessage?: string | null - onSubmit: (values: CreateFirstGroup) => void - onBack?: () => void -} - -export function GroupForm({ - heading, - description, - submitLabel, - isSubmitting, - errorMessage, - onSubmit, - onBack, -}: GroupFormProps) { - const { - register, - handleSubmit, - watch, - setValue, - formState: { errors }, - } = useForm({ - resolver: zodResolver(CreateFirstGroupSchema), - defaultValues, - mode: 'onTouched', - }) - - const days = watch('days') - const billingType = watch('billingType') - const dueDay = watch('dueDay') - - const toggleDay = (day: WeekDay) => { - const next = days.includes(day) ? days.filter((d) => d !== day) : [...days, day] - setValue('days', next, { shouldValidate: true }) - } - - const selectBillingType = (type: BillingType) => { - setValue('billingType', type, { shouldValidate: true }) - } - - return ( -
    -
    -

    {heading}

    -

    {description}

    -
    - -
    - - - {errors.name ?

    {errors.name.message}

    : null} -
    - -
    - -
    - {WEEK_DAY_CHIPS.map(({ value, label }) => { - const isActive = days.includes(value) - return ( - - ) - })} -
    - {errors.days ?

    {errors.days.message}

    : null} -
    - -
    - - - {errors.time ?

    {errors.time.message}

    : null} -
    - -
    -
    - - - {errors.capacity ? ( -

    {errors.capacity.message}

    - ) : null} -
    - -
    - -
    - - $ - - -
    - {errors.price ? ( -

    {errors.price.message}

    - ) : null} -
    -
    - -
    - -
    - {BILLING_TYPES.map(({ value, label, hint }) => { - const isActive = billingType === value - return ( - - ) - })} -
    -
    - -
    - - -

    - Los cobros vencerán el día {isFinite(dueDay) && dueDay ? dueDay : '1'} de cada mes. -

    - {errors.dueDay ? ( -

    {errors.dueDay.message}

    - ) : null} -
    - - {errorMessage ? ( -

    {errorMessage}

    - ) : null} - -
    - {onBack ? ( - - ) : null} - -
    -
    - ) -} \ No newline at end of file diff --git a/apps/web/src/components/onboarding/ConfirmationStep.tsx b/apps/web/src/components/onboarding/ConfirmationStep.tsx deleted file mode 100644 index 0060bdb..0000000 --- a/apps/web/src/components/onboarding/ConfirmationStep.tsx +++ /dev/null @@ -1,84 +0,0 @@ -import { useNavigate } from '@tanstack/react-router' -import { useQueryClient } from '@tanstack/react-query' -import type { OnboardingGroupDto } from '@gruperly/shared' -import { ArrowRight, CheckCircle2, CreditCard } from 'lucide-react' -import { useAuth } from '../../context/AuthProvider' -import { Badge, Button } from '../ui' -import { BILLING_LABELS, formatPrice, formatSchedule } from './constants' - -type ConfirmationStepProps = { - group: OnboardingGroupDto - providerName?: string -} - -export function ConfirmationStep({ group, providerName }: ConfirmationStepProps) { - const navigate = useNavigate() - const queryClient = useQueryClient() - const { refresh } = useAuth() - - const goToDashboard = () => { - // Revalida la caché (estado del onboarding, sesión, grupos) antes de redirigir. - void queryClient.invalidateQueries() - void refresh() - void navigate({ to: '/' }) - } - - return ( -
    -
    - - - -

    ¡Todo listo!

    -

    - Tu grupo se creó y ya podés empezar a cobrar a tus miembros. -

    -
    - -
    -
    -
    -

    {group.name}

    -

    - {formatSchedule(group.days ?? [], group.time)} -

    -
    - Activo -
    - -
    -
    -
    Precio
    -
    - {formatPrice(group.price)} - {group.billingType ? ` · ${BILLING_LABELS[group.billingType]}` : ''} -
    -
    -
    -
    Cupo
    -
    {group.capacity ?? '—'} miembros
    -
    -
    -
    Vencimiento
    -
    Día {group.dueDay ?? '—'} de cada mes
    -
    -
    -
    - - {providerName ? ( -
    - -

    - Vas a cobrar con {providerName} en modo - prueba. -

    -
    - ) : null} - - -
    - ) -} \ No newline at end of file diff --git a/apps/web/src/components/onboarding/FirstGroupStep.tsx b/apps/web/src/components/onboarding/FirstGroupStep.tsx deleted file mode 100644 index 32da7bd..0000000 --- a/apps/web/src/components/onboarding/FirstGroupStep.tsx +++ /dev/null @@ -1,30 +0,0 @@ -import { useMutation } from '@tanstack/react-query' -import type { CreateFirstGroup, OnboardingGroupDto } from '@gruperly/shared' -import { createFirstGroup } from '../../lib/api' -import { GroupForm } from '../groups/GroupForm' - -type FirstGroupStepProps = { - onBack: () => void - onCompleted: (group: OnboardingGroupDto) => void -} - -export function FirstGroupStep({ onBack, onCompleted }: FirstGroupStepProps) { - const create = useMutation({ - mutationFn: (values: CreateFirstGroup) => createFirstGroup(values), - onSuccess: (result) => onCompleted(result.group), - }) - - return ( - create.mutate(values)} - onBack={onBack} - /> - ) -} \ No newline at end of file diff --git a/apps/web/src/components/onboarding/PaymentStep.tsx b/apps/web/src/components/onboarding/PaymentStep.tsx deleted file mode 100644 index 8f59e12..0000000 --- a/apps/web/src/components/onboarding/PaymentStep.tsx +++ /dev/null @@ -1,171 +0,0 @@ -import { useState } from 'react' -import { useMutation } from '@tanstack/react-query' -import type { ConnectPaymentResult, PaymentProvider } from '@gruperly/shared' -import { - ArrowLeft, - ArrowRight, - BadgeCheck, - Check, - CheckCircle2, - CreditCard, - Loader2, - ShieldCheck, -} from 'lucide-react' -import { connectPayment } from '../../lib/api' -import { cn } from '../../lib/utils' -import { Badge, Button } from '../ui' -import { PAYMENT_PROVIDERS } from './constants' - -type PaymentStepProps = { - initialResult: ConnectPaymentResult | null - onConnected: (result: ConnectPaymentResult) => void - onBack: () => void -} - -export function PaymentStep({ initialResult, onConnected, onBack }: PaymentStepProps) { - const [selected, setSelected] = useState('MERCADO_PAGO') - const [connected, setConnected] = useState(initialResult) - - const connect = useMutation({ - mutationFn: () => connectPayment({ provider: selected, sandbox: true }), - onSuccess: (result) => { - setConnected(result) - onConnected(result) - }, - }) - - if (connected) { - return ( -
    -
    -

    Tu cobro está conectado

    -

    - Ya podés dejar listo tu primer grupo para cobrar con{' '} - {PAYMENT_PROVIDERS.find((p) => p.value === connected.provider)?.name ?? ''}. -

    -
    - -
    - - - -

    Cuenta conectada

    -
    - - {PAYMENT_PROVIDERS.find((p) => p.value === connected.provider)?.name} - - Modo prueba -
    -
    - -
    - - -
    -
    - ) - } - - return ( -
    -
    -

    Elegí tu procesador de cobro

    -

    - Los pagos de tus miembros van a llegar por esta plataforma. -

    -
    - -
    - {PAYMENT_PROVIDERS.map((provider) => { - const isSelected = selected === provider.value - return ( - - ) - })} -
    - -
    - -

    - Por ahora la conexión se hace en modo prueba (sandbox). Más adelante vas a poder - vincular tu cuenta real de {selected === 'STRIPE' ? 'Stripe' : 'Mercado Pago'}. -

    -
    - - {connect.isError ? ( -

    - No pudimos conectar la cuenta. Intentalo de nuevo. -

    - ) : null} - -
    - - -
    -
    - ) -} \ No newline at end of file diff --git a/apps/web/src/components/onboarding/Stepper.tsx b/apps/web/src/components/onboarding/Stepper.tsx deleted file mode 100644 index 491d4d3..0000000 --- a/apps/web/src/components/onboarding/Stepper.tsx +++ /dev/null @@ -1,59 +0,0 @@ -import { Check } from 'lucide-react' -import { cn } from '../../lib/utils' - -export type StepperProps = { - steps: readonly { label: string }[] - current: number -} - -export function Stepper({ steps, current }: StepperProps) { - return ( -
      - {steps.map((step, index) => { - const isDone = index < current - const isActive = index === current - - return ( -
    1. -
      - - {isDone ? ( - - ) : ( - {index + 1} - )} - - - {step.label} - -
      - - {index < steps.length - 1 ? ( - - ) : null} -
    2. - ) - })} -
    - ) -} \ No newline at end of file diff --git a/apps/web/src/components/onboarding/WelcomeStep.tsx b/apps/web/src/components/onboarding/WelcomeStep.tsx deleted file mode 100644 index 3a219ca..0000000 --- a/apps/web/src/components/onboarding/WelcomeStep.tsx +++ /dev/null @@ -1,63 +0,0 @@ -import { ArrowRight, Rocket, Users, Wallet } from 'lucide-react' -import { Button } from '../ui' - -type WelcomeStepProps = { - name: string - onNext: () => void -} - -const STEPS_TO_SETUP = [ - { - icon: Wallet, - title: 'Conectá tu cuenta de cobro', - description: 'Mercado Pago o Stripe, en modo prueba por ahora.', - }, - { - icon: Users, - title: 'Creá tu primer grupo', - description: 'Días, horario, precio y cupo de tu clase.', - }, - { - icon: Rocket, - title: 'Empezá a cobrar', - description: 'Todo listo para sumar miembros y cobrar al instante.', - }, -] - -export function WelcomeStep({ name, onNext }: WelcomeStepProps) { - return ( -
    -
    - - - -

    ¡Hola, {name}!

    -

    - Vamos a configurar tu cuenta en 3 pasos. Vas a tardar menos de 5 minutos. -

    -
    - -
      - {STEPS_TO_SETUP.map(({ icon: Icon, title, description }) => ( -
    1. - - - -
      -

      {title}

      -

      {description}

      -
      -
    2. - ))} -
    - - -
    - ) -} \ No newline at end of file diff --git a/apps/web/src/components/onboarding/constants.ts b/apps/web/src/components/onboarding/constants.ts deleted file mode 100644 index 308199a..0000000 --- a/apps/web/src/components/onboarding/constants.ts +++ /dev/null @@ -1,44 +0,0 @@ -import type { BillingType, PaymentProvider, WeekDay } from '@gruperly/shared' -export { BILLING_LABELS, WEEK_DAY_FULL_LABELS, formatPrice, formatSchedule } from '../../lib/format' - -export const WEEK_DAYS: readonly WeekDay[] = [ - 'MONDAY', - 'TUESDAY', - 'WEDNESDAY', - 'THURSDAY', - 'FRIDAY', - 'SATURDAY', - 'SUNDAY', -] - -export const WEEK_DAY_CHIPS: readonly { value: WeekDay; label: string }[] = [ - { value: 'MONDAY', label: 'Lun' }, - { value: 'TUESDAY', label: 'Mar' }, - { value: 'WEDNESDAY', label: 'Mié' }, - { value: 'THURSDAY', label: 'Jue' }, - { value: 'FRIDAY', label: 'Vie' }, - { value: 'SATURDAY', label: 'Sáb' }, - { value: 'SUNDAY', label: 'Dom' }, -] - -export const PAYMENT_PROVIDERS: readonly { - value: PaymentProvider - name: string - description: string -}[] = [ - { - value: 'MERCADO_PAGO', - name: 'Mercado Pago', - description: 'El procesador más usado en Latinoamérica', - }, - { - value: 'STRIPE', - name: 'Stripe', - description: 'Cobrá con tarjetas e internacionalmente', - }, -] - -export const BILLING_TYPES: readonly { value: BillingType; label: string; hint: string }[] = [ - { value: 'MONTHLY', label: 'Mensual', hint: 'Un cobro por mes' }, - { value: 'PER_CLASS', label: 'Por clase', hint: 'Cada clase que asista' }, -] \ No newline at end of file diff --git a/apps/web/src/components/onboarding/index.ts b/apps/web/src/components/onboarding/index.ts deleted file mode 100644 index 02224ec..0000000 --- a/apps/web/src/components/onboarding/index.ts +++ /dev/null @@ -1,5 +0,0 @@ -export { Stepper, type StepperProps } from './Stepper' -export { WelcomeStep } from './WelcomeStep' -export { PaymentStep } from './PaymentStep' -export { FirstGroupStep } from './FirstGroupStep' -export { ConfirmationStep } from './ConfirmationStep' \ No newline at end of file diff --git a/apps/web/src/routes/absence-notify.tsx b/apps/web/src/routes/absence-notify.tsx deleted file mode 100644 index 034babe..0000000 --- a/apps/web/src/routes/absence-notify.tsx +++ /dev/null @@ -1,164 +0,0 @@ -import { useState } from 'react' -import { useMutation, useQuery } from '@tanstack/react-query' -import { Link, useParams } from '@tanstack/react-router' -import { CalendarX2, CheckCircle2, Loader2, Moon, Sun } from 'lucide-react' -import { Badge, Button, useToast } from '../components/ui' -import { Logo } from '../components/brand' -import { useTheme } from '../context/ThemeProvider' -import { ApiError, getAbsenceDetails, publicNotifyAbsence } from '../lib/api' - -export function AbsenceNotifyView() { - const { token } = useParams({ strict: false }) as { token: string } - const { setTheme, isDark } = useTheme() - const toast = useToast() - - const [locallyNotified, setLocallyNotified] = useState([]) - - const detailsQuery = useQuery({ - queryKey: ['absence-details', token], - queryFn: () => getAbsenceDetails(token), - enabled: Boolean(token), - retry: 1, - }) - - const notifyMutation = useMutation({ - mutationFn: (sessionId: string) => - publicNotifyAbsence({ token, classSessionId: sessionId }), - onSuccess: (_data, sessionId) => { - setLocallyNotified((prev) => [...prev, sessionId]) - toast.success( - 'Tu profesor ya tiene registrado el aviso. Gracias por avisar.', - 'Ausencia avisada', - ) - }, - onError: (error: unknown) => { - if (error instanceof ApiError && error.problem?.status === 404) { - toast.error('Este enlace ya no es válido. Consultá a tu profesor.') - return - } - toast.error( - error instanceof Error ? error.message : 'No pudimos registrar el aviso.', - ) - }, - }) - - const details = detailsQuery.data - - return ( -
    -
    - - - - -
    - -
    -
    - {detailsQuery.isPending ? ( -
    - -

    Cargando tus clases...

    -
    - ) : null} - - {detailsQuery.isError || !details ? ( -
    -

    Enlace no válido

    -

    - No pudimos identificarte con este enlace. Consultá con tu profesor para - solicitar uno nuevo. -

    -
    - ) : null} - - {details ? ( -
    -
    -
    - -
    - - Aviso de ausencia - -

    Hola, {details.fullName}

    -

    - Grupo: {details.groupName} -

    -
    - - {details.sessions.length === 0 ? ( -

    - No tenés clases programadas para hoy. Si necesitás avisar de todas formas, - contactá a tu profesor. -

    - ) : ( -
      - {details.sessions.map((session) => { - const time = new Date(session.startsAt).toLocaleTimeString('es-MX', { - hour: '2-digit', - minute: '2-digit', - hour12: false, - }) - const notified = - session.notified || locallyNotified.includes(session.sessionId) - - return ( -
    • -
      -

      - Hoy · {time} hs -

      -

      - {session.groupName} -

      -
      - {notified ? ( - - - Ya avisaste - - ) : ( - - )} -
    • - ) - })} -
    - )} - -

    - Si avisás con anticipación, tu cupo se libera para una clase de recuperación. -

    -
    - ) : null} -
    -
    - -
    - Gruperly — Gestión sencilla de cobros y grupos -
    -
    - ) -} diff --git a/apps/web/src/routes/analytics.tsx b/apps/web/src/routes/analytics.tsx deleted file mode 100644 index 0e148d2..0000000 --- a/apps/web/src/routes/analytics.tsx +++ /dev/null @@ -1,473 +0,0 @@ -import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; -import { Link, useParams } from '@tanstack/react-router'; -import type { AttendeeStatus, StudentAtRiskDto } from '@gruperly/shared'; -import { - ArrowLeft, - CalendarCheck, - DoorOpen, - Loader2, - MessageCircle, - MoreVertical, - Pause, - Percent, - UserMinus, - Users, -} from 'lucide-react'; -import { useState, type ReactNode } from 'react'; -import { Avatar, Badge, Button, Modal, useToast } from '../components/ui'; -import { - getAttendeeHistory, - getGroupAnalytics, - getStudentsAtRisk, - updateAttendeeStatus, -} from '../lib/api'; -import { cn } from '../lib/utils'; - -type StatusAction = { student: StudentAtRiskDto; status: AttendeeStatus } | null; - -function KpiCard({ - icon, - label, - value, - hint, -}: { - icon: ReactNode; - label: string; - value: string; - hint?: string; -}) { - return ( -
    -
    - {icon} -
    -
    -

    {label}

    -

    {value}

    - {hint ?

    {hint}

    : null} -
    -
    - ); -} - -function statusLabel(status: string | null): string { - switch (status) { - case 'PRESENT': - return 'Presente'; - case 'ABSENT': - return 'Ausente'; - case 'EXCUSED': - return 'Avisó ausencia'; - default: - return 'Sin registrar'; - } -} - -function dotClass(status: string | null): string { - switch (status) { - case 'PRESENT': - return 'bg-success'; - case 'ABSENT': - return 'bg-danger'; - case 'EXCUSED': - return 'bg-warning'; - default: - return 'bg-border'; - } -} - -function formatSessionDate(iso: string): string { - return new Date(iso).toLocaleDateString('es-MX', { - weekday: 'short', - day: 'numeric', - month: 'short', - }); -} - -export function AnalyticsView() { - const { groupId } = useParams({ strict: false }) as { groupId: string }; - const queryClient = useQueryClient(); - const toast = useToast(); - - const [historyStudent, setHistoryStudent] = useState(null); - const [statusAction, setStatusAction] = useState(null); - const [menuOpenFor, setMenuOpenFor] = useState(null); - - const analyticsQuery = useQuery({ - queryKey: ['group-analytics', groupId], - queryFn: () => getGroupAnalytics(groupId), - enabled: Boolean(groupId), - }); - - const riskQuery = useQuery({ - queryKey: ['students-at-risk', groupId], - queryFn: () => getStudentsAtRisk(groupId), - enabled: Boolean(groupId), - }); - - const historyQuery = useQuery({ - queryKey: ['attendee-history', groupId, historyStudent?.attendeeId], - queryFn: () => getAttendeeHistory(groupId, historyStudent!.attendeeId!), - enabled: Boolean(groupId && historyStudent), - }); - - const statusMutation = useMutation({ - mutationFn: (action: Exclude) => - updateAttendeeStatus(action.student.attendeeId, action.status), - onSuccess: (_result, action) => { - const name = action.student.fullName.split(' ')[0]; - toast.success( - action.status === 'DROPPED' - ? `${name} fue dado de baja del grupo. Su vacante quedó disponible.` - : `La vacante de ${name} quedó pausada.`, - ); - setStatusAction(null); - void queryClient.invalidateQueries({ queryKey: ['students-at-risk', groupId] }); - void queryClient.invalidateQueries({ queryKey: ['group-attendees', groupId] }); - void queryClient.invalidateQueries({ queryKey: ['group', groupId] }); - void queryClient.invalidateQueries({ queryKey: ['classes-today'] }); - void queryClient.invalidateQueries({ queryKey: ['home-summary'] }); - void queryClient.invalidateQueries({ queryKey: ['groups-risk-overview'] }); - }, - onError: (err: Error) => { - toast.error(err.message || 'No pudimos actualizar el estado del alumno.'); - }, - }); - - const handleReengage = async (student: StudentAtRiskDto, groupName: string) => { - if (!student.phone) return; - const firstName = student.fullName.split(' ')[0] ?? student.fullName; - const message = - `¡Hola ${firstName}! 👋 Te extrañamos en ${groupName}. ` + - 'Notamos que no asististe a las últimas clases y queremos que vuelvas. ' + - 'Si tenés algún problema con tus horarios o tu membresía, escribinos y lo resolvemos juntos.'; - const waUrl = `https://wa.me/${student.phone.replace(/\D/g, '')}?text=${encodeURIComponent(message)}`; - try { - await navigator.clipboard.writeText(message); - toast.success('¡Abriendo WhatsApp! Mensaje copiado al portapapeles.'); - } catch { - // Si clipboard falla, igual abrimos WhatsApp con el mensaje. - } - window.open(waUrl, '_blank', 'noopener,noreferrer'); - }; - - const groupName = riskQuery.data?.groupName; - - if (analyticsQuery.isPending || riskQuery.isPending) { - return ( -
    - -
    - ); - } - - if (analyticsQuery.isError || riskQuery.isError || !analyticsQuery.data) { - return ( -
    -

    No pudimos cargar las estadísticas

    -

    Verificá tu conexión e intentá de nuevo.

    - -
    - ); - } - - const analytics = analyticsQuery.data; - const atRisk = riskQuery.data?.data ?? []; - - return ( -
    - - - Volver a {groupName ?? 'el grupo'} - - -
    -
    -

    Estadísticas

    -

    - Asistencia y gestión de riesgo de {groupName ?? 'tu grupo'}. -

    -
    - - Últimos 30 días - -
    - - {/* KPIs */} -
    - } - label="Asistencia promedio" - value={`${analytics.attendanceRate}%`} - hint="últimos 30 días" - /> - } - label="Asistencias del mes" - value={analytics.totalPresent.toLocaleString('es-MX')} - hint={`${analytics.totalClasses} clases dictadas`} - /> - } - label="Cupos recuperados" - value={analytics.recoveredSlots.toLocaleString('es-MX')} - hint="por ausencias avisadas" - /> -
    - - {/* Alumnos en riesgo */} -
    -
    - -

    Alumnos en riesgo

    - {atRisk.length > 0 ? ( - s.riskLevel === 'HIGH') ? 'danger' : 'warning'}> - {atRisk.length} {atRisk.length === 1 ? 'alumno' : 'alumnos'} - - ) : null} -
    -

    - Alumnos con ausencias consecutivas o baja asistencia mensual. -

    - - {atRisk.length === 0 ? ( -
    -

    ¡Sin alumnos en riesgo!

    -

    - No hay ausencias consecutivas ni asistencia por debajo del 50%. -

    -
    - ) : ( -
      - {atRisk.map((student) => ( -
    • -
      - - {student.riskLevel === 'HIGH' ? ( - - {student.consecutiveAbsences} faltas seguidas - - ) : ( - Baja asistencia - )} -
      - -
      - - -
      - - - {menuOpenFor === student.attendeeId ? ( - <> -
      setMenuOpenFor(null)} - aria-hidden="true" - /> -
      - - -
      - - ) : null} -
      -
      -
    • - ))} -
    - )} -
    - - {/* Modal: historial del alumno */} - setHistoryStudent(null)} - title={historyStudent?.fullName ?? 'Historial'} - description={historyStudent ? 'Historial de presentismo de las últimas clases.' : undefined} - maxWidth="md" - > - {historyStudent ? ( -
    - {historyQuery.isPending ? ( -
    - -
    - ) : historyQuery.isError || !historyQuery.data ? ( -
    - No pudimos cargar el historial de este alumno. -
    - ) : ( -
    -
    - - {historyQuery.data.attendanceRate}% - - - Presentismo general ({historyQuery.data.sessions.length} clases) - -
    - -
      - {historyQuery.data.sessions.map((session) => ( -
    • -
    • - ))} -
    -
    - )} -
    - ) : null} -
    - - {/* Modal: confirmar cambio de estado */} - setStatusAction(null)} - title={statusAction?.status === 'DROPPED' ? 'Dar de baja' : 'Pausar vacante'} - maxWidth="md" - > - {statusAction ? ( -
    -

    - {statusAction.student.fullName}{' '} - {statusAction.status === 'DROPPED' ? ( - <> - dejará de asistir al grupo y {groupName}. Su - vacante quedará disponible para otro alumno, y - su historial de asistencia se conservará. - - ) : ( - <> - será pausado en{' '} - {groupName}. Su vacante quedará{' '} - libre y podés reactivarla en cualquier - momento. - - )} -

    -
    - - -
    -
    - ) : null} -
    -
    - ); -} \ No newline at end of file diff --git a/apps/web/src/routes/auth/login.tsx b/apps/web/src/routes/auth/login.tsx deleted file mode 100644 index cb62413..0000000 --- a/apps/web/src/routes/auth/login.tsx +++ /dev/null @@ -1,113 +0,0 @@ -import { useForm } from 'react-hook-form' -import { z } from 'zod' -import { zodResolver } from '@hookform/resolvers/zod' -import { Link, useNavigate } from '@tanstack/react-router' -import { Fingerprint, Loader2 } from 'lucide-react' -import { authClient } from '../../lib/auth-client' -import { Button, Input, Label } from '../../components/ui' -import { AuthShell } from '../../components/auth' - -const schema = z.object({ - email: z.string().email('Ingresá un email válido'), - password: z.string().min(8, 'La contraseña debe tener al menos 8 caracteres'), -}) - -type FormValues = z.infer - -export function LoginPage() { - const navigate = useNavigate() - const { - register, - handleSubmit, - setError, - formState: { errors, isSubmitting }, - } = useForm({ resolver: zodResolver(schema) }) - - const onSubmit = handleSubmit(async ({ email, password }) => { - const { error } = await authClient.signIn.email({ email, password }) - if (error) { - setError('root', { message: error.message ?? 'No se pudo iniciar sesión' }) - return - } - navigate({ to: '/' }) - }) - - const handleGoogle = async () => { - await authClient.signIn.social({ provider: 'google', callbackURL: '/' }) - } - - const handlePasskey = async () => { - const { error, data } = await authClient.signIn.passkey() - if (error) { - setError('root', { message: error.message ?? 'No se pudo autenticar con passkey' }) - return - } - if (data) navigate({ to: '/' }) - } - - return ( - -
    -
    -
    - - - {errors.email ?

    {errors.email.message}

    : null} -
    - -
    - - - {errors.password ? ( -

    {errors.password.message}

    - ) : null} -
    - - {errors.root ?

    {errors.root.message}

    : null} - - -
    - -
    -
    - o -
    -
    - -
    - - -
    - -

    - ¿No tenés cuenta?{' '} - - Registrate - -

    -
    - - ) -} \ No newline at end of file diff --git a/apps/web/src/routes/auth/signup.tsx b/apps/web/src/routes/auth/signup.tsx deleted file mode 100644 index 939f02c..0000000 --- a/apps/web/src/routes/auth/signup.tsx +++ /dev/null @@ -1,142 +0,0 @@ -import { useForm } from 'react-hook-form' -import { z } from 'zod' -import { zodResolver } from '@hookform/resolvers/zod' -import { Link, useNavigate } from '@tanstack/react-router' -import { Loader2 } from 'lucide-react' -import { authClient } from '../../lib/auth-client' -import { Button, Input, Label } from '../../components/ui' -import { AuthShell } from '../../components/auth' - -const schema = z - .object({ - name: z.string().min(2, 'Ingresá tu nombre'), - email: z.string().email('Ingresá un email válido'), - password: z.string().min(8, 'La contraseña debe tener al menos 8 caracteres'), - confirmPassword: z.string(), - }) - .refine((v) => v.password === v.confirmPassword, { - message: 'Las contraseñas no coinciden', - path: ['confirmPassword'], - }) - -type FormValues = z.infer - -export function SignupPage() { - const navigate = useNavigate() - const { - register, - handleSubmit, - setError, - formState: { errors, isSubmitting }, - } = useForm({ resolver: zodResolver(schema) }) - - const onSubmit = handleSubmit(async ({ name, email, password }) => { - const { error, data } = await authClient.signUp.email( - { name, email, password }, - { - onSuccess: async () => { - await authClient.getSession() - }, - }, - ) - if (error) { - setError('root', { message: error.message ?? 'No se pudo registrar' }) - return - } - if (data?.token) { - // Con email verification activo, la sesión no se crea hasta verificar. - navigate({ to: '/verify-email', search: { email } }) - } - }) - - const handleGoogle = async () => { - await authClient.signIn.social({ provider: 'google', callbackURL: '/' }) - } - - return ( - -
    -
    -
    - - - {errors.name ?

    {errors.name.message}

    : null} -
    - -
    - - - {errors.email ?

    {errors.email.message}

    : null} -
    - -
    - - - {errors.password ? ( -

    {errors.password.message}

    - ) : null} -
    - -
    - - - {errors.confirmPassword ? ( -

    {errors.confirmPassword.message}

    - ) : null} -
    - - {errors.root ?

    {errors.root.message}

    : null} - - -
    - -
    -
    - o -
    -
    - - - -

    - ¿Ya tenés cuenta?{' '} - - Iniciá sesión - -

    -
    - - ) -} \ No newline at end of file diff --git a/apps/web/src/routes/auth/verify-email.tsx b/apps/web/src/routes/auth/verify-email.tsx deleted file mode 100644 index 3e1ba09..0000000 --- a/apps/web/src/routes/auth/verify-email.tsx +++ /dev/null @@ -1,91 +0,0 @@ -import { useEffect, useState } from 'react' -import { Link, useNavigate, useSearch } from '@tanstack/react-router' -import { MailCheck, MailWarning, Loader2 } from 'lucide-react' -import { authClient } from '../../lib/auth-client' -import { AuthShell } from '../../components/auth' - -type SearchParams = { - token?: string - email?: string -} - -type Status = 'idle' | 'verifying' | 'success' | 'error' - -export function VerifyEmailPage() { - const { token, email } = useSearch({ strict: false }) as SearchParams - const navigate = useNavigate() - const [status, setStatus] = useState(token ? 'verifying' : 'idle') - - useEffect(() => { - if (!token || status !== 'verifying') return - let cancelled = false - authClient - .verifyEmail({ query: { token } }) - .then(async ({ error }) => { - if (cancelled) return - if (error) { - setStatus('error') - return - } - await authClient.getSession() - navigate({ to: '/' }) - }) - .catch(() => { - if (!cancelled) setStatus('error') - }) - return () => { - cancelled = true - } - }, [token, status, navigate]) - - const title = - status === 'success' - ? 'Email verificado' - : status === 'error' - ? 'Vínculo inválido' - : 'Verificá tu email' - - return ( - -
    - {status === 'verifying' ? ( - - ) : status === 'success' ? ( - - ) : ( - - )} - - {status === 'success' ? ( -

    - Tu cuenta quedó verificada. Te estamos llevando a Gruperly… -

    - ) : status === 'error' ? ( -

    - El vínculo de verificación no es válido o expiró. -

    - ) : ( -

    - Te enviamos un correo a {email} para - confirmar tu cuenta. -

    - )} - - {status === 'success' ? ( - - Ir a Gruperly - - ) : null} - - {status === 'error' ? ( - - Intentar iniciar sesión - - ) : null} -
    -
    - ) -} \ No newline at end of file diff --git a/apps/web/src/routes/class-attendance.tsx b/apps/web/src/routes/class-attendance.tsx deleted file mode 100644 index a29af96..0000000 --- a/apps/web/src/routes/class-attendance.tsx +++ /dev/null @@ -1,259 +0,0 @@ -import { useEffect, useMemo, useState } from 'react' -import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' -import { Link, useParams } from '@tanstack/react-router' -import type { SessionStudentDto } from '@gruperly/shared' -import { ArrowLeft, Check, Loader2, X } from 'lucide-react' -import { Avatar, Badge, Button, useToast } from '../components/ui' -import { getSessionStudents, markAttendance } from '../lib/api' -import { cn } from '../lib/utils' - -type AttendanceChoice = 'PRESENT' | 'ABSENT' - -function isLocked(student: SessionStudentDto): boolean { - return student.notifiedAbsence || student.attendanceStatus === 'EXCUSED' -} - -function PaymentBadge({ status }: { status: SessionStudentDto['paymentStatus'] }) { - return status === 'UP_TO_DATE' ? ( - Al día - ) : ( - Pendiente - ) -} - -function AttendanceToggle({ - choice, - disabled, - onToggle, - fullName, -}: { - choice: AttendanceChoice - disabled?: boolean - onToggle: () => void - fullName: string -}) { - const isPresent = choice === 'PRESENT' - - return ( - - ) -} - -function StudentRow({ - student, - choice, - onToggle, -}: { - student: SessionStudentDto - choice: AttendanceChoice - onToggle: () => void -}) { - const locked = isLocked(student) - - return ( -
  • - -
    -

    {student.fullName}

    -
    - - {locked ? Avisó ausencia : null} -
    -
    - -
  • - ) -} - -export function ClassAttendanceView() { - const { sessionId } = useParams({ strict: false }) as { sessionId: string } - const queryClient = useQueryClient() - const toast = useToast() - - const studentsQuery = useQuery({ - queryKey: ['class-students', sessionId], - queryFn: () => getSessionStudents(sessionId), - staleTime: 0, - }) - - const students = studentsQuery.data?.students - - // Estado local de la toma: todos parten PRESENT (1-tap para marcar ausentes). - // Alumnas con ausencia avisada quedan bloqueadas en EXCUSED. - const [choices, setChoices] = useState>({}) - - useEffect(() => { - if (!students) return - const initial: Record = {} - for (const student of students) { - if (isLocked(student)) continue - initial[student.attendeeId] = student.attendanceStatus === 'ABSENT' ? 'ABSENT' : 'PRESENT' - } - setChoices(initial) - }, [students]) - - const presentCount = useMemo( - () => - (students ?? []).filter( - (student) => !isLocked(student) && choices[student.attendeeId] === 'PRESENT', - ).length, - [students, choices], - ) - - const toggleStudent = (attendeeId: string) => { - setChoices((prev) => ({ - ...prev, - [attendeeId]: prev[attendeeId] === 'ABSENT' ? 'PRESENT' : 'ABSENT', - })) - } - - const saveMutation = useMutation({ - mutationFn: () => { - const records = (students ?? []) - .filter((student) => !isLocked(student)) - .map((student) => ({ - attendeeId: student.attendeeId, - status: choices[student.attendeeId] ?? 'PRESENT', - })) - return markAttendance(sessionId, { classSessionId: sessionId, records }) - }, - onSuccess: () => { - toast.success('Asistencia guardada correctamente.', 'Listo') - void queryClient.invalidateQueries({ queryKey: ['classes-today'] }) - void queryClient.invalidateQueries({ queryKey: ['class-students', sessionId] }) - }, - onError: (error: Error) => { - toast.error(error.message || 'No pudimos guardar la asistencia.') - }, - }) - - const sessionInfo = studentsQuery.data - const startTime = sessionInfo - ? new Date(sessionInfo.startsAt).toLocaleTimeString('es-MX', { - hour: '2-digit', - minute: '2-digit', - hour12: false, - }) - : null - - return ( -
    - - - Volver al inicio - - - {studentsQuery.isPending ? ( -
    - -
    - ) : null} - - {studentsQuery.isError ? ( -
    -

    No pudimos cargar la lista de alumnos.

    - -
    - ) : null} - - {sessionInfo ? ( - <> -
    -
    -
    -

    - {sessionInfo.groupName} -

    -

    - {startTime ? `Hoy · ${startTime} hs` : 'Clase de hoy'} -

    -
    - - {presentCount}/{sessionInfo.students.length} presentes - -
    -
    - - {sessionInfo.students.length === 0 ? ( -
    -

    Este grupo no tiene alumnos

    -

    - Agregá miembros desde la ficha del grupo para tomar asistencia. -

    -
    - ) : ( -
      - {sessionInfo.students.map((student) => ( - toggleStudent(student.attendeeId)} - /> - ))} -
    - )} - - {sessionInfo.students.length > 0 ? ( -
    - -
    - ) : null} - - ) : null} -
    - ) -} diff --git a/apps/web/src/routes/create-group.tsx b/apps/web/src/routes/create-group.tsx deleted file mode 100644 index 4af6940..0000000 --- a/apps/web/src/routes/create-group.tsx +++ /dev/null @@ -1,39 +0,0 @@ -import { useMutation, useQueryClient } from '@tanstack/react-query' -import { useNavigate, Link } from '@tanstack/react-router' -import type { CreateFirstGroup } from '@gruperly/shared' -import { ChevronLeft } from 'lucide-react' -import { GroupForm } from '../components/groups/GroupForm' -import { createGroup } from '../lib/api' - -export function CreateGroupView() { - const navigate = useNavigate() - const queryClient = useQueryClient() - - const create = useMutation({ - mutationFn: (values: CreateFirstGroup) => createGroup(values), - onSuccess: (result) => { - void queryClient.invalidateQueries({ queryKey: ['groups'] }) - void navigate({ to: '/groups/$groupId', params: { groupId: result.group.id } }) - }, - }) - - return ( -
    - - - Grupos - - - create.mutate(values)} - /> -
    - ) -} \ No newline at end of file diff --git a/apps/web/src/routes/group-detail.tsx b/apps/web/src/routes/group-detail.tsx deleted file mode 100644 index 7616bb3..0000000 --- a/apps/web/src/routes/group-detail.tsx +++ /dev/null @@ -1,1680 +0,0 @@ -import { useState, useRef, type ReactNode } from 'react'; -import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'; -import { useParams, useNavigate, Link } from '@tanstack/react-router'; -import type { - AttendeeDto, - CreateAttendee, - CreateAttendeeResult, - CreateGroupWaitlistEntry, - GroupWaitlistEntryDto, - GroupWaitlistList, -} from '@gruperly/shared'; -import { - ArrowLeft, - BarChart3, - CalendarClock, - Check, - ChevronRight, - Clock, - Copy, - Download, - FileSpreadsheet, - Loader2, - Mail, - MessageCircle, - Phone, - Plus, - RefreshCw, - Search, - Share2, - ShieldCheck, - StickyNote, - Trash2, - UploadCloud, - UserCheck, - UserMinus, - UserPlus, - Users, -} from 'lucide-react'; -import { Badge, Button, Input, Label, Modal, useToast } from '../components/ui'; -import { - addToGroupWaitlist, - ApiError, - bulkCreateAttendees, - createAttendee, - getGroup, - getGroupAttendees, - getGroupsRiskOverview, - getGroupWaitlist, - getInviteToken, - promoteGroupWaitlistEntry, - removeGroupAttendee, - removeGroupWaitlistEntry, -} from '../lib/api'; -import { - downloadAttendeeTemplateCsv, - normalizeRowsToContacts, - parseCsvContent, - parseXlsxContent, - type ParsedContactRow, -} from '../lib/file-parser'; -import { BILLING_LABELS, formatPrice, formatSchedule } from '../lib/format'; - -export function GroupDetailView() { - const { groupId } = useParams({ strict: false }) as { groupId: string }; - const navigate = useNavigate(); - const queryClient = useQueryClient(); - const toast = useToast(); - - // Modals & Tabs - const [isInviteModalOpen, setIsInviteModalOpen] = useState(false); - const [isAddAttendeeModalOpen, setIsAddAttendeeModalOpen] = useState(false); - const [selectedAttendee, setSelectedAttendee] = useState(null); - const absenceNotifyUrl = selectedAttendee?.notifyToken - ? `${window.location.origin}/avisar-ausencia/${selectedAttendee.notifyToken}` - : null; - const [activeTab, setActiveTab] = useState<'quick' | 'bulk'>('quick'); - const [listSection, setListSection] = useState<'members' | 'waitlist'>('members'); - const [attendeeToRemove, setAttendeeToRemove] = useState(null); - const [selectedWaitlistEntry, setSelectedWaitlistEntry] = useState(null); - - // Quick form state - const [firstName, setFirstName] = useState(''); - const [lastName, setLastName] = useState(''); - const [phone, setPhone] = useState(''); - const [email, setEmail] = useState(''); - const [notes, setNotes] = useState(''); - - // Bulk upload state - const [parsedContacts, setParsedContacts] = useState([]); - const [fileName, setFileName] = useState(null); - const [isParsingFile, setIsParsingFile] = useState(false); - const [isDragging, setIsDragging] = useState(false); - const fileInputRef = useRef(null); - - // Capacity & waitlist state - const [isCapacityModalOpen, setIsCapacityModalOpen] = useState(false); - const [pendingCapacityPayload, setPendingCapacityPayload] = useState(null); - const [isBulkCapacityModalOpen, setIsBulkCapacityModalOpen] = useState(false); - - // Attendees search filter - const [searchFilter, setSearchFilter] = useState(''); - - // Queries - const groupQuery = useQuery({ - queryKey: ['group', groupId], - queryFn: () => getGroup(groupId), - enabled: Boolean(groupId), - }); - - const riskOverviewQuery = useQuery({ - queryKey: ['groups-risk-overview'], - queryFn: getGroupsRiskOverview, - enabled: Boolean(groupId), - }); - - const inviteTokenQuery = useQuery({ - queryKey: ['invite-token', groupId], - queryFn: () => getInviteToken(groupId), - enabled: Boolean(groupId) && isInviteModalOpen, - }); - - const attendeesQuery = useQuery({ - queryKey: ['group-attendees', groupId], - queryFn: () => getGroupAttendees(groupId, 1, 100), - enabled: Boolean(groupId), - }); - - const waitlistQuery = useQuery({ - queryKey: ['group-waitlist', groupId], - queryFn: () => getGroupWaitlist(groupId, 1, 100), - enabled: Boolean(groupId), - }); - - // Regenerate invite token mutation - const regenerateTokenMutation = useMutation({ - mutationFn: () => getInviteToken(groupId, true), - onSuccess: (data) => { - queryClient.setQueryData(['invite-token', groupId], data); - toast.success('Se generó un nuevo enlace de invitación.'); - }, - onError: () => { - toast.error('No se pudo regenerar el enlace de invitación.'); - }, - }); - - // Quick add attendee mutation - const resetQuickForm = () => { - setFirstName(''); - setLastName(''); - setPhone(''); - setEmail(''); - setNotes(''); - }; - - const closeAddAttendeeFlow = () => { - resetQuickForm(); - setPendingCapacityPayload(null); - setIsCapacityModalOpen(false); - setIsAddAttendeeModalOpen(false); - }; - - const handleCreateSuccess = (result: CreateAttendeeResult) => { - if (result.outcome === 'created') { - toast.success(`Miembro ${result.attendee.fullName} agregado con éxito.`); - } else { - toast.info(result.message); - } - queryClient.invalidateQueries({ queryKey: ['group-attendees', groupId] }); - closeAddAttendeeFlow(); - }; - - const createAttendeeMutation = useMutation({ - mutationFn: (payload: CreateAttendee) => createAttendee(groupId, payload), - onMutate: (payload) => setPendingCapacityPayload(payload), - onSuccess: handleCreateSuccess, - onError: (err: Error) => { - if (err instanceof ApiError && err.problem?.code === 'group_capacity_reached') { - setIsCapacityModalOpen(true); - return; - } - toast.error(err.message || 'Error al agregar miembro.'); - }, - }); - - // Force add (owner overrides the full capacity) - const createAttendeeForceMutation = useMutation({ - mutationFn: (payload: CreateAttendee) => createAttendee(groupId, payload, { allowOverflow: true }), - onSuccess: handleCreateSuccess, - onError: (err: Error) => { - toast.error(err.message || 'Error al agregar miembro.'); - }, - }); - - // Add to group waitlist - const addToWaitlistMutation = useMutation({ - mutationFn: (payload: CreateGroupWaitlistEntry) => addToGroupWaitlist(groupId, payload), - onMutate: async (payload: CreateGroupWaitlistEntry) => { - await queryClient.cancelQueries({ queryKey: ['group-waitlist', groupId] }); - const previousWaitlist = queryClient.getQueryData(['group-waitlist', groupId]); - - if (previousWaitlist) { - const optimisticEntry: GroupWaitlistEntryDto = { - id: `temp-${Date.now()}`, - groupId, - fullName: `${payload.firstName} ${payload.lastName ?? ''}`.trim(), - phone: payload.phone, - email: payload.email || null, - notes: payload.notes ?? null, - status: 'PENDING', - createdAt: new Date().toISOString(), - updatedAt: new Date().toISOString(), - }; - queryClient.setQueryData(['group-waitlist', groupId], { - data: [optimisticEntry, ...previousWaitlist.data], - pagination: { - ...previousWaitlist.pagination, - total: previousWaitlist.pagination.total + 1, - }, - }); - } - - return { previousWaitlist }; - }, - onSuccess: (entry) => { - toast.info(`${entry.fullName} fue agregado a la lista de espera del grupo.`); - queryClient.invalidateQueries({ queryKey: ['group-waitlist', groupId] }); - queryClient.invalidateQueries({ queryKey: ['group', groupId] }); - closeAddAttendeeFlow(); - }, - onError: (err: Error, _payload, context) => { - if (context?.previousWaitlist) { - queryClient.setQueryData(['group-waitlist', groupId], context.previousWaitlist); - } - if (err instanceof ApiError && err.problem?.code === 'already_waitlisted') { - toast.info('Este número ya está en la lista de espera del grupo.'); - } else { - toast.error(err.message || 'Error al agregar a la lista de espera.'); - } - setPendingCapacityPayload(null); - setIsCapacityModalOpen(false); - }, - }); - - // Bulk import mutation - const bulkImportMutation = useMutation({ - mutationFn: (attendees: Array<{ firstName: string; lastName: string; fullName: string; phone: string; email?: string; notes?: string }>) => - bulkCreateAttendees(groupId, { attendees }), - onSuccess: (res) => { - toast.success(res.message); - queryClient.invalidateQueries({ queryKey: ['group-attendees', groupId] }); - setParsedContacts([]); - setFileName(null); - setIsAddAttendeeModalOpen(false); - }, - onError: (err: Error) => { - toast.error(err.message || 'Error al importar miembros.'); - }, - }); - - // Waitlist & removal mutations - const invalidateGroupQueries = () => { - queryClient.invalidateQueries({ queryKey: ['group-attendees', groupId] }); - queryClient.invalidateQueries({ queryKey: ['group-waitlist', groupId] }); - queryClient.invalidateQueries({ queryKey: ['group', groupId] }); - }; - - const removeAttendeeMutation = useMutation({ - mutationFn: (payload: { attendeeId: string; promoteFromWaitlist: boolean }) => - removeGroupAttendee(groupId, payload.attendeeId, { promoteFromWaitlist: payload.promoteFromWaitlist }), - 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({ - mutationFn: (entryId: string) => promoteGroupWaitlistEntry(groupId, entryId), - onSuccess: (result) => { - toast.success(`${result.attendee.fullName} pasó de la lista de espera al grupo.`); - invalidateGroupQueries(); - }, - onError: (err: Error) => { - if (err instanceof ApiError && err.problem?.code === 'group_capacity_reached') { - toast.error('El grupo alcanzó su cupo. Quita un miembro o aumenta el cupo primero.'); - } else { - toast.error(err.message || 'No se pudo pasar al miembro al grupo.'); - } - }, - }); - - const removeWaitlistEntryMutation = useMutation({ - mutationFn: (entry: GroupWaitlistEntryDto) => removeGroupWaitlistEntry(groupId, entry.id), - onSuccess: (_result, entry) => { - toast.success(`${entry.fullName} fue quitado de la lista de espera.`); - invalidateGroupQueries(); - }, - onError: (err: Error) => { - toast.error(err.message || 'No se pudo quitar de la lista de espera.'); - }, - }); - - const handleCopyLink = async () => { - const url = inviteTokenQuery.data?.inviteUrl; - if (!url) return; - try { - await navigator.clipboard.writeText(url); - toast.success('¡Enlace de invitación copiado al portapapeles!'); - } catch { - toast.error('No se pudo copiar automáticamente. Copia el texto manualmente.'); - } - }; - - const handleCopyMessage = async () => { - if (!whatsappMessage) return; - try { - await navigator.clipboard.writeText(whatsappMessage); - toast.success('¡Mensaje copiado al portapapeles!'); - } catch { - toast.error('No se pudo copiar automáticamente. Copia el texto manualmente.'); - } - }; - - const handleOpenWhatsApp = async () => { - if (!whatsappShareUrl) return; - try { - if (whatsappMessage) { - await navigator.clipboard.writeText(whatsappMessage); - toast.success('¡Abriendo WhatsApp! Mensaje copiado al portapapeles.'); - } - } catch { - // Ignorar si clipboard falla - } - window.open(whatsappShareUrl, '_blank', 'noopener,noreferrer'); - }; - - const handleQuickSubmit = (e: React.FormEvent) => { - e.preventDefault(); - if (!firstName.trim() || !phone.trim()) { - toast.error('Nombre y teléfono son obligatorios.'); - return; - } - createAttendeeMutation.mutate({ - firstName: firstName.trim(), - lastName: lastName.trim(), - phone: phone.trim(), - email: email.trim() || undefined, - notes: notes.trim() || undefined, - }); - }; - - const processFile = async (file: File) => { - setIsParsingFile(true); - setFileName(file.name); - try { - let rawRows: string[][] = []; - const lower = file.name.toLowerCase(); - - if (lower.endsWith('.csv') || lower.endsWith('.txt')) { - const text = await file.text(); - rawRows = parseCsvContent(text); - } else if (lower.endsWith('.xlsx') || lower.endsWith('.xls')) { - const buffer = await file.arrayBuffer(); - rawRows = await parseXlsxContent(buffer); - } else { - toast.error('Formato no compatible. Sube un archivo .csv o .xlsx'); - setIsParsingFile(false); - return; - } - - const contacts = normalizeRowsToContacts(rawRows); - if (contacts.length === 0) { - toast.error('No se detectaron contactos en el archivo.'); - } else { - setParsedContacts(contacts); - const validCount = contacts.filter((c) => c.isValid).length; - toast.info(`Se detectaron ${contacts.length} filas (${validCount} válidas).`); - } - } catch (err: unknown) { - const message = err instanceof Error ? err.message : 'Error al procesar el archivo.'; - toast.error(message); - } finally { - setIsParsingFile(false); - } - }; - - const handleFileDrop = (e: React.DragEvent) => { - e.preventDefault(); - setIsDragging(false); - if (e.dataTransfer.files && e.dataTransfer.files.length > 0) { - void processFile(e.dataTransfer.files[0]); - } - }; - - const handleFileSelect = (e: React.ChangeEvent) => { - if (e.target.files && e.target.files.length > 0) { - void processFile(e.target.files[0]); - } - }; - - const removeContactRow = (id: string) => { - setParsedContacts((prev) => prev.filter((c) => c.id !== id)); - }; - - const doBulkImport = () => { - const validRows = parsedContacts.filter((c) => c.isValid); - if (validRows.length === 0) { - toast.error('No hay miembros válidos para importar.'); - return; - } - bulkImportMutation.mutate( - validRows.map((c) => ({ - firstName: c.firstName, - lastName: c.lastName, - fullName: c.fullName, - phone: c.phone, - email: c.email || undefined, - notes: c.notes || undefined, - })), - ); - }; - - const handleConfirmBulkImport = () => { - if (validRowsCount === 0) { - toast.error('No hay miembros válidos para importar.'); - return; - } - if (group?.capacity != null && attendeesTotal + validRowsCount > group.capacity) { - setIsBulkCapacityModalOpen(true); - return; - } - doBulkImport(); - }; - - const group = groupQuery.data; - const attendees = attendeesQuery.data?.data ?? []; - const attendeesTotal = attendeesQuery.data?.pagination?.total ?? attendees.length; - const waitlistEntries = waitlistQuery.data?.data ?? []; - const waitlistTotal = waitlistQuery.data?.pagination?.total ?? waitlistEntries.length; - const firstWaitlistEntry = waitlistEntries[0] ?? null; - const hasFreeCapacity = group?.capacity == null || attendeesTotal < group.capacity; - const filteredAttendees = attendees.filter((a) => { - const q = searchFilter.toLowerCase(); - return ( - a.fullName.toLowerCase().includes(q) || - (a.phone && a.phone.includes(q)) || - (a.email && a.email.toLowerCase().includes(q)) - ); - }); - - const validRowsCount = parsedContacts.filter((c) => c.isValid).length; - const invalidRowsCount = parsedContacts.length - validRowsCount; - - const whatsappMessage = - group && inviteTokenQuery.data?.inviteUrl - ? `¡Hola! 👋 Te invito a unirte al grupo *${group.name}*.\n\nCompleta tus datos de inscripción en el siguiente enlace:\n${inviteTokenQuery.data.inviteUrl}` - : ''; - - const whatsappShareUrl = whatsappMessage - ? `https://wa.me/?text=${encodeURIComponent(whatsappMessage)}` - : ''; - - if (groupQuery.isPending) { - return ( -
    - -
    - ); - } - - if (groupQuery.isError || !group) { - return ( -
    -

    Grupo no encontrado

    -

    No se pudo cargar la información de este grupo.

    - -
    - ); - } - - const riskLevel = - riskOverviewQuery.data?.items.find((item) => item.groupId === groupId)?.riskLevel ?? 'NONE'; - - return ( -
    - {/* Navigation & Header */} -
    - - - Volver a grupos - - -
    -
    -
    -

    {group.name}

    - Activo - {riskLevel === 'HIGH' || riskLevel === 'MEDIUM' ? ( - - - ) : null} -
    - {group.description ? ( -

    {group.description}

    - ) : null} -
    - -
    - - - -
    -
    -
    - - {/* Group Details Card */} -
    -
    - -
    -

    Horario

    -

    - {(group.days?.length ?? 0) > 0 ? formatSchedule(group.days ?? [], group.time) : 'Sin horario definido'} -

    -
    -
    - -
    - -
    -

    Miembros & Cupo

    -

    - {attendees.length} inscritos {waitlistTotal > 0 ? ` · ${waitlistTotal} en espera` : ''} - {group.capacity ? ` · Cupo de ${group.capacity}` : ''} -

    -
    -
    - -
    -
    - $ -
    -
    -

    Cobro

    -

    - {group.price != null ? formatPrice(group.price) : 'Sin precio'} - {group.billingType ? ` · ${BILLING_LABELS[group.billingType]}` : ''} - {group.dueDay ? ` · Vence día ${group.dueDay}` : ''} -

    -
    -
    -
    - - {/* Miembros & Lista de espera */} -
    -
    -
    -
    - - -
    - - {listSection === 'members' ? ( -
    - - setSearchFilter(e.target.value)} - className="pl-9 h-9 text-xs" - /> -
    - ) : null} -
    - -

    - {listSection === 'members' - ? 'Listado de todos los miembros incorporados al grupo.' - : 'Personas que esperan un cupo libre en el grupo. Al pasar a alguien al grupo, se crea automáticamente su registro como miembro.'} -

    -
    - - {listSection === 'members' ? ( - <> - {attendeesQuery.isPending ? ( -
    - -
    - ) : null} - - {attendeesQuery.isSuccess && attendees.length === 0 ? ( -
    - -

    Todavía no hay miembros en este grupo

    -

    - Puedes compartir el enlace de invitación único o agregar miembros de forma manual o masiva. -

    -
    - - -
    -
    - ) : null} - - {attendeesQuery.isSuccess && attendees.length > 0 && filteredAttendees.length === 0 ? ( -
    - No se encontraron miembros que coincidan con la búsqueda. -
    - ) : null} - - {filteredAttendees.length > 0 ? ( -
    - - - - - - - - - {filteredAttendees.map((attendee) => ( - setSelectedAttendee(attendee)} - > - - - - - ))} - -
    NombreTeléfono -
    -
    -
    - {attendee.fullName.charAt(0).toUpperCase()} -
    - {attendee.fullName} -
    -
    - {attendee.phone || —} - - -
    -
    - ) : null} - - ) : ( -
    - {waitlistQuery.isPending ? ( -
    - -
    - ) : null} - - {waitlistQuery.isSuccess && waitlistEntries.length === 0 ? ( -
    - -

    No hay nadie en la lista de espera

    -

    - Cuando el grupo alcance su cupo, las personas podrán sumarse a la espera y podrás pasarlas al grupo desde aquí. -

    -
    - ) : null} - - {waitlistEntries.length > 0 ? ( -
    - - - - - - - - - {waitlistEntries.map((entry) => ( - setSelectedWaitlistEntry(entry)} - > - - - - - ))} - -
    NombreTeléfono -
    -
    -
    - {entry.fullName.charAt(0).toUpperCase()} -
    -
    -

    {entry.fullName}

    - {entry.notes ? ( -

    {entry.notes}

    - ) : null} -
    -
    -
    - {entry.phone} - - -
    -
    - ) : null} -
    - )} -
    - - {/* MODAL: COMPARTIR LINK DE INVITACION */} - setIsInviteModalOpen(false)} - title="Compartir Link de Invitación" - description="Envía este enlace a tus miembros para que completen sus datos e ingresen directamente al grupo." - maxWidth="md" - > -
    - {inviteTokenQuery.isPending ? ( -
    - -
    - ) : ( - <> -
    - -
    - - -
    -
    - -
    -
    -

    Vista previa del mensaje para WhatsApp:

    - -
    -
    - {`¡Hola! 👋 Te invito a unirte al grupo `} - {group.name}. - {'\n\n'} - Completa tus datos de inscripción en el siguiente enlace: - {'\n'} - - {inviteTokenQuery.data?.inviteUrl} - -
    -
    - -
    - - - -
    - -

    - 💡 Al hacer clic en Abrir en WhatsApp, el mensaje completo se copia automáticamente al portapapeles. Si WhatsApp Web solo carga el enlace, puedes pegarlo directamente con Ctrl+V o Cmd+V. -

    - - )} -
    -
    - - {/* MODAL: AGREGAR ALUMNOS (CARGA INDIVIDUAL / MASIVA) */} - setIsAddAttendeeModalOpen(false)} - title="Agregar Miembros al Grupo" - description="Agrega miembros rápidamente completando sus datos o importa una lista de contactos." - maxWidth="lg" - > -
    - {/* Tabs Selector */} -
    - - -
    - - {/* TAB 1: CARGA RAPIDA */} - {activeTab === 'quick' ? ( -
    -
    -
    - - setFirstName(e.target.value)} - required - /> -
    -
    - - setLastName(e.target.value)} - /> -
    -
    - -
    - - setPhone(e.target.value)} - required - /> -

    - Usado para contacto y validación de duplicados. -

    -
    - -
    - - setEmail(e.target.value)} - /> -
    - -
    - - setNotes(e.target.value)} - /> -
    - -
    - - -
    -
    - ) : null} - - {/* TAB 2: CARGA MASIVA */} - {activeTab === 'bulk' ? ( -
    - {/* Dropzone */} -
    { - e.preventDefault(); - setIsDragging(true); - }} - onDragLeave={() => setIsDragging(false)} - onDrop={handleFileDrop} - onClick={() => fileInputRef.current?.click()} - className={`relative flex flex-col items-center justify-center p-6 rounded-xl border-2 border-dashed cursor-pointer transition-all ${ - isDragging - ? 'border-accent bg-accent/5' - : 'border-border hover:border-accent/60 bg-primary-soft/30' - }`} - > - - -

    - Arrastra tu archivo aquí o haz clic para seleccionarlo -

    -

    - Formatos soportados: CSV (.csv) o Excel (.xlsx) -

    - - {fileName ? ( -
    - - {fileName} -
    - ) : null} -
    - - {/* Template Download Link */} -
    - - ¿No tienes el archivo listo? Usa nuestra plantilla. - - -
    - - {isParsingFile ? ( -
    - - Leyendo y analizando archivo... -
    - ) : null} - - {/* Interactive Preview Table */} - {parsedContacts.length > 0 ? ( -
    -
    -
    - Vista Previa: - {validRowsCount} listos para importar - {invalidRowsCount > 0 ? ( - {invalidRowsCount} con errores - ) : null} -
    - - -
    - -
    - - - - - - - - - - - - {parsedContacts.map((c) => ( - - - - - - - - ))} - -
    NombreTeléfonoEmailEstado
    - {c.fullName || Sin nombre} - - {c.phone || Sin teléfono} - - {c.email || '—'} - - {c.isValid ? ( - Válido - ) : ( - - {c.error} - - )} - - -
    -
    - -
    - - -
    -
    - ) : null} -
    - ) : null} -
    -
    - - {/* MODAL: CUPO ALCANZADO (ALTA INDIVIDUAL) */} - { - setPendingCapacityPayload(null); - setIsCapacityModalOpen(false); - }} - title="Cupo alcanzado" - description="El grupo llegó a su cupo máximo de miembros." - maxWidth="md" - > - {pendingCapacityPayload ? ( -
    -

    - El grupo {group.name} ya alcanzó su cupo de{' '} - {group.capacity} miembros. ¿Qué deseas hacer con{' '} - - {`${pendingCapacityPayload.firstName.trim()} ${pendingCapacityPayload.lastName.trim()}`.trim()} - - ? -

    -
    - - -
    -

    - Si eliges agregarlo de todos modos, el grupo quedará por encima de su cupo. -

    -
    - ) : null} -
    - - {/* MODAL: AVISO DE CUPO EN CARGA MASIVA */} - setIsBulkCapacityModalOpen(false)} - title="Aviso de cupo" - description="La carga supera el cupo del grupo." - maxWidth="md" - > -
    -

    - Estás por importar {validRowsCount} miembro(s), pero el grupo ya - tiene {attendeesTotal} inscrito(s) y su cupo es de{' '} - {group.capacity}. ¿Deseas importarlos de todos modos? -

    -
    - - -
    -
    -
    - - {/* MODAL: DETALLE DEL PARTICIPANTE */} - setSelectedAttendee(null)} - title="Detalle del Participante" - maxWidth="sm" - > - {selectedAttendee ? ( -
    - {/* Header: avatar + name */} -
    -
    - {selectedAttendee.fullName.charAt(0).toUpperCase()} -
    -
    -

    - {selectedAttendee.fullName} -

    -

    - Incorporado el{' '} - {new Date(selectedAttendee.createdAt).toLocaleDateString('es-ES', { - day: 'numeric', - month: 'long', - year: 'numeric', - })} -

    -
    -
    - - {/* Info rows */} -
    - } - label="Teléfono" - > - {selectedAttendee.phone ? ( -
    - {selectedAttendee.phone} - e.stopPropagation()} - > - - WhatsApp - -
    - ) : ( - Sin teléfono - )} -
    - - } - label="Email" - > - {selectedAttendee.email ? ( - e.stopPropagation()} - > - {selectedAttendee.email} - - ) : ( - Sin email - )} - - - {(selectedAttendee.guardianName || selectedAttendee.guardianPhone) ? ( - <> - } - label="Responsable" - > - - {selectedAttendee.guardianName || —} - - - {selectedAttendee.guardianPhone ? ( - } - label="Tel. Responsable" - > -
    - {selectedAttendee.guardianPhone} - e.stopPropagation()} - > - - -
    -
    - ) : null} - - ) : null} - - } - label="Notas" - > - {selectedAttendee.notes ? ( - {selectedAttendee.notes} - ) : ( - Sin notas - )} - -
    - - {absenceNotifyUrl ? ( -
    -

    - Link para avisar ausencias -

    -
    - - {absenceNotifyUrl} - - -
    - {selectedAttendee.phone ? ( - - - Enviar por WhatsApp - - ) : null} -
    - ) : null} - -
    - -
    -
    - ) : null} -
    - {/* MODAL: CONFIRMAR QUITAR MIEMBRO */} - setAttendeeToRemove(null)} - title="Quitar del grupo" - maxWidth="md" - > - {attendeeToRemove ? ( -
    -

    - {attendeeToRemove.fullName} dejará de ser miembro del grupo{' '} - {group.name} - {firstWaitlistEntry ? ' y el cupo quedará libre.' : '.'} - {attendeeToRemove.phone ? ( - - Teléfono: {attendeeToRemove.phone} - - ) : null} -

    - - {firstWaitlistEntry ? ( -
    -
    - - - Hay {waitlistTotal} persona{waitlistTotal === 1 ? '' : 's'} esperando un cupo - -
    -

    - ¿Quieres pasar a{' '} - {firstWaitlistEntry.fullName}, el primero de - la lista de espera, al grupo? -

    -
    - - -
    -
    - ) : ( -
    - - -
    - )} -
    - ) : null} -
    - {/* MODAL: DETALLE LISTA DE ESPERA */} - setSelectedWaitlistEntry(null)} - title="Detalle de la lista de espera" - maxWidth="sm" - > - {selectedWaitlistEntry ? ( -
    - {/* Header: avatar + name */} -
    -
    - {selectedWaitlistEntry.fullName.charAt(0).toUpperCase()} -
    -
    -

    - {selectedWaitlistEntry.fullName} -

    -

    - En espera desde el{' '} - {new Date(selectedWaitlistEntry.createdAt).toLocaleDateString('es-ES', { - day: 'numeric', - month: 'long', - year: 'numeric', - })} -

    -
    -
    - - {/* Info rows */} -
    - } label="Teléfono"> - {selectedWaitlistEntry.phone ? ( -
    - {selectedWaitlistEntry.phone} - e.stopPropagation()} - > - - WhatsApp - -
    - ) : ( - Sin teléfono - )} -
    - - {selectedWaitlistEntry.email ? ( - } label="Email"> - e.stopPropagation()} - > - {selectedWaitlistEntry.email} - - - ) : null} - - } label="Notas"> - {selectedWaitlistEntry.notes ? ( - - {selectedWaitlistEntry.notes} - - ) : ( - Sin notas - )} - -
    - - {/* Footer: status + actions */} - {!hasFreeCapacity ? ( -

    - El grupo alcanzó su cupo de miembros. Quita un miembro o aumenta el cupo para poder pasar - a esta persona al grupo. -

    - ) : null} -
    - - -
    -
    - ) : null} -
    -
    - ); -} - -function DetailRow({ icon, label, children }: { icon: ReactNode; label: string; children: ReactNode }) { - return ( -
    -
    {icon}
    -
    -

    - {label} -

    -
    {children}
    -
    -
    - ); -} diff --git a/apps/web/src/routes/groups.tsx b/apps/web/src/routes/groups.tsx deleted file mode 100644 index 0087786..0000000 --- a/apps/web/src/routes/groups.tsx +++ /dev/null @@ -1,159 +0,0 @@ -import { useQuery } from '@tanstack/react-query' -import { useNavigate } from '@tanstack/react-router' -import { CalendarClock, Loader2, Plus, Users } from 'lucide-react' -import type { GroupDto, GroupRiskLevel } from '@gruperly/shared' -import { Badge, Button } from '../components/ui' -import { getGroups, getGroupsRiskOverview } from '../lib/api' -import { BILLING_LABELS, formatPrice, formatSchedule } from '../lib/format' -import { cn } from '../lib/utils' - -const RISK_LABELS: Record, string> = { - HIGH: 'Riesgo alto', - MEDIUM: 'Riesgo moderado', -} - -function GroupCard({ - group, - riskLevel, -}: { - group: GroupDto - riskLevel: GroupRiskLevel -}) { - const navigate = useNavigate() - const hasSchedule = (group.days?.length ?? 0) > 0 - const hasRisk = riskLevel === 'HIGH' || riskLevel === 'MEDIUM' - - return ( -
    -
    -
    -

    {group.name}

    - {group.description ? ( -

    {group.description}

    - ) : null} -
    -
    - {hasRisk ? ( - - - ) : null} - Activo -
    -
    - - {hasSchedule ? ( -
    -
    - - {formatSchedule(group.days ?? [], group.time)} -
    -
    - - - Cupo {group.capacity ?? '—'} miembros - {group.price != null - ? ` · ${formatPrice(group.price)}${group.billingType ? ` · ${BILLING_LABELS[group.billingType]}` : ''}` - : ''} - {group.dueDay != null ? ` · vence el día ${group.dueDay}` : ''} - -
    -
    - ) : ( -

    Aún sin plan de cobro configurado.

    - )} - -
    - -
    -
    - ) -} - -export function GroupsView() { - const navigate = useNavigate() - const groupsQuery = useQuery({ - queryKey: ['groups'], - queryFn: getGroups, - }) - const riskQuery = useQuery({ - queryKey: ['groups-risk-overview'], - queryFn: getGroupsRiskOverview, - }) - - const riskByGroup = new Map( - (riskQuery.data?.items ?? []).map((item) => [item.groupId, item.riskLevel]), - ) - - return ( -
    -
    -
    -

    Grupos

    -

    Tus grupos de cobranza.

    -
    - -
    - - {groupsQuery.isPending ? ( -
    - -
    - ) : null} - - {groupsQuery.isError ? ( -
    -

    No pudimos cargar tus grupos.

    - -
    - ) : null} - - {groupsQuery.isSuccess && groupsQuery.data.data.length === 0 ? ( -
    -

    Todavía no tenés grupos

    -

    - Crea tu primer grupo para empezar a cobrar. -

    - -
    - ) : null} - - {groupsQuery.isSuccess && groupsQuery.data.data.length > 0 ? ( -
    - {groupsQuery.data.data.map((group) => ( - - ))} -
    - ) : null} -
    - ) -} \ No newline at end of file diff --git a/apps/web/src/routes/home.tsx b/apps/web/src/routes/home.tsx deleted file mode 100644 index 431768a..0000000 --- a/apps/web/src/routes/home.tsx +++ /dev/null @@ -1,310 +0,0 @@ -import { useQuery } from '@tanstack/react-query' -import { useNavigate } from '@tanstack/react-router' -import { - CalendarClock, - ClipboardCheck, - Loader2, - Plus, - UserCheck, - Users, - Wallet, - type LucideIcon, -} from 'lucide-react' -import type { - ClassTodayDto, - HomeSummaryDto, - NextClassDto, - PaymentDto, - UpcomingPaymentDto, -} from '@gruperly/shared' -import { Badge, Button } from '../components/ui' -import { getClassesToday, getHomeSummary } from '../lib/api' -import { - formatPrice, - formatRelativeDateTime, - formatSchedule, - PAYMENT_STATUS_LABELS, -} from '../lib/format' -import { cn } from '../lib/utils' - -const PAYMENT_BADGE_VARIANT: Record< - PaymentDto['status'], - 'success' | 'warning' | 'danger' | 'neutral' -> = { - PENDING: 'warning', - OVERDUE: 'danger', - PAID: 'success', - CANCELLED: 'neutral', -} - -function TodayClassCard({ item }: { item: ClassTodayDto }) { - const navigate = useNavigate() - const time = new Date(item.startsAt).toLocaleTimeString('es-MX', { - hour: '2-digit', - minute: '2-digit', - hour12: false, - }) - - return ( -
    -
    -
    -

    - Clase de hoy -

    -

    {item.groupName}

    -
    - - Hoy · {time} hs -
    -

    - {item.enrolledCount} inscrito{item.enrolledCount === 1 ? '' : 's'} - {item.availableSlots != null ? ` · ${item.availableSlots} cupo${item.availableSlots === 1 ? '' : 's'} disponible${item.availableSlots === 1 ? '' : 's'}` : ''} -

    -
    -
    - - {item.hasAttendance ? 'Asistencia tomada' : 'Por tomar'} - -
    -
    -
    - - -
    -
    - ) -} - -function NextClassHero({ nextClass }: { nextClass: NextClassDto }) { - const navigate = useNavigate() - const hasSchedule = (nextClass.days?.length ?? 0) > 0 - - return ( -
    -
    -
    -

    - {nextClass.isNow ? 'Clase en curso' : 'Próxima clase'} -

    -

    {nextClass.name}

    - {hasSchedule ? ( -
    - - {formatSchedule(nextClass.days ?? [], nextClass.time)} -
    - ) : null} -
    -
    - - {nextClass.isNow ? 'En curso ahora' : formatRelativeDateTime(nextClass.occurrenceAt)} - -
    -
    -
    - -
    -
    - ) -} - -function UpcomingPaymentRow({ payment }: { payment: UpcomingPaymentDto }) { - return ( -
  • -
    -

    {payment.attendeeName}

    -

    - {payment.groupName} · {formatRelativeDateTime(payment.dueDate)} -

    -
    -
    - {formatPrice(payment.amount)} - - {PAYMENT_STATUS_LABELS[payment.status]} - -
    -
  • - ) -} - -function SummaryStats({ summary }: { summary: HomeSummaryDto }) { - const navigate = useNavigate() - const stats: { - label: string - value: string - sub?: string - icon: LucideIcon - to: '/groups' | '/payments' - }[] = [ - { - label: 'Grupos activos', - value: String(summary.stats.groups), - icon: Users, - to: '/groups', - }, - { - label: 'Cobros pendientes', - value: summary.stats.pendingAmount > 0 ? formatPrice(summary.stats.pendingAmount) : '0', - sub: `${summary.stats.pendingPayments} por cobrar`, - icon: Wallet, - to: '/payments', - }, - { - label: 'Asistentes', - value: String(summary.stats.attendees), - icon: UserCheck, - to: '/groups', - }, - ] - - return ( -
    - {stats.map((stat) => { - const Icon = stat.icon - return ( - - ) - })} -
    - ) -} - -export function HomeView() { - const navigate = useNavigate() - const summaryQuery = useQuery({ - queryKey: ['home-summary'], - queryFn: getHomeSummary, - }) - const classesTodayQuery = useQuery({ - queryKey: ['classes-today'], - queryFn: getClassesToday, - staleTime: 60_000, - }) - const todayClasses = classesTodayQuery.data?.data ?? [] - - return ( -
    -
    -

    Inicio

    -

    Tu actividad de cobros de un vistazo.

    -
    - - {summaryQuery.isPending ? ( -
    - -
    - ) : null} - - {summaryQuery.isError ? ( -
    -

    No pudimos cargar tu resumen.

    - -
    - ) : null} - - {summaryQuery.isSuccess && summaryQuery.data.stats.groups === 0 ? ( -
    -

    Todavía no tenés grupos

    -

    - Crea tu primer grupo para empezar a cobrar. -

    - -
    - ) : null} - - {summaryQuery.isSuccess && summaryQuery.data.stats.groups > 0 ? ( -
    - {todayClasses.length > 0 ? ( -
    - {todayClasses.map((classItem) => ( - - ))} -
    - ) : summaryQuery.data.nextClass ? ( - - ) : ( -
    -

    Sin clases programadas

    -

    - Agregá días y horario a tus grupos para ver tu próxima clase acá. -

    -
    - )} - - - -
    -
    -

    Próximos cobros

    - -
    - - {summaryQuery.data.upcomingPayments.length > 0 ? ( -
      - {summaryQuery.data.upcomingPayments.map((payment) => ( - - ))} -
    - ) : ( -

    - Sin cobros pendientes por ahora. -

    - )} -
    -
    - ) : null} -
    - ) -} \ No newline at end of file diff --git a/apps/web/src/routes/join-group.tsx b/apps/web/src/routes/join-group.tsx deleted file mode 100644 index c84e236..0000000 --- a/apps/web/src/routes/join-group.tsx +++ /dev/null @@ -1,343 +0,0 @@ -import { useState } from 'react'; -import { useQuery, useMutation } from '@tanstack/react-query'; -import { useParams, Link } from '@tanstack/react-router'; -import { - CalendarClock, - CheckCircle2, - Clock, - GraduationCap, - Loader2, - Moon, - Sun, - Users, -} from 'lucide-react'; -import { Badge, Button, Input, Label } from '../components/ui'; -import { Logo } from '../components/brand'; -import { useTheme } from '../context/ThemeProvider'; -import { getInviteInfo, joinViaInvite, ApiError } from '../lib/api'; -import { BILLING_LABELS, formatPrice, formatSchedule } from '../lib/format'; - -export function JoinGroupView() { - const { token } = useParams({ strict: false }) as { token: string }; - const { theme, setTheme, isDark } = useTheme(); - - const [firstName, setFirstName] = useState(''); - const [lastName, setLastName] = useState(''); - const [phone, setPhone] = useState(''); - const [email, setEmail] = useState(''); - const [errorMessage, setErrorMessage] = useState(null); - - // Success state - const [registeredAttendee, setRegisteredAttendee] = useState<{ - fullName: string; - phone: string | null; - } | null>(null); - - // Waitlist state (group is full) - const [waitlistInfo, setWaitlistInfo] = useState<{ message: string } | null>(null); - - const inviteQuery = useQuery({ - queryKey: ['public-invite', token], - queryFn: () => getInviteInfo(token), - enabled: Boolean(token), - retry: 1, - }); - - const joinMutation = useMutation({ - mutationFn: () => - joinViaInvite(token, { - firstName: firstName.trim(), - lastName: lastName.trim(), - phone: phone.trim(), - email: email.trim() || undefined, - }), - onSuccess: (data) => { - setErrorMessage(null); - if (data.status === 'waitlisted') { - setRegisteredAttendee(null); - setWaitlistInfo({ message: data.message }); - return; - } - setWaitlistInfo(null); - setRegisteredAttendee({ - fullName: data.attendee!.fullName, - phone: data.attendee!.phone, - }); - }, - onError: (error: unknown) => { - if (error instanceof ApiError) { - if (error.problem?.code === 'attendee_already_registered') { - setErrorMessage( - 'Ya te encuentras registrado en este grupo con ese número de teléfono. El profesor ya tiene tus datos.', - ); - return; - } - setErrorMessage(error.message || 'Error al procesar la inscripción.'); - } else if (error instanceof Error) { - setErrorMessage(error.message); - } else { - setErrorMessage('Ocurrió un error inesperado. Por favor, intenta de nuevo.'); - } - }, - }); - - const handleSubmit = (e: React.FormEvent) => { - e.preventDefault(); - setErrorMessage(null); - - if (!firstName.trim() || !lastName.trim() || !phone.trim()) { - setErrorMessage('Por favor completa los campos requeridos (Nombre, Apellido y Teléfono).'); - return; - } - - joinMutation.mutate(); - }; - - const group = inviteQuery.data; - - return ( -
    - {/* Public Header */} -
    - - - - - -
    - - {/* Main Content */} -
    -
    - {inviteQuery.isPending ? ( -
    - -

    Cargando información del grupo...

    -
    - ) : null} - - {inviteQuery.isError || !group ? ( -
    -

    Enlace no válido o expirado

    -

    - No pudimos encontrar este grupo. Por favor consulta con tu profesor para solicitar un nuevo enlace de invitación. -

    -
    - ) : null} - - {/* Registration Success Confirmation */} - {registeredAttendee && group ? ( -
    -
    - -
    - -
    - - Registro Confirmado - -

    ¡Inscripción Exitosa!

    -

    - Tus datos han sido registrados con éxito en el grupo{' '} - {group.name}. -

    -
    - -
    -
    - Profesor: - {group.teacherName} -
    -
    - Alumno: - {registeredAttendee.fullName} -
    - {registeredAttendee.phone ? ( -
    - Teléfono registrado: - {registeredAttendee.phone} -
    - ) : null} -
    - -

    - El profesor se pondrá en contacto contigo a la brevedad por WhatsApp para darte la bienvenida y coordinar los detalles de la clase. -

    -
    - ) : null} - - {/* Waitlist Confirmation (group full) */} - {waitlistInfo && group ? ( -
    -
    - -
    - -
    - - Lista de Espera - -

    Cupo completo

    -

    - {waitlistInfo.message} -

    -
    - -

    - El profesor se pondrá en contacto contigo cuando haya un lugar disponible en{' '} - {group.name}. -

    -
    - ) : null} - - {/* Inscription Form */} - {!registeredAttendee && !waitlistInfo && group ? ( -
    - {/* Group Info Header */} -
    -
    - - - Invitación Oficial - -
    -

    {group.name}

    -

    - Profesor: {group.teacherName} -

    - {group.description ? ( -

    {group.description}

    - ) : null} - - {/* Schedule & Price Details */} -
    - {(group.days?.length ?? 0) > 0 ? ( -
    - - {formatSchedule(group.days ?? [], group.time)} -
    - ) : null} - - {group.price != null ? ( -
    - {formatPrice(group.price)} - {group.billingType ? · {BILLING_LABELS[group.billingType]} : ''} -
    - ) : null} - - {group.capacity ? ( -
    - - Cupo {group.capacity} -
    - ) : null} -
    -
    - - {/* Form Header */} -
    -

    Completa tus datos

    -

    - Ingresa tus datos para registrarte en la lista de alumnos de este grupo. -

    -
    - - {/* Error banner */} - {errorMessage ? ( -
    - {errorMessage} -
    - ) : null} - - {/* Form */} -
    -
    -
    - - setFirstName(e.target.value)} - required - /> -
    - -
    - - setLastName(e.target.value)} - required - /> -
    -
    - -
    - - setPhone(e.target.value)} - required - /> -

    - El profesor se comunicará contigo por WhatsApp a este número. -

    -
    - -
    - - setEmail(e.target.value)} - /> -
    - -
    - -
    -
    -
    - ) : null} -
    -
    - - {/* Footer */} -
    - Gruperly — Gestión sencilla de cobros y grupos -
    -
    - ); -} diff --git a/apps/web/src/routes/onboarding.tsx b/apps/web/src/routes/onboarding.tsx deleted file mode 100644 index 7bbc76c..0000000 --- a/apps/web/src/routes/onboarding.tsx +++ /dev/null @@ -1,130 +0,0 @@ -import { useEffect, useState } from 'react' -import { useQuery } from '@tanstack/react-query' -import { useNavigate } from '@tanstack/react-router' -import { Loader2 } from 'lucide-react' -import type { ConnectPaymentResult, OnboardingGroupDto } from '@gruperly/shared' -import { Logo, LogoIcon } from '../components/brand' -import { - ConfirmationStep, - FirstGroupStep, - PaymentStep, - Stepper, - WelcomeStep, -} from '../components/onboarding' -import { PAYMENT_PROVIDERS } from '../components/onboarding/constants' -import { Button } from '../components/ui' -import { useAuth } from '../context/AuthProvider' -import { getOnboardingStatus } from '../lib/api' - -const STEPS = [ - { label: 'Bienvenida' }, - { label: 'Cobros' }, - { label: 'Tu grupo' }, - { label: 'Listo' }, -] - -export function OnboardingView() { - const { user, isPending: authPending } = useAuth() - const navigate = useNavigate() - - const [step, setStep] = useState(0) - const [paymentResult, setPaymentResult] = useState(null) - const [createdGroup, setCreatedGroup] = useState(null) - - const statusQuery = useQuery({ - queryKey: ['onboarding', 'status'], - queryFn: getOnboardingStatus, - enabled: !!user, - }) - - useEffect(() => { - const status = statusQuery.data - if (!status) return - if (status.completed) { - void navigate({ to: '/' }) - return - } - // Si interrumpió después de conectar el cobro, retomamos en el paso del grupo. - if (status.step === 'PAYMENT_CONNECTED') { - setStep((current) => (current === 0 ? 2 : current)) - } - }, [statusQuery.data, navigate]) - - if (authPending) { - return ( -
    - -
    - ) - } - - if (!user) { - return ( -
    -
    - - - -

    Tu cuenta, lista

    -

    - Iniciá sesión para configurar tus cobros y crear tu primer grupo. -

    - -
    -
    - ) - } - - if (statusQuery.isPending) { - return ( -
    - -
    - ) - } - - const firstName = user.name?.trim().split(/\s+/)[0] ?? 'profesor/a' - const providerName = paymentResult - ? PAYMENT_PROVIDERS.find((p) => p.value === paymentResult.provider)?.name - : undefined - - return ( -
    -
    - -
    - - - -
    - {step === 0 ? ( - setStep(1)} /> - ) : null} - {step === 1 ? ( - { - setPaymentResult(result) - setStep(2) - }} - onBack={() => setStep(0)} - /> - ) : null} - {step === 2 ? ( - setStep(1)} - onCompleted={(group) => { - setCreatedGroup(group) - setStep(3) - }} - /> - ) : null} - {step === 3 && createdGroup ? ( - - ) : null} -
    -
    - ) -} \ No newline at end of file diff --git a/apps/web/src/routes/payments.tsx b/apps/web/src/routes/payments.tsx deleted file mode 100644 index efcd8eb..0000000 --- a/apps/web/src/routes/payments.tsx +++ /dev/null @@ -1,8 +0,0 @@ -export function PaymentsView() { - return ( -
    -

    Cobros

    -

    Sigue los pagos de tus grupos.

    -
    - ) -} diff --git a/apps/web/src/routes/profile.tsx b/apps/web/src/routes/profile.tsx deleted file mode 100644 index a015713..0000000 --- a/apps/web/src/routes/profile.tsx +++ /dev/null @@ -1,27 +0,0 @@ -import { useAuth } from '../context/AuthProvider' -import { Avatar } from '../components/ui' - -export function ProfileView() { - const { user } = useAuth() - - return ( -
    -
    -

    Mi perfil

    -

    Tus datos personales.

    -
    - -
    -
    - -
    -

    - {user?.name ?? 'Usuario'} -

    -

    {user?.email}

    -
    -
    -
    -
    - ) -} \ No newline at end of file diff --git a/apps/web/src/routes/security.tsx b/apps/web/src/routes/security.tsx deleted file mode 100644 index 1892595..0000000 --- a/apps/web/src/routes/security.tsx +++ /dev/null @@ -1,183 +0,0 @@ -import { useState } from 'react' -import { useForm } from 'react-hook-form' -import { z } from 'zod' -import { zodResolver } from '@hookform/resolvers/zod' -import { Fingerprint, KeyRound, Loader2, Plus, Trash2 } from 'lucide-react' -import { authClient } from '../lib/auth-client' -import { Button, Input, Label } from '../components/ui' - -const changePasswordSchema = z - .object({ - currentPassword: z.string().min(1, 'Ingresá tu contraseña actual'), - newPassword: z.string().min(8, 'La nueva contraseña debe tener al menos 8 caracteres'), - }) - .refine((v) => v.currentPassword !== v.newPassword, { - message: 'La nueva contraseña debe ser distinta', - path: ['newPassword'], - }) - -type ChangePasswordValues = z.infer - -function PasskeyList({ onRefresh }: { onRefresh: () => void }) { - const { data, isPending } = authClient.useListPasskeys() - const [deletingId, setDeletingId] = useState(null) - - const handleDelete = async (id: string) => { - setDeletingId(id) - const { error } = await authClient.$fetch('/passkey/delete-passkey', { - method: 'POST', - body: { id }, - }) - setDeletingId(null) - if (!error) onRefresh() - } - - if (isPending) { - return - } - - const passkeys = data ?? [] - if (passkeys.length === 0) { - return

    Todavía no registraste ninguna passkey.

    - } - - return ( -
      - {passkeys.map((passkey) => ( -
    • - - - -
      -

      - {passkey.name ?? 'Passkey'} -

      -

      - {passkey.deviceType === 'singleDevice' ? 'Dispositivo' : 'Llave de seguridad'} ·{' '} - {new Date(passkey.createdAt).toLocaleDateString('es-AR')} -

      -
      - -
    • - ))} -
    - ) -} - -export function SecurityPage() { - const [passkeyKeys, setPasskeyKeys] = useState(0) - const [feedback, setFeedback] = useState(null) - - const { - register, - handleSubmit, - reset, - setError, - formState: { errors, isSubmitting }, - } = useForm({ resolver: zodResolver(changePasswordSchema) }) - - const refreshPasskeys = () => { - setPasskeyKeys((k) => k + 1) - } - - const handleAddPasskey = async () => { - setFeedback(null) - const { error } = await authClient.passkey.addPasskey() - if (error) setFeedback(`No se pudo agregar: ${error.message}`) - else { - setFeedback('Passkey registrada correctamente.') - refreshPasskeys() - } - } - - const onChangePassword = handleSubmit(async ({ currentPassword, newPassword }) => { - setFeedback(null) - const { error } = await authClient.changePassword({ - currentPassword, - newPassword, - revokeOtherSessions: true, - }) - if (error) { - setError('currentPassword', { message: error.message ?? 'No se pudo cambiar la contraseña' }) - return - } - reset({ currentPassword: '', newPassword: '' }) - setFeedback('Contraseña actualizada.') - }) - - return ( -
    -
    -

    Seguridad

    -

    - Gestioná tu contraseña y tus llaves de acceso (passkeys). -

    -
    - - {feedback ? ( -

    {feedback}

    - ) : null} - -
    -
    - -

    Cambiar contraseña

    -
    -
    -
    - - - {errors.currentPassword ? ( -

    {errors.currentPassword.message}

    - ) : null} -
    -
    - - - {errors.newPassword ? ( -

    {errors.newPassword.message}

    - ) : null} -
    - -
    -
    - -
    -
    -
    - -

    Passkeys

    -
    - -
    - -
    -
    - ) -} \ No newline at end of file diff --git a/apps/web/src/routes/settings.tsx b/apps/web/src/routes/settings.tsx deleted file mode 100644 index 8777eca..0000000 --- a/apps/web/src/routes/settings.tsx +++ /dev/null @@ -1,97 +0,0 @@ -import { Link } from '@tanstack/react-router' -import { Check, Fingerprint, Monitor, Moon, Sun } from 'lucide-react' -import { signOut } from '../lib/auth-client' -import { Button } from '../components/ui' -import { useTheme, type Theme } from '../context/ThemeProvider' -import { cn } from '../lib/utils' - -const THEME_OPTIONS: { value: Theme; label: string; description: string }[] = [ - { value: 'light', label: 'Claro', description: 'Interfaz en tonos claros' }, - { value: 'dark', label: 'Oscuro', description: 'Interfaz en tonos oscuros' }, - { value: 'system', label: 'Sistema', description: 'Sigue la preferencia de tu dispositivo' }, -] - -const THEME_ICONS: Record = { - light: Sun, - dark: Moon, - system: Monitor, -} - -function AppearanceCard() { - const { theme, setTheme } = useTheme() - - return ( -
    -
    -

    Apariencia

    -

    Tema claro u oscuro

    -
    - {THEME_OPTIONS.map((option) => { - const Icon = THEME_ICONS[option.value] - const isSelected = theme === option.value - return ( - - ) - })} -
    - ) -} - -export function SettingsView() { - const handleSignOut = async () => { - await signOut({ - fetchOptions: { headers: { 'Cache-Control': 'no-cache' } }, - }) - window.location.assign('/login') - } - - return ( -
    -
    -

    Ajustes

    -

    Configurá tu cuenta y tus grupos.

    -
    - -
    - - - - -
    -

    Seguridad

    -

    Contraseña y passkeys

    -
    - -
    - - - - -
    - ) -} \ No newline at end of file From 94c353f4f2c07472c71afc28895d51ca0c521ee4 Mon Sep 17 00:00:00 2001 From: Jose Selesan Date: Fri, 25 Sep 2026 10:05:56 -0300 Subject: [PATCH 4/6] Added routes --- AGENTS.md | 3 +- apps/web/package.json | 3 +- .../src/components/layout/AppLayoutGuard.tsx | 5 +- apps/web/src/components/layout/Header.tsx | 18 +- .../src/components/layout/PublicFooter.tsx | 7 + .../src/components/layout/PublicHeader.tsx | 14 + apps/web/src/components/layout/RootLayout.tsx | 10 +- .../web/src/components/layout/ThemeToggle.tsx | 17 + apps/web/src/components/layout/index.ts | 3 + .../absence-notify/AbsenceNotifyProvider.tsx | 65 +++ .../absence-notify/AbsenceNotifyView.tsx | 71 +++ .../absence-notify/AbsenceSessionRow.tsx | 44 ++ apps/web/src/features/auth/AuthShell.tsx | 25 + apps/web/src/features/auth/LoginPage.tsx | 113 ++++ apps/web/src/features/auth/SignupPage.tsx | 142 +++++ .../web/src/features/auth/VerifyEmailPage.tsx | 91 +++ .../class-attendance/AttendanceProvider.tsx | 117 ++++ .../class-attendance/AttendanceToggle.tsx | 45 ++ .../class-attendance/ClassAttendanceView.tsx | 90 +++ .../features/class-attendance/StudentRow.tsx | 37 ++ .../src/features/class-attendance/utils.ts | 7 + .../src/features/groups/CreateGroupView.tsx | 42 ++ apps/web/src/features/groups/GroupCard.tsx | 78 +++ apps/web/src/features/groups/GroupForm.tsx | 231 ++++++++ apps/web/src/features/groups/GroupsView.tsx | 81 +++ .../groups/analytics/AnalyticsView.tsx | 219 +++++++ .../groups/analytics/AtRiskStudentCard.tsx | 100 ++++ .../groups/analytics/AttendeeHistoryModal.tsx | 80 +++ .../src/features/groups/analytics/KpiCard.tsx | 26 + .../groups/analytics/StatusActionModal.tsx | 72 +++ .../src/features/groups/analytics/format.ts | 46 ++ apps/web/src/features/groups/constants.ts | 6 + .../groups/detail/AddAttendeeModal.tsx | 46 ++ .../groups/detail/AttendeeDetailModal.tsx | 150 +++++ .../groups/detail/BulkCapacityModal.tsx | 41 ++ .../groups/detail/BulkImportPanel.tsx | 228 ++++++++ .../features/groups/detail/CapacityModal.tsx | 61 ++ .../src/features/groups/detail/DetailRow.tsx | 15 + .../groups/detail/GroupDetailProvider.tsx | 537 ++++++++++++++++++ .../groups/detail/GroupDetailView.tsx | 55 ++ .../features/groups/detail/GroupHeader.tsx | 77 +++ .../features/groups/detail/GroupInfoCard.tsx | 47 ++ .../groups/detail/InviteLinkModal.tsx | 117 ++++ .../features/groups/detail/MembersTable.tsx | 45 ++ .../groups/detail/MembersWaitlistSection.tsx | 146 +++++ .../features/groups/detail/QuickAddForm.tsx | 124 ++++ .../groups/detail/RemoveAttendeeModal.tsx | 99 ++++ .../detail/WaitlistEntryDetailModal.tsx | 118 ++++ .../features/groups/detail/WaitlistTable.tsx | 48 ++ apps/web/src/features/home/HomeView.tsx | 108 ++++ apps/web/src/features/home/NextClassHero.tsx | 43 ++ apps/web/src/features/home/SummaryStats.tsx | 67 +++ apps/web/src/features/home/TodayClassCard.tsx | 58 ++ .../src/features/home/UpcomingPaymentRow.tsx | 23 + apps/web/src/features/home/constants.ts | 10 + .../src/features/join/GroupInviteSummary.tsx | 48 ++ .../src/features/join/InvalidInviteCard.tsx | 11 + apps/web/src/features/join/JoinForm.tsx | 113 ++++ .../src/features/join/JoinGroupProvider.tsx | 128 +++++ apps/web/src/features/join/JoinGroupView.tsx | 43 ++ .../web/src/features/join/JoinSuccessCard.tsx | 49 ++ .../src/features/join/WaitlistNoticeCard.tsx | 29 + .../features/onboarding/ConfirmationStep.tsx | 84 +++ .../features/onboarding/FirstGroupStep.tsx | 30 + .../onboarding/OnboardingProvider.tsx | 72 +++ .../features/onboarding/OnboardingView.tsx | 117 ++++ .../src/features/onboarding/PaymentStep.tsx | 171 ++++++ apps/web/src/features/onboarding/Stepper.tsx | 59 ++ .../src/features/onboarding/WelcomeStep.tsx | 63 ++ apps/web/src/features/onboarding/constants.ts | 44 ++ .../src/features/payments/PaymentsView.tsx | 8 + apps/web/src/features/profile/ProfileView.tsx | 27 + .../web/src/features/security/PasskeyList.tsx | 56 ++ .../src/features/security/SecurityPage.tsx | 123 ++++ apps/web/src/features/security/schema.ts | 13 + .../src/features/settings/AppearanceCard.tsx | 42 ++ .../src/features/settings/SettingsView.tsx | 41 ++ apps/web/src/features/settings/constants.ts | 14 + apps/web/src/routeTree.gen.ts | 410 +++++++++++++ apps/web/src/router.tsx | 150 +---- apps/web/src/routes/__root.tsx | 5 + apps/web/src/routes/_authenticated.tsx | 10 + .../class/$sessionId/attendance.tsx | 15 + .../groups/$groupId/analytics.tsx | 6 + .../_authenticated/groups/$groupId/index.tsx | 15 + .../routes/_authenticated/groups/index.tsx | 6 + .../src/routes/_authenticated/groups/new.tsx | 6 + apps/web/src/routes/_authenticated/index.tsx | 6 + .../src/routes/_authenticated/payments.tsx | 6 + .../web/src/routes/_authenticated/profile.tsx | 6 + .../src/routes/_authenticated/seguridad.tsx | 6 + .../src/routes/_authenticated/settings.tsx | 6 + .../web/src/routes/avisar-ausencia.$token.tsx | 15 + apps/web/src/routes/join.$token.tsx | 15 + apps/web/src/routes/login.tsx | 6 + apps/web/src/routes/onboarding.tsx | 6 + apps/web/src/routes/signup.tsx | 6 + apps/web/src/routes/verify-email.tsx | 10 + apps/web/vite.config.ts | 5 +- bun.lock | 37 +- 100 files changed, 6126 insertions(+), 183 deletions(-) create mode 100644 apps/web/src/components/layout/PublicFooter.tsx create mode 100644 apps/web/src/components/layout/PublicHeader.tsx create mode 100644 apps/web/src/components/layout/ThemeToggle.tsx create mode 100644 apps/web/src/features/absence-notify/AbsenceNotifyProvider.tsx create mode 100644 apps/web/src/features/absence-notify/AbsenceNotifyView.tsx create mode 100644 apps/web/src/features/absence-notify/AbsenceSessionRow.tsx create mode 100644 apps/web/src/features/auth/AuthShell.tsx create mode 100644 apps/web/src/features/auth/LoginPage.tsx create mode 100644 apps/web/src/features/auth/SignupPage.tsx create mode 100644 apps/web/src/features/auth/VerifyEmailPage.tsx create mode 100644 apps/web/src/features/class-attendance/AttendanceProvider.tsx create mode 100644 apps/web/src/features/class-attendance/AttendanceToggle.tsx create mode 100644 apps/web/src/features/class-attendance/ClassAttendanceView.tsx create mode 100644 apps/web/src/features/class-attendance/StudentRow.tsx create mode 100644 apps/web/src/features/class-attendance/utils.ts create mode 100644 apps/web/src/features/groups/CreateGroupView.tsx create mode 100644 apps/web/src/features/groups/GroupCard.tsx create mode 100644 apps/web/src/features/groups/GroupForm.tsx create mode 100644 apps/web/src/features/groups/GroupsView.tsx create mode 100644 apps/web/src/features/groups/analytics/AnalyticsView.tsx create mode 100644 apps/web/src/features/groups/analytics/AtRiskStudentCard.tsx create mode 100644 apps/web/src/features/groups/analytics/AttendeeHistoryModal.tsx create mode 100644 apps/web/src/features/groups/analytics/KpiCard.tsx create mode 100644 apps/web/src/features/groups/analytics/StatusActionModal.tsx create mode 100644 apps/web/src/features/groups/analytics/format.ts create mode 100644 apps/web/src/features/groups/constants.ts create mode 100644 apps/web/src/features/groups/detail/AddAttendeeModal.tsx create mode 100644 apps/web/src/features/groups/detail/AttendeeDetailModal.tsx create mode 100644 apps/web/src/features/groups/detail/BulkCapacityModal.tsx create mode 100644 apps/web/src/features/groups/detail/BulkImportPanel.tsx create mode 100644 apps/web/src/features/groups/detail/CapacityModal.tsx create mode 100644 apps/web/src/features/groups/detail/DetailRow.tsx create mode 100644 apps/web/src/features/groups/detail/GroupDetailProvider.tsx create mode 100644 apps/web/src/features/groups/detail/GroupDetailView.tsx create mode 100644 apps/web/src/features/groups/detail/GroupHeader.tsx create mode 100644 apps/web/src/features/groups/detail/GroupInfoCard.tsx create mode 100644 apps/web/src/features/groups/detail/InviteLinkModal.tsx create mode 100644 apps/web/src/features/groups/detail/MembersTable.tsx create mode 100644 apps/web/src/features/groups/detail/MembersWaitlistSection.tsx create mode 100644 apps/web/src/features/groups/detail/QuickAddForm.tsx create mode 100644 apps/web/src/features/groups/detail/RemoveAttendeeModal.tsx create mode 100644 apps/web/src/features/groups/detail/WaitlistEntryDetailModal.tsx create mode 100644 apps/web/src/features/groups/detail/WaitlistTable.tsx create mode 100644 apps/web/src/features/home/HomeView.tsx create mode 100644 apps/web/src/features/home/NextClassHero.tsx create mode 100644 apps/web/src/features/home/SummaryStats.tsx create mode 100644 apps/web/src/features/home/TodayClassCard.tsx create mode 100644 apps/web/src/features/home/UpcomingPaymentRow.tsx create mode 100644 apps/web/src/features/home/constants.ts create mode 100644 apps/web/src/features/join/GroupInviteSummary.tsx create mode 100644 apps/web/src/features/join/InvalidInviteCard.tsx create mode 100644 apps/web/src/features/join/JoinForm.tsx create mode 100644 apps/web/src/features/join/JoinGroupProvider.tsx create mode 100644 apps/web/src/features/join/JoinGroupView.tsx create mode 100644 apps/web/src/features/join/JoinSuccessCard.tsx create mode 100644 apps/web/src/features/join/WaitlistNoticeCard.tsx create mode 100644 apps/web/src/features/onboarding/ConfirmationStep.tsx create mode 100644 apps/web/src/features/onboarding/FirstGroupStep.tsx create mode 100644 apps/web/src/features/onboarding/OnboardingProvider.tsx create mode 100644 apps/web/src/features/onboarding/OnboardingView.tsx create mode 100644 apps/web/src/features/onboarding/PaymentStep.tsx create mode 100644 apps/web/src/features/onboarding/Stepper.tsx create mode 100644 apps/web/src/features/onboarding/WelcomeStep.tsx create mode 100644 apps/web/src/features/onboarding/constants.ts create mode 100644 apps/web/src/features/payments/PaymentsView.tsx create mode 100644 apps/web/src/features/profile/ProfileView.tsx create mode 100644 apps/web/src/features/security/PasskeyList.tsx create mode 100644 apps/web/src/features/security/SecurityPage.tsx create mode 100644 apps/web/src/features/security/schema.ts create mode 100644 apps/web/src/features/settings/AppearanceCard.tsx create mode 100644 apps/web/src/features/settings/SettingsView.tsx create mode 100644 apps/web/src/features/settings/constants.ts create mode 100644 apps/web/src/routeTree.gen.ts create mode 100644 apps/web/src/routes/__root.tsx create mode 100644 apps/web/src/routes/_authenticated.tsx create mode 100644 apps/web/src/routes/_authenticated/class/$sessionId/attendance.tsx create mode 100644 apps/web/src/routes/_authenticated/groups/$groupId/analytics.tsx create mode 100644 apps/web/src/routes/_authenticated/groups/$groupId/index.tsx create mode 100644 apps/web/src/routes/_authenticated/groups/index.tsx create mode 100644 apps/web/src/routes/_authenticated/groups/new.tsx create mode 100644 apps/web/src/routes/_authenticated/index.tsx create mode 100644 apps/web/src/routes/_authenticated/payments.tsx create mode 100644 apps/web/src/routes/_authenticated/profile.tsx create mode 100644 apps/web/src/routes/_authenticated/seguridad.tsx create mode 100644 apps/web/src/routes/_authenticated/settings.tsx create mode 100644 apps/web/src/routes/avisar-ausencia.$token.tsx create mode 100644 apps/web/src/routes/join.$token.tsx create mode 100644 apps/web/src/routes/login.tsx create mode 100644 apps/web/src/routes/onboarding.tsx create mode 100644 apps/web/src/routes/signup.tsx create mode 100644 apps/web/src/routes/verify-email.tsx diff --git a/AGENTS.md b/AGENTS.md index 2205d2d..35332c1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -48,7 +48,8 @@ bun --filter @gruperly/backend db:* # db:generate / db:migrate / db:push - **Base de datos**: todas las tablas usan **snake_case** vía `@@map` en `prisma/models/*.prisma` (p. ej. `User` → `users`, `WaitlistEntry` → `waitlist_entries`). Al agregar un modelo nuevo, incluir siempre `@@map("nombre_tabla")`. - **API** responde errores en **Problem Details RFC 7807** (`application/problem+json`) y resultados como `{ data, pagination }`; los "use cases" devuelven `Result` y nunca lanzan excepciones de dominio. - **Tailwind v4** con tokens en `@theme` dentro de `apps/web/src/index.css` (p. ej. `--color-accent: #1e90ff`). Se usan como clases auto-generadas: `text-accent`, `bg-success-soft`, etc. Radius por defecto `0.75rem` (`rounded-xl`). -- **Router NO es file-based** (aunque `stack.md` lo diga): las rutas se declaran manualmente en `apps/web/src/router.tsx` con `createRoute` + `addChildren` y se registran vía module augmentation. **Cada vista nueva debe añadirse ahí.** +- **Router ES file-based** (TanStack Router + `@tanstack/router-plugin`): las rutas viven en `apps/web/src/routes/` y solo contienen definiciones (`createFileRoute` + `component`), sin lógica de UI. `src/router.tsx` solo crea el router con el `routeTree` importado de `src/routeTree.gen.ts` (**archivo generado por el plugin en build/dev, versionado en git**: si agregás/renombrás una ruta, corré `bun --filter @gruperly/web build` para regenerarlo). Las rutas autenticadas cuelgan del layout pathless `_authenticated.tsx` (`AppLayoutGuard` + `RootLayout` con ``). +- **Vistas en `apps/web/src/features//`**: un componente por archivo, nombre de archivo en PascalCase igual al componente, imports relativos (sin alias). El estado compartido padre-hijo vive en un `*Provider.tsx` del feature (contexto + queries/mutations de React Query) que se monta en el route file; los componentes hijos consumen `use()` y las forms locales mantienen su propio estado. - Nav (Inicio/Grupos/Cobros/Ajustes) vive en `apps/web/src/components/layout/nav-items.ts`; es la fuente única para `BottomNav` (móvil) y `Sidebar` (desktop) — no dupliques la lista. - **UI**: primitivos propios en `apps/web/src/components/ui/` (avatar, button, badge) más helper `cn()` en `src/lib/utils.ts` (clsx + tailwind-merge). Aunque `stack.md` mencione Shadcn, **todavía no está instalado** (sin Radix); úsalos directos. - Layout mobile-first: `RootLayout` usa columna `max-w-md` en móvil y dos columnas (Sidebar + contenido `max-w-6xl`) en `lg+`. diff --git a/apps/web/package.json b/apps/web/package.json index d1620ca..64cac5e 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -14,7 +14,7 @@ "@gruperly/shared": "workspace:*", "@hookform/resolvers": "^3.9.0", "@tanstack/react-query": "^5.62.0", - "@tanstack/react-router": "^1.90.0", + "@tanstack/react-router": "^1.170.38", "better-auth": "1.7.2", "clsx": "^2.1.1", "lucide-react": "^1.34.0", @@ -27,6 +27,7 @@ "devDependencies": { "@gruperly/config": "workspace:*", "@tailwindcss/vite": "^4.3.3", + "@tanstack/router-plugin": "^1.168.40", "@types/react": "^19.0.0", "@types/react-dom": "^19.0.0", "@vitejs/plugin-react": "^4.3.0", diff --git a/apps/web/src/components/layout/AppLayoutGuard.tsx b/apps/web/src/components/layout/AppLayoutGuard.tsx index 787a58f..79f5718 100644 --- a/apps/web/src/components/layout/AppLayoutGuard.tsx +++ b/apps/web/src/components/layout/AppLayoutGuard.tsx @@ -1,4 +1,5 @@ import { useEffect } from 'react' +import type { ReactNode } from 'react' import { useQuery } from '@tanstack/react-query' import { useNavigate } from '@tanstack/react-router' import { Loader2 } from 'lucide-react' @@ -6,7 +7,7 @@ import { useAuth } from '../../context/AuthProvider' import { getOnboardingStatus } from '../../lib/api' import { RootLayout } from './RootLayout' -export function AppLayoutGuard() { +export function AppLayoutGuard({ children }: { children: ReactNode }) { const { user, isPending } = useAuth() const navigate = useNavigate() @@ -30,5 +31,5 @@ export function AppLayoutGuard() { ) } - return + return {children} } \ No newline at end of file diff --git a/apps/web/src/components/layout/Header.tsx b/apps/web/src/components/layout/Header.tsx index 163b3d4..c65fe7f 100644 --- a/apps/web/src/components/layout/Header.tsx +++ b/apps/web/src/components/layout/Header.tsx @@ -1,24 +1,8 @@ -import { Moon, Sun } from 'lucide-react' -import { useTheme } from '../../context/ThemeProvider' import { Logo } from '../brand' import { Breadcrumb } from './Breadcrumb' +import { ThemeToggle } from './ThemeToggle' import { UserMenu } from './UserMenu' -function ThemeToggle() { - const { isDark, setTheme } = useTheme() - - return ( - - ) -} - export function Header() { return (
    diff --git a/apps/web/src/components/layout/PublicFooter.tsx b/apps/web/src/components/layout/PublicFooter.tsx new file mode 100644 index 0000000..6703443 --- /dev/null +++ b/apps/web/src/components/layout/PublicFooter.tsx @@ -0,0 +1,7 @@ +export function PublicFooter() { + return ( +
    + Gruperly — Gestión sencilla de cobros y grupos +
    + ) +} \ No newline at end of file diff --git a/apps/web/src/components/layout/PublicHeader.tsx b/apps/web/src/components/layout/PublicHeader.tsx new file mode 100644 index 0000000..0a1e06d --- /dev/null +++ b/apps/web/src/components/layout/PublicHeader.tsx @@ -0,0 +1,14 @@ +import { Link } from '@tanstack/react-router' +import { Logo } from '../brand' +import { ThemeToggle } from './ThemeToggle' + +export function PublicHeader() { + return ( +
    + + + + +
    + ) +} \ No newline at end of file diff --git a/apps/web/src/components/layout/RootLayout.tsx b/apps/web/src/components/layout/RootLayout.tsx index 65ce4d7..bd04f01 100644 --- a/apps/web/src/components/layout/RootLayout.tsx +++ b/apps/web/src/components/layout/RootLayout.tsx @@ -1,9 +1,9 @@ -import { Outlet } from '@tanstack/react-router' +import type { ReactNode } from 'react' import { Header } from './Header' import { Sidebar } from './Sidebar' import { BottomNav } from './BottomNav' -export function RootLayout() { +export function RootLayout({ children }: { children: ReactNode }) { return (
    @@ -11,12 +11,10 @@ export function RootLayout() {
    -
    - -
    +
    {children}
    ) -} \ No newline at end of file +} diff --git a/apps/web/src/components/layout/ThemeToggle.tsx b/apps/web/src/components/layout/ThemeToggle.tsx new file mode 100644 index 0000000..5e0b255 --- /dev/null +++ b/apps/web/src/components/layout/ThemeToggle.tsx @@ -0,0 +1,17 @@ +import { Moon, Sun } from 'lucide-react' +import { useTheme } from '../../context/ThemeProvider' + +export function ThemeToggle() { + const { isDark, setTheme } = useTheme() + + return ( + + ) +} \ No newline at end of file diff --git a/apps/web/src/components/layout/index.ts b/apps/web/src/components/layout/index.ts index d21ba28..6fe960a 100644 --- a/apps/web/src/components/layout/index.ts +++ b/apps/web/src/components/layout/index.ts @@ -1,5 +1,8 @@ export { RootLayout } from './RootLayout' export { Header } from './Header' +export { ThemeToggle } from './ThemeToggle' +export { PublicHeader } from './PublicHeader' +export { PublicFooter } from './PublicFooter' export { Sidebar } from './Sidebar' export { BottomNav } from './BottomNav' export { NAV_ITEMS, type NavItem } from './nav-items' diff --git a/apps/web/src/features/absence-notify/AbsenceNotifyProvider.tsx b/apps/web/src/features/absence-notify/AbsenceNotifyProvider.tsx new file mode 100644 index 0000000..51e68d1 --- /dev/null +++ b/apps/web/src/features/absence-notify/AbsenceNotifyProvider.tsx @@ -0,0 +1,65 @@ +import { createContext, useContext, useState } from 'react' +import type { ReactNode } from 'react' +import { useMutation, useQuery } from '@tanstack/react-query' +import type { AbsenceDetails } from '@gruperly/shared' +import { useToast } from '../../components/ui' +import { ApiError, getAbsenceDetails, publicNotifyAbsence } from '../../lib/api' + +type AbsenceNotifyContextValue = { + token: string + details: AbsenceDetails | undefined + detailsPending: boolean + detailsFailed: boolean + isNotified: (session: { notified: boolean; sessionId: string }) => boolean + isNotifying: (sessionId: string) => boolean + notify: (sessionId: string) => void +} + +const AbsenceNotifyContext = createContext(null) + +export function AbsenceNotifyProvider({ token, children }: { token: string; children: ReactNode }) { + const toast = useToast() + const [locallyNotified, setLocallyNotified] = useState([]) + + const detailsQuery = useQuery({ + queryKey: ['absence-details', token], + queryFn: () => getAbsenceDetails(token), + enabled: Boolean(token), + retry: 1, + }) + + const notifyMutation = useMutation({ + mutationFn: (sessionId: string) => publicNotifyAbsence({ token, classSessionId: sessionId }), + onSuccess: (_data, sessionId) => { + setLocallyNotified((prev) => [...prev, sessionId]) + toast.success('Tu profesor ya tiene registrado el aviso. Gracias por avisar.', 'Ausencia avisada') + }, + onError: (error: unknown) => { + if (error instanceof ApiError && error.problem?.status === 404) { + toast.error('Este enlace ya no es válido. Consultá a tu profesor.') + return + } + toast.error(error instanceof Error ? error.message : 'No pudimos registrar el aviso.') + }, + }) + + const value: AbsenceNotifyContextValue = { + token, + details: detailsQuery.data, + detailsPending: detailsQuery.isPending, + detailsFailed: detailsQuery.isError, + isNotified: (session) => session.notified || locallyNotified.includes(session.sessionId), + isNotifying: (sessionId) => notifyMutation.isPending && notifyMutation.variables === sessionId, + notify: (sessionId) => notifyMutation.mutate(sessionId), + } + + return {children} +} + +export function useAbsenceNotify() { + const context = useContext(AbsenceNotifyContext) + if (!context) { + throw new Error('useAbsenceNotify debe usarse dentro de ') + } + return context +} \ No newline at end of file diff --git a/apps/web/src/features/absence-notify/AbsenceNotifyView.tsx b/apps/web/src/features/absence-notify/AbsenceNotifyView.tsx new file mode 100644 index 0000000..44adcde --- /dev/null +++ b/apps/web/src/features/absence-notify/AbsenceNotifyView.tsx @@ -0,0 +1,71 @@ +import { CalendarX2, Loader2 } from 'lucide-react' +import { PublicFooter, PublicHeader } from '../../components/layout' +import { Badge } from '../../components/ui' +import { AbsenceSessionRow } from './AbsenceSessionRow' +import { useAbsenceNotify } from './AbsenceNotifyProvider' + +export function AbsenceNotifyView() { + const { details, detailsPending, detailsFailed } = useAbsenceNotify() + + return ( +
    + + +
    +
    + {detailsPending ? ( +
    + +

    Cargando tus clases...

    +
    + ) : null} + + {detailsFailed || (!details && !detailsPending) ? ( +
    +

    Enlace no válido

    +

    + No pudimos identificarte con este enlace. Consultá con tu profesor para solicitar uno nuevo. +

    +
    + ) : null} + + {details ? ( +
    +
    +
    + +
    + + Aviso de ausencia + +

    Hola, {details.fullName}

    +

    + Grupo: {details.groupName} +

    +
    + + {details.sessions.length === 0 ? ( +

    + No tenés clases programadas para hoy. Si necesitás avisar de todas formas, contactá a tu + profesor. +

    + ) : ( +
      + {details.sessions.map((session) => ( + + ))} +
    + )} + +

    + Si avisás con anticipación, tu cupo se libera para una clase de recuperación. +

    +
    + ) : null} +
    +
    + + +
    + ) +} \ No newline at end of file diff --git a/apps/web/src/features/absence-notify/AbsenceSessionRow.tsx b/apps/web/src/features/absence-notify/AbsenceSessionRow.tsx new file mode 100644 index 0000000..5b35429 --- /dev/null +++ b/apps/web/src/features/absence-notify/AbsenceSessionRow.tsx @@ -0,0 +1,44 @@ +import { CheckCircle2, Loader2 } from 'lucide-react' +import { Button } from '../../components/ui' +import { useAbsenceNotify } from './AbsenceNotifyProvider' + +type AbsenceSession = { + sessionId: string + startsAt: string + groupName: string + notified: boolean +} + +export function AbsenceSessionRow({ session }: { session: AbsenceSession }) { + const { isNotified, isNotifying, notify } = useAbsenceNotify() + const time = new Date(session.startsAt).toLocaleTimeString('es-MX', { + hour: '2-digit', + minute: '2-digit', + hour12: false, + }) + + return ( +
  • +
    +

    Hoy · {time} hs

    +

    {session.groupName}

    +
    + {isNotified(session) ? ( + + + Ya avisaste + + ) : ( + + )} +
  • + ) +} \ No newline at end of file diff --git a/apps/web/src/features/auth/AuthShell.tsx b/apps/web/src/features/auth/AuthShell.tsx new file mode 100644 index 0000000..885b90d --- /dev/null +++ b/apps/web/src/features/auth/AuthShell.tsx @@ -0,0 +1,25 @@ +import type { ReactNode } from 'react' +import { Logo } from '../../components/brand' + +export type AuthShellProps = { + title: string + subtitle?: string + children: ReactNode +} + +export function AuthShell({ title, subtitle, children }: AuthShellProps) { + return ( +
    +
    +
    + +
    +
    +

    {title}

    + {subtitle ?

    {subtitle}

    : null} +
    {children}
    +
    +
    +
    + ) +} \ No newline at end of file diff --git a/apps/web/src/features/auth/LoginPage.tsx b/apps/web/src/features/auth/LoginPage.tsx new file mode 100644 index 0000000..1d76073 --- /dev/null +++ b/apps/web/src/features/auth/LoginPage.tsx @@ -0,0 +1,113 @@ +import { useForm } from 'react-hook-form' +import { z } from 'zod' +import { zodResolver } from '@hookform/resolvers/zod' +import { Link, useNavigate } from '@tanstack/react-router' +import { Fingerprint, Loader2 } from 'lucide-react' +import { authClient } from '../../lib/auth-client' +import { Button, Input, Label } from '../../components/ui' +import { AuthShell } from './AuthShell' + +const schema = z.object({ + email: z.string().email('Ingresá un email válido'), + password: z.string().min(8, 'La contraseña debe tener al menos 8 caracteres'), +}) + +type FormValues = z.infer + +export function LoginPage() { + const navigate = useNavigate() + const { + register, + handleSubmit, + setError, + formState: { errors, isSubmitting }, + } = useForm({ resolver: zodResolver(schema) }) + + const onSubmit = handleSubmit(async ({ email, password }) => { + const { error } = await authClient.signIn.email({ email, password }) + if (error) { + setError('root', { message: error.message ?? 'No se pudo iniciar sesión' }) + return + } + navigate({ to: '/' }) + }) + + const handleGoogle = async () => { + await authClient.signIn.social({ provider: 'google', callbackURL: '/' }) + } + + const handlePasskey = async () => { + const { error, data } = await authClient.signIn.passkey() + if (error) { + setError('root', { message: error.message ?? 'No se pudo autenticar con passkey' }) + return + } + if (data) navigate({ to: '/' }) + } + + return ( + +
    +
    +
    + + + {errors.email ?

    {errors.email.message}

    : null} +
    + +
    + + + {errors.password ? ( +

    {errors.password.message}

    + ) : null} +
    + + {errors.root ?

    {errors.root.message}

    : null} + + +
    + +
    +
    + o +
    +
    + +
    + + +
    + +

    + ¿No tenés cuenta?{' '} + + Registrate + +

    +
    + + ) +} \ No newline at end of file diff --git a/apps/web/src/features/auth/SignupPage.tsx b/apps/web/src/features/auth/SignupPage.tsx new file mode 100644 index 0000000..27c90d6 --- /dev/null +++ b/apps/web/src/features/auth/SignupPage.tsx @@ -0,0 +1,142 @@ +import { useForm } from 'react-hook-form' +import { z } from 'zod' +import { zodResolver } from '@hookform/resolvers/zod' +import { Link, useNavigate } from '@tanstack/react-router' +import { Loader2 } from 'lucide-react' +import { authClient } from '../../lib/auth-client' +import { Button, Input, Label } from '../../components/ui' +import { AuthShell } from './AuthShell' + +const schema = z + .object({ + name: z.string().min(2, 'Ingresá tu nombre'), + email: z.string().email('Ingresá un email válido'), + password: z.string().min(8, 'La contraseña debe tener al menos 8 caracteres'), + confirmPassword: z.string(), + }) + .refine((v) => v.password === v.confirmPassword, { + message: 'Las contraseñas no coinciden', + path: ['confirmPassword'], + }) + +type FormValues = z.infer + +export function SignupPage() { + const navigate = useNavigate() + const { + register, + handleSubmit, + setError, + formState: { errors, isSubmitting }, + } = useForm({ resolver: zodResolver(schema) }) + + const onSubmit = handleSubmit(async ({ name, email, password }) => { + const { error, data } = await authClient.signUp.email( + { name, email, password }, + { + onSuccess: async () => { + await authClient.getSession() + }, + }, + ) + if (error) { + setError('root', { message: error.message ?? 'No se pudo registrar' }) + return + } + if (data?.token) { + // Con email verification activo, la sesión no se crea hasta verificar. + navigate({ to: '/verify-email', search: { email } }) + } + }) + + const handleGoogle = async () => { + await authClient.signIn.social({ provider: 'google', callbackURL: '/' }) + } + + return ( + +
    +
    +
    + + + {errors.name ?

    {errors.name.message}

    : null} +
    + +
    + + + {errors.email ?

    {errors.email.message}

    : null} +
    + +
    + + + {errors.password ? ( +

    {errors.password.message}

    + ) : null} +
    + +
    + + + {errors.confirmPassword ? ( +

    {errors.confirmPassword.message}

    + ) : null} +
    + + {errors.root ?

    {errors.root.message}

    : null} + + +
    + +
    +
    + o +
    +
    + + + +

    + ¿Ya tenés cuenta?{' '} + + Iniciá sesión + +

    +
    + + ) +} \ No newline at end of file diff --git a/apps/web/src/features/auth/VerifyEmailPage.tsx b/apps/web/src/features/auth/VerifyEmailPage.tsx new file mode 100644 index 0000000..db72a56 --- /dev/null +++ b/apps/web/src/features/auth/VerifyEmailPage.tsx @@ -0,0 +1,91 @@ +import { useEffect, useState } from 'react' +import { Link, useNavigate, useSearch } from '@tanstack/react-router' +import { MailCheck, MailWarning, Loader2 } from 'lucide-react' +import { authClient } from '../../lib/auth-client' +import { AuthShell } from './AuthShell' + +type SearchParams = { + token?: string + email?: string +} + +type Status = 'idle' | 'verifying' | 'success' | 'error' + +export function VerifyEmailPage() { + const { token, email } = useSearch({ strict: false }) as SearchParams + const navigate = useNavigate() + const [status, setStatus] = useState(token ? 'verifying' : 'idle') + + useEffect(() => { + if (!token || status !== 'verifying') return + let cancelled = false + authClient + .verifyEmail({ query: { token } }) + .then(async ({ error }) => { + if (cancelled) return + if (error) { + setStatus('error') + return + } + await authClient.getSession() + navigate({ to: '/' }) + }) + .catch(() => { + if (!cancelled) setStatus('error') + }) + return () => { + cancelled = true + } + }, [token, status, navigate]) + + const title = + status === 'success' + ? 'Email verificado' + : status === 'error' + ? 'Vínculo inválido' + : 'Verificá tu email' + + return ( + +
    + {status === 'verifying' ? ( + + ) : status === 'success' ? ( + + ) : ( + + )} + + {status === 'success' ? ( +

    + Tu cuenta quedó verificada. Te estamos llevando a Gruperly… +

    + ) : status === 'error' ? ( +

    + El vínculo de verificación no es válido o expiró. +

    + ) : ( +

    + Te enviamos un correo a {email} para + confirmar tu cuenta. +

    + )} + + {status === 'success' ? ( + + Ir a Gruperly + + ) : null} + + {status === 'error' ? ( + + Intentar iniciar sesión + + ) : null} +
    +
    + ) +} \ No newline at end of file diff --git a/apps/web/src/features/class-attendance/AttendanceProvider.tsx b/apps/web/src/features/class-attendance/AttendanceProvider.tsx new file mode 100644 index 0000000..464e3d7 --- /dev/null +++ b/apps/web/src/features/class-attendance/AttendanceProvider.tsx @@ -0,0 +1,117 @@ +import { createContext, useContext, useEffect, useMemo, useState } from 'react' +import type { ReactNode } from 'react' +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' +import type { SessionStudents } from '@gruperly/shared' +import { useToast } from '../../components/ui' +import { getSessionStudents, markAttendance } from '../../lib/api' +import { isAttendanceLocked } from './utils' +import type { AttendanceChoice } from './utils' + +type AttendanceContextValue = { + sessionId: string + sessionInfo: SessionStudents | undefined + studentsPending: boolean + studentsFailed: boolean + retryStudents: () => void + startTime: string | null + presentCount: number + choices: Record + choiceFor: (attendeeId: string) => AttendanceChoice + toggleStudent: (attendeeId: string) => void + saveAttendance: () => void + isSaving: boolean +} + +const AttendanceContext = createContext(null) + +export function AttendanceProvider({ sessionId, children }: { sessionId: string; children: ReactNode }) { + const queryClient = useQueryClient() + const toast = useToast() + + const studentsQuery = useQuery({ + queryKey: ['class-students', sessionId], + queryFn: () => getSessionStudents(sessionId), + staleTime: 0, + }) + + const sessionInfo = studentsQuery.data + const [choices, setChoices] = useState>({}) + + useEffect(() => { + if (!sessionInfo) return + const initial: Record = {} + for (const student of sessionInfo.students) { + if (isAttendanceLocked(student)) continue + initial[student.attendeeId] = student.attendanceStatus === 'ABSENT' ? 'ABSENT' : 'PRESENT' + } + setChoices(initial) + }, [sessionInfo]) + + const presentCount = useMemo( + () => + (sessionInfo?.students ?? []).filter( + (student) => !isAttendanceLocked(student) && choices[student.attendeeId] === 'PRESENT', + ).length, + [sessionInfo, choices], + ) + + const toggleStudent = (attendeeId: string) => { + setChoices((prev) => ({ + ...prev, + [attendeeId]: prev[attendeeId] === 'ABSENT' ? 'PRESENT' : 'ABSENT', + })) + } + + const saveMutation = useMutation({ + mutationFn: () => { + const records = (sessionInfo?.students ?? []) + .filter((student) => !isAttendanceLocked(student)) + .map((student) => ({ + attendeeId: student.attendeeId, + status: choices[student.attendeeId] ?? 'PRESENT', + })) + return markAttendance(sessionId, { classSessionId: sessionId, records }) + }, + onSuccess: () => { + toast.success('Asistencia guardada correctamente.', 'Listo') + void queryClient.invalidateQueries({ queryKey: ['classes-today'] }) + void queryClient.invalidateQueries({ queryKey: ['class-students', sessionId] }) + }, + onError: (error: Error) => { + toast.error(error.message || 'No pudimos guardar la asistencia.') + }, + }) + + const startTime = sessionInfo + ? new Date(sessionInfo.startsAt).toLocaleTimeString('es-MX', { + hour: '2-digit', + minute: '2-digit', + hour12: false, + }) + : null + + const value: AttendanceContextValue = { + sessionId, + sessionInfo, + studentsPending: studentsQuery.isPending, + studentsFailed: studentsQuery.isError, + retryStudents: () => void studentsQuery.refetch(), + startTime, + presentCount, + choices, + choiceFor: (attendeeId) => choices[attendeeId] ?? 'PRESENT', + toggleStudent, + saveAttendance: () => saveMutation.mutate(), + isSaving: saveMutation.isPending, + } + + return {children} +} + +export function useAttendance() { + const context = useContext(AttendanceContext) + if (!context) { + throw new Error('useAttendance debe usarse dentro de ') + } + return context +} \ No newline at end of file diff --git a/apps/web/src/features/class-attendance/AttendanceToggle.tsx b/apps/web/src/features/class-attendance/AttendanceToggle.tsx new file mode 100644 index 0000000..2a86162 --- /dev/null +++ b/apps/web/src/features/class-attendance/AttendanceToggle.tsx @@ -0,0 +1,45 @@ +import { Check, X } from 'lucide-react' +import { cn } from '../../lib/utils' +import type { AttendanceChoice } from './utils' + +export function AttendanceToggle({ + choice, + disabled, + onToggle, + fullName, +}: { + choice: AttendanceChoice + disabled?: boolean + onToggle: () => void + fullName: string +}) { + const isPresent = choice === 'PRESENT' + + return ( + + ) +} \ No newline at end of file diff --git a/apps/web/src/features/class-attendance/ClassAttendanceView.tsx b/apps/web/src/features/class-attendance/ClassAttendanceView.tsx new file mode 100644 index 0000000..32e69ee --- /dev/null +++ b/apps/web/src/features/class-attendance/ClassAttendanceView.tsx @@ -0,0 +1,90 @@ +import { Link } from '@tanstack/react-router' +import { ArrowLeft, Loader2 } from 'lucide-react' +import { Badge, Button } from '../../components/ui' +import { useAttendance } from './AttendanceProvider' +import { StudentRow } from './StudentRow' + +export function ClassAttendanceView() { + const { + sessionInfo, + studentsPending, + studentsFailed, + retryStudents, + startTime, + presentCount, + saveAttendance, + isSaving, + } = useAttendance() + + return ( +
    + + + Volver al inicio + + + {studentsPending ? ( +
    + +
    + ) : null} + + {studentsFailed ? ( +
    +

    No pudimos cargar la lista de alumnos.

    + +
    + ) : null} + + {sessionInfo ? ( + <> +
    +
    +
    +

    {sessionInfo.groupName}

    +

    {startTime ? `Hoy · ${startTime} hs` : 'Clase de hoy'}

    +
    + + {presentCount}/{sessionInfo.students.length} presentes + +
    +
    + + {sessionInfo.students.length === 0 ? ( +
    +

    Este grupo no tiene alumnos

    +

    + Agregá miembros desde la ficha del grupo para tomar asistencia. +

    +
    + ) : ( +
      + {sessionInfo.students.map((student) => ( + + ))} +
    + )} + + {sessionInfo.students.length > 0 ? ( +
    + +
    + ) : null} + + ) : null} +
    + ) +} \ No newline at end of file diff --git a/apps/web/src/features/class-attendance/StudentRow.tsx b/apps/web/src/features/class-attendance/StudentRow.tsx new file mode 100644 index 0000000..75e3b4d --- /dev/null +++ b/apps/web/src/features/class-attendance/StudentRow.tsx @@ -0,0 +1,37 @@ +import type { SessionStudentDto } from '@gruperly/shared' +import { Avatar, Badge } from '../../components/ui' +import { AttendanceToggle } from './AttendanceToggle' +import { useAttendance } from './AttendanceProvider' +import { isAttendanceLocked } from './utils' + +function PaymentBadge({ status }: { status: SessionStudentDto['paymentStatus'] }) { + return status === 'UP_TO_DATE' ? Al día : Pendiente +} + +export function StudentRow({ student }: { student: SessionStudentDto }) { + const { choiceFor, toggleStudent } = useAttendance() + const locked = isAttendanceLocked(student) + + return ( +
  • + +
    +

    {student.fullName}

    +
    + + {locked ? Avisó ausencia : null} +
    +
    + toggleStudent(student.attendeeId)} + fullName={student.fullName} + /> +
  • + ) +} \ No newline at end of file diff --git a/apps/web/src/features/class-attendance/utils.ts b/apps/web/src/features/class-attendance/utils.ts new file mode 100644 index 0000000..f397e6e --- /dev/null +++ b/apps/web/src/features/class-attendance/utils.ts @@ -0,0 +1,7 @@ +import type { SessionStudentDto } from '@gruperly/shared' + +export type AttendanceChoice = 'PRESENT' | 'ABSENT' + +export function isAttendanceLocked(student: SessionStudentDto): boolean { + return student.notifiedAbsence || student.attendanceStatus === 'EXCUSED' +} diff --git a/apps/web/src/features/groups/CreateGroupView.tsx b/apps/web/src/features/groups/CreateGroupView.tsx new file mode 100644 index 0000000..ad5fcfa --- /dev/null +++ b/apps/web/src/features/groups/CreateGroupView.tsx @@ -0,0 +1,42 @@ +import { useMutation, useQueryClient } from '@tanstack/react-query' +import { Link, useNavigate } from '@tanstack/react-router' +import type { CreateFirstGroup } from '@gruperly/shared' +import { ChevronLeft } from 'lucide-react' +import { createGroup } from '../../lib/api' +import { GroupForm } from './GroupForm' + +export function CreateGroupView() { + const navigate = useNavigate() + const queryClient = useQueryClient() + + const create = useMutation({ + mutationFn: (values: CreateFirstGroup) => createGroup(values), + onSuccess: (result) => { + void queryClient.invalidateQueries({ queryKey: ['groups'] }) + void navigate({ to: '/groups/$groupId', params: { groupId: result.group.id } }) + }, + }) + + return ( +
    + + + Grupos + + + create.mutate(values)} + /> +
    + ) +} \ No newline at end of file diff --git a/apps/web/src/features/groups/GroupCard.tsx b/apps/web/src/features/groups/GroupCard.tsx new file mode 100644 index 0000000..145cecd --- /dev/null +++ b/apps/web/src/features/groups/GroupCard.tsx @@ -0,0 +1,78 @@ +import { useNavigate } from '@tanstack/react-router' +import type { GroupDto, GroupRiskLevel } from '@gruperly/shared' +import { CalendarClock, Users } from 'lucide-react' +import { Badge, Button } from '../../components/ui' +import { BILLING_LABELS, formatPrice, formatSchedule } from '../../lib/format' +import { cn } from '../../lib/utils' +import { RISK_LABELS } from './constants' + +export function GroupCard({ + group, + riskLevel, +}: { + group: GroupDto + riskLevel: GroupRiskLevel +}) { + const navigate = useNavigate() + const hasSchedule = (group.days?.length ?? 0) > 0 + const hasRisk = riskLevel === 'HIGH' || riskLevel === 'MEDIUM' + + return ( +
    +
    +
    +

    {group.name}

    + {group.description ? ( +

    {group.description}

    + ) : null} +
    +
    + {hasRisk ? ( + + + ) : null} + Activo +
    +
    + + {hasSchedule ? ( +
    +
    + + {formatSchedule(group.days ?? [], group.time)} +
    +
    + + + Cupo {group.capacity ?? '—'} miembros + {group.price != null + ? ` · ${formatPrice(group.price)}${group.billingType ? ` · ${BILLING_LABELS[group.billingType]}` : ''}` + : ''} + {group.dueDay != null ? ` · vence el día ${group.dueDay}` : ''} + +
    +
    + ) : ( +

    Aún sin plan de cobro configurado.

    + )} + +
    + +
    +
    + ) +} \ No newline at end of file diff --git a/apps/web/src/features/groups/GroupForm.tsx b/apps/web/src/features/groups/GroupForm.tsx new file mode 100644 index 0000000..a96a9ce --- /dev/null +++ b/apps/web/src/features/groups/GroupForm.tsx @@ -0,0 +1,231 @@ +import { useForm } from 'react-hook-form' +import { zodResolver } from '@hookform/resolvers/zod' +import type { BillingType, CreateFirstGroup, WeekDay } from '@gruperly/shared' +import { CreateFirstGroupSchema } from '@gruperly/shared' +import { ArrowLeft, Check, Loader2 } from 'lucide-react' +import { cn } from '../../lib/utils' +import { Button, Input, Label } from '../../components/ui' +import { BILLING_TYPES, WEEK_DAY_CHIPS } from '../onboarding/constants' + +const defaultValues: CreateFirstGroup = { + name: '', + days: [], + time: '09:00', + capacity: 1, + price: 0, + billingType: 'MONTHLY', + dueDay: 1, +} + +type GroupFormProps = { + heading: string + description: string + submitLabel: string + isSubmitting: boolean + errorMessage?: string | null + onSubmit: (values: CreateFirstGroup) => void + onBack?: () => void +} + +export function GroupForm({ + heading, + description, + submitLabel, + isSubmitting, + errorMessage, + onSubmit, + onBack, +}: GroupFormProps) { + const { + register, + handleSubmit, + watch, + setValue, + formState: { errors }, + } = useForm({ + resolver: zodResolver(CreateFirstGroupSchema), + defaultValues, + mode: 'onTouched', + }) + + const days = watch('days') + const billingType = watch('billingType') + const dueDay = watch('dueDay') + + const toggleDay = (day: WeekDay) => { + const next = days.includes(day) ? days.filter((d) => d !== day) : [...days, day] + setValue('days', next, { shouldValidate: true }) + } + + const selectBillingType = (type: BillingType) => { + setValue('billingType', type, { shouldValidate: true }) + } + + return ( +
    +
    +

    {heading}

    +

    {description}

    +
    + +
    + + + {errors.name ?

    {errors.name.message}

    : null} +
    + +
    + +
    + {WEEK_DAY_CHIPS.map(({ value, label }) => { + const isActive = days.includes(value) + return ( + + ) + })} +
    + {errors.days ?

    {errors.days.message}

    : null} +
    + +
    + + + {errors.time ?

    {errors.time.message}

    : null} +
    + +
    +
    + + + {errors.capacity ? ( +

    {errors.capacity.message}

    + ) : null} +
    + +
    + +
    + + $ + + +
    + {errors.price ? ( +

    {errors.price.message}

    + ) : null} +
    +
    + +
    + +
    + {BILLING_TYPES.map(({ value, label, hint }) => { + const isActive = billingType === value + return ( + + ) + })} +
    +
    + +
    + + +

    + Los cobros vencerán el día {isFinite(dueDay) && dueDay ? dueDay : '1'} de cada mes. +

    + {errors.dueDay ? ( +

    {errors.dueDay.message}

    + ) : null} +
    + + {errorMessage ? ( +

    {errorMessage}

    + ) : null} + +
    + {onBack ? ( + + ) : null} + +
    +
    + ) +} \ No newline at end of file diff --git a/apps/web/src/features/groups/GroupsView.tsx b/apps/web/src/features/groups/GroupsView.tsx new file mode 100644 index 0000000..76d0ab1 --- /dev/null +++ b/apps/web/src/features/groups/GroupsView.tsx @@ -0,0 +1,81 @@ +import { useQuery } from '@tanstack/react-query' +import { useNavigate } from '@tanstack/react-router' +import { Loader2, Plus } from 'lucide-react' +import { Button } from '../../components/ui' +import { getGroups, getGroupsRiskOverview } from '../../lib/api' +import { GroupCard } from './GroupCard' + +export function GroupsView() { + const navigate = useNavigate() + const groupsQuery = useQuery({ + queryKey: ['groups'], + queryFn: getGroups, + }) + const riskQuery = useQuery({ + queryKey: ['groups-risk-overview'], + queryFn: getGroupsRiskOverview, + }) + + const riskByGroup = new Map( + (riskQuery.data?.items ?? []).map((item) => [item.groupId, item.riskLevel]), + ) + + return ( +
    +
    +
    +

    Grupos

    +

    Tus grupos de cobranza.

    +
    + +
    + + {groupsQuery.isPending ? ( +
    + +
    + ) : null} + + {groupsQuery.isError ? ( +
    +

    No pudimos cargar tus grupos.

    + +
    + ) : null} + + {groupsQuery.isSuccess && groupsQuery.data.data.length === 0 ? ( +
    +

    Todavía no tenés grupos

    +

    + Crea tu primer grupo para empezar a cobrar. +

    + +
    + ) : null} + + {groupsQuery.isSuccess && groupsQuery.data.data.length > 0 ? ( +
    + {groupsQuery.data.data.map((group) => ( + + ))} +
    + ) : null} +
    + ) +} \ No newline at end of file diff --git a/apps/web/src/features/groups/analytics/AnalyticsView.tsx b/apps/web/src/features/groups/analytics/AnalyticsView.tsx new file mode 100644 index 0000000..fd27449 --- /dev/null +++ b/apps/web/src/features/groups/analytics/AnalyticsView.tsx @@ -0,0 +1,219 @@ +import { useState } from 'react' +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' +import { Link, useParams } from '@tanstack/react-router' +import type { StudentAtRiskDto } from '@gruperly/shared' +import { ArrowLeft, CalendarCheck, DoorOpen, Loader2, Percent, Users } from 'lucide-react' +import { Badge, Button, useToast } from '../../../components/ui' +import { getAttendeeHistory, getGroupAnalytics, getStudentsAtRisk, updateAttendeeStatus } from '../../../lib/api' +import { KpiCard } from './KpiCard' +import { AtRiskStudentCard, type StatusAction } from './AtRiskStudentCard' +import { AttendeeHistoryModal } from './AttendeeHistoryModal' +import { StatusActionModal } from './StatusActionModal' + +export function AnalyticsView() { + const { groupId } = useParams({ strict: false }) as { groupId: string } + const queryClient = useQueryClient() + const toast = useToast() + + const [historyStudent, setHistoryStudent] = useState(null) + const [statusAction, setStatusAction] = useState(null) + const [menuOpenFor, setMenuOpenFor] = useState(null) + + const analyticsQuery = useQuery({ + queryKey: ['group-analytics', groupId], + queryFn: () => getGroupAnalytics(groupId), + enabled: Boolean(groupId), + }) + + const riskQuery = useQuery({ + queryKey: ['students-at-risk', groupId], + queryFn: () => getStudentsAtRisk(groupId), + enabled: Boolean(groupId), + }) + + const historyQuery = useQuery({ + queryKey: ['attendee-history', groupId, historyStudent?.attendeeId], + queryFn: () => getAttendeeHistory(groupId, historyStudent!.attendeeId!), + enabled: Boolean(groupId && historyStudent), + }) + + const statusMutation = useMutation({ + mutationFn: (action: Exclude) => + updateAttendeeStatus(action.student.attendeeId, action.status), + onSuccess: (_result, action) => { + const name = action.student.fullName.split(' ')[0] + toast.success( + action.status === 'DROPPED' + ? `${name} fue dado de baja del grupo. Su vacante quedó disponible.` + : `La vacante de ${name} quedó pausada.`, + ) + setStatusAction(null) + void queryClient.invalidateQueries({ queryKey: ['students-at-risk', groupId] }) + void queryClient.invalidateQueries({ queryKey: ['group-attendees', groupId] }) + void queryClient.invalidateQueries({ queryKey: ['group', groupId] }) + void queryClient.invalidateQueries({ queryKey: ['classes-today'] }) + void queryClient.invalidateQueries({ queryKey: ['home-summary'] }) + void queryClient.invalidateQueries({ queryKey: ['groups-risk-overview'] }) + }, + onError: (err: Error) => { + toast.error(err.message || 'No pudimos actualizar el estado del alumno.') + }, + }) + + const handleReengage = async (student: StudentAtRiskDto, groupName: string) => { + if (!student.phone) return + const firstName = student.fullName.split(' ')[0] ?? student.fullName + const message = + `¡Hola ${firstName}! 👋 Te extrañamos en ${groupName}. ` + + 'Notamos que no asististe a las últimas clases y queremos que vuelvas. ' + + 'Si tenés algún problema con tus horarios o tu membresía, escribinos y lo resolvemos juntos.' + const waUrl = `https://wa.me/${student.phone.replace(/\D/g, '')}?text=${encodeURIComponent(message)}` + try { + await navigator.clipboard.writeText(message) + toast.success('¡Abriendo WhatsApp! Mensaje copiado al portapapeles.') + } catch { + // Si clipboard falla, igual abrimos WhatsApp con el mensaje. + } + window.open(waUrl, '_blank', 'noopener,noreferrer') + } + + const groupName = riskQuery.data?.groupName + + if (analyticsQuery.isPending || riskQuery.isPending) { + return ( +
    + +
    + ) + } + + if (analyticsQuery.isError || riskQuery.isError || !analyticsQuery.data) { + return ( +
    +

    No pudimos cargar las estadísticas

    +

    Verificá tu conexión e intentá de nuevo.

    + +
    + ) + } + + const analytics = analyticsQuery.data + const atRisk = riskQuery.data?.data ?? [] + + return ( +
    + + + Volver a {groupName ?? 'el grupo'} + + +
    +
    +

    Estadísticas

    +

    + Asistencia y gestión de riesgo de {groupName ?? 'tu grupo'}. +

    +
    + + Últimos 30 días + +
    + +
    + } + label="Asistencia promedio" + value={`${analytics.attendanceRate}%`} + hint="últimos 30 días" + /> + } + label="Asistencias del mes" + value={analytics.totalPresent.toLocaleString('es-MX')} + hint={`${analytics.totalClasses} clases dictadas`} + /> + } + label="Cupos recuperados" + value={analytics.recoveredSlots.toLocaleString('es-MX')} + hint="por ausencias avisadas" + /> +
    + +
    +
    + +

    Alumnos en riesgo

    + {atRisk.length > 0 ? ( + s.riskLevel === 'HIGH') ? 'danger' : 'warning'}> + {atRisk.length} {atRisk.length === 1 ? 'alumno' : 'alumnos'} + + ) : null} +
    +

    + Alumnos con ausencias consecutivas o baja asistencia mensual. +

    + + {atRisk.length === 0 ? ( +
    +

    ¡Sin alumnos en riesgo!

    +

    + No hay ausencias consecutivas ni asistencia por debajo del 50%. +

    +
    + ) : ( +
      + {atRisk.map((student) => ( + + setMenuOpenFor(menuOpenFor === student.attendeeId ? null : student.attendeeId) + } + onViewHistory={() => setHistoryStudent(student)} + onReengage={() => void handleReengage(student, groupName ?? 'tu clase')} + onRequestStatusAction={(action) => { + setStatusAction(action) + setMenuOpenFor(null) + }} + /> + ))} +
    + )} +
    + + setHistoryStudent(null)} + /> + + setStatusAction(null)} + onConfirm={() => { + if (statusAction) statusMutation.mutate(statusAction) + }} + /> +
    + ) +} \ No newline at end of file diff --git a/apps/web/src/features/groups/analytics/AtRiskStudentCard.tsx b/apps/web/src/features/groups/analytics/AtRiskStudentCard.tsx new file mode 100644 index 0000000..e848394 --- /dev/null +++ b/apps/web/src/features/groups/analytics/AtRiskStudentCard.tsx @@ -0,0 +1,100 @@ +import type { StudentAtRiskDto } from '@gruperly/shared' +import { MessageCircle, MoreVertical, Pause, UserMinus } from 'lucide-react' +import { Avatar, Badge, Button } from '../../../components/ui' +import { cn } from '../../../lib/utils' + +export type StatusAction = { student: StudentAtRiskDto; status: 'PAUSED' | 'DROPPED' } | null + +export function AtRiskStudentCard({ + student, + menuOpen, + onToggleMenu, + onViewHistory, + onReengage, + onRequestStatusAction, +}: { + student: StudentAtRiskDto + menuOpen: boolean + onToggleMenu: () => void + onViewHistory: () => void + onReengage: () => void + onRequestStatusAction: (action: Exclude) => void +}) { + return ( +
  • +
    + + {student.riskLevel === 'HIGH' ? ( + {student.consecutiveAbsences} faltas seguidas + ) : ( + Baja asistencia + )} +
    + +
    + + +
    + + + {menuOpen ? ( + <> + +
    +
  • + ) +} \ No newline at end of file diff --git a/apps/web/src/features/groups/analytics/AttendeeHistoryModal.tsx b/apps/web/src/features/groups/analytics/AttendeeHistoryModal.tsx new file mode 100644 index 0000000..5c7229d --- /dev/null +++ b/apps/web/src/features/groups/analytics/AttendeeHistoryModal.tsx @@ -0,0 +1,80 @@ +import type { StudentAtRiskDto } from '@gruperly/shared' +import { Loader2 } from 'lucide-react' +import { Modal } from '../../../components/ui' +import { cn } from '../../../lib/utils' +import { dotClass, formatSessionDate, sessionStatusTextClass, statusLabel } from './format' + +export function AttendeeHistoryModal({ + student, + sessions, + attendanceRate, + isPending, + isError, + onClose, +}: { + student: StudentAtRiskDto | null + sessions: + | { + classSessionId: string + startsAt: string + status: string | null + }[] + | undefined + attendanceRate: number | undefined + isPending: boolean + isError: boolean + onClose: () => void +}) { + return ( + + {student ? ( +
    + {isPending ? ( +
    + +
    + ) : isError || !sessions ? ( +
    + No pudimos cargar el historial de este alumno. +
    + ) : ( +
    +
    + {attendanceRate}% + + Presentismo general ({sessions.length} clases) + +
    + +
      + {sessions.map((session) => ( +
    • +
    • + ))} +
    +
    + )} +
    + ) : null} +
    + ) +} \ No newline at end of file diff --git a/apps/web/src/features/groups/analytics/KpiCard.tsx b/apps/web/src/features/groups/analytics/KpiCard.tsx new file mode 100644 index 0000000..8b2707a --- /dev/null +++ b/apps/web/src/features/groups/analytics/KpiCard.tsx @@ -0,0 +1,26 @@ +import type { ReactNode } from 'react' + +export function KpiCard({ + icon, + label, + value, + hint, +}: { + icon: ReactNode + label: string + value: string + hint?: string +}) { + return ( +
    +
    + {icon} +
    +
    +

    {label}

    +

    {value}

    + {hint ?

    {hint}

    : null} +
    +
    + ) +} \ No newline at end of file diff --git a/apps/web/src/features/groups/analytics/StatusActionModal.tsx b/apps/web/src/features/groups/analytics/StatusActionModal.tsx new file mode 100644 index 0000000..1d31327 --- /dev/null +++ b/apps/web/src/features/groups/analytics/StatusActionModal.tsx @@ -0,0 +1,72 @@ +import { Loader2, Pause, UserMinus } from 'lucide-react' +import { Button, Modal } from '../../../components/ui' +import { cn } from '../../../lib/utils' +import type { StatusAction } from './AtRiskStudentCard' + +export function StatusActionModal({ + action, + isPending, + groupName, + onCancel, + onConfirm, +}: { + action: StatusAction + isPending: boolean + groupName: string | undefined + onCancel: () => void + onConfirm: () => void +}) { + return ( + + {action ? ( +
    +

    + {action.student.fullName}{' '} + {action.status === 'DROPPED' ? ( + <> + dejará de asistir al grupo y {groupName}. Su + vacante quedará disponible para otro alumno, y + su historial de asistencia se conservará. + + ) : ( + <> + será pausado en{' '} + {groupName}. Su vacante quedará{' '} + libre y podés reactivarla en cualquier + momento. + + )} +

    +
    + + +
    +
    + ) : null} +
    + ) +} \ No newline at end of file diff --git a/apps/web/src/features/groups/analytics/format.ts b/apps/web/src/features/groups/analytics/format.ts new file mode 100644 index 0000000..e521aae --- /dev/null +++ b/apps/web/src/features/groups/analytics/format.ts @@ -0,0 +1,46 @@ +export function statusLabel(status: string | null): string { + switch (status) { + case 'PRESENT': + return 'Presente' + case 'ABSENT': + return 'Ausente' + case 'EXCUSED': + return 'Avisó ausencia' + default: + return 'Sin registrar' + } +} + +export function dotClass(status: string | null): string { + switch (status) { + case 'PRESENT': + return 'bg-success' + case 'ABSENT': + return 'bg-danger' + case 'EXCUSED': + return 'bg-warning' + default: + return 'bg-border' + } +} + +export function sessionStatusTextClass(status: string | null): string { + switch (status) { + case 'PRESENT': + return 'text-success' + case 'ABSENT': + return 'text-danger' + case 'EXCUSED': + return 'text-warning' + default: + return 'text-foreground/50' + } +} + +export function formatSessionDate(iso: string): string { + return new Date(iso).toLocaleDateString('es-MX', { + weekday: 'short', + day: 'numeric', + month: 'short', + }) +} \ No newline at end of file diff --git a/apps/web/src/features/groups/constants.ts b/apps/web/src/features/groups/constants.ts new file mode 100644 index 0000000..2363240 --- /dev/null +++ b/apps/web/src/features/groups/constants.ts @@ -0,0 +1,6 @@ +import type { GroupRiskLevel } from '@gruperly/shared' + +export const RISK_LABELS: Record, string> = { + HIGH: 'Riesgo alto', + MEDIUM: 'Riesgo moderado', +} \ No newline at end of file diff --git a/apps/web/src/features/groups/detail/AddAttendeeModal.tsx b/apps/web/src/features/groups/detail/AddAttendeeModal.tsx new file mode 100644 index 0000000..ea53a73 --- /dev/null +++ b/apps/web/src/features/groups/detail/AddAttendeeModal.tsx @@ -0,0 +1,46 @@ +import { Modal } from '../../../components/ui' +import { cn } from '../../../lib/utils' +import { BulkImportPanel } from './BulkImportPanel' +import { QuickAddForm } from './QuickAddForm' +import { useGroupDetail } from './GroupDetailProvider' + +export function AddAttendeeModal() { + const { isAddAttendeeModalOpen, closeAddAttendeeModal, activeTab, setActiveTab } = useGroupDetail() + + return ( + +
    +
    + + +
    + + {activeTab === 'quick' ? : } +
    +
    + ) +} \ No newline at end of file diff --git a/apps/web/src/features/groups/detail/AttendeeDetailModal.tsx b/apps/web/src/features/groups/detail/AttendeeDetailModal.tsx new file mode 100644 index 0000000..d01ab5f --- /dev/null +++ b/apps/web/src/features/groups/detail/AttendeeDetailModal.tsx @@ -0,0 +1,150 @@ +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}/avisar-ausencia/${selectedAttendee.notifyToken}` + : null + + return ( + setSelectedAttendee(null)} + title="Detalle del Participante" + maxWidth="sm" + > + {selectedAttendee ? ( +
    +
    +
    + {selectedAttendee.fullName.charAt(0).toUpperCase()} +
    +
    +

    {selectedAttendee.fullName}

    +

    + Incorporado el{' '} + {new Date(selectedAttendee.createdAt).toLocaleDateString('es-ES', { + day: 'numeric', + month: 'long', + year: 'numeric', + })} +

    +
    +
    + +
    + } label="Teléfono"> + {selectedAttendee.phone ? ( +
    + {selectedAttendee.phone} + + + WhatsApp + +
    + ) : ( + Sin teléfono + )} +
    + + } label="Email"> + {selectedAttendee.email ? ( + + {selectedAttendee.email} + + ) : ( + Sin email + )} + + + {selectedAttendee.guardianName || selectedAttendee.guardianPhone ? ( + <> + } label="Responsable"> + + {selectedAttendee.guardianName || —} + + + {selectedAttendee.guardianPhone ? ( + } label="Tel. Responsable"> +
    + {selectedAttendee.guardianPhone} + + + +
    +
    + ) : null} + + ) : null} + + } label="Notas"> + {selectedAttendee.notes ? ( + {selectedAttendee.notes} + ) : ( + Sin notas + )} + +
    + + {absenceNotifyUrl ? ( +
    +

    Link para avisar ausencias

    +
    + + {absenceNotifyUrl} + + +
    + {selectedAttendee.phone ? ( + + + Enviar por WhatsApp + + ) : null} +
    + ) : null} + +
    + +
    +
    + ) : null} +
    + ) +} \ No newline at end of file diff --git a/apps/web/src/features/groups/detail/BulkCapacityModal.tsx b/apps/web/src/features/groups/detail/BulkCapacityModal.tsx new file mode 100644 index 0000000..791fc11 --- /dev/null +++ b/apps/web/src/features/groups/detail/BulkCapacityModal.tsx @@ -0,0 +1,41 @@ +import { Check } from 'lucide-react' +import { Button, Modal } from '../../../components/ui' +import { useGroupDetail } from './GroupDetailProvider' + +export function BulkCapacityModal() { + const { + isBulkCapacityModalOpen, + closeBulkCapacityModal, + confirmBulkImportOverCapacity, + validRowsCount, + attendeesTotal, + group, + } = useGroupDetail() + + return ( + +
    +

    + Estás por importar {validRowsCount} miembro(s), pero el + grupo ya tiene {attendeesTotal} inscrito(s) y su cupo es + de {group?.capacity}. ¿Deseas importarlos de todos modos? +

    +
    + + +
    +
    +
    + ) +} \ No newline at end of file diff --git a/apps/web/src/features/groups/detail/BulkImportPanel.tsx b/apps/web/src/features/groups/detail/BulkImportPanel.tsx new file mode 100644 index 0000000..518dccf --- /dev/null +++ b/apps/web/src/features/groups/detail/BulkImportPanel.tsx @@ -0,0 +1,228 @@ +import { useRef } from 'react' +import { Check, Download, FileSpreadsheet, Loader2, Trash2, UploadCloud } from 'lucide-react' +import { Badge, Button, useToast } from '../../../components/ui' +import { + downloadAttendeeTemplateCsv, + normalizeRowsToContacts, + parseCsvContent, + parseXlsxContent, +} from '../../../lib/file-parser' +import { cn } from '../../../lib/utils' +import { useGroupDetail } from './GroupDetailProvider' + +export function BulkImportPanel() { + const { + parsedContacts, + setParsedContacts, + removeParsedContact, + fileName, + setFileName, + isParsingFile, + setIsParsingFile, + isDragging, + setIsDragging, + validRowsCount, + invalidRowsCount, + isSubmittingBulkImport, + closeAddAttendeeModal, + requestBulkImport, + } = useGroupDetail() + const toast = useToast() + const fileInputRef = useRef(null) + + const processFile = async (file: File) => { + const fileExtension = file.name.split('.').pop()?.toLowerCase() + if (!['csv', 'xlsx', 'xls', 'txt'].includes(fileExtension ?? '')) { + toast.error('Formato no compatible. Sube un archivo .csv o .xlsx') + return + } + + setIsParsingFile(true) + setFileName(file.name) + try { + const rawRows = + fileExtension === 'xlsx' || fileExtension === 'xls' + ? await parseXlsxContent(await file.arrayBuffer()) + : parseCsvContent(await file.text()) + + const contacts = normalizeRowsToContacts(rawRows) + if (contacts.length === 0) { + toast.error('No se detectaron contactos en el archivo.') + } else { + setParsedContacts(contacts) + const validCount = contacts.filter((c) => c.isValid).length + toast.info(`Se detectaron ${contacts.length} filas (${validCount} válidas).`) + } + } catch (err: unknown) { + const message = err instanceof Error ? err.message : 'Error al procesar el archivo.' + toast.error(message) + } finally { + setIsParsingFile(false) + } + } + + const handleFileDrop = (e: React.DragEvent) => { + e.preventDefault() + setIsDragging(false) + const file = e.dataTransfer.files[0] + if (file) { + void processFile(file) + } + } + + const handleFileSelect = (e: React.ChangeEvent) => { + const file = e.target.files?.[0] + if (file) { + void processFile(file) + } + } + + return ( +
    +
    { + e.preventDefault() + setIsDragging(true) + }} + onDragLeave={() => setIsDragging(false)} + onDrop={handleFileDrop} + onClick={() => fileInputRef.current?.click()} + className={cn( + 'relative flex cursor-pointer flex-col items-center justify-center rounded-xl border-2 border-dashed p-6 transition-all', + isDragging + ? 'border-accent bg-accent/5' + : 'border-border bg-primary-soft/30 hover:border-accent/60', + )} + > + + +

    + Arrastra tu archivo aquí o haz clic para seleccionarlo +

    +

    Formatos soportados: CSV (.csv) o Excel (.xlsx)

    + + {fileName ? ( +
    + + {fileName} +
    + ) : null} +
    + +
    + ¿No tienes el archivo listo? Usa nuestra plantilla. + +
    + + {isParsingFile ? ( +
    + + Leyendo y analizando archivo... +
    + ) : null} + + {parsedContacts.length > 0 ? ( +
    +
    +
    + Vista Previa: + {validRowsCount} listos para importar + {invalidRowsCount > 0 ? {invalidRowsCount} con errores : null} +
    + + +
    + +
    + + + + + + + + + + + {parsedContacts.map((contact) => ( + + + + + + + + ))} + +
    NombreTeléfonoEmailEstado +
    + {contact.fullName || Sin nombre} + + {contact.phone || Sin teléfono} + {contact.email || '—'} + {contact.isValid ? ( + + Válido + + ) : ( + + {contact.error} + + )} + + +
    +
    + +
    + + +
    +
    + ) : null} +
    + ) +} \ No newline at end of file diff --git a/apps/web/src/features/groups/detail/CapacityModal.tsx b/apps/web/src/features/groups/detail/CapacityModal.tsx new file mode 100644 index 0000000..926f5da --- /dev/null +++ b/apps/web/src/features/groups/detail/CapacityModal.tsx @@ -0,0 +1,61 @@ +import { Clock, Loader2, UserPlus } from 'lucide-react' +import { Button, Modal } from '../../../components/ui' +import { useGroupDetail } from './GroupDetailProvider' + +export function CapacityModal() { + const { + isCapacityModalOpen, + closeCapacityModal, + capacityPayload, + group, + submitForcedAttendee, + submitWaitlistEntry, + isSubmittingForcedAttendee, + isSubmittingWaitlistEntry, + } = useGroupDetail() + const isBusy = isSubmittingForcedAttendee || isSubmittingWaitlistEntry + + return ( + + {capacityPayload ? ( +
    +

    + El grupo {group?.name} ya alcanzó su cupo de{' '} + {group?.capacity} miembros. ¿Qué deseas hacer con{' '} + + {`${capacityPayload.firstName.trim()} ${(capacityPayload.lastName ?? '').trim()}`.trim()} + + ? +

    +
    + + +
    +

    + Si eliges agregarlo de todos modos, el grupo quedará por encima de su cupo. +

    +
    + ) : null} +
    + ) +} \ No newline at end of file diff --git a/apps/web/src/features/groups/detail/DetailRow.tsx b/apps/web/src/features/groups/detail/DetailRow.tsx new file mode 100644 index 0000000..b44d7c4 --- /dev/null +++ b/apps/web/src/features/groups/detail/DetailRow.tsx @@ -0,0 +1,15 @@ +import type { ReactNode } from 'react' + +export function DetailRow({ icon, label, children }: { icon: ReactNode; label: string; children: ReactNode }) { + return ( +
    +
    {icon}
    +
    +

    + {label} +

    +
    {children}
    +
    +
    + ) +} \ No newline at end of file diff --git a/apps/web/src/features/groups/detail/GroupDetailProvider.tsx b/apps/web/src/features/groups/detail/GroupDetailProvider.tsx new file mode 100644 index 0000000..322b3b2 --- /dev/null +++ b/apps/web/src/features/groups/detail/GroupDetailProvider.tsx @@ -0,0 +1,537 @@ +import { createContext, useContext, useMemo, useState } from 'react' +import type { ReactNode } from 'react' +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' +import type { + AttendeeDto, + CreateAttendee, + CreateAttendeeResult, + CreateGroupWaitlistEntry, + GroupDto, + GroupWaitlistEntryDto, + GroupWaitlistList, + GroupRiskLevel, +} from '@gruperly/shared' +import { useToast } from '../../../components/ui' +import type { ParsedContactRow } from '../../../lib/file-parser' +import { + addToGroupWaitlist, + ApiError, + bulkCreateAttendees, + createAttendee, + getGroup, + getGroupAttendees, + getGroupsRiskOverview, + getGroupWaitlist, + getInviteToken, + promoteGroupWaitlistEntry, + removeGroupAttendee, + removeGroupWaitlistEntry, +} from '../../../lib/api' + +export type BulkAttendeeRow = { + firstName: string + lastName: string + fullName: string + phone: string + email?: string + notes?: string +} + +export type ListSection = 'members' | 'waitlist' +export type AddAttendeeTab = 'quick' | 'bulk' + +type GroupDetailContextValue = { + groupId: string + group: GroupDto | undefined + groupQueryPending: boolean + riskLevel: GroupRiskLevel + attendees: AttendeeDto[] + attendeesTotal: number + attendeesPending: boolean + waitlistEntries: GroupWaitlistEntryDto[] + waitlistTotal: number + waitlistPending: boolean + firstWaitlistEntry: GroupWaitlistEntryDto | null + hasFreeCapacity: boolean + inviteUrl: string | undefined + invitePending: boolean + whatsappMessage: string + searchFilter: string + setSearchFilter: (value: string) => void + listSection: ListSection + setListSection: (value: ListSection) => void + activeTab: AddAttendeeTab + setActiveTab: (value: AddAttendeeTab) => void + isInviteModalOpen: boolean + openInviteModal: () => void + closeInviteModal: () => void + isAddAttendeeModalOpen: boolean + openAddAttendeeModal: () => void + closeAddAttendeeModal: () => void + selectedAttendee: AttendeeDto | null + setSelectedAttendee: (attendee: AttendeeDto | null) => void + attendeeToRemove: AttendeeDto | null + requestRemoveAttendee: (attendee: AttendeeDto) => void + cancelRemoveAttendee: () => void + confirmRemoveAttendee: (promoteFromWaitlist: boolean) => void + selectedWaitlistEntry: GroupWaitlistEntryDto | null + setSelectedWaitlistEntry: (entry: GroupWaitlistEntryDto | null) => void + isCapacityModalOpen: boolean + capacityPayload: CreateAttendee | null + closeCapacityModal: () => void + isBulkCapacityModalOpen: boolean + closeBulkCapacityModal: () => void + parsedContacts: ParsedContactRow[] + setParsedContacts: (contacts: ParsedContactRow[]) => void + removeParsedContact: (id: string) => void + fileName: string | null + setFileName: (name: string | null) => void + isParsingFile: boolean + setIsParsingFile: (value: boolean) => void + isDragging: boolean + setIsDragging: (value: boolean) => void + validRowsCount: number + invalidRowsCount: number + isSubmittingAttendee: boolean + isSubmittingForcedAttendee: boolean + isSubmittingWaitlistEntry: boolean + isSubmittingBulkImport: boolean + isSubmittingRemoval: boolean + isSubmittingPromotion: boolean + isSubmittingWaitlistRemoval: boolean + isRegeneratingInvite: boolean + submitQuickAttendee: (payload: CreateAttendee) => void + submitForcedAttendee: () => void + submitWaitlistEntry: () => void + requestBulkImport: () => void + confirmBulkImportOverCapacity: () => void + promoteEntry: (entry: GroupWaitlistEntryDto) => void + removeEntry: (entry: GroupWaitlistEntryDto) => void + regenerateInvite: () => void + copyInviteLink: () => Promise + copyWhatsappMessage: () => Promise + openWhatsapp: () => Promise + copyAbsenceNotifyUrl: (url: string) => void +} + +const GroupDetailContext = createContext(null) + +export function GroupDetailProvider({ groupId, children }: { groupId: string; children: ReactNode }) { + const queryClient = useQueryClient() + const toast = useToast() + + const [isInviteModalOpen, setIsInviteModalOpen] = useState(false) + const [isAddAttendeeModalOpen, setIsAddAttendeeModalOpen] = useState(false) + const [selectedAttendee, setSelectedAttendee] = useState(null) + const [activeTab, setActiveTab] = useState('quick') + const [listSection, setListSection] = useState('members') + const [attendeeToRemove, setAttendeeToRemove] = useState(null) + const [selectedWaitlistEntry, setSelectedWaitlistEntry] = useState(null) + const [isCapacityModalOpen, setIsCapacityModalOpen] = useState(false) + const [pendingCapacityPayload, setPendingCapacityPayload] = useState(null) + const [isBulkCapacityModalOpen, setIsBulkCapacityModalOpen] = useState(false) + const [searchFilter, setSearchFilter] = useState('') + const [parsedContacts, setParsedContacts] = useState([]) + const [fileName, setFileName] = useState(null) + const [isParsingFile, setIsParsingFile] = useState(false) + const [isDragging, setIsDragging] = useState(false) + + const groupQuery = useQuery({ + queryKey: ['group', groupId], + queryFn: () => getGroup(groupId), + enabled: Boolean(groupId), + }) + + const riskOverviewQuery = useQuery({ + queryKey: ['groups-risk-overview'], + queryFn: getGroupsRiskOverview, + enabled: Boolean(groupId), + }) + + const inviteTokenQuery = useQuery({ + queryKey: ['invite-token', groupId], + queryFn: () => getInviteToken(groupId), + enabled: Boolean(groupId) && isInviteModalOpen, + }) + + const attendeesQuery = useQuery({ + queryKey: ['group-attendees', groupId], + queryFn: () => getGroupAttendees(groupId, 1, 100), + enabled: Boolean(groupId), + }) + + const waitlistQuery = useQuery({ + queryKey: ['group-waitlist', groupId], + queryFn: () => getGroupWaitlist(groupId, 1, 100), + enabled: Boolean(groupId), + }) + + const group = groupQuery.data + const attendees = useMemo(() => attendeesQuery.data?.data ?? [], [attendeesQuery.data]) + const attendeesTotal = attendeesQuery.data?.pagination?.total ?? attendees.length + const waitlistEntries = useMemo(() => waitlistQuery.data?.data ?? [], [waitlistQuery.data]) + const waitlistTotal = waitlistQuery.data?.pagination?.total ?? waitlistEntries.length + const firstWaitlistEntry = waitlistEntries[0] ?? null + const hasFreeCapacity = group?.capacity == null || attendeesTotal < group.capacity + + const closeAddAttendeeFlow = () => { + setPendingCapacityPayload(null) + setIsCapacityModalOpen(false) + setIsAddAttendeeModalOpen(false) + } + + const invalidateGroupQueries = () => { + void queryClient.invalidateQueries({ queryKey: ['group-attendees', groupId] }) + void queryClient.invalidateQueries({ queryKey: ['group-waitlist', groupId] }) + void queryClient.invalidateQueries({ queryKey: ['group', groupId] }) + } + + const handleCreateSuccess = (result: CreateAttendeeResult) => { + if (result.outcome === 'created') { + toast.success(`Miembro ${result.attendee.fullName} agregado con éxito.`) + } else { + toast.info(result.message) + } + void queryClient.invalidateQueries({ queryKey: ['group-attendees', groupId] }) + closeAddAttendeeFlow() + } + + const regenerateTokenMutation = useMutation({ + mutationFn: () => getInviteToken(groupId, true), + onSuccess: (data) => { + queryClient.setQueryData(['invite-token', groupId], data) + toast.success('Se generó un nuevo enlace de invitación.') + }, + onError: () => { + toast.error('No se pudo regenerar el enlace de invitación.') + }, + }) + + const createAttendeeMutation = useMutation({ + mutationFn: (payload: CreateAttendee) => createAttendee(groupId, payload), + onMutate: (payload) => setPendingCapacityPayload(payload), + onSuccess: handleCreateSuccess, + onError: (err: Error) => { + if (err instanceof ApiError && err.problem?.code === 'group_capacity_reached') { + setIsCapacityModalOpen(true) + return + } + toast.error(err.message || 'Error al agregar miembro.') + }, + }) + + const createAttendeeForceMutation = useMutation({ + mutationFn: (payload: CreateAttendee) => createAttendee(groupId, payload, { allowOverflow: true }), + onSuccess: handleCreateSuccess, + onError: (err: Error) => { + toast.error(err.message || 'Error al agregar miembro.') + }, + }) + + const addToWaitlistMutation = useMutation({ + mutationFn: (payload: CreateGroupWaitlistEntry) => addToGroupWaitlist(groupId, payload), + onMutate: async (payload: CreateGroupWaitlistEntry) => { + await queryClient.cancelQueries({ queryKey: ['group-waitlist', groupId] }) + const previousWaitlist = queryClient.getQueryData(['group-waitlist', groupId]) + + if (previousWaitlist) { + const optimisticEntry: GroupWaitlistEntryDto = { + id: `temp-${Date.now()}`, + groupId, + fullName: `${payload.firstName} ${payload.lastName ?? ''}`.trim(), + phone: payload.phone, + email: payload.email || null, + notes: payload.notes ?? null, + status: 'PENDING', + createdAt: new Date().toISOString(), + updatedAt: new Date().toISOString(), + } + queryClient.setQueryData(['group-waitlist', groupId], { + data: [optimisticEntry, ...previousWaitlist.data], + pagination: { + ...previousWaitlist.pagination, + total: previousWaitlist.pagination.total + 1, + }, + }) + } + + return { previousWaitlist } + }, + onSuccess: (entry) => { + toast.info(`${entry.fullName} fue agregado a la lista de espera del grupo.`) + invalidateGroupQueries() + closeAddAttendeeFlow() + }, + onError: (err: Error, _payload, context) => { + if (context?.previousWaitlist) { + queryClient.setQueryData(['group-waitlist', groupId], context.previousWaitlist) + } + if (err instanceof ApiError && err.problem?.code === 'already_waitlisted') { + toast.info('Este número ya está en la lista de espera del grupo.') + } else { + toast.error(err.message || 'Error al agregar a la lista de espera.') + } + setPendingCapacityPayload(null) + setIsCapacityModalOpen(false) + }, + }) + + const bulkImportMutation = useMutation({ + mutationFn: (rows: BulkAttendeeRow[]) => bulkCreateAttendees(groupId, { attendees: rows }), + onSuccess: (res) => { + toast.success(res.message) + setParsedContacts([]) + setFileName(null) + void queryClient.invalidateQueries({ queryKey: ['group-attendees', groupId] }) + setIsAddAttendeeModalOpen(false) + }, + onError: (err: Error) => { + toast.error(err.message || 'Error al importar miembros.') + }, + }) + + const removeAttendeeMutation = useMutation({ + mutationFn: (payload: { attendeeId: string; promoteFromWaitlist: boolean }) => + removeGroupAttendee(groupId, payload.attendeeId, { promoteFromWaitlist: payload.promoteFromWaitlist }), + 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({ + mutationFn: (entryId: string) => promoteGroupWaitlistEntry(groupId, entryId), + onSuccess: (result) => { + toast.success(`${result.attendee.fullName} pasó de la lista de espera al grupo.`) + invalidateGroupQueries() + }, + onError: (err: Error) => { + if (err instanceof ApiError && err.problem?.code === 'group_capacity_reached') { + toast.error('El grupo alcanzó su cupo. Quita un miembro o aumenta el cupo primero.') + } else { + toast.error(err.message || 'No se pudo pasar al miembro al grupo.') + } + }, + }) + + const removeWaitlistEntryMutation = useMutation({ + mutationFn: (entry: GroupWaitlistEntryDto) => removeGroupWaitlistEntry(groupId, entry.id), + onSuccess: (_result, entry) => { + toast.success(`${entry.fullName} fue quitado de la lista de espera.`) + invalidateGroupQueries() + }, + onError: (err: Error) => { + toast.error(err.message || 'No se pudo quitar de la lista de espera.') + }, + }) + + const inviteUrl = inviteTokenQuery.data?.inviteUrl + const whatsappMessage = + group && inviteUrl + ? `¡Hola! 👋 Te invito a unirte al grupo *${group.name}*.\n\nCompleta tus datos de inscripción en el siguiente enlace:\n${inviteUrl}` + : '' + const whatsappShareUrl = whatsappMessage + ? `https://wa.me/?text=${encodeURIComponent(whatsappMessage)}` + : '' + + const copyInviteLink = async () => { + if (!inviteUrl) return + try { + await navigator.clipboard.writeText(inviteUrl) + toast.success('¡Enlace de invitación copiado al portapapeles!') + } catch { + toast.error('No se pudo copiar automáticamente. Copia el texto manualmente.') + } + } + + const copyWhatsappMessage = async () => { + if (!whatsappMessage) return + try { + await navigator.clipboard.writeText(whatsappMessage) + toast.success('¡Mensaje copiado al portapapeles!') + } catch { + toast.error('No se pudo copiar automáticamente. Copia el texto manualmente.') + } + } + + const openWhatsapp = async () => { + if (!whatsappShareUrl) return + try { + if (whatsappMessage) { + await navigator.clipboard.writeText(whatsappMessage) + toast.success('¡Abriendo WhatsApp! Mensaje copiado al portapapeles.') + } + } catch { + // Si el portapapeles falla, igual abrimos WhatsApp con el mensaje. + } + 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( + () => + parsedContacts + .filter((contact) => contact.isValid) + .map((contact) => ({ + firstName: contact.firstName, + lastName: contact.lastName, + fullName: contact.fullName, + phone: contact.phone, + email: contact.email || undefined, + notes: contact.notes || undefined, + })), + [parsedContacts], + ) + + const runBulkImport = () => { + if (validRows.length === 0) { + toast.error('No hay miembros válidos para importar.') + return + } + bulkImportMutation.mutate(validRows) + } + + const requestBulkImport = () => { + if (validRows.length === 0) { + toast.error('No hay miembros válidos para importar.') + return + } + if (group?.capacity != null && attendeesTotal + validRows.length > group.capacity) { + setIsBulkCapacityModalOpen(true) + return + } + runBulkImport() + } + + const value: GroupDetailContextValue = { + groupId, + group, + groupQueryPending: groupQuery.isPending, + riskLevel: riskOverviewQuery.data?.items.find((item) => item.groupId === groupId)?.riskLevel ?? 'NONE', + attendees, + attendeesTotal, + attendeesPending: attendeesQuery.isPending, + waitlistEntries, + waitlistTotal, + waitlistPending: waitlistQuery.isPending, + firstWaitlistEntry, + hasFreeCapacity, + inviteUrl, + invitePending: inviteTokenQuery.isPending, + whatsappMessage, + searchFilter, + setSearchFilter, + listSection, + setListSection, + activeTab, + setActiveTab, + isInviteModalOpen, + openInviteModal: () => setIsInviteModalOpen(true), + closeInviteModal: () => setIsInviteModalOpen(false), + isAddAttendeeModalOpen, + openAddAttendeeModal: () => setIsAddAttendeeModalOpen(true), + closeAddAttendeeModal: () => setIsAddAttendeeModalOpen(false), + selectedAttendee, + setSelectedAttendee, + attendeeToRemove, + requestRemoveAttendee: (attendee) => setAttendeeToRemove(attendee), + cancelRemoveAttendee: () => setAttendeeToRemove(null), + confirmRemoveAttendee: (promoteFromWaitlist) => { + if (!attendeeToRemove) return + removeAttendeeMutation.mutate({ + attendeeId: attendeeToRemove.id, + promoteFromWaitlist, + }) + }, + selectedWaitlistEntry, + setSelectedWaitlistEntry, + isCapacityModalOpen, + capacityPayload: pendingCapacityPayload, + closeCapacityModal: () => { + setPendingCapacityPayload(null) + setIsCapacityModalOpen(false) + }, + isBulkCapacityModalOpen, + closeBulkCapacityModal: () => setIsBulkCapacityModalOpen(false), + parsedContacts, + setParsedContacts, + removeParsedContact: (id) => setParsedContacts((prev) => prev.filter((c) => c.id !== id)), + fileName, + setFileName, + isParsingFile, + setIsParsingFile, + isDragging, + setIsDragging, + validRowsCount: validRows.length, + invalidRowsCount: parsedContacts.length - validRows.length, + isSubmittingAttendee: createAttendeeMutation.isPending, + isSubmittingForcedAttendee: createAttendeeForceMutation.isPending, + isSubmittingWaitlistEntry: addToWaitlistMutation.isPending, + isSubmittingBulkImport: bulkImportMutation.isPending, + isSubmittingRemoval: removeAttendeeMutation.isPending, + isSubmittingPromotion: promoteWaitlistMutation.isPending, + isSubmittingWaitlistRemoval: removeWaitlistEntryMutation.isPending, + isRegeneratingInvite: regenerateTokenMutation.isPending, + submitQuickAttendee: (payload) => createAttendeeMutation.mutate(payload), + submitForcedAttendee: () => { + if (pendingCapacityPayload) { + createAttendeeForceMutation.mutate({ ...pendingCapacityPayload }) + } + }, + submitWaitlistEntry: () => { + if (pendingCapacityPayload) { + addToWaitlistMutation.mutate({ ...pendingCapacityPayload }) + } + }, + requestBulkImport, + confirmBulkImportOverCapacity: () => { + setIsBulkCapacityModalOpen(false) + runBulkImport() + }, + promoteEntry: (entry) => { + setSelectedWaitlistEntry(null) + promoteWaitlistMutation.mutate(entry.id) + }, + removeEntry: (entry) => { + setSelectedWaitlistEntry(null) + removeWaitlistEntryMutation.mutate(entry) + }, + regenerateInvite: () => regenerateTokenMutation.mutate(), + copyInviteLink, + copyWhatsappMessage, + openWhatsapp, + copyAbsenceNotifyUrl, + } + + return {children} +} + +export function useGroupDetail() { + const context = useContext(GroupDetailContext) + if (!context) { + throw new Error('useGroupDetail debe usarse dentro de ') + } + return context +} \ No newline at end of file diff --git a/apps/web/src/features/groups/detail/GroupDetailView.tsx b/apps/web/src/features/groups/detail/GroupDetailView.tsx new file mode 100644 index 0000000..2dcb59f --- /dev/null +++ b/apps/web/src/features/groups/detail/GroupDetailView.tsx @@ -0,0 +1,55 @@ +import { useNavigate } from '@tanstack/react-router' +import { Loader2 } from 'lucide-react' +import { Button } from '../../../components/ui' +import { AddAttendeeModal } from './AddAttendeeModal' +import { AttendeeDetailModal } from './AttendeeDetailModal' +import { BulkCapacityModal } from './BulkCapacityModal' +import { CapacityModal } from './CapacityModal' +import { GroupHeader } from './GroupHeader' +import { GroupInfoCard } from './GroupInfoCard' +import { InviteLinkModal } from './InviteLinkModal' +import { MembersWaitlistSection } from './MembersWaitlistSection' +import { RemoveAttendeeModal } from './RemoveAttendeeModal' +import { useGroupDetail } from './GroupDetailProvider' +import { WaitlistEntryDetailModal } from './WaitlistEntryDetailModal' + +export function GroupDetailView() { + const { group, groupQueryPending } = useGroupDetail() + const navigate = useNavigate() + + if (groupQueryPending) { + return ( +
    + +
    + ) + } + + if (!group) { + return ( +
    +

    Grupo no encontrado

    +

    No se pudo cargar la información de este grupo.

    + +
    + ) + } + + return ( +
    + + + + + + + + + + + +
    + ) +} \ No newline at end of file diff --git a/apps/web/src/features/groups/detail/GroupHeader.tsx b/apps/web/src/features/groups/detail/GroupHeader.tsx new file mode 100644 index 0000000..ad1f9e3 --- /dev/null +++ b/apps/web/src/features/groups/detail/GroupHeader.tsx @@ -0,0 +1,77 @@ +import { Link, useNavigate } from '@tanstack/react-router' +import { ArrowLeft, BarChart3, Share2, UserPlus } from 'lucide-react' +import { Badge, Button } from '../../../components/ui' +import { RISK_LABELS } from '../constants' +import { useGroupDetail } from './GroupDetailProvider' + +export function GroupHeader() { + const { group, groupId, riskLevel, openInviteModal, openAddAttendeeModal } = useGroupDetail() + const navigate = useNavigate() + const hasRisk = riskLevel === 'HIGH' || riskLevel === 'MEDIUM' + + return ( +
    + + + Volver a grupos + + +
    +
    +
    +

    {group?.name}

    + Activo + {hasRisk ? ( + + + ) : null} +
    + {group?.description ? ( +

    {group.description}

    + ) : null} +
    + +
    + + + +
    +
    +
    + ) +} \ No newline at end of file diff --git a/apps/web/src/features/groups/detail/GroupInfoCard.tsx b/apps/web/src/features/groups/detail/GroupInfoCard.tsx new file mode 100644 index 0000000..7367125 --- /dev/null +++ b/apps/web/src/features/groups/detail/GroupInfoCard.tsx @@ -0,0 +1,47 @@ +import { CalendarClock, Users } from 'lucide-react' +import { BILLING_LABELS, formatPrice, formatSchedule } from '../../../lib/format' +import { useGroupDetail } from './GroupDetailProvider' + +export function GroupInfoCard() { + const { group, attendees, waitlistTotal } = useGroupDetail() + if (!group) return null + + return ( +
    +
    + +
    +

    Horario

    +

    + {(group.days?.length ?? 0) > 0 + ? formatSchedule(group.days ?? [], group.time) + : 'Sin horario definido'} +

    +
    +
    + +
    + +
    +

    Miembros & Cupo

    +

    + {attendees.length} inscritos {waitlistTotal > 0 ? ` · ${waitlistTotal} en espera` : ''} + {group.capacity ? ` · Cupo de ${group.capacity}` : ''} +

    +
    +
    + +
    +
    $
    +
    +

    Cobro

    +

    + {group.price != null ? formatPrice(group.price) : 'Sin precio'} + {group.billingType ? ` · ${BILLING_LABELS[group.billingType]}` : ''} + {group.dueDay ? ` · Vence día ${group.dueDay}` : ''} +

    +
    +
    +
    + ) +} \ No newline at end of file diff --git a/apps/web/src/features/groups/detail/InviteLinkModal.tsx b/apps/web/src/features/groups/detail/InviteLinkModal.tsx new file mode 100644 index 0000000..2a29b80 --- /dev/null +++ b/apps/web/src/features/groups/detail/InviteLinkModal.tsx @@ -0,0 +1,117 @@ +import { Copy, Loader2, MessageCircle, RefreshCw } from 'lucide-react' +import { Button, Input, Label, Modal } from '../../../components/ui' +import { cn } from '../../../lib/utils' +import { useGroupDetail } from './GroupDetailProvider' + +export function InviteLinkModal() { + const { + isInviteModalOpen, + closeInviteModal, + group, + inviteUrl, + invitePending, + isRegeneratingInvite, + regenerateInvite, + copyInviteLink, + copyWhatsappMessage, + openWhatsapp, + } = useGroupDetail() + + return ( + +
    + {invitePending ? ( +
    + +
    + ) : ( + <> +
    + +
    + + +
    +
    + +
    +
    +

    Vista previa del mensaje para WhatsApp:

    + +
    +
    + {`¡Hola! 👋 Te invito a unirte al grupo `} + {group?.name}. + {'\n\n'} + Completa tus datos de inscripción en el siguiente enlace: + {'\n'} + {inviteUrl} +
    +
    + +
    + + + +
    + +

    + Al hacer clic en Abrir en WhatsApp, el mensaje completo se copia + automáticamente al portapapeles. Si WhatsApp Web solo carga el enlace, podés pegarlo + directamente con Ctrl+V{' '} + o Cmd+V. +

    + + )} +
    +
    + ) +} \ No newline at end of file diff --git a/apps/web/src/features/groups/detail/MembersTable.tsx b/apps/web/src/features/groups/detail/MembersTable.tsx new file mode 100644 index 0000000..b3b154a --- /dev/null +++ b/apps/web/src/features/groups/detail/MembersTable.tsx @@ -0,0 +1,45 @@ +import type { AttendeeDto } from '@gruperly/shared' +import { ChevronRight } from 'lucide-react' +import { useGroupDetail } from './GroupDetailProvider' + +export function MembersTable({ attendees }: { attendees: AttendeeDto[] }) { + const { setSelectedAttendee } = useGroupDetail() + + return ( +
    + + + + + + + + + {attendees.map((attendee) => ( + setSelectedAttendee(attendee)} + > + + + + + ))} + +
    NombreTeléfono +
    +
    +
    + {attendee.fullName.charAt(0).toUpperCase()} +
    + {attendee.fullName} +
    +
    + {attendee.phone || —} + + +
    +
    + ) +} \ No newline at end of file diff --git a/apps/web/src/features/groups/detail/MembersWaitlistSection.tsx b/apps/web/src/features/groups/detail/MembersWaitlistSection.tsx new file mode 100644 index 0000000..301dc08 --- /dev/null +++ b/apps/web/src/features/groups/detail/MembersWaitlistSection.tsx @@ -0,0 +1,146 @@ +import { Clock, Loader2, Plus, Search, Share2, Users } from 'lucide-react' +import { Button, Input } from '../../../components/ui' +import { cn } from '../../../lib/utils' +import { useGroupDetail } from './GroupDetailProvider' +import { MembersTable } from './MembersTable' +import { WaitlistTable } from './WaitlistTable' + +export function MembersWaitlistSection() { + const { + attendees, + attendeesTotal, + attendeesPending, + waitlistEntries, + waitlistTotal, + waitlistPending, + listSection, + setListSection, + searchFilter, + setSearchFilter, + openInviteModal, + openAddAttendeeModal, + } = useGroupDetail() + + const query = searchFilter.toLowerCase() + const filteredAttendees = attendees.filter( + (a) => + a.fullName.toLowerCase().includes(query) || + (a.phone && a.phone.includes(query)) || + (a.email && a.email.toLowerCase().includes(query)), + ) + + return ( +
    +
    +
    +
    + + +
    + + {listSection === 'members' ? ( +
    + + setSearchFilter(e.target.value)} + className="h-9 pl-9 text-xs" + /> +
    + ) : null} +
    + +

    + {listSection === 'members' + ? 'Listado de todos los miembros incorporados al grupo.' + : 'Personas que esperan un cupo libre en el grupo. Al pasar a alguien al grupo, se crea automáticamente su registro como miembro.'} +

    +
    + + {listSection === 'members' ? ( + <> + {attendeesPending ? ( +
    + +
    + ) : null} + + {!attendeesPending && attendees.length === 0 ? ( +
    + +

    Todavía no hay miembros en este grupo

    +

    + Puedes compartir el enlace de invitación único o agregar miembros de forma manual o + masiva. +

    +
    + + +
    +
    + ) : null} + + {attendees.length > 0 && filteredAttendees.length === 0 ? ( +
    + No se encontraron miembros que coincidan con la búsqueda. +
    + ) : null} + + {filteredAttendees.length > 0 ? : null} + + ) : ( +
    + {waitlistPending ? ( +
    + +
    + ) : null} + + {!waitlistPending && waitlistEntries.length === 0 ? ( +
    + +

    No hay nadie en la lista de espera

    +

    + Cuando el grupo alcance su cupo, las personas podrán sumarse a la espera y podrás + pasarlas al grupo desde aquí. +

    +
    + ) : null} + + {waitlistEntries.length > 0 ? : null} +
    + )} +
    + ) +} \ No newline at end of file diff --git a/apps/web/src/features/groups/detail/QuickAddForm.tsx b/apps/web/src/features/groups/detail/QuickAddForm.tsx new file mode 100644 index 0000000..6d2b94b --- /dev/null +++ b/apps/web/src/features/groups/detail/QuickAddForm.tsx @@ -0,0 +1,124 @@ +import { useState } from 'react' +import { Check, Loader2 } from 'lucide-react' +import { Button, Input, Label, useToast } from '../../../components/ui' +import { useGroupDetail } from './GroupDetailProvider' + +export function QuickAddForm() { + const { submitQuickAttendee, isSubmittingAttendee, closeAddAttendeeModal } = useGroupDetail() + const toast = useToast() + const [firstName, setFirstName] = useState('') + const [lastName, setLastName] = useState('') + const [phone, setPhone] = useState('') + const [email, setEmail] = useState('') + const [notes, setNotes] = useState('') + + const handleSubmit = (e: React.FormEvent) => { + e.preventDefault() + if (!firstName.trim() || !phone.trim()) { + toast.error('Nombre y teléfono son obligatorios.') + return + } + submitQuickAttendee({ + firstName: firstName.trim(), + lastName: lastName.trim(), + phone: phone.trim(), + email: email.trim() || undefined, + notes: notes.trim() || undefined, + }) + } + + const resetForm = () => { + setFirstName('') + setLastName('') + setPhone('') + setEmail('') + setNotes('') + } + + return ( +
    +
    +
    + + setFirstName(e.target.value)} + required + /> +
    +
    + + setLastName(e.target.value)} + /> +
    +
    + +
    + + setPhone(e.target.value)} + required + /> +

    + Usado para contacto y validación de duplicados. +

    +
    + +
    + + setEmail(e.target.value)} + /> +
    + +
    + + setNotes(e.target.value)} + /> +
    + +
    + + +
    +
    + ) +} \ No newline at end of file diff --git a/apps/web/src/features/groups/detail/RemoveAttendeeModal.tsx b/apps/web/src/features/groups/detail/RemoveAttendeeModal.tsx new file mode 100644 index 0000000..445e545 --- /dev/null +++ b/apps/web/src/features/groups/detail/RemoveAttendeeModal.tsx @@ -0,0 +1,99 @@ +import { Clock, Loader2, Trash2, UserCheck, UserMinus } from 'lucide-react' +import { Button, Modal } from '../../../components/ui' +import { useGroupDetail } from './GroupDetailProvider' + +export function RemoveAttendeeModal() { + const { + attendeeToRemove, + cancelRemoveAttendee, + confirmRemoveAttendee, + group, + firstWaitlistEntry, + waitlistTotal, + isSubmittingRemoval, + } = useGroupDetail() + + return ( + + {attendeeToRemove ? ( +
    +

    + {attendeeToRemove.fullName} dejará de ser miembro del grupo{' '} + {group?.name} + {firstWaitlistEntry ? ' y el cupo quedará libre.' : '.'} + {attendeeToRemove.phone ? ( + Teléfono: {attendeeToRemove.phone} + ) : null} +

    + + {firstWaitlistEntry ? ( +
    +
    + + + Hay {waitlistTotal} persona{waitlistTotal === 1 ? '' : 's'} esperando un cupo + +
    +

    + ¿Quieres pasar a {firstWaitlistEntry.fullName}, el + primero de la lista de espera, al grupo? +

    +
    + + +
    +
    + ) : ( +
    + + +
    + )} +
    + ) : null} +
    + ) +} \ No newline at end of file diff --git a/apps/web/src/features/groups/detail/WaitlistEntryDetailModal.tsx b/apps/web/src/features/groups/detail/WaitlistEntryDetailModal.tsx new file mode 100644 index 0000000..2c651f1 --- /dev/null +++ b/apps/web/src/features/groups/detail/WaitlistEntryDetailModal.tsx @@ -0,0 +1,118 @@ +import { Loader2, Mail, MessageCircle, Phone, StickyNote, Trash2, UserCheck } from 'lucide-react' +import { Button, Modal } from '../../../components/ui' +import { DetailRow } from './DetailRow' +import { useGroupDetail } from './GroupDetailProvider' + +export function WaitlistEntryDetailModal() { + const { + selectedWaitlistEntry, + setSelectedWaitlistEntry, + hasFreeCapacity, + promoteEntry, + removeEntry, + isSubmittingPromotion, + isSubmittingWaitlistRemoval, + } = useGroupDetail() + + return ( + setSelectedWaitlistEntry(null)} + title="Detalle de la lista de espera" + maxWidth="sm" + > + {selectedWaitlistEntry ? ( +
    +
    +
    + {selectedWaitlistEntry.fullName.charAt(0).toUpperCase()} +
    +
    +

    {selectedWaitlistEntry.fullName}

    +

    + En espera desde el{' '} + {new Date(selectedWaitlistEntry.createdAt).toLocaleDateString('es-ES', { + day: 'numeric', + month: 'long', + year: 'numeric', + })} +

    +
    +
    + +
    + } label="Teléfono"> + {selectedWaitlistEntry.phone ? ( +
    + {selectedWaitlistEntry.phone} + + + WhatsApp + +
    + ) : ( + Sin teléfono + )} +
    + + {selectedWaitlistEntry.email ? ( + } label="Email"> + + {selectedWaitlistEntry.email} + + + ) : null} + + } label="Notas"> + {selectedWaitlistEntry.notes ? ( + {selectedWaitlistEntry.notes} + ) : ( + Sin notas + )} + +
    + + {!hasFreeCapacity ? ( +

    + El grupo alcanzó su cupo de miembros. Quita un miembro o aumenta el cupo para poder pasar a esta + persona al grupo. +

    + ) : null} + +
    + + +
    +
    + ) : null} +
    + ) +} \ No newline at end of file diff --git a/apps/web/src/features/groups/detail/WaitlistTable.tsx b/apps/web/src/features/groups/detail/WaitlistTable.tsx new file mode 100644 index 0000000..fe51b85 --- /dev/null +++ b/apps/web/src/features/groups/detail/WaitlistTable.tsx @@ -0,0 +1,48 @@ +import type { GroupWaitlistEntryDto } from '@gruperly/shared' +import { ChevronRight } from 'lucide-react' +import { useGroupDetail } from './GroupDetailProvider' + +export function WaitlistTable({ entries }: { entries: GroupWaitlistEntryDto[] }) { + const { setSelectedWaitlistEntry } = useGroupDetail() + + return ( +
    + + + + + + + + + {entries.map((entry) => ( + setSelectedWaitlistEntry(entry)} + > + + + + + ))} + +
    NombreTeléfono +
    +
    +
    + {entry.fullName.charAt(0).toUpperCase()} +
    +
    +

    {entry.fullName}

    + {entry.notes ? ( +

    {entry.notes}

    + ) : null} +
    +
    +
    {entry.phone} + +
    +
    + ) +} \ No newline at end of file diff --git a/apps/web/src/features/home/HomeView.tsx b/apps/web/src/features/home/HomeView.tsx new file mode 100644 index 0000000..bc58b66 --- /dev/null +++ b/apps/web/src/features/home/HomeView.tsx @@ -0,0 +1,108 @@ +import { useQuery } from '@tanstack/react-query' +import { useNavigate } from '@tanstack/react-router' +import { Loader2, Plus } from 'lucide-react' +import { Button } from '../../components/ui' +import { getClassesToday, getHomeSummary } from '../../lib/api' +import { SummaryStats } from './SummaryStats' +import { TodayClassCard } from './TodayClassCard' +import { NextClassHero } from './NextClassHero' +import { UpcomingPaymentRow } from './UpcomingPaymentRow' + +export function HomeView() { + const navigate = useNavigate() + const summaryQuery = useQuery({ + queryKey: ['home-summary'], + queryFn: getHomeSummary, + }) + const classesTodayQuery = useQuery({ + queryKey: ['classes-today'], + queryFn: getClassesToday, + staleTime: 60_000, + }) + const todayClasses = classesTodayQuery.data?.data ?? [] + + return ( +
    +
    +

    Inicio

    +

    Tu actividad de cobros de un vistazo.

    +
    + + {summaryQuery.isPending ? ( +
    + +
    + ) : null} + + {summaryQuery.isError ? ( +
    +

    No pudimos cargar tu resumen.

    + +
    + ) : null} + + {summaryQuery.isSuccess && summaryQuery.data.stats.groups === 0 ? ( +
    +

    Todavía no tenés grupos

    +

    + Crea tu primer grupo para empezar a cobrar. +

    + +
    + ) : null} + + {summaryQuery.isSuccess && summaryQuery.data.stats.groups > 0 ? ( +
    + {todayClasses.length > 0 ? ( +
    + {todayClasses.map((classItem) => ( + + ))} +
    + ) : summaryQuery.data.nextClass ? ( + + ) : ( +
    +

    Sin clases programadas

    +

    + Agregá días y horario a tus grupos para ver tu próxima clase acá. +

    +
    + )} + + + +
    +
    +

    Próximos cobros

    + +
    + + {summaryQuery.data.upcomingPayments.length > 0 ? ( +
      + {summaryQuery.data.upcomingPayments.map((payment) => ( + + ))} +
    + ) : ( +

    + Sin cobros pendientes por ahora. +

    + )} +
    +
    + ) : null} +
    + ) +} \ No newline at end of file diff --git a/apps/web/src/features/home/NextClassHero.tsx b/apps/web/src/features/home/NextClassHero.tsx new file mode 100644 index 0000000..fab5834 --- /dev/null +++ b/apps/web/src/features/home/NextClassHero.tsx @@ -0,0 +1,43 @@ +import { useNavigate } from '@tanstack/react-router' +import type { NextClassDto } from '@gruperly/shared' +import { CalendarClock } from 'lucide-react' +import { Badge, Button } from '../../components/ui' +import { formatRelativeDateTime, formatSchedule } from '../../lib/format' + +export function NextClassHero({ nextClass }: { nextClass: NextClassDto }) { + const navigate = useNavigate() + const hasSchedule = (nextClass.days?.length ?? 0) > 0 + + return ( +
    +
    +
    +

    + {nextClass.isNow ? 'Clase en curso' : 'Próxima clase'} +

    +

    {nextClass.name}

    + {hasSchedule ? ( +
    + + {formatSchedule(nextClass.days ?? [], nextClass.time)} +
    + ) : null} +
    +
    + + {nextClass.isNow ? 'En curso ahora' : formatRelativeDateTime(nextClass.occurrenceAt)} + +
    +
    +
    + +
    +
    + ) +} \ No newline at end of file diff --git a/apps/web/src/features/home/SummaryStats.tsx b/apps/web/src/features/home/SummaryStats.tsx new file mode 100644 index 0000000..4dfe454 --- /dev/null +++ b/apps/web/src/features/home/SummaryStats.tsx @@ -0,0 +1,67 @@ +import { useNavigate } from '@tanstack/react-router' +import type { HomeSummaryDto } from '@gruperly/shared' +import { UserCheck, Users, Wallet, type LucideIcon } from 'lucide-react' +import { cn } from '../../lib/utils' +import { formatPrice } from '../../lib/format' + +type StatTarget = '/groups' | '/payments' + +export function SummaryStats({ summary }: { summary: HomeSummaryDto }) { + const navigate = useNavigate() + const stats: { + label: string + value: string + sub?: string + icon: LucideIcon + to: StatTarget + }[] = [ + { + label: 'Grupos activos', + value: String(summary.stats.groups), + icon: Users, + to: '/groups', + }, + { + label: 'Cobros pendientes', + value: summary.stats.pendingAmount > 0 ? formatPrice(summary.stats.pendingAmount) : '0', + sub: `${summary.stats.pendingPayments} por cobrar`, + icon: Wallet, + to: '/payments', + }, + { + label: 'Asistentes', + value: String(summary.stats.attendees), + icon: UserCheck, + to: '/groups', + }, + ] + + return ( +
    + {stats.map((stat) => { + const Icon = stat.icon + return ( + + ) + })} +
    + ) +} \ No newline at end of file diff --git a/apps/web/src/features/home/TodayClassCard.tsx b/apps/web/src/features/home/TodayClassCard.tsx new file mode 100644 index 0000000..f5099b2 --- /dev/null +++ b/apps/web/src/features/home/TodayClassCard.tsx @@ -0,0 +1,58 @@ +import { useNavigate } from '@tanstack/react-router' +import type { ClassTodayDto } from '@gruperly/shared' +import { CalendarClock, ClipboardCheck } from 'lucide-react' +import { Badge, Button } from '../../components/ui' + +export function TodayClassCard({ item }: { item: ClassTodayDto }) { + const navigate = useNavigate() + const time = new Date(item.startsAt).toLocaleTimeString('es-MX', { + hour: '2-digit', + minute: '2-digit', + hour12: false, + }) + + return ( +
    +
    +
    +

    + Clase de hoy +

    +

    {item.groupName}

    +
    + + Hoy · {time} hs +
    +

    + {item.enrolledCount} inscrito{item.enrolledCount === 1 ? '' : 's'} + {item.availableSlots != null + ? ` · ${item.availableSlots} cupo${item.availableSlots === 1 ? '' : 's'} disponible${item.availableSlots === 1 ? '' : 's'}` + : ''} +

    +
    +
    + + {item.hasAttendance ? 'Asistencia tomada' : 'Por tomar'} + +
    +
    +
    + + +
    +
    + ) +} \ No newline at end of file diff --git a/apps/web/src/features/home/UpcomingPaymentRow.tsx b/apps/web/src/features/home/UpcomingPaymentRow.tsx new file mode 100644 index 0000000..7571ad9 --- /dev/null +++ b/apps/web/src/features/home/UpcomingPaymentRow.tsx @@ -0,0 +1,23 @@ +import type { UpcomingPaymentDto } from '@gruperly/shared' +import { Badge } from '../../components/ui' +import { formatPrice, formatRelativeDateTime, PAYMENT_STATUS_LABELS } from '../../lib/format' +import { PAYMENT_BADGE_VARIANT } from './constants' + +export function UpcomingPaymentRow({ payment }: { payment: UpcomingPaymentDto }) { + return ( +
  • +
    +

    {payment.attendeeName}

    +

    + {payment.groupName} · {formatRelativeDateTime(payment.dueDate)} +

    +
    +
    + {formatPrice(payment.amount)} + + {PAYMENT_STATUS_LABELS[payment.status]} + +
    +
  • + ) +} \ No newline at end of file diff --git a/apps/web/src/features/home/constants.ts b/apps/web/src/features/home/constants.ts new file mode 100644 index 0000000..18cb8c0 --- /dev/null +++ b/apps/web/src/features/home/constants.ts @@ -0,0 +1,10 @@ +import type { PaymentDto } from '@gruperly/shared' + +export type PaymentBadgeVariant = 'success' | 'warning' | 'danger' | 'neutral' + +export const PAYMENT_BADGE_VARIANT: Record = { + PENDING: 'warning', + OVERDUE: 'danger', + PAID: 'success', + CANCELLED: 'neutral', +} \ No newline at end of file diff --git a/apps/web/src/features/join/GroupInviteSummary.tsx b/apps/web/src/features/join/GroupInviteSummary.tsx new file mode 100644 index 0000000..35a9c33 --- /dev/null +++ b/apps/web/src/features/join/GroupInviteSummary.tsx @@ -0,0 +1,48 @@ +import { CalendarClock, GraduationCap, Users } from 'lucide-react' +import { Badge } from '../../components/ui' +import { BILLING_LABELS, formatPrice, formatSchedule } from '../../lib/format' +import { useJoinGroup } from './JoinGroupProvider' + +export function GroupInviteSummary() { + const { group } = useJoinGroup() + if (!group) return null + + return ( +
    +
    + + + Invitación Oficial + +
    +

    {group.name}

    +

    + Profesor: {group.teacherName} +

    + {group.description ?

    {group.description}

    : null} + +
    + {(group.days?.length ?? 0) > 0 ? ( +
    + + {formatSchedule(group.days ?? [], group.time)} +
    + ) : null} + + {group.price != null ? ( +
    + {formatPrice(group.price)} + {group.billingType ? · {BILLING_LABELS[group.billingType]} : ''} +
    + ) : null} + + {group.capacity ? ( +
    + + Cupo {group.capacity} +
    + ) : null} +
    +
    + ) +} \ No newline at end of file diff --git a/apps/web/src/features/join/InvalidInviteCard.tsx b/apps/web/src/features/join/InvalidInviteCard.tsx new file mode 100644 index 0000000..adcfe8e --- /dev/null +++ b/apps/web/src/features/join/InvalidInviteCard.tsx @@ -0,0 +1,11 @@ +export function InvalidInviteCard() { + return ( +
    +

    Enlace no válido o expirado

    +

    + No pudimos encontrar este grupo. Por favor consulta con tu profesor para solicitar un nuevo enlace de + invitación. +

    +
    + ) +} \ No newline at end of file diff --git a/apps/web/src/features/join/JoinForm.tsx b/apps/web/src/features/join/JoinForm.tsx new file mode 100644 index 0000000..f37c5c3 --- /dev/null +++ b/apps/web/src/features/join/JoinForm.tsx @@ -0,0 +1,113 @@ +import { Loader2 } from 'lucide-react' +import { Button, Input, Label } from '../../components/ui' +import { useJoinGroup } from './JoinGroupProvider' + +export function JoinForm() { + const { + firstName, + setFirstName, + lastName, + setLastName, + phone, + setPhone, + email, + setEmail, + errorMessage, + submit, + isSubmitting, + } = useJoinGroup() + + return ( +
    +
    +

    Completa tus datos

    +

    + Ingresa tus datos para registrarte en la lista de alumnos de este grupo. +

    +
    + + {errorMessage ? ( +
    + {errorMessage} +
    + ) : null} + +
    { + e.preventDefault() + submit() + }} + className="space-y-4" + > +
    +
    + + setFirstName(e.target.value)} + required + /> +
    + +
    + + setLastName(e.target.value)} + required + /> +
    +
    + +
    + + setPhone(e.target.value)} + required + /> +

    + El profesor se comunicará contigo por WhatsApp a este número. +

    +
    + +
    + + setEmail(e.target.value)} + /> +
    + +
    + +
    +
    +
    + ) +} \ No newline at end of file diff --git a/apps/web/src/features/join/JoinGroupProvider.tsx b/apps/web/src/features/join/JoinGroupProvider.tsx new file mode 100644 index 0000000..33cdb2b --- /dev/null +++ b/apps/web/src/features/join/JoinGroupProvider.tsx @@ -0,0 +1,128 @@ +import { createContext, useContext, useState } from 'react' +import type { ReactNode } from 'react' +import { useMutation, useQuery } from '@tanstack/react-query' +import type { GroupInviteInfoDto } from '@gruperly/shared' +import { ApiError, getInviteInfo, joinViaInvite } from '../../lib/api' + +type RegisteredAttendee = { + fullName: string + phone: string | null +} + +type JoinGroupContextValue = { + token: string + group: GroupInviteInfoDto | undefined + invitePending: boolean + inviteFailed: boolean + firstName: string + setFirstName: (value: string) => void + lastName: string + setLastName: (value: string) => void + phone: string + setPhone: (value: string) => void + email: string + setEmail: (value: string) => void + errorMessage: string | null + registeredAttendee: RegisteredAttendee | null + waitlistMessage: string | null + submit: () => void + isSubmitting: boolean +} + +const JoinGroupContext = createContext(null) + +export function JoinGroupProvider({ token, children }: { token: string; children: ReactNode }) { + const [firstName, setFirstName] = useState('') + const [lastName, setLastName] = useState('') + const [phone, setPhone] = useState('') + const [email, setEmail] = useState('') + const [errorMessage, setErrorMessage] = useState(null) + const [registeredAttendee, setRegisteredAttendee] = useState(null) + const [waitlistMessage, setWaitlistMessage] = useState(null) + + const inviteQuery = useQuery({ + queryKey: ['public-invite', token], + queryFn: () => getInviteInfo(token), + enabled: Boolean(token), + retry: 1, + }) + + const joinMutation = useMutation({ + mutationFn: () => + joinViaInvite(token, { + firstName: firstName.trim(), + lastName: lastName.trim(), + phone: phone.trim(), + email: email.trim() || undefined, + }), + onSuccess: (data) => { + setErrorMessage(null) + if (data.status === 'waitlisted') { + setRegisteredAttendee(null) + setWaitlistMessage(data.message) + return + } + setWaitlistMessage(null) + setRegisteredAttendee({ + fullName: data.attendee?.fullName ?? `${firstName.trim()} ${lastName.trim()}`.trim(), + phone: data.attendee?.phone ?? null, + }) + }, + onError: (error: unknown) => { + if (error instanceof ApiError) { + if (error.problem?.code === 'attendee_already_registered') { + setErrorMessage( + 'Ya te encuentras registrado en este grupo con ese número de teléfono. El profesor ya tiene tus datos.', + ) + return + } + setErrorMessage(error.message || 'Error al procesar la inscripción.') + return + } + if (error instanceof Error) { + setErrorMessage(error.message) + return + } + setErrorMessage('Ocurrió un error inesperado. Por favor, intenta de nuevo.') + }, + }) + + const submit = () => { + setErrorMessage(null) + if (!firstName.trim() || !lastName.trim() || !phone.trim()) { + setErrorMessage('Por favor completa los campos requeridos (Nombre, Apellido y Teléfono).') + return + } + joinMutation.mutate() + } + + const value: JoinGroupContextValue = { + token, + group: inviteQuery.data, + invitePending: inviteQuery.isPending, + inviteFailed: inviteQuery.isError, + firstName, + setFirstName, + lastName, + setLastName, + phone, + setPhone, + email, + setEmail, + errorMessage, + registeredAttendee, + waitlistMessage, + submit, + isSubmitting: joinMutation.isPending, + } + + return {children} +} + +export function useJoinGroup() { + const context = useContext(JoinGroupContext) + if (!context) { + throw new Error('useJoinGroup debe usarse dentro de ') + } + return context +} \ No newline at end of file diff --git a/apps/web/src/features/join/JoinGroupView.tsx b/apps/web/src/features/join/JoinGroupView.tsx new file mode 100644 index 0000000..0ab1c6c --- /dev/null +++ b/apps/web/src/features/join/JoinGroupView.tsx @@ -0,0 +1,43 @@ +import { Loader2 } from 'lucide-react' +import { PublicFooter, PublicHeader } from '../../components/layout' +import { GroupInviteSummary } from './GroupInviteSummary' +import { InvalidInviteCard } from './InvalidInviteCard' +import { JoinForm } from './JoinForm' +import { JoinSuccessCard } from './JoinSuccessCard' +import { useJoinGroup } from './JoinGroupProvider' +import { WaitlistNoticeCard } from './WaitlistNoticeCard' + +export function JoinGroupView() { + const { group, invitePending, inviteFailed, registeredAttendee, waitlistMessage } = useJoinGroup() + + return ( +
    + + +
    +
    + {invitePending ? ( +
    + +

    Cargando información del grupo...

    +
    + ) : null} + + {inviteFailed || (!group && !invitePending) ? : null} + + {registeredAttendee ? : null} + {waitlistMessage ? : null} + + {!registeredAttendee && !waitlistMessage && group ? ( +
    + + +
    + ) : null} +
    +
    + + +
    + ) +} \ No newline at end of file diff --git a/apps/web/src/features/join/JoinSuccessCard.tsx b/apps/web/src/features/join/JoinSuccessCard.tsx new file mode 100644 index 0000000..ccb451a --- /dev/null +++ b/apps/web/src/features/join/JoinSuccessCard.tsx @@ -0,0 +1,49 @@ +import { CheckCircle2 } from 'lucide-react' +import { Badge } from '../../components/ui' +import { useJoinGroup } from './JoinGroupProvider' + +export function JoinSuccessCard() { + const { group, registeredAttendee } = useJoinGroup() + if (!group || !registeredAttendee) return null + + return ( +
    +
    + +
    + +
    + + Registro Confirmado + +

    ¡Inscripción Exitosa!

    +

    + Tus datos han sido registrados con éxito en el grupo{' '} + {group.name}. +

    +
    + +
    +
    + Profesor: + {group.teacherName} +
    +
    + Alumno: + {registeredAttendee.fullName} +
    + {registeredAttendee.phone ? ( +
    + Teléfono registrado: + {registeredAttendee.phone} +
    + ) : null} +
    + +

    + El profesor se pondrá en contacto contigo a la brevedad por WhatsApp para darte la bienvenida y + coordinar los detalles de la clase. +

    +
    + ) +} \ No newline at end of file diff --git a/apps/web/src/features/join/WaitlistNoticeCard.tsx b/apps/web/src/features/join/WaitlistNoticeCard.tsx new file mode 100644 index 0000000..b84435a --- /dev/null +++ b/apps/web/src/features/join/WaitlistNoticeCard.tsx @@ -0,0 +1,29 @@ +import { Clock } from 'lucide-react' +import { Badge } from '../../components/ui' +import { useJoinGroup } from './JoinGroupProvider' + +export function WaitlistNoticeCard() { + const { group, waitlistMessage } = useJoinGroup() + if (!group || !waitlistMessage) return null + + return ( +
    +
    + +
    + +
    + + Lista de Espera + +

    Cupo completo

    +

    {waitlistMessage}

    +
    + +

    + El profesor se pondrá en contacto contigo cuando haya un lugar disponible en{' '} + {group.name}. +

    +
    + ) +} \ No newline at end of file diff --git a/apps/web/src/features/onboarding/ConfirmationStep.tsx b/apps/web/src/features/onboarding/ConfirmationStep.tsx new file mode 100644 index 0000000..3dfc98c --- /dev/null +++ b/apps/web/src/features/onboarding/ConfirmationStep.tsx @@ -0,0 +1,84 @@ +import { useNavigate } from '@tanstack/react-router' +import { useQueryClient } from '@tanstack/react-query' +import type { OnboardingGroupDto } from '@gruperly/shared' +import { ArrowRight, CheckCircle2, CreditCard } from 'lucide-react' +import { useAuth } from '../../context/AuthProvider' +import { Badge, Button } from '../../components/ui' +import { BILLING_LABELS, formatPrice, formatSchedule } from './constants' + +type ConfirmationStepProps = { + group: OnboardingGroupDto + providerName?: string +} + +export function ConfirmationStep({ group, providerName }: ConfirmationStepProps) { + const navigate = useNavigate() + const queryClient = useQueryClient() + const { refresh } = useAuth() + + const goToDashboard = () => { + // Revalida la caché (estado del onboarding, sesión, grupos) antes de redirigir. + void queryClient.invalidateQueries() + void refresh() + void navigate({ to: '/' }) + } + + return ( +
    +
    + + + +

    ¡Todo listo!

    +

    + Tu grupo se creó y ya podés empezar a cobrar a tus miembros. +

    +
    + +
    +
    +
    +

    {group.name}

    +

    + {formatSchedule(group.days ?? [], group.time)} +

    +
    + Activo +
    + +
    +
    +
    Precio
    +
    + {formatPrice(group.price)} + {group.billingType ? ` · ${BILLING_LABELS[group.billingType]}` : ''} +
    +
    +
    +
    Cupo
    +
    {group.capacity ?? '—'} miembros
    +
    +
    +
    Vencimiento
    +
    Día {group.dueDay ?? '—'} de cada mes
    +
    +
    +
    + + {providerName ? ( +
    + +

    + Vas a cobrar con {providerName} en modo + prueba. +

    +
    + ) : null} + + +
    + ) +} \ No newline at end of file diff --git a/apps/web/src/features/onboarding/FirstGroupStep.tsx b/apps/web/src/features/onboarding/FirstGroupStep.tsx new file mode 100644 index 0000000..32da7bd --- /dev/null +++ b/apps/web/src/features/onboarding/FirstGroupStep.tsx @@ -0,0 +1,30 @@ +import { useMutation } from '@tanstack/react-query' +import type { CreateFirstGroup, OnboardingGroupDto } from '@gruperly/shared' +import { createFirstGroup } from '../../lib/api' +import { GroupForm } from '../groups/GroupForm' + +type FirstGroupStepProps = { + onBack: () => void + onCompleted: (group: OnboardingGroupDto) => void +} + +export function FirstGroupStep({ onBack, onCompleted }: FirstGroupStepProps) { + const create = useMutation({ + mutationFn: (values: CreateFirstGroup) => createFirstGroup(values), + onSuccess: (result) => onCompleted(result.group), + }) + + return ( + create.mutate(values)} + onBack={onBack} + /> + ) +} \ No newline at end of file diff --git a/apps/web/src/features/onboarding/OnboardingProvider.tsx b/apps/web/src/features/onboarding/OnboardingProvider.tsx new file mode 100644 index 0000000..8294b4a --- /dev/null +++ b/apps/web/src/features/onboarding/OnboardingProvider.tsx @@ -0,0 +1,72 @@ +import { createContext, useContext, useEffect, useState } from 'react' +import type { ReactNode } from 'react' +import { useQuery } from '@tanstack/react-query' +import type { ConnectPaymentResult, OnboardingGroupDto, OnboardingStatusDto } from '@gruperly/shared' +import type { UseQueryResult } from '@tanstack/react-query' +import { useAuth } from '../../context/AuthProvider' +import { getOnboardingStatus } from '../../lib/api' +import { PAYMENT_PROVIDERS } from './constants' + +type OnboardingContextValue = { + step: number + setStep: (step: number) => void + paymentResult: ConnectPaymentResult | null + setPaymentResult: (result: ConnectPaymentResult) => void + createdGroup: OnboardingGroupDto | null + setCreatedGroup: (group: OnboardingGroupDto) => void + providerName: string | undefined + statusQuery: UseQueryResult +} + +const OnboardingContext = createContext(null) + +export function OnboardingProvider({ children }: { children: ReactNode }) { + const { user } = useAuth() + const [step, setStep] = useState(0) + const [paymentResult, setPaymentResult] = useState(null) + const [createdGroup, setCreatedGroup] = useState(null) + + const statusQuery = useQuery({ + queryKey: ['onboarding', 'status'], + queryFn: getOnboardingStatus, + enabled: !!user, + }) + + useEffect(() => { + const status = statusQuery.data + if (!status) return + // Si interrumpió después de conectar el cobro, retomamos en el paso del grupo. + if (status.step === 'PAYMENT_CONNECTED') { + setStep((current) => (current === 0 ? 2 : current)) + } + }, [statusQuery.data]) + + const providerName = paymentResult + ? PAYMENT_PROVIDERS.find((p) => p.value === paymentResult.provider)?.name + : undefined + + return ( + + {children} + + ) +} + +export function useOnboarding() { + const context = useContext(OnboardingContext) + if (!context) { + throw new Error('useOnboarding debe usarse dentro de ') + } + return context +} \ No newline at end of file diff --git a/apps/web/src/features/onboarding/OnboardingView.tsx b/apps/web/src/features/onboarding/OnboardingView.tsx new file mode 100644 index 0000000..bfd40e4 --- /dev/null +++ b/apps/web/src/features/onboarding/OnboardingView.tsx @@ -0,0 +1,117 @@ +import { useEffect } from 'react' +import { Loader2 } from 'lucide-react' +import { useNavigate } from '@tanstack/react-router' +import { Logo, LogoIcon } from '../../components/brand' +import { Button } from '../../components/ui' +import { useAuth } from '../../context/AuthProvider' +import { useOnboarding } from './OnboardingProvider' +import { Stepper } from './Stepper' +import { WelcomeStep } from './WelcomeStep' +import { PaymentStep } from './PaymentStep' +import { FirstGroupStep } from './FirstGroupStep' +import { ConfirmationStep } from './ConfirmationStep' + +const STEPS = [ + { label: 'Bienvenida' }, + { label: 'Cobros' }, + { label: 'Tu grupo' }, + { label: 'Listo' }, +] + +export function OnboardingView() { + const { user, isPending: authPending } = useAuth() + const navigate = useNavigate() + const { + step, + setStep, + paymentResult, + setPaymentResult, + createdGroup, + setCreatedGroup, + providerName, + statusQuery, + } = useOnboarding() + + useEffect(() => { + if (statusQuery.data?.completed) { + void navigate({ to: '/' }) + } + }, [statusQuery.data, navigate]) + + if (authPending) { + return ( +
    + +
    + ) + } + + if (!user) { + return ( +
    +
    + + + +

    Tu cuenta, lista

    +

    + Iniciá sesión para configurar tus cobros y crear tu primer grupo. +

    + +
    +
    + ) + } + + if (statusQuery.isPending) { + return ( +
    + +
    + ) + } + + const firstName = user.name?.trim().split(/\s+/)[0] ?? 'profesor/a' + + return ( +
    +
    + +
    + + + +
    + {step === 0 ? setStep(1)} /> : null} + {step === 1 ? ( + { + setPaymentResult(result) + setStep(2) + }} + onBack={() => setStep(0)} + /> + ) : null} + {step === 2 ? ( + setStep(1)} + onCompleted={(group) => { + setCreatedGroup(group) + setStep(3) + }} + /> + ) : null} + {step === 3 && createdGroup ? ( + + ) : null} +
    +
    + ) +} \ No newline at end of file diff --git a/apps/web/src/features/onboarding/PaymentStep.tsx b/apps/web/src/features/onboarding/PaymentStep.tsx new file mode 100644 index 0000000..0b7a51f --- /dev/null +++ b/apps/web/src/features/onboarding/PaymentStep.tsx @@ -0,0 +1,171 @@ +import { useState } from 'react' +import { useMutation } from '@tanstack/react-query' +import type { ConnectPaymentResult, PaymentProvider } from '@gruperly/shared' +import { + ArrowLeft, + ArrowRight, + BadgeCheck, + Check, + CheckCircle2, + CreditCard, + Loader2, + ShieldCheck, +} from 'lucide-react' +import { connectPayment } from '../../lib/api' +import { cn } from '../../lib/utils' +import { Badge, Button } from '../../components/ui' +import { PAYMENT_PROVIDERS } from './constants' + +type PaymentStepProps = { + initialResult: ConnectPaymentResult | null + onConnected: (result: ConnectPaymentResult) => void + onBack: () => void +} + +export function PaymentStep({ initialResult, onConnected, onBack }: PaymentStepProps) { + const [selected, setSelected] = useState('MERCADO_PAGO') + const [connected, setConnected] = useState(initialResult) + + const connect = useMutation({ + mutationFn: () => connectPayment({ provider: selected, sandbox: true }), + onSuccess: (result) => { + setConnected(result) + onConnected(result) + }, + }) + + if (connected) { + return ( +
    +
    +

    Tu cobro está conectado

    +

    + Ya podés dejar listo tu primer grupo para cobrar con{' '} + {PAYMENT_PROVIDERS.find((p) => p.value === connected.provider)?.name ?? ''}. +

    +
    + +
    + + + +

    Cuenta conectada

    +
    + + {PAYMENT_PROVIDERS.find((p) => p.value === connected.provider)?.name} + + Modo prueba +
    +
    + +
    + + +
    +
    + ) + } + + return ( +
    +
    +

    Elegí tu procesador de cobro

    +

    + Los pagos de tus miembros van a llegar por esta plataforma. +

    +
    + +
    + {PAYMENT_PROVIDERS.map((provider) => { + const isSelected = selected === provider.value + return ( + + ) + })} +
    + +
    + +

    + Por ahora la conexión se hace en modo prueba (sandbox). Más adelante vas a poder + vincular tu cuenta real de {selected === 'STRIPE' ? 'Stripe' : 'Mercado Pago'}. +

    +
    + + {connect.isError ? ( +

    + No pudimos conectar la cuenta. Intentalo de nuevo. +

    + ) : null} + +
    + + +
    +
    + ) +} \ No newline at end of file diff --git a/apps/web/src/features/onboarding/Stepper.tsx b/apps/web/src/features/onboarding/Stepper.tsx new file mode 100644 index 0000000..491d4d3 --- /dev/null +++ b/apps/web/src/features/onboarding/Stepper.tsx @@ -0,0 +1,59 @@ +import { Check } from 'lucide-react' +import { cn } from '../../lib/utils' + +export type StepperProps = { + steps: readonly { label: string }[] + current: number +} + +export function Stepper({ steps, current }: StepperProps) { + return ( +
      + {steps.map((step, index) => { + const isDone = index < current + const isActive = index === current + + return ( +
    1. +
      + + {isDone ? ( + + ) : ( + {index + 1} + )} + + + {step.label} + +
      + + {index < steps.length - 1 ? ( + + ) : null} +
    2. + ) + })} +
    + ) +} \ No newline at end of file diff --git a/apps/web/src/features/onboarding/WelcomeStep.tsx b/apps/web/src/features/onboarding/WelcomeStep.tsx new file mode 100644 index 0000000..74021ac --- /dev/null +++ b/apps/web/src/features/onboarding/WelcomeStep.tsx @@ -0,0 +1,63 @@ +import { ArrowRight, Rocket, Users, Wallet } from 'lucide-react' +import { Button } from '../../components/ui' + +type WelcomeStepProps = { + name: string + onNext: () => void +} + +const STEPS_TO_SETUP = [ + { + icon: Wallet, + title: 'Conectá tu cuenta de cobro', + description: 'Mercado Pago o Stripe, en modo prueba por ahora.', + }, + { + icon: Users, + title: 'Creá tu primer grupo', + description: 'Días, horario, precio y cupo de tu clase.', + }, + { + icon: Rocket, + title: 'Empezá a cobrar', + description: 'Todo listo para sumar miembros y cobrar al instante.', + }, +] + +export function WelcomeStep({ name, onNext }: WelcomeStepProps) { + return ( +
    +
    + + + +

    ¡Hola, {name}!

    +

    + Vamos a configurar tu cuenta en 3 pasos. Vas a tardar menos de 5 minutos. +

    +
    + +
      + {STEPS_TO_SETUP.map(({ icon: Icon, title, description }) => ( +
    1. + + + +
      +

      {title}

      +

      {description}

      +
      +
    2. + ))} +
    + + +
    + ) +} \ No newline at end of file diff --git a/apps/web/src/features/onboarding/constants.ts b/apps/web/src/features/onboarding/constants.ts new file mode 100644 index 0000000..308199a --- /dev/null +++ b/apps/web/src/features/onboarding/constants.ts @@ -0,0 +1,44 @@ +import type { BillingType, PaymentProvider, WeekDay } from '@gruperly/shared' +export { BILLING_LABELS, WEEK_DAY_FULL_LABELS, formatPrice, formatSchedule } from '../../lib/format' + +export const WEEK_DAYS: readonly WeekDay[] = [ + 'MONDAY', + 'TUESDAY', + 'WEDNESDAY', + 'THURSDAY', + 'FRIDAY', + 'SATURDAY', + 'SUNDAY', +] + +export const WEEK_DAY_CHIPS: readonly { value: WeekDay; label: string }[] = [ + { value: 'MONDAY', label: 'Lun' }, + { value: 'TUESDAY', label: 'Mar' }, + { value: 'WEDNESDAY', label: 'Mié' }, + { value: 'THURSDAY', label: 'Jue' }, + { value: 'FRIDAY', label: 'Vie' }, + { value: 'SATURDAY', label: 'Sáb' }, + { value: 'SUNDAY', label: 'Dom' }, +] + +export const PAYMENT_PROVIDERS: readonly { + value: PaymentProvider + name: string + description: string +}[] = [ + { + value: 'MERCADO_PAGO', + name: 'Mercado Pago', + description: 'El procesador más usado en Latinoamérica', + }, + { + value: 'STRIPE', + name: 'Stripe', + description: 'Cobrá con tarjetas e internacionalmente', + }, +] + +export const BILLING_TYPES: readonly { value: BillingType; label: string; hint: string }[] = [ + { value: 'MONTHLY', label: 'Mensual', hint: 'Un cobro por mes' }, + { value: 'PER_CLASS', label: 'Por clase', hint: 'Cada clase que asista' }, +] \ No newline at end of file diff --git a/apps/web/src/features/payments/PaymentsView.tsx b/apps/web/src/features/payments/PaymentsView.tsx new file mode 100644 index 0000000..4c66b40 --- /dev/null +++ b/apps/web/src/features/payments/PaymentsView.tsx @@ -0,0 +1,8 @@ +export function PaymentsView() { + return ( +
    +

    Cobros

    +

    Sigue los pagos de tus grupos.

    +
    + ) +} \ No newline at end of file diff --git a/apps/web/src/features/profile/ProfileView.tsx b/apps/web/src/features/profile/ProfileView.tsx new file mode 100644 index 0000000..f8d7f59 --- /dev/null +++ b/apps/web/src/features/profile/ProfileView.tsx @@ -0,0 +1,27 @@ +import { useAuth } from '../../context/AuthProvider' +import { Avatar } from '../../components/ui' + +export function ProfileView() { + const { user } = useAuth() + + return ( +
    +
    +

    Mi perfil

    +

    Tus datos personales.

    +
    + +
    +
    + +
    +

    + {user?.name ?? 'Usuario'} +

    +

    {user?.email}

    +
    +
    +
    +
    + ) +} \ No newline at end of file diff --git a/apps/web/src/features/security/PasskeyList.tsx b/apps/web/src/features/security/PasskeyList.tsx new file mode 100644 index 0000000..d3e9067 --- /dev/null +++ b/apps/web/src/features/security/PasskeyList.tsx @@ -0,0 +1,56 @@ +import { useState } from 'react' +import { Fingerprint, Loader2, Trash2 } from 'lucide-react' +import { authClient } from '../../lib/auth-client' +import { Button } from '../../components/ui' + +export function PasskeyList({ onRefresh }: { onRefresh: () => void }) { + const { data, isPending } = authClient.useListPasskeys() + const [deletingId, setDeletingId] = useState(null) + + const handleDelete = async (id: string) => { + setDeletingId(id) + const { error } = await authClient.$fetch('/passkey/delete-passkey', { + method: 'POST', + body: { id }, + }) + setDeletingId(null) + if (!error) onRefresh() + } + + if (isPending) { + return + } + + const passkeys = data ?? [] + if (passkeys.length === 0) { + return

    Todavía no registraste ninguna passkey.

    + } + + return ( +
      + {passkeys.map((passkey) => ( +
    • + + + +
      +

      {passkey.name ?? 'Passkey'}

      +

      + {passkey.deviceType === 'singleDevice' ? 'Dispositivo' : 'Llave de seguridad'} ·{' '} + {new Date(passkey.createdAt).toLocaleDateString('es-AR')} +

      +
      + +
    • + ))} +
    + ) +} \ No newline at end of file diff --git a/apps/web/src/features/security/SecurityPage.tsx b/apps/web/src/features/security/SecurityPage.tsx new file mode 100644 index 0000000..58b4d2f --- /dev/null +++ b/apps/web/src/features/security/SecurityPage.tsx @@ -0,0 +1,123 @@ +import { useState } from 'react' +import { useForm } from 'react-hook-form' +import { z } from 'zod' +import { zodResolver } from '@hookform/resolvers/zod' +import { Fingerprint, KeyRound, Loader2, Plus } from 'lucide-react' +import { authClient } from '../../lib/auth-client' +import { Button, Input, Label } from '../../components/ui' +import { PasskeyList } from './PasskeyList' +import { changePasswordSchema } from './schema' +import type { ChangePasswordValues } from './schema' + +export function SecurityPage() { + const [passkeyKeys, setPasskeyKeys] = useState(0) + const [feedback, setFeedback] = useState(null) + + const { + register, + handleSubmit, + reset, + setError, + formState: { errors, isSubmitting }, + } = useForm({ resolver: zodResolver(changePasswordSchema) }) + + const refreshPasskeys = () => { + setPasskeyKeys((k) => k + 1) + } + + const handleAddPasskey = async () => { + setFeedback(null) + const { error } = await authClient.passkey.addPasskey() + if (error) { + setFeedback(`No se pudo agregar la passkey: ${error.message ?? 'error desconocido'}`) + } else { + setFeedback('Passkey registrada correctamente.') + refreshPasskeys() + } + } + + const onChangePassword = handleSubmit(async ({ currentPassword, newPassword }) => { + setFeedback(null) + const { error } = await authClient.changePassword({ + currentPassword, + newPassword, + revokeOtherSessions: true, + }) + if (error) { + setError('currentPassword', { + message: error.message ?? 'No se pudo cambiar la contraseña', + }) + return + } + reset({ currentPassword: '', newPassword: '' }) + setFeedback('Contraseña actualizada.') + }) + + return ( +
    +
    +

    Seguridad

    +

    + Gestioná tu contraseña y tus llaves de acceso (passkeys). +

    +
    + + {feedback ? ( +

    {feedback}

    + ) : null} + +
    +
    + +

    Cambiar contraseña

    +
    +
    +
    + + + {errors.currentPassword ? ( +

    {errors.currentPassword.message}

    + ) : null} +
    +
    + + + {errors.newPassword ? ( +

    {errors.newPassword.message}

    + ) : null} +
    + +
    +
    + +
    +
    +
    + +

    Passkeys

    +
    + +
    + +
    +
    + ) +} \ No newline at end of file diff --git a/apps/web/src/features/security/schema.ts b/apps/web/src/features/security/schema.ts new file mode 100644 index 0000000..3da25fd --- /dev/null +++ b/apps/web/src/features/security/schema.ts @@ -0,0 +1,13 @@ +import { z } from 'zod' + +export const changePasswordSchema = z + .object({ + currentPassword: z.string().min(1, 'Ingresá tu contraseña actual'), + newPassword: z.string().min(8, 'La nueva contraseña debe tener al menos 8 caracteres'), + }) + .refine((v) => v.currentPassword !== v.newPassword, { + message: 'La nueva contraseña debe ser distinta', + path: ['newPassword'], + }) + +export type ChangePasswordValues = z.infer \ No newline at end of file diff --git a/apps/web/src/features/settings/AppearanceCard.tsx b/apps/web/src/features/settings/AppearanceCard.tsx new file mode 100644 index 0000000..df88949 --- /dev/null +++ b/apps/web/src/features/settings/AppearanceCard.tsx @@ -0,0 +1,42 @@ +import { Check } from 'lucide-react' +import { cn } from '../../lib/utils' +import { useTheme } from '../../context/ThemeProvider' +import { THEME_ICONS, THEME_OPTIONS } from './constants' + +export function AppearanceCard() { + const { theme, setTheme } = useTheme() + + return ( +
    +
    +

    Apariencia

    +

    Tema claro u oscuro

    +
    + {THEME_OPTIONS.map((option) => { + const Icon = THEME_ICONS[option.value] + const isSelected = theme === option.value + return ( + + ) + })} +
    + ) +} \ No newline at end of file diff --git a/apps/web/src/features/settings/SettingsView.tsx b/apps/web/src/features/settings/SettingsView.tsx new file mode 100644 index 0000000..dbdbaf8 --- /dev/null +++ b/apps/web/src/features/settings/SettingsView.tsx @@ -0,0 +1,41 @@ +import { Link } from '@tanstack/react-router' +import { Fingerprint } from 'lucide-react' +import { signOut } from '../../lib/auth-client' +import { Button } from '../../components/ui' +import { AppearanceCard } from './AppearanceCard' + +export function SettingsView() { + const handleSignOut = async () => { + await signOut({ + fetchOptions: { headers: { 'Cache-Control': 'no-cache' } }, + }) + window.location.assign('/login') + } + + return ( +
    +
    +

    Ajustes

    +

    Configurá tu cuenta y tus grupos.

    +
    + +
    + + + + +
    +

    Seguridad

    +

    Contraseña y passkeys

    +
    + +
    + + + + +
    + ) +} \ No newline at end of file diff --git a/apps/web/src/features/settings/constants.ts b/apps/web/src/features/settings/constants.ts new file mode 100644 index 0000000..e20dd69 --- /dev/null +++ b/apps/web/src/features/settings/constants.ts @@ -0,0 +1,14 @@ +import { Monitor, Moon, Sun } from 'lucide-react' +import type { Theme } from '../../context/ThemeProvider' + +export const THEME_OPTIONS: { value: Theme; label: string; description: string }[] = [ + { value: 'light', label: 'Claro', description: 'Interfaz en tonos claros' }, + { value: 'dark', label: 'Oscuro', description: 'Interfaz en tonos oscuros' }, + { value: 'system', label: 'Sistema', description: 'Sigue la preferencia de tu dispositivo' }, +] + +export const THEME_ICONS: Record = { + light: Sun, + dark: Moon, + system: Monitor, +} \ No newline at end of file diff --git a/apps/web/src/routeTree.gen.ts b/apps/web/src/routeTree.gen.ts new file mode 100644 index 0000000..632981b --- /dev/null +++ b/apps/web/src/routeTree.gen.ts @@ -0,0 +1,410 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as AuthenticatedRouteImport } from './routes/_authenticated' +import { Route as LoginRouteImport } from './routes/login' +import { Route as OnboardingRouteImport } from './routes/onboarding' +import { Route as SignupRouteImport } from './routes/signup' +import { Route as VerifyEmailRouteImport } from './routes/verify-email' +import { Route as AuthenticatedIndexRouteImport } from './routes/_authenticated/index' +import { Route as AuthenticatedPaymentsRouteImport } from './routes/_authenticated/payments' +import { Route as AuthenticatedProfileRouteImport } from './routes/_authenticated/profile' +import { Route as AuthenticatedSeguridadRouteImport } from './routes/_authenticated/seguridad' +import { Route as AuthenticatedSettingsRouteImport } from './routes/_authenticated/settings' +import { Route as AvisarAusenciaTokenRouteImport } from './routes/avisar-ausencia.$token' +import { Route as JoinTokenRouteImport } from './routes/join.$token' +import { Route as AuthenticatedGroupsIndexRouteImport } from './routes/_authenticated/groups/index' +import { Route as AuthenticatedGroupsNewRouteImport } from './routes/_authenticated/groups/new' +import { Route as AuthenticatedClassSessionIdAttendanceRouteImport } from './routes/_authenticated/class/$sessionId/attendance' +import { Route as AuthenticatedGroupsGroupIdIndexRouteImport } from './routes/_authenticated/groups/$groupId/index' +import { Route as AuthenticatedGroupsGroupIdAnalyticsRouteImport } from './routes/_authenticated/groups/$groupId/analytics' + +const AuthenticatedRoute = AuthenticatedRouteImport.update({ + id: '/_authenticated', + getParentRoute: () => rootRouteImport, +} as any) +const LoginRoute = LoginRouteImport.update({ + id: '/login', + path: '/login', + getParentRoute: () => rootRouteImport, +} as any) +const OnboardingRoute = OnboardingRouteImport.update({ + id: '/onboarding', + path: '/onboarding', + getParentRoute: () => rootRouteImport, +} as any) +const SignupRoute = SignupRouteImport.update({ + id: '/signup', + path: '/signup', + getParentRoute: () => rootRouteImport, +} as any) +const VerifyEmailRoute = VerifyEmailRouteImport.update({ + id: '/verify-email', + path: '/verify-email', + getParentRoute: () => rootRouteImport, +} as any) +const AuthenticatedIndexRoute = AuthenticatedIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => AuthenticatedRoute, +} as any) +const AuthenticatedPaymentsRoute = AuthenticatedPaymentsRouteImport.update({ + id: '/payments', + path: '/payments', + getParentRoute: () => AuthenticatedRoute, +} as any) +const AuthenticatedProfileRoute = AuthenticatedProfileRouteImport.update({ + id: '/profile', + path: '/profile', + getParentRoute: () => AuthenticatedRoute, +} as any) +const AuthenticatedSeguridadRoute = AuthenticatedSeguridadRouteImport.update({ + id: '/seguridad', + path: '/seguridad', + getParentRoute: () => AuthenticatedRoute, +} as any) +const AuthenticatedSettingsRoute = AuthenticatedSettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => AuthenticatedRoute, +} as any) +const AvisarAusenciaTokenRoute = AvisarAusenciaTokenRouteImport.update({ + id: '/avisar-ausencia/$token', + path: '/avisar-ausencia/$token', + getParentRoute: () => rootRouteImport, +} as any) +const JoinTokenRoute = JoinTokenRouteImport.update({ + id: '/join/$token', + path: '/join/$token', + getParentRoute: () => rootRouteImport, +} as any) +const AuthenticatedGroupsIndexRoute = + AuthenticatedGroupsIndexRouteImport.update({ + id: '/groups/', + path: '/groups/', + getParentRoute: () => AuthenticatedRoute, + } as any) +const AuthenticatedGroupsNewRoute = AuthenticatedGroupsNewRouteImport.update({ + id: '/groups/new', + path: '/groups/new', + getParentRoute: () => AuthenticatedRoute, +} as any) +const AuthenticatedClassSessionIdAttendanceRoute = + AuthenticatedClassSessionIdAttendanceRouteImport.update({ + id: '/class/$sessionId/attendance', + path: '/class/$sessionId/attendance', + getParentRoute: () => AuthenticatedRoute, + } as any) +const AuthenticatedGroupsGroupIdIndexRoute = + AuthenticatedGroupsGroupIdIndexRouteImport.update({ + id: '/groups/$groupId/', + path: '/groups/$groupId/', + getParentRoute: () => AuthenticatedRoute, + } as any) +const AuthenticatedGroupsGroupIdAnalyticsRoute = + AuthenticatedGroupsGroupIdAnalyticsRouteImport.update({ + id: '/groups/$groupId/analytics', + path: '/groups/$groupId/analytics', + getParentRoute: () => AuthenticatedRoute, + } as any) + +export interface FileRoutesByFullPath { + '/': typeof AuthenticatedIndexRoute + '/login': typeof LoginRoute + '/onboarding': typeof OnboardingRoute + '/signup': typeof SignupRoute + '/verify-email': typeof VerifyEmailRoute + '/payments': typeof AuthenticatedPaymentsRoute + '/profile': typeof AuthenticatedProfileRoute + '/seguridad': typeof AuthenticatedSeguridadRoute + '/settings': typeof AuthenticatedSettingsRoute + '/avisar-ausencia/$token': typeof AvisarAusenciaTokenRoute + '/join/$token': typeof JoinTokenRoute + '/groups/new': typeof AuthenticatedGroupsNewRoute + '/groups/': typeof AuthenticatedGroupsIndexRoute + '/class/$sessionId/attendance': typeof AuthenticatedClassSessionIdAttendanceRoute + '/groups/$groupId/analytics': typeof AuthenticatedGroupsGroupIdAnalyticsRoute + '/groups/$groupId/': typeof AuthenticatedGroupsGroupIdIndexRoute +} +export interface FileRoutesByTo { + '/login': typeof LoginRoute + '/onboarding': typeof OnboardingRoute + '/signup': typeof SignupRoute + '/verify-email': typeof VerifyEmailRoute + '/payments': typeof AuthenticatedPaymentsRoute + '/profile': typeof AuthenticatedProfileRoute + '/seguridad': typeof AuthenticatedSeguridadRoute + '/settings': typeof AuthenticatedSettingsRoute + '/avisar-ausencia/$token': typeof AvisarAusenciaTokenRoute + '/join/$token': typeof JoinTokenRoute + '/': typeof AuthenticatedIndexRoute + '/groups/new': typeof AuthenticatedGroupsNewRoute + '/groups': typeof AuthenticatedGroupsIndexRoute + '/class/$sessionId/attendance': typeof AuthenticatedClassSessionIdAttendanceRoute + '/groups/$groupId/analytics': typeof AuthenticatedGroupsGroupIdAnalyticsRoute + '/groups/$groupId': typeof AuthenticatedGroupsGroupIdIndexRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/_authenticated': typeof AuthenticatedRouteWithChildren + '/login': typeof LoginRoute + '/onboarding': typeof OnboardingRoute + '/signup': typeof SignupRoute + '/verify-email': typeof VerifyEmailRoute + '/_authenticated/payments': typeof AuthenticatedPaymentsRoute + '/_authenticated/profile': typeof AuthenticatedProfileRoute + '/_authenticated/seguridad': typeof AuthenticatedSeguridadRoute + '/_authenticated/settings': typeof AuthenticatedSettingsRoute + '/avisar-ausencia/$token': typeof AvisarAusenciaTokenRoute + '/join/$token': typeof JoinTokenRoute + '/_authenticated/': typeof AuthenticatedIndexRoute + '/_authenticated/groups/new': typeof AuthenticatedGroupsNewRoute + '/_authenticated/groups/': typeof AuthenticatedGroupsIndexRoute + '/_authenticated/class/$sessionId/attendance': typeof AuthenticatedClassSessionIdAttendanceRoute + '/_authenticated/groups/$groupId/analytics': typeof AuthenticatedGroupsGroupIdAnalyticsRoute + '/_authenticated/groups/$groupId/': typeof AuthenticatedGroupsGroupIdIndexRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: + | '/' + | '/login' + | '/onboarding' + | '/signup' + | '/verify-email' + | '/payments' + | '/profile' + | '/seguridad' + | '/settings' + | '/avisar-ausencia/$token' + | '/join/$token' + | '/groups/new' + | '/groups/' + | '/class/$sessionId/attendance' + | '/groups/$groupId/analytics' + | '/groups/$groupId/' + fileRoutesByTo: FileRoutesByTo + to: + | '/login' + | '/onboarding' + | '/signup' + | '/verify-email' + | '/payments' + | '/profile' + | '/seguridad' + | '/settings' + | '/avisar-ausencia/$token' + | '/join/$token' + | '/' + | '/groups/new' + | '/groups' + | '/class/$sessionId/attendance' + | '/groups/$groupId/analytics' + | '/groups/$groupId' + id: + | '__root__' + | '/_authenticated' + | '/login' + | '/onboarding' + | '/signup' + | '/verify-email' + | '/_authenticated/payments' + | '/_authenticated/profile' + | '/_authenticated/seguridad' + | '/_authenticated/settings' + | '/avisar-ausencia/$token' + | '/join/$token' + | '/_authenticated/' + | '/_authenticated/groups/new' + | '/_authenticated/groups/' + | '/_authenticated/class/$sessionId/attendance' + | '/_authenticated/groups/$groupId/analytics' + | '/_authenticated/groups/$groupId/' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + AuthenticatedRoute: typeof AuthenticatedRouteWithChildren + LoginRoute: typeof LoginRoute + OnboardingRoute: typeof OnboardingRoute + SignupRoute: typeof SignupRoute + VerifyEmailRoute: typeof VerifyEmailRoute + AvisarAusenciaTokenRoute: typeof AvisarAusenciaTokenRoute + JoinTokenRoute: typeof JoinTokenRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/_authenticated': { + id: '/_authenticated' + path: '' + fullPath: '/' + preLoaderRoute: typeof AuthenticatedRouteImport + parentRoute: typeof rootRouteImport + } + '/login': { + id: '/login' + path: '/login' + fullPath: '/login' + preLoaderRoute: typeof LoginRouteImport + parentRoute: typeof rootRouteImport + } + '/onboarding': { + id: '/onboarding' + path: '/onboarding' + fullPath: '/onboarding' + preLoaderRoute: typeof OnboardingRouteImport + parentRoute: typeof rootRouteImport + } + '/signup': { + id: '/signup' + path: '/signup' + fullPath: '/signup' + preLoaderRoute: typeof SignupRouteImport + parentRoute: typeof rootRouteImport + } + '/verify-email': { + id: '/verify-email' + path: '/verify-email' + fullPath: '/verify-email' + preLoaderRoute: typeof VerifyEmailRouteImport + parentRoute: typeof rootRouteImport + } + '/_authenticated/': { + id: '/_authenticated/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof AuthenticatedIndexRouteImport + parentRoute: typeof AuthenticatedRoute + } + '/_authenticated/payments': { + id: '/_authenticated/payments' + path: '/payments' + fullPath: '/payments' + preLoaderRoute: typeof AuthenticatedPaymentsRouteImport + parentRoute: typeof AuthenticatedRoute + } + '/_authenticated/profile': { + id: '/_authenticated/profile' + path: '/profile' + fullPath: '/profile' + preLoaderRoute: typeof AuthenticatedProfileRouteImport + parentRoute: typeof AuthenticatedRoute + } + '/_authenticated/seguridad': { + id: '/_authenticated/seguridad' + path: '/seguridad' + fullPath: '/seguridad' + preLoaderRoute: typeof AuthenticatedSeguridadRouteImport + parentRoute: typeof AuthenticatedRoute + } + '/_authenticated/settings': { + id: '/_authenticated/settings' + path: '/settings' + fullPath: '/settings' + preLoaderRoute: typeof AuthenticatedSettingsRouteImport + parentRoute: typeof AuthenticatedRoute + } + '/avisar-ausencia/$token': { + id: '/avisar-ausencia/$token' + path: '/avisar-ausencia/$token' + fullPath: '/avisar-ausencia/$token' + preLoaderRoute: typeof AvisarAusenciaTokenRouteImport + parentRoute: typeof rootRouteImport + } + '/join/$token': { + id: '/join/$token' + path: '/join/$token' + fullPath: '/join/$token' + preLoaderRoute: typeof JoinTokenRouteImport + parentRoute: typeof rootRouteImport + } + '/_authenticated/groups/': { + id: '/_authenticated/groups/' + path: '/groups' + fullPath: '/groups/' + preLoaderRoute: typeof AuthenticatedGroupsIndexRouteImport + parentRoute: typeof AuthenticatedRoute + } + '/_authenticated/groups/new': { + id: '/_authenticated/groups/new' + path: '/groups/new' + fullPath: '/groups/new' + preLoaderRoute: typeof AuthenticatedGroupsNewRouteImport + parentRoute: typeof AuthenticatedRoute + } + '/_authenticated/class/$sessionId/attendance': { + id: '/_authenticated/class/$sessionId/attendance' + path: '/class/$sessionId/attendance' + fullPath: '/class/$sessionId/attendance' + preLoaderRoute: typeof AuthenticatedClassSessionIdAttendanceRouteImport + parentRoute: typeof AuthenticatedRoute + } + '/_authenticated/groups/$groupId/': { + id: '/_authenticated/groups/$groupId/' + path: '/groups/$groupId' + fullPath: '/groups/$groupId/' + preLoaderRoute: typeof AuthenticatedGroupsGroupIdIndexRouteImport + parentRoute: typeof AuthenticatedRoute + } + '/_authenticated/groups/$groupId/analytics': { + id: '/_authenticated/groups/$groupId/analytics' + path: '/groups/$groupId/analytics' + fullPath: '/groups/$groupId/analytics' + preLoaderRoute: typeof AuthenticatedGroupsGroupIdAnalyticsRouteImport + parentRoute: typeof AuthenticatedRoute + } + } +} + +interface AuthenticatedRouteChildren { + AuthenticatedPaymentsRoute: typeof AuthenticatedPaymentsRoute + AuthenticatedProfileRoute: typeof AuthenticatedProfileRoute + AuthenticatedSeguridadRoute: typeof AuthenticatedSeguridadRoute + AuthenticatedSettingsRoute: typeof AuthenticatedSettingsRoute + AuthenticatedIndexRoute: typeof AuthenticatedIndexRoute + AuthenticatedGroupsNewRoute: typeof AuthenticatedGroupsNewRoute + AuthenticatedGroupsIndexRoute: typeof AuthenticatedGroupsIndexRoute + AuthenticatedClassSessionIdAttendanceRoute: typeof AuthenticatedClassSessionIdAttendanceRoute + AuthenticatedGroupsGroupIdAnalyticsRoute: typeof AuthenticatedGroupsGroupIdAnalyticsRoute + AuthenticatedGroupsGroupIdIndexRoute: typeof AuthenticatedGroupsGroupIdIndexRoute +} + +const AuthenticatedRouteChildren: AuthenticatedRouteChildren = { + AuthenticatedPaymentsRoute: AuthenticatedPaymentsRoute, + AuthenticatedProfileRoute: AuthenticatedProfileRoute, + AuthenticatedSeguridadRoute: AuthenticatedSeguridadRoute, + AuthenticatedSettingsRoute: AuthenticatedSettingsRoute, + AuthenticatedIndexRoute: AuthenticatedIndexRoute, + AuthenticatedGroupsNewRoute: AuthenticatedGroupsNewRoute, + AuthenticatedGroupsIndexRoute: AuthenticatedGroupsIndexRoute, + AuthenticatedClassSessionIdAttendanceRoute: + AuthenticatedClassSessionIdAttendanceRoute, + AuthenticatedGroupsGroupIdAnalyticsRoute: + AuthenticatedGroupsGroupIdAnalyticsRoute, + AuthenticatedGroupsGroupIdIndexRoute: AuthenticatedGroupsGroupIdIndexRoute, +} + +const AuthenticatedRouteWithChildren = AuthenticatedRoute._addFileChildren( + AuthenticatedRouteChildren, +) + +const rootRouteChildren: RootRouteChildren = { + AuthenticatedRoute: AuthenticatedRouteWithChildren, + LoginRoute: LoginRoute, + OnboardingRoute: OnboardingRoute, + SignupRoute: SignupRoute, + VerifyEmailRoute: VerifyEmailRoute, + AvisarAusenciaTokenRoute: AvisarAusenciaTokenRoute, + JoinTokenRoute: JoinTokenRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/apps/web/src/router.tsx b/apps/web/src/router.tsx index 8644dba..2172c1c 100644 --- a/apps/web/src/router.tsx +++ b/apps/web/src/router.tsx @@ -1,151 +1,5 @@ -import { createRootRoute, createRoute, createRouter, Outlet } from '@tanstack/react-router' -import { AppLayoutGuard } from './components/layout/AppLayoutGuard' -import { HomeView } from './routes/home' -import { GroupsView } from './routes/groups' -import { PaymentsView } from './routes/payments' -import { SettingsView } from './routes/settings' -import { ProfileView } from './routes/profile' -import { SecurityPage } from './routes/security' -import { LoginPage } from './routes/auth/login' -import { SignupPage } from './routes/auth/signup' -import { VerifyEmailPage } from './routes/auth/verify-email' -import { OnboardingView } from './routes/onboarding' -import { GroupDetailView } from './routes/group-detail' -import { CreateGroupView } from './routes/create-group' -import { JoinGroupView } from './routes/join-group' -import { ClassAttendanceView } from './routes/class-attendance' -import { AbsenceNotifyView } from './routes/absence-notify' -import { AnalyticsView } from './routes/analytics' - -const rootRoute = createRootRoute({ - component: () => , -}) - -const loginRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/login', - component: LoginPage, -}) - -const signupRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/signup', - component: SignupPage, -}) - -const verifyEmailRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/verify-email', - component: VerifyEmailPage, -}) - -const onboardingRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/onboarding', - component: OnboardingView, -}) - -const joinGroupRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/join/$token', - component: JoinGroupView, -}) - -// Página pública: el alumno avisa su ausencia con su token personal. -const absenceNotifyRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/avisar-ausencia/$token', - component: AbsenceNotifyView, -}) - -// Capa con la navegación de la app autenticada (Sidebar + BottomNav). -// El guard redirige a /onboarding a quien no completó el onboarding. -const appLayoutRoute = createRoute({ - getParentRoute: () => rootRoute, - id: 'app', - component: AppLayoutGuard, -}) - -const indexRoute = createRoute({ - getParentRoute: () => appLayoutRoute, - path: '/', - component: HomeView, -}) - -const groupsRoute = createRoute({ - getParentRoute: () => appLayoutRoute, - path: '/groups', - component: GroupsView, -}) - -const createGroupRoute = createRoute({ - getParentRoute: () => appLayoutRoute, - path: '/groups/new', - component: CreateGroupView, -}) - -const groupDetailRoute = createRoute({ - getParentRoute: () => appLayoutRoute, - path: '/groups/$groupId', - component: GroupDetailView, -}) - -const groupAnalyticsRoute = createRoute({ - getParentRoute: () => appLayoutRoute, - path: '/groups/$groupId/analytics', - component: AnalyticsView, -}) - -const paymentsRoute = createRoute({ - getParentRoute: () => appLayoutRoute, - path: '/payments', - component: PaymentsView, -}) - -const settingsRoute = createRoute({ - getParentRoute: () => appLayoutRoute, - path: '/settings', - component: SettingsView, -}) - -const securityRoute = createRoute({ - getParentRoute: () => appLayoutRoute, - path: '/seguridad', - component: SecurityPage, -}) - -const profileRoute = createRoute({ - getParentRoute: () => appLayoutRoute, - path: '/profile', - component: ProfileView, -}) - -const classAttendanceRoute = createRoute({ - getParentRoute: () => appLayoutRoute, - path: '/class/$sessionId/attendance', - component: ClassAttendanceView, -}) - -const routeTree = rootRoute.addChildren([ - loginRoute, - signupRoute, - verifyEmailRoute, - onboardingRoute, - joinGroupRoute, - absenceNotifyRoute, - appLayoutRoute.addChildren([ - indexRoute, - groupsRoute, - createGroupRoute, - groupDetailRoute, - groupAnalyticsRoute, - paymentsRoute, - settingsRoute, - securityRoute, - profileRoute, - classAttendanceRoute, - ]), -]) +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' export const router = createRouter({ routeTree }) diff --git a/apps/web/src/routes/__root.tsx b/apps/web/src/routes/__root.tsx new file mode 100644 index 0000000..f463b79 --- /dev/null +++ b/apps/web/src/routes/__root.tsx @@ -0,0 +1,5 @@ +import { createRootRoute, Outlet } from '@tanstack/react-router' + +export const Route = createRootRoute({ + component: () => , +}) diff --git a/apps/web/src/routes/_authenticated.tsx b/apps/web/src/routes/_authenticated.tsx new file mode 100644 index 0000000..83d1644 --- /dev/null +++ b/apps/web/src/routes/_authenticated.tsx @@ -0,0 +1,10 @@ +import { createFileRoute, Outlet } from '@tanstack/react-router' +import { AppLayoutGuard } from '../components/layout/AppLayoutGuard' + +export const Route = createFileRoute('/_authenticated')({ + component: () => ( + + + + ), +}) diff --git a/apps/web/src/routes/_authenticated/class/$sessionId/attendance.tsx b/apps/web/src/routes/_authenticated/class/$sessionId/attendance.tsx new file mode 100644 index 0000000..0fbe458 --- /dev/null +++ b/apps/web/src/routes/_authenticated/class/$sessionId/attendance.tsx @@ -0,0 +1,15 @@ +import { useParams } from '@tanstack/react-router' +import { createFileRoute } from '@tanstack/react-router' +import { AttendanceProvider } from '../../../../features/class-attendance/AttendanceProvider' +import { ClassAttendanceView } from '../../../../features/class-attendance/ClassAttendanceView' + +export const Route = createFileRoute('/_authenticated/class/$sessionId/attendance')({ + component: () => { + const { sessionId } = useParams({ from: '/_authenticated/class/$sessionId/attendance' }) + return ( + + + + ) + }, +}) diff --git a/apps/web/src/routes/_authenticated/groups/$groupId/analytics.tsx b/apps/web/src/routes/_authenticated/groups/$groupId/analytics.tsx new file mode 100644 index 0000000..cf270d5 --- /dev/null +++ b/apps/web/src/routes/_authenticated/groups/$groupId/analytics.tsx @@ -0,0 +1,6 @@ +import { createFileRoute } from '@tanstack/react-router' +import { AnalyticsView } from '../../../../features/groups/analytics/AnalyticsView' + +export const Route = createFileRoute('/_authenticated/groups/$groupId/analytics')({ + component: AnalyticsView, +}) diff --git a/apps/web/src/routes/_authenticated/groups/$groupId/index.tsx b/apps/web/src/routes/_authenticated/groups/$groupId/index.tsx new file mode 100644 index 0000000..0342f96 --- /dev/null +++ b/apps/web/src/routes/_authenticated/groups/$groupId/index.tsx @@ -0,0 +1,15 @@ +import { useParams } from '@tanstack/react-router' +import { createFileRoute } from '@tanstack/react-router' +import { GroupDetailProvider } from '../../../../features/groups/detail/GroupDetailProvider' +import { GroupDetailView } from '../../../../features/groups/detail/GroupDetailView' + +export const Route = createFileRoute('/_authenticated/groups/$groupId/')({ + component: () => { + const { groupId } = useParams({ from: '/_authenticated/groups/$groupId/' }) + return ( + + + + ) + }, +}) diff --git a/apps/web/src/routes/_authenticated/groups/index.tsx b/apps/web/src/routes/_authenticated/groups/index.tsx new file mode 100644 index 0000000..1fb30d8 --- /dev/null +++ b/apps/web/src/routes/_authenticated/groups/index.tsx @@ -0,0 +1,6 @@ +import { createFileRoute } from '@tanstack/react-router' +import { GroupsView } from '../../../features/groups/GroupsView' + +export const Route = createFileRoute('/_authenticated/groups/')({ + component: GroupsView, +}) diff --git a/apps/web/src/routes/_authenticated/groups/new.tsx b/apps/web/src/routes/_authenticated/groups/new.tsx new file mode 100644 index 0000000..c54f3f1 --- /dev/null +++ b/apps/web/src/routes/_authenticated/groups/new.tsx @@ -0,0 +1,6 @@ +import { createFileRoute } from '@tanstack/react-router' +import { CreateGroupView } from '../../../features/groups/CreateGroupView' + +export const Route = createFileRoute('/_authenticated/groups/new')({ + component: CreateGroupView, +}) diff --git a/apps/web/src/routes/_authenticated/index.tsx b/apps/web/src/routes/_authenticated/index.tsx new file mode 100644 index 0000000..fe48dab --- /dev/null +++ b/apps/web/src/routes/_authenticated/index.tsx @@ -0,0 +1,6 @@ +import { createFileRoute } from '@tanstack/react-router' +import { HomeView } from '../../features/home/HomeView' + +export const Route = createFileRoute('/_authenticated/')({ + component: HomeView, +}) diff --git a/apps/web/src/routes/_authenticated/payments.tsx b/apps/web/src/routes/_authenticated/payments.tsx new file mode 100644 index 0000000..5a9bce3 --- /dev/null +++ b/apps/web/src/routes/_authenticated/payments.tsx @@ -0,0 +1,6 @@ +import { createFileRoute } from '@tanstack/react-router' +import { PaymentsView } from '../../features/payments/PaymentsView' + +export const Route = createFileRoute('/_authenticated/payments')({ + component: PaymentsView, +}) diff --git a/apps/web/src/routes/_authenticated/profile.tsx b/apps/web/src/routes/_authenticated/profile.tsx new file mode 100644 index 0000000..6515713 --- /dev/null +++ b/apps/web/src/routes/_authenticated/profile.tsx @@ -0,0 +1,6 @@ +import { createFileRoute } from '@tanstack/react-router' +import { ProfileView } from '../../features/profile/ProfileView' + +export const Route = createFileRoute('/_authenticated/profile')({ + component: ProfileView, +}) diff --git a/apps/web/src/routes/_authenticated/seguridad.tsx b/apps/web/src/routes/_authenticated/seguridad.tsx new file mode 100644 index 0000000..1f473bd --- /dev/null +++ b/apps/web/src/routes/_authenticated/seguridad.tsx @@ -0,0 +1,6 @@ +import { createFileRoute } from '@tanstack/react-router' +import { SecurityPage } from '../../features/security/SecurityPage' + +export const Route = createFileRoute('/_authenticated/seguridad')({ + component: SecurityPage, +}) diff --git a/apps/web/src/routes/_authenticated/settings.tsx b/apps/web/src/routes/_authenticated/settings.tsx new file mode 100644 index 0000000..490e19f --- /dev/null +++ b/apps/web/src/routes/_authenticated/settings.tsx @@ -0,0 +1,6 @@ +import { createFileRoute } from '@tanstack/react-router' +import { SettingsView } from '../../features/settings/SettingsView' + +export const Route = createFileRoute('/_authenticated/settings')({ + component: SettingsView, +}) diff --git a/apps/web/src/routes/avisar-ausencia.$token.tsx b/apps/web/src/routes/avisar-ausencia.$token.tsx new file mode 100644 index 0000000..e9f9bbb --- /dev/null +++ b/apps/web/src/routes/avisar-ausencia.$token.tsx @@ -0,0 +1,15 @@ +import { useParams } from '@tanstack/react-router' +import { createFileRoute } from '@tanstack/react-router' +import { AbsenceNotifyProvider } from '../features/absence-notify/AbsenceNotifyProvider' +import { AbsenceNotifyView } from '../features/absence-notify/AbsenceNotifyView' + +export const Route = createFileRoute('/avisar-ausencia/$token')({ + component: () => { + const { token } = useParams({ from: '/avisar-ausencia/$token' }) + return ( + + + + ) + }, +}) diff --git a/apps/web/src/routes/join.$token.tsx b/apps/web/src/routes/join.$token.tsx new file mode 100644 index 0000000..401714e --- /dev/null +++ b/apps/web/src/routes/join.$token.tsx @@ -0,0 +1,15 @@ +import { useParams } from '@tanstack/react-router' +import { createFileRoute } from '@tanstack/react-router' +import { JoinGroupProvider } from '../features/join/JoinGroupProvider' +import { JoinGroupView } from '../features/join/JoinGroupView' + +export const Route = createFileRoute('/join/$token')({ + component: () => { + const { token } = useParams({ from: '/join/$token' }) + return ( + + + + ) + }, +}) diff --git a/apps/web/src/routes/login.tsx b/apps/web/src/routes/login.tsx new file mode 100644 index 0000000..649bea8 --- /dev/null +++ b/apps/web/src/routes/login.tsx @@ -0,0 +1,6 @@ +import { createFileRoute } from '@tanstack/react-router' +import { LoginPage } from '../features/auth/LoginPage' + +export const Route = createFileRoute('/login')({ + component: LoginPage, +}) diff --git a/apps/web/src/routes/onboarding.tsx b/apps/web/src/routes/onboarding.tsx new file mode 100644 index 0000000..27ea49c --- /dev/null +++ b/apps/web/src/routes/onboarding.tsx @@ -0,0 +1,6 @@ +import { createFileRoute } from '@tanstack/react-router' +import { OnboardingView } from '../features/onboarding/OnboardingView' + +export const Route = createFileRoute('/onboarding')({ + component: OnboardingView, +}) diff --git a/apps/web/src/routes/signup.tsx b/apps/web/src/routes/signup.tsx new file mode 100644 index 0000000..420199b --- /dev/null +++ b/apps/web/src/routes/signup.tsx @@ -0,0 +1,6 @@ +import { createFileRoute } from '@tanstack/react-router' +import { SignupPage } from '../features/auth/SignupPage' + +export const Route = createFileRoute('/signup')({ + component: SignupPage, +}) diff --git a/apps/web/src/routes/verify-email.tsx b/apps/web/src/routes/verify-email.tsx new file mode 100644 index 0000000..3ce5338 --- /dev/null +++ b/apps/web/src/routes/verify-email.tsx @@ -0,0 +1,10 @@ +import { createFileRoute } from '@tanstack/react-router' +import { VerifyEmailPage } from '../features/auth/VerifyEmailPage' + +export const Route = createFileRoute('/verify-email')({ + validateSearch: (search: Record): { token?: string; email?: string } => ({ + token: typeof search.token === 'string' ? search.token : undefined, + email: typeof search.email === 'string' ? search.email : undefined, + }), + component: VerifyEmailPage, +}) diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts index b8a6726..328c59e 100644 --- a/apps/web/vite.config.ts +++ b/apps/web/vite.config.ts @@ -1,10 +1,11 @@ import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' import tailwindcss from '@tailwindcss/vite' +import { tanstackRouter } from '@tanstack/router-plugin/vite' export default defineConfig({ - plugins: [react(), tailwindcss()], + plugins: [tanstackRouter({ target: 'react' }), react(), tailwindcss()], server: { port: 6173, }, -}) +}) \ No newline at end of file diff --git a/bun.lock b/bun.lock index bb0389c..de6ce51 100644 --- a/bun.lock +++ b/bun.lock @@ -43,7 +43,7 @@ "@gruperly/shared": "workspace:*", "@hookform/resolvers": "^3.9.0", "@tanstack/react-query": "^5.62.0", - "@tanstack/react-router": "^1.90.0", + "@tanstack/react-router": "^1.170.38", "better-auth": "1.7.2", "clsx": "^2.1.1", "lucide-react": "^1.34.0", @@ -56,6 +56,7 @@ "devDependencies": { "@gruperly/config": "workspace:*", "@tailwindcss/vite": "^4.3.3", + "@tanstack/router-plugin": "^1.168.40", "@types/react": "^19.0.0", "@types/react-dom": "^19.0.0", "@vitejs/plugin-react": "^4.3.0", @@ -408,19 +409,27 @@ "@tailwindcss/vite": ["@tailwindcss/vite@4.3.3", "", { "dependencies": { "@tailwindcss/node": "4.3.3", "@tailwindcss/oxide": "4.3.3", "tailwindcss": "4.3.3" }, "peerDependencies": { "vite": "^5.2.0 || ^6 || ^7 || ^8" } }, "sha512-yYU8cogLeSh/ms2jh8Fj7jaba/EWa7Ja6GoUqYZaraEuCI5YS6ms6ObZgjjedm+jm6XZjdNRWBpPP6Z86oOxcw=="], - "@tanstack/history": ["@tanstack/history@1.162.2", "", {}, "sha512-Lemp3DJbzNqcin/nZpWxycDaEqySDbnIshDbyHJMMCapD4ZQMe57szRpBXOfzfP6fyWAtHNrLrcBUyANJ6Vlow=="], + "@tanstack/history": ["@tanstack/history@1.162.4", "", {}, "sha512-utTS5L2OkeYUzXGohL1Z8sefu1GLNOJcxe8Hd6iIdc/Xo1K1nDB2JEp4iSFhvYh33xKC9V91TxrS8qfrpoKobQ=="], "@tanstack/query-core": ["@tanstack/query-core@5.102.8", "", {}, "sha512-ZNjkJ33CqvPNec/6lZBnHqLc3EVGPZ9ySLhYahU9TcuRFdmwXewuj0c4hwSWcGHqEUwcSrKeZ+oGcvPBqXcQcg=="], "@tanstack/react-query": ["@tanstack/react-query@5.102.8", "", { "dependencies": { "@tanstack/query-core": "5.102.8" }, "peerDependencies": { "react": "^18 || ^19" } }, "sha512-TYBea4OuXWD7MhaSHq069TWbFe7rcwWN6kzT7JF0OKi1K6c1gTv2IzD6A6ExJsCMozdkqBWeuIUZmu4KQg0O5A=="], - "@tanstack/react-router": ["@tanstack/react-router@1.170.33", "", { "dependencies": { "@tanstack/history": "1.162.2", "@tanstack/react-store": "^0.9.3", "@tanstack/router-core": "1.171.28", "isbot": "^5.1.22" }, "peerDependencies": { "react": ">=18.0.0 || >=19.0.0", "react-dom": ">=18.0.0 || >=19.0.0" } }, "sha512-iNnI98vH3kO/V4dy6YM0CInhqwWBddU0G5wZK5jiMvr3HsK2avDQSRx3RY/y6v+6zQAqb2kD6hUPHIenrJBTSw=="], + "@tanstack/react-router": ["@tanstack/react-router@1.170.38", "", { "dependencies": { "@tanstack/history": "1.162.4", "@tanstack/react-store": "^0.11.0", "@tanstack/router-core": "1.171.32", "isbot": "^5.1.22" }, "peerDependencies": { "react": ">=18.0.0 || >=19.0.0", "react-dom": ">=18.0.0 || >=19.0.0" } }, "sha512-iHM9b0aDJbuvftmkiQXawzoqsdV68p2Re2safbVLCnxafe+iLKV++2i3hI/BMAP6uR92/Mjw94JKJJfD7pbwHQ=="], - "@tanstack/react-store": ["@tanstack/react-store@0.9.3", "", { "dependencies": { "@tanstack/store": "0.9.3", "use-sync-external-store": "^1.6.0" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-y2iHd/N9OkoQbFJLUX1T9vbc2O9tjH0pQRgTcx1/Nz4IlwLvkgpuglXUx+mXt0g5ZDFrEeDnONPqkbfxXJKwRg=="], + "@tanstack/react-store": ["@tanstack/react-store@0.11.1", "", { "dependencies": { "@tanstack/store": "0.11.1", "use-sync-external-store": "^1.6.0" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-HaIGKI3YLmjBYIvy5DFDY23oNaYZIsTZfngey07Uh5iLVJgM3bIGCnZeOFOqzjFld9JHWcaHJnasD/bKoGKwJQ=="], - "@tanstack/router-core": ["@tanstack/router-core@1.171.28", "", { "dependencies": { "@tanstack/history": "1.162.2", "cookie-es": "^3.0.0", "seroval": "^1.6.2", "seroval-plugins": "^1.6.2" } }, "sha512-PvPWSklhw6i9b0rzScVh0btQsK5u/gBYN3mBHyDzhC/U4LrB3WzPXPkUunQUKvQOGXCp16UEb7Htc/ITGm5DkQ=="], + "@tanstack/router-core": ["@tanstack/router-core@1.171.32", "", { "dependencies": { "@tanstack/history": "1.162.4", "cookie-es": "^3.0.0", "seroval": "^1.6.2", "seroval-plugins": "^1.6.2" } }, "sha512-X86Jqk3vB2KJcUfS6oLi7B7yxbaa59QEhZRPPP1fRx3k+Jw/Fu1UYVBcRtdwK/OccQnrlQdVoKvNO3QXmyEBOw=="], - "@tanstack/store": ["@tanstack/store@0.9.3", "", {}, "sha512-8reSzl/qGWGGVKhBoxXPMWzATSbZLZFWhwBAFO9NAyp0TxzfBP0mIrGb8CP8KrQTmvzXlR/vFPPUrHTLBGyFyw=="], + "@tanstack/router-generator": ["@tanstack/router-generator@1.167.38", "", { "dependencies": { "@babel/types": "^7.29.8", "@tanstack/router-core": "1.171.32", "@tanstack/router-utils": "1.162.3", "@tanstack/virtual-file-routes": "1.162.0", "jiti": "^2.7.0", "magic-string": "^0.30.21", "prettier": "^3.9.6", "zod": "^4.5.4" } }, "sha512-lkqgFleDgfkW+QONVMKBs+ZGDUF0v9R9FkplS/GZvKDFpfnu+tZxmGlV2pryU1TDxyuSyjh56AtIla3NMrlScw=="], + + "@tanstack/router-plugin": ["@tanstack/router-plugin@1.168.40", "", { "dependencies": { "@babel/core": "^7.29.7", "@babel/template": "^7.29.7", "@babel/types": "^7.29.8", "@tanstack/router-core": "1.171.32", "@tanstack/router-generator": "1.167.38", "@tanstack/router-utils": "1.162.3", "chokidar": "^5.0.0", "unplugin": "^3.3.0", "zod": "^4.5.4" }, "peerDependencies": { "@rsbuild/core": ">=1.0.2 || ^2.0.0", "@tanstack/react-router": "^1.170.38", "vite": ">=5.0.0 || >=6.0.0 || >=7.0.0 || >=8.0.0", "vite-plugin-solid": "^2.11.10 || ^3.0.0-0", "webpack": ">=5.92.0" }, "optionalPeers": ["@rsbuild/core", "@tanstack/react-router", "vite", "vite-plugin-solid", "webpack"] }, "sha512-ifiXjjR4uivxwRDhgYAcfyrcu+Mwx+vlG0QjjQ7N5C5sKmzpt5UtsL21TNVvZDSZl2Vae8DcL84Z02fOs8ZZMQ=="], + + "@tanstack/router-utils": ["@tanstack/router-utils@1.162.3", "", { "dependencies": { "@babel/generator": "^7.29.8", "@babel/parser": "^7.29.8", "@babel/types": "^7.29.8", "ansis": "^4.3.1", "babel-dead-code-elimination": "^1.0.12", "diff": "^8.0.4", "pathe": "^2.0.3", "tinyglobby": "^0.2.17" } }, "sha512-Icb0xGuG1+54IV0WMLRcc3ErTx2HeJWyPG661FkQ8UT6guoBq1FJjFRqlG/JS0xi4mFFkBhvwO7tbLa32f3yxA=="], + + "@tanstack/store": ["@tanstack/store@0.11.1", "", {}, "sha512-mzTOBhypOuDJAy/D8n2MfUZ1HFkXnmSETviRyhqEC8LUE7/IZQExOTxMANj3KjTofYTkFNpBY67qaVrT41YccA=="], + + "@tanstack/virtual-file-routes": ["@tanstack/virtual-file-routes@1.162.0", "", {}, "sha512-uhOeFyxLcU41HzvrxsGpiWdcMbScY1EDgbZ5K7DVRMYInbLYWAC0EA/kx9wXAoSM8q82bUG2hRl8+EAjE6XAbA=="], "@turbo/darwin-64": ["@turbo/darwin-64@2.10.12", "", { "os": "darwin", "cpu": "x64" }, "sha512-9nKgKoF6ZOUsM+or0OtNf+TTJSfGvDNP7ZFv/ZGWVwOSCkumyctQiTeHwB4UNljHTnC41AqylgbunLDHoccNrA=="], @@ -504,12 +513,16 @@ "ajv": ["ajv@8.20.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="], + "ansis": ["ansis@4.4.0", "", {}, "sha512-9k3v7xcHwgdO/DruxGIg4HtjvlAZlcnsX/mzqUb1t3NkYnl9kK2UJ+Gq0io+vQf7iT//BD/HB/NBkUR1LWxoeA=="], + "asn1js": ["asn1js@3.0.10", "", { "dependencies": { "pvtsutils": "^1.3.6", "pvutils": "^1.1.5", "tslib": "^2.8.1" } }, "sha512-S2s3aOytiKdFRdulw2qPE51MzjzVOisppcVv7jVFR+Kw0kxwvFrDcYA0h7Ndqbmj0HkMIXYWaoj7fli8kgx1eg=="], "atomic-sleep": ["atomic-sleep@1.0.0", "", {}, "sha512-kNOjDqAh7px0XWNI+4QbzoiR/nTkHAWNud2uvnJquD1/x5a7EQZMJT0AczqK0Qn67oY/TTQ1LbUKajZpp3I9tQ=="], "aws-ssl-profiles": ["aws-ssl-profiles@1.1.2", "", {}, "sha512-NZKeq9AfyQvEeNlN0zSYAaWrmBffJh3IELMZfRpJVWgrpEbtEpnjvzqBPf+mxoI287JohRDoa+/nsfqqiZmF6g=="], + "babel-dead-code-elimination": ["babel-dead-code-elimination@1.0.12", "", { "dependencies": { "@babel/core": "^7.23.7", "@babel/parser": "^7.23.6", "@babel/traverse": "^7.23.7", "@babel/types": "^7.23.6" } }, "sha512-GERT7L2TiYcYDtYk1IpD+ASAYXjKbLTDPhBtYj7X1NuRMDTMtAx9kyBenub1Ev41lo91OHCKdmP+egTDmfQ7Ig=="], + "baseline-browser-mapping": ["baseline-browser-mapping@2.11.22", "", { "bin": { "baseline-browser-mapping": "dist/cli.cjs" } }, "sha512-pWc4w51fBFd7mav43/zKRC+RI6f4yfzQoVlfvE8dECePyfkn1bzLp01Fj0QACcyCZyFhiEMyD2qScfKRWgWibA=="], "better-auth": ["better-auth@1.7.2", "", { "dependencies": { "@better-auth/core": "1.7.2", "@better-auth/drizzle-adapter": "1.7.2", "@better-auth/kysely-adapter": "1.7.2", "@better-auth/memory-adapter": "1.7.2", "@better-auth/mongo-adapter": "1.7.2", "@better-auth/prisma-adapter": "1.7.2", "@better-auth/telemetry": "1.7.2", "@better-auth/utils": "0.4.2", "@better-fetch/fetch": "1.3.1", "@noble/ciphers": "^2.2.0", "@noble/hashes": "^2.2.0", "better-call": "1.4.0", "defu": "^6.1.4", "jose": "^6.2.3", "kysely": "^0.28.17 || ^0.29.0", "nanostores": "^1.3.0", "zod": "^4.3.6" }, "peerDependencies": { "@lynx-js/react": "*", "@prisma/client": "^5.0.0 || ^6.0.0 || ^7.0.0", "@sveltejs/kit": "^2.0.0", "@tanstack/react-start": "^1.0.0", "@tanstack/solid-start": "^1.0.0", "better-sqlite3": "^12.0.0", "drizzle-kit": ">=0.31.4 || >=1.0.0-beta.1", "drizzle-orm": "^0.45.2 || >=1.0.0-rc.1 <2.0.0", "mongodb": "^6.0.0 || ^7.0.0", "mysql2": "^3.0.0", "next": "^14.0.0 || ^15.0.0 || ^16.0.0", "pg": "^8.0.0", "prisma": "^5.0.0 || ^6.0.0 || ^7.0.0", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0", "solid-js": "^1.0.0", "svelte": "^4.0.0 || ^5.0.0", "vitest": "^2.0.0 || ^3.0.0 || ^4.0.0", "vue": "^3.0.0" }, "optionalPeers": ["@lynx-js/react", "@prisma/client", "@sveltejs/kit", "@tanstack/react-start", "@tanstack/solid-start", "better-sqlite3", "drizzle-kit", "drizzle-orm", "mongodb", "mysql2", "next", "pg", "prisma", "react", "react-dom", "solid-js", "svelte", "vitest", "vue"] }, "sha512-gKapKBEvYIGcMxi74RjQ7EbFLiqyQt58vdoJmL1qAlWSkY1Bc2Vqshl524/3u1NxauiOU03M/Ebh762Brmac9A=="], @@ -582,6 +595,8 @@ "detect-libc": ["detect-libc@2.1.2", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="], + "diff": ["diff@8.0.4", "", {}, "sha512-DPi0FmjiSU5EvQV0++GFDOJ9ASQUVFh5kD+OzOnYdi7n3Wpm9hWWGfB/O2blfHcMVTL5WkQXSnRiK9makhrcnw=="], + "dotenv": ["dotenv@16.6.1", "", {}, "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow=="], "effect": ["effect@3.20.0", "", { "dependencies": { "@standard-schema/spec": "^1.0.0", "fast-check": "^3.23.1" } }, "sha512-qMLfDJscrNG8p/aw+IkT9W7fgj50Z4wG5bLBy0Txsxz8iUHjDIkOgO3SV0WZfnQbNG2VJYb0b+rDLMrhM4+Krw=="], @@ -776,6 +791,8 @@ "postgres-interval": ["postgres-interval@1.2.0", "", { "dependencies": { "xtend": "^4.0.0" } }, "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ=="], + "prettier": ["prettier@3.9.8", "", { "bin": { "prettier": "bin/prettier.cjs" } }, "sha512-WRFq3Wn3WId7LLROfMLdH7xaFr2jR62wU8nLO6rQUOLOxNZUviyJQs1M0iIhLexSFy+L+w0ch66wtoO2jRjG0A=="], + "prisma": ["prisma@7.10.0", "", { "dependencies": { "@prisma/config": "7.10.0", "@prisma/dev": "0.24.17", "@prisma/engines": "7.10.0", "@prisma/studio-core": "0.33.0", "mysql2": "3.15.3", "postgres": "3.4.7" }, "peerDependencies": { "better-sqlite3": ">=9.0.0", "typescript": ">=5.4.0" }, "optionalPeers": ["better-sqlite3", "typescript"], "bin": { "prisma": "build/index.js" } }, "sha512-o0ornyJOWgygVAzGCpr8PdXV8EJLHyVGDDUr/voBQt8Azzw8cYTByzzPGcA/m4tCkPcnJA8raEOv2CslsKhPEw=="], "process-warning": ["process-warning@5.1.0", "", {}, "sha512-jQSaVHsPgtyw60e1rQ/A+/ArPEj/S8pS/vFnyGa/gYFXrKk/6RuDkoqVDQ5NI5MmS01698ltlAk0NoDBNLujRw=="], @@ -880,6 +897,8 @@ "undici-types": ["undici-types@6.21.0", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="], + "unplugin": ["unplugin@3.4.0", "", { "dependencies": { "@jridgewell/remapping": "^2.3.5", "picomatch": "^4.0.7", "webpack-virtual-modules": "^0.6.2" }, "peerDependencies": { "@farmfe/core": "*", "@rsbuild/core": "*", "@rspack/core": "*", "bun-types-no-globals": "*", "esbuild": "*", "rolldown": "*", "rollup": "*", "unloader": "*", "vite": "*", "webpack": "*" }, "optionalPeers": ["@farmfe/core", "@rsbuild/core", "@rspack/core", "bun-types-no-globals", "esbuild", "rolldown", "rollup", "unloader", "vite", "webpack"] }, "sha512-9skdIFlCsPdFV7wUfZxNsFInlW+7nJmGu2gkTu0OUhF56aXGsHab9x52/QhdJ4lC7ZDPWTxbiC4ANqVlsuaW3w=="], + "update-browserslist-db": ["update-browserslist-db@1.3.3", "", { "dependencies": { "escalade": "^3.2.0", "picocolors": "^1.1.1" }, "peerDependencies": { "browserslist": ">= 4.21.0" }, "bin": { "update-browserslist-db": "cli.js" } }, "sha512-pJ2sYawQS0R/WI928Gj5GlPhTGzbMelq0+4INtSYNDV9ErKJcX6xjGWkoG/VnB3dpUm00zALaqkrUD77pO5TDQ=="], "use-sync-external-store": ["use-sync-external-store@1.7.0", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-6L+EeigHMQhdaIPNIFUKwfWJSwWFQ8gJbJ2DLOs5sDIegTwR9fRxvnM3uciHKjIZhFz+KAv2emhWMRvDmMcY8A=="], @@ -888,6 +907,8 @@ "vite": ["vite@6.4.3", "", { "dependencies": { "esbuild": "^0.25.0", "fdir": "^6.4.4", "picomatch": "^4.0.2", "postcss": "^8.5.3", "rollup": "^4.34.9", "tinyglobby": "^0.2.13" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", "jiti": ">=1.21.0", "less": "*", "lightningcss": "^1.21.0", "sass": "*", "sass-embedded": "*", "stylus": "*", "sugarss": "*", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-NTKlcQjlAK7MlQoyb6LgaqHc8sso/pVyUJYWMws3jg21uTJw/LddqIFPcPqP6PzpgbIcZyKI85sFE4HBrQDA8A=="], + "webpack-virtual-modules": ["webpack-virtual-modules@0.6.2", "", {}, "sha512-66/V2i5hQanC51vBQKPH4aI8NMAcBW59FVBs+rC7eGHupMyfn34q7rZIE+ETlJ+XTevqfUhVVBgSUNSW2flEUQ=="], + "which": ["which@2.0.2", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="], "wrappy": ["wrappy@1.0.2", "", {}, "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="], @@ -922,6 +943,10 @@ "@tailwindcss/oxide-wasm32-wasi/tslib": ["tslib@2.8.1", "", { "bundled": true }, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="], + "@tanstack/router-generator/zod": ["zod@4.6.2", "", {}, "sha512-lh5RCAGFa1Cm2hjtNwLQhSs/AsqdWnTQaBER9fEwN/88pSh7KOtJavtBx/0VlkN/uFd61SwYmljLMDAsHlvzBQ=="], + + "@tanstack/router-plugin/zod": ["zod@4.6.2", "", {}, "sha512-lh5RCAGFa1Cm2hjtNwLQhSs/AsqdWnTQaBER9fEwN/88pSh7KOtJavtBx/0VlkN/uFd61SwYmljLMDAsHlvzBQ=="], + "@types/nodemailer/@types/node": ["@types/node@26.5.1", "", { "dependencies": { "undici-types": "~8.9.0" } }, "sha512-CzNm2FezW4VR/LjG6yUdiEgLE/rAQ9Slj5gCu/C2VrdcW7I0ahNZ8DRbHT7zOZ6r3ONgd/bsQIeSaoDGrd1C6g=="], "@types/pg/@types/node": ["@types/node@26.5.1", "", { "dependencies": { "undici-types": "~8.9.0" } }, "sha512-CzNm2FezW4VR/LjG6yUdiEgLE/rAQ9Slj5gCu/C2VrdcW7I0ahNZ8DRbHT7zOZ6r3ONgd/bsQIeSaoDGrd1C6g=="], From e736ed354749cc7df5f12b9749e489afc372ef1e Mon Sep 17 00:00:00 2001 From: Jose Selesan Date: Fri, 25 Sep 2026 10:10:28 -0300 Subject: [PATCH 5/6] Updated spanish routes to english --- apps/web/src/components/layout/Breadcrumb.tsx | 2 +- .../groups/detail/AttendeeDetailModal.tsx | 2 +- .../src/features/settings/SettingsView.tsx | 2 +- apps/web/src/routeTree.gen.ts | 76 +++++++++---------- .../{seguridad.tsx => security.tsx} | 2 +- ...a.$token.tsx => report-absence.$token.tsx} | 4 +- 6 files changed, 44 insertions(+), 44 deletions(-) rename apps/web/src/routes/_authenticated/{seguridad.tsx => security.tsx} (69%) rename apps/web/src/routes/{avisar-ausencia.$token.tsx => report-absence.$token.tsx} (76%) diff --git a/apps/web/src/components/layout/Breadcrumb.tsx b/apps/web/src/components/layout/Breadcrumb.tsx index 0b86caa..f51b9cf 100644 --- a/apps/web/src/components/layout/Breadcrumb.tsx +++ b/apps/web/src/components/layout/Breadcrumb.tsx @@ -17,7 +17,7 @@ const BREADCRUMBS: Record = { { label: 'Inicio', to: '/' }, { label: 'Ajustes' }, ], - '/seguridad': [ + '/security': [ { label: 'Inicio', to: '/' }, { label: 'Ajustes', to: '/settings' }, { label: 'Seguridad' }, diff --git a/apps/web/src/features/groups/detail/AttendeeDetailModal.tsx b/apps/web/src/features/groups/detail/AttendeeDetailModal.tsx index d01ab5f..395fc0b 100644 --- a/apps/web/src/features/groups/detail/AttendeeDetailModal.tsx +++ b/apps/web/src/features/groups/detail/AttendeeDetailModal.tsx @@ -7,7 +7,7 @@ export function AttendeeDetailModal() { const { selectedAttendee, setSelectedAttendee, requestRemoveAttendee, copyAbsenceNotifyUrl } = useGroupDetail() const absenceNotifyUrl = selectedAttendee?.notifyToken - ? `${window.location.origin}/avisar-ausencia/${selectedAttendee.notifyToken}` + ? `${window.location.origin}/report-absence/${selectedAttendee.notifyToken}` : null return ( diff --git a/apps/web/src/features/settings/SettingsView.tsx b/apps/web/src/features/settings/SettingsView.tsx index dbdbaf8..25b3212 100644 --- a/apps/web/src/features/settings/SettingsView.tsx +++ b/apps/web/src/features/settings/SettingsView.tsx @@ -20,7 +20,7 @@ export function SettingsView() {
    - + diff --git a/apps/web/src/routeTree.gen.ts b/apps/web/src/routeTree.gen.ts index 632981b..ecd9aa3 100644 --- a/apps/web/src/routeTree.gen.ts +++ b/apps/web/src/routeTree.gen.ts @@ -17,10 +17,10 @@ import { Route as VerifyEmailRouteImport } from './routes/verify-email' import { Route as AuthenticatedIndexRouteImport } from './routes/_authenticated/index' import { Route as AuthenticatedPaymentsRouteImport } from './routes/_authenticated/payments' import { Route as AuthenticatedProfileRouteImport } from './routes/_authenticated/profile' -import { Route as AuthenticatedSeguridadRouteImport } from './routes/_authenticated/seguridad' +import { Route as AuthenticatedSecurityRouteImport } from './routes/_authenticated/security' import { Route as AuthenticatedSettingsRouteImport } from './routes/_authenticated/settings' -import { Route as AvisarAusenciaTokenRouteImport } from './routes/avisar-ausencia.$token' import { Route as JoinTokenRouteImport } from './routes/join.$token' +import { Route as ReportAbsenceTokenRouteImport } from './routes/report-absence.$token' import { Route as AuthenticatedGroupsIndexRouteImport } from './routes/_authenticated/groups/index' import { Route as AuthenticatedGroupsNewRouteImport } from './routes/_authenticated/groups/new' import { Route as AuthenticatedClassSessionIdAttendanceRouteImport } from './routes/_authenticated/class/$sessionId/attendance' @@ -66,9 +66,9 @@ const AuthenticatedProfileRoute = AuthenticatedProfileRouteImport.update({ path: '/profile', getParentRoute: () => AuthenticatedRoute, } as any) -const AuthenticatedSeguridadRoute = AuthenticatedSeguridadRouteImport.update({ - id: '/seguridad', - path: '/seguridad', +const AuthenticatedSecurityRoute = AuthenticatedSecurityRouteImport.update({ + id: '/security', + path: '/security', getParentRoute: () => AuthenticatedRoute, } as any) const AuthenticatedSettingsRoute = AuthenticatedSettingsRouteImport.update({ @@ -76,16 +76,16 @@ const AuthenticatedSettingsRoute = AuthenticatedSettingsRouteImport.update({ path: '/settings', getParentRoute: () => AuthenticatedRoute, } as any) -const AvisarAusenciaTokenRoute = AvisarAusenciaTokenRouteImport.update({ - id: '/avisar-ausencia/$token', - path: '/avisar-ausencia/$token', - getParentRoute: () => rootRouteImport, -} as any) const JoinTokenRoute = JoinTokenRouteImport.update({ id: '/join/$token', path: '/join/$token', getParentRoute: () => rootRouteImport, } as any) +const ReportAbsenceTokenRoute = ReportAbsenceTokenRouteImport.update({ + id: '/report-absence/$token', + path: '/report-absence/$token', + getParentRoute: () => rootRouteImport, +} as any) const AuthenticatedGroupsIndexRoute = AuthenticatedGroupsIndexRouteImport.update({ id: '/groups/', @@ -124,10 +124,10 @@ export interface FileRoutesByFullPath { '/verify-email': typeof VerifyEmailRoute '/payments': typeof AuthenticatedPaymentsRoute '/profile': typeof AuthenticatedProfileRoute - '/seguridad': typeof AuthenticatedSeguridadRoute + '/security': typeof AuthenticatedSecurityRoute '/settings': typeof AuthenticatedSettingsRoute - '/avisar-ausencia/$token': typeof AvisarAusenciaTokenRoute '/join/$token': typeof JoinTokenRoute + '/report-absence/$token': typeof ReportAbsenceTokenRoute '/groups/new': typeof AuthenticatedGroupsNewRoute '/groups/': typeof AuthenticatedGroupsIndexRoute '/class/$sessionId/attendance': typeof AuthenticatedClassSessionIdAttendanceRoute @@ -141,10 +141,10 @@ export interface FileRoutesByTo { '/verify-email': typeof VerifyEmailRoute '/payments': typeof AuthenticatedPaymentsRoute '/profile': typeof AuthenticatedProfileRoute - '/seguridad': typeof AuthenticatedSeguridadRoute + '/security': typeof AuthenticatedSecurityRoute '/settings': typeof AuthenticatedSettingsRoute - '/avisar-ausencia/$token': typeof AvisarAusenciaTokenRoute '/join/$token': typeof JoinTokenRoute + '/report-absence/$token': typeof ReportAbsenceTokenRoute '/': typeof AuthenticatedIndexRoute '/groups/new': typeof AuthenticatedGroupsNewRoute '/groups': typeof AuthenticatedGroupsIndexRoute @@ -161,10 +161,10 @@ export interface FileRoutesById { '/verify-email': typeof VerifyEmailRoute '/_authenticated/payments': typeof AuthenticatedPaymentsRoute '/_authenticated/profile': typeof AuthenticatedProfileRoute - '/_authenticated/seguridad': typeof AuthenticatedSeguridadRoute + '/_authenticated/security': typeof AuthenticatedSecurityRoute '/_authenticated/settings': typeof AuthenticatedSettingsRoute - '/avisar-ausencia/$token': typeof AvisarAusenciaTokenRoute '/join/$token': typeof JoinTokenRoute + '/report-absence/$token': typeof ReportAbsenceTokenRoute '/_authenticated/': typeof AuthenticatedIndexRoute '/_authenticated/groups/new': typeof AuthenticatedGroupsNewRoute '/_authenticated/groups/': typeof AuthenticatedGroupsIndexRoute @@ -182,10 +182,10 @@ export interface FileRouteTypes { | '/verify-email' | '/payments' | '/profile' - | '/seguridad' + | '/security' | '/settings' - | '/avisar-ausencia/$token' | '/join/$token' + | '/report-absence/$token' | '/groups/new' | '/groups/' | '/class/$sessionId/attendance' @@ -199,10 +199,10 @@ export interface FileRouteTypes { | '/verify-email' | '/payments' | '/profile' - | '/seguridad' + | '/security' | '/settings' - | '/avisar-ausencia/$token' | '/join/$token' + | '/report-absence/$token' | '/' | '/groups/new' | '/groups' @@ -218,10 +218,10 @@ export interface FileRouteTypes { | '/verify-email' | '/_authenticated/payments' | '/_authenticated/profile' - | '/_authenticated/seguridad' + | '/_authenticated/security' | '/_authenticated/settings' - | '/avisar-ausencia/$token' | '/join/$token' + | '/report-absence/$token' | '/_authenticated/' | '/_authenticated/groups/new' | '/_authenticated/groups/' @@ -236,8 +236,8 @@ export interface RootRouteChildren { OnboardingRoute: typeof OnboardingRoute SignupRoute: typeof SignupRoute VerifyEmailRoute: typeof VerifyEmailRoute - AvisarAusenciaTokenRoute: typeof AvisarAusenciaTokenRoute JoinTokenRoute: typeof JoinTokenRoute + ReportAbsenceTokenRoute: typeof ReportAbsenceTokenRoute } declare module '@tanstack/react-router' { @@ -298,11 +298,11 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AuthenticatedProfileRouteImport parentRoute: typeof AuthenticatedRoute } - '/_authenticated/seguridad': { - id: '/_authenticated/seguridad' - path: '/seguridad' - fullPath: '/seguridad' - preLoaderRoute: typeof AuthenticatedSeguridadRouteImport + '/_authenticated/security': { + id: '/_authenticated/security' + path: '/security' + fullPath: '/security' + preLoaderRoute: typeof AuthenticatedSecurityRouteImport parentRoute: typeof AuthenticatedRoute } '/_authenticated/settings': { @@ -312,13 +312,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AuthenticatedSettingsRouteImport parentRoute: typeof AuthenticatedRoute } - '/avisar-ausencia/$token': { - id: '/avisar-ausencia/$token' - path: '/avisar-ausencia/$token' - fullPath: '/avisar-ausencia/$token' - preLoaderRoute: typeof AvisarAusenciaTokenRouteImport - parentRoute: typeof rootRouteImport - } '/join/$token': { id: '/join/$token' path: '/join/$token' @@ -326,6 +319,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof JoinTokenRouteImport parentRoute: typeof rootRouteImport } + '/report-absence/$token': { + id: '/report-absence/$token' + path: '/report-absence/$token' + fullPath: '/report-absence/$token' + preLoaderRoute: typeof ReportAbsenceTokenRouteImport + parentRoute: typeof rootRouteImport + } '/_authenticated/groups/': { id: '/_authenticated/groups/' path: '/groups' @@ -367,7 +367,7 @@ declare module '@tanstack/react-router' { interface AuthenticatedRouteChildren { AuthenticatedPaymentsRoute: typeof AuthenticatedPaymentsRoute AuthenticatedProfileRoute: typeof AuthenticatedProfileRoute - AuthenticatedSeguridadRoute: typeof AuthenticatedSeguridadRoute + AuthenticatedSecurityRoute: typeof AuthenticatedSecurityRoute AuthenticatedSettingsRoute: typeof AuthenticatedSettingsRoute AuthenticatedIndexRoute: typeof AuthenticatedIndexRoute AuthenticatedGroupsNewRoute: typeof AuthenticatedGroupsNewRoute @@ -380,7 +380,7 @@ interface AuthenticatedRouteChildren { const AuthenticatedRouteChildren: AuthenticatedRouteChildren = { AuthenticatedPaymentsRoute: AuthenticatedPaymentsRoute, AuthenticatedProfileRoute: AuthenticatedProfileRoute, - AuthenticatedSeguridadRoute: AuthenticatedSeguridadRoute, + AuthenticatedSecurityRoute: AuthenticatedSecurityRoute, AuthenticatedSettingsRoute: AuthenticatedSettingsRoute, AuthenticatedIndexRoute: AuthenticatedIndexRoute, AuthenticatedGroupsNewRoute: AuthenticatedGroupsNewRoute, @@ -402,8 +402,8 @@ const rootRouteChildren: RootRouteChildren = { OnboardingRoute: OnboardingRoute, SignupRoute: SignupRoute, VerifyEmailRoute: VerifyEmailRoute, - AvisarAusenciaTokenRoute: AvisarAusenciaTokenRoute, JoinTokenRoute: JoinTokenRoute, + ReportAbsenceTokenRoute: ReportAbsenceTokenRoute, } export const routeTree = rootRouteImport ._addFileChildren(rootRouteChildren) diff --git a/apps/web/src/routes/_authenticated/seguridad.tsx b/apps/web/src/routes/_authenticated/security.tsx similarity index 69% rename from apps/web/src/routes/_authenticated/seguridad.tsx rename to apps/web/src/routes/_authenticated/security.tsx index 1f473bd..b12e31e 100644 --- a/apps/web/src/routes/_authenticated/seguridad.tsx +++ b/apps/web/src/routes/_authenticated/security.tsx @@ -1,6 +1,6 @@ import { createFileRoute } from '@tanstack/react-router' import { SecurityPage } from '../../features/security/SecurityPage' -export const Route = createFileRoute('/_authenticated/seguridad')({ +export const Route = createFileRoute('/_authenticated/security')({ component: SecurityPage, }) diff --git a/apps/web/src/routes/avisar-ausencia.$token.tsx b/apps/web/src/routes/report-absence.$token.tsx similarity index 76% rename from apps/web/src/routes/avisar-ausencia.$token.tsx rename to apps/web/src/routes/report-absence.$token.tsx index e9f9bbb..721fa1e 100644 --- a/apps/web/src/routes/avisar-ausencia.$token.tsx +++ b/apps/web/src/routes/report-absence.$token.tsx @@ -3,9 +3,9 @@ import { createFileRoute } from '@tanstack/react-router' import { AbsenceNotifyProvider } from '../features/absence-notify/AbsenceNotifyProvider' import { AbsenceNotifyView } from '../features/absence-notify/AbsenceNotifyView' -export const Route = createFileRoute('/avisar-ausencia/$token')({ +export const Route = createFileRoute('/report-absence/$token')({ component: () => { - const { token } = useParams({ from: '/avisar-ausencia/$token' }) + const { token } = useParams({ from: '/report-absence/$token' }) return ( From 02af5e3c119160a309cc176d2761841249ac4af9 Mon Sep 17 00:00:00 2001 From: Jose Selesan Date: Mon, 28 Sep 2026 16:16:21 -0300 Subject: [PATCH 6/6] 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. --- .../attendees/features/get-by-id/route.ts | 20 ++ .../attendees/features/get-by-id/use-case.ts | 36 +++ .../attendees/features/get-stats/route.ts | 20 ++ .../attendees/features/get-stats/use-case.ts | 59 +++++ apps/backend/src/modules/groups/routes.ts | 4 + apps/backend/test/analytics-risk.test.ts | 6 +- apps/backend/test/attendee-get-by-id.test.ts | 105 +++++++++ apps/backend/test/attendee-stats.test.ts | 126 +++++++++++ .../class-attendance/AttendanceProvider.tsx | 1 + .../groups/detail/AttendeeAttendanceStats.tsx | 106 +++++++++ .../groups/detail/AttendeeDetailModal.tsx | 150 ------------- .../groups/detail/AttendeeDetailPage.tsx | 212 ++++++++++++++++++ .../groups/detail/AttendeeDetailProvider.tsx | 119 ++++++++++ .../groups/detail/GroupDetailProvider.tsx | 49 +--- .../groups/detail/GroupDetailView.tsx | 24 +- .../features/groups/detail/MembersTable.tsx | 10 +- .../groups/detail/RemoveAttendeeModal.tsx | 74 +++--- .../groups/detail/useRemoveAttendee.ts | 49 ++++ apps/web/src/lib/api.ts | 7 + apps/web/src/routeTree.gen.ts | 23 ++ .../groups/$groupId/attendees/$attendeeId.tsx | 17 ++ packages/shared/src/schemas/attendees.ts | 12 + 22 files changed, 997 insertions(+), 232 deletions(-) create mode 100644 apps/backend/src/modules/attendees/features/get-by-id/route.ts create mode 100644 apps/backend/src/modules/attendees/features/get-by-id/use-case.ts create mode 100644 apps/backend/src/modules/attendees/features/get-stats/route.ts create mode 100644 apps/backend/src/modules/attendees/features/get-stats/use-case.ts create mode 100644 apps/backend/test/attendee-get-by-id.test.ts create mode 100644 apps/backend/test/attendee-stats.test.ts create mode 100644 apps/web/src/features/groups/detail/AttendeeAttendanceStats.tsx delete mode 100644 apps/web/src/features/groups/detail/AttendeeDetailModal.tsx create mode 100644 apps/web/src/features/groups/detail/AttendeeDetailPage.tsx create mode 100644 apps/web/src/features/groups/detail/AttendeeDetailProvider.tsx create mode 100644 apps/web/src/features/groups/detail/useRemoveAttendee.ts create mode 100644 apps/web/src/routes/_authenticated/groups/$groupId/attendees/$attendeeId.tsx diff --git a/apps/backend/src/modules/attendees/features/get-by-id/route.ts b/apps/backend/src/modules/attendees/features/get-by-id/route.ts new file mode 100644 index 0000000..a954c68 --- /dev/null +++ b/apps/backend/src/modules/attendees/features/get-by-id/route.ts @@ -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; diff --git a/apps/backend/src/modules/attendees/features/get-by-id/use-case.ts b/apps/backend/src/modules/attendees/features/get-by-id/use-case.ts new file mode 100644 index 0000000..fac192b --- /dev/null +++ b/apps/backend/src/modules/attendees/features/get-by-id/use-case.ts @@ -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; +}; + +export class GetAttendee { + constructor(private readonly deps: GetAttendeeDeps = {}) {} + + async execute( + groupId: string, + attendeeId: string, + userId: string, + ): Promise> { + 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)); + } +} diff --git a/apps/backend/src/modules/attendees/features/get-stats/route.ts b/apps/backend/src/modules/attendees/features/get-stats/route.ts new file mode 100644 index 0000000..6bf75f3 --- /dev/null +++ b/apps/backend/src/modules/attendees/features/get-stats/route.ts @@ -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; diff --git a/apps/backend/src/modules/attendees/features/get-stats/use-case.ts b/apps/backend/src/modules/attendees/features/get-stats/use-case.ts new file mode 100644 index 0000000..95144b1 --- /dev/null +++ b/apps/backend/src/modules/attendees/features/get-stats/use-case.ts @@ -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; +}; + +export class GetAttendeeStats { + constructor(private readonly deps: GetAttendeeStatsDeps = {}) {} + + async execute( + groupId: string, + attendeeId: string, + userId: string, + ): Promise> { + 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, + }); + } +} diff --git a/apps/backend/src/modules/groups/routes.ts b/apps/backend/src/modules/groups/routes.ts index a490ac8..0b1197b 100644 --- a/apps/backend/src/modules/groups/routes.ts +++ b/apps/backend/src/modules/groups/routes.ts @@ -3,6 +3,8 @@ import analyticsRoutes from '../analytics/routes'; import addToGroupWaitlistRoute from '../attendees/features/add-to-waitlist/route'; import bulkCreateAttendeesRoute from '../attendees/features/bulk-create/route'; import createAttendeeRoute from '../attendees/features/create/route'; +import getAttendeeRoute from '../attendees/features/get-by-id/route'; +import getAttendeeStatsRoute from '../attendees/features/get-stats/route'; import removeAttendeeRoute from '../attendees/features/remove/route'; import groupWaitlistRoutes from '../group-waitlist/routes'; import createGroupRoute from './features/create/route'; @@ -23,6 +25,8 @@ routes.route('/', getByIdRoute); routes.route('/', addToGroupWaitlistRoute); routes.route('/', groupWaitlistRoutes); routes.route('/', analyticsRoutes); +routes.route('/', getAttendeeRoute); +routes.route('/', getAttendeeStatsRoute); routes.route('/', removeAttendeeRoute); export default routes; \ No newline at end of file diff --git a/apps/backend/test/analytics-risk.test.ts b/apps/backend/test/analytics-risk.test.ts index fa46c92..7075886 100644 --- a/apps/backend/test/analytics-risk.test.ts +++ b/apps/backend/test/analytics-risk.test.ts @@ -12,7 +12,6 @@ const at = (offsetDays: number) => new Date(Date.now() - offsetDays * day); function entry(status: 'PRESENT' | 'ABSENT' | 'EXCUSED', offsetDays: number) { return { status, occurredAt: at(offsetDays) }; } - describe('trailingAbsentStreak', () => { it('devuelve 0 sin registros', () => { expect(trailingAbsentStreak([])).toBe(0); @@ -34,13 +33,14 @@ describe('trailingAbsentStreak', () => { describe('lastAttendedAt', () => { it('devuelve la clase PRESENT más reciente', () => { + const now = Date.now(); const result = lastAttendedAt([ - entry('PRESENT', 0), + { status: 'PRESENT', occurredAt: new Date(now) }, entry('ABSENT', 7), entry('ABSENT', 14), ]); expect(result).not.toBeNull(); - expect(result?.getTime()).toBe(at(0).getTime()); + expect(result?.getTime()).toBe(now); }); it('devuelve null si nunca asistió', () => { diff --git a/apps/backend/test/attendee-get-by-id.test.ts b/apps/backend/test/attendee-get-by-id.test.ts new file mode 100644 index 0000000..d992f7d --- /dev/null +++ b/apps/backend/test/attendee-get-by-id.test.ts @@ -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 = {}) { + 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); + }); +}); diff --git a/apps/backend/test/attendee-stats.test.ts b/apps/backend/test/attendee-stats.test.ts new file mode 100644 index 0000000..74e1ba8 --- /dev/null +++ b/apps/backend/test/attendee-stats.test.ts @@ -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 = {}) { + 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); + }); +}); diff --git a/apps/web/src/features/class-attendance/AttendanceProvider.tsx b/apps/web/src/features/class-attendance/AttendanceProvider.tsx index 464e3d7..3a0c7a4 100644 --- a/apps/web/src/features/class-attendance/AttendanceProvider.tsx +++ b/apps/web/src/features/class-attendance/AttendanceProvider.tsx @@ -76,6 +76,7 @@ export function AttendanceProvider({ sessionId, children }: { sessionId: string; toast.success('Asistencia guardada correctamente.', 'Listo') void queryClient.invalidateQueries({ queryKey: ['classes-today'] }) void queryClient.invalidateQueries({ queryKey: ['class-students', sessionId] }) + void queryClient.invalidateQueries({ queryKey: ['attendee-stats'] }) }, onError: (error: Error) => { toast.error(error.message || 'No pudimos guardar la asistencia.') diff --git a/apps/web/src/features/groups/detail/AttendeeAttendanceStats.tsx b/apps/web/src/features/groups/detail/AttendeeAttendanceStats.tsx new file mode 100644 index 0000000..cea2ad4 --- /dev/null +++ b/apps/web/src/features/groups/detail/AttendeeAttendanceStats.tsx @@ -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 = { + good: 'bg-success', + mid: 'bg-warning', + low: 'bg-danger', + none: 'bg-border', +} + +const valueTone: Record = { + good: 'text-success', + mid: 'text-warning', + low: 'text-danger', + none: 'text-foreground/40', +} + +export function AttendeeAttendanceStats() { + const { attendeeStats, attendeeStatsPending, attendeeStatsFailed } = useAttendeeDetail() + + if (attendeeStatsPending) { + return ( +
    + +
    + ) + } + + if (attendeeStatsFailed || !attendeeStats) { + return ( +
    + No pudimos cargar la asistencia de este participante. +
    + ) + } + + const { presentCount, absentCount, excusedCount, totalMarked, attendanceRate } = attendeeStats + const tone = rateTone(attendanceRate, totalMarked) + + return ( +
    +
    +
    +

    + Asistencia +

    +

    + {totalMarked > 0 + ? `Sobre ${totalMarked} clases registradas` + : 'Sin clases registradas todavía'} +

    +
    +

    + {totalMarked > 0 ? `${attendanceRate}%` : '—'} +

    +
    + + + ) +} + +function StatCounter({ + value, + label, + valueClass, +}: { + value: number + label: string + valueClass: string +}) { + return ( +
    +
    {label}
    +
    {value}
    +
    + ) +} diff --git a/apps/web/src/features/groups/detail/AttendeeDetailModal.tsx b/apps/web/src/features/groups/detail/AttendeeDetailModal.tsx deleted file mode 100644 index 395fc0b..0000000 --- a/apps/web/src/features/groups/detail/AttendeeDetailModal.tsx +++ /dev/null @@ -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 ( - setSelectedAttendee(null)} - title="Detalle del Participante" - maxWidth="sm" - > - {selectedAttendee ? ( -
    -
    -
    - {selectedAttendee.fullName.charAt(0).toUpperCase()} -
    -
    -

    {selectedAttendee.fullName}

    -

    - Incorporado el{' '} - {new Date(selectedAttendee.createdAt).toLocaleDateString('es-ES', { - day: 'numeric', - month: 'long', - year: 'numeric', - })} -

    -
    -
    - -
    - } label="Teléfono"> - {selectedAttendee.phone ? ( -
    - {selectedAttendee.phone} - - - WhatsApp - -
    - ) : ( - Sin teléfono - )} -
    - - } label="Email"> - {selectedAttendee.email ? ( - - {selectedAttendee.email} - - ) : ( - Sin email - )} - - - {selectedAttendee.guardianName || selectedAttendee.guardianPhone ? ( - <> - } label="Responsable"> - - {selectedAttendee.guardianName || —} - - - {selectedAttendee.guardianPhone ? ( - } label="Tel. Responsable"> -
    - {selectedAttendee.guardianPhone} - - - -
    -
    - ) : null} - - ) : null} - - } label="Notas"> - {selectedAttendee.notes ? ( - {selectedAttendee.notes} - ) : ( - Sin notas - )} - -
    - - {absenceNotifyUrl ? ( -
    -

    Link para avisar ausencias

    -
    - - {absenceNotifyUrl} - - -
    - {selectedAttendee.phone ? ( - - - Enviar por WhatsApp - - ) : null} -
    - ) : null} - -
    - -
    -
    - ) : null} -
    - ) -} \ No newline at end of file diff --git a/apps/web/src/features/groups/detail/AttendeeDetailPage.tsx b/apps/web/src/features/groups/detail/AttendeeDetailPage.tsx new file mode 100644 index 0000000..4624cbd --- /dev/null +++ b/apps/web/src/features/groups/detail/AttendeeDetailPage.tsx @@ -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 ( +
    + +
    + ) + } + + if (attendeeFailed || !attendee) { + return ( +
    +

    Participante no encontrado

    +

    No se pudo cargar la información de este participante.

    + +
    + ) + } + + const absenceNotifyUrl = attendee.notifyToken + ? `${window.location.origin}/report-absence/${attendee.notifyToken}` + : null + + return ( +
    + + + Volver al grupo + + +
    +
    + {attendee.fullName.charAt(0).toUpperCase()} +
    +
    +

    {attendee.fullName}

    +

    + {groupName ? `${groupName} · ` : ''}Incorporado el{' '} + {new Date(attendee.createdAt).toLocaleDateString('es-ES', { + day: 'numeric', + month: 'long', + year: 'numeric', + })} +

    +
    +
    + + + +
    + } label="Teléfono"> + {attendee.phone ? ( +
    + {attendee.phone} + + + WhatsApp + +
    + ) : ( + Sin teléfono + )} +
    + + } label="Email"> + {attendee.email ? ( + + {attendee.email} + + ) : ( + Sin email + )} + + + {attendee.guardianName || attendee.guardianPhone ? ( + <> + } label="Responsable"> + + {attendee.guardianName || —} + + + {attendee.guardianPhone ? ( + } label="Tel. Responsable"> +
    + {attendee.guardianPhone} + + + +
    +
    + ) : null} + + ) : null} + + } label="Notas"> + {attendee.notes ? ( + {attendee.notes} + ) : ( + Sin notas + )} + +
    + + {absenceNotifyUrl ? ( +
    +

    Link para avisar ausencias

    +
    + + {absenceNotifyUrl} + + +
    + {attendee.phone ? ( + + + Enviar por WhatsApp + + ) : null} +
    + ) : null} + +
    + +
    + + +
    + ) +} diff --git a/apps/web/src/features/groups/detail/AttendeeDetailProvider.tsx b/apps/web/src/features/groups/detail/AttendeeDetailProvider.tsx new file mode 100644 index 0000000..c6ee77f --- /dev/null +++ b/apps/web/src/features/groups/detail/AttendeeDetailProvider.tsx @@ -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(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 {children} +} + +export function useAttendeeDetail() { + const context = useContext(AttendeeDetailContext) + if (!context) { + throw new Error('useAttendeeDetail debe usarse dentro de ') + } + return context +} diff --git a/apps/web/src/features/groups/detail/GroupDetailProvider.tsx b/apps/web/src/features/groups/detail/GroupDetailProvider.tsx index 322b3b2..6a8f4f1 100644 --- a/apps/web/src/features/groups/detail/GroupDetailProvider.tsx +++ b/apps/web/src/features/groups/detail/GroupDetailProvider.tsx @@ -24,9 +24,9 @@ import { getGroupWaitlist, getInviteToken, promoteGroupWaitlistEntry, - removeGroupAttendee, removeGroupWaitlistEntry, } from '../../../lib/api' +import { useRemoveAttendee } from './useRemoveAttendee' export type BulkAttendeeRow = { firstName: string @@ -68,8 +68,6 @@ type GroupDetailContextValue = { isAddAttendeeModalOpen: boolean openAddAttendeeModal: () => void closeAddAttendeeModal: () => void - selectedAttendee: AttendeeDto | null - setSelectedAttendee: (attendee: AttendeeDto | null) => void attendeeToRemove: AttendeeDto | null requestRemoveAttendee: (attendee: AttendeeDto) => void cancelRemoveAttendee: () => void @@ -111,7 +109,6 @@ type GroupDetailContextValue = { copyInviteLink: () => Promise copyWhatsappMessage: () => Promise openWhatsapp: () => Promise - copyAbsenceNotifyUrl: (url: string) => void } const GroupDetailContext = createContext(null) @@ -122,7 +119,6 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch const [isInviteModalOpen, setIsInviteModalOpen] = useState(false) const [isAddAttendeeModalOpen, setIsAddAttendeeModalOpen] = useState(false) - const [selectedAttendee, setSelectedAttendee] = useState(null) const [activeTab, setActiveTab] = useState('quick') const [listSection, setListSection] = useState('members') const [attendeeToRemove, setAttendeeToRemove] = useState(null) @@ -290,30 +286,9 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch }, }) - const removeAttendeeMutation = useMutation({ - mutationFn: (payload: { attendeeId: string; promoteFromWaitlist: boolean }) => - removeGroupAttendee(groupId, payload.attendeeId, { promoteFromWaitlist: payload.promoteFromWaitlist }), - 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 removeAttendeeMutation = useRemoveAttendee({ + groupId, + onRemoved: () => setAttendeeToRemove(null), }) const promoteWaitlistMutation = useMutation({ @@ -384,12 +359,6 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch 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( () => parsedContacts @@ -453,17 +422,12 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch isAddAttendeeModalOpen, openAddAttendeeModal: () => setIsAddAttendeeModalOpen(true), closeAddAttendeeModal: () => setIsAddAttendeeModalOpen(false), - selectedAttendee, - setSelectedAttendee, attendeeToRemove, requestRemoveAttendee: (attendee) => setAttendeeToRemove(attendee), cancelRemoveAttendee: () => setAttendeeToRemove(null), confirmRemoveAttendee: (promoteFromWaitlist) => { if (!attendeeToRemove) return - removeAttendeeMutation.mutate({ - attendeeId: attendeeToRemove.id, - promoteFromWaitlist, - }) + removeAttendeeMutation.removeAttendee({ attendee: attendeeToRemove, promoteFromWaitlist }) }, selectedWaitlistEntry, setSelectedWaitlistEntry, @@ -490,7 +454,7 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch isSubmittingForcedAttendee: createAttendeeForceMutation.isPending, isSubmittingWaitlistEntry: addToWaitlistMutation.isPending, isSubmittingBulkImport: bulkImportMutation.isPending, - isSubmittingRemoval: removeAttendeeMutation.isPending, + isSubmittingRemoval: removeAttendeeMutation.isRemovingAttendee, isSubmittingPromotion: promoteWaitlistMutation.isPending, isSubmittingWaitlistRemoval: removeWaitlistEntryMutation.isPending, isRegeneratingInvite: regenerateTokenMutation.isPending, @@ -522,7 +486,6 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch copyInviteLink, copyWhatsappMessage, openWhatsapp, - copyAbsenceNotifyUrl, } return {children} diff --git a/apps/web/src/features/groups/detail/GroupDetailView.tsx b/apps/web/src/features/groups/detail/GroupDetailView.tsx index 2dcb59f..3225b45 100644 --- a/apps/web/src/features/groups/detail/GroupDetailView.tsx +++ b/apps/web/src/features/groups/detail/GroupDetailView.tsx @@ -2,7 +2,6 @@ import { useNavigate } from '@tanstack/react-router' import { Loader2 } from 'lucide-react' import { Button } from '../../../components/ui' import { AddAttendeeModal } from './AddAttendeeModal' -import { AttendeeDetailModal } from './AttendeeDetailModal' import { BulkCapacityModal } from './BulkCapacityModal' import { CapacityModal } from './CapacityModal' import { GroupHeader } from './GroupHeader' @@ -14,7 +13,16 @@ import { useGroupDetail } from './GroupDetailProvider' import { WaitlistEntryDetailModal } from './WaitlistEntryDetailModal' export function GroupDetailView() { - const { group, groupQueryPending } = useGroupDetail() + const { + group, + groupQueryPending, + attendeeToRemove, + cancelRemoveAttendee, + confirmRemoveAttendee, + firstWaitlistEntry, + waitlistTotal, + isSubmittingRemoval, + } = useGroupDetail() const navigate = useNavigate() if (groupQueryPending) { @@ -47,8 +55,16 @@ export function GroupDetailView() { - - +
    ) diff --git a/apps/web/src/features/groups/detail/MembersTable.tsx b/apps/web/src/features/groups/detail/MembersTable.tsx index b3b154a..05b29e2 100644 --- a/apps/web/src/features/groups/detail/MembersTable.tsx +++ b/apps/web/src/features/groups/detail/MembersTable.tsx @@ -1,9 +1,15 @@ import type { AttendeeDto } from '@gruperly/shared' +import { useNavigate } from '@tanstack/react-router' import { ChevronRight } from 'lucide-react' import { useGroupDetail } from './GroupDetailProvider' 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 (
    @@ -20,7 +26,7 @@ export function MembersTable({ attendees }: { attendees: AttendeeDto[] }) { setSelectedAttendee(attendee)} + onClick={() => openAttendee(attendee.id)} >
    diff --git a/apps/web/src/features/groups/detail/RemoveAttendeeModal.tsx b/apps/web/src/features/groups/detail/RemoveAttendeeModal.tsx index 445e545..a196937 100644 --- a/apps/web/src/features/groups/detail/RemoveAttendeeModal.tsx +++ b/apps/web/src/features/groups/detail/RemoveAttendeeModal.tsx @@ -1,37 +1,51 @@ +import type { AttendeeDto, GroupWaitlistEntryDto } from '@gruperly/shared' import { Clock, Loader2, Trash2, UserCheck, UserMinus } from 'lucide-react' import { Button, Modal } from '../../../components/ui' -import { useGroupDetail } from './GroupDetailProvider' -export function RemoveAttendeeModal() { - const { - attendeeToRemove, - cancelRemoveAttendee, - confirmRemoveAttendee, - group, - firstWaitlistEntry, - waitlistTotal, - isSubmittingRemoval, - } = useGroupDetail() +type RemoveAttendeeModalProps = { + attendee: AttendeeDto | null + groupName: string | undefined + firstWaitlistEntry: GroupWaitlistEntryDto | null + waitlistTotal: number + isResolvingWaitlist: boolean + isSubmitting: boolean + onCancel: () => void + onConfirm: (promoteFromWaitlist: boolean) => void +} +export function RemoveAttendeeModal({ + attendee, + groupName, + firstWaitlistEntry, + waitlistTotal, + isResolvingWaitlist, + isSubmitting, + onCancel, + onConfirm, +}: RemoveAttendeeModalProps) { return ( - {attendeeToRemove ? ( + {attendee ? (

    - {attendeeToRemove.fullName} dejará de ser miembro del grupo{' '} - {group?.name} + {attendee.fullName} dejará de ser miembro del grupo{' '} + {groupName} {firstWaitlistEntry ? ' y el cupo quedará libre.' : '.'} - {attendeeToRemove.phone ? ( - Teléfono: {attendeeToRemove.phone} + {attendee.phone ? ( + Teléfono: {attendee.phone} ) : null}

    - {firstWaitlistEntry ? ( + {isResolvingWaitlist ? ( +
    + +
    + ) : firstWaitlistEntry ? (
    @@ -46,11 +60,11 @@ export function RemoveAttendeeModal() {
    ) : (
    -