From 90b991f3dd8ab4dcb59992bf942799ba4335ac9e Mon Sep 17 00:00:00 2001 From: together <3372184547@qq.com> Date: Mon, 16 Jun 2025 18:06:25 +0800 Subject: [PATCH] diyicitijiao --- .gitattributes | 2 + .gitignore | 33 ++ .mvn/wrapper/maven-wrapper.properties | 19 + mvnw | 259 ++++++++++++++ mvnw.cmd | 149 ++++++++ pom.xml | 111 ++++++ .../org/example/cg/ACCOUNT/common/Result.java | 29 ++ .../example/cg/ACCOUNT/config/WebConfig.java | 19 + .../ACCOUNT/controller/AccountController.java | 182 ++++++++++ .../cg/ACCOUNT/mapper/AccountMapper.java | 9 + .../org/example/cg/ACCOUNT/model/Account.java | 38 ++ .../BRANCH/controller/BranchController.java | 327 ++++++++++++++++++ .../cg/BRANCH/mapper/BranchMapper.java | 9 + .../org/example/cg/BRANCH/model/Branch.java | 106 ++++++ .../java/org/example/cg/CgApplication.java | 19 + .../example/cg/DISH/config/CorsConfig.java | 17 + .../cg/DISH/config/MybatisPlusConfig.java | 27 ++ .../cg/DISH/config/SecurityConfig.java | 28 ++ .../cg/DISH/controller/DishController.java | 120 +++++++ .../example/cg/DISH/mapper/DishMapper.java | 9 + .../java/org/example/cg/DISH/model/Dish.java | 76 ++++ .../security/JwtAuthenticationFilter.java | 53 +++ .../org/example/cg/DISH/security/JwtUtil.java | 99 ++++++ .../example/cg/ORDER/mapper/OrderMapper.java | 9 + .../org/example/cg/ORDER/model/Order.java | 44 +++ src/main/resources/application.yml | 63 ++++ .../org/example/cg/CgApplicationTests.java | 13 + 27 files changed, 1869 insertions(+) create mode 100644 .gitattributes create mode 100644 .gitignore create mode 100644 .mvn/wrapper/maven-wrapper.properties create mode 100644 mvnw create mode 100644 mvnw.cmd create mode 100644 pom.xml create mode 100644 src/main/java/org/example/cg/ACCOUNT/common/Result.java create mode 100644 src/main/java/org/example/cg/ACCOUNT/config/WebConfig.java create mode 100644 src/main/java/org/example/cg/ACCOUNT/controller/AccountController.java create mode 100644 src/main/java/org/example/cg/ACCOUNT/mapper/AccountMapper.java create mode 100644 src/main/java/org/example/cg/ACCOUNT/model/Account.java create mode 100644 src/main/java/org/example/cg/BRANCH/controller/BranchController.java create mode 100644 src/main/java/org/example/cg/BRANCH/mapper/BranchMapper.java create mode 100644 src/main/java/org/example/cg/BRANCH/model/Branch.java create mode 100644 src/main/java/org/example/cg/CgApplication.java create mode 100644 src/main/java/org/example/cg/DISH/config/CorsConfig.java create mode 100644 src/main/java/org/example/cg/DISH/config/MybatisPlusConfig.java create mode 100644 src/main/java/org/example/cg/DISH/config/SecurityConfig.java create mode 100644 src/main/java/org/example/cg/DISH/controller/DishController.java create mode 100644 src/main/java/org/example/cg/DISH/mapper/DishMapper.java create mode 100644 src/main/java/org/example/cg/DISH/model/Dish.java create mode 100644 src/main/java/org/example/cg/DISH/security/JwtAuthenticationFilter.java create mode 100644 src/main/java/org/example/cg/DISH/security/JwtUtil.java create mode 100644 src/main/java/org/example/cg/ORDER/mapper/OrderMapper.java create mode 100644 src/main/java/org/example/cg/ORDER/model/Order.java create mode 100644 src/main/resources/application.yml create mode 100644 src/test/java/org/example/cg/CgApplicationTests.java diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..3b41682 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +/mvnw text eol=lf +*.cmd text eol=crlf diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..667aaef --- /dev/null +++ b/.gitignore @@ -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/ diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..d58dfb7 --- /dev/null +++ b/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,19 @@ +# 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. +wrapperVersion=3.3.2 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip diff --git a/mvnw b/mvnw new file mode 100644 index 0000000..19529dd --- /dev/null +++ b/mvnw @@ -0,0 +1,259 @@ +#!/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.2 +# +# 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:]' +} + +# 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 <"${0%/*}/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.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${0##*/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 +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/mvnw.cmd b/mvnw.cmd new file mode 100644 index 0000000..249bdf3 --- /dev/null +++ b/mvnw.cmd @@ -0,0 +1,149 @@ +<# : 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.2 +@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) { "/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_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain" +if ($env:MAVEN_USER_HOME) { + $MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain" +} +$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::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 +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -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/pom.xml b/pom.xml new file mode 100644 index 0000000..86785b2 --- /dev/null +++ b/pom.xml @@ -0,0 +1,111 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.5.0 + + + org.example + CG + 0.0.1-SNAPSHOT + CG + CG + + + + + + + + + + + + + + + 17 + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + org.projectlombok + lombok + 1.18.36 + provided + + + + org.springframework.boot + spring-boot-starter-security + + + + + mysql + mysql-connector-java + 8.0.26 + + + + com.baomidou + mybatis-plus-spring-boot3-starter + 3.5.12 + + + + com.baomidou + mybatis-plus-jsqlparser + 3.5.12 + + + + com.alibaba + druid-spring-boot-starter + 1.2.18 + + + + io.jsonwebtoken + jjwt-api + 0.12.6 + + + + io.jsonwebtoken + jjwt-impl + 0.12.6 + + + + io.jsonwebtoken + jjwt-jackson + 0.12.6 + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/src/main/java/org/example/cg/ACCOUNT/common/Result.java b/src/main/java/org/example/cg/ACCOUNT/common/Result.java new file mode 100644 index 0000000..a81230d --- /dev/null +++ b/src/main/java/org/example/cg/ACCOUNT/common/Result.java @@ -0,0 +1,29 @@ +package org.example.cg.ACCOUNT.common; + +import lombok.Data; + +@Data +public class Result { + private int code; + private String msg; + private T data; + + public static Result success(T data) { + Result result = new Result<>(); + result.setCode(200); + result.setMsg("成功"); + result.setData(data); + return result; + } + + public static Result success() { + return success(null); + } + + public static Result error(String msg) { + Result result = new Result<>(); + result.setCode(500); + result.setMsg(msg); + return result; + } +} \ No newline at end of file diff --git a/src/main/java/org/example/cg/ACCOUNT/config/WebConfig.java b/src/main/java/org/example/cg/ACCOUNT/config/WebConfig.java new file mode 100644 index 0000000..7ad530d --- /dev/null +++ b/src/main/java/org/example/cg/ACCOUNT/config/WebConfig.java @@ -0,0 +1,19 @@ +package org.example.cg.ACCOUNT.config; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +public class WebConfig implements WebMvcConfigurer { + + @Value("${file.upload-dir}") + private String uploadDir; + + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + registry.addResourceHandler("/uploads/**") + .addResourceLocations("file:" + uploadDir + "/"); + } +} diff --git a/src/main/java/org/example/cg/ACCOUNT/controller/AccountController.java b/src/main/java/org/example/cg/ACCOUNT/controller/AccountController.java new file mode 100644 index 0000000..d059e9b --- /dev/null +++ b/src/main/java/org/example/cg/ACCOUNT/controller/AccountController.java @@ -0,0 +1,182 @@ +package org.example.cg.ACCOUNT.controller; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.example.cg.ACCOUNT.mapper.AccountMapper; +import org.example.cg.ACCOUNT.model.Account; +import org.example.cg.ACCOUNT.common.Result; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.bind.annotation.*; + +import java.time.LocalDateTime; + +@RestController +@RequestMapping("/accounts") +public class AccountController { + + @Autowired + private AccountMapper accountMapper; + + // 1. 获取所有账户信息(分页) + @GetMapping + public Result> getAllAccounts( + @RequestParam(defaultValue = "1") int pageNum, + @RequestParam(defaultValue = "10") int pageSize) { + + Page page = new Page<>(pageNum, pageSize); + Page accountPage = accountMapper.selectPage(page, null); + return Result.success(accountPage); + } + + // 2. 根据账户类型查询 + @GetMapping("/byType") + public Result> getAccountsByType( + @RequestParam String accountType, + @RequestParam(defaultValue = "1") int pageNum, + @RequestParam(defaultValue = "10") int pageSize) { + + LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); + queryWrapper.eq(Account::getAccountType, accountType); + + Page page = new Page<>(pageNum, pageSize); + Page resultPage = accountMapper.selectPage(page, queryWrapper); + return Result.success(resultPage); + } + + // 3. 新增账户 + @PostMapping + @Transactional + public Result createAccount(@RequestBody Account account) { + // 设置默认密码 + account.setAccountPassword("123456"); + account.setAccountId(null); + + // 设置创建和更新时间 + LocalDateTime now = LocalDateTime.now(); + account.setCreatedAt(now); + account.setUpdatedAt(now); + + // 设置默认逻辑删除状态 + account.setIsDeleted(0); + + // 执行插入 + int result = accountMapper.insert(account); + if (result > 0) { + return Result.success(account); + } else { + return Result.error("新增账户失败"); + } + } + + // 4. 逻辑删除账户 + @DeleteMapping("/{id}") + @Transactional + public Result deleteAccount(@PathVariable Long id) { + // 直接使用MyBatis Plus的deleteById方法 + int result = accountMapper.deleteById(id); + + if (result > 0) { + return Result.success(); + } else { + // 检查账户是否存在 + Account account = accountMapper.selectById(id); + if (account == null) { + return Result.error("账户不存在"); + } else { + return Result.error("删除账户失败"); + } + } + } + + + // 5. 编辑账户信息 + @PutMapping("/{id}") + @Transactional + public Result updateAccount( + @PathVariable Long id, + @RequestBody Account updatedAccount) { + + // 获取现有账户 + Account account = accountMapper.selectById(id); + if (account == null) { + return Result.error("账户不存在"); + } + + // 更新基本信息(排除密码、图片、创建时间) + account.setAccountName(updatedAccount.getAccountName()); + account.setAccountPhone(updatedAccount.getAccountPhone()); + account.setAccountGender(updatedAccount.getAccountGender()); + account.setAccountType(updatedAccount.getAccountType()); + + // 更新图片URL(如果提供了新URL) + if (updatedAccount.getAccountImg() != null && !updatedAccount.getAccountImg().isEmpty()) { + account.setAccountImg(updatedAccount.getAccountImg()); + } + + // 更新修改时间 + account.setUpdatedAt(LocalDateTime.now()); + + int result = accountMapper.updateById(account); + if (result > 0) { + return Result.success(account); + } else { + return Result.error("更新账户失败"); + } + } + + // 6. 重置密码 + @PutMapping("/{id}/reset-password") + @Transactional + public Result resetPassword(@PathVariable Long id) { + Account account = accountMapper.selectById(id); + if (account == null) { + return Result.error("账户不存在"); + } + + account.setAccountPassword("123456"); + account.setUpdatedAt(LocalDateTime.now()); + + int result = accountMapper.updateById(account); + if (result > 0) { + return Result.success(); + } else { + return Result.error("密码重置失败"); + } + } + + // 7. 条件模糊查询 + @GetMapping("/search") + public Result> searchAccounts( + @RequestParam(required = false) Long id, + @RequestParam(required = false) String accountName, + @RequestParam(required = false) String accountPhone, + @RequestParam(required = false) String accountGender, + @RequestParam(defaultValue = "1") int pageNum, + @RequestParam(defaultValue = "10") int pageSize) { + + LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); + + // 添加查询条件 + if (id != null) { + queryWrapper.eq(Account::getAccountId, id); + } + if (accountName != null && !accountName.isEmpty()) { + queryWrapper.like(Account::getAccountName, accountName); + } + if (accountPhone != null && !accountPhone.isEmpty()) { + queryWrapper.like(Account::getAccountPhone, accountPhone); + } + if (accountGender != null && !accountGender.isEmpty()) { + queryWrapper.like(Account::getAccountGender, accountGender); + } + + // 排除已删除的账户 + queryWrapper.eq(Account::getIsDeleted, 0); + + Page page = new Page<>(pageNum, pageSize); + Page resultPage = accountMapper.selectPage(page, queryWrapper); + return Result.success(resultPage); + } +} \ No newline at end of file diff --git a/src/main/java/org/example/cg/ACCOUNT/mapper/AccountMapper.java b/src/main/java/org/example/cg/ACCOUNT/mapper/AccountMapper.java new file mode 100644 index 0000000..f153a76 --- /dev/null +++ b/src/main/java/org/example/cg/ACCOUNT/mapper/AccountMapper.java @@ -0,0 +1,9 @@ +package org.example.cg.ACCOUNT.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.Mapper; +import org.example.cg.ACCOUNT.model.Account; + +@Mapper +public interface AccountMapper extends BaseMapper { +} \ No newline at end of file diff --git a/src/main/java/org/example/cg/ACCOUNT/model/Account.java b/src/main/java/org/example/cg/ACCOUNT/model/Account.java new file mode 100644 index 0000000..37fc70b --- /dev/null +++ b/src/main/java/org/example/cg/ACCOUNT/model/Account.java @@ -0,0 +1,38 @@ +package org.example.cg.ACCOUNT.model; + +import com.baomidou.mybatisplus.annotation.*; +import com.fasterxml.jackson.annotation.JsonFormat; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.time.LocalDateTime; + +@Data +@NoArgsConstructor +@AllArgsConstructor +@TableName("account") +public class Account { + @TableId(value = "account_id", type = IdType.AUTO) + private Long accountId; + + private String accountName; + private String accountPassword; + private String accountPhone; + private String accountType; + private String accountImg; + private String accountGender; + private String accountTag; + private String salary; + + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") + private LocalDateTime createdAt; + + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") + private LocalDateTime updatedAt; + + @TableLogic + @TableField("is_deleted") + private Integer isDeleted; + +} \ No newline at end of file diff --git a/src/main/java/org/example/cg/BRANCH/controller/BranchController.java b/src/main/java/org/example/cg/BRANCH/controller/BranchController.java new file mode 100644 index 0000000..1a81aa0 --- /dev/null +++ b/src/main/java/org/example/cg/BRANCH/controller/BranchController.java @@ -0,0 +1,327 @@ +package org.example.cg.BRANCH.controller; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; +import org.example.cg.BRANCH.model.Branch; +import org.example.cg.BRANCH.mapper.BranchMapper; +import org.example.cg.ACCOUNT.model.Account; +import org.example.cg.ACCOUNT.mapper.AccountMapper; + +import org.example.cg.ORDER.mapper.OrderMapper; +import org.example.cg.ORDER.model.Order; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + + +@RestController +@RequestMapping("/branch") // 定义请求路径前缀 +public class BranchController { + + @Autowired + private BranchMapper branchMapper; + @Autowired + private AccountMapper accountMapper; + @Autowired + private OrderMapper orderMapper; + + + /** + * 根据省份查询分店信息 + * @param province 省份名称 + * @return 分店列表 + */ + @GetMapping("/province/{province}") + public List getBranchesByProvince(@PathVariable String province) { + QueryWrapper queryWrapper = new QueryWrapper<>(); // 创建查询条件构造器 + queryWrapper.eq("province", province); // 设置查询条件:province字段等于指定值 + return branchMapper.selectList(queryWrapper); // 执行查询并返回结果列表 + } + + /** + * 根据ID逻辑删除分店 + * @param id 分店ID + * @return 删除结果(true表示成功,false表示失败) + */ + @DeleteMapping("/{id}") + public boolean deleteBranch(@PathVariable Long id) { + return branchMapper.deleteById(id) > 0; // 执行删除操作并返回影响行数,>0表示删除成功 + } + + // 新增分店接口 + @PostMapping("/add") + public boolean addBranch(@RequestBody Branch branch) { + // 设置默认值 + branch.setId(null); + branch.setStatus("营业中"); // 默认营业状态 + branch.setBossId(null); // 默认店长为空 + branch.setDeleted(0); // 默认未删除 + branch.setCreatedAt(LocalDate.now()); // 创建时间为当前日期 + branch.setUpdatedAt(LocalDate.now()); // 更新时间为当前日期 + + // 执行插入操作 + return branchMapper.insert(branch) > 0; + } + + + @PutMapping("/{id}") + public boolean updateBranch( + @PathVariable Long id, + @RequestBody Branch branch) { + + // 验证分店是否存在 + Branch existingBranch = branchMapper.selectById(id); + if (existingBranch == null) { + return false; + } + + // 创建更新包装器 + UpdateWrapper updateWrapper = new UpdateWrapper<>(); + updateWrapper.eq("branch_id", id); + + // 设置可更新字段 + if (branch.getName() != null) { + updateWrapper.set("branch_name", branch.getName()); + } + if (branch.getAddress() != null) { + updateWrapper.set("branch_address", branch.getAddress()); + } + if (branch.getPhone() != null) { + updateWrapper.set("branch_phone", branch.getPhone()); + } + if (branch.getStartTime() != null) { + updateWrapper.set("branch_start", branch.getStartTime()); + } + if (branch.getEndTime() != null) { + updateWrapper.set("branch_end", branch.getEndTime()); + } + + // 设置更新时间 + updateWrapper.set("updated_at", LocalDate.now()); + + // 执行更新 + return branchMapper.update(null, updateWrapper) > 0; + } + + /** + * 编辑负责人信息 + * @param branchId 分店ID + * @param request 包含更新信息的请求体 + * @return 更新结果 + */ + @PutMapping("/{branchId}/boss-info") + public boolean updateBossInfo( + @PathVariable Long branchId, + @RequestBody BossUpdateRequest request) { + + // 1. 获取分店信息 + Branch branch = branchMapper.selectById(branchId); + if (branch == null) { + return false; // 分店不存在 + } + + // 2. 检查分店是否有店长 + Long bossId = branch.getBossId(); + if (bossId == null) { + return false; // 分店没有店长 + } + + // 3. 获取店长账号信息 + Account bossAccount = accountMapper.selectById(bossId); + if (bossAccount == null) { + return false; // 店长账号不存在 + } + + // 4. 创建更新包装器 + UpdateWrapper updateWrapper = new UpdateWrapper<>(); + updateWrapper.eq("account_id", bossId); + + // 5. 更新字段(仅当请求中有提供值时更新) + if (request.getName() != null && !request.getName().isBlank()) { + updateWrapper.set("account_name", request.getName()); + } + if (request.getGender() != null && !request.getGender().isBlank()) { + updateWrapper.set("account_gender", request.getGender()); + } + if (request.getPhone() != null && !request.getPhone().isBlank()) { + updateWrapper.set("account_phone", request.getPhone()); + } + if (request.getSalary() != null) { + updateWrapper.set("salary", request.getSalary()); + } + + // 6. 执行更新 + return accountMapper.update(null, updateWrapper) > 0; + } + + + /** + * 根据分店ID获取负责人信息 + * @param branchId 分店ID + * @return 负责人Account对象 + */ + @GetMapping("/boss/{branchId}") + public Account getBossInfo(@PathVariable Long branchId) { + Branch branch = branchMapper.selectById(branchId); // 根据分店ID查询分店信息 + if (branch != null && branch.getBossId() != null) { + return accountMapper.selectById(branch.getBossId()); // 查询并返回负责人信息 + } else { + return null; // 分店不存在或没有负责人 + } + } + + /** + * 为分店设置店长 + * @param branchId 分店ID + * @param request 包含店长ID的请求体 + * @return 设置结果(true表示成功,false表示失败) + */ + @PutMapping("/{branchId}/boss") + public boolean setBranchBoss( + @PathVariable Long branchId, + @RequestBody BossRequest request) { + + // 1. 检查分店是否存在 + Branch branch = branchMapper.selectById(branchId); + if (branch == null) { + return false; // 分店不存在 + } + + // 2. 检查分店是否已有店长 + if (branch.getBossId() != null) { + return false; // 分店已有店长 + } + + // 3. 检查店长账号是否存在 + Account account = accountMapper.selectById(request.getBossId()); + if (account == null) { + return false; // 店长账号不存在 + } + + // 4. 更新分店信息 + UpdateWrapper updateWrapper = new UpdateWrapper<>(); + updateWrapper.eq("branch_id", branchId) + .set("branch_boss", request.getBossId()) + .set("updated_at", LocalDate.now()); + + return branchMapper.update(null, updateWrapper) > 0; + } + + + // 新增统计方法 + /** + * 根据分店ID统计每日订单数据 + * @param branchId 分店ID + * @return 每日统计结果 + */ + @GetMapping("/{branchId}/dailyStats") + public Map> getDailyStatsByBranch(@PathVariable Long branchId) { + // 查询该分店所有未删除的订单 + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.eq("branch_id", branchId) + .eq("is_deleted", 0); + List orders = orderMapper.selectList(queryWrapper); + + // 按日期分组并统计 + return orders.stream() + .collect(Collectors.groupingBy( + order -> order.getOrderTime().toLocalDate(), // 按日期分组 + Collectors.collectingAndThen( + Collectors.toList(), + list -> { + Map stats = new HashMap<>(); + stats.put("date", list.get(0).getOrderTime().toLocalDate()); + stats.put("orderCount", list.size()); + + // 计算总金额 + BigDecimal totalAmount = list.stream() + .map(Order::getOrderMoney) + .reduce(BigDecimal.ZERO, BigDecimal::add); + stats.put("totalAmount", totalAmount); + + return stats; + } + ) + )); + } + + /** + * 根据分店ID查询经纬度信息 + * @param id 分店ID + * @return 包含经纬度信息的Map + */ + @GetMapping("/location/{id}") + public Map getLocationById(@PathVariable Long id) { + Branch branch = branchMapper.selectById(id); + if (branch == null) { + throw new RuntimeException("分店不存在"); + } + + Map location = new HashMap<>(); + location.put("latitude", branch.getLatitude()); + location.put("longitude", branch.getLongitude()); + return location; + } + + // 内部类用于接收请求体 + static class BossRequest { + private Long bossId; + + // Getter和Setter + public Long getBossId() { + return bossId; + } + + public void setBossId(Long bossId) { + this.bossId = bossId; + } + } + + + // 内部类用于接收请求体 + static class BossUpdateRequest { + private String name; + private String gender; + private String phone; + private BigDecimal salary; + + // Getters and Setters + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getGender() { + return gender; + } + + public void setGender(String gender) { + this.gender = gender; + } + + public String getPhone() { + return phone; + } + + public void setPhone(String phone) { + this.phone = phone; + } + + public BigDecimal getSalary() { + return salary; + } + + public void setSalary(BigDecimal salary) { + this.salary = salary; + } + } +} diff --git a/src/main/java/org/example/cg/BRANCH/mapper/BranchMapper.java b/src/main/java/org/example/cg/BRANCH/mapper/BranchMapper.java new file mode 100644 index 0000000..3d0422c --- /dev/null +++ b/src/main/java/org/example/cg/BRANCH/mapper/BranchMapper.java @@ -0,0 +1,9 @@ +package org.example.cg.BRANCH.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.Mapper; +import org.example.cg.BRANCH.model.Branch; + +@Mapper +public interface BranchMapper extends BaseMapper { +} diff --git a/src/main/java/org/example/cg/BRANCH/model/Branch.java b/src/main/java/org/example/cg/BRANCH/model/Branch.java new file mode 100644 index 0000000..4d17a22 --- /dev/null +++ b/src/main/java/org/example/cg/BRANCH/model/Branch.java @@ -0,0 +1,106 @@ +package org.example.cg.BRANCH.model; + +import com.baomidou.mybatisplus.annotation.*; +import com.fasterxml.jackson.annotation.JsonFormat; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.math.BigDecimal; +import java.time.LocalDate; + +/** + * 分店实体类 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@TableName("branch") // 对应数据库表名 +public class Branch { + /** + * 分店ID(主键) + */ + @TableId(value = "branch_id", type = IdType.AUTO) + private Long id; + + /** + * 分店名称 + */ + @TableField("branch_name") + private String name; + + /** + * 分店地址 + */ + @TableField("branch_address") + private String address; + + /** + * 联系电话 + */ + @TableField("branch_phone") + private String phone; + + /** + * 营业开始时间 + */ + @TableField("branch_start") + private String startTime; + + /** + * 营业结束时间 + */ + @TableField("branch_end") + private String endTime; + + /** + * 分店状态(营业/停业) + */ + @TableField("branch_status") + private String status; + + /** + * 负责人ID(外键关联account表) + */ + @TableField("branch_boss") + private Long bossId; + + /** + * 所属省份 + */ + @TableField("province") + private String province; + + /** + * 创建时间 + */ + @JsonFormat(pattern = "yyyy-MM-dd") + @TableField("created_at") + private LocalDate createdAt; + + /** + * 最后更新时间 + */ + @JsonFormat(pattern = "yyyy-MM-dd") + @TableField("updated_at") + private LocalDate updatedAt; + + /** + * 逻辑删除 + */ + @TableLogic + @TableField("is_deleted") + private Integer deleted; + + /** + * 负责人ID(外键关联account表) + */ + @TableField("latitude") + private BigDecimal latitude; + + /** + * 负责人ID(外键关联account表) + */ + @TableField("longitude") + private BigDecimal longitude; +} \ No newline at end of file diff --git a/src/main/java/org/example/cg/CgApplication.java b/src/main/java/org/example/cg/CgApplication.java new file mode 100644 index 0000000..720d5a4 --- /dev/null +++ b/src/main/java/org/example/cg/CgApplication.java @@ -0,0 +1,19 @@ +package org.example.cg; + +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +@MapperScan("org.example.cg.DISH.config") +@MapperScan("org.example.cg.ACCOUNT.config") +@MapperScan("org.example.cg.BRANCH.config") +@MapperScan("org.example.cg.ORDER.config") + +public class CgApplication { + + public static void main(String[] args) { + SpringApplication.run(CgApplication.class, args); + } + +} diff --git a/src/main/java/org/example/cg/DISH/config/CorsConfig.java b/src/main/java/org/example/cg/DISH/config/CorsConfig.java new file mode 100644 index 0000000..9376e82 --- /dev/null +++ b/src/main/java/org/example/cg/DISH/config/CorsConfig.java @@ -0,0 +1,17 @@ +package org.example.cg.DISH.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.CorsRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +public class CorsConfig implements WebMvcConfigurer { + @Override + public void addCorsMappings(CorsRegistry registry) { + registry.addMapping("/**") // 允许所有路径 + .allowedOrigins("http://localhost:924") // 允许的前端源 + .allowedMethods("GET", "POST", "PUT", "DELETE") // 允许的 HTTP 方法 + .allowedHeaders("*") // 允许的请求头 + .allowCredentials(true); // 是否允许携带 Cookie + } +} \ No newline at end of file diff --git a/src/main/java/org/example/cg/DISH/config/MybatisPlusConfig.java b/src/main/java/org/example/cg/DISH/config/MybatisPlusConfig.java new file mode 100644 index 0000000..28cddc1 --- /dev/null +++ b/src/main/java/org/example/cg/DISH/config/MybatisPlusConfig.java @@ -0,0 +1,27 @@ +package org.example.cg.DISH.config; + +import com.baomidou.mybatisplus.annotation.DbType; +import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; +import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor; +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +@MapperScan("org.example.cg.DISH.mapper") +@MapperScan("org.example.cg.ACCOUNT.mapper") +@MapperScan("org.example.cg.BRANCH.mapper") +@MapperScan("org.example.cg.ORDER.mapper") +public class MybatisPlusConfig { + + /** + * 添加分页插件 + */ + @Bean + public MybatisPlusInterceptor mybatisPlusInterceptor() { + MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); + interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); // 如果配置多个插件, 切记分页最后添加 + // 如果有多数据源可以不配具体类型, 否则都建议配上具体的 DbType + return interceptor; + } +} \ No newline at end of file diff --git a/src/main/java/org/example/cg/DISH/config/SecurityConfig.java b/src/main/java/org/example/cg/DISH/config/SecurityConfig.java new file mode 100644 index 0000000..0c60a12 --- /dev/null +++ b/src/main/java/org/example/cg/DISH/config/SecurityConfig.java @@ -0,0 +1,28 @@ +package org.example.cg.DISH.config; + +import org.example.cg.DISH.security.JwtAuthenticationFilter; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.web.SecurityFilterChain; + +@Configuration +public class SecurityConfig { + @Autowired + private JwtAuthenticationFilter jwtAuthenticationFilter; + @Bean + public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { + http + .csrf(csrf -> csrf.disable()) // 禁用 CSRF + .authorizeHttpRequests(authorize ->authorize + .requestMatchers("/dishes", "/dishes/search").permitAll() // 放行登录和注册接口 + .anyRequest().permitAll() + //.anyRequest().authenticated() // 其他请求需要认证 + ) + //.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class) // 使用自定义 JWT 过滤器 + .formLogin(form -> form.disable()) ;// 禁用表单登录 + return http.build(); + } +} + diff --git a/src/main/java/org/example/cg/DISH/controller/DishController.java b/src/main/java/org/example/cg/DISH/controller/DishController.java new file mode 100644 index 0000000..78c6939 --- /dev/null +++ b/src/main/java/org/example/cg/DISH/controller/DishController.java @@ -0,0 +1,120 @@ +package org.example.cg.DISH.controller; + + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.example.cg.DISH.mapper.DishMapper; +import org.example.cg.DISH.model.Dish; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.time.LocalDateTime; +import java.util.List; + +/** + * 菜品管理控制器 + * 提供菜品的增删改查、分类查询、价格区间筛选等RESTful接口 + */ +@RestController +@RequestMapping("/dishes") +public class DishController { + + @Autowired + private DishMapper dishMapper; + + /** + * 根据菜品分类分页查询菜品数据 + * @param category 分类名称 + * @param page 当前页码 + * @param size 每页数量 + * @return 分页结果 + */ + @GetMapping("/category/{category}") + public IPage getDishesByCategory( + @PathVariable String category, + @RequestParam(defaultValue = "1") int page, + @RequestParam(defaultValue = "10") int size + ) { + IPage dishPage = new Page<>(page, size); + return dishMapper.selectPage(dishPage, + new LambdaQueryWrapper() + .eq(Dish::getCategory, category) + .orderByDesc(Dish::getCreatedAt)); + } + + /** + * 新增菜品 + * @param dish 菜品对象(需包含name, price, imageUrl, category, status) + * @return 新增的菜品对象 + */ + @PostMapping + public Dish createDish(@RequestBody Dish dish) { + dish.setCreatedAt(LocalDateTime.now()); + dish.setUpdatedAt(LocalDateTime.now()); + dish.setId(null); + dishMapper.insert(dish); + return dish; + } + + /** + * 编辑菜品 + * @param id 菜品ID + * @param updatedDish 修改后的菜品数据 + * @return 修改结果(1表示成功) + */ + @PutMapping("/{id}") + public Integer updateDish(@PathVariable Long id, @RequestBody Dish updatedDish) { + updatedDish.setId(id); + updatedDish.setUpdatedAt(LocalDateTime.now()); + return dishMapper.updateById(updatedDish); + } + + /** + * 删除菜品 + * @param id 菜品ID + * @return 删除结果(1表示成功) + */ + @DeleteMapping("/{id}") + public Integer deleteDish(@PathVariable Long id) { + return dishMapper.deleteById(id); + } + + /** + * 多条件搜索菜品(支持 ID 精确查询和名称模糊查询) + * @param keyword 查询关键词(可为 ID 或名称) + * @param page 当前页码 + * @param size 每页数量 + * @return 分页结果 + */ + @GetMapping("/search") + public Page searchDishes( + @RequestParam String keyword, + @RequestParam(defaultValue = "1") int page, + @RequestParam(defaultValue = "10") int size + ) { + Page dishPage = new Page<>(page, size); + LambdaQueryWrapper query = new LambdaQueryWrapper<>(); + + try { + // 尝试将 keyword 转换为 Long 类型的 ID + Long id = Long.parseLong(keyword); + query.eq(Dish::getId, id); + } catch (NumberFormatException e) { + // 无法转换为 ID 时,执行名称模糊查询 + query.like(Dish::getName, keyword); + } + + return dishMapper.selectPage(dishPage, query); + } + + /** + * 获取所有菜品列表(带排序) + * @return 所有菜品列表 + */ + @GetMapping + public List getAllDishes() { + return dishMapper.selectList(new LambdaQueryWrapper() + .orderByDesc(Dish::getCreatedAt)); + } +} \ No newline at end of file diff --git a/src/main/java/org/example/cg/DISH/mapper/DishMapper.java b/src/main/java/org/example/cg/DISH/mapper/DishMapper.java new file mode 100644 index 0000000..0214e08 --- /dev/null +++ b/src/main/java/org/example/cg/DISH/mapper/DishMapper.java @@ -0,0 +1,9 @@ +package org.example.cg.DISH.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.Mapper; +import org.example.cg.DISH.model.Dish; + +@Mapper +public interface DishMapper extends BaseMapper { +} diff --git a/src/main/java/org/example/cg/DISH/model/Dish.java b/src/main/java/org/example/cg/DISH/model/Dish.java new file mode 100644 index 0000000..763a945 --- /dev/null +++ b/src/main/java/org/example/cg/DISH/model/Dish.java @@ -0,0 +1,76 @@ +package org.example.cg.DISH.model; + +import com.baomidou.mybatisplus.annotation.*; +import com.fasterxml.jackson.annotation.JsonFormat; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import java.time.LocalDateTime; + +/** + * 菜品实体类 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@TableName("dishes") // 对应数据库表名 +public class Dish { + /** + * 菜品ID(主键) + */ + @TableId(value = "dish_id", type = IdType.AUTO) + private Long id; + + /** + * 菜品名称 + */ + @TableField("dish_name") + private String name; + + /** + * 菜品分类(如川菜/饮品等) + */ + private String category; + + /** + * 菜品价格 + */ + private Double price; + + /** + * 当前库存数量 + */ + private Integer stock; + + /** + * 菜品状态(在售/停售) + */ + private String status; + + /** + * 菜品描述 + */ + private String description; + + /** + * 菜品图片存储路径 + */ + private String imageUrl; + + /** + * 累计销售数量 + */ + private Integer sales; + + /** + * 创建时间 + */ + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") + private LocalDateTime createdAt; + + /** + * 最后更新时间 + */ + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") + private LocalDateTime updatedAt; +} \ No newline at end of file diff --git a/src/main/java/org/example/cg/DISH/security/JwtAuthenticationFilter.java b/src/main/java/org/example/cg/DISH/security/JwtAuthenticationFilter.java new file mode 100644 index 0000000..c19cd0a --- /dev/null +++ b/src/main/java/org/example/cg/DISH/security/JwtAuthenticationFilter.java @@ -0,0 +1,53 @@ +package org.example.cg.DISH.security; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; + +@Component +public class JwtAuthenticationFilter extends OncePerRequestFilter { + + @Autowired + private JwtUtil jwtUtil; // 引入 JwtUtil 类,用于处理 token 验证和解析 + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { + // 获取请求头中的 Authorization 字段中的 token + String token = request.getHeader("Authorization"); + + // 判断 token 是否存在且以 "Bearer " 开头 + if (token != null && token.startsWith("Bearer ")) { + // 去除 "Bearer " 前缀,获取纯净的 token + token = token.substring(7); + + // 验证 token 是否有效 + if (jwtUtil.isTokenValid(token)) { + // 解析 token 获取用户名 + String username = jwtUtil.getUsernameFromToken(token); + + // 创建一个身份验证对象(这里暂时不传权限信息,可以根据实际需求添加) + UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken( + username, null, null); + + // 设置额外的用户信息(如请求来源等) + authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); + + // 将认证信息设置到 Spring Security 的 SecurityContext 中 + SecurityContextHolder.getContext().setAuthentication(authenticationToken); + } + } + + // 继续请求的处理 + filterChain.doFilter(request, response); + } +} + diff --git a/src/main/java/org/example/cg/DISH/security/JwtUtil.java b/src/main/java/org/example/cg/DISH/security/JwtUtil.java new file mode 100644 index 0000000..359e9a8 --- /dev/null +++ b/src/main/java/org/example/cg/DISH/security/JwtUtil.java @@ -0,0 +1,99 @@ +package org.example.cg.DISH.security; + +import io.jsonwebtoken.*; +import io.jsonwebtoken.security.SignatureException; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import java.util.Date; + +@Component +public class JwtUtil { + + @Value("${jwt.secret}") + private String secretKey; // 从配置文件中读取的密钥 + + @Value("${jwt.expiration}") + private long expirationTime; // 从配置文件中读取的 Token 有效期(毫秒) + + /** + * 生成 JWT Token。 + * 包含用户 ID 和用户名。 + * @param userId 用户 ID + * @param username 用户名 + * @return String 生成的 JWT Token + */ + public String generateToken(Long userId, String username) { + return Jwts.builder() // 创建 JWT 构建器 + .setSubject(String.valueOf(userId)) // 设置用户 ID 作为主题 + .claim("username", username) // 添加用户名作为自定义 Claims + .setExpiration(new Date(System.currentTimeMillis() + expirationTime)) // 设置 Token 过期时间 + .signWith(SignatureAlgorithm.HS256, secretKey.getBytes()) // 使用 HMAC-SHA256 签名 + .compact(); // 构建并压缩 Token + } + + /** + * 解析 JWT Token。 + * 提取 Token 的 Claims 部分。 + * @param token JWT Token + * @return Claims 解析后的 Claims + * @throws RuntimeException 如果 Token 无效或已过期 + */ + public Claims parseToken(String token) { + try { + return Jwts.parser() // 创建 JWT 解析器 + .setSigningKey(secretKey.getBytes()) // 设置签名密钥 + .build() + .parseSignedClaims(token) // 解析 Token + .getPayload(); // 提取 Claims 部分 + } catch (ExpiredJwtException e) { + throw new RuntimeException("Token 已过期", e); // 捕获 Token 过期异常 + } catch (SignatureException e) { + throw new RuntimeException("无效的 JWT 签名", e); // 捕获签名验证失败异常 + } catch (JwtException e) { + throw new RuntimeException("无效的 JWT Token", e); // 捕获其他 JWT 异常 + } + } + + /** + * 从 Token 中提取用户 ID。 + * @param token JWT Token + * @return Long 用户 ID + */ + public Long getUserIdFromToken(String token) { + Claims claims = parseToken(token); // 解析 Token + return Long.valueOf(claims.getSubject()); // 提取用户 ID + } + + /** + * 从 Token 中提取用户名。 + * @param token JWT Token + * @return String 用户名 + */ + public String getUsernameFromToken(String token) { + Claims claims = parseToken(token); // 解析 Token + return claims.get("username", String.class); // 提取用户名 + } + + /** + * 判断 Token 是否有效。 + * 校验 Token 的签名和有效期。 + * @param token JWT Token + * @return boolean 是否有效 + */ + public boolean isTokenValid(String token) { + try { + Jwts.parser() // 创建 JWT 解析器 + .setSigningKey(secretKey.getBytes()) // 设置签名密钥 + .build() + .parseClaimsJws(token); // 解析 Token + return true; // 如果解析成功,返回 true + } catch (ExpiredJwtException e) { + // Token 已过期 + return false; + } catch (JwtException e) { + // 其他 JWT 异常,例如签名无效 + return false; + } + } +} diff --git a/src/main/java/org/example/cg/ORDER/mapper/OrderMapper.java b/src/main/java/org/example/cg/ORDER/mapper/OrderMapper.java new file mode 100644 index 0000000..b5503f3 --- /dev/null +++ b/src/main/java/org/example/cg/ORDER/mapper/OrderMapper.java @@ -0,0 +1,9 @@ +package org.example.cg.ORDER.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.Mapper; +import org.example.cg.ORDER.model.Order; + +@Mapper +public interface OrderMapper extends BaseMapper { +} diff --git a/src/main/java/org/example/cg/ORDER/model/Order.java b/src/main/java/org/example/cg/ORDER/model/Order.java new file mode 100644 index 0000000..0709f04 --- /dev/null +++ b/src/main/java/org/example/cg/ORDER/model/Order.java @@ -0,0 +1,44 @@ +package org.example.cg.ORDER.model; + +import com.baomidou.mybatisplus.annotation.*; +import lombok.Data; +import java.math.BigDecimal; +import java.time.LocalDateTime; + +@Data +@TableName("`order`") // 使用反引号因为order是SQL关键字 +public class Order { + @TableId(value = "order_id", type = IdType.AUTO) + private Long id; + + @TableField("account_id") + private Long accountId; + + @TableField("order_time") + private LocalDateTime orderTime; + + @TableField("branch_id") + private Long branchId; + + @TableField("order_money") + private BigDecimal orderMoney; + + @TableField("order_remarks") + private String remarks; + + @TableLogic + @TableField("is_deleted") + private Integer deleted; + + @TableField("deleted_at") + private LocalDateTime deletedAt; + + @TableField("created_at") + private LocalDateTime createdAt; + + @TableField("updated_at") + private LocalDateTime updatedAt; + + @TableField("order_status") + private Integer status; +} \ No newline at end of file diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 0000000..d581ec3 --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,63 @@ +#spring: +# application: +# name: cg +# datasource: # ??????? +# type: com.alibaba.druid.pool.DruidDataSource # ??Druid????? +# driver-class-name: com.mysql.cj.jdbc.Driver # ??MySQL????JDBC??? +# url: jdbc:mysql://mysql.zhujinjie.me:3306/cg # ?????????????????? +# username: root # ???????? +# password: .JS1045012666. # ??????? +# security: +# user: +# name: user +# password: 123 +# servlet: +# multipart: +# enabled: true +# max-file-size: 10MB +# max-request-size: 10MB +# location: ./uploads +## web: +## resources: +## static-locations: classpath:/static/, file:./uploads/ +#jwt: +# secret: "your_very_long_secret_key_here_with_at_least_32_bytes" # ????????????JWT,???????32?? +# expiration: 3600000 # ?????????????? 3600000 ?? 1 ?? +# +spring: + application: + name: cg + datasource: # 数据库配置 + type: com.alibaba.druid.pool.DruidDataSource # 使用Druid连接池 + driver-class-name: com.mysql.cj.jdbc.Driver # MySQL驱动 + url: jdbc:mysql://mysql.zhujinjie.me:3306/cg # 数据库连接URL + username: root # 数据库用户名 + password: .JS1045012666. # 数据库密码 + security: + user: + name: user + password: 123 + servlet: + multipart: + enabled: true + max-file-size: 10MB + max-request-size: 10MB + location: ./uploads + +# 文件上传配置 +file: + upload-dir: ./uploads # 文件上传目录,与multipart.location保持一致 + +# MyBatis Plus 配置 +mybatis-plus: + configuration: + map-underscore-to-camel-case: true # 开启驼峰命名自动映射 + global-config: + db-config: + logic-delete-field: is_deleted # 逻辑删除字段名 + logic-delete-value: 1 # 逻辑删除值 + logic-not-delete-value: 0 # 逻辑未删除值 + +jwt: + secret: "your_very_long_secret_key_here_with_at_least_32_bytes" # JWT密钥,建议至少32位 + expiration: 3600000 # JWT有效期,3600000毫秒=1小时 \ No newline at end of file diff --git a/src/test/java/org/example/cg/CgApplicationTests.java b/src/test/java/org/example/cg/CgApplicationTests.java new file mode 100644 index 0000000..ee59580 --- /dev/null +++ b/src/test/java/org/example/cg/CgApplicationTests.java @@ -0,0 +1,13 @@ +package org.example.cg; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class CgApplicationTests { + + @Test + void contextLoads() { + } + +}