Compare commits
51 Commits
d827f4aab9
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f368c83246 | ||
|
|
db5ac8e2ea | ||
|
|
a19c36579e | ||
|
|
6be263771d | ||
|
|
9275722e16 | ||
|
|
6740400788 | ||
|
|
6d386273fb | ||
|
|
56c3849357 | ||
|
|
f58c98cd46 | ||
|
|
8c7a3d7f1a | ||
|
|
f8047b6cd3 | ||
|
|
72c213f2b6 | ||
|
|
e6ea5cb302 | ||
|
|
64f0c5d754 | ||
|
|
d9ed15b481 | ||
|
|
87865f810f | ||
|
|
906e9c757b | ||
|
|
23bf4fd86a | ||
|
|
95c97e81fa | ||
|
|
128e033a9a | ||
|
|
4e2edb7c52 | ||
|
|
bbb2cf7d30 | ||
|
|
b712b1e2f1 | ||
|
|
1641bf2110 | ||
|
|
2f69b0a29d | ||
|
|
5ea7de558b | ||
|
|
596504840e | ||
|
|
56ce10fc55 | ||
|
|
0c86c087e4 | ||
|
|
fe7ec3d61e | ||
|
|
34ea034899 | ||
|
|
a99c54c705 | ||
|
|
d028e86bdd | ||
|
|
b5b152f43c | ||
|
|
82c6444c28 | ||
|
|
f937efce5c | ||
|
|
e15c95fafd | ||
|
|
9a0c601955 | ||
|
|
774ae7e7ae | ||
|
|
9a58b2a53e | ||
|
|
a4ad5e5815 | ||
|
|
7cd28fa974 | ||
|
|
bba33ef05b | ||
|
|
5f3b3f5973 | ||
|
|
f8ca5a3368 | ||
|
|
2d91f6f5c4 | ||
|
|
154f19d546 | ||
|
|
02d8dea9a9 | ||
|
|
d3bd00e506 | ||
|
|
e83b934e9c | ||
|
|
1eebd10f3a |
222
IMS_NEXUS_INTEGRATION_GUIDE.md
Normal file
222
IMS_NEXUS_INTEGRATION_GUIDE.md
Normal 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
105
README.md
@@ -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
|
||||
```
|
||||
|
||||
1606
attendance_report.html
Normal file
1606
attendance_report.html
Normal file
File diff suppressed because it is too large
Load Diff
@@ -69,6 +69,13 @@
|
||||
<artifactId>spring-boot-starter-validation</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Jsoup HTML Parser for SkillRack profile scraping -->
|
||||
<dependency>
|
||||
<groupId>org.jsoup</groupId>
|
||||
<artifactId>jsoup</artifactId>
|
||||
<version>1.18.1</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Spring Boot Starter Test -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
|
||||
@@ -1,8 +1,22 @@
|
||||
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 org.springframework.web.client.RestTemplate;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
@@ -12,26 +26,56 @@ 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.community.username:Community}")
|
||||
private String communityUsername;
|
||||
|
||||
@Value("${admin.community.password:RIT@2026}")
|
||||
private String communityPassword;
|
||||
|
||||
@Value("${admin.clubs.username:Clubs}")
|
||||
private String clubsUsername;
|
||||
|
||||
@Value("${admin.clubs.password:RIT@2026}")
|
||||
private String clubsPassword;
|
||||
|
||||
@Value("${admin.curriculum.username:Curriculum}")
|
||||
private String curriculumUsername;
|
||||
|
||||
@Value("${admin.curriculum.password:RIT@2026}")
|
||||
private String curriculumPassword;
|
||||
|
||||
@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 +90,537 @@ public class AdminController {
|
||||
if (p != null) inputPass = p.toString().trim();
|
||||
}
|
||||
|
||||
if (ADMIN_USER.equalsIgnoreCase(inputUser) && ADMIN_PASS.equals(inputPass)) {
|
||||
boolean isStandardPass = "RIT@2026".equalsIgnoreCase(inputPass);
|
||||
|
||||
// 1. Check Transport Admin ("Transport" / "RIT@2026")
|
||||
if ((transportUsername.equalsIgnoreCase(inputUser) && (transportPassword.equals(inputPass) || isStandardPass)) ||
|
||||
"transportadmin".equalsIgnoreCase(inputUser) && isStandardPass) {
|
||||
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 fleet admin login successful");
|
||||
return ResponseEntity.ok(response);
|
||||
}
|
||||
return ResponseEntity.ok(response);
|
||||
|
||||
// 2. Check Community & Senior Q&A Admin ("Community" / "RIT@2026" or "QA")
|
||||
if ((communityUsername.equalsIgnoreCase(inputUser) && (communityPassword.equals(inputPass) || isStandardPass)) ||
|
||||
"qa".equalsIgnoreCase(inputUser) && isStandardPass ||
|
||||
"communityadmin".equalsIgnoreCase(inputUser) && isStandardPass ||
|
||||
"seniorqa".equalsIgnoreCase(inputUser) && isStandardPass) {
|
||||
response.put("success", true);
|
||||
response.put("role", "ROLE_COMMUNITY");
|
||||
response.put("username", "Community & Q&A Admin");
|
||||
response.put("token", "COMMUNITY_SESSION_TOKEN_RIT_2026");
|
||||
response.put("message", "Community & Senior Q&A admin login successful");
|
||||
return ResponseEntity.ok(response);
|
||||
}
|
||||
|
||||
// 3. Check Clubs & Centers Admin ("Clubs" / "RIT@2026" or "Club")
|
||||
if ((clubsUsername.equalsIgnoreCase(inputUser) && (clubsPassword.equals(inputPass) || isStandardPass)) ||
|
||||
"club".equalsIgnoreCase(inputUser) && isStandardPass ||
|
||||
"clubadmin".equalsIgnoreCase(inputUser) && isStandardPass ||
|
||||
"clubsadmin".equalsIgnoreCase(inputUser) && isStandardPass) {
|
||||
response.put("success", true);
|
||||
response.put("role", "ROLE_CLUBS");
|
||||
response.put("username", "Clubs & Centers Admin");
|
||||
response.put("token", "CLUBS_SESSION_TOKEN_RIT_2026");
|
||||
response.put("message", "Clubs & Centers admin login successful");
|
||||
return ResponseEntity.ok(response);
|
||||
}
|
||||
|
||||
// 4. Check GPA Curriculum Admin ("Curriculum" / "RIT@2026" or "GPA" or "Academics")
|
||||
if ((curriculumUsername.equalsIgnoreCase(inputUser) && (curriculumPassword.equals(inputPass) || isStandardPass)) ||
|
||||
"gpa".equalsIgnoreCase(inputUser) && isStandardPass ||
|
||||
"gpaadmin".equalsIgnoreCase(inputUser) && isStandardPass ||
|
||||
"academics".equalsIgnoreCase(inputUser) && isStandardPass ||
|
||||
"curriculumadmin".equalsIgnoreCase(inputUser) && isStandardPass) {
|
||||
response.put("success", true);
|
||||
response.put("role", "ROLE_CURRICULUM");
|
||||
response.put("username", "GPA Curriculum Admin");
|
||||
response.put("token", "CURRICULUM_SESSION_TOKEN_RIT_2026");
|
||||
response.put("message", "GPA Curriculum admin login successful");
|
||||
return ResponseEntity.ok(response);
|
||||
}
|
||||
|
||||
// 5. Check Super Admin ("Admin" / "RIT@2026" or "ritadmin" / "ritadmin2026" or "superadmin")
|
||||
if ((superAdminUsername.equalsIgnoreCase(inputUser) && (superAdminPassword.equals(inputPass) || isStandardPass)) ||
|
||||
"superadmin".equalsIgnoreCase(inputUser) && isStandardPass ||
|
||||
("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', 'Community', 'Clubs', 'Curriculum', 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);
|
||||
Map<String, Object> loaded = objectMapper.readValue(bytes, Map.class);
|
||||
if (loaded != null) {
|
||||
List<Object> rawChatIds = (List<Object>) loaded.get("helper_chat_ids");
|
||||
List<Map<String, Object>> helpers = (List<Map<String, Object>>) loaded.get("seniorHelpers");
|
||||
|
||||
if (helpers == null && rawChatIds != null) {
|
||||
helpers = new ArrayList<>();
|
||||
for (Object id : rawChatIds) {
|
||||
Map<String, Object> h = new HashMap<>();
|
||||
h.put("chatId", Long.parseLong(id.toString()));
|
||||
h.put("name", "Senior Responder");
|
||||
helpers.add(h);
|
||||
}
|
||||
loaded.put("seniorHelpers", helpers);
|
||||
} else if (helpers != null && rawChatIds == null) {
|
||||
List<Long> ids = new ArrayList<>();
|
||||
for (Map<String, Object> h : helpers) {
|
||||
if (h.get("chatId") != null) {
|
||||
try {
|
||||
ids.add(Long.parseLong(h.get("chatId").toString()));
|
||||
} catch (Exception ignored) {}
|
||||
}
|
||||
}
|
||||
loaded.put("helper_chat_ids", ids);
|
||||
}
|
||||
return loaded;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
Map<String, Object> defaultCfg = new HashMap<>();
|
||||
defaultCfg.put("community_bot_token", "8973721012:AAG37F4Q4q584m_2aS8rT6qSWuA-WuHRGMY");
|
||||
defaultCfg.put("telegram_bot_token", "8973721012:AAG37F4Q4q584m_2aS8rT6qSWuA-WuHRGMY");
|
||||
defaultCfg.put("helper_chat_ids", new ArrayList<Long>(List.of(1873240361L, 5567776672L, 8518850169L, 7238144438L)));
|
||||
List<Map<String, Object>> defaultHelpers = new ArrayList<>();
|
||||
defaultHelpers.add(Map.of("chatId", 1873240361L, "name", "Senior Mentor (CSE)"));
|
||||
defaultHelpers.add(Map.of("chatId", 5567776672L, "name", "Senior Responder (ECE)"));
|
||||
defaultHelpers.add(Map.of("chatId", 8518850169L, "name", "Senior Responder (IT)"));
|
||||
defaultHelpers.add(Map.of("chatId", 7238144438L, "name", "Senior Responder (AIDS)"));
|
||||
defaultCfg.put("seniorHelpers", defaultHelpers);
|
||||
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"));
|
||||
if (payload.containsKey("bot_username")) current.put("bot_username", payload.get("bot_username"));
|
||||
if (payload.containsKey("seniorHelpers")) {
|
||||
@SuppressWarnings("unchecked")
|
||||
List<Map<String, Object>> helpers = (List<Map<String, Object>>) payload.get("seniorHelpers");
|
||||
current.put("seniorHelpers", helpers);
|
||||
List<Long> ids = new ArrayList<>();
|
||||
if (helpers != null) {
|
||||
for (Map<String, Object> h : helpers) {
|
||||
if (h.get("chatId") != null) {
|
||||
try {
|
||||
ids.add(Long.parseLong(h.get("chatId").toString()));
|
||||
} catch (Exception ignored) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
current.put("helper_chat_ids", ids);
|
||||
} else if (payload.containsKey("helper_chat_ids")) {
|
||||
current.put("helper_chat_ids", payload.get("helper_chat_ids"));
|
||||
}
|
||||
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");
|
||||
String nameStr = payload.get("name") != null ? payload.get("name").toString().trim() : "Senior Responder";
|
||||
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<Map<String, Object>> helpers = (List<Map<String, Object>>) config.getOrDefault("seniorHelpers", new ArrayList<>());
|
||||
if (helpers == null) helpers = new ArrayList<>();
|
||||
List<Long> helperIds = new ArrayList<>();
|
||||
|
||||
boolean found = false;
|
||||
for (Map<String, Object> h : helpers) {
|
||||
if (h.get("chatId") != null) {
|
||||
Long cId = Long.parseLong(h.get("chatId").toString());
|
||||
helperIds.add(cId);
|
||||
if (cId.equals(chatId)) {
|
||||
h.put("name", nameStr);
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!found) {
|
||||
Map<String, Object> newHelper = new HashMap<>();
|
||||
newHelper.put("chatId", chatId);
|
||||
newHelper.put("name", nameStr);
|
||||
helpers.add(newHelper);
|
||||
helperIds.add(chatId);
|
||||
}
|
||||
|
||||
config.put("seniorHelpers", helpers);
|
||||
config.put("helper_chat_ids", helperIds);
|
||||
saveTelegramConfigFile(config);
|
||||
|
||||
return ResponseEntity.ok(Map.of("success", true, "helpers", helpers, "helper_chat_ids", helperIds));
|
||||
}
|
||||
|
||||
@DeleteMapping("/telegram/helpers/{chatId}")
|
||||
public ResponseEntity<?> removeSeniorHelper(@PathVariable Long chatId) {
|
||||
Map<String, Object> config = readTelegramConfigFile();
|
||||
@SuppressWarnings("unchecked")
|
||||
List<Map<String, Object>> helpers = (List<Map<String, Object>>) config.getOrDefault("seniorHelpers", new ArrayList<>());
|
||||
if (helpers != null) {
|
||||
helpers.removeIf(h -> h.get("chatId") != null && Long.parseLong(h.get("chatId").toString()) == chatId);
|
||||
} else {
|
||||
helpers = new ArrayList<>();
|
||||
}
|
||||
|
||||
List<Long> helperIds = new ArrayList<>();
|
||||
for (Map<String, Object> h : helpers) {
|
||||
if (h.get("chatId") != null) {
|
||||
try {
|
||||
helperIds.add(Long.parseLong(h.get("chatId").toString()));
|
||||
} catch (Exception ignored) {}
|
||||
}
|
||||
}
|
||||
|
||||
config.put("seniorHelpers", helpers);
|
||||
config.put("helper_chat_ids", helperIds);
|
||||
saveTelegramConfigFile(config);
|
||||
|
||||
return ResponseEntity.ok(Map.of("success", true, "helpers", helpers, "helper_chat_ids", helperIds));
|
||||
}
|
||||
|
||||
@PostMapping("/telegram/test-bot")
|
||||
public ResponseEntity<?> testTelegramBot(@RequestBody Map<String, Object> payload) {
|
||||
String token = (String) payload.get("token");
|
||||
if (token == null || token.trim().isEmpty()) {
|
||||
Map<String, Object> cfg = readTelegramConfigFile();
|
||||
token = (String) cfg.getOrDefault("community_bot_token", "");
|
||||
}
|
||||
if (token == null || token.trim().isEmpty()) {
|
||||
return ResponseEntity.badRequest().body(Map.of("ok", false, "description", "Bot token is required"));
|
||||
}
|
||||
try {
|
||||
RestTemplate restTemplate = new RestTemplate();
|
||||
String url = "https://api.telegram.org/bot" + token.trim() + "/getMe";
|
||||
ResponseEntity<Map> response = restTemplate.getForEntity(url, Map.class);
|
||||
return ResponseEntity.ok(response.getBody());
|
||||
} catch (Exception e) {
|
||||
return ResponseEntity.ok(Map.of("ok", false, "description", e.getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
@PostMapping("/telegram/test-dispatch")
|
||||
public ResponseEntity<?> testTelegramDispatch(@RequestBody Map<String, Object> payload) {
|
||||
String token = (String) payload.get("token");
|
||||
Object chatIdObj = payload.get("chatId");
|
||||
String message = (String) payload.get("message");
|
||||
if (token == null || token.trim().isEmpty()) {
|
||||
Map<String, Object> cfg = readTelegramConfigFile();
|
||||
token = (String) cfg.getOrDefault("community_bot_token", "");
|
||||
}
|
||||
if (token == null || token.trim().isEmpty() || chatIdObj == null) {
|
||||
return ResponseEntity.badRequest().body(Map.of("ok", false, "description", "Bot token and chatId are required"));
|
||||
}
|
||||
if (message == null || message.trim().isEmpty()) {
|
||||
message = "🔔 *RIT Nexus Admin Test Ping*\n\nThis is a verified test notification confirming your Telegram Chat ID is active and connected to the Q&A dispatch system!";
|
||||
}
|
||||
try {
|
||||
RestTemplate restTemplate = new RestTemplate();
|
||||
String url = "https://api.telegram.org/bot" + token.trim() + "/sendMessage";
|
||||
Map<String, Object> body = new HashMap<>();
|
||||
body.put("chat_id", chatIdObj);
|
||||
body.put("text", message);
|
||||
body.put("parse_mode", "Markdown");
|
||||
ResponseEntity<Map> response = restTemplate.postForEntity(url, body, Map.class);
|
||||
return ResponseEntity.ok(response.getBody());
|
||||
} catch (Exception e) {
|
||||
return ResponseEntity.ok(Map.of("ok", false, "description", e.getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
@PostMapping("/telegram/test-broadcast")
|
||||
public ResponseEntity<?> testTelegramBroadcast(@RequestBody Map<String, Object> payload) {
|
||||
Map<String, Object> cfg = readTelegramConfigFile();
|
||||
String token = (String) payload.getOrDefault("token", cfg.get("community_bot_token"));
|
||||
String message = (String) payload.getOrDefault("message", "📢 *RIT Nexus Q&A Dispatch Network Test*\n\nAll senior responders are currently being pinged to verify real-time dispatch connectivity.");
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
List<Object> rawHelpers = (List<Object>) cfg.getOrDefault("helper_chat_ids", new ArrayList<>());
|
||||
int delivered = 0;
|
||||
List<Map<String, Object>> results = new ArrayList<>();
|
||||
RestTemplate restTemplate = new RestTemplate();
|
||||
|
||||
if (token != null && !token.trim().isEmpty() && rawHelpers != null) {
|
||||
for (Object idObj : rawHelpers) {
|
||||
try {
|
||||
String url = "https://api.telegram.org/bot" + token.trim() + "/sendMessage";
|
||||
Map<String, Object> body = new HashMap<>();
|
||||
body.put("chat_id", idObj);
|
||||
body.put("text", message);
|
||||
body.put("parse_mode", "Markdown");
|
||||
ResponseEntity<Map> res = restTemplate.postForEntity(url, body, Map.class);
|
||||
results.add(Map.of("chatId", idObj, "status", "success", "response", res.getBody()));
|
||||
delivered++;
|
||||
} catch (Exception e) {
|
||||
results.add(Map.of("chatId", idObj, "status", "failed", "error", e.getMessage()));
|
||||
}
|
||||
}
|
||||
}
|
||||
return ResponseEntity.ok(Map.of("success", true, "delivered", delivered, "total", rawHelpers != null ? rawHelpers.size() : 0, "details", results));
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────
|
||||
// 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")
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.rit.portal.controller;
|
||||
|
||||
import com.rit.portal.entity.SkillrackProfile;
|
||||
import com.rit.portal.service.SkillrackService;
|
||||
import lombok.Data;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/skillrack")
|
||||
@CrossOrigin(originPatterns = "*")
|
||||
@RequiredArgsConstructor
|
||||
public class SkillrackController {
|
||||
|
||||
private final SkillrackService skillrackService;
|
||||
|
||||
@GetMapping("/leaderboard")
|
||||
public List<SkillrackProfile> getLeaderboard() {
|
||||
return skillrackService.getAllRankedProfiles();
|
||||
}
|
||||
|
||||
@PostMapping("/register")
|
||||
public ResponseEntity<?> registerProfile(@RequestBody RegisterRequest request) {
|
||||
if (request.getSkillrackEmail() == null || request.getSkillrackEmail().trim().isEmpty()) {
|
||||
return ResponseEntity.badRequest().body(Map.of("error", "SkillRack email is required"));
|
||||
}
|
||||
if (request.getSkillrackPassword() == null || request.getSkillrackPassword().trim().isEmpty()) {
|
||||
return ResponseEntity.badRequest().body(Map.of("error", "SkillRack password is required"));
|
||||
}
|
||||
if (request.getStudentName() == null || request.getStudentName().trim().isEmpty()) {
|
||||
return ResponseEntity.badRequest().body(Map.of("error", "Student name is required"));
|
||||
}
|
||||
|
||||
try {
|
||||
SkillrackProfile profile = skillrackService.registerOrUpdateStudent(
|
||||
request.getStudentName(),
|
||||
request.getSkillrackEmail(),
|
||||
request.getSkillrackPassword(),
|
||||
request.getDepartment() != null ? request.getDepartment() : "CSE",
|
||||
request.getYear() != null ? request.getYear() : "1st Year"
|
||||
);
|
||||
return ResponseEntity.ok(profile);
|
||||
} catch (IllegalArgumentException e) {
|
||||
return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
|
||||
} catch (Exception e) {
|
||||
return ResponseEntity.internalServerError().body(Map.of("error", "Failed to register profile: " + e.getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
@PostMapping("/sync")
|
||||
public ResponseEntity<?> triggerSync() {
|
||||
skillrackService.syncAllProfilesWithSpacing();
|
||||
return ResponseEntity.ok(Map.of("message", "SkillRack background sync initiated with 5-second spacing."));
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class RegisterRequest {
|
||||
private String studentName;
|
||||
private String skillrackEmail;
|
||||
private String skillrackPassword;
|
||||
private String department;
|
||||
private String year;
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
31
backend/src/main/java/com/rit/portal/entity/ClubLike.java
Normal file
31
backend/src/main/java/com/rit/portal/entity/ClubLike.java
Normal 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();
|
||||
}
|
||||
@@ -30,11 +30,14 @@ public class CommunityAnswer {
|
||||
private String author;
|
||||
|
||||
@Column(name = "upvotes")
|
||||
@Builder.Default
|
||||
private Integer upvotes = 0;
|
||||
|
||||
@Column(name = "is_accepted")
|
||||
@Builder.Default
|
||||
private Boolean isAccepted = false;
|
||||
|
||||
@Column(name = "created_at")
|
||||
@Builder.Default
|
||||
private LocalDateTime createdAt = LocalDateTime.now();
|
||||
}
|
||||
|
||||
@@ -29,15 +29,19 @@ public class CommunityQuestion {
|
||||
private String author;
|
||||
|
||||
@Column(name = "upvotes")
|
||||
@Builder.Default
|
||||
private Integer upvotes = 0;
|
||||
|
||||
@Column(name = "tags", columnDefinition = "text[]")
|
||||
@Builder.Default
|
||||
private List<String> tags = new ArrayList<>();
|
||||
|
||||
@Column(name = "is_answered")
|
||||
@Builder.Default
|
||||
private Boolean isAnswered = false;
|
||||
|
||||
@Column(name = "created_at")
|
||||
@Builder.Default
|
||||
private LocalDateTime createdAt = LocalDateTime.now();
|
||||
|
||||
@OneToMany(mappedBy = "question", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
|
||||
|
||||
@@ -39,8 +39,10 @@ public class NotePyq {
|
||||
private String fileSize;
|
||||
|
||||
@Column(name = "downloads_count")
|
||||
@Builder.Default
|
||||
private Integer downloadsCount = 0;
|
||||
|
||||
@Column(name = "uploaded_at")
|
||||
@Builder.Default
|
||||
private LocalDateTime uploadedAt = LocalDateTime.now();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
package com.rit.portal.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Entity
|
||||
@Table(name = "skillrack_profiles")
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Builder
|
||||
public class SkillrackProfile {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Integer id;
|
||||
|
||||
@Column(name = "student_name", nullable = false)
|
||||
private String studentName;
|
||||
|
||||
@Column(name = "skillrack_email", nullable = false, unique = true)
|
||||
private String skillrackEmail;
|
||||
|
||||
@Column(name = "encrypted_password", nullable = false, length = 512)
|
||||
private String encryptedPassword;
|
||||
|
||||
@Column(nullable = false)
|
||||
private String department;
|
||||
|
||||
@Column(nullable = false)
|
||||
private String year;
|
||||
|
||||
@Column(name = "total_points")
|
||||
@Builder.Default
|
||||
private Integer totalPoints = 0;
|
||||
|
||||
@Column(name = "code_test_solved")
|
||||
@Builder.Default
|
||||
private Integer codeTestSolved = 0;
|
||||
|
||||
@Column(name = "code_tutor_solved")
|
||||
@Builder.Default
|
||||
private Integer codeTutorSolved = 0;
|
||||
|
||||
@Column(name = "code_track_solved")
|
||||
@Builder.Default
|
||||
private Integer codeTrackSolved = 0;
|
||||
|
||||
@Column(name = "dc_solved")
|
||||
@Builder.Default
|
||||
private Integer dcSolved = 0;
|
||||
|
||||
@Column(name = "gold_medals")
|
||||
@Builder.Default
|
||||
private Integer goldMedals = 0;
|
||||
|
||||
@Column(name = "silver_medals")
|
||||
@Builder.Default
|
||||
private Integer silverMedals = 0;
|
||||
|
||||
@Column(name = "bronze_medals")
|
||||
@Builder.Default
|
||||
private Integer bronzeMedals = 0;
|
||||
|
||||
@Column(name = "last_updated")
|
||||
private LocalDateTime lastUpdated;
|
||||
|
||||
@Column(name = "created_at")
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
@PrePersist
|
||||
protected void onCreate() {
|
||||
if (createdAt == null) createdAt = LocalDateTime.now();
|
||||
if (lastUpdated == null) lastUpdated = LocalDateTime.now();
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.rit.portal.repository;
|
||||
|
||||
import com.rit.portal.entity.SkillrackProfile;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public interface SkillrackProfileRepository extends JpaRepository<SkillrackProfile, Integer> {
|
||||
Optional<SkillrackProfile> findBySkillrackEmailIgnoreCase(String skillrackEmail);
|
||||
List<SkillrackProfile> findAllByOrderByTotalPointsDesc();
|
||||
boolean existsBySkillrackEmailIgnoreCase(String skillrackEmail);
|
||||
}
|
||||
@@ -45,8 +45,17 @@ public class BusLocationService {
|
||||
|
||||
public List<BusLocation> getActiveLocations() {
|
||||
Instant threshold = Instant.now().minus(STALE_DURATION);
|
||||
// Clean up stale entries on read
|
||||
return locationCache.values().stream()
|
||||
.filter(loc -> !loc.getLastUpdated().isBefore(threshold))
|
||||
.toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* Periodic background eviction of stale GPS coordinates every 5 minutes
|
||||
*/
|
||||
@org.springframework.scheduling.annotation.Scheduled(fixedRate = 300000)
|
||||
public void evictStaleLocations() {
|
||||
Instant threshold = Instant.now().minus(STALE_DURATION);
|
||||
locationCache.entrySet().removeIf(entry -> entry.getValue().getLastUpdated().isBefore(threshold));
|
||||
return List.copyOf(locationCache.values());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,330 @@
|
||||
package com.rit.portal.service;
|
||||
|
||||
import com.rit.portal.entity.SkillrackProfile;
|
||||
import com.rit.portal.repository.SkillrackProfileRepository;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.jsoup.Connection;
|
||||
import org.jsoup.Jsoup;
|
||||
import org.jsoup.nodes.Document;
|
||||
import org.jsoup.nodes.Element;
|
||||
import org.jsoup.select.Elements;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.*;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class SkillrackService {
|
||||
|
||||
private final SkillrackProfileRepository repository;
|
||||
|
||||
// AES-128 key (16 bytes) — in production, move to environment variable
|
||||
private static final String AES_KEY = "RitSkillR@ck2026";
|
||||
private static final String SKILLRACK_BASE = "https://www.skillrack.com";
|
||||
private static final String LOGIN_URL = SKILLRACK_BASE + "/faces/ui/profile.xhtml";
|
||||
private static final String PROFILE_URL = SKILLRACK_BASE + "/faces/candidate/manageprofile.xhtml";
|
||||
|
||||
// ─── Public API ───────────────────────────────────────────────────
|
||||
|
||||
public List<SkillrackProfile> getAllRankedProfiles() {
|
||||
return repository.findAllByOrderByTotalPointsDesc();
|
||||
}
|
||||
|
||||
public SkillrackProfile registerOrUpdateStudent(String studentName, String email, String password,
|
||||
String department, String year) {
|
||||
String cleanEmail = email.trim().toLowerCase();
|
||||
|
||||
SkillrackProfile profile = repository.findBySkillrackEmailIgnoreCase(cleanEmail)
|
||||
.orElse(SkillrackProfile.builder()
|
||||
.studentName(studentName.trim())
|
||||
.skillrackEmail(cleanEmail)
|
||||
.department(department.trim())
|
||||
.year(year.trim())
|
||||
.build());
|
||||
|
||||
profile.setStudentName(studentName.trim());
|
||||
profile.setDepartment(department.trim());
|
||||
profile.setYear(year.trim());
|
||||
profile.setEncryptedPassword(encrypt(password));
|
||||
|
||||
boolean success = fetchAndUpdateProfile(profile, password);
|
||||
if (!success) {
|
||||
throw new IllegalArgumentException(
|
||||
"Could not authenticate with SkillRack using '" + cleanEmail +
|
||||
"'. Please verify your email and password are correct.");
|
||||
}
|
||||
return repository.save(profile);
|
||||
}
|
||||
|
||||
public boolean fetchAndUpdateProfile(SkillrackProfile profile) {
|
||||
String password = decrypt(profile.getEncryptedPassword());
|
||||
if (password == null || password.isEmpty()) {
|
||||
log.warn("Cannot decrypt password for SkillRack profile: {}", profile.getSkillrackEmail());
|
||||
return false;
|
||||
}
|
||||
return fetchAndUpdateProfile(profile, password);
|
||||
}
|
||||
|
||||
/**
|
||||
* Core scraping method using SkillRack's container security:
|
||||
* 1. GET https://www.skillrack.com/faces/ui/profile.xhtml to establish JSESSIONID session
|
||||
* 2. POST to https://www.skillrack.com/faces/ui/j_security_check with j_username (Login ID) & j_password
|
||||
* 3. GET https://www.skillrack.com/faces/candidate/profileview.xhtml with authenticated session & parse HTML
|
||||
*/
|
||||
public boolean fetchAndUpdateProfile(SkillrackProfile profile, String rawPassword) {
|
||||
try {
|
||||
log.info("Fetching SkillRack stats for Login ID: {}", profile.getSkillrackEmail());
|
||||
|
||||
String loginPageUrl = SKILLRACK_BASE + "/faces/ui/profile.xhtml";
|
||||
String jSecurityCheckUrl = SKILLRACK_BASE + "/faces/ui/j_security_check";
|
||||
|
||||
// Step 1: GET login page to establish session cookie
|
||||
Connection.Response pageRes = Jsoup.connect(loginPageUrl)
|
||||
.method(Connection.Method.GET)
|
||||
.userAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36")
|
||||
.timeout(15000)
|
||||
.execute();
|
||||
|
||||
Map<String, String> cookies = new HashMap<>(pageRes.cookies());
|
||||
|
||||
// Step 2: POST login credentials to j_security_check
|
||||
Map<String, String> formData = new LinkedHashMap<>();
|
||||
formData.put("j_username", profile.getSkillrackEmail().trim());
|
||||
formData.put("j_password", rawPassword);
|
||||
|
||||
Connection.Response loginRes = Jsoup.connect(jSecurityCheckUrl)
|
||||
.method(Connection.Method.POST)
|
||||
.cookies(cookies)
|
||||
.data(formData)
|
||||
.userAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36")
|
||||
.header("Content-Type", "application/x-www-form-urlencoded")
|
||||
.header("Referer", loginPageUrl)
|
||||
.followRedirects(true)
|
||||
.timeout(15000)
|
||||
.execute();
|
||||
|
||||
cookies.putAll(loginRes.cookies());
|
||||
|
||||
// Step 3: Fetch candidate profile page with authenticated session
|
||||
Connection.Response profileRes = Jsoup.connect(PROFILE_URL)
|
||||
.method(Connection.Method.GET)
|
||||
.cookies(cookies)
|
||||
.userAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36")
|
||||
.followRedirects(true)
|
||||
.timeout(15000)
|
||||
.execute();
|
||||
|
||||
cookies.putAll(profileRes.cookies());
|
||||
Document profileDoc = profileRes.parse();
|
||||
String bodyText = profileDoc.body().text();
|
||||
|
||||
// Check if login failed (still on login page containing j_security_check form)
|
||||
if (bodyText.contains("j_security_check") || bodyText.contains("Invalid User ID")) {
|
||||
log.warn("SkillRack authentication failed for: {}", profile.getSkillrackEmail());
|
||||
return false;
|
||||
}
|
||||
|
||||
// Step 4: Parse profile stats from the HTML
|
||||
boolean parsed = parseProfileStats(profileDoc, profile);
|
||||
|
||||
if (!parsed) {
|
||||
// Fallback: Try to extract from raw text with regex patterns
|
||||
parsed = parseFromRawText(bodyText, profile);
|
||||
}
|
||||
|
||||
if (parsed) {
|
||||
profile.setLastUpdated(LocalDateTime.now());
|
||||
log.info("Successfully scraped SkillRack for {}: Points={}, CT={}, Tutor={}, Track={}, DC={}, Gold={}, Silver={}, Bronze={}",
|
||||
profile.getSkillrackEmail(), profile.getTotalPoints(),
|
||||
profile.getCodeTestSolved(), profile.getCodeTutorSolved(),
|
||||
profile.getCodeTrackSolved(), profile.getDcSolved(),
|
||||
profile.getGoldMedals(), profile.getSilverMedals(), profile.getBronzeMedals());
|
||||
return true;
|
||||
}
|
||||
|
||||
log.warn("Could not parse SkillRack profile data for: {}", profile.getSkillrackEmail());
|
||||
return false;
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to fetch SkillRack data for {}: {}", profile.getSkillrackEmail(), e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// ─── HTML Parsing ─────────────────────────────────────────────────
|
||||
|
||||
private boolean parseProfileStats(Document doc, SkillrackProfile profile) {
|
||||
String html = doc.html();
|
||||
boolean foundAnything = false;
|
||||
|
||||
// 1. Extract Real Name from .ui-chip-text if available
|
||||
Element chipEl = doc.selectFirst(".ui-chip-text");
|
||||
if (chipEl != null) {
|
||||
String chipText = chipEl.text().trim();
|
||||
if (chipText.contains("-")) {
|
||||
String[] parts = chipText.split("-");
|
||||
if (parts.length >= 1 && !parts[0].trim().isEmpty()) {
|
||||
profile.setStudentName(parts[0].trim());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Gold Medals (orange medal icon)
|
||||
Matcher goldM = Pattern.compile("ion-md-medal\"\\s+style=\"color:orange\"></i>\\s*(\\d+)").matcher(html);
|
||||
if (goldM.find()) {
|
||||
profile.setGoldMedals(Integer.parseInt(goldM.group(1)));
|
||||
foundAnything = true;
|
||||
}
|
||||
|
||||
// 3. Silver Medals (grey medal icon)
|
||||
Matcher silverM = Pattern.compile("ion-md-medal\"\\s+style=\"color:grey\"></i>\\s*(\\d+)").matcher(html);
|
||||
if (silverM.find()) {
|
||||
profile.setSilverMedals(Integer.parseInt(silverM.group(1)));
|
||||
foundAnything = true;
|
||||
}
|
||||
|
||||
// 4. Bronze Medals (brown medal icon)
|
||||
Matcher bronzeM = Pattern.compile("ion-md-medal\"\\s+style=\"color:brown\"></i>\\s*(\\d+)").matcher(html);
|
||||
if (bronzeM.find()) {
|
||||
profile.setBronzeMedals(Integer.parseInt(bronzeM.group(1)));
|
||||
foundAnything = true;
|
||||
}
|
||||
|
||||
// 5. Total Points / Score (brown flag icon)
|
||||
Matcher pointsM = Pattern.compile("ion-md-flag\"\\s+style=\"color:brown\"></i>\\s*(\\d+)").matcher(html);
|
||||
if (pointsM.find()) {
|
||||
profile.setTotalPoints(Integer.parseInt(pointsM.group(1)));
|
||||
foundAnything = true;
|
||||
}
|
||||
|
||||
return foundAnything;
|
||||
}
|
||||
|
||||
private boolean parseFromRawText(String text, SkillrackProfile profile) {
|
||||
boolean found = false;
|
||||
|
||||
// Pattern: "Code Test 123" or "CodeTest: 123" or "Code Test Solved: 123"
|
||||
found |= extractAndSet(text, "(?i)code\\s*test[^\\d]*(\\d+)", val -> profile.setCodeTestSolved(val));
|
||||
found |= extractAndSet(text, "(?i)code\\s*tutor[^\\d]*(\\d+)", val -> profile.setCodeTutorSolved(val));
|
||||
found |= extractAndSet(text, "(?i)code\\s*track[^\\d]*(\\d+)", val -> profile.setCodeTrackSolved(val));
|
||||
found |= extractAndSet(text, "(?i)daily\\s*challenge[^\\d]*(\\d+)", val -> profile.setDcSolved(val));
|
||||
found |= extractAndSet(text, "(?i)(?:dc|DC)[^\\d]*(\\d+)", val -> {
|
||||
if (profile.getDcSolved() == 0) profile.setDcSolved(val);
|
||||
});
|
||||
found |= extractAndSet(text, "(?i)gold[^\\d]*(\\d+)", val -> profile.setGoldMedals(val));
|
||||
found |= extractAndSet(text, "(?i)silver[^\\d]*(\\d+)", val -> profile.setSilverMedals(val));
|
||||
found |= extractAndSet(text, "(?i)bronze[^\\d]*(\\d+)", val -> profile.setBronzeMedals(val));
|
||||
found |= extractAndSet(text, "(?i)total\\s*(?:point|score)s?[^\\d]*(\\d+)", val -> profile.setTotalPoints(val));
|
||||
|
||||
// If total points not found, compute from components
|
||||
if (profile.getTotalPoints() == 0 && found) {
|
||||
int computed = profile.getCodeTestSolved() + profile.getCodeTutorSolved()
|
||||
+ profile.getCodeTrackSolved() + profile.getDcSolved();
|
||||
if (computed > 0) {
|
||||
profile.setTotalPoints(computed);
|
||||
}
|
||||
}
|
||||
|
||||
return found;
|
||||
}
|
||||
|
||||
private boolean extractAndSet(String text, String regex, java.util.function.IntConsumer setter) {
|
||||
Matcher m = Pattern.compile(regex).matcher(text);
|
||||
if (m.find()) {
|
||||
int val = parseIntSafe(m.group(1));
|
||||
if (val > 0) {
|
||||
setter.accept(val);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private int parseIntSafe(String s) {
|
||||
try {
|
||||
return Integer.parseInt(s.replaceAll("[^\\d]", ""));
|
||||
} catch (NumberFormatException e) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
// ─── AES Encryption Helpers ───────────────────────────────────────
|
||||
|
||||
private String encrypt(String plainText) {
|
||||
try {
|
||||
SecretKeySpec key = new SecretKeySpec(AES_KEY.getBytes(StandardCharsets.UTF_8), "AES");
|
||||
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
|
||||
cipher.init(Cipher.ENCRYPT_MODE, key);
|
||||
byte[] encrypted = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
|
||||
return Base64.getEncoder().encodeToString(encrypted);
|
||||
} catch (Exception e) {
|
||||
log.error("AES encryption failed: {}", e.getMessage());
|
||||
throw new RuntimeException("Encryption failed", e);
|
||||
}
|
||||
}
|
||||
|
||||
private String decrypt(String encryptedBase64) {
|
||||
try {
|
||||
SecretKeySpec key = new SecretKeySpec(AES_KEY.getBytes(StandardCharsets.UTF_8), "AES");
|
||||
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
|
||||
cipher.init(Cipher.DECRYPT_MODE, key);
|
||||
byte[] decoded = Base64.getDecoder().decode(encryptedBase64);
|
||||
byte[] decrypted = cipher.doFinal(decoded);
|
||||
return new String(decrypted, StandardCharsets.UTF_8);
|
||||
} catch (Exception e) {
|
||||
log.error("AES decryption failed: {}", e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Scheduled & Manual Sync ──────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Automatic daily sync at 2:30 AM — spaced 5s apart to avoid rate limits
|
||||
*/
|
||||
@Scheduled(cron = "0 30 2 * * ?")
|
||||
public void scheduledDailySync() {
|
||||
log.info("Starting scheduled daily SkillRack sync...");
|
||||
syncAllProfilesWithSpacing();
|
||||
}
|
||||
|
||||
/**
|
||||
* Manual or scheduled trigger to sync all profiles with 5-second delays.
|
||||
*/
|
||||
public void syncAllProfilesWithSpacing() {
|
||||
List<SkillrackProfile> profiles = repository.findAll();
|
||||
log.info("Queued {} SkillRack profiles for sync.", profiles.size());
|
||||
|
||||
new Thread(() -> {
|
||||
for (int i = 0; i < profiles.size(); i++) {
|
||||
SkillrackProfile p = profiles.get(i);
|
||||
try {
|
||||
boolean success = fetchAndUpdateProfile(p);
|
||||
if (success) {
|
||||
repository.save(p);
|
||||
}
|
||||
if (i < profiles.size() - 1) {
|
||||
log.info("Waiting 5s before next SkillRack profile sync...");
|
||||
Thread.sleep(5000);
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
log.error("SkillRack sync interrupted.");
|
||||
break;
|
||||
} catch (Exception e) {
|
||||
log.error("Error syncing SkillRack profile {}: {}", p.getSkillrackEmail(), e.getMessage());
|
||||
}
|
||||
}
|
||||
log.info("Finished SkillRack sync for all profiles.");
|
||||
}).start();
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -1,20 +1,40 @@
|
||||
# ─── 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@.}
|
||||
|
||||
# ─── HIKARICP CONNECTION POOL OPTIMIZATIONS ───
|
||||
spring.datasource.hikari.maximum-pool-size=30
|
||||
spring.datasource.hikari.minimum-idle=10
|
||||
spring.datasource.hikari.idle-timeout=300000
|
||||
spring.datasource.hikari.max-lifetime=1200000
|
||||
spring.datasource.hikari.connection-timeout=20000
|
||||
|
||||
# ─── JPA / HIBERNATE SETTINGS ───
|
||||
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
|
||||
spring.jpa.hibernate.ddl-auto=update
|
||||
spring.jpa.show-sql=true
|
||||
spring.jpa.properties.hibernate.format_sql=true
|
||||
spring.jpa.show-sql=false
|
||||
spring.jpa.properties.hibernate.format_sql=false
|
||||
|
||||
# ─── SERVER PORT ───
|
||||
# ─── SERVER PORT & HTTP GZIP COMPRESSION ───
|
||||
server.port=8085
|
||||
server.compression.enabled=true
|
||||
server.compression.mime-types=application/json,application/xml,text/html,text/xml,text/plain,application/javascript,text/css
|
||||
server.compression.min-response-size=1024
|
||||
|
||||
# ─── 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}
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.rit.portal;
|
||||
|
||||
import com.rit.portal.model.BusLocation;
|
||||
import com.rit.portal.service.BusLocationService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
public class BusLocationServiceTest {
|
||||
|
||||
private BusLocationService busLocationService;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
busLocationService = new BusLocationService();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUpdateAndGetLocation() {
|
||||
busLocationService.updateLocation("24A", 13.0827, 80.2707);
|
||||
|
||||
BusLocation loc = busLocationService.getLocation("24A");
|
||||
assertNotNull(loc);
|
||||
assertEquals("24A", loc.getRouteNumber());
|
||||
assertEquals(13.0827, loc.getLatitude());
|
||||
assertEquals(80.2707, loc.getLongitude());
|
||||
assertFalse(loc.isStopped());
|
||||
assertNotNull(loc.getLastUpdated());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testStopLocation() {
|
||||
busLocationService.updateLocation("15B", 12.9716, 77.5946);
|
||||
busLocationService.stopLocation("15B");
|
||||
|
||||
BusLocation loc = busLocationService.getLocation("15B");
|
||||
assertNotNull(loc);
|
||||
assertTrue(loc.isStopped());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetNonExistentLocationReturnsNull() {
|
||||
BusLocation loc = busLocationService.getLocation("NON_EXISTENT");
|
||||
assertNull(loc);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetActiveLocations() {
|
||||
busLocationService.updateLocation("R1", 13.0, 80.0);
|
||||
busLocationService.updateLocation("R2", 13.1, 80.1);
|
||||
|
||||
List<BusLocation> active = busLocationService.getActiveLocations();
|
||||
assertEquals(2, active.size());
|
||||
}
|
||||
}
|
||||
60
backend/src/test/java/com/rit/portal/EntityMappingTest.java
Normal file
60
backend/src/test/java/com/rit/portal/EntityMappingTest.java
Normal file
@@ -0,0 +1,60 @@
|
||||
package com.rit.portal;
|
||||
|
||||
import com.rit.portal.entity.CommunityAnswer;
|
||||
import com.rit.portal.entity.CommunityQuestion;
|
||||
import com.rit.portal.entity.NotePyq;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
public class EntityMappingTest {
|
||||
|
||||
@Test
|
||||
void testNotePyqBuilderDefaults() {
|
||||
NotePyq note = NotePyq.builder()
|
||||
.title("Data Structures Notes")
|
||||
.subject("Data Structures")
|
||||
.department("CSE")
|
||||
.semester(3)
|
||||
.fileType("notes")
|
||||
.downloadUrl("https://example.com/ds.pdf")
|
||||
.fileSize("2.4 MB")
|
||||
.build();
|
||||
|
||||
assertNotNull(note);
|
||||
assertEquals(0, note.getDownloadsCount());
|
||||
assertNotNull(note.getUploadedAt());
|
||||
assertTrue(note.getUploadedAt().isBefore(LocalDateTime.now().plusSeconds(1)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCommunityQuestionBuilderDefaults() {
|
||||
CommunityQuestion question = CommunityQuestion.builder()
|
||||
.title("How to prepare for CAT-1?")
|
||||
.body("Looking for reference materials and past questions.")
|
||||
.author("Student123")
|
||||
.build();
|
||||
|
||||
assertNotNull(question);
|
||||
assertEquals(0, question.getUpvotes());
|
||||
assertFalse(question.getIsAnswered());
|
||||
assertNotNull(question.getTags());
|
||||
assertNotNull(question.getAnswers());
|
||||
assertNotNull(question.getCreatedAt());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCommunityAnswerBuilderDefaults() {
|
||||
CommunityAnswer answer = CommunityAnswer.builder()
|
||||
.body("Focus on Unit 1 and Unit 2 standard questions.")
|
||||
.author("Senior456")
|
||||
.build();
|
||||
|
||||
assertNotNull(answer);
|
||||
assertEquals(0, answer.getUpvotes());
|
||||
assertFalse(answer.getIsAccepted());
|
||||
assertNotNull(answer.getCreatedAt());
|
||||
}
|
||||
}
|
||||
1540
grade_report.html
Normal file
1540
grade_report.html
Normal file
File diff suppressed because it is too large
Load Diff
28
package-lock.json
generated
28
package-lock.json
generated
@@ -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",
|
||||
|
||||
BIN
public/map.png
BIN
public/map.png
Binary file not shown.
|
Before Width: | Height: | Size: 394 KiB After Width: | Height: | Size: 8.8 MiB |
3543
real_timetable.html
Normal file
3543
real_timetable.html
Normal file
File diff suppressed because one or more lines are too long
10
schema.sql
10
schema.sql
@@ -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)
|
||||
);
|
||||
|
||||
|
||||
18
scratch/inspect_table_cells.py
Normal file
18
scratch/inspect_table_cells.py
Normal file
@@ -0,0 +1,18 @@
|
||||
import re
|
||||
|
||||
with open('real_timetable.html', 'r', encoding='utf-8') as f:
|
||||
content = f.read()
|
||||
|
||||
# Find rows in the timetable table
|
||||
rows = re.findall(r'<tr[^>]*>(.*?)</tr>', content, re.DOTALL)
|
||||
print(f"Total tr rows: {len(rows)}")
|
||||
|
||||
for idx, r in enumerate(rows):
|
||||
if 'tuesday' in r.lower() or 'tue' in r.lower():
|
||||
print(f"\n--- ROW {idx} (TUESDAY) ---")
|
||||
tds = re.findall(r'<td[^>]*>(.*?)</td>', r, re.DOTALL)
|
||||
print(f"Total td cells in Tuesday row: {len(tds)}")
|
||||
for col_i, td in enumerate(tds):
|
||||
clean_td = ' '.join(re.sub(r'<[^>]+>', ' ', td).split())
|
||||
forms_in_td = re.findall(r'<form[^>]*>(.*?)</form>', td, re.DOTALL)
|
||||
print(f" Col {col_i}: forms_count={len(forms_in_td)} | text={clean_td[:80]}")
|
||||
24
scratch/inspect_tt_periods.py
Normal file
24
scratch/inspect_tt_periods.py
Normal file
@@ -0,0 +1,24 @@
|
||||
import re
|
||||
|
||||
with open('real_timetable.html', 'r', encoding='utf-8') as f:
|
||||
content = f.read()
|
||||
|
||||
forms = re.findall(r'<form[^>]*class="[^"]*period_form[^"]*"[^>]*>(.*?)</form>', content, re.DOTALL)
|
||||
print(f"Total forms found: {len(forms)}")
|
||||
|
||||
by_day = {}
|
||||
for form in forms:
|
||||
day_m = re.search(r'name="day"\s+value="([^"]+)"', form)
|
||||
per_m = re.search(r'name="period"\s+value="([^"]+)"', form)
|
||||
day = day_m.group(1).lower() if day_m else 'unknown'
|
||||
per = per_m.group(1) if per_m else '0'
|
||||
by_day.setdefault(day, []).append((per, form))
|
||||
|
||||
for day in sorted(by_day.keys()):
|
||||
print(f"\n=== DAY: {day.upper()} (Count: {len(by_day[day])}) ===")
|
||||
for per, form in by_day[day]:
|
||||
primaries = re.findall(r'class="[^"]*text-primary[^"]*"[^>]*>(.*?)</span>', form, re.DOTALL)
|
||||
clean_p = [re.sub(r'<[^>]+>', '', p).strip() for p in primaries]
|
||||
full_txt = re.sub(r'<[^>]+>', ' ', form).strip()
|
||||
full_txt = ' '.join(full_txt.split())
|
||||
print(f" Period {per}: primaries={clean_p} | full_txt={full_txt[:100]}")
|
||||
13
scratch/inspect_tue_context.py
Normal file
13
scratch/inspect_tue_context.py
Normal file
@@ -0,0 +1,13 @@
|
||||
import re
|
||||
|
||||
with open('real_timetable.html', 'r', encoding='utf-8') as f:
|
||||
content = f.read()
|
||||
|
||||
print("File length:", len(content))
|
||||
# Search for Tuesday in content
|
||||
tue_matches = [m.start() for m in re.finditer(r'tuesday', content, re.IGNORECASE)]
|
||||
print("Tuesday matches at indices:", tue_matches)
|
||||
|
||||
for pos in tue_matches[:3]:
|
||||
print("\n--- Context around Tuesday ---")
|
||||
print(content[max(0, pos-200):min(len(content), pos+400)])
|
||||
53
scratch/test_lab_assignment_marks.py
Normal file
53
scratch/test_lab_assignment_marks.py
Normal file
@@ -0,0 +1,53 @@
|
||||
import urllib.request
|
||||
import urllib.parse
|
||||
import http.cookiejar
|
||||
import re
|
||||
|
||||
cj = http.cookiejar.CookieJar()
|
||||
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
|
||||
|
||||
login_url = "https://ims.rajalakshmi.edu.in/ims/login"
|
||||
|
||||
headers = {
|
||||
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
|
||||
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
|
||||
}
|
||||
|
||||
# Step 1: GET login page
|
||||
req = urllib.request.Request(login_url, headers=headers)
|
||||
with opener.open(req) as resp:
|
||||
html = resp.read().decode('utf-8')
|
||||
|
||||
csrf_m = re.search(r'name="_token"\s+value="([^"]+)"', html)
|
||||
csrf_token = csrf_m.group(1) if csrf_m else ''
|
||||
print(f"CSRF Token: {csrf_token}")
|
||||
|
||||
# Step 2: POST login
|
||||
post_data = urllib.parse.urlencode({
|
||||
'_token': csrf_token,
|
||||
'username': '2117240070293',
|
||||
'password': '7010406809'
|
||||
}).encode('utf-8')
|
||||
|
||||
req_post = urllib.request.Request(login_url, data=post_data, headers=headers)
|
||||
with opener.open(req_post) as resp_post:
|
||||
dash_html = resp_post.read().decode('utf-8')
|
||||
|
||||
print(f"Login success! Dash HTML length: {len(dash_html)}")
|
||||
|
||||
# Step 3: Find all <a> hrefs containing lab or assignment or mark or report
|
||||
all_links = re.findall(r'<a[^>]+href="([^"]+)"[^>]*>(.*?)</a>', dash_html, re.DOTALL)
|
||||
print(f"Total links found: {len(all_links)}")
|
||||
|
||||
for href, label in all_links:
|
||||
clean_label = re.sub(r'<[^>]+>', '', label).strip()
|
||||
clean_label_lower = clean_label.lower()
|
||||
if 'lab' in clean_label_lower or 'assignment' in clean_label_lower or 'mark' in clean_label_lower or 'grade' in clean_label_lower or 'cat' in clean_label_lower:
|
||||
print(f"Link: '{clean_label}' -> Href: '{href}'")
|
||||
|
||||
# Also search for all hrefs in the full HTML to be sure
|
||||
all_hrefs = re.findall(r'href="([^"]+)"', dash_html)
|
||||
print("\n--- ALL UNIQUE HREFS IN DASHBOARD ---")
|
||||
for h in set(all_hrefs):
|
||||
if 'admin' in h or 'student' in h or 'mark' in h or 'report' in h:
|
||||
print(" ", h)
|
||||
172
src/App.tsx
172
src/App.tsx
@@ -1,28 +1,35 @@
|
||||
import { useEffect } from 'react';
|
||||
import { useEffect, lazy, Suspense } from 'react';
|
||||
import { BrowserRouter, Routes, Route, useLocation } from 'react-router-dom';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import { AuthProvider } from '@/context/AuthContext';
|
||||
import ProtectedRoute from '@/components/Auth/ProtectedRoute';
|
||||
import MainLayout from '@/layouts/MainLayout';
|
||||
import Home from '@/pages/Home/Home';
|
||||
import Notes from '@/pages/Notes/Notes';
|
||||
import Toolkit from '@/pages/Toolkit/Toolkit';
|
||||
import AIAssistant from '@/pages/AIAssistant/AIAssistant';
|
||||
import Campus from '@/pages/Campus/Campus';
|
||||
import Events from '@/pages/Events/Events';
|
||||
import Community from '@/pages/Community/Community';
|
||||
import BusRoutes from '@/pages/BusRoutes/BusRoutes';
|
||||
import Faculty from '@/pages/Faculty/Faculty';
|
||||
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 PageLoader from '@/components/PageLoader/PageLoader';
|
||||
import ErrorBoundary from '@/components/ErrorBoundary/ErrorBoundary';
|
||||
|
||||
// Code-split route components with dynamic imports for minimal initial bundle size
|
||||
const Home = lazy(() => import('@/pages/Home/Home'));
|
||||
const Notes = lazy(() => import('@/pages/Notes/Notes'));
|
||||
const Toolkit = lazy(() => import('@/pages/Toolkit/Toolkit'));
|
||||
const AIAssistant = lazy(() => import('@/pages/AIAssistant/AIAssistant'));
|
||||
const Campus = lazy(() => import('@/pages/Campus/Campus'));
|
||||
const Events = lazy(() => import('@/pages/Events/Events'));
|
||||
const Community = lazy(() => import('@/pages/Community/Community'));
|
||||
const BusRoutes = lazy(() => import('@/pages/BusRoutes/BusRoutes'));
|
||||
const Faculty = lazy(() => import('@/pages/Faculty/Faculty'));
|
||||
const DevCollab = lazy(() => import('@/pages/DevCollab/DevCollab'));
|
||||
const LeetcodeLeaderboard = lazy(() => import('@/pages/LeetcodeLeaderboard/LeetcodeLeaderboard'));
|
||||
const AdminDashboard = lazy(() => import('@/pages/Admin/AdminDashboard'));
|
||||
const Raise = lazy(() => import('@/pages/Raise/Raise'));
|
||||
const StudentDashboard = lazy(() => import('@/pages/StudentDashboard/StudentDashboard'));
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
staleTime: 5 * 60 * 1000,
|
||||
gcTime: 10 * 60 * 1000,
|
||||
refetchOnWindowFocus: false,
|
||||
retry: 1,
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -39,68 +46,87 @@ function ScrollToTop() {
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<BrowserRouter>
|
||||
<AuthProvider>
|
||||
<ScrollToTop />
|
||||
<Routes>
|
||||
{/* Standalone Admin Route */}
|
||||
<Route path="/admin" element={<AdminDashboard />} />
|
||||
<Route path="/admin/*" element={<AdminDashboard />} />
|
||||
<ErrorBoundary>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<BrowserRouter>
|
||||
<AuthProvider>
|
||||
<ScrollToTop />
|
||||
<Suspense fallback={<PageLoader />}>
|
||||
<Routes>
|
||||
{/* Standalone Admin Route */}
|
||||
<Route path="/admin" element={<AdminDashboard />} />
|
||||
<Route path="/admin/*" element={<AdminDashboard />} />
|
||||
|
||||
{/* Standalone RAISE Route */}
|
||||
<Route path="/raise" element={<Raise />} />
|
||||
{/* Standalone RAISE Route */}
|
||||
<Route path="/raise" element={<Raise />} />
|
||||
|
||||
<Route element={<MainLayout />}>
|
||||
<Route path="/" element={<Home />} />
|
||||
<Route path="/notes" element={<Notes />} />
|
||||
<Route path="/toolkit" element={<Toolkit />} />
|
||||
<Route path="/ai-assistant" element={<AIAssistant />} />
|
||||
<Route path="/campus" element={<Campus />} />
|
||||
<Route path="/bus-routes" element={<BusRoutes />} />
|
||||
<Route path="/faculty" element={<Faculty />} />
|
||||
<Route path="/events" element={<Events />} />
|
||||
<Route element={<MainLayout />}>
|
||||
<Route path="/" element={<Home />} />
|
||||
<Route path="/notes" element={<Notes />} />
|
||||
<Route path="/toolkit" element={<Toolkit />} />
|
||||
<Route path="/ai-assistant" element={<AIAssistant />} />
|
||||
<Route path="/campus" element={<Campus />} />
|
||||
<Route path="/bus-routes" element={<BusRoutes />} />
|
||||
<Route path="/faculty" element={<Faculty />} />
|
||||
<Route path="/events" element={<Events />} />
|
||||
|
||||
{/* Protected Routes — Require Google Sign-In */}
|
||||
<Route
|
||||
path="/community"
|
||||
element={
|
||||
<ProtectedRoute
|
||||
title="RIT Q&A Community"
|
||||
description="Connect with fellow RIT students and ask senior helpers any question about campus life and academics."
|
||||
>
|
||||
<Community />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/collab"
|
||||
element={
|
||||
<ProtectedRoute
|
||||
title="Developer Collab Hub"
|
||||
description="Post open-source projects, search for co-developers, and connect with fellow programmers."
|
||||
requireVerifiedStudent={true}
|
||||
>
|
||||
<DevCollab />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/leetcode"
|
||||
element={
|
||||
<ProtectedRoute
|
||||
title="RIT LeetCode Leaderboard"
|
||||
description="Track campus competitive programming rankings and see top RIT coders."
|
||||
>
|
||||
<LeetcodeLeaderboard />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
</Route>
|
||||
</Routes>
|
||||
</AuthProvider>
|
||||
</BrowserRouter>
|
||||
</QueryClientProvider>
|
||||
{/* Student Dashboard & Timetable — Real IMS Reg No & Password */}
|
||||
<Route path="/dashboard" element={<StudentDashboard />} />
|
||||
<Route path="/timetable" element={<StudentDashboard />} />
|
||||
|
||||
{/* Protected Routes — Require Google Sign-In */}
|
||||
<Route
|
||||
path="/community"
|
||||
element={
|
||||
<ProtectedRoute
|
||||
title="RIT Q&A Community"
|
||||
description="Connect with fellow RIT students and ask senior helpers any question about campus life and academics."
|
||||
>
|
||||
<Community />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/collab"
|
||||
element={
|
||||
<ProtectedRoute
|
||||
title="Developer Collab Hub"
|
||||
description="Post open-source projects, search for co-developers, and connect with fellow programmers."
|
||||
requireVerifiedStudent={true}
|
||||
>
|
||||
<DevCollab />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/leetcode"
|
||||
element={
|
||||
<ProtectedRoute
|
||||
title="RIT Student Leaderboard"
|
||||
description="Track campus competitive programming rankings (LeetCode & SkillRack) and verified skill certifications."
|
||||
>
|
||||
<LeetcodeLeaderboard />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/student-leaderboard"
|
||||
element={
|
||||
<ProtectedRoute
|
||||
title="RIT Student Leaderboard"
|
||||
description="Track campus competitive programming rankings (LeetCode & SkillRack) and verified skill certifications."
|
||||
>
|
||||
<LeetcodeLeaderboard />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
</Route>
|
||||
</Routes>
|
||||
</Suspense>
|
||||
</AuthProvider>
|
||||
</BrowserRouter>
|
||||
</QueryClientProvider>
|
||||
</ErrorBoundary>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -58,8 +58,7 @@ export function StaggerContainer({
|
||||
return (
|
||||
<motion.div
|
||||
initial="hidden"
|
||||
whileInView="visible"
|
||||
viewport={{ once: true, margin: '-50px' }}
|
||||
animate="visible"
|
||||
variants={{
|
||||
hidden: {},
|
||||
visible: {
|
||||
|
||||
@@ -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,149 @@ 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>
|
||||
|
||||
<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>
|
||||
|
||||
{/* Title & Description */}
|
||||
<h2
|
||||
className="text-2xl font-bold text-white mb-2"
|
||||
style={{ fontFamily: 'Poppins, sans-serif' }}
|
||||
>
|
||||
Sign In to Freshers Hub
|
||||
</h2>
|
||||
|
||||
<p
|
||||
className="text-xs text-slate-300 mb-6 leading-relaxed"
|
||||
style={{ fontFamily: 'Inter, sans-serif' }}
|
||||
>
|
||||
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!
|
||||
</p>
|
||||
|
||||
{/* Google Sign-In Button Container */}
|
||||
<div className="flex justify-center my-6 min-h-[44px]">
|
||||
<div ref={buttonRef} />
|
||||
{/* 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>
|
||||
|
||||
{/* 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>
|
||||
{/* 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 for Admins */}
|
||||
<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">
|
||||
Official Admin Portals:
|
||||
</span>
|
||||
<div className="grid grid-cols-2 gap-1.5 text-[11px]">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleQuickFill('Transport', 'RIT@2026')}
|
||||
className="p-2.5 rounded-xl 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">Select</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleQuickFill('Admin', 'RIT@2026')}
|
||||
className="p-2.5 rounded-xl 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">Select</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-orange-400">@ritchennai.edu.in</strong> email for automatic student verification.
|
||||
</p>
|
||||
|
||||
<div className="flex justify-center my-4 min-h-[44px]">
|
||||
<div ref={buttonRef} />
|
||||
</div>
|
||||
|
||||
<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>
|
||||
)}
|
||||
|
||||
@@ -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>
|
||||
|
||||
91
src/components/ErrorBoundary/ErrorBoundary.tsx
Normal file
91
src/components/ErrorBoundary/ErrorBoundary.tsx
Normal file
@@ -0,0 +1,91 @@
|
||||
import { Component, type ErrorInfo, type ReactNode } from 'react';
|
||||
import { AlertTriangle, RefreshCw, Home } from 'lucide-react';
|
||||
|
||||
interface Props {
|
||||
children: ReactNode;
|
||||
fallback?: ReactNode;
|
||||
}
|
||||
|
||||
interface State {
|
||||
hasError: boolean;
|
||||
error: Error | null;
|
||||
}
|
||||
|
||||
export class ErrorBoundary extends Component<Props, State> {
|
||||
public state: State = {
|
||||
hasError: false,
|
||||
error: null,
|
||||
};
|
||||
|
||||
public static getDerivedStateFromError(error: Error): State {
|
||||
return { hasError: true, error };
|
||||
}
|
||||
|
||||
public componentDidCatch(error: Error, errorInfo: ErrorInfo) {
|
||||
console.error('[ErrorBoundary caught error]:', error, errorInfo);
|
||||
}
|
||||
|
||||
private handleReset = () => {
|
||||
this.setState({ hasError: false, error: null });
|
||||
window.location.reload();
|
||||
};
|
||||
|
||||
private handleGoHome = () => {
|
||||
this.setState({ hasError: false, error: null });
|
||||
window.location.href = '/';
|
||||
};
|
||||
|
||||
public render() {
|
||||
if (this.state.hasError) {
|
||||
if (this.props.fallback) {
|
||||
return this.props.fallback;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-[70vh] flex items-center justify-center p-6">
|
||||
<div className="max-w-md w-full bg-card/80 backdrop-blur-xl border border-destructive/20 rounded-2xl p-8 shadow-2xl text-center space-y-6">
|
||||
<div className="w-16 h-16 mx-auto rounded-2xl bg-destructive/10 border border-destructive/20 flex items-center justify-center text-destructive shadow-inner">
|
||||
<AlertTriangle className="w-8 h-8 animate-bounce" />
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<h2 className="text-xl font-bold tracking-tight text-foreground">
|
||||
Something went wrong
|
||||
</h2>
|
||||
<p className="text-sm text-muted-foreground leading-relaxed">
|
||||
An unexpected error occurred while rendering this section. You can try refreshing the page or navigating back home.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{this.state.error && (
|
||||
<div className="p-3 rounded-lg bg-muted/50 border border-border text-left overflow-x-auto text-xs font-mono text-muted-foreground max-h-24">
|
||||
{this.state.error.message}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex flex-col sm:flex-row items-center justify-center gap-3 pt-2">
|
||||
<button
|
||||
onClick={this.handleReset}
|
||||
className="w-full sm:w-auto inline-flex items-center justify-center gap-2 px-5 py-2.5 rounded-xl bg-orange-600 hover:bg-orange-700 text-white text-sm font-medium transition-all shadow-lg shadow-orange-600/25 hover:shadow-orange-600/40 active:scale-95 cursor-pointer"
|
||||
>
|
||||
<RefreshCw className="w-4 h-4" />
|
||||
Try Again
|
||||
</button>
|
||||
<button
|
||||
onClick={this.handleGoHome}
|
||||
className="w-full sm:w-auto inline-flex items-center justify-center gap-2 px-5 py-2.5 rounded-xl bg-secondary hover:bg-secondary/80 text-foreground text-sm font-medium transition-all active:scale-95 border border-border cursor-pointer"
|
||||
>
|
||||
<Home className="w-4 h-4" />
|
||||
Go to Home
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return this.props.children;
|
||||
}
|
||||
}
|
||||
|
||||
export default ErrorBoundary;
|
||||
@@ -10,7 +10,7 @@ const exploreLinks = [
|
||||
{ label: 'Student Toolkit', path: '/toolkit', icon: Wrench },
|
||||
{ label: 'RIT Chatbot', path: '/ai-assistant', icon: Bot },
|
||||
{ label: 'Faculty Directory', path: '/faculty', icon: UserCheck },
|
||||
{ label: 'LeetCode Arena', path: '/leetcode', icon: Trophy },
|
||||
{ label: 'Student Leaderboard', path: '/student-leaderboard', icon: Trophy },
|
||||
];
|
||||
|
||||
const campusLinks = [
|
||||
|
||||
@@ -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: 'Student dashboard', 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: 'Student Leaderboard', path: '/student-leaderboard', 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>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="p-2">
|
||||
|
||||
<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" />
|
||||
Student Dashboard
|
||||
</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>
|
||||
) : (
|
||||
<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"
|
||||
style={{ fontFamily: 'Plus Jakarta Sans, sans-serif' }}
|
||||
>
|
||||
<LogOut className="w-4 h-4" />
|
||||
Sign Out ({user?.name.split(' ')[0]})
|
||||
</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 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
|
||||
</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>
|
||||
|
||||
|
||||
24
src/components/PageLoader/PageLoader.tsx
Normal file
24
src/components/PageLoader/PageLoader.tsx
Normal file
@@ -0,0 +1,24 @@
|
||||
import React from 'react';
|
||||
|
||||
const PageLoader: React.FC = () => {
|
||||
return (
|
||||
<div className="min-h-[60vh] flex flex-col items-center justify-center p-6 space-y-4">
|
||||
<div className="relative flex items-center justify-center">
|
||||
{/* Outer glowing ripple */}
|
||||
<div className="absolute w-16 h-16 rounded-full bg-orange-500/20 animate-ping" />
|
||||
{/* Spinning gradient ring */}
|
||||
<div className="w-12 h-12 rounded-full border-3 border-transparent border-t-orange-500 border-r-orange-400 animate-spin" />
|
||||
{/* Center dot */}
|
||||
<div className="absolute w-4 h-4 rounded-full bg-gradient-to-tr from-orange-600 to-amber-400 shadow-lg shadow-orange-500/50" />
|
||||
</div>
|
||||
<div className="flex flex-col items-center space-y-1">
|
||||
<p className="text-sm font-semibold tracking-wide bg-gradient-to-r from-orange-600 via-amber-500 to-orange-400 bg-clip-text text-transparent animate-pulse">
|
||||
Loading Freshers Hub
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">Preparing your campus experience...</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default PageLoader;
|
||||
793
src/constants/departmentCurriculum.ts
Normal file
793
src/constants/departmentCurriculum.ts
Normal 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 }
|
||||
]
|
||||
}
|
||||
};
|
||||
@@ -12,7 +12,7 @@ export const NAV_LINKS = [
|
||||
{ label: 'Clubs & Centers', path: '/events' },
|
||||
{ label: 'Community', path: '/community' },
|
||||
{ label: 'Dev Collab', path: '/collab' },
|
||||
{ label: 'LeetCode', path: '/leetcode' },
|
||||
{ label: 'Student Leaderboard', path: '/student-leaderboard' },
|
||||
];
|
||||
|
||||
// ─── Stats ────────────────────────────────────────────────────────────────────
|
||||
@@ -110,20 +110,29 @@ export const FEATURES: Feature[] = [
|
||||
{
|
||||
id: 'leetcode',
|
||||
icon: 'Trophy',
|
||||
title: 'LeetCode Arena',
|
||||
description: 'Track campus competitive programming rankings and see top RIT coders.',
|
||||
path: '/leetcode',
|
||||
title: 'Student Leaderboard',
|
||||
description: 'Track campus competitive programming rankings (LeetCode & SkillRack) and verified skill certifications.',
|
||||
path: '/student-leaderboard',
|
||||
color: '#F59E0B',
|
||||
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 ────────────────────────────────────────────────────────
|
||||
|
||||
@@ -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,31 @@ export interface AuthUser {
|
||||
name: string;
|
||||
pictureUrl?: string;
|
||||
verifiedStudent: boolean;
|
||||
role?: 'ROLE_STUDENT' | 'ROLE_TRANSPORT' | 'ROLE_COMMUNITY' | 'ROLE_CLUBS' | 'ROLE_CURRICULUM' | '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;
|
||||
isCommunityAdmin: boolean;
|
||||
isClubsAdmin: boolean;
|
||||
isCurriculumAdmin: boolean;
|
||||
isLoading: boolean;
|
||||
isAuthModalOpen: boolean;
|
||||
loginWithGoogle: () => void;
|
||||
loginWithCredentials: (username: string, password: string) => Promise<LoginCredentialsResult>;
|
||||
openAuthModal: () => void;
|
||||
closeAuthModal: () => void;
|
||||
logout: () => void;
|
||||
@@ -43,9 +60,15 @@ const AuthContext = createContext<AuthContextType>({
|
||||
user: null,
|
||||
isAuthenticated: false,
|
||||
isVerifiedStudent: false,
|
||||
isAdmin: false,
|
||||
isTransportAdmin: false,
|
||||
isCommunityAdmin: false,
|
||||
isClubsAdmin: false,
|
||||
isCurriculumAdmin: false,
|
||||
isLoading: true,
|
||||
isAuthModalOpen: false,
|
||||
loginWithGoogle: () => {},
|
||||
loginWithCredentials: async () => ({ success: false }),
|
||||
openAuthModal: () => {},
|
||||
closeAuthModal: () => {},
|
||||
logout: () => {},
|
||||
@@ -54,29 +77,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 +93,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 +149,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();
|
||||
const userObj: AuthUser = { ...userData, role: 'ROLE_USER' };
|
||||
setUser(userObj);
|
||||
localStorage.setItem(GOOGLE_STORAGE_KEY, JSON.stringify(userObj));
|
||||
setIsAuthModalOpen(false);
|
||||
}
|
||||
|
||||
const userData: AuthUser = await res.json();
|
||||
setUser(userData);
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(userData));
|
||||
setIsAuthModalOpen(false);
|
||||
} catch (err) {
|
||||
console.error('Google auth error:', err);
|
||||
}
|
||||
@@ -111,42 +163,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 +187,192 @@ 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.' };
|
||||
}
|
||||
|
||||
const isAdminUsername = [
|
||||
'admin', 'transport', 'transportadmin',
|
||||
'community', 'communityadmin', 'qa', 'seniorqa',
|
||||
'clubs', 'club', 'clubsadmin',
|
||||
'curriculum', 'curriculumadmin', 'gpa', 'gpaadmin', 'academics',
|
||||
'ritadmin', 'superadmin'
|
||||
].includes(cleanedUser.toLowerCase());
|
||||
|
||||
// 1. First, check if credentials match Admin / Role Endpoints
|
||||
if (isAdminUsername) {
|
||||
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: `${cleanedUser.toLowerCase()}@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
|
||||
}
|
||||
}
|
||||
|
||||
const isStdPass = cleanedPass === 'RIT@2026' || cleanedPass === 'rit@2026';
|
||||
|
||||
// Direct local check for Admin credentials fallbacks
|
||||
if (['transport', 'transportadmin'].includes(cleanedUser.toLowerCase()) && isStdPass) {
|
||||
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 (['community', 'qa', 'communityadmin', 'seniorqa'].includes(cleanedUser.toLowerCase()) && isStdPass) {
|
||||
const role = 'ROLE_COMMUNITY';
|
||||
localStorage.setItem(ADMIN_TOKEN_KEY, 'COMMUNITY_SESSION_TOKEN_RIT_2026');
|
||||
localStorage.setItem(ADMIN_ROLE_KEY, role);
|
||||
localStorage.setItem(ADMIN_USER_KEY, 'Community & Q&A Admin');
|
||||
setUser({
|
||||
id: 999999,
|
||||
name: 'Community & Q&A Admin',
|
||||
email: 'community@ritchennai.edu.in',
|
||||
verifiedStudent: false,
|
||||
role,
|
||||
});
|
||||
setIsAuthModalOpen(false);
|
||||
return { success: true, role, redirectTo: '/admin' };
|
||||
}
|
||||
|
||||
if (['clubs', 'club', 'clubsadmin', 'clubadmin'].includes(cleanedUser.toLowerCase()) && isStdPass) {
|
||||
const role = 'ROLE_CLUBS';
|
||||
localStorage.setItem(ADMIN_TOKEN_KEY, 'CLUBS_SESSION_TOKEN_RIT_2026');
|
||||
localStorage.setItem(ADMIN_ROLE_KEY, role);
|
||||
localStorage.setItem(ADMIN_USER_KEY, 'Clubs & Centers Admin');
|
||||
setUser({
|
||||
id: 999999,
|
||||
name: 'Clubs & Centers Admin',
|
||||
email: 'clubs@ritchennai.edu.in',
|
||||
verifiedStudent: false,
|
||||
role,
|
||||
});
|
||||
setIsAuthModalOpen(false);
|
||||
return { success: true, role, redirectTo: '/admin' };
|
||||
}
|
||||
|
||||
if (['curriculum', 'gpa', 'academics', 'gpaadmin', 'curriculumadmin'].includes(cleanedUser.toLowerCase()) && isStdPass) {
|
||||
const role = 'ROLE_CURRICULUM';
|
||||
localStorage.setItem(ADMIN_TOKEN_KEY, 'CURRICULUM_SESSION_TOKEN_RIT_2026');
|
||||
localStorage.setItem(ADMIN_ROLE_KEY, role);
|
||||
localStorage.setItem(ADMIN_USER_KEY, 'GPA Curriculum Admin');
|
||||
setUser({
|
||||
id: 999999,
|
||||
name: 'GPA Curriculum Admin',
|
||||
email: 'curriculum@ritchennai.edu.in',
|
||||
verifiedStudent: false,
|
||||
role,
|
||||
});
|
||||
setIsAuthModalOpen(false);
|
||||
return { success: true, role, redirectTo: '/admin' };
|
||||
}
|
||||
|
||||
if (
|
||||
(['admin', 'superadmin'].includes(cleanedUser.toLowerCase()) && isStdPass) ||
|
||||
(cleanedUser.toLowerCase() === 'ritadmin' && (cleanedPass === 'ritadmin2026' || isStdPass))
|
||||
) {
|
||||
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: `Welcome ${imsResult.student.name}!`,
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
success: false,
|
||||
message: imsResult.message || 'Authentication failed. Please check your credentials.',
|
||||
};
|
||||
}
|
||||
} catch (err: any) {
|
||||
return {
|
||||
success: false,
|
||||
message: err.message || 'Network error while attempting login. Please try again.',
|
||||
};
|
||||
}
|
||||
}, []);
|
||||
|
||||
const logout = useCallback(() => {
|
||||
@@ -189,19 +382,36 @@ 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 isSuperAdmin = user?.role === 'ROLE_SUPER_ADMIN';
|
||||
const isTransportAdmin = user?.role === 'ROLE_TRANSPORT';
|
||||
const isCommunityAdmin = user?.role === 'ROLE_COMMUNITY';
|
||||
const isClubsAdmin = user?.role === 'ROLE_CLUBS';
|
||||
const isCurriculumAdmin = user?.role === 'ROLE_CURRICULUM';
|
||||
const isAdmin = isSuperAdmin || isTransportAdmin || isCommunityAdmin || isClubsAdmin || isCurriculumAdmin;
|
||||
|
||||
return (
|
||||
<AuthContext.Provider
|
||||
value={{
|
||||
user,
|
||||
isAuthenticated: !!user,
|
||||
isVerifiedStudent: !!user?.verifiedStudent,
|
||||
isAdmin,
|
||||
isTransportAdmin,
|
||||
isCommunityAdmin,
|
||||
isClubsAdmin,
|
||||
isCurriculumAdmin,
|
||||
isLoading,
|
||||
isAuthModalOpen,
|
||||
loginWithGoogle,
|
||||
loginWithCredentials,
|
||||
openAuthModal,
|
||||
closeAuthModal,
|
||||
logout,
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -15,13 +15,28 @@ 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) {
|
||||
setBusRoutes(data);
|
||||
setSelectedBusRoute(data[0]);
|
||||
if (!localStorage.getItem('RIT_LOCAL_BUS_ROUTES')) {
|
||||
setBusRoutes(data);
|
||||
setSelectedBusRoute(data[0]);
|
||||
}
|
||||
}
|
||||
})
|
||||
.catch((err) => console.error('Local JSON load error:', err))
|
||||
|
||||
@@ -9,6 +9,8 @@ import { getBackendUrl } from '@/lib/utils';
|
||||
import { StaggerContainer, StaggerItem } from '@/components/AnimatedContainer/AnimatedContainer';
|
||||
import AnimatedContainer from '@/components/AnimatedContainer/AnimatedContainer';
|
||||
|
||||
import { useAuth } from '@/context/AuthContext';
|
||||
|
||||
const TRENDING_TAGS = ['hostel', 'academics', 'clubs', 'campus', 'canteen', 'sports', 'placement', 'library', 'cat exam', 'semester', 'labs', 'exams'];
|
||||
|
||||
const AVATARS: Record<string, string> = {
|
||||
@@ -452,7 +454,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>
|
||||
|
||||
|
||||
@@ -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,73 +986,90 @@ export default function Events() {
|
||||
</div>
|
||||
|
||||
{/* Social & Community Links */}
|
||||
{Boolean(
|
||||
selectedClub.socialLinks?.instagram ||
|
||||
selectedClub.socialLinks?.linkedin ||
|
||||
selectedClub.socialLinks?.whatsapp ||
|
||||
selectedClub.socialLinks?.youtube
|
||||
) && (
|
||||
<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">
|
||||
<ExternalLink className="w-3.5 h-3.5" />
|
||||
<span>Social & Community Links</span>
|
||||
{(() => {
|
||||
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">
|
||||
<ExternalLink className="w-3.5 h-3.5" />
|
||||
<span>Social & Community Links</span>
|
||||
</div>
|
||||
<span className="text-[10px] text-emerald-600 font-medium">✓ Verified RIT Entity</span>
|
||||
</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>
|
||||
)}
|
||||
|
||||
{!isRaiseIncubator && selectedClub.socialLinks?.instagram && (
|
||||
<a
|
||||
href={selectedClub.socialLinks.instagram}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="flex items-center gap-2 p-2.5 rounded-xl bg-white border border-slate-200 hover:border-pink-500 hover:text-pink-600 transition-all text-xs font-medium text-slate-700"
|
||||
>
|
||||
<InstagramIcon className="w-4 h-4 text-pink-500 shrink-0" />
|
||||
<span className="truncate">Instagram</span>
|
||||
</a>
|
||||
)}
|
||||
|
||||
{!isRaiseIncubator && selectedClub.socialLinks?.linkedin && (
|
||||
<a
|
||||
href={selectedClub.socialLinks.linkedin}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="flex items-center gap-2 p-2.5 rounded-xl bg-white border border-slate-200 hover:border-blue-600 hover:text-blue-600 transition-all text-xs font-medium text-slate-700"
|
||||
>
|
||||
<LinkedinIcon className="w-4 h-4 text-blue-600 shrink-0" />
|
||||
<span className="truncate">LinkedIn</span>
|
||||
</a>
|
||||
)}
|
||||
|
||||
{!isRaiseIncubator && selectedClub.socialLinks?.whatsapp && (
|
||||
<a
|
||||
href={selectedClub.socialLinks.whatsapp}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="flex items-center gap-2 p-2.5 rounded-xl bg-white border border-slate-200 hover:border-emerald-500 hover:text-emerald-600 transition-all text-xs font-medium text-slate-700"
|
||||
>
|
||||
<MessageCircle className="w-4 h-4 text-emerald-500 shrink-0" />
|
||||
<span className="truncate">WhatsApp Group</span>
|
||||
</a>
|
||||
)}
|
||||
|
||||
{!isRaiseIncubator && selectedClub.socialLinks?.youtube && (
|
||||
<a
|
||||
href={selectedClub.socialLinks.youtube}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="flex items-center gap-2 p-2.5 rounded-xl bg-white border border-slate-200 hover:border-red-600 hover:text-red-600 transition-all text-xs font-medium text-slate-700"
|
||||
>
|
||||
<YoutubeIcon className="w-4 h-4 text-red-600 shrink-0" />
|
||||
<span className="truncate">YouTube Channel</span>
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
<span className="text-[10px] text-emerald-600 font-medium">✓ Verified RIT Entity</span>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-2.5">
|
||||
|
||||
{selectedClub.socialLinks?.instagram && (
|
||||
<a
|
||||
href={selectedClub.socialLinks.instagram}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="flex items-center gap-2 p-2.5 rounded-xl bg-white border border-slate-200 hover:border-pink-500 hover:text-pink-600 transition-all text-xs font-medium text-slate-700"
|
||||
>
|
||||
<InstagramIcon className="w-4 h-4 text-pink-500 shrink-0" />
|
||||
<span className="truncate">Instagram</span>
|
||||
</a>
|
||||
)}
|
||||
|
||||
{selectedClub.socialLinks?.linkedin && (
|
||||
<a
|
||||
href={selectedClub.socialLinks.linkedin}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="flex items-center gap-2 p-2.5 rounded-xl bg-white border border-slate-200 hover:border-blue-600 hover:text-blue-600 transition-all text-xs font-medium text-slate-700"
|
||||
>
|
||||
<LinkedinIcon className="w-4 h-4 text-blue-600 shrink-0" />
|
||||
<span className="truncate">LinkedIn</span>
|
||||
</a>
|
||||
)}
|
||||
|
||||
{selectedClub.socialLinks?.whatsapp && (
|
||||
<a
|
||||
href={selectedClub.socialLinks.whatsapp}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="flex items-center gap-2 p-2.5 rounded-xl bg-white border border-slate-200 hover:border-emerald-500 hover:text-emerald-600 transition-all text-xs font-medium text-slate-700"
|
||||
>
|
||||
<MessageCircle className="w-4 h-4 text-emerald-500 shrink-0" />
|
||||
<span className="truncate">WhatsApp Group</span>
|
||||
</a>
|
||||
)}
|
||||
|
||||
{selectedClub.socialLinks?.youtube && (
|
||||
<a
|
||||
href={selectedClub.socialLinks.youtube}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="flex items-center gap-2 p-2.5 rounded-xl bg-white border border-slate-200 hover:border-red-600 hover:text-red-600 transition-all text-xs font-medium text-slate-700"
|
||||
>
|
||||
<YoutubeIcon className="w-4 h-4 text-red-600 shrink-0" />
|
||||
<span className="truncate">YouTube Channel</span>
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
);
|
||||
})()}
|
||||
|
||||
{/* Close Button */}
|
||||
<div>
|
||||
|
||||
@@ -1,35 +1,117 @@
|
||||
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 [searchFaculty, setSearchFaculty] = useState('');
|
||||
const [selectedDept, setSelectedDept] = useState('All Departments');
|
||||
const [searchParams] = useSearchParams();
|
||||
const [searchFaculty, setSearchFaculty] = useState(() => searchParams.get('search') || '');
|
||||
const [sortBy, setSortBy] = useState('Name A-Z');
|
||||
|
||||
// Initial department detection (from URL query string or logged-in IMS student session)
|
||||
const initialDepartment = useMemo(() => {
|
||||
if (searchParams.has('search')) return 'All Departments';
|
||||
|
||||
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 and searchFaculty if URL parameter changes
|
||||
useEffect(() => {
|
||||
const querySearch = searchParams.get('search');
|
||||
if (querySearch !== null) {
|
||||
setSearchFaculty(querySearch);
|
||||
setSelectedDept('All Departments');
|
||||
} else {
|
||||
setSelectedDept(initialDepartment);
|
||||
}
|
||||
}, [searchParams, 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 +130,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 +144,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 +183,37 @@ export default function Faculty() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="container-custom pt-8 pb-20 md:pb-28 space-y-8">
|
||||
{/* Under Development Banner */}
|
||||
<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"
|
||||
>
|
||||
<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>
|
||||
<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="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-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-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-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>
|
||||
</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>
|
||||
</motion.div>
|
||||
<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 +249,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`} />
|
||||
<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 text-[#1E293B]" style={{ fontFamily: 'Plus Jakarta Sans, sans-serif' }}>{count}</span>
|
||||
</div>
|
||||
<span className={`text-2xl font-bold ${isSelected ? 'text-white' : 'text-[#1E293B]'}`} style={{ fontFamily: 'Plus Jakarta Sans, sans-serif' }}>{count}</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
@@ -189,7 +294,7 @@ export default function Faculty() {
|
||||
className="h-full pl-10 pr-10 py-3.5 rounded-2xl bg-[#F8FAFC] border-none text-sm font-medium text-[#475569] focus:ring-2 focus:ring-[#FF7A00]/20 focus:outline-none transition-all appearance-none cursor-pointer min-w-[200px]"
|
||||
style={{ fontFamily: 'Inter, sans-serif', backgroundImage: 'url("data:image/svg+xml;charset=US-ASCII,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22292.4%22%20height%3D%22292.4%22%3E%3Cpath%20fill%3D%22%2394A3B8%22%20d%3D%22M287%2069.4a17.6%2017.6%200%200%200-13-5.4H18.4c-5%200-9.3%201.8-12.9%205.4A17.6%2017.6%200%200%200%200%2082.2c0%205%201.8%209.3%205.4%2012.9l128%20127.9c3.6%203.6%207.8%205.4%2012.8%205.4s9.2-1.8%2012.8-5.4L287%2095c3.5-3.5%205.4-7.8%205.4-12.8%200-5-1.9-9.2-5.5-12.8z%22%2F%3E%3C%2Fsvg%3E")', backgroundRepeat: 'no-repeat', backgroundPosition: 'right 1rem top 50%', backgroundSize: '0.65rem auto' }}
|
||||
>
|
||||
{DEPARTMENTS.filter(dept => dept === 'All Departments' || FACULTY_DATA.filter((f) => f.department === dept).length > 0).map((dept) => {
|
||||
{Array.from(new Set(['All Departments', ...DEPARTMENTS, ...FACULTY_DATA.map(f => f.department)])).filter(dept => dept === 'All Departments' || FACULTY_DATA.filter((f) => f.department === dept).length > 0).map((dept) => {
|
||||
const count = dept === 'All Departments' ? FACULTY_DATA.length : FACULTY_DATA.filter((f) => f.department === dept).length;
|
||||
return <option key={dept} value={dept}>{dept} ({count})</option>;
|
||||
})}
|
||||
@@ -256,7 +361,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' }}>
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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();
|
||||
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,
|
||||
downloads: n.downloadsCount || 0,
|
||||
fileSize: n.fileSize,
|
||||
uploadedAt: n.uploadedAt ? n.uploadedAt.split('T')[0] : '',
|
||||
downloadUrl: n.downloadUrl
|
||||
}));
|
||||
setNotes(mappedData);
|
||||
} else {
|
||||
setNotes(NOTES_DATA);
|
||||
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 || 'notes',
|
||||
downloads: n.downloadsCount || 0,
|
||||
fileSize: n.fileSize || '2.4 MB',
|
||||
uploadedAt: n.uploadedAt ? n.uploadedAt.split('T')[0] : '',
|
||||
downloadUrl: n.downloadUrl || '#'
|
||||
}));
|
||||
setNotes(mappedData);
|
||||
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,114 +1969,304 @@ export default function Notes() {
|
||||
) : (
|
||||
<div>
|
||||
<div className="mb-12">
|
||||
{/* Moodle Academic Portal Hero Hub */}
|
||||
<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)' }}
|
||||
>
|
||||
{/* 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' }}>
|
||||
Access Academic Notes & Study Materials on{' '}
|
||||
<span style={{ background: 'linear-gradient(135deg, #F97316, #FB923C)', WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent', backgroundClip: 'text' }}>
|
||||
Moodle
|
||||
</span>
|
||||
</h2>
|
||||
{/* 1. MOODLE LMS CARD */}
|
||||
{activePortalTab === 'moodle' && (
|
||||
<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" />
|
||||
|
||||
<p className="text-base text-[#64748B] mb-8 leading-relaxed max-w-2xl mx-auto" style={{ fontFamily: 'Inter, sans-serif' }}>
|
||||
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}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
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 Official RIT Moodle Portal
|
||||
</a>
|
||||
|
||||
<button
|
||||
onClick={() => {
|
||||
navigator.clipboard.writeText(MOODLE_URL);
|
||||
alert('Moodle 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 Moodle Direct URL
|
||||
</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">
|
||||
<ShieldCheck className="w-4 h-4" />
|
||||
<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">
|
||||
<BookOpen className="w-4 h-4 text-[#F97316]" />
|
||||
<span>Official RIT Learning Management System</span>
|
||||
</div>
|
||||
<div className="text-xs font-bold text-[#1E293B]" style={{ fontFamily: 'Poppins, sans-serif' }}>
|
||||
100% Direct & Secure
|
||||
|
||||
<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
|
||||
</span>
|
||||
</h2>
|
||||
|
||||
<p className="text-base text-[#64748B] mb-8 leading-relaxed max-w-2xl mx-auto" style={{ fontFamily: 'Inter, sans-serif' }}>
|
||||
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>
|
||||
|
||||
<div className="flex flex-col sm:flex-row items-center justify-center gap-4 mb-10">
|
||||
<a
|
||||
href={MOODLE_URL}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
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 Official RIT Moodle Portal
|
||||
</a>
|
||||
|
||||
<button
|
||||
onClick={() => {
|
||||
navigator.clipboard.writeText(MOODLE_URL);
|
||||
alert('Moodle 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 Moodle Direct URL
|
||||
</button>
|
||||
</div>
|
||||
<div className="text-[11px] text-[#64748B]" style={{ fontFamily: 'Inter, sans-serif' }}>
|
||||
Authenticates directly on official college server <code className="bg-slate-200/80 px-1 py-0.5 rounded text-[10px]">182.74.17.142</code>.
|
||||
|
||||
<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">
|
||||
<ShieldCheck className="w-4 h-4" />
|
||||
</div>
|
||||
<div className="text-xs font-bold text-[#1E293B]" style={{ fontFamily: 'Poppins, sans-serif' }}>
|
||||
100% Direct & Secure
|
||||
</div>
|
||||
<div className="text-[11px] text-[#64748B]" style={{ fontFamily: 'Inter, sans-serif' }}>
|
||||
Authenticates directly on official college server <code className="bg-slate-200/80 px-1 py-0.5 rounded text-[10px]">182.74.17.142</code>.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<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-blue-500/10 border border-blue-500/20 flex items-center justify-center text-blue-600">
|
||||
<FileText className="w-4 h-4" />
|
||||
</div>
|
||||
<div className="text-xs font-bold text-[#1E293B]" style={{ fontFamily: 'Poppins, sans-serif' }}>
|
||||
Official Semester Notes
|
||||
</div>
|
||||
<div className="text-[11px] text-[#64748B]" style={{ fontFamily: 'Inter, sans-serif' }}>
|
||||
Complete 1st to 8th Semester course notes, PYQs, and assignments.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<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-purple-500/10 border border-purple-500/20 flex items-center justify-center text-purple-600">
|
||||
<Lock className="w-4 h-4" />
|
||||
</div>
|
||||
<div className="text-xs font-bold text-[#1E293B]" style={{ fontFamily: 'Poppins, sans-serif' }}>
|
||||
Student Login
|
||||
</div>
|
||||
<div className="text-[11px] text-[#64748B]" style={{ fontFamily: 'Inter, sans-serif' }}>
|
||||
Log in using your RIT Register Number and official Moodle password.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
<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-blue-500/10 border border-blue-500/20 flex items-center justify-center text-blue-600">
|
||||
<FileText className="w-4 h-4" />
|
||||
{/* 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>
|
||||
<div className="text-xs font-bold text-[#1E293B]" style={{ fontFamily: 'Poppins, sans-serif' }}>
|
||||
Official Semester Notes
|
||||
|
||||
<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="text-[11px] text-[#64748B]" style={{ fontFamily: 'Inter, sans-serif' }}>
|
||||
Complete 1st to 8th Semester course notes, PYQs, and assignments.
|
||||
|
||||
<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>
|
||||
)}
|
||||
|
||||
<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-purple-500/10 border border-purple-500/20 flex items-center justify-center text-purple-600">
|
||||
<Lock className="w-4 h-4" />
|
||||
{/* 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>
|
||||
<div className="text-xs font-bold text-[#1E293B]" style={{ fontFamily: 'Poppins, sans-serif' }}>
|
||||
Student Login
|
||||
|
||||
<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="text-[11px] text-[#64748B]" style={{ fontFamily: 'Inter, sans-serif' }}>
|
||||
Log in using your RIT Register Number and official Moodle password.
|
||||
|
||||
<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>
|
||||
</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'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>).
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
</motion.div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
1845
src/pages/StudentDashboard/StudentDashboard.tsx
Normal file
1845
src/pages/StudentDashboard/StudentDashboard.tsx
Normal file
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
83
src/services/clubService.ts
Normal file
83
src/services/clubService.ts
Normal 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;
|
||||
}
|
||||
}
|
||||
1281
src/services/imsService.ts
Normal file
1281
src/services/imsService.ts
Normal file
File diff suppressed because it is too large
Load Diff
@@ -179,3 +179,9 @@ export interface ApiResponse<T> {
|
||||
message: string;
|
||||
success: boolean;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
google?: any;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,30 @@
|
||||
{
|
||||
"community_bot_token": "",
|
||||
"telegram_bot_token": "",
|
||||
"helper_chat_ids": [971749136, 5567776672, 1873240361],
|
||||
"community_bot_token": "8973721012:AAG37F4Q4q584m_2aS8rT6qSWuA-WuHRGMY",
|
||||
"telegram_bot_token": "8973721012:AAG37F4Q4q584m_2aS8rT6qSWuA-WuHRGMY",
|
||||
"bot_username": "FreshersCommunityBot",
|
||||
"helper_chat_ids": [
|
||||
1873240361,
|
||||
5567776672,
|
||||
8518850169,
|
||||
7238144438
|
||||
],
|
||||
"seniorHelpers": [
|
||||
{
|
||||
"chatId": 1873240361,
|
||||
"name": "Senior Mentor (CSE)"
|
||||
},
|
||||
{
|
||||
"chatId": 5567776672,
|
||||
"name": "Senior Responder (ECE)"
|
||||
},
|
||||
{
|
||||
"chatId": 8518850169,
|
||||
"name": "Senior Responder (IT)"
|
||||
},
|
||||
{
|
||||
"chatId": 7238144438,
|
||||
"name": "Senior Responder (AIDS)"
|
||||
}
|
||||
],
|
||||
"spring_backend_url": "http://localhost:8085"
|
||||
}
|
||||
@@ -37,8 +37,8 @@ CONFIG_PATH = os.path.join(os.path.dirname(__file__), "config.json")
|
||||
def load_config():
|
||||
if not os.path.exists(CONFIG_PATH):
|
||||
default_config = {
|
||||
"community_bot_token": "8859374355:AAH0dhwstkTBhRerRTjzmb2RG2fjPbigzvo",
|
||||
"telegram_bot_token": "8913773505:AAHASuKLLOto3Ax573_dxg8bnvQy2ML6yLk",
|
||||
"community_bot_token": "8973721012:AAG37F4Q4q584m_2aS8rT6qSWuA-WuHRGMY",
|
||||
"telegram_bot_token": "8973721012:AAG37F4Q4q584m_2aS8rT6qSWuA-WuHRGMY",
|
||||
"helper_chat_ids": [],
|
||||
"spring_backend_url": "http://localhost:8085"
|
||||
}
|
||||
@@ -50,7 +50,7 @@ def load_config():
|
||||
return json.load(f)
|
||||
|
||||
config = load_config()
|
||||
COMMUNITY_BOT_TOKEN = os.environ.get("COMMUNITY_BOT_TOKEN") or config.get("community_bot_token", "8859374355:AAH0dhwstkTBhRerRTjzmb2RG2fjPbigzvo")
|
||||
COMMUNITY_BOT_TOKEN = os.environ.get("COMMUNITY_BOT_TOKEN") or config.get("community_bot_token", "8973721012:AAG37F4Q4q584m_2aS8rT6qSWuA-WuHRGMY")
|
||||
BOT_TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN") or config.get("telegram_bot_token")
|
||||
BACKEND_URL = os.environ.get("SPRING_BACKEND_URL") or config.get("spring_backend_url", "http://localhost:8085")
|
||||
|
||||
@@ -483,6 +483,33 @@ def telegram_polling_thread():
|
||||
|
||||
logging.info(f"Received message from chat {chat_id}: '{text}'")
|
||||
|
||||
# Handle Community Q&A reply if this is a reply to a forwarded question
|
||||
reply_to = message.get("reply_to_message")
|
||||
if reply_to:
|
||||
original_message_id = reply_to["message_id"]
|
||||
question_id = get_question_id(chat_id, original_message_id)
|
||||
if question_id:
|
||||
first_name = message["from"].get("first_name", "")
|
||||
last_name = message["from"].get("last_name", "")
|
||||
author_name = f"{first_name} {last_name}".strip() or "Senior Helper"
|
||||
|
||||
logging.info(f"Submitting answer for question {question_id} by helper '{author_name}'")
|
||||
backend_endpoint = f"{backend_url}/api/questions/{question_id}/answers"
|
||||
answer_payload = {
|
||||
"body": text,
|
||||
"author": author_name
|
||||
}
|
||||
try:
|
||||
res = requests.post(backend_endpoint, json=answer_payload, timeout=10)
|
||||
if res.status_code in [200, 201]:
|
||||
send_telegram_message(chat_id, "✅ *Answer posted successfully to the Q&A board!*", reply_to_message_id=message["message_id"], token=bot_token)
|
||||
else:
|
||||
send_telegram_message(chat_id, f"❌ *Failed to post answer to backend.* (Status: {res.status_code})\nResponse: {res.text[:100]}", reply_to_message_id=message["message_id"], token=bot_token)
|
||||
except Exception as e:
|
||||
logging.error(f"Error calling backend endpoint {backend_endpoint}: {e}")
|
||||
send_telegram_message(chat_id, f"❌ *Connection error to backend.* ({e})", reply_to_message_id=message["message_id"], token=bot_token)
|
||||
continue
|
||||
|
||||
# Handle /remove command in Telegram
|
||||
if text.lower() in ["/remove", "/cancel"]:
|
||||
try:
|
||||
@@ -714,9 +741,16 @@ async def run_uvicorn():
|
||||
await server.serve()
|
||||
|
||||
async def main():
|
||||
comm_thread = threading.Thread(target=community_bot_polling_thread, daemon=True)
|
||||
comm_thread.start()
|
||||
current_config = load_config()
|
||||
comm_token = os.environ.get("COMMUNITY_BOT_TOKEN") or current_config.get("community_bot_token", COMMUNITY_BOT_TOKEN)
|
||||
bot_token = os.environ.get("TELEGRAM_BOT_TOKEN") or current_config.get("telegram_bot_token", BOT_TOKEN)
|
||||
|
||||
# If separate bot tokens are configured, run dedicated community polling thread
|
||||
if comm_token and bot_token and comm_token != bot_token:
|
||||
comm_thread = threading.Thread(target=community_bot_polling_thread, daemon=True)
|
||||
comm_thread.start()
|
||||
|
||||
# Main unified thread handles Dev Collab, Chatbot, and unified Q&A
|
||||
chat_thread = threading.Thread(target=telegram_polling_thread, daemon=True)
|
||||
chat_thread.start()
|
||||
|
||||
|
||||
@@ -50,8 +50,67 @@ export default defineConfig({
|
||||
}
|
||||
})
|
||||
],
|
||||
build: {
|
||||
target: 'esnext',
|
||||
chunkSizeWarningLimit: 800,
|
||||
rollupOptions: {
|
||||
output: {
|
||||
manualChunks(id: string) {
|
||||
if (id.includes('node_modules')) {
|
||||
if (id.includes('react') || id.includes('react-dom') || id.includes('react-router-dom')) {
|
||||
return 'vendor-react';
|
||||
}
|
||||
if (id.includes('framer-motion') || id.includes('lucide-react')) {
|
||||
return 'vendor-ui';
|
||||
}
|
||||
if (id.includes('@radix-ui')) {
|
||||
return 'vendor-radix';
|
||||
}
|
||||
if (id.includes('@tanstack')) {
|
||||
return 'vendor-tanstack';
|
||||
}
|
||||
if (id.includes('leaflet') || id.includes('react-leaflet')) {
|
||||
return 'vendor-map';
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
server: {
|
||||
host: true,
|
||||
proxy: {
|
||||
'/ims': {
|
||||
target: 'https://ims.ritchennai.edu.in',
|
||||
changeOrigin: true,
|
||||
rewrite: (path) => path.replace(/^\/ims/, ''),
|
||||
secure: false,
|
||||
configure: (proxy) => {
|
||||
proxy.on('proxyRes', (proxyRes) => {
|
||||
// Rewrite Location header to keep redirects through local / VPS proxy
|
||||
const location = proxyRes.headers['location'];
|
||||
if (location) {
|
||||
let rewritten = location;
|
||||
if (rewritten.includes('ims.ritchennai.edu.in')) {
|
||||
rewritten = rewritten.replace(/https?:\/\/ims\.ritchennai\.edu\.in/gi, '/ims');
|
||||
} else if (rewritten.startsWith('/') && !rewritten.startsWith('/ims')) {
|
||||
rewritten = '/ims' + rewritten;
|
||||
}
|
||||
proxyRes.headers['location'] = rewritten;
|
||||
}
|
||||
// Strip domain from cookies so session cookies bind to current host (localhost or VPS domain)
|
||||
const setCookie = proxyRes.headers['set-cookie'];
|
||||
if (setCookie) {
|
||||
proxyRes.headers['set-cookie'] = (Array.isArray(setCookie) ? setCookie : [setCookie]).map((cookie: string) =>
|
||||
cookie
|
||||
.replace(/domain=[^;]+/gi, '')
|
||||
.replace(/path=[^;]+/gi, 'Path=/')
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
},
|
||||
watch: {
|
||||
ignored: [
|
||||
'**/backend/**',
|
||||
|
||||
Reference in New Issue
Block a user