feat: enhance chatbot Telegram/Discord integrations, add /remove commands and Q&A reply handling
This commit is contained in:
1
.gitignore
vendored
1
.gitignore
vendored
@@ -29,6 +29,7 @@ dist-ssr
|
||||
|
||||
# Maven & Java
|
||||
target/
|
||||
**/target/
|
||||
.mvn/
|
||||
|
||||
# Android & Gradle
|
||||
|
||||
@@ -2,8 +2,10 @@ package com.rit.portal;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
|
||||
@SpringBootApplication
|
||||
@EnableScheduling
|
||||
public class PortalApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
@@ -43,6 +43,10 @@ public class CollabController {
|
||||
public CollabRequest createCollabRequest(@RequestBody CollabRequest request) {
|
||||
if (request.getStatus() == null) request.setStatus("OPEN");
|
||||
if (request.getApplicationsCount() == null) request.setApplicationsCount(0);
|
||||
if (request.getCollaboratorsNeeded() == null || request.getCollaboratorsNeeded() < 1) {
|
||||
request.setCollaboratorsNeeded(1);
|
||||
}
|
||||
if (request.getAcceptedCount() == null) request.setAcceptedCount(0);
|
||||
request.setCreatedAt(LocalDateTime.now());
|
||||
return collabRequestRepository.save(request);
|
||||
}
|
||||
@@ -52,6 +56,10 @@ public class CollabController {
|
||||
@PathVariable Integer id,
|
||||
@RequestBody CollabApplication application) {
|
||||
return collabRequestRepository.findById(id).map(request -> {
|
||||
if ("CLOSED".equalsIgnoreCase(request.getStatus()) || "CANCELLED".equalsIgnoreCase(request.getStatus())) {
|
||||
return ResponseEntity.badRequest().<CollabApplication>build();
|
||||
}
|
||||
|
||||
application.setCollabRequest(request);
|
||||
if (application.getStatus() == null) application.setStatus("PENDING");
|
||||
application.setCreatedAt(LocalDateTime.now());
|
||||
@@ -95,9 +103,44 @@ public class CollabController {
|
||||
@PathVariable Integer applicationId,
|
||||
@RequestParam String status) {
|
||||
return collabApplicationRepository.findById(applicationId).map(app -> {
|
||||
app.setStatus(status.toUpperCase());
|
||||
String newStatus = status.toUpperCase();
|
||||
String oldStatus = app.getStatus();
|
||||
app.setStatus(newStatus);
|
||||
CollabApplication updated = collabApplicationRepository.save(app);
|
||||
|
||||
// Delete request entirely when accepted count meets requested collaborators count
|
||||
if ("ACCEPTED".equals(newStatus) && !"ACCEPTED".equals(oldStatus)) {
|
||||
CollabRequest parentReq = app.getCollabRequest();
|
||||
if (parentReq != null) {
|
||||
int accepted = (parentReq.getAcceptedCount() == null ? 0 : parentReq.getAcceptedCount()) + 1;
|
||||
parentReq.setAcceptedCount(accepted);
|
||||
int needed = parentReq.getCollaboratorsNeeded() == null ? 1 : parentReq.getCollaboratorsNeeded();
|
||||
if (accepted >= needed) {
|
||||
collabRequestRepository.delete(parentReq);
|
||||
} else {
|
||||
collabRequestRepository.save(parentReq);
|
||||
}
|
||||
}
|
||||
}
|
||||
return ResponseEntity.ok(updated);
|
||||
}).orElse(ResponseEntity.notFound().build());
|
||||
}
|
||||
|
||||
@GetMapping("/active/telegram/{chatId}")
|
||||
public List<CollabRequest> getActiveRequestsByTelegram(@PathVariable Long chatId) {
|
||||
return collabRequestRepository.findByTelegramChatIdAndStatusOrderByCreatedAtDesc(chatId, "OPEN");
|
||||
}
|
||||
|
||||
@GetMapping("/active/discord/{userId}")
|
||||
public List<CollabRequest> getActiveRequestsByDiscord(@PathVariable String userId) {
|
||||
return collabRequestRepository.findByDiscordUserIdAndStatusOrderByCreatedAtDesc(userId, "OPEN");
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public ResponseEntity<Void> deleteOrCancelCollabRequest(@PathVariable Integer id) {
|
||||
return collabRequestRepository.findById(id).map(req -> {
|
||||
collabRequestRepository.delete(req);
|
||||
return ResponseEntity.noContent().<Void>build();
|
||||
}).orElse(ResponseEntity.notFound().build());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.rit.portal.controller;
|
||||
|
||||
import com.rit.portal.entity.LeetcodeProfile;
|
||||
import com.rit.portal.service.LeetcodeService;
|
||||
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/leetcode")
|
||||
@CrossOrigin(originPatterns = "*")
|
||||
@RequiredArgsConstructor
|
||||
public class LeetcodeController {
|
||||
|
||||
private final LeetcodeService leetcodeService;
|
||||
|
||||
@GetMapping("/leaderboard")
|
||||
public List<LeetcodeProfile> getLeaderboard() {
|
||||
return leetcodeService.getAllRankedProfiles();
|
||||
}
|
||||
|
||||
@PostMapping("/register")
|
||||
public ResponseEntity<?> registerProfile(@RequestBody RegisterRequest request) {
|
||||
if (request.getLeetcodeUsername() == null || request.getLeetcodeUsername().trim().isEmpty()) {
|
||||
return ResponseEntity.badRequest().body(Map.of("error", "LeetCode username is required"));
|
||||
}
|
||||
if (request.getStudentName() == null || request.getStudentName().trim().isEmpty()) {
|
||||
return ResponseEntity.badRequest().body(Map.of("error", "Student name is required"));
|
||||
}
|
||||
|
||||
try {
|
||||
LeetcodeProfile profile = leetcodeService.registerOrUpdateStudent(
|
||||
request.getStudentName(),
|
||||
request.getLeetcodeUsername(),
|
||||
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<?> triggerSpacedSync() {
|
||||
leetcodeService.syncAllProfilesWithSpacing();
|
||||
return ResponseEntity.ok(Map.of("message", "24h background sync initiated with 3-second request spacing between users."));
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class RegisterRequest {
|
||||
private String studentName;
|
||||
private String leetcodeUsername;
|
||||
private String department;
|
||||
private String year;
|
||||
}
|
||||
}
|
||||
@@ -54,6 +54,14 @@ public class CollabRequest {
|
||||
@Builder.Default
|
||||
private Integer applicationsCount = 0;
|
||||
|
||||
@Column(name = "collaborators_needed")
|
||||
@Builder.Default
|
||||
private Integer collaboratorsNeeded = 1;
|
||||
|
||||
@Column(name = "accepted_count")
|
||||
@Builder.Default
|
||||
private Integer acceptedCount = 0;
|
||||
|
||||
@Column(name = "created_at")
|
||||
@Builder.Default
|
||||
private LocalDateTime createdAt = LocalDateTime.now();
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
package com.rit.portal.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Entity
|
||||
@Table(name = "leetcode_profiles")
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Builder
|
||||
public class LeetcodeProfile {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Integer id;
|
||||
|
||||
@Column(name = "student_name", nullable = false)
|
||||
private String studentName;
|
||||
|
||||
@Column(name = "leetcode_username", nullable = false, unique = true)
|
||||
private String leetcodeUsername;
|
||||
|
||||
@Column(nullable = false)
|
||||
private String department;
|
||||
|
||||
@Column(nullable = false)
|
||||
private String year;
|
||||
|
||||
@Column(name = "total_solved")
|
||||
@Builder.Default
|
||||
private Integer totalSolved = 0;
|
||||
|
||||
@Column(name = "easy_solved")
|
||||
@Builder.Default
|
||||
private Integer easySolved = 0;
|
||||
|
||||
@Column(name = "medium_solved")
|
||||
@Builder.Default
|
||||
private Integer mediumSolved = 0;
|
||||
|
||||
@Column(name = "hard_solved")
|
||||
@Builder.Default
|
||||
private Integer hardSolved = 0;
|
||||
|
||||
@Column(name = "ranking")
|
||||
@Builder.Default
|
||||
private Integer ranking = 0;
|
||||
|
||||
@Column(name = "reputation")
|
||||
@Builder.Default
|
||||
private Integer reputation = 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();
|
||||
}
|
||||
}
|
||||
@@ -8,4 +8,6 @@ import java.util.List;
|
||||
@Repository
|
||||
public interface CollabRequestRepository extends JpaRepository<CollabRequest, Integer> {
|
||||
List<CollabRequest> findAllByOrderByCreatedAtDesc();
|
||||
List<CollabRequest> findByTelegramChatIdAndStatusOrderByCreatedAtDesc(Long telegramChatId, String status);
|
||||
List<CollabRequest> findByDiscordUserIdAndStatusOrderByCreatedAtDesc(String discordUserId, String status);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.rit.portal.repository;
|
||||
|
||||
import com.rit.portal.entity.LeetcodeProfile;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public interface LeetcodeProfileRepository extends JpaRepository<LeetcodeProfile, Integer> {
|
||||
Optional<LeetcodeProfile> findByLeetcodeUsernameIgnoreCase(String leetcodeUsername);
|
||||
List<LeetcodeProfile> findAllByOrderByTotalSolvedDescRankingAsc();
|
||||
boolean existsByLeetcodeUsernameIgnoreCase(String leetcodeUsername);
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
package com.rit.portal.service;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.rit.portal.entity.LeetcodeProfile;
|
||||
import com.rit.portal.repository.LeetcodeProfileRepository;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.*;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.*;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class LeetcodeService {
|
||||
|
||||
private final LeetcodeProfileRepository repository;
|
||||
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||
private final RestTemplate restTemplate = new RestTemplate();
|
||||
|
||||
private static final String LEETCODE_GRAPHQL_URL = "https://leetcode.com/graphql";
|
||||
|
||||
public List<LeetcodeProfile> getAllRankedProfiles() {
|
||||
return repository.findAllByOrderByTotalSolvedDescRankingAsc();
|
||||
}
|
||||
|
||||
public LeetcodeProfile registerOrUpdateStudent(String studentName, String leetcodeUsername, String department, String year) {
|
||||
String cleanUsername = leetcodeUsername.trim();
|
||||
|
||||
LeetcodeProfile profile = repository.findByLeetcodeUsernameIgnoreCase(cleanUsername)
|
||||
.orElse(LeetcodeProfile.builder()
|
||||
.studentName(studentName.trim())
|
||||
.leetcodeUsername(cleanUsername)
|
||||
.department(department.trim())
|
||||
.year(year.trim())
|
||||
.build());
|
||||
|
||||
profile.setStudentName(studentName.trim());
|
||||
profile.setDepartment(department.trim());
|
||||
profile.setYear(year.trim());
|
||||
|
||||
// Fetch fresh stats immediately for registration
|
||||
boolean success = fetchAndUpdateProfile(profile);
|
||||
if (!success) {
|
||||
throw new IllegalArgumentException("LeetCode username '" + cleanUsername + "' could not be found on LeetCode.");
|
||||
}
|
||||
return repository.save(profile);
|
||||
}
|
||||
|
||||
public boolean fetchAndUpdateProfile(LeetcodeProfile profile) {
|
||||
try {
|
||||
log.info("Fetching LeetCode GraphQL stats for: {}", profile.getLeetcodeUsername());
|
||||
|
||||
String graphqlQuery = "{\"query\":\"query getUserProfile($username: String!) { matchedUser(username: $username) { username submitStats: submitStatsGlobal { acSubmissionNum { difficulty count } } profile { ranking reputation } } }\",\"variables\":{\"username\":\"" + profile.getLeetcodeUsername() + "\"}}";
|
||||
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.APPLICATION_JSON);
|
||||
headers.set("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");
|
||||
headers.set("Referer", "https://leetcode.com/");
|
||||
|
||||
HttpEntity<String> request = new HttpEntity<>(graphqlQuery, headers);
|
||||
ResponseEntity<String> response = restTemplate.postForEntity(LEETCODE_GRAPHQL_URL, request, String.class);
|
||||
|
||||
if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
|
||||
JsonNode root = objectMapper.readTree(response.getBody());
|
||||
JsonNode matchedUser = root.path("data").path("matchedUser");
|
||||
|
||||
if (matchedUser.isMissingNode() || matchedUser.isNull()) {
|
||||
log.warn("LeetCode username not found: {}", profile.getLeetcodeUsername());
|
||||
return false;
|
||||
}
|
||||
|
||||
// Extract ranking and reputation
|
||||
JsonNode profileNode = matchedUser.path("profile");
|
||||
if (!profileNode.isMissingNode()) {
|
||||
profile.setRanking(profileNode.path("ranking").asInt(0));
|
||||
profile.setReputation(profileNode.path("reputation").asInt(0));
|
||||
}
|
||||
|
||||
// Extract problem submission counts
|
||||
JsonNode acSubmissions = matchedUser.path("submitStats").path("acSubmissionNum");
|
||||
if (acSubmissions.isArray()) {
|
||||
for (JsonNode item : acSubmissions) {
|
||||
String diff = item.path("difficulty").asText("");
|
||||
int count = item.path("count").asInt(0);
|
||||
if ("All".equalsIgnoreCase(diff)) {
|
||||
profile.setTotalSolved(count);
|
||||
} else if ("Easy".equalsIgnoreCase(diff)) {
|
||||
profile.setEasySolved(count);
|
||||
} else if ("Medium".equalsIgnoreCase(diff)) {
|
||||
profile.setMediumSolved(count);
|
||||
} else if ("Hard".equalsIgnoreCase(diff)) {
|
||||
profile.setHardSolved(count);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
profile.setLastUpdated(LocalDateTime.now());
|
||||
log.info("Successfully updated LeetCode profile for {}: Total Solved = {}", profile.getLeetcodeUsername(), profile.getTotalSolved());
|
||||
return true;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to fetch LeetCode data for {}: {}", profile.getLeetcodeUsername(), e.getMessage());
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Automatic 24-hour scheduled job running at 2:00 AM every day.
|
||||
* Uses spaced requests (3-second delay between each user) to ensure ZERO IP blocking.
|
||||
*/
|
||||
@Scheduled(cron = "0 0 2 * * ?")
|
||||
public void scheduledDailySyncWithSpacedRequests() {
|
||||
log.info("Starting scheduled 24h LeetCode sync job...");
|
||||
syncAllProfilesWithSpacing();
|
||||
}
|
||||
|
||||
/**
|
||||
* Manual or scheduled trigger to sync all profiles with a 3-second delay between requests.
|
||||
*/
|
||||
public void syncAllProfilesWithSpacing() {
|
||||
List<LeetcodeProfile> profiles = repository.findAll();
|
||||
log.info("Queued {} LeetCode profiles for spaced synchronization.", profiles.size());
|
||||
|
||||
new Thread(() -> {
|
||||
for (int i = 0; i < profiles.size(); i++) {
|
||||
LeetcodeProfile profile = profiles.get(i);
|
||||
try {
|
||||
fetchAndUpdateProfile(profile);
|
||||
repository.save(profile);
|
||||
|
||||
// Space out requests by 3 seconds if not the last item
|
||||
if (i < profiles.size() - 1) {
|
||||
log.info("Waiting 3 seconds before fetching next profile to space out requests...");
|
||||
Thread.sleep(5000);
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
log.error("Spaced sync job interrupted.");
|
||||
break;
|
||||
} catch (Exception e) {
|
||||
log.error("Error during spaced sync for {}: {}", profile.getLeetcodeUsername(), e.getMessage());
|
||||
}
|
||||
}
|
||||
log.info("Finished spaced sync for all LeetCode profiles.");
|
||||
}).start();
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
com\rit\portal\controller\BusLocationController.class
|
||||
com\rit\portal\config\DataInitializer$1.class
|
||||
com\rit\portal\repository\CommunityAnswerRepository.class
|
||||
com\rit\portal\entity\CommunityAnswer$CommunityAnswerBuilder.class
|
||||
com\rit\portal\entity\CommunityQuestion.class
|
||||
com\rit\portal\controller\BusRouteController.class
|
||||
com\rit\portal\entity\NotePyq.class
|
||||
com\rit\portal\entity\CommunityAnswer.class
|
||||
com\rit\portal\controller\CommunityQuestionController.class
|
||||
com\rit\portal\dto\DriverLocationUpdate.class
|
||||
com\rit\portal\config\WebConfig.class
|
||||
com\rit\portal\repository\BusStopRepository.class
|
||||
com\rit\portal\config\DataInitializer.class
|
||||
com\rit\portal\entity\BusStop.class
|
||||
com\rit\portal\entity\BusStop$BusStopBuilder.class
|
||||
com\rit\portal\repository\BusRouteRepository.class
|
||||
com\rit\portal\entity\CommunityQuestion$CommunityQuestionBuilder.class
|
||||
com\rit\portal\entity\NotePyq$NotePyqBuilder.class
|
||||
com\rit\portal\entity\BusRoute$BusRouteBuilder.class
|
||||
com\rit\portal\controller\NotePyqController.class
|
||||
com\rit\portal\service\BusLocationService.class
|
||||
com\rit\portal\repository\NotePyqRepository.class
|
||||
com\rit\portal\model\BusLocation.class
|
||||
com\rit\portal\entity\BusRoute.class
|
||||
com\rit\portal\repository\CommunityQuestionRepository.class
|
||||
com\rit\portal\PortalApplication.class
|
||||
@@ -1,20 +0,0 @@
|
||||
F:\fresher\Freshers-Hub\backend\src\main\java\com\rit\portal\config\DataInitializer.java
|
||||
F:\fresher\Freshers-Hub\backend\src\main\java\com\rit\portal\config\WebConfig.java
|
||||
F:\fresher\Freshers-Hub\backend\src\main\java\com\rit\portal\controller\BusLocationController.java
|
||||
F:\fresher\Freshers-Hub\backend\src\main\java\com\rit\portal\controller\BusRouteController.java
|
||||
F:\fresher\Freshers-Hub\backend\src\main\java\com\rit\portal\controller\CommunityQuestionController.java
|
||||
F:\fresher\Freshers-Hub\backend\src\main\java\com\rit\portal\controller\NotePyqController.java
|
||||
F:\fresher\Freshers-Hub\backend\src\main\java\com\rit\portal\dto\DriverLocationUpdate.java
|
||||
F:\fresher\Freshers-Hub\backend\src\main\java\com\rit\portal\entity\BusRoute.java
|
||||
F:\fresher\Freshers-Hub\backend\src\main\java\com\rit\portal\entity\BusStop.java
|
||||
F:\fresher\Freshers-Hub\backend\src\main\java\com\rit\portal\entity\CommunityAnswer.java
|
||||
F:\fresher\Freshers-Hub\backend\src\main\java\com\rit\portal\entity\CommunityQuestion.java
|
||||
F:\fresher\Freshers-Hub\backend\src\main\java\com\rit\portal\entity\NotePyq.java
|
||||
F:\fresher\Freshers-Hub\backend\src\main\java\com\rit\portal\model\BusLocation.java
|
||||
F:\fresher\Freshers-Hub\backend\src\main\java\com\rit\portal\PortalApplication.java
|
||||
F:\fresher\Freshers-Hub\backend\src\main\java\com\rit\portal\repository\BusRouteRepository.java
|
||||
F:\fresher\Freshers-Hub\backend\src\main\java\com\rit\portal\repository\BusStopRepository.java
|
||||
F:\fresher\Freshers-Hub\backend\src\main\java\com\rit\portal\repository\CommunityAnswerRepository.java
|
||||
F:\fresher\Freshers-Hub\backend\src\main\java\com\rit\portal\repository\CommunityQuestionRepository.java
|
||||
F:\fresher\Freshers-Hub\backend\src\main\java\com\rit\portal\repository\NotePyqRepository.java
|
||||
F:\fresher\Freshers-Hub\backend\src\main\java\com\rit\portal\service\BusLocationService.java
|
||||
@@ -1,9 +1,9 @@
|
||||
package com.rit.driver;
|
||||
|
||||
public class Config {
|
||||
// Local testing backend URL (Your PC Wi-Fi IP)
|
||||
public static final String BACKEND_URL = "http://10.10.15.91:8085";
|
||||
|
||||
// Default driver security PIN
|
||||
public static final String BACKEND_URL = "http://10.43.158.201:8085";
|
||||
|
||||
|
||||
public static final String DEFAULT_PIN = "RITDRIVER";
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ 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';
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
@@ -47,6 +48,7 @@ function App() {
|
||||
<Route path="/events" element={<Events />} />
|
||||
<Route path="/community" element={<Community />} />
|
||||
<Route path="/collab" element={<DevCollab />} />
|
||||
<Route path="/leetcode" element={<LeetcodeLeaderboard />} />
|
||||
</Route>
|
||||
</Routes>
|
||||
</BrowserRouter>
|
||||
|
||||
@@ -92,10 +92,10 @@ export default function Navbar() {
|
||||
<motion.button
|
||||
whileTap={{ scale: 0.9 }}
|
||||
onClick={() => setIsMobileOpen(!isMobileOpen)}
|
||||
className="md:hidden w-9 h-9 rounded-xl flex items-center justify-center text-slate-300 hover:text-white hover:bg-white/10 transition-all"
|
||||
className="md:hidden w-11 h-11 rounded-xl flex items-center justify-center text-slate-200 hover:text-white bg-slate-800/60 hover:bg-slate-700/60 border border-slate-700/50 transition-all active:scale-95"
|
||||
aria-label="Toggle menu"
|
||||
>
|
||||
{isMobileOpen ? <X className="w-5 h-5" /> : <Menu className="w-5 h-5" />}
|
||||
{isMobileOpen ? <X className="w-5 h-5 stroke-[2.5]" /> : <Menu className="w-5 h-5 stroke-[2.5]" />}
|
||||
</motion.button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -108,20 +108,22 @@ export default function Navbar() {
|
||||
animate={{ height: 'auto', opacity: 1 }}
|
||||
exit={{ height: 0, opacity: 0 }}
|
||||
transition={{ duration: 0.25 }}
|
||||
className="overflow-hidden md:hidden"
|
||||
className="overflow-hidden md:hidden max-h-[80vh] overflow-y-auto"
|
||||
>
|
||||
<div className="px-4 pb-4 pt-2 flex flex-col gap-1 border-t border-white/10">
|
||||
<div className="px-4 pb-5 pt-3 grid grid-cols-2 gap-2 border-t border-white/10 bg-slate-950/90 backdrop-blur-2xl rounded-b-2xl">
|
||||
{NAV_LINKS.map((link) => {
|
||||
const isActive = location.pathname === link.path;
|
||||
return (
|
||||
<Link
|
||||
key={link.path}
|
||||
to={link.path}
|
||||
className="px-4 py-3 rounded-xl text-sm font-medium transition-all"
|
||||
onClick={() => setIsMobileOpen(false)}
|
||||
className="px-3.5 py-3 rounded-xl text-xs font-semibold uppercase tracking-wider flex items-center justify-center text-center transition-all min-h-[44px]"
|
||||
style={{
|
||||
fontFamily: 'Inter, sans-serif',
|
||||
fontFamily: 'Poppins, sans-serif',
|
||||
color: isActive ? '#FFFFFF' : '#CBD5E1',
|
||||
backgroundColor: isActive ? '#F97316' : 'transparent',
|
||||
backgroundColor: isActive ? '#F97316' : 'rgba(255, 255, 255, 0.05)',
|
||||
border: isActive ? '1px solid #FB923C' : '1px solid rgba(255, 255, 255, 0.08)',
|
||||
}}
|
||||
>
|
||||
{link.label}
|
||||
|
||||
@@ -11,6 +11,7 @@ export const NAV_LINKS = [
|
||||
{ label: 'Clubs', path: '/events' },
|
||||
{ label: 'Community', path: '/community' },
|
||||
{ label: 'Dev Collab', path: '/collab' },
|
||||
{ label: 'LeetCode', path: '/leetcode' },
|
||||
];
|
||||
|
||||
// ─── Stats ────────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -16,8 +16,11 @@ export interface CollabRequestItem {
|
||||
projectIdea: string;
|
||||
githubLink?: string;
|
||||
tag: string;
|
||||
collaboratorsNeeded?: number;
|
||||
acceptedCount?: number;
|
||||
contactInfo?: string;
|
||||
telegramChatId?: number;
|
||||
discordUserId?: string;
|
||||
status: string;
|
||||
applicationsCount: number;
|
||||
createdAt: string;
|
||||
@@ -41,6 +44,8 @@ const INITIAL_MOCK_REQUESTS: CollabRequestItem[] = [
|
||||
projectIdea: 'Building an automated AI Attendance & Proxy Detection system using OpenCV and Python for college labs.',
|
||||
githubLink: 'https://github.com/example/rit-ai-attendance',
|
||||
tag: 'looking for co-developing a project from scratch',
|
||||
collaboratorsNeeded: 2,
|
||||
acceptedCount: 0,
|
||||
contactInfo: '@rohan_sharma_rit',
|
||||
status: 'OPEN',
|
||||
applicationsCount: 3,
|
||||
@@ -54,6 +59,8 @@ const INITIAL_MOCK_REQUESTS: CollabRequestItem[] = [
|
||||
projectIdea: 'Need beta testers for our web-based RIT Bus Tracking & Live ETA PWA before publishing to campus app store.',
|
||||
githubLink: 'https://github.com/example/rit-bus-live',
|
||||
tag: 'looking for beta testers',
|
||||
collaboratorsNeeded: 5,
|
||||
acceptedCount: 2,
|
||||
contactInfo: '@ananya_rit_dev',
|
||||
status: 'OPEN',
|
||||
applicationsCount: 7,
|
||||
@@ -67,6 +74,8 @@ const INITIAL_MOCK_REQUESTS: CollabRequestItem[] = [
|
||||
projectIdea: 'Open-source IoT Smart Canteen Pre-order Hardware & Mobile App. Looking for React Native & ESP32 contributors!',
|
||||
githubLink: 'https://github.com/example/rit-smart-canteen',
|
||||
tag: 'looking for Open-source Collaborators/Contributers',
|
||||
collaboratorsNeeded: 3,
|
||||
acceptedCount: 1,
|
||||
contactInfo: '@karthik_ece_rit',
|
||||
status: 'OPEN',
|
||||
applicationsCount: 5,
|
||||
@@ -90,6 +99,7 @@ export default function DevCollab() {
|
||||
const [newDept, setNewDept] = useState('CSE');
|
||||
const [newYear, setNewYear] = useState('1st Year');
|
||||
const [newTag, setNewTag] = useState(TAG_OPTIONS[0]);
|
||||
const [newCollaboratorsNeeded, setNewCollaboratorsNeeded] = useState(1);
|
||||
const [newIdea, setNewIdea] = useState('');
|
||||
const [newGithub, setNewGithub] = useState('');
|
||||
const [newContact, setNewContact] = useState('');
|
||||
@@ -140,6 +150,7 @@ export default function DevCollab() {
|
||||
department: newDept,
|
||||
year: newYear,
|
||||
tag: newTag,
|
||||
collaboratorsNeeded: Number(newCollaboratorsNeeded) || 1,
|
||||
projectIdea: newIdea.trim(),
|
||||
githubLink: newGithub.trim() || null,
|
||||
contactInfo: newContact.trim() || undefined,
|
||||
@@ -159,6 +170,7 @@ export default function DevCollab() {
|
||||
setNewIdea('');
|
||||
setNewGithub('');
|
||||
setNewContact('');
|
||||
setNewCollaboratorsNeeded(1);
|
||||
})
|
||||
.catch(() => {
|
||||
// Local state fallback
|
||||
@@ -168,6 +180,8 @@ export default function DevCollab() {
|
||||
department: payload.department,
|
||||
year: payload.year,
|
||||
tag: payload.tag,
|
||||
collaboratorsNeeded: payload.collaboratorsNeeded,
|
||||
acceptedCount: 0,
|
||||
projectIdea: payload.projectIdea,
|
||||
githubLink: payload.githubLink || undefined,
|
||||
contactInfo: payload.contactInfo || '@student_rit',
|
||||
@@ -202,8 +216,7 @@ export default function DevCollab() {
|
||||
})
|
||||
.then((res) => res.json())
|
||||
.then(() => {
|
||||
showToast(`🚀 Collaboration request sent to ${selectedCollab.authorName} via Telegram!`);
|
||||
// Increment count locally
|
||||
showToast(`🚀 Collaboration request sent to ${selectedCollab.authorName}!`);
|
||||
setRequests((prev) =>
|
||||
prev.map((item) =>
|
||||
item.id === selectedCollab.id ? { ...item, applicationsCount: item.applicationsCount + 1 } : item
|
||||
@@ -226,7 +239,6 @@ export default function DevCollab() {
|
||||
.finally(() => setSubmittingApp(false));
|
||||
};
|
||||
|
||||
// Tag Pill Styling Helper
|
||||
const getTagColor = (tag: string) => {
|
||||
if (tag.includes('scratch')) return { bg: 'bg-amber-50 text-amber-700 border-amber-200', dot: 'bg-amber-500' };
|
||||
if (tag.includes('beta')) return { bg: 'bg-[#F5F3FF] text-[#8B5CF6] border-[#DDD6FE]', dot: 'bg-[#8B5CF6]' };
|
||||
@@ -315,10 +327,10 @@ export default function DevCollab() {
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-lg font-bold text-white mb-1" style={{ fontFamily: 'Poppins, sans-serif' }}>
|
||||
🤖 Post directly via Telegram or Discord Bot!
|
||||
🤖 Post or remove requests via Telegram or Discord!
|
||||
</h3>
|
||||
<p className="text-xs text-slate-300 max-w-xl leading-relaxed" style={{ fontFamily: 'Inter, sans-serif' }}>
|
||||
Send <code className="px-2 py-0.5 rounded bg-slate-800 text-orange-400 font-mono border border-slate-700">/collab</code> to our 24/7 Telegram bot or Discord bot to submit project requests directly from your chat!
|
||||
Send <code className="px-2 py-0.5 rounded bg-slate-800 text-orange-400 font-mono border border-slate-700">/collab</code> to post requests or <code className="px-2 py-0.5 rounded bg-slate-800 text-orange-400 font-mono border border-slate-700">/remove</code> to cancel active requests anytime!
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -377,23 +389,37 @@ export default function DevCollab() {
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 pb-12">
|
||||
{filteredRequests.map((item) => {
|
||||
const tagStyle = getTagColor(item.tag);
|
||||
const needed = item.collaboratorsNeeded || 1;
|
||||
const accepted = item.acceptedCount || 0;
|
||||
const isClosed = item.status === 'CLOSED' || item.status === 'CANCELLED' || accepted >= needed;
|
||||
|
||||
return (
|
||||
<motion.div
|
||||
key={item.id}
|
||||
whileHover={{ y: -4, boxShadow: '0 20px 40px -10px rgba(0,0,0,0.08)' }}
|
||||
className="bg-white rounded-3xl border border-[#E8ECF4] p-6 flex flex-col justify-between relative shadow-xs transition-all"
|
||||
className={`bg-white rounded-3xl border ${isClosed ? 'border-red-200 bg-slate-50/50' : 'border-[#E8ECF4]'} p-6 flex flex-col justify-between relative shadow-xs transition-all`}
|
||||
>
|
||||
<div>
|
||||
{/* Top Bar: Tag Badge */}
|
||||
<div className="flex items-start justify-between gap-2 mb-4">
|
||||
{/* Top Bar: Tag Badge & Status */}
|
||||
<div className="flex items-center justify-between gap-2 mb-4">
|
||||
<span className={`inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-[11px] font-semibold border ${tagStyle.bg}`}>
|
||||
<span className={`w-1.5 h-1.5 rounded-full ${tagStyle.dot}`} />
|
||||
{item.tag}
|
||||
</span>
|
||||
|
||||
{isClosed ? (
|
||||
<span className="px-2.5 py-1 rounded-full text-[11px] font-bold bg-red-50 text-red-600 border border-red-200 shadow-xs">
|
||||
CLOSED • SPOTS FILLED
|
||||
</span>
|
||||
) : (
|
||||
<span className="px-2.5 py-1 rounded-full text-[11px] font-semibold bg-blue-50 text-blue-700 border border-blue-200">
|
||||
{accepted} / {needed} Spots Filled
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Project Idea */}
|
||||
<h3 className="text-base font-bold text-[#1E293B] leading-snug mb-3" style={{ fontFamily: 'Poppins, sans-serif' }}>
|
||||
<h3 className={`text-base font-bold leading-snug mb-3 ${isClosed ? 'text-slate-600' : 'text-[#1E293B]'}`} style={{ fontFamily: 'Poppins, sans-serif' }}>
|
||||
{item.projectIdea}
|
||||
</h3>
|
||||
</div>
|
||||
@@ -429,20 +455,30 @@ export default function DevCollab() {
|
||||
|
||||
<div className="text-right">
|
||||
<div className="text-[11px] font-semibold text-emerald-600 bg-emerald-50 px-2 py-0.5 rounded-full">
|
||||
{item.applicationsCount} Requests
|
||||
{item.applicationsCount} Applications
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Primary Action Button */}
|
||||
<button
|
||||
onClick={() => setSelectedCollab(item)}
|
||||
className="w-full py-2.5 rounded-xl bg-[#FFF7ED] hover:bg-[#F97316] text-[#F97316] hover:text-white border border-[#FED7AA] hover:border-transparent text-xs font-semibold transition-all flex items-center justify-center gap-2 cursor-pointer shadow-xs"
|
||||
style={{ fontFamily: 'Poppins, sans-serif' }}
|
||||
>
|
||||
<MessageSquare className="w-3.5 h-3.5" />
|
||||
Send Collaboration Request
|
||||
</button>
|
||||
{isClosed ? (
|
||||
<button
|
||||
disabled
|
||||
className="w-full py-2.5 rounded-xl bg-slate-100 text-slate-400 text-xs font-semibold cursor-not-allowed border border-slate-200 flex items-center justify-center gap-2"
|
||||
>
|
||||
<CheckCircle2 className="w-3.5 h-3.5" />
|
||||
Collaborations Closed (Full)
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
onClick={() => setSelectedCollab(item)}
|
||||
className="w-full py-2.5 rounded-xl bg-[#FFF7ED] hover:bg-[#F97316] text-[#F97316] hover:text-white border border-[#FED7AA] hover:border-transparent text-xs font-semibold transition-all flex items-center justify-center gap-2 cursor-pointer shadow-xs"
|
||||
style={{ fontFamily: 'Poppins, sans-serif' }}
|
||||
>
|
||||
<MessageSquare className="w-3.5 h-3.5" />
|
||||
Send Collaboration Request
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</motion.div>
|
||||
);
|
||||
@@ -576,10 +612,26 @@ export default function DevCollab() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 5. Project Idea */}
|
||||
{/* 5. Collaborators Needed */}
|
||||
<div>
|
||||
<label className="block text-xs font-semibold text-[#1E293B] mb-1">
|
||||
5) Project Idea <span className="text-red-500">*</span>
|
||||
5) Number of Collaborators Needed <span className="text-red-500">*</span>
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
min={1}
|
||||
max={20}
|
||||
required
|
||||
value={newCollaboratorsNeeded}
|
||||
onChange={(e) => setNewCollaboratorsNeeded(Math.max(1, parseInt(e.target.value) || 1))}
|
||||
className="w-full px-4 py-2.5 rounded-xl border border-[#E5E7EB] bg-[#F8FAFC] text-sm text-[#1E293B] focus:bg-white focus:border-[#F97316] focus:outline-none transition-all"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 6. Project Idea */}
|
||||
<div>
|
||||
<label className="block text-xs font-semibold text-[#1E293B] mb-1">
|
||||
6) Project Idea <span className="text-red-500">*</span>
|
||||
</label>
|
||||
<textarea
|
||||
required
|
||||
@@ -656,7 +708,7 @@ export default function DevCollab() {
|
||||
initial={{ opacity: 0, scale: 0.95, y: 20 }}
|
||||
animate={{ opacity: 1, scale: 1, y: 0 }}
|
||||
exit={{ opacity: 0, scale: 0.95, y: 20 }}
|
||||
className="relative w-full max-w-lg bg-white rounded-3xl shadow-2xl p-6 sm:p-8 z-10"
|
||||
className="relative w-full max-w-lg bg-white rounded-3xl shadow-2xl p-6 sm:p-8 max-h-[90vh] overflow-y-auto z-10"
|
||||
>
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<div>
|
||||
|
||||
621
src/pages/LeetcodeLeaderboard/LeetcodeLeaderboard.tsx
Normal file
621
src/pages/LeetcodeLeaderboard/LeetcodeLeaderboard.tsx
Normal file
@@ -0,0 +1,621 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { motion, AnimatePresence } from 'framer-motion';
|
||||
import {
|
||||
Trophy, Search, Plus, RefreshCw, ExternalLink, Code2,
|
||||
Sparkles, Flame, Award, CheckCircle2, Shield, User, Filter, X, Clock
|
||||
} from 'lucide-react';
|
||||
import { getBackendUrl } from '@/lib/utils';
|
||||
|
||||
interface LeetcodeProfile {
|
||||
id: number;
|
||||
studentName: String;
|
||||
leetcodeUsername: string;
|
||||
department: string;
|
||||
year: string;
|
||||
totalSolved: number;
|
||||
easySolved: number;
|
||||
mediumSolved: number;
|
||||
hardSolved: number;
|
||||
ranking: number;
|
||||
reputation: number;
|
||||
lastUpdated: string;
|
||||
}
|
||||
|
||||
const DEPARTMENTS = ['All', 'CSE', 'IT', 'AI&DS', 'ECE', 'EEE', 'MECH', 'CIVIL', 'CSBS'];
|
||||
const YEARS = ['All', '1st Year', '2nd Year', '3rd Year', '4th Year'];
|
||||
|
||||
export default function LeetcodeLeaderboard() {
|
||||
const [profiles, setProfiles] = useState<LeetcodeProfile[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [selectedDept, setSelectedDept] = useState('All');
|
||||
const [selectedYear, setSelectedYear] = useState('All');
|
||||
const [showModal, setShowModal] = useState(false);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [isSyncing, setIsSyncing] = useState(false);
|
||||
const [toastMessage, setToastMessage] = useState<string | null>(null);
|
||||
|
||||
// Form State
|
||||
const [studentName, setStudentName] = useState('');
|
||||
const [leetcodeUsername, setLeetcodeUsername] = useState('');
|
||||
const [department, setDepartment] = useState('CSE');
|
||||
const [year, setYear] = useState('1st Year');
|
||||
|
||||
useEffect(() => {
|
||||
fetchLeaderboard();
|
||||
}, []);
|
||||
|
||||
const fetchLeaderboard = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await fetch(getBackendUrl('/api/leetcode/leaderboard'));
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
setProfiles(data);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to fetch leaderboard:', err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleRegister = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!studentName.trim() || !leetcodeUsername.trim()) return;
|
||||
|
||||
setIsSubmitting(true);
|
||||
try {
|
||||
const res = await fetch(getBackendUrl('/api/leetcode/register'), {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
studentName,
|
||||
leetcodeUsername,
|
||||
department,
|
||||
year
|
||||
}),
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
setToastMessage('✅ Profile added successfully! Fetched latest LeetCode stats.');
|
||||
setShowModal(false);
|
||||
setStudentName('');
|
||||
setLeetcodeUsername('');
|
||||
fetchLeaderboard();
|
||||
} else {
|
||||
const errData = await res.json();
|
||||
setToastMessage(`❌ ${errData.error || 'Failed to add profile'}`);
|
||||
}
|
||||
} catch (err) {
|
||||
setToastMessage('❌ Error connecting to server');
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
setTimeout(() => setToastMessage(null), 4000);
|
||||
}
|
||||
};
|
||||
|
||||
const handleTriggerSync = async () => {
|
||||
setIsSyncing(true);
|
||||
try {
|
||||
const res = await fetch(getBackendUrl('/api/leetcode/sync'), {
|
||||
method: 'POST'
|
||||
});
|
||||
if (res.ok) {
|
||||
setToastMessage('⚡ 24h background sync started! Requests are spaced out by 3s to prevent rate limits.');
|
||||
}
|
||||
} catch (err) {
|
||||
setToastMessage('❌ Failed to trigger sync');
|
||||
} finally {
|
||||
setIsSyncing(false);
|
||||
setTimeout(() => setToastMessage(null), 5000);
|
||||
}
|
||||
};
|
||||
|
||||
const filteredProfiles = profiles.filter((p) => {
|
||||
const matchesSearch =
|
||||
p.studentName.toLowerCase().includes(searchQuery.toLowerCase()) ||
|
||||
p.leetcodeUsername.toLowerCase().includes(searchQuery.toLowerCase());
|
||||
const matchesDept = selectedDept === 'All' || p.department === selectedDept;
|
||||
const matchesYear = selectedYear === 'All' || p.year === selectedYear;
|
||||
return matchesSearch && matchesDept && matchesYear;
|
||||
});
|
||||
|
||||
const totalCampusSolved = profiles.reduce((acc, curr) => acc + (curr.totalSolved || 0), 0);
|
||||
const topProfile = profiles.length > 0 ? profiles[0] : null;
|
||||
|
||||
return (
|
||||
<div className="min-h-screen pt-24 pb-16 bg-[#0B0F17] text-slate-100 px-4 sm:px-6 lg:px-8">
|
||||
{/* Toast Notification */}
|
||||
<AnimatePresence>
|
||||
{toastMessage && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: -20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
exit={{ opacity: 0, y: -20 }}
|
||||
className="fixed top-6 right-6 z-50 px-5 py-3 rounded-xl bg-slate-800/90 border border-slate-700 backdrop-blur-md text-white font-medium shadow-2xl flex items-center gap-2"
|
||||
>
|
||||
{toastMessage}
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
|
||||
<div className="max-w-7xl mx-auto space-y-8">
|
||||
{/* Banner Header */}
|
||||
<div className="relative overflow-hidden rounded-3xl bg-gradient-to-r from-slate-900 via-slate-800 to-slate-900 border border-slate-800 p-8 shadow-2xl">
|
||||
<div className="absolute top-0 right-0 -mt-12 -mr-12 w-96 h-96 bg-amber-500/10 rounded-full blur-3xl pointer-events-none" />
|
||||
<div className="absolute bottom-0 left-1/3 -mb-12 w-80 h-80 bg-teal-500/10 rounded-full blur-3xl pointer-events-none" />
|
||||
|
||||
<div className="relative z-10 flex flex-col lg:flex-row items-start lg:items-center justify-between gap-6">
|
||||
<div>
|
||||
<div className="inline-flex items-center gap-2 px-3.5 py-1.5 rounded-full bg-amber-500/10 border border-amber-500/20 text-amber-400 text-xs font-semibold uppercase tracking-wider mb-4">
|
||||
<Flame className="w-4 h-4 text-amber-500 animate-pulse" />
|
||||
RIT LeetCode Arena
|
||||
</div>
|
||||
<h1 className="text-3xl sm:text-5xl font-extrabold tracking-tight text-white font-poppins">
|
||||
Campus <span className="bg-clip-text text-transparent bg-gradient-to-r from-amber-400 via-orange-400 to-teal-400">LeetCode Leaderboard</span>
|
||||
</h1>
|
||||
<p className="mt-2 text-slate-400 max-w-2xl text-sm sm:text-base">
|
||||
Track top problem solvers across departments. Automatically updated every 24 hours with rate-limited, spaced background sync.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-3 shrink-0">
|
||||
<button
|
||||
onClick={() => setShowModal(true)}
|
||||
className="flex items-center gap-2 px-5 py-3 rounded-2xl bg-gradient-to-r from-amber-500 to-orange-500 hover:from-amber-600 hover:to-orange-600 text-slate-950 font-bold text-sm shadow-lg shadow-amber-500/25 transition-all transform hover:-translate-y-0.5 active:translate-y-0"
|
||||
>
|
||||
<Plus className="w-5 h-5 stroke-[2.5]" />
|
||||
Register Handle
|
||||
</button>
|
||||
<button
|
||||
onClick={handleTriggerSync}
|
||||
disabled={isSyncing}
|
||||
className="flex items-center gap-2 px-4 py-3 rounded-2xl bg-slate-800/80 hover:bg-slate-800 text-slate-300 border border-slate-700/80 font-semibold text-sm transition-all hover:text-white"
|
||||
>
|
||||
<RefreshCw className={`w-4 h-4 ${isSyncing ? 'animate-spin text-amber-400' : ''}`} />
|
||||
24h Spaced Sync
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Quick Metrics Bar */}
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-4 mt-8 pt-6 border-t border-slate-800/80">
|
||||
<div className="p-4 rounded-2xl bg-slate-950/40 border border-slate-800/60 backdrop-blur-sm">
|
||||
<span className="text-xs font-semibold text-slate-400 flex items-center gap-1.5">
|
||||
<Trophy className="w-4 h-4 text-amber-400" /> #1 Top Solver
|
||||
</span>
|
||||
<p className="text-lg font-bold text-white mt-1 truncate">
|
||||
{topProfile ? `${topProfile.studentName}` : 'N/A'}
|
||||
</p>
|
||||
<p className="text-xs text-amber-400 font-medium">
|
||||
{topProfile ? `${topProfile.totalSolved} Problems Solved` : ''}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="p-4 rounded-2xl bg-slate-950/40 border border-slate-800/60 backdrop-blur-sm">
|
||||
<span className="text-xs font-semibold text-slate-400 flex items-center gap-1.5">
|
||||
<Code2 className="w-4 h-4 text-teal-400" /> Total Campus Solved
|
||||
</span>
|
||||
<p className="text-xl font-bold text-white mt-1">
|
||||
{totalCampusSolved.toLocaleString()}
|
||||
</p>
|
||||
<p className="text-xs text-slate-500">Problems across all coders</p>
|
||||
</div>
|
||||
|
||||
<div className="p-4 rounded-2xl bg-slate-950/40 border border-slate-800/60 backdrop-blur-sm">
|
||||
<span className="text-xs font-semibold text-slate-400 flex items-center gap-1.5">
|
||||
<User className="w-4 h-4 text-indigo-400" /> Active Coders
|
||||
</span>
|
||||
<p className="text-xl font-bold text-white mt-1">
|
||||
{profiles.length}
|
||||
</p>
|
||||
<p className="text-xs text-slate-500">Registered RIT coders</p>
|
||||
</div>
|
||||
|
||||
<div className="p-4 rounded-2xl bg-slate-950/40 border border-slate-800/60 backdrop-blur-sm">
|
||||
<span className="text-xs font-semibold text-slate-400 flex items-center gap-1.5">
|
||||
<Clock className="w-4 h-4 text-emerald-400" /> Sync Frequency
|
||||
</span>
|
||||
<p className="text-base font-bold text-white mt-1">
|
||||
Every 24 Hours
|
||||
</p>
|
||||
<p className="text-[11px] text-emerald-400/90 font-mono">3s spaced rate-limiting</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Search & Filter Controls */}
|
||||
<div className="flex flex-col sm:flex-row gap-4 items-center justify-between bg-slate-900/60 border border-slate-800/80 p-4 rounded-2xl backdrop-blur-xl">
|
||||
<div className="relative w-full sm:w-80">
|
||||
<Search className="w-4 h-4 absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-400" />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Search by student name or handle..."
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
className="w-full pl-10 pr-4 py-2.5 rounded-xl bg-slate-950/60 border border-slate-800 text-sm text-white placeholder-slate-500 focus:outline-none focus:border-amber-500/50 transition-colors"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-3 w-full sm:w-auto">
|
||||
<div className="flex items-center gap-2">
|
||||
<Filter className="w-4 h-4 text-slate-400" />
|
||||
<select
|
||||
value={selectedDept}
|
||||
onChange={(e) => setSelectedDept(e.target.value)}
|
||||
className="bg-slate-950/60 border border-slate-800 rounded-xl px-3 py-2 text-xs font-medium text-slate-300 focus:outline-none focus:border-amber-500/50"
|
||||
>
|
||||
{DEPARTMENTS.map((d) => (
|
||||
<option key={d} value={d} className="bg-slate-900">
|
||||
Dept: {d}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<select
|
||||
value={selectedYear}
|
||||
onChange={(e) => setSelectedYear(e.target.value)}
|
||||
className="bg-slate-950/60 border border-slate-800 rounded-xl px-3 py-2 text-xs font-medium text-slate-300 focus:outline-none focus:border-amber-500/50"
|
||||
>
|
||||
{YEARS.map((y) => (
|
||||
<option key={y} value={y} className="bg-slate-900">
|
||||
Year: {y}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Leaderboard Table */}
|
||||
<div className="overflow-hidden rounded-2xl border border-slate-800 bg-slate-900/40 backdrop-blur-xl shadow-xl">
|
||||
{loading ? (
|
||||
<div className="p-16 text-center text-slate-500 flex flex-col items-center gap-3">
|
||||
<RefreshCw className="w-8 h-8 animate-spin text-amber-500" />
|
||||
<p className="text-sm font-medium">Fetching LeetCode rankings...</p>
|
||||
</div>
|
||||
) : filteredProfiles.length === 0 ? (
|
||||
<div className="p-16 text-center text-slate-500 space-y-3">
|
||||
<Trophy className="w-12 h-12 text-slate-700 mx-auto" />
|
||||
<p className="text-base font-semibold text-slate-300">No coders found</p>
|
||||
<p className="text-xs text-slate-500">Be the first to register your LeetCode handle!</p>
|
||||
<button
|
||||
onClick={() => setShowModal(true)}
|
||||
className="mt-2 inline-flex items-center gap-2 px-4 py-2 rounded-xl bg-amber-500 text-slate-950 font-bold text-xs"
|
||||
>
|
||||
<Plus className="w-4 h-4" /> Register Profile
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{/* Mobile Card View (Small Screens) */}
|
||||
<div className="block md:hidden divide-y divide-slate-800/80">
|
||||
{filteredProfiles.map((p, index) => {
|
||||
const rank = index + 1;
|
||||
const total = p.totalSolved || 1;
|
||||
const easyPct = Math.round(((p.easySolved || 0) / total) * 100);
|
||||
const medPct = Math.round(((p.mediumSolved || 0) / total) * 100);
|
||||
const hardPct = Math.round(((p.hardSolved || 0) / total) * 100);
|
||||
|
||||
return (
|
||||
<motion.div
|
||||
key={p.id}
|
||||
initial={{ opacity: 0, y: 10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: index * 0.03 }}
|
||||
className="p-4 space-y-3 bg-slate-900/60"
|
||||
>
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="flex items-center gap-3">
|
||||
{rank === 1 ? (
|
||||
<span className="text-2xl" title="Rank 1 Gold">🥇</span>
|
||||
) : rank === 2 ? (
|
||||
<span className="text-2xl" title="Rank 2 Silver">🥈</span>
|
||||
) : rank === 3 ? (
|
||||
<span className="text-2xl" title="Rank 3 Bronze">🥉</span>
|
||||
) : (
|
||||
<span className="text-xs font-mono font-extrabold px-2 py-1 rounded bg-slate-800 text-slate-400">
|
||||
#{rank}
|
||||
</span>
|
||||
)}
|
||||
|
||||
<div>
|
||||
<p className="font-bold text-white text-base leading-tight">{p.studentName}</p>
|
||||
<p className="text-xs text-slate-400 font-mono">@{p.leetcodeUsername}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="text-right">
|
||||
<p className="text-xl font-black text-amber-400 font-mono leading-none">{p.totalSolved}</p>
|
||||
<p className="text-[10px] text-slate-500 font-medium">Solved</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between text-xs text-slate-400 pt-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="px-2 py-0.5 rounded bg-slate-800 border border-slate-700 text-[11px] font-medium text-slate-300">
|
||||
{p.department}
|
||||
</span>
|
||||
<span className="text-[11px] text-slate-500">{p.year}</span>
|
||||
</div>
|
||||
|
||||
<a
|
||||
href={`https://leetcode.com/u/${p.leetcodeUsername}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-1 text-xs text-amber-400 hover:underline font-semibold"
|
||||
>
|
||||
LeetCode Profile <ExternalLink className="w-3.5 h-3.5" />
|
||||
</a>
|
||||
</div>
|
||||
|
||||
{/* Progress Bar */}
|
||||
<div className="space-y-1 pt-1">
|
||||
<div className="flex justify-between text-[10px] font-mono text-slate-400">
|
||||
<span className="text-emerald-400">Easy: {p.easySolved}</span>
|
||||
<span className="text-amber-400">Med: {p.mediumSolved}</span>
|
||||
<span className="text-rose-400">Hard: {p.hardSolved}</span>
|
||||
</div>
|
||||
<div className="w-full h-2 rounded-full bg-slate-800 overflow-hidden flex">
|
||||
<div style={{ width: `${easyPct}%` }} className="bg-emerald-500 h-full" />
|
||||
<div style={{ width: `${medPct}%` }} className="bg-amber-500 h-full" />
|
||||
<div style={{ width: `${hardPct}%` }} className="bg-rose-500 h-full" />
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Desktop Table View (Medium Screens & Up) */}
|
||||
<div className="hidden md:block overflow-x-auto">
|
||||
<table className="w-full text-left text-slate-300 border-collapse">
|
||||
<thead>
|
||||
<tr className="border-b border-slate-800 bg-slate-950/50 text-[11px] font-bold uppercase tracking-wider text-slate-400">
|
||||
<th className="py-4 px-6 text-center w-16">Rank</th>
|
||||
<th className="py-4 px-6">Student</th>
|
||||
<th className="py-4 px-6">Dept & Year</th>
|
||||
<th className="py-4 px-6 text-center">Total Solved</th>
|
||||
<th className="py-4 px-6 min-w-[200px]">Problems Breakdown</th>
|
||||
<th className="py-4 px-6 text-right">LeetCode Rank</th>
|
||||
<th className="py-4 px-6 text-center w-24">Profile</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-slate-800/60 text-sm">
|
||||
{filteredProfiles.map((p, index) => {
|
||||
const rank = index + 1;
|
||||
const total = p.totalSolved || 1;
|
||||
const easyPct = Math.round(((p.easySolved || 0) / total) * 100);
|
||||
const medPct = Math.round(((p.mediumSolved || 0) / total) * 100);
|
||||
const hardPct = Math.round(((p.hardSolved || 0) / total) * 100);
|
||||
|
||||
return (
|
||||
<motion.tr
|
||||
key={p.id}
|
||||
initial={{ opacity: 0, y: 10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: index * 0.03 }}
|
||||
className="hover:bg-slate-800/40 transition-colors group"
|
||||
>
|
||||
{/* Rank */}
|
||||
<td className="py-4 px-6 text-center font-extrabold">
|
||||
{rank === 1 ? (
|
||||
<div className="w-8 h-8 rounded-full bg-amber-500/20 text-amber-400 border border-amber-500/40 flex items-center justify-center mx-auto text-base shadow-[0_0_12px_rgba(245,158,11,0.3)]">
|
||||
🥇
|
||||
</div>
|
||||
) : rank === 2 ? (
|
||||
<div className="w-8 h-8 rounded-full bg-slate-300/20 text-slate-200 border border-slate-300/40 flex items-center justify-center mx-auto text-base">
|
||||
🥈
|
||||
</div>
|
||||
) : rank === 3 ? (
|
||||
<div className="w-8 h-8 rounded-full bg-amber-700/20 text-amber-600 border border-amber-700/40 flex items-center justify-center mx-auto text-base">
|
||||
🥉
|
||||
</div>
|
||||
) : (
|
||||
<span className="text-slate-500 font-mono">#{rank}</span>
|
||||
)}
|
||||
</td>
|
||||
|
||||
{/* Student Info */}
|
||||
<td className="py-4 px-6">
|
||||
<div>
|
||||
<p className="font-bold text-white group-hover:text-amber-400 transition-colors">
|
||||
{p.studentName}
|
||||
</p>
|
||||
<p className="text-xs text-slate-400 font-mono">
|
||||
@{p.leetcodeUsername}
|
||||
</p>
|
||||
</div>
|
||||
</td>
|
||||
|
||||
{/* Dept & Year */}
|
||||
<td className="py-4 px-6 text-xs text-slate-400">
|
||||
<span className="px-2.5 py-1 rounded-md bg-slate-800 border border-slate-700 text-slate-300 font-medium mr-1.5">
|
||||
{p.department}
|
||||
</span>
|
||||
<span className="text-slate-500">{p.year}</span>
|
||||
</td>
|
||||
|
||||
{/* Total Solved */}
|
||||
<td className="py-4 px-6 text-center">
|
||||
<span className="text-lg font-black text-amber-400 font-mono">
|
||||
{p.totalSolved}
|
||||
</span>
|
||||
</td>
|
||||
|
||||
{/* Problem Breakdown Bars */}
|
||||
<td className="py-4 px-6">
|
||||
<div className="space-y-1.5">
|
||||
<div className="flex items-center justify-between text-[11px] font-mono text-slate-400">
|
||||
<span className="text-emerald-400">Easy: {p.easySolved}</span>
|
||||
<span className="text-amber-400">Med: {p.mediumSolved}</span>
|
||||
<span className="text-rose-400">Hard: {p.hardSolved}</span>
|
||||
</div>
|
||||
<div className="w-full h-2 rounded-full bg-slate-800 overflow-hidden flex">
|
||||
<div
|
||||
style={{ width: `${easyPct}%` }}
|
||||
className="bg-emerald-500 h-full"
|
||||
title={`Easy: ${p.easySolved}`}
|
||||
/>
|
||||
<div
|
||||
style={{ width: `${medPct}%` }}
|
||||
className="bg-amber-500 h-full"
|
||||
title={`Medium: ${p.mediumSolved}`}
|
||||
/>
|
||||
<div
|
||||
style={{ width: `${hardPct}%` }}
|
||||
className="bg-rose-500 h-full"
|
||||
title={`Hard: ${p.hardSolved}`}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
|
||||
{/* LeetCode Global Rank */}
|
||||
<td className="py-4 px-6 text-right font-mono text-xs">
|
||||
{p.ranking > 0 ? (
|
||||
<span className="text-slate-300 font-medium">
|
||||
#{p.ranking.toLocaleString()}
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-slate-600">-</span>
|
||||
)}
|
||||
</td>
|
||||
|
||||
{/* Profile Link */}
|
||||
<td className="py-4 px-6 text-center">
|
||||
<a
|
||||
href={`https://leetcode.com/u/${p.leetcodeUsername}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center justify-center w-8 h-8 rounded-lg bg-slate-800 hover:bg-amber-500/20 text-slate-400 hover:text-amber-400 border border-slate-700/60 transition-colors"
|
||||
title="View on LeetCode"
|
||||
>
|
||||
<ExternalLink className="w-4 h-4" />
|
||||
</a>
|
||||
</td>
|
||||
</motion.tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Registration Modal */}
|
||||
<AnimatePresence>
|
||||
{showModal && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-950/80 backdrop-blur-sm">
|
||||
<motion.div
|
||||
initial={{ scale: 0.95, opacity: 0 }}
|
||||
animate={{ scale: 1, opacity: 1 }}
|
||||
exit={{ scale: 0.95, opacity: 0 }}
|
||||
className="w-full max-w-md bg-slate-900 border border-slate-800 rounded-3xl p-6 shadow-2xl relative max-h-[90vh] overflow-y-auto"
|
||||
>
|
||||
<button
|
||||
onClick={() => setShowModal(false)}
|
||||
className="absolute top-5 right-5 text-slate-400 hover:text-white"
|
||||
>
|
||||
<X className="w-5 h-5" />
|
||||
</button>
|
||||
|
||||
<div className="flex items-center gap-3 mb-6">
|
||||
<div className="w-10 h-10 rounded-2xl bg-amber-500/20 border border-amber-500/40 flex items-center justify-center text-amber-400">
|
||||
<Trophy className="w-5 h-5" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-lg font-bold text-white">Register LeetCode Handle</h3>
|
||||
<p className="text-xs text-slate-400">Join the RIT campus coding rankings</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleRegister} className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-xs font-semibold text-slate-300 mb-1.5">
|
||||
Your Full Name
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
required
|
||||
placeholder="e.g. Shanmuga Sundaram"
|
||||
value={studentName}
|
||||
onChange={(e) => setStudentName(e.target.value)}
|
||||
className="w-full px-4 py-2.5 rounded-xl bg-slate-950 border border-slate-800 text-sm text-white focus:outline-none focus:border-amber-500"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-xs font-semibold text-slate-300 mb-1.5">
|
||||
LeetCode Username (Exact)
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
required
|
||||
placeholder="e.g. neal_wu"
|
||||
value={leetcodeUsername}
|
||||
onChange={(e) => setLeetcodeUsername(e.target.value)}
|
||||
className="w-full px-4 py-2.5 rounded-xl bg-slate-950 border border-slate-800 text-sm text-white focus:outline-none focus:border-amber-500"
|
||||
/>
|
||||
<p className="text-[11px] text-slate-500 mt-1">We will immediately fetch your problem stats from LeetCode.</p>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className="block text-xs font-semibold text-slate-300 mb-1.5">
|
||||
Department
|
||||
</label>
|
||||
<select
|
||||
value={department}
|
||||
onChange={(e) => setDepartment(e.target.value)}
|
||||
className="w-full px-3 py-2.5 rounded-xl bg-slate-950 border border-slate-800 text-sm text-white focus:outline-none focus:border-amber-500"
|
||||
>
|
||||
{DEPARTMENTS.filter(d => d !== 'All').map(d => (
|
||||
<option key={d} value={d}>{d}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-xs font-semibold text-slate-300 mb-1.5">
|
||||
Year
|
||||
</label>
|
||||
<select
|
||||
value={year}
|
||||
onChange={(e) => setYear(e.target.value)}
|
||||
className="w-full px-3 py-2.5 rounded-xl bg-slate-950 border border-slate-800 text-sm text-white focus:outline-none focus:border-amber-500"
|
||||
>
|
||||
{YEARS.filter(y => y !== 'All').map(y => (
|
||||
<option key={y} value={y}>{y}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="pt-2 flex justify-end gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowModal(false)}
|
||||
className="px-4 py-2.5 rounded-xl bg-slate-800 text-slate-300 text-xs font-semibold hover:bg-slate-700"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isSubmitting}
|
||||
className="px-5 py-2.5 rounded-xl bg-amber-500 hover:bg-amber-600 text-slate-950 text-xs font-bold transition-all"
|
||||
>
|
||||
{isSubmitting ? 'Fetching Stats...' : 'Register Profile'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</motion.div>
|
||||
</div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -4,5 +4,5 @@
|
||||
"helper_chat_ids": [971749136, 5567776672],
|
||||
"discord_bot_token": "",
|
||||
"discord_helper_user_ids": [789393727641878568],
|
||||
"spring_backend_url": "http://localhost:8080"
|
||||
"spring_backend_url": "http://localhost:8085"
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ def load_config():
|
||||
"community_bot_token": "8859374355:AAH0dhwstkTBhRerRTjzmb2RG2fjPbigzvo",
|
||||
"telegram_bot_token": "8913773505:AAHASuKLLOto3Ax573_dxg8bnvQy2ML6yLk",
|
||||
"helper_chat_ids": [],
|
||||
"spring_backend_url": "http://localhost:8080"
|
||||
"spring_backend_url": "http://localhost:8085"
|
||||
}
|
||||
with open(CONFIG_PATH, "w") as f:
|
||||
json.dump(default_config, f, indent=2)
|
||||
@@ -54,7 +54,7 @@ config = load_config()
|
||||
COMMUNITY_BOT_TOKEN = os.environ.get("COMMUNITY_BOT_TOKEN") or config.get("community_bot_token", "8859374355:AAH0dhwstkTBhRerRTjzmb2RG2fjPbigzvo")
|
||||
BOT_TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN") or config.get("telegram_bot_token")
|
||||
DISCORD_TOKEN = os.environ.get("DISCORD_BOT_TOKEN") or config.get("discord_bot_token")
|
||||
BACKEND_URL = os.environ.get("SPRING_BACKEND_URL") or config.get("spring_backend_url", "http://localhost:8080")
|
||||
BACKEND_URL = os.environ.get("SPRING_BACKEND_URL") or config.get("spring_backend_url", "http://localhost:8085")
|
||||
|
||||
# Database Setup
|
||||
DB_PATH = os.path.join(os.path.dirname(__file__), "bot_mappings.db")
|
||||
@@ -161,7 +161,8 @@ def parse_collab_text(text: str):
|
||||
"year": None,
|
||||
"tag": None,
|
||||
"projectIdea": None,
|
||||
"githubLink": None
|
||||
"githubLink": None,
|
||||
"collaboratorsNeeded": None
|
||||
}
|
||||
|
||||
lines = text.splitlines()
|
||||
@@ -178,6 +179,7 @@ def parse_collab_text(text: str):
|
||||
data["tag"] = TAG_MAP.get(t, t)
|
||||
if len(parts) >= 5: data["projectIdea"] = parts[4]
|
||||
if len(parts) >= 6: data["githubLink"] = parts[5]
|
||||
if len(parts) >= 7 and parts[6].isdigit(): data["collaboratorsNeeded"] = int(parts[6])
|
||||
return data
|
||||
lines = lines[1:]
|
||||
|
||||
@@ -199,6 +201,9 @@ def parse_collab_text(text: str):
|
||||
data["projectIdea"] = v
|
||||
elif k in ["github", "github link", "link"]:
|
||||
data["githubLink"] = v
|
||||
elif k in ["collaborators", "collaborators needed", "needed"]:
|
||||
if v.isdigit():
|
||||
data["collaboratorsNeeded"] = int(v)
|
||||
else:
|
||||
if not data["projectIdea"]:
|
||||
data["projectIdea"] = line_str
|
||||
@@ -247,7 +252,6 @@ def community_bot_polling_thread():
|
||||
send_telegram_message(chat_id, welcome_text, force_reply=False, token=comm_token)
|
||||
continue
|
||||
|
||||
# Handle senior helper replies to questions
|
||||
reply_to = message.get("reply_to_message")
|
||||
if reply_to:
|
||||
if chat_id not in helpers:
|
||||
@@ -359,6 +363,19 @@ def telegram_polling_thread():
|
||||
token=bot_token
|
||||
)
|
||||
continue
|
||||
elif cb_data.startswith("collab_rm_"):
|
||||
req_id = cb_data.replace("collab_rm_", "")
|
||||
try:
|
||||
requests.delete(f"{backend_url}/api/collab/{req_id}", timeout=5)
|
||||
answer_telegram_callback(cb_id, "Request Removed!", token=bot_token)
|
||||
edit_telegram_message(
|
||||
cb_chat_id, cb_msg_id,
|
||||
"✅ *Collaboration Request cancelled and removed from RIT Dev Hub.*",
|
||||
token=bot_token
|
||||
)
|
||||
except Exception as e:
|
||||
logging.error(f"Error removing collab request: {e}")
|
||||
continue
|
||||
|
||||
# Interactive Collab Wizard Callbacks
|
||||
if cb_data.startswith("cflow_tag_"):
|
||||
@@ -368,6 +385,7 @@ def telegram_polling_thread():
|
||||
"tag": selected_tag,
|
||||
"dept": "CSE",
|
||||
"year": "1st Year",
|
||||
"collaboratorsNeeded": 1,
|
||||
"step": "dept"
|
||||
}
|
||||
answer_telegram_callback(cb_id, "Tag Selected!", token=bot_token)
|
||||
@@ -380,7 +398,7 @@ def telegram_polling_thread():
|
||||
}
|
||||
edit_telegram_message(
|
||||
cb_chat_id, cb_msg_id,
|
||||
f"📌 *Step 2 of 4: Select your Department*\n\nTag: `{selected_tag}`",
|
||||
f"📌 *Step 2 of 5: Select your Department*\n\nTag: `{selected_tag}`",
|
||||
reply_markup=dept_keyboard,
|
||||
token=bot_token
|
||||
)
|
||||
@@ -401,7 +419,7 @@ def telegram_polling_thread():
|
||||
}
|
||||
edit_telegram_message(
|
||||
cb_chat_id, cb_msg_id,
|
||||
f"📌 *Step 3 of 4: Select your Year*\n\nDepartment: `{dept_val}`",
|
||||
f"📌 *Step 3 of 5: Select your Year*\n\nDepartment: `{dept_val}`",
|
||||
reply_markup=yr_keyboard,
|
||||
token=bot_token
|
||||
)
|
||||
@@ -412,15 +430,38 @@ def telegram_polling_thread():
|
||||
if cb_chat_id not in USER_COLLAB_STATE:
|
||||
USER_COLLAB_STATE[cb_chat_id] = {}
|
||||
USER_COLLAB_STATE[cb_chat_id]["year"] = year_val
|
||||
USER_COLLAB_STATE[cb_chat_id]["step"] = "idea"
|
||||
USER_COLLAB_STATE[cb_chat_id]["step"] = "num"
|
||||
answer_telegram_callback(cb_id, "Year Selected!", token=bot_token)
|
||||
|
||||
num_keyboard = {
|
||||
"inline_keyboard": [
|
||||
[{"text": "1 Collaborator", "callback_data": "cflow_num_1"}, {"text": "2 Collaborators", "callback_data": "cflow_num_2"}],
|
||||
[{"text": "3 Collaborators", "callback_data": "cflow_num_3"}, {"text": "4 Collaborators", "callback_data": "cflow_num_4"}]
|
||||
]
|
||||
}
|
||||
edit_telegram_message(
|
||||
cb_chat_id, cb_msg_id,
|
||||
f"📌 *Step 4 of 5: How many collaborators are you looking for?*",
|
||||
reply_markup=num_keyboard,
|
||||
token=bot_token
|
||||
)
|
||||
continue
|
||||
|
||||
if cb_data.startswith("cflow_num_"):
|
||||
num_val = int(cb_data.replace("cflow_num_", ""))
|
||||
if cb_chat_id not in USER_COLLAB_STATE:
|
||||
USER_COLLAB_STATE[cb_chat_id] = {}
|
||||
USER_COLLAB_STATE[cb_chat_id]["collaboratorsNeeded"] = num_val
|
||||
USER_COLLAB_STATE[cb_chat_id]["step"] = "idea"
|
||||
answer_telegram_callback(cb_id, "Count Selected!", token=bot_token)
|
||||
|
||||
st = USER_COLLAB_STATE[cb_chat_id]
|
||||
edit_telegram_message(
|
||||
cb_chat_id, cb_msg_id,
|
||||
f"📌 *Step 4 of 4: Enter Project Idea & Name*\n\n"
|
||||
f"📌 *Step 5 of 5: Enter Project Idea & Name*\n\n"
|
||||
f"🏷️ Tag: `{st.get('tag')}`\n"
|
||||
f"🏫 Dept: `{st.get('dept')}` | Year: `{year_val}`\n\n"
|
||||
f"🏫 Dept: `{st.get('dept')}` | Year: `{st.get('year')}`\n"
|
||||
f"👥 Collaborators Needed: `{num_val}`\n\n"
|
||||
f"💬 *Now reply to this chat with your details in this format:*\n"
|
||||
f"`Name: Your Name`\n"
|
||||
f"`Idea: Building an AI attendance app`\n"
|
||||
@@ -439,6 +480,29 @@ def telegram_polling_thread():
|
||||
|
||||
logging.info(f"Received message from chat {chat_id}: '{text}'")
|
||||
|
||||
# Handle /remove command in Telegram
|
||||
if text.lower() in ["/remove", "/cancel"]:
|
||||
try:
|
||||
res = requests.get(f"{backend_url}/api/collab/active/telegram/{chat_id}", timeout=5)
|
||||
if res.status_code == 200:
|
||||
requests_list = res.json()
|
||||
if not requests_list:
|
||||
send_telegram_message(chat_id, "ℹ️ *You have no active collaboration requests to remove.*", token=bot_token)
|
||||
else:
|
||||
keyboard = []
|
||||
for req_item in requests_list:
|
||||
req_id = req_item["id"]
|
||||
snippet = req_item.get("projectIdea", "Project")[:28]
|
||||
keyboard.append([{"text": f"❌ Cancel: {snippet}", "callback_data": f"collab_rm_{req_id}"}])
|
||||
|
||||
rm_markup = {"inline_keyboard": keyboard}
|
||||
send_telegram_message(chat_id, "🗑️ *Your Active Collaboration Requests*\n\nTap a request below to cancel and remove it from RIT Dev Hub:", reply_markup=rm_markup, token=bot_token)
|
||||
else:
|
||||
send_telegram_message(chat_id, "❌ Failed to fetch active requests.", token=bot_token)
|
||||
except Exception as e:
|
||||
send_telegram_message(chat_id, f"❌ Error: {e}", token=bot_token)
|
||||
continue
|
||||
|
||||
# Handle /collab Command or structured collab post
|
||||
if text.lower().startswith("/collab") or (chat_id in USER_COLLAB_STATE and USER_COLLAB_STATE[chat_id].get("step") == "idea"):
|
||||
parsed = parse_collab_text(text)
|
||||
@@ -448,6 +512,7 @@ def telegram_polling_thread():
|
||||
dept = parsed.get("department") or st.get("dept") or "CSE"
|
||||
year = parsed.get("year") or st.get("year") or "1st Year"
|
||||
tag = parsed.get("tag") or st.get("tag") or TAG_MAP["1"]
|
||||
num_needed = st.get("collaboratorsNeeded") or parsed.get("collaboratorsNeeded") or 1
|
||||
idea = parsed.get("projectIdea")
|
||||
github = parsed.get("githubLink")
|
||||
|
||||
@@ -475,6 +540,7 @@ def telegram_polling_thread():
|
||||
"authorName": author_display,
|
||||
"department": dept,
|
||||
"year": year,
|
||||
"collaboratorsNeeded": num_needed,
|
||||
"projectIdea": idea,
|
||||
"githubLink": github or None,
|
||||
"tag": tag,
|
||||
@@ -490,8 +556,10 @@ def telegram_polling_thread():
|
||||
f"👤 *Author:* {author_display} ({dept}, {year})\n"
|
||||
f"📌 *Project Idea:* {idea}\n"
|
||||
f"🏷️ *Tag:* `{tag}`\n"
|
||||
f"👥 *Collaborators Looking For:* `{num_needed}`\n"
|
||||
f"📱 *Telegram Contact:* {contact_display}\n\n"
|
||||
f"When other developers apply on the website, you will receive a Telegram message right here to Accept or Decline!"
|
||||
f"When other developers apply on the website, you will receive a Telegram message right here to Accept or Decline!\n"
|
||||
f"*(Type `/remove` anytime to cancel your active requests)*"
|
||||
)
|
||||
send_telegram_message(chat_id, resp_msg, force_reply=False, token=bot_token)
|
||||
if chat_id in USER_COLLAB_STATE:
|
||||
@@ -507,7 +575,8 @@ def telegram_polling_thread():
|
||||
welcome_text = (
|
||||
f"👋 *Welcome to the RIT Chatbot 24/7!*\n\n"
|
||||
f"I can help you answer any questions about RIT Chennai — courses, hostels, transport, sports, and more.\n\n"
|
||||
f"🚀 *Developer Collaboration:* Type `/collab` to post your project idea and find co-developers!\n\n"
|
||||
f"🚀 *Developer Collaboration:* Type `/collab` to post your project idea!\n"
|
||||
f"🗑️ *Remove Request:* Type `/remove` to cancel your active requests.\n\n"
|
||||
f"💬 *Or just type your question here!*"
|
||||
)
|
||||
send_telegram_message(chat_id, welcome_text, force_reply=False, token=bot_token)
|
||||
@@ -589,12 +658,43 @@ async def broadcast_discord_collab_application(application_id: int, project_idea
|
||||
except Exception as e:
|
||||
logging.error(f"Failed to send Discord collab DM to {user_id_val}: {e}")
|
||||
|
||||
# Discord Remove Select View
|
||||
class DiscordCollabRemoveSelect(discord.ui.Select):
|
||||
def __init__(self, active_requests: list):
|
||||
options = []
|
||||
for req in active_requests:
|
||||
req_id = str(req["id"])
|
||||
snippet = req.get("projectIdea", "Project")[:45]
|
||||
options.append(discord.SelectOption(
|
||||
label=f"Cancel: {snippet}",
|
||||
value=req_id,
|
||||
description=f"Tag: {req.get('tag')} | Dept: {req.get('department')}",
|
||||
emoji="❌"
|
||||
))
|
||||
super().__init__(placeholder="Select a request to remove...", min_values=1, max_values=1, options=options)
|
||||
|
||||
async def callback(self, interaction: discord.Interaction):
|
||||
req_id = self.values[0]
|
||||
try:
|
||||
res = requests.delete(f"{BACKEND_URL}/api/collab/{req_id}", timeout=5)
|
||||
if res.status_code in [200, 204]:
|
||||
await interaction.response.send_message("✅ **Collaboration Request cancelled and removed from RIT Dev Hub.**", ephemeral=False)
|
||||
else:
|
||||
await interaction.response.send_message("❌ Failed to cancel request.", ephemeral=True)
|
||||
except Exception as e:
|
||||
await interaction.response.send_message(f"❌ Error: {e}", ephemeral=True)
|
||||
|
||||
class DiscordCollabRemoveView(discord.ui.View):
|
||||
def __init__(self, active_requests: list):
|
||||
super().__init__(timeout=180)
|
||||
self.add_item(DiscordCollabRemoveSelect(active_requests))
|
||||
|
||||
# Discord Native Interactive UI Components (Modal & Dropdown View)
|
||||
class CollabModal(discord.ui.Modal, title="Post Collaboration Request"):
|
||||
author_name = discord.ui.TextInput(label="1) Your Name", placeholder="e.g. Priyan Sharma", required=True)
|
||||
department = discord.ui.TextInput(label="2) Department", placeholder="e.g. CSE / ECE / AIML", required=True, default="CSE")
|
||||
year = discord.ui.TextInput(label="3) Year", placeholder="e.g. 1st Year / 2nd Year", required=True, default="1st Year")
|
||||
project_idea = discord.ui.TextInput(label="4) Project Idea & Details", style=discord.TextStyle.paragraph, placeholder="Describe your project idea and what help you need...", required=True)
|
||||
dept_and_year = discord.ui.TextInput(label="2) Dept & Year", placeholder="e.g. CSE, 1st Year", required=True, default="CSE, 1st Year")
|
||||
collaborators_needed = discord.ui.TextInput(label="3) Collaborators Needed", placeholder="e.g. 2", required=True, default="1")
|
||||
project_idea = discord.ui.TextInput(label="4) Project Idea & Details", style=discord.TextStyle.paragraph, placeholder="Describe your project idea...", required=True)
|
||||
github_link = discord.ui.TextInput(label="5) GitHub Link (Optional)", placeholder="https://github.com/...", required=False)
|
||||
|
||||
def __init__(self, tag: str):
|
||||
@@ -602,10 +702,25 @@ class CollabModal(discord.ui.Modal, title="Post Collaboration Request"):
|
||||
self.selected_tag = tag
|
||||
|
||||
async def on_submit(self, interaction: discord.Interaction):
|
||||
try:
|
||||
num_needed = int(self.collaborators_needed.value)
|
||||
except ValueError:
|
||||
num_needed = 1
|
||||
|
||||
dept_val = "CSE"
|
||||
year_val = "1st Year"
|
||||
if "," in self.dept_and_year.value:
|
||||
parts = [p.strip() for p in self.dept_and_year.value.split(",", 1)]
|
||||
dept_val = parts[0]
|
||||
year_val = parts[1]
|
||||
else:
|
||||
dept_val = self.dept_and_year.value.strip()
|
||||
|
||||
payload = {
|
||||
"authorName": self.author_name.value,
|
||||
"department": self.department.value,
|
||||
"year": self.year.value,
|
||||
"department": dept_val,
|
||||
"year": year_val,
|
||||
"collaboratorsNeeded": num_needed,
|
||||
"tag": self.selected_tag,
|
||||
"projectIdea": self.project_idea.value,
|
||||
"githubLink": self.github_link.value or None,
|
||||
@@ -617,9 +732,10 @@ class CollabModal(discord.ui.Modal, title="Post Collaboration Request"):
|
||||
if res.status_code in [200, 201]:
|
||||
await interaction.response.send_message(
|
||||
f"🎉 **Collaboration Request posted live to RIT Dev Hub!**\n"
|
||||
f"👤 **Author:** {self.author_name.value} ({self.department.value}, {self.year.value})\n"
|
||||
f"👤 **Author:** {self.author_name.value} ({dept_val}, {year_val})\n"
|
||||
f"📌 **Project:** {self.project_idea.value}\n"
|
||||
f"🏷️ **Tag:** `{self.selected_tag}`",
|
||||
f"🏷️ **Tag:** `{self.selected_tag}`\n"
|
||||
f"👥 **Collaborators Needed:** `{num_needed}`",
|
||||
ephemeral=False
|
||||
)
|
||||
else:
|
||||
@@ -690,6 +806,23 @@ async def on_message(message):
|
||||
mention_nick_str = f"<@!{discord_client.user.id}>"
|
||||
content = content.replace(mention_str, "").replace(mention_nick_str, "").strip()
|
||||
|
||||
# Discord /remove Command
|
||||
if content.lower().startswith("/remove") or content.lower().startswith("/cancel"):
|
||||
try:
|
||||
res = requests.get(f"{BACKEND_URL}/api/collab/active/discord/{message.author.id}", timeout=5)
|
||||
if res.status_code == 200:
|
||||
requests_list = res.json()
|
||||
if not requests_list:
|
||||
await message.reply("ℹ️ **You have no active collaboration requests to remove.**")
|
||||
else:
|
||||
view = DiscordCollabRemoveView(requests_list)
|
||||
await message.reply("🗑️ **Your Active Collaboration Requests**\nSelect a request from the dropdown below to cancel it:", view=view)
|
||||
else:
|
||||
await message.reply("❌ Failed to fetch active requests.")
|
||||
except Exception as e:
|
||||
await message.reply(f"❌ Error: {e}")
|
||||
return
|
||||
|
||||
# Discord Interactive /collab command
|
||||
if content.lower().startswith("/collab"):
|
||||
view = CollabView()
|
||||
@@ -700,6 +833,32 @@ async def on_message(message):
|
||||
)
|
||||
return
|
||||
|
||||
# Check if this message is a reply to a question DM sent to a helper
|
||||
if message.reference and message.reference.message_id:
|
||||
question_id = get_question_id(message.author.id, message.reference.message_id)
|
||||
if question_id:
|
||||
author_name = message.author.display_name or message.author.name or "Senior Helper"
|
||||
logging.info(f"Submitting answer for question {question_id} by Discord helper '{author_name}'")
|
||||
backend_endpoint = f"{BACKEND_URL}/api/questions/{question_id}/answers"
|
||||
answer_payload = {
|
||||
"body": content,
|
||||
"author": author_name
|
||||
}
|
||||
try:
|
||||
def call_backend():
|
||||
return requests.post(backend_endpoint, json=answer_payload, timeout=10)
|
||||
|
||||
loop = asyncio.get_event_loop()
|
||||
res = await loop.run_in_executor(None, call_backend)
|
||||
if res.status_code in [200, 201]:
|
||||
await message.reply("✅ **Answer posted successfully to the Q&A board!**")
|
||||
else:
|
||||
await message.reply(f"❌ **Failed to post answer to backend.** (Status: {res.status_code})")
|
||||
except Exception as e:
|
||||
logging.error(f"Error calling backend endpoint {backend_endpoint}: {e}")
|
||||
await message.reply(f"❌ **Connection error to backend.** ({e})")
|
||||
return
|
||||
|
||||
# Direct query fallback to Go chatbot service
|
||||
if not content.strip():
|
||||
return
|
||||
@@ -910,11 +1069,9 @@ async def run_uvicorn():
|
||||
await server.serve()
|
||||
|
||||
async def main():
|
||||
# Start Senior Helper Community Bot thread
|
||||
comm_thread = threading.Thread(target=community_bot_polling_thread, daemon=True)
|
||||
comm_thread.start()
|
||||
|
||||
# Start 24/7 Chatbot & Collab Bot thread
|
||||
chat_thread = threading.Thread(target=telegram_polling_thread, daemon=True)
|
||||
chat_thread.start()
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ export default defineConfig({
|
||||
tailwindcss(),
|
||||
],
|
||||
server: {
|
||||
host: true,
|
||||
watch: {
|
||||
ignored: [
|
||||
'**/backend/**',
|
||||
|
||||
Reference in New Issue
Block a user