diff --git a/src/main/kotlin/kr/co/vividnext/sodalive/admin/calculate/AdminCalculateQueryRepository.kt b/src/main/kotlin/kr/co/vividnext/sodalive/admin/calculate/AdminCalculateQueryRepository.kt index 2f863361..ed69b5d2 100644 --- a/src/main/kotlin/kr/co/vividnext/sodalive/admin/calculate/AdminCalculateQueryRepository.kt +++ b/src/main/kotlin/kr/co/vividnext/sodalive/admin/calculate/AdminCalculateQueryRepository.kt @@ -13,11 +13,15 @@ import kr.co.vividnext.sodalive.content.order.QOrder.order import kr.co.vividnext.sodalive.explorer.profile.creatorCommunity.QCreatorCommunity.creatorCommunity import kr.co.vividnext.sodalive.live.room.QLiveRoom.liveRoom 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 AdminCalculateQueryRepository(private val queryFactory: JPAQueryFactory) { +class AdminCalculateQueryRepository( + private val queryFactory: JPAQueryFactory, + private val countrySettlementExpressions: CountrySettlementExpressions +) { fun getCalculateLiveTotalCount(startDate: LocalDateTime, endDate: LocalDateTime): Int { return queryFactory .select(liveRoom.id) @@ -58,7 +62,15 @@ class AdminCalculateQueryRepository(private val queryFactory: JPAQueryFactory) { useCan.canUsage, useCan.id.count(), useCan.can.add(useCan.rewardCan).sum(), - creatorSettlementRatio.liveSettlementRatio + creatorSettlementRatio.liveSettlementRatio, + countrySettlementExpressions.newPolicyCan(useCan.createdAt, useCan.can.add(useCan.rewardCan)), + countrySettlementExpressions.newPolicyWeightedRatioCan( + useCan.createdAt, + useCan.can.add(useCan.rewardCan), + member.countryCode, + useCan.countryCode, + creatorSettlementRatio.liveSettlementRatio + ) ) ) .from(useCan) @@ -139,12 +151,21 @@ class AdminCalculateQueryRepository(private val queryFactory: JPAQueryFactory) { order.id.count(), order.can.sum(), order.point.sum(), - contentSettlementRatio + contentSettlementRatio, + countrySettlementExpressions.newPolicyCan(order.createdAt, order.can), + countrySettlementExpressions.newPolicyWeightedRatioCan( + order.createdAt, + order.can, + member.countryCode, + useCan.countryCode, + contentSettlementRatio + ) ) ) .from(order) .innerJoin(order.audioContent, audioContent) .innerJoin(audioContent.member, member) + .leftJoin(useCan).on(useCan.order.id.eq(order.id)) .leftJoin(creatorSettlementRatio) .on( member.id.eq(creatorSettlementRatio.member.id) @@ -171,15 +192,8 @@ class AdminCalculateQueryRepository(private val queryFactory: JPAQueryFactory) { private fun getFormattedDate(dateTimePath: DateTimePath): 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 ) } @@ -222,12 +236,21 @@ class AdminCalculateQueryRepository(private val queryFactory: JPAQueryFactory) { order.id.count(), order.can.sum(), order.point.sum(), - contentSettlementRatio + contentSettlementRatio, + countrySettlementExpressions.newPolicyCan(order.createdAt, order.can), + countrySettlementExpressions.newPolicyWeightedRatioCan( + order.createdAt, + order.can, + member.countryCode, + useCan.countryCode, + contentSettlementRatio + ) ) ) .from(order) .innerJoin(order.audioContent, audioContent) .innerJoin(audioContent.member, member) + .leftJoin(useCan).on(useCan.order.id.eq(order.id)) .leftJoin(creatorSettlementRatio) .on( member.id.eq(creatorSettlementRatio.member.id) @@ -284,7 +307,14 @@ class AdminCalculateQueryRepository(private val queryFactory: JPAQueryFactory) { getFormattedDate(audioContent.createdAt), donationFormattedDate, useCan.id.count(), - useCan.can.add(useCan.rewardCan).sum() + useCan.can.add(useCan.rewardCan).sum(), + countrySettlementExpressions.newPolicyCan(useCan.createdAt, useCan.can.add(useCan.rewardCan)), + countrySettlementExpressions.newPolicyWeightedRatioCan( + useCan.createdAt, + useCan.can.add(useCan.rewardCan), + member.countryCode, + useCan.countryCode + ) ) ) .from(useCan) @@ -337,7 +367,15 @@ class AdminCalculateQueryRepository(private val queryFactory: JPAQueryFactory) { creatorCommunity.price, useCan.id.count(), useCan.can.add(useCan.rewardCan).sum(), - creatorSettlementRatio.communitySettlementRatio + creatorSettlementRatio.communitySettlementRatio, + countrySettlementExpressions.newPolicyCan(useCan.createdAt, useCan.can.add(useCan.rewardCan)), + countrySettlementExpressions.newPolicyWeightedRatioCan( + useCan.createdAt, + useCan.can.add(useCan.rewardCan), + member.countryCode, + useCan.countryCode, + creatorSettlementRatio.communitySettlementRatio + ) ) ) .from(useCan) @@ -394,7 +432,15 @@ class AdminCalculateQueryRepository(private val queryFactory: JPAQueryFactory) { member.id, member.nickname, useCan.can.add(useCan.rewardCan).sum(), - creatorSettlementRatio.liveSettlementRatio + creatorSettlementRatio.liveSettlementRatio, + countrySettlementExpressions.newPolicyCan(useCan.createdAt, useCan.can.add(useCan.rewardCan)), + countrySettlementExpressions.newPolicyWeightedRatioCan( + useCan.createdAt, + useCan.can.add(useCan.rewardCan), + member.countryCode, + useCan.countryCode, + creatorSettlementRatio.liveSettlementRatio + ) ) ) .from(useCan) @@ -450,12 +496,21 @@ class AdminCalculateQueryRepository(private val queryFactory: JPAQueryFactory) { member.id, member.nickname, order.can.sum(), - creatorSettlementRatio.contentSettlementRatio + creatorSettlementRatio.contentSettlementRatio, + countrySettlementExpressions.newPolicyCan(order.createdAt, order.can), + countrySettlementExpressions.newPolicyWeightedRatioCan( + order.createdAt, + order.can, + member.countryCode, + useCan.countryCode, + audioContent.settlementRatio.coalesce(creatorSettlementRatio.contentSettlementRatio) + ) ) ) .from(order) .innerJoin(order.audioContent, audioContent) .innerJoin(audioContent.member, member) + .leftJoin(useCan).on(useCan.order.id.eq(order.id)) .leftJoin(creatorSettlementRatio) .on( member.id.eq(creatorSettlementRatio.member.id) @@ -507,7 +562,15 @@ class AdminCalculateQueryRepository(private val queryFactory: JPAQueryFactory) { member.id, member.nickname, useCan.can.add(useCan.rewardCan).sum(), - creatorSettlementRatio.communitySettlementRatio + creatorSettlementRatio.communitySettlementRatio, + countrySettlementExpressions.newPolicyCan(useCan.createdAt, useCan.can.add(useCan.rewardCan)), + countrySettlementExpressions.newPolicyWeightedRatioCan( + useCan.createdAt, + useCan.can.add(useCan.rewardCan), + member.countryCode, + useCan.countryCode, + creatorSettlementRatio.communitySettlementRatio + ) ) ) .from(useCan) diff --git a/src/main/kotlin/kr/co/vividnext/sodalive/admin/calculate/AdminCalculateService.kt b/src/main/kotlin/kr/co/vividnext/sodalive/admin/calculate/AdminCalculateService.kt index afd8d0e6..48f3620e 100644 --- a/src/main/kotlin/kr/co/vividnext/sodalive/admin/calculate/AdminCalculateService.kt +++ b/src/main/kotlin/kr/co/vividnext/sodalive/admin/calculate/AdminCalculateService.kt @@ -18,7 +18,6 @@ import kr.co.vividnext.sodalive.i18n.SodaMessageSource import kr.co.vividnext.sodalive.live.room.LiveRoomRepository import org.apache.poi.ss.usermodel.Sheet import org.apache.poi.xssf.streaming.SXSSFWorkbook -import org.springframework.cache.annotation.Cacheable import org.springframework.data.repository.findByIdOrNull import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional @@ -132,10 +131,6 @@ class AdminCalculateService( } @Transactional(readOnly = true) - @Cacheable( - cacheNames = ["cache_ttl_3_hours"], - key = "'cumulativeSalesByContent:' + " + "#offset + ':' + #limit" - ) fun getCumulativeSalesByContent(offset: Long, limit: Long): GetCumulativeSalesByContentResponse { val totalCount = repository.getCumulativeSalesByContentTotalCount() val items = repository diff --git a/src/main/kotlin/kr/co/vividnext/sodalive/creator/admin/calculate/CreatorAdminCalculateQueryRepository.kt b/src/main/kotlin/kr/co/vividnext/sodalive/creator/admin/calculate/CreatorAdminCalculateQueryRepository.kt index 0c782da1..43faf669 100644 --- a/src/main/kotlin/kr/co/vividnext/sodalive/creator/admin/calculate/CreatorAdminCalculateQueryRepository.kt +++ b/src/main/kotlin/kr/co/vividnext/sodalive/creator/admin/calculate/CreatorAdminCalculateQueryRepository.kt @@ -4,6 +4,7 @@ import com.querydsl.core.types.dsl.CaseBuilder import com.querydsl.core.types.dsl.DateTimePath import com.querydsl.core.types.dsl.Expressions import com.querydsl.core.types.dsl.StringTemplate +import com.querydsl.jpa.impl.JPAQuery import com.querydsl.jpa.impl.JPAQueryFactory import kr.co.vividnext.sodalive.admin.calculate.GetCalculateCommunityPostQueryData import kr.co.vividnext.sodalive.admin.calculate.GetCalculateContentDonationQueryData @@ -23,16 +24,36 @@ import kr.co.vividnext.sodalive.content.order.QOrder.order import kr.co.vividnext.sodalive.explorer.profile.creatorCommunity.QCreatorCommunity.creatorCommunity import kr.co.vividnext.sodalive.live.room.QLiveRoom.liveRoom 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 CreatorAdminCalculateQueryRepository(private val queryFactory: JPAQueryFactory) { +class CreatorAdminCalculateQueryRepository( + private val queryFactory: JPAQueryFactory, + private val countrySettlementExpressions: CountrySettlementExpressions +) { fun getCalculateLive( startDate: LocalDateTime, endDate: LocalDateTime, memberId: Long ): List { + return calculateLiveQuery(memberId) + .where(useCan.createdAt.goe(startDate), useCan.createdAt.loe(endDate)) + .fetch() + } + + fun getMonthlyCalculateLive( + startInclusiveUtc: LocalDateTime, + endExclusiveUtc: LocalDateTime, + memberId: Long + ): List { + return calculateLiveQuery(memberId) + .where(useCan.createdAt.goe(startInclusiveUtc), useCan.createdAt.lt(endExclusiveUtc)) + .fetch() + } + + private fun calculateLiveQuery(memberId: Long): JPAQuery { val formattedDate = getFormattedDate(liveRoom.beginDateTime) return queryFactory @@ -46,7 +67,15 @@ class CreatorAdminCalculateQueryRepository(private val queryFactory: JPAQueryFac useCan.canUsage, useCan.id.count(), useCan.can.add(useCan.rewardCan).sum(), - creatorSettlementRatio.liveSettlementRatio + creatorSettlementRatio.liveSettlementRatio, + countrySettlementExpressions.newPolicyCan(useCan.createdAt, useCan.can.add(useCan.rewardCan)), + countrySettlementExpressions.newPolicyWeightedRatioCan( + useCan.createdAt, + useCan.can.add(useCan.rewardCan), + member.countryCode, + useCan.countryCode, + creatorSettlementRatio.liveSettlementRatio + ) ) ) .from(useCan) @@ -59,13 +88,10 @@ class CreatorAdminCalculateQueryRepository(private val queryFactory: JPAQueryFac ) .where( useCan.isRefund.isFalse - .and(useCan.createdAt.goe(startDate)) - .and(useCan.createdAt.loe(endDate)) .and(liveRoom.member.id.eq(memberId)) ) .groupBy(liveRoom.id, useCan.canUsage, creatorSettlementRatio.liveSettlementRatio) .orderBy(liveRoom.id.desc(), useCan.canUsage.desc(), formattedDate.desc()) - .fetch() } fun getCalculateContentListTotalCount( @@ -108,6 +134,24 @@ class CreatorAdminCalculateQueryRepository(private val queryFactory: JPAQueryFac offset: Long, limit: Long ): List { + return calculateContentQuery(memberId) + .where(order.createdAt.goe(startDate), order.createdAt.loe(endDate)) + .offset(offset) + .limit(limit) + .fetch() + } + + fun getMonthlyCalculateContentList( + startInclusiveUtc: LocalDateTime, + endExclusiveUtc: LocalDateTime, + memberId: Long + ): List { + return calculateContentQuery(memberId) + .where(order.createdAt.goe(startInclusiveUtc), order.createdAt.lt(endExclusiveUtc)) + .fetch() + } + + private fun calculateContentQuery(memberId: Long): JPAQuery { val orderFormattedDate = getFormattedDate(order.createdAt) val pointGroup = CaseBuilder() .`when`(order.point.loe(0)).then(0) @@ -126,21 +170,28 @@ class CreatorAdminCalculateQueryRepository(private val queryFactory: JPAQueryFac order.id.count(), order.can.sum(), order.point.sum(), - contentSettlementRatio + contentSettlementRatio, + countrySettlementExpressions.newPolicyCan(order.createdAt, order.can), + countrySettlementExpressions.newPolicyWeightedRatioCan( + order.createdAt, + order.can, + member.countryCode, + useCan.countryCode, + contentSettlementRatio + ) ) ) .from(order) .innerJoin(order.audioContent, audioContent) .innerJoin(audioContent.member, member) + .leftJoin(useCan).on(useCan.order.id.eq(order.id)) .leftJoin(creatorSettlementRatio) .on( member.id.eq(creatorSettlementRatio.member.id) .and(creatorSettlementRatio.deletedAt.isNull) ) .where( - order.createdAt.goe(startDate) - .and(order.createdAt.loe(endDate)) - .and(order.isActive.isTrue) + order.isActive.isTrue .and(order.creator.id.eq(memberId)) ) .groupBy( @@ -151,23 +202,13 @@ class CreatorAdminCalculateQueryRepository(private val queryFactory: JPAQueryFac pointGroup, contentSettlementRatio ) - .offset(offset) - .limit(limit) .orderBy(member.id.desc(), orderFormattedDate.desc(), audioContent.id.asc()) - .fetch() } private fun getFormattedDate(dateTimePath: DateTimePath): 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 ) } @@ -217,12 +258,21 @@ class CreatorAdminCalculateQueryRepository(private val queryFactory: JPAQueryFac order.id.count(), order.can.sum(), order.point.sum(), - contentSettlementRatio + contentSettlementRatio, + countrySettlementExpressions.newPolicyCan(order.createdAt, order.can), + countrySettlementExpressions.newPolicyWeightedRatioCan( + order.createdAt, + order.can, + member.countryCode, + useCan.countryCode, + contentSettlementRatio + ) ) ) .from(order) .innerJoin(order.audioContent, audioContent) .innerJoin(audioContent.member, member) + .leftJoin(useCan).on(useCan.order.id.eq(order.id)) .leftJoin(creatorSettlementRatio) .on( member.id.eq(creatorSettlementRatio.member.id) @@ -276,6 +326,24 @@ class CreatorAdminCalculateQueryRepository(private val queryFactory: JPAQueryFac offset: Long, limit: Long ): List { + return calculateContentDonationQuery(memberId) + .where(useCan.createdAt.goe(startDate), useCan.createdAt.loe(endDate)) + .offset(offset) + .limit(limit) + .fetch() + } + + fun getMonthlyCalculateContentDonationList( + startInclusiveUtc: LocalDateTime, + endExclusiveUtc: LocalDateTime, + memberId: Long + ): List { + return calculateContentDonationQuery(memberId) + .where(useCan.createdAt.goe(startInclusiveUtc), useCan.createdAt.lt(endExclusiveUtc)) + .fetch() + } + + private fun calculateContentDonationQuery(memberId: Long): JPAQuery { val donationFormattedDate = getFormattedDate(useCan.createdAt) return queryFactory .select( @@ -286,7 +354,14 @@ class CreatorAdminCalculateQueryRepository(private val queryFactory: JPAQueryFac getFormattedDate(audioContent.createdAt), donationFormattedDate, useCan.id.count(), - useCan.can.add(useCan.rewardCan).sum() + useCan.can.add(useCan.rewardCan).sum(), + countrySettlementExpressions.newPolicyCan(useCan.createdAt, useCan.can.add(useCan.rewardCan)), + countrySettlementExpressions.newPolicyWeightedRatioCan( + useCan.createdAt, + useCan.can.add(useCan.rewardCan), + member.countryCode, + useCan.countryCode + ) ) ) .from(useCan) @@ -295,15 +370,10 @@ class CreatorAdminCalculateQueryRepository(private val queryFactory: JPAQueryFac .where( useCan.isRefund.isFalse .and(useCan.canUsage.eq(CanUsage.DONATION)) - .and(useCan.createdAt.goe(startDate)) - .and(useCan.createdAt.loe(endDate)) .and(audioContent.member.id.eq(memberId)) ) .groupBy(donationFormattedDate, audioContent.id) - .offset(offset) - .limit(limit) .orderBy(member.id.asc(), donationFormattedDate.desc()) - .fetch() } fun getCalculateCommunityPostTotalCount(startDate: LocalDateTime?, endDate: LocalDateTime?, memberId: Long): Int { @@ -332,6 +402,24 @@ class CreatorAdminCalculateQueryRepository(private val queryFactory: JPAQueryFac offset: Long, limit: Long ): List { + return calculateCommunityPostQuery(memberId) + .where(useCan.createdAt.goe(startDate), useCan.createdAt.loe(endDate)) + .offset(offset) + .limit(limit) + .fetch() + } + + fun getMonthlyCalculateCommunityPostList( + startInclusiveUtc: LocalDateTime, + endExclusiveUtc: LocalDateTime, + memberId: Long + ): List { + return calculateCommunityPostQuery(memberId) + .where(useCan.createdAt.goe(startInclusiveUtc), useCan.createdAt.lt(endExclusiveUtc)) + .fetch() + } + + private fun calculateCommunityPostQuery(memberId: Long): JPAQuery { val formattedDate = getFormattedDate(useCan.createdAt) return queryFactory .select( @@ -342,7 +430,15 @@ class CreatorAdminCalculateQueryRepository(private val queryFactory: JPAQueryFac creatorCommunity.price, useCan.id.count(), useCan.can.add(useCan.rewardCan).sum(), - creatorSettlementRatio.communitySettlementRatio + creatorSettlementRatio.communitySettlementRatio, + countrySettlementExpressions.newPolicyCan(useCan.createdAt, useCan.can.add(useCan.rewardCan)), + countrySettlementExpressions.newPolicyWeightedRatioCan( + useCan.createdAt, + useCan.can.add(useCan.rewardCan), + member.countryCode, + useCan.countryCode, + creatorSettlementRatio.communitySettlementRatio + ) ) ) .from(useCan) @@ -356,14 +452,9 @@ class CreatorAdminCalculateQueryRepository(private val queryFactory: JPAQueryFac .where( useCan.isRefund.isFalse .and(useCan.canUsage.eq(CanUsage.PAID_COMMUNITY_POST)) - .and(useCan.createdAt.goe(startDate)) - .and(useCan.createdAt.loe(endDate)) .and(creatorCommunity.member.id.eq(memberId)) ) .groupBy(formattedDate, creatorCommunity.id, creatorSettlementRatio.communitySettlementRatio) .orderBy(member.id.asc(), formattedDate.desc()) - .offset(offset) - .limit(limit) - .fetch() } } diff --git a/src/main/kotlin/kr/co/vividnext/sodalive/creator/admin/calculate/CreatorAdminCalculateService.kt b/src/main/kotlin/kr/co/vividnext/sodalive/creator/admin/calculate/CreatorAdminCalculateService.kt index 46ea0f64..fe273f81 100644 --- a/src/main/kotlin/kr/co/vividnext/sodalive/creator/admin/calculate/CreatorAdminCalculateService.kt +++ b/src/main/kotlin/kr/co/vividnext/sodalive/creator/admin/calculate/CreatorAdminCalculateService.kt @@ -4,17 +4,12 @@ import kr.co.vividnext.sodalive.admin.calculate.GetCalculateLiveResponse import kr.co.vividnext.sodalive.admin.calculate.GetCumulativeSalesByContentResponse import kr.co.vividnext.sodalive.extensions.convertLocalDateTime import kr.co.vividnext.sodalive.member.Member -import org.springframework.cache.annotation.Cacheable import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional @Service class CreatorAdminCalculateService(private val repository: CreatorAdminCalculateQueryRepository) { @Transactional(readOnly = true) - @Cacheable( - cacheNames = ["default"], - key = "'creatorCalculateLive:v20240403_01:' + " + "#member + ':' + #startDateStr + ':' + #endDateStr" - ) fun getCalculateLive(startDateStr: String, endDateStr: String, member: Member): List { val startDate = startDateStr.convertLocalDateTime() val endDate = endDateStr.convertLocalDateTime(hour = 23, minute = 59, second = 59) @@ -25,11 +20,6 @@ class CreatorAdminCalculateService(private val repository: CreatorAdminCalculate } @Transactional(readOnly = true) - @Cacheable( - cacheNames = ["cache_ttl_3_hours"], - key = "'creatorCalculateContentList:v20240403_01:' + " + - "#startDateStr + ':' + #endDateStr + ':' + #memberId + ':' + #offset + ':' + #limit" - ) fun getCalculateContentList( startDateStr: String, endDateStr: String, @@ -48,10 +38,6 @@ class CreatorAdminCalculateService(private val repository: CreatorAdminCalculate } @Transactional(readOnly = true) - @Cacheable( - cacheNames = ["cache_ttl_3_hours"], - key = "'creatorCumulativeSalesByContent:' + " + "#memberId + ':' + #offset + ':' + #limit" - ) fun getCumulativeSalesByContent(memberId: Long, offset: Long, limit: Long): GetCumulativeSalesByContentResponse { val totalCount = repository.getCumulativeSalesByContentTotalCount(memberId) val items = repository @@ -62,11 +48,6 @@ class CreatorAdminCalculateService(private val repository: CreatorAdminCalculate } @Transactional(readOnly = true) - @Cacheable( - cacheNames = ["cache_ttl_3_hours"], - key = "'creatorCalculateContentDonationList2:' + " + - "#startDateStr + ':' + #endDateStr + ':' + #memberId + ':' + #offset + ':' + #limit" - ) fun getCalculateContentDonationList( startDateStr: String, endDateStr: String, @@ -86,11 +67,6 @@ class CreatorAdminCalculateService(private val repository: CreatorAdminCalculate } @Transactional(readOnly = true) - @Cacheable( - cacheNames = ["cache_ttl_3_hours"], - key = "'creatorCalculateCommunityPost:' + " + - "#startDateStr + ':' + #endDateStr + ':' + #memberId + ':' + #offset + ':' + #limit" - ) fun getCalculateCommunityPost( startDateStr: String, endDateStr: String, diff --git a/src/test/kotlin/kr/co/vividnext/sodalive/admin/calculate/AdminCalculateQueryRepositoryTest.kt b/src/test/kotlin/kr/co/vividnext/sodalive/admin/calculate/AdminCalculateQueryRepositoryTest.kt index a15d302d..0027d691 100644 --- a/src/test/kotlin/kr/co/vividnext/sodalive/admin/calculate/AdminCalculateQueryRepositoryTest.kt +++ b/src/test/kotlin/kr/co/vividnext/sodalive/admin/calculate/AdminCalculateQueryRepositoryTest.kt @@ -1,8 +1,12 @@ package kr.co.vividnext.sodalive.admin.calculate import com.querydsl.jpa.impl.JPAQueryFactory +import kr.co.vividnext.sodalive.admin.calculate.ratio.CreatorSettlementRatio +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.can.use.UseCanRepository import kr.co.vividnext.sodalive.configs.QueryDslConfig import kr.co.vividnext.sodalive.content.AudioContent @@ -18,10 +22,16 @@ import kr.co.vividnext.sodalive.live.room.LiveRoomRepository 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.assertAll 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.Arguments +import org.junit.jupiter.params.provider.MethodSource import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest import org.springframework.context.annotation.Import @@ -46,10 +56,22 @@ class AdminCalculateQueryRepositoryTest @Autowired constructor( private val entityManager: EntityManager ) { private lateinit var repository: AdminCalculateQueryRepository + private val effectiveAt = LocalDateTime.of(2026, 10, 31, 15, 0) + private val startDate = effectiveAt.minusDays(1) + private val endDate = effectiveAt.plusDays(1) @BeforeEach fun setup() { - repository = AdminCalculateQueryRepository(queryFactory) + repository = AdminCalculateQueryRepository( + queryFactory, + CountrySettlementExpressions(CountrySettlementPolicy()) + ) + 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() } @Test @@ -86,6 +108,416 @@ class AdminCalculateQueryRepositoryTest @Autowired constructor( assertEquals(listOf(creator.id), communityRows.map { it.creatorId }) } + @ParameterizedTest + @MethodSource("countryCases") + @DisplayName("일반 관리자 조회의 실제 금액은 시행 시각부터 국가와 개별 비율을 적용한다") + fun shouldApplyCountryRatesThroughEveryGeneralAdminQuery( + creatorCountry: String?, + transactionCountry: String?, + individualRatio: Int?, + expected: List, + donationExpected: List + ) { + // given + val creator = saveMember(null, "creator", MemberRole.CREATOR).apply { countryCode = creatorCountry } + if (individualRatio != null) { + saveRatio(creator, individualRatio) + } + saveGeneralSources(creator, transactionCountry, effectiveAt) + entityManager.flush() + entityManager.clear() + + // when + val live = repository.getCalculateLive(startDate, endDate, 0, 10).single().toGetCalculateLiveResponse() + val content = repository.getCalculateContentList(startDate, endDate, 0, 10).single().toGetCalculateContentResponse() + val donation = repository.getCalculateContentDonationList(startDate, endDate, 0, 10) + .single().toGetCalculateContentDonationResponse() + val community = repository.getCalculateCommunityPostList(startDate, endDate, 0, 10) + .single().toGetCalculateCommunityPostResponse() + val cumulative = repository.getCumulativeSalesByContent(0, 10).single().toCumulativeSalesByContentItem() + val byCreator = listOf( + repository.getCalculateLiveByCreator(startDate, endDate, 0, 10).single().toGetCalculateByCreator(), + repository.getCalculateContentByCreator(startDate, endDate, 0, 10).single().toGetCalculateByCreator(), + repository.getCalculateCommunityByCreator(startDate, endDate, 0, 10).single().toGetCalculateByCreator() + ) + + // then: 100 CAN -> 10,000 KRW, PG 660; each amount is rounded independently. + assertAll( + { assertEquals(expected, live.run { listOf(totalKrw, paymentFee, settlementAmount, tax, depositAmount) }) }, + { + assertEquals( + expected, + content.run { listOf(totalKrw, paymentFee, settlementAmount, tax, depositAmount) } + ) + }, + { + assertEquals( + donationExpected, + donation.run { listOf(totalKrw, paymentFee, settlementAmount, tax, depositAmount) } + ) + }, + { + assertEquals( + expected, + community.run { listOf(totalKrw, paymentFee, settlementAmount, tax, depositAmount) } + ) + }, + { + assertEquals( + expected, + cumulative.run { listOf(totalKrw, paymentFee, settlementAmount, tax, depositAmount) } + ) + }, + { + assertEquals( + List(3) { expected }, + byCreator.map { listOf(it.totalKrw, it.paymentFee, it.settlementAmount, it.tax, it.depositAmount) } + ) + } + ) + } + + @Test + @DisplayName("라이브는 한 방에 구정책과 여러 국가가 섞여도 보상캔과 환불 조건 및 페이지를 유지한다") + fun shouldKeepOneLiveGroupAcrossPolicyBoundaryCountriesRewardsAndRefunds() { + // given + val creator = saveMember(null, "creator", MemberRole.CREATOR).apply { countryCode = "KR" } + val buyer = saveMember("buyer@test.com", "buyer", MemberRole.USER).apply { countryCode = "US" } + val room = saveLiveRoom(creator) + listOf(effectiveAt.minusSeconds(1) to "JP", effectiveAt to "KR", effectiveAt.plusSeconds(1) to "JP") + .forEach { (at, country) -> + saveUseCan(buyer, CanUsage.LIVE, 75, at, rewardCan = 25) { + this.room = room + countryCode = country + } + } + saveUseCan(buyer, CanUsage.LIVE, 999, effectiveAt) { + this.room = room + isRefund = true + } + saveUseCan(buyer, CanUsage.LIVE, 999, endDate.plusSeconds(1)) { this.room = room } + entityManager.flush() + entityManager.clear() + + // when + val count = repository.getCalculateLiveTotalCount(startDate, endDate) + val first = repository.getCalculateLive(startDate, endDate, 0, 1).single().toGetCalculateLiveResponse() + val next = repository.getCalculateLive(startDate, endDate, 1, 1) + val creatorCount = repository.getCalculateLiveByCreatorTotalCount(startDate, endDate) + val creatorRow = repository.getCalculateLiveByCreator(startDate, endDate, 0, 1).single().toGetCalculateByCreator() + val creatorNext = repository.getCalculateLiveByCreator(startDate, endDate, 1, 1) + + // then: 100*100*.934*(.70 + .75 + .50) = 18,213 before independent tax/deposit rounding. + assertEquals(1, count) + assertEquals(3, first.numberOfPeople) + assertEquals(300, first.totalAmount) + assertEquals(emptyList(), next) + assertEquals(1, creatorCount) + assertEquals(emptyList(), creatorNext) + assertAll( + { + assertEquals( + listOf(30_000, 1_980, 18_213, 601, 17_612), + listOf(first.totalKrw, first.paymentFee, first.settlementAmount, first.tax, first.depositAmount) + ) + }, + { + assertEquals( + listOf(300, 18_213, 601, 17_612), + listOf(creatorRow.totalCan, creatorRow.settlementAmount, creatorRow.tax, creatorRow.depositAmount) + ) + } + ) + } + + @Test + @DisplayName("콘텐츠는 주문 금액과 시각을 유지하고 국가 연결 누락과 분할 결제로 행이나 금액을 바꾸지 않는다") + fun shouldKeepOrderSourceContentOverridesPointsAndPagesAcrossBoundary() { + // given + val creator = saveMember(null, "creator", MemberRole.CREATOR).apply { countryCode = "KR" } + saveRatio(creator, 90) + val buyer = saveMember("buyer@test.com", "buyer", MemberRole.USER).apply { countryCode = "JP" } + val content = saveAudioContent(creator).apply { + price = 100 + settlementRatio = 80 + } + val old = saveOrder(buyer, creator, content, effectiveAt.minusSeconds(1)) + saveUseCan(buyer, CanUsage.ORDER_CONTENT, 999, effectiveAt.plusSeconds(1)) { + order = old + countryCode = "JP" + } + val same = saveOrder(buyer, creator, content, effectiveAt) + saveUseCan(buyer, CanUsage.ORDER_CONTENT, 1, effectiveAt.minusSeconds(1)) { + order = same + countryCode = "KR" + } + val cross = saveOrder(buyer, creator, content, effectiveAt.plusSeconds(1)) + val spend = saveUseCan(buyer, CanUsage.ORDER_CONTENT, 1, effectiveAt, rewardCan = 9) { + order = cross + countryCode = "JP" + } + listOf(PaymentGateway.PG, PaymentGateway.GOOGLE_IAP).forEach { gateway -> + entityManager.persist(UseCanCalculate(5, gateway, UseCanCalculateStatus.RECEIVED).apply { useCan = spend }) + } + saveOrder(buyer, creator, content, effectiveAt.plusSeconds(2)) + saveOrder(buyer, creator, content, effectiveAt.plusSeconds(3)) { + can = 0 + point = 100 + } + saveOrder(buyer, creator, content, effectiveAt.plusSeconds(4)) { isActive = false } + saveUseCan(buyer, CanUsage.DONATION, 999, effectiveAt) { + audioContent = content + countryCode = "JP" + } + entityManager.flush() + entityManager.clear() + + // when + val count = repository.getCalculateContentListTotalCount(startDate, endDate) + val rows = repository.getCalculateContentList(startDate, endDate, 0, 10) + val cumulativeCount = repository.getCumulativeSalesByContentTotalCount() + val cumulativeRows = repository.getCumulativeSalesByContent(0, 10) + val creatorCount = repository.getCalculateContentByCreatorTotalCount(startDate, endDate) + val creatorRow = repository.getCalculateContentByCreator(startDate, endDate, 0, 1).single().toGetCalculateByCreator() + + // then: daily new = 7,472 + 4,670 + 7,472; cumulative adds legacy content80, by-creator adds legacy creator90. + assertEquals(3, count) + assertEquals(3, rows.size) + assertEquals(1, repository.getCalculateContentList(startDate, endDate, 0, 1).size) + assertEquals(emptyList(), repository.getCalculateContentList(startDate, endDate, 3, 1)) + assertEquals(2, cumulativeCount) + assertEquals(2, cumulativeRows.size) + assertEquals(1, repository.getCumulativeSalesByContent(0, 1).size) + assertEquals(emptyList(), repository.getCumulativeSalesByContent(2, 1)) + assertEquals(1, creatorCount) + assertEquals( + emptyList(), + repository.getCalculateContentByCreator(startDate, endDate, 1, 1) + ) + val oldRow = rows.single { it.saleDate == "2026-10-31" }.toGetCalculateContentResponse() + val newRow = rows.single { it.saleDate == "2026-11-01" && it.totalPoint == 0 }.toGetCalculateContentResponse() + val pointRow = rows.single { it.totalPoint == 100 }.toGetCalculateContentResponse() + val cumulative = cumulativeRows.single { it.totalPoint == 0 }.toCumulativeSalesByContentItem() + val cumulativePoint = cumulativeRows.single { it.totalPoint == 100 }.toCumulativeSalesByContentItem() + assertAll( + { + assertEquals( + listOf(100, 7_472, 247, 7_225), + oldRow.run { listOf(totalCan, settlementAmount, tax, depositAmount) } + ) + }, + { + assertEquals( + listOf(3, 300, 30_000, 1_980, 19_614, 647, 18_967), + newRow.run { listOf(numberOfPeople, totalCan, totalKrw, paymentFee, settlementAmount, tax, depositAmount) } + ) + }, + { + assertEquals("포인트", pointRow.orderType) + assertEquals( + listOf(1, 0, 0, 0, 0, 0, 0), + pointRow.run { listOf(numberOfPeople, totalCan, totalKrw, paymentFee, settlementAmount, tax, depositAmount) } + ) + assertEquals("포인트", cumulativePoint.orderType) + assertEquals( + listOf(1, 0, 0, 0, 0, 0, 0), + cumulativePoint.run { + listOf(numberOfPeople, totalCan, totalKrw, paymentFee, settlementAmount, tax, depositAmount) + } + ) + }, + { + assertEquals( + listOf(4, 400, 40_000, 2_640, 27_086, 894, 26_192), + cumulative.run { + listOf(numberOfPeople, totalCan, totalKrw, paymentFee, settlementAmount, tax, depositAmount) + } + ) + }, + { + assertEquals( + listOf(400, 28_020, 925, 27_095), + listOf(creatorRow.totalCan, creatorRow.settlementAmount, creatorRow.tax, creatorRow.depositAmount) + ) + } + ) + } + + @Test + @DisplayName("후원과 커뮤니티는 국가로 일별 페이지를 나누지 않고 과거 금액과 환불 및 보상캔을 유지한다") + fun shouldKeepDonationAndCommunityDailyGroupsAndLegacyRounding() { + // given + val creator = saveMember(null, "creator", MemberRole.CREATOR).apply { countryCode = "KR" } + val buyer = saveMember("buyer@test.com", "buyer", MemberRole.USER) + val content = saveAudioContent(creator) + val post = saveCommunityPost(creator) + listOf( + Triple(effectiveAt.minusSeconds(1), "JP", 125), + Triple(effectiveAt, "KR", 100), + Triple(effectiveAt.plusSeconds(1), "JP", 100) + ).forEach { (at, country, total) -> + saveUseCan(buyer, CanUsage.DONATION, total - 25, at, rewardCan = 25) { + audioContent = content + countryCode = country + } + saveUseCan(buyer, CanUsage.PAID_COMMUNITY_POST, total - 25, at, rewardCan = 25) { + communityPost = post + countryCode = country + } + } + saveUseCan(buyer, CanUsage.DONATION, 999, effectiveAt) { + audioContent = content + isRefund = true + } + saveUseCan(buyer, CanUsage.PAID_COMMUNITY_POST, 999, effectiveAt) { + communityPost = post + isRefund = true + } + val order = saveOrder(buyer, creator, content, effectiveAt) + saveUseCan(buyer, CanUsage.ORDER_CONTENT, 999, effectiveAt) { + audioContent = content + this.order = order + } + entityManager.flush() + entityManager.clear() + + // when + val donationCount = repository.getCalculateContentDonationListTotalCount(startDate, endDate) + val donation = repository.getCalculateContentDonationList(startDate, endDate, 0, 1) + .single().toGetCalculateContentDonationResponse() + val oldDonation = repository.getCalculateContentDonationList(startDate, endDate, 1, 1) + .single().toGetCalculateContentDonationResponse() + val communityCount = repository.getCalculateCommunityPostTotalCount(startDate, endDate) + val community = repository.getCalculateCommunityPostList(startDate, endDate, 0, 1) + .single().toGetCalculateCommunityPostResponse() + val oldCommunity = repository.getCalculateCommunityPostList(startDate, endDate, 1, 1) + .single().toGetCalculateCommunityPostResponse() + val creatorCount = repository.getCalculateCommunityByCreatorTotalCount(startDate, endDate) + val creatorRow = repository.getCalculateCommunityByCreator(startDate, endDate, 0, 1).single().toGetCalculateByCreator() + + // then + assertEquals(2, donationCount) + assertEquals(2, communityCount) + assertEquals("2026-11-01", donation.donationDate) + assertEquals("2026-11-01", community.date) + assertEquals(2, donation.numberOfDonation) + assertEquals(2, community.numberOfPurchase) + assertEquals(1, creatorCount) + assertEquals( + emptyList(), + repository.getCalculateContentDonationList(startDate, endDate, 2, 1) + ) + assertEquals( + emptyList(), + repository.getCalculateCommunityPostList(startDate, endDate, 2, 1) + ) + assertAll( + { + assertEquals( + listOf(200, 20_000, 1_320, 11_675, 385, 11_290), + donation.run { listOf(totalCan, totalKrw, paymentFee, settlementAmount, tax, depositAmount) } + ) + }, + { + assertEquals( + listOf(200, 20_000, 1_320, 11_675, 385, 11_290), + community.run { listOf(totalCan, totalKrw, paymentFee, settlementAmount, tax, depositAmount) } + ) + }, + { + assertEquals( + listOf(125, 8_173, 270, 7_903), + oldDonation.run { listOf(totalCan, settlementAmount, tax, depositAmount) } + ) + }, + { + assertEquals( + listOf(125, 8_172, 270, 7_903), + oldCommunity.run { listOf(totalCan, settlementAmount, tax, depositAmount) } + ) + }, + { + assertEquals( + listOf(325, 19_847, 655, 19_193), + listOf(creatorRow.totalCan, creatorRow.settlementAmount, creatorRow.tax, creatorRow.depositAmount) + ) + } + ) + } + + @Test + @DisplayName("시행 직전 125캔의 모든 일반 조회는 기존 경로별 정확한 반올림을 유지한다") + fun shouldPreserveExactLegacyAmountsForEveryGeneralAdminQuery() { + // given + val creator = saveMember(null, "creator", MemberRole.CREATOR).apply { countryCode = "KR" } + saveGeneralSources(creator, "JP", effectiveAt.minusSeconds(1), totalCan = 125) + entityManager.flush() + entityManager.clear() + + // when + val live = repository.getCalculateLive(startDate, endDate, 0, 10).single().toGetCalculateLiveResponse() + val content = repository.getCalculateContentList(startDate, endDate, 0, 10).single().toGetCalculateContentResponse() + val donation = repository.getCalculateContentDonationList(startDate, endDate, 0, 10) + .single().toGetCalculateContentDonationResponse() + val community = repository.getCalculateCommunityPostList(startDate, endDate, 0, 10) + .single().toGetCalculateCommunityPostResponse() + val cumulative = repository.getCumulativeSalesByContent(0, 10).single().toCumulativeSalesByContentItem() + val byCreator = listOf( + repository.getCalculateLiveByCreator(startDate, endDate, 0, 10).single().toGetCalculateByCreator(), + repository.getCalculateContentByCreator(startDate, endDate, 0, 10).single().toGetCalculateByCreator(), + repository.getCalculateCommunityByCreator(startDate, endDate, 0, 10).single().toGetCalculateByCreator() + ) + + // then: legacy Double constants round 8,172.5 down here; donation's decimal constants round it up. + val expected = listOf(12_500, 825, 8_172, 270, 7_903) + assertAll( + { assertEquals(expected, live.run { listOf(totalKrw, paymentFee, settlementAmount, tax, depositAmount) }) }, + { assertEquals(expected, content.run { listOf(totalKrw, paymentFee, settlementAmount, tax, depositAmount) }) }, + { + assertEquals( + listOf(12_500, 825, 8_173, 270, 7_903), + donation.run { listOf(totalKrw, paymentFee, settlementAmount, tax, depositAmount) } + ) + }, + { assertEquals(expected, community.run { listOf(totalKrw, paymentFee, settlementAmount, tax, depositAmount) }) }, + { assertEquals(expected, cumulative.run { listOf(totalKrw, paymentFee, settlementAmount, tax, depositAmount) }) }, + { + assertEquals( + List(3) { expected }, + byCreator.map { listOf(it.totalKrw, it.paymentFee, it.settlementAmount, it.tax, it.depositAmount) } + ) + } + ) + } + + private fun saveRatio(creator: Member, ratio: Int) { + entityManager.persist(CreatorSettlementRatio(0, ratio, ratio, ratio).apply { member = creator }) + } + + private fun saveGeneralSources(creator: Member, country: String?, at: LocalDateTime, totalCan: Int = 100) { + val buyer = saveMember("buyer@test.com", "buyer", MemberRole.USER).apply { countryCode = "US" } + val room = saveLiveRoom(creator) + saveUseCan(buyer, CanUsage.LIVE, totalCan - 25, at, rewardCan = 25) { + this.room = room + countryCode = country + } + val content = saveAudioContent(creator).apply { price = totalCan } + val order = saveOrder(buyer, creator, content, at) + saveUseCan(buyer, CanUsage.ORDER_CONTENT, 1, at) { + this.order = order + countryCode = country + } + saveUseCan(buyer, CanUsage.DONATION, totalCan - 25, at, rewardCan = 25) { + audioContent = content + countryCode = country + } + val post = saveCommunityPost(creator) + saveUseCan(buyer, CanUsage.PAID_COMMUNITY_POST, totalCan - 25, at, rewardCan = 25) { + communityPost = post + countryCode = country + } + } + private fun saveMember(email: String?, nickname: String, role: MemberRole): Member { return memberRepository.saveAndFlush( Member( @@ -126,13 +558,21 @@ class AdminCalculateQueryRepositoryTest @Autowired constructor( return audioContentRepository.saveAndFlush(content) } - private fun saveOrder(buyer: Member, creator: Member, content: AudioContent, createdAt: LocalDateTime) { + private fun saveOrder( + buyer: Member, + creator: Member, + content: AudioContent, + createdAt: LocalDateTime, + configure: Order.() -> Unit = {} + ): Order { val order = Order(type = OrderType.KEEP) order.member = buyer order.creator = creator order.audioContent = content + order.configure() val saved = orderRepository.saveAndFlush(order) updateCreatedAt("Order", saved.id!!, createdAt) + return saved } private fun saveCommunityPost(creator: Member): CreatorCommunity { @@ -151,13 +591,15 @@ class AdminCalculateQueryRepositoryTest @Autowired constructor( usage: CanUsage, can: Int, createdAt: LocalDateTime, + rewardCan: Int = 0, configure: UseCan.() -> Unit - ) { - val useCan = UseCan(canUsage = usage, can = can, rewardCan = 0) + ): UseCan { + val useCan = UseCan(canUsage = usage, can = can, rewardCan = rewardCan) useCan.member = member useCan.configure() val saved = useCanRepository.saveAndFlush(useCan) updateCreatedAt("UseCan", saved.id!!, createdAt) + return saved } private fun updateCreatedAt(entityName: String, id: Long, createdAt: LocalDateTime) { @@ -166,4 +608,19 @@ class AdminCalculateQueryRepositoryTest @Autowired constructor( .setParameter("id", id) .executeUpdate() } + + companion object { + @JvmStatic + fun countryCases(): List = listOf( + Arguments.of("KR", "KR", null, listOf(10_000, 660, 7_005, 231, 6_774), listOf(10_000, 660, 7_005, 231, 6_774)), + Arguments.of("JP", "JP", null, listOf(10_000, 660, 6_538, 216, 6_322), listOf(10_000, 660, 6_538, 216, 6_322)), + Arguments.of("KR", "JP", 90, listOf(10_000, 660, 4_670, 154, 4_516), listOf(10_000, 660, 4_670, 154, 4_516)), + Arguments.of("KR", "KR", 90, listOf(10_000, 660, 8_406, 277, 8_129), listOf(10_000, 660, 7_005, 231, 6_774)), + Arguments.of("JP", "JP", 90, listOf(10_000, 660, 8_406, 277, 8_129), listOf(10_000, 660, 6_538, 216, 6_322)), + Arguments.of(null, null, null, listOf(10_000, 660, 7_005, 231, 6_774), listOf(10_000, 660, 7_005, 231, 6_774)), + Arguments.of("", " ", null, listOf(10_000, 660, 7_005, 231, 6_774), listOf(10_000, 660, 7_005, 231, 6_774)), + Arguments.of("JP", null, 90, listOf(10_000, 660, 4_670, 154, 4_516), listOf(10_000, 660, 4_670, 154, 4_516)), + Arguments.of(null, "JP", 90, listOf(10_000, 660, 4_670, 154, 4_516), listOf(10_000, 660, 4_670, 154, 4_516)) + ) + } } diff --git a/src/test/kotlin/kr/co/vividnext/sodalive/creator/admin/calculate/CreatorAdminCalculateQueryRepositoryTest.kt b/src/test/kotlin/kr/co/vividnext/sodalive/creator/admin/calculate/CreatorAdminCalculateQueryRepositoryTest.kt new file mode 100644 index 00000000..a7767641 --- /dev/null +++ b/src/test/kotlin/kr/co/vividnext/sodalive/creator/admin/calculate/CreatorAdminCalculateQueryRepositoryTest.kt @@ -0,0 +1,641 @@ +package kr.co.vividnext.sodalive.creator.admin.calculate + +import com.querydsl.jpa.impl.JPAQueryFactory +import kr.co.vividnext.sodalive.admin.calculate.GetCalculateCommunityPostQueryData +import kr.co.vividnext.sodalive.admin.calculate.GetCalculateContentDonationQueryData +import kr.co.vividnext.sodalive.admin.calculate.GetCalculateContentQueryData +import kr.co.vividnext.sodalive.admin.calculate.GetCumulativeSalesByContentQueryData +import kr.co.vividnext.sodalive.admin.calculate.ratio.CreatorSettlementRatio +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.common.BaseEntity +import kr.co.vividnext.sodalive.configs.QueryDslConfig +import kr.co.vividnext.sodalive.content.AudioContent +import kr.co.vividnext.sodalive.content.order.Order +import kr.co.vividnext.sodalive.content.order.OrderType +import kr.co.vividnext.sodalive.content.theme.AudioContentTheme +import kr.co.vividnext.sodalive.explorer.profile.creatorCommunity.CreatorCommunity +import kr.co.vividnext.sodalive.live.room.LiveRoom +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.assertAll +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.Arguments +import org.junit.jupiter.params.provider.MethodSource +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 CreatorAdminCalculateQueryRepositoryTest @Autowired constructor( + private val queryFactory: JPAQueryFactory, + private val entityManager: EntityManager +) { + private lateinit var repository: CreatorAdminCalculateQueryRepository + private lateinit var creator: Member + private lateinit var buyer: Member + private lateinit var room: LiveRoom + private lateinit var content: AudioContent + private lateinit var post: CreatorCommunity + private val effectiveAt = LocalDateTime.of(2026, 10, 31, 15, 0) + private val startDate = effectiveAt.minusDays(1) + private val endDate = effectiveAt.plusDays(1) + + @BeforeEach + fun setup() { + repository = CreatorAdminCalculateQueryRepository( + queryFactory, + CountrySettlementExpressions(CountrySettlementPolicy()) + ) + 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() + creator = persist(Member(password = "password", nickname = "creator", role = MemberRole.CREATOR, countryCode = "KR")) + buyer = persist(Member(password = "password", nickname = "buyer", countryCode = "US")) + room = persist( + LiveRoom("live", "notice", effectiveAt.minusDays(1), 1, isAdult = false, price = 100).apply { member = creator } + ) + val theme = persist(AudioContentTheme("theme", "theme.png")) + content = persist( + AudioContent("content", "detail", "ko", price = 100).apply { + member = creator + this.theme = theme + isActive = true + } + ) + post = persist(CreatorCommunity("community", 100, true, false).apply { member = creator }) + } + + @ParameterizedTest + @MethodSource("countryCases") + @DisplayName("크리에이터의 기존 일반 조회는 시행 시각부터 각 원천에 국가 비율을 연결한다") + fun shouldApplyCountryRatesThroughEveryGeneralCreatorQuery( + creatorCountry: String?, + transactionCountry: String?, + individualRatio: Int?, + expected: List, + donationExpected: List + ) { + // given + creator.countryCode = creatorCountry + if (individualRatio != null) { + persist(CreatorSettlementRatio(0, individualRatio, individualRatio, individualRatio).apply { member = creator }) + } + saveGeneralSources(effectiveAt, transactionCountry) + entityManager.flush() + entityManager.clear() + val creatorId = requireNotNull(creator.id) + + // when + val live = repository.getCalculateLive(startDate, endDate, creatorId).single().toGetCalculateLiveResponse() + val content = repository.getCalculateContentList(startDate, endDate, creatorId, 0, 10) + .single().toGetCalculateContentResponse() + val donation = repository.getCalculateContentDonationList(startDate, endDate, creatorId, 0, 10) + .single().toGetCalculateContentDonationResponse() + val community = repository.getCalculateCommunityPostList(startDate, endDate, creatorId, 0, 10) + .single().toGetCalculateCommunityPostResponse() + val cumulative = repository.getCumulativeSalesByContent(creatorId, 0, 10).single().toCumulativeSalesByContentItem() + + // then + assertAll( + { assertEquals(expected, live.run { listOf(totalKrw, paymentFee, settlementAmount, tax, depositAmount) }) }, + { + assertEquals( + expected, + content.run { listOf(totalKrw, paymentFee, settlementAmount, tax, depositAmount) } + ) + }, + { + assertEquals( + donationExpected, + donation.run { listOf(totalKrw, paymentFee, settlementAmount, tax, depositAmount) } + ) + }, + { + assertEquals( + expected, + community.run { listOf(totalKrw, paymentFee, settlementAmount, tax, depositAmount) } + ) + }, + { + assertEquals( + expected, + cumulative.run { listOf(totalKrw, paymentFee, settlementAmount, tax, depositAmount) } + ) + } + ) + } + + @Test + @DisplayName("라이브의 같은 행은 시행 전후와 국가가 섞여도 유지하고 다른 크리에이터 및 환불은 제외한다") + fun shouldKeepMixedPolicyLiveGroupScopedToItsCurrentCreator() { + // given + listOf(effectiveAt.minusSeconds(1) to "JP", effectiveAt to "KR", effectiveAt.plusSeconds(1) to "JP") + .forEach { (at, country) -> + persist( + UseCan(CanUsage.LIVE, 75, 25, countryCode = country).apply { + member = buyer + room = this@CreatorAdminCalculateQueryRepositoryTest.room + }, + at + ) + } + persist( + UseCan(CanUsage.LIVE, 999, 0, isRefund = true).apply { + member = buyer + room = this@CreatorAdminCalculateQueryRepositoryTest.room + }, + effectiveAt + ) + val other = persist(Member(password = "password", nickname = "other", role = MemberRole.CREATOR, countryCode = "KR")) + val otherRoom = persist( + LiveRoom("other", "notice", effectiveAt, 1, isAdult = false).apply { member = other } + ) + persist( + UseCan(CanUsage.LIVE, 999, 0, countryCode = "KR").apply { + member = buyer + room = otherRoom + }, + effectiveAt + ) + entityManager.flush() + entityManager.clear() + + // when + val rows = repository.getCalculateLive(startDate, endDate, requireNotNull(creator.id)) + + // then + assertEquals(1, rows.size) + val result = rows.single().toGetCalculateLiveResponse() + assertEquals(room.id, result.roomId) + assertEquals(3, result.numberOfPeople) + assertEquals( + listOf(300, 30_000, 1_980, 18_213, 601, 17_612), + result.run { listOf(totalAmount, totalKrw, paymentFee, settlementAmount, tax, depositAmount) } + ) + } + + @Test + @DisplayName("콘텐츠 주문은 누락 연결과 PG 분할에도 유지하고 콘텐츠 비율 및 주문 시각과 포인트 그룹을 보존한다") + fun shouldKeepOrderSourceContentOverridesPointsAndCreatorPagesAcrossBoundary() { + // given + persist(CreatorSettlementRatio(0, 90, 90, 90).apply { member = creator }) + content.settlementRatio = 80 + val old = saveOrder(effectiveAt.minusSeconds(1)) + persist( + UseCan(CanUsage.ORDER_CONTENT, 999, 0, countryCode = "JP").apply { + member = buyer + order = old + }, + effectiveAt.plusSeconds(1) + ) + val same = saveOrder(effectiveAt) + persist( + UseCan(CanUsage.ORDER_CONTENT, 1, 0, countryCode = "KR").apply { + member = buyer + order = same + }, + effectiveAt.minusSeconds(1) + ) + val cross = saveOrder(effectiveAt.plusSeconds(1)) + val spend = persist( + UseCan(CanUsage.ORDER_CONTENT, 1, 9, countryCode = "JP").apply { + member = buyer + order = cross + }, + effectiveAt + ) + listOf(PaymentGateway.PG, PaymentGateway.GOOGLE_IAP).forEach { gateway -> + persist(UseCanCalculate(5, gateway, UseCanCalculateStatus.RECEIVED).apply { useCan = spend }) + } + saveOrder(effectiveAt.plusSeconds(2)) + saveOrder(effectiveAt.plusSeconds(3)) { + can = 0 + point = 100 + } + saveOrder(effectiveAt.plusSeconds(4)) { isActive = false } + val other = persist(Member(password = "password", nickname = "other", role = MemberRole.CREATOR)) + val otherTheme = persist(AudioContentTheme("other", "other.png")) + val otherContent = persist( + AudioContent("other", "detail", "ko", price = 999).apply { + member = other + theme = otherTheme + } + ) + persist( + Order(OrderType.KEEP).apply { + member = buyer + creator = other + audioContent = otherContent + }, + effectiveAt + ) + persist( + UseCan(CanUsage.DONATION, 999, 0, countryCode = "JP").apply { + member = buyer + audioContent = content + }, + effectiveAt + ) + entityManager.flush() + entityManager.clear() + val creatorId = requireNotNull(creator.id) + + // when + val count = repository.getCalculateContentListTotalCount(startDate, endDate, creatorId) + val rows = repository.getCalculateContentList(startDate, endDate, creatorId, 0, 10) + val cumulativeCount = repository.getCumulativeSalesByContentTotalCount(creatorId) + val cumulativeRows = repository.getCumulativeSalesByContent(creatorId, 0, 10) + + // then + assertEquals(3, count) + assertEquals(3, rows.size) + assertEquals(1, repository.getCalculateContentList(startDate, endDate, creatorId, 0, 1).size) + assertEquals( + emptyList(), + repository.getCalculateContentList(startDate, endDate, creatorId, 3, 1) + ) + assertEquals(2, cumulativeCount) + assertEquals(2, cumulativeRows.size) + assertEquals(1, repository.getCumulativeSalesByContent(creatorId, 0, 1).size) + assertEquals(emptyList(), repository.getCumulativeSalesByContent(creatorId, 2, 1)) + val oldRow = rows.single { it.saleDate == "2026-10-31" }.toGetCalculateContentResponse() + val newRow = rows.single { it.saleDate == "2026-11-01" && it.totalPoint == 0 }.toGetCalculateContentResponse() + val pointRow = rows.single { it.totalPoint == 100 }.toGetCalculateContentResponse() + val cumulative = cumulativeRows.single { it.totalPoint == 0 }.toCumulativeSalesByContentItem() + val cumulativePoint = cumulativeRows.single { it.totalPoint == 100 }.toCumulativeSalesByContentItem() + assertAll( + { + assertEquals( + listOf(100, 7_472, 247, 7_225), + oldRow.run { listOf(totalCan, settlementAmount, tax, depositAmount) } + ) + }, + { + assertEquals( + listOf(3, 300, 30_000, 1_980, 19_614, 647, 18_967), + newRow.run { listOf(numberOfPeople, totalCan, totalKrw, paymentFee, settlementAmount, tax, depositAmount) } + ) + }, + { + assertEquals("포인트", pointRow.orderType) + assertEquals( + listOf(1, 0, 0, 0, 0, 0, 0), + pointRow.run { listOf(numberOfPeople, totalCan, totalKrw, paymentFee, settlementAmount, tax, depositAmount) } + ) + assertEquals("포인트", cumulativePoint.orderType) + assertEquals( + listOf(1, 0, 0, 0, 0, 0, 0), + cumulativePoint.run { + listOf(numberOfPeople, totalCan, totalKrw, paymentFee, settlementAmount, tax, depositAmount) + } + ) + }, + { + assertEquals( + listOf(4, 400, 40_000, 2_640, 27_086, 894, 26_192), + cumulative.run { + listOf(numberOfPeople, totalCan, totalKrw, paymentFee, settlementAmount, tax, depositAmount) + } + ) + } + ) + } + + @Test + @DisplayName("후원과 커뮤니티는 국가 혼합과 보상캔에도 기존 두 날짜 페이지 및 환불 제외를 유지한다") + fun shouldKeepDonationAndCommunityDailyGroupsAndLegacyRounding() { + // given + listOf( + Triple(effectiveAt.minusSeconds(1), "JP", 125), + Triple(effectiveAt, "KR", 100), + Triple(effectiveAt.plusSeconds(1), "JP", 100) + ).forEach { (at, country, total) -> + persist( + UseCan(CanUsage.DONATION, total - 25, 25, countryCode = country).apply { + member = buyer + audioContent = content + }, + at + ) + persist( + UseCan(CanUsage.PAID_COMMUNITY_POST, total - 25, 25, countryCode = country).apply { + member = buyer + communityPost = post + }, + at + ) + } + persist( + UseCan(CanUsage.DONATION, 999, 0, isRefund = true).apply { + member = buyer + audioContent = content + }, + effectiveAt + ) + persist( + UseCan(CanUsage.PAID_COMMUNITY_POST, 999, 0, isRefund = true).apply { + member = buyer + communityPost = post + }, + effectiveAt + ) + val order = saveOrder(effectiveAt) + persist( + UseCan(CanUsage.ORDER_CONTENT, 999, 0).apply { + member = buyer + audioContent = content + this.order = order + }, + effectiveAt + ) + val other = persist(Member(password = "password", nickname = "other", role = MemberRole.CREATOR)) + val otherTheme = persist(AudioContentTheme("other", "other.png")) + val otherContent = persist( + AudioContent("other", "detail", "ko").apply { + member = other + theme = otherTheme + } + ) + val otherPost = persist(CreatorCommunity("other", 100, true, false).apply { member = other }) + persist( + UseCan(CanUsage.DONATION, 999, 0).apply { + member = buyer + audioContent = otherContent + }, + effectiveAt + ) + persist( + UseCan(CanUsage.PAID_COMMUNITY_POST, 999, 0).apply { + member = buyer + communityPost = otherPost + }, + effectiveAt + ) + entityManager.flush() + entityManager.clear() + val creatorId = requireNotNull(creator.id) + + // when + val donationCount = repository.getCalculateContentDonationListTotalCount(startDate, endDate, creatorId) + val donation = repository.getCalculateContentDonationList(startDate, endDate, creatorId, 0, 1) + .single().toGetCalculateContentDonationResponse() + val oldDonation = repository.getCalculateContentDonationList(startDate, endDate, creatorId, 1, 1) + .single().toGetCalculateContentDonationResponse() + val communityCount = repository.getCalculateCommunityPostTotalCount(startDate, endDate, creatorId) + val community = repository.getCalculateCommunityPostList(startDate, endDate, creatorId, 0, 1) + .single().toGetCalculateCommunityPostResponse() + val oldCommunity = repository.getCalculateCommunityPostList(startDate, endDate, creatorId, 1, 1) + .single().toGetCalculateCommunityPostResponse() + + // then + assertEquals(2, donationCount) + assertEquals(2, communityCount) + assertEquals("2026-11-01", donation.donationDate) + assertEquals("2026-11-01", community.date) + assertEquals(2, donation.numberOfDonation) + assertEquals(2, community.numberOfPurchase) + assertEquals( + emptyList(), + repository.getCalculateContentDonationList(startDate, endDate, creatorId, 2, 1) + ) + assertEquals( + emptyList(), + repository.getCalculateCommunityPostList(startDate, endDate, creatorId, 2, 1) + ) + assertAll( + { + assertEquals( + listOf(200, 20_000, 1_320, 11_675, 385, 11_290), + donation.run { listOf(totalCan, totalKrw, paymentFee, settlementAmount, tax, depositAmount) } + ) + }, + { + assertEquals( + listOf(200, 20_000, 1_320, 11_675, 385, 11_290), + community.run { listOf(totalCan, totalKrw, paymentFee, settlementAmount, tax, depositAmount) } + ) + }, + { + assertEquals( + listOf(125, 8_173, 270, 7_903), + oldDonation.run { listOf(totalCan, settlementAmount, tax, depositAmount) } + ) + }, + { + assertEquals( + listOf(125, 8_172, 270, 7_903), + oldCommunity.run { listOf(totalCan, settlementAmount, tax, depositAmount) } + ) + } + ) + } + + @Test + @DisplayName("시행 직전의 모든 크리에이터 일반 조회는 기존 125캔 금액을 정확히 유지한다") + fun shouldPreserveExactLegacyAmountsForEveryGeneralCreatorQuery() { + // given + saveGeneralSources(effectiveAt.minusSeconds(1), "JP", totalCan = 125) + entityManager.flush() + entityManager.clear() + val creatorId = requireNotNull(creator.id) + + // when + val live = repository.getCalculateLive(startDate, endDate, creatorId).single().toGetCalculateLiveResponse() + val content = repository.getCalculateContentList(startDate, endDate, creatorId, 0, 10) + .single().toGetCalculateContentResponse() + val donation = repository.getCalculateContentDonationList(startDate, endDate, creatorId, 0, 10) + .single().toGetCalculateContentDonationResponse() + val community = repository.getCalculateCommunityPostList(startDate, endDate, creatorId, 0, 10) + .single().toGetCalculateCommunityPostResponse() + val cumulative = repository.getCumulativeSalesByContent(creatorId, 0, 10).single().toCumulativeSalesByContentItem() + + // then + val expected = listOf(12_500, 825, 8_172, 270, 7_903) + assertAll( + { assertEquals(expected, live.run { listOf(totalKrw, paymentFee, settlementAmount, tax, depositAmount) }) }, + { assertEquals(expected, content.run { listOf(totalKrw, paymentFee, settlementAmount, tax, depositAmount) }) }, + { + assertEquals( + listOf(12_500, 825, 8_173, 270, 7_903), + donation.run { listOf(totalKrw, paymentFee, settlementAmount, tax, depositAmount) } + ) + }, + { assertEquals(expected, community.run { listOf(totalKrw, paymentFee, settlementAmount, tax, depositAmount) }) }, + { assertEquals(expected, cumulative.run { listOf(totalKrw, paymentFee, settlementAmount, tax, depositAmount) }) } + ) + } + + @Test + @DisplayName("기존 거래도 크리에이터 현재 계정 국가가 변경되면 새 국가로 비교한다") + fun shouldUseCurrentCreatorCountryWhenRereadingExistingTransactions() { + // given + saveGeneralSources(effectiveAt, "KR") + creator.countryCode = "JP" + entityManager.flush() + entityManager.clear() + val creatorId = requireNotNull(creator.id) + + // when + val live = repository.getCalculateLive(startDate, endDate, creatorId).single().toGetCalculateLiveResponse() + val content = repository.getCalculateContentList(startDate, endDate, creatorId, 0, 10) + .single().toGetCalculateContentResponse() + val donation = repository.getCalculateContentDonationList(startDate, endDate, creatorId, 0, 10) + .single().toGetCalculateContentDonationResponse() + val community = repository.getCalculateCommunityPostList(startDate, endDate, creatorId, 0, 10) + .single().toGetCalculateCommunityPostResponse() + val cumulative = repository.getCumulativeSalesByContent(creatorId, 0, 10).single().toCumulativeSalesByContentItem() + + // then + assertEquals( + listOf(4_670, 4_670, 4_670, 4_670, 4_670), + listOf( + live.settlementAmount, + content.settlementAmount, + donation.settlementAmount, + community.settlementAmount, + cumulative.settlementAmount + ) + ) + } + + @Test + @DisplayName("월별 네 원천은 정책 전후 조회 범위의 시작 포함과 종료 제외 및 여러 행을 유지한다") + fun shouldApplyHalfOpenMonthlyBoundsToEveryGeneralSourceWithoutPagination() { + // given + val monthStart = effectiveAt.minusDays(1) + val monthEnd = LocalDateTime.of(2026, 11, 30, 15, 0) + saveGeneralSources(monthStart.minusSeconds(1), "KR") + saveGeneralSources(monthStart, "KR") + saveGeneralSources(effectiveAt, "KR") + saveGeneralSources(monthEnd.minusSeconds(1), "JP") + saveGeneralSources(monthEnd, "KR") + entityManager.flush() + entityManager.clear() + val creatorId = requireNotNull(creator.id) + + // when + val live = repository.getMonthlyCalculateLive(monthStart, monthEnd, creatorId) + val content = repository.getMonthlyCalculateContentList(monthStart, monthEnd, creatorId) + val donation = repository.getMonthlyCalculateContentDonationList(monthStart, monthEnd, creatorId) + val community = repository.getMonthlyCalculateCommunityPostList(monthStart, monthEnd, creatorId) + + // then + assertEquals(1, live.size) + assertEquals(3, content.size) + assertEquals(3, donation.size) + assertEquals(3, community.size) + val dates = listOf("2026-10-31", "2026-11-01", "2026-11-30") + assertEquals(dates, content.map { it.saleDate }.sorted()) + assertEquals(dates, donation.map { it.donationDate }.sorted()) + assertEquals(dates, community.map { it.date }.sorted()) + assertAll( + { + assertEquals( + listOf(300, 18_213), + listOf(live.sumOf { it.totalAmount }, live.sumOf { it.toGetCalculateLiveResponse().settlementAmount }) + ) + }, + { + assertEquals( + listOf(300, 18_213), + listOf(content.sumOf { it.totalCan }, content.sumOf { it.toGetCalculateContentResponse().settlementAmount }) + ) + }, + { + assertEquals( + listOf(300, 18_213), + listOf( + donation.sumOf { it.totalCan }, + donation.sumOf { it.toGetCalculateContentDonationResponse().settlementAmount } + ) + ) + }, + { + assertEquals( + listOf(300, 18_213), + listOf( + community.sumOf { it.totalCan }, + community.sumOf { it.toGetCalculateCommunityPostResponse().settlementAmount } + ) + ) + } + ) + assertEquals(400, repository.getCalculateLive(monthStart, monthEnd, creatorId).sumOf { it.totalAmount }) + assertEquals(400, repository.getCalculateContentList(monthStart, monthEnd, creatorId, 0, 10).sumOf { it.totalCan }) + assertEquals( + 400, + repository.getCalculateContentDonationList(monthStart, monthEnd, creatorId, 0, 10).sumOf { it.totalCan } + ) + assertEquals(400, repository.getCalculateCommunityPostList(monthStart, monthEnd, creatorId, 0, 10).sumOf { it.totalCan }) + } + + private fun saveGeneralSources(at: LocalDateTime, country: String?, totalCan: Int = 100) { + val order = saveOrder(at) { can = totalCan } + listOf( + UseCan(CanUsage.LIVE, totalCan - 25, 25, countryCode = country).apply { + room = this@CreatorAdminCalculateQueryRepositoryTest.room + }, + UseCan(CanUsage.ORDER_CONTENT, 1, 0, countryCode = country).apply { this.order = order }, + UseCan(CanUsage.DONATION, totalCan - 25, 25, countryCode = country).apply { audioContent = content }, + UseCan(CanUsage.PAID_COMMUNITY_POST, totalCan - 25, 25, countryCode = country).apply { communityPost = post } + ).forEach { spend -> + spend.member = buyer + persist(spend, at) + } + } + + private fun saveOrder(at: LocalDateTime, configure: Order.() -> Unit = {}): Order { + return persist( + Order(OrderType.KEEP).apply { + creator = this@CreatorAdminCalculateQueryRepositoryTest.creator + member = buyer + audioContent = content + configure() + }, + at + ) + } + + private fun persist(entity: T, at: LocalDateTime = effectiveAt.minusDays(2)): T { + entityManager.persist(entity) + entityManager.flush() + entity.createdAt = at + return entity + } + + companion object { + @JvmStatic + fun countryCases(): List = listOf( + Arguments.of("KR", "KR", null, listOf(10_000, 660, 7_005, 231, 6_774), listOf(10_000, 660, 7_005, 231, 6_774)), + Arguments.of("JP", "JP", null, listOf(10_000, 660, 6_538, 216, 6_322), listOf(10_000, 660, 6_538, 216, 6_322)), + Arguments.of("KR", "JP", 90, listOf(10_000, 660, 4_670, 154, 4_516), listOf(10_000, 660, 4_670, 154, 4_516)), + Arguments.of("KR", "KR", 90, listOf(10_000, 660, 8_406, 277, 8_129), listOf(10_000, 660, 7_005, 231, 6_774)), + Arguments.of("JP", "JP", 90, listOf(10_000, 660, 8_406, 277, 8_129), listOf(10_000, 660, 6_538, 216, 6_322)), + Arguments.of(null, null, null, listOf(10_000, 660, 7_005, 231, 6_774), listOf(10_000, 660, 7_005, 231, 6_774)), + Arguments.of("", " ", null, listOf(10_000, 660, 7_005, 231, 6_774), listOf(10_000, 660, 7_005, 231, 6_774)), + Arguments.of("JP", null, 90, listOf(10_000, 660, 4_670, 154, 4_516), listOf(10_000, 660, 4_670, 154, 4_516)), + Arguments.of(null, "JP", 90, listOf(10_000, 660, 4_670, 154, 4_516), listOf(10_000, 660, 4_670, 154, 4_516)) + ) + } +}