Invitation backend service and email dispatch
epic-admin-portal-user-management-task-010 — Implement backend logic for sending user invitations by email with role pre-assignment. Create the invitation record in the database, generate a secure invitation token, trigger the email dispatch via Supabase Edge Function or email provider, and validate that the inviting admin has permission to assign the selected role.
Acceptance Criteria
Technical Requirements
Execution Context
Tier 3 - 413 tasks
Can start after Tier 2 completes
Implementation Notes
Use Supabase's built-in `auth.admin.inviteUserByEmail()` if it supports role pre-assignment metadata; otherwise, implement a custom edge function that calls Supabase Auth's invite endpoint and separately writes the invitation metadata (role, org) to `user_invitations`. The acceptance flow (when the invitee clicks the email link) must read the pre-assigned role from `user_invitations` and apply it at the moment of account creation — store role_id in the invitation row, not in the email link itself. For token storage, store only the hash (SHA-256 or bcrypt) in the DB and send the raw token in the email; this prevents token leakage via DB access. Add a Supabase scheduled function or a DB trigger with pg_cron to mark expired invitations as 'expired' (cron every hour) to keep the table clean.
Document the edge function's environment variables (SMTP credentials, FROM address) in the project's .env.example.
Testing Requirements
Unit tests (Deno): (1) token generation produces unique 32-byte URL-safe strings; (2) role permission check rejects higher-than-admin roles; (3) duplicate detection returns correct HTTP status. Integration tests against a local Supabase instance: (1) full happy path — invite → DB row created → email dispatched; (2) duplicate invite replaces old token; (3) expired token rejected on acceptance; (4) RLS prevents non-admin reads. Use Supabase's local dev environment (`supabase start`) for integration tests. Verify email template renders correctly with the invitation link.
No flutter_test needed for this task — pure backend.
Displaying NHF users with membership in up to 5 local chapters in a flat list view without duplicating entries requires a non-trivial aggregation query. Incorrect query design could result in duplicated user rows or missing chapter affiliations, confusing admins and causing incorrect role assignments.
Mitigation & Contingency
Mitigation: Design the user list query to GROUP BY user_id and aggregate chapter affiliations as an array field. Use AdminRepository's typed models to surface this aggregated structure to the UI. Validate with a test dataset containing users in 5 chapters.
Contingency: If aggregation query complexity proves too high for real-time filtering, implement a separate multi-chapter affiliation fetch triggered only when a specific user row is expanded, reducing query complexity for the base list.
Composable multi-dimensional filters (role + chapter + status + certification state) applied server-side against an org with 2,000+ users may produce slow queries, particularly when filtering by certification state requires joining an additional table.
Mitigation & Contingency
Mitigation: Ensure the relevant filter columns (role, status, chapter_id, certification_expiry) are indexed in Supabase. Use cursor-based pagination rather than OFFSET to maintain consistent performance at high page numbers. Profile filter query combinations against a large dataset during development.
Contingency: If multi-filter performance degrades in production, introduce a denormalised search index table updated on user status changes, allowing the list query to filter from a single table.
Deactivating a user account that has ongoing activity assignments, open expense claims, or active chapter affiliations may leave orphaned records or break downstream workflows if the deactivation does not trigger correct cascade handling.
Mitigation & Contingency
Mitigation: Define and document the expected state of each dependent record type on user deactivation before implementing the toggle. Implement deactivation as a UserManagementService operation that checks for and warns about open dependencies before persisting. Write integration tests covering each dependency type.
Contingency: If orphaned record issues are discovered post-launch, provide an admin-accessible reconciliation view that surfaces users with inconsistent dependency states and allows manual resolution without requiring a code deploy.