Open-source personal finance manager. Self-hosted, privacy-first.
feat: resolve which modules a workspace shows (#571)
Tássio Noronha79e63aa7258e
diff --git a/backend/app/api/info.py b/backend/app/api/info.pyindex 7e25b92c..b500e80c 100644--- a/backend/app/api/info.py+++ b/backend/app/api/info.py@@ -3,22 +3,18 @@Tells the frontend which optional features are enabled so it can hidenav items, routes, etc. Lightweight — no auth required."""-import os-from fastapi import APIRouter-router = APIRouter(prefix="/api", tags=["info"])-+from app.core.feature_flags import feature_flag-def _flag(name: str, default: str = "false") -> bool:- return os.getenv(name, default).strip().lower() in ("1", "true", "yes", "on")+router = APIRouter(prefix="/api", tags=["info"])@router.get("/info")async def get_app_info():return {"features": {- "agents": _flag("AGENTS_ENABLED"),- "tesouro_direto": _flag("TESOURO_DIRETO_ENABLED"),+ "agents": feature_flag("AGENTS_ENABLED"),+ "tesouro_direto": feature_flag("TESOURO_DIRETO_ENABLED"),},}diff --git a/backend/app/api/workspaces.py b/backend/app/api/workspaces.pyindex 7b7b405c..68b81aac 100644--- a/backend/app/api/workspaces.py+++ b/backend/app/api/workspaces.py@@ -25,7 +25,7 @@ from app.schemas.workspace import (WorkspaceRead,WorkspaceUpdate,)-from app.services import workspace_service+from app.services import module_service, workspace_servicerouter = APIRouter(prefix="/api/workspaces", tags=["workspaces"])@@ -35,6 +35,19 @@ def _user_display_name(user: User) -> str | None:return prefs.get("display_name") or None+def _workspace_read(workspace: Workspace, role: str | None) -> WorkspaceRead:+ """Build the read model for a workspace.++ Every response that returns a workspace goes through here, so a new+ read path cannot ship without `enabled_modules` — forgetting it+ would leave the frontend hiding modules the server enabled.+ """+ item = WorkspaceRead.model_validate(workspace)+ item.role = role+ item.enabled_modules = module_service.resolve_modules(workspace)+ return item++@router.get("", response_model=list[WorkspaceRead])async def list_my_workspaces(session: AsyncSession = Depends(get_async_session),@@ -64,9 +77,7 @@ async def list_my_workspaces(out: list[WorkspaceRead] = []seen_ids: set[uuid.UUID] = set()for ws, role in member_rows.all():- item = WorkspaceRead.model_validate(ws)- item.role = role- out.append(item)+ out.append(_workspace_read(ws, role))seen_ids.add(ws.id)managed_rows = await session.execute(@@ -80,9 +91,7 @@ async def list_my_workspaces(for ws in managed_rows.scalars().all():if ws.id in seen_ids:continue- item = WorkspaceRead.model_validate(ws)- item.role = "manager"- out.append(item)+ out.append(_workspace_read(ws, "manager"))return out@@ -110,17 +119,13 @@ async def create_workspace_endpoint(self_membership=body.self_membership,)await session.commit()- item = WorkspaceRead.model_validate(workspace)- item.role = "owner" if body.self_membership else "manager"- return item+ return _workspace_read(workspace, "owner" if body.self_membership else "manager")@router.get("/current", response_model=WorkspaceRead)async def get_current_workspace(ctx: WorkspaceContext = Depends(current_workspace)):"""Return the workspace resolved from X-Workspace-Id (or the default)."""- item = WorkspaceRead.model_validate(ctx.workspace)- item.role = ctx.role- return item+ return _workspace_read(ctx.workspace, ctx.role)@router.patch("/{workspace_id}", response_model=WorkspaceRead)@@ -151,9 +156,7 @@ async def update_workspace(session.add(user)await session.commit()await session.refresh(workspace)- item = WorkspaceRead.model_validate(workspace)- item.role = member.role- return item+ return _workspace_read(workspace, member.role)@router.get("/{workspace_id}/members", response_model=list[MemberRead])@@ -310,9 +313,7 @@ async def archive_workspace_endpoint()workspace = await workspace_service.archive_workspace(session, workspace_id, user.id)await session.commit()- item = WorkspaceRead.model_validate(workspace)- item.role = "owner"- return item+ return _workspace_read(workspace, "owner")@router.delete(diff --git a/backend/app/core/feature_flags.py b/backend/app/core/feature_flags.pynew file mode 100644index 00000000..1d7a7e4d--- /dev/null+++ b/backend/app/core/feature_flags.py@@ -0,0 +1,14 @@+"""Environment-driven capability flags.++One parser, so everything that asks "is this capability enabled on this+deployment?" gets the same answer: the `/api/info` payload the frontend+reads, and the module resolver's deployment layer.+"""+import os++TRUTHY = ("1", "true", "yes", "on")+++def feature_flag(name: str, default: str = "false") -> bool:+ """Read a boolean capability flag from the environment."""+ return os.getenv(name, default).strip().lower() in TRUTHYdiff --git a/backend/app/schemas/workspace.py b/backend/app/schemas/workspace.pyindex 988ffb6f..b8b0bf7b 100644--- a/backend/app/schemas/workspace.py+++ b/backend/app/schemas/workspace.py@@ -25,6 +25,11 @@ class WorkspaceRead(BaseModel):# /api/workspaces (the listing endpoint). Omitted from per-workspace# detail responses since the membership row is fetched alongside.role: Optional[str] = None+ # Which modules this workspace shows, resolved server-side by+ # `services.module_service`. The frontend consumes this list; it must+ # never re-derive it from `kind`, or the two copies drift and a user+ # sees a module the server thinks is off.+ enabled_modules: list[str] = []class Config:from_attributes = Truediff --git a/backend/app/services/module_service.py b/backend/app/services/module_service.pynew file mode 100644index 00000000..31f866e1--- /dev/null+++ b/backend/app/services/module_service.py@@ -0,0 +1,260 @@+"""Which modules does a workspace show?++One answer, one place. A module is a top-level destination in the app;+this decides which ones a given workspace gets. Adding a workspace kind,+a per-workspace opt-out, or a deployment switch is a new entry in one of+the registries below, never an edit to navigation code.++The chain, in order:++ 0. Deployment — capability flags from the environment. Veto only.+ 1. Catalog — each module declares whether it is on by default.+ 2. Kind policy — the only layer with opinions today.+ 3. Workspace — per-workspace override. Abstains for now.+ 4. Supplemental — extension point. Abstains in this codebase.++Layer 0 is listed first because it is the outermost constraint, and+applied last because that is the only ordering in which it is genuinely+a veto: anything applied before layers 1-4 could be handed back by them.++What this is NOT:++ - Not a permission system. It answers "does this workspace show this+ module", never "may this user write". Nothing here belongs next to+ `require_write`; there is no API-level enforcement, by design.+ - Not a feature-flag framework. No per-user toggles, no remote config,+ no rollouts. `ModuleId` is closed on purpose — a stringly-typed+ module id is exactly how this would drift into one.+ - Not navigation metadata. Icons, paths and labels stay in the+ frontend. This answers *which* modules, never *how* to render them.++Deployment flags and this resolver answer different questions and+coexist deliberately: a flag turns a capability off for the whole+install (the operator's call), a kind policy turns it off for one+workspace. `AGENTS_ENABLED` is still read directly by the frontend and+is not part of the catalog — see MODULE_DEPLOYMENT_FLAGS.+"""+from collections.abc import Callable, Mapping, Sequence+from dataclasses import dataclass+from enum import Enum+from typing import Optional, Protocol++from app.core.feature_flags import feature_flag+from app.models.workspace import Workspace+++class ModuleId(str, Enum):+ """Top-level destinations. Closed set — see the module docstring."""++ TRANSACTIONS = "transactions"+ ACCOUNTS = "accounts"+ IMPORT = "import"+ REPORTS = "reports"+ ASSETS = "assets"+ BUDGETS = "budgets"+ GOALS = "goals"+ RECURRING = "recurring"+ CATEGORIES = "categories"+ PAYEES = "payees"+ SPLIT_GROUPS = "split_groups"+ RULES = "rules"+ INVOICES = "invoices"+++@dataclass(frozen=True)+class ModuleSpec:+ """Layer 1 — a module's base availability, before any policy runs."""++ module_id: ModuleId+ # True for everything a workspace gets unless a later layer removes+ # it. False for modules a policy has to opt into.+ default_enabled: bool+++CATALOG: Mapping[ModuleId, ModuleSpec] = {+ spec.module_id: spec+ for spec in (+ ModuleSpec(ModuleId.TRANSACTIONS, default_enabled=True),+ ModuleSpec(ModuleId.ACCOUNTS, default_enabled=True),+ ModuleSpec(ModuleId.IMPORT, default_enabled=True),+ ModuleSpec(ModuleId.REPORTS, default_enabled=True),+ ModuleSpec(ModuleId.ASSETS, default_enabled=True),+ ModuleSpec(ModuleId.BUDGETS, default_enabled=True),+ ModuleSpec(ModuleId.GOALS, default_enabled=True),+ ModuleSpec(ModuleId.RECURRING, default_enabled=True),+ ModuleSpec(ModuleId.CATEGORIES, default_enabled=True),+ ModuleSpec(ModuleId.PAYEES, default_enabled=True),+ ModuleSpec(ModuleId.SPLIT_GROUPS, default_enabled=True),+ ModuleSpec(ModuleId.RULES, default_enabled=True),+ ModuleSpec(ModuleId.INVOICES, default_enabled=False),+ )+}+++def catalog_defaults(catalog: Mapping[ModuleId, ModuleSpec] = CATALOG) -> frozenset[ModuleId]:+ return frozenset(s.module_id for s in catalog.values() if s.default_enabled)+++# ---------------------------------------------------------------------------+# Layer 2 — kind policy (the Strategy)+# ---------------------------------------------------------------------------+class ModulePolicy(Protocol):+ """One implementation per workspace kind."""++ def modules(self, base: frozenset[ModuleId]) -> frozenset[ModuleId]:+ """Return the modules this kind shows, given the catalog defaults."""+ ...+++class PersonalPolicy:+ """The catalog defaults, unchanged.++ Deliberately empty of opinions: `personal` renders exactly what the+ app rendered before modules existed, and the test asserting that is+ what keeps this true.+ """++ def modules(self, base: frozenset[ModuleId]) -> frozenset[ModuleId]:+ return base+++class BusinessPolicy:+ """The catalog defaults plus what a workspace tracking work needs."""++ def modules(self, base: frozenset[ModuleId]) -> frozenset[ModuleId]:+ return base | {ModuleId.INVOICES}+++KIND_POLICIES: Mapping[str, ModulePolicy] = {+ "personal": PersonalPolicy(),+ "business": BusinessPolicy(),+}+++# ---------------------------------------------------------------------------+# Layers 3 and 4 — providers+# ---------------------------------------------------------------------------+class ModuleProvider(Protocol):+ """A layer that may add, remove, or abstain.++ Return the new set, or None to abstain. Abstaining and returning the+ set unchanged mean the same thing to the resolver; None says so+ louder, and the tests assert on it.+ """++ def apply(+ self, current: frozenset[ModuleId], workspace: Workspace+ ) -> Optional[frozenset[ModuleId]]:+ ...+++class WorkspaceOverrideProvider:+ """Layer 3 — per-workspace opt-in/opt-out.++ Abstains: nothing is stored per workspace yet. When it becomes a DB+ read, memoize it on the request's WorkspaceContext — never in a+ global cache that outlives the request, or one workspace's answer+ leaks into another's.+ """++ def apply(+ self, current: frozenset[ModuleId], workspace: Workspace+ ) -> Optional[frozenset[ModuleId]]:+ return None+++class SupplementalProvider:+ """Layer 4 — extension point.++ A deployment can supply an implementation that further restricts the+ resolved set. This codebase ships one that always abstains, so the+ seam is exercised by the resolver and the tests without this+ repository holding any opinion about what would go there.+ """++ def apply(+ self, current: frozenset[ModuleId], workspace: Workspace+ ) -> Optional[frozenset[ModuleId]]:+ return None+++DEFAULT_PROVIDERS: Sequence[ModuleProvider] = (+ WorkspaceOverrideProvider(),+ SupplementalProvider(),+)+++# ---------------------------------------------------------------------------+# Layer 0 — deployment veto+# ---------------------------------------------------------------------------+# ModuleId -> environment flag name. Ships empty: no module in the+# catalog is deployment-gated today. The layer is wired and tested so+# that gating one later is adding an entry here, not building a+# mechanism.+#+# `agents` is deliberately absent. It is not a catalog module: the+# frontend reads AGENTS_ENABLED straight from /api/info at its own call+# sites, and folding it in here would turn this into an agents refactor.+MODULE_DEPLOYMENT_FLAGS: Mapping[ModuleId, str] = {}+++class ModuleResolver:+ """Runs the chain. Cheap enough to build per request."""++ def __init__(+ self,+ *,+ catalog: Mapping[ModuleId, ModuleSpec] = CATALOG,+ policies: Mapping[str, ModulePolicy] = KIND_POLICIES,+ providers: Sequence[ModuleProvider] = DEFAULT_PROVIDERS,+ deployment_flags: Mapping[ModuleId, str] = MODULE_DEPLOYMENT_FLAGS,+ flag_reader: Callable[[str], bool] = feature_flag,+ ) -> None:+ self._catalog = catalog+ self._policies = policies+ self._providers = providers+ self._deployment_flags = deployment_flags+ self._flag_reader = flag_reader++ def resolve(self, workspace: Workspace) -> list[str]:+ """The modules this workspace shows, as sorted strings.++ Sorted so the API response is stable and diffable; the frontend+ treats it as a set and never relies on the order.+ """+ resolved = self._resolve_ids(workspace)+ return sorted(m.value for m in resolved)++ def _resolve_ids(self, workspace: Workspace) -> frozenset[ModuleId]:+ current = catalog_defaults(self._catalog)++ # Layer 2. An unknown kind falls back to the catalog defaults+ # rather than raising: a workspace stored before a kind was+ # retired still has to render something sane.+ policy = self._policies.get(workspace.kind)+ if policy is not None:+ current = policy.modules(current)++ # Layers 3 and 4.+ for provider in self._providers:+ proposed = provider.apply(current, workspace)+ if proposed is not None:+ current = proposed++ # Layer 0, applied last so it cannot be undone. Veto only: a+ # flag can remove a module, never introduce one the layers above+ # did not grant.+ vetoed = {+ module_id+ for module_id, flag_name in self._deployment_flags.items()+ if not self._flag_reader(flag_name)+ }+ return frozenset(current - vetoed)+++_default_resolver = ModuleResolver()+++def resolve_modules(workspace: Workspace) -> list[str]:+ """Module list for a workspace, using the default chain."""+ return _default_resolver.resolve(workspace)diff --git a/backend/tests/test_module_service.py b/backend/tests/test_module_service.pynew file mode 100644index 00000000..d8433255--- /dev/null+++ b/backend/tests/test_module_service.py@@ -0,0 +1,159 @@+"""Module resolution: the catalog, the kind policies, and the chain.++The point of these tests is that the invariants are mechanical rather+than intentional. In particular, `personal` is asserted against a+literal list, so any change that would take a module away from an+existing workspace fails here first.+"""+import pytest++from app.models.workspace import WORKSPACE_KINDS, Workspace+from app.services.module_service import (+ CATALOG,+ KIND_POLICIES,+ MODULE_DEPLOYMENT_FLAGS,+ ModuleId,+ ModuleResolver,+ catalog_defaults,+ resolve_modules,+)++# What a personal workspace shows. This is the app exactly as it was+# before modules existed — spelled out rather than derived, so removing+# something from an existing user has to be a deliberate edit here.+PERSONAL_MODULES = [+ "accounts",+ "assets",+ "budgets",+ "categories",+ "goals",+ "import",+ "payees",+ "recurring",+ "reports",+ "rules",+ "split_groups",+ "transactions",+]+++def ws(kind: str) -> Workspace:+ return Workspace(name="W", kind=kind)+++# ---------------------------------------------------------------------------+# the two kinds+# ---------------------------------------------------------------------------+def test_personal_resolves_to_todays_navigation():+ assert resolve_modules(ws("personal")) == PERSONAL_MODULES+++def test_business_is_personal_plus_invoices():+ assert resolve_modules(ws("business")) == sorted(+ PERSONAL_MODULES + ["invoices"]+ )+++def test_invoices_is_the_only_difference():+ """Resist giving the policies more differences than the product has."""+ personal = set(resolve_modules(ws("personal")))+ business = set(resolve_modules(ws("business")))+ assert business - personal == {"invoices"}+ assert personal - business == set()+++def test_every_workspace_kind_has_a_policy():+ assert set(KIND_POLICIES) == set(WORKSPACE_KINDS)+++def test_unknown_kind_falls_back_to_catalog_defaults():+ """A row stored before a kind was retired still renders."""+ assert resolve_modules(ws("something_retired")) == PERSONAL_MODULES+++# ---------------------------------------------------------------------------+# the chain+# ---------------------------------------------------------------------------+def test_layers_three_and_four_abstain():+ """Neither may quietly start having opinions."""+ from app.services.module_service import (+ SupplementalProvider,+ WorkspaceOverrideProvider,+ )++ workspace = ws("business")+ current = catalog_defaults()+ assert WorkspaceOverrideProvider().apply(current, workspace) is None+ assert SupplementalProvider().apply(current, workspace) is None+++def test_deployment_flag_mapping_ships_empty():+ """No catalog module is deployment-gated today."""+ assert MODULE_DEPLOYMENT_FLAGS == {}+++def test_deployment_layer_vetoes_when_its_flag_is_off():+ """Proves the seam before anything uses it."""+ resolver = ModuleResolver(+ deployment_flags={ModuleId.ASSETS: "SOME_CAPABILITY_ENABLED"},+ flag_reader=lambda name: False,+ )+ assert "assets" not in resolver.resolve(ws("personal"))+ # Everything else is untouched.+ assert set(resolver.resolve(ws("personal"))) == set(PERSONAL_MODULES) - {"assets"}+++def test_deployment_layer_keeps_the_module_when_its_flag_is_on():+ resolver = ModuleResolver(+ deployment_flags={ModuleId.ASSETS: "SOME_CAPABILITY_ENABLED"},+ flag_reader=lambda name: True,+ )+ assert "assets" in resolver.resolve(ws("personal"))+++def test_deployment_layer_cannot_grant():+ """A flag being on must not introduce a module the kind policy+ withheld — otherwise an operator could enable a module the policy+ says doesn't belong, and the invariants stop holding."""+ resolver = ModuleResolver(+ deployment_flags={ModuleId.INVOICES: "SOME_CAPABILITY_ENABLED"},+ flag_reader=lambda name: True,+ )+ assert "invoices" not in resolver.resolve(ws("personal"))+++# ---------------------------------------------------------------------------+# the abstraction has to buy something+# ---------------------------------------------------------------------------+def test_a_new_kind_needs_only_a_new_policy():+ """No change to the resolver, the catalog, or any navigation code."""++ class ReadOnlyPolicy:+ def modules(self, base):+ return base - {ModuleId.IMPORT, ModuleId.RULES}++ resolver = ModuleResolver(policies={**KIND_POLICIES, "archive": ReadOnlyPolicy()})+ resolved = resolver.resolve(ws("archive"))+ assert "import" not in resolved and "rules" not in resolved+ assert "transactions" in resolved+ # The kinds that already existed are unaffected.+ assert resolver.resolve(ws("personal")) == PERSONAL_MODULES+++# ---------------------------------------------------------------------------+# catalog integrity+# ---------------------------------------------------------------------------+def test_catalog_covers_every_module_id():+ assert set(CATALOG) == set(ModuleId)+++def test_invoices_is_the_only_module_off_by_default():+ off = {m.value for m in ModuleId} - {m.value for m in catalog_defaults()}+ assert off == {"invoices"}++[email protected]("module_id", list(ModuleId))+def test_module_ids_are_lower_snake_case(module_id: ModuleId):+ """The frontend mirrors these verbatim."""+ assert module_id.value == module_id.value.lower().strip()+ assert " " not in module_id.value and "-" not in module_id.valuediff --git a/backend/tests/test_workspace_modules_api.py b/backend/tests/test_workspace_modules_api.pynew file mode 100644index 00000000..b7720f60--- /dev/null+++ b/backend/tests/test_workspace_modules_api.py@@ -0,0 +1,70 @@+"""`enabled_modules` reaches the client on every workspace read path.++The frontend hides any module missing from this list, so a response that+omits it is not a cosmetic bug — it blanks the navigation.+"""+import pytest+from httpx import AsyncClient++from app.services.module_service import resolve_modules+from app.models.workspace import Workspace+++async def test_listing_includes_enabled_modules(client: AsyncClient, auth_headers, test_user):+ resp = await client.get("/api/workspaces", headers=auth_headers)+ assert resp.status_code == 200, resp.text+ for item in resp.json():+ assert item["enabled_modules"], item+++async def test_current_workspace_includes_enabled_modules(+ client: AsyncClient, auth_headers, test_workspace+):+ resp = await client.get("/api/workspaces/current", headers=auth_headers)+ assert resp.status_code == 200, resp.text+ assert "invoices" not in resp.json()["enabled_modules"]+++async def test_create_and_update_include_enabled_modules(+ client: AsyncClient, auth_headers, test_user+):+ created = await client.post(+ "/api/workspaces",+ headers=auth_headers,+ json={"name": "Consultoria", "kind": "business", "self_membership": True},+ )+ assert created.status_code == 201, created.text+ assert "invoices" in created.json()["enabled_modules"]++ workspace_id = created.json()["id"]+ patched = await client.patch(+ f"/api/workspaces/{workspace_id}",+ headers=auth_headers,+ json={"name": "Consultoria BR"},+ )+ assert patched.status_code == 200, patched.text+ assert "invoices" in patched.json()["enabled_modules"]+++async def test_archive_includes_enabled_modules(client: AsyncClient, auth_headers, test_workspace):+ created = await client.post(+ "/api/workspaces",+ headers=auth_headers,+ json={"name": "Temp", "self_membership": True},+ )+ workspace_id = created.json()["id"]+ resp = await client.post(f"/api/workspaces/{workspace_id}/archive", headers=auth_headers)+ assert resp.status_code == 200, resp.text+ assert resp.json()["enabled_modules"]+++async def test_response_matches_the_resolver(client: AsyncClient, auth_headers, test_workspace):+ """The API must not compute its own answer."""+ resp = await client.get("/api/workspaces/current", headers=auth_headers)+ expected = resolve_modules(Workspace(name="x", kind=test_workspace.kind))+ assert resp.json()["enabled_modules"] == expecteddiff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex 0904f16c..aab07862 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -9,6 +9,7 @@ import { CollectionFilterProvider } from '@/contexts/collection-filter-context'import { ProtectedRoute } from '@/components/protected-route'import { AdminRoute } from '@/components/admin-route'import { AgentsRoute } from '@/components/agents-route'+import { ModuleRoute } from '@/components/module-route'import { AppLayout } from '@/components/app-layout'const SetupPage = lazy(() => import('@/pages/setup'))@@ -34,6 +35,7 @@ const AdminSettingsPage = lazy(() => import('@/pages/admin/settings'))const AgentsListPage = lazy(() => import('@/pages/agents-list'))const AgentDetailPage = lazy(() => import('@/pages/agent-detail'))const AgentConnectionsPage = lazy(() => import('@/pages/agent-connections'))+const InvoicesPage = lazy(() => import('@/pages/invoices'))const WorkspaceSettingsPage = lazy(() => import('@/pages/workspace-settings'))const OAuthCallbackPage = lazy(() => import('@/pages/oauth-callback'))const OIDCCallbackPage = lazy(() => import('@/pages/oidc-callback'))@@ -78,23 +80,24 @@ function App() {}><Route path="/" element={<DashboardPage />} />- <Route path="/transactions" element={<TransactionsPage />} />- <Route path="/accounts" element={<AccountsPage />} />- <Route path="/accounts/:id" element={<AccountDetailPage />} />+ <Route path="/transactions" element={<ModuleRoute module="transactions"><TransactionsPage /></ModuleRoute>} />+ <Route path="/accounts" element={<ModuleRoute module="accounts"><AccountsPage /></ModuleRoute>} />+ <Route path="/accounts/:id" element={<ModuleRoute module="accounts"><AccountDetailPage /></ModuleRoute>} /><Route path="/oauth/callback" element={<OAuthCallbackPage />} /><Route path="/enable-banking" element={<OAuthCallbackPage />} />- <Route path="/import" element={<ImportPage />} />- <Route path="/rules" element={<RulesPage />} />- <Route path="/categories" element={<CategoriesPage />} />+ <Route path="/import" element={<ModuleRoute module="import"><ImportPage /></ModuleRoute>} />+ <Route path="/rules" element={<ModuleRoute module="rules"><RulesPage /></ModuleRoute>} />+ <Route path="/categories" element={<ModuleRoute module="categories"><CategoriesPage /></ModuleRoute>} /><Route path="/collections" element={<CollectionsPage />} />- <Route path="/budgets" element={<BudgetsPage />} />- <Route path="/goals" element={<GoalsPage />} />- <Route path="/recurring" element={<RecurringPage />} />- <Route path="/assets" element={<AssetsPage />} />- <Route path="/reports" element={<ReportsPage />} />- <Route path="/payees" element={<PayeesPage />} />- <Route path="/groups" element={<GroupsPage />} />- <Route path="/groups/:id" element={<GroupDetailPage />} />+ <Route path="/budgets" element={<ModuleRoute module="budgets"><BudgetsPage /></ModuleRoute>} />+ <Route path="/goals" element={<ModuleRoute module="goals"><GoalsPage /></ModuleRoute>} />+ <Route path="/recurring" element={<ModuleRoute module="recurring"><RecurringPage /></ModuleRoute>} />+ <Route path="/assets" element={<ModuleRoute module="assets"><AssetsPage /></ModuleRoute>} />+ <Route path="/reports" element={<ModuleRoute module="reports"><ReportsPage /></ModuleRoute>} />+ <Route path="/payees" element={<ModuleRoute module="payees"><PayeesPage /></ModuleRoute>} />+ <Route path="/groups" element={<ModuleRoute module="split_groups"><GroupsPage /></ModuleRoute>} />+ <Route path="/groups/:id" element={<ModuleRoute module="split_groups"><GroupDetailPage /></ModuleRoute>} />+ <Route path="/invoices" element={<ModuleRoute module="invoices"><InvoicesPage /></ModuleRoute>} /><Route path="/workspace/settings" element={<WorkspaceSettingsPage />} /><Route path="/admin" element={<AdminRoute><AdminSettingsPage /></AdminRoute>} /><Route path="/agents" element={<AgentsRoute><AgentsListPage /></AgentsRoute>} />diff --git a/frontend/src/components/app-layout.tsx b/frontend/src/components/app-layout.tsxindex 729173f0..03284f73 100644--- a/frontend/src/components/app-layout.tsx+++ b/frontend/src/components/app-layout.tsx@@ -1,4 +1,4 @@-import { useState, useCallback, useEffect } from 'react'+import { useState, useCallback, useEffect, useMemo } from 'react'import { getAccountName } from '@/lib/account-utils'import { Link, Outlet, useLocation, useNavigate } from 'react-router-dom'import { useTranslation } from 'react-i18next'@@ -6,6 +6,7 @@ import { useDisplayLocale } from '@/hooks/use-display-locale'import { useQuery } from '@tanstack/react-query'import { useAuth } from '@/contexts/auth-context'import { useCollectionFilter } from '@/contexts/collection-filter-context'+import { useWorkspace } from '@/contexts/workspace-context'import { CollectionSelector } from '@/components/collection-selector'import { auth as authApi, backup as backupApi, admin as adminApi } from '@/lib/api'import { resolveSupportedLang } from '@/lib/i18n'@@ -33,23 +34,12 @@ import { ShellLogo } from '@/components/shell-logo'import { UpdateAvailableBanner } from '@/components/update-available-banner'import { UpdateAvailableDialog } from '@/components/update-available-dialog'import { WorkspaceSwitcher } from '@/components/workspace-switcher'+import { navItems, visibleNavItems, type NavItem } from '@/lib/nav-items'import {- ArrowLeftRight,- Building2,- SlidersHorizontal,- Upload,Menu,ChevronRight,- Tag,- PiggyBank,- Target,Eye,EyeOff,- Repeat,- Landmark,- Users,- Split,- BarChart3,Sun,Moon,Languages,@@ -71,31 +61,26 @@ import { useFeatureFlags } from '@/hooks/use-feature-flags'import { Bot, Search, Sparkles } from 'lucide-react'import { setThemeBasedOnSystem } from '@/lib/theme-utils'-type NavItem =- | { type: 'link'; key: string; path: string; icon: React.ElementType }- | { type: 'separator'; labelKey: string }--const navItems: NavItem[] = [- // The dashboard ("Painel") is now reachable by clicking the Securo- // logo + name in the sidebar header — no dedicated menu item to keep- // the sidebar focused on the main destinations. Transactions sits- // inside the ACCOUNTS section since it's account-scoped data.- { type: 'separator', labelKey: 'nav.groupAccounts' },- { type: 'link', key: 'transactions', path: '/transactions', icon: ArrowLeftRight },- { type: 'link', key: 'accounts', path: '/accounts', icon: Building2 },- { type: 'link', key: 'import', path: '/import', icon: Upload },- { type: 'separator', labelKey: 'nav.groupAnalysis' },- { type: 'link', key: 'reports', path: '/reports', icon: BarChart3 },- { type: 'link', key: 'assets', path: '/assets', icon: Landmark },- { type: 'separator', labelKey: 'nav.groupSetup' },- { type: 'link', key: 'budgets', path: '/budgets', icon: PiggyBank },- { type: 'link', key: 'goals', path: '/goals', icon: Target },- { type: 'link', key: 'recurring', path: '/recurring', icon: Repeat },- { type: 'link', key: 'categories', path: '/categories', icon: Tag },- { type: 'link', key: 'payees', path: '/payees', icon: Users },- { type: 'link', key: 'splitGroups', path: '/groups', icon: Split },- { type: 'link', key: 'rules', path: '/rules', icon: SlidersHorizontal },-]+/** Placeholder rows shown while the workspace's module list is in flight. */+function NavSkeleton() {+ return (+ <div className="flex flex-col gap-0.5" aria-hidden>+ {[3, 2, 7].map((count, section) => (+ <div key={section} className={cn('flex flex-col gap-0.5', section > 0 && 'pt-3')}>+ <div className="px-3 pt-1 pb-1">+ <div className="h-2 w-16 rounded bg-sidebar-accent/60 animate-pulse" />+ </div>+ {Array.from({ length: count }).map((_, row) => (+ <div key={row} className="flex items-center gap-3 px-3 py-2">+ <div className="h-4 w-4 rounded bg-sidebar-accent/60 animate-pulse" />+ <div className="h-3 flex-1 max-w-[7rem] rounded bg-sidebar-accent/40 animate-pulse" />+ </div>+ ))}+ </div>+ ))}+ </div>+ )+}function formatCurrency(value: number, currency = 'USD', locale = 'en-US') {return new Intl.NumberFormat(locale, { style: 'currency', currency }).format(@@ -124,6 +109,7 @@ export function AppLayout() {const [updateDialogOpen, setUpdateDialogOpen] = useState(false)useCommandPaletteHotkey(setPaletteOpen)const { agentsEnabled } = useFeatureFlags()+ const { hasModule, isLoading: workspaceLoading } = useWorkspace()// ⌘J / Ctrl+J toggles the global slide-over chat from anywhere.// Distinct from ⌘K (command palette) so users can have both open.@@ -149,7 +135,10 @@ export function AppLayout() {// a configuration surface (KB upload, providers, default selection),// not a daily destination. Moved to the user menu (Change password,// 2FA, Backups, AI agents).- const finalNavItems: NavItem[] = navItems+ const finalNavItems: NavItem[] = useMemo(+ () => visibleNavItems(navItems, hasModule),+ [hasModule],+ )const isMac =typeof navigator !== 'undefined' &&/Mac|iPhone|iPad|iPod/.test(navigator.platform)@@ -375,7 +364,11 @@ export function AppLayout() {<div className="flex-1 min-h-0 overflow-y-auto">{/* Nav */}<nav className="flex flex-col gap-0.5 px-3 pt-1 pb-3" data-tour="sidebar">- {finalNavItems.map((item, idx) => {+ {/* Which modules this workspace shows is resolved server-side,+ so until the workspace list lands there is no honest answer+ — a placeholder beats both an empty sidebar and a guess. */}+ {workspaceLoading && <NavSkeleton />}+ {!workspaceLoading && finalNavItems.map((item, idx) => {if (item.type === 'separator') {// The first separator sits right below the search bar// — without trimming the top padding it leaves a widediff --git a/frontend/src/components/command-palette.tsx b/frontend/src/components/command-palette.tsxindex 4f6babae..369f717c 100644--- a/frontend/src/components/command-palette.tsx+++ b/frontend/src/components/command-palette.tsx@@ -4,6 +4,8 @@ import { Dialog as DialogPrimitive } from 'radix-ui'import { useNavigate } from 'react-router-dom'import { useTranslation } from 'react-i18next'import { useDisplayLocale } from '@/hooks/use-display-locale'+import { useWorkspace } from '@/contexts/workspace-context'+import type { ModuleId } from '@/lib/modules'import { useQuery } from '@tanstack/react-query'import {Search,@@ -46,21 +48,25 @@ type StaticItem = {path?: stringonSelect?: (nav: (to: string) => void) => voidkeywords?: string[]+ /** Gate this destination on the workspace showing that module.+ * Omitted for surfaces outside the module concept (the dashboard). */+ module?: ModuleId}const NAV_ITEMS: StaticItem[] = [{ id: 'nav-dashboard', labelKey: 'nav.dashboard', icon: LayoutDashboard, path: '/', keywords: ['home', 'inicio', 'início'] },- { id: 'nav-transactions', labelKey: 'nav.transactions', icon: ArrowLeftRight, path: '/transactions', keywords: ['tx', 'transacoes', 'transações'] },- { id: 'nav-accounts', labelKey: 'nav.accounts', icon: Building2, path: '/accounts', keywords: ['contas'] },- { id: 'nav-import', labelKey: 'nav.import', icon: Upload, path: '/import', keywords: ['csv', 'ofx', 'importar'] },- { id: 'nav-reports', labelKey: 'nav.reports', icon: BarChart3, path: '/reports', keywords: ['relatorios', 'relatórios', 'charts'] },- { id: 'nav-assets', labelKey: 'nav.assets', icon: Landmark, path: '/assets', keywords: ['patrimonio', 'patrimônio'] },- { id: 'nav-budgets', labelKey: 'nav.budgets', icon: PiggyBank, path: '/budgets', keywords: ['orcamentos', 'orçamentos'] },- { id: 'nav-goals', labelKey: 'nav.goals', icon: Target, path: '/goals', keywords: ['metas'] },- { id: 'nav-recurring', labelKey: 'nav.recurring', icon: Repeat, path: '/recurring', keywords: ['recorrentes'] },- { id: 'nav-categories', labelKey: 'nav.categories', icon: Tag, path: '/categories', keywords: ['categorias'] },- { id: 'nav-payees', labelKey: 'nav.payees', icon: Users, path: '/payees', keywords: ['beneficiarios', 'beneficiários'] },- { id: 'nav-rules', labelKey: 'nav.rules', icon: SlidersHorizontal, path: '/rules', keywords: ['regras'] },+ { id: 'nav-transactions', labelKey: 'nav.transactions', icon: ArrowLeftRight, path: '/transactions', keywords: ['tx', 'transacoes', 'transações'], module: 'transactions' },+ { id: 'nav-invoices', labelKey: 'nav.invoices', icon: Receipt, path: '/invoices', keywords: ['cobrancas', 'cobranças', 'faturas', 'clientes', 'recebimentos'], module: 'invoices' },+ { id: 'nav-accounts', labelKey: 'nav.accounts', icon: Building2, path: '/accounts', keywords: ['contas'], module: 'accounts' },+ { id: 'nav-import', labelKey: 'nav.import', icon: Upload, path: '/import', keywords: ['csv', 'ofx', 'importar'], module: 'import' },+ { id: 'nav-reports', labelKey: 'nav.reports', icon: BarChart3, path: '/reports', keywords: ['relatorios', 'relatórios', 'charts'], module: 'reports' },+ { id: 'nav-assets', labelKey: 'nav.assets', icon: Landmark, path: '/assets', keywords: ['patrimonio', 'patrimônio'], module: 'assets' },+ { id: 'nav-budgets', labelKey: 'nav.budgets', icon: PiggyBank, path: '/budgets', keywords: ['orcamentos', 'orçamentos'], module: 'budgets' },+ { id: 'nav-goals', labelKey: 'nav.goals', icon: Target, path: '/goals', keywords: ['metas'], module: 'goals' },+ { id: 'nav-recurring', labelKey: 'nav.recurring', icon: Repeat, path: '/recurring', keywords: ['recorrentes'], module: 'recurring' },+ { id: 'nav-categories', labelKey: 'nav.categories', icon: Tag, path: '/categories', keywords: ['categorias'], module: 'categories' },+ { id: 'nav-payees', labelKey: 'nav.payees', icon: Users, path: '/payees', keywords: ['beneficiarios', 'beneficiários'], module: 'payees' },+ { id: 'nav-rules', labelKey: 'nav.rules', icon: SlidersHorizontal, path: '/rules', keywords: ['regras'], module: 'rules' },]const QUICK_ACTIONS: StaticItem[] = [@@ -256,6 +262,7 @@ export interface CommandPaletteProps {export function CommandPalette({ open, onOpenChange }: CommandPaletteProps) {const { t } = useTranslation()const navigate = useNavigate()+ const { hasModule } = useWorkspace()const [query, setQuery] = useState('')const [debounced, setDebounced] = useState('')const recents = useSyncExternalStore(subscribeRecents, getRecentSnapshot, getRecentSnapshot)@@ -311,11 +318,14 @@ export function CommandPalette({ open, onOpenChange }: CommandPaletteProps) {// Client-side filtered nav + quick actions so typing "regras" or "nova"// narrows the in-app items alongside the backend entity search.const filteredNavItems = useMemo(() => {- if (debounced.trim().length === 0) return NAV_ITEMS- return NAV_ITEMS.filter((n) =>+ // Same question the sidebar asks, so the palette can't offer a+ // destination the workspace doesn't show.+ const available = NAV_ITEMS.filter((n) => !n.module || hasModule(n.module))+ if (debounced.trim().length === 0) return available+ return available.filter((n) =>matchesQuery(debounced, [t(n.labelKey), n.path, ...(n.keywords ?? [])]))- }, [debounced, t])+ }, [debounced, t, hasModule])const filteredQuickActions = useMemo(() => {if (debounced.trim().length === 0) return QUICK_ACTIONSdiff --git a/frontend/src/components/module-route.tsx b/frontend/src/components/module-route.tsxnew file mode 100644index 00000000..6cb0e46b--- /dev/null+++ b/frontend/src/components/module-route.tsx@@ -0,0 +1,26 @@+import { Navigate } from 'react-router-dom'+import { useWorkspace } from '@/contexts/workspace-context'+import type { ModuleId } from '@/lib/modules'++/** Wraps a module's pages so navigating straight to the URL when the+ * active workspace doesn't show that module lands on home instead of+ * rendering it. Hiding the nav link alone leaves the page reachable.+ * Mirrors AdminRoute / AgentsRoute. */+export function ModuleRoute({+ module,+ children,+}: {+ module: ModuleId+ children: React.ReactNode+}) {+ const { hasModule, isLoading } = useWorkspace()+ if (isLoading) {+ return (+ <div className="flex items-center justify-center min-h-screen">+ <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" />+ </div>+ )+ }+ if (!hasModule(module)) return <Navigate to="/" replace />+ return <>{children}</>+}diff --git a/frontend/src/contexts/workspace-context.tsx b/frontend/src/contexts/workspace-context.tsxindex a65e7e86..a4a20ce2 100644--- a/frontend/src/contexts/workspace-context.tsx+++ b/frontend/src/contexts/workspace-context.tsx@@ -2,6 +2,7 @@ import { createContext, useCallback, useContext, useEffect, useMemo, useState, timport { useQueryClient } from '@tanstack/react-query'import { useAuth } from '@/contexts/auth-context'import { workspaces as workspacesApi, WORKSPACE_STORAGE_KEY } from '@/lib/api'+import type { ModuleId } from '@/lib/modules'import type { Workspace, WorkspaceRole } from '@/types'interface WorkspaceContextType {@@ -18,12 +19,19 @@ interface WorkspaceContextType {canManage: boolean/** True for owner, manager, OR editor — anyone allowed to mutate financial data. */canWrite: boolean+ /** Modules the active workspace shows, as resolved by the server. */+ enabledModules: ModuleId[]+ /**+ * The single question the UI asks about modules. False while the+ * workspace list is still loading, so nothing renders on a guess.+ */+ hasModule: (id: ModuleId) => boolean}const WorkspaceContext = createContext<WorkspaceContextType | null>(null)export function WorkspaceProvider({ children }: { children: ReactNode }) {- const { user, token } = useAuth()+ const { user, token, isLoading: authLoading } = useAuth()const [list, setList] = useState<Workspace[]>([])const [currentId, setCurrentId] = useState<string | null>(() => localStorage.getItem(WORKSPACE_STORAGE_KEY))const [isLoading, setIsLoading] = useState(true)@@ -59,6 +67,11 @@ export function WorkspaceProvider({ children }: { children: ReactNode }) {}, [])useEffect(() => {+ // Stay in the loading state until auth has settled. Reporting "done,+ // no workspaces" while the token is still being restored is a lie+ // that lasts one render — long enough for anything gated on+ // `hasModule` to decide the module is off and redirect away.+ if (authLoading) returnif (!user || !token) {setList([])setCurrentId(null)@@ -66,7 +79,7 @@ export function WorkspaceProvider({ children }: { children: ReactNode }) {return}void loadWorkspaces()- }, [user, token, loadWorkspaces])+ }, [authLoading, user, token, loadWorkspaces])const switchWorkspace = useCallback(async (id: string) => {@@ -94,6 +107,15 @@ export function WorkspaceProvider({ children }: { children: ReactNode }) {const canManage = role === 'owner' || role === 'manager'const canWrite = role === 'owner' || role === 'manager' || role === 'editor'+ const enabledModules = useMemo(+ () => (current?.enabled_modules ?? []) as ModuleId[],+ [current],+ )+ const hasModule = useCallback(+ (id: ModuleId) => enabledModules.includes(id),+ [enabledModules],+ )+return (<WorkspaceContext.Providervalue={{@@ -105,6 +127,8 @@ export function WorkspaceProvider({ children }: { children: ReactNode }) {role,canManage,canWrite,+ enabledModules,+ hasModule,}}>{children}diff --git a/frontend/src/lib/modules.ts b/frontend/src/lib/modules.tsnew file mode 100644index 00000000..4198fe19--- /dev/null+++ b/frontend/src/lib/modules.ts@@ -0,0 +1,29 @@+/**+ * Mirror of the backend's `ModuleId` (`services/module_service.py`).+ *+ * This file names the modules. It never decides which ones a workspace+ * gets — that is resolved server-side and arrives as+ * `workspace.enabled_modules`. Two copies of the rule would drift, and+ * the drift shows up as a user seeing a module the server thinks is off.+ */+export const MODULE_IDS = [+ 'transactions',+ 'accounts',+ 'import',+ 'reports',+ 'assets',+ 'budgets',+ 'goals',+ 'recurring',+ 'categories',+ 'payees',+ 'split_groups',+ 'rules',+ 'invoices',+] as const++export type ModuleId = (typeof MODULE_IDS)[number]++export function isModuleId(value: string): value is ModuleId {+ return (MODULE_IDS as readonly string[]).includes(value)+}diff --git a/frontend/src/lib/nav-items.test.ts b/frontend/src/lib/nav-items.test.tsnew file mode 100644index 00000000..29a60a38--- /dev/null+++ b/frontend/src/lib/nav-items.test.ts@@ -0,0 +1,114 @@+import { describe, it, expect } from 'vitest'+import { navItems, visibleNavItems, type NavItem } from './nav-items'+import { MODULE_IDS, type ModuleId } from './modules'++const all = () => true+const none = () => false+const allExcept =+ (...off: ModuleId[]) =>+ (id: ModuleId) =>+ !off.includes(id)++// Mirrors the backend's PersonalPolicy result. Spelled out rather than+// derived, so a change that takes a link away from existing users has+// to be a deliberate edit here.+const PERSONAL_MODULES: ModuleId[] = [+ 'transactions',+ 'accounts',+ 'import',+ 'reports',+ 'assets',+ 'budgets',+ 'goals',+ 'recurring',+ 'categories',+ 'payees',+ 'split_groups',+ 'rules',+]++const linkKeys = (items: NavItem[]) =>+ items.filter((i) => i.type === 'link').map((i) => i.key)++describe('nav catalog', () => {+ it('maps every link to a known module', () => {+ for (const item of navItems) {+ if (item.type !== 'link') continue+ expect(MODULE_IDS).toContain(item.module)+ }+ })++ it('has a link for every module in the catalog', () => {+ const covered = navItems.filter((i) => i.type === 'link').map((i) => i.module)+ expect([...covered].sort()).toEqual([...MODULE_IDS].sort())+ })++ it('gives every link a distinct module', () => {+ const covered = navItems.filter((i) => i.type === 'link').map((i) => i.module)+ expect(new Set(covered).size).toBe(covered.length)+ })+})++describe('visibleNavItems', () => {+ it('renders a personal workspace exactly as before modules existed', () => {+ const personal = visibleNavItems(navItems, (id) => PERSONAL_MODULES.includes(id))+ expect(linkKeys(personal)).toEqual([+ 'transactions',+ 'accounts',+ 'import',+ 'reports',+ 'assets',+ 'budgets',+ 'goals',+ 'recurring',+ 'categories',+ 'payees',+ 'splitGroups',+ 'rules',+ ])+ // All three section headers survive.+ expect(personal.filter((i) => i.type === 'separator')).toHaveLength(3)+ })++ it('adds invoices for a workspace that has it', () => {+ const business = visibleNavItems(navItems, all)+ expect(linkKeys(business)).toContain('invoices')+ // And it does not disturb the rest of the order.+ expect(linkKeys(business).indexOf('invoices')).toBe(1)+ })++ it('hides a section header once its last link goes', () => {+ const items: NavItem[] = [+ { type: 'separator', labelKey: 'a' },+ { type: 'link', key: 'one', path: '/1', icon: () => null, module: 'reports' },+ { type: 'separator', labelKey: 'b' },+ { type: 'link', key: 'two', path: '/2', icon: () => null, module: 'assets' },+ ]+ const result = visibleNavItems(items, allExcept('reports'))+ expect(result.map((i) => (i.type === 'separator' ? i.labelKey : i.key))).toEqual([+ 'b',+ 'two',+ ])+ })++ it('keeps a section header while any of its links remain', () => {+ const result = visibleNavItems(navItems, allExcept('transactions', 'invoices'))+ const labels = result.filter((i) => i.type === 'separator').map((i) => i.labelKey)+ expect(labels).toContain('nav.groupAccounts')+ expect(linkKeys(result)).toContain('accounts')+ })++ it('drops every header when no module is on', () => {+ expect(visibleNavItems(navItems, none)).toEqual([])+ })++ it('leaves a trailing header out rather than dangling', () => {+ const items: NavItem[] = [+ { type: 'link', key: 'one', path: '/1', icon: () => null, module: 'reports' },+ { type: 'separator', labelKey: 'trailing' },+ { type: 'link', key: 'two', path: '/2', icon: () => null, module: 'assets' },+ ]+ const result = visibleNavItems(items, allExcept('assets'))+ expect(result.map((i) => (i.type === 'separator' ? i.labelKey : i.key))).toEqual(['one'])+ })+})diff --git a/frontend/src/lib/nav-items.ts b/frontend/src/lib/nav-items.tsnew file mode 100644index 00000000..5fedf243--- /dev/null+++ b/frontend/src/lib/nav-items.ts@@ -0,0 +1,72 @@+import {+ ArrowLeftRight,+ BarChart3,+ Building2,+ Landmark,+ PiggyBank,+ Receipt,+ Repeat,+ SlidersHorizontal,+ Split,+ Tag,+ Target,+ Upload,+ Users,+} from 'lucide-react'+// Relative, not aliased: this file is pulled into the test project,+// which compiles without the `@/*` path mapping (see tsconfig.node.json).+import type { ModuleId } from './modules'++/**+ * Sidebar destinations. Lives outside `app-layout.tsx` so the filtering+ * below can be tested without mounting the whole layout.+ *+ * Every link carries the module it belongs to. That is what makes the+ * "a personal workspace shows exactly what it always showed" guarantee+ * checkable rather than aspirational.+ */+export type NavItem =+ | { type: 'link'; key: string; path: string; icon: React.ElementType; module: ModuleId }+ | { type: 'separator'; labelKey: string }++export const navItems: NavItem[] = [+ // The dashboard ("Painel") is now reachable by clicking the Securo+ // logo + name in the sidebar header — no dedicated menu item to keep+ // the sidebar focused on the main destinations. Transactions sits+ // inside the ACCOUNTS section since it's account-scoped data.+ { type: 'separator', labelKey: 'nav.groupAccounts' },+ { type: 'link', key: 'transactions', path: '/transactions', icon: ArrowLeftRight, module: 'transactions' },+ { type: 'link', key: 'invoices', path: '/invoices', icon: Receipt, module: 'invoices' },+ { type: 'link', key: 'accounts', path: '/accounts', icon: Building2, module: 'accounts' },+ { type: 'link', key: 'import', path: '/import', icon: Upload, module: 'import' },+ { type: 'separator', labelKey: 'nav.groupAnalysis' },+ { type: 'link', key: 'reports', path: '/reports', icon: BarChart3, module: 'reports' },+ { type: 'link', key: 'assets', path: '/assets', icon: Landmark, module: 'assets' },+ { type: 'separator', labelKey: 'nav.groupSetup' },+ { type: 'link', key: 'budgets', path: '/budgets', icon: PiggyBank, module: 'budgets' },+ { type: 'link', key: 'goals', path: '/goals', icon: Target, module: 'goals' },+ { type: 'link', key: 'recurring', path: '/recurring', icon: Repeat, module: 'recurring' },+ { type: 'link', key: 'categories', path: '/categories', icon: Tag, module: 'categories' },+ { type: 'link', key: 'payees', path: '/payees', icon: Users, module: 'payees' },+ { type: 'link', key: 'splitGroups', path: '/groups', icon: Split, module: 'split_groups' },+ { type: 'link', key: 'rules', path: '/rules', icon: SlidersHorizontal, module: 'rules' },+]++/**+ * Drop links whose module is off, then drop any section header left+ * with nothing under it. Without the second pass, hiding a section's+ * only link leaves a floating heading.+ */+export function visibleNavItems(+ items: NavItem[],+ hasModule: (id: ModuleId) => boolean,+): NavItem[] {+ const kept = items.filter((item) => item.type !== 'link' || hasModule(item.module))+ return kept.filter((item, index) => {+ if (item.type !== 'separator') return true+ // Links always follow their own header, so the item right after a+ // header is either one of its links or the next header.+ const next = kept[index + 1]+ return next !== undefined && next.type === 'link'+ })+}diff --git a/frontend/src/locales/de.json b/frontend/src/locales/de.jsonindex 54b1c343..99ace48d 100644--- a/frontend/src/locales/de.json+++ b/frontend/src/locales/de.json@@ -103,6 +103,7 @@"nav": {"dashboard": "Dashboard","transactions": "Transaktionen",+ "invoices": "Rechnungen","accounts": "Konten","collections": "Sammlungen","import": "Importieren",@@ -124,6 +125,10 @@"agents": "Agenten","aiAgents": "KI-Agenten"},+ "invoices": {+ "title": "Rechnungen",+ "comingNext": "Stelle deinen Kunden Rechnungen und behalte im Blick, was bezahlt ist und was offen bleibt. Das ist das Nächste, was gebaut wird."+ },"collections": {"title": "Sammlungen","subtitle": "Gruppiere deine Konten in benannte Sammlungen (z.B. Geschäftlich, Langfristig, Täglich), um dein Dashboard, deine Berichte und Transaktionen zu filtern.",diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.jsonindex a9008cea..801f0460 100644--- a/frontend/src/locales/en.json+++ b/frontend/src/locales/en.json@@ -103,6 +103,7 @@"nav": {"dashboard": "Dashboard","transactions": "Transactions",+ "invoices": "Invoices","accounts": "Accounts","collections": "Collections","import": "Import",@@ -124,6 +125,10 @@"agents": "Agents","aiAgents": "AI Agents"},+ "invoices": {+ "title": "Invoices",+ "comingNext": "Bill your clients and keep track of what has been paid and what is still open. This is the next thing being built."+ },"collections": {"title": "Collections","subtitle": "Group your accounts into named collections (e.g. Business, Long-term, Daily) to filter your dashboard, reports and transactions.",diff --git a/frontend/src/locales/es.json b/frontend/src/locales/es.jsonindex b31a7550..46c2eeea 100644--- a/frontend/src/locales/es.json+++ b/frontend/src/locales/es.json@@ -103,6 +103,7 @@"nav": {"dashboard": "Inicio","transactions": "Transacciones",+ "invoices": "Facturas","accounts": "Cuentas","collections": "Colecciones","import": "Importar",@@ -124,6 +125,10 @@"agents": "Agentes","aiAgents": "Agentes IA"},+ "invoices": {+ "title": "Facturas",+ "comingNext": "Cobra a tus clientes y controla lo que ya se pagó y lo que sigue pendiente. Es lo próximo que se está construyendo."+ },"collections": {"title": "Colecciones","subtitle": "Agrupa tus cuentas en colecciones con nombre (p. ej. Empresa, Largo plazo, Diario) para filtrar el panel, los informes y las transacciones.",diff --git a/frontend/src/locales/fr.json b/frontend/src/locales/fr.jsonindex c8391bb9..3563c124 100644--- a/frontend/src/locales/fr.json+++ b/frontend/src/locales/fr.json@@ -103,6 +103,7 @@"nav": {"dashboard": "Tableau de bord","transactions": "Transactions",+ "invoices": "Factures","accounts": "Comptes","collections": "Collections","import": "Importer",@@ -124,6 +125,10 @@"agents": "Agents","aiAgents": "Agents IA"},+ "invoices": {+ "title": "Factures",+ "comingNext": "Facturez vos clients et suivez ce qui a été payé et ce qui reste ouvert. C'est la prochaine chose en construction."+ },"collections": {"title": "Collections","subtitle": "Regroupez vos comptes dans des collections nommées (ex. Professionnel, Long terme, Quotidien) pour filtrer votre tableau de bord, vos rapports et vos transactions.",diff --git a/frontend/src/locales/it.json b/frontend/src/locales/it.jsonindex 688b0102..f1bcae01 100644--- a/frontend/src/locales/it.json+++ b/frontend/src/locales/it.json@@ -103,6 +103,7 @@"nav": {"dashboard": "Dashboard","transactions": "Transazioni",+ "invoices": "Fatture","accounts": "Conti","collections": "Collezioni","import": "Importa",@@ -124,6 +125,10 @@"agents": "Agenti","aiAgents": "Agenti IA"},+ "invoices": {+ "title": "Fatture",+ "comingNext": "Fattura i tuoi clienti e tieni traccia di cosa è stato pagato e cosa è ancora aperto. È la prossima cosa in costruzione."+ },"collections": {"title": "Collezioni","subtitle": "Raggruppa i tuoi conti in collezioni con nome (es. Azienda, Lungo termine, Quotidiano) per filtrare dashboard, report e transazioni.",diff --git a/frontend/src/locales/pl.json b/frontend/src/locales/pl.jsonindex 228b1604..e7bb15cc 100644--- a/frontend/src/locales/pl.json+++ b/frontend/src/locales/pl.json@@ -103,6 +103,7 @@"nav": {"dashboard": "Pulpit","transactions": "Transakcje",+ "invoices": "Faktury","accounts": "Konta","import": "Import","rules": "Reguły",@@ -124,6 +125,10 @@"aiAgents": "Agenci AI","collections": "Kolekcje"},+ "invoices": {+ "title": "Faktury",+ "comingNext": "Wystawiaj faktury klientom i śledź, co zostało zapłacone, a co wciąż jest otwarte. To następna rzecz w budowie."+ },"collections": {"title": "Kolekcje","subtitle": "Pogrupuj swoje konta w nazwane kolekcje (np. Firma, Długoterminowe, Codzienne), aby filtrować pulpit, raporty i transakcje.",diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.jsonindex cbed929d..d7352ef5 100644--- a/frontend/src/locales/pt-BR.json+++ b/frontend/src/locales/pt-BR.json@@ -103,6 +103,7 @@"nav": {"dashboard": "Painel","transactions": "Transações",+ "invoices": "Cobranças","accounts": "Contas","collections": "Coleções","import": "Importar",@@ -124,6 +125,10 @@"agents": "Agentes","aiAgents": "Agentes IA"},+ "invoices": {+ "title": "Cobranças",+ "comingNext": "Cobre seus clientes e acompanhe o que já foi pago e o que continua em aberto. É a próxima coisa sendo construída."+ },"collections": {"title": "Coleções","subtitle": "Agrupe suas contas em coleções nomeadas (ex.: Empresa, Longo prazo, Dia a dia) para filtrar o painel, relatórios e transações.",diff --git a/frontend/src/locales/pt-PT.json b/frontend/src/locales/pt-PT.jsonindex a75f6e49..fc5f8412 100644--- a/frontend/src/locales/pt-PT.json+++ b/frontend/src/locales/pt-PT.json@@ -103,6 +103,7 @@"nav": {"dashboard": "Painel","transactions": "Transações",+ "invoices": "Cobranças","accounts": "Contas","collections": "Coleções","import": "Importar",@@ -124,6 +125,10 @@"agents": "Agentes","aiAgents": "Agentes de IA"},+ "invoices": {+ "title": "Cobranças",+ "comingNext": "Cobra os teus clientes e acompanha o que já foi pago e o que continua em aberto. É a próxima coisa a ser construída."+ },"collections": {"title": "Coleções","subtitle": "Agrupa as tuas contas em coleções (ex.: Empresa, Longo prazo, Dia a dia) para filtrar o painel, os relatórios e as transações.",diff --git a/frontend/src/locales/ru.json b/frontend/src/locales/ru.jsonindex bccc5d03..b057b6d0 100644--- a/frontend/src/locales/ru.json+++ b/frontend/src/locales/ru.json@@ -103,6 +103,7 @@"nav": {"dashboard": "Панель","transactions": "Транзакции",+ "invoices": "Счета","accounts": "Счета","collections": "Коллекции","import": "Импорт",@@ -124,6 +125,10 @@"agents": "Агенты","aiAgents": "ИИ-агенты"},+ "invoices": {+ "title": "Счета",+ "comingNext": "Выставляйте счета клиентам и следите за тем, что оплачено, а что остаётся открытым. Это следующее, что будет сделано."+ },"collections": {"title": "Коллекции","subtitle": "Группируйте счета в именованные коллекции (например, Бизнес, Долгосрочные, Ежедневные), чтобы фильтровать панель, отчёты и транзакции.",diff --git a/frontend/src/locales/uk.json b/frontend/src/locales/uk.jsonindex 3028c346..1c6172b9 100644--- a/frontend/src/locales/uk.json+++ b/frontend/src/locales/uk.json@@ -103,6 +103,7 @@"nav": {"dashboard": "Панель","transactions": "Транзакції",+ "invoices": "Рахунки","accounts": "Рахунки","collections": "Колекції","import": "Імпорт",@@ -124,6 +125,10 @@"agents": "Агенти","aiAgents": "ШІ-агенти"},+ "invoices": {+ "title": "Рахунки",+ "comingNext": "Виставляйте рахунки клієнтам і стежте за тим, що оплачено, а що залишається відкритим. Це наступне, що буде зроблено."+ },"collections": {"title": "Колекції","subtitle": "Групуйте рахунки в іменовані колекції (наприклад, Бізнес, Довгострокові, Щоденні), щоб фільтрувати панель, звіти та транзакції.",diff --git a/frontend/src/pages/invoices.tsx b/frontend/src/pages/invoices.tsxnew file mode 100644index 00000000..f1b99ac4--- /dev/null+++ b/frontend/src/pages/invoices.tsx@@ -0,0 +1,30 @@+import { useTranslation } from 'react-i18next'+import { Receipt } from 'lucide-react'++/**+ * Placeholder until the invoices ledger lands. Deliberately honest+ * about being empty rather than showing a fake table: the nav entry+ * exists so the module boundary is real and testable.+ */+export default function InvoicesPage() {+ const { t } = useTranslation()++ return (+ <div className="container max-w-5xl py-8">+ <div className="rounded-xl border bg-card p-10 flex flex-col items-center text-center gap-3">+ <div className="h-12 w-12 rounded-xl bg-primary/10 flex items-center justify-center">+ <Receipt className="h-6 w-6 text-primary" />+ </div>+ <h1 className="text-xl font-semibold">+ {t('invoices.title', 'Invoices')}+ </h1>+ <p className="text-sm text-muted-foreground max-w-md leading-relaxed">+ {t(+ 'invoices.comingNext',+ 'Bill your clients and keep track of what has been paid and what is still open. This is the next thing being built.',+ )}+ </p>+ </div>+ </div>+ )+}diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.tsindex ca47c8f0..e53926a8 100644--- a/frontend/src/types/index.ts+++ b/frontend/src/types/index.ts@@ -62,6 +62,8 @@ export interface Workspace {created_by_user_id: string | nullmanaged_by_user_id: string | nullrole: WorkspaceRole | null+ /** Modules this workspace shows. Resolved server-side; see lib/modules.ts. */+ enabled_modules: string[]}export interface WorkspaceMember {