Implement OrgFieldConfigLoader from Supabase
epic-structured-post-session-report-foundation-task-005 — Implement OrgFieldConfigLoader that fetches per-organisation field configuration records from the org_field_configs Supabase table. Parse the JSONB config column into typed FieldConfig objects specifying field_key, field_type (text, number, boolean, select, date), label, required, visible, validation_rules, and options list. Cache results using ReportSchemaCache. Support forced refresh and graceful fallback to defaults when config is absent.
Acceptance Criteria
Technical Requirements
Execution Context
Tier 1 - 540 tasks
Can start after Tier 0 completes
Implementation Notes
Use .maybeSingle() rather than .single() when querying by org_id + feature_key, because the fallback path requires distinguishing 'no row found' from an error — .single() throws on zero rows while .maybeSingle() returns null. Parse the JSONB config column by calling jsonDecode on the returned string (Supabase Dart client may return it as a Map already — verify at runtime). Define the default fallback schema as a static const or static final on the class so it is clearly documented and easily updatable. Use the FieldConfig and FieldConfigSchema types defined in task-004's shared types file.
Document clearly that OrgFieldConfigLoader is scoped per feature_key — callers must pass 'post_session_report' as the featureKey when loading report field configs.
Testing Requirements
Write unit tests using flutter_test with mocked SupabaseClient and a real (non-mocked) ReportSchemaCache. Test: (1) cache hit returns cached schema without calling Supabase, (2) cache miss triggers Supabase query and caches result, (3) forceRefresh=true bypasses cache and re-fetches, (4) Supabase returns no rows → default fallback schema returned, (5) Supabase throws PostgrestException → OrgFieldConfigLoaderException thrown, (6) parsed schema fields are sorted by displayOrder, (7) missing optional JSON fields use safe defaults, (8) unknown FieldType value is skipped with warning and remaining fields still returned, (9) returned FieldConfigSchema.orgId matches the queried orgId. Write an integration test (if local Supabase available) that fetches seeded config and verifies round-trip JSON parsing.
Supabase RLS policies for multi-org report access may be more complex than anticipated — coordinators need cross-peer-mentor access within their org but not across orgs, and draft reports should be invisible to coordinators until submitted. Misconfigured RLS could expose sensitive health data or block legitimate access.
Mitigation & Contingency
Mitigation: Define and test RLS policies in isolation before writing repository code. Create a dedicated SQL migration file with policy definitions and an automated integration test suite that verifies each role's access boundaries using real Supabase auth tokens.
Contingency: If RLS proves too complex to express declaratively, implement application-level access control in the repository layer with explicit org and role checks, and add a security audit task before the feature goes to production.
The org field config JSON stored in Supabase may lack a stable, versioned schema contract. If different organisations have drifted to different field-definition formats, org-field-config-loader will fail silently or crash, breaking form rendering for those orgs.
Mitigation & Contingency
Mitigation: Define a canonical JSON Schema for field config and validate all existing org configs against it before implementation begins. Store a schema version field in every config record and handle version migrations explicitly in the loader.
Contingency: If existing configs are too heterogeneous, implement a config normalisation pass in org-field-config-loader that coerces known variants to the canonical format, logging warnings for fields that cannot be normalised so operations can fix them in the admin console.
TTL-based schema cache invalidation may cause peer mentors to use stale field definitions for up to the TTL window after an admin updates the org config, potentially collecting data against outdated field structures.
Mitigation & Contingency
Mitigation: Set a conservative TTL (e.g. 15 minutes) and expose a manual cache-bust mechanism triggered on app foreground-resume. Document the maximum staleness window in the admin console so org admins know to plan config changes outside active reporting windows.
Contingency: If stale schema causes a data quality incident, add a Supabase Realtime subscription to the org config table that invalidates the cache immediately on any config update.