feat(settlement): 비율별 정산 행과 확정 근거를 반영한다

This commit is contained in:
2026-11-23 07:49:57 +09:00
parent 36f4eef5a8
commit 23873c7694
85 changed files with 7579 additions and 2966 deletions
@@ -0,0 +1,14 @@
-- 서버 배포 전 대상 DB에서 1회 적용한다. 기존 source-detail 테이블이 있어야 한다.
-- 아래 컬럼이나 인덱스가 이미 있으면 재실행하지 말고 적용 이력을 확인한다.
ALTER TABLE agent_settlement_snapshot_source_detail
ADD COLUMN canonical_row_key VARCHAR(384) CHARACTER SET ascii COLLATE ascii_bin NULL
COMMENT '공통 정산행 키, 기존 확정은 NULL',
ADD COLUMN country_relation VARCHAR(24) NULL
COMMENT '확정 당시 국가 관계',
ADD COLUMN applied_settlement_ratio INT NULL
COMMENT '실제 적용 creator 정산 비율',
ADD COLUMN rate_info_available BOOLEAN NULL
COMMENT '확정 정산행 비율 정보 완전성',
ADD COLUMN provenance_json LONGTEXT NULL
COMMENT '소속 및 agent 비율 이력 참조 쌍 배열, null 비율 이력 포함',
ADD UNIQUE INDEX uk_snapshot_detail_canonical (snapshot_id, canonical_row_key);
@@ -1,9 +1,11 @@
package kr.co.vividnext.sodalive.admin.calculate
import com.querydsl.core.BooleanBuilder
import com.querydsl.core.types.dsl.CaseBuilder
import com.querydsl.core.types.dsl.DateTimePath
import com.querydsl.core.types.dsl.Expressions
import com.querydsl.core.types.dsl.StringTemplate
import com.querydsl.jpa.impl.JPAQuery
import com.querydsl.jpa.impl.JPAQueryFactory
import kr.co.vividnext.sodalive.admin.calculate.ratio.QCreatorSettlementRatio.creatorSettlementRatio
import kr.co.vividnext.sodalive.can.use.CanUsage
@@ -13,584 +15,355 @@ import kr.co.vividnext.sodalive.content.order.QOrder.order
import kr.co.vividnext.sodalive.explorer.profile.creatorCommunity.QCreatorCommunity.creatorCommunity
import kr.co.vividnext.sodalive.live.room.QLiveRoom.liveRoom
import kr.co.vividnext.sodalive.member.QMember.member
import kr.co.vividnext.sodalive.v2.settlement.adapter.out.persistence.CountrySettlementExpressions
import kr.co.vividnext.sodalive.v2.settlement.adapter.out.persistence.CanonicalSettlementQueryRepository
import kr.co.vividnext.sodalive.v2.settlement.domain.CountrySettlementPolicy
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementDisplayGrain
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementScope
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementSource
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementWindow
import kr.co.vividnext.sodalive.v2.settlement.dto.SettlementDisplayRow
import org.springframework.stereotype.Repository
import java.time.LocalDateTime
@Repository
class AdminCalculateQueryRepository(
private val queryFactory: JPAQueryFactory,
private val countrySettlementExpressions: CountrySettlementExpressions
private val canonicalRepository: CanonicalSettlementQueryRepository,
private val policy: CountrySettlementPolicy = CountrySettlementPolicy()
) {
fun getCalculateLiveTotalCount(startDate: LocalDateTime, endDate: LocalDateTime): Int {
return queryFactory
.select(liveRoom.id)
.from(useCan)
.innerJoin(useCan.room, liveRoom)
.innerJoin(liveRoom.member, member)
.leftJoin(creatorSettlementRatio)
.on(
member.id.eq(creatorSettlementRatio.member.id)
.and(creatorSettlementRatio.deletedAt.isNull)
)
.where(
useCan.isRefund.isFalse
.and(useCan.createdAt.goe(startDate))
.and(useCan.createdAt.loe(endDate))
)
.groupBy(liveRoom.id, useCan.canUsage, creatorSettlementRatio.liveSettlementRatio)
.fetch()
.size
}
fun getCalculateLiveTotalCount(startDate: LocalDateTime, endDate: LocalDateTime): Int =
countLive(scope(SettlementSource.LIVE, startDate, endDate))
fun getCalculateLive(
startDate: LocalDateTime,
endDate: LocalDateTime,
fun getCalculateLive(startDate: LocalDateTime, endDate: LocalDateTime, offset: Long, limit: Long) =
readLive(scope(SettlementSource.LIVE, startDate, endDate), offset, limit)
fun getCalculateContentListTotalCount(startDate: LocalDateTime, endDate: LocalDateTime): Int =
countContent(scope(SettlementSource.CONTENT_SALES, startDate, endDate))
fun getCalculateContentList(startDate: LocalDateTime, endDate: LocalDateTime, offset: Long, limit: Long) =
readContent(scope(SettlementSource.CONTENT_SALES, startDate, endDate), offset, limit)
fun getCumulativeSalesByContentTotalCount(): Int = countCumulative(scope(SettlementSource.CONTENT_SALES))
fun getCumulativeSalesByContent(offset: Long, limit: Long) =
readCumulative(scope(SettlementSource.CONTENT_SALES), offset, limit)
fun getCalculateContentDonationListTotalCount(startDate: LocalDateTime, endDate: LocalDateTime): Int =
countDonation(scope(SettlementSource.CONTENT_DONATION, startDate, endDate))
fun getCalculateContentDonationList(startDate: LocalDateTime, endDate: LocalDateTime, offset: Long, limit: Long) =
readDonation(scope(SettlementSource.CONTENT_DONATION, startDate, endDate), offset, limit)
fun getCalculateCommunityPostTotalCount(startDate: LocalDateTime?, endDate: LocalDateTime?): Int =
countCommunity(scope(SettlementSource.COMMUNITY_POST, startDate, endDate))
fun getCalculateCommunityPostList(startDate: LocalDateTime?, endDate: LocalDateTime?, offset: Long, limit: Long) =
readCommunity(scope(SettlementSource.COMMUNITY_POST, startDate, endDate), offset, limit)
fun getCalculateLiveByCreatorTotalCount(startDate: LocalDateTime, endDate: LocalDateTime): Int =
countByCreator(scope(SettlementSource.LIVE, startDate, endDate))
fun getCalculateLiveByCreator(startDate: LocalDateTime, endDate: LocalDateTime, offset: Long, limit: Long) =
readByCreator(scope(SettlementSource.LIVE, startDate, endDate), offset, limit)
fun getCalculateContentByCreatorTotalCount(startDate: LocalDateTime, endDate: LocalDateTime): Int =
countByCreator(scope(SettlementSource.CONTENT_SALES, startDate, endDate))
fun getCalculateContentByCreator(startDate: LocalDateTime, endDate: LocalDateTime, offset: Long, limit: Long) =
readByCreator(scope(SettlementSource.CONTENT_SALES, startDate, endDate), offset, limit)
fun getCalculateCommunityByCreatorTotalCount(startDate: LocalDateTime, endDate: LocalDateTime): Int =
countByCreator(scope(SettlementSource.COMMUNITY_POST, startDate, endDate))
fun getCalculateCommunityByCreator(startDate: LocalDateTime, endDate: LocalDateTime, offset: Long, limit: Long) =
readByCreator(scope(SettlementSource.COMMUNITY_POST, startDate, endDate), offset, limit)
internal fun countLive(scope: SettlementScope) = count(scope, SettlementDisplayGrain.DETAIL, legacyLive(scope))
internal fun countContent(scope: SettlementScope) = count(scope, SettlementDisplayGrain.DETAIL, legacyContent(scope))
internal fun countDonation(scope: SettlementScope) = count(scope, SettlementDisplayGrain.DETAIL, legacyDonation(scope))
internal fun countCommunity(scope: SettlementScope) = count(scope, SettlementDisplayGrain.DETAIL, legacyCommunity(scope))
internal fun countCumulative(scope: SettlementScope) =
count(scope, SettlementDisplayGrain.CONTENT_CUMULATIVE, legacyCumulative(scope))
internal fun readLive(scope: SettlementScope, offset: Long, limit: Long) =
page(scope, SettlementDisplayGrain.DETAIL, offset, limit, legacyLive(scope), ::liveRow)
internal fun readContent(scope: SettlementScope, offset: Long, limit: Long) =
page(scope, SettlementDisplayGrain.DETAIL, offset, limit, legacyContent(scope), ::contentRow)
internal fun readDonation(scope: SettlementScope, offset: Long, limit: Long) =
page(scope, SettlementDisplayGrain.DETAIL, offset, limit, legacyDonation(scope), ::donationRow)
internal fun readCommunity(scope: SettlementScope, offset: Long, limit: Long) =
page(scope, SettlementDisplayGrain.DETAIL, offset, limit, legacyCommunity(scope), ::communityRow)
internal fun readCumulative(scope: SettlementScope, offset: Long, limit: Long) =
page(scope, SettlementDisplayGrain.CONTENT_CUMULATIVE, offset, limit, legacyCumulative(scope), ::cumulativeRow)
internal fun readAllLive(scope: SettlementScope) = all(scope, legacyLive(scope), ::liveRow)
internal fun readAllContent(scope: SettlementScope) = all(scope, legacyContent(scope), ::contentRow)
internal fun readAllDonation(scope: SettlementScope) = all(scope, legacyDonation(scope), ::donationRow)
internal fun readAllCommunity(scope: SettlementScope) = all(scope, legacyCommunity(scope), ::communityRow)
private fun countByCreator(scope: SettlementScope) = count(scope, SettlementDisplayGrain.CREATOR, legacyByCreator(scope))
private fun readByCreator(scope: SettlementScope, offset: Long, limit: Long) =
page(scope, SettlementDisplayGrain.CREATOR, offset, limit, legacyByCreator(scope)) { row ->
GetCalculateByCreatorQueryData(
row.creatorId,
row.description.creatorNickname,
Math.toIntExact(row.amount.totalCan),
row.metadata.appliedSettlementRatio,
row.metadata,
row.amount
)
}
private fun <T> count(scope: SettlementScope, grain: SettlementDisplayGrain, legacy: JPAQuery<T>): Int =
Math.toIntExact(
Math.addExact(
canonicalRepository.countDisplayRows(scope, grain),
legacy.select(Expressions.ONE).fetch().size.toLong()
)
)
private fun <T> page(
scope: SettlementScope,
grain: SettlementDisplayGrain,
offset: Long,
limit: Long
): List<GetCalculateLiveQueryData> {
val formattedDate = getFormattedDate(liveRoom.beginDateTime)
limit: Long,
legacy: JPAQuery<T>,
map: (SettlementDisplayRow) -> T
): List<T> {
require(offset >= 0 && limit > 0)
val postCount = canonicalRepository.countDisplayRows(scope, grain)
val post = if (offset < postCount) {
canonicalRepository.readDisplayPage(scope, grain, offset, limit).map(map)
} else {
emptyList()
}
if (post.size.toLong() == limit) return post
return post + legacy.offset((offset - postCount).coerceAtLeast(0L)).limit(limit - post.size).fetch()
}
return queryFactory
.select(
QGetCalculateLiveQueryData(
member.nickname,
formattedDate,
liveRoom.title,
liveRoom.id,
liveRoom.price,
useCan.canUsage,
useCan.id.count(),
useCan.can.add(useCan.rewardCan).sum(),
creatorSettlementRatio.liveSettlementRatio,
countrySettlementExpressions.newPolicyCan(useCan.createdAt, useCan.can.add(useCan.rewardCan)),
countrySettlementExpressions.newPolicyWeightedRatioCan(
useCan.createdAt,
useCan.can.add(useCan.rewardCan),
member.countryCode,
useCan.countryCode,
creatorSettlementRatio.liveSettlementRatio
)
)
private fun <T> all(scope: SettlementScope, legacy: JPAQuery<T>, map: (SettlementDisplayRow) -> T): List<T> {
val rows = mutableListOf<T>()
var offset = 0L
do {
val page = canonicalRepository.readDisplayPage(scope, SettlementDisplayGrain.DETAIL, offset, 256L)
page.forEach { rows.add(map(it)) }
offset += page.size
} while (page.size == 256)
rows.addAll(legacy.fetch())
return rows
}
private fun legacyLive(scope: SettlementScope): JPAQuery<GetCalculateLiveQueryData> {
val date = getFormattedDate(liveRoom.beginDateTime)
return queryFactory.select(
QGetCalculateLiveQueryData(
member.nickname, date, liveRoom.title, liveRoom.id, liveRoom.price, useCan.canUsage,
useCan.id.count(), useCan.can.add(useCan.rewardCan).sum(), creatorSettlementRatio.liveSettlementRatio
)
.from(useCan)
.innerJoin(useCan.room, liveRoom)
.innerJoin(liveRoom.member, member)
).from(useCan).innerJoin(useCan.room, liveRoom).innerJoin(liveRoom.member, member)
.leftJoin(creatorSettlementRatio)
.on(
member.id.eq(creatorSettlementRatio.member.id)
.and(creatorSettlementRatio.deletedAt.isNull)
)
.where(
useCan.isRefund.isFalse
.and(useCan.createdAt.goe(startDate))
.and(useCan.createdAt.loe(endDate))
)
.on(member.id.eq(creatorSettlementRatio.member.id).and(creatorSettlementRatio.deletedAt.isNull))
.where(useCan.isRefund.isFalse, legacyWindow(useCan.createdAt, scope))
.groupBy(liveRoom.id, useCan.canUsage, creatorSettlementRatio.liveSettlementRatio)
.orderBy(member.nickname.desc(), liveRoom.id.desc(), useCan.canUsage.desc(), formattedDate.desc())
.offset(offset)
.limit(limit)
.fetch()
.orderBy(
member.nickname.desc(),
liveRoom.id.desc(),
useCan.canUsage.desc(),
date.desc(),
creatorSettlementRatio.liveSettlementRatio.asc()
)
}
fun getCalculateContentListTotalCount(startDate: LocalDateTime, endDate: LocalDateTime): Int {
val orderFormattedDate = getFormattedDate(order.createdAt)
val pointGroup = CaseBuilder()
.`when`(order.point.loe(0)).then(0)
.otherwise(1)
val contentSettlementRatio = audioContent.settlementRatio.coalesce(creatorSettlementRatio.contentSettlementRatio)
return queryFactory
.select(audioContent.id)
.from(order)
.innerJoin(order.audioContent, audioContent)
.innerJoin(audioContent.member, member)
private fun legacyContent(scope: SettlementScope): JPAQuery<GetCalculateContentQueryData> {
val date = getFormattedDate(order.createdAt)
val pointGroup = CaseBuilder().`when`(order.point.loe(0)).then(0).otherwise(1)
val ratio = audioContent.settlementRatio.coalesce(creatorSettlementRatio.contentSettlementRatio)
return queryFactory.select(
QGetCalculateContentQueryData(
member.nickname, audioContent.title, getFormattedDate(audioContent.createdAt), date, order.type, order.can,
order.id.count(), order.can.sum(), order.point.sum(), ratio, audioContent.id, pointGroup
)
).from(order).innerJoin(order.audioContent, audioContent).innerJoin(audioContent.member, member)
.leftJoin(creatorSettlementRatio)
.on(
member.id.eq(creatorSettlementRatio.member.id)
.and(creatorSettlementRatio.deletedAt.isNull)
)
.on(member.id.eq(creatorSettlementRatio.member.id).and(creatorSettlementRatio.deletedAt.isNull))
.where(
order.createdAt.goe(startDate)
.and(order.createdAt.loe(endDate))
.and(order.isActive.isTrue)
order.isActive.isTrue,
legacyWindow(order.createdAt, scope.copy(creatorId = null)),
scope.creatorId?.let { order.creator.id.eq(it) }
)
.groupBy(
audioContent.id,
order.type,
orderFormattedDate,
order.can,
pointGroup,
contentSettlementRatio
.groupBy(audioContent.id, order.type, date, order.can, pointGroup, ratio)
.orderBy(
member.id.desc(),
date.desc(),
audioContent.id.asc(),
order.type.asc(),
order.can.asc(),
pointGroup.asc(),
ratio.asc()
)
.fetch()
.size
}
fun getCalculateContentList(
startDate: LocalDateTime,
endDate: LocalDateTime,
offset: Long,
limit: Long
): List<GetCalculateContentQueryData> {
val orderFormattedDate = getFormattedDate(order.createdAt)
val pointGroup = CaseBuilder()
.`when`(order.point.loe(0)).then(0)
.otherwise(1)
val contentSettlementRatio = audioContent.settlementRatio.coalesce(creatorSettlementRatio.contentSettlementRatio)
private fun legacyCumulative(scope: SettlementScope): JPAQuery<GetCumulativeSalesByContentQueryData> {
val pointGroup = CaseBuilder().`when`(order.point.loe(0)).then(0).otherwise(1)
val ratio = audioContent.settlementRatio.coalesce(creatorSettlementRatio.contentSettlementRatio)
return queryFactory.select(
QGetCumulativeSalesByContentQueryData(
member.nickname, audioContent.title, getFormattedDate(audioContent.createdAt), order.type, order.can,
order.id.count(), order.can.sum(), order.point.sum(), ratio, audioContent.id, pointGroup
)
).from(order).innerJoin(order.audioContent, audioContent).innerJoin(audioContent.member, member)
.leftJoin(creatorSettlementRatio)
.on(member.id.eq(creatorSettlementRatio.member.id).and(creatorSettlementRatio.deletedAt.isNull))
.where(order.isActive.isTrue, legacyWindow(order.createdAt, scope))
.groupBy(member.id, audioContent.id, order.type, order.can, pointGroup, ratio)
.orderBy(member.id.desc(), audioContent.id.desc(), order.type.asc(), order.can.asc(), pointGroup.asc(), ratio.asc())
}
return queryFactory
.select(
QGetCalculateContentQueryData(
member.nickname,
audioContent.title,
getFormattedDate(audioContent.createdAt),
orderFormattedDate,
order.type,
order.can,
order.id.count(),
order.can.sum(),
order.point.sum(),
contentSettlementRatio,
countrySettlementExpressions.newPolicyCan(order.createdAt, order.can),
countrySettlementExpressions.newPolicyWeightedRatioCan(
order.createdAt,
order.can,
member.countryCode,
useCan.countryCode,
contentSettlementRatio
)
private fun legacyDonation(scope: SettlementScope): JPAQuery<GetCalculateContentDonationQueryData> {
val date = getFormattedDate(useCan.createdAt)
return queryFactory.select(
QGetCalculateContentDonationQueryData(
member.nickname,
audioContent.title,
audioContent.price,
getFormattedDate(audioContent.createdAt),
date,
useCan.id.count(),
useCan.can.add(useCan.rewardCan).sum(),
audioContent.id
)
).from(useCan).innerJoin(useCan.audioContent, audioContent).innerJoin(audioContent.member, member)
.where(useCan.isRefund.isFalse, useCan.canUsage.eq(CanUsage.DONATION), legacyWindow(useCan.createdAt, scope))
.groupBy(date, audioContent.id)
.orderBy(member.id.asc(), date.desc(), audioContent.id.desc())
}
private fun legacyCommunity(scope: SettlementScope): JPAQuery<GetCalculateCommunityPostQueryData> {
val date = getFormattedDate(useCan.createdAt)
return queryFactory.select(
QGetCalculateCommunityPostQueryData(
member.nickname,
Expressions.stringTemplate("substring({0}, 1, 10)", creatorCommunity.content),
date,
creatorCommunity.price,
useCan.id.count(),
useCan.can.add(useCan.rewardCan).sum(),
creatorSettlementRatio.communitySettlementRatio,
creatorCommunity.id
)
).from(useCan).innerJoin(useCan.communityPost, creatorCommunity).innerJoin(creatorCommunity.member, member)
.leftJoin(creatorSettlementRatio)
.on(member.id.eq(creatorSettlementRatio.member.id).and(creatorSettlementRatio.deletedAt.isNull))
.where(
useCan.isRefund.isFalse,
useCan.canUsage.eq(CanUsage.PAID_COMMUNITY_POST),
legacyWindow(useCan.createdAt, scope)
)
.groupBy(date, creatorCommunity.id, creatorSettlementRatio.communitySettlementRatio)
.orderBy(
member.id.asc(),
date.desc(),
creatorCommunity.id.desc(),
creatorSettlementRatio.communitySettlementRatio.asc()
)
}
private fun legacyByCreator(scope: SettlementScope): JPAQuery<GetCalculateByCreatorQueryData> {
val sales = scope.source == SettlementSource.CONTENT_SALES
val ratio = when (scope.source) {
SettlementSource.LIVE -> creatorSettlementRatio.liveSettlementRatio
SettlementSource.CONTENT_SALES -> creatorSettlementRatio.contentSettlementRatio
SettlementSource.COMMUNITY_POST -> creatorSettlementRatio.communitySettlementRatio
else -> error("Unsupported creator rollup: ${scope.source}")
}
val query = queryFactory.select(
QGetCalculateByCreatorQueryData(
member.id,
member.nickname,
if (sales) order.can.sum() else useCan.can.add(useCan.rewardCan).sum(),
ratio,
Expressions.constant(scope.source.name)
)
)
when (scope.source) {
SettlementSource.LIVE -> query.from(useCan).innerJoin(useCan.room, liveRoom).innerJoin(liveRoom.member, member)
.where(useCan.isRefund.isFalse, legacyWindow(useCan.createdAt, scope))
SettlementSource.CONTENT_SALES -> query.from(order).innerJoin(order.audioContent, audioContent)
.innerJoin(audioContent.member, member).where(order.isActive.isTrue, legacyWindow(order.createdAt, scope))
SettlementSource.COMMUNITY_POST -> query.from(useCan).innerJoin(useCan.communityPost, creatorCommunity)
.innerJoin(creatorCommunity.member, member).where(
useCan.isRefund.isFalse,
useCan.canUsage.eq(CanUsage.PAID_COMMUNITY_POST),
legacyWindow(useCan.createdAt, scope)
)
)
.from(order)
.innerJoin(order.audioContent, audioContent)
.innerJoin(audioContent.member, member)
.leftJoin(useCan).on(useCan.order.id.eq(order.id))
.leftJoin(creatorSettlementRatio)
.on(
member.id.eq(creatorSettlementRatio.member.id)
.and(creatorSettlementRatio.deletedAt.isNull)
)
.where(
order.createdAt.goe(startDate)
.and(order.createdAt.loe(endDate))
.and(order.isActive.isTrue)
)
.groupBy(
audioContent.id,
order.type,
orderFormattedDate,
order.can,
pointGroup,
contentSettlementRatio
)
.orderBy(member.id.desc(), orderFormattedDate.desc(), audioContent.id.asc())
.offset(offset)
.limit(limit)
.fetch()
else -> error("Unsupported creator rollup: ${scope.source}")
}
return query.leftJoin(creatorSettlementRatio)
.on(member.id.eq(creatorSettlementRatio.member.id).and(creatorSettlementRatio.deletedAt.isNull))
.groupBy(member.id, ratio).orderBy(member.id.desc(), ratio.asc())
}
private fun getFormattedDate(dateTimePath: DateTimePath<LocalDateTime>): StringTemplate {
return Expressions.stringTemplate(
"DATE_FORMAT(CONVERT_TZ({0}, 'UTC', 'Asia/Seoul'), '%Y-%m-%d')",
dateTimePath
private fun legacyWindow(event: DateTimePath<LocalDateTime>, scope: SettlementScope): BooleanBuilder {
val predicate = BooleanBuilder(event.lt(policy.effectiveAtUtc))
scope.window.startInclusiveUtc?.let { predicate.and(event.goe(it)) }
scope.window.endUtc?.let { predicate.and(if (scope.window.endExclusive) event.lt(it) else event.loe(it)) }
scope.creatorId?.let { predicate.and(member.id.eq(it)) }
return predicate
}
private fun liveRow(row: SettlementDisplayRow): GetCalculateLiveQueryData {
val grain = requireNotNull(row.sourceGrain)
return GetCalculateLiveQueryData(
row.description.creatorNickname, requireNotNull(row.description.displayDate), requireNotNull(row.description.title),
grain.sourceId, requireNotNull(row.description.sourcePrice), requireNotNull(grain.canUsage), row.transactionCount,
Math.toIntExact(row.amount.totalCan), row.metadata.appliedSettlementRatio, row.metadata, row.amount
)
}
fun getCumulativeSalesByContentTotalCount(): Int {
val pointGroup = CaseBuilder()
.`when`(order.point.loe(0)).then(0)
.otherwise(1)
val contentSettlementRatio = audioContent.settlementRatio.coalesce(creatorSettlementRatio.contentSettlementRatio)
return queryFactory
.select(audioContent.id)
.from(order)
.innerJoin(order.audioContent, audioContent)
.innerJoin(audioContent.member, member)
.leftJoin(creatorSettlementRatio)
.on(
member.id.eq(creatorSettlementRatio.member.id)
.and(creatorSettlementRatio.deletedAt.isNull)
)
.where(order.isActive.isTrue)
.groupBy(member.id, audioContent.id, order.type, order.can, pointGroup, contentSettlementRatio)
.fetch()
.size
private fun contentRow(row: SettlementDisplayRow): GetCalculateContentQueryData {
val grain = requireNotNull(row.sourceGrain)
return GetCalculateContentQueryData(
row.description.creatorNickname, requireNotNull(row.description.title),
requireNotNull(row.description.registrationDate),
requireNotNull(row.description.displayDate), requireNotNull(grain.orderType), requireNotNull(grain.orderPrice),
row.transactionCount, Math.toIntExact(row.amount.totalCan), Math.toIntExact(row.totalPoint),
row.metadata.appliedSettlementRatio, row.metadata, row.amount
)
}
fun getCumulativeSalesByContent(offset: Long, limit: Long): List<GetCumulativeSalesByContentQueryData> {
val pointGroup = CaseBuilder()
.`when`(order.point.loe(0)).then(0)
.otherwise(1)
val contentSettlementRatio = audioContent.settlementRatio.coalesce(creatorSettlementRatio.contentSettlementRatio)
return queryFactory
.select(
QGetCumulativeSalesByContentQueryData(
member.nickname,
audioContent.title,
getFormattedDate(audioContent.createdAt),
order.type,
order.can,
order.id.count(),
order.can.sum(),
order.point.sum(),
contentSettlementRatio,
countrySettlementExpressions.newPolicyCan(order.createdAt, order.can),
countrySettlementExpressions.newPolicyWeightedRatioCan(
order.createdAt,
order.can,
member.countryCode,
useCan.countryCode,
contentSettlementRatio
)
)
)
.from(order)
.innerJoin(order.audioContent, audioContent)
.innerJoin(audioContent.member, member)
.leftJoin(useCan).on(useCan.order.id.eq(order.id))
.leftJoin(creatorSettlementRatio)
.on(
member.id.eq(creatorSettlementRatio.member.id)
.and(creatorSettlementRatio.deletedAt.isNull)
)
.where(order.isActive.isTrue)
.groupBy(
member.id,
audioContent.id,
order.type,
order.can,
pointGroup,
contentSettlementRatio
)
.offset(offset)
.limit(limit)
.orderBy(member.id.desc(), audioContent.id.desc())
.fetch()
private fun cumulativeRow(row: SettlementDisplayRow): GetCumulativeSalesByContentQueryData {
val grain = requireNotNull(row.sourceGrain)
return GetCumulativeSalesByContentQueryData(
row.description.creatorNickname, requireNotNull(row.description.title),
requireNotNull(row.description.registrationDate),
requireNotNull(grain.orderType), requireNotNull(grain.orderPrice), row.transactionCount,
Math.toIntExact(row.amount.totalCan), Math.toIntExact(row.totalPoint), row.metadata.appliedSettlementRatio,
row.metadata, row.amount
)
}
fun getCalculateContentDonationListTotalCount(startDate: LocalDateTime, endDate: LocalDateTime): Int {
val donationFormattedDate = getFormattedDate(useCan.createdAt)
private fun donationRow(row: SettlementDisplayRow) = GetCalculateContentDonationQueryData(
row.description.creatorNickname, requireNotNull(row.description.title), requireNotNull(row.description.sourcePrice),
requireNotNull(row.description.registrationDate), requireNotNull(row.description.displayDate), row.transactionCount,
Math.toIntExact(row.amount.totalCan), row.metadata, row.amount
)
return queryFactory
.select(audioContent.id)
.from(useCan)
.innerJoin(useCan.audioContent, audioContent)
.innerJoin(audioContent.member, member)
.where(
useCan.isRefund.isFalse
.and(useCan.canUsage.eq(CanUsage.DONATION))
.and(useCan.createdAt.goe(startDate))
.and(useCan.createdAt.loe(endDate))
)
.groupBy(donationFormattedDate, audioContent.id)
.fetch()
.size
}
private fun communityRow(row: SettlementDisplayRow) = GetCalculateCommunityPostQueryData(
row.description.creatorNickname, requireNotNull(row.description.title), requireNotNull(row.description.displayDate),
requireNotNull(row.description.sourcePrice), row.transactionCount, Math.toIntExact(row.amount.totalCan),
row.metadata.appliedSettlementRatio, row.metadata, row.amount
)
fun getCalculateContentDonationList(
startDate: LocalDateTime,
endDate: LocalDateTime,
offset: Long,
limit: Long
): List<GetCalculateContentDonationQueryData> {
val donationFormattedDate = getFormattedDate(useCan.createdAt)
private fun scope(source: SettlementSource, start: LocalDateTime? = null, end: LocalDateTime? = null) =
SettlementScope(source, SettlementWindow(start, end, false))
return queryFactory
.select(
QGetCalculateContentDonationQueryData(
member.nickname,
audioContent.title,
audioContent.price,
getFormattedDate(audioContent.createdAt),
donationFormattedDate,
useCan.id.count(),
useCan.can.add(useCan.rewardCan).sum(),
countrySettlementExpressions.newPolicyCan(useCan.createdAt, useCan.can.add(useCan.rewardCan)),
countrySettlementExpressions.newPolicyWeightedRatioCan(
useCan.createdAt,
useCan.can.add(useCan.rewardCan),
member.countryCode,
useCan.countryCode
)
)
)
.from(useCan)
.innerJoin(useCan.audioContent, audioContent)
.innerJoin(audioContent.member, member)
.where(
useCan.isRefund.isFalse
.and(useCan.canUsage.eq(CanUsage.DONATION))
.and(useCan.createdAt.goe(startDate))
.and(useCan.createdAt.loe(endDate))
)
.groupBy(donationFormattedDate, audioContent.id)
.orderBy(member.id.asc(), donationFormattedDate.desc(), audioContent.id.desc())
.offset(offset)
.limit(limit)
.fetch()
}
fun getCalculateCommunityPostTotalCount(startDate: LocalDateTime?, endDate: LocalDateTime?): Int {
val formattedDate = getFormattedDate(useCan.createdAt)
return queryFactory
.select(creatorCommunity.id)
.from(useCan)
.innerJoin(useCan.communityPost, creatorCommunity)
.innerJoin(creatorCommunity.member, member)
.where(
useCan.isRefund.isFalse
.and(useCan.canUsage.eq(CanUsage.PAID_COMMUNITY_POST))
.and(useCan.createdAt.goe(startDate))
.and(useCan.createdAt.loe(endDate))
)
.groupBy(formattedDate, creatorCommunity.id)
.fetch()
.size
}
fun getCalculateCommunityPostList(
startDate: LocalDateTime?,
endDate: LocalDateTime?,
offset: Long,
limit: Long
): List<GetCalculateCommunityPostQueryData> {
val formattedDate = getFormattedDate(useCan.createdAt)
return queryFactory
.select(
QGetCalculateCommunityPostQueryData(
member.nickname,
Expressions.stringTemplate("substring({0}, 1, 10)", creatorCommunity.content),
formattedDate,
creatorCommunity.price,
useCan.id.count(),
useCan.can.add(useCan.rewardCan).sum(),
creatorSettlementRatio.communitySettlementRatio,
countrySettlementExpressions.newPolicyCan(useCan.createdAt, useCan.can.add(useCan.rewardCan)),
countrySettlementExpressions.newPolicyWeightedRatioCan(
useCan.createdAt,
useCan.can.add(useCan.rewardCan),
member.countryCode,
useCan.countryCode,
creatorSettlementRatio.communitySettlementRatio
)
)
)
.from(useCan)
.innerJoin(useCan.communityPost, creatorCommunity)
.innerJoin(creatorCommunity.member, member)
.leftJoin(creatorSettlementRatio)
.on(
member.id.eq(creatorSettlementRatio.member.id)
.and(creatorSettlementRatio.deletedAt.isNull)
)
.where(
useCan.isRefund.isFalse
.and(useCan.canUsage.eq(CanUsage.PAID_COMMUNITY_POST))
.and(useCan.createdAt.goe(startDate))
.and(useCan.createdAt.loe(endDate))
)
.groupBy(formattedDate, creatorCommunity.id, creatorSettlementRatio.communitySettlementRatio)
.orderBy(member.id.asc(), formattedDate.desc(), creatorCommunity.id.desc())
.offset(offset)
.limit(limit)
.fetch()
}
fun getCalculateLiveByCreatorTotalCount(startDate: LocalDateTime, endDate: LocalDateTime): Int {
return queryFactory
.select(member.id)
.from(useCan)
.innerJoin(useCan.room, liveRoom)
.innerJoin(liveRoom.member, member)
.leftJoin(creatorSettlementRatio)
.on(
member.id.eq(creatorSettlementRatio.member.id)
.and(creatorSettlementRatio.deletedAt.isNull)
)
.where(
useCan.isRefund.isFalse
.and(useCan.createdAt.goe(startDate))
.and(useCan.createdAt.loe(endDate))
)
.groupBy(member.id)
.fetch()
.size
}
fun getCalculateLiveByCreator(
startDate: LocalDateTime,
endDate: LocalDateTime,
offset: Long,
limit: Long
): List<GetCalculateByCreatorQueryData> {
return queryFactory
.select(
QGetCalculateByCreatorQueryData(
member.id,
member.nickname,
useCan.can.add(useCan.rewardCan).sum(),
creatorSettlementRatio.liveSettlementRatio,
countrySettlementExpressions.newPolicyCan(useCan.createdAt, useCan.can.add(useCan.rewardCan)),
countrySettlementExpressions.newPolicyWeightedRatioCan(
useCan.createdAt,
useCan.can.add(useCan.rewardCan),
member.countryCode,
useCan.countryCode,
creatorSettlementRatio.liveSettlementRatio
)
)
)
.from(useCan)
.innerJoin(useCan.room, liveRoom)
.innerJoin(liveRoom.member, member)
.leftJoin(creatorSettlementRatio)
.on(
member.id.eq(creatorSettlementRatio.member.id)
.and(creatorSettlementRatio.deletedAt.isNull)
)
.where(
useCan.isRefund.isFalse
.and(useCan.createdAt.goe(startDate))
.and(useCan.createdAt.loe(endDate))
)
.groupBy(member.id, creatorSettlementRatio.liveSettlementRatio)
.orderBy(member.id.desc())
.offset(offset)
.limit(limit)
.fetch()
}
fun getCalculateContentByCreatorTotalCount(startDate: LocalDateTime, endDate: LocalDateTime): Int {
return queryFactory
.select(member.id)
.from(order)
.innerJoin(order.audioContent, audioContent)
.innerJoin(audioContent.member, member)
.leftJoin(creatorSettlementRatio)
.on(
member.id.eq(creatorSettlementRatio.member.id)
.and(creatorSettlementRatio.deletedAt.isNull)
)
.where(
order.createdAt.goe(startDate)
.and(order.createdAt.loe(endDate))
.and(order.isActive.isTrue)
)
.groupBy(member.id)
.fetch()
.size
}
fun getCalculateContentByCreator(
startDate: LocalDateTime,
endDate: LocalDateTime,
offset: Long,
limit: Long
): List<GetCalculateByCreatorQueryData> {
return queryFactory
.select(
QGetCalculateByCreatorQueryData(
member.id,
member.nickname,
order.can.sum(),
creatorSettlementRatio.contentSettlementRatio,
countrySettlementExpressions.newPolicyCan(order.createdAt, order.can),
countrySettlementExpressions.newPolicyWeightedRatioCan(
order.createdAt,
order.can,
member.countryCode,
useCan.countryCode,
audioContent.settlementRatio.coalesce(creatorSettlementRatio.contentSettlementRatio)
)
)
)
.from(order)
.innerJoin(order.audioContent, audioContent)
.innerJoin(audioContent.member, member)
.leftJoin(useCan).on(useCan.order.id.eq(order.id))
.leftJoin(creatorSettlementRatio)
.on(
member.id.eq(creatorSettlementRatio.member.id)
.and(creatorSettlementRatio.deletedAt.isNull)
)
.where(
order.createdAt.goe(startDate)
.and(order.createdAt.loe(endDate))
.and(order.isActive.isTrue)
)
.groupBy(member.id, creatorSettlementRatio.contentSettlementRatio)
.orderBy(member.id.desc())
.offset(offset)
.limit(limit)
.fetch()
}
fun getCalculateCommunityByCreatorTotalCount(startDate: LocalDateTime, endDate: LocalDateTime): Int {
return queryFactory
.select(member.id)
.from(useCan)
.innerJoin(useCan.communityPost, creatorCommunity)
.innerJoin(creatorCommunity.member, member)
.leftJoin(creatorSettlementRatio)
.on(
member.id.eq(creatorSettlementRatio.member.id)
.and(creatorSettlementRatio.deletedAt.isNull)
)
.where(
useCan.isRefund.isFalse
.and(useCan.canUsage.eq(CanUsage.PAID_COMMUNITY_POST))
.and(useCan.createdAt.goe(startDate))
.and(useCan.createdAt.loe(endDate))
)
.groupBy(member.id)
.fetch()
.size
}
fun getCalculateCommunityByCreator(
startDate: LocalDateTime,
endDate: LocalDateTime,
offset: Long,
limit: Long
): List<GetCalculateByCreatorQueryData> {
return queryFactory
.select(
QGetCalculateByCreatorQueryData(
member.id,
member.nickname,
useCan.can.add(useCan.rewardCan).sum(),
creatorSettlementRatio.communitySettlementRatio,
countrySettlementExpressions.newPolicyCan(useCan.createdAt, useCan.can.add(useCan.rewardCan)),
countrySettlementExpressions.newPolicyWeightedRatioCan(
useCan.createdAt,
useCan.can.add(useCan.rewardCan),
member.countryCode,
useCan.countryCode,
creatorSettlementRatio.communitySettlementRatio
)
)
)
.from(useCan)
.innerJoin(useCan.communityPost, creatorCommunity)
.innerJoin(creatorCommunity.member, member)
.leftJoin(creatorSettlementRatio)
.on(
member.id.eq(creatorSettlementRatio.member.id)
.and(creatorSettlementRatio.deletedAt.isNull)
)
.where(
useCan.isRefund.isFalse
.and(useCan.canUsage.eq(CanUsage.PAID_COMMUNITY_POST))
.and(useCan.createdAt.goe(startDate))
.and(useCan.createdAt.loe(endDate))
)
.groupBy(member.id, creatorSettlementRatio.communitySettlementRatio)
.orderBy(member.id.desc())
.offset(offset)
.limit(limit)
.fetch()
}
private fun getFormattedDate(path: DateTimePath<LocalDateTime>): StringTemplate = Expressions.stringTemplate(
"DATE_FORMAT(CONVERT_TZ({0}, 'UTC', 'Asia/Seoul'), '%Y-%m-%d')",
path
)
}
@@ -16,11 +16,18 @@ import kr.co.vividnext.sodalive.extensions.convertLocalDateTime
import kr.co.vividnext.sodalive.i18n.LangContext
import kr.co.vividnext.sodalive.i18n.SodaMessageSource
import kr.co.vividnext.sodalive.live.room.LiveRoomRepository
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementCountryRelation
import kr.co.vividnext.sodalive.v2.settlement.dto.SettlementRateMetadata
import org.apache.poi.ss.usermodel.Row
import org.apache.poi.ss.usermodel.Sheet
import org.apache.poi.xssf.streaming.SXSSFWorkbook
import org.springframework.data.repository.findByIdOrNull
import org.springframework.stereotype.Service
import org.springframework.transaction.PlatformTransactionManager
import org.springframework.transaction.TransactionDefinition
import org.springframework.transaction.annotation.Isolation
import org.springframework.transaction.annotation.Transactional
import org.springframework.transaction.support.TransactionTemplate
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody
import java.time.LocalDateTime
@@ -32,7 +39,8 @@ class AdminCalculateService(
private val chargeRepository: ChargeRepository,
private val liveRoomRepository: LiveRoomRepository,
private val messageSource: SodaMessageSource,
private val langContext: LangContext
private val langContext: LangContext,
private val transactionManager: PlatformTransactionManager
) {
private fun formatMessage(key: String, vararg args: Any): String {
val template = messageSource.getMessage(key, langContext.lang).orEmpty()
@@ -96,7 +104,7 @@ class AdminCalculateService(
}
}
@Transactional(readOnly = true)
@Transactional(readOnly = true, isolation = Isolation.REPEATABLE_READ)
fun getCalculateLive(
startDateStr: String,
endDateStr: String,
@@ -113,7 +121,7 @@ class AdminCalculateService(
return GetCalculateLiveListResponse(totalCount, items)
}
@Transactional(readOnly = true)
@Transactional(readOnly = true, isolation = Isolation.REPEATABLE_READ)
fun getCalculateContentList(
startDateStr: String,
endDateStr: String,
@@ -130,7 +138,7 @@ class AdminCalculateService(
return GetCalculateContentListResponse(totalCount, items)
}
@Transactional(readOnly = true)
@Transactional(readOnly = true, isolation = Isolation.REPEATABLE_READ)
fun getCumulativeSalesByContent(offset: Long, limit: Long): GetCumulativeSalesByContentResponse {
val totalCount = repository.getCumulativeSalesByContentTotalCount()
val items = repository
@@ -140,7 +148,7 @@ class AdminCalculateService(
return GetCumulativeSalesByContentResponse(totalCount, items)
}
@Transactional(readOnly = true)
@Transactional(readOnly = true, isolation = Isolation.REPEATABLE_READ)
fun getCalculateContentDonationList(
startDateStr: String,
endDateStr: String,
@@ -157,7 +165,7 @@ class AdminCalculateService(
return GetCalculateContentDonationListResponse(totalCount, items)
}
@Transactional(readOnly = true)
@Transactional(readOnly = true, isolation = Isolation.REPEATABLE_READ)
fun getCalculateCommunityPost(
startDateStr: String,
endDateStr: String,
@@ -175,7 +183,7 @@ class AdminCalculateService(
return GetCreatorCalculateCommunityPostResponse(totalCount, items)
}
@Transactional(readOnly = true)
@Transactional(readOnly = true, isolation = Isolation.REPEATABLE_READ)
fun getCalculateLiveByCreator(
startDateStr: String,
endDateStr: String,
@@ -193,7 +201,7 @@ class AdminCalculateService(
GetCalculateByCreatorResponse(totalCount, items)
}
@Transactional(readOnly = true)
@Transactional(readOnly = true, isolation = Isolation.REPEATABLE_READ)
fun getCalculateContentByCreator(
startDateStr: String,
endDateStr: String,
@@ -211,7 +219,7 @@ class AdminCalculateService(
GetCalculateByCreatorResponse(totalCount, items)
}
@Transactional(readOnly = true)
@Transactional(readOnly = true, isolation = Isolation.REPEATABLE_READ)
fun getCalculateCommunityByCreator(
startDateStr: String,
endDateStr: String,
@@ -229,17 +237,8 @@ class AdminCalculateService(
GetCalculateByCreatorResponse(totalCount, items)
}
@Transactional(readOnly = true)
fun downloadCalculateLiveExcel(startDateStr: String, endDateStr: String): StreamingResponseBody {
val (startDate, endDate) = toDateRange(startDateStr, endDateStr)
val totalCount = repository.getCalculateLiveTotalCount(startDate, endDate)
val items = if (totalCount == 0) {
emptyList()
} else {
repository
.getCalculateLive(startDate, endDate, 0L, totalCount.toLong())
.map { it.toGetCalculateLiveResponse() }
}
return createExcelStream(
sheetName = "라이브 정산",
@@ -258,8 +257,13 @@ class AdminCalculateService(
"입금액"
)
) { sheet ->
items.forEachIndexed { index, item ->
val row = sheet.createRow(index + 1)
writePagedRows(
sheet,
{ repository.getCalculateLiveTotalCount(startDate, endDate) },
{ offset, limit ->
repository.getCalculateLive(startDate, endDate, offset, limit).map { it.toGetCalculateLiveResponse() }
}
) { row, item ->
row.createCell(0).setCellValue(item.nickname)
row.createCell(1).setCellValue(item.date)
row.createCell(2).setCellValue(item.title)
@@ -272,21 +276,13 @@ class AdminCalculateService(
row.createCell(9).setCellValue(item.settlementAmount.toDouble())
row.createCell(10).setCellValue(item.tax.toDouble())
row.createCell(11).setCellValue(item.depositAmount.toDouble())
writeMetadata(row, 12, item.metadata)
}
}
}
@Transactional(readOnly = true)
fun downloadCalculateContentListExcel(startDateStr: String, endDateStr: String): StreamingResponseBody {
val (startDate, endDate) = toDateRange(startDateStr, endDateStr)
val totalCount = repository.getCalculateContentListTotalCount(startDate, endDate)
val items = if (totalCount == 0) {
emptyList()
} else {
repository
.getCalculateContentList(startDate, endDate, 0L, totalCount.toLong())
.map { it.toGetCalculateContentResponse() }
}
return createExcelStream(
sheetName = "콘텐츠 정산",
@@ -306,8 +302,14 @@ class AdminCalculateService(
"입금액"
)
) { sheet ->
items.forEachIndexed { index, item ->
val row = sheet.createRow(index + 1)
writePagedRows(
sheet,
{ repository.getCalculateContentListTotalCount(startDate, endDate) },
{ offset, limit ->
repository.getCalculateContentList(startDate, endDate, offset, limit)
.map { it.toGetCalculateContentResponse() }
}
) { row, item ->
row.createCell(0).setCellValue(item.nickname)
row.createCell(1).setCellValue(item.title)
row.createCell(2).setCellValue(item.registrationDate)
@@ -321,21 +323,13 @@ class AdminCalculateService(
row.createCell(10).setCellValue(item.settlementAmount.toDouble())
row.createCell(11).setCellValue(item.tax.toDouble())
row.createCell(12).setCellValue(item.depositAmount.toDouble())
writeMetadata(row, 13, item.metadata)
}
}
}
@Transactional(readOnly = true)
fun downloadCalculateContentDonationListExcel(startDateStr: String, endDateStr: String): StreamingResponseBody {
val (startDate, endDate) = toDateRange(startDateStr, endDateStr)
val totalCount = repository.getCalculateContentDonationListTotalCount(startDate, endDate)
val items = if (totalCount == 0) {
emptyList()
} else {
repository
.getCalculateContentDonationList(startDate, endDate, 0L, totalCount.toLong())
.map { it.toGetCalculateContentDonationResponse() }
}
return createExcelStream(
sheetName = "콘텐츠 후원 정산",
@@ -354,8 +348,14 @@ class AdminCalculateService(
"입금액"
)
) { sheet ->
items.forEachIndexed { index, item ->
val row = sheet.createRow(index + 1)
writePagedRows(
sheet,
{ repository.getCalculateContentDonationListTotalCount(startDate, endDate) },
{ offset, limit ->
repository.getCalculateContentDonationList(startDate, endDate, offset, limit)
.map { it.toGetCalculateContentDonationResponse() }
}
) { row, item ->
row.createCell(0).setCellValue(item.nickname)
row.createCell(1).setCellValue(item.title)
row.createCell(2).setCellValue(item.paidOrFree)
@@ -368,21 +368,13 @@ class AdminCalculateService(
row.createCell(9).setCellValue(item.settlementAmount.toDouble())
row.createCell(10).setCellValue(item.tax.toDouble())
row.createCell(11).setCellValue(item.depositAmount.toDouble())
writeMetadata(row, 12, item.metadata)
}
}
}
@Transactional(readOnly = true)
fun downloadCalculateCommunityPostExcel(startDateStr: String, endDateStr: String): StreamingResponseBody {
val (startDate, endDate) = toDateRange(startDateStr, endDateStr)
val totalCount = repository.getCalculateCommunityPostTotalCount(startDate, endDate)
val items = if (totalCount == 0) {
emptyList()
} else {
repository
.getCalculateCommunityPostList(startDate, endDate, 0L, totalCount.toLong())
.map { it.toGetCalculateCommunityPostResponse() }
}
return createExcelStream(
sheetName = "커뮤니티 정산",
@@ -400,8 +392,14 @@ class AdminCalculateService(
"입금액"
)
) { sheet ->
items.forEachIndexed { index, item ->
val row = sheet.createRow(index + 1)
writePagedRows(
sheet,
{ repository.getCalculateCommunityPostTotalCount(startDate, endDate) },
{ offset, limit ->
repository.getCalculateCommunityPostList(startDate, endDate, offset, limit)
.map { it.toGetCalculateCommunityPostResponse() }
}
) { row, item ->
row.createCell(0).setCellValue(item.nickname)
row.createCell(1).setCellValue(item.title)
row.createCell(2).setCellValue(item.date)
@@ -413,58 +411,48 @@ class AdminCalculateService(
row.createCell(8).setCellValue(item.settlementAmount.toDouble())
row.createCell(9).setCellValue(item.tax.toDouble())
row.createCell(10).setCellValue(item.depositAmount.toDouble())
writeMetadata(row, 11, item.metadata)
}
}
}
@Transactional(readOnly = true)
fun downloadCalculateLiveByCreatorExcel(startDateStr: String, endDateStr: String): StreamingResponseBody {
val (startDate, endDate) = toDateRange(startDateStr, endDateStr)
val totalCount = repository.getCalculateLiveByCreatorTotalCount(startDate, endDate)
val items = if (totalCount == 0) {
emptyList()
} else {
repository
.getCalculateLiveByCreator(startDate, endDate, 0L, totalCount.toLong())
.map { it.toGetCalculateByCreator() }
}
return createCalculateByCreatorExcel("크리에이터별 라이브 정산", items)
return createCalculateByCreatorExcel(
"크리에이터별 라이브 정산",
{ repository.getCalculateLiveByCreatorTotalCount(startDate, endDate) },
{ offset, limit ->
repository.getCalculateLiveByCreator(startDate, endDate, offset, limit).map { it.toGetCalculateByCreator() }
}
)
}
@Transactional(readOnly = true)
fun downloadCalculateContentByCreatorExcel(startDateStr: String, endDateStr: String): StreamingResponseBody {
val (startDate, endDate) = toDateRange(startDateStr, endDateStr)
val totalCount = repository.getCalculateContentByCreatorTotalCount(startDate, endDate)
val items = if (totalCount == 0) {
emptyList()
} else {
repository
.getCalculateContentByCreator(startDate, endDate, 0L, totalCount.toLong())
.map { it.toGetCalculateByCreator() }
}
return createCalculateByCreatorExcel("크리에이터별 콘텐츠 정산", items)
return createCalculateByCreatorExcel(
"크리에이터별 콘텐츠 정산",
{ repository.getCalculateContentByCreatorTotalCount(startDate, endDate) },
{ offset, limit ->
repository.getCalculateContentByCreator(startDate, endDate, offset, limit).map { it.toGetCalculateByCreator() }
}
)
}
@Transactional(readOnly = true)
fun downloadCalculateCommunityByCreatorExcel(startDateStr: String, endDateStr: String): StreamingResponseBody {
val (startDate, endDate) = toDateRange(startDateStr, endDateStr)
val totalCount = repository.getCalculateCommunityByCreatorTotalCount(startDate, endDate)
val items = if (totalCount == 0) {
emptyList()
} else {
repository
.getCalculateCommunityByCreator(startDate, endDate, 0L, totalCount.toLong())
.map { it.toGetCalculateByCreator() }
}
return createCalculateByCreatorExcel("크리에이터별 커뮤니티 정산", items)
return createCalculateByCreatorExcel(
"크리에이터별 커뮤니티 정산",
{ repository.getCalculateCommunityByCreatorTotalCount(startDate, endDate) },
{ offset, limit ->
repository.getCalculateCommunityByCreator(startDate, endDate, offset, limit).map { it.toGetCalculateByCreator() }
}
)
}
private fun createCalculateByCreatorExcel(
sheetName: String,
items: List<GetCalculateByCreatorItem>
count: () -> Int,
load: (Long, Long) -> List<GetCalculateByCreatorItem>
): StreamingResponseBody {
return createExcelStream(
sheetName = sheetName,
@@ -479,8 +467,7 @@ class AdminCalculateService(
"입금액"
)
) { sheet ->
items.forEachIndexed { index, item ->
val row = sheet.createRow(index + 1)
writePagedRows(sheet, count, load) { row, item ->
row.createCell(0).setCellValue(item.creatorId.toDouble())
row.createCell(1).setCellValue(item.nickname)
row.createCell(2).setCellValue(item.totalCan.toDouble())
@@ -489,6 +476,7 @@ class AdminCalculateService(
row.createCell(5).setCellValue(item.settlementAmount.toDouble())
row.createCell(6).setCellValue(item.tax.toDouble())
row.createCell(7).setCellValue(item.depositAmount.toDouble())
writeMetadata(row, 8, item.metadata)
}
}
}
@@ -503,20 +491,59 @@ class AdminCalculateService(
try {
val sheet = workbook.createSheet(sheetName)
val headerRow = sheet.createRow(0)
headers.forEachIndexed { index, value ->
headerRow.createCell(index).setCellValue(value)
}
(headers + listOf("행 식별키", "거래 구분", "크리에이터 정산 비율(%)", "에이전트 번호", "에이전트 정산 비율(%)"))
.forEachIndexed { index, value ->
headerRow.createCell(index).setCellValue(value)
}
writeRows(sheet)
TransactionTemplate(transactionManager).apply {
isReadOnly = true
isolationLevel = TransactionDefinition.ISOLATION_REPEATABLE_READ
propagationBehavior = TransactionDefinition.PROPAGATION_REQUIRES_NEW
}.executeWithoutResult { writeRows(sheet) }
workbook.write(outputStream)
outputStream.flush()
} finally {
workbook.dispose()
workbook.close()
try {
workbook.dispose()
} finally {
workbook.close()
}
}
}
}
private fun <T> writePagedRows(
sheet: Sheet,
count: () -> Int,
load: (Long, Long) -> List<T>,
write: (Row, T) -> Unit
) {
val total = count().toLong()
var offset = 0L
while (offset < total) {
val limit = minOf(256L, total - offset)
val page = load(offset, limit)
page.forEachIndexed { index, item -> write(sheet.createRow(Math.toIntExact(offset + index + 1)), item) }
offset += limit
}
}
private fun writeMetadata(row: Row, start: Int, metadata: SettlementRateMetadata) {
row.createCell(start).setCellValue(metadata.rowKey)
row.createCell(start + 1).setCellValue(
when (metadata.countryRelation) {
SettlementCountryRelation.SAME_COUNTRY -> "동일 국가"
SettlementCountryRelation.CROSS_COUNTRY -> "다른 국가"
SettlementCountryRelation.LEGACY -> "기존 정책"
null -> "정보 미제공"
}
)
row.createCell(start + 2).apply { metadata.appliedSettlementRatio?.let { setCellValue(it.toDouble()) } }
row.createCell(start + 3).apply { metadata.agentId?.let { setCellValue(it.toString()) } }
row.createCell(start + 4).apply { metadata.appliedAgentSettlementRatio?.let { setCellValue(it.toDouble()) } }
}
private fun toDateRange(startDateStr: String, endDateStr: String): Pair<LocalDateTime, LocalDateTime> {
val startDate = startDateStr.convertLocalDateTime()
val endDate = endDateStr.convertLocalDateTime(hour = 23, minute = 59, second = 59)
@@ -1,6 +1,8 @@
package kr.co.vividnext.sodalive.admin.calculate
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.annotation.JsonUnwrapped
import kr.co.vividnext.sodalive.v2.settlement.dto.SettlementRateMetadata
data class GetCalculateByCreatorItem(
@JsonProperty("creatorId") val creatorId: Long,
@@ -10,5 +12,6 @@ data class GetCalculateByCreatorItem(
@JsonProperty("paymentFee") val paymentFee: Int,
@JsonProperty("settlementAmount") val settlementAmount: Int,
@JsonProperty("tax") val tax: Int,
@JsonProperty("depositAmount") val depositAmount: Int
@JsonProperty("depositAmount") val depositAmount: Int,
@get:JsonUnwrapped val metadata: SettlementRateMetadata
)
@@ -1,55 +1,78 @@
package kr.co.vividnext.sodalive.admin.calculate
import com.querydsl.core.annotations.QueryProjection
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementAmounts
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementCountryRelation
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementRowKey
import kr.co.vividnext.sodalive.v2.settlement.dto.SettlementRateMetadata
import java.math.BigDecimal
import java.math.RoundingMode
data class GetCalculateByCreatorQueryData @QueryProjection constructor(
data class GetCalculateByCreatorQueryData(
val creatorId: Long,
val nickname: String,
val totalCan: Int,
val settlementRatio: Int?,
val newPolicyCan: Int = 0,
val newPolicyWeightedRatioCan: Long = 0
val metadata: SettlementRateMetadata = legacySettlementMetadata("creator", settlementRatio, creatorId.toString()),
val amount: SettlementAmounts? = null
) {
@QueryProjection
constructor(creatorId: Long, nickname: String, totalCan: Int, settlementRatio: Int?) :
this(creatorId, nickname, totalCan, settlementRatio, 0, 0)
fun toGetCalculateByCreator(): GetCalculateByCreatorItem {
// 원화 = totalCoin * 100 ( 캔 1개 = 100원 )
val totalKrw = BigDecimal(totalCan).multiply(BigDecimal(100))
// 결제수수료 : 6.6%
val paymentFee = totalKrw.multiply(BigDecimal(0.066))
// 구정책과 신정책 기여액은 합산한 뒤 각 응답 필드에서 반올림한다.
val oldPolicyKrw = BigDecimal(totalCan - newPolicyCan).multiply(BigDecimal(100))
val oldPolicyNet = oldPolicyKrw.subtract(oldPolicyKrw.multiply(BigDecimal(0.066)))
val oldSettlementAmount = if (settlementRatio != null) {
oldPolicyNet.multiply(BigDecimal(settlementRatio).divide(BigDecimal(100.0)))
} else {
oldPolicyNet.multiply(BigDecimal(0.7))
}
val settlementAmount = oldSettlementAmount.add(
BigDecimal(newPolicyWeightedRatioCan).multiply(BigDecimal.ONE.subtract(BigDecimal(0.066)))
constructor(creatorId: Long, nickname: String, totalCan: Int, settlementRatio: Int?, source: String) :
this(
creatorId,
nickname,
totalCan,
settlementRatio,
legacySettlementMetadata("creator", settlementRatio, source, creatorId.toString())
)
// 원천세 = 정산금액의 3.3%
val tax = settlementAmount.multiply(BigDecimal(0.033))
// 입금액
val depositAmount = settlementAmount.subtract(tax)
fun toGetCalculateByCreator(): GetCalculateByCreatorItem {
val calculated = amount ?: legacyGeneralSettlementAmounts(totalCan, settlementRatio)
return GetCalculateByCreatorItem(
creatorId = creatorId,
nickname = nickname,
totalCan = totalCan,
totalKrw = totalKrw.toInt(),
paymentFee = paymentFee.setScale(0, RoundingMode.HALF_UP).toInt(),
settlementAmount = settlementAmount.setScale(0, RoundingMode.HALF_UP).toInt(),
tax = tax.setScale(0, RoundingMode.HALF_UP).toInt(),
depositAmount = depositAmount.setScale(0, RoundingMode.HALF_UP).toInt()
totalCan = Math.toIntExact(calculated.totalCan),
totalKrw = Math.toIntExact(calculated.grossAmount),
paymentFee = Math.toIntExact(calculated.paymentFee),
settlementAmount = Math.toIntExact(calculated.settlementAmount),
tax = Math.toIntExact(calculated.withholdingTax),
depositAmount = Math.toIntExact(calculated.depositAmount),
metadata = metadata
)
}
}
internal fun legacySettlementMetadata(
route: String,
ratio: Int?,
vararg identity: String?
) = SettlementRateMetadata(
SettlementRowKey.legacy(route, identity.toList() + ratio?.toString()),
SettlementCountryRelation.LEGACY,
ratio,
null,
null,
false
)
// Preserve the original binary constants and independent rounding for all general legacy routes except content donation.
internal fun legacyGeneralSettlementAmounts(totalCan: Int, ratio: Int?): SettlementAmounts {
val gross = BigDecimal(totalCan).multiply(BigDecimal(100))
val fee = gross.multiply(BigDecimal(0.066))
val net = gross.subtract(fee)
val settlement = if (ratio != null) {
net.multiply(BigDecimal(ratio).divide(BigDecimal(100.0)))
} else {
net.multiply(BigDecimal(0.7))
}
val tax = settlement.multiply(BigDecimal(0.033))
return SettlementAmounts(
totalCan.toLong(),
gross.longValueExact(),
fee.setScale(0, RoundingMode.HALF_UP).longValueExact(),
settlement.setScale(0, RoundingMode.HALF_UP).longValueExact(),
tax.setScale(0, RoundingMode.HALF_UP).longValueExact(),
settlement.subtract(tax).setScale(0, RoundingMode.HALF_UP).longValueExact(),
0L
)
}
@@ -1,10 +1,10 @@
package kr.co.vividnext.sodalive.admin.calculate
import com.querydsl.core.annotations.QueryProjection
import java.math.BigDecimal
import java.math.RoundingMode
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementAmounts
import kr.co.vividnext.sodalive.v2.settlement.dto.SettlementRateMetadata
data class GetCalculateCommunityPostQueryData @QueryProjection constructor(
data class GetCalculateCommunityPostQueryData(
val nickname: String,
val title: String,
val date: String,
@@ -12,8 +12,8 @@ data class GetCalculateCommunityPostQueryData @QueryProjection constructor(
val numberOfPurchase: Long,
val totalCan: Int,
val settlementRatio: Int?,
val newPolicyCan: Int = 0,
val newPolicyWeightedRatioCan: Long = 0
val metadata: SettlementRateMetadata = legacySettlementMetadata("community", settlementRatio),
val amount: SettlementAmounts? = null
) {
@QueryProjection
constructor(
@@ -23,46 +23,34 @@ data class GetCalculateCommunityPostQueryData @QueryProjection constructor(
can: Int,
numberOfPurchase: Long,
totalCan: Int,
settlementRatio: Int?
) : this(nickname, title, date, can, numberOfPurchase, totalCan, settlementRatio, 0, 0)
settlementRatio: Int?,
postId: Long
) : this(
nickname,
title,
date,
can,
numberOfPurchase,
totalCan,
settlementRatio,
legacySettlementMetadata("community", settlementRatio, postId.toString(), date)
)
fun toGetCalculateCommunityPostResponse(): GetCalculateCommunityPostResponse {
// 원화 = totalCoin * 100 ( 캔 1개 = 100원 )
val totalKrw = BigDecimal(totalCan).multiply(BigDecimal(100))
// 결제수수료 : 6.6%
val paymentFee = totalKrw.multiply(BigDecimal(0.066))
// 구정책과 신정책 기여액은 합산한 뒤 각 응답 필드에서 반올림한다.
val oldPolicyKrw = BigDecimal(totalCan - newPolicyCan).multiply(BigDecimal(100))
val oldPolicyNet = oldPolicyKrw.subtract(oldPolicyKrw.multiply(BigDecimal(0.066)))
val oldSettlementAmount = if (settlementRatio != null) {
oldPolicyNet.multiply(BigDecimal(settlementRatio).divide(BigDecimal(100.0)))
} else {
oldPolicyNet.multiply(BigDecimal(0.7))
}
val settlementAmount = oldSettlementAmount.add(
BigDecimal(newPolicyWeightedRatioCan).multiply(BigDecimal.ONE.subtract(BigDecimal(0.066)))
)
// 원천세 = 정산금액의 3.3%
val tax = settlementAmount.multiply(BigDecimal(0.033))
// 입금액
val depositAmount = settlementAmount.subtract(tax)
val calculated = amount ?: legacyGeneralSettlementAmounts(totalCan, settlementRatio)
return GetCalculateCommunityPostResponse(
nickname = nickname,
title = title,
date = date,
can = can,
numberOfPurchase = numberOfPurchase.toInt(),
totalCan = totalCan,
totalKrw = totalKrw.toInt(),
paymentFee = paymentFee.setScale(0, RoundingMode.HALF_UP).toInt(),
settlementAmount = settlementAmount.setScale(0, RoundingMode.HALF_UP).toInt(),
tax = tax.setScale(0, RoundingMode.HALF_UP).toInt(),
depositAmount = depositAmount.setScale(0, RoundingMode.HALF_UP).toInt()
numberOfPurchase = Math.toIntExact(numberOfPurchase),
totalCan = Math.toIntExact(calculated.totalCan),
totalKrw = Math.toIntExact(calculated.grossAmount),
paymentFee = Math.toIntExact(calculated.paymentFee),
settlementAmount = Math.toIntExact(calculated.settlementAmount),
tax = Math.toIntExact(calculated.withholdingTax),
depositAmount = Math.toIntExact(calculated.depositAmount),
metadata = metadata
)
}
}
@@ -1,6 +1,8 @@
package kr.co.vividnext.sodalive.admin.calculate
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.annotation.JsonUnwrapped
import kr.co.vividnext.sodalive.v2.settlement.dto.SettlementRateMetadata
data class GetCalculateCommunityPostResponse(
@JsonProperty("nickname") val nickname: String,
@@ -13,5 +15,6 @@ data class GetCalculateCommunityPostResponse(
@JsonProperty("paymentFee") val paymentFee: Int,
@JsonProperty("settlementAmount") val settlementAmount: Int,
@JsonProperty("tax") val tax: Int,
@JsonProperty("depositAmount") val depositAmount: Int
@JsonProperty("depositAmount") val depositAmount: Int,
@get:JsonUnwrapped val metadata: SettlementRateMetadata
)
@@ -1,26 +1,21 @@
package kr.co.vividnext.sodalive.admin.calculate
import com.querydsl.core.annotations.QueryProjection
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementAmounts
import kr.co.vividnext.sodalive.v2.settlement.dto.SettlementRateMetadata
import java.math.BigDecimal
import java.math.RoundingMode
data class GetCalculateContentDonationQueryData @QueryProjection constructor(
// 등록 크리에이터 닉네임
data class GetCalculateContentDonationQueryData(
val nickname: String,
// 콘텐츠 제목
val title: String,
// 콘텐츠 가격
val price: Int,
// 콘텐츠 등록 날짜
val registrationDate: String,
// 후원 날짜
val donationDate: String,
// 인원
val numberOfDonation: Long,
// 합계
val totalCan: Int,
val newPolicyCan: Int = 0,
val newPolicyWeightedRatioCan: Long = 0
val metadata: SettlementRateMetadata = legacySettlementMetadata("content-donation", 70),
val amount: SettlementAmounts? = null
) {
@QueryProjection
constructor(
@@ -30,51 +25,51 @@ data class GetCalculateContentDonationQueryData @QueryProjection constructor(
registrationDate: String,
donationDate: String,
numberOfDonation: Long,
totalCan: Int
) : this(nickname, title, price, registrationDate, donationDate, numberOfDonation, totalCan, 0, 0)
companion object {
private val KRW_PER_CAN = BigDecimal("100")
private val PAYMENT_FEE_RATE = BigDecimal("0.066")
private val SETTLEMENT_RATE = BigDecimal("0.7")
private val TAX_RATE = BigDecimal("0.033")
}
totalCan: Int,
contentId: Long
) : this(
nickname,
title,
price,
registrationDate,
donationDate,
numberOfDonation,
totalCan,
legacySettlementMetadata("content-donation", 70, contentId.toString(), donationDate)
)
fun toGetCalculateContentDonationResponse(): GetCalculateContentDonationResponse {
// 원화 = totalCoin * 100 ( 캔 1개 = 100원 )
val totalKrw = BigDecimal(totalCan).multiply(KRW_PER_CAN)
// 결제수수료 : 6.6%
val paymentFee = totalKrw.multiply(PAYMENT_FEE_RATE)
// 구정책과 신정책 기여액은 합산한 뒤 각 응답 필드에서 반올림한다.
val oldPolicyKrw = BigDecimal(totalCan - newPolicyCan).multiply(KRW_PER_CAN)
val oldSettlementAmount = oldPolicyKrw.subtract(oldPolicyKrw.multiply(PAYMENT_FEE_RATE)).multiply(SETTLEMENT_RATE)
val settlementAmount = oldSettlementAmount.add(
BigDecimal(newPolicyWeightedRatioCan).multiply(BigDecimal.ONE.subtract(PAYMENT_FEE_RATE))
)
// 원천세 = 정산금액의 3.3%
val tax = settlementAmount.multiply(TAX_RATE)
// 입금액
val depositAmount = settlementAmount.subtract(tax)
val paidOrFree = if (price > 0) "유료" else "무료"
val calculated = amount ?: calculateLegacyAmount()
return GetCalculateContentDonationResponse(
nickname = nickname,
title = title,
paidOrFree = paidOrFree,
paidOrFree = if (price > 0) "유료" else "무료",
registrationDate = registrationDate,
donationDate = donationDate,
numberOfDonation = numberOfDonation.toInt(),
totalCan = totalCan,
totalKrw = totalKrw.toInt(),
paymentFee = paymentFee.setScale(0, RoundingMode.HALF_UP).toInt(),
settlementAmount = settlementAmount.setScale(0, RoundingMode.HALF_UP).toInt(),
tax = tax.setScale(0, RoundingMode.HALF_UP).toInt(),
depositAmount = depositAmount.setScale(0, RoundingMode.HALF_UP).toInt()
numberOfDonation = Math.toIntExact(numberOfDonation),
totalCan = Math.toIntExact(calculated.totalCan),
totalKrw = Math.toIntExact(calculated.grossAmount),
paymentFee = Math.toIntExact(calculated.paymentFee),
settlementAmount = Math.toIntExact(calculated.settlementAmount),
tax = Math.toIntExact(calculated.withholdingTax),
depositAmount = Math.toIntExact(calculated.depositAmount),
metadata = metadata
)
}
private fun calculateLegacyAmount(): SettlementAmounts {
val gross = BigDecimal(totalCan).multiply(BigDecimal("100"))
val fee = gross.multiply(BigDecimal("0.066"))
val settlement = gross.subtract(fee).multiply(BigDecimal("0.7"))
val tax = settlement.multiply(BigDecimal("0.033"))
return SettlementAmounts(
totalCan.toLong(),
gross.longValueExact(),
fee.setScale(0, RoundingMode.HALF_UP).longValueExact(),
settlement.setScale(0, RoundingMode.HALF_UP).longValueExact(),
tax.setScale(0, RoundingMode.HALF_UP).longValueExact(),
settlement.subtract(tax).setScale(0, RoundingMode.HALF_UP).longValueExact(),
0L
)
}
}
@@ -1,6 +1,8 @@
package kr.co.vividnext.sodalive.admin.calculate
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.annotation.JsonUnwrapped
import kr.co.vividnext.sodalive.v2.settlement.dto.SettlementRateMetadata
data class GetCalculateContentDonationResponse(
@JsonProperty("nickname") val nickname: String,
@@ -14,5 +16,6 @@ data class GetCalculateContentDonationResponse(
@JsonProperty("paymentFee") val paymentFee: Int,
@JsonProperty("settlementAmount") val settlementAmount: Int,
@JsonProperty("tax") val tax: Int,
@JsonProperty("depositAmount") val depositAmount: Int
@JsonProperty("depositAmount") val depositAmount: Int,
@get:JsonUnwrapped val metadata: SettlementRateMetadata
)
@@ -2,32 +2,22 @@ package kr.co.vividnext.sodalive.admin.calculate
import com.querydsl.core.annotations.QueryProjection
import kr.co.vividnext.sodalive.content.order.OrderType
import java.math.BigDecimal
import java.math.RoundingMode
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementAmounts
import kr.co.vividnext.sodalive.v2.settlement.dto.SettlementRateMetadata
data class GetCalculateContentQueryData @QueryProjection constructor(
// 등록 크리에이터 닉네임
data class GetCalculateContentQueryData(
val nickname: String,
// 콘텐츠 제목
val title: String,
// 콘텐츠 등록 날짜
val registrationDate: String,
// 콘텐츠 판매 날짜
val saleDate: String,
// 대여/소장 구분
val orderType: OrderType,
// 판매 금액(캔)
val orderPrice: Int,
// 인원
val numberOfPeople: Long,
// 합계
val totalCan: Int,
// 포인트
val totalPoint: Int,
// 정산비율
val settlementRatio: Int?,
val newPolicyCan: Int = 0,
val newPolicyWeightedRatioCan: Long = 0
val metadata: SettlementRateMetadata = legacySettlementMetadata("content", settlementRatio),
val amount: SettlementAmounts? = null
) {
@QueryProjection
constructor(
@@ -40,68 +30,39 @@ data class GetCalculateContentQueryData @QueryProjection constructor(
numberOfPeople: Long,
totalCan: Int,
totalPoint: Int,
settlementRatio: Int?
settlementRatio: Int?,
contentId: Long,
pointGroup: Int
) : this(
nickname,
title,
registrationDate,
saleDate,
orderType,
orderPrice,
numberOfPeople,
totalCan,
totalPoint,
settlementRatio,
0,
0
nickname, title, registrationDate, saleDate, orderType, orderPrice, numberOfPeople, totalCan, totalPoint, settlementRatio,
legacySettlementMetadata(
"content",
settlementRatio,
contentId.toString(),
saleDate,
orderType.name,
orderPrice.toString(),
pointGroup.toString()
)
)
fun toGetCalculateContentResponse(): GetCalculateContentResponse {
val orderTypeStr = if (totalPoint > 0) {
"포인트"
} else if (orderType == OrderType.RENTAL) {
"대여"
} else {
"소장"
}
// 원화 = totalCoin * 100 ( 캔 1개 = 100원 )
val totalKrw = BigDecimal(totalCan).multiply(BigDecimal(100))
// 결제수수료 : 6.6%
val paymentFee = totalKrw.multiply(BigDecimal(0.066))
// 구정책과 신정책 기여액은 합산한 뒤 각 응답 필드에서 반올림한다.
val oldPolicyKrw = BigDecimal(totalCan - newPolicyCan).multiply(BigDecimal(100))
val oldPolicyNet = oldPolicyKrw.subtract(oldPolicyKrw.multiply(BigDecimal(0.066)))
val oldSettlementAmount = if (settlementRatio != null) {
oldPolicyNet.multiply(BigDecimal(settlementRatio).divide(BigDecimal(100.0)))
} else {
oldPolicyNet.multiply(BigDecimal(0.7))
}
val settlementAmount = oldSettlementAmount.add(
BigDecimal(newPolicyWeightedRatioCan).multiply(BigDecimal.ONE.subtract(BigDecimal(0.066)))
)
// 원천세 = 정산금액의 3.3%
val tax = settlementAmount.multiply(BigDecimal(0.033))
val depositAmount = settlementAmount.subtract(tax)
val calculated = amount ?: legacyGeneralSettlementAmounts(totalCan, settlementRatio)
return GetCalculateContentResponse(
nickname = nickname,
title = title,
registrationDate = registrationDate,
saleDate = saleDate,
orderType = orderTypeStr,
orderType = if (totalPoint > 0) "포인트" else if (orderType == OrderType.RENTAL) "대여" else "소장",
orderPrice = orderPrice,
numberOfPeople = numberOfPeople.toInt(),
totalCan = totalCan,
totalKrw = totalKrw.toInt(),
paymentFee = paymentFee.setScale(0, RoundingMode.HALF_UP).toInt(),
settlementAmount = settlementAmount.setScale(0, RoundingMode.HALF_UP).toInt(),
tax = tax.setScale(0, RoundingMode.HALF_UP).toInt(),
depositAmount = depositAmount.setScale(0, RoundingMode.HALF_UP).toInt()
numberOfPeople = Math.toIntExact(numberOfPeople),
totalCan = Math.toIntExact(calculated.totalCan),
totalKrw = Math.toIntExact(calculated.grossAmount),
paymentFee = Math.toIntExact(calculated.paymentFee),
settlementAmount = Math.toIntExact(calculated.settlementAmount),
tax = Math.toIntExact(calculated.withholdingTax),
depositAmount = Math.toIntExact(calculated.depositAmount),
metadata = metadata
)
}
}
@@ -1,6 +1,8 @@
package kr.co.vividnext.sodalive.admin.calculate
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.annotation.JsonUnwrapped
import kr.co.vividnext.sodalive.v2.settlement.dto.SettlementRateMetadata
data class GetCalculateContentResponse(
@JsonProperty("nickname") val nickname: String,
@@ -15,5 +17,6 @@ data class GetCalculateContentResponse(
@JsonProperty("paymentFee") val paymentFee: Int,
@JsonProperty("settlementAmount") val settlementAmount: Int,
@JsonProperty("tax") val tax: Int,
@JsonProperty("depositAmount") val depositAmount: Int
@JsonProperty("depositAmount") val depositAmount: Int,
@get:JsonUnwrapped val metadata: SettlementRateMetadata
)
@@ -2,27 +2,21 @@ package kr.co.vividnext.sodalive.admin.calculate
import com.querydsl.core.annotations.QueryProjection
import kr.co.vividnext.sodalive.can.use.CanUsage
import java.math.BigDecimal
import java.math.RoundingMode
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementAmounts
import kr.co.vividnext.sodalive.v2.settlement.dto.SettlementRateMetadata
data class GetCalculateLiveQueryData @QueryProjection constructor(
data class GetCalculateLiveQueryData(
val nickname: String,
val date: String,
val title: String,
// 라이브 방 id
val roomId: Long,
// 유료방 입장 금액
val entranceFee: Int,
// 코인 사용 구분
val canUsage: CanUsage,
// 참여인원
val memberCount: Long,
// 합계
val totalAmount: Int,
// 정산비율
val settlementRatio: Int?,
val newPolicyCan: Int = 0,
val newPolicyWeightedRatioCan: Long = 0
val metadata: SettlementRateMetadata = legacySettlementMetadata("live", settlementRatio, roomId.toString(), canUsage.name),
val amount: SettlementAmounts? = null
) {
@QueryProjection
constructor(
@@ -35,71 +29,33 @@ data class GetCalculateLiveQueryData @QueryProjection constructor(
memberCount: Long,
totalAmount: Int,
settlementRatio: Int?
) : this(nickname, date, title, roomId, entranceFee, canUsage, memberCount, totalAmount, settlementRatio, 0, 0)
) : this(
nickname, date, title, roomId, entranceFee, canUsage, memberCount, totalAmount, settlementRatio,
legacySettlementMetadata("live", settlementRatio, roomId.toString(), canUsage.name)
)
fun toGetCalculateLiveResponse(): GetCalculateLiveResponse {
val canUsageStr = when (canUsage) {
CanUsage.LIVE -> {
"유료"
}
CanUsage.SPIN_ROULETTE -> {
"룰렛"
}
CanUsage.HEART -> {
"하트"
}
else -> {
"후원"
}
}
val numberOfPeople = if (canUsage == CanUsage.LIVE) {
memberCount.toInt()
} else {
0
}
// 원화 = totalCoin * 100 ( 캔 1개 = 100원 )
val totalKrw = BigDecimal(totalAmount).multiply(BigDecimal(100))
// 결제수수료 : 6.6%
val paymentFee = totalKrw.multiply(BigDecimal(0.066))
// 구정책과 신정책 기여액은 합산한 뒤 각 응답 필드에서 반올림한다.
val oldPolicyKrw = BigDecimal(totalAmount - newPolicyCan).multiply(BigDecimal(100))
val oldPolicyNet = oldPolicyKrw.subtract(oldPolicyKrw.multiply(BigDecimal(0.066)))
val oldSettlementAmount = if (settlementRatio != null) {
oldPolicyNet.multiply(BigDecimal(settlementRatio).divide(BigDecimal(100.0)))
} else {
oldPolicyNet.multiply(BigDecimal(0.7))
}
val settlementAmount = oldSettlementAmount.add(
BigDecimal(newPolicyWeightedRatioCan).multiply(BigDecimal.ONE.subtract(BigDecimal(0.066)))
)
// 원천세 = 정산금액의 3.3%
val tax = settlementAmount.multiply(BigDecimal(0.033))
// 입금액
val depositAmount = settlementAmount.subtract(tax)
val calculated = amount ?: legacyGeneralSettlementAmounts(totalAmount, settlementRatio)
return GetCalculateLiveResponse(
nickname = nickname,
date = date,
title = title,
roomId = roomId,
entranceFee = entranceFee,
canUsageStr = canUsageStr,
numberOfPeople = numberOfPeople,
totalAmount = totalAmount,
totalKrw = totalKrw.toInt(),
paymentFee = paymentFee.setScale(0, RoundingMode.HALF_UP).toInt(),
settlementAmount = settlementAmount.setScale(0, RoundingMode.HALF_UP).toInt(),
tax = tax.setScale(0, RoundingMode.HALF_UP).toInt(),
depositAmount = depositAmount.setScale(0, RoundingMode.HALF_UP).toInt()
canUsageStr = when (canUsage) {
CanUsage.LIVE -> "유료"
CanUsage.SPIN_ROULETTE -> "룰렛"
CanUsage.HEART -> "하트"
else -> "후원"
},
numberOfPeople = if (canUsage == CanUsage.LIVE) Math.toIntExact(memberCount) else 0,
totalAmount = Math.toIntExact(calculated.totalCan),
totalKrw = Math.toIntExact(calculated.grossAmount),
paymentFee = Math.toIntExact(calculated.paymentFee),
settlementAmount = Math.toIntExact(calculated.settlementAmount),
tax = Math.toIntExact(calculated.withholdingTax),
depositAmount = Math.toIntExact(calculated.depositAmount),
metadata = metadata
)
}
}
@@ -1,6 +1,8 @@
package kr.co.vividnext.sodalive.admin.calculate
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.annotation.JsonUnwrapped
import kr.co.vividnext.sodalive.v2.settlement.dto.SettlementRateMetadata
data class GetCalculateLiveResponse(
@JsonProperty("nickname") val nickname: String,
@@ -15,5 +17,6 @@ data class GetCalculateLiveResponse(
@JsonProperty("paymentFee") val paymentFee: Int,
@JsonProperty("settlementAmount") val settlementAmount: Int,
@JsonProperty("tax") val tax: Int,
@JsonProperty("depositAmount") val depositAmount: Int
@JsonProperty("depositAmount") val depositAmount: Int,
@get:JsonUnwrapped val metadata: SettlementRateMetadata
)
@@ -1,32 +1,24 @@
package kr.co.vividnext.sodalive.admin.calculate
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.annotation.JsonUnwrapped
import com.querydsl.core.annotations.QueryProjection
import kr.co.vividnext.sodalive.content.order.OrderType
import java.math.BigDecimal
import java.math.RoundingMode
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementAmounts
import kr.co.vividnext.sodalive.v2.settlement.dto.SettlementRateMetadata
data class GetCumulativeSalesByContentQueryData @QueryProjection constructor(
// 등록 크리에이터 닉네임
data class GetCumulativeSalesByContentQueryData(
val nickname: String,
// 콘텐츠 제목
val title: String,
// 콘텐츠 등록 날짜
val registrationDate: String,
// 대여/소장 구분
val orderType: OrderType,
// 판매 금액(캔)
val orderPrice: Int,
// 인원
val numberOfPeople: Long,
// 합계
val totalCan: Int,
// 포인트
val totalPoint: Int,
// 정산비율
val settlementRatio: Int?,
val newPolicyCan: Int = 0,
val newPolicyWeightedRatioCan: Long = 0
val metadata: SettlementRateMetadata = legacySettlementMetadata("content-cumulative", settlementRatio),
val amount: SettlementAmounts? = null
) {
@QueryProjection
constructor(
@@ -38,57 +30,37 @@ data class GetCumulativeSalesByContentQueryData @QueryProjection constructor(
numberOfPeople: Long,
totalCan: Int,
totalPoint: Int,
settlementRatio: Int?
settlementRatio: Int?,
contentId: Long,
pointGroup: Int
) : this(
nickname, title, registrationDate, orderType, orderPrice, numberOfPeople, totalCan, totalPoint, settlementRatio, 0, 0
nickname, title, registrationDate, orderType, orderPrice, numberOfPeople, totalCan, totalPoint, settlementRatio,
legacySettlementMetadata(
"content-cumulative",
settlementRatio,
contentId.toString(),
orderType.name,
orderPrice.toString(),
pointGroup.toString()
)
)
fun toCumulativeSalesByContentItem(): CumulativeSalesByContentItem {
val orderTypeStr = if (totalPoint > 0) {
"포인트"
} else if (orderType == OrderType.RENTAL) {
"대여"
} else {
"소장"
}
// 원화 = totalCoin * 100 ( 캔 1개 = 100원 )
val totalKrw = BigDecimal(totalCan).multiply(BigDecimal(100))
// 결제수수료 : 6.6%
val paymentFee = totalKrw.multiply(BigDecimal(0.066))
// 구정책과 신정책 기여액은 합산한 뒤 각 응답 필드에서 반올림한다.
val oldPolicyKrw = BigDecimal(totalCan - newPolicyCan).multiply(BigDecimal(100))
val oldPolicyNet = oldPolicyKrw.subtract(oldPolicyKrw.multiply(BigDecimal(0.066)))
val oldSettlementAmount = if (settlementRatio != null) {
oldPolicyNet.multiply(BigDecimal(settlementRatio).divide(BigDecimal(100.0)))
} else {
oldPolicyNet.multiply(BigDecimal(0.7))
}
val settlementAmount = oldSettlementAmount.add(
BigDecimal(newPolicyWeightedRatioCan).multiply(BigDecimal.ONE.subtract(BigDecimal(0.066)))
)
// 원천세 = 정산금액의 3.3%
val tax = settlementAmount.multiply(BigDecimal(0.033))
// 입금액
val depositAmount = settlementAmount.subtract(tax)
val calculated = amount ?: legacyGeneralSettlementAmounts(totalCan, settlementRatio)
return CumulativeSalesByContentItem(
nickname = nickname,
title = title,
registrationDate = registrationDate,
orderType = orderTypeStr,
orderType = if (totalPoint > 0) "포인트" else if (orderType == OrderType.RENTAL) "대여" else "소장",
orderPrice = orderPrice,
numberOfPeople = numberOfPeople.toInt(),
totalCan = totalCan,
totalKrw = totalKrw.toInt(),
paymentFee = paymentFee.setScale(0, RoundingMode.HALF_UP).toInt(),
settlementAmount = settlementAmount.setScale(0, RoundingMode.HALF_UP).toInt(),
tax = tax.setScale(0, RoundingMode.HALF_UP).toInt(),
depositAmount = depositAmount.setScale(0, RoundingMode.HALF_UP).toInt()
numberOfPeople = Math.toIntExact(numberOfPeople),
totalCan = Math.toIntExact(calculated.totalCan),
totalKrw = Math.toIntExact(calculated.grossAmount),
paymentFee = Math.toIntExact(calculated.paymentFee),
settlementAmount = Math.toIntExact(calculated.settlementAmount),
tax = Math.toIntExact(calculated.withholdingTax),
depositAmount = Math.toIntExact(calculated.depositAmount),
metadata = metadata
)
}
}
@@ -110,5 +82,6 @@ data class CumulativeSalesByContentItem(
@JsonProperty("paymentFee") val paymentFee: Int,
@JsonProperty("settlementAmount") val settlementAmount: Int,
@JsonProperty("tax") val tax: Int,
@JsonProperty("depositAmount") val depositAmount: Int
@JsonProperty("depositAmount") val depositAmount: Int,
@get:JsonUnwrapped val metadata: SettlementRateMetadata
)
@@ -1,211 +1,200 @@
package kr.co.vividnext.sodalive.admin.calculate.channelDonation
import com.querydsl.core.types.dsl.DateTimePath
import com.querydsl.core.types.dsl.Expressions
import com.querydsl.core.types.dsl.StringTemplate
import com.querydsl.jpa.impl.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.member.QMember.member
import kr.co.vividnext.sodalive.v2.settlement.adapter.out.persistence.CountrySettlementExpressions
import kr.co.vividnext.sodalive.v2.settlement.adapter.out.persistence.CanonicalSettlementQueryRepository
import kr.co.vividnext.sodalive.v2.settlement.domain.CountrySettlementPolicy
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementDisplayGrain
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementScope
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementSource
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementSourceGrain
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementWindow
import kr.co.vividnext.sodalive.v2.settlement.dto.SettlementDisplayRow
import kr.co.vividnext.sodalive.v2.settlement.dto.SettlementRowDescription
import org.springframework.stereotype.Repository
import java.time.LocalDate
import java.time.LocalDateTime
@Repository
class AdminChannelDonationCalculateQueryRepository(
private val queryFactory: JPAQueryFactory,
private val countrySettlementExpressions: CountrySettlementExpressions
private val canonicalRepository: CanonicalSettlementQueryRepository,
private val policy: CountrySettlementPolicy
) {
fun getChannelDonationByDateTotal(
startDate: LocalDateTime,
endDate: LocalDateTime
): GetAdminChannelDonationSettlementTotalQueryData {
return getChannelDonationSettlementTotal(startDate, endDate)
}
): GetAdminChannelDonationSettlementTotalQueryData = getChannelDonationSettlementTotal(startDate, endDate)
fun getChannelDonationByCreatorTotal(
startDate: LocalDateTime,
endDate: LocalDateTime
): GetAdminChannelDonationSettlementTotalQueryData {
return getChannelDonationSettlementTotal(startDate, endDate)
}
): GetAdminChannelDonationSettlementTotalQueryData = getChannelDonationSettlementTotal(startDate, endDate)
private fun getChannelDonationSettlementTotal(
startDate: LocalDateTime,
endDate: LocalDateTime
): GetAdminChannelDonationSettlementTotalQueryData {
return queryFactory
.select(
QGetAdminChannelDonationSettlementTotalQueryData(
useCan.id.countDistinct(),
useCanCalculate.can.sum(),
countrySettlementExpressions.newPolicyCan(useCan.createdAt, useCanCalculate.can),
countrySettlementExpressions.newPolicyWeightedRatioCan(
useCan.createdAt,
useCanCalculate.can,
member.countryCode,
useCan.countryCode
)
)
)
.from(useCanCalculate)
.innerJoin(useCanCalculate.useCan, useCan)
.innerJoin(member)
.on(member.id.eq(useCanCalculate.recipientCreatorId))
.where(baseWhereCondition(startDate, endDate))
.fetchOne()
?: GetAdminChannelDonationSettlementTotalQueryData(
count = 0L,
totalCan = 0
)
}
fun getChannelDonationByDateTotalCount(startDate: LocalDateTime, endDate: LocalDateTime): Int {
val formattedDate = getFormattedDate(useCan.createdAt)
val distinctGroupKey = Expressions.stringTemplate(
"CONCAT({0}, '-', {1})",
formattedDate,
member.id.stringValue()
val scope = scope(startDate, endDate)
val legacy = queryFactory.select(
QGetAdminChannelDonationSettlementTotalQueryData(useCan.id.countDistinct(), useCanCalculate.can.sum())
)
return queryFactory
.select(distinctGroupKey.countDistinct())
.from(useCanCalculate)
.innerJoin(useCanCalculate.useCan, useCan)
.innerJoin(member)
.on(member.id.eq(useCanCalculate.recipientCreatorId))
.where(baseWhereCondition(startDate, endDate))
.fetchOne()
?.toInt()
?: 0
.innerJoin(member).on(member.id.eq(useCanCalculate.recipientCreatorId))
.where(legacyWhere(scope))
.fetchOne() ?: GetAdminChannelDonationSettlementTotalQueryData(0, 0)
// Legacy totals retain whole-period rounding; only the new regime sums rounded canonical rows.
val amount = legacy.amount + canonicalRepository.readTotals(scope)
return GetAdminChannelDonationSettlementTotalQueryData(
Math.addExact(legacy.count ?: 0L, canonicalRepository.countTransactions(scope)),
Math.toIntExact(amount.totalCan),
amount
)
}
fun getChannelDonationByCreatorTotalCount(startDate: LocalDateTime, endDate: LocalDateTime): Int {
return queryFactory
.select(member.id.countDistinct())
.from(useCanCalculate)
.innerJoin(useCanCalculate.useCan, useCan)
.innerJoin(member)
.on(member.id.eq(useCanCalculate.recipientCreatorId))
.where(baseWhereCondition(startDate, endDate))
.fetchOne()
?.toInt()
?: 0
}
fun getChannelDonationByDateTotalCount(startDate: LocalDateTime, endDate: LocalDateTime): Int =
countRows(scope(startDate, endDate), SettlementDisplayGrain.DETAIL)
fun getChannelDonationByCreatorTotalCount(startDate: LocalDateTime, endDate: LocalDateTime): Int =
countRows(scope(startDate, endDate), SettlementDisplayGrain.CREATOR)
fun getChannelDonationByDate(
startDate: LocalDateTime,
endDate: LocalDateTime,
offset: Long,
limit: Long
): List<GetAdminChannelDonationSettlementQueryData> {
val formattedDate = getFormattedDate(useCan.createdAt)
return queryFactory
.select(
QGetAdminChannelDonationSettlementQueryData(
formattedDate,
member.nickname,
useCan.id.countDistinct(),
useCanCalculate.can.sum(),
countrySettlementExpressions.newPolicyCan(useCan.createdAt, useCanCalculate.can),
countrySettlementExpressions.newPolicyWeightedRatioCan(
useCan.createdAt,
useCanCalculate.can,
member.countryCode,
useCan.countryCode
)
)
): List<GetAdminChannelDonationSettlementQueryData> =
readRows(scope(startDate, endDate), SettlementDisplayGrain.DETAIL, offset, limit).map { row ->
GetAdminChannelDonationSettlementQueryData(
requireNotNull(row.description.displayDate),
row.description.creatorNickname,
row.transactionCount,
Math.toIntExact(row.amount.totalCan),
row.amount,
row.metadata
)
.from(useCanCalculate)
.innerJoin(useCanCalculate.useCan, useCan)
.innerJoin(member)
.on(member.id.eq(useCanCalculate.recipientCreatorId))
.where(baseWhereCondition(startDate, endDate))
.groupBy(formattedDate, member.id)
.orderBy(formattedDate.desc(), member.id.desc())
.offset(offset)
.limit(limit)
.fetch()
}
}
fun getChannelDonationByCreator(
startDate: LocalDateTime,
endDate: LocalDateTime,
offset: Long,
limit: Long
): List<GetAdminChannelDonationSettlementByCreatorQueryData> {
return queryFactory
.select(
QGetAdminChannelDonationSettlementByCreatorQueryData(
member.nickname,
useCan.id.countDistinct(),
useCanCalculate.can.sum(),
countrySettlementExpressions.newPolicyCan(useCan.createdAt, useCanCalculate.can),
countrySettlementExpressions.newPolicyWeightedRatioCan(
useCan.createdAt,
useCanCalculate.can,
member.countryCode,
useCan.countryCode
)
)
): List<GetAdminChannelDonationSettlementByCreatorQueryData> =
readRows(scope(startDate, endDate), SettlementDisplayGrain.CREATOR, offset, limit).map { row ->
GetAdminChannelDonationSettlementByCreatorQueryData(
row.description.creatorNickname,
row.transactionCount,
Math.toIntExact(row.amount.totalCan),
row.amount,
row.metadata
)
.from(useCanCalculate)
.innerJoin(useCanCalculate.useCan, useCan)
.innerJoin(member)
.on(member.id.eq(useCanCalculate.recipientCreatorId))
.where(baseWhereCondition(startDate, endDate))
.groupBy(member.id)
.orderBy(member.id.desc())
.offset(offset)
.limit(limit)
.fetch()
}
}
fun getChannelDonationByCreatorForExcel(
startDate: LocalDateTime,
endDate: LocalDateTime
): List<GetAdminChannelDonationSettlementByCreatorQueryData> {
return queryFactory
.select(
QGetAdminChannelDonationSettlementByCreatorQueryData(
member.nickname,
useCan.id.countDistinct(),
useCanCalculate.can.sum(),
countrySettlementExpressions.newPolicyCan(useCan.createdAt, useCanCalculate.can),
countrySettlementExpressions.newPolicyWeightedRatioCan(
useCan.createdAt,
useCanCalculate.can,
member.countryCode,
useCan.countryCode
)
)
)
endDate: LocalDateTime,
offset: Long = 0,
limit: Long = 512
): List<GetAdminChannelDonationSettlementByCreatorQueryData> =
getChannelDonationByCreator(startDate, endDate, offset, limit)
private fun countRows(scope: SettlementScope, grain: SettlementDisplayGrain): Int {
val date = formattedDate()
val key = if (grain == SettlementDisplayGrain.DETAIL) {
Expressions.stringTemplate("CONCAT({0}, '-', {1})", date, member.id.stringValue())
} else {
member.id.stringValue()
}
val legacy = queryFactory.select(key.countDistinct())
.from(useCanCalculate)
.innerJoin(useCanCalculate.useCan, useCan)
.innerJoin(member)
.on(member.id.eq(useCanCalculate.recipientCreatorId))
.where(baseWhereCondition(startDate, endDate))
.groupBy(member.id)
.orderBy(member.id.desc())
.fetch()
.innerJoin(member).on(member.id.eq(useCanCalculate.recipientCreatorId))
.where(legacyWhere(scope))
.fetchOne() ?: 0L
return Math.toIntExact(Math.addExact(legacy, canonicalRepository.countDisplayRows(scope, grain)))
}
private fun baseWhereCondition(
startDate: LocalDateTime,
endDate: LocalDateTime
) = useCan.canUsage.eq(CanUsage.CHANNEL_DONATION)
private fun readRows(
scope: SettlementScope,
grain: SettlementDisplayGrain,
offset: Long,
limit: Long
): List<SettlementDisplayRow> {
require(offset >= 0 && limit > 0)
val newCount = canonicalRepository.countDisplayRows(scope, grain)
val rows = if (offset < newCount) {
canonicalRepository.readDisplayPage(scope, grain, offset, limit)
} else {
emptyList()
}
val remaining = limit - rows.size
return if (remaining > 0) {
rows + readLegacyPage(scope, grain, (offset - newCount).coerceAtLeast(0), remaining)
} else {
rows
}
}
private fun readLegacyPage(
scope: SettlementScope,
grain: SettlementDisplayGrain,
offset: Long,
limit: Long
): List<SettlementDisplayRow> {
val byDate = grain == SettlementDisplayGrain.DETAIL
val date = formattedDate()
val count = useCan.id.countDistinct()
val can = useCanCalculate.can.sum()
val query = queryFactory.select(member.id, member.nickname, count, can)
.from(useCanCalculate)
.innerJoin(useCanCalculate.useCan, useCan)
.innerJoin(member).on(member.id.eq(useCanCalculate.recipientCreatorId))
.where(legacyWhere(scope))
if (byDate) {
query.select(member.id, member.nickname, count, can, date)
.groupBy(date, member.id).orderBy(date.desc(), member.id.desc())
} else {
query.groupBy(member.id).orderBy(member.id.desc())
}
return query.offset(offset).limit(limit).fetch().map { tuple ->
val creatorId = requireNotNull(tuple[member.id])
val day = if (byDate) requireNotNull(tuple[date]) else null
SettlementDisplayRow(
legacyChannelDonationMetadata(
if (byDate) "channel-date" else "channel-creator",
if (byDate) listOf(creatorId.toString(), day) else listOf(creatorId.toString())
),
creatorId,
if (byDate) SettlementSourceGrain(creatorId, LocalDate.parse(day), null, null, null, null) else null,
requireNotNull(tuple[count]),
0,
legacyChannelDonationAmounts((tuple[can] ?: 0).toLong()),
SettlementRowDescription(requireNotNull(tuple[member.nickname]), null, day, null, null)
)
}
}
private fun scope(startDate: LocalDateTime, endDate: LocalDateTime) = SettlementScope(
SettlementSource.CHANNEL_DONATION,
SettlementWindow(startDate, endDate, false)
)
private fun legacyWhere(scope: SettlementScope) = useCan.canUsage.eq(CanUsage.CHANNEL_DONATION)
.and(useCan.isRefund.isFalse)
.and(useCanCalculate.status.eq(UseCanCalculateStatus.RECEIVED))
.and(useCan.createdAt.goe(startDate))
.and(useCan.createdAt.loe(endDate))
.and(useCan.createdAt.goe(requireNotNull(scope.window.startInclusiveUtc)))
.and(useCan.createdAt.loe(requireNotNull(scope.window.endUtc)))
.and(useCan.createdAt.lt(policy.effectiveAtUtc))
private fun getFormattedDate(dateTimePath: DateTimePath<LocalDateTime>): StringTemplate {
return Expressions.stringTemplate(
"DATE_FORMAT(CONVERT_TZ({0}, 'UTC', 'Asia/Seoul'), '%Y-%m-%d')",
dateTimePath
)
}
private fun formattedDate() = Expressions.stringTemplate(
"DATE_FORMAT(CONVERT_TZ({0}, 'UTC', 'Asia/Seoul'), '%Y-%m-%d')",
useCan.createdAt
)
}
@@ -1,18 +1,32 @@
package kr.co.vividnext.sodalive.admin.calculate.channelDonation
import kr.co.vividnext.sodalive.extensions.convertLocalDateTime
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementCountryRelation
import kr.co.vividnext.sodalive.v2.settlement.dto.SettlementRateMetadata
import org.apache.poi.ss.usermodel.Row
import org.apache.poi.ss.usermodel.Sheet
import org.apache.poi.xssf.streaming.SXSSFWorkbook
import org.springframework.stereotype.Service
import org.springframework.transaction.PlatformTransactionManager
import org.springframework.transaction.TransactionDefinition
import org.springframework.transaction.annotation.Isolation
import org.springframework.transaction.annotation.Transactional
import org.springframework.transaction.support.TransactionTemplate
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody
import java.time.LocalDateTime
@Service
class AdminChannelDonationCalculateService(
private val repository: AdminChannelDonationCalculateQueryRepository
private val repository: AdminChannelDonationCalculateQueryRepository,
transactionManager: PlatformTransactionManager
) {
@Transactional(readOnly = true)
private val exportTransaction = TransactionTemplate(transactionManager).apply {
isReadOnly = true
isolationLevel = TransactionDefinition.ISOLATION_REPEATABLE_READ
propagationBehavior = TransactionDefinition.PROPAGATION_REQUIRES_NEW
}
@Transactional(readOnly = true, isolation = Isolation.REPEATABLE_READ)
fun getChannelDonationByDate(
startDateStr: String,
endDateStr: String,
@@ -31,7 +45,7 @@ class AdminChannelDonationCalculateService(
return GetAdminChannelDonationSettlementResponse(totalCount, total, items)
}
@Transactional(readOnly = true)
@Transactional(readOnly = true, isolation = Isolation.REPEATABLE_READ)
fun getChannelDonationByCreator(
startDateStr: String,
endDateStr: String,
@@ -50,17 +64,8 @@ class AdminChannelDonationCalculateService(
return GetAdminChannelDonationSettlementByCreatorResponse(totalCount, total, items)
}
@Transactional(readOnly = true)
fun downloadChannelDonationByDateExcel(startDateStr: String, endDateStr: String): StreamingResponseBody {
val (startDate, endDate) = toDateRange(startDateStr, endDateStr)
val totalCount = repository.getChannelDonationByDateTotalCount(startDate, endDate)
val items = if (totalCount == 0) {
emptyList()
} else {
repository
.getChannelDonationByDate(startDate, endDate, 0L, totalCount.toLong())
.map { it.toResponseItem() }
}
return createExcelStream(
sheetName = "채널후원 정산",
@@ -76,27 +81,32 @@ class AdminChannelDonationCalculateService(
"입금액"
)
) { sheet ->
items.forEachIndexed { index, item ->
val row = sheet.createRow(index + 1)
row.createCell(0).setCellValue(item.date)
row.createCell(1).setCellValue(item.creator)
row.createCell(2).setCellValue(item.count.toDouble())
row.createCell(3).setCellValue(item.totalCan.toDouble())
row.createCell(4).setCellValue(item.krw.toDouble())
row.createCell(5).setCellValue(item.fee.toDouble())
row.createCell(6).setCellValue(item.settlementAmount.toDouble())
row.createCell(7).setCellValue(item.withholdingTax.toDouble())
row.createCell(8).setCellValue(item.depositAmount.toDouble())
val totalCount = repository.getChannelDonationByDateTotalCount(startDate, endDate).toLong()
var offset = 0L
var rowIndex = 1
while (offset < totalCount) {
val limit = minOf(EXPORT_PAGE_SIZE, totalCount - offset)
repository.getChannelDonationByDate(startDate, endDate, offset, limit).forEach { data ->
val item = data.toResponseItem()
val row = sheet.createRow(rowIndex++)
row.createCell(0).setCellValue(item.date)
row.createCell(1).setCellValue(item.creator)
row.createCell(2).setCellValue(item.count.toDouble())
row.createCell(3).setCellValue(item.totalCan.toDouble())
row.createCell(4).setCellValue(item.krw.toDouble())
row.createCell(5).setCellValue(item.fee.toDouble())
row.createCell(6).setCellValue(item.settlementAmount.toDouble())
row.createCell(7).setCellValue(item.withholdingTax.toDouble())
row.createCell(8).setCellValue(item.depositAmount.toDouble())
writeMetadata(row, 9, data.metadata)
}
offset += limit
}
}
}
@Transactional(readOnly = true)
fun downloadChannelDonationByCreatorExcel(startDateStr: String, endDateStr: String): StreamingResponseBody {
val (startDate, endDate) = toDateRange(startDateStr, endDateStr)
val items = repository
.getChannelDonationByCreatorForExcel(startDate, endDate)
.map { it.toResponseItem() }
return createExcelStream(
sheetName = "크리에이터별 채널후원 정산",
@@ -111,40 +121,65 @@ class AdminChannelDonationCalculateService(
"입금액"
)
) { sheet ->
items.forEachIndexed { index, item ->
val row = sheet.createRow(index + 1)
row.createCell(0).setCellValue(item.creator)
row.createCell(1).setCellValue(item.count.toDouble())
row.createCell(2).setCellValue(item.totalCan.toDouble())
row.createCell(3).setCellValue(item.krw.toDouble())
row.createCell(4).setCellValue(item.fee.toDouble())
row.createCell(5).setCellValue(item.settlementAmount.toDouble())
row.createCell(6).setCellValue(item.withholdingTax.toDouble())
row.createCell(7).setCellValue(item.depositAmount.toDouble())
}
var offset = 0L
var rowIndex = 1
do {
val page = repository.getChannelDonationByCreatorForExcel(startDate, endDate, offset, EXPORT_PAGE_SIZE)
page.forEach { data ->
val item = data.toResponseItem()
val row = sheet.createRow(rowIndex++)
row.createCell(0).setCellValue(item.creator)
row.createCell(1).setCellValue(item.count.toDouble())
row.createCell(2).setCellValue(item.totalCan.toDouble())
row.createCell(3).setCellValue(item.krw.toDouble())
row.createCell(4).setCellValue(item.fee.toDouble())
row.createCell(5).setCellValue(item.settlementAmount.toDouble())
row.createCell(6).setCellValue(item.withholdingTax.toDouble())
row.createCell(7).setCellValue(item.depositAmount.toDouble())
writeMetadata(row, 8, data.metadata)
}
offset += page.size
} while (page.size.toLong() == EXPORT_PAGE_SIZE)
}
}
private fun writeMetadata(row: Row, start: Int, metadata: SettlementRateMetadata) {
row.createCell(start).setCellValue(metadata.rowKey)
row.createCell(start + 1).setCellValue(
when (metadata.countryRelation) {
SettlementCountryRelation.SAME_COUNTRY -> "동일 국가"
SettlementCountryRelation.CROSS_COUNTRY -> "다른 국가"
SettlementCountryRelation.LEGACY -> "기존 정책"
null -> "정보 미제공"
}
)
metadata.appliedSettlementRatio?.let { row.createCell(start + 2).setCellValue(it.toDouble()) }
metadata.agentId?.let { row.createCell(start + 3).setCellValue(it.toString()) }
metadata.appliedAgentSettlementRatio?.let { row.createCell(start + 4).setCellValue(it.toDouble()) }
}
private fun createExcelStream(
sheetName: String,
headers: List<String>,
writeRows: (Sheet) -> Unit
): StreamingResponseBody {
return StreamingResponseBody { outputStream ->
val workbook = SXSSFWorkbook(100)
try {
val sheet = workbook.createSheet(sheetName)
val headerRow = sheet.createRow(0)
headers.forEachIndexed { index, value ->
headerRow.createCell(index).setCellValue(value)
}
exportTransaction.executeWithoutResult {
SXSSFWorkbook(100).use { workbook ->
try {
val sheet = workbook.createSheet(sheetName)
val headerRow = sheet.createRow(0)
(headers + METADATA_HEADERS).forEachIndexed { index, value ->
headerRow.createCell(index).setCellValue(value)
}
writeRows(sheet)
workbook.write(outputStream)
outputStream.flush()
} finally {
workbook.dispose()
workbook.close()
writeRows(sheet)
workbook.write(outputStream)
outputStream.flush()
} finally {
workbook.dispose()
}
}
}
}
}
@@ -155,4 +190,15 @@ class AdminChannelDonationCalculateService(
return startDate to endDate
}
companion object {
private const val EXPORT_PAGE_SIZE = 512L
private val METADATA_HEADERS = listOf(
"행 식별키",
"거래 구분",
"크리에이터 정산 비율(%)",
"에이전트 번호",
"에이전트 정산 비율(%)"
)
}
}
@@ -1,6 +1,7 @@
package kr.co.vividnext.sodalive.admin.calculate.channelDonation
import com.fasterxml.jackson.annotation.JsonProperty
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementCountryRelation
data class GetAdminChannelDonationSettlementByCreatorItem(
@JsonProperty("creator") val creator: String,
@@ -10,5 +11,11 @@ data class GetAdminChannelDonationSettlementByCreatorItem(
@JsonProperty("fee") val fee: Int,
@JsonProperty("settlementAmount") val settlementAmount: Int,
@JsonProperty("withholdingTax") val withholdingTax: Int,
@JsonProperty("depositAmount") val depositAmount: Int
@JsonProperty("depositAmount") val depositAmount: Int,
@JsonProperty("rowKey") val rowKey: String = "",
@JsonProperty("countryRelation") val countryRelation: SettlementCountryRelation? = null,
@JsonProperty("appliedSettlementRatio") val appliedSettlementRatio: Int? = null,
@JsonProperty("agentId") val agentId: Long? = null,
@JsonProperty("appliedAgentSettlementRatio") val appliedAgentSettlementRatio: Int? = null,
@JsonProperty("rateInfoAvailable") val rateInfoAvailable: Boolean = false
)
@@ -1,30 +1,41 @@
package kr.co.vividnext.sodalive.admin.calculate.channelDonation
import com.querydsl.core.annotations.QueryProjection
import kr.co.vividnext.sodalive.calculate.channelDonation.ChannelDonationSettlementCalculator
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementAmounts
import kr.co.vividnext.sodalive.v2.settlement.dto.SettlementRateMetadata
data class GetAdminChannelDonationSettlementByCreatorQueryData @QueryProjection constructor(
data class GetAdminChannelDonationSettlementByCreatorQueryData(
val creator: String,
val count: Long,
val totalCan: Int?,
val newPolicyCan: Int = 0,
val newPolicyWeightedRatioCan: Long = 0
val amount: SettlementAmounts = legacyChannelDonationAmounts((totalCan ?: 0).toLong()),
val metadata: SettlementRateMetadata = legacyChannelDonationMetadata("channel-creator", listOf(null))
) {
@QueryProjection
constructor(creator: String, count: Long, totalCan: Int?) : this(creator, count, totalCan, 0, 0)
constructor(creator: String, count: Long, totalCan: Int?) : this(
creator,
count,
totalCan,
legacyChannelDonationAmounts((totalCan ?: 0).toLong()),
legacyChannelDonationMetadata("channel-creator", listOf(null))
)
fun toResponseItem(): GetAdminChannelDonationSettlementByCreatorItem {
val settlement = ChannelDonationSettlementCalculator.calculate(totalCan ?: 0, newPolicyCan, newPolicyWeightedRatioCan)
return GetAdminChannelDonationSettlementByCreatorItem(
creator = creator,
count = count.toInt(),
totalCan = totalCan ?: 0,
krw = settlement.krw,
fee = settlement.fee,
settlementAmount = settlement.settlementAmount,
withholdingTax = settlement.withholdingTax,
depositAmount = settlement.depositAmount
count = Math.toIntExact(count),
totalCan = Math.toIntExact(amount.totalCan),
krw = Math.toIntExact(amount.grossAmount),
fee = Math.toIntExact(amount.paymentFee),
settlementAmount = Math.toIntExact(amount.settlementAmount),
withholdingTax = Math.toIntExact(amount.withholdingTax),
depositAmount = Math.toIntExact(amount.depositAmount),
rowKey = metadata.rowKey,
countryRelation = metadata.countryRelation,
appliedSettlementRatio = metadata.appliedSettlementRatio,
agentId = metadata.agentId,
appliedAgentSettlementRatio = metadata.appliedAgentSettlementRatio,
rateInfoAvailable = metadata.rateInfoAvailable
)
}
}
@@ -1,6 +1,7 @@
package kr.co.vividnext.sodalive.admin.calculate.channelDonation
import com.fasterxml.jackson.annotation.JsonProperty
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementCountryRelation
data class GetAdminChannelDonationSettlementItem(
@JsonProperty("date") val date: String,
@@ -11,5 +12,11 @@ data class GetAdminChannelDonationSettlementItem(
@JsonProperty("fee") val fee: Int,
@JsonProperty("settlementAmount") val settlementAmount: Int,
@JsonProperty("withholdingTax") val withholdingTax: Int,
@JsonProperty("depositAmount") val depositAmount: Int
@JsonProperty("depositAmount") val depositAmount: Int,
@JsonProperty("rowKey") val rowKey: String = "",
@JsonProperty("countryRelation") val countryRelation: SettlementCountryRelation? = null,
@JsonProperty("appliedSettlementRatio") val appliedSettlementRatio: Int? = null,
@JsonProperty("agentId") val agentId: Long? = null,
@JsonProperty("appliedAgentSettlementRatio") val appliedAgentSettlementRatio: Int? = null,
@JsonProperty("rateInfoAvailable") val rateInfoAvailable: Boolean = false
)
@@ -1,32 +1,44 @@
package kr.co.vividnext.sodalive.admin.calculate.channelDonation
import com.querydsl.core.annotations.QueryProjection
import kr.co.vividnext.sodalive.calculate.channelDonation.ChannelDonationSettlementCalculator
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementAmounts
import kr.co.vividnext.sodalive.v2.settlement.dto.SettlementRateMetadata
data class GetAdminChannelDonationSettlementQueryData @QueryProjection constructor(
data class GetAdminChannelDonationSettlementQueryData(
val date: String,
val creator: String,
val count: Long,
val totalCan: Int?,
val newPolicyCan: Int = 0,
val newPolicyWeightedRatioCan: Long = 0
val amount: SettlementAmounts = legacyChannelDonationAmounts((totalCan ?: 0).toLong()),
val metadata: SettlementRateMetadata = legacyChannelDonationMetadata("channel-date", listOf(null, date))
) {
@QueryProjection
constructor(date: String, creator: String, count: Long, totalCan: Int?) : this(date, creator, count, totalCan, 0, 0)
constructor(date: String, creator: String, count: Long, totalCan: Int?) : this(
date,
creator,
count,
totalCan,
legacyChannelDonationAmounts((totalCan ?: 0).toLong()),
legacyChannelDonationMetadata("channel-date", listOf(null, date))
)
fun toResponseItem(): GetAdminChannelDonationSettlementItem {
val settlement = ChannelDonationSettlementCalculator.calculate(totalCan ?: 0, newPolicyCan, newPolicyWeightedRatioCan)
return GetAdminChannelDonationSettlementItem(
date = date,
creator = creator,
count = count.toInt(),
totalCan = totalCan ?: 0,
krw = settlement.krw,
fee = settlement.fee,
settlementAmount = settlement.settlementAmount,
withholdingTax = settlement.withholdingTax,
depositAmount = settlement.depositAmount
count = Math.toIntExact(count),
totalCan = Math.toIntExact(amount.totalCan),
krw = Math.toIntExact(amount.grossAmount),
fee = Math.toIntExact(amount.paymentFee),
settlementAmount = Math.toIntExact(amount.settlementAmount),
withholdingTax = Math.toIntExact(amount.withholdingTax),
depositAmount = Math.toIntExact(amount.depositAmount),
rowKey = metadata.rowKey,
countryRelation = metadata.countryRelation,
appliedSettlementRatio = metadata.appliedSettlementRatio,
agentId = metadata.agentId,
appliedAgentSettlementRatio = metadata.appliedAgentSettlementRatio,
rateInfoAvailable = metadata.rateInfoAvailable
)
}
}
@@ -2,28 +2,48 @@ package kr.co.vividnext.sodalive.admin.calculate.channelDonation
import com.querydsl.core.annotations.QueryProjection
import kr.co.vividnext.sodalive.calculate.channelDonation.ChannelDonationSettlementCalculator
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementAmounts
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementCountryRelation
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementRowKey
import kr.co.vividnext.sodalive.v2.settlement.dto.SettlementRateMetadata
data class GetAdminChannelDonationSettlementTotalQueryData @QueryProjection constructor(
data class GetAdminChannelDonationSettlementTotalQueryData(
val count: Long?,
val totalCan: Int?,
val newPolicyCan: Int = 0,
val newPolicyWeightedRatioCan: Long = 0
val amount: SettlementAmounts = legacyChannelDonationAmounts((totalCan ?: 0).toLong())
) {
@QueryProjection
constructor(count: Long?, totalCan: Int?) : this(count, totalCan, 0, 0)
constructor(count: Long?, totalCan: Int?) : this(
count,
totalCan,
legacyChannelDonationAmounts((totalCan ?: 0).toLong())
)
fun toResponseTotal(): GetAdminChannelDonationSettlementTotal {
val totalCan = totalCan ?: 0
val settlement = ChannelDonationSettlementCalculator.calculate(totalCan, newPolicyCan, newPolicyWeightedRatioCan)
return GetAdminChannelDonationSettlementTotal(
count = (count ?: 0L).toInt(),
totalCan = totalCan,
krw = settlement.krw,
fee = settlement.fee,
settlementAmount = settlement.settlementAmount,
withholdingTax = settlement.withholdingTax,
depositAmount = settlement.depositAmount
count = Math.toIntExact(count ?: 0L),
totalCan = Math.toIntExact(amount.totalCan),
krw = Math.toIntExact(amount.grossAmount),
fee = Math.toIntExact(amount.paymentFee),
settlementAmount = Math.toIntExact(amount.settlementAmount),
withholdingTax = Math.toIntExact(amount.withholdingTax),
depositAmount = Math.toIntExact(amount.depositAmount)
)
}
}
internal fun legacyChannelDonationAmounts(totalCan: Long): SettlementAmounts {
val settlement = ChannelDonationSettlementCalculator.calculateAtRatio(totalCan, 85)
return SettlementAmounts(
totalCan,
settlement.krw,
settlement.fee,
settlement.settlementAmount,
settlement.withholdingTax,
settlement.depositAmount,
0
)
}
internal fun legacyChannelDonationMetadata(route: String, identity: List<String?>): SettlementRateMetadata =
SettlementRateMetadata(SettlementRowKey.legacy(route, identity), SettlementCountryRelation.LEGACY, 85, null, null, false)
@@ -1,14 +1,10 @@
package kr.co.vividnext.sodalive.admin.partner.agent.settlement
import kr.co.vividnext.sodalive.common.SodaException
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.calculate.AgentCalculateQueryRepository
import kr.co.vividnext.sodalive.partner.agent.calculate.GetAgentChannelDonationSettlementByCreatorItem
import kr.co.vividnext.sodalive.partner.agent.calculate.GetAgentChannelDonationSettlementByCreatorQueryData
import kr.co.vividnext.sodalive.partner.agent.calculate.GetAgentCreatorSettlementSummaryQueryData
import kr.co.vividnext.sodalive.partner.agent.calculate.GetAgentSettlementByCreatorItem
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.AgentSettlementSnapshotSourceDetail
@@ -16,10 +12,16 @@ import kr.co.vividnext.sodalive.partner.agent.settlement.snapshot.AgentSettlemen
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.partner.agent.settlement.snapshot.FinalizeAgentSettlementSnapshotResponse
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.SettlementRowKey
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementSource
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.LocalDateTime
import java.time.temporal.ChronoUnit
@Service
class AdminAgentSettlementSnapshotService(
@@ -28,354 +30,165 @@ class AdminAgentSettlementSnapshotService(
private val calculateRepository: AgentCalculateQueryRepository,
private val memberRepository: MemberRepository
) {
private data class SourceDetailDraft(
val creatorId: Long,
val assignmentId: Long?,
val agentSettlementRatioId: Long?,
val appliedAgentSettlementRatio: Int?,
val count: Int,
val totalCan: Int,
val krw: Int,
val fee: Int,
val settlementAmount: Int,
val tax: Int,
val depositAmount: Int,
val agentSettlementAmount: Int
)
private data class SnapshotFinalizeDraft(
val snapshots: List<AgentSettlementSnapshot>,
val sourceDetailsByCreatorId: Map<Long, List<SourceDetailDraft>>
)
private data class SnapshotAggregateDraft(
private data class SourceRow(
val creatorId: Long,
val creatorNickname: String,
var assignmentId: Long? = null,
var agentSettlementRatioId: Long? = null,
var appliedAgentSettlementRatio: Int? = null,
var sourceRowCount: Int = 0,
var count: Int = 0,
var totalCan: Int = 0,
var krw: Int = 0,
var fee: Int = 0,
var settlementAmount: Int = 0,
var tax: Int = 0,
var depositAmount: Int = 0,
var agentSettlementAmount: Int = 0,
val sourceDetails: MutableList<SourceDetailDraft> = mutableListOf()
) {
fun add(
assignmentId: Long?,
agentSettlementRatioId: Long?,
appliedAgentSettlementRatio: Int?,
count: Int,
totalCan: Int,
krw: Int,
fee: Int,
settlementAmount: Int,
tax: Int,
depositAmount: Int,
agentSettlementAmount: Int,
sourceDetail: SourceDetailDraft
) {
sourceRowCount += 1
this.assignmentId = if (sourceRowCount == 1) assignmentId else null
this.agentSettlementRatioId = if (sourceRowCount == 1) agentSettlementRatioId else null
this.appliedAgentSettlementRatio = if (sourceRowCount == 1) appliedAgentSettlementRatio else null
this.count += count
this.totalCan += totalCan
this.krw += krw
this.fee += fee
this.settlementAmount += settlementAmount
this.tax += tax
this.depositAmount += depositAmount
this.agentSettlementAmount += agentSettlementAmount
sourceDetails.add(sourceDetail)
}
}
val assignmentId: Long?,
val ratioId: Long?,
val agentRatio: Int?,
val count: Long,
val amount: SettlementAmounts,
val canonical: Boolean
)
@Transactional
@Transactional(isolation = Isolation.REPEATABLE_READ)
fun finalizeSnapshots(
request: FinalizeAgentSettlementSnapshotRequest,
finalizedByMemberId: Long
): FinalizeAgentSettlementSnapshotResponse {
val (startDate, endDate) = request.toDateRange()
val (start, end) = request.toDateRange()
if (
snapshotRepository.existsByPeriodStartAndPeriodEndAndSettlementTypeAndAgentId(
periodStart = startDate,
periodEnd = endDate,
settlementType = request.settlementType,
agentId = request.agentId
start,
end,
request.settlementType,
request.agentId
)
) {
return FinalizeAgentSettlementSnapshotResponse(finalizedCount = 0, alreadyFinalized = true)
return FinalizeAgentSettlementSnapshotResponse(0, true)
}
val agent = getAgent(request.agentId)
val finalizedAt = LocalDateTime.now()
val draft = when (request.settlementType) {
AgentSettlementSnapshotType.LIVE -> buildGenericSnapshots(
request = request,
agent = agent,
finalizedAt = finalizedAt,
finalizedByMemberId = finalizedByMemberId,
rows = calculateRepository.getCalculateLiveByCreator(startDate, endDate, request.agentId)
)
AgentSettlementSnapshotType.CONTENT -> buildGenericSnapshots(
request = request,
agent = agent,
finalizedAt = finalizedAt,
finalizedByMemberId = finalizedByMemberId,
rows = calculateRepository.getCalculateContentByCreator(startDate, endDate, request.agentId)
)
AgentSettlementSnapshotType.COMMUNITY -> buildGenericSnapshots(
request = request,
agent = agent,
finalizedAt = finalizedAt,
finalizedByMemberId = finalizedByMemberId,
rows = calculateRepository.getCalculateCommunityByCreator(startDate, endDate, request.agentId)
)
AgentSettlementSnapshotType.CONTENT_DONATION -> buildGenericSnapshots(
request = request,
agent = agent,
finalizedAt = finalizedAt,
finalizedByMemberId = finalizedByMemberId,
rows = calculateRepository.getCalculateContentDonationByCreator(startDate, endDate, request.agentId)
)
AgentSettlementSnapshotType.CHANNEL_DONATION -> buildChannelSnapshots(
request = request,
agent = agent,
finalizedAt = finalizedAt,
finalizedByMemberId = finalizedByMemberId,
rows = calculateRepository.getChannelDonationByCreator(startDate, endDate, request.agentId)
)
}
if (draft.snapshots.isNotEmpty()) {
snapshotRepository.saveAll(draft.snapshots)
sourceDetailRepository.saveAll(buildSourceDetails(draft))
}
return FinalizeAgentSettlementSnapshotResponse(finalizedCount = draft.snapshots.size, alreadyFinalized = false)
}
private fun getAgent(agentId: Long): Member {
val agent = memberRepository.findByIdOrNull(agentId)
val agent = memberRepository.findByIdOrNull(request.agentId)
?: throw SodaException(messageKey = "partner.agent.ratio.agent_not_found")
if (agent.role != MemberRole.AGENT) {
throw SodaException(messageKey = "partner.agent.ratio.invalid_agent")
if (agent.role != MemberRole.AGENT) throw SodaException(messageKey = "partner.agent.ratio.invalid_agent")
val finalizedAt = LocalDateTime.now().truncatedTo(ChronoUnit.SECONDS)
val rows = when (request.settlementType) {
AgentSettlementSnapshotType.LIVE ->
genericRows(calculateRepository.getCalculateLiveByCreator(start, end, request.agentId))
AgentSettlementSnapshotType.CONTENT ->
genericRows(calculateRepository.getCalculateContentByCreator(start, end, request.agentId))
AgentSettlementSnapshotType.COMMUNITY ->
genericRows(calculateRepository.getCalculateCommunityByCreator(start, end, request.agentId))
AgentSettlementSnapshotType.CONTENT_DONATION ->
genericRows(calculateRepository.getCalculateContentDonationByCreator(start, end, request.agentId))
AgentSettlementSnapshotType.CHANNEL_DONATION ->
calculateRepository.getChannelDonationByCreator(start, end, request.agentId).map { row ->
val item = row.toResponseItem()
SourceRow(
row.creatorId,
row.creatorNickname,
row.assignmentId,
row.agentSettlementRatioId,
row.agentSettlementRatio,
item.count.toLong(),
SettlementAmounts(
item.totalCan.toLong(),
item.krw.toLong(),
item.fee.toLong(),
item.settlementAmount.toLong(),
item.withholdingTax.toLong(),
item.depositAmount.toLong(),
item.agentSettlementAmount.toLong()
),
row.metadata?.rateInfoAvailable == true
)
}
}
return agent
val snapshots = rows.groupBy { it.creatorId }.mapValues { (creatorId, sources) ->
val amount = sources.fold(SettlementAmounts.ZERO) { sum, row -> sum + row.amount }
val single = sources.singleOrNull()
AgentSettlementSnapshot(
periodStart = start, periodEnd = end, settlementType = request.settlementType,
agentId = request.agentId, agentNickname = agent.nickname,
creatorId = creatorId, creatorNickname = sources.first().creatorNickname,
assignmentId = single?.assignmentId, agentSettlementRatioId = single?.ratioId,
appliedAgentSettlementRatio = single?.agentRatio,
count = Math.toIntExact(sources.fold(0L) { count, row -> Math.addExact(count, row.count) }),
totalCan = Math.toIntExact(amount.totalCan), krw = Math.toIntExact(amount.grossAmount),
fee = Math.toIntExact(amount.paymentFee), settlementAmount = Math.toIntExact(amount.settlementAmount),
tax = Math.toIntExact(amount.withholdingTax), depositAmount = Math.toIntExact(amount.depositAmount),
agentSettlementAmount = Math.toIntExact(amount.agentSettlementAmount),
finalizedAt = finalizedAt, finalizedByMemberId = finalizedByMemberId
)
}
if (snapshots.isEmpty()) return FinalizeAgentSettlementSnapshotResponse(0, false)
snapshotRepository.saveAll(snapshots.values.toList())
val legacyDetails = rows.filterNot { it.canonical }.map { row ->
AgentSettlementSnapshotSourceDetail(
snapshot = snapshots.getValue(row.creatorId), assignmentId = row.assignmentId,
agentSettlementRatioId = row.ratioId, appliedAgentSettlementRatio = row.agentRatio,
count = Math.toIntExact(row.count), totalCan = Math.toIntExact(row.amount.totalCan),
krw = Math.toIntExact(row.amount.grossAmount), fee = Math.toIntExact(row.amount.paymentFee),
settlementAmount = Math.toIntExact(row.amount.settlementAmount), tax = Math.toIntExact(row.amount.withholdingTax),
depositAmount = Math.toIntExact(row.amount.depositAmount),
agentSettlementAmount = Math.toIntExact(row.amount.agentSettlementAmount)
)
}
if (legacyDetails.isNotEmpty()) sourceDetailRepository.saveAll(legacyDetails)
if (!end.isBefore(CountrySettlementPolicy().effectiveAtUtc)) {
val source = when (request.settlementType) {
AgentSettlementSnapshotType.LIVE -> SettlementSource.LIVE
AgentSettlementSnapshotType.CONTENT -> SettlementSource.CONTENT_SALES
AgentSettlementSnapshotType.COMMUNITY -> SettlementSource.COMMUNITY_POST
AgentSettlementSnapshotType.CONTENT_DONATION -> SettlementSource.CONTENT_DONATION
AgentSettlementSnapshotType.CHANNEL_DONATION -> SettlementSource.CHANNEL_DONATION
}
var offset = 0L
do {
val page = calculateRepository.readCanonicalSettlementPage(start, end, request.agentId, source, offset, 256)
if (page.isEmpty()) break
val provenance = calculateRepository.getCanonicalProvenance(
start,
end,
request.agentId,
source,
page.map { it.key }
)
sourceDetailRepository.saveAll(
page.map { row ->
val references = provenance.getValue(row.key)
val economics = row.key.economics
AgentSettlementSnapshotSourceDetail(
snapshot = snapshots.getValue(row.key.creatorId),
assignmentId = references.map { it.assignmentId }.distinct().singleOrNull(),
agentSettlementRatioId = references.map { it.agentSettlementRatioId }.distinct().singleOrNull(),
appliedAgentSettlementRatio = economics.appliedAgentSettlementRatio,
count = Math.toIntExact(row.transactionCount), totalCan = Math.toIntExact(row.amount.totalCan),
krw = Math.toIntExact(row.amount.grossAmount), fee = Math.toIntExact(row.amount.paymentFee),
settlementAmount = Math.toIntExact(row.amount.settlementAmount),
tax = Math.toIntExact(row.amount.withholdingTax),
depositAmount = Math.toIntExact(row.amount.depositAmount),
agentSettlementAmount = Math.toIntExact(row.amount.agentSettlementAmount),
canonicalRowKey = SettlementRowKey.canonical(row.key), countryRelation = economics.countryRelation,
appliedSettlementRatio = economics.appliedSettlementRatio, rateInfoAvailable = true,
provenance = references
)
}
)
offset = Math.addExact(offset, page.size.toLong())
} while (page.size == 256)
}
return FinalizeAgentSettlementSnapshotResponse(snapshots.size, false)
}
private fun buildGenericSnapshots(
request: FinalizeAgentSettlementSnapshotRequest,
agent: Member,
finalizedAt: LocalDateTime,
finalizedByMemberId: Long,
rows: List<GetAgentCreatorSettlementSummaryQueryData>
): SnapshotFinalizeDraft {
val (startDate, endDate) = request.toDateRange()
val aggregateDrafts = linkedMapOf<Long, SnapshotAggregateDraft>()
rows.forEach { row ->
val item = row.toResponseItem()
val sourceDetail = item.toSourceDetailDraft(
assignmentId = row.assignmentId,
agentSettlementRatioId = row.agentSettlementRatioId,
appliedAgentSettlementRatio = row.agentSettlementRatio
)
val aggregate = aggregateDrafts.getOrPut(row.creatorId) {
SnapshotAggregateDraft(
creatorId = row.creatorId,
creatorNickname = item.creatorNickname
)
}
aggregate.add(
assignmentId = row.assignmentId,
agentSettlementRatioId = row.agentSettlementRatioId,
appliedAgentSettlementRatio = row.agentSettlementRatio,
count = item.count,
totalCan = item.totalCan,
krw = item.krw,
fee = item.fee,
settlementAmount = item.settlementAmount,
tax = item.tax,
depositAmount = item.depositAmount,
agentSettlementAmount = item.agentSettlementAmount,
sourceDetail = sourceDetail
)
}
val snapshots = aggregateDrafts.values.map { aggregate ->
AgentSettlementSnapshot(
periodStart = startDate,
periodEnd = endDate,
settlementType = request.settlementType,
agentId = agent.id!!,
agentNickname = agent.nickname,
creatorId = aggregate.creatorId,
creatorNickname = aggregate.creatorNickname,
assignmentId = aggregate.assignmentId,
agentSettlementRatioId = aggregate.agentSettlementRatioId,
appliedAgentSettlementRatio = aggregate.appliedAgentSettlementRatio,
count = aggregate.count,
totalCan = aggregate.totalCan,
krw = aggregate.krw,
fee = aggregate.fee,
settlementAmount = aggregate.settlementAmount,
tax = aggregate.tax,
depositAmount = aggregate.depositAmount,
agentSettlementAmount = aggregate.agentSettlementAmount,
finalizedAt = finalizedAt,
finalizedByMemberId = finalizedByMemberId
)
}
return SnapshotFinalizeDraft(
snapshots = snapshots,
sourceDetailsByCreatorId = aggregateDrafts.mapValues { (_, aggregate) ->
aggregate.sourceDetails.toList()
}
private fun genericRows(rows: List<GetAgentCreatorSettlementSummaryQueryData>): List<SourceRow> = rows.map { row ->
val item = row.toResponseItem()
SourceRow(
row.creatorId,
row.creatorNickname,
row.assignmentId,
row.agentSettlementRatioId,
row.agentSettlementRatio,
item.count.toLong(),
SettlementAmounts(
item.totalCan.toLong(),
item.krw.toLong(),
item.fee.toLong(),
item.settlementAmount.toLong(),
item.tax.toLong(),
item.depositAmount.toLong(),
item.agentSettlementAmount.toLong()
),
row.metadata?.rateInfoAvailable == true
)
}
private fun buildChannelSnapshots(
request: FinalizeAgentSettlementSnapshotRequest,
agent: Member,
finalizedAt: LocalDateTime,
finalizedByMemberId: Long,
rows: List<GetAgentChannelDonationSettlementByCreatorQueryData>
): SnapshotFinalizeDraft {
val (startDate, endDate) = request.toDateRange()
val aggregateDrafts = linkedMapOf<Long, SnapshotAggregateDraft>()
rows.forEach { row ->
val item = row.toResponseItem()
val sourceDetail = item.toSourceDetailDraft(
assignmentId = row.assignmentId,
agentSettlementRatioId = row.agentSettlementRatioId,
appliedAgentSettlementRatio = row.agentSettlementRatio
)
val aggregate = aggregateDrafts.getOrPut(row.creatorId) {
SnapshotAggregateDraft(
creatorId = row.creatorId,
creatorNickname = item.creatorNickname
)
}
aggregate.add(
assignmentId = row.assignmentId,
agentSettlementRatioId = row.agentSettlementRatioId,
appliedAgentSettlementRatio = row.agentSettlementRatio,
count = item.count,
totalCan = item.totalCan,
krw = item.krw,
fee = item.fee,
settlementAmount = item.settlementAmount,
tax = item.withholdingTax,
depositAmount = item.depositAmount,
agentSettlementAmount = item.agentSettlementAmount,
sourceDetail = sourceDetail
)
}
val snapshots = aggregateDrafts.values.map { aggregate ->
AgentSettlementSnapshot(
periodStart = startDate,
periodEnd = endDate,
settlementType = request.settlementType,
agentId = agent.id!!,
agentNickname = agent.nickname,
creatorId = aggregate.creatorId,
creatorNickname = aggregate.creatorNickname,
assignmentId = aggregate.assignmentId,
agentSettlementRatioId = aggregate.agentSettlementRatioId,
appliedAgentSettlementRatio = aggregate.appliedAgentSettlementRatio,
count = aggregate.count,
totalCan = aggregate.totalCan,
krw = aggregate.krw,
fee = aggregate.fee,
settlementAmount = aggregate.settlementAmount,
tax = aggregate.tax,
depositAmount = aggregate.depositAmount,
agentSettlementAmount = aggregate.agentSettlementAmount,
finalizedAt = finalizedAt,
finalizedByMemberId = finalizedByMemberId
)
}
return SnapshotFinalizeDraft(
snapshots = snapshots,
sourceDetailsByCreatorId = aggregateDrafts.mapValues { (_, aggregate) ->
aggregate.sourceDetails.toList()
}
)
}
private fun buildSourceDetails(draft: SnapshotFinalizeDraft): List<AgentSettlementSnapshotSourceDetail> {
val snapshotsByCreatorId = draft.snapshots.associateBy { it.creatorId }
return draft.sourceDetailsByCreatorId.flatMap { (creatorId, sourceDetails) ->
val snapshot = snapshotsByCreatorId.getValue(creatorId)
sourceDetails.map { detail ->
AgentSettlementSnapshotSourceDetail(
snapshot = snapshot,
assignmentId = detail.assignmentId,
agentSettlementRatioId = detail.agentSettlementRatioId,
appliedAgentSettlementRatio = detail.appliedAgentSettlementRatio,
count = detail.count,
totalCan = detail.totalCan,
krw = detail.krw,
fee = detail.fee,
settlementAmount = detail.settlementAmount,
tax = detail.tax,
depositAmount = detail.depositAmount,
agentSettlementAmount = detail.agentSettlementAmount
)
}
}
}
private fun GetAgentSettlementByCreatorItem.toSourceDetailDraft(
assignmentId: Long?,
agentSettlementRatioId: Long?,
appliedAgentSettlementRatio: Int?
) = SourceDetailDraft(
creatorId = creatorId,
assignmentId = assignmentId,
agentSettlementRatioId = agentSettlementRatioId,
appliedAgentSettlementRatio = appliedAgentSettlementRatio,
count = count,
totalCan = totalCan,
krw = krw,
fee = fee,
settlementAmount = settlementAmount,
tax = tax,
depositAmount = depositAmount,
agentSettlementAmount = agentSettlementAmount
)
private fun GetAgentChannelDonationSettlementByCreatorItem.toSourceDetailDraft(
assignmentId: Long?,
agentSettlementRatioId: Long?,
appliedAgentSettlementRatio: Int?
) = SourceDetailDraft(
creatorId = creatorId,
assignmentId = assignmentId,
agentSettlementRatioId = agentSettlementRatioId,
appliedAgentSettlementRatio = appliedAgentSettlementRatio,
count = count,
totalCan = totalCan,
krw = krw,
fee = fee,
settlementAmount = settlementAmount,
tax = withholdingTax,
depositAmount = depositAmount,
agentSettlementAmount = agentSettlementAmount
)
}
@@ -11,25 +11,34 @@ data class ChannelDonationSettlementAmount(
val depositAmount: Int
)
data class ChannelDonationSettlementLongAmount(
val krw: Long,
val fee: Long,
val settlementAmount: Long,
val withholdingTax: Long,
val depositAmount: Long
)
object ChannelDonationSettlementCalculator {
private val KRW_PER_CAN = BigDecimal("100")
private val FEE_RATE = BigDecimal("0.066")
private val SETTLEMENT_RATE = BigDecimal("0.85")
private val WITHHOLDING_TAX_RATE = BigDecimal("0.033")
fun calculate(totalCan: Int, newPolicyCan: Int, newPolicyWeightedRatioCan: Long): ChannelDonationSettlementAmount {
if (newPolicyCan == 0 && newPolicyWeightedRatioCan == 0L) return calculate(totalCan)
val krw = BigDecimal(totalCan).multiply(KRW_PER_CAN).setScale(0, RoundingMode.HALF_UP).toInt()
val fee = BigDecimal(krw).multiply(FEE_RATE).setScale(0, RoundingMode.HALF_UP).toInt()
val weightedRatioCan = BigDecimal(totalCan.toLong() - newPolicyCan.toLong())
.multiply(SETTLEMENT_RATE).multiply(KRW_PER_CAN).add(BigDecimal(newPolicyWeightedRatioCan))
// 비율을 나눠 반올림하지 않고 분자 전체를 곱한 뒤 정산액을 한 번 반올림한다.
val settlementAmount = BigDecimal(krw - fee).multiply(weightedRatioCan)
.divide(BigDecimal(totalCan).multiply(KRW_PER_CAN), 0, RoundingMode.HALF_UP).toInt()
val withholdingTax = BigDecimal(settlementAmount)
.multiply(WITHHOLDING_TAX_RATE).setScale(0, RoundingMode.HALF_UP).toInt()
return ChannelDonationSettlementAmount(krw, fee, settlementAmount, withholdingTax, settlementAmount - withholdingTax)
fun calculateAtRatio(totalCan: Long, appliedSettlementRatio: Int): ChannelDonationSettlementLongAmount {
val krw = BigDecimal(totalCan).multiply(KRW_PER_CAN).longValueExact()
val fee = BigDecimal(krw).multiply(FEE_RATE).setScale(0, RoundingMode.HALF_UP).longValueExact()
val settlementAmount = BigDecimal(krw).subtract(BigDecimal(fee)).multiply(BigDecimal(appliedSettlementRatio))
.divide(KRW_PER_CAN, 0, RoundingMode.HALF_UP).longValueExact()
val withholdingTax = BigDecimal(settlementAmount).multiply(WITHHOLDING_TAX_RATE)
.setScale(0, RoundingMode.HALF_UP).longValueExact()
return ChannelDonationSettlementLongAmount(
krw,
fee,
settlementAmount,
withholdingTax,
Math.subtractExact(settlementAmount, withholdingTax)
)
}
fun calculate(totalCan: Int): ChannelDonationSettlementAmount {
@@ -1,131 +1,22 @@
package kr.co.vividnext.sodalive.creator.admin.calculate
import com.querydsl.core.types.dsl.CaseBuilder
import com.querydsl.core.types.dsl.DateTimePath
import com.querydsl.core.types.dsl.Expressions
import com.querydsl.core.types.dsl.StringTemplate
import com.querydsl.jpa.impl.JPAQuery
import com.querydsl.jpa.impl.JPAQueryFactory
import kr.co.vividnext.sodalive.admin.calculate.GetCalculateCommunityPostQueryData
import kr.co.vividnext.sodalive.admin.calculate.GetCalculateContentDonationQueryData
import kr.co.vividnext.sodalive.admin.calculate.GetCalculateContentQueryData
import kr.co.vividnext.sodalive.admin.calculate.GetCalculateLiveQueryData
import kr.co.vividnext.sodalive.admin.calculate.GetCumulativeSalesByContentQueryData
import kr.co.vividnext.sodalive.admin.calculate.QGetCalculateCommunityPostQueryData
import kr.co.vividnext.sodalive.admin.calculate.QGetCalculateContentDonationQueryData
import kr.co.vividnext.sodalive.admin.calculate.QGetCalculateContentQueryData
import kr.co.vividnext.sodalive.admin.calculate.QGetCalculateLiveQueryData
import kr.co.vividnext.sodalive.admin.calculate.QGetCumulativeSalesByContentQueryData
import kr.co.vividnext.sodalive.admin.calculate.ratio.QCreatorSettlementRatio.creatorSettlementRatio
import kr.co.vividnext.sodalive.can.use.CanUsage
import kr.co.vividnext.sodalive.can.use.QUseCan.useCan
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.adapter.out.persistence.CountrySettlementExpressions
import kr.co.vividnext.sodalive.admin.calculate.AdminCalculateQueryRepository
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementScope
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementSource
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementWindow
import org.springframework.stereotype.Repository
import java.time.LocalDateTime
@Repository
class CreatorAdminCalculateQueryRepository(
private val queryFactory: JPAQueryFactory,
private val countrySettlementExpressions: CountrySettlementExpressions
) {
fun getCalculateLive(
startDate: LocalDateTime,
endDate: LocalDateTime,
memberId: Long
): List<GetCalculateLiveQueryData> {
return calculateLiveQuery(memberId)
.where(useCan.createdAt.goe(startDate), useCan.createdAt.loe(endDate))
.fetch()
}
class CreatorAdminCalculateQueryRepository(private val repository: AdminCalculateQueryRepository) {
fun getCalculateLive(startDate: LocalDateTime, endDate: LocalDateTime, memberId: Long) =
repository.readAllLive(scope(SettlementSource.LIVE, startDate, endDate, memberId))
fun getMonthlyCalculateLive(
startInclusiveUtc: LocalDateTime,
endExclusiveUtc: LocalDateTime,
memberId: Long
): List<GetCalculateLiveQueryData> {
return calculateLiveQuery(memberId)
.where(useCan.createdAt.goe(startInclusiveUtc), useCan.createdAt.lt(endExclusiveUtc))
.fetch()
}
fun getMonthlyCalculateLive(startInclusiveUtc: LocalDateTime, endExclusiveUtc: LocalDateTime, memberId: Long) =
repository.readAllLive(scope(SettlementSource.LIVE, startInclusiveUtc, endExclusiveUtc, memberId, true))
private fun calculateLiveQuery(memberId: Long): JPAQuery<GetCalculateLiveQueryData> {
val formattedDate = getFormattedDate(liveRoom.beginDateTime)
return queryFactory
.select(
QGetCalculateLiveQueryData(
member.nickname,
formattedDate,
liveRoom.title,
liveRoom.id,
liveRoom.price,
useCan.canUsage,
useCan.id.count(),
useCan.can.add(useCan.rewardCan).sum(),
creatorSettlementRatio.liveSettlementRatio,
countrySettlementExpressions.newPolicyCan(useCan.createdAt, useCan.can.add(useCan.rewardCan)),
countrySettlementExpressions.newPolicyWeightedRatioCan(
useCan.createdAt,
useCan.can.add(useCan.rewardCan),
member.countryCode,
useCan.countryCode,
creatorSettlementRatio.liveSettlementRatio
)
)
)
.from(useCan)
.innerJoin(useCan.room, liveRoom)
.innerJoin(liveRoom.member, member)
.leftJoin(creatorSettlementRatio)
.on(
member.id.eq(creatorSettlementRatio.member.id)
.and(creatorSettlementRatio.deletedAt.isNull)
)
.where(
useCan.isRefund.isFalse
.and(liveRoom.member.id.eq(memberId))
)
.groupBy(liveRoom.id, useCan.canUsage, creatorSettlementRatio.liveSettlementRatio)
.orderBy(liveRoom.id.desc(), useCan.canUsage.desc(), formattedDate.desc())
}
fun getCalculateContentListTotalCount(
startDate: LocalDateTime,
endDate: LocalDateTime,
memberId: Long
): Int {
val orderFormattedDate = getFormattedDate(order.createdAt)
val pointGroup = CaseBuilder()
.`when`(order.point.loe(0)).then(0)
.otherwise(1)
val contentSettlementRatio = audioContent.settlementRatio.coalesce(creatorSettlementRatio.contentSettlementRatio)
return queryFactory
.select(audioContent.id)
.from(order)
.innerJoin(order.audioContent, audioContent)
.innerJoin(audioContent.member, member)
.leftJoin(creatorSettlementRatio)
.on(
member.id.eq(creatorSettlementRatio.member.id)
.and(creatorSettlementRatio.deletedAt.isNull)
)
.where(
order.createdAt.goe(startDate)
.and(order.createdAt.loe(endDate))
.and(order.isActive.isTrue)
.and(order.creator.id.eq(memberId))
)
.groupBy(audioContent.id, order.type, orderFormattedDate, order.can, pointGroup, contentSettlementRatio)
.orderBy(member.id.desc(), orderFormattedDate.desc(), audioContent.id.asc())
.fetch()
.size
}
fun getCalculateContentListTotalCount(startDate: LocalDateTime, endDate: LocalDateTime, memberId: Long) =
repository.countContent(scope(SettlementSource.CONTENT_SALES, startDate, endDate, memberId))
fun getCalculateContentList(
startDate: LocalDateTime,
@@ -133,191 +24,19 @@ class CreatorAdminCalculateQueryRepository(
memberId: Long,
offset: Long,
limit: Long
): List<GetCalculateContentQueryData> {
return calculateContentQuery(memberId)
.where(order.createdAt.goe(startDate), order.createdAt.loe(endDate))
.offset(offset)
.limit(limit)
.fetch()
}
) = repository.readContent(scope(SettlementSource.CONTENT_SALES, startDate, endDate, memberId), offset, limit)
fun getMonthlyCalculateContentList(
startInclusiveUtc: LocalDateTime,
endExclusiveUtc: LocalDateTime,
memberId: Long
): List<GetCalculateContentQueryData> {
return calculateContentQuery(memberId)
.where(order.createdAt.goe(startInclusiveUtc), order.createdAt.lt(endExclusiveUtc))
.fetch()
}
fun getMonthlyCalculateContentList(startInclusiveUtc: LocalDateTime, endExclusiveUtc: LocalDateTime, memberId: Long) =
repository.readAllContent(scope(SettlementSource.CONTENT_SALES, startInclusiveUtc, endExclusiveUtc, memberId, true))
private fun calculateContentQuery(memberId: Long): JPAQuery<GetCalculateContentQueryData> {
val orderFormattedDate = getFormattedDate(order.createdAt)
val pointGroup = CaseBuilder()
.`when`(order.point.loe(0)).then(0)
.otherwise(1)
val contentSettlementRatio = audioContent.settlementRatio.coalesce(creatorSettlementRatio.contentSettlementRatio)
fun getCumulativeSalesByContentTotalCount(memberId: Long) =
repository.countCumulative(scope(SettlementSource.CONTENT_SALES, null, null, memberId))
return queryFactory
.select(
QGetCalculateContentQueryData(
member.nickname,
audioContent.title,
getFormattedDate(audioContent.createdAt),
orderFormattedDate,
order.type,
order.can,
order.id.count(),
order.can.sum(),
order.point.sum(),
contentSettlementRatio,
countrySettlementExpressions.newPolicyCan(order.createdAt, order.can),
countrySettlementExpressions.newPolicyWeightedRatioCan(
order.createdAt,
order.can,
member.countryCode,
useCan.countryCode,
contentSettlementRatio
)
)
)
.from(order)
.innerJoin(order.audioContent, audioContent)
.innerJoin(audioContent.member, member)
.leftJoin(useCan).on(useCan.order.id.eq(order.id))
.leftJoin(creatorSettlementRatio)
.on(
member.id.eq(creatorSettlementRatio.member.id)
.and(creatorSettlementRatio.deletedAt.isNull)
)
.where(
order.isActive.isTrue
.and(order.creator.id.eq(memberId))
)
.groupBy(
audioContent.id,
order.type,
orderFormattedDate,
order.can,
pointGroup,
contentSettlementRatio
)
.orderBy(member.id.desc(), orderFormattedDate.desc(), audioContent.id.asc())
}
fun getCumulativeSalesByContent(memberId: Long, offset: Long, limit: Long) =
repository.readCumulative(scope(SettlementSource.CONTENT_SALES, null, null, memberId), offset, limit)
private fun getFormattedDate(dateTimePath: DateTimePath<LocalDateTime>): StringTemplate {
return Expressions.stringTemplate(
"DATE_FORMAT(CONVERT_TZ({0}, 'UTC', 'Asia/Seoul'), '%Y-%m-%d')",
dateTimePath
)
}
fun getCumulativeSalesByContentTotalCount(memberId: Long): Int {
val pointGroup = CaseBuilder()
.`when`(order.point.loe(0)).then(0)
.otherwise(1)
val contentSettlementRatio = audioContent.settlementRatio.coalesce(creatorSettlementRatio.contentSettlementRatio)
return queryFactory
.select(audioContent.id)
.from(order)
.innerJoin(order.audioContent, audioContent)
.innerJoin(audioContent.member, member)
.leftJoin(creatorSettlementRatio)
.on(
member.id.eq(creatorSettlementRatio.member.id)
.and(creatorSettlementRatio.deletedAt.isNull)
)
.where(
audioContent.member.id.eq(memberId)
.and(order.isActive.isTrue)
)
.groupBy(member.id, audioContent.id, order.type, order.can, pointGroup, contentSettlementRatio)
.fetch()
.size
}
fun getCumulativeSalesByContent(
memberId: Long,
offset: Long,
limit: Long
): List<GetCumulativeSalesByContentQueryData> {
val pointGroup = CaseBuilder()
.`when`(order.point.loe(0)).then(0)
.otherwise(1)
val contentSettlementRatio = audioContent.settlementRatio.coalesce(creatorSettlementRatio.contentSettlementRatio)
return queryFactory
.select(
QGetCumulativeSalesByContentQueryData(
member.nickname,
audioContent.title,
getFormattedDate(audioContent.createdAt),
order.type,
order.can,
order.id.count(),
order.can.sum(),
order.point.sum(),
contentSettlementRatio,
countrySettlementExpressions.newPolicyCan(order.createdAt, order.can),
countrySettlementExpressions.newPolicyWeightedRatioCan(
order.createdAt,
order.can,
member.countryCode,
useCan.countryCode,
contentSettlementRatio
)
)
)
.from(order)
.innerJoin(order.audioContent, audioContent)
.innerJoin(audioContent.member, member)
.leftJoin(useCan).on(useCan.order.id.eq(order.id))
.leftJoin(creatorSettlementRatio)
.on(
member.id.eq(creatorSettlementRatio.member.id)
.and(creatorSettlementRatio.deletedAt.isNull)
)
.where(
audioContent.member.id.eq(memberId)
.and(order.isActive.isTrue)
)
.groupBy(
member.id,
audioContent.id,
order.type,
order.can,
pointGroup,
contentSettlementRatio
)
.offset(offset)
.limit(limit)
.orderBy(member.id.desc(), audioContent.id.desc())
.fetch()
}
fun getCalculateContentDonationListTotalCount(
startDate: LocalDateTime,
endDate: LocalDateTime,
memberId: Long
): Int {
val donationFormattedDate = getFormattedDate(useCan.createdAt)
return queryFactory
.select(audioContent.id)
.from(useCan)
.innerJoin(useCan.audioContent, audioContent)
.innerJoin(audioContent.member, member)
.where(
useCan.isRefund.isFalse
.and(useCan.canUsage.eq(CanUsage.DONATION))
.and(useCan.createdAt.goe(startDate))
.and(useCan.createdAt.loe(endDate))
.and(audioContent.member.id.eq(memberId))
)
.groupBy(donationFormattedDate, audioContent.id)
.fetch()
.size
}
fun getCalculateContentDonationListTotalCount(startDate: LocalDateTime, endDate: LocalDateTime, memberId: Long) =
repository.countDonation(scope(SettlementSource.CONTENT_DONATION, startDate, endDate, memberId))
fun getCalculateContentDonationList(
startDate: LocalDateTime,
@@ -325,75 +44,13 @@ class CreatorAdminCalculateQueryRepository(
memberId: Long,
offset: Long,
limit: Long
): List<GetCalculateContentDonationQueryData> {
return calculateContentDonationQuery(memberId)
.where(useCan.createdAt.goe(startDate), useCan.createdAt.loe(endDate))
.offset(offset)
.limit(limit)
.fetch()
}
) = repository.readDonation(scope(SettlementSource.CONTENT_DONATION, startDate, endDate, memberId), offset, limit)
fun getMonthlyCalculateContentDonationList(
startInclusiveUtc: LocalDateTime,
endExclusiveUtc: LocalDateTime,
memberId: Long
): List<GetCalculateContentDonationQueryData> {
return calculateContentDonationQuery(memberId)
.where(useCan.createdAt.goe(startInclusiveUtc), useCan.createdAt.lt(endExclusiveUtc))
.fetch()
}
fun getMonthlyCalculateContentDonationList(startInclusiveUtc: LocalDateTime, endExclusiveUtc: LocalDateTime, memberId: Long) =
repository.readAllDonation(scope(SettlementSource.CONTENT_DONATION, startInclusiveUtc, endExclusiveUtc, memberId, true))
private fun calculateContentDonationQuery(memberId: Long): JPAQuery<GetCalculateContentDonationQueryData> {
val donationFormattedDate = getFormattedDate(useCan.createdAt)
return queryFactory
.select(
QGetCalculateContentDonationQueryData(
member.nickname,
audioContent.title,
audioContent.price,
getFormattedDate(audioContent.createdAt),
donationFormattedDate,
useCan.id.count(),
useCan.can.add(useCan.rewardCan).sum(),
countrySettlementExpressions.newPolicyCan(useCan.createdAt, useCan.can.add(useCan.rewardCan)),
countrySettlementExpressions.newPolicyWeightedRatioCan(
useCan.createdAt,
useCan.can.add(useCan.rewardCan),
member.countryCode,
useCan.countryCode
)
)
)
.from(useCan)
.innerJoin(useCan.audioContent, audioContent)
.innerJoin(audioContent.member, member)
.where(
useCan.isRefund.isFalse
.and(useCan.canUsage.eq(CanUsage.DONATION))
.and(audioContent.member.id.eq(memberId))
)
.groupBy(donationFormattedDate, audioContent.id)
.orderBy(member.id.asc(), donationFormattedDate.desc())
}
fun getCalculateCommunityPostTotalCount(startDate: LocalDateTime?, endDate: LocalDateTime?, memberId: Long): Int {
val formattedDate = getFormattedDate(useCan.createdAt)
return queryFactory
.select(creatorCommunity.id)
.from(useCan)
.innerJoin(useCan.communityPost, creatorCommunity)
.innerJoin(creatorCommunity.member, member)
.where(
useCan.isRefund.isFalse
.and(useCan.canUsage.eq(CanUsage.PAID_COMMUNITY_POST))
.and(useCan.createdAt.goe(startDate))
.and(useCan.createdAt.loe(endDate))
.and(creatorCommunity.member.id.eq(memberId))
)
.groupBy(formattedDate, creatorCommunity.id)
.fetch()
.size
}
fun getCalculateCommunityPostTotalCount(startDate: LocalDateTime?, endDate: LocalDateTime?, memberId: Long) =
repository.countCommunity(scope(SettlementSource.COMMUNITY_POST, startDate, endDate, memberId))
fun getCalculateCommunityPostList(
startDate: LocalDateTime?,
@@ -401,60 +58,16 @@ class CreatorAdminCalculateQueryRepository(
memberId: Long,
offset: Long,
limit: Long
): List<GetCalculateCommunityPostQueryData> {
return calculateCommunityPostQuery(memberId)
.where(useCan.createdAt.goe(startDate), useCan.createdAt.loe(endDate))
.offset(offset)
.limit(limit)
.fetch()
}
) = repository.readCommunity(scope(SettlementSource.COMMUNITY_POST, startDate, endDate, memberId), offset, limit)
fun getMonthlyCalculateCommunityPostList(
startInclusiveUtc: LocalDateTime,
endExclusiveUtc: LocalDateTime,
memberId: Long
): List<GetCalculateCommunityPostQueryData> {
return calculateCommunityPostQuery(memberId)
.where(useCan.createdAt.goe(startInclusiveUtc), useCan.createdAt.lt(endExclusiveUtc))
.fetch()
}
fun getMonthlyCalculateCommunityPostList(startInclusiveUtc: LocalDateTime, endExclusiveUtc: LocalDateTime, memberId: Long) =
repository.readAllCommunity(scope(SettlementSource.COMMUNITY_POST, startInclusiveUtc, endExclusiveUtc, memberId, true))
private fun calculateCommunityPostQuery(memberId: Long): JPAQuery<GetCalculateCommunityPostQueryData> {
val formattedDate = getFormattedDate(useCan.createdAt)
return queryFactory
.select(
QGetCalculateCommunityPostQueryData(
member.nickname,
Expressions.stringTemplate("substring({0}, 1, 10)", creatorCommunity.content),
formattedDate,
creatorCommunity.price,
useCan.id.count(),
useCan.can.add(useCan.rewardCan).sum(),
creatorSettlementRatio.communitySettlementRatio,
countrySettlementExpressions.newPolicyCan(useCan.createdAt, useCan.can.add(useCan.rewardCan)),
countrySettlementExpressions.newPolicyWeightedRatioCan(
useCan.createdAt,
useCan.can.add(useCan.rewardCan),
member.countryCode,
useCan.countryCode,
creatorSettlementRatio.communitySettlementRatio
)
)
)
.from(useCan)
.innerJoin(useCan.communityPost, creatorCommunity)
.innerJoin(creatorCommunity.member, member)
.leftJoin(creatorSettlementRatio)
.on(
member.id.eq(creatorSettlementRatio.member.id)
.and(creatorSettlementRatio.deletedAt.isNull)
)
.where(
useCan.isRefund.isFalse
.and(useCan.canUsage.eq(CanUsage.PAID_COMMUNITY_POST))
.and(creatorCommunity.member.id.eq(memberId))
)
.groupBy(formattedDate, creatorCommunity.id, creatorSettlementRatio.communitySettlementRatio)
.orderBy(member.id.asc(), formattedDate.desc())
}
private fun scope(
source: SettlementSource,
start: LocalDateTime?,
end: LocalDateTime?,
memberId: Long,
endExclusive: Boolean = false
) = SettlementScope(source, SettlementWindow(start, end, endExclusive), creatorId = memberId)
}
@@ -5,11 +5,12 @@ import kr.co.vividnext.sodalive.admin.calculate.GetCumulativeSalesByContentRespo
import kr.co.vividnext.sodalive.extensions.convertLocalDateTime
import kr.co.vividnext.sodalive.member.Member
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Isolation
import org.springframework.transaction.annotation.Transactional
@Service
@Transactional(readOnly = true, isolation = Isolation.REPEATABLE_READ)
class CreatorAdminCalculateService(private val repository: CreatorAdminCalculateQueryRepository) {
@Transactional(readOnly = true)
fun getCalculateLive(startDateStr: String, endDateStr: String, member: Member): List<GetCalculateLiveResponse> {
val startDate = startDateStr.convertLocalDateTime()
val endDate = endDateStr.convertLocalDateTime(hour = 23, minute = 59, second = 59)
@@ -19,7 +20,6 @@ class CreatorAdminCalculateService(private val repository: CreatorAdminCalculate
.map { it.toGetCalculateLiveResponse() }
}
@Transactional(readOnly = true)
fun getCalculateContentList(
startDateStr: String,
endDateStr: String,
@@ -37,7 +37,6 @@ class CreatorAdminCalculateService(private val repository: CreatorAdminCalculate
return GetCalculateContentListResponse(totalCount, items)
}
@Transactional(readOnly = true)
fun getCumulativeSalesByContent(memberId: Long, offset: Long, limit: Long): GetCumulativeSalesByContentResponse {
val totalCount = repository.getCumulativeSalesByContentTotalCount(memberId)
val items = repository
@@ -47,7 +46,6 @@ class CreatorAdminCalculateService(private val repository: CreatorAdminCalculate
return GetCumulativeSalesByContentResponse(totalCount, items)
}
@Transactional(readOnly = true)
fun getCalculateContentDonationList(
startDateStr: String,
endDateStr: String,
@@ -66,7 +64,6 @@ class CreatorAdminCalculateService(private val repository: CreatorAdminCalculate
return GetCreatorCalculateContentDonationResponse(totalCount, items)
}
@Transactional(readOnly = true)
fun getCalculateCommunityPost(
startDateStr: String,
endDateStr: String,
@@ -1,84 +1,68 @@
package kr.co.vividnext.sodalive.creator.admin.calculate.channelDonation
import com.querydsl.core.types.dsl.BooleanExpression
import com.querydsl.core.types.dsl.DateTimePath
import com.querydsl.core.types.dsl.Expressions
import com.querydsl.core.types.dsl.StringTemplate
import com.querydsl.jpa.impl.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.member.QMember.member
import kr.co.vividnext.sodalive.v2.settlement.adapter.out.persistence.CountrySettlementExpressions
import kr.co.vividnext.sodalive.v2.settlement.adapter.out.persistence.CanonicalSettlementQueryRepository
import kr.co.vividnext.sodalive.v2.settlement.domain.CountrySettlementPolicy
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementDisplayGrain
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementScope
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementSource
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementWindow
import org.springframework.stereotype.Repository
import java.time.LocalDateTime
@Repository
class CreatorAdminChannelDonationCalculateQueryRepository(
private val queryFactory: JPAQueryFactory,
private val countrySettlementExpressions: CountrySettlementExpressions
private val canonicalRepository: CanonicalSettlementQueryRepository,
private val policy: CountrySettlementPolicy
) {
fun getChannelDonationSettlementTotal(
startDate: LocalDateTime,
endDate: LocalDateTime,
memberId: Long
): GetCreatorChannelDonationSettlementTotalQueryData {
return getChannelDonationSettlementTotal(
baseWhereCondition(startDate, memberId).and(useCan.createdAt.loe(endDate))
)
}
): GetCreatorChannelDonationSettlementTotalQueryData = getChannelDonationSettlementTotal(
scope(startDate, endDate, memberId)
)
fun getMonthlyChannelDonationSettlementTotal(
startInclusiveUtc: LocalDateTime,
endExclusiveUtc: LocalDateTime,
memberId: Long
): GetCreatorChannelDonationSettlementTotalQueryData {
return getChannelDonationSettlementTotal(
baseWhereCondition(startInclusiveUtc, memberId).and(useCan.createdAt.lt(endExclusiveUtc))
): GetCreatorChannelDonationSettlementTotalQueryData = getChannelDonationSettlementTotal(
scope(startInclusiveUtc, endExclusiveUtc, memberId, endExclusive = true)
)
private fun getChannelDonationSettlementTotal(scope: SettlementScope): GetCreatorChannelDonationSettlementTotalQueryData {
val legacy = queryFactory.select(
QGetCreatorChannelDonationSettlementTotalQueryData(useCan.id.countDistinct(), useCanCalculate.can.sum())
)
.from(useCanCalculate)
.innerJoin(useCanCalculate.useCan, useCan)
.where(legacyWhere(scope))
.fetchOne() ?: GetCreatorChannelDonationSettlementTotalQueryData(0, 0)
val amount = legacy.amount + canonicalRepository.readTotals(scope)
return GetCreatorChannelDonationSettlementTotalQueryData(
Math.addExact(legacy.count ?: 0L, canonicalRepository.countTransactions(scope)),
Math.toIntExact(amount.totalCan),
amount
)
}
private fun getChannelDonationSettlementTotal(
condition: BooleanExpression
): GetCreatorChannelDonationSettlementTotalQueryData {
return queryFactory
.select(
QGetCreatorChannelDonationSettlementTotalQueryData(
useCan.id.countDistinct(),
useCanCalculate.can.sum(),
countrySettlementExpressions.newPolicyCan(useCan.createdAt, useCanCalculate.can),
countrySettlementExpressions.newPolicyWeightedRatioCan(
useCan.createdAt,
useCanCalculate.can,
member.countryCode,
useCan.countryCode
)
)
)
.from(useCanCalculate)
.innerJoin(useCanCalculate.useCan, useCan)
.leftJoin(member)
.on(member.id.eq(useCanCalculate.recipientCreatorId))
.where(condition)
.fetchOne()
?: GetCreatorChannelDonationSettlementTotalQueryData(
count = 0L,
totalCan = 0
)
}
fun getChannelDonationTotalCount(startDate: LocalDateTime, endDate: LocalDateTime, memberId: Long): Int {
val formattedDate = getFormattedDate(useCan.createdAt)
return queryFactory
.select(formattedDate.countDistinct())
val scope = scope(startDate, endDate, memberId)
val legacy = queryFactory.select(formattedDate().countDistinct())
.from(useCanCalculate)
.innerJoin(useCanCalculate.useCan, useCan)
.where(baseWhereCondition(startDate, memberId), useCan.createdAt.loe(endDate))
.fetchOne()
?.toInt()
?: 0
.where(legacyWhere(scope))
.fetchOne() ?: 0L
return Math.toIntExact(
Math.addExact(legacy, canonicalRepository.countDisplayRows(scope, SettlementDisplayGrain.DETAIL))
)
}
fun getChannelDonation(
@@ -88,47 +72,68 @@ class CreatorAdminChannelDonationCalculateQueryRepository(
offset: Long,
limit: Long
): List<GetCreatorChannelDonationSettlementQueryData> {
val formattedDate = getFormattedDate(useCan.createdAt)
return queryFactory
.select(
QGetCreatorChannelDonationSettlementQueryData(
formattedDate,
useCan.id.countDistinct(),
useCanCalculate.can.sum(),
countrySettlementExpressions.newPolicyCan(useCan.createdAt, useCanCalculate.can),
countrySettlementExpressions.newPolicyWeightedRatioCan(
useCan.createdAt,
useCanCalculate.can,
member.countryCode,
useCan.countryCode
)
require(offset >= 0 && limit > 0)
val scope = scope(startDate, endDate, memberId)
val grain = SettlementDisplayGrain.DETAIL
val newCount = canonicalRepository.countDisplayRows(scope, grain)
val rows = if (offset < newCount) {
canonicalRepository.readDisplayPage(scope, grain, offset, limit).map { row ->
GetCreatorChannelDonationSettlementQueryData(
requireNotNull(row.description.displayDate),
row.transactionCount,
Math.toIntExact(row.amount.totalCan),
row.amount,
row.metadata
)
}
} else {
emptyList()
}
val remaining = limit - rows.size
if (remaining <= 0) return rows
val date = formattedDate()
val legacy = queryFactory.select(
QGetCreatorChannelDonationSettlementQueryData(
date,
useCan.id.countDistinct(),
useCanCalculate.can.sum(),
useCanCalculate.recipientCreatorId
)
)
.from(useCanCalculate)
.innerJoin(useCanCalculate.useCan, useCan)
.leftJoin(member)
.on(member.id.eq(useCanCalculate.recipientCreatorId))
.where(baseWhereCondition(startDate, memberId), useCan.createdAt.loe(endDate))
.groupBy(formattedDate)
.orderBy(formattedDate.desc())
.offset(offset)
.limit(limit)
.where(legacyWhere(scope))
.groupBy(date, useCanCalculate.recipientCreatorId)
.orderBy(date.desc())
.offset((offset - newCount).coerceAtLeast(0))
.limit(remaining)
.fetch()
return rows + legacy
}
private fun baseWhereCondition(startDate: LocalDateTime, memberId: Long) = useCan.canUsage.eq(
CanUsage.CHANNEL_DONATION
)
private fun scope(
startDate: LocalDateTime,
endDate: LocalDateTime,
memberId: Long,
endExclusive: Boolean = false
) = SettlementScope(SettlementSource.CHANNEL_DONATION, SettlementWindow(startDate, endDate, endExclusive), memberId)
private fun legacyWhere(scope: SettlementScope) = useCan.canUsage.eq(CanUsage.CHANNEL_DONATION)
.and(useCan.isRefund.isFalse)
.and(useCanCalculate.status.eq(UseCanCalculateStatus.RECEIVED))
.and(useCanCalculate.recipientCreatorId.eq(memberId))
.and(useCan.createdAt.goe(startDate))
private fun getFormattedDate(dateTimePath: DateTimePath<LocalDateTime>): StringTemplate {
return Expressions.stringTemplate(
"DATE_FORMAT(CONVERT_TZ({0}, 'UTC', 'Asia/Seoul'), '%Y-%m-%d')",
dateTimePath
.and(useCanCalculate.recipientCreatorId.eq(requireNotNull(scope.creatorId)))
.and(useCan.createdAt.goe(requireNotNull(scope.window.startInclusiveUtc)))
.and(
if (scope.window.endExclusive) {
useCan.createdAt.lt(requireNotNull(scope.window.endUtc))
} else {
useCan.createdAt.loe(requireNotNull(scope.window.endUtc))
}
)
}
.and(useCan.createdAt.lt(policy.effectiveAtUtc))
private fun formattedDate() = Expressions.stringTemplate(
"DATE_FORMAT(CONVERT_TZ({0}, 'UTC', 'Asia/Seoul'), '%Y-%m-%d')",
useCan.createdAt
)
}
@@ -2,13 +2,14 @@ package kr.co.vividnext.sodalive.creator.admin.calculate.channelDonation
import kr.co.vividnext.sodalive.extensions.convertLocalDateTime
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Isolation
import org.springframework.transaction.annotation.Transactional
@Service
class CreatorAdminChannelDonationCalculateService(
private val repository: CreatorAdminChannelDonationCalculateQueryRepository
) {
@Transactional(readOnly = true)
@Transactional(readOnly = true, isolation = Isolation.REPEATABLE_READ)
fun getChannelDonation(
startDateStr: String,
endDateStr: String,
@@ -1,6 +1,7 @@
package kr.co.vividnext.sodalive.creator.admin.calculate.channelDonation
import com.fasterxml.jackson.annotation.JsonProperty
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementCountryRelation
data class GetCreatorChannelDonationSettlementItem(
@JsonProperty("date") val date: String,
@@ -11,5 +12,11 @@ data class GetCreatorChannelDonationSettlementItem(
@JsonProperty("fee") val fee: Int,
@JsonProperty("settlementAmount") val settlementAmount: Int,
@JsonProperty("withholdingTax") val withholdingTax: Int,
@JsonProperty("depositAmount") val depositAmount: Int
@JsonProperty("depositAmount") val depositAmount: Int,
@JsonProperty("rowKey") val rowKey: String = "",
@JsonProperty("countryRelation") val countryRelation: SettlementCountryRelation? = null,
@JsonProperty("appliedSettlementRatio") val appliedSettlementRatio: Int? = null,
@JsonProperty("agentId") val agentId: Long? = null,
@JsonProperty("appliedAgentSettlementRatio") val appliedAgentSettlementRatio: Int? = null,
@JsonProperty("rateInfoAvailable") val rateInfoAvailable: Boolean = false
)
@@ -1,31 +1,52 @@
package kr.co.vividnext.sodalive.creator.admin.calculate.channelDonation
import com.querydsl.core.annotations.QueryProjection
import kr.co.vividnext.sodalive.calculate.channelDonation.ChannelDonationSettlementCalculator
import kr.co.vividnext.sodalive.admin.calculate.channelDonation.legacyChannelDonationAmounts
import kr.co.vividnext.sodalive.admin.calculate.channelDonation.legacyChannelDonationMetadata
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementAmounts
import kr.co.vividnext.sodalive.v2.settlement.dto.SettlementRateMetadata
data class GetCreatorChannelDonationSettlementQueryData @QueryProjection constructor(
data class GetCreatorChannelDonationSettlementQueryData(
val date: String,
val count: Long,
val totalCan: Int?,
val newPolicyCan: Int = 0,
val newPolicyWeightedRatioCan: Long = 0
val amount: SettlementAmounts = legacyChannelDonationAmounts((totalCan ?: 0).toLong()),
val metadata: SettlementRateMetadata = legacyChannelDonationMetadata("channel-date", listOf(null, date))
) {
@QueryProjection
constructor(date: String, count: Long, totalCan: Int?) : this(date, count, totalCan, 0, 0)
constructor(date: String, count: Long, totalCan: Int?) : this(
date,
count,
totalCan,
legacyChannelDonationAmounts((totalCan ?: 0).toLong()),
legacyChannelDonationMetadata("channel-date", listOf(null, date))
)
@QueryProjection
constructor(date: String, count: Long, totalCan: Int?, creatorId: Long) : this(
date,
count,
totalCan,
metadata = legacyChannelDonationMetadata("channel-date", listOf(creatorId.toString(), date))
)
fun toResponseItem(creatorNickname: String): GetCreatorChannelDonationSettlementItem {
val settlement = ChannelDonationSettlementCalculator.calculate(totalCan ?: 0, newPolicyCan, newPolicyWeightedRatioCan)
return GetCreatorChannelDonationSettlementItem(
date = date,
creator = creatorNickname,
count = count.toInt(),
totalCan = totalCan ?: 0,
krw = settlement.krw,
fee = settlement.fee,
settlementAmount = settlement.settlementAmount,
withholdingTax = settlement.withholdingTax,
depositAmount = settlement.depositAmount
count = Math.toIntExact(count),
totalCan = Math.toIntExact(amount.totalCan),
krw = Math.toIntExact(amount.grossAmount),
fee = Math.toIntExact(amount.paymentFee),
settlementAmount = Math.toIntExact(amount.settlementAmount),
withholdingTax = Math.toIntExact(amount.withholdingTax),
depositAmount = Math.toIntExact(amount.depositAmount),
rowKey = metadata.rowKey,
countryRelation = metadata.countryRelation,
appliedSettlementRatio = metadata.appliedSettlementRatio,
agentId = metadata.agentId,
appliedAgentSettlementRatio = metadata.appliedAgentSettlementRatio,
rateInfoAvailable = metadata.rateInfoAvailable
)
}
}
@@ -1,29 +1,30 @@
package kr.co.vividnext.sodalive.creator.admin.calculate.channelDonation
import com.querydsl.core.annotations.QueryProjection
import kr.co.vividnext.sodalive.calculate.channelDonation.ChannelDonationSettlementCalculator
import kr.co.vividnext.sodalive.admin.calculate.channelDonation.legacyChannelDonationAmounts
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementAmounts
data class GetCreatorChannelDonationSettlementTotalQueryData @QueryProjection constructor(
data class GetCreatorChannelDonationSettlementTotalQueryData(
val count: Long?,
val totalCan: Int?,
val newPolicyCan: Int = 0,
val newPolicyWeightedRatioCan: Long = 0
val amount: SettlementAmounts = legacyChannelDonationAmounts((totalCan ?: 0).toLong())
) {
@QueryProjection
constructor(count: Long?, totalCan: Int?) : this(count, totalCan, 0, 0)
constructor(count: Long?, totalCan: Int?) : this(
count,
totalCan,
legacyChannelDonationAmounts((totalCan ?: 0).toLong())
)
fun toResponseTotal(): GetCreatorChannelDonationSettlementTotal {
val totalCan = totalCan ?: 0
val settlement = ChannelDonationSettlementCalculator.calculate(totalCan, newPolicyCan, newPolicyWeightedRatioCan)
return GetCreatorChannelDonationSettlementTotal(
count = (count ?: 0L).toInt(),
totalCan = totalCan,
krw = settlement.krw,
fee = settlement.fee,
settlementAmount = settlement.settlementAmount,
withholdingTax = settlement.withholdingTax,
depositAmount = settlement.depositAmount
count = Math.toIntExact(count ?: 0L),
totalCan = Math.toIntExact(amount.totalCan),
krw = Math.toIntExact(amount.grossAmount),
fee = Math.toIntExact(amount.paymentFee),
settlementAmount = Math.toIntExact(amount.settlementAmount),
withholdingTax = Math.toIntExact(amount.withholdingTax),
depositAmount = Math.toIntExact(amount.depositAmount)
)
}
}
@@ -15,8 +15,20 @@ 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.adapter.out.persistence.CanonicalSettlementQueryRepository
import kr.co.vividnext.sodalive.v2.settlement.domain.CanonicalSettlementRow
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.SettlementCanonicalKey
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementCountryRelation
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementDisplayGrain
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementProvenance
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementRowKey
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementScope
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementSource
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementWindow
import kr.co.vividnext.sodalive.v2.settlement.dto.SettlementDisplayRow
import kr.co.vividnext.sodalive.v2.settlement.dto.SettlementRateMetadata
import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Repository
import java.time.LocalDateTime
@@ -29,7 +41,7 @@ class AgentCalculateQueryRepository(
@Value("\${cloud.aws.cloud-front.host}")
private val cloudFrontHost: String,
private val countrySettlementExpressions: CountrySettlementExpressions,
private val canonicalRepository: CanonicalSettlementQueryRepository,
private val countrySettlementPolicy: CountrySettlementPolicy
) {
fun getAssignedCreatorTotalCount(agentId: Long, currentTime: LocalDateTime): Int {
@@ -72,7 +84,7 @@ class AgentCalculateQueryRepository(
}
fun getCalculateLiveByCreatorTotalCount(startDate: LocalDateTime, endDate: LocalDateTime, agentId: Long): Int {
return queryFactory
val legacyCount = queryFactory
.select(member.id.countDistinct())
.from(useCan)
.innerJoin(useCan.room, liveRoom)
@@ -86,10 +98,13 @@ class AgentCalculateQueryRepository(
useCan.isRefund.isFalse
.and(useCan.createdAt.goe(startDate))
.and(useCan.createdAt.loe(endDate))
.and(useCan.createdAt.lt(countrySettlementPolicy.effectiveAtUtc))
)
.fetchOne()
?.toInt()
?: 0
?: 0L
return Math.toIntExact(
legacyCount + countCanonicalDisplayRows(settlementScope(startDate, endDate, agentId, SettlementSource.LIVE))
)
}
fun getCalculateLiveByCreator(
@@ -97,7 +112,8 @@ class AgentCalculateQueryRepository(
endDate: LocalDateTime,
agentId: Long
): List<GetAgentCreatorSettlementSummaryQueryData> {
return getCalculateLiveByCreatorRows(startDate, endDate, agentId, creatorIds = null)
return getCanonicalSummaryRows(settlementScope(startDate, endDate, agentId, SettlementSource.LIVE)) +
getCalculateLiveByCreatorRows(startDate, endDate, agentId, creatorIds = null)
}
fun getCalculateLiveByCreatorTotal(
@@ -106,6 +122,7 @@ class AgentCalculateQueryRepository(
agentId: Long
): GetAgentSettlementByCreatorTotal {
return getGenericSettlementTotal(
source = SettlementSource.LIVE,
subQuery = buildLiveSettlementTotalSubQuery(),
startDate = startDate,
endDate = endDate,
@@ -119,6 +136,20 @@ class AgentCalculateQueryRepository(
agentId: Long,
offset: Long,
limit: Long
): List<GetAgentCreatorSettlementSummaryQueryData> {
val scope = settlementScope(startDate, endDate, agentId, SettlementSource.LIVE)
return readSettlementPage(scope, offset, limit, { it.toSummaryQueryData() }) { legacyOffset, legacyLimit ->
getLegacyCalculateLiveByCreator(startDate, endDate, agentId, legacyOffset, legacyLimit)
.toLegacyDisplayRows(scope)
}
}
private fun getLegacyCalculateLiveByCreator(
startDate: LocalDateTime,
endDate: LocalDateTime,
agentId: Long,
offset: Long,
limit: Long
): List<GetAgentCreatorSettlementSummaryQueryData> {
val creatorIds = queryFactory
.select(member.id)
@@ -134,6 +165,7 @@ class AgentCalculateQueryRepository(
useCan.isRefund.isFalse
.and(useCan.createdAt.goe(startDate))
.and(useCan.createdAt.loe(endDate))
.and(useCan.createdAt.lt(countrySettlementPolicy.effectiveAtUtc))
)
.groupBy(member.id)
.orderBy(member.id.desc())
@@ -149,7 +181,7 @@ class AgentCalculateQueryRepository(
}
fun getCalculateContentByCreatorTotalCount(startDate: LocalDateTime, endDate: LocalDateTime, agentId: Long): Int {
return queryFactory
val legacyCount = queryFactory
.select(member.id.countDistinct())
.from(order)
.innerJoin(order.audioContent, audioContent)
@@ -162,11 +194,14 @@ class AgentCalculateQueryRepository(
.where(
order.createdAt.goe(startDate)
.and(order.createdAt.loe(endDate))
.and(order.createdAt.lt(countrySettlementPolicy.effectiveAtUtc))
.and(order.isActive.isTrue)
)
.fetchOne()
?.toInt()
?: 0
?: 0L
return Math.toIntExact(
legacyCount + countCanonicalDisplayRows(settlementScope(startDate, endDate, agentId, SettlementSource.CONTENT_SALES))
)
}
fun getCalculateContentByCreator(
@@ -174,7 +209,8 @@ class AgentCalculateQueryRepository(
endDate: LocalDateTime,
agentId: Long
): List<GetAgentCreatorSettlementSummaryQueryData> {
return getCalculateContentByCreatorRows(startDate, endDate, agentId, creatorIds = null)
return getCanonicalSummaryRows(settlementScope(startDate, endDate, agentId, SettlementSource.CONTENT_SALES)) +
getCalculateContentByCreatorRows(startDate, endDate, agentId, creatorIds = null)
}
fun getCalculateContentByCreatorTotal(
@@ -183,6 +219,7 @@ class AgentCalculateQueryRepository(
agentId: Long
): GetAgentSettlementByCreatorTotal {
return getGenericSettlementTotal(
source = SettlementSource.CONTENT_SALES,
subQuery = buildContentSettlementTotalSubQuery(),
startDate = startDate,
endDate = endDate,
@@ -196,6 +233,20 @@ class AgentCalculateQueryRepository(
agentId: Long,
offset: Long,
limit: Long
): List<GetAgentCreatorSettlementSummaryQueryData> {
val scope = settlementScope(startDate, endDate, agentId, SettlementSource.CONTENT_SALES)
return readSettlementPage(scope, offset, limit, { it.toSummaryQueryData() }) { legacyOffset, legacyLimit ->
getLegacyCalculateContentByCreator(startDate, endDate, agentId, legacyOffset, legacyLimit)
.toLegacyDisplayRows(scope)
}
}
private fun getLegacyCalculateContentByCreator(
startDate: LocalDateTime,
endDate: LocalDateTime,
agentId: Long,
offset: Long,
limit: Long
): List<GetAgentCreatorSettlementSummaryQueryData> {
val creatorIds = queryFactory
.select(member.id)
@@ -210,6 +261,7 @@ class AgentCalculateQueryRepository(
.where(
order.createdAt.goe(startDate)
.and(order.createdAt.loe(endDate))
.and(order.createdAt.lt(countrySettlementPolicy.effectiveAtUtc))
.and(order.isActive.isTrue)
)
.groupBy(member.id)
@@ -226,7 +278,7 @@ class AgentCalculateQueryRepository(
}
fun getCalculateCommunityByCreatorTotalCount(startDate: LocalDateTime, endDate: LocalDateTime, agentId: Long): Int {
return queryFactory
val legacyCount = queryFactory
.select(member.id.countDistinct())
.from(useCan)
.innerJoin(useCan.communityPost, creatorCommunity)
@@ -241,10 +293,13 @@ class AgentCalculateQueryRepository(
.and(useCan.canUsage.eq(CanUsage.PAID_COMMUNITY_POST))
.and(useCan.createdAt.goe(startDate))
.and(useCan.createdAt.loe(endDate))
.and(useCan.createdAt.lt(countrySettlementPolicy.effectiveAtUtc))
)
.fetchOne()
?.toInt()
?: 0
?: 0L
return Math.toIntExact(
legacyCount + countCanonicalDisplayRows(settlementScope(startDate, endDate, agentId, SettlementSource.COMMUNITY_POST))
)
}
fun getCalculateCommunityByCreator(
@@ -252,7 +307,8 @@ class AgentCalculateQueryRepository(
endDate: LocalDateTime,
agentId: Long
): List<GetAgentCreatorSettlementSummaryQueryData> {
return getCalculateCommunityByCreatorRows(startDate, endDate, agentId, creatorIds = null)
return getCanonicalSummaryRows(settlementScope(startDate, endDate, agentId, SettlementSource.COMMUNITY_POST)) +
getCalculateCommunityByCreatorRows(startDate, endDate, agentId, creatorIds = null)
}
fun getCalculateCommunityByCreatorTotal(
@@ -261,6 +317,7 @@ class AgentCalculateQueryRepository(
agentId: Long
): GetAgentSettlementByCreatorTotal {
return getGenericSettlementTotal(
source = SettlementSource.COMMUNITY_POST,
subQuery = buildCommunitySettlementTotalSubQuery(),
startDate = startDate,
endDate = endDate,
@@ -274,6 +331,20 @@ class AgentCalculateQueryRepository(
agentId: Long,
offset: Long,
limit: Long
): List<GetAgentCreatorSettlementSummaryQueryData> {
val scope = settlementScope(startDate, endDate, agentId, SettlementSource.COMMUNITY_POST)
return readSettlementPage(scope, offset, limit, { it.toSummaryQueryData() }) { legacyOffset, legacyLimit ->
getLegacyCalculateCommunityByCreator(startDate, endDate, agentId, legacyOffset, legacyLimit)
.toLegacyDisplayRows(scope)
}
}
private fun getLegacyCalculateCommunityByCreator(
startDate: LocalDateTime,
endDate: LocalDateTime,
agentId: Long,
offset: Long,
limit: Long
): List<GetAgentCreatorSettlementSummaryQueryData> {
val creatorIds = queryFactory
.select(member.id)
@@ -290,6 +361,7 @@ class AgentCalculateQueryRepository(
.and(useCan.canUsage.eq(CanUsage.PAID_COMMUNITY_POST))
.and(useCan.createdAt.goe(startDate))
.and(useCan.createdAt.loe(endDate))
.and(useCan.createdAt.lt(countrySettlementPolicy.effectiveAtUtc))
)
.groupBy(member.id)
.orderBy(member.id.desc())
@@ -309,7 +381,7 @@ class AgentCalculateQueryRepository(
endDate: LocalDateTime,
agentId: Long
): Int {
return queryFactory
val legacyCount = queryFactory
.select(member.id.countDistinct())
.from(useCan)
.innerJoin(useCan.audioContent, audioContent)
@@ -324,10 +396,15 @@ class AgentCalculateQueryRepository(
.and(useCan.canUsage.eq(CanUsage.DONATION))
.and(useCan.createdAt.goe(startDate))
.and(useCan.createdAt.loe(endDate))
.and(useCan.createdAt.lt(countrySettlementPolicy.effectiveAtUtc))
)
.fetchOne()
?.toInt()
?: 0
?: 0L
return Math.toIntExact(
legacyCount + countCanonicalDisplayRows(
settlementScope(startDate, endDate, agentId, SettlementSource.CONTENT_DONATION)
)
)
}
fun getCalculateContentDonationByCreator(
@@ -335,7 +412,8 @@ class AgentCalculateQueryRepository(
endDate: LocalDateTime,
agentId: Long
): List<GetAgentCreatorSettlementSummaryQueryData> {
return getCalculateContentDonationByCreatorRows(startDate, endDate, agentId, creatorIds = null)
return getCanonicalSummaryRows(settlementScope(startDate, endDate, agentId, SettlementSource.CONTENT_DONATION)) +
getCalculateContentDonationByCreatorRows(startDate, endDate, agentId, creatorIds = null)
}
fun getCalculateContentDonationByCreatorTotal(
@@ -344,6 +422,7 @@ class AgentCalculateQueryRepository(
agentId: Long
): GetAgentSettlementByCreatorTotal {
return getGenericSettlementTotal(
source = SettlementSource.CONTENT_DONATION,
subQuery = buildContentDonationSettlementTotalSubQuery(),
startDate = startDate,
endDate = endDate,
@@ -357,6 +436,20 @@ class AgentCalculateQueryRepository(
agentId: Long,
offset: Long,
limit: Long
): List<GetAgentCreatorSettlementSummaryQueryData> {
val scope = settlementScope(startDate, endDate, agentId, SettlementSource.CONTENT_DONATION)
return readSettlementPage(scope, offset, limit, { it.toSummaryQueryData() }) { legacyOffset, legacyLimit ->
getLegacyCalculateContentDonationByCreator(startDate, endDate, agentId, legacyOffset, legacyLimit)
.toLegacyDisplayRows(scope)
}
}
private fun getLegacyCalculateContentDonationByCreator(
startDate: LocalDateTime,
endDate: LocalDateTime,
agentId: Long,
offset: Long,
limit: Long
): List<GetAgentCreatorSettlementSummaryQueryData> {
val creatorIds = queryFactory
.select(member.id)
@@ -373,6 +466,7 @@ class AgentCalculateQueryRepository(
.and(useCan.canUsage.eq(CanUsage.DONATION))
.and(useCan.createdAt.goe(startDate))
.and(useCan.createdAt.loe(endDate))
.and(useCan.createdAt.lt(countrySettlementPolicy.effectiveAtUtc))
)
.groupBy(member.id)
.orderBy(member.id.desc())
@@ -388,7 +482,7 @@ class AgentCalculateQueryRepository(
}
fun getChannelDonationByCreatorTotalCount(startDate: LocalDateTime, endDate: LocalDateTime, agentId: Long): Int {
return queryFactory
val legacyCount = queryFactory
.select(member.id.countDistinct())
.from(useCanCalculate)
.innerJoin(useCanCalculate.useCan, useCan)
@@ -405,10 +499,15 @@ class AgentCalculateQueryRepository(
.and(useCanCalculate.status.eq(UseCanCalculateStatus.RECEIVED))
.and(useCan.createdAt.goe(startDate))
.and(useCan.createdAt.loe(endDate))
.and(useCan.createdAt.lt(countrySettlementPolicy.effectiveAtUtc))
)
.fetchOne()
?.toInt()
?: 0
?: 0L
return Math.toIntExact(
legacyCount + countCanonicalDisplayRows(
settlementScope(startDate, endDate, agentId, SettlementSource.CHANNEL_DONATION)
)
)
}
fun getChannelDonationByCreator(
@@ -416,7 +515,8 @@ class AgentCalculateQueryRepository(
endDate: LocalDateTime,
agentId: Long
): List<GetAgentChannelDonationSettlementByCreatorQueryData> {
return getChannelDonationByCreatorRows(startDate, endDate, agentId, creatorIds = null)
return getCanonicalSummaryRows(settlementScope(startDate, endDate, agentId, SettlementSource.CHANNEL_DONATION))
.map { it.toChannelQueryData() } + getChannelDonationByCreatorRows(startDate, endDate, agentId, creatorIds = null)
}
fun getChannelDonationByCreatorTotal(
@@ -439,21 +539,13 @@ class AgentCalculateQueryRepository(
FROM (
SELECT
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
ROUND((grouped.total_can * 100 - ROUND(grouped.total_can * 100 * 0.066, 0)) * 0.85, 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
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
@@ -469,6 +561,7 @@ class AgentCalculateQueryRepository(
AND ucc.status = 'RECEIVED'
AND uc.created_at >= :startDate
AND uc.created_at <= :endDate
AND uc.created_at < :countryPolicyEffectiveAt
GROUP BY acr.id, asr.id, COALESCE(asr.settlement_ratio, 7)
) grouped
) calculated
@@ -479,19 +572,19 @@ class AgentCalculateQueryRepository(
query.setParameter("endDate", endDate)
query.setParameter("agentId", agentId)
query.setParameter("countryPolicyEffectiveAt", countrySettlementPolicy.effectiveAtUtc)
query.setParameter("koreanDefaultRateEndExclusive", countrySettlementPolicy.koreanDefaultRateEndExclusiveUtc)
val result = query.singleResult as Array<*>
val total = settlementTotal(settlementScope(startDate, endDate, agentId, SettlementSource.CHANNEL_DONATION), result)
return GetAgentChannelDonationSettlementTotal(
count = result[0].toIntValue(),
totalCan = result[1].toIntValue(),
krw = result[2].toIntValue(),
fee = result[3].toIntValue(),
settlementAmount = result[4].toIntValue(),
withholdingTax = result[5].toIntValue(),
depositAmount = result[6].toIntValue(),
agentSettlementAmount = result[7].toIntValue()
total.count,
total.totalCan,
total.krw,
total.fee,
total.settlementAmount,
total.tax,
total.depositAmount,
total.agentSettlementAmount
)
}
@@ -501,6 +594,41 @@ class AgentCalculateQueryRepository(
agentId: Long,
offset: Long,
limit: Long
): List<GetAgentChannelDonationSettlementByCreatorQueryData> {
val scope = settlementScope(startDate, endDate, agentId, SettlementSource.CHANNEL_DONATION)
return readSettlementPage(
scope,
offset,
limit,
{ it.toSummaryQueryData().toChannelQueryData() }
) { legacyOffset, legacyLimit ->
getLegacyChannelDonationByCreator(startDate, endDate, agentId, legacyOffset, legacyLimit)
.map { row ->
val item = row.toResponseItem()
GetAgentCreatorSettlementSummaryQueryData(
row.creatorId, row.creatorNickname, row.assignmentId, row.agentSettlementRatioId,
row.count, row.totalCan, 85, row.agentSettlementRatio,
SettlementAmounts(
item.totalCan.toLong(),
item.krw.toLong(),
item.fee.toLong(),
item.settlementAmount.toLong(),
item.withholdingTax.toLong(),
item.depositAmount.toLong(),
item.agentSettlementAmount.toLong()
),
legacyMetadata(scope, row.creatorId, 85, row.agentSettlementRatio ?: 7)
)
}.toLegacyDisplayRows(scope).map { it.toChannelQueryData() }
}
}
private fun getLegacyChannelDonationByCreator(
startDate: LocalDateTime,
endDate: LocalDateTime,
agentId: Long,
offset: Long,
limit: Long
): List<GetAgentChannelDonationSettlementByCreatorQueryData> {
val creatorIds = queryFactory
.select(member.id)
@@ -519,6 +647,7 @@ class AgentCalculateQueryRepository(
.and(useCanCalculate.status.eq(UseCanCalculateStatus.RECEIVED))
.and(useCan.createdAt.goe(startDate))
.and(useCan.createdAt.loe(endDate))
.and(useCan.createdAt.lt(countrySettlementPolicy.effectiveAtUtc))
)
.groupBy(member.id)
.orderBy(member.id.desc())
@@ -549,15 +678,7 @@ class AgentCalculateQueryRepository(
useCan.id.count(),
useCan.can.add(useCan.rewardCan).sum(),
creatorSettlementRatio.liveSettlementRatio,
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
)
agentSettlementRatio.settlementRatio
)
)
.from(useCan)
@@ -579,6 +700,7 @@ class AgentCalculateQueryRepository(
useCan.isRefund.isFalse
.and(useCan.createdAt.goe(startDate))
.and(useCan.createdAt.loe(endDate))
.and(useCan.createdAt.lt(countrySettlementPolicy.effectiveAtUtc))
.and(if (!creatorIds.isNullOrEmpty()) member.id.`in`(creatorIds) else null)
)
.groupBy(
@@ -611,15 +733,7 @@ class AgentCalculateQueryRepository(
order.id.count(),
order.can.sum(),
contentSettlementRatio,
agentSettlementRatio.settlementRatio,
countrySettlementExpressions.newPolicyCan(order.createdAt, order.can),
countrySettlementExpressions.newPolicyWeightedRatioCan(
order.createdAt,
order.can,
member.countryCode,
useCan.countryCode,
contentSettlementRatio
)
agentSettlementRatio.settlementRatio
)
)
.from(order)
@@ -643,6 +757,7 @@ class AgentCalculateQueryRepository(
order.createdAt.goe(startDate)
.and(order.createdAt.loe(endDate))
.and(order.isActive.isTrue)
.and(order.createdAt.lt(countrySettlementPolicy.effectiveAtUtc))
.and(if (creatorIds != null && creatorIds.isNotEmpty()) member.id.`in`(creatorIds) else null)
)
.groupBy(
@@ -673,15 +788,7 @@ class AgentCalculateQueryRepository(
useCan.id.count(),
useCan.can.add(useCan.rewardCan).sum(),
creatorSettlementRatio.communitySettlementRatio,
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
)
agentSettlementRatio.settlementRatio
)
)
.from(useCan)
@@ -704,6 +811,7 @@ class AgentCalculateQueryRepository(
.and(useCan.canUsage.eq(CanUsage.PAID_COMMUNITY_POST))
.and(useCan.createdAt.goe(startDate))
.and(useCan.createdAt.loe(endDate))
.and(useCan.createdAt.lt(countrySettlementPolicy.effectiveAtUtc))
.and(if (creatorIds != null && creatorIds.isNotEmpty()) member.id.`in`(creatorIds) else null)
)
.groupBy(
@@ -734,14 +842,7 @@ class AgentCalculateQueryRepository(
useCan.id.count(),
useCan.can.add(useCan.rewardCan).sum(),
Expressions.numberTemplate(Int::class.java, "70"),
agentSettlementRatio.settlementRatio,
countrySettlementExpressions.newPolicyCan(useCan.createdAt, useCan.can.add(useCan.rewardCan)),
countrySettlementExpressions.newPolicyWeightedRatioCan(
useCan.createdAt,
useCan.can.add(useCan.rewardCan),
member.countryCode,
useCan.countryCode
)
agentSettlementRatio.settlementRatio
)
)
.from(useCan)
@@ -759,6 +860,7 @@ class AgentCalculateQueryRepository(
.and(useCan.canUsage.eq(CanUsage.DONATION))
.and(useCan.createdAt.goe(startDate))
.and(useCan.createdAt.loe(endDate))
.and(useCan.createdAt.lt(countrySettlementPolicy.effectiveAtUtc))
.and(if (creatorIds != null && creatorIds.isNotEmpty()) member.id.`in`(creatorIds) else null)
)
.groupBy(
@@ -787,14 +889,7 @@ class AgentCalculateQueryRepository(
agentSettlementRatio.id,
useCan.id.countDistinct(),
useCanCalculate.can.sum(),
agentSettlementRatio.settlementRatio,
countrySettlementExpressions.newPolicyCan(useCan.createdAt, useCanCalculate.can),
countrySettlementExpressions.newPolicyWeightedRatioCan(
useCan.createdAt,
useCanCalculate.can,
member.countryCode,
useCan.countryCode
)
agentSettlementRatio.settlementRatio
)
)
.from(useCanCalculate)
@@ -814,6 +909,7 @@ class AgentCalculateQueryRepository(
.and(useCanCalculate.status.eq(UseCanCalculateStatus.RECEIVED))
.and(useCan.createdAt.goe(startDate))
.and(useCan.createdAt.loe(endDate))
.and(useCan.createdAt.lt(countrySettlementPolicy.effectiveAtUtc))
.and(if (creatorIds != null && creatorIds.isNotEmpty()) member.id.`in`(creatorIds) else null)
)
.groupBy(
@@ -828,6 +924,7 @@ class AgentCalculateQueryRepository(
}
private fun getGenericSettlementTotal(
source: SettlementSource,
subQuery: String,
startDate: LocalDateTime,
endDate: LocalDateTime,
@@ -847,10 +944,8 @@ class AgentCalculateQueryRepository(
* (calculated.agent_settlement_ratio / 100.0), 0)), 0) AS agentSettlementAmount
FROM (
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
(grouped.total_can * 100 - grouped.total_can * 100 * 0.066)
* (grouped.settlement_ratio / 100.0) AS settlement_amount
FROM (
$subQuery
) grouped
@@ -862,20 +957,10 @@ class AgentCalculateQueryRepository(
query.setParameter("endDate", endDate)
query.setParameter("agentId", agentId)
query.setParameter("countryPolicyEffectiveAt", countrySettlementPolicy.effectiveAtUtc)
query.setParameter("koreanDefaultRateEndExclusive", countrySettlementPolicy.koreanDefaultRateEndExclusiveUtc)
val result = query.singleResult as Array<*>
return GetAgentSettlementByCreatorTotal(
count = result[0].toIntValue(),
totalCan = result[1].toIntValue(),
krw = result[2].toIntValue(),
fee = result[3].toIntValue(),
settlementAmount = result[4].toIntValue(),
tax = result[5].toIntValue(),
depositAmount = result[6].toIntValue(),
agentSettlementAmount = result[7].toIntValue()
)
return settlementTotal(settlementScope(startDate, endDate, agentId, source), result)
}
private fun buildLiveSettlementTotalSubQuery() = """
@@ -883,10 +968,7 @@ 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,
${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
COALESCE(asr.settlement_ratio, 7) AS agent_settlement_ratio
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
@@ -902,6 +984,7 @@ class AgentCalculateQueryRepository(
WHERE uc.is_refund = FALSE
AND uc.created_at >= :startDate
AND uc.created_at <= :endDate
AND uc.created_at < :countryPolicyEffectiveAt
GROUP BY acr.id, asr.id, COALESCE(csr.live_settlement_ratio, 70), COALESCE(asr.settlement_ratio, 7)
""".trimIndent()
@@ -910,13 +993,7 @@ 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,
${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
COALESCE(asr.settlement_ratio, 7) AS agent_settlement_ratio
FROM orders o
INNER JOIN content c ON o.content_id = c.id
INNER JOIN member m ON c.member_id = m.id
@@ -932,6 +1009,7 @@ class AgentCalculateQueryRepository(
AND (asr.effective_to IS NULL OR asr.effective_to > o.created_at)
WHERE o.created_at >= :startDate
AND o.created_at <= :endDate
AND o.created_at < :countryPolicyEffectiveAt
AND o.is_active = TRUE
GROUP BY
acr.id,
@@ -946,10 +1024,7 @@ 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,
${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
COALESCE(asr.settlement_ratio, 7) AS agent_settlement_ratio
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
@@ -966,6 +1041,7 @@ class AgentCalculateQueryRepository(
AND uc.can_usage = 'PAID_COMMUNITY_POST'
AND uc.created_at >= :startDate
AND uc.created_at <= :endDate
AND uc.created_at < :countryPolicyEffectiveAt
GROUP BY acr.id, asr.id, COALESCE(csr.community_settlement_ratio, 70), COALESCE(asr.settlement_ratio, 7)
""".trimIndent()
@@ -974,9 +1050,7 @@ 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,
${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
COALESCE(asr.settlement_ratio, 7) AS agent_settlement_ratio
FROM use_can uc
INNER JOIN content c ON uc.content_id = c.id
INNER JOIN member m ON c.member_id = m.id
@@ -991,38 +1065,193 @@ class AgentCalculateQueryRepository(
AND uc.can_usage = 'DONATION'
AND uc.created_at >= :startDate
AND uc.created_at <= :endDate
AND uc.created_at < :countryPolicyEffectiveAt
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)"
fun readCanonicalSettlementPage(
startDate: LocalDateTime,
endDate: LocalDateTime,
agentId: Long,
source: SettlementSource,
offset: Long,
limit: Long
): List<CanonicalSettlementRow> = canonicalRepository.readCanonicalPage(
settlementScope(startDate, endDate, agentId, source),
offset,
limit
)
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()
fun getCanonicalProvenance(
startDate: LocalDateTime,
endDate: LocalDateTime,
agentId: Long,
source: SettlementSource,
keys: List<SettlementCanonicalKey>
): Map<SettlementCanonicalKey, List<SettlementProvenance>> = canonicalRepository.readProvenance(
settlementScope(startDate, endDate, agentId, source),
keys
)
private fun settlementScope(
startDate: LocalDateTime,
endDate: LocalDateTime,
agentId: Long,
source: SettlementSource
) = SettlementScope(source, SettlementWindow(startDate, endDate, endExclusive = false), agentId = agentId)
private fun <T> readSettlementPage(
scope: SettlementScope,
offset: Long,
limit: Long,
mapper: (SettlementDisplayRow) -> T,
legacyLoader: (Long, Long) -> List<T>
): List<T> {
require(offset >= 0 && limit > 0)
val canonicalCount = countCanonicalDisplayRows(scope)
val rows = if (offset < canonicalCount) {
canonicalRepository.readDisplayPage(scope, SettlementDisplayGrain.CREATOR, offset, limit).map(mapper)
} else {
emptyList()
}
val remaining = limit - rows.size
return if (remaining > 0) rows + legacyLoader((offset - canonicalCount).coerceAtLeast(0), remaining) else rows
}
private fun Any?.toIntValue(): Int {
return when (this) {
null -> 0
is Number -> toInt()
else -> this.toString().toInt()
private fun SettlementDisplayRow.toSummaryQueryData() = GetAgentCreatorSettlementSummaryQueryData(
creatorId = creatorId,
creatorNickname = description.creatorNickname,
count = transactionCount,
totalCan = Math.toIntExact(amount.totalCan),
settlementRatio = metadata.appliedSettlementRatio,
agentSettlementRatio = metadata.appliedAgentSettlementRatio,
amount = amount,
metadata = metadata
)
private fun getCanonicalSummaryRows(scope: SettlementScope): List<GetAgentCreatorSettlementSummaryQueryData> {
if (requireNotNull(scope.window.endUtc).isBefore(countrySettlementPolicy.effectiveAtUtc)) return emptyList()
val summaries = linkedMapOf<String, GetAgentCreatorSettlementSummaryQueryData>()
val provenance = mutableMapOf<String, MutableSet<SettlementProvenance>>()
var offset = 0L
do {
val page = canonicalRepository.readCanonicalPage(scope, offset, 256)
if (page.isEmpty()) break
val references = canonicalRepository.readProvenance(scope, page.map { it.key })
val nicknames = queryFactory.select(member.id, member.nickname).from(member)
.where(member.id.`in`(page.map { it.key.creatorId }.distinct())).fetch()
.associate { requireNotNull(it.get(member.id)) to requireNotNull(it.get(member.nickname)) }
page.forEach { row ->
val economics = row.key.economics
val key = SettlementRowKey.creator(scope.source, row.key.creatorId, economics)
provenance.getOrPut(key) { linkedSetOf() }.addAll(references.getValue(row.key))
val previous = summaries[key]
val amount = (previous?.amount ?: SettlementAmounts.ZERO) + row.amount
summaries[key] = GetAgentCreatorSettlementSummaryQueryData(
creatorId = row.key.creatorId,
creatorNickname = nicknames.getValue(row.key.creatorId),
count = Math.addExact(previous?.count ?: 0L, row.transactionCount),
totalCan = Math.toIntExact(amount.totalCan),
settlementRatio = economics.appliedSettlementRatio,
agentSettlementRatio = economics.appliedAgentSettlementRatio,
amount = amount,
metadata = SettlementRateMetadata(
key,
economics.countryRelation,
economics.appliedSettlementRatio,
economics.agentId,
economics.appliedAgentSettlementRatio,
true
)
)
}
offset += page.size
} while (page.size == 256)
return summaries.map { (key, row) ->
val references = provenance.getValue(key)
row.copy(
assignmentId = references.map { it.assignmentId }.distinct().singleOrNull(),
agentSettlementRatioId = references.map { it.agentSettlementRatioId }.distinct().singleOrNull(),
agentSettlementRatio = row.agentSettlementRatio.takeIf { references.all { it.agentSettlementRatioId != null } }
)
}
}
private fun List<GetAgentCreatorSettlementSummaryQueryData>.toLegacyDisplayRows(
scope: SettlementScope
): List<GetAgentCreatorSettlementSummaryQueryData> = groupBy { it.creatorId }.map { (_, rows) ->
val total = rows.fold(SettlementAmounts.ZERO) { sum, row ->
val item = row.toResponseItem()
sum + SettlementAmounts(
item.totalCan.toLong(),
item.krw.toLong(),
item.fee.toLong(),
item.settlementAmount.toLong(),
item.tax.toLong(),
item.depositAmount.toLong(),
item.agentSettlementAmount.toLong()
)
}
val creatorRatio = rows.map { it.settlementRatio ?: 70 }.distinct().singleOrNull()
val agentRatio = rows.map { it.agentSettlementRatio ?: 7 }.distinct().singleOrNull()
rows.first().copy(
count = rows.fold(0L) { count, row -> Math.addExact(count, row.count) },
totalCan = Math.toIntExact(total.totalCan),
settlementRatio = creatorRatio,
agentSettlementRatio = agentRatio,
amount = total,
metadata = legacyMetadata(scope, rows.first().creatorId, creatorRatio, agentRatio)
)
}
private fun legacyMetadata(scope: SettlementScope, creatorId: Long, creatorRatio: Int?, agentRatio: Int?) =
SettlementRateMetadata(
SettlementRowKey.legacy("agent-${scope.source.name}", listOf(creatorId.toString(), scope.agentId.toString())),
SettlementCountryRelation.LEGACY,
creatorRatio,
scope.agentId,
agentRatio,
false
)
private fun GetAgentCreatorSettlementSummaryQueryData.toChannelQueryData() =
GetAgentChannelDonationSettlementByCreatorQueryData(
creatorId, creatorNickname, assignmentId, agentSettlementRatioId, count, totalCan, agentSettlementRatio,
amount, metadata
)
private fun settlementTotal(scope: SettlementScope, legacy: Array<*>): GetAgentSettlementByCreatorTotal {
val includesCanonical = !requireNotNull(scope.window.endUtc).isBefore(countrySettlementPolicy.effectiveAtUtc)
val canonicalAmounts = if (includesCanonical) canonicalRepository.readTotals(scope) else SettlementAmounts.ZERO
val canonicalCount = if (includesCanonical) canonicalRepository.countTransactions(scope) else 0L
val amounts = SettlementAmounts(
legacy[1].toString().toBigDecimal().longValueExact(),
legacy[2].toString().toBigDecimal().longValueExact(),
legacy[3].toString().toBigDecimal().longValueExact(),
legacy[4].toString().toBigDecimal().longValueExact(),
legacy[5].toString().toBigDecimal().longValueExact(),
legacy[6].toString().toBigDecimal().longValueExact(),
legacy[7].toString().toBigDecimal().longValueExact()
) + canonicalAmounts
return GetAgentSettlementByCreatorTotal(
count = Math.toIntExact(Math.addExact(legacy[0].toString().toBigDecimal().longValueExact(), canonicalCount)),
totalCan = Math.toIntExact(amounts.totalCan),
krw = Math.toIntExact(amounts.grossAmount),
fee = Math.toIntExact(amounts.paymentFee),
settlementAmount = Math.toIntExact(amounts.settlementAmount),
tax = Math.toIntExact(amounts.withholdingTax),
depositAmount = Math.toIntExact(amounts.depositAmount),
agentSettlementAmount = Math.toIntExact(amounts.agentSettlementAmount)
)
}
private fun countCanonicalDisplayRows(scope: SettlementScope): Long =
if (requireNotNull(scope.window.endUtc).isBefore(countrySettlementPolicy.effectiveAtUtc)) {
0L
} else {
canonicalRepository.countDisplayRows(scope, SettlementDisplayGrain.CREATOR)
}
private fun assignedToAgentAtEventTime(
agentId: Long,
eventTime: DateTimeExpression<LocalDateTime>
@@ -1,10 +1,12 @@
package kr.co.vividnext.sodalive.partner.agent.calculate
import kr.co.vividnext.sodalive.extensions.convertLocalDateTime
import kr.co.vividnext.sodalive.partner.agent.settlement.snapshot.AgentSettlementSnapshotQueryRepository
import kr.co.vividnext.sodalive.partner.agent.settlement.snapshot.AgentSettlementSnapshotRepository
import kr.co.vividnext.sodalive.partner.agent.settlement.snapshot.AgentSettlementSnapshotType
import kr.co.vividnext.sodalive.partner.agent.settlement.snapshot.toChannelDonationSettlementByCreatorItems
import kr.co.vividnext.sodalive.partner.agent.settlement.snapshot.toSettlementByCreatorItems
import kr.co.vividnext.sodalive.partner.agent.settlement.snapshot.toChannelDonationSettlementByCreatorResponse
import kr.co.vividnext.sodalive.partner.agent.settlement.snapshot.toSettlementByCreatorResponse
import kr.co.vividnext.sodalive.v2.settlement.domain.CountrySettlementPolicy
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.time.LocalDateTime
@@ -14,6 +16,8 @@ class AgentCalculateService(
private val repository: AgentCalculateQueryRepository,
private val snapshotRepository: AgentSettlementSnapshotRepository
) {
private val snapshotQueryRepository = AgentSettlementSnapshotQueryRepository(snapshotRepository)
@Transactional(readOnly = true)
fun getAssignedCreators(agentId: Long, offset: Long, limit: Long): GetAgentAssignedCreatorResponse {
val currentTime = LocalDateTime.now()
@@ -139,26 +143,31 @@ class AgentCalculateService(
limit: Long
): GetAgentChannelDonationSettlementByCreatorResponse {
val (startDate, endDate) = toDateRange(startDateStr, endDateStr)
val snapshots = snapshotRepository.findAllByPeriodStartAndPeriodEndAndSettlementTypeAndAgentIdOrderByCreatorIdDesc(
val finalized = snapshotRepository.existsByPeriodStartAndPeriodEndAndSettlementTypeAndAgentId(
periodStart = startDate,
periodEnd = endDate,
settlementType = AgentSettlementSnapshotType.CHANNEL_DONATION,
agentId = agentId
)
if (snapshots.isNotEmpty()) {
val total = snapshots.toChannelDonationSettlementByCreatorItems().toResponseTotal()
val items = snapshots.drop(offset.toInt()).take(limit.toInt()).toChannelDonationSettlementByCreatorItems()
return GetAgentChannelDonationSettlementByCreatorResponse(
totalCount = snapshots.size,
total = total,
items = items
)
if (finalized) {
return snapshotQueryRepository.readSettlementPage(
startDate,
endDate,
AgentSettlementSnapshotType.CHANNEL_DONATION,
agentId,
offset,
limit
).toChannelDonationSettlementByCreatorResponse()
}
val totalCount = repository.getChannelDonationByCreatorTotalCount(startDate, endDate, agentId)
val total = repository.getChannelDonationByCreatorTotal(startDate, endDate, agentId)
val items = repository.getChannelDonationByCreator(startDate, endDate, agentId, offset, limit)
.toMergedResponseItems()
val rows = repository.getChannelDonationByCreator(startDate, endDate, agentId, offset, limit)
val items = if (endDate.isBefore(CountrySettlementPolicy().effectiveAtUtc)) {
rows.toMergedResponseItems()
} else {
rows.map { it.toResponseItem() }
}
return GetAgentChannelDonationSettlementByCreatorResponse(
totalCount = totalCount,
@@ -179,26 +188,31 @@ class AgentCalculateService(
pagedRowsLoader: (LocalDateTime, LocalDateTime) -> List<GetAgentCreatorSettlementSummaryQueryData>
): GetAgentSettlementByCreatorResponse {
val (startDate, endDate) = toDateRange(startDateStr, endDateStr)
val snapshots = snapshotRepository.findAllByPeriodStartAndPeriodEndAndSettlementTypeAndAgentIdOrderByCreatorIdDesc(
val finalized = snapshotRepository.existsByPeriodStartAndPeriodEndAndSettlementTypeAndAgentId(
periodStart = startDate,
periodEnd = endDate,
settlementType = settlementType,
agentId = agentId
)
if (snapshots.isNotEmpty()) {
val total = snapshots.toSettlementByCreatorItems().toResponseTotal()
val items = snapshots.drop(offset.toInt()).take(limit.toInt()).toSettlementByCreatorItems()
return GetAgentSettlementByCreatorResponse(
totalCount = snapshots.size,
total = total,
items = items
)
if (finalized) {
return snapshotQueryRepository.readSettlementPage(
startDate,
endDate,
settlementType,
agentId,
offset,
limit
).toSettlementByCreatorResponse()
}
val totalCount = totalCountLoader(startDate, endDate)
val total = totalLoader(startDate, endDate)
val items = pagedRowsLoader(startDate, endDate)
.toMergedResponseItems()
val rows = pagedRowsLoader(startDate, endDate)
val items = if (endDate.isBefore(CountrySettlementPolicy().effectiveAtUtc)) {
rows.toMergedResponseItems()
} else {
rows.map { it.toResponseItem() }
}
return GetAgentSettlementByCreatorResponse(
totalCount = totalCount,
@@ -2,6 +2,10 @@ package kr.co.vividnext.sodalive.partner.agent.calculate
import com.querydsl.core.annotations.QueryProjection
import kr.co.vividnext.sodalive.calculate.channelDonation.ChannelDonationSettlementCalculator
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementAmounts
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementCountryRelation
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementRowKey
import kr.co.vividnext.sodalive.v2.settlement.dto.SettlementRateMetadata
import java.math.BigDecimal
import java.math.RoundingMode
@@ -32,10 +36,16 @@ data class GetAgentChannelDonationSettlementByCreatorItem(
val settlementAmount: Int,
val withholdingTax: Int,
val depositAmount: Int,
val agentSettlementAmount: Int
val agentSettlementAmount: Int,
val rowKey: String = SettlementRowKey.legacy("agent-channel-creator", listOf(creatorId.toString())),
val countryRelation: SettlementCountryRelation? = null,
val appliedSettlementRatio: Int? = null,
val agentId: Long? = null,
val appliedAgentSettlementRatio: Int? = null,
val rateInfoAvailable: Boolean = false
)
data class GetAgentChannelDonationSettlementByCreatorQueryData @QueryProjection constructor(
data class GetAgentChannelDonationSettlementByCreatorQueryData(
val creatorId: Long,
val creatorNickname: String,
val assignmentId: Long? = null,
@@ -43,11 +53,45 @@ data class GetAgentChannelDonationSettlementByCreatorQueryData @QueryProjection
val count: Long,
val totalCan: Int,
val agentSettlementRatio: Int? = null,
val newPolicyCan: Int = 0,
val newPolicyWeightedRatioCan: Long = 0L
val amount: SettlementAmounts? = null,
val metadata: SettlementRateMetadata? = null
) {
@QueryProjection
constructor(
creatorId: Long,
creatorNickname: String,
assignmentId: Long?,
agentSettlementRatioId: Long?,
count: Long,
totalCan: Int,
agentSettlementRatio: Int?
) : this(
creatorId, creatorNickname, assignmentId, agentSettlementRatioId, count, totalCan, agentSettlementRatio, null, null
)
fun toResponseItem(): GetAgentChannelDonationSettlementByCreatorItem {
val amount = ChannelDonationSettlementCalculator.calculate(totalCan, newPolicyCan, newPolicyWeightedRatioCan)
amount?.let {
val rate = requireNotNull(metadata)
return GetAgentChannelDonationSettlementByCreatorItem(
creatorId = creatorId,
creatorNickname = creatorNickname,
count = Math.toIntExact(count),
totalCan = Math.toIntExact(it.totalCan),
krw = Math.toIntExact(it.grossAmount),
fee = Math.toIntExact(it.paymentFee),
settlementAmount = Math.toIntExact(it.settlementAmount),
withholdingTax = Math.toIntExact(it.withholdingTax),
depositAmount = Math.toIntExact(it.depositAmount),
agentSettlementAmount = Math.toIntExact(it.agentSettlementAmount),
rowKey = rate.rowKey,
countryRelation = rate.countryRelation,
appliedSettlementRatio = rate.appliedSettlementRatio,
agentId = rate.agentId,
appliedAgentSettlementRatio = rate.appliedAgentSettlementRatio,
rateInfoAvailable = rate.rateInfoAvailable
)
}
val amount = ChannelDonationSettlementCalculator.calculate(totalCan)
return GetAgentChannelDonationSettlementByCreatorItem(
creatorId = creatorId,
creatorNickname = creatorNickname,
@@ -1,10 +1,12 @@
package kr.co.vividnext.sodalive.partner.agent.calculate
import com.querydsl.core.annotations.QueryProjection
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementAmounts
import kr.co.vividnext.sodalive.v2.settlement.dto.SettlementRateMetadata
import java.math.BigDecimal
import java.math.RoundingMode
data class GetAgentCreatorSettlementSummaryQueryData @QueryProjection constructor(
data class GetAgentCreatorSettlementSummaryQueryData(
val creatorId: Long,
val creatorNickname: String,
val assignmentId: Long? = null,
@@ -13,18 +15,50 @@ data class GetAgentCreatorSettlementSummaryQueryData @QueryProjection constructo
val totalCan: Int,
val settlementRatio: Int?,
val agentSettlementRatio: Int? = null,
val newPolicyCan: Int = 0,
val newPolicyWeightedRatioCan: Long = 0L
val amount: SettlementAmounts? = null,
val metadata: SettlementRateMetadata? = null
) {
@QueryProjection
constructor(
creatorId: Long,
creatorNickname: String,
assignmentId: Long?,
agentSettlementRatioId: Long?,
count: Long,
totalCan: Int,
settlementRatio: Int?,
agentSettlementRatio: Int?
) : this(
creatorId, creatorNickname, assignmentId, agentSettlementRatioId, count, totalCan, settlementRatio,
agentSettlementRatio, null, null
)
fun toResponseItem(): GetAgentSettlementByCreatorItem {
amount?.let {
val rate = requireNotNull(metadata)
return GetAgentSettlementByCreatorItem(
creatorId = creatorId,
creatorNickname = creatorNickname,
count = Math.toIntExact(count),
totalCan = Math.toIntExact(it.totalCan),
krw = Math.toIntExact(it.grossAmount),
fee = Math.toIntExact(it.paymentFee),
settlementAmount = Math.toIntExact(it.settlementAmount),
tax = Math.toIntExact(it.withholdingTax),
depositAmount = Math.toIntExact(it.depositAmount),
agentSettlementAmount = Math.toIntExact(it.agentSettlementAmount),
rowKey = rate.rowKey,
countryRelation = rate.countryRelation,
appliedSettlementRatio = rate.appliedSettlementRatio,
agentId = rate.agentId,
appliedAgentSettlementRatio = rate.appliedAgentSettlementRatio,
rateInfoAvailable = rate.rateInfoAvailable
)
}
val totalKrw = BigDecimal(totalCan).multiply(KRW_PER_CAN)
val fee = totalKrw.multiply(PAYMENT_FEE_RATE)
val legacyKrw = BigDecimal(totalCan.toLong() - newPolicyCan.toLong()).multiply(KRW_PER_CAN)
val legacySettlementAmount = legacyKrw.subtract(legacyKrw.multiply(PAYMENT_FEE_RATE))
val settlementAmount = totalKrw.subtract(fee)
.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()
@@ -1,5 +1,8 @@
package kr.co.vividnext.sodalive.partner.agent.calculate
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementCountryRelation
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementRowKey
data class GetAgentSettlementByCreatorResponse(
val totalCount: Int,
val total: GetAgentSettlementByCreatorTotal,
@@ -27,7 +30,13 @@ data class GetAgentSettlementByCreatorItem(
val settlementAmount: Int,
val tax: Int,
val depositAmount: Int,
val agentSettlementAmount: Int
val agentSettlementAmount: Int,
val rowKey: String = SettlementRowKey.legacy("agent-creator", listOf(creatorId.toString())),
val countryRelation: SettlementCountryRelation? = null,
val appliedSettlementRatio: Int? = null,
val agentId: Long? = null,
val appliedAgentSettlementRatio: Int? = null,
val rateInfoAvailable: Boolean = false
)
fun List<GetAgentSettlementByCreatorItem>.toResponseTotal(): GetAgentSettlementByCreatorTotal {
@@ -0,0 +1,135 @@
package kr.co.vividnext.sodalive.partner.agent.settlement.snapshot
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementAmounts
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementCountryRelation
import kr.co.vividnext.sodalive.v2.settlement.dto.SettlementDisplayRow
import kr.co.vividnext.sodalive.v2.settlement.dto.SettlementRateMetadata
import kr.co.vividnext.sodalive.v2.settlement.dto.SettlementRowDescription
import java.time.LocalDateTime
class AgentSettlementSnapshotQueryRepository(private val repository: AgentSettlementSnapshotRepository) {
fun readSettlementPage(
periodStart: LocalDateTime,
periodEnd: LocalDateTime,
settlementType: AgentSettlementSnapshotType,
agentId: Long,
offset: Long,
limit: Long
): SnapshotSettlementPage {
require(offset >= 0 && limit > 0)
val total = repository.readSettlementTotals(periodStart, periodEnd, settlementType.name, agentId)
val count = repository.countSettlementDisplayRows(periodStart, periodEnd, settlementType.name, agentId)
val items = repository.readSettlementDisplayRows(periodStart, periodEnd, settlementType.name, agentId, offset, limit)
return SnapshotSettlementPage(
count,
total.transactionCount,
total.toAmounts(),
items.map { row ->
SettlementDisplayRow(
SettlementRateMetadata(
row.rowKey,
row.countryRelation?.let(SettlementCountryRelation::valueOf),
row.appliedSettlementRatio,
row.agentId,
row.appliedAgentSettlementRatio,
row.rateInfoAvailable == 1
),
row.creatorId,
null,
row.transactionCount,
0,
row.toAmounts(),
SettlementRowDescription(row.creatorNickname, null, null, null, null)
)
}
)
}
}
data class SnapshotSettlementPage(
val totalCount: Long,
val transactionCount: Long,
val total: SettlementAmounts,
val items: List<SettlementDisplayRow>
)
interface SnapshotStoredAmounts {
val transactionCount: Long
val totalCan: Long
val grossAmount: Long
val paymentFee: Long
val settlementAmount: Long
val withholdingTax: Long
val depositAmount: Long
val agentSettlementAmount: Long
}
interface SnapshotStoredDisplayRow : SnapshotStoredAmounts {
val rowKey: String
val creatorId: Long
val creatorNickname: String
val countryRelation: String?
val appliedSettlementRatio: Int?
val agentId: Long
val appliedAgentSettlementRatio: Int?
val rateInfoAvailable: Int
}
private fun SnapshotStoredAmounts.toAmounts() = SettlementAmounts(
totalCan,
grossAmount,
paymentFee,
settlementAmount,
withholdingTax,
depositAmount,
agentSettlementAmount
)
private const val SNAPSHOT_SCOPE =
"s.period_start = :periodStart AND s.period_end = :periodEnd " +
"AND s.settlement_type = :settlementType AND s.agent_id = :agentId"
private const val COMPLETE_SNAPSHOT =
"EXISTS (SELECT 1 FROM agent_settlement_snapshot_source_detail c WHERE c.snapshot_id = s.id) " +
"AND NOT EXISTS (SELECT 1 FROM agent_settlement_snapshot_source_detail c " +
"WHERE c.snapshot_id = s.id AND c.canonical_row_key IS NULL)"
private const val SNAPSHOT_DISPLAY_INPUT =
"SELECT s.creator_id, s.creator_nickname, s.agent_id, d.country_relation, d.applied_settlement_ratio, " +
"d.applied_agent_settlement_ratio, CASE WHEN d.rate_info_available = TRUE THEN 1 ELSE 0 END AS rate_info_available, " +
"d.count AS transaction_count, d.total_can, d.krw, d.fee, d.settlement_amount, d.tax, " +
"d.deposit_amount, d.agent_settlement_amount, " +
"CONCAT('rs1|C|', CASE s.settlement_type WHEN 'LIVE' THEN 'LIVE' WHEN 'CONTENT' THEN 'CONTENT_SALES' " +
"WHEN 'CONTENT_DONATION' THEN 'CONTENT_DONATION' WHEN 'COMMUNITY' THEN 'COMMUNITY_POST' " +
"WHEN 'CHANNEL_DONATION' THEN 'CHANNEL_DONATION' END, '|', s.creator_id, '|', " +
"d.country_relation, '|', d.applied_settlement_ratio, '|', s.agent_id, '|', " +
"CASE WHEN d.applied_agent_settlement_ratio IS NULL THEN '~' " +
"ELSE CONCAT('', d.applied_agent_settlement_ratio) END) AS row_key " +
"FROM agent_settlement_snapshot s JOIN agent_settlement_snapshot_source_detail d ON d.snapshot_id = s.id " +
"WHERE $SNAPSHOT_SCOPE AND ($COMPLETE_SNAPSHOT) UNION ALL " +
"SELECT s.creator_id, s.creator_nickname, s.agent_id, NULL, NULL, s.applied_agent_settlement_ratio, 0, " +
"s.count, s.total_can, s.krw, s.fee, s.settlement_amount, s.tax, s.deposit_amount, s.agent_settlement_amount, " +
"CONCAT('ss0|', s.id) FROM agent_settlement_snapshot s " +
"WHERE $SNAPSHOT_SCOPE AND NOT ($COMPLETE_SNAPSHOT)"
internal const val SNAPSHOT_DISPLAY_COUNT =
"SELECT COUNT(*) FROM (SELECT row_key FROM ($SNAPSHOT_DISPLAY_INPUT) inputs GROUP BY row_key) display_keys"
internal const val SNAPSHOT_DISPLAY_PAGE =
"SELECT row_key AS rowKey, creator_id AS creatorId, creator_nickname AS creatorNickname, agent_id AS agentId, " +
"country_relation AS countryRelation, applied_settlement_ratio AS appliedSettlementRatio, " +
"applied_agent_settlement_ratio AS appliedAgentSettlementRatio, rate_info_available AS rateInfoAvailable, " +
"SUM(transaction_count) AS transactionCount, SUM(total_can) AS totalCan, SUM(krw) AS grossAmount, " +
"SUM(fee) AS paymentFee, SUM(settlement_amount) AS settlementAmount, SUM(tax) AS withholdingTax, " +
"SUM(deposit_amount) AS depositAmount, SUM(agent_settlement_amount) AS agentSettlementAmount " +
"FROM ($SNAPSHOT_DISPLAY_INPUT) inputs GROUP BY row_key, creator_id, creator_nickname, agent_id, " +
"country_relation, applied_settlement_ratio, applied_agent_settlement_ratio, rate_info_available " +
"ORDER BY creator_id DESC, row_key ASC LIMIT :limit OFFSET :offset"
internal const val SNAPSHOT_ROOT_TOTALS =
"SELECT COALESCE(SUM(s.count), 0) AS transactionCount, COALESCE(SUM(s.total_can), 0) AS totalCan, " +
"COALESCE(SUM(s.krw), 0) AS grossAmount, COALESCE(SUM(s.fee), 0) AS paymentFee, " +
"COALESCE(SUM(s.settlement_amount), 0) AS settlementAmount, COALESCE(SUM(s.tax), 0) AS withholdingTax, " +
"COALESCE(SUM(s.deposit_amount), 0) AS depositAmount, " +
"COALESCE(SUM(s.agent_settlement_amount), 0) AS agentSettlementAmount " +
"FROM agent_settlement_snapshot s WHERE $SNAPSHOT_SCOPE"
@@ -1,6 +1,8 @@
package kr.co.vividnext.sodalive.partner.agent.settlement.snapshot
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.jpa.repository.Query
import org.springframework.data.repository.query.Param
import java.time.LocalDateTime
interface AgentSettlementSnapshotRepository : JpaRepository<AgentSettlementSnapshot, Long> {
@@ -11,10 +13,29 @@ interface AgentSettlementSnapshotRepository : JpaRepository<AgentSettlementSnaps
agentId: Long
): Boolean
fun findAllByPeriodStartAndPeriodEndAndSettlementTypeAndAgentIdOrderByCreatorIdDesc(
periodStart: LocalDateTime,
periodEnd: LocalDateTime,
settlementType: AgentSettlementSnapshotType,
agentId: Long
): List<AgentSettlementSnapshot>
@Query(value = SNAPSHOT_ROOT_TOTALS, nativeQuery = true)
fun readSettlementTotals(
@Param("periodStart") periodStart: LocalDateTime,
@Param("periodEnd") periodEnd: LocalDateTime,
@Param("settlementType") settlementType: String,
@Param("agentId") agentId: Long
): SnapshotStoredAmounts
@Query(value = SNAPSHOT_DISPLAY_COUNT, nativeQuery = true)
fun countSettlementDisplayRows(
@Param("periodStart") periodStart: LocalDateTime,
@Param("periodEnd") periodEnd: LocalDateTime,
@Param("settlementType") settlementType: String,
@Param("agentId") agentId: Long
): Long
@Query(value = SNAPSHOT_DISPLAY_PAGE, nativeQuery = true)
fun readSettlementDisplayRows(
@Param("periodStart") periodStart: LocalDateTime,
@Param("periodEnd") periodEnd: LocalDateTime,
@Param("settlementType") settlementType: String,
@Param("agentId") agentId: Long,
@Param("offset") offset: Long,
@Param("limit") limit: Long
): List<SnapshotStoredDisplayRow>
}
@@ -1,39 +1,57 @@
package kr.co.vividnext.sodalive.partner.agent.settlement.snapshot
import kr.co.vividnext.sodalive.partner.agent.calculate.GetAgentChannelDonationSettlementByCreatorItem
import kr.co.vividnext.sodalive.partner.agent.calculate.GetAgentSettlementByCreatorItem
import kr.co.vividnext.sodalive.partner.agent.calculate.GetAgentChannelDonationSettlementByCreatorQueryData
import kr.co.vividnext.sodalive.partner.agent.calculate.GetAgentChannelDonationSettlementByCreatorResponse
import kr.co.vividnext.sodalive.partner.agent.calculate.GetAgentChannelDonationSettlementTotal
import kr.co.vividnext.sodalive.partner.agent.calculate.GetAgentCreatorSettlementSummaryQueryData
import kr.co.vividnext.sodalive.partner.agent.calculate.GetAgentSettlementByCreatorResponse
import kr.co.vividnext.sodalive.partner.agent.calculate.GetAgentSettlementByCreatorTotal
fun List<AgentSettlementSnapshot>.toSettlementByCreatorItems(): List<GetAgentSettlementByCreatorItem> {
return map {
GetAgentSettlementByCreatorItem(
creatorId = it.creatorId,
creatorNickname = it.creatorNickname,
count = it.count,
totalCan = it.totalCan,
krw = it.krw,
fee = it.fee,
settlementAmount = it.settlementAmount,
tax = it.tax,
depositAmount = it.depositAmount,
agentSettlementAmount = it.agentSettlementAmount
)
fun SnapshotSettlementPage.toSettlementByCreatorResponse() = GetAgentSettlementByCreatorResponse(
totalCount = Math.toIntExact(totalCount),
total = GetAgentSettlementByCreatorTotal(
Math.toIntExact(transactionCount),
Math.toIntExact(total.totalCan),
Math.toIntExact(total.grossAmount),
Math.toIntExact(total.paymentFee),
Math.toIntExact(total.settlementAmount),
Math.toIntExact(total.withholdingTax),
Math.toIntExact(total.depositAmount),
Math.toIntExact(total.agentSettlementAmount)
),
items = items.map { row ->
GetAgentCreatorSettlementSummaryQueryData(
creatorId = row.creatorId,
creatorNickname = row.description.creatorNickname,
count = row.transactionCount,
totalCan = Math.toIntExact(row.amount.totalCan),
settlementRatio = row.metadata.appliedSettlementRatio,
amount = row.amount,
metadata = row.metadata
).toResponseItem()
}
}
)
fun List<AgentSettlementSnapshot>.toChannelDonationSettlementByCreatorItems():
List<GetAgentChannelDonationSettlementByCreatorItem> {
return map {
GetAgentChannelDonationSettlementByCreatorItem(
creatorId = it.creatorId,
creatorNickname = it.creatorNickname,
count = it.count,
totalCan = it.totalCan,
krw = it.krw,
fee = it.fee,
settlementAmount = it.settlementAmount,
withholdingTax = it.tax,
depositAmount = it.depositAmount,
agentSettlementAmount = it.agentSettlementAmount
)
fun SnapshotSettlementPage.toChannelDonationSettlementByCreatorResponse() = GetAgentChannelDonationSettlementByCreatorResponse(
totalCount = Math.toIntExact(totalCount),
total = GetAgentChannelDonationSettlementTotal(
Math.toIntExact(transactionCount),
Math.toIntExact(total.totalCan),
Math.toIntExact(total.grossAmount),
Math.toIntExact(total.paymentFee),
Math.toIntExact(total.settlementAmount),
Math.toIntExact(total.withholdingTax),
Math.toIntExact(total.depositAmount),
Math.toIntExact(total.agentSettlementAmount)
),
items = items.map { row ->
GetAgentChannelDonationSettlementByCreatorQueryData(
creatorId = row.creatorId,
creatorNickname = row.description.creatorNickname,
count = row.transactionCount,
totalCan = Math.toIntExact(row.amount.totalCan),
amount = row.amount,
metadata = row.metadata
).toResponseItem()
}
}
)
@@ -1,13 +1,25 @@
package kr.co.vividnext.sodalive.partner.agent.settlement.snapshot
import kr.co.vividnext.sodalive.common.BaseEntity
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementCountryRelation
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementProvenance
import javax.persistence.Column
import javax.persistence.Convert
import javax.persistence.Entity
import javax.persistence.EnumType
import javax.persistence.Enumerated
import javax.persistence.FetchType
import javax.persistence.JoinColumn
import javax.persistence.ManyToOne
import javax.persistence.Table
import javax.persistence.UniqueConstraint
@Entity
@Table(
uniqueConstraints = [
UniqueConstraint(name = "uk_snapshot_detail_canonical", columnNames = ["snapshot_id", "canonical_row_key"])
]
)
class AgentSettlementSnapshotSourceDetail(
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "snapshot_id", nullable = false)
@@ -44,5 +56,22 @@ class AgentSettlementSnapshotSourceDetail(
var depositAmount: Int,
@Column(nullable = false, updatable = false)
var agentSettlementAmount: Int
var agentSettlementAmount: Int,
@Column(name = "canonical_row_key", length = 384, updatable = false)
var canonicalRowKey: String? = null,
@Enumerated(EnumType.STRING)
@Column(length = 24, updatable = false)
var countryRelation: SettlementCountryRelation? = null,
@Column(updatable = false)
var appliedSettlementRatio: Int? = null,
@Column(updatable = false)
var rateInfoAvailable: Boolean? = null,
@Convert(converter = SettlementProvenanceJsonConverter::class)
@Column(name = "provenance_json", columnDefinition = "LONGTEXT", updatable = false)
var provenance: List<SettlementProvenance>? = null
) : BaseEntity()
@@ -0,0 +1,20 @@
package kr.co.vividnext.sodalive.partner.agent.settlement.snapshot
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementProvenance
import javax.persistence.AttributeConverter
import javax.persistence.Converter
@Converter
class SettlementProvenanceJsonConverter : AttributeConverter<List<SettlementProvenance>?, String?> {
override fun convertToDatabaseColumn(attribute: List<SettlementProvenance>?): String? =
attribute?.let { mapper.writeValueAsString(it) }
override fun convertToEntityAttribute(dbData: String?): List<SettlementProvenance>? =
dbData?.let { mapper.readValue<List<SettlementProvenance>>(it) }
companion object {
private val mapper = jacksonObjectMapper()
}
}
@@ -6,9 +6,20 @@ 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.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.GetCreatorMonthlySettlementResponse
import kr.co.vividnext.sodalive.v2.settlement.adapter.out.persistence.CanonicalSettlementQueryRepository
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
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementEconomics
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementRowKey
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementScope
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementSource
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementWindow
import kr.co.vividnext.sodalive.v2.settlement.dto.SettlementRateMetadata
import org.springframework.data.repository.findByIdOrNull
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Isolation
@@ -23,7 +34,9 @@ import java.time.ZoneOffset
class CreatorMonthlySettlementService(
private val repository: CreatorAdminCalculateQueryRepository,
private val channelRepository: CreatorAdminChannelDonationCalculateQueryRepository,
private val memberRepository: MemberRepository
private val memberRepository: MemberRepository,
private val canonicalRepository: CanonicalSettlementQueryRepository,
private val policy: CountrySettlementPolicy
) {
@Transactional(readOnly = true, isolation = Isolation.REPEATABLE_READ)
fun getMonthlySummary(memberId: Long, month: YearMonth): GetCreatorMonthlySettlementResponse {
@@ -36,94 +49,130 @@ class CreatorMonthlySettlementService(
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() }
var total = SettlementAmounts.ZERO
val breakdown = SettlementSource.values().map { source ->
val scope = SettlementScope(source, SettlementWindow(startUtc, endUtc, endExclusive = true), creatorId = memberId)
val folded = linkedMapOf<SettlementEconomics, SettlementAmounts>()
if (endUtc.isAfter(policy.effectiveAtUtc)) {
canonicalRepository.forEachCanonicalRow(scope) { row ->
val economics = row.key.economics
folded[economics] = (folded[economics] ?: SettlementAmounts.ZERO) + row.amount
}
}
val rates = folded.mapKeys { (economics, _) ->
SettlementRateMetadata(
rowKey = SettlementRowKey.monthly(source, memberId, economics),
countryRelation = economics.countryRelation,
appliedSettlementRatio = economics.appliedSettlementRatio,
agentId = economics.agentId,
appliedAgentSettlementRatio = economics.appliedAgentSettlementRatio,
rateInfoAvailable = true
)
),
}.toMutableMap()
if (startUtc.isBefore(policy.effectiveAtUtc)) {
val legacyScope = scope.copy(window = scope.window.copy(endUtc = minOf(endUtc, policy.effectiveAtUtc)))
legacyAmounts(legacyScope)?.let { amount ->
val metadata = SettlementRateMetadata(
rowKey = SettlementRowKey.legacy("monthly", listOf(source.name, memberId.toString())),
countryRelation = SettlementCountryRelation.LEGACY,
appliedSettlementRatio = null,
agentId = null,
appliedAgentSettlementRatio = null,
rateInfoAvailable = false
)
rates[metadata] = amount
}
}
val amount = rates.values.fold(SettlementAmounts.ZERO) { sum, rate -> sum + rate }
total += amount
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()
)
source = when (source) {
SettlementSource.LIVE -> CreatorMonthlySettlementSource.LIVE
SettlementSource.CONTENT_SALES -> CreatorMonthlySettlementSource.CONTENT_SALES
SettlementSource.CONTENT_DONATION -> CreatorMonthlySettlementSource.CONTENT_DONATION
SettlementSource.COMMUNITY_POST -> CreatorMonthlySettlementSource.COMMUNITY_POST
SettlementSource.CHANNEL_DONATION -> CreatorMonthlySettlementSource.CHANNEL_DONATION
},
hasRevenueData = rates.isNotEmpty(),
amount = CreatorMonthlySettlementAmount(amount),
rateDetails = rates.entries
.sortedWith(compareBy({ it.key.countryRelation == SettlementCountryRelation.LEGACY }, { it.key.rowKey }))
.map { (metadata, rateAmount) ->
CreatorMonthlySettlementRateDetail(metadata, CreatorMonthlySettlementAmount(rateAmount))
}
)
)
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,
total = CreatorMonthlySettlementAmount(total),
breakdown = breakdown
)
}
private fun legacyAmounts(scope: SettlementScope): SettlementAmounts? {
val start = requireNotNull(scope.window.startInclusiveUtc)
val end = requireNotNull(scope.window.endUtc)
val memberId = requireNotNull(scope.creatorId)
val amounts = when (scope.source) {
SettlementSource.LIVE -> repository.getMonthlyCalculateLive(start, end, memberId).map { row ->
val response = row.toGetCalculateLiveResponse()
SettlementAmounts(
response.totalAmount.toLong(),
response.totalKrw.toLong(),
response.paymentFee.toLong(),
response.settlementAmount.toLong(),
response.tax.toLong(),
response.depositAmount.toLong(),
0
)
}
SettlementSource.CONTENT_SALES -> repository.getMonthlyCalculateContentList(start, end, memberId).map { row ->
val response = row.toGetCalculateContentResponse()
SettlementAmounts(
response.totalCan.toLong(),
response.totalKrw.toLong(),
response.paymentFee.toLong(),
response.settlementAmount.toLong(),
response.tax.toLong(),
response.depositAmount.toLong(),
0
)
}
SettlementSource.CONTENT_DONATION -> repository.getMonthlyCalculateContentDonationList(start, end, memberId)
.map { row ->
val response = row.toGetCalculateContentDonationResponse()
SettlementAmounts(
response.totalCan.toLong(),
response.totalKrw.toLong(),
response.paymentFee.toLong(),
response.settlementAmount.toLong(),
response.tax.toLong(),
response.depositAmount.toLong(),
0
)
}
SettlementSource.COMMUNITY_POST -> repository.getMonthlyCalculateCommunityPostList(start, end, memberId)
.map { row ->
val response = row.toGetCalculateCommunityPostResponse()
SettlementAmounts(
response.totalCan.toLong(),
response.totalKrw.toLong(),
response.paymentFee.toLong(),
response.settlementAmount.toLong(),
response.tax.toLong(),
response.depositAmount.toLong(),
0
)
}
SettlementSource.CHANNEL_DONATION -> {
// Legacy channel totals round the whole period rather than summing daily amounts.
val channel = channelRepository.getMonthlyChannelDonationSettlementTotal(start, end, memberId)
if ((channel.count ?: 0L) > 0L) listOf(channel.amount) else emptyList()
}
}
return if (amounts.isEmpty()) null else amounts.fold(SettlementAmounts.ZERO) { sum, amount -> sum + amount }
}
}
@@ -1,6 +1,8 @@
package kr.co.vividnext.sodalive.v2.api.creator.settlement.dto
import com.fasterxml.jackson.annotation.JsonUnwrapped
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementAmounts
import kr.co.vividnext.sodalive.v2.settlement.dto.SettlementRateMetadata
data class GetCreatorMonthlySettlementResponse(
val month: String,
@@ -25,6 +27,15 @@ data class CreatorMonthlySettlementAmount(
val withholdingTax: Long,
val depositAmount: Long
) {
constructor(amount: SettlementAmounts) : this(
amount.totalCan,
amount.grossAmount,
amount.paymentFee,
amount.settlementAmount,
amount.withholdingTax,
amount.depositAmount
)
val platformFee: Long
get() = grossAmount - paymentFee - settlementAmount
}
@@ -32,6 +43,12 @@ data class CreatorMonthlySettlementAmount(
data class CreatorMonthlySettlementSourceAmount(
val source: CreatorMonthlySettlementSource,
val hasRevenueData: Boolean,
@get:JsonUnwrapped val amount: CreatorMonthlySettlementAmount,
val rateDetails: List<CreatorMonthlySettlementRateDetail>
)
data class CreatorMonthlySettlementRateDetail(
@get:JsonUnwrapped val metadata: SettlementRateMetadata,
@get:JsonUnwrapped val amount: CreatorMonthlySettlementAmount
)
@@ -0,0 +1,335 @@
package kr.co.vividnext.sodalive.v2.settlement.adapter.out.persistence
import kr.co.vividnext.sodalive.can.use.CanUsage
import kr.co.vividnext.sodalive.content.order.OrderType
import kr.co.vividnext.sodalive.v2.settlement.domain.CanonicalSettlementRow
import kr.co.vividnext.sodalive.v2.settlement.domain.CountrySettlementPolicy
import kr.co.vividnext.sodalive.v2.settlement.domain.RateSeparatedSettlementCalculator
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementAmounts
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementCanonicalKey
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementCountryRelation
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementDisplayGrain
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementEconomics
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementProvenance
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementRowKey
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementScope
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementSource
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementSourceGrain
import kr.co.vividnext.sodalive.v2.settlement.dto.SettlementDisplayRow
import kr.co.vividnext.sodalive.v2.settlement.dto.SettlementRateMetadata
import kr.co.vividnext.sodalive.v2.settlement.dto.SettlementRowDescription
import org.hibernate.Session
import org.springframework.jdbc.core.JdbcTemplate
import org.springframework.jdbc.core.RowCallbackHandler
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate
import org.springframework.jdbc.datasource.SingleConnectionDataSource
import org.springframework.stereotype.Repository
import org.springframework.transaction.annotation.Transactional
import java.sql.ResultSet
import java.time.LocalDate
import javax.persistence.EntityManager
@Repository
@Transactional(readOnly = true)
class CanonicalSettlementQueryRepository(
private val entityManager: EntityManager,
private val policy: CountrySettlementPolicy
) {
fun countDisplayRows(scope: SettlementScope, grain: SettlementDisplayGrain): Long {
val sql = CanonicalSettlementSql(scope, policy)
val columns = sql.columns(grain).joinToString(", ")
return jdbc(sql) { db ->
requireNotNull(
db.queryForObject(
"SELECT COUNT(*) FROM (SELECT $columns FROM (${sql.inputs}) q GROUP BY $columns) g",
sql.parameters,
Long::class.java
)
)
}
}
fun readDisplayPage(
scope: SettlementScope,
grain: SettlementDisplayGrain,
offset: Long,
limit: Long
): List<SettlementDisplayRow> {
require(offset >= 0 && limit > 0)
val sql = CanonicalSettlementSql(scope, policy)
val columns = sql.columns(grain)
val group = columns.joinToString(", ")
sql.parameters.addValue("offset", offset).addValue("limit", limit)
return jdbc(sql) { db ->
val selected = db.query(
"SELECT g.* FROM (SELECT $group FROM (${sql.inputs}) q GROUP BY $group) g " +
"JOIN member m ON m.id = g.creator_id ORDER BY ${sql.order(grain)} LIMIT :limit OFFSET :offset",
sql.parameters
) { rs, _ -> displayIdentity(rs, grain) }
if (selected.isEmpty()) return@jdbc emptyList()
val filter = selectedFilter(selected, sql)
val folded = linkedMapOf<DisplayIdentity, CanonicalSettlementRow>()
db.query(
sql.grouped(filter),
sql.parameters,
RowCallbackHandler { rs ->
val row = canonicalRow(rs, scope.source)
val identity = displayIdentity(rs, grain)
val previous = folded[identity]
folded[identity] = if (previous == null) {
row
} else {
previous.copy(
transactionCount = Math.addExact(previous.transactionCount, row.transactionCount),
totalPoint = Math.addExact(previous.totalPoint, row.totalPoint),
amount = previous.amount + row.amount
)
}
}
)
// The grouped stream is closed before enrichment uses the same transaction-bound connection.
val descriptions = descriptions(db, sql, selected)
selected.map { identity ->
val row = folded.getValue(identity)
val economics = row.key.economics
val description = descriptions.getValue(identity.creatorId to identity.sourceId)
SettlementDisplayRow(
SettlementRateMetadata(
SettlementRowKey.display(row.key, grain),
economics.countryRelation,
economics.appliedSettlementRatio,
economics.agentId,
economics.appliedAgentSettlementRatio,
true
),
row.key.creatorId,
when (grain) {
SettlementDisplayGrain.DETAIL -> row.key.grain
SettlementDisplayGrain.CONTENT_CUMULATIVE -> row.key.grain.copy(dayKst = null, canUsage = null)
SettlementDisplayGrain.CREATOR, SettlementDisplayGrain.MONTHLY_RATE -> null
},
row.transactionCount,
row.totalPoint,
row.amount,
description.copy(
displayDate = if (scope.source == SettlementSource.LIVE) description.displayDate else identity.dayKst,
sourcePrice = if (scope.source == SettlementSource.CONTENT_SALES && identity.sourceId != null) {
identity.orderPrice
} else {
description.sourcePrice
}
)
)
}
}
}
fun readCanonicalPage(scope: SettlementScope, offset: Long, limit: Long): List<CanonicalSettlementRow> {
require(offset >= 0 && limit > 0)
val sql = CanonicalSettlementSql(scope, policy)
sql.parameters.addValue("offset", offset).addValue("limit", limit)
return jdbc(sql) { db ->
db.query(
"SELECT g.* FROM (${sql.grouped()}) g JOIN member m ON m.id = g.creator_id " +
"ORDER BY ${sql.order(SettlementDisplayGrain.DETAIL)} LIMIT :limit OFFSET :offset",
sql.parameters
) { rs, _ -> canonicalRow(rs, scope.source) }
}
}
fun countTransactions(scope: SettlementScope): Long {
val sql = CanonicalSettlementSql(scope, policy)
val identity = if (scope.source == SettlementSource.CHANNEL_DONATION && scope.agentId != null) {
"transaction_id, creator_id"
} else {
"transaction_id"
}
return jdbc(sql) { db ->
requireNotNull(
db.queryForObject(
"SELECT COUNT(*) FROM (SELECT DISTINCT $identity FROM (${sql.inputs}) q) t",
sql.parameters,
Long::class.java
)
)
}
}
fun readTotals(scope: SettlementScope): SettlementAmounts {
var total = SettlementAmounts.ZERO
forEachCanonicalRow(scope) { total += it.amount }
return total
}
fun readProvenance(
scope: SettlementScope,
canonicalKeys: List<SettlementCanonicalKey>
): Map<SettlementCanonicalKey, List<SettlementProvenance>> {
val keys = canonicalKeys.filter { it.source == scope.source }.distinct()
if (keys.isEmpty()) return emptyMap()
val sql = CanonicalSettlementSql(scope, policy)
val selected = keys.map { DisplayIdentity.from(it) }
val filter = selectedFilter(selected, sql)
val columns = sql.columns(SettlementDisplayGrain.DETAIL).joinToString(", ")
return jdbc(sql) { db ->
val result = linkedMapOf<SettlementCanonicalKey, MutableList<SettlementProvenance>>()
db.query(
"SELECT DISTINCT $columns, assignment_id, ratio_id FROM (${sql.inputs}) q WHERE $filter " +
"ORDER BY CASE WHEN assignment_id IS NULL THEN 0 ELSE 1 END, assignment_id, " +
"CASE WHEN ratio_id IS NULL THEN 0 ELSE 1 END, ratio_id",
sql.parameters,
RowCallbackHandler { rs ->
val key = canonicalKey(rs, scope.source)
result.getOrPut(key) { mutableListOf() }.add(
SettlementProvenance(rs.nullableLong("assignment_id"), rs.nullableLong("ratio_id"))
)
}
)
result
}
}
/** The callback is arithmetic-only: do not query or write while its JDBC stream is open. */
fun forEachCanonicalRow(scope: SettlementScope, consume: (CanonicalSettlementRow) -> Unit) {
val sql = CanonicalSettlementSql(scope, policy)
jdbc(sql) { db ->
db.query(
"SELECT g.* FROM (${sql.grouped()}) g JOIN member m ON m.id = g.creator_id " +
"ORDER BY ${sql.order(SettlementDisplayGrain.DETAIL)}",
sql.parameters,
RowCallbackHandler { rs -> consume(canonicalRow(rs, scope.source)) }
)
}
}
private fun <T> jdbc(sql: CanonicalSettlementSql, action: (NamedParameterJdbcTemplate) -> T): T {
val session = entityManager.unwrap(Session::class.java)
// Hibernate checks only these query spaces before JDBC, preserving AUTO read-your-writes without a global flush.
val synchronization = session.createNativeQuery("SELECT 1")
sql.spaces.forEach { synchronization.addSynchronizedQuerySpace(it) }
synchronization.resultList
return session.doReturningWork { connection ->
val template = JdbcTemplate(SingleConnectionDataSource(connection, true)).apply {
fetchSize = if (connection.metaData.databaseProductName == "MySQL") Int.MIN_VALUE else 512
}
action(NamedParameterJdbcTemplate(template))
}
}
private fun canonicalRow(rs: ResultSet, source: SettlementSource): CanonicalSettlementRow {
val key = canonicalKey(rs, source)
return CanonicalSettlementRow(
key,
rs.getLong("transaction_count"),
rs.getBigDecimal("total_point").longValueExact(),
RateSeparatedSettlementCalculator.calculate(
source,
rs.getBigDecimal("total_can").longValueExact(),
key.economics.appliedSettlementRatio,
key.economics.appliedAgentSettlementRatio
)
)
}
private fun canonicalKey(rs: ResultSet, source: SettlementSource) = SettlementCanonicalKey(
source,
rs.getLong("creator_id"),
economics(rs),
SettlementSourceGrain(
rs.getLong("source_id"),
rs.getString("day_kst")?.let { LocalDate.parse(it) },
rs.getString("can_usage")?.let { CanUsage.valueOf(it) },
rs.getString("order_type")?.let { OrderType.valueOf(it) },
rs.nullableInt("order_price"),
rs.nullableInt("point_group")
)
)
private fun economics(rs: ResultSet) = SettlementEconomics(
SettlementCountryRelation.valueOf(rs.getString("relation")),
rs.getInt("creator_ratio"),
rs.nullableLong("agent_id"),
rs.nullableInt("agent_ratio")
)
private fun displayIdentity(rs: ResultSet, grain: SettlementDisplayGrain): DisplayIdentity {
val hasSource = grain == SettlementDisplayGrain.DETAIL || grain == SettlementDisplayGrain.CONTENT_CUMULATIVE
return DisplayIdentity(
rs.getLong("creator_id"), economics(rs),
if (hasSource) rs.getLong("source_id") else null,
if (grain == SettlementDisplayGrain.DETAIL) rs.getString("day_kst") else null,
if (grain == SettlementDisplayGrain.DETAIL) rs.getString("can_usage") else null,
if (hasSource) rs.getString("order_type") else null,
if (hasSource) rs.nullableInt("order_price") else null,
if (hasSource) rs.nullableInt("point_group") else null,
grain
)
}
private fun selectedFilter(selected: List<DisplayIdentity>, sql: CanonicalSettlementSql): String =
selected.mapIndexed { index, key ->
val values = MapSqlParameterSource()
.addValue("creator_id", key.creatorId).addValue("relation", key.economics.countryRelation.name)
.addValue("creator_ratio", key.economics.appliedSettlementRatio).addValue("agent_id", key.economics.agentId)
.addValue("agent_ratio", key.economics.appliedAgentSettlementRatio).addValue("source_id", key.sourceId)
.addValue("day_kst", key.dayKst).addValue("can_usage", key.canUsage).addValue("order_type", key.orderType)
.addValue("order_price", key.orderPrice).addValue("point_group", key.pointGroup)
sql.columns(key.grain).joinToString(" AND ", "(", ")") { column ->
val value = values.getValue(column)
if (value == null) {
"q.$column IS NULL"
} else {
val parameter = "key${index}_$column"
sql.parameters.addValue(parameter, value)
"q.$column = :$parameter"
}
}
}.joinToString(" OR ", "(", ")")
private fun descriptions(
db: NamedParameterJdbcTemplate,
sql: CanonicalSettlementSql,
selected: List<DisplayIdentity>
): Map<Pair<Long, Long?>, SettlementRowDescription> {
val bySource = selected.first().sourceId != null
val ids = selected.map { if (bySource) requireNotNull(it.sourceId) else it.creatorId }.distinct()
val parameters = MapSqlParameterSource("ids", ids)
val query = if (bySource) {
"SELECT m.id, s.id, m.nickname, ${sql.descriptionFields()} FROM ${sql.descriptionFrom()} WHERE s.id IN (:ids)"
} else {
"SELECT m.id, NULL, m.nickname, NULL, NULL, NULL, NULL FROM member m WHERE m.id IN (:ids)"
}
return db.query(query, parameters) { rs, _ ->
(rs.getLong(1) to rs.getLong(2).let { if (rs.wasNull()) null else it }) to SettlementRowDescription(
rs.getString(3),
rs.getString(4),
rs.getString(5),
rs.getString(6),
rs.getInt(7).let { if (rs.wasNull()) null else it }
)
}.toMap()
}
private fun ResultSet.nullableLong(column: String): Long? = getLong(column).let { if (wasNull()) null else it }
private fun ResultSet.nullableInt(column: String): Int? = getInt(column).let { if (wasNull()) null else it }
private data class DisplayIdentity(
val creatorId: Long,
val economics: SettlementEconomics,
val sourceId: Long?,
val dayKst: String?,
val canUsage: String?,
val orderType: String?,
val orderPrice: Int?,
val pointGroup: Int?,
val grain: SettlementDisplayGrain
) {
companion object {
fun from(key: SettlementCanonicalKey) = DisplayIdentity(
key.creatorId, key.economics, key.grain.sourceId, key.grain.dayKst?.toString(), key.grain.canUsage?.name,
key.grain.orderType?.name, key.grain.orderPrice, key.grain.pointGroup, SettlementDisplayGrain.DETAIL
)
}
}
}
@@ -0,0 +1,175 @@
package kr.co.vividnext.sodalive.v2.settlement.adapter.out.persistence
import kr.co.vividnext.sodalive.v2.settlement.domain.CountrySettlementPolicy
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementDisplayGrain
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementScope
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementSource
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource
import java.sql.Timestamp
internal class CanonicalSettlementSql(val scope: SettlementScope, policy: CountrySettlementPolicy) {
val parameters = MapSqlParameterSource()
.addValue("policyStart", Timestamp.valueOf(policy.effectiveAtUtc))
.addValue("rateEnd", Timestamp.valueOf(policy.koreanDefaultRateEndExclusiveUtc))
private val sales = scope.source == SettlementSource.CONTENT_SALES
private val event = if (sales) "o.created_at" else "uc.created_at"
private val day = "DATE_FORMAT(CONVERT_TZ($event, 'UTC', 'Asia/Seoul'), '%Y-%m-%d')"
private val creatorCountry = "CASE WHEN m.country_code IS NULL OR TRIM(m.country_code) = '' THEN 'KR' ELSE m.country_code END"
private val buyerCountry =
"CASE WHEN uc.country_code IS NULL OR TRIM(uc.country_code) = '' THEN 'KR' ELSE uc.country_code END"
private val sourceId = when (scope.source) {
SettlementSource.LIVE -> "lr.id"
SettlementSource.CONTENT_SALES, SettlementSource.CONTENT_DONATION -> "c.id"
SettlementSource.COMMUNITY_POST -> "cc.id"
SettlementSource.CHANNEL_DONATION -> "m.id"
}
private val individual = when (scope.source) {
SettlementSource.LIVE -> "csr.live_settlement_ratio"
SettlementSource.CONTENT_SALES -> "COALESCE(c.settlement_ratio, csr.content_settlement_ratio)"
SettlementSource.COMMUNITY_POST -> "csr.community_settlement_ratio"
SettlementSource.CONTENT_DONATION, SettlementSource.CHANNEL_DONATION -> "NULL"
}
private val sourceFrom = when (scope.source) {
SettlementSource.LIVE -> "use_can uc JOIN live_room lr ON lr.id = uc.room_id JOIN member m ON m.id = lr.member_id"
SettlementSource.CONTENT_SALES -> """
orders o JOIN content c ON c.id = o.content_id JOIN member m ON m.id = c.member_id
LEFT JOIN use_can uc ON uc.order_id = o.id
""".trimIndent()
SettlementSource.CONTENT_DONATION ->
"use_can uc JOIN content c ON c.id = uc.content_id JOIN member m ON m.id = c.member_id"
SettlementSource.COMMUNITY_POST -> """
use_can uc JOIN creator_community cc ON cc.id = uc.creator_community_id
JOIN member m ON m.id = cc.member_id
""".trimIndent()
SettlementSource.CHANNEL_DONATION -> """
use_can_calculate ucc JOIN use_can uc ON uc.id = ucc.use_can_id
JOIN member m ON m.id = ucc.recipient_creator_id
""".trimIndent()
}
private val sourcePredicate = when (scope.source) {
SettlementSource.LIVE -> "uc.is_refund = FALSE"
SettlementSource.CONTENT_SALES -> "o.is_active = TRUE"
SettlementSource.CONTENT_DONATION -> "uc.is_refund = FALSE AND uc.can_usage = 'DONATION'"
SettlementSource.COMMUNITY_POST -> "uc.is_refund = FALSE AND uc.can_usage = 'PAID_COMMUNITY_POST'"
SettlementSource.CHANNEL_DONATION ->
"uc.is_refund = FALSE AND uc.can_usage = 'CHANNEL_DONATION' AND ucc.status = 'RECEIVED'"
}
private val can = when (scope.source) {
SettlementSource.CONTENT_SALES -> "CAST(o.can AS DECIMAL(20, 0))"
SettlementSource.CHANNEL_DONATION -> "CAST(ucc.can AS DECIMAL(20, 0))"
SettlementSource.LIVE, SettlementSource.CONTENT_DONATION, SettlementSource.COMMUNITY_POST ->
"CAST(uc.can AS DECIMAL(20, 0)) + uc.reward_can"
}
val spaces = listOf(
"member",
"use_can",
"creator_settlement_ratio",
"agent_creator_relation",
"agent_settlement_ratio"
) + when (scope.source) {
SettlementSource.LIVE -> listOf("live_room")
SettlementSource.CONTENT_SALES -> listOf("orders", "content")
SettlementSource.CONTENT_DONATION -> listOf("content")
SettlementSource.COMMUNITY_POST -> listOf("creator_community")
SettlementSource.CHANNEL_DONATION -> listOf("use_can_calculate")
}
val inputs: String
init {
val predicates = mutableListOf(sourcePredicate, "$event >= :policyStart")
scope.window.startInclusiveUtc?.let {
predicates.add("$event >= :windowStart")
parameters.addValue("windowStart", Timestamp.valueOf(it))
}
scope.window.endUtc?.let {
predicates.add("$event ${if (scope.window.endExclusive) "<" else "<="} :windowEnd")
parameters.addValue("windowEnd", Timestamp.valueOf(it))
}
scope.creatorId?.let {
predicates.add("m.id = :creatorId")
parameters.addValue("creatorId", it)
}
scope.agentId?.let {
predicates.add("acr.agent_id = :agentId")
parameters.addValue("agentId", it)
}
inputs = """
SELECT m.id AS creator_id, $sourceId AS source_id,
${if (scope.source == SettlementSource.LIVE) "NULL" else day} AS day_kst,
${if (scope.source == SettlementSource.LIVE) "uc.can_usage" else "NULL"} AS can_usage,
${if (sales) "o.type" else "NULL"} AS order_type,
${if (sales) "o.can" else "NULL"} AS order_price,
${if (sales) "CASE WHEN o.point > 0 THEN 1 ELSE 0 END" else "NULL"} AS point_group,
CASE WHEN ($creatorCountry) = ($buyerCountry) THEN 'SAME_COUNTRY' ELSE 'CROSS_COUNTRY' END AS relation,
CASE WHEN ($creatorCountry) <> ($buyerCountry) THEN 50
ELSE COALESCE($individual, CASE WHEN ($creatorCountry) = 'KR' AND $event < :rateEnd
THEN 75 ELSE 70 END) END AS creator_ratio,
acr.agent_id AS agent_id,
CASE WHEN acr.agent_id IS NULL THEN NULL ELSE COALESCE(asr.settlement_ratio, 7) END AS agent_ratio,
acr.id AS assignment_id, asr.id AS ratio_id,
${if (sales) "o.id" else "uc.id"} AS transaction_id,
$can AS can_value, ${if (sales) "CAST(o.point AS DECIMAL(20, 0))" else "0"} AS point_value
FROM $sourceFrom
LEFT JOIN creator_settlement_ratio csr ON csr.member_id = m.id AND csr.deleted_at IS NULL
LEFT JOIN agent_creator_relation acr ON acr.creator_id = m.id
AND acr.assigned_at <= $event AND (acr.unassigned_at IS NULL OR acr.unassigned_at > $event)
LEFT JOIN agent_settlement_ratio asr ON asr.member_id = acr.agent_id
AND asr.effective_from <= $event AND (asr.effective_to IS NULL OR asr.effective_to > $event)
WHERE ${predicates.joinToString(" AND ")}
""".trimIndent()
}
fun columns(grain: SettlementDisplayGrain): List<String> = ECONOMICS + when (grain) {
SettlementDisplayGrain.DETAIL -> SOURCE_GRAIN
SettlementDisplayGrain.CONTENT_CUMULATIVE -> listOf("source_id", "order_type", "order_price", "point_group")
SettlementDisplayGrain.CREATOR, SettlementDisplayGrain.MONTHLY_RATE -> emptyList()
}
fun grouped(filter: String = "1 = 1"): String {
val columns = columns(SettlementDisplayGrain.DETAIL).joinToString(", ")
return """
SELECT $columns, COUNT(DISTINCT transaction_id) AS transaction_count,
SUM(can_value) AS total_can, SUM(point_value) AS total_point
FROM ($inputs) q WHERE $filter GROUP BY $columns
""".trimIndent()
}
fun order(grain: SettlementDisplayGrain): String {
val leading = when (grain) {
SettlementDisplayGrain.CREATOR, SettlementDisplayGrain.MONTHLY_RATE -> "g.creator_id DESC"
SettlementDisplayGrain.CONTENT_CUMULATIVE -> "g.creator_id DESC, g.source_id DESC"
SettlementDisplayGrain.DETAIL -> when (scope.source) {
SettlementSource.LIVE -> "m.nickname DESC, g.source_id DESC, g.can_usage DESC"
SettlementSource.CONTENT_SALES -> "g.creator_id DESC, g.day_kst DESC, g.source_id ASC"
SettlementSource.CONTENT_DONATION, SettlementSource.COMMUNITY_POST ->
"g.creator_id ASC, g.day_kst DESC, g.source_id DESC"
SettlementSource.CHANNEL_DONATION -> "g.day_kst DESC, g.creator_id DESC"
}
}
// Binary token ordering matches the ASCII codec, including numeric prefixes and the null token '~'.
val tokens = columns(grain).map { "CASE WHEN g.$it IS NULL THEN '~' ELSE CONCAT('', g.$it) END" }
val stable = "CAST(CONCAT(${tokens.joinToString(", '|', ")}) AS BINARY(384)) ASC"
return "${if (scope.agentId != null) "g.creator_id DESC" else leading}, $stable"
}
fun descriptionFrom(): String = when (scope.source) {
SettlementSource.LIVE -> "live_room s JOIN member m ON m.id = s.member_id"
SettlementSource.CONTENT_SALES, SettlementSource.CONTENT_DONATION -> "content s JOIN member m ON m.id = s.member_id"
SettlementSource.COMMUNITY_POST -> "creator_community s JOIN member m ON m.id = s.member_id"
SettlementSource.CHANNEL_DONATION -> "member s JOIN member m ON m.id = s.id"
}
fun descriptionFields(): String = when (scope.source) {
SettlementSource.LIVE ->
"s.title, DATE_FORMAT(CONVERT_TZ(s.begin_date_time, 'UTC', 'Asia/Seoul'), '%Y-%m-%d'), NULL, s.price"
SettlementSource.CONTENT_SALES, SettlementSource.CONTENT_DONATION ->
"s.title, NULL, DATE_FORMAT(CONVERT_TZ(s.created_at, 'UTC', 'Asia/Seoul'), '%Y-%m-%d'), s.price"
SettlementSource.COMMUNITY_POST -> "SUBSTRING(s.content, 1, 10), NULL, NULL, s.price"
SettlementSource.CHANNEL_DONATION -> "NULL, NULL, NULL, NULL"
}
companion object {
val ECONOMICS = listOf("creator_id", "relation", "creator_ratio", "agent_id", "agent_ratio")
val SOURCE_GRAIN = listOf("source_id", "day_kst", "can_usage", "order_type", "order_price", "point_group")
}
}
@@ -1,34 +0,0 @@
package kr.co.vividnext.sodalive.v2.settlement.adapter.out.persistence
import com.querydsl.core.types.dsl.CaseBuilder
import com.querydsl.core.types.dsl.DateTimeExpression
import com.querydsl.core.types.dsl.NumberExpression
import com.querydsl.core.types.dsl.StringExpression
import kr.co.vividnext.sodalive.v2.settlement.domain.CountrySettlementPolicy
import org.springframework.stereotype.Component
import java.time.LocalDateTime
@Component
class CountrySettlementExpressions(private val policy: CountrySettlementPolicy) {
fun newPolicyCan(eventAt: DateTimeExpression<LocalDateTime>, can: NumberExpression<Int>): NumberExpression<Int> =
CaseBuilder().`when`(eventAt.goe(policy.effectiveAtUtc)).then(can).otherwise(0).sum().coalesce(0)
fun newPolicyWeightedRatioCan(
eventAt: DateTimeExpression<LocalDateTime>,
can: NumberExpression<Int>,
creatorCountry: StringExpression,
transactionCountry: StringExpression,
individualRatio: NumberExpression<Int>? = null
): NumberExpression<Long> {
val creator = CaseBuilder().`when`(creatorCountry.isNull.or(creatorCountry.trim().eq("")))
.then("KR").otherwise(creatorCountry)
val transaction = CaseBuilder().`when`(transactionCountry.isNull.or(transactionCountry.trim().eq("")))
.then("KR").otherwise(transactionCountry)
val defaultRatio = CaseBuilder()
.`when`(creator.eq("KR").and(eventAt.lt(policy.koreanDefaultRateEndExclusiveUtc))).then(75).otherwise(70)
val sameCountryRatio = individualRatio?.coalesce(defaultRatio) ?: defaultRatio
val ratio = CaseBuilder().`when`(creator.ne(transaction)).then(50).otherwise(sameCountryRatio)
return CaseBuilder().`when`(eventAt.goe(policy.effectiveAtUtc))
.then(can.longValue().multiply(ratio.longValue())).otherwise(0L).sum().coalesce(0L)
}
}
@@ -0,0 +1,55 @@
package kr.co.vividnext.sodalive.v2.settlement.domain
import kr.co.vividnext.sodalive.calculate.channelDonation.ChannelDonationSettlementCalculator
import java.math.BigDecimal
import java.math.RoundingMode
object RateSeparatedSettlementCalculator {
fun calculate(
source: SettlementSource,
totalCan: Long,
appliedSettlementRatio: Int,
appliedAgentSettlementRatio: Int?
): SettlementAmounts {
val (feeRate, taxRate) = when (source) {
SettlementSource.LIVE, SettlementSource.CONTENT_SALES, SettlementSource.COMMUNITY_POST ->
BigDecimal(0.066) to BigDecimal(0.033)
SettlementSource.CONTENT_DONATION -> BigDecimal("0.066") to BigDecimal("0.033")
SettlementSource.CHANNEL_DONATION -> {
val amount = ChannelDonationSettlementCalculator.calculateAtRatio(totalCan, appliedSettlementRatio)
return SettlementAmounts(
totalCan,
amount.krw,
amount.fee,
amount.settlementAmount,
amount.withholdingTax,
amount.depositAmount,
agentAmount(amount.settlementAmount, appliedAgentSettlementRatio)
)
}
}
val gross = BigDecimal(totalCan).multiply(BigDecimal(100))
val settlement = BigDecimal(totalCan).multiply(BigDecimal(appliedSettlementRatio)).multiply(
BigDecimal.ONE.subtract(feeRate)
)
val tax = settlement.multiply(taxRate)
val roundedSettlement = settlement.setScale(0, RoundingMode.HALF_UP).longValueExact()
return SettlementAmounts(
totalCan = totalCan,
grossAmount = gross.longValueExact(),
paymentFee = gross.multiply(feeRate).setScale(0, RoundingMode.HALF_UP).longValueExact(),
settlementAmount = roundedSettlement,
withholdingTax = tax.setScale(0, RoundingMode.HALF_UP).longValueExact(),
depositAmount = settlement.subtract(tax).setScale(0, RoundingMode.HALF_UP).longValueExact(),
agentSettlementAmount = agentAmount(roundedSettlement, appliedAgentSettlementRatio)
)
}
private fun agentAmount(settlementAmount: Long, appliedAgentSettlementRatio: Int?): Long =
if (appliedAgentSettlementRatio == null) {
0
} else {
BigDecimal(settlementAmount).multiply(BigDecimal(appliedAgentSettlementRatio))
.divide(BigDecimal(100), 0, RoundingMode.HALF_UP).longValueExact()
}
}
@@ -0,0 +1,90 @@
package kr.co.vividnext.sodalive.v2.settlement.domain
import kr.co.vividnext.sodalive.can.use.CanUsage
import kr.co.vividnext.sodalive.content.order.OrderType
import java.time.LocalDate
import java.time.LocalDateTime
enum class SettlementSource {
LIVE, CONTENT_SALES, CONTENT_DONATION, COMMUNITY_POST, CHANNEL_DONATION
}
enum class SettlementCountryRelation {
SAME_COUNTRY, CROSS_COUNTRY, LEGACY
}
enum class SettlementDisplayGrain {
DETAIL, CREATOR, CONTENT_CUMULATIVE, MONTHLY_RATE
}
data class SettlementWindow(
val startInclusiveUtc: LocalDateTime?,
val endUtc: LocalDateTime?,
val endExclusive: Boolean
)
data class SettlementScope(
val source: SettlementSource,
val window: SettlementWindow,
val creatorId: Long? = null,
val agentId: Long? = null
)
data class SettlementEconomics(
val countryRelation: SettlementCountryRelation,
val appliedSettlementRatio: Int,
val agentId: Long?,
val appliedAgentSettlementRatio: Int?
)
data class SettlementSourceGrain(
val sourceId: Long,
val dayKst: LocalDate?,
val canUsage: CanUsage?,
val orderType: OrderType?,
val orderPrice: Int?,
val pointGroup: Int?
)
data class SettlementCanonicalKey(
val source: SettlementSource,
val creatorId: Long,
val economics: SettlementEconomics,
val grain: SettlementSourceGrain
)
data class SettlementProvenance(
val assignmentId: Long?,
val agentSettlementRatioId: Long?
)
data class SettlementAmounts(
val totalCan: Long,
val grossAmount: Long,
val paymentFee: Long,
val settlementAmount: Long,
val withholdingTax: Long,
val depositAmount: Long,
val agentSettlementAmount: Long
) {
operator fun plus(other: SettlementAmounts): SettlementAmounts = SettlementAmounts(
Math.addExact(totalCan, other.totalCan),
Math.addExact(grossAmount, other.grossAmount),
Math.addExact(paymentFee, other.paymentFee),
Math.addExact(settlementAmount, other.settlementAmount),
Math.addExact(withholdingTax, other.withholdingTax),
Math.addExact(depositAmount, other.depositAmount),
Math.addExact(agentSettlementAmount, other.agentSettlementAmount)
)
companion object {
val ZERO = SettlementAmounts(0, 0, 0, 0, 0, 0, 0)
}
}
data class CanonicalSettlementRow(
val key: SettlementCanonicalKey,
val transactionCount: Long,
val totalPoint: Long,
val amount: SettlementAmounts
)
@@ -0,0 +1,52 @@
package kr.co.vividnext.sodalive.v2.settlement.domain
object SettlementRowKey {
fun canonical(key: SettlementCanonicalKey): String = display(key, SettlementDisplayGrain.DETAIL)
fun display(key: SettlementCanonicalKey, grain: SettlementDisplayGrain): String {
val sourceGrain = key.grain
val (token, parts) = when (grain) {
SettlementDisplayGrain.DETAIL -> "D" to listOf(
sourceGrain.sourceId.toString(),
sourceGrain.dayKst?.toString(),
sourceGrain.canUsage?.name,
sourceGrain.orderType?.name,
sourceGrain.orderPrice?.toString(),
sourceGrain.pointGroup?.toString()
)
SettlementDisplayGrain.CONTENT_CUMULATIVE -> "U" to listOf(
sourceGrain.sourceId.toString(),
sourceGrain.orderType?.name,
sourceGrain.orderPrice?.toString(),
sourceGrain.pointGroup?.toString()
)
SettlementDisplayGrain.CREATOR -> "C" to emptyList()
SettlementDisplayGrain.MONTHLY_RATE -> "M" to emptyList()
}
return (listOf("rs1", token) + economicsParts(key.source, key.creatorId, key.economics) + parts.map { it ?: "~" })
.joinToString("|")
}
fun creator(source: SettlementSource, creatorId: Long, economics: SettlementEconomics): String =
(listOf("rs1", "C") + economicsParts(source, creatorId, economics)).joinToString("|")
fun monthly(source: SettlementSource, creatorId: Long, economics: SettlementEconomics): String =
(listOf("rs1", "M") + economicsParts(source, creatorId, economics)).joinToString("|")
fun legacy(routeToken: String, identityParts: List<String?>): String {
require(routeToken.matches(Regex("[A-Za-z0-9_-]+")))
require(identityParts.all { it == null || it.matches(Regex("[A-Za-z0-9_:+.\\-]+")) })
return (listOf("lg1", routeToken) + identityParts.map { it ?: "~" }).joinToString("|")
}
fun historicalSnapshot(snapshotId: Long): String = "ss0|$snapshotId"
private fun economicsParts(source: SettlementSource, creatorId: Long, economics: SettlementEconomics): List<String> = listOf(
source.name,
creatorId.toString(),
economics.countryRelation.name,
economics.appliedSettlementRatio.toString(),
economics.agentId?.toString() ?: "~",
economics.appliedAgentSettlementRatio?.toString() ?: "~"
)
}
@@ -0,0 +1,22 @@
package kr.co.vividnext.sodalive.v2.settlement.dto
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementAmounts
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementSourceGrain
data class SettlementDisplayRow(
val metadata: SettlementRateMetadata,
val creatorId: Long,
val sourceGrain: SettlementSourceGrain?,
val transactionCount: Long,
val totalPoint: Long,
val amount: SettlementAmounts,
val description: SettlementRowDescription
)
data class SettlementRowDescription(
val creatorNickname: String,
val title: String?,
val displayDate: String?,
val registrationDate: String?,
val sourcePrice: Int?
)
@@ -0,0 +1,12 @@
package kr.co.vividnext.sodalive.v2.settlement.dto
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementCountryRelation
data class SettlementRateMetadata(
val rowKey: String,
val countryRelation: SettlementCountryRelation?,
val appliedSettlementRatio: Int?,
val agentId: Long?,
val appliedAgentSettlementRatio: Int?,
val rateInfoAvailable: Boolean
)
@@ -22,7 +22,7 @@ import kr.co.vividnext.sodalive.live.room.LiveRoomRepository
import kr.co.vividnext.sodalive.member.Member
import kr.co.vividnext.sodalive.member.MemberRepository
import kr.co.vividnext.sodalive.member.MemberRole
import kr.co.vividnext.sodalive.v2.settlement.adapter.out.persistence.CountrySettlementExpressions
import kr.co.vividnext.sodalive.v2.settlement.adapter.out.persistence.CanonicalSettlementQueryRepository
import kr.co.vividnext.sodalive.v2.settlement.domain.CountrySettlementPolicy
import org.junit.jupiter.api.Assertions.assertAll
import org.junit.jupiter.api.Assertions.assertEquals
@@ -64,7 +64,7 @@ class AdminCalculateQueryRepositoryTest @Autowired constructor(
fun setup() {
repository = AdminCalculateQueryRepository(
queryFactory,
CountrySettlementExpressions(CountrySettlementPolicy())
CanonicalSettlementQueryRepository(entityManager, CountrySettlementPolicy())
)
entityManager.createNativeQuery(
"CREATE ALIAS IF NOT EXISTS DATE_FORMAT FOR 'kr.co.vividnext.sodalive.support.H2MysqlDateFunctions.dateFormat'"
@@ -178,8 +178,8 @@ class AdminCalculateQueryRepositoryTest @Autowired constructor(
}
@Test
@DisplayName("라이브는 한 방에 구정책과 여러 국가가 섞여도 보상캔과 환불 조건 및 페이지를 유지한다")
fun shouldKeepOneLiveGroupAcrossPolicyBoundaryCountriesRewardsAndRefunds() {
@DisplayName("라이브는 신정책 비율별 행을 먼저 페이지하고 구정책 및 보상캔과 환불 조건을 보존한다")
fun shouldPageSplitLiveRatesBeforeLegacyWhileKeepingRewardsAndRefunds() {
// given
val creator = saveMember(null, "creator", MemberRole.CREATOR).apply { countryCode = "KR" }
val buyer = saveMember("buyer@test.com", "buyer", MemberRole.USER).apply { countryCode = "US" }
@@ -201,38 +201,47 @@ class AdminCalculateQueryRepositoryTest @Autowired constructor(
// when
val count = repository.getCalculateLiveTotalCount(startDate, endDate)
val first = repository.getCalculateLive(startDate, endDate, 0, 1).single().toGetCalculateLiveResponse()
val next = repository.getCalculateLive(startDate, endDate, 1, 1)
val rows = repository.getCalculateLive(startDate, endDate, 0, 10).map { it.toGetCalculateLiveResponse() }
val creatorCount = repository.getCalculateLiveByCreatorTotalCount(startDate, endDate)
val creatorRow = repository.getCalculateLiveByCreator(startDate, endDate, 0, 1).single().toGetCalculateByCreator()
val creatorNext = repository.getCalculateLiveByCreator(startDate, endDate, 1, 1)
val creators = repository.getCalculateLiveByCreator(startDate, endDate, 0, 10).map { it.toGetCalculateByCreator() }
// then: 100*100*.934*(.70 + .75 + .50) = 18,213 before independent tax/deposit rounding.
assertEquals(1, count)
assertEquals(3, first.numberOfPeople)
assertEquals(300, first.totalAmount)
assertEquals(emptyList<GetCalculateLiveQueryData>(), next)
assertEquals(1, creatorCount)
assertEquals(emptyList<GetCalculateByCreatorQueryData>(), creatorNext)
assertAll(
{
assertEquals(
listOf(30_000, 1_980, 18_213, 601, 17_612),
listOf(first.totalKrw, first.paymentFee, first.settlementAmount, first.tax, first.depositAmount)
)
},
{
assertEquals(
listOf(300, 18_213, 601, 17_612),
listOf(creatorRow.totalCan, creatorRow.settlementAmount, creatorRow.tax, creatorRow.depositAmount)
)
// then: key ASC within NEW puts CROSS_COUNTRY before SAME_COUNTRY; LEGACY is last.
val expected = listOf(
listOf(100, 10_000, 660, 4_670, 154, 4_516),
listOf(100, 10_000, 660, 7_005, 231, 6_774),
listOf(100, 10_000, 660, 6_538, 216, 6_322)
)
assertEquals(3, count)
assertEquals(3, rows.size)
assertEquals(listOf(1, 1, 1), rows.map { it.numberOfPeople })
assertEquals(
expected,
rows.map { listOf(it.totalAmount, it.totalKrw, it.paymentFee, it.settlementAmount, it.tax, it.depositAmount) }
)
assertEquals(3, creatorCount)
assertEquals(
expected,
creators.map { listOf(it.totalCan, it.totalKrw, it.paymentFee, it.settlementAmount, it.tax, it.depositAmount) }
)
assertEquals(
rows,
(0L..2L).flatMap { offset ->
repository.getCalculateLive(startDate, endDate, offset, 1).map { it.toGetCalculateLiveResponse() }
}
)
assertEquals(
creators,
(0L..2L).flatMap { offset ->
repository.getCalculateLiveByCreator(startDate, endDate, offset, 1).map { it.toGetCalculateByCreator() }
}
)
assertEquals(emptyList<GetCalculateLiveQueryData>(), repository.getCalculateLive(startDate, endDate, 3, 1))
assertEquals(emptyList<GetCalculateByCreatorQueryData>(), repository.getCalculateLiveByCreator(startDate, endDate, 3, 1))
}
@Test
@DisplayName("콘텐츠는 주문 금액과 시각을 유지하고 국가 연결 누락과 분할 결제로 행이나 금액을 바꾸지 않는다")
fun shouldKeepOrderSourceContentOverridesPointsAndPagesAcrossBoundary() {
@DisplayName("콘텐츠 비율별 페이지는 주문 원천과 누락 연결 및 PG 분할과 포인트를 보존한다")
fun shouldSplitContentRatesWhileKeepingOrderSourceOverridesPointsAndPages() {
// given
val creator = saveMember(null, "creator", MemberRole.CREATOR).apply { countryCode = "KR" }
saveRatio(creator, 90)
@@ -278,26 +287,27 @@ class AdminCalculateQueryRepositoryTest @Autowired constructor(
val cumulativeCount = repository.getCumulativeSalesByContentTotalCount()
val cumulativeRows = repository.getCumulativeSalesByContent(0, 10)
val creatorCount = repository.getCalculateContentByCreatorTotalCount(startDate, endDate)
val creatorRow = repository.getCalculateContentByCreator(startDate, endDate, 0, 1).single().toGetCalculateByCreator()
val creatorRows = repository.getCalculateContentByCreator(startDate, endDate, 0, 10).map { it.toGetCalculateByCreator() }
// then: daily new = 7,472 + 4,670 + 7,472; cumulative adds legacy content80, by-creator adds legacy creator90.
assertEquals(3, count)
assertEquals(3, rows.size)
// then: NEW same80 combines two 100-CAN orders; legacy detail80 and creator90 remain distinct.
assertEquals(4, count)
assertEquals(4, rows.size)
assertEquals(1, repository.getCalculateContentList(startDate, endDate, 0, 1).size)
assertEquals(emptyList<GetCalculateContentQueryData>(), repository.getCalculateContentList(startDate, endDate, 3, 1))
assertEquals(2, cumulativeCount)
assertEquals(2, cumulativeRows.size)
assertEquals(emptyList<GetCalculateContentQueryData>(), repository.getCalculateContentList(startDate, endDate, 4, 1))
assertEquals(4, cumulativeCount)
assertEquals(4, cumulativeRows.size)
assertEquals(1, repository.getCumulativeSalesByContent(0, 1).size)
assertEquals(emptyList<GetCumulativeSalesByContentQueryData>(), repository.getCumulativeSalesByContent(2, 1))
assertEquals(1, creatorCount)
assertEquals(emptyList<GetCumulativeSalesByContentQueryData>(), repository.getCumulativeSalesByContent(4, 1))
assertEquals(3, creatorCount)
assertEquals(
emptyList<GetCalculateByCreatorQueryData>(),
repository.getCalculateContentByCreator(startDate, endDate, 1, 1)
repository.getCalculateContentByCreator(startDate, endDate, 3, 1)
)
val oldRow = rows.single { it.saleDate == "2026-10-31" }.toGetCalculateContentResponse()
val newRow = rows.single { it.saleDate == "2026-11-01" && it.totalPoint == 0 }.toGetCalculateContentResponse()
val newRows = rows.filter { it.saleDate == "2026-11-01" && it.totalPoint == 0 }
.map { it.toGetCalculateContentResponse() }
val pointRow = rows.single { it.totalPoint == 100 }.toGetCalculateContentResponse()
val cumulative = cumulativeRows.single { it.totalPoint == 0 }.toCumulativeSalesByContentItem()
val cumulative = cumulativeRows.filter { it.totalPoint == 0 }.map { it.toCumulativeSalesByContentItem() }
val cumulativePoint = cumulativeRows.single { it.totalPoint == 100 }.toCumulativeSalesByContentItem()
assertAll(
{
@@ -308,8 +318,10 @@ class AdminCalculateQueryRepositoryTest @Autowired constructor(
},
{
assertEquals(
listOf(3, 300, 30_000, 1_980, 19_614, 647, 18_967),
newRow.run { listOf(numberOfPeople, totalCan, totalKrw, paymentFee, settlementAmount, tax, depositAmount) }
listOf(listOf(1, 100, 10_000, 660, 4_670, 154, 4_516), listOf(2, 200, 20_000, 1_320, 14_944, 493, 14_451)),
newRows.map { row ->
row.run { listOf(numberOfPeople, totalCan, totalKrw, paymentFee, settlementAmount, tax, depositAmount) }
}
)
},
{
@@ -328,24 +340,28 @@ class AdminCalculateQueryRepositoryTest @Autowired constructor(
},
{
assertEquals(
listOf(4, 400, 40_000, 2_640, 27_086, 894, 26_192),
cumulative.run {
listOf(numberOfPeople, totalCan, totalKrw, paymentFee, settlementAmount, tax, depositAmount)
listOf(
listOf(1, 100, 10_000, 660, 4_670, 154, 4_516),
listOf(2, 200, 20_000, 1_320, 14_944, 493, 14_451),
listOf(1, 100, 10_000, 660, 7_472, 247, 7_225)
),
cumulative.map { row ->
row.run { listOf(numberOfPeople, totalCan, totalKrw, paymentFee, settlementAmount, tax, depositAmount) }
}
)
},
{
assertEquals(
listOf(400, 28_020, 925, 27_095),
listOf(creatorRow.totalCan, creatorRow.settlementAmount, creatorRow.tax, creatorRow.depositAmount)
listOf(listOf(100, 4_670, 154, 4_516), listOf(200, 14_944, 493, 14_451), listOf(100, 8_406, 277, 8_129)),
creatorRows.map { listOf(it.totalCan, it.settlementAmount, it.tax, it.depositAmount) }
)
}
)
}
@Test
@DisplayName("후원과 커뮤니티는 국가로 일별 페이지를 나누지 않고 과거 금액과 환불 및 보상캔을 유지한다")
fun shouldKeepDonationAndCommunityDailyGroupsAndLegacyRounding() {
@DisplayName("후원과 커뮤니티는 국가별 최종 세 행으로 페이지하고 과거 반올림과 환불 및 보상캔을 보존한다")
fun shouldPageDonationAndCommunityRateRowsWithExactLegacyRounding() {
// given
val creator = saveMember(null, "creator", MemberRole.CREATOR).apply { countryCode = "KR" }
val buyer = saveMember("buyer@test.com", "buyer", MemberRole.USER)
@@ -385,42 +401,49 @@ class AdminCalculateQueryRepositoryTest @Autowired constructor(
val donationCount = repository.getCalculateContentDonationListTotalCount(startDate, endDate)
val donation = repository.getCalculateContentDonationList(startDate, endDate, 0, 1)
.single().toGetCalculateContentDonationResponse()
val oldDonation = repository.getCalculateContentDonationList(startDate, endDate, 1, 1)
val sameDonation = repository.getCalculateContentDonationList(startDate, endDate, 1, 1)
.single().toGetCalculateContentDonationResponse()
val oldDonation = repository.getCalculateContentDonationList(startDate, endDate, 2, 1)
.single().toGetCalculateContentDonationResponse()
val communityCount = repository.getCalculateCommunityPostTotalCount(startDate, endDate)
val community = repository.getCalculateCommunityPostList(startDate, endDate, 0, 1)
.single().toGetCalculateCommunityPostResponse()
val oldCommunity = repository.getCalculateCommunityPostList(startDate, endDate, 1, 1)
val sameCommunity = repository.getCalculateCommunityPostList(startDate, endDate, 1, 1)
.single().toGetCalculateCommunityPostResponse()
val oldCommunity = repository.getCalculateCommunityPostList(startDate, endDate, 2, 1)
.single().toGetCalculateCommunityPostResponse()
val creatorCount = repository.getCalculateCommunityByCreatorTotalCount(startDate, endDate)
val creatorRow = repository.getCalculateCommunityByCreator(startDate, endDate, 0, 1).single().toGetCalculateByCreator()
val creatorRows = repository.getCalculateCommunityByCreator(startDate, endDate, 0, 10)
.map { it.toGetCalculateByCreator() }
// then
assertEquals(2, donationCount)
assertEquals(2, communityCount)
assertEquals(3, donationCount)
assertEquals(3, communityCount)
assertEquals("2026-11-01", donation.donationDate)
assertEquals("2026-11-01", community.date)
assertEquals(2, donation.numberOfDonation)
assertEquals(2, community.numberOfPurchase)
assertEquals(1, creatorCount)
assertEquals(1, donation.numberOfDonation)
assertEquals(1, community.numberOfPurchase)
assertEquals(1, sameDonation.numberOfDonation)
assertEquals(1, sameCommunity.numberOfPurchase)
assertEquals(3, creatorCount)
assertEquals(
emptyList<GetCalculateContentDonationQueryData>(),
repository.getCalculateContentDonationList(startDate, endDate, 2, 1)
repository.getCalculateContentDonationList(startDate, endDate, 3, 1)
)
assertEquals(
emptyList<GetCalculateCommunityPostQueryData>(),
repository.getCalculateCommunityPostList(startDate, endDate, 2, 1)
repository.getCalculateCommunityPostList(startDate, endDate, 3, 1)
)
assertAll(
{
assertEquals(
listOf(200, 20_000, 1_320, 11_675, 385, 11_290),
listOf(100, 10_000, 660, 4_670, 154, 4_516),
donation.run { listOf(totalCan, totalKrw, paymentFee, settlementAmount, tax, depositAmount) }
)
},
{
assertEquals(
listOf(200, 20_000, 1_320, 11_675, 385, 11_290),
listOf(100, 10_000, 660, 4_670, 154, 4_516),
community.run { listOf(totalCan, totalKrw, paymentFee, settlementAmount, tax, depositAmount) }
)
},
@@ -438,11 +461,19 @@ class AdminCalculateQueryRepositoryTest @Autowired constructor(
},
{
assertEquals(
listOf(325, 19_847, 655, 19_193),
listOf(creatorRow.totalCan, creatorRow.settlementAmount, creatorRow.tax, creatorRow.depositAmount)
listOf(listOf(100, 4_670, 154, 4_516), listOf(100, 7_005, 231, 6_774), listOf(125, 8_172, 270, 7_903)),
creatorRows.map { listOf(it.totalCan, it.settlementAmount, it.tax, it.depositAmount) }
)
}
)
assertEquals(
listOf(100, 10_000, 660, 7_005, 231, 6_774),
sameDonation.run { listOf(totalCan, totalKrw, paymentFee, settlementAmount, tax, depositAmount) }
)
assertEquals(
listOf(100, 10_000, 660, 7_005, 231, 6_774),
sameCommunity.run { listOf(totalCan, totalKrw, paymentFee, settlementAmount, tax, depositAmount) }
)
}
@Test
@@ -26,6 +26,8 @@ import org.mockito.Mockito.atLeastOnce
import org.mockito.Mockito.mock
import org.mockito.Mockito.verify
import org.mockito.Mockito.`when`
import org.springframework.transaction.PlatformTransactionManager
import org.springframework.transaction.support.SimpleTransactionStatus
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.util.Optional
@@ -38,6 +40,9 @@ class AdminCalculateServiceTest {
private val liveRoomRepository = mock(LiveRoomRepository::class.java)
private val messageSource = mock(SodaMessageSource::class.java)
private val langContext = mock(LangContext::class.java)
private val transactionManager = mock(PlatformTransactionManager::class.java).apply {
`when`(getTransaction(any())).thenReturn(SimpleTransactionStatus())
}
private val adminCalculateService = AdminCalculateService(
repository,
@@ -46,7 +51,8 @@ class AdminCalculateServiceTest {
chargeRepository,
liveRoomRepository,
messageSource,
langContext
langContext,
transactionManager
)
@Test
@@ -0,0 +1,108 @@
package kr.co.vividnext.sodalive.admin.calculate
import com.fasterxml.jackson.databind.JsonNode
import org.apache.poi.ss.usermodel.CellType
import org.apache.poi.ss.usermodel.Row
import org.apache.poi.xssf.usermodel.XSSFWorkbook
import org.junit.jupiter.api.Assertions.assertEquals
import java.io.ByteArrayInputStream
internal data class RateSeparatedCalculateExcelFixture(val headers: List<String>, val fields: List<String>) {
fun assertWorkbook(bytes: ByteArray, rows: List<JsonNode>) {
XSSFWorkbook(ByteArrayInputStream(bytes)).use { workbook ->
val sheet = workbook.getSheetAt(0)
val metadata = listOf("행 식별키", "거래 구분", "크리에이터 정산 비율(%)", "에이전트 번호", "에이전트 정산 비율(%)")
assertEquals(headers + metadata, sheet.getRow(0).map { it.stringCellValue })
assertEquals(rows.size, sheet.lastRowNum)
rows.forEachIndexed { index, api ->
val excel = sheet.getRow(index + 1)
fields.forEachIndexed { column, field -> assertCell(excel, column, api.path(field)) }
val start = fields.size
assertEquals(CellType.STRING, excel.getCell(start).cellType)
assertEquals(api.path("rowKey").asText(), excel.getCell(start).stringCellValue)
val relation = when (api.path("countryRelation").asText()) {
"SAME_COUNTRY" -> "동일 국가"
"CROSS_COUNTRY" -> "다른 국가"
"LEGACY" -> "기존 정책"
else -> "정보 미제공"
}
assertEquals(relation, excel.getCell(start + 1).stringCellValue)
assertCell(excel, start + 2, api.path("appliedSettlementRatio"))
val agent = api.path("agentId")
if (agent.isNull) {
assertEquals(CellType.BLANK, excel.getCell(start + 3, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).cellType)
} else {
assertEquals(CellType.STRING, excel.getCell(start + 3).cellType)
assertEquals(agent.asText(), excel.getCell(start + 3).stringCellValue)
}
assertCell(excel, start + 4, api.path("appliedAgentSettlementRatio"))
}
}
}
private fun assertCell(row: Row, column: Int, expected: JsonNode) {
val cell = row.getCell(column, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK)
when {
expected.isNull -> assertEquals(CellType.BLANK, cell.cellType)
expected.isIntegralNumber -> {
assertEquals(CellType.NUMERIC, cell.cellType)
assertEquals(expected.doubleValue(), cell.numericCellValue)
}
expected.isTextual -> {
assertEquals(CellType.STRING, cell.cellType)
assertEquals(expected.textValue(), cell.stringCellValue)
}
else -> error("Unsupported API cell: $expected")
}
}
companion object {
fun forRoute(route: String): RateSeparatedCalculateExcelFixture = when (route) {
"live" -> RateSeparatedCalculateExcelFixture(
listOf(
"닉네임", "날짜", "라이브 제목", "입장료(캔)", "사용구분", "참여인원", "총 캔", "원화",
"결제수수료", "정산금액", "원천세", "입금액"
),
listOf(
"nickname", "date", "title", "entranceFee", "canUsageStr", "numberOfPeople", "totalAmount", "totalKrw",
"paymentFee", "settlementAmount", "tax", "depositAmount"
)
)
"content-list" -> RateSeparatedCalculateExcelFixture(
listOf(
"크리에이터", "콘텐츠 제목", "등록일", "판매일", "구분", "가격(캔)", "인원", "총 캔", "원화",
"결제수수료", "정산금액", "원천세", "입금액"
),
listOf(
"nickname", "title", "registrationDate", "saleDate", "orderType", "orderPrice", "numberOfPeople",
"totalCan", "totalKrw", "paymentFee", "settlementAmount", "tax", "depositAmount"
)
)
"content-donation-list" -> RateSeparatedCalculateExcelFixture(
listOf(
"크리에이터", "콘텐츠 제목", "유무료", "등록일", "후원일", "후원건수", "총 캔", "원화",
"결제수수료", "정산금액", "원천세", "입금액"
),
listOf(
"nickname", "title", "paidOrFree", "registrationDate", "donationDate", "numberOfDonation", "totalCan",
"totalKrw", "paymentFee", "settlementAmount", "tax", "depositAmount"
)
)
"community-post" -> RateSeparatedCalculateExcelFixture(
listOf(
"크리에이터", "게시글", "날짜", "가격(캔)", "구매건수", "총 캔", "원화",
"결제수수료", "정산금액", "원천세", "입금액"
),
listOf(
"nickname", "title", "date", "can", "numberOfPurchase", "totalCan", "totalKrw",
"paymentFee", "settlementAmount", "tax", "depositAmount"
)
)
"live-by-creator", "content-by-creator", "community-by-creator" -> RateSeparatedCalculateExcelFixture(
listOf("크리에이터 번호", "닉네임", "총 캔", "원화", "결제수수료", "정산금액", "원천세", "입금액"),
listOf("creatorId", "nickname", "totalCan", "totalKrw", "paymentFee", "settlementAmount", "tax", "depositAmount")
)
else -> error("Unknown test route: $route")
}
}
}
@@ -0,0 +1,269 @@
package kr.co.vividnext.sodalive.admin.calculate
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.ObjectMapper
import kr.co.vividnext.sodalive.configs.QueryDslConfig
import kr.co.vividnext.sodalive.jwt.TokenProvider
import kr.co.vividnext.sodalive.member.Member
import kr.co.vividnext.sodalive.member.MemberRole
import kr.co.vividnext.sodalive.member.token.MemberTokenRepository
import kr.co.vividnext.sodalive.support.EmbeddedRedisInitializer
import kr.co.vividnext.sodalive.v2.api.creator.settlement.MonthlySettlementHttpTestSupport
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.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import org.junit.jupiter.params.ParameterizedTest
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.context.annotation.Import
import org.springframework.http.HttpStatus
import org.springframework.test.context.ContextConfiguration
import org.springframework.transaction.support.TransactionTemplate
import java.io.ByteArrayOutputStream
import javax.persistence.EntityManager
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = ["spring.cache.type=none"])
@Import(QueryDslConfig::class)
@ContextConfiguration(initializers = [EmbeddedRedisInitializer::class])
class RateSeparatedCalculateExportIntegrationTest @Autowired constructor(
entityManager: EntityManager,
transactionTemplate: TransactionTemplate,
restTemplate: TestRestTemplate,
objectMapper: ObjectMapper,
tokenProvider: TokenProvider,
private val tokenRepository: MemberTokenRepository,
private val service: AdminCalculateService
) {
private val fixture = RateSeparatedCalculateFixture(entityManager, transactionTemplate)
private val http = MonthlySettlementHttpTestSupport(restTemplate, objectMapper, tokenProvider)
private lateinit var admin: Member
private val query = "?startDateStr=2026-11-01&endDateStr=2026-11-30"
private val moneyFields = listOf("totalCan", "totalKrw", "paymentFee", "settlementAmount", "tax", "depositAmount")
@BeforeEach
fun initialize() {
fixture.initialize()
admin = fixture.commit { member(MemberRole.ADMIN) }
}
@AfterEach
fun cleanup() {
try {
http.removeIssuedTokens(tokenRepository)
} finally {
fixture.cleanup()
}
}
@ParameterizedTest
@ValueSource(
strings = [
"live", "content-list", "content-donation-list", "community-post",
"live-by-creator", "content-by-creator", "community-by-creator"
]
)
@DisplayName("실제 DB의 75/50 및 실제 agent 조건은 최종 페이지와 JSON 및 실제 Excel 셀에서 일치한다")
fun shouldExportFinalEconomicRowsWithTypedMetadataAndExistingColumns(route: String) {
val (creator, firstAgent, secondAgent) = fixture.commit {
val creator = member()
val source = sources(creator)
val first = member(MemberRole.AGENT)
val second = member(MemberRole.AGENT)
assignment(first, creator, effectiveAt.plusHours(1) to effectiveAt.plusHours(3))
assignment(second, creator, effectiveAt.plusHours(3) to effectiveAt.plusHours(4))
agentRatio(first, 10, effectiveAt.plusHours(2) to null)
(0L..4L).forEach { hour ->
spendAll(source, CalculateSpend(effectiveAt.plusHours(hour), if (hour == 4L) "JP" else "KR"))
}
Triple(creator, requireNotNull(first.id), requireNotNull(second.id))
}
val data = http.success(http.get(admin, "/admin/calculate/$route$query&page=0&size=20"))
assertEquals(5, data.path("totalCount").intValue())
val rows = data.path("items").toList()
assertEquals(5, rows.size)
val keys = rows.map { it.path("rowKey").asText() }
assertTrue(keys.all { key -> key.isNotBlank() && key.length <= 384 && key.all { it.code in 32..126 } })
assertEquals(5, keys.toSet().size)
assertEquals(keys.sorted(), keys)
assertEquals(
setOf(
listOf("CROSS_COUNTRY", "50", "null", "null"),
listOf("SAME_COUNTRY", "75", "null", "null"),
listOf("SAME_COUNTRY", "75", "$firstAgent", "7"),
listOf("SAME_COUNTRY", "75", "$firstAgent", "10"),
listOf("SAME_COUNTRY", "75", "$secondAgent", "7")
),
rows.map { row ->
listOf("countryRelation", "appliedSettlementRatio", "agentId", "appliedAgentSettlementRatio")
.map { row.path(it).asText() }
}.toSet()
)
rows.forEach { row ->
listOf(
"rowKey",
"countryRelation",
"appliedSettlementRatio",
"agentId",
"appliedAgentSettlementRatio",
"rateInfoAvailable"
).forEach { assertTrue(row.has(it), "$it: $row") }
assertTrue(row.path("rowKey").isTextual)
assertTrue(row.path("rateInfoAvailable").isBoolean)
assertTrue(row.path("rateInfoAvailable").booleanValue())
assertTrue(row.path("appliedSettlementRatio").isIntegralNumber)
listOf("agentId", "appliedAgentSettlementRatio").forEach { field ->
assertTrue(row.path(field).isNull || row.path(field).isIntegralNumber, "$field: $row")
}
val expected = if (row.path("appliedSettlementRatio").intValue() == 75) {
listOf(1L, 100L, 7L, 70L, 2L, 68L)
} else {
listOf(1L, 100L, 7L, 47L, 2L, 45L)
}
assertEquals(expected, amounts(row, route))
}
assertEquals(
listOf(5L, 500L, 35L, 327L, 10L, 317L),
moneyFields.indices.map { i -> rows.sumOf { amounts(it, route)[i] } }
)
val pages = (0..3).map { page ->
val result = http.success(http.get(admin, "/admin/calculate/$route$query&page=$page&size=2"))
assertEquals(5, result.path("totalCount").intValue())
result.path("items").toList()
}
assertEquals(listOf(2, 2, 1, 0), pages.map { it.size })
assertEquals(rows, pages.flatten())
if (route in listOf("live", "content-list", "content-donation-list", "community-post")) {
val own = http.success(http.get(creator, "/creator-admin/calculate/$route$query&page=0&size=20"))
assertEquals(rows, if (route == "live") own.toList() else own.path("items").toList())
}
val body = when (route) {
"live" -> service.downloadCalculateLiveExcel("2026-11-01", "2026-11-30")
"content-list" -> service.downloadCalculateContentListExcel("2026-11-01", "2026-11-30")
"content-donation-list" -> service.downloadCalculateContentDonationListExcel("2026-11-01", "2026-11-30")
"community-post" -> service.downloadCalculateCommunityPostExcel("2026-11-01", "2026-11-30")
"live-by-creator" -> service.downloadCalculateLiveByCreatorExcel("2026-11-01", "2026-11-30")
"content-by-creator" -> service.downloadCalculateContentByCreatorExcel("2026-11-01", "2026-11-30")
"community-by-creator" -> service.downloadCalculateCommunityByCreatorExcel("2026-11-01", "2026-11-30")
else -> error("Unknown test route: $route")
}
// No surrounding transaction: the returned callback runs after the service call has returned.
val output = ByteArrayOutputStream()
body.writeTo(output)
RateSeparatedCalculateExcelFixture.forRoute(route).assertWorkbook(output.toByteArray(), rows)
}
@Test
@DisplayName("누적과 creator 집계는 이틀의 반올림된 상세 금액을 재반올림 없이 더한다")
fun shouldSumRoundedContentAndCommunityDetailsIntoRollups() {
val creator = fixture.commit {
val creator = member()
val source = sources(creator)
spendAll(source, CalculateSpend(effectiveAt))
spendAll(source, CalculateSpend(effectiveAt.plusDays(1)))
creator
}
val details = adminRows("content-list")
assertEquals(2, details.size)
details.forEach { assertEquals(listOf(1L, 100L, 7L, 70L, 2L, 68L), amounts(it, "content-list")) }
listOf("cumulative-sales-by-content", "content-by-creator", "community-by-creator").forEach { route ->
val rows = adminRows(route)
assertEquals(1, rows.size)
assertEquals(listOf(2L, 200L, 14L, 140L, 4L, 136L), amounts(rows.single(), route))
}
val live = adminRows("live-by-creator")
assertEquals(1, live.size)
assertEquals(listOf(2L, 200L, 13L, 140L, 5L, 135L), amounts(live.single(), "live-by-creator"))
val own = http.success(http.get(creator, "/creator-admin/calculate/cumulative-sales-by-content?page=0&size=20"))
assertEquals(1, own.path("totalCount").intValue())
assertEquals(listOf(2L, 200L, 14L, 140L, 4L, 136L), amounts(own.path("items").single(), "content-list"))
}
@Test
@DisplayName("혼합 기간은 높은 ID의 구정책보다 신정책을 먼저 반환하고 과거 creator70과 콘텐츠80을 보존한다")
fun shouldKeepLegacyContentPrecedenceAndReturnNewRegimeBeforeHigherCreatorId() {
val (current, old) = fixture.commit {
val current = member()
spendAll(sources(current), CalculateSpend(effectiveAt))
val old = member()
legacyRatio(old)
val source = sources(old)
source.content.settlementRatio = 80
spendAll(source, CalculateSpend(effectiveAt.minusSeconds(1), "JP", 100))
current to old
}
val dates = "?startDateStr=2026-10-31&endDateStr=2026-11-01&page=0&size=20"
val details = adminRows("content-list", dates)
val creators = adminRows("content-by-creator", dates)
assertEquals(2, details.size)
assertEquals(2, creators.size)
assertEquals(listOf(current.nickname, old.nickname), details.map { it.path("nickname").asText() })
assertEquals(listOf(current.nickname, old.nickname), creators.map { it.path("nickname").asText() })
assertEquals(listOf("SAME_COUNTRY", "LEGACY"), details.map { it.path("countryRelation").asText() })
assertEquals(listOf(100L, 10_000L, 660L, 7_472L, 247L, 7_225L), amounts(details.last(), "content-list"))
assertEquals(listOf(100L, 10_000L, 660L, 6_538L, 216L, 6_322L), amounts(creators.last(), "content-by-creator"))
}
@ParameterizedTest
@ValueSource(strings = ["live", "content-list", "content-donation-list", "community-post", "cumulative-sales-by-content"])
@DisplayName("기존 creator route는 주입한 소유자 ID를 무시하고 USER 및 ADMIN 역할을 거부한다")
fun shouldKeepCreatorOwnerAndRoleFilters(route: String) {
val (creator, other) = fixture.commit {
val creator = member()
spendAll(sources(creator), CalculateSpend(effectiveAt))
val other = member()
spendAll(sources(other), CalculateSpend(effectiveAt, "KR", 999))
creator to other
}
val path = "/creator-admin/calculate/$route$query&page=0&size=20" +
"&creatorId=${other.id}&memberId=${other.id}&userId=${other.id}"
val data = http.success(http.get(creator, path))
val rows = if (route == "live") data.toList() else data.path("items").toList()
assertEquals(1, rows.size)
assertEquals(listOf(1L, 100L, 7L, 70L, 2L, 68L), amounts(rows.single(), route))
listOf(MemberRole.USER, MemberRole.ADMIN).forEach { role ->
val actor = fixture.commit { member(role) }
http.failure(http.get(actor, path))
}
}
@Test
@DisplayName("일반 관리자 목록과 Excel은 기존 ADMIN 역할 및 미인증 거부를 유지한다")
fun shouldKeepAdminRoleChecksForListsAndExports() {
val creator = fixture.commit { member() }
val user = fixture.commit { member(MemberRole.USER) }
listOf(
"live",
"content-list",
"content-donation-list",
"community-post",
"live-by-creator",
"content-by-creator",
"community-by-creator"
).forEach { route ->
listOf("", "/excel").forEach { suffix ->
val path = "/admin/calculate/$route$suffix$query"
http.failure(http.get(creator, path))
http.failure(http.get(user, path))
}
}
assertEquals(HttpStatus.UNAUTHORIZED, http.get(null, "/admin/calculate/live$query").statusCode)
}
private fun adminRows(route: String, suffix: String = "$query&page=0&size=20"): List<JsonNode> {
val data = http.success(http.get(admin, "/admin/calculate/$route$suffix"))
assertEquals(data.path("totalCount").intValue(), data.path("items").size())
return data.path("items").toList()
}
private fun amounts(row: JsonNode, route: String): List<Long> =
(if (route == "live") listOf("totalAmount") + moneyFields.drop(1) else moneyFields)
.map { field ->
assertTrue(row.path(field).isIntegralNumber, "$field: $row")
row.path(field).longValue()
}
}
@@ -0,0 +1,158 @@
package kr.co.vividnext.sodalive.admin.calculate
import kr.co.vividnext.sodalive.admin.calculate.ratio.CreatorSettlementRatio
import kr.co.vividnext.sodalive.can.use.CanUsage
import kr.co.vividnext.sodalive.can.use.UseCan
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 kr.co.vividnext.sodalive.partner.agent.assignment.AgentCreatorRelation
import kr.co.vividnext.sodalive.partner.agent.ratio.AgentSettlementRatio
import org.hibernate.Session
import org.springframework.transaction.support.TransactionTemplate
import java.time.LocalDateTime
import java.util.UUID
import javax.persistence.EntityManager
internal class RateSeparatedCalculateFixture(
private val entityManager: EntityManager,
private val transactionTemplate: TransactionTemplate
) {
val effectiveAt: LocalDateTime = LocalDateTime.of(2026, 10, 31, 15, 0)
private val created = mutableListOf<BaseEntity>()
private val timestamps = mutableListOf<Pair<BaseEntity, LocalDateTime>>()
fun initialize() = commit {
val database = entityManager.unwrap(Session::class.java).doReturningWork { it.metaData.databaseProductName }
if (database == "H2") {
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: RateSeparatedCalculateFixture.() -> T): T =
requireNotNull(
transactionTemplate.execute {
val result = block()
entityManager.flush()
timestamps.forEach { (entity, at) ->
entityManager.createQuery("update ${entity.javaClass.simpleName} e set e.createdAt = :at where e.id = :id")
.setParameter("at", at)
.setParameter("id", entity.id)
.executeUpdate()
}
entityManager.flush()
entityManager.clear()
timestamps.clear()
result
}
)
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()
timestamps.clear()
}
fun member(role: MemberRole = MemberRole.CREATOR): Member {
val name = "rate-${UUID.randomUUID()}"
return save(Member(email = "$name@test.com", password = "password", nickname = name, role = role, countryCode = "KR"))
}
fun sources(creator: Member): CalculateSources {
val buyer = member(MemberRole.USER)
val room = save(
LiveRoom("rate-live", "notice", effectiveAt, 1, isAdult = false, price = 1).apply { member = creator }
)
val theme = save(AudioContentTheme("rate-theme", "theme.png"))
val content = save(
AudioContent("rate-content", "detail", "ko", price = 1).apply {
member = creator
this.theme = theme
isActive = true
}
)
timestamps.add(content to effectiveAt.minusDays(2))
val post = save(CreatorCommunity("rate-post-content", 1, true, false).apply { member = creator })
return CalculateSources(creator, buyer, room, content, post)
}
fun spendAll(source: CalculateSources, spend: CalculateSpend) {
val order = save(
Order(OrderType.KEEP).apply {
member = source.buyer
creator = source.creator
audioContent = source.content
can = spend.can
}
)
timestamps.add(order to spend.at)
listOf(
UseCan(CanUsage.LIVE, spend.can, 0, countryCode = spend.country).apply { room = source.room },
UseCan(CanUsage.ORDER_CONTENT, 1, 0, countryCode = spend.country).apply { this.order = order },
UseCan(CanUsage.DONATION, spend.can, 0, countryCode = spend.country).apply { audioContent = source.content },
UseCan(CanUsage.PAID_COMMUNITY_POST, spend.can, 0, countryCode = spend.country).apply { communityPost = source.post }
).forEach { use ->
use.member = source.buyer
save(use)
timestamps.add(use to spend.at)
}
}
fun assignment(agent: Member, creator: Member, window: Pair<LocalDateTime, LocalDateTime?>) {
save(
AgentCreatorRelation().apply {
this.agent = agent
this.creator = creator
assignedAt = window.first
unassignedAt = window.second
}
)
}
fun agentRatio(agent: Member, ratio: Int, window: Pair<LocalDateTime, LocalDateTime?>) {
save(
AgentSettlementRatio(ratio, window.first).apply {
member = agent
effectiveTo = window.second
}
)
}
fun legacyRatio(creator: Member) {
save(CreatorSettlementRatio(0, 70, 70, 70).apply { member = creator })
}
private fun <T : BaseEntity> save(entity: T): T {
entityManager.persist(entity)
created.add(entity)
return entity
}
}
internal data class CalculateSources(
val creator: Member,
val buyer: Member,
val room: LiveRoom,
val content: AudioContent,
val post: CreatorCommunity
)
internal data class CalculateSpend(val at: LocalDateTime, val country: String = "KR", val can: Int = 1)
@@ -12,7 +12,7 @@ import kr.co.vividnext.sodalive.configs.QueryDslConfig
import kr.co.vividnext.sodalive.member.Member
import kr.co.vividnext.sodalive.member.MemberRepository
import kr.co.vividnext.sodalive.member.MemberRole
import kr.co.vividnext.sodalive.v2.settlement.adapter.out.persistence.CountrySettlementExpressions
import kr.co.vividnext.sodalive.v2.settlement.adapter.out.persistence.CanonicalSettlementQueryRepository
import kr.co.vividnext.sodalive.v2.settlement.domain.CountrySettlementPolicy
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.BeforeEach
@@ -21,6 +21,7 @@ import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest
import org.springframework.context.annotation.Import
import org.springframework.transaction.PlatformTransactionManager
import java.time.LocalDateTime
import javax.persistence.EntityManager
@@ -31,7 +32,8 @@ class AdminChannelDonationCalculateQueryRepositoryTest @Autowired constructor(
private val memberRepository: MemberRepository,
private val useCanRepository: UseCanRepository,
private val useCanCalculateRepository: UseCanCalculateRepository,
private val entityManager: EntityManager
private val entityManager: EntityManager,
private val transactionManager: PlatformTransactionManager
) {
private lateinit var repository: AdminChannelDonationCalculateQueryRepository
@@ -40,7 +42,8 @@ class AdminChannelDonationCalculateQueryRepositoryTest @Autowired constructor(
registerMysqlDateFunctions()
repository = AdminChannelDonationCalculateQueryRepository(
queryFactory,
CountrySettlementExpressions(CountrySettlementPolicy())
CanonicalSettlementQueryRepository(entityManager, CountrySettlementPolicy()),
CountrySettlementPolicy()
)
}
@@ -133,6 +136,63 @@ class AdminChannelDonationCalculateQueryRepositoryTest @Autowired constructor(
assertEquals(70, items[1].totalCan)
}
@Test
@DisplayName("같은 날 75와 50 행을 페이지하고 전체 금액은 분리행 68과 91의 합 159를 반환한다")
fun shouldPageRateRowsAndKeepGlobalMoneyInBothAdminViews() {
val fixture = ChannelSettlementTestFixture(entityManager)
fixture.seedCountryRates()
val service = AdminChannelDonationCalculateService(repository, transactionManager)
val dates = (0L..2L).map { channelJson(service.getChannelDonationByDate("2026-11-02", "2026-11-02", it, 1)) }
val creators = (0L..2L).map { channelJson(service.getChannelDonationByCreator("2026-11-02", "2026-11-02", it, 1)) }
listOf(dates, creators).forEach { pages ->
pages.forEach { page ->
assertEquals(2, page.path("totalCount").intValue())
assertEquals(
channelJson(GetAdminChannelDonationSettlementTotal(2, 3, 300, 20, 164, 5, 159)),
page.path("total")
)
}
val items = pages.flatMap { it.path("items").toList() }
assertEquals(listOf(50, 75), items.map { it.path("appliedSettlementRatio").intValue() })
assertEquals(listOf("CROSS_COUNTRY", "SAME_COUNTRY"), items.map { it.path("countryRelation").asText() })
assertEquals(listOf(91, 68), items.map { it.path("depositAmount").intValue() })
assertEquals(listOf(1, 1), items.map { it.path("count").intValue() })
assertEquals(listOf(2, 1), items.map { it.path("totalCan").intValue() })
assertEquals(0, pages[2].path("items").size())
assertEquals(2, items.map { it.path("rowKey").asText() }.toSet().size)
items.forEach { item ->
assertEquals(true, item.path("rowKey").isTextual)
assertEquals(false, item.path("rowKey").asText().isEmpty())
assertEquals(true, item.path("rateInfoAvailable").booleanValue())
assertEquals(true, item.path("appliedSettlementRatio").isIntegralNumber)
assertEquals(true, item.path("agentId").isNull)
assertEquals(true, item.path("appliedAgentSettlementRatio").isNull)
}
}
}
@Test
@DisplayName("공유 UseCan 한 건의 PG 분할과 두 수신자는 표시행 2개이며 관리자 전체 건수는 1이다")
fun shouldCountSharedUseCanOnceAcrossRecipientAndGatewayRows() {
ChannelSettlementTestFixture(entityManager).seedSharedDonation()
val at = LocalDateTime.of(2026, 11, 2, 0, 0)
val until = at.plusDays(1)
val total = GetAdminChannelDonationSettlementTotal(1, 5, 500, 33, 350, 12, 338)
assertEquals(total, repository.getChannelDonationByDateTotal(at, until).toResponseTotal())
assertEquals(total, repository.getChannelDonationByCreatorTotal(at, until).toResponseTotal())
assertEquals(2, repository.getChannelDonationByDateTotalCount(at, until))
assertEquals(2, repository.getChannelDonationByCreatorTotalCount(at, until))
val dates = repository.getChannelDonationByDate(at, until, 0, 20).map { it.toResponseItem() }
val creators = repository.getChannelDonationByCreator(at, until, 0, 20).map { it.toResponseItem() }
assertEquals(listOf("rate-other", "rate-creator"), dates.map { it.creator })
assertEquals(listOf(1, 1), dates.map { it.count })
assertEquals(listOf(3, 2), dates.map { it.totalCan })
assertEquals(listOf(203, 135), dates.map { it.depositAmount })
assertEquals(dates.map { it.depositAmount }, creators.map { it.depositAmount })
}
private fun saveMember(nickname: String, role: MemberRole): Member {
return memberRepository.saveAndFlush(
Member(
@@ -7,6 +7,8 @@ import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import org.mockito.Mockito
import org.springframework.transaction.PlatformTransactionManager
import org.springframework.transaction.support.SimpleTransactionStatus
import java.io.ByteArrayOutputStream
class AdminChannelDonationCalculateServiceTest {
@@ -16,7 +18,9 @@ class AdminChannelDonationCalculateServiceTest {
@BeforeEach
fun setup() {
repository = Mockito.mock(AdminChannelDonationCalculateQueryRepository::class.java)
service = AdminChannelDonationCalculateService(repository)
val transactionManager = Mockito.mock(PlatformTransactionManager::class.java)
Mockito.`when`(transactionManager.getTransaction(Mockito.any())).thenReturn(SimpleTransactionStatus())
service = AdminChannelDonationCalculateService(repository, transactionManager)
}
@Test
@@ -9,7 +9,7 @@ import kr.co.vividnext.sodalive.can.use.UseCanCalculateStatus
import kr.co.vividnext.sodalive.configs.QueryDslConfig
import kr.co.vividnext.sodalive.member.Member
import kr.co.vividnext.sodalive.member.MemberRole
import kr.co.vividnext.sodalive.v2.settlement.adapter.out.persistence.CountrySettlementExpressions
import kr.co.vividnext.sodalive.v2.settlement.adapter.out.persistence.CanonicalSettlementQueryRepository
import kr.co.vividnext.sodalive.v2.settlement.domain.CountrySettlementPolicy
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.BeforeEach
@@ -51,7 +51,8 @@ class AdminChannelDonationCountryPolicyRepositoryTest @Autowired constructor(
).executeUpdate()
repository = AdminChannelDonationCalculateQueryRepository(
queryFactory,
CountrySettlementExpressions(CountrySettlementPolicy())
CanonicalSettlementQueryRepository(entityManager, CountrySettlementPolicy()),
CountrySettlementPolicy()
)
sender = saveMember("sender", "US", MemberRole.USER)
}
@@ -84,35 +85,36 @@ class AdminChannelDonationCountryPolicyRepositoryTest @Autowired constructor(
}
@Test
@DisplayName("정책 전후 한 캔씩은 크리에이터와 전체 집계를 유지하고 일별 금액의 합으로 대체하지 않는다")
fun shouldKeepMixedPolicyCreatorAndWholePeriodRoundingGrain() {
@DisplayName("정책 혼합 기간은 시행 전 금액과 시행 후 분리행 금액을 합하고 신정책 행부터 페이지한다")
fun shouldSumPreservedLegacyAndNewPolicyRows() {
val creator = saveMember("creator", "KR")
saveCalculation(creator, saveUsage(UseCan(CanUsage.CHANNEL_DONATION, 1, 0, countryCode = "KR"), start))
saveCalculation(creator, saveUsage(UseCan(CanUsage.CHANNEL_DONATION, 1, 0, countryCode = "KR"), boundary))
entityManager.flush()
entityManager.clear()
val expectedTotal = GetAdminChannelDonationSettlementTotal(2, 2, 200, 13, 150, 5, 145)
val expectedCreator = GetAdminChannelDonationSettlementByCreatorItem("creator", 2, 2, 200, 13, 150, 5, 145)
val expectedTotal = GetAdminChannelDonationSettlementTotal(2, 2, 200, 14, 149, 5, 144)
val newCreator = GetAdminChannelDonationSettlementByCreatorItem("creator", 1, 1, 100, 7, 70, 2, 68)
val legacyCreator = GetAdminChannelDonationSettlementByCreatorItem("creator", 1, 1, 100, 7, 79, 3, 76)
assertEquals(expectedTotal, repository.getChannelDonationByDateTotal(start, end).toResponseTotal())
assertEquals(expectedTotal, repository.getChannelDonationByCreatorTotal(start, end).toResponseTotal())
assertEquals(
listOf(expectedCreator),
repository.getChannelDonationByCreator(start, end, 0, 1).map { it.toResponseItem() }
listOf(newCreator),
repository.getChannelDonationByCreator(start, end, 0, 1).map { it.toResponseItem().financialColumns() }
)
assertEquals(
listOf(expectedCreator),
repository.getChannelDonationByCreatorForExcel(start, end).map { it.toResponseItem() }
listOf(newCreator, legacyCreator),
repository.getChannelDonationByCreatorForExcel(start, end).map { it.toResponseItem().financialColumns() }
)
assertEquals(1, repository.getChannelDonationByCreatorTotalCount(start, end))
assertEquals(2, repository.getChannelDonationByCreatorTotalCount(start, end))
assertEquals(2, repository.getChannelDonationByDateTotalCount(start, end))
assertEquals(
listOf(GetAdminChannelDonationSettlementItem("2026-11-01", "creator", 1, 1, 100, 7, 70, 2, 68)),
repository.getChannelDonationByDate(start, end, 0, 1).map { it.toResponseItem() }
repository.getChannelDonationByDate(start, end, 0, 1).map { it.toResponseItem().financialColumns() }
)
assertEquals(
listOf(GetAdminChannelDonationSettlementItem("2026-10-31", "creator", 1, 1, 100, 7, 79, 3, 76)),
repository.getChannelDonationByDate(start, end, 1, 1).map { it.toResponseItem() }
repository.getChannelDonationByDate(start, end, 1, 1).map { it.toResponseItem().financialColumns() }
)
assertEquals(
emptyList<GetAdminChannelDonationSettlementQueryData>(),
@@ -121,8 +123,8 @@ class AdminChannelDonationCountryPolicyRepositoryTest @Autowired constructor(
}
@Test
@DisplayName("여러 국가와 PG 분할 및 수신자가 섞여도 관리자 행과 페이지 및 후원 건수는 늘어나지 않는다")
fun shouldKeepRecipientAllocationsAndDistinctCountsWithoutCountryRows() {
@DisplayName("국가별 표시행은 분리하고 PG 분할과 수신자 공유의 전체 후원 건수 및 원천 필터는 보존한다")
fun shouldSeparateCountryRowsAndKeepRecipientDistinctCounts() {
val korean = saveMember("korean", "KR")
val japanese = saveMember("japanese", "JP")
val shared = saveUsage(UseCan(CanUsage.CHANNEL_DONATION, 5, 0, countryCode = "KR"), boundary)
@@ -143,26 +145,31 @@ class AdminChannelDonationCountryPolicyRepositoryTest @Autowired constructor(
entityManager.flush()
entityManager.clear()
val expectedTotal = GetAdminChannelDonationSettlementTotal(2, 6, 600, 40, 327, 11, 316)
val expectedTotal = GetAdminChannelDonationSettlementTotal(2, 6, 600, 40, 327, 12, 315)
assertEquals(expectedTotal, repository.getChannelDonationByDateTotal(start, end).toResponseTotal())
assertEquals(expectedTotal, repository.getChannelDonationByCreatorTotal(start, end).toResponseTotal())
assertEquals(2, repository.getChannelDonationByDateTotalCount(start, end))
assertEquals(2, repository.getChannelDonationByCreatorTotalCount(start, end))
assertEquals(3, repository.getChannelDonationByDateTotalCount(start, end))
assertEquals(3, repository.getChannelDonationByCreatorTotalCount(start, end))
assertEquals(
listOf(
GetAdminChannelDonationSettlementItem("2026-11-01", "japanese", 1, 3, 300, 20, 140, 5, 135),
GetAdminChannelDonationSettlementItem("2026-11-01", "korean", 2, 3, 300, 20, 187, 6, 181)
GetAdminChannelDonationSettlementItem("2026-11-01", "korean", 1, 1, 100, 7, 47, 2, 45),
GetAdminChannelDonationSettlementItem("2026-11-01", "korean", 1, 2, 200, 13, 140, 5, 135)
),
repository.getChannelDonationByDate(start, end, 0, 20).map { it.toResponseItem() }
repository.getChannelDonationByDate(start, end, 0, 20).map { it.toResponseItem().financialColumns() }
)
val expectedPage = listOf(GetAdminChannelDonationSettlementByCreatorItem("korean", 1, 1, 100, 7, 47, 2, 45))
assertEquals(
expectedPage,
repository.getChannelDonationByCreator(start, end, 1, 1).map { it.toResponseItem().financialColumns() }
)
val expectedPage = listOf(GetAdminChannelDonationSettlementByCreatorItem("korean", 2, 3, 300, 20, 187, 6, 181))
assertEquals(expectedPage, repository.getChannelDonationByCreator(start, end, 1, 1).map { it.toResponseItem() })
assertEquals(
listOf(
GetAdminChannelDonationSettlementByCreatorItem("japanese", 1, 3, 300, 20, 140, 5, 135),
GetAdminChannelDonationSettlementByCreatorItem("korean", 2, 3, 300, 20, 187, 6, 181)
GetAdminChannelDonationSettlementByCreatorItem("korean", 1, 1, 100, 7, 47, 2, 45),
GetAdminChannelDonationSettlementByCreatorItem("korean", 1, 2, 200, 13, 140, 5, 135)
),
repository.getChannelDonationByCreatorForExcel(start, end).map { it.toResponseItem() }
repository.getChannelDonationByCreatorForExcel(start, end).map { it.toResponseItem().financialColumns() }
)
}
@@ -184,11 +191,19 @@ class AdminChannelDonationCountryPolicyRepositoryTest @Autowired constructor(
assertEquals(sourceCount, repository.getChannelDonationByCreatorTotalCount(start, end))
assertEquals(
List(sourceCount) { GetAdminChannelDonationSettlementItem("2026-11-01", "creator", 1, 0, 0, 0, 0, 0, 0) },
repository.getChannelDonationByDate(start, end, 0, 20).map { it.toResponseItem() }
repository.getChannelDonationByDate(start, end, 0, 20).map { it.toResponseItem().financialColumns() }
)
val creators = List(sourceCount) { GetAdminChannelDonationSettlementByCreatorItem("creator", 1, 0, 0, 0, 0, 0, 0) }
assertEquals(creators, repository.getChannelDonationByCreator(start, end, 0, 20).map { it.toResponseItem() })
assertEquals(creators, repository.getChannelDonationByCreatorForExcel(start, end).map { it.toResponseItem() })
assertEquals(
creators,
repository.getChannelDonationByCreator(start, end, 0, 20)
.map { it.toResponseItem().financialColumns() }
)
assertEquals(
creators,
repository.getChannelDonationByCreatorForExcel(start, end)
.map { it.toResponseItem().financialColumns() }
)
}
private fun saveMember(nickname: String, country: String?, role: MemberRole = MemberRole.CREATOR): Member {
@@ -0,0 +1,156 @@
package kr.co.vividnext.sodalive.admin.calculate.channelDonation
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
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.creator.admin.calculate.channelDonation.GetCreatorChannelDonationSettlementItem
import kr.co.vividnext.sodalive.member.Member
import kr.co.vividnext.sodalive.member.MemberRole
import kr.co.vividnext.sodalive.partner.agent.assignment.AgentCreatorRelation
import kr.co.vividnext.sodalive.partner.agent.ratio.AgentSettlementRatio
import java.time.LocalDateTime
import javax.persistence.EntityManager
class ChannelSettlementTestFixture(private val entityManager: EntityManager) {
private val members = mutableListOf<Member>()
private val usages = mutableListOf<UseCan>()
val eventAt: LocalDateTime = LocalDateTime.of(2026, 11, 2, 3, 0)
val creator: Member = member("rate-creator", MemberRole.CREATOR)
private val sender = member("rate-sender", MemberRole.USER)
fun seedCountryRates() {
allocation(creator, usage(1, "KR", eventAt), 1)
allocation(creator, usage(2, "JP", eventAt.plusSeconds(1)), 2)
flush()
}
fun seedSharedDonation() {
val other = member("rate-other", MemberRole.CREATOR)
val shared = usage(5, "KR", eventAt)
allocation(creator, shared, 1)
val google = UseCanCalculate(1, PaymentGateway.GOOGLE_IAP, UseCanCalculateStatus.RECEIVED)
google.useCan = shared
google.recipientCreatorId = creator.id
entityManager.persist(google)
allocation(other, shared, 3)
flush()
}
fun seedAgentRates(secondRate: Int): Long {
val agent = member("rate-agent", MemberRole.AGENT)
val cut = eventAt.plusHours(1)
entityManager.persist(
AgentCreatorRelation().apply {
this.agent = agent
creator = this@ChannelSettlementTestFixture.creator
assignedAt = eventAt.minusDays(1)
unassignedAt = cut
}
)
entityManager.persist(
AgentCreatorRelation().apply {
this.agent = agent
creator = this@ChannelSettlementTestFixture.creator
assignedAt = cut
}
)
entityManager.persist(
AgentSettlementRatio(7, eventAt.minusDays(1)).apply {
member = agent
effectiveTo = cut
}
)
entityManager.persist(AgentSettlementRatio(secondRate, cut).apply { member = agent })
allocation(creator, usage(1, "KR", eventAt), 1)
allocation(creator, usage(3, "KR", cut), 3)
flush()
return requireNotNull(agent.id)
}
fun seedLegacyDays() {
allocation(creator, usage(1, "KR", LocalDateTime.of(2026, 10, 29, 15, 0)), 1)
allocation(creator, usage(1, "JP", LocalDateTime.of(2026, 10, 30, 15, 0)), 1)
flush()
}
fun deleteOwnedRows() {
val usageIds = usages.map { requireNotNull(it.id) }
if (usageIds.isNotEmpty()) {
entityManager.createQuery("delete from UseCanCalculate c where c.useCan.id in :ids")
.setParameter("ids", usageIds).executeUpdate()
entityManager.createQuery("delete from UseCan u where u.id in :ids")
.setParameter("ids", usageIds).executeUpdate()
}
val memberIds = members.map { requireNotNull(it.id) }
entityManager.createQuery("delete from AgentCreatorRelation r where r.creator.id in :ids")
.setParameter("ids", memberIds).executeUpdate()
entityManager.createQuery("delete from AgentSettlementRatio r where r.member.id in :ids")
.setParameter("ids", memberIds).executeUpdate()
entityManager.createQuery("delete from Member m where m.id in :ids")
.setParameter("ids", memberIds).executeUpdate()
entityManager.clear()
}
private fun member(nickname: String, role: MemberRole): Member {
val member = Member("$nickname@test.com", "password", nickname, role = role, countryCode = "KR")
entityManager.persist(member)
members.add(member)
return member
}
private fun usage(can: Int, country: String, at: LocalDateTime): UseCan {
val usage = UseCan(CanUsage.CHANNEL_DONATION, can, 0, countryCode = country)
usage.member = sender
entityManager.persist(usage)
usages.add(usage)
entityManager.flush()
entityManager.createQuery("update UseCan u set u.createdAt = :at where u.id = :id")
.setParameter("at", at).setParameter("id", usage.id).executeUpdate()
return usage
}
private fun allocation(creator: Member, usage: UseCan, can: Int) {
entityManager.persist(
UseCanCalculate(can, PaymentGateway.PG, UseCanCalculateStatus.RECEIVED).apply {
useCan = usage
recipientCreatorId = creator.id
}
)
}
private fun flush() {
entityManager.flush()
entityManager.clear()
}
}
private val channelTestObjectMapper = jacksonObjectMapper()
fun <T> channelJson(value: T): JsonNode = channelTestObjectMapper.readTree(channelTestObjectMapper.writeValueAsString(value))
// Preserve every existing financial/description assertion; metadata has separate JSON/workbook assertions.
fun GetAdminChannelDonationSettlementItem.financialColumns(): GetAdminChannelDonationSettlementItem =
GetAdminChannelDonationSettlementItem(
date, creator, count, totalCan, krw, fee, settlementAmount, withholdingTax, depositAmount
)
fun GetAdminChannelDonationSettlementByCreatorItem.financialColumns(): GetAdminChannelDonationSettlementByCreatorItem =
GetAdminChannelDonationSettlementByCreatorItem(
creator,
count,
totalCan,
krw,
fee,
settlementAmount,
withholdingTax,
depositAmount
)
fun GetCreatorChannelDonationSettlementItem.financialColumns(): GetCreatorChannelDonationSettlementItem =
GetCreatorChannelDonationSettlementItem(
date, creator, count, totalCan, krw, fee, settlementAmount, withholdingTax, depositAmount
)
@@ -0,0 +1,230 @@
package kr.co.vividnext.sodalive.admin.calculate.channelDonation
import com.fasterxml.jackson.databind.JsonNode
import kr.co.vividnext.sodalive.configs.QueryDslConfig
import kr.co.vividnext.sodalive.v2.settlement.adapter.config.CountrySettlementConfiguration
import kr.co.vividnext.sodalive.v2.settlement.adapter.out.persistence.CanonicalSettlementQueryRepository
import org.apache.poi.ss.usermodel.CellType
import org.apache.poi.ss.usermodel.Row
import org.apache.poi.xssf.usermodel.XSSFWorkbook
import org.junit.jupiter.api.AfterEach
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.CsvSource
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest
import org.springframework.context.annotation.Import
import org.springframework.transaction.PlatformTransactionManager
import org.springframework.transaction.annotation.Propagation
import org.springframework.transaction.annotation.Transactional
import org.springframework.transaction.support.TransactionTemplate
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import javax.persistence.EntityManager
@DataJpaTest(
properties = [
"spring.cache.type=none",
"spring.jpa.database-platform=kr.co.vividnext.sodalive.support.H2MySqlFunctionDialect"
]
)
@Import(
QueryDslConfig::class,
CountrySettlementConfiguration::class,
CanonicalSettlementQueryRepository::class,
AdminChannelDonationCalculateQueryRepository::class,
AdminChannelDonationCalculateService::class
)
@Transactional(propagation = Propagation.NOT_SUPPORTED)
class RateSeparatedChannelExportIntegrationTest @Autowired constructor(
private val entityManager: EntityManager,
private val service: AdminChannelDonationCalculateService,
transactionManager: PlatformTransactionManager
) {
private val transaction = TransactionTemplate(transactionManager)
private lateinit var fixture: ChannelSettlementTestFixture
@BeforeEach
fun setup() {
transaction.executeWithoutResult {
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()
fixture = ChannelSettlementTestFixture(entityManager)
}
}
@AfterEach
fun cleanup() {
transaction.executeWithoutResult { fixture.deleteOwnedRows() }
}
@ParameterizedTest
@CsvSource(
"false, COUNTRY_RATES",
"true, COUNTRY_RATES",
"false, SAME_AGENT_HISTORY",
"true, SAME_AGENT_HISTORY",
"false, AGENT_RATE_CHANGE",
"true, AGENT_RATE_CHANGE"
)
@DisplayName("실제 두 관리자 XLSX는 목록과 같은 행 및 전체 금액과 숫자 비율 및 문자열 agent ID를 내보낸다")
fun shouldExportListRowsAndTypedMetadataWithoutAnAmbientTransaction(byCreator: Boolean, case: ExportCase) {
val agentId = transaction.execute {
when (case) {
ExportCase.COUNTRY_RATES -> {
fixture.seedCountryRates()
null
}
ExportCase.SAME_AGENT_HISTORY -> fixture.seedAgentRates(7)
ExportCase.AGENT_RATE_CHANGE -> fixture.seedAgentRates(10)
}
}
val expectedTotal = when (case) {
ExportCase.COUNTRY_RATES -> GetAdminChannelDonationSettlementTotal(2, 3, 300, 20, 164, 5, 159)
ExportCase.SAME_AGENT_HISTORY -> GetAdminChannelDonationSettlementTotal(2, 4, 400, 26, 281, 9, 272)
ExportCase.AGENT_RATE_CHANGE -> GetAdminChannelDonationSettlementTotal(2, 4, 400, 27, 280, 9, 271)
}
val list = readList(byCreator, 0, 20)
val firstPage = readList(byCreator, 0, 1)
val expectedCount = when (case) {
ExportCase.COUNTRY_RATES, ExportCase.AGENT_RATE_CHANGE -> 2
ExportCase.SAME_AGENT_HISTORY -> 1
}
assertEquals(expectedCount, list.path("totalCount").intValue())
assertEquals(channelJson(expectedTotal), list.path("total"))
assertEquals(channelJson(expectedTotal), firstPage.path("total"))
assertEquals(1, firstPage.path("items").size())
assertEquals(expectedCount, list.path("items").size())
val secondPage = readList(byCreator, 1, 1)
assertEquals(channelJson(expectedTotal), secondPage.path("total"))
assertEquals(
list.path("items").toList(),
firstPage.path("items").toList() + secondPage.path("items").toList()
)
val expectedDeposits = when (case) {
ExportCase.COUNTRY_RATES -> listOf(68, 91)
ExportCase.SAME_AGENT_HISTORY -> listOf(272)
ExportCase.AGENT_RATE_CHANGE -> listOf(68, 203)
}
assertEquals(expectedDeposits, list.path("items").map { it.path("depositAmount").intValue() }.sorted())
val body = if (byCreator) {
service.downloadChannelDonationByCreatorExcel("2026-11-02", "2026-11-02")
} else {
service.downloadChannelDonationByDateExcel("2026-11-02", "2026-11-02")
}
val bytes = ByteArrayOutputStream().use { output ->
body.writeTo(output)
output.toByteArray()
}
XSSFWorkbook(ByteArrayInputStream(bytes)).use { workbook ->
val sheet = workbook.getSheetAt(0)
val existingHeaders = if (byCreator) {
listOf("크리에이터", "건수", "총 받은 캔 수", "원화", "수수료", "정산금액", "원천세", "입금액")
} else {
listOf("날짜", "크리에이터", "건수", "총 받은 캔 수", "원화", "수수료", "정산금액", "원천세", "입금액")
}
val metadataHeaders = listOf("행 식별키", "거래 구분", "크리에이터 정산 비율(%)", "에이전트 번호", "에이전트 정산 비율(%)")
val header = sheet.getRow(0)
assertEquals(
existingHeaders + metadataHeaders,
(0 until header.lastCellNum.toInt()).map { header.getCell(it).stringCellValue }
)
assertEquals(expectedCount, sheet.lastRowNum)
val fields = if (byCreator) {
listOf("creator", "count", "totalCan", "krw", "fee", "settlementAmount", "withholdingTax", "depositAmount")
} else {
listOf(
"date", "creator", "count", "totalCan", "krw", "fee", "settlementAmount", "withholdingTax", "depositAmount"
)
}
val metadataStart = fields.size
list.path("items").forEachIndexed { index, item ->
val row = sheet.getRow(index + 1)
fields.forEachIndexed { column, field ->
val cell = row.getCell(column)
when (field) {
"date", "creator" -> {
assertEquals(CellType.STRING, cell.cellType)
assertEquals(item.path(field).asText(), cell.stringCellValue)
}
else -> {
assertEquals(CellType.NUMERIC, cell.cellType)
assertEquals(item.path(field).doubleValue(), cell.numericCellValue)
}
}
}
assertEquals(CellType.STRING, row.getCell(metadataStart).cellType)
assertEquals(item.path("rowKey").asText(), row.getCell(metadataStart).stringCellValue)
val relation = when (item.path("countryRelation").asText()) {
"SAME_COUNTRY" -> "동일 국가"
"CROSS_COUNTRY" -> "다른 국가"
else -> error("Unexpected post-policy country relation")
}
assertEquals(relation, row.getCell(metadataStart + 1).stringCellValue)
assertEquals(CellType.NUMERIC, row.getCell(metadataStart + 2).cellType)
assertEquals(
item.path("appliedSettlementRatio").doubleValue(),
row.getCell(metadataStart + 2).numericCellValue
)
assertEquals(true, item.path("rateInfoAvailable").booleanValue())
if (agentId == null) {
assertEquals(
CellType.BLANK,
row.getCell(metadataStart + 3, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).cellType
)
assertEquals(
CellType.BLANK,
row.getCell(metadataStart + 4, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).cellType
)
} else {
assertEquals(CellType.STRING, row.getCell(metadataStart + 3).cellType)
assertEquals(agentId.toString(), row.getCell(metadataStart + 3).stringCellValue)
assertEquals(CellType.NUMERIC, row.getCell(metadataStart + 4).cellType)
assertEquals(
item.path("appliedAgentSettlementRatio").doubleValue(),
row.getCell(metadataStart + 4).numericCellValue
)
}
}
val expectedRatios = when (case) {
ExportCase.COUNTRY_RATES -> listOf(50.0, 75.0)
ExportCase.SAME_AGENT_HISTORY -> listOf(75.0)
ExportCase.AGENT_RATE_CHANGE -> listOf(75.0, 75.0)
}
assertEquals(
expectedRatios,
(1..sheet.lastRowNum).map { sheet.getRow(it).getCell(metadataStart + 2).numericCellValue }.sorted()
)
assertEquals(
expectedTotal.depositAmount.toDouble(),
(1..sheet.lastRowNum).sumOf { sheet.getRow(it).getCell(fields.lastIndex).numericCellValue }
)
if (agentId != null) {
val expectedAgentRatios = when (case) {
ExportCase.SAME_AGENT_HISTORY -> listOf(7.0)
ExportCase.AGENT_RATE_CHANGE -> listOf(7.0, 10.0)
ExportCase.COUNTRY_RATES -> error("Country-only fixture has no agent")
}
assertEquals(
expectedAgentRatios,
(1..sheet.lastRowNum).map { sheet.getRow(it).getCell(metadataStart + 4).numericCellValue }.sorted()
)
}
}
}
private fun readList(byCreator: Boolean, offset: Long, limit: Long): JsonNode = if (byCreator) {
channelJson(service.getChannelDonationByCreator("2026-11-02", "2026-11-02", offset, limit))
} else {
channelJson(service.getChannelDonationByDate("2026-11-02", "2026-11-02", offset, limit))
}
enum class ExportCase { COUNTRY_RATES, SAME_AGENT_HISTORY, AGENT_RATE_CHANGE }
}
@@ -29,7 +29,7 @@ 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.adapter.out.persistence.CanonicalSettlementQueryRepository
import kr.co.vividnext.sodalive.v2.settlement.domain.CountrySettlementPolicy
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.BeforeEach
@@ -72,7 +72,7 @@ class AdminAgentReadCurrentMonthListSummaryTest @Autowired constructor(
queryFactory,
entityManager,
cloudFrontHost,
CountrySettlementExpressions(policy),
CanonicalSettlementQueryRepository(entityManager, policy),
policy
)
repository = AdminAgentReadQueryRepository(queryFactory, calculateQueryRepository)
@@ -169,6 +169,56 @@ class AdminAgentReadCurrentMonthListSummaryTest @Autowired constructor(
assertEquals(true, item.liveAgentSettlementAmount > 0)
}
@Test
@DisplayName("11월 관리자 agent 목록은 라이브와 채널의 국가별 반올림 행 합계 12원을 사용한다")
fun shouldSumRoundedEconomicRowsInNovemberAgentList() {
val now = ZonedDateTime.of(LocalDateTime.of(2026, 11, 20, 12, 0), ZoneId.of("Asia/Seoul"))
val eventAt = LocalDateTime.of(2026, 10, 31, 15, 0)
val agent = saveMember("agent-november-rows", MemberRole.AGENT)
val creator = saveMember("creator-november-rows", MemberRole.CREATOR)
val sender = saveMember("sender-november-rows", MemberRole.USER)
saveRelation(agent, creator, eventAt)
val room = saveLiveRoom(creator, eventAt)
val liveSame = saveLiveUseCan(sender, room, 1, eventAt)
val liveCross = saveLiveUseCan(sender, room, 2, eventAt.plusSeconds(1))
val channelSame = saveChannelDonationUseCan(sender, 1, eventAt)
val channelCross = saveChannelDonationUseCan(sender, 2, eventAt.plusSeconds(1))
liveSame.countryCode = "KR"
liveCross.countryCode = "JP"
channelSame.countryCode = "KR"
channelCross.countryCode = "JP"
entityManager.flush()
updateUseCanCreatedAt(liveSame.id!!, eventAt)
updateUseCanCreatedAt(liveCross.id!!, eventAt.plusSeconds(1))
updateUseCanCreatedAt(channelSame.id!!, eventAt)
updateUseCanCreatedAt(channelCross.id!!, eventAt.plusSeconds(1))
saveUseCanCalculate(channelSame, creator.id!!, 1, PaymentGateway.PG)
saveUseCanCalculate(channelCross, creator.id!!, 2, PaymentGateway.PG)
val item = repository.getAgentList(0, 20, now).single { it.agentId == agent.id }
assertEquals(
listOf(12, 0, 0, 0, 12),
listOf(
item.liveAgentSettlementAmount,
item.contentAgentSettlementAmount,
item.communityAgentSettlementAmount,
item.contentDonationAgentSettlementAmount,
item.channelDonationAgentSettlementAmount
)
)
val live = calculateService.getCalculateLiveByCreator("2026-11-01", "2026-11-30", agent.id!!, 0, 1)
val channel = calculateService.getChannelDonationByCreator("2026-11-01", "2026-11-30", agent.id!!, 1, 1)
assertEquals(12, live.total.agentSettlementAmount)
assertEquals(12, channel.total.agentSettlementAmount)
assertEquals(2, live.totalCount)
assertEquals(2, channel.totalCount)
assertEquals(2, live.total.count)
assertEquals(2, channel.total.count)
assertEquals(1, live.items.size)
assertEquals(1, channel.items.size)
}
private fun seedCurrentMonthSettlementFixtures(agent: Member, now: LocalDateTime) {
val creator = saveMember("creator-${agent.nickname}", MemberRole.CREATOR)
val buyer = saveMember("buyer-${agent.nickname}", MemberRole.USER)
@@ -29,7 +29,7 @@ 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.adapter.out.persistence.CanonicalSettlementQueryRepository
import kr.co.vividnext.sodalive.v2.settlement.domain.CountrySettlementPolicy
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.BeforeEach
@@ -71,7 +71,7 @@ class AdminAgentReadParityTest @Autowired constructor(
queryFactory,
entityManager,
cloudFrontHost,
CountrySettlementExpressions(policy),
CanonicalSettlementQueryRepository(entityManager, policy),
policy
)
val adminQueryRepository = AdminAgentReadQueryRepository(queryFactory, queryRepository)
@@ -8,7 +8,7 @@ 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.adapter.out.persistence.CanonicalSettlementQueryRepository
import kr.co.vividnext.sodalive.v2.settlement.domain.CountrySettlementPolicy
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.BeforeEach
@@ -43,7 +43,7 @@ class AdminAgentReadQueryRepositoryTest @Autowired constructor(
queryFactory,
entityManager,
cloudFrontHost,
CountrySettlementExpressions(policy),
CanonicalSettlementQueryRepository(entityManager, policy),
policy
)
)
@@ -1,6 +1,10 @@
package kr.co.vividnext.sodalive.calculate.channelDonation
import kr.co.vividnext.sodalive.v2.settlement.domain.RateSeparatedSettlementCalculator
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementAmounts
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementSource
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
@@ -9,26 +13,111 @@ import org.junit.jupiter.params.provider.CsvSource
class ChannelDonationSettlementCalculatorTest {
@ParameterizedTest
@CsvSource(
"2,1,75,200,13,150,5,145",
"3,3,200,300,20,187,6,181",
"3,2,125,300,20,196,6,190",
"0,0,0,0,0,0,0,0",
"-2,-1,-75,-200,-13,-150,-5,-145",
"100,0,0,10000,660,7939,262,7677",
"1,0,0,100,7,79,3,76"
"1,75,100,7,70,2,68",
"2,50,200,13,94,3,91",
"4,75,400,26,281,9,272",
"0,75,0,0,0,0,0",
"-1,75,-100,-7,-70,-2,-68",
"40000000,75,4000000000,264000000,2802000000,92466000,2709534000"
)
@DisplayName("혼합 정책은 전체 PG를 한 번 반올림하고 정확한 유리수 비율로 정산한다")
fun shouldCalculateMixedPolicyWithoutRoundingWeightedRate(
total: Int,
newCan: Int,
weighted: Long,
krw: Int,
fee: Int,
settlement: Int,
tax: Int,
deposit: Int
@DisplayName("Long 진입점은 적용 비율과 순차 PG 정산 세금 반올림을 따른다")
fun shouldCalculateAtAppliedRatioWithLongAmounts(
totalCan: Long,
ratio: Int,
krw: Long,
fee: Long,
settlement: Long,
tax: Long,
deposit: Long
) {
val result = ChannelDonationSettlementCalculator.calculate(total, newCan, weighted)
val result = ChannelDonationSettlementCalculator.calculateAtRatio(totalCan, ratio)
assertEquals(ChannelDonationSettlementLongAmount(krw, fee, settlement, tax, deposit), result)
}
@ParameterizedTest
@CsvSource("-100", "-1", "0", "1", "2", "25", "100", "100000")
@DisplayName("유효한 기존 85퍼센트 계산과 새 Long 계산은 같은 결과다")
fun shouldMatchLegacyCalculatorWithinItsValidRange(totalCan: Int) {
val legacy = ChannelDonationSettlementCalculator.calculate(totalCan)
val result = ChannelDonationSettlementCalculator.calculateAtRatio(totalCan.toLong(), 85)
assertEquals(
ChannelDonationSettlementLongAmount(
legacy.krw.toLong(),
legacy.fee.toLong(),
legacy.settlementAmount.toLong(),
legacy.withholdingTax.toLong(),
legacy.depositAmount.toLong()
),
result
)
}
@Test
@DisplayName("Long 원화와 정산액 범위 초과는 조용히 잘라내지 않는다")
fun shouldRejectLongAmountOverflow() {
assertThrows(ArithmeticException::class.java) { ChannelDonationSettlementCalculator.calculateAtRatio(Long.MAX_VALUE, 75) }
assertThrows(ArithmeticException::class.java) { ChannelDonationSettlementCalculator.calculateAtRatio(Long.MIN_VALUE, 75) }
assertThrows(ArithmeticException::class.java) {
ChannelDonationSettlementCalculator.calculateAtRatio(1_000_000_000_000, Int.MAX_VALUE)
}
}
@ParameterizedTest
@CsvSource(
"1,1,0,200,14,149,5,144",
"0,2,1,300,20,187,7,180",
"1,1,1,300,21,196,7,189",
"-1,-1,0,-200,-14,-149,-5,-144"
)
@DisplayName("혼합 기간은 보존한 legacy 금액과 실제 canonical 국가별 반올림 금액을 더한다")
fun shouldSumLegacyAndCanonicalPolicyRows(
legacyCan: Int,
sameCountryCan: Long,
crossCountryCan: Long,
krw: Long,
fee: Long,
settlement: Long,
tax: Long,
deposit: Long
) {
val legacy = ChannelDonationSettlementCalculator.calculate(legacyCan)
val sameCountry = RateSeparatedSettlementCalculator.calculate(
SettlementSource.CHANNEL_DONATION,
sameCountryCan,
75,
null
)
val crossCountry = RateSeparatedSettlementCalculator.calculate(
SettlementSource.CHANNEL_DONATION,
crossCountryCan,
50,
null
)
val result = SettlementAmounts(
legacyCan.toLong(),
legacy.krw.toLong(),
legacy.fee.toLong(),
legacy.settlementAmount.toLong(),
legacy.withholdingTax.toLong(),
legacy.depositAmount.toLong(),
0
) + sameCountry + crossCountry
assertEquals(
SettlementAmounts(legacyCan + sameCountryCan + crossCountryCan, krw, fee, settlement, tax, deposit, 0),
result
)
}
@ParameterizedTest
@CsvSource("0,0,0,0,0,0", "100,10000,660,7939,262,7677", "1,100,7,79,3,76")
@DisplayName("구정책만 있는 zero와 100캔 및 1캔은 기존 85퍼센트 금액을 보존한다")
fun shouldPreserveLegacyOnlyAmounts(total: Int, krw: Int, fee: Int, settlement: Int, tax: Int, deposit: Int) {
val result = ChannelDonationSettlementCalculator.calculate(total)
assertEquals(ChannelDonationSettlementAmount(krw, fee, settlement, tax, deposit), result)
}
@@ -1,6 +1,7 @@
package kr.co.vividnext.sodalive.creator.admin.calculate
import com.querydsl.jpa.impl.JPAQueryFactory
import kr.co.vividnext.sodalive.admin.calculate.AdminCalculateQueryRepository
import kr.co.vividnext.sodalive.admin.calculate.GetCalculateCommunityPostQueryData
import kr.co.vividnext.sodalive.admin.calculate.GetCalculateContentDonationQueryData
import kr.co.vividnext.sodalive.admin.calculate.GetCalculateContentQueryData
@@ -21,7 +22,7 @@ import kr.co.vividnext.sodalive.explorer.profile.creatorCommunity.CreatorCommuni
import kr.co.vividnext.sodalive.live.room.LiveRoom
import kr.co.vividnext.sodalive.member.Member
import kr.co.vividnext.sodalive.member.MemberRole
import kr.co.vividnext.sodalive.v2.settlement.adapter.out.persistence.CountrySettlementExpressions
import kr.co.vividnext.sodalive.v2.settlement.adapter.out.persistence.CanonicalSettlementQueryRepository
import kr.co.vividnext.sodalive.v2.settlement.domain.CountrySettlementPolicy
import org.junit.jupiter.api.Assertions.assertAll
import org.junit.jupiter.api.Assertions.assertEquals
@@ -61,8 +62,10 @@ class CreatorAdminCalculateQueryRepositoryTest @Autowired constructor(
@BeforeEach
fun setup() {
repository = CreatorAdminCalculateQueryRepository(
queryFactory,
CountrySettlementExpressions(CountrySettlementPolicy())
AdminCalculateQueryRepository(
queryFactory,
CanonicalSettlementQueryRepository(entityManager, CountrySettlementPolicy())
)
)
entityManager.createNativeQuery(
"CREATE ALIAS IF NOT EXISTS DATE_FORMAT FOR 'kr.co.vividnext.sodalive.support.H2MysqlDateFunctions.dateFormat'"
@@ -147,8 +150,8 @@ class CreatorAdminCalculateQueryRepositoryTest @Autowired constructor(
}
@Test
@DisplayName("라이브의 같은 행은 시행 전후와 국가가 섞여도 유지하고 다른 크리에이터 및 환불은 제외한다")
fun shouldKeepMixedPolicyLiveGroupScopedToItsCurrentCreator() {
@DisplayName("라이브 비율별 신정책 행과 구정책 행은 본인 범위 및 환불 제외를 유지한다")
fun shouldSplitMixedPolicyLiveRatesWithinCurrentCreatorScope() {
// given
listOf(effectiveAt.minusSeconds(1) to "JP", effectiveAt to "KR", effectiveAt.plusSeconds(1) to "JP")
.forEach { (at, country) ->
@@ -185,19 +188,23 @@ class CreatorAdminCalculateQueryRepositoryTest @Autowired constructor(
val rows = repository.getCalculateLive(startDate, endDate, requireNotNull(creator.id))
// then
assertEquals(1, rows.size)
val result = rows.single().toGetCalculateLiveResponse()
assertEquals(room.id, result.roomId)
assertEquals(3, result.numberOfPeople)
assertEquals(3, rows.size)
val results = rows.map { it.toGetCalculateLiveResponse() }
assertEquals(listOf(room.id, room.id, room.id), results.map { it.roomId })
assertEquals(listOf(1, 1, 1), results.map { it.numberOfPeople })
assertEquals(
listOf(300, 30_000, 1_980, 18_213, 601, 17_612),
result.run { listOf(totalAmount, totalKrw, paymentFee, settlementAmount, tax, depositAmount) }
listOf(
listOf(100, 10_000, 660, 4_670, 154, 4_516),
listOf(100, 10_000, 660, 7_005, 231, 6_774),
listOf(100, 10_000, 660, 6_538, 216, 6_322)
),
results.map { listOf(it.totalAmount, it.totalKrw, it.paymentFee, it.settlementAmount, it.tax, it.depositAmount) }
)
}
@Test
@DisplayName("콘텐츠 주문은 누락 연결과 PG 분할에도 유지하고 콘텐츠 비율 및 주문 시각과 포인트 그룹을 보존한다")
fun shouldKeepOrderSourceContentOverridesPointsAndCreatorPagesAcrossBoundary() {
@DisplayName("본인 콘텐츠 비율별 페이지는 누락 연결과 PG 분할 및 주문 시각과 포인트를 보존한다")
fun shouldSplitContentRatesWithinCreatorPagesWhileKeepingOrderSource() {
// given
persist(CreatorSettlementRatio(0, 90, 90, 90).apply { member = creator })
content.settlementRatio = 80
@@ -268,21 +275,22 @@ class CreatorAdminCalculateQueryRepositoryTest @Autowired constructor(
val cumulativeRows = repository.getCumulativeSalesByContent(creatorId, 0, 10)
// then
assertEquals(3, count)
assertEquals(3, rows.size)
assertEquals(4, count)
assertEquals(4, rows.size)
assertEquals(1, repository.getCalculateContentList(startDate, endDate, creatorId, 0, 1).size)
assertEquals(
emptyList<GetCalculateContentQueryData>(),
repository.getCalculateContentList(startDate, endDate, creatorId, 3, 1)
repository.getCalculateContentList(startDate, endDate, creatorId, 4, 1)
)
assertEquals(2, cumulativeCount)
assertEquals(2, cumulativeRows.size)
assertEquals(4, cumulativeCount)
assertEquals(4, cumulativeRows.size)
assertEquals(1, repository.getCumulativeSalesByContent(creatorId, 0, 1).size)
assertEquals(emptyList<GetCumulativeSalesByContentQueryData>(), repository.getCumulativeSalesByContent(creatorId, 2, 1))
assertEquals(emptyList<GetCumulativeSalesByContentQueryData>(), repository.getCumulativeSalesByContent(creatorId, 4, 1))
val oldRow = rows.single { it.saleDate == "2026-10-31" }.toGetCalculateContentResponse()
val newRow = rows.single { it.saleDate == "2026-11-01" && it.totalPoint == 0 }.toGetCalculateContentResponse()
val newRows = rows.filter { it.saleDate == "2026-11-01" && it.totalPoint == 0 }
.map { it.toGetCalculateContentResponse() }
val pointRow = rows.single { it.totalPoint == 100 }.toGetCalculateContentResponse()
val cumulative = cumulativeRows.single { it.totalPoint == 0 }.toCumulativeSalesByContentItem()
val cumulative = cumulativeRows.filter { it.totalPoint == 0 }.map { it.toCumulativeSalesByContentItem() }
val cumulativePoint = cumulativeRows.single { it.totalPoint == 100 }.toCumulativeSalesByContentItem()
assertAll(
{
@@ -293,8 +301,10 @@ class CreatorAdminCalculateQueryRepositoryTest @Autowired constructor(
},
{
assertEquals(
listOf(3, 300, 30_000, 1_980, 19_614, 647, 18_967),
newRow.run { listOf(numberOfPeople, totalCan, totalKrw, paymentFee, settlementAmount, tax, depositAmount) }
listOf(listOf(1, 100, 10_000, 660, 4_670, 154, 4_516), listOf(2, 200, 20_000, 1_320, 14_944, 493, 14_451)),
newRows.map { row ->
row.run { listOf(numberOfPeople, totalCan, totalKrw, paymentFee, settlementAmount, tax, depositAmount) }
}
)
},
{
@@ -313,9 +323,13 @@ class CreatorAdminCalculateQueryRepositoryTest @Autowired constructor(
},
{
assertEquals(
listOf(4, 400, 40_000, 2_640, 27_086, 894, 26_192),
cumulative.run {
listOf(numberOfPeople, totalCan, totalKrw, paymentFee, settlementAmount, tax, depositAmount)
listOf(
listOf(1, 100, 10_000, 660, 4_670, 154, 4_516),
listOf(2, 200, 20_000, 1_320, 14_944, 493, 14_451),
listOf(1, 100, 10_000, 660, 7_472, 247, 7_225)
),
cumulative.map { row ->
row.run { listOf(numberOfPeople, totalCan, totalKrw, paymentFee, settlementAmount, tax, depositAmount) }
}
)
}
@@ -323,8 +337,8 @@ class CreatorAdminCalculateQueryRepositoryTest @Autowired constructor(
}
@Test
@DisplayName("후원과 커뮤니티는 국가 혼합과 보상캔에도 기존 두 날짜 페이지 및 환불 제외를 유지한다")
fun shouldKeepDonationAndCommunityDailyGroupsAndLegacyRounding() {
@DisplayName("본인 후원과 커뮤니티는 비율별 세 행으로 페이지하고 보상캔 및 환불과 과거 반올림을 보존한다")
fun shouldPageCreatorDonationAndCommunityRateRowsWithLegacyRounding() {
// given
listOf(
Triple(effectiveAt.minusSeconds(1), "JP", 125),
@@ -400,39 +414,45 @@ class CreatorAdminCalculateQueryRepositoryTest @Autowired constructor(
val donationCount = repository.getCalculateContentDonationListTotalCount(startDate, endDate, creatorId)
val donation = repository.getCalculateContentDonationList(startDate, endDate, creatorId, 0, 1)
.single().toGetCalculateContentDonationResponse()
val oldDonation = repository.getCalculateContentDonationList(startDate, endDate, creatorId, 1, 1)
val sameDonation = repository.getCalculateContentDonationList(startDate, endDate, creatorId, 1, 1)
.single().toGetCalculateContentDonationResponse()
val oldDonation = repository.getCalculateContentDonationList(startDate, endDate, creatorId, 2, 1)
.single().toGetCalculateContentDonationResponse()
val communityCount = repository.getCalculateCommunityPostTotalCount(startDate, endDate, creatorId)
val community = repository.getCalculateCommunityPostList(startDate, endDate, creatorId, 0, 1)
.single().toGetCalculateCommunityPostResponse()
val oldCommunity = repository.getCalculateCommunityPostList(startDate, endDate, creatorId, 1, 1)
val sameCommunity = repository.getCalculateCommunityPostList(startDate, endDate, creatorId, 1, 1)
.single().toGetCalculateCommunityPostResponse()
val oldCommunity = repository.getCalculateCommunityPostList(startDate, endDate, creatorId, 2, 1)
.single().toGetCalculateCommunityPostResponse()
// then
assertEquals(2, donationCount)
assertEquals(2, communityCount)
assertEquals(3, donationCount)
assertEquals(3, communityCount)
assertEquals("2026-11-01", donation.donationDate)
assertEquals("2026-11-01", community.date)
assertEquals(2, donation.numberOfDonation)
assertEquals(2, community.numberOfPurchase)
assertEquals(1, donation.numberOfDonation)
assertEquals(1, community.numberOfPurchase)
assertEquals(1, sameDonation.numberOfDonation)
assertEquals(1, sameCommunity.numberOfPurchase)
assertEquals(
emptyList<GetCalculateContentDonationQueryData>(),
repository.getCalculateContentDonationList(startDate, endDate, creatorId, 2, 1)
repository.getCalculateContentDonationList(startDate, endDate, creatorId, 3, 1)
)
assertEquals(
emptyList<GetCalculateCommunityPostQueryData>(),
repository.getCalculateCommunityPostList(startDate, endDate, creatorId, 2, 1)
repository.getCalculateCommunityPostList(startDate, endDate, creatorId, 3, 1)
)
assertAll(
{
assertEquals(
listOf(200, 20_000, 1_320, 11_675, 385, 11_290),
listOf(100, 10_000, 660, 4_670, 154, 4_516),
donation.run { listOf(totalCan, totalKrw, paymentFee, settlementAmount, tax, depositAmount) }
)
},
{
assertEquals(
listOf(200, 20_000, 1_320, 11_675, 385, 11_290),
listOf(100, 10_000, 660, 4_670, 154, 4_516),
community.run { listOf(totalCan, totalKrw, paymentFee, settlementAmount, tax, depositAmount) }
)
},
@@ -449,6 +469,14 @@ class CreatorAdminCalculateQueryRepositoryTest @Autowired constructor(
)
}
)
assertEquals(
listOf(100, 10_000, 660, 7_005, 231, 6_774),
sameDonation.run { listOf(totalCan, totalKrw, paymentFee, settlementAmount, tax, depositAmount) }
)
assertEquals(
listOf(100, 10_000, 660, 7_005, 231, 6_774),
sameCommunity.run { listOf(totalCan, totalKrw, paymentFee, settlementAmount, tax, depositAmount) }
)
}
@Test
@@ -541,7 +569,7 @@ class CreatorAdminCalculateQueryRepositoryTest @Autowired constructor(
val community = repository.getMonthlyCalculateCommunityPostList(monthStart, monthEnd, creatorId)
// then
assertEquals(1, live.size)
assertEquals(3, live.size)
assertEquals(3, content.size)
assertEquals(3, donation.size)
assertEquals(3, community.size)
@@ -1,6 +1,10 @@
package kr.co.vividnext.sodalive.creator.admin.calculate.channelDonation
import com.querydsl.jpa.impl.JPAQueryFactory
import kr.co.vividnext.sodalive.admin.calculate.channelDonation.AdminChannelDonationCalculateQueryRepository
import kr.co.vividnext.sodalive.admin.calculate.channelDonation.ChannelSettlementTestFixture
import kr.co.vividnext.sodalive.admin.calculate.channelDonation.GetAdminChannelDonationSettlementTotal
import kr.co.vividnext.sodalive.admin.calculate.channelDonation.channelJson
import kr.co.vividnext.sodalive.can.payment.PaymentGateway
import kr.co.vividnext.sodalive.can.use.CanUsage
import kr.co.vividnext.sodalive.can.use.UseCan
@@ -12,12 +16,14 @@ import kr.co.vividnext.sodalive.configs.QueryDslConfig
import kr.co.vividnext.sodalive.member.Member
import kr.co.vividnext.sodalive.member.MemberRepository
import kr.co.vividnext.sodalive.member.MemberRole
import kr.co.vividnext.sodalive.v2.settlement.adapter.out.persistence.CountrySettlementExpressions
import kr.co.vividnext.sodalive.v2.settlement.adapter.out.persistence.CanonicalSettlementQueryRepository
import kr.co.vividnext.sodalive.v2.settlement.domain.CountrySettlementPolicy
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.ValueSource
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest
import org.springframework.context.annotation.Import
@@ -40,7 +46,8 @@ class CreatorAdminChannelDonationCalculateQueryRepositoryTest @Autowired constru
registerMysqlDateFunctions()
repository = CreatorAdminChannelDonationCalculateQueryRepository(
queryFactory,
CountrySettlementExpressions(CountrySettlementPolicy())
CanonicalSettlementQueryRepository(entityManager, CountrySettlementPolicy()),
CountrySettlementPolicy()
)
}
@@ -83,6 +90,97 @@ class CreatorAdminChannelDonationCalculateQueryRepositoryTest @Autowired constru
assertEquals(50, items[0].totalCan)
}
@ParameterizedTest
@ValueSource(ints = [7, 10])
@DisplayName("크리에이터 조회는 실제 agent 조건으로 분리하고 같은 7퍼센트의 이력 ID 변경은 병합한다")
fun shouldReuseAgentEconomicsWithoutRoundingAtHistoryIds(secondRate: Int) {
val fixture = ChannelSettlementTestFixture(entityManager)
val agentId = fixture.seedAgentRates(secondRate)
val creatorId = requireNotNull(fixture.creator.id)
val service = CreatorAdminChannelDonationCalculateService(repository)
val expectedCount = if (secondRate == 7) 1 else 2
val expectedTotal = if (secondRate == 7) {
GetCreatorChannelDonationSettlementTotal(2, 4, 400, 26, 281, 9, 272)
} else {
GetCreatorChannelDonationSettlementTotal(2, 4, 400, 27, 280, 9, 271)
}
val pages = (0L..expectedCount.toLong()).map {
channelJson(service.getChannelDonation("2026-11-02", "2026-11-02", creatorId, "rate-creator", it, 1))
}
pages.forEach { page ->
assertEquals(expectedCount, page.path("totalCount").intValue())
assertEquals(channelJson(expectedTotal), page.path("total"))
}
val rows = pages.flatMap { it.path("items").toList() }
assertEquals(expectedCount, rows.size)
assertEquals(
if (secondRate == 7) listOf(272) else listOf(68, 203),
rows.map { it.path("depositAmount").intValue() }.sorted()
)
assertEquals(
if (secondRate == 7) listOf(7) else listOf(7, 10),
rows.map { it.path("appliedAgentSettlementRatio").intValue() }.sorted()
)
assertEquals(expectedCount, rows.map { it.path("rowKey").asText() }.toSet().size)
rows.forEach { row ->
assertEquals("SAME_COUNTRY", row.path("countryRelation").asText())
assertEquals(75, row.path("appliedSettlementRatio").intValue())
assertEquals(agentId, row.path("agentId").longValue())
assertEquals(true, row.path("agentId").isIntegralNumber)
assertEquals(true, row.path("rateInfoAvailable").booleanValue())
}
assertEquals(0, pages.last().path("items").size())
val allRows = channelJson(
service.getChannelDonation("2026-11-02", "2026-11-02", creatorId, "rate-creator", 0, 20)
).path("items").toList()
assertEquals(allRows, rows)
assertEquals(
expectedTotal,
repository.getMonthlyChannelDonationSettlementTotal(
LocalDateTime.of(2026, 11, 1, 15, 0),
LocalDateTime.of(2026, 11, 2, 15, 0),
creatorId
).toResponseTotal()
)
}
@Test
@DisplayName("시행 전 두 날짜의 85퍼센트 전체기간 154는 일별 76 더하기 76으로 바꾸지 않는다")
fun shouldPreserveLegacyWholePeriodRoundingAcrossAdminAndCreatorQueries() {
val fixture = ChannelSettlementTestFixture(entityManager)
fixture.seedLegacyDays()
val start = LocalDateTime.of(2026, 10, 29, 15, 0)
val end = LocalDateTime.of(2026, 10, 31, 14, 59, 59)
val creatorId = requireNotNull(fixture.creator.id)
val admin = AdminChannelDonationCalculateQueryRepository(
queryFactory,
CanonicalSettlementQueryRepository(entityManager, CountrySettlementPolicy()),
CountrySettlementPolicy()
)
assertEquals(
GetCreatorChannelDonationSettlementTotal(2, 2, 200, 13, 159, 5, 154),
repository.getChannelDonationSettlementTotal(start, end, creatorId).toResponseTotal()
)
assertEquals(
GetAdminChannelDonationSettlementTotal(2, 2, 200, 13, 159, 5, 154),
admin.getChannelDonationByDateTotal(start, end).toResponseTotal()
)
assertEquals(
GetAdminChannelDonationSettlementTotal(2, 2, 200, 13, 159, 5, 154),
admin.getChannelDonationByCreatorTotal(start, end).toResponseTotal()
)
assertEquals(
listOf(76, 76),
repository.getChannelDonation(start, end, creatorId, 0, 20).map { it.toResponseItem("rate-creator").depositAmount }
)
assertEquals(
listOf(154),
admin.getChannelDonationByCreator(start, end, 0, 20).map { it.toResponseItem().depositAmount }
)
}
private fun saveMember(nickname: String, role: MemberRole): Member {
return memberRepository.saveAndFlush(
Member(
@@ -1,6 +1,8 @@
package kr.co.vividnext.sodalive.creator.admin.calculate.channelDonation
import com.querydsl.jpa.impl.JPAQueryFactory
import kr.co.vividnext.sodalive.admin.calculate.channelDonation.channelJson
import kr.co.vividnext.sodalive.admin.calculate.channelDonation.financialColumns
import kr.co.vividnext.sodalive.can.payment.PaymentGateway
import kr.co.vividnext.sodalive.can.use.CanUsage
import kr.co.vividnext.sodalive.can.use.UseCan
@@ -9,7 +11,7 @@ import kr.co.vividnext.sodalive.can.use.UseCanCalculateStatus
import kr.co.vividnext.sodalive.configs.QueryDslConfig
import kr.co.vividnext.sodalive.member.Member
import kr.co.vividnext.sodalive.member.MemberRole
import kr.co.vividnext.sodalive.v2.settlement.adapter.out.persistence.CountrySettlementExpressions
import kr.co.vividnext.sodalive.v2.settlement.adapter.out.persistence.CanonicalSettlementQueryRepository
import kr.co.vividnext.sodalive.v2.settlement.domain.CountrySettlementPolicy
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.BeforeEach
@@ -51,7 +53,8 @@ class CreatorChannelDonationCountryPolicyRepositoryTest @Autowired constructor(
).executeUpdate()
repository = CreatorAdminChannelDonationCalculateQueryRepository(
queryFactory,
CountrySettlementExpressions(CountrySettlementPolicy())
CanonicalSettlementQueryRepository(entityManager, CountrySettlementPolicy()),
CountrySettlementPolicy()
)
sender = saveMember("sender", "US", MemberRole.USER)
}
@@ -81,8 +84,8 @@ class CreatorChannelDonationCountryPolicyRepositoryTest @Autowired constructor(
}
@Test
@DisplayName("크리에이터 전체 금액은 정책 전후 한 캔씩을 한 번 계산하고 일별 페이지의 반올림 합과 구분한다")
fun shouldKeepWholePeriodRoundingSeparateFromDailyPages() {
@DisplayName("혼합 기간의 크리에이터 전체 금액은 보존한 구정책 금액과 신정책 행 금액의 합이다")
fun shouldSumLegacyAndCanonicalMoneyAcrossDailyPages() {
val creator = saveMember("creator", "KR")
val creatorId = requireNotNull(creator.id)
saveCalculation(creator, saveUsage(UseCan(CanUsage.CHANNEL_DONATION, 1, 0, countryCode = "KR"), start))
@@ -91,17 +94,17 @@ class CreatorChannelDonationCountryPolicyRepositoryTest @Autowired constructor(
entityManager.clear()
assertEquals(
GetCreatorChannelDonationSettlementTotal(2, 2, 200, 13, 150, 5, 145),
GetCreatorChannelDonationSettlementTotal(2, 2, 200, 14, 149, 5, 144),
repository.getChannelDonationSettlementTotal(start, end, creatorId).toResponseTotal()
)
assertEquals(2, repository.getChannelDonationTotalCount(start, end, creatorId))
assertEquals(
listOf(GetCreatorChannelDonationSettlementItem("2026-11-01", "creator", 1, 1, 100, 7, 70, 2, 68)),
repository.getChannelDonation(start, end, creatorId, 0, 1).map { it.toResponseItem("creator") }
repository.getChannelDonation(start, end, creatorId, 0, 1).map { it.toResponseItem("creator").financialColumns() }
)
assertEquals(
listOf(GetCreatorChannelDonationSettlementItem("2026-10-31", "creator", 1, 1, 100, 7, 79, 3, 76)),
repository.getChannelDonation(start, end, creatorId, 1, 1).map { it.toResponseItem("creator") }
repository.getChannelDonation(start, end, creatorId, 1, 1).map { it.toResponseItem("creator").financialColumns() }
)
assertEquals(
emptyList<GetCreatorChannelDonationSettlementQueryData>(),
@@ -110,8 +113,8 @@ class CreatorChannelDonationCountryPolicyRepositoryTest @Autowired constructor(
}
@Test
@DisplayName("크리에이터 혼합 국가 일별 행은 본인의 수신 배분만 합하고 PG 분할을 후원 건수로 중복 계산하지 않는다")
fun shouldKeepMixedCountriesInOneDailyRowWithRecipientScopedAllocations() {
@DisplayName("크리에이터 국가별 행은 본인 배분만 합하고 PG 분할 건수와 제외 원천은 보존한다")
fun shouldSeparateCountryRowsWithRecipientScopedAllocations() {
val creator = saveMember("creator", "KR")
val creatorId = requireNotNull(creator.id)
val otherCreator = saveMember("other", "JP")
@@ -134,17 +137,28 @@ class CreatorChannelDonationCountryPolicyRepositoryTest @Autowired constructor(
entityManager.clear()
assertEquals(
GetCreatorChannelDonationSettlementTotal(2, 3, 300, 20, 187, 6, 181),
GetCreatorChannelDonationSettlementTotal(2, 3, 300, 20, 187, 7, 180),
repository.getChannelDonationSettlementTotal(start, end, creatorId).toResponseTotal()
)
assertEquals(1, repository.getChannelDonationTotalCount(start, end, creatorId))
assertEquals(2, repository.getChannelDonationTotalCount(start, end, creatorId))
val metadata = channelJson(
repository.getChannelDonation(start, end, creatorId, 0, 20).map { it.toResponseItem("creator") }
)
assertEquals(listOf("CROSS_COUNTRY", "SAME_COUNTRY"), metadata.map { it.path("countryRelation").asText() })
assertEquals(listOf(50, 75), metadata.map { it.path("appliedSettlementRatio").intValue() })
assertEquals(2, metadata.map { it.path("rowKey").asText() }.toSet().size)
assertEquals(true, metadata.all { it.path("rateInfoAvailable").booleanValue() })
assertEquals(
listOf(GetCreatorChannelDonationSettlementItem("2026-11-01", "creator", 2, 3, 300, 20, 187, 6, 181)),
repository.getChannelDonation(start, end, creatorId, 0, 1).map { it.toResponseItem("creator") }
listOf(GetCreatorChannelDonationSettlementItem("2026-11-01", "creator", 1, 1, 100, 7, 47, 2, 45)),
repository.getChannelDonation(start, end, creatorId, 0, 1).map { it.toResponseItem("creator").financialColumns() }
)
assertEquals(
listOf(GetCreatorChannelDonationSettlementItem("2026-11-01", "creator", 1, 2, 200, 13, 140, 5, 135)),
repository.getChannelDonation(start, end, creatorId, 1, 1).map { it.toResponseItem("creator").financialColumns() }
)
assertEquals(
emptyList<GetCreatorChannelDonationSettlementQueryData>(),
repository.getChannelDonation(start, end, creatorId, 1, 1)
repository.getChannelDonation(start, end, creatorId, 2, 1)
)
assertEquals(
GetCreatorChannelDonationSettlementTotal(0, 0, 0, 0, 0, 0, 0),
@@ -171,7 +185,7 @@ class CreatorChannelDonationCountryPolicyRepositoryTest @Autowired constructor(
assertEquals(sourceCount, repository.getChannelDonationTotalCount(start, end, creatorId))
assertEquals(
List(sourceCount) { GetCreatorChannelDonationSettlementItem("2026-11-01", "creator", 1, 0, 0, 0, 0, 0, 0) },
repository.getChannelDonation(start, end, creatorId, 0, 20).map { it.toResponseItem("creator") }
repository.getChannelDonation(start, end, creatorId, 0, 20).map { it.toResponseItem("creator").financialColumns() }
)
}
@@ -1,5 +1,7 @@
package kr.co.vividnext.sodalive.partner.agent.calculate
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.ObjectMapper
import com.querydsl.jpa.impl.JPAQueryFactory
import kr.co.vividnext.sodalive.admin.calculate.ratio.CreatorSettlementRatio
import kr.co.vividnext.sodalive.admin.calculate.ratio.CreatorSettlementRatioRepository
@@ -29,7 +31,7 @@ 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.adapter.out.persistence.CanonicalSettlementQueryRepository
import kr.co.vividnext.sodalive.v2.settlement.domain.CountrySettlementPolicy
import org.junit.jupiter.api.Assertions.assertAll
import org.junit.jupiter.api.Assertions.assertEquals
@@ -77,7 +79,7 @@ class AgentCalculateQueryRepositoryTest @Autowired constructor(
queryFactory,
entityManager,
cloudFrontHost,
CountrySettlementExpressions(policy),
CanonicalSettlementQueryRepository(entityManager, policy),
policy
)
service = AgentCalculateService(repository, snapshotRepository)
@@ -413,11 +415,7 @@ class AgentCalculateQueryRepositoryTest @Autowired constructor(
response,
expectedCount = 1,
expectedTotalCan = 20,
expectedAgentSettlementAmount = calculateGenericAgentSettlementAmount(
totalCan = 20,
settlementRatio = 70,
agentSettlementRatio = 7
)
expectedAgentSettlementAmount = 92
)
}
@@ -439,7 +437,7 @@ class AgentCalculateQueryRepositoryTest @Autowired constructor(
response,
expectedCount = 1,
expectedTotalCan = 50,
expectedAgentSettlementAmount = calculateChannelAgentSettlementAmount(totalCan = 50, agentSettlementRatio = 7)
expectedAgentSettlementAmount = 278
)
}
@@ -643,12 +641,8 @@ class AgentCalculateQueryRepositoryTest @Autowired constructor(
val liveRows = repository.getCalculateLiveByCreator(startDate, endDate, agent.id!!)
assertEquals(savedRatios.mapNotNull { it.id }, liveRows.mapNotNull { it.agentSettlementRatioId }.sorted())
val expectedGenericAgentSettlementAmount =
calculateGenericAgentSettlementAmount(totalCan = 10, settlementRatio = 70, agentSettlementRatio = 10) +
calculateGenericAgentSettlementAmount(totalCan = 20, settlementRatio = 70, agentSettlementRatio = 20)
val expectedChannelAgentSettlementAmount =
calculateChannelAgentSettlementAmount(totalCan = 10, agentSettlementRatio = 10) +
calculateChannelAgentSettlementAmount(totalCan = 20, agentSettlementRatio = 20)
val expectedGenericAgentSettlementAmount = 327
val expectedChannelAgentSettlementAmount = 397
val liveResponse = service.getCalculateLiveByCreator("2026-02-20", "2026-02-20", agent.id!!, 0, 10)
assertGenericSettlementResponse(
@@ -837,8 +831,8 @@ class AgentCalculateQueryRepositoryTest @Autowired constructor(
}
@Test
@DisplayName("한 agent 원천 그룹의 시행 전후 거래는 행을 늘리지 않고 채널 85와 75를 가중 집계한다")
fun shouldKeepOneSourceGroupForMixedLegacyAndCountryEvents() {
@DisplayName("시행 전 보존 행과 시행 후 경제 조건 행은 분리하고 반올림한 금액을 합산한다")
fun shouldSeparateLegacyAndPostPolicyRowsWithoutReroundingTheirTotals() {
val agent = saveMember("agent-country-mixed", MemberRole.AGENT)
val creator = saveMember("creator-country-mixed", MemberRole.CREATOR)
creator.countryCode = "KR"
@@ -846,18 +840,20 @@ class AgentCalculateQueryRepositoryTest @Autowired constructor(
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)
assertEquals(listOf(2, 2, 2, 2), countryRows(agent.id!!).map { it.size })
assertEquals(2, repository.getChannelDonationByCreator(countryStart, countryEnd, agent.id!!).size)
countryPages(agent.id!!, 0).forEach { assertEquals(2, it.totalCount) }
countryPages(agent.id!!, 1).forEach { assertEquals(1, it.items.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)
GetAgentSettlementByCreatorTotal(2, 26, 2_600, 172, 1_761, 58, 1_703, 124),
GetAgentChannelDonationSettlementTotal(2, 26, 2_600, 172, 1_943, 64, 1_879, 136)
)
}
@ParameterizedTest
@MethodSource("yearEndCases")
@DisplayName("연말 마지막 마이크로초 75와 새해 시작 70은 같은 소속 그룹에서 행과 건수를 유지하며 집계한다")
@DisplayName("연말 마지막 마이크로초 75와 새해 시작 70은 별도 표시 행이며 전체 건수와 금액을 보존한다")
fun shouldApplyYearEndRatesToRowsAndNativeTotals(
eventAts: List<LocalDateTime>,
case: CountryCase,
@@ -884,12 +880,15 @@ class AgentCalculateQueryRepositoryTest @Autowired constructor(
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 expectedDisplayCount = eventAts.size
assertEquals(List(5) { expectedDisplayCount }, creatorCounts)
assertEquals(List(4) { expectedDisplayCount }, rows.map { it.size })
assertEquals(expectedDisplayCount, channelRows.size)
rows.forEach { assertEquals(List(expectedDisplayCount) { creator.id }, it.map { row -> row.creatorId }) }
assertEquals(List(expectedDisplayCount) { creator.id }, channelRows.map { it.creatorId })
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 })
rows.forEach { assertEquals(List(expectedDisplayCount) { assignmentId }, it.map { row -> row.assignmentId }) }
assertEquals(List(expectedDisplayCount) { 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") }
@@ -903,8 +902,8 @@ class AgentCalculateQueryRepositoryTest @Autowired constructor(
}
@Test
@DisplayName("채널 혼합 2캔 그룹은 PG를 먼저 반올림하고 국가 가중 정산액에 agent 몫을 적용한다")
fun shouldRoundMixedTwoCanChannelGroupBeforeAgentCut() {
@DisplayName("시행 전 1캔 85와 시행 후 1캔 75는 각 행에서 PG와 agent 몫을 반올림한다")
fun shouldRoundLegacyAndPostPolicyChannelRowsBeforeSummingAgentCuts() {
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)
@@ -917,9 +916,10 @@ class AgentCalculateQueryRepositoryTest @Autowired constructor(
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)
val expected = GetAgentChannelDonationSettlementTotal(2, 2, 200, 14, 149, 5, 144, 11)
assertEquals(1, rows.size)
assertEquals(2, rows.size)
assertEquals(2, repository.getChannelDonationByCreatorTotalCount(countryStart, countryEnd, agent.id!!))
assertAll(
{ assertEquals(expected, rows.toMergedResponseItems().toResponseTotal()) },
{ assertEquals(expected, total) }
@@ -951,10 +951,11 @@ class AgentCalculateQueryRepositoryTest @Autowired constructor(
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)
val expected = GetAgentSettlementByCreatorTotal(3, 39, 3_900, 258, 2_550, 84, 2_466, 178)
assertEquals(1, rows.size)
assertEquals(1, repository.getCalculateContentByCreatorTotalCount(countryStart, countryEnd, agent.id!!))
assertEquals(2, rows.size)
assertEquals(2, repository.getCalculateContentByCreatorTotalCount(countryStart, countryEnd, agent.id!!))
assertEquals(listOf(1L, 2L), rows.map { it.count }.sorted())
assertAll(
{ assertEquals(expected, rows.toResponseTotal()) },
{ assertEquals(expected, total) }
@@ -1036,6 +1037,91 @@ class AgentCalculateQueryRepositoryTest @Autowired constructor(
)
}
@Test
@DisplayName("같은 creator의 75와 50 행은 서비스까지 분리하고 각 페이지와 전체 금액을 독립적으로 유지한다")
fun shouldPageFinalEconomicRowsForOneCreatorAcrossAllSources() {
val agent = saveMember("agent-economic-pages", MemberRole.AGENT)
val creator = saveMember("creator-economic-pages", MemberRole.CREATOR)
saveRelation(agent, creator)
seedCountrySources(creator, "KR", countryBoundary)
seedCountrySources(creator, "JP", countryBoundary.plusSeconds(1))
val mapper = ObjectMapper()
val expected = GetAgentSettlementByCreatorTotal(2, 26, 2_600, 172, 1_518, 50, 1_468, 106)
val genericPages = listOf(0L, 1L, 2L).map { countryPages(agent.id!!, it) }
val fullGeneric = countryPages(agent.id!!, 0, 10)
val fullChannel = service.getChannelDonationByCreator("2026-11-01", "2026-11-01", agent.id!!, 0, 10)
val channelPages = (0L..2L).map {
service.getChannelDonationByCreator("2026-11-01", "2026-11-01", agent.id!!, it, 1)
}
assertCountryResults(agent.id!!, expected, expected.toChannelTotal())
fullGeneric.forEachIndexed { source, full ->
assertEquals(expected, full.total)
assertEquals(2, full.totalCount)
assertEquals(2, full.items.size)
genericPages.forEachIndexed { page, responses ->
assertEquals(2, responses[source].totalCount)
assertEquals(expected, responses[source].total)
assertEquals(if (page == 2) 0 else 1, responses[source].items.size)
}
}
assertEquals(expected.toChannelTotal(), fullChannel.total)
assertEquals(2, fullChannel.totalCount)
assertEquals(2, fullChannel.items.size)
channelPages.forEachIndexed { page, response ->
assertEquals(2, response.totalCount)
assertEquals(expected.toChannelTotal(), response.total)
assertEquals(if (page == 2) 0 else 1, response.items.size)
}
val fullJson = fullGeneric.map { mapper.valueToTree<JsonNode>(it) } + listOf(mapper.valueToTree<JsonNode>(fullChannel))
val pagedJson = genericPages.take(2).mapIndexed { page, responses ->
responses.map { mapper.valueToTree<JsonNode>(it) } + listOf(mapper.valueToTree<JsonNode>(channelPages[page]))
}
fullJson.forEachIndexed { source, response ->
val items = response.path("items").toList()
assertEquals(listOf(creator.id, creator.id), items.map { it.path("creatorId").longValue() })
assertEquals(
setOf("SAME_COUNTRY", "CROSS_COUNTRY"),
items.map { it.path("countryRelation").asText() }.toSet()
)
assertEquals(listOf(50, 75), items.map { it.path("appliedSettlementRatio").intValue() }.sorted())
assertEquals(listOf(7, 7), items.map { it.path("appliedAgentSettlementRatio").intValue() })
assertEquals(listOf(agent.id, agent.id), items.map { it.path("agentId").longValue() })
assertEquals(listOf(true, true), items.map { it.path("rateInfoAvailable").booleanValue() })
val keys = items.map { it.path("rowKey").asText() }
assertEquals(2, keys.toSet().size)
items.forEach { assertEquals(true, it.path("rowKey").isTextual && it.path("rowKey").asText().isNotBlank()) }
assertEquals(keys, pagedJson.map { it[source].path("items")[0].path("rowKey").asText() })
}
}
@Test
@DisplayName("시행 후 일반 25캔 70은 원천 binary 상수 산술의 1634원을 agent 조회와 서비스에 그대로 전달한다")
fun shouldUseSourceArithmeticForGeneralPostPolicyRows() {
val agent = saveMember("agent-source-arithmetic", MemberRole.AGENT)
val creator = saveMember("creator-source-arithmetic", MemberRole.CREATOR)
val buyer = saveMember("buyer-source-arithmetic", MemberRole.USER)
saveRelation(agent, creator)
saveCreatorSettlementRatio(creator, 70, 70, 70)
saveLiveUseCan(buyer, saveLiveRoom(creator), 25, countryBoundary)
saveOrder(buyer, creator, saveAudioContent(creator, "source-arithmetic", 25, null), countryBoundary)
saveCommunityUseCan(buyer, saveCommunityPost(creator, 25), 25, countryBoundary)
val expected = GetAgentSettlementByCreatorTotal(1, 25, 2_500, 165, 1_634, 54, 1_581, 114)
val rows = countryRows(agent.id!!).take(3).map { it.toResponseTotal() }
val totals = countryNativeTotals(agent.id!!).take(3)
val responses = countryPages(agent.id!!, 0).take(3)
assertEquals(List(3) { expected }, rows)
assertEquals(List(3) { expected }, totals)
responses.forEach {
assertEquals(expected, it.total)
assertEquals(1_634, it.items.single().settlementAmount)
assertEquals(1_581, it.items.single().depositAmount)
assertEquals(114, it.items.single().agentSettlementAmount)
}
}
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)
@@ -1090,11 +1176,11 @@ class AgentCalculateQueryRepositoryTest @Autowired constructor(
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 countryPages(agentId: Long, offset: Long, limit: Long = 1) = listOf(
service.getCalculateLiveByCreator("2026-10-31", "2026-11-01", agentId, offset, limit),
service.getCalculateContentByCreator("2026-10-31", "2026-11-01", agentId, offset, limit),
service.getCalculateCommunityByCreator("2026-10-31", "2026-11-01", agentId, offset, limit),
service.getCalculateContentDonationByCreator("2026-10-31", "2026-11-01", agentId, offset, limit)
)
private fun assertCountryResults(
@@ -1163,8 +1249,8 @@ class AgentCalculateQueryRepositoryTest @Autowired constructor(
),
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)
CountryCase("KR", "KR", null, GetAgentSettlementByCreatorTotal(2, 26, 2_600, 172, 1_761, 58, 1_703, 124)),
GetAgentChannelDonationSettlementTotal(2, 26, 2_600, 172, 1_761, 58, 1_703, 124)
),
Arguments.of(
listOf(after),
@@ -1418,29 +1504,4 @@ class AgentCalculateQueryRepositoryTest @Autowired constructor(
assertEquals(it, response.items[0].agentSettlementAmount)
}
}
private fun calculateGenericAgentSettlementAmount(totalCan: Int, settlementRatio: Int, agentSettlementRatio: Int): Int {
val totalKrw = java.math.BigDecimal(totalCan).multiply(java.math.BigDecimal("100"))
val fee = totalKrw.multiply(java.math.BigDecimal("0.066"))
val settlementAmount = totalKrw.subtract(fee)
.multiply(java.math.BigDecimal(settlementRatio).divide(java.math.BigDecimal("100")))
.setScale(0, java.math.RoundingMode.HALF_UP)
.toInt()
return java.math.BigDecimal(settlementAmount)
.multiply(java.math.BigDecimal(agentSettlementRatio).divide(java.math.BigDecimal("100")))
.setScale(0, java.math.RoundingMode.HALF_UP)
.toInt()
}
private fun calculateChannelAgentSettlementAmount(totalCan: Int, agentSettlementRatio: Int): Int {
val settlementAmount = kr.co.vividnext.sodalive.calculate.channelDonation.ChannelDonationSettlementCalculator
.calculate(totalCan)
.settlementAmount
return java.math.BigDecimal(settlementAmount)
.multiply(java.math.BigDecimal(agentSettlementRatio).divide(java.math.BigDecimal("100")))
.setScale(0, java.math.RoundingMode.HALF_UP)
.toInt()
}
}
@@ -4,17 +4,22 @@ import kr.co.vividnext.sodalive.extensions.convertLocalDateTime
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.AgentSettlementSnapshotType
import kr.co.vividnext.sodalive.partner.agent.settlement.snapshot.SnapshotStoredAmounts
import kr.co.vividnext.sodalive.partner.agent.settlement.snapshot.SnapshotStoredDisplayRow
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.mockito.Mockito
import org.mockito.invocation.InvocationOnMock
import java.time.LocalDateTime
class AgentCalculateServiceTest {
private lateinit var repository: AgentCalculateQueryRepository
private lateinit var snapshotRepository: AgentSettlementSnapshotRepository
private lateinit var service: AgentCalculateService
private val snapshotsByType = mutableMapOf<AgentSettlementSnapshotType, List<AgentSettlementSnapshot>>()
private var nextSnapshotId = 1L
@BeforeEach
fun setup() {
@@ -22,10 +27,26 @@ class AgentCalculateServiceTest {
snapshotRepository = Mockito.mock(
AgentSettlementSnapshotRepository::class.java,
Mockito.withSettings().defaultAnswer { invocation ->
if (invocation.method.name == "findAllByPeriodStartAndPeriodEndAndSettlementTypeAndAgentIdOrderByCreatorIdDesc") {
emptyList<AgentSettlementSnapshot>()
} else {
Mockito.RETURNS_DEFAULTS.answer(invocation)
when (invocation.method.name) {
"existsByPeriodStartAndPeriodEndAndSettlementTypeAndAgentId" -> storedRows(invocation).isNotEmpty()
"countSettlementDisplayRows" -> storedRows(invocation).size.toLong()
"readSettlementDisplayRows" -> storedRows(invocation)
.drop(invocation.getArgument<Long>(4).toInt())
.take(invocation.getArgument<Long>(5).toInt()).map(::StoredRow)
"readSettlementTotals" -> {
val rows = storedRows(invocation)
object : SnapshotStoredAmounts {
override val transactionCount = rows.sumOf { it.count.toLong() }
override val totalCan = rows.sumOf { it.totalCan.toLong() }
override val grossAmount = rows.sumOf { it.krw.toLong() }
override val paymentFee = rows.sumOf { it.fee.toLong() }
override val settlementAmount = rows.sumOf { it.settlementAmount.toLong() }
override val withholdingTax = rows.sumOf { it.tax.toLong() }
override val depositAmount = rows.sumOf { it.depositAmount.toLong() }
override val agentSettlementAmount = rows.sumOf { it.agentSettlementAmount.toLong() }
}
}
else -> Mockito.RETURNS_DEFAULTS.answer(invocation)
}
}
)
@@ -157,7 +178,7 @@ class AgentCalculateServiceTest {
}
@Test
@DisplayName("에이전트 서비스는 콘텐츠 크리에이터별 응답을 크리에이터 기준으로 병합하고 agent 정산금을 계산한다")
@DisplayName("시행 전 콘텐츠 응답은 기존 creator 병합과 경로별 agent 금액을 보존한다")
fun shouldMergeContentSummaryRowsPerCreator() {
val totalRows = listOf(
GetAgentCreatorSettlementSummaryQueryData(
@@ -557,17 +578,8 @@ class AgentCalculateServiceTest {
@Test
@DisplayName("에이전트 서비스는 finalized 기간이면 다섯 카테고리 모두 스냅샷을 우선 사용한다")
fun shouldUseFinalizedSnapshotsFirstAcrossAllSettlementCategories() {
val startDate = "2026-02-20".convertLocalDateTime()
val endDate = "2026-02-21".convertLocalDateTime(hour = 23, minute = 59, second = 59)
Mockito.`when`(
snapshotRepository.findAllByPeriodStartAndPeriodEndAndSettlementTypeAndAgentIdOrderByCreatorIdDesc(
startDate,
endDate,
AgentSettlementSnapshotType.LIVE,
7L
)
).thenReturn(
stubSnapshots(
AgentSettlementSnapshotType.LIVE,
listOf(
createSnapshot(
settlementType = AgentSettlementSnapshotType.LIVE,
@@ -583,14 +595,8 @@ class AgentCalculateServiceTest {
)
)
)
Mockito.`when`(
snapshotRepository.findAllByPeriodStartAndPeriodEndAndSettlementTypeAndAgentIdOrderByCreatorIdDesc(
startDate,
endDate,
AgentSettlementSnapshotType.CONTENT,
7L
)
).thenReturn(
stubSnapshots(
AgentSettlementSnapshotType.CONTENT,
listOf(
createSnapshot(
settlementType = AgentSettlementSnapshotType.CONTENT,
@@ -606,14 +612,8 @@ class AgentCalculateServiceTest {
)
)
)
Mockito.`when`(
snapshotRepository.findAllByPeriodStartAndPeriodEndAndSettlementTypeAndAgentIdOrderByCreatorIdDesc(
startDate,
endDate,
AgentSettlementSnapshotType.COMMUNITY,
7L
)
).thenReturn(
stubSnapshots(
AgentSettlementSnapshotType.COMMUNITY,
listOf(
createSnapshot(
settlementType = AgentSettlementSnapshotType.COMMUNITY,
@@ -629,14 +629,8 @@ class AgentCalculateServiceTest {
)
)
)
Mockito.`when`(
snapshotRepository.findAllByPeriodStartAndPeriodEndAndSettlementTypeAndAgentIdOrderByCreatorIdDesc(
startDate,
endDate,
AgentSettlementSnapshotType.CONTENT_DONATION,
7L
)
).thenReturn(
stubSnapshots(
AgentSettlementSnapshotType.CONTENT_DONATION,
listOf(
createSnapshot(
settlementType = AgentSettlementSnapshotType.CONTENT_DONATION,
@@ -652,14 +646,8 @@ class AgentCalculateServiceTest {
)
)
)
Mockito.`when`(
snapshotRepository.findAllByPeriodStartAndPeriodEndAndSettlementTypeAndAgentIdOrderByCreatorIdDesc(
startDate,
endDate,
AgentSettlementSnapshotType.CHANNEL_DONATION,
7L
)
).thenReturn(
stubSnapshots(
AgentSettlementSnapshotType.CHANNEL_DONATION,
listOf(
createSnapshot(
settlementType = AgentSettlementSnapshotType.CHANNEL_DONATION,
@@ -773,17 +761,8 @@ class AgentCalculateServiceTest {
@Test
@DisplayName("에이전트 서비스는 finalized snapshot을 creatorId desc 순서로 페이지 조회한다")
fun shouldPageFinalizedSnapshotsByCreatorIdDesc() {
val startDate = "2026-02-20".convertLocalDateTime()
val endDate = "2026-02-21".convertLocalDateTime(hour = 23, minute = 59, second = 59)
Mockito.`when`(
snapshotRepository.findAllByPeriodStartAndPeriodEndAndSettlementTypeAndAgentIdOrderByCreatorIdDesc(
startDate,
endDate,
AgentSettlementSnapshotType.LIVE,
7L
)
).thenReturn(
stubSnapshots(
AgentSettlementSnapshotType.LIVE,
listOf(
createSnapshot(
settlementType = AgentSettlementSnapshotType.LIVE,
@@ -839,14 +818,8 @@ class AgentCalculateServiceTest {
val startDate = "2026-02-20".convertLocalDateTime()
val endDate = "2026-02-21".convertLocalDateTime(hour = 23, minute = 59, second = 59)
Mockito.`when`(
snapshotRepository.findAllByPeriodStartAndPeriodEndAndSettlementTypeAndAgentIdOrderByCreatorIdDesc(
startDate,
endDate,
AgentSettlementSnapshotType.LIVE,
7L
)
).thenReturn(
stubSnapshots(
AgentSettlementSnapshotType.LIVE,
listOf(
createSnapshot(
settlementType = AgentSettlementSnapshotType.LIVE,
@@ -885,6 +858,46 @@ class AgentCalculateServiceTest {
Mockito.verifyNoInteractions(repository)
}
@Test
@DisplayName("시행 후 같은 creator의 75와 50 및 agent 7과 10 행은 서비스에서 다시 병합하지 않는다")
fun shouldKeepPostPolicyEconomicRowsSeparateThroughService() {
val start = "2026-11-01".convertLocalDateTime()
val end = "2026-11-01".convertLocalDateTime(hour = 23, minute = 59, second = 59)
val rows = listOf(
GetAgentCreatorSettlementSummaryQueryData(
creatorId = 21L,
creatorNickname = "creator-a",
count = 1L,
totalCan = 1,
settlementRatio = 75,
agentSettlementRatio = 7
),
GetAgentCreatorSettlementSummaryQueryData(
creatorId = 21L,
creatorNickname = "creator-a",
count = 1L,
totalCan = 2,
settlementRatio = 50,
agentSettlementRatio = 10
)
)
Mockito.`when`(repository.getCalculateLiveByCreatorTotalCount(start, end, 7L)).thenReturn(2)
Mockito.`when`(repository.getCalculateLiveByCreatorTotal(start, end, 7L)).thenReturn(
GetAgentSettlementByCreatorTotal(2, 3, 300, 20, 163, 5, 158, 14)
)
Mockito.`when`(repository.getCalculateLiveByCreator(start, end, 7L, 0L, 20L)).thenReturn(rows)
val response = service.getCalculateLiveByCreator("2026-11-01", "2026-11-01", 7L, 0L, 20L)
assertEquals(2, response.items.size)
assertEquals(listOf(21L, 21L), response.items.map { it.creatorId })
assertEquals(listOf(1, 1), response.items.map { it.count })
assertEquals(listOf(1, 2), response.items.map { it.totalCan })
assertEquals(listOf(70, 93), response.items.map { it.settlementAmount })
assertEquals(listOf(68, 90), response.items.map { it.depositAmount })
assertEquals(listOf(5, 9), response.items.map { it.agentSettlementAmount })
}
private fun createSnapshot(
settlementType: AgentSettlementSnapshotType,
count: Int,
@@ -916,6 +929,43 @@ class AgentCalculateServiceTest {
agentSettlementAmount = agentSettlementAmount,
finalizedAt = LocalDateTime.of(2026, 2, 22, 0, 0, 0),
finalizedByMemberId = 1L
)
).also { it.id = nextSnapshotId++ }
}
private fun stubSnapshots(type: AgentSettlementSnapshotType, snapshots: List<AgentSettlementSnapshot>) {
snapshotsByType[type] = snapshots
}
private fun storedRows(invocation: InvocationOnMock): List<AgentSettlementSnapshot> {
if (invocation.getArgument<LocalDateTime>(0) != "2026-02-20".convertLocalDateTime() ||
invocation.getArgument<LocalDateTime>(1) != "2026-02-21".convertLocalDateTime(hour = 23, minute = 59, second = 59) ||
invocation.getArgument<Long>(3) != 7L
) {
return emptyList()
}
val type: AgentSettlementSnapshotType = when (invocation.method.name) {
"existsByPeriodStartAndPeriodEndAndSettlementTypeAndAgentId" -> invocation.getArgument(2)
else -> AgentSettlementSnapshotType.valueOf(invocation.getArgument(2))
}
return snapshotsByType[type].orEmpty()
}
private class StoredRow(private val snapshot: AgentSettlementSnapshot) : SnapshotStoredDisplayRow {
override val rowKey get() = "ss0|${snapshot.id}"
override val creatorId get() = snapshot.creatorId
override val creatorNickname get() = snapshot.creatorNickname
override val countryRelation: String? = null
override val appliedSettlementRatio: Int? = null
override val agentId get() = snapshot.agentId
override val appliedAgentSettlementRatio get() = snapshot.appliedAgentSettlementRatio
override val rateInfoAvailable = 0
override val transactionCount get() = snapshot.count.toLong()
override val totalCan get() = snapshot.totalCan.toLong()
override val grossAmount get() = snapshot.krw.toLong()
override val paymentFee get() = snapshot.fee.toLong()
override val settlementAmount get() = snapshot.settlementAmount.toLong()
override val withholdingTax get() = snapshot.tax.toLong()
override val depositAmount get() = snapshot.depositAmount.toLong()
override val agentSettlementAmount get() = snapshot.agentSettlementAmount.toLong()
}
}
@@ -18,7 +18,7 @@ import kr.co.vividnext.sodalive.partner.agent.settlement.snapshot.AgentSettlemen
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.adapter.out.persistence.CanonicalSettlementQueryRepository
import kr.co.vividnext.sodalive.v2.settlement.domain.CountrySettlementPolicy
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.BeforeEach
@@ -52,12 +52,18 @@ class AgentCountrySettlementSnapshotTest @Autowired constructor(
@BeforeEach
fun setup() {
entityManager.createNativeQuery(
"CREATE ALIAS IF NOT EXISTS DATE_FORMAT FOR 'kr.co.vividnext.sodalive.support.H2MysqlDateFunctions.dateFormat'"
).executeUpdate()
entityManager.createNativeQuery(
"CREATE ALIAS IF NOT EXISTS CONVERT_TZ FOR 'kr.co.vividnext.sodalive.support.H2MysqlDateFunctions.convertTz'"
).executeUpdate()
val policy = CountrySettlementPolicy()
val calculateRepository = AgentCalculateQueryRepository(
queryFactory,
entityManager,
"https://cdn.test",
CountrySettlementExpressions(policy),
CanonicalSettlementQueryRepository(entityManager, policy),
policy
)
service = AdminAgentSettlementSnapshotService(
@@ -110,7 +116,7 @@ class AgentCountrySettlementSnapshotTest @Autowired constructor(
assertEquals(stored.id, detail.snapshot.id)
assertEquals(assignment.id, detail.assignmentId)
assertEquals(null, detail.agentSettlementRatioId)
assertEquals(null, detail.appliedAgentSettlementRatio)
assertEquals(7, detail.appliedAgentSettlementRatio)
assertEquals(
expected,
listOf(
@@ -0,0 +1,271 @@
package kr.co.vividnext.sodalive.partner.agent.calculate
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.ObjectMapper
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.jwt.TokenProvider
import kr.co.vividnext.sodalive.live.room.LiveRoom
import kr.co.vividnext.sodalive.member.Member
import kr.co.vividnext.sodalive.member.MemberRole
import kr.co.vividnext.sodalive.member.token.MemberTokenRepository
import kr.co.vividnext.sodalive.partner.agent.assignment.AgentCreatorRelation
import kr.co.vividnext.sodalive.partner.agent.ratio.AgentSettlementRatio
import kr.co.vividnext.sodalive.support.EmbeddedRedisInitializer
import kr.co.vividnext.sodalive.v2.api.creator.settlement.MonthlySettlementHttpTestSupport
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.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.LocalDateTime
import java.util.UUID
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 RateSeparatedAgentLiveIntegrationTest @Autowired constructor(
private val entityManager: EntityManager,
private val transactionTemplate: TransactionTemplate,
restTemplate: TestRestTemplate,
objectMapper: ObjectMapper,
tokenProvider: TokenProvider,
private val tokenRepository: MemberTokenRepository
) {
private val http = MonthlySettlementHttpTestSupport(restTemplate, objectMapper, tokenProvider)
private val created = mutableListOf<BaseEntity>()
private val eventAt = LocalDateTime.of(2026, 10, 31, 15, 0)
private val routes = listOf("live-by-creator", "channel-donation-by-creator")
@BeforeEach
fun initializeDateFunctions() {
transactionTemplate.executeWithoutResult {
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()
}
}
@AfterEach
fun cleanupOwnedFixturesAndTokens() {
try {
http.removeIssuedTokens(tokenRepository)
} finally {
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()
}
}
@Test
@DisplayName("실제 agent 라이브와 채널 Bearer HTTP는 같은 creator의 75와 50 행 및 페이지별 키와 전체 합계를 보존한다")
fun shouldReturnSeparatedEconomicRowsAndStablePagesThroughBearerHttp() {
lateinit var creator: Member
val agent = requireNotNull(
transactionTemplate.execute {
val agent = member(MemberRole.AGENT)
creator = member(MemberRole.CREATOR)
val sender = member(MemberRole.USER)
save(
AgentCreatorRelation().apply {
this.agent = agent
this.creator = creator
assignedAt = eventAt
}
)
val room = save(
LiveRoom("agent-live", "notice", eventAt, 1, isAdult = false, price = 1).apply { member = creator }
)
listOf(1 to "KR", 2 to "JP").forEach { (can, country) ->
usage(
UseCan(CanUsage.LIVE, can, 0, countryCode = country).apply {
member = sender
this.room = room
}
)
val donation = usage(
UseCan(CanUsage.CHANNEL_DONATION, can, 0, countryCode = country).apply {
member = sender
}
)
save(
UseCanCalculate(can, PaymentGateway.PG, UseCanCalculateStatus.RECEIVED).apply {
useCan = donation
recipientCreatorId = creator.id
}
)
}
entityManager.flush()
entityManager.clear()
agent
}
)
routes.forEach { route ->
val full = http.success(http.get(agent, path(route, 0, 20)))
val pages = (0..2).map { http.success(http.get(agent, path(route, it, 1))) }
val channel = route == "channel-donation-by-creator"
val expected = if (channel) {
listOf(2, 3, 300, 20, 164, 5, 159, 12)
} else {
listOf(2, 3, 300, 20, 163, 5, 158, 12)
}
assertEquals(2, full.path("totalCount").intValue())
assertEquals(2, full.path("items").size())
assertMoney(full.path("total"), expected)
pages.forEachIndexed { page, data ->
assertEquals(2, data.path("totalCount").intValue())
assertMoney(data.path("total"), expected)
assertEquals(if (page == 2) 0 else 1, data.path("items").size())
}
val items = full.path("items").toList()
val byRelation = items.associateBy { it.path("countryRelation").asText() }
assertEquals(setOf("SAME_COUNTRY", "CROSS_COUNTRY"), byRelation.keys)
val same = requireNotNull(byRelation["SAME_COUNTRY"])
val cross = requireNotNull(byRelation["CROSS_COUNTRY"])
assertEquals(75, same.path("appliedSettlementRatio").intValue())
assertEquals(50, cross.path("appliedSettlementRatio").intValue())
assertMoney(same, listOf(1, 1, 100, 7, 70, 2, 68, 5))
assertMoney(
cross,
if (channel) listOf(1, 2, 200, 13, 94, 3, 91, 7) else listOf(1, 2, 200, 13, 93, 3, 90, 7)
)
items.forEach { item ->
assertEquals(creator.id, item.path("creatorId").longValue())
assertEquals(agent.id, item.path("agentId").longValue())
assertEquals(7, item.path("appliedAgentSettlementRatio").intValue())
assertEquals(true, item.path("rateInfoAvailable").booleanValue())
assertEquals(true, item.path("rowKey").isTextual && item.path("rowKey").asText().isNotBlank())
}
val keys = items.map { it.path("rowKey").asText() }
assertEquals(2, keys.toSet().size)
assertEquals(keys, pages.take(2).map { it.path("items")[0].path("rowKey").asText() })
}
}
@ParameterizedTest
@ValueSource(ints = [7, 10])
@DisplayName("실제 HTTP는 기본 7과 명시 7의 이력 ID 변경을 합치고 실제 10으로 바뀌면 271원과 agent 26원을 반환한다")
fun shouldSplitOnlyActualAgentEconomicsThroughBearerHttp(nextRatio: Int) {
val switchAt = eventAt.plusSeconds(10)
val agent = requireNotNull(
transactionTemplate.execute {
val agent = member(MemberRole.AGENT)
val creator = member(MemberRole.CREATOR)
val sender = member(MemberRole.USER)
save(
AgentCreatorRelation().apply {
this.agent = agent
this.creator = creator
assignedAt = eventAt
unassignedAt = switchAt
}
)
save(
AgentCreatorRelation().apply {
this.agent = agent
this.creator = creator
assignedAt = switchAt
}
)
save(AgentSettlementRatio(nextRatio, switchAt).apply { member = agent })
listOf(1 to eventAt, 3 to switchAt).forEach { (can, at) ->
val donation = usage(
UseCan(CanUsage.CHANNEL_DONATION, can, 0, countryCode = "KR").apply {
member = sender
}
).apply { createdAt = at }
save(
UseCanCalculate(can, PaymentGateway.PG, UseCanCalculateStatus.RECEIVED).apply {
useCan = donation
recipientCreatorId = creator.id
}
)
}
entityManager.flush()
entityManager.clear()
agent
}
)
val data = http.success(http.get(agent, path("channel-donation-by-creator", 0, 20)))
val split = nextRatio == 10
assertEquals(if (split) 2 else 1, data.path("totalCount").intValue())
assertEquals(if (split) 2 else 1, data.path("items").size())
assertMoney(
data.path("total"),
if (split) listOf(2, 4, 400, 27, 280, 9, 271, 26) else listOf(2, 4, 400, 26, 281, 9, 272, 20)
)
val items = data.path("items").sortedBy { it.path("appliedAgentSettlementRatio").intValue() }
assertEquals(
if (split) listOf(7, 10) else listOf(7),
items.map { it.path("appliedAgentSettlementRatio").intValue() }
)
assertEquals(List(items.size) { 75 }, items.map { it.path("appliedSettlementRatio").intValue() })
assertEquals(List(items.size) { "SAME_COUNTRY" }, items.map { it.path("countryRelation").asText() })
assertEquals(List(items.size) { true }, items.map { it.path("rateInfoAvailable").booleanValue() })
if (split) {
assertMoney(items[0], listOf(1, 1, 100, 7, 70, 2, 68, 5))
assertMoney(items[1], listOf(1, 3, 300, 20, 210, 7, 203, 21))
} else {
assertMoney(items.single(), listOf(2, 4, 400, 26, 281, 9, 272, 20))
}
}
@Test
@DisplayName("실제 agent 정산 HTTP는 Bearer 없는 요청을 기존 보안 체인의 401로 거부한다")
fun shouldRejectMissingBearerThroughHttp() {
assertEquals(HttpStatus.UNAUTHORIZED, http.get(null, path("live-by-creator", 0, 1)).statusCode)
}
private fun path(route: String, page: Int, size: Int) =
"/agent/calculate/$route?startDateStr=2026-11-01&endDateStr=2026-11-01&page=$page&size=$size"
private fun assertMoney(actual: JsonNode, expected: List<Int>) {
val fields = listOf("count", "totalCan", "krw", "fee", "settlementAmount", "depositAmount", "agentSettlementAmount")
val tax = if (actual.has("withholdingTax")) "withholdingTax" else "tax"
val ordered = fields.take(5) + tax + fields.drop(5)
ordered.forEach { assertEquals(true, actual.path(it).isIntegralNumber, "$it: $actual") }
assertEquals(expected, ordered.map { actual.path(it).intValue() }, actual.toString())
}
private fun member(role: MemberRole): Member = save(
Member(password = "password", nickname = "agent-http-${UUID.randomUUID()}", role = role, countryCode = "KR")
)
private fun usage(useCan: UseCan): UseCan = save(useCan).apply { createdAt = eventAt }
private fun <T : BaseEntity> save(entity: T): T {
entityManager.persist(entity)
created.add(entity)
return entity
}
}
@@ -0,0 +1,160 @@
package kr.co.vividnext.sodalive.partner.agent.settlement.snapshot
import com.fasterxml.jackson.core.type.TypeReference
import kr.co.vividnext.sodalive.member.Member
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementProvenance
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementRowKey
import org.hibernate.Session
import org.junit.jupiter.api.Assertions.assertEquals
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 java.util.stream.Stream
class RateSeparatedSnapshotPersistenceTest : SnapshotRegressionTestSupport() {
@ParameterizedTest
@MethodSource("historyCases")
@DisplayName("확정 DB 왕복은 같은 경제 조건을 한 번만 계산하고 null 비율 이력을 포함한 모든 참조 쌍을 보존한다")
fun shouldPersistOneCanonicalMoneyRowWithEveryHistoryPair(type: AgentSettlementSnapshotType, defaultFirst: Boolean) {
val (key, provenance) = seedHistory(type, defaultFirst)
val expectedCount = if (type == AgentSettlementSnapshotType.CONTENT) 4 else 3
val expected = when (type) {
AgentSettlementSnapshotType.CHANNEL_DONATION -> listOf(expectedCount, 4, 400, 26, 281, 9, 272, 20)
AgentSettlementSnapshotType.LIVE, AgentSettlementSnapshotType.CONTENT,
AgentSettlementSnapshotType.CONTENT_DONATION, AgentSettlementSnapshotType.COMMUNITY ->
listOf(expectedCount, 4, 400, 26, 280, 9, 271, 20)
}
val finalized = finalizer.finalizeSnapshots(request(type), 99L)
flushAndClear()
val summaries = snapshotRepository.findAll()
val details = detailRepository.findAll()
val response = page(type)
assertEquals(false, finalized.alreadyFinalized)
assertEquals(1, finalized.finalizedCount)
assertEquals(1, summaries.size)
assertEquals(1, details.size, "History IDs must not create extra monetary rows or extra rounding")
val stored = summaries.single()
assertEquals(request(type).toDateRange(), stored.periodStart to stored.periodEnd)
assertEquals(0, stored.finalizedAt.nano, "finalized_at is TIMESTAMP without fractional precision")
assertEquals(99L, stored.finalizedByMemberId)
assertEquals(null, stored.assignmentId)
assertEquals(null, stored.agentSettlementRatioId)
assertEquals(expected, snapshotMoney(stored))
assertEquals(stored.id, details.single().snapshot.id)
assertEquals(expected, snapshotMoney(details.single()))
assertEquals(1, response.path("totalCount").intValue())
assertEquals(expected, money(response.path("total")))
assertEquals(1, response.path("items").size())
val item = response.path("items").single()
assertEquals(true, item.path("rateInfoAvailable").booleanValue())
assertEquals("SAME_COUNTRY", item.path("countryRelation").asText())
assertEquals(75, item.path("appliedSettlementRatio").intValue())
assertEquals(agent.id, item.path("agentId").longValue())
assertEquals(7, item.path("appliedAgentSettlementRatio").intValue())
assertEquals(SettlementRowKey.creator(key.source, key.creatorId, key.economics), item.path("rowKey").asText())
assertEquals(expected, money(item))
// Check physical columns only after the existing response exposes complete persisted metadata.
entityManager.unwrap(Session::class.java).doWork { connection ->
connection.prepareStatement(
"SELECT canonical_row_key, country_relation, applied_settlement_ratio, rate_info_available, provenance_json " +
"FROM agent_settlement_snapshot_source_detail WHERE snapshot_id = ?"
).use { statement ->
statement.setLong(1, requireNotNull(stored.id))
statement.executeQuery().use { rows ->
assertEquals(true, rows.next())
assertEquals(SettlementRowKey.canonical(key), rows.getString("canonical_row_key"))
assertEquals("SAME_COUNTRY", rows.getString("country_relation"))
assertEquals(75, rows.getInt("applied_settlement_ratio"))
assertEquals(true, rows.getBoolean("rate_info_available"))
val pairs = objectMapper.readValue(
rows.getString("provenance_json"),
object : TypeReference<List<SettlementProvenance>>() {}
)
assertEquals(3, pairs.size)
assertEquals(provenance.toSet(), pairs.toSet())
assertEquals(false, rows.next())
}
}
}
}
@ParameterizedTest
@EnumSource(value = AgentSettlementSnapshotType::class, names = ["LIVE", "CHANNEL_DONATION"])
@DisplayName("현재 국가 비율 닉네임 변경과 재확정은 저장된 정산액 건수 표시 키 확정 시각을 바꾸지 않는다")
fun shouldKeepStoredRowsWhenCurrentInputsChangeAndFinalizationRepeats(type: AgentSettlementSnapshotType) {
seedHistory(type, defaultFirst = true)
finalizer.finalizeSnapshots(request(type), 99L)
flushAndClear()
val before = page(type)
val stored = snapshotRepository.findAll().single()
val id = requireNotNull(stored.id)
val finalizedAt = stored.finalizedAt
val detailsBefore = detailRepository.findAll()
assertEquals(1, detailsBefore.size)
val detailId = detailsBefore.single().id
val expected = when (type) {
AgentSettlementSnapshotType.CHANNEL_DONATION -> listOf(3, 4, 400, 26, 281, 9, 272, 20)
AgentSettlementSnapshotType.LIVE, AgentSettlementSnapshotType.CONTENT,
AgentSettlementSnapshotType.CONTENT_DONATION, AgentSettlementSnapshotType.COMMUNITY ->
listOf(3, 4, 400, 26, 280, 9, 271, 20)
}
assertEquals(expected, money(before.path("total")))
entityManager.find(Member::class.java, creator.id).apply {
countryCode = "JP"
nickname = "changed-after-finalization"
}
entityManager.createQuery("update AgentSettlementRatio r set r.settlementRatio = 99 where r.member.id = :id")
.setParameter("id", agent.id).executeUpdate()
flushAndClear()
val first = finalizer.finalizeSnapshots(request(type), 100L)
val second = finalizer.finalizeSnapshots(request(type), 101L)
flushAndClear()
val saved = snapshotRepository.findAll().single()
val detail = detailRepository.findAll().single()
assertEquals(listOf(true, true), listOf(first.alreadyFinalized, second.alreadyFinalized))
assertEquals(listOf(0, 0), listOf(first.finalizedCount, second.finalizedCount))
assertEquals(id, saved.id)
assertEquals(finalizedAt, saved.finalizedAt)
assertEquals(99L, saved.finalizedByMemberId)
assertEquals(detailId, detail.id)
assertEquals(expected, snapshotMoney(saved))
assertEquals(expected, snapshotMoney(detail))
assertEquals(before, page(type))
}
companion object {
@JvmStatic
fun historyCases(): Stream<Arguments> = AgentSettlementSnapshotType.values().flatMap { type ->
listOf(Arguments.of(type, false), Arguments.of(type, true))
}.stream()
}
}
internal fun snapshotMoney(snapshot: AgentSettlementSnapshot): List<Int> = listOf(
snapshot.count,
snapshot.totalCan,
snapshot.krw,
snapshot.fee,
snapshot.settlementAmount,
snapshot.tax,
snapshot.depositAmount,
snapshot.agentSettlementAmount
)
internal fun snapshotMoney(detail: AgentSettlementSnapshotSourceDetail): List<Int> = listOf(
detail.count,
detail.totalCan,
detail.krw,
detail.fee,
detail.settlementAmount,
detail.tax,
detail.depositAmount,
detail.agentSettlementAmount
)
@@ -0,0 +1,168 @@
package kr.co.vividnext.sodalive.partner.agent.settlement.snapshot
import kr.co.vividnext.sodalive.member.Member
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementCanonicalKey
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementCountryRelation
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementEconomics
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementRowKey
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementSource
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementSourceGrain
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.ValueSource
class RateSeparatedSnapshotQueryRepositoryTest : SnapshotRegressionTestSupport() {
@Test
@DisplayName("확정 HTTP는 세 canonical 상세를 두 최종 키로 페이지하고 빈 페이지에서도 root 금액과 거래 건수를 유지한다")
fun shouldPageFinalDisplayKeysAndKeepRootTotalsThroughHttp() {
seedChannelDisplayRows()
val result = finalizer.finalizeSnapshots(request(AgentSettlementSnapshotType.CHANNEL_DONATION), 99L)
flushAndClear()
assertEquals(1, result.finalizedCount)
assertEquals(1L, snapshotRepository.count())
assertEquals(3L, detailRepository.count())
val full = channelHttpPage(0, 20)
val pages = (0..2).map { channelHttpPage(it) }
val expectedTotal = listOf(3, 4, 400, 27, 234, 7, 227, 17)
assertEquals(2, full.path("totalCount").intValue())
assertEquals(2, full.path("items").size())
assertEquals(expectedTotal, money(full.path("total")))
pages.forEachIndexed { offset, page ->
assertEquals(2, page.path("totalCount").intValue())
assertEquals(expectedTotal, money(page.path("total")))
assertEquals(if (offset == 2) 0 else 1, page.path("items").size())
}
assertEquals(channelDisplayKeys(), full.path("items").map { it.path("rowKey").asText() })
assertEquals(full.path("items").toList(), pages.take(2).flatMap { it.path("items").toList() })
val byRelation = full.path("items").associateBy { it.path("countryRelation").asText() }
assertEquals(setOf("SAME_COUNTRY", "CROSS_COUNTRY"), byRelation.keys)
assertEquals(75, byRelation.getValue("SAME_COUNTRY").path("appliedSettlementRatio").intValue())
assertEquals(50, byRelation.getValue("CROSS_COUNTRY").path("appliedSettlementRatio").intValue())
assertEquals(listOf(2, 2, 200, 14, 140, 4, 136, 10), money(byRelation.getValue("SAME_COUNTRY")))
assertEquals(listOf(1, 2, 200, 13, 94, 3, 91, 7), money(byRelation.getValue("CROSS_COUNTRY")))
full.path("items").forEach { item ->
assertEquals(true, item.path("rateInfoAvailable").booleanValue())
assertEquals(creator.nickname, item.path("creatorNickname").asText())
assertEquals(agent.id, item.path("agentId").longValue())
assertEquals(7, item.path("appliedAgentSettlementRatio").intValue())
}
}
@ParameterizedTest
@ValueSource(booleans = [false, true])
@DisplayName("완전한 상세와 부분 키 및 키 없는 과거 확정이 섞여도 snapshot별 fallback은 요약과 상세를 중복 합산하지 않는다")
fun shouldFallbackPerSnapshotWithoutRepricingOrDoubleCounting(legacyHasDetails: Boolean) {
seedChannelDisplayRows()
val type = AgentSettlementSnapshotType.CHANNEL_DONATION
finalizer.finalizeSnapshots(request(type), 99L)
flushAndClear()
// This is an assertion RED on today's API, before fixture SQL mentions future columns.
assertEquals(2, channelHttpPage(0, 20).path("totalCount").intValue())
val complete = snapshotRepository.findAll().single()
val completeKeys = channelDisplayKeys()
val partial = historicalSummary(listOf(7, 13, 1_300, 86, 850, 28, 822, 60))
val legacy = historicalSummary(listOf(11, 17, 1_700, 112, 1_111, 37, 1_074, 78))
val keyedDetail = historicalDetail(partial, listOf(3, 4, 400, 26, 262, 9, 253, 18))
historicalDetail(partial, listOf(4, 9, 900, 60, 588, 19, 569, 42))
if (legacyHasDetails) {
historicalDetail(legacy, listOf(5, 8, 800, 53, 523, 17, 506, 37))
historicalDetail(legacy, listOf(6, 9, 900, 59, 588, 20, 568, 41))
}
entityManager.flush()
val canonicalKey = SettlementRowKey.canonical(
SettlementCanonicalKey(
SettlementSource.CHANNEL_DONATION,
partial.creatorId,
SettlementEconomics(SettlementCountryRelation.SAME_COUNTRY, 75, agent.id, 7),
SettlementSourceGrain(partial.creatorId, eventAt.plusHours(9).toLocalDate(), null, null, null, null)
)
)
entityManager.createNativeQuery(
"UPDATE agent_settlement_snapshot_source_detail SET canonical_row_key = :key, " +
"country_relation = 'SAME_COUNTRY', applied_settlement_ratio = 75, rate_info_available = TRUE, " +
"provenance_json = '[]' WHERE id = :id"
).setParameter("key", canonicalKey).setParameter("id", keyedDetail.id).executeUpdate()
entityManager.find(Member::class.java, creator.id).apply {
nickname = "current-name-must-not-replace-snapshot"
countryCode = "JP"
}
flushAndClear()
val full = channelHttpPage(0, 20)
val pages = (0..4).map { channelHttpPage(it) }
val expectedTotal = listOf(21, 34, 3_400, 225, 2_195, 72, 2_123, 155)
assertEquals(4, full.path("totalCount").intValue())
assertEquals(4, full.path("items").size())
assertEquals(expectedTotal, money(full.path("total")))
pages.forEachIndexed { offset, page ->
assertEquals(4, page.path("totalCount").intValue())
assertEquals(expectedTotal, money(page.path("total")))
assertEquals(if (offset == 4) 0 else 1, page.path("items").size())
}
assertEquals(full.path("items").toList(), pages.take(4).flatMap { it.path("items").toList() })
val items = full.path("items").associateBy { it.path("rowKey").asText() }
assertEquals(
completeKeys.toSet() + setOf("ss0|${partial.id}", "ss0|${legacy.id}"),
items.keys
)
listOf(partial, legacy).forEach { stored ->
val item = items.getValue("ss0|${stored.id}")
assertEquals(snapshotMoney(stored), money(item))
assertEquals(stored.creatorNickname, item.path("creatorNickname").asText())
assertEquals(false, item.path("rateInfoAvailable").booleanValue())
assertEquals(true, item.path("countryRelation").isNull)
assertEquals(true, item.path("appliedSettlementRatio").isNull)
}
val completeItems = full.path("items").filter { it.path("creatorId").longValue() == creator.id }
assertEquals(2, completeItems.size)
completeItems.forEach { assertEquals(creator.nickname, it.path("creatorNickname").asText()) }
flushAndClear()
val stored = snapshotRepository.findAll().associateBy { it.id }
assertEquals(3, stored.size)
listOf(partial, legacy).forEach {
assertEquals(eventAt.withHour(23).withMinute(59).withSecond(59), stored.getValue(it.id).finalizedAt)
assertEquals(55L, stored.getValue(it.id).finalizedByMemberId)
}
assertEquals(
listOf(3, 4, 400, 27, 234, 7, 227, 17),
snapshotMoney(stored.getValue(complete.id))
)
assertEquals(
listOf(7, 13, 1_300, 86, 850, 28, 822, 60),
snapshotMoney(stored.getValue(partial.id))
)
assertEquals(
listOf(11, 17, 1_700, 112, 1_111, 37, 1_074, 78),
snapshotMoney(stored.getValue(legacy.id))
)
}
private fun historicalSummary(amount: List<Int>): AgentSettlementSnapshot {
val member = newCreator()
val (start, end) = request(AgentSettlementSnapshotType.CHANNEL_DONATION).toDateRange()
return snapshotRepository.save(
AgentSettlementSnapshot(
periodStart = start, periodEnd = end, settlementType = AgentSettlementSnapshotType.CHANNEL_DONATION,
agentId = requireNotNull(agent.id), agentNickname = agent.nickname,
creatorId = requireNotNull(member.id), creatorNickname = member.nickname,
count = amount[0], totalCan = amount[1], krw = amount[2], fee = amount[3],
settlementAmount = amount[4], tax = amount[5], depositAmount = amount[6], agentSettlementAmount = amount[7],
finalizedAt = eventAt.withHour(23).withMinute(59).withSecond(59), finalizedByMemberId = 55L
)
)
}
private fun historicalDetail(snapshot: AgentSettlementSnapshot, amount: List<Int>): AgentSettlementSnapshotSourceDetail =
detailRepository.save(
AgentSettlementSnapshotSourceDetail(
snapshot = snapshot,
count = amount[0], totalCan = amount[1], krw = amount[2], fee = amount[3],
settlementAmount = amount[4], tax = amount[5], depositAmount = amount[6], agentSettlementAmount = amount[7]
)
)
}
@@ -0,0 +1,275 @@
package kr.co.vividnext.sodalive.partner.agent.settlement.snapshot
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.ObjectMapper
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.content.order.OrderType
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.MemberAdapter
import kr.co.vividnext.sodalive.member.MemberRole
import kr.co.vividnext.sodalive.partner.agent.assignment.AgentCreatorRelation
import kr.co.vividnext.sodalive.partner.agent.calculate.AgentCalculateService
import kr.co.vividnext.sodalive.partner.agent.ratio.AgentSettlementRatio
import kr.co.vividnext.sodalive.support.EmbeddedRedisInitializer
import kr.co.vividnext.sodalive.v2.api.creator.settlement.MonthlySettlementHttpFixture
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementCanonicalKey
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementCountryRelation
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementEconomics
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementProvenance
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementRowKey
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementSource
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementSourceGrain
import org.hibernate.Session
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.BeforeEach
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user
import org.springframework.test.context.ContextConfiguration
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status
import org.springframework.transaction.PlatformTransactionManager
import org.springframework.transaction.annotation.Transactional
import org.springframework.transaction.support.TransactionTemplate
import java.time.LocalDateTime
import javax.persistence.EntityManager
@SpringBootTest(properties = ["spring.cache.type=none"])
@AutoConfigureMockMvc
@ContextConfiguration(initializers = [EmbeddedRedisInitializer::class])
@Transactional
abstract class SnapshotRegressionTestSupport {
@Autowired
protected lateinit var entityManager: EntityManager
@Autowired
protected lateinit var snapshotRepository: AgentSettlementSnapshotRepository
@Autowired
protected lateinit var detailRepository: AgentSettlementSnapshotSourceDetailRepository
@Autowired
protected lateinit var finalizer: AdminAgentSettlementSnapshotService
@Autowired
protected lateinit var calculateService: AgentCalculateService
@Autowired
protected lateinit var objectMapper: ObjectMapper
@Autowired
private lateinit var transactionManager: PlatformTransactionManager
@Autowired
private lateinit var mockMvc: MockMvc
private lateinit var fixture: MonthlySettlementHttpFixture
protected lateinit var agent: Member
protected lateinit var creator: Member
protected val eventAt: LocalDateTime = LocalDateTime.of(2026, 11, 2, 3, 0)
@BeforeEach
fun initializeSnapshotFixture() {
fixture = MonthlySettlementHttpFixture(entityManager, TransactionTemplate(transactionManager))
val database = entityManager.unwrap(Session::class.java).doReturningWork { it.metaData.databaseProductName }
if (database == "H2") fixture.initialize()
agent = fixture.member(MemberRole.AGENT)
creator = fixture.member(MemberRole.CREATOR)
}
protected fun request(type: AgentSettlementSnapshotType) = FinalizeAgentSettlementSnapshotRequest(
requireNotNull(agent.id),
type,
"2026-11-02",
"2026-11-03"
)
protected fun flushAndClear() {
entityManager.flush()
entityManager.clear()
}
protected fun newCreator(): Member = fixture.member(MemberRole.CREATOR)
protected fun relation(member: Member, window: Pair<LocalDateTime, LocalDateTime?>): AgentCreatorRelation =
AgentCreatorRelation().apply {
agent = this@SnapshotRegressionTestSupport.agent
creator = member
assignedAt = window.first
unassignedAt = window.second
entityManager.persist(this)
}
protected fun seedHistory(
type: AgentSettlementSnapshotType,
defaultFirst: Boolean
): Pair<SettlementCanonicalKey, List<SettlementProvenance>> {
val cut = eventAt.plusHours(1)
val rateCut = eventAt.plusMinutes(30)
val first = relation(creator, eventAt.minusDays(1) to cut)
val second = relation(creator, cut to null)
val firstRatio = if (defaultFirst) {
null
} else {
AgentSettlementRatio(7, eventAt.minusDays(1)).apply {
member = agent
effectiveTo = rateCut
entityManager.persist(this)
}
}
val secondRatio = AgentSettlementRatio(7, rateCut).apply {
member = agent
entityManager.persist(this)
}
val spends = listOf(1 to eventAt, 1 to rateCut, 2 to cut)
val sourceId = when (type) {
AgentSettlementSnapshotType.LIVE -> {
val room = LiveRoom("snapshot-live", "notice", eventAt, 1, isAdult = false, price = 1).apply {
member = creator
entityManager.persist(this)
}
spends.forEach { (can, at) ->
fixture.usage(UseCan(CanUsage.LIVE, can, 0, countryCode = "KR").apply { this.room = room }, at)
}
requireNotNull(room.id)
}
AgentSettlementSnapshotType.CONTENT -> {
val content = fixture.content(creator)
spends.forEach { (can, at) ->
repeat(can) { fixture.order(content, 1, at) }
}
requireNotNull(content.id)
}
AgentSettlementSnapshotType.CONTENT_DONATION -> {
val content = fixture.content(creator)
spends.forEach { (can, at) ->
fixture.usage(
UseCan(CanUsage.DONATION, can, 0, countryCode = "KR").apply {
audioContent = content
},
at
)
}
requireNotNull(content.id)
}
AgentSettlementSnapshotType.COMMUNITY -> {
val post = CreatorCommunity("snapshot-post", 1, true, false).apply {
member = creator
entityManager.persist(this)
}
spends.forEach { (can, at) ->
fixture.usage(
UseCan(CanUsage.PAID_COMMUNITY_POST, can, 0, countryCode = "KR").apply {
communityPost = post
},
at
)
}
requireNotNull(post.id)
}
AgentSettlementSnapshotType.CHANNEL_DONATION -> {
spends.forEach { (can, at) -> fixture.channelDonation(creator, can, at) }
requireNotNull(creator.id)
}
}
val source = when (type) {
AgentSettlementSnapshotType.LIVE -> SettlementSource.LIVE
AgentSettlementSnapshotType.CONTENT -> SettlementSource.CONTENT_SALES
AgentSettlementSnapshotType.CONTENT_DONATION -> SettlementSource.CONTENT_DONATION
AgentSettlementSnapshotType.COMMUNITY -> SettlementSource.COMMUNITY_POST
AgentSettlementSnapshotType.CHANNEL_DONATION -> SettlementSource.CHANNEL_DONATION
}
val grain = when (type) {
AgentSettlementSnapshotType.LIVE -> SettlementSourceGrain(sourceId, null, CanUsage.LIVE, null, null, null)
AgentSettlementSnapshotType.CONTENT ->
SettlementSourceGrain(sourceId, eventAt.plusHours(9).toLocalDate(), null, OrderType.KEEP, 1, 0)
AgentSettlementSnapshotType.CONTENT_DONATION, AgentSettlementSnapshotType.COMMUNITY,
AgentSettlementSnapshotType.CHANNEL_DONATION ->
SettlementSourceGrain(sourceId, eventAt.plusHours(9).toLocalDate(), null, null, null, null)
}
val key = SettlementCanonicalKey(
source,
requireNotNull(creator.id),
SettlementEconomics(SettlementCountryRelation.SAME_COUNTRY, 75, agent.id, 7),
grain
)
flushAndClear()
return key to listOf(
SettlementProvenance(first.id, firstRatio?.id),
SettlementProvenance(first.id, secondRatio.id),
SettlementProvenance(second.id, secondRatio.id)
)
}
protected fun seedChannelDisplayRows() {
relation(creator, eventAt.minusDays(1) to null)
fixture.channelDonation(creator, 1, eventAt)
fixture.channelDonation(creator, 1, eventAt.plusDays(1))
val cross = fixture.usage(UseCan(CanUsage.CHANNEL_DONATION, 2, 0, countryCode = "JP"), eventAt)
entityManager.persist(
UseCanCalculate(2, PaymentGateway.PG, UseCanCalculateStatus.RECEIVED).apply {
useCan = cross
recipientCreatorId = creator.id
}
)
flushAndClear()
}
protected fun page(type: AgentSettlementSnapshotType): JsonNode {
val id = requireNotNull(agent.id)
return when (type) {
AgentSettlementSnapshotType.LIVE ->
objectMapper.valueToTree(calculateService.getCalculateLiveByCreator("2026-11-02", "2026-11-03", id, 0, 20))
AgentSettlementSnapshotType.CONTENT ->
objectMapper.valueToTree(calculateService.getCalculateContentByCreator("2026-11-02", "2026-11-03", id, 0, 20))
AgentSettlementSnapshotType.CONTENT_DONATION ->
objectMapper.valueToTree(
calculateService.getCalculateContentDonationByCreator("2026-11-02", "2026-11-03", id, 0, 20)
)
AgentSettlementSnapshotType.COMMUNITY ->
objectMapper.valueToTree(
calculateService.getCalculateCommunityByCreator("2026-11-02", "2026-11-03", id, 0, 20)
)
AgentSettlementSnapshotType.CHANNEL_DONATION ->
objectMapper.valueToTree(calculateService.getChannelDonationByCreator("2026-11-02", "2026-11-03", id, 0, 20))
}
}
protected fun channelDisplayKeys(): List<String> = listOf(
SettlementEconomics(SettlementCountryRelation.SAME_COUNTRY, 75, agent.id, 7),
SettlementEconomics(SettlementCountryRelation.CROSS_COUNTRY, 50, agent.id, 7)
).map {
SettlementRowKey.creator(
SettlementSource.CHANNEL_DONATION,
requireNotNull(creator.id),
it
)
}.sorted()
protected fun channelHttpPage(offset: Int, size: Int = 1): JsonNode {
val result = mockMvc.perform(
get("/agent/calculate/channel-donation-by-creator")
.param("startDateStr", "2026-11-02").param("endDateStr", "2026-11-03")
.param("page", offset.toString()).param("size", size.toString())
.with(user(MemberAdapter(entityManager.find(Member::class.java, agent.id))))
).andExpect(status().isOk).andReturn()
val body = objectMapper.readTree(result.response.contentAsString)
assertEquals(true, body.path("success").booleanValue(), body.toString())
return body.path("data")
}
protected fun money(value: JsonNode): List<Int> {
val tax = if (value.has("withholdingTax")) "withholdingTax" else "tax"
val fields = listOf("count", "totalCan", "krw", "fee", "settlementAmount", tax, "depositAmount", "agentSettlementAmount")
fields.forEach { assertEquals(true, value.path(it).isIntegralNumber, "$it: $value") }
return fields.map { value.path(it).intValue() }
}
}
@@ -23,6 +23,7 @@ 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
@@ -76,6 +77,16 @@ class CreatorChannelDonationEndToEndTest @Autowired constructor(
) {
private val tokenMemberIds = mutableSetOf<Long>()
@BeforeEach
fun initializeSettlementDateFunctions() {
jdbcTemplate.execute(
"CREATE ALIAS IF NOT EXISTS DATE_FORMAT FOR 'kr.co.vividnext.sodalive.support.H2MysqlDateFunctions.dateFormat'"
)
jdbcTemplate.execute(
"CREATE ALIAS IF NOT EXISTS CONVERT_TZ FOR 'kr.co.vividnext.sodalive.support.H2MysqlDateFunctions.convertTz'"
)
}
@AfterEach
fun removeIssuedTokens() {
tokenMemberIds.forEach { tokenRepository.deleteById(it) }
@@ -1,7 +1,12 @@
package kr.co.vividnext.sodalive.v2.api.creator.settlement
import com.fasterxml.jackson.databind.ObjectMapper
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.content.AudioContent
import kr.co.vividnext.sodalive.jwt.TokenProvider
import kr.co.vividnext.sodalive.member.Member
import kr.co.vividnext.sodalive.member.MemberRole
import kr.co.vividnext.sodalive.member.token.MemberTokenRepository
import kr.co.vividnext.sodalive.support.EmbeddedRedisInitializer
@@ -38,7 +43,7 @@ import javax.persistence.EntityManager
)
@ContextConfiguration(initializers = [EmbeddedRedisInitializer::class])
class CreatorMonthlySettlementHttpIntegrationTest @Autowired constructor(
entityManager: EntityManager,
private val entityManager: EntityManager,
transactionTemplate: TransactionTemplate,
restTemplate: TestRestTemplate,
objectMapper: ObjectMapper,
@@ -74,6 +79,7 @@ class CreatorMonthlySettlementHttpIntegrationTest @Autowired constructor(
assertFalse(data.path("hasRevenueData").booleanValue())
data.path("breakdown").forEach { source ->
assertFalse(source.path("hasRevenueData").booleanValue())
assertEquals(0, source.path("rateDetails").size())
http.amount(source, List(7) { 0L })
}
}
@@ -94,6 +100,10 @@ class CreatorMonthlySettlementHttpIntegrationTest @Autowired constructor(
assertEquals(source.path("source").asText() == "CONTENT_SALES", source.path("hasRevenueData").booleanValue())
http.amount(source, List(7) { 0L })
}
val zeroRow = data.path("breakdown")[1].path("rateDetails").single()
assertEquals(listOf("SAME_COUNTRY", "75", "null", "null"), http.economics(zeroRow))
assertTrue(zeroRow.path("rateInfoAvailable").booleanValue())
http.amount(zeroRow, List(7) { 0L })
}
@Test
@@ -113,13 +123,17 @@ class CreatorMonthlySettlementHttpIntegrationTest @Autowired constructor(
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)
listOf(2L, 200L, 14L, 46L, 140L, 4L, 136L)
)
data.path("breakdown").zip(expected).forEach { (source, amounts) ->
assertTrue(source.path("hasRevenueData").booleanValue())
http.amount(source, amounts)
val rate = source.path("rateDetails").single()
assertEquals(listOf("SAME_COUNTRY", "75", "null", "null"), http.economics(rate))
assertTrue(rate.path("rateInfoAvailable").booleanValue())
http.amount(rate, amounts)
}
http.amount(data.path("total"), listOf(17L, 1700L, 112L, 398L, 1190L, 40L, 1151L))
http.amount(data.path("total"), listOf(17L, 1700L, 113L, 397L, 1190L, 39L, 1152L))
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 ->
@@ -151,12 +165,172 @@ class CreatorMonthlySettlementHttpIntegrationTest @Autowired constructor(
)
}
if (route == "channel-donation") {
assertEquals(135L, legacy.path("total").path("depositAmount").longValue())
assertEquals(136L, legacy.path("total").path("depositAmount").longValue())
assertEquals(136L, legacy.path("items").sumOf { it.path("depositAmount").longValue() })
}
}
}
@Test
@DisplayName("국가·agent·실제 비율은 분리하고 같은 조건의 이력과 날짜별 반올림 결과는 월별로 합산한다")
fun shouldSplitMonthlyEconomicsAndFoldEqualHistoryAmountsThroughHttp() {
val (creator, firstAgent, secondAgent) = fixture.commit {
val creator = member()
val firstAgent = member(MemberRole.AGENT)
val secondAgent = member(MemberRole.AGENT)
val start = LocalDateTime.of(2026, 11, 18, 0, 0)
val historyCut = start.plusHours(1)
val rateCut = start.plusHours(2)
val agentCut = start.plusHours(3)
relation(firstAgent, creator, start to historyCut)
relation(firstAgent, creator, historyCut to agentCut)
relation(secondAgent, creator, agentCut to null)
agentRatio(firstAgent, 7, start to historyCut)
agentRatio(firstAgent, 7, historyCut to rateCut)
agentRatio(firstAgent, 10, rateCut to null)
agentRatio(secondAgent, 10, start to null)
channelDonation(creator, 1, start.minusHours(1))
channelDonation(creator, 1, start)
channelDonation(creator, 3, historyCut)
channelDonation(creator, 3, rateCut)
channelDonation(creator, 1, agentCut)
channelDonation(creator, 1, agentCut.plusDays(1))
channelDonation(creator, UseCan(CanUsage.CHANNEL_DONATION, 2, 999, countryCode = "JP"), agentCut)
channelDonation(creator, UseCan(CanUsage.CHANNEL_DONATION, 999, 0, isRefund = true), agentCut)
channelDonation(creator, UseCan(CanUsage.DONATION, 999, 0), agentCut)
channelDonation(creator, 999, agentCut).status = UseCanCalculateStatus.CALCULATE_COMPLETE
channelDonation(creator, 999, agentCut).status = UseCanCalculateStatus.REFUND
channelDonation(creator, 999, LocalDateTime.of(2026, 10, 31, 14, 59, 59))
channelDonation(creator, 999, LocalDateTime.of(2026, 11, 30, 15, 0))
channelDonation(member(), 777, agentCut)
Triple(creator, firstAgent, secondAgent)
}
val data = http.summary(creator)
val source = data.path("breakdown")[4]
val rates = source.path("rateDetails").toList()
val expected = mapOf(
listOf("SAME_COUNTRY", "75", "null", "null") to listOf(1L, 100L, 7L, 23L, 70L, 2L, 68L),
listOf("SAME_COUNTRY", "75", firstAgent.id.toString(), "7") to listOf(4L, 400L, 26L, 93L, 281L, 9L, 272L),
listOf("SAME_COUNTRY", "75", firstAgent.id.toString(), "10") to listOf(3L, 300L, 20L, 70L, 210L, 7L, 203L),
listOf("SAME_COUNTRY", "75", secondAgent.id.toString(), "10") to listOf(2L, 200L, 14L, 46L, 140L, 4L, 136L),
listOf("CROSS_COUNTRY", "50", secondAgent.id.toString(), "10") to listOf(2L, 200L, 13L, 93L, 94L, 3L, 91L)
)
assertEquals(5, rates.size)
assertEquals(expected.keys, rates.map(http::economics).toSet())
rates.forEach { rate ->
assertTrue(rate.path("rateInfoAvailable").booleanValue())
http.amount(rate, expected.getValue(http.economics(rate)))
}
val total = listOf(12L, 1200L, 80L, 325L, 795L, 25L, 770L)
http.amount(source, total)
http.amount(data.path("total"), total)
val query = "?startDateStr=2026-11-01&endDateStr=2026-11-30&page=0&size=20"
val detail = http.success(http.get(creator, "/creator-admin/calculate/channel-donation$query"))
assertEquals(6, detail.path("items").size())
http.channelAmount(listOf(detail.path("total")), total)
http.channelAmount(detail.path("items").toList(), total)
listOf(
Triple(firstAgent, listOf(7L, 700L, 46L, 163L, 491L, 16L, 475L), 41L),
Triple(secondAgent, listOf(4L, 400L, 27L, 139L, 234L, 7L, 227L), 23L)
).forEach { (agent, expectedAmount, expectedAgentAmount) ->
val agentData = http.success(http.get(agent, "/agent/calculate/channel-donation-by-creator$query"))
assertEquals(2, agentData.path("items").size())
http.channelAmount(listOf(agentData.path("total")), expectedAmount)
http.channelAmount(agentData.path("items").toList(), expectedAmount)
assertEquals(expectedAgentAmount, agentData.path("total").path("agentSettlementAmount").longValue())
assertEquals(expectedAgentAmount, agentData.path("items").sumOf { it.path("agentSettlementAmount").longValue() })
val monthlyRates = rates.filter { it.path("agentId").longValue() == agent.id }
val fields = listOf(
"totalCan",
"grossAmount",
"paymentFee",
"platformFee",
"settlementAmount",
"withholdingTax",
"depositAmount"
)
assertEquals(expectedAmount, fields.map { field -> monthlyRates.sumOf { it.path(field).longValue() } })
}
}
@Test
@DisplayName("월별 키는 다른 콘텐츠·날짜·금액·제목·닉네임에도 같은 경제 조건을 식별한다")
fun shouldKeepMonthlyRateKeysAcrossDetailAndLabelChangesThroughHttp() {
val (creator, originalContent) = fixture.commit {
val creator = member()
val content = content(creator)
listOf(18, 19).forEach { day -> order(content, 1, LocalDateTime.of(2026, 11, day, 0, 0)) }
creator to content
}
val before = http.summary(creator).path("breakdown")[1].path("rateDetails").single()
http.amount(before, listOf(2L, 200L, 14L, 46L, 140L, 4L, 136L))
fixture.commit {
entityManager.find(Member::class.java, creator.id).nickname = "renamed-monthly-${creator.id}"
entityManager.find(AudioContent::class.java, originalContent.id).title = "renamed-monthly-content"
val anotherContent = content(creator)
listOf(17, 20).forEach { day -> order(anotherContent, 1, LocalDateTime.of(2026, 11, day, 0, 0)) }
}
val after = http.summary(creator).path("breakdown")[1].path("rateDetails").single()
assertEquals(before.path("rowKey"), after.path("rowKey"))
assertEquals(listOf("SAME_COUNTRY", "75", "null", "null"), http.economics(after))
assertTrue(after.path("rateInfoAvailable").booleanValue())
http.amount(after, listOf(4L, 400L, 28L, 92L, 280L, 8L, 272L))
}
@Test
@DisplayName("시행 전 혼합 비율은 평균 비율을 꾸미지 않고 채널 월 전체의 기존 반올림도 보존한다")
fun shouldPreserveLegacyMoneyAndHonestRateMetadataThroughHttp() {
val creator = fixture.commit {
val creator = member()
val at = LocalDateTime.of(2026, 10, 18, 0, 0)
order(content(creator).apply { settlementRatio = 60 }, 1, at)
order(content(creator).apply { settlementRatio = 90 }, 1, at)
channelDonation(creator, 1, at)
channelDonation(creator, 1, at.plusDays(1))
creator
}
val data = http.summary(creator, "2026-10")
val sales = data.path("breakdown")[1]
val channel = data.path("breakdown")[4]
http.amount(sales, listOf(2L, 200L, 14L, 46L, 140L, 5L, 135L))
http.amount(channel, listOf(2L, 200L, 13L, 28L, 159L, 5L, 154L))
http.amount(data.path("total"), listOf(4L, 400L, 27L, 74L, 299L, 10L, 289L))
listOf(sales, channel).forEach { source ->
source.path("rateDetails").forEach { rate ->
assertEquals("LEGACY", rate.path("countryRelation").asText())
assertFalse(rate.path("rateInfoAvailable").booleanValue())
assertTrue(rate.path("agentId").isNull)
assertTrue(rate.path("appliedAgentSettlementRatio").isNull)
}
}
sales.path("rateDetails").forEach { rate ->
val ratio = rate.path("appliedSettlementRatio")
assertTrue(ratio.isNull || ratio.intValue() in setOf(60, 90))
if (!ratio.isNull) {
val expected = when (ratio.intValue()) {
60 -> listOf(1L, 100L, 7L, 37L, 56L, 2L, 54L)
90 -> listOf(1L, 100L, 7L, 9L, 84L, 3L, 81L)
else -> error("Unexpected legacy ratio: $ratio")
}
http.amount(rate, expected)
}
}
channel.path("rateDetails").forEach { rate ->
val ratio = rate.path("appliedSettlementRatio")
assertTrue(ratio.isNull || ratio.intValue() == 85)
}
val query = "?startDateStr=2026-10-01&endDateStr=2026-10-31&page=0&size=20"
val legacy = http.success(http.get(creator, "/creator-admin/calculate/channel-donation$query"))
http.channelAmount(listOf(legacy.path("total")), listOf(2L, 200L, 13L, 28L, 159L, 5L, 154L))
http.channelAmount(legacy.path("items").toList(), listOf(2L, 200L, 14L, 28L, 158L, 6L, 152L))
}
@ParameterizedTest
@CsvSource(
"2026-10, 2026-09-30T15:00:00Z, 2026-10-31T15:00:00Z",
@@ -14,6 +14,8 @@ import kr.co.vividnext.sodalive.explorer.profile.creatorCommunity.CreatorCommuni
import kr.co.vividnext.sodalive.live.room.LiveRoom
import kr.co.vividnext.sodalive.member.Member
import kr.co.vividnext.sodalive.member.MemberRole
import kr.co.vividnext.sodalive.partner.agent.assignment.AgentCreatorRelation
import kr.co.vividnext.sodalive.partner.agent.ratio.AgentSettlementRatio
import org.springframework.transaction.support.TransactionTemplate
import java.time.LocalDateTime
import java.util.UUID
@@ -81,16 +83,35 @@ internal class MonthlySettlementHttpFixture(
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
fun channelDonation(creator: Member, can: Int, at: LocalDateTime): UseCanCalculate =
channelDonation(creator, UseCan(CanUsage.CHANNEL_DONATION, can, 0, countryCode = "KR"), at)
fun channelDonation(creator: Member, useCan: UseCan, at: LocalDateTime): UseCanCalculate {
val persisted = usage(useCan, at)
return save(
UseCanCalculate(useCan.can, PaymentGateway.PG, UseCanCalculateStatus.RECEIVED).apply {
this.useCan = persisted
recipientCreatorId = creator.id
}
)
}
fun relation(agent: Member, creator: Member, window: Pair<LocalDateTime, LocalDateTime?>) = save(
AgentCreatorRelation().apply {
this.agent = agent
this.creator = creator
assignedAt = window.first
unassignedAt = window.second
}
)
fun agentRatio(agent: Member, ratio: Int, window: Pair<LocalDateTime, LocalDateTime?>) = save(
AgentSettlementRatio(ratio, window.first).apply {
member = agent
effectiveTo = window.second
}
)
fun allSources(creator: Member) {
val novemberStart = LocalDateTime.of(2026, 10, 31, 15, 0)
val nextDay = LocalDateTime.of(2026, 11, 1, 15, 0)
@@ -94,7 +94,11 @@ internal class MonthlySettlementHttpTestSupport(
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")
val fields = amountFields.toSet() + if (index == 0) {
emptySet()
} else {
setOf("source", "hasRevenueData", "rateDetails")
}
assertEquals(fields, amount.fieldNames().asSequence().toSet())
amountFields.forEach { field ->
assertTrue(amount.path(field).isIntegralNumber, "$field must be a JSON integer: $amount")
@@ -119,6 +123,50 @@ internal class MonthlySettlementHttpTestSupport(
data.path("breakdown").any { it.path("hasRevenueData").booleanValue() },
data.path("hasRevenueData").booleanValue()
)
val rowKeys = mutableSetOf<String>()
data.path("breakdown").forEach { source ->
val rates = source.path("rateDetails")
assertTrue(rates.isArray, "rateDetails must be an array: $source")
assertEquals(source.path("hasRevenueData").booleanValue(), rates.size() > 0)
rates.forEach { rate ->
assertEquals(
amountFields.toSet() + setOf(
"rowKey",
"countryRelation",
"appliedSettlementRatio",
"agentId",
"appliedAgentSettlementRatio",
"rateInfoAvailable"
),
rate.fieldNames().asSequence().toSet()
)
assertTrue(rate.path("rowKey").isTextual)
assertTrue(rate.path("rowKey").asText().isNotBlank())
assertTrue(rowKeys.add(rate.path("rowKey").asText()), "rateDetails keys must be unique across sources")
val relation = rate.path("countryRelation")
assertTrue(
relation.isNull || relation.isTextual && relation.asText() in
setOf("SAME_COUNTRY", "CROSS_COUNTRY", "LEGACY")
)
listOf("appliedSettlementRatio", "appliedAgentSettlementRatio").forEach { field ->
val value = rate.path(field)
assertTrue(value.isNull || value.isIntegralNumber && value.canConvertToInt(), field)
}
val agentId = rate.path("agentId")
assertTrue(agentId.isNull || agentId.isIntegralNumber && agentId.canConvertToLong())
assertTrue(rate.path("rateInfoAvailable").isBoolean)
amountFields.forEach { field ->
assertTrue(rate.path(field).isIntegralNumber, "$field must be a JSON integer: $rate")
assertTrue(rate.path(field).canConvertToLong(), "$field must fit Long: $rate")
}
assertEquals(
rate.path("grossAmount").longValue() - rate.path("paymentFee").longValue() -
rate.path("settlementAmount").longValue(),
rate.path("platformFee").longValue()
)
}
amount(source, amountFields.map { field -> rates.sumOf { it.path(field).longValue() } })
}
return data
}
@@ -145,4 +193,16 @@ internal class MonthlySettlementHttpTestSupport(
fun amount(actual: JsonNode, expected: List<Long>) {
assertEquals(expected, amountFields.map { actual.path(it).longValue() }, actual.toString())
}
fun economics(rate: JsonNode): List<String> =
listOf("countryRelation", "appliedSettlementRatio", "agentId", "appliedAgentSettlementRatio")
.map { rate.path(it).asText() }
fun channelAmount(rows: List<JsonNode>, expected: List<Long>) {
val fields = listOf("totalCan", "krw", "fee", "settlementAmount", "withholdingTax", "depositAmount")
assertEquals(
expected.filterIndexed { index, _ -> index != 3 },
fields.map { field -> rows.sumOf { it.path(field).longValue() } }
)
}
}
@@ -13,6 +13,7 @@ import kr.co.vividnext.sodalive.v2.creator.channel.donation.application.HideCrea
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
@@ -31,6 +32,16 @@ class CreatorAdminDonationHideIntegrationTest : CreatorAdminDonationTestSupport(
@Autowired private lateinit var existingHideService: HideCreatorChannelDonationService
@BeforeEach
fun initializeSettlementDateFunctions() {
jdbcTemplate.execute(
"CREATE ALIAS IF NOT EXISTS DATE_FORMAT FOR 'kr.co.vividnext.sodalive.support.H2MysqlDateFunctions.dateFormat'"
)
jdbcTemplate.execute(
"CREATE ALIAS IF NOT EXISTS CONVERT_TZ FOR 'kr.co.vividnext.sodalive.support.H2MysqlDateFunctions.convertTz'"
)
}
@ParameterizedTest
@ValueSource(booleans = [false, true])
@DisplayName("관리자 DELETE는 공개·비밀 후원의 숨김만 바꾸고 원문·모든 시각·원장·잔액·정산을 보존한다")
@@ -0,0 +1,141 @@
package kr.co.vividnext.sodalive.v2.settlement
import kr.co.vividnext.sodalive.admin.calculate.ratio.CreatorSettlementRatio
import kr.co.vividnext.sodalive.can.use.CanUsage
import kr.co.vividnext.sodalive.can.use.UseCan
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.MemberRole
import kr.co.vividnext.sodalive.v2.settlement.adapter.out.persistence.CanonicalSettlementQueryRepository
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
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementScope
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementSource
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementWindow
import org.junit.jupiter.api.Assertions.assertEquals
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.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest
import org.springframework.context.annotation.Import
import java.time.LocalDateTime
import javax.persistence.EntityManager
@DataJpaTest(properties = ["spring.cache.type=none"])
@Import(QueryDslConfig::class)
class CanonicalSettlementCountryPolicyRegressionTest @Autowired constructor(private val entityManager: EntityManager) {
private val boundary = LocalDateTime.of(2026, 10, 31, 15, 0)
private val repository = CanonicalSettlementQueryRepository(entityManager, CountrySettlementPolicy())
private val scope = SettlementScope(SettlementSource.LIVE, SettlementWindow(null, null, true))
@ParameterizedTest
@CsvSource(
"2026-10-31T15:00:00,KR,KR,80,SAME_COUNTRY,80,75,2,72",
"2026-10-31T15:00:00,JP,JP,85,SAME_COUNTRY,85,79,3,77",
"2027-01-01T15:00:00,KR,KR,75,SAME_COUNTRY,75,70,2,68",
"2027-01-01T15:00:00,KR,KR,90,SAME_COUNTRY,90,84,3,81",
"2027-01-01T15:00:00,KR,JP,90,CROSS_COUNTRY,50,47,2,45",
"2027-01-01T15:00:00,JP,JP,,SAME_COUNTRY,70,65,2,63",
"2026-12-31T15:00:00,,,,SAME_COUNTRY,70,65,2,63",
"2026-12-31T15:00:00,'',' ',,SAME_COUNTRY,70,65,2,63"
)
@DisplayName("실제 canonical 행은 개별80과85 및 새해의 개별 비율과 국가 관계를 보존한다")
fun shouldKeepIndividualAndCountryRatesAcrossDefaultExpiry(
eventAt: String,
creatorCountry: String?,
transactionCountry: String?,
individual: Int?,
relation: SettlementCountryRelation,
ratio: Int,
settlement: Long,
tax: Long,
deposit: Long
) {
val creator = saveCreator(creatorCountry, individual)
saveLiveUseCan(creator, 1, transactionCountry, LocalDateTime.parse(eventAt))
val rows = repository.readCanonicalPage(scope, 0, 10)
assertEquals(1, rows.size)
assertEquals(relation, rows.single().key.economics.countryRelation)
assertEquals(ratio, rows.single().key.economics.appliedSettlementRatio)
assertEquals(SettlementAmounts(1, 100, 7, settlement, tax, deposit, 0), rows.single().amount)
}
@ParameterizedTest
@CsvSource(
"2026-10-31T14:59:59.999999,0,,0,0,0",
"2026-10-31T15:00:00,1,75,70,2,68",
"2026-12-31T14:59:59.999999,1,75,70,2,68",
"2026-12-31T15:00:00,1,70,65,2,63",
"2026-12-31T15:00:00.000001,1,70,65,2,63"
)
@DisplayName("실제 canonical DB 조회는 고정 시행일과75 종료의 소수초 경계를 구분한다")
fun shouldKeepMicrosecondPolicyBoundaries(
eventAt: String,
expectedCan: Long,
expectedRatio: Int?,
settlement: Long,
tax: Long,
deposit: Long
) {
saveLiveUseCan(saveCreator("KR"), 1, "KR", LocalDateTime.parse(eventAt))
val rows = repository.readCanonicalPage(scope, 0, 10)
assertEquals(
if (expectedRatio == null) emptyList<Int>() else listOf(expectedRatio),
rows.map { it.key.economics.appliedSettlementRatio }
)
assertEquals(expectedCan, repository.countTransactions(scope))
assertEquals(
SettlementAmounts(expectedCan, expectedCan * 100, expectedCan * 7, settlement, tax, deposit, 0),
repository.readTotals(scope)
)
}
@Test
@DisplayName("실제 canonical SQL 집계와 금액은 Int를 넘는3000만캔90퍼센트를 Long으로 보존한다")
fun shouldKeepLongCanonicalAmountsFromDatabaseAggregation() {
saveLiveUseCan(saveCreator("KR", 90), 30_000_000, "KR", boundary)
val rows = repository.readCanonicalPage(scope, 0, 10)
assertEquals(1, rows.size)
assertEquals(90, rows.single().key.economics.appliedSettlementRatio)
assertEquals(
SettlementAmounts(30_000_000, 3_000_000_000, 198_000_000, 2_521_800_000, 83_219_400, 2_438_580_600, 0),
rows.single().amount
)
assertEquals(rows.single().amount, repository.readTotals(scope))
}
private fun saveCreator(country: String?, individual: Int? = null): Member {
val creator = Member(password = "password", nickname = "creator", countryCode = country, role = MemberRole.CREATOR)
entityManager.persist(creator)
individual?.let {
entityManager.persist(CreatorSettlementRatio(0, it, it, it).apply { member = creator })
}
return creator
}
private fun saveLiveUseCan(creator: Member, can: Int, country: String?, at: LocalDateTime) {
val room = LiveRoom("policy-live", "notice", boundary, 1, isAdult = false).apply { member = creator }
entityManager.persist(room)
val spend = UseCan(CanUsage.LIVE, can - 1, 1, countryCode = country).apply {
member = creator
this.room = room
}
entityManager.persist(spend)
entityManager.flush()
entityManager.createQuery("update UseCan u set u.createdAt = :at where u.id = :id")
.setParameter("at", at)
.setParameter("id", spend.id)
.executeUpdate()
entityManager.clear()
}
}
@@ -8,51 +8,68 @@ import kr.co.vividnext.sodalive.admin.calculate.GetCalculateLiveQueryData
import kr.co.vividnext.sodalive.admin.calculate.GetCumulativeSalesByContentQueryData
import kr.co.vividnext.sodalive.can.use.CanUsage
import kr.co.vividnext.sodalive.content.order.OrderType
import kr.co.vividnext.sodalive.v2.settlement.domain.CanonicalSettlementRow
import kr.co.vividnext.sodalive.v2.settlement.domain.RateSeparatedSettlementCalculator
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementCanonicalKey
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementCountryRelation
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementEconomics
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementRowKey
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementSource
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementSourceGrain
import kr.co.vividnext.sodalive.v2.settlement.dto.SettlementRateMetadata
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.CsvSource
import java.time.LocalDate
class CountrySettlementCalculationTest {
@ParameterizedTest
@CsvSource(
"2,1,75,,200,13,135,4,131",
"3,2,125,,300,20,182,6,176",
"2,2,150,,200,13,140,5,135",
"0,0,0,,0,0,0,0,0",
"-2,-1,-75,,-200,-13,-135,-4,-131",
"100,0,0,,10000,660,6538,216,6322"
"1,1,0,200,14,135,4,131",
"1,1,1,300,21,182,6,176",
"0,2,0,200,13,140,5,135",
"0,0,0,0,0,0,0,0",
"-1,-1,0,-200,-14,-135,-4,-131",
"100,0,0,10000,660,6538,216,6322"
)
@DisplayName("여섯 일반 매핑은 구정책과 신정책 기여액을 합한 뒤 필드별로 반올림한다")
fun shouldCombineUnroundedContributions(
total: Int,
newCan: Int,
weighted: Long,
ratio: Int?,
@DisplayName("여섯 일반 매핑은 보존한 구정책과 비율별로 반올림한 신정책 금액을 더한다")
fun shouldSumLegacyAndRoundedCanonicalContributions(
legacyCan: Int,
sameCountryCan: Int,
crossCountryCan: Int,
krw: Int,
fee: Int,
settlement: Int,
tax: Int,
deposit: Int
) {
val amounts = mapAmounts(total, newCan, weighted, ratio)
val contributions = listOf(
mapAmounts(legacyCan, null),
mapAmounts(sameCountryCan, null, canonicalRows(sameCountryCan, 75)),
mapAmounts(crossCountryCan, null, canonicalRows(crossCountryCan, 50))
)
val amounts = (0..5).map { mapper ->
(0..4).map { field -> contributions.sumOf { it[mapper][field] } }
}
amounts.forEach { assertEquals(listOf(krw, fee, settlement, tax, deposit), it) }
}
@ParameterizedTest
@CsvSource("2,1,75,80,145,5,140", "100,0,0,80,7472,247,7225")
@DisplayName("개별 구정책 비율은 신정책 기여액에 다시 적용하지 않는다")
@CsvSource("1,1,80,145,4,140", "100,0,80,7472,247,7225")
@DisplayName("개별 구정책 비율은 분리된 신정책 금액에 다시 적용하지 않는다")
fun shouldPreserveIndividualLegacyRatio(
total: Int,
legacyCan: Int,
newCan: Int,
weighted: Long,
ratio: Int,
settlement: Int,
tax: Int,
deposit: Int
) {
val amounts = mapAmounts(total, newCan, weighted, ratio)
val legacy = mapAmounts(legacyCan, ratio)
val canonical = mapAmounts(newCan, ratio, canonicalRows(newCan, 75))
val amounts = legacy.zip(canonical) { old, current -> old.zip(current) { a, b -> a + b } }
amounts.dropLast(1).forEach { assertEquals(listOf(settlement, tax, deposit), it.drop(2)) }
}
@@ -61,27 +78,123 @@ class CountrySettlementCalculationTest {
@CsvSource("125,,8172,8173", "10,75,700,654")
@DisplayName("Double 기반 구정책 반올림과 콘텐츠 후원의 정확한 십진 상수 차이를 보존한다")
fun shouldPreserveLegacyDecimalArtifacts(total: Int, ratio: Int?, expected: Int, donationExpected: Int) {
val amounts = mapAmounts(total, 0, 0, ratio)
val amounts = mapAmounts(total, ratio)
assertEquals(List(5) { expected } + donationExpected, amounts.map { it[2] })
}
private fun mapAmounts(total: Int, newCan: Int, weighted: Long, ratio: Int?): List<List<Int>> {
@ParameterizedTest
@CsvSource(
"1,75,200,14,140,4,136",
"0,75,0,0,0,0,0",
"-1,75,-200,-14,-140,-4,-136",
"1,50,200,14,94,4,90"
)
@DisplayName("여섯 공개 mapper는 이미 반올림한 canonical 합계를 개별 비율로 다시 가격 계산하지 않는다")
fun shouldKeepPrecomputedCanonicalAmountsThroughEveryMapper(
canPerRow: Int,
appliedRatio: Int,
krw: Int,
fee: Int,
settlement: Int,
tax: Int,
deposit: Int
) {
val first = canonicalRows(canPerRow, appliedRatio)
val second = canonicalRows(canPerRow, appliedRatio, LocalDate.of(2026, 11, 19))
val totals = first.mapValues { (source, row) ->
row.copy(amount = row.amount + second.getValue(source).amount, transactionCount = 2)
}
val amounts = mapAmounts(canPerRow * 2, 80, totals)
amounts.forEach { assertEquals(listOf(krw, fee, settlement, tax, deposit), it) }
}
private fun canonicalRows(
total: Int,
ratio: Int,
day: LocalDate = LocalDate.of(2026, 11, 18)
): Map<SettlementSource, CanonicalSettlementRow> = listOf(
SettlementSource.LIVE,
SettlementSource.CONTENT_SALES,
SettlementSource.COMMUNITY_POST,
SettlementSource.CONTENT_DONATION
).associateWith { source ->
val grain = when (source) {
SettlementSource.LIVE -> SettlementSourceGrain(day.dayOfMonth.toLong(), null, CanUsage.LIVE, null, null, null)
SettlementSource.CONTENT_SALES -> SettlementSourceGrain(1, day, null, OrderType.KEEP, 1, 0)
SettlementSource.COMMUNITY_POST, SettlementSource.CONTENT_DONATION -> SettlementSourceGrain(
1,
day,
null,
null,
null,
null
)
SettlementSource.CHANNEL_DONATION -> error("Channel is outside the general mapper contract")
}
val relation = if (ratio == 50) SettlementCountryRelation.CROSS_COUNTRY else SettlementCountryRelation.SAME_COUNTRY
CanonicalSettlementRow(
SettlementCanonicalKey(source, 1, SettlementEconomics(relation, ratio, null, null), grain),
1,
0,
RateSeparatedSettlementCalculator.calculate(source, total.toLong(), ratio, null)
)
}
private fun mapAmounts(
total: Int,
ratio: Int?,
rows: Map<SettlementSource, CanonicalSettlementRow> = emptyMap()
): List<List<Int>> {
fun metadata(source: SettlementSource): SettlementRateMetadata {
val row = rows[source] ?: return SettlementRateMetadata(
SettlementRowKey.legacy("mapper-fixture", listOf(source.name, "1")),
SettlementCountryRelation.LEGACY,
ratio,
null,
null,
false
)
return row.key.economics.let {
SettlementRateMetadata(
SettlementRowKey.canonical(row.key),
it.countryRelation,
it.appliedSettlementRatio,
it.agentId,
it.appliedAgentSettlementRatio,
true
)
}
}
val live = GetCalculateLiveQueryData(
"creator", "2026-11-18", "live", 1, 1, CanUsage.LIVE, 1, total, ratio, newCan, weighted
"creator", "2026-11-18", "live", 1, 1, CanUsage.LIVE, 1, total, ratio,
metadata(SettlementSource.LIVE), rows[SettlementSource.LIVE]?.amount
).toGetCalculateLiveResponse()
val content = GetCalculateContentQueryData(
"creator", "content", "2026-11-18", "2026-11-18", OrderType.KEEP, 1, 1, total, 0, ratio, newCan, weighted
"creator", "content", "2026-11-18", "2026-11-18", OrderType.KEEP, 1, 1, total, 0, ratio,
metadata(SettlementSource.CONTENT_SALES), rows[SettlementSource.CONTENT_SALES]?.amount
).toGetCalculateContentResponse()
val community = GetCalculateCommunityPostQueryData(
"creator", "post", "2026-11-18", 1, 1, total, ratio, newCan, weighted
"creator", "post", "2026-11-18", 1, 1, total, ratio,
metadata(SettlementSource.COMMUNITY_POST), rows[SettlementSource.COMMUNITY_POST]?.amount
).toGetCalculateCommunityPostResponse()
val creator = GetCalculateByCreatorQueryData(1, "creator", total, ratio, newCan, weighted).toGetCalculateByCreator()
val creator = GetCalculateByCreatorQueryData(
1,
"creator",
total,
ratio,
metadata(SettlementSource.LIVE),
rows[SettlementSource.LIVE]?.amount
).toGetCalculateByCreator()
val cumulative = GetCumulativeSalesByContentQueryData(
"creator", "content", "2026-11-18", OrderType.KEEP, 1, 1, total, 0, ratio, newCan, weighted
"creator", "content", "2026-11-18", OrderType.KEEP, 1, 1, total, 0, ratio,
metadata(SettlementSource.CONTENT_SALES), rows[SettlementSource.CONTENT_SALES]?.amount
).toCumulativeSalesByContentItem()
val donation = GetCalculateContentDonationQueryData(
"creator", "content", 1, "2026-11-18", "2026-11-18", 1, total, newCan, weighted
"creator", "content", 1, "2026-11-18", "2026-11-18", 1, total,
metadata(SettlementSource.CONTENT_DONATION), rows[SettlementSource.CONTENT_DONATION]?.amount
).toGetCalculateContentDonationResponse()
return listOf(
listOf(live.totalKrw, live.paymentFee, live.settlementAmount, live.tax, live.depositAmount),
@@ -1,188 +0,0 @@
package kr.co.vividnext.sodalive.v2.settlement
import com.querydsl.core.types.dsl.Expressions
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.UseCan
import kr.co.vividnext.sodalive.configs.QueryDslConfig
import kr.co.vividnext.sodalive.member.Member
import kr.co.vividnext.sodalive.member.QMember.member
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.DisplayName
import org.junit.jupiter.api.Test
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.CsvSource
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest
import org.springframework.context.annotation.Import
import java.time.LocalDateTime
import javax.persistence.EntityManager
@DataJpaTest(properties = ["spring.cache.type=none"])
@Import(QueryDslConfig::class)
class CountrySettlementExpressionsTest @Autowired constructor(
private val queryFactory: JPAQueryFactory,
private val entityManager: EntityManager
) {
private val boundary = LocalDateTime.of(2026, 10, 31, 15, 0)
private val expressions = CountrySettlementExpressions(CountrySettlementPolicy())
@ParameterizedTest
@CsvSource(
"2026-10-31T15:00:00,KR,KR,,75", "2026-10-31T15:00:00,JP,JP,,70",
"2026-10-31T15:00:00,KR,JP,90,50", "2026-10-31T15:00:00,JP,KR,90,50",
"2026-10-31T15:00:00,KR,KR,80,80", "2026-10-31T15:00:00,JP,JP,85,85",
"2026-10-31T15:00:00,,,,75", "2026-10-31T15:00:00,'',KR,,75",
"2026-10-31T15:00:00,KR,' ',,75", "2026-10-31T15:00:00,,JP,90,50",
"2026-10-31T15:00:00,JP,,90,50",
"2027-01-01T15:00:00,KR,KR,75,75", "2027-01-01T15:00:00,KR,KR,90,90",
"2027-01-01T15:00:00,KR,JP,90,50", "2027-01-01T15:00:00,JP,JP,,70",
"2026-12-31T15:00:00,,,,70", "2026-12-31T15:00:00,'',' ',,70"
)
@DisplayName("실제 집계는 거래 시각으로 기본값을 선택하고 새해에도 개별 비율과 국가 간 50퍼센트를 유지한다")
fun shouldAggregateCountryRatioAtEventTime(
eventAt: String,
creator: String?,
transaction: String?,
individual: Int?,
expected: Int
) {
val owner = Member(password = "password", nickname = "creator", countryCode = creator)
entityManager.persist(owner)
saveUseCan(owner, 1, transaction, LocalDateTime.parse(eventAt))
val individualExpression = individual?.let { Expressions.asNumber(it) }
val weighted = expressions.newPolicyWeightedRatioCan(
useCan.createdAt,
useCan.can.add(useCan.rewardCan),
member.countryCode,
useCan.countryCode,
individualExpression
)
val result = queryFactory.select(weighted).from(useCan).join(useCan.member, member).fetchOne()
assertEquals(expected.toLong(), result)
}
@ParameterizedTest
@CsvSource(
"2026-10-31T14:59:59.999999,0,0",
"2026-10-31T15:00:00,1,75",
"2026-12-31T14:59:59.999999,1,75",
"2026-12-31T15:00:00,1,70",
"2026-12-31T15:00:00.000001,1,70"
)
@DisplayName("실제 DB 집계는 시행 직전 1마이크로초를 제외하고 한국 기본75퍼센트는 새해 직전까지만 적용한다")
fun shouldApplyFixedStartAndKoreanDefaultExpiry(eventAt: String, expectedCan: Int, expectedWeighted: Long) {
// given
val owner = Member(password = "password", nickname = "creator", countryCode = "KR")
entityManager.persist(owner)
saveUseCan(owner, 1, "KR", LocalDateTime.parse(eventAt))
val newCan = expressions.newPolicyCan(useCan.createdAt, useCan.can.add(useCan.rewardCan))
val weighted = expressions.newPolicyWeightedRatioCan(
useCan.createdAt,
useCan.can.add(useCan.rewardCan),
member.countryCode,
useCan.countryCode
)
// when
val result = queryFactory.select(newCan, weighted).from(useCan).join(useCan.member, member).fetchOne()
// then
assertEquals(expectedCan, result?.get(newCan))
assertEquals(expectedWeighted, result?.get(weighted))
}
@Test
@DisplayName("공개 그룹 하나 안에서 시행일 이전을 제외하고 경계 시각부터 합산한다")
fun shouldAggregateMixedCountriesAtInclusiveFixedBoundary() {
val owner = Member(password = "password", nickname = "creator", countryCode = "KR")
entityManager.persist(owner)
saveUseCan(owner, 2, "KR", boundary.minusNanos(1_000))
saveUseCan(owner, 1, "KR", boundary)
saveUseCan(owner, 2, "JP", boundary.plusNanos(1_000))
val newCan = expressions.newPolicyCan(useCan.createdAt, useCan.can.add(useCan.rewardCan))
val weighted = expressions.newPolicyWeightedRatioCan(
useCan.createdAt,
useCan.can.add(useCan.rewardCan),
member.countryCode,
useCan.countryCode,
Expressions.asNumber(90)
)
val rows = queryFactory.select(newCan, weighted).from(useCan).join(useCan.member, member).groupBy(member.id).fetch()
assertEquals(1, rows.size)
assertEquals(3, rows.single().get(newCan))
assertEquals(190L, rows.single().get(weighted))
}
@Test
@DisplayName("동일 공개 그룹의 연말과 새해 거래는 각각 75퍼센트와 70퍼센트로 합산한다")
fun shouldAggregateBothKoreanDefaultsWithinOneGroup() {
// given
val owner = Member(password = "password", nickname = "creator", countryCode = "KR")
entityManager.persist(owner)
saveUseCan(owner, 1, "KR", LocalDateTime.parse("2026-12-31T14:59:59.999999"))
saveUseCan(owner, 1, "KR", LocalDateTime.parse("2026-12-31T15:00:00"))
val newCan = expressions.newPolicyCan(useCan.createdAt, useCan.can.add(useCan.rewardCan))
val weighted = expressions.newPolicyWeightedRatioCan(
useCan.createdAt,
useCan.can.add(useCan.rewardCan),
member.countryCode,
useCan.countryCode
)
// when
val rows = queryFactory.select(newCan, weighted).from(useCan).join(useCan.member, member).groupBy(member.id).fetch()
// then
assertEquals(1, rows.size)
assertEquals(2, rows.single().get(newCan))
assertEquals(145L, rows.single().get(weighted))
}
@Test
@DisplayName("가중 캔은 Int 범위를 넘기 전 Long으로 곱한다")
fun shouldMultiplyInLongBeforeSumming() {
val owner = Member(password = "password", nickname = "creator", countryCode = "KR")
entityManager.persist(owner)
saveUseCan(owner, 30_000_000, "KR", boundary)
val weighted = expressions.newPolicyWeightedRatioCan(
useCan.createdAt,
useCan.can.add(useCan.rewardCan),
member.countryCode,
useCan.countryCode,
Expressions.asNumber(90)
)
val result = queryFactory.select(weighted).from(useCan).join(useCan.member, member).fetchOne()
assertEquals(2_700_000_000L, result)
}
@Test
@DisplayName("원천이 없으면 두 집계는 null 대신 타입별 0을 반환한다")
fun shouldCoalesceEmptyAggregates() {
val newCan = expressions.newPolicyCan(useCan.createdAt, useCan.can)
val weighted = expressions.newPolicyWeightedRatioCan(useCan.createdAt, useCan.can, member.countryCode, useCan.countryCode)
val result = queryFactory.select(newCan, weighted).from(useCan).join(useCan.member, member).fetchOne()
assertEquals(0, result?.get(newCan))
assertEquals(0L, result?.get(weighted))
}
private fun saveUseCan(owner: Member, can: Int, country: String?, at: LocalDateTime) {
val spend = UseCan(CanUsage.LIVE, can - 1, 1, countryCode = country)
spend.member = owner
entityManager.persist(spend)
entityManager.flush()
queryFactory.update(useCan).set(useCan.createdAt, at).where(useCan.id.eq(spend.id)).execute()
entityManager.clear()
}
}
@@ -0,0 +1,136 @@
package kr.co.vividnext.sodalive.v2.settlement
import kr.co.vividnext.sodalive.v2.settlement.domain.RateSeparatedSettlementCalculator
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementAmounts
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementSource
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
class RateSeparatedSettlementCalculatorTest {
@ParameterizedTest
@CsvSource(
"LIVE,25,70,,2500,165,1634,54,1581,0",
"CONTENT_SALES,25,70,,2500,165,1634,54,1581,0",
"COMMUNITY_POST,25,70,,2500,165,1634,54,1581,0",
"CONTENT_DONATION,25,70,,2500,165,1635,54,1581,0",
"LIVE,13,70,7,1300,86,850,28,822,60",
"CONTENT_DONATION,13,70,7,1300,86,850,28,822,60",
"CHANNEL_DONATION,1,75,7,100,7,70,2,68,5",
"CHANNEL_DONATION,2,50,,200,13,94,3,91,0",
"CHANNEL_DONATION,3,75,10,300,20,210,7,203,21",
"CHANNEL_DONATION,4,75,7,400,26,281,9,272,20",
"LIVE,-13,70,7,-1300,-86,-850,-28,-822,-60",
"CONTENT_DONATION,-25,70,0,-2500,-165,-1635,-54,-1581,0",
"CHANNEL_DONATION,-1,75,7,-100,-7,-70,-2,-68,-5",
"LIVE,40000000,75,,4000000000,264000000,2802000000,92466000,2709534000,0",
"CONTENT_SALES,40000000,75,,4000000000,264000000,2802000000,92466000,2709534000,0",
"COMMUNITY_POST,40000000,75,,4000000000,264000000,2802000000,92466000,2709534000,0",
"CONTENT_DONATION,40000000,75,,4000000000,264000000,2802000000,92466000,2709534000,0",
"CHANNEL_DONATION,40000000,75,,4000000000,264000000,2802000000,92466000,2709534000,0"
)
@DisplayName("원천별 독립 반올림과 반올림된 정산액의 agent 몫을 보존한다")
fun shouldCalculateSourceSpecificGoldenAmounts(
source: SettlementSource,
totalCan: Long,
ratio: Int,
agentRatio: Int?,
gross: Long,
fee: Long,
settlement: Long,
tax: Long,
deposit: Long,
agent: Long
) {
val amount = RateSeparatedSettlementCalculator.calculate(source, totalCan, ratio, agentRatio)
assertEquals(SettlementAmounts(totalCan, gross, fee, settlement, tax, deposit, agent), amount)
}
@ParameterizedTest
@EnumSource(SettlementSource::class)
@DisplayName("거래 캔이 0이면 원천에 관계없이 금액은 0이다")
fun shouldCalculateZeroForEverySource(source: SettlementSource) {
val amount = RateSeparatedSettlementCalculator.calculate(source, 0, 75, 7)
assertEquals(SettlementAmounts.ZERO, amount)
}
@Test
@DisplayName("서로 다른 비율의 반올림된 행을 합산하여 159원을 유지한다")
fun shouldSumRoundedRowsWithoutCombiningTheirFinancialInputs() {
val sameCountry = RateSeparatedSettlementCalculator.calculate(SettlementSource.CHANNEL_DONATION, 1, 75, null)
val crossCountry = RateSeparatedSettlementCalculator.calculate(SettlementSource.CHANNEL_DONATION, 2, 50, null)
val amount = sameCountry + crossCountry
assertEquals(SettlementAmounts(3, 300, 20, 164, 5, 159, 0), amount)
}
@Test
@DisplayName("agent 조건이 다른 행의 입금액과 agent 몫은 재계산 없이 더한다")
fun shouldSumAgentSeparatedRowsWithoutDeductingAgentMoney() {
val first = RateSeparatedSettlementCalculator.calculate(SettlementSource.CHANNEL_DONATION, 1, 75, 7)
val second = RateSeparatedSettlementCalculator.calculate(SettlementSource.CHANNEL_DONATION, 3, 75, 10)
val amount = listOf(first, second).fold(SettlementAmounts.ZERO) { total, row -> total + row }
assertEquals(SettlementAmounts(4, 400, 27, 280, 9, 271, 26), amount)
}
@Test
@DisplayName("합산은 음수와 Long 범위의 각 필드를 그대로 더한다")
fun shouldAddEveryAmountFieldExactly() {
val positive = SettlementAmounts(40_000_000, 4_000_000_000, 264_000_000, 2_802_000_000, 92_466_000, 2_709_534_000, 99)
val negative = SettlementAmounts(-1, -2, -3, -4, -5, -6, -7)
val amount = positive + negative
assertEquals(
SettlementAmounts(39_999_999, 3_999_999_998, 263_999_997, 2_801_999_996, 92_465_995, 2_709_533_994, 92),
amount
)
assertEquals(positive, positive + SettlementAmounts.ZERO)
}
@Test
@DisplayName("일곱 금액 필드의 합산 overflow는 wrap하지 않는다")
fun shouldRejectOverflowInEveryAmountField() {
val maxima = listOf(
SettlementAmounts.ZERO.copy(totalCan = Long.MAX_VALUE),
SettlementAmounts.ZERO.copy(grossAmount = Long.MAX_VALUE),
SettlementAmounts.ZERO.copy(paymentFee = Long.MAX_VALUE),
SettlementAmounts.ZERO.copy(settlementAmount = Long.MAX_VALUE),
SettlementAmounts.ZERO.copy(withholdingTax = Long.MAX_VALUE),
SettlementAmounts.ZERO.copy(depositAmount = Long.MAX_VALUE),
SettlementAmounts.ZERO.copy(agentSettlementAmount = Long.MAX_VALUE)
)
val increment = SettlementAmounts(1, 1, 1, 1, 1, 1, 1)
maxima.forEach { maximum -> assertThrows(ArithmeticException::class.java) { maximum + increment } }
assertThrows(ArithmeticException::class.java) {
SettlementAmounts.ZERO.copy(totalCan = Long.MIN_VALUE) + increment.copy(
totalCan = -1
)
}
}
@ParameterizedTest
@EnumSource(SettlementSource::class)
@DisplayName("금액 계산의 Long 범위 초과는 정확한 변환에서 거부한다")
fun shouldRejectUnrepresentableAmounts(source: SettlementSource) {
assertThrows(ArithmeticException::class.java) {
RateSeparatedSettlementCalculator.calculate(source, Long.MAX_VALUE, 75, null)
}
assertThrows(ArithmeticException::class.java) {
RateSeparatedSettlementCalculator.calculate(source, Long.MIN_VALUE, 75, null)
}
assertThrows(ArithmeticException::class.java) {
RateSeparatedSettlementCalculator.calculate(source, 1_000_000_000, Int.MAX_VALUE, Int.MAX_VALUE)
}
}
}
@@ -0,0 +1,195 @@
package kr.co.vividnext.sodalive.v2.settlement
import kr.co.vividnext.sodalive.can.use.CanUsage
import kr.co.vividnext.sodalive.content.order.OrderType
import kr.co.vividnext.sodalive.v2.settlement.domain.CanonicalSettlementRow
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementAmounts
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementCanonicalKey
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementCountryRelation
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementDisplayGrain
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementEconomics
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementRowKey
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementSource
import kr.co.vividnext.sodalive.v2.settlement.domain.SettlementSourceGrain
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertNotEquals
import org.junit.jupiter.api.Assertions.assertThrows
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.EnumSource
import java.nio.charset.StandardCharsets
import java.time.LocalDate
class SettlementRowKeyTest {
private val economics = SettlementEconomics(SettlementCountryRelation.SAME_COUNTRY, 75, 11, 7)
private val grain = SettlementSourceGrain(42, LocalDate.of(2026, 11, 20), null, OrderType.KEEP, 25, 0)
private val key = SettlementCanonicalKey(SettlementSource.CONTENT_SALES, 9, economics, grain)
@Test
@DisplayName("상세 키는 경제 조건과 원천 여섯 필드를 고정 ASCII 위치로 인코딩한다")
fun shouldEncodeCanonicalDetailWithAllSourceGrainParts() {
val encoded = SettlementRowKey.canonical(key)
assertEquals("rs1|D|CONTENT_SALES|9|SAME_COUNTRY|75|11|7|42|2026-11-20|~|KEEP|25|0", encoded)
assertEquals(encoded, SettlementRowKey.display(key, SettlementDisplayGrain.DETAIL))
}
@Test
@DisplayName("누적 판매는 일자를 제외하고 원천과 판매 구분을 유지한다")
fun shouldEncodeContentCumulativeWithoutDailyGrain() {
val encoded = SettlementRowKey.display(key, SettlementDisplayGrain.CONTENT_CUMULATIVE)
assertEquals("rs1|U|CONTENT_SALES|9|SAME_COUNTRY|75|11|7|42|KEEP|25|0", encoded)
assertEquals(
encoded,
SettlementRowKey.display(
key.copy(grain = grain.copy(dayKst = LocalDate.of(2026, 11, 21))),
SettlementDisplayGrain.CONTENT_CUMULATIVE
)
)
}
@Test
@DisplayName("creator와 월별 키는 원천 grain 없이 경제 조건만 유지한다")
fun shouldEncodeCreatorAndMonthlyRollupsWithoutSourceGrain() {
val anotherGrain = key.copy(grain = grain.copy(sourceId = 99, dayKst = LocalDate.of(2026, 11, 21)))
assertEquals("rs1|C|CONTENT_SALES|9|SAME_COUNTRY|75|11|7", SettlementRowKey.creator(key.source, 9, economics))
assertEquals("rs1|M|CONTENT_SALES|9|SAME_COUNTRY|75|11|7", SettlementRowKey.monthly(key.source, 9, economics))
listOf(SettlementDisplayGrain.CREATOR, SettlementDisplayGrain.MONTHLY_RATE).forEach { displayGrain ->
assertEquals(SettlementRowKey.display(key, displayGrain), SettlementRowKey.display(anotherGrain, displayGrain))
}
assertEquals(
SettlementRowKey.creator(key.source, 9, economics),
SettlementRowKey.display(key, SettlementDisplayGrain.CREATOR)
)
assertEquals(
SettlementRowKey.monthly(key.source, 9, economics),
SettlementRowKey.display(key, SettlementDisplayGrain.MONTHLY_RATE)
)
}
@ParameterizedTest
@EnumSource(SettlementDisplayGrain::class)
@DisplayName("모든 표시 grain에서 원천과 국가 비율 agent 조건은 충돌하지 않는다")
fun shouldKeepDifferentEconomicIdentitiesDistinct(displayGrain: SettlementDisplayGrain) {
val alternatives = listOf(
key,
key.copy(source = SettlementSource.CONTENT_DONATION),
key.copy(creatorId = 10),
key.copy(economics = economics.copy(countryRelation = SettlementCountryRelation.CROSS_COUNTRY)),
key.copy(economics = economics.copy(appliedSettlementRatio = 50)),
key.copy(economics = economics.copy(agentId = 12)),
key.copy(economics = economics.copy(appliedAgentSettlementRatio = 10)),
key.copy(economics = economics.copy(agentId = null, appliedAgentSettlementRatio = null))
)
val encoded = alternatives.map { SettlementRowKey.display(it, displayGrain) }
assertEquals(alternatives.size, encoded.toSet().size)
}
@Test
@DisplayName("원천의 ID 날짜 사용구분 판매유형 단가 포인트구분을 구별한다")
fun shouldKeepEachDetailGrainComponentDistinct() {
val grains = listOf(
grain,
grain.copy(sourceId = 43),
grain.copy(dayKst = grain.dayKst?.plusDays(1)),
grain.copy(canUsage = CanUsage.HEART),
grain.copy(orderType = OrderType.RENTAL),
grain.copy(orderPrice = 26),
grain.copy(pointGroup = 1)
)
val encoded = grains.map { SettlementRowKey.canonical(key.copy(grain = it)) }
assertEquals(grains.size, encoded.toSet().size)
assertNotEquals(SettlementRowKey.canonical(key), SettlementRowKey.display(key, SettlementDisplayGrain.CONTENT_CUMULATIVE))
}
@Test
@DisplayName("미소속 null과 ID 및 비율 0은 서로 다른 키다")
fun shouldDistinguishNullMarkersFromNumericZero() {
val absent = key.copy(economics = economics.copy(agentId = null, appliedAgentSettlementRatio = null))
val zero = absent.copy(economics = absent.economics.copy(agentId = 0, appliedAgentSettlementRatio = 0))
assertEquals("rs1|D|CONTENT_SALES|9|SAME_COUNTRY|75|~|~|42|2026-11-20|~|KEEP|25|0", SettlementRowKey.canonical(absent))
assertNotEquals(SettlementRowKey.canonical(absent), SettlementRowKey.canonical(zero))
}
@Test
@DisplayName("동일 경제 조건이면 거래수와 금액이 달라도 같은 키다")
fun shouldKeepEconomicKeyStableAcrossAmountChanges() {
val original = CanonicalSettlementRow(key, 1, 0, SettlementAmounts.ZERO)
val rows = listOf(
original,
original.copy(
key = key.copy(),
transactionCount = 2,
totalPoint = 3,
amount = SettlementAmounts.ZERO.copy(totalCan = 4)
)
)
val encoded = rows.map { SettlementRowKey.canonical(it.key) }
assertEquals(listOf("rs1|D|CONTENT_SALES|9|SAME_COUNTRY|75|11|7|42|2026-11-20|~|KEEP|25|0"), encoded.distinct())
}
@Test
@DisplayName("최대 typed 값과 모든 enum의 키는 384 ASCII byte 안에 있다")
fun shouldKeepMaximumTypedKeysWithinAsciiStorageBound() {
val extreme = SettlementCanonicalKey(
SettlementSource.CHANNEL_DONATION,
Long.MIN_VALUE,
SettlementEconomics(SettlementCountryRelation.CROSS_COUNTRY, Int.MIN_VALUE, Long.MIN_VALUE, Int.MIN_VALUE),
SettlementSourceGrain(
Long.MIN_VALUE,
LocalDate.MAX,
CanUsage.CHARACTER_IMAGE_PURCHASE,
OrderType.RENTAL,
Int.MIN_VALUE,
Int.MIN_VALUE
)
)
assertEquals(
"rs1|D|CHANNEL_DONATION|-9223372036854775808|CROSS_COUNTRY|-2147483648|-9223372036854775808|-2147483648|" +
"-9223372036854775808|+999999999-12-31|CHARACTER_IMAGE_PURCHASE|RENTAL|-2147483648|-2147483648",
SettlementRowKey.canonical(extreme)
)
SettlementSource.values().forEach { source ->
SettlementDisplayGrain.values().forEach { displayGrain ->
val encoded = SettlementRowKey.display(extreme.copy(source = source), displayGrain)
assertTrue(encoded.all { it.code in 0..127 })
assertTrue(encoded.toByteArray(StandardCharsets.US_ASCII).size <= 384)
}
}
}
@Test
@DisplayName("구경로와 과거 snapshot 키는 분리된 namespace와 실제 식별값을 쓴다")
fun shouldEncodeLegacyAndHistoricalSnapshotIdentities() {
val encoded = SettlementRowKey.legacy("content-detail", listOf("9", "42", "2026-11-20", "KEEP", null, "0"))
assertEquals("lg1|content-detail|9|42|2026-11-20|KEEP|~|0", encoded)
assertEquals("ss0|123", SettlementRowKey.historicalSnapshot(123))
assertNotEquals(
encoded,
SettlementRowKey.legacy("content-cumulative", listOf("9", "42", "2026-11-20", "KEEP", null, "0"))
)
}
@Test
@DisplayName("구경로 식별값의 delimiter null표식 비ASCII 주입을 거부한다")
fun shouldRejectAmbiguousLegacyIdentityTokens() {
listOf("1|2", "~", "크리에이터", "").forEach { token ->
assertThrows(IllegalArgumentException::class.java) { SettlementRowKey.legacy("detail", listOf(token)) }
assertThrows(IllegalArgumentException::class.java) { SettlementRowKey.legacy(token, listOf("1")) }
}
}
}