added fake end points to simulate real arhitecture

This commit is contained in:
Shanmuga Krishnan S M
2026-08-17 14:36:32 +05:30
parent d827f4aab9
commit 1eebd10f3a
14 changed files with 3652 additions and 248 deletions

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -15,6 +15,18 @@ server.port=8085
# ─── GOOGLE OAUTH2 CONFIGURATION ───
google.client.id=${GOOGLE_CLIENT_ID:81935488244-vmab5t8fipfof1n6l7di7eg4fve6k8lf.apps.googleusercontent.com}
# ─── ADMIN PORTAL CREDENTIALS ───
# ─── ADMIN PORTAL MULTI-ROLE CREDENTIALS ───
admin.transport.username=${TRANSPORT_USERNAME:Transport}
admin.transport.password=${TRANSPORT_PASSWORD:RIT@2026}
admin.super.username=${SUPER_ADMIN_USERNAME:Admin}
admin.super.password=${SUPER_ADMIN_PASSWORD:RIT@2026}
admin.username=${ADMIN_USERNAME:ritadmin}
admin.password=${ADMIN_PASSWORD:ritadmin2026}
# ─── IMS INTEGRATION CONFIGURATION ───
# Options: "mock" (active now for testing & simulation) | "real" (for live college IMS)
ims.client.type=mock
ims.base-url=${IMS_BASE_URL:https://api.ims.ritchennai.edu.in}
ims.api-key=${IMS_API_KEY:rit_nexus_vps_secret_key_2026}