commit 6958c081d4611cda3f2d8560a6d27bb98acc7067 Author: Doubleyin <953994191@qq.com> Date: Fri Sep 26 00:29:15 2025 +0800 初始提交:部署 Spring Boot 应用 diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..0725c8c --- /dev/null +++ b/.dockerignore @@ -0,0 +1,26 @@ +# 排除Git目录 +.git +.gitignore + +# 排除IDE相关文件 +.idea/ +*.iml +*.iws +*.ipr +.vscode/ + +# 排除日志文件 +*.log + +# 排除构建输出目录 +target/ +!target/light-delivery-1.0.0.jar + +# 排除Maven相关文件 +.mvn/ +mvnw +mvnw.cmd + +# 排除系统文件 +.DS_Store +Thumbs.db \ No newline at end of file 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..67e211f --- /dev/null +++ b/.gitignore @@ -0,0 +1,93 @@ +# 项目构建输出目录 +target/ +!target/**/*.jar +build/ +out/ +bin/ + +# IDE 相关文件 +## IntelliJ IDEA +.idea/ +*.iws +*.iml +*.ipr +out/ + +## Eclipse +.settings/ +.classpath +.project +.metadata +bin/ +tmp/ +*.tmp +*.bak +*.swp +*~.nib +local.properties +.loadpath + +## NetBeans +.nb-gradle/ +build/ + +# 操作系统生成文件 +## macOS +.DS_Store +.AppleDouble +.LSOverride +Icon +._* +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +## Windows +Thumbs.db +ehthumbs.db +Desktop.ini +$RECYCLE.BIN/ +*.lnk + +## Linux +*~ + +# 日志文件 +*.log +logs/ +!**/src/main/resources/logback-spring.xml + +# 临时文件 +*.tmp +*.temp + +# Maven 包装器 +.mvn/ +mvnw +mvnw.cmd +!mvnw +!mvnw.cmd + +# 应用配置文件(通常外部化,但根据情况调整) +## 如果你选择将配置文件外置(不打包进JAR),并让每个环境单独管理,可以考虑忽略具体的配置文件。 +## 如果配置文件包含敏感信息(如密码),务必忽略;若只是样例,则不必。 +#**/src/main/resources/application*.yml +#**/src/main/resources/application*.properties +#**/src/main/resources/*.xml + +# 数据库文件 +*.db +*.sqlite + +# 大型文件或目录 +large-files/ +archived/ \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..0fdd859 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,22 @@ +# 使用官方 OpenJDK 运行时作为基础镜像 +FROM openjdk:17-jdk-slim + +# 设置维护者信息 +LABEL maintainer="Light Delivery Application" + +# 设置工作目录 +WORKDIR /app + +# 将 jar 文件复制到容器中 +COPY target/*.jar app.jar + +# 暴露应用程序端口 +EXPOSE 443 80 + +# 设置环境变量 +ENV JAVA_OPTS="" +ENV KEY_STORE_PASSWORD="" +ENV SPRING_PROFILES_ACTIVE="prod" + +# 运行应用程序 +ENTRYPOINT ["sh", "-c", "java $JAVA_OPTS -jar app.jar --spring.profiles.active=$SPRING_PROFILES_ACTIVE"] \ No newline at end of file diff --git a/HELP.md b/HELP.md new file mode 100644 index 0000000..e7cfb2c --- /dev/null +++ b/HELP.md @@ -0,0 +1,28 @@ +# Getting Started + +### Reference Documentation + +For further reference, please consider the following sections: + +* [Official Apache Maven documentation](https://maven.apache.org/guides/index.html) +* [Spring Boot Maven Plugin Reference Guide](https://docs.spring.io/spring-boot/3.5.6/maven-plugin) +* [Create an OCI image](https://docs.spring.io/spring-boot/3.5.6/maven-plugin/build-image.html) +* [Spring Web](https://docs.spring.io/spring-boot/3.5.6/reference/web/servlet.html) + +### Guides + +The following guides illustrate how to use some features concretely: + +* [Accessing data with MySQL](https://spring.io/guides/gs/accessing-data-mysql/) +* [Building a RESTful Web Service](https://spring.io/guides/gs/rest-service/) +* [Serving Web Content with Spring MVC](https://spring.io/guides/gs/serving-web-content/) +* [Building REST services with Spring](https://spring.io/guides/tutorials/rest/) + +### Maven Parent overrides + +Due to Maven's design, elements are inherited from the parent POM to the project POM. +While most of the inheritance is fine, it also inherits unwanted elements like `` and `` from the +parent. +To prevent this, the project POM contains empty overrides for these elements. +If you manually switch to a different parent and actually want the inheritance, you need to remove those overrides. + diff --git a/README.md b/README.md new file mode 100644 index 0000000..e7ae4ed --- /dev/null +++ b/README.md @@ -0,0 +1,147 @@ +# Light Delivery 后端项目 + +## 项目概述 + +Light Delivery 是一个为小程序配送服务设计的后端系统,提供了用户管理、订单管理、配送员管理、位置同步等核心功能。 + +## 技术栈 + +- Java 17 +- Spring Boot 3.1.4 +- Spring Data JPA +- Spring WebSocket +- MySQL +- Redis +- Maven + +## 主要功能模块 + +### 1. 用户管理 +- 微信小程序登录 +- 用户角色管理(管理员、配送员、游客) +- 用户签到功能 + +### 2. 订单管理 +- 订单创建与查询 +- 订单状态跟踪 +- 订单指派给配送员 + +### 3. 配送员管理 +- 配送员注册 +- 配送员位置实时同步 +- 配送员状态管理 + +### 4. 位置同步 +- 基于WebSocket的实时位置同步 +- REST API位置查询接口 +- 位置过期处理机制 + +## 项目结构 + +``` +src +├── main +│ ├── java +│ │ └── com +│ │ └── light +│ │ └── delivery +│ │ ├── config # 配置类 +│ │ ├── controller # 控制器层 +│ │ ├── dto # 数据传输对象 +│ │ ├── exception # 异常处理 +│ │ ├── model # 实体模型 +│ │ ├── repository # 数据访问层 +│ │ ├── service # 业务逻辑层 +│ │ │ └── impl # 业务逻辑实现 +│ │ └── util # 工具类 +│ └── resources +│ ├── application.properties # 配置文件 +│ └── db # 数据库脚本 +└── test # 测试代码 +``` + +## 核心设计 + +### 认证授权机制 + +系统采用基于JWT的无状态认证机制: + +1. 用户通过微信登录获取code +2. 后端通过code换取用户openid +3. 根据openid查找或创建用户 +4. 生成JWT Token返回给前端 +5. 前端在后续请求中通过Authorization头携带Token +6. 后端通过拦截器验证Token有效性 + +### 实时位置同步 + +位置同步采用双通道设计: + +1. WebSocket实时推送:建立长连接,服务器主动推送位置更新 +2. REST API查询:提供HTTP接口查询当前位置信息 + +位置信息现在存储在服务器内存缓存中,而不是持久化到数据库,以提高访问速度和减少数据库负载。 + +### 数据模型 + +主要实体包括: +- User:用户基础信息实体(所有用户通用) +- Employee:员工信息实体(后台配置数据,用于验证用户身份) +- DeliveryPerson:配送员扩展信息实体 +- Order:订单实体 + +用户系统架构说明: +- 所有用户首先以游客身份静默登录,创建User记录 +- 用户签到或注册时,系统根据手机号在Employee表中查找匹配记录 +- 如果匹配成功,将用户的openid写入Employee表,表示该员工已成为系统用户 +- 根据Employee中的角色信息更新User的角色 +- 对于配送员,还会创建或更新DeliveryPerson记录 + +## 部署说明 + +1. 确保安装了Java 17和Maven +2. 配置MySQL数据库 +3. 修改`application.properties`中的数据库连接信息 +4. 运行`mvn spring-boot:run`启动项目 + +## API接口 + +主要API接口包括: + +### 用户相关 +- `POST /user/wxlogin` - 微信登录 +- `GET /user/info` - 获取用户信息 +- `POST /user/logout` - 用户登出 +- `POST /user/signin` - 用户签到 +- `POST /user/register` - 注册为配送员 + +### 订单相关 +- `GET /orders` - 获取订单列表 +- `GET /orders/{id}` - 获取订单详情 +- `POST /orders/{id}/assign` - 指派订单 + +### 配送员相关 +- `GET /delivery-persons` - 获取配送员列表 +- `GET /delivery-persons/{id}` - 获取配送员详情 +- `PUT /delivery-persons/{id}/location` - 更新配送员位置 + +### 位置同步相关 +- `GET /location-sync/delivery-persons/locations` - 获取所有配送员位置 + +## 最近更新 + +### 位置历史记录功能移除 +为了简化系统架构并提高性能,我们移除了位置历史记录功能。具体变更包括: +- 删除了`LocationHistory`实体类 +- 删除了`LocationHistoryRepository`数据访问接口 +- 删除了`LocationService`服务接口及其实现类`LocationServiceImpl` +- 删除了`LocationController`控制器及相关API端点 + +位置信息现在完全基于实时同步机制,存储在服务器内存中,不再持久化到数据库。 + +## 注意事项 + +1. 系统仅支持微信登录,不再支持用户名密码登录 +2. 所有敏感接口都需要通过JWT Token认证 +3. 配送员位置信息具有时效性,默认5分钟内有效 +4. 位置历史记录功能已被移除,如有需要可使用第三方服务进行位置追踪 \ No newline at end of file diff --git a/absolute/path/to/application.properties b/absolute/path/to/application.properties new file mode 100644 index 0000000..e69de29 diff --git a/backend-api.md b/backend-api.md new file mode 100644 index 0000000..ca36ce4 --- /dev/null +++ b/backend-api.md @@ -0,0 +1,8 @@ +# 后端API文档 + +## 1. 用户相关接口 + +### POST /user/login +用户登录接口 + +**请求参数:** \ No newline at end of file diff --git a/docker-compose-dev.yml b/docker-compose-dev.yml new file mode 100644 index 0000000..8f0e975 --- /dev/null +++ b/docker-compose-dev.yml @@ -0,0 +1,19 @@ +services: + app: + build: . + container_name: light-delivery-app-dev + ports: + - "8080:8080" + environment: + - SPRING_PROFILES_ACTIVE=dev + - SPRING_DATASOURCE_URL=jdbc:mysql://115.190.121.151:3306/light_delivery?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true + - SPRING_DATASOURCE_USERNAME=double + - SPRING_DATASOURCE_PASSWORD=Hu@ng1998! + - JAVA_OPTS=-Xmx512m + restart: unless-stopped + networks: + - light-network + +networks: + light-network: + driver: bridge \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..ce17e39 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,23 @@ +services: + app: + build: . + container_name: light-delivery-app + ports: + - "443:443" + - "80:80" + environment: + - SPRING_PROFILES_ACTIVE=prod + - SPRING_DATASOURCE_URL=jdbc:mysql://115.190.121.151:3306/light_delivery?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true + - SPRING_DATASOURCE_USERNAME=double + - SPRING_DATASOURCE_PASSWORD=Hu@ng1998! + - JAVA_OPTS=-Xmx512m + - KEY_STORE_PASSWORD=changeit + volumes: + - /etc/ssl/certs:/etc/ssl/certs + restart: unless-stopped + networks: + - light-network + +networks: + light-network: + driver: bridge \ No newline at end of file diff --git a/mvnw b/mvnw new file mode 100644 index 0000000..bd8896b --- /dev/null +++ b/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/mvnw.cmd b/mvnw.cmd new file mode 100644 index 0000000..92450f9 --- /dev/null +++ b/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/pom.xml b/pom.xml new file mode 100644 index 0000000..c401679 --- /dev/null +++ b/pom.xml @@ -0,0 +1,192 @@ + + + 4.0.0 + + com.light + light-delivery + 1.0.0 + jar + + Light Delivery Backend + Backend for Light Delivery Mini Program + + + + org.springframework.boot + spring-boot-starter-parent + 3.1.4 + + + + + + 17 + 1.18.38 + 8.0.33 + + light + + 3.3.1 + + + + + + + + + + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-json + + + + org.springframework.boot + spring-boot-starter-websocket + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + org.springframework.boot + spring-boot-starter-data-redis + + + + org.projectlombok + lombok + 1.18.38 + + + + + io.jsonwebtoken + jjwt-api + 0.11.5 + + + io.jsonwebtoken + jjwt-impl + 0.11.5 + runtime + + + io.jsonwebtoken + jjwt-jackson + 0.11.5 + runtime + + + + + org.apache.tomcat.embed + tomcat-embed-core + + + + + com.mysql + mysql-connector-j + runtime + + + + + org.springframework.boot + spring-boot-devtools + runtime + true + + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.11.0 + + ${java.version} + ${java.version} + UTF-8 + + true + + + org.projectlombok + lombok + 1.18.38 + + + + + + + + + com.google.cloud.tools + jib-maven-plugin + ${jib-maven-plugin.version} + + + openjdk:17-jdk-slim + + + light-delivery + + latest + ${project.version} + + + + + 8080 + + USE_CURRENT_TIMESTAMP + + + + + + \ No newline at end of file diff --git a/src/main/java/com/light/delivery/LightApplication.java b/src/main/java/com/light/delivery/LightApplication.java new file mode 100644 index 0000000..bfe5fe0 --- /dev/null +++ b/src/main/java/com/light/delivery/LightApplication.java @@ -0,0 +1,18 @@ +package com.light.delivery; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +/** + * Spring Boot 应用程序入口类。 + */ +@SpringBootApplication +public class LightApplication { + /** + * 主方法,启动 Spring Boot 应用。 + * @param args 命令行参数 + */ + public static void main(String[] args) { + SpringApplication.run(LightApplication.class, args); + } +} \ No newline at end of file diff --git a/src/main/java/com/light/delivery/config/CachingRequestFilter.java b/src/main/java/com/light/delivery/config/CachingRequestFilter.java new file mode 100644 index 0000000..6d36ede --- /dev/null +++ b/src/main/java/com/light/delivery/config/CachingRequestFilter.java @@ -0,0 +1,21 @@ +package com.light.delivery.config; + +import jakarta.servlet.*; +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.stereotype.Component; +import org.springframework.web.util.ContentCachingRequestWrapper; + +import java.io.IOException; + +@Component +public class CachingRequestFilter implements Filter { + + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { + HttpServletRequest request = (HttpServletRequest) servletRequest; + // 使用 ContentCachingRequestWrapper 包装原始请求 + ContentCachingRequestWrapper wrappedRequest = new ContentCachingRequestWrapper(request); + // 继续执行过滤器链,传入包装后的请求 + filterChain.doFilter(wrappedRequest, servletResponse); + } +} \ No newline at end of file diff --git a/src/main/java/com/light/delivery/config/HttpsRedirectConfig.java b/src/main/java/com/light/delivery/config/HttpsRedirectConfig.java new file mode 100644 index 0000000..fc83372 --- /dev/null +++ b/src/main/java/com/light/delivery/config/HttpsRedirectConfig.java @@ -0,0 +1,43 @@ +package com.light.delivery.config; + +import org.apache.coyote.http11.Http11NioProtocol; +import org.apache.tomcat.util.descriptor.web.SecurityCollection; +import org.apache.tomcat.util.descriptor.web.SecurityConstraint; +import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; +import org.springframework.boot.web.servlet.server.ServletWebServerFactory; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.apache.catalina.Context; +import org.apache.catalina.connector.Connector; + +@Configuration +public class HttpsRedirectConfig { + + @Bean + @Profile("prod") + public ServletWebServerFactory servletContainer() { + TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() { + @Override + protected void postProcessContext(Context context) { + SecurityConstraint securityConstraint = new SecurityConstraint(); + securityConstraint.setUserConstraint("CONFIDENTIAL"); + SecurityCollection collection = new SecurityCollection(); + collection.addPattern("/*"); + securityConstraint.addCollection(collection); + context.addConstraint(securityConstraint); + } + }; + tomcat.addAdditionalTomcatConnectors(createHttpConnector()); + return tomcat; + } + + private Connector createHttpConnector() { + Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol"); + connector.setScheme("http"); + connector.setPort(80); // HTTP端口 + connector.setSecure(false); + connector.setRedirectPort(443); // 重定向到HTTPS端口 + return connector; + } +} \ No newline at end of file diff --git a/src/main/java/com/light/delivery/config/RequestLogInterceptor.java b/src/main/java/com/light/delivery/config/RequestLogInterceptor.java new file mode 100644 index 0000000..158e095 --- /dev/null +++ b/src/main/java/com/light/delivery/config/RequestLogInterceptor.java @@ -0,0 +1,50 @@ +package com.light.delivery.config; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.web.servlet.HandlerInterceptor; +import org.springframework.web.util.ContentCachingRequestWrapper; + +import java.nio.charset.StandardCharsets; + +public class RequestLogInterceptor implements HandlerInterceptor { + private static final Logger logger = LoggerFactory.getLogger(RequestLogInterceptor.class); + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { + // 关键:将请求转换为 ContentCachingRequestWrapper 类型 + ContentCachingRequestWrapper wrappedRequest = (ContentCachingRequestWrapper) request; + + logger.debug("\n=== 收到请求 ===\nMethod: {}\nURI: {}\nParams: {}\nHeaders: {}\nBody: {}", + request.getMethod(), + request.getRequestURI(), + request.getQueryString(), + getHeadersAsString(request), + getRequestBody(wrappedRequest)); // 传入包装后的请求 + return true; + } + + private String getHeadersAsString(HttpServletRequest request) { + StringBuilder headers = new StringBuilder(); + request.getHeaderNames().asIterator().forEachRemaining(headerName -> + headers.append(headerName).append(": ").append(request.getHeader(headerName)).append("\n")); + return headers.toString(); + } + + // 方法参数改为 ContentCachingRequestWrapper + private String getRequestBody(ContentCachingRequestWrapper request) { + try { + // 从包装请求的缓存中获取字节数组 + byte[] contentAsByteArray = request.getContentAsByteArray(); + if (contentAsByteArray.length > 0) { + return new String(contentAsByteArray, StandardCharsets.UTF_8); + } else { + return "[空请求体]"; + } + } catch (Exception e) { + return "[无法读取请求体]"; + } + } +} \ No newline at end of file diff --git a/src/main/java/com/light/delivery/config/SchedulingConfig.java b/src/main/java/com/light/delivery/config/SchedulingConfig.java new file mode 100644 index 0000000..fd6059f --- /dev/null +++ b/src/main/java/com/light/delivery/config/SchedulingConfig.java @@ -0,0 +1,10 @@ +package com.light.delivery.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.scheduling.annotation.EnableScheduling; + +@Configuration +@EnableScheduling +public class SchedulingConfig { + // 启用定时任务调度 +} \ No newline at end of file diff --git a/src/main/java/com/light/delivery/config/WebMvcConfig.java b/src/main/java/com/light/delivery/config/WebMvcConfig.java new file mode 100644 index 0000000..e24c038 --- /dev/null +++ b/src/main/java/com/light/delivery/config/WebMvcConfig.java @@ -0,0 +1,14 @@ +package com.light.delivery.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +public class WebMvcConfig implements WebMvcConfigurer { + @Override + public void addInterceptors(InterceptorRegistry registry) { + registry.addInterceptor(new RequestLogInterceptor()) + .addPathPatterns("/**"); // 拦截所有路径 + } +} diff --git a/src/main/java/com/light/delivery/config/WebsocketConfig.java b/src/main/java/com/light/delivery/config/WebsocketConfig.java new file mode 100644 index 0000000..db0523a --- /dev/null +++ b/src/main/java/com/light/delivery/config/WebsocketConfig.java @@ -0,0 +1,19 @@ +package com.light.delivery.config; + +import com.light.delivery.service.LocationWebSocketHandler; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.socket.config.annotation.EnableWebSocket; +import org.springframework.web.socket.config.annotation.WebSocketConfigurer; +import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry; + +@Configuration +@EnableWebSocket +public class WebsocketConfig implements WebSocketConfigurer { + + @Override + public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { + // 注册位置同步处理器 + registry.addHandler(new LocationWebSocketHandler(), "/ws/location") + .setAllowedOrigins("*"); + } +} \ No newline at end of file diff --git a/src/main/java/com/light/delivery/controller/DeliveryPersonController.java b/src/main/java/com/light/delivery/controller/DeliveryPersonController.java new file mode 100644 index 0000000..7ec92d4 --- /dev/null +++ b/src/main/java/com/light/delivery/controller/DeliveryPersonController.java @@ -0,0 +1,124 @@ +package com.light.delivery.controller; + +import com.light.delivery.dto.DeliveryPersonResponse; +import com.light.delivery.dto.OrderResponse; +import com.light.delivery.model.DeliveryPerson; +import com.light.delivery.service.DeliveryPersonService; +import com.light.delivery.service.impl.LocationSyncServiceImpl; +import lombok.Data; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +import java.util.List; +import java.util.stream.Collectors; + +/** + * 配送员相关接口控制器,提供配送员信息、位置、状态等管理功能。 + */ +@RestController +@RequestMapping("/delivery-persons") +public class DeliveryPersonController { + + /** + * 配送员服务层依赖注入。 + */ + @Autowired + private DeliveryPersonService deliveryPersonService; + + @Autowired + private LocationSyncServiceImpl locationSyncService; + + /** + * 获取所有配送员信息。 + * @return 配送员列表 + */ + @GetMapping + public ResponseEntity> getAllDeliveryPersons() { + List deliveryPersons = deliveryPersonService.getAllDeliveryPersons().stream().map(person -> { + DeliveryPersonResponse response = new DeliveryPersonResponse(); + response.setId(person.getId()); + // 从服务器缓存中获取位置和状态信息,而不是从数据库 + response.setStatus(locationSyncService.getDeliveryPersonStatus(person.getId())); + + DeliveryPersonResponse.Location location = new DeliveryPersonResponse.Location(); + location.setLongitude(locationSyncService.getDeliveryPersonLongitude(person.getId())); + location.setLatitude(locationSyncService.getDeliveryPersonLatitude(person.getId())); + response.setCurrentLocation(location); + return response; + }).collect(Collectors.toList()); + return ResponseEntity.ok(deliveryPersons); + } + + /** + * 根据ID获取配送员详情。 + * @param id 配送员ID + * @return 配送员对象 + */ + @GetMapping("/{id}") + public ResponseEntity getDeliveryPersonById(@PathVariable Long id) { + DeliveryPerson person = deliveryPersonService.getDeliveryPersonById(id); + DeliveryPersonResponse response = new DeliveryPersonResponse(); + response.setId(person.getId()); + // 从服务器缓存中获取位置和状态信息,而不是从数据库 + response.setStatus(locationSyncService.getDeliveryPersonStatus(id)); + + DeliveryPersonResponse.Location location = new DeliveryPersonResponse.Location(); + location.setLongitude(locationSyncService.getDeliveryPersonLongitude(id)); + location.setLatitude(locationSyncService.getDeliveryPersonLatitude(id)); + response.setCurrentLocation(location); + return ResponseEntity.ok(response); + } + + /** + * 更新指定货运人员位置。 + * @param id 货运人员ID + * @param locationRequest 包含经纬度 + * @return 操作结果 + */ + @PutMapping("/{id}/location") + public ResponseEntity updateLocation(@PathVariable Long id, @RequestBody LocationRequest locationRequest) { + deliveryPersonService.updateLocation(id, locationRequest.getLongitude(), locationRequest.getLatitude()); + return ResponseEntity.ok("位置更新成功"); + } + + /** + * 获取货运人员的当前订单。 + * @param id 货运人员ID + * @return 订单列表 + */ + @GetMapping("/{id}/orders") + public ResponseEntity> getCurrentOrders(@PathVariable Long id) { + List orders = deliveryPersonService.getCurrentOrders(id).stream().map(order -> { + OrderResponse response = new OrderResponse(); + response.setId(order.getId()); + response.setStatus(order.getStatus()); + response.setGoodsType(order.getGoodsType()); + response.setGoodsWeight(order.getGoodsWeight()); + response.setCreateTime(order.getCreateTime()); + response.setAssignTime(order.getAssignTime()); + response.setDeliveryTime(order.getDeliveryTime()); + OrderResponse.StartPoint startPoint = new OrderResponse.StartPoint(); + startPoint.setId(order.getWarehouseId()); + startPoint.setName(order.getWarehouseName()); + startPoint.setLongitude(order.getStartPointLongitude()); + startPoint.setLatitude(order.getStartPointLatitude()); + response.setStartPoint(startPoint); + OrderResponse.EndPoint endPoint = new OrderResponse.EndPoint(); + endPoint.setName(order.getEndPointName()); + endPoint.setLongitude(order.getEndPointLongitude()); + endPoint.setLatitude(order.getEndPointLatitude()); + response.setEndPoint(endPoint); + return response; + }).collect(Collectors.toList()); + return ResponseEntity.ok(orders); + } + + /** + * 位置请求体 + */ + @Data + public static class LocationRequest { + private Double longitude; + private Double latitude; + } +} \ No newline at end of file diff --git a/src/main/java/com/light/delivery/controller/LocationSyncController.java b/src/main/java/com/light/delivery/controller/LocationSyncController.java new file mode 100644 index 0000000..3e82ea2 --- /dev/null +++ b/src/main/java/com/light/delivery/controller/LocationSyncController.java @@ -0,0 +1,76 @@ +package com.light.delivery.controller; + +import com.light.delivery.model.DeliveryPerson; +import com.light.delivery.service.DeliveryPersonService; +import lombok.Data; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +import java.util.List; +import java.util.stream.Collectors; + +/** + * 位置同步控制器,提供配送员位置信息查询接口。 + * 用于获取所有已签到配送员的实时位置信息。 + */ +@RestController +@RequestMapping("/location-sync") +public class LocationSyncController { + + /** + * 配送员服务依赖注入 + */ + @Autowired + private DeliveryPersonService deliveryPersonService; + + /** + * 获取所有已签到配送员的实时位置。 + * 仅返回有位置信息的配送员(最近有更新位置的)。 + * @return 配送员位置列表 + */ + @GetMapping("/delivery-persons/locations") + public ResponseEntity> getDeliveryPersonLocations() { + List allDeliveryPersons = deliveryPersonService.getAllDeliveryPersons(); + + // 过滤出有位置信息的配送员(最近有更新位置的) + List locations = allDeliveryPersons.stream() + .filter(person -> person.getLatitude() != null && person.getLongitude() != null) + .map(person -> { + DeliveryPersonLocation location = new DeliveryPersonLocation(); + location.setDeliveryPersonId(person.getId()); + location.setLatitude(person.getLatitude()); + location.setLongitude(person.getLongitude()); + location.setStatus(person.getStatus()); + return location; + }) + .collect(Collectors.toList()); + + return ResponseEntity.ok(locations); + } + + /** + * 配送员位置信息DTO,用于向前端返回配送员位置数据。 + */ + @Data + public static class DeliveryPersonLocation { + /** + * 配送员ID + */ + private Long deliveryPersonId; + + /** + * 纬度 + */ + private Double latitude; + + /** + * 经度 + */ + private Double longitude; + + /** + * 状态 + */ + private String status; + } +} \ No newline at end of file diff --git a/src/main/java/com/light/delivery/controller/OrderController.java b/src/main/java/com/light/delivery/controller/OrderController.java new file mode 100644 index 0000000..10cfaa6 --- /dev/null +++ b/src/main/java/com/light/delivery/controller/OrderController.java @@ -0,0 +1,154 @@ +package com.light.delivery.controller; + +import com.light.delivery.dto.OrderResponse; +import com.light.delivery.model.Order; +import com.light.delivery.service.OrderService; +import lombok.Data; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.List; +import java.util.stream.Collectors; + +/** + * 订单相关接口控制器,提供订单的查询、分配、状态更新等功能。 + */ +@RestController +@RequestMapping("/orders") +public class OrderController { + + /** + * 订单服务层依赖注入。 + */ + @Autowired + private OrderService orderService; + + /** + * 获取所有待分配订单。 + * @return 待分配订单列表 + */ + @GetMapping("/pending") + public ResponseEntity> getPendingOrders() { + List orders = orderService.getPendingOrders().stream().map(order -> { + OrderResponse response = new OrderResponse(); + OrderResponse.StartPoint startPoint = new OrderResponse.StartPoint(); + startPoint.setId(order.getWarehouseId()); + startPoint.setName(order.getWarehouseName()); + startPoint.setLongitude(order.getStartPointLongitude()); + startPoint.setLatitude(order.getStartPointLatitude()); + response.setStartPoint(startPoint); + + OrderResponse.EndPoint endPoint = new OrderResponse.EndPoint(); + endPoint.setName(order.getEndPointName()); + endPoint.setLongitude(order.getEndPointLongitude()); + endPoint.setLatitude(order.getEndPointLatitude()); + response.setEndPoint(endPoint); + + response.setId(order.getId()); + response.setStatus(order.getStatus()); + response.setGoodsType(order.getGoodsType()); + response.setGoodsWeight(order.getGoodsWeight()); + response.setCreateTime(order.getCreateTime()); + response.setAssignTime(order.getAssignTime()); + response.setDeliveryTime(order.getDeliveryTime()); + return response; + }).collect(Collectors.toList()); + return ResponseEntity.ok(orders); + } + + /** + * 指派订单给特定货运人员。 + * @param id 订单ID + * @param assignRequest 包含 deliveryPersonId + * @return 操作结果 + */ + @PostMapping("/{id}/assign") + public ResponseEntity assignOrder(@PathVariable Long id, @RequestBody AssignRequest assignRequest) { + orderService.assignOrder(id, assignRequest.getDeliveryPersonId()); + return ResponseEntity.ok().build(); + } + + /** + * 根据ID获取订单详情。 + * @param id 订单ID + * @return 订单对象 + */ + @GetMapping("/{id}") + public ResponseEntity getOrderById(@PathVariable Long id) { + Order order = orderService.getOrderById(id); + OrderResponse response = new OrderResponse(); + OrderResponse.StartPoint startPoint = new OrderResponse.StartPoint(); + startPoint.setId(order.getWarehouseId()); + startPoint.setName(order.getWarehouseName()); + startPoint.setLongitude(order.getStartPointLongitude()); + startPoint.setLatitude(order.getStartPointLatitude()); + response.setStartPoint(startPoint); + + OrderResponse.EndPoint endPoint = new OrderResponse.EndPoint(); + endPoint.setName(order.getEndPointName()); + endPoint.setLongitude(order.getEndPointLongitude()); + endPoint.setLatitude(order.getEndPointLatitude()); + response.setEndPoint(endPoint); + + response.setId(order.getId()); + response.setStatus(order.getStatus()); + response.setGoodsType(order.getGoodsType()); + response.setGoodsWeight(order.getGoodsWeight()); + response.setCreateTime(order.getCreateTime()); + response.setAssignTime(order.getAssignTime()); + response.setDeliveryTime(order.getDeliveryTime()); + return ResponseEntity.ok(response); + } + + /** + * 更新订单状态。 + * @param id 订单ID + * @param status 新状态 + */ + @PutMapping("/{id}/status") + public void updateOrderStatus(@PathVariable Long id, @RequestParam String status) { + orderService.updateOrderStatus(id, status); + } + + /** + * 获取货运人员的当前订单。 + * @param deliveryPersonId 货运人员ID + * @return 订单列表 + */ + @GetMapping("/delivery-persons/{deliveryPersonId}/orders") + public ResponseEntity> getOrdersByDeliveryPerson(@PathVariable Long deliveryPersonId) { + List orders = orderService.getOrdersByDeliveryPerson(deliveryPersonId).stream().map(order -> { + OrderResponse response = new OrderResponse(); + // ...OrderResponse字段映射... + response.setId(order.getId()); + response.setStatus(order.getStatus()); + response.setGoodsType(order.getGoodsType()); + response.setGoodsWeight(order.getGoodsWeight()); + response.setCreateTime(order.getCreateTime()); + response.setAssignTime(order.getAssignTime()); + response.setDeliveryTime(order.getDeliveryTime()); + OrderResponse.StartPoint startPoint = new OrderResponse.StartPoint(); + startPoint.setId(order.getWarehouseId()); + startPoint.setName(order.getWarehouseName()); + startPoint.setLongitude(order.getStartPointLongitude()); + startPoint.setLatitude(order.getStartPointLatitude()); + response.setStartPoint(startPoint); + OrderResponse.EndPoint endPoint = new OrderResponse.EndPoint(); + endPoint.setName(order.getEndPointName()); + endPoint.setLongitude(order.getEndPointLongitude()); + endPoint.setLatitude(order.getEndPointLatitude()); + response.setEndPoint(endPoint); + return response; + }).collect(Collectors.toList()); + return ResponseEntity.ok(orders); + } + + /** + * 指派请求体 + */ + @Data + public static class AssignRequest { + private Long deliveryPersonId; + } +} \ No newline at end of file diff --git a/src/main/java/com/light/delivery/controller/UserController.java b/src/main/java/com/light/delivery/controller/UserController.java new file mode 100644 index 0000000..c396ad0 --- /dev/null +++ b/src/main/java/com/light/delivery/controller/UserController.java @@ -0,0 +1,174 @@ +package com.light.delivery.controller; + +import com.light.delivery.dto.UserInfoResponse; +import com.light.delivery.dto.UserResponse; +import com.light.delivery.model.LoginResponse; +import com.light.delivery.model.RegisterRequest; +import com.light.delivery.model.User; +import com.light.delivery.model.WxLoginRequest; +import com.light.delivery.service.UserService; +import com.light.delivery.util.JwtUtil; +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +/** + * 用户相关接口控制器,提供登录、获取用户信息、登出等功能。 + * 处理用户认证、授权和基本信息管理等相关HTTP请求。 + */ +@RestController +@RequestMapping("/user") +public class UserController { + + /** + * 用户服务层依赖注入。 + */ + @Autowired + private UserService userService; + + /** + * Jwt工具类依赖注入。 + */ + @Autowired + private JwtUtil jwtUtil; + + /** + * 获取当前用户信息接口。 + * @param request HTTP请求对象,用于提取认证令牌 + * @return 当前用户信息 + */ + @GetMapping("/info") + public ResponseEntity getUserInfo(HttpServletRequest request) { + String token = extractToken(request); + if (token == null) { + return ResponseEntity.badRequest().body("Authorization token is missing"); + } + + try { + User user = userService.getUserInfo(token); + UserInfoResponse response = toUserInfoResponse(user); + return ResponseEntity.ok(response); + } catch (Exception e) { + return ResponseEntity.badRequest().body("Invalid token: " + e.getMessage()); + } + } + + /** + * 将User实体转换为UserInfoResponse DTO。 + * @param user 用户实体 + * @return 用户信息响应DTO + */ + private UserInfoResponse toUserInfoResponse(User user) { + if (user == null) return null; + UserInfoResponse dto = new UserInfoResponse(); + dto.setId(user.getId()); + dto.setName(user.getName()); + dto.setPhone(user.getPhone()); + dto.setRole(user.getRole() != null ? user.getRole().getCode() : null); + dto.setOpenid(user.getOpenid()); + return dto; + } + + /** + * 从HTTP请求头中提取JWT令牌。 + * @param request HTTP请求对象 + * @return JWT令牌字符串 + */ + private String extractToken(HttpServletRequest request) { + String bearerToken = request.getHeader("Authorization"); + if (bearerToken != null && bearerToken.startsWith("Bearer ")) { + return bearerToken.substring(7); + } + return null; + } + + /** + * 用户登出接口。 + * @param request HTTP请求对象,用于提取认证令牌 + * @return 操作结果 + */ + @PostMapping("/logout") + public ResponseEntity logout(HttpServletRequest request) { + String token = extractToken(request); + userService.logout(token); + return ResponseEntity.ok("登出成功"); + } + + /** + * 微信小程序登录接口,接收code,返回openid和token。 + * @param wxLoginRequest 微信登录请求对象 + * @return 登录响应 + */ + @PostMapping("/wxlogin") + public ResponseEntity wxLogin(@RequestBody WxLoginRequest wxLoginRequest) { + System.out.println("[wxLogin] 收到请求参数: code=" + wxLoginRequest.getCode()); + LoginResponse loginResponse = userService.wxLogin(wxLoginRequest.getCode()); + return ResponseEntity.ok(loginResponse); + } + + /** + * 用户签到接口。 + * @param request HTTP请求对象,用于提取认证令牌 + * @return 更新后的用户信息 + */ + @PostMapping("/signin") + public ResponseEntity signIn(HttpServletRequest request) { + String token = extractToken(request); + if (token == null) { + return ResponseEntity.badRequest().body("Authorization token is missing"); + } + + try { + String username = jwtUtil.getUsernameFromToken(token); + User user = userService.getUserInfo(token); + User updatedUser = userService.signIn(user.getId()); + UserInfoResponse response = toUserInfoResponse(updatedUser); + return ResponseEntity.ok(response); + } catch (Exception e) { + return ResponseEntity.badRequest().body("Invalid token: " + e.getMessage()); + } + } + + /** + * 注册为骑手接口。 + * @param request HTTP请求对象,用于提取认证令牌 + * @param registerRequest 注册请求对象,包含姓名和手机号 + * @return 更新后的用户信息 + */ + @PostMapping("/register") + public ResponseEntity registerAsDeliveryPerson( + HttpServletRequest request, + @RequestBody RegisterRequest registerRequest) { + try { + String token = extractToken(request); + System.out.println("收到注册请求,Token: " + token); + + if (token == null || token.isEmpty()) { + System.err.println("缺少Authorization token"); + return ResponseEntity.badRequest().body(null); + } + + User user = userService.getUserInfo(token); + System.out.println("获取到用户信息: " + user); + + User updatedUser = userService.registerAsDeliveryPerson( + user.getId(), + registerRequest.getName(), + registerRequest.getPhone()); + UserInfoResponse response = toUserInfoResponse(updatedUser); + return ResponseEntity.ok(response); + } catch (IllegalArgumentException e) { + // 记录错误日志 + System.err.println("注册配送员时发生错误: " + e.getMessage()); + e.printStackTrace(); + return ResponseEntity.badRequest().build(); + } catch (Exception e) { + // 记录未预期的错误 + System.err.println("注册配送员时发生未预期错误: " + e.getMessage()); + e.printStackTrace(); + return ResponseEntity.status(500).build(); + } + } +} \ No newline at end of file diff --git a/src/main/java/com/light/delivery/controller/WarehouseController.java b/src/main/java/com/light/delivery/controller/WarehouseController.java new file mode 100644 index 0000000..bdb468d --- /dev/null +++ b/src/main/java/com/light/delivery/controller/WarehouseController.java @@ -0,0 +1,118 @@ +package com.light.delivery.controller; + +import com.light.delivery.dto.OrderResponse; +import com.light.delivery.dto.WarehouseInfo; +import com.light.delivery.model.Order; +import com.light.delivery.model.Warehouse; +import com.light.delivery.service.WarehouseService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +/** + * 仓库相关接口控制器,提供仓库的增查及订单查询等功能。 + */ +@RestController +@RequestMapping("/warehouses") +public class WarehouseController { + + /** + * 仓库服务层依赖注入。 + */ + @Autowired + private WarehouseService warehouseService; + + /** + * 获取所有仓库信息。 + * @return 仓库列表 + */ + @GetMapping + public ResponseEntity> getAllWarehouses() { + List warehouses = warehouseService.getAllWarehouses().stream().map(warehouse -> { + WarehouseInfo info = new WarehouseInfo(); + info.setId(warehouse.getId()); + info.setName(warehouse.getName()); + info.setAddress(warehouse.getAddress()); + info.setContact(warehouse.getContact()); + info.setPhone(warehouse.getPhone()); + info.setDescription(warehouse.getDescription()); + info.setStatus(warehouse.getStatus()); + info.setCapacity(warehouse.getCapacity()); + info.setLatitude(warehouse.getLatitude()); + info.setLongitude(warehouse.getLongitude()); + return info; + }).collect(Collectors.toList()); + return ResponseEntity.ok(warehouses); + } + + /** + * 根据ID获取仓库详情。 + * @param id 仓库ID + * @return 仓库对象 + */ + @GetMapping("/{id}") + public ResponseEntity getWarehouseById(@PathVariable Long id) { + Warehouse warehouse = warehouseService.getWarehouseById(id); + WarehouseInfo info = new WarehouseInfo(); + info.setId(warehouse.getId()); + info.setName(warehouse.getName()); + info.setAddress(warehouse.getAddress()); + info.setContact(warehouse.getContact()); + info.setPhone(warehouse.getPhone()); + info.setDescription(warehouse.getDescription()); + info.setStatus(warehouse.getStatus()); + info.setCapacity(warehouse.getCapacity()); + info.setLatitude(warehouse.getLatitude()); + info.setLongitude(warehouse.getLongitude()); + return ResponseEntity.ok(info); + } + + /** + * 获取指定仓库的所有订单。 + * @param id 仓库ID + * @return 订单列表 + */ + @GetMapping("/{id}/orders") + public ResponseEntity> getWarehouseOrders(@PathVariable Long id) { + List orders = warehouseService.getWarehouseOrders(id).stream().map(order -> { + OrderResponse response = new OrderResponse(); + response.setId(order.getId()); + response.setStatus(order.getStatus()); + response.setGoodsType(order.getGoodsType()); + response.setGoodsWeight(order.getGoodsWeight()); + response.setCreateTime(order.getCreateTime()); + response.setAssignTime(order.getAssignTime()); + response.setDeliveryTime(order.getDeliveryTime()); + + OrderResponse.StartPoint startPoint = new OrderResponse.StartPoint(); + startPoint.setId(order.getWarehouseId()); + startPoint.setName(order.getWarehouseName()); + startPoint.setLongitude(order.getStartPointLongitude()); + startPoint.setLatitude(order.getStartPointLatitude()); + response.setStartPoint(startPoint); + + OrderResponse.EndPoint endPoint = new OrderResponse.EndPoint(); + endPoint.setName(order.getEndPointName()); + endPoint.setLongitude(order.getEndPointLongitude()); + endPoint.setLatitude(order.getEndPointLatitude()); + response.setEndPoint(endPoint); + + return response; + }).collect(Collectors.toList()); + return ResponseEntity.ok(orders); + } + + /** + * 创建新仓库。 + * @param warehouse 仓库对象 + * @return 创建后的仓库对象 + */ + @PostMapping + public Warehouse createWarehouse(@RequestBody Warehouse warehouse) { + return warehouseService.createWarehouse(warehouse); + } +} \ No newline at end of file diff --git a/src/main/java/com/light/delivery/dto/DeliveryPersonResponse.java b/src/main/java/com/light/delivery/dto/DeliveryPersonResponse.java new file mode 100644 index 0000000..f0b3e6a --- /dev/null +++ b/src/main/java/com/light/delivery/dto/DeliveryPersonResponse.java @@ -0,0 +1,18 @@ +package com.light.delivery.dto; + +import lombok.Data; + +@Data +public class DeliveryPersonResponse { + private Long id; + private String name; + private String phone; + private String status; + private Location currentLocation; + + @Data + public static class Location { + private Double longitude; + private Double latitude; + } +} diff --git a/src/main/java/com/light/delivery/dto/OrderResponse.java b/src/main/java/com/light/delivery/dto/OrderResponse.java new file mode 100644 index 0000000..bf9a2ae --- /dev/null +++ b/src/main/java/com/light/delivery/dto/OrderResponse.java @@ -0,0 +1,32 @@ +package com.light.delivery.dto; + +import lombok.Data; + +@Data +public class OrderResponse { + private Long id; + private StartPoint startPoint; + private EndPoint endPoint; + private String status; + private String goodsType; + private Double goodsWeight; + private Long createTime; + private Long assignTime; + private Long deliveryTime; + + @Data + public static class StartPoint { + private Long id; + private String name; + private Double longitude; + private Double latitude; + } + + @Data + public static class EndPoint { + private Long id; + private String name; + private Double longitude; + private Double latitude; + } +} diff --git a/src/main/java/com/light/delivery/dto/UserInfoResponse.java b/src/main/java/com/light/delivery/dto/UserInfoResponse.java new file mode 100644 index 0000000..984e05c --- /dev/null +++ b/src/main/java/com/light/delivery/dto/UserInfoResponse.java @@ -0,0 +1,35 @@ +package com.light.delivery.dto; + +import lombok.Data; + +/** + * 用户信息响应 DTO,专用于前后端数据交互,避免直接暴露实体。 + * 该类仅包含用户基本信息,不包含敏感或角色特定的信息。 + */ +@Data +public class UserInfoResponse { + /** + * 用户唯一标识符 + */ + private Long id; + + /** + * 用户姓名 + */ + private String name; + + /** + * 用户联系电话 + */ + private String phone; + + /** + * 用户角色 + */ + private String role; + + /** + * 微信用户唯一标识 + */ + private String openid; +} \ No newline at end of file diff --git a/src/main/java/com/light/delivery/dto/UserResponse.java b/src/main/java/com/light/delivery/dto/UserResponse.java new file mode 100644 index 0000000..e8633cc --- /dev/null +++ b/src/main/java/com/light/delivery/dto/UserResponse.java @@ -0,0 +1,13 @@ +package com.light.delivery.dto; + +import lombok.Data; + +@Data +public class UserResponse { + private Long id; + private String name; + private String nickName; + private String role; + private String avatarUrl; + private String phone; +} \ No newline at end of file diff --git a/src/main/java/com/light/delivery/dto/WarehouseInfo.java b/src/main/java/com/light/delivery/dto/WarehouseInfo.java new file mode 100644 index 0000000..cd2d6fc --- /dev/null +++ b/src/main/java/com/light/delivery/dto/WarehouseInfo.java @@ -0,0 +1,17 @@ +package com.light.delivery.dto; + +import lombok.Data; + +@Data +public class WarehouseInfo { + private Long id; + private String name; + private String address; + private String contact; + private String phone; + private String description; + private String status; + private Integer capacity; + private Double latitude; + private Double longitude; +} \ No newline at end of file diff --git a/src/main/java/com/light/delivery/model/DeliveryPerson.java b/src/main/java/com/light/delivery/model/DeliveryPerson.java new file mode 100644 index 0000000..b1f9bbf --- /dev/null +++ b/src/main/java/com/light/delivery/model/DeliveryPerson.java @@ -0,0 +1,76 @@ +package com.light.delivery.model; + +import jakarta.persistence.*; +import lombok.Data; +import java.time.LocalDateTime; + +/** + * 配送员实体类,表示系统中配送员的扩展信息。 + * 配送员是用户的一种角色,除了基本的用户信息外,还有配送相关的特殊属性。 + */ +@Entity +@Table(name = "delivery_person") +@Data +public class DeliveryPerson { + /** + * 配送员唯一标识符 + */ + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + /** + * 关联的用户ID + */ + @Column(name = "user_id") + private Long userId; + + /** + * 当前纬度位置(瞬态,不存数据库) + */ + @Transient + private Double latitude; + + /** + * 当前经度位置(瞬态,不存数据库) + */ + @Transient + private Double longitude; + + /** + * 配送员状态(如 AVAILABLE 可接单, DELIVERING 配送中)(瞬态,不存数据库) + */ + @Transient + private String status; + + /** + * 当前配送订单ID + */ + @Column(name = "current_order_id") + private Long currentOrderId; + + /** + * 获取配送员当前位置信息 + * @return 当前位置对象 + */ + public CurrentLocation getCurrentLocation() { + CurrentLocation loc = new CurrentLocation(); + // 注意:实际位置应从缓存服务获取,此处仅返回内存中的值 + loc.setLongitude(this.longitude); + loc.setLatitude(this.latitude); + return loc; + } + + /** + * 当前位置信息内部类 + */ + public static class CurrentLocation { + private Double longitude; + private Double latitude; + + public Double getLongitude() { return longitude; } + public void setLongitude(Double longitude) { this.longitude = longitude; } + public Double getLatitude() { return latitude; } + public void setLatitude(Double latitude) { this.latitude = latitude; } + } +} \ No newline at end of file diff --git a/src/main/java/com/light/delivery/model/Employee.java b/src/main/java/com/light/delivery/model/Employee.java new file mode 100644 index 0000000..d305f0f --- /dev/null +++ b/src/main/java/com/light/delivery/model/Employee.java @@ -0,0 +1,45 @@ +package com.light.delivery.model; + +import jakarta.persistence.*; +import lombok.Data; + +/** + * 员工信息实体类,用于存储后台配置的员工数据。 + * 当用户注册为配送员或管理员时,系统会根据手机号在此表中查找匹配记录。 + */ +@Entity +@Table(name = "employee") +@Data +public class Employee { + /** + * 员工唯一标识符 + */ + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + /** + * 员工姓名 + */ + @Column(name = "name") + private String name; + + /** + * 员工联系电话 + */ + @Column(name = "phone", unique = true) + private String phone; + + /** + * 员工角色(如"DELIVERY_PERSON", "ADMIN") + */ + @Column(name = "role") + private String role; + + /** + * 微信用户唯一标识 + * 当员工注册为系统用户时,会将openid写入此字段 + */ + @Column(name = "openid", unique = true) + private String openid; +} \ No newline at end of file diff --git a/src/main/java/com/light/delivery/model/LoginResponse.java b/src/main/java/com/light/delivery/model/LoginResponse.java new file mode 100644 index 0000000..9f2d509 --- /dev/null +++ b/src/main/java/com/light/delivery/model/LoginResponse.java @@ -0,0 +1,36 @@ +package com.light.delivery.model; + +import com.light.delivery.dto.UserInfoResponse; +import lombok.Data; + +/** + * 登录响应类,封装用户登录成功后的返回信息。 + * 包含JWT令牌、用户基本信息和会话相关信息。 + */ +@Data +public class LoginResponse { + /** + * JWT访问令牌 + */ + private String token; + + /** + * 用户基本信息 + */ + private UserInfoResponse user; + + /** + * 微信用户唯一标识 + */ + private String openid; + + /** + * 微信会话密钥 + */ + private String sessionKey; + + /** + * 令牌过期时间(秒) + */ + private Long expiresIn; +} \ No newline at end of file diff --git a/src/main/java/com/light/delivery/model/Order.java b/src/main/java/com/light/delivery/model/Order.java new file mode 100644 index 0000000..e8a8a44 --- /dev/null +++ b/src/main/java/com/light/delivery/model/Order.java @@ -0,0 +1,62 @@ +package com.light.delivery.model; + +import jakarta.persistence.*; +import lombok.Data; + +/** + * 订单实体类,表示订单的详细信息。 + */ +@Entity +@Table(name = "orders") +@Data +public class Order { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + /** 订单编号 */ + private String orderNo; + /** 仓库ID */ + private Long warehouseId; + /** 仓库名称 */ + private String warehouseName; + /** 配送员ID */ + private Long deliveryPersonId; + /** 配送员名称 */ + private String deliveryPersonName; + /** 订单状态(pending/assigned/in_transit/delivered) */ + private String status; + /** 客户姓名 */ + private String customerName; + /** 客户电话 */ + private String customerPhone; + /** 配送地址 */ + private String deliveryAddress; + /** 配送纬度 */ + private Double deliveryLatitude; + /** 配送经度 */ + private Double deliveryLongitude; + /** 订单金额 */ + private Double amount; + /** 创建时间戳 */ + private Long createTime; + /** 指派时间戳(可选) */ + private Long assignTime; + /** 配送完成时间戳(可选) */ + private Long deliveryTime; + /** 货物类型 */ + private String goodsType; + /** 货物重量(公斤) */ + private Double goodsWeight; + /** 起点名称(仓库) */ + private String startPointName; + /** 起点经度 */ + private Double startPointLongitude; + /** 起点纬度 */ + private Double startPointLatitude; + /** 终点名称 */ + private String endPointName; + /** 终点经度 */ + private Double endPointLongitude; + /** 终点纬度 */ + private Double endPointLatitude; +} \ No newline at end of file diff --git a/src/main/java/com/light/delivery/model/RegisterRequest.java b/src/main/java/com/light/delivery/model/RegisterRequest.java new file mode 100644 index 0000000..8caa6da --- /dev/null +++ b/src/main/java/com/light/delivery/model/RegisterRequest.java @@ -0,0 +1,20 @@ +package com.light.delivery.model; + +import lombok.Data; + +/** + * 骑手注册请求数据模型,用于接收用户注册为配送员时提交的信息。 + * 包含姓名和手机号,用于与员工信息表进行匹配验证。 + */ +@Data +public class RegisterRequest { + /** + * 用户真实姓名 + */ + private String name; + + /** + * 用户手机号 + */ + private String phone; +} \ No newline at end of file diff --git a/src/main/java/com/light/delivery/model/User.java b/src/main/java/com/light/delivery/model/User.java new file mode 100644 index 0000000..c533654 --- /dev/null +++ b/src/main/java/com/light/delivery/model/User.java @@ -0,0 +1,44 @@ +package com.light.delivery.model; + +import jakarta.persistence.*; +import lombok.Data; + +/** + * 用户实体类,表示系统中的用户信息。 + * 所有用户首先以游客身份登录系统,之后可以注册为配送员或管理员。 + */ +@Entity +@Table(name = "user") +@Data +public class User { + /** + * 用户唯一标识符 + */ + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + /** + * 用户姓名 + */ + @Column(name = "name") + private String name; + + /** + * 联系电话 + */ + @Column(name = "phone") + private String phone; + + /** + * 用户角色(如 ADMIN, DELIVERY_PERSON, GUEST) + */ + @Enumerated(EnumType.STRING) + private UserRole role; + + /** + * 微信用户唯一标识 + */ + @Column(unique = true) + private String openid; +} \ No newline at end of file diff --git a/src/main/java/com/light/delivery/model/UserRole.java b/src/main/java/com/light/delivery/model/UserRole.java new file mode 100644 index 0000000..80bab30 --- /dev/null +++ b/src/main/java/com/light/delivery/model/UserRole.java @@ -0,0 +1,65 @@ +package com.light.delivery.model; + +/** + * 用户角色枚举 + * 定义系统中所有可能的用户角色类型 + */ +public enum UserRole { + /** + * 管理员角色,拥有最高权限 + */ + ADMIN("ADMIN", "管理员"), + + /** + * 配送员角色,可以接单和更新位置 + */ + DELIVERY_PERSON("DELIVERY_PERSON", "配送员"), + + /** + * 游客角色,默认角色,权限最低 + */ + GUEST("GUEST", "游客"); + + private final String code; + private final String description; + + UserRole(String code, String description) { + this.code = code; + this.description = description; + } + + /** + * 获取角色代码 + * @return 角色代码 + */ + public String getCode() { + return code; + } + + /** + * 获取角色描述 + * @return 角色描述 + */ + public String getDescription() { + return description; + } + + /** + * 根据代码获取UserRole枚举值 + * @param code 角色代码 + * @return 对应的UserRole枚举值,如果未找到则返回GUEST + */ + public static UserRole fromCode(String code) { + for (UserRole role : UserRole.values()) { + if (role.getCode().equals(code)) { + return role; + } + } + return GUEST; // 默认返回游客角色 + } + + @Override + public String toString() { + return code; + } +} \ No newline at end of file diff --git a/src/main/java/com/light/delivery/model/Warehouse.java b/src/main/java/com/light/delivery/model/Warehouse.java new file mode 100644 index 0000000..cef7249 --- /dev/null +++ b/src/main/java/com/light/delivery/model/Warehouse.java @@ -0,0 +1,45 @@ +package com.light.delivery.model; + +import jakarta.persistence.*; +import lombok.Data; + +/** + * 仓库实体类,表示仓库的基本信息。 + */ +@Entity +@Table(name = "warehouse") +@Data +public class Warehouse { + /** 仓库ID */ + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private Long id; + /** 仓库名称 */ + @Column(name = "name") + private String name; + /** 仓库纬度 */ + @Column(name = "latitude") + private Double latitude; + /** 仓库经度 */ + @Column(name = "longitude") + private Double longitude; + /** 仓库地址 */ + @Column(name = "address") + private String address; + /** 联系电话 */ + @Column(name = "phone") + private String phone; + /** 联系人 */ + @Column(name = "contact") + private String contact; + /** 描述 */ + @Column(name = "description") + private String description; + /** 状态 */ + @Column(name = "status") + private String status; + /** 容量 */ + @Column(name = "capacity") + private Integer capacity; +} \ No newline at end of file diff --git a/src/main/java/com/light/delivery/model/WxLoginRequest.java b/src/main/java/com/light/delivery/model/WxLoginRequest.java new file mode 100644 index 0000000..f01a399 --- /dev/null +++ b/src/main/java/com/light/delivery/model/WxLoginRequest.java @@ -0,0 +1,20 @@ +package com.light.delivery.model; + +import lombok.Data; + +/** + * 微信登录请求类,封装微信登录所需的参数。 + * 主要用于接收微信小程序登录时传递的code参数。 + */ +@Data +public class WxLoginRequest { + /** + * 微信登录凭证code + */ + private String code; + + /** + * 无参构造函数 + */ + public WxLoginRequest() {} +} \ No newline at end of file diff --git a/src/main/java/com/light/delivery/repository/DeliveryPersonRepository.java b/src/main/java/com/light/delivery/repository/DeliveryPersonRepository.java new file mode 100644 index 0000000..63c7786 --- /dev/null +++ b/src/main/java/com/light/delivery/repository/DeliveryPersonRepository.java @@ -0,0 +1,10 @@ +package com.light.delivery.repository; + +import com.light.delivery.model.DeliveryPerson; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface DeliveryPersonRepository extends JpaRepository { +} + diff --git a/src/main/java/com/light/delivery/repository/EmployeeRepository.java b/src/main/java/com/light/delivery/repository/EmployeeRepository.java new file mode 100644 index 0000000..017ec4f --- /dev/null +++ b/src/main/java/com/light/delivery/repository/EmployeeRepository.java @@ -0,0 +1,21 @@ +package com.light.delivery.repository; + +import com.light.delivery.model.Employee; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.Optional; + +/** + * 员工数据访问接口,提供对员工信息的数据库操作。 + * 继承JpaRepository,拥有基本的CRUD操作能力。 + */ +@Repository +public interface EmployeeRepository extends JpaRepository { + /** + * 根据手机号查找员工信息 + * @param phone 员工手机号 + * @return 员工信息Optional对象 + */ + Optional findByPhone(String phone); +} \ No newline at end of file diff --git a/src/main/java/com/light/delivery/repository/OrderRepository.java b/src/main/java/com/light/delivery/repository/OrderRepository.java new file mode 100644 index 0000000..bca94a0 --- /dev/null +++ b/src/main/java/com/light/delivery/repository/OrderRepository.java @@ -0,0 +1,15 @@ +package com.light.delivery.repository; + +import com.light.delivery.model.Order; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public interface OrderRepository extends JpaRepository { + List findByStatus(String status); + List findByWarehouseId(Long warehouseId); + List findByDeliveryPersonId(Long deliveryPersonId); +} + diff --git a/src/main/java/com/light/delivery/repository/UserRepository.java b/src/main/java/com/light/delivery/repository/UserRepository.java new file mode 100644 index 0000000..6dc2fb5 --- /dev/null +++ b/src/main/java/com/light/delivery/repository/UserRepository.java @@ -0,0 +1,19 @@ +package com.light.delivery.repository; + +import com.light.delivery.model.User; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +/** + * 用户数据访问接口,提供对用户信息的数据库操作。 + * 继承JpaRepository,拥有基本的CRUD操作能力。 + */ +@Repository +public interface UserRepository extends JpaRepository { + /** + * 根据微信openid查找用户 + * @param openid 微信openid + * @return 用户信息 + */ + User findByOpenid(String openid); +} \ No newline at end of file diff --git a/src/main/java/com/light/delivery/repository/WarehouseRepository.java b/src/main/java/com/light/delivery/repository/WarehouseRepository.java new file mode 100644 index 0000000..96575f4 --- /dev/null +++ b/src/main/java/com/light/delivery/repository/WarehouseRepository.java @@ -0,0 +1,10 @@ +package com.light.delivery.repository; + +import com.light.delivery.model.Warehouse; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface WarehouseRepository extends JpaRepository { +} + diff --git a/src/main/java/com/light/delivery/service/DeliveryPersonService.java b/src/main/java/com/light/delivery/service/DeliveryPersonService.java new file mode 100644 index 0000000..fc162bb --- /dev/null +++ b/src/main/java/com/light/delivery/service/DeliveryPersonService.java @@ -0,0 +1,36 @@ +package com.light.delivery.service; + +import com.light.delivery.model.DeliveryPerson; +import com.light.delivery.model.Order; + +import java.util.List; + +/** + * 配送员服务接口,定义配送员相关的业务操作。 + */ +public interface DeliveryPersonService { + /** + * 获取所有配送员信息。 + * @return 配送员列表 + */ + List getAllDeliveryPersons(); + /** + * 根据ID获取配送员详情。 + * @param id 配送员ID + * @return 配送员对象 + */ + DeliveryPerson getDeliveryPersonById(Long id); + /** + * 更新配送员当前位置。 + * @param id 配送员ID + * @param longitude 经度 + * @param latitude 纬度 + */ + void updateLocation(Long id, Double longitude, Double latitude); + /** + * 获取指定配送员的所有订单。 + * @param id 配送员ID + * @return 订单列表 + */ + List getCurrentOrders(Long id); +} \ No newline at end of file diff --git a/src/main/java/com/light/delivery/service/LocationSyncService.java b/src/main/java/com/light/delivery/service/LocationSyncService.java new file mode 100644 index 0000000..9e3579e --- /dev/null +++ b/src/main/java/com/light/delivery/service/LocationSyncService.java @@ -0,0 +1,33 @@ +package com.light.delivery.service; + +/** + * 位置同步服务接口 + */ +public interface LocationSyncService { + + /** + * 处理配送员位置更新 + * @param deliveryPersonId 配送员ID + * @param longitude 经度 + * @param latitude 纬度 + */ + void handleLocationUpdate(Long deliveryPersonId, Double longitude, Double latitude); + + /** + * 订阅位置更新 + * @param sessionId 会话ID + * @param deliveryPersonId 配送员ID + */ + void subscribe(String sessionId, Long deliveryPersonId); + + /** + * 取消订阅位置更新 + * @param sessionId 会话ID + */ + void unsubscribe(String sessionId); + + /** + * 清理过期的位置信息 + */ + void cleanupExpiredLocations(); +} \ No newline at end of file diff --git a/src/main/java/com/light/delivery/service/LocationWebSocketHandler.java b/src/main/java/com/light/delivery/service/LocationWebSocketHandler.java new file mode 100644 index 0000000..c494ba4 --- /dev/null +++ b/src/main/java/com/light/delivery/service/LocationWebSocketHandler.java @@ -0,0 +1,198 @@ +package com.light.delivery.service; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; +import org.springframework.web.socket.CloseStatus; +import org.springframework.web.socket.TextMessage; +import org.springframework.web.socket.WebSocketSession; +import org.springframework.web.socket.handler.TextWebSocketHandler; + +import java.io.IOException; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +@Component +public class LocationWebSocketHandler extends TextWebSocketHandler { + + // 存储所有连接的会话,key为配送员ID,value为会话 + private final Map sessions = new ConcurrentHashMap<>(); + + // 存储配送员最后更新位置的时间 + private final Map lastUpdateTimes = new ConcurrentHashMap<>(); + + private final ObjectMapper objectMapper = new ObjectMapper(); + + // 位置过期时间(毫秒),默认5分钟 + private static final long LOCATION_EXPIRE_TIME = 5 * 60 * 1000; + + @Override + public void afterConnectionEstablished(WebSocketSession session) throws Exception { + // 连接建立时,可以在这里进行身份验证 + System.out.println("WebSocket连接已建立: " + session.getId()); + } + + @Override + protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { + try { + // 解析消息 + String payload = message.getPayload(); + LocationMessage locationMessage = objectMapper.readValue(payload, LocationMessage.class); + + if ("updateLocation".equals(locationMessage.getType())) { + // 更新位置信息 + handleLocationUpdate(locationMessage); + } else if ("subscribe".equals(locationMessage.getType())) { + // 订阅位置更新 + handleSubscribe(session, locationMessage); + } else if ("unsubscribe".equals(locationMessage.getType())) { + // 取消订阅 + handleUnsubscribe(session, locationMessage); + } + } catch (Exception e) { + System.err.println("处理WebSocket消息时出错: " + e.getMessage()); + session.sendMessage(new TextMessage("{\"error\":\"消息处理失败\"}")); + } + } + + /** + * 处理位置更新消息 + */ + private void handleLocationUpdate(LocationMessage locationMessage) { + Long deliveryPersonId = locationMessage.getDeliveryPersonId(); + if (deliveryPersonId == null) { + return; + } + + // 更新最后更新时间 + lastUpdateTimes.put(deliveryPersonId, System.currentTimeMillis()); + + try { + // 广播位置更新给所有订阅者 + broadcastLocationUpdate(locationMessage); + } catch (IOException e) { + System.err.println("广播位置更新时出错: " + e.getMessage()); + } + } + + /** + * 处理订阅消息 + */ + private void handleSubscribe(WebSocketSession session, LocationMessage locationMessage) throws IOException { + Long deliveryPersonId = locationMessage.getDeliveryPersonId(); + if (deliveryPersonId != null) { + sessions.put(deliveryPersonId, session); + session.sendMessage(new TextMessage("{\"type\":\"subscribed\",\"deliveryPersonId\":" + deliveryPersonId + "}")); + } + } + + /** + * 处理取消订阅消息 + */ + private void handleUnsubscribe(WebSocketSession session, LocationMessage locationMessage) { + Long deliveryPersonId = locationMessage.getDeliveryPersonId(); + if (deliveryPersonId != null) { + sessions.remove(deliveryPersonId); + lastUpdateTimes.remove(deliveryPersonId); + } + } + + /** + * 广播位置更新给所有连接的客户端 + */ + private void broadcastLocationUpdate(LocationMessage locationMessage) throws IOException { + String message = objectMapper.writeValueAsString(locationMessage); + TextMessage textMessage = new TextMessage(message); + + // 发送给所有连接的客户端 + for (WebSocketSession session : sessions.values()) { + if (session.isOpen()) { + session.sendMessage(textMessage); + } + } + } + + @Override + public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { + // 连接关闭时,移除会话 + sessions.values().remove(session); + System.out.println("WebSocket连接已关闭: " + session.getId() + ", 状态: " + status); + } + + @Override + public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception { + System.err.println("WebSocket传输错误: " + exception.getMessage()); + sessions.values().remove(session); + } + + /** + * 定时检查并清理过期的位置信息(每30秒执行一次) + */ + @Scheduled(fixedRate = 30000) + public void cleanupExpiredLocations() { + long currentTime = System.currentTimeMillis(); + for (Map.Entry entry : lastUpdateTimes.entrySet()) { + Long deliveryPersonId = entry.getKey(); + Long lastUpdateTime = entry.getValue(); + + // 如果超过过期时间,则移除该配送员的信息 + if (currentTime - lastUpdateTime > LOCATION_EXPIRE_TIME) { + sessions.remove(deliveryPersonId); + lastUpdateTimes.remove(deliveryPersonId); + System.out.println("已清理过期位置信息,配送员ID: " + deliveryPersonId); + } + } + } + + /** + * 内部消息类,用于解析WebSocket消息 + */ + public static class LocationMessage { + private String type; // 消息类型: updateLocation, subscribe, unsubscribe + private Long deliveryPersonId; // 配送员ID + private Double latitude; // 纬度 + private Double longitude; // 经度 + private Long timestamp; // 时间戳 + + // Getters and Setters + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public Long getDeliveryPersonId() { + return deliveryPersonId; + } + + public void setDeliveryPersonId(Long deliveryPersonId) { + this.deliveryPersonId = deliveryPersonId; + } + + public Double getLatitude() { + return latitude; + } + + public void setLatitude(Double latitude) { + this.latitude = latitude; + } + + public Double getLongitude() { + return longitude; + } + + public void setLongitude(Double longitude) { + this.longitude = longitude; + } + + public Long getTimestamp() { + return timestamp; + } + + public void setTimestamp(Long timestamp) { + this.timestamp = timestamp; + } + } +} \ No newline at end of file diff --git a/src/main/java/com/light/delivery/service/OrderService.java b/src/main/java/com/light/delivery/service/OrderService.java new file mode 100644 index 0000000..eddf033 --- /dev/null +++ b/src/main/java/com/light/delivery/service/OrderService.java @@ -0,0 +1,41 @@ +package com.light.delivery.service; + +import com.light.delivery.model.Order; + +import java.util.List; + +/** + * 订单服务接口,定义订单相关的业务操作。 + */ +public interface OrderService { + /** + * 获取所有待分配订单。 + * @return 待分配订单列表 + */ + List getPendingOrders(); + /** + * 分配订单给指定配送员。 + * @param id 订单ID + * @param deliveryPersonId 配送员ID + */ + void assignOrder(Long id, Long deliveryPersonId); + /** + * 根据ID获取订单详情。 + * @param id 订单ID + * @return 订单对象 + */ + Order getOrderById(Long id); + /** + * 更新订单状态。 + * @param id 订单ID + * @param status 新状态 + */ + void updateOrderStatus(Long id, String status); + + /** + * 根据配送员ID获取订单列表。 + * @param deliveryPersonId 配送员ID + * @return 订单列表 + */ + List getOrdersByDeliveryPerson(Long deliveryPersonId); +} \ No newline at end of file diff --git a/src/main/java/com/light/delivery/service/UserService.java b/src/main/java/com/light/delivery/service/UserService.java new file mode 100644 index 0000000..9ea64e1 --- /dev/null +++ b/src/main/java/com/light/delivery/service/UserService.java @@ -0,0 +1,50 @@ +package com.light.delivery.service; + +import com.light.delivery.model.LoginResponse; +import com.light.delivery.model.User; +import com.light.delivery.model.WxLoginRequest; + +/** + * 用户服务接口,定义用户相关的业务操作。 + */ +public interface UserService { + /** + * 获取用户信息。 + * @param token 用户 token + * @return 用户信息 + */ + User getUserInfo(String token); + + /** + * 用户登出。 + * @param token 用户 token + */ + void logout(String token); + + /** + * 微信小程序登录,接收code,返回登录响应。 + */ + LoginResponse wxLogin(String code); + + /** + * 获取当前已登录用户(从上下文或模拟实现中) + */ + User getCurrentUser(); + + + /** + * 用户签到功能 + * @param userId 用户ID + * @return 签到结果 + */ + User signIn(Long userId); + + /** + * 注册为骑手 + * @param userId 用户ID + * @param name 姓名 + * @param phone 手机号 + * @return 注册结果 + */ + User registerAsDeliveryPerson(Long userId, String name, String phone); +} \ No newline at end of file diff --git a/src/main/java/com/light/delivery/service/WarehouseService.java b/src/main/java/com/light/delivery/service/WarehouseService.java new file mode 100644 index 0000000..eda018b --- /dev/null +++ b/src/main/java/com/light/delivery/service/WarehouseService.java @@ -0,0 +1,35 @@ +package com.light.delivery.service; + +import com.light.delivery.model.Order; +import com.light.delivery.model.Warehouse; + +import java.util.List; + +/** + * 仓库服务接口,定义仓库相关的业务操作。 + */ +public interface WarehouseService { + /** + * 获取所有仓库信息。 + * @return 仓库列表 + */ + List getAllWarehouses(); + /** + * 根据ID获取仓库详情。 + * @param id 仓库ID + * @return 仓库对象 + */ + Warehouse getWarehouseById(Long id); + /** + * 获取指定仓库的所有订单。 + * @param id 仓库ID + * @return 订单列表 + */ + List getWarehouseOrders(Long id); + /** + * 创建新仓库。 + * @param warehouse 仓库对象 + * @return 创建后的仓库对象 + */ + Warehouse createWarehouse(Warehouse warehouse); +} \ No newline at end of file diff --git a/src/main/java/com/light/delivery/service/impl/DeliveryPersonServiceImpl.java b/src/main/java/com/light/delivery/service/impl/DeliveryPersonServiceImpl.java new file mode 100644 index 0000000..ce1e5ec --- /dev/null +++ b/src/main/java/com/light/delivery/service/impl/DeliveryPersonServiceImpl.java @@ -0,0 +1,47 @@ +package com.light.delivery.service.impl; + +import com.light.delivery.model.DeliveryPerson; +import com.light.delivery.model.Order; +import com.light.delivery.repository.DeliveryPersonRepository; +import com.light.delivery.repository.OrderRepository; +import com.light.delivery.service.DeliveryPersonService; +import com.light.delivery.service.LocationSyncService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Optional; + +@Service +public class DeliveryPersonServiceImpl implements DeliveryPersonService { + @Autowired + private DeliveryPersonRepository deliveryPersonRepository; + + @Autowired + private OrderRepository orderRepository; + + @Autowired + private LocationSyncService locationSyncService; + + @Override + public List getAllDeliveryPersons() { + return deliveryPersonRepository.findAll(); + } + + @Override + public DeliveryPerson getDeliveryPersonById(Long id) { + Optional person = deliveryPersonRepository.findById(id); + return person.orElse(null); + } + + @Override + public void updateLocation(Long id, Double longitude, Double latitude) { + // 使用 LocationSyncService 更新位置信息到服务器缓存,而不是直接更新数据库 + locationSyncService.handleLocationUpdate(id, longitude, latitude); + } + + @Override + public List getCurrentOrders(Long id) { + return orderRepository.findByDeliveryPersonId(id); + } +} \ No newline at end of file diff --git a/src/main/java/com/light/delivery/service/impl/LocationSyncServiceImpl.java b/src/main/java/com/light/delivery/service/impl/LocationSyncServiceImpl.java new file mode 100644 index 0000000..3e28fd6 --- /dev/null +++ b/src/main/java/com/light/delivery/service/impl/LocationSyncServiceImpl.java @@ -0,0 +1,122 @@ +package com.light.delivery.service.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.light.delivery.model.DeliveryPerson; +import com.light.delivery.repository.DeliveryPersonRepository; +import com.light.delivery.service.LocationSyncService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.time.LocalDateTime; +import java.util.concurrent.ConcurrentHashMap; + +@Service +public class LocationSyncServiceImpl implements LocationSyncService { + + @Autowired + private DeliveryPersonRepository deliveryPersonRepository; + + // 存储会话ID与配送员ID的映射关系 + private final ConcurrentHashMap sessionDeliveryPersonMap = new ConcurrentHashMap<>(); + + // 存储配送员位置信息(经度、纬度) + private final ConcurrentHashMap deliveryPersonLongitudeMap = new ConcurrentHashMap<>(); + private final ConcurrentHashMap deliveryPersonLatitudeMap = new ConcurrentHashMap<>(); + + // 存储配送员状态信息 + private final ConcurrentHashMap deliveryPersonStatusMap = new ConcurrentHashMap<>(); + + // 存储配送员最后更新位置的时间 + private final ConcurrentHashMap lastUpdateTimes = new ConcurrentHashMap<>(); + + private final ObjectMapper objectMapper = new ObjectMapper(); + + // 位置过期时间(分钟) + private static final int LOCATION_EXPIRE_MINUTES = 5; + + @Override + public void handleLocationUpdate(Long deliveryPersonId, Double longitude, Double latitude) { + try { + // 更新内存缓存中的配送员位置,而不是数据库 + deliveryPersonLongitudeMap.put(deliveryPersonId, longitude); + deliveryPersonLatitudeMap.put(deliveryPersonId, latitude); + + // 更新最后更新时间 + lastUpdateTimes.put(deliveryPersonId, LocalDateTime.now()); + } catch (Exception e) { + System.err.println("更新配送员位置时出错: " + e.getMessage()); + } + } + + @Override + public void subscribe(String sessionId, Long deliveryPersonId) { + sessionDeliveryPersonMap.put(sessionId, deliveryPersonId); + lastUpdateTimes.put(deliveryPersonId, LocalDateTime.now()); + } + + @Override + public void unsubscribe(String sessionId) { + Long deliveryPersonId = sessionDeliveryPersonMap.remove(sessionId); + if (deliveryPersonId != null) { + // 从缓存中移除配送员信息 + deliveryPersonLongitudeMap.remove(deliveryPersonId); + deliveryPersonLatitudeMap.remove(deliveryPersonId); + deliveryPersonStatusMap.remove(deliveryPersonId); + lastUpdateTimes.remove(deliveryPersonId); + } + } + + @Override + public void cleanupExpiredLocations() { + LocalDateTime currentTime = LocalDateTime.now(); + lastUpdateTimes.entrySet().removeIf(entry -> { + LocalDateTime lastUpdateTime = entry.getValue(); + long minutesBetween = java.time.Duration.between(lastUpdateTime, currentTime).toMinutes(); + if (minutesBetween > LOCATION_EXPIRE_MINUTES) { + // 从缓存中清除过期的位置信息 + Long deliveryPersonId = entry.getKey(); + deliveryPersonLongitudeMap.remove(deliveryPersonId); + deliveryPersonLatitudeMap.remove(deliveryPersonId); + deliveryPersonStatusMap.remove(deliveryPersonId); + return true; // 移除这个过期的条目 + } + return false; // 保留未过期的条目 + }); + } + + /** + * 获取配送员当前经度 + * @param deliveryPersonId 配送员ID + * @return 经度 + */ + public Double getDeliveryPersonLongitude(Long deliveryPersonId) { + return deliveryPersonLongitudeMap.get(deliveryPersonId); + } + + /** + * 获取配送员当前纬度 + * @param deliveryPersonId 配送员ID + * @return 纬度 + */ + public Double getDeliveryPersonLatitude(Long deliveryPersonId) { + return deliveryPersonLatitudeMap.get(deliveryPersonId); + } + + /** + * 设置配送员状态 + * @param deliveryPersonId 配送员ID + * @param status 状态 + */ + public void setDeliveryPersonStatus(Long deliveryPersonId, String status) { + deliveryPersonStatusMap.put(deliveryPersonId, status); + } + + /** + * 获取配送员状态 + * @param deliveryPersonId 配送员ID + * @return 状态 + */ + public String getDeliveryPersonStatus(Long deliveryPersonId) { + return deliveryPersonStatusMap.get(deliveryPersonId); + } +} \ No newline at end of file diff --git a/src/main/java/com/light/delivery/service/impl/OrderServiceImpl.java b/src/main/java/com/light/delivery/service/impl/OrderServiceImpl.java new file mode 100644 index 0000000..f16ed4c --- /dev/null +++ b/src/main/java/com/light/delivery/service/impl/OrderServiceImpl.java @@ -0,0 +1,59 @@ +package com.light.delivery.service.impl; + +import com.light.delivery.model.Order; +import com.light.delivery.repository.OrderRepository; +import com.light.delivery.service.OrderService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Optional; + +/** + * 订单服务实现类,提供订单相关的业务逻辑实现。 + */ +@Service +public class OrderServiceImpl implements OrderService { + @Autowired + private OrderRepository orderRepository; + + /** + * 获取所有待分配订单。 + * @return 待分配订单列表 + */ + @Override + public List getPendingOrders() { + return orderRepository.findByStatus("PENDING"); + } + + @Override + public void assignOrder(Long id, Long deliveryPersonId) { + Optional optional = orderRepository.findById(id); + if (optional.isPresent()) { + Order order = optional.get(); + order.setDeliveryPersonId(deliveryPersonId); + order.setStatus("ASSIGNED"); + orderRepository.save(order); + } + } + + @Override + public Order getOrderById(Long id) { + return orderRepository.findById(id).orElse(null); + } + + @Override + public void updateOrderStatus(Long id, String status) { + Optional optional = orderRepository.findById(id); + if (optional.isPresent()) { + Order order = optional.get(); + order.setStatus(status); + orderRepository.save(order); + } + } + + @Override + public List getOrdersByDeliveryPerson(Long deliveryPersonId) { + return orderRepository.findByDeliveryPersonId(deliveryPersonId); + } +} \ No newline at end of file diff --git a/src/main/java/com/light/delivery/service/impl/UserServiceImpl.java b/src/main/java/com/light/delivery/service/impl/UserServiceImpl.java new file mode 100644 index 0000000..da48489 --- /dev/null +++ b/src/main/java/com/light/delivery/service/impl/UserServiceImpl.java @@ -0,0 +1,243 @@ +package com.light.delivery.service.impl; + +import com.light.delivery.dto.UserInfoResponse; +import com.light.delivery.model.Employee; +import com.light.delivery.model.LoginResponse; +import com.light.delivery.model.User; +import com.light.delivery.model.UserRole; +import com.light.delivery.model.WxLoginRequest; +import com.light.delivery.repository.EmployeeRepository; +import com.light.delivery.repository.UserRepository; +import com.light.delivery.service.UserService; +import com.light.delivery.util.JwtUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +/** + * 用户服务实现类,处理用户相关的业务逻辑。 + * 包括用户登录、注册、信息获取、签到等核心功能。 + */ +@Service +public class UserServiceImpl implements UserService { + + /** + * 用户数据访问对象,用于操作用户相关数据库表 + */ + @Autowired + private UserRepository userRepository; + + /** + * 员工数据访问对象,用于操作员工相关数据库表 + */ + @Autowired + private EmployeeRepository employeeRepository; + + /** + * JWT工具类,用于生成和解析JWT令牌 + */ + @Autowired + private JwtUtil jwtUtil; + + /** + * 根据JWT令牌获取用户信息。 + * 从token中解析出用户的openid,然后查询数据库获取完整的用户信息。 + * @param token 用户的JWT令牌 + * @return 用户实体对象 + * @throws IllegalArgumentException 当令牌无效或用户不存在时抛出异常 + */ + @Override + public User getUserInfo(String token) { + if (token == null || token.isEmpty()) { + throw new IllegalArgumentException("Authorization token is missing"); + } + + try { + // 解析token获取用户openid + String openid = jwtUtil.extractUsername(token); + if (openid == null || openid.isEmpty()) { + throw new IllegalArgumentException("Invalid token"); + } + + User user = userRepository.findByOpenid(openid); + if (user == null) { + throw new IllegalArgumentException("用户不存在"); + } + return user; + } catch (Exception e) { + // 捕获JWT解析异常等 + throw new IllegalArgumentException("Invalid token: " + e.getMessage()); + } + } + + /** + * 用户登出逻辑。 + * 由于使用无状态JWT认证,服务器端无需特殊处理。 + * 客户端应负责删除本地存储的token。 + * @param token 用户的JWT令牌(当前实现中未使用) + */ + @Override + public void logout(String token) { + // 无状态JWT,登出可为空实现,或清理本地缓存等 + } + + /** + * 处理微信登录逻辑。 + * 通过微信登录凭证(code)获取用户身份信息,创建或更新用户记录,并生成JWT令牌。 + * 实际项目中应调用微信API来获取真实的openid。 + * @param code 微信授权登录返回的临时凭证 + * @return 登录响应对象,包含JWT令牌、用户信息等 + * @throws IllegalArgumentException 当登录凭证为空时抛出异常 + */ + @Override + public LoginResponse wxLogin(String code) { + if (code == null || code.trim().isEmpty()) { + throw new IllegalArgumentException("登录code不能为空"); + } + + // 模拟微信登录,实际应该调用微信API获取 openid + String openid = "openid_" + code; // 模拟 openid + + User user = userRepository.findByOpenid(openid); + if (user == null) { + // 首次登录,创建新用户,默认为游客角色 + user = new User(); + user.setRole(UserRole.GUEST); // 默认为游客角色 + user.setOpenid(openid); + userRepository.save(user); + } else { + // 检查并修复用户角色 + if (user.getRole() == null) { + // 如果用户角色为空,设置为游客角色 + user.setRole(UserRole.GUEST); + userRepository.save(user); + } + } + + // 确保用户角色不为空,防止在生成token时出现空指针异常 + if (user.getRole() == null) { + user.setRole(UserRole.GUEST); + } + + String token = jwtUtil.generateToken(user.getOpenid(), user.getRole().getCode()); + LoginResponse response = new LoginResponse(); + response.setToken(token); + response.setUser(toUserInfoResponse(user)); + response.setOpenid(user.getOpenid()); + response.setSessionKey(""); + response.setExpiresIn(jwtUtil.getExpirationTime()); + return response; + } + + /** + * 用户签到功能。 + * 更新指定用户的信息,模拟签到过程。 + * 注意:当前实现中使用随机UUID作为openid,实际应用中应使用真实用户标识。 + * @param userId 用户唯一标识 + * @return 更新后的用户对象 + * @throws IllegalArgumentException 当指定ID的用户不存在时抛出异常 + */ + @Override + public User signIn(Long userId) { + Optional userOptional = userRepository.findById(userId); + if (!userOptional.isPresent()) { + throw new IllegalArgumentException("用户不存在"); + } + + User user = userOptional.get(); + // 不再更改用户的openid,保持原有的openid不变 + userRepository.save(user); + + return user; + } + + /** + * 用户注册成为配送员。 + * 验证用户提交的个人信息是否与员工数据库中的记录匹配, + * 如果验证成功,则更新用户角色为配送员,并建立用户与员工的关联。 + * @param userId 用户系统内的唯一标识 + * @param name 用户真实姓名 + * @param phone 用户手机号码 + * @return 更新后的用户对象 + * @throws IllegalArgumentException 当用户不存在、手机号未找到或姓名不匹配时抛出异常 + */ + @Override + public User registerAsDeliveryPerson(Long userId, String name, String phone) { + System.out.println("尝试注册配送员,用户ID: " + userId); + + Optional userOptional = userRepository.findById(userId); + if (!userOptional.isPresent()) { + System.err.println("未找到ID为 " + userId + " 的用户"); + throw new IllegalArgumentException("用户不存在"); + } + + // 查找员工信息表中是否有该手机号 + Optional employeeOptional = employeeRepository.findByPhone(phone); + if (!employeeOptional.isPresent()) { + throw new IllegalArgumentException("该手机号不在员工信息表中,请确认手机号是否正确"); + } + + Employee employee = employeeOptional.get(); + if (!employee.getName().equals(name)) { + throw new IllegalArgumentException("姓名与员工信息不匹配"); + } + + // 将openid写入employee表,表示该员工已成为系统用户 + employee.setOpenid(userOptional.get().getOpenid()); + employeeRepository.save(employee); + + // 更新用户信息 + User user = userOptional.get(); + user.setName(name); // 设置用户姓名 + user.setPhone(phone); // 设置用户手机号 + user.setRole(UserRole.fromCode(employee.getRole())); // 设置为员工对应的权限角色 + userRepository.save(user); + + return user; + } + + /** + * 处理微信登录请求对象。 + * 从WxLoginRequest对象中提取code参数,调用字符串参数版本的wxLogin方法。 + * @param wxLoginRequest 微信登录请求对象,包含登录所需参数 + * @return 登录响应对象 + */ + public LoginResponse wxLogin(WxLoginRequest wxLoginRequest) { + return wxLogin(wxLoginRequest.getCode()); + } + + /** + * 获取当前登录用户。 + * 在实际应用中,应从Spring Security上下文中获取当前认证用户。 + * 当前为简化实现,返回数据库中的第一个用户。 + * @return 当前用户对象 + * @throws IllegalArgumentException 当数据库中没有用户时抛出异常 + */ + @Override + public User getCurrentUser() { + // 这里应从安全上下文获取当前用户,简化为取第一个用户 + List users = userRepository.findAll(); + if (users.isEmpty()) throw new IllegalArgumentException("无用户"); + return users.get(0); + } + + /** + * 将用户实体转换为用户信息响应DTO。 + * 用于将数据库中的用户实体对象转换为对外暴露的响应数据传输对象。 + * @param user 用户实体对象 + * @return 用户信息响应DTO对象 + */ + private UserInfoResponse toUserInfoResponse(User user) { + UserInfoResponse dto = new UserInfoResponse(); + dto.setId(user.getId()); + dto.setName(user.getName()); + dto.setPhone(user.getPhone()); + dto.setRole(user.getRole() != null ? user.getRole().getCode() : null); + dto.setOpenid(user.getOpenid()); + return dto; + } +} \ No newline at end of file diff --git a/src/main/java/com/light/delivery/service/impl/WarehouseServiceImpl.java b/src/main/java/com/light/delivery/service/impl/WarehouseServiceImpl.java new file mode 100644 index 0000000..c117208 --- /dev/null +++ b/src/main/java/com/light/delivery/service/impl/WarehouseServiceImpl.java @@ -0,0 +1,63 @@ +package com.light.delivery.service.impl; + +import com.light.delivery.model.Order; +import com.light.delivery.model.Warehouse; +import com.light.delivery.repository.OrderRepository; +import com.light.delivery.repository.WarehouseRepository; +import com.light.delivery.service.WarehouseService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Optional; + +/** + * 仓库服务实现类,提供仓库相关的业务逻辑实现。 + */ +@Service +public class WarehouseServiceImpl implements WarehouseService { + @Autowired + private WarehouseRepository warehouseRepository; + @Autowired + private OrderRepository orderRepository; + + /** + * 获取所有仓库信息。 + * @return 仓库列表 + */ + @Override + public List getAllWarehouses() { + return warehouseRepository.findAll(); + } + + /** + * 根据ID获取仓库详情。 + * @param id 仓库ID + * @return 仓库对象 + */ + @Override + public Warehouse getWarehouseById(Long id) { + Optional warehouse = warehouseRepository.findById(id); + return warehouse.orElse(null); + } + + /** + * 获取指定仓库的所有订单。 + * @param id 仓库ID + * @return 订单列表 + */ + @Override + public List getWarehouseOrders(Long id) { + return orderRepository.findByWarehouseId(id); + } + + /** + * 创建新仓库。 + * @param warehouse 仓库对象 + * @return 创建的仓库对象 + */ + @Override + public Warehouse createWarehouse(Warehouse warehouse) { + return warehouseRepository.save(warehouse); + } +} \ No newline at end of file diff --git a/src/main/java/com/light/delivery/util/JwtUtil.java b/src/main/java/com/light/delivery/util/JwtUtil.java new file mode 100644 index 0000000..cc87e27 --- /dev/null +++ b/src/main/java/com/light/delivery/util/JwtUtil.java @@ -0,0 +1,179 @@ +package com.light.delivery.util; + +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.SignatureAlgorithm; +import io.jsonwebtoken.security.Keys; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import javax.crypto.SecretKey; +import java.util.Base64; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.function.Function; + + +/** + * JWT 工具类,负责生成、解析和校验 JWT Token。 + * 提供Token的创建、解析、验证等核心功能。 + */ +@Component +public class JwtUtil { + + /** + * JWT 密钥,从配置文件注入。 + */ + @Value("${jwt.secret}") + private String secret; + + /** + * JWT 过期时间(秒),从配置文件注入。 + */ + @Value("${jwt.expiration}") + private Long expiration; + + + /** + * 生成一个安全的随机密钥,并打印其Base64编码字符串(用于配置到配置文件中) + */ + public static void main(String[] args) { + // 生成一个专门用于 HS512 算法的安全随机密钥 + SecretKey secretKey = Keys.secretKeyFor(SignatureAlgorithm.HS512); + + // 将密钥转换为Base64字符串,方便存储在配置文件中 + String base64Key = Base64.getEncoder().encodeToString(secretKey.getEncoded()); + + System.out.println("Generated Base64 Secret Key: "); + System.out.println(base64Key); + // 复制控制台输出的这一长串字符,放到你的配置里 + } + + /** + * 生成包含用户名和角色的 JWT Token。 + * @param username 用户名 + * @param role 角色 + * @return 生成的 Token 字符串 + */ + public String generateToken(String username, String role) { + Map claims = new HashMap<>(); + claims.put("role", role); + return createToken(claims, username); + } + + /** + * 创建 JWT Token。 + * @param claims 载荷信息 + * @param subject 用户名 + * @return Token 字符串 + */ + private String createToken(Map claims, String subject) { + return Jwts.builder() + .setClaims(claims) + .setSubject(subject) + .setIssuedAt(new Date(System.currentTimeMillis())) + .setExpiration(new Date(System.currentTimeMillis() + expiration * 1000)) + .signWith(SignatureAlgorithm.HS512, secret) + .compact(); + } + + + /** + * 从Token中提取用户名。 + * @param token Token字符串 + * @return 用户名 + */ + public String getUsernameFromToken(String token) { + if (token == null) { + throw new IllegalArgumentException("Token cannot be null"); + } + + Claims claims = Jwts.parser() + .setSigningKey(secret) // secret 为你的 JWT 密钥 + .parseClaimsJws(token.replace("Bearer ", "")) + .getBody(); + return claims.getSubject(); // subject 通常存储用户名 + } + + /** + * 从Token中提取用户名。 + * @param token Token字符串 + * @return 用户名 + */ + public String extractUsername(String token) { + return getUsernameFromToken(token); + } + + /** + * 校验 Token 是否有效。 + * @param token Token 字符串 + * @param username 用户名 + * @return 是否有效 + */ + public Boolean validateToken(String token, String username) { + if (token == null) { + return false; + } + + final String extractedUsername = getUsernameFromToken(token); + return (extractedUsername.equals(username) && !isTokenExpired(token)); + } + + /** + * 从 Token 中提取角色。 + * @param token Token 字符串 + * @return 角色 + */ + public String extractRole(String token) { + final Claims claims = extractAllClaims(token); + return (String) claims.get("role"); + } + + /** + * 从 Token 中提取过期时间。 + * @param token Token 字符串 + * @return 过期时间 + */ + public Date extractExpiration(String token) { + return extractClaim(token, Claims::getExpiration); + } + + /** + * 从 Token 中提取自定义信息。 + * @param token Token 字符串 + * @param claimsResolver 提取函数 + * @param 返回类型 + * @return 提取的自定义信息 + */ + public T extractClaim(String token, Function claimsResolver) { + final Claims claims = extractAllClaims(token); + return claimsResolver.apply(claims); + } + + /** + * 解析 Token 中的所有声明。 + * @param token Token 字符串 + * @return 声明信息 + */ + private Claims extractAllClaims(String token) { + return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody(); + } + + /** + * 判断 Token 是否过期。 + * @param token Token 字符串 + * @return 是否过期 + */ + private Boolean isTokenExpired(String token) { + return extractExpiration(token).before(new Date()); + } + + /** + * 获取 JWT 过期时间。 + * @return 过期时间(秒) + */ + public Long getExpirationTime() { + return expiration; + } +} \ No newline at end of file diff --git a/src/main/resources/application-dev.yml b/src/main/resources/application-dev.yml new file mode 100644 index 0000000..0e05357 --- /dev/null +++ b/src/main/resources/application-dev.yml @@ -0,0 +1,16 @@ +# 开发环境配置 +server: + port: 8080 + +spring: + application: + name: light-delivery-backend-dev + +logging: + level: + com.light.delivery: DEBUG + +# JWT配置 +jwt: + secret: lightDeliveryDevSecretKey + expiration: 86400 \ No newline at end of file diff --git a/src/main/resources/application-prod.yml b/src/main/resources/application-prod.yml new file mode 100644 index 0000000..b3307a1 --- /dev/null +++ b/src/main/resources/application-prod.yml @@ -0,0 +1,20 @@ +# 生产环境配置 +server: + port: 443 + ssl: + key-store-type: PKCS12 + key-store: /etc/ssl/certs/www.doubleyin.cn.pfx + key-store-password: ${KEY_STORE_PASSWORD} + +spring: + application: + name: light-delivery-backend-prod + +logging: + level: + com.light.delivery: INFO + +# JWT配置 +jwt: + secret: lightDeliveryProdSecretKey + expiration: 86400 \ No newline at end of file diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties new file mode 100644 index 0000000..e9439bf --- /dev/null +++ b/src/main/resources/application.properties @@ -0,0 +1,38 @@ +spring.application.name=Light + +# --- MySQL Database Configuration (Remote Server) --- +spring.datasource.url=jdbc:mysql://115.190.121.151:3306/light_delivery?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true +spring.datasource.username=double +spring.datasource.password=Hu@ng1998! +spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver + +# JPA / Hibernate Settings +spring.jpa.hibernate.ddl-auto=update +spring.jpa.show-sql=true +spring.jpa.properties.hibernate.format_sql=true +# For MySQL +spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect + +# HikariCP Connection Pool Settings +spring.datasource.hikari.maximum-pool-size=10 +spring.datasource.hikari.minimum-idle=2 +spring.datasource.hikari.connection-timeout=30000 +spring.datasource.hikari.idle-timeout=600000 +spring.datasource.hikari.max-lifetime=1800000 + +# ------ WeChat Configuration ------ +wx.appId=wx1b790fd953ac27bf +wx.secret=b38c40c89cc4954472fb45d1e7cc27a4 +wx.token=huang1998 +wx.aesKey=lwararkj1BgurX8Qown6yjGNsqd8dEIEddDnYN3iLgc + +# WeChat API URLs +wx.api.access-token-url=https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential +wx.api.code2session-url=https://api.weixin.qq.com/sns/jscode2session + +# Logging Configuration +logging.level.com.light.delivery.config=DEBUG + +# JWT Configuration +jwt.secret=R/GuND+mK487AS+bUW5uqGmt5dyCkPf3g+uRdxHBY1eYEhxxG1cNgnfrk0l+vv+Xi8werl4P2lDAs0gaiqAqRA== +jwt.expiration=86400 \ 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..714dbf3 --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,16 @@ +# 默认配置 +spring: + profiles: + active: dev + +server: + port: 8080 + +logging: + level: + com.light.delivery: DEBUG + +# JWT配置 +jwt: + secret: lightDeliverySecretKey + expiration: 86400 \ No newline at end of file