Merge pull request 'feat: DB interface' (#3) from backend-dev into main

Reviewed-on: #3
This commit was merged in pull request #3.
This commit is contained in:
2026-07-27 15:58:22 +08:00
34 changed files with 1197 additions and 239 deletions
+2
View File
@@ -0,0 +1,2 @@
kotlin.jvm.target.validation=warning
kotlin.jvm.target=25
+1 -1
View File
@@ -1,6 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.5.1-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-9.6.1-bin.zip
networkTimeout=10000
retries=0
retryBackOffMs=500
+2 -2
View File
@@ -20,7 +20,7 @@
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
# gradlew start up script for POSIX generated by Gradle.
#
# Important for running:
#
@@ -29,7 +29,7 @@
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
# ksh gradlew
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
+2 -2
View File
@@ -19,7 +19,7 @@
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem gradlew startup script for Windows
@rem
@rem ##########################################################################
@@ -72,7 +72,7 @@ echo location of your Java installation. 1>&2
@rem Execute Gradle
@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
@@ -1,21 +1,16 @@
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.AccountService
import club.itstudio.itmanager.service.v1.AuthorizationService
import jakarta.validation.Valid
import jakarta.validation.constraints.Email
import jakarta.validation.constraints.NotBlank
import jakarta.validation.constraints.Pattern
import org.slf4j.LoggerFactory
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.bind.annotation.*
import org.springframework.web.server.ServerWebExchange
import reactor.core.publisher.Mono
@@ -23,34 +18,34 @@ import reactor.core.publisher.Mono
@RestController
@RequestMapping("/api/v1/auth")
class AuthorizeController(
private val service: AccountService
private val service: AuthorizationService
) {
private val logger = LoggerFactory.getLogger(this::class.java)
@GetMapping("/ask-code")
fun askVerifyCode(
@RequestParam @NotBlank @Email email: String,
@RequestParam @Pattern(regexp = "(register|reset)") type: 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 { messageHandler(it) }
.map(::messageHandler)
}
@PostMapping("/register")
fun emailRegister(@RequestBody @Valid vo: EmailRegisterVO): Mono<ApiResponse<Any?>> {
logger.info("Trying to register")
return service.registerEmailAccount(vo)
.map { messageHandler(it) }
.map(::messageHandler)
}
@PostMapping("/reset")
fun emailResetPassword(@RequestBody @Valid vo: PasswordResetVO): Mono<ApiResponse<Any?>> {
logger.info("Trying to reset password")
return service.resetEmailAccountPassword(vo)
.map { messageHandler(it) }
.map(::messageHandler)
}
@GetMapping("/logout")
@@ -71,7 +66,7 @@ class AuthorizeController(
return service
.jwtTokenRelogin(authorization)
?.map { ApiResponse.success(it) }
?: Mono.just(messageHandler("Please login with password."))
?: Mono.just(ApiResponse.failure(401, null, "Please login with password."))
}
private fun messageHandler(wrongMessage: String): ApiResponse<Any?> {
@@ -1,10 +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: String,
val type: EmailType,
val code: String
)
@@ -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,
}
@@ -1,6 +1,7 @@
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
@@ -28,21 +29,19 @@ class MailQueueListener(
val (email, type, code) = data
val message = when (type) {
"register" -> createMailMessage(
EmailType.REGISTER -> createMailMessage(
"Welcome to Our Service",
"Thank you for registering! Your verification code is: $code"
+ "\nThis code is valid for 3 minutes.",
email
)
"reset" -> createMailMessage(
EmailType.RESET -> createMailMessage(
"Password Reset Request",
"You requested a password reset. Your verification code is: $code"
+ "\nThis code is valid for 3 minutes.",
email
)
else -> return
}
sender.send(message)
logger.info("Email sent to $email.")
@@ -10,9 +10,13 @@ import reactor.core.publisher.Mono
interface AccountService : IService<Account>, ReactiveUserDetailsService {
fun findAccountByNameOrEmail(text: String): Mono<Account>
fun askEmailVerifyCode(type: String, email: String, ip: String): Mono<String>
fun registerEmailAccount(vo: EmailRegisterVO): Mono<String>
fun resetEmailAccountPassword(vo: PasswordResetVO): Mono<String>
fun invalidateJwt(headerToken: String?): Boolean
fun jwtTokenRelogin(headerToken: String?): Mono<ReloginVO>?
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>>
}
@@ -2,5 +2,14 @@ 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>
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>>
}
@@ -2,5 +2,16 @@ 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>
interface BorrowRecordService : IService<BorrowRecord> {
fun getBorrowRecordById(id: Long): Mono<BorrowRecord>
fun listByItem(itemId: Long): Mono<List<BorrowRecord>>
fun listByBorrower(borrowerId: Long): 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>>
}
@@ -2,5 +2,14 @@ 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>
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>>
}
@@ -2,5 +2,14 @@ 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>
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>>
}
@@ -2,5 +2,15 @@ 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>
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>>
}
@@ -2,5 +2,16 @@ package club.itstudio.itmanager.service
import com.baomidou.mybatisplus.extension.service.IService
import club.itstudio.itmanager.entity.dto.Evaluation
import reactor.core.publisher.Mono
interface EvaluationService : IService<Evaluation>
interface EvaluationService : IService<Evaluation> {
fun getEvaluationById(id: Long): Mono<Evaluation>
fun listByEvaluator(evaluatorId: Long): Mono<List<Evaluation>>
fun listByRelatedItem(itemId: Long): Mono<List<Evaluation>>
fun listByScore(score: Short): Mono<List<Evaluation>>
fun createEvaluation(evaluation: Evaluation): Mono<Boolean>
fun updateEvaluation(evaluation: Evaluation): Mono<Boolean>
fun deleteEvaluation(id: Long): Mono<Boolean>
fun deleteByEvaluator(evaluatorId: Long): Mono<Boolean>
fun exportAllEvaluations(): Mono<List<Evaluation>>
}
@@ -2,5 +2,16 @@ 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>
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>>
}
@@ -1,6 +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>
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>>
}
@@ -2,5 +2,15 @@ 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>
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>>
}
@@ -2,5 +2,16 @@ package club.itstudio.itmanager.service
import com.baomidou.mybatisplus.extension.service.IService
import club.itstudio.itmanager.entity.dto.Memo
import reactor.core.publisher.Mono
interface MemoService : IService<Memo>
interface MemoService : IService<Memo> {
fun getMemoById(id: Long): Mono<Memo>
fun searchMemos(keyword: String?): Mono<List<Memo>>
fun listByAuthor(authorId: Long): Mono<List<Memo>>
fun listByRelatedItem(itemId: Long): Mono<List<Memo>>
fun listPublicMemos(): Mono<List<Memo>>
fun createMemo(memo: Memo): Mono<Boolean>
fun updateMemo(memo: Memo): Mono<Boolean>
fun deleteMemo(id: Long): Mono<Boolean>
fun exportAllMemos(): Mono<List<Memo>>
}
@@ -2,5 +2,16 @@ package club.itstudio.itmanager.service
import com.baomidou.mybatisplus.extension.service.IService
import club.itstudio.itmanager.entity.dto.Personnel
import reactor.core.publisher.Mono
interface PersonnelService : IService<Personnel>
interface PersonnelService : IService<Personnel> {
fun getPersonnelById(id: Long): Mono<Personnel>
fun searchPersonnel(keyword: String?): Mono<List<Personnel>>
fun listByDepartment(departmentId: Long): Mono<List<Personnel>>
fun listByRole(role: String): Mono<List<Personnel>>
fun createPersonnel(personnel: Personnel): Mono<Boolean>
fun updatePersonnel(personnel: Personnel): Mono<Boolean>
fun deletePersonnel(id: Long): Mono<Boolean>
fun setActive(id: Long, active: Boolean): Mono<Boolean>
fun exportAllPersonnel(): Mono<List<Personnel>>
}
@@ -1,207 +1,144 @@
package club.itstudio.itmanager.service.impl
import com.baomidou.mybatisplus.core.toolkit.Wrappers
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
import club.itstudio.itmanager.entity.dto.Account
import club.itstudio.itmanager.entity.dto.EmailVerificationMsg
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.entity.enums.AccountRole
import club.itstudio.itmanager.mapper.AccountMapper
import club.itstudio.itmanager.service.AccountService
import club.itstudio.itmanager.utils.Const
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 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.security.crypto.password.PasswordEncoder
import org.springframework.stereotype.Service
import reactor.core.publisher.Mono
import reactor.core.scheduler.Schedulers
import java.time.Duration
import javax.security.auth.login.AccountNotFoundException
import kotlin.jvm.java
@Service
class AccountServiceImpl(
private val utils: FlowUtils,
private val jwtUtils: JwtUtils,
private val amqpTemplate: AmqpTemplate,
private val stringRedisTemplate: ReactiveStringRedisTemplate,
private val encoder: PasswordEncoder
) : ServiceImpl<AccountMapper, Account>(), AccountService {
class AccountServiceImpl : ServiceImpl<AccountMapper, Account>(), AccountService {
override fun findByUsername(username: String): Mono<UserDetails> {
return findAccountByNameOrEmail(username)
.switchIfEmpty(Mono.error(UsernameNotFoundException("Account with name $username not found")))
.map { account ->
User.withUsername(username)
.password(account.password)
.roles(if (account.isStaff) "STAFF" else "USER")
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 findAccountByNameOrEmail(text: String): Mono<Account> {
return Mono.fromCallable {
this.query()
.eq("username", text).or()
.eq("email", text)
override fun findAccountByName(username: String): Mono<Account> =
findAccount("username") {
ktQuery()
.eq(Account::username, username)
.one()
}.flatMap { account ->
Mono.just(account)
}
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 askEmailVerifyCode(type: String, 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.")
}
}
}
override fun registerEmailAccount(vo: EmailRegisterVO): Mono<String> {
val (email, code, username, password) = vo
return verifyCode(email, code).flatMap { error ->
if (error.isNotBlank()) {
return@flatMap Mono.just(error)
}
existAccountByEmail(email).flatMap { emailExists ->
if (emailExists) {
return@flatMap Mono.just("account with the same email already exists.")
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())
)
}
existAccountByUsername(username).flatMap { usernameExists ->
if (usernameExists) {
return@flatMap Mono.just("username already exists.")
}
override fun existAccountByName(
username: String
): Mono<Boolean> {
return blockingCall {
ktQuery()
.eq(Account::username, username)
.exists()
val encodedPassword = encoder.encode(password)
val account = Account(
username = username,
password = encodedPassword!!,
email = email,
isActive = true,
isStaff = false
}
}
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()
)
Mono.fromCallable { this.save(account) }
.flatMap { success ->
if (success) {
stringRedisTemplate.delete(Const.VERIFY_EMAIL_DATA + email)
.thenReturn("")
} else {
Mono.just("something went wrong. Please contact the administrator.")
}
}
}
}
}
}
override fun resetEmailAccountPassword(vo: PasswordResetVO): Mono<String> {
val (email, code, password) = vo
return verifyCode(email, code).flatMap { error ->
if (error.isNotBlank()) {
return@flatMap Mono.just(error)
}
existAccountByEmail(email).flatMap { exists ->
if (!exists) {
return@flatMap Mono.just("account with the email does not exist.")
}
val encodedPassword = encoder.encode(password)
Mono.fromCallable {
this.update()
.eq("email", email)
.set("password", encodedPassword)
.update()
}.flatMap { success ->
if (success) {
stringRedisTemplate.delete(Const.VERIFY_EMAIL_DATA + email)
.thenReturn("")
} else {
Mono.just("something went wrong. Please contact the administrator.")
}
}
}
}
}
override fun jwtTokenRelogin(headerToken: String?): Mono<ReloginVO>? {
val user = jwtUtils.resolveJwt(headerToken?.substring("Bearer ".length))
?.let { jwtUtils.toUser(it) }
?: return null
val accountMono = findAccountByNameOrEmail(user.username)
val voMono = accountMono.map {
ReloginVO(
jwtUtils.createJwt(user, it.id!!, it.username),
jwtUtils.expiresTime().toInstant().toString()
)
}
return voMono
}
override fun invalidateJwt(headerToken: String?): Boolean {
return jwtUtils.invalidateJwt(headerToken)
}
private fun existAccountByEmail(email: String): Mono<Boolean> {
return Mono.fromCallable {
this.baseMapper.exists(
Wrappers.query<Account>()
.eq("email", email)
)
}
}
private fun existAccountByUsername(username: String): Mono<Boolean> {
return Mono.fromCallable {
this.baseMapper.exists(
Wrappers.query<Account>()
.eq("username", username)
)
}
}
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 ->
when {
receivedCode == null || code != receivedCode ->
Mono.just("verify code is wrong.")
else -> Mono.just("")
}
}
.switchIfEmpty(Mono.just("verify code has not been sent"))
}
}
@@ -1,10 +1,62 @@
package club.itstudio.itmanager.service.impl
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
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
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()
}
}
@@ -1,10 +1,74 @@
package club.itstudio.itmanager.service.impl
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
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
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(borrowerId: Long): Mono<List<BorrowRecord>> =
blockingCall {
logger.info("Searching borrow records by borrower id")
ktQuery().eq(BorrowRecord::borrowerId, borrowerId).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()
}
}
@@ -1,10 +1,62 @@
package club.itstudio.itmanager.service.impl
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
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
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()
}
}
@@ -1,10 +1,62 @@
package club.itstudio.itmanager.service.impl
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
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
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()
}
}
@@ -1,10 +1,72 @@
package club.itstudio.itmanager.service.impl
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
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
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()
}
}
@@ -1,10 +1,74 @@
package club.itstudio.itmanager.service.impl
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
import club.itstudio.itmanager.entity.dto.Evaluation
import club.itstudio.itmanager.mapper.EvaluationMapper
import club.itstudio.itmanager.service.EvaluationService
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 EvaluationServiceImpl : ServiceImpl<EvaluationMapper, Evaluation>(), EvaluationService
class EvaluationServiceImpl : ServiceImpl<EvaluationMapper, Evaluation>(), EvaluationService {
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 getEvaluationById(id: Long): Mono<Evaluation> =
blockingCall {
logger.info("Searching evaluation by id")
ktQuery().eq(Evaluation::id, id).one()
}.switchIfEmpty(Mono.error(NoSuchElementException("Evaluation not found")))
override fun listByEvaluator(evaluatorId: Long): Mono<List<Evaluation>> =
blockingCall {
logger.info("Searching evaluations by evaluator id")
ktQuery().eq(Evaluation::evaluatorId, evaluatorId).list()
}
override fun listByRelatedItem(itemId: Long): Mono<List<Evaluation>> =
blockingCall {
logger.info("Searching evaluations by related item id")
ktQuery().eq(Evaluation::relatedItemId, itemId).list()
}
override fun listByScore(score: Short): Mono<List<Evaluation>> =
blockingCall {
logger.info("Searching evaluations by score")
ktQuery().eq(Evaluation::score, score).list()
}
override fun createEvaluation(evaluation: Evaluation): Mono<Boolean> =
blockingCall {
logger.info("Creating evaluation")
save(evaluation)
}
override fun updateEvaluation(evaluation: Evaluation): Mono<Boolean> =
blockingCall {
logger.info("Updating evaluation")
updateById(evaluation)
}
override fun deleteEvaluation(id: Long): Mono<Boolean> =
blockingCall {
logger.info("Deleting evaluation by id")
removeById(id)
}
override fun deleteByEvaluator(evaluatorId: Long): Mono<Boolean> =
blockingCall {
logger.info("Deleting evaluations by evaluator id")
remove(ktQuery().eq(Evaluation::evaluatorId, evaluatorId))
}
override fun exportAllEvaluations(): Mono<List<Evaluation>> =
blockingCall {
logger.info("Exporting all evaluations")
list()
}
}
@@ -1,10 +1,74 @@
package club.itstudio.itmanager.service.impl
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
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
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()
}
}
@@ -1,10 +1,123 @@
package club.itstudio.itmanager.service.impl
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
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
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()
}
}
@@ -1,10 +1,68 @@
package club.itstudio.itmanager.service.impl
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
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
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()
}
}
@@ -1,10 +1,80 @@
package club.itstudio.itmanager.service.impl
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
import club.itstudio.itmanager.entity.dto.Memo
import club.itstudio.itmanager.mapper.MemoMapper
import club.itstudio.itmanager.service.MemoService
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 MemoServiceImpl : ServiceImpl<MemoMapper, Memo>(), MemoService
class MemoServiceImpl : ServiceImpl<MemoMapper, Memo>(), MemoService {
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 getMemoById(id: Long): Mono<Memo> =
blockingCall {
logger.info("Searching memo by id")
ktQuery().eq(Memo::id, id).one()
}.switchIfEmpty(Mono.error(NoSuchElementException("Memo not found")))
override fun searchMemos(keyword: String?): Mono<List<Memo>> =
blockingCall {
logger.info("Searching memos with keyword")
if (keyword.isNullOrBlank()) {
list()
} else {
ktQuery().and {
it.like(Memo::title, keyword).or().like(Memo::content, keyword)
}.list()
}
}
override fun listByAuthor(authorId: Long): Mono<List<Memo>> =
blockingCall {
logger.info("Searching memos by author id")
ktQuery().eq(Memo::authorId, authorId).list()
}
override fun listByRelatedItem(itemId: Long): Mono<List<Memo>> =
blockingCall {
logger.info("Searching memos by related item id")
ktQuery().eq(Memo::relatedItemId, itemId).list()
}
override fun listPublicMemos(): Mono<List<Memo>> =
blockingCall {
logger.info("Listing public memos")
ktQuery().eq(Memo::isPublic, true).list()
}
override fun createMemo(memo: Memo): Mono<Boolean> =
blockingCall {
logger.info("Creating memo")
save(memo)
}
override fun updateMemo(memo: Memo): Mono<Boolean> =
blockingCall {
logger.info("Updating memo")
updateById(memo)
}
override fun deleteMemo(id: Long): Mono<Boolean> =
blockingCall {
logger.info("Deleting memo by id")
removeById(id)
}
override fun exportAllMemos(): Mono<List<Memo>> =
blockingCall {
logger.info("Exporting all memos")
list()
}
}
@@ -1,10 +1,83 @@
package club.itstudio.itmanager.service.impl
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
import club.itstudio.itmanager.entity.dto.Personnel
import club.itstudio.itmanager.mapper.PersonnelMapper
import club.itstudio.itmanager.service.PersonnelService
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 PersonnelServiceImpl : ServiceImpl<PersonnelMapper, Personnel>(), PersonnelService
class PersonnelServiceImpl : ServiceImpl<PersonnelMapper, Personnel>(), PersonnelService {
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 getPersonnelById(id: Long): Mono<Personnel> =
blockingCall {
logger.info("Searching personnel by id")
ktQuery().eq(Personnel::id, id).one()
}.switchIfEmpty(Mono.error(NoSuchElementException("Personnel not found")))
override fun searchPersonnel(keyword: String?): Mono<List<Personnel>> =
blockingCall {
logger.info("Searching personnel with keyword")
if (keyword.isNullOrBlank()) {
list()
} else {
ktQuery().and {
it.like(Personnel::name, keyword)
.or().like(Personnel::employeeNo, keyword)
.or().like(Personnel::phone, keyword)
.or().like(Personnel::email, keyword)
}.list()
}
}
override fun listByDepartment(departmentId: Long): Mono<List<Personnel>> =
blockingCall {
logger.info("Searching personnel by department id")
ktQuery().eq(Personnel::departmentId, departmentId).list()
}
override fun listByRole(role: String): Mono<List<Personnel>> =
blockingCall {
logger.info("Searching personnel by role")
ktQuery().eq(Personnel::role, role).list()
}
override fun createPersonnel(personnel: Personnel): Mono<Boolean> =
blockingCall {
logger.info("Creating personnel")
save(personnel)
}
override fun updatePersonnel(personnel: Personnel): Mono<Boolean> =
blockingCall {
logger.info("Updating personnel")
updateById(personnel)
}
override fun deletePersonnel(id: Long): Mono<Boolean> =
blockingCall {
logger.info("Deleting personnel by id")
removeById(id)
}
override fun setActive(id: Long, active: Boolean): Mono<Boolean> =
blockingCall {
logger.info("Setting personnel active status")
ktUpdate().eq(Personnel::id, id).set(Personnel::isActive, active).update()
}
override fun exportAllPersonnel(): Mono<List<Personnel>> =
blockingCall {
logger.info("Exporting all personnel")
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"))
}
}