Initial Commit

main
Qasim Ali 2026-01-06 19:29:42 +05:00
commit 2a2f0d7a7c
53 changed files with 2280 additions and 0 deletions

2
.gitattributes vendored Normal file
View File

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

33
.gitignore vendored Normal file
View File

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

3
.mvn/wrapper/maven-wrapper.properties vendored Normal file
View File

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

295
mvnw vendored Normal file
View File

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

189
mvnw.cmd vendored Normal file
View File

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

134
pom.xml Normal file
View File

@ -0,0 +1,134 @@
<?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>4.0.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.utopia</groupId>
<artifactId>wms</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>UtopiaWMS</name>
<description>It is a warehouse managment system.</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-liquibase</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc</artifactId>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-liquibase-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<!-- JWT dependencies-->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.11.5</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.11.5</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.11.5</version>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

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

View File

@ -0,0 +1,22 @@
package com.utopia.wms.config.security;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import java.util.Collection;
public class ApiKeyAuthentication extends AbstractAuthenticationToken {
private final String tenantId;
public ApiKeyAuthentication(String tenantId, Collection<? extends GrantedAuthority> authorities) {
super(authorities);
this.tenantId = tenantId;
setAuthenticated(true);
}
@Override
public Object getCredentials() { return null; }
@Override
public Object getPrincipal() { return tenantId; }
}

View File

@ -0,0 +1,44 @@
package com.utopia.wms.config.security;
import com.utopia.wms.repository.user.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
@RequiredArgsConstructor
public class ApplicationConfig {
private final UserRepository userRepository;
@Bean
public UserDetailsService userDetailsService() {
return username -> userRepository.findByEmail(username)
.orElseThrow(() -> new UsernameNotFoundException("User not found"));
}
@Bean
public AuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider(userDetailsService());
authProvider.setPasswordEncoder(passwordEncoder());
return authProvider;
}
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
return config.getAuthenticationManager();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}

View File

@ -0,0 +1,38 @@
package com.utopia.wms.config.security;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
@EnableWebSecurity
@EnableMethodSecurity // Enables @PreAuthorize, @PostAuthorize, etc.
@RequiredArgsConstructor
public class SecurityConfig {
private final SecurityFilter securityFilter;
private final AuthenticationProvider authenticationProvider;
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf(AbstractHttpConfigurer::disable)
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/auth/**").permitAll()
.anyRequest().authenticated()
)
.authenticationProvider(authenticationProvider)
.addFilterBefore(securityFilter, UsernamePasswordAuthenticationFilter.class);
return http.build();
}
}

View File

@ -0,0 +1,81 @@
package com.utopia.wms.config.security;
import com.utopia.wms.exception.InvalidApiKeyException;
import com.utopia.wms.service.auth.ApiKeyService;
import com.utopia.wms.service.auth.JwtService;
import com.utopia.wms.util.TenantContext;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
@Component
@RequiredArgsConstructor
public class SecurityFilter extends OncePerRequestFilter {
private final JwtService jwtService;
private final ApiKeyService apiKeyService;
private final UserDetailsService userDetailsService;
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
String authHeader = request.getHeader("Authorization");
String apiKey = request.getHeader("X-API-KEY");
try {
// 1. Handle API Token Authentication (Scanner/ERP)
if (apiKey != null) {
String tenantId = null;
try {
tenantId = apiKeyService.validateKey(apiKey);
} catch (InvalidApiKeyException ignored) {}
if (tenantId != null) {
// API Keys usually have "SYSTEM" authority or specific scopes
ApiKeyAuthentication auth = new ApiKeyAuthentication(tenantId,
AuthorityUtils.createAuthorityList("API_ACCESS", "INVENTORY_VIEW"));
SecurityContextHolder.getContext().setAuthentication(auth);
TenantContext.setTenantId(tenantId);
}
}
// 2. Handle JWT Authentication (Web UI/Mobile App)
else if (authHeader != null && authHeader.startsWith("Bearer ")) {
String jwt = authHeader.substring(7);
String userEmail = jwtService.extractUsername(jwt);
String tenantId = jwtService.extractTenantId(jwt);
if (userEmail != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = this.userDetailsService.loadUserByUsername(userEmail);
if (jwtService.isTokenValid(jwt, userDetails)) {
UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
userDetails, null, userDetails.getAuthorities()
);
authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authToken);
// Set the SaaS Tenant Context
TenantContext.setTenantId(tenantId);
}
}
}
} finally {
filterChain.doFilter(request, response);
// Clear context after request finishes to prevent memory leaks in ThreadLocal
TenantContext.clear();
}
}
}

View File

@ -0,0 +1,32 @@
package com.utopia.wms.controller.apikey;
import com.utopia.wms.exception.InvalidApiKeyException;
import com.utopia.wms.service.auth.ApiKeyService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/v1/apikey")
@RequiredArgsConstructor
public class ApiKeyController {
private final ApiKeyService service;
@PostMapping("/generate")
public ResponseEntity<?> generateApiKey(@RequestParam String tenantId, @RequestParam String displayName) {
String key = service.createApiKey(tenantId, displayName);
return ResponseEntity.ok(key);
}
@GetMapping("/validate/{key}")
public ResponseEntity<?> validate(@PathVariable String key) throws InvalidApiKeyException {
String validatedKey = service.validateKey(key);
return ResponseEntity.ok(validatedKey);
}
}

View File

@ -0,0 +1,30 @@
package com.utopia.wms.controller.auth;
import com.utopia.wms.dto.auth.AuthRequest;
import com.utopia.wms.dto.auth.AuthResponse;
import com.utopia.wms.dto.auth.RegisterRequest;
import com.utopia.wms.service.auth.AuthService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
public class AuthController {
private final AuthService authService;
@PostMapping("/register")
public ResponseEntity<AuthResponse> register(@RequestBody RegisterRequest request) {
return ResponseEntity.ok(authService.register(request));
}
@PostMapping("/authenticate")
public ResponseEntity<AuthResponse> authenticate(@RequestBody AuthRequest request) {
return ResponseEntity.ok(authService.authenticate(request));
}
}

View File

@ -0,0 +1,59 @@
package com.utopia.wms.controller.movement;
import com.utopia.wms.dto.inventory.InventoryItemDTO;
import com.utopia.wms.dto.movement.StockMovementRequest;
import com.utopia.wms.service.movement.StockMovementService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/api/v1/movement")
@RequiredArgsConstructor
@Validated
public class StockMovementController {
private final StockMovementService movementService;
/**
* Internal Transfer: Move stock from one bin to another.
* Accessible by both JWT (Users) and API Key (Integrations).
*/
@PostMapping("/transfer")
@PreAuthorize("hasAuthority('INVENTORY_ADJUST')")
public ResponseEntity<Map<String, String>> performTransfer(@RequestBody StockMovementRequest request) {
movementService.moveStock(
request.inventoryItemId(),
request.targetLocationCode(),
request.quantity(),
request.reason() != null ? request.reason() : "Mobile Scanner Transfer"
);
Map<String, String> response = new HashMap<>();
response.put("status", "success");
response.put("message", "Stock moved successfully to " + request.targetLocationCode());
return ResponseEntity.ok(response);
}
/**
* Quick Inquiry: Scan a location to see what's inside.
*/
@GetMapping("/inquiry/{locationCode}")
@PreAuthorize("hasAuthority('INVENTORY_VIEW')")
public ResponseEntity<List<InventoryItemDTO>> getBinContent(@PathVariable String locationCode) {
// Implementation would call a service to find all items in this location for the current tenant
return ResponseEntity.ok(movementService.getInventoryAtLocation(locationCode));
}
}

View File

@ -0,0 +1,3 @@
package com.utopia.wms.dto.auth;
public record AuthRequest(String email, String password) {}

View File

@ -0,0 +1,3 @@
package com.utopia.wms.dto.auth;
public record AuthResponse(String token) {}

View File

@ -0,0 +1,3 @@
package com.utopia.wms.dto.auth;
public record RegisterRequest(String email, String password, String tenantId) {}

View File

@ -0,0 +1,12 @@
package com.utopia.wms.dto.inventory;
public record InventoryItemDTO(
Long id,
String sku,
String description,
Integer quantityOnHand,
Integer quantityAvailable,
String batchNumber,
String status,
String uom
) {}

View File

@ -0,0 +1,12 @@
package com.utopia.wms.dto.movement;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import org.antlr.v4.runtime.misc.NotNull;
public record StockMovementRequest(
@NotNull Long inventoryItemId,
@NotBlank String targetLocationCode,
@Min(1) Integer quantity,
String reason
) {}

View File

@ -0,0 +1,34 @@
package com.utopia.wms.exception;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(InvalidApiKeyException.class)
public ResponseEntity<?> handleInvalidApiKeyException(InvalidApiKeyException ex) {
Map<String, Object> error = new HashMap<>();
error.put("status", "error");
error.put("errorCode", "WMS_API_KEY_INVALID_ERR");
error.put("message", ex.getMessage());
error.put("timestamp", LocalDateTime.now());
return ResponseEntity.badRequest().body(error);
}
@ExceptionHandler(RuntimeException.class)
public ResponseEntity<Map<String, Object>> handleScannerError(RuntimeException ex) {
Map<String, Object> error = new HashMap<>();
error.put("status", "error");
error.put("errorCode", "WMS_PROC_ERR");
error.put("message", ex.getMessage());
error.put("timestamp", LocalDateTime.now());
return ResponseEntity.badRequest().body(error);
}
}

View File

@ -0,0 +1,12 @@
package com.utopia.wms.exception;
public class InvalidApiKeyException extends Exception{
public InvalidApiKeyException(String message) {
super(message);
}
public InvalidApiKeyException(String message, Throwable cause) {
super(message, cause);
}
}

View File

@ -0,0 +1,47 @@
package com.utopia.wms.model.auth;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Index;
import jakarta.persistence.Table;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.annotations.JdbcTypeCode;
import java.sql.Types;
import java.time.LocalDateTime;
import java.util.UUID;
@Entity
@Getter
@Setter
@NoArgsConstructor
@Table(name = "api_keys", indexes = {
// Index for the Security Filter lookup (High performance)
@Index(name = "idx_api_key_hash", columnList = "hashedKey"),
// Index for filtering by Tenant (SaaS dashboard performance)
@Index(name = "idx_api_key_tenant", columnList = "tenantId")
})
public class ApiKey {
@Id
@GeneratedValue(strategy = GenerationType.UUID)
@JdbcTypeCode(Types.VARCHAR) // Forces mapping to VARCHAR(36)
@Column(name = "id", length = 36, columnDefinition = "VARCHAR(36)")
private UUID id;
@Column(nullable = false, unique = true)
private String hashedKey;
@Column(nullable = false)
private String tenantId;
@Column(nullable = false)
private String displayName; // e.g., "Warehouse Scanner 01"
private boolean active = true;
private LocalDateTime createdAt = LocalDateTime.now();
}

View File

@ -0,0 +1,27 @@
package com.utopia.wms.model.auth;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Entity
@Getter
@Setter
@NoArgsConstructor
@Table(name = "permissions")
public class Permission {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true)
private String name; // e.g., "INVENTORY_ADJUST"
private String description;
}

View File

@ -0,0 +1,40 @@
package com.utopia.wms.model.auth;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.JoinTable;
import jakarta.persistence.ManyToMany;
import jakarta.persistence.Table;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.util.HashSet;
import java.util.Set;
@Entity
@Getter
@Setter
@NoArgsConstructor
@Table(name = "roles")
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true)
private String name; // e.g., "MANAGER"
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(
name = "roles_permissions",
joinColumns = @JoinColumn(name = "role_id"),
inverseJoinColumns = @JoinColumn(name = "permission_id")
)
private Set<Permission> permissions = new HashSet<>();
}

View File

@ -0,0 +1,45 @@
package com.utopia.wms.model.inbound_order;
import com.utopia.wms.util.enums.OrderStatus;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.OneToMany;
import jakarta.persistence.Table;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.JdbcTypeCode;
import java.sql.Types;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.UUID;
@Entity
@Getter
@Setter
@Table(name = "purchase_orders")
public class PurchaseOrder {
@Id
@GeneratedValue(strategy = GenerationType.UUID)
@JdbcTypeCode(Types.VARCHAR)
@Column(name = "id", length = 36, columnDefinition = "VARCHAR(36)")
private UUID id;
private String tenantId;
private String poNumber; // e.g., PO-2026-001
private String vendorName;
@Enumerated(EnumType.STRING)
private OrderStatus status = OrderStatus.OPEN; // OPEN, IN_PROGRESS, COMPLETED, CANCELLED
@OneToMany(mappedBy = "purchaseOrder", cascade = CascadeType.ALL)
private List<PurchaseOrderLine> lines = new ArrayList<>();
private LocalDateTime createdAt = LocalDateTime.now();
}

View File

@ -0,0 +1,30 @@
package com.utopia.wms.model.inbound_order;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
import lombok.Getter;
import lombok.Setter;
@Entity
@Getter
@Setter
@Table(name = "purchase_order_lines")
public class PurchaseOrderLine {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
private PurchaseOrder purchaseOrder;
private String sku;
private Integer expectedQty;
private Integer receivedQty = 0; // Incremented during scanning
private String uom; // EA, CS, PL
}

View File

@ -0,0 +1,70 @@
package com.utopia.wms.model.inventory;
import com.utopia.wms.model.warehouse.WarehouseLocation;
import com.utopia.wms.util.enums.InventoryStatus;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Index;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
import lombok.Getter;
import lombok.Setter;
import java.time.LocalDate;
import java.time.LocalDateTime;
@Entity
@Getter
@Setter
@Table(name = "inventory_items", indexes = {
@Index(name = "idx_inv_tenant", columnList = "tenantId"),
@Index(name = "idx_inv_batch", columnList = "batchNumber"),
@Index(name = "idx_inv_serial", columnList = "serialNumber")
})
public class InventoryItem {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String tenantId;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "item_master_id")
private ItemMaster itemMaster;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "location_id")
private WarehouseLocation location;
// --- Enterprise Quantity Tracking ---
@Column(nullable = false)
private Integer quantityOnHand; // Physical count in bin
@Column(nullable = false)
private Integer quantityAllocated = 0; // Reserved for open orders
// Available = (OnHand - Allocated)
// --- Traceability (The "Why" it's Enterprise Grade) ---
private String batchNumber; // For Batch/Lot tracking (e.g., Food/Meds)
private String serialNumber; // For unique item tracking (e.g., iPhones)
private LocalDate expiryDate; // For FEFO (First Expired First Out) picking
private LocalDate manufacturingDate;
// --- Status Control ---
@Enumerated(EnumType.STRING)
private InventoryStatus status = InventoryStatus.AVAILABLE;
// AVAILABLE, QUARANTINE (QC check), DAMAGED, EXPIRED, RESERVED
private LocalDateTime lastCycleCount;
private String lastUserModified;
}

View File

@ -0,0 +1,59 @@
package com.utopia.wms.model.inventory;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Index;
import jakarta.persistence.Table;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.JdbcTypeCode;
import java.sql.Types;
import java.util.UUID;
@Entity
@Getter
@Setter
@Table(name = "item_masters", indexes = {
@Index(name = "idx_item_tenant_sku", columnList = "tenantId, sku")
})
public class ItemMaster {
@Id
@GeneratedValue(strategy = GenerationType.UUID)
@JdbcTypeCode(Types.VARCHAR) // Forces mapping to VARCHAR(36)
@Column(name = "id", length = 36, columnDefinition = "VARCHAR(36)")
private UUID id;
@Column(nullable = false)
private String tenantId;
@Column(nullable = false)
private String sku; // Stock Keeping Unit
@Column(nullable = false)
private String barcode; // EAN, UPC, or GS1
private String description;
// --- Enterprise Attributes ---
private String category; // e.g., "Electronics", "Perishables"
private String uom; // Unit of Measure: EA, PK, CS, PL
// Dimensions for "Cubing" (Space Optimization)
private Double weight;
private Double length;
private Double width;
private Double height;
// Tracking Strategy
private boolean isSerialTracked; // Must scan every unique unit
private boolean isBatchTracked; // Must track Lot/Batch numbers
// Replenishment
private Integer minStockLevel;
private Integer maxStockLevel;
}

View File

@ -0,0 +1,58 @@
package com.utopia.wms.model.movement;
import com.utopia.wms.model.warehouse.WarehouseLocation;
import com.utopia.wms.util.enums.MovementType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Index;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.time.LocalDateTime;
@Entity
@Getter
@Setter
@NoArgsConstructor
@Table(name = "stock_movement_logs", indexes = {
@Index(name = "idx_move_tenant", columnList = "tenantId"),
@Index(name = "idx_move_sku", columnList = "sku")
})
public class StockMovementLog {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String tenantId;
@Column(nullable = false)
private String sku;
@Enumerated(EnumType.STRING)
private MovementType type; // RECEIPT, TRANSFER, ADJUSTMENT, PICK, SHIP
private Integer quantity;
@ManyToOne
@JoinColumn(name = "from_location_id")
private WarehouseLocation fromLocation;
@ManyToOne
@JoinColumn(name = "to_location_id")
private WarehouseLocation toLocation;
private String batchNumber;
private String username; // The operator who performed the move
private LocalDateTime timestamp = LocalDateTime.now();
private String reasonCode; // e.g., "REPLENISHMENT", "DAMAGED_DURING_MOVE"
}

View File

@ -0,0 +1,77 @@
package com.utopia.wms.model.user;
import com.utopia.wms.model.auth.Role;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Index;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.annotations.JdbcTypeCode;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.sql.Types;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
@Entity
@Getter
@Setter
@NoArgsConstructor
@Table(name = "users", indexes = {
@Index(name = "idx_user_email", columnList = "email"),
@Index(name = "idx_user_tenant", columnList = "tenantId")
})
public class User implements UserDetails {
@Id
@GeneratedValue(strategy = GenerationType.UUID)
@JdbcTypeCode(Types.VARCHAR) // Forces mapping to VARCHAR(36)
@Column(name = "id", length = 36, columnDefinition = "VARCHAR(36)")
private UUID id;
@Column(unique = true, nullable = false)
private String email;
@Column(nullable = false)
private String password;
@Column(nullable = false)
private String tenantId; // The SaaS isolator
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "role_id")
private Role role;
private boolean enabled = true;
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
Set<SimpleGrantedAuthority> authorities = new HashSet<>();
// 1. Add the Role (prefixed with ROLE_)
authorities.add(new SimpleGrantedAuthority("ROLE_" + role.getName()));
// 2. Add individual permissions
role.getPermissions().forEach(p ->
authorities.add(new SimpleGrantedAuthority(p.getName()))
);
return authorities;
}
@Override public String getUsername() { return email; }
@Override public boolean isAccountNonExpired() { return true; }
@Override public boolean isAccountNonLocked() { return true; }
@Override public boolean isCredentialsNonExpired() { return true; }
}

View File

@ -0,0 +1,63 @@
package com.utopia.wms.model.warehouse;
import com.utopia.wms.util.enums.LocationType;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Index;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.OneToMany;
import jakarta.persistence.Table;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.util.ArrayList;
import java.util.List;
@Entity
@Getter
@Setter
@NoArgsConstructor
@Table(name = "warehouse_locations", indexes = {
@Index(name = "idx_loc_tenant_code", columnList = "tenantId, locationCode")
})
public class WarehouseLocation {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String tenantId;
@Column(nullable = false)
private String locationCode; // e.g., "AISLE-01" or "BIN-A1-01"
@Enumerated(EnumType.STRING)
@Column(nullable = false)
private LocationType type;
// --- Hierarchical Relation ---
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "parent_id")
private WarehouseLocation parent;
@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL)
private List<WarehouseLocation> children = new ArrayList<>();
// --- Optimization Meta-data ---
private Integer travelSequence; // Path optimization for pickers
private boolean isPickable; // Can a picker take items from here? (True for Bins, False for Zones)
private boolean isStorable; // Can we put inventory here? (True for Bins, False for Aisles)
@Column(nullable = false)
private boolean active = true;
}

View File

@ -0,0 +1,30 @@
package com.utopia.wms.repository.auth;
import com.utopia.wms.model.auth.ApiKey;
import jdk.jfr.Registered;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
@Registered
public interface ApiKeyRepository extends JpaRepository<ApiKey, UUID> {
/**
* Finds a tenant's ID by the hashed version of the API key.
* We only return the key if it is currently active.
*/
Optional<ApiKey> findByHashedKeyAndActiveTrue(String hashedKey);
/**
* Useful for the UI: List all API keys belonging to a specific SaaS tenant
* so they can manage or revoke them.
*/
List<ApiKey> findByTenantId(String tenantId);
/**
* Used to check if a key exists before attempting deletion or deactivation.
*/
boolean existsByHashedKey(String hashedKey);
}

View File

@ -0,0 +1,11 @@
package com.utopia.wms.repository.auth;
import com.utopia.wms.model.auth.Role;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface RoleRepository extends JpaRepository<Role, Integer> {
Optional<Role> findByName(String name);
}

View File

@ -0,0 +1,19 @@
package com.utopia.wms.repository.inventory;
import com.utopia.wms.dto.inventory.InventoryItemDTO;
import com.utopia.wms.model.inventory.InventoryItem;
import com.utopia.wms.model.inventory.ItemMaster;
import com.utopia.wms.model.warehouse.WarehouseLocation;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
import java.util.Optional;
public interface InventoryItemRepository extends JpaRepository<InventoryItem, Integer> {
Optional<InventoryItem> findByTenantIdAndItemMasterAndLocationAndBatchNumber(String tenantId, ItemMaster item, WarehouseLocation loc, String batch);
Optional<InventoryItem> findByIdAndTenantId(Long inventoryItemId, String tenantId);
List<InventoryItem> findByTenantIdAndLocationLocationCode(String tenantId, String locationCode);
}

View File

@ -0,0 +1,11 @@
package com.utopia.wms.repository.inventory;
import com.utopia.wms.model.inventory.ItemMaster;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface ItemMasterRepository extends JpaRepository<ItemMaster, Integer> {
Optional<ItemMaster> findByTenantIdAndSku(String tenantId, String sku);
}

View File

@ -0,0 +1,7 @@
package com.utopia.wms.repository.movement;
import com.utopia.wms.model.movement.StockMovementLog;
import org.springframework.data.jpa.repository.JpaRepository;
public interface StockMovementLogRepository extends JpaRepository<StockMovementLog, Long> {
}

View File

@ -0,0 +1,11 @@
package com.utopia.wms.repository.user;
import com.utopia.wms.model.user.User;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface UserRepository extends JpaRepository<User, Integer> {
Optional<User> findByEmail(String email);
}

View File

@ -0,0 +1,18 @@
package com.utopia.wms.repository.warehouse;
import com.utopia.wms.model.warehouse.WarehouseLocation;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
import java.util.Optional;
public interface WarehouseLocationRepository extends JpaRepository<WarehouseLocation, Long> {
// Find all children (e.g., all Bins in an Aisle)
List<WarehouseLocation> findByParentIdAndTenantId(Long parentId, String tenantId);
// Find top-level locations (The Warehouses or Zones themselves)
List<WarehouseLocation> findByParentIsNullAndTenantId(String tenantId);
Optional<WarehouseLocation> findByTenantIdAndLocationCode(String tenantId, String locationCode);
}

View File

@ -0,0 +1,62 @@
package com.utopia.wms.service.auth;
import com.utopia.wms.exception.InvalidApiKeyException;
import com.utopia.wms.model.auth.ApiKey;
import com.utopia.wms.repository.auth.ApiKeyRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.UUID;
@Service
@RequiredArgsConstructor
public class ApiKeyService {
private final ApiKeyRepository repository;
/**
* Creates a new API key for a tenant.
* Returns the RAW key (only time it will be visible).
*/
public String createApiKey(String tenantId, String displayName) {
String rawKey = generateRandomKey();
String hashedKey = hashKey(rawKey);
ApiKey apiKey = new ApiKey();
apiKey.setHashedKey(hashedKey);
apiKey.setTenantId(tenantId);
apiKey.setDisplayName(displayName);
repository.save(apiKey);
return rawKey; // Return this to the user to save securely
}
/**
* Validates an incoming API key from a request header.
*/
public String validateKey(String rawKey) throws InvalidApiKeyException {
String hashedKey = hashKey(rawKey);
return repository.findByHashedKeyAndActiveTrue(hashedKey)
.map(ApiKey::getTenantId)
.orElseThrow(() -> new InvalidApiKeyException("API key is not valid.")); // Returns tenantId if valid, else null
}
private String generateRandomKey() {
// Generates a secure random prefix + string (e.g., wms_live_...)
return "wms_" + UUID.randomUUID().toString().replace("-", "");
}
private String hashKey(String rawKey) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] encodedHash = digest.digest(rawKey.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encodedHash);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Error hashing API key", e);
}
}
}

View File

@ -0,0 +1,57 @@
package com.utopia.wms.service.auth;
import com.utopia.wms.dto.auth.AuthRequest;
import com.utopia.wms.dto.auth.AuthResponse;
import com.utopia.wms.dto.auth.RegisterRequest;
import com.utopia.wms.model.auth.Role;
import com.utopia.wms.model.user.User;
import com.utopia.wms.repository.auth.RoleRepository;
import com.utopia.wms.repository.user.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
public class AuthService {
private final UserRepository userRepository;
private final RoleRepository roleRepository;
private final PasswordEncoder passwordEncoder;
private final JwtService jwtService;
private final AuthenticationManager authenticationManager;
public AuthResponse register(RegisterRequest request) {
// 1. Get the ADMIN role (seeded via Liquibase)
Role adminRole = roleRepository.findByName("ADMIN")
.orElseThrow(() -> new RuntimeException("Default Role not found"));
// 2. Create the User
User user = new User();
user.setEmail(request.email());
user.setPassword(passwordEncoder.encode(request.password()));
user.setTenantId(request.tenantId());
user.setRole(adminRole);
user.setEnabled(true);
userRepository.save(user);
// 3. Generate Token
String jwtToken = jwtService.generateToken(user, user.getTenantId());
return new AuthResponse(jwtToken);
}
public AuthResponse authenticate(AuthRequest request) {
authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(request.email(), request.password())
);
User user = userRepository.findByEmail(request.email())
.orElseThrow();
String jwtToken = jwtService.generateToken(user, user.getTenantId());
return new AuthResponse(jwtToken);
}
}

View File

@ -0,0 +1,82 @@
package com.utopia.wms.service.auth;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
@Service
public class JwtService {
@Value("${application.security.jwt.secret-key}")
private String secretKey;
@Value("${application.security.jwt.expiration}")
private long jwtExpiration;
// Generate token with Tenant ID claim
public String generateToken(UserDetails userDetails, String tenantId) {
Map<String, Object> extraClaims = new HashMap<>();
extraClaims.put("tenantId", tenantId);
return buildToken(extraClaims, userDetails, jwtExpiration);
}
private String buildToken(Map<String, Object> extraClaims, UserDetails userDetails, long expiration) {
return Jwts.builder()
.setClaims(extraClaims)
.setSubject(userDetails.getUsername())
.setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(new Date(System.currentTimeMillis() + expiration))
.signWith(getSignInKey(), SignatureAlgorithm.HS256)
.compact();
}
public String extractTenantId(String token) {
return extractClaim(token, claims -> claims.get("tenantId", String.class));
}
public String extractUsername(String token) {
return extractClaim(token, Claims::getSubject);
}
public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {
final Claims claims = extractAllClaims(token);
return claimsResolver.apply(claims);
}
private Claims extractAllClaims(String token) {
return Jwts.parserBuilder()
.setSigningKey(getSignInKey())
.build()
.parseClaimsJws(token)
.getBody();
}
private Key getSignInKey() {
byte[] keyBytes = Decoders.BASE64.decode(secretKey);
return Keys.hmacShaKeyFor(keyBytes);
}
public boolean isTokenValid(String token, UserDetails userDetails) {
final String username = extractUsername(token);
return (username.equals(userDetails.getUsername())) && !isTokenExpired(token);
}
private boolean isTokenExpired(String token) {
return extractExpiration(token).before(new Date());
}
private Date extractExpiration(String token) {
return extractClaim(token, Claims::getExpiration);
}
}

View File

@ -0,0 +1,59 @@
package com.utopia.wms.service.inventory;
import com.utopia.wms.model.inventory.InventoryItem;
import com.utopia.wms.model.inventory.ItemMaster;
import com.utopia.wms.model.warehouse.WarehouseLocation;
import com.utopia.wms.repository.inventory.InventoryItemRepository;
import com.utopia.wms.repository.inventory.ItemMasterRepository;
import com.utopia.wms.repository.warehouse.WarehouseLocationRepository;
import com.utopia.wms.util.TenantContext;
import com.utopia.wms.util.enums.InventoryStatus;
import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
@Service
@RequiredArgsConstructor
public class InventoryImplService implements InventoryService {
private final InventoryItemRepository inventoryRepository;
private final ItemMasterRepository itemMasterRepository;
private final WarehouseLocationRepository locationRepository;
@Transactional
public void receiveInventory(String sku, String locationCode, int quantity, String batch, LocalDate expiry) {
String tenantId = TenantContext.getTenantId();
// 1. Validate Product
ItemMaster item = itemMasterRepository.findByTenantIdAndSku(tenantId, sku)
.orElseThrow(() -> new RuntimeException("SKU " + sku + " does not exist in Item Master."));
// 2. Validate Location
WarehouseLocation loc = locationRepository.findByTenantIdAndLocationCode(tenantId, locationCode)
.orElseThrow(() -> new RuntimeException("Location " + locationCode + " not found."));
// 3. Find or Create Inventory Record (SaaS Isolation + Batch Tracking)
InventoryItem inventory = inventoryRepository
.findByTenantIdAndItemMasterAndLocationAndBatchNumber(tenantId, item, loc, batch)
.orElseGet(() -> {
InventoryItem newItem = new InventoryItem();
newItem.setTenantId(tenantId);
newItem.setItemMaster(item);
newItem.setLocation(loc);
newItem.setBatchNumber(batch);
newItem.setExpiryDate(expiry);
newItem.setQuantityOnHand(0);
newItem.setStatus(InventoryStatus.AVAILABLE);
return newItem;
});
// 4. Update Quantity
inventory.setQuantityOnHand(inventory.getQuantityOnHand() + quantity);
inventory.setLastUserModified(SecurityContextHolder.getContext().getAuthentication().getName());
inventoryRepository.save(inventory);
}
}

View File

@ -0,0 +1,4 @@
package com.utopia.wms.service.inventory;
public interface InventoryService {
}

View File

@ -0,0 +1,113 @@
package com.utopia.wms.service.movement;
import com.utopia.wms.dto.inventory.InventoryItemDTO;
import com.utopia.wms.model.inventory.InventoryItem;
import com.utopia.wms.model.movement.StockMovementLog;
import com.utopia.wms.model.warehouse.WarehouseLocation;
import com.utopia.wms.repository.inventory.InventoryItemRepository;
import com.utopia.wms.repository.movement.StockMovementLogRepository;
import com.utopia.wms.repository.warehouse.WarehouseLocationRepository;
import com.utopia.wms.util.TenantContext;
import com.utopia.wms.util.enums.MovementType;
import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
@RequiredArgsConstructor
public class StockMovementImplService implements StockMovementService{
private final InventoryItemRepository inventoryRepository;
private final StockMovementLogRepository logRepository;
private final WarehouseLocationRepository locationRepository;
// --- The moveStock method we discussed ---
@Transactional
@Override
public void moveStock(Long inventoryItemId, String targetLocationCode, Integer moveQty, String reason) {
String tenantId = TenantContext.getTenantId();
String currentUser = SecurityContextHolder.getContext().getAuthentication().getName();
InventoryItem source = inventoryRepository.findByIdAndTenantId(inventoryItemId, tenantId)
.orElseThrow(() -> new RuntimeException("Source inventory not found"));
if (source.getQuantityOnHand() < moveQty) {
throw new RuntimeException("Insufficient stock. Available: " + source.getQuantityOnHand());
}
WarehouseLocation targetLoc = locationRepository.findByTenantIdAndLocationCode(tenantId, targetLocationCode)
.orElseThrow(() -> new RuntimeException("Target location not found"));
// Subtract from source
source.setQuantityOnHand(source.getQuantityOnHand() - moveQty);
if (source.getQuantityOnHand() == 0) {
inventoryRepository.delete(source);
} else {
inventoryRepository.save(source);
}
// Add to target
InventoryItem targetInv = inventoryRepository
.findByTenantIdAndItemMasterAndLocationAndBatchNumber(
tenantId, source.getItemMaster(), targetLoc, source.getBatchNumber())
.orElseGet(() -> createNewInventoryInstance(source, targetLoc));
targetInv.setQuantityOnHand(targetInv.getQuantityOnHand() + moveQty);
inventoryRepository.save(targetInv);
// Audit Log
saveMovementLog(source, targetLoc, moveQty, currentUser, reason);
}
// --- The new Inquiry method for Scanners ---
@Override
public List<InventoryItemDTO> getInventoryAtLocation(String locationCode) {
String tenantId = TenantContext.getTenantId();
return inventoryRepository.findByTenantIdAndLocationLocationCode(tenantId, locationCode)
.stream()
.map(this::convertToDTO)
.toList();
}
private InventoryItemDTO convertToDTO(InventoryItem item) {
return new InventoryItemDTO(
item.getId(),
item.getItemMaster().getSku(),
item.getItemMaster().getDescription(),
item.getQuantityOnHand(),
(item.getQuantityOnHand() - item.getQuantityAllocated()),
item.getBatchNumber(),
item.getStatus().name(),
item.getItemMaster().getUom()
);
}
private InventoryItem createNewInventoryInstance(InventoryItem source, WarehouseLocation targetLoc) {
InventoryItem target = new InventoryItem();
target.setTenantId(source.getTenantId());
target.setItemMaster(source.getItemMaster());
target.setLocation(targetLoc);
target.setBatchNumber(source.getBatchNumber());
target.setQuantityOnHand(0);
target.setQuantityAllocated(0);
target.setStatus(source.getStatus());
return target;
}
private void saveMovementLog(InventoryItem source, WarehouseLocation target, Integer qty, String user, String reason) {
StockMovementLog log = new StockMovementLog();
log.setTenantId(source.getTenantId());
log.setSku(source.getItemMaster().getSku());
log.setType(MovementType.TRANSFER);
log.setQuantity(qty);
log.setFromLocation(source.getLocation());
log.setToLocation(target);
log.setUsername(user);
log.setReasonCode(reason);
logRepository.save(log);
}
}

View File

@ -0,0 +1,15 @@
package com.utopia.wms.service.movement;
import com.utopia.wms.dto.inventory.InventoryItemDTO;
import jakarta.transaction.Transactional;
import java.util.List;
public interface StockMovementService {
// --- The moveStock method we discussed ---
@Transactional
void moveStock(Long inventoryItemId, String targetLocationCode, Integer moveQty, String reason);
// --- The new Inquiry method for Scanners ---
List<InventoryItemDTO> getInventoryAtLocation(String locationCode);
}

View File

@ -0,0 +1,17 @@
package com.utopia.wms.util;
public class TenantContext {
private static final ThreadLocal<String> CURRENT_TENANT = new ThreadLocal<>();
public static void setTenantId(String tenantId) {
CURRENT_TENANT.set(tenantId);
}
public static String getTenantId() {
return CURRENT_TENANT.get();
}
public static void clear() {
CURRENT_TENANT.remove();
}
}

View File

@ -0,0 +1,9 @@
package com.utopia.wms.util.enums;
public enum InventoryStatus {
AVAILABLE, // Ready to be sold/picked
QUARANTINE, // Blocked for Quality Control
DAMAGED, // Physical damage, cannot be sold
EXPIRED, // Past the sell-by date
RESERVED // Specifically held for a VIP or project
}

View File

@ -0,0 +1,11 @@
package com.utopia.wms.util.enums;
public enum LocationType {
RECEIVING, // Inbound dock area
PICKING, // Active area for small quantity orders
BULK, // High-level racking for pallets
PACKING, // Station where items are boxed
SHIPPING, // Outbound dock area
STAGING, // Temporary holding
RETURN // Items returned by customers
}

View File

@ -0,0 +1,5 @@
package com.utopia.wms.util.enums;
public enum MovementType {
RECEIPT, TRANSFER, ADJUSTMENT, PICK, SHIP
}

View File

@ -0,0 +1,5 @@
package com.utopia.wms.util.enums;
public enum OrderStatus {
OPEN, IN_PROGRESS, COMPLETED, CANCELLED
}

View File

@ -0,0 +1,21 @@
server.port=8088
spring.application.name=UtopiaWMS
# DATABASE CONFIGURATION
spring.datasource.url=jdbc:mysql://192.168.90.147:3306/wms
spring.datasource.username=utopia
spring.datasource.password=Utopia01
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
# JWT CONFIGURATION
application.security.jwt.secret-key=${JWT_SECRET_KEY:404E635266556A586E3272357538782F413F4428472B4B6250645367566B5970}
application.security.jwt.expiration: 86400000
# LIQUIBASE CONFIGURATION
spring.liquibase.change-log=classpath:/db/changelog/db.changelog-master.xml
spring.liquibase.enabled=true

View File

@ -0,0 +1,130 @@
<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog
xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-4.24.xsd">
<changeSet id="20260102-setup-rbac" author="qasim">
<insert tableName="permissions">
<column name="name" value="INVENTORY_VIEW"/>
<column name="description" value="View stock levels and locations"/>
</insert>
<insert tableName="permissions">
<column name="name" value="INVENTORY_ADJUST"/>
<column name="description" value="Perform stock takes and manual adjustments"/>
</insert>
<insert tableName="permissions">
<column name="name" value="ORDER_PICK"/>
<column name="description" value="Pick items for outgoing orders"/>
</insert>
<insert tableName="permissions">
<column name="name" value="USER_MANAGEMENT"/>
<column name="description" value="Create and manage warehouse staff"/>
</insert>
<insert tableName="roles">
<column name="id" value="1"/>
<column name="name" value="ADMIN"/>
</insert>
<insert tableName="roles">
<column name="id" value="2"/>
<column name="name" value="Supervisor"/>
</insert>
<insert tableName="roles_permissions">
<column name="role_id" value="1"/><column name="permission_id" value="1"/>
</insert>
<insert tableName="roles_permissions">
<column name="role_id" value="1"/><column name="permission_id" value="2"/>
</insert>
<insert tableName="roles_permissions">
<column name="role_id" value="1"/><column name="permission_id" value="4"/>
</insert>
<insert tableName="roles_permissions">
<column name="role_id" value="2"/><column name="permission_id" value="1"/>
</insert>
<insert tableName="roles_permissions">
<column name="role_id" value="2"/><column name="permission_id" value="3"/>
</insert>
</changeSet>
<changeSet id="fix-uuid-columns" author="qasim">
<modifyDataType tableName="users" columnName="id" newDataType="VARCHAR(36)"/>
<modifyDataType tableName="item_masters" columnName="id" newDataType="VARCHAR(36)"/>
</changeSet>
<changeSet id="fix-uuid-columns-for-apikey" author="qasim">
<modifyDataType tableName="api_keys" columnName="id" newDataType="VARCHAR(36)"/>
</changeSet>
<changeSet id="dummy-data" author="qasim">
<insert tableName="item_masters">
<column name="id" value="550e8400-e29b-41d4-a716-446655440000" type="UUID"/>
<column name="tenant_id" value="1"/>
<column name="sku" value="IPHONE-15-PRO"/>
<column name="barcode" value="194253701234"/>
<column name="description" value="Apple iPhone 15 Pro 256GB Titanium"/>
<column name="uom" value="EA"/>
<column name="is_serial_tracked" valueBoolean="true"/>
<column name="is_batch_tracked" valueBoolean="false"/>
</insert>
<insert tableName="item_masters">
<column name="id" value="550e8400-e29b-41d4-a716-446655440001" type="UUID"/>
<column name="tenant_id" value="1"/>
<column name="sku" value="LOGI-MX-MASTER"/>
<column name="barcode" value="097855151234"/>
<column name="description" value="Logitech MX Master 3S Wireless Mouse"/>
<column name="uom" value="EA"/>
<column name="is_serial_tracked" valueBoolean="false"/>
<column name="is_batch_tracked" valueBoolean="false"/>
</insert>
<insert tableName="warehouse_locations">
<column name="id" value="100"/>
<column name="tenant_id" value="1"/>
<column name="location_code" value="ZONE-A"/>
<column name="type" value="BULK"/>
<column name="is_storable" valueBoolean="false"/>
<column name="is_pickable" valueBoolean="false"/>
<column name="active" valueBoolean="true"/>
</insert>
<insert tableName="warehouse_locations">
<column name="id" value="101"/>
<column name="parent_id" value="100"/>
<column name="tenant_id" value="1"/>
<column name="location_code" value="AISLE-01"/>
<column name="type" value="BULK"/>
<column name="is_storable" valueBoolean="false"/>
<column name="is_pickable" valueBoolean="false"/>
<column name="active" valueBoolean="true"/>
</insert>
<insert tableName="warehouse_locations">
<column name="id" value="102"/>
<column name="parent_id" value="101"/>
<column name="tenant_id" value="1"/>
<column name="location_code" value="BIN-A1-01"/>
<column name="type" value="PICKING"/>
<column name="is_storable" valueBoolean="true"/>
<column name="is_pickable" valueBoolean="true"/>
<column name="active" valueBoolean="true"/>
</insert>
<insert tableName="inventory_items">
<column name="tenant_id" value="1"/>
<column name="item_master_id" value="550e8400-e29b-41d4-a716-446655440000" type="UUID"/>
<column name="location_id" value="102"/>
<column name="quantity_on_hand" value="50"/>
<column name="quantity_allocated" value="0"/>
<column name="status" value="AVAILABLE"/>
</insert>
</changeSet>
</databaseChangeLog>

View File

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