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

feat : 이벤트 만료 시 자동 만료 배치 작업 추가 #521

Merged
merged 5 commits into from
Mar 6, 2023
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package band.gosrock.job;


import band.gosrock.domain.domains.event.domain.Event;
import band.gosrock.domain.domains.event.service.EventService;
import band.gosrock.parameter.DateTimeJobParameter;
import band.gosrock.slack.SlackEventExpirationSender;
import java.time.LocalDateTime;
import java.util.List;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.JobScope;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Slf4j
@RequiredArgsConstructor
@Configuration
public class EventExpiration {

private static final String JOB_NAME = "이벤트_자동만료";
private static final String BEAN_PREFIX = JOB_NAME + "_";

private final JobBuilderFactory jobBuilderFactory;
private final StepBuilderFactory stepBuilderFactory;

private final SlackEventExpirationSender slackEventExpirationSender;
private final EventService eventService;

@Bean(BEAN_PREFIX + "dateTimeJobParameter")
@JobScope
public DateTimeJobParameter dateTimeJobParameter() {
return new DateTimeJobParameter();
}

@Bean(JOB_NAME)
public Job eventExpirationJob() {
return jobBuilderFactory
.get(JOB_NAME)
.preventRestart()
.start(eventExpirationStep())
.build();
}

@Bean(BEAN_PREFIX + "step")
@JobScope
public Step eventExpirationStep() {
return stepBuilderFactory
.get(BEAN_PREFIX + "step")
.tasklet(
(contribution, chunkContext) -> {
log.info(">>>>> 이벤트 자동 만료 작업 실행");
LocalDateTime time = dateTimeJobParameter().getTime();
List<Event> events = eventService.closeExpiredEventsEndAtBefore(time);
slackEventExpirationSender.execute(time, events);
return RepeatStatus.FINISHED;
})
.build();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

import band.gosrock.domain.domains.user.adaptor.UserAdaptor;
import band.gosrock.parameter.DateJobParameter;
import band.gosrock.slack.SlackSender;
import band.gosrock.slack.SlackUserNotificationSender;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
Expand All @@ -28,7 +28,7 @@ public class SlackUserStatistic {

private final JobBuilderFactory jobBuilderFactory;
private final StepBuilderFactory stepBuilderFactory;
private final SlackSender slackSender;
private final SlackUserNotificationSender slackSender;

private final UserAdaptor userAdaptor;
private final DateJobParameter dateJobParameter;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package band.gosrock.parameter;


import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Objects;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.springframework.batch.core.JobParametersInvalidException;
import org.springframework.beans.factory.annotation.Value;

@Getter
@NoArgsConstructor
public class DateTimeJobParameter {
private LocalDateTime time;

@Value("#{jobParameters[dateTime]}")
public void setDateTime(String dateTime) throws JobParametersInvalidException {
// 인자가 없다면 now 로 설정
if (Objects.isNull(dateTime)) this.time = LocalDateTime.now();
else {
try {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
this.time = LocalDateTime.parse(dateTime, formatter);
} catch (Exception e) {
throw new JobParametersInvalidException("올바르지 않은 시간 형식입니다");
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package band.gosrock.slack;

import static com.slack.api.model.block.Blocks.divider;
import static com.slack.api.model.block.Blocks.section;
import static com.slack.api.model.block.composition.BlockCompositions.plainText;

import band.gosrock.domain.domains.event.domain.Event;
import band.gosrock.infrastructure.config.slack.SlackServiceNotificationProvider;
import com.slack.api.model.block.Blocks;
import com.slack.api.model.block.LayoutBlock;
import com.slack.api.model.block.composition.MarkdownTextObject;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
@Slf4j
public class SlackEventExpirationSender {
private final SlackServiceNotificationProvider slackProvider;

public void execute(LocalDateTime time, List<Event> events) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
List<LayoutBlock> layoutBlocks = new ArrayList<>();

layoutBlocks.add(
Blocks.header(
headerBlockBuilder -> headerBlockBuilder.text(plainText("공연 자동 만료 알림"))));
layoutBlocks.add(divider());
MarkdownTextObject markdownDateTime =
MarkdownTextObject.builder().text("* 기준 시간:*\n" + time.format(formatter)).build();
MarkdownTextObject markdownTotalEvents =
MarkdownTextObject.builder().text("* 만료 공연 수:*\n" + events.size()).build();
layoutBlocks.add(
section(section -> section.fields(List.of(markdownDateTime, markdownTotalEvents))));
layoutBlocks.add(divider());

MarkdownTextObject markdownEventIdTitle =
MarkdownTextObject.builder().text("* 공연 ID:*\n").build();
MarkdownTextObject markdownEventNameTitle =
MarkdownTextObject.builder().text("* 공연 이름:*\n").build();
layoutBlocks.add(
section(
section ->
section.fields(
List.of(markdownEventIdTitle, markdownEventNameTitle))));

events.forEach(
event -> {
MarkdownTextObject markdownEventId =
MarkdownTextObject.builder().text(event.getId().toString()).build();
MarkdownTextObject markdownEventName =
MarkdownTextObject.builder()
.text(event.getEventBasic().getName())
.build();
layoutBlocks.add(
section(
section ->
section.fields(
List.of(markdownEventId, markdownEventName))));
});

slackProvider.sendNotification(layoutBlocks);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
@Component
@RequiredArgsConstructor
@Slf4j
public class SlackSender {
public class SlackUserNotificationSender {
private final SlackServiceNotificationProvider slackProvider;

public void execute(LocalDate date, Long todayUserCount, Long yesterdayCount) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@
import band.gosrock.domain.domains.event.domain.EventStatus;
import band.gosrock.domain.domains.event.exception.EventNotFoundException;
import band.gosrock.domain.domains.event.repository.EventRepository;
import java.time.LocalDateTime;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice;
import org.springframework.transaction.annotation.Transactional;

@Adaptor
@RequiredArgsConstructor
Expand All @@ -33,21 +33,22 @@ public Page<Event> findAllByHostIdIn(List<Long> hostId, Pageable pageable) {
return eventRepository.findAllByHostIdIn(hostId, pageable);
}

@Transactional(readOnly = true)
public Slice<Event> querySliceEventsByHostIdIn(List<Long> hostId, Pageable pageable) {
return eventRepository.querySliceEventsByHostIdIn(hostId, pageable);
}

@Transactional(readOnly = true)
public Slice<Event> querySliceEventsByStatus(EventStatus status, Pageable pageable) {
return eventRepository.querySliceEventsByStatus(status, pageable);
}

@Transactional(readOnly = true)
public Slice<Event> querySliceEventsByKeyword(String keyword, Pageable pageable) {
return eventRepository.querySliceEventsByKeyword(keyword, pageable);
}

public List<Event> queryEventsByEndAtBefore(LocalDateTime time) {
return eventRepository.queryEventsByEndAtBefore(time);
}

public List<Event> findAllByIds(List<Long> ids) {
return eventRepository.findAllByIdIn(ids);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

import band.gosrock.domain.domains.event.domain.Event;
import band.gosrock.domain.domains.event.domain.EventStatus;
import java.time.LocalDateTime;
import java.util.List;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice;
Expand All @@ -13,4 +14,6 @@ public interface EventCustomRepository {
Slice<Event> querySliceEventsByStatus(EventStatus status, Pageable pageable);

Slice<Event> querySliceEventsByKeyword(String keyword, Pageable pageable);

List<Event> queryEventsByEndAtBefore(LocalDateTime time);
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package band.gosrock.domain.domains.event.repository;

import static band.gosrock.domain.domains.event.domain.EventStatus.CLOSED;
import static band.gosrock.domain.domains.event.domain.EventStatus.OPEN;
import static band.gosrock.domain.domains.event.domain.QEvent.event;

Expand All @@ -8,6 +9,8 @@
import band.gosrock.domain.domains.event.domain.EventStatus;
import com.querydsl.core.types.OrderSpecifier;
import com.querydsl.core.types.dsl.BooleanExpression;
import com.querydsl.core.types.dsl.DateTemplate;
import com.querydsl.core.types.dsl.Expressions;
import com.querydsl.jpa.impl.JPAQueryFactory;
import java.time.LocalDateTime;
import java.util.List;
Expand Down Expand Up @@ -59,6 +62,11 @@ public Slice<Event> querySliceEventsByKeyword(String keyword, Pageable pageable)
return SliceUtil.valueOf(events, pageable);
}

@Override
public List<Event> queryEventsByEndAtBefore(LocalDateTime time) {
return queryFactory.selectFrom(event).where(endAtBefore(time), notEqClosed()).fetch();
}

private BooleanExpression hostIdIn(List<Long> hostId) {
return event.hostId.in(hostId);
}
Expand All @@ -67,11 +75,25 @@ private BooleanExpression eqStatusOpen() {
return event.status.eq(OPEN);
}

private BooleanExpression notEqClosed() {
return event.status.eq(CLOSED).not();
}

private BooleanExpression nameContains(String keyword) {
return keyword == null ? null : event.eventBasic.name.containsIgnoreCase(keyword);
}

private OrderSpecifier<LocalDateTime> createdAtDesc() {
return event.createdAt.desc();
}

private BooleanExpression endAtBefore(LocalDateTime time) {
DateTemplate<LocalDateTime> eventEndAtTemplate =
Expressions.dateTemplate(
LocalDateTime.class,
"TIMESTAMPADD(MINUTE,{0}, {1}) ",
event.eventBasic.runTime,
event.eventBasic.startAt);
return eventEndAtTemplate.before(time);
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package band.gosrock.domain.domains.event.service;

import static band.gosrock.domain.domains.event.domain.QEvent.event;

import band.gosrock.common.annotation.DomainService;
import band.gosrock.domain.domains.event.adaptor.EventAdaptor;
Expand All @@ -10,6 +11,8 @@
import band.gosrock.domain.domains.event.repository.EventRepository;
import band.gosrock.domain.domains.issuedTicket.adaptor.IssuedTicketAdaptor;
import band.gosrock.domain.domains.ticket_item.service.TicketItemService;
import java.time.LocalDateTime;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Transactional;

Expand Down Expand Up @@ -67,6 +70,13 @@ public Event updateEventStatus(Event event, EventStatus status) {
return eventRepository.save(event);
}

public List<Event> closeExpiredEventsEndAtBefore(LocalDateTime time) {
List<Event> events = eventAdaptor.queryEventsByEndAtBefore(time);
events.forEach(event -> updateEventStatus(event, EventStatus.CLOSED));
eventRepository.saveAll(events);
return events;
}

public Event deleteEventSoft(Event event) {
// 발급된 티켓이 있다면 삭제 불가
if (issuedTicketAdaptor.existsByEventId(event.getId()))
Expand Down