From 50ec2ac5ac46b2b36074d9ec2eab271833628e2e Mon Sep 17 00:00:00 2001 From: wate <110754234+r0liveir@users.noreply.github.com> Date: Wed, 2 Sep 2026 20:46:48 -0300 Subject: [PATCH 01/19] feat(db): define conference assignments Co-authored-by: Codex --- .../20260719224327_create_initial_tables.sql | 125 ++++++++++++++---- supabase/seed.sql | 11 +- 2 files changed, 110 insertions(+), 26 deletions(-) diff --git a/supabase/migrations/20260719224327_create_initial_tables.sql b/supabase/migrations/20260719224327_create_initial_tables.sql index ce34ead..ea021c1 100644 --- a/supabase/migrations/20260719224327_create_initial_tables.sql +++ b/supabase/migrations/20260719224327_create_initial_tables.sql @@ -1,68 +1,144 @@ create type activity_status as enum ('active', 'closed', 'planned', 'cancelled'); -create type committee_role as enum ('chair', 'delegate'); create type asset_type as enum ('preset', 'custom'); +create type committee_role as enum ('chair', 'delegate', 'observer'); +create type conference_role as enum ( + 'owner', + 'secretary_general', + 'director', + 'moderator', + 'rapporteur', + 'crisis_staff', + 'press', + 'logistics', + 'staff' +); + +------------------------------- +-- Conferences and committees +------------------------------- create table conferences ( - id bigint primary key generated always as identity, + id bigint primary key generated always as identity, name varchar(255) not null, status activity_status not null default 'planned', - owner_id uuid not null references auth.users on delete cascade + owner_id uuid null references auth.users(id) on delete set null, + location varchar(255), + logo_url varchar(1000), + theme_color varchar(7), + start_date timestamptz, + end_date timestamptz, + created_at timestamptz not null default now(), + updated_at timestamptz not null default now(), + + constraint conferences_theme_color_hex check ( + theme_color is null or theme_color ~ '^#[0-9A-Fa-f]{6}$' + ), + constraint conferences_date_range check ( + start_date is null or end_date is null or start_date <= end_date + ) ); create table committees ( id bigint primary key generated always as identity, - conference_id bigint not null references conferences(id), + conference_id bigint not null references conferences(id) on delete cascade, name varchar(64) not null, - status activity_status not null default 'planned' + status activity_status not null default 'planned', + created_at timestamptz not null default now(), + updated_at timestamptz not null default now(), + + -- Enables conference_assignments to verify committee_id belongs to the same conference_id. + constraint committees_id_conference_unique unique (id, conference_id) ); --- This table references preset/custom representations that we might work with. We can perhaps separate the two of them later +------------------------------- +-- Representations and layouts +------------------------------- + +-- Preset/custom separation is represented here, but detailed policy can stay in app logic for now. create table representations ( id bigint primary key generated always as identity, - name varchar(64), + name varchar(64) not null, rep_type asset_type not null default 'preset', code varchar(10), - identifier varchar(255) not null, -- this can be either an url if the rep_type is custom, or a code (like 'br') - conference_id bigint null -- if set references a specific conference. if we delete that conference entry, we might setup a custom handler on the - -- backend + identifier varchar(255) not null, + conference_id bigint null references conferences(id) on delete cascade, + created_at timestamptz not null default now() ); --- preset layouts for conferences create table layouts ( id bigint primary key generated always as identity, - name varchar(64), + name varchar(64) not null, conference_id bigint null references conferences(id) on delete cascade, - -- if conference_id is null, its a preset. else, its an overall layout for a conference - committee_id bigint null references committees(id) on delete cascade -- we can also customize for a committee + committee_id bigint null references committees(id) on delete cascade, + created_at timestamptz not null default now() ); --- present layout seats for conferences create table layout_seats ( layout_id bigint not null references layouts(id) on delete cascade, - representation_id bigint not null references representations(id) on delete cascade, - seat_label varchar(3), + representation_id bigint not null references representations(id) on delete cascade, + seat_label varchar(10), primary key (layout_id, representation_id) ); --- real committee seats. We'll use a copy-on-create strategy (thx codex) to populate this +-- Real committee seats. These are copied from a layout when a committee is configured. create table committee_seats ( committee_id bigint not null references committees(id) on delete cascade, representation_id bigint not null references representations(id) on delete cascade, - seat_label varchar(3), - + seat_label varchar(10), + primary key (committee_id, representation_id) ); +------------------------------- +-- Assignments +------------------------------- + +create table conference_assignments ( + id bigint primary key generated always as identity, + conference_id bigint not null references conferences(id) on delete cascade, + user_id uuid not null references auth.users(id) on delete cascade, + role conference_role not null, + committee_id bigint null, + created_at timestamptz not null default now(), + + -- A committee-scoped conference role must point to a committee in that same conference. + constraint conference_assignments_committee_in_conference foreign key ( + committee_id, + conference_id + ) references committees(id, conference_id) on delete cascade +); + +-- Split uniqueness because NULL committee_id values are not equal in a regular unique constraint. +create unique index conference_assignments_unique_conference_role + on conference_assignments (conference_id, user_id, role) + where committee_id is null; + +-- Committee-scoped roles dedupe separately from conference-wide roles. +create unique index conference_assignments_unique_committee_role + on conference_assignments (conference_id, user_id, role, committee_id) + where committee_id is not null; + create table committee_assignments ( - user_id uuid not null references auth.users(id) on delete cascade, + user_id uuid not null references auth.users(id) on delete cascade, committee_id bigint not null references committees(id) on delete cascade, role committee_role not null, - representation_id bigint null references representations(id), + representation_id bigint null references representations(id), - primary key (user_id, committee_id) + primary key (user_id, committee_id), + constraint committee_assignments_delegate_has_representation check ( + role <> 'delegate' or representation_id is not null + ) ); +create unique index committee_assignments_unique_representation + on committee_assignments (committee_id, representation_id) + where representation_id is not null; + +------------------------------- +-- Sessions +------------------------------- + create table sessions ( id bigint primary key generated always as identity, committee_id bigint not null references committees(id) on delete cascade, @@ -70,6 +146,5 @@ create table sessions ( status activity_status not null default 'planned', started_at timestamptz, ended_at timestamptz, - state_snapshot JSONB + state_snapshot jsonb ); - diff --git a/supabase/seed.sql b/supabase/seed.sql index 9b27847..98ddd53 100644 --- a/supabase/seed.sql +++ b/supabase/seed.sql @@ -10,6 +10,16 @@ insert into public.committees values ((select id from conferences where name = 'I WebMUN'), 'CSNU', 'planned'); +insert into public.conference_assignments + (conference_id, user_id, role, committee_id) +values + ( + (select id from conferences where name = 'I WebMUN'), + '11111111-1111-1111-1111-111111111111', + 'owner', + null + ); + insert into public.representations (name, code, identifier) values ('Albânia', 'al', 'al'), ('Alemanha', 'de', 'de'), @@ -100,4 +110,3 @@ insert into public.sessions (committee_id) values (1); - From 493e2eadeccba21e5a96bcec68f5e9b001dc9700 Mon Sep 17 00:00:00 2001 From: wate <110754234+r0liveir@users.noreply.github.com> Date: Wed, 2 Sep 2026 21:19:35 -0300 Subject: [PATCH 02/19] feat(backend): add conference module Co-authored-by: Codex --- backend/app/access/repository.py | 71 ++++- backend/app/access/service.py | 55 +++- backend/app/conference/__init__.py | 1 + backend/app/conference/enums.py | 19 ++ backend/app/conference/models.py | 36 +++ backend/app/conference/repository.py | 269 +++++++++++++++++++ backend/app/conference/schemas.py | 47 ++++ backend/app/conference/service.py | 151 +++++++++++ backend/app/conference/views.py | 108 ++++++++ backend/app/main.py | 2 + backend/app/tests/access/test_service.py | 65 ++++- backend/app/tests/conference/__init__.py | 1 + backend/app/tests/conference/test_service.py | 214 +++++++++++++++ 13 files changed, 1036 insertions(+), 3 deletions(-) create mode 100644 backend/app/conference/__init__.py create mode 100644 backend/app/conference/enums.py create mode 100644 backend/app/conference/models.py create mode 100644 backend/app/conference/repository.py create mode 100644 backend/app/conference/schemas.py create mode 100644 backend/app/conference/service.py create mode 100644 backend/app/conference/views.py create mode 100644 backend/app/tests/conference/__init__.py create mode 100644 backend/app/tests/conference/test_service.py diff --git a/backend/app/access/repository.py b/backend/app/access/repository.py index d37ee65..a077159 100644 --- a/backend/app/access/repository.py +++ b/backend/app/access/repository.py @@ -1,6 +1,6 @@ from uuid import UUID -from sqlalchemy import text +from sqlalchemy import bindparam, text from sqlalchemy.ext.asyncio import AsyncSession from .models import CommitteeAssignment @@ -69,3 +69,72 @@ async def get_session_assignment( role=row["role"], representation_id=row["representation_id"], ) + + +async def has_conference_management_role( + session: AsyncSession, + *, + conference_id: int, + user_id: UUID, + roles: set[str], +) -> bool: + query = text(""" + SELECT 1 + FROM public.conferences c + LEFT JOIN public.conference_assignments ca + ON ca.conference_id = c.id + AND ca.user_id = :user_id + AND ca.role IN :roles + WHERE c.id = :conference_id + AND ( + c.owner_id = :user_id + OR ca.user_id IS NOT NULL + ) + LIMIT 1 + """).bindparams(bindparam("roles", expanding=True)) + + result = await session.execute( + query, + { + "conference_id": conference_id, + "user_id": user_id, + "roles": list(roles), + }, + ) + return result.scalar_one_or_none() is not None + + +async def has_conference_assignment_for_session_access( + session: AsyncSession, + *, + conference_id: int, + committee_id: int, + user_id: UUID, + roles: set[str], +) -> bool: + query = text(""" + SELECT 1 + FROM public.committees cm + JOIN public.conference_assignments ca + ON ca.conference_id = cm.conference_id + AND ca.user_id = :user_id + AND ca.role IN :roles + AND ( + ca.committee_id IS NULL + OR ca.committee_id = cm.id + ) + WHERE cm.id = :committee_id + AND cm.conference_id = :conference_id + LIMIT 1 + """).bindparams(bindparam("roles", expanding=True)) + + result = await session.execute( + query, + { + "conference_id": conference_id, + "committee_id": committee_id, + "user_id": user_id, + "roles": list(roles), + }, + ) + return result.scalar_one_or_none() is not None diff --git a/backend/app/access/service.py b/backend/app/access/service.py index 91c28f6..5fd5197 100644 --- a/backend/app/access/service.py +++ b/backend/app/access/service.py @@ -6,7 +6,24 @@ from app.access.models import CommitteeAssignment from app.core.exceptions import AccessDeniedError -from .repository import get_committee_assignment, get_session_assignment +from .repository import ( + get_committee_assignment, + get_session_assignment, + has_conference_assignment_for_session_access, + has_conference_management_role, +) + +CONFERENCE_MANAGEMENT_ROLES = { + "owner", + "secretary_general", +} + +SESSION_ACCESS_GRANTING_CONFERENCE_ROLES = { + "owner", + "secretary_general", + "director", + "moderator", +} async def resolve_committee_assignment( @@ -62,3 +79,39 @@ async def verify_user_role( ) return assignment + + +async def verify_can_manage_conference( + session: AsyncSession, + user_id: UUID, + conference_id: int, +) -> None: + # TODO: split conference/dashboard access from live-session access as this grows. + can_manage = await has_conference_management_role( + session=session, + conference_id=conference_id, + user_id=user_id, + roles=CONFERENCE_MANAGEMENT_ROLES, + ) + if not can_manage: + raise AccessDeniedError("User cannot manage this conference") + + +async def verify_conference_assignment_can_grant_session_access( + session: AsyncSession, + user_id: UUID, + conference_id: int, + committee_id: int, +) -> None: + # TODO: keep role policy centralized here as conference/team access grows. + can_grant = await has_conference_assignment_for_session_access( + session=session, + conference_id=conference_id, + committee_id=committee_id, + user_id=user_id, + roles=SESSION_ACCESS_GRANTING_CONFERENCE_ROLES, + ) + if not can_grant: + raise AccessDeniedError( + "Conference assignment cannot grant committee session access" + ) diff --git a/backend/app/conference/__init__.py b/backend/app/conference/__init__.py new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/backend/app/conference/__init__.py @@ -0,0 +1 @@ + diff --git a/backend/app/conference/enums.py b/backend/app/conference/enums.py new file mode 100644 index 0000000..b526e60 --- /dev/null +++ b/backend/app/conference/enums.py @@ -0,0 +1,19 @@ +from enum import StrEnum + + +class ConferenceRole(StrEnum): + OWNER = "owner" + SECRETARY_GENERAL = "secretary_general" + DIRECTOR = "director" + MODERATOR = "moderator" + RAPPORTEUR = "rapporteur" + CRISIS_STAFF = "crisis_staff" + PRESS = "press" + LOGISTICS = "logistics" + STAFF = "staff" + + +class CommitteeRole(StrEnum): + CHAIR = "chair" + DELEGATE = "delegate" + OBSERVER = "observer" diff --git a/backend/app/conference/models.py b/backend/app/conference/models.py new file mode 100644 index 0000000..b5851de --- /dev/null +++ b/backend/app/conference/models.py @@ -0,0 +1,36 @@ +from dataclasses import dataclass +from datetime import datetime +from uuid import UUID + + +@dataclass(frozen=True) +class Conference: + id: int + name: str + status: str + owner_id: UUID | None + location: str | None + logo_url: str | None + theme_color: str | None + start_date: datetime | None + end_date: datetime | None + created_at: datetime + updated_at: datetime + + +@dataclass(frozen=True) +class Committee: + id: int + conference_id: int + name: str + status: str + created_at: datetime + updated_at: datetime + + +@dataclass(frozen=True) +class CommitteeAssignment: + user_id: UUID + committee_id: int + role: str + representation_id: int | None diff --git a/backend/app/conference/repository.py b/backend/app/conference/repository.py new file mode 100644 index 0000000..20b0478 --- /dev/null +++ b/backend/app/conference/repository.py @@ -0,0 +1,269 @@ +from uuid import UUID + +from sqlalchemy import text +from sqlalchemy.ext.asyncio import AsyncSession + +from .models import Committee, CommitteeAssignment, Conference +from .schemas import CommitteeCreate, ConferenceCreate + + +def _conference_from_row(row) -> Conference: + return Conference( + id=row["id"], + name=row["name"], + status=row["status"], + owner_id=row["owner_id"], + location=row["location"], + logo_url=row["logo_url"], + theme_color=row["theme_color"], + start_date=row["start_date"], + end_date=row["end_date"], + created_at=row["created_at"], + updated_at=row["updated_at"], + ) + + +def _committee_from_row(row) -> Committee: + return Committee( + id=row["id"], + conference_id=row["conference_id"], + name=row["name"], + status=row["status"], + created_at=row["created_at"], + updated_at=row["updated_at"], + ) + + +def _committee_assignment_from_row(row) -> CommitteeAssignment: + return CommitteeAssignment( + user_id=row["user_id"], + committee_id=row["committee_id"], + role=row["role"], + representation_id=row["representation_id"], + ) + + +async def create_conference( + session: AsyncSession, + *, + data: ConferenceCreate, + owner_id: UUID, +) -> Conference | None: + query = text(""" + INSERT INTO public.conferences + (name, owner_id, location, logo_url, theme_color, start_date, end_date) + VALUES + (:name, :owner_id, :location, :logo_url, :theme_color, :start_date, :end_date) + RETURNING + id, name, status, owner_id, location, logo_url, theme_color, + start_date, end_date, created_at, updated_at + """) + + result = await session.execute( + query, + { + "name": data.name, + "owner_id": owner_id, + "location": data.location, + "logo_url": data.logo_url, + "theme_color": data.theme_color, + "start_date": data.start_date, + "end_date": data.end_date, + }, + ) + row = result.mappings().one_or_none() + return _conference_from_row(row) if row is not None else None + + +async def create_conference_assignment( + session: AsyncSession, + *, + conference_id: int, + user_id: UUID, + role: str, + committee_id: int | None = None, +) -> None: + query = text(""" + INSERT INTO public.conference_assignments + (conference_id, user_id, role, committee_id) + VALUES + (:conference_id, :user_id, :role, :committee_id) + ON CONFLICT DO NOTHING + """) + + await session.execute( + query, + { + "conference_id": conference_id, + "user_id": user_id, + "role": role, + "committee_id": committee_id, + }, + ) + + +async def list_user_conferences( + session: AsyncSession, + *, + user_id: UUID, +) -> list[Conference]: + query = text(""" + SELECT DISTINCT + c.id, c.name, c.status, c.owner_id, c.location, c.logo_url, + c.theme_color, c.start_date, c.end_date, c.created_at, c.updated_at + FROM public.conferences c + LEFT JOIN public.conference_assignments ca + ON ca.conference_id = c.id + AND ca.user_id = :user_id + WHERE c.owner_id = :user_id + OR ca.user_id IS NOT NULL + ORDER BY c.created_at DESC, c.id DESC + """) + + result = await session.execute(query, {"user_id": user_id}) + return [_conference_from_row(row) for row in result.mappings().all()] + + +async def get_user_conference( + session: AsyncSession, + *, + conference_id: int, + user_id: UUID, +) -> Conference | None: + query = text(""" + SELECT + c.id, c.name, c.status, c.owner_id, c.location, c.logo_url, + c.theme_color, c.start_date, c.end_date, c.created_at, c.updated_at + FROM public.conferences c + LEFT JOIN public.conference_assignments ca + ON ca.conference_id = c.id + AND ca.user_id = :user_id + WHERE c.id = :conference_id + AND ( + c.owner_id = :user_id + OR ca.user_id IS NOT NULL + ) + """) + + result = await session.execute( + query, {"conference_id": conference_id, "user_id": user_id} + ) + row = result.mappings().one_or_none() + return _conference_from_row(row) if row is not None else None + + +async def create_committee( + session: AsyncSession, + *, + conference_id: int, + data: CommitteeCreate, +) -> Committee | None: + query = text(""" + INSERT INTO public.committees + (conference_id, name) + VALUES + (:conference_id, :name) + RETURNING id, conference_id, name, status, created_at, updated_at + """) + + result = await session.execute( + query, {"conference_id": conference_id, "name": data.name} + ) + row = result.mappings().one_or_none() + return _committee_from_row(row) if row is not None else None + + +async def list_conference_committees( + session: AsyncSession, + *, + conference_id: int, +) -> list[Committee]: + query = text(""" + SELECT id, conference_id, name, status, created_at, updated_at + FROM public.committees + WHERE conference_id = :conference_id + ORDER BY created_at DESC, id DESC + """) + + result = await session.execute(query, {"conference_id": conference_id}) + return [_committee_from_row(row) for row in result.mappings().all()] + + +async def get_user_committee( + session: AsyncSession, + *, + committee_id: int, + user_id: UUID, +) -> Committee | None: + query = text(""" + SELECT cm.id, cm.conference_id, cm.name, cm.status, cm.created_at, cm.updated_at + FROM public.committees cm + JOIN public.conferences c + ON c.id = cm.conference_id + LEFT JOIN public.conference_assignments ca + ON ca.conference_id = c.id + AND ca.user_id = :user_id + WHERE cm.id = :committee_id + AND ( + c.owner_id = :user_id + OR ca.user_id IS NOT NULL + ) + """) + + result = await session.execute( + query, {"committee_id": committee_id, "user_id": user_id} + ) + row = result.mappings().one_or_none() + return _committee_from_row(row) if row is not None else None + + +async def get_committee_assignment( + session: AsyncSession, + *, + committee_id: int, + user_id: UUID, +) -> CommitteeAssignment | None: + query = text(""" + SELECT user_id, committee_id, role, representation_id + FROM public.committee_assignments + WHERE committee_id = :committee_id + AND user_id = :user_id + """) + + result = await session.execute( + query, {"committee_id": committee_id, "user_id": user_id} + ) + row = result.mappings().one_or_none() + return _committee_assignment_from_row(row) if row is not None else None + + +async def upsert_committee_session_assignment( + session: AsyncSession, + *, + committee_id: int, + user_id: UUID, + role: str, +) -> CommitteeAssignment | None: + query = text(""" + INSERT INTO public.committee_assignments + (user_id, committee_id, role, representation_id) + VALUES + (:user_id, :committee_id, :role, null) + ON CONFLICT (user_id, committee_id) + DO UPDATE SET + role = EXCLUDED.role, + representation_id = null + WHERE public.committee_assignments.role <> 'delegate' + RETURNING user_id, committee_id, role, representation_id + """) + + result = await session.execute( + query, + { + "committee_id": committee_id, + "user_id": user_id, + "role": role, + }, + ) + row = result.mappings().one_or_none() + return _committee_assignment_from_row(row) if row is not None else None diff --git a/backend/app/conference/schemas.py b/backend/app/conference/schemas.py new file mode 100644 index 0000000..73e41b1 --- /dev/null +++ b/backend/app/conference/schemas.py @@ -0,0 +1,47 @@ +from datetime import datetime +from uuid import UUID + +from pydantic import BaseModel, Field + + +class ConferenceCreate(BaseModel): + name: str = Field(min_length=1, max_length=255) + location: str | None = Field(default=None, max_length=255) + logo_url: str | None = Field(default=None, max_length=1000) + theme_color: str | None = Field(default=None, pattern=r"^#[0-9A-Fa-f]{6}$") + start_date: datetime | None = None + end_date: datetime | None = None + + +class ConferenceRead(BaseModel): + id: int + name: str + status: str + owner_id: UUID | None + location: str | None + logo_url: str | None + theme_color: str | None + start_date: datetime | None + end_date: datetime | None + created_at: datetime + updated_at: datetime + + +class CommitteeCreate(BaseModel): + name: str = Field(min_length=1, max_length=64) + + +class CommitteeRead(BaseModel): + id: int + conference_id: int + name: str + status: str + created_at: datetime + updated_at: datetime + + +class CommitteeAssignmentRead(BaseModel): + user_id: UUID + committee_id: int + role: str + representation_id: int | None diff --git a/backend/app/conference/service.py b/backend/app/conference/service.py new file mode 100644 index 0000000..496f020 --- /dev/null +++ b/backend/app/conference/service.py @@ -0,0 +1,151 @@ +from typing import Literal +from uuid import UUID + +from sqlalchemy.ext.asyncio import AsyncSession + +import app.access.service as access +from app.core.exceptions import BadRequest, ConflictError, NotFoundError + +from . import repository +from .enums import CommitteeRole, ConferenceRole +from .models import Committee, CommitteeAssignment, Conference +from .schemas import CommitteeCreate, ConferenceCreate + + +async def create_conference( + session: AsyncSession, + *, + data: ConferenceCreate, + owner_id: UUID, +) -> Conference: + if data.start_date is not None and data.end_date is not None: + if data.start_date > data.end_date: + raise BadRequest("Conference start_date must be before end_date") + + conference = await repository.create_conference( + session=session, data=data, owner_id=owner_id + ) + if conference is None: + raise BadRequest("Could not create conference") + + await repository.create_conference_assignment( + session=session, + conference_id=conference.id, + user_id=owner_id, + role=ConferenceRole.OWNER, + ) + await session.commit() + + return conference + + +async def list_conferences( + session: AsyncSession, + *, + user_id: UUID, +) -> list[Conference]: + return await repository.list_user_conferences(session=session, user_id=user_id) + + +async def get_conference( + session: AsyncSession, + *, + conference_id: int, + user_id: UUID, +) -> Conference: + conference = await repository.get_user_conference( + session=session, conference_id=conference_id, user_id=user_id + ) + if conference is None: + raise NotFoundError("Conference not found") + return conference + + +async def create_committee( + session: AsyncSession, + *, + conference_id: int, + user_id: UUID, + data: CommitteeCreate, +) -> Committee: + await access.verify_can_manage_conference( + session=session, + conference_id=conference_id, + user_id=user_id, + ) + + committee = await repository.create_committee( + session=session, conference_id=conference_id, data=data + ) + if committee is None: + raise BadRequest("Could not create committee") + + await session.commit() + return committee + + +async def list_committees( + session: AsyncSession, + *, + conference_id: int, + user_id: UUID, +) -> list[Committee]: + await get_conference(session=session, conference_id=conference_id, user_id=user_id) + return await repository.list_conference_committees( + session=session, conference_id=conference_id + ) + + +async def get_committee( + session: AsyncSession, + *, + committee_id: int, + user_id: UUID, +) -> Committee: + committee = await repository.get_user_committee( + session=session, committee_id=committee_id, user_id=user_id + ) + if committee is None: + raise NotFoundError("Committee not found") + return committee + + +async def promote_conference_assignment_to_committee_assignment( + session: AsyncSession, + *, + conference_id: int, + committee_id: int, + user_id: UUID, + committee_role: Literal[ + CommitteeRole.CHAIR, CommitteeRole.OBSERVER + ] = CommitteeRole.CHAIR, +) -> CommitteeAssignment: + # Conference assignments are team/dashboard roles. + # Committee assignments are the live-session access projection. + if committee_role not in {CommitteeRole.CHAIR, CommitteeRole.OBSERVER}: + raise BadRequest("Only chair or observer session access can be promoted") + + await access.verify_conference_assignment_can_grant_session_access( + session=session, + conference_id=conference_id, + committee_id=committee_id, + user_id=user_id, + ) + + existing = await repository.get_committee_assignment( + session=session, committee_id=committee_id, user_id=user_id + ) + if existing is not None and existing.role == CommitteeRole.DELEGATE: + raise ConflictError("Cannot replace a delegate committee assignment") + + assignment = await repository.upsert_committee_session_assignment( + session=session, + committee_id=committee_id, + user_id=user_id, + role=committee_role, + ) + if assignment is None: + raise ConflictError("Could not promote committee session access") + + await session.commit() + return assignment diff --git a/backend/app/conference/views.py b/backend/app/conference/views.py new file mode 100644 index 0000000..a161184 --- /dev/null +++ b/backend/app/conference/views.py @@ -0,0 +1,108 @@ +from typing import Annotated + +from fastapi import APIRouter, Depends, status +from sqlalchemy.ext.asyncio import AsyncSession + +from app.auth.dep import get_current_user +from app.auth.service import AuthUser +from app.core.database import get_db_session + +from . import service +from .schemas import ( + CommitteeCreate, + CommitteeRead, + ConferenceCreate, + ConferenceRead, +) + +router = APIRouter() + + +@router.post( + "/conferences", + status_code=status.HTTP_201_CREATED, +) +async def create_conference_endpoint( + payload: ConferenceCreate, + session: Annotated[AsyncSession, Depends(get_db_session)], + current_user: Annotated[AuthUser, Depends(get_current_user)], +) -> ConferenceRead: + conference = await service.create_conference( + session=session, + data=payload, + owner_id=current_user.user_id, + ) + return ConferenceRead(**conference.__dict__) + + +@router.get("/conferences") +async def list_conferences_endpoint( + session: Annotated[AsyncSession, Depends(get_db_session)], + current_user: Annotated[AuthUser, Depends(get_current_user)], +) -> list[ConferenceRead]: + conferences = await service.list_conferences( + session=session, + user_id=current_user.user_id, + ) + return [ConferenceRead(**conference.__dict__) for conference in conferences] + + +@router.get("/conferences/{conference_id}") +async def get_conference_endpoint( + conference_id: int, + session: Annotated[AsyncSession, Depends(get_db_session)], + current_user: Annotated[AuthUser, Depends(get_current_user)], +) -> ConferenceRead: + conference = await service.get_conference( + session=session, + conference_id=conference_id, + user_id=current_user.user_id, + ) + return ConferenceRead(**conference.__dict__) + + +@router.post( + "/conferences/{conference_id}/committees", + status_code=status.HTTP_201_CREATED, +) +async def create_committee_endpoint( + conference_id: int, + payload: CommitteeCreate, + session: Annotated[AsyncSession, Depends(get_db_session)], + current_user: Annotated[AuthUser, Depends(get_current_user)], +) -> CommitteeRead: + committee = await service.create_committee( + session=session, + conference_id=conference_id, + user_id=current_user.user_id, + data=payload, + ) + return CommitteeRead(**committee.__dict__) + + +@router.get("/conferences/{conference_id}/committees") +async def list_committees_endpoint( + conference_id: int, + session: Annotated[AsyncSession, Depends(get_db_session)], + current_user: Annotated[AuthUser, Depends(get_current_user)], +) -> list[CommitteeRead]: + committees = await service.list_committees( + session=session, + conference_id=conference_id, + user_id=current_user.user_id, + ) + return [CommitteeRead(**committee.__dict__) for committee in committees] + + +@router.get("/committees/{committee_id}") +async def get_committee_endpoint( + committee_id: int, + session: Annotated[AsyncSession, Depends(get_db_session)], + current_user: Annotated[AuthUser, Depends(get_current_user)], +) -> CommitteeRead: + committee = await service.get_committee( + session=session, + committee_id=committee_id, + user_id=current_user.user_id, + ) + return CommitteeRead(**committee.__dict__) diff --git a/backend/app/main.py b/backend/app/main.py index 36c2daf..72c99ca 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -7,6 +7,7 @@ from fastapi.responses import JSONResponse from app.access.views import router as access_router +from app.conference.views import router as conference_router from app.core.config import get_settings from app.core.database import create_db from app.core.exceptions import AppException @@ -65,6 +66,7 @@ async def app_exception_handler(request: Request, exc: AppException): # include commitees here? app.include_router(session_router, prefix="/committees", tags=["committees"]) app.include_router(access_router, prefix="/access", tags=["access"]) +app.include_router(conference_router, tags=["conferences"]) def custom_openapi(): diff --git a/backend/app/tests/access/test_service.py b/backend/app/tests/access/test_service.py index a7a342a..a875e27 100644 --- a/backend/app/tests/access/test_service.py +++ b/backend/app/tests/access/test_service.py @@ -3,7 +3,12 @@ import pytest from app.access.models import CommitteeAssignment -from app.access.service import resolve_committee_assignment, verify_user_role +from app.access.service import ( + resolve_committee_assignment, + verify_can_manage_conference, + verify_conference_assignment_can_grant_session_access, + verify_user_role, +) from app.core.exceptions import AccessDeniedError @@ -92,3 +97,61 @@ async def chair_assignment(*_args, **_kwargs): assert ( await verify_user_role(object(), assignment.user_id, 1, "chair") is assignment ) + + +@pytest.mark.anyio +async def test_conference_management_check_denies_unprivileged_user(monkeypatch): + async def cannot_manage(*_args, **_kwargs): + return False + + monkeypatch.setattr( + "app.access.service.has_conference_management_role", cannot_manage + ) + + with pytest.raises(AccessDeniedError, match="cannot manage"): + await verify_can_manage_conference(object(), uuid4(), 1) + + +@pytest.mark.anyio +async def test_conference_management_check_allows_privileged_user(monkeypatch): + async def can_manage(*_args, **_kwargs): + return True + + monkeypatch.setattr("app.access.service.has_conference_management_role", can_manage) + + await verify_can_manage_conference(object(), uuid4(), 1) + + +@pytest.mark.anyio +async def test_session_access_projection_check_denies_unprivileged_assignment( + monkeypatch, +): + async def cannot_grant(*_args, **_kwargs): + return False + + monkeypatch.setattr( + "app.access.service.has_conference_assignment_for_session_access", + cannot_grant, + ) + + with pytest.raises(AccessDeniedError, match="cannot grant"): + await verify_conference_assignment_can_grant_session_access( + object(), uuid4(), 1, 10 + ) + + +@pytest.mark.anyio +async def test_session_access_projection_check_allows_privileged_assignment( + monkeypatch, +): + async def can_grant(*_args, **_kwargs): + return True + + monkeypatch.setattr( + "app.access.service.has_conference_assignment_for_session_access", + can_grant, + ) + + await verify_conference_assignment_can_grant_session_access( + object(), uuid4(), 1, 10 + ) diff --git a/backend/app/tests/conference/__init__.py b/backend/app/tests/conference/__init__.py new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/backend/app/tests/conference/__init__.py @@ -0,0 +1 @@ + diff --git a/backend/app/tests/conference/test_service.py b/backend/app/tests/conference/test_service.py new file mode 100644 index 0000000..b94d6f1 --- /dev/null +++ b/backend/app/tests/conference/test_service.py @@ -0,0 +1,214 @@ +from datetime import datetime +from uuid import uuid4 + +import pytest + +from app.conference.models import Committee, CommitteeAssignment, Conference +from app.conference.schemas import CommitteeCreate, ConferenceCreate +from app.conference.service import ( + create_committee, + create_conference, + promote_conference_assignment_to_committee_assignment, +) +from app.core.exceptions import AccessDeniedError, ConflictError + + +class FakeSession: + def __init__(self) -> None: + self.commits = 0 + + async def commit(self) -> None: + self.commits += 1 + + +def conference(owner_id): + now = datetime.now() + return Conference( + id=1, + name="I WebMUN", + status="planned", + owner_id=owner_id, + location=None, + logo_url=None, + theme_color=None, + start_date=None, + end_date=None, + created_at=now, + updated_at=now, + ) + + +def committee(): + now = datetime.now() + return Committee( + id=10, + conference_id=1, + name="CSNU", + status="planned", + created_at=now, + updated_at=now, + ) + + +@pytest.mark.anyio +async def test_create_conference_adds_owner_assignment(monkeypatch): + owner_id = uuid4() + fake_session = FakeSession() + created_assignments = [] + + async def repo_create_conference(*_args, **_kwargs): + return conference(owner_id) + + async def repo_create_assignment(*_args, **kwargs): + created_assignments.append( + { + "conference_id": kwargs["conference_id"], + "user_id": kwargs["user_id"], + "role": kwargs["role"], + } + ) + + monkeypatch.setattr( + "app.conference.service.repository.create_conference", repo_create_conference + ) + monkeypatch.setattr( + "app.conference.service.repository.create_conference_assignment", + repo_create_assignment, + ) + + result = await create_conference( + fake_session, + data=ConferenceCreate(name="I WebMUN"), + owner_id=owner_id, + ) + + assert result.id == 1 + assert created_assignments == [ + { + "conference_id": 1, + "user_id": owner_id, + "role": "owner", + } + ] + assert fake_session.commits == 1 + + +@pytest.mark.anyio +async def test_create_committee_requires_conference_management_role(monkeypatch): + async def cannot_manage(*_args, **_kwargs): + raise AccessDeniedError("User cannot manage this conference") + + monkeypatch.setattr( + "app.conference.service.access.verify_can_manage_conference", cannot_manage + ) + + with pytest.raises(AccessDeniedError, match="cannot manage"): + await create_committee( + FakeSession(), + conference_id=1, + user_id=uuid4(), + data=CommitteeCreate(name="CSNU"), + ) + + +@pytest.mark.anyio +async def test_create_committee_commits_when_user_can_manage(monkeypatch): + fake_session = FakeSession() + + async def can_manage(*_args, **_kwargs): + return None + + async def repo_create_committee(*_args, **_kwargs): + return committee() + + monkeypatch.setattr( + "app.conference.service.access.verify_can_manage_conference", can_manage + ) + monkeypatch.setattr( + "app.conference.service.repository.create_committee", repo_create_committee + ) + + result = await create_committee( + fake_session, + conference_id=1, + user_id=uuid4(), + data=CommitteeCreate(name="CSNU"), + ) + + assert result.id == 10 + assert fake_session.commits == 1 + + +@pytest.mark.anyio +async def test_promotion_refuses_to_replace_delegate_assignment(monkeypatch): + async def can_grant(*_args, **_kwargs): + return None + + async def existing_delegate(*_args, **_kwargs): + return CommitteeAssignment( + user_id=uuid4(), + committee_id=10, + role="delegate", + representation_id=3, + ) + + monkeypatch.setattr( + "app.conference.service.access.verify_conference_assignment_can_grant_session_access", + can_grant, + ) + monkeypatch.setattr( + "app.conference.service.repository.get_committee_assignment", existing_delegate + ) + + with pytest.raises(ConflictError, match="delegate"): + await promote_conference_assignment_to_committee_assignment( + FakeSession(), + conference_id=1, + committee_id=10, + user_id=uuid4(), + ) + + +@pytest.mark.anyio +async def test_promotion_creates_committee_session_access(monkeypatch): + fake_session = FakeSession() + user_id = uuid4() + + async def can_grant(*_args, **_kwargs): + return None + + async def no_existing_assignment(*_args, **_kwargs): + return None + + async def upsert_assignment(*_args, **kwargs): + return CommitteeAssignment( + user_id=kwargs["user_id"], + committee_id=kwargs["committee_id"], + role=kwargs["role"], + representation_id=None, + ) + + monkeypatch.setattr( + "app.conference.service.access.verify_conference_assignment_can_grant_session_access", + can_grant, + ) + monkeypatch.setattr( + "app.conference.service.repository.get_committee_assignment", + no_existing_assignment, + ) + monkeypatch.setattr( + "app.conference.service.repository.upsert_committee_session_assignment", + upsert_assignment, + ) + + result = await promote_conference_assignment_to_committee_assignment( + fake_session, + conference_id=1, + committee_id=10, + user_id=user_id, + ) + + assert result.user_id == user_id + assert result.role == "chair" + assert result.representation_id is None + assert fake_session.commits == 1 From 570bcd869e05a282f464d1127ebb7cc8fd15cc6b Mon Sep 17 00:00:00 2001 From: wate <110754234+r0liveir@users.noreply.github.com> Date: Wed, 2 Sep 2026 21:31:13 -0300 Subject: [PATCH 03/19] feat(backend): expose conference access summary Co-authored-by: Codex --- backend/app/access/schemas.py | 12 ++++ backend/app/access/service.py | 51 ++++++++++++++ backend/app/access/views.py | 16 ++++- backend/app/conference/models.py | 8 +++ backend/app/conference/repository.py | 31 ++++++++- backend/app/tests/access/test_service.py | 72 ++++++++++++++++++++ backend/app/tests/conference/test_service.py | 6 +- 7 files changed, 192 insertions(+), 4 deletions(-) diff --git a/backend/app/access/schemas.py b/backend/app/access/schemas.py index 864dfb0..e4ace4e 100644 --- a/backend/app/access/schemas.py +++ b/backend/app/access/schemas.py @@ -6,3 +6,15 @@ class SessionRepresentation(BaseModel): role: enums.SessionRoles representation_id: int | None + + +class CommitteeScopedConferenceRole(BaseModel): + committee_id: int + role: str + + +class ConferenceAccess(BaseModel): + conference_id: int + roles: list[str] + committee_roles: list[CommitteeScopedConferenceRole] + can_manage_conference: bool diff --git a/backend/app/access/service.py b/backend/app/access/service.py index 5fd5197..b77a02c 100644 --- a/backend/app/access/service.py +++ b/backend/app/access/service.py @@ -4,6 +4,9 @@ from sqlalchemy.ext.asyncio import AsyncSession from app.access.models import CommitteeAssignment +from app.access.schemas import CommitteeScopedConferenceRole, ConferenceAccess +from app.conference import repository as conference_repository +from app.conference.enums import ConferenceRole from app.core.exceptions import AccessDeniedError from .repository import ( @@ -97,6 +100,54 @@ async def verify_can_manage_conference( raise AccessDeniedError("User cannot manage this conference") +async def get_my_conference_access( + session: AsyncSession, + user_id: UUID, + conference_id: int, +) -> ConferenceAccess: + conference = await conference_repository.get_user_conference( + session=session, + conference_id=conference_id, + user_id=user_id, + ) + if conference is None: + raise AccessDeniedError("User has no access to this conference") + + assignments = await conference_repository.list_user_conference_assignments( + session=session, + conference_id=conference_id, + user_id=user_id, + ) + + roles = sorted( + { + assignment.role + for assignment in assignments + if assignment.committee_id is None + } + ) + if conference.owner_id == user_id and ConferenceRole.OWNER.value not in roles: + roles.append(ConferenceRole.OWNER.value) + + committee_roles = [ + CommitteeScopedConferenceRole( + committee_id=assignment.committee_id, + role=assignment.role, + ) + for assignment in assignments + if assignment.committee_id is not None + ] + + return ConferenceAccess( + conference_id=conference_id, + roles=roles, + committee_roles=committee_roles, + can_manage_conference=any( + role in CONFERENCE_MANAGEMENT_ROLES for role in roles + ), + ) + + async def verify_conference_assignment_can_grant_session_access( session: AsyncSession, user_id: UUID, diff --git a/backend/app/access/views.py b/backend/app/access/views.py index 702e5fe..48a1c99 100644 --- a/backend/app/access/views.py +++ b/backend/app/access/views.py @@ -7,8 +7,8 @@ from app.auth.service import AuthUser from app.core.database import get_db_session -from .schemas import SessionRepresentation -from .service import resolve_session_assignment +from .schemas import ConferenceAccess, SessionRepresentation +from .service import get_my_conference_access, resolve_session_assignment router = APIRouter() @@ -27,3 +27,15 @@ async def get_my_session_access( return SessionRepresentation( role=assignment.role, representation_id=assignment.representation_id ) + + +@router.get("/conferences/{conference_id}/me") +async def get_my_conference_access_endpoint( + conference_id: int, + db_session: Annotated[AsyncSession, Depends(get_db_session)], + current_user: Annotated[AuthUser, Depends(get_current_user)], +) -> ConferenceAccess: + """Return the authenticated user's dashboard/team access for a conference.""" + return await get_my_conference_access( + db_session, current_user.user_id, conference_id + ) diff --git a/backend/app/conference/models.py b/backend/app/conference/models.py index b5851de..14b8f01 100644 --- a/backend/app/conference/models.py +++ b/backend/app/conference/models.py @@ -34,3 +34,11 @@ class CommitteeAssignment: committee_id: int role: str representation_id: int | None + + +@dataclass(frozen=True) +class ConferenceAssignment: + conference_id: int + user_id: UUID + role: str + committee_id: int | None diff --git a/backend/app/conference/repository.py b/backend/app/conference/repository.py index 20b0478..c0cce38 100644 --- a/backend/app/conference/repository.py +++ b/backend/app/conference/repository.py @@ -3,7 +3,7 @@ from sqlalchemy import text from sqlalchemy.ext.asyncio import AsyncSession -from .models import Committee, CommitteeAssignment, Conference +from .models import Committee, CommitteeAssignment, Conference, ConferenceAssignment from .schemas import CommitteeCreate, ConferenceCreate @@ -43,6 +43,15 @@ def _committee_assignment_from_row(row) -> CommitteeAssignment: ) +def _conference_assignment_from_row(row) -> ConferenceAssignment: + return ConferenceAssignment( + conference_id=row["conference_id"], + user_id=row["user_id"], + role=row["role"], + committee_id=row["committee_id"], + ) + + async def create_conference( session: AsyncSession, *, @@ -152,6 +161,26 @@ async def get_user_conference( return _conference_from_row(row) if row is not None else None +async def list_user_conference_assignments( + session: AsyncSession, + *, + conference_id: int, + user_id: UUID, +) -> list[ConferenceAssignment]: + query = text(""" + SELECT conference_id, user_id, role, committee_id + FROM public.conference_assignments + WHERE conference_id = :conference_id + AND user_id = :user_id + ORDER BY committee_id NULLS FIRST, role + """) + + result = await session.execute( + query, {"conference_id": conference_id, "user_id": user_id} + ) + return [_conference_assignment_from_row(row) for row in result.mappings().all()] + + async def create_committee( session: AsyncSession, *, diff --git a/backend/app/tests/access/test_service.py b/backend/app/tests/access/test_service.py index a875e27..fe17a10 100644 --- a/backend/app/tests/access/test_service.py +++ b/backend/app/tests/access/test_service.py @@ -1,9 +1,11 @@ +from dataclasses import dataclass from uuid import uuid4 import pytest from app.access.models import CommitteeAssignment from app.access.service import ( + get_my_conference_access, resolve_committee_assignment, verify_can_manage_conference, verify_conference_assignment_can_grant_session_access, @@ -12,6 +14,18 @@ from app.core.exceptions import AccessDeniedError +@dataclass(frozen=True) +class Conference: + id: int + owner_id: object + + +@dataclass(frozen=True) +class ConferenceAssignment: + role: str + committee_id: int | None + + @pytest.mark.anyio async def test_denies_user_without_assignment(monkeypatch): async def no_assignment(*_args, **_kwargs): @@ -155,3 +169,61 @@ async def can_grant(*_args, **_kwargs): await verify_conference_assignment_can_grant_session_access( object(), uuid4(), 1, 10 ) + + +@pytest.mark.anyio +async def test_get_my_conference_access_includes_owner_fallback(monkeypatch): + owner_id = uuid4() + + async def repo_get_conference(*_args, **_kwargs): + return Conference(id=1, owner_id=owner_id) + + async def no_assignments(*_args, **_kwargs): + return [] + + monkeypatch.setattr( + "app.access.service.conference_repository.get_user_conference", + repo_get_conference, + ) + monkeypatch.setattr( + "app.access.service.conference_repository.list_user_conference_assignments", + no_assignments, + ) + + result = await get_my_conference_access(object(), owner_id, 1) + + assert result.roles == ["owner"] + assert result.committee_roles == [] + assert result.can_manage_conference is True + + +@pytest.mark.anyio +async def test_get_my_conference_access_splits_conference_and_committee_roles( + monkeypatch, +): + user_id = uuid4() + + async def repo_get_conference(*_args, **_kwargs): + return Conference(id=1, owner_id=uuid4()) + + async def assignments(*_args, **_kwargs): + return [ + ConferenceAssignment(role="press", committee_id=None), + ConferenceAssignment(role="moderator", committee_id=10), + ] + + monkeypatch.setattr( + "app.access.service.conference_repository.get_user_conference", + repo_get_conference, + ) + monkeypatch.setattr( + "app.access.service.conference_repository.list_user_conference_assignments", + assignments, + ) + + result = await get_my_conference_access(object(), user_id, 1) + + assert result.roles == ["press"] + assert result.committee_roles[0].committee_id == 10 + assert result.committee_roles[0].role == "moderator" + assert result.can_manage_conference is False diff --git a/backend/app/tests/conference/test_service.py b/backend/app/tests/conference/test_service.py index b94d6f1..f09c4ca 100644 --- a/backend/app/tests/conference/test_service.py +++ b/backend/app/tests/conference/test_service.py @@ -3,7 +3,11 @@ import pytest -from app.conference.models import Committee, CommitteeAssignment, Conference +from app.conference.models import ( + Committee, + CommitteeAssignment, + Conference, +) from app.conference.schemas import CommitteeCreate, ConferenceCreate from app.conference.service import ( create_committee, From bd25e706fbff93bf06bd59ba8db2fd76c769d04d Mon Sep 17 00:00:00 2001 From: wate <110754234+r0liveir@users.noreply.github.com> Date: Wed, 2 Sep 2026 21:44:38 -0300 Subject: [PATCH 04/19] refactor(api): move session routes under sessions Co-authored-by: Codex --- backend/app/main.py | 11 +- backend/app/session/views.py | 9 +- docker-compose.yml | 2 +- docs/backend/http-api.md | 13 +- docs/frontend/api-client.md | 7 +- docs/realtime/overview.md | 2 +- frontend/src/context/SessionContext.tsx | 2 +- frontend/src/pages/CreateCommittee.tsx | 4 +- frontend/src/schemas/types.gen.ts | 388 +++++++++++++++++++++++- 9 files changed, 393 insertions(+), 45 deletions(-) diff --git a/backend/app/main.py b/backend/app/main.py index 72c99ca..30bb7a0 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -1,7 +1,7 @@ from contextlib import asynccontextmanager import redis.asyncio as redis -from fastapi import FastAPI, Request +from fastapi import FastAPI, Request, Response, status from fastapi.middleware.cors import CORSMiddleware from fastapi.openapi.utils import get_openapi from fastapi.responses import JSONResponse @@ -50,6 +50,12 @@ async def app_exception_handler(request: Request, exc: AppException): return JSONResponse(status_code=exc.status_code, content={"detail": exc.message}) +@app.get("/health", status_code=status.HTTP_200_OK) +async def health(): + """Healthcheck route for containers and load balancers.""" + return Response(status_code=status.HTTP_200_OK) + + # CORS config for Vite app.add_middleware( CORSMiddleware, @@ -63,8 +69,7 @@ async def app_exception_handler(request: Request, exc: AppException): else ["*"], ) -# include commitees here? -app.include_router(session_router, prefix="/committees", tags=["committees"]) +app.include_router(session_router, prefix="/sessions", tags=["sessions"]) app.include_router(access_router, prefix="/access", tags=["access"]) app.include_router(conference_router, tags=["conferences"]) diff --git a/backend/app/session/views.py b/backend/app/session/views.py index e63c346..20e9875 100644 --- a/backend/app/session/views.py +++ b/backend/app/session/views.py @@ -7,7 +7,6 @@ from fastapi import ( APIRouter, Depends, - Response, WebSocket, WebSocketDisconnect, status, @@ -51,12 +50,6 @@ router = APIRouter() -@router.get("/health", status_code=status.HTTP_200_OK) -async def health(): - """Healthcheck route""" - return Response(status_code=status.HTTP_200_OK) - - @router.post("/", status_code=status.HTTP_200_OK) async def create_session_endpoint( session_schema: SessionCreationSchema, @@ -103,7 +96,7 @@ async def activate_session_endpoint( ) -@router.websocket("/ws/{session_id}") +@router.websocket("/{session_id}/ws") async def websocket_endpoint( websocket: WebSocket, session_id: int, diff --git a/docker-compose.yml b/docker-compose.yml index f67988c..87e5b16 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -74,7 +74,7 @@ services: condition: service_healthy healthcheck: test: ["CMD", "python3", "-c", "import urllib.request, sys; - res = urllib.request.urlopen('http://localhost:8000/committees/health', timeout=3); + res = urllib.request.urlopen('http://localhost:8000/health', timeout=3); sys.exit(0) if res.getcode() == 200 else sys.exit(1); "] interval: 30s timeout: 5s diff --git a/docs/backend/http-api.md b/docs/backend/http-api.md index c65d46e..861f0a5 100644 --- a/docs/backend/http-api.md +++ b/docs/backend/http-api.md @@ -14,19 +14,16 @@ resources, and `409` for invalid lifecycle transitions. ## Current routes -- `GET /committees/health` — health check. -- `POST /committees/` — creates a planned session from `{ committee_id, name - }`; chair only. Despite its path, it does not create a committee. -- `POST /committees/{session_id}/activate` — activates a planned session; +- `GET /health` — health check. +- `POST /sessions` — creates a planned session from `{ committee_id, name }`; + chair only. +- `POST /sessions/{session_id}/activate` — activates a planned session; chair only. - `GET /access/sessions/{session_id}/me` — returns the caller's role and `representation_id`. -- `WS /committees/ws/{session_id}` — authenticates from its first message and +- `WS /sessions/{session_id}/ws` — authenticates from its first message and exchanges procedure events and `SessionLiveState` snapshots. -The real-time overview currently says `/ws/{session_id}`; that omits the -implemented `/committees` prefix. - ## Target routes ### Identity and conferences diff --git a/docs/frontend/api-client.md b/docs/frontend/api-client.md index 34f7768..0cd1826 100644 --- a/docs/frontend/api-client.md +++ b/docs/frontend/api-client.md @@ -22,8 +22,7 @@ business rules. The target route map is in from API models. The dashboard should use the target conference, committee, assignment, and -session routes in the backend API document rather than page-local data or the -legacy `POST /committees/` session-creation route. +session routes in the backend API document rather than page-local data. ## Live sessions @@ -32,9 +31,7 @@ legacy `POST /committees/` session-creation route. - Replace the Zustand store with every received `SessionLiveState` snapshot. - Send live procedure actions—motions, votes, queues, and roll call—only over the WebSocket, never HTTP. -- The current implementation uses `/committees/ws/{session_id}`. The target is - `/api/v1/sessions/{session_id}/ws`; update the client and real-time docs in - the same change. +- The current implementation uses `/sessions/{session_id}/ws`. `representation_id` comes from server access/state data. It may identify a target when an event requires one, but it is not frontend-authenticated diff --git a/docs/realtime/overview.md b/docs/realtime/overview.md index cb59378..5682e61 100644 --- a/docs/realtime/overview.md +++ b/docs/realtime/overview.md @@ -1,6 +1,6 @@ # Real-time sessions -Active committee sessions use a WebSocket at `/committees/ws/{session_id}`. +Active committee sessions use a WebSocket at `/sessions/{session_id}/ws`. The server is authoritative: clients request actions and render the state it sends back. diff --git a/frontend/src/context/SessionContext.tsx b/frontend/src/context/SessionContext.tsx index c2347a4..6fd3eab 100644 --- a/frontend/src/context/SessionContext.tsx +++ b/frontend/src/context/SessionContext.tsx @@ -40,7 +40,7 @@ export function SessionProvider({ children }: { children: ReactNode }) { } const ws = new WebSocket( - `${import.meta.env.VITE_WS_URL}/ws/${parsedSessionId}`, + `${import.meta.env.VITE_WS_URL}/${parsedSessionId}/ws`, ); socket = ws diff --git a/frontend/src/pages/CreateCommittee.tsx b/frontend/src/pages/CreateCommittee.tsx index ec46086..dcf3b78 100644 --- a/frontend/src/pages/CreateCommittee.tsx +++ b/frontend/src/pages/CreateCommittee.tsx @@ -35,7 +35,7 @@ export default function SessionPage() { ) -} \ No newline at end of file +} diff --git a/frontend/src/schemas/types.gen.ts b/frontend/src/schemas/types.gen.ts index 329d2af..e38af2c 100644 --- a/frontend/src/schemas/types.gen.ts +++ b/frontend/src/schemas/types.gen.ts @@ -1,7 +1,163 @@ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { - baseUrl: 'http://backend:8000' | (string & {}); + baseUrl: `${string}://${string}` | (string & {}); +}; + +/** + * CommitteeCreate + */ +export type CommitteeCreate = { + /** + * Name + */ + name: string; +}; + +/** + * CommitteeRead + */ +export type CommitteeRead = { + /** + * Id + */ + id: number; + /** + * Conference Id + */ + conference_id: number; + /** + * Name + */ + name: string; + /** + * Status + */ + status: string; + /** + * Created At + */ + created_at: string; + /** + * Updated At + */ + updated_at: string; +}; + +/** + * CommitteeScopedConferenceRole + */ +export type CommitteeScopedConferenceRole = { + /** + * Committee Id + */ + committee_id: number; + /** + * Role + */ + role: string; +}; + +/** + * ConferenceAccess + */ +export type ConferenceAccess = { + /** + * Conference Id + */ + conference_id: number; + /** + * Roles + */ + roles: Array; + /** + * Committee Roles + */ + committee_roles: Array; + /** + * Can Manage Conference + */ + can_manage_conference: boolean; +}; + +/** + * ConferenceCreate + */ +export type ConferenceCreate = { + /** + * Name + */ + name: string; + /** + * Location + */ + location?: string | null; + /** + * Logo Url + */ + logo_url?: string | null; + /** + * Theme Color + */ + theme_color?: string | null; + /** + * Start Date + */ + start_date?: string | null; + /** + * End Date + */ + end_date?: string | null; +}; + +/** + * ConferenceRead + */ +export type ConferenceRead = { + /** + * Id + */ + id: number; + /** + * Name + */ + name: string; + /** + * Status + */ + status: string; + /** + * Owner Id + */ + owner_id: string | null; + /** + * Location + */ + location: string | null; + /** + * Logo Url + */ + logo_url: string | null; + /** + * Theme Color + */ + theme_color: string | null; + /** + * Start Date + */ + start_date: string | null; + /** + * End Date + */ + end_date: string | null; + /** + * Created At + */ + created_at: string; + /** + * Updated At + */ + updated_at: string; }; /** @@ -1209,7 +1365,12 @@ export type RollCallContext = { */ export type SessionEffect = { type: SessionEffectType; - data?: VotingContext; + /** + * Data + */ + data?: { + [key: string]: unknown; + }; }; /** @@ -1357,44 +1518,44 @@ export type ServerSessionMessage = ({ type: 'dispatch_result'; } & DispatchResultMessage); -export type HealthCommitteesHealthGetData = { +export type HealthHealthGetData = { body?: never; path?: never; query?: never; - url: '/committees/health'; + url: '/health'; }; -export type HealthCommitteesHealthGetResponses = { +export type HealthHealthGetResponses = { /** * Successful Response */ 200: unknown; }; -export type CreateSessionEndpointCommitteesPostData = { +export type CreateSessionEndpointSessionsPostData = { body: SessionCreationSchema; path?: never; query?: never; - url: '/committees/'; + url: '/sessions/'; }; -export type CreateSessionEndpointCommitteesPostErrors = { +export type CreateSessionEndpointSessionsPostErrors = { /** * Validation Error */ 422: HttpValidationError; }; -export type CreateSessionEndpointCommitteesPostError = CreateSessionEndpointCommitteesPostErrors[keyof CreateSessionEndpointCommitteesPostErrors]; +export type CreateSessionEndpointSessionsPostError = CreateSessionEndpointSessionsPostErrors[keyof CreateSessionEndpointSessionsPostErrors]; -export type CreateSessionEndpointCommitteesPostResponses = { +export type CreateSessionEndpointSessionsPostResponses = { /** * Successful Response */ 200: unknown; }; -export type ActivateSessionEndpointCommitteesSessionIdActivatePostData = { +export type ActivateSessionEndpointSessionsSessionIdActivatePostData = { body?: never; path: { /** @@ -1403,26 +1564,26 @@ export type ActivateSessionEndpointCommitteesSessionIdActivatePostData = { session_id: number; }; query?: never; - url: '/committees/{session_id}/activate'; + url: '/sessions/{session_id}/activate'; }; -export type ActivateSessionEndpointCommitteesSessionIdActivatePostErrors = { +export type ActivateSessionEndpointSessionsSessionIdActivatePostErrors = { /** * Validation Error */ 422: HttpValidationError; }; -export type ActivateSessionEndpointCommitteesSessionIdActivatePostError = ActivateSessionEndpointCommitteesSessionIdActivatePostErrors[keyof ActivateSessionEndpointCommitteesSessionIdActivatePostErrors]; +export type ActivateSessionEndpointSessionsSessionIdActivatePostError = ActivateSessionEndpointSessionsSessionIdActivatePostErrors[keyof ActivateSessionEndpointSessionsSessionIdActivatePostErrors]; -export type ActivateSessionEndpointCommitteesSessionIdActivatePostResponses = { +export type ActivateSessionEndpointSessionsSessionIdActivatePostResponses = { /** * Successful Response */ 204: void; }; -export type ActivateSessionEndpointCommitteesSessionIdActivatePostResponse = ActivateSessionEndpointCommitteesSessionIdActivatePostResponses[keyof ActivateSessionEndpointCommitteesSessionIdActivatePostResponses]; +export type ActivateSessionEndpointSessionsSessionIdActivatePostResponse = ActivateSessionEndpointSessionsSessionIdActivatePostResponses[keyof ActivateSessionEndpointSessionsSessionIdActivatePostResponses]; export type GetMySessionAccessAccessSessionsSessionIdMeGetData = { body?: never; @@ -1453,3 +1614,198 @@ export type GetMySessionAccessAccessSessionsSessionIdMeGetResponses = { }; export type GetMySessionAccessAccessSessionsSessionIdMeGetResponse = GetMySessionAccessAccessSessionsSessionIdMeGetResponses[keyof GetMySessionAccessAccessSessionsSessionIdMeGetResponses]; + +export type GetMyConferenceAccessEndpointAccessConferencesConferenceIdMeGetData = { + body?: never; + path: { + /** + * Conference Id + */ + conference_id: number; + }; + query?: never; + url: '/access/conferences/{conference_id}/me'; +}; + +export type GetMyConferenceAccessEndpointAccessConferencesConferenceIdMeGetErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type GetMyConferenceAccessEndpointAccessConferencesConferenceIdMeGetError = GetMyConferenceAccessEndpointAccessConferencesConferenceIdMeGetErrors[keyof GetMyConferenceAccessEndpointAccessConferencesConferenceIdMeGetErrors]; + +export type GetMyConferenceAccessEndpointAccessConferencesConferenceIdMeGetResponses = { + /** + * Successful Response + */ + 200: ConferenceAccess; +}; + +export type GetMyConferenceAccessEndpointAccessConferencesConferenceIdMeGetResponse = GetMyConferenceAccessEndpointAccessConferencesConferenceIdMeGetResponses[keyof GetMyConferenceAccessEndpointAccessConferencesConferenceIdMeGetResponses]; + +export type ListConferencesEndpointConferencesGetData = { + body?: never; + path?: never; + query?: never; + url: '/conferences'; +}; + +export type ListConferencesEndpointConferencesGetResponses = { + /** + * Response List Conferences Endpoint Conferences Get + * + * Successful Response + */ + 200: Array; +}; + +export type ListConferencesEndpointConferencesGetResponse = ListConferencesEndpointConferencesGetResponses[keyof ListConferencesEndpointConferencesGetResponses]; + +export type CreateConferenceEndpointConferencesPostData = { + body: ConferenceCreate; + path?: never; + query?: never; + url: '/conferences'; +}; + +export type CreateConferenceEndpointConferencesPostErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type CreateConferenceEndpointConferencesPostError = CreateConferenceEndpointConferencesPostErrors[keyof CreateConferenceEndpointConferencesPostErrors]; + +export type CreateConferenceEndpointConferencesPostResponses = { + /** + * Successful Response + */ + 201: ConferenceRead; +}; + +export type CreateConferenceEndpointConferencesPostResponse = CreateConferenceEndpointConferencesPostResponses[keyof CreateConferenceEndpointConferencesPostResponses]; + +export type GetConferenceEndpointConferencesConferenceIdGetData = { + body?: never; + path: { + /** + * Conference Id + */ + conference_id: number; + }; + query?: never; + url: '/conferences/{conference_id}'; +}; + +export type GetConferenceEndpointConferencesConferenceIdGetErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type GetConferenceEndpointConferencesConferenceIdGetError = GetConferenceEndpointConferencesConferenceIdGetErrors[keyof GetConferenceEndpointConferencesConferenceIdGetErrors]; + +export type GetConferenceEndpointConferencesConferenceIdGetResponses = { + /** + * Successful Response + */ + 200: ConferenceRead; +}; + +export type GetConferenceEndpointConferencesConferenceIdGetResponse = GetConferenceEndpointConferencesConferenceIdGetResponses[keyof GetConferenceEndpointConferencesConferenceIdGetResponses]; + +export type ListCommitteesEndpointConferencesConferenceIdCommitteesGetData = { + body?: never; + path: { + /** + * Conference Id + */ + conference_id: number; + }; + query?: never; + url: '/conferences/{conference_id}/committees'; +}; + +export type ListCommitteesEndpointConferencesConferenceIdCommitteesGetErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type ListCommitteesEndpointConferencesConferenceIdCommitteesGetError = ListCommitteesEndpointConferencesConferenceIdCommitteesGetErrors[keyof ListCommitteesEndpointConferencesConferenceIdCommitteesGetErrors]; + +export type ListCommitteesEndpointConferencesConferenceIdCommitteesGetResponses = { + /** + * Response List Committees Endpoint Conferences Conference Id Committees Get + * + * Successful Response + */ + 200: Array; +}; + +export type ListCommitteesEndpointConferencesConferenceIdCommitteesGetResponse = ListCommitteesEndpointConferencesConferenceIdCommitteesGetResponses[keyof ListCommitteesEndpointConferencesConferenceIdCommitteesGetResponses]; + +export type CreateCommitteeEndpointConferencesConferenceIdCommitteesPostData = { + body: CommitteeCreate; + path: { + /** + * Conference Id + */ + conference_id: number; + }; + query?: never; + url: '/conferences/{conference_id}/committees'; +}; + +export type CreateCommitteeEndpointConferencesConferenceIdCommitteesPostErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type CreateCommitteeEndpointConferencesConferenceIdCommitteesPostError = CreateCommitteeEndpointConferencesConferenceIdCommitteesPostErrors[keyof CreateCommitteeEndpointConferencesConferenceIdCommitteesPostErrors]; + +export type CreateCommitteeEndpointConferencesConferenceIdCommitteesPostResponses = { + /** + * Successful Response + */ + 201: CommitteeRead; +}; + +export type CreateCommitteeEndpointConferencesConferenceIdCommitteesPostResponse = CreateCommitteeEndpointConferencesConferenceIdCommitteesPostResponses[keyof CreateCommitteeEndpointConferencesConferenceIdCommitteesPostResponses]; + +export type GetCommitteeEndpointCommitteesCommitteeIdGetData = { + body?: never; + path: { + /** + * Committee Id + */ + committee_id: number; + }; + query?: never; + url: '/committees/{committee_id}'; +}; + +export type GetCommitteeEndpointCommitteesCommitteeIdGetErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type GetCommitteeEndpointCommitteesCommitteeIdGetError = GetCommitteeEndpointCommitteesCommitteeIdGetErrors[keyof GetCommitteeEndpointCommitteesCommitteeIdGetErrors]; + +export type GetCommitteeEndpointCommitteesCommitteeIdGetResponses = { + /** + * Successful Response + */ + 200: CommitteeRead; +}; + +export type GetCommitteeEndpointCommitteesCommitteeIdGetResponse = GetCommitteeEndpointCommitteesCommitteeIdGetResponses[keyof GetCommitteeEndpointCommitteesCommitteeIdGetResponses]; From 9e065f183d71ddd18e9a690cc1674e287c2fa249 Mon Sep 17 00:00:00 2001 From: wate <110754234+r0liveir@users.noreply.github.com> Date: Thu, 3 Sep 2026 07:44:04 -0300 Subject: [PATCH 05/19] feat(frontend): add conference context Co-authored-by: Codex --- frontend/src/context/ConferenceContext.tsx | 188 +++++++++++++++++++++ frontend/src/lib/api.ts | 46 +++-- frontend/src/main.tsx | 9 +- 3 files changed, 224 insertions(+), 19 deletions(-) create mode 100644 frontend/src/context/ConferenceContext.tsx diff --git a/frontend/src/context/ConferenceContext.tsx b/frontend/src/context/ConferenceContext.tsx new file mode 100644 index 0000000..565e9d0 --- /dev/null +++ b/frontend/src/context/ConferenceContext.tsx @@ -0,0 +1,188 @@ +import { createContext, useCallback, useContext, useEffect, useMemo, useState } from "react" +import type { ReactNode } from "react" + +import { useAuth } from "@/context/AuthContext" +import { apiJson } from "@/lib/api" +import type { + CommitteeCreate, + CommitteeRead, + ConferenceAccess, + ConferenceCreate, + ConferenceRead, +} from "@/schemas/types.gen" + +type ConferenceContextType = { + conferences: ConferenceRead[] + activeConference: ConferenceRead | null + activeConferenceId: number | null + committees: CommitteeRead[] + conferenceAccess: ConferenceAccess | null + canManageConference: boolean + loading: boolean + error: string | null + setActiveConferenceId: (conferenceId: number) => void + refreshConferences: () => Promise + refreshCommittees: () => Promise + createConference: (draft: ConferenceCreate) => Promise + createCommittee: (draft: CommitteeCreate) => Promise +} + +const ConferenceContext = createContext(null) + +export function ConferenceProvider({ children }: { children: ReactNode }) { + const { token, loading: authLoading } = useAuth() + const [conferences, setConferences] = useState([]) + const [activeConferenceId, setActiveConferenceIdState] = useState(null) + const [committees, setCommittees] = useState([]) + const [conferenceAccess, setConferenceAccess] = useState(null) + const [loading, setLoading] = useState(false) + const [error, setError] = useState(null) + + const activeConference = useMemo( + () => conferences.find((conference) => conference.id === activeConferenceId) ?? null, + [activeConferenceId, conferences] + ) + + const setActiveConferenceId = useCallback((conferenceId: number) => { + setActiveConferenceIdState(conferenceId) + }, []) + + const refreshConferences = useCallback(async () => { + if (!token) { + setConferences([]) + setActiveConferenceIdState(null) + return + } + + setLoading(true) + setError(null) + + try { + const nextConferences = await apiJson("/conferences") + setConferences(nextConferences) + setActiveConferenceIdState((currentId) => { + if (currentId && nextConferences.some((conference) => conference.id === currentId)) { + return currentId + } + + return nextConferences[0]?.id ?? null + }) + } catch (fetchError) { + setError(fetchError instanceof Error ? fetchError.message : "Failed to load conferences") + } finally { + setLoading(false) + } + }, [token]) + + const refreshCommittees = useCallback(async () => { + if (!activeConferenceId) { + setCommittees([]) + setConferenceAccess(null) + return + } + + setLoading(true) + setError(null) + + try { + const [nextCommittees, nextAccess] = await Promise.all([ + apiJson(`/conferences/${activeConferenceId}/committees`), + apiJson(`/access/conferences/${activeConferenceId}/me`), + ]) + setCommittees(nextCommittees) + setConferenceAccess(nextAccess) + } catch (fetchError) { + setError(fetchError instanceof Error ? fetchError.message : "Failed to load conference data") + } finally { + setLoading(false) + } + }, [activeConferenceId]) + + const createConference = useCallback(async (draft: ConferenceCreate) => { + const conference = await apiJson("/conferences", { + method: "POST", + body: JSON.stringify(draft), + }) + + setConferences((currentConferences) => [...currentConferences, conference]) + setActiveConferenceIdState(conference.id) + return conference + }, []) + + const createCommittee = useCallback(async (draft: CommitteeCreate) => { + if (!activeConferenceId) { + throw new Error("Select a conference before creating committees") + } + + const committee = await apiJson( + `/conferences/${activeConferenceId}/committees`, + { + method: "POST", + body: JSON.stringify(draft), + } + ) + + setCommittees((currentCommittees) => [...currentCommittees, committee]) + return committee + }, [activeConferenceId]) + + useEffect(() => { + if (authLoading) { + return + } + + void refreshConferences() + }, [authLoading, refreshConferences]) + + useEffect(() => { + void refreshCommittees() + }, [refreshCommittees]) + + const value = useMemo( + () => ({ + conferences, + activeConference, + activeConferenceId, + committees, + conferenceAccess, + canManageConference: conferenceAccess?.can_manage_conference ?? false, + loading, + error, + setActiveConferenceId, + refreshConferences, + refreshCommittees, + createConference, + createCommittee, + }), + [ + conferences, + activeConference, + activeConferenceId, + committees, + conferenceAccess, + loading, + error, + setActiveConferenceId, + refreshConferences, + refreshCommittees, + createConference, + createCommittee, + ] + ) + + return ( + + {children} + + ) +} + +export function useConference() { + const context = useContext(ConferenceContext) + + if (!context) { + throw new Error("useConference must be used inside ConferenceProvider") + } + + return context +} diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts index 1cc9fda..9782030 100644 --- a/frontend/src/lib/api.ts +++ b/frontend/src/lib/api.ts @@ -1,21 +1,35 @@ import { supabase } from "@/lib/supabaseClient" - export async function apiFetch( - path: string, - init: RequestInit = {}, - ): Promise { - const { data: { session } } = await supabase.auth.getSession() +export async function apiFetch( + path: string, + init: RequestInit = {}, +): Promise { + const { data: { session } } = await supabase.auth.getSession() - if (!session) { - throw new Error("Authentication required") - } + if (!session) { + throw new Error("Authentication required") + } + + return fetch(`${import.meta.env.VITE_API_URL}${path}`, { + ...init, + headers: { + ...init.headers, + Authorization: `Bearer ${session.access_token}`, + "Content-Type": "application/json", + }, + }) +} - return fetch(`${import.meta.env.VITE_API_URL}${path}`, { - ...init, - headers: { - ...init.headers, - Authorization: `Bearer ${session.access_token}`, - "Content-Type": "application/json", - }, - }) +export async function apiJson( + path: string, + init: RequestInit = {}, +): Promise { + const response = await apiFetch(path, init) + + if (!response.ok) { + const errorText = await response.text() + throw new Error(errorText || `Request failed with status ${response.status}`) } + + return response.json() as Promise +} diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx index 0bd6e73..9d359a7 100644 --- a/frontend/src/main.tsx +++ b/frontend/src/main.tsx @@ -4,13 +4,16 @@ import './index.css' import App from './App.tsx' import { TooltipProvider } from "@/components/ui/tooltip" import { AuthProvider } from '@/context/AuthContext' +import { ConferenceProvider } from '@/context/ConferenceContext' createRoot(document.getElementById('root')!).render( - - - + + + + + , ) From 3fcb71a10d5bbff360c1fb326e4e0030cd52a13d Mon Sep 17 00:00:00 2001 From: wate <110754234+r0liveir@users.noreply.github.com> Date: Thu, 3 Sep 2026 07:45:10 -0300 Subject: [PATCH 06/19] feat(frontend): wire conference switcher Co-authored-by: Codex --- .../components/userDashboard/mun-switcher.tsx | 155 ++++++++++++++---- 1 file changed, 120 insertions(+), 35 deletions(-) diff --git a/frontend/src/components/userDashboard/mun-switcher.tsx b/frontend/src/components/userDashboard/mun-switcher.tsx index 793adbe..d279a6d 100644 --- a/frontend/src/components/userDashboard/mun-switcher.tsx +++ b/frontend/src/components/userDashboard/mun-switcher.tsx @@ -2,6 +2,16 @@ import * as React from "react" +import { useConference } from "@/context/ConferenceContext" +import { Button } from "@/components/ui/button" +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from "@/components/ui/dialog" import { DropdownMenu, DropdownMenuContent, @@ -17,37 +27,53 @@ import { SidebarMenuItem, useSidebar, } from "@/components/ui/sidebar" -import { AudioLinesIcon, ChevronsUpDownIcon, GalleryVerticalEndIcon, PlusIcon, TerminalIcon } from "lucide-react" - - +import { Input } from "@/components/ui/input" +import { Label } from "@/components/ui/label" +import { ChevronsUpDownIcon, GalleryVerticalEndIcon, PlusIcon } from "lucide-react" export function MUNSwitcher() { - - const Conferences = [ - { - name: "Acme Inc", - logo: , - plan: "Enterprise", - }, - { - name: "Acme Corp.", - logo: , - plan: "Startup", - }, - { - name: "Evil Corp.", - logo: , - plan: "Free", - }, -] - const { isMobile } = useSidebar() - const [activeConference, setActiveTeam] = React.useState(Conferences[0]) + const { + conferences, + activeConference, + setActiveConferenceId, + createConference, + loading, + error, + } = useConference() + const [createDialogOpen, setCreateDialogOpen] = React.useState(false) + const [conferenceName, setConferenceName] = React.useState("") + const [conferenceLocation, setConferenceLocation] = React.useState("") + const [submitting, setSubmitting] = React.useState(false) + const [submitError, setSubmitError] = React.useState(null) + + async function handleCreateConference(event: React.FormEvent) { + event.preventDefault() + + const trimmedName = conferenceName.trim() + if (!trimmedName) { + return + } - if (!activeConference) { - return null + setSubmitting(true) + setSubmitError(null) + + try { + await createConference({ + name: trimmedName, + location: conferenceLocation.trim() || null, + }) + setConferenceName("") + setConferenceLocation("") + setCreateDialogOpen(false) + } catch (createError) { + setSubmitError( + createError instanceof Error ? createError.message : "Failed to create conference" + ) + } finally { + setSubmitting(false) + } } - return ( @@ -59,11 +85,15 @@ export function MUNSwitcher() { className="data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground" >
- {activeConference.logo} + {activeConference?.name.slice(0, 2).toUpperCase() ?? }
- {activeConference.name} - {activeConference.plan} + + {activeConference?.name ?? "No conference"} + + + {activeConference?.status ?? (loading ? "Loading" : "Select or create")} +
@@ -77,21 +107,32 @@ export function MUNSwitcher() { Conferences - {Conferences.map((team, index) => ( + {conferences.map((conference, index) => ( setActiveTeam(team)} + key={conference.id} + onClick={() => setActiveConferenceId(conference.id)} className="gap-2 p-2" >
- {team.logo} + {conference.name.slice(0, 2).toUpperCase()}
- {team.name} + {conference.name} ⌘{index + 1}
))} + {conferences.length === 0 ? ( + + {error ?? "No conferences found"} + + ) : null} - + { + event.preventDefault() + setCreateDialogOpen(true) + }} + >
@@ -100,6 +141,50 @@ export function MUNSwitcher() { + + + + Create conference + + Add the conference shell first. Committees and sessions can be created after it exists. + + +
+
+ + setConferenceName(event.target.value)} + required + /> +
+
+ + setConferenceLocation(event.target.value)} + /> +
+ {submitError ? ( +

{submitError}

+ ) : null} + + + + +
+
+
) } From 5a08353287b6b835a8ba19cd97abe790cba6d04c Mon Sep 17 00:00:00 2001 From: wate <110754234+r0liveir@users.noreply.github.com> Date: Thu, 3 Sep 2026 07:47:44 -0300 Subject: [PATCH 07/19] feat(frontend): wire committee management Co-authored-by: Codex --- .../conferenceMenus/committee-managemant.tsx | 426 ++++-------------- 1 file changed, 98 insertions(+), 328 deletions(-) diff --git a/frontend/src/components/userDashboard/conferenceMenus/committee-managemant.tsx b/frontend/src/components/userDashboard/conferenceMenus/committee-managemant.tsx index e149e8b..d636cde 100644 --- a/frontend/src/components/userDashboard/conferenceMenus/committee-managemant.tsx +++ b/frontend/src/components/userDashboard/conferenceMenus/committee-managemant.tsx @@ -11,8 +11,11 @@ import { getSortedRowModel, useReactTable, } from "@tanstack/react-table" -import { ArrowUpDown, ChevronDown } from "lucide-react" +import { ArrowUpDown, ChevronDown, PlusIcon } from "lucide-react" +import { useConference } from "@/context/ConferenceContext" +import type { CommitteeRead } from "@/schemas/types.gen" +import { Badge } from "@/components/ui/badge" import { Button } from "@/components/ui/button" import { Checkbox } from "@/components/ui/checkbox" import { @@ -31,13 +34,6 @@ import { } from "@/components/ui/dropdown-menu" import { Input } from "@/components/ui/input" import { Label } from "@/components/ui/label" -import { - Select, - SelectContent, - SelectItem, - SelectTrigger, - SelectValue, -} from "@/components/ui/select" import { Table, TableBody, @@ -47,172 +43,56 @@ import { TableRow, } from "@/components/ui/table" -type Committee = { - id: string - name: string - logo: string - colour: string - acronym: string - type: string -} - -type CommitteeDraft = Omit - -const committeeTypes = [ - "Traditional", - "WIMUN", - "Consensus", - "Teatro de Operações", - "Crisis", - "Specialized", -] - -function createLogoDataUrl(acronym: string, colour: string) { - const safeAcronym = acronym.trim() || "CM" - const safeColour = colour || "#64748b" - - return `data:image/svg+xml;charset=UTF-8,${encodeURIComponent( - ` - - ${safeAcronym} - ` - )}` -} - -const initialCommittees: Committee[] = [ - { - id: "c4c5f1d6-0f6e-41ed-a610-52e2cbb1b54a", - name: "Security Council", - logo: "SC", - colour: "#1d4ed8", - acronym: "SC", - type: "Traditional", - }, - { - id: "7f0a82f5-ae0b-4f5d-9c2c-7d2f72cbda0e", - name: "United Nations Children’s Fund", - logo: "UNICEF", - colour: "#0f766e", - acronym: "UNICEF", - type: "WIMUN", - }, - { - id: "86e0f1d0-6d76-4b70-86ec-061d4e8e4f57", - name: "World Health Organization", - logo: "WHO", - colour: "#15803d", - acronym: "WHO", - type: "Consensus", - }, - { - id: "bb64d5ce-0d34-4e8a-8c22-5f0b4db7ff90", - name: "Crisis Room", - logo: "CR", - colour: "#b45309", - acronym: "CR", - type: "Teatro de Operações", - }, -] - -function CommitteeLogoPreview({ logo, colour }: { logo: string; colour: string }) { - const displayLabel = logo.trim() || "--" - const isImageLogo = logo.startsWith("data:image/") || logo.startsWith("blob:") || /^https?:\/\//.test(logo) - - return ( -
- {isImageLogo ? ( - {displayLabel} - ) : ( -
- {displayLabel} -
- )} -
- ) +function formatDate(value: string) { + return new Intl.DateTimeFormat("pt-BR", { + dateStyle: "short", + timeStyle: "short", + }).format(new Date(value)) } export default function CommitteeManagement() { - const [committees, setCommittees] = React.useState(initialCommittees) + const { + activeConference, + committees, + createCommittee, + loading, + error, + canManageConference, + } = useConference() const [sorting, setSorting] = React.useState([]) const [columnFilters, setColumnFilters] = React.useState([]) const [columnVisibility, setColumnVisibility] = React.useState({}) const [rowSelection, setRowSelection] = React.useState({}) - const [editingCommitteeId, setEditingCommitteeId] = React.useState(null) - const [draftCommittee, setDraftCommittee] = React.useState(null) - - const editingCommittee = React.useMemo( - () => committees.find((committee) => committee.id === editingCommitteeId) ?? null, - [committees, editingCommitteeId] - ) - - React.useEffect(() => { - if (!editingCommittee) { - setDraftCommittee(null) - return - } + const [createDialogOpen, setCreateDialogOpen] = React.useState(false) + const [committeeName, setCommitteeName] = React.useState("") + const [submitError, setSubmitError] = React.useState(null) + const [submitting, setSubmitting] = React.useState(false) - setDraftCommittee({ - name: editingCommittee.name, - logo: editingCommittee.logo, - colour: editingCommittee.colour, - acronym: editingCommittee.acronym, - type: editingCommittee.type, - }) - }, [editingCommittee]) + async function handleCreateCommittee(event: React.FormEvent) { + event.preventDefault() - function openEditor(id: string) { - setEditingCommitteeId(id) - } - - function closeEditor() { - setEditingCommitteeId(null) - } - - async function handleLogoFileChange(file: File | null) { - if (!file) { + const trimmedName = committeeName.trim() + if (!trimmedName) { return } - const nextLogo = await new Promise((resolve, reject) => { - const reader = new FileReader() - - reader.onload = () => resolve(String(reader.result ?? "")) - reader.onerror = () => reject(reader.error) - reader.readAsDataURL(file) - }) - - setDraftCommittee((currentDraft) => - currentDraft ? { ...currentDraft, logo: nextLogo } : currentDraft - ) - } - - function saveDraftCommittee() { - if (!editingCommittee || !draftCommittee) { - return - } + setSubmitting(true) + setSubmitError(null) - setCommittees((currentCommittees) => - currentCommittees.map((committee) => - committee.id === editingCommittee.id - ? { - ...committee, - ...draftCommittee, - logo: - draftCommittee.logo || - createLogoDataUrl(draftCommittee.acronym, draftCommittee.colour), - } - : committee + try { + await createCommittee({ name: trimmedName }) + setCommitteeName("") + setCreateDialogOpen(false) + } catch (createError) { + setSubmitError( + createError instanceof Error ? createError.message : "Failed to create committee" ) - ) - closeEditor() + } finally { + setSubmitting(false) + } } - const columns = React.useMemo[]>( + const columns = React.useMemo[]>( () => [ { id: "select", @@ -250,68 +130,32 @@ export default function CommitteeManagement() { cell: ({ row }) => {row.original.name}, }, { - accessorKey: "logo", - header: "Logo", - cell: ({ row }) => ( -
- - Imagem do comitê -
- ), + accessorKey: "status", + header: "Status", + cell: ({ row }) => {row.original.status}, }, { - accessorKey: "colour", + accessorKey: "created_at", header: ({ column }) => ( ), cell: ({ row }) => ( -
-
- ), - }, - { - accessorKey: "acronym", - header: ({ column }) => ( - + + {formatDate(row.original.created_at)} + ), - cell: ({ row }) => {row.original.acronym}, - }, - { - accessorKey: "type", - header: ({ column }) => ( - - ), - cell: ({ row }) => {row.original.type}, }, { id: "actions", header: "Ações", - cell: ({ row }) => ( - ), @@ -340,33 +184,27 @@ export default function CommitteeManagement() { }, }) - function deleteSelectedCommittees() { - const selectedIds = new Set( - table.getFilteredSelectedRowModel().rows.map((row) => row.original.id) - ) - - if (selectedIds.size === 0) { - return - } - - setCommittees((currentCommittees) => - currentCommittees.filter((committee) => !selectedIds.has(committee.id)) - ) - setRowSelection({}) - } - const selectedCount = table.getFilteredSelectedRowModel().rows.length + const canCreateCommittee = Boolean(activeConference && canManageConference) return (

Gestão de comitês

- Edite nome, logo, cor, acrônimo e tipo dos comitês da conferência. + {activeConference + ? `Comitês de ${activeConference.name}.` + : "Selecione ou crie uma conferência para gerenciar comitês."}

-
+ {error ? ( +
+ {error} +
+ ) : null} + +
+ +
-
+
{table.getHeaderGroups().map((headerGroup) => ( @@ -447,7 +289,7 @@ export default function CommitteeManagement() { ) : ( - Nenhum comitê encontrado. + {loading ? "Carregando comitês..." : "Nenhum comitê encontrado."} )} @@ -481,112 +323,40 @@ export default function CommitteeManagement() { - !open && closeEditor()}> - + + - Editar comitê + Criar comitê - Atualize os atributos do comitê no formulário. O logo é enviado como arquivo de imagem. + O backend atual persiste apenas o nome do comitê. Campos visuais ficam para um endpoint posterior. - - {draftCommittee ? ( -
-
- - - setDraftCommittee((currentDraft) => - currentDraft ? { ...currentDraft, name: event.target.value } : currentDraft - ) - } - /> -
- -
- - - setDraftCommittee((currentDraft) => - currentDraft - ? { ...currentDraft, acronym: event.target.value.toUpperCase() } - : currentDraft - ) - } - className="uppercase" - /> -
- -
- - -
- -
- - - setDraftCommittee((currentDraft) => - currentDraft ? { ...currentDraft, colour: event.target.value } : currentDraft - ) - } - className="h-10 w-full p-1" - /> -
- -
- -
- -
- { - void handleLogoFileChange(event.target.files?.[0] ?? null) - }} - /> -

- Se você escolher um novo arquivo, ele substituirá o logo atual. -

-
-
-
+
+
+ + setCommitteeName(event.target.value)} + required + />
- ) : null} - - - - - + {submitError ? ( +

{submitError}

+ ) : null} + + + + +
From 37cc890fa57c4a26abc4d5bedc77d5fbccb32af7 Mon Sep 17 00:00:00 2001 From: wate <110754234+r0liveir@users.noreply.github.com> Date: Thu, 3 Sep 2026 08:02:49 -0300 Subject: [PATCH 08/19] feat(access): expose accessible conference committees Co-authored-by: Codex --- backend/app/access/models.py | 7 +++ backend/app/access/repository.py | 76 +++++++++++++++++++++++- backend/app/access/schemas.py | 7 +++ backend/app/access/service.py | 21 ++++++- backend/app/tests/access/test_service.py | 26 +++++++- frontend/src/schemas/types.gen.ts | 22 +++++++ 6 files changed, 156 insertions(+), 3 deletions(-) diff --git a/backend/app/access/models.py b/backend/app/access/models.py index 8881a43..7aeab60 100644 --- a/backend/app/access/models.py +++ b/backend/app/access/models.py @@ -12,3 +12,10 @@ class CommitteeAssignment: committee_id: int # TODO: remove this to map out to committees/conferences role: enums.SessionRoles representation_id: int | None + + +@dataclass(frozen=True) +class AccessibleCommittee: + committee_id: int + role: str + representation_id: int | None diff --git a/backend/app/access/repository.py b/backend/app/access/repository.py index a077159..f4e66f7 100644 --- a/backend/app/access/repository.py +++ b/backend/app/access/repository.py @@ -3,7 +3,7 @@ from sqlalchemy import bindparam, text from sqlalchemy.ext.asyncio import AsyncSession -from .models import CommitteeAssignment +from .models import AccessibleCommittee, CommitteeAssignment # TODO: pass this to a conference/ domain @@ -138,3 +138,77 @@ async def has_conference_assignment_for_session_access( }, ) return result.scalar_one_or_none() is not None + + +async def list_accessible_conference_committees( + session: AsyncSession, + *, + conference_id: int, + user_id: UUID, + conference_roles: set[str], +) -> list[AccessibleCommittee]: + query = text(""" + SELECT DISTINCT ON (committee_id) + committee_id, + role, + representation_id + FROM ( + SELECT + ca.committee_id, + ca.role::text AS role, + ca.representation_id, + CASE + WHEN ca.role::text = 'delegate' THEN 1 + WHEN ca.role::text = 'chair' THEN 2 + ELSE 3 + END AS priority + FROM public.committee_assignments ca + JOIN public.committees cm + ON cm.id = ca.committee_id + WHERE cm.conference_id = :conference_id + AND ca.user_id = :user_id + + UNION ALL + + SELECT + cm.id AS committee_id, + 'chair' AS role, + null::bigint AS representation_id, + 2 AS priority + FROM public.committees cm + JOIN public.conferences c + ON c.id = cm.conference_id + LEFT JOIN public.conference_assignments cfa + ON cfa.conference_id = c.id + AND cfa.user_id = :user_id + AND cfa.role IN :conference_roles + AND ( + cfa.committee_id IS NULL + OR cfa.committee_id = cm.id + ) + WHERE cm.conference_id = :conference_id + AND ( + c.owner_id = :user_id + OR cfa.user_id IS NOT NULL + ) + ) access + ORDER BY committee_id, priority + """).bindparams(bindparam("conference_roles", expanding=True)) + + result = await session.execute( + query, + { + "conference_id": conference_id, + "user_id": user_id, + "conference_roles": list(conference_roles), + }, + ) + + return [ + AccessibleCommittee( + committee_id=row["committee_id"], + role=row["role"], + representation_id=row["representation_id"], + ) + for row in result.mappings().all() + ] diff --git a/backend/app/access/schemas.py b/backend/app/access/schemas.py index e4ace4e..2dca730 100644 --- a/backend/app/access/schemas.py +++ b/backend/app/access/schemas.py @@ -13,8 +13,15 @@ class CommitteeScopedConferenceRole(BaseModel): role: str +class AccessibleCommittee(BaseModel): + committee_id: int + role: str + representation_id: int | None + + class ConferenceAccess(BaseModel): conference_id: int roles: list[str] committee_roles: list[CommitteeScopedConferenceRole] + accessible_committees: list[AccessibleCommittee] can_manage_conference: bool diff --git a/backend/app/access/service.py b/backend/app/access/service.py index b77a02c..6d5afb9 100644 --- a/backend/app/access/service.py +++ b/backend/app/access/service.py @@ -4,7 +4,11 @@ from sqlalchemy.ext.asyncio import AsyncSession from app.access.models import CommitteeAssignment -from app.access.schemas import CommitteeScopedConferenceRole, ConferenceAccess +from app.access.schemas import ( + AccessibleCommittee, + CommitteeScopedConferenceRole, + ConferenceAccess, +) from app.conference import repository as conference_repository from app.conference.enums import ConferenceRole from app.core.exceptions import AccessDeniedError @@ -14,6 +18,7 @@ get_session_assignment, has_conference_assignment_for_session_access, has_conference_management_role, + list_accessible_conference_committees, ) CONFERENCE_MANAGEMENT_ROLES = { @@ -137,11 +142,25 @@ async def get_my_conference_access( for assignment in assignments if assignment.committee_id is not None ] + accessible_committees = [ + AccessibleCommittee( + committee_id=committee.committee_id, + role=committee.role, + representation_id=committee.representation_id, + ) + for committee in await list_accessible_conference_committees( + session=session, + conference_id=conference_id, + user_id=user_id, + conference_roles=SESSION_ACCESS_GRANTING_CONFERENCE_ROLES, + ) + ] return ConferenceAccess( conference_id=conference_id, roles=roles, committee_roles=committee_roles, + accessible_committees=accessible_committees, can_manage_conference=any( role in CONFERENCE_MANAGEMENT_ROLES for role in roles ), diff --git a/backend/app/tests/access/test_service.py b/backend/app/tests/access/test_service.py index fe17a10..4b6a65d 100644 --- a/backend/app/tests/access/test_service.py +++ b/backend/app/tests/access/test_service.py @@ -3,7 +3,7 @@ import pytest -from app.access.models import CommitteeAssignment +from app.access.models import AccessibleCommittee, CommitteeAssignment from app.access.service import ( get_my_conference_access, resolve_committee_assignment, @@ -181,6 +181,9 @@ async def repo_get_conference(*_args, **_kwargs): async def no_assignments(*_args, **_kwargs): return [] + async def no_accessible_committees(*_args, **_kwargs): + return [] + monkeypatch.setattr( "app.access.service.conference_repository.get_user_conference", repo_get_conference, @@ -189,11 +192,16 @@ async def no_assignments(*_args, **_kwargs): "app.access.service.conference_repository.list_user_conference_assignments", no_assignments, ) + monkeypatch.setattr( + "app.access.service.list_accessible_conference_committees", + no_accessible_committees, + ) result = await get_my_conference_access(object(), owner_id, 1) assert result.roles == ["owner"] assert result.committee_roles == [] + assert result.accessible_committees == [] assert result.can_manage_conference is True @@ -212,6 +220,15 @@ async def assignments(*_args, **_kwargs): ConferenceAssignment(role="moderator", committee_id=10), ] + async def accessible_committees(*_args, **_kwargs): + return [ + AccessibleCommittee( + committee_id=10, + role="delegate", + representation_id=3, + ) + ] + monkeypatch.setattr( "app.access.service.conference_repository.get_user_conference", repo_get_conference, @@ -220,10 +237,17 @@ async def assignments(*_args, **_kwargs): "app.access.service.conference_repository.list_user_conference_assignments", assignments, ) + monkeypatch.setattr( + "app.access.service.list_accessible_conference_committees", + accessible_committees, + ) result = await get_my_conference_access(object(), user_id, 1) assert result.roles == ["press"] assert result.committee_roles[0].committee_id == 10 assert result.committee_roles[0].role == "moderator" + assert result.accessible_committees[0].committee_id == 10 + assert result.accessible_committees[0].role == "delegate" + assert result.accessible_committees[0].representation_id == 3 assert result.can_manage_conference is False diff --git a/frontend/src/schemas/types.gen.ts b/frontend/src/schemas/types.gen.ts index e38af2c..d3fd413 100644 --- a/frontend/src/schemas/types.gen.ts +++ b/frontend/src/schemas/types.gen.ts @@ -4,6 +4,24 @@ export type ClientOptions = { baseUrl: `${string}://${string}` | (string & {}); }; +/** + * AccessibleCommittee + */ +export type AccessibleCommittee = { + /** + * Committee Id + */ + committee_id: number; + /** + * Role + */ + role: string; + /** + * Representation Id + */ + representation_id: number | null; +}; + /** * CommitteeCreate */ @@ -74,6 +92,10 @@ export type ConferenceAccess = { * Committee Roles */ committee_roles: Array; + /** + * Accessible Committees + */ + accessible_committees: Array; /** * Can Manage Conference */ From fe379938cbfc28678d969460cf839caaffd65955 Mon Sep 17 00:00:00 2001 From: wate <110754234+r0liveir@users.noreply.github.com> Date: Thu, 3 Sep 2026 09:42:01 -0300 Subject: [PATCH 09/19] feat(conference): add committee metadata Co-authored-by: Codex --- backend/app/access/repository.py | 60 ++---- backend/app/access/service.py | 1 - backend/app/conference/models.py | 4 + backend/app/conference/repository.py | 37 +++- backend/app/conference/schemas.py | 8 + backend/app/tests/conference/test_service.py | 4 + .../conferenceMenus/committee-managemant.tsx | 178 +++++++++++++++++- frontend/src/schemas/types.gen.ts | 32 ++++ .../20260719224327_create_initial_tables.sql | 9 +- supabase/seed.sql | 11 +- 10 files changed, 279 insertions(+), 65 deletions(-) diff --git a/backend/app/access/repository.py b/backend/app/access/repository.py index f4e66f7..61a427f 100644 --- a/backend/app/access/repository.py +++ b/backend/app/access/repository.py @@ -6,7 +6,6 @@ from .models import AccessibleCommittee, CommitteeAssignment -# TODO: pass this to a conference/ domain async def get_committee_assignment( session: AsyncSession, user_id: UUID, committee_id: int ) -> CommitteeAssignment | None: @@ -145,62 +144,25 @@ async def list_accessible_conference_committees( *, conference_id: int, user_id: UUID, - conference_roles: set[str], ) -> list[AccessibleCommittee]: query = text(""" - SELECT DISTINCT ON (committee_id) - committee_id, - role, - representation_id - FROM ( - SELECT - ca.committee_id, - ca.role::text AS role, - ca.representation_id, - CASE - WHEN ca.role::text = 'delegate' THEN 1 - WHEN ca.role::text = 'chair' THEN 2 - ELSE 3 - END AS priority - FROM public.committee_assignments ca - JOIN public.committees cm - ON cm.id = ca.committee_id - WHERE cm.conference_id = :conference_id - AND ca.user_id = :user_id - - UNION ALL - - SELECT - cm.id AS committee_id, - 'chair' AS role, - null::bigint AS representation_id, - 2 AS priority - FROM public.committees cm - JOIN public.conferences c - ON c.id = cm.conference_id - LEFT JOIN public.conference_assignments cfa - ON cfa.conference_id = c.id - AND cfa.user_id = :user_id - AND cfa.role IN :conference_roles - AND ( - cfa.committee_id IS NULL - OR cfa.committee_id = cm.id - ) - WHERE cm.conference_id = :conference_id - AND ( - c.owner_id = :user_id - OR cfa.user_id IS NOT NULL - ) - ) access - ORDER BY committee_id, priority - """).bindparams(bindparam("conference_roles", expanding=True)) + SELECT + ca.committee_id, + ca.role, + ca.representation_id + FROM public.committee_assignments ca + JOIN public.committees cm + ON cm.id = ca.committee_id + WHERE cm.conference_id = :conference_id + AND ca.user_id = :user_id + ORDER BY cm.created_at DESC, cm.id DESC + """) result = await session.execute( query, { "conference_id": conference_id, "user_id": user_id, - "conference_roles": list(conference_roles), }, ) diff --git a/backend/app/access/service.py b/backend/app/access/service.py index 6d5afb9..eb52b3f 100644 --- a/backend/app/access/service.py +++ b/backend/app/access/service.py @@ -152,7 +152,6 @@ async def get_my_conference_access( session=session, conference_id=conference_id, user_id=user_id, - conference_roles=SESSION_ACCESS_GRANTING_CONFERENCE_ROLES, ) ] diff --git a/backend/app/conference/models.py b/backend/app/conference/models.py index 14b8f01..3a21fdd 100644 --- a/backend/app/conference/models.py +++ b/backend/app/conference/models.py @@ -23,6 +23,10 @@ class Committee: id: int conference_id: int name: str + acronym: str | None + committee_type: str | None + logo_url: str | None + theme_color: str | None status: str created_at: datetime updated_at: datetime diff --git a/backend/app/conference/repository.py b/backend/app/conference/repository.py index c0cce38..9ecd0f0 100644 --- a/backend/app/conference/repository.py +++ b/backend/app/conference/repository.py @@ -28,6 +28,10 @@ def _committee_from_row(row) -> Committee: id=row["id"], conference_id=row["conference_id"], name=row["name"], + acronym=row["acronym"], + committee_type=row["committee_type"], + logo_url=row["logo_url"], + theme_color=row["theme_color"], status=row["status"], created_at=row["created_at"], updated_at=row["updated_at"], @@ -189,14 +193,31 @@ async def create_committee( ) -> Committee | None: query = text(""" INSERT INTO public.committees - (conference_id, name) + (conference_id, name, acronym, committee_type, logo_url, theme_color) VALUES - (:conference_id, :name) - RETURNING id, conference_id, name, status, created_at, updated_at + ( + :conference_id, + :name, + :acronym, + :committee_type, + :logo_url, + :theme_color + ) + RETURNING + id, conference_id, name, acronym, committee_type, logo_url, theme_color, + status, created_at, updated_at """) result = await session.execute( - query, {"conference_id": conference_id, "name": data.name} + query, + { + "conference_id": conference_id, + "name": data.name, + "acronym": data.acronym, + "committee_type": data.committee_type, + "logo_url": data.logo_url, + "theme_color": data.theme_color, + }, ) row = result.mappings().one_or_none() return _committee_from_row(row) if row is not None else None @@ -208,7 +229,9 @@ async def list_conference_committees( conference_id: int, ) -> list[Committee]: query = text(""" - SELECT id, conference_id, name, status, created_at, updated_at + SELECT + id, conference_id, name, acronym, committee_type, logo_url, theme_color, + status, created_at, updated_at FROM public.committees WHERE conference_id = :conference_id ORDER BY created_at DESC, id DESC @@ -225,7 +248,9 @@ async def get_user_committee( user_id: UUID, ) -> Committee | None: query = text(""" - SELECT cm.id, cm.conference_id, cm.name, cm.status, cm.created_at, cm.updated_at + SELECT + cm.id, cm.conference_id, cm.name, cm.acronym, cm.committee_type, + cm.logo_url, cm.theme_color, cm.status, cm.created_at, cm.updated_at FROM public.committees cm JOIN public.conferences c ON c.id = cm.conference_id diff --git a/backend/app/conference/schemas.py b/backend/app/conference/schemas.py index 73e41b1..bb9abd0 100644 --- a/backend/app/conference/schemas.py +++ b/backend/app/conference/schemas.py @@ -29,12 +29,20 @@ class ConferenceRead(BaseModel): class CommitteeCreate(BaseModel): name: str = Field(min_length=1, max_length=64) + acronym: str | None = Field(default=None, max_length=16) + committee_type: str | None = Field(default=None, max_length=64) + logo_url: str | None = Field(default=None, max_length=1000) + theme_color: str | None = Field(default=None, pattern=r"^#[0-9A-Fa-f]{6}$") class CommitteeRead(BaseModel): id: int conference_id: int name: str + acronym: str | None + committee_type: str | None + logo_url: str | None + theme_color: str | None status: str created_at: datetime updated_at: datetime diff --git a/backend/app/tests/conference/test_service.py b/backend/app/tests/conference/test_service.py index f09c4ca..1876621 100644 --- a/backend/app/tests/conference/test_service.py +++ b/backend/app/tests/conference/test_service.py @@ -48,6 +48,10 @@ def committee(): id=10, conference_id=1, name="CSNU", + acronym="CSNU", + committee_type="Traditional", + logo_url=None, + theme_color="#1d4ed8", status="planned", created_at=now, updated_at=now, diff --git a/frontend/src/components/userDashboard/conferenceMenus/committee-managemant.tsx b/frontend/src/components/userDashboard/conferenceMenus/committee-managemant.tsx index d636cde..845d82a 100644 --- a/frontend/src/components/userDashboard/conferenceMenus/committee-managemant.tsx +++ b/frontend/src/components/userDashboard/conferenceMenus/committee-managemant.tsx @@ -34,6 +34,13 @@ import { } from "@/components/ui/dropdown-menu" import { Input } from "@/components/ui/input" import { Label } from "@/components/ui/label" +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from "@/components/ui/select" import { Table, TableBody, @@ -50,6 +57,40 @@ function formatDate(value: string) { }).format(new Date(value)) } +const committeeTypes = [ + "Traditional", + "WIMUN", + "Consensus", + "Teatro de Operações", + "Crisis", + "Specialized", +] + +function fallback(value: string | null | undefined) { + return value?.trim() || "N/A" +} + +function CommitteeLogoPreview({ committee }: { committee: CommitteeRead }) { + const label = committee.acronym?.trim() || committee.name.slice(0, 2).toUpperCase() + const themeColor = committee.theme_color ?? "#64748b" + + return ( +
+ {committee.logo_url ? ( + {label} + ) : ( +
+ {label} +
+ )} +
+ ) +} + export default function CommitteeManagement() { const { activeConference, @@ -65,6 +106,10 @@ export default function CommitteeManagement() { const [rowSelection, setRowSelection] = React.useState({}) const [createDialogOpen, setCreateDialogOpen] = React.useState(false) const [committeeName, setCommitteeName] = React.useState("") + const [committeeAcronym, setCommitteeAcronym] = React.useState("") + const [committeeType, setCommitteeType] = React.useState("") + const [committeeLogoUrl, setCommitteeLogoUrl] = React.useState("") + const [committeeThemeColor, setCommitteeThemeColor] = React.useState("#64748b") const [submitError, setSubmitError] = React.useState(null) const [submitting, setSubmitting] = React.useState(false) @@ -80,8 +125,18 @@ export default function CommitteeManagement() { setSubmitError(null) try { - await createCommittee({ name: trimmedName }) + await createCommittee({ + name: trimmedName, + acronym: committeeAcronym.trim() || null, + committee_type: committeeType || null, + logo_url: committeeLogoUrl.trim() || null, + theme_color: committeeThemeColor, + }) setCommitteeName("") + setCommitteeAcronym("") + setCommitteeType("") + setCommitteeLogoUrl("") + setCommitteeThemeColor("#64748b") setCreateDialogOpen(false) } catch (createError) { setSubmitError( @@ -129,6 +184,72 @@ export default function CommitteeManagement() { ), cell: ({ row }) => {row.original.name}, }, + { + accessorKey: "logo_url", + header: "Logo", + cell: ({ row }) => ( +
+ + + {row.original.logo_url ? "Imagem do comitê" : "N/A"} + +
+ ), + }, + { + accessorKey: "acronym", + header: ({ column }) => ( + + ), + cell: ({ row }) => ( + {fallback(row.original.acronym)} + ), + }, + { + accessorKey: "committee_type", + header: ({ column }) => ( + + ), + cell: ({ row }) => {fallback(row.original.committee_type)}, + }, + { + accessorKey: "theme_color", + header: ({ column }) => ( + + ), + cell: ({ row }) => ( +
+ {row.original.theme_color ? ( +
+ ), + }, { accessorKey: "status", header: "Status", @@ -328,11 +449,11 @@ export default function CommitteeManagement() { Criar comitê - O backend atual persiste apenas o nome do comitê. Campos visuais ficam para um endpoint posterior. + Configure os metadados básicos usados na dashboard da conferência. -
-
+ +
+
+ + + setCommitteeAcronym(event.target.value.toUpperCase()) + } + className="uppercase" + /> +
+
+ + +
+
+ + setCommitteeThemeColor(event.target.value)} + className="h-10 w-full p-1" + /> +
+
+ + setCommitteeLogoUrl(event.target.value)} + placeholder="https://..." + /> +
{submitError ? ( -

{submitError}

+

{submitError}

) : null} - + - ) : ( - - )} - - - - ))} + return ( + + + + +
+ + Session {session.sessionNumber} + + {sessionIsActive ? Active : null} +
+
+ + Start: {session.startTime} | End: {session.endTime} + +
+ + + {canActivateSessions ? ( + + ) : null} + {session.joinHref ? ( + + ) : ( + + )} + +
+
+ ) + })} ) -} \ No newline at end of file +} From e1cf051e168362b3740b4a993ecc7dc9257e9673 Mon Sep 17 00:00:00 2001 From: wate <110754234+r0liveir@users.noreply.github.com> Date: Thu, 3 Sep 2026 10:01:55 -0300 Subject: [PATCH 12/19] fix(frontend): point websocket env to sessions Co-authored-by: Codex --- frontend/.env.example | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frontend/.env.example b/frontend/.env.example index fad3328..f47eda9 100644 --- a/frontend/.env.example +++ b/frontend/.env.example @@ -1,6 +1,6 @@ # Env variables used to communicate with backend VITE_API_URL=http://localhost:8000 -VITE_WS_URL=ws://localhost:8000/committees +VITE_WS_URL=ws://localhost:8000/sessions # Supabase auth variables VITE_SUPABASE_URL= From f88d141b973d6d2c0a58fc044791af4e3beb008f Mon Sep 17 00:00:00 2001 From: wate <110754234+r0liveir@users.noreply.github.com> Date: Thu, 3 Sep 2026 11:47:00 -0300 Subject: [PATCH 13/19] fix(frontend): gate dashboard and session actions Co-authored-by: Codex --- frontend/src/App.tsx | 2 +- .../userDashboard/UserDash-sidebar.tsx | 31 ++++++++++------- .../committeeMenus/committee-sessions.tsx | 33 +++++++++++-------- .../src/components/userDashboard/nav-user.tsx | 22 ++++++++++--- 4 files changed, 57 insertions(+), 31 deletions(-) diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 40e66a3..f0beb4d 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -54,7 +54,7 @@ function App() { } /> } /> } /> - }> + }> } /> } /> } /> diff --git a/frontend/src/components/userDashboard/UserDash-sidebar.tsx b/frontend/src/components/userDashboard/UserDash-sidebar.tsx index c9f770f..1bb21e3 100644 --- a/frontend/src/components/userDashboard/UserDash-sidebar.tsx +++ b/frontend/src/components/userDashboard/UserDash-sidebar.tsx @@ -6,6 +6,7 @@ import { ConferenceMenus } from "@/components/userDashboard/conference-menus-lis import { CommitteeMenus } from "@/components/userDashboard/committee-menus-list" import { NavUser } from "@/components/userDashboard/nav-user" import { MUNSwitcher } from "@/components/userDashboard/mun-switcher" +import { useAuth } from "@/context/AuthContext" import { Sidebar, SidebarContent, @@ -16,17 +17,16 @@ import { -// This is sample data. -const data = { - user: { - name: "shadcn", - email: "m@example.com", - avatar: "/avatars/shadcn.jpg", - }, - -} - export function AppSidebar({ ...props }: React.ComponentProps) { + const { user, signOut } = useAuth() + const displayName = + user?.user_metadata?.name ?? + user?.user_metadata?.full_name ?? + user?.email?.split("@")[0] ?? + "User" + const displayEmail = user?.email ?? "" + const avatar = user?.user_metadata?.avatar_url ?? "" + return ( @@ -37,7 +37,16 @@ export function AppSidebar({ ...props }: React.ComponentProps) { - + { + void signOut() + }} + /> diff --git a/frontend/src/components/userDashboard/committeeMenus/committee-sessions.tsx b/frontend/src/components/userDashboard/committeeMenus/committee-sessions.tsx index 1de8e57..d0e9399 100644 --- a/frontend/src/components/userDashboard/committeeMenus/committee-sessions.tsx +++ b/frontend/src/components/userDashboard/committeeMenus/committee-sessions.tsx @@ -13,6 +13,7 @@ import { import { useConference } from "@/context/ConferenceContext" import { apiFetch } from "@/lib/api" import * as React from "react" +import { useNavigate } from "react-router-dom" type CommitteeSession = { id: string @@ -60,6 +61,7 @@ export default function CommitteeSessions({ onJoin, }: CommitteeSessionsProps) { const { activeCommittee, activeCommitteeAccess } = useConference() + const navigate = useNavigate() const [activatedSessionIds, setActivatedSessionIds] = React.useState>( () => new Set( @@ -98,6 +100,15 @@ export default function CommitteeSessions({ } } + function joinSession(session: CommitteeSession) { + if (session.joinHref) { + navigate(session.joinHref) + return + } + + onJoin?.(session) + } + return (
@@ -141,29 +152,23 @@ export default function CommitteeSessions({ - {canActivateSessions ? ( + {canActivateSessions && !sessionIsActive ? ( ) : null} - {session.joinHref ? ( - - ) : ( - - )} + diff --git a/frontend/src/components/userDashboard/nav-user.tsx b/frontend/src/components/userDashboard/nav-user.tsx index f29579d..0801c79 100644 --- a/frontend/src/components/userDashboard/nav-user.tsx +++ b/frontend/src/components/userDashboard/nav-user.tsx @@ -20,16 +20,28 @@ import { } from "@/components/ui/sidebar" import { ChevronsUpDownIcon, SparklesIcon, BadgeCheckIcon, CreditCardIcon, BellIcon, LogOutIcon } from "lucide-react" +function getInitials(name: string) { + return name + .split(" ") + .filter(Boolean) + .slice(0, 2) + .map((part) => part[0]?.toUpperCase()) + .join("") || "U" +} + export function NavUser({ user, + onSignOut, }: { user: { name: string email: string avatar: string } + onSignOut?: () => void }) { const { isMobile } = useSidebar() + const initials = getInitials(user.name) return ( @@ -40,9 +52,9 @@ export function NavUser({ size="lg" className="data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground" > - - - CN + + + {initials}
{user.name} @@ -61,7 +73,7 @@ export function NavUser({
- CN + {initials}
{user.name} @@ -96,7 +108,7 @@ export function NavUser({ - + Log out From bd6c9c5dbabc70032d1b7901b98230819beb6b9a Mon Sep 17 00:00:00 2001 From: wate <110754234+r0liveir@users.noreply.github.com> Date: Thu, 3 Sep 2026 12:46:40 -0300 Subject: [PATCH 14/19] fix(frontend): quiet conference fetch lint Co-authored-by: Codex --- frontend/src/context/ConferenceContext.tsx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/frontend/src/context/ConferenceContext.tsx b/frontend/src/context/ConferenceContext.tsx index c035eb4..4831b84 100644 --- a/frontend/src/context/ConferenceContext.tsx +++ b/frontend/src/context/ConferenceContext.tsx @@ -177,10 +177,12 @@ export function ConferenceProvider({ children }: { children: ReactNode }) { return } + // eslint-disable-next-line react-hooks/set-state-in-effect -- Initial data load starts after auth resolves and updates async request state. void refreshConferences() }, [authLoading, refreshConferences]) useEffect(() => { + // eslint-disable-next-line react-hooks/set-state-in-effect -- Committee/access data is synchronized when the active conference changes. void refreshCommittees() }, [refreshCommittees]) From 4fd49a96deb3e434bb619a19d9f7ef0dae24bfcf Mon Sep 17 00:00:00 2001 From: wate <110754234+r0liveir@users.noreply.github.com> Date: Sat, 5 Sep 2026 22:43:31 -0300 Subject: [PATCH 15/19] Implement real conference assignments and sessions Co-authored-by: Codex --- backend/app/conference/enums.py | 1 + backend/app/conference/models.py | 13 + backend/app/conference/repository.py | 153 +++++- backend/app/conference/schemas.py | 41 ++ backend/app/conference/service.py | 134 ++++- backend/app/conference/views.py | 87 +++ backend/app/session/repository.py | 21 + backend/app/session/schemas.py | 10 + backend/app/session/service.py | 7 + backend/app/session/views.py | 14 + backend/app/tests/conference/test_service.py | 24 +- .../committeeMenus/committee-sessions.tsx | 227 ++------ .../userDashboard/conference-menus-list.tsx | 2 +- .../conferenceMenus/committee-managemant.tsx | 43 +- .../participants/list-allocation.tsx | 443 ++-------------- .../team/manage-perms-roles.tsx | 381 +------------- .../conferenceMenus/team/team-alocate.tsx | 497 ++---------------- frontend/src/schemas/types.gen.ts | 409 +++++++++++++- ...100000_add_conference_participant_role.sql | 1 + 19 files changed, 1117 insertions(+), 1391 deletions(-) create mode 100644 supabase/migrations/20260905100000_add_conference_participant_role.sql diff --git a/backend/app/conference/enums.py b/backend/app/conference/enums.py index b526e60..3253a22 100644 --- a/backend/app/conference/enums.py +++ b/backend/app/conference/enums.py @@ -11,6 +11,7 @@ class ConferenceRole(StrEnum): PRESS = "press" LOGISTICS = "logistics" STAFF = "staff" + PARTICIPANT = "participant" class CommitteeRole(StrEnum): diff --git a/backend/app/conference/models.py b/backend/app/conference/models.py index 3a21fdd..5f5c849 100644 --- a/backend/app/conference/models.py +++ b/backend/app/conference/models.py @@ -46,3 +46,16 @@ class ConferenceAssignment: user_id: UUID role: str committee_id: int | None + + +@dataclass(frozen=True) +class Representation: + id: int + name: str + code: str | None + + +@dataclass(frozen=True) +class Layout: + id: int + name: str diff --git a/backend/app/conference/repository.py b/backend/app/conference/repository.py index 9ecd0f0..fbbeaf5 100644 --- a/backend/app/conference/repository.py +++ b/backend/app/conference/repository.py @@ -3,7 +3,7 @@ from sqlalchemy import text from sqlalchemy.ext.asyncio import AsyncSession -from .models import Committee, CommitteeAssignment, Conference, ConferenceAssignment +from .models import Committee, CommitteeAssignment, Conference, ConferenceAssignment, Layout, Representation from .schemas import CommitteeCreate, ConferenceCreate @@ -56,6 +56,14 @@ def _conference_assignment_from_row(row) -> ConferenceAssignment: ) +def _representation_from_row(row) -> Representation: + return Representation(id=row["id"], name=row["name"], code=row["code"]) + + +def _layout_from_row(row) -> Layout: + return Layout(id=row["id"], name=row["name"]) + + async def create_conference( session: AsyncSession, *, @@ -115,6 +123,118 @@ async def create_conference_assignment( ) +async def list_conference_assignments( + session: AsyncSession, *, conference_id: int +) -> list[dict]: + result = await session.execute( + text(""" + SELECT ca.conference_id, u.email, ca.role, ca.committee_id + FROM public.conference_assignments ca + JOIN auth.users u ON u.id = ca.user_id + WHERE ca.conference_id = :conference_id + ORDER BY ca.created_at DESC, ca.id DESC + """), + {"conference_id": conference_id}, + ) + return [dict(row) for row in result.mappings().all()] + + +async def get_user_id_by_email( + session: AsyncSession, *, email: str +) -> UUID | None: + result = await session.execute( + text("SELECT id FROM auth.users WHERE lower(email) = lower(:email) LIMIT 1"), + {"email": email.strip()}, + ) + return result.scalar_one_or_none() + + +async def is_committee_in_conference( + session: AsyncSession, *, conference_id: int, committee_id: int +) -> bool: + result = await session.execute( + text(""" + SELECT 1 FROM public.committees + WHERE id = :committee_id AND conference_id = :conference_id + """), + {"conference_id": conference_id, "committee_id": committee_id}, + ) + return result.scalar_one_or_none() is not None + + +async def is_conference_participant( + session: AsyncSession, *, conference_id: int, user_id: UUID +) -> bool: + result = await session.execute( + text(""" + SELECT 1 FROM public.conference_assignments + WHERE conference_id = :conference_id AND user_id = :user_id + AND role = 'participant' + LIMIT 1 + """), + {"conference_id": conference_id, "user_id": user_id}, + ) + return result.scalar_one_or_none() is not None + + +async def list_participant_allocations( + session: AsyncSession, *, conference_id: int +) -> list[dict]: + result = await session.execute( + text(""" + SELECT u.email, cm.id AS committee_id, cm.name AS committee_name, + r.id AS representation_id, r.name AS representation_name + FROM public.conference_assignments ca + JOIN auth.users u ON u.id = ca.user_id + LEFT JOIN public.committee_assignments cma + ON cma.user_id = ca.user_id + LEFT JOIN public.committees cm + ON cm.id = cma.committee_id AND cm.conference_id = ca.conference_id + LEFT JOIN public.representations r ON r.id = cma.representation_id + WHERE ca.conference_id = :conference_id AND ca.role = 'participant' + AND (cm.id IS NOT NULL OR cma.committee_id IS NULL) + ORDER BY u.email, cm.id + """), + {"conference_id": conference_id}, + ) + return [dict(row) for row in result.mappings().all()] + + +async def list_committee_representations( + session: AsyncSession, *, committee_id: int +) -> list[Representation]: + result = await session.execute( + text(""" + SELECT r.id, r.name, r.code + FROM public.committee_seats cs + JOIN public.representations r ON r.id = cs.representation_id + WHERE cs.committee_id = :committee_id + ORDER BY r.name, r.id + """), + {"committee_id": committee_id}, + ) + return [_representation_from_row(row) for row in result.mappings().all()] + + +async def upsert_participant_committee_assignment( + session: AsyncSession, *, user_id: UUID, committee_id: int, representation_id: int +) -> CommitteeAssignment | None: + result = await session.execute( + text(""" + INSERT INTO public.committee_assignments + (user_id, committee_id, role, representation_id) + VALUES (:user_id, :committee_id, 'delegate', :representation_id) + ON CONFLICT (user_id, committee_id) DO UPDATE SET + role = EXCLUDED.role, representation_id = EXCLUDED.representation_id + WHERE public.committee_assignments.role = 'delegate' + RETURNING user_id, committee_id, role, representation_id + """), + {"user_id": user_id, "committee_id": committee_id, "representation_id": representation_id}, + ) + row = result.mappings().one_or_none() + return _committee_assignment_from_row(row) if row is not None else None + + async def list_user_conferences( session: AsyncSession, *, @@ -223,6 +343,37 @@ async def create_committee( return _committee_from_row(row) if row is not None else None +async def list_available_layouts( + session: AsyncSession, *, conference_id: int +) -> list[Layout]: + result = await session.execute( + text(""" + SELECT id, name FROM public.layouts + WHERE committee_id IS NULL + AND (conference_id IS NULL OR conference_id = :conference_id) + ORDER BY conference_id NULLS LAST, name, id + """), + {"conference_id": conference_id}, + ) + return [_layout_from_row(row) for row in result.mappings().all()] + + +async def copy_layout_seats( + session: AsyncSession, *, layout_id: int, committee_id: int +) -> int: + result = await session.execute( + text(""" + INSERT INTO public.committee_seats (committee_id, representation_id, seat_label) + SELECT :committee_id, representation_id, seat_label + FROM public.layout_seats + WHERE layout_id = :layout_id + ON CONFLICT DO NOTHING + """), + {"layout_id": layout_id, "committee_id": committee_id}, + ) + return result.rowcount + + async def list_conference_committees( session: AsyncSession, *, diff --git a/backend/app/conference/schemas.py b/backend/app/conference/schemas.py index bb9abd0..7f57b78 100644 --- a/backend/app/conference/schemas.py +++ b/backend/app/conference/schemas.py @@ -3,6 +3,8 @@ from pydantic import BaseModel, Field +from .enums import ConferenceRole + class ConferenceCreate(BaseModel): name: str = Field(min_length=1, max_length=255) @@ -33,6 +35,7 @@ class CommitteeCreate(BaseModel): committee_type: str | None = Field(default=None, max_length=64) logo_url: str | None = Field(default=None, max_length=1000) theme_color: str | None = Field(default=None, pattern=r"^#[0-9A-Fa-f]{6}$") + layout_id: int = Field(gt=0) class CommitteeRead(BaseModel): @@ -53,3 +56,41 @@ class CommitteeAssignmentRead(BaseModel): committee_id: int role: str representation_id: int | None + + +class ConferenceAssignmentCreate(BaseModel): + email: str = Field(min_length=3, max_length=320) + role: ConferenceRole + committee_id: int | None = None + + +class ConferenceAssignmentRead(BaseModel): + conference_id: int + email: str + role: ConferenceRole + committee_id: int | None + + +class ParticipantAllocationCreate(BaseModel): + email: str = Field(min_length=3, max_length=320) + committee_id: int + representation_id: int + + +class ParticipantAllocationRead(BaseModel): + email: str + committee_id: int | None + committee_name: str | None + representation_id: int | None + representation_name: str | None + + +class RepresentationRead(BaseModel): + id: int + name: str + code: str | None + + +class LayoutRead(BaseModel): + id: int + name: str diff --git a/backend/app/conference/service.py b/backend/app/conference/service.py index 496f020..c46ab81 100644 --- a/backend/app/conference/service.py +++ b/backend/app/conference/service.py @@ -8,8 +8,8 @@ from . import repository from .enums import CommitteeRole, ConferenceRole -from .models import Committee, CommitteeAssignment, Conference -from .schemas import CommitteeCreate, ConferenceCreate +from .models import Committee, CommitteeAssignment, Conference, ConferenceAssignment, Layout, Representation +from .schemas import CommitteeCreate, ConferenceAssignmentCreate, ConferenceCreate, ParticipantAllocationCreate async def create_conference( @@ -74,16 +74,146 @@ async def create_committee( user_id=user_id, ) + layouts = await repository.list_available_layouts( + session=session, conference_id=conference_id + ) + if data.layout_id not in {layout.id for layout in layouts}: + raise BadRequest("Layout is not available for this conference") + committee = await repository.create_committee( session=session, conference_id=conference_id, data=data ) if committee is None: raise BadRequest("Could not create committee") + await repository.copy_layout_seats( + session=session, layout_id=data.layout_id, committee_id=committee.id + ) + + await repository.upsert_committee_session_assignment( + session=session, + committee_id=committee.id, + user_id=user_id, + role=CommitteeRole.CHAIR, + ) + await session.commit() return committee +async def list_available_layouts( + session: AsyncSession, *, conference_id: int, user_id: UUID +) -> list[Layout]: + await access.verify_can_manage_conference( + session=session, conference_id=conference_id, user_id=user_id + ) + return await repository.list_available_layouts( + session=session, conference_id=conference_id + ) + + +async def create_conference_assignment( + session: AsyncSession, + *, + conference_id: int, + created_by: UUID, + data: ConferenceAssignmentCreate, +) -> dict: + await access.verify_can_manage_conference( + session=session, conference_id=conference_id, user_id=created_by + ) + assignee_id = await repository.get_user_id_by_email(session=session, email=data.email) + if assignee_id is None: + raise BadRequest("User email was not found") + if data.committee_id is not None and not await repository.is_committee_in_conference( + session=session, conference_id=conference_id, committee_id=data.committee_id + ): + raise BadRequest("Committee does not belong to this conference") + await repository.create_conference_assignment( + session=session, + conference_id=conference_id, + user_id=assignee_id, + role=data.role, + committee_id=data.committee_id, + ) + await session.commit() + return { + "conference_id": conference_id, + "email": data.email, + "role": data.role, + "committee_id": data.committee_id, + } + + +async def list_conference_assignments( + session: AsyncSession, *, conference_id: int, user_id: UUID +) -> list[dict]: + await access.verify_can_manage_conference( + session=session, conference_id=conference_id, user_id=user_id + ) + return await repository.list_conference_assignments( + session=session, conference_id=conference_id + ) + + +async def list_participant_allocations( + session: AsyncSession, *, conference_id: int, user_id: UUID +) -> list[dict]: + await access.verify_can_manage_conference( + session=session, conference_id=conference_id, user_id=user_id + ) + return await repository.list_participant_allocations( + session=session, conference_id=conference_id + ) + + +async def allocate_participant( + session: AsyncSession, + *, + conference_id: int, + allocated_by: UUID, + data: ParticipantAllocationCreate, +) -> CommitteeAssignment: + await access.verify_can_manage_conference( + session=session, conference_id=conference_id, user_id=allocated_by + ) + participant_id = await repository.get_user_id_by_email(session=session, email=data.email) + if participant_id is None: + raise BadRequest("User email was not found") + if not await repository.is_conference_participant( + session=session, conference_id=conference_id, user_id=participant_id + ): + raise BadRequest("User is not a participant in this conference") + if not await repository.is_committee_in_conference( + session=session, conference_id=conference_id, committee_id=data.committee_id + ): + raise BadRequest("Committee does not belong to this conference") + representations = await repository.list_committee_representations( + session=session, committee_id=data.committee_id + ) + if data.representation_id not in {representation.id for representation in representations}: + raise BadRequest("Representation is not a seat in this committee") + assignment = await repository.upsert_participant_committee_assignment( + session=session, + user_id=participant_id, + committee_id=data.committee_id, + representation_id=data.representation_id, + ) + if assignment is None: + raise BadRequest("Could not allocate participant") + await session.commit() + return assignment + + +async def list_committee_representations( + session: AsyncSession, *, committee_id: int, user_id: UUID +) -> list[Representation]: + await get_committee(session=session, committee_id=committee_id, user_id=user_id) + return await repository.list_committee_representations( + session=session, committee_id=committee_id + ) + + async def list_committees( session: AsyncSession, *, diff --git a/backend/app/conference/views.py b/backend/app/conference/views.py index a161184..5eb7846 100644 --- a/backend/app/conference/views.py +++ b/backend/app/conference/views.py @@ -10,9 +10,16 @@ from . import service from .schemas import ( CommitteeCreate, + CommitteeAssignmentRead, CommitteeRead, + ConferenceAssignmentCreate, + ConferenceAssignmentRead, ConferenceCreate, ConferenceRead, + ParticipantAllocationCreate, + ParticipantAllocationRead, + LayoutRead, + RepresentationRead, ) router = APIRouter() @@ -61,6 +68,74 @@ async def get_conference_endpoint( return ConferenceRead(**conference.__dict__) +@router.get("/conferences/{conference_id}/layouts") +async def list_available_layouts_endpoint( + conference_id: int, + session: Annotated[AsyncSession, Depends(get_db_session)], + current_user: Annotated[AuthUser, Depends(get_current_user)], +) -> list[LayoutRead]: + layouts = await service.list_available_layouts( + session=session, conference_id=conference_id, user_id=current_user.user_id + ) + return [LayoutRead(**layout.__dict__) for layout in layouts] + + +@router.get("/conferences/{conference_id}/assignments") +async def list_conference_assignments_endpoint( + conference_id: int, + session: Annotated[AsyncSession, Depends(get_db_session)], + current_user: Annotated[AuthUser, Depends(get_current_user)], +) -> list[ConferenceAssignmentRead]: + assignments = await service.list_conference_assignments( + session=session, conference_id=conference_id, user_id=current_user.user_id + ) + return [ConferenceAssignmentRead(**assignment) for assignment in assignments] + + +@router.post("/conferences/{conference_id}/assignments", status_code=status.HTTP_201_CREATED) +async def create_conference_assignment_endpoint( + conference_id: int, + payload: ConferenceAssignmentCreate, + session: Annotated[AsyncSession, Depends(get_db_session)], + current_user: Annotated[AuthUser, Depends(get_current_user)], +) -> ConferenceAssignmentRead: + assignment = await service.create_conference_assignment( + session=session, + conference_id=conference_id, + created_by=current_user.user_id, + data=payload, + ) + return ConferenceAssignmentRead(**assignment) + + +@router.get("/conferences/{conference_id}/participants/allocations") +async def list_participant_allocations_endpoint( + conference_id: int, + session: Annotated[AsyncSession, Depends(get_db_session)], + current_user: Annotated[AuthUser, Depends(get_current_user)], +) -> list[ParticipantAllocationRead]: + allocations = await service.list_participant_allocations( + session=session, conference_id=conference_id, user_id=current_user.user_id + ) + return [ParticipantAllocationRead(**allocation) for allocation in allocations] + + +@router.put("/conferences/{conference_id}/participants/allocations") +async def allocate_participant_endpoint( + conference_id: int, + payload: ParticipantAllocationCreate, + session: Annotated[AsyncSession, Depends(get_db_session)], + current_user: Annotated[AuthUser, Depends(get_current_user)], +) -> CommitteeAssignmentRead: + assignment = await service.allocate_participant( + session=session, + conference_id=conference_id, + allocated_by=current_user.user_id, + data=payload, + ) + return CommitteeAssignmentRead(**assignment.__dict__) + + @router.post( "/conferences/{conference_id}/committees", status_code=status.HTTP_201_CREATED, @@ -106,3 +181,15 @@ async def get_committee_endpoint( user_id=current_user.user_id, ) return CommitteeRead(**committee.__dict__) + + +@router.get("/committees/{committee_id}/representations") +async def list_committee_representations_endpoint( + committee_id: int, + session: Annotated[AsyncSession, Depends(get_db_session)], + current_user: Annotated[AuthUser, Depends(get_current_user)], +) -> list[RepresentationRead]: + representations = await service.list_committee_representations( + session=session, committee_id=committee_id, user_id=current_user.user_id + ) + return [RepresentationRead(**representation.__dict__) for representation in representations] diff --git a/backend/app/session/repository.py b/backend/app/session/repository.py index c69648d..6211886 100644 --- a/backend/app/session/repository.py +++ b/backend/app/session/repository.py @@ -67,6 +67,27 @@ async def get_session_info( ) +async def list_committee_sessions( + session: AsyncSession, committee_id: int +) -> list[StoredSession]: + result = await session.execute( + text(""" + SELECT * FROM public.sessions + WHERE committee_id = :committee_id + ORDER BY id DESC + """), + {"committee_id": committee_id}, + ) + return [ + StoredSession( + id=row["id"], committee_id=row["committee_id"], name=row["name"], + status=row["status"], started_at=row["started_at"], + ended_at=row["ended_at"], state_snapshot=row["state_snapshot"], + ) + for row in result.mappings().all() + ] + + async def update_session_info( session: AsyncSession, session_info: StoredSession, diff --git a/backend/app/session/schemas.py b/backend/app/session/schemas.py index 90ff0b5..e2c9f09 100644 --- a/backend/app/session/schemas.py +++ b/backend/app/session/schemas.py @@ -1,3 +1,4 @@ +from datetime import datetime from typing import Annotated, Literal from uuid import UUID @@ -15,6 +16,15 @@ class SessionCreationSchema(BaseModel): name: str | None = None +class SessionRead(BaseModel): + id: int + committee_id: int + name: str | None + status: str + started_at: datetime | None + ended_at: datetime | None + + class MotionPayload(BaseModel): """General motion payload. Used on Delegate and Chair payloads""" diff --git a/backend/app/session/service.py b/backend/app/session/service.py index cda8ada..5e9219a 100644 --- a/backend/app/session/service.py +++ b/backend/app/session/service.py @@ -30,6 +30,7 @@ RollCallContext, SessionActor, SessionLiveState, + StoredSession, ) @@ -99,6 +100,12 @@ async def create_session_service( return session_id +async def list_committee_sessions( + session: AsyncSession, committee_id: int +) -> list[StoredSession]: + return await repository.list_committee_sessions(session=session, committee_id=committee_id) + + async def get_session_for_activation(session: AsyncSession, committee_session_id: int): stored = await repository.get_session_info( session=session, committee_session_id=committee_session_id diff --git a/backend/app/session/views.py b/backend/app/session/views.py index 93545e4..b1495b8 100644 --- a/backend/app/session/views.py +++ b/backend/app/session/views.py @@ -42,6 +42,7 @@ EventMessage, EventRejectedMessage, SessionCreationSchema, + SessionRead, StateSnapshotMessage, ) @@ -68,6 +69,19 @@ async def create_session_endpoint( return {"id": session_id, "status": "Created"} +@router.get("/committee/{committee_id}") +async def list_committee_sessions_endpoint( + committee_id: int, + session: Annotated[AsyncSession, Depends(get_db_session)], + current_user: Annotated[AuthUser, Depends(get_current_user)], +) -> list[SessionRead]: + await access.resolve_committee_assignment( + session=session, user_id=current_user.user_id, committee_id=committee_id + ) + sessions = await service.list_committee_sessions(session=session, committee_id=committee_id) + return [SessionRead(**stored.__dict__) for stored in sessions] + + @router.post("/{session_id}/activate", status_code=status.HTTP_204_NO_CONTENT) async def activate_session_endpoint( session_id: int, diff --git a/backend/app/tests/conference/test_service.py b/backend/app/tests/conference/test_service.py index 1876621..b5ff2b0 100644 --- a/backend/app/tests/conference/test_service.py +++ b/backend/app/tests/conference/test_service.py @@ -7,6 +7,7 @@ Committee, CommitteeAssignment, Conference, + Layout, ) from app.conference.schemas import CommitteeCreate, ConferenceCreate from app.conference.service import ( @@ -115,7 +116,7 @@ async def cannot_manage(*_args, **_kwargs): FakeSession(), conference_id=1, user_id=uuid4(), - data=CommitteeCreate(name="CSNU"), + data=CommitteeCreate(name="CSNU", layout_id=1), ) @@ -129,18 +130,37 @@ async def can_manage(*_args, **_kwargs): async def repo_create_committee(*_args, **_kwargs): return committee() + async def create_chair_assignment(*_args, **_kwargs): + return None + + async def available_layouts(*_args, **_kwargs): + return [Layout(id=1, name="Standard")] + + async def copy_seats(*_args, **_kwargs): + return 21 + monkeypatch.setattr( "app.conference.service.access.verify_can_manage_conference", can_manage ) monkeypatch.setattr( "app.conference.service.repository.create_committee", repo_create_committee ) + monkeypatch.setattr( + "app.conference.service.repository.upsert_committee_session_assignment", + create_chair_assignment, + ) + monkeypatch.setattr( + "app.conference.service.repository.list_available_layouts", available_layouts + ) + monkeypatch.setattr( + "app.conference.service.repository.copy_layout_seats", copy_seats + ) result = await create_committee( fake_session, conference_id=1, user_id=uuid4(), - data=CommitteeCreate(name="CSNU"), + data=CommitteeCreate(name="CSNU", layout_id=1), ) assert result.id == 10 diff --git a/frontend/src/components/userDashboard/committeeMenus/committee-sessions.tsx b/frontend/src/components/userDashboard/committeeMenus/committee-sessions.tsx index d0e9399..81ef91d 100644 --- a/frontend/src/components/userDashboard/committeeMenus/committee-sessions.tsx +++ b/frontend/src/components/userDashboard/committeeMenus/committee-sessions.tsx @@ -1,180 +1,57 @@ +import * as React from "react" import { Badge } from "@/components/ui/badge" import { Button } from "@/components/ui/button" -import { - Item, - ItemActions, - ItemContent, - ItemDescription, - ItemGroup, - ItemHeader, - ItemTitle, -} from "@/components/ui/item" +import { Input } from "@/components/ui/input" import { useConference } from "@/context/ConferenceContext" -import { apiFetch } from "@/lib/api" -import * as React from "react" -import { useNavigate } from "react-router-dom" - -type CommitteeSession = { - id: string - sessionNumber: number - startTime: string - endTime: string - status?: "planned" | "active" - joinHref?: string -} - -type CommitteeSessionsProps = { - sessions?: CommitteeSession[] - onJoin?: (session: CommitteeSession) => void -} - -const defaultSessions: CommitteeSession[] = [ - { - id: "1", - sessionNumber: 1, - startTime: "09:00", - endTime: "10:30", - status: "planned", - joinHref: "/sessions/1", - }, - { - id: "2", - sessionNumber: 2, - startTime: "11:00", - endTime: "12:30", - status: "planned", - joinHref: "/sessions/2", - }, - { - id: "3", - sessionNumber: 3, - startTime: "14:00", - endTime: "15:30", - status: "planned", - joinHref: "/sessions/3", - }, -] - -export default function CommitteeSessions({ - sessions = defaultSessions, - onJoin, -}: CommitteeSessionsProps) { - const { activeCommittee, activeCommitteeAccess } = useConference() - const navigate = useNavigate() - const [activatedSessionIds, setActivatedSessionIds] = React.useState>( - () => - new Set( - sessions - .filter((session) => session.status === "active") - .map((session) => session.id) - ) - ) - const [activatingSessionId, setActivatingSessionId] = React.useState< - string | null - >(null) - const [activationError, setActivationError] = React.useState(null) - const canActivateSessions = activeCommitteeAccess?.role === "chair" - - async function activateSession(session: CommitteeSession) { - setActivatingSessionId(session.id) - setActivationError(null) - - try { - const response = await apiFetch(`/sessions/${session.id}/activate`, { - method: "POST", - }) - - if (!response.ok) { - const errorText = await response.text() - throw new Error(errorText || "Failed to activate session") - } - - setActivatedSessionIds((currentIds) => new Set(currentIds).add(session.id)) - } catch (error) { - setActivationError( - error instanceof Error ? error.message : "Failed to activate session" - ) - } finally { - setActivatingSessionId(null) - } - } - - function joinSession(session: CommitteeSession) { - if (session.joinHref) { - navigate(session.joinHref) - return - } - - onJoin?.(session) - } - - return ( -
-
-

- {activeCommittee?.name ?? "Committee"} Sessions -

-

- View session time windows and join active sessions. -

-
- - {activationError ? ( -
- {activationError} -
- ) : null} - - - {sessions.map((session) => { - const sessionIsActive = activatedSessionIds.has(session.id) - - return ( - - - - -
- - Session {session.sessionNumber} - - {sessionIsActive ? Active : null} -
-
- - Start: {session.startTime} | End: {session.endTime} - -
- - - {canActivateSessions && !sessionIsActive ? ( - - ) : null} - - -
-
- ) - })} -
-
- ) +import { apiFetch, apiJson } from "@/lib/api" + +type CommitteeSession = { id: number; committee_id: number; name: string | null; status: string; started_at: string | null; ended_at: string | null } + +export default function CommitteeSessions() { + const { activeCommittee, activeCommitteeAccess } = useConference() + const [sessions, setSessions] = React.useState([]) + const [name, setName] = React.useState("") + const [error, setError] = React.useState(null) + const [creating, setCreating] = React.useState(false) + const [activating, setActivating] = React.useState(null) + const canManage = activeCommitteeAccess?.role === "chair" + + const load = React.useCallback(async () => { + if (!activeCommittee) return setSessions([]) + try { setSessions(await apiJson(`/sessions/committee/${activeCommittee.id}`)) } + catch (reason) { setError(reason instanceof Error ? reason.message : "Não foi possível carregar sessões") } + }, [activeCommittee]) + + React.useEffect(() => { void load() }, [load]) + + async function create(event: React.FormEvent) { + event.preventDefault() + if (!activeCommittee) return + setCreating(true); setError(null) + try { + await apiJson("/sessions/", { method: "POST", body: JSON.stringify({ committee_id: activeCommittee.id, name: name || null }) }) + setName(""); await load() + } catch (reason) { setError(reason instanceof Error ? reason.message : "Não foi possível criar a sessão") } + finally { setCreating(false) } + } + + async function activate(id: number) { + setActivating(id); setError(null) + try { + const response = await apiFetch(`/sessions/${id}/activate`, { method: "POST" }) + if (!response.ok) throw new Error((await response.text()) || "Não foi possível ativar a sessão") + await load() + } catch (reason) { setError(reason instanceof Error ? reason.message : "Não foi possível ativar a sessão") } + finally { setActivating(null) } + } + + return
+

Sessões {activeCommittee ? `— ${activeCommittee.name}` : ""}

Crie e ative sessões reais deste comitê.

+ {!activeCommittee ?

Selecione um comitê.

: <> + {canManage ? setName(event.target.value)} placeholder="Nome da sessão (opcional)" /> : null} + {error ?

{error}

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

{session.name || `Sessão ${session.id}`}

{session.status}
{canManage && session.status === "planned" ? : null}
)}{sessions.length === 0 ?

Nenhuma sessão criada.

: null}
+ } +
} diff --git a/frontend/src/components/userDashboard/conference-menus-list.tsx b/frontend/src/components/userDashboard/conference-menus-list.tsx index 35581d6..2573f2e 100644 --- a/frontend/src/components/userDashboard/conference-menus-list.tsx +++ b/frontend/src/components/userDashboard/conference-menus-list.tsx @@ -121,7 +121,7 @@ export function ConferenceMenus() { isActive={pathname === "/dashboard/conference/team/manage-perms-roles"} > - Papeis e Permissões + Papéis diff --git a/frontend/src/components/userDashboard/conferenceMenus/committee-managemant.tsx b/frontend/src/components/userDashboard/conferenceMenus/committee-managemant.tsx index 845d82a..5e7764d 100644 --- a/frontend/src/components/userDashboard/conferenceMenus/committee-managemant.tsx +++ b/frontend/src/components/userDashboard/conferenceMenus/committee-managemant.tsx @@ -14,6 +14,7 @@ import { import { ArrowUpDown, ChevronDown, PlusIcon } from "lucide-react" import { useConference } from "@/context/ConferenceContext" +import { apiJson } from "@/lib/api" import type { CommitteeRead } from "@/schemas/types.gen" import { Badge } from "@/components/ui/badge" import { Button } from "@/components/ui/button" @@ -66,6 +67,8 @@ const committeeTypes = [ "Specialized", ] +type Layout = { id: number; name: string } + function fallback(value: string | null | undefined) { return value?.trim() || "N/A" } @@ -110,9 +113,30 @@ export default function CommitteeManagement() { const [committeeType, setCommitteeType] = React.useState("") const [committeeLogoUrl, setCommitteeLogoUrl] = React.useState("") const [committeeThemeColor, setCommitteeThemeColor] = React.useState("#64748b") + const [layouts, setLayouts] = React.useState([]) + const [layoutId, setLayoutId] = React.useState("") const [submitError, setSubmitError] = React.useState(null) const [submitting, setSubmitting] = React.useState(false) + React.useEffect(() => { + if (!activeConference || !canManageConference) { + setLayouts([]) + setLayoutId("") + return + } + + void apiJson(`/conferences/${activeConference.id}/layouts`) + .then((availableLayouts) => { + setLayouts(availableLayouts) + setLayoutId(availableLayouts[0] ? String(availableLayouts[0].id) : "") + }) + .catch((layoutError) => + setSubmitError( + layoutError instanceof Error ? layoutError.message : "Failed to load layouts" + ) + ) + }, [activeConference, canManageConference]) + async function handleCreateCommittee(event: React.FormEvent) { event.preventDefault() @@ -131,12 +155,14 @@ export default function CommitteeManagement() { committee_type: committeeType || null, logo_url: committeeLogoUrl.trim() || null, theme_color: committeeThemeColor, + layout_id: Number(layoutId), }) setCommitteeName("") setCommitteeAcronym("") setCommitteeType("") setCommitteeLogoUrl("") setCommitteeThemeColor("#64748b") + setLayoutId(layouts[0] ? String(layouts[0].id) : "") setCreateDialogOpen(false) } catch (createError) { setSubmitError( @@ -507,6 +533,21 @@ export default function CommitteeManagement() { placeholder="https://..." />
+
+ + +
{submitError ? (

{submitError}

) : null} @@ -518,7 +559,7 @@ export default function CommitteeManagement() { > Cancelar - diff --git a/frontend/src/components/userDashboard/conferenceMenus/participants/list-allocation.tsx b/frontend/src/components/userDashboard/conferenceMenus/participants/list-allocation.tsx index 39e0782..6f09c77 100644 --- a/frontend/src/components/userDashboard/conferenceMenus/participants/list-allocation.tsx +++ b/frontend/src/components/userDashboard/conferenceMenus/participants/list-allocation.tsx @@ -1,396 +1,61 @@ import * as React from "react" -import { - type ColumnDef, - type ColumnFiltersState, - type SortingState, - type VisibilityState, - flexRender, - getCoreRowModel, - getFilteredRowModel, - getPaginationRowModel, - getSortedRowModel, - useReactTable, -} from "@tanstack/react-table" -import { ArrowUpDown, ChevronDown } from "lucide-react" import { Button } from "@/components/ui/button" -import { Checkbox } from "@/components/ui/checkbox" -import { - DropdownMenu, - DropdownMenuCheckboxItem, - DropdownMenuContent, - DropdownMenuTrigger, -} from "@/components/ui/dropdown-menu" -import { Input } from "@/components/ui/input" -import { - Select, - SelectContent, - SelectItem, - SelectTrigger, - SelectValue, -} from "@/components/ui/select" -import { - Table, - TableBody, - TableCell, - TableHead, - TableHeader, - TableRow, -} from "@/components/ui/table" +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select" +import { useConference } from "@/context/ConferenceContext" +import { apiJson } from "@/lib/api" -type Participant = { - id: string - name: string - email: string - committee: string - representation: string -} - -const committeeOptions = [ - "Security Council", - "UNICEF", - "UNHRC", - "WHO", - "ECOSOC", -] - -const representationOptions = [ - "Brazil", - "United States", - "France", - "Japan", - "Nigeria", - "Mexico", -] - -const initialParticipants: Participant[] = [ - { - id: "33f0e8f6-0cc7-4cc8-a6ff-f4f6bca6a467", - name: "Ana Martins", - email: "ana.martins@example.com", - committee: "Security Council", - representation: "Brazil", - }, - { - id: "88c48914-d4e2-48bf-b4f2-8d0f23f035e9", - name: "Diego Costa", - email: "diego.costa@example.com", - committee: "UNICEF", - representation: "Mexico", - }, - { - id: "8f66643e-11c9-4ee0-adbe-906cefd86f45", - name: "Sara Thompson", - email: "sara.thompson@example.com", - committee: "WHO", - representation: "United States", - }, - { - id: "fd177bd7-1cbc-454b-b7a6-041566a73ed3", - name: "Kenji Sato", - email: "kenji.sato@example.com", - committee: "UNHRC", - representation: "Japan", - }, - { - id: "131902c1-9c6f-4657-b46f-a6f8247693c4", - name: "Claire Dubois", - email: "claire.dubois@example.com", - committee: "ECOSOC", - representation: "France", - }, -] +type Allocation = { email: string; committee_id: number | null; committee_name: string | null; representation_id: number | null; representation_name: string | null } +type Representation = { id: number; name: string; code: string | null } export default function ParticipantListAllocation() { - const [participants, setParticipants] = React.useState(initialParticipants) - const [sorting, setSorting] = React.useState([]) - const [columnFilters, setColumnFilters] = React.useState([]) - const [columnVisibility, setColumnVisibility] = React.useState({}) - const [rowSelection, setRowSelection] = React.useState({}) - - const updateParticipant = React.useCallback( - (id: string, field: "committee" | "representation", value: string) => { - setParticipants((currentParticipants) => - currentParticipants.map((participant) => - participant.id === id ? { ...participant, [field]: value } : participant - ) - ) - }, - [] - ) - - const columns = React.useMemo[]>( - () => [ - { - id: "select", - header: ({ table }) => ( - table.toggleAllPageRowsSelected(!!value)} - aria-label="Selecionar todos" - /> - ), - cell: ({ row }) => ( - row.toggleSelected(!!value)} - aria-label="Selecionar participante" - /> - ), - enableSorting: false, - enableHiding: false, - }, - { - accessorKey: "name", - header: ({ column }) => ( - - ), - }, - { - accessorKey: "email", - header: ({ column }) => ( - - ), - }, - { - accessorKey: "committee", - header: ({ column }) => ( - - ), - cell: ({ row }) => ( - - ), - }, - { - accessorKey: "representation", - header: ({ column }) => ( - - ), - cell: ({ row }) => ( - - ), - }, - ], - [updateParticipant] - ) - - // eslint-disable-next-line react-hooks/incompatible-library -- React Compiler is not enabled; TanStack Table's mutable table API is intentional. - const table = useReactTable({ - data: participants, - columns, - onSortingChange: setSorting, - onColumnFiltersChange: setColumnFilters, - onColumnVisibilityChange: setColumnVisibility, - onRowSelectionChange: setRowSelection, - getCoreRowModel: getCoreRowModel(), - getPaginationRowModel: getPaginationRowModel(), - getSortedRowModel: getSortedRowModel(), - getFilteredRowModel: getFilteredRowModel(), - state: { - sorting, - columnFilters, - columnVisibility, - rowSelection, - }, - }) - - function deleteSelectedParticipants() { - const selectedIds = new Set( - table.getFilteredSelectedRowModel().rows.map((row) => row.original.id) - ) - - if (selectedIds.size === 0) { - return - } - - setParticipants((currentParticipants) => - currentParticipants.filter((participant) => !selectedIds.has(participant.id)) - ) - setRowSelection({}) - } - - const selectedCount = table.getFilteredSelectedRowModel().rows.length - - return ( -
-
-

Listagem e alocação de participantes

-

- Visualize participantes, pesquise por nome e ajuste comitê e representação. -

-
- -
-
- - table.getColumn("name")?.setFilterValue(event.target.value) - } - className="w-full md:max-w-sm" - /> - -
- - - - - - {table - .getAllColumns() - .filter((column) => column.getCanHide()) - .map((column) => ( - column.toggleVisibility(!!value)} - > - {column.id} - - ))} - - - - -
-
- -
-
- - {table.getHeaderGroups().map((headerGroup) => ( - - {headerGroup.headers.map((header) => ( - - {header.isPlaceholder - ? null - : flexRender( - header.column.columnDef.header, - header.getContext() - )} - - ))} - - ))} - - - {table.getRowModel().rows.length > 0 ? ( - table.getRowModel().rows.map((row) => ( - - {row.getVisibleCells().map((cell) => ( - - {flexRender(cell.column.columnDef.cell, cell.getContext())} - - ))} - - )) - ) : ( - - - Nenhum participante encontrado. - - - )} - -
-
- -
-

- {selectedCount} de {table.getFilteredRowModel().rows.length} participante(s) selecionado(s). -

- -
- - -
-
-
-
- ) + const { activeConferenceId, committees } = useConference() + const [allocations, setAllocations] = React.useState([]) + const [choices, setChoices] = React.useState>({}) + const [representations, setRepresentations] = React.useState>({}) + const [error, setError] = React.useState(null) + const [saving, setSaving] = React.useState(null) + + const load = React.useCallback(async () => { + if (!activeConferenceId) return setAllocations([]) + try { + const values = await apiJson(`/conferences/${activeConferenceId}/participants/allocations`) + setAllocations(values) + setChoices(Object.fromEntries(values.map((item) => [item.email, { committeeId: item.committee_id ? String(item.committee_id) : "", representationId: item.representation_id ? String(item.representation_id) : "" }]))) + } catch (reason) { setError(reason instanceof Error ? reason.message : "Não foi possível carregar participantes") } + }, [activeConferenceId]) + + React.useEffect(() => { void load() }, [load]) + + async function chooseCommittee(email: string, committeeId: string) { + setChoices((current) => ({ ...current, [email]: { committeeId, representationId: "" } })) + if (!committeeId || representations[Number(committeeId)]) return + try { + const seats = await apiJson(`/committees/${committeeId}/representations`) + setRepresentations((current) => ({ ...current, [Number(committeeId)]: seats })) + } catch (reason) { setError(reason instanceof Error ? reason.message : "Não foi possível carregar representações") } + } + + async function save(email: string) { + const choice = choices[email] + if (!activeConferenceId || !choice?.committeeId || !choice.representationId) return + setSaving(email); setError(null) + try { + await apiJson(`/conferences/${activeConferenceId}/participants/allocations`, { method: "PUT", body: JSON.stringify({ email, committee_id: Number(choice.committeeId), representation_id: Number(choice.representationId) }) }) + await load() + } catch (reason) { setError(reason instanceof Error ? reason.message : "Não foi possível salvar a alocação") } + finally { setSaving(null) } + } + + return
+

Listagem e alocação de participantes

Participantes adicionados à conferência aparecem aqui para alocação em comitês.

+ {!activeConferenceId ?

Selecione uma conferência.

: <> + {error ?

{error}

: null} +
{allocations.map((allocation) => { + const choice = choices[allocation.email] ?? { committeeId: "", representationId: "" } + const seats = representations[Number(choice.committeeId)] ?? [] + return + })}{allocations.length === 0 ? : null}
E-mailComitêRepresentação
{allocation.email}
Nenhum participante adicionado.
+ } +
} diff --git a/frontend/src/components/userDashboard/conferenceMenus/team/manage-perms-roles.tsx b/frontend/src/components/userDashboard/conferenceMenus/team/manage-perms-roles.tsx index f53d207..3ee150f 100644 --- a/frontend/src/components/userDashboard/conferenceMenus/team/manage-perms-roles.tsx +++ b/frontend/src/components/userDashboard/conferenceMenus/team/manage-perms-roles.tsx @@ -1,378 +1,11 @@ -import * as React from "react" -import { - type ColumnDef, - type ColumnFiltersState, - type SortingState, - type VisibilityState, - flexRender, - getCoreRowModel, - getFilteredRowModel, - getPaginationRowModel, - getSortedRowModel, - useReactTable, -} from "@tanstack/react-table" -import { ArrowUpDown, ChevronDown } from "lucide-react" - -import { Badge } from "@/components/ui/badge" -import { Button } from "@/components/ui/button" -import { Checkbox } from "@/components/ui/checkbox" -import { - DropdownMenu, - DropdownMenuCheckboxItem, - DropdownMenuContent, - DropdownMenuTrigger, -} from "@/components/ui/dropdown-menu" -import { Input } from "@/components/ui/input" -import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table" -import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover" - -type RoleRecord = { - id: string - name: string - description: string - permissions: string[] -} - -const permissionOptions = [ - "View dashboard", - "Manage participants", - "Manage teams", - "Manage committees", - "Manage docs", - "Manage session", -] - -const initialRoles: RoleRecord[] = [ - { - id: "role-1", - name: "Secretary General", - description: "Top-level conference administration and oversight.", - permissions: [ - "View dashboard", - "Manage participants", - "Manage teams", - "Manage committees", - "Manage docs", - "Manage session", - ], - }, - { - id: "role-2", - name: "Director", - description: "Committee leadership and operational setup.", - permissions: ["View dashboard", "Manage participants", "Manage committees", "Manage session"], - }, - { - id: "role-3", - name: "Moderator", - description: "Debate moderation and speaking flow support.", - permissions: ["View dashboard", "Manage session"], - }, - { - id: "role-4", - name: "Press Team", - description: "Media coverage, announcements, and internal reporting.", - permissions: ["View dashboard", "Manage docs"], - }, -] - -function PermissionBadges({ permissions }: { permissions: string[] }) { - return ( -
- {permissions.map((permission) => ( - - {permission} - - ))} -
- ) -} - -function PermissionSelector({ - permissions, - onChange, -}: { - permissions: string[] - onChange: (permissions: string[]) => void -}) { - const [open, setOpen] = React.useState(false) - const [query, setQuery] = React.useState("") - - const visiblePermissions = React.useMemo( - () => - permissionOptions.filter((permission) => - permission.toLowerCase().includes(query.trim().toLowerCase()) - ), - [query] - ) - - function togglePermission(permission: string) { - const nextPermissions = permissions.includes(permission) - ? permissions.filter((item) => item !== permission) - : [...permissions, permission] - - onChange(nextPermissions) - } - - return ( - - - - - -
- setQuery(event.target.value)} - placeholder="Search permissions..." - /> -
-
- {visiblePermissions.length > 0 ? ( -
- {visiblePermissions.map((permission) => { - const isSelected = permissions.includes(permission) - - return ( - - ) - })} -
- ) : ( -

No permissions found.

- )} -
-
-
- ) -} - export default function ManagePermsRoles() { - const [roles, setRoles] = React.useState(initialRoles) - const [sorting, setSorting] = React.useState([]) - const [columnFilters, setColumnFilters] = React.useState([]) - const [columnVisibility, setColumnVisibility] = React.useState({}) - const [rowSelection, setRowSelection] = React.useState({}) - - const updatePermissions = React.useCallback((id: string, permissions: string[]) => { - setRoles((currentRoles) => - currentRoles.map((role) => (role.id === id ? { ...role, permissions } : role)) - ) - }, []) - - const columns = React.useMemo[]>( - () => [ - { - id: "select", - header: ({ table }) => ( - table.toggleAllPageRowsSelected(!!value)} - aria-label="Select all" - /> - ), - cell: ({ row }) => ( - row.toggleSelected(!!value)} - aria-label="Select row" - /> - ), - enableSorting: false, - enableHiding: false, - }, - { - accessorKey: "name", - header: ({ column }) => ( - - ), - cell: ({ row }) => {row.original.name}, - }, - { - accessorKey: "description", - header: ({ column }) => ( - - ), - cell: ({ row }) => {row.original.description}, - }, - { - accessorKey: "permissions", - header: "Permissions", - cell: ({ row }) => ( -
- updatePermissions(row.original.id, nextPermissions)} - /> - -
- ), - }, - ], - [updatePermissions] - ) - - // eslint-disable-next-line react-hooks/incompatible-library -- React Compiler is not enabled; TanStack Table's mutable table API is intentional. - const table = useReactTable({ - data: roles, - columns, - onSortingChange: setSorting, - onColumnFiltersChange: setColumnFilters, - onColumnVisibilityChange: setColumnVisibility, - onRowSelectionChange: setRowSelection, - getCoreRowModel: getCoreRowModel(), - getPaginationRowModel: getPaginationRowModel(), - getSortedRowModel: getSortedRowModel(), - getFilteredRowModel: getFilteredRowModel(), - state: { - sorting, - columnFilters, - columnVisibility, - rowSelection, - }, - }) - - function deleteSelectedRoles() { - const selectedIds = new Set( - table.getFilteredSelectedRowModel().rows.map((row) => row.original.id) - ) - - if (selectedIds.size === 0) { - return - } - - setRoles((currentRoles) => currentRoles.filter((role) => !selectedIds.has(role.id))) - setRowSelection({}) - } - - const selectedCount = table.getFilteredSelectedRowModel().rows.length - return ( -
-
-

Roles and permissions

-

- Review roles and toggle the permissions granted to each role. -

-
- -
-
- table.getColumn("name")?.setFilterValue(event.target.value)} - className="w-full md:max-w-sm" - /> - -
- - - - - - {table - .getAllColumns() - .filter((column) => column.getCanHide()) - .map((column) => ( - column.toggleVisibility(!!value)} - > - {column.id} - - ))} - - - - -
-
- -
- - - {table.getHeaderGroups().map((headerGroup) => ( - - {headerGroup.headers.map((header) => ( - - {header.isPlaceholder - ? null - : flexRender(header.column.columnDef.header, header.getContext())} - - ))} - - ))} - - - {table.getRowModel().rows.length > 0 ? ( - table.getRowModel().rows.map((row) => ( - - {row.getVisibleCells().map((cell) => ( - - {flexRender(cell.column.columnDef.cell, cell.getContext())} - - ))} - - )) - ) : ( - - - No roles found. - - - )} - -
-
- -
-

- {selectedCount} of {table.getFilteredRowModel().rows.length} role(s) selected. -

- -
- - -
-
-
-
+
+

Papéis

+

+ As permissões por papel ainda não estão disponíveis. Por enquanto, os papéis + definidos ao adicionar uma pessoa determinam o acesso da conferência. +

+
) } diff --git a/frontend/src/components/userDashboard/conferenceMenus/team/team-alocate.tsx b/frontend/src/components/userDashboard/conferenceMenus/team/team-alocate.tsx index 406d3dd..9555e14 100644 --- a/frontend/src/components/userDashboard/conferenceMenus/team/team-alocate.tsx +++ b/frontend/src/components/userDashboard/conferenceMenus/team/team-alocate.tsx @@ -1,457 +1,64 @@ import * as React from "react" -import { - type ColumnDef, - type ColumnFiltersState, - type SortingState, - type VisibilityState, - flexRender, - getCoreRowModel, - getFilteredRowModel, - getPaginationRowModel, - getSortedRowModel, - useReactTable, -} from "@tanstack/react-table" -import { ArrowUpDown, ChevronDown } from "lucide-react" -import { Badge } from "@/components/ui/badge" import { Button } from "@/components/ui/button" -import { Checkbox } from "@/components/ui/checkbox" -import { - DropdownMenu, - DropdownMenuCheckboxItem, - DropdownMenuContent, - DropdownMenuLabel, - DropdownMenuSeparator, - DropdownMenuTrigger, -} from "@/components/ui/dropdown-menu" import { Input } from "@/components/ui/input" -import { - Table, - TableBody, - TableCell, - TableHead, - TableHeader, - TableRow, -} from "@/components/ui/table" +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select" +import { useConference } from "@/context/ConferenceContext" +import { apiJson } from "@/lib/api" -type TeamMember = { - id: string - name: string - email: string - roles: string[] - assignments: string[] -} - -const roleOptions = [ - "Secretary General", - "Director", - "Moderator", - "Rapporteur", - "Crisis Staff", - "Press", -] - -const assignmentOptions = [ - "Core Team", - "Logistics", - "Security Council", - "UNICEF", - "UNHRC", - "WHO", -] - -const initialTeamMembers: TeamMember[] = [ - { - id: "a2787617-43d1-4d75-a78e-359b758436fa", - name: "Luisa Almeida", - email: "luisa.almeida@example.com", - roles: ["Director", "Moderator"], - assignments: ["Security Council"], - }, - { - id: "8521bc6a-bd1d-4eee-a802-f98f85a0cf03", - name: "Mateus Silva", - email: "mateus.silva@example.com", - roles: ["Rapporteur"], - assignments: ["UNICEF", "Logistics"], - }, - { - id: "f83ab80f-c4a1-430f-8ac7-c95e3f29fdb6", - name: "Carla Ribeiro", - email: "carla.ribeiro@example.com", - roles: ["Secretary General"], - assignments: ["Core Team"], - }, - { - id: "b90ea379-8673-4094-95a5-ae8ea88a2f9f", - name: "Henrique Santos", - email: "henrique.santos@example.com", - roles: ["Crisis Staff", "Press"], - assignments: ["WHO", "UNHRC"], - }, -] - -function toSortedUniqueList(items: string[]) { - return [...new Set(items)].sort((first, second) => first.localeCompare(second)) -} - -function MultiAssignCell({ - value, - options, - onToggle, - buttonLabel, -}: { - value: string[] - options: string[] - onToggle: (option: string, checked: boolean) => void - buttonLabel: string -}) { - const selected = toSortedUniqueList(value) +type Assignment = { conference_id: number; email: string; role: string; committee_id: number | null } - return ( - - - - - - {buttonLabel} - - {options.map((option) => ( - onToggle(option, !!checked)} - > - {option} - - ))} - - - ) -} - -function AssignmentBadges({ values }: { values: string[] }) { - const sortedValues = toSortedUniqueList(values) - - if (sortedValues.length === 0) { - return Nenhum - } - - return ( -
- {sortedValues.map((value) => ( - - {value} - - ))} -
- ) -} +const roles = ["secretary_general", "director", "moderator", "rapporteur", "crisis_staff", "press", "logistics", "staff", "participant"] export default function TeamAllocate() { - const [teamMembers, setTeamMembers] = React.useState(initialTeamMembers) - const [sorting, setSorting] = React.useState([]) - const [columnFilters, setColumnFilters] = React.useState([]) - const [columnVisibility, setColumnVisibility] = React.useState({}) - const [rowSelection, setRowSelection] = React.useState({}) - - const toggleArrayValue = React.useCallback( - ( - memberId: string, - field: "roles" | "assignments", - option: string, - checked: boolean - ) => { - setTeamMembers((currentMembers) => - currentMembers.map((member) => { - if (member.id !== memberId) { - return member - } - - const currentValues = member[field] - const nextValues = checked - ? [...currentValues, option] - : currentValues.filter((item) => item !== option) - - return { - ...member, - [field]: toSortedUniqueList(nextValues), - } - }) - ) - }, - [] - ) - - const columns = React.useMemo[]>( - () => [ - { - id: "select", - header: ({ table }) => ( - table.toggleAllPageRowsSelected(!!value)} - aria-label="Selecionar todos" - /> - ), - cell: ({ row }) => ( - row.toggleSelected(!!value)} - aria-label="Selecionar membro" - /> - ), - enableSorting: false, - enableHiding: false, - }, - { - accessorKey: "name", - header: ({ column }) => ( - - ), - }, - { - accessorKey: "email", - header: ({ column }) => ( - - ), - }, - { - id: "roles", - accessorFn: (member) => member.roles.join(", "), - header: ({ column }) => ( - - ), - cell: ({ row }) => ( -
- - toggleArrayValue(row.original.id, "roles", option, checked) - } - /> - -
- ), - }, - { - id: "assignments", - accessorFn: (member) => member.assignments.join(", "), - header: ({ column }) => ( - - ), - cell: ({ row }) => ( -
- - toggleArrayValue(row.original.id, "assignments", option, checked) - } - /> - -
- ), - }, - ], - [toggleArrayValue] - ) - - // eslint-disable-next-line react-hooks/incompatible-library -- React Compiler is not enabled; TanStack Table's mutable table API is intentional. - const table = useReactTable({ - data: teamMembers, - columns, - onSortingChange: setSorting, - onColumnFiltersChange: setColumnFilters, - onColumnVisibilityChange: setColumnVisibility, - onRowSelectionChange: setRowSelection, - getCoreRowModel: getCoreRowModel(), - getPaginationRowModel: getPaginationRowModel(), - getSortedRowModel: getSortedRowModel(), - getFilteredRowModel: getFilteredRowModel(), - state: { - sorting, - columnFilters, - columnVisibility, - rowSelection, - }, - }) - - function deleteSelectedMembers() { - const selectedIds = new Set( - table.getFilteredSelectedRowModel().rows.map((row) => row.original.id) - ) - - if (selectedIds.size === 0) { - return + const { activeConferenceId, committees } = useConference() + const [assignments, setAssignments] = React.useState([]) + const [email, setEmail] = React.useState("") + const [role, setRole] = React.useState("participant") + const [committeeId, setCommitteeId] = React.useState("none") + const [error, setError] = React.useState(null) + const [saving, setSaving] = React.useState(false) + + const load = React.useCallback(async () => { + if (!activeConferenceId) return setAssignments([]) + try { + setAssignments(await apiJson(`/conferences/${activeConferenceId}/assignments`)) + } catch (reason) { + setError(reason instanceof Error ? reason.message : "Não foi possível carregar a equipe") } - - setTeamMembers((currentMembers) => - currentMembers.filter((member) => !selectedIds.has(member.id)) - ) - setRowSelection({}) + }, [activeConferenceId]) + + React.useEffect(() => { void load() }, [load]) + + async function submit(event: React.FormEvent) { + event.preventDefault() + if (!activeConferenceId) return + setSaving(true) + setError(null) + try { + await apiJson(`/conferences/${activeConferenceId}/assignments`, { + method: "POST", + body: JSON.stringify({ email, role, committee_id: committeeId === "none" ? null : Number(committeeId) }), + }) + setEmail("") + setCommitteeId("none") + await load() + } catch (reason) { + setError(reason instanceof Error ? reason.message : "Não foi possível adicionar a pessoa") + } finally { setSaving(false) } } - const selectedCount = table.getFilteredSelectedRowModel().rows.length - - return ( -
-
-

Listagem e alocação da equipe

-

- Gerencie membros da equipe, atribua papéis e distribua equipes/comitês. -

-
- -
-
- - table.getColumn("name")?.setFilterValue(event.target.value) - } - className="w-full md:max-w-sm" - /> - -
- - - - - - {table - .getAllColumns() - .filter((column) => column.getCanHide()) - .map((column) => ( - column.toggleVisibility(!!value)} - > - {column.id} - - ))} - - - - -
-
- -
- - - {table.getHeaderGroups().map((headerGroup) => ( - - {headerGroup.headers.map((header) => ( - - {header.isPlaceholder - ? null - : flexRender( - header.column.columnDef.header, - header.getContext() - )} - - ))} - - ))} - - - {table.getRowModel().rows.length > 0 ? ( - table.getRowModel().rows.map((row) => ( - - {row.getVisibleCells().map((cell) => ( - - {flexRender(cell.column.columnDef.cell, cell.getContext())} - - ))} - - )) - ) : ( - - - Nenhum membro encontrado. - - - )} - -
-
- -
-

- {selectedCount} de {table.getFilteredRowModel().rows.length} membro(s) selecionado(s). -

- -
- - -
-
-
-
- ) + return
+

Adicionar e alocar equipe

Adicione por e-mail e atribua um papel real na conferência.

+ {!activeConferenceId ?

Selecione uma conferência.

: <> +
+ + + + +
+ {error ?

{error}

: null} +
{assignments.map((assignment) => )}{assignments.length === 0 ? : null}
E-mailPapelComitê
{assignment.email}{assignment.role}{committees.find((committee) => committee.id === assignment.committee_id)?.name ?? "Toda a conferência"}
Nenhuma pessoa adicionada.
+ } +
} diff --git a/frontend/src/schemas/types.gen.ts b/frontend/src/schemas/types.gen.ts index 8badd1f..20ccc79 100644 --- a/frontend/src/schemas/types.gen.ts +++ b/frontend/src/schemas/types.gen.ts @@ -1,7 +1,7 @@ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { - baseUrl: `${string}://${string}` | (string & {}); + baseUrl: `file://${string}` | (string & {}); }; /** @@ -22,6 +22,28 @@ export type AccessibleCommittee = { representation_id: number | null; }; +/** + * CommitteeAssignmentRead + */ +export type CommitteeAssignmentRead = { + /** + * User Id + */ + user_id: string; + /** + * Committee Id + */ + committee_id: number; + /** + * Role + */ + role: string; + /** + * Representation Id + */ + representation_id: number | null; +}; + /** * CommitteeCreate */ @@ -46,6 +68,10 @@ export type CommitteeCreate = { * Theme Color */ theme_color?: string | null; + /** + * Layout Id + */ + layout_id: number; }; /** @@ -134,6 +160,40 @@ export type ConferenceAccess = { can_manage_conference: boolean; }; +/** + * ConferenceAssignmentCreate + */ +export type ConferenceAssignmentCreate = { + /** + * Email + */ + email: string; + role: ConferenceRole; + /** + * Committee Id + */ + committee_id?: number | null; +}; + +/** + * ConferenceAssignmentRead + */ +export type ConferenceAssignmentRead = { + /** + * Conference Id + */ + conference_id: number; + /** + * Email + */ + email: string; + role: ConferenceRole; + /** + * Committee Id + */ + committee_id: number | null; +}; + /** * ConferenceCreate */ @@ -214,6 +274,27 @@ export type ConferenceRead = { updated_at: string; }; +/** + * ConferenceRole + */ +export const ConferenceRole = { + OWNER: 'owner', + SECRETARY_GENERAL: 'secretary_general', + DIRECTOR: 'director', + MODERATOR: 'moderator', + RAPPORTEUR: 'rapporteur', + CRISIS_STAFF: 'crisis_staff', + PRESS: 'press', + LOGISTICS: 'logistics', + STAFF: 'staff', + PARTICIPANT: 'participant' +} as const; + +/** + * ConferenceRole + */ +export type ConferenceRole = typeof ConferenceRole[keyof typeof ConferenceRole]; + /** * HTTPValidationError */ @@ -224,6 +305,82 @@ export type HttpValidationError = { detail?: Array; }; +/** + * LayoutRead + */ +export type LayoutRead = { + /** + * Id + */ + id: number; + /** + * Name + */ + name: string; +}; + +/** + * ParticipantAllocationCreate + */ +export type ParticipantAllocationCreate = { + /** + * Email + */ + email: string; + /** + * Committee Id + */ + committee_id: number; + /** + * Representation Id + */ + representation_id: number; +}; + +/** + * ParticipantAllocationRead + */ +export type ParticipantAllocationRead = { + /** + * Email + */ + email: string; + /** + * Committee Id + */ + committee_id: number | null; + /** + * Committee Name + */ + committee_name: string | null; + /** + * Representation Id + */ + representation_id: number | null; + /** + * Representation Name + */ + representation_name: string | null; +}; + +/** + * RepresentationRead + */ +export type RepresentationRead = { + /** + * Id + */ + id: number; + /** + * Name + */ + name: string; + /** + * Code + */ + code: string | null; +}; + /** * SessionCreationSchema * @@ -240,6 +397,36 @@ export type SessionCreationSchema = { name?: string | null; }; +/** + * SessionRead + */ +export type SessionRead = { + /** + * Id + */ + id: number; + /** + * Committee Id + */ + committee_id: number; + /** + * Name + */ + name: string | null; + /** + * Status + */ + status: string; + /** + * Started At + */ + started_at: string | null; + /** + * Ended At + */ + ended_at: string | null; +}; + /** * SessionRepresentation */ @@ -1609,6 +1796,38 @@ export type CreateSessionEndpointSessionsPostResponses = { 200: unknown; }; +export type ListCommitteeSessionsEndpointSessionsCommitteeCommitteeIdGetData = { + body?: never; + path: { + /** + * Committee Id + */ + committee_id: number; + }; + query?: never; + url: '/sessions/committee/{committee_id}'; +}; + +export type ListCommitteeSessionsEndpointSessionsCommitteeCommitteeIdGetErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type ListCommitteeSessionsEndpointSessionsCommitteeCommitteeIdGetError = ListCommitteeSessionsEndpointSessionsCommitteeCommitteeIdGetErrors[keyof ListCommitteeSessionsEndpointSessionsCommitteeCommitteeIdGetErrors]; + +export type ListCommitteeSessionsEndpointSessionsCommitteeCommitteeIdGetResponses = { + /** + * Response List Committee Sessions Endpoint Sessions Committee Committee Id Get + * + * Successful Response + */ + 200: Array; +}; + +export type ListCommitteeSessionsEndpointSessionsCommitteeCommitteeIdGetResponse = ListCommitteeSessionsEndpointSessionsCommitteeCommitteeIdGetResponses[keyof ListCommitteeSessionsEndpointSessionsCommitteeCommitteeIdGetResponses]; + export type ActivateSessionEndpointSessionsSessionIdActivatePostData = { body?: never; path: { @@ -1772,6 +1991,162 @@ export type GetConferenceEndpointConferencesConferenceIdGetResponses = { export type GetConferenceEndpointConferencesConferenceIdGetResponse = GetConferenceEndpointConferencesConferenceIdGetResponses[keyof GetConferenceEndpointConferencesConferenceIdGetResponses]; +export type ListAvailableLayoutsEndpointConferencesConferenceIdLayoutsGetData = { + body?: never; + path: { + /** + * Conference Id + */ + conference_id: number; + }; + query?: never; + url: '/conferences/{conference_id}/layouts'; +}; + +export type ListAvailableLayoutsEndpointConferencesConferenceIdLayoutsGetErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type ListAvailableLayoutsEndpointConferencesConferenceIdLayoutsGetError = ListAvailableLayoutsEndpointConferencesConferenceIdLayoutsGetErrors[keyof ListAvailableLayoutsEndpointConferencesConferenceIdLayoutsGetErrors]; + +export type ListAvailableLayoutsEndpointConferencesConferenceIdLayoutsGetResponses = { + /** + * Response List Available Layouts Endpoint Conferences Conference Id Layouts Get + * + * Successful Response + */ + 200: Array; +}; + +export type ListAvailableLayoutsEndpointConferencesConferenceIdLayoutsGetResponse = ListAvailableLayoutsEndpointConferencesConferenceIdLayoutsGetResponses[keyof ListAvailableLayoutsEndpointConferencesConferenceIdLayoutsGetResponses]; + +export type ListConferenceAssignmentsEndpointConferencesConferenceIdAssignmentsGetData = { + body?: never; + path: { + /** + * Conference Id + */ + conference_id: number; + }; + query?: never; + url: '/conferences/{conference_id}/assignments'; +}; + +export type ListConferenceAssignmentsEndpointConferencesConferenceIdAssignmentsGetErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type ListConferenceAssignmentsEndpointConferencesConferenceIdAssignmentsGetError = ListConferenceAssignmentsEndpointConferencesConferenceIdAssignmentsGetErrors[keyof ListConferenceAssignmentsEndpointConferencesConferenceIdAssignmentsGetErrors]; + +export type ListConferenceAssignmentsEndpointConferencesConferenceIdAssignmentsGetResponses = { + /** + * Response List Conference Assignments Endpoint Conferences Conference Id Assignments Get + * + * Successful Response + */ + 200: Array; +}; + +export type ListConferenceAssignmentsEndpointConferencesConferenceIdAssignmentsGetResponse = ListConferenceAssignmentsEndpointConferencesConferenceIdAssignmentsGetResponses[keyof ListConferenceAssignmentsEndpointConferencesConferenceIdAssignmentsGetResponses]; + +export type CreateConferenceAssignmentEndpointConferencesConferenceIdAssignmentsPostData = { + body: ConferenceAssignmentCreate; + path: { + /** + * Conference Id + */ + conference_id: number; + }; + query?: never; + url: '/conferences/{conference_id}/assignments'; +}; + +export type CreateConferenceAssignmentEndpointConferencesConferenceIdAssignmentsPostErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type CreateConferenceAssignmentEndpointConferencesConferenceIdAssignmentsPostError = CreateConferenceAssignmentEndpointConferencesConferenceIdAssignmentsPostErrors[keyof CreateConferenceAssignmentEndpointConferencesConferenceIdAssignmentsPostErrors]; + +export type CreateConferenceAssignmentEndpointConferencesConferenceIdAssignmentsPostResponses = { + /** + * Successful Response + */ + 201: ConferenceAssignmentRead; +}; + +export type CreateConferenceAssignmentEndpointConferencesConferenceIdAssignmentsPostResponse = CreateConferenceAssignmentEndpointConferencesConferenceIdAssignmentsPostResponses[keyof CreateConferenceAssignmentEndpointConferencesConferenceIdAssignmentsPostResponses]; + +export type ListParticipantAllocationsEndpointConferencesConferenceIdParticipantsAllocationsGetData = { + body?: never; + path: { + /** + * Conference Id + */ + conference_id: number; + }; + query?: never; + url: '/conferences/{conference_id}/participants/allocations'; +}; + +export type ListParticipantAllocationsEndpointConferencesConferenceIdParticipantsAllocationsGetErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type ListParticipantAllocationsEndpointConferencesConferenceIdParticipantsAllocationsGetError = ListParticipantAllocationsEndpointConferencesConferenceIdParticipantsAllocationsGetErrors[keyof ListParticipantAllocationsEndpointConferencesConferenceIdParticipantsAllocationsGetErrors]; + +export type ListParticipantAllocationsEndpointConferencesConferenceIdParticipantsAllocationsGetResponses = { + /** + * Response List Participant Allocations Endpoint Conferences Conference Id Participants Allocations Get + * + * Successful Response + */ + 200: Array; +}; + +export type ListParticipantAllocationsEndpointConferencesConferenceIdParticipantsAllocationsGetResponse = ListParticipantAllocationsEndpointConferencesConferenceIdParticipantsAllocationsGetResponses[keyof ListParticipantAllocationsEndpointConferencesConferenceIdParticipantsAllocationsGetResponses]; + +export type AllocateParticipantEndpointConferencesConferenceIdParticipantsAllocationsPutData = { + body: ParticipantAllocationCreate; + path: { + /** + * Conference Id + */ + conference_id: number; + }; + query?: never; + url: '/conferences/{conference_id}/participants/allocations'; +}; + +export type AllocateParticipantEndpointConferencesConferenceIdParticipantsAllocationsPutErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type AllocateParticipantEndpointConferencesConferenceIdParticipantsAllocationsPutError = AllocateParticipantEndpointConferencesConferenceIdParticipantsAllocationsPutErrors[keyof AllocateParticipantEndpointConferencesConferenceIdParticipantsAllocationsPutErrors]; + +export type AllocateParticipantEndpointConferencesConferenceIdParticipantsAllocationsPutResponses = { + /** + * Successful Response + */ + 200: CommitteeAssignmentRead; +}; + +export type AllocateParticipantEndpointConferencesConferenceIdParticipantsAllocationsPutResponse = AllocateParticipantEndpointConferencesConferenceIdParticipantsAllocationsPutResponses[keyof AllocateParticipantEndpointConferencesConferenceIdParticipantsAllocationsPutResponses]; + export type ListCommitteesEndpointConferencesConferenceIdCommitteesGetData = { body?: never; path: { @@ -1863,3 +2238,35 @@ export type GetCommitteeEndpointCommitteesCommitteeIdGetResponses = { }; export type GetCommitteeEndpointCommitteesCommitteeIdGetResponse = GetCommitteeEndpointCommitteesCommitteeIdGetResponses[keyof GetCommitteeEndpointCommitteesCommitteeIdGetResponses]; + +export type ListCommitteeRepresentationsEndpointCommitteesCommitteeIdRepresentationsGetData = { + body?: never; + path: { + /** + * Committee Id + */ + committee_id: number; + }; + query?: never; + url: '/committees/{committee_id}/representations'; +}; + +export type ListCommitteeRepresentationsEndpointCommitteesCommitteeIdRepresentationsGetErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type ListCommitteeRepresentationsEndpointCommitteesCommitteeIdRepresentationsGetError = ListCommitteeRepresentationsEndpointCommitteesCommitteeIdRepresentationsGetErrors[keyof ListCommitteeRepresentationsEndpointCommitteesCommitteeIdRepresentationsGetErrors]; + +export type ListCommitteeRepresentationsEndpointCommitteesCommitteeIdRepresentationsGetResponses = { + /** + * Response List Committee Representations Endpoint Committees Committee Id Representations Get + * + * Successful Response + */ + 200: Array; +}; + +export type ListCommitteeRepresentationsEndpointCommitteesCommitteeIdRepresentationsGetResponse = ListCommitteeRepresentationsEndpointCommitteesCommitteeIdRepresentationsGetResponses[keyof ListCommitteeRepresentationsEndpointCommitteesCommitteeIdRepresentationsGetResponses]; diff --git a/supabase/migrations/20260905100000_add_conference_participant_role.sql b/supabase/migrations/20260905100000_add_conference_participant_role.sql new file mode 100644 index 0000000..02d7651 --- /dev/null +++ b/supabase/migrations/20260905100000_add_conference_participant_role.sql @@ -0,0 +1 @@ +alter type conference_role add value if not exists 'participant'; From d07d2ece52e10942dece83eaff4a125b01158b0f Mon Sep 17 00:00:00 2001 From: wate <110754234+r0liveir@users.noreply.github.com> Date: Sat, 5 Sep 2026 22:58:35 -0300 Subject: [PATCH 16/19] Enable joining active sessions Co-authored-by: Codex --- .../userDashboard/committeeMenus/committee-sessions.tsx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/frontend/src/components/userDashboard/committeeMenus/committee-sessions.tsx b/frontend/src/components/userDashboard/committeeMenus/committee-sessions.tsx index 81ef91d..c578b31 100644 --- a/frontend/src/components/userDashboard/committeeMenus/committee-sessions.tsx +++ b/frontend/src/components/userDashboard/committeeMenus/committee-sessions.tsx @@ -5,11 +5,13 @@ import { Button } from "@/components/ui/button" import { Input } from "@/components/ui/input" import { useConference } from "@/context/ConferenceContext" import { apiFetch, apiJson } from "@/lib/api" +import { useNavigate } from "react-router-dom" type CommitteeSession = { id: number; committee_id: number; name: string | null; status: string; started_at: string | null; ended_at: string | null } export default function CommitteeSessions() { const { activeCommittee, activeCommitteeAccess } = useConference() + const navigate = useNavigate() const [sessions, setSessions] = React.useState([]) const [name, setName] = React.useState("") const [error, setError] = React.useState(null) @@ -51,7 +53,7 @@ export default function CommitteeSessions() { {!activeCommittee ?

Selecione um comitê.

: <> {canManage ?
setName(event.target.value)} placeholder="Nome da sessão (opcional)" />
: null} {error ?

{error}

: null} -
{sessions.map((session) =>

{session.name || `Sessão ${session.id}`}

{session.status}
{canManage && session.status === "planned" ? : null}
)}{sessions.length === 0 ?

Nenhuma sessão criada.

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

{session.name || `Sessão ${session.id}`}

{session.status}
{canManage && session.status === "planned" ? : null}
)}{sessions.length === 0 ?

Nenhuma sessão criada.

: null}
} } From 79a5edebbd493a1d2445150dd548dcfe56194942 Mon Sep 17 00:00:00 2001 From: wate <110754234+r0liveir@users.noreply.github.com> Date: Sun, 6 Sep 2026 00:44:25 -0300 Subject: [PATCH 17/19] Refine conference setup flow Co-authored-by: Codex --- backend/app/conference/repository.py | 5 +- backend/app/conference/schemas.py | 1 - backend/app/conference/service.py | 14 ++-- frontend/src/App.tsx | 3 +- frontend/src/components/auth/login-form.tsx | 10 +-- frontend/src/components/homepage/navbar.tsx | 9 +-- .../participants/list-allocation.tsx | 40 +++++++---- .../conferenceMenus/team/team-alocate.tsx | 11 ++- frontend/src/context/ConferenceContext.tsx | 5 +- frontend/src/schemas/types.gen.ts | 6 +- .../20260719224327_create_initial_tables.sql | 3 +- ...100000_add_conference_participant_role.sql | 1 - supabase/seed.sql | 67 ------------------- 13 files changed, 53 insertions(+), 122 deletions(-) delete mode 100644 supabase/migrations/20260905100000_add_conference_participant_role.sql diff --git a/backend/app/conference/repository.py b/backend/app/conference/repository.py index fbbeaf5..8a5f222 100644 --- a/backend/app/conference/repository.py +++ b/backend/app/conference/repository.py @@ -132,6 +132,7 @@ async def list_conference_assignments( FROM public.conference_assignments ca JOIN auth.users u ON u.id = ca.user_id WHERE ca.conference_id = :conference_id + AND ca.committee_id IS NULL ORDER BY ca.created_at DESC, ca.id DESC """), {"conference_id": conference_id}, @@ -191,7 +192,9 @@ async def list_participant_allocations( LEFT JOIN public.committees cm ON cm.id = cma.committee_id AND cm.conference_id = ca.conference_id LEFT JOIN public.representations r ON r.id = cma.representation_id - WHERE ca.conference_id = :conference_id AND ca.role = 'participant' + WHERE ca.conference_id = :conference_id + AND ca.role = 'participant' + AND ca.committee_id IS NULL AND (cm.id IS NOT NULL OR cma.committee_id IS NULL) ORDER BY u.email, cm.id """), diff --git a/backend/app/conference/schemas.py b/backend/app/conference/schemas.py index 7f57b78..3dfa6b6 100644 --- a/backend/app/conference/schemas.py +++ b/backend/app/conference/schemas.py @@ -61,7 +61,6 @@ class CommitteeAssignmentRead(BaseModel): class ConferenceAssignmentCreate(BaseModel): email: str = Field(min_length=3, max_length=320) role: ConferenceRole - committee_id: int | None = None class ConferenceAssignmentRead(BaseModel): diff --git a/backend/app/conference/service.py b/backend/app/conference/service.py index c46ab81..ad02d16 100644 --- a/backend/app/conference/service.py +++ b/backend/app/conference/service.py @@ -124,24 +124,20 @@ async def create_conference_assignment( ) assignee_id = await repository.get_user_id_by_email(session=session, email=data.email) if assignee_id is None: - raise BadRequest("User email was not found") - if data.committee_id is not None and not await repository.is_committee_in_conference( - session=session, conference_id=conference_id, committee_id=data.committee_id - ): - raise BadRequest("Committee does not belong to this conference") + raise BadRequest("User cannot be added to this conference") await repository.create_conference_assignment( session=session, conference_id=conference_id, user_id=assignee_id, role=data.role, - committee_id=data.committee_id, + committee_id=None, ) await session.commit() return { "conference_id": conference_id, "email": data.email, "role": data.role, - "committee_id": data.committee_id, + "committee_id": None, } @@ -179,11 +175,11 @@ async def allocate_participant( ) participant_id = await repository.get_user_id_by_email(session=session, email=data.email) if participant_id is None: - raise BadRequest("User email was not found") + raise BadRequest("User cannot be allocated in this conference") if not await repository.is_conference_participant( session=session, conference_id=conference_id, user_id=participant_id ): - raise BadRequest("User is not a participant in this conference") + raise BadRequest("User cannot be allocated in this conference") if not await repository.is_committee_in_conference( session=session, conference_id=conference_id, committee_id=data.committee_id ): diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index f0beb4d..312371b 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -7,7 +7,6 @@ import Home from './pages/Home'; import Pricing from './pages/Info Pages/Pricing'; import OurTeam from './pages/Info Pages/OurTeam'; import ContactUs from './pages/Info Pages/Contact-us'; -import SignupPage from './pages/Signup'; import UserDash from './pages/UserDashboard'; import DashHome from './components/userDashboard/dash-home.tsx'; import CreateCommittee from './pages/CreateCommittee'; @@ -53,7 +52,7 @@ function App() { } /> } /> } /> - } /> + } /> }> } /> } /> diff --git a/frontend/src/components/auth/login-form.tsx b/frontend/src/components/auth/login-form.tsx index 88b4e12..7eaeac7 100644 --- a/frontend/src/components/auth/login-form.tsx +++ b/frontend/src/components/auth/login-form.tsx @@ -10,7 +10,6 @@ import { FieldSeparator, } from "@/components/ui/field" import { Input } from "@/components/ui/input" -import { Link } from "react-router-dom" import { supabase } from "@/lib/supabaseClient" export function LoginForm({ @@ -110,14 +109,11 @@ export function LoginForm({ Or continue with - - Don't have an account?{" "} - - Sign up - + Criação de contas temporariamente indisponível. diff --git a/frontend/src/components/homepage/navbar.tsx b/frontend/src/components/homepage/navbar.tsx index 92aa2a1..44a5e13 100644 --- a/frontend/src/components/homepage/navbar.tsx +++ b/frontend/src/components/homepage/navbar.tsx @@ -108,12 +108,7 @@ export default function Navbar() {
- - + @@ -140,4 +135,4 @@ function ListItem({ ) -} \ No newline at end of file +} diff --git a/frontend/src/components/userDashboard/conferenceMenus/participants/list-allocation.tsx b/frontend/src/components/userDashboard/conferenceMenus/participants/list-allocation.tsx index 6f09c77..c3f8ebb 100644 --- a/frontend/src/components/userDashboard/conferenceMenus/participants/list-allocation.tsx +++ b/frontend/src/components/userDashboard/conferenceMenus/participants/list-allocation.tsx @@ -7,14 +7,15 @@ import { apiJson } from "@/lib/api" type Allocation = { email: string; committee_id: number | null; committee_name: string | null; representation_id: number | null; representation_name: string | null } type Representation = { id: number; name: string; code: string | null } +type Choice = { committeeId: string; representationId: string } export default function ParticipantListAllocation() { const { activeConferenceId, committees } = useConference() const [allocations, setAllocations] = React.useState([]) - const [choices, setChoices] = React.useState>({}) + const [choices, setChoices] = React.useState>({}) const [representations, setRepresentations] = React.useState>({}) const [error, setError] = React.useState(null) - const [saving, setSaving] = React.useState(null) + const [saving, setSaving] = React.useState(false) const load = React.useCallback(async () => { if (!activeConferenceId) return setAllocations([]) @@ -22,6 +23,9 @@ export default function ParticipantListAllocation() { const values = await apiJson(`/conferences/${activeConferenceId}/participants/allocations`) setAllocations(values) setChoices(Object.fromEntries(values.map((item) => [item.email, { committeeId: item.committee_id ? String(item.committee_id) : "", representationId: item.representation_id ? String(item.representation_id) : "" }]))) + const committeeIds = [...new Set(values.flatMap((item) => item.committee_id ? [item.committee_id] : []))] + const seats = await Promise.all(committeeIds.map(async (committeeId) => [committeeId, await apiJson(`/committees/${committeeId}/representations`)] as const)) + setRepresentations(Object.fromEntries(seats)) } catch (reason) { setError(reason instanceof Error ? reason.message : "Não foi possível carregar participantes") } }, [activeConferenceId]) @@ -36,26 +40,38 @@ export default function ParticipantListAllocation() { } catch (reason) { setError(reason instanceof Error ? reason.message : "Não foi possível carregar representações") } } - async function save(email: string) { - const choice = choices[email] - if (!activeConferenceId || !choice?.committeeId || !choice.representationId) return - setSaving(email); setError(null) + const pendingAllocations = allocations.filter((allocation) => { + const choice = choices[allocation.email] + return choice?.committeeId && choice.representationId && ( + choice.committeeId !== String(allocation.committee_id ?? "") || + choice.representationId !== String(allocation.representation_id ?? "") + ) + }) + + async function saveAll() { + if (!activeConferenceId || pendingAllocations.length === 0) return + setSaving(true); setError(null) try { - await apiJson(`/conferences/${activeConferenceId}/participants/allocations`, { method: "PUT", body: JSON.stringify({ email, committee_id: Number(choice.committeeId), representation_id: Number(choice.representationId) }) }) + await Promise.all(pendingAllocations.map((allocation) => { + const choice = choices[allocation.email] + if (!choice) return Promise.resolve() + return apiJson(`/conferences/${activeConferenceId}/participants/allocations`, { method: "PUT", body: JSON.stringify({ email: allocation.email, committee_id: Number(choice.committeeId), representation_id: Number(choice.representationId) }) }) + })) await load() - } catch (reason) { setError(reason instanceof Error ? reason.message : "Não foi possível salvar a alocação") } - finally { setSaving(null) } + } catch (reason) { setError(reason instanceof Error ? reason.message : "Não foi possível salvar as alocações") } + finally { setSaving(false) } } return

Listagem e alocação de participantes

Participantes adicionados à conferência aparecem aqui para alocação em comitês.

{!activeConferenceId ?

Selecione uma conferência.

: <> {error ?

{error}

: null} -
{allocations.map((allocation) => { +
+
E-mailComitêRepresentação
{allocations.map((allocation) => { const choice = choices[allocation.email] ?? { committeeId: "", representationId: "" } const seats = representations[Number(choice.committeeId)] ?? [] - return - })}{allocations.length === 0 ? : null}
E-mailComitêRepresentação
{allocation.email}
Nenhum participante adicionado.
+ return {allocation.email} + })}{allocations.length === 0 ? Nenhum participante adicionado. : null}
} } diff --git a/frontend/src/components/userDashboard/conferenceMenus/team/team-alocate.tsx b/frontend/src/components/userDashboard/conferenceMenus/team/team-alocate.tsx index 9555e14..889ca03 100644 --- a/frontend/src/components/userDashboard/conferenceMenus/team/team-alocate.tsx +++ b/frontend/src/components/userDashboard/conferenceMenus/team/team-alocate.tsx @@ -11,11 +11,10 @@ type Assignment = { conference_id: number; email: string; role: string; committe const roles = ["secretary_general", "director", "moderator", "rapporteur", "crisis_staff", "press", "logistics", "staff", "participant"] export default function TeamAllocate() { - const { activeConferenceId, committees } = useConference() + const { activeConferenceId } = useConference() const [assignments, setAssignments] = React.useState([]) const [email, setEmail] = React.useState("") const [role, setRole] = React.useState("participant") - const [committeeId, setCommitteeId] = React.useState("none") const [error, setError] = React.useState(null) const [saving, setSaving] = React.useState(false) @@ -38,10 +37,9 @@ export default function TeamAllocate() { try { await apiJson(`/conferences/${activeConferenceId}/assignments`, { method: "POST", - body: JSON.stringify({ email, role, committee_id: committeeId === "none" ? null : Number(committeeId) }), + body: JSON.stringify({ email, role }), }) setEmail("") - setCommitteeId("none") await load() } catch (reason) { setError(reason instanceof Error ? reason.message : "Não foi possível adicionar a pessoa") @@ -49,16 +47,15 @@ export default function TeamAllocate() { } return
-

Adicionar e alocar equipe

Adicione por e-mail e atribua um papel real na conferência.

+

Adicionar pessoas à conferência

Adicione por e-mail e atribua um papel na conferência. Participantes são alocados em comitês na tela de participantes.

{!activeConferenceId ?

Selecione uma conferência.

: <>
-
{error ?

{error}

: null} -
{assignments.map((assignment) => )}{assignments.length === 0 ? : null}
E-mailPapelComitê
{assignment.email}{assignment.role}{committees.find((committee) => committee.id === assignment.committee_id)?.name ?? "Toda a conferência"}
Nenhuma pessoa adicionada.
+
{assignments.map((assignment) => )}{assignments.length === 0 ? : null}
E-mailPapel
{assignment.email}{assignment.role}
Nenhuma pessoa adicionada.
}
} diff --git a/frontend/src/context/ConferenceContext.tsx b/frontend/src/context/ConferenceContext.tsx index 4831b84..5a19d04 100644 --- a/frontend/src/context/ConferenceContext.tsx +++ b/frontend/src/context/ConferenceContext.tsx @@ -168,9 +168,10 @@ export function ConferenceProvider({ children }: { children: ReactNode }) { } ) - setCommittees((currentCommittees) => [...currentCommittees, committee]) + await refreshCommittees() + setActiveCommitteeIdState(committee.id) return committee - }, [activeConferenceId]) + }, [activeConferenceId, refreshCommittees]) useEffect(() => { if (authLoading) { diff --git a/frontend/src/schemas/types.gen.ts b/frontend/src/schemas/types.gen.ts index 20ccc79..ab7eeca 100644 --- a/frontend/src/schemas/types.gen.ts +++ b/frontend/src/schemas/types.gen.ts @@ -1,7 +1,7 @@ // This file is auto-generated by @hey-api/openapi-ts export type ClientOptions = { - baseUrl: `file://${string}` | (string & {}); + baseUrl: 'http://backend:8000' | (string & {}); }; /** @@ -169,10 +169,6 @@ export type ConferenceAssignmentCreate = { */ email: string; role: ConferenceRole; - /** - * Committee Id - */ - committee_id?: number | null; }; /** diff --git a/supabase/migrations/20260719224327_create_initial_tables.sql b/supabase/migrations/20260719224327_create_initial_tables.sql index c8c103e..d1e72e9 100644 --- a/supabase/migrations/20260719224327_create_initial_tables.sql +++ b/supabase/migrations/20260719224327_create_initial_tables.sql @@ -10,7 +10,8 @@ create type conference_role as enum ( 'crisis_staff', 'press', 'logistics', - 'staff' + 'staff', + 'participant' ); ------------------------------- diff --git a/supabase/migrations/20260905100000_add_conference_participant_role.sql b/supabase/migrations/20260905100000_add_conference_participant_role.sql deleted file mode 100644 index 02d7651..0000000 --- a/supabase/migrations/20260905100000_add_conference_participant_role.sql +++ /dev/null @@ -1 +0,0 @@ -alter type conference_role add value if not exists 'participant'; diff --git a/supabase/seed.sql b/supabase/seed.sql index f7c1165..ae881d3 100644 --- a/supabase/seed.sql +++ b/supabase/seed.sql @@ -1,32 +1,3 @@ --- default conference - -insert into public.conferences - (name, status, owner_id) -values - ('I WebMUN', 'active', '11111111-1111-1111-1111-111111111111'); - -insert into public.committees - (conference_id, name, acronym, committee_type, theme_color, status) -values - ( - (select id from conferences where name = 'I WebMUN'), - 'CSNU', - 'CSNU', - 'Traditional', - '#1d4ed8', - 'planned' - ); - -insert into public.conference_assignments - (conference_id, user_id, role, committee_id) -values - ( - (select id from conferences where name = 'I WebMUN'), - '11111111-1111-1111-1111-111111111111', - 'owner', - null - ); - insert into public.representations (name, code, identifier) values ('Albânia', 'al', 'al'), ('Alemanha', 'de', 'de'), @@ -79,41 +50,3 @@ values ((select id from layouts where name = 'Standard 21 Room'), (select id from representations where code = 'ch'), '3-8'), ((select id from layouts where name = 'Standard 21 Room'), (select id from representations where code = 'tw'), '1-1'), ((select id from layouts where name = 'Standard 21 Room'), (select id from representations where code = 'tr'), '2-6'); - -insert into committee_seats - (committee_id, representation_id, seat_label) -values - (1, (select id from representations where code = 'al'), '3-4'), - (1, (select id from representations where code = 'de'), '2-5'), - (1, (select id from representations where code = 'au'), '2-4'), - (1, (select id from representations where code = 'br'), '3-2'), - (1, (select id from representations where code = 'cn'), '1-6'), - (1, (select id from representations where code = 'kr'), '3-5'), - (1, (select id from representations where code = 'ae'), '3-9'), - (1, (select id from representations where code = 'us'), '1-2'), - (1, (select id from representations where code = 'ph'), '2-2'), - (1, (select id from representations where code = 'fr'), '1-4'), - (1, (select id from representations where code = 'gt'), '3-7'), - (1, (select id from representations where code = 'hk'), '3-1'), - (1, (select id from representations where code = 'in'), '3-6'), - (1, (select id from representations where code = 'id'), '3-3'), - (1, (select id from representations where code = 'jp'), '2-1'), - (1, (select id from representations where code = 'my'), '2-3'), - (1, (select id from representations where code = 'gb'), '1-3'), - (1, (select id from representations where code = 'ru'), '1-5'), - (1, (select id from representations where code = 'ch'), '3-8'), - (1, (select id from representations where code = 'tw'), '1-1'), - (1, (select id from representations where code = 'tr'), '2-6'); - -insert into public.committee_assignments - (user_id, committee_id, role, representation_id) -values - ('11111111-1111-1111-1111-111111111111', 1, 'chair', null), - ('22222222-2222-2222-2222-222222222222', 1, 'delegate', (select id from representations where code = 'al')), - ('33333333-3333-3333-3333-333333333333', 1, 'delegate', (select id from representations where code = 'de')), - ('44444444-4444-4444-4444-444444444444', 1, 'delegate', (select id from representations where code = 'br')); - -insert into public.sessions - (committee_id) -values - (1); From 52596670fdda894385b46f2c897b750c357f2543 Mon Sep 17 00:00:00 2001 From: wate <110754234+r0liveir@users.noreply.github.com> Date: Sun, 6 Sep 2026 00:44:47 -0300 Subject: [PATCH 18/19] Remove legacy committee creation page Co-authored-by: Codex --- frontend/src/App.tsx | 2 - frontend/src/pages/CreateCommittee.tsx | 53 -------------------------- 2 files changed, 55 deletions(-) delete mode 100644 frontend/src/pages/CreateCommittee.tsx diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 312371b..af1875e 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -9,7 +9,6 @@ import OurTeam from './pages/Info Pages/OurTeam'; import ContactUs from './pages/Info Pages/Contact-us'; import UserDash from './pages/UserDashboard'; import DashHome from './components/userDashboard/dash-home.tsx'; -import CreateCommittee from './pages/CreateCommittee'; import BasicInfo from './components/userDashboard/conferenceMenus/about/conference-basic-info.tsx'; @@ -70,7 +69,6 @@ function App() { } /> } /> - } /> } /> diff --git a/frontend/src/pages/CreateCommittee.tsx b/frontend/src/pages/CreateCommittee.tsx deleted file mode 100644 index dcf3b78..0000000 --- a/frontend/src/pages/CreateCommittee.tsx +++ /dev/null @@ -1,53 +0,0 @@ -import { Button } from "@/components/ui/button" - -export default function SessionPage() { - const payload = { - session_id: 0, - name: "CSNU", - delegations: [ - { seat: "3-4", name: "Albânia", code: "al" }, - { seat: "2-5", name: "Alemanha", code: "de" }, - { seat: "2-4", name: "Austrália", code: "au" }, - { seat: "3-2", name: "Brasil", code: "br" }, - { seat: "1-6", name: "China", code: "cn" }, - { seat: "3-5", name: "Coreia do Sul", code: "kr" }, - { seat: "3-9", name: "Emirados Árabes", code: "ae" }, - { seat: "1-2", name: "Estados Unidos", code: "us" }, - { seat: "2-2", name: "Filipinas", code: "ph" }, - { seat: "1-4", name: "França", code: "fr" }, - { seat: "3-7", name: "Guatemala", code: "gt" }, - { seat: "3-1", name: "Hong Kong", code: "hk" }, - { seat: "3-6", name: "Índia", code: "in" }, - { seat: "3-3", name: "Indonésia", code: "id" }, - { seat: "2-1", name: "Japão", code: "jp" }, - { seat: "2-3", name: "Malásia", code: "my" }, - { seat: "1-3", name: "Reino Unido", code: "gb" }, - { seat: "1-5", name: "Rússia", code: "ru" }, - { seat: "3-8", name: "Suíça", code: "ch" }, - { seat: "1-1", name: "Taiwan", code: "tw" }, - { seat: "2-6", name: "Turquia", code: "tr" }, - ], - } - - return ( -
-

Create a new Committee

- - -
- ) -} From cc0c54d832ef135a2f914f410b39c6c00828c886 Mon Sep 17 00:00:00 2001 From: wate <110754234+r0liveir@users.noreply.github.com> Date: Sun, 6 Sep 2026 00:57:09 -0300 Subject: [PATCH 19/19] feat: improve dashboard access flow Co-authored-by: Codex --- frontend/src/App.tsx | 2 +- frontend/src/components/auth/login-form.tsx | 2 +- .../userDashboard/conference-menus-list.tsx | 6 ++++++ .../conferenceMenus/conference-overview.tsx | 16 ++++++++++------ .../src/components/userDashboard/dash-home.tsx | 8 ++++++-- frontend/src/pages/Login_page.tsx | 7 ++++++- supabase/config.toml | 2 +- 7 files changed, 31 insertions(+), 12 deletions(-) diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index af1875e..d94ecd6 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -10,9 +10,9 @@ import ContactUs from './pages/Info Pages/Contact-us'; import UserDash from './pages/UserDashboard'; import DashHome from './components/userDashboard/dash-home.tsx'; import BasicInfo from './components/userDashboard/conferenceMenus/about/conference-basic-info.tsx'; +import ConferenceOverview from './components/userDashboard/conferenceMenus/conference-overview'; -import ConferenceOverview from './components/userDashboard/conferenceMenus/conference-overview'; import Enrollment from './components/userDashboard/conferenceMenus/participants/enrollment'; import ParticipantListAllocation from './components/userDashboard/conferenceMenus/participants/list-allocation'; import PresenceCertificates from './components/userDashboard/conferenceMenus/participants/presence-certificates'; diff --git a/frontend/src/components/auth/login-form.tsx b/frontend/src/components/auth/login-form.tsx index 7eaeac7..7c5c84b 100644 --- a/frontend/src/components/auth/login-form.tsx +++ b/frontend/src/components/auth/login-form.tsx @@ -113,7 +113,7 @@ export function LoginForm({ Login with Google (em breve) - Criação de contas temporariamente indisponível. + Não tem uma conta? diff --git a/frontend/src/components/userDashboard/conference-menus-list.tsx b/frontend/src/components/userDashboard/conference-menus-list.tsx index 2573f2e..ed0bd7e 100644 --- a/frontend/src/components/userDashboard/conference-menus-list.tsx +++ b/frontend/src/components/userDashboard/conference-menus-list.tsx @@ -15,6 +15,7 @@ import { } from "@/components/ui/sidebar" import { Link, useLocation } from "react-router-dom" import { ChevronRightIcon, LayoutDashboard, Users, Network, Info, Gavel } from "lucide-react" +import { useConference } from "@/context/ConferenceContext" @@ -22,6 +23,11 @@ import { ChevronRightIcon, LayoutDashboard, Users, Network, Info, Gavel } from " export function ConferenceMenus() { const { pathname } = useLocation() + const { activeConference } = useConference() + + if (!activeConference) { + return null + } return ( diff --git a/frontend/src/components/userDashboard/conferenceMenus/conference-overview.tsx b/frontend/src/components/userDashboard/conferenceMenus/conference-overview.tsx index 6cf708c..77096ec 100644 --- a/frontend/src/components/userDashboard/conferenceMenus/conference-overview.tsx +++ b/frontend/src/components/userDashboard/conferenceMenus/conference-overview.tsx @@ -1,13 +1,17 @@ +import { useConference } from "@/context/ConferenceContext" +import { Navigate } from "react-router-dom" +export default function ConferenceOverview() { + const { activeConference } = useConference() + if (!activeConference) { + return + } -export default function ConferenceOverview() { return (
-

This is the Conference Overview Page

-

- Such Info! much knowledge. -

+

{activeConference.name}

+

Visão geral da conferência.

) -} \ No newline at end of file +} diff --git a/frontend/src/components/userDashboard/dash-home.tsx b/frontend/src/components/userDashboard/dash-home.tsx index f1d509f..dc17b46 100644 --- a/frontend/src/components/userDashboard/dash-home.tsx +++ b/frontend/src/components/userDashboard/dash-home.tsx @@ -1,13 +1,17 @@ +import { useAuth } from "@/context/AuthContext" export default function DashHome() { + const { user } = useAuth() + const name = user?.user_metadata.name ?? user?.email?.split("@")[0] ?? "pessoa" + return (
-

Bem-vindo ao WebMun [USERNAME]!

+

Bem-vindo ao WebMun, {name}!

Explore as funcionalidades do WebMun e gerencie sua conferência de forma eficiente.

) -} \ No newline at end of file +} diff --git a/frontend/src/pages/Login_page.tsx b/frontend/src/pages/Login_page.tsx index 2384e14..1dae93b 100644 --- a/frontend/src/pages/Login_page.tsx +++ b/frontend/src/pages/Login_page.tsx @@ -1,7 +1,12 @@ -import { Link } from "react-router-dom" +import { Link, Navigate } from "react-router-dom" import { LoginForm } from "@/components/auth/login-form" +import { useAuth } from "@/context/AuthContext" export default function Auth() { + const { loading, token } = useAuth() + + if (loading) return

Loading session…

+ if (token) return return (
diff --git a/supabase/config.toml b/supabase/config.toml index 7ba3e61..c09ed5a 100644 --- a/supabase/config.toml +++ b/supabase/config.toml @@ -68,7 +68,7 @@ schema_paths = [] enabled = true # Specifies an ordered list of seed files to load during db reset. # Supports glob patterns relative to supabase directory: "./seeds/*.sql" -sql_paths = ["./users.sql", "./seed.sql"] +sql_paths = ["./seed.sql"] [db.network_restrictions] # Enable management of network restrictions.