add spaces

This commit is contained in:
xds
2025-02-17 17:58:07 +03:00
parent a5b334f6c2
commit d680345a9f
23 changed files with 1097 additions and 285 deletions

View File

@@ -43,6 +43,26 @@ class AuthService(
}
}
fun register(username: String, password: String, firstName: String): Mono<User> {
return userRepository.findByUsername(username)
.flatMap<User> { Mono.error(IllegalArgumentException("User with username '$username' already exists")) } // Ошибка, если пользователь уже существует
.switchIfEmpty(
Mono.defer {
val newUser = User(
username = username,
password = passwordEncoder.encode(password), // Шифрование пароля
firstName = firstName,
roles = mutableListOf("USER")
)
userRepository.save(newUser).map { user ->
user.password = null
user
} // Сохранение нового пользователя
}
)
}
@Cacheable("tokens")
fun isTokenValid(token: String): Mono<User> {
return tokenService.getToken(token)

View File

@@ -21,11 +21,7 @@ import org.springframework.data.mongodb.core.query.isEqualTo
import org.springframework.stereotype.Service
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
import space.luminic.budgerapp.models.BudgetCategory
import space.luminic.budgerapp.models.Category
import space.luminic.budgerapp.models.CategoryType
import space.luminic.budgerapp.models.SortSetting
import space.luminic.budgerapp.models.Transaction
import space.luminic.budgerapp.models.*
import space.luminic.budgerapp.repos.CategoryRepo
import java.time.LocalDate
import java.time.LocalDateTime
@@ -50,11 +46,12 @@ class CategoryService(
return categoryRepo.findById(id)
}
// @Cacheable("categories")
fun getCategories(type: String? = null, sortBy: String, direction: String): Mono<List<Category>> {
// @Cacheable("categories")
fun getCategories(spaceId: String, type: String? = null, sortBy: String, direction: String): Mono<List<Category>> {
val matchCriteria = mutableListOf<Criteria>()
// Добавляем фильтры
matchCriteria.add(Criteria.where("spaceDetails._id").`is`(ObjectId(spaceId)))
type?.let { matchCriteria.add(Criteria.where("type.code").isEqualTo(it)) }
val match = match(Criteria().andOperator(*matchCriteria.toTypedArray()))
@@ -62,16 +59,17 @@ class CategoryService(
val sort = sort(Sort.by(direction, sortBy))
val lookupSpaces = lookup("spaces", "space.\$id", "_id", "spaceDetails")
val aggregationBuilder = mutableListOf(
lookupSpaces,
match.takeIf { matchCriteria.isNotEmpty() },
sort,
).filterNotNull()
val aggregation = newAggregation(aggregationBuilder)
logger.error("STARTED")
return mongoTemplate.aggregate(
aggregation, "categories", Category::class.java
)
@@ -97,7 +95,8 @@ class CategoryService(
}
@CacheEvict(cacheNames = ["getAllCategories"], allEntries = true)
fun createCategory(category: Category): Mono<Category> {
fun createCategory(space: Space, category: Category): Mono<Category> {
category.space = space
return categoryRepo.save(category)
}
@@ -113,32 +112,32 @@ class CategoryService(
}
@CacheEvict(cacheNames = ["getAllCategories"], allEntries = true)
fun deleteCategory(categoryId: String): Mono<String> {
return categoryRepo.findById(categoryId).switchIfEmpty(
Mono.error(IllegalArgumentException("Category with id: $categoryId not found"))
).flatMap {
financialService.getTransactions(categoryId = categoryId)
.flatMapMany { transactions ->
categoryRepo.findByName("Другое").switchIfEmpty(
categoryRepo.save(
Category(
type = CategoryType("EXPENSE", "Траты"),
name = "Другое",
description = "Категория для других трат",
icon = "🚮"
)
)
).flatMapMany { category ->
Flux.fromIterable(transactions).flatMap { transaction ->
transaction.category = category // Присваиваем конкретный объект категории
financialService.editTransaction(transaction) // Сохраняем изменения
}
}
}
.then(categoryRepo.deleteById(categoryId)) // Удаляем старую категорию
.thenReturn(categoryId) // Возвращаем удалённую категорию
}
}
// fun deleteCategory(categoryId: String): Mono<String> {
// return categoryRepo.findById(categoryId).switchIfEmpty(
// Mono.error(IllegalArgumentException("Category with id: $categoryId not found"))
// ).flatMap {
// financialService.getTransactions(categoryId = categoryId)
// .flatMapMany { transactions ->
// categoryRepo.findByName("Другое").switchIfEmpty(
// categoryRepo.save(
// Category(
// type = CategoryType("EXPENSE", "Траты"),
// name = "Другое",
// description = "Категория для других трат",
// icon = "🚮"
// )
// )
// ).flatMapMany { category ->
// Flux.fromIterable(transactions).flatMap { transaction ->
// transaction.category = category // Присваиваем конкретный объект категории
// financialService.editTransaction(transaction) // Сохраняем изменения
// }
// }
// }
// .then(categoryRepo.deleteById(categoryId)) // Удаляем старую категорию
// .thenReturn(categoryId) // Возвращаем удалённую категорию
// }
// }
fun getBudgetCategories(dateFrom: LocalDate, dateTo: LocalDate): Mono<Map<String, Map<String, Double>>> {

View File

@@ -8,6 +8,7 @@ import org.springframework.cache.annotation.CacheEvict
import org.springframework.cache.annotation.Cacheable
import org.springframework.data.domain.Sort
import org.springframework.data.domain.Sort.Direction
import org.springframework.data.mongodb.core.MongoTemplate
import org.springframework.data.mongodb.core.ReactiveMongoTemplate
import org.springframework.data.mongodb.core.aggregation.Aggregation.*
import org.springframework.data.mongodb.core.aggregation.DateOperators.DateToString
@@ -19,6 +20,7 @@ import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
import space.luminic.budgerapp.models.*
import space.luminic.budgerapp.repos.BudgetRepo
import space.luminic.budgerapp.repos.CategoryRepo
import space.luminic.budgerapp.repos.TransactionRepo
import space.luminic.budgerapp.repos.WarnRepo
import java.time.*
@@ -32,7 +34,9 @@ class FinancialService(
val transactionsRepo: TransactionRepo,
val recurrentService: RecurrentService,
val userService: UserService,
val reactiveMongoTemplate: ReactiveMongoTemplate
val reactiveMongoTemplate: ReactiveMongoTemplate,
private val spaceService: SpaceService,
private val categoryRepo: CategoryRepo
) {
private val logger = LoggerFactory.getLogger(FinancialService::class.java)
@@ -191,75 +195,108 @@ class FinancialService(
}.then() // Возвращаем корректный Mono<Void>
}
@Cacheable("budgetsList")
fun getBudgets(sortSetting: SortSetting? = null): Mono<MutableList<Budget>> {
val sort = if (sortSetting != null) {
Sort.by(sortSetting.order, sortSetting.by)
} else {
Sort.by(Sort.Direction.DESC, "dateFrom")
}
fun getBudgets(spaceId: String, sortSetting: SortSetting? = null): Mono<List<Budget>> {
val sort = sortSetting?.let {
Sort.by(it.order, it.by)
} ?: Sort.by(Sort.Direction.DESC, "dateFrom")
return budgetRepo.findAll(sort)
.collectList() // Сбор Flux<Budget> в Mono<List<Budget>>
return ReactiveSecurityContextHolder.getContext()
.map { it.authentication }
.flatMap { authentication ->
val username = authentication.name
spaceService.getSpace(spaceId)
.switchIfEmpty(Mono.error(IllegalArgumentException("Space not found for $spaceId")))
.flatMap { space ->
userService.getByUsername(username)
.switchIfEmpty(Mono.error(IllegalArgumentException("User not found for username: $username")))
.flatMap { user ->
val userIds = space.users.mapNotNull { it.id?.toString() }
if (user.id !in userIds) {
Mono.error(IllegalArgumentException("User cannot access this Space"))
} else {
val spaceObjectId = try {
ObjectId(space.id!!) // Преобразуем строку в ObjectId
} catch (e: IllegalArgumentException) {
return@flatMap Mono.error(IllegalArgumentException("Invalid Space ID format: ${space.id}"))
}
println("Space ID type: ${spaceObjectId::class.java}, value: $spaceObjectId")
// Применяем сортировку к запросу
budgetRepo.findBySpaceId(spaceObjectId, sort).collectList()
}
}
}
}
}
// @Cacheable("budgets", key = "#id")
fun getBudget(id: String): Mono<BudgetDTO> {
return budgetRepo.findById(id)
.flatMap { budget ->
val budgetDTO = BudgetDTO(
budget.id,
budget.name,
budget.dateFrom,
budget.dateTo,
budget.createdAt,
categories = budget.categories,
incomeCategories = budget.incomeCategories,
)
return ReactiveSecurityContextHolder.getContext()
.flatMap { securityContext ->
val username = securityContext.authentication.name
budgetRepo.findById(id)
.flatMap { budget ->
// Проверяем, что пользователь есть в space бюджета
if (!budget.space!!.users.any { it.username == username }) {
return@flatMap Mono.error(IllegalArgumentException("User does not have access to this space"))
}
logger.info("Fetching categories and transactions")
val categoriesMono = getBudgetCategories(budgetDTO.dateFrom, budgetDTO.dateTo)
val transactionsMono =
getTransactionsByTypes(budgetDTO.dateFrom, budgetDTO.dateTo)
// Если доступ есть, продолжаем процесс
val budgetDTO = BudgetDTO(
budget.id,
budget.space,
budget.name,
budget.dateFrom,
budget.dateTo,
budget.createdAt,
categories = budget.categories,
incomeCategories = budget.incomeCategories,
)
logger.info("Fetching categories and transactions")
val categoriesMono = getBudgetCategories(budgetDTO.dateFrom, budgetDTO.dateTo)
val transactionsMono = getTransactionsByTypes(budgetDTO.dateFrom, budgetDTO.dateTo)
Mono.zip(categoriesMono, transactionsMono)
.flatMap { tuple ->
val categories = tuple.t1
val transactions = tuple.t2
Mono.zip(categoriesMono, transactionsMono)
.flatMap { tuple ->
val categories = tuple.t1
val transactions = tuple.t2
Flux.fromIterable(budgetDTO.categories)
.map { category ->
categories[category.category.id]?.let { data ->
category.currentSpent = data["instantAmount"] ?: 0.0
category.currentPlanned = data["plannedAmount"] ?: 0.0
}
category
}
.collectList()
.map { updatedCategories ->
budgetDTO.categories = updatedCategories
budgetDTO.plannedExpenses = transactions["plannedExpenses"] as MutableList
budgetDTO.plannedIncomes = transactions["plannedIncomes"] as MutableList
budgetDTO.transactions = transactions["instantTransactions"] as MutableList
Flux.fromIterable(budgetDTO.categories)
.map { category ->
categories[category.category.id]?.let { data ->
category.currentSpent = data["instantAmount"] ?: 0.0
category.currentPlanned = data["plannedAmount"] ?: 0.0
}
category
}
.collectList()
.map { updatedCategories ->
budgetDTO.categories = updatedCategories
budgetDTO.plannedExpenses = transactions["plannedExpenses"] as MutableList
budgetDTO.plannedIncomes = transactions["plannedIncomes"] as MutableList
budgetDTO.transactions = transactions["instantTransactions"] as MutableList
budgetDTO
budgetDTO
}
}
}
.doOnError { error ->
logger.error("Error fetching budget: ${error.message}", error)
}
.switchIfEmpty(Mono.error(BudgetNotFoundException("Budget not found with id: $id")))
}
.doOnError { error ->
logger.error("Error fetching budget: ${error.message}", error)
}
.switchIfEmpty(Mono.error(BudgetNotFoundException("Budget not found with id: $id")))
}
fun regenCats(): Mono<Void> {
fun regenBudgets(): Mono<Void> {
return budgetRepo.findAll()
.flatMap { budget ->
getCategoryTransactionPipeline(budget.dateFrom, budget.dateTo, "INCOME")
.map { categories ->
budget.incomeCategories = categories
spaceService.getSpace("67af3c0f652da946a7dd9931")
.map { space ->
budget.space = space
budget
}
.flatMap { updatedBudget -> budgetRepo.save(updatedBudget) }
@@ -267,12 +304,38 @@ class FinancialService(
.then()
}
fun regenTransactions(): Mono<Void> {
return transactionsRepo.findAll().flatMap { transaction ->
spaceService.getSpace("67af3c0f652da946a7dd9931")
.map { space ->
transaction.space = space
transaction
}
.flatMap { updatedTransaction -> transactionsRepo.save(updatedTransaction) }
}
.then()
}
fun regenCats(): Mono<Void> {
return categoryRepo.findAll()// Получаем список категорий
.flatMap { cat ->
spaceService.getSpace("67af3c0f652da946a7dd9931") // Получаем space
.map { space ->
cat.space = space // Привязываем пространство к категории
cat
}
}
.flatMap { updatedCategory -> categoryRepo.save(updatedCategory) } // Сохраняем в БД
.then() // Завершаем Mono<Void>
}
@CacheEvict(cacheNames = ["budgets", "budgetsList"], allEntries = true)
fun createBudget(budget: Budget, createRecurrent: Boolean): Mono<Budget> {
fun createBudget(spaceId: String, budget: Budget, createRecurrent: Boolean): Mono<Budget> {
return Mono.zip(
getBudgetByDate(budget.dateFrom).map { Optional.ofNullable(it) }
getBudgetByDate(budget.dateFrom, spaceId).map { Optional.ofNullable(it) }
.switchIfEmpty(Mono.just(Optional.empty())),
getBudgetByDate(budget.dateTo).map { Optional.ofNullable(it) }
getBudgetByDate(budget.dateTo, spaceId).map { Optional.ofNullable(it) }
.switchIfEmpty(Mono.just(Optional.empty()))
).flatMap { tuple ->
val startBudget = tuple.t1.orElse(null)
@@ -283,36 +346,59 @@ class FinancialService(
return@flatMap Mono.error<Budget>(IllegalArgumentException("Бюджет с теми же датами найден"))
}
// Если createRecurrent=true, создаем рекуррентные транзакции
val recurrentsCreation = if (createRecurrent) {
recurrentService.createRecurrentsForBudget(budget)
} else {
Mono.empty()
}
// Получаем Space по spaceId
return@flatMap spaceService.getSpace(spaceId)
.switchIfEmpty(Mono.error(IllegalArgumentException("Space not found for $spaceId")))
// Создаем бюджет после возможного создания рекуррентных транзакций
recurrentsCreation.then(
getCategoryTransactionPipeline(budget.dateFrom, budget.dateTo)
.flatMap { categories ->
budget.categories = categories
budgetRepo.save(budget)
}
.publishOn(reactor.core.scheduler.Schedulers.boundedElastic())
.doOnNext { savedBudget ->
// Выполнение updateBudgetWarns в фоне
updateBudgetWarns(budget = savedBudget)
.doOnError { error ->
// Логируем ошибку, если произошла
println("Error during updateBudgetWarns: ${error.message}")
.flatMap { space ->
// Проверяем, входит ли пользователь в этот Space
ReactiveSecurityContextHolder.getContext().flatMap { securityContext ->
val username = securityContext.authentication.name
userService.getByUsername(username)
.switchIfEmpty(Mono.error(IllegalArgumentException("User not found for username: $username")))
.flatMap { user ->
if (space.users.none { it.id == user.id }) {
return@flatMap Mono.error<Budget>(IllegalArgumentException("User does not have access to this space"))
}
// Присваиваем Space бюджету
budget.space = space
// Если createRecurrent=true, создаем рекуррентные транзакции
val recurrentsCreation = if (createRecurrent) {
recurrentService.createRecurrentsForBudget(space, budget)
} else {
Mono.empty()
}
// Создаем бюджет после возможного создания рекуррентных транзакций
recurrentsCreation.then(
getCategoryTransactionPipeline(budget.dateFrom, budget.dateTo)
.flatMap { categories ->
budget.categories = categories
budgetRepo.save(budget)
}
.publishOn(reactor.core.scheduler.Schedulers.boundedElastic())
.doOnNext { savedBudget ->
// Выполнение updateBudgetWarns в фоне
updateBudgetWarns(budget = savedBudget)
.doOnError { error ->
// Логируем ошибку, если произошла
println("Error during updateBudgetWarns: ${error.message}")
}
.subscribe()
}
)
}
.subscribe()
}
)
}
}
}
fun getBudgetByDate(date: LocalDate): Mono<Budget> {
return budgetRepo.findByDateFromLessThanEqualAndDateToGreaterThanEqual(date, date).switchIfEmpty(Mono.empty())
fun getBudgetByDate(date: LocalDate, spaceId: String): Mono<Budget> {
return budgetRepo.findByDateFromLessThanEqualAndDateToGreaterThanEqualAndSpace(date, date, ObjectId(spaceId))
.switchIfEmpty(Mono.empty())
}
@@ -530,6 +616,7 @@ class FinancialService(
@Cacheable("transactions")
fun getTransactions(
spaceId: String,
dateFrom: LocalDate? = null,
dateTo: LocalDate? = null,
transactionType: String? = null,
@@ -543,46 +630,71 @@ class FinancialService(
limit: Int? = null,
offset: Int? = null,
): Mono<MutableList<Transaction>> {
val matchCriteria = mutableListOf<Criteria>()
return ReactiveSecurityContextHolder.getContext()
.map { it.authentication }
.flatMap { authentication ->
val username = authentication.name
spaceService.getSpace(spaceId)
.switchIfEmpty(Mono.error(IllegalArgumentException("Space not found for $spaceId")))
.flatMap { space ->
userService.getByUsername(username)
.switchIfEmpty(Mono.error(IllegalArgumentException("User not found for username: $username")))
.flatMap { user ->
if (space.users.none { it.id.toString() == user.id }) {
return@flatMap Mono.error<MutableList<Transaction>>(IllegalArgumentException("User does not have access to this Space"))
}
// Добавляем фильтры
dateFrom?.let { matchCriteria.add(Criteria.where("date").gte(it)) }
dateTo?.let { matchCriteria.add(Criteria.where("date").lt(it)) }
transactionType?.let { matchCriteria.add(Criteria.where("type.code").`is`(it)) }
isDone?.let { matchCriteria.add(Criteria.where("isDone").`is`(it)) }
categoryId?.let { matchCriteria.add(Criteria.where("categoryDetails._id").`is`(it)) }
categoryType?.let { matchCriteria.add(Criteria.where("categoryDetails.type.code").`is`(it)) }
userId?.let { matchCriteria.add(Criteria.where("userDetails._id").`is`(ObjectId(it))) }
parentId?.let { matchCriteria.add(Criteria.where("parentId").`is`(it)) }
isChild?.let { matchCriteria.add(Criteria.where("parentId").exists(it)) }
val matchCriteria = mutableListOf<Criteria>()
// Сборка агрегации
val lookup = lookup("categories", "category.\$id", "_id", "categoryDetails")
val lookupUsers = lookup("users", "user.\$id", "_id", "userDetails")
val match = match(Criteria().andOperator(*matchCriteria.toTypedArray()))
// Добавляем фильтры
matchCriteria.add(Criteria.where("spaceDetails._id").`is`(ObjectId(spaceId)))
dateFrom?.let { matchCriteria.add(Criteria.where("date").gte(it)) }
dateTo?.let { matchCriteria.add(Criteria.where("date").lt(it)) }
transactionType?.let { matchCriteria.add(Criteria.where("type.code").`is`(it)) }
isDone?.let { matchCriteria.add(Criteria.where("isDone").`is`(it)) }
categoryId?.let { matchCriteria.add(Criteria.where("categoryDetails._id").`is`(it)) }
categoryType?.let {
matchCriteria.add(
Criteria.where("categoryDetails.type.code").`is`(it)
)
}
userId?.let { matchCriteria.add(Criteria.where("userDetails._id").`is`(ObjectId(it))) }
parentId?.let { matchCriteria.add(Criteria.where("parentId").`is`(it)) }
isChild?.let { matchCriteria.add(Criteria.where("parentId").exists(it)) }
var sort = sort(Sort.by(Direction.DESC, "date").and(Sort.by(Direction.DESC, "createdAt")))
// Сборка агрегации
val lookup = lookup("categories", "category.\$id", "_id", "categoryDetails")
val lookupSpaces = lookup("spaces", "space.\$id", "_id", "spaceDetails")
val lookupUsers = lookup("users", "user.\$id", "_id", "userDetails")
val match = match(Criteria().andOperator(*matchCriteria.toTypedArray()))
sortSetting?.let {
sort = sort(Sort.by(it.order, it.by).and(Sort.by(Direction.ASC, "createdAt")))
}
var sort =
sort(Sort.by(Direction.DESC, "date").and(Sort.by(Direction.DESC, "createdAt")))
val aggregationBuilder = mutableListOf(
lookup,
lookupUsers,
match.takeIf { matchCriteria.isNotEmpty() },
sort,
offset?.let { skip(it.toLong()) },
limit?.let { limit(it.toLong()) }
).filterNotNull()
sortSetting?.let {
sort = sort(Sort.by(it.order, it.by).and(Sort.by(Direction.ASC, "createdAt")))
}
val aggregation = newAggregation(aggregationBuilder)
val aggregationBuilder = mutableListOf(
lookup,
lookupSpaces,
lookupUsers,
match.takeIf { matchCriteria.isNotEmpty() },
sort,
offset?.let { skip(it.toLong()) },
limit?.let { limit(it.toLong()) }
).filterNotNull()
return reactiveMongoTemplate.aggregate(
aggregation, "transactions", Transaction::class.java
)
.collectList() // Преобразуем Flux<Transaction> в Mono<List<Transaction>>
.map { it.toMutableList() }
val aggregation = newAggregation(aggregationBuilder)
return@flatMap reactiveMongoTemplate.aggregate(
aggregation, "transactions", Transaction::class.java
)
.collectList()
.map { it.toMutableList() }
}
}
}
}
fun getTransactionsToDelete(dateFrom: LocalDate, dateTo: LocalDate): Mono<List<Transaction>> {
@@ -618,19 +730,29 @@ class FinancialService(
@CacheEvict(cacheNames = ["transactions"], allEntries = true)
fun createTransaction(transaction: Transaction): Mono<Transaction> {
fun createTransaction(spaceId: String, transaction: Transaction): Mono<Transaction> {
return ReactiveSecurityContextHolder.getContext()
.map { it.authentication }
.flatMap { authentication ->
val username = authentication.name
userService.getByUsername(username)
.switchIfEmpty(Mono.error(IllegalArgumentException("User not found for username: $username")))
.flatMap { user ->
transaction.user = user
transactionsRepo.save(transaction)
.flatMap { savedTransaction ->
updateBudgetOnCreate(savedTransaction)
.thenReturn(savedTransaction) // Ждём выполнения updateBudgetOnCreate перед возвратом
spaceService.getSpace(spaceId)
.switchIfEmpty(Mono.error(IllegalArgumentException("Space not found for $spaceId")))
.flatMap { space ->
userService.getByUsername(username)
.switchIfEmpty(Mono.error(IllegalArgumentException("User not found for username: $username")))
.flatMap { user ->
if (space.users.none { it.id.toString() == user.id }) {
return@flatMap Mono.error<Transaction>(IllegalArgumentException("User does not have access to this Space"))
}
// Привязываем space и user к транзакции
transaction.user = user
transaction.space = space
transactionsRepo.save(transaction)
.flatMap { savedTransaction ->
updateBudgetOnCreate(savedTransaction)
.thenReturn(savedTransaction) // Ждём выполнения updateBudgetOnCreate перед возвратом
}
}
}
}
@@ -1034,8 +1156,8 @@ class FinancialService(
tgUserName = userDocument["tgUserName"]?.let { it as String },
password = null,
isActive = userDocument["isActive"] as Boolean,
regDate = userDocument["regDate"] as Date,
createdAt = userDocument["createdAt"] as Date,
regDate = userDocument["regDate"] as LocalDate,
createdAt = userDocument["createdAt"] as LocalDateTime,
roles = userDocument["roles"] as ArrayList<String>,
)
@@ -1051,6 +1173,7 @@ class FinancialService(
)
return Transaction(
(document["_id"] as ObjectId).toString(),
null,
TransactionType(
transactionType["code"] as String,
transactionType["name"] as String
@@ -1582,7 +1705,7 @@ class FinancialService(
.collectList()
}
fun getCategorySummaries(dateFrom: LocalDate): Mono<List<Document>> {
fun getCategorySummaries(spaceId: String, dateFrom: LocalDate): Mono<List<Document>> {
val sixMonthsAgo = Date.from(
LocalDateTime.of(dateFrom, LocalTime.MIN)
.atZone(ZoneId.systemDefault())
@@ -1591,6 +1714,16 @@ class FinancialService(
val aggregation = listOf(
// 1. Фильтр за последние 6 месяцев
Document(
"\$lookup", Document("from", "spaces")
.append("localField", "space.\$id")
.append("foreignField", "_id")
.append("as", "spaceInfo")
),
// 4. Распаковываем массив категорий
Document("\$unwind", "\$spaceInfo"),
Document("\$match", Document("spaceInfo._id", ObjectId(spaceId))),
Document(
"\$match",
Document("date", Document("\$gte", sixMonthsAgo).append("\$lt", Date())).append("type.code", "INSTANT")
@@ -1720,6 +1853,7 @@ class FinancialService(
Document("\$sort", Document("categoryName", 1))
)
// Выполняем агрегацию
return reactiveMongoTemplate.getCollection("transactions")
.flatMapMany { it.aggregate(aggregation) }

View File

@@ -1,17 +1,14 @@
package space.luminic.budgerapp.services
import org.bson.types.ObjectId
import org.slf4j.LoggerFactory
import org.springframework.cache.annotation.CacheEvict
import org.springframework.cache.annotation.Cacheable
import org.springframework.security.core.context.ReactiveSecurityContextHolder
import org.springframework.stereotype.Service
import reactor.core.publisher.Mono
import space.luminic.budgerapp.models.Budget
import space.luminic.budgerapp.models.NotFoundException
import space.luminic.budgerapp.models.Recurrent
import space.luminic.budgerapp.models.Transaction
import space.luminic.budgerapp.models.TransactionType
import space.luminic.budgerapp.models.*
import space.luminic.budgerapp.repos.RecurrentRepo
import space.luminic.budgerapp.repos.TransactionRepo
import java.time.YearMonth
@@ -22,31 +19,40 @@ class RecurrentService(
private val recurrentRepo: RecurrentRepo,
private val transactionRepo: TransactionRepo,
private val userService: UserService,
private val spaceService: SpaceService,
) {
private val logger = LoggerFactory.getLogger(javaClass)
@Cacheable("recurrentsList")
fun getRecurrents(): Mono<List<Recurrent>> {
return recurrentRepo.findAll().collectList()
fun getRecurrents(space: Space): Mono<List<Recurrent>> {
// Запрос рекуррентных платежей
return recurrentRepo.findRecurrentsBySpaceId(ObjectId(space.id))
.collectList() // Преобразуем Flux<Recurrent> в Mono<List<Recurrent>>
}
@Cacheable("recurrents", key = "#id")
fun getRecurrentById(id: String): Mono<Recurrent> {
fun getRecurrentById(space: Space, id: String): Mono<Recurrent> {
// Запрос рекуррентных платежей
return recurrentRepo.findById(id)
.switchIfEmpty(Mono.error(NotFoundException("Recurrent with id: $id not found")))
}
@CacheEvict(cacheNames = ["recurrentsList", "recurrents"])
fun createRecurrent(recurrent: Recurrent): Mono<Recurrent> {
return if (recurrent.id == null && recurrent.atDay <= 31) recurrentRepo.save(recurrent) else Mono.error(
fun createRecurrent(space: Space, recurrent: Recurrent): Mono<Recurrent> {
return if (recurrent.id == null && recurrent.atDay <= 31) {
recurrent.space = space
recurrentRepo.save(recurrent)
} else Mono.error(
RuntimeException("Cannot create recurrent with id or date cannot be higher than 31")
)
}
@CacheEvict(cacheNames = ["recurrentsList", "recurrents"])
fun createRecurrentsForBudget(budget: Budget): Mono<Void> {
fun createRecurrentsForBudget(space: Space, budget: Budget): Mono<Void> {
val currentYearMonth = YearMonth.of(budget.dateFrom.year, budget.dateFrom.monthValue)
val daysInCurrentMonth = currentYearMonth.lengthOfMonth()
val context = ReactiveSecurityContextHolder.getContext()
@@ -63,7 +69,7 @@ class RecurrentService(
.switchIfEmpty(Mono.error(IllegalArgumentException("User not found for username: $username")))
}
.flatMapMany { user ->
recurrentRepo.findAll()
recurrentRepo.findRecurrentsBySpaceId(ObjectId(space.id))
.map { recurrent ->
// Определяем дату транзакции
val transactionDate = when {
@@ -111,7 +117,17 @@ class RecurrentService(
return recurrentRepo.deleteById(id)
}
fun regenRecurrents(): Mono<List<Recurrent>> {
return recurrentRepo.findAll()
.flatMap { recurrent ->
spaceService.getSpace("67af3c0f652da946a7dd9931")
.flatMap { space ->
recurrent.space = space
recurrentRepo.save(recurrent) // Сохраняем и возвращаем сохраненный объект
}
}
.collectList() // Собираем результаты в список
}
}

View File

@@ -0,0 +1,233 @@
package space.luminic.budgerapp.services
import org.bson.types.ObjectId
import org.springframework.data.domain.Sort
import org.springframework.data.domain.Sort.Direction
import org.springframework.security.core.context.ReactiveSecurityContextHolder
import org.springframework.stereotype.Service
import reactor.core.publisher.Mono
import space.luminic.budgerapp.models.Space
import space.luminic.budgerapp.models.SpaceInvite
import space.luminic.budgerapp.models.Transaction
import space.luminic.budgerapp.repos.BudgetRepo
import space.luminic.budgerapp.repos.SpaceRepo
import space.luminic.budgerapp.repos.UserRepo
import java.time.LocalDateTime
import java.util.UUID
@Service
class SpaceService(
private val spaceRepo: SpaceRepo,
private val userService: UserService,
private val budgetRepo: BudgetRepo,
private val userRepo: UserRepo
) {
fun isValidRequest(spaceId: String): Mono<Space> {
return ReactiveSecurityContextHolder.getContext()
.map { it.authentication }
.flatMap { authentication ->
val username = authentication.name
// Получаем пользователя по имени
userService.getByUsername(username)
.switchIfEmpty(Mono.error(IllegalArgumentException("User not found for username: $username")))
.flatMap { user ->
// Получаем пространство по ID
spaceRepo.findById(spaceId)
.switchIfEmpty(Mono.error(IllegalArgumentException("Space not found for id: $spaceId")))
.flatMap { space ->
// Проверяем доступ пользователя к пространству
if (space.users.none { it.id.toString() == user.id }) {
return@flatMap Mono.error<Space>(IllegalArgumentException("User does not have access to this Space"))
}
// Если проверка прошла успешно, возвращаем пространство
Mono.just(space)
}
}
}
}
fun getSpaces(): Mono<List<Space>> {
return ReactiveSecurityContextHolder.getContext()
.map { it.authentication }
.flatMap { authentication ->
val username = authentication.name
userService.getByUsername(username)
.switchIfEmpty(Mono.error(IllegalArgumentException("User not found for username: $username")))
.flatMapMany { user ->
spaceRepo.findByArrayElement(ObjectId(user.id!!))
}
.collectList() // Возвращаем Mono<List<Space>>
}
}
fun getSpace(spaceId: String): Mono<Space> {
return spaceRepo.findById(spaceId)
.switchIfEmpty(Mono.error(IllegalArgumentException("SpaceId not found for spaceId: $spaceId")))
}
fun createSpace(space: Space): Mono<Space> {
return ReactiveSecurityContextHolder.getContext()
.map { it.authentication }
.flatMap { authentication ->
val username = authentication.name
userService.getByUsername(username)
.switchIfEmpty(Mono.error(IllegalArgumentException("User not found for username: $username")))
.flatMap { user ->
space.owner = user
space.users.add(user)
spaceRepo.save(space)
}
}
}
fun deleteSpace(spaceId: String): Mono<Void> {
return budgetRepo.findBySpaceId(ObjectId(spaceId), Sort.by(Direction.DESC, "dateFrom"))
.flatMap { budget ->
budgetRepo.delete(budget) // Удаляем все бюджеты, связанные с этим Space
}
.then(spaceRepo.deleteById(spaceId)) // Затем удаляем сам Space
}
fun createInviteSpace(spaceId: String): Mono<SpaceInvite> {
return ReactiveSecurityContextHolder.getContext()
.map { it.authentication }
.flatMap { authentication ->
val username = authentication.name
userService.getByUsername(username)
.switchIfEmpty(Mono.error(IllegalArgumentException("User not found for username: $username")))
.flatMap { user ->
spaceRepo.findById(spaceId)
.switchIfEmpty(Mono.error(IllegalArgumentException("Space not found for id: $spaceId")))
.flatMap { space ->
if (space.users.none { it.id.toString() == user.id }) {
return@flatMap Mono.error<SpaceInvite>(IllegalArgumentException("User does not have access to this Space"))
}
val invite = SpaceInvite(
UUID.randomUUID().toString().split("-")[0],
user,
LocalDateTime.now().plusHours(1),
)
space.invites.add(invite)
// Сохраняем изменения и возвращаем созданное приглашение
spaceRepo.save(space).thenReturn(invite)
}
}
}
}
fun acceptInvite(code: String): Mono<Space> {
return ReactiveSecurityContextHolder.getContext()
.map { it.authentication }
.flatMap { authentication ->
val username = authentication.name
userService.getByUsername(username)
.switchIfEmpty(Mono.error(IllegalArgumentException("User not found for username: $username")))
.flatMap { user ->
spaceRepo.findSpaceByInvites(code)
.switchIfEmpty(Mono.error(IllegalArgumentException("Space with invite code: $code not found")))
.flatMap { space ->
val invite = space.invites.find { it.code == code }
// Проверяем, есть ли инвайт и не истек ли он
if (invite == null || invite.activeTill.isBefore(LocalDateTime.now())) {
return@flatMap Mono.error<Space>(IllegalArgumentException("Invite is invalid or expired"))
}
// Проверяем, не является ли пользователь уже участником
if (space.users.any { it.id == user.id }) {
return@flatMap Mono.error<Space>(IllegalArgumentException("User is already a member of this Space"))
}
// Добавляем пользователя и удаляем использованный инвайт
space.users.add(user)
space.invites.remove(invite)
spaceRepo.save(space)
}
}
}
}
fun leaveSpace(spaceId: String): Mono<Void> {
return ReactiveSecurityContextHolder.getContext()
.map { it.authentication }
.flatMap { authentication ->
val username = authentication.name
userService.getByUsername(username)
.switchIfEmpty(Mono.error(IllegalArgumentException("User not found for username: $username")))
.flatMap { user ->
spaceRepo.findById(spaceId)
.switchIfEmpty(Mono.error(IllegalArgumentException("Space not found for id: $spaceId")))
.flatMap { space ->
if (space.users.none { it.id.toString() == user.id }) {
return@flatMap Mono.error<Void>(IllegalArgumentException("User does not have access to this Space"))
}
// Удаляем пользователя из массива
space.users.removeIf { it.id == user.id }
// Сохраняем изменения
spaceRepo.save(space).then() // .then() для Mono<Void>
}
}
}
}
fun kickMember(spaceId: String, kickedUsername: String): Mono<Void> {
return ReactiveSecurityContextHolder.getContext()
.map { it.authentication }
.flatMap { authentication ->
val username = authentication.name
// Получаем текущего пользователя
userService.getByUsername(username)
.switchIfEmpty(Mono.error(IllegalArgumentException("User not found for username: $username")))
.flatMap { user ->
// Получаем пользователя, которого нужно исключить
userService.getByUsername(kickedUsername)
.switchIfEmpty(Mono.error(IllegalArgumentException("User not found for username: $kickedUsername")))
.flatMap { kickedUser ->
// Получаем пространство
spaceRepo.findById(spaceId)
.switchIfEmpty(Mono.error(IllegalArgumentException("Space not found for id: $spaceId")))
.flatMap { space ->
// Проверяем, является ли текущий пользователь владельцем
if (space.owner?.id != user.id) {
return@flatMap Mono.error<Void>(IllegalArgumentException("Only owners allowed for this action"))
}
// Проверяем, что пользователь, которого нужно исключить, присутствует в списке пользователей
val userToKick = space.users.find { it.username == kickedUsername }
if (userToKick != null) {
// Удаляем пользователя из пространства
space.users.removeIf { it.username == kickedUsername }
// Сохраняем изменения
return@flatMap spaceRepo.save(space).then()
} else {
return@flatMap Mono.error<Void>(IllegalArgumentException("User not found in this space"))
}
}
}
}
}
}
// fun regenSpaces(): Mono<List<Space>> {
// return spaceRepo.findAll()
// .flatMap { space ->
// userService.getUsers()
// .flatMap { users ->
// if (users.isEmpty()) {
// return@flatMap Mono.error<Space>(IllegalStateException("No users found"))
// }
// val updatedSpace = space.copy(owner = users.first()) // Создаем копию (если `Space` data class)
// spaceRepo.save(updatedSpace)
// }
// }
// .collectList()
// }
}