Author Supabase pre-aggregated stats views migration
epic-coordinator-statistics-dashboard-foundation-task-002 — Write the database migration that creates pre-aggregated Supabase views keyed by org_id + coordinator_id + month. Views must replace real-time aggregation of activity rows with sub-100ms indexed lookups. Include indexes on the composite key, period filtering columns, and activity_type columns. Sequence and test the migration against a staging Supabase instance.
Acceptance Criteria
Technical Requirements
Execution Context
Tier 1 - 540 tasks
Can start after Tier 0 completes
Implementation Notes
Use a standard PostgreSQL view (not materialised) initially — Supabase handles query planning well and a materialised view requires a refresh strategy that adds operational complexity. The view query should use DATE_TRUNC('month', occurred_at) to group by month. Use COALESCE for activity_count and total_duration_minutes to return 0 instead of NULL for missing months if a time series is needed. For the composite index, column order matters: put org_id first (highest cardinality filter), then coordinator_id, then activity_month.
Ensure the index is a B-tree index (default). If query latency exceeds 100ms after indexing, consider a materialised view with a pg_cron refresh job — document this as a follow-up task. The migration must be reviewed by the database lead before merging to main.
Testing Requirements
Manual testing on staging Supabase instance. Run EXPLAIN ANALYZE on target query patterns and capture output. Seed staging with synthetic activity data (minimum 3 coordinators, 2 orgs, 12 months each) using a seed SQL script committed alongside the migration. Verify RLS by connecting with a coordinator-role JWT and confirming only own-org rows are returned.
Verify idempotency by running the migration SQL twice and confirming no errors. Document all test results in the PR description. After migration is merged, run flutter integration tests that call the repository layer and assert returned data matches seeded values.
Pre-aggregated Supabase views may still be slow for orgs with very large activity datasets (NHF with 1,400 chapters). If the view query plan performs sequential scans, dashboard load times could exceed acceptable thresholds and degrade the perceived value of the feature.
Mitigation & Contingency
Mitigation: Design views with composite indexes on (org_id, coordinator_id, month) from the start. Run EXPLAIN ANALYZE during development against a seeded dataset of realistic scale. Add materialized view refresh strategy if needed.
Contingency: If live view performance is insufficient, convert to materialized views refreshed on a schedule or on activity-write triggers. Expose the refresh delay transparently in the UI with a 'last updated' timestamp.
Supabase RLS policies for the stats views may not be configured correctly during initial migration, potentially allowing cross-coordinator data leakage before the RoleAccessValidator layer is reached. This is a security and compliance risk.
Mitigation & Contingency
Mitigation: Write RLS integration tests as part of this epic that explicitly verify a coordinator JWT cannot read another coordinator's stats rows. Apply RLS policies in the migration script itself, not as a manual step.
Contingency: If an RLS gap is discovered post-deployment, immediately disable the stats screen via a feature flag, apply the corrected RLS migration, and re-enable after verification. Log and audit all queries that ran during the gap window.
Cache invalidation logic may not be triggered correctly when a new activity is registered by a peer mentor or when an expense approval is granted. Stale data could cause coordinators to make decisions based on outdated KPIs, undermining trust in the dashboard.
Mitigation & Contingency
Mitigation: Define explicit invalidation event contracts with the activity registration and expense approval pipelines. Implement an event bus subscription within StatsCacheManager. Document the invalidation contract in code.
Contingency: If event-driven invalidation proves unreliable, add a manual 'Refresh' pull-to-refresh gesture on the dashboard and reduce TTL to 5 minutes as a fallback degradation strategy.