Vendor Dashboard updated
2
.gitignore
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
ordering-site/*
|
||||
ordering_site/
|
||||
4
.vscode/settings.json
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"java.compile.nullAnalysis.mode": "automatic",
|
||||
"java.configuration.updateBuildConfiguration": "interactive"
|
||||
}
|
||||
2
backend/.gitattributes
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
/mvnw text eol=lf
|
||||
*.cmd text eol=crlf
|
||||
33
backend/.gitignore
vendored
Normal 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/
|
||||
3
backend/.mvn/wrapper/maven-wrapper.properties
vendored
Normal 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
@@ -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
@@ -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
@@ -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
@@ -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>
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
}
|
||||
102
backend/src/main/java/com/rit/canteen/sales/model/Order.java
Normal 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; }
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
144
backend/src/main/java/com/rit/canteen/sales/model/Product.java
Normal 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; }
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
91
backend/src/main/java/com/rit/canteen/sales/model/Stall.java
Normal 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; }
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
76
backend/src/main/java/com/rit/canteen/sales/model/User.java
Normal 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();
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
@@ -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> {
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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> {
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
11
backend/src/main/resources/application.properties
Normal 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
|
||||
@@ -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() {
|
||||
}
|
||||
|
||||
}
|
||||
24
frontend/.gitignore
vendored
Normal file
@@ -0,0 +1,24 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
73
frontend/README.md
Normal file
@@ -0,0 +1,73 @@
|
||||
# React + TypeScript + Vite
|
||||
|
||||
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
|
||||
|
||||
Currently, two official plugins are available:
|
||||
|
||||
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs)
|
||||
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
|
||||
|
||||
## React Compiler
|
||||
|
||||
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
|
||||
|
||||
## Expanding the ESLint configuration
|
||||
|
||||
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
|
||||
|
||||
```js
|
||||
export default defineConfig([
|
||||
globalIgnores(['dist']),
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [
|
||||
// Other configs...
|
||||
|
||||
// Remove tseslint.configs.recommended and replace with this
|
||||
tseslint.configs.recommendedTypeChecked,
|
||||
// Alternatively, use this for stricter rules
|
||||
tseslint.configs.strictTypeChecked,
|
||||
// Optionally, add this for stylistic rules
|
||||
tseslint.configs.stylisticTypeChecked,
|
||||
|
||||
// Other configs...
|
||||
],
|
||||
languageOptions: {
|
||||
parserOptions: {
|
||||
project: ['./tsconfig.node.json', './tsconfig.app.json'],
|
||||
tsconfigRootDir: import.meta.dirname,
|
||||
},
|
||||
// other options...
|
||||
},
|
||||
},
|
||||
])
|
||||
```
|
||||
|
||||
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
|
||||
|
||||
```js
|
||||
// eslint.config.js
|
||||
import reactX from 'eslint-plugin-react-x'
|
||||
import reactDom from 'eslint-plugin-react-dom'
|
||||
|
||||
export default defineConfig([
|
||||
globalIgnores(['dist']),
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [
|
||||
// Other configs...
|
||||
// Enable lint rules for React
|
||||
reactX.configs['recommended-typescript'],
|
||||
// Enable lint rules for React DOM
|
||||
reactDom.configs.recommended,
|
||||
],
|
||||
languageOptions: {
|
||||
parserOptions: {
|
||||
project: ['./tsconfig.node.json', './tsconfig.app.json'],
|
||||
tsconfigRootDir: import.meta.dirname,
|
||||
},
|
||||
// other options...
|
||||
},
|
||||
},
|
||||
])
|
||||
```
|
||||
23
frontend/eslint.config.js
Normal file
@@ -0,0 +1,23 @@
|
||||
import js from '@eslint/js'
|
||||
import globals from 'globals'
|
||||
import reactHooks from 'eslint-plugin-react-hooks'
|
||||
import reactRefresh from 'eslint-plugin-react-refresh'
|
||||
import tseslint from 'typescript-eslint'
|
||||
import { defineConfig, globalIgnores } from 'eslint/config'
|
||||
|
||||
export default defineConfig([
|
||||
globalIgnores(['dist']),
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [
|
||||
js.configs.recommended,
|
||||
tseslint.configs.recommended,
|
||||
reactHooks.configs.flat.recommended,
|
||||
reactRefresh.configs.vite,
|
||||
],
|
||||
languageOptions: {
|
||||
ecmaVersion: 2020,
|
||||
globals: globals.browser,
|
||||
},
|
||||
},
|
||||
])
|
||||
13
frontend/index.html
Normal file
@@ -0,0 +1,13 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>frontend</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
3973
frontend/package-lock.json
generated
Normal file
43
frontend/package.json
Normal file
@@ -0,0 +1,43 @@
|
||||
{
|
||||
"name": "frontend",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc -b && vite build",
|
||||
"lint": "eslint .",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@types/date-fns": "^2.5.3",
|
||||
"clsx": "^2.1.1",
|
||||
"date-fns": "^4.1.0",
|
||||
"framer-motion": "^12.38.0",
|
||||
"lucide-react": "^1.7.0",
|
||||
"react": "^19.2.4",
|
||||
"react-dom": "^19.2.4",
|
||||
"react-router-dom": "^7.14.0",
|
||||
"recharts": "^3.8.1",
|
||||
"tailwind-merge": "^3.5.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.39.4",
|
||||
"@tailwindcss/postcss": "^4.2.2",
|
||||
"@tailwindcss/vite": "^4.2.2",
|
||||
"@types/node": "^24.12.2",
|
||||
"@types/react": "^19.2.14",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@vitejs/plugin-react": "^6.0.1",
|
||||
"autoprefixer": "^10.4.27",
|
||||
"eslint": "^9.39.4",
|
||||
"eslint-plugin-react-hooks": "^7.0.1",
|
||||
"eslint-plugin-react-refresh": "^0.5.2",
|
||||
"globals": "^17.4.0",
|
||||
"postcss": "^8.5.8",
|
||||
"tailwindcss": "^4.2.2",
|
||||
"typescript": "~6.0.2",
|
||||
"typescript-eslint": "^8.58.0",
|
||||
"vite": "^8.0.4"
|
||||
}
|
||||
}
|
||||
6
frontend/postcss.config.js
Normal file
@@ -0,0 +1,6 @@
|
||||
export default {
|
||||
plugins: {
|
||||
'@tailwindcss/postcss': {},
|
||||
autoprefixer: {},
|
||||
},
|
||||
}
|
||||
1
frontend/public/favicon.svg
Normal file
|
After Width: | Height: | Size: 9.3 KiB |
24
frontend/public/icons.svg
Normal file
@@ -0,0 +1,24 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg">
|
||||
<symbol id="bluesky-icon" viewBox="0 0 16 17">
|
||||
<g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
|
||||
<defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
|
||||
</symbol>
|
||||
<symbol id="discord-icon" viewBox="0 0 20 19">
|
||||
<path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
|
||||
</symbol>
|
||||
<symbol id="documentation-icon" viewBox="0 0 21 20">
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
|
||||
</symbol>
|
||||
<symbol id="github-icon" viewBox="0 0 19 19">
|
||||
<path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
|
||||
</symbol>
|
||||
<symbol id="social-icon" viewBox="0 0 20 20">
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
|
||||
</symbol>
|
||||
<symbol id="x-icon" viewBox="0 0 19 19">
|
||||
<path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
|
||||
</symbol>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 4.9 KiB |
184
frontend/src/App.css
Normal file
@@ -0,0 +1,184 @@
|
||||
.counter {
|
||||
font-size: 16px;
|
||||
padding: 5px 10px;
|
||||
border-radius: 5px;
|
||||
color: var(--accent);
|
||||
background: var(--accent-bg);
|
||||
border: 2px solid transparent;
|
||||
transition: border-color 0.3s;
|
||||
margin-bottom: 24px;
|
||||
|
||||
&:hover {
|
||||
border-color: var(--accent-border);
|
||||
}
|
||||
&:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
}
|
||||
|
||||
.hero {
|
||||
position: relative;
|
||||
|
||||
.base,
|
||||
.framework,
|
||||
.vite {
|
||||
inset-inline: 0;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.base {
|
||||
width: 170px;
|
||||
position: relative;
|
||||
z-index: 0;
|
||||
}
|
||||
|
||||
.framework,
|
||||
.vite {
|
||||
position: absolute;
|
||||
}
|
||||
|
||||
.framework {
|
||||
z-index: 1;
|
||||
top: 34px;
|
||||
height: 28px;
|
||||
transform: perspective(2000px) rotateZ(300deg) rotateX(44deg) rotateY(39deg)
|
||||
scale(1.4);
|
||||
}
|
||||
|
||||
.vite {
|
||||
z-index: 0;
|
||||
top: 107px;
|
||||
height: 26px;
|
||||
width: auto;
|
||||
transform: perspective(2000px) rotateZ(300deg) rotateX(40deg) rotateY(39deg)
|
||||
scale(0.8);
|
||||
}
|
||||
}
|
||||
|
||||
#center {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 25px;
|
||||
place-content: center;
|
||||
place-items: center;
|
||||
flex-grow: 1;
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
padding: 32px 20px 24px;
|
||||
gap: 18px;
|
||||
}
|
||||
}
|
||||
|
||||
#next-steps {
|
||||
display: flex;
|
||||
border-top: 1px solid var(--border);
|
||||
text-align: left;
|
||||
|
||||
& > div {
|
||||
flex: 1 1 0;
|
||||
padding: 32px;
|
||||
@media (max-width: 1024px) {
|
||||
padding: 24px 20px;
|
||||
}
|
||||
}
|
||||
|
||||
.icon {
|
||||
margin-bottom: 16px;
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
}
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
flex-direction: column;
|
||||
text-align: center;
|
||||
}
|
||||
}
|
||||
|
||||
#docs {
|
||||
border-right: 1px solid var(--border);
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
border-right: none;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
}
|
||||
|
||||
#next-steps ul {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin: 32px 0 0;
|
||||
|
||||
.logo {
|
||||
height: 18px;
|
||||
}
|
||||
|
||||
a {
|
||||
color: var(--text-h);
|
||||
font-size: 16px;
|
||||
border-radius: 6px;
|
||||
background: var(--social-bg);
|
||||
display: flex;
|
||||
padding: 6px 12px;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
text-decoration: none;
|
||||
transition: box-shadow 0.3s;
|
||||
|
||||
&:hover {
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
.button-icon {
|
||||
height: 18px;
|
||||
width: 18px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
margin-top: 20px;
|
||||
flex-wrap: wrap;
|
||||
justify-content: center;
|
||||
|
||||
li {
|
||||
flex: 1 1 calc(50% - 8px);
|
||||
}
|
||||
|
||||
a {
|
||||
width: 100%;
|
||||
justify-content: center;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#spacer {
|
||||
height: 88px;
|
||||
border-top: 1px solid var(--border);
|
||||
@media (max-width: 1024px) {
|
||||
height: 48px;
|
||||
}
|
||||
}
|
||||
|
||||
.ticks {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
|
||||
&::before,
|
||||
&::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: -4.5px;
|
||||
border: 5px solid transparent;
|
||||
}
|
||||
|
||||
&::before {
|
||||
left: 0;
|
||||
border-left-color: var(--border);
|
||||
}
|
||||
&::after {
|
||||
right: 0;
|
||||
border-right-color: var(--border);
|
||||
}
|
||||
}
|
||||
97
frontend/src/App.tsx
Normal file
@@ -0,0 +1,97 @@
|
||||
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
|
||||
import Layout from './components/Layout.tsx';
|
||||
import Dashboard from './pages/Dashboard.tsx';
|
||||
import StoreDashboard from './pages/StoreDashboard.tsx';
|
||||
import BaseMenu from './pages/BaseMenu.tsx';
|
||||
import Products from './pages/Products.tsx';
|
||||
import Orders from './pages/Orders.tsx';
|
||||
import ArchivedOrders from './pages/ArchivedOrders.tsx';
|
||||
import Customers from './pages/Customers.tsx';
|
||||
import Login from './pages/Login.tsx';
|
||||
import Managers from './pages/Managers.tsx';
|
||||
import Stalls from './pages/Stalls.tsx';
|
||||
import Staff from './pages/Staff.tsx';
|
||||
import Terminals from './pages/Terminals.tsx';
|
||||
import Vendors from './pages/Vendors.tsx';
|
||||
import Purchases from './pages/Purchases.tsx';
|
||||
import VendorDashboard from './pages/VendorDashboard.tsx';
|
||||
import PurchaseAnalytics from './pages/PurchaseAnalytics.tsx';
|
||||
import Bills from './pages/Bills.tsx';
|
||||
import PurchaseSummary from './pages/PurchaseSummary.tsx';
|
||||
|
||||
const ProtectedRoute = ({ children }: { children: React.ReactNode }) => {
|
||||
const isLoggedIn = sessionStorage.getItem('isLoggedIn') === 'true';
|
||||
return isLoggedIn ? <>{children}</> : <Navigate to="/login" replace />;
|
||||
};
|
||||
|
||||
const PlaceholderPage = ({ title }: { title: string }) => (
|
||||
<div className="p-8">
|
||||
<h1 className="text-2xl font-bold text-[#1e293b]">{title}</h1>
|
||||
<div className="mt-8 p-12 border-2 border-dashed border-[#e2e8f0] rounded-xl flex flex-col items-center justify-center text-[#64748b]">
|
||||
<p className="text-lg font-medium">This page is under development</p>
|
||||
<p className="text-sm">We're working hard to bring you the best experience for {title}.</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<Router>
|
||||
<Routes>
|
||||
<Route path="/login" element={<Login />} />
|
||||
<Route path="/" element={
|
||||
<ProtectedRoute>
|
||||
<Layout />
|
||||
</ProtectedRoute>
|
||||
}>
|
||||
<Route index element={<Navigate to="/dashboard" replace />} />
|
||||
<Route path="dashboard" element={<Dashboard />} />
|
||||
<Route path="store-dashboard" element={<StoreDashboard />} />
|
||||
|
||||
{/* Sale */}
|
||||
<Route path="sale/orders" element={<Orders />} />
|
||||
<Route path="sale/archived-bills" element={<ArchivedOrders />} />
|
||||
|
||||
{/* Customers */}
|
||||
<Route path="customers/orders" element={<Customers />} />
|
||||
|
||||
{/* Purchases */}
|
||||
<Route path="purchases/dashboard" element={<VendorDashboard />} />
|
||||
<Route path="purchases/orders" element={<Purchases />} />
|
||||
<Route path="purchases/summary" element={<PurchaseSummary />} />
|
||||
<Route path="purchases/bills" element={<Bills />} />
|
||||
<Route path="purchases/vendor" element={<Vendors />} />
|
||||
<Route path="purchases/analytics" element={<PurchaseAnalytics />} />
|
||||
|
||||
{/* Inventory */}
|
||||
<Route path="inventory/base" element={<BaseMenu />} />
|
||||
<Route path="inventory/products" element={<Products />} />
|
||||
<Route path="inventory/online" element={<Navigate to="/inventory/products" replace />} />
|
||||
|
||||
{/* Expense */}
|
||||
<Route path="expense/overview" element={<PlaceholderPage title="Expense Overview" />} />
|
||||
<Route path="expense/category" element={<PlaceholderPage title="Expense Category" />} />
|
||||
|
||||
{/* Others */}
|
||||
<Route path="reports" element={<PlaceholderPage title="Reports" />} />
|
||||
<Route path="table" element={<PlaceholderPage title="Table Management" />} />
|
||||
<Route path="wallet" element={<PlaceholderPage title="Wallet" />} />
|
||||
<Route path="feedback" element={<PlaceholderPage title="Feedback" />} />
|
||||
|
||||
{/* Stores */}
|
||||
<Route path="stores/terminals" element={<Terminals />} />
|
||||
<Route path="stores/managers" element={<Managers />} />
|
||||
<Route path="stores/staffs" element={<Staff />} />
|
||||
<Route path="stores/stalls" element={<Stalls />} />
|
||||
|
||||
{/* Promotions */}
|
||||
<Route path="promotions/discounts" element={<PlaceholderPage title="Discounts" />} />
|
||||
<Route path="promotions/coupon" element={<PlaceholderPage title="Coupons" />} />
|
||||
<Route path="promotions/coupon-template" element={<PlaceholderPage title="Coupon Templates" />} />
|
||||
</Route>
|
||||
</Routes>
|
||||
</Router>
|
||||
);
|
||||
}
|
||||
|
||||
export default App;
|
||||
BIN
frontend/src/assets/college-logo.png
Normal file
|
After Width: | Height: | Size: 157 KiB |
BIN
frontend/src/assets/hero.png
Normal file
|
After Width: | Height: | Size: 44 KiB |
1
frontend/src/assets/react.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>
|
||||
|
After Width: | Height: | Size: 4.0 KiB |
BIN
frontend/src/assets/ritchennai.webp
Normal file
|
After Width: | Height: | Size: 1.4 MiB |
1
frontend/src/assets/vite.svg
Normal file
|
After Width: | Height: | Size: 8.5 KiB |
149
frontend/src/components/AddTerminalModal.tsx
Normal file
@@ -0,0 +1,149 @@
|
||||
import React, { useState } from 'react';
|
||||
import { motion, AnimatePresence } from 'framer-motion';
|
||||
import { X, Monitor, MapPin, Lock } from 'lucide-react';
|
||||
import Numpad from './Numpad.tsx';
|
||||
|
||||
interface AddTerminalModalProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
onSuccess: () => void;
|
||||
}
|
||||
|
||||
const AddTerminalModal: React.FC<AddTerminalModalProps> = ({ isOpen, onClose, onSuccess }) => {
|
||||
const [name, setName] = useState('');
|
||||
const [location, setLocation] = useState('');
|
||||
const [pin, setPin] = useState('');
|
||||
const [step, setStep] = useState(1); // 1: Details, 2: PIN
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const handleSubmit = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const response = await fetch('/api/terminals', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name, location, pin }),
|
||||
});
|
||||
if (response.ok) {
|
||||
onSuccess();
|
||||
reset();
|
||||
onClose();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to create terminal:', error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const reset = () => {
|
||||
setName('');
|
||||
setLocation('');
|
||||
setPin('');
|
||||
setStep(1);
|
||||
};
|
||||
|
||||
if (!isOpen) return null;
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-[60] flex items-center justify-center p-4 bg-black/40 backdrop-blur-sm">
|
||||
<motion.div
|
||||
initial={{ opacity: 0, scale: 0.95, y: 20 }}
|
||||
animate={{ opacity: 1, scale: 1, y: 0 }}
|
||||
exit={{ opacity: 0, scale: 0.95, y: 20 }}
|
||||
className="bg-white rounded-3xl shadow-2xl w-full max-w-md overflow-hidden relative"
|
||||
>
|
||||
<div className="p-6 border-b border-gray-100 flex items-center justify-between">
|
||||
<h3 className="text-xl font-bold text-[#231651]">Register New Terminal</h3>
|
||||
<button onClick={onClose} className="p-2 hover:bg-gray-100 rounded-full transition-colors">
|
||||
<X size={20} className="text-gray-400" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="p-8">
|
||||
<AnimatePresence mode="wait">
|
||||
{step === 1 ? (
|
||||
<motion.div
|
||||
key="step1"
|
||||
initial={{ opacity: 0, x: -20 }}
|
||||
animate={{ opacity: 1, x: 0 }}
|
||||
exit={{ opacity: 0, x: 20 }}
|
||||
className="space-y-6"
|
||||
>
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-semibold text-gray-700 flex items-center gap-2">
|
||||
<Monitor size={16} className="text-[#231651]" /> Terminal Name
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder="e.g. Counter 1"
|
||||
className="w-full h-12 px-4 bg-gray-50 border border-gray-200 rounded-xl focus:ring-2 focus:ring-[#231651]/20 focus:border-[#231651] outline-none transition-all"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-semibold text-gray-700 flex items-center gap-2">
|
||||
<MapPin size={16} className="text-[#231651]" /> Location
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={location}
|
||||
onChange={(e) => setLocation(e.target.value)}
|
||||
placeholder="e.g. Main Entrance"
|
||||
className="w-full h-12 px-4 bg-gray-50 border border-gray-200 rounded-xl focus:ring-2 focus:ring-[#231651]/20 focus:border-[#231651] outline-none transition-all"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button
|
||||
disabled={!name || !location}
|
||||
onClick={() => setStep(2)}
|
||||
className="w-full h-14 bg-[#231651] text-white rounded-2xl font-bold shadow-lg shadow-[#231651]/20 hover:scale-[1.02] active:scale-[0.98] transition-all disabled:opacity-50 disabled:scale-100"
|
||||
>
|
||||
Set Security PIN
|
||||
</button>
|
||||
</motion.div>
|
||||
) : (
|
||||
<motion.div
|
||||
key="step2"
|
||||
initial={{ opacity: 0, x: 20 }}
|
||||
animate={{ opacity: 1, x: 0 }}
|
||||
exit={{ opacity: 0, x: -20 }}
|
||||
className="space-y-6"
|
||||
>
|
||||
<div className="text-center mb-4">
|
||||
<div className="inline-flex p-3 bg-purple-50 text-[#231651] rounded-2xl mb-3">
|
||||
<Lock size={24} />
|
||||
</div>
|
||||
<h4 className="text-lg font-bold text-gray-900">Create Security PIN</h4>
|
||||
<p className="text-sm text-gray-500">This PIN is required to access the API Key</p>
|
||||
</div>
|
||||
|
||||
<Numpad value={pin} onChange={setPin} maxLength={4} />
|
||||
|
||||
<div className="flex gap-3 pt-4">
|
||||
<button
|
||||
onClick={() => setStep(1)}
|
||||
className="flex-1 h-14 bg-gray-100 text-gray-600 rounded-2xl font-bold hover:bg-gray-200 transition-all"
|
||||
>
|
||||
Back
|
||||
</button>
|
||||
<button
|
||||
disabled={pin.length < 4 || loading}
|
||||
onClick={handleSubmit}
|
||||
className="flex-[2] h-14 bg-[#231651] text-white rounded-2xl font-bold shadow-lg shadow-[#231651]/20 hover:scale-[1.02] active:scale-[0.98] transition-all disabled:opacity-50 disabled:scale-100"
|
||||
>
|
||||
{loading ? 'Registering...' : 'Register Terminal'}
|
||||
</button>
|
||||
</div>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
</motion.div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default AddTerminalModal;
|
||||
49
frontend/src/components/Header.tsx
Normal file
@@ -0,0 +1,49 @@
|
||||
import { Bell, Search, Settings, HelpCircle, Calendar } from 'lucide-react';
|
||||
|
||||
const Header = () => {
|
||||
const currentDate = new Date().toLocaleDateString('en-US', {
|
||||
weekday: 'long',
|
||||
year: 'numeric',
|
||||
month: 'long',
|
||||
day: 'numeric',
|
||||
});
|
||||
|
||||
return (
|
||||
<header className="h-16 bg-white/80 backdrop-blur-md border-b border-[#e2e8f0] px-8 flex items-center justify-between sticky top-0 z-40">
|
||||
<div className="flex items-center gap-4 flex-1">
|
||||
<div className="relative group w-full max-w-md">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 text-[#64748b] group-focus-within:text-[#231651] transition-colors" size={18} />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Search dashboard..."
|
||||
className="w-full bg-gray-50 border border-transparent rounded-lg py-2 pl-10 pr-4 text-sm focus:outline-none focus:bg-white focus:border-[#231651]/30 transition-all shadow-sm"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-6">
|
||||
<div className="hidden lg:flex items-center gap-2 text-[#64748b] text-sm">
|
||||
<Calendar size={16} />
|
||||
<span>{currentDate}</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-4 border-l border-[#e2e8f0] pl-6">
|
||||
<button className="relative p-2 text-[#64748b] hover:text-[#1e293b] hover:bg-gray-100 rounded-lg transition-all group">
|
||||
<Bell size={20} />
|
||||
<span className="absolute top-2 right-2 w-2 h-2 bg-red-500 rounded-full border-2 border-white"></span>
|
||||
</button>
|
||||
|
||||
<button className="p-2 text-[#64748b] hover:text-[#1e293b] hover:bg-gray-100 rounded-lg transition-all">
|
||||
<Settings size={20} />
|
||||
</button>
|
||||
|
||||
<button className="p-2 text-[#64748b] hover:text-[#1e293b] hover:bg-gray-100 rounded-lg transition-all">
|
||||
<HelpCircle size={20} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
};
|
||||
|
||||
export default Header;
|
||||
21
frontend/src/components/Layout.tsx
Normal file
@@ -0,0 +1,21 @@
|
||||
import { Outlet } from 'react-router-dom';
|
||||
import Sidebar from './Sidebar.tsx';
|
||||
import Header from './Header.tsx';
|
||||
|
||||
const Layout = () => {
|
||||
return (
|
||||
<div className="flex min-h-screen bg-[#f8fafc]">
|
||||
<Sidebar />
|
||||
<main className="flex-1 ml-64 flex flex-col min-w-0">
|
||||
<Header />
|
||||
<div className="flex-1 overflow-x-hidden overflow-y-auto">
|
||||
<div className="container mx-auto">
|
||||
<Outlet />
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Layout;
|
||||
81
frontend/src/components/Numpad.tsx
Normal file
@@ -0,0 +1,81 @@
|
||||
import { motion } from 'framer-motion';
|
||||
import { Delete } from 'lucide-react';
|
||||
import { clsx, type ClassValue } from 'clsx';
|
||||
import { twMerge } from 'tailwind-merge';
|
||||
|
||||
function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs));
|
||||
}
|
||||
|
||||
interface NumpadProps {
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
maxLength?: number;
|
||||
}
|
||||
|
||||
const Numpad: React.FC<NumpadProps> = ({ value, onChange, maxLength = 4 }) => {
|
||||
const handleNumberClick = (num: string) => {
|
||||
if (value.length < maxLength) {
|
||||
onChange(value + num);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = () => {
|
||||
onChange(value.slice(0, -1));
|
||||
};
|
||||
|
||||
const handleClear = () => {
|
||||
onChange('');
|
||||
};
|
||||
|
||||
const buttons = [
|
||||
'1', '2', '3',
|
||||
'4', '5', '6',
|
||||
'7', '8', '9',
|
||||
'C', '0', 'DEL'
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="w-full max-w-[280px] mx-auto p-4 bg-gray-50/50 rounded-2xl border border-gray-100">
|
||||
{/* PIN Display Dots */}
|
||||
<div className="flex justify-center gap-3 mb-8">
|
||||
{[...Array(maxLength)].map((_, i) => (
|
||||
<motion.div
|
||||
key={i}
|
||||
initial={false}
|
||||
animate={{
|
||||
scale: i < value.length ? 1.2 : 1,
|
||||
backgroundColor: i < value.length ? '#231651' : '#e2e8f0'
|
||||
}}
|
||||
className="w-3 h-3 rounded-full"
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Grid */}
|
||||
<div className="grid grid-cols-3 gap-3">
|
||||
{buttons.map((btn) => (
|
||||
<motion.button
|
||||
key={btn}
|
||||
whileHover={{ scale: 1.05, backgroundColor: '#f8fafc' }}
|
||||
whileTap={{ scale: 0.95 }}
|
||||
onClick={() => {
|
||||
if (btn === 'C') handleClear();
|
||||
else if (btn === 'DEL') handleDelete();
|
||||
else handleNumberClick(btn);
|
||||
}}
|
||||
className={cn(
|
||||
"h-14 flex items-center justify-center rounded-xl text-lg font-bold transition-all",
|
||||
btn === 'C' ? "text-red-500 hover:text-red-600" :
|
||||
btn === 'DEL' ? "text-gray-500" : "text-[#231651]"
|
||||
)}
|
||||
>
|
||||
{btn === 'DEL' ? <Delete size={20} /> : btn}
|
||||
</motion.button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Numpad;
|
||||
85
frontend/src/components/Pagination.tsx
Normal file
@@ -0,0 +1,85 @@
|
||||
import React from 'react';
|
||||
import {
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
ChevronDown
|
||||
} from 'lucide-react';
|
||||
|
||||
interface PaginationProps {
|
||||
currentPage: number; // 0-indexed
|
||||
pageSize: number;
|
||||
totalElements: number;
|
||||
onPageChange: (page: number) => void;
|
||||
onPageSizeChange: (size: number) => void;
|
||||
}
|
||||
|
||||
const Pagination: React.FC<PaginationProps> = ({
|
||||
currentPage,
|
||||
pageSize,
|
||||
totalElements,
|
||||
onPageChange,
|
||||
onPageSizeChange
|
||||
}) => {
|
||||
const totalPages = Math.ceil(totalElements / pageSize);
|
||||
const startRange = totalElements === 0 ? 0 : currentPage * pageSize + 1;
|
||||
const endRange = Math.min((currentPage + 1) * pageSize, totalElements);
|
||||
|
||||
return (
|
||||
<div className="flex items-center justify-end px-4 py-3 bg-white border-t border-slate-100 gap-8">
|
||||
{/* Rows per page */}
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="text-[10px] font-black text-slate-400 uppercase tracking-widest">Rows per page</span>
|
||||
<div className="relative group">
|
||||
<select
|
||||
value={pageSize}
|
||||
onChange={(e) => onPageSizeChange(Number(e.target.value))}
|
||||
className="appearance-none bg-slate-50 border border-slate-200 rounded-lg pl-3 pr-8 py-1.5 text-xs font-bold text-slate-700 outline-none cursor-pointer hover:border-slate-300 transition-all"
|
||||
>
|
||||
<option value={10}>10</option>
|
||||
<option value={20}>20</option>
|
||||
<option value={30}>30</option>
|
||||
<option value={50}>50</option>
|
||||
</select>
|
||||
<div className="absolute right-2.5 top-1/2 -translate-y-1/2 pointer-events-none text-slate-400 group-hover:text-slate-600 transition-colors">
|
||||
<ChevronDown size={14} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Range display */}
|
||||
<div className="text-xs font-bold text-slate-600 tracking-tight">
|
||||
{startRange}–{endRange} of <span className="font-black text-slate-900">{totalElements}</span>
|
||||
</div>
|
||||
|
||||
{/* Navigation buttons */}
|
||||
<div className="flex items-center gap-1">
|
||||
<button
|
||||
onClick={() => onPageChange(currentPage - 1)}
|
||||
disabled={currentPage === 0}
|
||||
className={`p-1.5 rounded-lg transition-all ${
|
||||
currentPage === 0
|
||||
? 'text-slate-200 cursor-not-allowed'
|
||||
: 'text-slate-500 hover:bg-slate-50 hover:text-slate-900 active:scale-90'
|
||||
}`}
|
||||
title="Previous Page"
|
||||
>
|
||||
<ChevronLeft size={20} />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => onPageChange(currentPage + 1)}
|
||||
disabled={currentPage >= totalPages - 1}
|
||||
className={`p-1.5 rounded-lg transition-all ${
|
||||
currentPage >= totalPages - 1
|
||||
? 'text-slate-200 cursor-not-allowed'
|
||||
: 'text-slate-500 hover:bg-slate-50 hover:text-slate-900 active:scale-90'
|
||||
}`}
|
||||
title="Next Page"
|
||||
>
|
||||
<ChevronRight size={20} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Pagination;
|
||||
182
frontend/src/components/PinVerificationModal.tsx
Normal file
@@ -0,0 +1,182 @@
|
||||
import React, { useState } from 'react';
|
||||
import { motion, AnimatePresence } from 'framer-motion';
|
||||
import { X, Lock, Copy, CheckCircle2, AlertCircle } from 'lucide-react';
|
||||
import Numpad from './Numpad.tsx';
|
||||
|
||||
interface PinVerificationModalProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
terminalId: number | null;
|
||||
terminalName: string;
|
||||
}
|
||||
|
||||
const PinVerificationModal: React.FC<PinVerificationModalProps> = ({
|
||||
isOpen,
|
||||
onClose,
|
||||
terminalId,
|
||||
terminalName
|
||||
}) => {
|
||||
const [pin, setPin] = useState('');
|
||||
const [apiKey, setApiKey] = useState<string | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [copied, setCopied] = useState(false);
|
||||
|
||||
const handleVerify = async (freshPin?: string) => {
|
||||
if (!terminalId) return;
|
||||
const pinToVerify = freshPin || pin;
|
||||
if (!pinToVerify || pinToVerify.length < 4) return;
|
||||
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const response = await fetch(`/api/terminals/${terminalId}/verify-pin`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ pin: pinToVerify }),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (response.ok) {
|
||||
setApiKey(data.apiKey);
|
||||
} else {
|
||||
setError(data.message || 'Verification failed');
|
||||
setPin('');
|
||||
}
|
||||
} catch (err) {
|
||||
setError('Connection error');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const copyToClipboard = () => {
|
||||
if (apiKey) {
|
||||
navigator.clipboard.writeText(apiKey);
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
}
|
||||
};
|
||||
|
||||
const handleClose = () => {
|
||||
setPin('');
|
||||
setApiKey(null);
|
||||
setError(null);
|
||||
onClose();
|
||||
};
|
||||
|
||||
if (!isOpen) return null;
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-[60] flex items-center justify-center p-4 bg-black/40 backdrop-blur-sm">
|
||||
<motion.div
|
||||
initial={{ opacity: 0, scale: 0.95, y: 20 }}
|
||||
animate={{ opacity: 1, scale: 1, y: 0 }}
|
||||
exit={{ opacity: 0, scale: 0.95, y: 20 }}
|
||||
className="bg-white rounded-3xl shadow-2xl w-full max-w-md overflow-hidden relative"
|
||||
>
|
||||
<div className="p-6 border-b border-gray-100 flex items-center justify-between">
|
||||
<h3 className="text-xl font-bold text-[#231651]">Security Authentication</h3>
|
||||
<button onClick={handleClose} className="p-2 hover:bg-gray-100 rounded-full transition-colors">
|
||||
<X size={20} className="text-gray-400" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="p-8">
|
||||
<AnimatePresence mode="wait">
|
||||
{!apiKey ? (
|
||||
<motion.div
|
||||
key="verification"
|
||||
initial={{ opacity: 0, scale: 0.95 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
exit={{ opacity: 0, scale: 1.05 }}
|
||||
className="space-y-6 text-center"
|
||||
>
|
||||
<div className="inline-flex p-4 bg-orange-50 text-orange-600 rounded-2xl mb-2">
|
||||
<Lock size={32} />
|
||||
</div>
|
||||
<div>
|
||||
<h4 className="text-lg font-bold text-gray-900">{terminalName}</h4>
|
||||
<p className="text-sm text-gray-500 mt-1">Enter your 4-digit security PIN to view the API Key</p>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: -10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
className="p-3 bg-red-50 text-red-600 rounded-xl text-sm font-medium flex items-center justify-center gap-2"
|
||||
>
|
||||
<AlertCircle size={16} />
|
||||
{error}
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
<Numpad value={pin} onChange={(v) => {
|
||||
setPin(v);
|
||||
if (v.length === 4) {
|
||||
// Slight delay for visual feedback of the last dot
|
||||
setTimeout(() => handleVerify(v), 100);
|
||||
}
|
||||
}} maxLength={4} />
|
||||
|
||||
<button
|
||||
disabled={pin.length < 4 || loading}
|
||||
onClick={() => handleVerify()}
|
||||
className="w-full h-14 bg-[#231651] text-white rounded-2xl font-bold shadow-lg shadow-[#231651]/20 hover:scale-[1.02] active:scale-[0.98] transition-all disabled:opacity-50 disabled:scale-100"
|
||||
>
|
||||
{loading ? 'Verifying...' : 'Verify PIN'}
|
||||
</button>
|
||||
</motion.div>
|
||||
) : (
|
||||
<motion.div
|
||||
key="result"
|
||||
initial={{ opacity: 0, scale: 1.1 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
className="space-y-8 text-center"
|
||||
>
|
||||
<div className="inline-flex p-4 bg-green-50 text-green-600 rounded-full mb-2">
|
||||
<CheckCircle2 size={40} />
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h4 className="text-xl font-bold text-gray-900">Authentication Successful</h4>
|
||||
<p className="text-sm text-gray-500 mt-1">Below is the API key for physical device integration</p>
|
||||
</div>
|
||||
|
||||
<div className="relative group">
|
||||
<div className="absolute -inset-1 bg-gradient-to-r from-purple-600 to-[#231651] rounded-2xl blur opacity-20 group-hover:opacity-40 transition duration-1000"></div>
|
||||
<div className="relative p-5 bg-gray-50 border border-gray-200 rounded-2xl break-all font-mono text-sm text-[#231651] flex items-center justify-between gap-4">
|
||||
<span className="text-left">{apiKey}</span>
|
||||
<button
|
||||
onClick={copyToClipboard}
|
||||
className="p-2 hover:bg-white rounded-lg transition-colors shadow-sm shrink-0"
|
||||
>
|
||||
{copied ? <CheckCircle2 size={18} className="text-green-600" /> : <Copy size={18} className="text-[#231651]" />}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="p-4 bg-blue-50/50 rounded-2xl flex gap-3 text-left">
|
||||
<AlertCircle size={20} className="text-blue-600 shrink-0 mt-0.5" />
|
||||
<p className="text-[12px] text-blue-700 leading-relaxed font-medium">
|
||||
This API key allows the terminal to communicate with the central server. Keep it secure and never share it publicly.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={handleClose}
|
||||
className="w-full h-14 bg-[#231651] text-white rounded-2xl font-bold shadow-lg shadow-[#231651]/20 hover:scale-[1.02] active:scale-[0.98] transition-all"
|
||||
>
|
||||
Close Session
|
||||
</button>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
</motion.div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default PinVerificationModal;
|
||||
312
frontend/src/components/Sidebar.tsx
Normal file
@@ -0,0 +1,312 @@
|
||||
import React, { useState } from 'react';
|
||||
import { NavLink, useLocation, useNavigate } from 'react-router-dom';
|
||||
import {
|
||||
BarChart3,
|
||||
ChevronRight,
|
||||
CreditCard,
|
||||
Gauge,
|
||||
LayoutGrid,
|
||||
Megaphone,
|
||||
MessageSquare,
|
||||
ShoppingCart,
|
||||
Store,
|
||||
Table2,
|
||||
Users,
|
||||
Wallet,
|
||||
ShoppingBag,
|
||||
Receipt,
|
||||
Search,
|
||||
LogOut
|
||||
} from 'lucide-react';
|
||||
import { motion, AnimatePresence } from 'framer-motion';
|
||||
import { clsx, type ClassValue } from 'clsx';
|
||||
import { twMerge } from 'tailwind-merge';
|
||||
import collegeLogo from '../assets/college-logo.png';
|
||||
|
||||
function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs));
|
||||
}
|
||||
|
||||
interface MenuItem {
|
||||
title: string;
|
||||
icon: React.ElementType;
|
||||
path?: string;
|
||||
subMenu?: { title: string; path: string }[];
|
||||
}
|
||||
|
||||
const menuItems: MenuItem[] = [
|
||||
{ title: 'Dashboard', icon: Gauge, path: '/dashboard' },
|
||||
{ title: 'Store Dashboard', icon: LayoutGrid, path: '/store-dashboard' },
|
||||
{
|
||||
title: 'Sale',
|
||||
icon: Receipt,
|
||||
subMenu: [
|
||||
{ title: 'Orders', path: '/sale/orders' },
|
||||
{ title: 'Archived Bills', path: '/sale/archived-bills' }
|
||||
]
|
||||
},
|
||||
{
|
||||
title: 'Customers',
|
||||
icon: Users,
|
||||
subMenu: [
|
||||
{ title: 'Orders', path: '/customers/orders' }
|
||||
]
|
||||
},
|
||||
{
|
||||
title: 'Vendors',
|
||||
icon: ShoppingBag,
|
||||
subMenu: [
|
||||
{ title: 'Dashboard', path: '/purchases/dashboard' },
|
||||
{ title: 'Orders', path: '/purchases/orders' },
|
||||
{ title: 'Summary', path: '/purchases/summary' },
|
||||
{ title: 'Bills', path: '/purchases/bills' },
|
||||
{ title: 'Vendors', path: '/purchases/vendor' },
|
||||
{ title: 'Purchase Analytics', path: '/purchases/analytics' }
|
||||
]
|
||||
},
|
||||
{
|
||||
title: 'Inventory',
|
||||
icon: ShoppingCart,
|
||||
subMenu: [
|
||||
{ title: 'Base Items', path: '/inventory/base' },
|
||||
{ title: 'Products', path: '/inventory/products' }
|
||||
]
|
||||
},
|
||||
{
|
||||
title: 'Expense',
|
||||
icon: Wallet,
|
||||
subMenu: [
|
||||
{ title: 'Overview', path: '/expense/overview' },
|
||||
{ title: 'Category', path: '/expense/category' }
|
||||
]
|
||||
},
|
||||
{ title: 'Reports', icon: BarChart3, path: '/reports' },
|
||||
{
|
||||
title: 'Stores',
|
||||
icon: Store,
|
||||
subMenu: [
|
||||
{ title: 'Terminals', path: '/stores/terminals' },
|
||||
{ title: 'Managers', path: '/stores/managers' },
|
||||
{ title: 'Staffs', path: '/stores/staffs' },
|
||||
{ title: 'Stalls', path: '/stores/stalls' }
|
||||
]
|
||||
},
|
||||
{ title: 'Table', icon: Table2, path: '/table' },
|
||||
{ title: 'Wallet', icon: CreditCard, path: '/wallet' },
|
||||
{
|
||||
title: 'Promotions',
|
||||
icon: Megaphone,
|
||||
subMenu: [
|
||||
{ title: 'Discounts', path: '/promotions/discounts' },
|
||||
{ title: 'Coupon', path: '/promotions/coupon' },
|
||||
{ title: 'CouponTemplate', path: '/promotions/coupon-template' }
|
||||
]
|
||||
},
|
||||
{ title: 'Feedback', icon: MessageSquare, path: '/feedback' },
|
||||
];
|
||||
|
||||
const Sidebar = () => {
|
||||
const [openMenus, setOpenMenus] = useState<string[]>([]);
|
||||
const location = useLocation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
// Permission Logic
|
||||
const userRole = sessionStorage.getItem('userRole') || 'master';
|
||||
const userPermissions = JSON.parse(sessionStorage.getItem('userPermissions') || '[]');
|
||||
|
||||
const filteredMenuItems = menuItems.filter(item => {
|
||||
if (userRole === 'master') return true;
|
||||
|
||||
// Map title to permission ID
|
||||
const permissionMap: Record<string, string> = {
|
||||
'Dashboard': 'dashboard',
|
||||
'Store Dashboard': 'dashboard',
|
||||
'Sale': 'sale',
|
||||
'Customers': 'customers',
|
||||
'Vendors': 'purchases',
|
||||
'Inventory': 'inventory',
|
||||
'Expense': 'expense',
|
||||
'Reports': 'reports',
|
||||
'Stores': 'stores',
|
||||
'Table': 'table',
|
||||
'Wallet': 'wallet',
|
||||
'Promotions': 'promotions',
|
||||
'Feedback': 'feedback'
|
||||
};
|
||||
|
||||
return userPermissions.includes(permissionMap[item.title]);
|
||||
});
|
||||
|
||||
const handleLogout = () => {
|
||||
sessionStorage.removeItem('isLoggedIn');
|
||||
sessionStorage.removeItem('userRole');
|
||||
sessionStorage.removeItem('userPermissions');
|
||||
navigate('/login');
|
||||
};
|
||||
|
||||
const toggleMenu = (title: string) => {
|
||||
setOpenMenus((prev) =>
|
||||
prev.includes(title)
|
||||
? prev.filter((item) => item !== title)
|
||||
: [...prev, title]
|
||||
);
|
||||
};
|
||||
|
||||
// Check if a sub-menu should be open based on the current location
|
||||
React.useEffect(() => {
|
||||
const currentMenu = menuItems.find(item =>
|
||||
item.subMenu?.some(sub => location.pathname.startsWith(sub.path))
|
||||
);
|
||||
if (currentMenu && !openMenus.includes(currentMenu.title)) {
|
||||
setOpenMenus(prev => [...prev, currentMenu.title]);
|
||||
}
|
||||
}, [location.pathname]);
|
||||
|
||||
return (
|
||||
<div className="w-64 bg-white h-screen border-r border-[#e2e8f0] flex flex-col fixed left-0 top-0 z-50 shadow-sm overflow-hidden font-inter">
|
||||
{/* Branding Section */}
|
||||
<div className="px-5 pt-8 pb-4 flex items-center">
|
||||
<img src={collegeLogo} alt="Branding" className="h-14 w-auto object-contain brightness-[1.05]" />
|
||||
</div>
|
||||
|
||||
{/* Premium Search Integration (Modern Dashboards usually have this) */}
|
||||
<div className="px-3 mb-4">
|
||||
<div className="relative flex items-center group">
|
||||
<div className="absolute left-3 flex items-center justify-center pointer-events-none">
|
||||
<Search size={16} className="text-[#64748b] group-focus-within:text-[#231651] transition-colors" />
|
||||
</div>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Search Menu..."
|
||||
title="Search for a specific module or page"
|
||||
className="w-full h-10 bg-gray-50 border border-[#e2e8f0] rounded-xl pl-10 pr-4 text-[13px] font-medium outline-none transition-all focus:bg-white focus:border-[#231651]/30 focus:shadow-sm placeholder:text-[#94a3b8] text-[#1e293b]"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* The main dashboard list starts here */}
|
||||
|
||||
<div className="flex-1 overflow-y-auto px-3 custom-scrollbar">
|
||||
<ul className="space-y-1">
|
||||
{filteredMenuItems.map((item) => (
|
||||
<li key={item.title}>
|
||||
{item.subMenu ? (
|
||||
<div>
|
||||
<button
|
||||
onClick={() => toggleMenu(item.title)}
|
||||
title={`Expand/Collapse ${item.title}`}
|
||||
className={cn(
|
||||
"w-full flex items-center justify-between p-2.5 rounded-xl text-sm font-semibold transition-all duration-200 group",
|
||||
openMenus.includes(item.title)
|
||||
? "text-[#521c4b] bg-[#521c4b]/5"
|
||||
: "text-[#475569] hover:bg-gray-50 hover:text-[#1e293b]"
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<item.icon size={18} strokeWidth={2} className={cn(
|
||||
"transition-colors",
|
||||
openMenus.includes(item.title) ? "text-[#231651]" : "text-[#64748b] group-hover:text-[#475569]"
|
||||
)} />
|
||||
<span className="tracking-tight">{item.title}</span>
|
||||
</div>
|
||||
<div className={cn(
|
||||
"transition-transform duration-300",
|
||||
openMenus.includes(item.title) ? "rotate-90" : ""
|
||||
)}>
|
||||
<ChevronRight size={14} className="opacity-60" />
|
||||
</div>
|
||||
</button>
|
||||
|
||||
<AnimatePresence initial={false}>
|
||||
{openMenus.includes(item.title) && (
|
||||
<motion.ul
|
||||
initial={{ height: 0, opacity: 0 }}
|
||||
animate={{ height: 'auto', opacity: 1 }}
|
||||
exit={{ height: 0, opacity: 0 }}
|
||||
transition={{ duration: 0.3, ease: "easeInOut" }}
|
||||
className="ml-6 mt-1 mb-2 space-y-0.5 border-l border-[#e2e8f0]/60 overflow-hidden"
|
||||
>
|
||||
{item.subMenu.map((sub) => (
|
||||
<li key={sub.title}>
|
||||
<NavLink
|
||||
to={sub.path}
|
||||
title={`Go to ${sub.title}`}
|
||||
className={({ isActive }) => cn(
|
||||
"flex items-center gap-3 py-2 px-4 rounded-lg text-[13px] font-medium transition-all group relative",
|
||||
isActive
|
||||
? "text-white bg-[#521c4b] shadow-md shadow-[#521c4b]/10"
|
||||
: "text-[#64748b] hover:text-[#1e293b] hover:translate-x-1"
|
||||
)}
|
||||
>
|
||||
{({ isActive }) => (
|
||||
<>
|
||||
<div className={cn(
|
||||
"w-1.5 h-1.5 rounded-full transition-all duration-300",
|
||||
isActive ? "bg-[#231651] scale-125" : "bg-gray-300 group-hover:bg-gray-400"
|
||||
)} />
|
||||
<span>{sub.title}</span>
|
||||
{isActive && (
|
||||
<motion.div
|
||||
layoutId="activeSubMenu"
|
||||
className="absolute left-[-1.5px] top-1/4 bottom-1/4 w-[3px] bg-[#231651] rounded-full"
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</NavLink>
|
||||
</li>
|
||||
))}
|
||||
</motion.ul>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
) : (
|
||||
<NavLink
|
||||
to={item.path!}
|
||||
title={`Go to ${item.title}`}
|
||||
className={({ isActive }) => cn(
|
||||
"flex items-center gap-3 p-2.5 rounded-xl text-sm font-semibold transition-all duration-200 group",
|
||||
isActive
|
||||
? "bg-[#521c4b] text-white shadow-lg shadow-[#521c4b]/15"
|
||||
: "text-[#475569] hover:bg-gray-50 hover:text-[#1e293b]"
|
||||
)}
|
||||
>
|
||||
{({ isActive }) => (
|
||||
<>
|
||||
<item.icon size={18} strokeWidth={2} className={cn(
|
||||
"transition-colors",
|
||||
isActive ? "text-white" : "text-[#64748b] group-hover:text-[#475569]"
|
||||
)} />
|
||||
<span className="tracking-tight">{item.title}</span>
|
||||
</>
|
||||
)}
|
||||
</NavLink>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div className="p-4 bg-gray-50/50 border-t border-[#e2e8f0]">
|
||||
<button
|
||||
onClick={handleLogout}
|
||||
title="Sign out of your account"
|
||||
className="w-full flex items-center gap-3 p-2.5 rounded-xl text-red-600 hover:bg-red-50 transition-all font-semibold text-sm group"
|
||||
>
|
||||
<LogOut size={18} className="group-hover:-translate-x-1 transition-transform" />
|
||||
<span>Logout</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<style dangerouslySetInnerHTML={{ __html: `
|
||||
.custom-scrollbar::-webkit-scrollbar { width: 4px; }
|
||||
.custom-scrollbar::-webkit-scrollbar-track { background: transparent; }
|
||||
.custom-scrollbar::-webkit-scrollbar-thumb { background: #e2e8f0; border-radius: 10px; }
|
||||
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');
|
||||
.font-inter { font-family: 'Inter', sans-serif; }
|
||||
` }} />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Sidebar;
|
||||
113
frontend/src/index.css
Normal file
@@ -0,0 +1,113 @@
|
||||
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&display=swap');
|
||||
@import "tailwindcss";
|
||||
|
||||
|
||||
@theme {
|
||||
--font-sans: "Inter", "system-ui", "-apple-system", "sans-serif";
|
||||
--color-primary: #231651;
|
||||
--color-primary-light: #35217a;
|
||||
--color-primary-glow: rgba(35, 22, 81, 0.1);
|
||||
--color-bg-main: #D6FFF6;
|
||||
--color-bg-sidebar: #ffffff;
|
||||
--color-text-dark: #231651;
|
||||
--color-text-primary: #231651;
|
||||
--color-text-secondary: #4a3e7a;
|
||||
--color-text-muted: #7b71af;
|
||||
--color-border: rgba(35, 22, 81, 0.1);
|
||||
--color-border-light: rgba(35, 22, 81, 0.05);
|
||||
}
|
||||
|
||||
@layer base {
|
||||
* {
|
||||
@apply border-border;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
@apply bg-bg-main text-text-primary antialiased;
|
||||
font-family: var(--font-sans);
|
||||
}
|
||||
|
||||
h1, h2, h3, h4, h5, h6 {
|
||||
@apply font-bold tracking-tight text-text-dark;
|
||||
}
|
||||
}
|
||||
|
||||
@layer components {
|
||||
.premium-card {
|
||||
@apply bg-white rounded-[2rem] border border-border shadow-sm transition-all duration-500 hover:shadow-xl hover:shadow-primary/5 hover:-translate-y-1;
|
||||
}
|
||||
|
||||
.glass-effect {
|
||||
@apply bg-white/80 backdrop-blur-md border border-white/20;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
@apply bg-primary text-white px-6 py-3 rounded-2xl font-bold transition-all duration-300 hover:bg-[#4a0a38] hover:scale-105 active:scale-95 shadow-lg shadow-primary/20;
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
@apply bg-white text-text-primary px-6 py-3 rounded-2xl font-bold border-2 border-border transition-all duration-300 hover:bg-gray-50 hover:border-primary/20;
|
||||
}
|
||||
}
|
||||
|
||||
/* Custom Scrollbar Override for v4 */
|
||||
* {
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: var(--color-border) transparent;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar {
|
||||
width: 5px;
|
||||
height: 5px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb {
|
||||
background-color: var(--color-border);
|
||||
border-radius: 100px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb:hover {
|
||||
background-color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
/* Animations */
|
||||
@keyframes slideUp {
|
||||
from { opacity: 0; transform: translateY(20px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
|
||||
.animate-slideUp {
|
||||
animation: slideUp 0.6s cubic-bezier(0.16, 1, 0.3, 1) forwards;
|
||||
}
|
||||
|
||||
/* Chart Tooltip Customization (v4 compatibility) */
|
||||
.recharts-default-tooltip {
|
||||
background-color: rgba(255, 255, 255, 0.95) !important;
|
||||
backdrop-filter: blur(8px) !important;
|
||||
border: 1px solid var(--color-border) !important;
|
||||
border-radius: 1rem !important;
|
||||
box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1) !important;
|
||||
padding: 1rem !important;
|
||||
}
|
||||
|
||||
.recharts-tooltip-label {
|
||||
font-size: 0.7rem !important;
|
||||
font-weight: 900 !important;
|
||||
color: var(--color-text-muted) !important;
|
||||
text-transform: uppercase !important;
|
||||
letter-spacing: 0.1em !important;
|
||||
margin-bottom: 0.5rem !important;
|
||||
}
|
||||
|
||||
.recharts-tooltip-item {
|
||||
color: var(--color-primary) !important;
|
||||
font-weight: 800 !important;
|
||||
font-size: 0.85rem !important;
|
||||
}
|
||||
10
frontend/src/main.tsx
Normal file
@@ -0,0 +1,10 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import './index.css'
|
||||
import App from './App.tsx'
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
)
|
||||
432
frontend/src/pages/ArchivedOrders.tsx
Normal file
@@ -0,0 +1,432 @@
|
||||
import React, { useState, useEffect, useMemo } from 'react';
|
||||
import {
|
||||
Search,
|
||||
Calendar,
|
||||
Filter,
|
||||
CreditCard,
|
||||
User,
|
||||
ShoppingBag,
|
||||
MoreVertical,
|
||||
RefreshCw,
|
||||
Archive,
|
||||
RotateCcw,
|
||||
CheckCircle,
|
||||
Clock,
|
||||
ArrowLeft
|
||||
} from 'lucide-react';
|
||||
import { format, subDays } from 'date-fns';
|
||||
import Pagination from '../components/Pagination';
|
||||
|
||||
interface OrderItem {
|
||||
id?: number;
|
||||
productName: string;
|
||||
quantity: number;
|
||||
price: number;
|
||||
productId: number;
|
||||
}
|
||||
|
||||
interface UserData {
|
||||
name: string;
|
||||
mobileNumber: string;
|
||||
}
|
||||
|
||||
interface Order {
|
||||
id: number;
|
||||
orderNumber: string;
|
||||
displayOrderId: string;
|
||||
totalAmount: number;
|
||||
status: string;
|
||||
paymentMethod: string;
|
||||
createdAt: string;
|
||||
user: UserData;
|
||||
items: OrderItem[];
|
||||
}
|
||||
|
||||
const ArchivedOrders: React.FC = () => {
|
||||
const [orders, setOrders] = useState<Order[]>([]);
|
||||
const [selectedOrder, setSelectedOrder] = useState<Order | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [statusFilter, setStatusFilter] = useState('');
|
||||
const [paymentFilter, setPaymentFilter] = useState('');
|
||||
|
||||
// Default to showing yesterday's orders in the archive view
|
||||
const [startDate, setStartDate] = useState(format(subDays(new Date(), 30), 'yyyy-MM-dd'));
|
||||
const [endDate, setEndDate] = useState(format(subDays(new Date(), 1), 'yyyy-MM-dd'));
|
||||
|
||||
// Pagination States
|
||||
const [currentPage, setCurrentPage] = useState(0);
|
||||
const [pageSize, setPageSize] = useState(10);
|
||||
const [totalElements, setTotalElements] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
fetchArchivedOrders();
|
||||
}, [startDate, endDate, statusFilter, paymentFilter, currentPage, pageSize]);
|
||||
|
||||
const fetchArchivedOrders = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const params = new URLSearchParams();
|
||||
params.append('archived', 'true'); // Explicitly request archived orders
|
||||
if (startDate) params.append('startDate', `${startDate}T00:00:00`);
|
||||
if (endDate) params.append('endDate', `${endDate}T23:59:59`);
|
||||
if (statusFilter) params.append('status', statusFilter);
|
||||
if (paymentFilter) params.append('paymentType', paymentFilter);
|
||||
if (searchQuery) params.append('search', searchQuery);
|
||||
params.append('page', currentPage.toString());
|
||||
params.append('size', pageSize.toString());
|
||||
|
||||
const response = await fetch(`http://${window.location.hostname}:8080/api/orders/all?${params.toString()}`);
|
||||
const data = await response.json();
|
||||
|
||||
if (data && data.content && Array.isArray(data.content)) {
|
||||
setOrders(data.content);
|
||||
setTotalElements(data.totalElements);
|
||||
if (data.content.length > 0) {
|
||||
setSelectedOrder(data.content[0]);
|
||||
} else {
|
||||
setSelectedOrder(null);
|
||||
}
|
||||
} else {
|
||||
setOrders([]);
|
||||
setTotalElements(0);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error fetching archived orders:', error);
|
||||
setOrders([]);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSearchSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
fetchArchivedOrders();
|
||||
};
|
||||
|
||||
const getStatusColor = (status: string) => {
|
||||
switch (status.toUpperCase()) {
|
||||
case 'COMPLETED': return 'bg-emerald-50 text-emerald-600 border-emerald-100';
|
||||
case 'PAID': return 'bg-indigo-50 text-indigo-600 border-indigo-100';
|
||||
case 'PENDING': return 'bg-amber-50 text-amber-600 border-amber-100';
|
||||
case 'CANCELLED': return 'bg-rose-50 text-rose-600 border-rose-100';
|
||||
default: return 'bg-slate-50 text-slate-600 border-slate-100';
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-[calc(100vh-64px)] bg-[#f8fafc] animate-in fade-in duration-500">
|
||||
{/* Top Filter Bar */}
|
||||
<div className="bg-white border-b border-slate-200 p-4 sticky top-0 z-10 shadow-sm">
|
||||
<form onSubmit={handleSearchSubmit} className="flex flex-wrap items-center gap-4 max-w-[1600px] mx-auto">
|
||||
<div className="flex items-center gap-3 mr-4">
|
||||
<div className="w-10 h-10 bg-slate-900 rounded-xl flex items-center justify-center text-white shadow-lg shadow-slate-200">
|
||||
<Archive size={20} />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-lg font-black text-slate-900 leading-none">Archived Bills</h1>
|
||||
<p className="text-[10px] text-slate-400 font-bold uppercase tracking-widest mt-1">Transaction History</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center bg-slate-50 border border-slate-200 rounded-lg px-3 py-2 gap-2 focus-within:border-slate-400 transition-all">
|
||||
<Calendar size={18} className="text-slate-400" />
|
||||
<input
|
||||
type="date"
|
||||
className="bg-transparent border-none text-sm font-medium text-slate-700 outline-none"
|
||||
value={startDate}
|
||||
onChange={(e) => setStartDate(e.target.value)}
|
||||
/>
|
||||
<span className="text-slate-300">to</span>
|
||||
<input
|
||||
type="date"
|
||||
className="bg-transparent border-none text-sm font-medium text-slate-700 outline-none"
|
||||
value={endDate}
|
||||
onChange={(e) => setEndDate(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center bg-slate-50 border border-slate-200 rounded-lg px-3 py-2 gap-2 min-w-[140px]">
|
||||
<Filter size={18} className="text-slate-400" />
|
||||
<select
|
||||
className="bg-transparent border-none text-sm font-medium text-slate-700 outline-none w-full cursor-pointer"
|
||||
value={statusFilter}
|
||||
onChange={(e) => setStatusFilter(e.target.value)}
|
||||
>
|
||||
<option value="">All Status</option>
|
||||
<option value="PAID">Paid</option>
|
||||
<option value="COMPLETED">Completed</option>
|
||||
<option value="CANCELLED">Cancelled</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 flex items-center bg-slate-50 border border-slate-200 rounded-lg px-4 py-2 gap-3 focus-within:bg-white focus-within:border-slate-400 transition-all shadow-inner">
|
||||
<Search size={18} className="text-slate-400" />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Search history by ID, Name or Mobile..."
|
||||
className="bg-transparent border-none text-sm w-full outline-none text-slate-700 placeholder:text-slate-400"
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
className="bg-slate-900 hover:bg-black text-white rounded-lg px-6 py-2 text-sm font-semibold transition-all shadow-md flex items-center gap-2 active:scale-95"
|
||||
>
|
||||
Search Archives
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
{/* Main Content Area */}
|
||||
<div className="flex-1 overflow-hidden flex max-w-[1800px] mx-auto w-full p-4 gap-4">
|
||||
{/* Left Column: Archived List */}
|
||||
<div className="w-[400px] flex flex-col gap-3 overflow-y-auto pr-2 custom-scrollbar pb-4">
|
||||
{loading ? (
|
||||
<div className="flex items-center justify-center p-12 text-slate-400 gap-2">
|
||||
<RefreshCw className="animate-spin" size={20} />
|
||||
<span>Scanning archives...</span>
|
||||
</div>
|
||||
) : orders.length === 0 ? (
|
||||
<div className="bg-white rounded-xl border border-slate-200 p-12 text-center shadow-sm">
|
||||
<Archive size={48} className="mx-auto text-slate-100 mb-4" />
|
||||
<h3 className="text-slate-600 font-semibold mb-1">No archived bills recorded</h3>
|
||||
<p className="text-slate-400 text-sm">Try expanding the date range</p>
|
||||
</div>
|
||||
) : (
|
||||
orders.map((order) => (
|
||||
<div
|
||||
key={order.id}
|
||||
onClick={() => setSelectedOrder(order)}
|
||||
className={`group relative bg-white border rounded-xl p-4 cursor-pointer transition-all hover:shadow-lg active:scale-[0.98] ${
|
||||
selectedOrder?.id === order.id
|
||||
? 'border-slate-900 ring-1 ring-slate-900 shadow-md'
|
||||
: 'border-slate-200 hover:border-slate-400'
|
||||
}`}
|
||||
>
|
||||
<div className="flex justify-between items-start mb-3">
|
||||
<div className={`px-2.5 py-0.5 rounded-full text-[10px] font-bold tracking-wider uppercase border opacity-70 ${getStatusColor(order.status)}`}>
|
||||
{order.status}
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<div className="text-[10px] text-slate-400 font-medium uppercase mb-0.5">Grand Total</div>
|
||||
<div className="text-lg font-black text-slate-900 leading-none">₹{order.totalAmount.toFixed(2)}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-end justify-between">
|
||||
<div>
|
||||
<div className="text-xs text-slate-400 font-medium mb-1 tracking-wider uppercase">Order #</div>
|
||||
<div className="text-2xl font-black text-slate-800 leading-none tracking-tight">#{order.displayOrderId}</div>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<div className="text-xs font-bold text-slate-700 mb-1">
|
||||
{order.user?.name || 'Anonymous User'}
|
||||
</div>
|
||||
<div className="text-[10px] text-slate-400 font-medium flex items-center justify-end gap-1">
|
||||
<Clock size={10} />
|
||||
{format(new Date(order.createdAt), 'dd MMMM yyyy')}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{selectedOrder?.id === order.id && (
|
||||
<div className="absolute left-0 top-0 bottom-0 w-1 bg-slate-900 rounded-l-xl" />
|
||||
)}
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
|
||||
<Pagination
|
||||
currentPage={currentPage}
|
||||
pageSize={pageSize}
|
||||
totalElements={totalElements}
|
||||
onPageChange={setCurrentPage}
|
||||
onPageSizeChange={(newSize) => {
|
||||
setPageSize(newSize);
|
||||
setCurrentPage(0);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Right Column: Order Details */}
|
||||
<div className="flex-1 bg-white border border-slate-200 rounded-2xl flex flex-col shadow-sm overflow-hidden relative mb-4">
|
||||
{selectedOrder ? (
|
||||
<>
|
||||
{/* Order Detail Header */}
|
||||
<div className="p-6 border-b border-slate-100 flex justify-between items-center bg-slate-50/50 sticky top-0 z-10">
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="bg-slate-900 p-3 rounded-xl text-white shadow-lg shadow-slate-200">
|
||||
<Archive size={24} />
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="text-2xl font-black text-slate-900 flex items-center gap-2 tracking-tight uppercase">
|
||||
Archived Receipt #{selectedOrder.displayOrderId}
|
||||
</h2>
|
||||
<p className="text-xs text-slate-400 font-black tracking-[0.2em] uppercase">Security ID: {selectedOrder.orderNumber}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="text-right mr-3">
|
||||
<div className="text-[10px] text-slate-400 font-black uppercase tracking-widest leading-none mb-1">Issued Date</div>
|
||||
<div className="text-xs font-bold text-slate-700">{format(new Date(selectedOrder.createdAt), 'EEEE, MMMM dd yyyy')}</div>
|
||||
</div>
|
||||
<div className={`px-4 py-1.5 rounded-lg text-xs font-black uppercase border shadow-sm ${getStatusColor(selectedOrder.status)}`}>
|
||||
{selectedOrder.status}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Content Scroll Area */}
|
||||
<div className="flex-1 overflow-y-auto p-8 custom-scrollbar">
|
||||
<div className="grid grid-cols-2 gap-8 mb-12">
|
||||
<div className="p-6 rounded-2xl border border-slate-100 bg-slate-50 flex items-center gap-6">
|
||||
<div className="w-14 h-14 bg-white rounded-xl shadow-sm flex items-center justify-center text-slate-400">
|
||||
<User size={28} />
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-[10px] text-slate-400 uppercase font-black tracking-widest mb-1">Customer Info</div>
|
||||
<div className="text-lg font-black text-slate-800 leading-none mb-1">{selectedOrder.user?.name || 'Walk-in Customer'}</div>
|
||||
<div className="text-xs font-bold text-slate-400">{selectedOrder.user?.mobileNumber || 'No Contact Data'}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="p-6 rounded-2xl border border-slate-100 bg-slate-50 flex items-center gap-6">
|
||||
<div className="w-14 h-14 bg-white rounded-xl shadow-sm flex items-center justify-center text-indigo-500">
|
||||
<CreditCard size={28} />
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-[10px] text-slate-400 uppercase font-black tracking-widest mb-1">Payment Method</div>
|
||||
<div className="text-lg font-black text-slate-800 leading-none mb-1">{selectedOrder.paymentMethod.toUpperCase()}</div>
|
||||
<div className="text-xs font-bold text-emerald-500 flex items-center gap-1"><CheckCircle size={10} /> Verified Record</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="flex justify-between items-center border-b border-slate-100 pb-3">
|
||||
<h3 className="text-[10px] font-black text-slate-400 uppercase tracking-[0.2em]">Archived Line Items</h3>
|
||||
<h3 className="text-[10px] font-black text-slate-400 uppercase tracking-[0.2em]">Value</h3>
|
||||
</div>
|
||||
|
||||
<div className="divide-y divide-slate-50">
|
||||
{selectedOrder.items.map((item, idx) => (
|
||||
<div key={idx} className="py-5 flex justify-between items-center group hover:bg-slate-50/50 transition-colors rounded-lg -mx-2 px-2">
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="w-10 h-10 bg-slate-100 rounded-lg flex items-center justify-center text-slate-400 font-bold text-xs uppercase group-hover:bg-slate-900 group-hover:text-white transition-colors">
|
||||
{item.productName.substring(0, 2)}
|
||||
</div>
|
||||
<div>
|
||||
<div className="font-black text-slate-800 text-sm italic">{item.productName}</div>
|
||||
<div className="text-[10px] text-slate-400 font-bold tracking-widest uppercase">Qty: {item.quantity} Unit(s)</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<div className="text-sm font-black text-slate-900">₹{(item.price * item.quantity).toLocaleString()}</div>
|
||||
<div className="text-[10px] font-bold text-slate-400 uppercase tracking-tighter">@ ₹{item.price}</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Bottom Totals Summary */}
|
||||
<div className="bg-slate-900 p-8 text-white">
|
||||
<div className="flex justify-between">
|
||||
<div className="flex gap-12">
|
||||
<div>
|
||||
<div className="text-[10px] text-slate-500 uppercase font-black tracking-widest mb-2">Unique Items</div>
|
||||
<div className="text-2xl font-black">{selectedOrder.items.length}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-[10px] text-slate-500 uppercase font-black tracking-widest mb-2">Record Status</div>
|
||||
<div className="text-xs font-black px-3 py-1 bg-white/10 rounded-full border border-white/20 inline-flex items-center gap-2 uppercase">
|
||||
<Clock size={12} /> Closed File
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-right flex flex-col gap-1 min-w-[250px]">
|
||||
<div className="text-[10px] text-slate-500 uppercase font-black tracking-widest mb-1">Final Settlement</div>
|
||||
<div className="text-4xl font-black text-emerald-400 leading-none mb-1">₹{selectedOrder.totalAmount.toLocaleString()}</div>
|
||||
<div className="text-[10px] text-slate-500 font-bold uppercase tracking-[0.2em]">Transaction Fully Reconciled</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-8 pt-8 border-t border-white/10 flex justify-between items-center">
|
||||
<p className="text-[9px] text-slate-500 uppercase font-bold tracking-widest max-w-sm">This is a permanent historical record. Modifications are disabled for archived data to maintain audit integrity.</p>
|
||||
<button
|
||||
onClick={() => window.print()}
|
||||
className="px-8 py-3 bg-white text-slate-900 rounded-xl font-black text-xs uppercase tracking-widest hover:bg-slate-200 transition-all active:scale-[0.98] flex items-center gap-2 shadow-xl"
|
||||
>
|
||||
Print Copy <ShoppingBag size={14} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div className="flex-1 flex flex-col items-center justify-center p-12 text-center text-slate-400">
|
||||
<div className="bg-slate-50 p-6 rounded-full mb-6">
|
||||
<Archive size={48} className="text-slate-100" />
|
||||
</div>
|
||||
<h3 className="text-slate-600 font-bold text-lg mb-2">Select a historical file</h3>
|
||||
<p className="max-w-xs mx-auto text-sm italic font-medium">Browse through your previous days' turnover by selecting an entry from the ledger on the left.</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>{`
|
||||
.custom-scrollbar::-webkit-scrollbar {
|
||||
width: 5px;
|
||||
}
|
||||
.custom-scrollbar::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
.custom-scrollbar::-webkit-scrollbar-thumb {
|
||||
background: #e2e8f0;
|
||||
border-radius: 10px;
|
||||
}
|
||||
.custom-scrollbar::-webkit-scrollbar-thumb:hover {
|
||||
background: #cbd5e1;
|
||||
}
|
||||
|
||||
@media print {
|
||||
body * {
|
||||
visibility: hidden;
|
||||
}
|
||||
.flex-1.bg-white.border.border-slate-200.rounded-2xl,
|
||||
.flex-1.bg-white.border.border-slate-200.rounded-2xl * {
|
||||
visibility: visible;
|
||||
}
|
||||
.flex-1.bg-white.border.border-slate-200.rounded-2xl {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
top: 0;
|
||||
width: 100%;
|
||||
border: none !important;
|
||||
box-shadow: none !important;
|
||||
}
|
||||
button,
|
||||
.sticky {
|
||||
display: none !important;
|
||||
}
|
||||
.bg-slate-900 {
|
||||
background-color: #f1f5f9 !important;
|
||||
color: #000 !important;
|
||||
}
|
||||
.text-emerald-400 {
|
||||
color: #059669 !important;
|
||||
}
|
||||
.text-slate-500 {
|
||||
color: #64748b !important;
|
||||
}
|
||||
}
|
||||
`}</style>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ArchivedOrders;
|
||||
400
frontend/src/pages/BaseMenu.tsx
Normal file
@@ -0,0 +1,400 @@
|
||||
import React, { useState, useEffect, useRef } from 'react';
|
||||
import { Plus, X, Search, Filter, MoreVertical, RefreshCw, Edit2, Power, PowerOff, ShoppingCart, Package, ExternalLink } from 'lucide-react';
|
||||
|
||||
interface BaseItem {
|
||||
id: number;
|
||||
name: string;
|
||||
description: string;
|
||||
active: boolean;
|
||||
}
|
||||
|
||||
interface Product {
|
||||
id: number;
|
||||
name: string;
|
||||
price: number;
|
||||
category: string;
|
||||
active: boolean;
|
||||
}
|
||||
|
||||
const BaseMenu = () => {
|
||||
const [items, setItems] = useState<BaseItem[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [showModal, setShowModal] = useState(false);
|
||||
const [editingItem, setEditingItem] = useState<BaseItem | null>(null);
|
||||
const [newItem, setNewItem] = useState({ name: '', description: '', active: true });
|
||||
const [openMenuId, setOpenMenuId] = useState<number | null>(null);
|
||||
|
||||
// Associated Products State
|
||||
const [selectedBaseItem, setSelectedBaseItem] = useState<BaseItem | null>(null);
|
||||
const [associatedProducts, setAssociatedProducts] = useState<Product[]>([]);
|
||||
const [productsLoading, setProductsLoading] = useState(false);
|
||||
const [showProductsModal, setShowProductsModal] = useState(false);
|
||||
|
||||
const menuRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
fetchItems();
|
||||
|
||||
const handleClickOutside = (event: MouseEvent) => {
|
||||
if (menuRef.current && !menuRef.current.contains(event.target as Node)) {
|
||||
setOpenMenuId(null);
|
||||
}
|
||||
};
|
||||
document.addEventListener('mousedown', handleClickOutside);
|
||||
return () => document.removeEventListener('mousedown', handleClickOutside);
|
||||
}, []);
|
||||
|
||||
const fetchItems = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const response = await fetch('http://localhost:8080/api/base-items');
|
||||
const data = await response.json();
|
||||
setItems(data);
|
||||
} catch (error) {
|
||||
console.error('Error fetching items:', error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const fetchAssociatedProducts = async (baseItem: BaseItem) => {
|
||||
setSelectedBaseItem(baseItem);
|
||||
setShowProductsModal(true);
|
||||
setProductsLoading(true);
|
||||
try {
|
||||
const response = await fetch(`http://localhost:8080/api/products/category/${encodeURIComponent(baseItem.name)}`);
|
||||
const data = await response.json();
|
||||
setAssociatedProducts(data);
|
||||
} catch (error) {
|
||||
console.error('Error fetching associated products:', error);
|
||||
} finally {
|
||||
setProductsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
const url = editingItem
|
||||
? `http://localhost:8080/api/base-items/${editingItem.id}`
|
||||
: 'http://localhost:8080/api/base-items';
|
||||
const method = editingItem ? 'PUT' : 'POST';
|
||||
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
method,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(newItem),
|
||||
});
|
||||
if (response.ok) {
|
||||
setShowModal(false);
|
||||
setEditingItem(null);
|
||||
setNewItem({ name: '', description: '', active: true });
|
||||
fetchItems();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error saving item:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleEdit = (item: BaseItem) => {
|
||||
setEditingItem(item);
|
||||
setNewItem({ name: item.name, description: item.description, active: item.active });
|
||||
setShowModal(true);
|
||||
setOpenMenuId(null);
|
||||
};
|
||||
|
||||
const handleToggleActive = async (item: BaseItem) => {
|
||||
try {
|
||||
const response = await fetch(`http://localhost:8080/api/base-items/${item.id}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ ...item, active: !item.active }),
|
||||
});
|
||||
if (response.ok) {
|
||||
fetchItems();
|
||||
setOpenMenuId(null);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error toggling active status:', error);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="p-8 font-inter">
|
||||
<div className="flex justify-between items-center mb-8">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-[#1e293b]">Base Items</h1>
|
||||
<p className="text-sm text-[#64748b]">Manage your base inventory items</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => {
|
||||
setEditingItem(null);
|
||||
setNewItem({ name: '', description: '', active: true });
|
||||
setShowModal(true);
|
||||
}}
|
||||
className="bg-[#231651] text-white px-4 py-2 rounded-xl flex items-center gap-2 shadow-lg shadow-[#231651]/20 hover:scale-[1.02] active:scale-95 transition-all"
|
||||
>
|
||||
<Plus size={20} />
|
||||
<span>Add New Item</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Filters Bar */}
|
||||
<div className="bg-white p-4 rounded-xl border border-[#e2e8f0] mb-6 flex flex-wrap gap-4 items-center justify-between shadow-sm">
|
||||
<div className="flex gap-4 items-center flex-1">
|
||||
<div className="relative flex-1 max-w-md">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 text-[#94a3b8]" size={18} />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Search items..."
|
||||
className="w-full pl-10 pr-4 py-2 bg-gray-50 border border-[#e2e8f0] rounded-lg text-sm focus:outline-none focus:border-[#231651]/30 transition-all"
|
||||
/>
|
||||
</div>
|
||||
<button className="flex items-center gap-2 px-3 py-2 border border-[#e2e8f0] rounded-lg text-sm text-[#64748b] hover:bg-gray-50 transition-all">
|
||||
<Filter size={16} />
|
||||
<span>Filter</span>
|
||||
</button>
|
||||
</div>
|
||||
<button onClick={fetchItems} className="p-2 text-[#64748b] hover:bg-gray-100 rounded-lg transition-all">
|
||||
<RefreshCw size={18} className={loading ? 'animate-spin' : ''} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Table */}
|
||||
<div className="bg-white rounded-xl border border-[#e2e8f0] shadow-sm overflow-hidden">
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-left border-collapse">
|
||||
<thead>
|
||||
<tr className="bg-gray-50/50 border-b border-[#e2e8f0]">
|
||||
<th className="px-6 py-4 text-xs font-bold text-[#64748b] uppercase tracking-wider">ID</th>
|
||||
<th className="px-6 py-4 text-xs font-bold text-[#64748b] uppercase tracking-wider">Item Name</th>
|
||||
<th className="px-6 py-4 text-xs font-bold text-[#64748b] uppercase tracking-wider">Description</th>
|
||||
<th className="px-6 py-4 text-xs font-bold text-[#64748b] uppercase tracking-wider text-center">Products</th>
|
||||
<th className="px-6 py-4 text-xs font-bold text-[#64748b] uppercase tracking-wider">Status</th>
|
||||
<th className="px-6 py-4 text-xs font-bold text-[#64748b] uppercase tracking-wider text-right">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-[#e2e8f0]">
|
||||
{loading ? (
|
||||
<tr>
|
||||
<td colSpan={6} className="px-6 py-12 text-center text-[#64748b]">
|
||||
<div className="flex flex-col items-center gap-3">
|
||||
<RefreshCw className="animate-spin" size={24} />
|
||||
<p>Loading items...</p>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
) : items.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={6} className="px-6 py-12 text-center text-[#64748b]">
|
||||
<p className="text-lg font-medium mb-1">No items found</p>
|
||||
<p className="text-sm">Click "Add New Item" to create your first item.</p>
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
items.map((item) => (
|
||||
<tr key={item.id} className="hover:bg-gray-50/50 transition-all group">
|
||||
<td className="px-6 py-4 text-sm font-medium text-[#64748b]">#{item.id}</td>
|
||||
<td className="px-6 py-4">
|
||||
<span className="text-sm font-bold text-[#1e293b]">{item.name}</span>
|
||||
</td>
|
||||
<td className="px-6 py-4 text-sm text-[#64748b] max-w-xs truncate">{item.description}</td>
|
||||
<td className="px-6 py-4 text-center">
|
||||
<button
|
||||
onClick={() => fetchAssociatedProducts(item)}
|
||||
className="p-2 text-[#231651] bg-[#231651]/5 hover:bg-[#231651]/10 rounded-xl transition-all"
|
||||
title="View Associated Products"
|
||||
>
|
||||
<ShoppingCart size={18} />
|
||||
</button>
|
||||
</td>
|
||||
<td className="px-6 py-4">
|
||||
<span className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-bold ${
|
||||
item.active
|
||||
? 'bg-green-100 text-green-700'
|
||||
: 'bg-gray-100 text-gray-600'
|
||||
}`}>
|
||||
<div className={`w-1.5 h-1.5 rounded-full ${item.active ? 'bg-green-500' : 'bg-gray-400'}`} />
|
||||
{item.active ? 'Active' : 'Inactive'}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-6 py-4 text-right relative">
|
||||
<button
|
||||
onClick={() => setOpenMenuId(openMenuId === item.id ? null : item.id)}
|
||||
className="p-1.5 text-[#94a3b8] hover:text-[#231651] hover:bg-[#231651]/5 rounded-lg transition-all"
|
||||
>
|
||||
<MoreVertical size={18} />
|
||||
</button>
|
||||
|
||||
{openMenuId === item.id && (
|
||||
<div
|
||||
ref={menuRef}
|
||||
className="absolute right-6 top-12 w-48 bg-white rounded-xl shadow-xl border border-[#e2e8f0] z-[60] overflow-hidden animate-in fade-in slide-in-from-top-2 duration-200"
|
||||
>
|
||||
<button
|
||||
onClick={() => handleEdit(item)}
|
||||
className="w-full flex items-center gap-3 px-4 py-3 text-sm text-[#475569] hover:bg-gray-50 hover:text-[#231651] transition-all"
|
||||
>
|
||||
<Edit2 size={16} />
|
||||
<span className="font-semibold">Edit Item</span>
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleToggleActive(item)}
|
||||
className="w-full flex items-center gap-3 px-4 py-3 text-sm text-[#475569] hover:bg-gray-50 hover:text-[#231651] transition-all border-t border-[#e2e8f0]/50"
|
||||
>
|
||||
{item.active ? (
|
||||
<>
|
||||
<PowerOff size={16} className="text-red-500" />
|
||||
<span className="font-semibold">Mark as Inactive</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Power size={16} className="text-green-500" />
|
||||
<span className="font-semibold">Mark as Active</span>
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Associated Products Modal */}
|
||||
{showProductsModal && (
|
||||
<div className="fixed inset-0 bg-black/50 backdrop-blur-sm z-[100] flex items-center justify-center p-4">
|
||||
<div className="bg-white rounded-3xl w-full max-w-2xl shadow-2xl overflow-hidden animate-in fade-in zoom-in duration-200">
|
||||
<div className="px-8 py-6 border-b border-[#e2e8f0] flex justify-between items-center bg-gray-50/50">
|
||||
<div>
|
||||
<h2 className="text-xl font-bold text-[#1e293b]">Products for: {selectedBaseItem?.name}</h2>
|
||||
<p className="text-xs text-[#64748b] mt-0.5">Showing all associated products in this category</p>
|
||||
</div>
|
||||
<button onClick={() => setShowProductsModal(false)} className="p-2 hover:bg-gray-200 rounded-full transition-all">
|
||||
<X size={24} className="text-[#64748b]" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="p-8 max-h-[60vh] overflow-y-auto">
|
||||
{productsLoading ? (
|
||||
<div className="flex flex-col items-center py-12 text-[#64748b]">
|
||||
<RefreshCw className="animate-spin mb-4" size={32} />
|
||||
<p className="font-medium">Fetching associated products...</p>
|
||||
</div>
|
||||
) : associatedProducts.length === 0 ? (
|
||||
<div className="flex flex-col items-center py-12 text-center">
|
||||
<div className="w-16 h-16 bg-gray-100 rounded-2xl flex items-center justify-center text-[#94a3b8] mb-4">
|
||||
<Package size={32} />
|
||||
</div>
|
||||
<h3 className="text-lg font-bold text-[#1e293b]">No Products Found</h3>
|
||||
<p className="text-sm text-[#64748b] mt-1 max-w-xs">There are no products currently linked to the "{selectedBaseItem?.name}" category.</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{associatedProducts.map(product => (
|
||||
<div key={product.id} className="flex items-center justify-between p-4 bg-gray-50 rounded-2xl border border-[#e2e8f0] hover:border-[#231651]/20 transition-all group">
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="w-12 h-12 bg-white rounded-xl flex items-center justify-center text-[#231651] shadow-sm group-hover:scale-105 transition-transform">
|
||||
<Package size={24} />
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-bold text-[#1e293b]">{product.name}</p>
|
||||
<span className={`text-[10px] font-bold uppercase tracking-wider px-2 py-0.5 rounded ${product.active ? 'text-green-600 bg-green-100' : 'text-gray-500 bg-gray-200'}`}>
|
||||
{product.active ? 'Active' : 'Inactive'}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<p className="text-lg font-bold text-[#231651]">₹{product.price}</p>
|
||||
<p className="text-[10px] text-[#64748b] font-medium">Sale Price</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="px-8 py-6 bg-gray-50/50 border-t border-[#e2e8f0] flex justify-end">
|
||||
<button
|
||||
onClick={() => setShowProductsModal(false)}
|
||||
className="px-6 py-2.5 bg-[#231651] text-white font-bold rounded-xl shadow-lg shadow-[#231651]/20 hover:scale-[1.02] active:scale-95 transition-all flex items-center gap-2"
|
||||
>
|
||||
Close View
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Standard Modal (Add/Edit) */}
|
||||
{showModal && (
|
||||
<div className="fixed inset-0 bg-black/50 backdrop-blur-sm z-[100] flex items-center justify-center p-4">
|
||||
<div className="bg-white rounded-2xl w-full max-w-md shadow-2xl overflow-hidden animate-in fade-in zoom-in duration-200">
|
||||
<div className="px-6 py-4 border-b border-[#e2e8f0] flex justify-between items-center bg-gray-50/50">
|
||||
<h2 className="text-lg font-bold text-[#1e293b]">
|
||||
{editingItem ? 'Edit Base Item' : 'Add New Base Item'}
|
||||
</h2>
|
||||
<button onClick={() => setShowModal(false)} className="p-1 hover:bg-gray-200 rounded-lg transition-all">
|
||||
<X size={20} className="text-[#64748b]" />
|
||||
</button>
|
||||
</div>
|
||||
<form onSubmit={handleSubmit} className="p-6 space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm font-bold text-[#475569] mb-1.5">Item Name</label>
|
||||
<input
|
||||
required
|
||||
type="text"
|
||||
value={newItem.name}
|
||||
onChange={(e) => setNewItem({ ...newItem, name: e.target.value })}
|
||||
placeholder="e.g. Fresh Tomato"
|
||||
className="w-full px-4 py-2.5 border border-[#e2e8f0] rounded-xl focus:outline-none focus:border-[#231651] focus:ring-1 focus:ring-[#231651] transition-all text-sm"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-bold text-[#475569] mb-1.5">Description</label>
|
||||
<textarea
|
||||
value={newItem.description}
|
||||
onChange={(e) => setNewItem({ ...newItem, description: e.target.value })}
|
||||
placeholder="Tell us more about this item..."
|
||||
rows={3}
|
||||
className="w-full px-4 py-2.5 border border-[#e2e8f0] rounded-xl focus:outline-none focus:border-[#231651] focus:ring-1 focus:ring-[#231651] transition-all text-sm resize-none"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center gap-3 py-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setNewItem({ ...newItem, active: !newItem.active })}
|
||||
className={`w-11 h-6 rounded-full transition-all relative ${newItem.active ? 'bg-[#231651]' : 'bg-gray-300'}`}
|
||||
>
|
||||
<div className={`absolute top-1 left-1 w-4 h-4 bg-white rounded-full transition-transform ${newItem.active ? 'translate-x-5' : ''}`} />
|
||||
</button>
|
||||
<span className="text-sm font-semibold text-[#1e293b]">Mark as Active</span>
|
||||
</div>
|
||||
<div className="pt-4 flex gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowModal(false)}
|
||||
className="flex-1 px-4 py-2.5 border border-[#e2e8f0] text-[#64748b] font-bold rounded-xl hover:bg-gray-50 transition-all text-sm"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
className="flex-1 px-4 py-2.5 bg-[#231651] text-white font-bold rounded-xl shadow-lg shadow-[#231651]/20 hover:scale-[1.02] active:scale-95 transition-all text-sm"
|
||||
>
|
||||
{editingItem ? 'Update Item' : 'Save Item'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default BaseMenu;
|
||||
331
frontend/src/pages/Bills.tsx
Normal file
@@ -0,0 +1,331 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Search, ChevronRight, Filter, Loader2, Download, Printer, X } from 'lucide-react';
|
||||
import { format } from 'date-fns';
|
||||
|
||||
interface PurchaseOrder {
|
||||
id: number;
|
||||
purchaseId: string;
|
||||
date: string;
|
||||
vendor: { id: number; name: string };
|
||||
amount: number;
|
||||
paidTotal: number;
|
||||
status: string;
|
||||
referenceId: string;
|
||||
}
|
||||
|
||||
const Bills: React.FC = () => {
|
||||
const [orders, setOrders] = useState<PurchaseOrder[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [statusFilter, setStatusFilter] = useState('All');
|
||||
const [searchTerm, setSearchTerm] = useState('');
|
||||
|
||||
const [selectedOrder, setSelectedOrder] = useState<PurchaseOrder | null>(null);
|
||||
const [showPayModal, setShowPayModal] = useState(false);
|
||||
const [paymentAmount, setPaymentAmount] = useState<number>(0);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
fetchOrders();
|
||||
}, []);
|
||||
|
||||
const fetchOrders = async () => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
const response = await fetch('/api/purchases/orders');
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
setOrders(data);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error fetching orders:', error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleRecordPayment = async () => {
|
||||
if (!selectedOrder) return;
|
||||
|
||||
try {
|
||||
setIsSaving(true);
|
||||
const updatedPaidTotal = Number(selectedOrder.paidTotal) + Number(paymentAmount);
|
||||
|
||||
const response = await fetch('/api/purchases/orders', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
...selectedOrder,
|
||||
paidTotal: updatedPaidTotal,
|
||||
status: updatedPaidTotal >= selectedOrder.amount ? 'CLOSE' : 'PARTIALLY PAID'
|
||||
}),
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
await fetchOrders();
|
||||
setShowPayModal(false);
|
||||
setSelectedOrder(null);
|
||||
setPaymentAmount(0);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error recording payment:', error);
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const filteredOrders = orders.filter(order => {
|
||||
const matchesSearch = order.purchaseId.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
order.referenceId?.toLowerCase().includes(searchTerm.toLowerCase());
|
||||
const matchesStatus = statusFilter === 'All' || order.status === statusFilter;
|
||||
return matchesSearch && matchesStatus;
|
||||
});
|
||||
|
||||
const getStatusColor = (status: string) => {
|
||||
switch (status) {
|
||||
case 'BILLED':
|
||||
return 'bg-green-100 text-green-700 border-green-200';
|
||||
case 'CLOSE':
|
||||
case 'CLOSED':
|
||||
return 'bg-red-100 text-red-700 border-red-200';
|
||||
case 'OPEN':
|
||||
return 'bg-blue-100 text-blue-700 border-blue-200';
|
||||
case 'PARTIALLY PAID':
|
||||
return 'bg-amber-100 text-amber-700 border-amber-200';
|
||||
default:
|
||||
return 'bg-slate-100 text-slate-700 border-slate-200';
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full bg-slate-50/50">
|
||||
{/* Header Section */}
|
||||
<div className="p-6 bg-white border-b border-slate-200">
|
||||
<div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-slate-900">Purchase Bills</h1>
|
||||
<p className="text-sm text-slate-500 mt-1">Manage and track your vendor payments and payables</p>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<button
|
||||
title="Download bill report"
|
||||
className="flex items-center gap-2 px-4 py-2 text-sm font-semibold text-slate-700 bg-white border border-slate-200 rounded-lg hover:bg-slate-50 transition-all shadow-sm"
|
||||
>
|
||||
<Download size={18} />
|
||||
Export
|
||||
</button>
|
||||
<button
|
||||
title="Print all bills"
|
||||
className="flex items-center gap-2 px-4 py-2 text-sm font-semibold text-white bg-indigo-600 rounded-lg hover:bg-indigo-700 transition-all shadow-md shadow-indigo-100"
|
||||
>
|
||||
<Printer size={18} />
|
||||
Print Batch
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Filters and Search */}
|
||||
<div className="flex flex-col md:flex-row md:items-center justify-between gap-4 mt-6">
|
||||
<div className="relative flex-1 max-w-md">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" size={18} />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Search by ID or Reference..."
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
title="Search through bills"
|
||||
className="w-full pl-10 pr-4 py-2 bg-slate-100 border-transparent focus:bg-white focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 rounded-xl text-sm transition-all outline-none"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="relative min-w-[160px]">
|
||||
<Filter className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" size={16} />
|
||||
<select
|
||||
value={statusFilter}
|
||||
onChange={(e) => setStatusFilter(e.target.value)}
|
||||
title="Filter by payment status"
|
||||
className="w-full pl-10 pr-4 py-2 bg-white border border-slate-200 rounded-lg text-sm appearance-none focus:outline-none focus:ring-2 focus:ring-indigo-500/20"
|
||||
>
|
||||
<option value="All">All Status</option>
|
||||
<option value="BILLED">Billed</option>
|
||||
<option value="CLOSE">Closed</option>
|
||||
<option value="OPEN">Open</option>
|
||||
<option value="PARTIALLY PAID">Partially Paid</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Table Section */}
|
||||
<div className="flex-1 overflow-auto p-6">
|
||||
<div className="bg-white rounded-2xl border border-slate-200 shadow-sm overflow-hidden">
|
||||
<table className="w-full text-left border-collapse">
|
||||
<thead>
|
||||
<tr className="bg-slate-50 border-b border-slate-200">
|
||||
<th className="px-6 py-4 text-[13px] font-bold text-slate-500 uppercase tracking-wider">Purchase ID</th>
|
||||
<th className="px-6 py-4 text-[13px] font-bold text-slate-500 uppercase tracking-wider">Date</th>
|
||||
<th className="px-6 py-4 text-[13px] font-bold text-slate-500 uppercase tracking-wider">Status</th>
|
||||
<th className="px-6 py-4 text-[13px] font-bold text-slate-500 uppercase tracking-wider text-right">Order Amount (₹)</th>
|
||||
<th className="px-6 py-4 text-[13px] font-bold text-slate-500 uppercase tracking-wider text-right">Paid Total (₹)</th>
|
||||
<th className="px-6 py-4 text-[13px] font-bold text-slate-500 uppercase tracking-wider text-right">Payables (₹)</th>
|
||||
<th className="px-6 py-4 text-[13px] font-bold text-slate-500 uppercase tracking-wider">Reference ID</th>
|
||||
<th className="px-6 py-4 text-[13px] font-bold text-slate-500 uppercase tracking-wider"></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-slate-100">
|
||||
{isLoading ? (
|
||||
<tr>
|
||||
<td colSpan={8} className="px-6 py-12 text-center text-slate-400">
|
||||
<div className="flex flex-col items-center gap-2">
|
||||
<Loader2 size={24} className="animate-spin text-indigo-500" />
|
||||
<span>Loading bills...</span>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
) : filteredOrders.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={8} className="px-6 py-12 text-center text-slate-400">
|
||||
No matching bills found
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
filteredOrders.map((order) => {
|
||||
const payables = Number(order.amount) - Number(order.paidTotal);
|
||||
return (
|
||||
<tr key={order.id} className="hover:bg-slate-50 transition-colors group">
|
||||
<td className="px-6 py-4">
|
||||
<span className="font-semibold text-slate-900">{order.purchaseId}</span>
|
||||
</td>
|
||||
<td className="px-6 py-4 text-[13px] text-slate-600">
|
||||
{order.date ? format(new Date(order.date), 'dd-MMM-yyyy hh:mm a') : '-'}
|
||||
</td>
|
||||
<td className="px-6 py-4">
|
||||
<span className={`px-3 py-1 rounded-full text-[11px] font-bold border ${getStatusColor(order.status)} uppercase`}>
|
||||
{order.status}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-6 py-4 text-[13px] font-bold text-slate-900 text-right">
|
||||
{Number(order.amount).toFixed(2)}
|
||||
</td>
|
||||
<td className="px-6 py-4 text-[13px] font-medium text-slate-600 text-right">
|
||||
{Number(order.paidTotal).toFixed(2)}
|
||||
</td>
|
||||
<td className={`px-6 py-4 text-[13px] font-bold text-right ${payables > 0 ? 'text-red-600' : 'text-green-600'}`}>
|
||||
{payables.toFixed(2)}
|
||||
</td>
|
||||
<td className="px-6 py-4 text-[13px] text-slate-500">
|
||||
{order.referenceId || '-'}
|
||||
</td>
|
||||
<td className="px-6 py-4 text-right">
|
||||
<button
|
||||
onClick={() => {
|
||||
setSelectedOrder(order);
|
||||
setPaymentAmount(payables);
|
||||
setShowPayModal(true);
|
||||
}}
|
||||
title="Record Payment"
|
||||
className="p-2 text-slate-300 hover:text-indigo-600 hover:bg-indigo-50 rounded-lg transition-all"
|
||||
>
|
||||
<ChevronRight size={20} className="group-hover:translate-x-0.5 transition-transform" />
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Payment Modal */}
|
||||
{showPayModal && selectedOrder && (
|
||||
<div className="fixed inset-0 bg-slate-900/50 backdrop-blur-sm z-50 flex items-center justify-center p-4">
|
||||
<div className="bg-white rounded-2xl shadow-2xl w-full max-w-md overflow-hidden animate-in fade-in zoom-in duration-200">
|
||||
<div className="p-6 border-b border-slate-100">
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="text-xl font-bold text-slate-900">Record Payment</h2>
|
||||
<button
|
||||
onClick={() => setShowPayModal(false)}
|
||||
className="p-2 hover:bg-slate-100 rounded-full transition-colors"
|
||||
>
|
||||
<X size={20} className="text-slate-400" />
|
||||
</button>
|
||||
</div>
|
||||
<p className="text-sm text-slate-500 mt-1">Order #{selectedOrder.purchaseId}</p>
|
||||
</div>
|
||||
|
||||
<div className="p-6 space-y-4">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="p-4 bg-slate-50 rounded-xl">
|
||||
<p className="text-[11px] font-bold text-slate-500 uppercase tracking-wider">Order Total</p>
|
||||
<p className="text-lg font-bold text-slate-900">₹{Number(selectedOrder.amount).toFixed(2)}</p>
|
||||
</div>
|
||||
<div className="p-4 bg-red-50 rounded-xl">
|
||||
<p className="text-[11px] font-bold text-red-500 uppercase tracking-wider">Remaining</p>
|
||||
<p className="text-lg font-bold text-red-600">₹{(selectedOrder.amount - selectedOrder.paidTotal).toFixed(2)}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-semibold text-slate-700">Payment Amount (₹)</label>
|
||||
<input
|
||||
type="number"
|
||||
value={paymentAmount}
|
||||
onChange={(e) => setPaymentAmount(Number(e.target.value))}
|
||||
className="w-full px-4 py-3 bg-slate-100 border-transparent focus:bg-white focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 rounded-xl text-lg font-bold outline-none transition-all"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="p-6 bg-slate-50 flex items-center gap-3">
|
||||
<button
|
||||
onClick={() => setShowPayModal(false)}
|
||||
className="flex-1 px-4 py-3 text-sm font-semibold text-slate-700 bg-white border border-slate-200 rounded-xl hover:bg-slate-50 transition-all"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
onClick={handleRecordPayment}
|
||||
disabled={isSaving || paymentAmount <= 0}
|
||||
className="flex-[2] px-8 py-3 text-sm font-semibold text-white bg-indigo-600 rounded-xl hover:bg-indigo-700 disabled:opacity-50 disabled:cursor-not-allowed transition-all shadow-lg shadow-indigo-100 flex items-center justify-center gap-2"
|
||||
>
|
||||
{isSaving ? <Loader2 size={18} className="animate-spin" /> : 'Confirm Payment'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Footer / Pagination */}
|
||||
<div className="p-4 px-6 bg-white border-t border-slate-200 flex items-center justify-between text-sm text-slate-500">
|
||||
<div>
|
||||
Showing {filteredOrders.length} of {orders.length} bills
|
||||
</div>
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<span>Show:</span>
|
||||
<select className="bg-slate-50 border border-slate-200 rounded px-2 py-1 outline-none">
|
||||
<option>10</option>
|
||||
<option>20</option>
|
||||
<option>50</option>
|
||||
</select>
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<button className="p-2 hover:bg-slate-100 rounded">
|
||||
<ChevronRight size={18} className="rotate-180" />
|
||||
</button>
|
||||
<span className="px-3">1 of 1</span>
|
||||
<button className="p-2 hover:bg-slate-100 rounded">
|
||||
<ChevronRight size={18} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Bills;
|
||||
487
frontend/src/pages/Customers.tsx
Normal file
@@ -0,0 +1,487 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Search, User, Phone, Tag, ChevronRight, UserCheck, UserMinus, MoreVertical, LayoutGrid, List, Edit2, Trash2, Shield, X, Eye, EyeOff, Loader2, AlertCircle, CheckCircle } from 'lucide-react';
|
||||
import Pagination from '../components/Pagination';
|
||||
|
||||
interface UserDto {
|
||||
id: number;
|
||||
mobileNumber: string;
|
||||
name: string;
|
||||
loggedIn: boolean;
|
||||
}
|
||||
|
||||
const Customers: React.FC = () => {
|
||||
const [users, setUsers] = useState<UserDto[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [searchTerm, setSearchTerm] = useState('');
|
||||
const [viewMode, setViewMode] = useState<'table' | 'grid'>('table');
|
||||
|
||||
// Pagination States
|
||||
const [currentPage, setCurrentPage] = useState(0);
|
||||
const [pageSize, setPageSize] = useState(10);
|
||||
const [totalElements, setTotalElements] = useState(0);
|
||||
|
||||
// Edit Modal State
|
||||
const [showEditModal, setShowEditModal] = useState(false);
|
||||
const [editingUser, setEditingUser] = useState<UserDto | null>(null);
|
||||
const [editForm, setEditForm] = useState({ name: '', mobileNumber: '', pin: '' });
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [showPin, setShowPin] = useState(false);
|
||||
const [errors, setErrors] = useState<{[key: string]: string}>({});
|
||||
|
||||
// Notification State
|
||||
const [toast, setToast] = useState<{message: string, type: 'success' | 'error'} | null>(null);
|
||||
|
||||
// Action Menu State
|
||||
const [openMenuId, setOpenMenuId] = useState<number | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
fetchUsers();
|
||||
}, [currentPage, pageSize]);
|
||||
|
||||
const fetchUsers = async () => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
const host = window.location.hostname;
|
||||
const response = await fetch(`http://${host}:8080/api/auth/users?page=${currentPage}&size=${pageSize}`);
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
if (data && data.content) {
|
||||
setUsers(data.content);
|
||||
setTotalElements(data.totalElements);
|
||||
} else {
|
||||
setUsers([]);
|
||||
setTotalElements(0);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error fetching users:', error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const showNotification = (message: string, type: 'success' | 'error') => {
|
||||
setToast({ message, type });
|
||||
setTimeout(() => setToast(null), 3000);
|
||||
};
|
||||
|
||||
const handleEditClick = (user: UserDto) => {
|
||||
setEditingUser(user);
|
||||
setEditForm({ name: user.name, mobileNumber: user.mobileNumber, pin: '' });
|
||||
setShowEditModal(true);
|
||||
setOpenMenuId(null);
|
||||
setErrors({});
|
||||
setShowPin(false);
|
||||
};
|
||||
|
||||
const handleDeleteClick = async (user: UserDto) => {
|
||||
if (!window.confirm(`Are you sure you want to permanently delete ${user.name}? This action cannot be undone.`)) return;
|
||||
|
||||
try {
|
||||
const host = window.location.hostname;
|
||||
const response = await fetch(`http://${host}:8080/api/auth/users/${user.id}`, {
|
||||
method: 'DELETE',
|
||||
});
|
||||
if (response.ok) {
|
||||
showNotification(`${user.name} deleted successfully`, 'success');
|
||||
fetchUsers();
|
||||
setOpenMenuId(null);
|
||||
} else {
|
||||
showNotification('Failed to delete user', 'error');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error deleting user:', error);
|
||||
showNotification('Error connecting to server', 'error');
|
||||
}
|
||||
};
|
||||
|
||||
const validateForm = () => {
|
||||
const newErrors: {[key: string]: string} = {};
|
||||
if (!editForm.name.trim()) newErrors.name = 'Full Name is required';
|
||||
|
||||
if (!/^[0-9]{10}$/.test(editForm.mobileNumber)) {
|
||||
newErrors.mobileNumber = 'Mobile number must be exactly 10 digits';
|
||||
}
|
||||
|
||||
if (editForm.pin && !/^[0-9]{6}$/.test(editForm.pin)) {
|
||||
newErrors.pin = 'PIN must be exactly 6 digits';
|
||||
}
|
||||
|
||||
setErrors(newErrors);
|
||||
return Object.keys(newErrors).length === 0;
|
||||
};
|
||||
|
||||
const handleUpdateSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!editingUser) return;
|
||||
if (!validateForm()) return;
|
||||
|
||||
setIsSaving(true);
|
||||
try {
|
||||
const host = window.location.hostname;
|
||||
const response = await fetch(`http://${host}:8080/api/auth/users/${editingUser.id}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(editForm),
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
showNotification('Customer profile updated successfully', 'success');
|
||||
setShowEditModal(false);
|
||||
fetchUsers();
|
||||
} else {
|
||||
const error = await response.json();
|
||||
showNotification(error.message || 'Failed to update user', 'error');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error updating user:', error);
|
||||
showNotification('Connection error, try again later', 'error');
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const getInitials = (name: string) => {
|
||||
if (!name) return '??';
|
||||
return name.split(' ').map(n => n[0]).join('').toUpperCase().slice(0, 2);
|
||||
};
|
||||
|
||||
const filteredUsers = users.filter(user =>
|
||||
user.name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
user.mobileNumber?.includes(searchTerm)
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Toast Notification - Moved outside animation trapping */}
|
||||
{toast && (
|
||||
<div className="fixed top-8 left-1/2 -translate-x-1/2 z-[200] animate-in fade-in slide-in-from-top-4 duration-300">
|
||||
<div className={`px-6 py-3 rounded-2xl shadow-2xl flex items-center gap-3 border ${
|
||||
toast.type === 'success'
|
||||
? 'bg-emerald-50 border-emerald-100 text-emerald-800'
|
||||
: 'bg-red-50 border-red-100 text-red-800'
|
||||
}`}>
|
||||
{toast.type === 'success' ? <CheckCircle size={20} className="text-emerald-500" /> : <AlertCircle size={20} className="text-red-500" />}
|
||||
<span className="text-sm font-bold">{toast.message}</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Main Animated Container */}
|
||||
<div className="flex flex-col h-full bg-[#f8fafc] p-8 gap-8 overflow-y-auto animate-slideUp font-inter relative">
|
||||
{/* Header Section */}
|
||||
<div className="flex flex-col md:flex-row md:items-center justify-between gap-6 max-w-[1600px]">
|
||||
<div className="flex items-center gap-5">
|
||||
<div className="w-14 h-14 bg-[#231651] rounded-xl flex items-center justify-center shadow-lg shadow-[#231651]/20">
|
||||
<User className="text-white w-7 h-7" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-[#1e293b]">Customer Management</h1>
|
||||
<p className="text-sm text-[#64748b]">View and manage customers registered through the ordering site</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="relative group min-w-[320px]">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 text-[#94a3b8] group-focus-within:text-[#231651] transition-colors" size={18} />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Search customers..."
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
className="w-full pl-10 pr-4 py-2 bg-white border border-[#e2e8f0] rounded-xl text-sm focus:outline-none focus:border-[#231651]/30 transition-all shadow-sm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex p-1 bg-white border border-[#e2e8f0] rounded-xl shadow-sm">
|
||||
<button
|
||||
className={`p-1.5 rounded-lg transition-all ${viewMode === 'table' ? 'bg-[#231651] text-white' : 'text-[#64748b] hover:bg-gray-50'}`}
|
||||
onClick={() => setViewMode('table')}
|
||||
>
|
||||
<List size={20} />
|
||||
</button>
|
||||
<button
|
||||
className={`p-1.5 rounded-lg transition-all ${viewMode === 'grid' ? 'bg-[#231651] text-white' : 'text-[#64748b] hover:bg-gray-50'}`}
|
||||
onClick={() => setViewMode('grid')}
|
||||
>
|
||||
<LayoutGrid size={20} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Main Content */}
|
||||
<div className="max-w-[1600px]">
|
||||
{isLoading ? (
|
||||
<div className="flex flex-col items-center justify-center py-24 bg-white rounded-xl border border-[#e2e8f0] shadow-sm">
|
||||
<div className="w-10 h-10 border-4 border-[#231651]/10 border-t-[#231651] rounded-full animate-spin"></div>
|
||||
<p className="mt-4 text-[#64748b] font-medium text-sm">Loading customer base...</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="bg-white rounded-xl border border-[#e2e8f0] shadow-sm">
|
||||
{viewMode === 'table' ? (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-left border-collapse">
|
||||
<thead>
|
||||
<tr className="bg-gray-50/50 border-b border-[#e2e8f0]">
|
||||
<th className="px-6 py-4 text-xs font-bold text-[#64748b] uppercase tracking-wider">Customer Info</th>
|
||||
<th className="px-6 py-4 text-xs font-bold text-[#64748b] uppercase tracking-wider">Contact Info</th>
|
||||
<th className="px-6 py-4 text-xs font-bold text-[#64748b] uppercase tracking-wider">Membership</th>
|
||||
<th className="px-6 py-4 text-xs font-bold text-[#64748b] uppercase tracking-wider">Status</th>
|
||||
<th className="px-6 py-4 text-xs font-bold text-[#64748b] uppercase tracking-wider text-right">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-[#e2e8f0]">
|
||||
{filteredUsers.length > 0 ? (
|
||||
filteredUsers.map((user) => (
|
||||
<tr key={user.id} className="hover:bg-gray-50/50 transition-all">
|
||||
<td className="px-6 py-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-10 h-10 bg-[#231651] rounded-lg flex items-center justify-center text-white font-bold text-sm">
|
||||
{getInitials(user.name)}
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm font-bold text-[#1e293b]">{user.name}</p>
|
||||
<p className="text-[11px] text-[#64748b]">ID: {user.id.toString().padStart(4, '0')}</p>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-6 py-4">
|
||||
<div className="flex items-center gap-2 text-sm text-[#1e293b] font-medium">
|
||||
<Phone size={14} className="text-[#94a3b8]" />
|
||||
<span>{user.mobileNumber}</span>
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-6 py-4">
|
||||
<span className="px-2.5 py-1 bg-blue-50 text-blue-600 rounded-lg text-xs font-semibold whitespace-nowrap">
|
||||
REGULAR CUSTOMER
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-6 py-4">
|
||||
<span className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-bold ${
|
||||
user.loggedIn
|
||||
? 'bg-green-100 text-green-700'
|
||||
: 'bg-gray-100 text-gray-600'
|
||||
}`}>
|
||||
<div className={`w-1.5 h-1.5 rounded-full ${user.loggedIn ? 'bg-green-500' : 'bg-gray-400'}`} />
|
||||
{user.loggedIn ? 'Active Now' : 'Offline'}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-6 py-4 text-right relative">
|
||||
<button onClick={() => setOpenMenuId(openMenuId === user.id ? null : user.id)} className="p-1.5 text-[#94a3b8] hover:text-[#231651] rounded-lg transition-colors">
|
||||
<MoreVertical size={18} />
|
||||
</button>
|
||||
|
||||
{openMenuId === user.id && (
|
||||
<div className="absolute right-6 top-10 w-40 bg-white rounded-xl shadow-2xl border border-[#e2e8f0] z-50 overflow-hidden animate-in fade-in slide-in-from-top-2">
|
||||
<button onClick={() => handleEditClick(user)} className="w-full flex items-center gap-3 px-4 py-3 text-sm hover:bg-gray-50 text-[#475569] font-medium border-b border-[#f1f5f9]">
|
||||
<Edit2 size={16} /> Edit User
|
||||
</button>
|
||||
<button onClick={() => handleDeleteClick(user)} className="w-full flex items-center gap-3 px-4 py-3 text-sm hover:bg-gray-50 text-red-600 font-medium font-bold">
|
||||
<Trash2 size={16} /> Delete User
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))
|
||||
) : (
|
||||
<tr>
|
||||
<td colSpan={5} className="px-6 py-12 text-center text-[#64748b]">
|
||||
<div className="flex flex-col items-center justify-center">
|
||||
<User size={40} className="mb-2 opacity-20" />
|
||||
<p className="font-medium">No customers found</p>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6 p-6">
|
||||
{filteredUsers.map(user => (
|
||||
<div key={user.id} className="group relative p-6 bg-white border border-[#e2e8f0] rounded-xl flex flex-col items-center text-center transition-all hover:shadow-lg hover:-translate-y-1">
|
||||
<div className="absolute top-4 right-4">
|
||||
<button onClick={() => setOpenMenuId(openMenuId === user.id ? null : user.id)} className="p-1.5 text-[#94a3b8] hover:text-[#231651] rounded-lg">
|
||||
<MoreVertical size={18} />
|
||||
</button>
|
||||
{openMenuId === user.id && (
|
||||
<div className="absolute right-0 mt-2 w-40 bg-white rounded-xl shadow-2xl border border-[#e2e8f0] z-50 overflow-hidden">
|
||||
<button onClick={() => handleEditClick(user)} className="w-full flex items-center gap-3 px-4 py-3 text-sm hover:bg-gray-50 text-[#475569] font-medium">
|
||||
<Edit2 size={16} /> Edit
|
||||
</button>
|
||||
<button onClick={() => handleDeleteClick(user)} className="w-full flex items-center gap-3 px-4 py-3 text-sm hover:bg-gray-50 text-red-600 font-medium">
|
||||
<Trash2 size={16} /> Delete
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="relative mb-4">
|
||||
<div className="w-20 h-20 bg-[#231651] rounded-2xl flex items-center justify-center text-2xl font-bold text-white shadow-lg shadow-[#231651]/20">
|
||||
{getInitials(user.name)}
|
||||
</div>
|
||||
<div className={`absolute -bottom-1 -right-1 w-5 h-5 rounded-full border-4 border-white shadow-sm ${user.loggedIn ? 'bg-green-500' : 'bg-gray-400'}`}></div>
|
||||
</div>
|
||||
|
||||
<h3 className="text-lg font-bold text-[#1e293b] mb-0.5">{user.name}</h3>
|
||||
<p className="text-sm text-[#64748b] font-medium mb-4">{user.mobileNumber}</p>
|
||||
|
||||
<div className="flex items-center gap-2 mb-6">
|
||||
<span className="px-2 py-0.5 bg-blue-50 text-blue-600 text-[10px] font-bold rounded-lg border border-blue-100 uppercase tracking-wider">
|
||||
RIT STUDENT
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<button onClick={() => handleEditClick(user)} className="w-full py-2.5 bg-gray-50 border border-[#e2e8f0] text-[#1e293b] hover:bg-[#231651] hover:text-white rounded-xl flex items-center justify-center gap-2 text-sm font-bold transition-all">
|
||||
Edit Profile <Edit2 size={16} />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Pagination
|
||||
currentPage={currentPage}
|
||||
pageSize={pageSize}
|
||||
totalElements={totalElements}
|
||||
onPageChange={setCurrentPage}
|
||||
onPageSizeChange={(newSize) => {
|
||||
setPageSize(newSize);
|
||||
setCurrentPage(0);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Edit User Modal - Positioned absolutely relative to viewport */}
|
||||
{showEditModal && (
|
||||
<div className="fixed inset-0 bg-[#231651]/20 backdrop-blur-sm z-[100] flex items-center justify-center p-4 overflow-y-auto">
|
||||
<div className="bg-white rounded-3xl w-full max-w-2xl shadow-2xl overflow-hidden animate-in zoom-in duration-300 my-auto">
|
||||
<div className="px-10 py-8 border-b border-[#e2e8f0] flex justify-between items-center bg-gray-50/50">
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="w-12 h-12 bg-[#231651]/5 rounded-xl flex items-center justify-center text-[#231651]">
|
||||
<Edit2 size={24} />
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="text-2xl font-bold text-[#1e293b]">Edit Customer</h2>
|
||||
<p className="text-sm text-[#64748b]">Update account details and security credentials</p>
|
||||
</div>
|
||||
</div>
|
||||
<button onClick={() => setShowEditModal(false)} className="p-2 hover:bg-gray-200 rounded-full transition-colors">
|
||||
<X size={24} className="text-[#64748b]" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleUpdateSubmit} className="p-10 space-y-8">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-8">
|
||||
<div>
|
||||
<label className="block text-[11px] uppercase font-black text-[#64748b] mb-2.5 tracking-widest ml-1">Full Name</label>
|
||||
<div className="relative">
|
||||
<User size={20} className="absolute left-4 top-1/2 -translate-y-1/2 text-[#94a3b8]" />
|
||||
<input
|
||||
required
|
||||
type="text"
|
||||
value={editForm.name}
|
||||
onChange={(e) => {
|
||||
setEditForm({...editForm, name: e.target.value});
|
||||
if (errors.name) setErrors({...errors, name: ''});
|
||||
}}
|
||||
className={`w-full pl-12 pr-4 py-4 bg-slate-50 border rounded-2xl text-base font-bold focus:ring-4 focus:ring-[#231651]/5 focus:border-[#231651] transition-all outline-none ${
|
||||
errors.name ? 'border-red-500 ring-4 ring-red-500/5' : 'border-[#e2e8f0]'
|
||||
}`}
|
||||
placeholder="e.g. John Doe"
|
||||
/>
|
||||
</div>
|
||||
{errors.name && <p className="text-xs text-red-500 mt-2 font-bold flex items-center gap-1 ml-1"><AlertCircle size={12} />{errors.name}</p>}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-[11px] uppercase font-black text-[#64748b] mb-2.5 tracking-widest ml-1">Mobile Number</label>
|
||||
<div className="relative">
|
||||
<Phone size={20} className="absolute left-4 top-1/2 -translate-y-1/2 text-[#94a3b8]" />
|
||||
<input
|
||||
required
|
||||
type="text"
|
||||
maxLength={10}
|
||||
value={editForm.mobileNumber}
|
||||
onChange={(e) => {
|
||||
const val = e.target.value.replace(/\D/g, '');
|
||||
setEditForm({...editForm, mobileNumber: val});
|
||||
if (errors.mobileNumber) setErrors({...errors, mobileNumber: ''});
|
||||
}}
|
||||
className={`w-full pl-12 pr-4 py-4 bg-slate-50 border rounded-2xl text-base font-bold focus:ring-4 focus:ring-[#231651]/5 focus:border-[#231651] transition-all outline-none ${
|
||||
errors.mobileNumber ? 'border-red-500 ring-4 ring-red-500/5' : 'border-[#e2e8f0]'
|
||||
}`}
|
||||
placeholder="10-digit number"
|
||||
/>
|
||||
</div>
|
||||
{errors.mobileNumber && <p className="text-xs text-red-500 mt-2 font-bold flex items-center gap-1 ml-1"><AlertCircle size={12} />{errors.mobileNumber}</p>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="p-6 bg-slate-50 rounded-[2rem] border border-[#e2e8f0] border-dashed">
|
||||
<label className="block text-[11px] uppercase font-black text-[#64748b] mb-3 tracking-widest ml-1">Reset Security PIN (Optional)</label>
|
||||
<div className="relative max-w-sm">
|
||||
<Shield size={20} className="absolute left-4 top-1/2 -translate-y-1/2 text-[#94a3b8]" />
|
||||
<input
|
||||
type={showPin ? "text" : "password"}
|
||||
maxLength={6}
|
||||
value={editForm.pin}
|
||||
onChange={(e) => {
|
||||
const val = e.target.value.replace(/\D/g, '');
|
||||
setEditForm({...editForm, pin: val});
|
||||
if (errors.pin) setErrors({...errors, pin: ''});
|
||||
}}
|
||||
className={`w-full pl-12 pr-12 py-4 bg-white border rounded-2xl text-base font-bold focus:ring-4 focus:ring-[#231651]/5 focus:border-[#231651] transition-all outline-none ${
|
||||
errors.pin ? 'border-red-500 ring-4 ring-red-500/5' : 'border-[#e2e8f0]'
|
||||
}`}
|
||||
placeholder="Enter new 6-digit PIN"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowPin(!showPin)}
|
||||
className="absolute right-4 top-1/2 -translate-y-1/2 text-[#94a3b8] hover:text-[#231651] transition-colors p-1"
|
||||
>
|
||||
{showPin ? <EyeOff size={20} /> : <Eye size={20} />}
|
||||
</button>
|
||||
</div>
|
||||
{errors.pin ? (
|
||||
<p className="text-xs text-red-500 mt-2 font-bold flex items-center gap-1 ml-1"><AlertCircle size={12} />{errors.pin}</p>
|
||||
) : (
|
||||
<p className="text-xs text-[#94a3b8] mt-3 font-semibold ml-1">Only update this if the student has forgotten their credentials.</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex gap-4 pt-6">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowEditModal(false)}
|
||||
className="flex-1 px-8 py-4 border-2 border-[#e2e8f0] text-[#64748b] font-bold rounded-2xl hover:bg-gray-50 transition-all text-sm"
|
||||
>
|
||||
Discard Changes
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isSaving}
|
||||
className="flex-[1.5] px-8 py-4 bg-[#231651] text-white font-bold rounded-2xl shadow-xl shadow-[#231651]/20 hover:scale-[1.01] active:scale-95 transition-all flex items-center justify-center gap-3 text-sm"
|
||||
>
|
||||
{isSaving ? (
|
||||
<><Loader2 size={20} className="animate-spin" /> Syncing Details...</>
|
||||
) : (
|
||||
<><Edit2 size={20} /> Save Account Updates</>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default Customers;
|
||||
306
frontend/src/pages/Dashboard.tsx
Normal file
@@ -0,0 +1,306 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import {
|
||||
Target,
|
||||
ChevronRight,
|
||||
ShoppingBag,
|
||||
ArrowRight,
|
||||
Wallet
|
||||
} from 'lucide-react';
|
||||
import {
|
||||
AreaChart,
|
||||
Area,
|
||||
XAxis,
|
||||
YAxis,
|
||||
CartesianGrid,
|
||||
Tooltip,
|
||||
ResponsiveContainer,
|
||||
PieChart,
|
||||
Pie,
|
||||
Cell
|
||||
} from 'recharts';
|
||||
import { motion } from 'framer-motion';
|
||||
|
||||
const Dashboard = () => {
|
||||
const [activeTab, setActiveTab] = useState('Sales');
|
||||
const [timeRange, setTimeRange] = useState('Today');
|
||||
const [data, setData] = useState<any>(null);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchData = async () => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
const response = await fetch('/api/dashboard/stats');
|
||||
if (response.ok) {
|
||||
const result = await response.json();
|
||||
setData(result);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error fetching dashboard data:', error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
fetchData();
|
||||
}, []);
|
||||
|
||||
if (isLoading || !data) {
|
||||
return (
|
||||
<div className="h-screen flex items-center justify-center bg-slate-50/50">
|
||||
<motion.div
|
||||
animate={{ scale: [1, 1.1, 1], opacity: [0.5, 1, 0.5] }}
|
||||
transition={{ repeat: Infinity, duration: 1.5 }}
|
||||
className="text-[#521c4b] font-black uppercase tracking-widest text-sm"
|
||||
>
|
||||
Loading Business Intelligence...
|
||||
</motion.div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const { stats, storeOverview, hourlySales, insights } = data;
|
||||
|
||||
const pieData = [
|
||||
{ name: 'Full Payment', value: stats.totalSales, color: '#8b5cf6' },
|
||||
{ name: 'Credit', value: 0, color: '#fbbf24' } // Credits logic can be added later
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="p-8 space-y-8 bg-slate-50/50 min-h-screen font-inter">
|
||||
{/* Top Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex flex-col">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<button title="Navigate back to previous section" className="p-1.5 hover:bg-slate-100 rounded-lg transition-all">
|
||||
<ArrowRight className="rotate-180 text-slate-400" size={18} />
|
||||
</button>
|
||||
<h2 className="text-xs font-black text-[#521c4b] uppercase tracking-widest">Dashboard</h2>
|
||||
</div>
|
||||
<h1 className="text-2xl font-black text-slate-800">Good morning</h1>
|
||||
<p className="text-[10px] text-slate-400 font-medium flex items-center gap-1.5">
|
||||
<span className="p-0.5 bg-slate-200 rounded text-slate-500">i</span>
|
||||
The default time settings for the merchant view are from 12:00 AM to 11:59 PM.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="relative group">
|
||||
<select title="Filter by store type or category" className="appearance-none bg-white border border-slate-200 rounded-xl px-4 py-2 pr-10 text-xs font-bold text-slate-600 outline-none focus:border-[#521c4b] transition-all cursor-pointer shadow-sm">
|
||||
<option>Store Type: All</option>
|
||||
</select>
|
||||
<div className="absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none">
|
||||
<ChevronRight size={14} className="rotate-90 text-slate-400" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Main Stats Grid */}
|
||||
<div className="grid grid-cols-12 gap-6">
|
||||
{/* Sales Chart Section */}
|
||||
<div className="col-span-12 lg:col-span-5 bg-white p-6 rounded-[32px] border border-slate-100 shadow-sm relative overflow-hidden group">
|
||||
<div className="flex items-center gap-8 mb-8 border-b border-slate-50">
|
||||
{['Sales', 'Payments'].map(tab => (
|
||||
<button
|
||||
key={tab}
|
||||
title={`View ${tab} analysis and trends`}
|
||||
onClick={() => setActiveTab(tab)}
|
||||
className={`pb-4 text-[11px] font-black uppercase tracking-widest transition-all relative ${activeTab === tab ? 'text-[#521c4b]' : 'text-slate-400 hover:text-slate-600'}`}
|
||||
>
|
||||
{tab}
|
||||
{activeTab === tab && (
|
||||
<motion.div layoutId="tabLineMain" className="absolute bottom-0 left-0 right-0 h-0.5 bg-[#521c4b]" />
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-end mb-4 gap-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-2.5 h-2.5 rounded-full border-2 border-[#521c4b]/30 bg-[#521c4b]/10" />
|
||||
<span className="text-[10px] font-black text-slate-400 uppercase tracking-widest">Today's Revenue</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="h-[280px] w-full mt-4">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<AreaChart data={hourlySales}>
|
||||
<defs>
|
||||
<linearGradient id="colorSalesMain" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="5%" stopColor="#f43f5e" stopOpacity={0.2}/>
|
||||
<stop offset="95%" stopColor="#f43f5e" stopOpacity={0}/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#f1f5f9" />
|
||||
<XAxis dataKey="time" axisLine={false} tickLine={false} tick={{fill: '#94a3b8', fontSize: 10, fontWeight: 700}} />
|
||||
<YAxis axisLine={false} tickLine={false} tick={{fill: '#94a3b8', fontSize: 10, fontWeight: 700}} tickFormatter={(v) => v >= 1000 ? `₹${v/1000}k` : `₹${v}`} />
|
||||
<Tooltip contentStyle={{ borderRadius: '12px', border: 'none', boxShadow: '0 10px 15px -3px rgb(0 0 0 / 0.1)' }} />
|
||||
<Area type="monotone" dataKey="value" stroke="#f43f5e" strokeWidth={3} fillOpacity={1} fill="url(#colorSalesMain)" />
|
||||
</AreaChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Total Sales Gauge */}
|
||||
<div className="col-span-12 lg:col-span-4 bg-white p-6 rounded-[32px] border border-slate-100 shadow-sm relative">
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<h3 className="text-sm font-black text-slate-800 tracking-tight uppercase tracking-widest">Total Revenue</h3>
|
||||
<Target size={14} className="text-slate-300" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="relative h-[280px] flex flex-col items-center justify-center">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<PieChart>
|
||||
<Pie
|
||||
data={pieData}
|
||||
cx="50%"
|
||||
cy="50%"
|
||||
innerRadius={75}
|
||||
outerRadius={100}
|
||||
paddingAngle={0}
|
||||
dataKey="value"
|
||||
startAngle={210}
|
||||
endAngle={-30}
|
||||
>
|
||||
{pieData.map((entry, index) => (
|
||||
<Cell key={`cell-${index}`} fill={entry.color} />
|
||||
))}
|
||||
</Pie>
|
||||
</PieChart>
|
||||
</ResponsiveContainer>
|
||||
<div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 text-center">
|
||||
<h2 className="text-3xl font-black text-slate-800 tracking-tighter">₹{stats.totalSales.toLocaleString()}</h2>
|
||||
<p className="text-[10px] font-black text-slate-400 uppercase tracking-widest mt-1">Life Time</p>
|
||||
</div>
|
||||
<div className="flex gap-6 mt-2">
|
||||
{pieData.map(item => (
|
||||
<div key={item.name} className="flex items-center gap-2">
|
||||
<div className="w-2.5 h-2.5 rounded-full" style={{ backgroundColor: item.color }} />
|
||||
<span className="text-[9px] font-black text-slate-500 uppercase tracking-widest font-black">{item.name}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Right Stats Column */}
|
||||
<div className="col-span-12 lg:col-span-3 space-y-6">
|
||||
{/* Filters */}
|
||||
<div className="flex items-center justify-between overflow-x-auto gap-2 pb-2 scrollbar-none">
|
||||
{['Yesterday', 'Today', 'Week', '30 Days'].map(range => (
|
||||
<button
|
||||
key={range}
|
||||
title={`Analyze data from ${range.toLowerCase()}`}
|
||||
onClick={() => setTimeRange(range)}
|
||||
className={`whitespace-nowrap px-3 py-2 text-[10px] font-black uppercase tracking-widest transition-all rounded-xl ${timeRange === range ? 'text-white bg-[#521c4b] shadow-md shadow-[#521c4b]/20' : 'text-slate-400 hover:text-slate-600'}`}
|
||||
>
|
||||
{range}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Total Orders Card */}
|
||||
<div title="View detailed order volume and throughput" className="bg-white p-6 rounded-[24px] border border-slate-100 shadow-sm relative h-[180px] flex flex-col justify-between group hover:border-[#521c4b]/30 transition-all cursor-pointer">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="p-2 bg-amber-50 text-amber-500 rounded-xl group-hover:scale-110 transition-transform">
|
||||
<ShoppingBag size={20} />
|
||||
</div>
|
||||
<h4 className="text-[11px] font-black text-slate-400 uppercase tracking-widest leading-none">Total Orders</h4>
|
||||
</div>
|
||||
<div className="flex flex-col items-center">
|
||||
<h2 className="text-5xl font-black text-slate-800 tracking-tighter">{stats.activeOrders}</h2>
|
||||
<div className="w-full h-1 bg-green-500 rounded-full mt-4 shadow-sm" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Expenses Card */}
|
||||
<div title="Track operational expenditures and overhead" className="bg-white p-6 rounded-[24px] border border-slate-100 shadow-sm h-[130px] flex flex-col justify-between group hover:border-[#521c4b]/30 transition-all cursor-pointer">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="p-2 bg-slate-50 text-[#521c4b] rounded-xl shadow-sm group-hover:bg-[#521c4b]/10 transition-colors">
|
||||
<Wallet size={20} />
|
||||
</div>
|
||||
<h4 className="text-[11px] font-black text-slate-400 uppercase tracking-widest leading-none">Total Expenses</h4>
|
||||
</div>
|
||||
<div className="text-center pb-2">
|
||||
<h2 className="text-3xl font-black text-slate-800 tracking-tighter">₹0</h2>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Bottom Section */}
|
||||
<div className="grid grid-cols-12 gap-8 mt-4 pb-12">
|
||||
{/* Store Insights */}
|
||||
<div className="col-span-12 lg:col-span-5 bg-white rounded-[32px] border border-slate-100 shadow-sm p-8 flex flex-col">
|
||||
<h3 className="text-sm font-black text-slate-800 tracking-tight mb-8 uppercase tracking-widest">Business Intelligence</h3>
|
||||
<div className="space-y-4 flex-1">
|
||||
{insights.map((insight: string, idx: number) => (
|
||||
<motion.div
|
||||
initial={{ x: -20, opacity: 0 }}
|
||||
animate={{ x: 0, opacity: 1 }}
|
||||
transition={{ delay: idx * 0.1 }}
|
||||
key={idx}
|
||||
className="p-5 rounded-2xl border border-slate-100 bg-slate-50/50 hover:bg-white hover:shadow-md hover:border-transparent transition-all cursor-default"
|
||||
>
|
||||
<p className="text-[11px] font-black text-slate-600 leading-relaxed uppercase tracking-tight">{insight}</p>
|
||||
</motion.div>
|
||||
))}
|
||||
</div>
|
||||
<div className="mt-8">
|
||||
<button title="Refresh and sync comprehensive business insights" className="w-full py-3 border border-dashed border-slate-200 rounded-2xl text-[10px] font-black text-slate-400 uppercase tracking-widest hover:border-[#521c4b]/30 hover:text-[#521c4b] transition-all">
|
||||
Generate More Insights
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Store Overview */}
|
||||
<div className="col-span-12 lg:col-span-7 bg-white rounded-[32px] border border-slate-100 shadow-sm p-8">
|
||||
<div className="flex items-center justify-between mb-8">
|
||||
<h3 className="text-sm font-black text-slate-800 tracking-tight uppercase tracking-widest">Store Performance</h3>
|
||||
<button title="View detailed metrics for all geographic locations" className="text-[10px] font-black text-[#521c4b] uppercase tracking-widest hover:underline">View All Locations</button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-6">
|
||||
{(storeOverview.length > 0 ? storeOverview : [{name: 'No active sales currently', sale: 0, orders: 0, taxes: 0, purchase: 0}]).map((store: any, idx: number) => (
|
||||
<div key={idx} className="p-6 rounded-[28px] border border-slate-50 bg-slate-50/30 group hover:bg-white hover:shadow-lg hover:border-transparent transition-all border-l-4 border-l-[#521c4b]/30">
|
||||
<p className="text-xs font-black text-slate-800 mb-6 uppercase tracking-widest flex items-center justify-between">
|
||||
{store.name}
|
||||
<ArrowRight size={14} className="opacity-0 group-hover:opacity-100 transition-opacity text-[#521c4b]" />
|
||||
</p>
|
||||
<div className="grid grid-cols-4 gap-4">
|
||||
<div className="space-y-1.5">
|
||||
<p className="text-[9px] font-black text-rose-500 uppercase tracking-widest opacity-60">Gross Sale</p>
|
||||
<p className="text-lg font-black text-slate-800 tracking-tighter">₹{Number(store.sale).toLocaleString()}</p>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<p className="text-[9px] font-black text-blue-500 uppercase tracking-widest opacity-60">Volume</p>
|
||||
<p className="text-lg font-black text-slate-800 tracking-tighter">{store.orders} Orders</p>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<p className="text-[9px] font-black text-indigo-500 uppercase tracking-widest opacity-60">Taxation</p>
|
||||
<p className="text-lg font-black text-slate-800 tracking-tighter">₹{store.taxes}</p>
|
||||
</div>
|
||||
<div className="space-y-1.5 text-right">
|
||||
<p className="text-[9px] font-black text-amber-500 uppercase tracking-widest opacity-60">Procurement</p>
|
||||
<p className="text-lg font-black text-slate-800 tracking-tighter">₹{store.purchase}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="mt-10 flex justify-center">
|
||||
<button title="Execute a granular comparison across different store cohorts" className="flex items-center gap-3 px-8 py-3 bg-[#521c4b] text-white text-[11px] font-black uppercase tracking-widest rounded-2xl shadow-xl shadow-[#521c4b]/20 hover:scale-105 transition-all group">
|
||||
Detailed Comparison
|
||||
<ArrowRight size={16} className="group-hover:translate-x-1 transition-transform" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Dashboard;
|
||||
225
frontend/src/pages/Login.tsx
Normal file
@@ -0,0 +1,225 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { motion } from 'framer-motion';
|
||||
import {
|
||||
User,
|
||||
Lock,
|
||||
Eye,
|
||||
EyeOff,
|
||||
ArrowRight,
|
||||
ShieldCheck,
|
||||
UserCircle2
|
||||
} from 'lucide-react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
|
||||
// Import Assets
|
||||
import collegeLogo from '../assets/college-logo.png';
|
||||
import buildingPhoto from '../assets/ritchennai.webp';
|
||||
|
||||
const Login = () => {
|
||||
const [role, setRole] = useState<'manager' | 'master'>('manager');
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
const [username, setUsername] = useState('admin');
|
||||
const [password, setPassword] = useState('admin');
|
||||
const navigate = useNavigate();
|
||||
|
||||
// Ensure any previous session is completely wiped out when arriving at the login screen
|
||||
useEffect(() => {
|
||||
sessionStorage.removeItem('isLoggedIn');
|
||||
sessionStorage.removeItem('userRole');
|
||||
sessionStorage.removeItem('userPermissions');
|
||||
}, []);
|
||||
|
||||
const handleLogin = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/system/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ email: username, password })
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const user = await response.json();
|
||||
|
||||
// Strict Role Validation
|
||||
if (user.role.toLowerCase() !== role) {
|
||||
alert(`Access Denied: You are trying to login as ${role.toUpperCase()}, but your credentials belong to a ${user.role.toUpperCase()} account.`);
|
||||
return;
|
||||
}
|
||||
|
||||
sessionStorage.setItem('isLoggedIn', 'true');
|
||||
sessionStorage.setItem('userRole', user.role.toLowerCase());
|
||||
sessionStorage.setItem('userPermissions', JSON.stringify(user.permissions || []));
|
||||
navigate('/store-dashboard');
|
||||
} else {
|
||||
const error = await response.text();
|
||||
alert(error || 'Invalid credentials');
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Login error:', err);
|
||||
alert('Network error - make sure backend is running');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-[#f8fafc] flex flex-col md:flex-row overflow-hidden font-inter">
|
||||
{/* Left Section: Login Form */}
|
||||
<div className="w-full md:w-[45%] lg:w-[40%] flex flex-col p-8 md:p-12 lg:p-16 relative z-10 bg-white shadow-2xl">
|
||||
{/* Top Logo */}
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: -20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
className="mb-16"
|
||||
>
|
||||
<img src={collegeLogo} alt="College Logo" className="h-16 md:h-20 object-contain" />
|
||||
</motion.div>
|
||||
|
||||
{/* Login Container */}
|
||||
<motion.div
|
||||
initial={{ opacity: 0, x: -30 }}
|
||||
animate={{ opacity: 1, x: 0 }}
|
||||
transition={{ delay: 0.2 }}
|
||||
className="flex-1 flex flex-col justify-center max-w-sm mx-auto w-full"
|
||||
>
|
||||
<div className="text-center mb-10">
|
||||
<h2 className="text-[10px] font-black tracking-[0.3em] text-[#1e293b] uppercase mb-2">
|
||||
Canteen Management System
|
||||
</h2>
|
||||
<div className="w-12 h-1 bg-[#231651] mx-auto rounded-full"></div>
|
||||
</div>
|
||||
|
||||
{/* Role Toggle */}
|
||||
<div className="bg-[#f1f5f9] p-1.5 rounded-2xl flex gap-1 mb-8 relative">
|
||||
<motion.div
|
||||
className="absolute h-[calc(100%-12px)] top-1.5 bg-white rounded-xl shadow-sm z-0"
|
||||
initial={false}
|
||||
animate={{
|
||||
left: role === 'manager' ? '6px' : '50%',
|
||||
width: 'calc(50% - 9px)'
|
||||
}}
|
||||
transition={{ type: "spring", stiffness: 300, damping: 30 }}
|
||||
/>
|
||||
<button
|
||||
onClick={() => setRole('manager')}
|
||||
className={`flex-1 flex items-center justify-center gap-2 py-3 rounded-xl text-xs font-bold transition-all relative z-10 ${role === 'manager' ? 'text-[#231651]' : 'text-[#94a3b8] hover:text-[#64748b]'
|
||||
}`}
|
||||
>
|
||||
<UserCircle2 size={16} />
|
||||
MANAGER
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setRole('master')}
|
||||
className={`flex-1 flex items-center justify-center gap-2 py-3 rounded-xl text-xs font-bold transition-all relative z-10 ${role === 'master' ? 'text-[#231651]' : 'text-[#94a3b8] hover:text-[#64748b]'
|
||||
}`}
|
||||
>
|
||||
<ShieldCheck size={16} />
|
||||
MASTER
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Form */}
|
||||
<form onSubmit={handleLogin} className="space-y-6">
|
||||
<div className="space-y-2">
|
||||
<label className="text-[10px] font-black text-[#94a3b8] uppercase tracking-widest pl-1">
|
||||
Secure User ID
|
||||
</label>
|
||||
<div className="relative group">
|
||||
<div className="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none text-[#94a3b8] group-focus-within:text-[#231651] transition-colors">
|
||||
<User size={18} />
|
||||
</div>
|
||||
<input
|
||||
type="text"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
placeholder="Username"
|
||||
className="w-full bg-white border-2 border-[#e2e8f0] focus:border-[#231651] rounded-2xl py-4 pl-12 pr-4 text-sm font-semibold outline-none transition-all placeholder:text-[#cbd5e1]"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<div className="flex justify-between items-center pl-1">
|
||||
<label className="text-[10px] font-black text-[#94a3b8] uppercase tracking-widest">
|
||||
Passcode
|
||||
</label>
|
||||
<button type="button" className="text-[10px] font-black text-[#231651] uppercase hover:underline">
|
||||
Forgot Access?
|
||||
</button>
|
||||
</div>
|
||||
<div className="relative group">
|
||||
<div className="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none text-[#94a3b8] group-focus-within:text-[#231651] transition-colors">
|
||||
<Lock size={18} />
|
||||
</div>
|
||||
<input
|
||||
type={showPassword ? 'text' : 'password'}
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
placeholder="••••••••"
|
||||
className="w-full bg-white border-2 border-[#e2e8f0] focus:border-[#231651] rounded-2xl py-4 pl-12 pr-12 text-sm font-semibold outline-none transition-all placeholder:text-[#cbd5e1]"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowPassword(!showPassword)}
|
||||
className="absolute inset-y-0 right-0 pr-4 flex items-center text-[#94a3b8] hover:text-[#64748b] transition-colors"
|
||||
>
|
||||
{showPassword ? <EyeOff size={18} /> : <Eye size={18} />}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
className="w-full bg-[#231651] text-white rounded-2xl py-4 font-black text-sm flex items-center justify-center gap-3 shadow-xl shadow-[#231651]/20 hover:scale-[1.02] active:scale-[0.98] transition-all overflow-hidden group relative"
|
||||
>
|
||||
<span className="relative z-10">CONNECT TO PORTAL</span>
|
||||
<ArrowRight size={18} className="relative z-10 group-hover:translate-x-1 transition-transform" />
|
||||
<motion.div
|
||||
className="absolute inset-0 bg-white/10"
|
||||
initial={{ x: '-100%' }}
|
||||
whileHover={{ x: '100%' }}
|
||||
transition={{ duration: 0.6 }}
|
||||
/>
|
||||
</button>
|
||||
</form>
|
||||
</motion.div>
|
||||
|
||||
{/* Footer */}
|
||||
<div className="mt-auto text-center">
|
||||
<p className="text-[10px] font-black text-[#cbd5e1] uppercase tracking-[0.2em]">
|
||||
© 2026 RITCHENNAI • SYSTEM PORTAL
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Right Section: Visual */}
|
||||
<div className="hidden md:flex flex-1 relative bg-[#f8fafc] items-center justify-center p-8 overflow-hidden">
|
||||
|
||||
{/* Decorative Circles */}
|
||||
<div className="absolute top-20 right-20 w-64 h-64 bg-[#231651]/5 rounded-full blur-3xl"></div>
|
||||
<div className="absolute bottom-20 left-40 w-96 h-96 bg-[#231651]/5 rounded-full blur-3xl"></div>
|
||||
|
||||
{/* Image Container with Custom Shape (using clip-path or rounded corners) */}
|
||||
<motion.div
|
||||
initial={{ opacity: 0, scale: 0.95, x: 50 }}
|
||||
animate={{ opacity: 1, scale: 1, x: 0 }}
|
||||
transition={{ duration: 0.8 }}
|
||||
className="w-full h-full relative z-10"
|
||||
>
|
||||
<div className="w-full h-full overflow-hidden shadow-2xl border-[12px] border-white bg-white">
|
||||
<img
|
||||
src={buildingPhoto}
|
||||
alt="RIT Chennai Building"
|
||||
className="w-full h-full object-cover"
|
||||
/>
|
||||
{/* Overlay Gradient */}
|
||||
<div className="absolute inset-0 bg-gradient-to-tr from-[#231651]/20 to-transparent"></div>
|
||||
</div>
|
||||
|
||||
</motion.div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Login;
|
||||
377
frontend/src/pages/Managers.tsx
Normal file
@@ -0,0 +1,377 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { motion, AnimatePresence } from 'framer-motion';
|
||||
import {
|
||||
UserPlus,
|
||||
Search,
|
||||
Trash2,
|
||||
Shield,
|
||||
Mail,
|
||||
Lock,
|
||||
Check,
|
||||
X,
|
||||
LayoutGrid,
|
||||
Receipt,
|
||||
Users,
|
||||
ShoppingBag,
|
||||
ShoppingCart,
|
||||
Wallet,
|
||||
BarChart3,
|
||||
Table2,
|
||||
CreditCard,
|
||||
Megaphone,
|
||||
MessageSquare,
|
||||
Store
|
||||
} from 'lucide-react';
|
||||
|
||||
interface Manager {
|
||||
id: string;
|
||||
name: string;
|
||||
email: string;
|
||||
role: string;
|
||||
sections: string[];
|
||||
status: 'active' | 'inactive';
|
||||
}
|
||||
|
||||
const ALL_SECTIONS = [
|
||||
{ id: 'dashboard', label: 'Dashboard', icon: LayoutGrid },
|
||||
{ id: 'sale', label: 'Sale', icon: Receipt },
|
||||
{ id: 'customers', label: 'Customers', icon: Users },
|
||||
{ id: 'purchases', label: 'Purchases', icon: ShoppingBag },
|
||||
{ id: 'inventory', label: 'Inventory', icon: ShoppingCart },
|
||||
{ id: 'expense', label: 'Expense', icon: Wallet },
|
||||
{ id: 'reports', label: 'Reports', icon: BarChart3 },
|
||||
{ id: 'table', label: 'Table Management', icon: Table2 },
|
||||
{ id: 'wallet', label: 'Wallet', icon: CreditCard },
|
||||
{ id: 'promotions', label: 'Promotions', icon: Megaphone },
|
||||
{ id: 'feedback', label: 'Feedback', icon: MessageSquare },
|
||||
{ id: 'stores', label: 'Stores', icon: Store }
|
||||
];
|
||||
|
||||
const Managers = () => {
|
||||
const [managers, setManagers] = useState<Manager[]>([]);
|
||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
// Form State
|
||||
const [formData, setFormData] = useState({
|
||||
name: '',
|
||||
email: '',
|
||||
password: '',
|
||||
viewOnly: false,
|
||||
selectedSections: [] as string[]
|
||||
});
|
||||
|
||||
// Fetch from Backend
|
||||
const fetchManagers = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await fetch('/api/system/managers');
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
// Backend uses 'permissions' field, map it to 'sections' for the component if needed
|
||||
const mappedData = data.map((m: any) => ({
|
||||
...m,
|
||||
sections: m.permissions || []
|
||||
}));
|
||||
setManagers(mappedData);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Error fetching managers:', err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
fetchManagers();
|
||||
}, []);
|
||||
|
||||
const toggleSection = (sectionId: string) => {
|
||||
setFormData(prev => ({
|
||||
...prev,
|
||||
selectedSections: prev.selectedSections.includes(sectionId)
|
||||
? prev.selectedSections.filter(id => id !== sectionId)
|
||||
: [...prev.selectedSections, sectionId]
|
||||
}));
|
||||
};
|
||||
|
||||
const handleCreateAccount = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
try {
|
||||
const response = await fetch('/api/system/managers', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
name: formData.name,
|
||||
email: formData.email,
|
||||
password: formData.password,
|
||||
viewOnly: formData.viewOnly,
|
||||
permissions: formData.selectedSections
|
||||
})
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
fetchManagers();
|
||||
setIsModalOpen(false);
|
||||
setFormData({ name: '', email: '', password: '', viewOnly: false, selectedSections: [] });
|
||||
} else {
|
||||
alert('Failed to create manager');
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Create manager error:', err);
|
||||
alert('Network error - make sure backend is running');
|
||||
}
|
||||
};
|
||||
|
||||
const dismissManager = async (id: string) => {
|
||||
if (window.confirm('Are you sure you want to dismiss this manager?')) {
|
||||
try {
|
||||
const response = await fetch(`/api/system/managers/${id}`, {
|
||||
method: 'DELETE'
|
||||
});
|
||||
if (response.ok) {
|
||||
fetchManagers();
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Delete error:', err);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="p-8 space-y-8 bg-[#f8fafc] min-h-screen font-inter">
|
||||
<div className="flex justify-between items-center">
|
||||
<div>
|
||||
<h1 className="text-3xl font-black text-[#231651]">Managers</h1>
|
||||
<p className="text-[#64748b] text-sm mt-1">Manage portal access and role assignments</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setIsModalOpen(true)}
|
||||
className="flex items-center gap-2 bg-[#231651] text-white px-6 py-3 rounded-2xl font-bold shadow-xl shadow-[#231651]/20 hover:scale-105 transition-all"
|
||||
>
|
||||
<UserPlus size={20} />
|
||||
<span>Add New Member</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Search & Stats */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
|
||||
<div className="md:col-span-2 relative group flex items-center">
|
||||
<div className="absolute left-5 flex items-center justify-center pointer-events-none">
|
||||
<Search className="text-[#94a3b8] group-focus-within:text-[#231651] transition-colors" size={20} />
|
||||
</div>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Search by name or email..."
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
className="w-full h-14 bg-white border border-[#e2e8f0] rounded-2xl pl-14 pr-4 text-sm font-semibold outline-none transition-all focus:border-[#231651]/30 focus:shadow-md shadow-sm text-[#1e293b] placeholder:text-[#94a3b8]"
|
||||
/>
|
||||
</div>
|
||||
<div className="bg-white p-4 rounded-2xl border border-[#e2e8f0] shadow-sm flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-[10px] font-black text-[#94a3b8] uppercase tracking-widest">Active Managers</p>
|
||||
<h3 className="text-2xl font-black text-[#231651]">{managers.length}</h3>
|
||||
</div>
|
||||
<div className="p-3 bg-emerald-50 text-emerald-600 rounded-xl">
|
||||
<Shield size={24} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Managers List */}
|
||||
<div className="bg-white rounded-3xl border border-[#e2e8f0] shadow-sm overflow-hidden">
|
||||
<table className="w-full text-left">
|
||||
<thead className="bg-gray-50 border-b border-[#e2e8f0]">
|
||||
<tr>
|
||||
<th className="px-6 py-4 text-[10px] font-black text-[#94a3b8] uppercase tracking-widest">Manager</th>
|
||||
<th className="px-6 py-4 text-[10px] font-black text-[#94a3b8] uppercase tracking-widest">Role</th>
|
||||
<th className="px-6 py-4 text-[10px] font-black text-[#94a3b8] uppercase tracking-widest">Permissions</th>
|
||||
<th className="px-6 py-4 text-[10px] font-black text-[#94a3b8] uppercase tracking-widest">Status</th>
|
||||
<th className="px-6 py-4"></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-[#e2e8f0]">
|
||||
{managers.filter(m => m.name.toLowerCase().includes(searchQuery.toLowerCase()) || m.email.toLowerCase().includes(searchQuery.toLowerCase())).map((manager) => (
|
||||
<tr key={manager.id} className="hover:bg-gray-50/50 transition-colors">
|
||||
<td className="px-6 py-5">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-10 h-10 rounded-full bg-[#231651] text-white flex items-center justify-center font-bold">
|
||||
{manager.name.charAt(0)}
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm font-black text-[#1e293b]">{manager.name}</p>
|
||||
<p className="text-xs font-medium text-[#94a3b8]">{manager.email}</p>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-6 py-5">
|
||||
<span className="px-3 py-1 rounded-full bg-blue-50 text-blue-600 text-[10px] font-black uppercase tracking-wider">
|
||||
{manager.role}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-6 py-5">
|
||||
<div className="flex flex-wrap gap-1 max-w-[200px]">
|
||||
{manager.sections.map(s => (
|
||||
<span key={s} className="px-2 py-0.5 rounded-md bg-gray-100 text-[#64748b] text-[9px] font-bold uppercase">
|
||||
{s}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-6 py-5">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<div className="w-2 h-2 rounded-full bg-emerald-500"></div>
|
||||
<span className="text-[10px] font-black text-emerald-600 uppercase">Active</span>
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-6 py-5 text-right">
|
||||
<button
|
||||
onClick={() => dismissManager(manager.id)}
|
||||
className="p-2 text-[#94a3b8] hover:text-red-600 hover:bg-red-50 rounded-xl transition-all"
|
||||
>
|
||||
<Trash2 size={18} />
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{/* Create Account Modal */}
|
||||
<AnimatePresence>
|
||||
{isModalOpen && (
|
||||
<div className="fixed inset-0 z-[100] flex items-center justify-center p-4">
|
||||
<motion.div
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
onClick={() => setIsModalOpen(false)}
|
||||
className="absolute inset-0 bg-[#1e293b]/60 backdrop-blur-sm"
|
||||
/>
|
||||
<motion.div
|
||||
initial={{ opacity: 0, scale: 0.9, y: 20 }}
|
||||
animate={{ opacity: 1, scale: 1, y: 0 }}
|
||||
exit={{ opacity: 0, scale: 0.9, y: 20 }}
|
||||
className="relative bg-white w-full max-w-2xl rounded-[2.5rem] shadow-2xl overflow-hidden"
|
||||
>
|
||||
<div className="p-8 md:p-10">
|
||||
<div className="flex justify-between items-start mb-8">
|
||||
<div>
|
||||
<h2 className="text-2xl font-black text-[#1e293b]">Create manager account for <span className="text-[#231651]">RIT Canteen</span></h2>
|
||||
</div>
|
||||
<button onClick={() => setIsModalOpen(false)} className="p-2 hover:bg-gray-100 rounded-full transition-colors text-[#94a3b8]">
|
||||
<X size={24} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleCreateAccount} className="space-y-6">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<div className="space-y-2">
|
||||
<label className="text-[10px] font-black text-[#94a3b8] uppercase tracking-widest pl-1">Name / Terminal Name</label>
|
||||
<div className="relative group">
|
||||
<input
|
||||
required
|
||||
type="text"
|
||||
value={formData.name}
|
||||
onChange={(e) => setFormData({...formData, name: e.target.value})}
|
||||
placeholder="e.g. Main Desk"
|
||||
className="w-full bg-white border-2 border-[#e2e8f0] focus:border-[#231651] rounded-2xl py-3 pl-4 pr-4 text-sm font-semibold outline-none transition-all"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="text-[10px] font-black text-[#94a3b8] uppercase tracking-widest pl-1">Email Address</label>
|
||||
<div className="relative group">
|
||||
<div className="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none text-[#94a3b8]">
|
||||
<Mail size={16} />
|
||||
</div>
|
||||
<input
|
||||
required
|
||||
type="email"
|
||||
value={formData.email}
|
||||
onChange={(e) => setFormData({...formData, email: e.target.value})}
|
||||
placeholder="manager@rit.edu"
|
||||
className="w-full bg-white border-2 border-[#e2e8f0] focus:border-[#231651] rounded-2xl py-3 pl-11 pr-4 text-sm font-semibold outline-none transition-all"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<label className="text-[10px] font-black text-[#94a3b8] uppercase tracking-widest pl-1">Password (Optional)</label>
|
||||
<div className="relative group">
|
||||
<div className="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none text-[#94a3b8]">
|
||||
<Lock size={16} />
|
||||
</div>
|
||||
<input
|
||||
type="password"
|
||||
value={formData.password}
|
||||
onChange={(e) => setFormData({...formData, password: e.target.value})}
|
||||
placeholder="••••••••"
|
||||
className="w-full bg-white border-2 border-[#e2e8f0] focus:border-[#231651] rounded-2xl py-3 pl-11 pr-4 text-sm font-semibold outline-none transition-all"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3 py-2">
|
||||
<div
|
||||
onClick={() => setFormData({...formData, viewOnly: !formData.viewOnly})}
|
||||
className={cn(
|
||||
"w-5 h-5 rounded border-2 flex items-center justify-center cursor-pointer transition-all",
|
||||
formData.viewOnly ? "bg-[#231651] border-[#231651]" : "border-[#e2e8f0]"
|
||||
)}
|
||||
>
|
||||
{formData.viewOnly && <Check size={14} className="text-white" />}
|
||||
</div>
|
||||
<span className="text-sm font-bold text-[#64748b]">View only access</span>
|
||||
</div>
|
||||
|
||||
{/* Sections Selection */}
|
||||
<div className="space-y-4">
|
||||
<label className="text-[10px] font-black text-[#94a3b8] uppercase tracking-widest pl-1">Accessible Sections</label>
|
||||
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3">
|
||||
{ALL_SECTIONS.map((section) => (
|
||||
<div
|
||||
key={section.id}
|
||||
onClick={() => toggleSection(section.id)}
|
||||
className={cn(
|
||||
"flex flex-col items-center justify-center p-4 rounded-2xl border-2 cursor-pointer transition-all gap-2",
|
||||
formData.selectedSections.includes(section.id)
|
||||
? "bg-[#231651]/5 border-[#231651] text-[#231651]"
|
||||
: "bg-white border-[#e2e8f0] text-[#94a3b8] hover:border-[#231651]/30"
|
||||
)}
|
||||
>
|
||||
<section.icon size={20} />
|
||||
<span className="text-[9px] font-black uppercase text-center">{section.label}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="pt-4">
|
||||
<button
|
||||
type="submit"
|
||||
className="w-full bg-[#231651] text-white rounded-2xl py-4 font-black text-sm shadow-xl shadow-[#231651]/20 hover:scale-[1.02] active:scale-[0.98] transition-all"
|
||||
>
|
||||
Create Account
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</motion.div>
|
||||
</div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
// Helper for class names
|
||||
function cn(...inputs: any[]) {
|
||||
return inputs.filter(Boolean).join(' ');
|
||||
}
|
||||
|
||||
export default Managers;
|
||||
819
frontend/src/pages/Orders.tsx
Normal file
@@ -0,0 +1,819 @@
|
||||
import React, { useState, useEffect, useMemo } from 'react';
|
||||
import {
|
||||
Search,
|
||||
Calendar,
|
||||
Filter,
|
||||
CreditCard,
|
||||
User,
|
||||
ShoppingBag,
|
||||
MoreVertical,
|
||||
MessageCircle,
|
||||
RefreshCw,
|
||||
Trash2,
|
||||
Plus,
|
||||
Minus,
|
||||
Check,
|
||||
X as XIcon,
|
||||
RotateCcw,
|
||||
Edit2
|
||||
} from 'lucide-react';
|
||||
import { format } from 'date-fns';
|
||||
import Pagination from '../components/Pagination';
|
||||
|
||||
interface OrderItem {
|
||||
id?: number;
|
||||
productName: string;
|
||||
quantity: number;
|
||||
price: number;
|
||||
productId: number;
|
||||
}
|
||||
|
||||
interface Product {
|
||||
id: number;
|
||||
name: string;
|
||||
price: number;
|
||||
category: string;
|
||||
}
|
||||
|
||||
interface UserData {
|
||||
name: string;
|
||||
mobileNumber: string;
|
||||
}
|
||||
|
||||
interface Order {
|
||||
id: number;
|
||||
orderNumber: string;
|
||||
displayOrderId: string;
|
||||
totalAmount: number;
|
||||
status: string;
|
||||
paymentMethod: string;
|
||||
createdAt: string;
|
||||
user: UserData;
|
||||
items: OrderItem[];
|
||||
}
|
||||
|
||||
const Orders: React.FC = () => {
|
||||
const [orders, setOrders] = useState<Order[]>([]);
|
||||
const [selectedOrder, setSelectedOrder] = useState<Order | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [statusFilter, setStatusFilter] = useState('');
|
||||
const [paymentFilter, setPaymentFilter] = useState('');
|
||||
const [startDate, setStartDate] = useState(format(new Date(), 'yyyy-MM-dd'));
|
||||
const [endDate, setEndDate] = useState(format(new Date(), 'yyyy-MM-dd'));
|
||||
|
||||
// Pagination States
|
||||
const [currentPage, setCurrentPage] = useState(0);
|
||||
const [pageSize, setPageSize] = useState(10);
|
||||
const [totalElements, setTotalElements] = useState(0);
|
||||
|
||||
// Action Menu & Edit Modal States
|
||||
const [showActionMenu, setShowActionMenu] = useState(false);
|
||||
const [isEditModalOpen, setIsEditModalOpen] = useState(false);
|
||||
const [allProducts, setAllProducts] = useState<Product[]>([]);
|
||||
const [editSearchQuery, setEditSearchQuery] = useState('');
|
||||
const [editingItems, setEditingItems] = useState<OrderItem[]>([]);
|
||||
const [isUpdatingOrder, setIsUpdatingOrder] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
fetchOrders();
|
||||
fetchProducts();
|
||||
}, [startDate, endDate, statusFilter, paymentFilter, currentPage, pageSize]);
|
||||
|
||||
const fetchProducts = async () => {
|
||||
try {
|
||||
const response = await fetch(`http://${window.location.hostname}:8080/api/products`);
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
setAllProducts(data);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error fetching products:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const fetchOrders = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
// Build query params
|
||||
const params = new URLSearchParams();
|
||||
params.append('archived', 'false'); // Only show live orders
|
||||
if (startDate) params.append('startDate', `${startDate}T00:00:00`);
|
||||
if (endDate) params.append('endDate', `${endDate}T23:59:59`);
|
||||
if (statusFilter) params.append('status', statusFilter);
|
||||
if (paymentFilter) params.append('paymentType', paymentFilter);
|
||||
if (searchQuery) params.append('search', searchQuery);
|
||||
params.append('page', currentPage.toString());
|
||||
params.append('size', pageSize.toString());
|
||||
|
||||
const response = await fetch(`http://${window.location.hostname}:8080/api/orders/all?${params.toString()}`);
|
||||
const data = await response.json();
|
||||
|
||||
if (data && data.content && Array.isArray(data.content)) {
|
||||
setOrders(data.content);
|
||||
setTotalElements(data.totalElements);
|
||||
|
||||
// If we have a selected order, try to refresh it from the data list
|
||||
if (selectedOrder) {
|
||||
const updated = data.content.find((o: Order) => o.id === selectedOrder.id);
|
||||
if (updated) setSelectedOrder(updated);
|
||||
} else if (data.content.length > 0) {
|
||||
setSelectedOrder(data.content[0]);
|
||||
}
|
||||
} else {
|
||||
console.error('API did not return a valid Page object:', data);
|
||||
setOrders([]);
|
||||
setTotalElements(0);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error fetching orders:', error);
|
||||
setOrders([]);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleApproveOrder = async (orderId: number) => {
|
||||
try {
|
||||
const response = await fetch(`http://${window.location.hostname}:8080/api/orders/${orderId}/status`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ status: 'COMPLETED' })
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
fetchOrders();
|
||||
} else {
|
||||
alert('Failed to update order status');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error updating order:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleMarkUndelivered = async (orderId: number) => {
|
||||
try {
|
||||
const response = await fetch(`http://${window.location.hostname}:8080/api/orders/${orderId}/status`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ status: 'PAID' })
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
setShowActionMenu(false);
|
||||
fetchOrders();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error marking undelivered:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleEditOrder = () => {
|
||||
if (!selectedOrder) return;
|
||||
setEditingItems([...selectedOrder.items]);
|
||||
setIsEditModalOpen(true);
|
||||
setShowActionMenu(false);
|
||||
};
|
||||
|
||||
const updateItemQuantity = (index: number, delta: number) => {
|
||||
const newItems = [...editingItems];
|
||||
newItems[index].quantity = Math.max(1, newItems[index].quantity + delta);
|
||||
setEditingItems(newItems);
|
||||
};
|
||||
|
||||
const removeItem = (index: number) => {
|
||||
setEditingItems(editingItems.filter((_, i) => i !== index));
|
||||
};
|
||||
|
||||
const addProductToOrder = (product: Product) => {
|
||||
// Check if product already in list
|
||||
const existing = editingItems.findIndex(item => item.productId === product.id);
|
||||
if (existing !== -1) {
|
||||
updateItemQuantity(existing, 1);
|
||||
} else {
|
||||
setEditingItems([...editingItems, {
|
||||
productId: product.id,
|
||||
productName: product.name,
|
||||
price: product.price,
|
||||
quantity: 1
|
||||
}]);
|
||||
}
|
||||
setEditSearchQuery('');
|
||||
};
|
||||
|
||||
const editTotal = useMemo(() => {
|
||||
return editingItems.reduce((sum, item) => sum + (item.price * item.quantity), 0);
|
||||
}, [editingItems]);
|
||||
|
||||
const saveOrderEdits = async () => {
|
||||
if (!selectedOrder) return;
|
||||
setIsUpdatingOrder(true);
|
||||
try {
|
||||
const response = await fetch(`http://${window.location.hostname}:8080/api/orders/${selectedOrder.id}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
...selectedOrder,
|
||||
items: editingItems,
|
||||
totalAmount: editTotal
|
||||
})
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
setIsEditModalOpen(false);
|
||||
fetchOrders();
|
||||
} else {
|
||||
alert('Failed to update order details');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error saving edits:', error);
|
||||
} finally {
|
||||
setIsUpdatingOrder(false);
|
||||
}
|
||||
};
|
||||
|
||||
const filteredProducts = useMemo(() => {
|
||||
if (!editSearchQuery.trim()) return [];
|
||||
return allProducts.filter(p =>
|
||||
p.name.toLowerCase().includes(editSearchQuery.toLowerCase()) ||
|
||||
p.category.toLowerCase().includes(editSearchQuery.toLowerCase())
|
||||
).slice(0, 5); // Limit results
|
||||
}, [allProducts, editSearchQuery]);
|
||||
|
||||
const handleSearchSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
fetchOrders();
|
||||
};
|
||||
|
||||
const getStatusColor = (status: string) => {
|
||||
switch (status.toUpperCase()) {
|
||||
case 'COMPLETED': return 'bg-emerald-50 text-emerald-600 border-emerald-100';
|
||||
case 'PAID': return 'bg-indigo-50 text-indigo-600 border-indigo-100';
|
||||
case 'PENDING': return 'bg-amber-50 text-amber-600 border-amber-100';
|
||||
case 'CANCELLED': return 'bg-rose-50 text-rose-600 border-rose-100';
|
||||
default: return 'bg-slate-50 text-slate-600 border-slate-100';
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-[calc(100vh-64px)] bg-[#f8fafc]">
|
||||
{/* Top Filter Bar */}
|
||||
<div className="bg-white border-b border-slate-200 p-4 sticky top-0 z-10 shadow-sm">
|
||||
<form onSubmit={handleSearchSubmit} className="flex flex-wrap items-center gap-4 max-w-[1600px] mx-auto">
|
||||
{/* Date Picker */}
|
||||
<div className="flex items-center bg-slate-50 border border-slate-200 rounded-lg px-3 py-2 gap-2 focus-within:border-indigo-400 focus-within:ring-1 focus-within:ring-indigo-400 transition-all">
|
||||
<Calendar size={18} className="text-slate-400" />
|
||||
<input
|
||||
type="date"
|
||||
className="bg-transparent border-none text-sm font-medium text-slate-700 outline-none"
|
||||
value={startDate}
|
||||
onChange={(e) => setStartDate(e.target.value)}
|
||||
/>
|
||||
<span className="text-slate-300">|</span>
|
||||
<input
|
||||
type="date"
|
||||
className="bg-transparent border-none text-sm font-medium text-slate-700 outline-none"
|
||||
value={endDate}
|
||||
onChange={(e) => setEndDate(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Status Select */}
|
||||
<div className="flex items-center bg-slate-50 border border-slate-200 rounded-lg px-3 py-2 gap-2 min-w-[140px]">
|
||||
<Filter size={18} className="text-slate-400" />
|
||||
<select
|
||||
className="bg-transparent border-none text-sm font-medium text-slate-700 outline-none w-full cursor-pointer"
|
||||
value={statusFilter}
|
||||
onChange={(e) => setStatusFilter(e.target.value)}
|
||||
>
|
||||
<option value="">All Status</option>
|
||||
<option value="PAID">Paid</option>
|
||||
<option value="COMPLETED">Completed</option>
|
||||
<option value="PENDING">Pending</option>
|
||||
<option value="CANCELLED">Cancelled</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{/* Payment Type */}
|
||||
<div className="flex items-center bg-slate-50 border border-slate-200 rounded-lg px-3 py-2 gap-2 min-w-[140px]">
|
||||
<CreditCard size={18} className="text-slate-400" />
|
||||
<select
|
||||
className="bg-transparent border-none text-sm font-medium text-slate-700 outline-none w-full cursor-pointer"
|
||||
value={paymentFilter}
|
||||
onChange={(e) => setPaymentFilter(e.target.value)}
|
||||
>
|
||||
<option value="">Payment Type</option>
|
||||
<option value="UPI">UPI Payment</option>
|
||||
<option value="CREDIT">Credit</option>
|
||||
<option value="CASH">Cash</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{/* Search Box */}
|
||||
<div className="flex-1 flex items-center bg-slate-50 border border-slate-200 rounded-lg px-4 py-2 gap-3 focus-within:bg-white focus-within:border-indigo-400 focus-within:ring-1 focus-within:ring-indigo-400 transition-all shadow-inner">
|
||||
<Search size={18} className="text-slate-400" />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Search Order ID, Customer Name, Mobile..."
|
||||
className="bg-transparent border-none text-sm w-full outline-none text-slate-700 placeholder:text-slate-400"
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
title="Filter orders by date and criteria"
|
||||
className="bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg px-6 py-2 text-sm font-semibold transition-all shadow-md shadow-indigo-100 flex items-center gap-2 active:scale-95"
|
||||
>
|
||||
Apply Filters
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setSearchQuery('');
|
||||
setStatusFilter('');
|
||||
setPaymentFilter('');
|
||||
setStartDate(format(new Date(), 'yyyy-MM-dd'));
|
||||
setEndDate(format(new Date(), 'yyyy-MM-dd'));
|
||||
}}
|
||||
className="text-slate-500 hover:bg-slate-100 p-2 rounded-lg transition-colors border border-transparent hover:border-slate-200"
|
||||
title="Clear Filters"
|
||||
>
|
||||
<RefreshCw size={18} />
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
{/* Main Content Area */}
|
||||
<div className="flex-1 overflow-hidden flex max-w-[1800px] mx-auto w-full p-4 gap-4">
|
||||
{/* Left Column: Orders List */}
|
||||
<div className="w-[400px] flex flex-col gap-3 overflow-y-auto pr-2 custom-scrollbar pb-4">
|
||||
{loading ? (
|
||||
<div className="flex items-center justify-center p-12 text-slate-400 gap-2">
|
||||
<RefreshCw className="animate-spin" size={20} />
|
||||
<span>Loading orders...</span>
|
||||
</div>
|
||||
) : orders.length === 0 ? (
|
||||
<div className="bg-white rounded-xl border border-slate-200 p-12 text-center shadow-sm">
|
||||
<ShoppingBag size={48} className="mx-auto text-slate-200 mb-4" />
|
||||
<h3 className="text-slate-600 font-semibold mb-1">No orders found</h3>
|
||||
<p className="text-slate-400 text-sm">Try adjusting your filters</p>
|
||||
</div>
|
||||
) : (
|
||||
orders.map((order) => (
|
||||
<div
|
||||
key={order.id}
|
||||
onClick={() => setSelectedOrder(order)}
|
||||
className={`group relative bg-white border rounded-xl p-4 cursor-pointer transition-all hover:shadow-lg active:scale-[0.98] ${
|
||||
selectedOrder?.id === order.id
|
||||
? 'border-indigo-600 ring-1 ring-indigo-600 shadow-md'
|
||||
: 'border-slate-200 hover:border-indigo-300'
|
||||
}`}
|
||||
>
|
||||
<div className="flex justify-between items-start mb-3">
|
||||
<div className={`px-2.5 py-0.5 rounded-full text-[10px] font-bold tracking-wider uppercase border ${getStatusColor(order.status)}`}>
|
||||
{order.status}
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<div className="text-[10px] text-slate-400 font-medium uppercase mb-0.5">Grand Total</div>
|
||||
<div className="text-lg font-black text-slate-900 leading-none">₹{order.totalAmount.toFixed(2)}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-end justify-between">
|
||||
<div>
|
||||
<div className="text-xs text-slate-400 font-medium mb-1">Order #</div>
|
||||
<div className="text-2xl font-black text-slate-800 leading-none tracking-tight">#{order.displayOrderId}</div>
|
||||
<div className="mt-4 flex items-center gap-2 text-xs font-semibold px-2 py-1 bg-slate-100 text-slate-600 rounded-md w-fit uppercase">
|
||||
<CreditCard size={12} />
|
||||
{order.paymentMethod}
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<div className="text-xs font-bold text-slate-700 mb-1 truncate max-w-[150px]">
|
||||
{order.user?.name || 'Anonymous User'}
|
||||
</div>
|
||||
<div className="text-[10px] text-slate-400 font-medium">
|
||||
{format(new Date(order.createdAt), 'dd/MM/yy HH:mm')}
|
||||
</div>
|
||||
<div className="mt-3 text-[10px] inline-flex items-center gap-1 font-bold px-2 py-0.5 bg-[#231651] text-white rounded shadow-sm uppercase">
|
||||
<User size={10} />
|
||||
{order.user?.name ? 'REGISTERED' : 'WALK-IN'}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{selectedOrder?.id === order.id && (
|
||||
<div className="absolute left-0 top-0 bottom-0 w-1 bg-indigo-600 rounded-l-xl" />
|
||||
)}
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
|
||||
<Pagination
|
||||
currentPage={currentPage}
|
||||
pageSize={pageSize}
|
||||
totalElements={totalElements}
|
||||
onPageChange={setCurrentPage}
|
||||
onPageSizeChange={(newSize) => {
|
||||
setPageSize(newSize);
|
||||
setCurrentPage(0); // Reset to first page on size change
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Right Column: Order Details */}
|
||||
<div className="flex-1 bg-white border border-slate-200 rounded-2xl flex flex-col shadow-sm overflow-hidden relative mb-4">
|
||||
{selectedOrder ? (
|
||||
<>
|
||||
{/* Order Detail Header */}
|
||||
<div className="p-6 border-b border-slate-100 flex justify-between items-center bg-white sticky top-0 z-10">
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="bg-indigo-50 p-3 rounded-xl text-indigo-600">
|
||||
<ShoppingBag size={24} />
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="text-2xl font-black text-slate-900 flex items-center gap-2 tracking-tight">
|
||||
Order #{selectedOrder.displayOrderId}
|
||||
</h2>
|
||||
<p className="text-xs text-slate-400 font-medium tracking-wide">ID: {selectedOrder.orderNumber}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<button className="text-emerald-500 hover:bg-emerald-50 p-2 rounded-lg transition-colors border border-transparent hover:border-emerald-100">
|
||||
<MessageCircle size={20} />
|
||||
</button>
|
||||
|
||||
<div className="relative action-menu-container">
|
||||
<button
|
||||
onClick={() => setShowActionMenu(!showActionMenu)}
|
||||
title="More actions"
|
||||
className={`p-2 rounded-lg transition-all ${showActionMenu ? 'bg-slate-100 text-indigo-600' : 'text-slate-400 hover:bg-slate-50'}`}
|
||||
>
|
||||
<MoreVertical size={20} />
|
||||
</button>
|
||||
{showActionMenu && (
|
||||
<div className="absolute right-0 mt-2 w-56 bg-white border border-slate-200 rounded-xl shadow-2xl z-20 overflow-hidden py-1 animate-in fade-in zoom-in duration-200">
|
||||
<div className="px-4 py-2 text-[10px] font-bold text-slate-400 uppercase tracking-widest border-b border-slate-50">Manual Actions</div>
|
||||
<button
|
||||
onClick={() => handleMarkUndelivered(selectedOrder.id)}
|
||||
className="w-full text-left px-4 py-3 text-sm font-semibold text-slate-700 hover:bg-slate-50 flex items-center gap-3 transition-colors"
|
||||
>
|
||||
<RotateCcw size={16} className="text-amber-500" /> Mark Undelivered
|
||||
</button>
|
||||
<button
|
||||
onClick={handleEditOrder}
|
||||
title="Modify items in this order"
|
||||
className="w-full text-left px-4 py-3 text-sm font-semibold text-slate-700 hover:bg-slate-50 flex items-center gap-3 transition-colors"
|
||||
>
|
||||
<Edit2 size={16} className="text-indigo-500" /> Edit Order Items
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className={`ml-2 px-4 py-1.5 rounded-lg text-xs font-bold uppercase border shadow-sm ${getStatusColor(selectedOrder.status)}`}>
|
||||
{selectedOrder.status}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Tabs Container */}
|
||||
<div className="px-6 bg-white border-b border-slate-50 flex gap-8">
|
||||
{['Orders', 'Payment Information', 'Customer Details'].map((tab, idx) => (
|
||||
<button
|
||||
key={tab}
|
||||
className={`py-4 text-xs font-bold uppercase tracking-widest relative transition-colors ${
|
||||
idx === 0 ? 'text-indigo-600' : 'text-slate-400 hover:text-slate-600'
|
||||
}`}
|
||||
>
|
||||
{tab}
|
||||
{idx === 0 && <div className="absolute bottom-0 left-0 right-0 h-0.5 bg-indigo-600" />}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Content Scroll Area */}
|
||||
<div className="flex-1 overflow-y-auto p-8 custom-scrollbar">
|
||||
<div className="grid grid-cols-3 gap-12 mb-12">
|
||||
<div className="space-y-1.5">
|
||||
<div className="text-[10px] text-slate-400 uppercase font-black tracking-widest">Date & Time</div>
|
||||
<div className="text-sm font-bold text-slate-700 bg-slate-50 p-3 rounded-lg border border-slate-100">
|
||||
{format(new Date(selectedOrder.createdAt), 'yyyy-MM-dd HH:mm:ss')}
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<div className="text-[10px] text-slate-400 uppercase font-black tracking-widest">Payment Type</div>
|
||||
<div className="text-sm font-bold text-indigo-900 bg-indigo-50 p-3 rounded-lg border border-indigo-100 flex items-center gap-2">
|
||||
<CreditCard size={14} />
|
||||
{selectedOrder.paymentMethod.toUpperCase()}
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<div className="text-[10px] text-slate-400 uppercase font-black tracking-widest">Payment ID</div>
|
||||
<div className="text-sm font-mono font-medium text-slate-600 bg-slate-50 p-3 rounded-lg border border-slate-100 flex items-center justify-between group">
|
||||
<span className="truncate">Pay_{selectedOrder.orderNumber.split('-')[1] || '000'}...</span>
|
||||
<button className="opacity-0 group-hover:opacity-100 transition-opacity"><RefreshCw size={12} /></button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="flex justify-between items-center border-b border-slate-100 pb-3">
|
||||
<h3 className="text-[10px] font-black text-slate-400 uppercase tracking-[0.2em]">Items</h3>
|
||||
<h3 className="text-[10px] font-black text-slate-400 uppercase tracking-[0.2em]">Price</h3>
|
||||
</div>
|
||||
|
||||
<div className="divide-y divide-slate-50">
|
||||
{selectedOrder.items.map((item, idx) => (
|
||||
<div key={idx} className="py-5 flex justify-between items-center group hover:bg-slate-50/50 transition-colors rounded-lg -mx-2 px-2">
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="w-10 h-10 bg-slate-100 rounded-lg flex items-center justify-center text-slate-400 font-bold text-xs uppercase">
|
||||
{item.productName.substring(0, 2)}
|
||||
</div>
|
||||
<div>
|
||||
<div className="font-black text-slate-800 text-sm">{item.productName}</div>
|
||||
<div className="text-xs text-slate-400 font-medium">Standard Portion</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-8">
|
||||
<div className="text-right">
|
||||
<div className="text-sm font-black text-slate-900">₹{(item.price * item.quantity).toLocaleString()}</div>
|
||||
<div className="text-[10px] font-bold text-slate-400">
|
||||
{item.quantity} x <span className="text-indigo-400 font-black">₹{item.price}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Bottom Summary Panel */}
|
||||
<div className="bg-slate-50 p-8 border-t border-slate-100 shadow-[0_-4px_20px_rgba(0,0,0,0.02)]">
|
||||
<div className="flex justify-between mb-8">
|
||||
<div className="flex gap-12">
|
||||
<div>
|
||||
<div className="text-[10px] text-slate-400 uppercase font-black tracking-widest mb-1.5">Total Items</div>
|
||||
<div className="text-xl font-black text-slate-800">{selectedOrder.items.length}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-[10px] text-slate-400 uppercase font-black tracking-widest mb-1.5">Total Quantity</div>
|
||||
<div className="text-xl font-black text-slate-800">
|
||||
{selectedOrder.items.reduce((sum, item) => sum + item.quantity, 0)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-right flex flex-col gap-2 min-w-[200px]">
|
||||
<div className="flex justify-between items-center text-xs text-slate-500 font-bold">
|
||||
<span>Order Summary</span>
|
||||
<span className="font-black">₹{selectedOrder.totalAmount.toLocaleString()}</span>
|
||||
</div>
|
||||
<div className="flex justify-between items-center text-base text-slate-900 font-black pt-2 border-t border-slate-200">
|
||||
<span>Total Sum</span>
|
||||
<span className="text-2xl text-emerald-600">₹{selectedOrder.totalAmount.toLocaleString()}</span>
|
||||
</div>
|
||||
<div className={`flex justify-between items-center text-sm font-black pt-1 ${selectedOrder.status.toUpperCase() === 'COMPLETED' ? 'text-slate-400' : 'text-rose-600'}`}>
|
||||
<span>Balance Due</span>
|
||||
<span>₹{selectedOrder.status.toUpperCase() === 'COMPLETED' ? '0.00' : selectedOrder.totalAmount.toLocaleString()}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-3">
|
||||
<button
|
||||
onClick={() => window.print()}
|
||||
className="flex-1 bg-white border border-slate-200 text-slate-700 py-3 rounded-xl font-black text-xs uppercase tracking-widest hover:bg-slate-50 transition-all active:scale-[0.98]"
|
||||
>
|
||||
Print Receipt
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleApproveOrder(selectedOrder.id)}
|
||||
disabled={selectedOrder.status.toUpperCase() === 'COMPLETED'}
|
||||
className={`flex-1 py-3 rounded-xl font-black text-xs uppercase tracking-widest transition-all shadow-md active:scale-[0.98] ${
|
||||
selectedOrder.status.toUpperCase() === 'COMPLETED'
|
||||
? 'bg-emerald-500 text-white cursor-not-allowed opacity-80'
|
||||
: 'bg-indigo-600 text-white hover:bg-indigo-700 shadow-indigo-100'
|
||||
}`}
|
||||
>
|
||||
{selectedOrder.status.toUpperCase() === 'COMPLETED' ? 'Order Completed' : 'Approve Order'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div className="flex-1 flex flex-col items-center justify-center p-12 text-center text-slate-400">
|
||||
<div className="bg-slate-50 p-6 rounded-full mb-6">
|
||||
<ShoppingBag size={48} className="text-slate-200" />
|
||||
</div>
|
||||
<h3 className="text-slate-600 font-bold text-lg mb-2">Select an order to view details</h3>
|
||||
<p className="max-w-xs mx-auto text-sm">Pick an order from the list on the left to see full transaction history, items, and customer info.</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Edit Order Modal */}
|
||||
{isEditModalOpen && (
|
||||
<div className="fixed inset-0 bg-slate-900/60 backdrop-blur-sm z-[100] flex items-center justify-center p-4 animate-in fade-in duration-300">
|
||||
<div className="bg-white rounded-3xl w-full max-w-4xl max-h-[90vh] flex flex-col shadow-2xl overflow-hidden border border-slate-200">
|
||||
{/* Modal Header */}
|
||||
<div className="px-8 py-6 border-b border-slate-100 flex justify-between items-center bg-white sticky top-0 z-10">
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="bg-indigo-600 p-2.5 rounded-xl text-white">
|
||||
<ShoppingBag size={24} />
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="text-xl font-black text-slate-900 tracking-tight">Edit Order Items</h2>
|
||||
<p className="text-xs text-slate-400 font-bold uppercase tracking-wider">Order #{selectedOrder?.displayOrderId}</p>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setIsEditModalOpen(false)}
|
||||
className="text-slate-400 hover:bg-slate-100 p-2 rounded-xl transition-all hover:rotate-90"
|
||||
>
|
||||
<XIcon size={24} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-hidden flex">
|
||||
{/* Left Column: Line Items */}
|
||||
<div className="flex-1 overflow-y-auto p-8 custom-scrollbar border-r border-slate-50">
|
||||
<div className="flex justify-between items-center mb-6">
|
||||
<h3 className="text-[10px] font-black text-slate-400 uppercase tracking-[0.2em]">Current Items</h3>
|
||||
<span className="text-[10px] font-black bg-indigo-50 text-indigo-600 px-2.5 py-1 rounded-full uppercase tracking-widest">{editingItems.length} Total</span>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
{editingItems.length === 0 ? (
|
||||
<div className="text-center py-12 bg-slate-50 rounded-2xl border-2 border-dashed border-slate-200">
|
||||
<ShoppingBag className="mx-auto text-slate-300 mb-2" size={32} />
|
||||
<p className="text-sm font-bold text-slate-400">No items in this order</p>
|
||||
</div>
|
||||
) : (
|
||||
editingItems.map((item, idx) => (
|
||||
<div key={idx} className="flex items-center justify-between p-4 bg-white border border-slate-100 rounded-2xl group hover:border-indigo-200 hover:shadow-md transition-all">
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="w-10 h-10 bg-slate-50 rounded-lg flex items-center justify-center font-black text-slate-400 text-xs uppercase border border-slate-100 group-hover:bg-indigo-600 group-hover:text-white group-hover:border-indigo-600 transition-colors">
|
||||
{item.productName.substring(0, 2)}
|
||||
</div>
|
||||
<div>
|
||||
<div className="font-bold text-slate-800 text-sm">{item.productName}</div>
|
||||
<div className="text-[10px] font-black text-indigo-400 uppercase">₹{item.price} each</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-6">
|
||||
<div className="flex items-center bg-slate-50 rounded-xl p-1 border border-slate-100">
|
||||
<button
|
||||
onClick={() => updateItemQuantity(idx, -1)}
|
||||
className="p-1.5 hover:bg-white hover:text-rose-500 rounded-lg transition-all active:scale-90"
|
||||
>
|
||||
<Minus size={14} />
|
||||
</button>
|
||||
<span className="w-10 text-center text-sm font-black text-slate-700">{item.quantity}</span>
|
||||
<button
|
||||
onClick={() => updateItemQuantity(idx, 1)}
|
||||
className="p-1.5 hover:bg-white hover:text-emerald-500 rounded-lg transition-all active:scale-90"
|
||||
>
|
||||
<Plus size={14} />
|
||||
</button>
|
||||
</div>
|
||||
<div className="text-right min-w-[80px]">
|
||||
<div className="text-sm font-black text-slate-900 leading-none mb-1">₹{(item.price * item.quantity).toFixed(2)}</div>
|
||||
<button
|
||||
onClick={() => removeItem(idx)}
|
||||
className="text-[10px] font-black text-rose-400 hover:text-rose-600 uppercase tracking-widest transition-colors flex items-center gap-1 active:scale-95"
|
||||
>
|
||||
<Trash2 size={10} /> Delete
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Right Column: Search Items to Add */}
|
||||
<div className="w-[350px] bg-slate-50/50 p-8 flex flex-col">
|
||||
<h3 className="text-[10px] font-black text-slate-400 uppercase tracking-[0.2em] mb-4">Add Items</h3>
|
||||
<div className="relative mb-6">
|
||||
<div className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400">
|
||||
<Plus size={16} />
|
||||
</div>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Search food items..."
|
||||
className="w-full bg-white border border-slate-200 rounded-xl py-2.5 pl-10 pr-4 text-sm font-medium outline-none focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 transition-all shadow-sm"
|
||||
value={editSearchQuery}
|
||||
onChange={(e) => setEditSearchQuery(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 space-y-2 overflow-y-auto custom-scrollbar">
|
||||
{filteredProducts.length > 0 ? (
|
||||
filteredProducts.map(product => (
|
||||
<button
|
||||
key={product.id}
|
||||
onClick={() => addProductToOrder(product)}
|
||||
className="w-full text-left p-3 bg-white border border-slate-100 rounded-xl hover:border-indigo-400 hover:shadow-md transition-all group flex justify-between items-center animate-in slide-in-from-right-4 duration-300"
|
||||
>
|
||||
<div>
|
||||
<div className="font-bold text-slate-800 text-sm group-hover:text-indigo-600 transition-colors">{product.name}</div>
|
||||
<div className="text-[10px] font-black text-slate-400 uppercase tracking-widest">{product.category}</div>
|
||||
</div>
|
||||
<div className="font-black text-emerald-600 text-xs">₹{product.price}</div>
|
||||
</button>
|
||||
))
|
||||
) : editSearchQuery ? (
|
||||
<div className="text-center py-6 text-slate-400 italic text-sm">No items matching your search</div>
|
||||
) : (
|
||||
<div className="text-center py-6 flex flex-col items-center gap-2">
|
||||
<div className="bg-white p-3 rounded-2xl shadow-sm text-slate-200">
|
||||
<Search size={24} />
|
||||
</div>
|
||||
<p className="text-xs font-bold text-slate-400 max-w-[150px] mx-auto">Start typing to add delicious items to the order</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="mt-8 pt-8 border-t border-slate-200">
|
||||
<div className="flex justify-between items-center mb-4">
|
||||
<span className="text-[10px] font-black text-slate-400 uppercase tracking-widest">New Order Total</span>
|
||||
<span className="text-2xl font-black text-emerald-600 tracking-tighter">₹{editTotal.toFixed(2)}</span>
|
||||
</div>
|
||||
<button
|
||||
onClick={saveOrderEdits}
|
||||
disabled={isUpdatingOrder || editingItems.length === 0}
|
||||
className={`w-full py-4 rounded-2xl text-xs font-black uppercase tracking-[0.2em] shadow-xl transition-all active:scale-[0.98] flex items-center justify-center gap-2 ${
|
||||
isUpdatingOrder || editingItems.length === 0
|
||||
? 'bg-slate-200 text-slate-400 cursor-not-allowed'
|
||||
: 'bg-[#231651] text-white hover:bg-[#2d1b66] shadow-indigo-100'
|
||||
}`}
|
||||
>
|
||||
{isUpdatingOrder ? <RefreshCw className="animate-spin" size={14} /> : <Check size={14} />}
|
||||
{isUpdatingOrder ? 'Updating...' : 'Update Order'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<style>{`
|
||||
.custom-scrollbar::-webkit-scrollbar {
|
||||
width: 5px;
|
||||
}
|
||||
.custom-scrollbar::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
.custom-scrollbar::-webkit-scrollbar-thumb {
|
||||
background: #e2e8f0;
|
||||
border-radius: 10px;
|
||||
}
|
||||
.custom-scrollbar::-webkit-scrollbar-thumb:hover {
|
||||
background: #cbd5e1;
|
||||
}
|
||||
.action-menu-container .animate-in {
|
||||
transform-origin: top right;
|
||||
}
|
||||
|
||||
@media print {
|
||||
/* Hide everything except the order detail container */
|
||||
body * {
|
||||
visibility: hidden;
|
||||
}
|
||||
.flex-1.bg-white.border.border-slate-200.rounded-2xl,
|
||||
.flex-1.bg-white.border.border-slate-200.rounded-2xl * {
|
||||
visibility: visible;
|
||||
}
|
||||
.flex-1.bg-white.border.border-slate-200.rounded-2xl {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
top: 0;
|
||||
width: 100%;
|
||||
border: none !important;
|
||||
box-shadow: none !important;
|
||||
}
|
||||
/* Hide buttons and tabs in print */
|
||||
button,
|
||||
.px-6.bg-white.border-b.border-slate-50.flex.gap-8,
|
||||
.action-menu-container {
|
||||
display: none !important;
|
||||
}
|
||||
/* Optimize for receipt layout */
|
||||
.p-8 {
|
||||
padding: 20px !important;
|
||||
}
|
||||
}
|
||||
`}</style>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Orders;
|
||||
537
frontend/src/pages/Products.tsx
Normal file
@@ -0,0 +1,537 @@
|
||||
import React, { useState, useEffect, useRef } from 'react';
|
||||
import { Plus, X, Search, Filter, MoreVertical, RefreshCw, Edit2, Power, PowerOff, Tag, Package, Image as ImageIcon, Barcode, DollarSign, ChevronDown, Clock, Check, Trash2, Database } from 'lucide-react';
|
||||
|
||||
interface ProductSession {
|
||||
id?: number;
|
||||
dayOfWeek: string;
|
||||
active: boolean;
|
||||
startTime: string;
|
||||
endTime: string;
|
||||
}
|
||||
|
||||
interface Product {
|
||||
id?: number;
|
||||
productId: string;
|
||||
name: string;
|
||||
category: string;
|
||||
description: string;
|
||||
basePrice: number;
|
||||
price: number;
|
||||
offerPrice: number;
|
||||
discountPercent: number;
|
||||
discountAmount: number;
|
||||
counter: string;
|
||||
tag: string;
|
||||
parcelCharges: number;
|
||||
barcode: string;
|
||||
attributesOptional: boolean;
|
||||
veg: boolean;
|
||||
hasAllergy: boolean;
|
||||
parcelNotAllowed: boolean;
|
||||
sessionOptional: boolean;
|
||||
sessions: ProductSession[];
|
||||
imageData: string;
|
||||
active: boolean;
|
||||
stock: number;
|
||||
stalls?: { id: number; name: string }[];
|
||||
}
|
||||
|
||||
interface Stall {
|
||||
id: number;
|
||||
name: string;
|
||||
baseItems?: { id: number; name: string }[];
|
||||
}
|
||||
|
||||
interface BaseItem {
|
||||
id: number;
|
||||
name: string;
|
||||
}
|
||||
|
||||
const DAYS = ['SUNDAY', 'MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', 'FRIDAY', 'SATURDAY'];
|
||||
|
||||
const getDefaultSessions = (): ProductSession[] =>
|
||||
DAYS.map(day => ({ dayOfWeek: day, active: true, startTime: '00:00', endTime: '23:59' }));
|
||||
|
||||
const emptyProduct: Product = {
|
||||
productId: '',
|
||||
name: '',
|
||||
category: '',
|
||||
description: '',
|
||||
basePrice: 0,
|
||||
price: 0,
|
||||
offerPrice: 0,
|
||||
discountPercent: 0,
|
||||
discountAmount: 0,
|
||||
counter: '',
|
||||
tag: '',
|
||||
parcelCharges: 0,
|
||||
barcode: '',
|
||||
attributesOptional: false,
|
||||
veg: false,
|
||||
hasAllergy: false,
|
||||
parcelNotAllowed: false,
|
||||
sessionOptional: false,
|
||||
sessions: getDefaultSessions(),
|
||||
imageData: '',
|
||||
active: true,
|
||||
stock: 0
|
||||
};
|
||||
|
||||
const Products = () => {
|
||||
const [products, setProducts] = useState<Product[]>([]);
|
||||
const [baseItems, setBaseItems] = useState<BaseItem[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [showModal, setShowModal] = useState(false);
|
||||
const [showSessionModal, setShowSessionModal] = useState(false);
|
||||
const [editingProduct, setEditingProduct] = useState<Product | null>(null);
|
||||
const [formData, setFormData] = useState<Product>(emptyProduct);
|
||||
const [allStalls, setAllStalls] = useState<Stall[]>([]);
|
||||
const [openMenuId, setOpenMenuId] = useState<number | null>(null);
|
||||
const menuRef = useRef<HTMLDivElement>(null);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
fetchProducts();
|
||||
fetchBaseItems();
|
||||
fetchAllStalls();
|
||||
const handleClickOutside = (event: MouseEvent) => {
|
||||
if (menuRef.current && !menuRef.current.contains(event.target as Node)) {
|
||||
setOpenMenuId(null);
|
||||
}
|
||||
};
|
||||
document.addEventListener('mousedown', handleClickOutside);
|
||||
return () => document.removeEventListener('mousedown', handleClickOutside);
|
||||
}, []);
|
||||
|
||||
const fetchProducts = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const response = await fetch('http://localhost:8080/api/products');
|
||||
const data = await response.json();
|
||||
setProducts(data);
|
||||
} catch (error) {
|
||||
console.error('Error fetching products:', error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const fetchBaseItems = async () => {
|
||||
try {
|
||||
const response = await fetch('http://localhost:8080/api/base-items');
|
||||
const data = await response.json();
|
||||
setBaseItems(data);
|
||||
} catch (error) {
|
||||
console.error('Error fetching base items:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const fetchAllStalls = async () => {
|
||||
try {
|
||||
const response = await fetch('http://localhost:8080/api/stalls');
|
||||
const data = await response.json();
|
||||
setAllStalls(data);
|
||||
} catch (error) {
|
||||
console.error('Error fetching stalls:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
const url = editingProduct
|
||||
? `http://localhost:8080/api/products/${editingProduct.id}`
|
||||
: 'http://localhost:8080/api/products';
|
||||
const method = editingProduct ? 'PUT' : 'POST';
|
||||
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
method,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(formData),
|
||||
});
|
||||
if (response.ok) {
|
||||
setShowModal(false);
|
||||
setEditingProduct(null);
|
||||
setFormData(emptyProduct);
|
||||
fetchProducts();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error saving product:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleEdit = (product: Product) => {
|
||||
setEditingProduct(product);
|
||||
setFormData({
|
||||
...product,
|
||||
sessions: product.sessions && product.sessions.length > 0 ? product.sessions : getDefaultSessions()
|
||||
});
|
||||
setShowModal(true);
|
||||
setOpenMenuId(null);
|
||||
};
|
||||
|
||||
const handleToggleActive = async (product: Product) => {
|
||||
try {
|
||||
const response = await fetch(`http://localhost:8080/api/products/${product.id}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ ...product, active: !product.active }),
|
||||
});
|
||||
if (response.ok) {
|
||||
fetchProducts();
|
||||
setOpenMenuId(null);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error toggling active status:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleToggleStock = async (product: Product) => {
|
||||
try {
|
||||
const response = await fetch(`http://localhost:8080/api/products/${product.id}/toggle-stock`, {
|
||||
method: 'PATCH',
|
||||
});
|
||||
if (response.ok) {
|
||||
fetchProducts();
|
||||
setOpenMenuId(null);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error toggling stock status:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (product: Product) => {
|
||||
if (!window.confirm(`Are you sure you want to delete ${product.name}?`)) return;
|
||||
try {
|
||||
const response = await fetch(`http://localhost:8080/api/products/${product.id}`, {
|
||||
method: 'DELETE',
|
||||
});
|
||||
if (response.ok) {
|
||||
fetchProducts();
|
||||
setOpenMenuId(null);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error deleting product:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (file) {
|
||||
const reader = new FileReader();
|
||||
reader.onloadend = () => {
|
||||
setFormData({ ...formData, imageData: reader.result as string });
|
||||
};
|
||||
reader.readAsDataURL(file);
|
||||
}
|
||||
};
|
||||
|
||||
const updateSession = (index: number, updates: Partial<ProductSession>) => {
|
||||
const newSessions = [...formData.sessions];
|
||||
newSessions[index] = { ...newSessions[index], ...updates };
|
||||
setFormData({ ...formData, sessions: newSessions });
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="p-8 font-inter">
|
||||
<div className="flex justify-between items-center mb-8">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-[#1e293b]">Products</h1>
|
||||
<p className="text-sm text-[#64748b]">Manage your product catalog and inventory</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => {
|
||||
setEditingProduct(null);
|
||||
setFormData(emptyProduct);
|
||||
setShowModal(true);
|
||||
}}
|
||||
className="bg-[#231651] text-white px-4 py-2 rounded-xl flex items-center gap-2 shadow-lg shadow-[#231651]/20 hover:scale-[1.02] active:scale-95 transition-all"
|
||||
>
|
||||
<Plus size={20} />
|
||||
<span>Add New Product</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Filters Bar */}
|
||||
<div className="bg-white p-4 rounded-xl border border-[#e2e8f0] mb-6 flex flex-wrap gap-4 items-center justify-between shadow-sm">
|
||||
<div className="flex gap-4 items-center flex-1">
|
||||
<div className="relative flex-1 max-w-md">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 text-[#94a3b8]" size={18} />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Search products..."
|
||||
className="w-full pl-10 pr-4 py-2 bg-gray-50 border border-[#e2e8f0] rounded-lg text-sm focus:outline-none focus:border-[#231651]/30 transition-all"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<button onClick={fetchProducts} className="p-2 text-[#64748b] hover:bg-gray-100 rounded-lg transition-all">
|
||||
<RefreshCw size={18} className={loading ? 'animate-spin' : ''} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Table */}
|
||||
<div className="bg-white rounded-xl border border-[#e2e8f0] shadow-sm">
|
||||
<div className="overflow-x-visible">
|
||||
<table className="w-full text-left border-collapse">
|
||||
<thead>
|
||||
<tr className="bg-gray-50/50 border-b border-[#e2e8f0]">
|
||||
<th className="px-6 py-4 text-xs font-bold text-[#64748b] uppercase tracking-wider">Product Info</th>
|
||||
<th className="px-6 py-4 text-xs font-bold text-[#64748b] uppercase tracking-wider">Category</th>
|
||||
<th className="px-6 py-4 text-xs font-bold text-[#64748b] uppercase tracking-wider">Selling at</th>
|
||||
<th className="px-6 py-4 text-xs font-bold text-[#64748b] uppercase tracking-wider">Price Details</th>
|
||||
<th className="px-6 py-4 text-xs font-bold text-[#64748b] uppercase tracking-wider">Status</th>
|
||||
<th className="px-6 py-4 text-xs font-bold text-[#64748b] uppercase tracking-wider text-right">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-[#e2e8f0]">
|
||||
{loading ? (
|
||||
<tr><td colSpan={5} className="px-6 py-12 text-center text-[#64748b]"><RefreshCw className="animate-spin inline mr-2" />Loading...</td></tr>
|
||||
) : products.map((product) => (
|
||||
<tr key={product.id} className="hover:bg-gray-50/50 transition-all">
|
||||
<td className="px-6 py-4">
|
||||
<div className="flex items-center gap-3">
|
||||
{product.imageData ? (
|
||||
<img src={product.imageData} alt={product.name} className="w-10 h-10 rounded-lg object-cover" />
|
||||
) : (
|
||||
<div className="w-10 h-10 rounded-lg bg-gray-100 flex items-center justify-center text-[#231651]"><Package size={20} /></div>
|
||||
)}
|
||||
<div>
|
||||
<p className="text-sm font-bold text-[#1e293b]">{product.name}</p>
|
||||
<p className="text-[11px] text-[#64748b]">ID: {product.productId || 'N/A'}</p>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-6 py-4">
|
||||
<span className="px-2.5 py-1 bg-blue-50 text-blue-600 rounded-lg text-xs font-semibold">{product.category}</span>
|
||||
</td>
|
||||
<td className="px-6 py-4">
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{(() => {
|
||||
// Combine direct stalls with stalls that have this product's category in their baseItems
|
||||
const directStalls = product.stalls || [];
|
||||
const indirectStalls = allStalls.filter(s =>
|
||||
s.baseItems?.some(bi => bi.name.toLowerCase() === product.category?.toLowerCase())
|
||||
).map(s => ({ id: s.id, name: s.name }));
|
||||
|
||||
// Unique stalls by ID
|
||||
const combinedStalls = Array.from(
|
||||
new Map([...directStalls, ...indirectStalls].map(s => [s.id, s])).values()
|
||||
);
|
||||
|
||||
return combinedStalls.length > 0 ? (
|
||||
combinedStalls.map(stall => (
|
||||
<span key={stall.id} className="px-2 py-0.5 bg-purple-50 text-purple-600 rounded-md text-[10px] font-bold border border-purple-100 italic whitespace-nowrap">
|
||||
{stall.name}
|
||||
</span>
|
||||
))
|
||||
) : (
|
||||
<span className="text-[10px] text-[#94a3b8] italic">Not Assigned</span>
|
||||
);
|
||||
})()}
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-6 py-4 text-sm font-bold text-[#1e293b]">₹{product.price}</td>
|
||||
<td className="px-6 py-4">
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<span className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-bold w-fit ${product.active ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-600'}`}>
|
||||
<div className={`w-1.5 h-1.5 rounded-full ${product.active ? 'bg-green-500' : 'bg-gray-400'}`} />
|
||||
{product.active ? 'Active' : 'Inactive'}
|
||||
</span>
|
||||
<span className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-bold w-fit ${product.stock > 0 ? 'bg-orange-100 text-orange-700' : 'bg-red-100 text-red-700'}`}>
|
||||
<Database size={12} />
|
||||
{product.stock > 0 ? `In Stock (${product.stock})` : 'Out of Stock'}
|
||||
</span>
|
||||
</div>
|
||||
</td>
|
||||
<td className={`px-6 py-4 text-right relative ${openMenuId === product.id ? 'z-[100]' : 'z-0'}`}>
|
||||
<button onClick={() => setOpenMenuId(openMenuId === product.id ? null : (product.id as number))} className="p-1.5 text-[#94a3b8] hover:text-[#231651] rounded-lg transition-colors">
|
||||
<MoreVertical size={18} />
|
||||
</button>
|
||||
{openMenuId === product.id && (
|
||||
<div
|
||||
ref={menuRef}
|
||||
onMouseDown={(e) => e.stopPropagation()}
|
||||
className="absolute right-6 top-12 w-48 bg-white rounded-xl shadow-2xl border border-[#e2e8f0] z-[110] overflow-hidden animate-in fade-in slide-in-from-top-2 duration-200"
|
||||
>
|
||||
<button onClick={() => handleEdit(product)} className="w-full flex items-center gap-3 px-4 py-3 text-sm hover:bg-gray-50 text-[#475569] font-medium"><Edit2 size={16} />Edit</button>
|
||||
<button onClick={() => handleToggleStock(product)} className="w-full flex items-center gap-3 px-4 py-3 text-sm hover:bg-gray-50 text-[#475569] font-medium border-t border-[#f1f5f9]">
|
||||
<Database size={16} className={product.stock > 0 ? "text-orange-500" : "text-green-500"} />
|
||||
{product.stock > 0 ? "Mark Out of Stock" : "Mark In Stock"}
|
||||
</button>
|
||||
<button onClick={() => handleToggleActive(product)} className="w-full flex items-center gap-3 px-4 py-3 text-sm hover:bg-gray-50 text-[#475569] font-medium border-t border-[#f1f5f9]">
|
||||
{product.active ? <><PowerOff size={16} className="text-red-500" />Deactivate</> : <><Power size={16} className="text-green-500" />Activate</>}
|
||||
</button>
|
||||
<button onClick={() => handleDelete(product)} className="w-full flex items-center gap-3 px-4 py-3 text-sm hover:bg-gray-50 text-red-600 font-medium border-t border-[#f1f5f9]"><Trash2 size={16} />Delete</button>
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Product Modal */}
|
||||
{showModal && (
|
||||
<div className="fixed inset-0 bg-[#231651]/20 backdrop-blur-sm z-[100] flex items-center justify-center p-4 overflow-y-auto">
|
||||
<div className="bg-white rounded-3xl w-full max-w-5xl shadow-2xl my-8 overflow-hidden">
|
||||
<div className="px-8 py-6 border-b border-[#e2e8f0] flex justify-between items-center bg-gray-50/50">
|
||||
<h2 className="text-xl font-bold text-[#1e293b]">{editingProduct ? 'Edit Product' : 'Add New Product'}</h2>
|
||||
<button onClick={() => setShowModal(false)} className="p-2 hover:bg-gray-200 rounded-full"><X size={24} className="text-[#64748b]" /></button>
|
||||
</div>
|
||||
<form onSubmit={handleSubmit} className="p-8">
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
|
||||
<div className="space-y-4">
|
||||
<div><label className="block text-[11px] uppercase font-bold text-[#64748b] mb-1.5">Product ID</label><input type="text" value={formData.productId} onChange={(e) => setFormData({ ...formData, productId: e.target.value })} className="w-full px-4 py-3 border border-[#e2e8f0] rounded-xl text-sm" /></div>
|
||||
<div><label className="block text-[11px] uppercase font-bold text-[#64748b] mb-1.5">Product Name *</label><input required type="text" value={formData.name} onChange={(e) => setFormData({ ...formData, name: e.target.value })} className="w-full px-4 py-3 border border-[#e2e8f0] rounded-xl text-sm font-semibold" /></div>
|
||||
<div>
|
||||
<label className="block text-[11px] uppercase font-bold text-[#64748b] mb-1.5">Category</label>
|
||||
<select required value={formData.category} onChange={(e) => setFormData({ ...formData, category: e.target.value })} className="w-full px-4 py-3 border border-[#e2e8f0] rounded-xl text-sm">
|
||||
<option value="">Select Category</option>
|
||||
{baseItems.map(item => <option key={item.id} value={item.name}>{item.name}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
<div><label className="block text-[11px] uppercase font-bold text-[#64748b] mb-1.5">Description</label><textarea value={formData.description} onChange={(e) => setFormData({ ...formData, description: e.target.value })} rows={3} className="w-full px-4 py-3 border border-[#e2e8f0] rounded-xl text-sm resize-none" /></div>
|
||||
</div>
|
||||
<div className="space-y-4">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div><label className="block text-[11px] uppercase font-bold text-[#64748b] mb-1.5">Base Price</label><input type="number" value={formData.basePrice} onChange={(e) => setFormData({ ...formData, basePrice: parseFloat(e.target.value) || 0 })} className="w-full px-4 py-3 border border-[#e2e8f0] rounded-xl text-sm" /></div>
|
||||
<div><label className="block text-[11px] uppercase font-bold text-[#64748b] mb-1.5">Sale Price</label><input type="number" value={formData.price} onChange={(e) => setFormData({ ...formData, price: parseFloat(e.target.value) || 0 })} className="w-full px-4 py-3 border border-[#e2e8f0] rounded-xl text-sm font-bold" /></div>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div><label className="block text-[11px] uppercase font-bold text-[#64748b] mb-1.5">Discount %</label><input type="number" value={formData.discountPercent} onChange={(e) => setFormData({ ...formData, discountPercent: parseFloat(e.target.value) || 0 })} className="w-full px-4 py-3 border border-[#e2e8f0] rounded-xl text-sm" /></div>
|
||||
<div><label className="block text-[11px] uppercase font-bold text-[#64748b] mb-1.5">Offer Price</label><input type="number" value={formData.offerPrice} onChange={(e) => setFormData({ ...formData, offerPrice: parseFloat(e.target.value) || 0 })} className="w-full px-4 py-3 border border-[#e2e8f0] rounded-xl text-sm" /></div>
|
||||
</div>
|
||||
<div><label className="block text-[11px] uppercase font-bold text-[#64748b] mb-1.5">Barcode</label><input type="text" value={formData.barcode} onChange={(e) => setFormData({ ...formData, barcode: e.target.value })} className="w-full px-4 py-3 border border-[#e2e8f0] rounded-xl text-sm" /></div>
|
||||
<div><label className="block text-[11px] uppercase font-bold text-[#64748b] mb-1.5">Stock Quantity</label><input type="number" value={formData.stock} onChange={(e) => setFormData({ ...formData, stock: parseInt(e.target.value) || 0 })} className="w-full px-4 py-3 border border-[#e2e8f0] rounded-xl text-sm font-semibold" /></div>
|
||||
<div><label className="block text-[11px] uppercase font-bold text-[#64748b] mb-1.5">Counter</label>
|
||||
<select value={formData.counter} onChange={(e) => setFormData({ ...formData, counter: e.target.value })} className="w-full px-4 py-3 border border-[#e2e8f0] rounded-xl text-sm"><option value="">Select Counter</option><option value="Main Counter">Main Counter</option></select></div>
|
||||
</div>
|
||||
<div className="space-y-4">
|
||||
<div className="group">
|
||||
<label className="block text-[11px] uppercase font-bold text-[#64748b] mb-1.5 ml-1">Product Image</label>
|
||||
<div
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
className="border-2 border-dashed border-[#e2e8f0] rounded-2xl p-6 flex flex-col items-center justify-center text-[#94a3b8] hover:border-[#231651]/30 hover:bg-gray-50 transition-all cursor-pointer h-40 overflow-hidden"
|
||||
>
|
||||
{formData.imageData ? (
|
||||
<img src={formData.imageData} alt="Preview" className="w-full h-full object-contain" />
|
||||
) : (
|
||||
<>
|
||||
<ImageIcon size={32} strokeWidth={1.5} className="mb-2" />
|
||||
<p className="text-[10px] font-bold uppercase tracking-wider text-center">Drop or Select image</p>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<input ref={fileInputRef} type="file" accept="image/*" onChange={handleImageChange} className="hidden" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Advanced Options */}
|
||||
<div className="mt-8 space-y-6">
|
||||
<div className="flex flex-wrap gap-8 p-6 bg-gray-50 rounded-2xl border border-[#e2e8f0]">
|
||||
<div className="flex flex-col gap-4 min-w-[200px]">
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div><p className="text-sm font-bold text-[#1e293b]">Additional Attributes</p></div>
|
||||
<button type="button" onClick={() => setFormData({ ...formData, attributesOptional: !formData.attributesOptional })} className={`w-11 h-6 rounded-full relative transition-all ${formData.attributesOptional ? 'bg-[#231651]' : 'bg-gray-300'}`}><div className={`absolute top-1 left-1 w-4 h-4 bg-white rounded-full transition-transform ${formData.attributesOptional ? 'translate-x-5' : ''}`} /></button>
|
||||
</div>
|
||||
{formData.attributesOptional && (
|
||||
<div className="flex gap-4 animate-in fade-in slide-in-from-left-2">
|
||||
<label className="flex items-center gap-2 cursor-pointer"><input type="checkbox" checked={formData.veg} onChange={(e) => setFormData({ ...formData, veg: e.target.checked })} className="w-4 h-4 rounded text-[#231651]" /><span className="text-xs font-semibold">Veg</span></label>
|
||||
<label className="flex items-center gap-2 cursor-pointer"><input type="checkbox" checked={formData.hasAllergy} onChange={(e) => setFormData({ ...formData, hasAllergy: e.target.checked })} className="w-4 h-4 rounded text-[#231651]" /><span className="text-xs font-semibold">Allergy</span></label>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-4 min-w-[200px]">
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div><p className="text-sm font-bold text-[#1e293b]">Session</p></div>
|
||||
<button type="button" onClick={() => setFormData({ ...formData, sessionOptional: !formData.sessionOptional })} className={`w-11 h-6 rounded-full relative transition-all ${formData.sessionOptional ? 'bg-[#231651]' : 'bg-gray-300'}`}><div className={`absolute top-1 left-1 w-4 h-4 bg-white rounded-full transition-transform ${formData.sessionOptional ? 'translate-x-5' : ''}`} /></button>
|
||||
</div>
|
||||
{formData.sessionOptional && (
|
||||
<button type="button" onClick={() => setShowSessionModal(true)} className="flex items-center gap-2 px-4 py-2 bg-white border border-[#231651]/20 text-[#231651] text-xs font-bold rounded-xl hover:bg-[#231651]/5 transition-all w-fit animate-in fade-in slide-in-from-left-2"><Clock size={14} /> Configure Session</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-4 mt-10">
|
||||
<button type="button" onClick={() => setShowModal(false)} className="flex-1 px-8 py-4 border-2 border-[#e2e8f0] text-[#64748b] font-bold rounded-2xl hover:bg-gray-50 transition-all">Discard</button>
|
||||
<button type="submit" className="flex-[2] px-8 py-4 bg-[#231651] text-white font-bold rounded-2xl shadow-xl hover:scale-[1.01] transition-all flex items-center justify-center gap-2"><Package size={20} /><span>{editingProduct ? 'Update Product' : 'Save Product'}</span></button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Session Configuration Modal */}
|
||||
{showSessionModal && (
|
||||
<div className="fixed inset-0 bg-[#231651]/40 backdrop-blur-md z-[110] flex items-center justify-center p-4">
|
||||
<div className="bg-white rounded-[40px] w-full max-w-4xl shadow-2xl overflow-hidden animate-in zoom-in duration-300">
|
||||
<div className="p-10">
|
||||
<h2 className="text-2xl font-bold text-[#1e293b] text-center mb-8">Select the session that the time product show in menu</h2>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6 max-h-[60vh] overflow-y-auto px-2 custom-scrollbar">
|
||||
{formData.sessions.map((session, index) => (
|
||||
<div key={session.dayOfWeek} className="p-6 rounded-3xl border-2 border-[#e2e8f0] relative">
|
||||
<div className="flex items-center justify-center gap-3 mb-6">
|
||||
<div
|
||||
onClick={() => updateSession(index, { active: !session.active })}
|
||||
className={`w-6 h-6 rounded-md flex items-center justify-center cursor-pointer transition-all ${session.active ? 'bg-[#51133d]' : 'bg-gray-200'}`}
|
||||
>
|
||||
{session.active && <Check size={14} className="text-white" strokeWidth={4} />}
|
||||
</div>
|
||||
<span className="text-lg font-bold text-[#1e293b]">{session.dayOfWeek}</span>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4 opacity-100 transition-opacity">
|
||||
<div className="relative">
|
||||
<label className="absolute -top-2 left-4 bg-white px-1 text-[10px] font-bold text-[#94a3b8] z-10">Start Time</label>
|
||||
<div className="flex items-center justify-between px-5 py-4 bg-white border border-[#e2e8f0] rounded-2xl">
|
||||
<input
|
||||
type="time"
|
||||
disabled={!session.active}
|
||||
value={session.startTime}
|
||||
onChange={(e) => updateSession(index, { startTime: e.target.value })}
|
||||
className="bg-transparent border-none outline-none text-sm font-bold text-[#1e293b] w-full disabled:text-gray-400"
|
||||
/>
|
||||
<Clock size={18} className="text-[#94a3b8]" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="relative">
|
||||
<label className="absolute -top-2 left-4 bg-white px-1 text-[10px] font-bold text-[#94a3b8] z-10">End Time</label>
|
||||
<div className="flex items-center justify-between px-5 py-4 bg-white border border-[#e2e8f0] rounded-2xl">
|
||||
<input
|
||||
type="time"
|
||||
disabled={!session.active}
|
||||
value={session.endTime}
|
||||
onChange={(e) => updateSession(index, { endTime: e.target.value })}
|
||||
className="bg-transparent border-none outline-none text-sm font-bold text-[#1e293b] w-full disabled:text-gray-400"
|
||||
/>
|
||||
<Clock size={18} className="text-[#94a3b8]" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex justify-end gap-4 mt-10 pt-4">
|
||||
<button onClick={() => setShowSessionModal(false)} className="px-10 py-4 bg-[#f46d43] text-white font-bold rounded-2xl shadow-lg hover:scale-105 transition-all">Close</button>
|
||||
<button onClick={() => setShowSessionModal(false)} className="px-10 py-4 bg-[#3d1351] text-white font-bold rounded-2xl shadow-lg hover:scale-105 transition-all">Submit</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<style dangerouslySetInnerHTML={{ __html: `
|
||||
.custom-scrollbar::-webkit-scrollbar { width: 6px; }
|
||||
.custom-scrollbar::-webkit-scrollbar-track { background: transparent; }
|
||||
.custom-scrollbar::-webkit-scrollbar-thumb { background: #e2e8f0; border-radius: 10px; }
|
||||
` }} />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Products;
|
||||
325
frontend/src/pages/PurchaseAnalytics.tsx
Normal file
@@ -0,0 +1,325 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import {
|
||||
TrendingUp,
|
||||
TrendingDown,
|
||||
Calendar,
|
||||
Filter,
|
||||
DollarSign,
|
||||
Percent,
|
||||
Search,
|
||||
Loader2
|
||||
} from 'lucide-react';
|
||||
import { format, startOfMonth, endOfMonth } from 'date-fns';
|
||||
|
||||
interface StatBoxProps {
|
||||
title: string;
|
||||
value: string | number;
|
||||
subtext: string;
|
||||
icon: any;
|
||||
colorClass: string;
|
||||
}
|
||||
|
||||
const StatBox = ({ title, value, subtext, icon: Icon, colorClass }: StatBoxProps) => (
|
||||
<div className="bg-white p-6 rounded-2xl border border-[#e2e8f0] flex-1 shadow-sm">
|
||||
<div className="flex justify-between items-start mb-4">
|
||||
<div>
|
||||
<p className="text-[10px] font-bold text-[#64748b] uppercase tracking-wider mb-1">{title}</p>
|
||||
<h3 className="text-2xl font-black text-[#1e293b]">₹{value}</h3>
|
||||
</div>
|
||||
<div className={`p-2.5 rounded-xl ${colorClass}`}>
|
||||
<Icon size={18} />
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-[11px] text-[#94a3b8] font-medium leading-relaxed">{subtext}</p>
|
||||
</div>
|
||||
);
|
||||
|
||||
interface ProductAnalytics {
|
||||
product: string;
|
||||
qty: number;
|
||||
basePrice: number;
|
||||
currentPrice: number;
|
||||
inflatedAmount: number;
|
||||
deflatedAmount: number;
|
||||
rate: number;
|
||||
trend: 'up' | 'down' | 'stable';
|
||||
}
|
||||
|
||||
const PurchaseAnalytics = () => {
|
||||
const [searchTerm, setSearchTerm] = useState('');
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [analytics, setAnalytics] = useState<ProductAnalytics[]>([]);
|
||||
const [filterType, setFilterType] = useState<'all' | 'up' | 'down'>('all');
|
||||
const [summary, setSummary] = useState({
|
||||
totalBase: 0,
|
||||
totalInflated: 0,
|
||||
totalDeflated: 0,
|
||||
inflationRate: 0,
|
||||
inflatedCount: 0,
|
||||
deflatedCount: 0
|
||||
});
|
||||
|
||||
const [dateRange] = useState({
|
||||
start: startOfMonth(new Date()),
|
||||
end: endOfMonth(new Date())
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
fetchData();
|
||||
}, []);
|
||||
|
||||
const fetchData = async () => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
const response = await fetch('/api/purchases/orders');
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
processAnalytics(data);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error fetching analytics:', error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const processAnalytics = (purchaseOrders: any[]) => {
|
||||
const productStats: Record<string, { qty: number, prices: { date: Date, rate: number }[] }> = {};
|
||||
|
||||
purchaseOrders.forEach(order => {
|
||||
order.items?.forEach((item: any) => {
|
||||
if (!productStats[item.productName]) {
|
||||
productStats[item.productName] = { qty: 0, prices: [] };
|
||||
}
|
||||
productStats[item.productName].qty += item.quantity;
|
||||
productStats[item.productName].prices.push({
|
||||
date: new Date(order.date),
|
||||
rate: item.rate
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
let totalBase = 0;
|
||||
let totalInflated = 0;
|
||||
let totalDeflated = 0;
|
||||
let inflatedCount = 0;
|
||||
let deflatedCount = 0;
|
||||
|
||||
const analyzedData: ProductAnalytics[] = Object.keys(productStats).map(productName => {
|
||||
const stats = productStats[productName];
|
||||
stats.prices.sort((a, b) => a.date.getTime() - b.date.getTime());
|
||||
|
||||
const basePrice = stats.prices[0].rate;
|
||||
const currentPrice = stats.prices[stats.prices.length - 1].rate;
|
||||
const qty = stats.qty;
|
||||
|
||||
const priceDiff = currentPrice - basePrice;
|
||||
const impactAmount = Math.abs(priceDiff * qty);
|
||||
|
||||
let inflatedAmount = 0;
|
||||
let deflatedAmount = 0;
|
||||
let trend: 'up' | 'down' | 'stable' = 'stable';
|
||||
|
||||
if (priceDiff > 0) {
|
||||
inflatedAmount = impactAmount;
|
||||
totalInflated += inflatedAmount;
|
||||
inflatedCount++;
|
||||
trend = 'up';
|
||||
} else if (priceDiff < 0) {
|
||||
deflatedAmount = impactAmount;
|
||||
totalDeflated += deflatedAmount;
|
||||
deflatedCount++;
|
||||
trend = 'down';
|
||||
}
|
||||
|
||||
totalBase += basePrice * qty;
|
||||
const rate = basePrice !== 0 ? (Math.abs(priceDiff) / basePrice) * 100 : 0;
|
||||
|
||||
return {
|
||||
product: productName,
|
||||
qty,
|
||||
basePrice,
|
||||
currentPrice,
|
||||
inflatedAmount,
|
||||
deflatedAmount,
|
||||
rate,
|
||||
trend
|
||||
};
|
||||
});
|
||||
|
||||
const inflationRate = totalBase !== 0 ? (totalInflated / totalBase) * 100 : 0;
|
||||
|
||||
setAnalytics(analyzedData);
|
||||
setSummary({
|
||||
totalBase,
|
||||
totalInflated,
|
||||
totalDeflated,
|
||||
inflationRate,
|
||||
inflatedCount,
|
||||
deflatedCount
|
||||
});
|
||||
};
|
||||
|
||||
const filteredAnalytics = analytics.filter(item => {
|
||||
const matchesSearch = item.product.toLowerCase().includes(searchTerm.toLowerCase());
|
||||
const matchesFilter = filterType === 'all' || item.trend === filterType;
|
||||
return matchesSearch && matchesFilter;
|
||||
});
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="h-full flex flex-col items-center justify-center gap-4">
|
||||
<Loader2 className="animate-spin text-[#521c4b]" size={40} />
|
||||
<p className="text-sm font-bold text-slate-500 uppercase tracking-widest">Calculating Market Analytics...</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="p-8 space-y-8 animate-in fade-in duration-500">
|
||||
{/* Header */}
|
||||
<div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="text-2xl font-black text-[#521c4b] tracking-tight uppercase">Purchase Analytics</h1>
|
||||
<div className="flex items-center gap-2 mt-1">
|
||||
<span className="bg-[#521c4b]/10 text-[#521c4b] text-[10px] font-bold px-2 py-0.5 rounded-full uppercase">
|
||||
Start: {format(dateRange.start, 'yyyy-MM-dd')}
|
||||
</span>
|
||||
<span className="bg-[#521c4b]/10 text-[#521c4b] text-[10px] font-bold px-2 py-0.5 rounded-full uppercase">
|
||||
End: {format(dateRange.end, 'yyyy-MM-dd')}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<button
|
||||
onClick={() => setFilterType('all')}
|
||||
className={`px-4 py-2 rounded-xl text-xs font-bold uppercase transition-all ${filterType === 'all' ? 'bg-[#521c4b] text-white shadow-lg' : 'bg-white border text-slate-500 border-slate-200 hover:bg-slate-50'}`}
|
||||
>
|
||||
Show All
|
||||
</button>
|
||||
<button title="Calendar" className="p-2.5 bg-white border border-[#e2e8f0] rounded-xl text-[#64748b] transition-all"><Calendar size={18} /></button>
|
||||
<button title="Filter" className="p-2.5 bg-white border border-[#e2e8f0] rounded-xl text-[#64748b] transition-all"><Filter size={18} /></button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Top Stats */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
|
||||
<StatBox title="Total Base Amount" value={summary.totalBase.toFixed(2)} subtext="Initial purchase costs" icon={DollarSign} colorClass="bg-gray-100 text-gray-500" />
|
||||
<StatBox title="Total Inflated Amount" value={summary.totalInflated.toFixed(2)} subtext="Extra cost from hikes" icon={TrendingUp} colorClass="bg-rose-100 text-rose-500" />
|
||||
<StatBox title="Total Deflated Amount" value={summary.totalDeflated.toFixed(2)} subtext="Actual savings realized" icon={TrendingDown} colorClass="bg-emerald-100 text-emerald-500" />
|
||||
<div className="bg-white p-6 rounded-2xl border border-[#e2e8f0] flex-1 shadow-sm">
|
||||
<div className="flex justify-between items-start mb-4">
|
||||
<div>
|
||||
<p className="text-[10px] font-bold text-[#64748b] uppercase tracking-wider mb-1">Inflation Rate</p>
|
||||
<h3 className="text-2xl font-black text-[#1e293b]">{summary.inflationRate.toFixed(2)}%</h3>
|
||||
</div>
|
||||
<div className="p-2.5 rounded-xl bg-violet-100 text-violet-500"><Percent size={18} /></div>
|
||||
</div>
|
||||
<p className="text-[11px] text-[#94a3b8] font-medium leading-relaxed">Overall price impact percentage</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
|
||||
<div className="lg:col-span-2 bg-white rounded-3xl border border-[#e2e8f0] shadow-sm overflow-hidden">
|
||||
<div className="p-6 border-b border-[#e2e8f0] flex items-center justify-between bg-slate-50/30">
|
||||
<h3 className="text-sm font-black text-[#1e293b] uppercase tracking-wider">
|
||||
{filterType === 'up' ? 'Price Hikes (Inflated)' : filterType === 'down' ? 'Savings (Deflated)' : 'Market Price Status'}
|
||||
</h3>
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 text-[#94a3b8]" size={14} />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Search products..."
|
||||
className="pl-9 pr-4 py-2 border border-[#e2e8f0] rounded-xl text-xs outline-none focus:border-[#521c4b]/30 transition-all font-medium"
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-left">
|
||||
<thead>
|
||||
<tr className="bg-slate-50/50">
|
||||
<th className="px-6 py-4 text-[10px] font-bold text-[#64748b] uppercase tracking-widest leading-none">Product</th>
|
||||
<th className="px-6 py-4 text-[10px] font-bold text-[#64748b] uppercase tracking-widest leading-none">Qty</th>
|
||||
<th className="px-6 py-4 text-[10px] font-bold text-[#64748b] uppercase tracking-widest leading-none text-right">Base Price</th>
|
||||
<th className="px-6 py-4 text-[10px] font-bold text-[#64748b] uppercase tracking-widest leading-none text-right">Impact Amount</th>
|
||||
<th className="px-6 py-4 text-[10px] font-bold text-[#64748b] uppercase tracking-widest leading-none text-center">Impact Rate</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-[#e2e8f0]">
|
||||
{filteredAnalytics.length === 0 ? (
|
||||
<tr><td colSpan={5} className="px-6 py-12 text-center text-slate-400 text-sm">No matching trends found</td></tr>
|
||||
) : (
|
||||
filteredAnalytics.map((item, idx) => (
|
||||
<tr key={idx} className="hover:bg-gray-50/50 transition-colors group">
|
||||
<td className="px-6 py-4"><p className="text-xs font-bold text-[#1e293b] group-hover:text-[#521c4b]">{item.product}</p></td>
|
||||
<td className="px-6 py-4 text-xs font-bold text-[#475569]">{item.qty}</td>
|
||||
<td className="px-6 py-4 text-xs font-bold text-[#475569] text-right">₹{item.basePrice.toFixed(2)}</td>
|
||||
<td className="px-6 py-4 text-right">
|
||||
<div className="flex flex-col items-end">
|
||||
<span className={`text-xs font-black ${item.trend === 'up' ? 'text-rose-500' : item.trend === 'down' ? 'text-emerald-500' : 'text-slate-400'}`}>
|
||||
{item.trend === 'up' ? '+' : item.trend === 'down' ? '-' : ''}₹{(item.inflatedAmount || item.deflatedAmount).toFixed(2)}
|
||||
</span>
|
||||
<p className="text-[10px] font-bold text-[#94a3b8] uppercase tracking-tighter">
|
||||
{item.trend === 'up' ? 'Incurred' : item.trend === 'down' ? 'Saved' : 'Neutral'}
|
||||
</p>
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-6 py-4 text-center">
|
||||
<span className={`inline-flex items-center px-2 py-0.5 rounded-lg text-[10px] font-bold ${item.trend === 'up' ? 'bg-rose-50 text-rose-600' : item.trend === 'down' ? 'bg-emerald-50 text-emerald-600' : 'bg-gray-100 text-gray-500'}`}>
|
||||
{item.rate.toFixed(1)}%
|
||||
</span>
|
||||
</td>
|
||||
</tr>
|
||||
))
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-6">
|
||||
<div className="bg-white p-6 rounded-3xl border border-[#e2e8f0] shadow-sm">
|
||||
<h3 className="text-sm font-black text-[#1e293b] uppercase tracking-wider mb-6">Market Trends</h3>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<button
|
||||
onClick={() => setFilterType('up')}
|
||||
className={`p-4 rounded-2xl flex flex-col items-center justify-center gap-2 transition-all cursor-pointer hover:border-[#521c4b]/50 border-2 ${filterType === 'up' ? 'bg-[#521c4b] text-white border-[#521c4b]' : 'bg-gray-50 text-slate-400 border-transparent hover:bg-slate-100'}`}
|
||||
>
|
||||
<TrendingUp size={20} />
|
||||
<span className="text-[10px] font-bold uppercase tracking-wider">Inflation</span>
|
||||
<span className="text-sm font-black">{summary.inflatedCount}</span>
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setFilterType('down')}
|
||||
className={`p-4 rounded-2xl flex flex-col items-center justify-center gap-2 transition-all cursor-pointer hover:border-emerald-600/50 border-2 ${filterType === 'down' ? 'bg-emerald-600 text-white border-emerald-600' : 'bg-gray-50 text-slate-400 border-transparent hover:bg-slate-100'}`}
|
||||
>
|
||||
<TrendingDown size={20} />
|
||||
<span className="text-[10px] font-bold uppercase tracking-wider">Deflation</span>
|
||||
<span className="text-sm font-black">{summary.deflatedCount}</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="mt-8 flex flex-col items-center py-8">
|
||||
<div className="relative w-32 h-32 flex items-center justify-center">
|
||||
<div className="absolute inset-0 rounded-full border-[10px] border-slate-100"></div>
|
||||
<div className="text-center">
|
||||
<p className="text-3xl font-black text-[#1e293b]">{filterType === 'up' ? summary.inflatedCount : filterType === 'down' ? summary.deflatedCount : summary.inflatedCount + summary.deflatedCount}</p>
|
||||
<p className="text-[10px] font-bold text-[#94a3b8] uppercase">Selected</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className={`mt-8 w-full p-4 rounded-2xl border ${filterType === 'up' ? 'bg-rose-50 border-rose-100 text-rose-600' : filterType === 'down' ? 'bg-emerald-50 border-emerald-100 text-emerald-600' : 'bg-slate-50 border-slate-200 text-slate-600'}`}>
|
||||
<p className="text-[10px] font-bold text-center uppercase">
|
||||
{filterType === 'up' ? 'Showing all price hikes' : filterType === 'down' ? 'Showing all price drops' : 'Select a trend to filter table'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default PurchaseAnalytics;
|
||||
219
frontend/src/pages/PurchaseSummary.tsx
Normal file
@@ -0,0 +1,219 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import {
|
||||
Filter,
|
||||
ArrowRight,
|
||||
Search,
|
||||
CheckCircle2,
|
||||
AlertCircle
|
||||
} from 'lucide-react';
|
||||
import {
|
||||
AreaChart,
|
||||
Area,
|
||||
XAxis,
|
||||
YAxis,
|
||||
Tooltip,
|
||||
ResponsiveContainer
|
||||
} from 'recharts';
|
||||
import { motion } from 'framer-motion';
|
||||
|
||||
const PurchaseSummary = () => {
|
||||
const [activeRange, setActiveRange] = useState('Today');
|
||||
const [data, setData] = useState<any>(null);
|
||||
const [bills, setBills] = useState<any[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchData = async () => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
// Fetch summary and bills in parallel
|
||||
const [summaryRes, billsRes] = await Promise.all([
|
||||
fetch('/api/purchases/summary'),
|
||||
fetch('/api/purchases/orders')
|
||||
]);
|
||||
|
||||
if (summaryRes.ok && billsRes.ok) {
|
||||
const summaryData = await summaryRes.json();
|
||||
const billsData = await billsRes.json();
|
||||
setData(summaryData);
|
||||
setBills(billsData);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error fetching purchase summary:', error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
fetchData();
|
||||
}, []);
|
||||
|
||||
if (isLoading || !data) {
|
||||
return (
|
||||
<div className="h-screen flex items-center justify-center bg-slate-50/50">
|
||||
<motion.div
|
||||
animate={{ scale: [1, 1.05, 1] }}
|
||||
transition={{ repeat: Infinity, duration: 2 }}
|
||||
className="text-[#521c4b] font-black uppercase tracking-widest text-xs"
|
||||
>
|
||||
Compiling Fiscal Intelligence...
|
||||
</motion.div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const summaryStats = [
|
||||
{ title: "Total Purchases", value: `₹${data.totalAmount.toLocaleString()}`, icon: AlertCircle, color: "text-rose-500", bg: "bg-rose-50" },
|
||||
{ title: "Total Credits", value: `₹${data.balanceAmount.toLocaleString()}`, icon: AlertCircle, color: "text-amber-500", bg: "bg-amber-50" },
|
||||
{ title: "Credit Paid", value: `₹${data.paidAmount.toLocaleString()}`, icon: AlertCircle, color: "text-emerald-500", bg: "bg-emerald-50" },
|
||||
{ title: "Balance Credit", value: `₹${data.balanceAmount.toLocaleString()}`, icon: AlertCircle, color: "text-indigo-500", bg: "bg-indigo-50" },
|
||||
{ title: "Bills to Pay", value: data.unpaidCount.toString(), icon: AlertCircle, color: "text-blue-500", bg: "bg-blue-50" }
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="p-8 space-y-8 bg-slate-50/50 min-h-screen font-inter">
|
||||
{/* Top Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex flex-col">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<button title="Back" className="p-1.5 hover:bg-slate-100 rounded-lg transition-all">
|
||||
<ArrowRight className="rotate-180 text-slate-400" size={18} />
|
||||
</button>
|
||||
<h2 className="text-xs font-black text-[#521c4b] uppercase tracking-widest">Purchases</h2>
|
||||
</div>
|
||||
<h1 className="text-2xl font-black text-slate-800">Summary</h1>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2 bg-white p-1 rounded-2xl border border-slate-200 shadow-sm">
|
||||
{['Yesterday', 'Today', 'Week', '30 Days'].map(range => (
|
||||
<button
|
||||
key={range}
|
||||
onClick={() => setActiveRange(range)}
|
||||
className={`px-4 py-2 text-[10px] font-black uppercase tracking-widest transition-all rounded-xl ${activeRange === range ? 'text-white bg-[#521c4b] shadow-md shadow-[#521c4b]/20' : 'text-slate-400 hover:text-slate-600'}`}
|
||||
>
|
||||
{range}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-12 gap-8">
|
||||
<div className="col-span-12 lg:col-span-5 space-y-6">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
{summaryStats.map((stat, idx) => (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, scale: 0.9 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
transition={{ delay: idx * 0.05 }}
|
||||
key={idx}
|
||||
whileHover={{ y: -4 }}
|
||||
className="bg-white p-6 rounded-[28px] border border-slate-100 shadow-sm transition-all"
|
||||
>
|
||||
<div className="flex items-center gap-3 mb-4">
|
||||
<div className={`p-2.5 rounded-xl ${stat.bg} ${stat.color}`}>
|
||||
<stat.icon size={20} />
|
||||
</div>
|
||||
<h3 className="text-[9px] font-black text-slate-400 uppercase tracking-widest leading-none">{stat.title}</h3>
|
||||
</div>
|
||||
<p className="text-2xl font-black text-slate-800">{stat.value}</p>
|
||||
</motion.div>
|
||||
))}
|
||||
|
||||
<div className="col-span-2 bg-[#521c4b] p-6 rounded-[32px] shadow-lg shadow-[#521c4b]/20 text-white relative overflow-hidden group">
|
||||
<div className="absolute -right-8 -top-8 w-32 h-32 bg-white/10 rounded-full blur-3xl" />
|
||||
<div className="relative z-10 flex items-end justify-between">
|
||||
<div>
|
||||
<h3 className="text-[10px] font-black uppercase tracking-widest opacity-80 text-white/70 mb-8">Bill Fulfillment</h3>
|
||||
<p className="text-4xl font-black mb-1">{bills.filter(b => b.status === 'PAID').length}</p>
|
||||
<p className="text-[10px] font-bold uppercase tracking-widest opacity-60">Cleared Bills</p>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<CheckCircle2 size={32} className="text-emerald-400 mb-6 ml-auto" />
|
||||
<p className="text-lg font-black text-emerald-400">
|
||||
{bills.length > 0 ? Math.round((bills.filter(b => b.status === 'PAID').length / bills.length) * 100) : 0}%
|
||||
</p>
|
||||
<p className="text-[9px] font-bold uppercase tracking-widest opacity-60">Success Rate</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="col-span-12 lg:col-span-7 space-y-8">
|
||||
<div className="bg-white p-8 rounded-[40px] border border-slate-100 shadow-sm h-full">
|
||||
<div className="flex items-center justify-between mb-8">
|
||||
<h3 className="text-sm font-black text-slate-800 tracking-tight uppercase tracking-widest">Purchase Trends</h3>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-3 h-3 rounded-full bg-[#f43f5e]" />
|
||||
<span className="text-[10px] font-black text-slate-400 uppercase tracking-widest">Procurement Volume</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="h-[280px]">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<AreaChart data={data.trend}>
|
||||
<defs>
|
||||
<linearGradient id="purchaseGradSum" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="5%" stopColor="#f43f5e" stopOpacity={0.1}/>
|
||||
<stop offset="95%" stopColor="#f43f5e" stopOpacity={0}/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<XAxis dataKey="date" axisLine={false} tickLine={false} tick={{fill: '#94a3b8', fontSize: 10, fontWeight: 700}} />
|
||||
<YAxis axisLine={false} tickLine={false} tick={{fill: '#94a3b8', fontSize: 10, fontWeight: 700}} tickFormatter={(v) => `₹${v/1000}k`} />
|
||||
<Tooltip contentStyle={{ borderRadius: '16px', border: 'none', boxShadow: '0 10px 25px -5px rgb(0 0 0 / 0.1)' }} />
|
||||
<Area type="monotone" dataKey="amount" stroke="#f43f5e" strokeWidth={4} fillOpacity={1} fill="url(#purchaseGradSum)" />
|
||||
</AreaChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-white rounded-[32px] border border-slate-100 shadow-sm p-8 pb-12">
|
||||
<div className="flex items-center justify-between mb-8">
|
||||
<h3 className="text-sm font-black text-slate-800 tracking-tight uppercase tracking-widest">Recent Activity</h3>
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" size={14} />
|
||||
<input type="text" title="Search" placeholder="Filter bills..." className="pl-9 pr-4 py-2 bg-slate-50 border border-slate-100 rounded-xl text-xs font-bold outline-none focus:border-[#521c4b] transition-all" />
|
||||
</div>
|
||||
<button title="Filter" className="p-2.5 bg-slate-50 rounded-xl text-slate-500 border border-slate-100"><Filter size={16} /></button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full">
|
||||
<thead>
|
||||
<tr className="bg-slate-50/50">
|
||||
<th className="px-6 py-4 text-left text-[10px] font-black text-slate-400 uppercase tracking-widest">Bill No</th>
|
||||
<th className="px-6 py-4 text-left text-[10px] font-black text-slate-400 uppercase tracking-widest">Date</th>
|
||||
<th className="px-6 py-4 text-left text-[10px] font-black text-slate-400 uppercase tracking-widest">Vendor</th>
|
||||
<th className="px-6 py-4 text-left text-[10px] font-black text-slate-400 uppercase tracking-widest">Status</th>
|
||||
<th className="px-6 py-4 text-right text-[10px] font-black text-slate-400 uppercase tracking-widest">Balance</th>
|
||||
<th className="px-6 py-4 text-right text-[10px] font-black text-slate-400 uppercase tracking-widest">Amount</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-slate-50">
|
||||
{bills.map((bill: any, idx: number) => (
|
||||
<tr key={idx} className="hover:bg-slate-50/50 transition-all cursor-pointer group">
|
||||
<td className="px-6 py-5 text-xs font-black text-slate-800">{bill.purchaseId}</td>
|
||||
<td className="px-6 py-5 text-xs font-bold text-slate-400">{bill.date}</td>
|
||||
<td className="px-6 py-5">
|
||||
<span className="text-xs font-black text-slate-700">{bill.vendor?.name || 'Walk-in'}</span>
|
||||
</td>
|
||||
<td className="px-6 py-5">
|
||||
<span className={`px-3 py-1.5 rounded-xl text-[9px] font-black uppercase tracking-widest ${bill.status === 'PAID' ? 'bg-emerald-50 text-emerald-600' : 'bg-rose-50 text-rose-600'}`}>
|
||||
{bill.status}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-6 py-5 text-right text-xs font-black text-rose-500">₹{bill.balance.toLocaleString()}</td>
|
||||
<td className="px-6 py-5 text-right text-xs font-black text-[#521c4b]">₹{bill.amount.toLocaleString()}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default PurchaseSummary;
|
||||