critical priority medium complexity backend pending backend specialist Tier 3

Acceptance Criteria

A Supabase database trigger (or Edge Function webhook) fires on INSERT/UPDATE to the peer mentor status table whenever status transitions to 'paused', 'expired_cert', or 'reinstated'
On 'paused' transition: a removeMentor sync operation is enqueued for the affected mentor
On 'expired_cert' transition: a removeMentor sync operation is enqueued for the affected mentor
On 'reinstated' transition with a valid current certification: a restoreMentor sync operation is enqueued
On 'reinstated' transition with no valid certification: no restoreMentor is enqueued; a warning log entry is created instead
The trigger only fires for mentors belonging to the HLF organisation (organisation_id check); no sync is triggered for NHF or Blindeforbundet mentors
Sync operations are enqueued as records in a dedicated sync_queue table (mentor_id, operation, status: pending/processing/done/failed, created_at, attempts) to decouple the trigger from the actual API call
No sync operation is enqueued if an identical pending operation already exists in the queue for the same mentor (idempotency guard)
A queue processor (Edge Function invoked on schedule or via pg_cron) dequeues pending operations and calls HLFWebsiteSyncService
Manual status changes made by coordinators through the admin interface also fire the trigger (same code path)

Technical Requirements

frameworks
Supabase Edge Functions (Deno)
Supabase PostgreSQL triggers or pg_net webhooks
BLoC (coordinator UI state reflecting sync status)
apis
Supabase Database Webhooks or pg_cron for queue processing
HLFWebsiteSyncService Edge Function (task-006)
Supabase Realtime (optional: broadcast sync queue status to coordinator UI)
data models
assignment
certification
performance requirements
Trigger-to-enqueue latency must be under 500ms
Queue processor must process each pending operation within 30 seconds of becoming eligible
Queue table must have indexes on (status, created_at) for efficient dequeue queries
security requirements
Database trigger runs with SECURITY DEFINER and restricted to service role — not callable by mobile clients
Organisation ID check in trigger prevents cross-tenant sync operations
Sync queue table subject to RLS: only service role can insert/update sync_queue rows

Execution Context

Execution Tier
Tier 3

Tier 3 - 413 tasks

Can start after Tier 2 completes

Implementation Notes

Prefer a Supabase database trigger over application-level event hooks for reliability — database triggers fire even if the Flutter app is offline or the backend service restarts. Use a sync_queue table as an outbox pattern (transactional outbox) to ensure the enqueue operation is atomic with the status update. The queue processor Edge Function should use SELECT ... FOR UPDATE SKIP LOCKED for concurrent-safe dequeue.

When checking 'reinstated' certification validity, query the certification table for the mentor's most recent cert with expires_at > NOW() — do not rely on the status field alone. Consider adding a triggered_by_event column to the sync_queue for traceability (e.g., 'status_change', 'manual_coordinator_action').

Testing Requirements

Unit tests: mock the status repository and assert that correct sync operations are enqueued for each status transition scenario (paused → remove, expired_cert → remove, reinstated+valid_cert → restore, reinstated+no_cert → no-op with warning). Integration tests against Supabase test instance: insert a mentor status row, assert sync_queue row is created with correct operation type; update status to reinstated, assert restore operation enqueued; verify idempotency guard prevents duplicate queue entries. Test the HLF-only filter: update an NHF mentor status and assert no sync_queue row is created.

Component
HLF Website Sync Service
service high
Epic Risks (4)
high impact medium prob technical

The nightly expiry checker may run multiple times due to scheduler retries or infrastructure issues, causing duplicate auto-transitions and duplicate coordinator notifications that erode trust in the notification system.

Mitigation & Contingency

Mitigation: Implement idempotency via a unique constraint on (mentor_id, threshold_day, certification_expiry_date) in the cert_expiry_reminders table. Auto-transitions should be wrapped in a Postgres RPC that checks current status before applying, making repeated invocations safe.

Contingency: Add a compensation query in the reconciliation log that detects duplicate log entries for the same certification period and alerts the operations team for manual review within 24 hours.

high impact medium prob integration

The HLF Dynamics portal API may have eventual-consistency behaviour or rate limits that cause website listing updates to lag behind status changes, leaving expired mentors visible on the public website for an unacceptable window.

Mitigation & Contingency

Mitigation: Design the sync service to be triggered immediately on status transitions (event-driven via database webhook) in addition to the nightly batch run. Implement a reconciliation job that verifies sync state against app state and re-triggers any divergent records.

Contingency: If real-time sync cannot be guaranteed, implement a manual 'force sync' action in the coordinator dashboard so coordinators can trigger an immediate re-sync for urgent cases. Document the expected sync lag in coordinator onboarding materials.

medium impact medium prob scope

Stakeholder requests to extend the expiry checker to handle additional certification types, grace periods, or organisation-specific threshold configurations may significantly increase scope beyond what is designed here, delaying delivery.

Mitigation & Contingency

Mitigation: Parameterise threshold day values (30, 14, 7) via configuration repository rather than hard-coding them, enabling per-organisation customisation without code changes. Document that grace period logic and additional cert types are out of scope for this epic and require a dedicated follow-up.

Contingency: Deliver the feature with hard-coded HLF-standard thresholds first and introduce the configuration repository as a follow-up task in the next sprint, using a feature flag to enable per-org threshold overrides.

high impact low prob security

Dynamics portal API credentials stored as environment secrets in Supabase Edge Function configuration may be rotated or invalidated by HLF IT without notice, causing silent sync failures that go undetected for multiple days.

Mitigation & Contingency

Mitigation: Implement credential health-check calls on each scheduler run and emit an immediate alert on auth failure rather than only alerting after N consecutive failures. Document the credential rotation procedure with HLF IT and establish a rotation notification protocol.

Contingency: Maintain a break-glass manual sync script accessible to HLF administrators that can re-execute the Dynamics sync with newly provided credentials while the automated system is restored.