Convert backends to Firebase and combine projects

This commit is contained in:
2026-06-18 14:07:24 +05:30
commit 0a76feafc5
147 changed files with 35104 additions and 0 deletions

2
RIT-EMS-main/backend/.gitattributes vendored Normal file
View File

@@ -0,0 +1,2 @@
/mvnw text eol=lf
*.cmd text eol=crlf

33
RIT-EMS-main/backend/.gitignore vendored Normal file
View File

@@ -0,0 +1,33 @@
HELP.md
target/
.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/

View File

@@ -0,0 +1,3 @@
wrapperVersion=3.3.4
distributionType=only-script
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.14/apache-maven-3.9.14-bin.zip

295
RIT-EMS-main/backend/mvnw vendored Normal file
View File

@@ -0,0 +1,295 @@
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Apache Maven Wrapper startup batch script, version 3.3.4
#
# Optional ENV vars
# -----------------
# JAVA_HOME - location of a JDK home dir, required when download maven via java source
# MVNW_REPOURL - repo url base for downloading maven distribution
# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output
# ----------------------------------------------------------------------------
set -euf
[ "${MVNW_VERBOSE-}" != debug ] || set -x
# OS specific support.
native_path() { printf %s\\n "$1"; }
case "$(uname)" in
CYGWIN* | MINGW*)
[ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")"
native_path() { cygpath --path --windows "$1"; }
;;
esac
# set JAVACMD and JAVACCMD
set_java_home() {
# For Cygwin and MinGW, ensure paths are in Unix format before anything is touched
if [ -n "${JAVA_HOME-}" ]; then
if [ -x "$JAVA_HOME/jre/sh/java" ]; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
JAVACCMD="$JAVA_HOME/jre/sh/javac"
else
JAVACMD="$JAVA_HOME/bin/java"
JAVACCMD="$JAVA_HOME/bin/javac"
if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then
echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2
echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2
return 1
fi
fi
else
JAVACMD="$(
'set' +e
'unset' -f command 2>/dev/null
'command' -v java
)" || :
JAVACCMD="$(
'set' +e
'unset' -f command 2>/dev/null
'command' -v javac
)" || :
if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then
echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2
return 1
fi
fi
}
# hash string like Java String::hashCode
hash_string() {
str="${1:-}" h=0
while [ -n "$str" ]; do
char="${str%"${str#?}"}"
h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296))
str="${str#?}"
done
printf %x\\n $h
}
verbose() { :; }
[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; }
die() {
printf %s\\n "$1" >&2
exit 1
}
trim() {
# MWRAPPER-139:
# Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds.
# Needed for removing poorly interpreted newline sequences when running in more
# exotic environments such as mingw bash on Windows.
printf "%s" "${1}" | tr -d '[:space:]'
}
scriptDir="$(dirname "$0")"
scriptName="$(basename "$0")"
# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties
while IFS="=" read -r key value; do
case "${key-}" in
distributionUrl) distributionUrl=$(trim "${value-}") ;;
distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;;
esac
done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties"
[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
case "${distributionUrl##*/}" in
maven-mvnd-*bin.*)
MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/
case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in
*AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;;
:Darwin*x86_64) distributionPlatform=darwin-amd64 ;;
:Darwin*arm64) distributionPlatform=darwin-aarch64 ;;
:Linux*x86_64*) distributionPlatform=linux-amd64 ;;
*)
echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2
distributionPlatform=linux-amd64
;;
esac
distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip"
;;
maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;;
*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;;
esac
# apply MVNW_REPOURL and calculate MAVEN_HOME
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}"
distributionUrlName="${distributionUrl##*/}"
distributionUrlNameMain="${distributionUrlName%.*}"
distributionUrlNameMain="${distributionUrlNameMain%-bin}"
MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}"
MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")"
exec_maven() {
unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || :
exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD"
}
if [ -d "$MAVEN_HOME" ]; then
verbose "found existing MAVEN_HOME at $MAVEN_HOME"
exec_maven "$@"
fi
case "${distributionUrl-}" in
*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;;
*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;;
esac
# prepare tmp dir
if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then
clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; }
trap clean HUP INT TERM EXIT
else
die "cannot create temp dir"
fi
mkdir -p -- "${MAVEN_HOME%/*}"
# Download and Install Apache Maven
verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
verbose "Downloading from: $distributionUrl"
verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
# select .zip or .tar.gz
if ! command -v unzip >/dev/null; then
distributionUrl="${distributionUrl%.zip}.tar.gz"
distributionUrlName="${distributionUrl##*/}"
fi
# verbose opt
__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR=''
[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v
# normalize http auth
case "${MVNW_PASSWORD:+has-password}" in
'') MVNW_USERNAME='' MVNW_PASSWORD='' ;;
has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;;
esac
if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then
verbose "Found wget ... using wget"
wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl"
elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then
verbose "Found curl ... using curl"
curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl"
elif set_java_home; then
verbose "Falling back to use Java to download"
javaSource="$TMP_DOWNLOAD_DIR/Downloader.java"
targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName"
cat >"$javaSource" <<-END
public class Downloader extends java.net.Authenticator
{
protected java.net.PasswordAuthentication getPasswordAuthentication()
{
return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() );
}
public static void main( String[] args ) throws Exception
{
setDefault( new Downloader() );
java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() );
}
}
END
# For Cygwin/MinGW, switch paths to Windows format before running javac and java
verbose " - Compiling Downloader.java ..."
"$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java"
verbose " - Running Downloader.java ..."
"$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")"
fi
# If specified, validate the SHA-256 sum of the Maven distribution zip file
if [ -n "${distributionSha256Sum-}" ]; then
distributionSha256Result=false
if [ "$MVN_CMD" = mvnd.sh ]; then
echo "Checksum validation is not supported for maven-mvnd." >&2
echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
exit 1
elif command -v sha256sum >/dev/null; then
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then
distributionSha256Result=true
fi
elif command -v shasum >/dev/null; then
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then
distributionSha256Result=true
fi
else
echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2
echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
exit 1
fi
if [ $distributionSha256Result = false ]; then
echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2
echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2
exit 1
fi
fi
# unzip and move
if command -v unzip >/dev/null; then
unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip"
else
tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar"
fi
# Find the actual extracted directory name (handles snapshots where filename != directory name)
actualDistributionDir=""
# First try the expected directory name (for regular distributions)
if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then
if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then
actualDistributionDir="$distributionUrlNameMain"
fi
fi
# If not found, search for any directory with the Maven executable (for snapshots)
if [ -z "$actualDistributionDir" ]; then
# enable globbing to iterate over items
set +f
for dir in "$TMP_DOWNLOAD_DIR"/*; do
if [ -d "$dir" ]; then
if [ -f "$dir/bin/$MVN_CMD" ]; then
actualDistributionDir="$(basename "$dir")"
break
fi
fi
done
set -f
fi
if [ -z "$actualDistributionDir" ]; then
verbose "Contents of $TMP_DOWNLOAD_DIR:"
verbose "$(ls -la "$TMP_DOWNLOAD_DIR")"
die "Could not find Maven distribution directory in extracted archive"
fi
verbose "Found extracted Maven distribution directory: $actualDistributionDir"
printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url"
mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME"
clean || :
exec_maven "$@"

189
RIT-EMS-main/backend/mvnw.cmd vendored Normal file
View File

@@ -0,0 +1,189 @@
<# : batch portion
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM http://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Apache Maven Wrapper startup batch script, version 3.3.4
@REM
@REM Optional ENV vars
@REM MVNW_REPOURL - repo url base for downloading maven distribution
@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output
@REM ----------------------------------------------------------------------------
@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0)
@SET __MVNW_CMD__=
@SET __MVNW_ERROR__=
@SET __MVNW_PSMODULEP_SAVE=%PSModulePath%
@SET PSModulePath=
@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @(
IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B)
)
@SET PSModulePath=%__MVNW_PSMODULEP_SAVE%
@SET __MVNW_PSMODULEP_SAVE=
@SET __MVNW_ARG0_NAME__=
@SET MVNW_USERNAME=
@SET MVNW_PASSWORD=
@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*)
@echo Cannot start maven from wrapper >&2 && exit /b 1
@GOTO :EOF
: end batch / begin powershell #>
$ErrorActionPreference = "Stop"
if ($env:MVNW_VERBOSE -eq "true") {
$VerbosePreference = "Continue"
}
# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties
$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl
if (!$distributionUrl) {
Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
}
switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) {
"maven-mvnd-*" {
$USE_MVND = $true
$distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip"
$MVN_CMD = "mvnd.cmd"
break
}
default {
$USE_MVND = $false
$MVN_CMD = $script -replace '^mvnw','mvn'
break
}
}
# apply MVNW_REPOURL and calculate MAVEN_HOME
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
if ($env:MVNW_REPOURL) {
$MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" }
$distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')"
}
$distributionUrlName = $distributionUrl -replace '^.*/',''
$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$',''
$MAVEN_M2_PATH = "$HOME/.m2"
if ($env:MAVEN_USER_HOME) {
$MAVEN_M2_PATH = "$env:MAVEN_USER_HOME"
}
if (-not (Test-Path -Path $MAVEN_M2_PATH)) {
New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null
}
$MAVEN_WRAPPER_DISTS = $null
if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) {
$MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists"
} else {
$MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists"
}
$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain"
$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join ''
$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME"
if (Test-Path -Path "$MAVEN_HOME" -PathType Container) {
Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME"
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
exit $?
}
if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) {
Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl"
}
# prepare tmp dir
$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile
$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir"
$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null
trap {
if ($TMP_DOWNLOAD_DIR.Exists) {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
}
New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null
# Download and Install Apache Maven
Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
Write-Verbose "Downloading from: $distributionUrl"
Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
$webclient = New-Object System.Net.WebClient
if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) {
$webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD)
}
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null
# If specified, validate the SHA-256 sum of the Maven distribution zip file
$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum
if ($distributionSha256Sum) {
if ($USE_MVND) {
Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties."
}
Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash
if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) {
Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property."
}
}
# unzip and move
Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null
# Find the actual extracted directory name (handles snapshots where filename != directory name)
$actualDistributionDir = ""
# First try the expected directory name (for regular distributions)
$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain"
$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD"
if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) {
$actualDistributionDir = $distributionUrlNameMain
}
# If not found, search for any directory with the Maven executable (for snapshots)
if (!$actualDistributionDir) {
Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object {
$testPath = Join-Path $_.FullName "bin/$MVN_CMD"
if (Test-Path -Path $testPath -PathType Leaf) {
$actualDistributionDir = $_.Name
}
}
}
if (!$actualDistributionDir) {
Write-Error "Could not find Maven distribution directory in extracted archive"
}
Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir"
Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null
try {
Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null
} catch {
if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) {
Write-Error "fail to move MAVEN_HOME"
}
} finally {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"

View File

@@ -0,0 +1,89 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.ems</groupId>
<artifactId>backend</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>backend</name>
<description/>
<url/>
<licenses>
<license/>
</licenses>
<developers>
<developer/>
</developers>
<scm>
<connection/>
<developerConnection/>
<tag/>
<url/>
</scm>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.36</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,13 @@
package com.ems.backend;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class BackendApplication {
public static void main(String[] args) {
SpringApplication.run(BackendApplication.class, args);
}
}

View File

@@ -0,0 +1,31 @@
package com.ems.backend.config;
import com.ems.backend.model.User;
import com.ems.backend.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.Collections;
@Service
public class CustomUserDetailsService implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
User user = userRepository.findByEmail(email)
.orElseThrow(() -> new UsernameNotFoundException("User not found with email: " + email));
return new org.springframework.security.core.userdetails.User(
user.getEmail(),
user.getPassword(),
Collections.singletonList(new SimpleGrantedAuthority("ROLE_" + user.getRole()))
);
}
}

View File

@@ -0,0 +1,61 @@
package com.ems.backend.config;
import com.ems.backend.model.User;
import com.ems.backend.repository.UserRepository;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
public class DataInitializer {
@Bean
public CommandLineRunner initData(UserRepository userRepository, PasswordEncoder passwordEncoder) {
return args -> {
updateOrCreateUser(userRepository, passwordEncoder, "admin@rit.edu", "admin123", "System Administrator", "ADMIN", "ADMIN");
updateOrCreateUser(userRepository, passwordEncoder, "faculty@rit.edu", "faculty123", "Dr. Faculty Member", "FACULTY", "CSE");
updateOrCreateUser(userRepository, passwordEncoder, "hod@rit.edu", "hod123", "Prof. Head of Dept", "HOD", "AI&ML");
updateOrCreateUser(userRepository, passwordEncoder, "principal@rit.edu", "principal123", "Dr. College Principal", "PRINCIPAL", null);
updateOrCreateUser(userRepository, passwordEncoder, "placement@rit.edu", "placement123", "Placement Coordinator", "PLACEMENT", "Placement Department");
// Newly added users based on request
updateOrCreateUser(userRepository, passwordEncoder, "admin2@rit.edu", "admin123", "Secondary Admin", "ADMIN", "ADMIN");
updateOrCreateUser(userRepository, passwordEncoder, "principal2@rit.edu", "principal123", "Vice Principal", "PRINCIPAL", null);
updateOrCreateUser(userRepository, passwordEncoder, "hod_cse@rit.edu", "hod123", "CSE HOD", "HOD", "CSE");
updateOrCreateUser(userRepository, passwordEncoder, "faculty2@rit.edu", "faculty123", "Assistant Professor CSE", "FACULTY", "CSE");
System.out.println("Demo users verified and updated.");
};
}
private void updateOrCreateUser(UserRepository repo, PasswordEncoder encoder, String email, String pass, String name, String role, String dept) {
User user = repo.findByEmail(email).orElse(new User());
user.setEmail(email);
user.setPassword(encoder.encode(pass));
user.setFullName(name);
user.setRole(role);
user.setDepartment(dept);
// Synchronize flags with roles/departments
if ("PLACEMENT".equals(role) || "Placement Department".equals(dept)) {
user.setPlacementStaff(true);
}
if ("FACULTY".equals(role)) {
user.setClassIncharge(true);
user.setInchargeClass("CSE");
user.setInchargeBatch("3rd Year");
user.setInchargeSection("A");
if (user.getClassStrength() == null || user.getClassStrength() == 0) {
user.setClassStrength(60);
}
}
// Ensure new fields are initialized if new
if (user.getAssignedClubs() == null) {
user.setAssignedClubs(new java.util.ArrayList<>());
}
repo.save(user);
}
}

View File

@@ -0,0 +1,88 @@
package com.ems.backend.config;
import com.ems.backend.model.Event;
import com.ems.backend.model.User;
import com.ems.backend.repository.EventRepository;
import com.ems.backend.repository.UserRepository;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
@Configuration
public class DataSeeder {
@Bean
CommandLineRunner initDatabase(EventRepository eventRepository, UserRepository userRepository) {
return args -> {
// Check if we already have events to avoid duplicate seeding on every restart
// unless the user specifically wants to clear them.
// For this task, we will add them if they don't exist for these depts in this range.
User proposer = userRepository.findByEmail("faculty@rit.edu").orElse(null);
if (proposer == null) {
System.out.println("No faculty user found to seed events. Please run DataInitializer first.");
return;
}
String[] depts = {"CSE", "AI&ML", "ECE"};
String[] statuses = {"REQUESTED", "APPROVED", "COMPLETED", "CANCELLED", "PENDING_PR"};
String[] categories = {"ACADEMIC", "CLUB", "PLACEMENT", "SPORTS"};
String[] types = {"Workshop", "Seminar", "Guest Lecture", "Competition"};
String[] years = {"1st Year", "2nd Year", "3rd Year", "4th Year"};
Random random = new Random();
for (String dept : depts) {
for (int month = 1; month <= 6; month++) {
// Create 2 events per department per month
for (int i = 0; i < 2; i++) {
int day = random.nextInt(25) + 1;
int hour = 9 + random.nextInt(8);
LocalDateTime start = LocalDateTime.of(2026, month, day, hour, 0);
LocalDateTime end = start.plusHours(2 + random.nextInt(3));
String status = statuses[random.nextInt(statuses.length)];
// Logic: Past events are more likely to be COMPLETED or APPROVED
if (start.isBefore(LocalDateTime.now())) {
if (random.nextBoolean()) status = "COMPLETED";
}
String[] venues = {
"GB 4th floor auditorium",
"Wozniak Auditorium",
"C6-02 Indoor Theatre",
"H Block Guest Lecture Theatre",
"Steve Jobs Computer Centre 1",
"Steve Jobs Computer Centre 2"
};
String venue = venues[random.nextInt(venues.length)];
eventRepository.save(Event.builder()
.title(dept + " " + types[random.nextInt(types.length)] + " - " + month + "/" + day)
.description("Sample event for " + dept + " department.")
.startDate(start)
.endDate(end)
.location(venue)
.category(categories[random.nextInt(categories.length)])
.type(types[random.nextInt(types.length)])
.institution("RIT")
.department(dept)
.academicYears(Arrays.asList(years[random.nextInt(years.length)]))
.status(status)
.proposer(proposer)
.budget(1000.0 * (random.nextInt(20) + 5))
.build());
}
}
}
System.out.println("Seeded events for CSE, AI&ML, ECE for Jan-June semester.");
};
}
}

View File

@@ -0,0 +1,57 @@
package com.ems.backend.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import java.util.Arrays;
import java.util.List;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf.disable())
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
.authorizeHttpRequests(auth -> auth
.anyRequest().permitAll()
)
.httpBasic(basic -> basic.disable())
.formLogin(form -> form.disable());
return http.build();
}
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
return config.getAuthenticationManager();
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(List.of("*")); // For development
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
configuration.setAllowedHeaders(Arrays.asList("Authorization", "Content-Type", "X-Requested-With"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}

View File

@@ -0,0 +1,85 @@
package com.ems.backend.controller;
import com.ems.backend.model.User;
import com.ems.backend.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/api/admin")
@CrossOrigin(origins = "*")
public class AdminController {
@Autowired
private UserRepository userRepository;
@Autowired
private PasswordEncoder passwordEncoder;
@GetMapping("/users")
public ResponseEntity<List<User>> getAllUsers() {
return ResponseEntity.ok(userRepository.findAll());
}
@PostMapping("/users")
public ResponseEntity<?> createUser(@RequestBody User user) {
if (user == null || user.getEmail() == null || user.getEmail().trim().isEmpty()) {
return ResponseEntity.status(400).body(Map.of("message", "Email is required"));
}
if (user.getFullName() == null || user.getFullName().trim().isEmpty()) {
return ResponseEntity.status(400).body(Map.of("message", "Full name is required"));
}
if (user.getPassword() == null || user.getPassword().trim().isEmpty()) {
return ResponseEntity.status(400).body(Map.of("message", "Password is required"));
}
user.setEmail(user.getEmail().trim().toLowerCase());
user.setFullName(user.getFullName().trim());
if (user.getRole() == null || user.getRole().trim().isEmpty()) {
user.setRole("FACULTY");
}
if (user.getDepartment() == null || user.getDepartment().trim().isEmpty()) {
user.setDepartment("H&S Dept");
}
if (userRepository.findByEmail(user.getEmail()).isPresent()) {
return ResponseEntity.status(400).body(Map.of("message", "User with this email already exists"));
}
user.setPassword(passwordEncoder.encode(user.getPassword()));
userRepository.save(user);
return ResponseEntity.ok(user);
}
@PutMapping("/users/{id}")
public ResponseEntity<?> updateUser(@PathVariable Long id, @RequestBody User userDetails) {
User user = userRepository.findById(id).orElseThrow();
user.setFullName(userDetails.getFullName());
user.setEmail(userDetails.getEmail());
user.setRole(userDetails.getRole());
user.setDepartment(userDetails.getDepartment());
user.setClubCoordinator(userDetails.isClubCoordinator());
user.setPlacementStaff(userDetails.isPlacementStaff());
user.setClassIncharge(userDetails.isClassIncharge());
user.setClassStrength(userDetails.getClassStrength());
user.setInchargeClass(userDetails.getInchargeClass());
user.setInchargeBatch(userDetails.getInchargeBatch());
user.setInchargeSection(userDetails.getInchargeSection());
user.setAssignedClubs(userDetails.getAssignedClubs());
if (userDetails.getPassword() != null && !userDetails.getPassword().isEmpty()) {
user.setPassword(passwordEncoder.encode(userDetails.getPassword()));
}
userRepository.save(user);
return ResponseEntity.ok(user);
}
@DeleteMapping("/users/{id}")
public ResponseEntity<?> deleteUser(@PathVariable Long id) {
userRepository.deleteById(id);
return ResponseEntity.ok(Map.of("message", "User deleted successfully"));
}
}

View File

@@ -0,0 +1,53 @@
package com.ems.backend.controller;
import com.ems.backend.dto.LoginRequest;
import com.ems.backend.model.User;
import com.ems.backend.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
import java.util.Optional;
@RestController
@RequestMapping("/api/auth")
@CrossOrigin(origins = "*")
public class AuthController {
@Autowired
private UserRepository userRepository;
@Autowired
private PasswordEncoder passwordEncoder;
@PostMapping("/login")
public ResponseEntity<?> login(@RequestBody LoginRequest loginRequest) {
Optional<User> userOptional = userRepository.findByEmail(loginRequest.getEmail());
if (userOptional.isPresent()) {
User user = userOptional.get();
if (passwordEncoder.matches(loginRequest.getPassword(), user.getPassword())) {
java.util.Map<String, Object> responseMap = new java.util.HashMap<>();
responseMap.put("id", user.getId());
responseMap.put("email", user.getEmail());
responseMap.put("fullName", user.getFullName());
responseMap.put("role", user.getRole());
responseMap.put("department", user.getDepartment() != null ? user.getDepartment() : "N/A");
responseMap.put("isClubCoordinator", user.isClubCoordinator());
responseMap.put("isPlacementStaff", user.isPlacementStaff());
responseMap.put("isClassIncharge", user.isClassIncharge());
responseMap.put("inchargeClass", user.getInchargeClass());
responseMap.put("inchargeBatch", user.getInchargeBatch());
responseMap.put("inchargeSection", user.getInchargeSection());
responseMap.put("classStrength", user.getClassStrength());
responseMap.put("assignedClubs", user.getAssignedClubs() != null ? user.getAssignedClubs() : java.util.List.of());
return ResponseEntity.ok(responseMap);
}
}
return ResponseEntity.status(401).body(Map.of("message", "Invalid email or passcode"));
}
}

View File

@@ -0,0 +1,70 @@
package com.ems.backend.controller;
import com.ems.backend.model.ClassMapping;
import com.ems.backend.repository.ClassRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/api/classes")
@CrossOrigin(origins = "*")
public class ClassController {
@Autowired
private ClassRepository classRepository;
@GetMapping
public ResponseEntity<List<ClassMapping>> getAllClasses() {
return ResponseEntity.ok(classRepository.findAll());
}
@PostMapping
public ResponseEntity<?> createClass(@RequestBody ClassMapping classMapping) {
classRepository.save(classMapping);
return ResponseEntity.ok(classMapping);
}
@DeleteMapping("/{id}")
public ResponseEntity<?> deleteClass(@PathVariable Long id) {
classRepository.deleteById(id);
return ResponseEntity.ok(Map.of("message", "Class mapping deleted successfully"));
}
@PostMapping("/promote")
public ResponseEntity<?> promoteAcademicYear(@RequestParam String institution) {
List<ClassMapping> allClasses = classRepository.findAll();
for (ClassMapping cm : allClasses) {
if (!cm.getInstitution().trim().equalsIgnoreCase(institution.trim())) {
continue;
}
String currentYear = cm.getAcademicYear();
switch (currentYear) {
case "1st Year":
cm.setAcademicYear("2nd Year");
classRepository.save(cm);
break;
case "2nd Year":
cm.setAcademicYear("3rd Year");
classRepository.save(cm);
break;
case "3rd Year":
cm.setAcademicYear("4th Year");
classRepository.save(cm);
break;
case "4th Year":
classRepository.delete(cm);
break;
default:
break;
}
}
return ResponseEntity.ok(Map.of("message", "Academic year promotion completed for " + institution));
}
}

View File

@@ -0,0 +1,437 @@
package com.ems.backend.controller;
import com.ems.backend.model.Event;
import com.ems.backend.model.User;
import com.ems.backend.repository.EventRepository;
import com.ems.backend.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
@RestController
@RequestMapping("/api/events")
@CrossOrigin(origins = "*")
public class EventController {
@Autowired
private EventRepository eventRepository;
@Autowired
private UserRepository userRepository;
@PostMapping("/propose")
@Transactional
public ResponseEntity<?> proposeEvent(@RequestBody Map<String, Object> payload) {
try {
Long userId = Long.valueOf(payload.get("userId").toString());
User proposer = userRepository.findById(userId).orElseThrow();
if (!"FACULTY".equals(proposer.getRole()) &&
!"HOD".equals(proposer.getRole()) &&
!"PRINCIPAL".equals(proposer.getRole()) &&
!"PLACEMENT".equals(proposer.getRole()) &&
!"ADMIN".equals(proposer.getRole())) {
return ResponseEntity.status(403).body(Map.of("message", "Only authorized users can propose events"));
}
Event event = new Event();
event.setTitle(payload.get("eventName").toString());
event.setStartDate(parseDateTime(payload.get("startDate")));
event.setEndDate(parseDateTime(payload.get("endDate")));
event.setType(payload.get("eventType") != null ? payload.get("eventType").toString() : "Institutional");
event.setInstitution(payload.get("institution").toString());
event.setDepartment(payload.get("department").toString());
event.setAcademicYears((List<String>) payload.get("academicYears"));
event.setLocation(payload.get("venue").toString());
event.setGuestName(payload.get("guestName") != null ? payload.get("guestName").toString() : null);
event.setGuestSocialProfile(payload.get("socialProfile") != null ? payload.get("socialProfile").toString() : null);
event.setRequirements((List<String>) payload.get("requirements"));
event.setTargetedSections((List<String>) payload.get("targetedSections"));
event.setGroupRequestId(payload.get("groupRequestId") != null ? payload.get("groupRequestId").toString() : null);
// New Fields
event.setDescription(payload.get("description") != null ? payload.get("description").toString() : null);
event.setSponsors((List<String>) payload.get("sponsors"));
String budgetStr = payload.get("budget") != null ? payload.get("budget").toString() : "";
event.setBudget(budgetStr.isEmpty() ? 0.0 : Double.valueOf(budgetStr));
event.setHasRegistrationFee(payload.get("hasRegistrationFee") != null && (boolean) payload.get("hasRegistrationFee"));
String feeStr = payload.get("registrationFee") != null ? payload.get("registrationFee").toString() : "";
event.setRegistrationFee(feeStr.isEmpty() ? 0.0 : Double.valueOf(feeStr));
String category = payload.get("category") != null ? payload.get("category").toString() : "ACADEMIC";
event.setCategory(category);
event.setCentreName(payload.get("centreName") != null ? payload.get("centreName").toString() : null);
if (payload.containsKey("isPublicEvent")) {
event.setPublicEvent((boolean) payload.get("isPublicEvent"));
}
// Workflow Logic
if ("PRINCIPAL".equals(proposer.getRole())) {
event.setStatus("APPROVED");
} else if ("HOD".equals(proposer.getRole()) ||
"CLUB".equals(category) ||
"PLACEMENT".equals(category) ||
"INSTITUTIONAL".equals(category) ||
"PLACEMENT".equals(proposer.getRole()) ||
proposer.isPlacementStaff() ||
"Placement Department".equals(proposer.getDepartment())) {
event.setStatus("PENDING_PR");
} else {
event.setStatus("REQUESTED");
}
event.setProposer(proposer);
if (event.getStartDate().isBefore(LocalDateTime.now())) {
return ResponseEntity.status(400).body(Map.of("message", "Cannot schedule events in the past"));
}
if (event.getEndDate().isBefore(event.getStartDate()) || event.getEndDate().isEqual(event.getStartDate())) {
return ResponseEntity.status(400).body(Map.of("message", "End date must be after start date"));
}
event.setLocation(event.getLocation().trim());
event.setInstitution(event.getInstitution().trim());
// Priority & Conflict Logic
List<Event> conflicts = eventRepository.findConflictingEvents(
event.getInstitution(),
event.getLocation(),
event.getStartDate(),
event.getEndDate(),
-1L,
event.getGroupRequestId()
);
if (!conflicts.isEmpty()) {
if ("PLACEMENT".equals(category) && Boolean.TRUE.equals(payload.get("cancelConflicting"))) {
for (Event conflict : conflicts) {
conflict.setStatus("CANCELLED");
conflict.setRejectionReason("This event is cancelled due to the placement activity happening at the venue at this timing.");
eventRepository.save(conflict);
}
} else {
String conflictMsg = getConflictMessage(event);
return ResponseEntity.status(HttpStatus.CONFLICT).body(Map.of(
"message", conflictMsg,
"conflicts", conflicts,
"canOverride", "PLACEMENT".equals(category)
));
}
}
eventRepository.save(event);
return ResponseEntity.ok(Map.of("message", "Event proposed successfully", "id", event.getId()));
} catch (Exception e) {
return ResponseEntity.status(400).body(Map.of("message", "Failed to propose event: " + e.getMessage()));
}
}
@GetMapping
public List<Event> getAllEvents() {
List<Event> events = eventRepository.findAll();
populateConflictMessages(events);
return events;
}
@PostMapping("/batch-create")
@Transactional
public ResponseEntity<?> batchCreateEvents(@RequestBody List<Map<String, Object>> eventsPayload) {
try {
if (eventsPayload == null || eventsPayload.isEmpty()) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(Map.of("message", "No events provided for import"));
}
List<Event> eventsToSave = new ArrayList<>();
for (Map<String, Object> payload : eventsPayload) {
Event event = new Event();
String title = payload.get("title") != null ? payload.get("title").toString() : "Untitled Event";
event.setTitle(title);
Object dateObj = payload.get("startDate") != null ? payload.get("startDate") : payload.get("finalDate");
if (dateObj == null) {
throw new RuntimeException("Missing date for event: " + title);
}
LocalDateTime start = parseDateTime(dateObj);
event.setStartDate(start);
// Try to calculate duration from original event if available
if (payload.get("startDate") != null && payload.get("endDate") != null) {
try {
LocalDateTime origStart = parseDateTime(payload.get("startDate"));
LocalDateTime origEnd = parseDateTime(payload.get("endDate"));
java.time.Duration duration = java.time.Duration.between(origStart, origEnd);
event.setEndDate(start.plus(duration));
} catch (Exception e) {
event.setEndDate(start.plusHours(2));
}
} else {
event.setEndDate(start.plusHours(2));
}
event.setType(payload.get("type") != null ? payload.get("type").toString() : "Seminar");
event.setInstitution(payload.get("institution") != null ? payload.get("institution").toString().trim() : "RIT");
String dept = payload.get("targetDepartment") != null ? payload.get("targetDepartment").toString() :
(payload.get("department") != null ? payload.get("department").toString() : "General");
event.setDepartment(dept);
Object ay = payload.get("targetBatch") != null ? List.of(payload.get("targetBatch").toString()) : payload.get("academicYears");
event.setAcademicYears((List<String>) ay);
String venue = payload.get("venue") != null ? payload.get("venue").toString() :
(payload.get("location") != null ? payload.get("location").toString() : "TBD");
event.setLocation(venue.trim());
event.setCategory(payload.get("category") != null ? payload.get("category").toString() : "ACADEMIC");
event.setStatus(payload.get("status") != null ? payload.get("status").toString() : "APPROVED");
if (payload.containsKey("requirements")) {
event.setRequirements((List<String>) payload.get("requirements"));
}
if (payload.get("proposer") != null) {
try {
Object proposerObj = payload.get("proposer");
if (proposerObj instanceof Map) {
Map<String, Object> prop = (Map<String, Object>) proposerObj;
Object idObj = prop.get("id");
if (idObj != null) {
Long propId = Long.valueOf(idObj.toString());
userRepository.findById(propId).ifPresent(event::setProposer);
}
}
} catch (Exception e) {
System.err.println("Warning: Could not map proposer for batch event: " + e.getMessage());
}
}
if (event.getStartDate() == null || event.getEndDate() == null) {
throw new RuntimeException("Missing start or end date for event: " + title);
}
if (event.getEndDate().isBefore(event.getStartDate()) || event.getEndDate().isEqual(event.getStartDate())) {
throw new RuntimeException("End date must be after start date for event: " + title);
}
eventsToSave.add(event);
}
for (Event event : eventsToSave) {
String conflictMsg = getConflictMessage(event);
if (conflictMsg != null) {
throw new RuntimeException("Conflict in batch item '" + event.getTitle() + "': " + conflictMsg);
}
}
for (int i = 0; i < eventsToSave.size(); i++) {
Event current = eventsToSave.get(i);
for (int j = i + 1; j < eventsToSave.size(); j++) {
Event other = eventsToSave.get(j);
if (isVenueTimingConflict(current, other)) {
throw new RuntimeException("Conflict between imported events '" + current.getTitle() + "' and '" + other.getTitle() + "' at " + current.getLocation());
}
}
}
for (Event event : eventsToSave) {
eventRepository.save(event);
}
return ResponseEntity.ok(Map.of("message", "Batch events created successfully", "count", eventsToSave.size()));
} catch (Exception e) {
String errorMsg = e.getMessage() != null ? e.getMessage() : "Unknown error during batch creation";
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(Map.of("message", "Failed to create batch events: " + errorMsg));
}
}
@PostMapping("/{id}/approve")
@Transactional
public ResponseEntity<?> approveEvent(@PathVariable Long id, @RequestParam Long userId) {
User user = userRepository.findById(userId).orElseThrow();
Event event = eventRepository.findById(id).orElseThrow();
String conflictMsg = getConflictMessage(event);
if (conflictMsg != null) {
return ResponseEntity.status(HttpStatus.CONFLICT).body(Map.of("message", conflictMsg));
}
if ("HOD".equals(user.getRole())) {
event.setStatus("PENDING_PR");
} else if ("PRINCIPAL".equals(user.getRole())) {
event.setStatus("APPROVED");
} else {
return ResponseEntity.status(403).body(Map.of("message", "Only HoD or Principal can approve events"));
}
eventRepository.save(event);
return ResponseEntity.ok(Map.of("message", "Event action completed successfully", "status", event.getStatus()));
}
@PostMapping("/{id}/reject")
public ResponseEntity<?> rejectEvent(@PathVariable Long id, @RequestParam Long userId, @RequestBody(required = false) Map<String, String> payload) {
User user = userRepository.findById(userId).orElseThrow();
Event event = eventRepository.findById(id).orElseThrow();
String reason = payload != null ? payload.get("reason") : null;
if (reason == null || reason.trim().isEmpty()) {
return ResponseEntity.status(400).body(Map.of("message", "Rejection reason is mandatory"));
}
if ("HOD".equals(user.getRole())) {
event.setStatus("HOD_REJECTED");
} else if ("PRINCIPAL".equals(user.getRole())) {
event.setStatus("PRINCIPAL_REJECTED");
} else {
return ResponseEntity.status(403).body(Map.of("message", "Only HoD or Principal can reject events"));
}
event.setRejectionReason(reason);
eventRepository.save(event);
return ResponseEntity.ok(Map.of("message", "Event rejected successfully", "status", event.getStatus()));
}
@PutMapping("/{id}")
@Transactional
public ResponseEntity<?> updateEvent(@PathVariable Long id, @RequestBody Map<String, Object> payload) {
try {
Event event = eventRepository.findById(id).orElseThrow();
Long userId = Long.valueOf(payload.get("userId").toString());
User user = userRepository.findById(userId).orElseThrow();
boolean isAdmin = "ADMIN".equals(user.getRole());
if (!isAdmin) {
if (!event.getProposer().getId().equals(userId)) {
return ResponseEntity.status(403).body(Map.of("message", "Only the proposer can edit this event"));
}
if (!"REQUESTED".equals(event.getStatus())) {
return ResponseEntity.status(403).body(Map.of("message", "Event cannot be edited once it moves past the initial request stage"));
}
}
if (payload.containsKey("title")) event.setTitle(payload.get("title").toString());
if (payload.containsKey("startDate")) event.setStartDate(parseDateTime(payload.get("startDate")));
if (payload.containsKey("endDate")) event.setEndDate(parseDateTime(payload.get("endDate")));
if (payload.containsKey("eventType")) event.setType(payload.get("eventType").toString());
if (payload.containsKey("institution")) event.setInstitution(payload.get("institution").toString());
if (payload.containsKey("department")) event.setDepartment(payload.get("department").toString());
if (payload.containsKey("venue")) event.setLocation(payload.get("venue").toString());
if (payload.containsKey("guestName")) event.setGuestName(payload.get("guestName").toString());
if (payload.containsKey("socialProfile")) event.setGuestSocialProfile(payload.get("socialProfile").toString());
if (payload.containsKey("academicYears")) event.setAcademicYears((List<String>) payload.get("academicYears"));
if (payload.containsKey("targetedSections")) event.setTargetedSections((List<String>) payload.get("targetedSections"));
if (payload.containsKey("requirements")) event.setRequirements((List<String>) payload.get("requirements"));
if (payload.containsKey("sponsors")) event.setSponsors((List<String>) payload.get("sponsors"));
if (payload.containsKey("description")) event.setDescription(payload.get("description").toString());
if (payload.containsKey("budget")) {
String budgetStr = payload.get("budget").toString();
event.setBudget(budgetStr.isEmpty() ? 0.0 : Double.valueOf(budgetStr));
}
if (payload.containsKey("hasRegistrationFee")) event.setHasRegistrationFee((boolean) payload.get("hasRegistrationFee"));
if (payload.containsKey("registrationFee")) {
String feeStr = payload.get("registrationFee").toString();
event.setRegistrationFee(feeStr.isEmpty() ? 0.0 : Double.valueOf(feeStr));
}
if (payload.containsKey("centreName")) event.setCentreName(payload.get("centreName").toString());
if (payload.containsKey("isPublicEvent")) event.setPublicEvent((boolean) payload.get("isPublicEvent"));
if (payload.containsKey("status") && isAdmin) {
event.setStatus(payload.get("status").toString());
}
if (event.getEndDate().isBefore(event.getStartDate()) || event.getEndDate().isEqual(event.getStartDate())) {
return ResponseEntity.status(400).body(Map.of("message", "End date must be after start date"));
}
event.setLocation(event.getLocation().trim());
event.setInstitution(event.getInstitution().trim());
String conflictMsg = getConflictMessage(event);
if (conflictMsg != null) {
return ResponseEntity.status(HttpStatus.CONFLICT).body(Map.of("message", conflictMsg));
}
eventRepository.save(event);
return ResponseEntity.ok(Map.of("message", "Event updated successfully"));
} catch (Exception e) {
return ResponseEntity.status(400).body(Map.of("message", "Failed to update event: " + e.getMessage()));
}
}
private void populateConflictMessages(List<Event> events) {
for (Event event : events) {
if (!"APPROVED".equals(event.getStatus()) && !"COMPLETED".equals(event.getStatus()) && !"CANCELLED".equals(event.getStatus())) {
event.setConflictMessage(getConflictMessage(event));
}
}
}
private String getConflictMessage(Event event) {
LocalDateTime start = event.getStartDate();
LocalDateTime end = event.getEndDate();
String location = event.getLocation().trim();
String institution = event.getInstitution().trim();
List<Event> conflicts = eventRepository.findConflictingEvents(
institution,
location,
start,
end,
event.getId() != null ? event.getId() : -1L,
event.getGroupRequestId()
);
if (!conflicts.isEmpty()) {
Event conflict = conflicts.get(0);
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm");
return String.format("Venue Conflict: '%s' is already booked for '%s' from %s to %s",
location, conflict.getTitle(),
conflict.getStartDate().format(timeFormatter),
conflict.getEndDate().format(timeFormatter));
}
return null;
}
private boolean isVenueTimingConflict(Event first, Event second) {
if ("CANCELLED".equals(first.getStatus()) || "CANCELLED".equals(second.getStatus())) {
return false;
}
return first.getInstitution().trim().equals(second.getInstitution().trim())
&& first.getLocation().trim().equalsIgnoreCase(second.getLocation().trim())
&& first.getStartDate().isBefore(second.getEndDate())
&& first.getEndDate().isAfter(second.getStartDate());
}
private LocalDateTime parseDateTime(Object value) {
if (value == null) return null;
String str = value.toString().trim();
if (str.isEmpty()) return null;
str = str.replace(" ", "T");
if (str.length() == 10) str += "T00:00:00";
if (str.length() == 16) str += ":00";
if (str.contains("+")) str = str.substring(0, str.indexOf("+"));
if (str.contains("Z")) str = str.replace("Z", "");
if (str.contains(".")) str = str.substring(0, str.indexOf("."));
try {
return LocalDateTime.parse(str);
} catch (Exception e) {
System.err.println("Failed to parse date: " + str);
throw e;
}
}
}

View File

@@ -0,0 +1,34 @@
package com.ems.backend.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.sql.DataSource;
import java.sql.Connection;
import java.util.Map;
@RestController
public class HealthController {
@Autowired
private DataSource dataSource;
@GetMapping("/api/health")
public Map<String, Object> health() {
String dbStatus = "DOWN";
try (Connection connection = dataSource.getConnection()) {
if (connection.isValid(1)) {
dbStatus = "UP";
}
} catch (Exception e) {
dbStatus = "DOWN: " + e.getMessage();
}
return Map.of(
"status", "UP",
"message", "EMS Backend is running",
"database", dbStatus
);
}
}

View File

@@ -0,0 +1,27 @@
package com.ems.backend.controller;
import com.ems.backend.model.InstitutionalNote;
import com.ems.backend.repository.InstitutionalNoteRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/notes")
@CrossOrigin(origins = "*")
public class NoteController {
@Autowired
private InstitutionalNoteRepository noteRepository;
@GetMapping
public List<InstitutionalNote> getAllNotes() {
return noteRepository.findAll();
}
@PostMapping
public InstitutionalNote createNote(@RequestBody InstitutionalNote note) {
return noteRepository.save(note);
}
}

View File

@@ -0,0 +1,13 @@
package com.ems.backend.dto;
import lombok.Data;
public class LoginRequest {
private String email;
private String password;
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
public String getPassword() { return password; }
public void setPassword(String password) { this.password = password; }
}

View File

@@ -0,0 +1,36 @@
package com.ems.backend.model;
import jakarta.persistence.*;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import java.time.LocalDateTime;
@MappedSuperclass
public abstract class BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@CreationTimestamp
@Column(updatable = false)
private LocalDateTime createdAt;
@UpdateTimestamp
private LocalDateTime updatedAt;
public BaseEntity() {}
public BaseEntity(Long id, LocalDateTime createdAt, LocalDateTime updatedAt) {
this.id = id;
this.createdAt = createdAt;
this.updatedAt = updatedAt;
}
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public LocalDateTime getCreatedAt() { return createdAt; }
public void setCreatedAt(LocalDateTime createdAt) { this.createdAt = createdAt; }
public LocalDateTime getUpdatedAt() { return updatedAt; }
public void setUpdatedAt(LocalDateTime updatedAt) { this.updatedAt = updatedAt; }
}

View File

@@ -0,0 +1,44 @@
package com.ems.backend.model;
import jakarta.persistence.*;
import lombok.*;
import java.util.List;
@Entity
@Table(name = "classes")
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class ClassMapping extends BaseEntity {
@Column(nullable = false)
private String institution; // RIT, RSB
@Column(nullable = false)
private String department;
@Column(nullable = false)
private String academicYear; // 1st Year, 2nd Year, etc.
@ElementCollection
@CollectionTable(name = "class_sections", joinColumns = @JoinColumn(name = "class_id"))
@Column(name = "section_name")
private List<String> sections;
@Builder.Default
private String status = "Ready";
public String getInstitution() { return institution; }
public void setInstitution(String institution) { this.institution = institution; }
public String getDepartment() { return department; }
public void setDepartment(String department) { this.department = department; }
public String getAcademicYear() { return academicYear; }
public void setAcademicYear(String academicYear) { this.academicYear = academicYear; }
public java.util.List<String> getSections() { return sections; }
public void setSections(java.util.List<String> sections) { this.sections = sections; }
public String getStatus() { return status; }
public void setStatus(String status) { this.status = status; }
}

View File

@@ -0,0 +1,206 @@
package com.ems.backend.model;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Table;
import java.time.LocalDateTime;
import java.util.List;
@Entity
@Table(name = "events")
public class Event extends BaseEntity {
@Column(nullable = false)
private String title;
@Column(columnDefinition = "TEXT")
private String description;
@Column(nullable = false)
private LocalDateTime startDate;
@Column(nullable = false)
private LocalDateTime endDate;
@Column(nullable = false)
private String location;
@Column(nullable = false)
private String category; // ACADEMIC, CLUB, etc.
@Column(nullable = false)
private String type; // Workshop, Seminar, etc.
@Column(nullable = false)
private String institution; // RIT, RSB
@Column(nullable = false)
private String department;
@jakarta.persistence.ElementCollection
private List<String> academicYears;
@Column(nullable = false)
private String status; // PENDING, APPROVED, COMPLETED, CANCELLED
private String guestName;
private String guestSocialProfile;
@jakarta.persistence.ElementCollection
private List<String> requirements;
@jakarta.persistence.ElementCollection
private List<String> targetedSections;
private Double budget;
@Column(columnDefinition = "boolean default false")
private boolean hasRegistrationFee;
private Double registrationFee;
@jakarta.persistence.ElementCollection
private List<String> sponsors;
@jakarta.persistence.ManyToOne
@jakarta.persistence.JoinColumn(name = "user_id")
private User proposer;
@Column(columnDefinition = "TEXT")
private String rejectionReason;
private String groupRequestId;
private String centreName;
@Column(columnDefinition = "boolean default false")
private boolean isPublicEvent;
@jakarta.persistence.Transient
private String conflictMessage;
public Event() {}
public Event(String title, String description, LocalDateTime startDate, LocalDateTime endDate, String location, String category, String type, String institution, String department, List<String> academicYears, String status, String guestName, String guestSocialProfile, List<String> requirements, List<String> targetedSections, Double budget, boolean hasRegistrationFee, Double registrationFee, User proposer, String centreName, boolean isPublicEvent) {
this.title = title;
this.description = description;
this.startDate = startDate;
this.endDate = endDate;
this.location = location;
this.category = category;
this.type = type;
this.institution = institution;
this.department = department;
this.academicYears = academicYears;
this.status = status;
this.guestName = guestName;
this.guestSocialProfile = guestSocialProfile;
this.requirements = requirements;
this.targetedSections = targetedSections;
this.budget = budget;
this.hasRegistrationFee = hasRegistrationFee;
this.registrationFee = registrationFee;
this.proposer = proposer;
this.centreName = centreName;
this.isPublicEvent = isPublicEvent;
}
// Manual Getters and Setters
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
public LocalDateTime getStartDate() { return startDate; }
public void setStartDate(LocalDateTime startDate) { this.startDate = startDate; }
public LocalDateTime getEndDate() { return endDate; }
public void setEndDate(LocalDateTime endDate) { this.endDate = endDate; }
public String getLocation() { return location; }
public void setLocation(String location) { this.location = location; }
public String getCategory() { return category; }
public void setCategory(String category) { this.category = category; }
public String getType() { return type; }
public void setType(String type) { this.type = type; }
public String getInstitution() { return institution; }
public void setInstitution(String institution) { this.institution = institution; }
public String getDepartment() { return department; }
public void setDepartment(String department) { this.department = department; }
public List<String> getAcademicYears() { return academicYears; }
public void setAcademicYears(List<String> academicYears) { this.academicYears = academicYears; }
public String getStatus() { return status; }
public void setStatus(String status) { this.status = status; }
public String getGuestName() { return guestName; }
public void setGuestName(String guestName) { this.guestName = guestName; }
public String getGuestSocialProfile() { return guestSocialProfile; }
public void setGuestSocialProfile(String guestSocialProfile) { this.guestSocialProfile = guestSocialProfile; }
public List<String> getRequirements() { return requirements; }
public void setRequirements(List<String> requirements) { this.requirements = requirements; }
public List<String> getTargetedSections() { return targetedSections; }
public void setTargetedSections(List<String> targetedSections) { this.targetedSections = targetedSections; }
public Double getBudget() { return budget; }
public void setBudget(Double budget) { this.budget = budget; }
public boolean isHasRegistrationFee() { return hasRegistrationFee; }
public void setHasRegistrationFee(boolean hasRegistrationFee) { this.hasRegistrationFee = hasRegistrationFee; }
public Double getRegistrationFee() { return registrationFee; }
public void setRegistrationFee(Double registrationFee) { this.registrationFee = registrationFee; }
public List<String> getSponsors() { return sponsors; }
public void setSponsors(List<String> sponsors) { this.sponsors = sponsors; }
public User getProposer() { return proposer; }
public void setProposer(User proposer) { this.proposer = proposer; }
public String getRejectionReason() { return rejectionReason; }
public void setRejectionReason(String rejectionReason) { this.rejectionReason = rejectionReason; }
public String getGroupRequestId() { return groupRequestId; }
public void setGroupRequestId(String groupRequestId) { this.groupRequestId = groupRequestId; }
public String getConflictMessage() { return conflictMessage; }
public void setConflictMessage(String conflictMessage) { this.conflictMessage = conflictMessage; }
public String getCentreName() {
return centreName;
}
public void setCentreName(String centreName) {
this.centreName = centreName;
}
public boolean isPublicEvent() {
return isPublicEvent;
}
public void setPublicEvent(boolean publicEvent) {
isPublicEvent = publicEvent;
}
// Manual Builder
public static EventBuilder builder() {
return new EventBuilder();
}
public static class EventBuilder {
private Event event = new Event();
public EventBuilder title(String title) { event.setTitle(title); return this; }
public EventBuilder description(String description) { event.setDescription(description); return this; }
public EventBuilder startDate(LocalDateTime startDate) { event.setStartDate(startDate); return this; }
public EventBuilder endDate(LocalDateTime endDate) { event.setEndDate(endDate); return this; }
public EventBuilder location(String location) { event.setLocation(location); return this; }
public EventBuilder category(String category) { event.setCategory(category); return this; }
public EventBuilder type(String type) { event.setType(type); return this; }
public EventBuilder institution(String institution) { event.setInstitution(institution); return this; }
public EventBuilder department(String department) { event.setDepartment(department); return this; }
public EventBuilder academicYears(List<String> academicYears) { event.setAcademicYears(academicYears); return this; }
public EventBuilder status(String status) { event.setStatus(status); return this; }
public EventBuilder guestName(String guestName) { event.setGuestName(guestName); return this; }
public EventBuilder guestSocialProfile(String guestSocialProfile) { event.setGuestSocialProfile(guestSocialProfile); return this; }
public EventBuilder requirements(List<String> requirements) { event.setRequirements(requirements); return this; }
public EventBuilder targetedSections(List<String> targetedSections) { event.setTargetedSections(targetedSections); return this; }
public EventBuilder budget(Double budget) { event.setBudget(budget); return this; }
public EventBuilder hasRegistrationFee(boolean hasRegistrationFee) { event.setHasRegistrationFee(hasRegistrationFee); return this; }
public EventBuilder registrationFee(Double registrationFee) { event.setRegistrationFee(registrationFee); return this; }
public EventBuilder sponsors(List<String> sponsors) { event.setSponsors(sponsors); return this; }
public EventBuilder proposer(User proposer) { event.setProposer(proposer); return this; }
public EventBuilder groupRequestId(String groupRequestId) { event.setGroupRequestId(groupRequestId); return this; }
public Event build() {
return event;
}
}
}

View File

@@ -0,0 +1,31 @@
package com.ems.backend.model;
import jakarta.persistence.*;
import lombok.Data;
import java.time.LocalDate;
import java.time.LocalDateTime;
@Entity
@Data
@Table(name = "institutional_notes")
public class InstitutionalNote {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String content;
@Column(nullable = false)
private LocalDate targetDate;
private String authorName;
private String authorEmail;
private LocalDateTime createdAt;
@PrePersist
protected void onCreate() {
createdAt = LocalDateTime.now();
}
}

View File

@@ -0,0 +1,94 @@
package com.ems.backend.model;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Table;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
@Entity
@Table(name = "users")
public class User extends BaseEntity {
@Column(unique = true, nullable = false)
private String email;
@Column(nullable = false)
private String password;
@Column(nullable = false)
private String fullName;
@Column(nullable = false)
private String role; // FACULTY, HOD, PRINCIPAL
private String department;
@Column(columnDefinition = "boolean default false")
@JsonProperty("isClubCoordinator")
private boolean isClubCoordinator;
@Column(columnDefinition = "boolean default false")
@JsonProperty("isPlacementStaff")
private boolean isPlacementStaff;
@Column(columnDefinition = "boolean default false")
@JsonProperty("isClassIncharge")
private boolean isClassIncharge;
@Column
private Integer classStrength;
@Column
private String inchargeClass;
@Column
private String inchargeBatch;
@Column
private String inchargeSection;
@jakarta.persistence.ElementCollection
@JsonProperty("assignedClubs")
private List<String> assignedClubs;
public User() {}
public User(String email, String password, String fullName, String role, String department, boolean isClubCoordinator, boolean isPlacementStaff, List<String> assignedClubs) {
this.email = email;
this.password = password;
this.fullName = fullName;
this.role = role;
this.department = department;
this.isClubCoordinator = isClubCoordinator;
this.isPlacementStaff = isPlacementStaff;
this.assignedClubs = assignedClubs;
}
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
public String getPassword() { return password; }
public void setPassword(String password) { this.password = password; }
public String getFullName() { return fullName; }
public void setFullName(String fullName) { this.fullName = fullName; }
public String getRole() { return role; }
public void setRole(String role) { this.role = role; }
public String getDepartment() { return department; }
public void setDepartment(String department) { this.department = department; }
public boolean isClubCoordinator() { return isClubCoordinator; }
public void setClubCoordinator(boolean clubCoordinator) { isClubCoordinator = clubCoordinator; }
public boolean isPlacementStaff() { return isPlacementStaff; }
public void setPlacementStaff(boolean placementStaff) { isPlacementStaff = placementStaff; }
public boolean isClassIncharge() { return isClassIncharge; }
public void setClassIncharge(boolean classIncharge) { isClassIncharge = classIncharge; }
public Integer getClassStrength() { return classStrength; }
public void setClassStrength(Integer classStrength) { this.classStrength = classStrength; }
public String getInchargeClass() { return inchargeClass; }
public void setInchargeClass(String inchargeClass) { this.inchargeClass = inchargeClass; }
public String getInchargeBatch() { return inchargeBatch; }
public void setInchargeBatch(String inchargeBatch) { this.inchargeBatch = inchargeBatch; }
public String getInchargeSection() { return inchargeSection; }
public void setInchargeSection(String inchargeSection) { this.inchargeSection = inchargeSection; }
public List<String> getAssignedClubs() { return assignedClubs; }
public void setAssignedClubs(List<String> assignedClubs) { this.assignedClubs = assignedClubs; }
}

View File

@@ -0,0 +1,9 @@
package com.ems.backend.repository;
import com.ems.backend.model.ClassMapping;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ClassRepository extends JpaRepository<ClassMapping, Long> {
}

View File

@@ -0,0 +1,26 @@
package com.ems.backend.repository;
import com.ems.backend.model.Event;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.time.LocalDateTime;
import java.util.List;
@Repository
public interface EventRepository extends JpaRepository<Event, Long> {
List<Event> findByCategory(String category);
List<Event> findByStatus(String status);
@Query("SELECT e FROM Event e WHERE e.status = 'APPROVED' AND e.institution = :institution AND e.location = :location " +
"AND e.startDate < :endDate AND e.endDate > :startDate AND e.id != :eventId " +
"AND (e.groupRequestId IS NULL OR :groupRequestId IS NULL OR e.groupRequestId != :groupRequestId)")
List<Event> findConflictingEvents(@Param("institution") String institution,
@Param("location") String location,
@Param("startDate") LocalDateTime startDate,
@Param("endDate") LocalDateTime endDate,
@Param("eventId") Long eventId,
@Param("groupRequestId") String groupRequestId);
}

View File

@@ -0,0 +1,10 @@
package com.ems.backend.repository;
import com.ems.backend.model.InstitutionalNote;
import org.springframework.data.jpa.repository.JpaRepository;
import java.time.LocalDate;
import java.util.List;
public interface InstitutionalNoteRepository extends JpaRepository<InstitutionalNote, Long> {
List<InstitutionalNote> findByTargetDate(LocalDate targetDate);
}

View File

@@ -0,0 +1,12 @@
package com.ems.backend.repository;
import com.ems.backend.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByEmail(String email);
}

View File

@@ -0,0 +1,14 @@
server.port=8081
spring.application.name=backend
# Database Configuration
spring.datasource.url=jdbc:mysql://localhost:3306/ems_db?createDatabaseIfNotExist=true&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=Abiram@07
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# JPA Configuration
spring.jpa.hibernate.ddl-auto=create
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect

View File

@@ -0,0 +1,13 @@
package com.ems.backend;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class BackendApplicationTests {
@Test
void contextLoads() {
}
}