feat(admin-calculate): 채널 후원 조회에 국가별 정산을 적용한다

This commit is contained in:
2026-11-20 17:48:03 +09:00
parent a5ea270a2d
commit 6734e71bf6
6 changed files with 320 additions and 21 deletions
@@ -9,12 +9,14 @@ import kr.co.vividnext.sodalive.can.use.QUseCan.useCan
import kr.co.vividnext.sodalive.can.use.QUseCanCalculate.useCanCalculate
import kr.co.vividnext.sodalive.can.use.UseCanCalculateStatus
import kr.co.vividnext.sodalive.member.QMember.member
import kr.co.vividnext.sodalive.v2.settlement.adapter.out.persistence.CountrySettlementExpressions
import org.springframework.stereotype.Repository
import java.time.LocalDateTime
@Repository
class AdminChannelDonationCalculateQueryRepository(
private val queryFactory: JPAQueryFactory
private val queryFactory: JPAQueryFactory,
private val countrySettlementExpressions: CountrySettlementExpressions
) {
fun getChannelDonationByDateTotal(
startDate: LocalDateTime,
@@ -38,7 +40,14 @@ class AdminChannelDonationCalculateQueryRepository(
.select(
QGetAdminChannelDonationSettlementTotalQueryData(
useCan.id.countDistinct(),
useCanCalculate.can.sum()
useCanCalculate.can.sum(),
countrySettlementExpressions.newPolicyCan(useCan.createdAt, useCanCalculate.can),
countrySettlementExpressions.newPolicyWeightedRatioCan(
useCan.createdAt,
useCanCalculate.can,
member.countryCode,
useCan.countryCode
)
)
)
.from(useCanCalculate)
@@ -100,7 +109,14 @@ class AdminChannelDonationCalculateQueryRepository(
formattedDate,
member.nickname,
useCan.id.countDistinct(),
useCanCalculate.can.sum()
useCanCalculate.can.sum(),
countrySettlementExpressions.newPolicyCan(useCan.createdAt, useCanCalculate.can),
countrySettlementExpressions.newPolicyWeightedRatioCan(
useCan.createdAt,
useCanCalculate.can,
member.countryCode,
useCan.countryCode
)
)
)
.from(useCanCalculate)
@@ -126,7 +142,14 @@ class AdminChannelDonationCalculateQueryRepository(
QGetAdminChannelDonationSettlementByCreatorQueryData(
member.nickname,
useCan.id.countDistinct(),
useCanCalculate.can.sum()
useCanCalculate.can.sum(),
countrySettlementExpressions.newPolicyCan(useCan.createdAt, useCanCalculate.can),
countrySettlementExpressions.newPolicyWeightedRatioCan(
useCan.createdAt,
useCanCalculate.can,
member.countryCode,
useCan.countryCode
)
)
)
.from(useCanCalculate)
@@ -150,7 +173,14 @@ class AdminChannelDonationCalculateQueryRepository(
QGetAdminChannelDonationSettlementByCreatorQueryData(
member.nickname,
useCan.id.countDistinct(),
useCanCalculate.can.sum()
useCanCalculate.can.sum(),
countrySettlementExpressions.newPolicyCan(useCan.createdAt, useCanCalculate.can),
countrySettlementExpressions.newPolicyWeightedRatioCan(
useCan.createdAt,
useCanCalculate.can,
member.countryCode,
useCan.countryCode
)
)
)
.from(useCanCalculate)
@@ -174,15 +204,8 @@ class AdminChannelDonationCalculateQueryRepository(
private fun getFormattedDate(dateTimePath: DateTimePath<LocalDateTime>): StringTemplate {
return Expressions.stringTemplate(
"DATE_FORMAT({0}, {1})",
Expressions.dateTimeTemplate(
LocalDateTime::class.java,
"CONVERT_TZ({0},{1},{2})",
dateTimePath,
"UTC",
"Asia/Seoul"
),
"%Y-%m-%d"
"DATE_FORMAT(CONVERT_TZ({0}, 'UTC', 'Asia/Seoul'), '%Y-%m-%d')",
dateTimePath
)
}
}
@@ -6,10 +6,15 @@ import kr.co.vividnext.sodalive.calculate.channelDonation.ChannelDonationSettlem
data class GetAdminChannelDonationSettlementByCreatorQueryData @QueryProjection constructor(
val creator: String,
val count: Long,
val totalCan: Int?
val totalCan: Int?,
val newPolicyCan: Int = 0,
val newPolicyWeightedRatioCan: Long = 0
) {
@QueryProjection
constructor(creator: String, count: Long, totalCan: Int?) : this(creator, count, totalCan, 0, 0)
fun toResponseItem(): GetAdminChannelDonationSettlementByCreatorItem {
val settlement = ChannelDonationSettlementCalculator.calculate(totalCan ?: 0)
val settlement = ChannelDonationSettlementCalculator.calculate(totalCan ?: 0, newPolicyCan, newPolicyWeightedRatioCan)
return GetAdminChannelDonationSettlementByCreatorItem(
creator = creator,
@@ -7,10 +7,15 @@ data class GetAdminChannelDonationSettlementQueryData @QueryProjection construct
val date: String,
val creator: String,
val count: Long,
val totalCan: Int?
val totalCan: Int?,
val newPolicyCan: Int = 0,
val newPolicyWeightedRatioCan: Long = 0
) {
@QueryProjection
constructor(date: String, creator: String, count: Long, totalCan: Int?) : this(date, creator, count, totalCan, 0, 0)
fun toResponseItem(): GetAdminChannelDonationSettlementItem {
val settlement = ChannelDonationSettlementCalculator.calculate(totalCan ?: 0)
val settlement = ChannelDonationSettlementCalculator.calculate(totalCan ?: 0, newPolicyCan, newPolicyWeightedRatioCan)
return GetAdminChannelDonationSettlementItem(
date = date,
@@ -5,11 +5,16 @@ import kr.co.vividnext.sodalive.calculate.channelDonation.ChannelDonationSettlem
data class GetAdminChannelDonationSettlementTotalQueryData @QueryProjection constructor(
val count: Long?,
val totalCan: Int?
val totalCan: Int?,
val newPolicyCan: Int = 0,
val newPolicyWeightedRatioCan: Long = 0
) {
@QueryProjection
constructor(count: Long?, totalCan: Int?) : this(count, totalCan, 0, 0)
fun toResponseTotal(): GetAdminChannelDonationSettlementTotal {
val totalCan = totalCan ?: 0
val settlement = ChannelDonationSettlementCalculator.calculate(totalCan)
val settlement = ChannelDonationSettlementCalculator.calculate(totalCan, newPolicyCan, newPolicyWeightedRatioCan)
return GetAdminChannelDonationSettlementTotal(
count = (count ?: 0L).toInt(),
@@ -12,6 +12,8 @@ import kr.co.vividnext.sodalive.configs.QueryDslConfig
import kr.co.vividnext.sodalive.member.Member
import kr.co.vividnext.sodalive.member.MemberRepository
import kr.co.vividnext.sodalive.member.MemberRole
import kr.co.vividnext.sodalive.v2.settlement.adapter.out.persistence.CountrySettlementExpressions
import kr.co.vividnext.sodalive.v2.settlement.domain.CountrySettlementPolicy
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.DisplayName
@@ -36,7 +38,10 @@ class AdminChannelDonationCalculateQueryRepositoryTest @Autowired constructor(
@BeforeEach
fun setup() {
registerMysqlDateFunctions()
repository = AdminChannelDonationCalculateQueryRepository(queryFactory)
repository = AdminChannelDonationCalculateQueryRepository(
queryFactory,
CountrySettlementExpressions(CountrySettlementPolicy())
)
}
@Test
@@ -0,0 +1,256 @@
package kr.co.vividnext.sodalive.admin.calculate.channelDonation
import com.querydsl.jpa.impl.JPAQueryFactory
import kr.co.vividnext.sodalive.can.payment.PaymentGateway
import kr.co.vividnext.sodalive.can.use.CanUsage
import kr.co.vividnext.sodalive.can.use.UseCan
import kr.co.vividnext.sodalive.can.use.UseCanCalculate
import kr.co.vividnext.sodalive.can.use.UseCanCalculateStatus
import kr.co.vividnext.sodalive.configs.QueryDslConfig
import kr.co.vividnext.sodalive.member.Member
import kr.co.vividnext.sodalive.member.MemberRole
import kr.co.vividnext.sodalive.v2.settlement.adapter.out.persistence.CountrySettlementExpressions
import kr.co.vividnext.sodalive.v2.settlement.domain.CountrySettlementPolicy
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.MethodSource
import org.junit.jupiter.params.provider.ValueSource
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest
import org.springframework.context.annotation.Import
import java.time.LocalDateTime
import javax.persistence.EntityManager
@DataJpaTest(
properties = [
"spring.cache.type=none",
"spring.jpa.database-platform=kr.co.vividnext.sodalive.support.H2MySqlFunctionDialect"
]
)
@Import(QueryDslConfig::class)
class AdminChannelDonationCountryPolicyRepositoryTest @Autowired constructor(
private val queryFactory: JPAQueryFactory,
private val entityManager: EntityManager
) {
private lateinit var repository: AdminChannelDonationCalculateQueryRepository
private lateinit var sender: Member
private val boundary = LocalDateTime.of(2026, 10, 31, 15, 0)
private val start = boundary.minusSeconds(1)
private val end = boundary.plusDays(1)
@BeforeEach
fun setup() {
entityManager.createNativeQuery(
"CREATE ALIAS IF NOT EXISTS DATE_FORMAT FOR 'kr.co.vividnext.sodalive.support.H2MysqlDateFunctions.dateFormat'"
).executeUpdate()
entityManager.createNativeQuery(
"CREATE ALIAS IF NOT EXISTS CONVERT_TZ FOR 'kr.co.vividnext.sodalive.support.H2MysqlDateFunctions.convertTz'"
).executeUpdate()
repository = AdminChannelDonationCalculateQueryRepository(
queryFactory,
CountrySettlementExpressions(CountrySettlementPolicy())
)
sender = saveMember("sender", "US", MemberRole.USER)
}
@ParameterizedTest
@MethodSource("policyCases")
@DisplayName("관리자 기존 조회는 사용 시각과 수신자의 현재 국가 및 저장된 거래 국가로 후원 금액을 계산한다")
fun shouldApplyCountryPolicyThroughCurrentAdminQueries(case: PolicyCase) {
val creator = saveMember("creator", "US")
val usage = saveUsage(UseCan(CanUsage.CHANNEL_DONATION, 100, 0, countryCode = case.transactionCountry), case.at)
saveCalculation(creator, usage)
creator.countryCode = case.creatorCountry
entityManager.flush()
entityManager.clear()
val dateTotal = repository.getChannelDonationByDateTotal(start, end).toResponseTotal()
val creatorTotal = repository.getChannelDonationByCreatorTotal(start, end).toResponseTotal()
val daily = repository.getChannelDonationByDate(start, end, 0, 20).single().toResponseItem()
val byCreator = repository.getChannelDonationByCreator(start, end, 0, 20).single().toResponseItem()
val excel = repository.getChannelDonationByCreatorForExcel(start, end).single().toResponseItem()
assertEquals(case.expected, dateTotal)
assertEquals(case.expected, creatorTotal)
assertEquals(case.expected.settlementAmount, daily.settlementAmount)
assertEquals(case.expected.settlementAmount, byCreator.settlementAmount)
assertEquals(case.expected.settlementAmount, excel.settlementAmount)
assertEquals("creator", daily.creator)
assertEquals(1, daily.count)
assertEquals(100, daily.totalCan)
}
@Test
@DisplayName("정책 전후 한 캔씩은 크리에이터와 전체 집계를 유지하고 일별 금액의 합으로 대체하지 않는다")
fun shouldKeepMixedPolicyCreatorAndWholePeriodRoundingGrain() {
val creator = saveMember("creator", "KR")
saveCalculation(creator, saveUsage(UseCan(CanUsage.CHANNEL_DONATION, 1, 0, countryCode = "KR"), start))
saveCalculation(creator, saveUsage(UseCan(CanUsage.CHANNEL_DONATION, 1, 0, countryCode = "KR"), boundary))
entityManager.flush()
entityManager.clear()
val expectedTotal = GetAdminChannelDonationSettlementTotal(2, 2, 200, 13, 150, 5, 145)
val expectedCreator = GetAdminChannelDonationSettlementByCreatorItem("creator", 2, 2, 200, 13, 150, 5, 145)
assertEquals(expectedTotal, repository.getChannelDonationByDateTotal(start, end).toResponseTotal())
assertEquals(expectedTotal, repository.getChannelDonationByCreatorTotal(start, end).toResponseTotal())
assertEquals(
listOf(expectedCreator),
repository.getChannelDonationByCreator(start, end, 0, 1).map { it.toResponseItem() }
)
assertEquals(
listOf(expectedCreator),
repository.getChannelDonationByCreatorForExcel(start, end).map { it.toResponseItem() }
)
assertEquals(1, repository.getChannelDonationByCreatorTotalCount(start, end))
assertEquals(2, repository.getChannelDonationByDateTotalCount(start, end))
assertEquals(
listOf(GetAdminChannelDonationSettlementItem("2026-11-01", "creator", 1, 1, 100, 7, 70, 2, 68)),
repository.getChannelDonationByDate(start, end, 0, 1).map { it.toResponseItem() }
)
assertEquals(
listOf(GetAdminChannelDonationSettlementItem("2026-10-31", "creator", 1, 1, 100, 7, 79, 3, 76)),
repository.getChannelDonationByDate(start, end, 1, 1).map { it.toResponseItem() }
)
assertEquals(
emptyList<GetAdminChannelDonationSettlementQueryData>(),
repository.getChannelDonationByDate(start, end, 2, 1)
)
}
@Test
@DisplayName("여러 국가와 PG 분할 및 수신자가 섞여도 관리자 행과 페이지 및 후원 건수는 늘어나지 않는다")
fun shouldKeepRecipientAllocationsAndDistinctCountsWithoutCountryRows() {
val korean = saveMember("korean", "KR")
val japanese = saveMember("japanese", "JP")
val shared = saveUsage(UseCan(CanUsage.CHANNEL_DONATION, 5, 0, countryCode = "KR"), boundary)
saveCalculation(korean, shared, UseCanCalculate(1, PaymentGateway.PG, UseCanCalculateStatus.RECEIVED))
saveCalculation(korean, shared, UseCanCalculate(1, PaymentGateway.GOOGLE_IAP, UseCanCalculateStatus.RECEIVED))
saveCalculation(japanese, shared, UseCanCalculate(3, PaymentGateway.APPLE_IAP, UseCanCalculateStatus.RECEIVED))
val foreign = saveUsage(UseCan(CanUsage.CHANNEL_DONATION, 1, 0, countryCode = "JP"), boundary.plusSeconds(1))
saveCalculation(korean, foreign)
saveCalculation(korean, foreign, UseCanCalculate(40, PaymentGateway.PG, UseCanCalculateStatus.REFUND))
saveCalculation(korean, foreign, UseCanCalculate(40, PaymentGateway.PG, UseCanCalculateStatus.CALCULATE_COMPLETE))
entityManager.persist(
UseCanCalculate(40, PaymentGateway.PG, UseCanCalculateStatus.RECEIVED).apply { useCan = foreign }
)
saveCalculation(korean, saveUsage(UseCan(CanUsage.CHANNEL_DONATION, 40, 0, isRefund = true), boundary))
saveCalculation(korean, saveUsage(UseCan(CanUsage.DONATION, 40, 0), boundary))
saveCalculation(korean, saveUsage(UseCan(CanUsage.CHANNEL_DONATION, 40, 0), start.minusSeconds(1)))
saveCalculation(korean, saveUsage(UseCan(CanUsage.CHANNEL_DONATION, 40, 0), end.plusSeconds(1)))
entityManager.flush()
entityManager.clear()
val expectedTotal = GetAdminChannelDonationSettlementTotal(2, 6, 600, 40, 327, 11, 316)
assertEquals(expectedTotal, repository.getChannelDonationByDateTotal(start, end).toResponseTotal())
assertEquals(expectedTotal, repository.getChannelDonationByCreatorTotal(start, end).toResponseTotal())
assertEquals(2, repository.getChannelDonationByDateTotalCount(start, end))
assertEquals(2, repository.getChannelDonationByCreatorTotalCount(start, end))
assertEquals(
listOf(
GetAdminChannelDonationSettlementItem("2026-11-01", "japanese", 1, 3, 300, 20, 140, 5, 135),
GetAdminChannelDonationSettlementItem("2026-11-01", "korean", 2, 3, 300, 20, 187, 6, 181)
),
repository.getChannelDonationByDate(start, end, 0, 20).map { it.toResponseItem() }
)
val expectedPage = listOf(GetAdminChannelDonationSettlementByCreatorItem("korean", 2, 3, 300, 20, 187, 6, 181))
assertEquals(expectedPage, repository.getChannelDonationByCreator(start, end, 1, 1).map { it.toResponseItem() })
assertEquals(
listOf(
GetAdminChannelDonationSettlementByCreatorItem("japanese", 1, 3, 300, 20, 140, 5, 135),
GetAdminChannelDonationSettlementByCreatorItem("korean", 2, 3, 300, 20, 187, 6, 181)
),
repository.getChannelDonationByCreatorForExcel(start, end).map { it.toResponseItem() }
)
}
@ParameterizedTest
@ValueSource(ints = [0, 1])
@DisplayName("빈 관리자 집계와 유효한 0캔 후원은 금액이 0이어도 행과 건수가 다르다")
fun shouldDistinguishEmptyResultsFromZeroCanSources(sourceCount: Int) {
val creator = saveMember("creator", "KR")
repeat(sourceCount) {
saveCalculation(creator, saveUsage(UseCan(CanUsage.CHANNEL_DONATION, 0, 0, countryCode = "KR"), boundary))
}
entityManager.flush()
entityManager.clear()
val expected = GetAdminChannelDonationSettlementTotal(sourceCount, 0, 0, 0, 0, 0, 0)
assertEquals(expected, repository.getChannelDonationByDateTotal(start, end).toResponseTotal())
assertEquals(expected, repository.getChannelDonationByCreatorTotal(start, end).toResponseTotal())
assertEquals(sourceCount, repository.getChannelDonationByDateTotalCount(start, end))
assertEquals(sourceCount, repository.getChannelDonationByCreatorTotalCount(start, end))
assertEquals(
List(sourceCount) { GetAdminChannelDonationSettlementItem("2026-11-01", "creator", 1, 0, 0, 0, 0, 0, 0) },
repository.getChannelDonationByDate(start, end, 0, 20).map { it.toResponseItem() }
)
val creators = List(sourceCount) { GetAdminChannelDonationSettlementByCreatorItem("creator", 1, 0, 0, 0, 0, 0, 0) }
assertEquals(creators, repository.getChannelDonationByCreator(start, end, 0, 20).map { it.toResponseItem() })
assertEquals(creators, repository.getChannelDonationByCreatorForExcel(start, end).map { it.toResponseItem() })
}
private fun saveMember(nickname: String, country: String?, role: MemberRole = MemberRole.CREATOR): Member {
val member = Member(
email = "$nickname@test.com",
password = "password",
nickname = nickname,
role = role,
countryCode = country
)
entityManager.persist(member)
return member
}
private fun saveUsage(usage: UseCan, at: LocalDateTime): UseCan {
usage.member = sender
entityManager.persist(usage)
entityManager.flush()
entityManager.createQuery("update UseCan u set u.createdAt = :at where u.id = :id")
.setParameter("at", at).setParameter("id", usage.id).executeUpdate()
return usage
}
private fun saveCalculation(
creator: Member,
usage: UseCan,
calculation: UseCanCalculate = UseCanCalculate(usage.can, PaymentGateway.PG, UseCanCalculateStatus.RECEIVED)
) {
calculation.useCan = usage
calculation.recipientCreatorId = creator.id
entityManager.persist(calculation)
}
data class PolicyCase(
val creatorCountry: String?,
val transactionCountry: String?,
val at: LocalDateTime,
val expected: GetAdminChannelDonationSettlementTotal
)
companion object {
@JvmStatic
fun policyCases(): List<PolicyCase> {
val boundary = LocalDateTime.of(2026, 10, 31, 15, 0)
val legacy = GetAdminChannelDonationSettlementTotal(1, 100, 10000, 660, 7939, 262, 7677)
val korean = GetAdminChannelDonationSettlementTotal(1, 100, 10000, 660, 7005, 231, 6774)
val foreign = GetAdminChannelDonationSettlementTotal(1, 100, 10000, 660, 6538, 216, 6322)
val cross = GetAdminChannelDonationSettlementTotal(1, 100, 10000, 660, 4670, 154, 4516)
return listOf(
PolicyCase("JP", "KR", boundary.minusSeconds(1), legacy),
PolicyCase("KR", "KR", boundary, korean),
PolicyCase("KR", "KR", boundary.plusDays(1), korean),
PolicyCase("JP", "JP", boundary.plusSeconds(1), foreign),
PolicyCase("KR", "JP", boundary, cross),
PolicyCase(null, null, boundary, korean),
PolicyCase(null, "KR", boundary, korean),
PolicyCase("KR", null, boundary, korean),
PolicyCase("", " ", boundary, korean),
PolicyCase(" ", "", boundary, korean),
PolicyCase("JP", null, boundary, cross),
PolicyCase(null, "JP", boundary, cross)
)
}
}
}