Implement N+1-safe cross-chapter JOIN query
epic-multi-chapter-membership-handling-data-layer-task-005 — Implement the Supabase-backed CrossChapterActivityQuery. Issue a single SQL query that JOINs contact_chapters to the activities table on chapter_id, filtered by contact_id. Order results by activity date descending. Parse the flat result set into a typed list of CrossChapterActivityResult objects. The implementation must not issue per-chapter sub-queries. Respect RLS so only activities in chapters accessible to the authenticated user are returned.
Acceptance Criteria
Technical Requirements
Execution Context
Tier 2 - 518 tasks
Can start after Tier 1 completes
Implementation Notes
PostgREST foreign key embedding syntax for a join: supabase.from('contact_chapters').select('chapter_id, chapters(name), activities(id, activity_type, activity_date, duration_minutes, summary, is_billable)').eq('contact_id', contactId).order('activity_date', referencedTable: 'activities', ascending: false). Note that PostgREST returns a nested JSON structure; you will need to flatten it: for each contact_chapter row, extract chapter_id and chapters.name, then iterate the embedded activities array. This is still a single HTTP call. Alternatively, use a Supabase RPC (stored procedure) for more control over the SQL.
The RPC approach is preferable if the join involves more than 2 levels of nesting or if you need DISTINCT ON for deduplication. Create the RPC in a migration file and call it via supabase.rpc('get_cross_chapter_activities', params: {'p_contact_id': contactId}). Ensure the function is defined with SECURITY INVOKER (not DEFINER) so it runs under the caller's RLS context.
Testing Requirements
Write unit tests using a mocked SupabaseClient: (1) mock a successful response with 3 activities across 2 chapters and verify the result list contains 3 CrossChapterActivityResult objects with correct chapterName values; (2) mock an empty response and verify an empty list is returned; (3) mock a PostgrestException and verify ActivityQueryException is thrown. Write integration tests against a local Supabase instance: seed contact_chapters with 3 chapter affiliations, seed activities for each chapter, call fetchActivitiesForContact, and assert all activities are returned in date-descending order; verify that activities from a 4th chapter (not affiliated) are not returned. Use flutter_test for all tests.
The Cross-Chapter Activity Query must avoid N+1 fetches across chapters. If naively implemented as a per-chapter loop, it will cause severe performance degradation for contacts affiliated with 5 chapters on poor mobile connections.
Mitigation & Contingency
Mitigation: Design the query as a single PostgREST join of contact_chapters and activities on contact_id from the start. Add a query performance test with 5 affiliations and 100+ activities to the integration test suite and enforce a maximum execution time threshold.
Contingency: If a performance regression is detected post-merge, introduce a Supabase RPC function (stored procedure) to move the join server-side, bypassing any client-side N+1 pattern.
If the Duplicate Warning Event Logger write fails silently (network error, RLS denial), audit entries will be missing from the Bufdir compliance record without the user being aware.
Mitigation & Contingency
Mitigation: Implement the logger with a local fallback queue: if the Supabase write fails, persist the event locally and retry on next launch. Log all failures to a verbose output channel.
Contingency: Add a reconciliation job that compares locally queued events to Supabase entries and re-submits any gaps. Provide a data export of the local queue for manual audit if reconciliation fails.
Two coordinators simultaneously adding the 5th chapter affiliation for the same contact could bypass the maximum enforcement check if both reads occur before either write completes.
Mitigation & Contingency
Mitigation: Enforce the 5-affiliation maximum as a database-level constraint (CHECK + trigger or RPC with a FOR UPDATE lock) rather than relying solely on application-layer validation.
Contingency: If a constraint violation is detected in production, run a corrective query to end the most recently created excess affiliation and notify the relevant coordinator.