Skip to content

fix: 投票率分母改用名冊人數而非已投票人數 - #57

Merged
l7wei merged 1 commit into
NTHU-SA:mainfrom
ChiuKuanHsun:fix/turnout-rate-denominator
Aug 31, 2026
Merged

l7wei merged 1 commit into
NTHU-SA:mainfrom
ChiuKuanHsun:fix/turnout-rate-denominator

Conversation

@ChiuKuanHsun

@ChiuKuanHsun ChiuKuanHsun commented Aug 30, 2026 •

Copy link
Copy Markdown
Member

問題

lib/statisticsService.ts 計算投票率時,分母用的是 activity.users.length:

const totalEligibleVoters = activity.users.length;

但 activity.users 存的是已投票的學號清單(votingService.ts 投票成功後 $addToSet 進去的),也就是分子本身。結果:

  • 投票率 turnoutRate 恆為 100%
  • 後台結果頁的「合格選民數」顯示成已投票人數

本地實測(名冊 5 人、投出 1 票)修正前的 /api/stats 回應:

{ "totalVotes": 1, "totalEligibleVoters": 1, "turnoutRate": "100.00" }

修正

改用 activity.eligible_voters_count —— 上傳選舉人名冊 CSV 時寫入的名冊人數。

同樣情境修正後:

{ "totalVotes": 1, "totalEligibleVoters": 5, "turnoutRate": "20.00" }

沒上傳過名冊的活動 eligible_voters_count 為 0,既有的 totalEligibleVoters > 0 保護會讓投票率維持 "0",不會除以零。

測試

新增 __tests__/statisticsService.test.ts,涵蓋四種情況:

  • 投票率以名冊人數為分母(5 票 / 500 人 = 1.00%)
  • 未上傳名冊時投票率為 0,不除以零
  • choose_one 逐選項計票
  • 活動不存在回傳 404

已確認這些測試在還原修正後會失敗(2 項),確實能擋住回歸。

npm run lint、npm run type-check、npm test(64 tests)皆通過。

影響範圍

只改後端統計計算,/api/stats 的回應結構不變,前端不需要調整。唯一的行為差異是投票率與合格選民數會顯示成正確的值。

calculateActivityStatistics 原本用 activity.users.length 當投票率的
分母,但該欄位存的是「已投票的學號清單」,等同於分子,導致投票率
恆為 100%、「合格選民數」顯示成已投票人數。

改用 activity.eligible_voters_count(上傳選舉人名冊 CSV 時寫入的
名冊人數),與後台結果頁「合格選民數」的語意一致。未上傳過名冊的
活動該欄位為 0,既有的除以零保護會讓投票率維持 "0"。

新增 __tests__/statisticsService.test.ts 涵蓋投票率計算、無名冊、
choose_one 計票與活動不存在四種情況。
@sonarqubecloud

Copy link
Copy Markdown

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

修正後端統計計算中投票率分母誤用「已投票名單」導致投票率恆為 100% 的問題,改以活動的名冊人數欄位計算,並補上單元測試防止回歸。

Changes:

  • /api/stats 相關統計計算:投票率分母改用 eligible_voters_count(名冊人數)而非 users.length(已投票人數)。
  • 新增 statisticsService 單元測試,覆蓋名冊分母、無名冊除以零保護、choose_one 計票與活動不存在回傳 404。

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.

File Description
lib/statisticsService.ts 修正投票率/合格選民數計算基準,改用名冊人數欄位。
tests/statisticsService.test.ts 新增統計服務測試,涵蓋分母修正與回歸保護。

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread lib/statisticsService.ts
type: string;
rule: string;
users: string[];
eligible_voters_count: number;
@l7wei

l7wei commented Aug 31, 2026

Copy link
Copy Markdown
Member

Hi @ChiuKuanHsun ,
Thanks for your 1st PR for Voting-System, merged.

@l7wei
l7wei merged commit 0ce12cb into NTHU-SA:main Aug 31, 2026
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants