-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTimetableThemeService.kt
More file actions
427 lines (358 loc) · 14.8 KB
/
Copy pathTimetableThemeService.kt
File metadata and controls
427 lines (358 loc) · 14.8 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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
package com.wafflestudio.snutt.theme.service
import com.wafflestudio.snutt.common.enums.BasicThemeType
import com.wafflestudio.snutt.common.exception.AlreadyDownloadedThemeException
import com.wafflestudio.snutt.common.exception.InvalidThemeColorCountException
import com.wafflestudio.snutt.common.exception.InvalidThemeTypeException
import com.wafflestudio.snutt.common.exception.NotDefaultThemeErrorException
import com.wafflestudio.snutt.common.exception.NotPublishedThemeException
import com.wafflestudio.snutt.common.exception.PublishedThemeDeleteErrorException
import com.wafflestudio.snutt.common.exception.ThemeNotFoundException
import com.wafflestudio.snutt.friend.dto.FriendState
import com.wafflestudio.snutt.friend.service.FriendService
import com.wafflestudio.snutt.theme.data.ColorSet
import com.wafflestudio.snutt.theme.data.ThemeMarketInfo
import com.wafflestudio.snutt.theme.data.ThemeOrigin
import com.wafflestudio.snutt.theme.data.ThemeStatus
import com.wafflestudio.snutt.theme.data.TimetableTheme
import com.wafflestudio.snutt.theme.dto.TimetableThemeDto
import com.wafflestudio.snutt.theme.repository.TimetableThemeRepository
import com.wafflestudio.snutt.timetables.data.Timetable
import com.wafflestudio.snutt.timetables.repository.TimetableRepository
import com.wafflestudio.snutt.users.service.UserService
import kotlinx.coroutines.flow.collect
import org.springframework.stereotype.Service
import java.time.LocalDateTime
interface TimetableThemeService {
suspend fun getThemes(userId: String): List<TimetableTheme>
suspend fun getBestThemes(page: Int): List<TimetableTheme>
suspend fun getFriendsThemes(
userId: String,
page: Int,
): List<TimetableTheme>
suspend fun addTheme(
userId: String,
name: String,
colors: List<ColorSet>,
): TimetableTheme
suspend fun modifyTheme(
userId: String,
themeId: String,
name: String?,
colors: List<ColorSet>?,
): TimetableTheme
suspend fun publishTheme(
userId: String,
themeId: String,
publishName: String,
authorAnonymous: Boolean,
)
suspend fun downloadTheme(
downloadedUserId: String,
themeId: String,
name: String,
): TimetableTheme
suspend fun deleteTheme(
userId: String,
themeId: String,
)
suspend fun deletePublishedTheme(
userId: String,
themeId: String,
)
suspend fun copyTheme(
userId: String,
themeId: String,
): TimetableTheme
suspend fun setDefault(
userId: String,
themeId: String? = null,
basicThemeType: BasicThemeType? = null,
): TimetableTheme
suspend fun unsetDefault(
userId: String,
themeId: String? = null,
basicThemeType: BasicThemeType? = null,
): TimetableTheme
suspend fun getDefaultTheme(userId: String): TimetableTheme
suspend fun getTheme(
userId: String,
themeId: String? = null,
basicThemeType: BasicThemeType? = null,
): TimetableTheme
suspend fun searchThemes(keyword: String): List<TimetableTheme>
suspend fun getNewColorIndexAndColor(timetable: Timetable): Pair<Int, ColorSet?>
suspend fun convertThemesToTimetableDtos(themes: List<TimetableTheme>): List<TimetableThemeDto>
}
@Service
class TimetableThemeServiceImpl(
private val timetableThemeRepository: TimetableThemeRepository,
private val timetableRepository: TimetableRepository,
private val friendService: FriendService,
private val userService: UserService,
) : TimetableThemeService {
companion object {
private const val MAX_COLOR_COUNT = 9
private val copyNumberRegex = """\s\(\d+\)$""".toRegex()
}
override suspend fun getThemes(userId: String): List<TimetableTheme> {
val defaultTheme = getDefaultTheme(userId)
val customThemes = timetableThemeRepository.findByUserIdAndIsCustomTrueOrderByUpdatedAtDesc(userId)
customThemes.forEach { if (it.id == defaultTheme.id) it.isDefault = true } // iOS, Android 3.5.0 버전 대응을 위함
val basicThemes =
BasicThemeType.entries.map {
buildTimetableTheme(
userId,
it,
isDefault = it.displayName == defaultTheme.name,
)
}
return basicThemes + customThemes
}
override suspend fun getBestThemes(page: Int): List<TimetableTheme> =
timetableThemeRepository.findPublishedTimetablesOrderByDownloadsDesc(page)
override suspend fun getFriendsThemes(
userId: String,
page: Int,
): List<TimetableTheme> {
val friendIds = friendService.getMyFriends(userId, state = FriendState.ACTIVE).map { it.second.id!! }
return timetableThemeRepository.findOriginalThemesByUserIds(friendIds, page)
}
override suspend fun addTheme(
userId: String,
name: String,
colors: List<ColorSet>,
): TimetableTheme {
if (colors.size !in 1..MAX_COLOR_COUNT) throw InvalidThemeColorCountException
val theme =
TimetableTheme(
userId = userId,
name = name,
colors = colors,
isCustom = true,
)
return timetableThemeRepository.save(theme)
}
override suspend fun modifyTheme(
userId: String,
themeId: String,
name: String?,
colors: List<ColorSet>?,
): TimetableTheme {
val theme = getCustomTheme(userId, themeId)
name?.let {
theme.name = it
}
colors?.let {
if (it.size !in 1..MAX_COLOR_COUNT) throw InvalidThemeColorCountException
val colorMap = requireNotNull(theme.colors).mapIndexed { i, color -> color to colors.getOrNull(i) }.toMap()
val timetables = timetableRepository.findByUserIdAndThemeId(userId, themeId)
timetables.forEach { timetable ->
timetable.lectures.forEach { lecture ->
if (lecture.color in theme.colors!!) {
colorMap[lecture.color]?.let { newColor -> lecture.color = newColor }
}
}
}
timetableRepository.saveAll(timetables).collect()
theme.colors = it
}
theme.updatedAt = LocalDateTime.now()
return timetableThemeRepository.save(theme)
}
override suspend fun publishTheme(
userId: String,
themeId: String,
publishName: String,
authorAnonymous: Boolean,
) {
val theme = getCustomTheme(userId, themeId)
theme.apply {
status = ThemeStatus.PUBLISHED
publishInfo =
ThemeMarketInfo(
publishName = publishName,
authorAnonymous = authorAnonymous,
downloads = 0,
)
}
timetableThemeRepository.save(theme)
}
override suspend fun downloadTheme(
downloadedUserId: String,
themeId: String,
name: String,
): TimetableTheme {
val theme = timetableThemeRepository.findById(themeId) ?: throw ThemeNotFoundException
if (theme.status != ThemeStatus.PUBLISHED) throw ThemeNotFoundException
if (timetableThemeRepository.existsByOriginIdAndUserId(themeId, downloadedUserId)) throw AlreadyDownloadedThemeException
val downloadedTheme =
theme.copy(
id = null,
name = theme.publishInfo!!.publishName,
userId = downloadedUserId,
origin =
ThemeOrigin(
originId = theme.id!!,
authorId = theme.userId,
),
status = ThemeStatus.DOWNLOADED,
publishInfo = null,
createdAt = LocalDateTime.now(),
updatedAt = LocalDateTime.now(),
)
timetableThemeRepository.addDownloadCount(themeId)
return timetableThemeRepository.save(downloadedTheme)
}
override suspend fun deleteTheme(
userId: String,
themeId: String,
) {
val theme = getCustomTheme(userId, themeId)
val timetables = timetableRepository.findByUserIdAndThemeId(userId, themeId)
timetables.forEach {
it.theme = BasicThemeType.SNUTT
it.themeId = null
}
timetableRepository.saveAll(timetables).collect()
if (theme.status == ThemeStatus.PUBLISHED) throw PublishedThemeDeleteErrorException
timetableThemeRepository.delete(theme)
}
override suspend fun deletePublishedTheme(
userId: String,
themeId: String,
) {
val theme = getCustomTheme(userId, themeId)
if (theme.status == ThemeStatus.PUBLISHED) {
theme.status = ThemeStatus.PRIVATE
} else {
throw NotPublishedThemeException
}
timetableThemeRepository.save(theme)
}
override suspend fun copyTheme(
userId: String,
themeId: String,
): TimetableTheme {
val theme = getCustomTheme(userId, themeId)
val baseName = theme.name.replace(copyNumberRegex, "")
val lastCopiedThemeNumber = getLastCopiedThemeNumber(userId, theme.name)
val newTheme =
TimetableTheme(
userId = userId,
name = "$baseName (${lastCopiedThemeNumber + 1})",
colors = theme.colors,
isCustom = true,
)
return timetableThemeRepository.save(newTheme)
}
private suspend fun getLastCopiedThemeNumber(
userId: String,
name: String,
): Int {
val baseName = name.replace(copyNumberRegex, "")
return timetableThemeRepository
.findLastChild(userId, baseName)
?.name
?.replace(baseName, "")
?.filter { it.isDigit() }
?.toIntOrNull() ?: 0
}
// iOS, Android 3.5.0 버전에서만 사용
override suspend fun setDefault(
userId: String,
themeId: String?,
basicThemeType: BasicThemeType?,
): TimetableTheme {
require((themeId == null) xor (basicThemeType == null))
if (basicThemeType != null) { // 3.5.0 버전에서만 사용하기에 basic 테마의 경우 유저가 직접적으로 default 테마로 지정하는 것 불가하도록 처리
return getDefaultTheme(userId)
}
val theme =
themeId?.let {
timetableThemeRepository.findByIdAndUserId(it, userId) ?: throw ThemeNotFoundException
} ?: return buildTimetableTheme(userId, BasicThemeType.SNUTT, isDefault = true)
theme.isDefault = true
theme.updatedAt = LocalDateTime.now() // updatedAt 을 가장 최신으로 만듦으로써 getDefaultTheme() 의 로직상 default 테마가 되도록 함
return timetableThemeRepository.save(theme)
}
// iOS, Android 3.5.0 버전에서만 사용
override suspend fun unsetDefault(
userId: String,
themeId: String?,
basicThemeType: BasicThemeType?,
): TimetableTheme {
require((themeId == null) xor (basicThemeType == null))
val theme = getDefaultTheme(userId)
themeId?.let {
if (theme.isCustom.not() || theme.id != it) throw NotDefaultThemeErrorException
} ?: run {
if (theme.isCustom || theme.name != basicThemeType!!.displayName) throw NotDefaultThemeErrorException
}
return buildTimetableTheme(userId, BasicThemeType.SNUTT, isDefault = true)
}
override suspend fun getDefaultTheme(userId: String): TimetableTheme {
val customThemes = timetableThemeRepository.findByUserIdAndIsCustomTrueOrderByUpdatedAtDesc(userId)
val defaultTheme = customThemes.firstOrNull() ?: buildTimetableTheme(userId, BasicThemeType.SNUTT, isDefault = true)
return defaultTheme.apply { isDefault = true }
}
override suspend fun getTheme(
userId: String,
themeId: String?,
basicThemeType: BasicThemeType?,
): TimetableTheme {
require((themeId == null) xor (basicThemeType == null))
val defaultTheme = getDefaultTheme(userId)
return themeId?.let {
timetableThemeRepository.findByIdAndUserId(it, userId) ?: throw ThemeNotFoundException
} ?: buildTimetableTheme(
userId,
basicThemeType!!,
isDefault = basicThemeType.displayName == defaultTheme.name,
)
}
override suspend fun searchThemes(keyword: String): List<TimetableTheme> =
timetableThemeRepository.findPublishedTimetablesByPublishNameContaining(keyword)
private suspend fun getCustomTheme(
userId: String,
themeId: String,
): TimetableTheme =
timetableThemeRepository.findByIdAndUserId(themeId, userId)?.also {
if (!it.isCustom) throw InvalidThemeTypeException
} ?: throw ThemeNotFoundException
private fun buildTimetableTheme(
userId: String,
basicThemeType: BasicThemeType,
isDefault: Boolean,
) = TimetableTheme(
userId = userId,
name = basicThemeType.displayName,
colors = null,
isCustom = false,
).also { it.isDefault = isDefault }
override suspend fun getNewColorIndexAndColor(timetable: Timetable): Pair<Int, ColorSet?> =
if (timetable.themeId == null) {
val alreadyUsedIndexes = timetable.lectures.map { it.colorIndex }
val indexToCount = (1..MAX_COLOR_COUNT).associateWith { colorIndex -> alreadyUsedIndexes.count { it == colorIndex } }
val minCount = indexToCount.minOf { it.value }
indexToCount.entries
.filter { (_, count) -> count == minCount }
.map { it.key }
.random() to null
} else {
val theme = getTheme(timetable.userId, timetable.themeId)
val alreadyUsedColors = timetable.lectures.map { requireNotNull(it.color) }
val colorToCount = requireNotNull(theme.colors).associateWith { color -> alreadyUsedColors.count { it == color } }
val minCount = colorToCount.minOf { it.value }
0 to
colorToCount.entries
.filter { (_, count) -> count == minCount }
.map { it.key }
.random()
}
override suspend fun convertThemesToTimetableDtos(themes: List<TimetableTheme>): List<TimetableThemeDto> {
val nicknameMap = userService.getUsers(themes.map { it.userId }).associate { it.id to it.nicknameWithoutTag }
return themes.mapNotNull { TimetableThemeDto(it, nicknameMap[it.userId]) }
}
}
fun TimetableTheme.toBasicThemeType() = if (isCustom) BasicThemeType.SNUTT else requireNotNull(BasicThemeType.from(name))
fun TimetableTheme.toIdForTimetable() = if (isCustom) id else null