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 d37ee65..61a427f 100644 --- a/backend/app/access/repository.py +++ b/backend/app/access/repository.py @@ -1,12 +1,11 @@ from uuid import UUID -from sqlalchemy import text +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 async def get_committee_assignment( session: AsyncSession, user_id: UUID, committee_id: int ) -> CommitteeAssignment | None: @@ -69,3 +68,109 @@ 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 + + +async def list_accessible_conference_committees( + session: AsyncSession, + *, + conference_id: int, + user_id: UUID, +) -> list[AccessibleCommittee]: + query = text(""" + 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, + }, + ) + + 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 864dfb0..2dca730 100644 --- a/backend/app/access/schemas.py +++ b/backend/app/access/schemas.py @@ -6,3 +6,22 @@ class SessionRepresentation(BaseModel): role: enums.SessionRoles representation_id: int | None + + +class CommitteeScopedConferenceRole(BaseModel): + committee_id: int + 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 91c28f6..eb52b3f 100644 --- a/backend/app/access/service.py +++ b/backend/app/access/service.py @@ -4,9 +4,34 @@ from sqlalchemy.ext.asyncio import AsyncSession from app.access.models import CommitteeAssignment +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 -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, + list_accessible_conference_committees, +) + +CONFERENCE_MANAGEMENT_ROLES = { + "owner", + "secretary_general", +} + +SESSION_ACCESS_GRANTING_CONFERENCE_ROLES = { + "owner", + "secretary_general", + "director", + "moderator", +} async def resolve_committee_assignment( @@ -62,3 +87,100 @@ 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 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 + ] + 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, + ) + ] + + 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 + ), + ) + + +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/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/__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..3253a22 --- /dev/null +++ b/backend/app/conference/enums.py @@ -0,0 +1,20 @@ +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" + PARTICIPANT = "participant" + + +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..5f5c849 --- /dev/null +++ b/backend/app/conference/models.py @@ -0,0 +1,61 @@ +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 + acronym: str | None + committee_type: str | None + logo_url: str | None + theme_color: str | None + 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 + + +@dataclass(frozen=True) +class ConferenceAssignment: + conference_id: int + 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 new file mode 100644 index 0000000..8a5f222 --- /dev/null +++ b/backend/app/conference/repository.py @@ -0,0 +1,477 @@ +from uuid import UUID + +from sqlalchemy import text +from sqlalchemy.ext.asyncio import AsyncSession + +from .models import Committee, CommitteeAssignment, Conference, ConferenceAssignment, Layout, Representation +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"], + 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"], + ) + + +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"], + ) + + +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"], + ) + + +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, + *, + 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_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 + AND ca.committee_id IS NULL + 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 ca.committee_id IS NULL + 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, + *, + 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 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, + *, + conference_id: int, + data: CommitteeCreate, +) -> Committee | None: + query = text(""" + INSERT INTO public.committees + (conference_id, name, acronym, committee_type, logo_url, theme_color) + VALUES + ( + :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, + "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 + + +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, + *, + conference_id: int, +) -> list[Committee]: + query = text(""" + 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 + """) + + 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.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 + 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..3dfa6b6 --- /dev/null +++ b/backend/app/conference/schemas.py @@ -0,0 +1,95 @@ +from datetime import datetime +from uuid import UUID + +from pydantic import BaseModel, Field + +from .enums import ConferenceRole + + +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) + 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}$") + layout_id: int = Field(gt=0) + + +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 + + +class CommitteeAssignmentRead(BaseModel): + user_id: UUID + committee_id: int + role: str + representation_id: int | None + + +class ConferenceAssignmentCreate(BaseModel): + email: str = Field(min_length=3, max_length=320) + role: ConferenceRole + + +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 new file mode 100644 index 0000000..ad02d16 --- /dev/null +++ b/backend/app/conference/service.py @@ -0,0 +1,277 @@ +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, ConferenceAssignment, Layout, Representation +from .schemas import CommitteeCreate, ConferenceAssignmentCreate, ConferenceCreate, ParticipantAllocationCreate + + +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, + ) + + 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 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=None, + ) + await session.commit() + return { + "conference_id": conference_id, + "email": data.email, + "role": data.role, + "committee_id": None, + } + + +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 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 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 + ): + 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, + *, + 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..5eb7846 --- /dev/null +++ b/backend/app/conference/views.py @@ -0,0 +1,195 @@ +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, + CommitteeAssignmentRead, + CommitteeRead, + ConferenceAssignmentCreate, + ConferenceAssignmentRead, + ConferenceCreate, + ConferenceRead, + ParticipantAllocationCreate, + ParticipantAllocationRead, + LayoutRead, + RepresentationRead, +) + +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.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, +) +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__) + + +@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/main.py b/backend/app/main.py index e6e6a3b..5188c19 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -2,12 +2,13 @@ from contextlib import asynccontextmanager, suppress 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 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 @@ -72,6 +73,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, @@ -85,9 +92,9 @@ 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"]) def custom_openapi(): 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 f7fbcdd..b1495b8 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, @@ -43,18 +42,13 @@ EventMessage, EventRejectedMessage, SessionCreationSchema, + SessionRead, StateSnapshotMessage, ) 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, @@ -75,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, @@ -101,7 +108,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/backend/app/tests/access/test_service.py b/backend/app/tests/access/test_service.py index a7a342a..4b6a65d 100644 --- a/backend/app/tests/access/test_service.py +++ b/backend/app/tests/access/test_service.py @@ -1,12 +1,31 @@ +from dataclasses import dataclass from uuid import uuid4 import pytest -from app.access.models import CommitteeAssignment -from app.access.service import resolve_committee_assignment, verify_user_role +from app.access.models import AccessibleCommittee, CommitteeAssignment +from app.access.service import ( + get_my_conference_access, + resolve_committee_assignment, + verify_can_manage_conference, + verify_conference_assignment_can_grant_session_access, + verify_user_role, +) 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): @@ -92,3 +111,143 @@ 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 + ) + + +@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 [] + + async def no_accessible_committees(*_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, + ) + 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 + + +@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), + ] + + 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, + ) + monkeypatch.setattr( + "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/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..b5ff2b0 --- /dev/null +++ b/backend/app/tests/conference/test_service.py @@ -0,0 +1,242 @@ +from datetime import datetime +from uuid import uuid4 + +import pytest + +from app.conference.models import ( + Committee, + CommitteeAssignment, + Conference, + Layout, +) +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", + acronym="CSNU", + committee_type="Traditional", + logo_url=None, + theme_color="#1d4ed8", + 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", layout_id=1), + ) + + +@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() + + 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", layout_id=1), + ) + + 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 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/.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= diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 40e66a3..d94ecd6 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -7,14 +7,12 @@ 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'; 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'; @@ -53,8 +51,8 @@ function App() { } /> } /> } /> - } /> - }> + } /> + }> } /> } /> } /> @@ -71,7 +69,6 @@ function App() { } /> } /> - } /> } /> diff --git a/frontend/src/components/auth/login-form.tsx b/frontend/src/components/auth/login-form.tsx index 88b4e12..7c5c84b 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 - + Não tem uma conta? 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/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/committee-menus-list.tsx b/frontend/src/components/userDashboard/committee-menus-list.tsx index 63e7aa2..30616a3 100644 --- a/frontend/src/components/userDashboard/committee-menus-list.tsx +++ b/frontend/src/components/userDashboard/committee-menus-list.tsx @@ -3,6 +3,13 @@ import { CollapsibleContent, CollapsibleTrigger, } from "@/components/ui/collapsible" +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuLabel, + DropdownMenuTrigger, +} from "@/components/ui/dropdown-menu" import { SidebarGroup, SidebarGroupLabel, @@ -12,9 +19,11 @@ import { SidebarMenuSub, SidebarMenuSubButton, SidebarMenuSubItem, + useSidebar, } from "@/components/ui/sidebar" +import { useConference } from "@/context/ConferenceContext" import { Link, useLocation } from "react-router-dom" -import { ChevronRightIcon, Info } from "lucide-react" +import { ChevronsUpDownIcon, ChevronRightIcon, Info } from "lucide-react" @@ -22,21 +31,72 @@ import { ChevronRightIcon, Info } from "lucide-react" export function CommitteeMenus() { const { pathname } = useLocation() + const { isMobile } = useSidebar() + const { + accessibleCommittees, + activeCommittee, + conferenceAccess, + setActiveCommitteeId, + } = useConference() + const accessRoleByCommitteeId = new Map( + conferenceAccess?.accessible_committees.map((committee) => [ + committee.committee_id, + committee.role, + ]) ?? [] + ) + + if (accessibleCommittees.length === 0) { + return null + } return ( Comites + + + + + + {activeCommittee?.name ?? "Selecionar comite"} + + + + + + Comites acessiveis + + {accessibleCommittees.map((committee) => ( + setActiveCommitteeId(committee.id)} + className="gap-2 p-2" + > + {committee.name} + + {accessRoleByCommitteeId.get(committee.id) ?? ""} + + + ))} + + + + - [Committee Name] + {activeCommittee?.name ?? "Comite"} diff --git a/frontend/src/components/userDashboard/committeeMenus/committee-sessions.tsx b/frontend/src/components/userDashboard/committeeMenus/committee-sessions.tsx index 7a66778..c578b31 100644 --- a/frontend/src/components/userDashboard/committeeMenus/committee-sessions.tsx +++ b/frontend/src/components/userDashboard/committeeMenus/committee-sessions.tsx @@ -1,96 +1,59 @@ +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, apiJson } from "@/lib/api" +import { useNavigate } from "react-router-dom" -type CommitteeSession = { - id: string - sessionNumber: number - startTime: string - endTime: string - joinHref?: string -} +type CommitteeSession = { id: number; committee_id: number; name: string | null; status: string; started_at: string | null; ended_at: string | null } -type CommitteeSessionsProps = { - sessions?: CommitteeSession[] - onJoin?: (session: CommitteeSession) => void -} +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) + const [creating, setCreating] = React.useState(false) + const [activating, setActivating] = React.useState(null) + const canManage = activeCommitteeAccess?.role === "chair" -const defaultSessions: CommitteeSession[] = [ - { - id: "session-1", - sessionNumber: 1, - startTime: "09:00", - endTime: "10:30", - joinHref: "/session/1", - }, - { - id: "session-2", - sessionNumber: 2, - startTime: "11:00", - endTime: "12:30", - joinHref: "/session/2", - }, - { - id: "session-3", - sessionNumber: 3, - startTime: "14:00", - endTime: "15:30", - joinHref: "/session/3", - }, -] + 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]) -export default function CommitteeSessions({ - sessions = defaultSessions, - onJoin, -}: CommitteeSessionsProps) { - return ( -
-
-

Committee Sessions

-

- View session time windows and join active sessions. -

-
+ React.useEffect(() => { void load() }, [load]) - - {sessions.map((session) => ( - - - - - Session {session.sessionNumber} - - - Start: {session.startTime} | End: {session.endTime} - - + 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) } + } - - {session.joinHref ? ( - - ) : ( - - )} - - - - ))} - -
- ) -} \ No newline at end of file + 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..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 ( @@ -121,7 +127,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 e149e8b..5e7764d 100644 --- a/frontend/src/components/userDashboard/conferenceMenus/committee-managemant.tsx +++ b/frontend/src/components/userDashboard/conferenceMenus/committee-managemant.tsx @@ -11,8 +11,12 @@ 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 { apiJson } from "@/lib/api" +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 { @@ -47,17 +51,13 @@ import { TableRow, } from "@/components/ui/table" -type Committee = { - id: string - name: string - logo: string - colour: string - acronym: string - type: string +function formatDate(value: string) { + return new Intl.DateTimeFormat("pt-BR", { + dateStyle: "short", + timeStyle: "short", + }).format(new Date(value)) } -type CommitteeDraft = Omit - const committeeTypes = [ "Traditional", "WIMUN", @@ -67,69 +67,27 @@ const committeeTypes = [ "Specialized", ] -function createLogoDataUrl(acronym: string, colour: string) { - const safeAcronym = acronym.trim() || "CM" - const safeColour = colour || "#64748b" +type Layout = { id: number; name: string } - return `data:image/svg+xml;charset=UTF-8,${encodeURIComponent( - ` - - ${safeAcronym} - ` - )}` +function fallback(value: string | null | undefined) { + return value?.trim() || "N/A" } -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) +function CommitteeLogoPreview({ committee }: { committee: CommitteeRead }) { + const label = committee.acronym?.trim() || committee.name.slice(0, 2).toUpperCase() + const themeColor = committee.theme_color ?? "#64748b" return (
- {isImageLogo ? ( - {displayLabel} + {committee.logo_url ? ( + {label} ) : (
- {displayLabel} + {label}
)}
@@ -137,82 +95,85 @@ function CommitteeLogoPreview({ logo, colour }: { logo: string; colour: string } } 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] - ) + 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 [layouts, setLayouts] = React.useState([]) + const [layoutId, setLayoutId] = React.useState("") + const [submitError, setSubmitError] = React.useState(null) + const [submitting, setSubmitting] = React.useState(false) React.useEffect(() => { - if (!editingCommittee) { - setDraftCommittee(null) + if (!activeConference || !canManageConference) { + setLayouts([]) + setLayoutId("") return } - setDraftCommittee({ - name: editingCommittee.name, - logo: editingCommittee.logo, - colour: editingCommittee.colour, - acronym: editingCommittee.acronym, - type: editingCommittee.type, - }) - }, [editingCommittee]) - - function openEditor(id: string) { - setEditingCommitteeId(id) - } - - function closeEditor() { - setEditingCommitteeId(null) - } - - async function handleLogoFileChange(file: File | null) { - if (!file) { - return - } - - const nextLogo = await new Promise((resolve, reject) => { - const reader = new FileReader() + 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]) - reader.onload = () => resolve(String(reader.result ?? "")) - reader.onerror = () => reject(reader.error) - reader.readAsDataURL(file) - }) + async function handleCreateCommittee(event: React.FormEvent) { + event.preventDefault() - setDraftCommittee((currentDraft) => - currentDraft ? { ...currentDraft, logo: nextLogo } : currentDraft - ) - } - - function saveDraftCommittee() { - if (!editingCommittee || !draftCommittee) { + const trimmedName = committeeName.trim() + if (!trimmedName) { return } - setCommittees((currentCommittees) => - currentCommittees.map((committee) => - committee.id === editingCommittee.id - ? { - ...committee, - ...draftCommittee, - logo: - draftCommittee.logo || - createLogoDataUrl(draftCommittee.acronym, draftCommittee.colour), - } - : committee + setSubmitting(true) + setSubmitError(null) + + try { + await createCommittee({ + name: trimmedName, + acronym: committeeAcronym.trim() || null, + 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( + 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 +211,98 @@ export default function CommitteeManagement() { cell: ({ row }) => {row.original.name}, }, { - accessorKey: "logo", + accessorKey: "logo_url", header: "Logo", cell: ({ row }) => (
- - Imagem do comitê + + + {row.original.logo_url ? "Imagem do comitê" : "N/A"} +
), }, { - accessorKey: "colour", + accessorKey: "acronym", header: ({ column }) => ( ), cell: ({ row }) => ( -
-
+ {fallback(row.original.acronym)} ), }, { - accessorKey: "acronym", + accessorKey: "committee_type", header: ({ column }) => ( ), - cell: ({ row }) => {row.original.acronym}, + cell: ({ row }) => {fallback(row.original.committee_type)}, }, { - accessorKey: "type", + accessorKey: "theme_color", header: ({ column }) => ( + ), + cell: ({ row }) => ( +
+ {row.original.theme_color ? ( +
+ ), + }, + { + accessorKey: "status", + header: "Status", + cell: ({ row }) => {row.original.status}, + }, + { + accessorKey: "created_at", + header: ({ column }) => ( + ), - cell: ({ row }) => {row.original.type}, + cell: ({ row }) => ( + + {formatDate(row.original.created_at)} + + ), }, { id: "actions", header: "Ações", - cell: ({ row }) => ( - ), @@ -340,33 +331,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 +436,7 @@ export default function CommitteeManagement() { ) : ( - Nenhum comitê encontrado. + {loading ? "Carregando comitês..." : "Nenhum comitê encontrado."} )} @@ -481,112 +470,100 @@ 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. + Configure os metadados básicos usados na dashboard da conferência. - - {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} - - - - - +
+ + + 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}

+ ) : null} + + + + +
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/conferenceMenus/participants/list-allocation.tsx b/frontend/src/components/userDashboard/conferenceMenus/participants/list-allocation.tsx index 39e0782..c3f8ebb 100644 --- a/frontend/src/components/userDashboard/conferenceMenus/participants/list-allocation.tsx +++ b/frontend/src/components/userDashboard/conferenceMenus/participants/list-allocation.tsx @@ -1,396 +1,77 @@ 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 } +type Choice = { committeeId: string; representationId: string } 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(false) + + 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) : "" }]))) + 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]) + + 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") } + } + + 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 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 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) => { + 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..889ca03 100644 --- a/frontend/src/components/userDashboard/conferenceMenus/team/team-alocate.tsx +++ b/frontend/src/components/userDashboard/conferenceMenus/team/team-alocate.tsx @@ -1,457 +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 { 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 } = useConference() + const [assignments, setAssignments] = React.useState([]) + const [email, setEmail] = React.useState("") + const [role, setRole] = React.useState("participant") + 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 }), + }) + setEmail("") + 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 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-mailPapel
{assignment.email}{assignment.role}
Nenhuma pessoa adicionada.
+ } +
} 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/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} + + + + +
+
+
) } 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 diff --git a/frontend/src/context/ConferenceContext.tsx b/frontend/src/context/ConferenceContext.tsx new file mode 100644 index 0000000..5a19d04 --- /dev/null +++ b/frontend/src/context/ConferenceContext.tsx @@ -0,0 +1,247 @@ +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 { + AccessibleCommittee, + CommitteeCreate, + CommitteeRead, + ConferenceAccess, + ConferenceCreate, + ConferenceRead, +} from "@/schemas/types.gen" + +type ConferenceContextType = { + conferences: ConferenceRead[] + activeConference: ConferenceRead | null + activeConferenceId: number | null + committees: CommitteeRead[] + accessibleCommittees: CommitteeRead[] + activeCommittee: CommitteeRead | null + activeCommitteeId: number | null + activeCommitteeAccess: AccessibleCommittee | null + conferenceAccess: ConferenceAccess | null + canManageConference: boolean + loading: boolean + error: string | null + setActiveConferenceId: (conferenceId: number) => void + setActiveCommitteeId: (committeeId: 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 [activeCommitteeId, setActiveCommitteeIdState] = 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 activeCommitteeAccess = useMemo( + () => + conferenceAccess?.accessible_committees.find( + (committee) => committee.committee_id === activeCommitteeId + ) ?? null, + [activeCommitteeId, conferenceAccess] + ) + + const accessibleCommittees = useMemo(() => { + const accessibleIds = new Set( + conferenceAccess?.accessible_committees.map((committee) => committee.committee_id) ?? [] + ) + + return committees.filter((committee) => accessibleIds.has(committee.id)) + }, [committees, conferenceAccess]) + + const activeCommittee = useMemo( + () => committees.find((committee) => committee.id === activeCommitteeId) ?? null, + [activeCommitteeId, committees] + ) + + const setActiveConferenceId = useCallback((conferenceId: number) => { + setActiveConferenceIdState(conferenceId) + setActiveCommitteeIdState(null) + }, []) + + const setActiveCommitteeId = useCallback((committeeId: number) => { + setActiveCommitteeIdState(committeeId) + }, []) + + const refreshConferences = useCallback(async () => { + if (!token) { + setConferences([]) + setActiveConferenceIdState(null) + setActiveCommitteeIdState(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) + setActiveCommitteeIdState(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) + setActiveCommitteeIdState((currentId) => { + const accessibleIds = new Set( + nextAccess.accessible_committees.map((committee) => committee.committee_id) + ) + + if (currentId && accessibleIds.has(currentId)) { + return currentId + } + + return nextCommittees.find((committee) => accessibleIds.has(committee.id))?.id ?? null + }) + } 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), + } + ) + + await refreshCommittees() + setActiveCommitteeIdState(committee.id) + return committee + }, [activeConferenceId, refreshCommittees]) + + useEffect(() => { + if (authLoading) { + 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]) + + const value = useMemo( + () => ({ + conferences, + activeConference, + activeConferenceId, + committees, + accessibleCommittees, + activeCommittee, + activeCommitteeId, + activeCommitteeAccess, + conferenceAccess, + canManageConference: conferenceAccess?.can_manage_conference ?? false, + loading, + error, + setActiveConferenceId, + setActiveCommitteeId, + refreshConferences, + refreshCommittees, + createConference, + createCommittee, + }), + [ + conferences, + activeConference, + activeConferenceId, + committees, + accessibleCommittees, + activeCommittee, + activeCommitteeId, + activeCommitteeAccess, + conferenceAccess, + loading, + error, + setActiveConferenceId, + setActiveCommitteeId, + 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/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/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( - - - + + + + + , ) diff --git a/frontend/src/pages/CreateCommittee.tsx b/frontend/src/pages/CreateCommittee.tsx deleted file mode 100644 index ec46086..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

- - -
- ) -} \ 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/frontend/src/schemas/types.gen.ts b/frontend/src/schemas/types.gen.ts index 329d2af..ab7eeca 100644 --- a/frontend/src/schemas/types.gen.ts +++ b/frontend/src/schemas/types.gen.ts @@ -4,6 +4,293 @@ export type ClientOptions = { baseUrl: 'http://backend:8000' | (string & {}); }; +/** + * AccessibleCommittee + */ +export type AccessibleCommittee = { + /** + * Committee Id + */ + committee_id: number; + /** + * Role + */ + role: string; + /** + * Representation Id + */ + 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 + */ +export type CommitteeCreate = { + /** + * Name + */ + name: string; + /** + * Acronym + */ + acronym?: string | null; + /** + * Committee Type + */ + committee_type?: string | null; + /** + * Logo Url + */ + logo_url?: string | null; + /** + * Theme Color + */ + theme_color?: string | null; + /** + * Layout Id + */ + layout_id: number; +}; + +/** + * CommitteeRead + */ +export type CommitteeRead = { + /** + * Id + */ + id: number; + /** + * Conference Id + */ + conference_id: number; + /** + * Name + */ + name: string; + /** + * Acronym + */ + acronym: string | null; + /** + * Committee Type + */ + committee_type: string | null; + /** + * Logo Url + */ + logo_url: string | null; + /** + * Theme Color + */ + theme_color: string | null; + /** + * 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; + /** + * Accessible Committees + */ + accessible_committees: Array; + /** + * Can Manage Conference + */ + can_manage_conference: boolean; +}; + +/** + * ConferenceAssignmentCreate + */ +export type ConferenceAssignmentCreate = { + /** + * Email + */ + email: string; + role: ConferenceRole; +}; + +/** + * ConferenceAssignmentRead + */ +export type ConferenceAssignmentRead = { + /** + * Conference Id + */ + conference_id: number; + /** + * Email + */ + email: string; + role: ConferenceRole; + /** + * Committee Id + */ + committee_id: number | null; +}; + +/** + * 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; +}; + +/** + * 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 */ @@ -14,6 +301,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 * @@ -30,6 +393,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 */ @@ -1209,10 +1602,15 @@ export type RollCallContext = { */ export type SessionEffect = { type: SessionEffectType; - data?: VotingContext; -}; - -/** + /** + * Data + */ + data?: { + [key: string]: unknown; + }; +}; + +/** * SessionEffectType */ export const SessionEffectType = { VOTE_CLOSED: 'Vote Closed' } as const; @@ -1357,44 +1755,76 @@ 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 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: { /** @@ -1403,26 +1833,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 +1883,386 @@ 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 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: { + /** + * 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]; + +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/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. diff --git a/supabase/migrations/20260719224327_create_initial_tables.sql b/supabase/migrations/20260719224327_create_initial_tables.sql index ce34ead..d1e72e9 100644 --- a/supabase/migrations/20260719224327_create_initial_tables.sql +++ b/supabase/migrations/20260719224327_create_initial_tables.sql @@ -1,68 +1,152 @@ 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', + 'participant' +); + +------------------------------- +-- 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' + acronym varchar(16), + committee_type varchar(64), + logo_url varchar(1000), + theme_color varchar(7), + 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), + constraint committees_theme_color_hex check ( + theme_color is null or theme_color ~ '^#[0-9A-Fa-f]{6}$' + ) ); --- 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 +154,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..ae881d3 100644 --- a/supabase/seed.sql +++ b/supabase/seed.sql @@ -1,15 +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, status) -values - ((select id from conferences where name = 'I WebMUN'), 'CSNU', 'planned'); - insert into public.representations (name, code, identifier) values ('Albânia', 'al', 'al'), ('Alemanha', 'de', 'de'), @@ -62,42 +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); -