feat(creator-admin): 커뮤니티 게시글과 댓글 관리를 추가한다
This commit is contained in:
+131
@@ -0,0 +1,131 @@
|
||||
package kr.co.vividnext.sodalive.v2.creator.admin.commentmanagement.community.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.community.application.CreatorAdminCommunityService
|
||||
import kr.co.vividnext.sodalive.v2.creator.admin.commentmanagement.community.dto.CreatorAdminCommunityCommentQuery
|
||||
import kr.co.vividnext.sodalive.v2.creator.admin.commentmanagement.domain.CreatorAdminCommentPolicy
|
||||
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/community/posts")
|
||||
class CreatorAdminCommunityController(
|
||||
private val service: CreatorAdminCommunityService,
|
||||
private val parser: CreatorAdminCommentRequestParser
|
||||
) {
|
||||
@GetMapping
|
||||
fun posts(
|
||||
@AuthenticationPrincipal(expression = "#this == 'anonymousUser' ? null : member") member: Member?,
|
||||
@RequestParam(defaultValue = "0") page: Int,
|
||||
@RequestParam(defaultValue = "10") size: Int,
|
||||
@RequestParam(defaultValue = "latest") order: String
|
||||
) = ApiResponse.ok(
|
||||
service.posts(
|
||||
requireCreator(member),
|
||||
CreatorAdminCommentPolicy.parsePage(page, size),
|
||||
CreatorAdminCommentPolicy.parseOrder(order)
|
||||
)
|
||||
)
|
||||
|
||||
@GetMapping("/{postId}")
|
||||
fun post(
|
||||
@AuthenticationPrincipal(expression = "#this == 'anonymousUser' ? null : member") member: Member?,
|
||||
@PathVariable postId: Long
|
||||
) = ApiResponse.ok(service.post(requireCreator(member), CreatorAdminCommentPolicy.requirePositiveId(postId)))
|
||||
|
||||
@GetMapping("/{postId}/comments")
|
||||
fun comments(
|
||||
@AuthenticationPrincipal(expression = "#this == 'anonymousUser' ? null : member") member: Member?,
|
||||
@PathVariable postId: Long,
|
||||
@RequestParam(defaultValue = "0") page: Int,
|
||||
@RequestParam(defaultValue = "10") size: Int,
|
||||
@RequestParam(defaultValue = "latest") order: String,
|
||||
@RequestParam(defaultValue = "all") visibility: String
|
||||
) = ApiResponse.ok(
|
||||
service.comments(
|
||||
requireCreator(member),
|
||||
CreatorAdminCommentPolicy.requirePositiveId(postId),
|
||||
CreatorAdminCommunityCommentQuery(
|
||||
CreatorAdminCommentPolicy.parsePage(page, size),
|
||||
CreatorAdminCommentPolicy.parseOrder(order),
|
||||
CreatorAdminCommentPolicy.parseVisibility(visibility)
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
@DeleteMapping("/{postId}/comments/{commentId}")
|
||||
fun deleteComment(
|
||||
@AuthenticationPrincipal(expression = "#this == 'anonymousUser' ? null : member") member: Member?,
|
||||
@PathVariable postId: Long,
|
||||
@PathVariable commentId: Long
|
||||
): ApiResponse<Unit> {
|
||||
service.deleteComment(
|
||||
requireCreator(member),
|
||||
CreatorAdminCommentPolicy.requirePositiveId(postId),
|
||||
CreatorAdminCommentPolicy.requirePositiveId(commentId)
|
||||
)
|
||||
return ApiResponse.ok()
|
||||
}
|
||||
|
||||
@PostMapping("/{postId}/comments/{commentId}/replies", consumes = [MediaType.APPLICATION_JSON_VALUE])
|
||||
fun createReply(
|
||||
@AuthenticationPrincipal(expression = "#this == 'anonymousUser' ? null : member") member: Member?,
|
||||
@PathVariable postId: Long,
|
||||
@PathVariable commentId: Long,
|
||||
@RequestBody body: String
|
||||
): ApiResponse<Unit> {
|
||||
service.createReply(
|
||||
requireCreator(member),
|
||||
CreatorAdminCommentPolicy.requirePositiveId(postId),
|
||||
CreatorAdminCommentPolicy.requirePositiveId(commentId),
|
||||
parser.parseReply(body).content
|
||||
)
|
||||
return ApiResponse.ok()
|
||||
}
|
||||
|
||||
@PutMapping("/{postId}/comments/{commentId}/replies/{replyId}", consumes = [MediaType.APPLICATION_JSON_VALUE])
|
||||
fun updateReply(
|
||||
@AuthenticationPrincipal(expression = "#this == 'anonymousUser' ? null : member") member: Member?,
|
||||
@PathVariable postId: Long,
|
||||
@PathVariable commentId: Long,
|
||||
@PathVariable replyId: Long,
|
||||
@RequestBody body: String
|
||||
): ApiResponse<Unit> {
|
||||
service.updateReply(
|
||||
requireCreator(member),
|
||||
CreatorAdminCommentPolicy.requirePositiveId(postId),
|
||||
CreatorAdminCommentPolicy.requirePositiveId(commentId),
|
||||
CreatorAdminCommentPolicy.requirePositiveId(replyId),
|
||||
parser.parseReply(body).content
|
||||
)
|
||||
return ApiResponse.ok()
|
||||
}
|
||||
|
||||
@DeleteMapping("/{postId}/comments/{commentId}/replies/{replyId}")
|
||||
fun deleteReply(
|
||||
@AuthenticationPrincipal(expression = "#this == 'anonymousUser' ? null : member") member: Member?,
|
||||
@PathVariable postId: Long,
|
||||
@PathVariable commentId: Long,
|
||||
@PathVariable replyId: Long
|
||||
): ApiResponse<Unit> {
|
||||
service.deleteReply(
|
||||
requireCreator(member),
|
||||
CreatorAdminCommentPolicy.requirePositiveId(postId),
|
||||
CreatorAdminCommentPolicy.requirePositiveId(commentId),
|
||||
CreatorAdminCommentPolicy.requirePositiveId(replyId)
|
||||
)
|
||||
return ApiResponse.ok()
|
||||
}
|
||||
}
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
package kr.co.vividnext.sodalive.v2.creator.admin.commentmanagement.community.adapter.out.persistence
|
||||
|
||||
import com.querydsl.jpa.JPAExpressions
|
||||
import com.querydsl.jpa.impl.JPAQueryFactory
|
||||
import kr.co.vividnext.sodalive.explorer.profile.creatorCommunity.CreatorCommunity
|
||||
import kr.co.vividnext.sodalive.explorer.profile.creatorCommunity.CreatorCommunityRepository
|
||||
import kr.co.vividnext.sodalive.explorer.profile.creatorCommunity.QCreatorCommunity.creatorCommunity
|
||||
import kr.co.vividnext.sodalive.explorer.profile.creatorCommunity.comment.CreatorCommunityComment
|
||||
import kr.co.vividnext.sodalive.explorer.profile.creatorCommunity.comment.QCreatorCommunityComment
|
||||
import kr.co.vividnext.sodalive.explorer.profile.creatorCommunity.comment.QCreatorCommunityComment.creatorCommunityComment
|
||||
import kr.co.vividnext.sodalive.v2.creator.admin.commentmanagement.community.dto.CreatorAdminCommunityCommentQuery
|
||||
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.domain.CreatorAdminCommentVisibility
|
||||
import kr.co.vividnext.sodalive.v2.creator.admin.commentmanagement.dto.CreatorAdminCommentCountsResponse
|
||||
import org.springframework.stereotype.Repository
|
||||
import javax.persistence.EntityManager
|
||||
import javax.persistence.LockModeType
|
||||
|
||||
@Repository
|
||||
class CreatorAdminCommunityRepository(
|
||||
private val queryFactory: JPAQueryFactory,
|
||||
private val entityManager: EntityManager,
|
||||
private val postRepository: CreatorCommunityRepository
|
||||
) {
|
||||
fun findPost(postId: Long): CreatorCommunity? = postRepository.findByIdAndIsActiveTrue(postId)
|
||||
|
||||
fun lockPost(postId: Long): CreatorCommunity? {
|
||||
val post = postRepository.findByIdAndIsActiveTrueForUpdate(postId) ?: return null
|
||||
entityManager.refresh(post, LockModeType.PESSIMISTIC_WRITE)
|
||||
return post.takeIf { it.isActive }
|
||||
}
|
||||
|
||||
fun countPosts(ownerId: Long): Long = requireNotNull(
|
||||
queryFactory.select(creatorCommunity.id.count()).from(creatorCommunity)
|
||||
.where(creatorCommunity.member.id.eq(ownerId), creatorCommunity.isActive.isTrue)
|
||||
.fetchOne()
|
||||
)
|
||||
|
||||
fun findPosts(ownerId: Long, page: CreatorAdminCommentPage, order: CreatorAdminCommentOrder): List<CreatorCommunity> {
|
||||
val sorting = when (order) {
|
||||
CreatorAdminCommentOrder.LATEST -> arrayOf(creatorCommunity.createdAt.desc(), creatorCommunity.id.desc())
|
||||
CreatorAdminCommentOrder.OLDEST -> arrayOf(creatorCommunity.createdAt.asc(), creatorCommunity.id.asc())
|
||||
}
|
||||
return queryFactory.selectFrom(creatorCommunity)
|
||||
.where(creatorCommunity.member.id.eq(ownerId), creatorCommunity.isActive.isTrue)
|
||||
.orderBy(*sorting).offset(page.offset).limit(page.size.toLong())
|
||||
.fetch()
|
||||
}
|
||||
|
||||
fun parentCounts(postIds: List<Long>): Map<Long, Long> {
|
||||
if (postIds.isEmpty()) return emptyMap()
|
||||
val comment = creatorCommunityComment
|
||||
val count = comment.id.count()
|
||||
return queryFactory.select(comment.creatorCommunity.id, count).from(comment)
|
||||
.where(comment.creatorCommunity.id.`in`(postIds), comment.isActive.isTrue, comment.parent.isNull)
|
||||
.groupBy(comment.creatorCommunity.id).fetch()
|
||||
.associate { requireNotNull(it.get(comment.creatorCommunity.id)) to requireNotNull(it.get(count)) }
|
||||
}
|
||||
|
||||
fun commentCounts(postId: Long): CreatorAdminCommentCountsResponse {
|
||||
val comment = creatorCommunityComment
|
||||
val count = comment.id.count()
|
||||
val counts = queryFactory.select(comment.isSecret, count).from(comment)
|
||||
.where(comment.creatorCommunity.id.eq(postId), comment.isActive.isTrue, comment.parent.isNull)
|
||||
.groupBy(comment.isSecret).fetch()
|
||||
.associate { requireNotNull(it.get(comment.isSecret)) to requireNotNull(it.get(count)) }
|
||||
val public = counts[false] ?: 0L
|
||||
val secret = counts[true] ?: 0L
|
||||
return CreatorAdminCommentCountsResponse(all = public + secret, public = public, secret = secret)
|
||||
}
|
||||
|
||||
fun findComments(postId: Long, query: CreatorAdminCommunityCommentQuery): List<CreatorCommunityComment> {
|
||||
val comment = creatorCommunityComment
|
||||
val visibility = when (query.visibility) {
|
||||
CreatorAdminCommentVisibility.ALL -> null
|
||||
CreatorAdminCommentVisibility.PUBLIC -> comment.isSecret.isFalse
|
||||
CreatorAdminCommentVisibility.SECRET -> comment.isSecret.isTrue
|
||||
}
|
||||
val sorting = when (query.order) {
|
||||
CreatorAdminCommentOrder.LATEST -> arrayOf(comment.createdAt.desc(), comment.id.desc())
|
||||
CreatorAdminCommentOrder.OLDEST -> arrayOf(comment.createdAt.asc(), comment.id.asc())
|
||||
}
|
||||
return queryFactory.selectFrom(comment).join(comment.member).fetchJoin()
|
||||
.where(comment.creatorCommunity.id.eq(postId), comment.isActive.isTrue, comment.parent.isNull, visibility)
|
||||
.orderBy(*sorting).offset(query.page.offset).limit(query.page.size.toLong())
|
||||
.fetch()
|
||||
}
|
||||
|
||||
fun latestReplies(postId: Long, rootIds: List<Long>, ownerId: Long): Map<Long, CreatorCommunityComment> {
|
||||
if (rootIds.isEmpty()) return emptyMap()
|
||||
val reply = creatorCommunityComment
|
||||
val newer = QCreatorCommunityComment("newerCreatorAdminCommunityReply")
|
||||
val newerExists = JPAExpressions.selectOne().from(newer).where(
|
||||
newer.parent.id.eq(reply.parent.id),
|
||||
newer.creatorCommunity.id.eq(postId),
|
||||
newer.member.id.eq(ownerId),
|
||||
newer.isActive.isTrue,
|
||||
newer.createdAt.gt(reply.createdAt).or(newer.createdAt.eq(reply.createdAt).and(newer.id.gt(reply.id)))
|
||||
)
|
||||
return queryFactory.selectFrom(reply).join(reply.member).fetchJoin()
|
||||
.where(
|
||||
reply.creatorCommunity.id.eq(postId),
|
||||
reply.parent.id.`in`(rootIds),
|
||||
reply.member.id.eq(ownerId),
|
||||
reply.isActive.isTrue,
|
||||
newerExists.notExists()
|
||||
).fetch().associateBy { requireNotNull(it.parent?.id) }
|
||||
}
|
||||
|
||||
fun hasActiveCreatorReply(root: CreatorCommunityComment, ownerId: Long): Boolean =
|
||||
queryFactory.selectFrom(creatorCommunityComment)
|
||||
.where(
|
||||
creatorCommunityComment.parent.id.eq(root.id),
|
||||
creatorCommunityComment.creatorCommunity.id.eq(requireNotNull(root.creatorCommunity).id),
|
||||
creatorCommunityComment.member.id.eq(ownerId),
|
||||
creatorCommunityComment.isActive.isTrue
|
||||
).setLockMode(LockModeType.PESSIMISTIC_WRITE).fetchFirst() != null
|
||||
|
||||
fun lockReply(root: CreatorCommunityComment, replyId: Long): CreatorCommunityComment? {
|
||||
val comment = creatorCommunityComment
|
||||
val reply = queryFactory.selectFrom(comment).where(
|
||||
comment.id.eq(replyId),
|
||||
comment.parent.id.eq(root.id),
|
||||
comment.creatorCommunity.id.eq(requireNotNull(root.creatorCommunity).id),
|
||||
comment.isActive.isTrue
|
||||
).setLockMode(LockModeType.PESSIMISTIC_WRITE).fetchFirst() ?: return null
|
||||
entityManager.refresh(reply, LockModeType.PESSIMISTIC_WRITE)
|
||||
return reply
|
||||
}
|
||||
|
||||
fun saveReply(reply: CreatorCommunityComment) {
|
||||
entityManager.persist(reply)
|
||||
}
|
||||
}
|
||||
+170
@@ -0,0 +1,170 @@
|
||||
package kr.co.vividnext.sodalive.v2.creator.admin.commentmanagement.community.application
|
||||
|
||||
import kr.co.vividnext.sodalive.aws.cloudfront.AudioContentCloudFront
|
||||
import kr.co.vividnext.sodalive.explorer.profile.creatorCommunity.CreatorCommunity
|
||||
import kr.co.vividnext.sodalive.explorer.profile.creatorCommunity.comment.CreatorCommunityComment
|
||||
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.community.adapter.out.persistence.CreatorAdminCommunityRepository
|
||||
import kr.co.vividnext.sodalive.v2.creator.admin.commentmanagement.community.dto.CreatorAdminCommunityCommentQuery
|
||||
import kr.co.vividnext.sodalive.v2.creator.admin.commentmanagement.community.dto.CreatorAdminCommunityCommentResponse
|
||||
import kr.co.vividnext.sodalive.v2.creator.admin.commentmanagement.community.dto.CreatorAdminCommunityPostResponse
|
||||
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.domain.CreatorAdminCommentVisibility
|
||||
import kr.co.vividnext.sodalive.v2.creator.admin.commentmanagement.dto.CreatorAdminCommentPageResponse
|
||||
import kr.co.vividnext.sodalive.v2.creator.admin.commentmanagement.dto.CreatorAdminCommentReplyResponse
|
||||
import kr.co.vividnext.sodalive.v2.creator.admin.commentmanagement.dto.CreatorAdminCommentWriterResponse
|
||||
import org.springframework.beans.factory.annotation.Value
|
||||
import org.springframework.stereotype.Service
|
||||
import org.springframework.transaction.annotation.Transactional
|
||||
|
||||
@Service
|
||||
@Transactional(readOnly = true)
|
||||
class CreatorAdminCommunityService(
|
||||
private val repository: CreatorAdminCommunityRepository,
|
||||
private val threadLocks: CommentThreadLockPort,
|
||||
private val audioContentCloudFront: AudioContentCloudFront,
|
||||
@Value("\${cloud.aws.cloud-front.host}") private val imageHost: String
|
||||
) {
|
||||
fun posts(
|
||||
creator: Member,
|
||||
page: CreatorAdminCommentPage,
|
||||
order: CreatorAdminCommentOrder
|
||||
): CreatorAdminCommentPageResponse<CreatorAdminCommunityPostResponse> {
|
||||
val ownerId = requireNotNull(creator.id)
|
||||
val total = repository.countPosts(ownerId)
|
||||
val posts = if (page.offset < total) repository.findPosts(ownerId, page, order) else emptyList()
|
||||
val counts = repository.parentCounts(posts.map { requireNotNull(it.id) })
|
||||
return CreatorAdminCommentPageResponse(
|
||||
items = posts.map { it.toResponse(counts[requireNotNull(it.id)] ?: 0L) },
|
||||
totalCount = total,
|
||||
page = page.page,
|
||||
size = page.size
|
||||
)
|
||||
}
|
||||
|
||||
fun post(creator: Member, postId: Long): CreatorAdminCommunityPostResponse {
|
||||
val post = ownedPost(repository.findPost(postId), creator)
|
||||
return post.toResponse(repository.parentCounts(listOf(postId))[postId] ?: 0L)
|
||||
}
|
||||
|
||||
fun comments(
|
||||
creator: Member,
|
||||
postId: Long,
|
||||
query: CreatorAdminCommunityCommentQuery
|
||||
): CreatorAdminCommentPageResponse<CreatorAdminCommunityCommentResponse> {
|
||||
ownedPost(repository.findPost(postId), creator)
|
||||
val counts = repository.commentCounts(postId)
|
||||
val total = when (query.visibility) {
|
||||
CreatorAdminCommentVisibility.ALL -> counts.all
|
||||
CreatorAdminCommentVisibility.PUBLIC -> counts.public
|
||||
CreatorAdminCommentVisibility.SECRET -> counts.secret
|
||||
}
|
||||
val roots = if (query.page.offset < total) repository.findComments(postId, query) else emptyList()
|
||||
val replies = repository.latestReplies(postId, roots.map { requireNotNull(it.id) }, requireNotNull(creator.id))
|
||||
return CreatorAdminCommentPageResponse(
|
||||
items = roots.map { root ->
|
||||
val rootId = requireNotNull(root.id)
|
||||
val reply = replies[rootId]
|
||||
CreatorAdminCommunityCommentResponse(
|
||||
commentId = rootId,
|
||||
writer = requireNotNull(root.member).toWriter(),
|
||||
content = root.comment,
|
||||
createdAtUtc = requireNotNull(root.createdAt).toUtcIso(),
|
||||
isSecret = root.isSecret,
|
||||
creatorReply = reply?.let {
|
||||
CreatorAdminCommentReplyResponse(
|
||||
replyId = requireNotNull(it.id),
|
||||
writer = requireNotNull(it.member).toWriter(),
|
||||
content = it.comment,
|
||||
createdAtUtc = requireNotNull(it.createdAt).toUtcIso(),
|
||||
isSecret = it.isSecret
|
||||
)
|
||||
}
|
||||
)
|
||||
},
|
||||
totalCount = total,
|
||||
page = query.page.page,
|
||||
size = query.page.size,
|
||||
counts = counts
|
||||
)
|
||||
}
|
||||
|
||||
@Transactional
|
||||
fun deleteComment(creator: Member, postId: Long, commentId: Long) {
|
||||
lockedRoot(creator, postId, commentId).isActive = false
|
||||
}
|
||||
|
||||
@Transactional
|
||||
fun createReply(creator: Member, postId: Long, commentId: Long, content: String) {
|
||||
val root = lockedRoot(creator, postId, commentId)
|
||||
if (!root.isActive || repository.hasActiveCreatorReply(root, requireNotNull(creator.id))) {
|
||||
throw CreatorAdminCommentException(CreatorAdminCommentError.CONFLICT)
|
||||
}
|
||||
repository.saveReply(
|
||||
CreatorCommunityComment(content, isSecret = root.isSecret).apply {
|
||||
member = creator
|
||||
creatorCommunity = root.creatorCommunity
|
||||
parent = root
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
@Transactional
|
||||
fun updateReply(creator: Member, postId: Long, commentId: Long, replyId: Long, content: String) {
|
||||
val root = lockedRoot(creator, postId, commentId)
|
||||
val reply = ownedReply(creator, root, replyId)
|
||||
if (reply.comment != content) reply.comment = content
|
||||
}
|
||||
|
||||
@Transactional
|
||||
fun deleteReply(creator: Member, postId: Long, commentId: Long, replyId: Long) {
|
||||
val root = lockedRoot(creator, postId, commentId)
|
||||
ownedReply(creator, root, replyId).isActive = false
|
||||
}
|
||||
|
||||
private fun ownedPost(post: CreatorCommunity?, creator: Member): CreatorCommunity {
|
||||
if (post == null) throw CreatorAdminCommentException(CreatorAdminCommentError.NOT_FOUND)
|
||||
if (post.member?.id != creator.id) throw CreatorAdminCommentException(CreatorAdminCommentError.ACCESS_DENIED)
|
||||
return post
|
||||
}
|
||||
|
||||
private fun lockedRoot(creator: Member, postId: Long, commentId: Long): CreatorCommunityComment {
|
||||
ownedPost(repository.lockPost(postId), creator)
|
||||
val root = threadLocks.lockCommunityRoot(commentId)
|
||||
?: throw CreatorAdminCommentException(CreatorAdminCommentError.NOT_FOUND)
|
||||
if (root.creatorCommunity?.id != postId || root.parent != null) {
|
||||
throw CreatorAdminCommentException(CreatorAdminCommentError.NOT_FOUND)
|
||||
}
|
||||
return root
|
||||
}
|
||||
|
||||
private fun ownedReply(creator: Member, root: CreatorCommunityComment, replyId: Long): CreatorCommunityComment {
|
||||
if (!root.isActive) throw CreatorAdminCommentException(CreatorAdminCommentError.NOT_FOUND)
|
||||
val reply = repository.lockReply(root, replyId)
|
||||
?: throw CreatorAdminCommentException(CreatorAdminCommentError.NOT_FOUND)
|
||||
if (reply.member?.id != creator.id) throw CreatorAdminCommentException(CreatorAdminCommentError.ACCESS_DENIED)
|
||||
return reply
|
||||
}
|
||||
|
||||
private fun CreatorCommunity.toResponse(commentCount: Long): CreatorAdminCommunityPostResponse =
|
||||
CreatorAdminCommunityPostResponse(
|
||||
postId = requireNotNull(id), content = content, price = price,
|
||||
imageUrl = imagePath.toCdnUrl(imageHost),
|
||||
audioUrl = audioPath?.let { audioContentCloudFront.generateSignedURL(it, 1_800_000L) },
|
||||
isFixed = isFixed, isCommentAvailable = isCommentAvailable,
|
||||
createdAtUtc = requireNotNull(createdAt).toUtcIso(), commentCount = commentCount
|
||||
)
|
||||
|
||||
private fun Member.toWriter(): CreatorAdminCommentWriterResponse = CreatorAdminCommentWriterResponse(
|
||||
memberId = requireNotNull(id),
|
||||
nickname = nickname.removeDeletedNicknamePrefix(),
|
||||
profileImageUrl = profileImage.toCdnUrl(imageHost)
|
||||
)
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package kr.co.vividnext.sodalive.v2.creator.admin.commentmanagement.community.dto
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty
|
||||
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.domain.CreatorAdminCommentVisibility
|
||||
import kr.co.vividnext.sodalive.v2.creator.admin.commentmanagement.dto.CreatorAdminCommentReplyResponse
|
||||
import kr.co.vividnext.sodalive.v2.creator.admin.commentmanagement.dto.CreatorAdminCommentWriterResponse
|
||||
|
||||
data class CreatorAdminCommunityPostResponse(
|
||||
val postId: Long,
|
||||
val content: String,
|
||||
val price: Int,
|
||||
val imageUrl: String?,
|
||||
val audioUrl: String?,
|
||||
@get:JsonProperty("isFixed")
|
||||
val isFixed: Boolean,
|
||||
@get:JsonProperty("isCommentAvailable")
|
||||
val isCommentAvailable: Boolean,
|
||||
val createdAtUtc: String,
|
||||
val commentCount: Long
|
||||
)
|
||||
|
||||
data class CreatorAdminCommunityCommentResponse(
|
||||
val commentId: Long,
|
||||
val writer: CreatorAdminCommentWriterResponse,
|
||||
val content: String,
|
||||
val createdAtUtc: String,
|
||||
@get:JsonProperty("isSecret")
|
||||
val isSecret: Boolean,
|
||||
val creatorReply: CreatorAdminCommentReplyResponse?
|
||||
)
|
||||
|
||||
data class CreatorAdminCommunityCommentQuery(
|
||||
val page: CreatorAdminCommentPage,
|
||||
val order: CreatorAdminCommentOrder,
|
||||
val visibility: CreatorAdminCommentVisibility
|
||||
)
|
||||
+187
@@ -0,0 +1,187 @@
|
||||
package kr.co.vividnext.sodalive.v2.creator.admin.commentmanagement.community
|
||||
|
||||
import kr.co.vividnext.sodalive.explorer.profile.creatorCommunity.comment.CreatorCommunityComment
|
||||
import kr.co.vividnext.sodalive.member.MemberRole
|
||||
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.EnumSource
|
||||
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
|
||||
|
||||
class CreatorAdminCommunityAccessIntegrationTest : CreatorAdminCommunityTestSupport() {
|
||||
@Test
|
||||
@DisplayName("모든 커뮤니티 관리 경로는 미인증 요청을 401로 거부한다")
|
||||
fun shouldRejectUnauthenticatedCommunityOperations() {
|
||||
val post = savePost("private post")
|
||||
val root = saveComment(post, comment = CreatorCommunityComment("secret parent", isSecret = true))
|
||||
val reply = saveReply(root)
|
||||
flushAndClear()
|
||||
|
||||
managementRequests(post, root, reply).forEach { request ->
|
||||
mockMvc.perform(request)
|
||||
.andExpect(status().isUnauthorized)
|
||||
.andExpect(jsonPath("$.success").value(false))
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@EnumSource(MemberRole::class, names = ["USER", "ADMIN"])
|
||||
@DisplayName("USER와 ADMIN은 일반 크리에이터 관리 경로를 403으로 거부한다")
|
||||
fun shouldRejectNonCreatorRolesOnEveryOperation(role: MemberRole) {
|
||||
val post = savePost()
|
||||
val root = saveComment(post)
|
||||
val reply = saveReply(root)
|
||||
val member = saveMember("community-role-${role.name}", role)
|
||||
|
||||
managementRequests(post, root, reply).forEach { request ->
|
||||
perform(request, member)
|
||||
.andExpect(status().isForbidden)
|
||||
.andExpect(jsonPath("$.success").value(false))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("다른 크리에이터의 게시글 상세와 댓글 및 변경은 403이며 비밀 원문을 노출하지 않는다")
|
||||
fun shouldRejectForeignCreatorResourcesWithoutLeakingSecretContent() {
|
||||
val post = savePost("private foreign post")
|
||||
val root = saveComment(post, comment = CreatorCommunityComment("private foreign parent", isSecret = true))
|
||||
val reply = saveReply(root, content = "private foreign reply")
|
||||
val foreign = saveMember("community-foreign-manager", MemberRole.CREATOR)
|
||||
|
||||
managementRequests(post, root, reply).drop(1).forEach { request ->
|
||||
val result = perform(request, foreign)
|
||||
.andExpect(status().isForbidden)
|
||||
.andExpect(jsonPath("$.success").value(false))
|
||||
val body = response(result)
|
||||
assertTrue(body.path("data").isNull)
|
||||
assertFalse(body.toString().contains("private foreign"))
|
||||
}
|
||||
|
||||
val stored = commentsFor(post)
|
||||
assertEquals(listOf("private foreign parent", "private foreign reply"), stored.map { it.comment })
|
||||
assertTrue(stored.all { it.isActive })
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("팬이나 다른 크리에이터 작성 답글은 게시글 소유자도 수정 삭제할 수 없다")
|
||||
fun shouldAllowReplyChangesOnlyForTheAuthenticatedWriter() {
|
||||
val post = savePost()
|
||||
val root = saveComment(post)
|
||||
val fanReply = saveReply(root, fan, "fan reply")
|
||||
val creatorReply = saveReply(root, saveMember("different-reply-writer", MemberRole.CREATOR), "other creator reply")
|
||||
|
||||
listOf(fanReply, creatorReply).forEach { reply ->
|
||||
val path = "${rootPath(root)}/replies/${reply.id}"
|
||||
listOf(
|
||||
put(path).contentType(MediaType.APPLICATION_JSON).content(contentBody("forbidden edit")),
|
||||
delete(path)
|
||||
).forEach { request ->
|
||||
perform(request)
|
||||
.andExpect(status().isForbidden)
|
||||
.andExpect(jsonPath("$.success").value(false))
|
||||
}
|
||||
}
|
||||
|
||||
val stored = commentsFor(post)
|
||||
assertEquals(listOf("fan parent", "fan reply", "other creator reply"), stored.map { it.comment })
|
||||
assertTrue(stored.all { it.isActive })
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("서로 다른 게시글 부모 답글 ID와 중첩 답글을 부모로 삼는 변경은 모두 404로 거부한다")
|
||||
fun shouldRejectMismatchedPostParentAndReplyRelationships() {
|
||||
val post = savePost()
|
||||
val root = saveComment(post)
|
||||
val nestedParent = saveReply(root)
|
||||
val nestedReply = saveReply(nestedParent)
|
||||
val siblingRoot = saveComment(post, comment = CreatorCommunityComment("sibling parent"))
|
||||
val siblingReply = saveReply(siblingRoot)
|
||||
val otherPost = savePost("other owned post")
|
||||
val otherRoot = saveComment(otherPost)
|
||||
val otherReply = saveReply(otherRoot)
|
||||
val mixedRoot = "${commentsPath(post)}/${otherRoot.id}"
|
||||
val replies = "${rootPath(root)}/replies"
|
||||
val nestedReplies = "${rootPath(nestedParent)}/replies"
|
||||
val requests = listOf(
|
||||
delete(mixedRoot),
|
||||
post("$mixedRoot/replies").contentType(MediaType.APPLICATION_JSON).content(contentBody("mixed post")),
|
||||
put("$mixedRoot/replies/${otherReply.id}").contentType(MediaType.APPLICATION_JSON).content(contentBody("mixed")),
|
||||
delete("$mixedRoot/replies/${otherReply.id}"),
|
||||
put("$replies/${otherReply.id}").contentType(MediaType.APPLICATION_JSON).content(contentBody("mixed parent")),
|
||||
delete("$replies/${otherReply.id}"),
|
||||
put("$replies/${siblingReply.id}").contentType(MediaType.APPLICATION_JSON).content(contentBody("sibling reply")),
|
||||
delete("$replies/${siblingReply.id}"),
|
||||
put("$replies/${nestedReply.id}").contentType(MediaType.APPLICATION_JSON).content(contentBody("nested reply")),
|
||||
delete("$replies/${nestedReply.id}"),
|
||||
put("$replies/${root.id}").contentType(MediaType.APPLICATION_JSON).content(contentBody("parent as reply")),
|
||||
delete("$replies/${root.id}"),
|
||||
delete(rootPath(nestedParent)),
|
||||
post(nestedReplies).contentType(MediaType.APPLICATION_JSON).content(contentBody("nested parent"))
|
||||
)
|
||||
|
||||
requests.forEach { request ->
|
||||
perform(request)
|
||||
.andExpect(status().isNotFound)
|
||||
.andExpect(jsonPath("$.success").value(false))
|
||||
}
|
||||
|
||||
val stored = commentsFor(post)
|
||||
assertEquals(
|
||||
listOf(root.id, nestedParent.id, nestedReply.id, siblingRoot.id, siblingReply.id),
|
||||
stored.map { it.id }
|
||||
)
|
||||
assertEquals(
|
||||
listOf("fan parent", "creator reply", "creator reply", "sibling parent", "creator reply"),
|
||||
stored.map { it.comment }
|
||||
)
|
||||
assertTrue(stored.all { it.isActive })
|
||||
val otherStored = commentsFor(otherPost)
|
||||
assertEquals(listOf(otherRoot.id, otherReply.id), otherStored.map { it.id })
|
||||
assertEquals(listOf("fan parent", "creator reply"), otherStored.map { it.comment })
|
||||
assertTrue(otherStored.all { it.isActive })
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("비활성 게시글 상세 댓글 및 변경은 404이며 없는 게시글도 404다")
|
||||
fun shouldRejectInactiveAndMissingPosts() {
|
||||
val post = savePost { isActive = false }
|
||||
val root = saveComment(post)
|
||||
val reply = saveReply(root)
|
||||
|
||||
managementRequests(post, root, reply).drop(1).forEach { request ->
|
||||
perform(request)
|
||||
.andExpect(status().isNotFound)
|
||||
.andExpect(jsonPath("$.success").value(false))
|
||||
}
|
||||
listOf("$POSTS/${Long.MAX_VALUE}", "$POSTS/${Long.MAX_VALUE}/comments").forEach { path ->
|
||||
perform(get(path))
|
||||
.andExpect(status().isNotFound)
|
||||
.andExpect(jsonPath("$.success").value(false))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("삭제된 부모에 답글 등록은 409이며 기존 자식을 포함한 row를 바꾸지 않는다")
|
||||
fun shouldRejectReplyCreationForDeletedParent() {
|
||||
val post = savePost()
|
||||
val root = saveComment(post, comment = CreatorCommunityComment("deleted", isActive = false))
|
||||
val existing = saveReply(root, fan)
|
||||
|
||||
perform(post("${rootPath(root)}/replies").contentType(MediaType.APPLICATION_JSON).content(contentBody("rejected")))
|
||||
.andExpect(status().isConflict)
|
||||
.andExpect(jsonPath("$.success").value(false))
|
||||
|
||||
val stored = commentsFor(post)
|
||||
assertEquals(listOf(root.id, existing.id), stored.map { it.id })
|
||||
assertEquals(listOf(false, true), stored.map { it.isActive })
|
||||
}
|
||||
}
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
package kr.co.vividnext.sodalive.v2.creator.admin.commentmanagement.community
|
||||
|
||||
import kr.co.vividnext.sodalive.explorer.profile.creatorCommunity.comment.CreatorCommunityComment
|
||||
import kr.co.vividnext.sodalive.member.MemberRole
|
||||
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.get
|
||||
|
||||
class CreatorAdminCommunityCommentQueryIntegrationTest : CreatorAdminCommunityTestSupport() {
|
||||
@ParameterizedTest
|
||||
@CsvSource("all,15", "public,12", "secret,3")
|
||||
@DisplayName("필터 개수는 선택 게시글의 소유자 부모를 포함한 전체 범위이며 페이지와 필터로 축소되지 않는다")
|
||||
fun shouldFilterSelectedPostParentsWithFullScopeCounts(visibility: String, total: Int) {
|
||||
val post = savePost { isCommentAvailable = false }
|
||||
val publicRoots = (1..11).map { saveComment(post, comment = CreatorCommunityComment("public $it")) } +
|
||||
saveComment(post, owner, CreatorCommunityComment("owner public parent"))
|
||||
val secretRoots = listOf(
|
||||
saveComment(post, comment = CreatorCommunityComment("secret one", isSecret = true)),
|
||||
saveComment(post, comment = CreatorCommunityComment("secret two", isSecret = true)),
|
||||
saveComment(post, owner, CreatorCommunityComment("owner secret parent", isSecret = true))
|
||||
)
|
||||
entityManager.persist(
|
||||
BlockMember().apply {
|
||||
member = owner
|
||||
blockedMember = fan
|
||||
}
|
||||
)
|
||||
val inactive = saveComment(post, comment = CreatorCommunityComment("inactive", isActive = false))
|
||||
saveReply(publicRoots.first())
|
||||
saveReply(publicRoots.first(), fan)
|
||||
saveReply(inactive)
|
||||
saveComment(savePost("another owned post"))
|
||||
saveComment(savePost("foreign post", saveMember("query-foreign-owner", MemberRole.CREATOR)))
|
||||
val expected = when (visibility) {
|
||||
"all" -> publicRoots + secretRoots
|
||||
"public" -> publicRoots
|
||||
"secret" -> secretRoots
|
||||
else -> error("Unexpected test visibility: $visibility")
|
||||
}.map { requireNotNull(it.id) }.sortedDescending()
|
||||
|
||||
listOf(0, 1, 2).forEach { page ->
|
||||
val result = data(
|
||||
perform(get(commentsPath(post)).param("visibility", visibility).param("page", page.toString()))
|
||||
)
|
||||
|
||||
assertEquals(total, result.path("totalCount").asInt())
|
||||
assertEquals(15, result.path("counts").path("all").asInt())
|
||||
assertEquals(12, result.path("counts").path("public").asInt())
|
||||
assertEquals(3, result.path("counts").path("secret").asInt())
|
||||
assertEquals(page, result.path("page").asInt())
|
||||
assertEquals(10, result.path("size").asInt())
|
||||
assertEquals((page + 1) * 10 < total, result.path("hasNext").asBoolean())
|
||||
assertEquals(expected.drop(page * 10).take(10), result.path("items").map { it.path("commentId").asLong() })
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = ["latest", "oldest"])
|
||||
@DisplayName("부모 댓글은 작성 시각과 ID를 같은 방향으로 정렬하여 페이지 경계를 유지한다")
|
||||
fun shouldPageCommentIdsByCreationTimeAndId(order: String) {
|
||||
val post = savePost()
|
||||
val roots = (1..11).map { saveComment(post, comment = CreatorCommunityComment("parent $it")) }
|
||||
roots.first().createdAt = CREATED_AT.plusDays(1)
|
||||
roots.last().createdAt = CREATED_AT.minusDays(1)
|
||||
val ascending = listOf(roots.last()) + roots.subList(1, 10) + roots.first()
|
||||
val expected = (if (order == "oldest") ascending else ascending.reversed()).map { it.id }
|
||||
|
||||
(0..2).forEach { page ->
|
||||
val result = data(perform(get(commentsPath(post)).param("order", order).param("page", page.toString())))
|
||||
|
||||
assertEquals(expected.drop(page * 10).take(10), result.path("items").map { it.path("commentId").asLong() })
|
||||
assertEquals(11, result.path("totalCount").asInt())
|
||||
assertEquals(page == 0, result.path("hasNext").asBoolean())
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("최신 답글은 활성 소유 크리에이터의 직접 답글 중 작성 시각과 ID로 선택하고 작성자와 비밀 여부를 반환한다")
|
||||
fun shouldSelectLatestActiveDirectOwnerReplyWithWriterAndVisibility() {
|
||||
val post = savePost()
|
||||
val root = saveComment(post, comment = CreatorCommunityComment("비밀 원문 日本語\n🙂", isSecret = true))
|
||||
val earlier = saveReply(root, content = "earlier").apply { createdAt = CREATED_AT.minusDays(1) }
|
||||
saveReply(root, content = "same time lower id")
|
||||
val latest = saveReply(root, content = "latest owner reply")
|
||||
saveReply(root, fan, "newer fan reply").createdAt = CREATED_AT.plusDays(3)
|
||||
saveReply(root, saveMember("other-reply-creator", MemberRole.CREATOR)).createdAt = CREATED_AT.plusDays(4)
|
||||
saveReply(root, content = "inactive owner reply").apply {
|
||||
isActive = false
|
||||
createdAt = CREATED_AT.plusDays(5)
|
||||
}
|
||||
saveReply(latest, content = "nested owner reply").createdAt = CREATED_AT.plusDays(6)
|
||||
entityManager.flush()
|
||||
entityManager.createQuery("update CreatorCommunityComment c set c.updatedAt = :time where c.id = :id")
|
||||
.setParameter("time", CREATED_AT.plusDays(20))
|
||||
.setParameter("id", earlier.id)
|
||||
.executeUpdate()
|
||||
|
||||
val result = comments(post)
|
||||
val item = result.path("items").single()
|
||||
val reply = item.path("creatorReply")
|
||||
|
||||
assertEquals(1, result.path("totalCount").asInt())
|
||||
assertEquals(root.id, item.path("commentId").asLong())
|
||||
assertEquals("비밀 원문 日本語\n🙂", item.path("content").asText())
|
||||
assertTrue(item.path("isSecret").asBoolean())
|
||||
assertEquals(fan.id, item.path("writer").path("memberId").asLong())
|
||||
assertEquals(fan.nickname, item.path("writer").path("nickname").asText())
|
||||
assertTrue(item.path("writer").has("profileImageUrl"))
|
||||
assertEquals("2026-11-20T23:59:59Z", item.path("createdAtUtc").asText())
|
||||
assertEquals(latest.id, reply.path("replyId").asLong())
|
||||
assertEquals("latest owner reply", reply.path("content").asText())
|
||||
assertEquals(owner.id, reply.path("writer").path("memberId").asLong())
|
||||
assertEquals(owner.nickname, reply.path("writer").path("nickname").asText())
|
||||
assertEquals("https://test.cloudfront.net/profile/manager.png", reply.path("writer").path("profileImageUrl").asText())
|
||||
assertTrue(reply.path("isSecret").asBoolean())
|
||||
assertEquals("2026-11-20T23:59:59Z", reply.path("createdAtUtc").asText())
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("다른 게시글 댓글을 섞지 않으며 활성 크리에이터 답글이 없으면 null을 반환한다")
|
||||
fun shouldKeepSelectedPostScopeAndReturnNullWithoutCreatorReply() {
|
||||
val first = savePost("first")
|
||||
val second = savePost("second")
|
||||
val firstRoot = saveComment(first)
|
||||
saveReply(firstRoot)
|
||||
val secondRoot = saveComment(second, owner, CreatorCommunityComment("owner parent in selected post"))
|
||||
saveReply(secondRoot, fan)
|
||||
saveReply(secondRoot).isActive = false
|
||||
|
||||
val result = comments(second)
|
||||
val item = result.path("items").single()
|
||||
|
||||
assertEquals(secondRoot.id, item.path("commentId").asLong())
|
||||
assertEquals(1, result.path("totalCount").asInt())
|
||||
assertEquals(1, result.path("counts").path("all").asInt())
|
||||
assertEquals(1, result.path("counts").path("public").asInt())
|
||||
assertEquals(0, result.path("counts").path("secret").asInt())
|
||||
assertFalse(result.path("hasNext").asBoolean())
|
||||
assertTrue(item.path("creatorReply").isNull)
|
||||
}
|
||||
}
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
package kr.co.vividnext.sodalive.v2.creator.admin.commentmanagement.community
|
||||
|
||||
import kr.co.vividnext.sodalive.explorer.profile.creatorCommunity.comment.CreatorCommunityComment
|
||||
import org.junit.jupiter.api.Assertions.assertEquals
|
||||
import org.junit.jupiter.api.Assertions.assertTrue
|
||||
import org.junit.jupiter.api.DisplayName
|
||||
import org.junit.jupiter.params.ParameterizedTest
|
||||
import org.junit.jupiter.params.provider.CsvSource
|
||||
import org.junit.jupiter.params.provider.ValueSource
|
||||
import org.springframework.http.MediaType
|
||||
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.nio.charset.StandardCharsets
|
||||
|
||||
class CreatorAdminCommunityInputIntegrationTest : CreatorAdminCommunityTestSupport() {
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = [false, true])
|
||||
@DisplayName("답글 등록 수정은 누락 잘못된 JSON 타입 임의 필드 공백과 UTF-8 초과 입력을 400으로 거부한다")
|
||||
fun shouldRejectInvalidReplyBodiesWithoutPersistingChanges(update: Boolean) {
|
||||
val post = savePost()
|
||||
val root = saveComment(post, comment = CreatorCommunityComment("parent", isSecret = true))
|
||||
val reply = if (update) saveReply(root, content = "original") else null
|
||||
val path = "${rootPath(root)}/replies" + if (update) "/${requireNotNull(reply).id}" else ""
|
||||
val invalidContents = listOf("", " \t\n ", "a".repeat(65_536), "가".repeat(21_846), "🙂".repeat(16_384))
|
||||
val invalidBodies = listOf(
|
||||
"{}",
|
||||
"null",
|
||||
"[]",
|
||||
"{\"content\":null}",
|
||||
"{\"content\":42}",
|
||||
"{\"content\":true}",
|
||||
"{\"content\":[]}",
|
||||
"{\"content\":{}}",
|
||||
"{\"content\":",
|
||||
"{\"content\":\"body\",\"unknown\":true}",
|
||||
"{\"content\":\"body\",\"authorId\":${fan.id}}",
|
||||
"{\"content\":\"body\",\"isSecret\":false}",
|
||||
"{\"content\":\"body\",\"isActive\":false}"
|
||||
) + invalidContents.map(::contentBody)
|
||||
|
||||
invalidBodies.forEach { body ->
|
||||
val request = if (update) put(path) else post(path)
|
||||
perform(request.contentType(MediaType.APPLICATION_JSON).content(body))
|
||||
.andExpect(status().isBadRequest)
|
||||
.andExpect(jsonPath("$.success").value(false))
|
||||
}
|
||||
|
||||
val stored = commentsFor(post)
|
||||
assertEquals(if (update) listOf(root.id, requireNotNull(reply).id) else listOf(root.id), stored.map { it.id })
|
||||
assertEquals(if (update) listOf("parent", "original") else listOf("parent"), stored.map { it.comment })
|
||||
assertTrue(stored.all { it.isActive && it.isSecret })
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = [false, true])
|
||||
@DisplayName("답글 등록 수정은 trim 후 UTF-8 정확히 65535 byte인 다중바이트 본문을 잘라내지 않고 저장한다")
|
||||
fun shouldStoreExactUtf8TextLimitWithoutTruncation(update: Boolean) {
|
||||
val post = savePost()
|
||||
val root = saveComment(post)
|
||||
val reply = if (update) saveReply(root, content = "before") else null
|
||||
val path = "${rootPath(root)}/replies" + if (update) "/${requireNotNull(reply).id}" else ""
|
||||
val content = "🙂".repeat(16_383) + "한"
|
||||
val request = if (update) put(path) else post(path)
|
||||
|
||||
expectMutation(perform(request.contentType(MediaType.APPLICATION_JSON).content(contentBody(" \n$content\t "))))
|
||||
|
||||
val stored = commentsFor(post).single { it.parent?.id == root.id }
|
||||
assertEquals(content, stored.comment)
|
||||
assertEquals(65_535, stored.comment.toByteArray(StandardCharsets.UTF_8).size)
|
||||
assertEquals(owner.id, stored.member?.id)
|
||||
assertEquals(root.id, stored.parent?.id)
|
||||
assertEquals(content, comments(post).path("items").single().path("creatorReply").path("content").asText())
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource("page,-1", "size,0", "size,101", "order,invalid")
|
||||
@DisplayName("게시글과 댓글 목록은 잘못된 페이지 크기 정렬을 400으로 거부한다")
|
||||
fun shouldRejectInvalidListParameters(parameter: String, value: String) {
|
||||
val post = savePost()
|
||||
saveComment(post)
|
||||
|
||||
listOf(POSTS, commentsPath(post)).forEach { path ->
|
||||
perform(get(path).param(parameter, value))
|
||||
.andExpect(status().isBadRequest)
|
||||
.andExpect(jsonPath("$.success").value(false))
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = ["friends", "PUBLIC"])
|
||||
@DisplayName("댓글 목록은 계약에 없는 공개 범위를 400으로 거부한다")
|
||||
fun shouldRejectInvalidCommentVisibility(visibility: String) {
|
||||
val post = savePost()
|
||||
saveComment(post)
|
||||
|
||||
perform(get(commentsPath(post)).param("visibility", visibility))
|
||||
.andExpect(status().isBadRequest)
|
||||
.andExpect(jsonPath("$.success").value(false))
|
||||
}
|
||||
}
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
package kr.co.vividnext.sodalive.v2.creator.admin.commentmanagement.community
|
||||
|
||||
import kr.co.vividnext.sodalive.explorer.profile.creatorCommunity.comment.CreatorCommunityComment
|
||||
import kr.co.vividnext.sodalive.member.MemberRole
|
||||
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.ValueSource
|
||||
import org.mockito.Mockito
|
||||
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
|
||||
|
||||
class CreatorAdminCommunityIntegrationTest : CreatorAdminCommunityTestSupport() {
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = [false, true])
|
||||
@DisplayName("목록과 상세는 소유 활성 유료 성인 게시글 원문과 첨부 및 모든 활성 부모 수를 반환한다")
|
||||
fun shouldReturnFullOwnedPostWithAttachmentsAndAllActiveParentCount(detail: Boolean) {
|
||||
val content = "한글 日本語 🙂\n" + "원문 전체 보존 ".repeat(30)
|
||||
val post = savePost(content) {
|
||||
price = 300
|
||||
isAdult = true
|
||||
isFixed = true
|
||||
imagePath = "community/full.png"
|
||||
audioPath = "community/full.m4a"
|
||||
}
|
||||
val root = saveComment(post)
|
||||
saveComment(post, owner, CreatorCommunityComment("owner parent"))
|
||||
saveComment(post, comment = CreatorCommunityComment("secret parent", isSecret = true))
|
||||
saveComment(post, comment = CreatorCommunityComment("deleted parent", isActive = false))
|
||||
saveReply(root)
|
||||
saveReply(root, fan, "fan reply")
|
||||
savePost("inactive") { isActive = false }
|
||||
savePost("foreign", saveMember("foreign-community-creator", MemberRole.CREATOR))
|
||||
Mockito.`when`(audioContentCloudFront.generateSignedURL("community/full.m4a", 1_800_000L))
|
||||
.thenReturn("https://signed.example.com/full.m4a?Expires=1")
|
||||
|
||||
val result = data(perform(get(if (detail) "$POSTS/${post.id}" else POSTS)))
|
||||
val item = if (detail) result else result.path("items").single()
|
||||
|
||||
assertEquals(post.id, item.path("postId").asLong())
|
||||
assertEquals(content, item.path("content").asText())
|
||||
assertEquals(300, item.path("price").asInt())
|
||||
assertEquals("https://test.cloudfront.net/community/full.png", item.path("imageUrl").asText())
|
||||
assertEquals("https://signed.example.com/full.m4a?Expires=1", item.path("audioUrl").asText())
|
||||
assertTrue(item.path("isFixed").asBoolean())
|
||||
assertTrue(item.path("isCommentAvailable").asBoolean())
|
||||
assertEquals("2026-11-20T23:59:59Z", item.path("createdAtUtc").asText())
|
||||
assertEquals(3, item.path("commentCount").asInt())
|
||||
if (!detail) assertEquals(1, result.path("totalCount").asInt())
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = [false, true])
|
||||
@DisplayName("첨부 없는 게시글은 목록과 상세에서 null 첨부와 댓글 허용 여부 및 0개수를 반환한다")
|
||||
fun shouldReturnExplicitNullAttachmentsAndEmptyParentCount(detail: Boolean) {
|
||||
val post = savePost { isCommentAvailable = false }
|
||||
|
||||
val result = data(perform(get(if (detail) "$POSTS/${post.id}" else POSTS)))
|
||||
val item = if (detail) result else result.path("items").single()
|
||||
|
||||
assertEquals(post.id, item.path("postId").asLong())
|
||||
assertTrue(item.path("imageUrl").isNull)
|
||||
assertTrue(item.path("audioUrl").isNull)
|
||||
assertEquals(0, item.path("price").asInt())
|
||||
assertFalse(item.path("isFixed").asBoolean())
|
||||
assertFalse(item.path("isCommentAvailable").asBoolean())
|
||||
assertEquals(0, item.path("commentCount").asInt())
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = ["latest", "oldest"])
|
||||
@DisplayName("관리 게시글 정렬은 고정 여부와 고정 시각보다 작성 시각을 우선한다")
|
||||
fun shouldSortPostsByCreationTimeWithoutPinnedPriority(order: String) {
|
||||
val newest = savePost("new normal").apply { createdAt = CREATED_AT.plusDays(1) }
|
||||
val oldest = savePost("old fixed") {
|
||||
isFixed = true
|
||||
fixedAt = CREATED_AT.plusDays(10)
|
||||
}.apply { createdAt = CREATED_AT.minusDays(1) }
|
||||
val middle = savePost("middle normal")
|
||||
val ascending = listOf(oldest.id, middle.id, newest.id)
|
||||
|
||||
val result = data(perform(get(POSTS).param("order", order)))
|
||||
|
||||
assertEquals(
|
||||
if (order == "oldest") ascending else ascending.reversed(),
|
||||
result.path("items").map { it.path("postId").asLong() }
|
||||
)
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = ["latest", "oldest"])
|
||||
@DisplayName("동시간 게시글 100개는 기본 10개씩 열 페이지에 중복 누락 없이 정렬되고 초과 페이지는 비어 있다")
|
||||
fun shouldPageStablePostIdsAcrossTenPagesAndKeepCountsBeyondEnd(order: String) {
|
||||
val ids = (1..100).map { savePost("post $it").id }
|
||||
val expected = if (order == "oldest") ids else ids.reversed()
|
||||
|
||||
(0..10).forEach { page ->
|
||||
val result = data(perform(get(POSTS).param("page", page.toString()).param("order", order)))
|
||||
|
||||
assertEquals(expected.drop(page * 10).take(10), result.path("items").map { it.path("postId").asLong() })
|
||||
assertEquals(100, result.path("totalCount").asInt())
|
||||
assertEquals(page, result.path("page").asInt())
|
||||
assertEquals(10, result.path("size").asInt())
|
||||
assertEquals(page < 9, result.path("hasNext").asBoolean())
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("소유 게시글이 없으면 기본 페이지와 빈 목록 및 정확한 0개수를 반환한다")
|
||||
fun shouldReturnEmptyOwnedPostPage() {
|
||||
val result = data(perform(get(POSTS)))
|
||||
|
||||
assertTrue(result.path("items").isArray)
|
||||
assertEquals(0, result.path("items").size())
|
||||
assertEquals(0, result.path("totalCount").asInt())
|
||||
assertEquals(0, result.path("page").asInt())
|
||||
assertEquals(10, result.path("size").asInt())
|
||||
assertFalse(result.path("hasNext").asBoolean())
|
||||
}
|
||||
}
|
||||
+166
@@ -0,0 +1,166 @@
|
||||
package kr.co.vividnext.sodalive.v2.creator.admin.commentmanagement.community
|
||||
|
||||
import kr.co.vividnext.sodalive.explorer.profile.creatorCommunity.comment.CreatorCommunityComment
|
||||
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
|
||||
|
||||
class CreatorAdminCommunityReplyIntegrationTest : CreatorAdminCommunityTestSupport() {
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = [false, true])
|
||||
@DisplayName("답글 등록은 인증 소유자를 작성자로 저장하고 부모 공개 범위를 상속하며 Unicode와 줄바꿈을 보존한다")
|
||||
fun shouldCreateTrimmedUnicodeReplyAsOwnerWithInheritedVisibility(secret: Boolean) {
|
||||
val post = savePost()
|
||||
val root = saveComment(post, comment = CreatorCommunityComment("parent", isSecret = secret))
|
||||
val content = "한글 日本語 🙂\n둘째 줄"
|
||||
|
||||
expectMutation(
|
||||
perform(
|
||||
post("${rootPath(root)}/replies").contentType(MediaType.APPLICATION_JSON)
|
||||
.content(contentBody(" \t$content\n "))
|
||||
)
|
||||
)
|
||||
|
||||
val reply = commentsFor(post).single { it.parent?.id == root.id }
|
||||
assertEquals(owner.id, reply.member?.id)
|
||||
assertEquals(post.id, reply.creatorCommunity?.id)
|
||||
assertEquals(content, reply.comment)
|
||||
assertEquals(secret, reply.isSecret)
|
||||
assertTrue(reply.isActive)
|
||||
val result = comments(post)
|
||||
assertEquals(1, result.path("totalCount").asInt())
|
||||
val visible = result.path("items").single().path("creatorReply")
|
||||
assertEquals(reply.id, visible.path("replyId").asLong())
|
||||
assertEquals(owner.id, visible.path("writer").path("memberId").asLong())
|
||||
assertTrue(visible.has("isSecret"))
|
||||
assertEquals(secret, visible.path("isSecret").asBoolean())
|
||||
assertEquals(content, visible.path("content").asText())
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("답글 수정은 공백을 정규화하고 동일 정규화 본문 재수정은 저장 시각을 바꾸지 않는다")
|
||||
fun shouldUpdateOwnReplyAndKeepIdenticalNormalizedEditAsNoOp() {
|
||||
val post = savePost()
|
||||
val root = saveComment(post, comment = CreatorCommunityComment("secret parent", isSecret = true))
|
||||
val reply = saveReply(root, content = "before")
|
||||
val path = "${rootPath(root)}/replies/${reply.id}"
|
||||
val content = "수정 日本語 🙂\n줄바꿈"
|
||||
|
||||
expectMutation(perform(put(path).contentType(MediaType.APPLICATION_JSON).content(contentBody(" $content "))))
|
||||
|
||||
val updated = reloadComment(reply)
|
||||
assertEquals(content, updated.comment)
|
||||
assertEquals(root.id, updated.parent?.id)
|
||||
assertEquals(owner.id, updated.member?.id)
|
||||
assertTrue(updated.isSecret)
|
||||
assertEquals(content, comments(post).path("items").single().path("creatorReply").path("content").asText())
|
||||
val updatedAt = requireNotNull(updated.updatedAt)
|
||||
|
||||
expectMutation(perform(put(path).contentType(MediaType.APPLICATION_JSON).content(contentBody("\n$content\t"))))
|
||||
|
||||
val unchanged = reloadComment(reply)
|
||||
assertEquals(updatedAt, unchanged.updatedAt)
|
||||
assertEquals(content, unchanged.comment)
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("활성 크리에이터 직접 답글이 하나라도 있으면 중복 등록을 409로 거부한다")
|
||||
fun shouldRejectDuplicateReplyWithoutChangingExistingRows() {
|
||||
val post = savePost()
|
||||
val root = saveComment(post)
|
||||
val first = saveReply(root, content = "first")
|
||||
val second = saveReply(root, content = "second")
|
||||
val fanReply = saveReply(root, fan)
|
||||
|
||||
perform(post("${rootPath(root)}/replies").contentType(MediaType.APPLICATION_JSON).content(contentBody("duplicate")))
|
||||
.andExpect(status().isConflict)
|
||||
.andExpect(jsonPath("$.success").value(false))
|
||||
|
||||
val stored = commentsFor(post)
|
||||
assertEquals(listOf(root.id, first.id, second.id, fanReply.id), stored.map { it.id })
|
||||
assertEquals(listOf("fan parent", "first", "second", "creator reply"), stored.map { it.comment })
|
||||
assertTrue(stored.all { it.isActive })
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("최신 답글 삭제는 이전 활성 답글을 드러내고 모두 삭제된 뒤에만 새 답글 등록을 허용한다")
|
||||
fun shouldRevealPriorReplyAndAllowRecreationOnlyAfterAllOwnerRepliesAreDeleted() {
|
||||
val post = savePost()
|
||||
val root = saveComment(post)
|
||||
val prior = saveReply(root, content = "prior").apply { createdAt = CREATED_AT.minusDays(1) }
|
||||
val latest = saveReply(root, content = "latest")
|
||||
val fanReply = saveReply(root, fan, "fan survives")
|
||||
val replies = "${rootPath(root)}/replies"
|
||||
|
||||
expectMutation(
|
||||
perform(put("$replies/${prior.id}").contentType(MediaType.APPLICATION_JSON).content(contentBody("edited prior")))
|
||||
)
|
||||
assertEquals(latest.id, comments(post).path("items").single().path("creatorReply").path("replyId").asLong())
|
||||
|
||||
expectMutation(perform(delete("$replies/${latest.id}")))
|
||||
val revealed = comments(post).path("items").single().path("creatorReply")
|
||||
assertEquals(prior.id, revealed.path("replyId").asLong())
|
||||
assertEquals("edited prior", revealed.path("content").asText())
|
||||
assertFalse(reloadComment(latest).isActive)
|
||||
assertTrue(reloadComment(root).isActive)
|
||||
assertTrue(reloadComment(fanReply).isActive)
|
||||
|
||||
perform(post(replies).contentType(MediaType.APPLICATION_JSON).content(contentBody("still duplicate")))
|
||||
.andExpect(status().isConflict)
|
||||
.andExpect(jsonPath("$.success").value(false))
|
||||
|
||||
expectMutation(perform(delete("$replies/${prior.id}")))
|
||||
assertTrue(comments(post).path("items").single().path("creatorReply").isNull)
|
||||
|
||||
expectMutation(perform(post(replies).contentType(MediaType.APPLICATION_JSON).content(contentBody("recreated"))))
|
||||
val stored = commentsFor(post)
|
||||
assertEquals(5, stored.size)
|
||||
assertEquals(
|
||||
setOf(root.id, fanReply.id),
|
||||
stored.filter { it.isActive && it.comment != "recreated" }.map { it.id }.toSet()
|
||||
)
|
||||
assertEquals(setOf(prior.id, latest.id), stored.filter { !it.isActive }.map { it.id }.toSet())
|
||||
val recreated = stored.single { it.comment == "recreated" }
|
||||
assertNotEquals(latest.id, recreated.id)
|
||||
assertEquals(root.id, recreated.parent?.id)
|
||||
assertEquals(owner.id, recreated.member?.id)
|
||||
assertTrue(recreated.isActive)
|
||||
assertEquals(recreated.id, comments(post).path("items").single().path("creatorReply").path("replyId").asLong())
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("부모 삭제는 답글 row를 보존하면서 관리 댓글 목록과 게시글 목록 상세의 부모 수에서 제외한다")
|
||||
fun shouldSoftDeleteParentAndRemoveItFromAllManagementCounts() {
|
||||
val post = savePost()
|
||||
val deleted = saveComment(post, comment = CreatorCommunityComment("secret deleted", isSecret = true))
|
||||
val ownerReply = saveReply(deleted)
|
||||
val fanReply = saveReply(deleted, fan)
|
||||
val survivor = saveComment(post, owner, CreatorCommunityComment("owner parent survives"))
|
||||
|
||||
expectMutation(perform(delete(rootPath(deleted))))
|
||||
|
||||
assertFalse(reloadComment(deleted).isActive)
|
||||
assertTrue(reloadComment(ownerReply).isActive)
|
||||
assertTrue(reloadComment(fanReply).isActive)
|
||||
val result = comments(post)
|
||||
assertEquals(listOf(survivor.id), result.path("items").map { it.path("commentId").asLong() })
|
||||
assertEquals(1, result.path("totalCount").asInt())
|
||||
assertEquals(1, result.path("counts").path("all").asInt())
|
||||
assertEquals(1, result.path("counts").path("public").asInt())
|
||||
assertEquals(0, result.path("counts").path("secret").asInt())
|
||||
assertEquals(1, data(perform(get("$POSTS/${post.id}"))).path("commentCount").asInt())
|
||||
assertEquals(1, data(perform(get(POSTS))).path("items").single().path("commentCount").asInt())
|
||||
}
|
||||
}
|
||||
+164
@@ -0,0 +1,164 @@
|
||||
package kr.co.vividnext.sodalive.v2.creator.admin.commentmanagement.community
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode
|
||||
import com.fasterxml.jackson.databind.ObjectMapper
|
||||
import kr.co.vividnext.sodalive.aws.cloudfront.AudioContentCloudFront
|
||||
import kr.co.vividnext.sodalive.explorer.profile.creatorCommunity.CreatorCommunity
|
||||
import kr.co.vividnext.sodalive.explorer.profile.creatorCommunity.comment.CreatorCommunityComment
|
||||
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.junit.jupiter.api.Assertions.assertTrue
|
||||
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.boot.test.mock.mockito.MockBean
|
||||
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.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 org.springframework.transaction.annotation.Transactional
|
||||
import java.nio.charset.StandardCharsets
|
||||
import java.time.LocalDateTime
|
||||
import javax.persistence.EntityManager
|
||||
|
||||
internal const val POSTS = "/api/v2/creator-admin/comment-management/community/posts"
|
||||
internal val CREATED_AT: LocalDateTime = LocalDateTime.of(2026, 11, 20, 23, 59, 59)
|
||||
|
||||
@SpringBootTest(properties = ["cloud.aws.cloud-front.host=https://test.cloudfront.net"])
|
||||
@AutoConfigureMockMvc
|
||||
@Transactional
|
||||
@ContextConfiguration(initializers = [EmbeddedRedisInitializer::class])
|
||||
abstract class CreatorAdminCommunityTestSupport {
|
||||
@Autowired
|
||||
protected lateinit var mockMvc: MockMvc
|
||||
|
||||
@Autowired
|
||||
protected lateinit var entityManager: EntityManager
|
||||
|
||||
@Autowired
|
||||
protected lateinit var objectMapper: ObjectMapper
|
||||
|
||||
@MockBean
|
||||
protected lateinit var audioContentCloudFront: AudioContentCloudFront
|
||||
|
||||
protected lateinit var owner: Member
|
||||
protected lateinit var fan: Member
|
||||
|
||||
@BeforeEach
|
||||
fun setUpCommunityMembers() {
|
||||
owner = saveMember("community-manager", MemberRole.CREATOR).apply { profileImage = "profile/manager.png" }
|
||||
fan = saveMember("community-fan", MemberRole.USER)
|
||||
}
|
||||
|
||||
protected fun saveMember(nickname: String, role: MemberRole): Member = Member(
|
||||
email = "$nickname@example.com",
|
||||
password = "password",
|
||||
nickname = nickname,
|
||||
role = role
|
||||
).apply(entityManager::persist)
|
||||
|
||||
protected fun savePost(
|
||||
content: String = "community post",
|
||||
writer: Member = owner,
|
||||
configure: CreatorCommunity.() -> Unit = {}
|
||||
): CreatorCommunity = CreatorCommunity(content, price = 0, isCommentAvailable = true, isAdult = false).apply {
|
||||
member = writer
|
||||
configure()
|
||||
entityManager.persist(this)
|
||||
createdAt = CREATED_AT
|
||||
}
|
||||
|
||||
protected fun saveComment(
|
||||
post: CreatorCommunity,
|
||||
writer: Member = fan,
|
||||
comment: CreatorCommunityComment = CreatorCommunityComment("fan parent")
|
||||
): CreatorCommunityComment = comment.apply {
|
||||
creatorCommunity = post
|
||||
member = writer
|
||||
entityManager.persist(this)
|
||||
createdAt = CREATED_AT
|
||||
}
|
||||
|
||||
protected fun saveReply(
|
||||
root: CreatorCommunityComment,
|
||||
writer: Member = owner,
|
||||
content: String = "creator reply"
|
||||
): CreatorCommunityComment = saveComment(
|
||||
requireNotNull(root.creatorCommunity),
|
||||
writer,
|
||||
CreatorCommunityComment(content, isSecret = root.isSecret).apply { parent = root }
|
||||
)
|
||||
|
||||
protected fun flushAndClear() {
|
||||
entityManager.flush()
|
||||
entityManager.clear()
|
||||
}
|
||||
|
||||
protected fun perform(request: MockHttpServletRequestBuilder, member: Member = owner): ResultActions {
|
||||
flushAndClear()
|
||||
return mockMvc.perform(request.with(user(MemberAdapter(member))))
|
||||
}
|
||||
|
||||
protected fun response(actions: ResultActions): JsonNode = objectMapper.readTree(
|
||||
actions.andReturn().response.getContentAsString(StandardCharsets.UTF_8)
|
||||
)
|
||||
|
||||
protected fun data(actions: ResultActions): JsonNode {
|
||||
actions.andExpect(status().isOk).andExpect(jsonPath("$.success").value(true))
|
||||
return response(actions).path("data")
|
||||
}
|
||||
|
||||
protected fun expectMutation(actions: ResultActions) {
|
||||
actions.andExpect(status().isOk).andExpect(jsonPath("$.success").value(true))
|
||||
val body = response(actions)
|
||||
assertTrue(body.has("data"))
|
||||
assertTrue(body.path("data").isNull)
|
||||
}
|
||||
|
||||
protected fun contentBody(content: String): String = objectMapper.writeValueAsString(mapOf("content" to content))
|
||||
|
||||
protected fun commentsPath(post: CreatorCommunity): String = "$POSTS/${post.id}/comments"
|
||||
|
||||
protected fun rootPath(root: CreatorCommunityComment): String =
|
||||
"${commentsPath(requireNotNull(root.creatorCommunity))}/${root.id}"
|
||||
|
||||
protected fun comments(post: CreatorCommunity): JsonNode = data(perform(get(commentsPath(post))))
|
||||
|
||||
protected fun managementRequests(
|
||||
post: CreatorCommunity,
|
||||
root: CreatorCommunityComment,
|
||||
reply: CreatorCommunityComment
|
||||
): List<MockHttpServletRequestBuilder> = listOf(
|
||||
get(POSTS),
|
||||
get("$POSTS/${post.id}"),
|
||||
get(commentsPath(post)),
|
||||
delete(rootPath(root)),
|
||||
post("${rootPath(root)}/replies").contentType(MediaType.APPLICATION_JSON).content(contentBody("create")),
|
||||
put("${rootPath(root)}/replies/${reply.id}").contentType(MediaType.APPLICATION_JSON).content(contentBody("update")),
|
||||
delete("${rootPath(root)}/replies/${reply.id}")
|
||||
)
|
||||
|
||||
protected fun commentsFor(post: CreatorCommunity): List<CreatorCommunityComment> {
|
||||
flushAndClear()
|
||||
return entityManager.createQuery(
|
||||
"select c from CreatorCommunityComment c where c.creatorCommunity.id = :postId order by c.id",
|
||||
CreatorCommunityComment::class.java
|
||||
).setParameter("postId", post.id).resultList
|
||||
}
|
||||
|
||||
protected fun reloadComment(comment: CreatorCommunityComment): CreatorCommunityComment {
|
||||
flushAndClear()
|
||||
return entityManager.find(CreatorCommunityComment::class.java, comment.id)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user