Implement Supabase queries for annual stats aggregation
epic-annual-impact-summary-core-services-task-004 — Write the Supabase RPC calls and PostgREST queries that retrieve activity records filtered by peer mentor user ID and a rolling date window. Queries must compute total session hours, count distinct contacts helped, and return per-activity-type counts. Include proper RLS policy compliance and ensure queries work against both online Supabase and can be adapted for offline cache reads.
Acceptance Criteria
Technical Requirements
Execution Context
Tier 2 - 518 tasks
Can start after Tier 1 completes
Implementation Notes
Write the SQL function in a migration file under supabase/migrations/ so it is version-controlled and reproducible. Use LANGUAGE plpgsql for the function body to allow the auth.uid() guard check before the main query. The Dart repository class (AnnualStatsRepository) should accept a SupabaseClient via constructor injection — this makes it straightforward to substitute a mock client in unit tests. Define AnnualStatsException as a sealed class with a reason enum (networkError, authError, parseError, unexpectedError) and an optional message field — this gives BLoC/Riverpod consumers a clean error discrimination surface without importing Supabase types.
Cache the raw Map response (not the parsed model) so the offline cache layer (task-006) can store and replay it without needing to re-serialise the domain model.
Testing Requirements
Two test layers: (1) Unit tests — mock the Supabase client using a fake implementation; test that fetchAnnualStats passes correct parameters to supabase.rpc(); test that a successful response is deserialised to Map
Activity records may contain duplicate entries (as evidenced by the duplicate-detection feature dependency) or proxy-registered activities that should be attributed differently. Including duplicates or mis-attributed records would produce inflated stats, undermining trust in the summary.
Mitigation & Contingency
Mitigation: Implement the aggregation query to join against the deduplication-reviewed-flag on activity records and filter out unresolved duplicates. Coordinate with the duplicate-detection feature team to confirm the authoritative flag field before implementing the RPC. Include a data-quality warning in the summary when unresolved duplicates are detected.
Contingency: If deduplication state is unreliable at release time, add a prominent disclaimer in the summary UI noting that figures reflect all registered activities and may include duplicates pending review. Track a follow-up task to re-aggregate after deduplication runs.
Each organisation wants to define their own milestone thresholds (e.g., NHF's counting model differs from HLF's certification model). Implementing configurable thresholds may expand scope significantly if the configuration UI is expected in this epic.
Mitigation & Contingency
Mitigation: Scope this epic strictly to the evaluation engine and a hardcoded default threshold set. Define the MilestoneDefinition interface with an organisation_id discriminator so per-org configs can be loaded from the database in a later sprint. Build the admin configuration UI as a separate follow-on task outside this epic.
Contingency: If stakeholders require per-org milestone configuration before launch, deliver a JSON-based configuration file per org as an interim solution, loaded from Supabase storage, until a full admin UI is built.
Android 13+ restricts access to media collections and requires READ_MEDIA_IMAGES permission for gallery saves, while older Android versions use WRITE_EXTERNAL_STORAGE. Handling both permission models correctly across the device matrix is error-prone.
Mitigation & Contingency
Mitigation: Use the permission_handler Flutter package with version-aware permission requests abstracted behind the summary-share-service interface. Write platform-specific unit tests for both Android API levels in the test harness. Test on a minimum of three Android versions (API 29, 32, 34) in CI.
Contingency: If gallery save is broken on specific Android versions at launch, disable the 'Save to gallery' option on affected API levels and surface only clipboard and system share sheet, which require no media permissions.