Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[YS-130] feat: 기간이 지난 공고 state 변경 스케줄링 구현 #35

Merged
merged 23 commits into from
Jan 17, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
71bed6e
feat: implement experiment post lists filtering API with pagination
chock-cho Jan 14, 2025
d6f6c66
test: add test codes for experiment post filtering API usecase
chock-cho Jan 14, 2025
47e41da
fix: add unreflected source files
chock-cho Jan 14, 2025
5e2d49f
fix: update '_ALL' option to return all posts on that region
chock-cho Jan 14, 2025
f27bbdc
fix: update code review's feedbacks
chock-cho Jan 14, 2025
e330a38
refact: delegate domain converter to ExperimentMapper
chock-cho Jan 14, 2025
fc437ad
refact: rename usecase's class to suffix
chock-cho Jan 14, 2025
12ee7f1
refact: rename API endpoint query parameter →
chock-cho Jan 14, 2025
d8fdc9c
test: update test codes for refactoring
chock-cho Jan 14, 2025
b243be7
refact: update misunderstood requirement to meet the busniess logic
chock-cho Jan 14, 2025
b4500f5
fix: add ExperimentMapperTest codes to meet the test coverage
chock-cho Jan 14, 2025
1894eed
refact: refactor validator codes to upgrade readability
chock-cho Jan 14, 2025
0942256
feat: add WebSecurityConfig codes to allow permit without authentication
chock-cho Jan 14, 2025
fb1e6e3
fix: fix conflicts from dev branch
chock-cho Jan 14, 2025
5559259
fix: fix QueryDSL generation issues with entity and enum
Ji-soo708 Jan 14, 2025
71b7638
test: add test codes to meet the test coverage guage
chock-cho Jan 14, 2025
8980490
fix: resolve merge conflicts from origin dev branch
chock-cho Jan 15, 2025
50a764b
feat: implement experiment state scheudler using Quartz libraries
chock-cho Jan 15, 2025
1c61795
feat: add scheduling jobs to application layer for clean architecture
chock-cho Jan 15, 2025
e07f600
test: add test codes for experiment post status scheduler
chock-cho Jan 15, 2025
88ebd65
refact: delete final lines to specify eof line
chock-cho Jan 17, 2025
419b985
feat: specify Quartz time zone `Asia/Seoul`
chock-cho Jan 17, 2025
7d01e56
fix: resolve merge conlficts from dev branch
chock-cho Jan 17, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ dependencies {
implementation("org.mariadb.jdbc:mariadb-java-client:2.7.3")
implementation("org.springdoc:springdoc-openapi-starter-webmvc-ui:2.7.0")
implementation("org.springframework.cloud:spring-cloud-starter-openfeign")
implementation("org.springframework.boot:spring-boot-starter-quartz")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

저도 기간이 지난 공고 state를 변경하는 작업은 가볍다고 생각해서 quartz 구현 방식이 좋은 거 같아요 👍

implementation("io.awspring.cloud:spring-cloud-starter-aws:2.4.4")
compileOnly("org.projectlombok:lombok")
runtimeOnly("com.mysql:mysql-connector-j")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import com.dobby.backend.domain.exception.ExperimentAreaOverflowException
import com.dobby.backend.infrastructure.database.entity.enums.areaInfo.Area
import jakarta.transaction.Transactional
import org.springframework.stereotype.Service
import java.time.LocalDate

@Service
class ExperimentPostService(
Expand All @@ -19,7 +20,8 @@ class ExperimentPostService(
private val getExperimentPostCountsByRegionUseCase: GetExperimentPostCountsByRegionUseCase,
private val getExperimentPostCountsByAreaUseCase: GetExperimentPostCountsByAreaUseCase,
private val getExperimentPostApplyMethodUseCase: GetExperimentPostApplyMethodUseCase,
private val generateExperimentPostPreSignedUrlUseCase: GenerateExperimentPostPreSignedUrlUseCase
private val generateExperimentPostPreSignedUrlUseCase: GenerateExperimentPostPreSignedUrlUseCase,
private val updateExpiredExperimentPostUseCase: UpdateExpiredExperimentPostUseCase
) {
@Transactional
fun createNewExperimentPost(input: CreateExperimentPostUseCase.Input): CreateExperimentPostUseCase.Output {
Expand All @@ -42,6 +44,11 @@ class ExperimentPostService(
return getExperimentPostApplyMethodUseCase.execute(input)
}

@Transactional
fun updateExpiredExperimentPosts(input: UpdateExpiredExperimentPostUseCase.Input): UpdateExpiredExperimentPostUseCase.Output {
return updateExpiredExperimentPostUseCase.execute(input)
}

fun getExperimentPostCounts(input: Any): Any {
return when (input) {
is GetExperimentPostCountsByRegionUseCase.Input -> getExperimentPostCountsByRegionUseCase.execute(input)
Expand Down Expand Up @@ -69,7 +76,6 @@ class ExperimentPostService(
throw ExperimentAreaInCorrectException()
}
}

fun generatePreSignedUrl(input: GenerateExperimentPostPreSignedUrlUseCase.Input): GenerateExperimentPostPreSignedUrlUseCase.Output {
return generateExperimentPostPreSignedUrlUseCase.execute(input)
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package com.dobby.backend.application.usecase.experiment

import com.dobby.backend.application.usecase.UseCase
import com.dobby.backend.domain.gateway.experiment.ExperimentPostGateway
import java.time.LocalDate

class UpdateExpiredExperimentPostUseCase(
private val experimentPostGateway: ExperimentPostGateway
) : UseCase<UpdateExpiredExperimentPostUseCase.Input, UpdateExpiredExperimentPostUseCase.Output> {
data class Input(
val currentDate : LocalDate
)
data class Output(
val affectedRowsCount: Long
)

override fun execute(input: Input): Output {
return Output(
experimentPostGateway.updateExperimentPostStatus(input.currentDate)
)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import com.dobby.backend.domain.model.experiment.Pagination
import com.dobby.backend.domain.model.experiment.ExperimentPost
import com.dobby.backend.infrastructure.database.entity.enums.areaInfo.Region
import jakarta.persistence.Tuple
import java.time.LocalDate

interface ExperimentPostGateway {
fun save(experimentPost: ExperimentPost): ExperimentPost
Expand All @@ -14,6 +15,7 @@ interface ExperimentPostGateway {
fun countExperimentPosts(): Int
fun countExperimentPostByRegionGroupedByArea(region: Region): List<Tuple>
fun countExperimentPostGroupedByRegion(): List<Tuple>
fun updateExperimentPostStatus(todayDate : LocalDate) : Long
fun findExperimentPostsByMemberIdWithPagination(memberId: Long, pagination: Pagination, order: String): List<ExperimentPost>?
fun countExperimentPostsByMemberId(memberId: Long): Int
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package com.dobby.backend.infrastructure.config

import com.dobby.backend.infrastructure.scheduler.ExpiredExperimentPostJob
import org.quartz.*
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import java.util.*

@Configuration
class SchedulerConfig {
@Bean
fun expiredExperimentPostJobDetail(): JobDetail {
return JobBuilder.newJob(ExpiredExperimentPostJob::class.java)
.withIdentity("expired_experiment_post_job")
.storeDurably()
.build()
}

@Bean
fun expiredExperimentPostTrigger(): Trigger {
return TriggerBuilder.newTrigger()
.forJob(expiredExperimentPostJobDetail())
.withIdentity("expired_experiment_post_trigger")
.withSchedule(
CronScheduleBuilder.dailyAtHourAndMinute(0, 0)
Comment on lines +23 to +25
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Quartz 스케줄러는 기본적으로 시스템의 기본 시간대를 따르는데 설정하지 않아도 한국 시간대에 동작할 수 있지만, 안정성과 명시성을 위해 명확히 타임존을 설정하는 것은 어떨까요??

Suggested change
.withIdentity("expired_experiment_post_trigger")
.withSchedule(
CronScheduleBuilder.dailyAtHourAndMinute(0, 0)
.withIdentity("expired_experiment_post_trigger")
.withSchedule(
CronScheduleBuilder.dailyAtHourAndMinute(0, 0)
.inTimeZone(TimeZone.getTimeZone("Asia/Seoul"))

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

저도 해당 부분을 저희 '대규모 설계 시스템 기초 스터디'에서 7주차(어제자 발표)로 공부한 TimeZone 이슈에서 명시할 필요성이 있다는 것을 느꼈습니다!
인사이트 있는 피드백 정말 감사합니다! 반영하겠습니다.

.inTimeZone(TimeZone.getTimeZone("Asia/Seoul"))
)
.build()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import com.dobby.backend.domain.model.experiment.CustomFilter
import com.dobby.backend.domain.model.experiment.Pagination
import com.dobby.backend.infrastructure.database.entity.experiment.ExperimentPostEntity
import org.springframework.stereotype.Repository
import java.time.LocalDate

@Repository
interface ExperimentPostCustomRepository {
Expand All @@ -12,6 +13,7 @@ interface ExperimentPostCustomRepository {
pagination: Pagination
): List<ExperimentPostEntity>?

fun updateExperimentPostStatus(currentDate : LocalDate): Long
fun findExperimentPostsByMemberIdWithPagination(
memberId: Long,
pagination: Pagination,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import com.querydsl.core.types.OrderSpecifier
import com.querydsl.core.types.dsl.BooleanExpression
import com.querydsl.jpa.impl.JPAQueryFactory
import org.springframework.stereotype.Repository
import java.time.LocalDate

@Repository
class ExperimentPostCustomRepositoryImpl (
Expand Down Expand Up @@ -87,6 +88,19 @@ class ExperimentPostCustomRepositoryImpl (
return recruitDone?.let { post.recruitDone.eq(it) }
}

@Override
override fun updateExperimentPostStatus(currentDate: LocalDate): Long {
val experimentPost = QExperimentPostEntity.experimentPostEntity

return jpaQueryFactory.update(experimentPost)
.set(experimentPost.recruitDone, true)
.where(
experimentPost.endDate.lt(currentDate)
.and(experimentPost.recruitDone.eq(false))
)
.execute()
}

private fun getOrderClause(order: String): OrderSpecifier<*> {
val post = QExperimentPostEntity.experimentPostEntity
return if (order == "ASC") {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import com.dobby.backend.infrastructure.database.repository.ExperimentPostCustom
import com.dobby.backend.infrastructure.database.repository.ExperimentPostRepository
import jakarta.persistence.Tuple
import org.springframework.stereotype.Component
import java.time.LocalDate

@Component
class ExperimentPostGatewayImpl(
Expand Down Expand Up @@ -56,6 +57,9 @@ class ExperimentPostGatewayImpl(
return experimentPostRepository.countExperimentPostGroupedByRegion()
}

override fun updateExperimentPostStatus(currentDate: LocalDate): Long {
return experimentPostCustomRepository.updateExperimentPostStatus(currentDate)
}
override fun findExperimentPostsByMemberIdWithPagination(
memberId: Long,
pagination: Pagination,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.dobby.backend.infrastructure.scheduler

import com.dobby.backend.application.service.ExperimentPostService
import com.dobby.backend.application.usecase.experiment.UpdateExpiredExperimentPostUseCase
import org.quartz.Job
import org.quartz.JobExecutionContext
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component
import java.time.LocalDate

@Component
class ExpiredExperimentPostJob(
private val experimentPostService: ExperimentPostService
) : Job{
companion object {
private val logger : Logger = LoggerFactory.getLogger(ExpiredExperimentPostJob::class.java)
}

override fun execute(context: JobExecutionContext) {
val input = UpdateExpiredExperimentPostUseCase.Input(
LocalDate.now()
)
val output = experimentPostService.updateExpiredExperimentPosts(input)
logger.info("${output.affectedRowsCount} expired posts have been updated during scheduling jobs.")
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ object ExperimentPostMapper {
)
}


private fun toApplyMethodInfo(dto: ApplyMethodInfo): CreateExperimentPostUseCase.ApplyMethodInfo {
return CreateExperimentPostUseCase.ApplyMethodInfo(
content = dto.content,
Expand All @@ -55,6 +56,7 @@ object ExperimentPostMapper {
)
}


private fun toImageListInfo(dto: ImageListInfo): CreateExperimentPostUseCase.ImageListInfo {
return CreateExperimentPostUseCase.ImageListInfo(
images = dto.images
Expand Down Expand Up @@ -204,8 +206,9 @@ object ExperimentPostMapper {
univName = output.postInfo.univName,
reward = output.postInfo.reward,
durationInfo = DurationInfo(
startDate = output.postInfo.durationInfo.startDate,
endDate = output.postInfo.durationInfo.endDate
startDate = output.postInfo.durationInfo?.startDate,
endDate = output.postInfo.durationInfo?.endDate

)
),
recuritDone = output.postInfo.recruitDone
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import com.dobby.backend.application.usecase.experiment.UpdateExpiredExperimentPostUseCase
import com.dobby.backend.domain.gateway.experiment.ExperimentPostGateway
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.core.spec.style.BehaviorSpec
import io.kotest.matchers.shouldBe
import io.mockk.clearMocks
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import java.time.LocalDate

class UpdateExperimentPostUseCaseTest : BehaviorSpec({

val experimentPostGateway = mockk<ExperimentPostGateway>()
val updateExpiredExperimentPostUseCase = UpdateExpiredExperimentPostUseCase(experimentPostGateway)

given("게시글이 만료되어 상태가 업데이트되는 경우") {
val currentDate = LocalDate.of(2025, 1, 16)
val input = UpdateExpiredExperimentPostUseCase.Input(currentDate)
every { experimentPostGateway.updateExperimentPostStatus(any()) } returns 5L

`when`("Execute를 호출하면") {
then("UseCase는 업데이트된 게시글 수를 반환해야 한다") {
val output = updateExpiredExperimentPostUseCase.execute(input)
output.affectedRowsCount shouldBe 5L
verify(exactly = 1) { experimentPostGateway.updateExperimentPostStatus(currentDate) }
}
}
}

given("업데이트할 게시글이 없는 경우") {
val currentDate = LocalDate.of(2025, 1, 17)
val input = UpdateExpiredExperimentPostUseCase.Input(currentDate)

// Mock 설정을 각 테스트에서 바로 적용하지 않고 초기화 시 설정
every { experimentPostGateway.updateExperimentPostStatus(currentDate) } returns 0L

`when`("Execute를 호출하면") {
then("UseCase는 0을 반환해야 한다") {
val output = updateExpiredExperimentPostUseCase.execute(input)
output.affectedRowsCount shouldBe 0L
verify(exactly = 1) { experimentPostGateway.updateExperimentPostStatus(currentDate) }
}
}
}

given("Gateway에서 예외를 던지면") {
val currentDate = LocalDate.of(2025, 1, 18)
val input = UpdateExpiredExperimentPostUseCase.Input(currentDate)
val exceptionMessage = "Database error"

// 예외를 던지는 Mock 설정
every { experimentPostGateway.updateExperimentPostStatus(currentDate) } throws RuntimeException(exceptionMessage)

`when`("Execute를 호출하면") {
then("UseCase는 예외를 상위로 전달해야 한다") {
val exception = shouldThrow<RuntimeException> {
updateExpiredExperimentPostUseCase.execute(input)
}

exception.message shouldBe exceptionMessage
verify(exactly = 1) { experimentPostGateway.updateExperimentPostStatus(currentDate) }
}
}
}
})
Loading