Skip to content

Refactor/#167 대시보드 성과 집계 방식 개선 - 조직 기반 데이터 집계로 수정#170

Merged
ojy0903 merged 9 commits into
developfrom
refactor/#167
Jul 8, 2026
Merged

Refactor/#167 대시보드 성과 집계 방식 개선 - 조직 기반 데이터 집계로 수정#170
ojy0903 merged 9 commits into
developfrom
refactor/#167

Conversation

@ojy0903

@ojy0903 ojy0903 commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator

📌 관련 이슈

🚀 개요

이번 PR에서 변경된 핵심 내용을 요약해주세요.

대시보드 전체 지표 조회 (GET /api/dashborad/{orgId}/metrics) API 에서 가장 최신 time_bucket 조회를 DB 테이블 전체 기준이 아닌 각 조직 기준으로 조회하도록 개선

📄 작업 내용

구체적인 작업 내용을 설명해주세요.

  • DashboardServiceImpl 내부 getAggregatedMetrics 메서드 내 metricFactRepository 메서드 사용 변경
  • MetricFactRepository 내부 findLatestTimeBucketByOrgId 메서드 수정

📸 스크린샷 / 테스트 결과 (선택)

결과물 확인을 위한 사진이나 테스트 로그를 첨부해주세요.

기존 develop 브랜치에 timebucket 최신값 로깅을 추가하고 테스트
image

DB 상태 : MetricFact 테이블에서 가장 최근 timeBucket 은 6월20일, 모든 metricFact 는 orgId=1 인 조직의 project 에 소속
image
image

develop 브랜치
API 정상 응답
image

서버 로그 내부 timeBucket 최신 값 6월 20일 확인
image

project_id=2 인 임의의 project 생성 후 (org_id = 2 에 소속), 해당 project 에 속하는 임의의 metricFact 값 추가
image
image

API 호출 결과 다른 조직의 최신 time_bucket 값이 로그로 조회됨.
image
image

---> 이와 같이 기존에는 해당 time_bucket 최신값이 조직 상관없이 테이블 내에서 가장 최신 값으로 조회되는 방식이였는데, 이 최신값이 각 조직 별 metricFact 의 최신값으로 조회되어야 할 것 같아 이를 개선했습니다.
refactor/#167 브랜치
image

다른 조직의 데이터 값이 존재하여도 요청값에 있는 조직의 최신 time_bucket 으로 조회됨을 확인
image
image

✅ 체크리스트

  • 브랜치 전략(GitHub Flow)을 준수했나요?
  • 메서드 단위로 코드가 잘 쪼개져 있나요?
  • 테스트 통과 확인
  • 서버 실행 확인
  • API 동작 확인

🔍 리뷰 포인트 (Review Points)

리뷰어가 중점적으로 확인했으면 하는 부분을 적어주세요. (P1~P4 적용 가이드)

  • Meta 로그인 관련 프론트측에서 버그 수정 요청 받아서 진행하다가 이 부분을 발견하여 개선하였습니다.
  • MetricFactRepository 쪽 메서드 1개 수정이라 가볍게 보셔도 될 거 같습니다...
  • 그리고 리팩터링 진행하다가 생각난건데, 지금 구조에서는 지표 관련 계산 시에 Project 엔티티에 연관되어 있는 광고 객체들을 통해 지표를 계산하는데, Project 엔티티로 연결되지 않은 AdCampaign 들에 대해서 지표 계산을 포함해야할지 고민입니다... 사용자가 광고 플랫폼 연동을 진행해서 생성된 AdCampaign 들을 Project 엔티티로 묶지 않는 경우도 있을까요..??
    -> 커밋 내역 중에 Revert 로 되돌린 커밋이 이 Project로 연동되지 않은 AdCampaign 도 지표 계산에 포함되도록 했다가 되돌린 작업입니다...

💬 리뷰어 가이드 (P-Rules)
P1: 필수 반영 (Critical) - 버그 가능성, 컨벤션 위반. 해결 전 머지 불가.
P2: 적극 권장 (Recommended) - 더 나은 대안 제시. 가급적 반영 권장.
P3: 제안 (Suggestion) - 아이디어 공유. 반영 여부는 드라이버 자율.
P4: 단순 확인/칭찬 (Nit) - 사소한 오타, 칭찬 등 피드백.

Summary by CodeRabbit

  • Bug Fixes
    • 대시보드 집계 기준이 전체 데이터가 아닌 조직별 최신 데이터 기준으로 계산되도록 개선했습니다.
    • 최신 기간 계산 범위를 하루 확장해, 일부 최신 데이터가 집계에서 누락되는 문제를 줄였습니다.

@ojy0903 ojy0903 self-assigned this Jul 8, 2026
@ojy0903 ojy0903 added 🐛 Bug 버그 수정 ♻️ Refactor 코드 구조 개선 labels Jul 8, 2026
@coderabbitai

coderabbitai Bot commented Jul 8, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@ojy0903, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 52 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 8f7003b7-fcbe-4e45-8137-1df49d98e715

📥 Commits

Reviewing files that changed from the base of the PR and between 98b7ad8 and 1ce752e.

📒 Files selected for processing (1)
  • src/main/java/com/whereyouad/WhereYouAd/domains/advertisement/persistence/repository/MetricFactRepository.java

Walkthrough

대시보드 성과 집계 기준을 전체 데이터 최신 timeBucket에서 조직(orgId) 기준 최신 timeBucket으로 변경했습니다. MetricFactRepository에 findLatestTimeBucketByOrgId가 추가되어 기존 메서드를 대체했고, DashboardServiceImpl은 이를 활용해 currentEnd(+1일) 기준으로 집계 기간을 재계산합니다.

Changes

조직 기반 대시보드 집계

Layer / File(s) Summary
조직별 최신 timeBucket 조회 쿼리
.../persistence/repository/MetricFactRepository.java
findLatestTimeBucket()을 제거하고, project를 조인해 organization.id = :orgId로 필터링하는 findLatestTimeBucketByOrgId(Long orgId)를 추가함.
집계 기간 산정 로직 변경
.../dashboard/domain/service/DashboardServiceImpl.java
조직별 최신 timeBucket으로 latestDate를 구하고 currentEnd = latestDate.plusDays(1)로 상한을 하루 확장, oneMonthAgo/twoMonthsAgo를 재계산하며 두 집계 쿼리 호출 인자를 currentEnd로 변경. 미사용 BudgetFieldType import 제거.

Estimated code review effort: 2 (Simple) | ~10 minutes

Sequence Diagram(s)

sequenceDiagram
  participant DashboardServiceImpl
  participant MetricFactRepository
  participant Database

  DashboardServiceImpl->>MetricFactRepository: findLatestTimeBucketByOrgId(orgId)
  MetricFactRepository->>Database: MetricFact JOIN project WHERE organization.id = orgId
  Database-->>MetricFactRepository: 최신 timeBucket
  MetricFactRepository-->>DashboardServiceImpl: latestDate
  DashboardServiceImpl->>DashboardServiceImpl: currentEnd = latestDate.plusDays(1)
  DashboardServiceImpl->>DashboardServiceImpl: oneMonthAgo/twoMonthsAgo 재계산
  DashboardServiceImpl->>MetricFactRepository: findMetricsSumByOrgIdAndDateRange(..., currentEnd)
  DashboardServiceImpl->>MetricFactRepository: findMetricsSumByOrgIdAndProvider(..., currentEnd)
Loading

Possibly related PRs

  • WhereYouAd/WhereYouAd-Backend#53: 동일한 MetricFactRepository/DashboardServiceImpl의 집계 기간 및 최신 timeBucket 사용 흐름을 다루고 있음.

Suggested reviewers: jinnieusLab


시니어 개발자 시점에서 한마디 남기자면요, orgId 조인 쿼리로 바뀐 부분(findLatestTimeBucketByOrgId)은 실제 버그(Mock 데이터 timeBucket 때문에 지표 안 잡히던 문제)를 정확히 짚어서 고친 좋은 수정이에요! 다만 currentEnd = latestDate.plusDays(1)처럼 상한을 하루 늘린 이유가 코드만 봐서는 명확하지 않으니, 주석 한 줄로 "왜 +1일인지"(예: 당일 데이터 포함 목적) 남겨두면 다음 리뷰어가 헷갈리지 않을 것 같아요. 쿼리 성능 측면에서는 project 조인이 인덱스만 잘 타면 문제없어 보이니, organization.id에 인덱스가 있는지만 한 번 확인해보세요 🙂

🐰 조직마다 시계를 다시 맞추고
   최신 데이터 쫓아 하루를 더하네
   Mock 데이터야 이제는 안녕
   진짜 성과가 반짝반짝 빛나요
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Linked Issues check ✅ Passed 조직별 최신 time_bucket 조회로 변경하고 서비스 호출도 함께 수정해 #167의 핵심 요구사항을 충족합니다.
Out of Scope Changes check ✅ Passed 설명된 범위를 벗어난 별도 기능 추가나 무관한 변경은 보이지 않습니다.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Title check ✅ Passed 제목이 조직 기준 최신 time_bucket 조회로의 변경이라는 핵심 내용을 잘 요약합니다.
Description check ✅ Passed 템플릿의 필수 섹션(이슈, 개요, 작업 내용, 체크리스트, 리뷰 포인트)을 모두 포함해 충분히 작성되었습니다.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch refactor/#167

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@src/main/java/com/whereyouad/WhereYouAd/domains/advertisement/persistence/repository/MetricFactRepository.java`:
- Around line 32-37: Update findLatestTimeBucketByOrgId in MetricFactRepository
so the latest timeBucket is computed with the same active/ongoing filters used
by the aggregation queries, rather than taking MAX over all MetricFact rows for
the organization. Add the necessary conditions tied to the project/org status
(OrgStatus.ACTIVE and Status.ON_GOING) in the JPQL, and adjust the nearby
comment to say “해당 조직” instead of “해당 프로젝트” to match the method’s scope.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 23f1391d-7eba-416c-889e-de46c41af4ba

📥 Commits

Reviewing files that changed from the base of the PR and between 98dff56 and 98b7ad8.

📒 Files selected for processing (2)
  • src/main/java/com/whereyouad/WhereYouAd/domains/advertisement/persistence/repository/MetricFactRepository.java
  • src/main/java/com/whereyouad/WhereYouAd/domains/dashboard/domain/service/DashboardServiceImpl.java

@kingmingyu kingmingyu left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

P4: 고생하셨습니다! 이런 문제가 있었군요.. 프로젝트 관련해서는 저희가 기존 광고 계정을 연동하고 광고 데이터를 불러오면 그걸 목적에 맞는 프로젝트를 생성해서 그 프로젝트끼리 데이터를 비교하고 분석하는 걸로 기억을 해서 지금도 상태도 괜찮을 것 같습니다!

@jinnieusLab jinnieusLab left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

P4: 오 고생하셨습니다! 지표가 전체에 대해서 조회 되도록 구현된 줄은 몰랐는데 발견해주셔서 다행이네요... 감사합니다!
제 생각에도 유저가 프로젝트 생성 시 원하는 캠페인을 선택하여 묶고 있는 흐름이니, 지금처럼 Project 연관 관계에 해당하는 캠페인들만 지표에 반영하는 방향으로 그대로 가도 될 것 같습니다!

@ojy0903 ojy0903 merged commit fc3dd11 into develop Jul 8, 2026
2 checks passed
@ojy0903 ojy0903 deleted the refactor/#167 branch July 8, 2026 14:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐛 Bug 버그 수정 ♻️ Refactor 코드 구조 개선

Projects

None yet

Development

Successfully merging this pull request may close these issues.

refactor: 대시보드 성과 집계 방식 개선 - 조직 기반 데이터 집계로 수정

3 participants