# RIT Event Management System (EMS) - Comprehensive System Documentation

The **RIT Event Management System (EMS)** is a state-of-the-art web application developed for the Rajalakshmi Institute of Technology (RIT) to handle, automate, audit, and coordinate campus-wide events, venue requests, and academic schedules.

---

## 1. Executive Summary & Core Objective

In an active educational institution like RIT (and the sister school RSB), coordinating events such as academic workshops, guest lectures, sports events, student club activities, and high-priority placement drives presents significant scheduling challenges:
1. **Venue Booking Conflicts:** Overlapping bookings for major facilities (e.g., auditoriums, seminar halls, labs).
2. **Complex Approvals:** Manual routing of proposals from Faculty, through Heads of Departments (HOD), up to the Principal.
3. **Academic Semester Swapping:** Transitioning routine weekly/monthly schedules from one semester to the next.
4. **Data Overload:** Migrating bulk event schedules from legacy tools or Google Forms.

The EMS platform addresses these challenges by offering:
* **Interactive Venues at a Glance:** Live timeline visuals showing hourly and daily room utilization.
* **Role-Based Workflows:** Direct automated routing of event proposals based on standard institutional roles.
* **Smart Conflict Solver:** Automated, real-time database queries matching proposed locations, dates, and institutions.
* **Overriding Placement System:** Privileged scheduling options for Placement staff to secure facilities.
* **Semester Swap Simulation:** Dynamic tool mapping active calendars onto subsequent semesters with calendar shift simulations.
* **Fuzzy Excel Parser:** In-browser sheet processor mapping arbitrary data columns into structured event templates.

---

## 2. System Architecture & Tech Stack

The platform runs on a serverless, database-first architecture using Firebase. All backend endpoints are intercepted and resolved client-side in the browser.

```mermaid
graph LR
    subgraph Frontend [React SPA Client]
        React[React 19 / TS / Vite]
        Router[Component & Context Routing]
        Tailwind[Tailwind CSS & Glassmorphism UI]
        Framer[Framer Motion Animations]
        Interceptor[Fetch Interceptor firebaseBackend.ts]
    end

    subgraph Backend [Firebase Cloud Platform]
        Firestore[(Cloud Firestore Database)]
        Auth[Firebase Authentication]
    end

    React <--> Interceptor
    Interceptor <-->|Firebase Client SDK| Firestore
    Interceptor <-->|Firebase Client SDK| Auth
```

### Firebase Backend Specifications
* **Database Service:** Cloud Firestore for real-time document storage.
* **Data Access & Interception:** A client-side fetch interceptor implemented in `firebaseBackend.ts` intercepts all `/api/*` REST HTTP requests and handles the queries/transactions natively using the Firebase Client SDK.
* **Authentication:** Google OAuth 2.0 and email/passcode flows, integrated with Firebase Auth and sync'd to the `ems_users` Firestore collection.
* **Security & Roles:** Verified inside frontend routing handlers and secured using Firestore Security Rules.

### Frontend Specifications
* **Core Framework:** React 19, TypeScript, Vite
* **State Management:** React Context API (specifically `AuthContext` managing authenticated states).
* **Styling System:** Tailwind CSS with custom global CSS utilities for modern glassmorphism design layouts.
* **Animations:** Framer Motion powering tab transitions, modal slides, and responsive components.
* **Icon Suite:** Lucide React
* **Utility Libraries:**
  * `date-fns`: Date formatting, calendar scheduling, and duration differences.
  * `xlsx`: In-browser parsing of spreadsheet files (.xlsx, .csv).

---

## 3. Database Schema & Architecture

The database contains four primary collections managed in Cloud Firestore.

```mermaid
erDiagram
    USERS {
        Long id PK
        String email UK
        String password
        String fullName
        String role
        String department
        Boolean isClubCoordinator
        Boolean isPlacementStaff
        Boolean isClassIncharge
        Integer classStrength
        String inchargeClass
        String inchargeBatch
        String inchargeSection
    }
    EVENTS {
        Long id PK
        String title
        Text description
        LocalDateTime startDate
        LocalDateTime endDate
        String location
        String category
        String type
        String institution
        String department
        String status
        String guestName
        String guestSocialProfile
        Double budget
        Boolean hasRegistrationFee
        Double registrationFee
        Text rejectionReason
        String groupRequestId
        Long proposer_id FK
    }
    CLASS_MAPPING {
        Long id PK
        String institution
        String department
        String academicYear
        String status
    }
    INSTITUTIONAL_NOTE {
        Long id PK
        String content
        LocalDate targetDate
        String authorName
        String authorEmail
        LocalDateTime createdAt
    }
    USERS ||--o{ EVENTS : proposes
```

### A. User Entity (`users`)
Holds profiles, credentials, permissions, and roles.
* `id` (Long, Primary Key): Auto-incremented.
* `email` (String, Unique): Institutional email (`@rit.edu` or `@ritindia.edu`).
* `password` (String): BCrypt hashed password representation.
* `fullName` (String): User's display name.
* `role` (String): Enum-like values: `ADMIN`, `PRINCIPAL`, `HOD`, `FACULTY`, `PLACEMENT`.
* `department` (String): Department names (e.g., `CSE`, `AI&ML`, `ECE`, `H&S Dept`, etc.).
* `isClubCoordinator` (Boolean): Authorizes coordination of student club events.
* `isPlacementStaff` (Boolean): Grants authority to override schedule conflicts for placement events.
* `isClassIncharge` (Boolean): Authorizes dashboard widgets showing class sizes and updates.
* `classStrength` (Integer): Student count for the in-charge class.
* `inchargeClass` / `inchargeBatch` / `inchargeSection` (String): Specific details identifying the class in charge.
* `assignedClubs` (ElementCollection): List of student clubs managed by the user.

### B. Event Entity (`events`)
Details individual event proposals, resources, status, and audit workflows.
* `id` (Long, Primary Key): Auto-incremented.
* `title` (String, Not Null): The name of the event.
* `description` (Text): Detailed agenda or description.
* `startDate` / `endDate` (LocalDateTime): Timestamps for the event duration.
* `location` (String): Specific venue (e.g., `GB 4th floor auditorium`, `Wozniak Auditorium`, `Mini Seminar Hall`).
* `category` (String): Dictates the routing logic: `ACADEMIC`, `CLUB`, `PLACEMENT`, `SPORTS`, `INSTITUTIONAL`.
* `type` (String): Event type (e.g., `Workshop`, `Seminar`, `Guest Lecture`, `Competition`).
* `institution` (String): Targets `RIT` or `RSB`.
* `department` (String): Proposing department.
* `academicYears` (ElementCollection): Targeted cohorts (e.g., `1st Year`, `2nd Year`, `3rd Year`, `4th Year`).
* `targetedSections` (ElementCollection): Target sections (e.g., `A`, `B`, `C`).
* `status` (String): Current lifecycle stage:
  * `REQUESTED`: Submitted by Faculty, pending HOD approval.
  * `PENDING_PR`: Approved by HOD, pending Principal approval (or submitted directly by HOD/Placement, bypassing HOD stage).
  * `APPROVED`: Fully approved, venue locked, and calendar entry created.
  * `COMPLETED`: Event time has elapsed.
  * `CANCELLED`: Cancelled manually or displaced by an overriding placement event.
  * `HOD_REJECTED`: Rejected at the HOD stage.
  * `PRINCIPAL_REJECTED`: Rejected at the Principal stage.
* `guestName` / `guestSocialProfile` (String): Guest details and links.
* `requirements` (ElementCollection): Resources required (e.g., `Mementos`, `Projector`, `Lunch`, `Wi-Fi`, `Mic`).
* `budget` (Double): Requested budget.
* `hasRegistrationFee` (Boolean) / `registrationFee` (Double): Entry fee details.
* `sponsors` (ElementCollection): Partner/sponsor list.
* `proposer` (ManyToOne -> User): Reference to user who created the event proposal.
* `rejectionReason` (Text): Comments input by HOD or Principal when rejecting.
* `groupRequestId` (String): Link identifier for recurring events.

### C. ClassMapping Entity (`classes`)
Used for maintaining lists of student cohorts and sections.
* `id` (Long, Primary Key)
* `institution` (String): `RIT` or `RSB`.
* `department` (String): Department name.
* `academicYear` (String): `1st Year`, `2nd Year`, etc.
* `sections` (ElementCollection): List of associated sections.
* `status` (String): Defaults to `Ready`.

### D. InstitutionalNote Entity (`institutional_notes`)
Pinned warnings, announcements, or notifications on the main calendar.
* `id` (Long, Primary Key)
* `content` (String, Not Null)
* `targetDate` (LocalDate): Date on which the note should appear on the calendar.
* `authorName` / `authorEmail` (String): Creator info.
* `createdAt` (LocalDateTime)

---

## 4. Role-Based Access Control & Navigation

The frontend app adjusts its views, menus, and dashboard components dynamically based on the logged-in user's role and authorization flags:

| Role / Flag | Menu Items Available | Special Features |
| :--- | :--- | :--- |
| **FACULTY** | Dashboard, Propose Event, All Events, Institutional Checklist, Event History | Can see personal proposal status, updates class strength if marked as Class Incharge. |
| **HOD** | Dashboard, Propose Event, Approvals, All Events, Institutional Checklist, Event History, Automation Console | Can approve/reject department proposals. Can access the Semester Swap simulator. |
| **PRINCIPAL** | Dashboard, Propose Event, Approvals, All Events, Institutional Checklist, Event History, Automation Console | Can approve/reject any pending events. Master checklist dashboard widget access. |
| **PLACEMENT** | Dashboard, Propose Event, All Events, Institutional Checklist, Event History | Proposes placement events that can optionally override existing bookings. |
| **ADMIN** | Dashboard, Propose Event, Approvals, Clubs Checklist, All Events, Institutional Checklist, Event History, Automation Console, Excel Import, Class Configurations, User Management | Full control over users, classes, excel file parses, database configurations, and approvals. |
| **isClubCoordinator = true** | Add *Clubs* Menu option | Grants access to the Club Checklist page to coordinate student club activities. |

---

## 5. Site Map & Route Specification

The system uses a Single-Page Application (SPA) shell in [App.tsx](file:///e:/RIT-EMS-main/frontend/src/App.tsx) driven by state routing.

```mermaid
graph TD
    Login[LoginPage.tsx] -->|POST /api/auth/login success| Shell[App.tsx SPA Shell]
    
    subgraph SPA Navigation & Components
        Shell -->|dashboard| Overview[Overview.tsx]
        Shell -->|propose| Proposal[EventProposalForm.tsx]
        Shell -->|approvals| Approvals[ApprovalsView.tsx]
        Shell -->|clubs| Clubs[ClubInstitutionalChecklist.tsx]
        Shell -->|events| Events[AllEvents.tsx]
        Shell -->|checklist| Checklist[InstitutionalChecklist.tsx]
        Shell -->|history| History[EventHistory.tsx]
        Shell -->|classes| ClassMgmt[ClassManagement.tsx]
        Shell -->|automation| Automation[AutomationView.tsx]
        Shell -->|import-excel| ExcelImport[ExcelImport.tsx]
        Shell -->|user-management| UserMgmt[UserManagement.tsx]
    end

    subgraph Embedded Widgets in Overview
        Overview --> Cal[InstitutionalCalendar.tsx]
        Overview --> Ven[VenuesAtGlance.tsx]
        Overview --> Time[VenueTimeline.tsx]
        Overview --> Fac[FacultyEventManagement.tsx]
        Overview --> Pri[PrincipalMasterChecklist.tsx]
    end
```

### Route & Component Specification Details

#### 1. Login Gate
* **Component:** [LoginPage.tsx](file:///e:/RIT-EMS-main/frontend/src/pages/LoginPage.tsx)
* **Access:** Anonymous/Public.
* **Description:** Provides a modern UI with split-card layout, college logos, and forms for institutional email & password.
* **API Endpoint called:** `POST /api/auth/login`

#### 2. Overview Dashboard (`dashboard`)
* **Component:** [Overview.tsx](file:///e:/RIT-EMS-main/frontend/src/components/dashboard/Overview.tsx)
* **Access:** All Authenticated Users.
* **Features:**
  * Displays circular progress indicators representing events by category.
  * Shows role-specific cards (e.g., Faculty see their proposals; Class Incharges see class stats; Principals see Master Checklist).
* **Embedded Sub-Components:**
  * **[InstitutionalCalendar.tsx](file:///e:/RIT-EMS-main/frontend/src/components/dashboard/InstitutionalCalendar.tsx):** Interactive calendar with day-based event popovers and notes.
  * **[VenuesAtGlance.tsx](file:///e:/RIT-EMS-main/frontend/src/components/dashboard/VenuesAtGlance.tsx):** Displays a grid of main campus venues and their immediate status.
  * **[VenueTimeline.tsx](file:///e:/RIT-EMS-main/frontend/src/components/dashboard/VenueTimeline.tsx):** A timeline mapping hour blocks for venue bookings.
  * **[FacultyEventManagement.tsx](file:///e:/RIT-EMS-main/frontend/src/components/dashboard/FacultyEventManagement.tsx):** Faculty-specific event table displaying submission stages.
  * **[PrincipalMasterChecklist.tsx](file:///e:/RIT-EMS-main/frontend/src/components/dashboard/PrincipalMasterChecklist.tsx):** Principal-specific checklist audit view.
* **API Endpoints called:** `GET /api/events`, `GET /api/notes`, `POST /api/notes`, `PUT /api/admin/users/{id}` (for class updates).

#### 3. Propose Event (`propose`)
* **Component:** [EventProposalForm.tsx](file:///e:/RIT-EMS-main/frontend/src/components/dashboard/EventProposalForm.tsx)
* **Access:** All Authenticated Users.
* **Features:**
  * Handles standard scheduling, multi-select sections/target academic years, and venue requirements (Catering, Projector, Wi-Fi, etc.).
  * Support for recurring group bookings.
  * Placement role can toggle "Override Conflicts".
* **API Endpoints called:** `POST /api/events/propose`, `PUT /api/events/{id}`

#### 4. Approvals (`approvals`)
* **Component:** [ApprovalsView.tsx](file:///e:/RIT-EMS-main/frontend/src/components/dashboard/ApprovalsView.tsx)
* **Access:** HOD and PRINCIPAL.
* **Features:** Tabulated view listing pending events. HOD reviews `REQUESTED` events. Principal reviews `PENDING_PR` events. Rejections trigger a popover modal requesting comment.
* **API Endpoints called:** `GET /api/events`, `POST /api/events/{id}/approve`, `POST /api/events/{id}/reject`

#### 5. Clubs Checklist (`clubs`)
* **Component:** [ClubInstitutionalChecklist.tsx](file:///e:/RIT-EMS-main/frontend/src/components/dashboard/ClubInstitutionalChecklist.tsx)
* **Access:** Club Coordinators and Admin.
* **Features:** Filters events specifically marked under the `CLUB` category and presents a checklist layout.
* **API Endpoints called:** `GET /api/events`

#### 6. All Events (`events`)
* **Component:** [AllEvents.tsx](file:///e:/RIT-EMS-main/frontend/src/components/dashboard/AllEvents.tsx)
* **Access:** All Authenticated Users.
* **Features:** Grid searching, text filters, date search, category chips, and delete/edit buttons for event owners or Admin.
* **API Endpoints called:** `GET /api/events`, `DELETE /api/events/{id}`

#### 7. Institutional Checklist (`checklist`)
* **Component:** [InstitutionalChecklist.tsx](file:///e:/RIT-EMS-main/frontend/src/components/dashboard/InstitutionalChecklist.tsx)
* **Access:** All Authenticated Users.
* **Features:** Visual grid displaying requirements (Wi-Fi, catering, projector) for approved upcoming events, highlighting completeness.
* **API Endpoints called:** `GET /api/events`

#### 8. Event History (`history`)
* **Component:** [EventHistory.tsx](file:///e:/RIT-EMS-main/frontend/src/components/dashboard/EventHistory.tsx)
* **Access:** All Authenticated Users.
* **Features:** Lists elapsed events with filters. Features summary stats showing total budget spent and event count.
* **API Endpoints called:** `GET /api/events`

#### 9. Automation Console (`automation`)
* **Component:** [AutomationView.tsx](file:///e:/RIT-EMS-main/frontend/src/components/dashboard/AutomationView.tsx)
* **Access:** HOD, PRINCIPAL, and ADMIN.
* **Features:**
  * **Semester Swap:** Selects a batch of events (e.g., CSE 3rd Year RIT) and maps them to a future date range (+/- 6 months) to replicate schedules.
  * **Conflict Analysis:** In-memory check identifying overlap with existing entries or weekends, recommending alternatives.
  * **Review Gate:** Verification modal showing proposed events before batch creation.
* **API Endpoints called:** `GET /api/events`, `POST /api/events/batch-create`

#### 10. Excel Import (`import-excel`)
* **Component:** [ExcelImport.tsx](file:///e:/RIT-EMS-main/frontend/src/components/dashboard/ExcelImport.tsx)
* **Access:** ADMIN.
* **Features:**
  * File uploader utilizing `xlsx` to parse spreadsheet columns.
  * Mapping panel to align sheet columns with event details.
  * Proposer verification: Automatically registers unrecognized emails (`password` defaults to `Password@123`).
  * Conflict resolver indicating venue/time overlaps and recommending shifts.
* **API Endpoints called:** `GET /api/events`, `GET /api/admin/users`, `POST /api/admin/users`, `POST /api/events/batch-create`

#### 11. Class Configurations (`classes`)
* **Component:** [ClassManagement.tsx](file:///e:/RIT-EMS-main/frontend/src/components/dashboard/ClassManagement.tsx)
* **Access:** ADMIN.
* **Features:** Add classes, update sections, and perform the "Yearly Promotion" (e.g. promoting 1st Years -> 2nd Years, deleting graduating 4th Years).
* **API Endpoints called:** `GET /api/classes`, `POST /api/classes`, `DELETE /api/classes/{id}`, `POST /api/classes/promote`

#### 12. User Management (`user-management`)
* **Component:** [UserManagement.tsx](file:///e:/RIT-EMS-main/frontend/src/components/dashboard/UserManagement.tsx)
* **Access:** ADMIN.
* **Features:** CRUD management for user accounts. Controls department assignments, club responsibilities, role changes, and passwords.
* **API Endpoints called:** `GET /api/admin/users`, `POST /api/admin/users`, `PUT /api/admin/users/{id}`, `DELETE /api/admin/users/{id}`

---

## 6. Key Workflows & Logic Specs

### A. Real-time Conflict Auditing Engine
During event creation, the application validates for timing and location conflicts directly against Firestore.
1. The frontend query helper scan the `ems_events` collection to identify overlapping bookings:
   $$\text{Start}_A < \text{End}_B \quad \text{and} \quad \text{End}_A > \text{Start}_B$$
2. **Placement Override Case:**
   If the proposer is a `PLACEMENT` coordinator and `cancelConflicting=true` is checked:
   * The fetch interceptor updates all conflicting Firestore event documents' status to `CANCELLED`.
   * It registers a rejection/displacement reason on the cancelled events.
   * The placement event is saved in `PENDING_PR` (for Principal review).
3. **General Case:**
   If conflicts exist and it is not an overridden placement, a conflict message is returned and flagged to the user.

### B. Event Approval Pipeline
The approval flow routes events dynamically depending on the proposer:
```
           [ Faculty Proposes Event ]
                      │
                      ▼
             [ HOD Desk Review ]
             (Status: REQUESTED)
                /          \
            Approve       Reject ──► [ Status: HOD_REJECTED ]
              /
             ▼
      [ Principal Desk Review ]
      (Status: PENDING_PR)
         /               \
     Approve            Reject ──► [ Status: PRINCIPAL_REJECTED ]
       /
      ▼
[ Status: APPROVED ]
(Venue Locked / Calendar Pinned)
```
* **Bypass Rule 1:** If the proposer is the **Principal**, the event is auto-approved (`APPROVED`).
* **Bypass Rule 2:** If the proposer is an **HOD**, or the event category is **Club**, **Placement**, or **Institutional**, the proposal bypasses HOD review and goes directly to the Principal (`PENDING_PR`).

### C. Semester Swap Calendar Shift
This tool allows admins/HODs/Principals to duplicate schedules for new semesters:
1. Select source filters (e.g., Department = CSE, Academic Year = 3rd Year).
2. The UI fetches matching events, maps them to target dates (shifted by a user-specified offset, e.g., 180 days), and simulates their placement.
3. The UI checks each shifted event against the database for venue conflicts or weekends:
   * If an event lands on a Saturday or Sunday, the UI suggests shifting it to the nearest Friday or Monday.
   * If a venue conflict occurs, the UI flags it and suggests venue changes.
4. Clicking "Commit" submits a bulk payload to `POST /api/events/batch-create`.

---

## 7. Developer & Local Deployment Guide

### Prerequisites
* Node.js (v18+)

### 1. Launch Frontend Client
1. Navigate to the `frontend` folder.
2. Install dependencies:
   ```bash
   npm install
   ```
3. Run the development server:
   ```bash
   npm run dev
   ```
4. The frontend runs at `http://localhost:5173`.

### 2. Firebase Configurations
* The Firebase client config is hardcoded in `frontend/src/lib/firebaseBackend.ts` to connect directly to the Firestore backend.
* On first load, if the database collections (`ems_users` or `ems_classes`) are empty, `firebaseBackend.ts` automatically seeds default institutional accounts and mock classes.

### 3. Seed User Accounts & Logins
On startup, the system seeds accounts with their default passwords:
* **Faculty Member:** `faculty@rit.edu` / `faculty123`
* **HOD:** `hod@rit.edu` / `hod123`
* **Principal:** `principal@rit.edu` / `principal123`
* **Placement Officer:** `placement@rit.edu` / `placement123`
* **Administrator:** `admin@rit.edu` / `admin123`
