Implement OrganizationUnitRepository with CRUD and tree queries
epic-organizational-hierarchy-management-foundation-task-005 — Implement the OrganizationUnitRepository class that wraps Supabase client calls for: fetchUnit(id), fetchSubtree(unitId) via RPC, fetchChildren(unitId), createUnit, updateUnit, softDeleteUnit (sets deleted_at), and restoreUnit. Apply soft-delete filters on all reads. Handle typed Dart model conversion and error mapping to domain exceptions.
Acceptance Criteria
Technical Requirements
Execution Context
Tier 2 - 518 tasks
Can start after Tier 1 completes
Implementation Notes
Define OrganizationUnitRepository as an abstract class so BLoC and use-case code depends on the abstraction, not the Supabase implementation. This is essential for unit testing the BLoC layer without a real database. Use Riverpod's Provider or AsyncNotifierProvider to expose the repository — follow the existing provider pattern in the project. Error mapping: wrap all Supabase calls in try/catch, inspect the exception type (PostgrestException, SocketException, etc.) and rethrow as domain exceptions.
For soft-delete filter: use .filter('deleted_at', 'is', null) in Supabase queries — do not rely on a database view unless one already exists. For restoreUnit, use .update({'deleted_at': null}) — confirm Supabase Flutter SDK handles null updates correctly (it does as of supabase_flutter 2.x). The repository should not contain business logic (e.g., permission checks beyond what RLS enforces) — keep it a thin data access layer. Do not cache data in the repository; caching belongs in the BLoC or use-case layer if needed.
Testing Requirements
Write unit tests using flutter_test with a mock Supabase client (implement a FakeOrganizationUnitRepository conforming to the abstract interface). Test scenarios: (1) fetchUnit returns OrganizationUnit on success. (2) fetchUnit returns null when Supabase returns empty list. (3) fetchUnit throws OrganizationUnitNotFoundException when record is soft-deleted.
(4) fetchSubtree builds correct OrganizationUnitTree from flat RPC response. (5) createUnit returns created entity with server-assigned id. (6) softDeleteUnit succeeds and subsequent fetchUnit returns null. (7) Supabase network error maps to NetworkException.
(8) Supabase 403 maps to PermissionException. Write at least one integration test against a local Supabase instance that exercises the full round-trip: create → fetch → softDelete → confirm deleted. Use flutter_test for all tests.
Recursive CTE queries for large hierarchies (1,400+ nodes) may exceed Supabase query timeouts or produce unacceptably slow responses, degrading tree load time beyond the 1-second target.
Mitigation & Contingency
Mitigation: Implement Supabase RPC functions for subtree fetches rather than client-side recursive calls. Use materialized path or closure table as a supplemental index for depth-first traversal. Benchmark with realistic NHF data volumes during development.
Contingency: Fall back to a pre-computed flat unit list stored in the hierarchy cache with client-side tree reconstruction, trading freshness for speed. Add a background refresh job to keep the cache warm.
Concurrent writes from multiple admin sessions could cause cache staleness, leading to stale tree views and incorrect ancestor path computations that corrupt aggregation results.
Mitigation & Contingency
Mitigation: Use optimistic versioning on cache entries with a short TTL (5 minutes) as a safety net. Subscribe to Supabase Realtime on the organization_units table to push invalidation events to all connected clients.
Contingency: Provide a manual 'Refresh Hierarchy' action in the admin portal that forces a full cache bust, and display a staleness warning banner when the cache age exceeds the TTL.
Persisting the flat unit list to local storage may expose organization structure data if the device is compromised or the storage is not properly encrypted, violating data protection requirements.
Mitigation & Contingency
Mitigation: Use flutter_secure_storage (AES-256 backed by Keychain/Keystore) for the local unit list cache rather than SharedPreferences. Include only unit IDs, names, and types — no member PII.
Contingency: Disable local-storage persistence entirely and rely on in-memory cache only. Accept the trade-off of no offline hierarchy access for the security guarantee.