-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathReadingLogService.kt
More file actions
290 lines (246 loc) · 10.3 KB
/
ReadingLogService.kt
File metadata and controls
290 lines (246 loc) · 10.3 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
package com.stepbookstep.server.domain.reading.application
import com.stepbookstep.server.domain.book.domain.BookRepository
import com.stepbookstep.server.domain.mypage.domain.ReadStatus
import com.stepbookstep.server.domain.reading.domain.GoalMetric
import com.stepbookstep.server.domain.reading.domain.ReadingGoalRepository
import com.stepbookstep.server.domain.reading.domain.ReadingLog
import com.stepbookstep.server.domain.reading.domain.ReadingLogRepository
import com.stepbookstep.server.domain.reading.domain.ReadingLogStatus
import com.stepbookstep.server.domain.reading.domain.ReadingLogStatus.*
import com.stepbookstep.server.domain.reading.domain.UserBook
import com.stepbookstep.server.domain.reading.domain.UserBookRepository
import com.stepbookstep.server.domain.reading.presentation.dto.BookReadingDetailResponse
import com.stepbookstep.server.domain.reading.presentation.dto.GoalInfo
import com.stepbookstep.server.domain.reading.presentation.dto.ReadingLogItem
import com.stepbookstep.server.global.response.CustomException
import com.stepbookstep.server.global.response.ErrorCode
import org.springframework.cache.annotation.CacheEvict
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.time.LocalDate
import java.time.OffsetDateTime
@Service
class ReadingLogService(
private val readingLogRepository: ReadingLogRepository,
private val userBookRepository: UserBookRepository,
private val bookRepository: BookRepository,
private val readingGoalRepository: ReadingGoalRepository
) {
@CacheEvict(value = ["userStatistics"], key = "#userId + '_' + T(java.time.Year).now().value")
@Transactional
fun createLog(
userId: Long,
bookId: Long,
bookStatus: ReadingLogStatus,
recordDate: LocalDate?,
readQuantity: Int?,
durationSeconds: Int?,
rating: Int?
): CreateLogResult {
validateBookExists(bookId)
validateByStatus(
userId = userId,
bookId = bookId,
bookStatus = bookStatus,
readQuantity = readQuantity,
durationSeconds = durationSeconds,
rating = rating
)
val book = bookRepository.findById(bookId)
.orElseThrow { CustomException(ErrorCode.BOOK_NOT_FOUND) }
val userBook = userBookRepository.findByUserIdAndBookId(userId, bookId)
?: userBookRepository.save(
UserBook(
userId = userId,
book = book,
status = bookStatus.toReadStatus()
)
)
val actualRecordDate = recordDate ?: LocalDate.now()
val now = OffsetDateTime.now()
val targetStatus = bookStatus.toReadStatus()
if (userBook.status != targetStatus) {
userBook.status = targetStatus
}
when (bookStatus) {
FINISHED -> {
userBook.finishedAt = actualRecordDate.atStartOfDay().atOffset(now.offset)
userBook.rating = rating
}
STOPPED -> {
userBook.finishedAt = actualRecordDate.atStartOfDay().atOffset(now.offset)
userBook.rating = rating
}
READING -> Unit
}
userBook.updatedAt = now
// 완독/중지 시에는 페이지/시간 무시, READING일 때만 저장
val log = readingLogRepository.save(
ReadingLog(
userId = userId,
bookId = bookId,
bookStatus = bookStatus,
recordDate = actualRecordDate,
readQuantity = if (bookStatus == READING) readQuantity else null,
durationSeconds = if (bookStatus == READING) durationSeconds else null,
rating = if (bookStatus == READING) null else rating
)
)
if (bookStatus == READING) {
userBook.totalPagesRead = readQuantity ?: userBook.totalPagesRead
val totalPages = book.itemPage ?: 0
userBook.progressPercent =
if (totalPages > 0 && userBook.totalPagesRead > 0) {
((userBook.totalPagesRead.toDouble() / totalPages) * 100).toInt().coerceIn(0, 100)
} else 0
}
if (bookStatus == FINISHED || bookStatus == STOPPED) {
deactivateActiveGoalIfExists(userId, bookId)
}
val finishedCount: Int? = if (bookStatus == FINISHED) {
userBookRepository.countByUserIdAndStatus(userId, ReadStatus.FINISHED)
} else null
return CreateLogResult(log, finishedCount)
}
private fun validateBookExists(bookId: Long) {
if (!bookRepository.existsById(bookId)) {
throw CustomException(ErrorCode.BOOK_NOT_FOUND)
}
}
/**
* 상태별 검증.
* READING이면 activeGoal을 반환해서 아래 로직(필요시)에 재사용 가능하게 할 수도 있음.
*/
private fun validateByStatus(
userId: Long,
bookId: Long,
bookStatus: ReadingLogStatus,
readQuantity: Int?,
durationSeconds: Int?,
rating: Int?
) = when (bookStatus) {
READING -> validateReadingLog(userId, bookId, readQuantity, durationSeconds)
FINISHED -> {
validateRating(rating)
null
}
STOPPED -> {
validateRating(rating)
null
}
}
private fun validateReadingLog(
userId: Long,
bookId: Long,
readQuantity: Int?,
durationSeconds: Int?
) = run {
val activeGoal = readingGoalRepository.findByUserIdAndBookIdAndActiveTrue(userId, bookId)
?: throw CustomException(ErrorCode.GOAL_NOT_FOUND)
// 읽은 페이지 필수 검증
if (readQuantity == null) {
throw CustomException(ErrorCode.READ_QUANTITY_REQUIRED)
}
// 페이지 역행 검증 (이전 기록보다 적은 페이지 입력 불가)
validatePageProgression(userId, bookId, readQuantity)
// 목표 metric에 따른 추가 검증
validateByGoalMetric(activeGoal.metric, durationSeconds)
activeGoal
}
/**
* 페이지 역행 검증
* - 이전 기록보다 적은 페이지를 입력할 수 없음
*/
private fun validatePageProgression(userId: Long, bookId: Long, readQuantity: Int) {
val latestRecord = readingLogRepository.findLatestRecordByUserIdAndBookId(userId, bookId).firstOrNull()
if (latestRecord != null && latestRecord.readQuantity != null) {
if (readQuantity < latestRecord.readQuantity!!) {
throw CustomException(ErrorCode.PAGE_CANNOT_GO_BACK)
}
}
}
private fun validateByGoalMetric(metric: GoalMetric, durationSeconds: Int?) {
when (metric) {
GoalMetric.TIME -> {
if (durationSeconds == null) {
throw CustomException(ErrorCode.DURATION_REQUIRED)
}
}
GoalMetric.PAGE -> Unit
}
}
private fun validateRating(rating: Int?) {
when {
rating == null -> throw CustomException(ErrorCode.RATING_REQUIRED)
rating !in 1..5 -> throw CustomException(ErrorCode.INVALID_RATING)
}
}
private fun deactivateActiveGoalIfExists(userId: Long, bookId: Long) {
val activeGoal = readingGoalRepository.findByUserIdAndBookIdAndActiveTrue(userId, bookId)
if (activeGoal != null) {
activeGoal.active = false
activeGoal.updatedAt = OffsetDateTime.now()
readingGoalRepository.save(activeGoal)
}
}
private fun ReadingLogStatus.toReadStatus(): ReadStatus = when (this) {
READING -> ReadStatus.READING
FINISHED -> ReadStatus.FINISHED
STOPPED -> ReadStatus.STOPPED
}
/**
* 독서 상세 페이지 조회
* - 도서 상태, 목표, 진도, 시작일/종료일, 별점, 독서 기록 리스트
*/
@Transactional(readOnly = true)
fun getBookReadingDetail(userId: Long, bookId: Long): BookReadingDetailResponse {
val book = bookRepository.findById(bookId)
.orElseThrow { CustomException(ErrorCode.BOOK_NOT_FOUND) }
val userBook = userBookRepository.findByUserIdAndBookId(userId, bookId)
?: throw CustomException(ErrorCode.USER_BOOK_NOT_FOUND)
val goal = readingGoalRepository.findTopByUserIdAndBookIdOrderByCreatedAtDesc(userId, bookId)
val goalMetric = goal?.metric
val allLogs = readingLogRepository.findAllByUserIdAndBookIdOrderByRecordDateAscCreatedAtAsc(userId, bookId)
val currentPage = userBook.totalPagesRead
val totalPages = book.itemPage
val progressPercent = userBook.progressPercent
val startDate = allLogs.firstOrNull()?.recordDate
val endDate = allLogs
.lastOrNull { it.bookStatus == FINISHED || it.bookStatus == STOPPED }
?.recordDate
val rating = allLogs
.lastOrNull { (it.bookStatus == FINISHED || it.bookStatus == STOPPED) && it.rating != null }
?.rating
?: userBook.rating
val readingLogs = allLogs.filter { it.bookStatus == READING }
val readingLogItems = readingLogs.mapIndexed { index, log ->
val quantity = log.readQuantity
val prevQuantity = if (index > 0) readingLogs[index - 1].readQuantity ?: 0 else 0
val pagesRead = if (quantity != null) (quantity - prevQuantity).coerceAtLeast(0) else null
val percent = if (totalPages > 0 && quantity != null) {
((quantity.toDouble() / totalPages) * 100).toInt().coerceIn(0, 100)
} else null
ReadingLogItem(
logId = log.id,
recordDate = log.recordDate,
pagesRead = pagesRead,
durationSeconds = log.durationSeconds
)
}.reversed()
return BookReadingDetailResponse(
bookStatus = userBook.status,
goal = goal?.let { GoalInfo.from(it) },
currentPage = currentPage,
totalPages = totalPages,
progressPercent = progressPercent,
startDate = startDate,
endDate = endDate,
rating = rating,
readingLogs = readingLogItems
)
}
}
data class CreateLogResult(
val log: ReadingLog,
val finishedCount: Int?
)