Skip to content
Open
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
@@ -0,0 +1,10 @@
package com.weeth.domain.account.application.event

data class DuesObligationCreatedEvent(
val clubId: Long,
val accountId: Long,
val paymentTargetId: Long,
val userId: Long,
val accountName: String,
val amount: Int,
)
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import com.weeth.domain.account.application.dto.request.SaveAccountBasicRequest
import com.weeth.domain.account.application.dto.request.SaveAccountCarryOverRequest
import com.weeth.domain.account.application.dto.request.SavePaymentTargetsRequest
import com.weeth.domain.account.application.dto.response.CreateAccountDraftResponse
import com.weeth.domain.account.application.event.DuesObligationCreatedEvent
import com.weeth.domain.account.application.exception.AccountCarryOverAmountMismatchException
import com.weeth.domain.account.application.exception.AccountExistsException
import com.weeth.domain.account.application.exception.AccountInvalidDraftStateException
Expand Down Expand Up @@ -32,6 +33,7 @@ import com.weeth.domain.club.domain.repository.ClubMemberCardinalReader
import com.weeth.domain.club.domain.repository.ClubReader
import com.weeth.domain.club.domain.service.ClubPermissionPolicy
import com.weeth.domain.user.domain.repository.UserReader
import org.springframework.context.ApplicationEventPublisher
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.time.LocalDateTime
Expand All @@ -46,6 +48,7 @@ class RegisterAccountUseCase(
private val clubMemberCardinalReader: ClubMemberCardinalReader,
private val clubPermissionPolicy: ClubPermissionPolicy,
private val userReader: UserReader,
private val eventPublisher: ApplicationEventPublisher,
) {
@Transactional
fun createDraft(
Expand Down Expand Up @@ -207,6 +210,19 @@ class RegisterAccountUseCase(
settlePreviousAccountBalance(previousAccount, account)

account.markModifiedBy(userId)
paymentTargetRepository.findAllByAccountIdOrderByIdAsc(account.id).forEach { target ->
val amount = target.outstandingObligation() ?: return@forEach
eventPublisher.publishEvent(
DuesObligationCreatedEvent(
clubId,
account.id,
target.id,
target.clubMember.user.id,
checkNotNull(account.name),
amount.value,
),
)
}
}

/** 직전 활성 기수 장부를 잠금 조회한다. 잔액 검증과 마감에 같은 잠금 인스턴스를 재사용한다. */
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.weeth.domain.account.domain.entity

import com.weeth.domain.account.domain.enums.AccountPaymentStatus
import com.weeth.domain.account.domain.enums.AccountStatus
import com.weeth.domain.account.domain.enums.AccountTargetStatus
import com.weeth.domain.account.domain.vo.Money
import com.weeth.domain.club.domain.entity.ClubMember
Expand Down Expand Up @@ -93,6 +94,16 @@ class AccountPaymentTarget(
}
}

fun outstandingObligation(): Money? {
if (account.status != AccountStatus.ACTIVE || targetStatus != AccountTargetStatus.TARGETED ||
paymentStatus != AccountPaymentStatus.UNPAID || dueAmount <= paidAmount ||
!clubMember.isActive() || !clubMember.user.isActive() || clubMember.club.id != account.club.id
) {
return null
}
return Money.of(dueAmount - paidAmount)
}

fun target(dueAmount: Money) {
require(dueAmount.value > 0) { "납부 대상 금액은 0보다 커야 합니다: ${dueAmount.value}" }
targetStatus = AccountTargetStatus.TARGETED
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.weeth.domain.account.domain.repository

import com.weeth.domain.account.domain.entity.AccountPaymentTarget

interface AccountPaymentTargetReader {
fun findByIdWithObligationDetails(id: Long): AccountPaymentTarget?
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,19 @@ import org.springframework.data.jpa.repository.Modifying
import org.springframework.data.jpa.repository.Query
import org.springframework.data.repository.query.Param

interface AccountPaymentTargetRepository : JpaRepository<AccountPaymentTarget, Long> {
interface AccountPaymentTargetRepository :
JpaRepository<AccountPaymentTarget, Long>,
AccountPaymentTargetReader {
@Query(
"""SELECT t FROM AccountPaymentTarget t
JOIN FETCH t.account a JOIN FETCH a.club
JOIN FETCH t.clubMember cm JOIN FETCH cm.club JOIN FETCH cm.user
WHERE t.id = :id""",
)
override fun findByIdWithObligationDetails(
@Param("id") id: Long,
): AccountPaymentTarget?

fun findAllByAccountId(accountId: Long): List<AccountPaymentTarget>

fun findByAccountIdAndClubMemberId(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@ import com.weeth.domain.club.domain.entity.ClubMemberCardinal
import com.weeth.domain.club.domain.enums.MemberStatus

interface ClubMemberCardinalReader {
fun findCardinalNumbersByClubIdAndUserId(
clubId: Long,
userId: Long,
): List<Int>

fun findAllByClubMember(clubMember: ClubMember): List<ClubMemberCardinal>

fun findAllByClubMembers(clubMembers: List<ClubMember>): List<ClubMemberCardinal>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,16 @@ import org.springframework.data.repository.query.Param
interface ClubMemberCardinalRepository :
JpaRepository<ClubMemberCardinal, Long>,
ClubMemberCardinalReader {
@Query(
"""SELECT cmc.cardinal.cardinalNumber FROM ClubMemberCardinal cmc
WHERE cmc.clubMember.club.id = :clubId AND cmc.clubMember.user.id = :userId
AND cmc.clubMember.memberStatus = com.weeth.domain.club.domain.enums.MemberStatus.ACTIVE""",
)
override fun findCardinalNumbersByClubIdAndUserId(
@Param("clubId") clubId: Long,
@Param("userId") userId: Long,
): List<Int>

override fun findAllByClubMember(clubMember: ClubMember): List<ClubMemberCardinal>

fun existsByClubMember(clubMember: ClubMember): Boolean
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
import org.springframework.stereotype.Component
import java.time.Clock
import java.util.concurrent.Callable
import java.util.concurrent.ExecutorService
import java.util.concurrent.ScheduledExecutorService
Expand All @@ -32,6 +33,7 @@ class NotificationDeliveryProcessor(
@Value("\${notification.dispatch.send-timeout-millis:20000}") private val timeoutMillis: Long = 20000,
@Value("\${notification.dispatch.visibility-seconds:60}") private val visibilitySeconds: Int = 60,
@Value("\${notification.dispatch.heartbeat-millis:10000}") private val heartbeatMillis: Long = 10000,
private val clock: Clock = Clock.systemUTC(),
) {
private val log = LoggerFactory.getLogger(javaClass)

Expand Down Expand Up @@ -85,7 +87,15 @@ class NotificationDeliveryProcessor(
): PushNotificationResult {
val future =
try {
io.submit(Callable { sender.sendMulticast(attempt.command) })
io.submit(
Callable {
if (attempt.expiresAt?.isAfter(clock.instant()) == false) {
retryable(attempt, "REMINDER_EXPIRED")
} else {
sender.sendMulticast(attempt.command)
}
},
)
} catch (
_: Exception,
) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package com.weeth.domain.notification.application.dispatch

import com.weeth.domain.notification.application.usecase.command.GenerateSessionDayReminderUseCase
import com.weeth.domain.notification.domain.service.SessionDayReminderPolicy
import com.weeth.domain.session.domain.repository.SessionReader
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
import org.springframework.data.domain.PageRequest
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Component
import java.time.Clock
import java.time.LocalDateTime
import java.time.LocalTime
import java.time.ZoneId

@Component
@ConditionalOnProperty(prefix = "notification.dispatch", name = ["enabled"], havingValue = "true")
class SessionDayReminderScheduler(
private val generator: GenerateSessionDayReminderUseCase,
private val sessions: SessionReader,
private val policy: SessionDayReminderPolicy,
private val clock: Clock,
@Value("\${notification.day-reminder.enabled:false}") private val enabled: Boolean = false,
) {
private val log = LoggerFactory.getLogger(javaClass)

@Scheduled(cron = "0 * * * * *", zone = "Asia/Seoul", scheduler = "notificationMaintenanceScheduler")
fun runOnce() {
if (!enabled) return
var afterClubId = 0L
while (true) {
val now = LocalDateTime.ofInstant(clock.instant(), ZoneId.of("Asia/Seoul"))
if (!policy.isWindow(now)) return
val date = now.toLocalDate()
val clubIds =
sessions.findDayReminderClubIds(
date.atStartOfDay(),
date.plusDays(1).atStartOfDay(),
now,
date.atTime(LocalTime.NOON),
afterClubId,
PageRequest.of(0, 100),
)
if (clubIds.isEmpty()) return
clubIds.forEach { clubId ->
try {
val claim = generator.claim(clubId) ?: return@forEach
try {
generator.generate(claim)
} catch (exception: Exception) {
log.warn("정오 안내 생성 실패. clubId={}, exceptionType={}", clubId, exception.javaClass.simpleName)
generator.expire(claim)
}
} catch (_: Exception) {
log.warn("정오 안내 선점·복구 실패. clubId={}", clubId)
}
}
afterClubId = clubIds.last()
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import java.time.LocalDateTime
data class NotificationResponse(
@field:Schema(description = "알림 ID", example = "1")
val id: Long,
@field:Schema(description = "알림 유형", example = "NOTICE_CREATED")
@field:Schema(description = "알림 유형 (공지·일정·세션·회비 납부 의무 안내)", example = "NOTICE_CREATED")
val type: NotificationType,
@field:Schema(description = "알림 제목", example = "새 공지가 등록되었습니다")
val title: String,
Expand All @@ -18,7 +18,7 @@ data class NotificationResponse(
val targetPath: String,
@field:Schema(description = "동아리 ID", example = "1A2b3C")
val clubId: String,
@field:Schema(description = "알림 참조 유형", example = "POST")
@field:Schema(description = "알림 참조 유형 (POST·EVENT·SESSION·ACCOUNT_PAYMENT_TARGET 등)", example = "POST")
val referenceType: NotificationReferenceType,
@field:Schema(description = "알림 참조 ID", example = "100")
val referenceId: Long,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package com.weeth.domain.notification.application.event

import com.weeth.domain.account.application.event.DuesObligationCreatedEvent
import com.weeth.domain.notification.application.usecase.command.CreateNotificationUseCase
import com.weeth.domain.notification.domain.enums.NotificationReferenceType
import com.weeth.domain.notification.domain.enums.NotificationType
import com.weeth.domain.notification.domain.vo.NotificationRequest
import com.weeth.global.common.id.TsidBase62Encoder
import org.springframework.stereotype.Component
import org.springframework.transaction.event.TransactionPhase
import org.springframework.transaction.event.TransactionalEventListener
import java.text.NumberFormat
import java.util.Locale

@Component
class CreateDuesNotificationEventListener(
private val createNotificationUseCase: CreateNotificationUseCase,
) {
@TransactionalEventListener(phase = TransactionPhase.BEFORE_COMMIT)
fun handle(event: DuesObligationCreatedEvent) {
val clubId = TsidBase62Encoder.encode(event.clubId)
val targetPath = "/clubs/$clubId/accounts"
createNotificationUseCase.execute(
NotificationRequest(
eventId = "DUES_OBLIGATION_CREATED:${event.accountId}:${event.paymentTargetId}",
type = NotificationType.DUES_OBLIGATION_CREATED,
variables =
mapOf(
"accountName" to event.accountName,
"dueAmount" to NumberFormat.getIntegerInstance(Locale.KOREA).format(event.amount),
),
targetPath = targetPath,
clubId = event.clubId,
referenceType = NotificationReferenceType.ACCOUNT_PAYMENT_TARGET,
referenceId = event.paymentTargetId,
data =
mapOf(
"type" to NotificationType.DUES_OBLIGATION_CREATED.name,
"referenceType" to NotificationReferenceType.ACCOUNT_PAYMENT_TARGET.name,
"referenceId" to event.paymentTargetId.toString(),
"accountId" to event.accountId.toString(),
"clubId" to clubId,
"targetPath" to targetPath,
),
),
listOf(event.userId),
)
}
}
Loading
Loading