# State Management ## Purpose Describe how the frontend manages global state with Zustand stores, including authentication, site context, billing, and settings. ## Code Locations (exact paths) - Auth store: `frontend/src/store/authStore.ts` - Site store: `frontend/src/store/siteStore.ts` - Billing store: `frontend/src/store/billingStore.ts` - Settings store: `frontend/src/store/settingsStore.ts` - Other UI/state stores: `frontend/src/store/onboardingStore.ts`, `columnVisibilityStore.ts`, `pageSizeStore.ts`, `settingsStore.ts`, etc. ## High-Level Responsibilities - Persist authentication state (user, tokens), refresh sessions, and enforce account/plan presence. - Track the active site (and sector via sector store) across modules, with persistence and change events. - Fetch and cache billing balances/usage/limits. - Load and update account/module settings with coalesced fetches and persistence. ## Detailed Behavior - `authStore`: - Persists `user`, `token`, `refreshToken`, `isAuthenticated`, `loading`. - `login(email,password)`: POST `/api/v1/auth/login/`; stores tokens/user; errors mapped to PLAN_REQUIRED/ACCOUNT_REQUIRED/AUTH_FAILED; resets loading on error. - `register(data)`: POST `/api/v1/auth/register/`; stores tokens/user; resets loading on error. - `refreshToken()`: POST `/api/v1/auth/refresh/`; updates access token; attempts `refreshUser`; logs out on failure. - `refreshUser()`: GET `/api/v1/auth/users/me/`; requires account+plan; updates user or logs out on auth failure; clears loading guard. - `logout()`: clears all auth fields. - `siteStore`: - Persists `activeSite`; stores `loading`/`error`. - `setActiveSite(site)`: sets/persists site, dispatches `siteChanged` event, triggers sector store load for the site. - `loadActiveSite()`: fetches sites via `fetchSites`; picks prior site if still active, else first active; persists selection. - `refreshActiveSite()`: refreshes current site from server; reloads if inactive/missing. - `billingStore`: - Holds `balance`, `usageSummary`, `usageLimits`, `loading`/`error`, `lastUpdated`. - `loadBalance()`: calls `getCreditBalance`; keeps prior balance during retry; sets `lastUpdated`. - `loadUsageSummary(startDate?, endDate?)`: calls `getCreditUsageSummary`; updates summary. - `loadUsageLimits()`: calls `getCreditUsageLimits`; tolerates 404 by returning null; records errors otherwise. - `reset()`: clears billing state. - `settingsStore`: - Persists `accountSettings`, `moduleSettings`, `moduleEnableSettings`, `loading`/`error`. - Account settings: load all, load one, create/update with create/update endpoints; handles typed errors (not found vs validation). - Module settings: load/update per module; stores per-module map. - Module enable settings: caches for 60s, coalesces concurrent fetches; `isModuleEnabled` helper. - `reset()` clears settings state. - Other stores: - `onboardingStore`, `columnVisibilityStore`, `pageSizeStore` manage UI/onboarding/table preferences (see respective files for exact fields/actions). ## Data Structures / Models Involved (no code) - Store state interfaces defined in each file (auth user shape, site, billing balance/usage, settings maps). ## Execution Flow - Components/hooks read/write state via `useXStore` hooks. - Auth flows call store actions, which perform fetches and update state; ProtectedRoute/ModuleGuard rely on auth and settings/module enable flags. - Site changes dispatch `siteChanged` for downstream listeners and trigger sector loading. - Billing/settings loads fetch data on demand and cache/persist where configured. ## Cross-Module Interactions - Auth tokens consumed by `fetchAPI` for all API calls. - Active site influences planner/writer/automation calls via query params/context. - Module enable settings influence `ModuleGuard`. - Billing data feeds billing pages and credit displays. ## State Transitions - Auth: unauthenticated → login/register → authenticated; refresh updates tokens/user; logout clears. - Site: load/refresh/set updates `activeSite` and notifies listeners. - Billing/settings: load/update actions mutate cached maps and loading/error flags. ## Error Handling - Auth store resets loading on all error paths; throws descriptive errors. - Billing store tolerates missing limits (404) and surfaces messages; balance retry preserves prior state. - Settings store differentiates not-found vs validation errors; stores messages in `error`. ## Tenancy Rules - Auth store requires account+plan; site store filters on accessible sites; billing/settings calls use authenticated endpoints tied to the user’s account. ## Billing Rules - Enforced via backend; billing store reads balances/usage/limits and does not mutate credits. ## Background Tasks / Schedulers - None; all store actions are user-driven fetches with immediate state updates. ## Key Design Considerations - Zustand `persist` used for auth/site/settings to survive reloads. - Guarded loading flags and error handling prevent stuck states. - Site changes broadcast events for dependent components/stores. ## How Developers Should Work With This Module - Use existing store actions for auth/site/billing/settings instead of duplicating fetch logic. - When adding new shared state, create a dedicated store in `src/store` and persist only needed slices. - Keep error/reset semantics consistent (always clear loading on failure).