Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: 회원가입시 3개 받도록 수정 #558

Merged
merged 2 commits into from
Nov 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.nexters.bottles.api.auth.component

import com.nexters.bottles.api.auth.component.event.DeleteUserEventDto
import com.nexters.bottles.app.auth.event.DeleteUserEventDto
import com.nexters.bottles.app.auth.service.BlackListService
import com.nexters.bottles.app.auth.service.RefreshTokenService
import com.nexters.bottles.app.bottle.service.BottleCachingService
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import com.nexters.bottles.api.auth.component.ApplePublicKeyGenerator
import com.nexters.bottles.api.auth.component.AuthCodeGenerator
import com.nexters.bottles.api.auth.component.JwtTokenProvider
import com.nexters.bottles.api.auth.component.NaverSmsEncoder
import com.nexters.bottles.api.auth.component.event.DeleteUserEventDto
import com.nexters.bottles.api.auth.event.dto.SignUpEventDto
import com.nexters.bottles.app.auth.event.DeleteUserEventDto
import com.nexters.bottles.app.auth.event.SignUpEventDto
import com.nexters.bottles.api.auth.facade.dto.AppleRevokeResponse
import com.nexters.bottles.api.auth.facade.dto.AppleSignInUpRequest
import com.nexters.bottles.api.auth.facade.dto.AppleSignInUpResponse
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ class BottleFacade(
if (isActiveMatching) {
val matchingHour = BOTTLE_PUSH_TIME.hour
bottleService.matchRandomBottle(user.id, matchingHour, blockUserIds, blockedMeUserIds)
?.also {
.forEach {
applicationEventPublisher.publishEvent(
BottleMatchEventDto(
bottleId = it.id,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ class BottleFacadeV2(
).map { it.userId }.toSet() // 나를 차단한 유저

bottleService.matchRandomBottle(user.id, BOTTLE_PUSH_TIME.hour, blockUserIds, blockedMeUserIds)
?.also {
.forEach {
applicationEventPublisher.publishEvent(
BottleMatchEventDto(
bottleId = it.id,
Expand Down Expand Up @@ -78,7 +78,7 @@ class BottleFacadeV2(
).map { it.userId }.toSet() // 나를 차단한 유저

bottleService.matchAdditionalRandomBottle(user.id, BOTTLE_PUSH_TIME.hour, blockUserIds, blockedMeUserIds)
?.also {
.forEach {
applicationEventPublisher.publishEvent(
BottleMatchEventDto(
bottleId = it.id,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package com.nexters.bottles.api.auth.event
package com.nexters.bottles.app.auth.event

import com.nexters.bottles.api.auth.event.dto.SignUpEventDto
import com.nexters.bottles.app.notification.component.FcmClient
import com.nexters.bottles.app.notification.component.dto.FcmNotification
import com.nexters.bottles.app.notification.service.FcmTokenService
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.nexters.bottles.api.auth.component.event
package com.nexters.bottles.app.auth.event

data class DeleteUserEventDto(
val userId: Long,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.nexters.bottles.api.auth.event.dto
package com.nexters.bottles.app.auth.event

class SignUpEventDto(
val userName: String? = null,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,36 @@ class BottleMatchingRepository(
)
}

fun findAllUserCanBeMatchedWithoutIntroduction(userId: Long, gender: Gender): List<UsersCanBeMatchedDto> {
val sql = """
SELECT u.id AS willMatchUserId, u.gender AS willMatchUserGender, u.city AS city
FROM user u
LEFT JOIN bottle_history bh ON bh.user_id = :userId AND bh.matched_user_id = u.id
WHERE bh.id IS NULL
AND u.id != :userId
AND u.gender != :gender
AND u.deleted = false
AND u.is_match_activated = true;
""".trimIndent()

val namedParameters = mapOf(
"userId" to userId,
"gender" to gender.name
)

return namedParameterJdbcTemplate.query(
sql,
namedParameters,
{ rs, _ ->
UsersCanBeMatchedDto(
willMatchUserId = rs.getLong("willMatchUserId"),
willMatchUserGender = rs.getString("willMatchUserGender"),
willMatchCity = rs.getString("city")
)
}
)
}

fun findAdditionalAllUserCanBeMatched(userId: Long, gender: Gender): List<UsersCanBeMatchedDto> {
val sql = """
SELECT u.id AS willMatchUserId, u.gender AS willMatchUserGender, u.city AS city
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -167,45 +167,47 @@ class BottleService(
userId: Long,
matchingHour: Int,
blockUserIds: Set<Long>,
blockedMeUserIds: Set<Long>
): Bottle? {
blockedMeUserIds: Set<Long>,
count: Int = 1,
): List<Bottle> {
val user = userRepository.findByIdOrNull(userId) ?: throw IllegalStateException("회원가입 상태를 문의해주세요")

if (user.isNotRegisterProfile()) return null
if (user.isMatchInactive()) return null
if (user.isNotRegisterProfile()) return emptyList()
if (user.isMatchInactive()) return emptyList()

val matchingTime = getMatchingTime(matchingHour)
if (user.lastRandomMatchedAt > matchingTime) return null
if (user.lastRandomMatchedAt > matchingTime) return emptyList()

val usersCanBeMatched = bottleMatchingRepository.findAllUserCanBeMatched(user.id, user.gender!!)
.filter { it.willMatchUserId !in blockUserIds }
.filter { it.willMatchUserId !in blockedMeUserIds }

if (usersCanBeMatched.isEmpty()) return null
if (usersCanBeMatched.isEmpty()) return emptyList()

val matchingUserDto = findUserSameRegionOrRandom(usersCanBeMatched, user)
val matchingUser = userRepository.findByIdAndDeletedFalse(matchingUserDto.willMatchUserId)
?: throw IllegalArgumentException("탈퇴한 회원입니다")
val matchingUserDtos = findUserSameRegionOrRandom(usersCanBeMatched, user, count)
val matchingUsers = userRepository.findByIdInAndDeletedFalse(matchingUserDtos.map { it.willMatchUserId })

val bottle = Bottle(targetUser = user, sourceUser = matchingUser, expiredAt = matchingTime.plusDays(1))
val savedBottle = bottleRepository.save(bottle)
val now = LocalDateTime.now()
var bottles = matchingUsers.map { matchingUser -> Bottle(targetUser = user, sourceUser = matchingUser, expiredAt = now.plusDays(1)) }
val savedBottles = bottleRepository.saveAll(bottles)

user.updateLastRandomMatchedAt(LocalDateTime.now())

return savedBottle
return savedBottles
}

@Transactional
fun matchAdditionalRandomBottle(
userId: Long,
matchingHour: Int,
blockUserIds: Set<Long>,
blockedMeUserIds: Set<Long>
): Bottle? {
blockedMeUserIds: Set<Long>,
count: Int = 1,
): List<Bottle> {
val user = userRepository.findByIdOrNull(userId) ?: throw IllegalStateException("회원가입 상태를 문의해주세요")

if (user.isNotRegisterProfile()) return null
if (user.isMatchInactive()) return null
if (user.isNotRegisterProfile()) return emptyList()
if (user.isMatchInactive()) return emptyList()

var usersCanBeMatched = bottleMatchingRepository.findAllUserCanBeMatched(user.id, user.gender!!)
.filter { it.willMatchUserId !in blockUserIds }
Expand All @@ -218,18 +220,18 @@ class BottleService(
.filter { it.willMatchUserId !in blockedMeUserIds }
}

if (usersCanBeMatched.isEmpty()) return null
if (usersCanBeMatched.isEmpty()) return emptyList()

val matchingUserDto = findUserSameRegionOrRandom(usersCanBeMatched, user)
val matchingUser = userRepository.findByIdAndDeletedFalse(matchingUserDto.willMatchUserId)
?: throw IllegalArgumentException("탈퇴한 회원입니다")
val matchingUserDtos = findUserSameRegionOrRandom(usersCanBeMatched, user, count)
val matchingUsers = userRepository.findByIdInAndDeletedFalse(matchingUserDtos.map { it.willMatchUserId })

val bottle = Bottle(targetUser = user, sourceUser = matchingUser, expiredAt = LocalDateTime.now().plusDays(1))
val savedBottle = bottleRepository.save(bottle)
val now = LocalDateTime.now()
var bottles = matchingUsers.map { matchingUser -> Bottle(targetUser = user, sourceUser = matchingUser, expiredAt = now.plusDays(1)) }
val savedBottles = bottleRepository.saveAll(bottles)

user.updateLastRandomMatchedAt(LocalDateTime.now())

return savedBottle
return savedBottles
}

private fun getMatchingTime(matchingHour: Int): LocalDateTime {
Expand All @@ -243,13 +245,25 @@ class BottleService(

private fun findUserSameRegionOrRandom(
usersCanBeMatchedDtos: List<UsersCanBeMatchedDto>,
targetUser: User
): UsersCanBeMatchedDto {
return usersCanBeMatchedDtos.shuffled()
.firstOrNull {
targetUser: User,
count: Int,
): List<UsersCanBeMatchedDto> {
val canBeMatchedDtos = usersCanBeMatchedDtos.shuffled()
.filter {
targetUser.gender?.name != it.willMatchUserGender
targetUser.city == it.willMatchCity
} ?: usersCanBeMatchedDtos[0]
}


// 필터링된 사용자가 count에 도달하지 못하면 추가로 사용자 채우기
return if (canBeMatchedDtos.size < count) {
val additionalDtos = usersCanBeMatchedDtos.shuffled()
.filter { it !in canBeMatchedDtos } // 이미 선택된 항목을 제외
.take(count - canBeMatchedDtos.size) // 모자란 개수만큼 추가
canBeMatchedDtos + additionalDtos // 기존 결과에 추가 결과를 합쳐서 반환
} else {
canBeMatchedDtos
}
}

@Transactional(readOnly = true)
Expand Down Expand Up @@ -285,23 +299,22 @@ class BottleService(
}

@Transactional
fun matchFirstRandomBottle(userId: Long): Bottle? {
fun matchFirstRandomBottle(userId: Long, count: Int): List<Bottle> {
val user = userRepository.findByIdOrNull(userId) ?: throw IllegalStateException("회원가입 상태를 문의해주세요")

val usersCanBeMatched = bottleMatchingRepository.findAllUserCanBeMatched(user.id, user.gender!!)
if (usersCanBeMatched.isEmpty()) return null
val usersCanBeMatched = bottleMatchingRepository.findAllUserCanBeMatchedWithoutIntroduction(user.id, user.gender!!).take(count)
if (usersCanBeMatched.isEmpty()) return emptyList()

val matchingUserDto = findUserSameRegionOrRandom(usersCanBeMatched, user)
val matchingUser = userRepository.findByIdAndDeletedFalse(matchingUserDto.willMatchUserId)
?: throw IllegalArgumentException("탈퇴한 회원입니다")
val matchingUserDtos = findUserSameRegionOrRandom(usersCanBeMatched, user, count)
val matchingUsers = userRepository.findByIdInAndDeletedFalse(matchingUserDtos.map { it.willMatchUserId })

val now = LocalDateTime.now()
val bottle = Bottle(targetUser = user, sourceUser = matchingUser, expiredAt = now.plusDays(1))
val savedBottle = bottleRepository.save(bottle)
var bottles = matchingUsers.map { matchingUser -> Bottle(targetUser = user, sourceUser = matchingUser, expiredAt = now.plusDays(1)) }
val savedBottles = bottleRepository.saveAll(bottles)

user.updateLastRandomMatchedAt(now)

return savedBottle
return savedBottles
}

// TODO 클라이언트에서 문답 읽음 표시를 v2로 옮긴 후 변경 -> Letter의 isReadByOtherUser 제거 (이후 읽음 표시는 BottleReadHistory 한곳에서만 관리하도록 함)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
package com.nexters.bottles.app.user.component.event

import com.nexters.bottles.app.auth.event.SignUpEventDto
import com.nexters.bottles.app.bottle.service.BottleHistoryService
import com.nexters.bottles.app.bottle.service.BottleService
import com.nexters.bottles.app.common.component.FileService
import com.nexters.bottles.app.user.component.event.dto.IntroductionSaveEventDto
import com.nexters.bottles.app.user.component.event.dto.UploadImageEventDto
import com.nexters.bottles.app.user.service.UserService
import org.springframework.scheduling.annotation.Async
Expand All @@ -20,8 +20,9 @@ class UserProfileApplicationEventListener(

@Async
@TransactionalEventListener
fun handleCustomEvent(event: IntroductionSaveEventDto) {
bottleService.matchFirstRandomBottle(event.userId)?.let {
fun handleCustomEvent(event: SignUpEventDto) {
var savedBottles = bottleService.matchFirstRandomBottle(event.userId, 3)
savedBottles.forEach {
bottleHistoryService.saveMatchingHistory(sourceUserId = it.sourceUser.id, targetUserId = it.targetUser.id)
}
}
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ interface UserRepository : JpaRepository<User, Long> {

fun findByIdAndDeletedFalse(id: Long): User?

fun findByIdInAndDeletedFalse(id: List<Long>): List<User>

fun findAllByDeletedFalseAndIsMatchActivatedTrue(): List<User>

fun findByPhoneNumber(phoneNumber: String?): User?
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package com.nexters.bottles.app.user.service

import com.nexters.bottles.app.user.component.event.dto.IntroductionSaveEventDto
import com.nexters.bottles.app.user.component.event.dto.UploadImageEventDto
import com.nexters.bottles.app.user.domain.QuestionAndAnswer
import com.nexters.bottles.app.user.domain.User
Expand Down Expand Up @@ -43,15 +42,7 @@ class UserProfileService(
fun saveIntroduction(userId: Long, introduction: List<QuestionAndAnswer>, firstMatchingCount: Int) {
val user = userRepository.findByIdOrNull(userId) ?: throw IllegalStateException("회원가입 상태를 문의해주세요")
profileRepository.findByUserId(user.id)?.let {
val isFirstRegisterIntroduction = it.introduction.isEmpty()
it.introduction = introduction
if (isFirstRegisterIntroduction) {
repeat(firstMatchingCount) {
applicationEventPublisher.publishEvent(
IntroductionSaveEventDto(userId = userId)
)
}
}
} ?: run {
profileRepository.save(
UserProfile(
Expand Down
Loading