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
@@ -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
)