diff --git a/code/fms/fms-api/.gitattributes b/code/fms/fms-api/.gitattributes new file mode 100644 index 00000000..3b41682a --- /dev/null +++ b/code/fms/fms-api/.gitattributes @@ -0,0 +1,2 @@ +/mvnw text eol=lf +*.cmd text eol=crlf diff --git a/code/fms/fms-api/.gitignore b/code/fms/fms-api/.gitignore new file mode 100644 index 00000000..80dc5024 --- /dev/null +++ b/code/fms/fms-api/.gitignore @@ -0,0 +1,36 @@ +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/ + +### Organization database configs ### +/config/dbconfigs/*.properties diff --git a/code/fms/fms-api/.mvn/wrapper/maven-wrapper.properties b/code/fms/fms-api/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 00000000..216df058 --- /dev/null +++ b/code/fms/fms-api/.mvn/wrapper/maven-wrapper.properties @@ -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.16/apache-maven-3.9.16-bin.zip diff --git a/code/fms/fms-api/config/dbconfigs/README.md b/code/fms/fms-api/config/dbconfigs/README.md new file mode 100644 index 00000000..54940590 --- /dev/null +++ b/code/fms/fms-api/config/dbconfigs/README.md @@ -0,0 +1,16 @@ +# Organization Database Configs + +Each organization uses one SQL Server connection file named `{ORG_ID}.properties`. +Organization IDs are normalized to uppercase and may contain only letters, numbers, +underscores, and hyphens. + +Example: `G3HD.properties` + +```properties +url=jdbc:sqlserver://127.0.0.1:1433;databaseName=G3HD +username=sa +password=your-password +driver=com.microsoft.sqlserver.jdbc.SQLServerDriver +``` + +The `*.properties` files in this directory are ignored by Git. diff --git a/code/fms/fms-api/mvnw b/code/fms/fms-api/mvnw new file mode 100644 index 00000000..bd8896bf --- /dev/null +++ b/code/fms/fms-api/mvnw @@ -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-,maven-mvnd--}/ +[ -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 "$@" diff --git a/code/fms/fms-api/mvnw.cmd b/code/fms/fms-api/mvnw.cmd new file mode 100644 index 00000000..92450f93 --- /dev/null +++ b/code/fms/fms-api/mvnw.cmd @@ -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-,maven-mvnd--}/ +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" diff --git a/code/fms/fms-api/pom.xml b/code/fms/fms-api/pom.xml new file mode 100644 index 00000000..3659fe72 --- /dev/null +++ b/code/fms/fms-api/pom.xml @@ -0,0 +1,91 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 4.1.0 + + + cn.g3soft + fms-api + 0.0.1-SNAPSHOT + fms-api + fms-api + + + + + + + + + + + + + + + 21 + + + + org.springframework.boot + spring-boot-starter-webmvc + + + org.springframework.boot + spring-boot-starter-jdbc + + + com.alibaba + druid + 1.2.18 + + + io.jsonwebtoken + jjwt-api + 0.12.6 + + + io.jsonwebtoken + jjwt-impl + 0.12.6 + runtime + + + io.jsonwebtoken + jjwt-jackson + 0.12.6 + runtime + + + + org.springframework.boot + spring-boot-devtools + runtime + true + + + com.microsoft.sqlserver + mssql-jdbc + runtime + + + org.springframework.boot + spring-boot-starter-webmvc-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/FmsApiApplication.java b/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/FmsApiApplication.java new file mode 100644 index 00000000..29e2d6e1 --- /dev/null +++ b/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/FmsApiApplication.java @@ -0,0 +1,15 @@ +package cn.g3soft.fmsapi; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.context.properties.ConfigurationPropertiesScan; + +@SpringBootApplication +@ConfigurationPropertiesScan +public class FmsApiApplication { + + public static void main(String[] args) { + SpringApplication.run(FmsApiApplication.class, args); + } + +} diff --git a/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/config/AuthProperties.java b/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/config/AuthProperties.java new file mode 100644 index 00000000..dedabb09 --- /dev/null +++ b/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/config/AuthProperties.java @@ -0,0 +1,28 @@ +package cn.g3soft.fmsapi.config; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +import java.time.Duration; + +@ConfigurationProperties(prefix = "fms.auth") +public class AuthProperties { + + private String jwtSecret; + private Duration jwtExpiration = Duration.ofHours(24); + + public String getJwtSecret() { + return jwtSecret; + } + + public void setJwtSecret(String jwtSecret) { + this.jwtSecret = jwtSecret; + } + + public Duration getJwtExpiration() { + return jwtExpiration; + } + + public void setJwtExpiration(Duration jwtExpiration) { + this.jwtExpiration = jwtExpiration; + } +} diff --git a/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/config/JwtAuthFilter.java b/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/config/JwtAuthFilter.java new file mode 100644 index 00000000..e64c4f80 --- /dev/null +++ b/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/config/JwtAuthFilter.java @@ -0,0 +1,77 @@ +package cn.g3soft.fmsapi.config; + +import cn.g3soft.fmsapi.database.OrgContext; +import cn.g3soft.fmsapi.utils.ApiResponse; +import cn.g3soft.fmsapi.utils.JwtUtils; +import io.jsonwebtoken.JwtException; +import jakarta.annotation.Resource; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; +import tools.jackson.databind.ObjectMapper; + +import java.io.IOException; + +@Component +public class JwtAuthFilter extends OncePerRequestFilter { + + private static final String BEARER_PREFIX = "Bearer "; + private static final String LOGIN_PATH = "/auth/login"; + + @Resource + private JwtUtils jwtUtils; + + @Resource + private ObjectMapper objectMapper; + + @Override + protected boolean shouldNotFilter(HttpServletRequest request) { + return "OPTIONS".equalsIgnoreCase(request.getMethod()) + || LOGIN_PATH.equals(request.getServletPath()); + } + + @Override + protected void doFilterInternal( + HttpServletRequest request, + HttpServletResponse response, + FilterChain filterChain + ) throws ServletException, IOException { + String orgId; + try { + String token = getToken(request); + orgId = jwtUtils.getOrgId(token); + OrgContext.setOrgId(orgId); + } catch (JwtException | IllegalArgumentException exception) { + writeUnauthorized(response); + return; + } + + try { + filterChain.doFilter(request, response); + } finally { + OrgContext.clear(); + } + } + + private String getToken(HttpServletRequest request) { + String authorization = request.getHeader("Authorization"); + if (authorization == null || !authorization.startsWith(BEARER_PREFIX)) { + throw new IllegalArgumentException("缺少登录凭证"); + } + return authorization.substring(BEARER_PREFIX.length()).trim(); + } + + private void writeUnauthorized(HttpServletResponse response) throws IOException { + ApiResponse body = ApiResponse.fail( + ApiResponse.AUTH_ERROR_CODE, + "未登录或登录已失效" + ); + response.setStatus(200); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application/json"); + objectMapper.writeValue(response.getWriter(), body); + } +} diff --git a/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/controller/AuthController.java b/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/controller/AuthController.java new file mode 100644 index 00000000..f0e4f7e5 --- /dev/null +++ b/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/controller/AuthController.java @@ -0,0 +1,53 @@ +package cn.g3soft.fmsapi.controller; + +import cn.g3soft.fmsapi.exception.BusinessException; +import cn.g3soft.fmsapi.service.AuthService; +import cn.g3soft.fmsapi.utils.ApiResponse; +import cn.g3soft.fmsapi.utils.ParamUtils; +import cn.g3soft.fmsapi.utils.StringUtils; +import jakarta.annotation.Resource; +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.sql.SQLException; +import java.util.Map; +import java.util.Optional; + +@RestController +@RequestMapping("/auth") +public class AuthController { + + @Resource + private AuthService authService; + + @PostMapping("/login") + public ApiResponse> login( + @RequestBody(required = false) Map request + ) throws SQLException { + String orgId = ParamUtils.getString(request, "orgid"); + String userId = ParamUtils.getString(request, "userid"); + String password = ParamUtils.getString(request, "password"); + + if (StringUtils.isBlank(orgId)) { + throw new BusinessException("机构码不能为空"); + } + if (StringUtils.isBlank(userId)) { + throw new BusinessException("用户ID不能为空"); + } + + Optional> loginResponse = authService.login( + orgId, + userId, + password + ); + if (loginResponse.isEmpty()) { + return ApiResponse.fail( + ApiResponse.AUTH_ERROR_CODE, + "机构码、账号或密码错误" + ); + } + return ApiResponse.success(loginResponse.get()); + } +} diff --git a/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/controller/DataController.java b/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/controller/DataController.java new file mode 100644 index 00000000..6b37d779 --- /dev/null +++ b/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/controller/DataController.java @@ -0,0 +1,35 @@ +package cn.g3soft.fmsapi.controller; + +import cn.g3soft.fmsapi.service.DataService; +import cn.g3soft.fmsapi.utils.ApiResponse; +import jakarta.annotation.Resource; +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.sql.SQLException; +import java.util.List; +import java.util.Map; + +@RestController +@RequestMapping("/data") +public class DataController { + + @Resource + private DataService dataService; + + @PostMapping("/loaddata") + public ApiResponse>> loadData( + @RequestBody(required = false) Map params + ) throws SQLException { + return ApiResponse.success(dataService.loadData(params)); + } + + @PostMapping("/loaddatabysql") + public ApiResponse>> loadDataBySql( + @RequestBody(required = false) Map params + ) throws SQLException { + return ApiResponse.success(dataService.loadDataBySql(params)); + } +} diff --git a/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/database/OrgContext.java b/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/database/OrgContext.java new file mode 100644 index 00000000..867e6485 --- /dev/null +++ b/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/database/OrgContext.java @@ -0,0 +1,32 @@ +package cn.g3soft.fmsapi.database; + +public final class OrgContext { + + private static final ThreadLocal ORG_ID_HOLDER = new ThreadLocal<>(); + + private OrgContext() { + } + + public static void setOrgId(String orgId) { + if (orgId == null || orgId.isBlank()) { + throw new IllegalArgumentException("机构码不能为空"); + } + ORG_ID_HOLDER.set(orgId); + } + + public static String getOrgId() { + return ORG_ID_HOLDER.get(); + } + + public static String requireOrgId() { + String orgId = getOrgId(); + if (orgId == null) { + throw new IllegalStateException("当前请求未设置机构上下文"); + } + return orgId; + } + + public static void clear() { + ORG_ID_HOLDER.remove(); + } +} diff --git a/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/database/OrgDataSourceFactory.java b/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/database/OrgDataSourceFactory.java new file mode 100644 index 00000000..bfa89f00 --- /dev/null +++ b/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/database/OrgDataSourceFactory.java @@ -0,0 +1,46 @@ +package cn.g3soft.fmsapi.database; + +import com.alibaba.druid.pool.DruidDataSource; +import jakarta.annotation.Resource; +import org.springframework.stereotype.Component; + +import java.sql.SQLException; + +@Component +public class OrgDataSourceFactory { + + @Resource + private OrgDatabaseProperties properties; + + public DruidDataSource create(String orgId, OrgDatabaseConfig config) { + OrgDatabaseProperties.Pool poolProperties = properties.getPool(); + DruidDataSource dataSource = new DruidDataSource(); + dataSource.setName("fms-" + orgId); + dataSource.setUrl(config.url()); + dataSource.setUsername(config.username()); + dataSource.setPassword(config.password()); + dataSource.setDriverClassName(config.driver()); + dataSource.setInitialSize(poolProperties.getInitialSize()); + dataSource.setMinIdle(poolProperties.getMinIdle()); + dataSource.setMaxActive(poolProperties.getMaxActive()); + dataSource.setMaxWait(poolProperties.getMaxWait()); + dataSource.setValidationQuery(poolProperties.getValidationQuery()); + dataSource.setTestWhileIdle(poolProperties.isTestWhileIdle()); + dataSource.setTestOnBorrow(poolProperties.isTestOnBorrow()); + dataSource.setTestOnReturn(poolProperties.isTestOnReturn()); + dataSource.setTimeBetweenEvictionRunsMillis( + poolProperties.getTimeBetweenEvictionRuns().toMillis() + ); + dataSource.setMinEvictableIdleTimeMillis( + poolProperties.getMinEvictableIdleTime().toMillis() + ); + + try { + dataSource.init(); + return dataSource; + } catch (SQLException exception) { + dataSource.close(); + throw new IllegalStateException("初始化机构数据库连接池失败: " + orgId, exception); + } + } +} diff --git a/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/database/OrgDataSourceManager.java b/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/database/OrgDataSourceManager.java new file mode 100644 index 00000000..f75308e0 --- /dev/null +++ b/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/database/OrgDataSourceManager.java @@ -0,0 +1,61 @@ +package cn.g3soft.fmsapi.database; + +import com.alibaba.druid.pool.DruidDataSource; +import jakarta.annotation.PreDestroy; +import jakarta.annotation.Resource; +import org.springframework.stereotype.Component; + +import java.sql.Connection; +import java.sql.SQLException; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +@Component +public class OrgDataSourceManager { + + private final ConcurrentMap dataSources = new ConcurrentHashMap<>(); + + @Resource + private OrgDatabaseConfigLoader configLoader; + + @Resource + private OrgDataSourceFactory dataSourceFactory; + + public DruidDataSource getDataSource(String orgId) { + String normalizedOrgId = configLoader.normalizeOrgId(orgId); + return dataSources.computeIfAbsent(normalizedOrgId, this::createDataSource); + } + + public Connection getConnection(String orgId) throws SQLException { + return getDataSource(orgId).getConnection(); + } + + public Connection getConnection() throws SQLException { + return getConnection(OrgContext.requireOrgId()); + } + + public boolean closeDataSource(String orgId) { + String normalizedOrgId = configLoader.normalizeOrgId(orgId); + DruidDataSource dataSource = dataSources.remove(normalizedOrgId); + if (dataSource == null) { + return false; + } + dataSource.close(); + return true; + } + + public int getDataSourceCount() { + return dataSources.size(); + } + + @PreDestroy + public void closeAll() { + dataSources.values().forEach(DruidDataSource::close); + dataSources.clear(); + } + + private DruidDataSource createDataSource(String orgId) { + OrgDatabaseConfig config = configLoader.load(orgId); + return dataSourceFactory.create(orgId, config); + } +} diff --git a/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/database/OrgDatabaseConfig.java b/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/database/OrgDatabaseConfig.java new file mode 100644 index 00000000..06b68892 --- /dev/null +++ b/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/database/OrgDatabaseConfig.java @@ -0,0 +1,9 @@ +package cn.g3soft.fmsapi.database; + +public record OrgDatabaseConfig( + String url, + String username, + String password, + String driver +) { +} diff --git a/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/database/OrgDatabaseConfigLoader.java b/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/database/OrgDatabaseConfigLoader.java new file mode 100644 index 00000000..ebeee826 --- /dev/null +++ b/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/database/OrgDatabaseConfigLoader.java @@ -0,0 +1,102 @@ +package cn.g3soft.fmsapi.database; + +import cn.g3soft.fmsapi.exception.BusinessException; +import jakarta.annotation.PostConstruct; +import jakarta.annotation.Resource; +import org.springframework.stereotype.Component; + +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Locale; +import java.util.Properties; +import java.util.regex.Pattern; + +@Component +public class OrgDatabaseConfigLoader { + + private static final Pattern ORG_ID_PATTERN = Pattern.compile("[A-Z0-9_-]{1,32}"); + private static final String DEFAULT_SQL_SERVER_DRIVER = + "com.microsoft.sqlserver.jdbc.SQLServerDriver"; + + @Resource + private OrgDatabaseProperties properties; + + private Path configDir; + + @PostConstruct + public void init() { + this.configDir = properties.getConfigDir().toAbsolutePath().normalize(); + } + + public OrgDatabaseConfig load(String orgId) { + String normalizedOrgId = normalizeOrgId(orgId); + Path configFile = configDir.resolve(normalizedOrgId + ".properties").normalize(); + if (!configFile.startsWith(configDir)) { + throw new IllegalArgumentException("机构配置文件路径不合法"); + } + if (!Files.isRegularFile(configFile)) { + throw new IllegalStateException("未找到机构数据库配置文件: " + configFile); + } + + Properties properties = new Properties(); + try (InputStream input = Files.newInputStream(configFile); + InputStreamReader reader = new InputStreamReader(input, StandardCharsets.UTF_8)) { + properties.load(reader); + } catch (IOException exception) { + throw new IllegalStateException("读取机构数据库配置文件失败: " + configFile, exception); + } + + String url = required(properties, "url", configFile); + if (!url.toLowerCase(Locale.ROOT).startsWith("jdbc:sqlserver:")) { + throw new IllegalStateException("机构数据库必须使用 SQL Server: " + configFile); + } + + return new OrgDatabaseConfig( + url, + required(properties, "username", configFile), + requiredPassword(properties, configFile), + readDriver(properties) + ); + } + + public String normalizeOrgId(String orgId) { + if (orgId == null) { + throw new BusinessException("机构码不能为空"); + } + + String normalized = orgId.trim().toUpperCase(Locale.ROOT); + if (!ORG_ID_PATTERN.matcher(normalized).matches()) { + throw new BusinessException("机构码格式不正确"); + } + return normalized; + } + + public Path getConfigDir() { + return configDir; + } + + private String required(Properties properties, String key, Path configFile) { + String value = properties.getProperty(key); + if (value == null || value.isBlank()) { + throw new IllegalStateException("机构数据库配置缺少 " + key + ": " + configFile); + } + return value.trim(); + } + + private String requiredPassword(Properties properties, Path configFile) { + String password = properties.getProperty("password"); + if (password == null || password.isBlank()) { + throw new IllegalStateException("机构数据库配置缺少 password: " + configFile); + } + return password; + } + + private String readDriver(Properties properties) { + String driver = properties.getProperty("driver"); + return driver == null || driver.isBlank() ? DEFAULT_SQL_SERVER_DRIVER : driver.trim(); + } +} diff --git a/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/database/OrgDatabaseProperties.java b/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/database/OrgDatabaseProperties.java new file mode 100644 index 00000000..2be6561e --- /dev/null +++ b/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/database/OrgDatabaseProperties.java @@ -0,0 +1,119 @@ +package cn.g3soft.fmsapi.database; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +import java.nio.file.Path; +import java.time.Duration; + +@ConfigurationProperties(prefix = "fms.database") +public class OrgDatabaseProperties { + + private Path configDir = Path.of("./config/dbconfigs"); + private final Pool pool = new Pool(); + + public Path getConfigDir() { + return configDir; + } + + public void setConfigDir(Path configDir) { + this.configDir = configDir; + } + + public Pool getPool() { + return pool; + } + + public static class Pool { + + private int initialSize; + private int minIdle; + private int maxActive = 10; + private long maxWait = 5000; + private String validationQuery = "SELECT 1"; + private boolean testWhileIdle = true; + private boolean testOnBorrow; + private boolean testOnReturn; + private Duration timeBetweenEvictionRuns = Duration.ofMinutes(1); + private Duration minEvictableIdleTime = Duration.ofMinutes(5); + + public int getInitialSize() { + return initialSize; + } + + public void setInitialSize(int initialSize) { + this.initialSize = initialSize; + } + + public int getMinIdle() { + return minIdle; + } + + public void setMinIdle(int minIdle) { + this.minIdle = minIdle; + } + + public int getMaxActive() { + return maxActive; + } + + public void setMaxActive(int maxActive) { + this.maxActive = maxActive; + } + + public long getMaxWait() { + return maxWait; + } + + public void setMaxWait(long maxWait) { + this.maxWait = maxWait; + } + + public String getValidationQuery() { + return validationQuery; + } + + public void setValidationQuery(String validationQuery) { + this.validationQuery = validationQuery; + } + + public boolean isTestWhileIdle() { + return testWhileIdle; + } + + public void setTestWhileIdle(boolean testWhileIdle) { + this.testWhileIdle = testWhileIdle; + } + + public boolean isTestOnBorrow() { + return testOnBorrow; + } + + public void setTestOnBorrow(boolean testOnBorrow) { + this.testOnBorrow = testOnBorrow; + } + + public boolean isTestOnReturn() { + return testOnReturn; + } + + public void setTestOnReturn(boolean testOnReturn) { + this.testOnReturn = testOnReturn; + } + + public Duration getTimeBetweenEvictionRuns() { + return timeBetweenEvictionRuns; + } + + public void setTimeBetweenEvictionRuns(Duration timeBetweenEvictionRuns) { + this.timeBetweenEvictionRuns = timeBetweenEvictionRuns; + } + + public Duration getMinEvictableIdleTime() { + return minEvictableIdleTime; + } + + public void setMinEvictableIdleTime(Duration minEvictableIdleTime) { + this.minEvictableIdleTime = minEvictableIdleTime; + } + } +} diff --git a/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/database/OrgRoutingDataSource.java b/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/database/OrgRoutingDataSource.java new file mode 100644 index 00000000..a5f87b8a --- /dev/null +++ b/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/database/OrgRoutingDataSource.java @@ -0,0 +1,28 @@ +package cn.g3soft.fmsapi.database; + +import jakarta.annotation.Resource; +import org.springframework.context.annotation.Primary; +import org.springframework.jdbc.datasource.AbstractDataSource; +import org.springframework.stereotype.Component; + +import java.sql.Connection; +import java.sql.SQLException; + +@Primary +@Component +public class OrgRoutingDataSource extends AbstractDataSource { + + @Resource + private OrgDataSourceManager dataSourceManager; + + @Override + public Connection getConnection() throws SQLException { + return dataSourceManager.getConnection(); + } + + @Override + public Connection getConnection(String username, String password) throws SQLException { + return dataSourceManager.getDataSource(OrgContext.requireOrgId()) + .getConnection(username, password); + } +} diff --git a/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/exception/BusinessException.java b/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/exception/BusinessException.java new file mode 100644 index 00000000..bab7594c --- /dev/null +++ b/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/exception/BusinessException.java @@ -0,0 +1,8 @@ +package cn.g3soft.fmsapi.exception; + +public class BusinessException extends RuntimeException { + + public BusinessException(String message) { + super(message); + } +} diff --git a/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/exception/GlobalExceptionHandler.java b/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/exception/GlobalExceptionHandler.java new file mode 100644 index 00000000..5128998c --- /dev/null +++ b/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/exception/GlobalExceptionHandler.java @@ -0,0 +1,36 @@ +package cn.g3soft.fmsapi.exception; + +import cn.g3soft.fmsapi.utils.ApiResponse; +import jakarta.servlet.http.HttpServletRequest; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +@RestControllerAdvice +public class GlobalExceptionHandler { + + private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class); + + @ExceptionHandler(BusinessException.class) + public ApiResponse handleBusinessException(BusinessException exception) { + return ApiResponse.fail(exception.getMessage()); + } + + @ExceptionHandler(Exception.class) + public ApiResponse handleException( + Exception exception, + HttpServletRequest request + ) { + LOGGER.error( + "系统异常,method={},uri={}", + request.getMethod(), + request.getRequestURI(), + exception + ); + return ApiResponse.fail( + ApiResponse.SYSTEM_ERROR_CODE, + "系统异常,请稍后重试" + ); + } +} diff --git a/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/service/AuthService.java b/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/service/AuthService.java new file mode 100644 index 00000000..0e1a824c --- /dev/null +++ b/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/service/AuthService.java @@ -0,0 +1,85 @@ +package cn.g3soft.fmsapi.service; + +import cn.g3soft.fmsapi.utils.DbUtils; +import cn.g3soft.fmsapi.utils.JwtUtils; +import jakarta.annotation.Resource; +import org.springframework.stereotype.Service; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.sql.SQLException; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; + +@Service +public class AuthService { + + @Resource + private DbUtils dbUtils; + + @Resource + private JwtUtils jwtUtils; + + public Optional> login( + String orgId, + String userId, + String password + ) throws SQLException { + String normalizedOrgId = orgId.trim().toUpperCase(Locale.ROOT); + String normalizedUserId = userId.trim(); + List> users = dbUtils.loadData( + normalizedOrgId, + "b_user", + "b_id = " + dbUtils.toSqlStringLiteral(normalizedUserId), + null, + List.of("b_id", "b_name", "b_password") + ); + + if (users.isEmpty()) { + return Optional.empty(); + } + + Map account = users.getFirst(); + String storedPassword = getString(account, "b_password"); + if (!passwordMatches(storedPassword, password)) { + return Optional.empty(); + } + + String accountId = getString(account, "b_id"); + String token = jwtUtils.generateToken(accountId, normalizedOrgId); + + Map user = new LinkedHashMap<>(); + user.put("id", accountId); + user.put("name", getString(account, "b_name")); + + Map result = new LinkedHashMap<>(); + result.put("token", token); + result.put("orgid", normalizedOrgId); + result.put("user", user); + return Optional.of(result); + } + + private String getString(Map row, String column) { + for (Map.Entry entry : row.entrySet()) { + if (entry.getKey().equalsIgnoreCase(column)) { + Object value = entry.getValue(); + return value == null ? null : value.toString(); + } + } + return null; + } + + private boolean passwordMatches(String storedPassword, String submittedPassword) { + if (storedPassword == null || submittedPassword == null) { + return false; + } + + return MessageDigest.isEqual( + storedPassword.getBytes(StandardCharsets.UTF_8), + submittedPassword.getBytes(StandardCharsets.UTF_8) + ); + } +} diff --git a/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/service/DataService.java b/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/service/DataService.java new file mode 100644 index 00000000..2af4b673 --- /dev/null +++ b/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/service/DataService.java @@ -0,0 +1,32 @@ +package cn.g3soft.fmsapi.service; + +import cn.g3soft.fmsapi.utils.DbUtils; +import cn.g3soft.fmsapi.utils.ParamUtils; +import jakarta.annotation.Resource; +import org.springframework.stereotype.Service; + +import java.sql.SQLException; +import java.util.List; +import java.util.Map; + +@Service +public class DataService { + + @Resource + private DbUtils dbUtils; + + public List> loadData(Map params) throws SQLException { + return dbUtils.loadData( + ParamUtils.getRequiredString(params, "viewName"), + ParamUtils.getString(params, "searchCondition"), + ParamUtils.getString(params, "orderField"), + ParamUtils.getList(params, "searchColumns") + ); + } + + public List> loadDataBySql(Map params) throws SQLException { + return dbUtils.loadDataBySql( + ParamUtils.getRequiredString(params, "sql") + ); + } +} diff --git a/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/utils/ApiResponse.java b/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/utils/ApiResponse.java new file mode 100644 index 00000000..8d34eddd --- /dev/null +++ b/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/utils/ApiResponse.java @@ -0,0 +1,25 @@ +package cn.g3soft.fmsapi.utils; + +public record ApiResponse( + int code, + String message, + T data +) { + + public static final int SUCCESS_CODE = 0; + public static final int AUTH_ERROR_CODE = 401; + public static final int SYSTEM_ERROR_CODE = 500; + public static final int BUSINESS_ERROR_CODE = 1000; + + public static ApiResponse success(T data) { + return new ApiResponse<>(SUCCESS_CODE, "操作成功", data); + } + + public static ApiResponse fail(String message) { + return fail(BUSINESS_ERROR_CODE, message); + } + + public static ApiResponse fail(int code, String message) { + return new ApiResponse<>(code, message, null); + } +} diff --git a/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/utils/DbUtils.java b/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/utils/DbUtils.java new file mode 100644 index 00000000..9d2dd5ec --- /dev/null +++ b/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/utils/DbUtils.java @@ -0,0 +1,245 @@ +package cn.g3soft.fmsapi.utils; + +import cn.g3soft.fmsapi.database.OrgDataSourceManager; +import cn.g3soft.fmsapi.exception.BusinessException; +import jakarta.annotation.Resource; +import org.springframework.jdbc.datasource.DataSourceUtils; +import org.springframework.stereotype.Component; + +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +@Component +public class DbUtils { + + private static final Pattern SAFE_IDENTIFIER = Pattern.compile("[A-Za-z_][A-Za-z0-9_]*"); + private static final Pattern READ_SQL_PATTERN = Pattern.compile("(?is)^\\s*(select|with)\\b"); + private static final Pattern WRITE_SQL_PATTERN = Pattern.compile( + "(?i)\\b(insert|update|delete|merge|drop|truncate|alter|create|exec|execute|grant|revoke|backup|restore|dbcc|kill|use|into)\\b" + ); + private static final Pattern SQL_COMMENT_PATTERN = Pattern.compile("--|/\\*|\\*/"); + + @Resource + private OrgDataSourceManager dataSourceManager; + + @Resource + private DataSource dataSource; + + public List> loadData(String viewName) throws SQLException { + return loadData(viewName, null, null, null); + } + + public List> loadData( + String viewName, + String searchCondition, + String orderField, + List searchColumns + ) throws SQLException { + String sql = buildLoadDataSql(viewName, searchCondition, orderField, searchColumns); + Connection connection = DataSourceUtils.getConnection(dataSource); + try { + return executeQuery(connection, sql); + } finally { + DataSourceUtils.releaseConnection(connection, dataSource); + } + } + + public List> loadData( + String orgId, + String viewName, + String searchCondition, + String orderField, + List searchColumns + ) throws SQLException { + String sql = buildLoadDataSql(viewName, searchCondition, orderField, searchColumns); + try (Connection connection = dataSourceManager.getConnection(orgId)) { + return executeQuery(connection, sql); + } + } + + private String buildLoadDataSql( + String viewName, + String searchCondition, + String orderField, + List searchColumns + ) { + String columnsSql = buildColumns(searchColumns); + StringBuilder sql = new StringBuilder("SELECT ") + .append(columnsSql) + .append(" FROM ") + .append(quoteQualifiedIdentifier(viewName)); + + if (hasText(searchCondition)) { + sql.append(" WHERE ").append(searchCondition.trim()); + } + if (hasText(orderField)) { + sql.append(" ORDER BY ").append(buildOrderBy(orderField)); + } + + String querySql = sql.toString(); + validateReadOnlySql(querySql); + return querySql; + } + + public List> loadDataBySql(String sql) throws SQLException { + validateReadOnlySql(sql); + + Connection connection = DataSourceUtils.getConnection(dataSource); + try { + return executeQuery(connection, sql); + } finally { + DataSourceUtils.releaseConnection(connection, dataSource); + } + } + + public List> loadDataBySql( + Connection connection, + String sql + ) throws SQLException { + if (connection == null) { + throw new IllegalArgumentException("数据库连接不能为空"); + } + validateReadOnlySql(sql); + + return executeQuery(connection, sql); + } + + private List> executeQuery( + Connection connection, + String sql + ) throws SQLException { + try (Statement statement = connection.createStatement()) { + try (ResultSet resultSet = statement.executeQuery(sql)) { + return readRows(resultSet); + } + } + } + + public String toSqlStringLiteral(String value) { + if (value == null) { + return "NULL"; + } + return "N'" + value.replace("'", "''") + "'"; + } + + public void validateIdentifier(String identifier) { + if (!hasText(identifier) || !SAFE_IDENTIFIER.matcher(identifier).matches()) { + throw new BusinessException("非法数据库标识符: " + identifier); + } + } + + public void validateReadOnlySql(String sql) { + if (!hasText(sql)) { + throw new BusinessException("查询 SQL 不能为空"); + } + + String normalizedSql = sql.trim(); + if (!READ_SQL_PATTERN.matcher(normalizedSql).find()) { + throw new BusinessException("只允许执行只读查询"); + } + String sqlStructure = removeStringLiterals(normalizedSql); + if (sqlStructure.contains(";")) { + throw new BusinessException("查询 SQL 不允许包含分号"); + } + if (SQL_COMMENT_PATTERN.matcher(sqlStructure).find()) { + throw new BusinessException("查询 SQL 不允许包含注释"); + } + if (WRITE_SQL_PATTERN.matcher(sqlStructure).find()) { + throw new BusinessException("查询 SQL 包含非只读关键字"); + } + } + + private String removeStringLiterals(String sql) { + StringBuilder result = new StringBuilder(sql.length()); + boolean inString = false; + + for (int index = 0; index < sql.length(); index++) { + char character = sql.charAt(index); + if (character != '\'') { + result.append(inString ? ' ' : character); + continue; + } + + if (inString && index + 1 < sql.length() && sql.charAt(index + 1) == '\'') { + result.append(" "); + index++; + continue; + } + + inString = !inString; + result.append(' '); + } + + if (inString) { + throw new BusinessException("SQL 字符串未闭合"); + } + return result.toString(); + } + + private String buildColumns(List searchColumns) { + if (searchColumns == null || searchColumns.isEmpty()) { + return "*"; + } + return searchColumns.stream() + .map(this::quoteQualifiedIdentifier) + .collect(Collectors.joining(", ")); + } + + private String buildOrderBy(String orderField) { + String[] parts = orderField.trim().split("\\s+"); + if (parts.length > 2) { + throw new BusinessException("排序字段格式不正确"); + } + + String direction = ""; + if (parts.length == 2) { + if (!"asc".equalsIgnoreCase(parts[1]) && !"desc".equalsIgnoreCase(parts[1])) { + throw new BusinessException("排序方向只允许 ASC 或 DESC"); + } + direction = " " + parts[1].toUpperCase(); + } + return quoteQualifiedIdentifier(parts[0]) + direction; + } + + private String quoteQualifiedIdentifier(String identifier) { + if (!hasText(identifier)) { + throw new BusinessException("数据库标识符不能为空"); + } + + return Arrays.stream(identifier.trim().split("\\.")) + .peek(this::validateIdentifier) + .map(part -> "[" + part + "]") + .collect(Collectors.joining(".")); + } + + private List> readRows(ResultSet resultSet) throws SQLException { + ResultSetMetaData metadata = resultSet.getMetaData(); + int columnCount = metadata.getColumnCount(); + List> rows = new ArrayList<>(); + + while (resultSet.next()) { + Map row = new LinkedHashMap<>(columnCount); + for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) { + row.put(metadata.getColumnLabel(columnIndex), resultSet.getObject(columnIndex)); + } + rows.add(row); + } + + return rows; + } + + private boolean hasText(String value) { + return value != null && !value.isBlank(); + } +} diff --git a/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/utils/JwtUtils.java b/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/utils/JwtUtils.java new file mode 100644 index 00000000..0852b1f8 --- /dev/null +++ b/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/utils/JwtUtils.java @@ -0,0 +1,62 @@ +package cn.g3soft.fmsapi.utils; + +import cn.g3soft.fmsapi.config.AuthProperties; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.security.Keys; +import jakarta.annotation.PostConstruct; +import jakarta.annotation.Resource; +import org.springframework.stereotype.Component; + +import javax.crypto.SecretKey; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.time.Instant; +import java.util.Date; + +@Component +public class JwtUtils { + + @Resource + private AuthProperties properties; + + private SecretKey signingKey; + private Duration expiration; + + @PostConstruct + public void init() { + String jwtSecret = properties.getJwtSecret(); + if (jwtSecret == null || jwtSecret.getBytes(StandardCharsets.UTF_8).length < 32) { + throw new IllegalStateException("JWT 密钥长度不能少于 32 字节"); + } + if (properties.getJwtExpiration() == null + || properties.getJwtExpiration().isZero() + || properties.getJwtExpiration().isNegative()) { + throw new IllegalStateException("JWT 有效期必须大于 0"); + } + + this.signingKey = Keys.hmacShaKeyFor(jwtSecret.getBytes(StandardCharsets.UTF_8)); + this.expiration = properties.getJwtExpiration(); + } + + public String generateToken(String userId, String orgId) { + Instant issuedAt = Instant.now(); + Instant expiresAt = issuedAt.plus(expiration); + + return Jwts.builder() + .subject(userId) + .claim("orgid", orgId) + .issuedAt(Date.from(issuedAt)) + .expiration(Date.from(expiresAt)) + .signWith(signingKey) + .compact(); + } + + public String getOrgId(String token) { + return Jwts.parser() + .verifyWith(signingKey) + .build() + .parseSignedClaims(token) + .getPayload() + .get("orgid", String.class); + } +} diff --git a/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/utils/ParamUtils.java b/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/utils/ParamUtils.java new file mode 100644 index 00000000..182835b3 --- /dev/null +++ b/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/utils/ParamUtils.java @@ -0,0 +1,59 @@ +package cn.g3soft.fmsapi.utils; + +import cn.g3soft.fmsapi.exception.BusinessException; + +import java.util.List; +import java.util.Map; + +public final class ParamUtils { + + private ParamUtils() { + } + + public static String getString(Map params, String field) { + return get(params, field, String.class); + } + + public static String getRequiredString(Map params, String field) { + String value = getString(params, field); + if (StringUtils.isBlank(value)) { + throw new BusinessException(field + " 不能为空"); + } + return value; + } + + public static T get(Map params, String field, Class type) { + Object value = getValue(params, field); + if (value == null) { + return null; + } + if (!type.isInstance(value)) { + throw new BusinessException(field + " 参数类型不正确"); + } + return type.cast(value); + } + + @SuppressWarnings("unchecked") + public static List getList(Map params, String field) { + Object value = getValue(params, field); + if (value == null) { + return null; + } + if (!(value instanceof List values)) { + throw new BusinessException(field + " 参数类型不正确"); + } + return (List) values; + } + + public static Object[] getArray(Map params, String field) { + List values = getList(params, field); + if (values == null) { + return null; + } + return values.toArray(); + } + + private static Object getValue(Map params, String field) { + return params == null ? null : params.get(field); + } +} diff --git a/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/utils/StringUtils.java b/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/utils/StringUtils.java new file mode 100644 index 00000000..7cfe4afe --- /dev/null +++ b/code/fms/fms-api/src/main/java/cn/g3soft/fmsapi/utils/StringUtils.java @@ -0,0 +1,11 @@ +package cn.g3soft.fmsapi.utils; + +public final class StringUtils { + + private StringUtils() { + } + + public static boolean isBlank(String value) { + return value == null || value.isBlank(); + } +} diff --git a/code/fms/fms-api/src/main/resources/application.yaml b/code/fms/fms-api/src/main/resources/application.yaml new file mode 100644 index 00000000..a6c149d2 --- /dev/null +++ b/code/fms/fms-api/src/main/resources/application.yaml @@ -0,0 +1,25 @@ +server: + servlet: + context-path: /api + +spring: + application: + name: fms-api + +fms: + auth: + jwt-secret: "${FMS_JWT_SECRET:fms-api-development-jwt-secret-change-me}" + jwt-expiration: 24h + database: + config-dir: ./config/dbconfigs + pool: + initial-size: 0 + min-idle: 0 + max-active: 10 + max-wait: 5000 + validation-query: SELECT 1 + test-while-idle: true + test-on-borrow: false + test-on-return: false + time-between-eviction-runs: 60s + min-evictable-idle-time: 5m diff --git a/code/fms/fms-api/src/test/java/cn/g3soft/fmsapi/FmsApiApplicationTests.java b/code/fms/fms-api/src/test/java/cn/g3soft/fmsapi/FmsApiApplicationTests.java new file mode 100644 index 00000000..6e0d7e0e --- /dev/null +++ b/code/fms/fms-api/src/test/java/cn/g3soft/fmsapi/FmsApiApplicationTests.java @@ -0,0 +1,13 @@ +package cn.g3soft.fmsapi; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class FmsApiApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/code/fms/fms-vue/package.json b/code/fms/fms-vue/package.json index ce2f57c5..01a7b5f3 100644 --- a/code/fms/fms-vue/package.json +++ b/code/fms/fms-vue/package.json @@ -11,8 +11,9 @@ "fmt:check": "oxfmt --check" }, "dependencies": { - "@antdv-next/icons": "1.1.1", + "@lucide/vue": "^1.24.0", "antdv-next": "^1.4.2", + "nprogress": "^0.2.0", "pinia": "^4.0.2", "pinia-plugin-persistedstate": "^4.7.1", "vue": "^3.5.39", diff --git a/code/fms/fms-vue/pnpm-lock.yaml b/code/fms/fms-vue/pnpm-lock.yaml index f741a37f..277e0208 100644 --- a/code/fms/fms-vue/pnpm-lock.yaml +++ b/code/fms/fms-vue/pnpm-lock.yaml @@ -8,12 +8,15 @@ importers: .: dependencies: - '@antdv-next/icons': - specifier: 1.1.1 - version: 1.1.1(vue@3.5.39) + '@lucide/vue': + specifier: ^1.24.0 + version: 1.24.0(vue@3.5.39) antdv-next: specifier: ^1.4.2 version: 1.4.2(vue@3.5.39) + nprogress: + specifier: ^0.2.0 + version: 0.2.0 pinia: specifier: ^4.0.2 version: 4.0.2(@vue/devtools-api@8.1.5)(vue@3.5.39) @@ -171,6 +174,11 @@ packages: '@jridgewell/trace-mapping@0.3.31': resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} + '@lucide/vue@1.24.0': + resolution: {integrity: sha512-5bNPX0G2YEWdUlBYk7pE8SgDg/f1mkIFpJ9vtE44pW/cwRz7Ioc0tOTESoVJAPvxIELSmYekX+XXIJMjsswNIg==} + peerDependencies: + vue: '>=3.0.1' + '@napi-rs/wasm-runtime@1.1.6': resolution: {integrity: sha512-ZLv/JdUfkvOy9eCnnBaGfiO+XimbjebAeO+MRQqD/B+FR1tnRN0tpKSJHRbE8sFfS6aqsXZ67TQjfwfsxULVbg==} peerDependencies: @@ -1094,6 +1102,9 @@ packages: nostics@1.1.4: resolution: {integrity: sha512-U4FApICSLCQ0dYiN59pxUCEZC053palQXi57yLaNdMaL6TBY4C4q3qZrJKUGcor2dGv8EhEwt8y5KvU2bo2kFg==} + nprogress@0.2.0: + resolution: {integrity: sha512-I19aIingLgR1fmhftnbWWO3dXc0hSxqHQHQb3H8m+K3TnEn/iSeTZZOyvKXWqQESMwuUVnatlCnZdLBZZt2VSA==} + obug@2.1.3: resolution: {integrity: sha512-9miFgM2OFba7hB+pRgvtV84pYTBaoTHohvmIgiRt6dRIzbwEOIaNaP+dIlGs2fNFoB0SeISs0Jz5WFVRid6Xyg==} engines: {node: '>=12.20.0'} @@ -1481,6 +1492,10 @@ snapshots: '@jridgewell/resolve-uri': 3.1.2 '@jridgewell/sourcemap-codec': 1.5.5 + '@lucide/vue@1.24.0(vue@3.5.39)': + dependencies: + vue: 3.5.39 + '@napi-rs/wasm-runtime@1.1.6(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.1)': dependencies: '@emnapi/core': 1.11.1 @@ -2291,6 +2306,8 @@ snapshots: nostics@1.1.4: {} + nprogress@0.2.0: {} + obug@2.1.3: {} oxfmt@0.58.0: diff --git a/code/fms/fms-vue/src/App.vue b/code/fms/fms-vue/src/App.vue index f5065806..9d556e9f 100644 --- a/code/fms/fms-vue/src/App.vue +++ b/code/fms/fms-vue/src/App.vue @@ -1,7 +1,15 @@ + + diff --git a/code/fms/fms-vue/src/data/mockRecords.js b/code/fms/fms-vue/src/data/mockRecords.js new file mode 100644 index 00000000..c99c0d48 --- /dev/null +++ b/code/fms/fms-vue/src/data/mockRecords.js @@ -0,0 +1,134 @@ +export const mockRecords = [ + { + id: "FY-2026-0001", + name: "华东区域运费结算", + state: "草稿", + customer: "华东客户中心", + businessType: "海运", + owner: "张三", + amount: "4,960.00", + currency: "CNY", + updated_at: "2026-07-16 09:20", + }, + { + id: "FY-2026-0002", + name: "华南客户月度账单", + state: "处理中", + customer: "华南供应链有限公司", + businessType: "空运", + owner: "李四", + amount: "6,240.00", + currency: "CNY", + updated_at: "2026-07-16 08:45", + }, + { + id: "FY-2026-0003", + name: "北方港口代理费用", + state: "已完成", + customer: "北方港口服务公司", + businessType: "陆运", + owner: "王五", + amount: "7,520.00", + currency: "USD", + updated_at: "2026-07-15 17:32", + }, + { + id: "FY-2026-0004", + name: "国际空运服务费", + state: "处理中", + customer: "国际物流有限公司", + businessType: "空运", + owner: "张三", + amount: "8,800.00", + currency: "CNY", + updated_at: "2026-07-15 16:10", + }, + { + id: "FY-2026-0005", + name: "出口报关服务费用", + state: "已完成", + customer: "远洋贸易有限公司", + businessType: "海运", + owner: "李四", + amount: "10,080.00", + currency: "CNY", + updated_at: "2026-07-15 14:56", + }, + { + id: "FY-2026-0006", + name: "华中干线运输费用", + state: "草稿", + customer: "华中运输服务公司", + businessType: "陆运", + owner: "王五", + amount: "11,360.00", + currency: "USD", + updated_at: "2026-07-15 11:24", + }, + { + id: "FY-2026-0007", + name: "仓储增值服务结算", + state: "已取消", + customer: "城市仓储有限公司", + businessType: "铁路", + owner: "张三", + amount: "12,640.00", + currency: "CNY", + updated_at: "2026-07-14 18:05", + }, + { + id: "FY-2026-0008", + name: "跨境电商物流账单", + state: "已完成", + customer: "跨境电商有限公司", + businessType: "空运", + owner: "李四", + amount: "13,920.00", + currency: "CNY", + updated_at: "2026-07-14 15:40", + }, + { + id: "FY-2026-0009", + name: "西南区域配送费用", + state: "处理中", + customer: "西南配送服务中心", + businessType: "陆运", + owner: "王五", + amount: "15,200.00", + currency: "USD", + updated_at: "2026-07-14 13:18", + }, + { + id: "FY-2026-0010", + name: "危险品运输服务费", + state: "草稿", + customer: "特种运输有限公司", + businessType: "海运", + owner: "张三", + amount: "16,480.00", + currency: "CNY", + updated_at: "2026-07-14 10:02", + }, + { + id: "FY-2026-0011", + name: "铁路联运代理费用", + state: "已完成", + customer: "铁路联运服务公司", + businessType: "铁路", + owner: "李四", + amount: "17,760.00", + currency: "CNY", + updated_at: "2026-07-13 16:27", + }, + { + id: "FY-2026-0012", + name: "客户临时加急费用", + state: "已取消", + customer: "重点客户服务中心", + businessType: "空运", + owner: "王五", + amount: "19,040.00", + currency: "USD", + updated_at: "2026-07-13 09:51", + }, +]; diff --git a/code/fms/fms-vue/src/layouts/DefaultLayout.vue b/code/fms/fms-vue/src/layouts/DefaultLayout.vue index 12dcd9f3..e632e1ad 100644 --- a/code/fms/fms-vue/src/layouts/DefaultLayout.vue +++ b/code/fms/fms-vue/src/layouts/DefaultLayout.vue @@ -1,431 +1,54 @@ diff --git a/code/fms/fms-vue/src/layouts/components/AppTabs.vue b/code/fms/fms-vue/src/layouts/components/AppTabs.vue new file mode 100644 index 00000000..b69746cd --- /dev/null +++ b/code/fms/fms-vue/src/layouts/components/AppTabs.vue @@ -0,0 +1,322 @@ + + + + + diff --git a/code/fms/fms-vue/src/layouts/components/AppToolbar.vue b/code/fms/fms-vue/src/layouts/components/AppToolbar.vue new file mode 100644 index 00000000..82dffaaf --- /dev/null +++ b/code/fms/fms-vue/src/layouts/components/AppToolbar.vue @@ -0,0 +1,179 @@ + + + + + diff --git a/code/fms/fms-vue/src/router/index.js b/code/fms/fms-vue/src/router/index.js index 2cd647f0..c7f063b3 100644 --- a/code/fms/fms-vue/src/router/index.js +++ b/code/fms/fms-vue/src/router/index.js @@ -1,4 +1,8 @@ import { createRouter, createWebHistory } from "vue-router"; +import NProgress from "nprogress"; +import "nprogress/nprogress.css"; + +NProgress.configure({ showSpinner: false }); const routes = [ { @@ -26,6 +30,19 @@ const routes = [ source: "v_bs_business", }, }, + { + path: "business/orders/:id", + name: "business-order-detail", + component: () => import("../views/DetailView.vue"), + meta: { + title: "业务单据详情", + listTitle: "业务单据", + section: "业务管理", + menuKey: "/business/orders", + listPath: "/business/orders", + detail: true, + }, + }, { path: "fees/receivable", name: "fees-receivable", @@ -37,6 +54,19 @@ const routes = [ source: "v_fee_receivable", }, }, + { + path: "fees/receivable/:id", + name: "fees-receivable-detail", + component: () => import("../views/DetailView.vue"), + meta: { + title: "应收费用详情", + listTitle: "应收费用", + section: "费用管理", + menuKey: "/fees/receivable", + listPath: "/fees/receivable", + detail: true, + }, + }, { path: "reports/operations", name: "reports-operations", @@ -48,6 +78,19 @@ const routes = [ source: "v_report_operations", }, }, + { + path: "reports/operations/:id", + name: "reports-operations-detail", + component: () => import("../views/DetailView.vue"), + meta: { + title: "运营报表详情", + listTitle: "运营报表", + section: "报表中心", + menuKey: "/reports/operations", + listPath: "/reports/operations", + detail: true, + }, + }, { path: "system/users", name: "system-users", @@ -59,6 +102,19 @@ const routes = [ source: "sys_user", }, }, + { + path: "system/users/:id", + name: "system-users-detail", + component: () => import("../views/DetailView.vue"), + meta: { + title: "用户管理详情", + listTitle: "用户管理", + section: "系统设置", + menuKey: "/system/users", + listPath: "/system/users", + detail: true, + }, + }, ], }, { @@ -74,9 +130,18 @@ const router = createRouter({ }); router.beforeEach((to) => { + NProgress.start(); document.title = to.meta.title ? `${to.meta.title} - FMS 管理系统` : "FMS 管理系统"; return true; }); +router.afterEach(() => { + NProgress.done(); +}); + +router.onError(() => { + NProgress.done(); +}); + export default router; diff --git a/code/fms/fms-vue/src/stores/app.js b/code/fms/fms-vue/src/stores/app.js index fe8c95c5..9290dbc0 100644 --- a/code/fms/fms-vue/src/stores/app.js +++ b/code/fms/fms-vue/src/stores/app.js @@ -1,10 +1,12 @@ import { defineStore } from "pinia"; +const createDefaultVisitedTabs = () => [{ key: "/dashboard", label: "工作台", closable: false }]; + export const useAppStore = defineStore("app", { state: () => ({ locale: "zh-CN", sidebarCollapsed: false, - visitedTabs: [{ key: "/dashboard", label: "工作台", closable: false }], + visitedTabs: createDefaultVisitedTabs(), }), actions: { toggleSidebar() { @@ -24,6 +26,10 @@ export const useAppStore = defineStore("app", { }, persist: { key: "fms-app", - pick: ["locale", "sidebarCollapsed", "visitedTabs"], + pick: ["locale"], + afterHydrate: ({ store }) => { + store.sidebarCollapsed = false; + store.visitedTabs = createDefaultVisitedTabs(); + }, }, }); diff --git a/code/fms/fms-vue/src/styles/main.scss b/code/fms/fms-vue/src/styles/main.scss index f36397ce..8307d546 100644 --- a/code/fms/fms-vue/src/styles/main.scss +++ b/code/fms/fms-vue/src/styles/main.scss @@ -16,12 +16,15 @@ body, #app, .ant-app, .theme-root { - min-height: 100%; + width: 100%; + height: 100%; + min-width: 0; + min-height: 0; margin: 0; } body { - min-width: 1200px; + overflow: hidden; } button, @@ -35,6 +38,14 @@ a { text-decoration: none; } +.lucide { + width: 16px; + height: 16px; + flex: none; + stroke-width: 1.8; + vertical-align: -0.125em; +} + .theme-root { --fms-bg: #f5f7fa; --fms-surface: #ffffff; @@ -46,6 +57,7 @@ a { color: var(--fms-text); background: var(--fms-bg); + overflow: hidden; } @media (prefers-reduced-motion: reduce) { diff --git a/code/fms/fms-vue/src/views/DashboardView.vue b/code/fms/fms-vue/src/views/DashboardView.vue index c97b336e..6486b954 100644 --- a/code/fms/fms-vue/src/views/DashboardView.vue +++ b/code/fms/fms-vue/src/views/DashboardView.vue @@ -1,17 +1,11 @@ diff --git a/code/fms/fms-vue/src/views/DetailView.vue b/code/fms/fms-vue/src/views/DetailView.vue new file mode 100644 index 00000000..48ec8450 --- /dev/null +++ b/code/fms/fms-vue/src/views/DetailView.vue @@ -0,0 +1,125 @@ + + + + + diff --git a/code/fms/fms-vue/src/views/LoginView.vue b/code/fms/fms-vue/src/views/LoginView.vue index 2644cd2f..46d702a6 100644 --- a/code/fms/fms-vue/src/views/LoginView.vue +++ b/code/fms/fms-vue/src/views/LoginView.vue @@ -1,7 +1,7 @@