feat(creator-admin): 팬톡 조회와 답글 관리를 추가한다
This commit is contained in:
+102
@@ -0,0 +1,102 @@
|
||||
package kr.co.vividnext.sodalive.v2.creator.admin.commentmanagement.fantalk.adapter.`in`.web
|
||||
|
||||
import kr.co.vividnext.sodalive.common.ApiResponse
|
||||
import kr.co.vividnext.sodalive.member.Member
|
||||
import kr.co.vividnext.sodalive.v2.creator.admin.commentmanagement.adapter.`in`.web.CreatorAdminCommentRequestParser
|
||||
import kr.co.vividnext.sodalive.v2.creator.admin.commentmanagement.adapter.`in`.web.requireCreator
|
||||
import kr.co.vividnext.sodalive.v2.creator.admin.commentmanagement.domain.CreatorAdminCommentPolicy
|
||||
import kr.co.vividnext.sodalive.v2.creator.admin.commentmanagement.dto.CreatorAdminCommentPageResponse
|
||||
import kr.co.vividnext.sodalive.v2.creator.admin.commentmanagement.fantalk.application.CreatorAdminFanTalkService
|
||||
import kr.co.vividnext.sodalive.v2.creator.admin.commentmanagement.fantalk.dto.CreatorAdminFanTalkResponse
|
||||
import org.springframework.http.MediaType
|
||||
import org.springframework.security.core.annotation.AuthenticationPrincipal
|
||||
import org.springframework.web.bind.annotation.DeleteMapping
|
||||
import org.springframework.web.bind.annotation.GetMapping
|
||||
import org.springframework.web.bind.annotation.PathVariable
|
||||
import org.springframework.web.bind.annotation.PostMapping
|
||||
import org.springframework.web.bind.annotation.PutMapping
|
||||
import org.springframework.web.bind.annotation.RequestBody
|
||||
import org.springframework.web.bind.annotation.RequestMapping
|
||||
import org.springframework.web.bind.annotation.RequestParam
|
||||
import org.springframework.web.bind.annotation.RestController
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v2/creator-admin/comment-management/fantalks")
|
||||
class CreatorAdminFanTalkController(
|
||||
private val service: CreatorAdminFanTalkService,
|
||||
private val requestParser: CreatorAdminCommentRequestParser
|
||||
) {
|
||||
@GetMapping
|
||||
fun list(
|
||||
@AuthenticationPrincipal(expression = "#this == 'anonymousUser' ? null : member") member: Member?,
|
||||
@RequestParam(defaultValue = "0") page: Int,
|
||||
@RequestParam(defaultValue = "10") size: Int,
|
||||
@RequestParam(defaultValue = "latest") order: String
|
||||
): ApiResponse<CreatorAdminCommentPageResponse<CreatorAdminFanTalkResponse>> {
|
||||
val creator = requireCreator(member)
|
||||
return ApiResponse.ok(
|
||||
service.list(
|
||||
requireNotNull(creator.id),
|
||||
CreatorAdminCommentPolicy.parsePage(page, size),
|
||||
CreatorAdminCommentPolicy.parseOrder(order)
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@DeleteMapping("/{fanTalkId}")
|
||||
fun delete(
|
||||
@AuthenticationPrincipal(expression = "#this == 'anonymousUser' ? null : member") member: Member?,
|
||||
@PathVariable fanTalkId: Long
|
||||
): ApiResponse<Unit> {
|
||||
val creator = requireCreator(member)
|
||||
service.delete(requireNotNull(creator.id), CreatorAdminCommentPolicy.requirePositiveId(fanTalkId))
|
||||
return ApiResponse.ok()
|
||||
}
|
||||
|
||||
@PostMapping("/{fanTalkId}/replies", consumes = [MediaType.APPLICATION_JSON_VALUE])
|
||||
fun createReply(
|
||||
@AuthenticationPrincipal(expression = "#this == 'anonymousUser' ? null : member") member: Member?,
|
||||
@PathVariable fanTalkId: Long,
|
||||
@RequestBody body: String
|
||||
): ApiResponse<Unit> {
|
||||
val creator = requireCreator(member)
|
||||
service.createReply(
|
||||
creator,
|
||||
CreatorAdminCommentPolicy.requirePositiveId(fanTalkId),
|
||||
requestParser.parseReply(body)
|
||||
)
|
||||
return ApiResponse.ok()
|
||||
}
|
||||
|
||||
@PutMapping("/{fanTalkId}/replies/{replyId}", consumes = [MediaType.APPLICATION_JSON_VALUE])
|
||||
fun updateReply(
|
||||
@AuthenticationPrincipal(expression = "#this == 'anonymousUser' ? null : member") member: Member?,
|
||||
@PathVariable fanTalkId: Long,
|
||||
@PathVariable replyId: Long,
|
||||
@RequestBody body: String
|
||||
): ApiResponse<Unit> {
|
||||
val creator = requireCreator(member)
|
||||
service.updateReply(
|
||||
requireNotNull(creator.id),
|
||||
CreatorAdminCommentPolicy.requirePositiveId(fanTalkId),
|
||||
CreatorAdminCommentPolicy.requirePositiveId(replyId),
|
||||
requestParser.parseReply(body)
|
||||
)
|
||||
return ApiResponse.ok()
|
||||
}
|
||||
|
||||
@DeleteMapping("/{fanTalkId}/replies/{replyId}")
|
||||
fun deleteReply(
|
||||
@AuthenticationPrincipal(expression = "#this == 'anonymousUser' ? null : member") member: Member?,
|
||||
@PathVariable fanTalkId: Long,
|
||||
@PathVariable replyId: Long
|
||||
): ApiResponse<Unit> {
|
||||
val creator = requireCreator(member)
|
||||
service.deleteReply(
|
||||
requireNotNull(creator.id),
|
||||
CreatorAdminCommentPolicy.requirePositiveId(fanTalkId),
|
||||
CreatorAdminCommentPolicy.requirePositiveId(replyId)
|
||||
)
|
||||
return ApiResponse.ok()
|
||||
}
|
||||
}
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
package kr.co.vividnext.sodalive.v2.creator.admin.commentmanagement.fantalk.adapter.out.persistence
|
||||
|
||||
import com.querydsl.core.types.dsl.BooleanExpression
|
||||
import com.querydsl.jpa.JPAExpressions
|
||||
import com.querydsl.jpa.impl.JPAQueryFactory
|
||||
import kr.co.vividnext.sodalive.explorer.profile.CreatorCheers
|
||||
import kr.co.vividnext.sodalive.explorer.profile.QCreatorCheers
|
||||
import kr.co.vividnext.sodalive.explorer.profile.QCreatorCheers.creatorCheers
|
||||
import kr.co.vividnext.sodalive.member.QMember.member
|
||||
import kr.co.vividnext.sodalive.v2.creator.admin.commentmanagement.domain.CreatorAdminCommentOrder
|
||||
import kr.co.vividnext.sodalive.v2.creator.admin.commentmanagement.domain.CreatorAdminCommentPage
|
||||
import org.springframework.stereotype.Repository
|
||||
import javax.persistence.EntityManager
|
||||
import javax.persistence.LockModeType
|
||||
|
||||
@Repository
|
||||
class CreatorAdminFanTalkRepository(
|
||||
private val queryFactory: JPAQueryFactory,
|
||||
private val entityManager: EntityManager
|
||||
) {
|
||||
fun countRoots(creatorId: Long): Long = requireNotNull(
|
||||
queryFactory.select(creatorCheers.id.count())
|
||||
.from(creatorCheers)
|
||||
.where(rootCondition(creatorId))
|
||||
.fetchOne()
|
||||
)
|
||||
|
||||
fun findRoots(
|
||||
creatorId: Long,
|
||||
page: CreatorAdminCommentPage,
|
||||
order: CreatorAdminCommentOrder
|
||||
): List<CreatorCheers> {
|
||||
val sorting = when (order) {
|
||||
CreatorAdminCommentOrder.LATEST -> arrayOf(creatorCheers.createdAt.desc(), creatorCheers.id.desc())
|
||||
CreatorAdminCommentOrder.OLDEST -> arrayOf(creatorCheers.createdAt.asc(), creatorCheers.id.asc())
|
||||
}
|
||||
return queryFactory.selectFrom(creatorCheers)
|
||||
.join(creatorCheers.member, member).fetchJoin()
|
||||
.where(rootCondition(creatorId))
|
||||
.orderBy(*sorting)
|
||||
.offset(page.offset)
|
||||
.limit(page.size.toLong())
|
||||
.fetch()
|
||||
}
|
||||
|
||||
fun findLatestOwnerReplies(creatorId: Long, rootIds: List<Long>): List<CreatorCheers> {
|
||||
if (rootIds.isEmpty()) return emptyList()
|
||||
val newer = QCreatorCheers("newerCreatorAdminFanTalkReply")
|
||||
return queryFactory.selectFrom(creatorCheers)
|
||||
.join(creatorCheers.member, member).fetchJoin()
|
||||
.where(
|
||||
creatorCheers.parent.id.`in`(rootIds),
|
||||
creatorCheers.creator.id.eq(creatorId),
|
||||
creatorCheers.member.id.eq(creatorId),
|
||||
creatorCheers.isActive.isTrue,
|
||||
JPAExpressions.selectOne().from(newer)
|
||||
.where(
|
||||
newer.parent.id.eq(creatorCheers.parent.id),
|
||||
newer.creator.id.eq(creatorId),
|
||||
newer.member.id.eq(creatorId),
|
||||
newer.isActive.isTrue,
|
||||
newer.createdAt.gt(creatorCheers.createdAt).or(
|
||||
newer.createdAt.eq(creatorCheers.createdAt).and(newer.id.gt(creatorCheers.id))
|
||||
)
|
||||
)
|
||||
.notExists()
|
||||
)
|
||||
.fetch()
|
||||
}
|
||||
|
||||
fun hasActiveOwnerReplyForUpdate(creatorId: Long, rootId: Long): Boolean = queryFactory.selectFrom(creatorCheers)
|
||||
.where(
|
||||
creatorCheers.parent.id.eq(rootId),
|
||||
creatorCheers.creator.id.eq(creatorId),
|
||||
creatorCheers.member.id.eq(creatorId),
|
||||
creatorCheers.isActive.isTrue
|
||||
)
|
||||
.setLockMode(LockModeType.PESSIMISTIC_WRITE)
|
||||
.fetchFirst() != null
|
||||
|
||||
fun lockReply(rootId: Long, replyId: Long): CreatorCheers? = queryFactory.selectFrom(creatorCheers)
|
||||
.where(creatorCheers.id.eq(replyId), creatorCheers.parent.id.eq(rootId))
|
||||
.setLockMode(LockModeType.PESSIMISTIC_WRITE)
|
||||
.fetchOne()
|
||||
?.also { entityManager.refresh(it, LockModeType.PESSIMISTIC_WRITE) }
|
||||
|
||||
private fun rootCondition(creatorId: Long): BooleanExpression = creatorCheers.creator.id.eq(creatorId)
|
||||
.and(creatorCheers.parent.isNull)
|
||||
.and(creatorCheers.isActive.isTrue)
|
||||
.and(creatorCheers.member.id.ne(creatorId))
|
||||
}
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
package kr.co.vividnext.sodalive.v2.creator.admin.commentmanagement.fantalk.application
|
||||
|
||||
import kr.co.vividnext.sodalive.explorer.profile.CreatorCheers
|
||||
import kr.co.vividnext.sodalive.explorer.profile.CreatorCheersRepository
|
||||
import kr.co.vividnext.sodalive.extensions.removeDeletedNicknamePrefix
|
||||
import kr.co.vividnext.sodalive.extensions.toUtcIso
|
||||
import kr.co.vividnext.sodalive.member.Member
|
||||
import kr.co.vividnext.sodalive.v2.commentthread.port.out.CommentThreadLockPort
|
||||
import kr.co.vividnext.sodalive.v2.common.domain.toCdnUrl
|
||||
import kr.co.vividnext.sodalive.v2.creator.admin.commentmanagement.domain.CreatorAdminCommentError
|
||||
import kr.co.vividnext.sodalive.v2.creator.admin.commentmanagement.domain.CreatorAdminCommentException
|
||||
import kr.co.vividnext.sodalive.v2.creator.admin.commentmanagement.domain.CreatorAdminCommentOrder
|
||||
import kr.co.vividnext.sodalive.v2.creator.admin.commentmanagement.domain.CreatorAdminCommentPage
|
||||
import kr.co.vividnext.sodalive.v2.creator.admin.commentmanagement.dto.CreatorAdminCommentPageResponse
|
||||
import kr.co.vividnext.sodalive.v2.creator.admin.commentmanagement.dto.CreatorAdminCommentReplyRequest
|
||||
import kr.co.vividnext.sodalive.v2.creator.admin.commentmanagement.dto.CreatorAdminCommentReplyResponse
|
||||
import kr.co.vividnext.sodalive.v2.creator.admin.commentmanagement.dto.CreatorAdminCommentWriterResponse
|
||||
import kr.co.vividnext.sodalive.v2.creator.admin.commentmanagement.fantalk.adapter.out.persistence.CreatorAdminFanTalkRepository
|
||||
import kr.co.vividnext.sodalive.v2.creator.admin.commentmanagement.fantalk.dto.CreatorAdminFanTalkResponse
|
||||
import org.springframework.beans.factory.annotation.Value
|
||||
import org.springframework.stereotype.Service
|
||||
import org.springframework.transaction.annotation.Transactional
|
||||
|
||||
@Service
|
||||
class CreatorAdminFanTalkService(
|
||||
private val repository: CreatorAdminFanTalkRepository,
|
||||
private val creatorCheersRepository: CreatorCheersRepository,
|
||||
private val threadLock: CommentThreadLockPort,
|
||||
@Value("\${cloud.aws.cloud-front.host}") private val cloudFrontHost: String
|
||||
) {
|
||||
@Transactional(readOnly = true)
|
||||
fun list(
|
||||
creatorId: Long,
|
||||
page: CreatorAdminCommentPage,
|
||||
order: CreatorAdminCommentOrder
|
||||
): CreatorAdminCommentPageResponse<CreatorAdminFanTalkResponse> {
|
||||
val roots = repository.findRoots(creatorId, page, order)
|
||||
val replies = repository.findLatestOwnerReplies(creatorId, roots.map { requireNotNull(it.id) })
|
||||
.associate { reply ->
|
||||
requireNotNull(reply.parent).id to CreatorAdminCommentReplyResponse(
|
||||
replyId = requireNotNull(reply.id),
|
||||
writer = writer(requireNotNull(reply.member)),
|
||||
content = reply.cheers,
|
||||
createdAtUtc = requireNotNull(reply.createdAt).toUtcIso(),
|
||||
isSecret = false
|
||||
)
|
||||
}
|
||||
return CreatorAdminCommentPageResponse(
|
||||
items = roots.map { root ->
|
||||
CreatorAdminFanTalkResponse(
|
||||
fanTalkId = requireNotNull(root.id),
|
||||
writer = writer(requireNotNull(root.member)),
|
||||
content = root.cheers,
|
||||
createdAtUtc = requireNotNull(root.createdAt).toUtcIso(),
|
||||
creatorReply = replies[root.id]
|
||||
)
|
||||
},
|
||||
totalCount = repository.countRoots(creatorId),
|
||||
page = page.page,
|
||||
size = page.size
|
||||
)
|
||||
}
|
||||
|
||||
@Transactional
|
||||
fun delete(creatorId: Long, fanTalkId: Long) {
|
||||
lockOwnedRoot(creatorId, fanTalkId).isActive = false
|
||||
}
|
||||
|
||||
@Transactional
|
||||
fun createReply(creator: Member, fanTalkId: Long, request: CreatorAdminCommentReplyRequest) {
|
||||
val creatorId = requireNotNull(creator.id)
|
||||
val root = lockOwnedRoot(creatorId, fanTalkId)
|
||||
if (!root.isActive) throw CreatorAdminCommentException(CreatorAdminCommentError.CONFLICT)
|
||||
// A locking read after the root lock sees replies committed after an earlier REPEATABLE READ snapshot.
|
||||
if (repository.hasActiveOwnerReplyForUpdate(creatorId, fanTalkId)) {
|
||||
throw CreatorAdminCommentException(CreatorAdminCommentError.CONFLICT)
|
||||
}
|
||||
creatorCheersRepository.save(
|
||||
CreatorCheers(cheers = request.content, languageCode = null).apply {
|
||||
member = creator
|
||||
this.creator = creator
|
||||
parent = root
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
@Transactional
|
||||
fun updateReply(creatorId: Long, fanTalkId: Long, replyId: Long, request: CreatorAdminCommentReplyRequest) {
|
||||
val root = lockOwnedRoot(creatorId, fanTalkId)
|
||||
val reply = lockOwnedReply(creatorId, root, replyId)
|
||||
if (reply.cheers != request.content) reply.cheers = request.content
|
||||
}
|
||||
|
||||
@Transactional
|
||||
fun deleteReply(creatorId: Long, fanTalkId: Long, replyId: Long) {
|
||||
val root = lockOwnedRoot(creatorId, fanTalkId)
|
||||
lockOwnedReply(creatorId, root, replyId).isActive = false
|
||||
}
|
||||
|
||||
private fun lockOwnedRoot(creatorId: Long, fanTalkId: Long): CreatorCheers {
|
||||
val root = threadLock.lockFanTalkRoot(fanTalkId)
|
||||
?: throw CreatorAdminCommentException(CreatorAdminCommentError.NOT_FOUND)
|
||||
if (root.creator?.id != creatorId) throw CreatorAdminCommentException(CreatorAdminCommentError.ACCESS_DENIED)
|
||||
if (root.member?.id == creatorId) {
|
||||
throw CreatorAdminCommentException(CreatorAdminCommentError.NOT_FOUND)
|
||||
}
|
||||
return root
|
||||
}
|
||||
|
||||
private fun lockOwnedReply(creatorId: Long, root: CreatorCheers, replyId: Long): CreatorCheers {
|
||||
val reply = repository.lockReply(requireNotNull(root.id), replyId)
|
||||
?: throw CreatorAdminCommentException(CreatorAdminCommentError.NOT_FOUND)
|
||||
if (reply.creator?.id != creatorId) {
|
||||
throw CreatorAdminCommentException(CreatorAdminCommentError.NOT_FOUND)
|
||||
}
|
||||
if (reply.member?.id != creatorId) throw CreatorAdminCommentException(CreatorAdminCommentError.ACCESS_DENIED)
|
||||
if (!root.isActive || !reply.isActive) throw CreatorAdminCommentException(CreatorAdminCommentError.NOT_FOUND)
|
||||
return reply
|
||||
}
|
||||
|
||||
private fun writer(member: Member): CreatorAdminCommentWriterResponse = CreatorAdminCommentWriterResponse(
|
||||
memberId = requireNotNull(member.id),
|
||||
nickname = member.nickname.removeDeletedNicknamePrefix(),
|
||||
profileImageUrl = member.profileImage.toCdnUrl(cloudFrontHost) ?: "$cloudFrontHost/profile/default-profile.png"
|
||||
)
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package kr.co.vividnext.sodalive.v2.creator.admin.commentmanagement.fantalk.dto
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty
|
||||
import kr.co.vividnext.sodalive.v2.creator.admin.commentmanagement.dto.CreatorAdminCommentReplyResponse
|
||||
import kr.co.vividnext.sodalive.v2.creator.admin.commentmanagement.dto.CreatorAdminCommentWriterResponse
|
||||
|
||||
data class CreatorAdminFanTalkResponse(
|
||||
val fanTalkId: Long,
|
||||
val writer: CreatorAdminCommentWriterResponse,
|
||||
val content: String,
|
||||
val createdAtUtc: String,
|
||||
val creatorReply: CreatorAdminCommentReplyResponse?,
|
||||
@get:JsonProperty("isSecret")
|
||||
val isSecret: Boolean = false
|
||||
)
|
||||
+202
@@ -0,0 +1,202 @@
|
||||
package kr.co.vividnext.sodalive.v2.creator.admin.commentmanagement.fantalk
|
||||
|
||||
import kr.co.vividnext.sodalive.member.MemberRole
|
||||
import org.hamcrest.Matchers.nullValue
|
||||
import org.junit.jupiter.api.Assertions.assertEquals
|
||||
import org.junit.jupiter.api.Assertions.assertTrue
|
||||
import org.junit.jupiter.api.DisplayName
|
||||
import org.junit.jupiter.api.Test
|
||||
import org.junit.jupiter.params.ParameterizedTest
|
||||
import org.junit.jupiter.params.provider.CsvSource
|
||||
import org.junit.jupiter.params.provider.ValueSource
|
||||
import org.springframework.http.MediaType
|
||||
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder
|
||||
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete
|
||||
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
|
||||
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post
|
||||
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put
|
||||
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath
|
||||
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status
|
||||
|
||||
class CreatorAdminFanTalkAccessIntegrationTest : FanTalkIntegrationTestSupport() {
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = ["GET", "DELETE_ROOT", "POST", "PUT", "DELETE_REPLY"])
|
||||
@DisplayName("팬톡 관리의 모든 HTTP 경로는 미인증 요청을 401로 거부한다")
|
||||
fun shouldRejectUnauthenticatedRequests(operation: String) {
|
||||
val root = saveRoot()
|
||||
val reply = saveReply(root)
|
||||
flushAndClear()
|
||||
|
||||
mockMvc.perform(request(operation, root.id, reply.id))
|
||||
.andExpect(status().isUnauthorized)
|
||||
.andExpect(jsonPath("$.success").value(false))
|
||||
.andExpect(jsonPath("$.data").value(nullValue()))
|
||||
|
||||
flushAndClear()
|
||||
assertEquals(2L, countCheers())
|
||||
assertTrue(findCheers(root.id).isActive)
|
||||
assertTrue(findCheers(reply.id).isActive)
|
||||
assertEquals("creator reply", findCheers(reply.id).cheers)
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource("GET,USER", "GET,ADMIN", "POST,USER", "POST,ADMIN", "PUT,USER", "DELETE_REPLY,USER", "DELETE_ROOT,USER")
|
||||
@DisplayName("팬톡 관리는 일반 회원과 ADMIN 역할의 대리 관리를 403으로 거부한다")
|
||||
fun shouldRejectRolesWithoutCreatorPermission(operation: String, role: MemberRole) {
|
||||
val root = saveRoot()
|
||||
val reply = saveReply(root)
|
||||
val actor = when (role) {
|
||||
MemberRole.USER -> fan
|
||||
MemberRole.ADMIN -> saveMember("fantalk-management-admin", MemberRole.ADMIN)
|
||||
else -> error("Unsupported test role: $role")
|
||||
}
|
||||
flushAndClear()
|
||||
|
||||
perform(request(operation, root.id, reply.id), actor)
|
||||
.andExpect(status().isForbidden)
|
||||
.andExpect(jsonPath("$.success").value(false))
|
||||
.andExpect(jsonPath("$.data").value(nullValue()))
|
||||
|
||||
flushAndClear()
|
||||
assertEquals(2L, countCheers())
|
||||
assertTrue(findCheers(root.id).isActive)
|
||||
assertTrue(findCheers(reply.id).isActive)
|
||||
assertEquals("creator reply", findCheers(reply.id).cheers)
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = ["DELETE_ROOT", "POST", "PUT", "DELETE_REPLY"])
|
||||
@DisplayName("타 크리에이터 채널의 팬톡과 답글은 403이며 저장 상태가 유지된다")
|
||||
fun shouldRejectOtherCreatorResourcesWithoutMutation(operation: String) {
|
||||
val root = saveRoot(creator = otherOwner)
|
||||
val reply = saveReply(root, otherOwner)
|
||||
flushAndClear()
|
||||
|
||||
reject(request(operation, root.id, reply.id), 403)
|
||||
|
||||
flushAndClear()
|
||||
assertEquals(2L, countCheers())
|
||||
assertTrue(findCheers(root.id).isActive)
|
||||
assertTrue(findCheers(reply.id).isActive)
|
||||
assertEquals("creator reply", findCheers(reply.id).cheers)
|
||||
assertEquals(otherOwner.id, findCheers(reply.id).member?.id)
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource("PUT,fan", "DELETE_REPLY,fan", "PUT,creator", "DELETE_REPLY,creator")
|
||||
@DisplayName("소유 채널에서도 팬이나 다른 크리에이터가 쓴 답글은 수정과 삭제를 403으로 거부한다")
|
||||
fun shouldRejectRepliesWrittenByAnotherMember(operation: String, writerKind: String) {
|
||||
val root = saveRoot()
|
||||
val writer = when (writerKind) {
|
||||
"fan" -> fan
|
||||
"creator" -> otherOwner
|
||||
else -> error("Unsupported test writer: $writerKind")
|
||||
}
|
||||
val reply = saveReply(root, writer, "someone else's reply")
|
||||
flushAndClear()
|
||||
|
||||
reject(request(operation, root.id, reply.id), 403)
|
||||
|
||||
flushAndClear()
|
||||
assertEquals("someone else's reply", findCheers(reply.id).cheers)
|
||||
assertTrue(findCheers(reply.id).isActive)
|
||||
assertTrue(findCheers(root.id).isActive)
|
||||
assertEquals(2L, countCheers())
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource(
|
||||
"PUT,anotherRoot",
|
||||
"DELETE_REPLY,anotherRoot",
|
||||
"PUT,nested",
|
||||
"DELETE_REPLY,nested",
|
||||
"PUT,mixed",
|
||||
"DELETE_REPLY,mixed"
|
||||
)
|
||||
@DisplayName("답글의 다른 부모·중첩 부모·불일치 creator 관계는 404로 거부한다")
|
||||
fun shouldRejectMismatchedDirectReplyRelations(operation: String, relation: String) {
|
||||
val root = saveRoot()
|
||||
val reply = when (relation) {
|
||||
"anotherRoot" -> saveReply(saveRoot(text = "another root"))
|
||||
"nested" -> saveReply(saveReply(root), text = "nested reply")
|
||||
"mixed" -> saveReply(root).apply { creator = otherOwner }
|
||||
else -> error("Unsupported test relation: $relation")
|
||||
}
|
||||
flushAndClear()
|
||||
val beforeCount = countCheers()
|
||||
val beforeContent = findCheers(reply.id).cheers
|
||||
|
||||
reject(request(operation, root.id, reply.id), 404)
|
||||
|
||||
flushAndClear()
|
||||
assertEquals(beforeCount, countCheers())
|
||||
assertEquals(beforeContent, findCheers(reply.id).cheers)
|
||||
assertTrue(findCheers(reply.id).isActive)
|
||||
assertTrue(findCheers(root.id).isActive)
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource("DELETE_ROOT,creatorRoot", "POST,creatorRoot", "DELETE_ROOT,reply", "POST,reply")
|
||||
@DisplayName("부모 삭제와 답글 등록은 크리에이터 작성 원글과 답글 ID를 팬 원글로 취급하지 않는다")
|
||||
fun shouldRejectCreatorRootsAndReplyIdsAsFanRoots(operation: String, targetKind: String) {
|
||||
val root = saveRoot()
|
||||
val target = when (targetKind) {
|
||||
"creatorRoot" -> saveRoot(writer = owner)
|
||||
"reply" -> saveReply(root)
|
||||
else -> error("Unsupported test target: $targetKind")
|
||||
}
|
||||
flushAndClear()
|
||||
val beforeCount = countCheers()
|
||||
|
||||
reject(request(operation, target.id, null), 404)
|
||||
|
||||
flushAndClear()
|
||||
assertEquals(beforeCount, countCheers())
|
||||
assertTrue(findCheers(target.id).isActive)
|
||||
assertTrue(findCheers(root.id).isActive)
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = ["DELETE_ROOT", "POST", "PUT", "DELETE_REPLY"])
|
||||
@DisplayName("존재하지 않는 팬톡 또는 답글 ID는 404이며 기존 row를 바꾸지 않는다")
|
||||
fun shouldRejectMissingResources(operation: String) {
|
||||
val root = saveRoot()
|
||||
val rootId = when (operation) {
|
||||
"DELETE_ROOT", "POST" -> Long.MAX_VALUE
|
||||
"PUT", "DELETE_REPLY" -> requireNotNull(root.id)
|
||||
else -> error("Unsupported test operation: $operation")
|
||||
}
|
||||
flushAndClear()
|
||||
|
||||
reject(request(operation, rootId, Long.MAX_VALUE), 404)
|
||||
|
||||
flushAndClear()
|
||||
assertEquals(1L, countCheers())
|
||||
assertTrue(findCheers(root.id).isActive)
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("삭제된 팬톡 부모에는 답글을 등록할 수 없으며 409와 기존 데이터 보존을 보장한다")
|
||||
fun shouldRejectReplyCreationForDeletedRoot() {
|
||||
val root = saveRoot().apply { isActive = false }
|
||||
flushAndClear()
|
||||
|
||||
reject(request("POST", root.id, null), 409)
|
||||
|
||||
flushAndClear()
|
||||
assertEquals(1L, countCheers())
|
||||
assertEquals(0, replies(root).size)
|
||||
assertEquals(false, findCheers(root.id).isActive)
|
||||
}
|
||||
|
||||
private fun request(operation: String, rootId: Long?, replyId: Long?): MockHttpServletRequestBuilder = when (operation) {
|
||||
"GET" -> get(BASE)
|
||||
"DELETE_ROOT" -> delete("$BASE/${requireNotNull(rootId)}")
|
||||
"POST" -> post("$BASE/${requireNotNull(rootId)}/replies")
|
||||
.contentType(MediaType.APPLICATION_JSON).content(body("new reply"))
|
||||
"PUT" -> put("$BASE/${requireNotNull(rootId)}/replies/${requireNotNull(replyId)}")
|
||||
.contentType(MediaType.APPLICATION_JSON).content(body("changed reply"))
|
||||
"DELETE_REPLY" -> delete("$BASE/${requireNotNull(rootId)}/replies/${requireNotNull(replyId)}")
|
||||
else -> error("Unsupported test operation: $operation")
|
||||
}
|
||||
}
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
package kr.co.vividnext.sodalive.v2.creator.admin.commentmanagement.fantalk
|
||||
|
||||
import org.junit.jupiter.api.Assertions.assertEquals
|
||||
import org.junit.jupiter.api.Assertions.assertTrue
|
||||
import org.junit.jupiter.api.DisplayName
|
||||
import org.junit.jupiter.params.ParameterizedTest
|
||||
import org.junit.jupiter.params.provider.Arguments
|
||||
import org.junit.jupiter.params.provider.MethodSource
|
||||
import org.springframework.http.MediaType
|
||||
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post
|
||||
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put
|
||||
import java.util.stream.Stream
|
||||
|
||||
class CreatorAdminFanTalkInputIntegrationTest : FanTalkIntegrationTestSupport() {
|
||||
@ParameterizedTest(name = "{0}: invalid JSON case {index}")
|
||||
@MethodSource("invalidBodies")
|
||||
@DisplayName("등록과 수정은 공백·누락·비문자열·알 수 없는 필드를 400으로 거부하고 DB를 바꾸지 않는다")
|
||||
fun shouldRejectInvalidReplyBodiesWithoutPersistenceChanges(method: String, json: String?) {
|
||||
val root = saveRoot()
|
||||
val general = saveReply(root, fan, "keep general reply")
|
||||
val existing = when (method) {
|
||||
"POST" -> null
|
||||
"PUT" -> saveReply(root, text = "keep owner reply")
|
||||
else -> error("Unsupported test method: $method")
|
||||
}
|
||||
flushAndClear()
|
||||
val beforeCount = countCheers()
|
||||
val beforeReplies = replies(root).map { Triple(it.id, it.cheers, it.isActive) }
|
||||
val request = when (method) {
|
||||
"POST" -> post("$BASE/${root.id}/replies")
|
||||
"PUT" -> put("$BASE/${root.id}/replies/${requireNotNull(existing).id}")
|
||||
else -> error("Unsupported test method: $method")
|
||||
}.contentType(MediaType.APPLICATION_JSON)
|
||||
json?.let { request.content(it.toByteArray(Charsets.UTF_8)) }
|
||||
|
||||
reject(request, 400)
|
||||
|
||||
flushAndClear()
|
||||
assertEquals(beforeCount, countCheers())
|
||||
assertEquals(beforeReplies, replies(root).map { Triple(it.id, it.cheers, it.isActive) })
|
||||
assertTrue(findCheers(root.id).isActive)
|
||||
assertTrue(findCheers(general.id).isActive)
|
||||
}
|
||||
|
||||
@ParameterizedTest(name = "{0}: accepted UTF-8 boundary case {index}")
|
||||
@MethodSource("maximumByteBodies")
|
||||
@DisplayName("등록과 수정은 ASCII·한글·이모지의 UTF-8 65535바이트 본문을 잘라내지 않고 저장한다")
|
||||
fun shouldPersistExactlyMaximumUtf8BytesWithoutTruncating(method: String, text: String) {
|
||||
val root = saveRoot()
|
||||
val existing = when (method) {
|
||||
"POST" -> null
|
||||
"PUT" -> saveReply(root, text = "before boundary update")
|
||||
else -> error("Unsupported test method: $method")
|
||||
}
|
||||
flushAndClear()
|
||||
val request = when (method) {
|
||||
"POST" -> post("$BASE/${root.id}/replies")
|
||||
"PUT" -> put("$BASE/${root.id}/replies/${requireNotNull(existing).id}")
|
||||
else -> error("Unsupported test method: $method")
|
||||
}.contentType(MediaType.APPLICATION_JSON).content(body(" $text \n"))
|
||||
|
||||
mutate(request)
|
||||
|
||||
flushAndClear()
|
||||
val saved = replies(root).single()
|
||||
assertEquals(text, saved.cheers)
|
||||
assertEquals(65535, saved.cheers.toByteArray(Charsets.UTF_8).size)
|
||||
assertEquals(owner.id, saved.member?.id)
|
||||
assertEquals(owner.id, saved.creator?.id)
|
||||
assertEquals(root.id, saved.parent?.id)
|
||||
assertTrue(saved.isActive)
|
||||
existing?.let { assertEquals(it.id, saved.id) }
|
||||
assertEquals(text, list().path("items").single().path("creatorReply").path("content").asText())
|
||||
}
|
||||
|
||||
private companion object {
|
||||
@JvmStatic
|
||||
fun invalidBodies(): Stream<Arguments> {
|
||||
val jsonBodies = listOf(
|
||||
null,
|
||||
"{}",
|
||||
"""{"content":null}""",
|
||||
"""{"content":""}""",
|
||||
"""{"content":" \t\r\n "}""",
|
||||
"""{"content":"\u2003\n\u3000"}""",
|
||||
"""{"content":123}""",
|
||||
"""{"content":true}""",
|
||||
"""{"content":{}}""",
|
||||
"""{"content":[]}""",
|
||||
"""{"content":"unterminated""",
|
||||
"""{"content":"reply","extra":"ignored"}""",
|
||||
"""{"content":"reply","authorId":123}""",
|
||||
"""{"content":"reply","isSecret":false}""",
|
||||
"""{"content":"reply","isActive":false}""",
|
||||
"""{"content":"${"a".repeat(65536)}"}""",
|
||||
"""{"content":"${"가".repeat(21846)}"}""",
|
||||
"""{"content":"${"\uD83D\uDE03".repeat(16384)}"}"""
|
||||
)
|
||||
return listOf("POST", "PUT").flatMap { method -> jsonBodies.map { Arguments.of(method, it) } }.stream()
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun maximumByteBodies(): Stream<Arguments> {
|
||||
val texts = listOf("a".repeat(65535), "가".repeat(21845), "\uD83D\uDE03".repeat(16383) + "abc")
|
||||
return listOf("POST", "PUT").flatMap { method -> texts.map { Arguments.of(method, it) } }.stream()
|
||||
}
|
||||
}
|
||||
}
|
||||
+185
@@ -0,0 +1,185 @@
|
||||
package kr.co.vividnext.sodalive.v2.creator.admin.commentmanagement.fantalk
|
||||
|
||||
import kr.co.vividnext.sodalive.member.block.BlockMember
|
||||
import org.junit.jupiter.api.Assertions.assertEquals
|
||||
import org.junit.jupiter.api.Assertions.assertFalse
|
||||
import org.junit.jupiter.api.Assertions.assertTrue
|
||||
import org.junit.jupiter.api.DisplayName
|
||||
import org.junit.jupiter.api.Test
|
||||
import org.junit.jupiter.params.ParameterizedTest
|
||||
import org.junit.jupiter.params.provider.CsvSource
|
||||
import org.junit.jupiter.params.provider.ValueSource
|
||||
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete
|
||||
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
|
||||
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath
|
||||
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status
|
||||
import java.time.LocalDateTime
|
||||
import java.time.ZoneOffset
|
||||
|
||||
class CreatorAdminFanTalkIntegrationTest : FanTalkIntegrationTestSupport() {
|
||||
@Test
|
||||
@DisplayName("다른 크리에이터가 내 채널에 남긴 팬톡도 조회하고 관리할 수 있다")
|
||||
fun shouldManageRootWrittenByAnotherCreator() {
|
||||
val root = saveRoot(writer = otherOwner)
|
||||
flushAndClear()
|
||||
|
||||
val data = list()
|
||||
assertEquals(listOf(root.id), data.path("items").map { it.path("fanTalkId").asLong() })
|
||||
assertEquals(1, data.path("totalCount").asInt())
|
||||
mutate(delete("$BASE/${root.id}"))
|
||||
flushAndClear()
|
||||
assertFalse(findCheers(root.id).isActive)
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = ["latest", "oldest"])
|
||||
@DisplayName("팬톡은 기본 10개씩 작성시각과 ID를 같은 방향으로 정렬하고 범위 초과 페이지를 보정하지 않는다")
|
||||
fun shouldPageTenRootsWithStableTimestampAndIdOrder(order: String) {
|
||||
val newest = saveRoot(text = "newest")
|
||||
setCreatedAt(newest, CREATED_AT.plusMinutes(1))
|
||||
val tied = (1..12).map { index ->
|
||||
saveRoot(text = "tied $index").also { setCreatedAt(it, CREATED_AT) }
|
||||
}
|
||||
val oldest = saveRoot(text = "oldest")
|
||||
setCreatedAt(oldest, CREATED_AT.minusMinutes(1))
|
||||
saveReply(tied.first())
|
||||
flushAndClear()
|
||||
val ascendingIds = listOf(oldest.id) + tied.map { it.id } + newest.id
|
||||
val expectedIds = when (order) {
|
||||
"latest" -> ascendingIds.reversed()
|
||||
"oldest" -> ascendingIds
|
||||
else -> error("Unsupported test order: $order")
|
||||
}
|
||||
|
||||
(0..2).forEach { page ->
|
||||
val data = list(get(BASE).param("order", order).param("page", page.toString()))
|
||||
|
||||
assertEquals(expectedIds.drop(page * 10).take(10), data.path("items").map { it.path("fanTalkId").asLong() })
|
||||
assertEquals(14, data.path("totalCount").asInt())
|
||||
assertEquals(page, data.path("page").asInt())
|
||||
assertEquals(10, data.path("size").asInt())
|
||||
assertEquals(page == 0, data.path("hasNext").asBoolean())
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("기본 최신순 목록은 소유 채널의 활성 팬 원글만 반환하고 차단 작성자를 관리 범위에서 숨기지 않는다")
|
||||
fun shouldScopeDefaultListToOwnedActiveFanRootsIncludingBlockedWriters() {
|
||||
val first = saveRoot(text = "first root")
|
||||
val second = saveRoot(text = "second root")
|
||||
setCreatedAt(first, CREATED_AT)
|
||||
setCreatedAt(second, CREATED_AT)
|
||||
saveRoot(creator = otherOwner)
|
||||
saveRoot(writer = owner, text = "creator root")
|
||||
saveRoot().isActive = false
|
||||
saveReply(second, fan, "general reply")
|
||||
entityManager.persist(
|
||||
BlockMember().apply {
|
||||
member = owner
|
||||
blockedMember = fan
|
||||
}
|
||||
)
|
||||
flushAndClear()
|
||||
|
||||
val data = list()
|
||||
|
||||
assertEquals(listOf(second.id, first.id), data.path("items").map { it.path("fanTalkId").asLong() })
|
||||
assertEquals(2, data.path("totalCount").asInt())
|
||||
assertEquals(0, data.path("page").asInt())
|
||||
assertEquals(10, data.path("size").asInt())
|
||||
assertFalse(data.path("hasNext").asBoolean())
|
||||
val item = data.path("items").first()
|
||||
assertEquals("second root", item.path("content").asText())
|
||||
assertEquals("2026-11-20T12:00:00Z", item.path("createdAtUtc").asText())
|
||||
assertFalse(item.path("isSecret").asBoolean(true))
|
||||
assertTrue(item.path("creatorReply").isNull)
|
||||
val writer = item.path("writer")
|
||||
assertEquals(setOf("memberId", "nickname", "profileImageUrl"), writer.fieldNames().asSequence().toSet())
|
||||
assertEquals(fan.id, writer.path("memberId").asLong())
|
||||
assertEquals(fan.nickname, writer.path("nickname").asText())
|
||||
assertEquals("https://test.cloudfront.net/${fan.profileImage}", writer.path("profileImageUrl").asText())
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("팬톡 작성자 프로필이 없어도 nullable profileImageUrl 필드는 응답에 포함된다")
|
||||
fun shouldIncludeProfileImageFieldWhenWriterHasNoProfile() {
|
||||
fan.profileImage = null
|
||||
saveRoot()
|
||||
flushAndClear()
|
||||
|
||||
val writer = list().path("items").single().path("writer")
|
||||
|
||||
assertEquals(fan.id, writer.path("memberId").asLong())
|
||||
assertEquals(fan.nickname, writer.path("nickname").asText())
|
||||
assertTrue(writer.has("profileImageUrl"))
|
||||
val image = writer.path("profileImageUrl")
|
||||
assertTrue(image.isNull || image.asText() == "https://test.cloudfront.net/profile/default-profile.png")
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(ints = [0, 123456789, 999999999])
|
||||
@DisplayName("팬톡과 답글 시각은 날짜 경계와 소수초를 DB 왕복한 값 그대로 UTC로 반환한다")
|
||||
fun shouldReturnUtcTimesFromDatabaseReadback(nanos: Int) {
|
||||
val root = saveRoot()
|
||||
val reply = saveReply(root)
|
||||
val time = LocalDateTime.of(2026, 11, 20, 23, 59, 59, nanos)
|
||||
setCreatedAt(root, time)
|
||||
setCreatedAt(reply, time)
|
||||
flushAndClear()
|
||||
val rootTime = requireNotNull(findCheers(root.id).createdAt).toInstant(ZoneOffset.UTC).toString()
|
||||
val replyTime = requireNotNull(findCheers(reply.id).createdAt).toInstant(ZoneOffset.UTC).toString()
|
||||
entityManager.clear()
|
||||
|
||||
val item = list().path("items").single()
|
||||
|
||||
assertEquals(rootTime, item.path("createdAtUtc").asText())
|
||||
assertEquals(replyTime, item.path("creatorReply").path("createdAtUtc").asText())
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("소유 팬톡이 없으면 빈 목록과 기본 페이지 메타데이터를 반환한다")
|
||||
fun shouldReturnEmptyPageForOwnerWithoutRoots() {
|
||||
saveRoot(creator = otherOwner)
|
||||
flushAndClear()
|
||||
|
||||
val data = list()
|
||||
|
||||
assertTrue(data.path("items").isArray)
|
||||
assertEquals(0, data.path("items").size())
|
||||
assertEquals(0, data.path("totalCount").asInt())
|
||||
assertEquals(0, data.path("page").asInt())
|
||||
assertEquals(10, data.path("size").asInt())
|
||||
assertFalse(data.path("hasNext").asBoolean())
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource("page,-1", "size,0", "size,101", "order,invalid")
|
||||
@DisplayName("팬톡 목록의 잘못된 페이지 크기와 정렬 값은 400으로 거부한다")
|
||||
fun shouldRejectInvalidListParameters(name: String, value: String) {
|
||||
reject(get(BASE).param(name, value), 400)
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("팬톡 부모 삭제는 자식 row를 유지하면서 관리자와 앱 목록 및 count에서 스레드를 숨긴다")
|
||||
fun shouldSoftDeleteRootAndHideThreadWithoutDeletingChildren() {
|
||||
val root = saveRoot()
|
||||
val reply = saveReply(root)
|
||||
val generalReply = saveReply(root, fan, "general reply")
|
||||
flushAndClear()
|
||||
|
||||
mutate(delete("$BASE/${root.id}"))
|
||||
|
||||
flushAndClear()
|
||||
assertFalse(findCheers(root.id).isActive)
|
||||
assertTrue(findCheers(reply.id).isActive)
|
||||
assertTrue(findCheers(generalReply.id).isActive)
|
||||
assertEquals(listOf(reply.id, generalReply.id), replies(root).map { it.id })
|
||||
val data = list()
|
||||
assertEquals(0, data.path("totalCount").asInt())
|
||||
assertEquals(0, data.path("items").size())
|
||||
perform(get("/api/v2/creator-channels/${owner.id}/fan-talks"), fan)
|
||||
.andExpect(status().isOk)
|
||||
.andExpect(jsonPath("$.data.fanTalkCount").value(0))
|
||||
.andExpect(jsonPath("$.data.fanTalks.length()").value(0))
|
||||
}
|
||||
}
|
||||
+189
@@ -0,0 +1,189 @@
|
||||
package kr.co.vividnext.sodalive.v2.creator.admin.commentmanagement.fantalk
|
||||
|
||||
import org.junit.jupiter.api.Assertions.assertEquals
|
||||
import org.junit.jupiter.api.Assertions.assertFalse
|
||||
import org.junit.jupiter.api.Assertions.assertNotEquals
|
||||
import org.junit.jupiter.api.Assertions.assertTrue
|
||||
import org.junit.jupiter.api.DisplayName
|
||||
import org.junit.jupiter.api.Test
|
||||
import org.junit.jupiter.params.ParameterizedTest
|
||||
import org.junit.jupiter.params.provider.ValueSource
|
||||
import org.springframework.http.MediaType
|
||||
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete
|
||||
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
|
||||
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post
|
||||
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put
|
||||
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath
|
||||
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status
|
||||
import java.time.ZoneOffset
|
||||
|
||||
class CreatorAdminFanTalkReplyIntegrationTest : FanTalkIntegrationTestSupport() {
|
||||
@Test
|
||||
@DisplayName("팬톡 답글 등록과 수정은 정규화한 Unicode 본문을 본인 명의로 저장하고 200 null data를 반환한다")
|
||||
fun shouldPersistCreatedAndUpdatedOwnerReplyWithUnicodeAndNewlines() {
|
||||
val root = saveRoot()
|
||||
setCreatedAt(root, CREATED_AT)
|
||||
flushAndClear()
|
||||
|
||||
mutate(
|
||||
post("$BASE/${root.id}/replies").contentType(MediaType.APPLICATION_JSON)
|
||||
.content(body(" 고마워요\nありがとう \uD83D\uDE03\n두 번째 줄 "))
|
||||
)
|
||||
|
||||
flushAndClear()
|
||||
val created = replies(root).single()
|
||||
val replyId = created.id
|
||||
val createdAt = created.createdAt
|
||||
assertEquals("고마워요\nありがとう \uD83D\uDE03\n두 번째 줄", created.cheers)
|
||||
assertEquals(root.id, created.parent?.id)
|
||||
assertEquals(owner.id, created.member?.id)
|
||||
assertEquals(owner.id, created.creator?.id)
|
||||
assertTrue(created.isActive)
|
||||
assertTrue(findCheers(root.id).isActive)
|
||||
val response = list().path("items").single().path("creatorReply")
|
||||
assertEquals(replyId, response.path("replyId").asLong())
|
||||
assertEquals(created.cheers, response.path("content").asText())
|
||||
assertEquals(requireNotNull(createdAt).toInstant(ZoneOffset.UTC).toString(), response.path("createdAtUtc").asText())
|
||||
assertEquals(owner.id, response.path("writer").path("memberId").asLong())
|
||||
assertEquals(owner.nickname, response.path("writer").path("nickname").asText())
|
||||
assertEquals(
|
||||
"https://test.cloudfront.net/${owner.profileImage}",
|
||||
response.path("writer").path("profileImageUrl").asText()
|
||||
)
|
||||
assertFalse(response.path("isSecret").asBoolean(true))
|
||||
|
||||
mutate(
|
||||
put("$BASE/${root.id}/replies/$replyId").contentType(MediaType.APPLICATION_JSON)
|
||||
.content(body(" \n수정한 답글\nこんにちは \uD83C\uDF1F "))
|
||||
)
|
||||
|
||||
flushAndClear()
|
||||
val updated = findCheers(replyId)
|
||||
assertEquals("수정한 답글\nこんにちは \uD83C\uDF1F", updated.cheers)
|
||||
assertEquals(createdAt, updated.createdAt)
|
||||
assertEquals(owner.id, updated.member?.id)
|
||||
assertEquals(owner.id, updated.creator?.id)
|
||||
assertEquals(root.id, updated.parent?.id)
|
||||
assertTrue(updated.isActive)
|
||||
assertEquals(1, replies(root).size)
|
||||
assertEquals(updated.cheers, list().path("items").single().path("creatorReply").path("content").asText())
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("관리자는 작성시각과 ID가 최신인 활성 소유자 직계 답글 하나만 표시하고 기존 다중 답글을 보존한다")
|
||||
fun shouldSelectLatestActiveDirectOwnerReplyWithoutCollapsingExistingReplies() {
|
||||
val root = saveRoot()
|
||||
val earlier = saveReply(root, text = "earlier")
|
||||
setCreatedAt(earlier, CREATED_AT)
|
||||
val tied = saveReply(root, text = "first tied")
|
||||
setCreatedAt(tied, CREATED_AT.plusMinutes(1))
|
||||
val latest = saveReply(root, text = "last tied")
|
||||
setCreatedAt(latest, CREATED_AT.plusMinutes(1))
|
||||
val higherIdOlderReply = saveReply(root, text = "higher ID but older")
|
||||
setCreatedAt(higherIdOlderReply, CREATED_AT.minusMinutes(1))
|
||||
entityManager.createQuery("update CreatorCheers c set c.updatedAt = :time where c.id = :id")
|
||||
.setParameter("time", CREATED_AT.plusYears(1)).setParameter("id", higherIdOlderReply.id).executeUpdate()
|
||||
val general = saveReply(root, fan, "general reply")
|
||||
setCreatedAt(general, CREATED_AT.plusMinutes(2))
|
||||
val inactive = saveReply(root).apply { isActive = false }
|
||||
setCreatedAt(inactive, CREATED_AT.plusMinutes(3))
|
||||
val nested = saveReply(latest, text = "nested owner reply")
|
||||
setCreatedAt(nested, CREATED_AT.plusMinutes(4))
|
||||
val foreignWriter = saveReply(root, otherOwner, "another creator wrote this")
|
||||
setCreatedAt(foreignWriter, CREATED_AT.plusMinutes(5))
|
||||
val mixedCreator = saveReply(root, text = "wrong creator relation").apply { creator = otherOwner }
|
||||
setCreatedAt(mixedCreator, CREATED_AT.plusMinutes(6))
|
||||
flushAndClear()
|
||||
|
||||
val reply = list().path("items").single().path("creatorReply")
|
||||
|
||||
assertEquals(latest.id, reply.path("replyId").asLong())
|
||||
assertEquals("last tied", reply.path("content").asText())
|
||||
assertEquals("2026-11-20T12:01:00Z", reply.path("createdAtUtc").asText())
|
||||
assertEquals(owner.id, reply.path("writer").path("memberId").asLong())
|
||||
assertFalse(reply.path("isSecret").asBoolean(true))
|
||||
flushAndClear()
|
||||
assertEquals(
|
||||
listOf(
|
||||
earlier.id,
|
||||
tied.id,
|
||||
latest.id,
|
||||
higherIdOlderReply.id,
|
||||
general.id,
|
||||
inactive.id,
|
||||
foreignWriter.id,
|
||||
mixedCreator.id
|
||||
),
|
||||
replies(root).map { it.id }
|
||||
)
|
||||
assertTrue(findCheers(nested.id).isActive)
|
||||
assertTrue(findCheers(general.id).isActive)
|
||||
perform(get("/api/v2/creator-channels/${owner.id}/fan-talks"), fan)
|
||||
.andExpect(status().isOk)
|
||||
.andExpect(jsonPath("$.data.fanTalks[0].creatorReplies.length()").value(4))
|
||||
.andExpect(jsonPath("$.data.fanTalks[0].creatorReplies[0].fanTalkId").value(higherIdOlderReply.id))
|
||||
.andExpect(jsonPath("$.data.fanTalks[0].creatorReplies[3].fanTalkId").value(latest.id))
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("최신 답글 삭제는 이전 답글을 드러내고 모든 소유자 답글 삭제 후에만 일반 답글을 유지하며 재등록한다")
|
||||
fun shouldRevealPriorReplyAndAllowRecreationOnlyAfterEveryOwnerReplyIsDeleted() {
|
||||
val root = saveRoot()
|
||||
val prior = saveReply(root, text = "prior")
|
||||
setCreatedAt(prior, CREATED_AT)
|
||||
val latest = saveReply(root, text = "latest")
|
||||
setCreatedAt(latest, CREATED_AT.plusMinutes(1))
|
||||
val general = saveReply(root, fan, "general reply survives")
|
||||
flushAndClear()
|
||||
|
||||
reject(post("$BASE/${root.id}/replies").contentType(MediaType.APPLICATION_JSON).content(body("duplicate")), 409)
|
||||
mutate(delete("$BASE/${root.id}/replies/${latest.id}"))
|
||||
|
||||
flushAndClear()
|
||||
assertFalse(findCheers(latest.id).isActive)
|
||||
assertTrue(findCheers(prior.id).isActive)
|
||||
assertEquals(prior.id, list().path("items").single().path("creatorReply").path("replyId").asLong())
|
||||
reject(post("$BASE/${root.id}/replies").contentType(MediaType.APPLICATION_JSON).content(body("still duplicate")), 409)
|
||||
flushAndClear()
|
||||
assertEquals(3, replies(root).size)
|
||||
|
||||
mutate(delete("$BASE/${root.id}/replies/${prior.id}"))
|
||||
|
||||
flushAndClear()
|
||||
assertFalse(findCheers(prior.id).isActive)
|
||||
assertTrue(list().path("items").single().path("creatorReply").isNull)
|
||||
mutate(post("$BASE/${root.id}/replies").contentType(MediaType.APPLICATION_JSON).content(body("new reply")))
|
||||
|
||||
flushAndClear()
|
||||
val recreated = replies(root).single { it.isActive && it.member?.id == owner.id }
|
||||
assertNotEquals(prior.id, recreated.id)
|
||||
assertNotEquals(latest.id, recreated.id)
|
||||
assertEquals("new reply", recreated.cheers)
|
||||
assertEquals(owner.id, recreated.creator?.id)
|
||||
assertTrue(findCheers(root.id).isActive)
|
||||
assertTrue(findCheers(general.id).isActive)
|
||||
assertEquals("general reply survives", findCheers(general.id).cheers)
|
||||
assertEquals(4, replies(root).size)
|
||||
assertEquals(recreated.id, list().path("items").single().path("creatorReply").path("replyId").asLong())
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = ["same reply", " same reply\n "])
|
||||
@DisplayName("정규화 후 동일한 본문 PUT은 성공 no-op이며 본문과 생성 및 수정 시각을 바꾸지 않는다")
|
||||
fun shouldKeepPersistedTimestampsForIdenticalNormalizedPut(text: String) {
|
||||
val root = saveRoot()
|
||||
val reply = saveReply(root, text = "same reply")
|
||||
setCreatedAt(reply, CREATED_AT)
|
||||
flushAndClear()
|
||||
|
||||
mutate(put("$BASE/${root.id}/replies/${reply.id}").contentType(MediaType.APPLICATION_JSON).content(body(text)))
|
||||
|
||||
flushAndClear()
|
||||
val unchanged = findCheers(reply.id)
|
||||
assertEquals("same reply", unchanged.cheers)
|
||||
assertEquals(CREATED_AT, unchanged.createdAt)
|
||||
assertEquals(CREATED_AT, unchanged.updatedAt)
|
||||
assertTrue(unchanged.isActive)
|
||||
assertEquals(1, replies(root).size)
|
||||
}
|
||||
}
|
||||
+146
@@ -0,0 +1,146 @@
|
||||
package kr.co.vividnext.sodalive.v2.creator.admin.commentmanagement.fantalk
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode
|
||||
import com.fasterxml.jackson.databind.ObjectMapper
|
||||
import kr.co.vividnext.sodalive.explorer.profile.CreatorCheers
|
||||
import kr.co.vividnext.sodalive.member.Member
|
||||
import kr.co.vividnext.sodalive.member.MemberAdapter
|
||||
import kr.co.vividnext.sodalive.member.MemberRole
|
||||
import kr.co.vividnext.sodalive.support.EmbeddedRedisInitializer
|
||||
import org.hamcrest.Matchers.nullValue
|
||||
import org.junit.jupiter.api.BeforeEach
|
||||
import org.springframework.beans.factory.annotation.Autowired
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc
|
||||
import org.springframework.boot.test.context.SpringBootTest
|
||||
import org.springframework.http.MediaType
|
||||
import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user
|
||||
import org.springframework.test.context.ContextConfiguration
|
||||
import org.springframework.test.web.servlet.MockMvc
|
||||
import org.springframework.test.web.servlet.ResultActions
|
||||
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder
|
||||
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
|
||||
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.content
|
||||
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath
|
||||
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status
|
||||
import org.springframework.transaction.annotation.Transactional
|
||||
import java.time.LocalDateTime
|
||||
import javax.persistence.EntityManager
|
||||
|
||||
@SpringBootTest(properties = ["cloud.aws.cloud-front.host=https://test.cloudfront.net"])
|
||||
@AutoConfigureMockMvc
|
||||
@Transactional
|
||||
@ContextConfiguration(initializers = [EmbeddedRedisInitializer::class])
|
||||
abstract class FanTalkIntegrationTestSupport {
|
||||
@Autowired
|
||||
protected lateinit var mockMvc: MockMvc
|
||||
|
||||
@Autowired
|
||||
protected lateinit var objectMapper: ObjectMapper
|
||||
|
||||
@Autowired
|
||||
protected lateinit var entityManager: EntityManager
|
||||
|
||||
protected lateinit var owner: Member
|
||||
protected lateinit var otherOwner: Member
|
||||
protected lateinit var fan: Member
|
||||
|
||||
@BeforeEach
|
||||
fun setUpMembers() {
|
||||
owner = saveMember("fantalk-management-owner", MemberRole.CREATOR)
|
||||
otherOwner = saveMember("fantalk-management-other-owner", MemberRole.CREATOR)
|
||||
fan = saveMember("fantalk-management-fan")
|
||||
}
|
||||
|
||||
protected fun saveMember(nickname: String, role: MemberRole = MemberRole.USER): Member = Member(
|
||||
email = "$nickname@test.com",
|
||||
password = "password",
|
||||
nickname = nickname,
|
||||
profileImage = "$nickname.png",
|
||||
role = role
|
||||
).also(entityManager::persist)
|
||||
|
||||
protected fun saveRoot(
|
||||
writer: Member = fan,
|
||||
creator: Member = owner,
|
||||
text: String = "fan root"
|
||||
): CreatorCheers = CreatorCheers(cheers = text, languageCode = "ko").apply {
|
||||
member = writer
|
||||
this.creator = creator
|
||||
}.also(entityManager::persist)
|
||||
|
||||
protected fun saveReply(
|
||||
root: CreatorCheers,
|
||||
writer: Member = owner,
|
||||
text: String = "creator reply"
|
||||
): CreatorCheers = CreatorCheers(cheers = text, languageCode = "ko").apply {
|
||||
parent = root
|
||||
member = writer
|
||||
creator = root.creator
|
||||
}.also(entityManager::persist)
|
||||
|
||||
protected fun setCreatedAt(cheers: CreatorCheers, time: LocalDateTime) {
|
||||
entityManager.flush()
|
||||
entityManager.createQuery("update CreatorCheers c set c.createdAt = :time, c.updatedAt = :time where c.id = :id")
|
||||
.setParameter("time", time)
|
||||
.setParameter("id", cheers.id)
|
||||
.executeUpdate()
|
||||
}
|
||||
|
||||
protected fun flushAndClear() {
|
||||
entityManager.flush()
|
||||
entityManager.clear()
|
||||
}
|
||||
|
||||
protected fun findCheers(id: Long?): CreatorCheers = requireNotNull(
|
||||
entityManager.find(CreatorCheers::class.java, requireNotNull(id))
|
||||
)
|
||||
|
||||
protected fun replies(root: CreatorCheers): List<CreatorCheers> = entityManager.createQuery(
|
||||
"select c from CreatorCheers c where c.parent.id = :rootId order by c.id",
|
||||
CreatorCheers::class.java
|
||||
).setParameter("rootId", root.id).resultList
|
||||
|
||||
protected fun countCheers(): Long = entityManager.createQuery(
|
||||
"select count(c) from CreatorCheers c",
|
||||
java.lang.Long::class.java
|
||||
).singleResult.toLong()
|
||||
|
||||
protected fun perform(request: MockHttpServletRequestBuilder, member: Member = owner): ResultActions = mockMvc.perform(
|
||||
request.header("Accept-Language", "en").with(user(MemberAdapter(member)))
|
||||
)
|
||||
|
||||
protected fun list(request: MockHttpServletRequestBuilder = get(BASE)): JsonNode {
|
||||
val result = perform(request)
|
||||
.andExpect(status().isOk)
|
||||
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("$.success").value(true))
|
||||
.andExpect(jsonPath("$.message").value(nullValue()))
|
||||
.andReturn()
|
||||
return objectMapper.readTree(result.response.contentAsByteArray).path("data")
|
||||
}
|
||||
|
||||
protected fun mutate(request: MockHttpServletRequestBuilder) {
|
||||
perform(request)
|
||||
.andExpect(status().isOk)
|
||||
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("$.success").value(true))
|
||||
.andExpect(jsonPath("$.message").value(nullValue()))
|
||||
.andExpect(jsonPath("$.data").value(nullValue()))
|
||||
}
|
||||
|
||||
protected fun reject(request: MockHttpServletRequestBuilder, code: Int) {
|
||||
perform(request)
|
||||
.andExpect(status().`is`(code))
|
||||
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("$.success").value(false))
|
||||
.andExpect(jsonPath("$.message").isString)
|
||||
.andExpect(jsonPath("$.data").value(nullValue()))
|
||||
}
|
||||
|
||||
protected fun body(text: String): ByteArray = objectMapper.writeValueAsBytes(mapOf("content" to text))
|
||||
|
||||
protected companion object {
|
||||
const val BASE = "/api/v2/creator-admin/comment-management/fantalks"
|
||||
val CREATED_AT: LocalDateTime = LocalDateTime.of(2026, 11, 20, 12, 0)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user