Vendor Dashboard updated

This commit is contained in:
2026-04-09 14:14:57 +05:30
commit dd3e811cdf
113 changed files with 16725 additions and 0 deletions

2
backend/.gitattributes vendored Normal file
View File

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

33
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

120
backend/backend_startup.log Normal file
View File

@@ -0,0 +1,120 @@
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------< com.example:backend >-------------------------
[INFO] Building backend 0.0.1-SNAPSHOT
[INFO] from pom.xml
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] >>> spring-boot:3.5.0:run (default-cli) > test-compile @ backend >>>
[INFO]
[INFO] --- resources:3.3.1:resources (default-resources) @ backend ---
[INFO] Copying 1 resource from src/main/resources to target/classes
[INFO] Copying 0 resource from src/main/resources to target/classes
[INFO]
[INFO] --- compiler:3.14.0:compile (default-compile) @ backend ---
[INFO] Recompiling the module because of added or removed source files.
[INFO] Compiling 21 source files with javac [debug parameters release 17] to target/classes
[INFO]
[INFO] --- resources:3.3.1:testResources (default-testResources) @ backend ---
[INFO] skip non existing resourceDirectory /Users/sidharth/development/Positeasy clone/backend/src/test/resources
[INFO]
[INFO] --- compiler:3.14.0:testCompile (default-testCompile) @ backend ---
[INFO] Recompiling the module because of changed dependency.
[INFO] Compiling 1 source file with javac [debug parameters release 17] to target/test-classes
[INFO]
[INFO] <<< spring-boot:3.5.0:run (default-cli) < test-compile @ backend <<<
[INFO]
[INFO]
[INFO] --- spring-boot:3.5.0:run (default-cli) @ backend ---
[INFO] Attaching agents: []
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v3.5.0)
2026-04-07T19:05:00.341+05:30 INFO 10378 --- [backend] [ main] c.rit.canteen.sales.BackendApplication : Starting BackendApplication using Java 17.0.18 with PID 10378 (/Users/sidharth/development/Positeasy clone/backend/target/classes started by sidharth in /Users/sidharth/development/Positeasy clone/backend)
2026-04-07T19:05:00.342+05:30 INFO 10378 --- [backend] [ main] c.rit.canteen.sales.BackendApplication : No active profile set, falling back to 1 default profile: "default"
2026-04-07T19:05:00.576+05:30 INFO 10378 --- [backend] [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2026-04-07T19:05:00.602+05:30 INFO 10378 --- [backend] [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 16 ms. Found 3 JPA repository interfaces.
2026-04-07T19:05:00.781+05:30 INFO 10378 --- [backend] [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port 8080 (http)
2026-04-07T19:05:00.787+05:30 INFO 10378 --- [backend] [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2026-04-07T19:05:00.787+05:30 INFO 10378 --- [backend] [ main] o.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/10.1.41]
2026-04-07T19:05:00.810+05:30 INFO 10378 --- [backend] [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2026-04-07T19:05:00.810+05:30 INFO 10378 --- [backend] [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 453 ms
2026-04-07T19:05:00.870+05:30 INFO 10378 --- [backend] [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2026-04-07T19:05:00.890+05:30 INFO 10378 --- [backend] [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 6.6.15.Final
2026-04-07T19:05:00.901+05:30 INFO 10378 --- [backend] [ main] o.h.c.internal.RegionFactoryInitiator : HHH000026: Second-level cache disabled
2026-04-07T19:05:00.989+05:30 INFO 10378 --- [backend] [ main] o.s.o.j.p.SpringPersistenceUnitInfo : No LoadTimeWeaver setup: ignoring JPA class transformer
2026-04-07T19:05:01.000+05:30 INFO 10378 --- [backend] [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2026-04-07T19:05:01.067+05:30 INFO 10378 --- [backend] [ main] com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Added connection org.postgresql.jdbc.PgConnection@108b121f
2026-04-07T19:05:01.067+05:30 INFO 10378 --- [backend] [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2026-04-07T19:05:01.083+05:30 WARN 10378 --- [backend] [ main] org.hibernate.orm.deprecation : HHH90000025: PostgreSQLDialect does not need to be specified explicitly using 'hibernate.dialect' (remove the property setting and it will be selected by default)
2026-04-07T19:05:01.089+05:30 INFO 10378 --- [backend] [ main] org.hibernate.orm.connections.pooling : HHH10001005: Database info:
Database JDBC URL [Connecting through datasource 'HikariDataSource (HikariPool-1)']
Database driver: undefined/unknown
Database version: 18.1
Autocommit mode: undefined/unknown
Isolation level: undefined/unknown
Minimum pool size: undefined/unknown
Maximum pool size: undefined/unknown
2026-04-07T19:05:01.398+05:30 INFO 10378 --- [backend] [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000489: No JTA platform available (set 'hibernate.transaction.jta.platform' to enable JTA platform integration)
2026-04-07T19:05:01.487+05:30 INFO 10378 --- [backend] [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2026-04-07T19:05:01.614+05:30 WARN 10378 --- [backend] [ main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2026-04-07T19:05:01.779+05:30 INFO 10378 --- [backend] [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port 8080 (http) with context path '/'
2026-04-07T19:05:01.783+05:30 INFO 10378 --- [backend] [ main] c.rit.canteen.sales.BackendApplication : Started BackendApplication in 1.584 seconds (process running for 1.69)
Hibernate: select count(*) from base_items bi1_0
Hibernate: select count(*) from products p1_0
2026-04-07T19:06:48.144+05:30 INFO 10378 --- [backend] [0.0-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2026-04-07T19:06:48.146+05:30 INFO 10378 --- [backend] [0.0-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2026-04-07T19:06:48.147+05:30 INFO 10378 --- [backend] [0.0-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 1 ms
Hibernate: select bi1_0.id,bi1_0.active,bi1_0.description,bi1_0.name from base_items bi1_0
Hibernate: select bi1_0.id,bi1_0.active,bi1_0.description,bi1_0.name from base_items bi1_0
Hibernate: select bi1_0.id,bi1_0.active,bi1_0.description,bi1_0.name from base_items bi1_0
Hibernate: select p1_0.id,p1_0.active,p1_0.attributes_optional,p1_0.barcode,p1_0.base_price,p1_0.category,p1_0.counter,p1_0.description,p1_0.discount_amount,p1_0.discount_percent,p1_0.has_allergy,p1_0.image_data,p1_0.is_veg,p1_0.name,p1_0.offer_price,p1_0.parcel_charges,p1_0.parcel_not_allowed,p1_0.price,p1_0.product_id,p1_0.session_optional,p1_0.stock,p1_0.tag from products p1_0
Hibernate: select bi1_0.id,bi1_0.active,bi1_0.description,bi1_0.name from base_items bi1_0
Hibernate: select s1_0.product_id,s1_0.id,s1_0.active,s1_0.day_of_week,s1_0.end_time,s1_0.start_time from product_sessions s1_0 where s1_0.product_id=?
Hibernate: select p1_0.id,p1_0.active,p1_0.attributes_optional,p1_0.barcode,p1_0.base_price,p1_0.category,p1_0.counter,p1_0.description,p1_0.discount_amount,p1_0.discount_percent,p1_0.has_allergy,p1_0.image_data,p1_0.is_veg,p1_0.name,p1_0.offer_price,p1_0.parcel_charges,p1_0.parcel_not_allowed,p1_0.price,p1_0.product_id,p1_0.session_optional,p1_0.stock,p1_0.tag from products p1_0
Hibernate: select s1_0.product_id,s1_0.id,s1_0.active,s1_0.day_of_week,s1_0.end_time,s1_0.start_time from product_sessions s1_0 where s1_0.product_id=?
Hibernate: select bi1_0.id,bi1_0.active,bi1_0.description,bi1_0.name from base_items bi1_0
Hibernate: select bi1_0.id,bi1_0.active,bi1_0.description,bi1_0.name from base_items bi1_0
Hibernate: select p1_0.id,p1_0.active,p1_0.attributes_optional,p1_0.barcode,p1_0.base_price,p1_0.category,p1_0.counter,p1_0.description,p1_0.discount_amount,p1_0.discount_percent,p1_0.has_allergy,p1_0.image_data,p1_0.is_veg,p1_0.name,p1_0.offer_price,p1_0.parcel_charges,p1_0.parcel_not_allowed,p1_0.price,p1_0.product_id,p1_0.session_optional,p1_0.stock,p1_0.tag from products p1_0
Hibernate: select s1_0.product_id,s1_0.id,s1_0.active,s1_0.day_of_week,s1_0.end_time,s1_0.start_time from product_sessions s1_0 where s1_0.product_id=?
Hibernate: select p1_0.id,p1_0.active,p1_0.attributes_optional,p1_0.barcode,p1_0.base_price,p1_0.category,p1_0.counter,p1_0.description,p1_0.discount_amount,p1_0.discount_percent,p1_0.has_allergy,p1_0.image_data,p1_0.is_veg,p1_0.name,p1_0.offer_price,p1_0.parcel_charges,p1_0.parcel_not_allowed,p1_0.price,p1_0.product_id,p1_0.session_optional,p1_0.stock,p1_0.tag from products p1_0
Hibernate: select s1_0.product_id,s1_0.id,s1_0.active,s1_0.day_of_week,s1_0.end_time,s1_0.start_time from product_sessions s1_0 where s1_0.product_id=?
Hibernate: select bi1_0.id,bi1_0.active,bi1_0.description,bi1_0.name from base_items bi1_0
Hibernate: select p1_0.id,p1_0.active,p1_0.attributes_optional,p1_0.barcode,p1_0.base_price,p1_0.category,p1_0.counter,p1_0.description,p1_0.discount_amount,p1_0.discount_percent,p1_0.has_allergy,p1_0.image_data,p1_0.is_veg,p1_0.name,p1_0.offer_price,p1_0.parcel_charges,p1_0.parcel_not_allowed,p1_0.price,p1_0.product_id,p1_0.session_optional,p1_0.stock,p1_0.tag from products p1_0
Hibernate: select s1_0.product_id,s1_0.id,s1_0.active,s1_0.day_of_week,s1_0.end_time,s1_0.start_time from product_sessions s1_0 where s1_0.product_id=?
Hibernate: select bi1_0.id,bi1_0.active,bi1_0.description,bi1_0.name from base_items bi1_0
Hibernate: select p1_0.id,p1_0.active,p1_0.attributes_optional,p1_0.barcode,p1_0.base_price,p1_0.category,p1_0.counter,p1_0.description,p1_0.discount_amount,p1_0.discount_percent,p1_0.has_allergy,p1_0.image_data,p1_0.is_veg,p1_0.name,p1_0.offer_price,p1_0.parcel_charges,p1_0.parcel_not_allowed,p1_0.price,p1_0.product_id,p1_0.session_optional,p1_0.stock,p1_0.tag from products p1_0
Hibernate: select s1_0.product_id,s1_0.id,s1_0.active,s1_0.day_of_week,s1_0.end_time,s1_0.start_time from product_sessions s1_0 where s1_0.product_id=?
Hibernate: select p1_0.id,p1_0.active,p1_0.attributes_optional,p1_0.barcode,p1_0.base_price,p1_0.category,p1_0.counter,p1_0.description,p1_0.discount_amount,p1_0.discount_percent,p1_0.has_allergy,p1_0.image_data,p1_0.is_veg,p1_0.name,p1_0.offer_price,p1_0.parcel_charges,p1_0.parcel_not_allowed,p1_0.price,p1_0.product_id,p1_0.session_optional,p1_0.stock,p1_0.tag from products p1_0 where p1_0.id=?
Hibernate: select s1_0.product_id,s1_0.id,s1_0.active,s1_0.day_of_week,s1_0.end_time,s1_0.start_time from product_sessions s1_0 where s1_0.product_id=?
Hibernate: update products set active=?,attributes_optional=?,barcode=?,base_price=?,category=?,counter=?,description=?,discount_amount=?,discount_percent=?,has_allergy=?,image_data=?,is_veg=?,name=?,offer_price=?,parcel_charges=?,parcel_not_allowed=?,price=?,product_id=?,session_optional=?,stock=?,tag=? where id=?
Hibernate: select p1_0.id,p1_0.active,p1_0.attributes_optional,p1_0.barcode,p1_0.base_price,p1_0.category,p1_0.counter,p1_0.description,p1_0.discount_amount,p1_0.discount_percent,p1_0.has_allergy,p1_0.image_data,p1_0.is_veg,p1_0.name,p1_0.offer_price,p1_0.parcel_charges,p1_0.parcel_not_allowed,p1_0.price,p1_0.product_id,p1_0.session_optional,p1_0.stock,p1_0.tag from products p1_0
Hibernate: select s1_0.product_id,s1_0.id,s1_0.active,s1_0.day_of_week,s1_0.end_time,s1_0.start_time from product_sessions s1_0 where s1_0.product_id=?
Hibernate: select bi1_0.id,bi1_0.active,bi1_0.description,bi1_0.name from base_items bi1_0
Hibernate: select bi1_0.id,bi1_0.active,bi1_0.description,bi1_0.name from base_items bi1_0
Hibernate: select p1_0.id,p1_0.active,p1_0.attributes_optional,p1_0.barcode,p1_0.base_price,p1_0.category,p1_0.counter,p1_0.description,p1_0.discount_amount,p1_0.discount_percent,p1_0.has_allergy,p1_0.image_data,p1_0.is_veg,p1_0.name,p1_0.offer_price,p1_0.parcel_charges,p1_0.parcel_not_allowed,p1_0.price,p1_0.product_id,p1_0.session_optional,p1_0.stock,p1_0.tag from products p1_0
Hibernate: select s1_0.product_id,s1_0.id,s1_0.active,s1_0.day_of_week,s1_0.end_time,s1_0.start_time from product_sessions s1_0 where s1_0.product_id=?
Hibernate: select bi1_0.id,bi1_0.active,bi1_0.description,bi1_0.name from base_items bi1_0
Hibernate: select bi1_0.id,bi1_0.active,bi1_0.description,bi1_0.name from base_items bi1_0
Hibernate: select bi1_0.id,bi1_0.active,bi1_0.description,bi1_0.name from base_items bi1_0
Hibernate: select bi1_0.id,bi1_0.active,bi1_0.description,bi1_0.name from base_items bi1_0
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 08:44 min
[INFO] Finished at: 2026-04-07T19:13:43+05:30
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:3.5.0:run (default-cli) on project backend: Process terminated with exit code: 137 -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

295
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
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"

77
backend/pom.xml Normal file
View File

@@ -0,0 +1,77 @@
<?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.5.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</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-data-jpa</artifactId>
</dependency>
<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>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</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>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,19 @@
package com.rit.canteen.sales;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration;
@SpringBootApplication(exclude = {
SecurityAutoConfiguration.class,
UserDetailsServiceAutoConfiguration.class
})
@org.springframework.scheduling.annotation.EnableScheduling
public class BackendApplication {
public static void main(String[] args) {
SpringApplication.run(BackendApplication.class, args);
}
}

View File

@@ -0,0 +1,54 @@
package com.rit.canteen.sales.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
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;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf(AbstractHttpConfigurer::disable)
.cors(Customizer.withDefaults())
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/auth/**").permitAll()
.requestMatchers("/api/**").permitAll()
.anyRequest().permitAll()
);
return http.build();
}
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
// Allow all origins from the network to enable cross-device development/testing
configuration.setAllowedOriginPatterns(List.of("*"));
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
configuration.setAllowedHeaders(List.of("*"));
configuration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}

View File

@@ -0,0 +1,24 @@
package com.rit.canteen.sales.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOriginPatterns("*")
.allowedMethods("GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS")
.allowedHeaders("*")
.allowCredentials(true);
}
};
}
}

View File

@@ -0,0 +1,40 @@
package com.rit.canteen.sales.controller;
import com.rit.canteen.sales.model.BaseItem;
import com.rit.canteen.sales.repository.BaseItemRepository;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/base-items")
public class BaseItemController {
@Autowired
private BaseItemRepository baseItemRepository;
@GetMapping
public List<BaseItem> getAllBaseItems() {
return baseItemRepository.findAll();
}
@PostMapping
public BaseItem createBaseItem(@Valid @RequestBody BaseItem baseItem) {
return baseItemRepository.save(baseItem);
}
@PutMapping("/{id}")
public ResponseEntity<BaseItem> updateBaseItem(@PathVariable Long id, @Valid @RequestBody BaseItem baseItemDetails) {
return baseItemRepository.findById(id)
.map(item -> {
item.setName(baseItemDetails.getName());
item.setDescription(baseItemDetails.getDescription());
item.setActive(baseItemDetails.isActive());
return ResponseEntity.ok(baseItemRepository.save(item));
})
.orElse(ResponseEntity.notFound().build());
}
}

View File

@@ -0,0 +1,29 @@
package com.rit.canteen.sales.controller;
import com.rit.canteen.sales.model.GeneralDashboardData;
import com.rit.canteen.sales.model.Order;
import com.rit.canteen.sales.service.DashboardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/api/dashboard")
public class DashboardController {
@Autowired
private DashboardService dashboardService;
@GetMapping("/stats")
public GeneralDashboardData getStats() {
return dashboardService.getGeneralDashboardData();
}
@GetMapping("/recent-orders")
public List<Order> getRecentOrders() {
return dashboardService.getRecentOrders();
}
}

View File

@@ -0,0 +1,215 @@
package com.rit.canteen.sales.controller;
import com.rit.canteen.sales.model.Order;
import com.rit.canteen.sales.model.OrderItem;
import com.rit.canteen.sales.model.User;
import com.rit.canteen.sales.repository.OrderRepository;
import com.rit.canteen.sales.repository.ProductRepository;
import jakarta.persistence.criteria.Join;
import jakarta.persistence.criteria.JoinType;
import jakarta.persistence.criteria.Predicate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
import java.util.*;
@RestController
@RequestMapping("/api/orders")
public class OrderController {
@Autowired
private OrderRepository orderRepository;
@Autowired
private ProductRepository productRepository;
@Autowired
private com.rit.canteen.sales.service.OrderArchiverService orderArchiverService;
@GetMapping("/all")
public ResponseEntity<?> getAllOrders(
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startDate,
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endDate,
@RequestParam(required = false) String status,
@RequestParam(required = false) String paymentType,
@RequestParam(required = false) String search,
@RequestParam(defaultValue = "false") boolean archived,
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int size) {
try {
System.out.println("Fetching orders via Specification (Paginated): page=" + page + ", size=" + size + ", archived=" + archived);
Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "createdAt"));
Specification<Order> spec = (root, query, cb) -> {
List<Predicate> predicates = new ArrayList<>();
// Add archive filter
predicates.add(cb.equal(root.get("isArchived"), archived));
if (startDate != null) {
predicates.add(cb.greaterThanOrEqualTo(root.get("createdAt"), startDate));
}
if (endDate != null) {
predicates.add(cb.lessThanOrEqualTo(root.get("createdAt"), endDate));
}
if (status != null && !status.isEmpty()) {
predicates.add(cb.equal(root.get("status"), status));
}
if (paymentType != null && !paymentType.isEmpty()) {
predicates.add(cb.equal(root.get("paymentMethod"), paymentType));
}
if (search != null && !search.isEmpty()) {
String searchLower = "%" + search.toLowerCase() + "%";
Join<Order, User> userJoin = root.join("user", JoinType.LEFT);
Predicate searchPredicate = cb.or(
cb.like(cb.lower(root.get("displayOrderId")), searchLower),
cb.like(cb.lower(root.get("orderNumber")), searchLower),
cb.like(cb.lower(userJoin.get("name")), searchLower),
cb.like(cb.lower(userJoin.get("mobileNumber")), searchLower)
);
predicates.add(searchPredicate);
}
// Fetch join for actual data queries to avoid N+1
if (query != null && !Long.class.equals(query.getResultType()) && !long.class.equals(query.getResultType())) {
root.fetch("user", JoinType.LEFT);
}
return cb.and(predicates.toArray(new Predicate[0]));
};
Page<Order> orderPage = orderRepository.findAll(spec, pageable);
return ResponseEntity.ok(orderPage);
} catch (Exception e) {
System.err.println("Error fetching orders with Specification: " + e.getMessage());
e.printStackTrace();
Map<String, String> error = new HashMap<>();
error.put("error", e.getMessage());
return ResponseEntity.status(500).body(error);
}
}
@PostMapping("/archive-now")
public ResponseEntity<?> triggerArchival() {
try {
int count = orderArchiverService.archiveNow();
return ResponseEntity.ok(Map.of("success", true, "archivedCount", count));
} catch (Exception e) {
return ResponseEntity.status(500).body(Map.of("error", e.getMessage()));
}
}
@PostMapping
public ResponseEntity<Map<String, Object>> placeOrder(@RequestBody Order order) {
// Link items to the order for bidirectional relationship
if (order.getItems() != null) {
for (OrderItem item : order.getItems()) {
System.out.println("🛒 RECEIVED ITEM: " + item.getProductName() + " | StallID: " + item.getStallId() + " | StallName: " + item.getStallName());
item.setOrder(order);
}
}
// Use the actual creation time or current time for counting
LocalDateTime now = LocalDateTime.now();
order.setCreatedAt(now);
// Calculate start of current day to find how many orders placed today
LocalDateTime startOfDay = now.toLocalDate().atStartOfDay();
long todaysOrderCount = orderRepository.countByCreatedAtGreaterThanEqual(startOfDay);
// Generate formatted display ID (#001, #002...) resetting daily
String displayId = String.format("%03d", todaysOrderCount + 1);
order.setDisplayOrderId(displayId);
// Save the complete order first
Order savedOrder = orderRepository.save(order);
// --- Reduct Stock Logic ---
if (savedOrder.getItems() != null) {
for (OrderItem item : savedOrder.getItems()) {
Long productId = item.getProductId();
if (productId != null) {
productRepository.findById(productId).ifPresent(product -> {
int currentStock = product.getStock() != null ? product.getStock() : 0;
product.setStock(currentStock - item.getQuantity());
productRepository.save(product);
System.out.println("Updating Stock for " + product.getName() + ": " + currentStock + " -> " + product.getStock());
});
}
}
}
System.out.println("Placed Daily Order: " + savedOrder.getId() + " -> Display ID: #" + displayId);
Map<String, Object> response = new HashMap<>();
response.put("success", true);
response.put("orderNumber", savedOrder.getOrderNumber()); // Secure ID for QR
response.put("displayOrderId", savedOrder.getDisplayOrderId()); // Sequential ID (#001)
response.put("message", "Order placed successfully");
return ResponseEntity.ok(response);
}
@GetMapping("/user/{userId}")
public List<Order> getUserOrders(@PathVariable Long userId) {
return orderRepository.findByUserIdOrderByCreatedAtDesc(userId);
}
@PatchMapping("/{id}/status")
public ResponseEntity<?> updateOrderStatus(
@PathVariable Long id,
@RequestBody Map<String, String> statusUpdate) {
try {
String newStatus = statusUpdate.get("status");
if (newStatus == null || newStatus.isEmpty()) {
return ResponseEntity.badRequest().body(Map.of("error", "Status is required"));
}
return orderRepository.findById(id)
.map(order -> {
order.setStatus(newStatus.toUpperCase());
orderRepository.save(order);
return ResponseEntity.ok(Map.of("success", true, "message", "Order status updated to " + newStatus));
})
.orElse(ResponseEntity.notFound().build());
} catch (Exception e) {
return ResponseEntity.status(500).body(Map.of("error", e.getMessage()));
}
}
@PutMapping("/{id}")
public ResponseEntity<?> updateOrder(@PathVariable Long id, @RequestBody Order updatedOrder) {
try {
return orderRepository.findById(id)
.map(existingOrder -> {
// Update basic fields
existingOrder.setTotalAmount(updatedOrder.getTotalAmount());
existingOrder.setPaymentMethod(updatedOrder.getPaymentMethod());
// Clear and replace items for a clean update
existingOrder.getItems().clear();
if (updatedOrder.getItems() != null) {
for (OrderItem newItem : updatedOrder.getItems()) {
newItem.setOrder(existingOrder);
existingOrder.getItems().add(newItem);
}
}
Order saved = orderRepository.save(existingOrder);
return ResponseEntity.ok(saved);
})
.orElse(ResponseEntity.notFound().build());
} catch (Exception e) {
return ResponseEntity.status(500).body(Map.of("error", e.getMessage()));
}
}
}

View File

@@ -0,0 +1,92 @@
package com.rit.canteen.sales.controller;
import com.rit.canteen.sales.model.Product;
import com.rit.canteen.sales.repository.ProductRepository;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/products")
public class ProductController {
@Autowired
private ProductRepository productRepository;
@GetMapping
public List<Product> getAllProducts() {
return productRepository.findAllWithStalls();
}
@GetMapping("/category/{categoryName}")
public List<Product> getProductsByCategory(@PathVariable String categoryName) {
return productRepository.findAll().stream()
.filter(p -> categoryName.equals(p.getCategory()))
.toList();
}
@PostMapping
public Product createProduct(@Valid @RequestBody Product product) {
return productRepository.save(product);
}
@PutMapping("/{id}")
public ResponseEntity<Product> updateProduct(@PathVariable Long id, @Valid @RequestBody Product productDetails) {
return productRepository.findById(id)
.map(product -> {
product.setProductId(productDetails.getProductId());
product.setName(productDetails.getName());
product.setCategory(productDetails.getCategory());
product.setDescription(productDetails.getDescription());
product.setBasePrice(productDetails.getBasePrice());
product.setPrice(productDetails.getPrice());
product.setOfferPrice(productDetails.getOfferPrice());
product.setDiscountPercent(productDetails.getDiscountPercent());
product.setDiscountAmount(productDetails.getDiscountAmount());
product.setCounter(productDetails.getCounter());
product.setTag(productDetails.getTag());
product.setParcelCharges(productDetails.getParcelCharges());
product.setBarcode(productDetails.getBarcode());
product.setAttributesOptional(productDetails.isAttributesOptional());
product.setVeg(productDetails.isVeg());
product.setHasAllergy(productDetails.isHasAllergy());
product.setParcelNotAllowed(productDetails.isParcelNotAllowed());
product.setSessionOptional(productDetails.isSessionOptional());
product.getSessions().clear();
if (productDetails.getSessions() != null) {
product.getSessions().addAll(productDetails.getSessions());
}
product.setImageData(productDetails.getImageData());
product.setActive(productDetails.isActive());
product.setStock(productDetails.getStock());
return ResponseEntity.ok(productRepository.save(product));
})
.orElse(ResponseEntity.notFound().build());
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteProduct(@PathVariable Long id) {
return productRepository.findById(id)
.map(product -> {
productRepository.delete(product);
return ResponseEntity.ok().<Void>build();
})
.orElse(ResponseEntity.notFound().build());
}
@PatchMapping("/{id}/toggle-stock")
public ResponseEntity<Product> toggleStock(@PathVariable Long id) {
return productRepository.findById(id)
.map(product -> {
Integer currentStock = product.getStock() != null ? product.getStock() : 0;
product.setStock(currentStock > 0 ? 0 : 99); // Toggle between Out of Stock and In Stock
return ResponseEntity.ok(productRepository.save(product));
})
.orElse(ResponseEntity.notFound().build());
}
}

View File

@@ -0,0 +1,74 @@
package com.rit.canteen.sales.controller;
import com.rit.canteen.sales.model.PurchaseOrder;
import com.rit.canteen.sales.model.PurchaseOrderHistory;
import com.rit.canteen.sales.model.Vendor;
import com.rit.canteen.sales.service.PurchaseService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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/purchases")
public class PurchaseController {
private static final Logger logger = LoggerFactory.getLogger(PurchaseController.class);
@Autowired
private PurchaseService purchaseService;
@GetMapping("/orders")
public List<PurchaseOrder> getAllOrders() {
return purchaseService.getAllOrders();
}
@PostMapping("/orders")
public PurchaseOrder createOrder(@RequestBody PurchaseOrder order) {
logger.info("Received request to create/update order: {}", order.getPurchaseId());
return purchaseService.createOrder(order);
}
@GetMapping("/orders/{id}/history")
public List<PurchaseOrderHistory> getOrderHistory(@PathVariable Long id) {
return purchaseService.getOrderHistory(id);
}
@GetMapping("/vendors")
public List<Vendor> getAllVendors() {
return purchaseService.getAllVendors();
}
@PostMapping("/vendors")
public ResponseEntity<?> createVendor(@RequestBody Vendor vendor) {
try {
logger.info("Received request to create/update vendor: {}", vendor.getName());
Vendor savedVendor = purchaseService.createVendor(vendor);
return ResponseEntity.ok(savedVendor);
} catch (Exception e) {
logger.error("Error creating/updating vendor: ", e);
return ResponseEntity.status(500).body("Error: " + e.getMessage());
}
}
@DeleteMapping("/vendors/{id}")
public ResponseEntity<Void> deleteVendor(@PathVariable Long id) {
purchaseService.deleteVendor(id);
return ResponseEntity.noContent().build();
}
@DeleteMapping("/orders/{id}")
public ResponseEntity<Void> deleteOrder(@PathVariable Long id) {
purchaseService.deleteOrder(id);
return ResponseEntity.noContent().build();
}
@GetMapping("/summary")
public Map<String, Object> getSummary() {
return purchaseService.getPurchaseSummary();
}
}

View File

@@ -0,0 +1,133 @@
package com.rit.canteen.sales.controller;
import com.rit.canteen.sales.model.BaseItem;
import com.rit.canteen.sales.model.Product;
import com.rit.canteen.sales.model.Stall;
import com.rit.canteen.sales.repository.BaseItemRepository;
import com.rit.canteen.sales.repository.ProductRepository;
import com.rit.canteen.sales.repository.StallRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
@RestController
@RequestMapping("/api/stalls")
public class StallController {
@Autowired
private StallRepository stallRepository;
@Autowired
private ProductRepository productRepository;
@Autowired
private BaseItemRepository baseItemRepository;
@GetMapping
@Transactional(readOnly = true)
public List<Stall> getAllStalls() {
return stallRepository.findAll();
}
@GetMapping("/active")
@Transactional(readOnly = true)
public List<Stall> getActiveStalls() {
return stallRepository.findByActiveTrue();
}
@GetMapping("/{id}")
@Transactional(readOnly = true)
public ResponseEntity<Stall> getStallById(@PathVariable Long id) {
return stallRepository.findById(id)
.map(stall -> {
// Start with explicitly linked products
Set<Product> allProducts = new HashSet<>(stall.getProducts());
// Add products from linked BaseItems (categories)
if (stall.getBaseItems() != null) {
for (BaseItem baseItem : stall.getBaseItems()) {
List<Product> categoryProducts = productRepository.findByCategory(baseItem.getName());
if (categoryProducts != null) {
allProducts.addAll(categoryProducts);
}
}
}
// Update the products list in the object before returning
// Note: This is transient as the transaction is read-only
stall.setProducts(new ArrayList<>(allProducts));
return ResponseEntity.ok(stall);
})
.orElse(ResponseEntity.notFound().build());
}
@PostMapping
public ResponseEntity<Stall> createStall(@RequestBody Stall stall) {
Stall savedStall = stallRepository.save(stall);
return ResponseEntity.ok(savedStall);
}
@PutMapping("/{id}")
@Transactional
public ResponseEntity<Stall> updateStall(@PathVariable Long id, @RequestBody Stall updatedStall) {
return stallRepository.findById(id)
.map(stall -> {
stall.setName(updatedStall.getName());
stall.setDescription(updatedStall.getDescription());
if (updatedStall.getImageData() != null) {
stall.setImageData(updatedStall.getImageData());
}
stall.setActive(updatedStall.isActive());
stall.setTemporarilyClosed(updatedStall.isTemporarilyClosed());
stall.setSessionOptional(updatedStall.isSessionOptional());
// Update sessions
stall.getSessions().clear();
if (updatedStall.getSessions() != null) {
stall.getSessions().addAll(updatedStall.getSessions());
}
return ResponseEntity.ok(stallRepository.save(stall));
})
.orElse(ResponseEntity.notFound().build());
}
@DeleteMapping("/{id}")
public ResponseEntity<?> deleteStall(@PathVariable Long id) {
return stallRepository.findById(id)
.map(stall -> {
stallRepository.delete(stall);
return ResponseEntity.ok(Map.of("success", true, "message", "Stall deleted successfully"));
})
.orElse(ResponseEntity.notFound().build());
}
@PutMapping("/{id}/items")
@Transactional
public ResponseEntity<Stall> updateStallItems(
@PathVariable Long id,
@RequestBody Map<String, List<Long>> itemIds) {
return stallRepository.findById(id)
.map(stall -> {
if (itemIds.containsKey("productIds")) {
List<Product> products = productRepository.findAllById(itemIds.get("productIds"));
stall.setProducts(products);
}
if (itemIds.containsKey("baseItemIds")) {
List<BaseItem> baseItems = baseItemRepository.findAllById(itemIds.get("baseItemIds"));
stall.setBaseItems(baseItems);
}
return ResponseEntity.ok(stallRepository.save(stall));
})
.orElse(ResponseEntity.notFound().build());
}
}

View File

@@ -0,0 +1,65 @@
package com.rit.canteen.sales.controller;
import com.rit.canteen.sales.model.SystemUser;
import com.rit.canteen.sales.service.SystemUserService;
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;
import java.util.Optional;
@RestController
@RequestMapping("/api/system")
public class SystemAuthController {
@Autowired
private SystemUserService userService;
@PostMapping("/login")
public ResponseEntity<?> login(@RequestBody Map<String, String> credentials) {
String email = credentials.get("email");
String password = credentials.get("password");
Optional<SystemUser> user = userService.authenticate(email, password);
if (user.isPresent()) {
return ResponseEntity.ok(user.get());
} else {
return ResponseEntity.status(401).body("Invalid credentials");
}
}
@GetMapping("/managers")
public ResponseEntity<List<SystemUser>> getManagers() {
return ResponseEntity.ok(userService.getAllManagers());
}
@PostMapping("/managers")
public ResponseEntity<SystemUser> addManager(@RequestBody SystemUser manager) {
return ResponseEntity.ok(userService.createManager(manager));
}
@DeleteMapping("/managers/{id}")
public ResponseEntity<Void> deleteManager(@PathVariable Long id) {
userService.deleteManager(id);
return ResponseEntity.noContent().build();
}
@GetMapping("/staff")
public ResponseEntity<List<SystemUser>> getStaff() {
return ResponseEntity.ok(userService.getAllStaff());
}
@PostMapping("/staff")
public ResponseEntity<SystemUser> addStaff(@RequestBody SystemUser staff) {
return ResponseEntity.ok(userService.createStaff(staff));
}
@DeleteMapping("/staff/{id}")
public ResponseEntity<Void> deleteStaff(@PathVariable Long id) {
userService.deleteManager(id); // Using existing delete logic
return ResponseEntity.noContent().build();
}
}

View File

@@ -0,0 +1,100 @@
package com.rit.canteen.sales.controller;
import com.rit.canteen.sales.model.Order;
import com.rit.canteen.sales.model.Terminal;
import com.rit.canteen.sales.model.TerminalDTO;
import com.rit.canteen.sales.service.TerminalService;
import com.rit.canteen.sales.repository.TerminalRepository;
import com.rit.canteen.sales.repository.OrderRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@RestController
@RequestMapping("/api/terminals")
public class TerminalController {
@Autowired
private TerminalService terminalService;
@Autowired
private TerminalRepository terminalRepository;
@Autowired
private OrderRepository orderRepository;
@GetMapping
public List<TerminalDTO> getAllTerminals() {
return terminalService.getAllTerminals().stream()
.map(t -> new TerminalDTO(
t.getId(),
t.getName(),
t.getLocation(),
"********",
"****"
))
.toList();
}
@PostMapping
public ResponseEntity<Terminal> createTerminal(@RequestBody Terminal terminal) {
Terminal created = terminalService.createTerminal(terminal);
return new ResponseEntity<>(created, HttpStatus.CREATED);
}
@PostMapping("/{id}/verify-pin")
public ResponseEntity<?> verifyPinAndGetDetails(@PathVariable Long id, @RequestBody Map<String, String> request) {
String pin = request.get("pin");
if (terminalService.verifyPin(id, pin)) {
Optional<Terminal> terminal = terminalService.getTerminalById(id);
return ResponseEntity.ok(terminal.get());
} else {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Map.of("message", "Invalid Security PIN"));
}
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteTerminal(@PathVariable Long id) {
terminalService.deleteTerminal(id);
return ResponseEntity.noContent().build();
}
@GetMapping("/orders/{orderNumber}")
public ResponseEntity<?> getOrderForTerminal(
@PathVariable String orderNumber,
@RequestHeader("X-API-KEY") String apiKey) {
// 1. Verify API Key
Optional<Terminal> terminal = terminalRepository.findByApiKey(apiKey);
if (terminal.isEmpty()) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Map.of("message", "Invalid API Key"));
}
// 2. Fetch Order
Optional<Order> orderOpt = orderRepository.findByOrderNumber(orderNumber);
if (orderOpt.isPresent()) {
Order order = orderOpt.get();
// Check if order is expired/archived
if (order.isArchived()) {
return ResponseEntity.status(HttpStatus.GONE)
.body(Map.of("message", "This order has expired and cannot be processed."));
}
// Check if order is already fulfilled
if ("COMPLETED".equalsIgnoreCase(order.getStatus())) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body(Map.of("message", "This order has already been fulfilled and cannot be printed again."));
}
return ResponseEntity.ok(order);
} else {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of("message", "Order not found"));
}
}
}

View File

@@ -0,0 +1,140 @@
package com.rit.canteen.sales.controller;
import com.rit.canteen.sales.model.*;
import com.rit.canteen.sales.service.UserService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/auth")
public class UserController {
@Autowired
private UserService userService;
/**
* Check if a user exists by mobile number.
* POST /api/auth/check
*/
@PostMapping("/check")
public ResponseEntity<LoginResponse> checkUserExists(@Valid @RequestBody LoginRequest request) {
LoginResponse response = userService.checkUserExists(request.getMobileNumber());
return ResponseEntity.ok(response);
}
/**
* Register a new user with mobile number, name and PIN.
* POST /api/auth/register
*/
@PostMapping("/register")
public ResponseEntity<LoginResponse> registerUser(@Valid @RequestBody PinVerificationRequest request) {
LoginResponse response = userService.registerUser(request.getMobileNumber(), request.getName(), request.getPin());
if (response.isSuccess()) {
return ResponseEntity.ok(response);
} else {
return ResponseEntity.badRequest().body(response);
}
}
/**
* Verify PIN and login an existing user.
* POST /api/auth/login
*/
@PostMapping("/login")
public ResponseEntity<LoginResponse> login(@Valid @RequestBody PinVerificationRequest request) {
LoginResponse response = userService.verifyPinAndLogin(request.getMobileNumber(), request.getPin());
if (response.isSuccess()) {
return ResponseEntity.ok(response);
} else {
return ResponseEntity.badRequest().body(response);
}
}
/**
* Logout a user.
* POST /api/auth/logout
*/
@PostMapping("/logout")
public ResponseEntity<LoginResponse> logout(@Valid @RequestBody LoginRequest request) {
LoginResponse response = userService.logout(request.getMobileNumber());
if (response.isSuccess()) {
return ResponseEntity.ok(response);
} else {
return ResponseEntity.badRequest().body(response);
}
}
/**
* Change user PIN.
* POST /api/auth/change-pin
*/
@PostMapping("/change-pin")
public ResponseEntity<LoginResponse> changePin(@Valid @RequestBody ChangePinRequest request) {
LoginResponse response = userService.changePin(request.getMobileNumber(), request.getCurrentPin(), request.getNewPin());
if (response.isSuccess()) {
return ResponseEntity.ok(response);
} else {
return ResponseEntity.badRequest().body(response);
}
}
/**
* Get user details by mobile number.
* GET /api/auth/user/{mobileNumber}
*/
@GetMapping("/user/{mobileNumber}")
public ResponseEntity<LoginResponse.UserDto> getUser(@PathVariable String mobileNumber) {
LoginResponse.UserDto userDto = userService.getUserByMobile(mobileNumber);
if (userDto != null) {
return ResponseEntity.ok(userDto);
} else {
return ResponseEntity.notFound().build();
}
}
/**
* Get all registered users for administration dashboard.
* GET /api/auth/users
*/
/**
* Get all registered users for administration dashboard.
* GET /api/auth/users
*/
@GetMapping("/users")
public ResponseEntity<Page<LoginResponse.UserDto>> getAllUsers(
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int size) {
Page<LoginResponse.UserDto> users = userService.getAllUsers(PageRequest.of(page, size));
return ResponseEntity.ok(users);
}
/**
* Update user details as an administrator.
* PUT /api/auth/users/{id}
*/
@PutMapping("/users/{id}")
public ResponseEntity<LoginResponse.UserDto> updateUser(@PathVariable Long id, @Valid @RequestBody UserUpdateRequest request) {
LoginResponse.UserDto updated = userService.updateUser(id, request.getName(), request.getMobileNumber(), request.getPin());
if (updated != null) {
return ResponseEntity.ok(updated);
} else {
return ResponseEntity.notFound().build();
}
}
/**
* Delete a user from the system.
* DELETE /api/auth/users/{id}
*/
@DeleteMapping("/users/{id}")
public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
userService.deleteUser(id);
return ResponseEntity.noContent().build();
}
}

View File

@@ -0,0 +1,31 @@
package com.rit.canteen.sales.exception;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<Map<String, Object>> handleAllExceptions(Exception ex, WebRequest request) {
Map<String, Object> body = new HashMap<>();
body.put("timestamp", LocalDateTime.now());
body.put("message", ex.getMessage());
body.put("success", false);
// Include stack trace first few lines for easier debugging in browser
StackTraceElement[] stackTrace = ex.getStackTrace();
if (stackTrace.length > 0) {
body.put("details", stackTrace[0].toString());
}
return new ResponseEntity<>(body, HttpStatus.INTERNAL_SERVER_ERROR);
}
}

View File

@@ -0,0 +1,64 @@
package com.rit.canteen.sales.model;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import jakarta.validation.constraints.NotBlank;
@Entity
@Table(name = "base_items")
public class BaseItem {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank(message = "Item name is required")
private String name;
private String description;
private boolean active;
public BaseItem() {}
public BaseItem(String name, String description, boolean active) {
this.name = name;
this.description = description;
this.active = active;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
}

View File

@@ -0,0 +1,43 @@
package com.rit.canteen.sales.model;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
public class ChangePinRequest {
@NotBlank(message = "Mobile number is required")
private String mobileNumber;
@NotBlank(message = "Current PIN is required")
@Pattern(regexp = "^[0-9]{6}$", message = "PIN must be 6 digits")
private String currentPin;
@NotBlank(message = "New PIN is required")
@Pattern(regexp = "^[0-9]{6}$", message = "PIN must be 6 digits")
private String newPin;
// Getters and Setters
public String getMobileNumber() {
return mobileNumber;
}
public void setMobileNumber(String mobileNumber) {
this.mobileNumber = mobileNumber;
}
public String getCurrentPin() {
return currentPin;
}
public void setCurrentPin(String currentPin) {
this.currentPin = currentPin;
}
public String getNewPin() {
return newPin;
}
public void setNewPin(String newPin) {
this.newPin = newPin;
}
}

View File

@@ -0,0 +1,28 @@
package com.rit.canteen.sales.model;
public class DashboardStats {
private long totalSales;
private int activeOrders;
private int dailyCustomers;
private double revenueGrowth;
public DashboardStats(long totalSales, int activeOrders, int dailyCustomers, double revenueGrowth) {
this.totalSales = totalSales;
this.activeOrders = activeOrders;
this.dailyCustomers = dailyCustomers;
this.revenueGrowth = revenueGrowth;
}
// Getters and Setters
public long getTotalSales() { return totalSales; }
public void setTotalSales(long totalSales) { this.totalSales = totalSales; }
public int getActiveOrders() { return activeOrders; }
public void setActiveOrders(int activeOrders) { this.activeOrders = activeOrders; }
public int getDailyCustomers() { return dailyCustomers; }
public void setDailyCustomers(int dailyCustomers) { this.dailyCustomers = dailyCustomers; }
public double getRevenueGrowth() { return revenueGrowth; }
public void setRevenueGrowth(double revenueGrowth) { this.revenueGrowth = revenueGrowth; }
}

View File

@@ -0,0 +1,24 @@
package com.rit.canteen.sales.model;
import java.util.List;
import java.util.Map;
public class GeneralDashboardData {
private DashboardStats stats;
private List<Map<String, Object>> storeOverview;
private List<Map<String, Object>> hourlySales;
private List<String> insights;
public GeneralDashboardData(DashboardStats stats, List<Map<String, Object>> storeOverview, List<Map<String, Object>> hourlySales, List<String> insights) {
this.stats = stats;
this.storeOverview = storeOverview;
this.hourlySales = hourlySales;
this.insights = insights;
}
// Getters
public DashboardStats getStats() { return stats; }
public List<Map<String, Object>> getStoreOverview() { return storeOverview; }
public List<Map<String, Object>> getHourlySales() { return hourlySales; }
public List<String> getInsights() { return insights; }
}

View File

@@ -0,0 +1,20 @@
package com.rit.canteen.sales.model;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
public class LoginRequest {
@NotBlank(message = "Mobile number is required")
@Pattern(regexp = "^[0-9]{10}$", message = "Mobile number must be 10 digits")
private String mobileNumber;
public LoginRequest() {}
public LoginRequest(String mobileNumber) {
this.mobileNumber = mobileNumber;
}
public String getMobileNumber() { return mobileNumber; }
public void setMobileNumber(String mobileNumber) { this.mobileNumber = mobileNumber; }
}

View File

@@ -0,0 +1,68 @@
package com.rit.canteen.sales.model;
public class LoginResponse {
private boolean success;
private String message;
private boolean userExists;
private UserDto user;
public LoginResponse() {}
public LoginResponse(boolean success, String message) {
this.success = success;
this.message = message;
}
public LoginResponse(boolean success, String message, boolean userExists) {
this.success = success;
this.message = message;
this.userExists = userExists;
}
public LoginResponse(boolean success, String message, UserDto user) {
this.success = success;
this.message = message;
this.user = user;
}
public boolean isSuccess() { return success; }
public void setSuccess(boolean success) { this.success = success; }
public String getMessage() { return message; }
public void setMessage(String message) { this.message = message; }
public boolean isUserExists() { return userExists; }
public void setUserExists(boolean userExists) { this.userExists = userExists; }
public UserDto getUser() { return user; }
public void setUser(UserDto user) { this.user = user; }
public static class UserDto {
private Long id;
private String mobileNumber;
private String name;
private boolean isLoggedIn;
public UserDto() {}
public UserDto(Long id, String mobileNumber, String name, boolean isLoggedIn) {
this.id = id;
this.mobileNumber = mobileNumber;
this.name = name;
this.isLoggedIn = isLoggedIn;
}
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getMobileNumber() { return mobileNumber; }
public void setMobileNumber(String mobileNumber) { this.mobileNumber = mobileNumber; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public boolean isLoggedIn() { return isLoggedIn; }
public void setLoggedIn(boolean loggedIn) { isLoggedIn = loggedIn; }
}
}

View File

@@ -0,0 +1,102 @@
package com.rit.canteen.sales.model;
import jakarta.persistence.*;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
@Entity
@Table(name = "canteen_orders")
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true)
private String orderNumber; // Internal secure unique ID (e.g., ORD-X7Y9Z)
@Column(nullable = true)
private String displayOrderId; // Sequential human-readable ID (e.g., 001)
@Column(name = "user_id", nullable = false)
private Long userId;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id", insertable = false, updatable = false)
@com.fasterxml.jackson.annotation.JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
private User user;
@Column(nullable = false)
private BigDecimal totalAmount;
@Column(nullable = false)
private String status; // PENDING, COMPLETED, CANCELLED
@Column(nullable = false)
private String paymentMethod;
@Column(nullable = false)
private LocalDateTime createdAt;
@Column(name = "is_archived", nullable = false)
private boolean isArchived = false;
@OneToMany(mappedBy = "order", cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
private List<OrderItem> items = new ArrayList<>();
public Order() {
this.orderNumber = "ORD-" + UUID.randomUUID().toString().substring(0, 8).toUpperCase();
this.status = "PAID";
this.createdAt = LocalDateTime.now();
this.items = new ArrayList<>();
}
@PrePersist
protected void onCreate() {
if (createdAt == null) createdAt = LocalDateTime.now();
if (orderNumber == null) orderNumber = "ORD-" + UUID.randomUUID().toString().substring(0, 8).toUpperCase();
if (status == null) status = "PAID";
this.isArchived = false;
if (items != null) {
for (OrderItem item : items) {
item.setOrder(this);
}
}
}
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getOrderNumber() { return orderNumber; }
public void setOrderNumber(String orderNumber) { this.orderNumber = orderNumber; }
public String getDisplayOrderId() { return displayOrderId; }
public void setDisplayOrderId(String displayOrderId) { this.displayOrderId = displayOrderId; }
public Long getUserId() { return userId; }
public void setUserId(Long userId) { this.userId = userId; }
public User getUser() { return user; }
public void setUser(User user) { this.user = user; }
public BigDecimal getTotalAmount() { return totalAmount; }
public void setTotalAmount(BigDecimal totalAmount) { this.totalAmount = totalAmount; }
public String getStatus() { return status; }
public void setStatus(String status) { this.status = status; }
public String getPaymentMethod() { return paymentMethod; }
public void setPaymentMethod(String paymentMethod) { this.paymentMethod = paymentMethod; }
public LocalDateTime getCreatedAt() { return createdAt; }
public void setCreatedAt(LocalDateTime createdAt) { this.createdAt = createdAt; }
public boolean isArchived() { return isArchived; }
public void setArchived(boolean archived) { isArchived = archived; }
public List<OrderItem> getItems() { return items; }
public void setItems(List<OrderItem> items) { this.items = items; }
}

View File

@@ -0,0 +1,60 @@
package com.rit.canteen.sales.model;
import jakarta.persistence.*;
import java.math.BigDecimal;
import com.fasterxml.jackson.annotation.JsonIgnore;
@Entity
@Table(name = "canteen_order_items")
public class OrderItem {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "order_id", nullable = false)
@JsonIgnore
private Order order;
@Column(nullable = false)
private Long productId;
@Column(nullable = false)
private String productName;
@Column(nullable = false)
private BigDecimal price;
@Column(nullable = false)
private int quantity;
private Long stallId;
private String stallName;
public OrderItem() {}
public Order getOrder() { return order; }
public void setOrder(Order order) { this.order = order; }
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public Long getProductId() { return productId; }
public void setProductId(Long productId) { this.productId = productId; }
public String getProductName() { return productName; }
public void setProductName(String productName) { this.productName = productName; }
public BigDecimal getPrice() { return price; }
public void setPrice(BigDecimal price) { this.price = price; }
public int getQuantity() { return quantity; }
public void setQuantity(int quantity) { this.quantity = quantity; }
public Long getStallId() { return stallId; }
public void setStallId(Long stallId) { this.stallId = stallId; }
public String getStallName() { return stallName; }
public void setStallName(String stallName) { this.stallName = stallName; }
}

View File

@@ -0,0 +1,36 @@
package com.rit.canteen.sales.model;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size;
public class PinVerificationRequest {
@NotBlank(message = "Mobile number is required")
@Pattern(regexp = "^[0-9]{10}$", message = "Mobile number must be 10 digits")
private String mobileNumber;
private String name;
@NotBlank(message = "PIN is required")
@Size(min = 6, max = 6, message = "PIN must be exactly 6 digits")
@Pattern(regexp = "^[0-9]{6}$", message = "PIN must be exactly 6 digits")
private String pin;
public PinVerificationRequest() {}
public PinVerificationRequest(String mobileNumber, String name, String pin) {
this.mobileNumber = mobileNumber;
this.name = name;
this.pin = pin;
}
public String getMobileNumber() { return mobileNumber; }
public void setMobileNumber(String mobileNumber) { this.mobileNumber = mobileNumber; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getPin() { return pin; }
public void setPin(String pin) { this.pin = pin; }
}

View File

@@ -0,0 +1,144 @@
package com.rit.canteen.sales.model;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
@Entity
@Table(name = "products")
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String productId;
@NotBlank(message = "Product name is required")
private String name;
private String category;
private String description;
private BigDecimal basePrice;
private BigDecimal price;
private BigDecimal offerPrice;
private Double discountPercent;
private BigDecimal discountAmount;
private String counter;
private String tag;
private BigDecimal parcelCharges;
private String barcode;
private boolean attributesOptional;
// Additional Attributes
private boolean isVeg;
private boolean hasAllergy;
private boolean parcelNotAllowed;
private boolean sessionOptional;
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "product_id")
private List<ProductSession> sessions = new ArrayList<>();
@Column(columnDefinition = "TEXT")
private String imageData; // Base64 image data
private boolean active = true;
private Integer stock = 0;
@ManyToMany(mappedBy = "products", fetch = FetchType.EAGER)
@JsonIgnoreProperties({"products", "baseItems", "sessions", "imageData"})
private List<Stall> stalls = new ArrayList<>();
public Product() {}
// Getters and Setters
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public Integer getStock() { return stock; }
public void setStock(Integer stock) { this.stock = stock; }
public String getProductId() { return productId; }
public void setProductId(String productId) { this.productId = productId; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getCategory() { return category; }
public void setCategory(String category) { this.category = category; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
public BigDecimal getBasePrice() { return basePrice; }
public void setBasePrice(BigDecimal basePrice) { this.basePrice = basePrice; }
public BigDecimal getPrice() { return price; }
public void setPrice(BigDecimal price) { this.price = price; }
public BigDecimal getOfferPrice() { return offerPrice; }
public void setOfferPrice(BigDecimal offerPrice) { this.offerPrice = offerPrice; }
public Double getDiscountPercent() { return discountPercent; }
public void setDiscountPercent(Double discountPercent) { this.discountPercent = discountPercent; }
public BigDecimal getDiscountAmount() { return discountAmount; }
public void setDiscountAmount(BigDecimal discountAmount) { this.discountAmount = discountAmount; }
public String getCounter() { return counter; }
public void setCounter(String counter) { this.counter = counter; }
public String getTag() { return tag; }
public void setTag(String tag) { this.tag = tag; }
public BigDecimal getParcelCharges() { return parcelCharges; }
public void setParcelCharges(BigDecimal parcelCharges) { this.parcelCharges = parcelCharges; }
public String getBarcode() { return barcode; }
public void setBarcode(String barcode) { this.barcode = barcode; }
public boolean isAttributesOptional() { return attributesOptional; }
public void setAttributesOptional(boolean attributesOptional) { this.attributesOptional = attributesOptional; }
public boolean isVeg() { return isVeg; }
public void setVeg(boolean veg) { isVeg = veg; }
public boolean isHasAllergy() { return hasAllergy; }
public void setHasAllergy(boolean hasAllergy) { this.hasAllergy = hasAllergy; }
public boolean isParcelNotAllowed() { return parcelNotAllowed; }
public void setParcelNotAllowed(boolean parcelNotAllowed) { this.parcelNotAllowed = parcelNotAllowed; }
public boolean isSessionOptional() { return sessionOptional; }
public void setSessionOptional(boolean sessionOptional) { this.sessionOptional = sessionOptional; }
public List<ProductSession> getSessions() { return sessions; }
public void setSessions(List<ProductSession> sessions) { this.sessions = sessions; }
public String getImageData() { return imageData; }
public void setImageData(String imageData) { this.imageData = imageData; }
public boolean isActive() { return active; }
public void setActive(boolean active) { this.active = active; }
public List<Stall> getStalls() { return stalls; }
public void setStalls(List<Stall> stalls) { this.stalls = stalls; }
}

View File

@@ -0,0 +1,46 @@
package com.rit.canteen.sales.model;
import jakarta.persistence.*;
import java.time.LocalTime;
@Entity
@Table(name = "product_sessions")
public class ProductSession {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String dayOfWeek;
private boolean active;
private LocalTime startTime;
private LocalTime endTime;
public ProductSession() {}
public ProductSession(String dayOfWeek, boolean active, LocalTime startTime, LocalTime endTime) {
this.dayOfWeek = dayOfWeek;
this.active = active;
this.startTime = startTime;
this.endTime = endTime;
}
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getDayOfWeek() { return dayOfWeek; }
public void setDayOfWeek(String dayOfWeek) { this.dayOfWeek = dayOfWeek; }
public boolean isActive() { return active; }
public void setActive(boolean active) { this.active = active; }
public LocalTime getStartTime() { return startTime; }
public void setStartTime(LocalTime startTime) { this.startTime = startTime; }
public LocalTime getEndTime() { return endTime; }
public void setEndTime(LocalTime endTime) { this.endTime = endTime; }
}

View File

@@ -0,0 +1,80 @@
package com.rit.canteen.sales.model;
import jakarta.persistence.*;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
@Entity
@Table(name = "purchase_orders")
public class PurchaseOrder {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(unique = true)
private String purchaseId; // PO_1001, etc.
private LocalDateTime date;
@ManyToOne
@JoinColumn(name = "vendor_id")
private Vendor vendor;
@Column(precision = 19, scale = 2)
private BigDecimal amount;
@Column(precision = 19, scale = 2)
private BigDecimal discount = BigDecimal.ZERO;
@Column(precision = 19, scale = 2)
private BigDecimal paidTotal = BigDecimal.ZERO;
private String status; // OPEN, RECEIVED, BILLED, CLOSED
private String referenceId;
private String instruction;
@OneToMany(mappedBy = "purchaseOrder", cascade = CascadeType.ALL, orphanRemoval = true)
private List<PurchaseOrderItem> items;
public PurchaseOrder() {}
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getPurchaseId() { return purchaseId; }
public void setPurchaseId(String purchaseId) { this.purchaseId = purchaseId; }
public LocalDateTime getDate() { return date; }
public void setDate(LocalDateTime date) { this.date = date; }
public Vendor getVendor() { return vendor; }
public void setVendor(Vendor vendor) { this.vendor = vendor; }
public BigDecimal getAmount() { return amount; }
public void setAmount(BigDecimal amount) { this.amount = amount; }
public BigDecimal getDiscount() { return discount; }
public void setDiscount(BigDecimal discount) { this.discount = discount; }
public BigDecimal getPaidTotal() { return paidTotal; }
public void setPaidTotal(BigDecimal paidTotal) { this.paidTotal = paidTotal; }
public String getStatus() { return status; }
public void setStatus(String status) { this.status = status; }
public String getReferenceId() { return referenceId; }
public void setReferenceId(String referenceId) { this.referenceId = referenceId; }
public String getInstruction() { return instruction; }
public void setInstruction(String instruction) { this.instruction = instruction; }
public List<PurchaseOrderItem> getItems() { return items; }
public void setItems(List<PurchaseOrderItem> items) { this.items = items; }
public BigDecimal getPayables() {
return amount != null ? amount.subtract(paidTotal) : BigDecimal.ZERO;
}
}

View File

@@ -0,0 +1,51 @@
package com.rit.canteen.sales.model;
import jakarta.persistence.*;
import java.math.BigDecimal;
import java.time.LocalDateTime;
@Entity
@Table(name = "purchase_order_history")
public class PurchaseOrderHistory {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
@JoinColumn(name = "purchase_order_id", nullable = false)
private PurchaseOrder purchaseOrder;
private BigDecimal oldAmount;
private BigDecimal newAmount;
private LocalDateTime changeDate;
private String reason;
public PurchaseOrderHistory() {}
public PurchaseOrderHistory(PurchaseOrder purchaseOrder, BigDecimal oldAmount, BigDecimal newAmount, String reason) {
this.purchaseOrder = purchaseOrder;
this.oldAmount = oldAmount;
this.newAmount = newAmount;
this.changeDate = LocalDateTime.now();
this.reason = reason;
}
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public PurchaseOrder getPurchaseOrder() { return purchaseOrder; }
public void setPurchaseOrder(PurchaseOrder purchaseOrder) { this.purchaseOrder = purchaseOrder; }
public BigDecimal getOldAmount() { return oldAmount; }
public void setOldAmount(BigDecimal oldAmount) { this.oldAmount = oldAmount; }
public BigDecimal getNewAmount() { return newAmount; }
public void setNewAmount(BigDecimal newAmount) { this.newAmount = newAmount; }
public LocalDateTime getChangeDate() { return changeDate; }
public void setChangeDate(LocalDateTime changeDate) { this.changeDate = changeDate; }
public String getReason() { return reason; }
public void setReason(String reason) { this.reason = reason; }
}

View File

@@ -0,0 +1,48 @@
package com.rit.canteen.sales.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.*;
import java.math.BigDecimal;
@Entity
@Table(name = "purchase_order_items")
public class PurchaseOrderItem {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
@JoinColumn(name = "purchase_order_id", nullable = false)
@JsonIgnore
private PurchaseOrder purchaseOrder;
private String productName;
private Double quantity;
@Column(precision = 19, scale = 2)
private BigDecimal rate;
@Column(precision = 19, scale = 2)
private BigDecimal total;
public PurchaseOrderItem() {}
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public PurchaseOrder getPurchaseOrder() { return purchaseOrder; }
public void setPurchaseOrder(PurchaseOrder purchaseOrder) { this.purchaseOrder = purchaseOrder; }
public String getProductName() { return productName; }
public void setProductName(String productName) { this.productName = productName; }
public Double getQuantity() { return quantity; }
public void setQuantity(Double quantity) { this.quantity = quantity; }
public BigDecimal getRate() { return rate; }
public void setRate(BigDecimal rate) { this.rate = rate; }
public BigDecimal getTotal() { return total; }
public void setTotal(BigDecimal total) { this.total = total; }
}

View File

@@ -0,0 +1,91 @@
package com.rit.canteen.sales.model;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.util.ArrayList;
import java.util.List;
@Entity
@Table(name = "stalls")
public class Stall {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank(message = "Stall title is required")
private String name;
private String description;
@Column(columnDefinition = "TEXT")
private String imageData; // Base64 image data
private boolean active = true;
private boolean temporarilyClosed = false;
private boolean sessionOptional = false;
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "stall_id")
private List<StallSession> sessions = new ArrayList<>();
@ManyToMany
@JoinTable(
name = "stall_products",
joinColumns = @JoinColumn(name = "stall_id"),
inverseJoinColumns = @JoinColumn(name = "product_id")
)
@JsonIgnoreProperties({"stalls", "sessions"})
private List<Product> products = new ArrayList<>();
@ManyToMany
@JoinTable(
name = "stall_base_items",
joinColumns = @JoinColumn(name = "stall_id"),
inverseJoinColumns = @JoinColumn(name = "base_item_id")
)
@JsonIgnoreProperties({"imageData", "description"})
private List<BaseItem> baseItems = new ArrayList<>();
public Stall() {}
public Stall(String name, String description, String imageData) {
this.name = name;
this.description = description;
this.imageData = imageData;
}
// Getters and Setters
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
public String getImageData() { return imageData; }
public void setImageData(String imageData) { this.imageData = imageData; }
public boolean isActive() { return active; }
public void setActive(boolean active) { this.active = active; }
public List<Product> getProducts() { return products; }
public void setProducts(List<Product> products) { this.products = products; }
public List<BaseItem> getBaseItems() { return baseItems; }
public void setBaseItems(List<BaseItem> baseItems) { this.baseItems = baseItems; }
public boolean isTemporarilyClosed() { return temporarilyClosed; }
public void setTemporarilyClosed(boolean temporarilyClosed) { this.temporarilyClosed = temporarilyClosed; }
public boolean isSessionOptional() { return sessionOptional; }
public void setSessionOptional(boolean sessionOptional) { this.sessionOptional = sessionOptional; }
public List<StallSession> getSessions() { return sessions; }
public void setSessions(List<StallSession> sessions) { this.sessions = sessions; }
}

View File

@@ -0,0 +1,46 @@
package com.rit.canteen.sales.model;
import jakarta.persistence.*;
import java.time.LocalTime;
@Entity
@Table(name = "stall_sessions")
public class StallSession {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String dayOfWeek;
private boolean active;
private LocalTime startTime;
private LocalTime endTime;
public StallSession() {}
public StallSession(String dayOfWeek, boolean active, LocalTime startTime, LocalTime endTime) {
this.dayOfWeek = dayOfWeek;
this.active = active;
this.startTime = startTime;
this.endTime = endTime;
}
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getDayOfWeek() { return dayOfWeek; }
public void setDayOfWeek(String dayOfWeek) { this.dayOfWeek = dayOfWeek; }
public boolean isActive() { return active; }
public void setActive(boolean active) { this.active = active; }
public LocalTime getStartTime() { return startTime; }
public void setStartTime(LocalTime startTime) { this.startTime = startTime; }
public LocalTime getEndTime() { return endTime; }
public void setEndTime(LocalTime endTime) { this.endTime = endTime; }
}

View File

@@ -0,0 +1,55 @@
package com.rit.canteen.sales.model;
import jakarta.persistence.*;
import java.util.List;
@Entity
@Table(name = "system_users")
public class SystemUser {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String name;
@Column(unique = true, nullable = false)
private String email;
@Column(nullable = false)
private String password;
@Column(nullable = false)
private String role; // MASTER, MANAGER
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name = "system_user_permissions", joinColumns = @JoinColumn(name = "user_id"))
@Column(name = "permission")
private List<String> permissions;
@Column(nullable = false)
private boolean viewOnly = false;
public SystemUser() {}
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
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 getRole() { return role; }
public void setRole(String role) { this.role = role; }
public List<String> getPermissions() { return permissions; }
public void setPermissions(List<String> permissions) { this.permissions = permissions; }
public boolean isViewOnly() { return viewOnly; }
public void setViewOnly(boolean viewOnly) { this.viewOnly = viewOnly; }
}

View File

@@ -0,0 +1,50 @@
package com.rit.canteen.sales.model;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank;
@Entity
@Table(name = "terminals")
public class Terminal {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank(message = "Terminal name is required")
private String name;
@NotBlank(message = "Location is required")
private String location;
@NotBlank(message = "Security PIN is required")
private String pin;
@Column(unique = true)
private String apiKey;
public Terminal() {}
public Terminal(String name, String location, String pin, String apiKey) {
this.name = name;
this.location = location;
this.pin = pin;
this.apiKey = apiKey;
}
// Getters and Setters
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getLocation() { return location; }
public void setLocation(String location) { this.location = location; }
public String getPin() { return pin; }
public void setPin(String pin) { this.pin = pin; }
public String getApiKey() { return apiKey; }
public void setApiKey(String apiKey) { this.apiKey = apiKey; }
}

View File

@@ -0,0 +1,35 @@
package com.rit.canteen.sales.model;
public class TerminalDTO {
private Long id;
private String name;
private String location;
private String apiKey;
private String pin;
public TerminalDTO() {}
public TerminalDTO(Long id, String name, String location, String apiKey, String pin) {
this.id = id;
this.name = name;
this.location = location;
this.apiKey = apiKey;
this.pin = pin;
}
// Getters and Setters
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getLocation() { return location; }
public void setLocation(String location) { this.location = location; }
public String getApiKey() { return apiKey; }
public void setApiKey(String apiKey) { this.apiKey = apiKey; }
public String getPin() { return pin; }
public void setPin(String pin) { this.pin = pin; }
}

View File

@@ -0,0 +1,76 @@
package com.rit.canteen.sales.model;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
import java.time.LocalDateTime;
@Entity
@Table(name = "app_users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank(message = "Mobile number is required")
@Pattern(regexp = "^[0-9]{10}$", message = "Mobile number must be 10 digits")
@Column(unique = true, nullable = false, length = 10)
private String mobileNumber;
@Column(nullable = true)
private String name;
@Column(nullable = false)
@com.fasterxml.jackson.annotation.JsonIgnore
private String pinHash;
@Column(nullable = false)
private boolean isLoggedIn = false;
@Column(nullable = false)
private LocalDateTime createdAt;
@Column(nullable = false)
private LocalDateTime updatedAt;
@Column(nullable = true)
private LocalDateTime lastLoginAt;
public User() {}
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getMobileNumber() { return mobileNumber; }
public void setMobileNumber(String mobileNumber) { this.mobileNumber = mobileNumber; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getPinHash() { return pinHash; }
public void setPinHash(String pinHash) { this.pinHash = pinHash; }
public boolean isLoggedIn() { return isLoggedIn; }
public void setLoggedIn(boolean loggedIn) { isLoggedIn = loggedIn; }
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; }
public LocalDateTime getLastLoginAt() { return lastLoginAt; }
public void setLastLoginAt(LocalDateTime lastLoginAt) { this.lastLoginAt = lastLoginAt; }
@PrePersist
protected void onCreate() {
createdAt = LocalDateTime.now();
updatedAt = LocalDateTime.now();
}
@PreUpdate
protected void onUpdate() {
updatedAt = LocalDateTime.now();
}
}

View File

@@ -0,0 +1,41 @@
package com.rit.canteen.sales.model;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size;
/**
* DTO for administrative user updates.
*/
public class UserUpdateRequest {
private String name;
@Pattern(regexp = "^[0-9]{10}$", message = "Mobile number must be 10 digits")
private String mobileNumber;
@Pattern(regexp = "^[0-9]{6}$|", message = "PIN must be exactly 6 digits if provided")
private String pin;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMobileNumber() {
return mobileNumber;
}
public void setMobileNumber(String mobileNumber) {
this.mobileNumber = mobileNumber;
}
public String getPin() {
return pin;
}
public void setPin(String pin) {
this.pin = pin;
}
}

View File

@@ -0,0 +1,50 @@
package com.rit.canteen.sales.model;
import jakarta.persistence.*;
import java.math.BigDecimal;
@Entity
@Table(name = "vendors")
public class Vendor {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String name;
private String companyName;
private String contactNumber;
private String email;
@Column(precision = 19, scale = 2, nullable = false)
private BigDecimal totalAmount = BigDecimal.ZERO;
@Column(nullable = false)
private Integer totalOrders = 0;
public Vendor() {}
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getCompanyName() { return companyName; }
public void setCompanyName(String companyName) { this.companyName = companyName; }
public String getContactNumber() { return contactNumber; }
public void setContactNumber(String contactNumber) { this.contactNumber = contactNumber; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
public BigDecimal getTotalAmount() { return totalAmount; }
public void setTotalAmount(BigDecimal totalAmount) { this.totalAmount = totalAmount; }
public Integer getTotalOrders() { return totalOrders; }
public void setTotalOrders(Integer totalOrders) { this.totalOrders = totalOrders; }
}

View File

@@ -0,0 +1,9 @@
package com.rit.canteen.sales.repository;
import com.rit.canteen.sales.model.BaseItem;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface BaseItemRepository extends JpaRepository<BaseItem, Long> {
}

View File

@@ -0,0 +1,43 @@
package com.rit.canteen.sales.repository;
import com.rit.canteen.sales.model.Order;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
public interface OrderRepository extends JpaRepository<Order, Long>, JpaSpecificationExecutor<Order> {
List<Order> findByUserIdOrderByCreatedAtDesc(Long userId);
long countByCreatedAtGreaterThanEqual(LocalDateTime startOfDay);
List<Order> findByIsArchivedFalseAndCreatedAtBefore(LocalDateTime timestamp);
Optional<Order> findByOrderNumber(String orderNumber);
@Query("SELECT SUM(o.totalAmount) FROM Order o")
BigDecimal getTotalRevenue();
@Query("SELECT COUNT(DISTINCT o.userId) FROM Order o WHERE o.createdAt >= :startOfDay")
long countUniqueUsersToday(@Param("startOfDay") LocalDateTime startOfDay);
@Query("SELECT SUM(o.totalAmount) FROM Order o WHERE o.createdAt >= :start AND o.createdAt <= :end")
BigDecimal getRevenuePerPeriod(@Param("start") LocalDateTime start, @Param("end") LocalDateTime end);
List<Order> findTop5ByOrderByCreatedAtDesc();
@Query("SELECT i.stallName, SUM(i.price * i.quantity), COUNT(DISTINCT o.id) " +
"FROM Order o JOIN o.items i " +
"WHERE o.createdAt >= :start AND o.createdAt <= :end " +
"GROUP BY i.stallName")
List<Object[]> getStoreOverview(@Param("start") LocalDateTime start, @Param("end") LocalDateTime end);
@Query("SELECT HOUR(o.createdAt), SUM(o.totalAmount) " +
"FROM Order o " +
"WHERE o.createdAt >= :start AND o.createdAt <= :end " +
"GROUP BY HOUR(o.createdAt) " +
"ORDER BY HOUR(o.createdAt)")
List<Object[]> getHourlySales(@Param("start") LocalDateTime start, @Param("end") LocalDateTime end);
}

View File

@@ -0,0 +1,16 @@
package com.rit.canteen.sales.repository;
import com.rit.canteen.sales.model.Product;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
@Query("SELECT DISTINCT p FROM Product p LEFT JOIN FETCH p.stalls")
List<Product> findAllWithStalls();
List<Product> findByCategory(String category);
}

View File

@@ -0,0 +1,9 @@
package com.rit.canteen.sales.repository;
import com.rit.canteen.sales.model.PurchaseOrderHistory;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface PurchaseOrderHistoryRepository extends JpaRepository<PurchaseOrderHistory, Long> {
List<PurchaseOrderHistory> findByPurchaseOrderIdOrderByChangeDateDesc(Long purchaseOrderId);
}

View File

@@ -0,0 +1,25 @@
package com.rit.canteen.sales.repository;
import com.rit.canteen.sales.model.PurchaseOrder;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
@Repository
public interface PurchaseOrderRepository extends JpaRepository<PurchaseOrder, Long> {
Optional<PurchaseOrder> findByPurchaseId(String purchaseId);
@org.springframework.data.jpa.repository.Query("SELECT SUM(p.amount) FROM PurchaseOrder p")
java.math.BigDecimal getTotalPurchaseAmount();
@org.springframework.data.jpa.repository.Query("SELECT SUM(COALESCE(p.amount, 0) - COALESCE(p.paidTotal, 0)) FROM PurchaseOrder p")
java.math.BigDecimal getTotalBalanceAmount();
@org.springframework.data.jpa.repository.Query("SELECT COUNT(p) FROM PurchaseOrder p WHERE p.status != 'PAID'")
long countUnpaidBills();
@org.springframework.data.jpa.repository.Query("SELECT p.date, SUM(p.amount) FROM PurchaseOrder p GROUP BY p.date ORDER BY p.date ASC")
List<Object[]> getPurchaseTrend();
}

View File

@@ -0,0 +1,12 @@
package com.rit.canteen.sales.repository;
import com.rit.canteen.sales.model.Stall;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface StallRepository extends JpaRepository<Stall, Long> {
List<Stall> findByActiveTrue();
}

View File

@@ -0,0 +1,11 @@
package com.rit.canteen.sales.repository;
import com.rit.canteen.sales.model.SystemUser;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
import java.util.List;
public interface SystemUserRepository extends JpaRepository<SystemUser, Long> {
Optional<SystemUser> findByEmail(String email);
List<SystemUser> findByRole(String role);
}

View File

@@ -0,0 +1,12 @@
package com.rit.canteen.sales.repository;
import com.rit.canteen.sales.model.Terminal;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface TerminalRepository extends JpaRepository<Terminal, Long> {
Optional<Terminal> findByApiKey(String apiKey);
}

View File

@@ -0,0 +1,13 @@
package com.rit.canteen.sales.repository;
import com.rit.canteen.sales.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> findByMobileNumber(String mobileNumber);
boolean existsByMobileNumber(String mobileNumber);
}

View File

@@ -0,0 +1,9 @@
package com.rit.canteen.sales.repository;
import com.rit.canteen.sales.model.Vendor;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface VendorRepository extends JpaRepository<Vendor, Long> {
}

View File

@@ -0,0 +1,108 @@
package com.rit.canteen.sales.service;
import com.rit.canteen.sales.model.DashboardStats;
import com.rit.canteen.sales.model.GeneralDashboardData;
import com.rit.canteen.sales.model.Order;
import com.rit.canteen.sales.repository.OrderRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
@Service
public class DashboardService {
@Autowired
private OrderRepository orderRepository;
public GeneralDashboardData getGeneralDashboardData() {
LocalDateTime startOfToday = LocalDate.now().atStartOfDay();
LocalDateTime endOfToday = LocalDate.now().atTime(LocalTime.MAX);
DashboardStats stats = getDashboardStats();
// 1. Store Overview
List<Object[]> storeData = orderRepository.getStoreOverview(startOfToday, endOfToday);
List<Map<String, Object>> storeOverview = new ArrayList<>();
for (Object[] row : storeData) {
Map<String, Object> store = new HashMap<>();
store.put("name", row[0] != null ? row[0] : "Unknown Stall");
store.put("sale", row[1] != null ? row[1] : 0);
store.put("orders", row[2] != null ? row[2] : 0);
store.put("taxes", 0); // Placeholder
store.put("purchase", 0); // Placeholder
storeOverview.add(store);
}
// 2. Hourly Sales
List<Object[]> hourlyData = orderRepository.getHourlySales(startOfToday, endOfToday);
List<Map<String, Object>> hourlySales = new ArrayList<>();
// Initialize 24 hours
for (int i = 0; i < 24; i += 2) {
Map<String, Object> hourMap = new HashMap<>();
String label = i == 0 ? "12am" : (i > 12 ? (i-12) + "pm" : i + (i == 12 ? "pm" : "am"));
hourMap.put("time", label);
hourMap.put("value", 0);
for (Object[] row : hourlyData) {
int h = (int) row[0];
if (h >= i && h < i + 2) {
BigDecimal val = (BigDecimal) row[1];
hourMap.put("value", ((Number) hourMap.get("value")).doubleValue() + val.doubleValue());
}
}
hourlySales.add(hourMap);
}
// 3. Dynamic Insights
List<String> insights = new ArrayList<>();
if (stats.getActiveOrders() > 0) {
insights.add(stats.getActiveOrders() + " orders today! Clearly the crowd's found their happy place 💃🕺");
BigDecimal avg = stats.getTotalSales() > 0 ? BigDecimal.valueOf(stats.getTotalSales()).divide(BigDecimal.valueOf(stats.getActiveOrders()), 2, RoundingMode.HALF_UP) : BigDecimal.ZERO;
insights.add("" + avg + " average order value! Proof that happy bellies don't need heavy bills 🤤🔥");
} else {
insights.add("Waiting for the first orders of the day to roll in... ☕");
}
return new GeneralDashboardData(stats, storeOverview, hourlySales, insights);
}
public DashboardStats getDashboardStats() {
LocalDateTime startOfToday = LocalDate.now().atStartOfDay();
LocalDateTime endOfToday = LocalDate.now().atTime(LocalTime.MAX);
LocalDateTime startOfYesterday = LocalDate.now().minusDays(1).atStartOfDay();
LocalDateTime endOfYesterday = LocalDate.now().minusDays(1).atTime(LocalTime.MAX);
BigDecimal totalRevenueRaw = orderRepository.getTotalRevenue();
long totalSales = totalRevenueRaw != null ? totalRevenueRaw.longValue() : 0;
int activeOrders = (int) orderRepository.countByCreatedAtGreaterThanEqual(startOfToday);
int dailyCustomers = (int) orderRepository.countUniqueUsersToday(startOfToday);
BigDecimal todayRevenue = orderRepository.getRevenuePerPeriod(startOfToday, endOfToday);
BigDecimal yesterdayRevenue = orderRepository.getRevenuePerPeriod(startOfYesterday, endOfYesterday);
double growth = 0;
if (yesterdayRevenue != null && yesterdayRevenue.compareTo(BigDecimal.ZERO) > 0) {
BigDecimal today = todayRevenue != null ? todayRevenue : BigDecimal.ZERO;
growth = today.subtract(yesterdayRevenue)
.divide(yesterdayRevenue, 4, RoundingMode.HALF_UP)
.multiply(new BigDecimal(100))
.doubleValue();
} else if (todayRevenue != null && todayRevenue.compareTo(BigDecimal.ZERO) > 0) {
growth = 100.0;
}
return new DashboardStats(totalSales, activeOrders, dailyCustomers, growth);
}
public List<Order> getRecentOrders() {
return orderRepository.findTop5ByOrderByCreatedAtDesc();
}
}

View File

@@ -0,0 +1,119 @@
package com.rit.canteen.sales.service;
import com.rit.canteen.sales.model.BaseItem;
import com.rit.canteen.sales.model.Product;
import com.rit.canteen.sales.repository.BaseItemRepository;
import com.rit.canteen.sales.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;
import java.math.BigDecimal;
@Component
public class DatabaseSeeder implements CommandLineRunner {
@Autowired
private BaseItemRepository baseItemRepository;
@Autowired
private ProductRepository productRepository;
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public void run(String... args) throws Exception {
repairStallsSchema();
repairLobColumns();
if (baseItemRepository.count() == 0) {
seedCategories();
}
if (productRepository.count() == 0) {
seedProducts();
}
}
private void repairStallsSchema() {
System.out.println("Checking schema consistency for 'stalls' table...");
try {
jdbcTemplate.execute("ALTER TABLE stalls ADD COLUMN IF NOT EXISTS session_optional BOOLEAN DEFAULT FALSE");
jdbcTemplate.execute("ALTER TABLE stalls ADD COLUMN IF NOT EXISTS temporarily_closed BOOLEAN DEFAULT FALSE");
System.out.println("Schema consistency confirmed.");
} catch (Exception e) {
System.err.println("Schema repair notice (this may happen if columns already exist): " + e.getMessage());
}
}
private void repairLobColumns() {
System.out.println("Checking image columns for LOB-to-TEXT migration...");
try {
// Repair products table
if (!isColumnTextType("products", "image_data")) {
System.out.println("Migrating products.image_data to TEXT...");
try { jdbcTemplate.execute("ALTER TABLE products DROP COLUMN image_data"); } catch (Exception e) {}
jdbcTemplate.execute("ALTER TABLE products ADD COLUMN image_data TEXT");
}
// Repair stalls table
if (!isColumnTextType("stalls", "image_data")) {
System.out.println("Migrating stalls.image_data to TEXT...");
try { jdbcTemplate.execute("ALTER TABLE stalls DROP COLUMN image_data"); } catch (Exception e) {}
jdbcTemplate.execute("ALTER TABLE stalls ADD COLUMN image_data TEXT");
}
System.out.println("Image schema check complete.");
} catch (Exception e) {
System.err.println("Database migration notice: " + e.getMessage());
}
}
private boolean isColumnTextType(String tableName, String columnName) {
try {
String query = "SELECT data_type FROM information_schema.columns WHERE table_name = ? AND column_name = ?";
String dataType = jdbcTemplate.queryForObject(query, String.class, tableName, columnName);
return "text".equalsIgnoreCase(dataType);
} catch (Exception e) {
return false; // Column might not exist or other error
}
}
private void seedCategories() {
BaseItem breakfast = new BaseItem("Breakfast", "Morning favorites", true);
BaseItem lunch = new BaseItem("Lunch", "Hearty meals", true);
BaseItem snacks = new BaseItem("Snacks", "Quick bites", true);
BaseItem beverages = new BaseItem("Beverages", "Refreshing drinks", true);
BaseItem desserts = new BaseItem("Desserts", "Sweet treats", true);
baseItemRepository.saveAll(List.of(breakfast, lunch, snacks, beverages, desserts));
System.out.println("Categories seeded!");
}
private void seedProducts() {
Product dosa = createProduct("Masala Dosa", "Breakfast", "Crispy dosa with potato filling", 60.0, 50, true);
Product poha = createProduct("Poha", "Breakfast", "Flattened rice with onions and spices", 30.0, 40, true);
Product thali = createProduct("Veg Thali", "Lunch", "Full meal with roti, sabzi, dal and rice", 120.0, 30, true);
Product biryani = createProduct("Chicken Biryani", "Lunch", "Aromatic rice with spiced chicken", 150.0, 20, false);
Product samosa = createProduct("Samosa", "Snacks", "Deep fried pastry with potato filling", 15.0, 100, true);
Product tea = createProduct("Masala Tea", "Beverages", "Traditional Indian spiced tea", 10.0, 200, true);
Product iceCream = createProduct("Vanilla Ice Cream", "Desserts", "Classic vanilla flavor", 30.0, 0, true); // Out of stock
productRepository.saveAll(List.of(dosa, poha, thali, biryani, samosa, tea, iceCream));
System.out.println("Products seeded!");
}
private Product createProduct(String name, String category, String desc, Double price, Integer stock, boolean isVeg) {
Product p = new Product();
p.setName(name);
p.setCategory(category);
p.setDescription(desc);
p.setPrice(BigDecimal.valueOf(price));
p.setBasePrice(BigDecimal.valueOf(price * 0.8));
p.setStock(stock);
p.setVeg(isVeg);
p.setActive(true);
return p;
}
}

View File

@@ -0,0 +1,57 @@
package com.rit.canteen.sales.service;
import com.rit.canteen.sales.model.Order;
import com.rit.canteen.sales.repository.OrderRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
@Service
public class OrderArchiverService {
@Autowired
private OrderRepository orderRepository;
/**
* Automatically archives orders from previous days at midnight (12:00 AM).
* Cron: 0 0 0 * * * (Second Minute Hour Day Month DayOfWeek)
*/
@Scheduled(cron = "0 0 0 * * *")
@Transactional
public void archivePreviousDayOrders() {
LocalDateTime startOfToday = LocalDate.now().atStartOfDay();
System.out.println("Starting automated archival process for orders before: " + startOfToday);
List<Order> ordersToArchive = orderRepository.findByIsArchivedFalseAndCreatedAtBefore(startOfToday);
if (!ordersToArchive.isEmpty()) {
for (Order order : ordersToArchive) {
order.setArchived(true);
}
orderRepository.saveAll(ordersToArchive);
System.out.println("Successfully archived " + ordersToArchive.size() + " orders.");
} else {
System.out.println("No orders found to archive for today.");
}
}
/**
* Manual trigger for archival logic (useful for testing or initial setup).
*/
@Transactional
public int archiveNow() {
LocalDateTime startOfToday = LocalDate.now().atStartOfDay();
List<Order> ordersToArchive = orderRepository.findByIsArchivedFalseAndCreatedAtBefore(startOfToday);
for (Order order : ordersToArchive) {
order.setArchived(true);
}
orderRepository.saveAll(ordersToArchive);
return ordersToArchive.size();
}
}

View File

@@ -0,0 +1,123 @@
package com.rit.canteen.sales.service;
import com.rit.canteen.sales.model.PurchaseOrder;
import com.rit.canteen.sales.model.Vendor;
import com.rit.canteen.sales.repository.PurchaseOrderRepository;
import com.rit.canteen.sales.repository.VendorRepository;
import com.rit.canteen.sales.repository.PurchaseOrderHistoryRepository;
import com.rit.canteen.sales.model.PurchaseOrderHistory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@Service
@Transactional
public class PurchaseService {
@Autowired
private PurchaseOrderRepository purchaseOrderRepository;
@Autowired
private VendorRepository vendorRepository;
@Autowired
private PurchaseOrderHistoryRepository historyRepository;
public List<PurchaseOrder> getAllOrders() {
return purchaseOrderRepository.findAll();
}
public List<Vendor> getAllVendors() {
return vendorRepository.findAll();
}
public PurchaseOrder createOrder(PurchaseOrder order) {
if (order == null) throw new IllegalArgumentException("Order cannot be null");
// Check for history if this is an update
if (order.getId() != null) {
purchaseOrderRepository.findById(order.getId()).ifPresent(existing -> {
BigDecimal oldAmount = existing.getAmount() != null ? existing.getAmount() : BigDecimal.ZERO;
BigDecimal newAmount = order.getAmount() != null ? order.getAmount() : BigDecimal.ZERO;
if (oldAmount.compareTo(newAmount) != 0) {
historyRepository.save(new PurchaseOrderHistory(existing, oldAmount, newAmount, "Amount updated during processing"));
}
});
}
// Link items to the parent order
if (order.getItems() != null) {
order.getItems().forEach(item -> item.setPurchaseOrder(order));
}
PurchaseOrder savedOrder = purchaseOrderRepository.save(order);
// Update vendor statistics (only for NEW orders to avoid double counting,
// OR we should adjust the difference for updates - but user mostly wants new orders tracked)
if (order.getId() == null && savedOrder.getVendor() != null && savedOrder.getVendor().getId() != null) {
vendorRepository.findById(savedOrder.getVendor().getId()).ifPresent(vendor -> {
vendor.setTotalOrders((vendor.getTotalOrders() != null ? vendor.getTotalOrders() : 0) + 1);
BigDecimal currentAmount = vendor.getTotalAmount() != null ? vendor.getTotalAmount() : BigDecimal.ZERO;
BigDecimal orderAmount = savedOrder.getAmount() != null ? savedOrder.getAmount() : BigDecimal.ZERO;
vendor.setTotalAmount(currentAmount.add(orderAmount));
vendorRepository.save(vendor);
});
}
return savedOrder;
}
public List<PurchaseOrderHistory> getOrderHistory(Long orderId) {
return historyRepository.findByPurchaseOrderIdOrderByChangeDateDesc(orderId);
}
public Vendor createVendor(Vendor vendor) {
if (vendor == null) throw new IllegalArgumentException("Vendor cannot be null");
return vendorRepository.save(vendor);
}
public Optional<PurchaseOrder> getOrderById(Long id) {
if (id == null) return Optional.empty();
return purchaseOrderRepository.findById(id);
}
public void deleteVendor(Long id) {
if (id != null) vendorRepository.deleteById(id);
}
public void deleteOrder(Long id) {
if (id != null) purchaseOrderRepository.deleteById(id);
}
public Map<String, Object> getPurchaseSummary() {
Map<String, Object> summary = new HashMap<>();
BigDecimal total = purchaseOrderRepository.getTotalPurchaseAmount();
BigDecimal balance = purchaseOrderRepository.getTotalBalanceAmount();
long unpaidCount = purchaseOrderRepository.countUnpaidBills();
summary.put("totalAmount", total != null ? total : BigDecimal.ZERO);
summary.put("balanceAmount", balance != null ? balance : BigDecimal.ZERO);
summary.put("paidAmount", (total != null ? total : BigDecimal.ZERO).subtract(balance != null ? balance : BigDecimal.ZERO));
summary.put("unpaidCount", unpaidCount);
List<Object[]> trendData = purchaseOrderRepository.getPurchaseTrend();
List<Map<String, Object>> trend = new ArrayList<>();
for (Object[] row : trendData) {
Map<String, Object> point = new HashMap<>();
point.put("date", row[0].toString());
point.put("amount", row[1]);
trend.add(point);
}
summary.put("trend", trend);
return summary;
}
}

View File

@@ -0,0 +1,99 @@
package com.rit.canteen.sales.service;
import com.rit.canteen.sales.model.SystemUser;
import com.rit.canteen.sales.repository.SystemUserRepository;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class SystemUserService {
@Autowired
private SystemUserRepository repository;
@Autowired
private BCryptPasswordEncoder passwordEncoder;
@PostConstruct
public void init() {
// Handle migration from old credentials if they exist
repository.findByEmail("admin@ritcanteen.com").ifPresent(oldUser -> {
boolean hasNewAdmin = repository.findByEmail("admin").isPresent();
if (hasNewAdmin) {
repository.delete(oldUser);
System.out.println(">>> REMOVED OBSOLETE MASTER USER: admin@ritcanteen.com");
} else {
oldUser.setEmail("admin");
oldUser.setPassword(passwordEncoder.encode("admin"));
repository.save(oldUser);
System.out.println(">>> MIGRATED MASTER USER: admin / admin");
}
});
// Ensure 'admin' user exists and has the correct password
Optional<SystemUser> adminUser = repository.findByEmail("admin");
if (adminUser.isPresent()) {
SystemUser admin = adminUser.get();
admin.setPassword(passwordEncoder.encode("admin"));
admin.setRole("MASTER");
repository.save(admin);
System.out.println(">>> UPDATED MASTER USER PASSWORD: admin / admin");
} else {
SystemUser master = new SystemUser();
master.setName("Admin Master");
master.setEmail("admin");
master.setPassword(passwordEncoder.encode("admin"));
master.setRole("MASTER");
master.setPermissions(List.of("dashboard", "sale", "customers", "purchases", "inventory", "expense", "reports", "stores", "table", "wallet", "promotions", "feedback"));
master.setViewOnly(false);
repository.save(master);
System.out.println(">>> SEEDED MASTER USER: admin / admin");
}
}
public List<SystemUser> getAllManagers() {
return repository.findByRole("MANAGER");
}
public SystemUser createManager(SystemUser manager) {
manager.setRole("MANAGER");
manager.setPassword(passwordEncoder.encode(manager.getPassword()));
return repository.save(manager);
}
public List<SystemUser> getAllStaff() {
return repository.findByRole("STAFF");
}
public SystemUser createStaff(SystemUser staff) {
staff.setRole("STAFF");
staff.setPassword(passwordEncoder.encode(staff.getPassword()));
return repository.save(staff);
}
public void deleteManager(Long id) {
if (id != null) {
repository.deleteById(id);
}
}
public Optional<SystemUser> authenticate(String email, String password) {
System.out.println(">>> Attempting authentication for: " + email);
Optional<SystemUser> user = repository.findByEmail(email);
if (user.isPresent()) {
boolean matches = passwordEncoder.matches(password, user.get().getPassword());
System.out.println(">>> User found. Password match: " + matches);
if (matches) {
return user;
}
} else {
System.out.println(">>> User NOT found: " + email);
}
return Optional.empty();
}
}

View File

@@ -0,0 +1,46 @@
package com.rit.canteen.sales.service;
import com.rit.canteen.sales.model.Terminal;
import com.rit.canteen.sales.repository.TerminalRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
@Service
public class TerminalService {
@Autowired
private TerminalRepository terminalRepository;
public List<Terminal> getAllTerminals() {
return terminalRepository.findAll();
}
public Terminal createTerminal(Terminal terminal) {
// Generate a secure API Key
terminal.setApiKey("POS-" + UUID.randomUUID().toString().replace("-", "").toUpperCase());
return terminalRepository.save(terminal);
}
public boolean verifyPin(Long id, String pin) {
if (id == null) return false;
Optional<Terminal> terminalOpt = terminalRepository.findById(id);
return terminalOpt.map(terminal ->
terminal.getPin().trim().equals(pin.trim())
).orElse(false);
}
public Optional<Terminal> getTerminalById(Long id) {
if (id == null) return Optional.empty();
return terminalRepository.findById(id);
}
public void deleteTerminal(Long id) {
if (id != null) {
terminalRepository.deleteById(id);
}
}
}

View File

@@ -0,0 +1,203 @@
package com.rit.canteen.sales.service;
import com.rit.canteen.sales.model.*;
import com.rit.canteen.sales.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
/**
* Check if a user exists by mobile number.
* Returns a LoginResponse indicating whether the user exists.
*/
public LoginResponse checkUserExists(String mobileNumber) {
boolean exists = userRepository.existsByMobileNumber(mobileNumber);
if (exists) {
return new LoginResponse(true, "User found. Please enter your PIN.", true);
} else {
return new LoginResponse(true, "User not found. Please enter your name and create a PIN.", false);
}
}
/**
* Register a new user with name, mobile number and a 6-digit PIN.
* Encrypts the PIN using BCrypt and marks the user as logged in.
*/
public LoginResponse registerUser(String mobileNumber, String name, String pin) {
if (userRepository.existsByMobileNumber(mobileNumber)) {
return new LoginResponse(false, "User already exists. Please login instead.");
}
if (name == null || name.isBlank()) {
return new LoginResponse(false, "Name is required for registration.");
}
if (pin == null || pin.length() != 6 || !pin.matches("^[0-9]{6}$")) {
return new LoginResponse(false, "PIN must be exactly 6 digits.");
}
User user = new User();
user.setMobileNumber(mobileNumber);
user.setName(name);
user.setPinHash(passwordEncoder.encode(pin));
user.setLoggedIn(true);
user.setLastLoginAt(LocalDateTime.now());
userRepository.save(user);
LoginResponse.UserDto userDto = new LoginResponse.UserDto(
user.getId(), user.getMobileNumber(), user.getName(), user.isLoggedIn()
);
return new LoginResponse(true, "Registration successful. You are now logged in.", userDto);
}
/**
* Verify the PIN for an existing user and log them in.
*/
public LoginResponse verifyPinAndLogin(String mobileNumber, String pin) {
Optional<User> userOpt = userRepository.findByMobileNumber(mobileNumber);
if (userOpt.isEmpty()) {
return new LoginResponse(false, "User not found. Please register first.");
}
User user = userOpt.get();
if (!passwordEncoder.matches(pin, user.getPinHash())) {
return new LoginResponse(false, "Incorrect PIN. Please try again.");
}
user.setLoggedIn(true);
user.setLastLoginAt(LocalDateTime.now());
userRepository.save(user);
LoginResponse.UserDto userDto = new LoginResponse.UserDto(
user.getId(), user.getMobileNumber(), user.getName(), user.isLoggedIn()
);
return new LoginResponse(true, "Login successful.", userDto);
}
/**
* Logout a user by updating their logged-in status.
*/
public LoginResponse logout(String mobileNumber) {
Optional<User> userOpt = userRepository.findByMobileNumber(mobileNumber);
if (userOpt.isEmpty()) {
return new LoginResponse(false, "User not found.");
}
User user = userOpt.get();
user.setLoggedIn(false);
userRepository.save(user);
return new LoginResponse(true, "Logged out successfully.");
}
/**
* Change a user's PIN after verifying the current one.
*/
public LoginResponse changePin(String mobileNumber, String currentPin, String newPin) {
Optional<User> userOpt = userRepository.findByMobileNumber(mobileNumber);
if (userOpt.isEmpty()) {
return new LoginResponse(false, "User not found.");
}
User user = userOpt.get();
// Verify current PIN
if (!passwordEncoder.matches(currentPin, user.getPinHash())) {
return new LoginResponse(false, "Incorrect current PIN. Check and try again.");
}
// Validate new PIN format
if (newPin == null || newPin.length() != 6 || !newPin.matches("^[0-9]{6}$")) {
return new LoginResponse(false, "New PIN must be exactly 6 digits.");
}
// Check if new PIN is the same as current
if (currentPin.equals(newPin)) {
return new LoginResponse(false, "New PIN cannot be the same as the current one.");
}
// Update PIN
user.setPinHash(passwordEncoder.encode(newPin));
userRepository.save(user);
return new LoginResponse(true, "Security PIN updated successfully.");
}
/**
* Get user details by mobile number.
*/
public LoginResponse.UserDto getUserByMobile(String mobileNumber) {
Optional<User> userOpt = userRepository.findByMobileNumber(mobileNumber);
if (userOpt.isEmpty()) {
return null;
}
User user = userOpt.get();
return new LoginResponse.UserDto(user.getId(), user.getMobileNumber(), user.getName(), user.isLoggedIn());
}
/**
* Get all registered users for administration dashboard (Paginated).
*/
public Page<LoginResponse.UserDto> getAllUsers(Pageable pageable) {
return userRepository.findAll(pageable)
.map(user -> new LoginResponse.UserDto(
user.getId(),
user.getMobileNumber(),
user.getName(),
user.isLoggedIn()
));
}
/**
* Update user details as an administrator.
*/
public LoginResponse.UserDto updateUser(Long userId, String name, String mobileNumber, String newPin) {
Optional<User> userOpt = userRepository.findById(userId);
if (userOpt.isEmpty()) {
return null;
}
User user = userOpt.get();
if (name != null) user.setName(name);
if (mobileNumber != null) user.setMobileNumber(mobileNumber);
// Only update PIN if it is provided and valid
if (newPin != null && !newPin.isBlank()) {
if (newPin.length() == 6 && newPin.matches("^[0-9]{6}$")) {
user.setPinHash(passwordEncoder.encode(newPin));
}
}
userRepository.save(user);
return new LoginResponse.UserDto(user.getId(), user.getMobileNumber(), user.getName(), user.isLoggedIn());
}
/**
* Delete a user from the system.
*/
public void deleteUser(Long userId) {
userRepository.deleteById(userId);
}
}

View File

@@ -0,0 +1,11 @@
spring.application.name=backend
server.address=0.0.0.0
spring.datasource.url=jdbc:postgresql://localhost:5432/canteen_automation
spring.datasource.username=postgres
spring.datasource.password=Abiram@07
spring.datasource.driver-class-name=org.postgresql.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect

View File

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