Skip to content

fix(analytics): uniqueViewers now uses COUNT(DISTINCT viewer_id) instead of inflated groupBy#449

Open
Srejoye wants to merge 1 commit into
Dev-Card:mainfrom
Srejoye:fix/analytics-unique-viewers-distinct-count
Open

fix(analytics): uniqueViewers now uses COUNT(DISTINCT viewer_id) instead of inflated groupBy#449
Srejoye wants to merge 1 commit into
Dev-Card:mainfrom
Srejoye:fix/analytics-unique-viewers-distinct-count

Conversation

@Srejoye
Copy link
Copy Markdown
Contributor

@Srejoye Srejoye commented Jun 1, 2026

Summary

Fixes #436

The uniqueViewers field in GET /api/analytics/overview was computed using groupBy(['viewerId', 'viewerIp']), which groups on a composite key. A single authenticated viewer visiting from two different IPs produced two group rows and was counted as two unique viewers. Anonymous visitors (viewerId = null) with different IPs each added separate rows, causing severe overcounting on public profiles.

Changes

  • Replace the cardView.groupBy workaround with a $queryRaw executing COUNT(DISTINCT viewer_id) — the correct SQL the code comment itself described but did not implement
  • Anonymous views (viewer_id IS NULL) are explicitly excluded from the distinct count; they represent unidentifiable sessions and cannot be meaningfully deduplicated
  • BigInt returned by $queryRaw is cast to Number before returning

Testing

  • Seed one authenticated viewer with 5 views across 3 distinct IPs → uniqueViewers must equal 1
  • Seed 3 anonymous views from 3 distinct IPs → must not inflate the count
  • Seed 3 distinct authenticated viewers → uniqueViewers must equal 3
  • Verified existing analytics tests pass with updated assertions

Notes

If tracking anonymous unique visitors becomes a requirement in future, a separate uniqueAnonymousVisitors field using COUNT(DISTINCT viewer_ip) can be added with explicit documentation of its limitations.

@Harxhit Harxhit added the gssoc:approved Required label for every approved PR. Gives the base +50 points and enables contribution tracking. label Jun 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gssoc:approved Required label for every approved PR. Gives the base +50 points and enables contribution tracking.

Projects

None yet

2 participants