Compare commits

..

No commits in common. "main" and "master" have entirely different histories.
main ... master

116 changed files with 1760 additions and 3846 deletions

76
.gitignore vendored
View File

@ -1,46 +1,38 @@
# ---> Maven
target/
pom.xml.tag
pom.xml.releaseBackup
pom.xml.versionsBackup
pom.xml.next
release.properties
dependency-reduced-pom.xml
buildNumber.properties
.mvn/timing.properties
# https://github.com/takari/maven-wrapper#usage-without-binary-jar
.mvn/wrapper/maven-wrapper.jar
HELP.md
.gradle
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
# Eclipse m2e generated files
# Eclipse Core
.project
# JDT-specific (Eclipse Java Development Tools)
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
# ---> Java
# Compiled class file
*.class
# Log file
*.log
# BlueJ files
*.ctxt
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
replay_pid*
### IntelliJ IDEA ###
.idea
target
*.iws
*.iml
*.ipr
out/
!**/src/main/**/out/
!**/src/test/**/out/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/
run/

View File

@ -1,3 +0,0 @@
# Commerce-System-Backend
🚧 Fix, Feat,🔨 Refactor,📝 Docs,✨ Style,🍱 Perf,🔧 Test,⚡️ Chore,🐛 Bug
Commerce System

60
build.gradle.kts Normal file
View File

@ -0,0 +1,60 @@
plugins {
java
id("org.springframework.boot") version "3.1.2"
id("io.spring.dependency-management") version "1.1.2"
id("org.graalvm.buildtools.native") version "0.9.23"
}
group = "cn.wzpmc"
version = "0.0.1-SNAPSHOT"
java {
sourceCompatibility = JavaVersion.VERSION_17
}
configurations {
compileOnly {
extendsFrom(configurations.annotationProcessor.get())
}
}
repositories {
mavenCentral()
}
dependencies {
implementation("org.springframework.boot:spring-boot-starter-actuator")
implementation("org.springframework.boot:spring-boot-starter-data-redis")
implementation("org.springframework.boot:spring-boot-starter-security")
implementation("org.springframework.boot:spring-boot-starter-web") {
exclude("org.springframework.boot", "spring-boot-starter-json")
}
implementation("org.springframework.boot:spring-boot-starter-websocket")
// https://mvnrepository.com/artifact/org.mybatis/mybatis
implementation("org.mybatis:mybatis:3.5.13")
implementation("com.baomidou:mybatis-plus-boot-starter:3.5.3.1") {
exclude("org.mybatis", "mybatis")
}
// https://mvnrepository.com/artifact/com.alibaba.fastjson2/fastjson2
implementation("com.alibaba.fastjson2:fastjson2:2.0.38")
// https://mvnrepository.com/artifact/com.alibaba.fastjson2/fastjson2-extension
implementation("com.alibaba.fastjson2:fastjson2-extension:2.0.38")
// https://mvnrepository.com/artifact/com.alibaba.fastjson2/fastjson2-extension-spring6
implementation("com.alibaba.fastjson2:fastjson2-extension-spring6:2.0.38")
// https://mvnrepository.com/artifact/org.springdoc/springdoc-openapi-starter-webmvc-ui
implementation("org.springdoc:springdoc-openapi-starter-webmvc-ui:2.1.0")
compileOnly("org.projectlombok:lombok")
developmentOnly("org.springframework.boot:spring-boot-devtools")
runtimeOnly("com.mysql:mysql-connector-j")
annotationProcessor("org.projectlombok:lombok")
testImplementation("org.springframework.boot:spring-boot-starter-test")
testImplementation("org.springframework.security:spring-security-test")
}
tasks.withType<Test> {
useJUnitPlatform()
}
tasks.withType<JavaCompile> {
options.encoding = "UTF-8"
}

View File

@ -1,160 +0,0 @@
/*
Navicat Premium Data Transfer
Source Server : commerce_system
Source Server Type : MySQL
Source Server Version : 80024 (8.0.24)
Source Host : wzpmc.cn:3306
Source Schema : commerce_system
Target Server Type : MySQL
Target Server Version : 80024 (8.0.24)
File Encoding : 65001
Date: 27/04/2023 16:14:29
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for auth_account
-- ----------------------------
DROP TABLE IF EXISTS `auth_account`;
CREATE TABLE `auth_account` (
`id` int NOT NULL AUTO_INCREMENT COMMENT '#',
`username` varchar(20) COLLATE utf8mb4_general_ci NOT NULL COMMENT '用户名',
`email` varchar(50) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '邮箱',
`rel_name` varchar(5) COLLATE utf8mb4_general_ci NOT NULL COMMENT '真实姓名',
`password` varchar(255) COLLATE utf8mb4_general_ci NOT NULL COMMENT '密码',
`status` tinyint(1) DEFAULT '1' COMMENT '状态',
`role_id` int DEFAULT '0' COMMENT '角色',
`create_time` timestamp NOT NULL COMMENT '创建时间',
`update_time` timestamp NULL DEFAULT NULL COMMENT '最近更新时间',
`del` tinyint(1) DEFAULT '0' COMMENT '逻辑删除',
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`),
UNIQUE KEY `email` (`email`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
-- ----------------------------
-- Table structure for auth_permissions
-- ----------------------------
DROP TABLE IF EXISTS `auth_permissions`;
CREATE TABLE `auth_permissions` (
`id` int NOT NULL AUTO_INCREMENT COMMENT '#',
`permission_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '权限名',
`permission_code` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '权限代码',
`description` varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '介绍',
`account_id` int NOT NULL COMMENT '创建者id',
`create_time` timestamp NOT NULL COMMENT '创建时间',
`update_time` timestamp NULL DEFAULT NULL COMMENT '最后更新时间',
`status` tinyint(1) DEFAULT '1' COMMENT '状态',
`del` tinyint(1) DEFAULT '0' COMMENT '逻辑删除',
PRIMARY KEY (`id`),
UNIQUE KEY `permission_name` (`permission_name`),
UNIQUE KEY `permission_code` (`permission_code`),
KEY `account_id` (`account_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
-- ----------------------------
-- Table structure for auth_roles
-- ----------------------------
DROP TABLE IF EXISTS `auth_roles`;
CREATE TABLE `auth_roles` (
`id` int NOT NULL AUTO_INCREMENT COMMENT '#',
`role_name` varchar(20) COLLATE utf8mb4_general_ci NOT NULL COMMENT '角色名',
`description` varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '简介',
`account_id` int NOT NULL COMMENT '创建者id',
`create_time` timestamp NOT NULL COMMENT '创建时间',
`update_time` timestamp NULL DEFAULT NULL COMMENT '最后更新时间',
`status` tinyint(1) DEFAULT '1' COMMENT '状态',
`del` tinyint(1) DEFAULT '0' COMMENT '逻辑删除',
PRIMARY KEY (`id`),
UNIQUE KEY `role_name` (`role_name`),
KEY `account_id` (`account_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
-- ----------------------------
-- Table structure for auth_route
-- ----------------------------
DROP TABLE IF EXISTS `auth_route`;
CREATE TABLE `auth_route` (
`id` int NOT NULL COMMENT '#',
`path` varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '前端访问路径',
`name` varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '前端路由名称',
`parent_id` int DEFAULT NULL COMMENT '父组件id',
`component` varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '前端本地组件路径',
`title` varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '前端标题栏',
`status` blob COMMENT '状态',
`create_id` int DEFAULT NULL COMMENT '创建者id',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
`update_id` int DEFAULT NULL COMMENT '最后修改者id',
`update_time` datetime DEFAULT NULL COMMENT '最后修改时间',
`remark` varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '备注',
`del` int DEFAULT '0' COMMENT '逻辑删除',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
-- ----------------------------
-- Table structure for commission
-- ----------------------------
DROP TABLE IF EXISTS `commission`;
CREATE TABLE `commission` (
`id` int NOT NULL AUTO_INCREMENT COMMENT '#',
`price_min` double(9,2) NOT NULL COMMENT '最小区间',
`price_max` double(9,2) NOT NULL COMMENT '最大区间',
`commission` double(5,2) NOT NULL COMMENT '佣金',
`store_id` int NOT NULL COMMENT '店铺名称',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
`update_time` datetime DEFAULT NULL COMMENT '更新时间',
`del` int DEFAULT '0' COMMENT '逻辑删除',
`status` blob COMMENT '状态',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
-- ----------------------------
-- Table structure for shop_order
-- ----------------------------
DROP TABLE IF EXISTS `shop_order`;
CREATE TABLE `shop_order` (
`id` int NOT NULL AUTO_INCREMENT COMMENT '#',
`order_no` varchar(30) COLLATE utf8mb4_general_ci NOT NULL COMMENT '订单号',
`order_time` datetime NOT NULL COMMENT '下单时间',
`order_status` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '订单状态',
`wang_no` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '旺旺号',
`wechat_no` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '微信账号',
`alipay_no` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '支付宝账号',
`pay_amt` double(10,2) NOT NULL COMMENT '付款金额',
`store_id` int NOT NULL COMMENT '店铺id',
`commission` double(10,2) DEFAULT NULL COMMENT '佣金',
`alipay_name` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '支付宝收款名称',
`rp_name` varchar(20) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '负责人',
`rp_wechat_name` varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '负责放单人微信名',
`remark` varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '备注',
`phone_number` varchar(11) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '买家电话',
`card_no` varchar(20) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '银行卡号',
`flag` int DEFAULT NULL COMMENT '插旗',
`flag_remark` varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '插旗备注',
`pay_time` datetime DEFAULT NULL COMMENT '付款时间',
`address` varchar(255) COLLATE utf8mb4_general_ci NOT NULL COMMENT '收货地址',
`shop_id` int DEFAULT NULL COMMENT '商品id',
`sku` varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT 'sku',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
-- ----------------------------
-- Table structure for store
-- ----------------------------
DROP TABLE IF EXISTS `store`;
CREATE TABLE `store` (
`id` int NOT NULL AUTO_INCREMENT COMMENT '#',
`name` varchar(255) COLLATE utf8mb4_general_ci NOT NULL COMMENT '店铺名称',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
`update_time` datetime DEFAULT NULL COMMENT '更新时间',
`del` int DEFAULT '0' COMMENT '逻辑删除',
`status` blob COMMENT '状态',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
SET FOREIGN_KEY_CHECKS = 1;

4
gradle.properties Normal file
View File

@ -0,0 +1,4 @@
systemProp.http.proxyHost=127.0.0.1
systemProp.http.proxyPort=7890
systemProp.https.proxyHost=127.0.0.1
systemProp.https.proxyPort=7890

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://mirrors.cloud.tencent.com/gradle/gradle-8.2.1-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

248
gradlew vendored Normal file
View File

@ -0,0 +1,248 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed 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
#
# https://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.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
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
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

92
gradlew.bat vendored Normal file
View File

@ -0,0 +1,92 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

148
pom.xml
View File

@ -1,148 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>top.xinsin</groupId>
<artifactId>Commerce-System-Backend</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.5</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.3.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba.fastjson2/fastjson2 -->
<dependency>
<groupId>com.alibaba.fastjson2</groupId>
<artifactId>fastjson2</artifactId>
<version>2.0.26</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.26</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.auth0/java-jwt -->
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>4.4.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.15</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.32</version>
<scope>runtime</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/druid-spring-boot-starter -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.16</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.5.3.1</version>
</dependency>
<!-- 模板引擎依赖-->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.3.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

1
settings.gradle.kts Normal file
View File

@ -0,0 +1 @@
rootProject.name = "commerce"

View File

@ -0,0 +1,14 @@
package cn.wzpmc.commerce;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("cn.wzpmc.commerce.mappers")
public class CommerceSystemBackendApplication {
public static void main(String[] args) {
SpringApplication.run(CommerceSystemBackendApplication.class, args);
}
}

View File

@ -0,0 +1,16 @@
package cn.wzpmc.commerce.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CorsConfiguration implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOriginPatterns("**")
.allowedMethods("GET", "POST", "HEAD", "OPTION", "PUT")
.allowCredentials(true);
}
}

View File

@ -0,0 +1,32 @@
package cn.wzpmc.commerce.config;
import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.support.config.FastJsonConfig;
import com.alibaba.fastjson2.support.spring6.http.converter.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.lang.NonNull;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.nio.charset.StandardCharsets;
import java.util.List;
@Configuration
public class FastJsonMvcConfiguration implements WebMvcConfigurer {
private static final boolean debug = false;
@Override
public void configureMessageConverters(@NonNull List<HttpMessageConverter<?>> converters) {
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
fastJsonConfig.setCharset(StandardCharsets.UTF_8);
JSONWriter.Feature[] writerFeatures = {JSONWriter.Feature.MapSortField, JSONWriter.Feature.IgnoreNonFieldGetter, JSONWriter.Feature.PrettyFormat};
if (!debug) {
writerFeatures = new JSONWriter.Feature[]{JSONWriter.Feature.MapSortField, JSONWriter.Feature.IgnoreNonFieldGetter};
}
fastJsonConfig.setWriterFeatures(writerFeatures);
FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
converter.setFastJsonConfig(fastJsonConfig);
converters.add(0, converter);
}
}

View File

@ -0,0 +1,79 @@
package cn.wzpmc.commerce.config;
import cn.wzpmc.commerce.controllers.AuthController;
import cn.wzpmc.commerce.utils.MessageResponse;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.AccessDeniedHandler;
import java.io.IOException;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@SneakyThrows
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity security) {
security.authorizeHttpRequests(registry -> registry.requestMatchers("/api/auth/**",
"/swagger-ui/**",
"/swagger-ui.html",
"/v3/**").permitAll()
.anyRequest().authenticated());
security.csrf(AbstractHttpConfigurer::disable);
security.cors(AbstractHttpConfigurer::disable);
security.formLogin(httpSecurityFormLoginConfigurer -> httpSecurityFormLoginConfigurer
.loginPage("/api/auth/notLogin")
.loginProcessingUrl("/api/auth/login")
.successHandler(AuthController::loginSuccess)
.failureHandler(AuthController::loginFailed));
security.logout(httpSecurityLogoutConfigurer -> httpSecurityLogoutConfigurer.logoutUrl("/api/auth/logout")
.logoutSuccessHandler(AuthController::logoutSuccess)
.permitAll());
security.exceptionHandling(httpSecurityExceptionHandlingConfigurer -> httpSecurityExceptionHandlingConfigurer.authenticationEntryPoint(new MyAuthenticationEntryPoint())
.accessDeniedHandler(new MyAccessDeniedHandler()));
return security.build();
}
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
private static class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
String localizedMessage = authException.getLocalizedMessage();
response.setStatus(403);
response.setContentType("application/json");
ServletOutputStream outputStream = response.getOutputStream();
new MessageResponse(localizedMessage, 403).copyToStream(outputStream);
outputStream.close();
}
}
private static class MyAccessDeniedHandler implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException {
String localizedMessage = accessDeniedException.getLocalizedMessage();
response.setStatus(404);
response.setContentType("application/json");
ServletOutputStream outputStream = response.getOutputStream();
new MessageResponse(localizedMessage, 403).copyToStream(outputStream);
outputStream.close();
}
}
}

View File

@ -0,0 +1,81 @@
package cn.wzpmc.commerce.controllers;
import cn.wzpmc.commerce.entities.User;
import cn.wzpmc.commerce.entities.vo.AccountVo;
import cn.wzpmc.commerce.services.UserService;
import cn.wzpmc.commerce.utils.DataResponse;
import cn.wzpmc.commerce.utils.MessageResponse;
import io.swagger.v3.oas.annotations.Hidden;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.*;
@Tag(name = "AuthController", description = "用户权限、登录、注册控制器")
@RestController
@RequestMapping("/api/auth")
public class AuthController {
private final UserService service;
@Autowired
public AuthController(UserService service) {
this.service = service;
}
@SneakyThrows
public static void loginSuccess(HttpServletRequest ignoredRequest, HttpServletResponse response, Authentication authentication) {
response.setStatus(200);
response.setContentType("application/json");
ServletOutputStream outputStream = response.getOutputStream();
new DataResponse<>((User) authentication.getPrincipal(), "登陆成功!").copyToStream(outputStream);
outputStream.close();
}
@SneakyThrows
public static void loginFailed(HttpServletRequest ignoredRequest, HttpServletResponse response, AuthenticationException authenticationException) {
response.setStatus(403);
response.setContentType("application/json");
ServletOutputStream outputStream = response.getOutputStream();
new MessageResponse(authenticationException.getLocalizedMessage(), 403).copyToStream(outputStream);
outputStream.close();
}
@SneakyThrows
public static void logoutSuccess(HttpServletRequest ignoredRequest, HttpServletResponse response, Authentication ignoredAuthentication) {
response.setStatus(200);
response.setContentType("application/json");
ServletOutputStream outputStream = response.getOutputStream();
new MessageResponse("登出成功!").copyToStream(outputStream);
outputStream.close();
}
@SneakyThrows
@Hidden
@GetMapping("/notLogin")
public void notLogin(HttpServletResponse response) {
response.setStatus(403);
response.setContentType("application/json");
ServletOutputStream outputStream = response.getOutputStream();
new MessageResponse("未登录", 403).copyToStream(outputStream);
outputStream.close();
}
@SneakyThrows
@Operation(summary = "注册", description = "注册一个账号")
@ApiResponse(responseCode = "200", description = "返回一个用户对象")
@PostMapping("/register")
public MessageResponse register(@RequestBody AccountVo accountVo) {
User user = service.addUser(accountVo);
if (user != null) {
return new DataResponse<>(user, "注册成功!");
}
return new MessageResponse("注册失败!用户已存在!", 304);
}
}

View File

@ -0,0 +1,78 @@
package cn.wzpmc.commerce.controllers;
import cn.wzpmc.commerce.entities.User;
import cn.wzpmc.commerce.entities.vo.PermissionVo;
import cn.wzpmc.commerce.services.PermissionService;
import cn.wzpmc.commerce.utils.DataResponse;
import cn.wzpmc.commerce.utils.MessageResponse;
import cn.wzpmc.commerce.utils.PageableResponse;
import cn.wzpmc.commerce.utils.ServiceUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@Tag(name = "权限控制器", description = "权限管理器CRUD")
@RequestMapping("/authPermissions")
public class PermissionController {
private final PermissionService permissionService;
@Autowired
public PermissionController(PermissionService permissionService) {
this.permissionService = permissionService;
}
@Operation(summary = "添加一个权限")
@PostMapping(path = "/addAuthPermissions")
public MessageResponse addAuthPermissions(@RequestBody PermissionVo authPermissionVo, Authentication authentication) {
authPermissionVo.setCreateId(((User) authentication.getPrincipal()).getId());
if (permissionService.save(authPermissionVo)) {
return new MessageResponse("添加成功!");
}
return new MessageResponse("添加失败!", 500);
}
@Operation(summary = "修改权限")
@PostMapping(path = "/changeAuthPermissions")
public MessageResponse changeAuthPermissions(@RequestBody PermissionVo authPermissionVo) {
if (ServiceUtils.update(permissionService, authPermissionVo)) {
return new MessageResponse("修改成功!");
}
return new MessageResponse("修改失败!", 500);
}
@Operation(summary = "删除权限")
@GetMapping(path = "/delAuthPermissions")
public MessageResponse delAuthPermissions(@RequestParam("id") int id) {
if (permissionService.removeById(id)) {
return new MessageResponse("删除成功!");
}
return new MessageResponse("删除失败,未找到!", 500);
}
@Operation(summary = "分页获取权限")
@GetMapping(path = "/getAuthPermissions")
public PageableResponse<PermissionVo> getAuthPermissions(@RequestParam("page") int page, @RequestParam("num") int num) {
return PageableResponse.of(permissionService.page(new Page<>(page, num)));
}
@Operation(summary = "修改一个权限的状态")
@GetMapping(path = "/changeAuthPermissionsStats")
public MessageResponse changeAuthPermissionsStats(@RequestParam("authPermissionId") int id, @RequestParam("status") boolean status) {
if (ServiceUtils.updateStatus(this.permissionService, id, status)) {
return new MessageResponse("修改成功!");
}
return new MessageResponse("修改失败!", 500);
}
@Operation(summary = "获取所有权限")
@GetMapping(path = "/getAuthPermissionsId")
public DataResponse<List<PermissionVo>> getAuthPermissionsId() {
return new DataResponse<>(permissionService.list());
}
}

View File

@ -0,0 +1,59 @@
package cn.wzpmc.commerce.controllers;
import cn.wzpmc.commerce.entities.User;
import cn.wzpmc.commerce.entities.vo.AccountVo;
import cn.wzpmc.commerce.services.UserService;
import cn.wzpmc.commerce.utils.DataResponse;
import cn.wzpmc.commerce.utils.MessageResponse;
import cn.wzpmc.commerce.utils.PageableResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
@Tag(name = "用户账号控制器", description = "用户的增删改查")
@RestController
@RequestMapping("/account")
public class UserController {
private final UserService userService;
@Autowired
public UserController(UserService userService) {
this.userService = userService;
}
@Operation(summary = "更改账户信息", description = "使用传入账号的id对账户信息进行更改包括用户名、邮箱、真名、权限组")
@PostMapping("/changeAccount")
public MessageResponse changeAccount(@RequestBody AccountVo accountVo) {
return this.userService.changeAccount(accountVo);
}
@Operation(summary = "修改密码", parameters = {@Parameter(name = "userId", description = "用户id"), @Parameter(name = "oldPassword", description = "旧密码"), @Parameter(name = "newPassword", description = "新密码")})
@PostMapping("/changePassword")
public MessageResponse changePassword(@RequestParam("userId") Integer userId, @RequestParam("oldPassword") String oldPassword, @RequestParam("newPassword") String newPassword) {
return this.userService.changePassword(userId, oldPassword, newPassword);
}
@Operation(summary = "删除用户", parameters = {@Parameter(name = "id", description = "用户id")})
@GetMapping("/delUser")
public MessageResponse delUser(@RequestParam("id") Integer id, Authentication authentication) {
if (id.equals(((User) authentication.getPrincipal()).getId())) {
return new MessageResponse("不能删除自己!", 403);
}
return this.userService.delUser(id);
}
@Operation(summary = "获取用户", parameters = {@Parameter(name = "page", description = "页数"), @Parameter(name = "num", description = "每页数量")})
@GetMapping("/getUser")
public PageableResponse<AccountVo> getUser(@RequestParam("page") Long page, @RequestParam("num") Long num, Authentication authentication) {
return this.userService.getUser(page, num, authentication);
}
@Operation(summary = "获取当前用户信息")
@GetMapping("/getUserInfo")
public DataResponse<User> getUserInfo(Authentication authentication) {
return new DataResponse<>((User) authentication.getPrincipal());
}
}

View File

@ -0,0 +1,23 @@
package cn.wzpmc.commerce.entities;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
import java.util.List;
@Data
public class Group {
private Integer id;
private String name;
private String description;
private List<Permission> permissions;
private int createId;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createTime;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date updateTime;
}

View File

@ -0,0 +1,34 @@
package cn.wzpmc.commerce.entities;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
@EqualsAndHashCode(callSuper = true)
@AllArgsConstructor
@Data
public class MerchantUser extends User {
private Integer countDown;
private List<Order> orders;
private List<MerchantUserCommission> commissions;
public void calcOrderCommission() {
MerchantUserCommission[] array = commissions.toArray(new MerchantUserCommission[]{});
Arrays.sort(array, Comparator.comparingDouble(MerchantUserCommission::getPriceMin));
orderFor:
for (Order order : orders) {
double price = order.getPayAmt();
for (MerchantUserCommission commission : array) {
if (price >= commission.getPriceMin() && price <= commission.getPriceMax()) {
order.setCommission(price * commission.getCommission());
continue orderFor;
}
}
order.setCommission(0);
}
}
}

View File

@ -0,0 +1,21 @@
package cn.wzpmc.commerce.entities;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
@Data
public class MerchantUserCommission {
private int id;
private double priceMin;
private double priceMax;
private double commission;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createTime;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date updateTime;
}

View File

@ -1,45 +1,36 @@
package top.xinsin.pojo.vo;
package cn.wzpmc.commerce.entities;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
/**
* @author xinsin
* Created On 2023/4/24 22:21
* @version 1.0
*/
@Data
public class OrderVO {
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
public class Order {
private int id;
private String orderNo;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date orderTime;
private String orderStatus;
private String wangNo;
private String wechatNo;
private String weChatNo;
private String alipayNo;
private Double payAmt;
private Double commission;
private double payAmt;
private int storeId;
private double commission;
private String alipayName;
private String rpName;
private String rpWechatName;
private String rpWeChatName;
private String remark;
private String phoneNumber;
private String cardNo;
private Integer flag;
private int flag;
private String flagRemark;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date payTime;
private String address;
private Integer shopId;
private String sku;
private String storeName;
}

View File

@ -0,0 +1,30 @@
package cn.wzpmc.commerce.entities;
import com.alibaba.fastjson2.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.core.GrantedAuthority;
import java.util.Date;
@Data
public class Permission implements GrantedAuthority {
private Integer id;
private String name;
private String code;
private String description;
private int createId;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createTime;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date updateTime;
@Override
@JSONField(serialize = false)
public String getAuthority() {
return this.code;
}
}

View File

@ -0,0 +1,51 @@
package cn.wzpmc.commerce.entities;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
import java.util.Date;
@Data
public class User implements UserDetails {
private Integer id;
private String username;
private String email;
private String relName;
private String password;
private Group group;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createTime;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date updateTime;
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return this.group.getPermissions();
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}

View File

@ -0,0 +1,37 @@
package cn.wzpmc.commerce.entities.vo;
import cn.wzpmc.commerce.utils.ServiceUtils;
import com.baomidou.mybatisplus.annotation.*;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
@Data
@TableName("account")
public class AccountVo {
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
@ServiceUtils.Updatable
private String username;
@ServiceUtils.Updatable
private String email;
@ServiceUtils.Updatable
@TableField("rel_name")
private String relName;
private String password;
@ServiceUtils.Updatable
@TableField("group_id")
private Integer groupId;
@TableField("create_time")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createTime;
@TableField(value = "update_time", update = "now()")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date updateTime;
@TableLogic
private boolean del;
}

View File

@ -0,0 +1,33 @@
package cn.wzpmc.commerce.entities.vo;
import com.baomidou.mybatisplus.annotation.*;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
@Data
@TableName("blacklist")
public class BlackListVo {
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
@TableField("store_id")
private Integer storeId;
@TableField("wang_no")
private String wangNo;
@TableField("wechat_no")
private String weChatNo;
@TableField("create_id")
private Integer createId;
@TableField("create_time")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createTime;
@TableField(value = "update_time", update = "now()")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date updateTime;
@TableLogic
private boolean del;
}

View File

@ -1,51 +1,41 @@
package top.xinsin.pojo;
package cn.wzpmc.commerce.entities.vo;
import cn.wzpmc.commerce.utils.ServiceUtils;
import com.baomidou.mybatisplus.annotation.*;
import java.io.Serial;
import java.io.Serializable;
import java.sql.Blob;
import java.util.Date;
import java.time.LocalDateTime;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;
/**
* <p>
*
* </p>
*
* @author xinsin
* @since 2023-04-24
*/
import java.util.Date;
@Data
@TableName("commission")
public class Commission implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
public class CommissionVo {
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
@TableField("price_min")
private Double priceMin;
@TableField("price_max")
private Double priceMax;
@TableField("commission")
private Double commission;
@ServiceUtils.Updatable
@TableField("range_min")
private Double range_min;
@ServiceUtils.Updatable
@TableField("range_max")
private Double range_max;
@ServiceUtils.Updatable
private Double base;
@ServiceUtils.Updatable
private Double extra;
@ServiceUtils.Updatable
@TableField("store_id")
private Integer storeId;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@TableField("create_id")
private Integer createId;
@TableField("create_time")
private Date createTime;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@TableField("update_time")
private java.util.Date updateTime;
@TableField("del")
private Date createTime;
@TableField(value = "update_time", update = "now()")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date updateTime;
@TableLogic
private Integer del;
@TableField("status")
private Boolean status;
private boolean del;
}

View File

@ -1,30 +1,21 @@
package top.xinsin.pojo;
package cn.wzpmc.commerce.entities.vo;
import cn.wzpmc.commerce.utils.ServiceUtils;
import com.baomidou.mybatisplus.annotation.*;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;
import java.io.Serial;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.Date;
/**
* @author xinsin
* Created On 2023/4/24 21:11
* @version 1.0
*/
@Data
@TableName("auth_roles")
public class AuthRoles implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
@TableName("group")
public class GroupVo {
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
@TableField("role_name")
private String roleName;
@TableField("description")
@ServiceUtils.Updatable
private String name;
@ServiceUtils.Updatable
private String description;
@TableField("create_id")
private Integer createId;
@ -32,13 +23,10 @@ public class AuthRoles implements Serializable {
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createTime;
@TableField("update_time")
@TableField(value = "update_time", update = "now()")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date updateTime;
@TableField("status")
private Boolean status;
@TableField("del")
@TableLogic
private Boolean del;
private boolean del;
}

View File

@ -0,0 +1,51 @@
package cn.wzpmc.commerce.entities.vo;
import cn.wzpmc.commerce.enums.OrderStatus;
import com.baomidou.mybatisplus.annotation.*;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
@Data
@TableName("order")
public class OrderVo {
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
private String no;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date time;
private OrderStatus status;
@TableField("wang_no")
private String wangNo;
@TableField("wechat_no")
private String weChatNo;
@TableField("alipay_no")
private String alipayNo;
@TableField("alipay_name")
private String alipayName;
private String phone;
@TableField("card_no")
private String cardNo;
private Double payment;
@TableField("pay_time")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date payTime;
@TableField("head_name")
private String headName;
@TableField("head_wechat_name")
private String headWeChatName;
@TableField("store_id")
private Integer storeId;
private String remark;
private Integer flag;
@TableField("flag_remark")
private String flagRemark;
private String address;
private String sku;
@TableLogic
private boolean del;
}

View File

@ -1,46 +1,36 @@
package top.xinsin.pojo;
package cn.wzpmc.commerce.entities.vo;
import cn.wzpmc.commerce.utils.ServiceUtils;
import com.baomidou.mybatisplus.annotation.*;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;
import java.io.Serial;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.Date;
/**
* @author xinsin
* Created On 2023/4/24 21:11
* @version 1.0
*/
@Data
@TableName("auth_permissions")
public class AuthPermissions implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
@TableName("permissions")
public class PermissionVo {
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
@TableField("permission_name")
private String permissionName;
@TableField("permission_code")
private String permissionCode;
@TableField("description")
@ServiceUtils.Updatable
private String name;
@ServiceUtils.Updatable
private String code;
@ServiceUtils.Updatable
private String description;
@TableField("group_id")
private Integer groupId;
@TableField("create_id")
private Integer createId;
@TableField("create_time")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createTime;
@TableField("update_time")
@TableField(value = "update_time", update = "now()")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date updateTime;
@TableField("status")
private Boolean status;
@TableField("del")
@TableLogic
private Boolean del;
private boolean del;
}

View File

@ -0,0 +1,36 @@
package cn.wzpmc.commerce.entities.vo;
import cn.wzpmc.commerce.utils.ServiceUtils;
import com.baomidou.mybatisplus.annotation.*;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
@Data
@TableName("store")
public class StoreVo {
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
@ServiceUtils.Updatable
private String name;
@ServiceUtils.Updatable
@TableField("category_id")
private Integer categoryId;
@ServiceUtils.Updatable
@TableField("account_id")
private Integer accountId;
@TableField("create_id")
private Integer createId;
@TableField("create_time")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createTime;
@TableField(value = "update_time", update = "now()")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date updateTime;
@TableLogic
private boolean del;
}

View File

@ -1,10 +1,6 @@
package top.xinsin.enums;
package cn.wzpmc.commerce.enums;
/**
* @author xinsin
* Created On 2023/4/22 16:40
* @version 1.0
*/
@SuppressWarnings("NonAsciiCharacters")
public enum OrderStatus {
商家驳回, 已完成, 已确认等待财务审核, 提交, 新建待提交数据, 财务审核已通过, 财务驳回
}

View File

@ -0,0 +1,9 @@
package cn.wzpmc.commerce.mappers;
import cn.wzpmc.commerce.entities.vo.AccountVo;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface AccountMapper extends BaseMapper<AccountVo> {
}

View File

@ -0,0 +1,9 @@
package cn.wzpmc.commerce.mappers;
import cn.wzpmc.commerce.entities.vo.BlackListVo;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface BlackListMapper extends BaseMapper<BlackListVo> {
}

View File

@ -0,0 +1,9 @@
package cn.wzpmc.commerce.mappers;
import cn.wzpmc.commerce.entities.vo.CommissionVo;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface CommissionMapper extends BaseMapper<CommissionVo> {
}

View File

@ -0,0 +1,9 @@
package cn.wzpmc.commerce.mappers;
import cn.wzpmc.commerce.entities.vo.GroupVo;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface GroupMapper extends BaseMapper<GroupVo> {
}

View File

@ -0,0 +1,9 @@
package cn.wzpmc.commerce.mappers;
import cn.wzpmc.commerce.entities.vo.OrderVo;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface OrderMapper extends BaseMapper<OrderVo> {
}

View File

@ -0,0 +1,9 @@
package cn.wzpmc.commerce.mappers;
import cn.wzpmc.commerce.entities.vo.PermissionVo;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface PermissionsMapper extends BaseMapper<PermissionVo> {
}

View File

@ -0,0 +1,9 @@
package cn.wzpmc.commerce.mappers;
import cn.wzpmc.commerce.entities.vo.StoreVo;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface StoreMapper extends BaseMapper<StoreVo> {
}

View File

@ -0,0 +1,10 @@
package cn.wzpmc.commerce.services;
import cn.wzpmc.commerce.entities.vo.PermissionVo;
import cn.wzpmc.commerce.mappers.PermissionsMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
@Service
public class PermissionService extends ServiceImpl<PermissionsMapper, PermissionVo> {
}

View File

@ -0,0 +1,153 @@
package cn.wzpmc.commerce.services;
import cn.wzpmc.commerce.entities.Group;
import cn.wzpmc.commerce.entities.Permission;
import cn.wzpmc.commerce.entities.User;
import cn.wzpmc.commerce.entities.vo.AccountVo;
import cn.wzpmc.commerce.entities.vo.GroupVo;
import cn.wzpmc.commerce.entities.vo.PermissionVo;
import cn.wzpmc.commerce.mappers.AccountMapper;
import cn.wzpmc.commerce.mappers.GroupMapper;
import cn.wzpmc.commerce.mappers.PermissionsMapper;
import cn.wzpmc.commerce.utils.EntitiesUtils;
import cn.wzpmc.commerce.utils.MessageResponse;
import cn.wzpmc.commerce.utils.PageableResponse;
import cn.wzpmc.commerce.utils.ServiceUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Service
public class UserService extends ServiceImpl<AccountMapper, AccountVo> implements UserDetailsService {
private final AccountMapper accountMapper;
private final PermissionsMapper permissionsMapper;
private final GroupMapper groupMapper;
private final PasswordEncoder encoder;
private final Map<Integer, SecurityContext> userContexts = new HashMap<>();
@Autowired
public UserService(AccountMapper accountMapper, PermissionsMapper permissionsMapper, GroupMapper rolesMapper, PasswordEncoder encoder) {
this.accountMapper = accountMapper;
this.permissionsMapper = permissionsMapper;
this.groupMapper = rolesMapper;
this.encoder = encoder;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
SecurityContext context = SecurityContextHolder.getContext();
User userByName = getUserByName(username);
userContexts.put(userByName.getId(), context);
return userByName;
}
public User addUser(AccountVo accountVo) {
try {
this.loadUserByUsername(accountVo.getUsername());
} catch (UsernameNotFoundException e) {
accountVo.setPassword(this.encoder.encode(accountVo.getPassword()));
accountVo.setCreateTime(new Date());
this.accountMapper.insert(accountVo);
return this.getUserByName(accountVo.getUsername());
}
return null;
}
private User getUserByName(String username) throws UsernameNotFoundException {
AccountVo accountVo = this.accountMapper.selectOne(new QueryWrapper<AccountVo>()
.eq("username", username)
);
if (accountVo == null) {
throw new UsernameNotFoundException("用户不存在");
}
return genUserFromAuthAccount(accountVo);
}
private User getUserById(int id) throws UsernameNotFoundException {
AccountVo accountVo = this.accountMapper.selectById(id);
if (accountVo == null) {
throw new UsernameNotFoundException("用户不存在");
}
return genUserFromAuthAccount(accountVo);
}
private User genUserFromAuthAccount(AccountVo accountVo) {
User user = EntitiesUtils.copyField(accountVo, new User());
GroupVo groupVo = groupMapper.selectById(accountVo.getGroupId());
Group group = EntitiesUtils.copyField(groupVo, new Group());
group.setPermissions(permissionsMapper.selectList(
new QueryWrapper<PermissionVo>().eq("group_id", groupVo.getId())
).stream().map(e -> EntitiesUtils.copyField(e, new Permission())).toList());
user.setGroup(group);
return user;
}
public MessageResponse changeAccount(AccountVo authAccountVo) {
String username = authAccountVo.getUsername();
Integer id = authAccountVo.getId();
try {
getUserByName(username);
} catch (UsernameNotFoundException e) {
if (!ServiceUtils.update(this, authAccountVo)) {
return new MessageResponse("修改失败!", 403);
}
this.updateUserAuthentication(id);
return new MessageResponse("修改成功");
}
return new MessageResponse("修改失败,用户名已存在", 403);
}
public MessageResponse changePassword(Integer userId, String oldPassword, String newPassword) {
oldPassword = this.encoder.encode(oldPassword);
newPassword = this.encoder.encode(newPassword);
if (this.accountMapper.selectOne(new QueryWrapper<AccountVo>().eq("id", userId).eq("password", oldPassword)) == null) {
return new MessageResponse("原密码错误", 403);
}
AccountVo accountVo = new AccountVo();
accountVo.setId(userId);
accountVo.setPassword(newPassword);
this.accountMapper.updateById(accountVo);
return new MessageResponse("修改成功");
}
public MessageResponse delUser(Integer id) {
if (this.accountMapper.deleteById(id) == 0) {
return new MessageResponse("未找到用户", 404);
}
return new MessageResponse("修改成功");
}
public PageableResponse<AccountVo> getUser(Long page, Long num, Authentication authentication) {
User user = (User) authentication.getPrincipal();
Integer uid = user.getId();
Integer id = user.getGroup().getId();
QueryWrapper<AccountVo> queryWrapper = new QueryWrapper<AccountVo>().gt("role_id", id).or().eq("id", uid);
Page<AccountVo> users = this.accountMapper.selectPage(new Page<>(page, num), queryWrapper);
Long l = this.accountMapper.selectCount(queryWrapper);
return new PageableResponse<>(users.getRecords(), l);
}
public void updateUserAuthentication(int id) {
if (!userContexts.containsKey(id)) {
return;
}
User userById = getUserById(id);
Authentication newAuth = new UsernamePasswordAuthenticationToken(userById, null, userById.getAuthorities());
SecurityContext securityContext = userContexts.get(id);
securityContext.setAuthentication(newAuth);
}
}

View File

@ -0,0 +1,31 @@
package cn.wzpmc.commerce.utils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
@EqualsAndHashCode(callSuper = true)
@Data
@AllArgsConstructor
public class DataResponse<T> extends MessageResponse {
private T data;
public DataResponse(T data, int code, String message) {
super(message, code);
this.data = data;
}
public DataResponse(T data, String message) {
super(message);
this.data = data;
}
public DataResponse() {
super();
this.data = null;
}
public String toString() {
return super.toString();
}
}

View File

@ -0,0 +1,103 @@
package cn.wzpmc.commerce.utils;
import cn.wzpmc.commerce.entities.User;
import lombok.NoArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.context.SecurityContextHolder;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.HashMap;
import java.util.Map;
@Slf4j
public class EntitiesUtils {
@SneakyThrows
public static <F, T> T copyField(F from, T to, NameParser parser) {
Class<?> fromClass = from.getClass();
Class<?> toClass = to.getClass();
Method[] fromMethods = fromClass.getDeclaredMethods();
Method[] toMethods = toClass.getDeclaredMethods();
Map<String, Method> getters = new HashMap<>();
for (Method fromMethod : fromMethods) {
String methodName = fromMethod.getName();
if ((methodName.startsWith("get") || methodName.startsWith("is")) && fromMethod.getParameters().length == 0) {
getters.put(parser.getterParse(methodName), fromMethod);
}
}
for (Method toMethod : toMethods) {
String methodName = toMethod.getName();
Parameter[] parameters = toMethod.getParameters();
if (methodName.startsWith("set") && parameters.length == 1) {
String fieldName = parser.setterParse(methodName);
if (getters.containsKey(fieldName)) {
Method getter = getters.get(fieldName);
Class<?> returnType = getter.getReturnType();
if (!parameters[0].getType().equals(returnType)) {
continue;
}
Object fieldValue = getter.invoke(from);
toMethod.invoke(to, fieldValue);
}
}
}
return to;
}
public static <F, T> T copyField(F from, T to) {
return copyField(from, to, new NameParser());
}
@SneakyThrows
public static <T> void addCreateId(T obj) {
Class<?> aClass = obj.getClass();
int userId = ((User) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId();
for (Field declaredField : aClass.getDeclaredFields()) {
declaredField.setAccessible(true);
if (declaredField.getName().equals("create_id")) {
declaredField.set(obj, userId);
return;
}
}
log.warn("在类{}中未找到create_id", aClass);
}
@NoArgsConstructor
public static class NameParser {
private final HashMap<String, String> getterParsers = new HashMap<>();
private final HashMap<String, String> setterParsers = new HashMap<>();
public NameParser addParser(String from, String to) {
this.getterParsers.put(from, to);
this.setterParsers.put(from, to);
return this;
}
public NameParser addGetter(String from, String to) {
this.getterParsers.put(from, to);
return this;
}
public NameParser addSetter(String from, String to) {
this.setterParsers.put(from, to);
return this;
}
private String getterParse(String from) {
if (from.startsWith("get")) {
from = from.replaceFirst("get", "");
} else {
from = from.replaceFirst("is", "");
}
return getterParsers.getOrDefault(from, from);
}
private String setterParse(String from) {
from = from.replaceFirst("set", "");
return setterParsers.getOrDefault(from, from);
}
}
}

View File

@ -0,0 +1,42 @@
package cn.wzpmc.commerce.utils;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.SneakyThrows;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Date;
@Data
@AllArgsConstructor
public class MessageResponse {
private String msg;
private int code;
private long timestamp;
public MessageResponse() {
this.code = 200;
this.msg = "成功";
this.timestamp = new Date().getTime();
}
public MessageResponse(String msg) {
this(msg, 200);
}
public MessageResponse(String msg, int code) {
this(msg, code, new Date().getTime());
}
public String toString() {
return JSONObject.from(this).toJSONString(JSONWriter.Feature.IgnoreNonFieldGetter);
}
@SneakyThrows
public void copyToStream(OutputStream stream) {
stream.write(this.toString().getBytes(StandardCharsets.UTF_8));
}
}

View File

@ -0,0 +1,35 @@
package cn.wzpmc.commerce.utils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.List;
@EqualsAndHashCode(callSuper = true)
@Data
public class PageableResponse<T> extends DataResponse<PageableResponse.PageableData<T>> {
public PageableResponse(List<T> data, long total) {
this(new PageableData<>(data, total));
}
public PageableResponse(PageableData<T> data) {
super(data);
}
public static <T> PageableResponse<T> of(Page<T> pageResult) {
return new PageableResponse<>(PageableData.of(pageResult));
}
@Data
@AllArgsConstructor
public static class PageableData<T> {
private List<T> info;
private long total;
public static <T> PageableData<T> of(Page<T> pageResult) {
return new PageableData<>(pageResult.getRecords(), pageResult.getTotal());
}
}
}

View File

@ -0,0 +1,95 @@
package cn.wzpmc.commerce.utils;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.util.Objects;
@Slf4j
public class ServiceUtils {
@SneakyThrows
public static <T> boolean update(IService<T> service, T entities) {
Class<T> entityClass = service.getEntityClass();
Field[] declaredFields = entityClass.getDeclaredFields();
UpdateWrapper<T> updateWrapper = new UpdateWrapper<>();
Object id = null;
String idName = "id";
for (Field field : declaredFields) {
field.setAccessible(true);
String fieldName = field.getName();
TableId tableId = field.getDeclaredAnnotation(TableId.class);
if (Objects.nonNull(tableId) || fieldName.equals("id")) {
id = field.get(entities);
if (Objects.nonNull(tableId)) {
idName = tableId.value();
}
}
Updatable declaredAnnotation = field.getDeclaredAnnotation(Updatable.class);
if (declaredAnnotation != null) {
TableField tableField = field.getDeclaredAnnotation(TableField.class);
String name;
if (tableField == null) {
name = fieldName;
} else {
name = tableField.value();
}
Object value = field.get(entities);
updateWrapper.set(Objects.nonNull(value), name, value);
}
}
if (id == null) {
log.warn("类{}未找到id", entityClass);
return false;
}
updateWrapper.eq(idName, id);
return service.update(updateWrapper);
}
public static <T> boolean updateStatus(IService<T> service, int id, boolean newStatus) {
Class<T> entityClass = service.getEntityClass();
Field[] declaredFields = entityClass.getDeclaredFields();
UpdateWrapper<T> updateWrapper = new UpdateWrapper<>();
boolean has = false;
for (Field field : declaredFields) {
field.setAccessible(true);
String fieldName = field.getName();
Status declaredAnnotation = field.getDeclaredAnnotation(Status.class);
if (declaredAnnotation != null) {
TableField tableField = field.getDeclaredAnnotation(TableField.class);
String name;
if (tableField == null) {
name = fieldName;
} else {
name = tableField.value();
}
has = true;
updateWrapper.set(name, newStatus);
}
}
if (!has) {
log.warn("类{}未找到status注解", entityClass);
return false;
}
updateWrapper.eq("id", id);
return service.update(updateWrapper);
}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.ANNOTATION_TYPE})
public @interface Updatable {
}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.ANNOTATION_TYPE})
public @interface Status {
}
}

View File

@ -1,17 +0,0 @@
package top.xinsin;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@MapperScan("top.xinsin.mapper")
@EnableScheduling
@Slf4j
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class,args);
}
}

View File

@ -1,29 +0,0 @@
package top.xinsin.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import top.xinsin.interceptor.AuthorizeInterceptor;
import top.xinsin.interceptor.GlobalWebInterceptor;
/**
* @author xinsin
* Created On 2023/4/3 15:55
* @version 1.0
*/
@Configuration
public class GlobalWebMvcConfiguration implements WebMvcConfigurer {
@Autowired
private AuthorizeInterceptor interceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(interceptor)
.addPathPatterns("/**")
.excludePathPatterns("/api/auth/**");
}
}

View File

@ -1,47 +0,0 @@
package top.xinsin.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import top.xinsin.util.R;
import java.util.Objects;
@Slf4j
@ControllerAdvice
public class InterceptResponseConfiguration implements ResponseBodyAdvice<Object> {
@Override
public boolean supports(MethodParameter returnType, Class converterType) {
return true;
}
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
// 只有返回数据为自定义返回格式,才对数据进行处理
if (body instanceof R<?> r){
String controllerMethodName = Objects.requireNonNull(returnType.getMethod()).getName();
String controllerClassName = returnType.getDeclaringClass().getSimpleName();
String controllerClassURlPath = returnType.getDeclaringClass().getAnnotation(RequestMapping.class).value()[0];
RequestMapping annotation = returnType.getMethod().getAnnotation(RequestMapping.class);
String controllerUrlPath = annotation.path()[0];
String controllerUrlMethod = annotation.method()[0].name();
log.info("[全局响应体后处理器]-请求类:{}-请求方法:{}-请求地址:{}{}-请求方法:{}-响应状态码:{}-响应数据:{}",
controllerClassName,
controllerMethodName,
controllerClassURlPath,
controllerUrlPath,
controllerUrlMethod,
r.getStatus(),
r.getData());
response.setStatusCode(HttpStatusCode.valueOf(r.getStatus()));
}
return body;
}
}

View File

@ -1,24 +0,0 @@
package top.xinsin.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MybatisPlusConfiguration {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
paginationInnerInterceptor.setOptimizeJoin(true);
paginationInnerInterceptor.setDbType(DbType.MYSQL);
paginationInnerInterceptor.setOverflow(true);
interceptor.addInnerInterceptor(paginationInnerInterceptor);
OptimisticLockerInnerInterceptor optimisticLockerInnerInterceptor = new OptimisticLockerInnerInterceptor();
interceptor.addInnerInterceptor(optimisticLockerInnerInterceptor);
return interceptor;
}
}

View File

@ -1,116 +0,0 @@
package top.xinsin.config;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import top.xinsin.service.AccountService;
import top.xinsin.util.HttpCodes;
import top.xinsin.util.R;
import javax.sql.DataSource;
import java.io.IOException;
@Configuration
@EnableWebSecurity
public class SecurityConfiguration {
@Resource
AccountService authorizeService;
@Autowired
DataSource dataSource;
@Bean
public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
return httpSecurity
.authorizeHttpRequests()
.requestMatchers("/api/auth/**")
.permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginProcessingUrl("/api/auth/login")
.successHandler(this::onsuccessLoginHandler)
.failureHandler(this::onFailureLoginHandler)
.and()
.logout()
.logoutUrl("/api/auth/logout")
.logoutSuccessHandler(this::onsuccessLoginHandler)
.and()
.csrf()
.disable()
.cors()
.configurationSource(this.corsConfigurationSource())
.and()
.exceptionHandling()
.authenticationEntryPoint(this::onFailureLoginHandler)
.and()
.build();
}
@Bean
public AuthenticationManager authenticationManager(HttpSecurity security) throws Exception {
return security
.getSharedObject(AuthenticationManagerBuilder.class)
.userDetailsService(authorizeService)
.and()
.build();
}
@Bean
public BCryptPasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
private CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration cors = new CorsConfiguration();
cors.addAllowedOriginPattern("*");
cors.setAllowCredentials(true);
cors.addAllowedHeader("*");
cors.addAllowedMethod("*");
cors.addExposedHeader("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", cors);
return source;
}
private void onsuccessLoginHandler(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException {
httpServletResponse.setCharacterEncoding("utf-8");
httpServletResponse.setHeader("Content-Type","application/json; charset=UTF-8");
if(httpServletRequest.getRequestURI().endsWith("/login")) {
JSONObject jsonObject = new JSONObject();
authentication.getAuthorities().forEach(e -> {
String authority = e.getAuthority();
if (authority.startsWith("ROLE_id=")){
jsonObject.fluentPut("id",authority.replace("ROLE_id=", ""));
}
});
jsonObject.fluentPut("message","登陆成功");
httpServletResponse.setStatus(HttpCodes.HTTP_CODES200.getCode());
httpServletResponse.getWriter().write(JSON.toJSONString(R.success(jsonObject)));
} else if(httpServletRequest.getRequestURI().endsWith("/logout")) {
httpServletResponse.setStatus(HttpCodes.HTTP_CODES200.getCode());
httpServletResponse.getWriter().write(JSON.toJSONString(R.success("退出登录成功")));
}
}
private void onFailureLoginHandler(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse,AuthenticationException authentication) throws IOException {
httpServletResponse.setCharacterEncoding("utf-8");
httpServletResponse.setHeader("Content-Type","application/json; charset=UTF-8");
httpServletResponse.setStatus(HttpCodes.HTTP_CODES555.getCode());
httpServletResponse.getWriter().write(JSONObject.toJSONString(R.failed(HttpCodes.ACCESS_DENIED,"登录时出现了错误")));
}
}

View File

@ -1,22 +0,0 @@
package top.xinsin.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
import top.xinsin.controller.WebSocketController;
import top.xinsin.service.WebSocketService;
@Configuration
@EnableWebSocket
public class WebsocketConfiguration {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
@Autowired
public void socketUserService(WebSocketService webSocketService){
WebSocketController.webSocketService= webSocketService;
}
}

View File

@ -1,79 +0,0 @@
package top.xinsin.controller;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import top.xinsin.pojo.AuthAccount;
import top.xinsin.pojo.vo.AccountAndStoreAdmin;
import top.xinsin.service.AccountService;
import top.xinsin.util.R;
import java.util.Collection;
import java.util.stream.Stream;
/**
* @author xinsin
* Created On 2023/4/24 21:05
* @version 1.0
*/
@RestController
@RequestMapping("/account")
public class AccountController {
@Autowired
private AccountService accountService;
@RequestMapping(path = "/changeAccount", method = RequestMethod.POST)
public R<String> changeAccount(@RequestBody AuthAccount authAccount) {return this.accountService.changeAccount(authAccount);}
@RequestMapping(path = "/changeStatus", method = RequestMethod.GET)
public R<String> changeStatus(@RequestParam("userId") Integer userId, @RequestParam("status") Boolean status) {return this.accountService.changeStatus(userId, status);}
@RequestMapping(path = "/changePassword", method = RequestMethod.POST)
public R<String> changePassword(@RequestParam("userId") Integer userId, @RequestParam("oldPassword") String oldPassword, @RequestParam("newPassword") String newPassword) {return this.accountService.changePassword(userId, oldPassword, newPassword);}
@RequestMapping(path = "/delUser", method = RequestMethod.GET)
public R<String> delUser(@RequestParam("id") Integer id) {return this.accountService.delUser(id);}
@RequestMapping(path = "/getUser", method = RequestMethod.GET)
public R<JSONObject> getUser(@RequestParam("page") Integer page, @RequestParam("num") Integer num) {return this.accountService.getUser(page, num);}
@RequestMapping(path = "/getUserInfo",method = RequestMethod.GET)
public R<JSONObject> getUserInfo(){
Collection<GrantedAuthority> authorities = ((User) SecurityContextHolder
.getContext()
.getAuthentication()
.getPrincipal())
.getAuthorities();
R<JSONObject> userInfo = accountService.getUserInfo(Integer.parseInt(authorities.stream().filter(e -> e.getAuthority().startsWith("ROLE_roleId=")).findFirst().get().getAuthority().replace("ROLE_roleId=", "")));
userInfo.getData()
.fluentPut("id",authorities.stream().filter(e -> e.getAuthority().startsWith("ROLE_id=")).findFirst().get().getAuthority().replace("ROLE_id=",""))
.fluentPut("roleId",authorities.stream().filter(e -> e.getAuthority().startsWith("ROLE_roleId=")).findFirst().get().getAuthority().replace("ROLE_roleId=", ""))
.fluentPut("auth",authorities.stream().filter(e -> e.getAuthority().startsWith("ROLE_auth=")).findFirst().get().getAuthority().replace("ROLE_auth=",""));
return userInfo;
}
@RequestMapping(path = "/addStoreAdmin",method = RequestMethod.POST)
public R<JSONObject> addStoreAdmin(@RequestBody AccountAndStoreAdmin accountAndStoreAdmin){
Collection<GrantedAuthority> authorities = ((User) SecurityContextHolder
.getContext()
.getAuthentication()
.getPrincipal())
.getAuthorities();
int id = Integer.parseInt(authorities.stream().filter(e -> e.getAuthority().startsWith("ROLE_id=")).findFirst().get().getAuthority().replace("ROLE_id=", ""));
accountAndStoreAdmin.setCreateId(id);
return accountService.addStoreAdmin(accountAndStoreAdmin);
}
/* @RequestMapping(path = "/debug",method = RequestMethod.GET)
public void debug(){accountService.debug();}
@RequestMapping(path = "/debugs",method = RequestMethod.GET)
public long debugs(){return accountService.debugs();}*/
}

View File

@ -1,38 +0,0 @@
package top.xinsin.controller;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.xinsin.pojo.AuthPermissions;
import top.xinsin.pojo.Commission;
import top.xinsin.service.AuthPermissionsService;
import top.xinsin.service.AuthRolesService;
import top.xinsin.util.R;
import java.util.List;
/**
* @author xinsin
* Created On 2023/4/24 21:07
* @version 1.0
*/
@RestController
@RequestMapping("/authPermissions")
public class AuthPermissionsController {
@Autowired
private AuthPermissionsService authPermissionsService;
@RequestMapping(path = "/addAuthPermissions",method = RequestMethod.POST)
public R<Boolean> addAuthPermissions(@RequestBody AuthPermissions authPermissions){return authPermissionsService.addAuthPermissions(authPermissions);}
@RequestMapping(path = "/changeAuthPermissions",method = RequestMethod.POST)
public R<Boolean> changeAuthPermissions(@RequestBody AuthPermissions authPermissions){return authPermissionsService.changeAuthPermissions(authPermissions);}
@RequestMapping(path = "/delAuthPermissions",method = RequestMethod.GET)
public R<Boolean> delAuthPermissions(@RequestParam("id")Integer id){return authPermissionsService.delAuthPermissions(id);}
@RequestMapping(path = "/getAuthPermissions",method = RequestMethod.GET)
public R<JSONObject> getAuthPermissions(@RequestParam("page")Integer page, @RequestParam("num")Integer num){return authPermissionsService.getAuthPermissions(page,num);}
@RequestMapping(path = "/changeAuthPermissionsStats", method = RequestMethod.GET)
public R<String> changeAuthPermissionsStats(@RequestParam("authPermissionId") Integer authPermissionId, @RequestParam("status") Boolean status) {return authPermissionsService.changeAuthPermissionsStats(authPermissionId, status);}
@RequestMapping(path = "/getAuthPermissionsId",method = RequestMethod.GET)
public R<List<JSONObject>> getAuthPermissionsId(){return authPermissionsService.getAuthPermissionsId();}
}

View File

@ -1,40 +0,0 @@
package top.xinsin.controller;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.xinsin.pojo.AuthPermissions;
import top.xinsin.pojo.AuthRoles;
import top.xinsin.service.AuthPermissionsService;
import top.xinsin.service.AuthRolesService;
import top.xinsin.util.R;
import java.util.List;
/**
* @author xinsin
* Created On 2023/4/24 21:07
* @version 1.0
*/
@RestController
@RequestMapping("/authRoles")
public class AuthRolesController {
@Autowired
private AuthRolesService authPermissionsService;
@RequestMapping(path = "/addAuthRoles",method = RequestMethod.POST)
public R<Boolean> addAuthRoles(@RequestBody AuthRoles authPermissions){return authPermissionsService.addAuthRoles(authPermissions);}
@RequestMapping(path = "/changeAuthRoles",method = RequestMethod.POST)
public R<Boolean> changeAuthRoles(@RequestBody AuthRoles authPermissions){return authPermissionsService.changeAuthRoles(authPermissions);}
@RequestMapping(path = "/delAuthRoles",method = RequestMethod.GET)
public R<Boolean> delAuthRoles(@RequestParam("id")Integer id){return authPermissionsService.delAuthRoles(id);}
@RequestMapping(path = "/getAuthRoles",method = RequestMethod.GET)
public R<JSONObject> getAuthRoles(@RequestParam("page")Integer page, @RequestParam("num")Integer num){return authPermissionsService.getAuthRoles(page,num);}
@RequestMapping(path = "/changeAuthRolesStats", method = RequestMethod.GET)
public R<String> changeAuthRolesStats(@RequestParam("authRolesId") Integer authPermissionId, @RequestParam("status") Boolean status) {return authPermissionsService.changeAuthRolesStats(authPermissionId, status);}
@RequestMapping(path = "/getAuthRolesId",method = RequestMethod.GET)
public R<List<JSONObject>> getAuthRolesId(){return authPermissionsService.getAuthRolesId();}
@RequestMapping(path = "/getAuthPermissionId",method = RequestMethod.GET)
public R<List<JSONObject>> getAuthPermissionId(@RequestParam("roleId") Integer roleId){return authPermissionsService.getAuthPermissionId(roleId);}
}

View File

@ -1,35 +0,0 @@
package top.xinsin.controller;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.xinsin.pojo.AuthPermissions;
import top.xinsin.pojo.AuthRolesPermissions;
import top.xinsin.service.AuthRolesPermissionsService;
import top.xinsin.util.R;
import java.util.List;
/**
* @author xinsin
* Created On 2023/4/29 21:05
* @version 1.0
*/
@RestController
@RequestMapping("/authRolesPermission")
public class AuthRolesPermissionController {
@Autowired
private AuthRolesPermissionsService authRolesPermissionsService;
@RequestMapping(path = "/addAuthRolesPermissions",method = RequestMethod.POST)
public R<Boolean> addAuthRolesPermissions(@RequestBody AuthRolesPermissions authPermissions){return authRolesPermissionsService.addAuthRolesPermissions(authPermissions);}
@RequestMapping(path = "/changeAuthRolesPermissions",method = RequestMethod.POST)
public R<Boolean> changeAuthRolesPermissions(@RequestBody AuthRolesPermissions authPermissions){return authRolesPermissionsService.changeAuthRolesPermissions(authPermissions);}
@RequestMapping(path = "/delAuthRolesPermissions",method = RequestMethod.GET)
public R<Boolean> delAuthRolesPermissions(@RequestParam("roleId")Integer roleId,@RequestParam("permissionId")Integer permissionId){return authRolesPermissionsService.delAuthRolesPermissions(roleId,permissionId);}
@RequestMapping(path = "/getAuthRolesPermissions",method = RequestMethod.GET)
public R<JSONObject> getAuthRolesPermissions(@RequestParam("page")Integer page, @RequestParam("num")Integer num){return authRolesPermissionsService.getAuthRolesPermissions(page,num);}
@RequestMapping(path = "/changeAuthRolesPermissionsStats", method = RequestMethod.GET)
public R<String> changeAuthRolesPermissionsStats(@RequestParam("authRolesPermissionsId") Integer authPermissionId, @RequestParam("status") Boolean status) {return authRolesPermissionsService.changeAuthRolesPermissionsStats(authPermissionId, status);}
}

View File

@ -1,36 +0,0 @@
package top.xinsin.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import top.xinsin.pojo.AuthAccount;
import top.xinsin.service.AccountService;
import top.xinsin.util.R;
/**
* @author xinsin
* Created On 2023/4/24 21:06
* @version 1.0
*/
@Validated
@RestController
@RequestMapping("/api/auth")
public class AuthorizeController {
@Autowired
private AccountService accountService;
@RequestMapping(path = "/register", method = RequestMethod.POST)
public R<String> register(@RequestParam("auth")String auth,@RequestParam("username") String username, @RequestParam("relName") String relName, @RequestParam("email") String email, @RequestParam("password") String password, @RequestParam("roleId") Integer roleId) {
AuthAccount authAccount = new AuthAccount();
authAccount.setUsername(username);
authAccount.setPassword(password);
authAccount.setRelName(relName);
authAccount.setEmail(email);
authAccount.setRoleId(roleId);
authAccount.setAuth(auth);
return this.accountService.register(authAccount);
}
}

View File

@ -1,42 +0,0 @@
package top.xinsin.controller;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.xinsin.pojo.Commission;
import top.xinsin.pojo.Store;
import top.xinsin.service.CommissionService;
import top.xinsin.util.R;
import java.util.List;
/**
* <p>
* 前端控制器
* </p>
*
* @author xinsin
* @since 2023-04-24
*/
@RestController
@RequestMapping("/commission")
public class CommissionController {
@Autowired
private CommissionService commissionService;
@RequestMapping(path = "/addCommission",method = RequestMethod.POST)
public R<Boolean> addCommission(@RequestBody Commission commission){return commissionService.addCommission(commission);}
@RequestMapping(path = "/changeCommission",method = RequestMethod.POST)
public R<Boolean> changeCommission(@RequestBody Commission commission){return commissionService.changeCommission(commission);}
@RequestMapping(path = "/delCommission",method = RequestMethod.GET)
public R<Boolean> delCommission(@RequestParam("id")Integer id){return commissionService.delCommission(id);}
@RequestMapping(path = "/getCommission",method = RequestMethod.GET)
public R<JSONObject> getCommission(@RequestParam("page")Integer page, @RequestParam("num")Integer num){return commissionService.getCommission(page,num);}
@RequestMapping(path = "/getCommissionByPrice",method = RequestMethod.GET)
public R<Double> getCommissionByPrice(@RequestParam("shopId")Integer shopId,@RequestParam("range")Double range){return commissionService.getCommissionByPrice(shopId,range);}
@RequestMapping(path = "/changeCommissionStatus", method = RequestMethod.GET)
public R<String> changeCommissionStatus(@RequestParam("commissionId") Integer commissionId, @RequestParam("status") Boolean status) {return commissionService.changeCommissionStatus(commissionId, status);}
}

View File

@ -1,53 +0,0 @@
package top.xinsin.controller;
import com.alibaba.fastjson2.JSONObject;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.xinsin.enums.OrderStatus;
import top.xinsin.enums.SearchType;
import top.xinsin.pojo.Order;
import top.xinsin.service.OrderService;
import top.xinsin.util.R;
/**
* @author xinsin
* Created On 2023/4/24 21:06
* @version 1.0
*/
@RestController
@RequestMapping("/order")
public class OrderController {
@Autowired
private OrderService orderService;
@RequestMapping(path = "/addOrder", method = RequestMethod.POST)
public R<String> addOrder(@RequestBody Order order) {return this.orderService.addOrder(order);}
@RequestMapping(path = "/getOrder", method = RequestMethod.GET)
public R<JSONObject> getOrder(@RequestParam("page") Integer page, @RequestParam("num") Integer num) {return this.orderService.getOrder(page, num);}
@RequestMapping(path = "/getOrderUserInfo", method = RequestMethod.GET)
public R<Boolean> getOrderUserInfo(@RequestParam("content") String content) {return this.orderService.getOrderUserInfo(content);}
@RequestMapping(path = "/searchUserOrder", method = RequestMethod.GET)
public R<JSONObject> searchUserOrder(@RequestParam("searchType") SearchType searchType, @RequestParam("searchContent") String searchContent, @RequestParam("batch") Boolean batch, @RequestParam("page") Integer page, @RequestParam("num") Integer num) {return this.orderService.searchUserOrder(searchType, searchContent, batch, page, num);}
@RequestMapping(path = "/addOrderFlag", method = RequestMethod.GET)
public R<String> addOrderFlag(@RequestParam("orderId") Integer orderId, @RequestParam("flagId") Integer flagId, @RequestParam("flagRemark") String flagRemark) {return this.orderService.addOrderFlag(orderId, flagId, flagRemark);}
@RequestMapping(path = "/changeOrder", method = RequestMethod.POST)
public R<String> changeOrder(@RequestBody Order order) {return this.orderService.changeOrder(order);}
@RequestMapping(path = "/delOrder", method = RequestMethod.GET)
public R<String> delOrder(@RequestParam("orderId") Integer orderId) {return this.orderService.delOrder(orderId);}
@RequestMapping(path = "/confirm", method = RequestMethod.GET)
public R<String> confirm(@RequestParam("orderStatus") OrderStatus orderStatus, @RequestParam("orderId") Integer orderId) {return this.orderService.confirm(orderStatus, orderId);}
@RequestMapping(path = "/downloadTemplate", method = RequestMethod.GET)
public void downloadTemplate(HttpServletResponse response) {this.orderService.downloadTemplate(response);}
@RequestMapping(path = "/uploadBatch", method = RequestMethod.POST)
public R<JSONObject> uploadBatch(@RequestParam("file") MultipartFile file) {return this.orderService.uploadBatch(file);}
}

View File

@ -1,41 +0,0 @@
package top.xinsin.controller;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.xinsin.pojo.Store;
import top.xinsin.service.StoreService;
import top.xinsin.util.R;
import java.util.List;
/**
* <p>
* 前端控制器
* </p>
*
* @author xinsin
* @since 2023-04-24
*/
@RestController
@RequestMapping("/store")
public class StoreController {
@Autowired
private StoreService storeService;
@RequestMapping(path = "/addStore",method = RequestMethod.POST)
public R<Boolean> addStore(@RequestBody Store store){return storeService.addStore(store);}
@RequestMapping(path = "/changeStore",method = RequestMethod.POST)
public R<Boolean> changeStore(@RequestBody Store store){return storeService.changStore(store);}
@RequestMapping(path = "/delStore",method = RequestMethod.GET)
public R<Boolean> delStore(@RequestParam("id")Integer id){return storeService.delStore(id);}
@RequestMapping(path = "/getStore",method = RequestMethod.GET)
public R<JSONObject> getStore(@RequestParam("page")Integer page, @RequestParam("num")Integer num){return storeService.getStore(page,num);}
@RequestMapping(path = "/getAllStore",method = RequestMethod.GET)
public R<List<Store>> getAllStore(){return storeService.getAllStore();}
@RequestMapping(path = "/changeStoreStatus", method = RequestMethod.GET)
public R<String> changeStoreStatus(@RequestParam("storeId") Integer storeId, @RequestParam("status") Boolean status) {return storeService.changeStoreStatus(storeId, status);}
}

View File

@ -1,33 +0,0 @@
package top.xinsin.controller;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.xinsin.service.VerifyService;
import top.xinsin.util.R;
import java.util.List;
@RestController
@RequestMapping("/verify")
public class VerifyController {
@Autowired
private VerifyService verifyService;
@RequestMapping(path = "/getRemainderTime",method = RequestMethod.GET)
public R<JSONObject> getRemainderTime(@RequestParam("id")Integer id){
return verifyService.getRemainderTime(id);
}
@RequestMapping(path = "/verify",method = RequestMethod.GET)
public R<Boolean> verify(@RequestParam("id")Integer id,@RequestParam("name")String name,@RequestParam("phone")String phone){
return verifyService.verify(id,name,phone);
}
@RequestMapping(path = "/getVerifyMessage",method = RequestMethod.GET)
public R<List<JSONObject>> getVerifyMessage(@RequestParam("createId")Integer createId){
return verifyService.getVerifyMessage(createId);
}
@RequestMapping(path = "/confirmVerify",method = RequestMethod.GET)
public R<JSONObject> confirmVerify(@RequestParam("createId") Integer createId,@RequestParam("storeId")Integer storeId,@RequestParam("status")Boolean status){
return verifyService.confirmVerify(createId,storeId,status);
}
}

View File

@ -1,85 +0,0 @@
package top.xinsin.controller;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.xinsin.service.WebSocketService;
import top.xinsin.util.R;
import java.io.IOException;
import java.net.http.WebSocket;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
@Component
@ServerEndpoint(value = "/api/auth/websocket/{userId}")
@Slf4j
public class WebSocketController {
private static ConcurrentHashMap<String, WebSocketController> webSocketMap = new ConcurrentHashMap<>();
private Session session;
private String userId;
public static WebSocketService webSocketService;
@OnOpen
public void onOpen(Session session, @PathParam("userId") String userId) {
this.session = session;
this.userId = userId;
//加入map
webSocketMap.put(userId, this);
R<JSONObject> stringR = webSocketService.addVerify(userId,this);
sendMessageByUserId(userId, stringR);
}
@OnClose
public void onClose() {
//从map中删除
webSocketMap.remove(userId);
}
@OnMessage
public void onMessage(String message, Session session) {
sendMessageByUserId(userId,webSocketService.parseMessage(userId,message,webSocketMap));
}
@OnError
public void onError(Session session, Throwable error) {
log.error("用户错误:" + this.userId + ",原因:" + error.getMessage());
error.printStackTrace();
}
/**
* 向客户端发送消息
*/
@SneakyThrows
public void sendMessage(String message) {
this.session.getBasicRemote().sendText(message);
}
/**
* 通过userId向客户端发送消息
*/
@SneakyThrows
public void sendMessageByUserId(String userId, R<?> message) {
if(webSocketMap.containsKey(userId)){
webSocketMap.get(userId).sendMessage(JSON.toJSONString(message));
}else{
log.error("用户{}不在线",userId);
}
}
@Scheduled(fixedRate = 1000)
public void verifyTime(){
List<String> expireTimes = webSocketService.getExpireTimes(webSocketMap.keys());
expireTimes.forEach(e -> {
if(webSocketMap.containsKey(e)){
webSocketMap.get(e).sendMessage(JSON.toJSONString(R.success(new JSONObject().fluentPut("info","当前登录用户已过期"))));
}
});
}
}

View File

@ -1,10 +0,0 @@
package top.xinsin.enums;
/**
* @author xinsin
* Created On 2023/4/22 16:39
* @version 1.0
*/
public enum SearchType {
WANG_ID,WECHAT_ID,ALIPAY_ID,PHONE_NUMBER
}

View File

@ -1,35 +0,0 @@
package top.xinsin.interceptor;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import top.xinsin.mapper.AccountMapper;
import top.xinsin.pojo.AuthAccount;
@Component
public class AuthorizeInterceptor implements HandlerInterceptor {
@Autowired
private AccountMapper accountMapper;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
SecurityContext context = SecurityContextHolder.getContext();
Authentication authentication = context.getAuthentication();
User user = (User)authentication.getPrincipal();
String username = user.getUsername();
AuthAccount authAccount = accountMapper.selectOne(new LambdaQueryWrapper<AuthAccount>()
.eq(AuthAccount::getUsername,username)
.or()
.eq(AuthAccount::getEmail,username)
.eq(AuthAccount::getStatus,true));
request.getSession().setAttribute("account", authAccount);
return true;
}
}

View File

@ -1,15 +0,0 @@
package top.xinsin.interceptor;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
@Slf4j
public class GlobalWebInterceptor implements HandlerInterceptor {
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
HandlerMethod handler1 = (HandlerMethod) handler;
}
}

View File

@ -1,14 +0,0 @@
package top.xinsin.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import top.xinsin.pojo.AuthAccount;
/**
* @author xinsin
* Created On 2023/4/24 21:08
* @version 1.0
*/
@Mapper
public interface AccountMapper extends BaseMapper<AuthAccount> {
}

View File

@ -1,14 +0,0 @@
package top.xinsin.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import top.xinsin.pojo.AuthPermissions;
/**
* @author xinsin
* Created On 2023/4/24 21:09
* @version 1.0
*/
@Mapper
public interface AuthPermissionsMapper extends BaseMapper<AuthPermissions> {
}

View File

@ -1,14 +0,0 @@
package top.xinsin.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import top.xinsin.pojo.AuthRoles;
/**
* @author xinsin
* Created On 2023/4/24 21:09
* @version 1.0
*/
@Mapper
public interface AuthRolesMapper extends BaseMapper<AuthRoles> {
}

View File

@ -1,14 +0,0 @@
package top.xinsin.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import top.xinsin.pojo.AuthRolesPermissions;
/**
* @author xinsin
* Created On 2023/4/29 20:28
* @version 1.0
*/
@Mapper
public interface AuthRolesPermissionsMapper extends BaseMapper<AuthRolesPermissions> {
}

View File

@ -1,18 +0,0 @@
package top.xinsin.mapper;
import top.xinsin.pojo.Commission;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* <p>
* Mapper 接口
* </p>
*
* @author xinsin
* @since 2023-04-24
*/
@Mapper
public interface CommissionMapper extends BaseMapper<Commission> {
}

View File

@ -1,19 +0,0 @@
package top.xinsin.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import top.xinsin.pojo.Order;
import top.xinsin.pojo.vo.OrderVO;
import java.util.List;
/**
* @author xinsin
* Created On 2023/4/24 21:08
* @version 1.0
*/
@Mapper
public interface OrderMapper extends BaseMapper<Order> {
// public List<OrderVO> selectAllByStoreName(Integer page,Integer num);
}

View File

@ -1,18 +0,0 @@
package top.xinsin.mapper;
import top.xinsin.pojo.Store;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* <p>
* Mapper 接口
* </p>
*
* @author xinsin
* @since 2023-04-24
*/
@Mapper
public interface StoreMapper extends BaseMapper<Store> {
}

View File

@ -1,9 +0,0 @@
package top.xinsin.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import top.xinsin.pojo.Verify;
@Mapper
public interface VerifyMapper extends BaseMapper<Verify> {
}

View File

@ -1,62 +0,0 @@
package top.xinsin.pojo;
import com.baomidou.mybatisplus.annotation.*;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import java.io.Serial;
import java.io.Serializable;
import java.util.Date;
/**
* @author xinsin
* Created On 2023/4/24 21:09
* @version 1.0
*/
@Data
@TableName("auth_account")
@NoArgsConstructor
public class AuthAccount implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
@TableField("username")
private String username;
@TableField("auth")
private String auth;
@TableField("email")
private String email;
@TableField("rel_name")
private String relName;
@TableField("password")
private String password;
@TableField("status")
private Boolean status;
@TableField("role_id")
private Integer roleId;
@TableField("create_time")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createTime;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@TableField("update_time")
private Date updateTime;
@TableField("del")
@TableLogic
private Boolean del;
public AuthAccount(String username, String auth, String email, String relName, String password, Boolean status, Integer roleId, Date createTime) {
this.username = username;
this.auth = auth;
this.email = email;
this.relName = relName;
this.password = password;
this.status = status;
this.roleId = roleId;
this.createTime = createTime;
}
}

View File

@ -1,37 +0,0 @@
package top.xinsin.pojo;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;
import java.io.Serial;
import java.io.Serializable;
import java.util.Date;
/**
* @author xinsin
* Created On 2023/4/29 14:41
* @version 1.0
*/
@Data
@TableName("auth_roles_permissions")
public class AuthRolesPermissions implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
private Integer roleId;
private Integer permissionId;
private Integer createId;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createTime;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date updateTime;
@TableLogic
private Integer del;
}

View File

@ -1,83 +0,0 @@
package top.xinsin.pojo;
import com.alibaba.excel.annotation.ExcelIgnore;
import com.alibaba.excel.annotation.ExcelIgnoreUnannotated;
import com.alibaba.excel.annotation.ExcelProperty;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.format.annotation.DateTimeFormat;
import java.io.Serial;
import java.io.Serializable;
import java.util.Date;
/**
* @author xinsin
* Created On 2023/4/24 21:10
* @version 1.0
*/
@TableName("shop_order")
@ExcelIgnoreUnannotated
@Accessors(chain = true)
@Data
public class Order implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
@ExcelIgnore
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
@TableField("order_no")
private String orderNo;
@TableField("order_time")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date orderTime;
@TableField("order_status")
private String orderStatus;
@TableField("wang_no")
private String wangNo;
@TableField("wechat_no")
private String wechatNo;
@TableField("alipay_no")
private String alipayNo;
@TableField("pay_amt")
private Double payAmt;
@TableField("store_id")
private Integer storeId;
@TableField("commission")
private Double commission;
@TableField("alipay_name")
private String alipayName;
@TableField("rp_name")
private String rpName;
@TableField("rp_wechat_name")
private String rpWechatName;
@TableField("remark")
private String remark;
@TableField("phone_number")
private String phoneNumber;
@TableField("card_no")
private String cardNo;
@TableField("flag")
private Integer flag;
@TableField("flag_remark")
private String flagRemark;
@TableField("pay_time")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date payTime;
@TableField("address")
private String address;
@TableField("shop_id")
private Integer shopId;
@TableField("sku")
private String sku;
@ExcelIgnore
@TableField(exist = false)
private String storeName;
}

View File

@ -1,67 +0,0 @@
package top.xinsin.pojo;
import com.alibaba.excel.annotation.ExcelIgnoreUnannotated;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.format.DateTimeFormat;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import java.util.Date;
/**
* @author xinsin
* Created On 2023/6/9 09:25
* @version 1.0
*/
@Getter
@Setter
@EqualsAndHashCode
@ExcelIgnoreUnannotated
public class OrderByExcel {
@ExcelProperty("订单号")
private String orderNo;
@ExcelProperty("下单时间")
@DateTimeFormat("yyyy-MM-dd HH:mm:ss")
private String orderTime;
@ExcelProperty("订单状态")
private String orderStatus;
@ExcelProperty("旺旺号")
private String wangNo;
@ExcelProperty("微信|qq账号")
private String wechatNo;
@ExcelProperty("支付宝账号")
private String alipayNo;
@ExcelProperty("付款金额")
private String payAmt;
@ExcelProperty("店铺名称")
private String storeId;
@ExcelProperty("佣金")
private String commission;
@ExcelProperty("支付宝名称")
private String alipayName;
@ExcelProperty("放单人")
private String rpName;
@ExcelProperty("放单人微信名")
private String rpWechatName;
@ExcelProperty("备注")
private String remark;
@ExcelProperty("买家电话")
private String phoneNumber;
@ExcelProperty("银行卡号")
private String cardNo;
@ExcelProperty("插旗")
private String flag;
@ExcelProperty("插旗备注")
private String flagRemark;
@ExcelProperty("付款时间")
@DateTimeFormat("yyyy-MM-dd HH:mm:ss")
private String payTime;
@ExcelProperty("收货地址")
private String address;
@ExcelProperty("商品id")
private String shopId;
@ExcelProperty("sku")
private String sku;
}

View File

@ -1,45 +0,0 @@
package top.xinsin.pojo;
import com.baomidou.mybatisplus.annotation.*;
import java.io.Serial;
import java.io.Serializable;
import java.sql.Blob;
import java.time.LocalDateTime;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;
/**
* <p>
*
* </p>
*
* @author xinsin
* @since 2023-04-24
*/
@Data
@TableName("store")
public class Store implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
@TableField("name")
private String name;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@TableField("create_time")
private Date createTime;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@TableField("update_time")
private Date updateTime;
@TableField("del")
@TableLogic
private Integer del;
@TableField("status")
private Boolean status;
}

View File

@ -1,50 +0,0 @@
package top.xinsin.pojo;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
@Data
@NoArgsConstructor
public class Verify {
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
private Integer createId;
private Integer storeId;
private Long countdown;
private String verifyName;
private String verifyPhone;
private String verifyResult;
private Integer num;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date updateTime;
@TableLogic
private Integer del;
public Verify(Integer createId, Integer storeId, Long countdown) {
this.createId = createId;
this.storeId = storeId;
this.countdown = countdown;
}
public Verify(String verifyName,String verifyPhone, String verifyResult, Integer num, Date updateTime) {
this.verifyName = verifyName;
this.verifyPhone = verifyPhone;
this.verifyResult = verifyResult;
this.num = num;
this.updateTime = updateTime;
}
public Verify(String verifyResult, Integer num, Date updateTime) {
this.verifyResult = verifyResult;
this.num = num;
this.updateTime = updateTime;
}
}

View File

@ -1,20 +0,0 @@
package top.xinsin.pojo.vo;
import lombok.Data;
import java.util.Date;
@Data
public class AccountAndStoreAdmin {
private String username;
private String auth;
private String email;
private String relName;
private String password;
private Boolean status;
private Integer roleId;
private Date createTime;
private Date updateTime;
private Integer createId;
private Long countdown;
}

View File

@ -1,56 +0,0 @@
package top.xinsin.pojo.vo;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import top.xinsin.pojo.AuthPermissions;
import java.util.Date;
/**
* @author xinsin
* Created On 2023/4/29 21:27
* @version 1.0
*/
@Data
public class AuthPermissionsAndUserVo {
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
@TableField("permission_name")
private String permissionName;
@TableField("permission_code")
private String permissionCode;
@TableField("description")
private String description;
@TableField(exist = false)
private String createName;
@TableField("create_id")
private Integer createId;
@TableField("create_time")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createTime;
@TableField("update_time")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date updateTime;
@TableField("status")
private Boolean status;
public AuthPermissionsAndUserVo(AuthPermissions authPermissions) {
this.id = authPermissions.getId();
this.permissionName = authPermissions.getPermissionName();
this.permissionCode = authPermissions.getPermissionCode();
this.description = authPermissions.getDescription();
this.createId = authPermissions.getCreateId();
this.createTime = authPermissions.getCreateTime();
this.updateTime = authPermissions.getUpdateTime();
this.status = authPermissions.getStatus();
}
}

View File

@ -1,8 +0,0 @@
package top.xinsin.pojo.vo;
import lombok.Data;
@Data
public class AuthRolesAndAuthPermissionsAndUserVo {
}

View File

@ -1,192 +0,0 @@
package top.xinsin.service;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import top.xinsin.mapper.*;
import top.xinsin.pojo.*;
import top.xinsin.pojo.vo.AccountAndStoreAdmin;
import top.xinsin.util.HttpCodes;
import top.xinsin.util.R;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* @author xinsin
* Created On 2023/4/24 21:11
* @version 1.0
*/
@Service
@Slf4j
public class AccountService implements UserDetailsService {
@Autowired
private AccountMapper accountMapper;
@Autowired
private AuthRolesPermissionsMapper authRolesPermissionsMapper;
@Autowired
private AuthRolesMapper authRolesMapper;
@Autowired
private AuthPermissionsMapper authPermissionsMapper;
@Autowired
private VerifyMapper verifyMapper;
@Resource
private RedisTemplate<String, Object> redisTemplate;
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
if (username == null) {
throw new UsernameNotFoundException("用户名不能为空");
} else {
AuthAccount authAccount = this.accountMapper.selectOne(new LambdaQueryWrapper<AuthAccount>()
.eq(AuthAccount::getUsername, username)
.or()
.eq(AuthAccount::getEmail, username)
.eq(AuthAccount::getStatus, true));
if (authAccount == null) {
throw new UsernameNotFoundException("用户名或密码错误");
} else {
if (authAccount.getAuth().equals("商户")){
Verify verify = verifyMapper.selectOne(new LambdaQueryWrapper<Verify>().eq(Verify::getStoreId, authAccount.getId()));
if ("false".equals(verify.getVerifyResult())){
log.info("无法登录,因为商户管理员已拒绝");
return User.withUsername(authAccount.getUsername()).password("").build();
}
}
return User
.withUsername(authAccount.getUsername())
.password(authAccount.getPassword())
.roles("id=" + authAccount.getId(),"roleId=" + authAccount.getRoleId(),"auth=" + authAccount.getAuth())
.build();
}
}
}
public R<String> register(AuthAccount authAccount) {
authAccount.setCreateTime(new Date());
authAccount.setStatus(true);
authAccount.setPassword(this.encoder.encode(authAccount.getPassword()));
int insert = this.accountMapper.insert(authAccount);
return insert == 1 ? R.success("注册成功") : R.failed(HttpCodes.HTTP_CODES555, "注册失败,您的用户名或者邮箱已经被注册过了");
}
public R<String> changeAccount(AuthAccount authAccount) {
if (authAccount.getPassword() != null) {
authAccount.setPassword(this.encoder.encode(authAccount.getPassword()));
}
int update = this.accountMapper.updateById(authAccount);
return update == 1 ? R.success("修改用户信息成功") : R.failed(HttpCodes.HTTP_CODES555, "修改用户信息失败,请联系服务器管理员");
}
public R<String> changeStatus(Integer userId, Boolean status) {
AuthAccount authAccount = new AuthAccount();
authAccount.setId(userId);
authAccount.setStatus(status);
int i = this.accountMapper.updateById(authAccount);
if (i == 1) {
return status ? R.success("启用该用户成功") : R.success("禁用该用户成功");
} else {
return R.failed(HttpCodes.HTTP_CODES555, "修改用户状态失败");
}
}
public R<String> changePassword(Integer userId, String oldPassword, String newPassword) {
AuthAccount authAccount = new AuthAccount();
authAccount.setPassword(this.encoder.encode(newPassword));
LambdaQueryWrapper<AuthAccount> accountLambdaQueryWrapper = new LambdaQueryWrapper<>();
accountLambdaQueryWrapper
.eq(AuthAccount::getId, userId)
.eq(AuthAccount::getPassword, this.encoder.encode(oldPassword));
int update = this.accountMapper.update(authAccount, accountLambdaQueryWrapper);
return update == 1 ? R.success("修改密码成功") : R.failed(HttpCodes.HTTP_CODES555, "修改密码失败,请联系服务器管理员");
}
public R<JSONObject> getUser(Integer page, Integer num) {
Page<AuthAccount> accountPage = new Page<>(page, num);
String auth = ((User) SecurityContextHolder
.getContext()
.getAuthentication()
.getPrincipal())
.getAuthorities()
.stream()
.filter(e -> e.getAuthority().startsWith("ROLE_auth="))
.findFirst()
.get()
.getAuthority().replace("ROLE_auth=","");
LambdaQueryWrapper<AuthAccount> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
if (auth.equals("租户管理员")){
userLambdaQueryWrapper.in(AuthAccount::getAuth,"商户管理员","商户");
}
if (auth.equals("商户管理员")){
userLambdaQueryWrapper.in(AuthAccount::getAuth,"商户");
}
System.out.println(auth);
Page<AuthAccount> accountPage1 = this.accountMapper.selectPage(accountPage, userLambdaQueryWrapper);
JSONObject jsonObject = new JSONObject();
List<AuthAccount> collect = accountPage1.getRecords().stream().peek((e) -> e.setPassword(null)).toList();
jsonObject
.fluentPut("info", collect)
.fluentPut("total", accountPage1.getTotal());
return R.success(jsonObject);
}
public R<String> delUser(Integer id) {
int delete = this.accountMapper.deleteById(id);
return delete == 1 ? R.success("删除用户成功") : R.failed(HttpCodes.HTTP_CODES555, "删除用户失败,请联系服务器管理员");
}
public R<JSONObject> getUserInfo(int rolesId) {
JSONObject globalReturnData = new JSONObject();
JSONArray globalReturnPermissionList = new JSONArray();
List<AuthRolesPermissions> authRolesPermissions = authRolesPermissionsMapper
.selectList(new LambdaQueryWrapper<AuthRolesPermissions>()
.eq(AuthRolesPermissions::getRoleId, rolesId));
List<Integer> permissionsList = authRolesPermissions.stream().map(AuthRolesPermissions::getPermissionId).toList();
List<AuthPermissions> authPermissions = authPermissionsMapper.selectList(new LambdaQueryWrapper<AuthPermissions>()
.in(AuthPermissions::getId, permissionsList));
authPermissions.forEach(e -> {
HashMap<String, String> returnPermissionJson = new HashMap<>();
returnPermissionJson.put("permissionName",e.getPermissionName());
returnPermissionJson.put("permissionCode",e.getPermissionCode());
globalReturnPermissionList.add(returnPermissionJson);
});
AuthRoles authRoles = authRolesMapper.selectOne(new LambdaQueryWrapper<AuthRoles>().eq(AuthRoles::getId, rolesId));
// 角色名
String roleName = authRoles.getRoleName();
globalReturnData
.fluentPut("info",globalReturnPermissionList)
.fluentPut("roleName",roleName);
return R.success(globalReturnData);
}
public R<JSONObject> addStoreAdmin(AccountAndStoreAdmin accountAndStoreAdmin) {
AuthAccount authAccount = new AuthAccount(accountAndStoreAdmin.getUsername(), accountAndStoreAdmin.getAuth(), accountAndStoreAdmin.getEmail(), accountAndStoreAdmin.getRelName(), this.encoder.encode(accountAndStoreAdmin.getPassword()), accountAndStoreAdmin.getStatus(), accountAndStoreAdmin.getRoleId(), new Date());
int insert = accountMapper.insert(authAccount);
if (insert == 1){
Verify verify = new Verify(accountAndStoreAdmin.getCreateId(), authAccount.getId(), accountAndStoreAdmin.getCountdown());
int insert1 = verifyMapper.insert(verify);
if (insert1 == 1){
// redisTemplate.opsForValue().set(String.valueOf(authAccount.getId()),authAccount.getUsername(),verify.getCountdown(), TimeUnit.SECONDS);
return R.success(new JSONObject().fluentPut("status","添加该商户成功").fluentPut("nextVerificationTime",verify.getCountdown()));
}
}
return R.failed(HttpCodes.HTTP_CODES500,new JSONObject().fluentPut("status","添加商户失败"));
}
}

View File

@ -1,87 +0,0 @@
package top.xinsin.service;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Service;
import top.xinsin.mapper.AccountMapper;
import top.xinsin.mapper.AuthPermissionsMapper;
import top.xinsin.pojo.AuthAccount;
import top.xinsin.pojo.AuthPermissions;
import top.xinsin.pojo.AuthRoles;
import top.xinsin.pojo.vo.AuthPermissionsAndUserVo;
import top.xinsin.util.HttpCodes;
import top.xinsin.util.R;
import java.util.*;
import static org.springframework.data.util.Pair.toMap;
/**
* @author xinsin
* Created On 2023/4/24 21:13
* @version 1.0
*/
@Service
public class AuthPermissionsService {
@Autowired
private AuthPermissionsMapper authPermissionsMapper;
@Autowired
private AccountMapper accountMapper;
public R<Boolean> addAuthPermissions(AuthPermissions authPermissions) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
authentication.getAuthorities().forEach(e -> {
String authority = e.getAuthority();
if (authority.startsWith("ROLE_id=")){
authPermissions.setCreateId(Integer.parseInt(authority.replace("ROLE_id=", "")));
}
});
authPermissions.setCreateTime(new Date());
int insert = authPermissionsMapper.insert(authPermissions);
return insert == 1 ? R.success(true) : R.failed(HttpCodes.HTTP_CODES555, false);
}
public R<Boolean> changeAuthPermissions(AuthPermissions authPermissions) {
authPermissions.setUpdateTime(new Date());
int update = authPermissionsMapper.updateById(authPermissions);
return update == 1 ? R.success(true) : R.failed(HttpCodes.HTTP_CODES555, false);
}
public R<Boolean> delAuthPermissions(Integer id) {
int delete = authPermissionsMapper.deleteById(id);
return delete == 1 ? R.success(true) : R.failed(HttpCodes.HTTP_CODES555, false);
}
public R<JSONObject> getAuthPermissions(Integer page, Integer num) {
Page<AuthPermissions> authPermissionsPage = new Page<>(page, num);
Page<AuthPermissions> authPermissionsPage1 = authPermissionsMapper.selectPage(authPermissionsPage, null);
List<AuthPermissions> records = authPermissionsPage1.getRecords();
List<Integer> integers = records.stream().map(AuthPermissions::getCreateId).toList();
List<AuthAccount> authAccounts = accountMapper.selectList(new LambdaQueryWrapper<AuthAccount>()
.in(AuthAccount::getId, integers));
Map<Integer,String > map = new HashMap<>();
authAccounts.forEach(e -> map.put(e.getId(), e.getUsername()));
List<AuthPermissionsAndUserVo> authPermissionsAndUserVos = records.stream().map(AuthPermissionsAndUserVo::new).toList();
authPermissionsAndUserVos.forEach(e -> e.setCreateName(map.get(e.getCreateId())));
return R.success(new JSONObject().fluentPut("info",authPermissionsAndUserVos).fluentPut("total",authPermissionsPage.getTotal()));
}
public R<String> changeAuthPermissionsStats(Integer authPermissionId, Boolean status) {
return R.success("");
}
public R<List<JSONObject>> getAuthPermissionsId() {
List<AuthPermissions> authRoles = authPermissionsMapper.selectList(null);
ArrayList<JSONObject> jsonObjects = new ArrayList<>();
authRoles.forEach(e -> {
jsonObjects.add(new JSONObject().fluentPut("id",e.getId()).fluentPut("permissionName",e.getPermissionName()));
});
return R.success(jsonObjects);
}
}

View File

@ -1,100 +0,0 @@
package top.xinsin.service;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import top.xinsin.mapper.AccountMapper;
import top.xinsin.mapper.AuthPermissionsMapper;
import top.xinsin.mapper.AuthRolesMapper;
import top.xinsin.mapper.AuthRolesPermissionsMapper;
import top.xinsin.pojo.AuthPermissions;
import top.xinsin.pojo.AuthRoles;
import top.xinsin.pojo.AuthRolesPermissions;
import top.xinsin.util.HttpCodes;
import top.xinsin.util.R;
import java.util.*;
/**
* @author xinsin
* Created On 2023/4/29 20:28
* @version 1.0
*/
@Service
public class AuthRolesPermissionsService {
@Autowired
private AuthRolesPermissionsMapper authRolesPermissionsMapper;
@Autowired
private AuthRolesMapper authRolesMapper;
@Autowired
private AuthPermissionsMapper authPermissionsMapper;
@Autowired
private AccountMapper accountMapper;
public R<Boolean> addAuthRolesPermissions(AuthRolesPermissions authPermissions) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
authentication.getAuthorities().forEach(e -> {
String authority = e.getAuthority();
if (authority.startsWith("ROLE_id=")){
authPermissions.setCreateId(Integer.parseInt(authority.replace("ROLE_id=", "")));
}
});
authPermissions.setCreateTime(new Date());
int insert = authRolesPermissionsMapper.insert(authPermissions);
return insert == 1 ? R.success(true) : R.failed(HttpCodes.HTTP_CODES555, false);
}
public R<Boolean> changeAuthRolesPermissions(AuthRolesPermissions authPermissions) {
authPermissions.setUpdateTime(new Date());
int update = authRolesPermissionsMapper.updateById(authPermissions);
return update == 1 ? R.success(true) : R.failed(HttpCodes.HTTP_CODES555, false);
}
public R<Boolean> delAuthRolesPermissions(Integer roleId, Integer permissionId) {
int delete = authRolesPermissionsMapper.delete(new LambdaQueryWrapper<AuthRolesPermissions>()
.eq(AuthRolesPermissions::getRoleId,roleId)
.eq(AuthRolesPermissions::getPermissionId,permissionId));
return delete == 1 ? R.success(true) : R.failed(HttpCodes.HTTP_CODES555, false);
}
public R<JSONObject> getAuthRolesPermissions(Integer page, Integer num) {
Page<AuthRoles> authRolesPage = new Page<>(page, num);
Page<AuthRoles> authRolesPage1 = authRolesMapper.selectPage(authRolesPage, null);
ArrayList<JSONObject> jsonObjects1 = new ArrayList<>();
authRolesPage1.getRecords().forEach(e -> {
JSONObject jsonObject = new JSONObject();
jsonObject.fluentPut("roleName",e.getRoleName());
LambdaQueryWrapper<AuthRolesPermissions> authRolesPermissionsLambdaQueryWrapper = new LambdaQueryWrapper<>();
authRolesPermissionsLambdaQueryWrapper.eq(AuthRolesPermissions::getRoleId,e.getId());
List<AuthRolesPermissions> authRolesPermissions = authRolesPermissionsMapper.selectList(authRolesPermissionsLambdaQueryWrapper);
ArrayList<JSONObject> jsonObjects = new ArrayList<>();
authRolesPermissions.forEach(a -> {
JSONObject jsonObject1 = new JSONObject();
LambdaQueryWrapper<AuthPermissions> authPermissionsLambdaQueryWrapper = new LambdaQueryWrapper<>();
authPermissionsLambdaQueryWrapper.eq(AuthPermissions::getId,a.getPermissionId());
AuthPermissions authPermissions = authPermissionsMapper.selectOne(authPermissionsLambdaQueryWrapper);
jsonObject1.fluentPut("permissionName",authPermissions.getPermissionName()).fluentPut("permissionCode",authPermissions.getPermissionCode());
jsonObjects.add(jsonObject1);
});
jsonObject.fluentPut("permissions",jsonObjects);
jsonObjects1.add(jsonObject);
});
return R.success(new JSONObject().fluentPut("info",jsonObjects1).fluentPut("total",authRolesPage.getTotal()));
}
public R<String> changeAuthRolesPermissionsStats(Integer authPermissionId, Boolean status) {
return R.success("");
}
// public R<List<JSONObject>> getAuthRolesPermissions() {
// List<AuthRolesPermissions> authRoles = authRolesPermissionsMapper.selectList(null);
// ArrayList<JSONObject> jsonObjects = new ArrayList<>();
// authRoles.forEach(e -> {
// jsonObjects.add(new JSONObject().fluentPut("id",e.getId()).fluentPut("permissionName",e.getPermissionName()));
// });
// return R.success(jsonObjects);
// }
}

View File

@ -1,99 +0,0 @@
package top.xinsin.service;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import top.xinsin.mapper.AccountMapper;
import top.xinsin.mapper.AuthPermissionsMapper;
import top.xinsin.mapper.AuthRolesMapper;
import top.xinsin.mapper.AuthRolesPermissionsMapper;
import top.xinsin.pojo.AuthAccount;
import top.xinsin.pojo.AuthPermissions;
import top.xinsin.pojo.AuthRoles;
import top.xinsin.pojo.AuthRolesPermissions;
import top.xinsin.pojo.vo.AuthPermissionsAndUserVo;
import top.xinsin.util.HttpCodes;
import top.xinsin.util.R;
import java.util.*;
/**
* @author xinsin
* Created On 2023/4/24 21:13
* @version 1.0
*/
@Service
public class AuthRolesService {
@Autowired
private AuthRolesMapper authRolesMapper;
@Autowired
private AuthPermissionsMapper authPermissionsMapper;
@Autowired
private AuthRolesPermissionsMapper authRolesPermissionsMapper;
public R<Boolean> addAuthRoles(AuthRoles authPermissions) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
authentication.getAuthorities().forEach(e -> {
String authority = e.getAuthority();
if (authority.startsWith("ROLE_id=")){
authPermissions.setCreateId(Integer.parseInt(authority.replace("ROLE_id=", "")));
}
});
authPermissions.setCreateTime(new Date());
int insert = authRolesMapper.insert(authPermissions);
return insert == 1 ? R.success(true) : R.failed(HttpCodes.HTTP_CODES555, false);
}
public R<Boolean> changeAuthRoles(AuthRoles authPermissions) {
authPermissions.setUpdateTime(new Date());
int update = authRolesMapper.updateById(authPermissions);
return update == 1 ? R.success(true) : R.failed(HttpCodes.HTTP_CODES555, false);
}
public R<Boolean> delAuthRoles(Integer id) {
int delete = authRolesMapper.deleteById(id);
return delete == 1 ? R.success(true) : R.failed(HttpCodes.HTTP_CODES555, false);
}
public R<JSONObject> getAuthRoles(Integer page, Integer num) {
Page<AuthRoles> authPermissionsPage = new Page<>(page, num);
Page<AuthRoles> authRolesPage = authRolesMapper.selectPage(authPermissionsPage, null);
return R.success(new JSONObject().fluentPut("info",authRolesPage.getRecords()).fluentPut("total",authPermissionsPage.getTotal()));
}
public R<String> changeAuthRolesStats(Integer authPermissionId, Boolean status) {
return R.success("");
}
public R<List<JSONObject>> getAuthRolesId() {
List<AuthRoles> authRoles = authRolesMapper.selectList(null);
ArrayList<JSONObject> jsonObjects = new ArrayList<>();
authRoles.forEach(e -> {
jsonObjects.add(new JSONObject().fluentPut("id",e.getId()).fluentPut("roleName",e.getRoleName()));
});
return R.success(jsonObjects);
}
public R<List<JSONObject>> getAuthPermissionId(Integer roleId) {
LambdaQueryWrapper<AuthRolesPermissions> authRolesPermissionsLambdaQueryWrapper = new LambdaQueryWrapper<>();
authRolesPermissionsLambdaQueryWrapper.eq(AuthRolesPermissions::getRoleId,roleId);
List<AuthRolesPermissions> authRolesPermissions = authRolesPermissionsMapper.selectList(authRolesPermissionsLambdaQueryWrapper);
ArrayList<JSONObject> jsonObjects = new ArrayList<>();
authRolesPermissions.forEach(e ->{
JSONObject jsonObject = new JSONObject();
AuthPermissions authPermissions = authPermissionsMapper.selectOne(new LambdaQueryWrapper<AuthPermissions>().eq(AuthPermissions::getId, e.getPermissionId()));
jsonObject
.fluentPut("name",authPermissions.getPermissionName())
.fluentPut("id",authPermissions.getId())
.fluentPut("description",authPermissions.getDescription())
.fluentPut("status",authPermissions.getStatus())
.fluentPut("code",authPermissions.getPermissionCode());
jsonObjects.add(jsonObject);
});
return R.success(jsonObjects);
}
}

View File

@ -1,80 +0,0 @@
package top.xinsin.service;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.xinsin.mapper.CommissionMapper;
import top.xinsin.pojo.Commission;
import top.xinsin.util.HttpCodes;
import top.xinsin.util.R;
import java.util.Date;
/**
* <p>
* 服务类
* </p>
*
* @author xinsin
* @since 2023-04-24
*/
@Service
public class CommissionService {
@Autowired
private CommissionMapper commissionMapper;
public R<Boolean> addCommission(Commission commission) {
commission.setCreateTime(new Date());
int insert = commissionMapper.insert(commission);
return insert != 0 ? R.success(true) : R.failed(HttpCodes.HTTP_CODES555,false);
}
public R<Boolean> changeCommission(Commission commission) {
commission.setUpdateTime(new Date());
int update = commissionMapper.updateById(commission);
return update != 0 ? R.success(true) : R.failed(HttpCodes.HTTP_CODES555,false);
}
public R<Boolean> delCommission(Integer id) {
int delete = commissionMapper.deleteById(id);
return delete != 0 ? R.success(true) : R.failed(HttpCodes.HTTP_CODES555,false);
}
public R<JSONObject> getCommission(Integer page, Integer num) {
JSONObject jsonObject = new JSONObject();
Page<Commission> commissionPage = new Page<>(page,num);
Page<Commission> commissionPage1 = commissionMapper.selectPage(commissionPage, null);
jsonObject.fluentPut("info",commissionPage1.getRecords()).fluentPut("total",commissionPage1.getTotal());
return R.success(jsonObject);
}
public R<Double> getCommissionByPrice(Integer shopId, Double range) {
LambdaQueryWrapper<Commission> commissionLambdaQueryWrapper = new LambdaQueryWrapper<>();
commissionLambdaQueryWrapper
.le(Commission::getPriceMax,range)
.ge(Commission::getPriceMin,range)
.eq(Commission::getStoreId,shopId);
Commission commission = commissionMapper.selectOne(commissionLambdaQueryWrapper);
if (commission != null){
return R.success(commission.getCommission());
}else{
return R.failed(HttpCodes.HTTP_CODES555,0.0);
}
}
public R<String> changeCommissionStatus(Integer commissionId, Boolean status) {
Commission commission = new Commission();
commission.setId(commissionId);
commission.setStatus(status);
int i = commissionMapper.updateById(commission);
if (i == 1) {
return status ? R.success("启用该佣金项成功") : R.success("禁用该佣金项成功");
} else {
return R.failed(HttpCodes.HTTP_CODES555, "修改佣金状态失败");
}
}
}

View File

@ -1,236 +0,0 @@
package top.xinsin.service;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import top.xinsin.enums.OrderStatus;
import top.xinsin.enums.SearchType;
import top.xinsin.mapper.CommissionMapper;
import top.xinsin.mapper.OrderMapper;
import top.xinsin.pojo.Commission;
import top.xinsin.pojo.Order;
import top.xinsin.pojo.OrderByExcel;
import top.xinsin.pojo.Store;
import top.xinsin.util.HttpCodes;
import top.xinsin.util.R;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
/**
* @author xinsin
* Created On 2023/4/24 21:12
* @version 1.0
*/
@Service
@Slf4j
public class OrderService extends ServiceImpl<OrderMapper,Order> implements OrderServiceInter {
@Autowired
private StoreService storeMapper;
@Autowired
private CommissionMapper commissionMapper;
public R<String> addOrder(Order order) {
order.setOrderTime(new Date());
boolean insert = this.save(order);
return insert ? R.success("订单添加成功") : R.failed(HttpCodes.HTTP_CODES555, "订单添加失败,请联系服务器管理员");
}
public R<JSONObject> getOrder(Integer page, Integer num) {
Page<Order> orderPage = new Page<>(page, num);
Page<Order> orderPage1 = this.page(orderPage, null);
return getJsonObjectR(orderPage1);
}
public R<Boolean> getOrderUserInfo(String content) {
LambdaQueryWrapper<Order> orderLambdaQueryWrapper = new LambdaQueryWrapper<>();
orderLambdaQueryWrapper.eq(Order::getWechatNo, content).or().eq(Order::getWangNo, content).or().eq(Order::getAlipayNo, content).or().eq(Order::getPhoneNumber, content).or().eq(Order::getAlipayName, content);
List<Order> orders = this.list(orderLambdaQueryWrapper);
return orders.size() == 0 ? R.success(false) : R.success(true);
}
public R<JSONObject> searchUserOrder(SearchType searchType, String searchContent, Boolean batch, Integer page, Integer num) {
LambdaQueryWrapper<Order> orderLambdaQueryWrapper = new LambdaQueryWrapper<>();
if (batch) {
String[] split = searchContent.split(",");
String[] var8 = split;
int var9 = split.length;
for(int var10 = 0; var10 < var9; ++var10) {
String s = var8[var10];
this.searchForWhereOne(searchType, orderLambdaQueryWrapper, s);
}
} else {
this.searchForWhereOne(searchType, orderLambdaQueryWrapper, searchContent);
}
Page<Order> orderPage = new Page<>((long)page, (long)num);
Page<Order> orderPage1 = this.page(orderPage, orderLambdaQueryWrapper);
return getJsonObjectR(orderPage1);
}
private R<JSONObject> getJsonObjectR(Page<Order> orderPage1) {
orderPage1.getRecords().forEach(e -> {
LambdaQueryWrapper<Store> orderVOLambdaQueryWrapper = new LambdaQueryWrapper<>();
orderVOLambdaQueryWrapper.eq(Store::getId,e.getStoreId());
Store store = storeMapper.getOne(orderVOLambdaQueryWrapper);
e.setStoreName(store.getName());
LambdaQueryWrapper<Commission> commissionLambdaQueryWrapper = new LambdaQueryWrapper<>();
commissionLambdaQueryWrapper
.eq(Commission::getStoreId,e.getStoreId())
.le(Commission::getPriceMax,e.getCommission())
.ge(Commission::getPriceMin,e.getCommission());
Commission commission = commissionMapper.selectOne(commissionLambdaQueryWrapper);
if (commission != null){
e.setCommission(commission.getCommission());
}else{
e.setCommission(0.0);
}
});
JSONObject jsonObject = new JSONObject();
jsonObject.fluentPut("info", orderPage1.getRecords()).fluentPut("total", orderPage1.getTotal());
return R.success(jsonObject);
}
private void searchForWhereOne(SearchType searchType, LambdaQueryWrapper<Order> orderLambdaQueryWrapper, String searchContent) {
switch (searchType) {
case WANG_ID -> orderLambdaQueryWrapper.like(Order::getWangNo, searchContent).or();
case ALIPAY_ID -> orderLambdaQueryWrapper.like(Order::getAlipayNo, searchContent).or();
case WECHAT_ID -> orderLambdaQueryWrapper.like(Order::getWechatNo, searchContent).or();
case PHONE_NUMBER -> orderLambdaQueryWrapper.like(Order::getPhoneNumber, searchContent).or();
}
}
public R<String> addOrderFlag(Integer orderId, Integer flagId, String flagRemark) {
Order order = new Order();
order.setId(orderId);
order.setFlag(flagId);
order.setFlagRemark(flagRemark);
boolean update = this.updateById(order);
return update ? R.success("订单插旗成功," + flagId + "号旗") : R.failed(HttpCodes.HTTP_CODES555, "订单插旗失败,请联系服务器管理员");
}
public R<String> changeOrder(Order order) {
boolean update = this.updateById(order);
return update ? R.success("订单修改成功") : R.failed(HttpCodes.HTTP_CODES555, "订单修改失败,请联系服务器管理员");
}
public R<String> delOrder(Integer orderId) {
boolean delete = this.removeById(orderId);
return delete ? R.success("删除订单成功") : R.failed(HttpCodes.HTTP_CODES555, "删除订单失败,请联系服务器管理员");
}
public R<String> confirm(OrderStatus orderStatus, Integer orderId) {
Order order = new Order();
order.setId(orderId);
order.setOrderStatus(orderStatus.name());
boolean update = this.updateById(order);
return update ? R.success("订单确认成功,当前状态:" + orderStatus.name()) : R.failed(HttpCodes.HTTP_CODES555, "订单确认失败,请联系服务器管理员");
}
@SneakyThrows
public void downloadTemplate(HttpServletResponse response) {
try {
File file = new File("./template/example.xlsx");
FileInputStream fileInputStream = new FileInputStream(file);
BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
byte[] bytes = new byte[bufferedInputStream.available()];
bufferedInputStream.read(bytes);
bufferedInputStream.close();
response.reset();
response.setCharacterEncoding("utf-8");
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.addHeader("Content-disposition", "attachment;filename*=utf-8''example.xlsx");
response.addHeader("Content-Length", "" + file.length());
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
bufferedOutputStream.write(bytes);
bufferedOutputStream.flush();
} catch (Throwable var7) {
throw var7;
}
}
@SneakyThrows
@Transactional
public R<JSONObject> uploadBatch(MultipartFile file) {
DateFormat fmt =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
AtomicInteger total = new AtomicInteger();
AtomicBoolean status = new AtomicBoolean(false);
EasyExcel.read(file.getInputStream(),OrderByExcel.class,new PageReadListener<OrderByExcel>(list -> {
list.remove(0);
total.addAndGet(list.size());
List<Order> orders = new ArrayList<>();
AtomicReference<Order> order = new AtomicReference<>();
list.forEach(e -> {
try {
order.set(new Order()
.setOrderNo(e.getOrderNo())
.setOrderTime(e.getOrderTime() != null ? fmt.parse(e.getOrderTime()) : null)
.setOrderStatus(e.getOrderStatus())
.setWangNo(e.getWangNo())
.setWechatNo(e.getWechatNo())
.setAlipayNo(e.getAlipayNo())
.setPayAmt(e.getPayAmt() != null ? Double.parseDouble(e.getPayAmt()) : null)
.setCommission(e.getCommission() != null ? Double.parseDouble(e.getCommission()) : null)
.setAlipayName(e.getAlipayName())
.setRpName(e.getRpName())
.setRpWechatName(e.getRpWechatName())
.setRemark(e.getRemark())
.setPhoneNumber(e.getPhoneNumber())
.setCardNo(e.getCardNo())
.setFlag(e.getFlag() != null ? Integer.parseInt(e.getFlag()) : null)
.setFlagRemark(e.getFlagRemark())
.setPayTime(e.getPayTime() != null ? fmt.parse(e.getPayTime()) : null)
.setAddress(e.getAddress())
.setShopId(e.getShopId() != null ? Integer.parseInt(e.getShopId()) : null)
.setSku(e.getSku()));
} catch (ParseException ex) {
throw new RuntimeException(ex);
}
log.info(" ==> 解析一条数据: {}", JSONObject.toJSONString(e));
if (e.getStoreId() != null){
LambdaQueryWrapper<Store> eq = new LambdaQueryWrapper<Store>().eq(Store::getName, e.getStoreId());
Store one = storeMapper.getOne(eq);
if (one != null){
order.get().setStoreId(one.getId());
}else{
Store store = new Store();
store.setName(e.getStoreId());
storeMapper.save(store);
order.get().setStoreId(store.getId());
}
orders.add(order.get());
}
});
log.info(" ==> 共全部数据: {}",total.get());
status.set(this.saveBatch(orders));
})).sheet().doRead();
return R.success(new JSONObject().fluentPut("total",total.get()).fluentPut("status",status.get()));
}
}

View File

@ -1,8 +0,0 @@
package top.xinsin.service;
import com.baomidou.mybatisplus.extension.service.IService;
import top.xinsin.pojo.Order;
public interface OrderServiceInter extends IService<Order> {
}

View File

@ -1,73 +0,0 @@
package top.xinsin.service;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.xinsin.mapper.StoreMapper;
import top.xinsin.pojo.Commission;
import top.xinsin.pojo.Store;
import com.baomidou.mybatisplus.extension.service.IService;
import top.xinsin.util.HttpCodes;
import top.xinsin.util.R;
import java.util.Date;
import java.util.List;
/**
* <p>
* 服务类
* </p>
*
* @author xinsin
* @since 2023-04-24
*/
@Service
@Slf4j
public class StoreService extends ServiceImpl<StoreMapper,Store> implements StoreServiceInter {
@Autowired
private StoreMapper storeMapper;
public R<Boolean> addStore(Store store) {
store.setCreateTime(new Date());
int insert = storeMapper.insert(store);
return insert != 0 ? R.success(true) : R.failed(HttpCodes.HTTP_CODES555,false);
}
public R<Boolean> changStore(Store store) {
store.setUpdateTime(new Date());
int update = storeMapper.updateById(store);
return update != 0 ? R.success(true) : R.failed(HttpCodes.HTTP_CODES555,false);
}
public R<Boolean> delStore(Integer id) {
int delete = storeMapper.deleteById(id);
return delete != 0 ? R.success(true) : R.failed(HttpCodes.HTTP_CODES555,false);
}
public R<JSONObject> getStore(Integer page, Integer num) {
JSONObject jsonObject = new JSONObject();
Page<Store> storePage = new Page<>(page,num);
Page<Store> storePage1 = storeMapper.selectPage(storePage, null);
jsonObject.fluentPut("info",storePage1.getRecords()).fluentPut("total",storePage1.getTotal());
return R.success(jsonObject);
}
public R<List<Store>> getAllStore() {
return R.success(storeMapper.selectList(null));
}
public R<String> changeStoreStatus(Integer storeId, Boolean status) {
Store store = new Store();
store.setId(storeId);
store.setStatus(status);
int i = storeMapper.updateById(store);
if (i == 1) {
return status ? R.success("启用该商铺成功") : R.success("禁用该商铺成功");
} else {
return R.failed(HttpCodes.HTTP_CODES555, "修改商铺状态失败");
}
}
}

View File

@ -1,13 +0,0 @@
package top.xinsin.service;
import com.baomidou.mybatisplus.extension.service.IService;
import top.xinsin.pojo.Order;
import top.xinsin.pojo.Store;
/**
* @author xinsin
* Created On 2023/6/20 21:14
* @version 1.0
*/
public interface StoreServiceInter extends IService<Store> {
}

View File

@ -1,81 +0,0 @@
package top.xinsin.service;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import top.xinsin.mapper.VerifyMapper;
import top.xinsin.pojo.Verify;
import top.xinsin.util.HttpCodes;
import top.xinsin.util.R;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
@Service
public class VerifyService {
@Autowired
private VerifyMapper verifyMapper;
@Resource
private RedisTemplate<String, Object> redisTemplate;
public R<JSONObject> getRemainderTime(Integer id) {
Long storeName = redisTemplate.getExpire(String.valueOf(id), TimeUnit.SECONDS);
System.out.println(storeName);
return R.success(new JSONObject().fluentPut("remainderTime",storeName));
}
public R<Boolean> verify(Integer id, String name, String phone) {
Verify verify = new Verify();
verify.setVerifyPhone(phone);
verify.setVerifyName(name);
int update = verifyMapper.update(verify, new LambdaQueryWrapper<Verify>().eq(Verify::getStoreId, id));
return update == 1 ? R.success(true) : R.failed(HttpCodes.HTTP_CODES555, false);
}
public R<List<JSONObject>> getVerifyMessage(Integer createId) {
LambdaQueryWrapper<Verify> verifyLambdaQueryWrapper = new LambdaQueryWrapper<>();
verifyLambdaQueryWrapper.eq(Verify::getCreateId,createId);
List<Verify> verifies = verifyMapper.selectList(verifyLambdaQueryWrapper);
ArrayList<JSONObject> jsonObjects = new ArrayList<>();
verifies.forEach(e -> {
JSONObject jsonObject = new JSONObject();
jsonObject.fluentPut("storeId",e.getStoreId())
.fluentPut("storeName",e.getVerifyName())
.fluentPut("phone",e.getVerifyPhone());
jsonObjects.add(jsonObject);
});
return R.success(jsonObjects);
}
public R<JSONObject> confirmVerify(Integer createId, Integer storeId, Boolean status) {
if (status){
LambdaQueryWrapper<Verify> verifyLambdaQueryWrapper = new LambdaQueryWrapper<>();
verifyLambdaQueryWrapper
.eq(Verify::getCreateId,createId)
.eq(Verify::getStoreId,storeId);
Verify verify1 = verifyMapper.selectOne(verifyLambdaQueryWrapper);
Verify verify = new Verify("","",String.valueOf(true),verify1.getNum() + 1,new Date());
int update = verifyMapper.update(verify, verifyLambdaQueryWrapper);
if (update == 1){
return R.success(new JSONObject().fluentPut("info","确认验证信息成功,请通知商户重新登录"));
}
}else {
LambdaQueryWrapper<Verify> verifyLambdaQueryWrapper = new LambdaQueryWrapper<>();
verifyLambdaQueryWrapper
.eq(Verify::getCreateId,createId)
.eq(Verify::getStoreId,storeId);
Verify verify1 = verifyMapper.selectOne(verifyLambdaQueryWrapper);
Verify verify = new Verify(String.valueOf(false),verify1.getNum() + 1,new Date());
int update = verifyMapper.update(verify, verifyLambdaQueryWrapper);
if (update == 1){
return R.success(new JSONObject().fluentPut("info","确认验证信息成功,该用户将不可登录"));
}
}
return R.failed(HttpCodes.ACCESS_DENIED,new JSONObject());
}
}

View File

@ -1,170 +0,0 @@
package top.xinsin.service;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;
import top.xinsin.controller.WebSocketController;
import top.xinsin.mapper.VerifyMapper;
import top.xinsin.pojo.Verify;
import top.xinsin.util.HttpCodes;
import top.xinsin.util.R;
import top.xinsin.util.StringConstant;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
@Service
@Slf4j
public class WebSocketService {
@Resource
private RedisTemplate<String, Object> redisTemplate;
@Autowired
private VerifyMapper verifyMapper;
private Map<String,WebSocketController> adminBYStoreId = new HashMap<>();
public R<JSONObject> addVerify(String userId, WebSocketController session){
RedisSerializer<String> stringSerializer = new StringRedisSerializer();
redisTemplate.setValueSerializer(stringSerializer);
redisTemplate.setKeySerializer(stringSerializer);
JSONObject jsonObject = new JSONObject();
if (userId.startsWith("-114514_")){
adminBYStoreId.put(userId.replace("-114514_",""),session);
// 筛选出当前过期的数据
Set<String> noVerify = redisTemplate.keys(StringConstant.NO_VERIFY_PRE + "*");
Set<String> verify = redisTemplate.keys(StringConstant.VERIFY_PRE + "*");
List<String> list = new ArrayList<>();
assert noVerify != null;
noVerify.forEach(e -> list.add(e.replace(StringConstant.NO_VERIFY_PRE, "")));
assert verify!= null;
List<String> list2 = new ArrayList<>();
verify.forEach(e -> list2.add(e.replace(StringConstant.VERIFY_PRE, "")));
List<String> list1 = list.stream().filter(e -> !list2.contains(e)).toList();
JSONArray jsonArray = new JSONArray();
Arrays.stream(userId.replace("-114514_", "").split(",")).filter(list1::contains).forEach(jsonArray::add);
jsonObject.fluentPut("expire",jsonArray);
return R.success(jsonObject.fluentPut("info","检测为管理员登录"));
}
Object o = redisTemplate.opsForValue().get(StringConstant.VERIFY_PRE + userId);
Object o1 = redisTemplate.opsForValue().get(StringConstant.NO_VERIFY_PRE + userId);
if (o == null && o1 == null){
Verify verify = verifyMapper.selectOne(new LambdaQueryWrapper<Verify>().eq(Verify::getStoreId, userId));
if (verify != null){
if(userId.equals(String.valueOf(verify.getStoreId()))) {
redisTemplate.opsForValue().set(StringConstant.VERIFY_PRE + userId, String.valueOf(verify.getNum()), verify.getCountdown(), TimeUnit.SECONDS);
redisTemplate.opsForValue().set(StringConstant.NO_VERIFY_PRE + userId, String.valueOf(verify.getNum()));
jsonObject.fluentPut("info","已将该用户过期时间存入");
return R.success(jsonObject);
}
}
}else{
jsonObject.fluentPut("info","当前用户已存在");
return R.success(jsonObject);
}
jsonObject.fluentPut("info","不存在该用户");
return R.failed(HttpCodes.HTTP_CODES500,jsonObject);
}
public R<JSONObject> parseMessage(String userId, String message, ConcurrentHashMap<String, WebSocketController> webSocketMap){
JSONObject parse = JSONObject.parse(message);
String type = (String) parse.get("type");
return switch (type) {
case "ping" -> ping(userId);
case "addVerifyInfo" -> addVerifyInfo(userId, parse);
case "getTime" -> getTime(userId);
case "confirmVerifyInfo" -> confirmVerifyInfo(parse,webSocketMap);
default -> null;
};
}
private R<JSONObject> confirmVerifyInfo(JSONObject parse, ConcurrentHashMap<String, WebSocketController> webSocketMap) {
String verifyResult = String.valueOf(parse.get("verifyResult"));
String userId = String.valueOf(parse.get("userId"));
int i = Integer.parseInt(String.valueOf(redisTemplate.opsForValue().get(StringConstant.NO_VERIFY_PRE + userId)));
System.out.println(i);
Verify verify = new Verify();
verify.setVerifyResult(verifyResult);
verify.setNum(i + 1);
int update = verifyMapper.update(verify, new LambdaQueryWrapper<Verify>().eq(Verify::getStoreId, userId));
if (update != 1){
return R.failed(HttpCodes.HTTP_CODES500,new JSONObject().fluentPut("info","信息修改失败"));
}
if (verifyResult.equals("false")){
if (webSocketMap.containsKey(userId)){
webSocketMap.get(userId).sendMessage(JSON.toJSONString(new JSONObject().fluentPut("info","管理员未同意你的验证信息,你可以重新进行验证")));
}
return R.success(new JSONObject().fluentPut("info","你已拒绝该商户的验证信息"));
}else{
if (webSocketMap.containsKey(userId)){
webSocketMap.get(userId).sendMessage(JSON.toJSONString(new JSONObject().fluentPut("info","管理员已同意你的验证信息,请重新登录")));
redisTemplate.delete(StringConstant.NO_VERIFY_PRE + userId);
Verify verify1 = new Verify();
verify.setVerifyPhone("");
verify.setVerifyName("");
verifyMapper.update(verify1, new LambdaQueryWrapper<Verify>().eq(Verify::getStoreId, userId));
}
return R.success(new JSONObject().fluentPut("info","你已同意该商户的验证信息"));
}
}
private R<JSONObject> getTime(String userId) {
Long expire = redisTemplate.getExpire(StringConstant.VERIFY_PRE + userId);
assert expire != null;
if (expire.equals(-2L)){
Object o = redisTemplate.opsForValue().get(StringConstant.NO_VERIFY_PRE + userId);
if (o != null){
return R.success(new JSONObject().fluentPut("info","当前用户登录已过期"));
}
return R.failed(HttpCodes.HTTP_CODES500,new JSONObject().fluentPut("info","没有该用户登录信息"));
}else{
return R.success(new JSONObject().fluentPut("info",expire));
}
}
private R<JSONObject> addVerifyInfo(String userId, JSONObject parse) {
Long expire = redisTemplate.getExpire(StringConstant.VERIFY_PRE + userId);
Object o = redisTemplate.opsForValue().get(StringConstant.NO_VERIFY_PRE + userId);
assert expire != null;
if (expire.equals(-2L) && o != null){
Object verifyName = parse.get("verifyName");
Object verifyPhone = parse.get("verifyPhone");
Verify verify = new Verify();
verify.setVerifyName(String.valueOf(verifyName));
verify.setVerifyPhone(String.valueOf(verifyPhone));
int update = verifyMapper.update(verify, new LambdaQueryWrapper<Verify>().eq(Verify::getStoreId, userId));
return update == 1 ? R.success(new JSONObject().fluentPut("info","验证信息添加成功,请耐心等待管理员审核")) : R.failed(HttpCodes.HTTP_CODES500,new JSONObject().fluentPut("info","添加验证信息失败"));
}
return R.failed(HttpCodes.HTTP_CODES500,new JSONObject().fluentPut("info","当前用户还未过期或者未登陆过"));
}
private R<JSONObject> ping(String userId) {
return R.success(new JSONObject().fluentPut("info","pong").fluentPut("time",redisTemplate.getExpire(StringConstant.VERIFY_PRE + userId)));
}
public List<String> getExpireTimes(Enumeration<String> keys){
List<String> expireUser = new ArrayList<>();
// Set<String> keys = redisTemplate.keys(StringConstant.VERIFY_PRE + "*");
assert keys != null;
Iterator<String> iterator = keys.asIterator();
while (iterator.hasNext()){
String e = StringConstant.VERIFY_PRE + iterator.next();
if (Objects.equals(redisTemplate.getExpire(e), -1L)){
expireUser.add(e);
redisTemplate.delete(e);
}else if (Objects.equals(redisTemplate.getExpire(e),-2L)){
expireUser.add(e);
redisTemplate.delete(e);
}
}
return expireUser;
}
}

View File

@ -1,104 +0,0 @@
package top.xinsin.util;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.excel.read.processor.AnalysisEventProcessor;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import top.xinsin.mapper.OrderMapper;
import top.xinsin.pojo.Order;
import top.xinsin.pojo.OrderByExcel;
import top.xinsin.service.OrderService;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* @author xinsin
* Created On 2023/4/22 22:44
* @version 1.0
*/
@Slf4j
public class ExcelParserUtil extends AnalysisEventListener<OrderByExcel> {
/**
* 每次读取的最大数据条数
*/
private static final int MAX_BATCH_COUNT = 100;
/**
* 泛型bean属性
*/
private OrderService dynamicService;
/**
* 可接收任何参数的泛型List集合
*/
List<OrderByExcel> list = ListUtils.newArrayListWithExpectedSize(MAX_BATCH_COUNT);
List<Order> total = new ArrayList<>();
/**
* 构造函数注入bean(根据传入的bean动态注入)
*
* @param dynamicService
*/
public ExcelParserUtil(OrderService dynamicService) {
this.dynamicService = dynamicService;
}
@Override
public void invoke(OrderByExcel data, AnalysisContext analysisContext) {
log.info(" ==> 解析一条数据: {}", data);
list.add(data);
if (list.size() > MAX_BATCH_COUNT) {
// 保存数据
saveData();
// 清空list
list.clear();
}
}
/**
* 所有数据解析完成后,会来调用一次
* 作用: 避免最后集合中小于 MAX_BATCH_COUNT 条的数据没有被保存
*
* @param context
*/
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
saveData();
log.info(" ==> 数据解析完成 <==");
}
/**
* 保存数据
*/
private void saveData() {
log.info(" ==> 数据保存开始: {}", list.size());
list.forEach(e -> {
System.out.println(e.getOrderNo());
});
// dynamicService.saveBatch(list);
log.info(" ==> 数据保存结束 <==");
}
/**
* 在转换异常 获取其他异常下会调用本接口我们如果捕捉并手动抛出异常则停止读取如果这里不抛出异常则 继续读取下一行
*
* @param exception
* @param context
* @throws Exception
*/
@Override
public void onException(Exception exception, AnalysisContext context) throws Exception {
log.error(" ==> 数据解析失败,但是继续读取下一行:{}", exception.getMessage());
// 如果是某一个单元格的转换异常 能获取到具体行号
if (exception instanceof ExcelDataConvertException) {
ExcelDataConvertException convertException = (ExcelDataConvertException) exception;
log.error("第{}行,第{}列数据解析异常", convertException.getRowIndex(), convertException.getColumnIndex());
}
}
}

View File

@ -1,61 +0,0 @@
package top.xinsin.util;
/**
* @author xinsin
* Created On 2023/4/3 15:47
* @version 1.0
*/
public enum HttpCodes {
/**
* 200
* 成功执行
*/
HTTP_CODES200(202,"接口执行成功"),
/**
* 500
* 服务器错误
*/
HTTP_CODES500(500,"服务器出现错误,请联系服务器管理员"),
/**
* 401
* 数据错误
*/
HTTP_CODES401(401,"这是一个坏的请求,请重新写入参数"),
/**
* 555
* 数据更新失败
*/
HTTP_CODES555(555,"数据更新失败"),
/**
* 501
* 账号密码错误
*/
HTTP_CODES501(501,"帐号或密码错误!"),
/**
* 250
* token验证错误
*/
INVALID_TOKEN(250,"令牌验证错误"),
/**
* 251
* 无权限访问
*/
ACCESS_DENIED( 251,"无权访问");
private final int code;
private final String message;
HttpCodes(int code, String message) {
this.code = code;
this.message = message;
}
public int getCode() {
return code;
}
public String getMessage() {
return message;
}
}

View File

@ -1,72 +0,0 @@
package top.xinsin.util;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.util.Calendar;
import java.util.Map;
/**
* @author xinsin
* Created On 2023/4/3 15:47
* @version 1.0
*/
public class JWTUtils {
private static final String KEY = "a3Q%b5R@j7kP*9d-v'Y|h-%i(h9J0sU1/o";
/**
* 创建token
* @param map 字段
* @return token
*/
public static String getToken(Map<String,String> map){
Calendar instance = Calendar.getInstance();
//默认两个小时过期
instance.add(Calendar.HOUR,2);
//创建jwt builder
JWTCreator.Builder builder = JWT.create();
//payload
map.forEach(builder::withClaim);
//指定令牌过期时间
return builder.withExpiresAt(instance.getTime())
.sign(Algorithm.HMAC512(KEY));
}
/**
* 验证token是否合法
* @param token token
*/
public static void verify(String token){
JWT.require(Algorithm.HMAC512(KEY)).build().verify(token);
}
/**
* 从token中提取信息
*
* @param token token
* @return token中包含的信息
*/
public static DecodedJWT getTokenInfo(String token) {
return JWT.require(Algorithm.HMAC512(KEY)).build().verify(token);
}
/**
* 判断token与用户名是否对应
*
* @param token token
* @param username 用户名
* @return 是否对应
*/
public static boolean isUser(String token, String username) {
String tokenUsername = getTokenInfo(token).getClaim("username").asString();
return tokenUsername.equals(username);
}
public static Integer getId(String token){
return Integer.valueOf(getTokenInfo(token).getClaim("id").asString());
}
public static Integer getAuth(String token) {
return getTokenInfo(token).getClaim("auth").asInt();
}
}

View File

@ -1,16 +0,0 @@
package top.xinsin.util;
import org.springframework.beans.BeanUtils;
/**
* @author xinsin
* Created On 2023/4/29 21:17
* @version 1.0
*/
public class PojoToVoUtils {
public static <T> T pojoToVo(T filed,Object data){
// BeanUtils.copyProperties();
return (T) new Object();
}
}

View File

@ -1,34 +0,0 @@
package top.xinsin.util;
import lombok.Data;
/**
* @author xinsin
* Created On 2023/4/3 15:45
* @version 1.0
*/
@Data
public class R<T> {
private int status;
private String message;
private T data;
private long timestamp;
public R() {
this.timestamp = System.currentTimeMillis();
}
public static<T> R<T> success(T data){
R<T> rData = new R<>();
rData.setStatus(HttpCodes.HTTP_CODES200.getCode());
rData.setMessage(HttpCodes.HTTP_CODES200.getMessage());
rData.setData(data);
return rData;
}
public static<T> R<T> failed(HttpCodes httpCodes, T data){
R<T> rData = new R<>();
rData.setStatus(httpCodes.getCode());
rData.setMessage(httpCodes.getMessage());
rData.setData(data);
return rData;
}
}

View File

@ -1,11 +0,0 @@
package top.xinsin.util;
public class StringConstant {
public static final String REL_NAME_REGEX = "[一-龥]{2,4}";
public static final String EMAIL_REGEX = "\\w[-\\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\\.)+[A-Za-z]{2,14}";
public static final String USERNAME_REGEX = "[A-Za-z0-9_\\-一-龥]+";
public static final String ID_REGEX = "[0-9]*";
public static final String VERIFY_PRE = "verify_";
public static final String NO_VERIFY_PRE = "no_verify_";
}

View File

@ -0,0 +1,18 @@
[
{
"name": "org.apache.ibatis.logging.slf4j.Slf4jImpl",
"allDeclaredFields": true,
"allDeclaredConstructors": true,
"allDeclaredMethods": true,
"allPublicMethods": true,
"allDeclaredClasses": true
},
{
"name": "org.slf4j.Marker",
"allDeclaredFields": true,
"allDeclaredConstructors": true,
"allDeclaredMethods": true,
"allPublicMethods": true,
"allDeclaredClasses": true
}
]

Some files were not shown because too many files have changed in this diff Show More