Skip to content

fix: 기록장 투표 정보 퍼센트가 아닌 득표수로 표시되도록 수정#247

Merged
ljh130334 merged 1 commit intodevelopfrom
hotfix/vote
Sep 16, 2025
Merged

fix: 기록장 투표 정보 퍼센트가 아닌 득표수로 표시되도록 수정#247
ljh130334 merged 1 commit intodevelopfrom
hotfix/vote

Conversation

@ljh130334
Copy link
Member

@ljh130334 ljh130334 commented Sep 16, 2025

#️⃣ 연관된 이슈

#246

📝 작업 내용

기록장 투표 표시를 퍼센트에서 득표수로 변경

투표 API의 count 필드를 활용해서 기록장에서 투표 결과를 퍼센트(%) 대신 득표수(표)로 표시하도록 수정했습니다.

1. 타입 정의 업데이트

  • VoteItemResult, VoteItem, PollOption 타입에 count 필드 추가
  • API 응답에서 받아오는 득표수 데이터를 타입에 반영

2. 투표 결과 표시 변경

  • PollRecord.tsx에서 투표 결과 텍스트를 {percentage}%{count}표로 변경
  • 투표 여부 확인 로직을 percentage > 0count > 0으로 수정

3. 애니메이션 로직 개선

  • 득표수를 기반으로 전체 투표수 대비 비율을 계산하는 getPercentage 함수 추가
  • 기존 퍼센트 기반 애니메이션을 득표수 기반으로 전환

4. 최고 득표 옵션 판별 로직 수정

  • 퍼센트 대신 득표수를 기준으로 최고 득표 옵션 판별
  • API 응답 데이터 변환 시 count 필드 매핑 및 최고 득표 계산 로직 추가

5. 투표 후 업데이트 로직 개선

  • 투표 API 호출 후 응답에서 받은 count 데이터를 상태에 반영
  • 득표수를 기준으로 최고 득표 옵션 재계산

Summary by CodeRabbit

  • 새로운 기능

    • 투표 결과가 퍼센트 대신 득표수(‘표’)로 표시됩니다.
    • 진행 바가 각 항목의 득표수를 바탕으로 퍼센트를 계산해 시각화합니다.
    • 총 투표수가 0인 경우도 자연스럽게 표시됩니다.
  • 버그 수정

    • 최고 득표 항목 판정이 퍼센트 기반에서 득표수 기반으로 정확해졌으며, 동률도 올바르게 처리됩니다.
    • 투표 여부 판단 로직이 득표수 기준으로 일관되게 동작합니다.

@ljh130334 ljh130334 self-assigned this Sep 16, 2025
@ljh130334 ljh130334 added the ✨ Feature 기능 개발 label Sep 16, 2025
@vercel
Copy link

vercel bot commented Sep 16, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Comments Updated (UTC)
thip Ready Ready Preview Comment Sep 16, 2025 0:55am

@coderabbitai
Copy link

coderabbitai bot commented Sep 16, 2025

Walkthrough

투표 로직과 UI를 퍼센트 기반에서 “득표 수(count)” 기반으로 전환. PollRecord 렌더링과 애니메이션이 count 중심으로 수정되고, Memory 변환 로직이 최대 득표 수로 isHighest를 재계산. 공용 타입(VoteItem, PollOption, VoteItemResult)에 count 필드가 추가됨.

Changes

Cohort / File(s) Change Summary
Poll UI 컴포넌트 업데이트
src/components/memory/RecordItem/PollRecord.tsx
퍼센트 의존 로직을 득표 수 기반으로 변경. hasVotes, isHighest 판정, totalVotes 누적, getPercentage(count) 추가. 바 차트/표시값을 count와 계산된 퍼센트로 렌더. 0표 처리 및 애니메이션 설명 갱신.
Memory 변환 로직
src/pages/memory/Memory.tsx
convertPostToRecord에서 poll 옵션별 count를 주입하고, 전체 중 maxCount를 계산하여 maxCount>0인 항목에 isHighest=true 설정.
공용 타입: 메모리
src/types/memory.ts
VoteItemPollOptioncount: number 필드 추가(필수). 기존 필드 변경 없음.
공용 타입: 레코드
src/types/record.ts
VoteItemResultcount: number 필드 추가(필수).

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant U as User
  participant PR as PollRecord (UI)
  participant API as Vote API
  participant M as Memory 변환 로직
  participant V as View (렌더)

  rect rgba(200,230,255,0.25)
    Note over U,PR: 투표 수행
    U->>PR: 옵션 선택 및 투표
    PR->>API: POST /vote (옵션 ID)
    API-->>PR: 응답 { count 들, isVoted 등 }
  end

  rect rgba(220,255,220,0.25)
    Note over PR,M: count 기반 데이터 업데이트
    PR->>M: voteItems with count
    M->>M: maxCount 계산 및 isHighest 재설정
    M-->>V: pollOptions(count 포함)
  end

  rect rgba(255,245,200,0.35)
    Note over V: 렌더링
    V->>V: totalVotes 합산, getPercentage(count)
    V-->>U: 바/라벨 표시 (count 및 퍼센트)
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related issues

Possibly related PRs

Suggested labels

🐞 BugFix

Suggested reviewers

  • heeeeyong

Poem

작은 발 퐁퐁, 토끼는 셈했죠
퍼센트 아닌 콩콩, 표 수를 셌죠
가장 높은 산? count로 고르자!
바는 꽉 차고, 숫자는 춤추네
삐약삐약 코드에, 오늘도 폴짝! 🐇✨

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed 제목 "fix: 기록장 투표 정보 퍼센트가 아닌 득표수로 표시되도록 수정"은 변경의 핵심인 "퍼센트 대신 득표수로 표시"를 명확하고 간결하게 요약합니다. 제공된 변경 요약과 타입/UI 수정(percentage → count, isHighest 판정 변경 등)을 정확히 반영하므로 PR의 주요 목적을 팀원이 빠르게 이해할 수 있습니다. 불필요한 상세 나열이나 모호한 표현 없이 목적 중심으로 작성되어 있습니다.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch hotfix/vote

Tip

👮 Agentic pre-merge checks are now available in preview!

Pro plan users can now enable pre-merge checks in their settings to enforce checklists before merging PRs.

  • Built-in checks – Quickly apply ready-made checks to enforce title conventions, require pull request descriptions that follow templates, validate linked issues for compliance, and more.
  • Custom agentic checks – Define your own rules using CodeRabbit’s advanced agentic capabilities to enforce organization-specific policies and workflows. For example, you can instruct CodeRabbit’s agent to verify that API documentation is updated whenever API schema files are modified in a PR. Note: Upto 5 custom checks are currently allowed during the preview period. Pricing for this feature will be announced in a few weeks.

Please see the documentation for more information.

Example:

reviews:
  pre_merge_checks:
    custom_checks:
      - name: "Undocumented Breaking Changes"
        mode: "warning"
        instructions: |
          Pass/fail criteria: All breaking changes to public APIs, CLI flags, environment variables, configuration keys, database schemas, or HTTP/GraphQL endpoints must be documented in the "Breaking Change" section of the PR description and in CHANGELOG.md. Exclude purely internal or private changes (e.g., code not exported from package entry points or explicitly marked as internal).

Please share your feedback with us on this Discord post.


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 and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (5)
src/types/memory.ts (2)

5-7: VoteItem에 count 추가는 적합. percentage 이중 출처 위험 주의(선택적 비권고 표시 제안)

퍼센트는 이제 화면에서 계산 가능하여 서버/클라이언트 간 불일치 소지가 있습니다. percentage를 비권고로 표시해 혼선을 줄이는 것을 제안합니다.

아래처럼 JSDoc 비권고 표시만 추가(동작 변화 없음):

 export interface VoteItem {
   voteItemId: number;
   itemName: string;
-  percentage: number;
+  /** @deprecated 화면에서는 count에서 파생 계산합니다. */
+  percentage: number;
   count: number;
   isVoted: boolean;
 }

86-90: PollOption에도 count 추가 OK. percentage는 선택적/파생 데이터로 관리 권장

렌더링은 count 중심이므로 percentage는 파생 데이터로 다루는 편이 안전합니다. 최소한 비권고 표기를 추가하거나(위 코멘트와 동일), 차후 마이그레이션에서 optional(percentage?: number)을 고려해주세요.

src/pages/memory/Memory.tsx (1)

34-45: maxCount를 map 내부에서 매번 계산 — 한 번만 계산하도록 리팩터 필요

동일 배열에 대해 Math.max를 매 항목마다 호출하고 있습니다. 성능/가독성 측면에서 사전에 1회 계산하고 재사용하세요. 또한 기본값은 || 대신 ?? 사용이 의도에 더 부합합니다.

적용 diff(선택 구간 내 변경):

-    pollOptions: post.voteItems.map((item) => {
-      const maxCount = Math.max(...post.voteItems.map(v => v.count || 0));
-      return {
+    pollOptions: post.voteItems.map((item) => {
+      return {
         id: item.voteItemId.toString(),
         text: item.itemName,
         percentage: item.percentage,
-        count: item.count || 0,
-        isHighest: (item.count || 0) === maxCount && maxCount > 0,
+        count: item.count ?? 0,
+        isHighest: (item.count ?? 0) === maxCount && maxCount > 0,
         voteItemId: item.voteItemId,
         isVoted: item.isVoted,
       };
     }),

선택 구간 밖에 추가해야 하는 보조 코드:

// return { ... } 직전에 1회 계산
const maxCount = Math.max(...post.voteItems.map(v => v.count ?? 0));
src/components/memory/RecordItem/PollRecord.tsx (2)

94-97: isHighest 계산에 매번 Math.max 호출 + 0표 동률 하이라이트 가능성

  • 각 옵션마다 Math.max를 재계산합니다.
  • 모든 항목이 0표일 때도 isHighest가 true가 될 수 있어(동률) 상태 일관성이 떨어집니다. UI에서는 hasVotes로 가려지지만, 상태 자체는 깔끔하게 유지하는 것이 좋습니다.

한 번만 최대값을 계산하고, 0 초과인 경우에만 최고표로 표시하도록 조정하세요.

적용 diff(선택 구간 내 변경):

-            return {
+            return {
               ...opt,
               percentage: updatedItem.percentage,
-              count: updatedItem.count,
+              count: updatedItem.count,
               isVoted: updatedItem.isVoted,
-              isHighest: updatedItem.count === Math.max(...response.data.voteItems.map(item => item.count))
+              isHighest: updatedItem.count > 0 && updatedItem.count === newMaxCount
             };

선택 구간 밖에 추가해야 하는 보조 코드(성공 분기 내, updatedOptions 계산 직전에):

const counts = response.data.voteItems?.map(item => item.count ?? 0) ?? [];
const newMaxCount = counts.length ? Math.max(...counts) : 0;

146-156: count 기반 애니메이션 계산 LGTM. 경계/캐싱 소폭 개선 제안

현재 구현은 명확합니다. 미세 개선으로:

  • getPercentage에서 결과를 Math.min(Math.max(value, 0), 100)로 클램프.
  • hasVotes/totalVotesuseMemo로 캐싱(옵션).
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Jira integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 201c98e and b715160.

📒 Files selected for processing (4)
  • src/components/memory/RecordItem/PollRecord.tsx (4 hunks)
  • src/pages/memory/Memory.tsx (1 hunks)
  • src/types/memory.ts (2 hunks)
  • src/types/record.ts (1 hunks)
🔇 Additional comments (3)
src/types/record.ts (1)

38-40: count 필드 추가 LGTM + 역호환 여부 확인 요청

UI/로직이 count 기반으로 이동한 것과 일치합니다. 백엔드 응답에서 항상 count가 내려오지 않을 가능성(구버전 API)이 있다면, 변환 단계에서 ?? 0으로 기본값을 보장하는지 최종 확인 부탁드립니다.

src/components/memory/RecordItem/PollRecord.tsx (2)

175-176: 퍼센트 채움 로직 전환 LGTM

getPercentage(option.count)로의 전환이 목적과 일치합니다.


190-191: 표시 형식 전환 확인 — LGTM

텍스트 퍼센트 표기는 {option.count}표로 변경되어 요구사항을 충족합니다.

확인된 항목(참고):

  • src/components/memory/RecordItem/PollRecord.tsx — PollPercentage가 {option.count}표로 출력됨 (확인됨).
  • src/components/memory/RecordItem/PollRecord.styled.ts — PollBarFill가 percentage prop을 받아 width: ${percentage}%로 사용(바 너비/애니메이션).
  • src/types/record.ts, src/types/memory.ts, src/pages/memory/Memory.tsx — percentage 필드/매핑 존재.

텍스트 렌더링 측면 문제 없음. percentage 값을 완전히 제거하려면 바 너비 계산과 타입/매핑도 함께 변경해야 합니다.

@ljh130334 ljh130334 merged commit aba2121 into develop Sep 16, 2025
3 checks passed
@ljh130334 ljh130334 deleted the hotfix/vote branch November 17, 2025 00:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

✨ Feature 기능 개발

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant