diff --git a/src/main/kotlin/kr/co/vividnext/sodalive/v2/api/creator/settlement/adapter/in/web/CreatorMonthlySettlementController.kt b/src/main/kotlin/kr/co/vividnext/sodalive/v2/api/creator/settlement/adapter/in/web/CreatorMonthlySettlementController.kt index c864e756..47965fdd 100644 --- a/src/main/kotlin/kr/co/vividnext/sodalive/v2/api/creator/settlement/adapter/in/web/CreatorMonthlySettlementController.kt +++ b/src/main/kotlin/kr/co/vividnext/sodalive/v2/api/creator/settlement/adapter/in/web/CreatorMonthlySettlementController.kt @@ -4,6 +4,7 @@ import kr.co.vividnext.sodalive.common.ApiResponse import kr.co.vividnext.sodalive.common.SodaException import kr.co.vividnext.sodalive.member.Member import kr.co.vividnext.sodalive.v2.api.creator.settlement.application.CreatorMonthlySettlementService +import kr.co.vividnext.sodalive.v2.api.creator.settlement.dto.GetCreatorMonthlySettlementHistoryResponse import kr.co.vividnext.sodalive.v2.api.creator.settlement.dto.GetCreatorMonthlySettlementResponse import org.springframework.http.CacheControl import org.springframework.http.ResponseEntity @@ -19,6 +20,21 @@ import java.time.YearMonth @PreAuthorize("hasRole('CREATOR')") @RequestMapping("/creator-admin/calculate") class CreatorMonthlySettlementController(private val service: CreatorMonthlySettlementService) { + @GetMapping("/monthly-history") + fun getMonthlyHistory( + @RequestParam(required = false) page: String?, + @RequestParam(required = false) size: String?, + @AuthenticationPrincipal(expression = "#this == 'anonymousUser' ? null : member") member: Member? + ): ResponseEntity> { + val memberId = member?.id ?: throw SodaException(messageKey = "common.error.bad_credentials") + val requestedPage = (page ?: "0").toIntOrNull()?.takeIf { it >= 0 } + ?: throw SodaException(messageKey = "common.error.invalid_request", errorProperty = "page") + val requestedSize = (size ?: "10").toIntOrNull()?.takeIf { it in 1..100 } + ?: throw SodaException(messageKey = "common.error.invalid_request", errorProperty = "size") + val history = service.getMonthlyHistory(memberId, requestedPage, requestedSize) + return ResponseEntity.ok().cacheControl(CacheControl.noStore()).body(ApiResponse.ok(history)) + } + @GetMapping("/monthly-summary") fun getMonthlySummary( @RequestParam month: String, diff --git a/src/main/kotlin/kr/co/vividnext/sodalive/v2/api/creator/settlement/application/CreatorMonthlySettlementService.kt b/src/main/kotlin/kr/co/vividnext/sodalive/v2/api/creator/settlement/application/CreatorMonthlySettlementService.kt index 12f9987f..b2169896 100644 --- a/src/main/kotlin/kr/co/vividnext/sodalive/v2/api/creator/settlement/application/CreatorMonthlySettlementService.kt +++ b/src/main/kotlin/kr/co/vividnext/sodalive/v2/api/creator/settlement/application/CreatorMonthlySettlementService.kt @@ -6,11 +6,14 @@ import kr.co.vividnext.sodalive.creator.admin.calculate.channelDonation.CreatorA import kr.co.vividnext.sodalive.member.MemberRepository import kr.co.vividnext.sodalive.member.MemberRole import kr.co.vividnext.sodalive.v2.api.creator.settlement.dto.CreatorMonthlySettlementAmount +import kr.co.vividnext.sodalive.v2.api.creator.settlement.dto.CreatorMonthlySettlementHistoryItem import kr.co.vividnext.sodalive.v2.api.creator.settlement.dto.CreatorMonthlySettlementRateDetail import kr.co.vividnext.sodalive.v2.api.creator.settlement.dto.CreatorMonthlySettlementSource import kr.co.vividnext.sodalive.v2.api.creator.settlement.dto.CreatorMonthlySettlementSourceAmount +import kr.co.vividnext.sodalive.v2.api.creator.settlement.dto.GetCreatorMonthlySettlementHistoryResponse import kr.co.vividnext.sodalive.v2.api.creator.settlement.dto.GetCreatorMonthlySettlementResponse import kr.co.vividnext.sodalive.v2.settlement.adapter.out.persistence.CanonicalSettlementQueryRepository +import kr.co.vividnext.sodalive.v2.settlement.adapter.out.persistence.CreatorSettlementMonthQueryRepository import kr.co.vividnext.sodalive.v2.settlement.domain.CountrySettlementPolicy import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementAmounts import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementCountryRelation @@ -24,11 +27,13 @@ import org.springframework.data.repository.findByIdOrNull import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Isolation import org.springframework.transaction.annotation.Transactional +import java.time.Clock import java.time.Instant import java.time.LocalDateTime import java.time.YearMonth import java.time.ZoneId import java.time.ZoneOffset +import java.time.temporal.ChronoUnit @Service class CreatorMonthlySettlementService( @@ -36,13 +41,30 @@ class CreatorMonthlySettlementService( private val channelRepository: CreatorAdminChannelDonationCalculateQueryRepository, private val memberRepository: MemberRepository, private val canonicalRepository: CanonicalSettlementQueryRepository, - private val policy: CountrySettlementPolicy + private val policy: CountrySettlementPolicy, + private val monthRepository: CreatorSettlementMonthQueryRepository, + private val clock: Clock = Clock.systemUTC() ) { + @Transactional(readOnly = true, isolation = Isolation.REPEATABLE_READ) + fun getMonthlyHistory(memberId: Long, page: Int, size: Int): GetCreatorMonthlySettlementHistoryResponse { + requireCreator(memberId) + val firstAt = monthRepository.findFirstTransactionAt(memberId) + ?: return GetCreatorMonthlySettlementHistoryResponse(emptyList(), 0L) + val zone = ZoneId.of("Asia/Seoul") + val firstMonth = YearMonth.from(firstAt.atOffset(ZoneOffset.UTC).atZoneSameInstant(zone)) + val currentMonth = YearMonth.now(clock.withZone(zone)) + val totalCount = (ChronoUnit.MONTHS.between(firstMonth, currentMonth) + 1L).coerceAtLeast(0L) + val offset = page.toLong() * size + val count = (totalCount - offset).coerceIn(0L, size.toLong()).toInt() + val items = (0 until count).map { index -> + CreatorMonthlySettlementHistoryItem(getMonthlySummary(memberId, currentMonth.minusMonths(offset + index))) + } + return GetCreatorMonthlySettlementHistoryResponse(items, totalCount) + } + @Transactional(readOnly = true, isolation = Isolation.REPEATABLE_READ) fun getMonthlySummary(memberId: Long, month: YearMonth): GetCreatorMonthlySettlementResponse { - val creator = memberRepository.findByIdOrNull(memberId) - ?: throw SodaException(messageKey = "common.error.bad_credentials") - if (creator.role != MemberRole.CREATOR) throw SodaException(messageKey = "common.error.access_denied") + requireCreator(memberId) val zone = ZoneId.of("Asia/Seoul") val start = month.atDay(1).atStartOfDay(zone).toInstant() @@ -106,12 +128,18 @@ class CreatorMonthlySettlementService( month = month.toString(), periodStartInclusive = start.toString(), periodEndExclusive = end.toString(), - calculatedAt = Instant.now().toString(), + calculatedAt = Instant.now(clock).toString(), total = CreatorMonthlySettlementAmount(total), breakdown = breakdown ) } + private fun requireCreator(memberId: Long) { + val creator = memberRepository.findByIdOrNull(memberId) + ?: throw SodaException(messageKey = "common.error.bad_credentials") + if (creator.role != MemberRole.CREATOR) throw SodaException(messageKey = "common.error.access_denied") + } + private fun legacyAmounts(scope: SettlementScope): SettlementAmounts? { val start = requireNotNull(scope.window.startInclusiveUtc) val end = requireNotNull(scope.window.endUtc) diff --git a/src/main/kotlin/kr/co/vividnext/sodalive/v2/api/creator/settlement/dto/GetCreatorMonthlySettlementHistoryResponse.kt b/src/main/kotlin/kr/co/vividnext/sodalive/v2/api/creator/settlement/dto/GetCreatorMonthlySettlementHistoryResponse.kt new file mode 100644 index 00000000..4eaed281 --- /dev/null +++ b/src/main/kotlin/kr/co/vividnext/sodalive/v2/api/creator/settlement/dto/GetCreatorMonthlySettlementHistoryResponse.kt @@ -0,0 +1,23 @@ +package kr.co.vividnext.sodalive.v2.api.creator.settlement.dto + +import java.time.LocalDate + +data class GetCreatorMonthlySettlementHistoryResponse( + val items: List, + val totalCount: Long +) + +class CreatorMonthlySettlementHistoryItem(summary: GetCreatorMonthlySettlementResponse) { + val month: String = summary.month + val periodStartInclusive: String = summary.periodStartInclusive + val periodEndExclusive: String = summary.periodEndExclusive + val timeZone: String = summary.timeZone + val calculatedAt: String = summary.calculatedAt + val currency: String = summary.currency + val calculationStatus: String = summary.calculationStatus + val hasRevenueData: Boolean = summary.hasRevenueData + val payoutStatus: String = summary.payoutStatus + val plannedPayoutDate: LocalDate? = null + val actualPayoutDate: LocalDate? = null + val total: CreatorMonthlySettlementAmount = summary.total +} diff --git a/src/main/kotlin/kr/co/vividnext/sodalive/v2/settlement/adapter/out/persistence/CreatorSettlementMonthQueryRepository.kt b/src/main/kotlin/kr/co/vividnext/sodalive/v2/settlement/adapter/out/persistence/CreatorSettlementMonthQueryRepository.kt new file mode 100644 index 00000000..a6f789b8 --- /dev/null +++ b/src/main/kotlin/kr/co/vividnext/sodalive/v2/settlement/adapter/out/persistence/CreatorSettlementMonthQueryRepository.kt @@ -0,0 +1,53 @@ +package kr.co.vividnext.sodalive.v2.settlement.adapter.out.persistence + +import com.querydsl.jpa.impl.JPAQueryFactory +import kr.co.vividnext.sodalive.can.use.CanUsage +import kr.co.vividnext.sodalive.can.use.QUseCan.useCan +import kr.co.vividnext.sodalive.can.use.QUseCanCalculate.useCanCalculate +import kr.co.vividnext.sodalive.can.use.UseCanCalculateStatus +import kr.co.vividnext.sodalive.content.QAudioContent.audioContent +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.domain.CountrySettlementPolicy +import org.springframework.stereotype.Repository +import java.time.LocalDateTime + +@Repository +class CreatorSettlementMonthQueryRepository( + private val queryFactory: JPAQueryFactory, + private val policy: CountrySettlementPolicy +) { + fun findFirstTransactionAt(creatorId: Long): LocalDateTime? = listOfNotNull( + queryFactory.select(useCan.createdAt.min()) + .from(useCan).innerJoin(useCan.room, liveRoom).innerJoin(liveRoom.member, member) + .where(member.id.eq(creatorId), useCan.isRefund.isFalse) + .fetchOne(), + queryFactory.select(order.createdAt.min()) + .from(order).innerJoin(order.audioContent, audioContent).innerJoin(audioContent.member, member) + .where( + order.isActive.isTrue, + order.createdAt.lt(policy.effectiveAtUtc).and(order.creator.id.eq(creatorId)) + .or(order.createdAt.goe(policy.effectiveAtUtc).and(member.id.eq(creatorId))) + ) + .fetchOne(), + queryFactory.select(useCan.createdAt.min()) + .from(useCan).innerJoin(useCan.audioContent, audioContent).innerJoin(audioContent.member, member) + .where(member.id.eq(creatorId), useCan.isRefund.isFalse, useCan.canUsage.eq(CanUsage.DONATION)) + .fetchOne(), + queryFactory.select(useCan.createdAt.min()) + .from(useCan).innerJoin(useCan.communityPost, creatorCommunity).innerJoin(creatorCommunity.member, member) + .where(member.id.eq(creatorId), useCan.isRefund.isFalse, useCan.canUsage.eq(CanUsage.PAID_COMMUNITY_POST)) + .fetchOne(), + queryFactory.select(useCan.createdAt.min()) + .from(useCanCalculate).innerJoin(useCanCalculate.useCan, useCan) + .where( + useCanCalculate.recipientCreatorId.eq(creatorId), + useCanCalculate.status.eq(UseCanCalculateStatus.RECEIVED), + useCan.canUsage.eq(CanUsage.CHANNEL_DONATION), + useCan.isRefund.isFalse + ) + .fetchOne() + ).minOrNull() +} diff --git a/src/test/kotlin/kr/co/vividnext/sodalive/v2/api/creator/settlement/CreatorMonthlySettlementHistoryEligibilityHttpIntegrationTest.kt b/src/test/kotlin/kr/co/vividnext/sodalive/v2/api/creator/settlement/CreatorMonthlySettlementHistoryEligibilityHttpIntegrationTest.kt new file mode 100644 index 00000000..cb8a3d2a --- /dev/null +++ b/src/test/kotlin/kr/co/vividnext/sodalive/v2/api/creator/settlement/CreatorMonthlySettlementHistoryEligibilityHttpIntegrationTest.kt @@ -0,0 +1,189 @@ +package kr.co.vividnext.sodalive.v2.api.creator.settlement + +import kr.co.vividnext.sodalive.can.use.CanUsage +import kr.co.vividnext.sodalive.can.use.UseCan +import kr.co.vividnext.sodalive.can.use.UseCanCalculateStatus +import kr.co.vividnext.sodalive.member.Member +import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementSource +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.DisplayName +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.CsvSource +import org.junit.jupiter.params.provider.ValueSource +import java.time.LocalDateTime + +class CreatorMonthlySettlementHistoryEligibilityHttpIntegrationTest : MonthlySettlementHistoryHttpTestSupport() { + @ParameterizedTest + @CsvSource( + "LIVE, 2026-10-01T00:00:00, 2", "LIVE, 2026-10-31T15:00:00, 1", + "CONTENT_SALES, 2026-10-01T00:00:00, 2", "CONTENT_SALES, 2026-10-31T15:00:00, 1", + "CONTENT_DONATION, 2026-10-01T00:00:00, 2", "CONTENT_DONATION, 2026-10-31T15:00:00, 1", + "COMMUNITY_POST, 2026-10-01T00:00:00, 2", "COMMUNITY_POST, 2026-10-31T15:00:00, 1", + "CHANNEL_DONATION, 2026-10-01T00:00:00, 2", "CHANNEL_DONATION, 2026-10-31T15:00:00, 1" + ) + @DisplayName("다섯 원천의 최초 적격 시각은 시행 전후 모두 월 상세와 같은 소유권을 따른다") + fun shouldFindFirstEligibleMonthForEachSource(source: SettlementSource, timestamp: String, count: Long) { + val at = LocalDateTime.parse(timestamp) + val creator = fixture.commit { + val creator = member() + addSource(source, creator, at) + creator + } + + val data = history(creator) + + assertEquals(count, data.path("totalCount").longValue()) + val first = data.path("items").last() + assertEquals(if (count == 2L) "2026-10" else "2026-11", first.path("month").asText()) + assertTrue(first.path("hasRevenueData").booleanValue()) + assertEquals(1L, first.path("total").path("totalCan").longValue()) + assertEquals(summary(creator, first.path("month").asText()).path("total"), first.path("total")) + } + + @ParameterizedTest + @CsvSource( + "2026-10-31T14:59:59, true, 2", + "2026-10-31T14:59:59, false, 0", + "2026-10-31T15:00:00, true, 0", + "2026-10-31T15:00:00, false, 1" + ) + @DisplayName("판매 소유자가 서로 다르면 시행 직전 orders.creator와 시행 후 content.member로 정확히 분기한다") + fun shouldPreserveLegacySalesOwnerMismatch(timestamp: String, queryOrderOwner: Boolean, count: Long) { + val creator = fixture.commit { + val orderOwner = member() + val contentOwner = member() + order(content(contentOwner), 1, LocalDateTime.parse(timestamp)).creator = orderOwner + if (queryOrderOwner) orderOwner else contentOwner + } + + val data = history(creator) + + assertEquals(count, data.path("totalCount").longValue()) + if (count == 0L) { + assertEquals(0, data.path("items").size()) + } else { + val first = data.path("items").last() + assertEquals(1L, first.path("total").path("totalCan").longValue()) + assertEquals(summary(creator, first.path("month").asText()).path("total"), first.path("total")) + } + } + + @ParameterizedTest + @ValueSource(strings = ["2026-10-01T00:00:00", "2026-11-01T00:00:00"]) + @DisplayName("판매는 선택적인 UseCan의 환불·용도·시각에 의해 최초 주문 월을 잃지 않는다") + fun shouldUseOrderEligibilityAndTimestampDespiteAssociatedRefundedUsage(timestamp: String) { + val creator = fixture.commit { + val creator = member() + val order = order(content(creator), 1, LocalDateTime.parse(timestamp)) + usage( + UseCan(CanUsage.DONATION, 999, 0, isRefund = true).apply { this.order = order }, + LocalDateTime.of(2024, 1, 1, 0, 0) + ) + creator + } + + val data = history(creator) + + assertEquals(if (timestamp.startsWith("2026-10")) 2L else 1L, data.path("totalCount").longValue()) + assertEquals(1L, data.path("items").last().path("total").path("totalCan").longValue()) + } + + @ParameterizedTest + @ValueSource( + strings = [ + "live-refund", "live-other", "live-no-room", "sale-inactive", "sale-other", + "donation-refund", "donation-usage", "donation-other", "donation-no-content", + "community-refund", "community-usage", "community-other", "community-no-post", + "channel-refund", "channel-usage", "channel-complete", "channel-status-refund", + "channel-other", "channel-null-recipient", "channel-no-allocation" + ] + ) + @DisplayName("환불·비활성·용도·소유자·연결·채널 상태가 부적격이면 과거 이력이 생기지 않는다") + fun shouldExcludeIneligibleEarlierTransactions(scenario: String) { + val creator = fixture.commit { + val creator = member() + val other = member() + val at = LocalDateTime.of(2026, 4, 1, 0, 0) + when (scenario) { + "live-refund", "live-other", "live-no-room" -> usage( + UseCan(CanUsage.LIVE, 999, 0, isRefund = scenario == "live-refund").apply { + if (scenario != "live-no-room") room = room(if (scenario == "live-other") other else creator) + }, + at + ) + "sale-inactive", "sale-other" -> order(content(if (scenario == "sale-other") other else creator), 999, at) + .apply { isActive = scenario != "sale-inactive" } + "donation-refund", "donation-usage", "donation-other", "donation-no-content" -> usage( + UseCan( + if (scenario == "donation-usage") CanUsage.LIVE else CanUsage.DONATION, + 999, + 0, + isRefund = scenario == "donation-refund" + ).apply { + if (scenario != "donation-no-content") { + audioContent = content(if (scenario == "donation-other") other else creator) + } + }, + at + ) + "community-refund", "community-usage", "community-other", "community-no-post" -> usage( + UseCan( + if (scenario == "community-usage") CanUsage.DONATION else CanUsage.PAID_COMMUNITY_POST, + 999, + 0, + isRefund = scenario == "community-refund" + ).apply { + if (scenario != "community-no-post") { + communityPost = post(if (scenario == "community-other") other else creator) + } + }, + at + ) + "channel-no-allocation" -> usage(UseCan(CanUsage.CHANNEL_DONATION, 999, 0), at) + else -> channelDonation( + if (scenario == "channel-other") other else creator, + UseCan( + if (scenario == "channel-usage") CanUsage.DONATION else CanUsage.CHANNEL_DONATION, + 999, + 0, + isRefund = scenario == "channel-refund" + ), + at + ).apply { + status = when (scenario) { + "channel-complete" -> UseCanCalculateStatus.CALCULATE_COMPLETE + "channel-status-refund" -> UseCanCalculateStatus.REFUND + else -> UseCanCalculateStatus.RECEIVED + } + if (scenario == "channel-null-recipient") recipientCreatorId = null + } + } + channelDonation(creator, 1, LocalDateTime.of(2026, 11, 1, 0, 0)).createdAt = LocalDateTime.of(2020, 1, 1, 0, 0) + creator + } + + val data = history(creator) + + assertEquals(1L, data.path("totalCount").longValue(), scenario) + assertEquals(listOf("2026-11"), data.path("items").map { it.path("month").asText() }) + http.amount(data.path("items").single().path("total"), listOf(1L, 100L, 7L, 23L, 70L, 2L, 68L)) + } + + private fun addSource(source: SettlementSource, creator: Member, at: LocalDateTime) = with(fixture) { + when (source) { + SettlementSource.LIVE -> usage(UseCan(CanUsage.DONATION, 1, 0).apply { room = room(creator) }, at) + SettlementSource.CONTENT_SALES -> order(content(creator), 1, at) + SettlementSource.CONTENT_DONATION -> usage( + UseCan(CanUsage.DONATION, 1, 0).apply { audioContent = content(creator) }, + at + ) + SettlementSource.COMMUNITY_POST -> usage( + UseCan(CanUsage.PAID_COMMUNITY_POST, 1, 0).apply { communityPost = post(creator) }, + at + ) + SettlementSource.CHANNEL_DONATION -> channelDonation(creator, 1, at) + } + Unit + } +} diff --git a/src/test/kotlin/kr/co/vividnext/sodalive/v2/api/creator/settlement/CreatorMonthlySettlementHistoryHttpIntegrationTest.kt b/src/test/kotlin/kr/co/vividnext/sodalive/v2/api/creator/settlement/CreatorMonthlySettlementHistoryHttpIntegrationTest.kt new file mode 100644 index 00000000..448384c0 --- /dev/null +++ b/src/test/kotlin/kr/co/vividnext/sodalive/v2/api/creator/settlement/CreatorMonthlySettlementHistoryHttpIntegrationTest.kt @@ -0,0 +1,204 @@ +package kr.co.vividnext.sodalive.v2.api.creator.settlement + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.DisplayName +import org.junit.jupiter.api.Test +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.CsvSource +import java.time.LocalDateTime +import java.time.YearMonth + +class CreatorMonthlySettlementHistoryHttpIntegrationTest : MonthlySettlementHistoryHttpTestSupport() { + @Test + @DisplayName("등록된 크리에이터는 실제 첫 거래 월부터 기본 이력 페이지를 조회한다") + fun shouldReturnDefaultHistoryPageFromPersistedTransactionsThroughHttp() { + val creator = fixture.commit { + val creator = member() + order(content(creator), 1, LocalDateTime.of(2026, 10, 31, 15, 0)) + creator + } + + val data = history(creator) + + assertEquals(1L, data.path("totalCount").longValue()) + assertEquals(listOf("2026-11"), data.path("items").map { it.path("month").asText() }) + http.amount(data.path("items").single().path("total"), listOf(1L, 100L, 7L, 23L, 70L, 2L, 68L)) + } + + @Test + @DisplayName("적격 거래가 없으면 0개월의 빈 이력을 반환한다") + fun shouldReturnEmptyHistoryWithoutTransactions() { + val creator = fixture.commit { member() } + + val data = history(creator) + + assertEquals(0L, data.path("totalCount").longValue()) + assertEquals(emptyList(), data.path("items").map { it.path("month").asText() }) + } + + @ParameterizedTest + @CsvSource("2026-11-30T15:00:00", "2027-01-01T00:00:00") + @DisplayName("최초 거래가 미래 KST 월에만 있으면 빈 이력이다") + fun shouldReturnEmptyHistoryWhenFirstTransactionIsInAFutureMonth(at: String) { + val creator = fixture.commit { + val creator = member() + order(content(creator), 1, LocalDateTime.parse(at)) + creator + } + + val data = history(creator) + + assertEquals(0L, data.path("totalCount").longValue()) + assertEquals(0, data.path("items").size()) + } + + @ParameterizedTest + @CsvSource("2026-02, 10", "2026-01, 11", "2025-10, 14") + @DisplayName("기본 페이지는 거래 없는 달까지 전체 개월 수를 유지하며 최근 열 달만 반환한다") + fun shouldPageTenMonthsIncludingEmptyInterveningMonths(first: String, count: Long) { + val creator = fixture.commit { + val creator = member() + order(content(creator), 1, YearMonth.parse(first).atDay(1).atTime(0, 0)) + creator + } + + val data = history(creator) + + assertEquals(count, data.path("totalCount").longValue()) + assertEquals( + listOf("2026-11", "2026-10", "2026-09", "2026-08", "2026-07", "2026-06", "2026-05", "2026-04", "2026-03", "2026-02"), + data.path("items").map { it.path("month").asText() } + ) + } + + @ParameterizedTest + @CsvSource("1, 10, 1", "2, 10, 0", "2147483647, 100, 0", "0, 100, 11") + @DisplayName("마지막·범위 밖·최대 page와 size는 전체 월 수를 보존하고 오버플로하지 않는다") + fun shouldKeepStableCountForFinalOutOfRangeAndHugePages(page: Int, size: Int, itemCount: Int) { + val creator = fixture.commit { + val creator = member() + order(content(creator), 1, LocalDateTime.of(2026, 1, 1, 0, 0)) + creator + } + + val data = history(creator, "?page=$page&size=$size") + + assertEquals(11L, data.path("totalCount").longValue()) + assertEquals(itemCount, data.path("items").size()) + if (page == 1) assertEquals("2026-01", data.path("items").single().path("month").asText()) + assertEquals(itemCount, data.path("items").map { it.path("month").asText() }.toSet().size) + } + + @Test + @DisplayName("같은 거래 데이터의 두 페이지를 연결하면 복수 원천·거래에도 열한 달이 중복·누락 없이 이어진다") + fun shouldTraverseElevenMonthsAcrossPagesForTheSamePersistedTransactions() { + val creator = fixture.commit { + val creator = member() + val content = content(creator) + val at = LocalDateTime.of(2026, 1, 1, 0, 0) + order(content, 1, at) + order(content, 2, at.plusDays(1)) + channelDonation(creator, 3, at) + allSources(creator) + creator + } + + val firstPage = history(creator, "?page=0&size=10") + val finalPage = history(creator, "?page=1&size=10") + + assertEquals(11L, firstPage.path("totalCount").longValue()) + assertEquals(11L, finalPage.path("totalCount").longValue()) + assertEquals(10, firstPage.path("items").size()) + assertEquals(1, finalPage.path("items").size()) + val months = (firstPage.path("items").toList() + finalPage.path("items").toList()) + .map { it.path("month").asText() } + assertEquals( + listOf( + "2026-11", + "2026-10", + "2026-09", + "2026-08", + "2026-07", + "2026-06", + "2026-05", + "2026-04", + "2026-03", + "2026-02", + "2026-01" + ), + months + ) + assertEquals(11, months.toSet().size) + } + + @Test + @DisplayName("과거·빈 중간 달·현재 월의 이력은 상세 금액과 같으며 이번 달 전체 창을 사용한다") + fun shouldReuseSummaryTotalsAndFullCurrentMonthWithoutInventingPayoutDates() { + val creator = fixture.commit { + val creator = member() + val content = content(creator) + order(content, 1, LocalDateTime.of(2026, 9, 15, 0, 0)) + allSources(creator) + order(content, 1, LocalDateTime.of(2026, 11, 30, 14, 59, 59)) + creator + } + + val data = history(creator, "?size=3") + + assertEquals(3L, data.path("totalCount").longValue()) + assertEquals(listOf("2026-11", "2026-10", "2026-09"), data.path("items").map { it.path("month").asText() }) + data.path("items").forEach { item -> + val detail = summary(creator, item.path("month").asText()) + listOf("total", "periodStartInclusive", "periodEndExclusive", "hasRevenueData").forEach { + assertEquals(detail.path(it), item.path(it), it) + } + } + http.amount(data.path("items")[0].path("total"), listOf(18L, 1800L, 120L, 420L, 1260L, 41L, 1220L)) + http.amount(data.path("items")[1].path("total"), List(7) { 0L }) + http.amount(data.path("items")[2].path("total"), listOf(1L, 100L, 7L, 28L, 65L, 2L, 63L)) + assertFalse(data.path("items")[1].path("hasRevenueData").booleanValue()) + } + + @Test + @DisplayName("현재 KST 첫날의 0원 거래도 이력 한 행과 거래 존재 true로 구분한다") + fun shouldIncludeZeroValueTransactionAtTheKstCurrentMonthBoundary() { + val creator = fixture.commit { + val creator = member() + order(content(creator), 0, LocalDateTime.of(2026, 10, 31, 15, 0)) + creator + } + + val data = history(creator, "?size=1") + + assertEquals(1L, data.path("totalCount").longValue()) + val item = data.path("items").single() + assertEquals("2026-11", item.path("month").asText()) + assertTrue(item.path("hasRevenueData").booleanValue()) + assertEquals("2026-10-31T15:00:00Z", item.path("periodStartInclusive").asText()) + assertEquals("2026-11-30T15:00:00Z", item.path("periodEndExclusive").asText()) + http.amount(item.path("total"), List(7) { 0L }) + } + + @Test + @DisplayName("윤년 2월의 KST 시작 직전과 시작 거래는 서로 다른 최초 월과 페이지가 된다") + fun shouldKeepLeapMonthAndKstBoundaryMonthsDistinct() { + val creator = fixture.commit { + val creator = member() + val content = content(creator) + order(content, 1, LocalDateTime.of(2024, 1, 31, 14, 59, 59)) + order(content, 1, LocalDateTime.of(2024, 1, 31, 15, 0)) + creator + } + + val data = history(creator, "?page=16&size=2") + + assertEquals(35L, data.path("totalCount").longValue()) + assertEquals(listOf("2024-03", "2024-02"), data.path("items").map { it.path("month").asText() }) + val leap = data.path("items")[1] + assertEquals("2024-01-31T15:00:00Z", leap.path("periodStartInclusive").asText()) + assertEquals("2024-02-29T15:00:00Z", leap.path("periodEndExclusive").asText()) + http.amount(leap.path("total"), listOf(1L, 100L, 7L, 28L, 65L, 2L, 63L)) + } +} diff --git a/src/test/kotlin/kr/co/vividnext/sodalive/v2/api/creator/settlement/CreatorMonthlySettlementHistorySecurityHttpIntegrationTest.kt b/src/test/kotlin/kr/co/vividnext/sodalive/v2/api/creator/settlement/CreatorMonthlySettlementHistorySecurityHttpIntegrationTest.kt new file mode 100644 index 00000000..53060d02 --- /dev/null +++ b/src/test/kotlin/kr/co/vividnext/sodalive/v2/api/creator/settlement/CreatorMonthlySettlementHistorySecurityHttpIntegrationTest.kt @@ -0,0 +1,86 @@ +package kr.co.vividnext.sodalive.v2.api.creator.settlement + +import kr.co.vividnext.sodalive.common.SodaException +import kr.co.vividnext.sodalive.member.MemberRole +import kr.co.vividnext.sodalive.v2.api.creator.settlement.application.CreatorMonthlySettlementService +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.DisplayName +import org.junit.jupiter.api.Test +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.CsvSource +import org.junit.jupiter.params.provider.EnumSource +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.http.HttpStatus +import java.time.LocalDateTime + +class CreatorMonthlySettlementHistorySecurityHttpIntegrationTest : MonthlySettlementHistoryHttpTestSupport() { + @Autowired private lateinit var service: CreatorMonthlySettlementService + + @Test + @DisplayName("익명 이력 요청은 실제 보안 체인에서 401로 거부한다") + fun shouldRejectAnonymousHistoryRequest() { + val response = http.get(null, "/creator-admin/calculate/monthly-history") + + println("HISTORY HTTP EVIDENCE anonymous status=${response.statusCodeValue} body=${response.body}") + assertEquals(HttpStatus.UNAUTHORIZED, response.statusCode) + } + + @ParameterizedTest + @EnumSource(value = MemberRole::class, names = ["USER", "ADMIN", "AGENT"]) + @DisplayName("거래가 없어도 USER·ADMIN·AGENT의 등록 토큰은 이력을 조회하지 못한다") + fun shouldRejectNonCreatorsEvenWithoutHistory(role: MemberRole) { + val actor = fixture.commit { member(role) } + + val response = http.get(actor, "/creator-admin/calculate/monthly-history") + + println("HISTORY HTTP EVIDENCE role=$role status=${response.statusCodeValue} body=${response.body}") + http.failure(response) + } + + @ParameterizedTest + @EnumSource(value = MemberRole::class, names = ["USER", "ADMIN", "AGENT"]) + @DisplayName("서비스도 빈 이력을 조기 반환하기 전에 크리에이터 권한을 검사한다") + fun shouldEnforceCreatorRoleBeforeServiceReturnsEmptyHistory(role: MemberRole) { + val actor = fixture.commit { member(role) } + + val exception = assertThrows(SodaException::class.java) { + service.getMonthlyHistory(requireNotNull(actor.id), 0, 10) + } + + assertEquals("common.error.access_denied", exception.messageKey) + } + + @Test + @DisplayName("타인 ID·월·sort 주입은 본인의 월 범위와 역순 정렬을 바꾸지 못한다") + fun shouldIgnoreInjectedIdsMonthAndSort() { + val (creator, other) = fixture.commit { + val creator = member() + order(content(creator), 1, LocalDateTime.of(2026, 10, 1, 0, 0)) + val other = member() + order(content(other), 999, LocalDateTime.of(2024, 1, 1, 0, 0)) + creator to other + } + + val data = history(creator, "?creatorId=${other.id}&memberId=${other.id}&userId=${other.id}&month=2024-01&sort=month,asc") + + assertEquals(2L, data.path("totalCount").longValue()) + assertEquals(listOf("2026-11", "2026-10"), data.path("items").map { it.path("month").asText() }) + assertEquals(listOf(0L, 1L), data.path("items").map { it.path("total").path("totalCan").longValue() }) + } + + @ParameterizedTest + @CsvSource( + "page, -1", "page, 1.5", "page, bad", "page, 2147483648", "page, -2147483649", "page, ''", + "size, 0", "size, -1", "size, 101", "size, 1.5", "size, bad", "size, 2147483648", "size, -2147483649", "size, ''" + ) + @DisplayName("페이지·크기의 형식·Int 범위·허용 범위 오류는 해당 errorProperty로 반환한다") + fun shouldRejectInvalidNumericInputWithItsProperty(property: String, value: String) { + val creator = fixture.commit { member() } + + val response = http.get(creator, "/creator-admin/calculate/monthly-history?$property=$value") + + println("HISTORY HTTP EVIDENCE invalid=$property:$value status=${response.statusCodeValue} body=${response.body}") + http.failure(response, property) + } +} diff --git a/src/test/kotlin/kr/co/vividnext/sodalive/v2/api/creator/settlement/MonthlySettlementHistoryHttpTestSupport.kt b/src/test/kotlin/kr/co/vividnext/sodalive/v2/api/creator/settlement/MonthlySettlementHistoryHttpTestSupport.kt new file mode 100644 index 00000000..c0c26376 --- /dev/null +++ b/src/test/kotlin/kr/co/vividnext/sodalive/v2/api/creator/settlement/MonthlySettlementHistoryHttpTestSupport.kt @@ -0,0 +1,123 @@ +package kr.co.vividnext.sodalive.v2.api.creator.settlement + +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.ObjectMapper +import kr.co.vividnext.sodalive.jwt.TokenProvider +import kr.co.vividnext.sodalive.member.Member +import kr.co.vividnext.sodalive.member.token.MemberTokenRepository +import kr.co.vividnext.sodalive.support.EmbeddedRedisInitializer +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.BeforeEach +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.boot.test.context.SpringBootTest +import org.springframework.boot.test.context.TestConfiguration +import org.springframework.boot.test.web.client.TestRestTemplate +import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.Import +import org.springframework.test.context.ContextConfiguration +import org.springframework.transaction.support.TransactionTemplate +import java.time.Clock +import java.time.Instant +import java.time.ZoneOffset +import javax.persistence.EntityManager + +@SpringBootTest( + webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, + properties = [ + "spring.cache.type=none", + "spring.datasource.url=jdbc:h2:mem:monthly-history-\${random.uuid};MODE=MySQL;DATABASE_TO_UPPER=false;" + + "NON_KEYWORDS=VALUE;DB_CLOSE_DELAY=0;DB_CLOSE_ON_EXIT=FALSE" + ] +) +@ContextConfiguration(initializers = [EmbeddedRedisInitializer::class]) +@Import(MonthlySettlementHistoryClockConfiguration::class) +abstract class MonthlySettlementHistoryHttpTestSupport { + @Autowired protected lateinit var entityManager: EntityManager + + @Autowired private lateinit var transactionTemplate: TransactionTemplate + + @Autowired private lateinit var restTemplate: TestRestTemplate + + @Autowired private lateinit var objectMapper: ObjectMapper + + @Autowired private lateinit var tokenProvider: TokenProvider + + @Autowired private lateinit var tokenRepository: MemberTokenRepository + + internal val fixture by lazy { MonthlySettlementHttpFixture(entityManager, transactionTemplate) } + internal val http by lazy { MonthlySettlementHttpTestSupport(restTemplate, objectMapper, tokenProvider) } + + @BeforeEach + fun initializeHistoryFixtures() { + fixture.initialize() + } + + @AfterEach + fun cleanupHistoryFixturesAndTokens() { + try { + http.removeIssuedTokens(tokenRepository) + } finally { + fixture.cleanup() + } + } + + internal fun history(creator: Member, query: String = ""): JsonNode { + val response = http.get(creator, "/creator-admin/calculate/monthly-history$query") + println( + "HISTORY HTTP EVIDENCE query=$query status=${response.statusCodeValue} " + + "cache-control=${response.headers.cacheControl} body=${response.body}" + ) + val data = http.success(response) + val message = objectMapper.readTree(requireNotNull(response.body)).path("message") + assertTrue(message.isMissingNode || message.isNull || message.isTextual) + assertEquals("no-store", response.headers.cacheControl) + assertEquals(setOf("items", "totalCount"), data.fieldNames().asSequence().toSet()) + assertTrue(data.path("totalCount").isIntegralNumber) + assertTrue(data.path("totalCount").canConvertToLong()) + assertTrue(data.path("items").isArray) + data.path("items").forEach { item -> + assertEquals( + setOf( + "month", "periodStartInclusive", "periodEndExclusive", "timeZone", "calculatedAt", "currency", + "calculationStatus", "hasRevenueData", "payoutStatus", "plannedPayoutDate", "actualPayoutDate", "total" + ), + item.fieldNames().asSequence().toSet() + ) + assertEquals("Asia/Seoul", item.path("timeZone").asText()) + assertEquals("KRW", item.path("currency").asText()) + assertEquals("PROVISIONAL", item.path("calculationStatus").asText()) + assertEquals("UNKNOWN", item.path("payoutStatus").asText()) + assertTrue(item.path("plannedPayoutDate").isNull) + assertTrue(item.path("actualPayoutDate").isNull) + assertTrue(item.path("hasRevenueData").isBoolean) + assertEquals("2026-10-31T15:00:00Z", item.path("calculatedAt").asText()) + listOf("periodStartInclusive", "periodEndExclusive").forEach { Instant.parse(item.path(it).asText()) } + val total = item.path("total") + assertEquals( + setOf( + "totalCan", + "grossAmount", + "paymentFee", + "platformFee", + "settlementAmount", + "withholdingTax", + "depositAmount" + ), + total.fieldNames().asSequence().toSet() + ) + total.forEach { assertTrue(it.isIntegralNumber && it.canConvertToLong()) } + } + return data + } + + internal fun summary(creator: Member, month: String): JsonNode = + http.success(http.get(creator, "/creator-admin/calculate/monthly-summary?month=$month")) +} + +@TestConfiguration +class MonthlySettlementHistoryClockConfiguration { + @Bean + fun monthlyHistoryClock(): Clock = Clock.fixed(Instant.parse("2026-10-31T15:00:00Z"), ZoneOffset.UTC) +} diff --git a/src/test/kotlin/kr/co/vividnext/sodalive/v2/api/creator/settlement/MonthlySettlementHttpFixture.kt b/src/test/kotlin/kr/co/vividnext/sodalive/v2/api/creator/settlement/MonthlySettlementHttpFixture.kt index 75ad60d2..86fbc8b3 100644 --- a/src/test/kotlin/kr/co/vividnext/sodalive/v2/api/creator/settlement/MonthlySettlementHttpFixture.kt +++ b/src/test/kotlin/kr/co/vividnext/sodalive/v2/api/creator/settlement/MonthlySettlementHttpFixture.kt @@ -68,6 +68,16 @@ internal class MonthlySettlementHttpFixture( ) } + fun room(creator: Member): LiveRoom = save( + LiveRoom("history-live", "notice", LocalDateTime.of(2026, 11, 1, 0, 0), 1, isAdult = false, price = 1).apply { + member = creator + } + ) + + fun post(creator: Member): CreatorCommunity = save( + CreatorCommunity("history-post", 3, isCommentAvailable = true, isAdult = false).apply { member = creator } + ) + fun order(content: AudioContent, can: Int, at: LocalDateTime): Order = saveAt( Order(type = OrderType.KEEP).apply { member = buyer