critical priority low complexity backend pending backend specialist Tier 0

Acceptance Criteria

`TenantContext` is an immutable model with fields: orgId (String), orgName (String), brandingTokens (BrandingTokens), featureFlags (Map<String, bool>), terminologyLabels (Map<String, String>), status (TenantContextStatus enum: loading/ready/error/empty)
`BrandingTokens` model contains: primaryColor (Color), logoAssetPath (String?), fontVariant (String?)
`TenantContextStatus` enum has values: `empty`, `loading`, `ready`, `error`
Abstract `TenantContextService` exposes: `Future<void> load(String orgId)`, `void clear()`, `Future<void> refresh()`, and a read-only `TenantContext get currentContext`
Riverpod provider is declared as `StateNotifierProvider<TenantContextNotifier, TenantContext>` — the notifier shape is defined even if the implementation is a stub
All models use `copyWith` pattern for immutable updates
Initial/empty `TenantContext` factory is provided: `TenantContext.empty()` returns a valid object with status `empty` and safe defaults
File structure places interface and models in domain layer, separate from any Supabase or UI code
Dart analyzer reports zero errors and zero warnings

Technical Requirements

frameworks
Flutter
Riverpod
data models
TenantContext
BrandingTokens
TenantContextStatus
TenantContextService
performance requirements
TenantContext model must support efficient copyWith — no deep cloning of large structures
StateNotifier state updates must be minimal — only changed fields trigger rebuilds
security requirements
Feature flags map must not expose internal permission keys to UI layer directly — expose typed accessors
TenantContext must not store auth credentials or session tokens

Execution Context

Execution Tier
Tier 0

Tier 0 - 440 tasks

Implementation Notes

Use `Color` from Flutter's `dart:ui` (or `material.dart`) for `primaryColor` in BrandingTokens — avoid raw int hex values to prevent inconsistency. The `terminologyLabels` map is intentionally untyped (`Map`) at the model level because label keys are organization-defined — type safety is enforced at the widget layer by `TerminologyAwareTextWidget` which uses known key constants. Define label key constants (e.g., `LabelKeys.peerMentor`) in a separate constants file so consumers don't use raw string keys. The `featureFlags` map should similarly have a `FeatureFlags` accessor class that wraps the raw map and provides named boolean getters (e.g., `flags.hasGamification`).

This avoids typo-prone string lookups throughout the app.

Testing Requirements

Unit tests with `flutter_test`: (1) `TenantContext.empty()` returns object with status `empty` and non-null safe defaults for all fields, (2) `copyWith` on TenantContext correctly updates individual fields while preserving others, (3) BrandingTokens equality — two instances with identical values are equal, (4) TenantContextStatus serialization — each enum value roundtrips through `toString()` and fromString parsing, (5) a stub `TenantContextNotifier` can be constructed and its initial state is `TenantContext.empty()`. Aim for 100% model-layer coverage.

Component
Tenant Context Service
service high
Epic Risks (4)
high impact medium prob technical

TenantContextService must invalidate all downstream Riverpod providers when the org context changes (org switch scenario). If any provider caches org-specific data without subscribing to the tenant context, it will serve stale data from the previous org after a switch — which is both a UX failure and a potential GDPR violation.

Mitigation & Contingency

Mitigation: Define a single TenantContextProvider at the root of the Riverpod provider graph that all org-scoped providers depend on via ref.watch(). When TenantContextService.seedContext() runs, it invalidates TenantContextProvider which cascades invalidation to all dependents. Document this pattern in an architectural decision record so all developers follow it.

Contingency: Implement a post-switch integrity check that re-fetches a sample of each major data entity type and confirms the returned org_id matches the newly selected context; surface a reload prompt if any mismatch is detected.

medium impact medium prob security

MultiOrgMembershipResolver must query role assignments across potentially multiple tenant schemas. The anon or authenticated Supabase RLS policy may not permit cross-schema queries, making it impossible to return the full list of orgs a user belongs to in a single call.

Mitigation & Contingency

Mitigation: Design the membership query to use a dedicated Supabase edge function or a shared public schema view that aggregates role assignments across tenant schemas with a service-role key, returning only the org IDs the calling user is permitted to see. This keeps the client read-only.

Contingency: If cross-schema queries cannot be made safely, fall back to a per-org sequential membership check using the list of known org IDs and coalesce results client-side with appropriate timeout handling.

medium impact low prob technical

go_router redirect guards behave differently on web vs. mobile for deep links and browser back-button navigation. If the app is later deployed as a Progressive Web App (PWA) for admin use, the OrgRouteGuard may loop or fail to apply correctly on browser navigation events.

Mitigation & Contingency

Mitigation: Implement the guard as a GoRouter.redirect callback (not a ShellRoute redirect) following go_router best practices for platform-agnostic guards. Write widget tests that simulate navigation with and without auth/org context on both mobile and web target platforms in CI.

Contingency: If web-specific guard behaviour differs unacceptably, introduce a platform check in the guard and apply separate redirect logic branches for web vs. mobile until a unified solution is found.

medium impact medium prob scope

In Phase 2 the OrgSelectionService will need to coordinate the handoff to BankID/Vipps authentication after the org is selected, storing the returned personnummer against the correct tenant's member record. If the service is designed too narrowly for Phase 1 email/password flow, retrofitting Phase 2 will require invasive changes to an already-tested component.

Mitigation & Contingency

Mitigation: Design OrgSelectionService with an AuthHandoffStrategy interface from the start (Phase 1 implementation: email/password, Phase 2: BankID/Vipps). The strategy pattern makes the Phase 2 swap an additive change rather than a rewrite. Stub the interface in Phase 1 with a TODO comment referencing the Phase 2 epic.

Contingency: If Phase 2 requirements diverge significantly from Phase 1 assumptions, create a dedicated Phase2OrgSelectionService subclass that extends the base and overrides the auth handoff step, preserving Phase 1 behaviour unchanged.