diff --git a/src/main/kotlin/kr/co/vividnext/sodalive/partner/agent/calculate/AgentCalculateQueryRepository.kt b/src/main/kotlin/kr/co/vividnext/sodalive/partner/agent/calculate/AgentCalculateQueryRepository.kt index 710af214..b52f7856 100644 --- a/src/main/kotlin/kr/co/vividnext/sodalive/partner/agent/calculate/AgentCalculateQueryRepository.kt +++ b/src/main/kotlin/kr/co/vividnext/sodalive/partner/agent/calculate/AgentCalculateQueryRepository.kt @@ -15,6 +15,8 @@ import kr.co.vividnext.sodalive.live.room.QLiveRoom.liveRoom import kr.co.vividnext.sodalive.member.QMember.member import kr.co.vividnext.sodalive.partner.agent.assignment.QAgentCreatorRelation.agentCreatorRelation import kr.co.vividnext.sodalive.partner.agent.ratio.QAgentSettlementRatio.agentSettlementRatio +import kr.co.vividnext.sodalive.v2.settlement.adapter.out.persistence.CountrySettlementExpressions +import kr.co.vividnext.sodalive.v2.settlement.domain.CountrySettlementPolicy import org.springframework.beans.factory.annotation.Value import org.springframework.stereotype.Repository import java.time.LocalDateTime @@ -26,7 +28,9 @@ class AgentCalculateQueryRepository( private val entityManager: EntityManager, @Value("\${cloud.aws.cloud-front.host}") - private val cloudFrontHost: String + private val cloudFrontHost: String, + private val countrySettlementExpressions: CountrySettlementExpressions, + private val countrySettlementPolicy: CountrySettlementPolicy ) { fun getAssignedCreatorTotalCount(agentId: Long, currentTime: LocalDateTime): Int { return queryFactory @@ -423,42 +427,59 @@ class AgentCalculateQueryRepository( val query = entityManager.createNativeQuery( """ SELECT - COALESCE(SUM(grouped.count_value), 0) AS count, - COALESCE(SUM(grouped.total_can), 0) AS totalCan, - COALESCE(SUM(grouped.total_can * 100), 0) AS krw, - COALESCE(SUM(ROUND(grouped.total_can * 100 * 0.066, 0)), 0) AS fee, - COALESCE(SUM(ROUND(((grouped.total_can * 100) - ROUND(grouped.total_can * 100 * 0.066, 0)) * 0.85, 0)), 0) AS settlementAmount, - COALESCE(SUM(ROUND(ROUND(((grouped.total_can * 100) - ROUND(grouped.total_can * 100 * 0.066, 0)) * 0.85, 0) * 0.033, 0)), 0) AS withholdingTax, - COALESCE(SUM(ROUND(((grouped.total_can * 100) - ROUND(grouped.total_can * 100 * 0.066, 0)) * 0.85, 0) - ROUND(ROUND(((grouped.total_can * 100) - ROUND(grouped.total_can * 100 * 0.066, 0)) * 0.85, 0) * 0.033, 0)), 0) AS depositAmount, - COALESCE(SUM(ROUND(ROUND(((grouped.total_can * 100) - ROUND(grouped.total_can * 100 * 0.066, 0)) * 0.85, 0) * (grouped.agent_settlement_ratio / 100.0), 0)), 0) AS agentSettlementAmount + COALESCE(SUM(calculated.count_value), 0) AS count, + COALESCE(SUM(calculated.total_can), 0) AS totalCan, + COALESCE(SUM(calculated.total_can * 100), 0) AS krw, + COALESCE(SUM(ROUND(calculated.total_can * 100 * 0.066, 0)), 0) AS fee, + COALESCE(SUM(calculated.settlement_amount), 0) AS settlementAmount, + COALESCE(SUM(ROUND(calculated.settlement_amount * 0.033, 0)), 0) AS withholdingTax, + COALESCE(SUM(calculated.settlement_amount - ROUND(calculated.settlement_amount * 0.033, 0)), 0) AS depositAmount, + COALESCE(SUM(ROUND(calculated.settlement_amount + * (calculated.agent_settlement_ratio / 100.0), 0)), 0) AS agentSettlementAmount FROM ( SELECT - COUNT(DISTINCT uc.id) AS count_value, - SUM(ucc.can) AS total_can, - COALESCE(asr.settlement_ratio, 7) AS agent_settlement_ratio - FROM use_can_calculate ucc - INNER JOIN use_can uc ON ucc.use_can_id = uc.id - INNER JOIN member m ON m.id = ucc.recipient_creator_id - INNER JOIN agent_creator_relation acr ON acr.creator_id = m.id - AND acr.agent_id = :agentId - AND acr.assigned_at <= uc.created_at - AND (acr.unassigned_at IS NULL OR acr.unassigned_at > uc.created_at) - LEFT JOIN agent_settlement_ratio asr ON asr.member_id = :agentId - AND asr.effective_from <= uc.created_at - AND (asr.effective_to IS NULL OR asr.effective_to > uc.created_at) - WHERE uc.can_usage = 'CHANNEL_DONATION' - AND uc.is_refund = FALSE - AND ucc.status = 'RECEIVED' - AND uc.created_at >= :startDate - AND uc.created_at <= :endDate - GROUP BY acr.id, asr.id, COALESCE(asr.settlement_ratio, 7) - ) grouped + grouped.*, + ROUND(CASE + WHEN grouped.new_policy_can = 0 AND grouped.new_policy_weighted_ratio_can = 0 + THEN (grouped.total_can * 100 - ROUND(grouped.total_can * 100 * 0.066, 0)) * 0.85 + ELSE CAST((grouped.total_can * 100 - ROUND(grouped.total_can * 100 * 0.066, 0)) + * ((grouped.total_can - grouped.new_policy_can) * 85 + grouped.new_policy_weighted_ratio_can) + AS DECIMAL(65, 20)) + / (grouped.total_can * 100) + END, 0) AS settlement_amount + FROM ( + SELECT + COUNT(DISTINCT uc.id) AS count_value, + SUM(ucc.can) AS total_can, + COALESCE(asr.settlement_ratio, 7) AS agent_settlement_ratio, + ${newPolicyCanSql("uc.created_at", "ucc.can")} AS new_policy_can, + ${newPolicyWeightedRatioCanSql("uc.created_at", "ucc.can")} AS new_policy_weighted_ratio_can + FROM use_can_calculate ucc + INNER JOIN use_can uc ON ucc.use_can_id = uc.id + INNER JOIN member m ON m.id = ucc.recipient_creator_id + INNER JOIN agent_creator_relation acr ON acr.creator_id = m.id + AND acr.agent_id = :agentId + AND acr.assigned_at <= uc.created_at + AND (acr.unassigned_at IS NULL OR acr.unassigned_at > uc.created_at) + LEFT JOIN agent_settlement_ratio asr ON asr.member_id = :agentId + AND asr.effective_from <= uc.created_at + AND (asr.effective_to IS NULL OR asr.effective_to > uc.created_at) + WHERE uc.can_usage = 'CHANNEL_DONATION' + AND uc.is_refund = FALSE + AND ucc.status = 'RECEIVED' + AND uc.created_at >= :startDate + AND uc.created_at <= :endDate + GROUP BY acr.id, asr.id, COALESCE(asr.settlement_ratio, 7) + ) grouped + ) calculated """.trimIndent() ) query.setParameter("startDate", startDate) query.setParameter("endDate", endDate) query.setParameter("agentId", agentId) + query.setParameter("countryPolicyEffectiveAt", countrySettlementPolicy.effectiveAtUtc) + query.setParameter("koreanDefaultRateEndExclusive", countrySettlementPolicy.koreanDefaultRateEndExclusiveUtc) val result = query.singleResult as Array<*> @@ -528,7 +549,15 @@ class AgentCalculateQueryRepository( useCan.id.count(), useCan.can.add(useCan.rewardCan).sum(), creatorSettlementRatio.liveSettlementRatio, - agentSettlementRatio.settlementRatio + agentSettlementRatio.settlementRatio, + 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) @@ -582,12 +611,22 @@ class AgentCalculateQueryRepository( order.id.count(), order.can.sum(), contentSettlementRatio, - agentSettlementRatio.settlementRatio + agentSettlementRatio.settlementRatio, + 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)) .innerJoin(agentCreatorRelation) .on( agentCreatorRelation.creator.id.eq(member.id) @@ -634,7 +673,15 @@ class AgentCalculateQueryRepository( useCan.id.count(), useCan.can.add(useCan.rewardCan).sum(), creatorSettlementRatio.communitySettlementRatio, - agentSettlementRatio.settlementRatio + agentSettlementRatio.settlementRatio, + 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) @@ -687,7 +734,14 @@ class AgentCalculateQueryRepository( useCan.id.count(), useCan.can.add(useCan.rewardCan).sum(), Expressions.numberTemplate(Int::class.java, "70"), - agentSettlementRatio.settlementRatio + agentSettlementRatio.settlementRatio, + countrySettlementExpressions.newPolicyCan(useCan.createdAt, useCan.can.add(useCan.rewardCan)), + countrySettlementExpressions.newPolicyWeightedRatioCan( + useCan.createdAt, + useCan.can.add(useCan.rewardCan), + member.countryCode, + useCan.countryCode + ) ) ) .from(useCan) @@ -733,7 +787,14 @@ class AgentCalculateQueryRepository( agentSettlementRatio.id, useCan.id.countDistinct(), useCanCalculate.can.sum(), - agentSettlementRatio.settlementRatio + agentSettlementRatio.settlementRatio, + countrySettlementExpressions.newPolicyCan(useCan.createdAt, useCanCalculate.can), + countrySettlementExpressions.newPolicyWeightedRatioCan( + useCan.createdAt, + useCanCalculate.can, + member.countryCode, + useCan.countryCode + ) ) ) .from(useCanCalculate) @@ -775,23 +836,33 @@ class AgentCalculateQueryRepository( val query = entityManager.createNativeQuery( """ SELECT - COALESCE(SUM(grouped.count_value), 0) AS count, - COALESCE(SUM(grouped.total_can), 0) AS totalCan, - COALESCE(SUM(grouped.total_can * 100), 0) AS krw, - COALESCE(SUM(ROUND(grouped.total_can * 100 * 0.066, 0)), 0) AS fee, - COALESCE(SUM(ROUND(((grouped.total_can * 100) - ((grouped.total_can * 100) * 0.066)) * (grouped.settlement_ratio / 100.0), 0)), 0) AS settlementAmount, - COALESCE(SUM(ROUND((((grouped.total_can * 100) - ((grouped.total_can * 100) * 0.066)) * (grouped.settlement_ratio / 100.0)) * 0.033, 0)), 0) AS tax, - COALESCE(SUM(ROUND((((grouped.total_can * 100) - ((grouped.total_can * 100) * 0.066)) * (grouped.settlement_ratio / 100.0)) - ((((grouped.total_can * 100) - ((grouped.total_can * 100) * 0.066)) * (grouped.settlement_ratio / 100.0)) * 0.033), 0)), 0) AS depositAmount, - COALESCE(SUM(ROUND(ROUND(((grouped.total_can * 100) - ((grouped.total_can * 100) * 0.066)) * (grouped.settlement_ratio / 100.0), 0) * (grouped.agent_settlement_ratio / 100.0), 0)), 0) AS agentSettlementAmount + COALESCE(SUM(calculated.count_value), 0) AS count, + COALESCE(SUM(calculated.total_can), 0) AS totalCan, + COALESCE(SUM(calculated.total_can * 100), 0) AS krw, + COALESCE(SUM(ROUND(calculated.total_can * 100 * 0.066, 0)), 0) AS fee, + COALESCE(SUM(ROUND(calculated.settlement_amount, 0)), 0) AS settlementAmount, + COALESCE(SUM(ROUND(calculated.settlement_amount * 0.033, 0)), 0) AS tax, + COALESCE(SUM(ROUND(calculated.settlement_amount - calculated.settlement_amount * 0.033, 0)), 0) AS depositAmount, + COALESCE(SUM(ROUND(ROUND(calculated.settlement_amount, 0) + * (calculated.agent_settlement_ratio / 100.0), 0)), 0) AS agentSettlementAmount FROM ( - $subQuery - ) grouped + SELECT grouped.*, + (((grouped.total_can - grouped.new_policy_can) * 100) + - ((grouped.total_can - grouped.new_policy_can) * 100 * 0.066)) + * (grouped.settlement_ratio / 100.0) + + grouped.new_policy_weighted_ratio_can * (1.0 - 0.066) AS settlement_amount + FROM ( + $subQuery + ) grouped + ) calculated """.trimIndent() ) query.setParameter("startDate", startDate) query.setParameter("endDate", endDate) query.setParameter("agentId", agentId) + query.setParameter("countryPolicyEffectiveAt", countrySettlementPolicy.effectiveAtUtc) + query.setParameter("koreanDefaultRateEndExclusive", countrySettlementPolicy.koreanDefaultRateEndExclusiveUtc) val result = query.singleResult as Array<*> @@ -812,7 +883,10 @@ class AgentCalculateQueryRepository( COUNT(uc.id) AS count_value, SUM(uc.can + uc.reward_can) AS total_can, COALESCE(csr.live_settlement_ratio, 70) AS settlement_ratio, - COALESCE(asr.settlement_ratio, 7) AS agent_settlement_ratio + COALESCE(asr.settlement_ratio, 7) AS agent_settlement_ratio, + ${newPolicyCanSql("uc.created_at", "uc.can + uc.reward_can")} AS new_policy_can, + ${newPolicyWeightedRatioCanSql("uc.created_at", "uc.can + uc.reward_can", "csr.live_settlement_ratio")} + AS new_policy_weighted_ratio_can FROM use_can uc INNER JOIN live_room lr ON uc.room_id = lr.id INNER JOIN member m ON lr.member_id = m.id @@ -836,10 +910,17 @@ class AgentCalculateQueryRepository( COUNT(o.id) AS count_value, SUM(o.can) AS total_can, COALESCE(COALESCE(c.settlement_ratio, csr.content_settlement_ratio), 70) AS settlement_ratio, - COALESCE(asr.settlement_ratio, 7) AS agent_settlement_ratio + COALESCE(asr.settlement_ratio, 7) AS agent_settlement_ratio, + ${newPolicyCanSql("o.created_at", "o.can")} AS new_policy_can, + ${newPolicyWeightedRatioCanSql( + "o.created_at", + "o.can", + "COALESCE(c.settlement_ratio, csr.content_settlement_ratio)" + )} AS new_policy_weighted_ratio_can FROM orders o INNER JOIN content c ON o.content_id = c.id INNER JOIN member m ON c.member_id = m.id + LEFT JOIN use_can uc ON uc.order_id = o.id INNER JOIN agent_creator_relation acr ON acr.creator_id = m.id AND acr.agent_id = :agentId AND acr.assigned_at <= o.created_at @@ -865,7 +946,10 @@ class AgentCalculateQueryRepository( COUNT(uc.id) AS count_value, SUM(uc.can + uc.reward_can) AS total_can, COALESCE(csr.community_settlement_ratio, 70) AS settlement_ratio, - COALESCE(asr.settlement_ratio, 7) AS agent_settlement_ratio + COALESCE(asr.settlement_ratio, 7) AS agent_settlement_ratio, + ${newPolicyCanSql("uc.created_at", "uc.can + uc.reward_can")} AS new_policy_can, + ${newPolicyWeightedRatioCanSql("uc.created_at", "uc.can + uc.reward_can", "csr.community_settlement_ratio")} + AS new_policy_weighted_ratio_can FROM use_can uc INNER JOIN creator_community cc ON uc.creator_community_id = cc.id INNER JOIN member m ON cc.member_id = m.id @@ -890,7 +974,9 @@ class AgentCalculateQueryRepository( COUNT(uc.id) AS count_value, SUM(uc.can + uc.reward_can) AS total_can, 70 AS settlement_ratio, - COALESCE(asr.settlement_ratio, 7) AS agent_settlement_ratio + COALESCE(asr.settlement_ratio, 7) AS agent_settlement_ratio, + ${newPolicyCanSql("uc.created_at", "uc.can + uc.reward_can")} AS new_policy_can, + ${newPolicyWeightedRatioCanSql("uc.created_at", "uc.can + uc.reward_can")} AS new_policy_weighted_ratio_can FROM use_can uc INNER JOIN content c ON uc.content_id = c.id INNER JOIN member m ON c.member_id = m.id @@ -908,6 +994,27 @@ class AgentCalculateQueryRepository( GROUP BY acr.id, asr.id, COALESCE(asr.settlement_ratio, 7) """.trimIndent() + private fun newPolicyCanSql(eventAt: String, can: String) = + "SUM(CASE WHEN $eventAt >= :countryPolicyEffectiveAt THEN ($can) ELSE 0 END)" + + private fun newPolicyWeightedRatioCanSql(eventAt: String, can: String, individualRatio: String? = null): String { + val creatorCountry = "CASE WHEN m.country_code IS NULL OR TRIM(m.country_code) = '' THEN 'KR' ELSE m.country_code END" + val transactionCountry = + "CASE WHEN uc.country_code IS NULL OR TRIM(uc.country_code) = '' THEN 'KR' ELSE uc.country_code END" + val defaultRatio = + "CASE WHEN ($creatorCountry) = 'KR' AND $eventAt < :koreanDefaultRateEndExclusive THEN 75 ELSE 70 END" + val sameCountryRatio = individualRatio?.let { "COALESCE($it, $defaultRatio)" } ?: defaultRatio + return """ + SUM(CASE WHEN $eventAt >= :countryPolicyEffectiveAt + THEN CAST(($can) AS DECIMAL(20, 0)) * CASE + WHEN ($creatorCountry) <> ($transactionCountry) THEN 50 + ELSE $sameCountryRatio + END + ELSE 0 + END) + """.trimIndent() + } + private fun Any?.toIntValue(): Int { return when (this) { null -> 0 diff --git a/src/main/kotlin/kr/co/vividnext/sodalive/partner/agent/calculate/GetAgentChannelDonationSettlementByCreatorResponse.kt b/src/main/kotlin/kr/co/vividnext/sodalive/partner/agent/calculate/GetAgentChannelDonationSettlementByCreatorResponse.kt index a42c4c19..749d6ce8 100644 --- a/src/main/kotlin/kr/co/vividnext/sodalive/partner/agent/calculate/GetAgentChannelDonationSettlementByCreatorResponse.kt +++ b/src/main/kotlin/kr/co/vividnext/sodalive/partner/agent/calculate/GetAgentChannelDonationSettlementByCreatorResponse.kt @@ -42,10 +42,12 @@ data class GetAgentChannelDonationSettlementByCreatorQueryData @QueryProjection val agentSettlementRatioId: Long? = null, val count: Long, val totalCan: Int, - val agentSettlementRatio: Int? = null + val agentSettlementRatio: Int? = null, + val newPolicyCan: Int = 0, + val newPolicyWeightedRatioCan: Long = 0L ) { fun toResponseItem(): GetAgentChannelDonationSettlementByCreatorItem { - val amount = ChannelDonationSettlementCalculator.calculate(totalCan) + val amount = ChannelDonationSettlementCalculator.calculate(totalCan, newPolicyCan, newPolicyWeightedRatioCan) return GetAgentChannelDonationSettlementByCreatorItem( creatorId = creatorId, creatorNickname = creatorNickname, diff --git a/src/main/kotlin/kr/co/vividnext/sodalive/partner/agent/calculate/GetAgentCreatorSettlementSummaryQueryData.kt b/src/main/kotlin/kr/co/vividnext/sodalive/partner/agent/calculate/GetAgentCreatorSettlementSummaryQueryData.kt index 777f4cea..f399f7b9 100644 --- a/src/main/kotlin/kr/co/vividnext/sodalive/partner/agent/calculate/GetAgentCreatorSettlementSummaryQueryData.kt +++ b/src/main/kotlin/kr/co/vividnext/sodalive/partner/agent/calculate/GetAgentCreatorSettlementSummaryQueryData.kt @@ -12,13 +12,19 @@ data class GetAgentCreatorSettlementSummaryQueryData @QueryProjection constructo val count: Long, val totalCan: Int, val settlementRatio: Int?, - val agentSettlementRatio: Int? = null + val agentSettlementRatio: Int? = null, + val newPolicyCan: Int = 0, + val newPolicyWeightedRatioCan: Long = 0L ) { fun toResponseItem(): GetAgentSettlementByCreatorItem { val totalKrw = BigDecimal(totalCan).multiply(KRW_PER_CAN) val fee = totalKrw.multiply(PAYMENT_FEE_RATE) - val settlementAmount = totalKrw.subtract(fee) + val legacyKrw = BigDecimal(totalCan.toLong() - newPolicyCan.toLong()).multiply(KRW_PER_CAN) + val legacySettlementAmount = legacyKrw.subtract(legacyKrw.multiply(PAYMENT_FEE_RATE)) .multiply(BigDecimal(settlementRatio ?: DEFAULT_SETTLEMENT_RATIO).divide(PERCENT_DIVISOR)) + val newSettlementAmount = BigDecimal(newPolicyWeightedRatioCan).multiply(KRW_PER_CAN) + .multiply(BigDecimal.ONE.subtract(PAYMENT_FEE_RATE)).divide(PERCENT_DIVISOR) + val settlementAmount = legacySettlementAmount.add(newSettlementAmount) val tax = settlementAmount.multiply(TAX_RATE) val depositAmount = settlementAmount.subtract(tax) val roundedSettlementAmount = settlementAmount.setScale(0, RoundingMode.HALF_UP).toInt() diff --git a/src/test/kotlin/kr/co/vividnext/sodalive/admin/partner/agent/read/AdminAgentReadCurrentMonthListSummaryTest.kt b/src/test/kotlin/kr/co/vividnext/sodalive/admin/partner/agent/read/AdminAgentReadCurrentMonthListSummaryTest.kt index 680fb90f..90fbf7bc 100644 --- a/src/test/kotlin/kr/co/vividnext/sodalive/admin/partner/agent/read/AdminAgentReadCurrentMonthListSummaryTest.kt +++ b/src/test/kotlin/kr/co/vividnext/sodalive/admin/partner/agent/read/AdminAgentReadCurrentMonthListSummaryTest.kt @@ -29,6 +29,8 @@ import kr.co.vividnext.sodalive.partner.agent.assignment.AgentCreatorRelationRep import kr.co.vividnext.sodalive.partner.agent.calculate.AgentCalculateQueryRepository import kr.co.vividnext.sodalive.partner.agent.calculate.AgentCalculateService import kr.co.vividnext.sodalive.partner.agent.settlement.snapshot.AgentSettlementSnapshotRepository +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 @@ -65,7 +67,14 @@ class AdminAgentReadCurrentMonthListSummaryTest @Autowired constructor( @BeforeEach fun setup() { - val calculateQueryRepository = AgentCalculateQueryRepository(queryFactory, entityManager, cloudFrontHost) + val policy = CountrySettlementPolicy() + val calculateQueryRepository = AgentCalculateQueryRepository( + queryFactory, + entityManager, + cloudFrontHost, + CountrySettlementExpressions(policy), + policy + ) repository = AdminAgentReadQueryRepository(queryFactory, calculateQueryRepository) calculateService = AgentCalculateService(calculateQueryRepository, snapshotRepository) registerMysqlDateFunctions() diff --git a/src/test/kotlin/kr/co/vividnext/sodalive/admin/partner/agent/read/AdminAgentReadParityTest.kt b/src/test/kotlin/kr/co/vividnext/sodalive/admin/partner/agent/read/AdminAgentReadParityTest.kt index cb00e507..6f9acaee 100644 --- a/src/test/kotlin/kr/co/vividnext/sodalive/admin/partner/agent/read/AdminAgentReadParityTest.kt +++ b/src/test/kotlin/kr/co/vividnext/sodalive/admin/partner/agent/read/AdminAgentReadParityTest.kt @@ -29,6 +29,8 @@ import kr.co.vividnext.sodalive.partner.agent.assignment.AgentCreatorRelationRep import kr.co.vividnext.sodalive.partner.agent.calculate.AgentCalculateQueryRepository import kr.co.vividnext.sodalive.partner.agent.calculate.AgentCalculateService import kr.co.vividnext.sodalive.partner.agent.settlement.snapshot.AgentSettlementSnapshotRepository +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 @@ -64,7 +66,14 @@ class AdminAgentReadParityTest @Autowired constructor( @BeforeEach fun setup() { registerMysqlDateFunctions() - val queryRepository = AgentCalculateQueryRepository(queryFactory, entityManager, cloudFrontHost) + val policy = CountrySettlementPolicy() + val queryRepository = AgentCalculateQueryRepository( + queryFactory, + entityManager, + cloudFrontHost, + CountrySettlementExpressions(policy), + policy + ) val adminQueryRepository = AdminAgentReadQueryRepository(queryFactory, queryRepository) agentService = AgentCalculateService(queryRepository, snapshotRepository) adminService = AdminAgentReadService(adminQueryRepository, memberRepository, agentService) diff --git a/src/test/kotlin/kr/co/vividnext/sodalive/admin/partner/agent/read/AdminAgentReadQueryRepositoryTest.kt b/src/test/kotlin/kr/co/vividnext/sodalive/admin/partner/agent/read/AdminAgentReadQueryRepositoryTest.kt index e05de78d..14f6c3c2 100644 --- a/src/test/kotlin/kr/co/vividnext/sodalive/admin/partner/agent/read/AdminAgentReadQueryRepositoryTest.kt +++ b/src/test/kotlin/kr/co/vividnext/sodalive/admin/partner/agent/read/AdminAgentReadQueryRepositoryTest.kt @@ -8,6 +8,8 @@ import kr.co.vividnext.sodalive.member.MemberRole import kr.co.vividnext.sodalive.partner.agent.assignment.AgentCreatorRelation import kr.co.vividnext.sodalive.partner.agent.assignment.AgentCreatorRelationRepository import kr.co.vividnext.sodalive.partner.agent.calculate.AgentCalculateQueryRepository +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 @@ -34,9 +36,16 @@ class AdminAgentReadQueryRepositoryTest @Autowired constructor( @BeforeEach fun setup() { + val policy = CountrySettlementPolicy() repository = AdminAgentReadQueryRepository( queryFactory, - AgentCalculateQueryRepository(queryFactory, entityManager, cloudFrontHost) + AgentCalculateQueryRepository( + queryFactory, + entityManager, + cloudFrontHost, + CountrySettlementExpressions(policy), + policy + ) ) } diff --git a/src/test/kotlin/kr/co/vividnext/sodalive/partner/agent/calculate/AgentCalculateQueryRepositoryTest.kt b/src/test/kotlin/kr/co/vividnext/sodalive/partner/agent/calculate/AgentCalculateQueryRepositoryTest.kt index d6ec2fea..5f9a7832 100644 --- a/src/test/kotlin/kr/co/vividnext/sodalive/partner/agent/calculate/AgentCalculateQueryRepositoryTest.kt +++ b/src/test/kotlin/kr/co/vividnext/sodalive/partner/agent/calculate/AgentCalculateQueryRepositoryTest.kt @@ -29,10 +29,18 @@ import kr.co.vividnext.sodalive.partner.agent.assignment.AgentCreatorRelationRep import kr.co.vividnext.sodalive.partner.agent.ratio.AgentSettlementRatio import kr.co.vividnext.sodalive.partner.agent.ratio.AgentSettlementRatioRepository import kr.co.vividnext.sodalive.partner.agent.settlement.snapshot.AgentSettlementSnapshotRepository +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.api.function.Executable +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.Arguments +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 @@ -64,7 +72,14 @@ class AgentCalculateQueryRepositoryTest @Autowired constructor( @BeforeEach fun setup() { registerMysqlDateFunctions() - repository = AgentCalculateQueryRepository(queryFactory, entityManager, cloudFrontHost) + val policy = CountrySettlementPolicy() + repository = AgentCalculateQueryRepository( + queryFactory, + entityManager, + cloudFrontHost, + CountrySettlementExpressions(policy), + policy + ) service = AgentCalculateService(repository, snapshotRepository) } @@ -755,6 +770,421 @@ class AgentCalculateQueryRepositoryTest @Autowired constructor( assertEquals(zeroTotal, repository.getCalculateContentDonationByCreatorTotal(startDate, endDate, agent.id!!)) } + @ParameterizedTest + @MethodSource("countryCases") + @DisplayName("다섯 원천의 실제 행과 SQL total은 시행일부터 국가 비율과 반올림 후 기본 agent 7퍼센트를 적용한다") + fun shouldApplyCountryPolicyToRowsAndNativeTotals(case: CountryCase) { + val agent = saveMember("agent-country", MemberRole.AGENT) + val creator = saveMember("creator-country", MemberRole.CREATOR) + creator.countryCode = case.creatorCountry + saveRelation(agent, creator) + case.individualRatio?.let { saveCreatorSettlementRatio(creator, it, it, it) } + seedCountrySources(creator, case.transactionCountry, countryBoundary) + + assertCountryResults(agent.id!!, case.expected, case.expected.toChannelTotal()) + } + + @ParameterizedTest + @ValueSource(strings = ["2026-10-31T15:00:00", "2026-12-31T15:00:00"]) + @DisplayName("시행 시작과 한국 기본 비율 종료에도 같은 국가의 라이브 콘텐츠 커뮤니티는 개별 비율을 우선한다") + fun shouldKeepIndividualRatioForSameCountryAfterEffectiveAt(eventAtStr: String) { + val agent = saveMember("agent-country-individual", MemberRole.AGENT) + val creator = saveMember("creator-country-individual", MemberRole.CREATOR) + val eventAt = LocalDateTime.parse(eventAtStr) + creator.countryCode = "KR" + saveRelation(agent, creator) + saveCreatorSettlementRatio(creator, 90, 90, 90) + seedCountrySources(creator, "KR", eventAt) + val actual = countryRows(agent.id!!, eventAt, eventAt).take(3).map { it.toResponseTotal() } + + countryNativeTotals(agent.id!!, eventAt, eventAt).take(3) + val expected = GetAgentSettlementByCreatorTotal(1, 13, 1_300, 86, 1_093, 36, 1_057, 77) + + assertAll(actual.map { total -> Executable { assertEquals(expected, total) } }) + } + + @Test + @DisplayName("시행 직전 거래는 다른 국가여도 기존 개별 비율과 후원 70 및 채널 85퍼센트를 유지한다") + fun shouldKeepLegacyCountryAmountsImmediatelyBeforeEffectiveAt() { + val agent = saveMember("agent-country-legacy", MemberRole.AGENT) + val creator = saveMember("creator-country-legacy", MemberRole.CREATOR) + creator.countryCode = "KR" + saveRelation(agent, creator) + saveCreatorSettlementRatio(creator, 90, 90, 90) + seedCountrySources(creator, "JP", countryBoundary.minusSeconds(1)) + + val rows = countryRows(agent.id!!) + val totals = countryNativeTotals(agent.id!!) + val legacy = GetAgentSettlementByCreatorTotal(1, 13, 1_300, 86, 1_093, 36, 1_057, 77) + val donation = GetAgentSettlementByCreatorTotal(1, 13, 1_300, 86, 850, 28, 822, 60) + val channel = GetAgentChannelDonationSettlementTotal(1, 13, 1_300, 86, 1_032, 34, 998, 72) + + assertAll( + (rows.map { it.toResponseTotal() } + totals).mapIndexed { index, actual -> + Executable { assertEquals(if (index % 4 == 3) donation else legacy, actual, "generic $index") } + } + listOf( + Executable { + assertEquals( + channel, + repository.getChannelDonationByCreator(countryStart, countryEnd, agent.id!!) + .toMergedResponseItems().toResponseTotal() + ) + }, + Executable { + assertEquals(channel, repository.getChannelDonationByCreatorTotal(countryStart, countryEnd, agent.id!!)) + } + ) + ) + } + + @Test + @DisplayName("한 agent 원천 그룹의 시행 전후 거래는 행을 늘리지 않고 채널 85와 75를 가중 집계한다") + fun shouldKeepOneSourceGroupForMixedLegacyAndCountryEvents() { + val agent = saveMember("agent-country-mixed", MemberRole.AGENT) + val creator = saveMember("creator-country-mixed", MemberRole.CREATOR) + creator.countryCode = "KR" + saveRelation(agent, creator) + seedCountrySources(creator, "KR", countryBoundary.minusSeconds(1)) + seedCountrySources(creator, "KR", countryBoundary) + + assertEquals(listOf(1, 1, 1, 1), countryRows(agent.id!!).map { it.size }) + assertEquals(1, repository.getChannelDonationByCreator(countryStart, countryEnd, agent.id!!).size) + assertCountryResults( + agent.id!!, + GetAgentSettlementByCreatorTotal(2, 26, 2_600, 172, 1_761, 58, 1_702, 123), + GetAgentChannelDonationSettlementTotal(2, 26, 2_600, 172, 1_942, 64, 1_878, 136) + ) + } + + @ParameterizedTest + @MethodSource("yearEndCases") + @DisplayName("연말 마지막 마이크로초 75와 새해 시작 70은 같은 소속 그룹에서 행과 건수를 유지하며 집계한다") + fun shouldApplyYearEndRatesToRowsAndNativeTotals( + eventAts: List, + case: CountryCase, + expectedChannel: GetAgentChannelDonationSettlementTotal + ) { + val agent = saveMember("agent-year-end", MemberRole.AGENT) + val creator = saveMember("creator-year-end", MemberRole.CREATOR) + creator.countryCode = case.creatorCountry + saveRelation(agent, creator) + case.individualRatio?.let { saveCreatorSettlementRatio(creator, it, it, it) } + eventAts.forEach { seedCountrySources(creator, case.transactionCountry, it) } + val start = LocalDateTime.of(2026, 12, 31, 14, 59, 59, 999_999_000) + val end = LocalDateTime.of(2026, 12, 31, 15, 0) + + val rows = countryRows(agent.id!!, start, end) + val nativeTotals = countryNativeTotals(agent.id!!, start, end) + val channelRows = repository.getChannelDonationByCreator(start, end, agent.id!!) + val channelTotal = repository.getChannelDonationByCreatorTotal(start, end, agent.id!!) + val creatorCounts = listOf( + repository.getCalculateLiveByCreatorTotalCount(start, end, agent.id!!), + repository.getCalculateContentByCreatorTotalCount(start, end, agent.id!!), + repository.getCalculateCommunityByCreatorTotalCount(start, end, agent.id!!), + repository.getCalculateContentDonationByCreatorTotalCount(start, end, agent.id!!), + repository.getChannelDonationByCreatorTotalCount(start, end, agent.id!!) + ) + + assertEquals(listOf(1, 1, 1, 1, 1), creatorCounts) + assertEquals(listOf(1, 1, 1, 1), rows.map { it.size }) + assertEquals(1, channelRows.size) + val assignmentId = relationRepository.findAllByCreatorIdOrderByAssignedAtAsc(creator.id!!).single().id + rows.forEach { assertEquals(listOf(assignmentId), it.map { row -> row.assignmentId }) } + assertEquals(listOf(assignmentId), channelRows.map { it.assignmentId }) + assertAll( + (rows.map { it.toResponseTotal() } + nativeTotals).mapIndexed { index, actual -> + Executable { assertEquals(case.expected, actual, "generic rows 0..3 / native 4..7: $index") } + } + listOf( + Executable { + assertEquals(expectedChannel, channelRows.toMergedResponseItems().toResponseTotal(), "channel rows") + }, + Executable { assertEquals(expectedChannel, channelTotal, "channel native") } + ) + ) + } + + @Test + @DisplayName("채널 혼합 2캔 그룹은 PG를 먼저 반올림하고 국가 가중 정산액에 agent 몫을 적용한다") + fun shouldRoundMixedTwoCanChannelGroupBeforeAgentCut() { + val agent = saveMember("agent-country-two-can", MemberRole.AGENT) + val creator = saveMember("creator-country-two-can", MemberRole.CREATOR) + val sender = saveMember("sender-country-two-can", MemberRole.USER) + creator.countryCode = "KR" + saveRelation(agent, creator) + listOf(countryBoundary.minusSeconds(1), countryBoundary).forEach { eventAt -> + val donation = saveChannelDonationUseCan(sender, 1, eventAt) + saveUseCanCalculate(donation, creator.id!!, 1, PaymentGateway.PG) + } + + val rows = repository.getChannelDonationByCreator(countryStart, countryEnd, agent.id!!) + val total = repository.getChannelDonationByCreatorTotal(countryStart, countryEnd, agent.id!!) + val expected = GetAgentChannelDonationSettlementTotal(2, 2, 200, 13, 150, 5, 145, 11) + + assertEquals(1, rows.size) + assertAll( + { assertEquals(expected, rows.toMergedResponseItems().toResponseTotal()) }, + { assertEquals(expected, total) } + ) + } + + @Test + @DisplayName("콘텐츠 판매는 Order 시각과 연결 UseCan 국가를 사용하고 콘텐츠 비율보다 다른 국가 50을 우선한다") + fun shouldApplyContentOverrideAndCrossCountryRatioWithoutLosingUnlinkedOrders() { + val agent = saveMember("agent-country-content", MemberRole.AGENT) + val creator = saveMember("creator-country-content", MemberRole.CREATOR) + val buyer = saveMember("buyer-country-content", MemberRole.USER) + creator.countryCode = "KR" + saveRelation(agent, creator) + saveCreatorSettlementRatio(creator, 60, 60, 60) + val content = saveAudioContent(creator, "country-content", 13, 80) + listOf("KR", "JP", null).forEach { country -> + val order = saveOrder(buyer, creator, content, countryBoundary) + if (country != null) { + val useCan = useCanRepository.saveAndFlush( + UseCan(CanUsage.ORDER_CONTENT, 13, 0, countryCode = country).also { + it.member = buyer + it.order = order + } + ) + updateUseCanCreatedAt(useCan.id!!, countryBoundary.minusSeconds(1)) + } + } + + val rows = repository.getCalculateContentByCreator(countryStart, countryEnd, agent.id!!) + val total = repository.getCalculateContentByCreatorTotal(countryStart, countryEnd, agent.id!!) + val expected = GetAgentSettlementByCreatorTotal(3, 39, 3_900, 257, 2_550, 84, 2_466, 179) + + assertEquals(1, rows.size) + assertEquals(1, repository.getCalculateContentByCreatorTotalCount(countryStart, countryEnd, agent.id!!)) + assertAll( + { assertEquals(expected, rows.toResponseTotal()) }, + { assertEquals(expected, total) } + ) + } + + @Test + @DisplayName("국가별 정산 total은 creator 페이지 및 빈 페이지와 독립적이며 모든 페이지의 그룹 계산과 같다") + fun shouldKeepCountryNativeTotalsIndependentOfCreatorPages() { + val agent = saveMember("agent-country-pages", MemberRole.AGENT) + val korean = saveMember("creator-country-kr", MemberRole.CREATOR) + val foreign = saveMember("creator-country-jp", MemberRole.CREATOR) + korean.countryCode = "KR" + foreign.countryCode = "JP" + listOf(korean, foreign).forEach { creator -> + saveRelation(agent, creator) + seedCountrySources(creator, creator.countryCode, countryBoundary) + } + val expected = GetAgentSettlementByCreatorTotal(2, 26, 2_600, 172, 1_761, 58, 1_703, 124) + val firstPages = countryPages(agent.id!!, 0) + val secondPages = countryPages(agent.id!!, 1) + val emptyPages = countryPages(agent.id!!, 2) + val rowTotals = countryRows(agent.id!!).map { it.toResponseTotal() } + + firstPages.indices.forEach { index -> + val first = firstPages[index] + val second = secondPages[index] + val empty = emptyPages[index] + assertEquals(listOf(2, 2, 2), listOf(first.totalCount, second.totalCount, empty.totalCount)) + assertEquals(listOf(expected, expected, expected), listOf(first.total, second.total, empty.total)) + assertEquals(listOf(foreign.id, korean.id), (first.items + second.items).map { it.creatorId }) + assertEquals(listOf(850, 911), (first.items + second.items).map { it.settlementAmount }) + assertEquals(listOf(60, 64), (first.items + second.items).map { it.agentSettlementAmount }) + assertEquals(emptyList(), empty.items) + assertEquals(expected, rowTotals[index]) + } + val channelPages = (0L..2L).map { service.getChannelDonationByCreator("2026-10-31", "2026-11-01", agent.id!!, it, 1) } + assertEquals(listOf(2, 2, 2), channelPages.map { it.totalCount }) + assertEquals(List(3) { expected.toChannelTotal() }, channelPages.map { it.total }) + assertEquals(listOf(foreign.id, korean.id), channelPages.flatMap { it.items }.map { it.creatorId }) + assertEquals(listOf(850, 911), channelPages.flatMap { it.items }.map { it.settlementAmount }) + assertEquals(listOf(60, 64), channelPages.flatMap { it.items }.map { it.agentSettlementAmount }) + assertEquals( + expected.toChannelTotal(), + repository.getChannelDonationByCreator(countryStart, countryEnd, agent.id!!) + .toMergedResponseItems().toResponseTotal() + ) + } + + @Test + @DisplayName("국가 정책 적용 시에도 소속과 agent 비율 구간의 끝은 배타적이고 새 구간 시작은 포함한다") + fun shouldKeepAssignmentAndAgentRatioEndExclusiveAtCountryBoundary() { + val firstAgent = saveMember("agent-country-history-a", MemberRole.AGENT) + val secondAgent = saveMember("agent-country-history-b", MemberRole.AGENT) + val creator = saveMember("creator-country-history", MemberRole.CREATOR) + saveRelation(firstAgent, creator, countryBoundary.minusSeconds(1), countryBoundary.plusSeconds(1)) + saveRelation(secondAgent, creator, countryBoundary.plusSeconds(1)) + saveAgentSettlementRatio(firstAgent, 10, countryBoundary.minusSeconds(1), countryBoundary) + saveAgentSettlementRatio(firstAgent, 20, countryBoundary, countryBoundary.plusSeconds(1)) + listOf(-2L, -1L, 0L, 1L).forEach { seedCountrySources(creator, null, countryBoundary.plusSeconds(it)) } + + val rows = countryRows(firstAgent.id!!) + val ratios = agentSettlementRatioRepository.findAllByMemberIdOrderByEffectiveFromAsc(firstAgent.id!!) + rows.forEach { sourceRows -> + assertEquals( + ratios.mapNotNull { it.id }.sorted(), + sourceRows.mapNotNull { it.agentSettlementRatioId }.sorted() + ) + } + assertCountryResults( + firstAgent.id!!, + GetAgentSettlementByCreatorTotal(2, 26, 2_600, 172, 1_761, 58, 1_703, 267), + GetAgentChannelDonationSettlementTotal(2, 26, 2_600, 172, 1_943, 64, 1_879, 285) + ) + assertCountryResults( + secondAgent.id!!, + GetAgentSettlementByCreatorTotal(1, 13, 1_300, 86, 911, 30, 881, 64), + GetAgentChannelDonationSettlementTotal(1, 13, 1_300, 86, 911, 30, 881, 64) + ) + } + + private val countryBoundary = LocalDateTime.of(2026, 10, 31, 15, 0) + private val countryStart = LocalDateTime.of(2026, 10, 31, 0, 0) + private val countryEnd = LocalDateTime.of(2026, 11, 1, 23, 59, 59) + + private fun seedCountrySources(creator: Member, country: String?, eventAt: LocalDateTime) { + val buyer = saveMember("buyer-${creator.id}-$eventAt", MemberRole.USER) + buyer.countryCode = "US" + val room = liveRoomRepository.findAll().firstOrNull { it.member?.id == creator.id } ?: saveLiveRoom(creator) + val content = saveAudioContent(creator, "country-${creator.id}-$eventAt", 13, null) + val post = saveCommunityPost(creator, 13) + val order = saveOrder(buyer, creator, content, eventAt) + val orderUseCan = useCanRepository.saveAndFlush( + UseCan(CanUsage.ORDER_CONTENT, 13, 0, countryCode = country).also { + it.member = buyer + it.order = order + } + ) + val events = listOf( + saveLiveUseCan(buyer, room, 13, eventAt), + saveCommunityUseCan(buyer, post, 13, eventAt), + saveContentDonationUseCan(buyer, content, 13, eventAt), + saveChannelDonationUseCan(buyer, 13, eventAt), + orderUseCan + ) + events.forEach { it.countryCode = country } + // 국가 변경을 먼저 flush해 고정된 거래 시각이 dirty update로 덮어써지지 않게 한다. + entityManager.flush() + events.forEach { updateUseCanCreatedAt(it.id!!, eventAt) } + saveUseCanCalculate(events[3], creator.id!!, 5, PaymentGateway.PG) + saveUseCanCalculate(events[3], creator.id!!, 8, PaymentGateway.GOOGLE_IAP) + } + + private fun countryRows( + agentId: Long, + startDate: LocalDateTime = countryStart, + endDate: LocalDateTime = countryEnd + ) = listOf( + repository.getCalculateLiveByCreator(startDate, endDate, agentId), + repository.getCalculateContentByCreator(startDate, endDate, agentId), + repository.getCalculateCommunityByCreator(startDate, endDate, agentId), + repository.getCalculateContentDonationByCreator(startDate, endDate, agentId) + ) + + private fun countryNativeTotals( + agentId: Long, + startDate: LocalDateTime = countryStart, + endDate: LocalDateTime = countryEnd + ) = listOf( + repository.getCalculateLiveByCreatorTotal(startDate, endDate, agentId), + repository.getCalculateContentByCreatorTotal(startDate, endDate, agentId), + repository.getCalculateCommunityByCreatorTotal(startDate, endDate, agentId), + repository.getCalculateContentDonationByCreatorTotal(startDate, endDate, agentId) + ) + + private fun countryPages(agentId: Long, offset: Long) = listOf( + service.getCalculateLiveByCreator("2026-10-31", "2026-11-01", agentId, offset, 1), + service.getCalculateContentByCreator("2026-10-31", "2026-11-01", agentId, offset, 1), + service.getCalculateCommunityByCreator("2026-10-31", "2026-11-01", agentId, offset, 1), + service.getCalculateContentDonationByCreator("2026-10-31", "2026-11-01", agentId, offset, 1) + ) + + private fun assertCountryResults( + agentId: Long, + expected: GetAgentSettlementByCreatorTotal, + expectedChannel: GetAgentChannelDonationSettlementTotal + ) { + val rowTotals = countryRows(agentId).map { it.toResponseTotal() } + val nativeTotals = countryNativeTotals(agentId) + val channelRows = repository.getChannelDonationByCreator(countryStart, countryEnd, agentId) + .toMergedResponseItems().toResponseTotal() + val channelTotal = repository.getChannelDonationByCreatorTotal(countryStart, countryEnd, agentId) + assertAll( + (rowTotals + nativeTotals).mapIndexed { index, actual -> + Executable { assertEquals(expected, actual, "generic rows 0..3 / native 4..7: $index") } + } + listOf( + Executable { assertEquals(expectedChannel, channelRows, "channel rows") }, + Executable { assertEquals(expectedChannel, channelTotal, "channel native") } + ) + ) + } + + private fun GetAgentSettlementByCreatorTotal.toChannelTotal() = GetAgentChannelDonationSettlementTotal( + count = count, + totalCan = totalCan, + krw = krw, + fee = fee, + settlementAmount = settlementAmount, + withholdingTax = tax, + depositAmount = depositAmount, + agentSettlementAmount = agentSettlementAmount + ) + + data class CountryCase( + val creatorCountry: String?, + val transactionCountry: String?, + val individualRatio: Int?, + val expected: GetAgentSettlementByCreatorTotal + ) + + companion object { + @JvmStatic + fun countryCases() = listOf( + CountryCase("KR", "KR", null, GetAgentSettlementByCreatorTotal(1, 13, 1_300, 86, 911, 30, 881, 64)), + CountryCase("JP", "JP", null, GetAgentSettlementByCreatorTotal(1, 13, 1_300, 86, 850, 28, 822, 60)), + CountryCase("KR", "JP", 90, GetAgentSettlementByCreatorTotal(1, 13, 1_300, 86, 607, 20, 587, 42)), + CountryCase(null, "KR", null, GetAgentSettlementByCreatorTotal(1, 13, 1_300, 86, 911, 30, 881, 64)), + CountryCase("KR", null, null, GetAgentSettlementByCreatorTotal(1, 13, 1_300, 86, 911, 30, 881, 64)), + CountryCase("", " ", null, GetAgentSettlementByCreatorTotal(1, 13, 1_300, 86, 911, 30, 881, 64)) + ) + + @JvmStatic + fun yearEndCases(): List { + val before = LocalDateTime.of(2026, 12, 31, 14, 59, 59, 999_999_000) + val after = LocalDateTime.of(2026, 12, 31, 15, 0) + return listOf( + Arguments.of( + listOf(before), + CountryCase("KR", "KR", null, GetAgentSettlementByCreatorTotal(1, 13, 1_300, 86, 911, 30, 881, 64)), + GetAgentChannelDonationSettlementTotal(1, 13, 1_300, 86, 911, 30, 881, 64) + ), + Arguments.of( + listOf(after), + CountryCase("KR", "KR", null, GetAgentSettlementByCreatorTotal(1, 13, 1_300, 86, 850, 28, 822, 60)), + GetAgentChannelDonationSettlementTotal(1, 13, 1_300, 86, 850, 28, 822, 60) + ), + Arguments.of( + listOf(before, after), + CountryCase("KR", "KR", null, GetAgentSettlementByCreatorTotal(2, 26, 2_600, 172, 1_761, 58, 1_702, 123)), + GetAgentChannelDonationSettlementTotal(2, 26, 2_600, 172, 1_760, 58, 1_702, 123) + ), + Arguments.of( + listOf(after), + CountryCase(null, null, null, GetAgentSettlementByCreatorTotal(1, 13, 1_300, 86, 850, 28, 822, 60)), + GetAgentChannelDonationSettlementTotal(1, 13, 1_300, 86, 850, 28, 822, 60) + ), + Arguments.of( + listOf(after), + CountryCase("JP", "JP", null, GetAgentSettlementByCreatorTotal(1, 13, 1_300, 86, 850, 28, 822, 60)), + GetAgentChannelDonationSettlementTotal(1, 13, 1_300, 86, 850, 28, 822, 60) + ), + Arguments.of( + listOf(after), + CountryCase("KR", "JP", 90, GetAgentSettlementByCreatorTotal(1, 13, 1_300, 86, 607, 20, 587, 42)), + GetAgentChannelDonationSettlementTotal(1, 13, 1_300, 86, 607, 20, 587, 42) + ) + ) + } + } + private fun saveMember(nickname: String, role: MemberRole, profileImage: String? = null): Member { return memberRepository.saveAndFlush( Member( diff --git a/src/test/kotlin/kr/co/vividnext/sodalive/partner/agent/calculate/AgentCountrySettlementSnapshotTest.kt b/src/test/kotlin/kr/co/vividnext/sodalive/partner/agent/calculate/AgentCountrySettlementSnapshotTest.kt new file mode 100644 index 00000000..d14a3381 --- /dev/null +++ b/src/test/kotlin/kr/co/vividnext/sodalive/partner/agent/calculate/AgentCountrySettlementSnapshotTest.kt @@ -0,0 +1,278 @@ +package kr.co.vividnext.sodalive.partner.agent.calculate + +import com.querydsl.jpa.impl.JPAQueryFactory +import kr.co.vividnext.sodalive.admin.partner.agent.settlement.AdminAgentSettlementSnapshotService +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.live.room.LiveRoom +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.partner.agent.assignment.AgentCreatorRelation +import kr.co.vividnext.sodalive.partner.agent.settlement.snapshot.AgentSettlementSnapshot +import kr.co.vividnext.sodalive.partner.agent.settlement.snapshot.AgentSettlementSnapshotRepository +import kr.co.vividnext.sodalive.partner.agent.settlement.snapshot.AgentSettlementSnapshotSourceDetailRepository +import kr.co.vividnext.sodalive.partner.agent.settlement.snapshot.AgentSettlementSnapshotType +import kr.co.vividnext.sodalive.partner.agent.settlement.snapshot.FinalizeAgentSettlementSnapshotRequest +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.params.ParameterizedTest +import org.junit.jupiter.params.provider.Arguments +import org.junit.jupiter.params.provider.EnumSource +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.jpa.database-platform=kr.co.vividnext.sodalive.support.H2MySqlFunctionDialect"]) +@Import(QueryDslConfig::class) +class AgentCountrySettlementSnapshotTest @Autowired constructor( + private val queryFactory: JPAQueryFactory, + private val entityManager: EntityManager, + private val memberRepository: MemberRepository, + private val snapshotRepository: AgentSettlementSnapshotRepository, + private val sourceDetailRepository: AgentSettlementSnapshotSourceDetailRepository +) { + private val boundary = LocalDateTime.of(2026, 10, 31, 15, 0) + private lateinit var service: AdminAgentSettlementSnapshotService + private lateinit var calculateService: AgentCalculateService + private lateinit var agent: Member + private lateinit var creator: Member + private lateinit var buyer: Member + private lateinit var assignment: AgentCreatorRelation + + @BeforeEach + fun setup() { + val policy = CountrySettlementPolicy() + val calculateRepository = AgentCalculateQueryRepository( + queryFactory, + entityManager, + "https://cdn.test", + CountrySettlementExpressions(policy), + policy + ) + service = AdminAgentSettlementSnapshotService( + snapshotRepository, + sourceDetailRepository, + calculateRepository, + memberRepository + ) + calculateService = AgentCalculateService(calculateRepository, snapshotRepository) + agent = memberRepository.saveAndFlush(Member(password = "password", nickname = "agent", role = MemberRole.AGENT)) + creator = memberRepository.saveAndFlush(Member(password = "password", nickname = "creator", role = MemberRole.CREATOR)) + buyer = memberRepository.saveAndFlush(Member(password = "password", nickname = "buyer", countryCode = "JP")) + assignment = AgentCreatorRelation().also { + it.agent = agent + it.creator = creator + it.assignedAt = boundary.minusDays(1) + entityManager.persist(it) + } + } + + @ParameterizedTest + @MethodSource("newSnapshotCases") + @DisplayName("신규 agent 확정은 시행일 75와 새해 70을 실제 쿼리에서 받아 source detail과 같은 금액으로 저장한다") + fun shouldFinalizeCountryAmountsThroughExistingQueryPath( + type: AgentSettlementSnapshotType, + eventAt: LocalDateTime, + expected: List + ) { + seedEvent(type, eventAt) + val date = eventAt.plusHours(9).toLocalDate().toString() + val request = request(type, date) + + val result = service.finalizeSnapshots(request, finalizedByMemberId = 99L) + entityManager.flush() + entityManager.clear() + val stored = snapshotRepository.findAll().single() + val detail = sourceDetailRepository.findAll().single() + + assertEquals(false, result.alreadyFinalized) + assertEquals(1, result.finalizedCount) + assertEquals(request.toDateRange(), stored.periodStart to stored.periodEnd) + assertEquals(type, stored.settlementType) + assertEquals(agent.id, stored.agentId) + assertEquals(creator.id, stored.creatorId) + assertEquals(assignment.id, stored.assignmentId) + assertEquals(null, stored.agentSettlementRatioId) + assertEquals(null, stored.appliedAgentSettlementRatio) + assertEquals(99L, stored.finalizedByMemberId) + assertEquals(expected, amounts(stored)) + assertEquals(stored.id, detail.snapshot.id) + assertEquals(assignment.id, detail.assignmentId) + assertEquals(null, detail.agentSettlementRatioId) + assertEquals(null, detail.appliedAgentSettlementRatio) + assertEquals( + expected, + listOf( + detail.count, + detail.totalCan, + detail.krw, + detail.fee, + detail.settlementAmount, + detail.tax, + detail.depositAmount, + detail.agentSettlementAmount + ) + ) + assertEquals(listOf(expected[4], expected[7]), readAmounts(type, date)) + } + + @ParameterizedTest + @EnumSource(value = AgentSettlementSnapshotType::class, names = ["LIVE", "CHANNEL_DONATION"]) + @DisplayName("저장된 agent 확정은 현재 국가 변경 후에도 조회 금액을 보존하며 반복 확정으로 재계산하지 않는다") + fun shouldPreserveSavedSnapshotsAndRejectRepeatedFinalizeAfterCountryChange(type: AgentSettlementSnapshotType) { + seedEvent(type) + val request = request(type) + val (start, end) = request.toDateRange() + val legacyAmount = when (type) { + AgentSettlementSnapshotType.CHANNEL_DONATION -> listOf(1_032, 34, 998, 72) + else -> listOf(850, 28, 822, 60) + } + val saved = snapshotRepository.saveAndFlush( + AgentSettlementSnapshot( + periodStart = start, + periodEnd = end, + settlementType = type, + agentId = agent.id!!, + agentNickname = agent.nickname, + creatorId = creator.id!!, + creatorNickname = creator.nickname, + assignmentId = assignment.id, + count = 1, + totalCan = 13, + krw = 1_300, + fee = 86, + settlementAmount = legacyAmount[0], + tax = legacyAmount[1], + depositAmount = legacyAmount[2], + agentSettlementAmount = legacyAmount[3], + finalizedAt = boundary.plusDays(1), + finalizedByMemberId = 55L + ) + ) + creator.countryCode = "JP" + entityManager.flush() + entityManager.clear() + + val responseAmounts = readAmounts(type) + val first = service.finalizeSnapshots(request, finalizedByMemberId = 99L) + val second = service.finalizeSnapshots(request, finalizedByMemberId = 99L) + entityManager.flush() + entityManager.clear() + val stored = snapshotRepository.findAll().single() + + assertEquals(listOf(legacyAmount[0], legacyAmount[3]), responseAmounts) + assertEquals(listOf(true, true), listOf(first.alreadyFinalized, second.alreadyFinalized)) + assertEquals(listOf(0, 0), listOf(first.finalizedCount, second.finalizedCount)) + assertEquals(saved.id, stored.id) + assertEquals(listOf(1, 13, 1_300, 86) + legacyAmount, amounts(stored)) + assertEquals(55L, stored.finalizedByMemberId) + assertEquals(boundary.plusDays(1), stored.finalizedAt) + assertEquals(0L, sourceDetailRepository.count()) + } + + private fun seedEvent(type: AgentSettlementSnapshotType, eventAt: LocalDateTime = boundary) { + val useCan = UseCan( + canUsage = when (type) { + AgentSettlementSnapshotType.CHANNEL_DONATION -> CanUsage.CHANNEL_DONATION + else -> CanUsage.LIVE + }, + can = 13, + rewardCan = 0 + ) + useCan.member = buyer + if (type == AgentSettlementSnapshotType.LIVE) { + val room = LiveRoom( + title = "country-live", + notice = "notice", + beginDateTime = eventAt, + numberOfPeople = 10, + isAdult = false, + price = 13 + ) + room.member = creator + entityManager.persist(room) + useCan.room = room + } + entityManager.persist(useCan) + if (type == AgentSettlementSnapshotType.CHANNEL_DONATION) { + listOf(PaymentGateway.PG to 5, PaymentGateway.GOOGLE_IAP to 8).forEach { (gateway, can) -> + entityManager.persist( + UseCanCalculate(can, gateway, UseCanCalculateStatus.RECEIVED).also { + it.useCan = useCan + it.recipientCreatorId = creator.id + } + ) + } + } + entityManager.flush() + entityManager.createQuery("update UseCan u set u.createdAt = :at where u.id = :id") + .setParameter("at", eventAt).setParameter("id", useCan.id).executeUpdate() + } + + private fun request(type: AgentSettlementSnapshotType, date: String = "2026-11-01") = FinalizeAgentSettlementSnapshotRequest( + agentId = agent.id!!, + settlementType = type, + startDateStr = date, + endDateStr = date + ) + + private fun amounts(snapshot: AgentSettlementSnapshot) = listOf( + snapshot.count, + snapshot.totalCan, + snapshot.krw, + snapshot.fee, + snapshot.settlementAmount, + snapshot.tax, + snapshot.depositAmount, + snapshot.agentSettlementAmount + ) + + private fun readAmounts(type: AgentSettlementSnapshotType, date: String = "2026-11-01"): List = when (type) { + AgentSettlementSnapshotType.CHANNEL_DONATION -> { + val response = calculateService.getChannelDonationByCreator(date, date, agent.id!!, 0, 10) + assertEquals(1, response.totalCount) + assertEquals(response.total.settlementAmount, response.items.single().settlementAmount) + assertEquals(response.total.agentSettlementAmount, response.items.single().agentSettlementAmount) + listOf(response.total.settlementAmount, response.total.agentSettlementAmount) + } + else -> { + val response = calculateService.getCalculateLiveByCreator(date, date, agent.id!!, 0, 10) + assertEquals(1, response.totalCount) + assertEquals(response.total.settlementAmount, response.items.single().settlementAmount) + assertEquals(response.total.agentSettlementAmount, response.items.single().agentSettlementAmount) + listOf(response.total.settlementAmount, response.total.agentSettlementAmount) + } + } + + companion object { + @JvmStatic + fun newSnapshotCases(): List = listOf( + AgentSettlementSnapshotType.LIVE, + AgentSettlementSnapshotType.CHANNEL_DONATION + ).flatMap { type -> + listOf( + Arguments.of( + type, + LocalDateTime.of(2026, 10, 31, 15, 0), + listOf(1, 13, 1_300, 86, 911, 30, 881, 64) + ), + Arguments.of( + type, + LocalDateTime.of(2026, 12, 31, 15, 0), + listOf(1, 13, 1_300, 86, 850, 28, 822, 60) + ) + ) + } + } +}