Author Supabase SQL views for activity aggregation
epic-activity-statistics-dashboard-data-foundation-task-004 — Write the Supabase SQL views that pre-aggregate activity data: (1) peer_mentor_stats_view — activity count, total hours, and reimbursement amount grouped by peer_mentor_id and chapter_id; (2) chapter_stats_view — same metrics rolled up to chapter level. SQL must use the identical aggregation logic as the Bufdir export pipeline (same rounding, same category mapping) to ensure zero reconciliation delta. Include migration file with up/down scripts.
Acceptance Criteria
Technical Requirements
Execution Context
Tier 1 - 540 tasks
Can start after Tier 0 completes
Implementation Notes
Locate migration files in supabase/migrations/ following the existing naming convention. Before writing the SQL, extract and review the exact aggregation logic from the Bufdir export pipeline (likely in a Supabase Edge Function or existing SQL file) — do not replicate from memory. Key areas of divergence to watch: (a) rounding — use ROUND(value::numeric, 2) not TRUNC; (b) category exclusions — some activity categories may be excluded from Bufdir totals; (c) reimbursement rates — may vary by organisation or activity type and reference a lookup table. Use CREATE OR REPLACE VIEW (not CREATE VIEW) so the migration is re-runnable.
Column aliases must exactly match the snake_case field names in the Dart PeerMentorStatRow and StatsSnapshot models from task-001 to eliminate any mapping layer. Add inline SQL comments explaining each aggregation formula and its Bufdir reference.
Testing Requirements
SQL-level regression tests using pgTAP (if available on Supabase) or a seed-data script: (1) insert a known set of activities (e.g., 10 activities for peer mentor A across 2 chapters, with known hours and reimbursement amounts) and assert view output matches hand-calculated expected values; (2) insert an activity outside the date-range filter and assert it is excluded from aggregated totals; (3) run the same dataset through the Bufdir export query and assert zero delta on all numeric columns; (4) verify that a SELECT by the anon role is denied (permission error). Run migration up/down/up in CI to confirm idempotency.
Materialized views over large activity tables may have refresh latency exceeding the 2-second SLA under high insert load, causing stale data to appear on the dashboard immediately after a peer mentor registers an activity.
Mitigation & Contingency
Mitigation: Design the materialized view refresh trigger to run asynchronously via a Supabase Edge Function rather than a synchronous trigger, and set a maximum staleness tolerance of 5 seconds documented in the feature spec. Add a CONCURRENTLY refresh strategy so reads are never blocked.
Contingency: If refresh latency cannot meet SLA, fall back to a regular (non-materialized) view for the dashboard and accept slightly higher query cost per request. Revisit materialized approach once Supabase pg_cron or background workers are available.
The aggregation counting rules for the dashboard may diverge from those used in the Bufdir export pipeline (e.g., which activity types count, how duplicate registrations are handled), creating a reconciliation burden for coordinators at reporting time.
Mitigation & Contingency
Mitigation: Run the BufDir Alignment Validator against a shared reference dataset before any view is merged to main. Encode the counting rules as a shared Supabase function called by both the stats views and the export query builder so there is a single source of truth.
Contingency: If divergence is discovered post-launch, ship a visible banner on the dashboard stating that numbers are indicative and may differ from the export until the reconciliation fix is deployed. Prioritize the fix as a P0 defect.
Multi-chapter coordinators (up to 5 chapters per NHF requirement) require RLS policies that filter on an array of chapter IDs, which is more complex than single-value RLS and could be misconfigured, leaking data across chapters or blocking legitimate access.
Mitigation & Contingency
Mitigation: Write integration tests that verify cross-chapter isolation for a coordinator assigned to chapters A and B cannot see data from chapter C. Use parameterized RLS policies with auth.uid()-based chapter lookup to avoid hardcoded values.
Contingency: If RLS misconfiguration is detected in testing, temporarily restrict coordinator queries to single-chapter scope (coordinator's primary chapter) and ship multi-chapter support as a fast-follow patch once RLS logic is verified.