feat(creator-calculate): 본인 월별 정산 요약 API를 추가한다

This commit is contained in:
2026-11-20 17:50:28 +09:00
parent ed6f476894
commit d98a205ea6
6 changed files with 764 additions and 0 deletions
@@ -0,0 +1,35 @@
package kr.co.vividnext.sodalive.v2.api.creator.settlement.adapter.`in`.web
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.GetCreatorMonthlySettlementResponse
import org.springframework.http.CacheControl
import org.springframework.http.ResponseEntity
import org.springframework.security.access.prepost.PreAuthorize
import org.springframework.security.core.annotation.AuthenticationPrincipal
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
import java.time.YearMonth
@RestController
@PreAuthorize("hasRole('CREATOR')")
@RequestMapping("/creator-admin/calculate")
class CreatorMonthlySettlementController(private val service: CreatorMonthlySettlementService) {
@GetMapping("/monthly-summary")
fun getMonthlySummary(
@RequestParam month: String,
@AuthenticationPrincipal(expression = "#this == 'anonymousUser' ? null : member") member: Member?
): ResponseEntity<ApiResponse<GetCreatorMonthlySettlementResponse>> {
val memberId = member?.id ?: throw SodaException(messageKey = "common.error.bad_credentials")
if (!month.matches(Regex("[0-9]{4}-(0[1-9]|1[0-2])"))) {
throw SodaException(messageKey = "common.error.invalid_request", errorProperty = "month")
}
val requestedMonth = YearMonth.parse(month)
val summary = service.getMonthlySummary(memberId, requestedMonth)
return ResponseEntity.ok().cacheControl(CacheControl.noStore()).body(ApiResponse.ok(summary))
}
}
@@ -0,0 +1,129 @@
package kr.co.vividnext.sodalive.v2.api.creator.settlement.application
import kr.co.vividnext.sodalive.common.SodaException
import kr.co.vividnext.sodalive.creator.admin.calculate.CreatorAdminCalculateQueryRepository
import kr.co.vividnext.sodalive.creator.admin.calculate.channelDonation.CreatorAdminChannelDonationCalculateQueryRepository
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.CreatorMonthlySettlementSource
import kr.co.vividnext.sodalive.v2.api.creator.settlement.dto.CreatorMonthlySettlementSourceAmount
import kr.co.vividnext.sodalive.v2.api.creator.settlement.dto.GetCreatorMonthlySettlementResponse
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.Instant
import java.time.LocalDateTime
import java.time.YearMonth
import java.time.ZoneId
import java.time.ZoneOffset
@Service
class CreatorMonthlySettlementService(
private val repository: CreatorAdminCalculateQueryRepository,
private val channelRepository: CreatorAdminChannelDonationCalculateQueryRepository,
private val memberRepository: MemberRepository
) {
@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")
val zone = ZoneId.of("Asia/Seoul")
val start = month.atDay(1).atStartOfDay(zone).toInstant()
val end = month.plusMonths(1).atDay(1).atStartOfDay(zone).toInstant()
val startUtc = LocalDateTime.ofInstant(start, ZoneOffset.UTC)
val endUtc = LocalDateTime.ofInstant(end, ZoneOffset.UTC)
val live = repository.getMonthlyCalculateLive(startUtc, endUtc, memberId)
.map { it.toGetCalculateLiveResponse() }
val content = repository.getMonthlyCalculateContentList(startUtc, endUtc, memberId)
.map { it.toGetCalculateContentResponse() }
val contentDonation = repository.getMonthlyCalculateContentDonationList(startUtc, endUtc, memberId)
.map { it.toGetCalculateContentDonationResponse() }
val community = repository.getMonthlyCalculateCommunityPostList(startUtc, endUtc, memberId)
.map { it.toGetCalculateCommunityPostResponse() }
val channelQuery = channelRepository.getMonthlyChannelDonationSettlementTotal(startUtc, endUtc, memberId)
val channel = channelQuery.toResponseTotal()
val breakdown = listOf(
CreatorMonthlySettlementSourceAmount(
source = CreatorMonthlySettlementSource.LIVE,
hasRevenueData = live.isNotEmpty(),
amount = CreatorMonthlySettlementAmount(
totalCan = live.sumOf { it.totalAmount.toLong() },
grossAmount = live.sumOf { it.totalKrw.toLong() },
paymentFee = live.sumOf { it.paymentFee.toLong() },
settlementAmount = live.sumOf { it.settlementAmount.toLong() },
withholdingTax = live.sumOf { it.tax.toLong() },
depositAmount = live.sumOf { it.depositAmount.toLong() }
)
),
CreatorMonthlySettlementSourceAmount(
source = CreatorMonthlySettlementSource.CONTENT_SALES,
hasRevenueData = content.isNotEmpty(),
amount = CreatorMonthlySettlementAmount(
totalCan = content.sumOf { it.totalCan.toLong() },
grossAmount = content.sumOf { it.totalKrw.toLong() },
paymentFee = content.sumOf { it.paymentFee.toLong() },
settlementAmount = content.sumOf { it.settlementAmount.toLong() },
withholdingTax = content.sumOf { it.tax.toLong() },
depositAmount = content.sumOf { it.depositAmount.toLong() }
)
),
CreatorMonthlySettlementSourceAmount(
source = CreatorMonthlySettlementSource.CONTENT_DONATION,
hasRevenueData = contentDonation.isNotEmpty(),
amount = CreatorMonthlySettlementAmount(
totalCan = contentDonation.sumOf { it.totalCan.toLong() },
grossAmount = contentDonation.sumOf { it.totalKrw.toLong() },
paymentFee = contentDonation.sumOf { it.paymentFee.toLong() },
settlementAmount = contentDonation.sumOf { it.settlementAmount.toLong() },
withholdingTax = contentDonation.sumOf { it.tax.toLong() },
depositAmount = contentDonation.sumOf { it.depositAmount.toLong() }
)
),
CreatorMonthlySettlementSourceAmount(
source = CreatorMonthlySettlementSource.COMMUNITY_POST,
hasRevenueData = community.isNotEmpty(),
amount = CreatorMonthlySettlementAmount(
totalCan = community.sumOf { it.totalCan.toLong() },
grossAmount = community.sumOf { it.totalKrw.toLong() },
paymentFee = community.sumOf { it.paymentFee.toLong() },
settlementAmount = community.sumOf { it.settlementAmount.toLong() },
withholdingTax = community.sumOf { it.tax.toLong() },
depositAmount = community.sumOf { it.depositAmount.toLong() }
)
),
CreatorMonthlySettlementSourceAmount(
source = CreatorMonthlySettlementSource.CHANNEL_DONATION,
hasRevenueData = (channelQuery.count ?: 0L) > 0L,
amount = CreatorMonthlySettlementAmount(
totalCan = channel.totalCan.toLong(),
grossAmount = channel.krw.toLong(),
paymentFee = channel.fee.toLong(),
settlementAmount = channel.settlementAmount.toLong(),
withholdingTax = channel.withholdingTax.toLong(),
depositAmount = channel.depositAmount.toLong()
)
)
)
val total = CreatorMonthlySettlementAmount(
totalCan = breakdown.sumOf { it.amount.totalCan },
grossAmount = breakdown.sumOf { it.amount.grossAmount },
paymentFee = breakdown.sumOf { it.amount.paymentFee },
settlementAmount = breakdown.sumOf { it.amount.settlementAmount },
withholdingTax = breakdown.sumOf { it.amount.withholdingTax },
depositAmount = breakdown.sumOf { it.amount.depositAmount }
)
return GetCreatorMonthlySettlementResponse(
month = month.toString(),
periodStartInclusive = start.toString(),
periodEndExclusive = end.toString(),
calculatedAt = Instant.now().toString(),
total = total,
breakdown = breakdown
)
}
}
@@ -0,0 +1,40 @@
package kr.co.vividnext.sodalive.v2.api.creator.settlement.dto
import com.fasterxml.jackson.annotation.JsonUnwrapped
data class GetCreatorMonthlySettlementResponse(
val month: String,
val periodStartInclusive: String,
val periodEndExclusive: String,
val calculatedAt: String,
val total: CreatorMonthlySettlementAmount,
val breakdown: List<CreatorMonthlySettlementSourceAmount>
) {
val timeZone: String = "Asia/Seoul"
val currency: String = "KRW"
val calculationStatus: String = "PROVISIONAL"
val hasRevenueData: Boolean = breakdown.any { it.hasRevenueData }
val payoutStatus: String = "UNKNOWN"
}
data class CreatorMonthlySettlementAmount(
val totalCan: Long,
val grossAmount: Long,
val paymentFee: Long,
val settlementAmount: Long,
val withholdingTax: Long,
val depositAmount: Long
) {
val platformFee: Long
get() = grossAmount - paymentFee - settlementAmount
}
data class CreatorMonthlySettlementSourceAmount(
val source: CreatorMonthlySettlementSource,
val hasRevenueData: Boolean,
@get:JsonUnwrapped val amount: CreatorMonthlySettlementAmount
)
enum class CreatorMonthlySettlementSource {
LIVE, CONTENT_SALES, CONTENT_DONATION, COMMUNITY_POST, CHANNEL_DONATION
}
@@ -0,0 +1,287 @@
package kr.co.vividnext.sodalive.v2.api.creator.settlement
import com.fasterxml.jackson.databind.ObjectMapper
import kr.co.vividnext.sodalive.jwt.TokenProvider
import kr.co.vividnext.sodalive.member.MemberRole
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.assertFalse
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.CsvSource
import org.junit.jupiter.params.provider.EnumSource
import org.junit.jupiter.params.provider.ValueSource
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.web.client.TestRestTemplate
import org.springframework.http.HttpStatus
import org.springframework.test.context.ContextConfiguration
import org.springframework.transaction.support.TransactionTemplate
import java.time.Instant
import java.time.LocalDateTime
import java.time.YearMonth
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-http-\${random.uuid};MODE=MySQL;DATABASE_TO_UPPER=false;" +
"NON_KEYWORDS=VALUE;DB_CLOSE_DELAY=0;DB_CLOSE_ON_EXIT=FALSE"
]
)
@ContextConfiguration(initializers = [EmbeddedRedisInitializer::class])
class CreatorMonthlySettlementHttpIntegrationTest @Autowired constructor(
entityManager: EntityManager,
transactionTemplate: TransactionTemplate,
restTemplate: TestRestTemplate,
objectMapper: ObjectMapper,
tokenProvider: TokenProvider,
private val tokenRepository: MemberTokenRepository
) {
private val fixture = MonthlySettlementHttpFixture(entityManager, transactionTemplate)
private val http = MonthlySettlementHttpTestSupport(restTemplate, objectMapper, tokenProvider)
@BeforeEach
fun initializeDateFunctions() {
fixture.initialize()
}
@AfterEach
fun cleanupCommittedFixturesAndTokens() {
try {
http.removeIssuedTokens(tokenRepository)
} finally {
fixture.cleanup()
}
}
@Test
@DisplayName("빈 월은 다섯 0원 원천과 잠정·지급 확인 불가 상태를 지급일 필드 없이 반환한다")
fun shouldReturnFiveZeroSourcesForAnEmptyMonthThroughHttp() {
val creator = fixture.commit { member() }
val data = http.summary(creator)
assertEquals("2026-10-31T15:00:00Z", data.path("periodStartInclusive").asText())
assertEquals("2026-11-30T15:00:00Z", data.path("periodEndExclusive").asText())
assertFalse(data.path("hasRevenueData").booleanValue())
data.path("breakdown").forEach { source ->
assertFalse(source.path("hasRevenueData").booleanValue())
http.amount(source, List(7) { 0L })
}
}
@Test
@DisplayName("사용 기록 연결이 없는 유효 0 CAN 주문도 콘텐츠 거래 존재로 구분한다")
fun shouldDistinguishAnActiveZeroCanOrderFromNoRevenueDataThroughHttp() {
val creator = fixture.commit {
val creator = member()
order(content(creator), 0, LocalDateTime.of(2026, 11, 18, 0, 0))
creator
}
val data = http.summary(creator)
assertTrue(data.path("hasRevenueData").booleanValue())
data.path("breakdown").forEach { source ->
assertEquals(source.path("source").asText() == "CONTENT_SALES", source.path("hasRevenueData").booleanValue())
http.amount(source, List(7) { 0L })
}
}
@Test
@DisplayName("11월 전체의 한국 75% 다섯 원천 합계는 기존 크리에이터 HTTP 및 채널 전체 total과 일치한다")
fun shouldSumFiveSourcesAndReconcileExistingCreatorRoutesThroughHttp() {
val creator = fixture.commit {
val creator = member()
allSources(creator)
channelDonation(member(), 777, LocalDateTime.of(2026, 11, 18, 0, 0))
creator
}
val data = http.summary(creator)
val expected = listOf(
listOf(2L, 200L, 13L, 47L, 140L, 5L, 135L),
listOf(9L, 900L, 59L, 211L, 630L, 21L, 610L),
listOf(1L, 100L, 7L, 23L, 70L, 2L, 68L),
listOf(3L, 300L, 20L, 70L, 210L, 7L, 203L),
listOf(2L, 200L, 13L, 47L, 140L, 5L, 135L)
)
data.path("breakdown").zip(expected).forEach { (source, amounts) ->
assertTrue(source.path("hasRevenueData").booleanValue())
http.amount(source, amounts)
}
http.amount(data.path("total"), listOf(17L, 1700L, 112L, 398L, 1190L, 40L, 1151L))
val query = "?startDateStr=2026-11-01&endDateStr=2026-11-30&page=0&size=20"
val routes = listOf("live", "content-list", "content-donation-list", "community-post", "channel-donation")
routes.forEachIndexed { index, route ->
val legacy = http.success(http.get(creator, "/creator-admin/calculate/$route$query"))
val rows = when (route) {
"live" -> legacy.toList()
"channel-donation" -> listOf(legacy.path("total"))
else -> legacy.path("items").toList()
}
assertFalse(rows.isEmpty(), route)
val oldFields = when (route) {
"live" -> listOf("totalAmount", "totalKrw", "paymentFee", "settlementAmount", "tax", "depositAmount")
"channel-donation" -> listOf("totalCan", "krw", "fee", "settlementAmount", "withholdingTax", "depositAmount")
else -> listOf("totalCan", "totalKrw", "paymentFee", "settlementAmount", "tax", "depositAmount")
}
val monthlyFields = listOf(
"totalCan",
"grossAmount",
"paymentFee",
"settlementAmount",
"withholdingTax",
"depositAmount"
)
oldFields.zip(monthlyFields).forEach { (oldField, monthlyField) ->
assertEquals(
rows.sumOf { it.path(oldField).longValue() },
data.path("breakdown")[index].path(monthlyField).longValue(),
"$route $oldField must reconcile with $monthlyField"
)
}
if (route == "channel-donation") {
assertEquals(135L, legacy.path("total").path("depositAmount").longValue())
assertEquals(136L, legacy.path("items").sumOf { it.path("depositAmount").longValue() })
}
}
}
@ParameterizedTest
@CsvSource(
"2026-10, 2026-09-30T15:00:00Z, 2026-10-31T15:00:00Z",
"2026-11, 2026-10-31T15:00:00Z, 2026-11-30T15:00:00Z",
"2026-12, 2026-11-30T15:00:00Z, 2026-12-31T15:00:00Z",
"2024-02, 2024-01-31T15:00:00Z, 2024-02-29T15:00:00Z"
)
@DisplayName("KST 월·윤년 경계와 고정 시행일·연말 소수초는 조회 순서와 무관하게 거래 시각의 비율을 적용한다")
fun shouldUseHalfOpenKstMonthIncludingFractionalLastSecondThroughHttp(month: String, start: String, end: String) {
val startUtc = LocalDateTime.ofInstant(Instant.parse(start), ZoneOffset.UTC)
val endUtc = LocalDateTime.ofInstant(Instant.parse(end), ZoneOffset.UTC)
val creator = fixture.commit {
val creator = member()
val content = content(creator)
listOf(startUtc.minusSeconds(1), startUtc, endUtc.minusNanos(1000), endUtc).forEach { at ->
order(content, 1, at)
}
creator
}
if (month == "2026-10" || month == "2026-12") {
val next = http.summary(creator, YearMonth.parse(month).plusMonths(1).toString())
assertEquals(end, next.path("periodStartInclusive").asText())
assertEquals(
if (month == "2026-10") "2026-11-30T15:00:00Z" else "2027-01-31T15:00:00Z",
next.path("periodEndExclusive").asText()
)
val nextExpected = if (month == "2026-10") {
listOf(1L, 100L, 7L, 23L, 70L, 2L, 68L)
} else {
listOf(1L, 100L, 7L, 28L, 65L, 2L, 63L)
}
http.amount(next.path("total"), nextExpected)
http.amount(next.path("breakdown")[1], nextExpected)
}
val data = http.summary(creator, month)
assertEquals(start, data.path("periodStartInclusive").asText())
assertEquals(end, data.path("periodEndExclusive").asText())
val expected = if (month == "2026-11" || month == "2026-12") {
listOf(2L, 200L, 14L, 46L, 140L, 4L, 136L)
} else {
listOf(2L, 200L, 14L, 56L, 130L, 4L, 126L)
}
http.amount(data.path("total"), expected)
http.amount(data.path("breakdown")[1], expected)
}
@Test
@DisplayName("행별 Int 범위의 원천도 월 합계는 Int를 넘는 Long JSON 정수로 보존한다")
fun shouldKeepMonthlyAmountsAboveIntRangeThroughHttp() {
val creator = fixture.commit {
val creator = member()
val content = content(creator)
listOf(19, 20).forEach { day -> order(content, 20_000_000, LocalDateTime.of(2026, 11, day, 0, 0)) }
creator
}
val data = http.summary(creator)
http.amount(
data.path("total"),
listOf(40_000_000L, 4_000_000_000L, 264_000_000L, 934_000_000L, 2_802_000_000L, 92_466_000L, 2_709_534_000L)
)
}
@Test
@DisplayName("Bearer 없는 실제 월별 HTTP 요청은 기존 보안 체인에서 401로 거부한다")
fun shouldRejectMissingBearerTokenThroughHttp() {
val response = http.get(null, "/creator-admin/calculate/monthly-summary?month=2026-11")
assertEquals(HttpStatus.UNAUTHORIZED, response.statusCode, response.body)
}
@ParameterizedTest
@EnumSource(value = MemberRole::class, names = ["USER", "ADMIN"])
@DisplayName("USER와 ADMIN의 등록 Bearer도 기존 HTTP 200 오류 래퍼로 크리에이터 조회를 거부한다")
fun shouldRejectNonCreatorRolesThroughHttp(role: MemberRole) {
val actor = fixture.commit { member(role) }
val response = http.get(actor, "/creator-admin/calculate/monthly-summary?month=2026-11")
http.failure(response)
}
@Test
@DisplayName("주입한 creatorId·userId·memberId는 다른 크리에이터의 다섯 원천을 노출하지 않는다")
fun shouldIgnoreInjectedCreatorAndUserIdsThroughHttp() {
val (creator, otherCreatorId) = fixture.commit {
val creator = member()
val other = member()
allSources(other)
creator to requireNotNull(other.id)
}
val data = http.summary(
creator,
extraQuery = "&creatorId=$otherCreatorId&userId=$otherCreatorId&memberId=$otherCreatorId"
)
assertFalse(data.path("hasRevenueData").booleanValue())
data.path("breakdown").forEach { source ->
assertFalse(source.path("hasRevenueData").booleanValue())
http.amount(source, List(7) { 0L })
}
}
@ParameterizedTest
@ValueSource(strings = ["2026-1", "2026-00", "2026-13", "2026-11-01", "not-a-month", ""])
@DisplayName("잘못된 월은 기존 업무 오류 래퍼와 month 오류 속성으로 거부한다")
fun shouldRejectMalformedMonthWithMonthErrorPropertyThroughHttp(month: String) {
val creator = fixture.commit { member() }
val response = http.get(creator, "/creator-admin/calculate/monthly-summary?month=$month")
http.failure(response, "month")
}
@Test
@DisplayName("필수 month 누락은 현재 바인딩 오류 래퍼로 거부한다")
fun shouldRejectMissingMonthThroughCurrentBindingErrorWrapper() {
val creator = fixture.commit { member() }
val response = http.get(creator, "/creator-admin/calculate/monthly-summary")
http.failure(response)
}
}
@@ -0,0 +1,125 @@
package kr.co.vividnext.sodalive.v2.api.creator.settlement
import kr.co.vividnext.sodalive.can.payment.PaymentGateway
import kr.co.vividnext.sodalive.can.use.CanUsage
import kr.co.vividnext.sodalive.can.use.UseCan
import kr.co.vividnext.sodalive.can.use.UseCanCalculate
import kr.co.vividnext.sodalive.can.use.UseCanCalculateStatus
import kr.co.vividnext.sodalive.common.BaseEntity
import kr.co.vividnext.sodalive.content.AudioContent
import kr.co.vividnext.sodalive.content.order.Order
import kr.co.vividnext.sodalive.content.order.OrderType
import kr.co.vividnext.sodalive.content.theme.AudioContentTheme
import kr.co.vividnext.sodalive.explorer.profile.creatorCommunity.CreatorCommunity
import kr.co.vividnext.sodalive.live.room.LiveRoom
import kr.co.vividnext.sodalive.member.Member
import kr.co.vividnext.sodalive.member.MemberRole
import org.springframework.transaction.support.TransactionTemplate
import java.time.LocalDateTime
import java.util.UUID
import javax.persistence.EntityManager
internal class MonthlySettlementHttpFixture(
private val entityManager: EntityManager,
private val transactionTemplate: TransactionTemplate
) {
private val created = mutableListOf<BaseEntity>()
private val buyer by lazy { member(MemberRole.USER) }
fun initialize() = commit {
entityManager.createNativeQuery(
"CREATE ALIAS IF NOT EXISTS DATE_FORMAT FOR 'kr.co.vividnext.sodalive.support.H2MysqlDateFunctions.dateFormat'"
).executeUpdate()
entityManager.createNativeQuery(
"CREATE ALIAS IF NOT EXISTS CONVERT_TZ FOR 'kr.co.vividnext.sodalive.support.H2MysqlDateFunctions.convertTz'"
).executeUpdate()
}
fun <T : Any> commit(block: MonthlySettlementHttpFixture.() -> T): T =
requireNotNull(transactionTemplate.execute { block() })
fun cleanup() {
transactionTemplate.executeWithoutResult {
entityManager.clear()
created.asReversed().forEach { entity ->
entityManager.createQuery("delete from ${entity.javaClass.simpleName} e where e.id = :id")
.setParameter("id", entity.id)
.executeUpdate()
}
}
created.clear()
}
fun member(role: MemberRole = MemberRole.CREATOR): Member {
val name = "monthly-${UUID.randomUUID()}"
return save(Member(email = "$name@test.com", password = "password", nickname = name, role = role, countryCode = "KR"))
}
fun content(creator: Member): AudioContent {
val theme = save(AudioContentTheme(theme = "monthly", image = "monthly.png"))
return save(
AudioContent(title = "monthly-content", detail = "detail", languageCode = "ko", price = 9).apply {
this.theme = theme
member = creator
isActive = true
}
)
}
fun order(content: AudioContent, can: Int, at: LocalDateTime): Order = saveAt(
Order(type = OrderType.KEEP).apply {
member = buyer
creator = content.member
audioContent = content
this.can = can
},
at
)
fun usage(useCan: UseCan, at: LocalDateTime): UseCan {
useCan.member = buyer
return saveAt(useCan, at)
}
fun channelDonation(creator: Member, can: Int, at: LocalDateTime) {
val useCan = usage(UseCan(CanUsage.CHANNEL_DONATION, can, 0, countryCode = "KR"), at)
save(
UseCanCalculate(can, PaymentGateway.PG, UseCanCalculateStatus.RECEIVED).apply {
this.useCan = useCan
recipientCreatorId = creator.id
}
)
}
fun allSources(creator: Member) {
val novemberStart = LocalDateTime.of(2026, 10, 31, 15, 0)
val nextDay = LocalDateTime.of(2026, 11, 1, 15, 0)
val content = content(creator)
val room = save(
LiveRoom("monthly-live", "notice", novemberStart, 1, isAdult = false, price = 1).apply { member = creator }
)
val post = save(
CreatorCommunity("monthly-post", 3, isCommentAvailable = true, isAdult = false).apply { member = creator }
)
listOf(novemberStart, nextDay).forEach { at ->
usage(UseCan(CanUsage.LIVE, 1, 0, countryCode = "KR").apply { this.room = room }, at)
channelDonation(creator, 1, at)
}
order(content, 9, nextDay)
usage(UseCan(CanUsage.DONATION, 1, 0, countryCode = "KR").apply { audioContent = content }, nextDay)
usage(UseCan(CanUsage.PAID_COMMUNITY_POST, 3, 0, countryCode = "KR").apply { communityPost = post }, novemberStart)
}
private fun <T : BaseEntity> save(entity: T): T {
entityManager.persist(entity)
created.add(entity)
return entity
}
private fun <T : BaseEntity> saveAt(entity: T, at: LocalDateTime): T {
save(entity)
entity.createdAt = at
entityManager.flush()
return entity
}
}
@@ -0,0 +1,148 @@
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.MemberAdapter
import kr.co.vividnext.sodalive.member.token.MemberTokenRepository
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertTrue
import org.springframework.boot.test.web.client.TestRestTemplate
import org.springframework.http.HttpEntity
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpMethod
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import java.time.Instant
import java.time.temporal.ChronoUnit
internal class MonthlySettlementHttpTestSupport(
private val restTemplate: TestRestTemplate,
private val objectMapper: ObjectMapper,
private val tokenProvider: TokenProvider
) {
private val tokenMemberIds = mutableSetOf<Long>()
private val amountFields = listOf(
"totalCan",
"grossAmount",
"paymentFee",
"platformFee",
"settlementAmount",
"withholdingTax",
"depositAmount"
)
private val sources = listOf("LIVE", "CONTENT_SALES", "CONTENT_DONATION", "COMMUNITY_POST", "CHANNEL_DONATION")
fun removeIssuedTokens(repository: MemberTokenRepository) {
tokenMemberIds.forEach { repository.deleteById(it) }
tokenMemberIds.clear()
}
fun get(actor: Member?, path: String): ResponseEntity<String> {
val headers = HttpHeaders().apply { set(HttpHeaders.ACCEPT_LANGUAGE, "ko") }
if (actor != null) {
val principal = MemberAdapter(actor)
val memberId = requireNotNull(actor.id)
tokenMemberIds.add(memberId)
headers.setBearerAuth(
tokenProvider.createToken(
UsernamePasswordAuthenticationToken(principal, "", principal.authorities),
memberId
)
)
}
return restTemplate.exchange(path, HttpMethod.GET, HttpEntity<Void>(headers), String::class.java)
}
fun summary(actor: Member, month: String = "2026-11", extraQuery: String = ""): JsonNode {
val before = Instant.now().truncatedTo(ChronoUnit.SECONDS)
val response = get(actor, "/creator-admin/calculate/monthly-summary?month=$month$extraQuery")
val after = Instant.now()
val data = success(response)
println(
"MONTHLY HTTP EVIDENCE month=$month status=${response.statusCodeValue} " +
"cache-control=${response.headers.cacheControl} body=${response.body}"
)
assertEquals(listOf("no-store"), response.headers.cacheControl?.split(',')?.map { it.trim() })
assertEquals(
setOf(
"month", "timeZone", "periodStartInclusive", "periodEndExclusive", "calculatedAt", "currency",
"calculationStatus", "hasRevenueData", "payoutStatus", "total", "breakdown"
),
data.fieldNames().asSequence().toSet()
)
assertFalse(data.has("plannedPayoutDate"))
assertFalse(data.has("actualPayoutDate"))
assertEquals(month, data.path("month").asText())
assertEquals("Asia/Seoul", data.path("timeZone").asText())
assertEquals("KRW", data.path("currency").asText())
assertEquals("PROVISIONAL", data.path("calculationStatus").asText())
assertEquals("UNKNOWN", data.path("payoutStatus").asText())
listOf("periodStartInclusive", "periodEndExclusive", "calculatedAt").forEach { field ->
assertTrue(data.path(field).isTextual, field)
assertTrue(data.path(field).asText().endsWith("Z"), field)
Instant.parse(data.path(field).asText())
}
val calculatedAt = Instant.parse(data.path("calculatedAt").asText())
assertFalse(calculatedAt.isBefore(before), "calculatedAt must describe this request: $data")
assertFalse(calculatedAt.isAfter(after), "calculatedAt must describe this request: $data")
assertTrue(data.path("breakdown").isArray)
assertEquals(sources, data.path("breakdown").map { it.path("source").asText() })
val amounts = listOf(data.path("total")) + data.path("breakdown").toList()
amounts.forEachIndexed { index, amount ->
val fields = amountFields.toSet() + if (index == 0) emptySet() else setOf("source", "hasRevenueData")
assertEquals(fields, amount.fieldNames().asSequence().toSet())
amountFields.forEach { field ->
assertTrue(amount.path(field).isIntegralNumber, "$field must be a JSON integer: $amount")
assertTrue(amount.path(field).canConvertToLong(), "$field must fit Long: $amount")
}
assertEquals(
amount.path("grossAmount").longValue() - amount.path("paymentFee").longValue() -
amount.path("settlementAmount").longValue(),
amount.path("platformFee").longValue()
)
}
amountFields.forEach { field ->
assertEquals(
data.path("breakdown").sumOf { it.path(field).longValue() },
data.path("total").path(field).longValue(),
"total.$field must sum all five sources"
)
}
assertTrue(data.path("hasRevenueData").isBoolean)
data.path("breakdown").forEach { assertTrue(it.path("hasRevenueData").isBoolean) }
assertEquals(
data.path("breakdown").any { it.path("hasRevenueData").booleanValue() },
data.path("hasRevenueData").booleanValue()
)
return data
}
fun success(response: ResponseEntity<String>): JsonNode {
assertEquals(HttpStatus.OK, response.statusCode, response.body)
assertTrue(MediaType.APPLICATION_JSON.isCompatibleWith(requireNotNull(response.headers.contentType)))
val body = objectMapper.readTree(requireNotNull(response.body))
assertTrue(body.path("success").isBoolean, body.toString())
assertTrue(body.path("success").booleanValue(), body.toString())
return body.path("data")
}
fun failure(response: ResponseEntity<String>, errorProperty: String? = null) {
assertEquals(HttpStatus.OK, response.statusCode, response.body)
val body = objectMapper.readTree(requireNotNull(response.body))
assertTrue(body.path("success").isBoolean, body.toString())
assertFalse(body.path("success").booleanValue(), body.toString())
assertTrue(body.path("data").isNull, body.toString())
assertTrue(body.path("message").isTextual, body.toString())
assertTrue(body.path("message").asText().isNotBlank(), body.toString())
if (errorProperty != null) assertEquals(errorProperty, body.path("errorProperty").asText(), body.toString())
}
fun amount(actual: JsonNode, expected: List<Long>) {
assertEquals(expected, amountFields.map { actual.path(it).longValue() }, actual.toString())
}
}