# RIT Event Management System (EMS) - Project Overview & Site Map

This document provides a comprehensive technical overview of the RIT Event Management System (EMS). It details the core goals, features, technology stack, database architecture, directory layout, and a functional site map. 

This file is structured specifically to allow developers and agentic AI systems to decode and understand the system perfectly.

---

## 1. Project Goal & Context

The **RIT Event Management System (EMS)** is a unified platform developed for Rajalakshmi Institute of Technology (RIT) to manage, propose, audit, approve, and automate institutional events. Events range from academic workshops and guest lectures to placement drives, cultural events, and sports activities.

The system addresses critical administrative bottlenecks such as:
1. **Venue Conflicts:** Preventing overlapping bookings for key venues (e.g., auditoriums, seminar halls, computer labs).
2. **Multi-tier Approvals:** Routing proposals through HODs and the Principal based on roles, departments, and event categories.
3. **Semester Scheduling:** Transitioning calendar plans from one semester to the next with minimal manual effort.
4. **Data Aggregation:** Importing bulk event plans directly from external sources (such as Google Form spreadsheet responses).

---

## 2. Technology Stack

### Backend
* **Core Backend Service:** Firebase (Firestore Database, Firebase Authentication)
* **API Architecture:** Serverless client-side interceptor via `firebaseBackend.ts` which intercepts `/api/*` requests in the browser and processes them directly against Firestore collections.
* **Database:** Cloud Firestore (Collections: `ems_users`, `ems_events`, `ems_notes`, `ems_classes`)
* **Security:** Checked via frontend role verification and Firestore Security Rules.

### Frontend
* **Core Framework:** React 19, TypeScript, Vite
* **Routing & State:** Component/Context state driving dynamic view rendering in a single-page application (SPA) shell
* **Styling:** Tailwind CSS, custom Vanilla CSS tokens, modern glassmorphism aesthetic
* **Animations:** Framer Motion (for smooth layout and viewport transitions)
* **Icons:** Lucide React
* **Utility Libraries:**
  * `date-fns` for robust date comparisons and timeline layouts
  * `xlsx` for parsing spreadsheet files (.xlsx/.csv) in-browser

---

## 3. Database Schema & Architecture

The system contains four principal Firestore collections.

### A. User Entity (`users`)
Holds institutional account profiles, login credentials, permissions, and roles.
* `id` (Long, PK): Auto-incremented identifier.
* `email` (String, Unique): Institutional email (e.g., `@rit.edu` or `@ritindia.edu`).
* `password` (String): BCrypt hashed passcode.
* `fullName` (String): User's display name.
* `role` (String): Access levels: `ADMIN`, `PRINCIPAL`, `HOD`, `FACULTY`, `PLACEMENT`.
* `department` (String): E.g., `CSE`, `AI&ML`, `ECE`, `H&S Dept`, etc.
* `isClubCoordinator` (Boolean): Grants authorization to manage student club events.
* `isPlacementStaff` (Boolean): Grants authority to propose overriding placement activities.
* `isClassIncharge` (Boolean): Grants class representative dashboard view.
* `classStrength` (Integer): Total student count for incharge class.
* `inchargeClass` / `inchargeBatch` / `inchargeSection` (String): Targeted class details.
* `assignedClubs` (ElementCollection): List of student clubs the user is permitted to coordinate.

### B. Event Entity (`events`)
Models event proposals, scheduling, requirements, and life-cycles.
* `id` (Long, PK)
* `title` (String, Nullable=false)
* `description` (Text)
* `startDate` / `endDate` (LocalDateTime)
* `location` (String): Maps to standard venues (e.g., `GB 4th floor auditorium`, `Wozniak Auditorium`).
* `category` (String): Categories dictate processing logic: `ACADEMIC`, `CLUB`, `PLACEMENT`, `SPORTS`, `INSTITUTIONAL`.
* `type` (String): E.g., `Workshop`, `Seminar`, `Guest Lecture`, `Competition`.
* `institution` (String): `RIT` or `RSB`.
* `department` (String)
* `academicYears` (ElementCollection): List of targeted academic batches (e.g., `1st Year`, `2nd Year`).
* `targetedSections` (ElementCollection): Targeted sections (e.g., `A`, `B`).
* `status` (String): `REQUESTED` (Pending HoD review), `PENDING_PR` (Pending Principal approval), `APPROVED` (Active scheduled event), `COMPLETED` (Past event), `CANCELLED`, `HOD_REJECTED`, `PRINCIPAL_REJECTED`.
* `guestName` / `guestSocialProfile` (String)
* `requirements` (ElementCollection): Mandatory resources (e.g., `Mementos`, `Projector`, `Lunch`, `Wi-Fi`).
* `budget` (Double)
* `hasRegistrationFee` (Boolean) / `registrationFee` (Double)
* `sponsors` (ElementCollection)
* `proposer` (ManyToOne -> `User`)
* `rejectionReason` (Text)
* `groupRequestId` (String): Identifier tying grouped recurring requests.

### C. ClassMapping Entity (`classes`)
Used for maintaining class information and batch promotions.
* `id` (Long, PK)
* `institution` (String): E.g., `RIT`, `RSB`.
* `department` (String)
* `academicYear` (String): E.g., `1st Year`, `2nd Year`, etc.
* `sections` (ElementCollection): List of section names associated with this mapping.
* `status` (String): Defaults to `Ready`.

### D. InstitutionalNote Entity (`institutional_notes`)
Used for pinning warnings, reminders, or notifications on the main calendar.
* `id` (Long, PK)
* `content` (String, Nullable=false)
* `targetDate` (LocalDate)
* `authorName` / `authorEmail` (String)
* `createdAt` (LocalDateTime)

---

## 4. Key Workflows & Backend API Endpoints

### A. Authentication
1. **Login Flow:** User submits credentials to `POST /api/auth/login`.
2. **Matching:** The system performs database lookup and BCrypt check.
3. **Response:** A JSON representation of the logged-in User is returned (stored in `localStorage` as `ems_user`).

### B. Event Proposal & Approval Chain
1. **Proposal submission:** Submits to `POST /api/events/propose`.
2. **Real-time Conflict Audit:** The backend executes `findConflictingEvents()` matching `location`, `institution`, and date overlaps against `APPROVED` events.
   * **Placement Overriding:** If the new proposal is a `PLACEMENT` event and `cancelConflicting` is `true`, the system sets conflicting events' status to `CANCELLED` and writes a displacement reason.
   * **General Conflict:** If a conflict exists and it isn't an overridden placement, a `409 Conflict` status is returned with overlap logs.
3. **Workflow Routing:**
   * Proposer is **Principal** -> Auto-approved (`APPROVED`).
   * Proposer is **HoD**, or event is **Club/Placement/Institutional** -> Sent straight to Principal (`PENDING_PR`).
   * Proposer is **Faculty** -> Sent to HoD (`REQUESTED`).
4. **HoD Action (`POST /api/events/{id}/approve`):** Sets status to `PENDING_PR` (Principal Desk).
5. **Principal Action (`POST /api/events/{id}/approve`):** Sets status to `APPROVED`.
6. **Rejections (`POST /api/events/{id}/reject`):** Updates status to `HOD_REJECTED` or `PRINCIPAL_REJECTED` and embeds a mandatory `reason`.

### C. Class Promotions
* `POST /api/classes/promote?institution=RIT`
* Promotes all class mappings for the specified institution:
  * `1st Year` -> `2nd Year`
  * `2nd Year` -> `3rd Year`
  * `3rd Year` -> `4th Year`
  * `4th Year` mappings are deleted (graduated).

---

## 5. Directory Layout & Architecture

### Frontend Layout
```text
frontend/src/
├── App.tsx                     # Main Router shell
├── main.tsx                    # React Entry mount
├── App.css                     # Framework and styling additions
├── index.css                   # Core Tailwind and glassmorphism styling definitions
├── assets/                     # Logos, background images
├── context/
│   └── AuthContext.tsx         # Session controller (localStorage wrapper)
├── lib/
│   ├── config.ts               # API Base URL config (http://localhost:8081)
│   └── utils.ts                # Class-name merging helper (cn)
├── pages/
│   └── LoginPage.tsx           # Institutional Portal interface
└── components/
    ├── DashboardLayout.tsx     # Frame containing sidebar, header, and content
    ├── Sidebar.tsx             # Interactive sidebar navigation (role filtered)
    └── dashboard/              # Workspace Tab Components:
        ├── Overview.tsx        # Dashboard welcome, stats, and calendars
        ├── AllEvents.tsx       # Grid view and edit trigger for all system events
        ├── EventProposalForm.x # Configurator for single and recurring proposals
        ├── ApprovalsView.tsx   # HoD/Principal checklist for pending items
        ├── InstitutionalChecklist.tsx # Audit checklist of requirement fulfillments
        ├── InstitutionalCalendar.tsx  # Dynamic React Calendar showing notes/events
        ├── VenueTimeline.tsx   # Live visual scheduling chart of venue occupancies
        ├── VenuesAtGlance.tsx  # Today's room availability checker
        ├── FacultyEventManagement.tsx # Faculty personal dashboard view
        ├── PrincipalMasterChecklist.x # Checklist of all active requirements
        ├── ClubInstitutionalChecklist.x # Special checklist for Student Clubs
        ├── AutomationView.tsx  # Semester Swap automation dashboard
        ├── ExcelImport.tsx     # Bulk spreadsheet spreadsheet import tool
        ├── UserManagement.tsx  # Admin credentials manager
        ├── ClassManagement.tsx # Admin class config manager
        ├── EventDetailsModal.tsx # Detailed view overlays
        └── Pagination.tsx      # Table list page controllers
```

---

## 6. Functional Site Map (Page Router Decodes)

The following map defines frontend routes, navigation identifiers, role restrictions, and the underlying controllers/endpoints.

```mermaid
graph TD
    Login[LoginPage.tsx] -->|Auth Success| Dashboard[App.tsx Dashboard Shell]
    
    subgraph Dashboard Views
        OverviewView[Overview.tsx <br> Dashboard Option]
        ProposalView[EventProposalForm.tsx <br> Propose Option]
        ApprovalsView[ApprovalsView.tsx <br> Approvals Option]
        AllEventsView[AllEvents.tsx <br> All Events Option]
        ChecklistView[InstitutionalChecklist.tsx <br> Checklist Option]
        HistoryView[EventHistory.tsx <br> History Option]
        ClubsView[ClubInstitutionalChecklist.tsx <br> Clubs Option]
        AutomationView[AutomationView.tsx <br> Automation Option]
        ExcelImportView[ExcelImport.tsx <br> Excel Import Option]
        ClassesView[ClassManagement.tsx <br> Classes Option]
        UsersView[UserManagement.tsx <br> Manage Users Option]
    end

    classDef roleAll fill:#e0f7fa,stroke:#00acc1,stroke-width:1px;
    classDef roleStaff fill:#e8eaf6,stroke:#3f51b5,stroke-width:1px;
    classDef roleApprover fill:#fff3e0,stroke:#ff9800,stroke-width:1px;
    classDef roleAdmin fill:#fbe9e7,stroke:#ff5722,stroke-width:1px;
    
    class OverviewView,ProposalView,AllEventsView,ChecklistView,HistoryView roleAll;
    class ClubsView roleStaff;
    class ApprovalsView,AutomationView roleApprover;
    class ClassesView,UsersView,ExcelImportView roleAdmin;
```

### Route-by-Route Specification

#### 1. Login Gate
* **Component:** `LoginPage.tsx`
* **Route Logic:** Rendered if `isAuthenticated` is `false`.
* **Access:** Public.
* **Backend Interaction:** `POST /api/auth/login`

#### 2. Overview Dashboard (`dashboard`)
* **Component:** `Overview.tsx`
* **Access:** All Authenticated Users.
* **Contextual Features:**
  * **Principal Desk:** Shows `PrincipalMasterChecklist` (auditing table).
  * **Class Incharge Desk:** Shows current class details and a form to submit class strength updates via `PUT /api/admin/users/{id}`.
  * **Faculty Desk:** Shows `FacultyEventManagement` (table of personal proposed events, status, edit buttons).
  * **Live Analytics:** Renders circular progress counters matching categories (Academic, Cultural, Placement, Sports, Other).
* **Embedded Sub-Components:**
  * `InstitutionalCalendar.tsx` (Grid of events, notes fetching from `GET /api/notes`, notes creation via `POST /api/notes`).
  * `VenuesAtGlance.tsx` (Highlights venue reservation blocks).
  * `VenueTimeline.tsx` (Hour-by-hour calendar lines for room allocations).
* **Backend Interaction:** `GET /api/events`, `GET /api/notes`, `POST /api/notes`

#### 3. Propose Event (`propose`)
* **Component:** `EventProposalForm.tsx`
* **Access:** `FACULTY`, `HOD`, `PRINCIPAL`, `PLACEMENT`, `ADMIN`.
* **Features:** Form requesting Title, Start/End DateTime, Location, Category (Academic, Club, Placement, Sports), Type (Workshop, Seminar, etc.), targeted Academic Years & Sections, Guest details, budget details, sponsors, and checklist requirements.
* **Modes:** Handles new proposals, recurring group proposals, and edit modes (loading existing values into form inputs).
* **Backend Interaction:** `POST /api/events/propose`, `PUT /api/events/{id}`

#### 4. Approvals (`approvals`)
* **Component:** `ApprovalsView.tsx`
* **Access:** `HOD`, `PRINCIPAL`.
* **Features:** Lists all events where status is:
  * `REQUESTED` (If role is `HOD`)
  * `PENDING_PR` (If role is `PRINCIPAL`)
* **Actions:** Approve triggers `POST /api/events/{id}/approve?userId={id}`. Reject opens a modal requesting description and triggers `POST /api/events/{id}/reject?userId={id}`.
* **Backend Interaction:** `GET /api/events`, `POST /api/events/{id}/approve`, `POST /api/events/{id}/reject`

#### 5. Clubs (`clubs`)
* **Component:** `ClubInstitutionalChecklist.tsx`
* **Access:** Users with `isClubCoordinator = true` or `role = ADMIN`.
* **Features:** Lists current club activity proposals and maps checklists for student societies.
* **Backend Interaction:** `GET /api/events`

#### 6. All Events (`events`)
* **Component:** `AllEvents.tsx`
* **Access:** All Authenticated Users.
* **Features:** Tabulated search dashboard filtering all system events (Upcoming vs. Finished). Allows editing events (via Propose Event view) if the user is the proposer or an administrator.
* **Backend Interaction:** `GET /api/events`

#### 7. Institutional Checklist (`checklist`)
* **Component:** `InstitutionalChecklist.tsx`
* **Access:** All Authenticated Users.
* **Features:** Generates a checklist report detailing logistics (Catering, venue prep, Wi-Fi configuration, etc.) for upcoming events.
* **Backend Interaction:** `GET /api/events`

#### 8. Event History (`history`)
* **Component:** `EventHistory.tsx`
* **Access:** All Authenticated Users.
* **Features:** Searchable catalog of past completed events with analytics summaries and export tools.
* **Backend Interaction:** `GET /api/events`

#### 9. Automation Console (`automation`)
* **Component:** `AutomationView.tsx`
* **Access:** `HOD`, `PRINCIPAL`, `ADMIN`.
* **Features:**
  * **Semester Swap:** Selects source Institution/Dept/Batch (e.g. RIT CSE 3rd Year) and target Institution/Dept/Batch. Simulates calendar shifts (+/- 6 months).
  * **Conflict Analysis:** Performs live in-memory evaluation for weekend events (recommends quick-shifting to Friday or Monday) and database overlaps.
  * **Review Gate:** Displays simulated changes in a modal allowing the operator to Commit, Reschedule, or Skip. Committing makes a batch API request.
* **Backend Interaction:** `GET /api/events`, `POST /api/events/batch-create`

#### 10. Excel Import (`import-excel`)
* **Component:** `ExcelImport.tsx`
* **Access:** `ADMIN` (and accessible from Dashboard views).
* **Features:**
  * **Fuzzy Parsing:** Converts excel columns (Form Responses) into structured Event payloads.
  * **Auto-Registration:** Identifies if the listed proposer does not exist in the user database. If missing, registers a new account (`password` defaults to `Password@123`) using the `POST /api/admin/users` service.
  * **Conflict Solver:** Identifies venue/timing conflicts. Suggests moving to alternative venues or shifting times.
* **Backend Interaction:** `GET /api/events`, `GET /api/admin/users`, `POST /api/admin/users`, `POST /api/events/batch-create`

#### 11. Class Configurations (`classes`)
* **Component:** `ClassManagement.tsx`
* **Access:** `ADMIN`.
* **Features:**
  * Configures class metadata (Institution, Department, Academic Year, Sections).
  * **Yearly Promotion:** Promotes student batches via a quick action (e.g. promoting 1st Years to 2nd Years, deleting graduating 4th Years).
* **Backend Interaction:** `GET /api/classes`, `POST /api/classes`, `DELETE /api/classes/{id}`, `POST /api/classes/promote`

#### 12. User Management (`user-management`)
* **Component:** `UserManagement.tsx`
* **Access:** `ADMIN`.
* **Features:** Add new users, edit existing user profile fields (including modifying student club assignments and Class Incharge details), delete accounts, or change passcodes.
* **Backend Interaction:** `GET /api/admin/users`, `POST /api/admin/users`, `PUT /api/admin/users/{id}`, `DELETE /api/admin/users/{id}`
