refactor: wrong dir name

This commit is contained in:
SOR
2026-08-09 13:42:03 +08:00
parent 2a678d9093
commit d6e8390ed6
86 changed files with 5 additions and 11 deletions
+3
View File
@@ -0,0 +1,3 @@
/gradlew text eol=lf
*.bat text eol=crlf
*.jar binary
+43
View File
@@ -0,0 +1,43 @@
HELP.md
.gradle
build/
!../../gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
src/main/resources/
!src/main/resources/application.yaml
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
out/
!**/src/main/**/out/
!**/src/test/**/out/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/
### Kotlin ###
.kotlin
+55
View File
@@ -0,0 +1,55 @@
plugins {
kotlin("jvm") version "2.3.21"
kotlin("plugin.spring") version "2.3.21"
id("org.springframework.boot") version "4.1.0"
id("io.spring.dependency-management") version "1.1.7"
}
group = "club.itstudio"
version = "0.0.1-SNAPSHOT"
description = "itmanager"
java {
toolchain {
languageVersion = JavaLanguageVersion.of(25)
}
}
repositories {
mavenCentral()
}
dependencies {
implementation("com.auth0:java-jwt:4.4.0")
implementation("com.baomidou:mybatis-plus-spring-boot4-starter:3.5.15")
implementation("org.springframework.boot:spring-boot-starter-amqp")
implementation("org.springframework.boot:spring-boot-starter-data-redis-reactive")
implementation("org.springframework.boot:spring-boot-starter-json")
implementation("org.springframework.boot:spring-boot-starter-mail")
implementation("org.springframework.boot:spring-boot-starter-security")
implementation("org.springframework.boot:spring-boot-starter-validation")
implementation("org.springframework.boot:spring-boot-starter-webflux")
implementation("org.springframework:spring-messaging")
implementation("org.jetbrains.kotlin:kotlin-reflect")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-reactor")
implementation("org.jetbrains.kotlinx:kotlinx-datetime:0.6.0")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.7.1")
implementation("io.projectreactor.kotlin:reactor-kotlin-extensions")
implementation("tools.jackson.module:jackson-module-kotlin")
runtimeOnly("org.mariadb.jdbc:mariadb-java-client")
testImplementation("org.springframework.boot:spring-boot-starter-test")
testImplementation("org.springframework.boot:spring-boot-starter-security-test")
testImplementation("org.jetbrains.kotlin:kotlin-test-junit5")
testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test")
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}
kotlin {
compilerOptions {
freeCompilerArgs.addAll("-Xjsr305=strict", "-Xannotation-default-target=param-property")
}
}
tasks.withType<Test> {
useJUnitPlatform()
}
+2
View File
@@ -0,0 +1,2 @@
kotlin.jvm.target.validation=warning
kotlin.jvm.target=25
Binary file not shown.
+9
View File
@@ -0,0 +1,9 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.6.1-bin.zip
networkTimeout=10000
retries=0
retryBackOffMs=500
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored Executable
+248
View File
@@ -0,0 +1,248 @@
#!/bin/sh
#
# Copyright © 2015 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.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# gradlew 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 gradlew
#
# 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/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/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##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || 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
# 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=SC2039,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=SC2039,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" )
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 optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# 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" "$@"
+82
View File
@@ -0,0 +1,82 @@
@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
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem gradlew startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables, and ensure extensions are enabled
setlocal EnableExtensions
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. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
"%COMSPEC%" /c exit 1
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
"%COMSPEC%" /c exit 1
:execute
@rem Setup the command line
@rem Execute gradlew
@rem endlocal doesn't take effect until after the line is parsed and variables are expanded
@rem which allows us to clear the local environment before executing the java command
endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel
:exitWithErrorLevel
@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts
"%COMSPEC%" /c exit %ERRORLEVEL%
+1
View File
@@ -0,0 +1 @@
rootProject.name = "itmanager"
@@ -0,0 +1,11 @@
package club.itstudio.itmanager
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class ItmanagerApplication
fun main(args: Array<String>) {
runApplication<ItmanagerApplication>(*args)
}
@@ -0,0 +1,15 @@
package club.itstudio.itmanager.config
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
import org.springframework.security.crypto.password.PasswordEncoder
@Configuration
class BeanConfig {
@Bean
fun passwordEncoder(): PasswordEncoder {
return BCryptPasswordEncoder()
}
}
@@ -0,0 +1,60 @@
package club.itstudio.itmanager.config
import kotlinx.serialization.json.Json
import kotlinx.serialization.serializer
import org.springframework.amqp.core.Message
import org.springframework.amqp.core.MessageProperties
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory
import org.springframework.amqp.rabbit.connection.ConnectionFactory
import org.springframework.amqp.rabbit.core.RabbitTemplate
import org.springframework.amqp.support.converter.AbstractMessageConverter
import org.springframework.amqp.support.converter.MessageConverter
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.boot.amqp.autoconfigure.SimpleRabbitListenerContainerFactoryConfigurer
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
@Configuration
class RabbitConfig {
@Bean
fun messageConverter(@Qualifier("kotlinxSerializationJson") json: Json): MessageConverter =
object : AbstractMessageConverter() {
override fun createMessage(obj: Any, messageProperties: MessageProperties): Message {
val serializer = json.serializersModule.serializer(obj::class.java)
val jsonString = json.encodeToString(serializer, obj)
val bytes = jsonString.toByteArray(Charsets.UTF_8)
messageProperties.contentType = MessageProperties.CONTENT_TYPE_JSON
messageProperties.contentLength = bytes.size.toLong()
return Message(bytes, messageProperties)
}
override fun fromMessage(message: Message): Any {
val content = String(message.body, Charsets.UTF_8)
return content
}
}
@Bean
fun rabbitTemplate(
connectionFactory: ConnectionFactory,
messageConverter: MessageConverter
): RabbitTemplate {
val rabbitTemplate = RabbitTemplate(connectionFactory)
rabbitTemplate.messageConverter = messageConverter
return rabbitTemplate
}
@Bean
fun rabbitListenerContainerFactory(
configurer: SimpleRabbitListenerContainerFactoryConfigurer,
connectionFactory: ConnectionFactory,
messageConverter: MessageConverter
): SimpleRabbitListenerContainerFactory {
val factory = SimpleRabbitListenerContainerFactory()
configurer.configure(factory, connectionFactory)
factory.setMessageConverter(messageConverter)
return factory
}
}
@@ -0,0 +1,153 @@
package club.itstudio.itmanager.config
import club.itstudio.itmanager.entity.ApiResponse
import club.itstudio.itmanager.entity.vo.response.AuthorizeVO
import club.itstudio.itmanager.filter.JwtAuthorizeFilter
import club.itstudio.itmanager.service.AccountService
import club.itstudio.itmanager.utils.DateUtils
import club.itstudio.itmanager.utils.JwtUtils
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.encodeToJsonElement
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.security.authentication.ReactiveAuthenticationManager
import org.springframework.security.authentication.UserDetailsRepositoryReactiveAuthenticationManager
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity
import org.springframework.security.config.web.server.SecurityWebFiltersOrder
import org.springframework.security.config.web.server.ServerHttpSecurity
import org.springframework.security.core.userdetails.User
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.security.web.server.SecurityWebFilterChain
import org.springframework.security.web.server.authentication.AuthenticationWebFilter
import org.springframework.security.web.server.authentication.ServerAuthenticationConverter
import org.springframework.security.web.server.context.NoOpServerSecurityContextRepository
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatchers
import org.springframework.web.server.ServerWebExchange
import reactor.core.publisher.Mono
@Configuration
@EnableWebFluxSecurity
class SecurityConfig(
private val jwtUtils: JwtUtils,
private val service: AccountService,
private val jwtAuthorizeFilter: JwtAuthorizeFilter,
private val passwordEncoder: PasswordEncoder
) {
@Bean
fun reactiveAuthenticationManager(): ReactiveAuthenticationManager {
val manager = UserDetailsRepositoryReactiveAuthenticationManager(service)
manager.setPasswordEncoder(passwordEncoder)
return manager
}
@Bean
fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
return http
.authorizeExchange {
it
.pathMatchers(
"/api/v1/auth/relogin"
).authenticated()
.pathMatchers(
"/api/v1/auth/**",
"/ws/**",
"/error"
).permitAll()
.anyExchange()
.authenticated()
}
.addFilterAt(loginAuthenticationFilter(), SecurityWebFiltersOrder.AUTHENTICATION)
.addFilterAt(jwtAuthorizeFilter, SecurityWebFiltersOrder.AUTHENTICATION)
.exceptionHandling {
it.authenticationEntryPoint { exchange, ex ->
writeJsonResponse(
exchange,
HttpStatus.UNAUTHORIZED,
ApiResponse.unauthenticated(ex.message)
)
}
.accessDeniedHandler { exchange, ex ->
writeJsonResponse(
exchange,
HttpStatus.FORBIDDEN,
ApiResponse.forbidden(ex.message)
)
}
}
.csrf { it.disable() }
.securityContextRepository(NoOpServerSecurityContextRepository.getInstance())
.build()
}
@Bean
fun loginAuthenticationFilter(): AuthenticationWebFilter {
val filter = AuthenticationWebFilter(reactiveAuthenticationManager())
filter.setRequiresAuthenticationMatcher(
ServerWebExchangeMatchers.pathMatchers("/api/v1/auth/login")
)
filter.setServerAuthenticationConverter(loginAuthenticationConverter())
filter.setAuthenticationSuccessHandler { webFilterExchange, authentication ->
val user = authentication.principal as User
service.findAccountByNameOrEmail(user.username)
.flatMap { account ->
val vo = account.toAnotherObject(
AuthorizeVO::class,
mapOf(
"token" to jwtUtils.createJwt(user, account.id!!, account.username),
"expire" to DateUtils.dateToLocalDateTime(jwtUtils.expiresTime())
)
)
writeJsonResponse(
webFilterExchange.exchange,
HttpStatus.OK,
ApiResponse.success(vo)
)
}
}
filter.setAuthenticationFailureHandler { webFilterExchange, exception ->
writeJsonResponse(
webFilterExchange.exchange,
HttpStatus.UNAUTHORIZED,
ApiResponse.unauthenticated(exception.message)
)
}
return filter
}
private fun loginAuthenticationConverter(): ServerAuthenticationConverter {
return ServerAuthenticationConverter { exchange ->
exchange.formData.flatMap { formData ->
val username = formData.getFirst("username")
val password = formData.getFirst("password")
if (username != null && password != null) {
Mono.just(
UsernamePasswordAuthenticationToken(
username,
password
)
)
} else {
Mono.empty()
}
}
}
}
private inline fun <reified T> writeJsonResponse(
exchange: ServerWebExchange,
status: HttpStatus,
body: ApiResponse<T>
): Mono<Void> {
val response = exchange.response
response.statusCode = status
response.headers.contentType = MediaType.APPLICATION_JSON
val jsonString = Json.encodeToJsonElement(body).toString()
val buffer = response.bufferFactory().wrap(jsonString.toByteArray())
return response.writeWith(Mono.just(buffer))
}
}
@@ -0,0 +1,17 @@
package club.itstudio.itmanager.config
import kotlinx.serialization.json.Json
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
@Configuration
class SerializationConfig {
@Bean
fun kotlinxSerializationJson(): Json = Json {
ignoreUnknownKeys = true
isLenient = true
encodeDefaults = false
prettyPrint = true
}
}
@@ -0,0 +1,14 @@
package club.itstudio.itmanager.controller
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import reactor.core.publisher.Mono
@RestController
@RequestMapping("/api/test")
class TestController {
@GetMapping("/hello")
fun test(): Mono<String> = Mono.just("Hello Kotlin WebFlux!")
}
@@ -0,0 +1,72 @@
package club.itstudio.itmanager.controller.v1
import club.itstudio.itmanager.entity.ApiResponse
import club.itstudio.itmanager.entity.enums.EmailType
import club.itstudio.itmanager.entity.vo.request.EmailRegisterVO
import club.itstudio.itmanager.entity.vo.request.PasswordResetVO
import club.itstudio.itmanager.service.v1.AuthorizationService
import club.itstudio.itmanager.utils.Const
import jakarta.validation.Valid
import jakarta.validation.constraints.Email
import jakarta.validation.constraints.NotBlank
import org.slf4j.LoggerFactory
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.*
import org.springframework.web.server.ServerWebExchange
import reactor.core.publisher.Mono
@Validated
@RestController
@RequestMapping("/api/v1/auth")
class AuthorizeController(
private val service: AuthorizationService
) {
private val logger = LoggerFactory.getLogger(this::class.java)
@GetMapping("/ask-code")
fun askVerifyCode(
@RequestParam @NotBlank @Email email: String,
@RequestParam type: EmailType,
exchange: ServerWebExchange
): Mono<ApiResponse<Any?>> {
logger.info("Trying to ask code")
val ip = exchange.request.remoteAddress?.address?.hostAddress ?: "unknown"
return service.askEmailVerifyCode(type, email, ip)
.map(Const::messageHandler)
}
@PostMapping("/register")
fun emailRegister(@RequestBody @Valid vo: EmailRegisterVO): Mono<ApiResponse<Any?>> {
logger.info("Trying to register")
return service.registerEmailAccount(vo)
.map(Const::messageHandler)
}
@PostMapping("/reset")
fun emailResetPassword(@RequestBody @Valid vo: PasswordResetVO): Mono<ApiResponse<Any?>> {
logger.info("Trying to reset password")
return service.resetEmailAccountPassword(vo)
.map(Const::messageHandler)
}
@GetMapping("/logout")
fun logout(exchange: ServerWebExchange): Mono<ApiResponse<Any?>> {
logger.info("Trying to logout")
val authorization = exchange.request.headers.getFirst("Authorization")
return Mono.fromCallable { service.invalidateJwt(authorization) }
.map { success ->
if (success) ApiResponse.success()
else ApiResponse.logoutFailed()
}
}
@GetMapping("/relogin")
fun relogin(exchange: ServerWebExchange): Mono<ApiResponse<Any?>> {
logger.info("Trying to relogin")
val authorization = exchange.request.headers.getFirst("Authorization")
return service
.jwtTokenRelogin(authorization)
?.map { ApiResponse.success(it) }
?: Mono.just(ApiResponse.failure(401, null, "Please login with password."))
}
}
@@ -0,0 +1,29 @@
package club.itstudio.itmanager.controller.v1
import club.itstudio.itmanager.utils.Const
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.*
import reactor.core.publisher.Mono
@Validated
@RestController
@RequestMapping("/api/v1/departments")
class DepartmentsController {
// departments/ GET/POST/PUT/DELETE 部门 CRUD 操作
@GetMapping("", "/")
fun getDepartments(): Mono<String> = Const.INTERNAL_ERROR_MONO
@PostMapping("", "/")
fun createDepartment(): Mono<String> = Const.INTERNAL_ERROR_MONO
@PutMapping("", "/")
fun updateDepartment(): Mono<String> = Const.INTERNAL_ERROR_MONO
@DeleteMapping("", "/")
fun deleteDepartment(@RequestParam(required = false) id: String?): Mono<String> = Const.INTERNAL_ERROR_MONO
// departments/{id}/ DELETE 删除部门(发送邮件通知)
@DeleteMapping("/{id}", "/{id}/")
fun deleteById(@PathVariable("id") id: String): Mono<String> = Const.INTERNAL_ERROR_MONO
}
@@ -0,0 +1,23 @@
package club.itstudio.itmanager.controller.v1
import club.itstudio.itmanager.utils.Const
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.*
import reactor.core.publisher.Mono
@Validated
@RestController
@RequestMapping("/api/v1/email")
class EmailController {
// notification-settings/ GET/POST 获取/更新通知设置和邮箱列表
@GetMapping("/notification-settings", "/notification-settings/")
fun getNotificationSettings(): Mono<String> = Const.INTERNAL_ERROR_MONO
@PostMapping("/notification-settings", "/notification-settings/")
fun updateNotificationSettings(): Mono<String> = Const.INTERNAL_ERROR_MONO
// toggle-email-status/ POST 切换邮箱启用/禁用状态
@PostMapping("/toggle-email-status", "/toggle-email-status/")
fun toggleEmailStatus(): Mono<String> = Const.INTERNAL_ERROR_MONO
}
@@ -0,0 +1,46 @@
package club.itstudio.itmanager.controller.v1
import club.itstudio.itmanager.utils.Const
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.*
import reactor.core.publisher.Mono
@Validated
@RestController
@RequestMapping("/api/v1/finance")
class FinanceController {
// finance/ GET/POST/PUT/DELETE 财务记录 CRUD 操作
@GetMapping("", "/")
fun getFinanceRecords(): Mono<String> = Const.INTERNAL_ERROR_MONO
@PostMapping("", "/")
fun createFinanceRecord(): Mono<String> = Const.INTERNAL_ERROR_MONO
@PutMapping("", "/")
fun updateFinanceRecord(): Mono<String> = Const.INTERNAL_ERROR_MONO
@DeleteMapping("", "/")
fun deleteFinanceRecord(@RequestParam(required = false) id: String?): Mono<String> = Const.INTERNAL_ERROR_MONO
// finance/{id}/upload_images/ POST 上传财务凭证图片
@PostMapping("/{id}/upload_images", "/{id}/upload_images/")
fun uploadImages(@PathVariable("id") id: String): Mono<String> = Const.INTERNAL_ERROR_MONO
// finance/{id}/ DELETE 删除财务记录(发送邮件通知)
@DeleteMapping("/{id}", "/{id}/")
fun deleteById(@PathVariable("id") id: String): Mono<String> = Const.INTERNAL_ERROR_MONO
// finance/categories/ GET/POST/PUT/DELETE 财务分类 CRUD 操作
@GetMapping("/categories", "/categories/")
fun getFinanceCategories(): Mono<String> = Const.INTERNAL_ERROR_MONO
@PostMapping("/categories", "/categories/")
fun createFinanceCategory(): Mono<String> = Const.INTERNAL_ERROR_MONO
@PutMapping("/categories", "/categories/")
fun updateFinanceCategory(): Mono<String> = Const.INTERNAL_ERROR_MONO
@DeleteMapping("/categories", "/categories/")
fun deleteFinanceCategory(@RequestParam(required = false) id: String?): Mono<String> = Const.INTERNAL_ERROR_MONO
}
@@ -0,0 +1,178 @@
package club.itstudio.itmanager.controller.v1
import club.itstudio.itmanager.entity.ApiResponse
import club.itstudio.itmanager.entity.dto.Attachment
import club.itstudio.itmanager.entity.dto.Category
import club.itstudio.itmanager.entity.dto.Item
import club.itstudio.itmanager.service.v1.ItemsApiService
import club.itstudio.itmanager.utils.Const
import com.baomidou.mybatisplus.extension.plugins.pagination.Page
import jakarta.validation.Valid
import org.slf4j.LoggerFactory
import org.springframework.http.codec.multipart.FilePart
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.*
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
@Validated
@RestController
@RequestMapping("/api/v1/items")
class ItemsController(
private val service: ItemsApiService
) {
private val logger = LoggerFactory.getLogger(this::class.java)
// items/ GET/POST/PUT/DELETE 物品 CRUD 操作
@GetMapping("", "/")
fun getItems(
@RequestParam(defaultValue = "1") pageNum: Long,
@RequestParam(defaultValue = "10") pageSize: Long,
@RequestParam(required = false) keyword: String?,
@RequestParam(required = false) status: String?
): Mono<ApiResponse<Any?>> {
logger.info("Trying to list items")
val page = Page<Item>(pageNum, pageSize)
return service.getItems(page, keyword, status)
.map { ApiResponse.success(it) }
}
@PostMapping("", "/")
fun createItem(@RequestBody @Valid item: Item): Mono<ApiResponse<Any?>> {
logger.info("Trying to create item")
return service.createItem(item)
.map(Const::messageHandler)
}
@PutMapping("", "/")
fun updateItem(@RequestBody @Valid item: Item): Mono<ApiResponse<Any?>> {
logger.info("Trying to update item")
return service.updateItem(item)
.map(Const::messageHandler)
}
@DeleteMapping("", "/")
fun deleteItem(@RequestParam(required = false) id: Long?): Mono<ApiResponse<Any?>> {
logger.info("Trying to delete item")
return service.deleteItem(id)
.map(Const::messageHandler)
}
// items/{id}/upload_images/ POST 上传物品图片
@PostMapping("/{id}/upload_images", "/{id}/upload_images/")
fun uploadImages(
@PathVariable("id") id: Long,
@RequestPart("files") files: Flux<FilePart>
): Mono<ApiResponse<Any?>> {
logger.info("Trying to upload images for item {}", id)
return service.uploadImages(id, files)
.map(Const::messageHandler)
}
// items/{id}/set_primary_image/ POST 设置主图片
@PostMapping("/{id}/set_primary_image", "/{id}/set_primary_image/")
fun setPrimaryImage(
@PathVariable("id") id: Long,
@RequestParam imageId: Long
): Mono<ApiResponse<Any?>> {
logger.info("Trying to set primary image for item {}", id)
return service.setPrimaryImage(id, imageId)
.map(Const::messageHandler)
}
// items/{id}/borrow/ POST 借用物品
@PostMapping("/{id}/borrow", "/{id}/borrow/")
fun borrowItem(
@PathVariable("id") id: Long,
@RequestParam(defaultValue = "1") quantity: Int
): Mono<ApiResponse<Any?>> {
logger.info("Trying to borrow item {}", id)
return service.borrowItem(id, quantity)
.map(Const::messageHandler)
}
// items/{id}/return_item/ POST 归还物品
@PostMapping("/{id}/return_item", "/{id}/return_item/")
fun returnItem(
@PathVariable("id") id: Long,
@RequestParam(defaultValue = "1") quantity: Int
): Mono<ApiResponse<Any?>> {
logger.info("Trying to return item {}", id)
return service.returnItem(id, quantity)
.map(Const::messageHandler)
}
// items/available/ GET 获取可用物品列表
@GetMapping("/available", "/available/")
fun getAvailableItems(): Mono<ApiResponse<Any?>> {
logger.info("Trying to list available items")
return service.getAvailableItems()
.map { ApiResponse.success(it) }
}
// items/in_use/ GET 获取使用中的物品列表
@GetMapping("/in_use", "/in_use/")
fun getInUseItems(): Mono<ApiResponse<Any?>> {
logger.info("Trying to list in-use items")
return service.getInUseItems()
.map { ApiResponse.success(it) }
}
// items/categories/ GET/POST/PUT/DELETE 物品类别 CRUD 操作
@GetMapping("/categories", "/categories/")
fun getItemCategories(): Mono<ApiResponse<Any?>> {
logger.info("Trying to list item categories")
return service.getItemCategories()
.map { ApiResponse.success(it) }
}
@PostMapping("/categories", "/categories/")
fun createItemCategory(@RequestBody @Valid category: Category): Mono<ApiResponse<Any?>> {
logger.info("Trying to create item category")
return service.createItemCategory(category)
.map(Const::messageHandler)
}
@PutMapping("/categories", "/categories/")
fun updateItemCategory(@RequestBody @Valid category: Category): Mono<ApiResponse<Any?>> {
logger.info("Trying to update item category")
return service.updateItemCategory(category)
.map(Const::messageHandler)
}
@DeleteMapping("/categories", "/categories/")
fun deleteItemCategory(@RequestParam(required = false) id: Long?): Mono<ApiResponse<Any?>> {
logger.info("Trying to delete item category")
return service.deleteItemCategory(id)
.map(Const::messageHandler)
}
// items/images/ GET/POST/PUT/DELETE 物品图片 CRUD 操作
@GetMapping("/images", "/images/")
fun getItemImages(): Mono<ApiResponse<Any?>> {
logger.info("Trying to list item images")
return service.getItemImages()
.map { ApiResponse.success(it) }
}
@PostMapping("/images", "/images/")
fun createItemImage(@RequestBody @Valid attachment: Attachment): Mono<ApiResponse<Any?>> {
logger.info("Trying to create item image")
return service.createItemImage(attachment)
.map(Const::messageHandler)
}
@PutMapping("/images", "/images/")
fun updateItemImage(@RequestBody @Valid attachment: Attachment): Mono<ApiResponse<Any?>> {
logger.info("Trying to update item image")
return service.updateItemImage(attachment)
.map(Const::messageHandler)
}
@DeleteMapping("/images", "/images/")
fun deleteItemImage(@RequestParam(required = false) id: Long?): Mono<ApiResponse<Any?>> {
logger.info("Trying to delete item image")
return service.deleteItemImage(id)
.map(Const::messageHandler)
}
}
@@ -0,0 +1,29 @@
package club.itstudio.itmanager.controller.v1
import club.itstudio.itmanager.utils.Const
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.*
import reactor.core.publisher.Mono
@Validated
@RestController
@RequestMapping("/api/v1/proof-images")
class ProofImagesController {
// proof-images/ GET/POST/PUT/DELETE 财务凭证图片 CRUD 操作
@GetMapping("", "/")
fun getProofImages(): Mono<String> = Const.INTERNAL_ERROR_MONO
@PostMapping("", "/")
fun createProofImage(): Mono<String> = Const.INTERNAL_ERROR_MONO
@PutMapping("", "/")
fun updateProofImage(): Mono<String> = Const.INTERNAL_ERROR_MONO
@DeleteMapping("", "/")
fun deleteProofImage(@RequestParam(required = false) id: String?): Mono<String> = Const.INTERNAL_ERROR_MONO
// proof-images/{id}/ DELETE 删除凭证图片(自动删除物理文件)
@DeleteMapping("/{id}", "/{id}/")
fun deleteById(@PathVariable("id") id: String): Mono<String> = Const.INTERNAL_ERROR_MONO
}
@@ -0,0 +1,50 @@
package club.itstudio.itmanager.controller.v1
import club.itstudio.itmanager.utils.Const
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.*
import reactor.core.publisher.Mono
@Validated
@RestController
@RequestMapping("/api/v1/usages")
class UsagesController {
// usages/ GET/POST/PUT/DELETE 物品使用记录 CRUD 操作
@GetMapping("", "/")
fun getUsages(): Mono<String> = Const.INTERNAL_ERROR_MONO
@PostMapping("", "/")
fun createUsage(): Mono<String> = Const.INTERNAL_ERROR_MONO
@PutMapping("", "/")
fun updateUsage(): Mono<String> = Const.INTERNAL_ERROR_MONO
@DeleteMapping("", "/")
fun deleteUsage(@RequestParam(required = false) id: String?): Mono<String> = Const.INTERNAL_ERROR_MONO
// usages/{id}/upload_images/ POST 上传使用记录图片
@PostMapping("/{id}/upload_images", "/{id}/upload_images/")
fun uploadImages(@PathVariable("id") id: String): Mono<String> = Const.INTERNAL_ERROR_MONO
// usages/current/ GET 获取当前使用中的记录
@GetMapping("/current", "/current/")
fun getCurrentUsages(): Mono<String> = Const.INTERNAL_ERROR_MONO
// usages/by_user/ GET 根据用户姓名获取使用记录
@GetMapping("/by_user", "/by_user/")
fun getUsagesByUser(@RequestParam(required = false) name: String?): Mono<String> = Const.INTERNAL_ERROR_MONO
// usages/images/ GET/POST/PUT/DELETE 使用记录图片 CRUD 操作
@GetMapping("/images", "/images/")
fun getUsageImages(): Mono<String> = Const.INTERNAL_ERROR_MONO
@PostMapping("/images", "/images/")
fun createUsageImage(): Mono<String> = Const.INTERNAL_ERROR_MONO
@PutMapping("/images", "/images/")
fun updateUsageImage(): Mono<String> = Const.INTERNAL_ERROR_MONO
@DeleteMapping("/images", "/images/")
fun deleteUsageImage(@RequestParam(required = false) id: String?): Mono<String> = Const.INTERNAL_ERROR_MONO
}
@@ -0,0 +1,18 @@
package club.itstudio.itmanager.controller.v1
import club.itstudio.itmanager.utils.Const
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import reactor.core.publisher.Mono
@Validated
@RestController
@RequestMapping("/api/v1/users")
class UsersController {
// users/ GET 获取用户列表(只读)
@GetMapping("", "/")
fun getUsers(): Mono<String> = Const.INTERNAL_ERROR_MONO
}
@@ -0,0 +1,41 @@
package club.itstudio.itmanager.entity
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
@Serializable
data class ApiResponse<T>(
val code: Int,
val data: T,
val message: String
) {
companion object {
fun <T> success(data: T, message: String = "Success"): ApiResponse<T> {
return ApiResponse(200, data, message)
}
// 针对无 data 返回的情况,统一使用 Any?
fun success(message: String = "Success"): ApiResponse<Any?> {
return ApiResponse(200, null, message)
}
fun <T> failure(code: Int = 401, data: T, message: String?): ApiResponse<T> {
return ApiResponse(code, data, message ?: "Failure")
}
fun unauthenticated(message: String?) =
failure(401, null, message)
fun forbidden(message: String?) =
failure(403, null, message)
fun logoutFailed(message: String = ""): ApiResponse<Any?> {
val formatMessage = if (message.isBlank()) "" else ": $message"
return failure(400, null, "Logout Failed$formatMessage")
}
}
}
inline fun <reified T> ApiResponse<T>.toJsonString(): String {
return Json.encodeToString(this)
}
@@ -0,0 +1,39 @@
package club.itstudio.itmanager.entity
import kotlin.reflect.KClass
import kotlin.reflect.KMutableProperty1
import kotlin.reflect.KProperty1
import kotlin.reflect.full.createInstance
import kotlin.reflect.full.declaredMemberProperties
import kotlin.reflect.full.memberProperties
import kotlin.reflect.jvm.isAccessible
interface DataCopy {
fun <T : Any> toAnotherObject(
toClass: KClass<T>,
otherProperties: Map<String, Any?> = emptyMap()
): T {
@Suppress("UNCHECKED_CAST")
val sourceProps = this::class.memberProperties
.associate { it.name to (it as KProperty1<Any, *>).get(this) }
return try {
val vo = toClass.createInstance()
for (prop in toClass.declaredMemberProperties) {
@Suppress("UNCHECKED_CAST")
val mutableProp = prop as? KMutableProperty1<Any, Any?> ?: continue
val value = when {
sourceProps.containsKey(prop.name) -> sourceProps[prop.name]
otherProperties.containsKey(prop.name) -> otherProperties[prop.name]
else -> continue
}
mutableProp.isAccessible = true
mutableProp.set(vo, value)
}
vo
} catch (e: ReflectiveOperationException) {
throw RuntimeException(
"Failed to instantiate ${toClass.simpleName}. Does it have a no-arg constructor?", e
)
}
}
}
@@ -0,0 +1,23 @@
package club.itstudio.itmanager.entity.dto
import com.baomidou.mybatisplus.annotation.IdType
import com.baomidou.mybatisplus.annotation.TableId
import com.baomidou.mybatisplus.annotation.TableName
import club.itstudio.itmanager.entity.DataCopy
import kotlinx.datetime.LocalDateTime
import kotlinx.serialization.Serializable
@Serializable
@TableName("account")
data class Account(
@TableId(type = IdType.AUTO)
val id: Long? = null,
val username: String = "",
val password: String = "",
val email: String? = null,
val fullName: String? = null,
val isActive: Boolean = true,
val isStaff: Boolean = false,
val createdAt: LocalDateTime? = null,
val updatedAt: LocalDateTime? = null
) : DataCopy
@@ -0,0 +1,23 @@
package club.itstudio.itmanager.entity.dto
import com.baomidou.mybatisplus.annotation.IdType
import com.baomidou.mybatisplus.annotation.TableId
import com.baomidou.mybatisplus.annotation.TableName
import club.itstudio.itmanager.entity.DataCopy
import kotlinx.datetime.LocalDateTime
import kotlinx.serialization.Serializable
@Serializable
@TableName("attachments")
data class Attachment(
@TableId(type = IdType.AUTO)
val id: Long? = null,
val relatedTable: String? = null,
val relatedId: Long? = null,
val fileName: String? = null,
val filePath: String? = null,
val fileSize: Long? = null,
val contentType: String? = null,
val uploadedBy: Long? = null,
val uploadedAt: LocalDateTime? = null
) : DataCopy
@@ -0,0 +1,26 @@
package club.itstudio.itmanager.entity.dto
import com.baomidou.mybatisplus.annotation.IdType
import com.baomidou.mybatisplus.annotation.TableId
import com.baomidou.mybatisplus.annotation.TableName
import club.itstudio.itmanager.entity.DataCopy
import kotlinx.datetime.LocalDateTime
import kotlinx.serialization.Serializable
@Serializable
@TableName("borrow_records")
data class BorrowRecord(
@TableId(type = IdType.AUTO)
val id: Long? = null,
val itemId: Long = 0,
val borrower: String = "",
val quantity: Int = 1,
val borrowDate: LocalDateTime? = null,
val dueDate: LocalDateTime? = null,
val returnDate: LocalDateTime? = null,
val status: String = "BORROWED", // BORROWED / RETURNED / OVERDUE / CANCELED
val approver: String? = null,
val note: String? = null,
val createdAt: LocalDateTime? = null,
val updatedAt: LocalDateTime? = null
) : DataCopy
@@ -0,0 +1,20 @@
package club.itstudio.itmanager.entity.dto
import com.baomidou.mybatisplus.annotation.IdType
import com.baomidou.mybatisplus.annotation.TableId
import com.baomidou.mybatisplus.annotation.TableName
import club.itstudio.itmanager.entity.DataCopy
import kotlinx.datetime.LocalDateTime
import kotlinx.serialization.Serializable
@Serializable
@TableName("categories")
data class Category(
@TableId(type = IdType.AUTO)
val id: Long? = null,
val name: String = "",
val parentId: Long? = null,
val description: String? = null,
val createdAt: LocalDateTime? = null,
val updatedAt: LocalDateTime? = null
) : DataCopy
@@ -0,0 +1,21 @@
package club.itstudio.itmanager.entity.dto
import com.baomidou.mybatisplus.annotation.IdType
import com.baomidou.mybatisplus.annotation.TableId
import com.baomidou.mybatisplus.annotation.TableName
import club.itstudio.itmanager.entity.DataCopy
import kotlinx.datetime.LocalDateTime
import kotlinx.serialization.Serializable
@Serializable
@TableName("departments")
data class Department(
@TableId(type = IdType.AUTO)
val id: Long? = null,
val name: String = "",
val code: String? = null,
val parentId: Long? = null,
val description: String? = null,
val createdAt: LocalDateTime? = null,
val updatedAt: LocalDateTime? = null
) : DataCopy
@@ -0,0 +1,24 @@
package club.itstudio.itmanager.entity.dto
import com.baomidou.mybatisplus.annotation.IdType
import com.baomidou.mybatisplus.annotation.TableId
import com.baomidou.mybatisplus.annotation.TableName
import club.itstudio.itmanager.entity.DataCopy
import kotlinx.datetime.LocalDateTime
import kotlinx.serialization.Serializable
@Serializable
@TableName("email_notices")
data class EmailNotice(
@TableId(type = IdType.AUTO)
val id: Long? = null,
val name: String? = null,
val targetEmails: String? = null,
val subject: String? = null,
val body: String? = null,
val enabled: Boolean = true,
val scheduleCron: String? = null,
val lastSentAt: LocalDateTime? = null,
val createdAt: LocalDateTime? = null,
val updatedAt: LocalDateTime? = null
) : DataCopy
@@ -0,0 +1,11 @@
package club.itstudio.itmanager.entity.dto
import club.itstudio.itmanager.entity.enums.EmailType
import kotlinx.serialization.Serializable
@Serializable
data class EmailVerificationMsg(
val email: String,
val type: EmailType,
val code: String
)
@@ -0,0 +1,26 @@
package club.itstudio.itmanager.entity.dto
import com.baomidou.mybatisplus.annotation.IdType
import com.baomidou.mybatisplus.annotation.TableId
import com.baomidou.mybatisplus.annotation.TableName
import club.itstudio.itmanager.entity.DataCopy
import kotlinx.datetime.LocalDateTime
import kotlinx.serialization.Serializable
import java.math.BigDecimal
@Serializable
@TableName("finance_records")
data class FinanceRecord(
@TableId(type = IdType.AUTO)
val id: Long? = null,
val recordNo: String? = null,
val type: String = "", // PURCHASE / REFUND / REPAIR / DEPRECIATION / OTHER
val relatedItemId: Long? = null,
val amount: BigDecimal = BigDecimal.ZERO,
val currency: String = "CNY",
val vendor: String? = null,
val occurredAt: LocalDateTime? = null,
val recordedBy: Long? = null,
val note: String? = null,
val createdAt: LocalDateTime? = null
) : DataCopy
@@ -0,0 +1,35 @@
package club.itstudio.itmanager.entity.dto
import com.baomidou.mybatisplus.annotation.IdType
import com.baomidou.mybatisplus.annotation.TableId
import com.baomidou.mybatisplus.annotation.TableName
import club.itstudio.itmanager.entity.DataCopy
import kotlinx.datetime.LocalDate
import kotlinx.datetime.LocalDateTime
import kotlinx.serialization.Serializable
import java.math.BigDecimal
@Serializable
@TableName("items")
data class Item(
@TableId(type = IdType.AUTO)
val id: Long? = null,
val code: String = "",
val name: String = "",
val categoryId: Long? = null,
val model: String? = null,
val brand: String? = null,
val location: String? = null,
val totalQuantity: Int = 0,
val availableQuantity: Int = 0,
val unit: String = "件",
val price: BigDecimal? = null,
val purchaseDate: LocalDate? = null,
val supplier: String? = null,
val status: String = "normal",
val description: String? = null,
val imagePath: String? = null,
val createdBy: Long? = null,
val createdAt: LocalDateTime? = null,
val updatedAt: LocalDateTime? = null
) : DataCopy
@@ -0,0 +1,25 @@
package club.itstudio.itmanager.entity.dto
import com.baomidou.mybatisplus.annotation.IdType
import com.baomidou.mybatisplus.annotation.TableId
import com.baomidou.mybatisplus.annotation.TableName
import club.itstudio.itmanager.entity.DataCopy
import club.itstudio.itmanager.entity.enums.TransactionType
import kotlinx.datetime.LocalDateTime
import kotlinx.serialization.Serializable
@Serializable
@TableName("item_transactions")
data class ItemTransaction(
@TableId(type = IdType.AUTO)
val id: Long? = null,
val itemId: Long = 0,
val transType: TransactionType = TransactionType.IN,
val quantity: Int = 0,
val fromLocation: String? = null,
val toLocation: String? = null,
val relatedId: Long? = null,
val operatorId: Long? = null,
val note: String? = null,
val createdAt: LocalDateTime? = null
) : DataCopy
@@ -0,0 +1,16 @@
package club.itstudio.itmanager.entity.enums
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
enum class AccountRole {
@SerialName("user")
USER,
@SerialName("admin")
ADMIN;
companion object {
fun fromIsStaff(isStaff: Boolean): AccountRole = if (isStaff) ADMIN else USER
}
}
@@ -0,0 +1,13 @@
package club.itstudio.itmanager.entity.enums
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
enum class EmailType {
@SerialName("register")
REGISTER,
@SerialName("reset")
RESET,
}
@@ -0,0 +1,19 @@
package club.itstudio.itmanager.entity.enums
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
enum class TransactionType {
@SerialName("IN")
IN,
@SerialName("OUT")
OUT,
@SerialName("ADJUST")
ADJUST,
@SerialName("TRANSFER")
TRANSFER,
}
@@ -0,0 +1,19 @@
package club.itstudio.itmanager.entity.vo.request
import jakarta.validation.constraints.Email
import jakarta.validation.constraints.Pattern
import kotlinx.serialization.Serializable
import org.hibernate.validator.constraints.Length
@Serializable
data class EmailRegisterVO(
@param:Email
val email: String = "",
@param:Length(min = 6, max = 6)
val code: String? = null,
@param:Pattern(regexp = "^[a-zA-Z0-9\\u4e00-\\u9fa5]+$")
@param:Length(min = 4, max = 16)
val username: String = "",
@param:Length(min = 6, max = 20)
val password: String = "",
)
@@ -0,0 +1,15 @@
package club.itstudio.itmanager.entity.vo.request
import jakarta.validation.constraints.Email
import kotlinx.serialization.Serializable
import org.hibernate.validator.constraints.Length
@Serializable
data class PasswordResetVO(
@param:Email
val email: String = "",
@param:Length(min = 6, max = 6)
val code: String? = null,
@param:Length(min = 6, max = 20)
val password: String = "",
)
@@ -0,0 +1,13 @@
package club.itstudio.itmanager.entity.vo.response
import club.itstudio.itmanager.utils.DateUtils.getCurrentDateTime
import kotlinx.datetime.LocalDateTime
import kotlinx.serialization.Serializable
@Serializable
data class AuthorizeVO(
val username: String = "",
val role: String = "",
val token: String = "",
val expire: LocalDateTime = getCurrentDateTime(),
)
@@ -0,0 +1,9 @@
package club.itstudio.itmanager.entity.vo.response
import kotlinx.serialization.Serializable
@Serializable
data class ReloginVO(
val token: String = "",
val expire: String = "",
)
@@ -0,0 +1,23 @@
package club.itstudio.itmanager.exception
import club.itstudio.itmanager.entity.ApiResponse
import jakarta.validation.ValidationException
import org.slf4j.LoggerFactory
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.RestControllerAdvice
@RestControllerAdvice
class ValidationController {
private val log = LoggerFactory.getLogger(ValidationController::class.java)
@ExceptionHandler(ValidationException::class)
fun validationException(e: Exception): ApiResponse<out String?> {
log.warn("Resolve [${e.javaClass.name}: ${e.message}]")
return ApiResponse.failure(
400,
null,
"parameter validation error"
)
}
}
@@ -0,0 +1,38 @@
package club.itstudio.itmanager.filter
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpMethod
import org.springframework.web.cors.CorsConfiguration
import org.springframework.web.cors.reactive.CorsWebFilter
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource
@Configuration
class CorsFilter {
@Bean
fun corsWebFilter(): CorsWebFilter {
val config = CorsConfiguration().apply {
allowedOriginPatterns = listOf("*")
allowedMethods = listOf(
HttpMethod.GET.name(),
HttpMethod.POST.name(),
HttpMethod.PUT.name(),
HttpMethod.DELETE.name(),
HttpMethod.OPTIONS.name()
)
allowedHeaders = listOf(
HttpHeaders.AUTHORIZATION,
HttpHeaders.CONTENT_TYPE
)
allowCredentials = true
}
val source = UrlBasedCorsConfigurationSource().apply {
registerCorsConfiguration("/**", config)
}
return CorsWebFilter(source)
}
}
@@ -0,0 +1,81 @@
package club.itstudio.itmanager.filter
import club.itstudio.itmanager.entity.ApiResponse
import club.itstudio.itmanager.entity.toJsonString
import club.itstudio.itmanager.utils.Const
import org.springframework.beans.factory.annotation.Value
import org.springframework.core.annotation.Order
import org.springframework.data.redis.core.ReactiveStringRedisTemplate
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.stereotype.Component
import org.springframework.web.server.ServerWebExchange
import org.springframework.web.server.WebFilter
import org.springframework.web.server.WebFilterChain
import reactor.core.publisher.Mono
import java.time.Duration
@Component
@Order(Const.FLOW_LIMIT_ORDER)
class FlowLimitFilter(
private val template: ReactiveStringRedisTemplate,
@param:Value($$"${app.flow-limit.count}")
private val limitCount: Int,
@param:Value($$"${app.flow-limit.limit-time}")
private val limitTime: Int,
@param:Value($$"${app.flow-limit.ban-time}")
private val expireTime: Int,
) : WebFilter {
override fun filter(exchange: ServerWebExchange, chain: WebFilterChain): Mono<Void> {
val address = exchange.request.remoteAddress?.address?.hostAddress ?: "unknown"
return tryCount(address).flatMap { allowed ->
if (allowed) {
chain.filter(exchange)
} else {
writeBlockMessage(exchange)
}
}
}
private fun writeBlockMessage(exchange: ServerWebExchange): Mono<Void> {
val response = exchange.response
response.statusCode = HttpStatus.FORBIDDEN
response.headers.contentType = MediaType.APPLICATION_JSON
val buffer = response.bufferFactory()
.wrap(ApiResponse.forbidden("Too many requests").toJsonString().toByteArray())
return response.writeWith(Mono.just(buffer))
}
private fun tryCount(ip: String): Mono<Boolean> {
val blockKey = Const.FLOW_LIMIT_BLOCK + ip
val counterKey = Const.FLOW_LIMIT_COUNTER + ip
return template.hasKey(blockKey).flatMap { isBlocked ->
if (isBlocked) {
Mono.just(false)
} else {
template.opsForValue().increment(counterKey).flatMap { count ->
if (count == 1L) {
template.expire(
counterKey,
Duration.ofSeconds(limitTime.toLong())
).thenReturn(true)
} else if (count > limitCount) {
template.opsForValue()
.set(
blockKey,
"1",
Duration.ofSeconds(expireTime.toLong())
)
.thenReturn(false)
} else {
Mono.just(true)
}
}
}
}
}
}
@@ -0,0 +1,37 @@
package club.itstudio.itmanager.filter
import club.itstudio.itmanager.utils.JwtUtils
import org.springframework.http.HttpHeaders
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.context.ReactiveSecurityContextHolder
import org.springframework.stereotype.Component
import org.springframework.web.server.ServerWebExchange
import org.springframework.web.server.WebFilter
import org.springframework.web.server.WebFilterChain
import reactor.core.publisher.Mono
@Component
class JwtAuthorizeFilter(
private val utils: JwtUtils
) : WebFilter {
override fun filter(exchange: ServerWebExchange, chain: WebFilterChain): Mono<Void> {
val authorization = exchange.request.headers.getFirst(HttpHeaders.AUTHORIZATION)
val jwt = utils.resolveJwt(authorization)
return if (jwt != null) {
val user = utils.toUser(jwt)
val authentication = UsernamePasswordAuthenticationToken(
user,
null,
user.authorities
)
exchange.attributes["id"] = utils.toId(jwt)
chain.filter(exchange)
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(authentication))
} else {
chain.filter(exchange)
}
}
}
@@ -0,0 +1,58 @@
package club.itstudio.itmanager.listener
import club.itstudio.itmanager.entity.dto.EmailVerificationMsg
import club.itstudio.itmanager.entity.enums.EmailType
import kotlinx.serialization.json.Json
import org.slf4j.LoggerFactory
import org.springframework.amqp.rabbit.annotation.RabbitHandler
import org.springframework.amqp.rabbit.annotation.RabbitListener
import org.springframework.beans.factory.annotation.Value
import org.springframework.mail.SimpleMailMessage
import org.springframework.mail.javamail.JavaMailSender
import org.springframework.stereotype.Component
@Component
@RabbitListener(queues = ["mail"])
class MailQueueListener(
@param:Value($$"${spring.mail.username}")
private val username: String,
private val json: Json,
private val sender: JavaMailSender
) {
private val logger = LoggerFactory.getLogger(this::class.java)
@RabbitHandler
fun senderMailMessage(content: String) {
val data = json.decodeFromString<EmailVerificationMsg>(content)
val (email, type, code) = data
val message = when (type) {
EmailType.REGISTER -> createMailMessage(
"Welcome to Our Service",
"Thank you for registering! Your verification code is: $code"
+ "\nThis code is valid for 3 minutes.",
email
)
EmailType.RESET -> createMailMessage(
"Password Reset Request",
"You requested a password reset. Your verification code is: $code"
+ "\nThis code is valid for 3 minutes.",
email
)
}
sender.send(message)
logger.info("Email sent to $email.")
}
fun createMailMessage(title: String, content: String, to: String): SimpleMailMessage {
val message = SimpleMailMessage()
message.subject = title
message.text = content
message.from = username
message.setTo(to)
return message
}
}
@@ -0,0 +1,8 @@
package club.itstudio.itmanager.mapper
import com.baomidou.mybatisplus.core.mapper.BaseMapper
import club.itstudio.itmanager.entity.dto.Account
import org.apache.ibatis.annotations.Mapper
@Mapper
interface AccountMapper : BaseMapper<Account>
@@ -0,0 +1,8 @@
package club.itstudio.itmanager.mapper
import com.baomidou.mybatisplus.core.mapper.BaseMapper
import club.itstudio.itmanager.entity.dto.Attachment
import org.apache.ibatis.annotations.Mapper
@Mapper
interface AttachmentMapper : BaseMapper<Attachment>
@@ -0,0 +1,8 @@
package club.itstudio.itmanager.mapper
import com.baomidou.mybatisplus.core.mapper.BaseMapper
import club.itstudio.itmanager.entity.dto.BorrowRecord
import org.apache.ibatis.annotations.Mapper
@Mapper
interface BorrowRecordMapper : BaseMapper<BorrowRecord>
@@ -0,0 +1,8 @@
package club.itstudio.itmanager.mapper
import com.baomidou.mybatisplus.core.mapper.BaseMapper
import club.itstudio.itmanager.entity.dto.Category
import org.apache.ibatis.annotations.Mapper
@Mapper
interface CategoryMapper : BaseMapper<Category>
@@ -0,0 +1,8 @@
package club.itstudio.itmanager.mapper
import com.baomidou.mybatisplus.core.mapper.BaseMapper
import club.itstudio.itmanager.entity.dto.Department
import org.apache.ibatis.annotations.Mapper
@Mapper
interface DepartmentMapper : BaseMapper<Department>
@@ -0,0 +1,8 @@
package club.itstudio.itmanager.mapper
import com.baomidou.mybatisplus.core.mapper.BaseMapper
import club.itstudio.itmanager.entity.dto.EmailNotice
import org.apache.ibatis.annotations.Mapper
@Mapper
interface EmailNoticeMapper : BaseMapper<EmailNotice>
@@ -0,0 +1,8 @@
package club.itstudio.itmanager.mapper
import com.baomidou.mybatisplus.core.mapper.BaseMapper
import club.itstudio.itmanager.entity.dto.FinanceRecord
import org.apache.ibatis.annotations.Mapper
@Mapper
interface FinanceRecordMapper : BaseMapper<FinanceRecord>
@@ -0,0 +1,8 @@
package club.itstudio.itmanager.mapper
import com.baomidou.mybatisplus.core.mapper.BaseMapper
import club.itstudio.itmanager.entity.dto.Item
import org.apache.ibatis.annotations.Mapper
@Mapper
interface ItemMapper : BaseMapper<Item>
@@ -0,0 +1,8 @@
package club.itstudio.itmanager.mapper
import com.baomidou.mybatisplus.core.mapper.BaseMapper
import club.itstudio.itmanager.entity.dto.ItemTransaction
import org.apache.ibatis.annotations.Mapper
@Mapper
interface ItemTransactionMapper : BaseMapper<ItemTransaction>
@@ -0,0 +1,22 @@
package club.itstudio.itmanager.service
import com.baomidou.mybatisplus.extension.service.IService
import club.itstudio.itmanager.entity.dto.Account
import club.itstudio.itmanager.entity.vo.request.EmailRegisterVO
import club.itstudio.itmanager.entity.vo.request.PasswordResetVO
import club.itstudio.itmanager.entity.vo.response.ReloginVO
import org.springframework.security.core.userdetails.ReactiveUserDetailsService
import reactor.core.publisher.Mono
interface AccountService : IService<Account>, ReactiveUserDetailsService {
fun findAccountByNameOrEmail(text: String): Mono<Account>
fun findAccountByName(username: String): Mono<Account>
fun findAccountByEmail(email: String): Mono<Account>
fun existAccountByName(username: String): Mono<Boolean>
fun existAccountByEmail(email: String): Mono<Boolean>
fun resetPasswordByEmail(email: String, encodedPassword: String): Mono<Void>
// fun batchInsert(accounts: List<Account>): Mono<Boolean>
// fun replaceAll(accounts: List<Account>): Mono<Boolean>
// fun exportAll(): Mono<List<Account>>
}
@@ -0,0 +1,15 @@
package club.itstudio.itmanager.service
import com.baomidou.mybatisplus.extension.service.IService
import club.itstudio.itmanager.entity.dto.Attachment
import reactor.core.publisher.Mono
interface AttachmentService : IService<Attachment> {
fun getAttachmentById(id: Long): Mono<Attachment>
fun listByRelated(relatedTable: String, relatedId: Long): Mono<List<Attachment>>
fun listByUploader(uploadedBy: Long): Mono<List<Attachment>>
fun createAttachment(attachment: Attachment): Mono<Boolean>
fun deleteAttachment(id: Long): Mono<Boolean>
fun deleteByRelated(relatedTable: String, relatedId: Long): Mono<Boolean>
fun exportAllAttachments(): Mono<List<Attachment>>
}
@@ -0,0 +1,17 @@
package club.itstudio.itmanager.service
import com.baomidou.mybatisplus.extension.service.IService
import club.itstudio.itmanager.entity.dto.BorrowRecord
import reactor.core.publisher.Mono
interface BorrowRecordService : IService<BorrowRecord> {
fun getBorrowRecordById(id: Long): Mono<BorrowRecord>
fun listByItem(itemId: Long): Mono<List<BorrowRecord>>
fun listByBorrower(borrower: String): Mono<List<BorrowRecord>>
fun listByStatus(status: String): Mono<List<BorrowRecord>>
fun listOverdueRecords(): Mono<List<BorrowRecord>>
fun createBorrowRecord(record: BorrowRecord): Mono<Boolean>
fun updateBorrowRecord(record: BorrowRecord): Mono<Boolean>
fun deleteBorrowRecord(id: Long): Mono<Boolean>
fun exportAllBorrowRecords(): Mono<List<BorrowRecord>>
}
@@ -0,0 +1,15 @@
package club.itstudio.itmanager.service
import com.baomidou.mybatisplus.extension.service.IService
import club.itstudio.itmanager.entity.dto.Category
import reactor.core.publisher.Mono
interface CategoryService : IService<Category> {
fun getCategoryById(id: Long): Mono<Category>
fun listAllCategories(): Mono<List<Category>>
fun listByParentId(parentId: Long): Mono<List<Category>>
fun createCategory(category: Category): Mono<Boolean>
fun updateCategory(category: Category): Mono<Boolean>
fun deleteCategory(id: Long): Mono<Boolean>
fun exportAllCategories(): Mono<List<Category>>
}
@@ -0,0 +1,15 @@
package club.itstudio.itmanager.service
import com.baomidou.mybatisplus.extension.service.IService
import club.itstudio.itmanager.entity.dto.Department
import reactor.core.publisher.Mono
interface DepartmentService : IService<Department> {
fun getDepartmentById(id: Long): Mono<Department>
fun listAllDepartments(): Mono<List<Department>>
fun listByParentId(parentId: Long): Mono<List<Department>>
fun createDepartment(department: Department): Mono<Boolean>
fun updateDepartment(department: Department): Mono<Boolean>
fun deleteDepartment(id: Long): Mono<Boolean>
fun exportAllDepartments(): Mono<List<Department>>
}
@@ -0,0 +1,16 @@
package club.itstudio.itmanager.service
import com.baomidou.mybatisplus.extension.service.IService
import club.itstudio.itmanager.entity.dto.EmailNotice
import reactor.core.publisher.Mono
interface EmailNoticeService : IService<EmailNotice> {
fun getEmailNoticeById(id: Long): Mono<EmailNotice>
fun listAllNotices(): Mono<List<EmailNotice>>
fun listEnabledNotices(): Mono<List<EmailNotice>>
fun createEmailNotice(notice: EmailNotice): Mono<Boolean>
fun updateEmailNotice(notice: EmailNotice): Mono<Boolean>
fun deleteEmailNotice(id: Long): Mono<Boolean>
fun toggleEnabled(id: Long): Mono<Boolean>
fun exportAllEmailNotices(): Mono<List<EmailNotice>>
}
@@ -0,0 +1,17 @@
package club.itstudio.itmanager.service
import com.baomidou.mybatisplus.extension.service.IService
import club.itstudio.itmanager.entity.dto.FinanceRecord
import reactor.core.publisher.Mono
interface FinanceRecordService : IService<FinanceRecord> {
fun getFinanceRecordById(id: Long): Mono<FinanceRecord>
fun listByType(type: String): Mono<List<FinanceRecord>>
fun listByDateRange(start: String, end: String): Mono<List<FinanceRecord>>
fun listByVendor(vendor: String): Mono<List<FinanceRecord>>
fun listByRelatedItem(itemId: Long): Mono<List<FinanceRecord>>
fun createFinanceRecord(record: FinanceRecord): Mono<Boolean>
fun updateFinanceRecord(record: FinanceRecord): Mono<Boolean>
fun deleteFinanceRecord(id: Long): Mono<Boolean>
fun exportAllFinanceRecords(): Mono<List<FinanceRecord>>
}
@@ -0,0 +1,23 @@
package club.itstudio.itmanager.service
import com.baomidou.mybatisplus.extension.plugins.pagination.Page
import com.baomidou.mybatisplus.extension.service.IService
import club.itstudio.itmanager.entity.dto.Item
import reactor.core.publisher.Mono
interface ItemService : IService<Item> {
fun pageItems(page: Page<Item>, keyword: String?, status: String?): Mono<Page<Item>>
fun getItemById(id: Long): Mono<Item>
fun listAvailableItems(): Mono<List<Item>>
fun listInUseItems(): Mono<List<Item>>
fun listItemsByCategory(categoryId: Long): Mono<List<Item>>
fun createItem(item: Item): Mono<Boolean>
fun updateItem(item: Item): Mono<Boolean>
fun removeItemById(id: Long): Mono<Boolean>
fun setPrimaryImage(id: Long, imagePath: String): Mono<Boolean>
fun borrowItem(id: Long, quantity: Int): Mono<Boolean>
fun returnItem(id: Long, quantity: Int): Mono<Boolean>
fun batchInsertItems(items: List<Item>): Mono<Boolean>
fun replaceAllItems(items: List<Item>): Mono<Boolean>
fun exportAllItems(): Mono<List<Item>>
}
@@ -0,0 +1,16 @@
package club.itstudio.itmanager.service
import com.baomidou.mybatisplus.extension.service.IService
import club.itstudio.itmanager.entity.dto.ItemTransaction
import reactor.core.publisher.Mono
interface ItemTransactionService : IService<ItemTransaction> {
fun getTransactionById(id: Long): Mono<ItemTransaction>
fun listByItem(itemId: Long): Mono<List<ItemTransaction>>
fun listByType(transType: String): Mono<List<ItemTransaction>>
fun listByOperator(operatorId: Long): Mono<List<ItemTransaction>>
fun createTransaction(transaction: ItemTransaction): Mono<Boolean>
fun updateTransaction(transaction: ItemTransaction): Mono<Boolean>
fun deleteTransaction(id: Long): Mono<Boolean>
fun exportAllTransactions(): Mono<List<ItemTransaction>>
}
@@ -0,0 +1,144 @@
package club.itstudio.itmanager.service.impl
import club.itstudio.itmanager.entity.dto.Account
import club.itstudio.itmanager.entity.enums.AccountRole
import club.itstudio.itmanager.mapper.AccountMapper
import club.itstudio.itmanager.service.AccountService
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
import org.slf4j.LoggerFactory
import org.springframework.security.core.userdetails.User
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.security.core.userdetails.UsernameNotFoundException
import org.springframework.stereotype.Service
import reactor.core.publisher.Mono
import reactor.core.scheduler.Schedulers
import javax.security.auth.login.AccountNotFoundException
import kotlin.jvm.java
@Service
class AccountServiceImpl : ServiceImpl<AccountMapper, Account>(), AccountService {
private val logger = LoggerFactory.getLogger(this::class.java)
override fun findByUsername(
username: String
): Mono<UserDetails> {
return findAccountByName(username)
.map {
User.withUsername(it.username)
.password(it.password)
.roles(AccountRole.fromIsStaff(it.isStaff).name)
.build()
}
.onErrorMap(
AccountNotFoundException::class.java
) {
UsernameNotFoundException(
"User not found"
)
}
}
override fun findAccountByName(username: String): Mono<Account> =
findAccount("username") {
ktQuery()
.eq(Account::username, username)
.one()
}
override fun findAccountByEmail(email: String): Mono<Account> =
findAccount("email") {
ktQuery()
.eq(Account::email, email)
.one()
}
private fun <T : Any> blockingCall(
block: () -> T?
): Mono<T> =
Mono.fromCallable(block)
.subscribeOn(Schedulers.boundedElastic())
private fun findAccount(
fieldName: String,
query: () -> Account?
): Mono<Account> {
return blockingCall {
logger.info(
"Searching account by {}",
fieldName
)
query()
}.switchIfEmpty(
Mono.error(
AccountNotFoundException()
)
)
}
override fun findAccountByNameOrEmail(
text: String
): Mono<Account> {
return blockingCall {
logger.info(
"Searching account by identifier"
)
ktQuery()
.and {
it.eq(Account::email, text)
.or()
.eq(Account::username, text)
}
.one()
}.switchIfEmpty(
Mono.error(AccountNotFoundException())
)
}
override fun existAccountByName(
username: String
): Mono<Boolean> {
return blockingCall {
ktQuery()
.eq(Account::username, username)
.exists()
}
}
override fun existAccountByEmail(
email: String
): Mono<Boolean> {
return blockingCall {
ktQuery()
.eq(Account::email, email)
.exists()
}
}
override fun resetPasswordByEmail(
email: String,
encodedPassword: String
): Mono<Void> {
return blockingCall {
ktUpdate()
.eq(Account::email, email)
.set(
Account::password,
encodedPassword
)
.update()
}
.flatMap { updated ->
if (updated) {
Mono.empty()
} else {
Mono.error(
AccountNotFoundException()
)
}
}
}
}
@@ -0,0 +1,62 @@
package club.itstudio.itmanager.service.impl
import club.itstudio.itmanager.entity.dto.Attachment
import club.itstudio.itmanager.mapper.AttachmentMapper
import club.itstudio.itmanager.service.AttachmentService
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
import reactor.core.publisher.Mono
import reactor.core.scheduler.Schedulers
import java.util.NoSuchElementException
@Service
class AttachmentServiceImpl : ServiceImpl<AttachmentMapper, Attachment>(), AttachmentService {
private val logger = LoggerFactory.getLogger(this::class.java)
private fun <T : Any> blockingCall(block: () -> T?): Mono<T> =
Mono.fromCallable(block).subscribeOn(Schedulers.boundedElastic())
override fun getAttachmentById(id: Long): Mono<Attachment> =
blockingCall {
logger.info("Searching attachment by id")
ktQuery().eq(Attachment::id, id).one()
}.switchIfEmpty(Mono.error(NoSuchElementException("Attachment not found")))
override fun listByRelated(relatedTable: String, relatedId: Long): Mono<List<Attachment>> =
blockingCall {
logger.info("Searching attachments by related table and id")
ktQuery().eq(Attachment::relatedTable, relatedTable).eq(Attachment::relatedId, relatedId).list()
}
override fun listByUploader(uploadedBy: Long): Mono<List<Attachment>> =
blockingCall {
logger.info("Searching attachments by uploader")
ktQuery().eq(Attachment::uploadedBy, uploadedBy).list()
}
override fun createAttachment(attachment: Attachment): Mono<Boolean> =
blockingCall {
logger.info("Creating attachment")
save(attachment)
}
override fun deleteAttachment(id: Long): Mono<Boolean> =
blockingCall {
logger.info("Deleting attachment by id")
removeById(id)
}
override fun deleteByRelated(relatedTable: String, relatedId: Long): Mono<Boolean> =
blockingCall {
logger.info("Deleting attachments by related table and id")
remove(ktQuery().eq(Attachment::relatedTable, relatedTable).eq(Attachment::relatedId, relatedId))
}
override fun exportAllAttachments(): Mono<List<Attachment>> =
blockingCall {
logger.info("Exporting all attachments")
list()
}
}
@@ -0,0 +1,74 @@
package club.itstudio.itmanager.service.impl
import club.itstudio.itmanager.entity.dto.BorrowRecord
import club.itstudio.itmanager.mapper.BorrowRecordMapper
import club.itstudio.itmanager.service.BorrowRecordService
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
import reactor.core.publisher.Mono
import reactor.core.scheduler.Schedulers
import java.util.NoSuchElementException
@Service
class BorrowRecordServiceImpl : ServiceImpl<BorrowRecordMapper, BorrowRecord>(), BorrowRecordService {
private val logger = LoggerFactory.getLogger(this::class.java)
private fun <T : Any> blockingCall(block: () -> T?): Mono<T> =
Mono.fromCallable(block).subscribeOn(Schedulers.boundedElastic())
override fun getBorrowRecordById(id: Long): Mono<BorrowRecord> =
blockingCall {
logger.info("Searching borrow record by id")
ktQuery().eq(BorrowRecord::id, id).one()
}.switchIfEmpty(Mono.error(NoSuchElementException("BorrowRecord not found")))
override fun listByItem(itemId: Long): Mono<List<BorrowRecord>> =
blockingCall {
logger.info("Searching borrow records by item id")
ktQuery().eq(BorrowRecord::itemId, itemId).list()
}
override fun listByBorrower(borrower: String): Mono<List<BorrowRecord>> =
blockingCall {
logger.info("Searching borrow records by borrower")
ktQuery().eq(BorrowRecord::borrower, borrower).list()
}
override fun listByStatus(status: String): Mono<List<BorrowRecord>> =
blockingCall {
logger.info("Searching borrow records by status")
ktQuery().eq(BorrowRecord::status, status).list()
}
override fun listOverdueRecords(): Mono<List<BorrowRecord>> =
blockingCall {
logger.info("Searching overdue borrow records")
ktQuery().eq(BorrowRecord::status, "OVERDUE").list()
}
override fun createBorrowRecord(record: BorrowRecord): Mono<Boolean> =
blockingCall {
logger.info("Creating borrow record")
save(record)
}
override fun updateBorrowRecord(record: BorrowRecord): Mono<Boolean> =
blockingCall {
logger.info("Updating borrow record")
updateById(record)
}
override fun deleteBorrowRecord(id: Long): Mono<Boolean> =
blockingCall {
logger.info("Deleting borrow record by id")
removeById(id)
}
override fun exportAllBorrowRecords(): Mono<List<BorrowRecord>> =
blockingCall {
logger.info("Exporting all borrow records")
list()
}
}
@@ -0,0 +1,62 @@
package club.itstudio.itmanager.service.impl
import club.itstudio.itmanager.entity.dto.Category
import club.itstudio.itmanager.mapper.CategoryMapper
import club.itstudio.itmanager.service.CategoryService
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
import reactor.core.publisher.Mono
import reactor.core.scheduler.Schedulers
import java.util.NoSuchElementException
@Service
class CategoryServiceImpl : ServiceImpl<CategoryMapper, Category>(), CategoryService {
private val logger = LoggerFactory.getLogger(this::class.java)
private fun <T : Any> blockingCall(block: () -> T?): Mono<T> =
Mono.fromCallable(block).subscribeOn(Schedulers.boundedElastic())
override fun getCategoryById(id: Long): Mono<Category> =
blockingCall {
logger.info("Searching category by id")
ktQuery().eq(Category::id, id).one()
}.switchIfEmpty(Mono.error(NoSuchElementException("Category not found")))
override fun listAllCategories(): Mono<List<Category>> =
blockingCall {
logger.info("Listing all categories")
list()
}
override fun listByParentId(parentId: Long): Mono<List<Category>> =
blockingCall {
logger.info("Searching categories by parent id")
ktQuery().eq(Category::parentId, parentId).list()
}
override fun createCategory(category: Category): Mono<Boolean> =
blockingCall {
logger.info("Creating category")
save(category)
}
override fun updateCategory(category: Category): Mono<Boolean> =
blockingCall {
logger.info("Updating category")
updateById(category)
}
override fun deleteCategory(id: Long): Mono<Boolean> =
blockingCall {
logger.info("Deleting category by id")
removeById(id)
}
override fun exportAllCategories(): Mono<List<Category>> =
blockingCall {
logger.info("Exporting all categories")
list()
}
}
@@ -0,0 +1,62 @@
package club.itstudio.itmanager.service.impl
import club.itstudio.itmanager.entity.dto.Department
import club.itstudio.itmanager.mapper.DepartmentMapper
import club.itstudio.itmanager.service.DepartmentService
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
import reactor.core.publisher.Mono
import reactor.core.scheduler.Schedulers
import java.util.NoSuchElementException
@Service
class DepartmentServiceImpl : ServiceImpl<DepartmentMapper, Department>(), DepartmentService {
private val logger = LoggerFactory.getLogger(this::class.java)
private fun <T : Any> blockingCall(block: () -> T?): Mono<T> =
Mono.fromCallable(block).subscribeOn(Schedulers.boundedElastic())
override fun getDepartmentById(id: Long): Mono<Department> =
blockingCall {
logger.info("Searching department by id")
ktQuery().eq(Department::id, id).one()
}.switchIfEmpty(Mono.error(NoSuchElementException("Department not found")))
override fun listAllDepartments(): Mono<List<Department>> =
blockingCall {
logger.info("Listing all departments")
list()
}
override fun listByParentId(parentId: Long): Mono<List<Department>> =
blockingCall {
logger.info("Searching departments by parent id")
ktQuery().eq(Department::parentId, parentId).list()
}
override fun createDepartment(department: Department): Mono<Boolean> =
blockingCall {
logger.info("Creating department")
save(department)
}
override fun updateDepartment(department: Department): Mono<Boolean> =
blockingCall {
logger.info("Updating department")
updateById(department)
}
override fun deleteDepartment(id: Long): Mono<Boolean> =
blockingCall {
logger.info("Deleting department by id")
removeById(id)
}
override fun exportAllDepartments(): Mono<List<Department>> =
blockingCall {
logger.info("Exporting all departments")
list()
}
}
@@ -0,0 +1,72 @@
package club.itstudio.itmanager.service.impl
import club.itstudio.itmanager.entity.dto.EmailNotice
import club.itstudio.itmanager.mapper.EmailNoticeMapper
import club.itstudio.itmanager.service.EmailNoticeService
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
import reactor.core.publisher.Mono
import reactor.core.scheduler.Schedulers
import java.util.NoSuchElementException
@Service
class EmailNoticeServiceImpl : ServiceImpl<EmailNoticeMapper, EmailNotice>(), EmailNoticeService {
private val logger = LoggerFactory.getLogger(this::class.java)
private fun <T : Any> blockingCall(block: () -> T?): Mono<T> =
Mono.fromCallable(block).subscribeOn(Schedulers.boundedElastic())
override fun getEmailNoticeById(id: Long): Mono<EmailNotice> =
blockingCall {
logger.info("Searching email notice by id")
ktQuery().eq(EmailNotice::id, id).one()
}.switchIfEmpty(Mono.error(NoSuchElementException("EmailNotice not found")))
override fun listAllNotices(): Mono<List<EmailNotice>> =
blockingCall {
logger.info("Listing all email notices")
list()
}
override fun listEnabledNotices(): Mono<List<EmailNotice>> =
blockingCall {
logger.info("Listing enabled email notices")
ktQuery().eq(EmailNotice::enabled, true).list()
}
override fun createEmailNotice(notice: EmailNotice): Mono<Boolean> =
blockingCall {
logger.info("Creating email notice")
save(notice)
}
override fun updateEmailNotice(notice: EmailNotice): Mono<Boolean> =
blockingCall {
logger.info("Updating email notice")
updateById(notice)
}
override fun deleteEmailNotice(id: Long): Mono<Boolean> =
blockingCall {
logger.info("Deleting email notice by id")
removeById(id)
}
override fun toggleEnabled(id: Long): Mono<Boolean> =
blockingCall {
val notice = ktQuery().eq(EmailNotice::id, id).one()
if (notice != null) {
updateById(notice.copy(enabled = !notice.enabled))
} else {
false
}
}
override fun exportAllEmailNotices(): Mono<List<EmailNotice>> =
blockingCall {
logger.info("Exporting all email notices")
list()
}
}
@@ -0,0 +1,74 @@
package club.itstudio.itmanager.service.impl
import club.itstudio.itmanager.entity.dto.FinanceRecord
import club.itstudio.itmanager.mapper.FinanceRecordMapper
import club.itstudio.itmanager.service.FinanceRecordService
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
import reactor.core.publisher.Mono
import reactor.core.scheduler.Schedulers
import java.util.NoSuchElementException
@Service
class FinanceRecordServiceImpl : ServiceImpl<FinanceRecordMapper, FinanceRecord>(), FinanceRecordService {
private val logger = LoggerFactory.getLogger(this::class.java)
private fun <T : Any> blockingCall(block: () -> T?): Mono<T> =
Mono.fromCallable(block).subscribeOn(Schedulers.boundedElastic())
override fun getFinanceRecordById(id: Long): Mono<FinanceRecord> =
blockingCall {
logger.info("Searching finance record by id")
ktQuery().eq(FinanceRecord::id, id).one()
}.switchIfEmpty(Mono.error(NoSuchElementException("FinanceRecord not found")))
override fun listByType(type: String): Mono<List<FinanceRecord>> =
blockingCall {
logger.info("Searching finance records by type")
ktQuery().eq(FinanceRecord::type, type).list()
}
override fun listByDateRange(start: String, end: String): Mono<List<FinanceRecord>> =
blockingCall {
logger.info("Searching finance records by date range")
ktQuery().apply("occurred_at BETWEEN {0} AND {1}", start, end).list()
}
override fun listByVendor(vendor: String): Mono<List<FinanceRecord>> =
blockingCall {
logger.info("Searching finance records by vendor")
ktQuery().eq(FinanceRecord::vendor, vendor).list()
}
override fun listByRelatedItem(itemId: Long): Mono<List<FinanceRecord>> =
blockingCall {
logger.info("Searching finance records by related item id")
ktQuery().eq(FinanceRecord::relatedItemId, itemId).list()
}
override fun createFinanceRecord(record: FinanceRecord): Mono<Boolean> =
blockingCall {
logger.info("Creating finance record")
save(record)
}
override fun updateFinanceRecord(record: FinanceRecord): Mono<Boolean> =
blockingCall {
logger.info("Updating finance record")
updateById(record)
}
override fun deleteFinanceRecord(id: Long): Mono<Boolean> =
blockingCall {
logger.info("Deleting finance record by id")
removeById(id)
}
override fun exportAllFinanceRecords(): Mono<List<FinanceRecord>> =
blockingCall {
logger.info("Exporting all finance records")
list()
}
}
@@ -0,0 +1,123 @@
package club.itstudio.itmanager.service.impl
import club.itstudio.itmanager.entity.dto.Item
import club.itstudio.itmanager.mapper.ItemMapper
import club.itstudio.itmanager.service.ItemService
import com.baomidou.mybatisplus.extension.plugins.pagination.Page
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
import reactor.core.publisher.Mono
import reactor.core.scheduler.Schedulers
import java.util.NoSuchElementException
@Service
class ItemServiceImpl : ServiceImpl<ItemMapper, Item>(), ItemService {
private val logger = LoggerFactory.getLogger(this::class.java)
private fun <T : Any> blockingCall(block: () -> T?): Mono<T> =
Mono.fromCallable(block).subscribeOn(Schedulers.boundedElastic())
override fun pageItems(page: Page<Item>, keyword: String?, status: String?): Mono<Page<Item>> =
blockingCall {
logger.info("Paging items with keyword and status")
val wrapper = ktQuery()
if (!keyword.isNullOrBlank()) {
wrapper.and {
it.like(Item::name, keyword).or().like(Item::code, keyword)
}
}
if (!status.isNullOrBlank()) {
wrapper.eq(Item::status, status)
}
page(page, wrapper)
}
override fun getItemById(id: Long): Mono<Item> =
blockingCall {
logger.info("Searching item by id")
ktQuery().eq(Item::id, id).one()
}.switchIfEmpty(Mono.error(NoSuchElementException("Item not found")))
override fun listAvailableItems(): Mono<List<Item>> =
blockingCall {
logger.info("Listing available items")
ktQuery().gt(Item::availableQuantity, 0).eq(Item::status, "normal").list()
}
override fun listInUseItems(): Mono<List<Item>> =
blockingCall {
logger.info("Listing in-use items")
ktQuery().apply("total_quantity - available_quantity > 0").list()
}
override fun listItemsByCategory(categoryId: Long): Mono<List<Item>> =
blockingCall {
logger.info("Listing items by category")
ktQuery().eq(Item::categoryId, categoryId).list()
}
override fun createItem(item: Item): Mono<Boolean> =
blockingCall {
logger.info("Creating item")
save(item)
}
override fun updateItem(item: Item): Mono<Boolean> =
blockingCall {
logger.info("Updating item")
updateById(item)
}
override fun removeItemById(id: Long): Mono<Boolean> =
blockingCall {
logger.info("Removing item by id")
removeById(id)
}
override fun setPrimaryImage(id: Long, imagePath: String): Mono<Boolean> =
blockingCall {
logger.info("Setting primary image for item")
ktUpdate().eq(Item::id, id).set(Item::imagePath, imagePath).update()
}
override fun borrowItem(id: Long, quantity: Int): Mono<Boolean> =
blockingCall {
val item = ktQuery().eq(Item::id, id).one()
if (item != null && item.availableQuantity >= quantity) {
ktUpdate().eq(Item::id, id).set(Item::availableQuantity, item.availableQuantity - quantity).update()
} else {
false
}
}
override fun returnItem(id: Long, quantity: Int): Mono<Boolean> =
blockingCall {
val item = ktQuery().eq(Item::id, id).one()
if (item != null && item.totalQuantity >= item.availableQuantity + quantity) {
ktUpdate().eq(Item::id, id).set(Item::availableQuantity, item.availableQuantity + quantity).update()
} else {
false
}
}
override fun batchInsertItems(items: List<Item>): Mono<Boolean> =
blockingCall {
logger.info("Batch inserting items")
saveBatch(items)
}
override fun replaceAllItems(items: List<Item>): Mono<Boolean> =
blockingCall {
logger.info("Replacing all items")
remove(ktQuery())
saveBatch(items)
}
override fun exportAllItems(): Mono<List<Item>> =
blockingCall {
logger.info("Exporting all items")
list()
}
}
@@ -0,0 +1,68 @@
package club.itstudio.itmanager.service.impl
import club.itstudio.itmanager.entity.dto.ItemTransaction
import club.itstudio.itmanager.mapper.ItemTransactionMapper
import club.itstudio.itmanager.service.ItemTransactionService
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
import reactor.core.publisher.Mono
import reactor.core.scheduler.Schedulers
import java.util.NoSuchElementException
@Service
class ItemTransactionServiceImpl : ServiceImpl<ItemTransactionMapper, ItemTransaction>(), ItemTransactionService {
private val logger = LoggerFactory.getLogger(this::class.java)
private fun <T : Any> blockingCall(block: () -> T?): Mono<T> =
Mono.fromCallable(block).subscribeOn(Schedulers.boundedElastic())
override fun getTransactionById(id: Long): Mono<ItemTransaction> =
blockingCall {
logger.info("Searching transaction by id")
ktQuery().eq(ItemTransaction::id, id).one()
}.switchIfEmpty(Mono.error(NoSuchElementException("ItemTransaction not found")))
override fun listByItem(itemId: Long): Mono<List<ItemTransaction>> =
blockingCall {
logger.info("Searching transactions by item id")
ktQuery().eq(ItemTransaction::itemId, itemId).list()
}
override fun listByType(transType: String): Mono<List<ItemTransaction>> =
blockingCall {
logger.info("Searching transactions by type")
ktQuery().eq(ItemTransaction::transType, transType).list()
}
override fun listByOperator(operatorId: Long): Mono<List<ItemTransaction>> =
blockingCall {
logger.info("Searching transactions by operator id")
ktQuery().eq(ItemTransaction::operatorId, operatorId).list()
}
override fun createTransaction(transaction: ItemTransaction): Mono<Boolean> =
blockingCall {
logger.info("Creating transaction")
save(transaction)
}
override fun updateTransaction(transaction: ItemTransaction): Mono<Boolean> =
blockingCall {
logger.info("Updating transaction")
updateById(transaction)
}
override fun deleteTransaction(id: Long): Mono<Boolean> =
blockingCall {
logger.info("Deleting transaction by id")
removeById(id)
}
override fun exportAllTransactions(): Mono<List<ItemTransaction>> =
blockingCall {
logger.info("Exporting all transactions")
list()
}
}
@@ -0,0 +1,148 @@
package club.itstudio.itmanager.service.v1
import club.itstudio.itmanager.entity.dto.Account
import club.itstudio.itmanager.entity.dto.EmailVerificationMsg
import club.itstudio.itmanager.entity.enums.EmailType
import club.itstudio.itmanager.entity.vo.request.EmailRegisterVO
import club.itstudio.itmanager.entity.vo.request.PasswordResetVO
import club.itstudio.itmanager.entity.vo.response.ReloginVO
import club.itstudio.itmanager.service.AccountService
import club.itstudio.itmanager.utils.Const
import club.itstudio.itmanager.utils.DateUtils.getCurrentDateTime
import club.itstudio.itmanager.utils.FlowUtils
import club.itstudio.itmanager.utils.JwtUtils
import org.springframework.amqp.core.AmqpTemplate
import org.springframework.data.redis.core.ReactiveStringRedisTemplate
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.stereotype.Service
import reactor.core.publisher.Mono
import reactor.core.scheduler.Schedulers
import java.time.Duration
@Service
class AuthorizationService(
private val accountService: AccountService,
private val utils: FlowUtils,
private val jwtUtils: JwtUtils,
private val amqpTemplate: AmqpTemplate,
private val stringRedisTemplate: ReactiveStringRedisTemplate,
private val encoder: PasswordEncoder
) {
fun askEmailVerifyCode(type: EmailType, email: String, ip: String): Mono<String> {
return verifyLimit(ip).flatMap { allowed ->
if (allowed) {
val code = (100000..999999).random().toString()
val data = EmailVerificationMsg(email, type, code)
Mono.fromRunnable<Void> {
amqpTemplate.convertAndSend("mail", data)
}.then(
stringRedisTemplate.opsForValue()
.set(
Const.VERIFY_EMAIL_DATA + email,
code,
Duration.ofMinutes(3)
)
).thenReturn("").subscribeOn(Schedulers.boundedElastic())
} else {
Mono.just("Request limit exceeded. Please try again later.")
}
}
}
fun registerEmailAccount(vo: EmailRegisterVO): Mono<String> {
val (email, code, username, password) = vo
return verifyCode(email, code)
.flatMap { result ->
if (result.isNotBlank()) {
return@flatMap Mono.just(result)
}
accountService.existAccountByEmail(email)
.flatMap { emailExists ->
if (emailExists) {
return@flatMap Mono.just("account with the same email already exists.")
}
accountService.existAccountByName(username)
.flatMap { usernameExists ->
if (usernameExists) {
return@flatMap Mono.just("username already exists.")
}
val account = Account(
id = null,
username = username,
password = encoder.encode(password)!!,
email = email,
isStaff = false,
createdAt = getCurrentDateTime()
)
Mono.fromCallable { accountService.save(account) }
.flatMap { success ->
if (success) {
stringRedisTemplate.delete(Const.VERIFY_EMAIL_DATA + email)
.thenReturn("")
} else {
Const.INTERNAL_ERROR_MONO
}
}
}
}
}
}
fun resetEmailAccountPassword(vo: PasswordResetVO): Mono<String> {
val (email, code, password) = vo
val encodedPassword =
encoder.encode(password)
?: return Const.INTERNAL_ERROR_MONO
return verifyCode(email, code)
.then(
accountService.resetPasswordByEmail(
email,
encodedPassword
)
)
.then(
stringRedisTemplate.delete(
Const.VERIFY_EMAIL_DATA + email
)
)
.thenReturn("Password reset successfully")
}
fun jwtTokenRelogin(headerToken: String?): Mono<ReloginVO>? {
val user = jwtUtils.resolveJwt(headerToken?.substring("Bearer ".length))
?.let { jwtUtils.toUser(it) }
?: return null
val accountMono = accountService.findAccountByName(user.username)
val voMono = accountMono.map {
ReloginVO(
jwtUtils.createJwt(user, it.id!!, it.username),
jwtUtils.expiresTime().toInstant().toString()
)
}
return voMono
}
fun invalidateJwt(headerToken: String?): Boolean {
return jwtUtils.invalidateJwt(headerToken)
}
private fun verifyLimit(ip: String): Mono<Boolean> {
val key = Const.VERIFY_EMAIL_LIMIT + ip
return utils.limitOnceCheck(key, 60)
}
private fun verifyCode(email: String, receivedCode: String?): Mono<String> {
return stringRedisTemplate.opsForValue()
.get(Const.VERIFY_EMAIL_DATA + email)
.flatMap { code ->
if (receivedCode == null || code != receivedCode)
Mono.just("verify code is wrong.")
else Mono.just("")
}
.switchIfEmpty(Mono.just("verify code has not been sent"))
}
}
@@ -0,0 +1,354 @@
package club.itstudio.itmanager.service.v1
import club.itstudio.itmanager.entity.dto.Attachment
import club.itstudio.itmanager.entity.dto.Category
import club.itstudio.itmanager.entity.dto.Item
import club.itstudio.itmanager.entity.dto.ItemTransaction
import club.itstudio.itmanager.entity.enums.TransactionType
import club.itstudio.itmanager.service.AttachmentService
import club.itstudio.itmanager.service.CategoryService
import club.itstudio.itmanager.service.ItemService
import club.itstudio.itmanager.service.ItemTransactionService
import club.itstudio.itmanager.utils.Const
import club.itstudio.itmanager.utils.DateUtils.getCurrentDateTime
import com.baomidou.mybatisplus.extension.plugins.pagination.Page
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Value
import org.springframework.http.codec.multipart.FilePart
import org.springframework.stereotype.Service
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
import reactor.core.scheduler.Schedulers
import java.io.IOException
import java.nio.file.Files
import java.nio.file.Paths
import java.util.NoSuchElementException
import java.util.UUID
@Service
class ItemsApiService(
private val itemService: ItemService,
private val categoryService: CategoryService,
private val attachmentService: AttachmentService,
private val transactionService: ItemTransactionService,
@Value($$"${app.file.data-path}")
private val dataPath: String
) {
private val logger = LoggerFactory.getLogger(this::class.java)
fun getItems(page: Page<Item>, keyword: String?, status: String?): Mono<Page<Item>> {
logger.info("Listing items with keyword and status")
return itemService.pageItems(page, keyword, status)
}
fun createItem(item: Item): Mono<String> {
logger.info("Creating item")
val rightNow = getCurrentDateTime()
return itemService.createItem(
item.copy(
id = null,
createdAt = rightNow,
updatedAt = rightNow
)
).flatMap { success ->
if (success) Mono.just("")
else Mono.just("item create failed.")
}
}
fun updateItem(item: Item): Mono<String> {
logger.info("Updating item")
if (item.id == null) return Mono.just("item id is required.")
return itemService.updateItem(
item.copy(updatedAt = getCurrentDateTime())
).flatMap { success ->
if (success) Mono.just("")
else Mono.just("item update failed.")
}
}
fun deleteItem(id: Long?): Mono<String> {
logger.info("Deleting item with id {}", id)
if (id == null) return Mono.just("item id is required.")
return itemService.removeItemById(id).flatMap { success ->
if (success) {
cleanupItemAttachments(id)
} else {
Mono.just("item delete failed.")
}
}
}
fun uploadImages(id: Long, files: Flux<FilePart>): Mono<String> {
logger.info("Uploading images for item {}", id)
return itemService.getItemById(id)
.flatMap { item ->
files.flatMap { file -> saveItemImage(id, file) }
.collectList()
.flatMap { attachments ->
if (attachments.isEmpty()) {
Mono.just("no image files provided.")
} else {
Flux.fromIterable(attachments)
.flatMap { attachmentService.createAttachment(it) }
.collectList()
.flatMap { results ->
if (results.any { !it }) {
Mono.just("item image upload failed.")
} else {
setPrimaryImageIfBlank(item, attachments.first(), id)
}
}
}
}
}
.onErrorResume(NoSuchElementException::class.java) { Mono.just("item not found.") }
.onErrorResume { Mono.just(Const.INTERNAL_ERROR_STR) }
}
fun setPrimaryImage(id: Long, imageId: Long): Mono<String> {
logger.info("Setting primary image for item {}", id)
return itemService.getItemById(id)
.flatMap { _ ->
attachmentService.getAttachmentById(imageId)
.flatMap { attachment ->
if (attachment.relatedTable == "items" && attachment.relatedId == id) {
val path = attachment.filePath
if (path.isNullOrBlank()) {
Mono.just("image file path is empty.")
} else {
itemService.setPrimaryImage(id, path).flatMap { success ->
if (success) Mono.just("")
else Mono.just("set primary image failed.")
}
}
} else {
Mono.just("image does not belong to this item.")
}
}
.onErrorResume(NoSuchElementException::class.java) { _ -> Mono.just("image not found.") }
}
.onErrorResume(NoSuchElementException::class.java) { _ -> Mono.just("item not found.") }
.onErrorResume { _ -> Mono.just(Const.INTERNAL_ERROR_STR) }
}
fun borrowItem(id: Long, quantity: Int): Mono<String> {
logger.info("Borrowing item {} with quantity {}", id, quantity)
if (quantity <= 0) return Mono.just("quantity must be positive.")
return itemService.getItemById(id)
.flatMap { item ->
itemService.borrowItem(id, quantity)
.flatMap { success ->
if (success) {
transactionService.createTransaction(
ItemTransaction(
itemId = id,
transType = TransactionType.OUT,
quantity = quantity,
fromLocation = item.location,
createdAt = getCurrentDateTime()
)
).onErrorResume { error ->
logger.warn("Failed to record OUT transaction for item {}: {}", id, error.message)
Mono.just(false)
}.thenReturn("")
} else {
Mono.just("item available quantity is not enough.")
}
}
}
.onErrorResume(NoSuchElementException::class.java) { Mono.just("item not found.") }
.onErrorResume { Mono.just(Const.INTERNAL_ERROR_STR) }
}
fun returnItem(id: Long, quantity: Int): Mono<String> {
logger.info("Returning item {} with quantity {}", id, quantity)
if (quantity <= 0) return Mono.just("quantity must be positive.")
return itemService.getItemById(id)
.flatMap { item ->
itemService.returnItem(id, quantity)
.flatMap { success ->
if (success) {
transactionService.createTransaction(
ItemTransaction(
itemId = id,
transType = TransactionType.IN,
quantity = quantity,
toLocation = item.location,
createdAt = getCurrentDateTime()
)
).onErrorResume { error ->
logger.warn("Failed to record IN transaction for item {}: {}", id, error.message)
Mono.just(false)
}.thenReturn("")
} else {
Mono.just("item cannot be returned with the given quantity.")
}
}
}
.onErrorResume(NoSuchElementException::class.java) { Mono.just("item not found.") }
.onErrorResume { Mono.just(Const.INTERNAL_ERROR_STR) }
}
fun getAvailableItems(): Mono<List<Item>> {
logger.info("Listing available items")
return itemService.listAvailableItems()
}
fun getInUseItems(): Mono<List<Item>> {
logger.info("Listing in-use items")
return itemService.listInUseItems()
}
fun getItemCategories(): Mono<List<Category>> {
logger.info("Listing item categories")
return categoryService.listAllCategories()
}
fun createItemCategory(category: Category): Mono<String> {
logger.info("Creating item category")
return categoryService.createCategory(
category.copy(
id = null,
createdAt = getCurrentDateTime(),
updatedAt = getCurrentDateTime()
)
).flatMap { success ->
if (success) Mono.just("")
else Mono.just("category create failed.")
}
}
fun updateItemCategory(category: Category): Mono<String> {
logger.info("Updating item category")
if (category.id == null) return Mono.just("category id is required.")
return categoryService.updateCategory(
category.copy(updatedAt = getCurrentDateTime())
).flatMap { success ->
if (success) Mono.just("")
else Mono.just("category update failed.")
}
}
fun deleteItemCategory(id: Long?): Mono<String> {
logger.info("Deleting item category with id {}", id)
if (id == null) return Mono.just("category id is required.")
return categoryService.deleteCategory(id).flatMap { success ->
if (success) Mono.just("")
else Mono.just("category delete failed.")
}
}
fun getItemImages(): Mono<List<Attachment>> {
logger.info("Listing item images")
return attachmentService.exportAllAttachments()
.map { list -> list.filter { it.relatedTable == "items" } }
}
fun createItemImage(attachment: Attachment): Mono<String> {
logger.info("Creating item image")
return attachmentService.createAttachment(
attachment.copy(
id = null,
uploadedAt = getCurrentDateTime()
)
).flatMap { success ->
if (success) Mono.just("")
else Mono.just("item image create failed.")
}
}
fun updateItemImage(attachment: Attachment): Mono<String> {
logger.info("Updating item image")
if (attachment.id == null) return Mono.just("item image id is required.")
return Mono.fromCallable { attachmentService.updateById(attachment) }
.subscribeOn(Schedulers.boundedElastic())
.flatMap { success ->
if (success) Mono.just("")
else Mono.just("item image update failed.")
}
}
fun deleteItemImage(id: Long?): Mono<String> {
logger.info("Deleting item image with id {}", id)
if (id == null) return Mono.just("item image id is required.")
return attachmentService.getAttachmentById(id)
.flatMap { attachment ->
attachmentService.deleteAttachment(id).flatMap { success ->
if (success) {
deletePhysicalFile(attachment.filePath).thenReturn("")
} else {
Mono.just("item image delete failed.")
}
}
}
.onErrorResume(NoSuchElementException::class.java) { Mono.just("item image not found.") }
.onErrorResume { Mono.just(Const.INTERNAL_ERROR_STR) }
}
private fun setPrimaryImageIfBlank(item: Item, attachment: Attachment, id: Long): Mono<String> {
if (!item.imagePath.isNullOrBlank()) return Mono.just("")
val path = attachment.filePath ?: return Mono.just("")
return itemService.setPrimaryImage(id, path).flatMap { success ->
if (success) Mono.just("")
else Mono.just("set primary image failed.")
}
}
private fun saveItemImage(itemId: Long, file: FilePart): Mono<Attachment> {
val directory = Paths.get(dataPath, Const.FILE_DIR_IMAGE, "items", itemId.toString())
val savedName = generateSafeFileName(file.filename())
val target = directory.resolve(savedName)
return Mono.fromCallable {
Files.createDirectories(directory)
file.transferTo(target)
Attachment(
relatedTable = "items",
relatedId = itemId,
fileName = savedName,
filePath = target.toString(),
fileSize = Files.size(target),
contentType = file.headers().contentType?.toString(),
uploadedAt = getCurrentDateTime()
)
}.subscribeOn(Schedulers.boundedElastic())
}
private fun generateSafeFileName(original: String?): String {
val extension = original
?.substringAfterLast('.')
?.lowercase()
?.takeIf {
it.isNotBlank() &&
it.length <= 10 &&
it.all { ch -> ch.isLetterOrDigit() }
}
return if (extension != null) "${UUID.randomUUID()}.$extension" else UUID.randomUUID().toString()
}
private fun cleanupItemAttachments(itemId: Long): Mono<String> {
return attachmentService.listByRelated("items", itemId)
.flatMap { attachments ->
Flux.fromIterable(attachments)
.flatMap { deletePhysicalFile(it.filePath) }
.then(attachmentService.deleteByRelated("items", itemId))
.thenReturn("")
}
.onErrorResume { error ->
logger.warn("Failed to clean up attachments for item {}: {}", itemId, error.message)
Mono.just("")
}
}
private fun deletePhysicalFile(path: String?): Mono<Void> {
if (path.isNullOrBlank()) return Mono.empty()
return Mono.fromRunnable<Void> {
try {
Files.deleteIfExists(Paths.get(path))
} catch (e: IOException) {
logger.warn("Failed to delete file: {}", path, e)
}
}.subscribeOn(Schedulers.boundedElastic())
}
}
@@ -0,0 +1,29 @@
package club.itstudio.itmanager.utils
import club.itstudio.itmanager.entity.ApiResponse
import reactor.core.publisher.Mono
object Const {
const val FLOW_LIMIT_ORDER = -101
const val JWT_BLACK_LIST = "jwt:blacklist:"
const val VERIFY_EMAIL_LIMIT = "verify:email:limit:"
const val VERIFY_EMAIL_DATA = "verify:email:data:"
const val FLOW_LIMIT_COUNTER = "flow:counter:"
const val FLOW_LIMIT_BLOCK = "flow:block:"
const val FILE_DIR_IMAGE = "image"
const val INTERNAL_ERROR_STR = "something went wrong. Please contact the administrator."
val INTERNAL_ERROR_MONO = Mono.just(INTERNAL_ERROR_STR)
// for Controllers
fun messageHandler(wrongMessage: String): ApiResponse<Any?> {
return if (wrongMessage.isBlank()) {
ApiResponse.success()
} else {
ApiResponse.failure(400, null, wrongMessage)
}
}
}
@@ -0,0 +1,17 @@
package club.itstudio.itmanager.utils
import kotlinx.datetime.*
import kotlinx.datetime.TimeZone
import java.util.*
object DateUtils {
fun getCurrentDateTime() =
Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault())
fun dateToLocalDateTime(date: Date): LocalDateTime {
return date
.toInstant()
.toKotlinInstant()
.toLocalDateTime(TimeZone.currentSystemDefault())
}
}
@@ -0,0 +1,26 @@
package club.itstudio.itmanager.utils
import jakarta.annotation.Resource
import org.springframework.data.redis.core.ReactiveStringRedisTemplate
import org.springframework.stereotype.Component
import reactor.core.publisher.Mono
import java.time.Duration
@Component
class FlowUtils(
@Resource
val template: ReactiveStringRedisTemplate
) {
fun limitOnceCheck(key: String, blockTime: Int): Mono<Boolean> {
return template.hasKey(key).flatMap { exists ->
if (exists) {
Mono.just(false)
} else {
template.opsForValue()
.set(key, "", Duration.ofSeconds(blockTime.toLong()))
.thenReturn(true)
}
}
}
}
@@ -0,0 +1,109 @@
package club.itstudio.itmanager.utils
import com.auth0.jwt.JWT
import com.auth0.jwt.JWTVerifier
import com.auth0.jwt.algorithms.Algorithm
import com.auth0.jwt.interfaces.DecodedJWT
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Value
import org.springframework.data.redis.core.StringRedisTemplate
import org.springframework.security.core.userdetails.User
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.stereotype.Component
import java.util.*
import java.util.concurrent.TimeUnit
@Component
class JwtUtils(
@param:Value($$"${spring.security.jwt.key}")
private val key: String,
@param:Value($$"${spring.security.jwt.expire-hours}")
private val expireHours: Int,
private val template: StringRedisTemplate
) {
private val algorithm: Algorithm = Algorithm.HMAC256(key)
private val jwtVerifier: JWTVerifier = JWT.require(algorithm).build()
private val logger = LoggerFactory.getLogger(this::class.java)
fun invalidateJwt(headerToken: String?): Boolean {
val token = this.convertToToken(headerToken) ?: return false
try {
val jwt = jwtVerifier.verify(token)
val id = jwt.id
return deleteToken(id, jwt.expiresAt)
} catch (e: Exception) {
logger.error("Error occurred while invalidating JWT", e)
return false
}
}
private fun deleteToken(uuid: String, time: Date): Boolean {
val now = Date()
val expire = (time.time - now.time).coerceAtLeast(0)
template.opsForValue().set(
Const.JWT_BLACK_LIST + uuid,
"deleted",
expire,
TimeUnit.MILLISECONDS
)
return true
}
private fun isInvalidToken(uuid: String): Boolean =
template.hasKey(Const.JWT_BLACK_LIST + uuid) ?: false
fun resolveJwt(headerToken: String?): DecodedJWT? {
val token = convertToToken(headerToken) ?: return null
try {
val decodedJWT = jwtVerifier.verify(token)
if (this.isInvalidToken(decodedJWT.id)) return null
val expiresAt = decodedJWT.expiresAt
return if (Date().after(expiresAt)) null
else decodedJWT
} catch (e: Exception) {
logger.error("Error occurred while resolving JWT", e)
return null
}
}
fun createJwt(
details: UserDetails,
id: Long,
username: String
): String {
return JWT.create()
.withJWTId(UUID.randomUUID().toString())
.withClaim("id", id)
.withClaim("username", username)
.withClaim(
"authorities",
details.authorities.map { it.authority }.toList()
)
.withExpiresAt(expiresTime())
.withIssuedAt(Date())
.sign(algorithm)
}
fun toUser(jwt: DecodedJWT): UserDetails {
val claims = jwt.claims
return User
.withUsername(claims["username"]!!.asString())
.password("********")
.authorities(*(claims["authorities"]!!.asArray(String::class.java)))
.build()
}
fun toId(jwt: DecodedJWT) = jwt.claims["id"]?.asLong() ?: -1L
fun expiresTime(): Date {
val cal = Calendar.getInstance()
cal.add(Calendar.HOUR, expireHours)
return cal.time
}
fun convertToToken(headerToken: String?): String? =
headerToken?.replace("Bearer ", "")
}
@@ -0,0 +1,43 @@
spring:
webflux:
base-path: /
mail:
#host: smtp.example.com
#username: 123456@example.com
#password: password
#port: 123456
protocol: smtp
properties:
mail.smtp.auth: true
mail.smtp.ssl.enable: true
mail.smtp.timeout: 5000
rabbitmq:
host: localhost
port: 5672
virtual-host: /
username: admin
password: 123456
application:
name: itmanager
security:
jwt:
#key: 6846513216
expire-hours: 168
datasource:
url: jdbc:mariadb://localhost:3306/itstudio_manager
driver-class-name: org.mariadb.jdbc.Driver
#username: root
#password: 123456
app:
flow-limit:
count: 1000
limit-time: 3
ban-time: 60
file:
data-path: ./data
@@ -0,0 +1,14 @@
package club.itstudio.itmanager
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
@SpringBootTest
class ItmanagerApplicationTests {
@Test
fun contextLoads() {
println(BCryptPasswordEncoder().encode("123456"))
}
}