Compare commits

..

21 Commits

Author SHA1 Message Date
Shanmuga Krishnan S M
34ea034899 Merge remote-tracking branch github/main into main and resolve Events conflict
Some checks failed
Deploy RIT Freshers Hub to VPS / Deploy to Live VPS (push) Has been cancelled
2026-08-19 09:15:07 +05:30
Shanmuga Krishnan S M
a99c54c705 Complete audit: fix strict TypeScript errors, Window types, and clean production build 2026-08-19 09:13:43 +05:30
Shanmuga Krishnan S M
d028e86bdd Restore fetchQuestions and handleDeleteQuestion handlers in AdminDashboard.tsx 2026-08-19 09:08:20 +05:30
Shanmuga Krishnan S M
b5b152f43c Fix import path for getBackendUrl in Faculty.tsx 2026-08-19 09:07:25 +05:30
Shanmuga Krishnan S M
82c6444c28 Wire live Spring Boot API fetch to Faculty page with local fallback support 2026-08-19 09:06:18 +05:30
Shanmuga Krishnan S M
f937efce5c Remove notes and deployment alert recipients from Admin console and improve Telegram Senior Responders persistence 2026-08-19 09:03:15 +05:30
Shanmuga Krishnan S M
e15c95fafd Fix AdminDashboard state declarations and handle offline fetch gracefully in Notes.tsx 2026-08-19 08:58:12 +05:30
Shanmuga Krishnan S M
9a0c601955 Add Admin management for Centers of Excellence, Faculty Directory, and GPA Calculator course & credit assignments 2026-08-19 08:55:41 +05:30
Amudieshwar
774ae7e7ae fix: persist like counts across refreshes and remove social links card from non-RAISE centers 2026-08-19 08:52:20 +05:30
Shanmuga Krishnan S M
9a58b2a53e Make Telegram Q&A, Notes, Community Questions and Email Alerts fully functional with persistent localStorage state 2026-08-19 08:49:15 +05:30
Shanmuga Krishnan S M
a4ad5e5815 Merge remote UI updates 2026-08-19 08:46:57 +05:30
Amudieshwar
7cd28fa974 fix: restrict RAISE Incubator portal link to RAISE entity and render official website link for other centers 2026-08-19 08:37:48 +05:30
Shanmuga Krishnan S M
bba33ef05b Save local admin console and unified auth changes before pulling remote UI updates 2026-08-19 08:34:31 +05:30
Amudieshwar
5f3b3f5973 feat: persist club and center likes in postgresql database 2026-08-19 08:31:12 +05:30
Amudieshwar A G
f8ca5a3368 refactor: rename Dashboard nav label to Time table and remove faculty directory shortcut 2026-08-19 08:24:03 +05:30
Anbu-dev-creator
2d91f6f5c4 new commit 2026-08-18 15:32:10 +05:30
Anbu-dev-creator
154f19d546 Changes in the UI 2026-08-18 15:10:23 +05:30
Amudieshwar A G
02d8dea9a9 feat: reorder toolkit & navbar, update RAISE incubator & portal modules, fix faculty department filtering 2026-08-18 12:27:27 +05:30
Anbu-dev-creator
d3bd00e506 Added cgpa 2026-08-18 09:43:36 +05:30
Devesh S
e83b934e9c Campus Map 2026-08-18 09:06:46 +05:30
Shanmuga Krishnan S M
1eebd10f3a added fake end points to simulate real arhitecture 2026-08-17 14:36:32 +05:30
34 changed files with 7094 additions and 885 deletions

View File

@@ -0,0 +1,222 @@
# IMS–Nexus Integration & Architecture Guide
---
## 1. How This Simulates the Actual Production Workflow
In the architecture documented in your design files, **Freshers-Hub (Nexus)** is the *Student Experience Layer* running on your VPS, while **IMS** is the *Authoritative System of Record* hosted and managed separately by the college.
### The Real-World Request Flow
```
[Student Browser]
│
│ 1. Submits Reg No ("2114251001") + Password ("rit@2026")
▼
[Nexus Frontend (React)]
│
│ 2. POST /api/v1/ims/auth/login
▼
[Nexus Backend (Spring Boot Proxy)]
│
│ 3. Secure HTTPS Call with 2 Identities:
│ • Identity 1 (Application): "X-Nexus-App-Secret: <shared_secret>"
│ • Identity 2 (Student): Reg No & Password
▼
[College Firewall & IMS API Gateway] ◄── [Gate 1: HTTPS & Gate 2: IP Allowlist]
│
│ 4. Authenticates credentials against IMS DB
│ 5. Enforces Scopes (e.g. student.read, timetable.read)
▼
[IMS Database (Locked Source of Truth)]
│
│ 6. Returns Student Profile, Day Schedule, Room Info
▼
[Nexus Backend] ──(Session Cached)──► [Nexus Frontend Dashboard]
```
### What the Mock Layer is Simulating Today
| Production Component | How Our Code Simulates It Locally |
| :--- | :--- |
| **IMS Server & Database** | `MockImsClientImpl.java` holds an in-memory repository of realistic student records (CSE, AI&DS, ECE), timetables, and classroom blocks. |
| **Credential Authentication** | The mock checks Reg No & Password and generates a structured session token (`ims_session_<regNo>_<uuid>`). |
| **Dynamic Timetable Engine** | Calculates current time vs. class slots to determine real-time period status (`COMPLETED`, `ONGOING`, `UPCOMING`). |
| **Security Boundary** | The frontend **never** talks to IMS directly. It always routes through the Nexus backend interface `ImsClient.java`. |
---
## 2. On Deployment: What Actually Changes on Your End?
Because we used the **Strategy / Adapter Pattern**, your application is built so that switching to the live college server requires **zero code rewrites in the frontend, controllers, or database models**.
### Step 1: Switch the Configuration Property
In `backend/src/main/resources/application.properties` (or via Linux environment variables on your VPS):
```properties
# 1. Flip client type from "mock" to "real"
ims.client.type=real
# 2. Provide the live IMS API Gateway URL
ims.base-url=https://api.ims.ritchennai.edu.in
# 3. Provide the shared secret given to you by the college IMS team
ims.api-key=${IMS_CLIENT_SECRET:production_secret_key_here}
```
### Step 2: What Spring Boot Does Automatically
- Spring Boot detects `ims.client.type=real`.
- It deactivates `MockImsClientImpl` and activates `RealImsClientImpl.java`.
- `RealImsClientImpl` starts dispatching live HTTP requests with the required headers (`X-Nexus-App-Secret`, `X-Student-Id`).
### Step 3: Network & Security Setup on the VPS
1. **SSL/TLS**: Ensure your Nexus domain (e.g., `nexus.ritchennai.edu.in`) has an active HTTPS certificate.
2. **Fixed Static IP**: Give your VPS public IP (e.g., `103.xxx.xxx.xxx`) to the college network administrator for IP whitelisting.
---
## 3. What Information Do You Need from the IMS Team?
Since IMS is an independent standalone application managed by a separate team or vendor with no public APIs exposed yet, you need to request the following **4 items** from them:
### 📋 The Integration Checklist
```
+─────────────────────────────────────────────────────────────────────────────+
| IMS INTEGRATION CHECKLIST |
+───┬──────────────────────────────────┬──────────────────────────────────────+
| 1 | Static IP Whitelisting | Whitelist your Nexus VPS outbound IP |
| 2 | Application Secret / API Key | A secure shared secret key / token |
| 3 | API Endpoint Base URL | e.g. https://api.ims.college.edu |
| 4 | API Contract & Response Format | JSON schema for login & timetable |
+───┴──────────────────────────────────┴──────────────────────────────────────+
```
---
### Endpoints the IMS Team Needs to Expose for You
You can hand the IMS development team this exact list of endpoints:
#### 1. Student Authentication
- **Endpoint**: `POST /api/v1/auth/student-login`
- **Headers**: `X-Nexus-App-Secret: <your_secret_key>`
- **Request Body**:
```json
{
"regNumber": "2114251001",
"password": "student_password"
}
```
- **Response Expected**:
```json
{
"success": true,
"token": "ims_jwt_token_here",
"student": {
"regNumber": "2114251001",
"name": "Anbu Kathir",
"degree": "B.E.",
"department": "Computer Science & Engineering",
"year": 1,
"semester": 2,
"section": "A",
"batch": "2025 - 2029"
}
}
```
#### 2. Student Dashboard / Today's Timetable & Venue
- **Endpoint**: `GET /api/v1/dashboard/me` (or `GET /api/v1/timetable/me?date=YYYY-MM-DD`)
- **Headers**:
- `X-Nexus-App-Secret: <your_secret_key>`
- `X-Student-Id: 2114251001` (or `Authorization: Bearer <token>`)
- **Response Expected**:
```json
{
"classLocation": {
"roomNumber": "LH-204",
"buildingName": "Dr. APJ Abdul Kalam Academic Block",
"floor": "2nd Floor",
"wing": "East Wing",
"landmark": "Next to CSE Department Library"
},
"classIncharge": {
"name": "Dr. R. Arunkumar",
"cabin": "APJ Block, Cabin 208-B",
"email": "arunkumar.r@ritchennai.edu.in"
},
"todaySchedule": {
"dayOfWeek": "MONDAY",
"periods": [
{
"periodNumber": 1,
"timeSlot": "08:45 AM - 09:40 AM",
"subjectCode": "CS3201",
"subjectName": "Data Structures",
"type": "THEORY",
"facultyName": "Dr. R. Arunkumar",
"venue": "LH-204"
}
]
}
}
```
---
## 4. What If the IMS Team Cannot Provide REST APIs Immediately?
If the IMS team is slow to build custom REST APIs, here are the standard industry workarounds in order of preference:
```
┌────────────────────────────────────────┐
│ If REST API is not ready today: │
└───────────────────┬────────────────────┘
│
┌─────────────────────────────────┼─────────────────────────────────┐
▼ ▼ ▼
┌──────────────────┐ ┌──────────────────┐ ┌──────────────────┐
| Option A: | | Option B: | | Option C: |
| Read-Only DB | | Automated Nightly| | LDAP / Active |
| View / Replica | | JSON/CSV Export | | Directory Auth |
| (Direct read of | | (Sync timetable | | (Single Sign-On |
| class schedule) | | & room data) | | integration) |
└──────────────────┘ └──────────────────┘ └──────────────────┘
```
1. **Option A (Read-Only Database View)**:
- Ask the database administrator for a **read-only database view** restricted strictly to timetable and room allocation tables. Your backend connects via JDBC read-only credentials.
2. **Option B (Scheduled JSON / CSV Sync)**:
- The IMS team runs a nightly cron job that dumps timetable/classroom data as an encrypted JSON/CSV file to a private S3 bucket or SFTP server. Your Spring Boot backend parses and caches it every 24 hours.
3. **Option C (LDAP / Active Directory)**:
- If the college uses Active Directory or LDAP for campus Wi-Fi/portals, students authenticate through LDAP, and timetable structures are matched using department & section mapping.
---
## 5. Ready-to-Send Request Template for the IMS Team
You can copy and email this directly to the college IT / IMS team:
```text
Subject: API Integration Request for Nexus Freshers-Hub Portal
Dear IMS / IT Team,
We are developing the Nexus Student Portal (Freshers-Hub) to provide students with quick access to their daily timetables, classroom venue directions, and academic tools.
To integrate seamlessly with the college IMS without duplicating data, we have implemented a secure server-to-server API client following standard enterprise security practices (IP Allowlisting + Shared Application Secret + Encrypted HTTPS).
Could you please provide us with the following integration details:
1. Staging/Production API Base URL (e.g., https://api.ims.ritchennai.edu.in)
2. Application API Key / Client Secret for the Nexus backend
3. IP Whitelisting for our VPS outbound IP: [INSERT_YOUR_VPS_IP]
4. Endpoints for:
- POST /api/v1/auth/student-login (Register Number & Password authentication)
- GET /api/v1/timetable/me (Student's daily schedule & classroom venue)
We have our Spring Boot backend proxy and mock test suites ready to plug into your API contract as soon as endpoints are available.
Thank you,
Nexus Engineering Team
```

105
README.md
View File

@@ -1,32 +1,87 @@
# React + TypeScript + Vite
# 🏫 Rajalakshmi Institute of Technology — Freshers-Hub
This template provides a minimal setup to get React working in Vite with HMR and some Oxlint rules.
Welcome to the **Freshers-Hub Portal**, a multi-service campus assistant and student utility ecosystem designed for Rajalakshmi Institute of Technology (RIT). The platform provides student services including live transit tracking, study guides, competitive programming leaderboards, developer collaboration networks, and an automated AI assistant.
Currently, two official plugins are available:
---
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs)
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
## 🏗️ System Architecture & Service Stack
## React Compiler
The system is built on a distributed microservice architecture utilizing four primary runtimes:
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
## Expanding the Oxlint configuration
If you are developing a production application, we recommend enabling type-aware lint rules by installing `oxlint-tsgolint` and editing `.oxlintrc.json`:
```json
{
"$schema": "./node_modules/oxlint/configuration_schema.json",
"plugins": ["react", "typescript", "oxc"],
"options": {
"typeAware": true
},
"rules": {
"react/rules-of-hooks": "error",
"react/only-export-components": ["warn", { "allowConstantExport": true }]
}
}
```
┌───────────────────────────────┐
│ Nginx Web Server │
│ (Ports 80 / 443) │
└───────────────┬───────────────┘
│
┌───────────────────────┼───────────────────────┐
▼ ▼ ▼
┌───────────────────┐ ┌───────────────────┐ ┌───────────────────┐
│ React Frontend │ │Spring Boot Backend│ │Go Chatbot Service │
│ (Vite App) │ │ (Port 8085) │ │ (Port 8081) │
└───────────────────┘ └─────────┬─────────┘ └───────────────────┘
│
▼
┌───────────────────┐ ┌───────────────────┐
│ Python Gateway │◄──┤ Telegram Bot & │
│ (Port 8082) │ │ Discord Bot │
└───────────────────┘ └───────────────────┘
```
See the [Oxlint rules documentation](https://oxc.rs/docs/guide/usage/linter/rules) for the full list of rules and categories.
### Stack Components:
1. **Frontend**: React, TypeScript, Vite, Tailwind CSS, Leaflet Maps, and Framer Motion.
2. **Core API Backend**: Spring Boot, Java 21, Hibernate/JPA, and PostgreSQL.
3. **Go Chatbot Engine**: Go microservice performing spelling correction (Levenshtein Distance) and BM25 ranking queries.
4. **Python Bot Gateway**: FastAPI HTTP listener interfacing with Telegram and Discord bot APIs.
---
## ⚙️ Service Ports & Deployments
| Component | Dev Port | Production Port | Daemon Service | Description |
| :--- | :---: | :---: | :---: | :--- |
| **React App** | `5173` | `80` / `443` | `nginx` | Frontend web client |
| **Spring Boot API** | `8085` | `8085` | `springboot` | Core business logic & database API |
| **Go Chatbot API** | `8081` | `8081` | `chatbot` | Keyword lookup & campus Q&A engine |
| **Python Bot Server** | `8082` | `8082` | `telegram-bot` | Telegram/Discord webhook router |
| **PostgreSQL Database** | `5432` | `5432` | `postgresql` | Primary database cluster |
---
## 📑 Feature Documentation Directories
For full functional breakdowns, REST API schemas, and technical setup guides for each platform feature, refer to the guides inside [docs/features/](file:///c:/Users/deves/OneDrive/project_main/Freshers-Hub/docs/features):
- 📚 **[Academic Resources Sync](file:///c:/Users/deves/OneDrive/project_main/Freshers-Hub/docs/features/academic_resources.md)**: Syncs static uploads on the VPS directly to database catalog endpoints.
- 🛠️ **[Interactive Student Toolkit](file:///c:/Users/deves/OneDrive/project_main/Freshers-Hub/docs/features/student_toolkit.md)**: Contains SGPA/CGPA formulas and college internal marks calculation algorithms.
- 🚌 **[Live Bus GPS Tracking](file:///c:/Users/deves/OneDrive/project_main/Freshers-Hub/docs/features/live_bus_tracking.md)**: Renders live bus coordinates with custom Leaflet overlays and static JSON fail-safes.
- 🤖 **[AI Chatbot Microservice](file:///c:/Users/deves/OneDrive/project_main/Freshers-Hub/docs/features/ai_chatbot_engine.md)**: Custom Go BM25 NLP search engine and spelling correction pipeline details.
- 💬 **[Moderated Q&A Forum](file:///c:/Users/deves/OneDrive/project_main/Freshers-Hub/docs/features/community_qa_forum.md)**: Moderation workflow linking student web queries with Telegram Senior Helper channels.
- 🤝 **[Developer Collab Hub](file:///c:/Users/deves/OneDrive/project_main/Freshers-Hub/docs/features/developer_collab_hub.md)**: Project listings filtered by RIT subdomains and linked with Telegram/Discord bot accept/decline callback requests.
- 🏆 **[LeetCode Leaderboard](file:///c:/Users/deves/OneDrive/project_main/Freshers-Hub/docs/features/leetcode_leaderboard.md)**: LeetCode GraphQL polling details using spaced request queues to avoid rate limit bans.
- 🗺️ **[Interactive Campus Blueprint](file:///c:/Users/deves/OneDrive/project_main/Freshers-Hub/docs/features/campus_map.md)**: Percentage-based blueprint vector coordinates system.
- 👩‍🏫 **[Faculty Directory](file:///c:/Users/deves/OneDrive/project_main/Freshers-Hub/docs/features/faculty_directory.md)**: Unified campus-wide search and sorting directories for RIT professors.
- 🏆 **[Clubs & Centers Explorer](file:///c:/Users/deves/OneDrive/project_main/Freshers-Hub/docs/features/campus_events.md)**: Extracurricular search matching tool with a built-in interest matching quiz.
- 🚀 **[RAISE Incubator Landing](file:///c:/Users/deves/OneDrive/project_main/Freshers-Hub/docs/features/raise_incubator.md)**: Startup slot pitch reservation system.
- 🔑 **[Admin Panel & Service Watchdog](file:///c:/Users/deves/OneDrive/project_main/Freshers-Hub/docs/features/admin_dashboard.md)**: Operations watchdog script, notification lists, and system health status pipelines.
---
## 🛠️ Verification & Building
To verify that the system compiles successfully after local configurations:
1. **Verify Frontend Build**:
```bash
npm run build
```
2. **Verify Java Backend Compilation**:
```bash
cd backend
./mvnw clean package -DskipTests
```
3. **Verify Go Microservice Compilation**:
```bash
cd chatbot-service
go build -o chatbot
```

View File

@@ -1,8 +1,21 @@
package com.rit.portal.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rit.portal.entity.BusRoute;
import com.rit.portal.entity.BusStop;
import com.rit.portal.entity.CommunityQuestion;
import com.rit.portal.entity.NotePyq;
import com.rit.portal.repository.BusRouteRepository;
import com.rit.portal.repository.BusStopRepository;
import com.rit.portal.repository.CommunityQuestionRepository;
import com.rit.portal.repository.NotePyqRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
@@ -12,26 +25,38 @@ import java.util.*;
@RestController
@RequestMapping("/api/admin")
@CrossOrigin(originPatterns = "*")
public class AdminController {
// Hardcoded credentials - no @Value injection needed
private static final String ADMIN_USER = "ritadmin";
private static final String ADMIN_PASS = "ritadmin2026";
@Autowired
private BusRouteRepository busRouteRepository;
private Path getRecipientsFilePath() {
Path vpsPath = Paths.get("/var/www/freshers-hub/scripts/recipients.txt");
if (vpsPath.getParent() != null && Files.exists(vpsPath.getParent())) {
return vpsPath;
}
Path localPath = Paths.get("scripts/recipients.txt").toAbsolutePath();
if (localPath.getParent() != null && !Files.exists(localPath.getParent())) {
try {
Files.createDirectories(localPath.getParent());
} catch (IOException ignored) {}
}
return localPath;
}
@Autowired
private BusStopRepository busStopRepository;
@Autowired
private NotePyqRepository notePyqRepository;
@Autowired
private CommunityQuestionRepository communityQuestionRepository;
@Value("${admin.transport.username:Transport}")
private String transportUsername;
@Value("${admin.transport.password:RIT@2026}")
private String transportPassword;
@Value("${admin.super.username:Admin}")
private String superAdminUsername;
@Value("${admin.super.password:RIT@2026}")
private String superAdminPassword;
private final ObjectMapper objectMapper = new ObjectMapper();
// ─────────────────────────────────────────────────────────────
// 1. MULTI-ROLE ADMIN AUTHENTICATION
// ─────────────────────────────────────────────────────────────
@PostMapping("/login")
public ResponseEntity<Map<String, Object>> login(@RequestBody Map<String, Object> payload) {
Map<String, Object> response = new HashMap<>();
@@ -46,27 +71,337 @@ public class AdminController {
if (p != null) inputPass = p.toString().trim();
}
if (ADMIN_USER.equalsIgnoreCase(inputUser) && ADMIN_PASS.equals(inputPass)) {
// 1. Check Transport Admin ("Transport" / "RIT@2026")
if (transportUsername.equalsIgnoreCase(inputUser) && transportPassword.equals(inputPass)) {
response.put("success", true);
response.put("message", "Admin login successful");
response.put("token", "ADMIN_SESSION_TOKEN_RIT_2026");
} else {
response.put("success", false);
response.put("message", "Invalid admin credentials");
}
response.put("role", "ROLE_TRANSPORT");
response.put("username", "Transport Admin");
response.put("token", "TRANSPORT_SESSION_TOKEN_RIT_2026");
response.put("message", "Transport admin login successful");
return ResponseEntity.ok(response);
}
// 2. Check Super Admin ("Admin" / "RIT@2026" or "ritadmin" / "ritadmin2026")
if ((superAdminUsername.equalsIgnoreCase(inputUser) && superAdminPassword.equals(inputPass)) ||
("ritadmin".equalsIgnoreCase(inputUser) && "ritadmin2026".equals(inputPass))) {
response.put("success", true);
response.put("role", "ROLE_SUPER_ADMIN");
response.put("username", "Super Admin");
response.put("token", "ADMIN_SESSION_TOKEN_RIT_2026");
response.put("message", "Super admin login successful");
return ResponseEntity.ok(response);
}
response.put("success", false);
response.put("message", "Invalid credentials. Use 'Transport' or 'Admin' with password 'RIT@2026'.");
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
} catch (Exception e) {
response.put("success", false);
response.put("message", "Login error: " + e.getMessage());
return ResponseEntity.ok(response);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
}
}
// ─────────────────────────────────────────────────────────────
// 2. TRANSPORT & BUS FLEET MANAGEMENT
// ─────────────────────────────────────────────────────────────
@GetMapping("/transport/routes")
public ResponseEntity<List<BusRoute>> getAllTransportRoutes() {
return ResponseEntity.ok(busRouteRepository.findAll());
}
@PostMapping("/transport/routes")
public ResponseEntity<?> createBusRoute(@RequestBody Map<String, Object> routeData) {
try {
String number = (String) routeData.get("number");
String name = (String) routeData.get("name");
String from = (String) routeData.get("from");
String to = (String) routeData.get("to");
String departureTime = (String) routeData.get("departureTime");
String arrivalTime = (String) routeData.get("arrivalTime");
String color = (String) routeData.getOrDefault("color", "#FF6B00");
if (number == null || name == null || from == null || to == null) {
return ResponseEntity.badRequest().body(Map.of("error", "Missing required route fields"));
}
BusRoute newRoute = BusRoute.builder()
.number(number.trim().toUpperCase())
.name(name.trim())
.from(from.trim())
.to(to.trim())
.departureTime(departureTime != null ? departureTime : "07:00 AM")
.arrivalTime(arrivalTime != null ? arrivalTime : "08:30 AM")
.color(color)
.stops(new ArrayList<>())
.build();
// Save parent route first
BusRoute saved = busRouteRepository.save(newRoute);
// Handle nested stops
Object stopsObj = routeData.get("stops");
if (stopsObj instanceof List<?> rawStops) {
int order = 1;
for (Object item : rawStops) {
if (item instanceof Map<?, ?> stopMap) {
String stopName = (String) stopMap.get("name");
String time = (String) stopMap.get("time");
if (stopName != null && !stopName.isBlank()) {
BusStop stop = BusStop.builder()
.route(saved)
.name(stopName.trim())
.time(time != null ? time.trim() : "07:30 AM")
.stopOrder(order++)
.build();
busStopRepository.save(stop);
saved.getStops().add(stop);
}
}
}
}
return ResponseEntity.status(HttpStatus.CREATED).body(saved);
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Map.of("error", "Failed to create route: " + e.getMessage()));
}
}
@PutMapping("/transport/routes/{id}")
public ResponseEntity<?> updateBusRoute(@PathVariable Integer id, @RequestBody Map<String, Object> routeData) {
Optional<BusRoute> optionalRoute = busRouteRepository.findById(id);
if (optionalRoute.isEmpty()) {
return ResponseEntity.notFound().build();
}
try {
BusRoute route = optionalRoute.get();
if (routeData.containsKey("number")) route.setNumber(((String) routeData.get("number")).trim().toUpperCase());
if (routeData.containsKey("name")) route.setName(((String) routeData.get("name")).trim());
if (routeData.containsKey("from")) route.setFrom(((String) routeData.get("from")).trim());
if (routeData.containsKey("to")) route.setTo(((String) routeData.get("to")).trim());
if (routeData.containsKey("departureTime")) route.setDepartureTime((String) routeData.get("departureTime"));
if (routeData.containsKey("arrivalTime")) route.setArrivalTime((String) routeData.get("arrivalTime"));
if (routeData.containsKey("color")) route.setColor((String) routeData.get("color"));
// Clear old stops and replace
if (routeData.containsKey("stops")) {
Object stopsObj = routeData.get("stops");
if (stopsObj instanceof List<?> rawStops) {
route.getStops().clear();
busRouteRepository.save(route);
int order = 1;
for (Object item : rawStops) {
if (item instanceof Map<?, ?> stopMap) {
String stopName = (String) stopMap.get("name");
String time = (String) stopMap.get("time");
if (stopName != null && !stopName.isBlank()) {
BusStop stop = BusStop.builder()
.route(route)
.name(stopName.trim())
.time(time != null ? time.trim() : "07:30 AM")
.stopOrder(order++)
.build();
busStopRepository.save(stop);
route.getStops().add(stop);
}
}
}
}
}
BusRoute saved = busRouteRepository.save(route);
return ResponseEntity.ok(saved);
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Map.of("error", "Failed to update route: " + e.getMessage()));
}
}
@DeleteMapping("/transport/routes/{id}")
public ResponseEntity<?> deleteBusRoute(@PathVariable Integer id) {
if (!busRouteRepository.existsById(id)) {
return ResponseEntity.notFound().build();
}
busRouteRepository.deleteById(id);
return ResponseEntity.ok(Map.of("message", "Route deleted successfully"));
}
// ─────────────────────────────────────────────────────────────
// 3. TELEGRAM BOT Q&A "SENIORS" & CONFIGURATION MANAGEMENT
// ─────────────────────────────────────────────────────────────
private Path getTelegramConfigPath() {
// Priority 1: Production VPS path
Path vpsPath = Paths.get("/var/www/freshers-hub/telegram-bot/config.json");
if (Files.exists(vpsPath)) {
return vpsPath;
}
// Priority 2: Local relative directory
Path localPath1 = Paths.get("telegram-bot/config.json").toAbsolutePath();
if (Files.exists(localPath1)) {
return localPath1;
}
Path localPath2 = Paths.get("../telegram-bot/config.json").toAbsolutePath();
if (Files.exists(localPath2)) {
return localPath2;
}
return localPath1;
}
@SuppressWarnings("unchecked")
private Map<String, Object> readTelegramConfigFile() {
Path path = getTelegramConfigPath();
if (Files.exists(path)) {
try {
byte[] bytes = Files.readAllBytes(path);
return objectMapper.readValue(bytes, Map.class);
} catch (Exception e) {
e.printStackTrace();
}
}
Map<String, Object> defaultCfg = new HashMap<>();
defaultCfg.put("community_bot_token", "");
defaultCfg.put("telegram_bot_token", "");
defaultCfg.put("helper_chat_ids", new ArrayList<Long>(List.of(971749136L, 5567776672L, 1873240361L)));
defaultCfg.put("spring_backend_url", "http://localhost:8085");
return defaultCfg;
}
private void saveTelegramConfigFile(Map<String, Object> config) {
Path path = getTelegramConfigPath();
try {
if (path.getParent() != null && !Files.exists(path.getParent())) {
Files.createDirectories(path.getParent());
}
objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File(path.toString()), config);
} catch (Exception e) {
e.printStackTrace();
}
}
@GetMapping("/telegram/config")
public ResponseEntity<Map<String, Object>> getTelegramConfig() {
return ResponseEntity.ok(readTelegramConfigFile());
}
@PutMapping("/telegram/config")
public ResponseEntity<?> updateTelegramConfig(@RequestBody Map<String, Object> payload) {
Map<String, Object> current = readTelegramConfigFile();
if (payload.containsKey("community_bot_token")) current.put("community_bot_token", payload.get("community_bot_token"));
if (payload.containsKey("telegram_bot_token")) current.put("telegram_bot_token", payload.get("telegram_bot_token"));
if (payload.containsKey("spring_backend_url")) current.put("spring_backend_url", payload.get("spring_backend_url"));
saveTelegramConfigFile(current);
return ResponseEntity.ok(Map.of("success", true, "config", current));
}
@PostMapping("/telegram/helpers")
public ResponseEntity<?> addSeniorHelper(@RequestBody Map<String, Object> payload) {
Object chatIdObj = payload.get("chatId");
if (chatIdObj == null) {
return ResponseEntity.badRequest().body(Map.of("error", "chatId is required"));
}
Long chatId;
try {
chatId = Long.parseLong(chatIdObj.toString().trim());
} catch (NumberFormatException e) {
return ResponseEntity.badRequest().body(Map.of("error", "chatId must be a valid integer number"));
}
Map<String, Object> config = readTelegramConfigFile();
@SuppressWarnings("unchecked")
List<Object> rawHelpers = (List<Object>) config.getOrDefault("helper_chat_ids", new ArrayList<>());
List<Long> helpers = new ArrayList<>();
for (Object o : rawHelpers) {
helpers.add(Long.parseLong(o.toString()));
}
if (!helpers.contains(chatId)) {
helpers.add(chatId);
config.put("helper_chat_ids", helpers);
saveTelegramConfigFile(config);
}
return ResponseEntity.ok(Map.of("success", true, "helpers", helpers));
}
@DeleteMapping("/telegram/helpers/{chatId}")
public ResponseEntity<?> removeSeniorHelper(@PathVariable Long chatId) {
Map<String, Object> config = readTelegramConfigFile();
@SuppressWarnings("unchecked")
List<Object> rawHelpers = (List<Object>) config.getOrDefault("helper_chat_ids", new ArrayList<>());
List<Long> helpers = new ArrayList<>();
for (Object o : rawHelpers) {
helpers.add(Long.parseLong(o.toString()));
}
boolean removed = helpers.removeIf(id -> id.equals(chatId));
if (removed) {
config.put("helper_chat_ids", helpers);
saveTelegramConfigFile(config);
}
return ResponseEntity.ok(Map.of("success", true, "helpers", helpers));
}
// ─────────────────────────────────────────────────────────────
// 4. NOTES & PYQS STUDY MATERIALS MODERATION
// ─────────────────────────────────────────────────────────────
@GetMapping("/notes")
public ResponseEntity<List<NotePyq>> getAllNotes() {
return ResponseEntity.ok(notePyqRepository.findAll());
}
@DeleteMapping("/notes/{id}")
public ResponseEntity<?> deleteNote(@PathVariable Integer id) {
if (!notePyqRepository.existsById(id)) {
return ResponseEntity.notFound().build();
}
notePyqRepository.deleteById(id);
return ResponseEntity.ok(Map.of("message", "Note deleted successfully"));
}
// ─────────────────────────────────────────────────────────────
// 5. COMMUNITY QUESTIONS MODERATION
// ─────────────────────────────────────────────────────────────
@GetMapping("/questions")
public ResponseEntity<List<CommunityQuestion>> getAllQuestions() {
return ResponseEntity.ok(communityQuestionRepository.findAll());
}
@DeleteMapping("/questions/{id}")
public ResponseEntity<?> deleteQuestion(@PathVariable Integer id) {
if (!communityQuestionRepository.existsById(id)) {
return ResponseEntity.notFound().build();
}
communityQuestionRepository.deleteById(id);
return ResponseEntity.ok(Map.of("message", "Question deleted successfully"));
}
// ─────────────────────────────────────────────────────────────
// 6. DEPLOYMENT RECIPIENTS (GIT PUSH HEALTH NOTIFICATIONS)
// ─────────────────────────────────────────────────────────────
private Path getRecipientsFilePath() {
Path vpsPath = Paths.get("/var/www/freshers-hub/scripts/recipients.txt");
if (vpsPath.getParent() != null && Files.exists(vpsPath.getParent())) {
return vpsPath;
}
Path localPath = Paths.get("scripts/recipients.txt").toAbsolutePath();
if (localPath.getParent() != null && !Files.exists(localPath.getParent())) {
try {
Files.createDirectories(localPath.getParent());
} catch (IOException ignored) {}
}
return localPath;
}
@GetMapping("/recipients")
public ResponseEntity<List<String>> getRecipients() {
Path path = getRecipientsFilePath();
List<String> recipients = getRecipientsList(path);
return ResponseEntity.ok(recipients);
return ResponseEntity.ok(getRecipientsList(path));
}
@PostMapping("/recipients")

View File

@@ -0,0 +1,98 @@
package com.rit.portal.controller;
import com.rit.portal.entity.ClubLike;
import com.rit.portal.repository.ClubLikeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
@RestController
@RequestMapping("/api/clubs")
@CrossOrigin(origins = "*")
public class ClubController {
@Autowired
private ClubLikeRepository clubLikeRepository;
/**
* Get total count of likes for all clubs & centers
*/
@GetMapping("/likes")
public ResponseEntity<Map<String, Long>> getAllClubLikes() {
List<Object[]> results = clubLikeRepository.countAllGroupedByClubId();
Map<String, Long> likesMap = new HashMap<>();
for (Object[] result : results) {
String clubId = (String) result[0];
Long count = (Long) result[1];
likesMap.put(clubId, count);
}
return ResponseEntity.ok(likesMap);
}
/**
* Get list of club IDs liked by a specific user or device
*/
@GetMapping("/user-likes")
public ResponseEntity<List<String>> getUserLikedClubs(@RequestParam("userIdentifier") String userIdentifier) {
if (userIdentifier == null || userIdentifier.isBlank()) {
return ResponseEntity.ok(Collections.emptyList());
}
List<ClubLike> likes = clubLikeRepository.findByUserIdentifier(userIdentifier);
List<String> likedClubIds = likes.stream()
.map(ClubLike::getClubId)
.collect(Collectors.toList());
return ResponseEntity.ok(likedClubIds);
}
/**
* Toggle like state for a club/center by a user or device
*/
@PostMapping("/{clubId}/like")
@Transactional
public ResponseEntity<Map<String, Object>> toggleClubLike(
@PathVariable("clubId") String clubId,
@RequestBody(required = false) Map<String, String> payload,
@RequestParam(value = "userIdentifier", required = false) String paramUserIdentifier) {
String userIdentifier = null;
if (payload != null && payload.containsKey("userIdentifier")) {
userIdentifier = payload.get("userIdentifier");
}
if ((userIdentifier == null || userIdentifier.isBlank()) && paramUserIdentifier != null) {
userIdentifier = paramUserIdentifier;
}
if (userIdentifier == null || userIdentifier.isBlank()) {
userIdentifier = "anonymous_guest";
}
Optional<ClubLike> existingLike = clubLikeRepository.findByClubIdAndUserIdentifier(clubId, userIdentifier);
boolean isNowLiked;
if (existingLike.isPresent()) {
clubLikeRepository.delete(existingLike.get());
isNowLiked = false;
} else {
ClubLike newLike = ClubLike.builder()
.clubId(clubId)
.userIdentifier(userIdentifier)
.createdAt(LocalDateTime.now())
.build();
clubLikeRepository.save(newLike);
isNowLiked = true;
}
long newCount = clubLikeRepository.countByClubId(clubId);
Map<String, Object> response = new HashMap<>();
response.put("clubId", clubId);
response.put("liked", isNowLiked);
response.put("count", newCount);
return ResponseEntity.ok(response);
}
}

View File

@@ -0,0 +1,75 @@
package com.rit.portal.controller;
import com.rit.portal.dto.ims.StudentDashboardDto.*;
import com.rit.portal.service.ims.ImsClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/v1/ims")
public class StudentDashboardController {
@Autowired
private ImsClient imsClient;
/**
* POST /api/v1/ims/auth/login
* Authenticates student via Register Number (e.g. 2114251001) and Password.
*/
@PostMapping("/auth/login")
public ResponseEntity<ImsLoginResponse> loginWithIms(@RequestBody ImsLoginRequest request) {
ImsLoginResponse response = imsClient.authenticate(request.getRegNumber(), request.getPassword());
if (!response.isSuccess()) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
}
return ResponseEntity.ok(response);
}
/**
* GET /api/v1/ims/auth/mock-users
* Returns pre-configured mock student credentials for instant testing.
*/
@GetMapping("/auth/mock-users")
public ResponseEntity<List<MockUserCredentialDto>> getMockUsers() {
return ResponseEntity.ok(imsClient.getAvailableMockUsers());
}
/**
* Helper to resolve the student's register number from email, header, or param.
*/
private String resolveStudentId(String regNumber, String userEmail) {
if (regNumber != null && !regNumber.isBlank()) {
return regNumber.trim();
}
if (userEmail != null && !userEmail.isBlank()) {
String digits = userEmail.split("@")[0].replaceAll("[^0-9]", "");
return digits.isEmpty() ? "2114251001" : digits;
}
return "2114251001";
}
/**
* GET /api/v1/ims/dashboard/me
* Returns: Timetable of the day, Class Location, Class Teachers, Student & Dept Info
*/
@GetMapping("/dashboard/me")
public ResponseEntity<DashboardResponse> getMyDashboard(
@RequestParam(required = false) String regNumber,
@RequestParam(required = false) String email,
@RequestHeader(value = "X-IMS-Student-Id", required = false) String headerStudentId,
@RequestHeader(value = "X-Dev-Student-Id", required = false) String devStudentOverride) {
String studentId = (devStudentOverride != null && !devStudentOverride.isBlank())
? devStudentOverride
: (headerStudentId != null && !headerStudentId.isBlank())
? headerStudentId
: resolveStudentId(regNumber, email);
DashboardResponse response = imsClient.getStudentDashboard(studentId);
return ResponseEntity.ok(response);
}
}

View File

@@ -0,0 +1,133 @@
package com.rit.portal.dto.ims;
import lombok.*;
import java.time.LocalDate;
import java.util.List;
public class StudentDashboardDto {
// ─── 0. IMS Authentication DTOs ──────────────────────────────
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public static class ImsLoginRequest {
private String regNumber; // e.g. "2114251001" or "251001"
private String password; // e.g. "rit@2026"
}
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public static class ImsLoginResponse {
private boolean success;
private String message;
private String token; // IMS Session / Bearer Token
private StudentInfo student;
}
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public static class MockUserCredentialDto {
private String regNumber;
private String defaultPassword;
private String studentName;
private String department;
private String section;
}
// ─── 1. Student & Department Details ─────────────────────────
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public static class StudentInfo {
private String studentId; // e.g. "2114251001" or "251001"
private String regNumber; // e.g. "2114251001"
private String name; // e.g. "Anbu Kathir"
private String email; // e.g. "251001@ritchennai.edu.in"
private String degree; // e.g. "B.E."
private String department; // e.g. "Computer Science & Engineering"
private String departmentCode; // e.g. "CSE"
private int year; // e.g. 1
private int semester; // e.g. 2
private String section; // e.g. "A"
private String batch; // e.g. "2025 - 2029"
private String regulation; // e.g. "2021 Regulation"
}
// ─── 2. Class & Campus Location ─────────────────────────────
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public static class ClassLocationInfo {
private String roomNumber; // e.g. "LH-204"
private String buildingName; // e.g. "Dr. APJ Abdul Kalam Academic Block"
private String floor; // e.g. "2nd Floor"
private String wing; // e.g. "East Wing"
private String landmark; // e.g. "Next to CSE Department Library, Opposite to Seminar Hall"
}
// ─── 3. Faculty / Staff for this Class ───────────────────────
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public static class ClassFacultyMember {
private String subjectCode; // e.g. "CS3201"
private String subjectName; // e.g. "Data Structures & Algorithms"
private String facultyName; // e.g. "Dr. R. Arunkumar"
private String designation; // e.g. "Associate Professor"
private String email; // e.g. "arunkumar.r@ritchennai.edu.in"
private String officeLocation; // e.g. "APJ Block, Cabin 208-B"
private String phoneExtension; // e.g. "Ext. 312"
private String avatarUrl; // Optional photo
private boolean isClassIncharge; // true if Class Incharge
}
// ─── 4. Timetable Period ─────────────────────────────────────
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public static class TimetablePeriod {
private int periodNumber; // 1 to 6
private String timeSlot; // e.g. "08:45 AM - 09:40 AM"
private String startTime; // "08:45"
private String endTime; // "09:40"
private String subjectCode; // "CS3201"
private String subjectName; // "Data Structures & Algorithms"
private String type; // "THEORY" | "LAB" | "TUTORIAL" | "LIBRARY"
private String facultyName; // "Dr. R. Arunkumar"
private String venue; // "LH-204" or "CC-03 Lab"
private String status; // "UPCOMING" | "ONGOING" | "COMPLETED"
}
// ─── 5. Daily Timetable ──────────────────────────────────────
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public static class DaySchedule {
private String dayOfWeek; // "MONDAY", "TUESDAY", etc.
private LocalDate date;
private List<TimetablePeriod> periods;
}
// ─── Complete Dashboard Aggregate ────────────────────────────
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public static class DashboardResponse {
private StudentInfo student;
private ClassLocationInfo classLocation;
private List<ClassFacultyMember> facultyList;
private DaySchedule todaySchedule;
private boolean isMockData;
}
}

View File

@@ -0,0 +1,31 @@
package com.rit.portal.entity;
import jakarta.persistence.*;
import lombok.*;
import java.time.LocalDateTime;
@Entity
@Table(name = "club_likes", uniqueConstraints = {
@UniqueConstraint(name = "unique_club_user_like", columnNames = {"club_id", "user_identifier"})
})
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class ClubLike {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "club_id", nullable = false, length = 100)
private String clubId;
@Column(name = "user_identifier", nullable = false, length = 255)
private String userIdentifier;
@Column(name = "created_at")
@Builder.Default
private LocalDateTime createdAt = LocalDateTime.now();
}

View File

@@ -0,0 +1,23 @@
package com.rit.portal.repository;
import com.rit.portal.entity.ClubLike;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
@Repository
public interface ClubLikeRepository extends JpaRepository<ClubLike, Long> {
Optional<ClubLike> findByClubIdAndUserIdentifier(String clubId, String userIdentifier);
boolean existsByClubIdAndUserIdentifier(String clubId, String userIdentifier);
long countByClubId(String clubId);
List<ClubLike> findByUserIdentifier(String userIdentifier);
@Query("SELECT c.clubId, COUNT(c) FROM ClubLike c GROUP BY c.clubId")
List<Object[]> countAllGroupedByClubId();
}

View File

@@ -0,0 +1,15 @@
package com.rit.portal.service.ims;
import com.rit.portal.dto.ims.StudentDashboardDto.*;
import java.time.LocalDate;
import java.util.List;
public interface ImsClient {
ImsLoginResponse authenticate(String regNumber, String password);
List<MockUserCredentialDto> getAvailableMockUsers();
DashboardResponse getStudentDashboard(String studentId);
StudentInfo getStudentInfo(String studentId);
ClassLocationInfo getClassLocation(String department, String section, int semester);
List<ClassFacultyMember> getClassFaculty(String department, String section, int semester);
DaySchedule getDaySchedule(String studentId, LocalDate date);
}

View File

@@ -0,0 +1,441 @@
package com.rit.portal.service.ims;
import com.rit.portal.dto.ims.StudentDashboardDto.*;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.*;
@Service
@ConditionalOnProperty(name = "ims.client.type", havingValue = "mock", matchIfMissing = true)
public class MockImsClientImpl implements ImsClient {
private final Map<String, StudentInfo> studentDb = new HashMap<>();
private final Map<String, String> userPasswords = new HashMap<>();
private final Map<String, ClassLocationInfo> locationDb = new HashMap<>();
private final Map<String, List<ClassFacultyMember>> facultyDb = new HashMap<>();
private final List<MockUserCredentialDto> mockUserList = new ArrayList<>();
public MockImsClientImpl() {
seedMockData();
}
private void seedMockData() {
// ─────────────────────────────────────────────────────────────
// 1. MOCK STUDENT 1: 2114251001 (CSE - Section A, Year 1, Sem 2)
// ─────────────────────────────────────────────────────────────
StudentInfo s1 = StudentInfo.builder()
.studentId("2114251001")
.regNumber("2114251001")
.name("Anbu Kathir")
.email("251001@ritchennai.edu.in")
.degree("B.E.")
.department("Computer Science & Engineering")
.departmentCode("CSE")
.year(1)
.semester(2)
.section("A")
.batch("2025 - 2029")
.regulation("2021 Regulation")
.build();
studentDb.put("2114251001", s1);
studentDb.put("251001", s1);
userPasswords.put("2114251001", "rit@2026");
userPasswords.put("251001", "rit@2026");
mockUserList.add(MockUserCredentialDto.builder()
.regNumber("2114251001")
.defaultPassword("rit@2026")
.studentName("Anbu Kathir")
.department("Computer Science & Engineering")
.section("Sec A")
.build());
locationDb.put("CSE_A_2", ClassLocationInfo.builder()
.roomNumber("LH-204")
.buildingName("Dr. APJ Abdul Kalam Academic Block")
.floor("2nd Floor")
.wing("East Wing")
.landmark("Next to CSE Department Library, Opposite to Seminar Hall")
.build());
facultyDb.put("CSE_A_2", List.of(
ClassFacultyMember.builder()
.subjectCode("CS3201")
.subjectName("Data Structures & Algorithms")
.facultyName("Dr. R. Arunkumar")
.designation("Associate Professor & Class Incharge")
.email("arunkumar.r@ritchennai.edu.in")
.officeLocation("APJ Block, Cabin 208-B")
.phoneExtension("Ext. 312")
.avatarUrl("https://api.dicebear.com/7.x/avataaars/svg?seed=Arunkumar")
.isClassIncharge(true)
.build(),
ClassFacultyMember.builder()
.subjectCode("MA3251")
.subjectName("Discrete Mathematics")
.facultyName("Dr. S. Malathi")
.designation("Professor (Mathematics)")
.email("malathi.s@ritchennai.edu.in")
.officeLocation("Science & Humanities Block, 1st Floor")
.phoneExtension("Ext. 118")
.avatarUrl("https://api.dicebear.com/7.x/avataaars/svg?seed=Malathi")
.isClassIncharge(false)
.build(),
ClassFacultyMember.builder()
.subjectCode("CS3202")
.subjectName("Digital Principles & System Design")
.facultyName("Dr. M. Balaji")
.designation("Assistant Professor")
.email("balaji.m@ritchennai.edu.in")
.officeLocation("APJ Block, Cabin 104")
.phoneExtension("Ext. 325")
.avatarUrl("https://api.dicebear.com/7.x/avataaars/svg?seed=Balaji")
.isClassIncharge(false)
.build(),
ClassFacultyMember.builder()
.subjectCode("GE3251")
.subjectName("Environmental Sciences & Sustainability")
.facultyName("Dr. T. Gayathri")
.designation("Assistant Professor (Chemistry)")
.email("gayathri.t@ritchennai.edu.in")
.officeLocation("Science Block, Chemistry Cabin 3")
.phoneExtension("Ext. 142")
.avatarUrl("https://api.dicebear.com/7.x/avataaars/svg?seed=Gayathri")
.isClassIncharge(false)
.build(),
ClassFacultyMember.builder()
.subjectCode("CS3271")
.subjectName("Data Structures Laboratory")
.facultyName("Dr. R. Arunkumar / Dr. K. Revathi")
.designation("Lab In-Charges")
.email("lab.cse@ritchennai.edu.in")
.officeLocation("Computing Center 3 (CC-03)")
.phoneExtension("Ext. 330")
.avatarUrl("https://api.dicebear.com/7.x/avataaars/svg?seed=Revathi")
.isClassIncharge(false)
.build()
));
// ─────────────────────────────────────────────────────────────
// 2. MOCK STUDENT 2: 2114251002 (AI&DS - Section B, Year 1, Sem 2)
// ─────────────────────────────────────────────────────────────
StudentInfo s2 = StudentInfo.builder()
.studentId("2114251002")
.regNumber("2114251002")
.name("Priyadharshini M")
.email("251002@ritchennai.edu.in")
.degree("B.Tech.")
.department("Artificial Intelligence & Data Science")
.departmentCode("AIDS")
.year(1)
.semester(2)
.section("B")
.batch("2025 - 2029")
.regulation("2021 Regulation")
.build();
studentDb.put("2114251002", s2);
studentDb.put("251002", s2);
userPasswords.put("2114251002", "rit@2026");
userPasswords.put("251002", "rit@2026");
mockUserList.add(MockUserCredentialDto.builder()
.regNumber("2114251002")
.defaultPassword("rit@2026")
.studentName("Priyadharshini M")
.department("AI & Data Science")
.section("Sec B")
.build());
locationDb.put("AIDS_B_2", ClassLocationInfo.builder()
.roomNumber("LH-301")
.buildingName("Sir Isaac Newton Innovation Block")
.floor("3rd Floor")
.wing("North Wing")
.landmark("Opposite AI Centre of Excellence, Near Lift Lobby")
.build());
facultyDb.put("AIDS_B_2", List.of(
ClassFacultyMember.builder()
.subjectCode("AD3251")
.subjectName("Data Structures Design")
.facultyName("Dr. N. Saravanan")
.designation("Associate Professor & Class Incharge")
.email("saravanan.n@ritchennai.edu.in")
.officeLocation("Newton Block, Cabin 302")
.phoneExtension("Ext. 401")
.avatarUrl("https://api.dicebear.com/7.x/avataaars/svg?seed=Saravanan")
.isClassIncharge(true)
.build(),
ClassFacultyMember.builder()
.subjectCode("AD3252")
.subjectName("Foundations of Artificial Intelligence")
.facultyName("Prof. J. Daniel")
.designation("Assistant Professor")
.email("daniel.j@ritchennai.edu.in")
.officeLocation("Newton Block, Cabin 306")
.phoneExtension("Ext. 405")
.avatarUrl("https://api.dicebear.com/7.x/avataaars/svg?seed=Daniel")
.isClassIncharge(false)
.build(),
ClassFacultyMember.builder()
.subjectCode("MA3251")
.subjectName("Probability and Statistics")
.facultyName("Dr. V. Lakshmi")
.designation("Professor (Mathematics)")
.email("lakshmi.v@ritchennai.edu.in")
.officeLocation("Science Block, Cabin 108")
.phoneExtension("Ext. 119")
.avatarUrl("https://api.dicebear.com/7.x/avataaars/svg?seed=Lakshmi")
.isClassIncharge(false)
.build()
));
// ─────────────────────────────────────────────────────────────
// 3. MOCK STUDENT 3: 2114251003 (ECE - Section A, Year 1, Sem 2)
// ─────────────────────────────────────────────────────────────
StudentInfo s3 = StudentInfo.builder()
.studentId("2114251003")
.regNumber("2114251003")
.name("Rahul V")
.email("251003@ritchennai.edu.in")
.degree("B.E.")
.department("Electronics & Communication Engineering")
.departmentCode("ECE")
.year(1)
.semester(2)
.section("A")
.batch("2025 - 2029")
.regulation("2021 Regulation")
.build();
studentDb.put("2114251003", s3);
studentDb.put("251003", s3);
userPasswords.put("2114251003", "rit@2026");
userPasswords.put("251003", "rit@2026");
mockUserList.add(MockUserCredentialDto.builder()
.regNumber("2114251003")
.defaultPassword("rit@2026")
.studentName("Rahul V")
.department("Electronics & Comm. Engg.")
.section("Sec A")
.build());
locationDb.put("ECE_A_2", ClassLocationInfo.builder()
.roomNumber("LH-105")
.buildingName("Rabindranath Tagore Academic Block")
.floor("1st Floor")
.wing("South Wing")
.landmark("Near Department Auditorium")
.build());
facultyDb.put("ECE_A_2", List.of(
ClassFacultyMember.builder()
.subjectCode("EC3251")
.subjectName("Circuit Analysis")
.facultyName("Dr. I. Chandra")
.designation("Professor & Class Incharge")
.email("chandra.i@ritchennai.edu.in")
.officeLocation("Tagore Block, Cabin 112")
.phoneExtension("Ext. 502")
.avatarUrl("https://api.dicebear.com/7.x/avataaars/svg?seed=Chandra")
.isClassIncharge(true)
.build()
));
}
@Override
public ImsLoginResponse authenticate(String regNumber, String password) {
if (regNumber == null || regNumber.isBlank()) {
return ImsLoginResponse.builder()
.success(false)
.message("Register Number is required.")
.build();
}
String cleanedReg = regNumber.trim();
StudentInfo student = studentDb.get(cleanedReg);
if (student == null) {
String digits = cleanedReg.replaceAll("[^0-9]", "");
student = studentDb.get(digits);
}
if (student == null) {
student = StudentInfo.builder()
.studentId(cleanedReg)
.regNumber(cleanedReg)
.name("Student (" + cleanedReg + ")")
.email(cleanedReg + "@ritchennai.edu.in")
.degree("B.E.")
.department("Computer Science & Engineering")
.departmentCode("CSE")
.year(1)
.semester(2)
.section("A")
.batch("2025 - 2029")
.regulation("2021 Regulation")
.build();
studentDb.put(cleanedReg, student);
userPasswords.put(cleanedReg, "rit@2026");
}
String expectedPassword = userPasswords.getOrDefault(cleanedReg, "rit@2026");
boolean isValid = password != null && (
password.equals(expectedPassword) ||
password.equals("rit@2026") ||
password.equals("password") ||
password.equals("123456")
);
if (!isValid) {
return ImsLoginResponse.builder()
.success(false)
.message("Invalid Register Number or Password. Default password: rit@2026")
.build();
}
String token = "ims_session_" + student.getRegNumber() + "_" + UUID.randomUUID().toString().substring(0, 8);
return ImsLoginResponse.builder()
.success(true)
.message("IMS Login Successful")
.token(token)
.student(student)
.build();
}
@Override
public List<MockUserCredentialDto> getAvailableMockUsers() {
return Collections.unmodifiableList(mockUserList);
}
@Override
public DashboardResponse getStudentDashboard(String studentId) {
StudentInfo student = getStudentInfo(studentId);
String classKey = student.getDepartmentCode() + "_" + student.getSection() + "_" + student.getSemester();
ClassLocationInfo location = locationDb.getOrDefault(classKey, locationDb.get("CSE_A_2"));
List<ClassFacultyMember> faculty = facultyDb.getOrDefault(classKey, facultyDb.get("CSE_A_2"));
DaySchedule schedule = getDaySchedule(studentId, LocalDate.now());
return DashboardResponse.builder()
.student(student)
.classLocation(location)
.facultyList(faculty)
.todaySchedule(schedule)
.isMockData(true)
.build();
}
@Override
public StudentInfo getStudentInfo(String studentId) {
if (studentId == null || studentId.isBlank()) {
return studentDb.get("2114251001");
}
String cleaned = studentId.trim();
StudentInfo student = studentDb.get(cleaned);
if (student != null) return student;
String digits = cleaned.replaceAll("[^0-9]", "");
return studentDb.getOrDefault(digits, studentDb.get("2114251001"));
}
@Override
public ClassLocationInfo getClassLocation(String department, String section, int semester) {
String key = department + "_" + section + "_" + semester;
return locationDb.getOrDefault(key, locationDb.get("CSE_A_2"));
}
@Override
public List<ClassFacultyMember> getClassFaculty(String department, String section, int semester) {
String key = department + "_" + section + "_" + semester;
return facultyDb.getOrDefault(key, facultyDb.get("CSE_A_2"));
}
@Override
public DaySchedule getDaySchedule(String studentId, LocalDate date) {
DayOfWeek day = date.getDayOfWeek();
String dayName = (day == DayOfWeek.SATURDAY || day == DayOfWeek.SUNDAY) ? "MONDAY" : day.name();
LocalTime now = LocalTime.now();
List<TimetablePeriod> periods = buildTimetableForDay(studentId, dayName, now);
return DaySchedule.builder()
.dayOfWeek(dayName)
.date(date)
.periods(periods)
.build();
}
private List<TimetablePeriod> buildTimetableForDay(String studentId, String dayOfWeek, LocalTime now) {
List<TimetablePeriod> list = new ArrayList<>();
String[][] slots = {
{"1", "08:45 AM - 09:40 AM", "08:45", "09:40"},
{"2", "09:40 AM - 10:35 AM", "09:40", "10:35"},
{"3", "10:50 AM - 11:45 AM", "10:50", "11:45"},
{"4", "11:45 AM - 12:40 PM", "11:45", "12:40"},
{"5", "01:30 PM - 02:25 PM", "13:30", "14:25"},
{"6", "02:25 PM - 03:20 PM", "14:25", "15:20"}
};
boolean isAids = studentId != null && studentId.contains("251002");
String room = isAids ? "LH-301" : "LH-204";
String lab = isAids ? "AI-02 Lab" : "CC-03 Lab";
String[][] subjects;
if ("WEDNESDAY".equalsIgnoreCase(dayOfWeek) || "FRIDAY".equalsIgnoreCase(dayOfWeek)) {
subjects = new String[][]{
{isAids ? "AD3251" : "CS3201", isAids ? "Data Structures Design" : "Data Structures & Algorithms", "THEORY", isAids ? "Dr. N. Saravanan" : "Dr. R. Arunkumar", room},
{"MA3251", isAids ? "Probability & Stats" : "Discrete Mathematics", "THEORY", isAids ? "Dr. V. Lakshmi" : "Dr. S. Malathi", room},
{isAids ? "AD3271" : "CS3271", isAids ? "AI & DS Practical Lab" : "Data Structures Laboratory", "LAB", isAids ? "Dr. N. Saravanan" : "Dr. R. Arunkumar", lab},
{isAids ? "AD3271" : "CS3271", isAids ? "AI & DS Practical Lab" : "Data Structures Laboratory", "LAB", isAids ? "Dr. N. Saravanan" : "Dr. R. Arunkumar", lab},
{isAids ? "AD3252" : "CS3202", isAids ? "Foundations of AI" : "Digital Principles & System Design", "THEORY", isAids ? "Prof. J. Daniel" : "Dr. M. Balaji", room},
{"GE3251", "Environmental Sciences", "THEORY", "Dr. T. Gayathri", room}
};
} else {
subjects = new String[][]{
{"MA3251", isAids ? "Probability & Stats" : "Discrete Mathematics", "THEORY", isAids ? "Dr. V. Lakshmi" : "Dr. S. Malathi", room},
{isAids ? "AD3251" : "CS3201", isAids ? "Data Structures Design" : "Data Structures & Algorithms", "THEORY", isAids ? "Dr. N. Saravanan" : "Dr. R. Arunkumar", room},
{isAids ? "AD3252" : "CS3202", isAids ? "Foundations of AI" : "Digital Principles & System Design", "THEORY", isAids ? "Prof. J. Daniel" : "Dr. M. Balaji", room},
{"GE3251", "Environmental Sciences", "THEORY", "Dr. T. Gayathri", room},
{isAids ? "AD3251" : "CS3201", isAids ? "AI Problem Solving Tutorial" : "DSA Tutorial & Problem Solving", "TUTORIAL", isAids ? "Dr. N. Saravanan" : "Dr. R. Arunkumar", room},
{"LIB", "Digital Library & Research Hours", "LIBRARY", "Chief Librarian", "Central Library - 2nd Floor"}
};
}
for (int i = 0; i < slots.length; i++) {
LocalTime start = LocalTime.parse(slots[i][2]);
LocalTime end = LocalTime.parse(slots[i][3]);
String status = "UPCOMING";
if (now.isAfter(end)) {
status = "COMPLETED";
} else if (now.isAfter(start) && now.isBefore(end)) {
status = "ONGOING";
}
list.add(TimetablePeriod.builder()
.periodNumber(Integer.parseInt(slots[i][0]))
.timeSlot(slots[i][1])
.startTime(slots[i][2])
.endTime(slots[i][3])
.subjectCode(subjects[i][0])
.subjectName(subjects[i][1])
.type(subjects[i][2])
.facultyName(subjects[i][3])
.venue(subjects[i][4])
.status(status)
.build());
}
return list;
}
}

View File

@@ -0,0 +1,98 @@
package com.rit.portal.service.ims;
import com.rit.portal.dto.ims.StudentDashboardDto.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
@Service
@ConditionalOnProperty(name = "ims.client.type", havingValue = "real")
public class RealImsClientImpl implements ImsClient {
@Value("${ims.base-url:https://api.ims.ritchennai.edu.in}")
private String imsBaseUrl;
@Value("${ims.api-key:}")
private String imsApiKey;
private final RestTemplate restTemplate = new RestTemplate();
private HttpHeaders createHeaders(String studentId) {
HttpHeaders headers = new HttpHeaders();
headers.set("X-Nexus-App-Secret", imsApiKey);
if (studentId != null && !studentId.isBlank()) {
headers.set("X-Student-Id", studentId);
}
headers.set("Accept", "application/json");
return headers;
}
@Override
public ImsLoginResponse authenticate(String regNumber, String password) {
String url = imsBaseUrl + "/api/v1/auth/student-login";
ImsLoginRequest request = ImsLoginRequest.builder()
.regNumber(regNumber)
.password(password)
.build();
HttpEntity<ImsLoginRequest> entity = new HttpEntity<>(request, createHeaders(null));
ResponseEntity<ImsLoginResponse> resp = restTemplate.exchange(url, HttpMethod.POST, entity, ImsLoginResponse.class);
return resp.getBody();
}
@Override
public List<MockUserCredentialDto> getAvailableMockUsers() {
return Collections.emptyList();
}
@Override
public DashboardResponse getStudentDashboard(String studentId) {
String url = imsBaseUrl + "/api/v1/dashboard/me";
HttpEntity<?> entity = new HttpEntity<>(createHeaders(studentId));
ResponseEntity<DashboardResponse> resp = restTemplate.exchange(url, HttpMethod.GET, entity, DashboardResponse.class);
DashboardResponse body = resp.getBody();
if (body != null) {
body.setMockData(false);
}
return body;
}
@Override
public StudentInfo getStudentInfo(String studentId) {
String url = imsBaseUrl + "/api/v1/students/me";
HttpEntity<?> entity = new HttpEntity<>(createHeaders(studentId));
ResponseEntity<StudentInfo> resp = restTemplate.exchange(url, HttpMethod.GET, entity, StudentInfo.class);
return resp.getBody();
}
@Override
public ClassLocationInfo getClassLocation(String department, String section, int semester) {
String url = String.format("%s/api/v1/classes/location?dept=%s&sec=%s&sem=%d", imsBaseUrl, department, section, semester);
HttpEntity<?> entity = new HttpEntity<>(createHeaders(null));
return restTemplate.exchange(url, HttpMethod.GET, entity, ClassLocationInfo.class).getBody();
}
@Override
public List<ClassFacultyMember> getClassFaculty(String department, String section, int semester) {
String url = String.format("%s/api/v1/classes/faculty?dept=%s&sec=%s&sem=%d", imsBaseUrl, department, section, semester);
HttpEntity<?> entity = new HttpEntity<>(createHeaders(null));
ClassFacultyMember[] array = restTemplate.exchange(url, HttpMethod.GET, entity, ClassFacultyMember[].class).getBody();
return array != null ? Arrays.asList(array) : Collections.emptyList();
}
@Override
public DaySchedule getDaySchedule(String studentId, LocalDate date) {
String url = String.format("%s/api/v1/timetable/me?date=%s", imsBaseUrl, date.toString());
HttpEntity<?> entity = new HttpEntity<>(createHeaders(studentId));
return restTemplate.exchange(url, HttpMethod.GET, entity, DaySchedule.class).getBody();
}
}

View File

@@ -1,7 +1,7 @@
# ─── DATABASE CONNECTION CONFIGURATION ───
spring.datasource.url=jdbc:postgresql://localhost:5432/rit_freshers_hub?sslmode=disable
spring.datasource.username=postgres
spring.datasource.password=${DB_PASSWORD:Anbukathir@2006}
spring.datasource.password=${DB_PASSWORD:Amudiesh22@.}
# ─── JPA / HIBERNATE SETTINGS ───
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
@@ -15,6 +15,18 @@ server.port=8085
# ─── GOOGLE OAUTH2 CONFIGURATION ───
google.client.id=${GOOGLE_CLIENT_ID:81935488244-vmab5t8fipfof1n6l7di7eg4fve6k8lf.apps.googleusercontent.com}
# ─── ADMIN PORTAL CREDENTIALS ───
# ─── ADMIN PORTAL MULTI-ROLE CREDENTIALS ───
admin.transport.username=${TRANSPORT_USERNAME:Transport}
admin.transport.password=${TRANSPORT_PASSWORD:RIT@2026}
admin.super.username=${SUPER_ADMIN_USERNAME:Admin}
admin.super.password=${SUPER_ADMIN_PASSWORD:RIT@2026}
admin.username=${ADMIN_USERNAME:ritadmin}
admin.password=${ADMIN_PASSWORD:ritadmin2026}
# ─── IMS INTEGRATION CONFIGURATION ───
# Options: "mock" (active now for testing & simulation) | "real" (for live college IMS)
ims.client.type=mock
ims.base-url=${IMS_BASE_URL:https://api.ims.ritchennai.edu.in}
ims.api-key=${IMS_API_KEY:rit_nexus_vps_secret_key_2026}

28
package-lock.json generated
View File

@@ -102,7 +102,6 @@
"integrity": "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@babel/code-frame": "^7.29.7",
"@babel/generator": "^7.29.7",
@@ -1637,6 +1636,17 @@
"tslib": "^2.4.0"
}
},
"node_modules/@emnapi/runtime": {
"version": "1.11.3",
"resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz",
"integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==",
"dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
"tslib": "^2.4.0"
}
},
"node_modules/@emnapi/wasi-threads": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.2.tgz",
@@ -4422,7 +4432,6 @@
"resolved": "https://registry.npmjs.org/@tanstack/react-query/-/react-query-5.101.3.tgz",
"integrity": "sha512-ZjgcRwmQUSCythDPj6pE2NKFi9bpQegxIBxgt3hPytXI1ElFHNaa3A7aWW8vFaLCIRjPv467rbREYHbxcdgQbg==",
"license": "MIT",
"peer": true,
"dependencies": {
"@tanstack/query-core": "5.101.3"
},
@@ -4508,7 +4517,6 @@
"integrity": "sha512-Dh8vAsV36ig5wa9OX4pXvMc9D3Veibfw2wix0CUwYODLD8nkj9UsLjASr49nPg+2eKzxhBV+v7L8pXvT4e639Q==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"undici-types": "~7.18.0"
}
@@ -4519,7 +4527,6 @@
"integrity": "sha512-MXfmqaVPEVgkBT/aY0aGCkRWWtByiYQXo3xdQ8r5RzuFrPiRn8Gar2tQdXSUQ2GKV3bkXckek89V8wQBY2Q/Aw==",
"devOptional": true,
"license": "MIT",
"peer": true,
"dependencies": {
"csstype": "^3.2.2"
}
@@ -4530,7 +4537,6 @@
"integrity": "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==",
"devOptional": true,
"license": "MIT",
"peer": true,
"peerDependencies": {
"@types/react": "^19.2.0"
}
@@ -4606,7 +4612,6 @@
"integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"fast-deep-equal": "^3.1.3",
"fast-uri": "^3.0.1",
@@ -4865,7 +4870,6 @@
}
],
"license": "MIT",
"peer": true,
"dependencies": {
"baseline-browser-mapping": "^2.10.42",
"caniuse-lite": "^1.0.30001803",
@@ -6541,8 +6545,7 @@
"version": "1.9.4",
"resolved": "https://registry.npmjs.org/leaflet/-/leaflet-1.9.4.tgz",
"integrity": "sha512-nxS1ynzJOmOlHp+iL3FyWqK89GtNL8U8rvlMOsQdTTssxZwCXh8N2NB3GDQOL+YR3XnWyZAxwQixURb+FA74PA==",
"license": "BSD-2-Clause",
"peer": true
"license": "BSD-2-Clause"
},
"node_modules/leven": {
"version": "3.1.0",
@@ -7170,7 +7173,6 @@
}
],
"license": "MIT",
"peer": true,
"dependencies": {
"nanoid": "^3.3.16",
"picocolors": "^1.1.1",
@@ -7214,7 +7216,6 @@
"resolved": "https://registry.npmjs.org/react/-/react-19.2.7.tgz",
"integrity": "sha512-HNe9WslTbXmFK8o8cmwgAeJFSBvt1bPdHCVKtaaV+WlAN36mpT4hcRpwbf3fY56ar2oIXzsBpOAiIRHAdY0OlQ==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=0.10.0"
}
@@ -7224,7 +7225,6 @@
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.7.tgz",
"integrity": "sha512-t0BRVXvbiE/o20Hfw669rLbMCDWtYZLvmJigy2f0MxsXF+71pxhR3xOkspmsO8h3ZlNzyibAmtCa3l4lYKk6gQ==",
"license": "MIT",
"peer": true,
"dependencies": {
"scheduler": "^0.27.0"
},
@@ -7237,7 +7237,6 @@
"resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.82.0.tgz",
"integrity": "sha512-Zw/uFZ2dO+02GHlBn7JFGn8kZJ7LdM33B/0BXOovzFay+CMhf94JMw5BVu+F1tVkUKjNvBuaE3fz5BJhga10Tg==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=18.0.0"
},
@@ -7544,7 +7543,6 @@
"integrity": "sha512-RXOqwaPsBGjMNMa4sQjDjHieHEZDFoj/Rdr46l2MU5DfEs16wHJPC2RPTPHWhNl+M3aI472LLqFkFKut4SblOg==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@types/estree": "1.0.9"
},
@@ -8090,7 +8088,6 @@
"integrity": "sha512-SNiDnXyHSrxVcIOtVbULzcTmniUiwcV7Nwdyj1twVubeTmbjoa8p69KKDpfkdoOavuM4/GRm1+ykI8qqnavHoA==",
"dev": true,
"license": "BSD-2-Clause",
"peer": true,
"dependencies": {
"@jridgewell/source-map": "^0.3.3",
"acorn": "^8.15.0",
@@ -8416,7 +8413,6 @@
"integrity": "sha512-7ULLwsCdYx/nRyrpiEwvqb5TFHrMVZyBt+rg/OAXT7rgj/z+DtTDyKFeLAdDkubDVDKD8jOsndmy7m55XcfUsw==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"lightningcss": "^1.32.0",
"picomatch": "^4.0.5",

Binary file not shown.

Before

Width:  |  Height:  |  Size: 394 KiB

After

Width:  |  Height:  |  Size: 8.8 MiB

View File

@@ -135,3 +135,13 @@ CREATE TABLE IF NOT EXISTS confessions (
reactions_count INT DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- 10. Club & Center Likes Table
CREATE TABLE IF NOT EXISTS club_likes (
id SERIAL PRIMARY KEY,
club_id VARCHAR(100) NOT NULL,
user_identifier VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT unique_club_user_like UNIQUE (club_id, user_identifier)
);

View File

@@ -17,6 +17,7 @@ import DevCollab from '@/pages/DevCollab/DevCollab';
import LeetcodeLeaderboard from '@/pages/LeetcodeLeaderboard/LeetcodeLeaderboard';
import AdminDashboard from '@/pages/Admin/AdminDashboard';
import Raise from '@/pages/Raise/Raise';
import StudentDashboard from '@/pages/StudentDashboard/StudentDashboard';
const queryClient = new QueryClient({
defaultOptions: {
@@ -61,6 +62,9 @@ function App() {
<Route path="/faculty" element={<Faculty />} />
<Route path="/events" element={<Events />} />
{/* Student Dashboard — Timetable, Staff, Location (IMS Reg No & Password) */}
<Route path="/dashboard" element={<StudentDashboard />} />
{/* Protected Routes — Require Google Sign-In */}
<Route
path="/community"

View File

@@ -58,8 +58,7 @@ export function StaggerContainer({
return (
<motion.div
initial="hidden"
whileInView="visible"
viewport={{ once: true, margin: '-50px' }}
animate="visible"
variants={{
hidden: {},
visible: {

View File

@@ -1,7 +1,11 @@
import { useEffect, useRef } from 'react';
import { useEffect, useRef, useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { X, ShieldCheck, Sparkles } from 'lucide-react';
import {
X, ShieldCheck, Sparkles, User, KeyRound,
ArrowRight, AlertCircle, GraduationCap, Bus, Shield
} from 'lucide-react';
import { useAuth } from '@/context/AuthContext';
import { useNavigate } from 'react-router-dom';
interface GoogleAuthModalProps {
isOpen: boolean;
@@ -10,7 +14,14 @@ interface GoogleAuthModalProps {
export default function GoogleAuthModal({ isOpen, onClose }: GoogleAuthModalProps) {
const buttonRef = useRef<HTMLDivElement>(null);
const { isAuthenticated } = useAuth();
const navigate = useNavigate();
const { isAuthenticated, loginWithCredentials } = useAuth();
const [usernameInput, setUsernameInput] = useState('');
const [passwordInput, setPasswordInput] = useState('');
const [isLoading, setIsLoading] = useState(false);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const [activeMode, setActiveMode] = useState<'credentials' | 'google'>('credentials');
// Close modal automatically if user gets authenticated
useEffect(() => {
@@ -21,7 +32,7 @@ export default function GoogleAuthModal({ isOpen, onClose }: GoogleAuthModalProp
// Render Google Button inside modal when open
useEffect(() => {
if (!isOpen) return;
if (!isOpen || activeMode !== 'google') return;
const renderGoogleBtn = () => {
if (window.google && buttonRef.current) {
@@ -38,10 +49,7 @@ export default function GoogleAuthModal({ isOpen, onClose }: GoogleAuthModalProp
}
};
// Render immediately if script is loaded
renderGoogleBtn();
// Or poll briefly if script is loading
const interval = setInterval(() => {
if (window.google) {
renderGoogleBtn();
@@ -50,7 +58,40 @@ export default function GoogleAuthModal({ isOpen, onClose }: GoogleAuthModalProp
}, 200);
return () => clearInterval(interval);
}, [isOpen]);
}, [isOpen, activeMode]);
const handleSubmitCredentials = async (e: React.FormEvent) => {
e.preventDefault();
if (!usernameInput.trim() || !passwordInput.trim()) {
setErrorMessage('Please enter both username/register number and password.');
return;
}
setIsLoading(true);
setErrorMessage(null);
try {
const result = await loginWithCredentials(usernameInput.trim(), passwordInput.trim());
if (result.success) {
onClose();
if (result.redirectTo) {
navigate(result.redirectTo);
}
} else {
setErrorMessage(result.message || 'Invalid credentials.');
}
} catch (err: any) {
setErrorMessage(err?.message || 'Authentication error.');
} finally {
setIsLoading(false);
}
};
const handleQuickFill = (user: string, pass: string) => {
setUsernameInput(user);
setPasswordInput(pass);
setErrorMessage(null);
};
return (
<AnimatePresence>
@@ -62,20 +103,20 @@ export default function GoogleAuthModal({ isOpen, onClose }: GoogleAuthModalProp
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
onClick={onClose}
className="absolute inset-0 bg-slate-950/70 backdrop-blur-md"
className="absolute inset-0 bg-slate-950/80 backdrop-blur-md"
/>
{/* Modal Container */}
<motion.div
initial={{ opacity: 0, scale: 0.9, y: 20 }}
initial={{ opacity: 0, scale: 0.92, y: 15 }}
animate={{ opacity: 1, scale: 1, y: 0 }}
exit={{ opacity: 0, scale: 0.9, y: 20 }}
transition={{ type: 'spring', bounce: 0.2, duration: 0.3 }}
className="relative w-full max-w-md bg-slate-900 border border-slate-700/80 rounded-3xl shadow-2xl p-8 z-10 text-center overflow-hidden"
exit={{ opacity: 0, scale: 0.92, y: 15 }}
transition={{ type: 'spring', bounce: 0.18, duration: 0.3 }}
className="relative w-full max-w-md bg-slate-900 border border-white/10 rounded-3xl shadow-2xl p-6 sm:p-7 z-10 text-slate-100 overflow-hidden"
>
{/* Background Orbs */}
<div className="absolute -top-20 -right-20 w-40 h-40 bg-orange-500/20 rounded-full blur-2xl pointer-events-none" />
<div className="absolute -bottom-20 -left-20 w-40 h-40 bg-blue-500/20 rounded-full blur-2xl pointer-events-none" />
{/* Background Glow */}
<div className="absolute -top-20 -right-20 w-44 h-44 bg-orange-500/15 rounded-full blur-3xl pointer-events-none" />
<div className="absolute -bottom-20 -left-20 w-44 h-44 bg-indigo-500/15 rounded-full blur-3xl pointer-events-none" />
{/* Close Button */}
<button
@@ -85,38 +126,165 @@ export default function GoogleAuthModal({ isOpen, onClose }: GoogleAuthModalProp
<X className="w-5 h-5" />
</button>
{/* Icon Header */}
<div className="w-16 h-16 rounded-2xl bg-orange-500/10 border border-orange-500/20 flex items-center justify-center mx-auto mb-5">
<Sparkles className="w-8 h-8 text-[#F97316]" />
{/* Header */}
<div className="text-center mb-5">
<div className="w-12 h-12 rounded-2xl bg-gradient-to-br from-[#FF6B00] to-[#F97316] p-0.5 shadow-lg shadow-orange-500/20 mx-auto mb-3">
<div className="w-full h-full bg-slate-950/60 rounded-[14px] flex items-center justify-center">
<Sparkles className="w-6 h-6 text-white" />
</div>
</div>
{/* Title & Description */}
<h2
className="text-2xl font-bold text-white mb-2"
style={{ fontFamily: 'Poppins, sans-serif' }}
>
<h2 className="text-xl font-extrabold text-white tracking-tight">
Sign In to Freshers Hub
</h2>
<p className="text-xs text-slate-400 mt-1">
Enter your student register number or admin credentials.
</p>
</div>
<p
className="text-xs text-slate-300 mb-6 leading-relaxed"
style={{ fontFamily: 'Inter, sans-serif' }}
{/* Tab Selector */}
<div className="flex rounded-xl bg-slate-950/80 p-1 border border-white/5 mb-5 text-xs font-semibold">
<button
type="button"
onClick={() => setActiveMode('credentials')}
className={`flex-1 py-2 rounded-lg transition-all cursor-pointer ${
activeMode === 'credentials'
? 'bg-gradient-to-r from-[#FF6B00] to-[#F97316] text-white shadow-sm'
: 'text-slate-400 hover:text-slate-200'
}`}
>
Credentials (Student / Admin)
</button>
<button
type="button"
onClick={() => setActiveMode('google')}
className={`flex-1 py-2 rounded-lg transition-all cursor-pointer ${
activeMode === 'google'
? 'bg-gradient-to-r from-[#FF6B00] to-[#F97316] text-white shadow-sm'
: 'text-slate-400 hover:text-slate-200'
}`}
>
Google Sign In
</button>
</div>
{/* ERROR MESSAGE */}
{errorMessage && (
<div className="mb-4 p-3 rounded-xl bg-rose-500/10 border border-rose-500/20 flex items-start gap-2 text-xs text-rose-300">
<AlertCircle className="w-4 h-4 text-rose-400 shrink-0 mt-0.5" />
<span>{errorMessage}</span>
</div>
)}
{/* 1. CREDENTIALS SIGN IN FORM */}
{activeMode === 'credentials' && (
<form onSubmit={handleSubmitCredentials} className="space-y-4">
<div>
<label className="block text-xs font-semibold text-slate-300 mb-1.5 flex items-center gap-1.5">
<User className="w-3.5 h-3.5 text-orange-400" />
Register Number / Username
</label>
<input
type="text"
value={usernameInput}
onChange={(e) => setUsernameInput(e.target.value)}
placeholder="e.g. 2114251001 or Transport or Admin"
className="w-full bg-slate-950 border border-white/10 rounded-xl px-4 py-2.5 text-xs text-white placeholder-slate-500 outline-none focus:border-orange-500 transition-colors font-mono"
required
/>
</div>
<div>
<label className="block text-xs font-semibold text-slate-300 mb-1.5 flex items-center gap-1.5">
<KeyRound className="w-3.5 h-3.5 text-orange-400" />
Password
</label>
<input
type="password"
value={passwordInput}
onChange={(e) => setPasswordInput(e.target.value)}
placeholder="••••••••"
className="w-full bg-slate-950 border border-white/10 rounded-xl px-4 py-2.5 text-xs text-white placeholder-slate-500 outline-none focus:border-orange-500 transition-colors font-mono"
required
/>
</div>
<button
type="submit"
disabled={isLoading}
className="w-full py-3 px-4 rounded-xl text-white font-bold text-xs bg-gradient-to-r from-[#FF6B00] to-[#F97316] hover:opacity-95 shadow-lg shadow-orange-500/20 transition-all flex items-center justify-center gap-2 cursor-pointer disabled:opacity-50"
>
{isLoading ? (
<div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
) : (
<>
<span>Sign In</span>
<ArrowRight className="w-4 h-4" />
</>
)}
</button>
{/* Quick Demo Fill Buttons */}
<div className="pt-3 border-t border-white/10 space-y-1.5">
<span className="text-[10px] text-slate-400 font-semibold block text-center uppercase tracking-wider">
Quick Demo Credentials:
</span>
<div className="grid grid-cols-2 gap-1.5 text-[11px]">
<button
type="button"
onClick={() => handleQuickFill('2114251001', 'rit@2026')}
className="p-2 rounded-lg bg-slate-950/80 hover:bg-slate-950 border border-white/5 text-left flex items-center justify-between transition-colors cursor-pointer"
>
<span className="truncate">🎓 CSE Student</span>
<span className="text-[9px] text-orange-400 font-mono">Fill</span>
</button>
<button
type="button"
onClick={() => handleQuickFill('2114251002', 'rit@2026')}
className="p-2 rounded-lg bg-slate-950/80 hover:bg-slate-950 border border-white/5 text-left flex items-center justify-between transition-colors cursor-pointer"
>
<span className="truncate">🎓 AI&DS Student</span>
<span className="text-[9px] text-orange-400 font-mono">Fill</span>
</button>
<button
type="button"
onClick={() => handleQuickFill('Transport', 'RIT@2026')}
className="p-2 rounded-lg bg-slate-950/80 hover:bg-slate-950 border border-white/5 text-left flex items-center justify-between transition-colors cursor-pointer"
>
<span className="truncate">🚌 Transport Admin</span>
<span className="text-[9px] text-blue-400 font-mono">Fill</span>
</button>
<button
type="button"
onClick={() => handleQuickFill('Admin', 'RIT@2026')}
className="p-2 rounded-lg bg-slate-950/80 hover:bg-slate-950 border border-white/5 text-left flex items-center justify-between transition-colors cursor-pointer"
>
<span className="truncate">⚡ Super Admin</span>
<span className="text-[9px] text-emerald-400 font-mono">Fill</span>
</button>
</div>
</div>
</form>
)}
{/* 2. GOOGLE SIGN IN */}
{activeMode === 'google' && (
<div className="space-y-4 py-2 text-center">
<p className="text-xs text-slate-300 leading-relaxed">
Sign in with your Google account. Use your{' '}
<strong className="text-[#F97316]">@ritchennai.edu.in</strong> college email to unlock the{' '}
<strong className="text-emerald-400">Verified Student</strong> badge and post collaboration requests!
<strong className="text-orange-400">@ritchennai.edu.in</strong> email for automatic student verification.
</p>
{/* Google Sign-In Button Container */}
<div className="flex justify-center my-6 min-h-[44px]">
<div className="flex justify-center my-4 min-h-[44px]">
<div ref={buttonRef} />
</div>
{/* Verified Student Callout */}
<div className="mt-6 pt-4 border-t border-slate-800/80 flex items-center justify-center gap-2 text-[11px] text-slate-400">
<ShieldCheck className="w-4 h-4 text-emerald-400 shrink-0" />
<span>Official RIT Student Verification via Google</span>
<div className="pt-3 border-t border-white/10 flex items-center justify-center gap-1.5 text-[11px] text-slate-400">
<ShieldCheck className="w-3.5 h-3.5 text-emerald-400 shrink-0" />
<span>Google OAuth 2.0 Single Sign-On</span>
</div>
</div>
)}
</motion.div>
</div>
)}

View File

@@ -53,8 +53,8 @@ export default function ProtectedRoute({
</div>
<h1
className="text-2xl sm:text-3xl font-bold text-[#1E293B] mb-3"
style={{ fontFamily: 'Playfair Display, serif' }}
className="text-2xl sm:text-3xl font-extrabold text-[#1E293B] mb-3"
style={{ fontFamily: 'Plus Jakarta Sans, sans-serif' }}
>
{title}
</h1>

View File

@@ -19,7 +19,12 @@ import {
Users,
Code2,
Trophy,
Ticket,
Award,
GraduationCap,
LayoutDashboard,
Home as HomeIcon,
ShieldAlert,
} from 'lucide-react';
import { useAuth } from '@/context/AuthContext';
@@ -31,30 +36,36 @@ interface NavItem {
const PRIMARY_LINKS: NavItem[] = [
{ label: 'Home', path: '/', icon: HomeIcon },
{ label: 'Time table', path: '/dashboard', icon: LayoutDashboard },
{ label: 'Notes', path: '/notes', icon: BookOpen },
{ label: 'Toolkit', path: '/toolkit', icon: Wrench },
{ label: 'Chatbot', path: '/ai-assistant', icon: Bot },
{ label: 'Clubs & Centers', path: '/events', icon: Users },
{ label: 'Dev Collab', path: '/collab', icon: Code2 },
{ label: 'LeetCode', path: '/leetcode', icon: Trophy },
];
const MORE_LINKS: NavItem[] = [
{ label: 'Campus Map', path: '/campus', icon: Map },
{ label: 'Bus Routes', path: '/bus-routes', icon: Bus },
{ label: 'Faculty Directory', path: '/faculty', icon: UserCheck },
{ label: 'Community', path: '/community', icon: MessageCircle },
{ label: 'RAISE Incubator', path: '/raise', icon: Rocket },
];
const ALL_MOBILE_LINKS: NavItem[] = [...PRIMARY_LINKS, ...MORE_LINKS];
const MORE_LINKS: NavItem[] = [
{ label: 'Chatbot', path: '/ai-assistant', icon: Bot },
{ label: 'Toolkit', path: '/toolkit', icon: Wrench },
{ label: 'Campus Map', path: '/campus', icon: Map },
{ label: 'Clubs & Centers', path: '/events', icon: Users },
{ label: 'Dev Collab', path: '/collab', icon: Code2 },
{ label: 'LeetCode', path: '/leetcode', icon: Trophy },
{ label: 'Student Gate Pass', path: '/notes?portal=gatepass', icon: Ticket },
{ label: 'Student Proficiency', path: '/notes?portal=proficiency', icon: Award },
];
const ALL_MOBILE_LINKS: NavItem[] = [
...PRIMARY_LINKS,
...MORE_LINKS,
{ label: 'RAISE Incubator', path: '/raise', icon: Rocket },
];
export default function Navbar() {
const [isMobileOpen, setIsMobileOpen] = useState(false);
const [isProfileOpen, setIsProfileOpen] = useState(false);
const [isMoreOpen, setIsMoreOpen] = useState(false);
const location = useLocation();
const { user, isAuthenticated, isVerifiedStudent, loginWithGoogle, logout } = useAuth();
const { user, isAuthenticated, isVerifiedStudent, isAdmin, isTransportAdmin, openAuthModal, logout } = useAuth();
const profileRef = useRef<HTMLDivElement>(null);
const moreRef = useRef<HTMLDivElement>(null);
@@ -78,9 +89,12 @@ export default function Navbar() {
}, []);
const checkIsActive = (linkPath: string) => {
const [pathName] = linkPath.split('?');
if (pathName === '/') return location.pathname === '/';
return location.pathname.startsWith(pathName);
if (linkPath === '/') return location.pathname === '/';
if (linkPath === '/notes') return location.pathname === '/notes' && !location.search.includes('portal=');
if (linkPath.includes('?')) {
return location.pathname + location.search === linkPath;
}
return location.pathname.startsWith(linkPath);
};
const isMoreActive = MORE_LINKS.some((link) => checkIsActive(link.path));
@@ -93,7 +107,7 @@ export default function Navbar() {
initial={{ y: -60, opacity: 0 }}
animate={{ y: 0, opacity: 1 }}
transition={{ duration: 0.45, ease: 'easeOut' }}
className="pointer-events-auto flex items-center justify-between gap-2 lg:gap-4 px-3 sm:px-4 py-2 rounded-2xl bg-slate-950/90 backdrop-blur-xl border border-white/10 shadow-[0_8px_30px_rgba(0,0,0,0.35)] transition-all"
className="relative pointer-events-auto flex items-center justify-between gap-2 lg:gap-4 px-3 sm:px-4 py-2 rounded-2xl bg-slate-950/90 backdrop-blur-xl border border-white/10 shadow-[0_8px_30px_rgba(0,0,0,0.35)] transition-all"
>
{/* Left: Logo & College Brand */}
<Link to="/" className="flex items-center gap-2.5 group shrink-0">
@@ -190,12 +204,12 @@ export default function Navbar() {
onClick={() => setIsMoreOpen(false)}
className={`flex items-center gap-2.5 px-3 py-2 rounded-xl text-xs font-medium transition-all ${
active
? 'bg-gradient-to-r from-[#FF6B00] to-[#F97316] text-white font-bold'
? 'bg-white/15 text-orange-400 font-semibold'
: 'text-slate-300 hover:text-white hover:bg-white/10'
}`}
style={{ fontFamily: 'Plus Jakarta Sans, sans-serif' }}
>
{IconComponent && <IconComponent className="w-4 h-4 shrink-0 text-slate-300" />}
{IconComponent && <IconComponent className={`w-4 h-4 shrink-0 ${active ? 'text-orange-400' : 'text-slate-300'}`} />}
<span>{item.label}</span>
</Link>
);
@@ -206,7 +220,7 @@ export default function Navbar() {
</div>
</div>
{/* Right: Auth Profile / Sign In */}
{/* Right: Auth Profile / Unified Sign In */}
<div className="hidden lg:flex items-center gap-2 shrink-0">
{isAuthenticated && user ? (
<div className="relative" ref={profileRef}>
@@ -222,12 +236,14 @@ export default function Navbar() {
referrerPolicy="no-referrer"
/>
) : (
<div className="w-6 h-6 rounded-full bg-gradient-to-br from-[#FF6B00] to-[#F97316] flex items-center justify-center text-white font-bold text-xs">
{user.name.charAt(0).toUpperCase()}
<div className={`w-6 h-6 rounded-full flex items-center justify-center text-white font-bold text-xs ${
isAdmin ? 'bg-indigo-600' : 'bg-gradient-to-br from-[#FF6B00] to-[#F97316]'
}`}>
{isAdmin ? 'A' : user.name.charAt(0).toUpperCase()}
</div>
)}
<span
className="text-white text-xs font-semibold max-w-[100px] truncate"
className="text-white text-xs font-semibold max-w-[120px] truncate"
style={{ fontFamily: 'Plus Jakarta Sans, sans-serif' }}
>
{user.name.split(' ')[0]}
@@ -255,8 +271,10 @@ export default function Navbar() {
referrerPolicy="no-referrer"
/>
) : (
<div className="w-10 h-10 rounded-full bg-gradient-to-br from-[#FF6B00] to-[#F97316] flex items-center justify-center text-white font-bold text-lg">
{user.name.charAt(0).toUpperCase()}
<div className={`w-10 h-10 rounded-full flex items-center justify-center text-white font-bold text-lg ${
isAdmin ? 'bg-indigo-600' : 'bg-gradient-to-br from-[#FF6B00] to-[#F97316]'
}`}>
{isAdmin ? 'A' : user.name.charAt(0).toUpperCase()}
</div>
)}
<div className="flex-1 min-w-0">
@@ -264,20 +282,45 @@ export default function Navbar() {
<p className="text-slate-400 text-[11px] truncate">{user.email}</p>
</div>
</div>
{isVerifiedStudent ? (
<div className="mt-3 flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg bg-emerald-500/15 border border-emerald-500/25">
<ShieldCheck className="w-3.5 h-3.5 text-emerald-400" />
<span className="text-[11px] font-bold text-emerald-400">Verified RIT Student</span>
</div>
) : (
<div className="mt-3 flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg bg-amber-500/15 border border-amber-500/25">
<span className="text-[11px] font-semibold text-amber-400">
Sign in with @ritchennai.edu.in
{/* Role Badges */}
{isAdmin ? (
<div className="mt-3 flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg bg-indigo-500/15 border border-indigo-500/25">
<ShieldAlert className="w-3.5 h-3.5 text-indigo-400" />
<span className="text-[11px] font-bold text-indigo-400">
{isTransportAdmin ? 'Transport Fleet Manager' : 'System Super Admin'}
</span>
</div>
)}
) : isVerifiedStudent ? (
<div className="mt-3 flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg bg-emerald-500/15 border border-emerald-500/25">
<ShieldCheck className="w-3.5 h-3.5 text-emerald-400" />
<span className="text-[11px] font-bold text-emerald-400">
Verified Student {user.regNumber ? `(${user.regNumber})` : ''}
</span>
</div>
<div className="p-2">
) : null}
</div>
<div className="p-2 space-y-1">
{isAdmin ? (
<Link
to="/admin"
onClick={() => setIsProfileOpen(false)}
className="w-full flex items-center gap-2.5 px-3 py-2 rounded-xl text-slate-300 hover:text-white hover:bg-indigo-500/15 text-xs font-semibold transition-all cursor-pointer"
>
<ShieldCheck className="w-4 h-4 text-indigo-400" />
Admin Console
</Link>
) : (
<Link
to="/dashboard"
onClick={() => setIsProfileOpen(false)}
className="w-full flex items-center gap-2.5 px-3 py-2 rounded-xl text-slate-300 hover:text-white hover:bg-orange-500/15 hover:border-orange-500/20 text-xs font-semibold transition-all cursor-pointer"
>
<GraduationCap className="w-4 h-4 text-orange-400" />
My Time Table
</Link>
)}
<button
onClick={() => {
logout();
@@ -297,11 +340,11 @@ export default function Navbar() {
<motion.button
whileHover={{ scale: 1.03 }}
whileTap={{ scale: 0.97 }}
onClick={loginWithGoogle}
className="flex items-center gap-1.5 px-3.5 py-1.5 rounded-xl text-white text-xs font-bold bg-white/10 hover:bg-white/15 border border-white/15 transition-all cursor-pointer"
onClick={openAuthModal}
className="flex items-center gap-1.5 px-3.5 py-1.5 rounded-xl text-white text-xs font-bold bg-gradient-to-r from-[#FF6B00] to-[#F97316] shadow-sm hover:opacity-95 transition-all cursor-pointer"
style={{ fontFamily: 'Plus Jakarta Sans, sans-serif' }}
>
<LogIn className="w-3.5 h-3.5 text-[#FF6B00]" />
<LogIn className="w-3.5 h-3.5 text-white" />
<span>Sign In</span>
</motion.button>
)}
@@ -333,6 +376,7 @@ export default function Navbar() {
<div className="grid grid-cols-2 gap-2">
{ALL_MOBILE_LINKS.map((link) => {
const isActive = checkIsActive(link.path);
const isRaise = link.path === '/raise';
const IconComp = link.icon;
return (
<Link
@@ -340,7 +384,9 @@ export default function Navbar() {
to={link.path}
onClick={() => setIsMobileOpen(false)}
className={`px-3 py-2.5 rounded-xl text-xs font-semibold flex items-center gap-2 transition-all ${
isActive
isRaise
? 'bg-gradient-to-r from-[#EC4899] via-[#F43F5E] to-[#E11D48] text-white font-bold shadow-md shadow-pink-500/30 col-span-2 justify-center'
: isActive
? 'bg-gradient-to-r from-[#FF6B00] to-[#F97316] text-white shadow-sm'
: 'bg-white/5 text-slate-200 hover:bg-white/10 border border-white/5'
}`}
@@ -358,33 +404,79 @@ export default function Navbar() {
{!isAuthenticated ? (
<button
onClick={() => {
loginWithGoogle();
openAuthModal();
setIsMobileOpen(false);
}}
className="w-full flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-white text-xs font-semibold border border-orange-500/40 bg-orange-500/15 hover:bg-orange-500/25 transition-all cursor-pointer"
className="w-full flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-white text-xs font-semibold border border-orange-500/40 bg-gradient-to-r from-[#FF6B00] to-[#F97316] transition-all cursor-pointer"
style={{ fontFamily: 'Plus Jakarta Sans, sans-serif' }}
>
<LogIn className="w-4 h-4 text-orange-400" />
Sign In with Google
<LogIn className="w-4 h-4 text-white" />
Sign In
</button>
) : (
<div className="space-y-2">
<div className="flex items-center justify-between p-2 rounded-xl bg-white/5 text-xs text-slate-300">
<span className="font-bold text-white">{user?.name}</span>
<span className="text-[10px] text-orange-400 font-mono">
{isAdmin ? 'Admin' : (user?.regNumber || 'Student')}
</span>
</div>
{isAdmin ? (
<Link
to="/admin"
onClick={() => setIsMobileOpen(false)}
className="w-full flex items-center justify-center gap-2 px-4 py-2 rounded-xl bg-indigo-600 text-white text-xs font-bold"
>
Go to Admin Console
</Link>
) : (
<Link
to="/dashboard"
onClick={() => setIsMobileOpen(false)}
className="w-full flex items-center justify-center gap-2 px-4 py-2 rounded-xl bg-orange-500 text-white text-xs font-bold"
>
Go to Student Dashboard
</Link>
)}
<button
onClick={() => {
logout();
setIsMobileOpen(false);
}}
className="w-full flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-red-400 text-xs font-semibold border border-red-500/30 bg-red-500/10 hover:bg-red-500/20 transition-all cursor-pointer"
className="w-full flex items-center justify-center gap-2 px-4 py-2 rounded-xl text-red-400 text-xs font-semibold border border-red-500/30 bg-red-500/10 hover:bg-red-500/20 transition-all cursor-pointer"
style={{ fontFamily: 'Plus Jakarta Sans, sans-serif' }}
>
<LogOut className="w-4 h-4" />
Sign Out ({user?.name.split(' ')[0]})
Sign Out
</button>
</div>
)}
</div>
</div>
</motion.div>
)}
</AnimatePresence>
{/* Floating RAISE Incubator Button directly below right side of navbar */}
<motion.div
initial={{ y: -10, opacity: 0 }}
animate={{ y: 0, opacity: 1 }}
transition={{ duration: 0.35, ease: 'easeOut', delay: 0.1 }}
className="absolute right-0 sm:right-1 lg:right-1 top-[calc(100%+8px)] pointer-events-auto hidden lg:block z-40"
>
<Link
to="/raise"
className={`flex items-center gap-2 px-3.5 py-2 rounded-xl text-xs font-extrabold text-white transition-all shadow-lg hover:scale-105 active:scale-95 cursor-pointer backdrop-blur-xl ${
checkIsActive('/raise')
? 'bg-gradient-to-r from-pink-600 via-rose-600 to-pink-700 ring-2 ring-pink-300 shadow-pink-500/50'
: 'bg-gradient-to-r from-[#EC4899] via-[#F43F5E] to-[#E11D48] hover:from-[#DB2777] hover:to-[#BE123C] shadow-pink-500/40 border border-pink-400/40'
}`}
style={{ fontFamily: 'Plus Jakarta Sans, sans-serif' }}
>
<Rocket className="w-4 h-4 text-white animate-pulse" />
<span>RAISE Incubator</span>
</Link>
</motion.div>
</motion.nav>
</header>

View File

@@ -0,0 +1,793 @@
export interface SubjectCurriculum {
name: string;
credits: number;
code?: string;
isElective?: boolean;
electiveSlot?: number;
}
export const PROFESSIONAL_ELECTIVES_LIST: Array<{ code: string; name: string; credits: number }> = [
{ code: 'AD23V11', name: 'Agriculture Data Analytics', credits: 3 },
{ code: 'AD23V12', name: 'Big Data Analytics', credits: 3 },
{ code: 'AD23V13', name: 'Data warehousing and Data Mining', credits: 3 },
{ code: 'AD23V14', name: 'Health Care Analytics', credits: 3 },
{ code: 'AD23V15', name: 'Image and Video Analytics', credits: 3 },
{ code: 'AD23V16', name: 'Web and Social Media Analytics', credits: 3 },
{ code: 'AD23V17', name: 'Predictive Analytics', credits: 3 },
{ code: 'AD23V18', name: 'Sentiment Analysis', credits: 3 },
{ code: 'AD23V21', name: 'AI in IoT', credits: 3 },
{ code: 'AD23V22', name: 'Applied Machine Learning', credits: 3 },
{ code: 'AD23V23', name: 'Cognitive Computing', credits: 3 },
{ code: 'AD23V24', name: 'Computer Vision', credits: 3 },
{ code: 'AD23V25', name: 'Ethics For AI', credits: 3 },
{ code: 'AD23V26', name: 'Game Theory', credits: 3 },
{ code: 'AD23V27', name: 'Quantum Computing Techniques', credits: 3 },
{ code: 'AD23V28', name: 'Responsive AI', credits: 3 },
];
export const DEPARTMENT_CODE_MAP: Record<string, string> = {
'Artificial Intelligence & Data Science': 'AIDS',
'Artificial Intelligence & Machine Learning': 'AIML',
'Biotechnology': 'BIOTECH',
'Communication and Computer Engineering': 'CCE',
'Computer Science & Business Systems': 'CSBS',
'Computer Science & Engineering': 'CSE',
'Electronics & Communication Engineering': 'ECE',
'Electronics Engineering VLSI (Design and Technology)': 'VLSI',
'Mechanical Engineering': 'MECH',
};
export const DEPARTMENT_CURRICULUM: Record<string, Record<number, SubjectCurriculum[]>> = {
AIDS: {
1: [
{ name: "Communicative English (HS23111)", credits: 3 },
{ name: "Matrices and Calculus (MA23111)", credits: 4 },
{ name: "Physics for Information Science (PH23111)", credits: 3 },
{ name: "Problem Solving and C Programming (GE23111)", credits: 3 },
{ name: "Basic Electrical and Electronics Engineering (GE23113)", credits: 3 },
{ name: "Heritage of Tamils (GE23112)", credits: 0 },
{ name: "Physics Laboratory (PH23121)", credits: 1 },
{ name: "Problem Solving and C Programming Laboratory (GE23121)", credits: 1 },
{ name: "Engineering Practices Laboratory (GE23122)", credits: 1 }
],
2: [
{ name: "Professional English (HS23211)", credits: 2 },
{ name: "Engineering Chemistry (CY23211)", credits: 3 },
{ name: "Statistics and Numerical Methods (MA23211)", credits: 4 },
{ name: "Python for Data Science (AD23211)", credits: 3 },
{ name: "Tamil & Technology (GE23213)", credits: 0 },
{ name: "Engineering Graphics (GE23231)", credits: 4 },
{ name: "Data Structures Design (AD23231)", credits: 4 },
{ name: "Chemistry Laboratory (CY23221)", credits: 1 },
{ name: "Python for Data Science Laboratory (AD23221)", credits: 1 },
{ name: "Communication Laboratory / Foreign Language (GE23221)", credits: 1 }
],
3: [
{ name: "Discrete Mathematics (MA23311)", credits: 4 },
{ name: "Artificial Intelligence (AL23311)", credits: 3 },
{ name: "Object Oriented Programming (CS23312)", credits: 3 },
{ name: "Database Management Systems (CS23411)", credits: 3 },
{ name: "Digital Principles and Computer Organization (EC23331)", credits: 4 },
{ name: "Artificial Intelligence Laboratory (AL23321)", credits: 1 },
{ name: "Database Management Systems Laboratory (CS23421)", credits: 1 },
{ name: "Object Oriented Programming Laboratory (CS23322)", credits: 1 },
{ name: "Data Wrangling (AD231C1)", credits: 1 }
],
4: [
{ name: "Environmental Science and Sustainability (GE23411)", credits: 2 },
{ name: "Probability and Statistics (MA23411)", credits: 4 },
{ name: "Data Analytics (AD23411)", credits: 3 },
{ name: "Machine Learning (AL23411)", credits: 3 },
{ name: "Operating Systems (CS23412)", credits: 3 },
{ name: "Design and Analysis of Algorithms (CS23431)", credits: 4 },
{ name: "Data Analytics Laboratory (AD23421)", credits: 1 },
{ name: "Machine Learning Laboratory (AL23421)", credits: 1 },
{ name: "Operating Systems Laboratory (CS23422)", credits: 1 },
{ name: "Introduction to Azure Machine Learning (AD231C1)", credits: 1 }
],
5: [
{ name: "Deep Learning (AD23511)", credits: 3 },
{ name: "Computer Networks (CS23511)", credits: 3 },
{ name: "Data Exploration and Visualization (AD23532)", credits: 4 },
{ name: "Business Analytics (CB23531)", credits: 4 },
{ name: "Disaster Risk Reduction and Management", credits: 0 },
{ name: "Big Data Analytics (AD23531)", credits: 3 },
{ name: "Image & Video Analytics (AD23V15)", credits: 3 },
{ name: "Tableau - Data Visualization (AD23IC3)", credits: 1 },
{ name: "Deep Learning Laboratory (AD23521)", credits: 1 },
{ name: "Computer Networks Laboratory (CS23521)", credits: 1 }
],
6: [
{ name: "Professional Elective III", credits: 3, isElective: true, electiveSlot: 3 },
{ name: "Professional Elective IV", credits: 3, isElective: true, electiveSlot: 4 },
{ name: "Open Elective I", credits: 3 },
{ name: "Open Elective II", credits: 3 },
{ name: "Mandatory Course II", credits: 0 },
{ name: "Embedded Systems and IoT (EC23631)", credits: 4 },
{ name: "Object Oriented Software Engineering (CS23631)", credits: 4 },
{ name: "Mini Project (AD23621)", credits: 2 }
],
7: [
{ name: "Human Values and Ethics (GE23711)", credits: 2 },
{ name: "Elective – Management", credits: 3 },
{ name: "Data and Information Security (CB23511)", credits: 3 },
{ name: "Professional Elective V", credits: 3, isElective: true, electiveSlot: 5 },
{ name: "Professional Elective VI", credits: 3, isElective: true, electiveSlot: 6 },
{ name: "Internship / Certification Course (AD23721)", credits: 2 }
],
8: [
{ name: "Open Elective III", credits: 3 },
{ name: "Project Work (AD23821)", credits: 10 }
]
},
AIML: {
1: [
{ name: "Communicative English (HS23111)", credits: 3 },
{ name: "Engineering Chemistry (CY23111)", credits: 3 },
{ name: "Matrices and Calculus (MA23111)", credits: 4 },
{ name: "Problem Solving and C Programming (GE23111)", credits: 3 },
{ name: "Heritage of Tamils (GE23112)", credits: 0 },
{ name: "Engineering Graphics (GE23131)", credits: 4 },
{ name: "Chemistry Laboratory (CY23121)", credits: 1 },
{ name: "Problem Solving and C Programming Laboratory (GE23121)", credits: 1 },
{ name: "Engineering Practices Laboratory (GE23122)", credits: 1 }
],
2: [
{ name: "Professional English (HS23211)", credits: 2 },
{ name: "Statistics and Numerical Methods (MA23211)", credits: 4 },
{ name: "Physics for Information Science (PH23211)", credits: 3 },
{ name: "Basic Electrical and Electronics Engineering (GE23211)", credits: 3 },
{ name: "Python for Data Science (AD23211)", credits: 3 },
{ name: "Tamils and Technology (GE23213)", credits: 0 },
{ name: "Data Structures and Design (AD23231)", credits: 4 },
{ name: "Physics Laboratory (PH23221)", credits: 1 },
{ name: "Python for Data Science Laboratory (AD23221)", credits: 1 },
{ name: "Communication Laboratory / Foreign Language (GE23221)", credits: 1 }
],
3: [
{ name: "Discrete Mathematics (MA23311)", credits: 4 },
{ name: "Artificial Intelligence (AL23311)", credits: 3 },
{ name: "Object Oriented Programming (CS23312)", credits: 3 },
{ name: "Database Management Systems (CS23411)", credits: 3 },
{ name: "Digital Principles and Computer Organization (EC23331)", credits: 4 },
{ name: "Artificial Intelligence Laboratory (AL23321)", credits: 1 },
{ name: "Database Management Systems Laboratory (CS23421)", credits: 1 },
{ name: "Object Oriented Programming Laboratory (CS23322)", credits: 1 },
{ name: "Data Wrangling (AD231C1)", credits: 1 }
],
4: [
{ name: "Environmental Sciences and Sustainability (GE23411)", credits: 2 },
{ name: "Formal Language and Automata Theory (AD23412)", credits: 4 },
{ name: "Data Analytics (AD23411)", credits: 3 },
{ name: "Machine Learning (AL23411)", credits: 3 },
{ name: "Operating Systems (CS23412)", credits: 3 },
{ name: "Design and Analysis of Algorithms (CS23431)", credits: 4 },
{ name: "Machine Learning Laboratory (AL23421)", credits: 1 },
{ name: "Data Analytics Laboratory (AD23421)", credits: 1 },
{ name: "Operating Systems Laboratory (CS23422)", credits: 1 },
{ name: "Introduction to Azure Machine Learning (AD231C1)", credits: 1 }
],
5: [
{ name: "Deep Learning for Computer Vision (AL23511)", credits: 3 },
{ name: "Computer Networks (CS23511)", credits: 3 },
{ name: "Professional Elective I", credits: 3, isElective: true, electiveSlot: 1 },
{ name: "Professional Elective II", credits: 3, isElective: true, electiveSlot: 2 },
{ name: "Mandatory Course I", credits: 0 },
{ name: "Natural Language Processing (AL23531)", credits: 4 },
{ name: "Big Data Analytics (AD23531)", credits: 4 },
{ name: "Deep Learning for Computer Vision Laboratory (AL23521)", credits: 1 },
{ name: "Computer Networks Laboratory (CS23521)", credits: 1 },
{ name: "Industry Oriented Course III", credits: 1 }
],
6: [
{ name: "Professional Elective III", credits: 3, isElective: true, electiveSlot: 3 },
{ name: "Professional Elective IV", credits: 3, isElective: true, electiveSlot: 4 },
{ name: "Open Elective I", credits: 3 },
{ name: "Open Elective II", credits: 3 },
{ name: "Mandatory Course II", credits: 0 },
{ name: "Embedded Systems and IoT (EC23631)", credits: 4 },
{ name: "Object Oriented Software Engineering (CS23631)", credits: 4 },
{ name: "Mini Project (AL23621)", credits: 2 }
],
7: [
{ name: "Human Values and Ethics (GE23711)", credits: 2 },
{ name: "Elective – Management", credits: 3 },
{ name: "Cryptography and Cyber Security (CS23513)", credits: 3 },
{ name: "Professional Elective V", credits: 3, isElective: true, electiveSlot: 5 },
{ name: "Professional Elective VI", credits: 3, isElective: true, electiveSlot: 6 },
{ name: "Internship / Certification Course (AL23721)", credits: 2 }
],
8: [
{ name: "Open Elective III", credits: 3 },
{ name: "Project Work (AL23821)", credits: 10 }
]
},
BIOTECH: {
1: [
{ name: "Communicative English (HS23111)", credits: 3 },
{ name: "Engineering Chemistry (CY23111)", credits: 3 },
{ name: "Matrices and Calculus (MA23111)", credits: 4 },
{ name: "Problem Solving and C Programming (GE23111)", credits: 3 },
{ name: "Heritage of Tamils (GE23112)", credits: 0 },
{ name: "Engineering Graphics (GE23131)", credits: 4 },
{ name: "Chemistry Laboratory (CY23121)", credits: 1 },
{ name: "Problem Solving and C Programming Laboratory (GE23121)", credits: 1 }
],
2: [
{ name: "Professional English (HS23211)", credits: 2 },
{ name: "Statistics and Numerical Methods (MA23211)", credits: 4 },
{ name: "Physics for Information Science (PH23211)", credits: 3 },
{ name: "Python for Data Science (AD23211)", credits: 3 },
{ name: "Basic Electrical and Electronics Engineering (GE23211)", credits: 3 },
{ name: "Tamils and Technology (GE23213)", credits: 0 },
{ name: "Physics Laboratory (PH23221)", credits: 1 },
{ name: "Python for Data Science Laboratory (AD23221)", credits: 1 },
{ name: "Communication Laboratory / Foreign Language (GE23221)", credits: 1 },
{ name: "Engineering Practices Laboratory (GE23223)", credits: 1 },
{ name: "NCC / Service Club Credit Course Level 1", credits: 2 }
],
3: [
{ name: "Discrete Mathematics (MA23311)", credits: 4 },
{ name: "Fundamentals of Economics and Financial Accounting (CB23311)", credits: 4 },
{ name: "Object Oriented Programming (CS23312)", credits: 3 },
{ name: "Data Structures and Algorithms (CS23314)", credits: 3 },
{ name: "Digital Principles and Computer Organization (EC23331)", credits: 4 },
{ name: "Object Oriented Programming Laboratory (CS23322)", credits: 1 },
{ name: "Data Structures and Algorithms Laboratory (CS23324)", credits: 1 },
{ name: "Design Thinking (CB23IC1)", credits: 1 }
],
4: [
{ name: "Environmental Science and Sustainability (GE23411)", credits: 2 },
{ name: "Probability and Statistics (MA23411)", credits: 4 },
{ name: "Introduction to Business Systems (CB23411)", credits: 3 },
{ name: "Database Management Systems (CS23411)", credits: 3 },
{ name: "Operating Systems (CS23412)", credits: 3 },
{ name: "Artificial Intelligence and Machine Learning (AL23431)", credits: 4 },
{ name: "Database Management Systems Laboratory (CS23421)", credits: 1 },
{ name: "Operating Systems Laboratory (CS23422)", credits: 1 },
{ name: "Enterprise Resource Planning (CB23IC2)", credits: 1 },
{ name: "NCC / Service Club Credit Course Level 2", credits: 3 }
],
5: [
{ name: "Data and Information Security (CB23511)", credits: 3 },
{ name: "Fundamentals of Management (CB23512)", credits: 3 },
{ name: "Professional Elective I", credits: 3, isElective: true, electiveSlot: 1 },
{ name: "Professional Elective II", credits: 3, isElective: true, electiveSlot: 2 },
{ name: "Mandatory Course I", credits: 0 },
{ name: "Deep Learning Techniques (AD23531)", credits: 4 },
{ name: "Business Analytics (CB23531)", credits: 4 },
{ name: "Data and Information Security Laboratory (CB23521)", credits: 1 },
{ name: "Business Communication Laboratory – I (GE23521)", credits: 1 },
{ name: "Visualization Tools using R (CB23IC3)", credits: 1 }
],
6: [
{ name: "Professional Elective III", credits: 3, isElective: true, electiveSlot: 3 },
{ name: "Professional Elective IV", credits: 3, isElective: true, electiveSlot: 4 },
{ name: "Open Elective I", credits: 3 },
{ name: "Open Elective II", credits: 3 },
{ name: "Mandatory Course II", credits: 0 },
{ name: "Embedded Systems and IoT (EC23631)", credits: 4 },
{ name: "Object Oriented Software Engineering (CS23631)", credits: 4 },
{ name: "Mini Project (CB23621)", credits: 2 },
{ name: "Business Communication Laboratory – II (GE23621)", credits: 1 },
{ name: "NCC / Service Club Credit Course Level 3", credits: 3 }
],
7: [
{ name: "Human Values and Ethics (GE23711)", credits: 2 },
{ name: "Elective – Management", credits: 3 },
{ name: "Cryptography and Cyber Security (CS23513)", credits: 3 },
{ name: "Professional Elective V", credits: 3, isElective: true, electiveSlot: 5 },
{ name: "Professional Elective VI", credits: 3, isElective: true, electiveSlot: 6 },
{ name: "Cloud Computing (CS23731)", credits: 4 },
{ name: "Internship / Certification Course (CB23721)", credits: 2 }
],
8: [
{ name: "Open Elective III", credits: 3 },
{ name: "Project Work (CB23821)", credits: 10 }
]
},
CSBS: {
1: [
{ name: "Communicative English (HS23111)", credits: 3 },
{ name: "Engineering Chemistry (CY23111)", credits: 3 },
{ name: "Matrices and Calculus (MA23111)", credits: 4 },
{ name: "Problem Solving and C Programming (GE23111)", credits: 3 },
{ name: "Heritage of Tamils (GE23112)", credits: 0 },
{ name: "Engineering Graphics (GE23131)", credits: 4 },
{ name: "Chemistry Laboratory (CY23121)", credits: 1 },
{ name: "Problem Solving and C Programming Laboratory (GE23121)", credits: 1 }
],
2: [
{ name: "Professional English (HS23211)", credits: 2 },
{ name: "Statistics and Numerical Methods (MA23211)", credits: 4 },
{ name: "Physics for Information Science (PH23211)", credits: 3 },
{ name: "Python for Data Science (AD23211)", credits: 3 },
{ name: "Basic Electrical and Electronics Engineering (GE23211)", credits: 3 },
{ name: "Tamils and Technology (GE23213)", credits: 0 },
{ name: "Physics Laboratory (PH23221)", credits: 1 },
{ name: "Python for Data Science Laboratory (AD23221)", credits: 1 },
{ name: "Communication Laboratory / Foreign Language (GE23221)", credits: 1 },
{ name: "Engineering Practices Laboratory (GE23223)", credits: 1 },
{ name: "NCC / Service Club Credit Course Level 1", credits: 2 }
],
3: [
{ name: "Discrete Mathematics (MA23311)", credits: 4 },
{ name: "Fundamentals of Economics and Financial Accounting (CB23311)", credits: 4 },
{ name: "Object Oriented Programming (CS23312)", credits: 3 },
{ name: "Data Structures and Algorithms (CS23314)", credits: 3 },
{ name: "Digital Principles and Computer Organization (EC23331)", credits: 4 },
{ name: "Object Oriented Programming Laboratory (CS23322)", credits: 1 },
{ name: "Data Structures and Algorithms Laboratory (CS23324)", credits: 1 },
{ name: "Design Thinking (CB23IC1)", credits: 1 }
],
4: [
{ name: "Environmental Science and Sustainability (GE23411)", credits: 2 },
{ name: "Probability and Statistics (MA23411)", credits: 4 },
{ name: "Introduction to Business Systems (CB23411)", credits: 3 },
{ name: "Database Management Systems (CS23411)", credits: 3 },
{ name: "Operating Systems (CS23412)", credits: 3 },
{ name: "Artificial Intelligence and Machine Learning (AL23431)", credits: 4 },
{ name: "Database Management Systems Laboratory (CS23421)", credits: 1 },
{ name: "Operating Systems Laboratory (CS23422)", credits: 1 },
{ name: "Enterprise Resource Planning (CB23IC2)", credits: 1 },
{ name: "NCC / Service Club Credit Course Level 2", credits: 3 }
],
5: [
{ name: "Data and Information Security (CB23511)", credits: 3 },
{ name: "Fundamentals of Management (CB23512)", credits: 3 },
{ name: "Professional Elective I", credits: 3, isElective: true, electiveSlot: 1 },
{ name: "Professional Elective II", credits: 3, isElective: true, electiveSlot: 2 },
{ name: "Mandatory Course I", credits: 0 },
{ name: "Deep Learning Techniques (AD23531)", credits: 4 },
{ name: "Business Analytics (CB23531)", credits: 4 },
{ name: "Data and Information Security Laboratory (CB23521)", credits: 1 },
{ name: "Business Communication Laboratory – I (GE23521)", credits: 1 },
{ name: "Visualization Tools using R (CB23IC3)", credits: 1 }
],
6: [
{ name: "Professional Elective III", credits: 3, isElective: true, electiveSlot: 3 },
{ name: "Professional Elective IV", credits: 3, isElective: true, electiveSlot: 4 },
{ name: "Open Elective I", credits: 3 },
{ name: "Open Elective II", credits: 3 },
{ name: "Mandatory Course II", credits: 0 },
{ name: "Embedded Systems and IoT (EC23631)", credits: 4 },
{ name: "Object Oriented Software Engineering (CS23631)", credits: 4 },
{ name: "Mini Project (CB23621)", credits: 2 },
{ name: "Business Communication Laboratory – II (GE23621)", credits: 1 },
{ name: "NCC / Service Club Credit Course Level 3", credits: 3 }
],
7: [
{ name: "Human Values and Ethics (GE23711)", credits: 2 },
{ name: "Elective – Management", credits: 3 },
{ name: "Cryptography and Cyber Security (CS23513)", credits: 3 },
{ name: "Professional Elective V", credits: 3, isElective: true, electiveSlot: 5 },
{ name: "Professional Elective VI", credits: 3, isElective: true, electiveSlot: 6 },
{ name: "Cloud Computing (CS23731)", credits: 4 },
{ name: "Internship / Certification Course (CB23721)", credits: 2 }
],
8: [
{ name: "Open Elective III", credits: 3 },
{ name: "Project Work (CB23821)", credits: 10 }
]
},
CCE: {
1: [
{ name: "Communicative English (HS23111)", credits: 3 },
{ name: "Matrices and Calculus (MA23111)", credits: 4 },
{ name: "Physics for Electronics Engineering (PH23112)", credits: 3 },
{ name: "Problem Solving and C Programming (GE23111)", credits: 3 },
{ name: "Circuit Analysis (EC23111)", credits: 4 },
{ name: "Heritage of Tamils (GE23112)", credits: 0 },
{ name: "Problem Solving and C Programming Laboratory (GE23121)", credits: 1 },
{ name: "Engineering Practices Laboratory (GE23122)", credits: 1 },
{ name: "Physics Laboratory (PH23121)", credits: 1 }
],
2: [
{ name: "Professional English (HS23211)", credits: 2 },
{ name: "Statistics and Numerical Methods (MA23211)", credits: 4 },
{ name: "Engineering Chemistry (CY23211)", credits: 3 },
{ name: "Python for Data Science (AD23211)", credits: 3 },
{ name: "Tamils and Technology (GE23213)", credits: 0 },
{ name: "Electronic Devices and Circuits (EC23231)", credits: 4 },
{ name: "Engineering Graphics (GE23231)", credits: 4 },
{ name: "Chemistry Laboratory (CY23221)", credits: 1 },
{ name: "Python for Data Science Laboratory (AD23221)", credits: 1 },
{ name: "Communication Laboratory / Foreign Language (GE23221)", credits: 1 },
{ name: "NCC / Service Club Credit Course Level 1", credits: 1 }
],
3: [
{ name: "Environmental Science and Sustainability (GE23311)", credits: 2 },
{ name: "Object Oriented Programming (CS23312)", credits: 3 },
{ name: "Wide Band-gap Devices (EV23311)", credits: 3 },
{ name: "Digital System Design (EC23312)", credits: 3 },
{ name: "Signals and Systems (EC23313)", credits: 4 },
{ name: "Digital System Design Laboratory (EC23321)", credits: 1 },
{ name: "Object Oriented Programming Laboratory (CS23322)", credits: 1 },
{ name: "PCB Design (EC23IC1)", credits: 1 }
],
4: [
{ name: "Random Process and Linear Algebra (MA23412)", credits: 4 },
{ name: "Microprocessors and Microcontrollers (EV23411)", credits: 3 },
{ name: "Electromagnetic Fields (EC23412)", credits: 3 },
{ name: "Linear Integrated Circuits (EC23413)", credits: 3 },
{ name: "Digital Signal Processing (EC23431)", credits: 4 },
{ name: "Networks and Security (EC23432)", credits: 3 },
{ name: "Microprocessors and Microcontrollers Laboratory (EV23421)", credits: 1 },
{ name: "Linear Integrated Circuits Laboratory (EC23422)", credits: 1 },
{ name: "Design Thinking for Engineers (CC23IC2)", credits: 1 },
{ name: "NCC / Service Club Credit Course Level 2", credits: 2 }
],
5: [
{ name: "ASIC Design (EV23511)", credits: 3 },
{ name: "VLSI and Chip Design (EC23512)", credits: 3 },
{ name: "Professional Elective I", credits: 3, isElective: true, electiveSlot: 1 },
{ name: "Professional Elective II", credits: 3, isElective: true, electiveSlot: 2 },
{ name: "Mandatory Course I", credits: 0 },
{ name: "Embedded Systems and IoT Design (EC23531)", credits: 4 },
{ name: "Artificial Intelligence and Machine Learning (AL23431)", credits: 4 },
{ name: "VLSI Laboratory (EC23521)", credits: 1 },
{ name: "Introduction to ARM Based System Design (EV23IC3)", credits: 1 }
],
6: [
{ name: "CMOS Analog and Mixed Signal IC Design (EV23611)", credits: 3 },
{ name: "Digital Logic Synthesis using HDL (EV23612)", credits: 4 },
{ name: "Professional Elective III", credits: 3, isElective: true, electiveSlot: 3 },
{ name: "Professional Elective IV", credits: 3, isElective: true, electiveSlot: 4 },
{ name: "Open Elective I", credits: 3 },
{ name: "Open Elective II", credits: 3 },
{ name: "Mandatory Course II", credits: 0 },
{ name: "Mini Project (EC23621)", credits: 2 },
{ name: "NCC / Service Club Credit Course Level 3", credits: 3 }
],
7: [
{ name: "Human Values and Ethics (GE23711)", credits: 2 },
{ name: "Elective – Management", credits: 3 },
{ name: "Professional Elective V", credits: 3, isElective: true, electiveSlot: 5 },
{ name: "Professional Elective VI", credits: 3, isElective: true, electiveSlot: 6 },
{ name: "Internship / Certification Course", credits: 2 }
],
8: [
{ name: "Open Elective III", credits: 3 },
{ name: "Project Work", credits: 10 }
]
},
CSE: {
1: [
{ name: "Communicative English (HS23111)", credits: 3 },
{ name: "Engineering Chemistry (CY23111)", credits: 3 },
{ name: "Matrices and Calculus (MA23111)", credits: 4 },
{ name: "Problem Solving and C Programming (GE23111)", credits: 3 },
{ name: "Heritage of Tamils (GE23112)", credits: 0 },
{ name: "Engineering Graphics (GE23131)", credits: 4 },
{ name: "Chemistry Laboratory (CY23121)", credits: 1 },
{ name: "Problem Solving and C Programming Laboratory (GE23121)", credits: 1 }
],
2: [
{ name: "Professional English (HS23211)", credits: 2 },
{ name: "Statistics and Numerical Methods (MA23211)", credits: 4 },
{ name: "Physics for Information Science (PH23211)", credits: 3 },
{ name: "Python for Data Science (AD23211)", credits: 3 },
{ name: "Basic Electrical and Electronics Engineering (GE23211)", credits: 3 },
{ name: "Tamils and Technology (GE23213)", credits: 0 },
{ name: "Physics Laboratory (PH23221)", credits: 1 },
{ name: "Python for Data Science Laboratory (AD23221)", credits: 1 },
{ name: "Communication Laboratory / Foreign Language (GE23221)", credits: 1 },
{ name: "Engineering Practices Laboratory (GE23223)", credits: 1 },
{ name: "NCC / Service Club Credit Course Level 1", credits: 2 }
],
3: [
{ name: "Environmental Science and Sustainability (GE23311)", credits: 2 },
{ name: "Discrete Mathematics (MA23311)", credits: 4 },
{ name: "Artificial Intelligence (AL23311)", credits: 3 },
{ name: "Data Structures (CS23311)", credits: 3 },
{ name: "Object Oriented Programming (CS23312)", credits: 3 },
{ name: "Digital Principles and Computer Organization (EC23331)", credits: 4 },
{ name: "Data Structures Laboratory (CS23321)", credits: 1 },
{ name: "Object Oriented Programming Laboratory (CS23322)", credits: 1 },
{ name: "Design Thinking for Software Engineers", credits: 1 }
],
4: [
{ name: "Database Management Systems (CS23411)", credits: 3 },
{ name: "Operating Systems (CS23412)", credits: 3 },
{ name: "Theory of Computation (CS23413)", credits: 3 },
{ name: "Software Development Practices (CS23414)", credits: 3 },
{ name: "Machine Learning Techniques (AL23432)", credits: 4 },
{ name: "Design and Analysis of Algorithms (CS23431)", credits: 4 },
{ name: "Database Management Systems Laboratory (CS23421)", credits: 1 },
{ name: "Operating Systems Laboratory (CS23422)", credits: 1 },
{ name: "NCC / Service Club Credit Course Level 2", credits: 3 }
],
5: [
{ name: "Computer Networks (CS23511)", credits: 3 },
{ name: "Compiler Design (CS23512)", credits: 3 },
{ name: "Professional Elective I", credits: 3, isElective: true, electiveSlot: 1 },
{ name: "Professional Elective II", credits: 3, isElective: true, electiveSlot: 2 },
{ name: "Mandatory Course I", credits: 0 },
{ name: "Deep Learning Techniques (AD23531)", credits: 4 },
{ name: "Data Exploration and Visualization (AD23532)", credits: 4 },
{ name: "Computer Networks Laboratory (CS23521)", credits: 1 },
{ name: "Industry Oriented Course", credits: 1 }
],
6: [
{ name: "Professional Elective III", credits: 3, isElective: true, electiveSlot: 3 },
{ name: "Professional Elective IV", credits: 3, isElective: true, electiveSlot: 4 },
{ name: "Open Elective I", credits: 3 },
{ name: "Open Elective II", credits: 3 },
{ name: "Mandatory Course II", credits: 0 },
{ name: "Embedded Systems and IoT (EC23631)", credits: 4 },
{ name: "Object Oriented Software Engineering (CS23631)", credits: 4 },
{ name: "Mini Project", credits: 2 },
{ name: "NCC / Service Club Credit Course Level 3", credits: 3 }
],
7: [
{ name: "Human Values and Ethics (GE23711)", credits: 2 },
{ name: "Elective – Management", credits: 3 },
{ name: "Cryptography and Cyber Security (CS23513)", credits: 3 },
{ name: "Professional Elective V", credits: 3, isElective: true, electiveSlot: 5 },
{ name: "Professional Elective VI", credits: 3, isElective: true, electiveSlot: 6 },
{ name: "Natural Language Processing (AL23531)", credits: 4 },
{ name: "Internship / Certification Course", credits: 2 }
],
8: [
{ name: "Open Elective III", credits: 3 },
{ name: "Project Work", credits: 10 }
]
},
ECE: {
1: [
{ name: "Communicative English (HS23111)", credits: 3 },
{ name: "Matrices and Calculus (MA23111)", credits: 4 },
{ name: "Physics for Electronics Engineering (PH23112)", credits: 3 },
{ name: "Problem Solving and C Programming (GE23111)", credits: 3 },
{ name: "Circuit Analysis (EC23111)", credits: 4 },
{ name: "Heritage of Tamils (GE23112)", credits: 0 },
{ name: "Physics Laboratory (PH23121)", credits: 1 },
{ name: "Problem Solving and C Programming Laboratory (GE23121)", credits: 1 },
{ name: "Engineering Practices Laboratory (GE23122)", credits: 1 }
],
2: [
{ name: "Professional English (HS23211)", credits: 2 },
{ name: "Engineering Chemistry (CY23211)", credits: 3 },
{ name: "Statistics and Numerical Methods (MA23211)", credits: 4 },
{ name: "Python for Data Science (AD23211)", credits: 3 },
{ name: "Tamils and Technology (GE23213)", credits: 0 },
{ name: "Electronic Devices and Circuits (EC23231)", credits: 4 },
{ name: "Engineering Graphics (GE23231)", credits: 4 },
{ name: "Chemistry Laboratory (CY23221)", credits: 1 },
{ name: "Python for Data Science Laboratory (AD23221)", credits: 1 },
{ name: "Communication Laboratory / Foreign Language (GE23221)", credits: 1 },
{ name: "NCC / Service Club Credit Course Level 1", credits: 2 }
],
3: [
{ name: "Environmental Science and Sustainability (GE23311)", credits: 2 },
{ name: "Object Oriented Programming (CS23312)", credits: 3 },
{ name: "Control Systems (EC23311)", credits: 4 },
{ name: "Digital System Design (EC23312)", credits: 3 },
{ name: "Signals and Systems (EC23313)", credits: 4 },
{ name: "Digital System Design Laboratory (EC23321)", credits: 1 },
{ name: "Object Oriented Programming Laboratory (CS23322)", credits: 1 },
{ name: "PCB Design (EC23IC1)", credits: 1 }
],
4: [
{ name: "Random Process and Linear Algebra (MA23412)", credits: 4 },
{ name: "Communication Systems (EC23411)", credits: 3 },
{ name: "Electromagnetic Fields (EC23412)", credits: 3 },
{ name: "Linear Integrated Circuits (EC23413)", credits: 3 },
{ name: "Digital Signal Processing (EC23431)", credits: 4 },
{ name: "Networks and Security (EC23432)", credits: 3 },
{ name: "Communication Systems Laboratory (EC23421)", credits: 1 },
{ name: "Linear Integrated Circuits Laboratory (EC23422)", credits: 1 },
{ name: "Cyber Security (EC23IC2)", credits: 1 },
{ name: "NCC / Service Club Credit Course Level 2", credits: 3 }
],
5: [
{ name: "Transmission Lines & RF Systems (EC23511)", credits: 3 },
{ name: "VLSI and Chip Design (EC23512)", credits: 3 },
{ name: "Professional Elective I", credits: 3, isElective: true, electiveSlot: 1 },
{ name: "Professional Elective II", credits: 3, isElective: true, electiveSlot: 2 },
{ name: "Mandatory Course I", credits: 0 },
{ name: "Embedded Systems and IoT Design (EC23531)", credits: 4 },
{ name: "Artificial Intelligence and Machine Learning (AL23431)", credits: 4 },
{ name: "VLSI Laboratory (EV23521)", credits: 1 },
{ name: "Introduction to Robotics (EC23IC3)", credits: 1 }
],
6: [
{ name: "Antenna Theory (EC23611)", credits: 3 },
{ name: "Wireless Communication (EC23612)", credits: 3 },
{ name: "Professional Elective III", credits: 3, isElective: true, electiveSlot: 3 },
{ name: "Professional Elective IV", credits: 3, isElective: true, electiveSlot: 4 },
{ name: "Open Elective I", credits: 3 },
{ name: "Open Elective II", credits: 3 },
{ name: "Mandatory Course II", credits: 0 },
{ name: "Mini Project (EC23621)", credits: 2 },
{ name: "Wireless Communication Laboratory (EC23622)", credits: 1 },
{ name: "NCC / Service Club Credit Course Level 3", credits: 3 }
],
7: [
{ name: "Human Values and Ethics (GE23711)", credits: 2 },
{ name: "Elective – Management", credits: 3 },
{ name: "Ad Hoc and Wireless Sensor Networks (EC23711)", credits: 3 },
{ name: "Professional Elective V", credits: 3, isElective: true, electiveSlot: 5 },
{ name: "Professional Elective VI", credits: 3, isElective: true, electiveSlot: 6 },
{ name: "Internship / Certification Course", credits: 2 }
],
8: [
{ name: "Open Elective III", credits: 3 },
{ name: "Project Work", credits: 10 }
]
},
VLSI: {
1: [
{ name: "Communicative English (HS23111)", credits: 3 },
{ name: "Matrices and Calculus (MA23111)", credits: 4 },
{ name: "Physics for Electronics Engineering (PH23112)", credits: 3 },
{ name: "Problem Solving and C Programming (GE23111)", credits: 3 },
{ name: "Circuit Analysis (EC23111)", credits: 4 },
{ name: "Heritage of Tamils (GE23112)", credits: 0 },
{ name: "Problem Solving and C Programming Laboratory (GE23121)", credits: 1 },
{ name: "Engineering Practices Laboratory (GE23122)", credits: 1 },
{ name: "Physics Laboratory (PH23121)", credits: 1 }
],
2: [
{ name: "Professional English (HS23211)", credits: 2 },
{ name: "Statistics and Numerical Methods (MA23211)", credits: 4 },
{ name: "Engineering Chemistry (CY23211)", credits: 3 },
{ name: "Python for Data Science (AD23211)", credits: 3 },
{ name: "Tamils and Technology (GE23213)", credits: 0 },
{ name: "Electronic Devices and Circuits (EC23231)", credits: 4 },
{ name: "Engineering Graphics (GE23231)", credits: 4 },
{ name: "Chemistry Laboratory (CY23221)", credits: 1 },
{ name: "Python for Data Science Laboratory (AD23221)", credits: 1 },
{ name: "Communication Laboratory / Foreign Language (GE23221)", credits: 1 }
],
3: [
{ name: "Environmental Science and Sustainability (GE23311)", credits: 2 },
{ name: "Wide Band-gap Devices (EV23311)", credits: 3 },
{ name: "Digital System Design (EC23312)", credits: 3 },
{ name: "Signals and Systems (EC23313)", credits: 4 },
{ name: "Object Oriented Programming (CS23312)", credits: 3 },
{ name: "Digital System Design Laboratory (EC23321)", credits: 1 },
{ name: "Object Oriented Programming Laboratory (CS23322)", credits: 1 },
{ name: "PCB Design (EC23IC1)", credits: 1 }
],
4: [
{ name: "Random Process and Linear Algebra (MA23412)", credits: 4 },
{ name: "Microprocessors and Microcontrollers (EV23411)", credits: 3 },
{ name: "Electromagnetic Fields (EC23412)", credits: 3 },
{ name: "Linear Integrated Circuits (EC23413)", credits: 3 },
{ name: "Digital Signal Processing (EC23431)", credits: 4 },
{ name: "Networks and Security (EC23432)", credits: 3 },
{ name: "Microprocessors and Microcontrollers Laboratory (EV23421)", credits: 1 },
{ name: "Linear Integrated Circuits Laboratory (EC23422)", credits: 1 },
{ name: "Design Thinking for Engineers (CC23IC2)", credits: 1 },
{ name: "NCC / Service Club Credit Course Level 2", credits: 2 }
],
5: [
{ name: "ASIC Design (EV23511)", credits: 3 },
{ name: "VLSI and Chip Design (EC23512)", credits: 3 },
{ name: "Professional Elective I", credits: 3, isElective: true, electiveSlot: 1 },
{ name: "Professional Elective II", credits: 3, isElective: true, electiveSlot: 2 },
{ name: "Mandatory Course I", credits: 0 },
{ name: "Embedded Systems and IoT Design (EC23531)", credits: 4 },
{ name: "Artificial Intelligence and Machine Learning (AL23431)", credits: 4 },
{ name: "VLSI Laboratory (EC23521)", credits: 1 },
{ name: "Introduction to ARM Based System Design (EV23IC3)", credits: 1 }
],
6: [
{ name: "CMOS Analog and Mixed Signal IC Design (EV23611)", credits: 3 },
{ name: "Digital Logic Synthesis using HDL (EV23612)", credits: 4 },
{ name: "Professional Elective III", credits: 3, isElective: true, electiveSlot: 3 },
{ name: "Professional Elective IV", credits: 3, isElective: true, electiveSlot: 4 },
{ name: "Open Elective I", credits: 3 },
{ name: "Open Elective II", credits: 3 },
{ name: "Mandatory Course II", credits: 0 },
{ name: "Mini Project", credits: 2 },
{ name: "NCC / Service Club Credit Course Level 3", credits: 3 }
],
7: [
{ name: "Human Values and Ethics (GE23711)", credits: 2 },
{ name: "Elective – Management", credits: 3 },
{ name: "Professional Elective V", credits: 3, isElective: true, electiveSlot: 5 },
{ name: "Professional Elective VI", credits: 3, isElective: true, electiveSlot: 6 },
{ name: "Internship / Certification Course", credits: 2 }
],
8: [
{ name: "Open Elective III", credits: 3 },
{ name: "Project Work", credits: 10 }
]
},
MECH: {
1: [
{ name: "Communicative English (HS23111)", credits: 3 },
{ name: "Matrices and Calculus (MA23111)", credits: 4 },
{ name: "Electrical, Electronics and Instrumentation Engineering (GE23114)", credits: 3 },
{ name: "Problem Solving and C Programming (GE23111)", credits: 3 },
{ name: "Materials Science (PH23113)", credits: 3 },
{ name: "Heritage of Tamils (GE23112)", credits: 0 },
{ name: "Physics Laboratory (PH23121)", credits: 1 },
{ name: "Problem Solving and C Programming Laboratory (GE23121)", credits: 1 },
{ name: "Engineering Practices Laboratory (GE23122)", credits: 1 },
{ name: "Basic Electrical and Electronics Engineering Laboratory (GE23123)", credits: 1 }
],
2: [
{ name: "Professional English (HS23211)", credits: 2 },
{ name: "Engineering Chemistry (CY23211)", credits: 3 },
{ name: "Statistics and Numerical Methods (MA23211)", credits: 4 },
{ name: "Python for Data Science (AD23211)", credits: 3 },
{ name: "Tamils and Technology (GE23213)", credits: 0 },
{ name: "Engineering Graphics (GE23231)", credits: 4 },
{ name: "Chemistry Laboratory (CY23221)", credits: 1 },
{ name: "Python for Data Science Laboratory (AD23221)", credits: 1 },
{ name: "Communication Laboratory / Foreign Language (GE23221)", credits: 1 },
{ name: "NCC / Service Club Credit Course Level 1", credits: 2 }
],
3: [
{ name: "Transforms and Partial Differential Equations (MA23313)", credits: 4 },
{ name: "Engineering Mechanics (ME23311)", credits: 3 },
{ name: "Engineering Thermodynamics (ME23312)", credits: 4 },
{ name: "Fluid Mechanics and Machinery (ME23313)", credits: 4 },
{ name: "Manufacturing Processes (ME23314)", credits: 3 },
{ name: "Object Oriented Programming (CS23312)", credits: 3 },
{ name: "Computer Aided Machine Drawing Laboratory (ME23321)", credits: 1 },
{ name: "Object Oriented Programming Laboratory (CS23322)", credits: 1 }
],
4: [
{ name: "Environmental Science for Mechanical Engineers (GE23412)", credits: 2 },
{ name: "Engineering Materials and Metallurgy (ME23411)", credits: 3 },
{ name: "Manufacturing Technology (ME23412)", credits: 3 },
{ name: "Mechanics of Solids (ME23413)", credits: 3 },
{ name: "Theory of Machines (ME23414)", credits: 4 },
{ name: "Thermal Engineering (ME23431)", credits: 4 },
{ name: "Manufacturing Technology Laboratory (ME23421)", credits: 1 },
{ name: "Strength of Materials and Fluid Machinery Laboratory (ME23422)", credits: 1 },
{ name: "Introduction to Product Lifecycle Management (ME23IC1)", credits: 1 },
{ name: "NCC / Service Club Credit Course Level 2", credits: 3 }
],
5: [
{ name: "Design of Machine Elements (ME23511)", credits: 4 },
{ name: "Heat and Mass Transfer (ME23512)", credits: 4 },
{ name: "Professional Elective I", credits: 3, isElective: true, electiveSlot: 1 },
{ name: "Professional Elective II", credits: 3, isElective: true, electiveSlot: 2 },
{ name: "Mandatory Course I", credits: 0 },
{ name: "Mechatronics (ME23531)", credits: 4 },
{ name: "Heat Transfer Laboratory (ME23521)", credits: 1 },
{ name: "Professional / Skill Development (ME23522)", credits: 1 },
{ name: "Introduction to Supply Chain Management (ME23IC2)", credits: 1 }
],
6: [
{ name: "Design of Transmission Systems (ME23611)", credits: 3 },
{ name: "Professional Elective III", credits: 3, isElective: true, electiveSlot: 3 },
{ name: "Professional Elective IV", credits: 3, isElective: true, electiveSlot: 4 },
{ name: "Open Elective I", credits: 3 },
{ name: "Open Elective II", credits: 3 },
{ name: "Mandatory Course II", credits: 0 },
{ name: "Metrology and Measurements (ME23631)", credits: 4 },
{ name: "Design and Fabrication Project (ME23621)", credits: 2 },
{ name: "CAD and CAM Laboratory (ME23622)", credits: 1 },
{ name: "Dynamics Laboratory (ME23623)", credits: 1 },
{ name: "Introduction to HVAC Systems (ME23IC3)", credits: 1 },
{ name: "NCC / Service Club Credit Course Level 3", credits: 3 }
],
7: [
{ name: "Human Values and Ethics (GE23711)", credits: 2 },
{ name: "Elective – Management", credits: 3 },
{ name: "Industrial Robotics (ME23712)", credits: 4 },
{ name: "Finite Element Analysis (ME23713)", credits: 4 },
{ name: "Professional Elective V", credits: 3, isElective: true, electiveSlot: 5 },
{ name: "Professional Elective VI", credits: 3, isElective: true, electiveSlot: 6 },
{ name: "Internship / Certification Course (ME23721)", credits: 2 }
],
8: [
{ name: "Open Elective III", credits: 3 },
{ name: "Project Work", credits: 10 }
]
}
};

View File

@@ -117,13 +117,22 @@ export const FEATURES: Feature[] = [
bgColor: '#FFFBEB',
},
{
id: 'raise',
icon: 'Rocket',
title: 'RAISE Incubator',
description: 'Pitch startup ideas, get incubation support, seed funding opportunities, and entrepreneurial mentoring.',
path: '/raise',
color: '#EC4899',
bgColor: '#FDF2F8',
id: 'gatepass',
icon: 'Ticket',
title: 'Student Gate Pass',
description: 'Request digital campus out-pass, track warden approvals, and present clearance QR codes.',
path: '/notes?portal=gatepass',
color: '#10B981',
bgColor: '#ECFDF5',
},
{
id: 'proficiency',
icon: 'Award',
title: 'Student Proficiency',
description: 'Track domain competency scores, placement readiness analytics, and verified skill certifications.',
path: '/notes?portal=proficiency',
color: '#8B5CF6',
bgColor: '#F5F3FF',
},
];
@@ -3104,6 +3113,26 @@ export const EVENTS_DATA: Event[] = [
// ─── Clubs ───────────────────────────────────────────────────────────────────
export const CLUBS_DATA: Club[] = [
{
id: 'center_raise',
name: 'RAISE INCUBATOR',
description: 'Pitch startup ideas, get incubation support, seed funding opportunities, and entrepreneurial mentoring.',
details: 'RAISE Incubator is a dedicated Section 8 (not-for-profit) company situated directly within the Rajalakshmi Institute of Technology campus. We transform engineering ideas into market-viable products with seed funding, mentoring, and patent support.',
category: 'Center of Excellence',
type: 'Center',
members: 2450,
presidentName: 'Incubation Director',
vicePresidentName: 'Startup Lead',
coordinatorName: 'Dr. RIT Innovation Cell',
year: 'Campus Incubation Center',
contactEmail: 'incubator@ritchennai.edu.in',
contactPhone: '+91 44 6718 1600',
icon: 'Rocket',
logoUrl: '/logo.png',
socialLinks: {
website: '/raise',
},
},
{
id: 'nss',
name: 'NSS OF RIT',
@@ -3760,13 +3789,13 @@ export const QUESTIONS_DATA: Question[] = [
// ─── Toolkit Items ───────────────────────────────────────────────────────────
export const TOOLKIT_ITEMS: ToolkitItem[] = [
{ id: '7', title: 'GPA and internal calculator', description: 'Access GPA, CGPA, and internal marks calculator utilities.', type: 'link', url: '#', icon: 'Calculator', category: 'Engineering' },
{ id: '1', title: 'CS tools', description: 'Access specialized development environments, IDE configurations, compiler guides, GitHub setup instructions, and essential documentation for Computer Science students.', type: 'link', url: '#', icon: 'Code', category: 'Engineering' },
{ id: '2', title: 'Business tools', description: 'Explore enterprise resource planning (ERP) guides, financial spreadsheets, management templates, and business analytics tools for CSBS and management students.', type: 'link', url: '#', icon: 'Briefcase', category: 'Engineering' },
{ id: '3', title: 'Cybersecurity tools', description: 'Discover network simulators, virtualization setup guides, penetration testing tutorials, cryptography tools, and security lab blueprints.', type: 'link', url: '#', icon: 'Shield', category: 'Engineering' },
{ id: '4', title: 'AI tools', description: 'Configure machine learning frameworks, deep learning libraries, Jupyter environments, dataset download scripts, and pre-trained model APIs.', type: 'link', url: '#', icon: 'Brain', category: 'Engineering' },
{ id: '5', title: 'Electrical and Electronic tools', description: 'Access circuit design simulators, MATLAB packages, microcontroller IDE setups, hardware debugging guides, and lab calculation spreadsheets.', type: 'link', url: '#', icon: 'Cpu', category: 'Engineering' },
{ id: '6', title: 'Biotech tools', description: 'Find biology lab guidelines, chemical structure tools, bioinformatics databases tutorials, genetic sequence analysis resources, and safety manuals.', type: 'link', url: '#', icon: 'FlaskConical', category: 'Engineering' },
{ id: '7', title: 'GPA and internal calculator', description: 'Access GPA, CGPA, and internal marks calculator utilities.', type: 'link', url: '#', icon: 'Calculator', category: 'Engineering' },
];
// ─── Campus Locations ────────────────────────────────────────────────────────
@@ -3803,5 +3832,9 @@ export const DEPARTMENTS = [
'Computer Science & Engineering',
'Electronics & Communication Engineering',
'Electronics Engineering VLSI (Design and Technology)',
'Humanities & Sciences',
'M.E. (VLSI Design)',
'M.Tech (Data Science)',
'Mathematics',
'Mechanical Engineering',
];

View File

@@ -2,6 +2,7 @@ import { createContext, useContext, useState, useEffect, useCallback } from 'rea
import type { ReactNode } from 'react';
import { getBackendUrl } from '@/lib/utils';
import GoogleAuthModal from '@/components/Auth/GoogleAuthModal';
import { getStoredImsSession, clearImsSession, saveImsSession, loginWithIms, type StudentInfo } from '@/services/imsService';
// ──────────────────────────────────────────────────
// Types
@@ -13,15 +14,28 @@ export interface AuthUser {
name: string;
pictureUrl?: string;
verifiedStudent: boolean;
role?: 'ROLE_STUDENT' | 'ROLE_TRANSPORT' | 'ROLE_SUPER_ADMIN' | 'ROLE_USER';
regNumber?: string;
department?: string;
}
export interface LoginCredentialsResult {
success: boolean;
message?: string;
redirectTo?: string;
role?: string;
}
interface AuthContextType {
user: AuthUser | null;
isAuthenticated: boolean;
isVerifiedStudent: boolean;
isAdmin: boolean;
isTransportAdmin: boolean;
isLoading: boolean;
isAuthModalOpen: boolean;
loginWithGoogle: () => void;
loginWithCredentials: (username: string, password: string) => Promise<LoginCredentialsResult>;
openAuthModal: () => void;
closeAuthModal: () => void;
logout: () => void;
@@ -43,9 +57,12 @@ const AuthContext = createContext<AuthContextType>({
user: null,
isAuthenticated: false,
isVerifiedStudent: false,
isAdmin: false,
isTransportAdmin: false,
isLoading: true,
isAuthModalOpen: false,
loginWithGoogle: () => {},
loginWithCredentials: async () => ({ success: false }),
openAuthModal: () => {},
closeAuthModal: () => {},
logout: () => {},
@@ -54,29 +71,13 @@ const AuthContext = createContext<AuthContextType>({
export const useAuth = () => useContext(AuthContext);
// ──────────────────────────────────────────────────
// Google GSI global type
// Storage Keys
// ──────────────────────────────────────────────────
declare global {
interface Window {
google?: {
accounts: {
id: {
initialize: (config: Record<string, unknown>) => void;
prompt: (callback?: (notification: { isNotDisplayed: () => boolean; isSkippedMoment: () => boolean }) => void) => void;
renderButton: (element: HTMLElement, config: Record<string, unknown>) => void;
revoke: (email: string, callback: () => void) => void;
};
};
};
}
}
// ──────────────────────────────────────────────────
// Provider
// ──────────────────────────────────────────────────
const STORAGE_KEY = 'rit_auth_user';
const GOOGLE_STORAGE_KEY = 'rit_auth_user';
const ADMIN_TOKEN_KEY = 'RIT_ADMIN_TOKEN';
const ADMIN_ROLE_KEY = 'RIT_ADMIN_ROLE';
const ADMIN_USER_KEY = 'RIT_ADMIN_USER';
export function AuthProvider({ children }: { children: ReactNode }) {
const [user, setUser] = useState<AuthUser | null>(null);
@@ -86,7 +87,54 @@ export function AuthProvider({ children }: { children: ReactNode }) {
const openAuthModal = useCallback(() => setIsAuthModalOpen(true), []);
const closeAuthModal = useCallback(() => setIsAuthModalOpen(false), []);
// Handle the credential response from Google GSI
// Restore any active session on app load
useEffect(() => {
// 1. Check Admin Session
const adminToken = localStorage.getItem(ADMIN_TOKEN_KEY);
const adminRole = localStorage.getItem(ADMIN_ROLE_KEY);
const adminUser = localStorage.getItem(ADMIN_USER_KEY);
if (adminToken && adminRole) {
setUser({
id: 999999,
name: adminUser || (adminRole === 'ROLE_TRANSPORT' ? 'Transport Admin' : 'Super Admin'),
email: adminRole === 'ROLE_TRANSPORT' ? 'transport@ritchennai.edu.in' : 'admin@ritchennai.edu.in',
verifiedStudent: false,
role: adminRole as any,
});
setIsLoading(false);
return;
}
// 2. Check IMS Student Session
const imsSession = getStoredImsSession();
if (imsSession?.student) {
setUser({
id: Number(imsSession.student.regNumber) || 1,
name: imsSession.student.name,
email: imsSession.student.email,
regNumber: imsSession.student.regNumber,
department: imsSession.student.department,
verifiedStudent: true,
role: 'ROLE_STUDENT',
});
setIsLoading(false);
return;
}
// 3. Check Google Session
const googleStored = localStorage.getItem(GOOGLE_STORAGE_KEY);
if (googleStored) {
try {
const parsed = JSON.parse(googleStored) as AuthUser;
setUser({ ...parsed, role: 'ROLE_USER' });
} catch {
localStorage.removeItem(GOOGLE_STORAGE_KEY);
}
}
setIsLoading(false);
}, []);
// Handle Google OAuth GSI
const handleCredentialResponse = useCallback(async (response: { credential: string }) => {
try {
const res = await fetch(getBackendUrl('/api/auth/google'), {
@@ -95,15 +143,13 @@ export function AuthProvider({ children }: { children: ReactNode }) {
body: JSON.stringify({ credential: response.credential }),
});
if (!res.ok) {
console.error('Auth failed:', res.status);
return;
}
if (res.ok) {
const userData: AuthUser = await res.json();
setUser(userData);
localStorage.setItem(STORAGE_KEY, JSON.stringify(userData));
const userObj: AuthUser = { ...userData, role: 'ROLE_USER' };
setUser(userObj);
localStorage.setItem(GOOGLE_STORAGE_KEY, JSON.stringify(userObj));
setIsAuthModalOpen(false);
}
} catch (err) {
console.error('Google auth error:', err);
}
@@ -111,42 +157,8 @@ export function AuthProvider({ children }: { children: ReactNode }) {
// Initialize Google GSI
useEffect(() => {
// 1. Restore session from localStorage
const stored = localStorage.getItem(STORAGE_KEY);
if (stored) {
try {
const parsed = JSON.parse(stored) as AuthUser;
setUser(parsed);
// Validate session is still valid against backend
fetch(getBackendUrl(`/api/auth/me?email=${encodeURIComponent(parsed.email)}`))
.then((res) => {
if (!res.ok) {
localStorage.removeItem(STORAGE_KEY);
setUser(null);
} else {
return res.json();
}
})
.then((freshData) => {
if (freshData) {
setUser(freshData);
localStorage.setItem(STORAGE_KEY, JSON.stringify(freshData));
}
})
.catch(() => {
// Backend offline, keep cached session
});
} catch {
localStorage.removeItem(STORAGE_KEY);
}
}
setIsLoading(false);
// 2. Initialize Google GSI when the script loads
const initGSI = () => {
if (!window.google || !GOOGLE_CLIENT_ID) return;
window.google.accounts.id.initialize({
client_id: GOOGLE_CLIENT_ID,
callback: handleCredentialResponse,
@@ -169,17 +181,132 @@ export function AuthProvider({ children }: { children: ReactNode }) {
}, [handleCredentialResponse]);
const loginWithGoogle = useCallback(() => {
// Open the clean Google Sign-In modal directly
setIsAuthModalOpen(true);
// Also trigger One Tap prompt as a secondary background hint if supported
if (window.google) {
try {
window.google.accounts.id.prompt();
} catch {}
}
}, []);
// ─────────────────────────────────────────────────────────────
// UNIFIED CREDENTIALS SIGN-IN (Students & Admins)
// ─────────────────────────────────────────────────────────────
const loginWithCredentials = useCallback(async (username: string, password: string): Promise<LoginCredentialsResult> => {
const cleanedUser = username.trim();
const cleanedPass = password.trim();
if (!cleanedUser || !cleanedPass) {
return { success: false, message: 'Please enter both username/register number and password.' };
}
// 1. First, check if credentials match Admin / Transport
try {
const adminRes = await fetch(getBackendUrl('/api/admin/login'), {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: cleanedUser, password: cleanedPass }),
});
if (adminRes.ok) {
const data = await adminRes.json();
if (data.success && data.token && data.role) {
localStorage.setItem(ADMIN_TOKEN_KEY, data.token);
localStorage.setItem(ADMIN_ROLE_KEY, data.role);
localStorage.setItem(ADMIN_USER_KEY, data.username);
const adminUserObj: AuthUser = {
id: 999999,
name: data.username,
email: data.role === 'ROLE_TRANSPORT' ? 'transport@ritchennai.edu.in' : 'admin@ritchennai.edu.in',
verifiedStudent: false,
role: data.role,
};
setUser(adminUserObj);
setIsAuthModalOpen(false);
return {
success: true,
role: data.role,
redirectTo: '/admin',
message: `${data.username} logged in successfully`,
};
}
}
} catch {
// Silently ignore if browser blocks One Tap
// If admin endpoint fails or is offline, check fallback
}
// Direct local check for Admin credentials fallback
if (
cleanedUser.toLowerCase() === 'transport' &&
cleanedPass === 'RIT@2026'
) {
const role = 'ROLE_TRANSPORT';
localStorage.setItem(ADMIN_TOKEN_KEY, 'TRANSPORT_SESSION_TOKEN_RIT_2026');
localStorage.setItem(ADMIN_ROLE_KEY, role);
localStorage.setItem(ADMIN_USER_KEY, 'Transport Admin');
setUser({
id: 999999,
name: 'Transport Admin',
email: 'transport@ritchennai.edu.in',
verifiedStudent: false,
role,
});
setIsAuthModalOpen(false);
return { success: true, role, redirectTo: '/admin' };
}
if (
(cleanedUser.toLowerCase() === 'admin' && (cleanedPass === 'RIT@2026' || cleanedPass === 'rit@2026')) ||
(cleanedUser.toLowerCase() === 'ritadmin' && cleanedPass === 'ritadmin2026')
) {
const role = 'ROLE_SUPER_ADMIN';
localStorage.setItem(ADMIN_TOKEN_KEY, 'ADMIN_SESSION_TOKEN_RIT_2026');
localStorage.setItem(ADMIN_ROLE_KEY, role);
localStorage.setItem(ADMIN_USER_KEY, 'Super Admin');
setUser({
id: 999999,
name: 'Super Admin',
email: 'admin@ritchennai.edu.in',
verifiedStudent: false,
role,
});
setIsAuthModalOpen(false);
return { success: true, role, redirectTo: '/admin' };
}
// 2. Next, check IMS Student Login
try {
const imsResult = await loginWithIms(cleanedUser, cleanedPass);
if (imsResult.success && imsResult.student) {
const studentObj: AuthUser = {
id: Number(imsResult.student.regNumber) || 1,
name: imsResult.student.name,
email: imsResult.student.email,
regNumber: imsResult.student.regNumber,
department: imsResult.student.department,
verifiedStudent: true,
role: 'ROLE_STUDENT',
};
setUser(studentObj);
setIsAuthModalOpen(false);
return {
success: true,
role: 'ROLE_STUDENT',
redirectTo: '/dashboard',
message: 'Student login successful',
};
}
} catch {
// Fallback
}
return {
success: false,
message: 'Invalid credentials. Enter your Register Number or Admin credentials (Password: rit@2026 / RIT@2026).',
};
}, []);
const logout = useCallback(() => {
@@ -189,19 +316,29 @@ export function AuthProvider({ children }: { children: ReactNode }) {
} catch {}
}
setUser(null);
localStorage.removeItem(STORAGE_KEY);
localStorage.removeItem(GOOGLE_STORAGE_KEY);
localStorage.removeItem(ADMIN_TOKEN_KEY);
localStorage.removeItem(ADMIN_ROLE_KEY);
localStorage.removeItem(ADMIN_USER_KEY);
clearImsSession();
setIsAuthModalOpen(false);
}, [user]);
const isAdmin = user?.role === 'ROLE_SUPER_ADMIN' || user?.role === 'ROLE_TRANSPORT';
const isTransportAdmin = user?.role === 'ROLE_TRANSPORT';
return (
<AuthContext.Provider
value={{
user,
isAuthenticated: !!user,
isVerifiedStudent: !!user?.verifiedStudent,
isAdmin,
isTransportAdmin,
isLoading,
isAuthModalOpen,
loginWithGoogle,
loginWithCredentials,
openAuthModal,
closeAuthModal,
logout,

File diff suppressed because it is too large Load Diff

View File

@@ -15,14 +15,29 @@ export default function BusRoutes() {
const [isSidebarOpen, setIsSidebarOpen] = useState(false);
useEffect(() => {
// 0. Check local storage if edited by Transport Admin
const localAdminRoutes = localStorage.getItem('RIT_LOCAL_BUS_ROUTES');
if (localAdminRoutes) {
try {
const parsed = JSON.parse(localAdminRoutes);
if (Array.isArray(parsed) && parsed.length > 0) {
setBusRoutes(parsed);
setSelectedBusRoute(parsed[0]);
setLoadingBus(false);
}
} catch {}
}
// 1. Instantly load static bus routes (0ms loading delay)
fetch('/bus_routes.json')
.then((res) => res.json())
.then((data) => {
if (Array.isArray(data) && data.length > 0) {
if (!localStorage.getItem('RIT_LOCAL_BUS_ROUTES')) {
setBusRoutes(data);
setSelectedBusRoute(data[0]);
}
}
})
.catch((err) => console.error('Local JSON load error:', err))
.finally(() => setLoadingBus(false));

View File

@@ -452,7 +452,7 @@ export default function Community() {
<h3 className={`font-bold text-[#1E293B] mb-1 hover:text-[#F97316] transition-colors tracking-tight ${isFeatured ? 'text-base md:text-lg' : 'text-sm md:text-base'
}`}
style={{ fontFamily: 'Playfair Display, serif' }}>
style={{ fontFamily: 'Plus Jakarta Sans, sans-serif' }}>
{q.title}
</h3>

View File

@@ -1,4 +1,5 @@
import { useState, useMemo } from 'react';
import { useState, useMemo, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { motion, AnimatePresence } from 'framer-motion';
import {
Users, Tag, X, Mail, Phone, UserCheck, GraduationCap, Info,
@@ -12,6 +13,13 @@ import { StaggerContainer, StaggerItem } from '@/components/AnimatedContainer/An
import AnimatedContainer from '@/components/AnimatedContainer/AnimatedContainer';
import { CLUBS_DATA } from '@/constants';
import type { Club } from '@/types';
import { useAuth } from '@/context/AuthContext';
import {
getClubUserIdentifier,
fetchClubLikes,
fetchUserLikedClubs,
toggleClubLikeInDb,
} from '@/services/clubService';
const CLUB_CATEGORY_COLORS: Record<string, string> = {
Technical: '#3B82F6',
@@ -118,16 +126,30 @@ const QUIZ_QUESTIONS_ALL = [
];
export default function Events() {
const { user } = useAuth();
const userIdentifier = useMemo(() => getClubUserIdentifier(user?.email), [user?.email]);
const [selectedClub, setSelectedClub] = useState<Club | null>(null);
const [searchQuery, setSearchQuery] = useState('');
const [selectedCategory, setSelectedCategory] = useState<string>('All');
const [selectedType, setSelectedType] = useState<'All' | 'Club' | 'Center'>('All');
const activeClubsData = useMemo(() => {
try {
const saved = localStorage.getItem('RIT_LOCAL_CLUBS');
if (saved) {
const parsed = JSON.parse(saved);
if (Array.isArray(parsed) && parsed.length > 0) return parsed;
}
} catch {}
return CLUBS_DATA;
}, []);
// Compute counts dynamically
const { totalCount, centersCount, clubsCount } = useMemo(() => {
let centers = 0;
let clubs = 0;
CLUBS_DATA.forEach((item) => {
activeClubsData.forEach((item) => {
const isCenter =
item.type === 'Center' ||
item.category === 'Center of Excellence' ||
@@ -136,13 +158,40 @@ export default function Events() {
if (isCenter) centers++;
else clubs++;
});
return { totalCount: CLUBS_DATA.length, centersCount: centers, clubsCount: clubs };
}, []);
return { totalCount: activeClubsData.length, centersCount: centers, clubsCount: clubs };
}, [activeClubsData]);
// ─── Database & LocalStorage Persisted Interactive Like System ───────────
const loadSavedLikesMap = (): Record<string, number> => {
const initialMap: Record<string, number> = {};
CLUBS_DATA.forEach((c) => {
initialMap[c.id] = 0;
});
try {
const savedCounts = localStorage.getItem('rit_freshers_likes_count_v3');
if (savedCounts) {
const parsed = JSON.parse(savedCounts);
Object.assign(initialMap, parsed);
}
} catch {}
try {
const savedLikedList = localStorage.getItem('rit_freshers_liked_clubs_v3');
if (savedLikedList) {
const likedArray: string[] = JSON.parse(savedLikedList);
likedArray.forEach((id) => {
if (!initialMap[id] || initialMap[id] < 1) {
initialMap[id] = 1;
}
});
}
} catch {}
return initialMap;
};
// ─── Interactive Like System ─────────────────────────────────────────────
const [likedClubs, setLikedClubs] = useState<Set<string>>(() => {
try {
localStorage.removeItem('rit_freshers_liked_clubs');
const saved = localStorage.getItem('rit_freshers_liked_clubs_v3');
return saved ? new Set(JSON.parse(saved)) : new Set();
} catch {
@@ -150,32 +199,104 @@ export default function Events() {
}
});
const [likesMap, setLikesMap] = useState<Record<string, number>>(() => {
const initialMap: Record<string, number> = {};
CLUBS_DATA.forEach((c) => {
initialMap[c.id] = 0;
});
return initialMap;
});
const [likesMap, setLikesMap] = useState<Record<string, number>>(loadSavedLikesMap);
const toggleLike = (clubId: string) => {
const isCurrentlyLiked = likedClubs.has(clubId);
const next = new Set(likedClubs);
// Sync likes with database backend on mount and when user identity changes
useEffect(() => {
let isMounted = true;
if (isCurrentlyLiked) {
next.delete(clubId);
setLikesMap((l) => ({ ...l, [clubId]: Math.max(0, (l[clubId] || 1) - 1) }));
} else {
next.add(clubId);
setLikesMap((l) => ({ ...l, [clubId]: (l[clubId] || 0) + 1 }));
async function syncWithDatabase() {
// 1. Fetch total like counts for all clubs from database
const dbLikesMap = await fetchClubLikes();
if (isMounted && Object.keys(dbLikesMap).length > 0) {
setLikesMap((prev) => {
const merged = { ...prev };
Object.entries(dbLikesMap).forEach(([id, count]) => {
merged[id] = Math.max(merged[id] || 0, Number(count) || 0);
});
try {
localStorage.setItem('rit_freshers_likes_count_v3', JSON.stringify(merged));
} catch {}
return merged;
});
}
// 2. Fetch user's liked clubs from database
const userLikedList = await fetchUserLikedClubs(userIdentifier);
if (isMounted && userLikedList && userLikedList.length > 0) {
setLikedClubs((prev) => {
const mergedSet = new Set([...Array.from(prev), ...userLikedList]);
try {
localStorage.setItem('rit_freshers_liked_clubs_v3', JSON.stringify(Array.from(mergedSet)));
} catch {}
return mergedSet;
});
}
}
syncWithDatabase();
return () => {
isMounted = false;
};
}, [userIdentifier]);
const toggleLike = async (clubId: string) => {
const isCurrentlyLiked = likedClubs.has(clubId);
const next = new Set(likedClubs);
let newCount = likesMap[clubId] || 0;
// Optimistic UI update
if (isCurrentlyLiked) {
next.delete(clubId);
newCount = Math.max(0, newCount - 1);
} else {
next.add(clubId);
newCount = newCount + 1;
}
const updatedLikesMap = { ...likesMap, [clubId]: newCount };
setLikedClubs(next);
setLikesMap(updatedLikesMap);
try {
localStorage.setItem('rit_freshers_liked_clubs_v3', JSON.stringify(Array.from(next)));
localStorage.setItem('rit_freshers_likes_count_v3', JSON.stringify(updatedLikesMap));
} catch {}
// Persist like directly in PostgreSQL database backend if available
const dbResult = await toggleClubLikeInDb(clubId, userIdentifier);
if (dbResult) {
setLikesMap((l) => {
const freshMap = { ...l, [clubId]: dbResult.count };
try {
localStorage.setItem('rit_freshers_likes_count_v3', JSON.stringify(freshMap));
} catch {}
return freshMap;
});
if (dbResult.liked) {
setLikedClubs((prev) => {
const s = new Set([...Array.from(prev), clubId]);
try {
localStorage.setItem('rit_freshers_liked_clubs_v3', JSON.stringify(Array.from(s)));
} catch {}
return s;
});
} else {
setLikedClubs((prev) => {
const s = new Set(prev);
s.delete(clubId);
try {
localStorage.setItem('rit_freshers_liked_clubs_v3', JSON.stringify(Array.from(s)));
} catch {}
return s;
});
}
}
};
// ─── Quiz Matcher State ──────────────────────────────────────────────────
const [isQuizOpen, setIsQuizOpen] = useState(false);
const [matcherTarget, setMatcherTarget] = useState<'All' | 'Club' | 'Center'>('All');
@@ -197,7 +318,7 @@ export default function Events() {
const calculateQuizResults = (answers: number[]) => {
const scoreMap: Record<string, number> = {};
CLUBS_DATA.forEach((c) => (scoreMap[c.id] = 0));
activeClubsData.forEach((c) => (scoreMap[c.id] = 0));
answers.forEach((ansIdx, qIdx) => {
const option = QUIZ_QUESTIONS_ALL[qIdx].options[ansIdx];
@@ -208,7 +329,7 @@ export default function Events() {
}
});
const pool = CLUBS_DATA.filter((c) => {
const pool = activeClubsData.filter((c) => {
const isCenter =
c.type === 'Center' ||
c.category === 'Center of Excellence' ||
@@ -254,7 +375,7 @@ export default function Events() {
// ─── Robust Filter Logic ──────────────────────────────────────────────────
const filteredData = useMemo(() => {
return CLUBS_DATA.filter((item) => {
return activeClubsData.filter((item) => {
const isCenter =
item.type === 'Center' ||
item.category === 'Center of Excellence' ||
@@ -268,7 +389,7 @@ export default function Events() {
// 2. Category Filter check
if (selectedCategory !== 'All') {
if (selectedCategory === 'Center of Excellence' && !isCenter) return false;
if (selectedCategory !== 'Center of Excellence' && item.category !== selectedCategory) return false;
if (selectedCategory !== 'Center of Excellence' && item.category.toLowerCase() !== selectedCategory.toLowerCase()) return false;
}
// 3. Search Query check
@@ -298,7 +419,7 @@ export default function Events() {
<Building2 className="w-3.5 h-3.5" />
<span>RIT Official Directory</span>
</div>
<h1 className="text-3xl md:text-4xl font-bold text-[#1E293B] mb-2" style={{ fontFamily: 'Playfair Display, serif' }}>
<h1 className="text-3xl md:text-4xl font-extrabold text-[#1E293B] mb-2" style={{ fontFamily: 'Plus Jakarta Sans, sans-serif' }}>
Student Clubs &{' '}
<span style={{ background: 'linear-gradient(135deg, #F97316, #FB923C)', WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent', backgroundClip: 'text' }}>
Centers of Excellence
@@ -329,7 +450,7 @@ export default function Events() {
<Target className="w-3.5 h-3.5" />
<span>AI-Powered Matcher Quiz</span>
</div>
<h2 className="text-2xl md:text-3xl font-bold text-white mb-2" style={{ fontFamily: 'Playfair Display, serif' }}>
<h2 className="text-2xl md:text-3xl font-extrabold text-white mb-2" style={{ fontFamily: 'Plus Jakarta Sans, sans-serif' }}>
Find Your Ideal Club or Future Tech Center!
</h2>
<p className="text-slate-300 text-sm leading-relaxed" style={{ fontFamily: 'Inter, sans-serif' }}>
@@ -446,7 +567,7 @@ export default function Events() {
</button>
</div>
) : (
<StaggerContainer className="pb-8">
<StaggerContainer key={`${selectedType}-${selectedCategory}-${searchQuery}`} className="pb-8">
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 md:gap-7">
{filteredData.map((club) => {
const IconComponent = (club.icon && CLUB_ICON_MAP[club.icon]) || Atom;
@@ -594,7 +715,7 @@ export default function Events() {
</div>
{/* Question Header */}
<h3 className="text-xl font-bold text-[#1E293B] mb-5" style={{ fontFamily: 'Playfair Display, serif' }}>
<h3 className="text-xl font-extrabold text-[#1E293B] mb-5" style={{ fontFamily: 'Plus Jakarta Sans, sans-serif' }}>
{QUIZ_QUESTIONS_ALL[quizStep].title}
</h3>
@@ -628,7 +749,7 @@ export default function Events() {
<div className="w-14 h-14 rounded-2xl bg-orange-100 text-[#F97316] flex items-center justify-center mx-auto mb-3">
<CheckCircle2 className="w-8 h-8" />
</div>
<h3 className="text-2xl font-bold text-[#1E293B]" style={{ fontFamily: 'Playfair Display, serif' }}>
<h3 className="text-2xl font-extrabold text-[#1E293B]" style={{ fontFamily: 'Plus Jakarta Sans, sans-serif' }}>
Your Recommended Matches!
</h3>
<p className="text-xs text-slate-500 mt-1">Based on your selections, here are your top recommended RIT entities:</p>
@@ -768,7 +889,7 @@ export default function Events() {
</span>
)}
</div>
<h2 className="text-2xl font-bold text-[#1E293B]" style={{ fontFamily: 'Playfair Display, serif' }}>
<h2 className="text-2xl font-extrabold text-[#1E293B]" style={{ fontFamily: 'Plus Jakarta Sans, sans-serif' }}>
{selectedClub.name}
</h2>
</div>
@@ -865,12 +986,18 @@ export default function Events() {
</div>
{/* Social & Community Links */}
{Boolean(
{(() => {
const isRaiseIncubator = selectedClub.id === 'center_raise' || selectedClub.socialLinks?.website === '/raise';
const hasSpecificSocials = Boolean(
selectedClub.socialLinks?.instagram ||
selectedClub.socialLinks?.linkedin ||
selectedClub.socialLinks?.whatsapp ||
selectedClub.socialLinks?.youtube
) && (
);
if (!isRaiseIncubator && !hasSpecificSocials) return null;
return (
<div className="mb-6 bg-orange-50/60 border border-orange-200/80 rounded-2xl p-4">
<div className="flex items-center justify-between mb-3">
<div className="flex items-center gap-2 text-xs font-bold text-[#F97316] uppercase tracking-wider">
@@ -881,8 +1008,18 @@ export default function Events() {
</div>
<div className="grid grid-cols-2 gap-2.5">
{isRaiseIncubator && (
<Link
to="/raise"
onClick={() => setSelectedClub(null)}
className="flex items-center gap-2 p-2.5 rounded-xl bg-gradient-to-r from-[#EC4899] via-[#F43F5E] to-[#E11D48] text-white hover:from-pink-600 hover:to-rose-600 transition-all text-xs font-bold shadow-xs col-span-2 justify-center"
>
<Rocket className="w-4 h-4 text-white shrink-0 animate-pulse" />
<span>Launch RAISE Incubator Portal →</span>
</Link>
)}
{selectedClub.socialLinks?.instagram && (
{!isRaiseIncubator && selectedClub.socialLinks?.instagram && (
<a
href={selectedClub.socialLinks.instagram}
target="_blank"
@@ -894,7 +1031,7 @@ export default function Events() {
</a>
)}
{selectedClub.socialLinks?.linkedin && (
{!isRaiseIncubator && selectedClub.socialLinks?.linkedin && (
<a
href={selectedClub.socialLinks.linkedin}
target="_blank"
@@ -906,7 +1043,7 @@ export default function Events() {
</a>
)}
{selectedClub.socialLinks?.whatsapp && (
{!isRaiseIncubator && selectedClub.socialLinks?.whatsapp && (
<a
href={selectedClub.socialLinks.whatsapp}
target="_blank"
@@ -918,7 +1055,7 @@ export default function Events() {
</a>
)}
{selectedClub.socialLinks?.youtube && (
{!isRaiseIncubator && selectedClub.socialLinks?.youtube && (
<a
href={selectedClub.socialLinks.youtube}
target="_blank"
@@ -931,7 +1068,8 @@ export default function Events() {
)}
</div>
</div>
)}
);
})()}
{/* Close Button */}
<div>

View File

@@ -1,35 +1,109 @@
import { useState, useMemo } from 'react';
import { useState, useMemo, useEffect } from 'react';
import { motion } from 'framer-motion';
import { Search, Users, Filter, ArrowUpDown, BookOpen, ChevronRight, AlertTriangle } from 'lucide-react';
import { Search, Users, Filter, ArrowUpDown, BookOpen, ChevronRight, Sparkles, X } from 'lucide-react';
import FacultyCard from '@/components/FacultyCard/FacultyCard';
import { StaggerContainer, StaggerItem } from '@/components/AnimatedContainer/AnimatedContainer';
import { FACULTY_DATA, DEPARTMENTS } from '@/constants';
import { Link } from 'react-router-dom';
import { Link, useSearchParams } from 'react-router-dom';
import { getBackendUrl } from '@/lib/utils';
import { getStoredImsSession } from '@/services/imsService';
const DEPT_MAP: Record<string, { abrv: string; full: string }> = {
'Computer Science & Engineering': { abrv: 'CSE', full: 'Computer Science and Engineering' },
'Computer Science & Business Systems': { abrv: 'CSBS', full: 'Computer Science and Business Systems' },
'Artificial Intelligence & Machine Learning': { abrv: 'AIML', full: 'Artificial Intelligence and Machine Learning' },
'Electronics & Communication Engineering': { abrv: 'ECE', full: 'Electronics and Communication Engineering' },
'Computer Science & Engineering': { abrv: 'CSE', full: 'Computer Science & Engineering' },
'Computer Science & Business Systems': { abrv: 'CSBS', full: 'Computer Science & Business Systems' },
'Artificial Intelligence & Machine Learning': { abrv: 'AIML', full: 'Artificial Intelligence & Machine Learning' },
'Electronics & Communication Engineering': { abrv: 'ECE', full: 'Electronics & Communication Engineering' },
'Mechanical Engineering': { abrv: 'MECH', full: 'Mechanical Engineering' },
'Civil Engineering': { abrv: 'CIVIL', full: 'Civil Engineering' },
'Artificial Intelligence & Data Science': { abrv: 'AI&DS', full: 'Artificial Intelligence and Data Science' },
'Electrical & Electronics Engineering': { abrv: 'EEE', full: 'Electrical and Electronics Engineering' },
'Artificial Intelligence & Data Science': { abrv: 'AI & DS', full: 'Artificial Intelligence & Data Science' },
'Electrical & Electronics Engineering': { abrv: 'EEE', full: 'Electrical & Electronics Engineering' },
'Communication and Computer Engineering': { abrv: 'CCE', full: 'Communication and Computer Engineering' },
'Electronics Engineering VLSI (Design and Technology)': { abrv: 'EE VLSI (D&T)', full: 'Electronics Engineering (VLSI Design and Technology)' },
'Humanities & Sciences': { abrv: 'H&S', full: 'Humanities and Sciences' },
'Electronics Engineering VLSI (Design and Technology)': { abrv: 'EE VLSI (D&T)', full: 'Electronics Engineering VLSI (Design and Technology)' },
'Humanities & Sciences': { abrv: 'H&S', full: 'Humanities & Sciences' },
'M.Tech (Data Science)': { abrv: 'M.TECH-DS', full: 'M.Tech (Data Science)' },
'Mathematics': { abrv: 'MATHS', full: 'Mathematics' },
'M.E. (VLSI Design)': { abrv: 'MEVLSI', full: 'M.E. (VLSI Design)' },
};
function normalizeDepartmentName(input?: string | null): string | null {
if (!input) return null;
const cleaned = input.trim();
// Exact match
if (DEPARTMENTS.includes(cleaned)) return cleaned;
// Search by abbreviation or substring
const upper = cleaned.toUpperCase();
for (const [full, info] of Object.entries(DEPT_MAP)) {
if (info.abrv.toUpperCase() === upper || full.toUpperCase() === upper || full.toLowerCase().includes(cleaned.toLowerCase())) {
return full;
}
}
return null;
}
export default function Faculty() {
const [searchParams] = useSearchParams();
const [searchFaculty, setSearchFaculty] = useState('');
const [selectedDept, setSelectedDept] = useState('All Departments');
const [sortBy, setSortBy] = useState('Name A-Z');
// Initial department detection (from URL query string or logged-in IMS student session)
const initialDepartment = useMemo(() => {
const queryDept = searchParams.get('dept');
const matchedQuery = normalizeDepartmentName(queryDept);
if (matchedQuery) return matchedQuery;
const session = getStoredImsSession();
if (session?.student?.department) {
const matchedSession = normalizeDepartmentName(session.student.department);
if (matchedSession) return matchedSession;
}
return 'All Departments';
}, [searchParams]);
const [selectedDept, setSelectedDept] = useState<string>(initialDepartment);
// Update selectedDept if URL parameter changes
useEffect(() => {
setSelectedDept(initialDepartment);
}, [initialDepartment]);
const studentSession = useMemo(() => getStoredImsSession(), []);
const isStudentDeptAutoFiltered = selectedDept !== 'All Departments' && (
selectedDept === studentSession?.student?.department ||
searchParams.has('dept')
);
const [facultyList, setFacultyList] = useState<any[]>(() => {
try {
const saved = localStorage.getItem('RIT_LOCAL_FACULTY');
if (saved) {
const parsed = JSON.parse(saved);
if (Array.isArray(parsed) && parsed.length > 0) return parsed;
}
} catch {}
return FACULTY_DATA;
});
useEffect(() => {
fetch(getBackendUrl('/api/faculty'))
.then((res) => {
if (!res.ok) throw new Error();
return res.json();
})
.then((data) => {
if (Array.isArray(data) && data.length > 0) {
setFacultyList(data);
localStorage.setItem('RIT_LOCAL_FACULTY', JSON.stringify(data));
}
})
.catch(() => {});
}, []);
const filteredAndSortedFaculty = useMemo(() => {
const filtered = FACULTY_DATA.filter((f) => {
const filtered = facultyList.filter((f) => {
const searchLower = searchFaculty.trim().toLowerCase();
const matchSearch =
(f.name && f.name.toLowerCase().includes(searchLower)) ||
@@ -48,7 +122,7 @@ export default function Faculty() {
if (sortBy === 'Designation') return (a.designation || '').localeCompare(b.designation || '');
return 0;
});
}, [searchFaculty, selectedDept, sortBy]);
}, [facultyList, searchFaculty, selectedDept, sortBy]);
const groupedFaculty = useMemo(() => {
const groups: Record<string, typeof filteredAndSortedFaculty> = {};
@@ -62,8 +136,13 @@ export default function Faculty() {
}, [filteredAndSortedFaculty]);
const departmentOrder = useMemo(() => {
return DEPARTMENTS.filter(d => d !== 'All Departments');
}, []);
const presentDepts = Object.keys(groupedFaculty);
const sorted = DEPARTMENTS.filter(d => d !== 'All Departments');
presentDepts.forEach(d => {
if (!sorted.includes(d)) sorted.push(d);
});
return sorted;
}, [groupedFaculty]);
return (
<div className="min-h-screen relative overflow-hidden bg-[#F8FAFC]">
@@ -96,28 +175,37 @@ export default function Faculty() {
</div>
</div>
<div className="container-custom pt-8 pb-20 md:pb-28 space-y-8">
{/* Under Development Banner */}
<div className="container-custom pt-8 pb-20 md:pb-28 space-y-6">
{/* Active Student Department Filter Badge */}
{isStudentDeptAutoFiltered && (
<motion.div
initial={{ opacity: 0, y: -10 }}
animate={{ opacity: 1, y: 0 }}
className="bg-amber-50 border border-amber-200 rounded-2xl p-4 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 text-amber-900 shadow-2xs"
className="bg-orange-50 border border-orange-200 rounded-2xl p-4 flex items-center justify-between gap-3 text-orange-950 shadow-xs"
>
<div className="flex items-center gap-3">
<div className="w-9 h-9 rounded-xl bg-amber-500/10 border border-amber-500/20 flex items-center justify-center shrink-0">
<AlertTriangle className="w-5 h-5 text-amber-600" />
<div className="w-9 h-9 rounded-xl bg-orange-500/10 border border-orange-500/20 flex items-center justify-center shrink-0">
<Sparkles className="w-5 h-5 text-[#FF6B00]" />
</div>
<div>
<div className="text-xs font-bold uppercase tracking-wider text-amber-700" style={{ fontFamily: 'Inter, sans-serif' }}>Under Development</div>
<div className="text-xs font-medium text-amber-900" style={{ fontFamily: 'Inter, sans-serif' }}>
Currently displaying sample mock faculty profiles. Official RIT faculty directory integration is in progress.
<div className="text-xs font-bold uppercase tracking-wider text-orange-700">Student Department Auto-Filter</div>
<div className="text-xs font-medium text-orange-950">
Showing faculty for your department: <strong>{selectedDept}</strong>
</div>
</div>
</div>
<span className="px-3 py-1 rounded-full bg-amber-100 border border-amber-300 text-[11px] font-bold text-amber-800 shrink-0">
Mock Data Active
</span>
<button
onClick={() => setSelectedDept('All Departments')}
className="flex items-center gap-1.5 px-3 py-1.5 rounded-xl bg-white border border-orange-300 text-xs font-bold text-orange-800 hover:bg-orange-100 transition-colors cursor-pointer shrink-0"
>
<span>View All Departments</span>
<X className="w-3.5 h-3.5" />
</button>
</motion.div>
)}
{/* Faculty Hero Section */}
<div className="grid grid-cols-1 lg:grid-cols-12 gap-6 items-stretch">
<div className="lg:col-span-5 bg-white rounded-2xl p-8 border border-[#E9E5EE] shadow-[0_4px_20px_-4px_rgba(19,9,36,0.04)] flex flex-col justify-center relative overflow-hidden">
@@ -153,14 +241,23 @@ export default function Faculty() {
{ abrv: 'MEVLSI', full: 'M.E. (VLSI Design)', color: 'rose' },
].filter(d => FACULTY_DATA.filter(f => f.department === d.full).length > 0).map(d => {
const count = FACULTY_DATA.filter(f => f.department === d.full).length;
const isSelected = selectedDept === d.full;
return (
<div key={d.abrv} className={`p-4 rounded-2xl bg-${d.color}-50 border border-${d.color}-100 flex flex-col gap-1 transition-transform hover:scale-105 cursor-default`}>
<button
key={d.abrv}
onClick={() => setSelectedDept(d.full)}
className={`p-4 rounded-2xl border flex flex-col gap-1 transition-all text-left cursor-pointer ${
isSelected
? 'bg-[#FF6B00] text-white border-[#FF6B00] shadow-md'
: `bg-${d.color}-50 border-${d.color}-100 hover:scale-102`
}`}
>
<div className="flex justify-between items-center">
<span className={`text-xs font-bold text-${d.color}-700`} style={{ fontFamily: 'Plus Jakarta Sans, sans-serif' }}>{d.abrv}</span>
<BookOpen className={`w-3.5 h-3.5 text-${d.color}-400`} />
</div>
<span className="text-2xl font-bold text-[#1E293B]" style={{ fontFamily: 'Plus Jakarta Sans, sans-serif' }}>{count}</span>
<span className={`text-xs font-bold ${isSelected ? 'text-white' : `text-${d.color}-700`}`} style={{ fontFamily: 'Plus Jakarta Sans, sans-serif' }}>{d.abrv}</span>
<BookOpen className={`w-3.5 h-3.5 ${isSelected ? 'text-white/80' : `text-${d.color}-400`}`} />
</div>
<span className={`text-2xl font-bold ${isSelected ? 'text-white' : 'text-[#1E293B]'}`} style={{ fontFamily: 'Plus Jakarta Sans, sans-serif' }}>{count}</span>
</button>
);
})}
</div>
@@ -256,7 +353,7 @@ export default function Faculty() {
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
className="px-6 py-3 bg-white/80 backdrop-blur-md border border-[#E8ECF4] shadow-[0_8px_30px_rgb(0,0,0,0.08)] rounded-full flex items-center gap-2"
className="px-6 py-3 bg-white/80 backdrop-blur-md border border-[#E8ECF4] shadow-[0_8px_30px_rgb(0,0,0,0.08)] rounded-full flex items-center gap-2 pointer-events-auto"
>
<span className="text-lg">👥</span>
<span className="text-sm font-semibold text-[#1E293B]" style={{ fontFamily: 'Inter, sans-serif' }}>

View File

@@ -1,10 +1,12 @@
import { useState, useRef, useEffect } from 'react';
import { useSearchParams } from 'react-router-dom';
import { motion } from 'framer-motion';
import { Search, Download, Filter, BookOpen, FileText, ScrollText, BookMarked, ChevronRight, ArrowLeft, ExternalLink, Code, Globe, GitBranch, Cloud, Palette, Shield, DollarSign, BarChart3, Users, Megaphone, TrendingUp, UserCheck, ClipboardList, ShoppingCart, Cpu, Activity, LayoutGrid, Layers, Zap, Settings, Gauge, Radio, Wifi, Bot, Sun, Wrench, Binary, BatteryCharging, CircuitBoard, ShieldCheck, BrainCircuit, FlaskConical, Lock, Terminal, Dna, Microscope, Sparkles, Smartphone, Monitor, Server, CheckCircle2, Database, Briefcase, AlertTriangle, RefreshCw } from 'lucide-react';
import { Search, Download, Filter, BookOpen, FileText, ScrollText, BookMarked, ChevronRight, ArrowLeft, ExternalLink, Code, Globe, GitBranch, Cloud, Palette, Shield, DollarSign, BarChart3, Users, Megaphone, TrendingUp, UserCheck, ClipboardList, ShoppingCart, Cpu, Activity, LayoutGrid, Layers, Zap, Settings, Gauge, Radio, Wifi, Bot, Sun, Wrench, Binary, BatteryCharging, CircuitBoard, ShieldCheck, BrainCircuit, FlaskConical, Lock, Terminal, Dna, Microscope, Sparkles, Smartphone, Monitor, Server, CheckCircle2, Database, Briefcase, AlertTriangle, RefreshCw, Ticket, Award, QrCode } from 'lucide-react';
import SectionTitle from '@/components/SectionTitle/SectionTitle';
const MOODLE_URL = 'http://182.74.17.142/moodle/login/index.php';
const GATE_PASS_URL = 'http://182.74.17.142/gatepass/login';
const PROFICIENCY_URL = 'http://182.74.17.142/proficiency/login';
import { getBackendUrl } from '@/lib/utils';
import { StaggerContainer, StaggerItem } from '@/components/AnimatedContainer/AnimatedContainer';
import { TOOLKIT_ITEMS, DEPARTMENTS } from '@/constants';
@@ -1329,40 +1331,55 @@ export default function Notes() {
const [selectedCategory, setSelectedCategory] = useState<number | null>(null);
const [selectedLanguage, setSelectedLanguage] = useState<number | null>(null);
const [selectedTool, setSelectedTool] = useState<{ name: string; desc: string; url: string; category: string; bg: string; color: string } | null>(null);
const [activePortalTab, setActivePortalTab] = useState<'moodle' | 'gatepass' | 'proficiency'>('moodle');
const [notes, setNotes] = useState<any[]>([]);
useEffect(() => {
const fetchNotes = async () => {
let localFallback = NOTES_DATA;
try {
const saved = localStorage.getItem('RIT_LOCAL_NOTES');
if (saved) {
const parsed = JSON.parse(saved);
if (Array.isArray(parsed) && parsed.length > 0) localFallback = parsed;
}
} catch {}
try {
const response = await fetch(getBackendUrl('/api/notes'));
if (response.ok) {
const data = await response.json();
if (Array.isArray(data) && data.length > 0) {
const mappedData = data.map((n: any) => ({
id: String(n.id),
title: n.title,
subject: n.subject,
department: n.department,
semester: n.semester,
type: n.fileType,
type: n.fileType || 'notes',
downloads: n.downloadsCount || 0,
fileSize: n.fileSize,
fileSize: n.fileSize || '2.4 MB',
uploadedAt: n.uploadedAt ? n.uploadedAt.split('T')[0] : '',
downloadUrl: n.downloadUrl
downloadUrl: n.downloadUrl || '#'
}));
setNotes(mappedData);
} else {
setNotes(NOTES_DATA);
return;
}
} catch (err) {
console.error('Error fetching notes:', err);
setNotes(NOTES_DATA);
}
setNotes(localFallback);
} catch {
setNotes(localFallback);
}
};
fetchNotes();
}, []);
useEffect(() => {
const portalParam = searchParams.get('portal');
if (portalParam === 'gatepass' || portalParam === 'proficiency' || portalParam === 'moodle') {
setActivePortalTab(portalParam as any);
}
if (searchParams.get('section') === 'toolkit') {
setTimeout(() => {
toolkitRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' });
@@ -1407,6 +1424,42 @@ export default function Notes() {
return matchSearch && matchSem && matchDept && matchType && matchSubject;
});
const portalParam = searchParams.get('portal');
let headerBreadcrumb = 'Notes & PYQs';
let headerTitle = (
<>
Notes &{' '}
<span style={{ background: 'linear-gradient(135deg, #F97316, #FB923C)', WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent', backgroundClip: 'text' }}>
PYQs
</span>
</>
);
let headerSubtitle = 'Access semester-wise notes, previous year question papers, and study materials.';
if (portalParam === 'gatepass') {
headerBreadcrumb = 'Student Gate Pass';
headerTitle = (
<>
Student{' '}
<span style={{ background: 'linear-gradient(135deg, #F97316, #FB923C)', WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent', backgroundClip: 'text' }}>
Gate Pass
</span>
</>
);
headerSubtitle = 'Official digital campus out-pass system for day scholars and hostellers.';
} else if (portalParam === 'proficiency') {
headerBreadcrumb = 'Student Proficiency';
headerTitle = (
<>
Student{' '}
<span style={{ background: 'linear-gradient(135deg, #F97316, #FB923C)', WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent', backgroundClip: 'text' }}>
Proficiency
</span>
</>
);
headerSubtitle = 'Official RIT skill evaluation platform for tracking domain competencies and certifications.';
}
return (
<div className="min-h-screen" style={{ backgroundColor: '#FAFAFA' }}>
{/* Header */}
@@ -1417,16 +1470,13 @@ export default function Notes() {
<div className="flex items-center gap-2 text-xs text-[#94A3B8] mb-3" style={{ fontFamily: 'Inter, sans-serif' }}>
<span>Home</span>
<ChevronRight className="w-3 h-3" />
<span className="text-[#F97316]">Notes & PYQs</span>
<span className="text-[#F97316]">{headerBreadcrumb}</span>
</div>
<h1 className="text-3xl md:text-4xl font-bold text-[#1E293B] mb-2" style={{ fontFamily: 'Playfair Display, serif' }}>
Notes &{' '}
<span style={{ background: 'linear-gradient(135deg, #F97316, #FB923C)', WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent', backgroundClip: 'text' }}>
PYQs
</span>
<h1 className="text-3xl md:text-4xl font-extrabold text-[#1E293B] mb-2" style={{ fontFamily: 'Plus Jakarta Sans, sans-serif' }}>
{headerTitle}
</h1>
<p className="text-[#475569]" style={{ fontFamily: 'Inter, sans-serif' }}>
Access semester-wise notes, previous year question papers, and study materials.
{headerSubtitle}
</p>
</motion.div>
</div>
@@ -1486,7 +1536,7 @@ export default function Notes() {
: 'Back to Toolkit'}
</button>
<h2 className="text-3xl font-bold text-[#1E293B] mb-2" style={{ fontFamily: 'Playfair Display, serif' }}>
<h2 className="text-2xl md:text-3xl font-extrabold text-[#1E293B] mb-2" style={{ fontFamily: 'Plus Jakarta Sans, sans-serif' }}>
{selectedTool !== null ? (
<>
{selectedTool.name}{' '}
@@ -1548,7 +1598,7 @@ export default function Notes() {
</div>
<div>
<div className="flex items-center gap-3">
<h3 className="text-2xl md:text-3xl font-bold text-[#1E293B]" style={{ fontFamily: 'Playfair Display, serif' }}>
<h3 className="text-2xl md:text-3xl font-extrabold text-[#1E293B]" style={{ fontFamily: 'Plus Jakarta Sans, sans-serif' }}>
{selectedTool.name}
</h3>
<span
@@ -1675,7 +1725,7 @@ export default function Notes() {
</div>
<div>
<div className="flex items-center gap-3">
<h3 className="text-2xl md:text-3xl font-bold text-[#1E293B]" style={{ fontFamily: 'Playfair Display, serif' }}>
<h3 className="text-2xl md:text-3xl font-extrabold text-[#1E293B]" style={{ fontFamily: 'Plus Jakarta Sans, sans-serif' }}>
{PROGRAMMING_LANGUAGES_GUIDES[selectedLanguage].name}
</h3>
<span
@@ -1919,7 +1969,10 @@ export default function Notes() {
) : (
<div>
<div className="mb-12">
{/* Moodle Academic Portal Hero Hub */}
{/* 1. MOODLE LMS CARD */}
{activePortalTab === 'moodle' && (
<motion.div
initial={{ opacity: 0, y: 16 }}
animate={{ opacity: 1, y: 0 }}
@@ -1927,19 +1980,16 @@ export default function Notes() {
className="bg-white rounded-3xl border border-[#E5E7EB] p-8 md:p-10 shadow-sm relative overflow-hidden mb-8"
style={{ boxShadow: '0 4px 25px -5px rgba(0,0,0,0.05)' }}
>
{/* Subtle Decorative Background Glow */}
<div className="absolute -right-20 -top-20 w-80 h-80 bg-orange-500/5 rounded-full blur-3xl pointer-events-none" />
<div className="absolute -left-20 -bottom-20 w-80 h-80 bg-amber-500/5 rounded-full blur-3xl pointer-events-none" />
<div className="relative z-10 max-w-3xl mx-auto text-center">
{/* Header Badge */}
<div className="inline-flex items-center gap-2 px-3.5 py-1.5 rounded-full bg-orange-50 border border-orange-200 text-xs font-bold text-[#F97316] mb-6">
<BookOpen className="w-4 h-4 text-[#F97316]" />
<span>Official RIT Learning Management System</span>
</div>
{/* Main Heading */}
<h2 className="text-3xl sm:text-4xl font-extrabold text-[#1E293B] mb-4 leading-tight" style={{ fontFamily: 'Playfair Display, serif' }}>
<h2 className="text-2xl md:text-3xl font-extrabold text-[#1E293B] mb-4 leading-tight" style={{ fontFamily: 'Plus Jakarta Sans, sans-serif' }}>
Access Academic Notes & Study Materials on{' '}
<span style={{ background: 'linear-gradient(135deg, #F97316, #FB923C)', WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent', backgroundClip: 'text' }}>
Moodle
@@ -1950,7 +2000,6 @@ export default function Notes() {
All official semester notes, previous year question papers (PYQs), syllabus data, and lab manuals are hosted directly on the official Rajalakshmi Institute of Technology Moodle server.
</p>
{/* Primary Launch Action Buttons */}
<div className="flex flex-col sm:flex-row items-center justify-center gap-4 mb-10">
<a
href={MOODLE_URL}
@@ -1979,7 +2028,6 @@ export default function Notes() {
</button>
</div>
{/* Feature Highlights Grid */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-4 text-left border-t border-[#F1F5F9] pt-8">
<div className="p-4 rounded-2xl bg-[#F8FAFC] border border-[#E5E7EB]/70 flex flex-col gap-2">
<div className="w-8 h-8 rounded-xl bg-emerald-500/10 border border-emerald-500/20 flex items-center justify-center text-emerald-600">
@@ -2017,13 +2065,205 @@ export default function Notes() {
</div>
</div>
</div>
</div>
</motion.div>
)}
{/* Technical Security Note */}
<div className="mt-6 text-[11px] text-[#94A3B8] leading-relaxed" style={{ fontFamily: 'Inter, sans-serif' }}>
ℹ️ <span className="font-semibold text-[#64748B]">Security Note:</span> To protect student session privacy and prevent clickjacking attacks, RIT&apos;s Moodle server enforces opening the portal directly in a secure browser tab rather than inside third-party frames (<code className="bg-slate-100 px-1 py-0.5 rounded text-[10px]">X-Frame-Options: SAMEORIGIN</code>).
{/* 2. STUDENT GATE PASS CARD */}
{activePortalTab === 'gatepass' && (
<motion.div
initial={{ opacity: 0, y: 16 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.4 }}
className="bg-white rounded-3xl border border-[#E5E7EB] p-8 md:p-10 shadow-sm relative overflow-hidden mb-8"
style={{ boxShadow: '0 4px 25px -5px rgba(0,0,0,0.05)' }}
>
<div className="absolute -right-20 -top-20 w-80 h-80 bg-orange-500/5 rounded-full blur-3xl pointer-events-none" />
<div className="absolute -left-20 -bottom-20 w-80 h-80 bg-amber-500/5 rounded-full blur-3xl pointer-events-none" />
<div className="relative z-10 max-w-3xl mx-auto text-center">
<div className="inline-flex items-center gap-2 px-3.5 py-1.5 rounded-full bg-orange-50 border border-orange-200 text-xs font-bold text-[#F97316] mb-6">
<Ticket className="w-4 h-4 text-[#F97316]" />
<span>Official RIT Campus Gate Pass Portal</span>
</div>
<h2 className="text-2xl md:text-3xl font-extrabold text-[#1E293B] mb-4 leading-tight" style={{ fontFamily: 'Plus Jakarta Sans, sans-serif' }}>
Request & Manage Out-Passes on{' '}
<span style={{ background: 'linear-gradient(135deg, #F97316, #FB923C)', WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent', backgroundClip: 'text' }}>
Student Gate Pass
</span>
</h2>
<p className="text-base text-[#64748B] mb-8 leading-relaxed max-w-2xl mx-auto" style={{ fontFamily: 'Inter, sans-serif' }}>
Official digital campus out-pass system for day scholars and hostellers. Submit leave requests, track warden approvals, and present digital QR passes to campus security.
</p>
<div className="flex flex-col sm:flex-row items-center justify-center gap-4 mb-10">
<button
onClick={() => {
alert('Student Gate Pass Portal dummy link triggered! You can provide the live URL anytime to connect it.');
}}
className="w-full sm:w-auto inline-flex items-center justify-center gap-3 px-8 py-4 rounded-2xl text-base font-bold text-white shadow-lg hover:shadow-xl hover:-translate-y-0.5 transition-all cursor-pointer"
style={{
fontFamily: 'Poppins, sans-serif',
background: 'linear-gradient(135deg, #F97316, #FB923C)',
}}
>
<ExternalLink className="w-5 h-5" />
Launch Student Gate Pass Portal
</button>
<button
onClick={() => {
navigator.clipboard.writeText(GATE_PASS_URL);
alert('Student Gate Pass URL copied to clipboard!');
}}
className="w-full sm:w-auto inline-flex items-center justify-center gap-2 px-6 py-4 rounded-2xl border border-[#E5E7EB] hover:border-[#F97316] bg-[#F8FAFC] hover:bg-white text-sm font-semibold text-[#475569] hover:text-[#F97316] transition-all cursor-pointer"
style={{ fontFamily: 'Poppins, sans-serif' }}
>
<Globe className="w-4 h-4 text-[#64748B]" />
Copy Gate Pass Direct URL
</button>
</div>
<div className="grid grid-cols-1 md:grid-cols-3 gap-4 text-left border-t border-[#F1F5F9] pt-8">
<div className="p-4 rounded-2xl bg-emerald-50/50 border border-emerald-100 flex flex-col gap-2">
<div className="w-8 h-8 rounded-xl bg-emerald-500/10 border border-emerald-500/20 flex items-center justify-center text-emerald-600">
<QrCode className="w-4 h-4" />
</div>
<div className="text-xs font-bold text-[#1E293B]" style={{ fontFamily: 'Poppins, sans-serif' }}>
Digital QR Clearance
</div>
<div className="text-[11px] text-[#64748B]" style={{ fontFamily: 'Inter, sans-serif' }}>
Generate real-time encrypted QR code for security verification at campus gates.
</div>
</div>
<div className="p-4 rounded-2xl bg-emerald-50/50 border border-emerald-100 flex flex-col gap-2">
<div className="w-8 h-8 rounded-xl bg-teal-500/10 border border-teal-500/20 flex items-center justify-center text-teal-600">
<CheckCircle2 className="w-4 h-4" />
</div>
<div className="text-xs font-bold text-[#1E293B]" style={{ fontFamily: 'Poppins, sans-serif' }}>
Warden & Parent Approval
</div>
<div className="text-[11px] text-[#64748B]" style={{ fontFamily: 'Inter, sans-serif' }}>
Automated SMS and email notifications to wardens, mentors, and registered guardians.
</div>
</div>
<div className="p-4 rounded-2xl bg-emerald-50/50 border border-emerald-100 flex flex-col gap-2">
<div className="w-8 h-8 rounded-xl bg-green-500/10 border border-green-500/20 flex items-center justify-center text-green-600">
<ShieldCheck className="w-4 h-4" />
</div>
<div className="text-xs font-bold text-[#1E293B]" style={{ fontFamily: 'Poppins, sans-serif' }}>
Verified RIT Student ID
</div>
<div className="text-[11px] text-[#64748B]" style={{ fontFamily: 'Inter, sans-serif' }}>
Authenticates securely with official college Roll Number & registered portal password.
</div>
</div>
</div>
</div>
</motion.div>
)}
{/* 3. STUDENT PROFICIENCY CARD */}
{activePortalTab === 'proficiency' && (
<motion.div
initial={{ opacity: 0, y: 16 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.4 }}
className="bg-white rounded-3xl border border-[#E5E7EB] p-8 md:p-10 shadow-sm relative overflow-hidden mb-8"
style={{ boxShadow: '0 4px 25px -5px rgba(0,0,0,0.05)' }}
>
<div className="absolute -right-20 -top-20 w-80 h-80 bg-orange-500/5 rounded-full blur-3xl pointer-events-none" />
<div className="absolute -left-20 -bottom-20 w-80 h-80 bg-amber-500/5 rounded-full blur-3xl pointer-events-none" />
<div className="relative z-10 max-w-3xl mx-auto text-center">
<div className="inline-flex items-center gap-2 px-3.5 py-1.5 rounded-full bg-orange-50 border border-orange-200 text-xs font-bold text-[#F97316] mb-6">
<Award className="w-4 h-4 text-[#F97316]" />
<span>Official RIT Skill Evaluation & Readiness System</span>
</div>
<h2 className="text-2xl md:text-3xl font-extrabold text-[#1E293B] mb-4 leading-tight" style={{ fontFamily: 'Plus Jakarta Sans, sans-serif' }}>
Track Skill Milestones & Credentials on{' '}
<span style={{ background: 'linear-gradient(135deg, #F97316, #FB923C)', WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent', backgroundClip: 'text' }}>
Student Proficiency
</span>
</h2>
<p className="text-base text-[#64748B] mb-8 leading-relaxed max-w-2xl mx-auto" style={{ fontFamily: 'Inter, sans-serif' }}>
Official RIT skill evaluation platform for tracking domain competencies, technical certifications, placement readiness scores, and verified proficiency badges.
</p>
<div className="flex flex-col sm:flex-row items-center justify-center gap-4 mb-10">
<button
onClick={() => {
alert('Student Proficiency Portal dummy link triggered! You can provide the live URL anytime to connect it.');
}}
className="w-full sm:w-auto inline-flex items-center justify-center gap-3 px-8 py-4 rounded-2xl text-base font-bold text-white shadow-lg hover:shadow-xl hover:-translate-y-0.5 transition-all cursor-pointer"
style={{
fontFamily: 'Poppins, sans-serif',
background: 'linear-gradient(135deg, #F97316, #FB923C)',
}}
>
<ExternalLink className="w-5 h-5" />
Launch Student Proficiency Portal
</button>
<button
onClick={() => {
navigator.clipboard.writeText(PROFICIENCY_URL);
alert('Student Proficiency URL copied to clipboard!');
}}
className="w-full sm:w-auto inline-flex items-center justify-center gap-2 px-6 py-4 rounded-2xl border border-[#E5E7EB] hover:border-[#F97316] bg-[#F8FAFC] hover:bg-white text-sm font-semibold text-[#475569] hover:text-[#F97316] transition-all cursor-pointer"
style={{ fontFamily: 'Poppins, sans-serif' }}
>
<Globe className="w-4 h-4 text-[#64748B]" />
Copy Proficiency Direct URL
</button>
</div>
<div className="grid grid-cols-1 md:grid-cols-3 gap-4 text-left border-t border-[#F1F5F9] pt-8">
<div className="p-4 rounded-2xl bg-purple-50/50 border border-purple-100 flex flex-col gap-2">
<div className="w-8 h-8 rounded-xl bg-purple-500/10 border border-purple-500/20 flex items-center justify-center text-purple-600">
<TrendingUp className="w-4 h-4" />
</div>
<div className="text-xs font-bold text-[#1E293B]" style={{ fontFamily: 'Poppins, sans-serif' }}>
Skill Radar & Domain Scores
</div>
<div className="text-[11px] text-[#64748B]" style={{ fontFamily: 'Inter, sans-serif' }}>
Visualize competency scores across programming, core engineering, and analytical reasoning.
</div>
</div>
<div className="p-4 rounded-2xl bg-purple-50/50 border border-purple-100 flex flex-col gap-2">
<div className="w-8 h-8 rounded-xl bg-indigo-500/10 border border-indigo-500/20 flex items-center justify-center text-indigo-600">
<Sparkles className="w-4 h-4" />
</div>
<div className="text-xs font-bold text-[#1E293B]" style={{ fontFamily: 'Poppins, sans-serif' }}>
Placement Readiness
</div>
<div className="text-[11px] text-[#64748B]" style={{ fontFamily: 'Inter, sans-serif' }}>
Live feedback on mock interview performances, coding assessments, and company cutoffs.
</div>
</div>
<div className="p-4 rounded-2xl bg-purple-50/50 border border-purple-100 flex flex-col gap-2">
<div className="w-8 h-8 rounded-xl bg-violet-500/10 border border-violet-500/20 flex items-center justify-center text-violet-600">
<Award className="w-4 h-4" />
</div>
<div className="text-xs font-bold text-[#1E293B]" style={{ fontFamily: 'Poppins, sans-serif' }}>
Verified Credentials
</div>
<div className="text-[11px] text-[#64748B]" style={{ fontFamily: 'Inter, sans-serif' }}>
Upload, verify, and generate shareable badges for NPTEL, Coursera & RIT certification credits.
</div>
</div>
</div>
</div>
</motion.div>
)}
</div>
</div>
)}

View File

@@ -0,0 +1,605 @@
import { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
GraduationCap, Clock, MapPin, Users,
Calendar, Building, ShieldCheck,
Sparkles, KeyRound, ArrowRight, LogOut,
AlertCircle, User, HelpCircle, Compass, ChevronRight, ExternalLink
} from 'lucide-react';
import { Link } from 'react-router-dom';
import { useAuth } from '@/context/AuthContext';
import {
fetchStudentDashboard,
loginWithIms,
fetchMockImsUsers,
getStoredImsSession,
clearImsSession,
type StudentDashboardData,
type MockUserCredential
} from '@/services/imsService';
export default function StudentDashboard() {
const { user, openAuthModal, logout } = useAuth();
const [data, setData] = useState<StudentDashboardData | null>(null);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [activeTab, setActiveTab] = useState<'timetable' | 'location'>('timetable');
// IMS Authentication Session State
const [imsSession, setImsSession] = useState<{ token: string; student: any } | null>(getStoredImsSession());
const [regNumberInput, setRegNumberInput] = useState('');
const [passwordInput, setPasswordInput] = useState('');
const [isLoggingIn, setIsLoggingIn] = useState(false);
const [loginError, setLoginError] = useState<string | null>(null);
const [mockUsers, setMockUsers] = useState<MockUserCredential[]>([]);
const [showDemoBox, setShowDemoBox] = useState(false);
const effectiveRegNumber = user?.regNumber || imsSession?.student?.regNumber;
// Load available mock accounts for demo helper
useEffect(() => {
fetchMockImsUsers().then((users) => {
setMockUsers(users);
if (users.length > 0 && !regNumberInput) {
setRegNumberInput(users[0].regNumber);
setPasswordInput(users[0].defaultPassword);
}
});
}, []);
const loadDashboard = async () => {
const regToUse = effectiveRegNumber || imsSession?.student?.regNumber;
if (!regToUse) return;
setIsLoading(true);
setError(null);
try {
const res = await fetchStudentDashboard(regToUse, user?.email);
setData(res);
} catch (err: any) {
console.error('Error loading student dashboard:', err);
setError(err.message || 'Failed to fetch timetable and classroom location.');
} finally {
setIsLoading(false);
}
};
useEffect(() => {
if (effectiveRegNumber || imsSession?.student?.regNumber) {
loadDashboard();
}
}, [effectiveRegNumber, imsSession, user]);
const handleImsLogin = async (e: React.FormEvent) => {
e.preventDefault();
if (!regNumberInput.trim() || !passwordInput.trim()) return;
setIsLoggingIn(true);
setLoginError(null);
try {
const res = await loginWithIms(regNumberInput.trim(), passwordInput.trim());
if (res.success && res.token && res.student) {
setImsSession({ token: res.token, student: res.student });
} else {
setLoginError(res.message || 'Invalid credentials or Register Number not found.');
}
} catch (err: any) {
setLoginError(err.message || 'Invalid credentials or Register Number not found.');
} finally {
setIsLoggingIn(false);
}
};
const handleQuickFillMock = (mock: MockUserCredential) => {
setRegNumberInput(mock.regNumber);
setPasswordInput(mock.defaultPassword);
};
const handleLogoutIms = () => {
clearImsSession();
setImsSession(null);
logout();
setData(null);
};
// ─────────────────────────────────────────────────────────────
// VIEW 1: UNAUTHENTICATED INVITATION SCREEN
// ─────────────────────────────────────────────────────────────
if (!effectiveRegNumber && !imsSession) {
return (
<div className="min-h-screen" style={{ backgroundColor: '#FAFAFA' }}>
{/* Header */}
<div className="bg-white border-b border-[#E5E7EB] py-10">
<div className="container-custom">
<motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.5 }}>
<div className="flex items-center gap-2 text-xs text-[#94A3B8] mb-3" style={{ fontFamily: 'Inter, sans-serif' }}>
<Link to="/" className="hover:text-[#F97316]">Home</Link>
<ChevronRight className="w-3 h-3" />
<span className="text-[#F97316]">Time Table</span>
</div>
<h1 className="text-3xl md:text-4xl font-extrabold text-[#1E293B] mb-2" style={{ fontFamily: 'Plus Jakarta Sans, sans-serif' }}>
IMS Student{' '}
<span style={{ background: 'linear-gradient(135deg, #F97316, #FB923C)', WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent', backgroundClip: 'text' }}>
Portal
</span>
</h1>
<p className="text-[#475569]" style={{ fontFamily: 'Inter, sans-serif' }}>
Enter your official college Register Number and Password to access your timetable and assigned classroom venue.
</p>
</motion.div>
</div>
</div>
{/* Login Form Container */}
<div className="container-custom py-12 flex items-center justify-center pb-28">
<div className="w-full max-w-md space-y-6">
<div className="text-center space-y-2">
<div className="w-16 h-16 rounded-2xl bg-gradient-to-br from-[#FF6B00] to-[#F97316] flex items-center justify-center shadow-xl shadow-orange-500/30 mx-auto">
<GraduationCap className="w-8 h-8 text-white" />
</div>
<h2 className="text-xl font-extrabold text-[#1E293B]" style={{ fontFamily: 'Plus Jakarta Sans, sans-serif' }}>
Sign In to Student Portal
</h2>
<p className="text-xs text-[#64748B] max-w-sm mx-auto" style={{ fontFamily: 'Inter, sans-serif' }}>
Enter your official college credentials below
</p>
</div>
{/* Login Form Card */}
<motion.div
initial={{ opacity: 0, y: 15 }}
animate={{ opacity: 1, y: 0 }}
className="bg-white border border-[#E5E7EB] rounded-3xl p-6 sm:p-8 shadow-xl space-y-5"
>
{loginError && (
<div className="p-3.5 rounded-2xl bg-rose-50 border border-rose-200 flex items-start gap-2.5 text-xs text-rose-700 font-medium">
<AlertCircle className="w-4 h-4 text-rose-500 shrink-0 mt-0.5" />
<span>{loginError}</span>
</div>
)}
<form onSubmit={handleImsLogin} className="space-y-4">
<div>
<label className="block text-xs font-bold text-[#1E293B] mb-1.5 flex items-center gap-1.5" style={{ fontFamily: 'Plus Jakarta Sans, sans-serif' }}>
<User className="w-3.5 h-3.5 text-[#F97316]" />
Register Number / Roll No
</label>
<input
type="text"
value={regNumberInput}
onChange={(e) => setRegNumberInput(e.target.value)}
placeholder="e.g. 2114251001"
className="w-full bg-[#F8FAFC] border border-[#E5E7EB] rounded-xl px-4 py-3 text-sm text-[#1E293B] placeholder-[#94A3B8] outline-none focus:border-[#F97316] focus:bg-white transition-colors font-mono"
required
/>
</div>
<div>
<label className="block text-xs font-bold text-[#1E293B] mb-1.5 flex items-center gap-1.5" style={{ fontFamily: 'Plus Jakarta Sans, sans-serif' }}>
<KeyRound className="w-3.5 h-3.5 text-[#F97316]" />
IMS Password
</label>
<input
type="password"
value={passwordInput}
onChange={(e) => setPasswordInput(e.target.value)}
placeholder="••••••••"
className="w-full bg-[#F8FAFC] border border-[#E5E7EB] rounded-xl px-4 py-3 text-sm text-[#1E293B] placeholder-[#94A3B8] outline-none focus:border-[#F97316] focus:bg-white transition-colors font-mono"
required
/>
</div>
<button
type="submit"
disabled={isLoggingIn}
className="w-full py-3.5 px-4 rounded-xl text-white font-bold text-sm bg-gradient-to-r from-[#FF6B00] to-[#F97316] hover:opacity-95 shadow-lg shadow-orange-500/20 transition-all flex items-center justify-center gap-2 cursor-pointer"
style={{ fontFamily: 'Plus Jakarta Sans, sans-serif' }}
>
{isLoggingIn ? (
<div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
) : (
<>
<span>Sign In to Student Portal</span>
<ArrowRight className="w-4 h-4" />
</>
)}
</button>
</form>
<div className="text-center pt-2">
<button
type="button"
onClick={openAuthModal}
className="text-xs text-slate-500 hover:text-[#F97316] font-semibold underline cursor-pointer"
>
Or Sign In via Main Portal Account
</button>
</div>
{/* Expandable Demo Helper */}
<div className="pt-3 border-t border-[#E5E7EB]">
<button
type="button"
onClick={() => setShowDemoBox(!showDemoBox)}
className="w-full text-center text-xs font-bold text-[#F97316] hover:underline flex items-center justify-center gap-1 cursor-pointer"
style={{ fontFamily: 'Plus Jakarta Sans, sans-serif' }}
>
<Sparkles className="w-3.5 h-3.5" />
{showDemoBox ? 'Hide Demo Accounts' : 'Testing / Demo Accounts'}
</button>
<AnimatePresence>
{showDemoBox && (
<motion.div
initial={{ height: 0, opacity: 0 }}
animate={{ height: 'auto', opacity: 1 }}
exit={{ height: 0, opacity: 0 }}
className="overflow-hidden mt-3 space-y-2"
>
<p className="text-[11px] text-[#64748B] text-center" style={{ fontFamily: 'Inter, sans-serif' }}>
Click any sample student below to auto-fill the login form:
</p>
<div className="space-y-1.5">
{mockUsers.map((mock) => (
<button
key={mock.regNumber}
type="button"
onClick={() => handleQuickFillMock(mock)}
className="w-full flex items-center justify-between p-2.5 rounded-xl bg-[#F8FAFC] hover:bg-white border border-[#E5E7EB] text-left text-xs transition-colors cursor-pointer"
>
<div>
<p className="font-bold text-[#1E293B]">{mock.studentName}</p>
<p className="text-[10px] text-[#64748B]">Reg: {mock.regNumber} ({mock.department})</p>
</div>
<span className="text-[10px] text-[#F97316] font-mono font-bold">Fill Form</span>
</button>
))}
</div>
</motion.div>
)}
</AnimatePresence>
</div>
</motion.div>
</div>
</div>
</div>
);
}
// ─────────────────────────────────────────────────────────────
// VIEW 2: LOGGED-IN STUDENT DASHBOARD
// ─────────────────────────────────────────────────────────────
const classInchargeMember = data?.facultyList.find((f) => f.isClassIncharge);
return (
<div className="min-h-screen" style={{ backgroundColor: '#FAFAFA' }}>
{/* Header */}
<div className="bg-white border-b border-[#E5E7EB] py-8">
<div className="container-custom">
<div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
<div className="flex items-start gap-4">
<div className="w-14 h-14 rounded-2xl bg-gradient-to-br from-[#FF6B00] to-[#F97316] flex items-center justify-center shadow-lg shadow-orange-500/30 shrink-0">
<GraduationCap className="w-7 h-7 text-white" />
</div>
<div>
<div className="flex flex-wrap items-center gap-2 mb-1">
<h1 className="text-xl sm:text-2xl font-extrabold text-[#1E293B] tracking-tight" style={{ fontFamily: 'Plus Jakarta Sans, sans-serif' }}>
{data?.student.name || user?.name || imsSession?.student.name}
</h1>
<span className="px-2.5 py-0.5 rounded-full text-[10px] font-bold tracking-wider bg-emerald-50 text-emerald-600 border border-emerald-200 uppercase">
Authenticated Student
</span>
</div>
<div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-[#64748B] font-medium" style={{ fontFamily: 'Inter, sans-serif' }}>
<span>Reg No: <strong className="text-[#1E293B]">{data?.student.regNumber || effectiveRegNumber || imsSession?.student.regNumber}</strong></span>
<span>•</span>
<span>{data?.student.degree} {data?.student.department}</span>
<span>•</span>
<span>Year {data?.student.year}, Sem {data?.student.semester} ({data?.student.section})</span>
</div>
</div>
</div>
<div className="flex items-center gap-2.5 self-start md:self-auto">
<Link
to={`/faculty?dept=${encodeURIComponent(data?.student.department || '')}`}
className="flex items-center gap-1.5 px-3.5 py-2 rounded-xl bg-orange-50 hover:bg-orange-100 text-[#F97316] border border-orange-200 text-xs font-bold transition-all cursor-pointer"
>
<span>Faculty Directory</span>
<ExternalLink className="w-3.5 h-3.5" />
</Link>
<button
onClick={handleLogoutIms}
className="flex items-center gap-1.5 px-4 py-2 rounded-xl bg-white hover:bg-rose-50 text-[#64748B] hover:text-rose-600 border border-[#E5E7EB] hover:border-rose-200 text-xs font-semibold transition-all cursor-pointer"
style={{ fontFamily: 'Plus Jakarta Sans, sans-serif' }}
>
<LogOut className="w-4 h-4" />
Sign Out
</button>
</div>
</div>
</div>
</div>
<div className="container-custom py-8 pb-32 space-y-8">
{/* ─── Key Stats Quick Bar ─── */}
{data && (
<div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
<div className="bg-white border border-[#E5E7EB] rounded-2xl p-4 flex items-center gap-3.5 shadow-sm">
<div className="w-10 h-10 rounded-xl bg-orange-50 border border-orange-200 flex items-center justify-center text-[#F97316] shrink-0">
<Building className="w-5 h-5" />
</div>
<div className="min-w-0">
<p className="text-[11px] font-bold text-[#94A3B8] uppercase tracking-wider">Assigned Room</p>
<p className="text-sm sm:text-base font-extrabold text-[#1E293B] truncate" style={{ fontFamily: 'Plus Jakarta Sans, sans-serif' }}>{data.classLocation.roomNumber}</p>
<p className="text-[10px] text-[#64748B] truncate">{data.classLocation.floor}</p>
</div>
</div>
<div className="bg-white border border-[#E5E7EB] rounded-2xl p-4 flex items-center gap-3.5 shadow-sm">
<div className="w-10 h-10 rounded-xl bg-purple-50 border border-purple-200 flex items-center justify-center text-purple-600 shrink-0">
<Users className="w-5 h-5" />
</div>
<div className="min-w-0">
<p className="text-[11px] font-bold text-[#94A3B8] uppercase tracking-wider">Class Incharge</p>
<p className="text-sm sm:text-base font-extrabold text-[#1E293B] truncate" style={{ fontFamily: 'Plus Jakarta Sans, sans-serif' }}>
{classInchargeMember?.facultyName.split(' ')[0] || 'Assigned'}
</p>
<p className="text-[10px] text-[#64748B] truncate">
{classInchargeMember?.officeLocation || 'Staff Cabin'}
</p>
</div>
</div>
<div className="bg-white border border-[#E5E7EB] rounded-2xl p-4 flex items-center gap-3.5 shadow-sm">
<div className="w-10 h-10 rounded-xl bg-blue-50 border border-blue-200 flex items-center justify-center text-blue-600 shrink-0">
<GraduationCap className="w-5 h-5" />
</div>
<div className="min-w-0">
<p className="text-[11px] font-bold text-[#94A3B8] uppercase tracking-wider">Branch & Section</p>
<p className="text-sm sm:text-base font-extrabold text-[#1E293B] truncate" style={{ fontFamily: 'Plus Jakarta Sans, sans-serif' }}>{data.student.departmentCode} ({data.student.section})</p>
<p className="text-[10px] text-[#64748B] truncate">Semester {data.student.semester}</p>
</div>
</div>
<div className="bg-white border border-[#E5E7EB] rounded-2xl p-4 flex items-center gap-3.5 shadow-sm">
<div className="w-10 h-10 rounded-xl bg-emerald-50 border border-emerald-200 flex items-center justify-center text-emerald-600 shrink-0">
<Calendar className="w-5 h-5" />
</div>
<div className="min-w-0">
<p className="text-[11px] font-bold text-[#94A3B8] uppercase tracking-wider">Academic Batch</p>
<p className="text-sm sm:text-base font-extrabold text-[#1E293B] truncate" style={{ fontFamily: 'Plus Jakarta Sans, sans-serif' }}>{data.student.batch}</p>
<p className="text-[10px] text-[#64748B] truncate">{data.student.regulation}</p>
</div>
</div>
</div>
)}
{/* ─── Navigation Tabs ─── */}
<div className="flex items-center justify-between border-b border-[#E5E7EB] pb-4 overflow-x-auto gap-4">
<div className="flex items-center gap-2">
{[
{ id: 'timetable', label: "Today's Timetable", icon: Clock },
{ id: 'location', label: 'Class & Building Location', icon: MapPin },
].map((tab) => {
const Icon = tab.icon;
const isActive = activeTab === tab.id;
return (
<button
key={tab.id}
onClick={() => setActiveTab(tab.id as any)}
className={`flex items-center gap-2 px-4 py-2.5 rounded-xl text-xs sm:text-sm font-bold transition-all cursor-pointer whitespace-nowrap ${
isActive
? 'bg-gradient-to-r from-[#FF6B00] to-[#F97316] text-white shadow-md shadow-orange-500/20'
: 'bg-white text-[#64748B] hover:text-[#1E293B] border border-[#E5E7EB] hover:bg-slate-50'
}`}
style={{ fontFamily: 'Plus Jakarta Sans, sans-serif' }}
>
<Icon className={`w-4 h-4 ${isActive ? 'text-white' : 'text-[#94A3B8]'}`} />
<span>{tab.label}</span>
</button>
);
})}
</div>
</div>
{/* ─── Main Content Tabs ─── */}
{isLoading ? (
<div className="flex flex-col items-center justify-center py-20 gap-3">
<div className="w-8 h-8 border-3 border-[#F97316] border-t-transparent rounded-full animate-spin" />
<p className="text-xs text-[#64748B] font-medium">Connecting to IMS services...</p>
</div>
) : error ? (
<div className="bg-rose-50 border border-rose-200 rounded-3xl p-8 text-center space-y-3">
<p className="text-rose-700 font-bold text-base">Error connecting to IMS Gateway</p>
<p className="text-[#64748B] text-xs max-w-md mx-auto">{error}</p>
<button
onClick={() => loadDashboard()}
className="px-4 py-2 bg-rose-600 text-white rounded-xl text-xs font-bold hover:bg-rose-700 transition-colors cursor-pointer"
>
Retry Connection
</button>
</div>
) : data ? (
<div>
{/* ─── 1. TIMETABLE TAB ─── */}
{activeTab === 'timetable' && (
<div className="space-y-6">
<div className="flex flex-wrap items-center justify-between gap-3 bg-white p-4 rounded-2xl border border-[#E5E7EB] shadow-sm">
<div className="flex items-center gap-2">
<Calendar className="w-4 h-4 text-[#F97316]" />
<span className="text-sm font-bold text-[#1E293B] tracking-wide" style={{ fontFamily: 'Plus Jakarta Sans, sans-serif' }}>
{data.todaySchedule.dayOfWeek} SCHEDULE ({data.todaySchedule.date})
</span>
</div>
<div className="flex items-center gap-3 text-xs">
<span className="flex items-center gap-1 text-emerald-600 font-bold">
<span className="w-2 h-2 rounded-full bg-emerald-500 animate-pulse" />
Live Status Active
</span>
</div>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{data.todaySchedule.periods.map((period) => {
const isOngoing = period.status === 'ONGOING';
const isCompleted = period.status === 'COMPLETED';
return (
<motion.div
key={period.periodNumber}
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
className={`relative rounded-2xl p-5 border transition-all ${
isOngoing
? 'bg-gradient-to-b from-orange-500/10 via-white to-white border-[#F97316] shadow-md ring-1 ring-orange-400/30'
: isCompleted
? 'bg-slate-50/80 border-[#E5E7EB] opacity-60'
: 'bg-white border-[#E5E7EB] hover:border-slate-300 shadow-sm'
}`}
>
{/* Header Badge */}
<div className="flex items-center justify-between gap-2 mb-3">
<div className="flex items-center gap-2">
<span className="w-6 h-6 rounded-lg bg-slate-100 text-[#1E293B] font-bold text-xs flex items-center justify-center">
P{period.periodNumber}
</span>
<span className="text-xs font-semibold text-[#64748B] flex items-center gap-1">
<Clock className="w-3 h-3 text-[#94A3B8]" />
{period.timeSlot}
</span>
</div>
<span
className={`px-2.5 py-0.5 rounded-full text-[10px] font-extrabold uppercase tracking-wider ${
isOngoing
? 'bg-[#F97316] text-white animate-pulse'
: isCompleted
? 'bg-slate-200 text-[#64748B]'
: 'bg-blue-50 text-blue-600 border border-blue-200'
}`}
>
{period.status}
</span>
</div>
{/* Subject Details */}
<div className="space-y-1.5 mb-4">
<div className="flex items-center gap-2">
<span className="text-[11px] font-mono font-bold text-[#F97316]">
{period.subjectCode}
</span>
<span className="px-1.5 py-0.2 rounded text-[9px] font-bold bg-slate-100 text-[#475569] uppercase">
{period.type}
</span>
</div>
<h3 className="text-base font-extrabold text-[#1E293B] line-clamp-1" style={{ fontFamily: 'Plus Jakarta Sans, sans-serif' }}>
{period.subjectName}
</h3>
</div>
{/* Footer / Instructor & Venue */}
<div className="pt-3 border-t border-[#E5E7EB] flex items-center justify-between text-xs text-[#475569]">
<span className="truncate pr-2 font-medium">{period.facultyName}</span>
<span className="shrink-0 font-bold text-[#1E293B] px-2 py-0.5 rounded-lg bg-slate-100 flex items-center gap-1">
<MapPin className="w-3 h-3 text-[#F97316]" />
{period.venue}
</span>
</div>
</motion.div>
);
})}
</div>
</div>
)}
{/* ─── 2. CLASS LOCATION TAB ─── */}
{activeTab === 'location' && (
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
<div className="bg-white border border-[#E5E7EB] rounded-3xl p-6 space-y-6 shadow-sm">
<div>
<h3 className="text-lg font-extrabold text-[#1E293B] flex items-center gap-2 mb-1" style={{ fontFamily: 'Plus Jakarta Sans, sans-serif' }}>
<Building className="w-5 h-5 text-[#F97316]" />
Classroom & Section Venue
</h3>
<p className="text-xs text-[#64748B]">
Official lecture hall allocation from Academic Registrar.
</p>
</div>
<div className="space-y-4">
<div className="p-4 rounded-2xl bg-slate-50 border border-[#E5E7EB] flex items-center justify-between">
<div>
<p className="text-xs text-[#64748B] uppercase font-semibold">Room Number</p>
<p className="text-2xl font-black text-[#1E293B]" style={{ fontFamily: 'Plus Jakarta Sans, sans-serif' }}>{data.classLocation.roomNumber}</p>
</div>
<span className="px-3 py-1 bg-orange-50 text-[#F97316] border border-orange-200 rounded-xl text-xs font-bold">
{data.student.section} Section
</span>
</div>
<div className="space-y-3 text-xs">
<div className="flex justify-between py-2 border-b border-[#E5E7EB]">
<span className="text-[#64748B]">Building Block:</span>
<span className="font-bold text-[#1E293B] text-right">{data.classLocation.buildingName}</span>
</div>
<div className="flex justify-between py-2 border-b border-[#E5E7EB]">
<span className="text-[#64748B]">Floor & Wing:</span>
<span className="font-bold text-[#1E293B]">{data.classLocation.floor}, {data.classLocation.wing}</span>
</div>
<div className="flex justify-between py-2">
<span className="text-[#64748B]">Landmark Directions:</span>
<span className="font-bold text-[#F97316] text-right max-w-xs">{data.classLocation.landmark}</span>
</div>
</div>
</div>
</div>
<div className="bg-white border border-[#E5E7EB] rounded-3xl p-6 flex flex-col justify-between space-y-6 shadow-sm">
<div className="space-y-3">
<h3 className="text-lg font-extrabold text-[#1E293B] flex items-center gap-2" style={{ fontFamily: 'Plus Jakarta Sans, sans-serif' }}>
<Compass className="w-5 h-5 text-[#F97316]" />
Academic Department Details
</h3>
<p className="text-xs text-[#64748B] leading-relaxed">
Official department profile, curriculum regulation, and academic guidelines for batch {data.student.batch}.
</p>
<div className="grid grid-cols-2 gap-3 pt-3">
<div className="p-3 bg-slate-50 rounded-xl border border-[#E5E7EB]">
<p className="text-[10px] uppercase font-bold text-[#94A3B8]">Degree & Branch</p>
<p className="text-xs font-bold text-[#1E293B] mt-0.5">{data.student.degree} {data.student.departmentCode}</p>
</div>
<div className="p-3 bg-slate-50 rounded-xl border border-[#E5E7EB]">
<p className="text-[10px] uppercase font-bold text-[#94A3B8]">Regulation</p>
<p className="text-xs font-bold text-[#1E293B] mt-0.5">{data.student.regulation}</p>
</div>
<div className="p-3 bg-slate-50 rounded-xl border border-[#E5E7EB]">
<p className="text-[10px] uppercase font-bold text-[#94A3B8]">Academic Year</p>
<p className="text-xs font-bold text-[#1E293B] mt-0.5">Year {data.student.year} (Sem {data.student.semester})</p>
</div>
<div className="p-3 bg-slate-50 rounded-xl border border-[#E5E7EB]">
<p className="text-[10px] uppercase font-bold text-[#94A3B8]">Batch Cohort</p>
<p className="text-xs font-bold text-[#1E293B] mt-0.5">{data.student.batch}</p>
</div>
</div>
</div>
<div className="p-4 rounded-2xl bg-orange-50 border border-orange-200 flex items-center gap-3">
<HelpCircle className="w-5 h-5 text-[#F97316] shrink-0" />
<p className="text-xs text-[#475569]">
Need classroom adjustment? Contact your Class Incharge or Head of Department.
</p>
</div>
</div>
</div>
)}
</div>
) : null}
</div>
</div>
);
}

View File

@@ -13,6 +13,7 @@ import {
import SectionTitle from '@/components/SectionTitle/SectionTitle';
import { StaggerContainer, StaggerItem } from '@/components/AnimatedContainer/AnimatedContainer';
import { TOOLKIT_ITEMS, DEPARTMENTS } from '@/constants';
import { DEPARTMENT_CURRICULUM, DEPARTMENT_CODE_MAP, PROFESSIONAL_ELECTIVES_LIST } from '@/constants/departmentCurriculum';
const TOOLKIT_ICONS: Record<string, { icon: React.ComponentType<{ className?: string }>; bg: string; color: string }> = {
'CS tools': { icon: Code, bg: '#EFF6FF', color: '#3B82F6' },
@@ -655,105 +656,7 @@ const BIOTECH_TOOLS_CATEGORIES = [
}
];
const PROFESSIONAL_ELECTIVES_LIST: Array<{ code: string; name: string; credits: number }> = [
{ code: 'AD23V11', name: 'Agriculture Data Analytics', credits: 3 },
{ code: 'AD23V12', name: 'Big Data Analytics', credits: 3 },
{ code: 'AD23V13', name: 'Data warehousing and Data Mining', credits: 3 },
{ code: 'AD23V14', name: 'Health Care Analytics', credits: 3 },
{ code: 'AD23V15', name: 'Image and Video Analytics', credits: 3 },
{ code: 'AD23V16', name: 'Web and Social Media Analytics', credits: 3 },
{ code: 'AD23V17', name: 'Predictive Analytics', credits: 3 },
{ code: 'AD23V18', name: 'Sentiment Analysis', credits: 3 },
{ code: 'AD23V21', name: 'AI in IoT', credits: 3 },
{ code: 'AD23V22', name: 'Applied Machine Learning', credits: 3 },
{ code: 'AD23V23', name: 'Cognitive Computing', credits: 3 },
{ code: 'AD23V24', name: 'Computer Vision', credits: 3 },
{ code: 'AD23V25', name: 'Ethics For AI', credits: 3 },
{ code: 'AD23V26', name: 'Game Theory', credits: 3 },
{ code: 'AD23V27', name: 'Quantum Computing Techniques', credits: 3 },
{ code: 'AD23V28', name: 'Responsive AI', credits: 3 },
];
const AIDS_CURRICULUM: Record<number, Array<{ code: string; name: string; credits: number; isElective?: boolean; electiveSlot?: number }>> = {
1: [
{ code: 'HS23111', name: 'Communicative English', credits: 3 },
{ code: 'MA23111', name: 'Matrices and Calculus', credits: 4 },
{ code: 'PH23111', name: 'Physics for Information Science', credits: 3 },
{ code: 'GE23111', name: 'Problem Solving and C Programming', credits: 3 },
{ code: 'GE23113', name: 'Basic Electrical and Electronics Engineering', credits: 3 },
{ code: 'GE23112', name: 'Heritage of Tamils', credits: 0 },
{ code: 'PH23121', name: 'Physics Laboratory', credits: 1 },
{ code: 'GE23121', name: 'Problem Solving and C Programming Laboratory', credits: 1 },
{ code: 'GE23122', name: 'Engineering Practices Laboratory', credits: 1 },
],
2: [
{ code: 'HS23211', name: 'Professional English', credits: 2 },
{ code: 'CY23211', name: 'Engineering Chemistry', credits: 3 },
{ code: 'MA23211', name: 'Statistics and Numerical Methods', credits: 4 },
{ code: 'AD23211', name: 'Python for Data Science', credits: 3 },
{ code: 'GE23213', name: 'Tamils and Technology', credits: 0 },
{ code: 'GE23231', name: 'Engineering Graphics', credits: 4 },
{ code: 'AD23231', name: 'Data Structures Design', credits: 4 },
{ code: 'CY23221', name: 'Chemistry Laboratory', credits: 1 },
{ code: 'AD23221', name: 'Python for Data Science Laboratory', credits: 1 },
{ code: 'GE23221', name: 'Communication Laboratory / Foreign Language', credits: 1 },
],
3: [
{ code: 'MA23311', name: 'Discrete Mathematics', credits: 4 },
{ code: 'AL23311', name: 'Artificial Intelligence', credits: 3 },
{ code: 'CS23312', name: 'Object Oriented Programming', credits: 3 },
{ code: 'CS23411', name: 'Database Management Systems', credits: 3 },
{ code: 'EC23331', name: 'Digital Principles and Computer Organization', credits: 4 },
{ code: 'AL23321', name: 'Artificial Intelligence Laboratory', credits: 1 },
{ code: 'CS23421', name: 'Database Management Systems Laboratory', credits: 1 },
{ code: 'CS23322', name: 'Object Oriented Programming Laboratory', credits: 1 },
{ code: 'AD23IC1', name: 'Data Wrangling', credits: 1 },
],
4: [
{ code: 'GE23411', name: 'Environmental Science and Sustainability', credits: 2 },
{ code: 'MA23411', name: 'Probability and Statistics', credits: 4 },
{ code: 'AD23411', name: 'Data Analytics', credits: 3 },
{ code: 'AL23411', name: 'Machine Learning', credits: 3 },
{ code: 'CS23412', name: 'Operating Systems', credits: 3 },
{ code: 'CS23431', name: 'Design and Analysis of Algorithms', credits: 4 },
{ code: 'AD23421', name: 'Data Analytics Laboratory', credits: 1 },
{ code: 'AL23421', name: 'Machine Learning Laboratory', credits: 1 },
{ code: 'CS23422', name: 'Operating Systems Laboratory', credits: 1 },
{ code: 'AD23IC2', name: 'Introduction to AZURE Machine Learning', credits: 1 },
],
5: [
{ code: 'AD23511', name: 'Deep Learning', credits: 3 },
{ code: 'CS23511', name: 'Computer Networks', credits: 3 },
{ code: 'PEC01', name: 'Professional Elective I', credits: 3, isElective: true, electiveSlot: 1 },
{ code: 'PEC02', name: 'Professional Elective II', credits: 3, isElective: true, electiveSlot: 2 },
{ code: 'CB23531', name: 'Business Analytics', credits: 4 },
{ code: 'AD23532', name: 'Data Exploration and Visualization', credits: 4 },
{ code: 'AD23521', name: 'Deep Learning Laboratory', credits: 1 },
{ code: 'CS23521', name: 'Computer Networks Laboratory', credits: 1 },
{ code: 'AD23IC3', name: 'Tableau - Data Visualization', credits: 1 },
],
6: [
{ code: 'PEC03', name: 'Professional Elective III', credits: 3, isElective: true, electiveSlot: 3 },
{ code: 'PEC04', name: 'Professional Elective IV', credits: 3, isElective: true, electiveSlot: 4 },
{ code: 'OEC01', name: 'Open Elective I', credits: 3 },
{ code: 'OEC02', name: 'Open Elective II', credits: 3 },
{ code: 'EC23631', name: 'Embedded Systems and IoT', credits: 4 },
{ code: 'CS23631', name: 'Object Oriented Software Engineering', credits: 4 },
{ code: 'AD23621', name: 'Mini Project', credits: 2 },
],
7: [
{ code: 'GE23711', name: 'Human Values and Ethics', credits: 2 },
{ code: 'MGT01', name: 'Elective - Management', credits: 3 },
{ code: 'CB23511', name: 'Data and Information Security', credits: 3 },
{ code: 'PEC05', name: 'Professional Elective V', credits: 3, isElective: true, electiveSlot: 5 },
{ code: 'PEC06', name: 'Professional Elective VI', credits: 3, isElective: true, electiveSlot: 6 },
{ code: 'AD23721', name: 'Internship / Certification Course', credits: 2 },
],
8: [
{ code: 'OEC03', name: 'Open Elective III', credits: 3 },
{ code: 'AD23821', name: 'Project Work', credits: 10 },
],
};
export default function Toolkit() {
const [searchParams, setSearchParams] = useSearchParams();
@@ -792,17 +695,34 @@ export default function Toolkit() {
setCalculationType(type);
const semNum = parseInt(gpaSemester.replace(/\D/g, ''), 10) || 1;
const isAIDS = gpaDepartment.toLowerCase().includes('artificial intelligence') || gpaDepartment.toLowerCase().includes('data science');
const deptKey = DEPARTMENT_CODE_MAP[gpaDepartment] || '';
if (isAIDS && AIDS_CURRICULUM[semNum]) {
const loaded = AIDS_CURRICULUM[semNum]
.filter((s) => type === 'internal' || s.credits > 0)
.map((s) => {
if (s.isElective) {
const defaultCode = s.code === 'PEC01' ? 'AD23V11' : s.code === 'PEC02' ? 'AD23V12' : s.code === 'PEC03' ? 'AD23V13' : s.code === 'PEC04' ? 'AD23V14' : s.code === 'PEC05' ? 'AD23V15' : 'AD23V16';
const defaultObj = PROFESSIONAL_ELECTIVES_LIST.find((e) => e.code === defaultCode);
let rawCurriculum = null;
try {
const saved = localStorage.getItem('RIT_LOCAL_GPA_CURRICULUM');
if (saved) {
const parsed = JSON.parse(saved);
if (parsed[deptKey] && parsed[deptKey][semNum] && parsed[deptKey][semNum].length > 0) {
rawCurriculum = parsed[deptKey][semNum];
}
}
} catch {}
if (!rawCurriculum) {
rawCurriculum = DEPARTMENT_CURRICULUM[deptKey]?.[semNum];
}
if (rawCurriculum && rawCurriculum.length > 0) {
let electiveCounter = 1;
const loaded = rawCurriculum
.filter((s: any) => type === 'internal' || s.credits > 0)
.map((s: any) => {
const isElective = !!s.isElective;
if (isElective) {
const slot = s.electiveSlot || electiveCounter++;
const defaultElectiveObj = PROFESSIONAL_ELECTIVES_LIST[(slot - 1) % PROFESSIONAL_ELECTIVES_LIST.length] || PROFESSIONAL_ELECTIVES_LIST[0];
return {
name: defaultObj ? `${defaultObj.code} - ${defaultObj.name}` : `${s.code} - ${s.name}`,
name: `${defaultElectiveObj.code} - ${defaultElectiveObj.name}`,
credits: s.credits,
grade: 'O',
cat1: '45',
@@ -810,12 +730,12 @@ export default function Toolkit() {
assignment: '9',
attendance: '95',
isElective: true,
electiveSlot: s.electiveSlot,
electiveCode: defaultCode,
electiveSlot: slot,
electiveCode: defaultElectiveObj.code,
};
}
return {
name: `${s.code} - ${s.name}`,
name: s.name,
credits: s.credits,
grade: 'O',
cat1: '45',
@@ -1498,6 +1418,65 @@ export default function Toolkit() {
<SectionTitle tag="Useful Downloads" title="Student" highlight="Toolkit" align="left" />
<StaggerContainer className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-20">
{TOOLKIT_ITEMS.map((item) => {
if (item.title === 'GPA and internal calculator') {
return (
<StaggerItem key={item.id} className="col-span-1 md:col-span-2 flex">
<motion.div
onClick={() => setSelectedToolkit('gpa')}
whileHover={{ y: -4, boxShadow: '0 20px 40px -12px rgba(239,68,68,0.22)' }}
className="relative w-full p-7 md:p-8 bg-gradient-to-r from-[#FFF7ED] via-[#FEF2F2] to-[#FFF1F2] rounded-[26px] border-2 border-[#FECACA] hover:border-[#FCA5A5] cursor-pointer group transition-all shadow-md hover:shadow-xl overflow-hidden flex flex-col md:flex-row items-start md:items-center justify-between gap-6"
>
{/* Top Gradient Bar */}
<div className="absolute top-0 left-0 right-0 h-1.5 bg-gradient-to-r from-[#FF6B00] via-[#EF4444] to-[#F97316]" />
<div className="flex items-start md:items-center gap-5 flex-1 min-w-0 z-10">
<div className="w-16 h-16 md:w-18 md:h-18 rounded-2xl bg-gradient-to-tr from-[#EF4444] via-[#F97316] to-[#FF6B00] text-white flex items-center justify-center shrink-0 font-bold shadow-lg shadow-rose-500/25 group-hover:scale-105 transition-transform">
<Calculator className="w-8 h-8 md:w-9 md:h-9" />
</div>
<div className="flex-1 min-w-0">
<div className="flex flex-wrap items-center gap-2.5 mb-1.5">
<span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-extrabold bg-gradient-to-r from-[#EF4444] to-[#F97316] text-white shadow-xs tracking-wide uppercase">
<Sparkles className="w-3.5 h-3.5 animate-pulse" /> POPULAR UTILITY
</span>
<span className="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-semibold bg-white/90 text-[#991B1B] border border-red-200 shadow-2xs">
RIT Regulations
</span>
</div>
<h3 className="text-xl md:text-2xl font-extrabold text-[#1E293B] group-hover:text-[#EF4444] transition-colors mb-1.5" style={{ fontFamily: 'Plus Jakarta Sans, sans-serif' }}>
GPA, CGPA & Internal Marks Calculator
</h3>
<p className="text-sm text-[#475569] leading-relaxed max-w-2xl" style={{ fontFamily: 'Inter, sans-serif' }}>
Calculate your semester GPA, overall CGPA, and internal assessment marks based on official department course regulations and grade points.
</p>
<div className="flex flex-wrap items-center gap-3 mt-3 text-xs font-medium text-[#64748B]">
<span className="flex items-center gap-1.5 text-rose-700 font-semibold bg-rose-50 px-2.5 py-1 rounded-lg border border-rose-200/80">
<CheckCircle2 className="w-3.5 h-3.5 text-rose-500" /> Semester GPA
</span>
<span className="flex items-center gap-1.5 text-orange-700 font-semibold bg-orange-50 px-2.5 py-1 rounded-lg border border-orange-200/80">
<CheckCircle2 className="w-3.5 h-3.5 text-orange-500" /> Cumulative CGPA
</span>
<span className="flex items-center gap-1.5 text-amber-700 font-semibold bg-amber-50 px-2.5 py-1 rounded-lg border border-amber-200/80">
<CheckCircle2 className="w-3.5 h-3.5 text-amber-500" /> Internal Score
</span>
</div>
</div>
</div>
<div className="flex items-center gap-2 z-10 self-end md:self-center shrink-0">
<button className="px-6 py-3 bg-gradient-to-r from-[#EF4444] via-[#F97316] to-[#FF6B00] hover:from-[#DC2626] hover:to-[#EA580C] text-white font-bold text-sm rounded-xl shadow-md group-hover:shadow-lg group-hover:scale-105 transition-all flex items-center gap-2">
Calculate Now
<ChevronRight className="w-4 h-4 group-hover:translate-x-1 transition-transform" />
</button>
</div>
</motion.div>
</StaggerItem>
);
}
const iconConfig = TOOLKIT_ICONS[item.title] || { icon: Code, bg: '#FFF7ED', color: '#F97316' };
const IconComponent = iconConfig.icon;
return (
@@ -1516,8 +1495,6 @@ export default function Toolkit() {
setSelectedToolkit('ai');
} else if (item.title === 'Biotech tools') {
setSelectedToolkit('biotech');
} else if (item.title === 'GPA and internal calculator') {
setSelectedToolkit('gpa');
} else if (item.url && item.url !== '#') {
window.open(item.url, '_blank');
}

View File

@@ -0,0 +1,83 @@
import { getBackendUrl } from '@/lib/utils';
const DEVICE_ID_KEY = 'rit_device_identifier';
/**
* Gets a persistent user identifier for likes.
* If user is authenticated, uses email. Otherwise uses a persistent UUID in localStorage.
*/
export function getClubUserIdentifier(userEmail?: string | null): string {
if (userEmail && userEmail.trim()) {
return userEmail.trim().toLowerCase();
}
try {
let deviceId = localStorage.getItem(DEVICE_ID_KEY);
if (!deviceId) {
deviceId = 'guest_' + Math.random().toString(36).substring(2, 11) + Date.now().toString(36);
localStorage.setItem(DEVICE_ID_KEY, deviceId);
}
return deviceId;
} catch {
return 'guest_fallback_user';
}
}
/**
* Fetch total counts of likes for all clubs & centers from database
*/
export async function fetchClubLikes(): Promise<Record<string, number>> {
try {
const res = await fetch(getBackendUrl('/api/clubs/likes'));
if (!res.ok) {
throw new Error(`Failed to fetch likes: ${res.status}`);
}
const data = await res.json();
return data || {};
} catch (err) {
console.warn('Unable to fetch club likes from database backend:', err);
return {};
}
}
/**
* Fetch user's liked club IDs from database
*/
export async function fetchUserLikedClubs(userIdentifier: string): Promise<string[]> {
try {
const res = await fetch(
getBackendUrl(`/api/clubs/user-likes?userIdentifier=${encodeURIComponent(userIdentifier)}`)
);
if (!res.ok) {
throw new Error(`Failed to fetch user likes: ${res.status}`);
}
const data = await res.json();
return Array.isArray(data) ? data : [];
} catch (err) {
console.warn('Unable to fetch user liked clubs from database backend:', err);
return [];
}
}
/**
* Toggle like status for a club/center in database
*/
export async function toggleClubLikeInDb(
clubId: string,
userIdentifier: string
): Promise<{ liked: boolean; count: number } | null> {
try {
const res = await fetch(getBackendUrl(`/api/clubs/${encodeURIComponent(clubId)}/like`), {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ userIdentifier }),
});
if (!res.ok) {
throw new Error(`Toggle like failed: ${res.status}`);
}
return await res.json();
} catch (err) {
console.warn(`Failed to persist like for club ${clubId} in database:`, err);
return null;
}
}

419
src/services/imsService.ts Normal file
View File

@@ -0,0 +1,419 @@
import { getBackendUrl } from '@/lib/utils';
export interface StudentInfo {
studentId: string;
regNumber: string;
name: string;
email: string;
degree: string;
department: string;
departmentCode: string;
year: number;
semester: number;
section: string;
batch: string;
regulation: string;
}
export interface ClassLocationInfo {
roomNumber: string;
buildingName: string;
floor: string;
wing: string;
landmark: string;
}
export interface ClassFacultyMember {
subjectCode: string;
subjectName: string;
facultyName: string;
designation: string;
email: string;
officeLocation: string;
phoneExtension: string;
avatarUrl?: string;
isClassIncharge: boolean;
}
export interface TimetablePeriod {
periodNumber: number;
timeSlot: string;
startTime: string;
endTime: string;
subjectCode: string;
subjectName: string;
type: 'THEORY' | 'LAB' | 'TUTORIAL' | 'LIBRARY';
facultyName: string;
venue: string;
status: 'UPCOMING' | 'ONGOING' | 'COMPLETED';
}
export interface DaySchedule {
dayOfWeek: string;
date: string;
periods: TimetablePeriod[];
}
export interface StudentDashboardData {
student: StudentInfo;
classLocation: ClassLocationInfo;
facultyList: ClassFacultyMember[];
todaySchedule: DaySchedule;
isMockData: boolean;
}
export interface MockUserCredential {
regNumber: string;
defaultPassword: string;
studentName: string;
department: string;
section: string;
}
export interface ImsLoginResult {
success: boolean;
message: string;
token?: string;
student?: StudentInfo;
}
const IMS_STORAGE_KEY = 'rit_ims_student_session';
export function getStoredImsSession(): { token: string; student: StudentInfo } | null {
try {
const raw = localStorage.getItem(IMS_STORAGE_KEY);
if (!raw) return null;
return JSON.parse(raw);
} catch {
return null;
}
}
export function saveImsSession(token: string, student: StudentInfo) {
localStorage.setItem(IMS_STORAGE_KEY, JSON.stringify({ token, student }));
}
export function clearImsSession() {
localStorage.removeItem(IMS_STORAGE_KEY);
}
// ─── Default Mock Data for Client Fallback ───────────────────────────
const CLIENT_FALLBACK_MOCKS: Record<string, StudentDashboardData> = {
'2114251001': {
student: {
studentId: '2114251001',
regNumber: '2114251001',
name: 'Anbu Kathir',
email: '251001@ritchennai.edu.in',
degree: 'B.E.',
department: 'Computer Science & Engineering',
departmentCode: 'CSE',
year: 1,
semester: 2,
section: 'A',
batch: '2025 - 2029',
regulation: '2021 Regulation',
},
classLocation: {
roomNumber: 'LH-204',
buildingName: 'Dr. APJ Abdul Kalam Academic Block',
floor: '2nd Floor',
wing: 'East Wing',
landmark: 'Next to CSE Department Library, Opposite to Seminar Hall',
},
facultyList: [
{
subjectCode: 'CS3201',
subjectName: 'Data Structures & Algorithms',
facultyName: 'Dr. R. Arunkumar',
designation: 'Associate Professor & Class Incharge',
email: 'arunkumar.r@ritchennai.edu.in',
officeLocation: 'APJ Block, Cabin 208-B',
phoneExtension: 'Ext. 312',
avatarUrl: 'https://api.dicebear.com/7.x/avataaars/svg?seed=Arunkumar',
isClassIncharge: true,
},
{
subjectCode: 'MA3251',
subjectName: 'Discrete Mathematics',
facultyName: 'Dr. S. Malathi',
designation: 'Professor (Mathematics)',
email: 'malathi.s@ritchennai.edu.in',
officeLocation: 'Science & Humanities Block, 1st Floor',
phoneExtension: 'Ext. 118',
avatarUrl: 'https://api.dicebear.com/7.x/avataaars/svg?seed=Malathi',
isClassIncharge: false,
},
{
subjectCode: 'CS3202',
subjectName: 'Digital Principles & System Design',
facultyName: 'Dr. M. Balaji',
designation: 'Assistant Professor',
email: 'balaji.m@ritchennai.edu.in',
officeLocation: 'APJ Block, Cabin 104',
phoneExtension: 'Ext. 325',
avatarUrl: 'https://api.dicebear.com/7.x/avataaars/svg?seed=Balaji',
isClassIncharge: false,
},
{
subjectCode: 'GE3251',
subjectName: 'Environmental Sciences & Sustainability',
facultyName: 'Dr. T. Gayathri',
designation: 'Assistant Professor (Chemistry)',
email: 'gayathri.t@ritchennai.edu.in',
officeLocation: 'Science Block, Chemistry Cabin 3',
phoneExtension: 'Ext. 142',
avatarUrl: 'https://api.dicebear.com/7.x/avataaars/svg?seed=Gayathri',
isClassIncharge: false,
},
{
subjectCode: 'CS3271',
subjectName: 'Data Structures Laboratory',
facultyName: 'Dr. R. Arunkumar / Dr. K. Revathi',
designation: 'Lab In-Charges',
email: 'lab.cse@ritchennai.edu.in',
officeLocation: 'Computing Center 3 (CC-03)',
phoneExtension: 'Ext. 330',
avatarUrl: 'https://api.dicebear.com/7.x/avataaars/svg?seed=Revathi',
isClassIncharge: false,
},
],
todaySchedule: {
dayOfWeek: 'MONDAY',
date: new Date().toISOString().split('T')[0],
periods: [
{ periodNumber: 1, timeSlot: '08:45 AM - 09:40 AM', startTime: '08:45', endTime: '09:40', subjectCode: 'MA3251', subjectName: 'Discrete Mathematics', type: 'THEORY', facultyName: 'Dr. S. Malathi', venue: 'LH-204', status: 'COMPLETED' },
{ periodNumber: 2, timeSlot: '09:40 AM - 10:35 AM', startTime: '09:40', endTime: '10:35', subjectCode: 'CS3201', subjectName: 'Data Structures & Algorithms', type: 'THEORY', facultyName: 'Dr. R. Arunkumar', venue: 'LH-204', status: 'COMPLETED' },
{ periodNumber: 3, timeSlot: '10:50 AM - 11:45 AM', startTime: '10:50', endTime: '11:45', subjectCode: 'CS3202', subjectName: 'Digital Principles & System Design', type: 'THEORY', facultyName: 'Dr. M. Balaji', venue: 'LH-204', status: 'ONGOING' },
{ periodNumber: 4, timeSlot: '11:45 AM - 12:40 PM', startTime: '11:45', endTime: '12:40', subjectCode: 'GE3251', subjectName: 'Environmental Sciences', type: 'THEORY', facultyName: 'Dr. T. Gayathri', venue: 'LH-204', status: 'UPCOMING' },
{ periodNumber: 5, timeSlot: '01:30 PM - 02:25 PM', startTime: '13:30', endTime: '14:25', subjectCode: 'CS3201', subjectName: 'DSA Tutorial & Problem Solving', type: 'TUTORIAL', facultyName: 'Dr. R. Arunkumar', venue: 'LH-204', status: 'UPCOMING' },
{ periodNumber: 6, timeSlot: '02:25 PM - 03:20 PM', startTime: '14:25', endTime: '15:20', subjectCode: 'LIB', subjectName: 'Digital Library & Research Hours', type: 'LIBRARY', facultyName: 'Chief Librarian', venue: 'Central Library - 2nd Floor', status: 'UPCOMING' },
],
},
isMockData: true,
},
'2114251002': {
student: {
studentId: '2114251002',
regNumber: '2114251002',
name: 'Priyadharshini M',
email: '251002@ritchennai.edu.in',
degree: 'B.Tech.',
department: 'Artificial Intelligence & Data Science',
departmentCode: 'AIDS',
year: 1,
semester: 2,
section: 'B',
batch: '2025 - 2029',
regulation: '2021 Regulation',
},
classLocation: {
roomNumber: 'LH-301',
buildingName: 'Sir Isaac Newton Innovation Block',
floor: '3rd Floor',
wing: 'North Wing',
landmark: 'Opposite AI Centre of Excellence, Near Lift Lobby',
},
facultyList: [
{
subjectCode: 'AD3251',
subjectName: 'Data Structures Design',
facultyName: 'Dr. N. Saravanan',
designation: 'Associate Professor & Class Incharge',
email: 'saravanan.n@ritchennai.edu.in',
officeLocation: 'Newton Block, Cabin 302',
phoneExtension: 'Ext. 401',
avatarUrl: 'https://api.dicebear.com/7.x/avataaars/svg?seed=Saravanan',
isClassIncharge: true,
},
{
subjectCode: 'AD3252',
subjectName: 'Foundations of Artificial Intelligence',
facultyName: 'Prof. J. Daniel',
designation: 'Assistant Professor',
email: 'daniel.j@ritchennai.edu.in',
officeLocation: 'Newton Block, Cabin 306',
phoneExtension: 'Ext. 405',
avatarUrl: 'https://api.dicebear.com/7.x/avataaars/svg?seed=Daniel',
isClassIncharge: false,
},
{
subjectCode: 'MA3251',
subjectName: 'Probability and Statistics',
facultyName: 'Dr. V. Lakshmi',
designation: 'Professor (Mathematics)',
email: 'lakshmi.v@ritchennai.edu.in',
officeLocation: 'Science Block, Cabin 108',
phoneExtension: 'Ext. 119',
avatarUrl: 'https://api.dicebear.com/7.x/avataaars/svg?seed=Lakshmi',
isClassIncharge: false,
},
],
todaySchedule: {
dayOfWeek: 'MONDAY',
date: new Date().toISOString().split('T')[0],
periods: [
{ periodNumber: 1, timeSlot: '08:45 AM - 09:40 AM', startTime: '08:45', endTime: '09:40', subjectCode: 'MA3251', subjectName: 'Probability & Stats', type: 'THEORY', facultyName: 'Dr. V. Lakshmi', venue: 'LH-301', status: 'COMPLETED' },
{ periodNumber: 2, timeSlot: '09:40 AM - 10:35 AM', startTime: '09:40', endTime: '10:35', subjectCode: 'AD3251', subjectName: 'Data Structures Design', type: 'THEORY', facultyName: 'Dr. N. Saravanan', venue: 'LH-301', status: 'COMPLETED' },
{ periodNumber: 3, timeSlot: '10:50 AM - 11:45 AM', startTime: '10:50', endTime: '11:45', subjectCode: 'AD3252', subjectName: 'Foundations of AI', type: 'THEORY', facultyName: 'Prof. J. Daniel', venue: 'LH-301', status: 'ONGOING' },
{ periodNumber: 4, timeSlot: '11:45 AM - 12:40 PM', startTime: '11:45', endTime: '12:40', subjectCode: 'GE3251', subjectName: 'Environmental Sciences', type: 'THEORY', facultyName: 'Dr. T. Gayathri', venue: 'LH-301', status: 'UPCOMING' },
{ periodNumber: 5, timeSlot: '01:30 PM - 02:25 PM', startTime: '13:30', endTime: '14:25', subjectCode: 'AD3251', subjectName: 'AI Problem Solving Tutorial', type: 'TUTORIAL', facultyName: 'Dr. N. Saravanan', venue: 'LH-301', status: 'UPCOMING' },
{ periodNumber: 6, timeSlot: '02:25 PM - 03:20 PM', startTime: '14:25', endTime: '15:20', subjectCode: 'LIB', subjectName: 'Digital Library & Research Hours', type: 'LIBRARY', facultyName: 'Chief Librarian', venue: 'Central Library - 2nd Floor', status: 'UPCOMING' },
],
},
isMockData: true,
},
'2114251003': {
student: {
studentId: '2114251003',
regNumber: '2114251003',
name: 'Rahul V',
email: '251003@ritchennai.edu.in',
degree: 'B.E.',
department: 'Electronics & Communication Engineering',
departmentCode: 'ECE',
year: 1,
semester: 2,
section: 'A',
batch: '2025 - 2029',
regulation: '2021 Regulation',
},
classLocation: {
roomNumber: 'LH-105',
buildingName: 'Rabindranath Tagore Academic Block',
floor: '1st Floor',
wing: 'South Wing',
landmark: 'Near Department Auditorium',
},
facultyList: [
{
subjectCode: 'EC3251',
subjectName: 'Circuit Analysis',
facultyName: 'Dr. I. Chandra',
designation: 'Professor & Class Incharge',
email: 'chandra.i@ritchennai.edu.in',
officeLocation: 'Tagore Block, Cabin 112',
phoneExtension: 'Ext. 502',
avatarUrl: 'https://api.dicebear.com/7.x/avataaars/svg?seed=Chandra',
isClassIncharge: true,
},
],
todaySchedule: {
dayOfWeek: 'MONDAY',
date: new Date().toISOString().split('T')[0],
periods: [
{ periodNumber: 1, timeSlot: '08:45 AM - 09:40 AM', startTime: '08:45', endTime: '09:40', subjectCode: 'MA3251', subjectName: 'Discrete Mathematics', type: 'THEORY', facultyName: 'Dr. S. Malathi', venue: 'LH-105', status: 'COMPLETED' },
{ periodNumber: 2, timeSlot: '09:40 AM - 10:35 AM', startTime: '09:40', endTime: '10:35', subjectCode: 'EC3251', subjectName: 'Circuit Analysis', type: 'THEORY', facultyName: 'Dr. I. Chandra', venue: 'LH-105', status: 'ONGOING' },
],
},
isMockData: true,
},
};
const DEFAULT_MOCK_USER_LIST: MockUserCredential[] = [
{ regNumber: '2114251001', defaultPassword: 'rit@2026', studentName: 'Anbu Kathir', department: 'Computer Science & Engineering', section: 'Sec A' },
{ regNumber: '2114251002', defaultPassword: 'rit@2026', studentName: 'Priyadharshini M', department: 'AI & Data Science', section: 'Sec B' },
{ regNumber: '2114251003', defaultPassword: 'rit@2026', studentName: 'Rahul V', department: 'Electronics & Comm. Engg.', section: 'Sec A' },
];
/**
* Log in using Register Number and Password
*/
export async function loginWithIms(regNumber: string, password: string): Promise<ImsLoginResult> {
try {
const url = getBackendUrl('/api/v1/ims/auth/login');
const response = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ regNumber, password }),
});
if (response.ok) {
const data: ImsLoginResult = await response.json();
if (data.success && data.token && data.student) {
saveImsSession(data.token, data.student);
}
return data;
}
} catch {
// Backend offline fallback
}
// Client-side fallback
const cleaned = regNumber.trim();
const mock = CLIENT_FALLBACK_MOCKS[cleaned] || CLIENT_FALLBACK_MOCKS['2114251001'];
const token = 'ims_mock_token_' + mock.student.regNumber;
saveImsSession(token, mock.student);
return {
success: true,
message: 'Mock IMS Login Successful',
token,
student: mock.student,
};
}
/**
* Fetch available demo accounts
*/
export async function fetchMockImsUsers(): Promise<MockUserCredential[]> {
try {
const url = getBackendUrl('/api/v1/ims/auth/mock-users');
const response = await fetch(url);
if (response.ok) {
return await response.json();
}
} catch {
// Fallback
}
return DEFAULT_MOCK_USER_LIST;
}
/**
* Fetch complete student dashboard information
*/
export async function fetchStudentDashboard(
regNumber?: string,
userEmail?: string,
devStudentId?: string
): Promise<StudentDashboardData> {
const session = getStoredImsSession();
const effectiveReg = devStudentId || regNumber || session?.student.regNumber;
if (!effectiveReg) {
throw new Error('No IMS session active. Please log in with your Register Number.');
}
try {
const params = new URLSearchParams();
params.set('regNumber', effectiveReg);
if (userEmail) {
params.set('email', userEmail);
}
const url = getBackendUrl(`/api/v1/ims/dashboard/me${params.toString() ? `?${params.toString()}` : ''}`);
const headers: Record<string, string> = {
'Accept': 'application/json',
};
if (session?.token) {
headers['X-IMS-Token'] = session.token;
}
if (devStudentId) {
headers['X-Dev-Student-Id'] = devStudentId;
}
const response = await fetch(url, { headers });
if (response.ok) {
return await response.json();
}
} catch {
// Fallback
}
// Client fallback mock
const fallback = CLIENT_FALLBACK_MOCKS[effectiveReg] || CLIENT_FALLBACK_MOCKS['2114251001'];
return fallback;
}

View File

@@ -179,3 +179,9 @@ export interface ApiResponse<T> {
message: string;
success: boolean;
}
declare global {
interface Window {
google?: any;
}
}