diff --git a/AGENTS.md b/AGENTS.md index 49dc495..0e7d92d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -78,12 +78,12 @@ Seed sample data from `hub-backend` (Postgres must be up and migrated): Setup y comandos exactos (BD de test, `DATABASE_URL`, Playwright) en [BUILD.md](BUILD.md#tests). -## Commit messages — Conventional Commits (required) +## Commit messages — Conventional Commits in Spanish (required) Every commit must follow [Conventional Commits](https://www.conventionalcommits.org): ``` -(): +(): ``` **Allowed types** @@ -107,22 +107,27 @@ Every commit must follow [Conventional Commits](https://www.conventionalcommits. **Rules** +- **Write commit subjects and bodies in Spanish.** The conventional `type` and + `scope` tokens stay in English, but the description and the body are Spanish. - Description in the imperative mood, lowercase, no trailing period: - `feat(projects): add privacy flag to project detail`. + `feat(projects): agregar indicador de privacidad al detalle del proyecto`. - Keep the subject under ~72 characters; put the "why" in the body if needed. - Reference issues in the body (`Refs #92`), not in the subject. - Breaking changes: add `!` after the type/scope and explain in a - `BREAKING CHANGE:` footer, e.g. `refactor(auth)!: drop legacy session cookie`. + `BREAKING CHANGE:` footer, e.g. + `refactor(auth)!: eliminar la cookie de sesión heredada`. Keep the + `BREAKING CHANGE:` keyword and write its explanation in Spanish. - One logical change per commit; don't mix a refactor with a feature. -- PR titles should follow the same convention, since merges keep the history. +- **PR titles and descriptions are also written in Spanish.** Titles follow the + same Conventional Commits convention, since merges keep the history. Examples: ``` -feat(frontend): open every module with ModuleHeader -fix(backend): return 404 for private projects to non-members -refactor(prisma): extract project visibility into AuthorizationService -docs: document the UTB design system +feat(frontend): abrir cada módulo con ModuleHeader +fix(backend): responder 404 para proyectos privados a no miembros +refactor(prisma): extraer la visibilidad de proyectos a AuthorizationService +docs: documentar el sistema de diseño UTB ``` ## General guidelines diff --git a/BUILD.md b/BUILD.md index 3b0a8fa..dc00e37 100644 --- a/BUILD.md +++ b/BUILD.md @@ -183,8 +183,7 @@ las dos suites (supertest y Playwright). - `prisma/fixtures/milestones.json` y `observations.json`: indexados por el nombre del proyecto. - `prisma/fixtures/attachments/`: archivos de ejemplo que se suben a - RustFS. Las portadas `portada-*.jpg` acompañan a los proyectos finalizados; - por convención, la primera imagen de un proyecto es su portada. + RustFS. - El historial de estados reparte las transiciones entre la fecha de inicio y la de fin (o "hoy" si el proyecto sigue activo), de modo que los proyectos cerrados quedan con una cronología coherente. diff --git a/docs/backend_arch.md b/docs/backend_arch.md index 433a47a..0417568 100644 --- a/docs/backend_arch.md +++ b/docs/backend_arch.md @@ -577,9 +577,11 @@ mostrados, y si es inválido se responde `401` en lugar de degradar a anónimo. estudiantes ven además los privados en `approved` en modo de vista previa. - `assertProjectMember` (usado por observaciones, hitos, anexos y entregas) es de miembros: proponente, actores asignados y roles revisores. Los proyectos - públicos solo exponen su información base en el listado y el detalle. La vista - previa de un privado expone aún menos: nombre, estado, fase, fuente, ubicación, - descripción, requisitos de equipo y resultados esperados. + públicos exponen su información base en el listado y el detalle, incluida la + descripción y el nombre del proponente; el correo, la cédula, el equipo y los + anexos quedan reservados a los miembros. La vista previa de un privado expone + aún menos: nombre, estado, fase, fuente, ubicación, descripción, requisitos de + equipo y resultados esperados. - `canExpressInterest` exige rol global `student`, proyecto `approved`, y que el solicitante no sea el proponente ni un actor asignado. El interés duplicado y el estado se validan en `ProjectsService`. diff --git a/docs/frontend_arch.md b/docs/frontend_arch.md index 5e71654..9778e9a 100644 --- a/docs/frontend_arch.md +++ b/docs/frontend_arch.md @@ -18,7 +18,7 @@ Ver también: [Arquitectura del backend](./backend_arch.md), - `app/api/` — route handlers que actúan como BFF/proxy hacia el backend. - `app/services/` — acceso a datos y sesión. - `app/components/` — componentes propios (shell, sidebar, navbar, auth, - formularios). + formularios y controles compartidos de listados). - `components/ui/` — componentes base de shadcn/ui. - `lib/utils.ts` — utilidades (por ejemplo `cn`). - `lib/download.ts` — descarga de respuestas binarias y lectura de `Content-Disposition`. @@ -29,6 +29,7 @@ Ver también: [Arquitectura del backend](./backend_arch.md), | Ruta | Pantalla | | --- | --- | | `/` | Landing pública, sin sidebar ni topbar. | +| `/gallery` | Galería pública de proyectos finalizados y no privados (`GET /projects` sin sesión), con búsqueda, filtros de fuente y año en la barra, orden y paginación en cliente; topbar de marca y sin sidebar. | | `/home` | Inicio interno (requiere sesión): proyectos propios y asignados del usuario. | | `/login` | Inicio de sesión. | | `/register` | Registro de proponentes (auto-login). | diff --git a/docs/frontend_design_system.md b/docs/frontend_design_system.md index 0f038aa..b92dbe2 100644 --- a/docs/frontend_design_system.md +++ b/docs/frontend_design_system.md @@ -148,6 +148,12 @@ izquierda y un **topbar** claro (`bg-card`) sticky sobre el contenido. dropdown de perfil conserva **Mi perfil** y **Cerrar sesión**. - En login y registro no hay sidebar: el topbar recupera la marca estática a la izquierda y deja el formulario a ancho completo. +- La galería pública (`/gallery`) tampoco monta sidebar: usa el topbar con la + marca y el widget de sesión. Lista los proyectos finalizados y públicos en + tarjetas enlazadas al detalle, con búsqueda, filtros de fuente y año + integrados en la barra de búsqueda, orden y paginación de nueve tarjetas. En + móvil la barra se apila y la descripción se recorta a tres líneas. Reutiliza + los controles compartidos de listados y los estados de carga, vacío y error. - La landing pública (`/`) no monta sidebar ni topbar. El acceso a la sesión vive en el CTA **Iniciar sesión** del hero. @@ -160,8 +166,8 @@ pestañas de usuario dentro del cuerpo: la navegación vive solo en la sidebar. La landing `/` mantiene su hero y no publica header ni usa el shell. El inicio interno (`/home`) requiere sesión y publica su header como cualquier módulo. Las -pantallas cargadas sin `PageFrame` (login, registro y algunos estados de carga) -dejan el topbar sin título de módulo. +pantallas cargadas sin `PageFrame` (login, registro, galería y algunos estados de +carga) dejan el topbar sin título de módulo. ## Convenciones para pantallas nuevas diff --git a/hub-backend/prisma/fixtures/attachments/portada-auditoria-seguridad.jpg b/hub-backend/prisma/fixtures/attachments/portada-auditoria-seguridad.jpg deleted file mode 100644 index 851ceaf..0000000 Binary files a/hub-backend/prisma/fixtures/attachments/portada-auditoria-seguridad.jpg and /dev/null differ diff --git a/hub-backend/prisma/fixtures/attachments/portada-cacao.jpg b/hub-backend/prisma/fixtures/attachments/portada-cacao.jpg deleted file mode 100644 index 508b01a..0000000 Binary files a/hub-backend/prisma/fixtures/attachments/portada-cacao.jpg and /dev/null differ diff --git a/hub-backend/prisma/fixtures/attachments/portada-calidad-textil.jpg b/hub-backend/prisma/fixtures/attachments/portada-calidad-textil.jpg deleted file mode 100644 index 97d3c65..0000000 Binary files a/hub-backend/prisma/fixtures/attachments/portada-calidad-textil.jpg and /dev/null differ diff --git a/hub-backend/prisma/fixtures/attachments/portada-comercio-justo.jpg b/hub-backend/prisma/fixtures/attachments/portada-comercio-justo.jpg deleted file mode 100644 index 87538eb..0000000 Binary files a/hub-backend/prisma/fixtures/attachments/portada-comercio-justo.jpg and /dev/null differ diff --git a/hub-backend/prisma/fixtures/attachments/portada-demanda-electrica.jpg b/hub-backend/prisma/fixtures/attachments/portada-demanda-electrica.jpg deleted file mode 100644 index 3cdbff7..0000000 Binary files a/hub-backend/prisma/fixtures/attachments/portada-demanda-electrica.jpg and /dev/null differ diff --git a/hub-backend/prisma/fixtures/attachments/portada-deslizamientos.jpg b/hub-backend/prisma/fixtures/attachments/portada-deslizamientos.jpg deleted file mode 100644 index 123573b..0000000 Binary files a/hub-backend/prisma/fixtures/attachments/portada-deslizamientos.jpg and /dev/null differ diff --git a/hub-backend/prisma/fixtures/attachments/portada-donaciones.jpg b/hub-backend/prisma/fixtures/attachments/portada-donaciones.jpg deleted file mode 100644 index 24e56ff..0000000 Binary files a/hub-backend/prisma/fixtures/attachments/portada-donaciones.jpg and /dev/null differ diff --git a/hub-backend/prisma/fixtures/attachments/portada-economia-circular.jpg b/hub-backend/prisma/fixtures/attachments/portada-economia-circular.jpg deleted file mode 100644 index 5b63291..0000000 Binary files a/hub-backend/prisma/fixtures/attachments/portada-economia-circular.jpg and /dev/null differ diff --git a/hub-backend/prisma/fixtures/attachments/portada-firma-electronica.jpg b/hub-backend/prisma/fixtures/attachments/portada-firma-electronica.jpg deleted file mode 100644 index 4ef78e0..0000000 Binary files a/hub-backend/prisma/fixtures/attachments/portada-firma-electronica.jpg and /dev/null differ diff --git a/hub-backend/prisma/fixtures/attachments/portada-glaciares.jpg b/hub-backend/prisma/fixtures/attachments/portada-glaciares.jpg deleted file mode 100644 index 2e65423..0000000 Binary files a/hub-backend/prisma/fixtures/attachments/portada-glaciares.jpg and /dev/null differ diff --git a/hub-backend/prisma/fixtures/attachments/portada-historia-clinica.jpg b/hub-backend/prisma/fixtures/attachments/portada-historia-clinica.jpg deleted file mode 100644 index 4cda3e2..0000000 Binary files a/hub-backend/prisma/fixtures/attachments/portada-historia-clinica.jpg and /dev/null differ diff --git a/hub-backend/prisma/fixtures/attachments/portada-invernaderos.jpg b/hub-backend/prisma/fixtures/attachments/portada-invernaderos.jpg deleted file mode 100644 index 26a0b02..0000000 Binary files a/hub-backend/prisma/fixtures/attachments/portada-invernaderos.jpg and /dev/null differ diff --git a/hub-backend/prisma/fixtures/attachments/portada-kiosco-salud.jpg b/hub-backend/prisma/fixtures/attachments/portada-kiosco-salud.jpg deleted file mode 100644 index 8af4f54..0000000 Binary files a/hub-backend/prisma/fixtures/attachments/portada-kiosco-salud.jpg and /dev/null differ diff --git a/hub-backend/prisma/fixtures/attachments/portada-pasantias.jpg b/hub-backend/prisma/fixtures/attachments/portada-pasantias.jpg deleted file mode 100644 index e322eec..0000000 Binary files a/hub-backend/prisma/fixtures/attachments/portada-pasantias.jpg and /dev/null differ diff --git a/hub-backend/prisma/fixtures/attachments/portada-puentes.jpg b/hub-backend/prisma/fixtures/attachments/portada-puentes.jpg deleted file mode 100644 index f33bb1f..0000000 Binary files a/hub-backend/prisma/fixtures/attachments/portada-puentes.jpg and /dev/null differ diff --git a/hub-backend/prisma/fixtures/attachments/portada-robot-riego.jpg b/hub-backend/prisma/fixtures/attachments/portada-robot-riego.jpg deleted file mode 100644 index 4976675..0000000 Binary files a/hub-backend/prisma/fixtures/attachments/portada-robot-riego.jpg and /dev/null differ diff --git a/hub-backend/prisma/fixtures/attachments/portada-senderismo.jpg b/hub-backend/prisma/fixtures/attachments/portada-senderismo.jpg deleted file mode 100644 index 7b31bf6..0000000 Binary files a/hub-backend/prisma/fixtures/attachments/portada-senderismo.jpg and /dev/null differ diff --git a/hub-backend/prisma/fixtures/attachments/portada-turismo.jpg b/hub-backend/prisma/fixtures/attachments/portada-turismo.jpg deleted file mode 100644 index 8eaafa1..0000000 Binary files a/hub-backend/prisma/fixtures/attachments/portada-turismo.jpg and /dev/null differ diff --git a/hub-backend/prisma/fixtures/attachments/portada-ultima-milla.jpg b/hub-backend/prisma/fixtures/attachments/portada-ultima-milla.jpg deleted file mode 100644 index 3efcd95..0000000 Binary files a/hub-backend/prisma/fixtures/attachments/portada-ultima-milla.jpg and /dev/null differ diff --git a/hub-backend/prisma/fixtures/projects.json b/hub-backend/prisma/fixtures/projects.json index f895500..4e01ac5 100644 --- a/hub-backend/prisma/fixtures/projects.json +++ b/hub-backend/prisma/fixtures/projects.json @@ -336,7 +336,7 @@ { "email": "student.valentina@capstonehub.test", "role": "student" }, { "email": "student.sebastian@capstonehub.test", "role": "student" } ], - "attachments": ["portada-cacao.jpg", "anteproyecto.pdf"] + "attachments": ["anteproyecto.pdf"] }, { "name": "Sistema de Alerta Temprana de Deslizamientos", @@ -369,7 +369,7 @@ { "email": "student.camila@capstonehub.test", "role": "student" }, { "email": "student.esteban@capstonehub.test", "role": "student" } ], - "attachments": ["portada-deslizamientos.jpg", "anteproyecto.pdf"] + "attachments": ["anteproyecto.pdf"] }, { "name": "Portal de Comercio Justo para Artesanos Salasacas", @@ -403,7 +403,7 @@ { "email": "student.daniela@capstonehub.test", "role": "student" }, { "email": "student.isabela@capstonehub.test", "role": "student" } ], - "attachments": ["portada-comercio-justo.jpg", "logo-proyecto.png"] + "attachments": ["logo-proyecto.png"] }, { "name": "Gemelo Digital para Riego de Invernaderos", @@ -437,7 +437,7 @@ { "email": "student.martin@capstonehub.test", "role": "student" }, { "email": "student.mateo@capstonehub.test", "role": "student" } ], - "attachments": ["portada-invernaderos.jpg", "anteproyecto.pdf"] + "attachments": ["anteproyecto.pdf"] }, { "name": "Kiosco de Salud Comunitaria Autónomo", @@ -471,7 +471,7 @@ { "email": "student.valentina@capstonehub.test", "role": "student" }, { "email": "student.camila@capstonehub.test", "role": "student" } ], - "attachments": ["portada-kiosco-salud.jpg", "anteproyecto.pdf"] + "attachments": ["anteproyecto.pdf"] }, { "name": "Análisis de Flujo Turístico con Datos Abiertos", @@ -505,7 +505,7 @@ { "email": "student.daniela@capstonehub.test", "role": "student" }, { "email": "student.esteban@capstonehub.test", "role": "student" } ], - "attachments": ["portada-turismo.jpg"] + "attachments": [] }, { "name": "Robot de Inspección para Galerías de Riego", @@ -539,7 +539,7 @@ { "email": "student.esteban@capstonehub.test", "role": "student" }, { "email": "student.martin@capstonehub.test", "role": "student" } ], - "attachments": ["portada-robot-riego.jpg", "anteproyecto.pdf"] + "attachments": ["anteproyecto.pdf"] }, { "name": "Optimización Logística de Última Milla", @@ -573,7 +573,7 @@ { "email": "student.mateo@capstonehub.test", "role": "student" }, { "email": "student.valentina@capstonehub.test", "role": "student" } ], - "attachments": ["portada-ultima-milla.jpg"] + "attachments": [] }, { "name": "Monitoreo Estructural de Puentes con Sensores IoT", @@ -606,7 +606,7 @@ { "email": "student.camila@capstonehub.test", "role": "student" }, { "email": "student.martin@capstonehub.test", "role": "student" } ], - "attachments": ["portada-puentes.jpg", "anteproyecto.pdf"] + "attachments": ["anteproyecto.pdf"] }, { "name": "Plataforma de Economía Circular para Mipymes", @@ -639,7 +639,7 @@ { "email": "student.isabela@capstonehub.test", "role": "student" }, { "email": "student.daniela@capstonehub.test", "role": "student" } ], - "attachments": ["portada-economia-circular.jpg"] + "attachments": [] }, { "name": "Control de Calidad Textil con Visión por Computador", @@ -673,7 +673,7 @@ { "email": "student.sebastian@capstonehub.test", "role": "student" }, { "email": "student.esteban@capstonehub.test", "role": "student" } ], - "attachments": ["portada-calidad-textil.jpg", "anteproyecto.pdf"] + "attachments": ["anteproyecto.pdf"] }, { "name": "App de Senderismo Seguro para los Andes", @@ -706,7 +706,7 @@ { "email": "student.valentina@capstonehub.test", "role": "student" }, { "email": "student.camila@capstonehub.test", "role": "student" } ], - "attachments": ["portada-senderismo.jpg"] + "attachments": [] }, { "name": "Módulo de Firma Electrónica para Trámites Académicos", @@ -740,7 +740,7 @@ { "email": "student.daniela@capstonehub.test", "role": "student" }, { "email": "student.mateo@capstonehub.test", "role": "student" } ], - "attachments": ["portada-firma-electronica.jpg", "logo-proyecto.png"] + "attachments": ["logo-proyecto.png"] }, { "name": "Predicción de Demanda Eléctrica con Machine Learning", @@ -774,7 +774,7 @@ { "email": "student.esteban@capstonehub.test", "role": "student" }, { "email": "student.isabela@capstonehub.test", "role": "student" } ], - "attachments": ["portada-demanda-electrica.jpg", "anteproyecto.pdf"] + "attachments": ["anteproyecto.pdf"] }, { "name": "Trazabilidad de Donaciones para Fundaciones", @@ -807,7 +807,7 @@ { "email": "student.martin@capstonehub.test", "role": "student" }, { "email": "student.valentina@capstonehub.test", "role": "student" } ], - "attachments": ["portada-donaciones.jpg"] + "attachments": [] }, { "name": "Auditoría de Seguridad de la Plataforma Académica", @@ -841,7 +841,7 @@ { "email": "student.mateo@capstonehub.test", "role": "student" }, { "email": "student.sebastian@capstonehub.test", "role": "student" } ], - "attachments": ["portada-auditoria-seguridad.jpg"] + "attachments": [] }, { "name": "Historia Clínica Electrónica para Convenio Hospitalario", @@ -875,7 +875,7 @@ { "email": "student.camila@capstonehub.test", "role": "student" }, { "email": "student.daniela@capstonehub.test", "role": "student" } ], - "attachments": ["portada-historia-clinica.jpg"] + "attachments": [] }, { "name": "Plataforma de Pasantías y Vinculación", @@ -908,7 +908,7 @@ { "email": "student.isabela@capstonehub.test", "role": "student" }, { "email": "student.martin@capstonehub.test", "role": "student" } ], - "attachments": ["portada-pasantias.jpg"] + "attachments": [] }, { "name": "Biofertilizantes a partir de Residuos Agroindustriales", @@ -999,7 +999,7 @@ { "email": "student.esteban@capstonehub.test", "role": "student" }, { "email": "student.camila@capstonehub.test", "role": "student" } ], - "attachments": ["portada-glaciares.jpg", "anteproyecto.pdf"] + "attachments": ["anteproyecto.pdf"] } ] } diff --git a/hub-backend/src/projects/project-exports.service.spec.ts b/hub-backend/src/projects/project-exports.service.spec.ts index 133813f..3a89990 100644 --- a/hub-backend/src/projects/project-exports.service.spec.ts +++ b/hub-backend/src/projects/project-exports.service.spec.ts @@ -24,6 +24,7 @@ const user: AuthenticatedUser = { const listProject: ProjectListResponse = { id: 1, name: 'Proyecto Demo', + description: 'Descripción del proyecto', status: ProjectStatus.approved, phase: ProjectPhase.semester_1, startDate: new Date('2026-01-15T00:00:00Z'), diff --git a/hub-backend/src/projects/projects.select.ts b/hub-backend/src/projects/projects.select.ts index 88d966b..ccebb45 100644 --- a/hub-backend/src/projects/projects.select.ts +++ b/hub-backend/src/projects/projects.select.ts @@ -122,6 +122,7 @@ export type ProjectProposerResponse = { export type ProjectListResponse = { id: number; name: string; + description: string; status: ProjectStatus; phase: ProjectPhase; startDate: Date | null; @@ -422,6 +423,7 @@ export function mapProjectListResponse( return { id: project.id, name: project.name, + description: project.description, status: project.status, phase: project.phase, startDate: isPrivatePreview ? null : project.startDate, diff --git a/hub-backend/test/projects.e2e-spec.ts b/hub-backend/test/projects.e2e-spec.ts index 4baa9f1..c4b75ea 100644 --- a/hub-backend/test/projects.e2e-spec.ts +++ b/hub-backend/test/projects.e2e-spec.ts @@ -18,6 +18,7 @@ import { ProjectStatus, UserRole, } from '../src/generated/prisma/client'; +import { PrismaService } from '../src/prisma.service'; describe('Projects (e2e)', () => { const getApp = useTestApp(); @@ -317,4 +318,59 @@ describe('Projects (e2e)', () => { ), ).toBe(false); }); + + it('expone al público solo los proyectos finalizados y no privados', async () => { + const app = getApp(); + const prisma = app.get(PrismaService); + const { projectId } = await createProjectWithProposer(app, false); + const { projectId: privateProjectId } = await createProjectWithProposer( + app, + true, + ); + const { projectId: pendingProjectId } = await createProjectWithProposer( + app, + false, + ); + + await prisma.project.updateMany({ + where: { id: { in: [projectId, privateProjectId] } }, + data: { status: ProjectStatus.closed }, + }); + + const list = await request(app.getHttpServer()) + .get('/projects?status=closed&isPrivate=false&sort=year-desc&limit=100') + .expect(200); + + const projects = list.body as { + id: number; + description: string; + canViewSensitiveData: boolean; + isPrivatePreview: boolean; + actors: unknown[]; + proposer: { + fullName: string; + email: string | null; + idNumber: string | null; + } | null; + }[]; + const ids = projects.map((project) => project.id); + + expect(ids).toContain(projectId); + expect(ids).not.toContain(privateProjectId); + expect(ids).not.toContain(pendingProjectId); + + const project = projects.find((item) => item.id === projectId); + + expect(project).toMatchObject({ + description: 'Descripción del proyecto', + canViewSensitiveData: false, + isPrivatePreview: false, + }); + expect(project?.proposer).toMatchObject({ + fullName: 'Proponente E2E', + email: null, + idNumber: null, + }); + expect(project?.actors).toEqual([]); + }); }); diff --git a/hub-frontend/app/components/app-shell.tsx b/hub-frontend/app/components/app-shell.tsx index c942184..bad5b40 100644 --- a/hub-frontend/app/components/app-shell.tsx +++ b/hub-frontend/app/components/app-shell.tsx @@ -8,17 +8,18 @@ import { TooltipProvider } from "@/components/ui/tooltip"; /** * Shell de la plataforma: sidebar fija a la izquierda + topbar sticky. La - * landing pública (`/`) no monta chrome; login y registro solo muestran el - * topbar con la marca. + * landing pública (`/`) no monta chrome; la galería pública (`/gallery`) y + * las pantallas de autenticación solo muestran el topbar con la marca. */ export default function AppShell({ children, }: Readonly<{ children: React.ReactNode }>) { const pathname = usePathname(); const isLanding = pathname === "/"; + const isGallery = pathname.startsWith("/gallery"); const isAuthPage = pathname.startsWith("/login") || pathname.startsWith("/register"); - const showSidebar = !isLanding && !isAuthPage; + const showSidebar = !isLanding && !isGallery && !isAuthPage; if (isLanding) { return <>{children}; diff --git a/hub-frontend/app/components/filter-checkbox.tsx b/hub-frontend/app/components/filter-checkbox.tsx new file mode 100644 index 0000000..bf56cb9 --- /dev/null +++ b/hub-frontend/app/components/filter-checkbox.tsx @@ -0,0 +1,35 @@ +"use client"; + +import { Checkbox } from "@/components/ui/checkbox"; + +type FilterCheckboxProps = { + readonly id: string; + readonly label: string; + readonly checked: boolean; + readonly onChange: (checked: boolean) => void; +}; + +/** Casilla con etiqueta para los paneles de filtros rápidos. */ +export default function FilterCheckbox({ + id, + label, + checked, + onChange, +}: FilterCheckboxProps) { + return ( +
+ onChange(value === true)} + /> + + +
+ ); +} diff --git a/hub-frontend/app/components/filter-popover.tsx b/hub-frontend/app/components/filter-popover.tsx new file mode 100644 index 0000000..9ce8928 --- /dev/null +++ b/hub-frontend/app/components/filter-popover.tsx @@ -0,0 +1,143 @@ +"use client"; + +import { useId, useState } from "react"; +import { RiArrowDownSLine } from "@remixicon/react"; +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { Checkbox } from "@/components/ui/checkbox"; +import { Input } from "@/components/ui/input"; +import { + Popover, + PopoverContent, + PopoverTrigger, +} from "@/components/ui/popover"; + +export type FilterOption = { + readonly value: string; + readonly label: string; +}; + +type FilterPopoverProps = { + readonly label: string; + readonly options: readonly FilterOption[]; + readonly selected: string[]; + readonly onChange: (selected: string[]) => void; + readonly searchable?: boolean; +}; + +function toggleValue(values: string[], value: string): string[] { + return values.includes(value) + ? values.filter((currentValue) => currentValue !== value) + : [...values, value]; +} + +/** Popover de selección múltiple reutilizable para filtros de listados. */ +export default function FilterPopover({ + label, + options, + selected, + onChange, + searchable = false, +}: FilterPopoverProps) { + const id = useId(); + const [query, setQuery] = useState(""); + + const normalizedQuery = query.trim().toLowerCase(); + const visibleOptions = normalizedQuery + ? options.filter((option) => + option.label.toLowerCase().includes(normalizedQuery), + ) + : options; + + return ( + + + } + > + {label} + + {selected.length > 0 ? ( + + {selected.length} + + ) : null} + + + + +
+ + {label} + + + {selected.length > 0 ? ( + + ) : null} +
+ + {searchable ? ( +
+ setQuery(event.target.value)} + placeholder={`Buscar ${label.toLowerCase()}...`} + aria-label={`Buscar ${label.toLowerCase()}`} + className="h-7" + /> +
+ ) : null} + +
+ {visibleOptions.length > 0 ? ( + visibleOptions.map((option, index) => ( +
+ + onChange(toggleValue(selected, option.value)) + } + /> + + +
+ )) + ) : ( +

+ Sin opciones. +

+ )} +
+
+
+ ); +} diff --git a/hub-frontend/app/components/list-pagination.tsx b/hub-frontend/app/components/list-pagination.tsx new file mode 100644 index 0000000..e0062fe --- /dev/null +++ b/hub-frontend/app/components/list-pagination.tsx @@ -0,0 +1,82 @@ +"use client"; + +import { useState } from "react"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; + +type ListPaginationProps = { + readonly id: string; + readonly pageIndex: number; + readonly pageCount: number; + readonly onPageChange: (pageIndex: number) => void; +}; + +/** Paginación numérica reutilizable para listados y galerías. */ +export default function ListPagination({ + id, + pageIndex, + pageCount, + onPageChange, +}: ListPaginationProps) { + const [pageDraft, setPageDraft] = useState(null); + const currentPage = Math.min(pageIndex + 1, pageCount); + + function commitPage() { + const parsed = Number.parseInt(pageDraft ?? "", 10); + + if (Number.isNaN(parsed)) { + setPageDraft(null); + return; + } + + onPageChange(Math.min(Math.max(parsed, 1), pageCount) - 1); + setPageDraft(null); + } + + return ( +
+
+ + + setPageDraft(event.target.value)} + onBlur={commitPage} + onKeyDown={(event) => { + if (event.key === "Enter") { + commitPage(); + } + }} + className="h-7 w-14 px-1 text-center" + /> + + de {pageCount} +
+ +
+ + + +
+
+ ); +} diff --git a/hub-frontend/app/components/list-search-input.tsx b/hub-frontend/app/components/list-search-input.tsx new file mode 100644 index 0000000..243e65f --- /dev/null +++ b/hub-frontend/app/components/list-search-input.tsx @@ -0,0 +1,40 @@ +"use client"; + +import { RiSearchLine } from "@remixicon/react"; +import { Input } from "@/components/ui/input"; +import { cn } from "@/lib/utils"; + +type ListSearchInputProps = { + readonly value: string; + readonly onChange: (value: string) => void; + readonly placeholder: string; + readonly ariaLabel: string; + readonly className?: string; +}; + +/** Campo de búsqueda reutilizable para listados y galerías. */ +export default function ListSearchInput({ + value, + onChange, + placeholder, + ariaLabel, + className, +}: ListSearchInputProps) { + return ( +
+
+ ); +} diff --git a/hub-frontend/app/components/sort-popover.tsx b/hub-frontend/app/components/sort-popover.tsx new file mode 100644 index 0000000..677b39f --- /dev/null +++ b/hub-frontend/app/components/sort-popover.tsx @@ -0,0 +1,89 @@ +"use client"; + +import { useState } from "react"; +import { RiArrowDownSLine, RiCheckLine } from "@remixicon/react"; +import { Button } from "@/components/ui/button"; +import { + Popover, + PopoverContent, + PopoverTrigger, +} from "@/components/ui/popover"; + +export type SortOption = { + readonly value: T; + readonly label: string; +}; + +type SortPopoverProps = { + readonly value: T; + readonly options: readonly SortOption[]; + readonly onChange: (value: T) => void; + readonly placeholder?: string; + readonly placeholderValue?: T; + readonly title?: string; +}; + +/** Popover de orden reutilizable para listados y galerías. */ +export default function SortPopover({ + value, + options, + onChange, + placeholder = "Ordenar", + placeholderValue, + title = "Ordenar por", +}: SortPopoverProps) { + const [open, setOpen] = useState(false); + const selectedLabel = + options.find((option) => option.value === value)?.label ?? placeholder; + const showPlaceholder = + placeholderValue !== undefined && value === placeholderValue; + + return ( + + + } + > + {showPlaceholder ? placeholder : selectedLabel} + + + + +

+ {title} +

+ + {options.map((option) => ( + + ))} +
+
+ ); +} diff --git a/hub-frontend/app/gallery/gallery-card.tsx b/hub-frontend/app/gallery/gallery-card.tsx new file mode 100644 index 0000000..e7a5185 --- /dev/null +++ b/hub-frontend/app/gallery/gallery-card.tsx @@ -0,0 +1,94 @@ +import type { CSSProperties } from "react"; +import Link from "next/link"; +import { + RiArrowRightLine, + RiMapPinLine, + RiUser3Line, +} from "@remixicon/react"; +import { Badge } from "@/components/ui/badge"; +import { + Card, + CardContent, + CardDescription, + CardHeader, + CardTitle, +} from "@/components/ui/card"; +import { getProjectYear } from "../projects/project-list-config"; +import type { ProjectItem } from "../services/schemas"; +import { formatProjectSource, formatStatus } from "../services/utils"; + +type GalleryCardProps = { + readonly project: ProjectItem; + readonly index: number; +}; + +export default function GalleryCard({ + project, + index, +}: GalleryCardProps) { + const year = getProjectYear(project); + + return ( + + + +
+ {formatStatus(project.status)} + + {year ? ( + {year} + ) : null} +
+ + + {project.name} + + + + {project.description || "Sin descripción disponible."} + +
+ + +
+ {project.proposer?.fullName ? ( + + + ) : null} + + {project.location ? ( + + + ) : null} + + {project.source ? ( + + {formatProjectSource(project.source)} + + ) : null} +
+ + + Ver detalle + +
+
+ + ); +} diff --git a/hub-frontend/app/gallery/gallery-explorer.tsx b/hub-frontend/app/gallery/gallery-explorer.tsx new file mode 100644 index 0000000..d379168 --- /dev/null +++ b/hub-frontend/app/gallery/gallery-explorer.tsx @@ -0,0 +1,161 @@ +"use client"; + +import { useEffect, useMemo, useState } from "react"; +import { useSearchParams } from "next/navigation"; +import { useApiResource } from "@/lib/use-api-resource"; +import { getProjects } from "../services/projects"; +import { buildYearOptions } from "../projects/project-list-config"; +import { useRemoteProjects } from "../projects/use-remote-projects"; +import { + GALLERY_BASE_QUERY, + createDefaultGalleryFilters, + galleryFiltersFromSearchParams, + galleryFiltersToApiQuery, + galleryFiltersToSearchParams, + hasActiveGalleryFilters, + type GalleryFilters, +} from "./gallery-filters"; +import GalleryResults from "./gallery-results"; +import GalleryToolbar from "./gallery-toolbar"; + +export default function GalleryExplorer() { + const searchParams = useSearchParams(); + const [filters, setFilters] = useState(() => + galleryFiltersFromSearchParams( + new URLSearchParams(searchParams.toString()), + ), + ); + const [pageIndex, setPageIndex] = useState(0); + const [reloadKey, setReloadKey] = useState(0); + + const { + data: baseData, + loading: baseLoading, + error: baseError, + } = useApiResource( + () => getProjects(GALLERY_BASE_QUERY), + [reloadKey], + ); + + const hasActiveFilters = hasActiveGalleryFilters(filters); + const apiQuery = useMemo( + () => galleryFiltersToApiQuery(filters), + [filters], + ); + const queryKey = useMemo(() => JSON.stringify(apiQuery), [apiQuery]); + const remoteProjects = useRemoteProjects({ + enabled: hasActiveFilters, + query: apiQuery, + queryKey, + reloadKey, + }); + + const currentRemote = + remoteProjects?.queryKey === queryKey ? remoteProjects : null; + const baseProjects = useMemo( + () => baseData?.projects ?? [], + [baseData], + ); + const projects = hasActiveFilters + ? (remoteProjects?.projects ?? []) + : baseProjects; + + const yearOptions = useMemo(() => { + const options = buildYearOptions(baseProjects); + const values = new Set(options.map((option) => option.value)); + + for (const selected of filters.year) { + if (!values.has(selected)) { + options.push({ + value: selected, + label: selected === "sin-anio" ? "Sin año" : selected, + }); + values.add(selected); + } + } + + return options.sort((left, right) => { + if (left.value === "sin-anio") { + return 1; + } + + if (right.value === "sin-anio") { + return -1; + } + + return Number(right.value) - Number(left.value); + }); + }, [baseProjects, filters.year]); + + const loading = hasActiveFilters ? remoteProjects === null : baseLoading; + const status = hasActiveFilters + ? currentRemote?.status + : baseData?.status; + const error = hasActiveFilters + ? (currentRemote?.error ?? null) + : (baseData?.error ?? baseError ?? null); + + useEffect(() => { + function handlePopState() { + setFilters( + galleryFiltersFromSearchParams( + new URLSearchParams(window.location.search), + ), + ); + setPageIndex(0); + } + + window.addEventListener("popstate", handlePopState); + + return () => window.removeEventListener("popstate", handlePopState); + }, []); + + useEffect(() => { + const nextSearch = galleryFiltersToSearchParams(filters).toString(); + const currentSearch = window.location.search.replace(/^\?/, ""); + + if (nextSearch === currentSearch) { + return; + } + + const nextUrl = `${window.location.pathname}${ + nextSearch ? `?${nextSearch}` : "" + }${window.location.hash}`; + + window.history.replaceState(null, "", nextUrl); + }, [filters]); + + function handleFiltersChange(nextFilters: GalleryFilters) { + setFilters(nextFilters); + setPageIndex(0); + } + + function clearFilters() { + setFilters(createDefaultGalleryFilters()); + setPageIndex(0); + } + + return ( +
+ + + setReloadKey((key) => key + 1)} + /> +
+ ); +} diff --git a/hub-frontend/app/gallery/gallery-filters.ts b/hub-frontend/app/gallery/gallery-filters.ts new file mode 100644 index 0000000..18b32c2 --- /dev/null +++ b/hub-frontend/app/gallery/gallery-filters.ts @@ -0,0 +1,135 @@ +import { + PROJECT_FILTER_PARAMS, + PROJECT_SORT_OPTIONS, + isProjectSource, + type ProjectSort, +} from "../projects/project-list-config"; +import type { ProjectListQuery } from "../services/projects"; + +export type GallerySort = Exclude; + +export type GalleryFilters = { + search: string; + source: string[]; + year: string[]; + sort: GallerySort; +}; + +export const GALLERY_PAGE_SIZE = 9; + +export const GALLERY_SORT_OPTIONS: { value: GallerySort; label: string }[] = + PROJECT_SORT_OPTIONS.filter( + (option) => option.value !== "relevance", + ) as { value: GallerySort; label: string }[]; + +const GALLERY_SORT_VALUES = new Set( + GALLERY_SORT_OPTIONS.map((option) => option.value), +); + +/** Filtros que siempre acompañan a la galería: solo proyectos públicos cerrados. */ +export const GALLERY_BASE_QUERY: ProjectListQuery = { + status: ["closed"], + isPrivate: false, + sort: "year-desc", + limit: 100, +}; + +export function createDefaultGalleryFilters(): GalleryFilters { + return { + search: "", + source: [], + year: [], + sort: "year-desc", + }; +} + +export function isGallerySort(value: string | null): value is GallerySort { + return value !== null && GALLERY_SORT_VALUES.has(value); +} + +function isGalleryYear(value: string): boolean { + return value === "sin-anio" || /^\d{4}$/.test(value); +} + +export function galleryFiltersFromSearchParams( + searchParams: URLSearchParams, +): GalleryFilters { + return { + search: searchParams.get(PROJECT_FILTER_PARAMS.search) ?? "", + source: searchParams + .getAll(PROJECT_FILTER_PARAMS.source) + .filter(isProjectSource), + year: searchParams + .getAll(PROJECT_FILTER_PARAMS.year) + .filter(isGalleryYear), + sort: isGallerySort(searchParams.get(PROJECT_FILTER_PARAMS.sort)) + ? (searchParams.get(PROJECT_FILTER_PARAMS.sort) as GallerySort) + : "year-desc", + }; +} + +export function galleryFiltersToSearchParams( + filters: GalleryFilters, +): URLSearchParams { + const params = new URLSearchParams(); + const search = filters.search.trim(); + + if (search) { + params.set(PROJECT_FILTER_PARAMS.search, search); + } + + filters.source.forEach((value) => + params.append(PROJECT_FILTER_PARAMS.source, value), + ); + filters.year.forEach((value) => + params.append(PROJECT_FILTER_PARAMS.year, value), + ); + + if (filters.sort !== "year-desc") { + params.set(PROJECT_FILTER_PARAMS.sort, filters.sort); + } + + return params; +} + +export function galleryFiltersToApiQuery( + filters: GalleryFilters, +): ProjectListQuery { + const query: ProjectListQuery = { + ...GALLERY_BASE_QUERY, + sort: filters.sort, + }; + const search = filters.search.trim(); + + if (search) { + query.search = search; + } + + if (filters.source.length > 0) { + query.source = filters.source; + } + + const years = filters.year + .filter((year) => year !== "sin-anio") + .map(Number) + .filter((year) => Number.isInteger(year)); + + if (years.length > 0) { + query.year = years; + } + + if (filters.year.includes("sin-anio")) { + query.withoutYear = true; + } + + return query; +} + +export function hasActiveGalleryFilters(filters: GalleryFilters): boolean { + return ( + filters.search.trim() !== "" || + filters.source.length > 0 || + filters.year.length > 0 || + filters.sort !== "year-desc" + ); +} diff --git a/hub-frontend/app/gallery/gallery-results.tsx b/hub-frontend/app/gallery/gallery-results.tsx new file mode 100644 index 0000000..1644029 --- /dev/null +++ b/hub-frontend/app/gallery/gallery-results.tsx @@ -0,0 +1,127 @@ +"use client"; + +import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"; +import { Button } from "@/components/ui/button"; +import { + Empty, + EmptyContent, + EmptyDescription, + EmptyHeader, + EmptyTitle, +} from "@/components/ui/empty"; +import { isServiceUnavailableStatus } from "@/lib/http"; +import ListPagination from "../components/list-pagination"; +import ServiceUnavailable from "../components/service-unavailable"; +import type { ProjectItem } from "../services/schemas"; +import GalleryCard from "./gallery-card"; +import { GALLERY_PAGE_SIZE } from "./gallery-filters"; +import GallerySkeleton from "./gallery-skeleton"; + +type GalleryResultsProps = { + readonly projects: ProjectItem[]; + readonly loading: boolean; + readonly status?: number; + readonly error: string | null; + readonly hasActiveFilters: boolean; + readonly pageIndex: number; + readonly onPageChange: (pageIndex: number) => void; + readonly onClearFilters: () => void; + readonly onRetry: () => void; +}; + +export default function GalleryResults({ + projects, + loading, + status, + error, + hasActiveFilters, + pageIndex, + onPageChange, + onClearFilters, + onRetry, +}: GalleryResultsProps) { + if (loading) { + return ; + } + + if (isServiceUnavailableStatus(status)) { + return ; + } + + if (error) { + return ( + + No se pudo cargar la galería + + {error} +
+ +
+
+
+ ); + } + + if (projects.length === 0) { + return ( + + + + {hasActiveFilters + ? "No hay proyectos con esos filtros" + : "Aún no hay proyectos finalizados"} + + + {hasActiveFilters + ? "Prueba a cambiar la búsqueda o a limpiar los filtros seleccionados." + : "La galería se llenará a medida que los proyectos cierren su ciclo."} + + + + {hasActiveFilters ? ( + + + + ) : null} + + ); + } + + const pageCount = Math.max( + 1, + Math.ceil(projects.length / GALLERY_PAGE_SIZE), + ); + const safePageIndex = Math.min(pageIndex, pageCount - 1); + const paginatedProjects = projects.slice( + safePageIndex * GALLERY_PAGE_SIZE, + (safePageIndex + 1) * GALLERY_PAGE_SIZE, + ); + + return ( + <> +

+ {projects.length}{" "} + {projects.length === 1 ? "proyecto" : "proyectos"} +

+ +
+ {paginatedProjects.map((project, index) => ( + + ))} +
+ + {pageCount > 1 ? ( + + ) : null} + + ); +} diff --git a/hub-frontend/app/gallery/gallery-skeleton.tsx b/hub-frontend/app/gallery/gallery-skeleton.tsx new file mode 100644 index 0000000..6523019 --- /dev/null +++ b/hub-frontend/app/gallery/gallery-skeleton.tsx @@ -0,0 +1,20 @@ +import { Skeleton } from "@/components/ui/skeleton"; + +const SKELETON_KEYS = [ + "skeleton-a", + "skeleton-b", + "skeleton-c", + "skeleton-d", + "skeleton-e", + "skeleton-f", +] as const; + +export default function GallerySkeleton() { + return ( +
+ {SKELETON_KEYS.map((key) => ( + + ))} +
+ ); +} diff --git a/hub-frontend/app/gallery/gallery-toolbar.tsx b/hub-frontend/app/gallery/gallery-toolbar.tsx new file mode 100644 index 0000000..288fc0b --- /dev/null +++ b/hub-frontend/app/gallery/gallery-toolbar.tsx @@ -0,0 +1,78 @@ +"use client"; + +import { Button } from "@/components/ui/button"; +import FilterPopover from "../components/filter-popover"; +import ListSearchInput from "../components/list-search-input"; +import SortPopover from "../components/sort-popover"; +import { + PROJECT_SOURCE_OPTIONS, + type FilterOption, +} from "../projects/project-list-config"; +import { + GALLERY_SORT_OPTIONS, + type GalleryFilters, +} from "./gallery-filters"; + +type GalleryToolbarProps = { + readonly filters: GalleryFilters; + readonly yearOptions: FilterOption[]; + readonly onFiltersChange: (filters: GalleryFilters) => void; + readonly hasActiveFilters: boolean; + readonly onClearFilters: () => void; +}; + +export default function GalleryToolbar({ + filters, + yearOptions, + onFiltersChange, + hasActiveFilters, + onClearFilters, +}: GalleryToolbarProps) { + return ( +
+
+
+ onFiltersChange({ ...filters, search })} + placeholder="Buscar en la galería..." + ariaLabel="Buscar en la galería" + /> +
+ +
+ onFiltersChange({ ...filters, source })} + /> + + onFiltersChange({ ...filters, year })} + /> + + onFiltersChange({ ...filters, sort })} + /> + + {hasActiveFilters ? ( + + ) : null} +
+
+
+ ); +} diff --git a/hub-frontend/app/gallery/page.tsx b/hub-frontend/app/gallery/page.tsx new file mode 100644 index 0000000..d898642 --- /dev/null +++ b/hub-frontend/app/gallery/page.tsx @@ -0,0 +1,33 @@ +import type { Metadata } from "next"; +import { Suspense } from "react"; +import GalleryExplorer from "./gallery-explorer"; +import GallerySkeleton from "./gallery-skeleton"; + +const GALLERY_DESCRIPTION = + "Proyectos finalizados de la Universidad Tecnológica de Bolívar."; + +export const metadata: Metadata = { + title: "Galería de proyectos | CapstoneHUB", + description: GALLERY_DESCRIPTION, +}; + +export default function GalleryPage() { + return ( +
+
+
+

+ Galería +

+

+ {GALLERY_DESCRIPTION} +

+
+ + }> + + +
+
+ ); +} diff --git a/hub-frontend/app/page.tsx b/hub-frontend/app/page.tsx index 4b14c88..9dc34ca 100644 --- a/hub-frontend/app/page.tsx +++ b/hub-frontend/app/page.tsx @@ -104,6 +104,15 @@ export default function Home() { Iniciar sesión + + + Explorar la galería de proyectos finalizados +