-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathStatisticService.kt
More file actions
326 lines (279 loc) · 10.6 KB
/
StatisticService.kt
File metadata and controls
326 lines (279 loc) · 10.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
package com.stepbookstep.server.domain.reading.application
import com.stepbookstep.server.domain.book.domain.BookRepository
import com.stepbookstep.server.domain.reading.domain.*
import com.stepbookstep.server.domain.reading.presentation.dto.*
import org.springframework.cache.annotation.Cacheable
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.time.LocalDate
import java.time.Year
import java.time.YearMonth
import kotlin.math.roundToInt
@Service
class StatisticsService(
private val userBookRepository: UserBookRepository,
private val readingLogRepository: ReadingLogRepository,
private val readingGoalRepository: ReadingGoalRepository,
private val bookRepository: BookRepository
) {
/**
* 전체 독서 통계 조회
*/
@Cacheable(value = ["userStatistics"], key = "#userId + '_' + #year")
@Transactional(readOnly = true)
fun getReadingStatistics(userId: Long, year: Int): ReadingStatisticsResponse {
return ReadingStatisticsResponse(
bookSummary = getBookSummary(userId),
monthlyGraph = getMonthlyGraph(userId, year),
cumulativeTime = getCumulativeTime(userId),
goalAchievement = getGoalAchievement(userId),
categoryPreference = getCategoryPreference(userId)
)
}
/**
* 완독한 책 요약 정보
*/
@Transactional(readOnly = true)
fun getBookSummary(userId: Long): BookSummaryDto {
val finishedBooks = userBookRepository.findFinishedBooksByUserId(userId)
val finishedBookCount = finishedBooks.size
val totalWeightKg = finishedBooks.sumOf { userBook ->
(userBook.book.weight ?: 0).toDouble()
} / 1000.0 // g을 kg으로 변환
return BookSummaryDto(
finishedBookCount = finishedBookCount,
totalWeightKg = String.format("%.1f", totalWeightKg).toDouble()
)
}
/**
* 월별 독서 그래프
*/
@Transactional(readOnly = true)
fun getMonthlyGraph(userId: Long, year: Int): MonthlyGraphResponse {
val currentMonth = if (Year.now().value == year) {
YearMonth.now().monthValue
} else {
-1
}
val monthlyData = readingLogRepository.countFinishedBooksGroupedByMonth(userId, year)
.associate {
val month = (it[0] as Number).toInt()
val count = (it[1] as Number).toInt()
month to count
}
val allMonthsData = (1..12).map { month ->
MonthlyDataDto(
month = month,
bookCount = monthlyData[month] ?: 0,
isCurrentMonth = month == currentMonth
)
}
return MonthlyGraphResponse(
year = year,
monthlyData = allMonthsData
)
}
/**
* 누적 독서 시간
*/
@Transactional(readOnly = true)
fun getCumulativeTime(userId: Long): CumulativeTimeDto {
val totalSeconds = readingLogRepository.sumAllDurationByUserId(userId)
?.toLong() ?: 0L
val totalMinutes = (totalSeconds / 60).toInt()
val hours = (totalMinutes / 60)
val minutes = (totalMinutes % 60)
val days=hours/24
return CumulativeTimeDto(
hours = hours,
minutes = minutes,
totalMinutes = totalMinutes,
days=days,
)
}
/**
* 누적 목표 달성 기록
*/
@Transactional(readOnly = true)
fun getGoalAchievement(userId: Long): GoalAchievementDto {
// 모든 목표 조회 (활성/비활성 포함)
val allGoals = readingGoalRepository.findAllByUserId(userId)
if (allGoals.isEmpty()) {
return GoalAchievementDto(
achievementRate = 0,
maxAchievementRate = 0
)
}
// 모든 목표의 기록을 한 번에 조회 (N+1 쿼리 방지)
val bookIds = allGoals.map { it.bookId }.distinct()
val earliestGoalDate = allGoals.minOf { it.createdAt.toLocalDate() }
val allLogs = readingLogRepository.findAllByBooksInDateRange(
userId = userId,
bookIds = bookIds,
startDate = earliestGoalDate
).groupBy { it.bookId }
var totalPeriods = 0
var achievedPeriods = 0
allGoals.forEach { goal ->
val goalStartDate = goal.createdAt.toLocalDate()
val goalEndDate = if (goal.active) {
LocalDate.now()
} else {
goal.updatedAt.toLocalDate()
}
val periods = getPeriodsBetweenDates(goalStartDate, goalEndDate, goal.period)
val bookLogs = allLogs[goal.bookId] ?: emptyList()
periods.forEach { (startDate, endDate) ->
totalPeriods++
val achieved = checkPeriodAchievementInMemory(
logs = bookLogs,
startDate = startDate,
endDate = endDate,
metric = goal.metric,
targetAmount = goal.targetAmount
)
if (achieved) {
achievedPeriods++
}
}
}
val achievementRate = if (totalPeriods > 0) {
((achievedPeriods.toDouble() / totalPeriods) * 100).roundToInt()
} else {
0
}
val maxAchievementRate = calculateMaxAchievementRateInMemory(userId, allGoals, allLogs)
return GoalAchievementDto(
achievementRate = achievementRate,
maxAchievementRate = maxAchievementRate
)
}
/**
* 기간 달성 여부 확인
*/
private fun checkPeriodAchievementInMemory(
logs: List<ReadingLog>,
startDate: LocalDate,
endDate: LocalDate,
metric: GoalMetric,
targetAmount: Int
): Boolean {
val actualAmount = when (metric) {
GoalMetric.PAGE -> {
// 기간 시작 전 마지막 기록
val baselineRecord = logs
.filter { it.recordDate < startDate && it.readQuantity != null }
.maxByOrNull { it.recordDate }
// 기간 내 마지막 기록
val lastRecordInPeriod = logs
.filter { it.recordDate in startDate..endDate && it.readQuantity != null }
.maxByOrNull { it.recordDate }
val baseline = baselineRecord?.readQuantity ?: 0
val endValue = lastRecordInPeriod?.readQuantity ?: return false
(endValue - baseline).coerceAtLeast(0)
}
GoalMetric.TIME -> {
logs
.filter { it.recordDate in startDate..endDate && it.durationSeconds != null }
.sumOf { it.durationSeconds ?: 0 } / 60
}
}
return actualAmount >= targetAmount
}
/**
* 날짜 범위를 기간 단위로 나눔
* 목표 생성일 기준으로 기간 분할
*/
private fun getPeriodsBetweenDates(
startDate: LocalDate,
endDate: LocalDate,
period: GoalPeriod
): List<Pair<LocalDate, LocalDate>> {
val periods = mutableListOf<Pair<LocalDate, LocalDate>>()
var currentDate = startDate
while (currentDate <= endDate) {
val periodEnd = when (period) {
GoalPeriod.DAILY -> currentDate
GoalPeriod.WEEKLY -> {
// 생성일 기준 7일 단위
currentDate.plusDays(6).coerceAtMost(endDate)
}
GoalPeriod.MONTHLY -> {
// 생성일 기준 1개월 단위
currentDate.plusMonths(1).minusDays(1).coerceAtMost(endDate)
}
}
periods.add(currentDate to periodEnd)
currentDate = when (period) {
GoalPeriod.DAILY -> currentDate.plusDays(1)
GoalPeriod.WEEKLY -> periodEnd.plusDays(1)
GoalPeriod.MONTHLY -> periodEnd.plusDays(1)
}
}
return periods
}
/**
* 개별 목표별 최고 달성률 계산
*/
private fun calculateMaxAchievementRateInMemory(
userId: Long,
goals: List<ReadingGoal>,
allLogs: Map<Long, List<ReadingLog>>
): Int {
return goals.maxOfOrNull { goal ->
val goalStartDate = goal.createdAt.toLocalDate()
val goalEndDate = if (goal.active) {
LocalDate.now()
} else {
goal.updatedAt.toLocalDate()
}
val periods = getPeriodsBetweenDates(goalStartDate, goalEndDate, goal.period)
val bookLogs = allLogs[goal.bookId] ?: emptyList()
if (periods.isEmpty()) return@maxOfOrNull 0
val achievedCount = periods.count { (startDate, endDate) ->
checkPeriodAchievementInMemory(
logs = bookLogs,
startDate = startDate,
endDate = endDate,
metric = goal.metric,
targetAmount = goal.targetAmount
)
}
((achievedCount.toDouble() / periods.size) * 100).roundToInt()
} ?: 0
}
/**
* 선호 분야 통계
*/
@Transactional(readOnly = true)
fun getCategoryPreference(userId: Long): CategoryPreferenceResponse {
val finishedBooks = userBookRepository.findFinishedBooksByUserId(userId)
val totalBookCount = finishedBooks.size
if (totalBookCount == 0) {
return CategoryPreferenceResponse(
totalBookCount = 0,
categories = emptyList()
)
}
// 장르별 집계 (Book의 genre 필드 사용)
val categoryCountMap = mutableMapOf<String, Int>()
finishedBooks.forEach { userBook ->
val category = userBook.book.origin.ifBlank { "미분류" }
categoryCountMap[category] = categoryCountMap.getOrDefault(category, 0) + 1
}
val sortedCategories = categoryCountMap.entries
.sortedByDescending { it.value }
val categories = sortedCategories.mapIndexed { index, entry ->
CategoryDto(
rank = index + 1,
categoryName = entry.key,
bookCount = entry.value,
percentage = ((entry.value.toDouble() / totalBookCount) * 100).roundToInt()
)
}
return CategoryPreferenceResponse(
totalBookCount = totalBookCount,
categories = categories
)
}
}