-
Notifications
You must be signed in to change notification settings - Fork 0
Feat/#137 타임라인 - 타임라인 엔티티 AI 요약 #138
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
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
a6c3b2e
:recycle: refactor: 타임라인 수정, 삭제 시 MEMBER도 가능하도록 변경
kingmingyu eed55ba
:sparkles: feat: 타임라인 생성, 수정 시 현재 데이터가 존재하지 않으면 예외 반환
kingmingyu a726335
:sparkles: feat: 타임라인 요약 AI 프롬프트 추가
kingmingyu 2f2dbc6
:sparkles: feat: 타임라인 요약 AI API 호출
kingmingyu ab4a20b
:sparkles: feat: 타임라인 요약 AI 관련 에러코드 추가
kingmingyu 0b610ef
:sparkles: feat: 타임라인 요약 AI 서비스 로직 구현(Service에서 요청 검증 후 비동기 처리 호출)
kingmingyu bae5f36
:sparkles: feat: 타임라인 요약 AI Controller 및 Docs 작성
kingmingyu 29f4570
:sparkles: feat: 타임라인 요약 프롬프트에 비교기간 데이터 추가
kingmingyu File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
5 changes: 5 additions & 0 deletions
5
.../java/com/whereyouad/WhereYouAd/domains/timeline/domain/service/TimelineAsyncService.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| package com.whereyouad.WhereYouAd.domains.timeline.domain.service; | ||
|
|
||
| public interface TimelineAsyncService { | ||
| void summarizeAsync(Long timelineId, Long orgId); | ||
| } |
59 changes: 59 additions & 0 deletions
59
...a/com/whereyouad/WhereYouAd/domains/timeline/domain/service/TimelineAsyncServiceImpl.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,59 @@ | ||
| package com.whereyouad.WhereYouAd.domains.timeline.domain.service; | ||
|
|
||
| import com.whereyouad.WhereYouAd.domains.advertisement.domain.constant.Grain; | ||
| import com.whereyouad.WhereYouAd.domains.advertisement.persistence.entity.MetricFact; | ||
| import com.whereyouad.WhereYouAd.domains.advertisement.persistence.repository.MetricFactRepository; | ||
| import com.whereyouad.WhereYouAd.domains.timeline.exception.TimelineException; | ||
| import com.whereyouad.WhereYouAd.domains.timeline.exception.code.TimelineErrorCode; | ||
| import com.whereyouad.WhereYouAd.domains.timeline.persistence.entity.Timeline; | ||
| import com.whereyouad.WhereYouAd.domains.timeline.persistence.repository.TimelineRepository; | ||
| import com.whereyouad.WhereYouAd.infrastructure.client.openai.service.OpenApiService; | ||
| import lombok.RequiredArgsConstructor; | ||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.springframework.scheduling.annotation.Async; | ||
| import org.springframework.stereotype.Service; | ||
| import org.springframework.transaction.annotation.Transactional; | ||
|
|
||
| import java.util.List; | ||
|
|
||
| @Slf4j | ||
| @Service | ||
| @RequiredArgsConstructor | ||
| public class TimelineAsyncServiceImpl implements TimelineAsyncService { | ||
|
|
||
| private final TimelineRepository timelineRepository; | ||
| private final MetricFactRepository metricFactRepository; | ||
| private final OpenApiService openApiService; | ||
|
|
||
| @Override | ||
| @Async | ||
| @Transactional | ||
| public void summarizeAsync(Long timelineId, Long orgId) { | ||
| Timeline timeline = timelineRepository.findById(timelineId) | ||
| .orElseThrow(() -> new TimelineException(TimelineErrorCode.TIMELINE_NOT_FOUND)); | ||
|
|
||
| // 분석 기간 Metric_fact 데이터 불러오기 | ||
| List<MetricFact> facts = metricFactRepository.findByOrgAndPeriodAndGrain( | ||
| orgId, | ||
| timeline.getStartDate().atStartOfDay(), | ||
| timeline.getEndDate().plusDays(1).atStartOfDay(), | ||
| Grain.DAILY | ||
| ); | ||
|
|
||
| // 비교 기간 Metric_fact 데이터 불러오기 | ||
| List<MetricFact> comparisonFacts = metricFactRepository.findByOrgAndPeriodAndGrain( | ||
| orgId, | ||
| timeline.getComparisonStartDate().atStartOfDay(), | ||
| timeline.getComparisonEndDate().plusDays(1).atStartOfDay(), | ||
| Grain.DAILY | ||
| ); | ||
|
|
||
| try { | ||
| // 타임라인 AI요약 생성 요청 | ||
| String summary = openApiService.generateTimelineSummary(timeline, facts, comparisonFacts); | ||
| timeline.updateSummary(summary); | ||
| } catch (Exception e) { | ||
| log.error("[Timeline AI 요약 실패] timelineId={}, error={}", timelineId, e.getMessage()); | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,11 +1,9 @@ | ||
| package com.whereyouad.WhereYouAd.domains.timeline.domain.service; | ||
|
|
||
| import com.whereyouad.WhereYouAd.domains.advertisement.persistence.repository.projection.MetricSumProjection; | ||
| import com.whereyouad.WhereYouAd.domains.organization.domain.constant.OrgRole; | ||
| import com.whereyouad.WhereYouAd.domains.organization.domain.constant.OrgStatus; | ||
| import com.whereyouad.WhereYouAd.domains.organization.exception.code.OrgErrorCode; | ||
| import com.whereyouad.WhereYouAd.domains.organization.exception.handler.OrgHandler; | ||
| import com.whereyouad.WhereYouAd.domains.organization.persistence.entity.OrgMember; | ||
| import com.whereyouad.WhereYouAd.domains.organization.persistence.entity.Organization; | ||
| import com.whereyouad.WhereYouAd.domains.organization.persistence.repository.OrgMemberRepository; | ||
| import com.whereyouad.WhereYouAd.domains.organization.persistence.repository.OrgRepository; | ||
|
|
@@ -28,12 +26,13 @@ | |
| import lombok.RequiredArgsConstructor; | ||
| import org.springframework.stereotype.Service; | ||
| import org.springframework.transaction.annotation.Transactional; | ||
| import org.springframework.transaction.support.TransactionSynchronization; | ||
| import org.springframework.transaction.support.TransactionSynchronizationManager; | ||
|
|
||
| import java.time.DayOfWeek; | ||
| import java.math.BigDecimal; | ||
| import java.math.RoundingMode; | ||
| import java.time.LocalDate; | ||
| import java.time.LocalTime; | ||
| import java.util.ArrayList; | ||
| import java.util.Comparator; | ||
| import java.util.List; | ||
|
|
@@ -50,6 +49,7 @@ public class TimelineServiceImpl implements TimelineService { | |
| private final OrgRepository orgRepository; | ||
| private final OrgMemberRepository orgMemberRepository; | ||
| private final TimelineUtil timelineUtil; | ||
| private final TimelineAsyncService timelineAsyncService; | ||
|
|
||
| @Override | ||
| public TimelineResponse.CreateResponseDTO createTimeline(Long userId, Long orgId, TimelineRequest.TimelineCreateDto dto) { | ||
|
|
@@ -91,6 +91,11 @@ public TimelineResponse.CreateResponseDTO createTimeline(Long userId, Long orgId | |
| Status.ON_GOING | ||
| ); | ||
|
|
||
| // 현재 기간에 성과 데이터가 없거나 모두 0이면 타임라인 생성 불가 | ||
| if (isProjectionEmpty(currentFacts)) { | ||
| throw new TimelineException(TimelineErrorCode.TIMELINE_NO_CURRENT_DATA); | ||
| } | ||
|
|
||
| // 입력받은 DTO를 타임라인 엔티티로 변환 | ||
| Timeline timeline = TimelineConverter.toTimeline(dto, organization, userId, comparisonDates.start(), comparisonDates.end()); | ||
|
|
||
|
|
@@ -117,12 +122,9 @@ public TimelineResponse.CreateResponseDTO updateTimeline(Long userId, Long orgId | |
| throw new TimelineException(TimelineErrorCode.TIMELINE_NOT_FOUND); | ||
| } | ||
|
|
||
| // 4. ADMIN 권한 검증 | ||
| OrgMember member = orgMemberRepository.findByUserIdAndOrgId(userId, orgId) | ||
| // 4. 조직 멤버 검증 | ||
| orgMemberRepository.findByUserIdAndOrgId(userId, orgId) | ||
| .orElseThrow(() -> new TimelineException(TimelineErrorCode.TIMELINE_UPDATE_FORBIDDEN)); | ||
| if (member.getRole() != OrgRole.ADMIN) { | ||
| throw new TimelineException(TimelineErrorCode.TIMELINE_UPDATE_FORBIDDEN); | ||
| } | ||
|
|
||
| // 5. 날짜 검증 | ||
| if (dto.endDate().isBefore(dto.startDate())) { | ||
|
|
@@ -154,6 +156,11 @@ public TimelineResponse.CreateResponseDTO updateTimeline(Long userId, Long orgId | |
| Status.ON_GOING | ||
| ); | ||
|
|
||
| // 현재 기간에 성과 데이터가 없거나 모두 0이면 수정 불가 | ||
| if (isProjectionEmpty(currentFacts)) { | ||
| throw new TimelineException(TimelineErrorCode.TIMELINE_NO_CURRENT_DATA); | ||
| } | ||
|
|
||
| // 8. 성과 리스트 -> boolean 플래그 변환 | ||
| boolean useClick = dto.metrics().contains(MetricType.CLICK); | ||
| boolean useConversion = dto.metrics().contains(MetricType.CONVERSION); | ||
|
|
@@ -188,14 +195,9 @@ public void deleteTimeline(Long userId, Long orgId, Long timelineId) { | |
| } | ||
|
|
||
| // 조직 맴버가 아닌 경우 | ||
| OrgMember member = orgMemberRepository.findByUserIdAndOrgId(userId, orgId) | ||
| orgMemberRepository.findByUserIdAndOrgId(userId, orgId) | ||
| .orElseThrow(() -> new TimelineException(TimelineErrorCode.TIMELINE_DELETE_FORBIDDEN)); | ||
|
|
||
| // ADMIN 권한이 없는 경우 | ||
| if (member.getRole() != OrgRole.ADMIN) { | ||
| throw new TimelineException(TimelineErrorCode.TIMELINE_DELETE_FORBIDDEN); | ||
| } | ||
|
|
||
| // 삭제 | ||
| timelineRepository.delete(timeline); | ||
| } | ||
|
|
@@ -255,6 +257,42 @@ public TimelineResponse.TimelineDetailDTO getTimelineDetail(Long userId, Long or | |
| return TimelineConverter.toTimelineDetailDTO(timeline, metrics, dailyTrend, platformContributions); | ||
| } | ||
|
|
||
| @Override | ||
| public void requestTimelineSummary(Long userId, Long orgId, Long timelineId) { | ||
| orgRepository.findById(orgId) | ||
| .orElseThrow(() -> new OrgHandler(OrgErrorCode.ORG_NOT_FOUND)); | ||
|
|
||
| orgMemberRepository.findByUserIdAndOrgId(userId, orgId) | ||
| .orElseThrow(() -> new TimelineException(TimelineErrorCode.TIMELINE_READ_FORBIDDEN)); | ||
|
|
||
| Timeline timeline = timelineRepository.findById(timelineId) | ||
| .orElseThrow(() -> new TimelineException(TimelineErrorCode.TIMELINE_NOT_FOUND)); | ||
|
|
||
| // 해당 조직의 타임라인이 아닌 경우 | ||
| if (!timeline.getOrganization().getId().equals(orgId)) { | ||
| throw new TimelineException(TimelineErrorCode.TIMELINE_NOT_FOUND); | ||
| } | ||
|
|
||
| // 생성 이후 MetricFact 변동 or 광고 상태 변경을 대비한 재검증 | ||
| boolean hasData = metricFactRepository.existsByTimeBucketBetweenAndOrg( | ||
| timeline.getStartDate().atStartOfDay(), | ||
| timeline.getEndDate().plusDays(1).atStartOfDay(), | ||
| orgId | ||
| ); | ||
|
Comment on lines
+277
to
+281
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 요약 요청 전 데이터 재검증 조건이 실제 요약 조회 조건과 다릅니다. 여기서는 기간+조직만 확인하고, 비동기 생성에서는 수정 방향 예시- boolean hasData = metricFactRepository.existsByTimeBucketBetweenAndOrg(
- timeline.getStartDate().atStartOfDay(),
- timeline.getEndDate().plusDays(1).atStartOfDay(),
- orgId
- );
+ boolean hasData = !metricFactRepository.findByOrgAndPeriodAndGrain(
+ orgId,
+ timeline.getStartDate().atStartOfDay(),
+ timeline.getEndDate().plusDays(1).atStartOfDay(),
+ Grain.DAILY
+ ).isEmpty();🤖 Prompt for AI Agents |
||
| if (!hasData) { | ||
| throw new TimelineException(TimelineErrorCode.TIMELINE_NO_METRIC_DATA); | ||
| } | ||
|
|
||
| // 트랜잭션 훅 등록 | ||
| TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() { | ||
| @Override | ||
| // 트랜잭션이 성공적으로 커밋된 시점 이후에 호출 | ||
| public void afterCommit() { | ||
| timelineAsyncService.summarizeAsync(timelineId, orgId); | ||
| } | ||
| }); | ||
| } | ||
|
|
||
| // 선택된 지표를 리스트로 변환해주는 메서드 | ||
| private List<MetricType> buildMetricList(Timeline timeline) { | ||
| List<MetricType> metrics = new ArrayList<>(); | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.