Open-source personal finance manager. Self-hosted, privacy-first.
feat: workspaces with members and roles (#227)
Tássio Noronhad1bda2fc4ca0
diff --git a/backend/alembic/versions/052_add_workspaces.py b/backend/alembic/versions/052_add_workspaces.pynew file mode 100644index 00000000..d16eee9a--- /dev/null+++ b/backend/alembic/versions/052_add_workspaces.py@@ -0,0 +1,308 @@+"""add workspaces + workspace_members + workspace_id on financial tables++Revision ID: 052+Revises: 051+Create Date: 2026-05-26++Strategy+--------+1. Create `workspaces` + `workspace_members`.+2. For every existing user, insert one Personal workspace and an `owner`+ membership row.+3. Add nullable `workspace_id` to every financial table.+4. Backfill `workspace_id` from `user_id` -> that user's Personal workspace.+ For tables without a direct `user_id` (asset_value, group_member,+ group_settlement, transaction_split, payee_mapping), join through the+ owning parent.+5. Set `workspace_id` NOT NULL + index + FK.++`user_id` columns are kept in place. They now mean "created_by" / owner+for entities where authorship is meaningful (transactions, groups). For+purely workspace-shared catalog entities (categories, payees, rules,+budgets, goals), `user_id` becomes audit-only and stops being used for+visibility filtering — the query layer pivots to `workspace_id`.+"""++from alembic import op+import sqlalchemy as sa+++revision = "052"+down_revision = "051"+branch_labels = None+depends_on = None+++# Tables that get a direct workspace_id column backfilled from their own+# user_id. Order doesn't matter for the schema change but matters for the+# backfill — none of these depend on each other.+TABLES_WITH_USER_ID = [+ "accounts",+ "asset_groups",+ "assets",+ "bank_connections",+ "budgets",+ "categories",+ "category_groups",+ "credit_card_bills",+ "goals",+ "groups",+ "import_logs",+ "payees",+ "recurring_transactions",+ "rules",+ "transaction_attachments",+ "transactions",+]+++def upgrade() -> None:+ # 1. workspaces+ op.create_table(+ "workspaces",+ sa.Column("id", sa.dialects.postgresql.UUID(as_uuid=True), primary_key=True),+ sa.Column("name", sa.String(100), nullable=False),+ sa.Column("kind", sa.String(30), nullable=False, server_default="personal"),+ sa.Column(+ "created_by_user_id",+ sa.dialects.postgresql.UUID(as_uuid=True),+ sa.ForeignKey("users.id", ondelete="SET NULL"),+ nullable=True,+ ),+ sa.Column("is_archived", sa.Boolean, nullable=False, server_default="false"),+ sa.Column("default_currency", sa.String(3), nullable=False, server_default="USD"),+ sa.Column("locale", sa.String(10), nullable=True),+ sa.Column("icon", sa.String(50), nullable=True),+ sa.Column("color", sa.String(7), nullable=True),+ sa.Column("created_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),+ )+ op.create_index("ix_workspaces_kind", "workspaces", ["kind"])++ # 2. workspace_members+ op.create_table(+ "workspace_members",+ sa.Column("id", sa.dialects.postgresql.UUID(as_uuid=True), primary_key=True),+ sa.Column(+ "workspace_id",+ sa.dialects.postgresql.UUID(as_uuid=True),+ sa.ForeignKey("workspaces.id", ondelete="CASCADE"),+ nullable=False,+ ),+ sa.Column(+ "user_id",+ sa.dialects.postgresql.UUID(as_uuid=True),+ sa.ForeignKey("users.id", ondelete="CASCADE"),+ nullable=False,+ ),+ sa.Column("role", sa.String(20), nullable=False, server_default="owner"),+ sa.Column(+ "invited_by_user_id",+ sa.dialects.postgresql.UUID(as_uuid=True),+ sa.ForeignKey("users.id", ondelete="SET NULL"),+ nullable=True,+ ),+ sa.Column("joined_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),+ sa.UniqueConstraint("workspace_id", "user_id", name="uq_workspace_member"),+ )+ op.create_index("ix_workspace_members_user", "workspace_members", ["user_id"])+ op.create_index("ix_workspace_members_workspace", "workspace_members", ["workspace_id"])++ # 3. Backfill: one Personal workspace per existing user + owner membership.+ # Localized default name based on the user's `preferences->>'language'`.+ # The use of gen_random_uuid() requires the pgcrypto extension; Postgres+ # 13+ ships it but make the extension explicit to be safe.+ op.execute("CREATE EXTENSION IF NOT EXISTS pgcrypto")+ op.execute(+ """+ INSERT INTO workspaces (id, name, kind, created_by_user_id, default_currency, locale)+ SELECT+ gen_random_uuid(),+ CASE+ WHEN COALESCE(preferences->>'language', 'en') LIKE 'pt%' THEN 'Pessoal'+ ELSE 'Personal'+ END,+ 'personal',+ id,+ COALESCE(preferences->>'currency_display', 'USD'),+ COALESCE(preferences->>'language', 'en')+ FROM users+ """+ )+ op.execute(+ """+ INSERT INTO workspace_members (id, workspace_id, user_id, role)+ SELECT+ gen_random_uuid(),+ w.id,+ w.created_by_user_id,+ 'owner'+ FROM workspaces w+ WHERE w.created_by_user_id IS NOT NULL+ """+ )++ # 4. Add nullable workspace_id to every financial table.+ for tbl in TABLES_WITH_USER_ID:+ op.add_column(+ tbl,+ sa.Column(+ "workspace_id",+ sa.dialects.postgresql.UUID(as_uuid=True),+ sa.ForeignKey("workspaces.id", ondelete="CASCADE"),+ nullable=True,+ ),+ )++ # 5. Backfill workspace_id from each row's user_id (each user has+ # exactly one Personal workspace post-step-3, so the join is 1:1).+ for tbl in TABLES_WITH_USER_ID:+ op.execute(+ f"""+ UPDATE {tbl} t+ SET workspace_id = w.id+ FROM workspaces w+ WHERE w.created_by_user_id = t.user_id+ AND w.kind = 'personal'+ """+ )++ # 6. NOT NULL + index.+ for tbl in TABLES_WITH_USER_ID:+ op.alter_column(tbl, "workspace_id", nullable=False)+ op.create_index(f"ix_{tbl}_workspace_id", tbl, ["workspace_id"])++ # 7. Tables without user_id but with a parent FK — fill workspace_id+ # transitively. Useful so per-row visibility checks don't have to+ # join through the parent every time.+ # asset_values -> assets.workspace_id+ op.add_column(+ "asset_values",+ sa.Column(+ "workspace_id",+ sa.dialects.postgresql.UUID(as_uuid=True),+ sa.ForeignKey("workspaces.id", ondelete="CASCADE"),+ nullable=True,+ ),+ )+ op.execute(+ "UPDATE asset_values av SET workspace_id = a.workspace_id "+ "FROM assets a WHERE a.id = av.asset_id"+ )+ op.alter_column("asset_values", "workspace_id", nullable=False)+ op.create_index("ix_asset_values_workspace_id", "asset_values", ["workspace_id"])++ # group_members -> groups.workspace_id+ op.add_column(+ "group_members",+ sa.Column(+ "workspace_id",+ sa.dialects.postgresql.UUID(as_uuid=True),+ sa.ForeignKey("workspaces.id", ondelete="CASCADE"),+ nullable=True,+ ),+ )+ op.execute(+ "UPDATE group_members gm SET workspace_id = g.workspace_id "+ "FROM groups g WHERE g.id = gm.group_id"+ )+ op.alter_column("group_members", "workspace_id", nullable=False)+ op.create_index("ix_group_members_workspace_id", "group_members", ["workspace_id"])++ # group_settlements -> groups.workspace_id+ op.add_column(+ "group_settlements",+ sa.Column(+ "workspace_id",+ sa.dialects.postgresql.UUID(as_uuid=True),+ sa.ForeignKey("workspaces.id", ondelete="CASCADE"),+ nullable=True,+ ),+ )+ op.execute(+ "UPDATE group_settlements s SET workspace_id = g.workspace_id "+ "FROM groups g WHERE g.id = s.group_id"+ )+ op.alter_column("group_settlements", "workspace_id", nullable=False)+ op.create_index("ix_group_settlements_workspace_id", "group_settlements", ["workspace_id"])++ # transaction_splits -> transactions.workspace_id+ op.add_column(+ "transaction_splits",+ sa.Column(+ "workspace_id",+ sa.dialects.postgresql.UUID(as_uuid=True),+ sa.ForeignKey("workspaces.id", ondelete="CASCADE"),+ nullable=True,+ ),+ )+ op.execute(+ "UPDATE transaction_splits ts SET workspace_id = t.workspace_id "+ "FROM transactions t WHERE t.id = ts.transaction_id"+ )+ op.alter_column("transaction_splits", "workspace_id", nullable=False)+ op.create_index("ix_transaction_splits_workspace_id", "transaction_splits", ["workspace_id"])++ # payee_mapping -> payees.workspace_id (via target_id which references payees)+ # The mapping has its own user_id today so handle it like the rest;+ # check first that the column exists.+ bind = op.get_bind()+ has_user_id_on_mapping = bind.execute(+ sa.text(+ "SELECT 1 FROM information_schema.columns "+ "WHERE table_name='payee_mapping' AND column_name='user_id'"+ )+ ).scalar()+ if has_user_id_on_mapping:+ op.add_column(+ "payee_mapping",+ sa.Column(+ "workspace_id",+ sa.dialects.postgresql.UUID(as_uuid=True),+ sa.ForeignKey("workspaces.id", ondelete="CASCADE"),+ nullable=True,+ ),+ )+ op.execute(+ """+ UPDATE payee_mapping pm+ SET workspace_id = w.id+ FROM workspaces w+ WHERE w.created_by_user_id = pm.user_id+ AND w.kind = 'personal'+ """+ )+ op.alter_column("payee_mapping", "workspace_id", nullable=False)+ op.create_index("ix_payee_mapping_workspace_id", "payee_mapping", ["workspace_id"])+++def downgrade() -> None:+ # Drop workspace_id columns first (FKs require this), then the+ # workspace tables themselves.+ extra_tables = [+ "asset_values",+ "group_members",+ "group_settlements",+ "transaction_splits",+ "payee_mapping",+ ]+ bind = op.get_bind()+ for tbl in TABLES_WITH_USER_ID + extra_tables:+ has_col = bind.execute(+ sa.text(+ f"SELECT 1 FROM information_schema.columns "+ f"WHERE table_name='{tbl}' AND column_name='workspace_id'"+ )+ ).scalar()+ if not has_col:+ continue+ try:+ op.drop_index(f"ix_{tbl}_workspace_id", table_name=tbl)+ except Exception:+ pass+ op.drop_column(tbl, "workspace_id")++ op.drop_index("ix_workspace_members_workspace", table_name="workspace_members")+ op.drop_index("ix_workspace_members_user", table_name="workspace_members")+ op.drop_table("workspace_members")+ op.drop_index("ix_workspaces_kind", table_name="workspaces")+ op.drop_table("workspaces")diff --git a/backend/alembic/versions/053_workspace_managed_by.py b/backend/alembic/versions/053_workspace_managed_by.pynew file mode 100644index 00000000..dbfc7a04--- /dev/null+++ b/backend/alembic/versions/053_workspace_managed_by.py@@ -0,0 +1,44 @@+"""add managed_by_user_id to workspaces++Revision ID: 053+Revises: 052+Create Date: 2026-05-26++Adds a nullable FK that expresses "this workspace is administered by+user X from outside its membership roster." The managed-by user has+effective owner rights in the workspace without being listed as a+member. Designed for setups where one user provisions and operates+workspaces on behalf of other people (e.g. external collaborators who+work across several distinct sets of books).+"""++from alembic import op+import sqlalchemy as sa+++revision = "053"+down_revision = "052"+branch_labels = None+depends_on = None+++def upgrade() -> None:+ op.add_column(+ "workspaces",+ sa.Column(+ "managed_by_user_id",+ sa.dialects.postgresql.UUID(as_uuid=True),+ sa.ForeignKey("users.id", ondelete="SET NULL"),+ nullable=True,+ ),+ )+ op.create_index(+ "ix_workspaces_managed_by_user_id",+ "workspaces",+ ["managed_by_user_id"],+ )+++def downgrade() -> None:+ op.drop_index("ix_workspaces_managed_by_user_id", table_name="workspaces")+ op.drop_column("workspaces", "managed_by_user_id")diff --git a/backend/alembic/versions/054_agents_workspace_id.py b/backend/alembic/versions/054_agents_workspace_id.pynew file mode 100644index 00000000..4d317971--- /dev/null+++ b/backend/alembic/versions/054_agents_workspace_id.py@@ -0,0 +1,55 @@+"""add workspace_id to agents + conversations++Revision ID: 054+Revises: 053+Create Date: 2026-05-26++Agents are tenant-scoped: a workspace's own assistants don't show up+in another workspace. Conversations inherit the workspace from the+agent they were started against — switching workspaces during a chat+isn't supported (the agent itself doesn't follow).++Backfill: every existing agent + conversation reparents to its owning+user's first (oldest) workspace. After backfill the column is NOT NULL+and indexed.+"""++from alembic import op+import sqlalchemy as sa+++revision = "054"+down_revision = "053"+branch_labels = None+depends_on = None+++def upgrade() -> None:+ for table in ("agents", "agent_conversations"):+ op.add_column(+ table,+ sa.Column(+ "workspace_id",+ sa.dialects.postgresql.UUID(as_uuid=True),+ sa.ForeignKey("workspaces.id", ondelete="CASCADE"),+ nullable=True,+ ),+ )+ # Backfill via the user's first workspace.+ op.execute(+ f"""+ UPDATE {table} t+ SET workspace_id = w.id+ FROM workspaces w+ WHERE w.created_by_user_id = t.user_id+ AND w.kind = 'personal'+ """+ )+ op.alter_column(table, "workspace_id", nullable=False)+ op.create_index(f"ix_{table}_workspace_id", table, ["workspace_id"])+++def downgrade() -> None:+ for table in ("agents", "agent_conversations"):+ op.drop_index(f"ix_{table}_workspace_id", table_name=table)+ op.drop_column(table, "workspace_id")diff --git a/backend/app/agents/api/agents.py b/backend/app/agents/api/agents.pyindex 98c5d305..5f492e39 100644--- a/backend/app/agents/api/agents.py+++ b/backend/app/agents/api/agents.py@@ -9,9 +9,12 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom app.agents.mcp.client import MCPRegistryfrom app.agents.schemas.agent import AgentCreate, AgentRead, AgentToolToggle, AgentUpdatefrom app.agents.services import agent_service-from app.core.auth import current_active_userfrom app.core.database import get_async_session-from app.models.user import User+from app.core.workspace_context import (+ WorkspaceContext,+ current_workspace,+ current_writable_workspace,+)router = APIRouter(prefix="/api/agents", tags=["agents"])@@ -19,20 +22,22 @@ router = APIRouter(prefix="/api/agents", tags=["agents"])@router.get("", response_model=list[AgentRead])async def list_agents(include_archived: bool = False,+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- return await agent_service.list_agents(session, user.id, include_archived=include_archived)+ return await agent_service.list_agents(+ session, ctx.workspace.id, include_archived=include_archived+ )@router.get("/default", response_model=AgentRead)async def get_default_agent(+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- """Used by the global slide-over chat panel. Returns the user-flagged- default agent, or the most-recently-created one as a fallback."""- agent = await agent_service.get_default_agent(session, user.id)+ """Used by the global slide-over chat panel. Returns the workspace's+ flagged default agent, or its most-recently-created one as a fallback."""+ agent = await agent_service.get_default_agent(session, ctx.workspace.id)if agent is None:raise HTTPException(status_code=404, detail="no agent available")return agent@@ -41,19 +46,19 @@ async def get_default_agent(@router.post("", response_model=AgentRead, status_code=status.HTTP_201_CREATED)async def create_agent(data: AgentCreate,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- return await agent_service.create_agent(session, user.id, data)+ return await agent_service.create_agent(session, ctx.workspace.id, ctx.user_id, data)@router.get("/{agent_id}", response_model=AgentRead)async def get_agent(agent_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- agent = await agent_service.get_agent(session, agent_id, user.id)+ agent = await agent_service.get_agent(session, agent_id, ctx.workspace.id)if agent is None:raise HTTPException(status_code=404, detail="agent not found")return agent@@ -63,10 +68,10 @@ async def get_agent(async def update_agent(agent_id: uuid.UUID,data: AgentUpdate,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- agent = await agent_service.update_agent(session, agent_id, user.id, data)+ agent = await agent_service.update_agent(session, agent_id, ctx.workspace.id, data)if agent is None:raise HTTPException(status_code=404, detail="agent not found")return agent@@ -75,10 +80,10 @@ async def update_agent(@router.delete("/{agent_id}", status_code=status.HTTP_204_NO_CONTENT)async def delete_agent(agent_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- ok = await agent_service.delete_agent(session, agent_id, user.id)+ ok = await agent_service.delete_agent(session, agent_id, ctx.workspace.id)if not ok:raise HTTPException(status_code=404, detail="agent not found")@@ -86,19 +91,19 @@ async def delete_agent(@router.get("/{agent_id}/tools")async def get_agent_tools(agent_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),) -> dict[str, Any]:"""Discover all tools from registered MCP servers and merge with theper-agent enablement state. Returns shape:{ servers: [{name}], tools: [{server, name, description, enabled, is_proposal}] }"""- agent = await agent_service.get_agent(session, agent_id, user.id)+ agent = await agent_service.get_agent(session, agent_id, ctx.workspace.id)if agent is None:raise HTTPException(status_code=404, detail="agent not found")mcp = MCPRegistry()- handles = await mcp.discover(user_id=user.id)+ handles = await mcp.discover(user_id=ctx.user_id, workspace_id=ctx.workspace.id)rows = await agent_service.list_tools(session, agent_id)enabled_lookup = {(r.server, r.tool_name): r.enabled for r in rows}no_explicit_rows = len(rows) == 0@@ -120,10 +125,10 @@ async def get_agent_tools(async def put_agent_tools(agent_id: uuid.UUID,items: list[AgentToolToggle],+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- agent = await agent_service.get_agent(session, agent_id, user.id)+ agent = await agent_service.get_agent(session, agent_id, ctx.workspace.id)if agent is None:raise HTTPException(status_code=404, detail="agent not found")await agent_service.replace_tool_enablement(diff --git a/backend/app/agents/api/chat.py b/backend/app/agents/api/chat.pyindex 887f1c0e..a15e2ee2 100644--- a/backend/app/agents/api/chat.py+++ b/backend/app/agents/api/chat.py@@ -19,9 +19,8 @@ from starlette.responses import StreamingResponsefrom app.agents.runtime.executor import AgentExecutor, ExecutorEventfrom app.agents.schemas.conversation import SendMessageRequestfrom app.agents.services import agent_service, conversation_service-from app.core.auth import current_active_userfrom app.core.database import get_async_session-from app.models.user import User+from app.core.workspace_context import WorkspaceContext, current_workspacerouter = APIRouter(prefix="/api/agents", tags=["agents"])@@ -35,21 +34,25 @@ def _format_event(event: ExecutorEvent) -> bytes:async def chat(agent_id: uuid.UUID,body: SendMessageRequest,+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- agent = await agent_service.get_agent(session, agent_id, user.id)+ agent = await agent_service.get_agent(session, agent_id, ctx.workspace.id)if agent is None:raise HTTPException(status_code=404, detail="agent not found")conv = Noneif body.conversation_id:- conv = await conversation_service.get_conversation(session, body.conversation_id, user.id)+ conv = await conversation_service.get_conversation(session, body.conversation_id, ctx.workspace.id)if conv is None or conv.agent_id != agent_id:raise HTTPException(status_code=404, detail="conversation not found")if conv is None:conv = await conversation_service.create_conversation(- session, user_id=user.id, agent_id=agent_id, channel=body.channel,+ session,+ workspace_id=ctx.workspace.id,+ user_id=ctx.user_id,+ agent_id=agent_id,+ channel=body.channel,)executor = AgentExecutor()@@ -61,7 +64,8 @@ async def chat(async for ev in executor.run(session=session,agent=agent,- user_id=user.id,+ user_id=ctx.user_id,+ workspace_id=ctx.workspace.id,conversation_id=conv.id,user_message=body.content,channel=body.channel,diff --git a/backend/app/agents/api/conversations.py b/backend/app/agents/api/conversations.pyindex cb107a74..8d50578d 100644--- a/backend/app/agents/api/conversations.py+++ b/backend/app/agents/api/conversations.py@@ -10,9 +10,12 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom app.agents.schemas.conversation import ConversationRead, MessageReadfrom app.agents.services import agent_service, conversation_service-from app.core.auth import current_active_userfrom app.core.database import get_async_session-from app.models.user import User+from app.core.workspace_context import (+ WorkspaceContext,+ current_workspace,+ current_writable_workspace,+)logger = logging.getLogger(__name__)@@ -34,19 +37,21 @@ _TITLE_PROMPT = (async def list_conversations(agent_id: Optional[uuid.UUID] = Query(None),limit: int = Query(50, ge=1, le=200),+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- return await conversation_service.list_conversations(session, user.id, agent_id=agent_id, limit=limit)+ return await conversation_service.list_conversations(+ session, ctx.workspace.id, agent_id=agent_id, limit=limit+ )@router.get("/conversations/{conversation_id}", response_model=ConversationRead)async def get_conversation(conversation_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- conv = await conversation_service.get_conversation(session, conversation_id, user.id)+ conv = await conversation_service.get_conversation(session, conversation_id, ctx.workspace.id)if conv is None:raise HTTPException(status_code=404, detail="conversation not found")return conv@@ -56,10 +61,10 @@ async def get_conversation(async def list_messages(conversation_id: uuid.UUID,limit: int = Query(200, ge=1, le=500),+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- conv = await conversation_service.get_conversation(session, conversation_id, user.id)+ conv = await conversation_service.get_conversation(session, conversation_id, ctx.workspace.id)if conv is None:raise HTTPException(status_code=404, detail="conversation not found")return await conversation_service.list_messages(session, conversation_id, limit=limit)@@ -69,10 +74,12 @@ async def list_messages(async def rename_conversation(conversation_id: uuid.UUID,body: RenameConversationBody,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- conv = await conversation_service.update_title(session, conversation_id, user.id, body.title)+ conv = await conversation_service.update_title(+ session, conversation_id, ctx.workspace.id, body.title+ )if conv is None:raise HTTPException(status_code=404, detail="conversation not found")return conv@@ -81,8 +88,8 @@ async def rename_conversation(@router.post("/conversations/{conversation_id}/generate-title", response_model=ConversationRead)async def generate_title(conversation_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):"""Ask the conversation's agent's LLM to summarize the chat into ashort title. Persists the result and returns the updated row. Best-@@ -91,7 +98,7 @@ async def generate_title(from app.agents.providers.base import ChatMessagefrom app.agents.runtime.executor import _provider_and_model_for- conv = await conversation_service.get_conversation(session, conversation_id, user.id)+ conv = await conversation_service.get_conversation(session, conversation_id, ctx.workspace.id)if conv is None:raise HTTPException(status_code=404, detail="conversation not found")@@ -103,7 +110,7 @@ async def generate_title(if not transcript:return conv # nothing to summarize yet- agent = await agent_service.get_agent(session, conv.agent_id, user.id)+ agent = await agent_service.get_agent(session, conv.agent_id, ctx.workspace.id)if agent is None:return conv@@ -127,7 +134,7 @@ async def generate_title(candidate = next((line.strip().strip('"').strip("'") for line in content.splitlines() if line.strip()), "")if candidate:conv = await conversation_service.update_title(- session, conversation_id, user.id, candidate[:80]+ session, conversation_id, ctx.workspace.id, candidate[:80])except Exception: # noqa: BLE001logger.exception("title generation failed for conversation %s", conversation_id)@@ -137,9 +144,9 @@ async def generate_title(@router.delete("/conversations/{conversation_id}", status_code=status.HTTP_204_NO_CONTENT)async def delete_conversation(conversation_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- ok = await conversation_service.delete_conversation(session, conversation_id, user.id)+ ok = await conversation_service.delete_conversation(session, conversation_id, ctx.workspace.id)if not ok:raise HTTPException(status_code=404, detail="conversation not found")diff --git a/backend/app/agents/api/knowledge.py b/backend/app/agents/api/knowledge.pyindex c3429278..f9bbc861 100644--- a/backend/app/agents/api/knowledge.py+++ b/backend/app/agents/api/knowledge.py@@ -7,9 +7,12 @@ from fastapi import APIRouter, Depends, File, Form, HTTPException, UploadFile, sfrom sqlalchemy.ext.asyncio import AsyncSessionfrom app.agents.services import agent_service, knowledge_service-from app.core.auth import current_active_userfrom app.core.database import get_async_session-from app.models.user import User+from app.core.workspace_context import (+ WorkspaceContext,+ current_workspace,+ current_writable_workspace,+)router = APIRouter(prefix="/api/agents", tags=["agents"])@@ -34,10 +37,10 @@ def _serialize(doc) -> dict[str, Any]:@router.get("/{agent_id}/knowledge")async def list_knowledge(agent_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- agent = await agent_service.get_agent(session, agent_id, user.id)+ agent = await agent_service.get_agent(session, agent_id, ctx.workspace.id)if agent is None:raise HTTPException(status_code=404, detail="agent not found")docs = await knowledge_service.list_docs(session, agent_id)@@ -49,10 +52,10 @@ async def upload_knowledge(agent_id: uuid.UUID,file: UploadFile = File(...),pinned: bool = Form(False),+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- agent = await agent_service.get_agent(session, agent_id, user.id)+ agent = await agent_service.get_agent(session, agent_id, ctx.workspace.id)if agent is None:raise HTTPException(status_code=404, detail="agent not found")payload = await file.read()@@ -60,7 +63,7 @@ async def upload_knowledge(doc = await knowledge_service.upload_doc(session,agent_id=agent_id,- user_id=user.id,+ user_id=ctx.user_id,filename=file.filename or "document",mime=file.content_type or "application/octet-stream",payload=payload,@@ -84,10 +87,10 @@ async def toggle_pin(agent_id: uuid.UUID,doc_id: uuid.UUID,pinned: bool,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- doc = await knowledge_service.set_pinned(session, doc_id, user.id, pinned)+ doc = await knowledge_service.set_pinned(session, doc_id, ctx.user_id, pinned)if doc is None:raise HTTPException(status_code=404, detail="doc not found")return _serialize(doc)@@ -97,9 +100,9 @@ async def toggle_pin(async def delete_knowledge(agent_id: uuid.UUID,doc_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- ok = await knowledge_service.delete_doc(session, doc_id, user.id)+ ok = await knowledge_service.delete_doc(session, doc_id, ctx.user_id)if not ok:raise HTTPException(status_code=404, detail="doc not found")diff --git a/backend/app/agents/api/mcp_tokens.py b/backend/app/agents/api/mcp_tokens.pyindex 83374153..d0ebf79d 100644--- a/backend/app/agents/api/mcp_tokens.py+++ b/backend/app/agents/api/mcp_tokens.py@@ -3,9 +3,14 @@Lets a logged-in user generate a JWT they can paste into Claude Desktop,n8n, or any other MCP client. The token is signed with the same`AGENTS_MCP_JWT_SECRET` the internal runtime uses, scoped to the calling-user, with a configurable TTL (default 90 days) and an `ext: true`-claim. The MCP server already verifies any valid JWT — no auth changes-needed there.+user AND their active workspace, with a configurable TTL (default 90+days) and an `ext: true` claim. The MCP server already verifies any+valid JWT — no auth changes needed there.++External tokens are bound to one workspace at creation time. Users with+multiple workspaces issue one token per workspace (they switch contexts+in the UI before issuing) so external agents always land in a+predictable tenant.Follows the AGENTS_ENABLED master switch: when agents are off, therouter isn't mounted at all so the endpoint 404s.@@ -16,19 +21,25 @@ from fastapi import APIRouter, Depends, statusfrom app.agents.config import get_agent_settingsfrom app.agents.mcp.auth import mint_token-from app.core.auth import current_active_user-from app.models.user import User+from app.core.workspace_context import WorkspaceContext, current_workspacerouter = APIRouter(prefix="/api/agents/mcp-tokens", tags=["agents"])@router.post("", status_code=status.HTTP_201_CREATED)-async def create_mcp_token(user: User = Depends(current_active_user)):+async def create_mcp_token(ctx: WorkspaceContext = Depends(current_workspace)):s = get_agent_settings()ttl_seconds = max(s.mcp_external_ttl_days, 1) * 86400- token = mint_token(user_id=user.id, ttl_seconds=ttl_seconds, external=True)+ token = mint_token(+ user_id=ctx.user_id,+ workspace_id=ctx.workspace.id,+ ttl_seconds=ttl_seconds,+ external=True,+ )return {"token": token,"expires_in_seconds": ttl_seconds,"expires_in_days": s.mcp_external_ttl_days,+ "workspace_id": str(ctx.workspace.id),+ "workspace_name": ctx.workspace.name,}diff --git a/backend/app/agents/mcp/auth.py b/backend/app/agents/mcp/auth.pyindex 55bdc3f0..0096a4e0 100644--- a/backend/app/agents/mcp/auth.py+++ b/backend/app/agents/mcp/auth.py@@ -17,11 +17,20 @@ JWT_ALGO = "HS256"def mint_token(*,user_id: uuid.UUID,+ workspace_id: Optional[uuid.UUID] = None,conversation_id: Optional[uuid.UUID] = None,agent_id: Optional[uuid.UUID] = None,ttl_seconds: Optional[int] = None,external: bool = False,) -> str:+ """Mint an MCP JWT scoped to a (user, workspace) pair.++ `workspace_id` is recommended for every internal call so MCP tools+ operate within the right tenant. It's optional only because long-+ lived external tokens issued before the multi-workspace migration+ still verify — the MCP server falls back to the user's default+ workspace when the claim is absent.+ """s = get_agent_settings()now = int(time.time())payload = {@@ -31,6 +40,8 @@ def mint_token("iat": now,"exp": now + (ttl_seconds or s.mcp_jwt_ttl_seconds),}+ if workspace_id:+ payload["ws_id"] = str(workspace_id)if conversation_id:payload["conv_id"] = str(conversation_id)if agent_id:diff --git a/backend/app/agents/mcp/client.py b/backend/app/agents/mcp/client.pyindex 14c31424..1503ed75 100644--- a/backend/app/agents/mcp/client.py+++ b/backend/app/agents/mcp/client.py@@ -132,10 +132,16 @@ class MCPRegistry:self,*,user_id: uuid.UUID,+ workspace_id: Optional[uuid.UUID] = None,conversation_id: Optional[uuid.UUID] = None,agent_id: Optional[uuid.UUID] = None,) -> list[ToolHandle]:- token = mint_token(user_id=user_id, conversation_id=conversation_id, agent_id=agent_id)+ token = mint_token(+ user_id=user_id,+ workspace_id=workspace_id,+ conversation_id=conversation_id,+ agent_id=agent_id,+ )out: list[ToolHandle] = []for client in self._servers.values():try:@@ -170,13 +176,19 @@ class MCPRegistry:wire_name: str,arguments: dict[str, Any],user_id: uuid.UUID,+ workspace_id: Optional[uuid.UUID] = None,conversation_id: Optional[uuid.UUID] = None,agent_id: Optional[uuid.UUID] = None,) -> dict[str, Any]:# Pass agent_id so per-agent tools (search_knowledge_base) can# scope their results. Without this, MCP-side ctx.agent_id is# None and the knowledge tool refuses.- token = mint_token(user_id=user_id, conversation_id=conversation_id, agent_id=agent_id)+ token = mint_token(+ user_id=user_id,+ workspace_id=workspace_id,+ conversation_id=conversation_id,+ agent_id=agent_id,+ )# Happy path: namespaced name (server__tool).if "__" in wire_name:diff --git a/backend/app/agents/models/__init__.py b/backend/app/agents/models/__init__.pyindex 96a2c7ac..e00daa23 100644--- a/backend/app/agents/models/__init__.py+++ b/backend/app/agents/models/__init__.py@@ -4,6 +4,13 @@ from app.agents.models.conversation import Conversation, Messagefrom app.agents.models.knowledge import KnowledgeDoc, KnowledgeChunkfrom app.agents.models.usage import LlmUsage+# Re-run the autostamp installer now that Agent + Conversation are loaded so+# their inserts inherit workspace_id like the core financial models. Safe to+# call multiple times — the listener registration is idempotent.+from app.core.workspace_autostamp import install_workspace_autostamp # noqa: E402++install_workspace_autostamp()+__all__ = ["Agent","AgentTool",diff --git a/backend/app/agents/models/agent.py b/backend/app/agents/models/agent.pyindex d28687ad..40203598 100644--- a/backend/app/agents/models/agent.py+++ b/backend/app/agents/models/agent.py@@ -15,6 +15,9 @@ class Agent(Base):id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), index=True)+ workspace_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True), ForeignKey("workspaces.id", ondelete="CASCADE"), index=True+ )name: Mapped[str] = mapped_column(String(120))description: Mapped[Optional[str]] = mapped_column(Text, nullable=True)system_prompt: Mapped[str] = mapped_column(Text, default="")diff --git a/backend/app/agents/models/conversation.py b/backend/app/agents/models/conversation.pyindex 4e343313..c2eff16f 100644--- a/backend/app/agents/models/conversation.py+++ b/backend/app/agents/models/conversation.py@@ -16,6 +16,9 @@ class Conversation(Base):id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)agent_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("agents.id", ondelete="CASCADE"), index=True)user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), index=True)+ workspace_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True), ForeignKey("workspaces.id", ondelete="CASCADE"), index=True+ )# Channel of origin: "web", "whatsapp", "api", etc. The runtime is# channel-agnostic; this column lets us segment conversations later.diff --git a/backend/app/agents/runtime/executor.py b/backend/app/agents/runtime/executor.pyindex 04849a40..e87c1821 100644--- a/backend/app/agents/runtime/executor.py+++ b/backend/app/agents/runtime/executor.py@@ -324,6 +324,7 @@ class AgentExecutor:session: AsyncSession,agent: Agent,user_id: uuid.UUID,+ workspace_id: Optional[uuid.UUID] = None,conversation_id: uuid.UUID,user_message: str,channel: str = "web",@@ -367,7 +368,9 @@ class AgentExecutor:from app.models.user import Useruser = await session.get(User, user_id)if user is not None:- primer = await context_service.build_context_primer(session, user)+ primer = await context_service.build_context_primer(+ session, user, workspace_id=agent.workspace_id+ )if primer:messages.append(ChatMessage(role="system", content=primer))except Exception: # noqa: BLE001@@ -398,7 +401,12 @@ class AgentExecutor:# 3. Discover tools from MCP and filter by per-agent whitelist.try:- handles = await self.mcp.discover(user_id=user_id, conversation_id=conversation_id, agent_id=agent.id)+ handles = await self.mcp.discover(+ user_id=user_id,+ workspace_id=workspace_id,+ conversation_id=conversation_id,+ agent_id=agent.id,+ )except Exception:logger.exception("MCP discovery failed; running without tools")handles = []@@ -527,7 +535,7 @@ class AgentExecutor:yield evresults = await asyncio.gather(*[- _safe_call_tool(self.mcp, c, user_id=user_id, conversation_id=conversation_id, agent_id=agent.id)+ _safe_call_tool(self.mcp, c, user_id=user_id, workspace_id=workspace_id, conversation_id=conversation_id, agent_id=agent.id)for c in assembled_calls])for c, res in zip(assembled_calls, results):@@ -597,6 +605,7 @@ async def _safe_call_tool(call: ToolCall,*,user_id: uuid.UUID,+ workspace_id: Optional[uuid.UUID] = None,conversation_id: uuid.UUID,agent_id: Optional[uuid.UUID] = None,) -> dict[str, Any]:@@ -606,6 +615,7 @@ async def _safe_call_tool(wire_name=call.name,arguments=call.arguments,user_id=user_id,+ workspace_id=workspace_id,conversation_id=conversation_id,agent_id=agent_id,)diff --git a/backend/app/agents/services/agent_service.py b/backend/app/agents/services/agent_service.pyindex e0caa291..3560e765 100644--- a/backend/app/agents/services/agent_service.py+++ b/backend/app/agents/services/agent_service.py@@ -12,8 +12,13 @@ from app.agents.models.knowledge import KnowledgeDocfrom app.agents.schemas.agent import AgentCreate, AgentUpdate-async def list_agents(session: AsyncSession, user_id: uuid.UUID, *, include_archived: bool = False) -> list[Agent]:- q = select(Agent).where(Agent.user_id == user_id).order_by(Agent.created_at.desc())+async def list_agents(+ session: AsyncSession,+ workspace_id: uuid.UUID,+ *,+ include_archived: bool = False,+) -> list[Agent]:+ q = select(Agent).where(Agent.workspace_id == workspace_id).order_by(Agent.created_at.desc())if not include_archived:q = q.where(Agent.is_archived.is_(False))rows = list((await session.execute(q)).scalars().all())@@ -43,15 +48,25 @@ async def list_agents(session: AsyncSession, user_id: uuid.UUID, *, include_archreturn rows-async def get_agent(session: AsyncSession, agent_id: uuid.UUID, user_id: uuid.UUID) -> Optional[Agent]:+async def get_agent(+ session: AsyncSession,+ agent_id: uuid.UUID,+ workspace_id: uuid.UUID,+) -> Optional[Agent]:return (await session.execute(- select(Agent).where(Agent.id == agent_id, Agent.user_id == user_id)+ select(Agent).where(Agent.id == agent_id, Agent.workspace_id == workspace_id))).scalar_one_or_none()-async def create_agent(session: AsyncSession, user_id: uuid.UUID, data: AgentCreate) -> Agent:+async def create_agent(+ session: AsyncSession,+ workspace_id: uuid.UUID,+ user_id: uuid.UUID,+ data: AgentCreate,+) -> Agent:agent = Agent(user_id=user_id,+ workspace_id=workspace_id,name=data.name,description=data.description,system_prompt=data.system_prompt,@@ -74,19 +89,26 @@ async def create_agent(session: AsyncSession, user_id: uuid.UUID, data: AgentCreasync def update_agent(- session: AsyncSession, agent_id: uuid.UUID, user_id: uuid.UUID, data: AgentUpdate+ session: AsyncSession,+ agent_id: uuid.UUID,+ workspace_id: uuid.UUID,+ data: AgentUpdate,) -> Optional[Agent]:- agent = await get_agent(session, agent_id, user_id)+ agent = await get_agent(session, agent_id, workspace_id)if agent is None:return Nonepayload = data.model_dump(exclude_unset=True)# If turning this agent into the default, clear the flag on every- # other agent of the same user first — the partial unique index- # would otherwise reject the commit.+ # other agent in the same workspace first — the partial unique+ # index would otherwise reject the commit.if payload.get("is_default") is True:await session.execute(update(Agent)- .where(Agent.user_id == user_id, Agent.id != agent_id, Agent.is_default.is_(True))+ .where(+ Agent.workspace_id == workspace_id,+ Agent.id != agent_id,+ Agent.is_default.is_(True),+ ).values(is_default=False))for field, value in payload.items():@@ -96,13 +118,15 @@ async def update_agent(return agent-async def get_default_agent(session: AsyncSession, user_id: uuid.UUID) -> Optional[Agent]:+async def get_default_agent(+ session: AsyncSession, workspace_id: uuid.UUID+) -> Optional[Agent]:"""The default agent is what the global slide-over chat panel uses.Falls back to the most-recently-created non-archived agent so the- panel still works for users who haven't picked one yet."""+ panel still works for workspaces that haven't picked one yet."""explicit = (await session.execute(select(Agent).where(- Agent.user_id == user_id,+ Agent.workspace_id == workspace_id,Agent.is_default.is_(True),Agent.is_archived.is_(False),)@@ -111,14 +135,16 @@ async def get_default_agent(session: AsyncSession, user_id: uuid.UUID) -> Optionreturn explicitreturn (await session.execute(select(Agent)- .where(Agent.user_id == user_id, Agent.is_archived.is_(False))+ .where(Agent.workspace_id == workspace_id, Agent.is_archived.is_(False)).order_by(Agent.created_at.desc()).limit(1))).scalar_one_or_none()-async def delete_agent(session: AsyncSession, agent_id: uuid.UUID, user_id: uuid.UUID) -> bool:- agent = await get_agent(session, agent_id, user_id)+async def delete_agent(+ session: AsyncSession, agent_id: uuid.UUID, workspace_id: uuid.UUID+) -> bool:+ agent = await get_agent(session, agent_id, workspace_id)if agent is None:return Falseawait session.delete(agent)diff --git a/backend/app/agents/services/context_service.py b/backend/app/agents/services/context_service.pyindex 09c27275..e5ca08db 100644--- a/backend/app/agents/services/context_service.py+++ b/backend/app/agents/services/context_service.py@@ -9,6 +9,7 @@ Goals:"""from __future__ import annotations+import uuidfrom datetime import datetime, timezonefrom decimal import Decimalfrom typing import Optional@@ -40,10 +41,16 @@ def _user_label(user: User) -> str:return email or "the user"-async def build_context_primer(session: AsyncSession, user: User, *, max_accounts: int = 10) -> str:+async def build_context_primer(+ session: AsyncSession,+ user: User,+ *,+ workspace_id: uuid.UUID | None = None,+ max_accounts: int = 10,+) -> str:"""Returns a short Markdown block describing who the user is and- what their accounts look like. Empty string when there's nothing- useful to say."""+ what their accounts look like in the active workspace. Empty string+ when there's nothing useful to say."""from app.services import account_serviceprefs = getattr(user, "preferences", None) or {}@@ -64,10 +71,12 @@ async def build_context_primer(session: AsyncSession, user: User, *, max_accountlines.append(f"- Today is {today_utc} (UTC)")lines.append("")- try:- rows = await account_service.get_accounts(session, user.id, include_closed=False)- except Exception: # noqa: BLE001- rows = []+ rows: list[dict] = []+ if workspace_id is not None:+ try:+ rows = await account_service.get_accounts(session, workspace_id, include_closed=False)+ except Exception: # noqa: BLE001+ rows = []if rows:lines.append(f"Their open accounts (top {min(len(rows), max_accounts)}):")diff --git a/backend/app/agents/services/conversation_service.py b/backend/app/agents/services/conversation_service.pyindex 10c0c275..e0b36664 100644--- a/backend/app/agents/services/conversation_service.py+++ b/backend/app/agents/services/conversation_service.py@@ -10,9 +10,12 @@ from app.agents.models.conversation import Conversation, Messageasync def list_conversations(- session: AsyncSession, user_id: uuid.UUID, agent_id: Optional[uuid.UUID] = None, limit: int = 50+ session: AsyncSession,+ workspace_id: uuid.UUID,+ agent_id: Optional[uuid.UUID] = None,+ limit: int = 50,) -> list[Conversation]:- q = select(Conversation).where(Conversation.user_id == user_id)+ q = select(Conversation).where(Conversation.workspace_id == workspace_id)if agent_id:q = q.where(Conversation.agent_id == agent_id)q = q.order_by(Conversation.updated_at.desc()).limit(limit)@@ -20,22 +23,32 @@ async def list_conversations(async def get_conversation(- session: AsyncSession, conversation_id: uuid.UUID, user_id: uuid.UUID+ session: AsyncSession, conversation_id: uuid.UUID, workspace_id: uuid.UUID) -> Optional[Conversation]:return (await session.execute(- select(Conversation).where(Conversation.id == conversation_id, Conversation.user_id == user_id)+ select(Conversation).where(+ Conversation.id == conversation_id,+ Conversation.workspace_id == workspace_id,+ ))).scalar_one_or_none()async def create_conversation(session: AsyncSession,*,+ workspace_id: uuid.UUID,user_id: uuid.UUID,agent_id: uuid.UUID,channel: str = "web",title: Optional[str] = None,) -> Conversation:- conv = Conversation(user_id=user_id, agent_id=agent_id, channel=channel, title=title)+ conv = Conversation(+ workspace_id=workspace_id,+ user_id=user_id,+ agent_id=agent_id,+ channel=channel,+ title=title,+ )session.add(conv)await session.commit()await session.refresh(conv)@@ -43,9 +56,9 @@ async def create_conversation(async def delete_conversation(- session: AsyncSession, conversation_id: uuid.UUID, user_id: uuid.UUID+ session: AsyncSession, conversation_id: uuid.UUID, workspace_id: uuid.UUID) -> bool:- conv = await get_conversation(session, conversation_id, user_id)+ conv = await get_conversation(session, conversation_id, workspace_id)if conv is None:return Falseawait session.delete(conv)@@ -112,12 +125,12 @@ async def update_title_if_empty(async def update_title(- session: AsyncSession, conversation_id: uuid.UUID, user_id: uuid.UUID, title: str+ session: AsyncSession, conversation_id: uuid.UUID, workspace_id: uuid.UUID, title: str) -> Optional[Conversation]:"""Always overwrites the title (used by the rename UI and by theLLM-generated title endpoint). Returns the updated row, or None if- not found / not owned by this user."""- conv = await get_conversation(session, conversation_id, user_id)+ not found / not in this workspace."""+ conv = await get_conversation(session, conversation_id, workspace_id)if conv is None:return Noneconv.title = (title or "").strip()[:200] or Nonediff --git a/backend/app/api/accounts.py b/backend/app/api/accounts.pyindex 76d699c9..1a3d06fd 100644--- a/backend/app/api/accounts.py+++ b/backend/app/api/accounts.py@@ -6,9 +6,12 @@ from typing import Optionalfrom fastapi import APIRouter, Depends, HTTPException, Query, statusfrom sqlalchemy.ext.asyncio import AsyncSession-from app.core.auth import current_active_userfrom app.core.database import get_async_session-from app.models.user import User+from app.core.workspace_context import (+ WorkspaceContext,+ current_workspace,+ current_writable_workspace,+)from app.schemas.account import (AccountCreate,AccountRead,@@ -25,11 +28,11 @@ router = APIRouter(prefix="/api/accounts", tags=["accounts"])@router.get("", response_model=list[AccountRead])async def list_accounts(include_closed: bool = False,+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- accounts = await account_service.get_accounts(session, user.id, include_closed=include_closed)- primary_currency = user.primary_currency+ accounts = await account_service.get_accounts(session, ctx.workspace.id, include_closed=include_closed)+ primary_currency = ctx.user.primary_currencyfor acc in accounts:if acc["currency"] != primary_currency:converted, _ = await convert(@@ -46,20 +49,20 @@ async def get_account_summary(date_to: Optional[str] = Query(None, alias="to", description="YYYY-MM-DD"),bill_id: Optional[uuid.UUID] = Query(None, description="Aggregate by bill_id (issue #92); takes precedence over from/to"),unbilled_only: bool = Query(False, description="Cycle-math fallback only: exclude txs already linked to any bill"),+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):from_date = date.fromisoformat(date_from) if date_from else Noneto_date = date.fromisoformat(date_to) if date_to else Nonesummary = await account_service.get_account_summary(- session, account_id, user.id, date_from=from_date, date_to=to_date,+ session, account_id, ctx.workspace.id, date_from=from_date, date_to=to_date,bill_id=bill_id, unbilled_only=unbilled_only,)if not summary:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Account not found")- account = await account_service.get_account(session, account_id, user.id)- primary_currency = user.primary_currency+ account = await account_service.get_account(session, account_id, ctx.workspace.id)+ primary_currency = ctx.user.primary_currencyif account and account.currency != primary_currency:bal, _ = await convert(session, Decimal(str(summary["current_balance"])), account.currency, primary_currency)inc, _ = await convert(session, Decimal(str(summary["monthly_income"])), account.currency, primary_currency)@@ -76,19 +79,19 @@ async def get_account_balance_history(account_id: uuid.UUID,date_from: Optional[str] = Query(None, alias="from", description="YYYY-MM-DD"),date_to: Optional[str] = Query(None, alias="to", description="YYYY-MM-DD"),+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):from_date = date.fromisoformat(date_from) if date_from else Noneto_date = date.fromisoformat(date_to) if date_to else Nonehistory = await account_service.get_account_balance_history(- session, account_id, user.id, date_from=from_date, date_to=to_date,+ session, account_id, ctx.workspace.id, date_from=from_date, date_to=to_date,)if history is None:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Account not found")- account = await account_service.get_account(session, account_id, user.id)- primary_currency = user.primary_currency+ account = await account_service.get_account(session, account_id, ctx.workspace.id)+ primary_currency = ctx.user.primary_currencyif account and account.currency != primary_currency:for point in history:point_date = date.fromisoformat(point["date"])@@ -104,8 +107,8 @@ async def get_account_balance_history(async def get_account_bills(account_id: uuid.UUID,limit: int = Query(24, ge=1, le=200, description="Max bills to return, newest due_date first"),+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):"""List credit-card bills for an account, newest due_date first.@@ -114,7 +117,7 @@ async def get_account_bills(happened). Issue #92."""bills = await account_service.get_credit_card_bills(- session, account_id, user.id, limit=limit,+ session, account_id, ctx.workspace.id, limit=limit,)if bills is None:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Account not found")@@ -124,10 +127,10 @@ async def get_account_bills(@router.get("/{account_id}", response_model=AccountRead)async def get_account(account_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- account = await account_service.get_account(session, account_id, user.id)+ account = await account_service.get_account(session, account_id, ctx.workspace.id)if not account:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Account not found")return account_service.serialize_account(account, None, None)@@ -136,10 +139,10 @@ async def get_account(@router.post("", response_model=AccountRead, status_code=status.HTTP_201_CREATED)async def create_account(data: AccountCreate,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- account = await account_service.create_account(session, user.id, data)+ account = await account_service.create_account(session, ctx.workspace.id, ctx.user_id, data)return account_service.serialize_account(account, None, None)@@ -147,11 +150,11 @@ async def create_account(async def update_account(account_id: uuid.UUID,data: AccountUpdate,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):try:- account = await account_service.update_account(session, account_id, user.id, data)+ account = await account_service.update_account(session, account_id, ctx.workspace.id, data)except ValueError as e:raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))if not account:@@ -162,11 +165,11 @@ async def update_account(@router.delete("/{account_id}", status_code=status.HTTP_204_NO_CONTENT)async def delete_account(account_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):try:- deleted = await account_service.delete_account(session, account_id, user.id)+ deleted = await account_service.delete_account(session, account_id, ctx.workspace.id)except ValueError as e:raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))if not deleted:@@ -176,11 +179,11 @@ async def delete_account(@router.post("/{account_id}/close", response_model=AccountRead)async def close_account(account_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):try:- account = await account_service.close_account(session, account_id, user.id)+ account = await account_service.close_account(session, account_id, ctx.workspace.id)except ValueError as e:raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))if not account:@@ -191,11 +194,11 @@ async def close_account(@router.post("/{account_id}/reopen", response_model=AccountRead)async def reopen_account(account_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):try:- account = await account_service.reopen_account(session, account_id, user.id)+ account = await account_service.reopen_account(session, account_id, ctx.workspace.id)except ValueError as e:raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))if not account:diff --git a/backend/app/api/asset_groups.py b/backend/app/api/asset_groups.pyindex 10fec124..d24a5e2c 100644--- a/backend/app/api/asset_groups.py+++ b/backend/app/api/asset_groups.py@@ -3,9 +3,12 @@ import uuidfrom fastapi import APIRouter, Depends, HTTPException, statusfrom sqlalchemy.ext.asyncio import AsyncSession-from app.core.auth import current_active_userfrom app.core.database import get_async_session-from app.models.user import User+from app.core.workspace_context import (+ WorkspaceContext,+ current_workspace,+ current_writable_workspace,+)from app.schemas.asset_group import AssetGroupCreate, AssetGroupRead, AssetGroupUpdatefrom app.services import asset_group_service@@ -14,29 +17,29 @@ router = APIRouter(prefix="/api/asset-groups", tags=["asset-groups"])@router.get("", response_model=list[AssetGroupRead])async def list_groups(+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- return await asset_group_service.get_groups(session, user.id)+ return await asset_group_service.get_groups(session, ctx.workspace.id, ctx.user_id)@router.post("", response_model=AssetGroupRead, status_code=status.HTTP_201_CREATED)async def create_group(data: AssetGroupCreate,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- return await asset_group_service.create_group(session, user.id, data)+ return await asset_group_service.create_group(session, ctx.workspace.id, ctx.user_id, data)@router.patch("/{group_id}", response_model=AssetGroupRead)async def update_group(group_id: uuid.UUID,data: AssetGroupUpdate,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- group = await asset_group_service.update_group(session, group_id, user.id, data)+ group = await asset_group_service.update_group(session, group_id, ctx.workspace.id, ctx.user_id, data)if not group:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Group not found")return group@@ -45,10 +48,10 @@ async def update_group(@router.delete("/{group_id}", status_code=status.HTTP_204_NO_CONTENT)async def delete_group(group_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- deleted = await asset_group_service.delete_group(session, group_id, user.id)+ deleted = await asset_group_service.delete_group(session, group_id, ctx.workspace.id)if not deleted:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,diff --git a/backend/app/api/assets.py b/backend/app/api/assets.pyindex 1361e5a5..b36ad3c3 100644--- a/backend/app/api/assets.py+++ b/backend/app/api/assets.py@@ -7,6 +7,11 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom app.core.auth import current_active_userfrom app.core.database import get_async_session+from app.core.workspace_context import (+ WorkspaceContext,+ current_workspace,+ current_writable_workspace,+)from app.models.user import Userfrom app.providers.market_price import (MarketPriceRateLimitedError,@@ -89,8 +94,8 @@ async def market_quote(@router.post("/{asset_id}/refresh-price", response_model=AssetRead)async def refresh_asset_price(asset_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),) -> AssetRead:"""Trigger an immediate price refresh for a single market-priced asset.@@ -104,7 +109,7 @@ async def refresh_asset_price(result = await session.execute(sa_select(AssetModel).where(- AssetModel.id == asset_id, AssetModel.user_id == user.id+ AssetModel.id == asset_id, AssetModel.workspace_id == ctx.workspace.id))asset = result.scalar_one_or_none()@@ -130,14 +135,14 @@ async def refresh_asset_price()await session.commit()- refreshed = await asset_service.get_asset(session, asset_id, user.id)+ refreshed = await asset_service.get_asset(session, asset_id, ctx.workspace.id)if refreshed is None:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Asset not found")# Stamp the primary-currency fields so the refresh response has the same# shape as the list endpoint — the React Query cache update needs them# to keep the row rendering consistent (BRL rollup, gain/loss).- primary_currency = user.primary_currency+ primary_currency = ctx.user.primary_currencyif refreshed.currency != primary_currency and refreshed.current_value is not None:converted, _ = await convert(session, Decimal(str(refreshed.current_value)), refreshed.currency, primary_currency,@@ -154,11 +159,11 @@ async def refresh_asset_price(@router.get("", response_model=list[AssetRead])async def list_assets(include_archived: bool = False,+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- assets = await asset_service.get_assets(session, user.id, include_archived=include_archived)- primary_currency = user.primary_currency+ assets = await asset_service.get_assets(session, ctx.workspace.id, include_archived=include_archived)+ primary_currency = ctx.user.primary_currencyfor asset in assets:if asset.currency != primary_currency and asset.current_value is not None:converted, _ = await convert(@@ -175,19 +180,19 @@ async def list_assets(@router.get("/portfolio-trend")async def portfolio_trend(+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- return await asset_service.get_portfolio_trend(session, user.id)+ return await asset_service.get_portfolio_trend(session, ctx.workspace.id, ctx.user_id)@router.get("/{asset_id}", response_model=AssetRead)async def get_asset(asset_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- asset = await asset_service.get_asset(session, asset_id, user.id)+ asset = await asset_service.get_asset(session, asset_id, ctx.workspace.id)if not asset:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Asset not found")return asset@@ -196,10 +201,10 @@ async def get_asset(@router.post("", response_model=AssetRead, status_code=status.HTTP_201_CREATED)async def create_asset(data: AssetCreate,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- return await asset_service.create_asset(session, user.id, data)+ return await asset_service.create_asset(session, ctx.workspace.id, ctx.user_id, data)@router.patch("/{asset_id}", response_model=AssetRead)@@ -207,10 +212,12 @@ async def update_asset(asset_id: uuid.UUID,data: AssetUpdate,regenerate_growth: bool = Query(False),+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- asset = await asset_service.update_asset(session, asset_id, user.id, data, regenerate_growth=regenerate_growth)+ asset = await asset_service.update_asset(+ session, asset_id, ctx.workspace.id, ctx.user_id, data, regenerate_growth=regenerate_growth+ )if not asset:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Asset not found")return asset@@ -219,10 +226,10 @@ async def update_asset(@router.delete("/{asset_id}", status_code=status.HTTP_204_NO_CONTENT)async def delete_asset(asset_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- deleted = await asset_service.delete_asset(session, asset_id, user.id)+ deleted = await asset_service.delete_asset(session, asset_id, ctx.workspace.id)if not deleted:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Asset not found")@@ -230,10 +237,10 @@ async def delete_asset(@router.get("/{asset_id}/values", response_model=list[AssetValueRead])async def list_asset_values(asset_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- values = await asset_service.get_asset_values(session, asset_id, user.id)+ values = await asset_service.get_asset_values(session, asset_id, ctx.workspace.id)if values is None:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Asset not found")return values@@ -243,10 +250,10 @@ async def list_asset_values(async def get_asset_value_trend(asset_id: uuid.UUID,months: int = Query(12, ge=1, le=120),+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- trend = await asset_service.get_asset_value_trend(session, asset_id, user.id, months=months)+ trend = await asset_service.get_asset_value_trend(session, asset_id, ctx.workspace.id, months=months)if trend is None:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Asset not found")return trend@@ -256,10 +263,10 @@ async def get_asset_value_trend(async def add_asset_value(asset_id: uuid.UUID,data: AssetValueCreate,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- value = await asset_service.add_asset_value(session, asset_id, user.id, data)+ value = await asset_service.add_asset_value(session, asset_id, ctx.workspace.id, data)if value is None:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Asset not found")return value@@ -268,9 +275,9 @@ async def add_asset_value(@router.delete("/values/{value_id}", status_code=status.HTTP_204_NO_CONTENT)async def delete_asset_value(value_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- deleted = await asset_service.delete_asset_value(session, value_id, user.id)+ deleted = await asset_service.delete_asset_value(session, value_id, ctx.workspace.id)if not deleted:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Value not found")diff --git a/backend/app/api/attachments.py b/backend/app/api/attachments.pyindex dbe18b96..d64a3544 100644--- a/backend/app/api/attachments.py+++ b/backend/app/api/attachments.py@@ -4,9 +4,12 @@ from fastapi import APIRouter, Depends, HTTPException, UploadFile, statusfrom fastapi.responses import Responsefrom sqlalchemy.ext.asyncio import AsyncSession-from app.core.auth import current_active_userfrom app.core.database import get_async_session-from app.models.user import User+from app.core.workspace_context import (+ WorkspaceContext,+ current_workspace,+ current_writable_workspace,+)from app.schemas.attachment import AttachmentRead, AttachmentRenamefrom app.services import attachment_service@@ -20,14 +23,15 @@ router = APIRouter(async def upload_attachment(transaction_id: uuid.UUID,file: UploadFile,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):data = await file.read()try:attachment = await attachment_service.upload_attachment(session=session,- user_id=user.id,+ workspace_id=ctx.workspace.id,+ user_id=ctx.user_id,transaction_id=transaction_id,filename=file.filename or "unnamed",content_type=file.content_type or "application/octet-stream",@@ -43,11 +47,11 @@ async def upload_attachment(@router.get("", response_model=list[AttachmentRead])async def list_attachments(transaction_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):try:- return await attachment_service.list_attachments(session, user.id, transaction_id)+ return await attachment_service.list_attachments(session, ctx.workspace.id, transaction_id)except LookupError:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Transaction not found")@@ -56,12 +60,12 @@ async def list_attachments(async def download_attachment(transaction_id: uuid.UUID,attachment_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):try:attachment, data = await attachment_service.download_attachment(- session, attachment_id, user.id+ session, attachment_id, ctx.workspace.id)except LookupError:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Attachment not found")@@ -77,12 +81,12 @@ async def rename_attachment(transaction_id: uuid.UUID,attachment_id: uuid.UUID,body: AttachmentRename,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):try:return await attachment_service.rename_attachment(- session, attachment_id, user.id, body.filename+ session, attachment_id, ctx.workspace.id, body.filename)except LookupError:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Attachment not found")@@ -94,10 +98,10 @@ async def rename_attachment(async def delete_attachment(transaction_id: uuid.UUID,attachment_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):try:- await attachment_service.delete_attachment(session, attachment_id, user.id)+ await attachment_service.delete_attachment(session, attachment_id, ctx.workspace.id)except LookupError:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Attachment not found")diff --git a/backend/app/api/budgets.py b/backend/app/api/budgets.pyindex d135e6b2..89bb87c5 100644--- a/backend/app/api/budgets.py+++ b/backend/app/api/budgets.py@@ -5,9 +5,12 @@ from typing import Optionalfrom fastapi import APIRouter, Depends, HTTPException, Query, statusfrom sqlalchemy.ext.asyncio import AsyncSession-from app.core.auth import current_active_userfrom app.core.database import get_async_session-from app.models.user import User+from app.core.workspace_context import (+ WorkspaceContext,+ current_workspace,+ current_writable_workspace,+)from app.schemas.budget import BudgetCreate, BudgetRead, BudgetUpdate, BudgetVsActualfrom app.services import budget_service@@ -17,20 +20,20 @@ router = APIRouter(prefix="/api/budgets", tags=["budgets"])@router.get("", response_model=list[BudgetRead])async def list_budgets(month: Optional[date] = Query(None),+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- return await budget_service.get_budgets(session, user.id, month)+ return await budget_service.get_budgets(session, ctx.workspace.id, month)@router.post("", response_model=BudgetRead, status_code=status.HTTP_201_CREATED)async def create_budget(data: BudgetCreate,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):try:- return await budget_service.create_budget(session, user.id, data)+ return await budget_service.create_budget(session, ctx.workspace.id, ctx.user_id, data)except Exception as e:raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))@@ -39,10 +42,10 @@ async def create_budget(async def update_budget(budget_id: uuid.UUID,data: BudgetUpdate,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- budget = await budget_service.update_budget(session, budget_id, user.id, data)+ budget = await budget_service.update_budget(session, budget_id, ctx.workspace.id, data)if not budget:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Budget not found")return budget@@ -51,10 +54,10 @@ async def update_budget(@router.delete("/{budget_id}", status_code=status.HTTP_204_NO_CONTENT)async def delete_budget(budget_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- deleted = await budget_service.delete_budget(session, budget_id, user.id)+ deleted = await budget_service.delete_budget(session, budget_id, ctx.workspace.id)if not deleted:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Budget not found")@@ -62,7 +65,7 @@ async def delete_budget(@router.get("/comparison", response_model=list[BudgetVsActual])async def budget_comparison(month: Optional[date] = Query(None),+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- return await budget_service.get_budget_vs_actual(session, user.id, month)+ return await budget_service.get_budget_vs_actual(session, ctx.workspace.id, ctx.user_id, month)diff --git a/backend/app/api/categories.py b/backend/app/api/categories.pyindex 30190063..e4c8d144 100644--- a/backend/app/api/categories.py+++ b/backend/app/api/categories.py@@ -3,9 +3,12 @@ import uuidfrom fastapi import APIRouter, Depends, HTTPException, statusfrom sqlalchemy.ext.asyncio import AsyncSession-from app.core.auth import current_active_userfrom app.core.database import get_async_session-from app.models.user import User+from app.core.workspace_context import (+ WorkspaceContext,+ current_workspace,+ current_writable_workspace,+)from app.schemas.category import CategoryCreate, CategoryRead, CategoryUpdatefrom app.services import category_service@@ -14,29 +17,29 @@ router = APIRouter(prefix="/api/categories", tags=["categories"])@router.get("", response_model=list[CategoryRead])async def list_categories(+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- return await category_service.get_categories(session, user.id)+ return await category_service.get_categories(session, ctx.workspace.id)@router.post("", response_model=CategoryRead, status_code=status.HTTP_201_CREATED)async def create_category(data: CategoryCreate,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- return await category_service.create_category(session, user.id, data)+ return await category_service.create_category(session, ctx.workspace.id, ctx.user_id, data)@router.patch("/{category_id}", response_model=CategoryRead)async def update_category(category_id: uuid.UUID,data: CategoryUpdate,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- category = await category_service.update_category(session, category_id, user.id, data)+ category = await category_service.update_category(session, category_id, ctx.workspace.id, data)if not category:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Category not found")return category@@ -45,10 +48,10 @@ async def update_category(@router.delete("/{category_id}", status_code=status.HTTP_204_NO_CONTENT)async def delete_category(category_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- deleted = await category_service.delete_category(session, category_id, user.id)+ deleted = await category_service.delete_category(session, category_id, ctx.workspace.id)if not deleted:raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST,diff --git a/backend/app/api/category_groups.py b/backend/app/api/category_groups.pyindex d476da3c..a405e8b9 100644--- a/backend/app/api/category_groups.py+++ b/backend/app/api/category_groups.py@@ -3,9 +3,12 @@ import uuidfrom fastapi import APIRouter, Depends, HTTPException, statusfrom sqlalchemy.ext.asyncio import AsyncSession-from app.core.auth import current_active_userfrom app.core.database import get_async_session-from app.models.user import User+from app.core.workspace_context import (+ WorkspaceContext,+ current_workspace,+ current_writable_workspace,+)from app.schemas.category_group import CategoryGroupCreate, CategoryGroupRead, CategoryGroupUpdatefrom app.services import category_group_service@@ -14,29 +17,29 @@ router = APIRouter(prefix="/api/category-groups", tags=["category-groups"])@router.get("", response_model=list[CategoryGroupRead])async def list_groups(+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- return await category_group_service.get_groups(session, user.id)+ return await category_group_service.get_groups(session, ctx.workspace.id)@router.post("", response_model=CategoryGroupRead, status_code=status.HTTP_201_CREATED)async def create_group(data: CategoryGroupCreate,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- return await category_group_service.create_group(session, user.id, data)+ return await category_group_service.create_group(session, ctx.workspace.id, ctx.user_id, data)@router.patch("/{group_id}", response_model=CategoryGroupRead)async def update_group(group_id: uuid.UUID,data: CategoryGroupUpdate,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- group = await category_group_service.update_group(session, group_id, user.id, data)+ group = await category_group_service.update_group(session, group_id, ctx.workspace.id, data)if not group:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Group not found")return group@@ -45,10 +48,10 @@ async def update_group(@router.delete("/{group_id}", status_code=status.HTTP_204_NO_CONTENT)async def delete_group(group_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- deleted = await category_group_service.delete_group(session, group_id, user.id)+ deleted = await category_group_service.delete_group(session, group_id, ctx.workspace.id)if not deleted:raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST,diff --git a/backend/app/api/connections.py b/backend/app/api/connections.pyindex 1f88eb55..f27f89a0 100644--- a/backend/app/api/connections.py+++ b/backend/app/api/connections.py@@ -3,9 +3,12 @@ import uuidfrom fastapi import APIRouter, Depends, HTTPException, statusfrom sqlalchemy.ext.asyncio import AsyncSession-from app.core.auth import current_active_userfrom app.core.database import get_async_session-from app.models.user import User+from app.core.workspace_context import (+ WorkspaceContext,+ current_workspace,+ current_writable_workspace,+)from app.providers import all_known_providersfrom app.schemas.bank_connection import (BankConnectionRead,@@ -32,11 +35,11 @@ async def get_available_providers():@router.post("/connect-token", response_model=ConnectTokenResponse)async def create_connect_token(data: ConnectTokenRequest,- user: User = Depends(current_active_user),+ ctx: WorkspaceContext = Depends(current_writable_workspace),):"""Create a connect token for widget-based bank connection flows."""try:- token_data = await connection_service.create_connect_token(data.provider, user.id)+ token_data = await connection_service.create_connect_token(data.provider, ctx.user_id)return ConnectTokenResponse(**token_data)except ValueError as e:raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))@@ -49,19 +52,19 @@ async def create_connect_token(@router.get("", response_model=list[BankConnectionRead])async def list_connections(+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- return await connection_service.get_connections(session, user.id)+ return await connection_service.get_connections(session, ctx.workspace.id)@router.post("/oauth/url", response_model=OAuthUrlResponse)async def get_oauth_url(data: OAuthUrlRequest,- user: User = Depends(current_active_user),+ ctx: WorkspaceContext = Depends(current_writable_workspace),):try:- url = connection_service.get_oauth_url(data.provider, user.id)+ url = connection_service.get_oauth_url(data.provider, ctx.user_id)return OAuthUrlResponse(url=url)except ValueError as e:raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))@@ -70,12 +73,12 @@ async def get_oauth_url(@router.post("/oauth/callback", response_model=BankConnectionRead)async def oauth_callback(data: OAuthCallbackRequest,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):try:connection = await connection_service.handle_oauth_callback(- session, user.id, data.code, data.provider+ session, ctx.workspace.id, ctx.user_id, data.code, data.provider)return connectionexcept Exception as e:@@ -88,11 +91,13 @@ async def oauth_callback(@router.post("/{connection_id}/sync")async def sync_connection(connection_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):try:- connection, merged_count = await connection_service.sync_connection(session, connection_id, user.id)+ connection, merged_count = await connection_service.sync_connection(+ session, connection_id, ctx.workspace.id, ctx.user_id+ )result = BankConnectionRead.model_validate(connection)return {**result.model_dump(mode="json"), "merged_count": merged_count}except ValueError as e:@@ -107,11 +112,11 @@ async def sync_connection(@router.post("/{connection_id}/reconnect-token", response_model=ReconnectTokenResponse)async def get_reconnect_token(connection_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):"""Get a connect token for reconnecting an errored/expired connection."""- connection = await connection_service.get_connection(session, connection_id, user.id)+ connection = await connection_service.get_connection(session, connection_id, ctx.workspace.id)if not connection:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Connection not found")@@ -124,7 +129,7 @@ async def get_reconnect_token(try:token_data = await connection_service.create_connect_token(- connection.provider, user.id, item_id=item_id+ connection.provider, ctx.user_id, item_id=item_id)return ReconnectTokenResponse(**token_data)except Exception as e:@@ -138,11 +143,11 @@ async def get_reconnect_token(async def update_settings(connection_id: uuid.UUID,data: ConnectionSettingsUpdate,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):connection = await connection_service.update_connection_settings(- session, connection_id, user.id, data.model_dump(exclude_unset=True)+ session, connection_id, ctx.workspace.id, data.model_dump(exclude_unset=True))if not connection:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Connection not found")@@ -152,21 +157,21 @@ async def update_settings(@router.delete("/{connection_id}", status_code=status.HTTP_204_NO_CONTENT)async def delete_connection(connection_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- deleted = await connection_service.delete_connection(session, connection_id, user.id)+ deleted = await connection_service.delete_connection(session, connection_id, ctx.workspace.id)if not deleted:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Connection not found")@router.post("/transfers/detect")async def detect_transfers(+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- """One-time backfill scan: detect transfer pairs across all existing transactions."""- pairs_created = await detect_transfer_pairs(session, user.id)+ """One-time backfill scan: detect transfer pairs across all existing transactions in this workspace."""+ pairs_created = await detect_transfer_pairs(session, ctx.workspace.id)await session.commit()return {"pairs_created": pairs_created}@@ -174,11 +179,11 @@ async def detect_transfers(@router.delete("/transfers/{pair_id}", status_code=status.HTTP_204_NO_CONTENT)async def unlink_transfer(pair_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):"""Manual unlink: remove a transfer pair link so both transactions are treated normally."""- unlinked = await unlink_transfer_pair(session, user.id, pair_id)+ unlinked = await unlink_transfer_pair(session, ctx.workspace.id, pair_id)if not unlinked:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Transfer pair not found")await session.commit()diff --git a/backend/app/api/dashboard.py b/backend/app/api/dashboard.pyindex 56e4f47d..b4cc99c1 100644--- a/backend/app/api/dashboard.py+++ b/backend/app/api/dashboard.py@@ -4,9 +4,8 @@ from typing import Optionalfrom fastapi import APIRouter, Depends, Queryfrom sqlalchemy.ext.asyncio import AsyncSession-from app.core.auth import current_active_userfrom app.core.database import get_async_session-from app.models.user import User+from app.core.workspace_context import WorkspaceContext, current_workspacefrom app.schemas.dashboard import DashboardSummary, SpendingByCategory, MonthlyTrend, ProjectedTransaction, BalanceHistoryfrom app.services import dashboard_service@@ -17,43 +16,53 @@ router = APIRouter(prefix="/api/dashboard", tags=["dashboard"])async def get_summary(month: Optional[date] = Query(None),balance_date: Optional[date] = Query(None),+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- return await dashboard_service.get_summary(session, user.id, month, balance_date)+ return await dashboard_service.get_summary(+ session, ctx.workspace.id, ctx.user_id, month, balance_date+ )@router.get("/spending-by-category", response_model=list[SpendingByCategory])async def get_spending_by_category(month: Optional[date] = Query(None),+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- return await dashboard_service.get_spending_by_category(session, user.id, month)+ return await dashboard_service.get_spending_by_category(+ session, ctx.workspace.id, ctx.user_id, month+ )@router.get("/monthly-trend", response_model=list[MonthlyTrend])async def get_monthly_trend(months: int = Query(6, ge=1, le=12),+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- return await dashboard_service.get_monthly_trend(session, user.id, months)+ return await dashboard_service.get_monthly_trend(+ session, ctx.workspace.id, ctx.user_id, months+ )@router.get("/balance-history", response_model=BalanceHistory)async def get_balance_history(month: Optional[date] = Query(None),+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- return await dashboard_service.get_balance_history(session, user.id, month)+ return await dashboard_service.get_balance_history(+ session, ctx.workspace.id, ctx.user_id, month+ )@router.get("/projected-transactions", response_model=list[ProjectedTransaction])async def get_projected_transactions(month: Optional[date] = Query(None),+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- return await dashboard_service.get_projected_transactions(session, user.id, month)+ return await dashboard_service.get_projected_transactions(+ session, ctx.workspace.id, ctx.user_id, month+ )diff --git a/backend/app/api/export.py b/backend/app/api/export.pyindex 30a8b2a5..0025d27f 100644--- a/backend/app/api/export.py+++ b/backend/app/api/export.py@@ -10,8 +10,8 @@ from fastapi.responses import StreamingResponsefrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession-from app.core.auth import current_active_userfrom app.core.database import get_async_session+from app.core.workspace_context import WorkspaceContext, current_workspacefrom app.models.account import Accountfrom app.models.asset import Assetfrom app.models.asset_value import AssetValue@@ -22,7 +22,6 @@ from app.models.import_log import ImportLogfrom app.models.recurring_transaction import RecurringTransactionfrom app.models.rule import Rulefrom app.models.transaction import Transaction-from app.models.user import Userrouter = APIRouter(prefix="/api/export", tags=["export"])@@ -44,23 +43,27 @@ def _serialize(obj) -> dict:@router.get("/backup")async def backup(+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- user_id = user.id+ """Export every entity in the current workspace as a JSON zip.- # Query all entities for the current user- accounts = (await session.execute(select(Account).where(Account.user_id == user_id))).scalars().all()- transactions = (await session.execute(select(Transaction).where(Transaction.user_id == user_id))).scalars().all()- categories = (await session.execute(select(Category).where(Category.user_id == user_id))).scalars().all()- category_groups = (await session.execute(select(CategoryGroup).where(CategoryGroup.user_id == user_id))).scalars().all()- rules = (await session.execute(select(Rule).where(Rule.user_id == user_id))).scalars().all()- recurring_transactions = (await session.execute(select(RecurringTransaction).where(RecurringTransaction.user_id == user_id))).scalars().all()- budgets = (await session.execute(select(Budget).where(Budget.user_id == user_id))).scalars().all()- assets = (await session.execute(select(Asset).where(Asset.user_id == user_id))).scalars().all()- import_logs = (await session.execute(select(ImportLog).where(ImportLog.user_id == user_id))).scalars().all()+ Backup is scoped to one workspace at a time — users with multiple+ workspaces back each one up separately. AssetValue inherits its+ workspace from its Asset and is filtered transitively.+ """+ ws_id = ctx.workspace.id++ accounts = (await session.execute(select(Account).where(Account.workspace_id == ws_id))).scalars().all()+ transactions = (await session.execute(select(Transaction).where(Transaction.workspace_id == ws_id))).scalars().all()+ categories = (await session.execute(select(Category).where(Category.workspace_id == ws_id))).scalars().all()+ category_groups = (await session.execute(select(CategoryGroup).where(CategoryGroup.workspace_id == ws_id))).scalars().all()+ rules = (await session.execute(select(Rule).where(Rule.workspace_id == ws_id))).scalars().all()+ recurring_transactions = (await session.execute(select(RecurringTransaction).where(RecurringTransaction.workspace_id == ws_id))).scalars().all()+ budgets = (await session.execute(select(Budget).where(Budget.workspace_id == ws_id))).scalars().all()+ assets = (await session.execute(select(Asset).where(Asset.workspace_id == ws_id))).scalars().all()+ import_logs = (await session.execute(select(ImportLog).where(ImportLog.workspace_id == ws_id))).scalars().all()- # AssetValue lacks user_id — filter via asset_idsasset_ids = [a.id for a in assets]if asset_ids:asset_values = (await session.execute(select(AssetValue).where(AssetValue.asset_id.in_(asset_ids)))).scalars().all()@@ -80,7 +83,6 @@ async def backup("import_logs": import_logs,}- # Build in-memory ZIPbuf = io.BytesIO()with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:entity_counts = {}@@ -92,6 +94,8 @@ async def backup(metadata = {"export_date": datetime.utcnow().isoformat(),"format_version": "1.0",+ "workspace_id": str(ws_id),+ "workspace_name": ctx.workspace.name,"entity_counts": entity_counts,}zf.writestr("metadata.json", json.dumps(metadata, indent=2, ensure_ascii=False))diff --git a/backend/app/api/goals.py b/backend/app/api/goals.pyindex 2ca7ecab..8b5c4334 100644--- a/backend/app/api/goals.py+++ b/backend/app/api/goals.py@@ -4,9 +4,12 @@ from typing import Optionalfrom fastapi import APIRouter, Depends, HTTPException, Query, statusfrom sqlalchemy.ext.asyncio import AsyncSession-from app.core.auth import current_active_userfrom app.core.database import get_async_session-from app.models.user import User+from app.core.workspace_context import (+ WorkspaceContext,+ current_workspace,+ current_writable_workspace,+)from app.schemas.goal import GoalCreate, GoalRead, GoalSummary, GoalUpdatefrom app.services import goal_service@@ -16,29 +19,29 @@ router = APIRouter(prefix="/api/goals", tags=["goals"])@router.get("", response_model=list[GoalRead])async def list_goals(status: Optional[str] = Query(None),+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- return await goal_service.get_goals(session, user.id, status)+ return await goal_service.get_goals(session, ctx.workspace.id, ctx.user_id, status)@router.get("/summary", response_model=list[GoalSummary])async def goal_summary(limit: int = Query(3, ge=1, le=10),+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- return await goal_service.get_goal_summary(session, user.id, limit)+ return await goal_service.get_goal_summary(session, ctx.workspace.id, ctx.user_id, limit)@router.post("", response_model=GoalRead, status_code=status.HTTP_201_CREATED)async def create_goal(data: GoalCreate,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):try:- return await goal_service.create_goal(session, user.id, data)+ return await goal_service.create_goal(session, ctx.workspace.id, ctx.user_id, data)except Exception as e:raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))@@ -46,10 +49,10 @@ async def create_goal(@router.get("/{goal_id}", response_model=GoalRead)async def get_goal(goal_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- goal = await goal_service.get_goal(session, goal_id, user.id)+ goal = await goal_service.get_goal(session, goal_id, ctx.workspace.id, ctx.user_id)if not goal:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Goal not found")return goal@@ -59,10 +62,10 @@ async def get_goal(async def update_goal(goal_id: uuid.UUID,data: GoalUpdate,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- goal = await goal_service.update_goal(session, goal_id, user.id, data)+ goal = await goal_service.update_goal(session, goal_id, ctx.workspace.id, ctx.user_id, data)if not goal:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Goal not found")return goal@@ -71,9 +74,9 @@ async def update_goal(@router.delete("/{goal_id}", status_code=status.HTTP_204_NO_CONTENT)async def delete_goal(goal_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- deleted = await goal_service.delete_goal(session, goal_id, user.id)+ deleted = await goal_service.delete_goal(session, goal_id, ctx.workspace.id)if not deleted:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Goal not found")diff --git a/backend/app/api/groups.py b/backend/app/api/groups.pyindex f3821951..f5acea39 100644--- a/backend/app/api/groups.py+++ b/backend/app/api/groups.py@@ -3,9 +3,12 @@ import uuidfrom fastapi import APIRouter, Depends, HTTPException, Query, statusfrom sqlalchemy.ext.asyncio import AsyncSession-from app.core.auth import current_active_userfrom app.core.database import get_async_session-from app.models.user import User+from app.core.workspace_context import (+ WorkspaceContext,+ current_workspace,+ current_writable_workspace,+)from app.schemas.group import (GroupBalances,GroupCreate,@@ -29,20 +32,22 @@ router = APIRouter(prefix="/api/groups", tags=["groups"])@router.get("", response_model=list[GroupRead])async def list_groups(include_archived: bool = Query(False),+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- return await group_service.list_groups(session, user.id, include_archived=include_archived)+ return await group_service.list_groups(+ session, ctx.workspace.id, ctx.user_id, include_archived=include_archived+ )@router.post("", response_model=GroupRead, status_code=status.HTTP_201_CREATED)async def create_group(data: GroupCreate,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):try:- return await group_service.create_group(session, user.id, data)+ return await group_service.create_group(session, ctx.workspace.id, ctx.user_id, data)except ValueError as e:raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))@@ -50,12 +55,15 @@ async def create_group(@router.get("/{group_id}", response_model=GroupRead)async def get_group(group_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- # Read endpoint — visible to the owner and to any linked member,- # so a person added to someone else's group can see the shared view.- group = await group_service.get_group_visible(session, group_id, user.id)+ # Read endpoint — visible to workspace members and to cross-workspace+ # linked members (the Splitwise case where someone is added from+ # outside this workspace).+ group = await group_service.get_group_visible(+ session, group_id, ctx.workspace.id, ctx.user_id+ )if not group:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Group not found")return group@@ -65,11 +73,13 @@ async def get_group(async def update_group(group_id: uuid.UUID,data: GroupUpdate,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):try:- group = await group_service.update_group(session, group_id, user.id, data)+ group = await group_service.update_group(+ session, group_id, ctx.workspace.id, ctx.user_id, data+ )except ValueError as e:raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))if not group:@@ -80,11 +90,11 @@ async def update_group(@router.delete("/{group_id}", status_code=status.HTTP_204_NO_CONTENT)async def delete_group(group_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):try:- deleted = await group_service.delete_group(session, group_id, user.id)+ deleted = await group_service.delete_group(session, group_id, ctx.workspace.id)except ValueError as e:raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(e))if not deleted:@@ -94,10 +104,12 @@ async def delete_group(@router.get("/{group_id}/members", response_model=list[GroupMemberRead])async def list_members(group_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- members = await group_service.list_members(session, group_id, user.id)+ members = await group_service.list_members(+ session, group_id, ctx.workspace.id, ctx.user_id+ )if members is None:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Group not found")return members@@ -111,11 +123,11 @@ async def list_members(async def create_member(group_id: uuid.UUID,data: GroupMemberCreate,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):try:- member = await group_service.create_member(session, group_id, user.id, data)+ member = await group_service.create_member(session, group_id, ctx.workspace.id, data)except ValueError as e:raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))if member is None:@@ -128,11 +140,13 @@ async def update_member(group_id: uuid.UUID,member_id: uuid.UUID,data: GroupMemberUpdate,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):try:- member = await group_service.update_member(session, group_id, member_id, user.id, data)+ member = await group_service.update_member(+ session, group_id, member_id, ctx.workspace.id, data+ )except ValueError as e:raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))if member is None:@@ -146,11 +160,13 @@ async def update_member(async def delete_member(group_id: uuid.UUID,member_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):try:- deleted = await group_service.delete_member(session, group_id, member_id, user.id)+ deleted = await group_service.delete_member(+ session, group_id, member_id, ctx.workspace.id+ )except ValueError as e:raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(e))if not deleted:@@ -161,10 +177,12 @@ async def delete_member(async def list_group_transactions(group_id: uuid.UUID,limit: int = 20,+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- txs = await group_service.list_transactions(session, group_id, user.id, limit=limit)+ txs = await group_service.list_transactions(+ session, group_id, ctx.workspace.id, ctx.user_id, limit=limit+ )if txs is None:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Group not found")return txs@@ -173,10 +191,12 @@ async def list_group_transactions(@router.get("/{group_id}/balances", response_model=GroupBalances)async def get_balances(group_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- balances = await balance_service.compute_balances(session, group_id, user.id)+ balances = await balance_service.compute_balances(+ session, group_id, ctx.workspace.id, ctx.user_id+ )if balances is None:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Group not found")return balances@@ -185,10 +205,12 @@ async def get_balances(@router.get("/{group_id}/settlements", response_model=list[GroupSettlementRead])async def list_settlements(group_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- settlements = await settlement_service.list_settlements(session, group_id, user.id)+ settlements = await settlement_service.list_settlements(+ session, group_id, ctx.workspace.id, ctx.user_id+ )if settlements is None:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Group not found")return settlements@@ -202,12 +224,12 @@ async def list_settlements(async def create_settlement(group_id: uuid.UUID,data: GroupSettlementCreate,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):try:settlement = await settlement_service.create_settlement(- session, group_id, user.id, data+ session, group_id, ctx.workspace.id, ctx.user_id, data)except PermissionError as e:raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(e))@@ -225,12 +247,12 @@ async def update_settlement(group_id: uuid.UUID,settlement_id: uuid.UUID,data: GroupSettlementUpdate,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):try:settlement = await settlement_service.update_settlement(- session, group_id, settlement_id, user.id, data+ session, group_id, settlement_id, ctx.workspace.id, ctx.user_id, data)except PermissionError as e:raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(e))@@ -250,12 +272,12 @@ async def update_settlement(async def delete_settlement(group_id: uuid.UUID,settlement_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):try:deleted = await settlement_service.delete_settlement(- session, group_id, settlement_id, user.id+ session, group_id, settlement_id, ctx.workspace.id, ctx.user_id)except PermissionError as e:raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(e))diff --git a/backend/app/api/import_logs.py b/backend/app/api/import_logs.pyindex d0911970..4e08d0e7 100644--- a/backend/app/api/import_logs.py+++ b/backend/app/api/import_logs.py@@ -3,11 +3,14 @@ from sqlalchemy import delete, selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom sqlalchemy.orm import joinedload-from app.core.auth import current_active_userfrom app.core.database import get_async_session+from app.core.workspace_context import (+ WorkspaceContext,+ current_workspace,+ current_writable_workspace,+)from app.models.import_log import ImportLogfrom app.models.transaction import Transaction-from app.models.user import Userfrom app.schemas.import_log import ImportLogReadrouter = APIRouter(prefix="/api/import-logs", tags=["import-logs"])@@ -15,13 +18,13 @@ router = APIRouter(prefix="/api/import-logs", tags=["import-logs"])@router.get("", response_model=list[ImportLogRead])async def list_import_logs(+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):result = await session.execute(select(ImportLog).options(joinedload(ImportLog.account))- .where(ImportLog.user_id == user.id)+ .where(ImportLog.workspace_id == ctx.workspace.id).order_by(ImportLog.created_at.desc()))logs = result.scalars().unique().all()@@ -45,14 +48,16 @@ async def list_import_logs(@router.delete("/{import_log_id}", status_code=status.HTTP_204_NO_CONTENT)async def delete_import_log(import_log_id: str,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):import uuid as _uuidlog_id = _uuid.UUID(import_log_id)result = await session.execute(- select(ImportLog).where(ImportLog.id == log_id, ImportLog.user_id == user.id)+ select(ImportLog).where(+ ImportLog.id == log_id, ImportLog.workspace_id == ctx.workspace.id+ ))log = result.scalar_one_or_none()if not log:diff --git a/backend/app/api/import_transactions.py b/backend/app/api/import_transactions.pyindex ad015713..6de92028 100644--- a/backend/app/api/import_transactions.py+++ b/backend/app/api/import_transactions.py@@ -5,12 +5,14 @@ from typing import Optionalfrom fastapi import APIRouter, Depends, File, Form, HTTPException, UploadFile, statusfrom sqlalchemy.ext.asyncio import AsyncSession-from app.core.auth import current_active_userfrom app.core.database import get_async_session-from app.models.user import User+from app.core.workspace_context import (+ WorkspaceContext,+ current_workspace,+ current_writable_workspace,+)from app.schemas.transaction import TransactionImportPreview, TransactionImportRequest-from app.services import import_service-from app.services import account_service+from app.services import account_service, import_servicelogger = logging.getLogger(__name__)@@ -25,8 +27,8 @@ async def preview_import(inflow_column: Optional[str] = Form(None),outflow_column: Optional[str] = Form(None),column_mapping: Optional[str] = Form(None),+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):content = await file.read()filename = file.filename or ""@@ -117,7 +119,7 @@ async def preview_import()transactions = await import_service.enrich_with_category_suggestions(- session, user.id, transactions,+ session, ctx.workspace.id, transactions,)# Expose CSV headers so the UI can offer accurate column-mapping dropdowns.@@ -139,16 +141,18 @@ async def preview_import(@router.post("/import", status_code=status.HTTP_201_CREATED)async def import_transactions(data: TransactionImportRequest,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- # Verify account belongs to user- account = await account_service.get_account(session, data.account_id, user.id)+ # Verify the target account lives in this workspace BEFORE doing any+ # writes — otherwise a hand-rolled request could import into an+ # account owned by another tenant.+ account = await account_service.get_account(session, data.account_id, ctx.workspace.id)if not account:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Account not found")imported, skipped, excluded, import_log_id = await import_service.import_transactions(- session, user.id, data.account_id, data.transactions, "import",+ session, ctx.workspace.id, ctx.user_id, data.account_id, data.transactions, "import",filename=data.filename, detected_format=data.detected_format,detect_duplicates=data.detect_duplicates,)diff --git a/backend/app/api/payees.py b/backend/app/api/payees.pyindex 1528873d..11737ad5 100644--- a/backend/app/api/payees.py+++ b/backend/app/api/payees.py@@ -5,9 +5,12 @@ from typing import Optionalfrom fastapi import APIRouter, Depends, HTTPException, Query, statusfrom sqlalchemy.ext.asyncio import AsyncSession-from app.core.auth import current_active_userfrom app.core.database import get_async_session-from app.models.user import User+from app.core.workspace_context import (+ WorkspaceContext,+ current_workspace,+ current_writable_workspace,+)from app.schemas.payee import PayeeCreate, PayeeMergeRequest, PayeeRead, PayeeSummary, PayeeUpdatefrom app.schemas.category import CategoryReadfrom app.services import payee_service@@ -17,19 +20,19 @@ router = APIRouter(prefix="/api/payees", tags=["payees"])@router.get("", response_model=list[PayeeRead])async def list_payees(+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- return await payee_service.get_payees(session, user.id)+ return await payee_service.get_payees(session, ctx.workspace.id)@router.get("/{payee_id}", response_model=PayeeRead)async def get_payee(payee_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- payee = await payee_service.get_payee(session, payee_id, user.id)+ payee = await payee_service.get_payee(session, payee_id, ctx.workspace.id)if not payee:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Payee not found")return payee@@ -40,11 +43,11 @@ async def get_payee_summary(payee_id: uuid.UUID,start_date: Optional[date] = Query(None, alias="from"),end_date: Optional[date] = Query(None, alias="to"),+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):try:- result = await payee_service.get_payee_summary(session, payee_id, user.id, start_date, end_date)+ result = await payee_service.get_payee_summary(session, payee_id, ctx.workspace.id, start_date, end_date)return PayeeSummary(payee=PayeeRead.model_validate(result["payee"], from_attributes=True),total_spent=result["total_spent"],@@ -60,11 +63,11 @@ async def get_payee_summary(@router.post("", response_model=PayeeRead, status_code=status.HTTP_201_CREATED)async def create_payee(data: PayeeCreate,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):try:- return await payee_service.create_payee(session, user.id, data)+ return await payee_service.create_payee(session, ctx.workspace.id, ctx.user_id, data)except ValueError as e:raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))@@ -73,11 +76,11 @@ async def create_payee(async def update_payee(payee_id: uuid.UUID,data: PayeeUpdate,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):try:- payee = await payee_service.update_payee(session, payee_id, user.id, data)+ payee = await payee_service.update_payee(session, payee_id, ctx.workspace.id, data)except ValueError as e:raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))if not payee:@@ -88,10 +91,10 @@ async def update_payee(@router.delete("/{payee_id}", status_code=status.HTTP_204_NO_CONTENT)async def delete_payee(payee_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- deleted = await payee_service.delete_payee(session, payee_id, user.id)+ deleted = await payee_service.delete_payee(session, payee_id, ctx.workspace.id)if not deleted:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Payee not found")@@ -99,11 +102,11 @@ async def delete_payee(@router.post("/merge")async def merge_payees(data: PayeeMergeRequest,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):try:- reassigned = await payee_service.merge_payees(session, user.id, data.target_id, data.source_ids)+ reassigned = await payee_service.merge_payees(session, ctx.workspace.id, data.target_id, data.source_ids)return {"merged": len(data.source_ids), "transactions_reassigned": reassigned}except ValueError as e:raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))diff --git a/backend/app/api/recurring_transactions.py b/backend/app/api/recurring_transactions.pyindex 663ffb0d..9a61df33 100644--- a/backend/app/api/recurring_transactions.py+++ b/backend/app/api/recurring_transactions.py@@ -3,9 +3,12 @@ import uuidfrom fastapi import APIRouter, Depends, HTTPException, statusfrom sqlalchemy.ext.asyncio import AsyncSession-from app.core.auth import current_active_userfrom app.core.database import get_async_session-from app.models.user import User+from app.core.workspace_context import (+ WorkspaceContext,+ current_workspace,+ current_writable_workspace,+)from app.schemas.recurring_transaction import (RecurringTransactionCreate,RecurringTransactionRead,@@ -18,20 +21,22 @@ router = APIRouter(prefix="/api/recurring-transactions", tags=["recurring-transa@router.get("", response_model=list[RecurringTransactionRead])async def list_recurring_transactions(+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- return await recurring_transaction_service.get_recurring_transactions(session, user.id)+ return await recurring_transaction_service.get_recurring_transactions(session, ctx.workspace.id)@router.post("", response_model=RecurringTransactionRead, status_code=status.HTTP_201_CREATED)async def create_recurring_transaction(data: RecurringTransactionCreate,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):try:- return await recurring_transaction_service.create_recurring_transaction(session, user.id, data)+ return await recurring_transaction_service.create_recurring_transaction(+ session, ctx.workspace.id, ctx.user_id, data+ )except ValueError as e:raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))@@ -40,12 +45,12 @@ async def create_recurring_transaction(async def update_recurring_transaction(recurring_id: uuid.UUID,data: RecurringTransactionUpdate,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):try:recurring = await recurring_transaction_service.update_recurring_transaction(- session, recurring_id, user.id, data+ session, recurring_id, ctx.workspace.id, data)except ValueError as e:raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))@@ -57,18 +62,20 @@ async def update_recurring_transaction(@router.delete("/{recurring_id}", status_code=status.HTTP_204_NO_CONTENT)async def delete_recurring_transaction(recurring_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- deleted = await recurring_transaction_service.delete_recurring_transaction(session, recurring_id, user.id)+ deleted = await recurring_transaction_service.delete_recurring_transaction(+ session, recurring_id, ctx.workspace.id+ )if not deleted:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Recurring transaction not found")@router.post("/generate")async def generate_recurring_transactions(+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- count = await recurring_transaction_service.generate_pending(session, user.id)+ count = await recurring_transaction_service.generate_pending(session, ctx.user_id)return {"generated": count}diff --git a/backend/app/api/reports.py b/backend/app/api/reports.pyindex 32e99dde..318143fe 100644--- a/backend/app/api/reports.py+++ b/backend/app/api/reports.py@@ -1,9 +1,8 @@from fastapi import APIRouter, Depends, Queryfrom sqlalchemy.ext.asyncio import AsyncSession-from app.core.auth import current_active_userfrom app.core.database import get_async_session-from app.models.user import User+from app.core.workspace_context import WorkspaceContext, current_workspacefrom app.schemas.report import ReportResponsefrom app.services import report_service@@ -14,11 +13,11 @@ router = APIRouter(prefix="/api/reports", tags=["reports"])async def get_net_worth(months: int = Query(12, ge=1, le=24),interval: str = Query("monthly", pattern="^(daily|weekly|monthly|yearly)$"),+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):return await report_service.get_net_worth_report(- session, user.id, months, interval, user.primary_currency+ session, ctx.workspace.id, ctx.user_id, months, interval, ctx.user.primary_currency)@@ -26,11 +25,11 @@ async def get_net_worth(async def get_income_expenses(months: int = Query(12, ge=1, le=24),interval: str = Query("monthly", pattern="^(daily|weekly|monthly|yearly)$"),+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):return await report_service.get_income_expenses_report(- session, user.id, months, interval, user.primary_currency+ session, ctx.workspace.id, ctx.user_id, months, interval, ctx.user.primary_currency)@@ -39,9 +38,9 @@ async def get_cash_flow(months: int = Query(6, ge=1, le=12),interval: str = Query("daily", pattern="^(daily|weekly|monthly)$"),baseline: bool = Query(False),+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):return await report_service.get_cash_flow_report(- session, user.id, months, interval, user.primary_currency, baseline=baseline,+ session, ctx.workspace.id, ctx.user_id, months, interval, ctx.user.primary_currency, baseline=baseline,)diff --git a/backend/app/api/rules.py b/backend/app/api/rules.pyindex 4d5a24a2..9ebb8ac2 100644--- a/backend/app/api/rules.py+++ b/backend/app/api/rules.py@@ -3,9 +3,12 @@ import uuidfrom fastapi import APIRouter, Depends, HTTPException, statusfrom sqlalchemy.ext.asyncio import AsyncSession-from app.core.auth import current_active_userfrom app.core.database import get_async_session-from app.models.user import User+from app.core.workspace_context import (+ WorkspaceContext,+ current_workspace,+ current_writable_workspace,+)from app.schemas.rule import RuleCreate, RuleRead, RuleUpdatefrom app.services import rule_servicefrom app.services.rule_service import DuplicateRuleError@@ -15,20 +18,20 @@ router = APIRouter(prefix="/api/rules", tags=["rules"])@router.get("", response_model=list[RuleRead])async def list_rules(+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- return await rule_service.get_rules(session, user.id)+ return await rule_service.get_rules(session, ctx.workspace.id)@router.post("", response_model=RuleRead, status_code=status.HTTP_201_CREATED)async def create_rule(data: RuleCreate,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):try:- return await rule_service.create_rule(session, user.id, data)+ return await rule_service.create_rule(session, ctx.workspace.id, ctx.user_id, data)except DuplicateRuleError:raise HTTPException(status_code=status.HTTP_409_CONFLICT,@@ -40,11 +43,11 @@ async def create_rule(async def update_rule(rule_id: uuid.UUID,data: RuleUpdate,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):try:- rule = await rule_service.update_rule(session, rule_id, user.id, data)+ rule = await rule_service.update_rule(session, rule_id, ctx.workspace.id, data)except DuplicateRuleError:raise HTTPException(status_code=status.HTTP_409_CONFLICT,@@ -58,21 +61,21 @@ async def update_rule(@router.delete("/{rule_id}", status_code=status.HTTP_204_NO_CONTENT)async def delete_rule(rule_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- deleted = await rule_service.delete_rule(session, rule_id, user.id)+ deleted = await rule_service.delete_rule(session, rule_id, ctx.workspace.id)if not deleted:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Rule not found")@router.get("/packs", response_model=list[dict])async def list_rule_packs(+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):"""List available country-specific rule packs with installed status."""- installed_map = await rule_service.get_installed_packs(session, user.id)+ installed_map = await rule_service.get_installed_packs(session, ctx.user_id)packs = []for code, pack in rule_service.RULE_PACKS.items():packs.append({@@ -89,8 +92,8 @@ async def list_rule_packs(async def install_rule_pack(pack_code: str,create_missing_categories: bool = False,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):"""Install a country-specific rule pack.@@ -99,10 +102,10 @@ async def install_rule_pack("""if pack_code not in rule_service.RULE_PACKS:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Rule pack not found")- lang = (user.preferences or {}).get("language", "pt-BR")+ lang = (ctx.user.preferences or {}).get("language", "pt-BR")result = await rule_service.install_rule_pack(session,- user.id,+ ctx.user_id,pack_code,lang,create_missing_categories=create_missing_categories,@@ -116,9 +119,9 @@ async def install_rule_pack(@router.post("/apply-all", response_model=dict)async def apply_all_rules(+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):"""Re-apply all active rules to all existing transactions."""- count = await rule_service.apply_all_rules(session, user.id)+ count = await rule_service.apply_all_rules(session, ctx.workspace.id)return {"applied": count}diff --git a/backend/app/api/search.py b/backend/app/api/search.pyindex 064532fb..b84c9d74 100644--- a/backend/app/api/search.py+++ b/backend/app/api/search.py@@ -1,9 +1,8 @@from fastapi import APIRouter, Depends, Queryfrom sqlalchemy.ext.asyncio import AsyncSession-from app.core.auth import current_active_userfrom app.core.database import get_async_session-from app.models.user import User+from app.core.workspace_context import WorkspaceContext, current_workspacefrom app.services import search_servicerouter = APIRouter(prefix="/api/search", tags=["search"])@@ -13,8 +12,8 @@ router = APIRouter(prefix="/api/search", tags=["search"])async def global_search(q: str = Query("", min_length=0, max_length=100),limit: int = Query(5, ge=1, le=20),+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):"""Global search across transactions, accounts, payees, categories, goals and assets.@@ -23,7 +22,8 @@ async def global_search("""hits = await search_service.search_all(session=session,- user_id=user.id,+ workspace_id=ctx.workspace.id,+ user_id=ctx.user_id,query=q,per_type_limit=limit,)diff --git a/backend/app/api/setup.py b/backend/app/api/setup.pyindex 0444c76f..e5660ba8 100644--- a/backend/app/api/setup.py+++ b/backend/app/api/setup.py@@ -64,10 +64,19 @@ async def create_admin(sql_update(User).where(User.id == user.id).values(preferences=prefs))+ # Personal workspace gets auto-created here too (setup endpoint runs+ # programmatically, so the registration hook's `request is None` early+ # exit fires; we have to set up the workspace ourselves).+ from app.services.workspace_service import create_personal_workspace_for_user++ await db_session.refresh(user)+ workspace = await create_personal_workspace_for_user(db_session, user)+# Create default wallet with the chosen currencywallet_name = "Carteira" if body.language.startswith("pt") else "Wallet"wallet = Account(user_id=user.id,+ workspace_id=workspace.id,name=wallet_name,type="checking",balance=Decimal("0.00"),@@ -80,8 +89,8 @@ async def create_admin(from app.services.category_service import create_default_categoriesfrom app.services.rule_service import create_default_rules- await create_default_categories(db_session, user.id, body.language)- await create_default_rules(db_session, user.id, body.language)+ await create_default_categories(db_session, user.id, body.language, workspace_id=workspace.id)+ await create_default_rules(db_session, user.id, body.language, workspace_id=workspace.id)# Refresh user to get updated preferences for token generationawait db_session.refresh(user)diff --git a/backend/app/api/transactions.py b/backend/app/api/transactions.pyindex 23430424..17bf9680 100644--- a/backend/app/api/transactions.py+++ b/backend/app/api/transactions.py@@ -9,9 +9,12 @@ from fastapi.responses import StreamingResponsefrom pydantic import BaseModelfrom sqlalchemy.ext.asyncio import AsyncSession-from app.core.auth import current_active_userfrom app.core.database import get_async_session-from app.models.user import User+from app.core.workspace_context import (+ WorkspaceContext,+ current_workspace,+ current_writable_workspace,+)from app.schemas.transaction import BulkAddToGroupRequest, BulkCategorizeRequest, BulkTagsRequest, CreateCounterpartRequest, LinkTransferRequest, TransactionCreate, TransactionRead, TransactionUpdate, TransferCreate, TransferReadfrom app.services import transaction_servicefrom app.services.admin_service import get_credit_card_accounting_mode@@ -81,12 +84,12 @@ async def list_transactions(max_amount: Optional[float] = Query(None, ge=0, description="Filter to transactions with absolute amount <= this value (primary currency)."),sort_by: Optional[str] = Query(None, description="Column to sort by (date|amount|description|payee|category|account|type|status). Default: date desc."),sort_dir: str = Query("desc", regex="^(asc|desc)$"),+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):accounting_mode = await get_credit_card_accounting_mode(session)transactions, total, summary = await transaction_service.get_transactions(- session, user.id,+ session, ctx.workspace.id, ctx.user_id,account_ids=_merge_id_filters(account_id, account_ids),category_ids=_merge_id_filters(category_id, category_ids),payee_id=payee_id, from_date=from_date, to_date=to_date, page=page, limit=limit,@@ -103,7 +106,7 @@ async def list_transactions(max_amount=max_amount,include_summary=True,)- primary_currency = user.primary_currency+ primary_currency = ctx.user.primary_currencyitems = [_tag_fx_fallback(TransactionRead.model_validate(tx, from_attributes=True), primary_currency) for tx in transactions]summary_out = (TransactionsSummary(**summary, currency=primary_currency)@@ -126,23 +129,23 @@ async def export_transactions(uncategorized: bool = Query(False),type: Optional[str] = Query(None),tags: Optional[List[str]] = Query(None),- transaction_ids: Optional[List[uuid.UUID]] = Query(None, description="If set, exports exactly these rows (scoped to the user); other filters are ignored."),+ transaction_ids: Optional[List[uuid.UUID]] = Query(None, description="If set, exports exactly these rows (scoped to the workspace); other filters are ignored."),+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):accounting_mode = await get_credit_card_accounting_mode(session)if transaction_ids:# Selection-only export: bypass user-facing filters but keep the- # service-level user/visibility scoping intact.+ # service-level workspace/visibility scoping intact.transactions, _, _ = await transaction_service.get_transactions(- session, user.id,+ session, ctx.workspace.id, ctx.user_id,skip_pagination=True,accounting_mode=accounting_mode,transaction_ids=transaction_ids,)else:transactions, _, _ = await transaction_service.get_transactions(- session, user.id,+ session, ctx.workspace.id, ctx.user_id,account_ids=_merge_id_filters(account_id, account_ids),category_ids=_merge_id_filters(category_id, category_ids),payee_id=payee_id, from_date=from_date, to_date=to_date,@@ -152,7 +155,7 @@ async def export_transactions()output = io.StringIO()- output.write("\ufeff") # UTF-8 BOM for Excel+ output.write("") # UTF-8 BOM for Excelwriter = csv.writer(output)writer.writerow(["date", "description", "amount", "type", "currency", "category", "account", "payee", "payee_name", "notes", "status", "source", "amount_primary", "fx_rate_used"])for tx in transactions:@@ -185,11 +188,11 @@ async def export_transactions(@router.patch("/bulk-categorize")async def bulk_categorize(data: BulkCategorizeRequest,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):count = await transaction_service.bulk_update_category(- session, user.id, data.transaction_ids, data.category_id+ session, ctx.workspace.id, data.transaction_ids, data.category_id)return {"updated": count}@@ -197,11 +200,11 @@ async def bulk_categorize(@router.patch("/bulk-add-tags")async def bulk_add_tags(data: BulkTagsRequest,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):count = await transaction_service.bulk_add_tags(- session, user.id, data.transaction_ids, data.tags+ session, ctx.workspace.id, data.transaction_ids, data.tags)return {"updated": count}@@ -209,11 +212,11 @@ async def bulk_add_tags(@router.patch("/bulk-remove-tags")async def bulk_remove_tags(data: BulkTagsRequest,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):count = await transaction_service.bulk_remove_tags(- session, user.id, data.transaction_ids, data.tags+ session, ctx.workspace.id, data.transaction_ids, data.tags)return {"updated": count}@@ -221,13 +224,14 @@ async def bulk_remove_tags(@router.patch("/bulk-add-to-group")async def bulk_add_to_group(data: BulkAddToGroupRequest,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):try:return await transaction_service.bulk_add_to_group(session,- user.id,+ ctx.workspace.id,+ ctx.user_id,data.transaction_ids,data.group_id,share_type=data.share_type,@@ -240,14 +244,16 @@ async def bulk_add_to_group(@router.post("/transfer", response_model=TransferRead, status_code=status.HTTP_201_CREATED)async def create_transfer(data: TransferCreate,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):try:- debit_tx, credit_tx = await transaction_service.create_transfer(session, user.id, data)- debit_full = await transaction_service.get_transaction(session, debit_tx.id, user.id)- credit_full = await transaction_service.get_transaction(session, credit_tx.id, user.id)- primary_currency = user.primary_currency+ debit_tx, credit_tx = await transaction_service.create_transfer(+ session, ctx.workspace.id, ctx.user_id, data+ )+ debit_full = await transaction_service.get_transaction(session, debit_tx.id, ctx.workspace.id)+ credit_full = await transaction_service.get_transaction(session, credit_tx.id, ctx.workspace.id)+ primary_currency = ctx.user.primary_currencyreturn TransferRead(debit=_tag_fx_fallback(TransactionRead.model_validate(debit_full, from_attributes=True), primary_currency),credit=_tag_fx_fallback(TransactionRead.model_validate(credit_full, from_attributes=True), primary_currency),@@ -260,17 +266,17 @@ async def create_transfer(@router.post("/link-transfer", response_model=TransferRead)async def link_transfer(data: LinkTransferRequest,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):"""Link two existing transactions as an inter-account transfer pair."""try:debit_tx, credit_tx = await transaction_service.link_existing_as_transfer(- session, user.id, data.transaction_ids+ session, ctx.workspace.id, data.transaction_ids)- debit_full = await transaction_service.get_transaction(session, debit_tx.id, user.id)- credit_full = await transaction_service.get_transaction(session, credit_tx.id, user.id)- primary_currency = user.primary_currency+ debit_full = await transaction_service.get_transaction(session, debit_tx.id, ctx.workspace.id)+ credit_full = await transaction_service.get_transaction(session, credit_tx.id, ctx.workspace.id)+ primary_currency = ctx.user.primary_currencyreturn TransferRead(debit=_tag_fx_fallback(TransactionRead.model_validate(debit_full, from_attributes=True), primary_currency),credit=_tag_fx_fallback(TransactionRead.model_validate(credit_full, from_attributes=True), primary_currency),@@ -284,18 +290,18 @@ async def link_transfer(async def create_counterpart(transaction_id: uuid.UUID,data: CreateCounterpartRequest,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):"""Mark a transaction as a transfer by auto-creating its counterpart inanother (typically manual) account."""try:debit_tx, credit_tx = await transaction_service.create_transfer_counterpart(- session, user.id, transaction_id, data.to_account_id+ session, ctx.workspace.id, ctx.user_id, transaction_id, data.to_account_id)- debit_full = await transaction_service.get_transaction(session, debit_tx.id, user.id)- credit_full = await transaction_service.get_transaction(session, credit_tx.id, user.id)- primary_currency = user.primary_currency+ debit_full = await transaction_service.get_transaction(session, debit_tx.id, ctx.workspace.id)+ credit_full = await transaction_service.get_transaction(session, credit_tx.id, ctx.workspace.id)+ primary_currency = ctx.user.primary_currencyreturn TransferRead(debit=_tag_fx_fallback(TransactionRead.model_validate(debit_full, from_attributes=True), primary_currency),credit=_tag_fx_fallback(TransactionRead.model_validate(credit_full, from_attributes=True), primary_currency),@@ -310,17 +316,17 @@ async def get_transfer_candidates(transaction_id: uuid.UUID,limit: int = Query(10, ge=1, le=50),window_days: int = Query(30, ge=1, le=365),+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):"""Return ranked candidate transactions to link as a transfer counterpart."""- anchor = await transaction_service.get_transaction(session, transaction_id, user.id)+ anchor = await transaction_service.get_transaction(session, transaction_id, ctx.workspace.id)if not anchor:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Transaction not found")candidates = await transaction_service.get_transfer_candidates(- session, user.id, transaction_id, limit=limit, window_days=window_days+ session, ctx.workspace.id, transaction_id, limit=limit, window_days=window_days)- primary_currency = user.primary_currency+ primary_currency = ctx.user.primary_currencyreturn [_tag_fx_fallback(TransactionRead.model_validate(tx, from_attributes=True), primary_currency)for tx in candidates@@ -330,26 +336,28 @@ async def get_transfer_candidates(@router.get("/{transaction_id}", response_model=TransactionRead)async def get_transaction(transaction_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- transaction = await transaction_service.get_transaction(session, transaction_id, user.id)+ transaction = await transaction_service.get_transaction(session, transaction_id, ctx.workspace.id)if not transaction:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Transaction not found")- primary_currency = user.primary_currency+ primary_currency = ctx.user.primary_currencyreturn _tag_fx_fallback(TransactionRead.model_validate(transaction, from_attributes=True), primary_currency)@router.post("", response_model=TransactionRead, status_code=status.HTTP_201_CREATED)async def create_transaction(data: TransactionCreate,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):try:- transaction = await transaction_service.create_transaction(session, user.id, data)- full_tx = await transaction_service.get_transaction(session, transaction.id, user.id)- primary_currency = user.primary_currency+ transaction = await transaction_service.create_transaction(+ session, ctx.workspace.id, ctx.user_id, data+ )+ full_tx = await transaction_service.get_transaction(session, transaction.id, ctx.workspace.id)+ primary_currency = ctx.user.primary_currencyreturn _tag_fx_fallback(TransactionRead.model_validate(full_tx, from_attributes=True), primary_currency)except ValueError as e:raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))@@ -359,38 +367,44 @@ async def create_transaction(async def update_transaction(transaction_id: uuid.UUID,data: TransactionUpdate,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):try:- transaction = await transaction_service.update_transaction(session, transaction_id, user.id, data)+ transaction = await transaction_service.update_transaction(+ session, transaction_id, ctx.workspace.id, ctx.user_id, data+ )except ValueError as e:raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))if not transaction:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Transaction not found")- primary_currency = user.primary_currency+ primary_currency = ctx.user.primary_currencyreturn _tag_fx_fallback(TransactionRead.model_validate(transaction, from_attributes=True), primary_currency)@router.patch("/{transaction_id}/ignore", response_model=TransactionRead)async def toggle_ignore_transaction(transaction_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- transaction = await transaction_service.toggle_ignore_transaction(session, transaction_id, user.id)+ transaction = await transaction_service.toggle_ignore_transaction(+ session, transaction_id, ctx.workspace.id+ )if not transaction:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Transaction not found")- primary_currency = user.primary_currency+ primary_currency = ctx.user.primary_currencyreturn _tag_fx_fallback(TransactionRead.model_validate(transaction, from_attributes=True), primary_currency)@router.delete("/{transaction_id}", status_code=status.HTTP_204_NO_CONTENT)async def delete_transaction(transaction_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),- user: User = Depends(current_active_user),):- deleted = await transaction_service.delete_transaction(session, transaction_id, user.id)+ deleted = await transaction_service.delete_transaction(+ session, transaction_id, ctx.workspace.id+ )if not deleted:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Transaction not found")diff --git a/backend/app/api/workspaces.py b/backend/app/api/workspaces.pynew file mode 100644index 00000000..f02c2a8c--- /dev/null+++ b/backend/app/api/workspaces.py@@ -0,0 +1,306 @@+"""Workspace + member management endpoints.++Note: there's intentionally NO `POST /api/workspaces` endpoint here.+Workspaces are auto-created at user registration; additional workspaces+(Freelancer / Small Business / Accountant Firm) ship as part of the+templates feature in a later phase.+"""+import uuid++from fastapi import APIRouter, Depends, HTTPException, status+from fastapi_users import schemas as fu_schemas+from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from app.core.auth import current_active_user, get_user_manager, UserManager+from app.core.database import get_async_session+from app.core.workspace_context import WorkspaceContext, current_workspace+from app.models.user import User+from app.models.workspace import Workspace, WorkspaceMember+from app.schemas.workspace import (+ MemberInvite,+ MemberRead,+ MemberRoleUpdate,+ WorkspaceCreate,+ WorkspaceRead,+ WorkspaceUpdate,+)+from app.services import workspace_service++router = APIRouter(prefix="/api/workspaces", tags=["workspaces"])+++def _user_display_name(user: User) -> str | None:+ prefs = user.preferences or {}+ return prefs.get("display_name") or None++[email protected]("", response_model=list[WorkspaceRead])+async def list_my_workspaces(+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ """Return every workspace the current user can access.++ Unions two sets:+ - workspaces where the user has a `workspace_members` row (role+ comes from that row)+ - workspaces where `workspaces.managed_by_user_id` matches the+ user but they have no membership (role = 'manager')++ A user who is both a member AND the external manager is reported+ with their concrete membership role (not the virtual manager one)+ since their explicit role is the more specific signal.+ """+ member_rows = await session.execute(+ select(Workspace, WorkspaceMember.role)+ .join(WorkspaceMember, WorkspaceMember.workspace_id == Workspace.id)+ .where(+ WorkspaceMember.user_id == user.id,+ Workspace.is_archived.is_(False),+ )+ .order_by(Workspace.created_at.asc())+ )+ 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)+ seen_ids.add(ws.id)++ managed_rows = await session.execute(+ select(Workspace)+ .where(+ Workspace.managed_by_user_id == user.id,+ Workspace.is_archived.is_(False),+ )+ .order_by(Workspace.created_at.asc())+ )+ 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)+ return out++[email protected]("", response_model=WorkspaceRead, status_code=status.HTTP_201_CREATED)+async def create_workspace_endpoint(+ body: WorkspaceCreate,+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ """Create a new workspace; the caller becomes its manager.++ Use case: a user provisioning a workspace they'll operate (either+ for themselves as a second container, or on behalf of someone else+ who'll be invited later as the day-to-day owner).+ """+ workspace = await workspace_service.create_workspace(+ session,+ name=body.name,+ creator=user,+ kind=body.kind,+ default_currency=body.default_currency,+ locale=body.locale,+ icon=body.icon,+ color=body.color,+ self_membership=body.self_membership,+ )+ await session.commit()+ item = WorkspaceRead.model_validate(workspace)+ item.role = "owner" if body.self_membership else "manager"+ return item++[email protected]("/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++[email protected]("/{workspace_id}", response_model=WorkspaceRead)+async def update_workspace(+ workspace_id: uuid.UUID,+ body: WorkspaceUpdate,+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ member = await workspace_service.require_membership(+ session, workspace_id, user.id, min_role="owner"+ )+ workspace = await session.get(Workspace, workspace_id)+ if workspace is None:+ raise HTTPException(status_code=404, detail="Workspace not found")+ for key, value in body.model_dump(exclude_unset=True).items():+ setattr(workspace, key, value)+ await session.commit()+ await session.refresh(workspace)+ item = WorkspaceRead.model_validate(workspace)+ item.role = member.role+ return item++[email protected]("/{workspace_id}/members", response_model=list[MemberRead])+async def list_workspace_members(+ workspace_id: uuid.UUID,+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ # Any member can list members of their own workspace.+ await workspace_service.require_membership(session, workspace_id, user.id)+ rows = await workspace_service.list_members(session, workspace_id)+ return [+ MemberRead(+ id=m.id,+ user_id=u.id,+ email=u.email,+ display_name=_user_display_name(u),+ role=m.role,+ joined_at=m.joined_at,+ )+ for m, u in rows+ ]+++ "/{workspace_id}/members",+ response_model=MemberRead,+ status_code=status.HTTP_201_CREATED,+)+async def invite_member(+ workspace_id: uuid.UUID,+ body: MemberInvite,+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+ user_manager: UserManager = Depends(get_user_manager),+):+ await workspace_service.require_membership(+ session, workspace_id, user.id, min_role="owner"+ )++ # Find existing user by email (case-insensitive — fastapi-users+ # stores email lowercased on register, but be safe).+ existing = await session.execute(+ select(User).where(User.email == body.email.lower())+ )+ target = existing.scalar_one_or_none()++ if target is None:+ # Brand-new user — only allowed if a password was provided.+ if not body.password:+ raise HTTPException(+ status_code=400,+ detail="User not found. Provide a password to create them.",+ )+ try:+ create_payload = fu_schemas.BaseUserCreate(+ email=body.email,+ password=body.password,+ )+ target = await user_manager.create(create_payload)+ # The fresh user gets their own Personal workspace by virtue+ # of the registration hook (called below via on_after_register+ # when request is non-None; programmatic call leaves it empty,+ # so we bootstrap explicitly).+ await workspace_service.create_personal_workspace_for_user(session, target)+ except Exception as e:+ raise HTTPException(status_code=400, detail=f"Could not create user: {e}")++ member = await workspace_service.add_member(+ session,+ workspace_id=workspace_id,+ user_id=target.id,+ role=body.role,+ invited_by_user_id=user.id,+ )+ await session.commit()+ return MemberRead(+ id=member.id,+ user_id=target.id,+ email=target.email,+ display_name=_user_display_name(target),+ role=member.role,+ joined_at=member.joined_at,+ )+++ "/{workspace_id}/members/{member_user_id}",+ response_model=MemberRead,+)+async def change_member_role(+ workspace_id: uuid.UUID,+ member_user_id: uuid.UUID,+ body: MemberRoleUpdate,+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ await workspace_service.require_membership(+ session, workspace_id, user.id, min_role="owner"+ )+ member = await workspace_service.update_member_role(+ session, workspace_id, member_user_id, body.role+ )+ await session.commit()+ target = await session.get(User, member_user_id)+ return MemberRead(+ id=member.id,+ user_id=target.id,+ email=target.email,+ display_name=_user_display_name(target),+ role=member.role,+ joined_at=member.joined_at,+ )++[email protected]("/{workspace_id}/stats")+async def workspace_stats(+ workspace_id: uuid.UUID,+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ """KPIs surfaced on the settings page (members / accounts / transactions)."""+ await workspace_service.require_membership(session, workspace_id, user.id)+ return await workspace_service.get_workspace_stats(session, workspace_id)++[email protected]("/{workspace_id}/archive", response_model=WorkspaceRead)+async def archive_workspace_endpoint(+ workspace_id: uuid.UUID,+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ """Soft-delete: flips is_archived. Requires owner role. Refuses to+ archive the requester's last accessible workspace."""+ await workspace_service.require_membership(+ session, workspace_id, user.id, min_role="owner"+ )+ workspace = await workspace_service.archive_workspace(session, workspace_id, user.id)+ await session.commit()+ item = WorkspaceRead.model_validate(workspace)+ item.role = "owner"+ return item+++ "/{workspace_id}/members/{member_user_id}",+ status_code=status.HTTP_204_NO_CONTENT,+)+async def remove_workspace_member(+ workspace_id: uuid.UUID,+ member_user_id: uuid.UUID,+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ # Owner can remove anyone; a non-owner can remove themselves only.+ requester = await workspace_service.require_membership(session, workspace_id, user.id)+ if requester.role != "owner" and member_user_id != user.id:+ raise HTTPException(status_code=403, detail="Only the owner can remove other members")+ await workspace_service.remove_member(session, workspace_id, member_user_id)+ await session.commit()+ return Nonediff --git a/backend/app/core/auth.py b/backend/app/core/auth.pyindex bde23107..63327652 100644--- a/backend/app/core/auth.py+++ b/backend/app/core/auth.py@@ -37,13 +37,20 @@ class UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):from app.models.account import Accountfrom app.services.category_service import create_default_categoriesfrom app.services.rule_service import create_default_rules+ from app.services.workspace_service import create_personal_workspace_for_usersession = self.user_db.sessioncurrency = user.primary_currencylang = (user.preferences or {}).get("language", "en")++ # Every new user gets a Personal workspace + owner membership.+ # All their seeded data (wallet, categories, rules) reparent to it.+ workspace = await create_personal_workspace_for_user(session, user)+wallet_name = "Carteira" if lang.startswith("pt") else "Wallet"wallet = Account(user_id=user.id,+ workspace_id=workspace.id,name=wallet_name,type="checking",balance=Decimal("0.00"),@@ -53,8 +60,8 @@ class UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):await session.commit()# Create default categories and rules for the new user- await create_default_categories(session, user.id, lang)- await create_default_rules(session, user.id, lang)+ await create_default_categories(session, user.id, lang, workspace_id=workspace.id)+ await create_default_rules(session, user.id, lang, workspace_id=workspace.id)async def get_user_manager(user_db: SQLAlchemyUserDatabase = Depends(get_user_db)):diff --git a/backend/app/core/workspace_autostamp.py b/backend/app/core/workspace_autostamp.pynew file mode 100644index 00000000..7213ec78--- /dev/null+++ b/backend/app/core/workspace_autostamp.py@@ -0,0 +1,180 @@+"""Auto-stamp `workspace_id` on financial entities when only `user_id` is set.++Provides backwards compatibility for code that pre-dates the workspace+column. When a row is inserted without `workspace_id` but with `user_id`,+the listener resolves the user's first workspace and fills it in. Once+the query layer + every caller passes `workspace_id` explicitly, the+listeners can be removed.++Resolution caches per `(session, user_id)` to avoid re-querying for the+common case of many rows being inserted under the same user (imports,+seed data, test fixtures).+"""+from __future__ import annotations++import uuid+from typing import Any++from sqlalchemy import event, select+from sqlalchemy.orm import Mapper, Session++from app.models.account import Account+from app.models.asset import Asset+from app.models.asset_group import AssetGroup+from app.models.asset_value import AssetValue+from app.models.bank_connection import BankConnection+from app.models.budget import Budget+from app.models.category import Category+from app.models.category_group import CategoryGroup+from app.models.credit_card_bill import CreditCardBill+from app.models.goal import Goal+from app.models.group import Group, GroupMember+from app.models.group_settlement import GroupSettlement+from app.models.import_log import ImportLog+from app.models.payee import Payee, PayeeMapping+from app.models.recurring_transaction import RecurringTransaction+from app.models.rule import Rule+from app.models.transaction import Transaction+from app.models.transaction_attachment import TransactionAttachment+from app.models.transaction_split import TransactionSplit+from app.models.workspace import Workspace, WorkspaceMember+++_AUTOSTAMP_MODELS = (+ Account,+ Asset,+ AssetGroup,+ AssetValue,+ BankConnection,+ Budget,+ Category,+ CategoryGroup,+ CreditCardBill,+ Goal,+ Group,+ GroupMember,+ GroupSettlement,+ ImportLog,+ Payee,+ PayeeMapping,+ RecurringTransaction,+ Rule,+ Transaction,+ TransactionAttachment,+ TransactionSplit,+)+++def _register_agent_models() -> tuple:+ """Optional Agent + Conversation models: register only when the agents+ feature is enabled (the modules are import-gated by AGENTS_ENABLED)."""+ try:+ from app.agents.models.agent import Agent+ from app.agents.models.conversation import Conversation++ return (Agent, Conversation)+ except Exception:+ return ()+++def _cache_key(session: Session, user_id: uuid.UUID) -> str:+ return f"_ws_autostamp:{id(session)}:{user_id}"+++def _resolve_workspace_for_user(session: Session, user_id: uuid.UUID) -> uuid.UUID | None:+ """Find the user's first workspace. Synchronous — listener runs on the sync mapper."""+ # The listener is invoked from a sync-binding even in async sessions+ # (SQLAlchemy translates), so use the sync-style execute.+ row = session.execute(+ select(Workspace.id)+ .join(WorkspaceMember, WorkspaceMember.workspace_id == Workspace.id)+ .where(+ WorkspaceMember.user_id == user_id,+ Workspace.is_archived.is_(False),+ )+ .order_by(Workspace.created_at.asc())+ .limit(1)+ ).first()+ return row[0] if row else None+++# Parent FK columns to consult in order — when a row's workspace_id is+# missing, look up the parent and inherit its workspace_id. Order+# matters: more specific parents come first.+_PARENT_LOOKUPS: tuple[tuple[str, str], ...] = (+ ("account_id", "app.models.account:Account"),+ ("connection_id", "app.models.bank_connection:BankConnection"),+ ("asset_id", "app.models.asset:Asset"),+ ("group_id", "app.models.group:Group"),+ ("transaction_id", "app.models.transaction:Transaction"),+ ("agent_id", "app.agents.models.agent:Agent"),+)+++def _import_model(spec: str) -> Any:+ module_path, class_name = spec.split(":")+ import importlib++ module = importlib.import_module(module_path)+ return getattr(module, class_name)+++def _resolve_from_parent(session: Session, target: Any) -> uuid.UUID | None:+ """Walk parent FKs and return the first workspace_id we find."""+ for column, spec in _PARENT_LOOKUPS:+ parent_id = getattr(target, column, None)+ if parent_id is None:+ continue+ ParentModel = _import_model(spec)+ parent = session.get(ParentModel, parent_id)+ if parent is not None:+ ws = getattr(parent, "workspace_id", None)+ if ws is not None:+ return ws+ return None+++def _before_insert(mapper: Mapper, connection: Any, target: Any) -> None:+ if getattr(target, "workspace_id", None) is not None:+ return+ # Use the sync session bound to this connection. Mapper events fire+ # inside a flush, so the session is reachable via the target's+ # InstanceState.+ from sqlalchemy.orm import object_session+ session = object_session(target)+ if session is None:+ return++ # Prefer the parent's workspace — this keeps synced rows in the+ # workspace that owns the bank connection / account / asset, which+ # may not be the user's *default* workspace.+ parent_ws = _resolve_from_parent(session, target)+ if parent_ws is not None:+ target.workspace_id = parent_ws+ return++ # Fallback: route the row to the user's first workspace. Correct+ # for single-workspace users (everyone today) and a safe default+ # for orphan-shaped rows.+ user_id = getattr(target, "user_id", None)+ if user_id is None:+ return+ cache_key = _cache_key(session, user_id)+ ws_id = getattr(session, cache_key, None)+ if ws_id is None:+ ws_id = _resolve_workspace_for_user(session, user_id)+ if ws_id is None:+ return+ setattr(session, cache_key, ws_id)+ target.workspace_id = ws_id+++def install_workspace_autostamp() -> None:+ """Idempotent: register the listener on each model exactly once."""+ for model in _AUTOSTAMP_MODELS + _register_agent_models():+ if not event.contains(model, "before_insert", _before_insert):+ event.listen(model, "before_insert", _before_insert)+++# Install immediately on import so it's active for the FastAPI app + tests.+install_workspace_autostamp()diff --git a/backend/app/core/workspace_context.py b/backend/app/core/workspace_context.pynew file mode 100644index 00000000..4e98eae8--- /dev/null+++ b/backend/app/core/workspace_context.py@@ -0,0 +1,111 @@+"""FastAPI dependency that resolves the current workspace for a request.++Resolution order:+ 1. `X-Workspace-Id` header — explicit selection from the frontend.+ 2. The user's first/default workspace (`get_default_workspace`).++If neither resolves, raises 404. Returns a `WorkspaceContext` value+object that carries the workspace + the requester's membership + the+inferred role. Routes that mutate data check `ctx.role` to enforce+viewer/editor/owner restrictions; routes that just read use any+membership.+"""+import uuid+from dataclasses import dataclass+from typing import Optional++from fastapi import Depends, Header, HTTPException+from sqlalchemy.ext.asyncio import AsyncSession++from app.core.auth import current_active_user+from app.core.database import get_async_session+from app.models.user import User+from app.models.workspace import Workspace, WorkspaceMember+from app.services.workspace_service import (+ _virtual_manager_member,+ get_default_workspace,+ get_membership,+ is_workspace_manager,+)+++@dataclass+class WorkspaceContext:+ workspace: Workspace+ member: WorkspaceMember+ user: User++ @property+ def id(self) -> uuid.UUID:+ return self.workspace.id++ @property+ def user_id(self) -> uuid.UUID:+ """The current human's user_id — used as `created_by` on new rows."""+ return self.user.id++ @property+ def role(self) -> str:+ return self.member.role++ @property+ def can_write(self) -> bool:+ return self.role in ("owner", "editor", "manager")++ @property+ def is_owner(self) -> bool:+ # Workspace managers get effective owner rights for permission gates.+ return self.role in ("owner", "manager")++ def require_write(self) -> None:+ if not self.can_write:+ raise HTTPException(status_code=403, detail="Read-only role")++ def require_owner(self) -> None:+ if not self.is_owner:+ raise HTTPException(status_code=403, detail="Owner role required")+++async def current_workspace(+ x_workspace_id: Optional[str] = Header(default=None, alias="X-Workspace-Id"),+ user: User = Depends(current_active_user),+ session: AsyncSession = Depends(get_async_session),+) -> WorkspaceContext:+ """Dependency: resolve and validate the current workspace + membership."""+ if x_workspace_id:+ try:+ ws_uuid = uuid.UUID(x_workspace_id)+ except (ValueError, TypeError):+ raise HTTPException(status_code=400, detail="Invalid X-Workspace-Id")+ workspace = await session.get(Workspace, ws_uuid)+ if workspace is None or workspace.is_archived:+ raise HTTPException(status_code=404, detail="Workspace not found")+ member = await get_membership(session, ws_uuid, user.id)+ if member is None:+ # Fall back to manager-of access.+ if await is_workspace_manager(session, ws_uuid, user.id):+ member = _virtual_manager_member(ws_uuid, user.id)+ else:+ raise HTTPException(status_code=404, detail="Workspace not found")+ return WorkspaceContext(workspace=workspace, member=member, user=user)++ # Fallback: user's first non-archived workspace (member-of or managed).+ default = await get_default_workspace(session, user.id)+ if default is None:+ raise HTTPException(status_code=404, detail="No workspace available")+ member = await get_membership(session, default.id, user.id)+ if member is None:+ # Managed-only workspace path.+ if await is_workspace_manager(session, default.id, user.id):+ member = _virtual_manager_member(default.id, user.id)+ else:+ raise HTTPException(status_code=500, detail="Workspace state inconsistent")+ return WorkspaceContext(workspace=default, member=member, user=user)+++# Convenience: write-gated context. Raises 403 if the user can't write.+async def current_writable_workspace(+ ctx: WorkspaceContext = Depends(current_workspace),+) -> WorkspaceContext:+ ctx.require_write()+ return ctxdiff --git a/backend/app/main.py b/backend/app/main.pyindex 8eb1077d..9f0a735a 100644--- a/backend/app/main.py+++ b/backend/app/main.py@@ -33,6 +33,7 @@ from app.api.settings import router as settings_routerfrom app.api.transactions import router as transactions_routerfrom app.api.two_factor import router as two_factor_routerfrom app.api.user_lookup import router as user_lookup_router+from app.api.workspaces import router as workspaces_routerfrom app.api.admin import router as admin_router, check_registration_enabledfrom app.core.auth import fastapi_usersfrom app.core.config import get_settings@@ -133,6 +134,7 @@ app.include_router(export_router)app.include_router(attachments_router)app.include_router(payees_router)app.include_router(settings_router)+app.include_router(workspaces_router)app.include_router(admin_router)app.include_router(info_router)diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.pyindex 39ed9c75..e4f4aa67 100644--- a/backend/app/models/__init__.py+++ b/backend/app/models/__init__.py@@ -1,4 +1,5 @@from app.models.user import User+from app.models.workspace import Workspace, WorkspaceMemberfrom app.models.category import Categoryfrom app.models.category_group import CategoryGroupfrom app.models.bank_connection import BankConnection@@ -21,8 +22,15 @@ from app.models.group import Group, GroupMemberfrom app.models.transaction_split import TransactionSplitfrom app.models.group_settlement import GroupSettlement+# Side-effect import: register the before_insert listener that auto-stamps+# workspace_id from user_id on financial entities. Imported last so all+# referenced models are loaded.+from app.core import workspace_autostamp # noqa: F401, E402+__all__ = ["User",+ "Workspace",+ "WorkspaceMember","Category","CategoryGroup","BankConnection",diff --git a/backend/app/models/account.py b/backend/app/models/account.pyindex b8908856..31e51b5d 100644--- a/backend/app/models/account.py+++ b/backend/app/models/account.py@@ -19,6 +19,9 @@ class Account(Base):id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id"))+ workspace_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True), ForeignKey("workspaces.id", ondelete="CASCADE"), index=True+ )connection_id: Mapped[Optional[uuid.UUID]] = mapped_column(UUID(as_uuid=True), ForeignKey("bank_connections.id"), nullable=True)external_id: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)name: Mapped[str] = mapped_column(String(255))diff --git a/backend/app/models/asset.py b/backend/app/models/asset.pyindex c5c6a790..fe6ea0a5 100644--- a/backend/app/models/asset.py+++ b/backend/app/models/asset.py@@ -19,6 +19,9 @@ class Asset(Base):id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id"))+ workspace_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True), ForeignKey("workspaces.id", ondelete="CASCADE"), index=True+ )name: Mapped[str] = mapped_column(String(255))type: Mapped[str] = mapped_column(String(50)) # real_estate, vehicle, valuable, investment, othercurrency: Mapped[str] = mapped_column(String(3), default="USD")diff --git a/backend/app/models/asset_group.py b/backend/app/models/asset_group.pyindex 7acb57ad..7cd54dee 100644--- a/backend/app/models/asset_group.py+++ b/backend/app/models/asset_group.py@@ -28,6 +28,9 @@ class AssetGroup(Base):id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id"))+ workspace_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True), ForeignKey("workspaces.id", ondelete="CASCADE"), index=True+ )name: Mapped[str] = mapped_column(String(100))icon: Mapped[str] = mapped_column(String(50), default="wallet")color: Mapped[str] = mapped_column(String(7), default="#0EA5E9")diff --git a/backend/app/models/asset_value.py b/backend/app/models/asset_value.pyindex 9d6ab9d8..8acfcd73 100644--- a/backend/app/models/asset_value.py+++ b/backend/app/models/asset_value.py@@ -15,6 +15,9 @@ class AssetValue(Base):id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)asset_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("assets.id", ondelete="CASCADE"))+ workspace_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True), ForeignKey("workspaces.id", ondelete="CASCADE"), index=True+ )amount: Mapped[Decimal] = mapped_column(Numeric(precision=15, scale=6))date: Mapped[date] = mapped_column(Date)source: Mapped[str] = mapped_column(String(20), default="manual") # manual, rule, syncdiff --git a/backend/app/models/bank_connection.py b/backend/app/models/bank_connection.pyindex 0382c94d..4c9a885d 100644--- a/backend/app/models/bank_connection.py+++ b/backend/app/models/bank_connection.py@@ -18,6 +18,9 @@ class BankConnection(Base):id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id"))+ workspace_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True), ForeignKey("workspaces.id", ondelete="CASCADE"), index=True+ )provider: Mapped[str] = mapped_column(String(50)) # "pluggy", "belvo", etc.external_id: Mapped[str] = mapped_column(String(255)) # Provider's item IDinstitution_name: Mapped[str] = mapped_column(String(255))diff --git a/backend/app/models/budget.py b/backend/app/models/budget.pyindex f01b0165..5c9e6b4b 100644--- a/backend/app/models/budget.py+++ b/backend/app/models/budget.py@@ -23,6 +23,9 @@ class Budget(Base):id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id"))+ workspace_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True), ForeignKey("workspaces.id", ondelete="CASCADE"), index=True+ )category_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("categories.id"))amount: Mapped[Decimal] = mapped_column(Numeric(precision=15, scale=2))month: Mapped[date] = mapped_column(Date) # First day of monthdiff --git a/backend/app/models/category.py b/backend/app/models/category.pyindex bea93b6f..4a4b5ce0 100644--- a/backend/app/models/category.py+++ b/backend/app/models/category.py@@ -17,6 +17,9 @@ class Category(Base):id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id"))+ workspace_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True), ForeignKey("workspaces.id", ondelete="CASCADE"), index=True+ )group_id: Mapped[Optional[uuid.UUID]] = mapped_column(UUID(as_uuid=True), ForeignKey("category_groups.id"), nullable=True)name: Mapped[str] = mapped_column(String(100))icon: Mapped[str] = mapped_column(String(50), default="circle-help")diff --git a/backend/app/models/category_group.py b/backend/app/models/category_group.pyindex 0267ca50..cb6df34a 100644--- a/backend/app/models/category_group.py+++ b/backend/app/models/category_group.py@@ -17,6 +17,9 @@ class CategoryGroup(Base):id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id"))+ workspace_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True), ForeignKey("workspaces.id", ondelete="CASCADE"), index=True+ )name: Mapped[str] = mapped_column(String(100))icon: Mapped[str] = mapped_column(String(50), default="folder")color: Mapped[str] = mapped_column(String(7), default="#6B7280")diff --git a/backend/app/models/credit_card_bill.py b/backend/app/models/credit_card_bill.pyindex 9f0a4fc2..1e7a1300 100644--- a/backend/app/models/credit_card_bill.py+++ b/backend/app/models/credit_card_bill.py@@ -28,6 +28,9 @@ class CreditCardBill(Base):id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id"), nullable=False)+ workspace_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True), ForeignKey("workspaces.id", ondelete="CASCADE"), index=True+ )account_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("accounts.id", ondelete="CASCADE"), nullable=False)diff --git a/backend/app/models/goal.py b/backend/app/models/goal.pyindex 69931b0d..bebaf9c1 100644--- a/backend/app/models/goal.py+++ b/backend/app/models/goal.py@@ -22,6 +22,9 @@ class Goal(Base):id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id"))+ workspace_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True), ForeignKey("workspaces.id", ondelete="CASCADE"), index=True+ )name: Mapped[str] = mapped_column(String(255))target_amount: Mapped[Decimal] = mapped_column(Numeric(precision=15, scale=2))current_amount: Mapped[Decimal] = mapped_column(Numeric(precision=15, scale=2), default=Decimal("0.00"))diff --git a/backend/app/models/group.py b/backend/app/models/group.pyindex 763d3ef1..1dd487cf 100644--- a/backend/app/models/group.py+++ b/backend/app/models/group.py@@ -35,6 +35,9 @@ class Group(Base):user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"))+ workspace_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True), ForeignKey("workspaces.id", ondelete="CASCADE"), index=True+ )name: Mapped[str] = mapped_column(String(100))kind: Mapped[str] = mapped_column(String(20), default="social", server_default="social")default_currency: Mapped[str] = mapped_column(String(3), default="USD", server_default="USD")@@ -62,6 +65,9 @@ class GroupMember(Base):group_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("groups.id", ondelete="CASCADE"))+ workspace_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True), ForeignKey("workspaces.id", ondelete="CASCADE"), index=True+ )name: Mapped[str] = mapped_column(String(100))# Nullable so shadow members (non-Securo people) work from day one.# SET NULL on delete preserves the shadow record + its history ifdiff --git a/backend/app/models/group_settlement.py b/backend/app/models/group_settlement.pyindex 646a0e2d..98b32fc6 100644--- a/backend/app/models/group_settlement.py+++ b/backend/app/models/group_settlement.py@@ -21,6 +21,9 @@ class GroupSettlement(Base):group_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("groups.id", ondelete="CASCADE"))+ workspace_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True), ForeignKey("workspaces.id", ondelete="CASCADE"), index=True+ )from_member_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("group_members.id", ondelete="RESTRICT"))diff --git a/backend/app/models/import_log.py b/backend/app/models/import_log.pyindex a95fe05b..6d8f156f 100644--- a/backend/app/models/import_log.py+++ b/backend/app/models/import_log.py@@ -19,6 +19,9 @@ class ImportLog(Base):id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id"))+ workspace_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True), ForeignKey("workspaces.id", ondelete="CASCADE"), index=True+ )account_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("accounts.id", ondelete="CASCADE"))filename: Mapped[str] = mapped_column(String(255))format: Mapped[str] = mapped_column(String(10))diff --git a/backend/app/models/payee.py b/backend/app/models/payee.pyindex a585760c..31ca7842 100644--- a/backend/app/models/payee.py+++ b/backend/app/models/payee.py@@ -18,6 +18,9 @@ class Payee(Base):id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id"))+ workspace_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True), ForeignKey("workspaces.id", ondelete="CASCADE"), index=True+ )name: Mapped[str] = mapped_column(String(255))type: Mapped[str] = mapped_column(String(20), default="merchant")is_favorite: Mapped[bool] = mapped_column(Boolean, default=False)@@ -33,6 +36,9 @@ class PayeeMapping(Base):id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id"))+ workspace_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True), ForeignKey("workspaces.id", ondelete="CASCADE"), index=True+ )target_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("payees.id", ondelete="CASCADE"))target: Mapped["Payee"] = relationship()diff --git a/backend/app/models/recurring_transaction.py b/backend/app/models/recurring_transaction.pyindex 5e5bce35..90087bc6 100644--- a/backend/app/models/recurring_transaction.py+++ b/backend/app/models/recurring_transaction.py@@ -24,6 +24,9 @@ class RecurringTransaction(Base):id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id"))+ workspace_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True), ForeignKey("workspaces.id", ondelete="CASCADE"), index=True+ )account_id: Mapped[Optional[uuid.UUID]] = mapped_column(UUID(as_uuid=True), ForeignKey("accounts.id", ondelete="CASCADE"), nullable=True)category_id: Mapped[Optional[uuid.UUID]] = mapped_column(UUID(as_uuid=True), ForeignKey("categories.id"), nullable=True)description: Mapped[str] = mapped_column(String(500))diff --git a/backend/app/models/rule.py b/backend/app/models/rule.pyindex 48fe67ec..f7c9e2b5 100644--- a/backend/app/models/rule.py+++ b/backend/app/models/rule.py@@ -16,6 +16,9 @@ class Rule(Base):id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id"))+ workspace_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True), ForeignKey("workspaces.id", ondelete="CASCADE"), index=True+ )name: Mapped[str] = mapped_column(String(255))conditions_op: Mapped[str] = mapped_column(String(3), default="and") # "and" | "or"conditions: Mapped[list] = mapped_column(JSON, default=list)diff --git a/backend/app/models/transaction.py b/backend/app/models/transaction.pyindex c5ca1d2b..a81ea680 100644--- a/backend/app/models/transaction.py+++ b/backend/app/models/transaction.py@@ -24,6 +24,9 @@ class Transaction(Base):id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id"))+ workspace_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True), ForeignKey("workspaces.id", ondelete="CASCADE"), index=True+ )account_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("accounts.id"), nullable=False)category_id: Mapped[Optional[uuid.UUID]] = mapped_column(UUID(as_uuid=True), ForeignKey("categories.id"), nullable=True)external_id: Mapped[Optional[str]] = mapped_column(String(255), nullable=True) # Provider's transaction IDdiff --git a/backend/app/models/transaction_attachment.py b/backend/app/models/transaction_attachment.pyindex 7289c154..78d20912 100644--- a/backend/app/models/transaction_attachment.py+++ b/backend/app/models/transaction_attachment.py@@ -20,6 +20,9 @@ class TransactionAttachment(Base):UUID(as_uuid=True), ForeignKey("transactions.id", ondelete="CASCADE"))user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id"))+ workspace_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True), ForeignKey("workspaces.id", ondelete="CASCADE"), index=True+ )filename: Mapped[str] = mapped_column(String(255))storage_key: Mapped[str] = mapped_column(String(500))content_type: Mapped[str] = mapped_column(String(100))diff --git a/backend/app/models/transaction_split.py b/backend/app/models/transaction_split.pyindex 2f7c5311..d4cc5939 100644--- a/backend/app/models/transaction_split.py+++ b/backend/app/models/transaction_split.py@@ -21,6 +21,9 @@ class TransactionSplit(Base):transaction_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("transactions.id", ondelete="CASCADE"))+ workspace_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True), ForeignKey("workspaces.id", ondelete="CASCADE"), index=True+ )# RESTRICT: removing a member with active splits requires reassigning# or deleting those splits first. Group-level CASCADE still works# when no splits exist.diff --git a/backend/app/models/workspace.py b/backend/app/models/workspace.pynew file mode 100644index 00000000..b0c9dce8--- /dev/null+++ b/backend/app/models/workspace.py@@ -0,0 +1,96 @@+import uuid+from datetime import datetime, timezone+from typing import TYPE_CHECKING, Optional++from sqlalchemy import Boolean, DateTime, ForeignKey, String, UniqueConstraint+from sqlalchemy.dialects.postgresql import UUID+from sqlalchemy.orm import Mapped, mapped_column, relationship++from app.core.database import Base++if TYPE_CHECKING:+ from app.models.user import User+++# Allowed values for Workspace.kind. Drives template defaults + module+# visibility. New kinds get added here; the data model is identical.+WORKSPACE_KINDS = ("personal", "freelancer", "small_business", "accountant_firm")++# Roles a member can hold inside a workspace. `owner` is the+# member-management + workspace-config role; `editor` can read/write+# financial data; `viewer` is read-only.+WORKSPACE_ROLES = ("owner", "editor", "viewer")++# Virtual role surfaced when a user accesses a workspace via+# `managed_by_user_id` rather than via a `workspace_members` row. They+# get effective owner rights but aren't part of the member roster.+MANAGER_VIRTUAL_ROLE = "manager"+++class Workspace(Base):+ __tablename__ = "workspaces"++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ name: Mapped[str] = mapped_column(String(100))+ kind: Mapped[str] = mapped_column(String(30), default="personal", server_default="personal")+ # The human who originally created the workspace. Distinct from+ # `owner` role membership — ownership can transfer via the members+ # table, but this field records the creator for audit.+ created_by_user_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True), ForeignKey("users.id", ondelete="SET NULL"), nullable=True+ )+ # Soft-delete. Cascading hard delete across all financial entities+ # is too aggressive; archived workspaces stay in the DB until an+ # admin purge.+ is_archived: Mapped[bool] = mapped_column(Boolean, default=False, server_default="false")+ # Optional external administrator. When set, this user has effective+ # owner rights in the workspace without being a member. Use case:+ # one user provisions and operates a workspace on behalf of another+ # (or operates several distinct workspaces side by side without+ # being a "member" of each). Distinct from `created_by_user_id`+ # because management can transfer while creation history stays.+ managed_by_user_id: Mapped[Optional[uuid.UUID]] = mapped_column(+ UUID(as_uuid=True), ForeignKey("users.id", ondelete="SET NULL"), nullable=True+ )+ # Workspace-level defaults. Individual members can still override via+ # their own user preferences for display, but new accounts inherit+ # `default_currency` etc. from here.+ default_currency: Mapped[str] = mapped_column(String(3), default="USD", server_default="USD")+ locale: Mapped[Optional[str]] = mapped_column(String(10), nullable=True)+ icon: Mapped[Optional[str]] = mapped_column(String(50), nullable=True)+ color: Mapped[Optional[str]] = mapped_column(String(7), nullable=True)+ created_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)+ )++ members: Mapped[list["WorkspaceMember"]] = relationship(+ back_populates="workspace", cascade="all, delete-orphan"+ )+++class WorkspaceMember(Base):+ __tablename__ = "workspace_members"+ __table_args__ = (+ UniqueConstraint("workspace_id", "user_id", name="uq_workspace_member"),+ )++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ workspace_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True), ForeignKey("workspaces.id", ondelete="CASCADE")+ )+ user_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE")+ )+ role: Mapped[str] = mapped_column(String(20), default="owner", server_default="owner")+ # Tracks the user who last invited or modified this membership.+ # Useful for audit when the invite flow gains an "invited_by"+ # surface; nullable for the bootstrap rows created by the migration.+ invited_by_user_id: Mapped[Optional[uuid.UUID]] = mapped_column(+ UUID(as_uuid=True), ForeignKey("users.id", ondelete="SET NULL"), nullable=True+ )+ joined_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)+ )++ workspace: Mapped["Workspace"] = relationship(back_populates="members")+ user: Mapped["User"] = relationship(foreign_keys=[user_id])diff --git a/backend/app/schemas/workspace.py b/backend/app/schemas/workspace.pynew file mode 100644index 00000000..2ff2e6fd--- /dev/null+++ b/backend/app/schemas/workspace.py@@ -0,0 +1,72 @@+import uuid+from datetime import datetime+from typing import Optional++from pydantic import BaseModel, EmailStr, Field++class WorkspaceRead(BaseModel):+ id: uuid.UUID+ name: str+ kind: str+ is_archived: bool+ default_currency: str+ locale: Optional[str] = None+ icon: Optional[str] = None+ color: Optional[str] = None+ created_at: datetime+ created_by_user_id: Optional[uuid.UUID] = None+ managed_by_user_id: Optional[uuid.UUID] = None+ # The current user's role inside this workspace, when surfaced via+ # /api/workspaces (the listing endpoint). Omitted from per-workspace+ # detail responses since the membership row is fetched alongside.+ role: Optional[str] = None++ class Config:+ from_attributes = True+++class WorkspaceCreate(BaseModel):+ name: str = Field(min_length=1, max_length=100)+ kind: str = "personal"+ default_currency: Optional[str] = Field(default=None, min_length=3, max_length=3)+ locale: Optional[str] = Field(default=None, max_length=10)+ icon: Optional[str] = Field(default=None, max_length=50)+ color: Optional[str] = Field(default=None, max_length=7)+ # When True, also add the creator as an `owner` member. When False+ # (default), the creator is only the external manager — useful when+ # the workspace will be handed off to someone else as the day-to-day+ # owner.+ self_membership: bool = False+++class WorkspaceUpdate(BaseModel):+ name: Optional[str] = Field(default=None, min_length=1, max_length=100)+ icon: Optional[str] = Field(default=None, max_length=50)+ color: Optional[str] = Field(default=None, max_length=7)+ default_currency: Optional[str] = Field(default=None, min_length=3, max_length=3)+ locale: Optional[str] = Field(default=None, max_length=10)+++class MemberRead(BaseModel):+ id: uuid.UUID+ user_id: uuid.UUID+ email: str+ display_name: Optional[str] = None+ role: str+ joined_at: datetime++ class Config:+ from_attributes = True+++class MemberInvite(BaseModel):+ email: EmailStr+ role: str = "editor"+ # Optional password — only used when inviting a brand-new user. If+ # omitted, the endpoint rejects the invite when the target user+ # doesn't exist. (Email-based magic-link onboarding can come later.)+ password: Optional[str] = Field(default=None, min_length=8, max_length=128)+++class MemberRoleUpdate(BaseModel):+ role: strdiff --git a/backend/app/services/_query_filters.py b/backend/app/services/_query_filters.pyindex ba9b21d0..12f8cb66 100644--- a/backend/app/services/_query_filters.py+++ b/backend/app/services/_query_filters.py@@ -76,6 +76,7 @@ async def owner_split_offset_pnl(month_end: date,use_effective_date: bool = False,primary_currency: Optional[str] = None,+ workspace_id: Optional[uuid.UUID] = None,) -> tuple[float, float]:"""Return (income_offset, expense_offset) — the totals to *subtract*from the owner's full-amount aggregations so only their own share@@ -119,6 +120,11 @@ async def owner_split_offset_pnl(.join(Transaction, TransactionSplit.transaction_id == Transaction.id).where(Transaction.user_id == user_id,+ *(+ [Transaction.workspace_id == workspace_id]+ if workspace_id is not None+ else []+ ),TransactionSplit.group_member_id.notin_(viewer_member_ids),Transaction.source != "opening_balance",date_col >= month_start,@@ -160,6 +166,7 @@ async def owner_split_offset_by_category(month_end: date,use_effective_date: bool = False,primary_currency: Optional[str] = None,+ workspace_id: Optional[uuid.UUID] = None,) -> dict:"""Per-category, sum of non-owner shares on owner-side debit splits —subtract from full owner debits to get the owner's category share."""@@ -187,6 +194,11 @@ async def owner_split_offset_by_category(.join(Transaction, TransactionSplit.transaction_id == Transaction.id).where(Transaction.user_id == user_id,+ *(+ [Transaction.workspace_id == workspace_id]+ if workspace_id is not None+ else []+ ),Transaction.type == "debit",TransactionSplit.group_member_id.notin_(viewer_member_ids),Transaction.source != "opening_balance",@@ -237,7 +249,14 @@ async def viewer_shared_pnl(from app.models.group import GroupMemberfrom app.models.transaction_split import TransactionSplit- member_ids = select(GroupMember.id).where(GroupMember.linked_user_id == user_id)+ # Cross-workspace Splitwise projection: include only invitations+ # (linked_user_id matches but is_self is False). Self-memberships+ # represent the user in their own group and are already counted via+ # the workspace-scoped Transaction filter at the caller.+ member_ids = select(GroupMember.id).where(+ GroupMember.linked_user_id == user_id,+ GroupMember.is_self.is_(False),+ )date_col = Transaction.effective_date if use_effective_date else Transaction.dateresult = await session.execute(@@ -314,7 +333,14 @@ async def viewer_shared_spending_by_category(from app.models.group import GroupMemberfrom app.models.transaction_split import TransactionSplit- member_ids = select(GroupMember.id).where(GroupMember.linked_user_id == user_id)+ # Cross-workspace Splitwise projection: include only invitations+ # (linked_user_id matches but is_self is False). Self-memberships+ # represent the user in their own group and are already counted via+ # the workspace-scoped Transaction filter at the caller.+ member_ids = select(GroupMember.id).where(+ GroupMember.linked_user_id == user_id,+ GroupMember.is_self.is_(False),+ )date_col = Transaction.effective_date if use_effective_date else Transaction.dateresult = await session.execute(diff --git a/backend/app/services/account_service.py b/backend/app/services/account_service.pyindex cccc4ebe..af3f4d37 100644--- a/backend/app/services/account_service.py+++ b/backend/app/services/account_service.py@@ -20,7 +20,7 @@ def get_account_name(account: Account) -> str:return account.display_name or account.name-async def get_accounts(session: AsyncSession, user_id: uuid.UUID, include_closed: bool = False) -> list[dict]:+async def get_accounts(session: AsyncSession, workspace_id: uuid.UUID, include_closed: bool = False) -> list[dict]:# Subquery: compute current_balance per account from transactions in one pass# Use amount_primary only when tx currency differs from account currency# (converts foreign txs to account's reporting currency)@@ -86,8 +86,8 @@ async def get_accounts(session: AsyncSession, user_id: uuid.UUID, include_closed.outerjoin(prev_balance_sq, Account.id == prev_balance_sq.c.account_id).where(or_(- Account.user_id == user_id,- BankConnection.user_id == user_id,+ Account.workspace_id == workspace_id,+ BankConnection.workspace_id == workspace_id,)))@@ -151,7 +151,7 @@ def serialize_account(async def get_credit_card_bills(session: AsyncSession,account_id: uuid.UUID,- user_id: uuid.UUID,+ workspace_id: uuid.UUID,*,limit: int = 24,) -> Optional[list[CreditCardBill]]:@@ -162,7 +162,7 @@ async def get_credit_card_bills(accounts with no synced bills — the read path then keeps using thecycle-math fallback."""- account = await get_account(session, account_id, user_id)+ account = await get_account(session, account_id, workspace_id)if account is None:return Noneif account.type != "credit_card":@@ -176,25 +176,31 @@ async def get_credit_card_bills(return list(result.scalars().all())-async def get_account(session: AsyncSession, account_id: uuid.UUID, user_id: uuid.UUID) -> Optional[Account]:+async def get_account(session: AsyncSession, account_id: uuid.UUID, workspace_id: uuid.UUID) -> Optional[Account]:result = await session.execute(select(Account).outerjoin(BankConnection).where(Account.id == account_id,or_(- Account.user_id == user_id,- BankConnection.user_id == user_id,+ Account.workspace_id == workspace_id,+ BankConnection.workspace_id == workspace_id,),))return result.scalar_one_or_none()-async def create_account(session: AsyncSession, user_id: uuid.UUID, data: AccountCreate) -> Account:+async def create_account(+ session: AsyncSession,+ workspace_id: uuid.UUID,+ user_id: uuid.UUID,+ data: AccountCreate,+) -> Account:is_cc = data.type == "credit_card"account = Account(user_id=user_id,+ workspace_id=workspace_id,name=data.name,type=data.type,balance=data.balance,@@ -215,6 +221,7 @@ async def create_account(session: AsyncSession, user_id: uuid.UUID, data: Accounopening_type = "debit" if data.type == "credit_card" else "credit"opening_tx = Transaction(user_id=user_id,+ workspace_id=workspace_id,account_id=account.id,description="Saldo inicial",amount=data.balance,@@ -232,9 +239,9 @@ async def create_account(session: AsyncSession, user_id: uuid.UUID, data: Accounasync def update_account(- session: AsyncSession, account_id: uuid.UUID, user_id: uuid.UUID, data: AccountUpdate+ session: AsyncSession, account_id: uuid.UUID, workspace_id: uuid.UUID, data: AccountUpdate) -> Optional[Account]:- account = await get_account(session, account_id, user_id)+ account = await get_account(session, account_id, workspace_id)if not account:return None@@ -309,6 +316,7 @@ async def update_account(else:opening_tx = Transaction(user_id=account.user_id,+ workspace_id=account.workspace_id,account_id=account_id,description="Saldo inicial",amount=new_balance,@@ -425,6 +433,7 @@ async def sync_opening_balance_for_connected_account(else:opening_tx = Transaction(user_id=account.user_id,+ workspace_id=account.workspace_id,account_id=account.id,description="Saldo inicial",amount=amount,@@ -438,8 +447,8 @@ async def sync_opening_balance_for_connected_account(await session.flush()-async def delete_account(session: AsyncSession, account_id: uuid.UUID, user_id: uuid.UUID) -> bool:- account = await get_account(session, account_id, user_id)+async def delete_account(session: AsyncSession, account_id: uuid.UUID, workspace_id: uuid.UUID) -> bool:+ account = await get_account(session, account_id, workspace_id)if not account:return False@@ -493,9 +502,9 @@ async def delete_account(session: AsyncSession, account_id: uuid.UUID, user_id:async def close_account(- session: AsyncSession, account_id: uuid.UUID, user_id: uuid.UUID+ session: AsyncSession, account_id: uuid.UUID, workspace_id: uuid.UUID) -> Optional[Account]:- account = await get_account(session, account_id, user_id)+ account = await get_account(session, account_id, workspace_id)if not account:return Noneif account.is_closed:@@ -517,9 +526,9 @@ async def close_account(async def reopen_account(- session: AsyncSession, account_id: uuid.UUID, user_id: uuid.UUID+ session: AsyncSession, account_id: uuid.UUID, workspace_id: uuid.UUID) -> Optional[Account]:- account = await get_account(session, account_id, user_id)+ account = await get_account(session, account_id, workspace_id)if not account:return Noneif not account.is_closed:@@ -534,12 +543,12 @@ async def reopen_account(async def get_account_summary(- session: AsyncSession, account_id: uuid.UUID, user_id: uuid.UUID,+ session: AsyncSession, account_id: uuid.UUID, workspace_id: uuid.UUID,date_from: Optional[_Date] = None, date_to: Optional[_Date] = None,bill_id: Optional[uuid.UUID] = None,unbilled_only: bool = False,) -> Optional[dict]:- account = await get_account(session, account_id, user_id)+ account = await get_account(session, account_id, workspace_id)if not account:return None@@ -785,10 +794,10 @@ async def _account_daily_balance_series(async def get_account_balance_history(- session: AsyncSession, account_id: uuid.UUID, user_id: uuid.UUID,+ session: AsyncSession, account_id: uuid.UUID, workspace_id: uuid.UUID,date_from: Optional[_Date] = None, date_to: Optional[_Date] = None,) -> Optional[list[dict]]:- account = await get_account(session, account_id, user_id)+ account = await get_account(session, account_id, workspace_id)if not account:return Nonediff --git a/backend/app/services/admin_service.py b/backend/app/services/admin_service.pyindex 04deffc5..513250e6 100644--- a/backend/app/services/admin_service.py+++ b/backend/app/services/admin_service.py@@ -51,6 +51,7 @@ async def create_user(from app.models.account import Accountfrom app.services.category_service import create_default_categoriesfrom app.services.rule_service import create_default_rules+ from app.services.workspace_service import create_personal_workspace_for_usercreate_schema = BaseUserCreate(email=data.email,@@ -77,9 +78,15 @@ async def create_user(# request=None — which is exactly this path — so admin-created users# would otherwise land with no defaults and a broken UX.lang = (user.preferences or {}).get("language", "en")+ # Every new user gets a Personal workspace + owner membership so the+ # seeded wallet/categories/rules below have somewhere to live.+ workspace = await create_personal_workspace_for_user(session, user)+ await session.commit()+wallet_name = "Carteira" if lang.startswith("pt") else "Wallet"wallet = Account(user_id=user.id,+ workspace_id=workspace.id,name=wallet_name,type="checking",balance=Decimal("0.00"),@@ -88,8 +95,8 @@ async def create_user(session.add(wallet)await session.commit()- await create_default_categories(session, user.id, lang)- await create_default_rules(session, user.id, lang)+ await create_default_categories(session, user.id, lang, workspace_id=workspace.id)+ await create_default_rules(session, user.id, lang, workspace_id=workspace.id)return userdiff --git a/backend/app/services/asset_group_service.py b/backend/app/services/asset_group_service.pyindex 7f860b6f..0ad5a885 100644--- a/backend/app/services/asset_group_service.py+++ b/backend/app/services/asset_group_service.py@@ -122,10 +122,12 @@ async def _primary_currency_for(session: AsyncSession, user_id: uuid.UUID) -> streturn get_settings().default_currency-async def get_groups(session: AsyncSession, user_id: uuid.UUID) -> list[AssetGroupRead]:+async def get_groups(+ session: AsyncSession, workspace_id: uuid.UUID, user_id: uuid.UUID+) -> list[AssetGroupRead]:result = await session.execute(select(AssetGroup)- .where(AssetGroup.user_id == user_id)+ .where(AssetGroup.workspace_id == workspace_id).order_by(AssetGroup.position, AssetGroup.name))groups = list(result.scalars().all())@@ -147,10 +149,13 @@ async def get_groups(session: AsyncSession, user_id: uuid.UUID) -> list[AssetGroasync def get_group(- session: AsyncSession, group_id: uuid.UUID, user_id: uuid.UUID+ session: AsyncSession,+ group_id: uuid.UUID,+ workspace_id: uuid.UUID,+ user_id: uuid.UUID,) -> Optional[AssetGroupRead]:result = await session.execute(- select(AssetGroup).where(AssetGroup.id == group_id, AssetGroup.user_id == user_id)+ select(AssetGroup).where(AssetGroup.id == group_id, AssetGroup.workspace_id == workspace_id))group = result.scalar_one_or_none()if not group:@@ -162,6 +167,8 @@ async def get_group(async def _next_position(session: AsyncSession, user_id: uuid.UUID) -> int:+ # Position is per-user for sync compatibility — the connection sync path+ # also calls this, and isn't yet workspace-scoped.row = await session.execute(select(func.coalesce(func.max(AssetGroup.position), -1) + 1).where(AssetGroup.user_id == user_id@@ -171,7 +178,10 @@ async def _next_position(session: AsyncSession, user_id: uuid.UUID) -> int:async def create_group(- session: AsyncSession, user_id: uuid.UUID, data: AssetGroupCreate+ session: AsyncSession,+ workspace_id: uuid.UUID,+ user_id: uuid.UUID,+ data: AssetGroupCreate,) -> AssetGroupRead:# Let the caller supply a position, otherwise append to the end so new# groups don't fight with existing drag-ordered ones.@@ -180,6 +190,7 @@ async def create_group(position = await _next_position(session, user_id)group = AssetGroup(user_id=user_id,+ workspace_id=workspace_id,name=data.name,icon=data.icon,color=data.color,@@ -193,10 +204,14 @@ async def create_group(async def update_group(- session: AsyncSession, group_id: uuid.UUID, user_id: uuid.UUID, data: AssetGroupUpdate+ session: AsyncSession,+ group_id: uuid.UUID,+ workspace_id: uuid.UUID,+ user_id: uuid.UUID,+ data: AssetGroupUpdate,) -> Optional[AssetGroupRead]:result = await session.execute(- select(AssetGroup).where(AssetGroup.id == group_id, AssetGroup.user_id == user_id)+ select(AssetGroup).where(AssetGroup.id == group_id, AssetGroup.workspace_id == workspace_id))group = result.scalar_one_or_none()if not group:@@ -211,9 +226,9 @@ async def update_group(return _group_to_read(group, count, cv, cvp, institution)-async def delete_group(session: AsyncSession, group_id: uuid.UUID, user_id: uuid.UUID) -> bool:+async def delete_group(session: AsyncSession, group_id: uuid.UUID, workspace_id: uuid.UUID) -> bool:result = await session.execute(- select(AssetGroup).where(AssetGroup.id == group_id, AssetGroup.user_id == user_id)+ select(AssetGroup).where(AssetGroup.id == group_id, AssetGroup.workspace_id == workspace_id))group = result.scalar_one_or_none()if not group:diff --git a/backend/app/services/asset_service.py b/backend/app/services/asset_service.pyindex f613645c..82624641 100644--- a/backend/app/services/asset_service.py+++ b/backend/app/services/asset_service.py@@ -245,10 +245,10 @@ async def _get_value_count(session: AsyncSession, asset_id: uuid.UUID) -> int:async def get_assets(- session: AsyncSession, user_id: uuid.UUID, include_archived: bool = False+ session: AsyncSession, workspace_id: uuid.UUID, include_archived: bool = False) -> list[AssetRead]:- """List all assets for a user with computed current_value."""- query = select(Asset).where(Asset.user_id == user_id)+ """List all assets in a workspace with computed current_value."""+ query = select(Asset).where(Asset.workspace_id == workspace_id)if not include_archived:query = query.where(Asset.is_archived == False)query = query.order_by(Asset.position, Asset.name)@@ -265,11 +265,11 @@ async def get_assets(async def get_asset(- session: AsyncSession, asset_id: uuid.UUID, user_id: uuid.UUID+ session: AsyncSession, asset_id: uuid.UUID, workspace_id: uuid.UUID) -> Optional[AssetRead]:"""Get a single asset with computed fields."""result = await session.execute(- select(Asset).where(Asset.id == asset_id, Asset.user_id == user_id)+ select(Asset).where(Asset.id == asset_id, Asset.workspace_id == workspace_id))asset = result.scalar_one_or_none()if not asset:@@ -281,6 +281,7 @@ async def get_asset(async def create_asset(session: AsyncSession,+ workspace_id: uuid.UUID,user_id: uuid.UUID,data: AssetCreate,*,@@ -312,6 +313,7 @@ async def create_asset(asset = Asset(user_id=user_id,+ workspace_id=workspace_id,name=data.name,type=data.type,# For market_price, the quote's currency is authoritative — a user@@ -406,12 +408,16 @@ async def create_asset(async def update_asset(- session: AsyncSession, asset_id: uuid.UUID, user_id: uuid.UUID, data: AssetUpdate,+ session: AsyncSession,+ asset_id: uuid.UUID,+ workspace_id: uuid.UUID,+ user_id: uuid.UUID,+ data: AssetUpdate,regenerate_growth: bool = False,) -> Optional[AssetRead]:"""Partial update of an asset."""result = await session.execute(- select(Asset).where(Asset.id == asset_id, Asset.user_id == user_id)+ select(Asset).where(Asset.id == asset_id, Asset.workspace_id == workspace_id))asset = result.scalar_one_or_none()if not asset:@@ -485,11 +491,11 @@ async def update_asset(async def delete_asset(- session: AsyncSession, asset_id: uuid.UUID, user_id: uuid.UUID+ session: AsyncSession, asset_id: uuid.UUID, workspace_id: uuid.UUID) -> bool:"""Delete an asset (cascades to values)."""result = await session.execute(- select(Asset).where(Asset.id == asset_id, Asset.user_id == user_id)+ select(Asset).where(Asset.id == asset_id, Asset.workspace_id == workspace_id))asset = result.scalar_one_or_none()if not asset:@@ -500,12 +506,12 @@ async def delete_asset(async def get_asset_values(- session: AsyncSession, asset_id: uuid.UUID, user_id: uuid.UUID+ session: AsyncSession, asset_id: uuid.UUID, workspace_id: uuid.UUID) -> Optional[list[AssetValueRead]]:"""Get value history for an asset, most recent first."""# Verify ownershipowner_check = await session.execute(- select(Asset.id).where(Asset.id == asset_id, Asset.user_id == user_id)+ select(Asset.id).where(Asset.id == asset_id, Asset.workspace_id == workspace_id))if not owner_check.scalar_one_or_none():return None@@ -520,12 +526,12 @@ async def get_asset_values(async def add_asset_value(- session: AsyncSession, asset_id: uuid.UUID, user_id: uuid.UUID, data: AssetValueCreate+ session: AsyncSession, asset_id: uuid.UUID, workspace_id: uuid.UUID, data: AssetValueCreate) -> Optional[AssetValueRead]:"""Add a new value entry for an asset."""# Verify ownershipowner_check = await session.execute(- select(Asset.id).where(Asset.id == asset_id, Asset.user_id == user_id)+ select(Asset.id).where(Asset.id == asset_id, Asset.workspace_id == workspace_id))if not owner_check.scalar_one_or_none():return None@@ -543,13 +549,13 @@ async def add_asset_value(async def delete_asset_value(- session: AsyncSession, value_id: uuid.UUID, user_id: uuid.UUID+ session: AsyncSession, value_id: uuid.UUID, workspace_id: uuid.UUID) -> bool:"""Delete a specific asset value entry."""result = await session.execute(select(AssetValue).join(Asset, AssetValue.asset_id == Asset.id)- .where(AssetValue.id == value_id, Asset.user_id == user_id)+ .where(AssetValue.id == value_id, Asset.workspace_id == workspace_id))value = result.scalar_one_or_none()if not value:@@ -560,12 +566,12 @@ async def delete_asset_value(async def get_asset_value_trend(- session: AsyncSession, asset_id: uuid.UUID, user_id: uuid.UUID, months: int = 12+ session: AsyncSession, asset_id: uuid.UUID, workspace_id: uuid.UUID, months: int = 12) -> Optional[list[dict]]:"""Get value trend data for charting."""# Verify ownershipowner_check = await session.execute(- select(Asset.id).where(Asset.id == asset_id, Asset.user_id == user_id)+ select(Asset.id).where(Asset.id == asset_id, Asset.workspace_id == workspace_id))if not owner_check.scalar_one_or_none():return None@@ -580,16 +586,23 @@ async def get_asset_value_trend(async def get_portfolio_trend(- session: AsyncSession, user_id: uuid.UUID+ session: AsyncSession,+ workspace_id: uuid.UUID,+ user_id: Optional[uuid.UUID] = None,) -> dict:"""Get portfolio trend data for stacked area chart.Returns asset metadata + pivoted trend with fill-forward values.Sold assets are included so their pre-sell history still contributesto the historical total; their contribution drops to 0 the day after- sell_date."""+ sell_date.++ `user_id` is only used to resolve the user's primary_currency for the+ chart's converted totals; it falls back to the workspace's default when+ not supplied.+ """result = await session.execute(select(Asset).where(- Asset.user_id == user_id,+ Asset.workspace_id == workspace_id,Asset.is_archived == False,).order_by(Asset.position, Asset.name))@@ -599,7 +612,7 @@ async def get_portfolio_trend(return {"assets": [], "trend": [], "total": 0.0}# Get user's primary currency for conversion- user = await session.get(User, user_id)+ user = await session.get(User, user_id) if user_id is not None else Noneprimary_currency = user.primary_currency if user else get_settings().default_currencyvalues_map = await _load_asset_native_values(session, active_assets)@@ -698,20 +711,30 @@ async def get_portfolio_trend(async def get_asset_values_at(session: AsyncSession,- user_id: uuid.UUID,+ scope_id: uuid.UUID,as_of_date: Optional[date] = None,primary_currency: Optional[str] = None,+ *,+ by_workspace: bool = False,) -> tuple[dict[str, float], float]:"""Return (per_currency_totals, primary_total) for all active assets.+ `scope_id` is a workspace_id when `by_workspace=True` (preferred for+ multi-tenant code paths), otherwise treated as a legacy user_id+ filter. Both branches honor the `is_archived=False` + `sell_date is None`+ filters.+- as_of_date=None: uses live prices (current view).- as_of_date set: uses the latest AssetValue on or before that date,falling back to purchase_price only if the asset existed by that date.- primary_currency=None: primary_total is 0.0."""+ scope_filter = (+ Asset.workspace_id == scope_id if by_workspace else Asset.user_id == scope_id+ )result = await session.execute(select(Asset).where(- Asset.user_id == user_id,+ scope_filter,Asset.is_archived == False,Asset.sell_date.is_(None),)diff --git a/backend/app/services/attachment_service.py b/backend/app/services/attachment_service.pyindex 9ad73671..ac3c8e71 100644--- a/backend/app/services/attachment_service.py+++ b/backend/app/services/attachment_service.py@@ -39,12 +39,13 @@ def _validate_file(filename: str, content_type: str, size: int) -> None:raise ValueError(f"File type '.{ext}' is not allowed. Allowed: {', '.join(sorted(allowed))}")-async def _verify_transaction_ownership(- session: AsyncSession, transaction_id: uuid.UUID, user_id: uuid.UUID+async def _verify_transaction_in_workspace(+ session: AsyncSession, transaction_id: uuid.UUID, workspace_id: uuid.UUID) -> Transaction:result = await session.execute(select(Transaction).where(- Transaction.id == transaction_id, Transaction.user_id == user_id+ Transaction.id == transaction_id,+ Transaction.workspace_id == workspace_id,))transaction = result.scalar_one_or_none()@@ -55,6 +56,7 @@ async def _verify_transaction_ownership(async def upload_attachment(session: AsyncSession,+ workspace_id: uuid.UUID,user_id: uuid.UUID,transaction_id: uuid.UUID,filename: str,@@ -63,13 +65,13 @@ async def upload_attachment() -> TransactionAttachment:filename = sanitize_filename(filename)_validate_file(filename, content_type, len(data))- await _verify_transaction_ownership(session, transaction_id, user_id)+ await _verify_transaction_in_workspace(session, transaction_id, workspace_id)settings = get_settings()count_result = await session.execute(select(func.count()).where(TransactionAttachment.transaction_id == transaction_id,- TransactionAttachment.user_id == user_id,+ TransactionAttachment.workspace_id == workspace_id,))current_count = count_result.scalar_one()@@ -79,12 +81,13 @@ async def upload_attachment()prefix = uuid.uuid4().hex[:8]- storage_key = f"{user_id}/{transaction_id}/{prefix}_{filename}"+ storage_key = f"{workspace_id}/{transaction_id}/{prefix}_{filename}"storage = get_storage_provider()stored = await storage.upload(storage_key, data, content_type)attachment = TransactionAttachment(+ workspace_id=workspace_id,user_id=user_id,transaction_id=transaction_id,filename=filename,@@ -99,14 +102,14 @@ async def upload_attachment(async def list_attachments(- session: AsyncSession, user_id: uuid.UUID, transaction_id: uuid.UUID+ session: AsyncSession, workspace_id: uuid.UUID, transaction_id: uuid.UUID) -> list[TransactionAttachment]:- await _verify_transaction_ownership(session, transaction_id, user_id)+ await _verify_transaction_in_workspace(session, transaction_id, workspace_id)result = await session.execute(select(TransactionAttachment).where(TransactionAttachment.transaction_id == transaction_id,- TransactionAttachment.user_id == user_id,+ TransactionAttachment.workspace_id == workspace_id,).order_by(TransactionAttachment.created_at))@@ -114,11 +117,12 @@ async def list_attachments(async def download_attachment(- session: AsyncSession, attachment_id: uuid.UUID, user_id: uuid.UUID+ session: AsyncSession, attachment_id: uuid.UUID, workspace_id: uuid.UUID) -> tuple[TransactionAttachment, bytes]:result = await session.execute(select(TransactionAttachment).where(- TransactionAttachment.id == attachment_id, TransactionAttachment.user_id == user_id+ TransactionAttachment.id == attachment_id,+ TransactionAttachment.workspace_id == workspace_id,))attachment = result.scalar_one_or_none()@@ -131,7 +135,10 @@ async def download_attachment(async def rename_attachment(- session: AsyncSession, attachment_id: uuid.UUID, user_id: uuid.UUID, new_filename: str+ session: AsyncSession,+ attachment_id: uuid.UUID,+ workspace_id: uuid.UUID,+ new_filename: str,) -> TransactionAttachment:new_filename = sanitize_filename(new_filename)if not new_filename:@@ -139,7 +146,8 @@ async def rename_attachment(result = await session.execute(select(TransactionAttachment).where(- TransactionAttachment.id == attachment_id, TransactionAttachment.user_id == user_id+ TransactionAttachment.id == attachment_id,+ TransactionAttachment.workspace_id == workspace_id,))attachment = result.scalar_one_or_none()@@ -184,11 +192,12 @@ async def cleanup_attachment_files(async def delete_attachment(- session: AsyncSession, attachment_id: uuid.UUID, user_id: uuid.UUID+ session: AsyncSession, attachment_id: uuid.UUID, workspace_id: uuid.UUID) -> None:result = await session.execute(select(TransactionAttachment).where(- TransactionAttachment.id == attachment_id, TransactionAttachment.user_id == user_id+ TransactionAttachment.id == attachment_id,+ TransactionAttachment.workspace_id == workspace_id,))attachment = result.scalar_one_or_none()diff --git a/backend/app/services/balance_service.py b/backend/app/services/balance_service.pyindex 3a3e3496..fcdb91d8 100644--- a/backend/app/services/balance_service.py+++ b/backend/app/services/balance_service.py@@ -28,13 +28,17 @@ from app.models.transaction_split import TransactionSplitasync def compute_balances(- session: AsyncSession, group_id: uuid.UUID, user_id: uuid.UUID+ session: AsyncSession,+ group_id: uuid.UUID,+ workspace_id: uuid.UUID,+ user_id: uuid.UUID,) -> Optional[dict]:- # Visible to the owner AND any linked member — they all need to- # see the same who-owes-whom view.+ # Visible to anyone with read access to the group — workspace members+ # plus cross-workspace linked members. They all see the same+ # who-owes-whom view.from app.services.group_service import get_group_visible- group = await get_group_visible(session, group_id, user_id)+ group = await get_group_visible(session, group_id, workspace_id, user_id)if not group:return Nonediff --git a/backend/app/services/budget_service.py b/backend/app/services/budget_service.pyindex fe2dd4ad..26697708 100644--- a/backend/app/services/budget_service.py+++ b/backend/app/services/budget_service.py@@ -28,7 +28,7 @@ def _primary_amount_expr():async def _build_budget_map(- session: AsyncSession, user_id: uuid.UUID, month_start: date+ session: AsyncSession, workspace_id: uuid.UUID, month_start: date) -> dict[str, tuple[Decimal, bool]]:"""Build a map of category_id -> (amount, is_recurring) for the given month.@@ -46,7 +46,7 @@ async def _build_budget_map(func.max(Budget.month).label("max_month"),).where(- Budget.user_id == user_id,+ Budget.workspace_id == workspace_id,Budget.is_recurring == True, # noqa: E712Budget.month <= month_start,)@@ -64,7 +64,7 @@ async def _build_budget_map(),).where(- Budget.user_id == user_id,+ Budget.workspace_id == workspace_id,Budget.is_recurring == True, # noqa: E712))@@ -74,7 +74,7 @@ async def _build_budget_map(# Query 2: Month-specific overrides (take priority over recurring)overrides_result = await session.execute(select(Budget).where(- Budget.user_id == user_id,+ Budget.workspace_id == workspace_id,Budget.is_recurring == False, # noqa: E712Budget.month == month_start,)@@ -86,10 +86,10 @@ async def _build_budget_map(async def get_budgets(- session: AsyncSession, user_id: uuid.UUID, month: Optional[date] = None+ session: AsyncSession, workspace_id: uuid.UUID, month: Optional[date] = None) -> list[Budget]:if not month:- query = select(Budget).where(Budget.user_id == user_id)+ query = select(Budget).where(Budget.workspace_id == workspace_id)result = await session.execute(query.order_by(Budget.month.desc()))return list(result.scalars().all())@@ -98,7 +98,7 @@ async def get_budgets(# Get month-specific overridesoverrides_result = await session.execute(select(Budget).where(- Budget.user_id == user_id,+ Budget.workspace_id == workspace_id,Budget.is_recurring == False, # noqa: E712Budget.month == month_start,)@@ -113,7 +113,7 @@ async def get_budgets(func.max(Budget.month).label("max_month"),).where(- Budget.user_id == user_id,+ Budget.workspace_id == workspace_id,Budget.is_recurring == True, # noqa: E712Budget.month <= month_start,)@@ -131,7 +131,7 @@ async def get_budgets(),).where(- Budget.user_id == user_id,+ Budget.workspace_id == workspace_id,Budget.is_recurring == True, # noqa: E712))@@ -144,19 +144,23 @@ async def get_budgets(async def get_budget(- session: AsyncSession, budget_id: uuid.UUID, user_id: uuid.UUID+ session: AsyncSession, budget_id: uuid.UUID, workspace_id: uuid.UUID) -> Optional[Budget]:result = await session.execute(- select(Budget).where(Budget.id == budget_id, Budget.user_id == user_id)+ select(Budget).where(Budget.id == budget_id, Budget.workspace_id == workspace_id))return result.scalar_one_or_none()async def create_budget(- session: AsyncSession, user_id: uuid.UUID, data: BudgetCreate+ session: AsyncSession,+ workspace_id: uuid.UUID,+ user_id: uuid.UUID,+ data: BudgetCreate,) -> Budget:budget = Budget(user_id=user_id,+ workspace_id=workspace_id,category_id=data.category_id,amount=data.amount,month=data.month.replace(day=1),@@ -169,9 +173,9 @@ async def create_budget(async def update_budget(- session: AsyncSession, budget_id: uuid.UUID, user_id: uuid.UUID, data: BudgetUpdate+ session: AsyncSession, budget_id: uuid.UUID, workspace_id: uuid.UUID, data: BudgetUpdate) -> Optional[Budget]:- budget = await get_budget(session, budget_id, user_id)+ budget = await get_budget(session, budget_id, workspace_id)if not budget:return None@@ -181,6 +185,7 @@ async def update_budget(# Create a new recurring record with new effective-from monthnew_budget = Budget(user_id=budget.user_id,+ workspace_id=budget.workspace_id,category_id=budget.category_id,amount=data.amount if data.amount is not None else budget.amount,month=effective,@@ -201,9 +206,9 @@ async def update_budget(async def delete_budget(- session: AsyncSession, budget_id: uuid.UUID, user_id: uuid.UUID+ session: AsyncSession, budget_id: uuid.UUID, workspace_id: uuid.UUID) -> bool:- budget = await get_budget(session, budget_id, user_id)+ budget = await get_budget(session, budget_id, workspace_id)if not budget:return False@@ -213,7 +218,10 @@ async def delete_budget(async def get_budget_vs_actual(- session: AsyncSession, user_id: uuid.UUID, month: Optional[date] = None+ session: AsyncSession,+ workspace_id: uuid.UUID,+ user_id: uuid.UUID,+ month: Optional[date] = None,) -> list[BudgetVsActual]:if not month:month = date.today().replace(day=1)@@ -231,11 +239,11 @@ async def get_budget_vs_actual(prev_month_start = month_start.replace(month=month_start.month - 1)prev_month_end = month_start- # Get all categories for this user with their groups+ # Get all categories for this workspace with their groupscats_result = await session.execute(select(Category, CategoryGroup).outerjoin(CategoryGroup, Category.group_id == CategoryGroup.id)- .where(Category.user_id == user_id)+ .where(Category.workspace_id == workspace_id))all_categories = cats_result.all()@@ -243,7 +251,7 @@ async def get_budget_vs_actual(return []# Get budgets for this month (with recurring resolution)- budget_map = await _build_budget_map(session, user_id, month_start)+ budget_map = await _build_budget_map(session, workspace_id, month_start)# Get user's primary currency for FX conversion + reporting modeuser = await session.get(User, user_id)@@ -261,7 +269,7 @@ async def get_budget_vs_actual(func.sum(_primary_amount_expr()),).where(- Transaction.user_id == user_id,+ Transaction.workspace_id == workspace_id,Transaction.type == "debit",report_date >= month_start,report_date < month_end,@@ -279,6 +287,7 @@ async def get_budget_vs_actual(session, user_id, month_start, month_end,use_effective_date=accounting_mode == "accrual",primary_currency=primary_currency,+ workspace_id=workspace_id,)for cat_uuid, total in own_offset.items():if cat_uuid is None:@@ -307,7 +316,7 @@ async def get_budget_vs_actual(spending_map[cat_id] = spending_map.get(cat_id, Decimal("0")) + Decimal(str(total))# Add projected recurring transactions for this month (converted to primary currency)- projections = await _get_recurring_projections(session, user_id, month_start, month_end)+ projections = await _get_recurring_projections(session, workspace_id, month_start, month_end)for proj in projections:if proj["type"] != "debit" or not proj["category_id"]:continue@@ -325,7 +334,7 @@ async def get_budget_vs_actual(func.sum(_primary_amount_expr()),).where(- Transaction.user_id == user_id,+ Transaction.workspace_id == workspace_id,Transaction.type == "debit",report_date >= prev_month_start,report_date < prev_month_end,@@ -342,6 +351,7 @@ async def get_budget_vs_actual(session, user_id, prev_month_start, prev_month_end,use_effective_date=accounting_mode == "accrual",primary_currency=primary_currency,+ workspace_id=workspace_id,)for cat_uuid, total in prev_own_offset.items():if cat_uuid is None:@@ -366,7 +376,7 @@ async def get_budget_vs_actual(prev_spending_map[cat_id] = prev_spending_map.get(cat_id, Decimal("0")) + Decimal(str(total))# Add projected recurring transactions for previous month (converted to primary currency)- prev_projections = await _get_recurring_projections(session, user_id, prev_month_start, prev_month_end)+ prev_projections = await _get_recurring_projections(session, workspace_id, prev_month_start, prev_month_end)for proj in prev_projections:if proj["type"] != "debit" or not proj["category_id"]:continuediff --git a/backend/app/services/category_group_service.py b/backend/app/services/category_group_service.pyindex 2fbec17b..2061914c 100644--- a/backend/app/services/category_group_service.py+++ b/backend/app/services/category_group_service.py@@ -47,13 +47,19 @@ def _resolve_group_name(key: str, lang: str) -> str:return entry.get(lang, entry.get("en", key))-async def create_default_groups(session: AsyncSession, user_id: uuid.UUID, lang: str = "pt-BR") -> dict[str, CategoryGroup]:+async def create_default_groups(+ session: AsyncSession,+ user_id: uuid.UUID,+ lang: str = "pt-BR",+ workspace_id: Optional[uuid.UUID] = None,+) -> dict[str, CategoryGroup]:"""Create default category groups for a user. Returns dict of internal_key -> group. Uses flush (not commit)."""groups = {}for key, data in DEFAULT_GROUPS_I18N.items():name = data.get(lang, data.get("en", key))group = CategoryGroup(user_id=user_id,+ workspace_id=workspace_id,name=name,icon=data["icon"],color=data["color"],@@ -66,36 +72,41 @@ async def create_default_groups(session: AsyncSession, user_id: uuid.UUID, lang:return groups-async def get_groups(session: AsyncSession, user_id: uuid.UUID) -> list[CategoryGroup]:+async def get_groups(session: AsyncSession, workspace_id: uuid.UUID) -> list[CategoryGroup]:result = await session.execute(select(CategoryGroup)- .where(CategoryGroup.user_id == user_id)+ .where(CategoryGroup.workspace_id == workspace_id).options(selectinload(CategoryGroup.categories)).order_by(CategoryGroup.position))return list(result.scalars().all())-async def get_group(session: AsyncSession, group_id: uuid.UUID, user_id: uuid.UUID) -> Optional[CategoryGroup]:+async def get_group(session: AsyncSession, group_id: uuid.UUID, workspace_id: uuid.UUID) -> Optional[CategoryGroup]:result = await session.execute(select(CategoryGroup)- .where(CategoryGroup.id == group_id, CategoryGroup.user_id == user_id)+ .where(CategoryGroup.id == group_id, CategoryGroup.workspace_id == workspace_id).options(selectinload(CategoryGroup.categories)))return result.scalar_one_or_none()-async def create_group(session: AsyncSession, user_id: uuid.UUID, data: CategoryGroupCreate) -> CategoryGroup:- group = CategoryGroup(user_id=user_id, **data.model_dump())+async def create_group(+ session: AsyncSession,+ workspace_id: uuid.UUID,+ user_id: uuid.UUID,+ data: CategoryGroupCreate,+) -> CategoryGroup:+ group = CategoryGroup(user_id=user_id, workspace_id=workspace_id, **data.model_dump())session.add(group)await session.commit()- return await get_group(session, group.id, user_id)+ return await get_group(session, group.id, workspace_id)async def update_group(- session: AsyncSession, group_id: uuid.UUID, user_id: uuid.UUID, data: CategoryGroupUpdate+ session: AsyncSession, group_id: uuid.UUID, workspace_id: uuid.UUID, data: CategoryGroupUpdate) -> Optional[CategoryGroup]:- group = await get_group(session, group_id, user_id)+ group = await get_group(session, group_id, workspace_id)if not group:return None@@ -103,11 +114,11 @@ async def update_group(setattr(group, key, value)await session.commit()- return await get_group(session, group_id, user_id)+ return await get_group(session, group_id, workspace_id)-async def delete_group(session: AsyncSession, group_id: uuid.UUID, user_id: uuid.UUID) -> bool:- group = await get_group(session, group_id, user_id)+async def delete_group(session: AsyncSession, group_id: uuid.UUID, workspace_id: uuid.UUID) -> bool:+ group = await get_group(session, group_id, workspace_id)if not group or group.is_system:return Falsediff --git a/backend/app/services/category_service.py b/backend/app/services/category_service.pyindex 61eb0b9f..69308efb 100644--- a/backend/app/services/category_service.py+++ b/backend/app/services/category_service.py@@ -34,16 +34,41 @@ DEFAULT_CATEGORIES_I18N = {}-async def create_default_categories(session: AsyncSession, user_id: uuid.UUID, lang: str = "pt-BR") -> list[Category]:- # Guard against double-creation (race between categories and groups endpoints)- existing = await session.execute(- select(Category).where(Category.user_id == user_id).limit(1)- )- if existing.scalar_one_or_none():- return await get_categories(session, user_id)+async def create_default_categories(+ session: AsyncSession,+ user_id: uuid.UUID,+ lang: str = "pt-BR",+ workspace_id: Optional[uuid.UUID] = None,+) -> list[Category]:+ # Guard against double-creation. Scope the check to the workspace+ # when one is provided so a user creating a SECOND workspace still+ # gets the defaults seeded there — the prior guard checked+ # user_id and short-circuited every workspace after the first.+ if workspace_id is not None:+ existing = await session.execute(+ select(Category).where(Category.workspace_id == workspace_id).limit(1)+ )+ if existing.scalar_one_or_none():+ return await get_categories(session, workspace_id)+ else:+ # Legacy/test path with no explicit workspace_id — fall back to+ # the user's first workspace via the autostamp listener.+ existing = await session.execute(+ select(Category).where(Category.user_id == user_id).limit(1)+ )+ if existing.scalar_one_or_none():+ from app.models.workspace import Workspace, WorkspaceMember+ row = await session.execute(+ select(Workspace.id)+ .join(WorkspaceMember, WorkspaceMember.workspace_id == Workspace.id)+ .where(WorkspaceMember.user_id == user_id)+ .limit(1)+ )+ scope_id = row.scalar()+ return await get_categories(session, scope_id) if scope_id else []# Create default groups first- groups = await create_default_groups(session, user_id, lang)+ groups = await create_default_groups(session, user_id, lang, workspace_id=workspace_id)categories = []for key, data in DEFAULT_CATEGORIES_I18N.items():@@ -52,6 +77,7 @@ async def create_default_categories(session: AsyncSession, user_id: uuid.UUID, lgroup = groups.get(group_key) if group_key else Nonecategory = Category(user_id=user_id,+ workspace_id=workspace_id,name=name,icon=data["icon"],color=data["color"],@@ -65,22 +91,33 @@ async def create_default_categories(session: AsyncSession, user_id: uuid.UUID, lreturn categories-async def get_categories(session: AsyncSession, user_id: uuid.UUID) -> list[Category]:+async def get_categories(session: AsyncSession, workspace_id: uuid.UUID) -> list[Category]:result = await session.execute(- select(Category).where(Category.user_id == user_id).order_by(Category.is_system.desc(), Category.name)+ select(Category)+ .where(Category.workspace_id == workspace_id)+ .order_by(Category.is_system.desc(), Category.name))return list(result.scalars().all())-async def get_category(session: AsyncSession, category_id: uuid.UUID, user_id: uuid.UUID) -> Optional[Category]:+async def get_category(+ session: AsyncSession, category_id: uuid.UUID, workspace_id: uuid.UUID+) -> Optional[Category]:result = await session.execute(- select(Category).where(Category.id == category_id, Category.user_id == user_id)+ select(Category).where(+ Category.id == category_id, Category.workspace_id == workspace_id+ ))return result.scalar_one_or_none()-async def create_category(session: AsyncSession, user_id: uuid.UUID, data: CategoryCreate) -> Category:- category = Category(user_id=user_id, **data.model_dump())+async def create_category(+ session: AsyncSession,+ workspace_id: uuid.UUID,+ user_id: uuid.UUID,+ data: CategoryCreate,+) -> Category:+ category = Category(user_id=user_id, workspace_id=workspace_id, **data.model_dump())session.add(category)await session.commit()await session.refresh(category)@@ -88,9 +125,12 @@ async def create_category(session: AsyncSession, user_id: uuid.UUID, data: Categasync def update_category(- session: AsyncSession, category_id: uuid.UUID, user_id: uuid.UUID, data: CategoryUpdate+ session: AsyncSession,+ category_id: uuid.UUID,+ workspace_id: uuid.UUID,+ data: CategoryUpdate,) -> Optional[Category]:- category = await get_category(session, category_id, user_id)+ category = await get_category(session, category_id, workspace_id)if not category:return None@@ -102,8 +142,10 @@ async def update_category(return category-async def delete_category(session: AsyncSession, category_id: uuid.UUID, user_id: uuid.UUID) -> bool:- category = await get_category(session, category_id, user_id)+async def delete_category(+ session: AsyncSession, category_id: uuid.UUID, workspace_id: uuid.UUID+) -> bool:+ category = await get_category(session, category_id, workspace_id)if not category or category.is_system:return Falsediff --git a/backend/app/services/connection_service.py b/backend/app/services/connection_service.pyindex bad204c3..609b3e1b 100644--- a/backend/app/services/connection_service.py+++ b/backend/app/services/connection_service.py@@ -331,10 +331,10 @@ async def _match_pluggy_category(return result.scalar_one_or_none()-async def get_connections(session: AsyncSession, user_id: uuid.UUID) -> list[BankConnection]:+async def get_connections(session: AsyncSession, workspace_id: uuid.UUID) -> list[BankConnection]:result = await session.execute(select(BankConnection)- .where(BankConnection.user_id == user_id)+ .where(BankConnection.workspace_id == workspace_id).options(selectinload(BankConnection.accounts)).order_by(BankConnection.created_at.desc()))@@ -342,11 +342,11 @@ async def get_connections(session: AsyncSession, user_id: uuid.UUID) -> list[Banasync def get_connection(- session: AsyncSession, connection_id: uuid.UUID, user_id: uuid.UUID+ session: AsyncSession, connection_id: uuid.UUID, workspace_id: uuid.UUID) -> Optional[BankConnection]:result = await session.execute(select(BankConnection)- .where(BankConnection.id == connection_id, BankConnection.user_id == user_id)+ .where(BankConnection.id == connection_id, BankConnection.workspace_id == workspace_id).options(selectinload(BankConnection.accounts)))return result.scalar_one_or_none()@@ -369,10 +369,10 @@ async def create_connect_token(async def update_connection_settings(session: AsyncSession,connection_id: uuid.UUID,- user_id: uuid.UUID,+ workspace_id: uuid.UUID,settings_update: dict,) -> Optional[BankConnection]:- connection = await get_connection(session, connection_id, user_id)+ connection = await get_connection(session, connection_id, workspace_id)if not connection:return None@@ -393,12 +393,17 @@ async def update_connection_settings(async def handle_oauth_callback(- session: AsyncSession, user_id: uuid.UUID, code: str, provider_name: str+ session: AsyncSession,+ workspace_id: uuid.UUID,+ user_id: uuid.UUID,+ code: str,+ provider_name: str,) -> BankConnection:provider = get_provider(provider_name)connection_data = await provider.handle_oauth_callback(code)connection = BankConnection(+ workspace_id=workspace_id,user_id=user_id,provider=provider_name,external_id=connection_data.external_id,@@ -419,6 +424,7 @@ async def handle_oauth_callback(is_cc = acc_data.type == "credit_card"account = Account(user_id=user_id,+ workspace_id=workspace_id,connection_id=connection.id,external_id=acc_data.external_id,name=acc_data.name,@@ -482,6 +488,7 @@ async def handle_oauth_callback()transaction = Transaction(user_id=user_id,+ workspace_id=workspace_id,account_id=account.id,external_id=txn_data.external_id,description=txn_data.description,@@ -530,7 +537,7 @@ async def handle_oauth_callback(await sync_opening_balance_for_connected_account(session, account)# Detect transfer pairs among newly synced transactions- await detect_transfer_pairs(session, user_id, candidate_ids=new_tx_ids)+ await detect_transfer_pairs(session, workspace_id, candidate_ids=new_tx_ids)# Investment holdings live on /investments — separate endpoint from# /accounts. Pulled after account setup so holdings are available on@@ -958,9 +965,12 @@ async def _sync_credit_card_bills(async def sync_connection(- session: AsyncSession, connection_id: uuid.UUID, user_id: uuid.UUID+ session: AsyncSession,+ connection_id: uuid.UUID,+ workspace_id: uuid.UUID,+ user_id: uuid.UUID,) -> tuple[BankConnection, int]:- connection = await get_connection(session, connection_id, user_id)+ connection = await get_connection(session, connection_id, workspace_id)if not connection:raise ValueError("Connection not found")@@ -1207,7 +1217,7 @@ async def sync_connection(# Detect transfer pairs among newly synced transactionsif new_tx_ids:- await detect_transfer_pairs(session, user_id, candidate_ids=new_tx_ids)+ await detect_transfer_pairs(session, workspace_id, candidate_ids=new_tx_ids)# Clean up phantom duplicates: providers occasionally double-report the# same payment with different ids. Once transfer detection has paired@@ -1237,9 +1247,9 @@ async def sync_connection(async def delete_connection(- session: AsyncSession, connection_id: uuid.UUID, user_id: uuid.UUID+ session: AsyncSession, connection_id: uuid.UUID, workspace_id: uuid.UUID) -> bool:- connection = await get_connection(session, connection_id, user_id)+ connection = await get_connection(session, connection_id, workspace_id)if not connection:return False@@ -1283,7 +1293,7 @@ async def delete_connection()await session.execute(delete(Payee).where(- Payee.user_id == user_id,+ Payee.workspace_id == workspace_id,Payee.id.in_(affected_payee_ids),~has_transactions,~has_external_mappings,diff --git a/backend/app/services/dashboard_service.py b/backend/app/services/dashboard_service.pyindex a8a6e49a..83eb2b47 100644--- a/backend/app/services/dashboard_service.py+++ b/backend/app/services/dashboard_service.py@@ -38,14 +38,17 @@ def _month_range(month: date) -> tuple[date, date]:async def _get_recurring_projections(- session: AsyncSession, user_id: uuid.UUID, month_start: date, month_end: date+ session: AsyncSession,+ workspace_id: uuid.UUID,+ month_start: date,+ month_end: date,) -> list[dict]:"""Compute virtual recurring transaction projections for a month.Pure read — no DB writes. Returns list of dicts with category_id, amount, type, currency."""result = await session.execute(select(RecurringTransaction).where(- RecurringTransaction.user_id == user_id,+ RecurringTransaction.workspace_id == workspace_id,RecurringTransaction.is_active == True,RecurringTransaction.start_date < month_end,)@@ -75,7 +78,10 @@ async def _get_recurring_projections(async def get_summary(- session: AsyncSession, user_id: uuid.UUID, month: Optional[date] = None,+ session: AsyncSession,+ workspace_id: uuid.UUID,+ user_id: uuid.UUID,+ month: Optional[date] = None,balance_date: Optional[date] = None,) -> DashboardSummary:if not month:@@ -104,14 +110,14 @@ async def get_summary(# Current or future month: todaycutoff = today- total_balance = await _total_balance_by_currency(session, user_id, cutoff)+ total_balance = await _total_balance_by_currency(session, workspace_id, cutoff)# For current/future months, project the total balance by adding recurring# projections from cutoff+1 through month_end.if month_end > cutoff:projection_start = cutoff + timedelta(days=1)balance_projections = await _get_recurring_projections(- session, user_id, projection_start, month_end+ session, workspace_id, projection_start, month_end)for proj in balance_projections:signed = proj["amount"] if proj["type"] == "credit" else -proj["amount"]@@ -128,7 +134,7 @@ async def get_summary().join(Account, Transaction.account_id == Account.id).where(- Transaction.user_id == user_id,+ Transaction.workspace_id == workspace_id,Account.is_closed == False,report_date >= month_start,report_date < month_end,@@ -143,7 +149,12 @@ async def get_summary(# Subtract non-owner shares of the user's own split txs — they paid# for the others, so those amounts aren't their actual cost.own_offset_inc, own_offset_exp = await owner_split_offset_pnl(- session, user_id, month_start, month_end, use_effective_date=False+ session,+ user_id,+ month_start,+ month_end,+ use_effective_date=False,+ workspace_id=workspace_id,)monthly_income -= own_offset_incmonthly_expenses -= own_offset_exp@@ -162,23 +173,23 @@ async def get_summary(real_monthly_expenses = monthly_expenses# Add virtual recurring projections- projections = await _get_recurring_projections(session, user_id, month_start, month_end)+ projections = await _get_recurring_projections(session, workspace_id, month_start, month_end)for proj in projections:if proj["type"] == "credit":monthly_income += proj["amount"]else:monthly_expenses += proj["amount"]- # Account count — all accounts belonging to the user (manual + bank-connected)+ # Account count — all accounts in this workspace (manual + bank-connected)accounts_count = await session.scalar(select(func.count()).select_from(Account)- .where(Account.user_id == user_id)+ .where(Account.workspace_id == workspace_id)) or 0# Pending categorization — exclude opening_balance and transfer pairspending_cat_filters = [- Transaction.user_id == user_id,+ Transaction.workspace_id == workspace_id,Transaction.category_id.is_(None),Transaction.source != "opening_balance",# Settlement-sourced rows are auto-generated movements (paying@@ -204,7 +215,8 @@ async def get_summary(# Asset values — use cutoff so past months show historical valuesassets_value, assets_value_primary = await get_asset_values_at(- session, user_id, as_of_date=cutoff, primary_currency=primary_currency+ session, workspace_id, as_of_date=cutoff, primary_currency=primary_currency,+ by_workspace=True,)# Add asset values to total balance@@ -231,7 +243,7 @@ async def get_summary().join(Account, Transaction.account_id == Account.id).where(- Transaction.user_id == user_id,+ Transaction.workspace_id == workspace_id,Account.is_closed == False,report_date >= month_start,report_date < month_end,@@ -253,6 +265,7 @@ async def get_summary(month_end,use_effective_date=False,primary_currency=primary_currency,+ workspace_id=workspace_id,)monthly_income_primary -= own_offset_inc_primonthly_expenses_primary -= own_offset_exp_pri@@ -265,7 +278,8 @@ async def get_summary(from app.models.transaction_split import TransactionSplitviewer_member_ids = select(GroupMember.id).where(- GroupMember.linked_user_id == user_id+ GroupMember.linked_user_id == user_id,+ GroupMember.is_self.is_(False),)shared_currency_rows = await session.execute(select(@@ -325,7 +339,7 @@ async def get_summary(# participate in. We reuse the group balance computation so partial# settlements are already netted out.pending_shares_net = await _compute_pending_shares_net(- session, user_id, primary_currency+ session, workspace_id, user_id, primary_currency)return DashboardSummary(@@ -347,7 +361,10 @@ async def get_summary(async def _compute_pending_shares_net(- session: AsyncSession, user_id: uuid.UUID, primary_currency: str+ session: AsyncSession,+ workspace_id: uuid.UUID,+ user_id: uuid.UUID,+ primary_currency: str,) -> float:"""Sum, in primary currency, the user's net position across everygroup they belong to.@@ -362,23 +379,31 @@ async def _compute_pending_shares_net(from app.models.group import Group, GroupMemberfrom app.services.balance_service import compute_balances- # All groups the user can see (owned + linked-as-member).+ # Scope to groups that live in the CURRENT workspace (where the+ # user is the creator) PLUS groups they're a linked member of from+ # other workspaces (cross-workspace projection). Drop `is_self`+ # links — those are the user's own self-member in their own group,+ # already accounted for by the workspace-scoped path.owned_q = await session.execute(- select(Group.id).where(Group.user_id == user_id)+ select(Group.id).where(+ Group.user_id == user_id,+ Group.workspace_id == workspace_id,+ ))owned_ids = {row[0] for row in owned_q.all()}linked_q = await session.execute(select(GroupMember.group_id, GroupMember.id).where(- GroupMember.linked_user_id == user_id+ GroupMember.linked_user_id == user_id,+ GroupMember.is_self.is_(False),))linked_rows = list(linked_q.all())- linked_ids = {row.group_id for row in linked_rows}+ linked_ids = {row.group_id for row in linked_rows} - owned_idsmember_id_for_group = {row.group_id: row.id for row in linked_rows}total_primary = 0.0for gid in owned_ids | linked_ids:- balances = await compute_balances(session, gid, user_id)+ balances = await compute_balances(session, gid, workspace_id, user_id)if not balances:continuefor line in balances["lines"]:@@ -403,7 +428,10 @@ async def _compute_pending_shares_net(async def get_spending_by_category(- session: AsyncSession, user_id: uuid.UUID, month: Optional[date] = None+ session: AsyncSession,+ workspace_id: uuid.UUID,+ user_id: uuid.UUID,+ month: Optional[date] = None,) -> list[SpendingByCategory]:if not month:month = date.today().replace(day=1)@@ -431,7 +459,7 @@ async def get_spending_by_category(.join(Account, Transaction.account_id == Account.id).outerjoin(Category, Transaction.category_id == Category.id).where(- Transaction.user_id == user_id,+ Transaction.workspace_id == workspace_id,Account.is_closed == False,Transaction.type == "debit",report_date >= month_start,@@ -462,6 +490,7 @@ async def get_spending_by_category(month_end,use_effective_date=accounting_mode == "accrual",primary_currency=primary_currency,+ workspace_id=workspace_id,)for cat_uuid, offset_total in owner_offset.items():cat_id = str(cat_uuid) if cat_uuid else None@@ -511,7 +540,7 @@ async def get_spending_by_category(}# Add virtual recurring projections (debit only), converted to primary currency- projections = await _get_recurring_projections(session, user_id, month_start, month_end)+ projections = await _get_recurring_projections(session, workspace_id, month_start, month_end)# We need category info for recurring projections — fetch categoriescat_cache: dict[str, dict] = {}for proj in projections:@@ -564,7 +593,10 @@ async def get_spending_by_category(async def get_monthly_trend(- session: AsyncSession, user_id: uuid.UUID, months: int = 6+ session: AsyncSession,+ workspace_id: uuid.UUID,+ user_id: uuid.UUID,+ months: int = 6,) -> list[MonthlyTrend]:accounting_mode = await get_credit_card_accounting_mode(session)report_date = (@@ -580,7 +612,7 @@ async def get_monthly_trend().join(Account, Transaction.account_id == Account.id).where(- Transaction.user_id == user_id,+ Transaction.workspace_id == workspace_id,Account.is_closed == False,Transaction.source != "opening_balance",counts_as_user_pnl(),@@ -612,6 +644,7 @@ async def get_monthly_trend(session, user_id, m_start, m_end,use_effective_date=accounting_mode == "accrual",primary_currency=primary_currency,+ workspace_id=workspace_id,)shared_inc, shared_exp = await viewer_shared_pnl(session, user_id, m_start, m_end,@@ -630,7 +663,10 @@ async def get_monthly_trend(async def get_projected_transactions(- session: AsyncSession, user_id: uuid.UUID, month: Optional[date] = None+ session: AsyncSession,+ workspace_id: uuid.UUID,+ user_id: uuid.UUID,+ month: Optional[date] = None,) -> list[ProjectedTransaction]:"""Return virtual recurring transaction projections for a month,enriched with description and category info for display."""@@ -646,7 +682,7 @@ async def get_projected_transactions(result = await session.execute(select(RecurringTransaction).where(- RecurringTransaction.user_id == user_id,+ RecurringTransaction.workspace_id == workspace_id,RecurringTransaction.is_active == True,RecurringTransaction.start_date < month_end,)@@ -733,14 +769,17 @@ def _signed_primary_expr():async def _get_open_accounts(- session: AsyncSession, user_id: uuid.UUID+ session: AsyncSession, workspace_id: uuid.UUID) -> list[Account]:- """Get all non-closed accounts for a user."""+ """Get all non-closed accounts for a workspace."""result = await session.execute(select(Account).outerjoin(BankConnection).where(- or_(Account.user_id == user_id, BankConnection.user_id == user_id),+ or_(+ Account.workspace_id == workspace_id,+ BankConnection.workspace_id == workspace_id,+ ),Account.is_closed == False,))@@ -787,10 +826,10 @@ async def _account_balance_at(async def _total_balance_by_currency(- session: AsyncSession, user_id: uuid.UUID, cutoff: date+ session: AsyncSession, workspace_id: uuid.UUID, cutoff: date) -> dict[str, float]:"""Get total balance across all open accounts at a date, grouped by currency."""- accounts = await _get_open_accounts(session, user_id)+ accounts = await _get_open_accounts(session, workspace_id)totals: dict[str, float] = {}for account in accounts:bal = await _account_balance_at(session, account, cutoff)@@ -799,18 +838,21 @@ async def _total_balance_by_currency(async def _balance_at(- session: AsyncSession, user_id: uuid.UUID, cutoff: date+ session: AsyncSession, workspace_id: uuid.UUID, cutoff: date,+ *, primary_currency_hint: Optional[str] = None,) -> float:- """Get total balance across all open accounts at a specific date, converted to primary currency."""- totals = await _total_balance_by_currency(session, user_id, cutoff)+ """Get total balance across all open accounts at a specific date, converted to primary currency.++ `primary_currency_hint` lets callers avoid an extra User lookup when they+ already know the workspace's primary currency.+ """+ totals = await _total_balance_by_currency(session, workspace_id, cutoff)# If all same currency, just sumif len(totals) <= 1:return sum(totals.values())- # Convert to primary currency- user = await session.get(User, user_id)- primary_currency = user.primary_currency if user else get_settings().default_currency+ primary_currency = primary_currency_hint or get_settings().default_currencytotal = 0.0for currency, amount in totals.items():@@ -820,7 +862,12 @@ async def _balance_at(async def _daily_deltas(- session: AsyncSession, user_id: uuid.UUID, start: date, end: date+ session: AsyncSession,+ workspace_id: uuid.UUID,+ start: date,+ end: date,+ *,+ primary_currency_hint: Optional[str] = None,) -> dict[int, float]:"""Get daily balance deltas for a date range [start, end).Computes per-account in native currency (using amount_primary only for@@ -844,7 +891,7 @@ async def _daily_deltas(.join(Account, Transaction.account_id == Account.id).outerjoin(Category, Transaction.category_id == Category.id).where(- Transaction.user_id == user_id,+ Transaction.workspace_id == workspace_id,Account.is_closed == False,Transaction.date >= start,Transaction.date < end,@@ -864,8 +911,7 @@ async def _daily_deltas(return {int(row[0]): float(row[2] or 0) for row in rows}# Multiple currencies: convert each to primary- user = await session.get(User, user_id)- primary_currency = user.primary_currency if user else get_settings().default_currency+ primary_currency = primary_currency_hint or get_settings().default_currencydeltas: dict[int, float] = {}for row in rows:@@ -880,7 +926,10 @@ async def _daily_deltas(async def get_balance_history(- session: AsyncSession, user_id: uuid.UUID, month: Optional[date] = None+ session: AsyncSession,+ workspace_id: uuid.UUID,+ user_id: uuid.UUID,+ month: Optional[date] = None,) -> BalanceHistory:if not month:month = date.today().replace(day=1)@@ -896,21 +945,36 @@ async def get_balance_history(prev_days_in_month = (prev_month_end - prev_month_start).days+ # Look up the user's primary currency once so the helpers can avoid+ # re-querying.+ user = await session.get(User, user_id)+ primary_currency = user.primary_currency if user else get_settings().default_currency+# Starting balances- current_start = await _balance_at(session, user_id, month_start - timedelta(days=1))- prev_start = await _balance_at(session, user_id, prev_month_start - timedelta(days=1))+ current_start = await _balance_at(+ session, workspace_id, month_start - timedelta(days=1),+ primary_currency_hint=primary_currency,+ )+ prev_start = await _balance_at(+ session, workspace_id, prev_month_start - timedelta(days=1),+ primary_currency_hint=primary_currency,+ )# Daily deltas from real transactions- current_deltas = await _daily_deltas(session, user_id, month_start, month_end)- prev_deltas = await _daily_deltas(session, user_id, prev_month_start, prev_month_end)+ current_deltas = await _daily_deltas(+ session, workspace_id, month_start, month_end,+ primary_currency_hint=primary_currency,+ )+ prev_deltas = await _daily_deltas(+ session, workspace_id, prev_month_start, prev_month_end,+ primary_currency_hint=primary_currency,+ )# Recurring projections for future days of current month (converted to primary currency)proj_deltas: dict[int, float] = {}if month_end > today:- user = await session.get(User, user_id)- primary_currency = user.primary_currency if user else get_settings().default_currencyproj_start = max(month_start, today + timedelta(days=1))- projections = await _get_recurring_projections(session, user_id, proj_start, month_end)+ projections = await _get_recurring_projections(session, workspace_id, proj_start, month_end)for proj in projections:day = proj["date"].dayproj_converted, _ = await convert(diff --git a/backend/app/services/goal_service.py b/backend/app/services/goal_service.pyindex 4fb8256f..b69f5d04 100644--- a/backend/app/services/goal_service.py+++ b/backend/app/services/goal_service.py@@ -31,6 +31,8 @@ async def _resolve_current_amount(Returns the amount in the goal's currency."""goal_currency = goal.currency+ # Asset/account/net_worth lookups need the goal's workspace scope.+ workspace_id = goal.workspace_idif goal.tracking_type == "account" and goal.account_id:account = await session.get(Account, goal.account_id)@@ -61,7 +63,7 @@ async def _resolve_current_amount(elif goal.tracking_type == "net_worth":# Reuse dashboard's account query and balance logic so manual accounts# (whose balance is computed from transactions) are handled correctly.- accounts = await _get_open_accounts(session, user_id)+ accounts = await _get_open_accounts(session, workspace_id)today = date.today()total = Decimal("0")for acc in accounts:@@ -72,8 +74,8 @@ async def _resolve_current_amount(converted, _ = await convert(session, bal, acc.currency, goal_currency)total += converted- # Add asset values- assets_by_currency, _ = await get_asset_values_at(session, user_id)+ # Add asset values (scoped by the goal's workspace).+ assets_by_currency, _ = await get_asset_values_at(session, workspace_id, by_workspace=True)for currency, amount in assets_by_currency.items():if currency == goal_currency:total += Decimal(str(amount))@@ -217,9 +219,12 @@ async def _enrich_goal(async def get_goals(- session: AsyncSession, user_id: uuid.UUID, status: Optional[str] = None+ session: AsyncSession,+ workspace_id: uuid.UUID,+ user_id: uuid.UUID,+ status: Optional[str] = None,) -> list[GoalRead]:- query = select(Goal).where(Goal.user_id == user_id).order_by(Goal.position, Goal.created_at)+ query = select(Goal).where(Goal.workspace_id == workspace_id).order_by(Goal.position, Goal.created_at)if status:query = query.where(Goal.status == status)result = await session.execute(query)@@ -228,10 +233,13 @@ async def get_goals(async def get_goal(- session: AsyncSession, goal_id: uuid.UUID, user_id: uuid.UUID+ session: AsyncSession,+ goal_id: uuid.UUID,+ workspace_id: uuid.UUID,+ user_id: uuid.UUID,) -> Optional[GoalRead]:result = await session.execute(- select(Goal).where(Goal.id == goal_id, Goal.user_id == user_id)+ select(Goal).where(Goal.id == goal_id, Goal.workspace_id == workspace_id))goal = result.scalar_one_or_none()if not goal:@@ -240,10 +248,14 @@ async def get_goal(async def create_goal(- session: AsyncSession, user_id: uuid.UUID, data: GoalCreate+ session: AsyncSession,+ workspace_id: uuid.UUID,+ user_id: uuid.UUID,+ data: GoalCreate,) -> GoalRead:goal = Goal(user_id=user_id,+ workspace_id=workspace_id,name=data.name,target_amount=data.target_amount,current_amount=data.current_amount,@@ -266,10 +278,14 @@ async def create_goal(async def update_goal(- session: AsyncSession, goal_id: uuid.UUID, user_id: uuid.UUID, data: GoalUpdate+ session: AsyncSession,+ goal_id: uuid.UUID,+ workspace_id: uuid.UUID,+ user_id: uuid.UUID,+ data: GoalUpdate,) -> Optional[GoalRead]:result = await session.execute(- select(Goal).where(Goal.id == goal_id, Goal.user_id == user_id)+ select(Goal).where(Goal.id == goal_id, Goal.workspace_id == workspace_id))goal = result.scalar_one_or_none()if not goal:@@ -282,10 +298,10 @@ async def update_goal(async def delete_goal(- session: AsyncSession, goal_id: uuid.UUID, user_id: uuid.UUID+ session: AsyncSession, goal_id: uuid.UUID, workspace_id: uuid.UUID) -> bool:result = await session.execute(- select(Goal).where(Goal.id == goal_id, Goal.user_id == user_id)+ select(Goal).where(Goal.id == goal_id, Goal.workspace_id == workspace_id))goal = result.scalar_one_or_none()if not goal:@@ -296,12 +312,15 @@ async def delete_goal(async def get_goal_summary(- session: AsyncSession, user_id: uuid.UUID, limit: int = 3+ session: AsyncSession,+ workspace_id: uuid.UUID,+ user_id: uuid.UUID,+ limit: int = 3,) -> list[GoalSummary]:"""Get a summary of active goals for the dashboard widget."""result = await session.execute(select(Goal)- .where(Goal.user_id == user_id, Goal.status == "active")+ .where(Goal.workspace_id == workspace_id, Goal.status == "active").order_by(Goal.position, Goal.created_at).limit(limit))diff --git a/backend/app/services/group_service.py b/backend/app/services/group_service.pyindex 1419b721..2e7c9e07 100644--- a/backend/app/services/group_service.py+++ b/backend/app/services/group_service.py@@ -19,8 +19,9 @@ from app.schemas.group import (def _tag_owner(group: Group, user_id: uuid.UUID) -> Group:"""Set a transient `is_owner` flag for the response layer.- Pydantic's from_attributes picks this up — the schema treats- `is_owner` as derived per-request, not stored on the model.+ The "owner" of a group is the human who created it, not the+ workspace it lives in — `Group.user_id` retains creator semantics+ even after the workspace migration."""group.is_owner = group.user_id == user_id # type: ignore[attr-defined]if getattr(group, "members", None):@@ -36,7 +37,16 @@ def _tag_member_self(requesting user rather than the stored flag (which only marks theowner's own member). Falls back to the stored flag for an ownerwhose self-member isn't linked to a Securo account.++ Uses `set_committed_value` rather than a plain attribute assignment:+ a plain assignment dirties the row, and the next session commit+ would persist this per-request view as if it were the canonical+ truth. The set_committed_value call updates the in-memory attribute+ (so Pydantic from_attributes still sees the overridden value) but+ leaves the row clean."""+ from sqlalchemy.orm.attributes import set_committed_value+is_linked_to_caller = (member.linked_user_id is not None and member.linked_user_id == user_id)@@ -45,7 +55,7 @@ def _tag_member_self(and member.linked_user_id is Noneand bool(member.is_self))- member.is_self = is_linked_to_caller or is_owner_self_unlinked+ set_committed_value(member, "is_self", is_linked_to_caller or is_owner_self_unlinked)return member@@ -62,23 +72,38 @@ async def _resolve_member_email(return result.scalar_one_or_none()-def _visible_predicate(user_id: uuid.UUID):- """Group is visible if the user is the owner OR linked as a member.- Implemented as a subquery so the filter survives joins/options."""+def _visible_predicate(workspace_id: uuid.UUID, user_id: uuid.UUID):+ """Group is visible when EITHER:+ - it lives in the current workspace (any workspace member sees it), OR+ - the requesting user is linked as a member from outside the+ workspace (cross-workspace settlement projection — the Splitwise+ case where Adam invites Eve from her own workspace).++ `is_self` memberships are EXCLUDED from the cross-workspace+ projection: those represent the group's owner, who should see the+ group only in the workspace where it lives — not in every other+ workspace they belong to.+ """member_groups = (select(GroupMember.group_id)- .where(GroupMember.linked_user_id == user_id)+ .where(+ GroupMember.linked_user_id == user_id,+ GroupMember.is_self.is_(False),+ ).distinct())- return or_(Group.user_id == user_id, Group.id.in_(member_groups))+ return or_(Group.workspace_id == workspace_id, Group.id.in_(member_groups))async def list_groups(- session: AsyncSession, user_id: uuid.UUID, include_archived: bool = False+ session: AsyncSession,+ workspace_id: uuid.UUID,+ user_id: uuid.UUID,+ include_archived: bool = False,) -> list[Group]:query = (select(Group)- .where(_visible_predicate(user_id))+ .where(_visible_predicate(workspace_id, user_id)).options(selectinload(Group.members)).order_by(Group.created_at.desc()))@@ -89,29 +114,31 @@ async def list_groups(async def get_group(- session: AsyncSession, group_id: uuid.UUID, user_id: uuid.UUID+ session: AsyncSession,+ group_id: uuid.UUID,+ workspace_id: uuid.UUID,) -> Optional[Group]:- """Returns the group if the user is the owner. Used by edit paths- that need to enforce ownership."""+ """Returns the group if it lives in this workspace. Used by edit+ paths that need to enforce workspace ownership."""result = await session.execute(select(Group)- .where(Group.id == group_id, Group.user_id == user_id)+ .where(Group.id == group_id, Group.workspace_id == workspace_id).options(selectinload(Group.members)))- group = result.scalar_one_or_none()- if group is not None:- _tag_owner(group, user_id)- return group+ return result.scalar_one_or_none()async def get_group_visible(- session: AsyncSession, group_id: uuid.UUID, user_id: uuid.UUID+ session: AsyncSession,+ group_id: uuid.UUID,+ workspace_id: uuid.UUID,+ user_id: uuid.UUID,) -> Optional[Group]:- """Returns the group if the user is the owner OR a linked member.- Use for read-only endpoints that should also serve members."""+ """Returns the group if visible under the read predicate:+ in-workspace OR the user is a linked cross-workspace member."""result = await session.execute(select(Group)- .where(Group.id == group_id, _visible_predicate(user_id))+ .where(Group.id == group_id, _visible_predicate(workspace_id, user_id)).options(selectinload(Group.members)))group = result.scalar_one_or_none()@@ -121,18 +148,24 @@ async def get_group_visible(async def create_group(- session: AsyncSession, user_id: uuid.UUID, data: GroupCreate+ session: AsyncSession,+ workspace_id: uuid.UUID,+ user_id: uuid.UUID,+ data: GroupCreate,) -> Group:+ # Uniqueness is scoped to the workspace, not the creator — a+ # workspace can't have two "Lunch Club" groups even if different+ # members created them.existing = await session.execute(select(Group).where(- Group.user_id == user_id,+ Group.workspace_id == workspace_id,func.lower(Group.name) == data.name.strip().lower(),))if existing.scalar_one_or_none():raise ValueError("A group with this name already exists")- group = Group(user_id=user_id, **data.model_dump())+ group = Group(workspace_id=workspace_id, user_id=user_id, **data.model_dump())session.add(group)await session.flush()# Eager-load members so the response shape stays stable.@@ -144,10 +177,11 @@ async def create_group(async def update_group(session: AsyncSession,group_id: uuid.UUID,+ workspace_id: uuid.UUID,user_id: uuid.UUID,data: GroupUpdate,) -> Optional[Group]:- group = await get_group(session, group_id, user_id)+ group = await get_group(session, group_id, workspace_id)if not group:return None@@ -155,7 +189,7 @@ async def update_group(if "name" in update_data and update_data["name"]:clash = await session.execute(select(Group).where(- Group.user_id == user_id,+ Group.workspace_id == workspace_id,func.lower(Group.name) == update_data["name"].strip().lower(),Group.id != group_id,)@@ -172,9 +206,11 @@ async def update_group(async def delete_group(- session: AsyncSession, group_id: uuid.UUID, user_id: uuid.UUID+ session: AsyncSession,+ group_id: uuid.UUID,+ workspace_id: uuid.UUID,) -> bool:- group = await get_group(session, group_id, user_id)+ group = await get_group(session, group_id, workspace_id)if not group:return Falsetry:@@ -192,14 +228,16 @@ async def delete_group(async def list_members(- session: AsyncSession, group_id: uuid.UUID, user_id: uuid.UUID+ session: AsyncSession,+ group_id: uuid.UUID,+ workspace_id: uuid.UUID,+ user_id: uuid.UUID,) -> Optional[list[GroupMember]]:# Skip the eager-loaded `Group.members` collection here — within a# long-lived session (notably tests) the identity map can hold a# stale snapshot after upstream mutations like `_clear_self_flag`.# A direct query always reflects the current row state.- # Visible to owners AND linked members (read-only context).- group = await get_group_visible(session, group_id, user_id)+ group = await get_group_visible(session, group_id, workspace_id, user_id)if not group:return Noneresult = await session.execute(@@ -213,10 +251,10 @@ async def list_members(async def create_member(session: AsyncSession,group_id: uuid.UUID,- user_id: uuid.UUID,+ workspace_id: uuid.UUID,data: GroupMemberCreate,) -> Optional[GroupMember]:- group = await get_group(session, group_id, user_id)+ group = await get_group(session, group_id, workspace_id)if not group:return None@@ -240,7 +278,9 @@ async def create_member(# caller can override by passing linked_user_id explicitly.if payload.get("linked_user_id") is None:payload["linked_user_id"] = await _resolve_member_email(session, payload.get("email"))- member = GroupMember(group_id=group_id, **payload)+ member = GroupMember(+ group_id=group_id, workspace_id=workspace_id, **payload+ )session.add(member)await session.commit()await session.refresh(member)@@ -251,10 +291,10 @@ async def update_member(session: AsyncSession,group_id: uuid.UUID,member_id: uuid.UUID,- user_id: uuid.UUID,+ workspace_id: uuid.UUID,data: GroupMemberUpdate,) -> Optional[GroupMember]:- group = await get_group(session, group_id, user_id)+ group = await get_group(session, group_id, workspace_id)if not group:return None@@ -303,9 +343,9 @@ async def delete_member(session: AsyncSession,group_id: uuid.UUID,member_id: uuid.UUID,- user_id: uuid.UUID,+ workspace_id: uuid.UUID,) -> bool:- group = await get_group(session, group_id, user_id)+ group = await get_group(session, group_id, workspace_id)if not group:return False@@ -333,17 +373,19 @@ async def delete_member(async def list_transactions(session: AsyncSession,group_id: uuid.UUID,+ workspace_id: uuid.UUID,user_id: uuid.UUID,limit: int = 20,) -> Optional[list]:"""Return the most recent transactions whose splits reference any- member of this group. Visible to owner + linked members."""+ member of this group. Visible to workspace members + linked+ cross-workspace members."""from sqlalchemy.orm import selectinload as _selfrom app.models.transaction import Transactionfrom app.models.transaction_split import TransactionSplit- if not await get_group_visible(session, group_id, user_id):+ if not await get_group_visible(session, group_id, workspace_id, user_id):return Nonemember_ids_subq = select(GroupMember.id).where(GroupMember.group_id == group_id)diff --git a/backend/app/services/import_service.py b/backend/app/services/import_service.pyindex 0b7742e8..aab8bc4d 100644--- a/backend/app/services/import_service.py+++ b/backend/app/services/import_service.py@@ -484,18 +484,18 @@ def parse_csv(async def enrich_with_category_suggestions(session: AsyncSession,- user_id: uuid.UUID,+ workspace_id: uuid.UUID,transactions: list[TransactionImport],) -> list[TransactionImport]:result = await session.execute(select(Rule)- .where(Rule.user_id == user_id, Rule.is_active == True)+ .where(Rule.workspace_id == workspace_id, Rule.is_active == True).order_by(Rule.priority, Rule.id))rules = result.scalars().all()category_result = await session.execute(- select(Category).where(Category.user_id == user_id)+ select(Category).where(Category.workspace_id == workspace_id))category_name_map = {str(c.id): c.name for c in category_result.scalars()}@@ -528,6 +528,7 @@ async def enrich_with_category_suggestions(async def import_transactions(session: AsyncSession,+ workspace_id: uuid.UUID,user_id: uuid.UUID,account_id: uuid.UUID,transactions: list[TransactionImport],@@ -536,7 +537,11 @@ async def import_transactions(detected_format: str = "",detect_duplicates: bool = True,) -> tuple[int, int, int, uuid.UUID]:- """Import transactions into an account. Returns (imported, skipped, excluded, import_log_id)."""+ """Import transactions into an account in the given workspace.++ `workspace_id` scopes tenant filters + stamps new rows. `user_id`+ is the creator/author recorded on Transaction + ImportLog.+ Returns (imported, skipped, excluded, import_log_id)."""from app.models.import_log import ImportLogincluded = [t for t in transactions if not t.excluded]@@ -549,6 +554,7 @@ async def import_transactions(# Create import log first to get its IDimport_log = ImportLog(user_id=user_id,+ workspace_id=workspace_id,account_id=account_id,filename=filename,format=detected_format,@@ -566,9 +572,9 @@ async def import_transactions(account = account_result.scalar_one_or_none()account_currency = account.currency if account else get_settings().default_currency- # Build category name → id map for this user (used when CSV provides category names)+ # Build category name → id map scoped to the workspace.category_result = await session.execute(- select(Category).where(Category.user_id == user_id)+ select(Category).where(Category.workspace_id == workspace_id))category_map = {c.name: c.id for c in category_result.scalars()}@@ -627,6 +633,7 @@ async def import_transactions(transaction = Transaction(user_id=user_id,+ workspace_id=workspace_id,account_id=account_id,description=txn_data.description,amount=txn_data.amount,diff --git a/backend/app/services/payee_service.py b/backend/app/services/payee_service.pyindex ebffbebb..471fe9a6 100644--- a/backend/app/services/payee_service.py+++ b/backend/app/services/payee_service.py@@ -12,8 +12,8 @@ from app.models.category import Categoryfrom app.schemas.payee import PayeeCreate, PayeeUpdate-async def get_payees(session: AsyncSession, user_id: uuid.UUID) -> list[Payee]:- """List all payees for a user with transaction counts."""+async def get_payees(session: AsyncSession, workspace_id: uuid.UUID) -> list[Payee]:+ """List all payees in a workspace with transaction counts."""count_subq = (select(Transaction.payee_id,@@ -27,7 +27,7 @@ async def get_payees(session: AsyncSession, user_id: uuid.UUID) -> list[Payee]:result = await session.execute(select(Payee, tx_count.label("transaction_count")).outerjoin(count_subq, Payee.id == count_subq.c.payee_id)- .where(Payee.user_id == user_id)+ .where(Payee.workspace_id == workspace_id).order_by(Payee.name))payees = []@@ -38,46 +38,67 @@ async def get_payees(session: AsyncSession, user_id: uuid.UUID) -> list[Payee]:return payees-async def get_payee(session: AsyncSession, payee_id: uuid.UUID, user_id: uuid.UUID) -> Optional[Payee]:+async def get_payee(session: AsyncSession, payee_id: uuid.UUID, workspace_id: uuid.UUID) -> Optional[Payee]:result = await session.execute(- select(Payee).where(Payee.id == payee_id, Payee.user_id == user_id)+ select(Payee).where(Payee.id == payee_id, Payee.workspace_id == workspace_id))return result.scalar_one_or_none()-async def get_or_create_payee(session: AsyncSession, user_id: uuid.UUID, name: str) -> Payee:- """Find a payee by name (case-insensitive) or create a new one."""+async def get_or_create_payee(+ session: AsyncSession,+ user_id: uuid.UUID,+ name: str,+ *,+ workspace_id: Optional[uuid.UUID] = None,+) -> Payee:+ """Find a payee by name (case-insensitive) or create a new one.++ `user_id` is kept first for backwards compatibility with import/connection+ sync paths. When `workspace_id` is provided, the lookup scopes by workspace;+ otherwise the autostamp listener fills it in on insert.+ """name = name.strip()if not name:raise ValueError("Payee name cannot be empty")- result = await session.execute(- select(Payee).where(Payee.user_id == user_id, func.lower(Payee.name) == name.lower())- )+ lookup = select(Payee).where(func.lower(Payee.name) == name.lower())+ if workspace_id is not None:+ lookup = lookup.where(Payee.workspace_id == workspace_id)+ else:+ lookup = lookup.where(Payee.user_id == user_id)+ result = await session.execute(lookup)payee = result.scalar_one_or_none()if payee:return payeepayee = Payee(user_id=user_id, name=name)+ if workspace_id is not None:+ payee.workspace_id = workspace_idsession.add(payee)await session.flush()return payee-async def create_payee(session: AsyncSession, user_id: uuid.UUID, data: PayeeCreate) -> Payee:+async def create_payee(+ session: AsyncSession,+ workspace_id: uuid.UUID,+ user_id: uuid.UUID,+ data: PayeeCreate,+) -> Payee:# Check uniquenessexisting = await session.execute(- select(Payee).where(Payee.user_id == user_id, func.lower(Payee.name) == data.name.strip().lower())+ select(Payee).where(Payee.workspace_id == workspace_id, func.lower(Payee.name) == data.name.strip().lower()))if existing.scalar_one_or_none():raise ValueError("A payee with this name already exists")- payee = Payee(user_id=user_id, **data.model_dump())+ payee = Payee(user_id=user_id, workspace_id=workspace_id, **data.model_dump())session.add(payee)await session.flush()# Self-mapping for merge tracking- mapping = PayeeMapping(id=payee.id, user_id=user_id, target_id=payee.id)+ mapping = PayeeMapping(id=payee.id, user_id=user_id, workspace_id=workspace_id, target_id=payee.id)session.add(mapping)await session.commit()@@ -87,9 +108,9 @@ async def create_payee(session: AsyncSession, user_id: uuid.UUID, data: PayeeCreasync def update_payee(- session: AsyncSession, payee_id: uuid.UUID, user_id: uuid.UUID, data: PayeeUpdate+ session: AsyncSession, payee_id: uuid.UUID, workspace_id: uuid.UUID, data: PayeeUpdate) -> Optional[Payee]:- payee = await get_payee(session, payee_id, user_id)+ payee = await get_payee(session, payee_id, workspace_id)if not payee:return None@@ -99,7 +120,7 @@ async def update_payee(if "name" in update_data and update_data["name"]:existing = await session.execute(select(Payee).where(- Payee.user_id == user_id,+ Payee.workspace_id == workspace_id,func.lower(Payee.name) == update_data["name"].strip().lower(),Payee.id != payee_id,)@@ -115,8 +136,8 @@ async def update_payee(return payee-async def delete_payee(session: AsyncSession, payee_id: uuid.UUID, user_id: uuid.UUID) -> bool:- payee = await get_payee(session, payee_id, user_id)+async def delete_payee(session: AsyncSession, payee_id: uuid.UUID, workspace_id: uuid.UUID) -> bool:+ payee = await get_payee(session, payee_id, workspace_id)if not payee:return False@@ -139,13 +160,13 @@ async def delete_payee(session: AsyncSession, payee_id: uuid.UUID, user_id: uuidasync def merge_payees(session: AsyncSession,- user_id: uuid.UUID,+ workspace_id: uuid.UUID,target_id: uuid.UUID,source_ids: list[uuid.UUID],) -> int:"""Merge source payees into target. Returns number of transactions reassigned."""# Validate target- target = await get_payee(session, target_id, user_id)+ target = await get_payee(session, target_id, workspace_id)if not target:raise ValueError("Target payee not found")@@ -153,7 +174,7 @@ async def merge_payees(for source_id in source_ids:if source_id == target_id:continue- source = await get_payee(session, source_id, user_id)+ source = await get_payee(session, source_id, workspace_id)if not source:raise ValueError(f"Source payee {source_id} not found")@@ -179,7 +200,7 @@ async def merge_payees(for source_id in source_ids:if source_id == target_id:continue- source = await get_payee(session, source_id, user_id)+ source = await get_payee(session, source_id, workspace_id)if source:await session.delete(source)@@ -190,18 +211,18 @@ async def merge_payees(async def get_payee_summary(session: AsyncSession,payee_id: uuid.UUID,- user_id: uuid.UUID,+ workspace_id: uuid.UUID,start_date: Optional[date] = None,end_date: Optional[date] = None,) -> dict:"""Return spending analytics for a payee."""- payee = await get_payee(session, payee_id, user_id)+ payee = await get_payee(session, payee_id, workspace_id)if not payee:raise ValueError("Payee not found")base = select(Transaction).where(Transaction.payee_id == payee_id,- Transaction.user_id == user_id,+ Transaction.workspace_id == workspace_id,)if start_date:base = base.where(Transaction.date >= start_date)@@ -228,7 +249,7 @@ async def get_payee_summary().where(Transaction.payee_id == payee_id,- Transaction.user_id == user_id,+ Transaction.workspace_id == workspace_id,))row = totals.one()@@ -238,7 +259,7 @@ async def get_payee_summary(select(Transaction.category_id, func.count(Transaction.id).label("cnt")).where(Transaction.payee_id == payee_id,- Transaction.user_id == user_id,+ Transaction.workspace_id == workspace_id,Transaction.category_id.isnot(None),).group_by(Transaction.category_id)diff --git a/backend/app/services/recurring_transaction_service.py b/backend/app/services/recurring_transaction_service.pyindex b2eef814..2d0f0203 100644--- a/backend/app/services/recurring_transaction_service.py+++ b/backend/app/services/recurring_transaction_service.py@@ -15,18 +15,18 @@ from app.services.credit_card_service import apply_effective_datefrom app.services.fx_rate_service import stamp_primary_amount-async def _verify_account_owned(- session: AsyncSession, user_id: uuid.UUID, account_id: uuid.UUID+async def _verify_account_in_workspace(+ session: AsyncSession, workspace_id: uuid.UUID, account_id: uuid.UUID) -> None:- """Raise ValueError if the account does not belong to the user (directly or via a bank connection)."""+ """Raise ValueError if the account isn't reachable from this workspace."""result = await session.execute(select(Account).outerjoin(BankConnection).where(Account.id == account_id,or_(- Account.user_id == user_id,- BankConnection.user_id == user_id,+ Account.workspace_id == workspace_id,+ BankConnection.workspace_id == workspace_id,),))@@ -35,30 +35,33 @@ async def _verify_account_owned(async def get_recurring_transactions(- session: AsyncSession, user_id: uuid.UUID+ session: AsyncSession, workspace_id: uuid.UUID) -> list[RecurringTransaction]:result = await session.execute(select(RecurringTransaction)- .where(RecurringTransaction.user_id == user_id)+ .where(RecurringTransaction.workspace_id == workspace_id).order_by(RecurringTransaction.next_occurrence))return list(result.scalars().all())async def get_recurring_transaction(- session: AsyncSession, recurring_id: uuid.UUID, user_id: uuid.UUID+ session: AsyncSession, recurring_id: uuid.UUID, workspace_id: uuid.UUID) -> Optional[RecurringTransaction]:result = await session.execute(select(RecurringTransaction)- .where(RecurringTransaction.id == recurring_id, RecurringTransaction.user_id == user_id)+ .where(RecurringTransaction.id == recurring_id, RecurringTransaction.workspace_id == workspace_id))return result.scalar_one_or_none()async def create_recurring_transaction(- session: AsyncSession, user_id: uuid.UUID, data: RecurringTransactionCreate+ session: AsyncSession,+ workspace_id: uuid.UUID,+ user_id: uuid.UUID,+ data: RecurringTransactionCreate,) -> RecurringTransaction:- await _verify_account_owned(session, user_id, data.account_id)+ await _verify_account_in_workspace(session, workspace_id, data.account_id)next_occ = data.start_dateif data.skip_first:next_occ = _advance_date(@@ -67,6 +70,7 @@ async def create_recurring_transaction()recurring = RecurringTransaction(user_id=user_id,+ workspace_id=workspace_id,account_id=data.account_id,category_id=data.category_id,description=data.description,@@ -91,9 +95,9 @@ async def create_recurring_transaction(async def update_recurring_transaction(- session: AsyncSession, recurring_id: uuid.UUID, user_id: uuid.UUID, data: RecurringTransactionUpdate+ session: AsyncSession, recurring_id: uuid.UUID, workspace_id: uuid.UUID, data: RecurringTransactionUpdate) -> Optional[RecurringTransaction]:- recurring = await get_recurring_transaction(session, recurring_id, user_id)+ recurring = await get_recurring_transaction(session, recurring_id, workspace_id)if not recurring:return None@@ -106,7 +110,7 @@ async def update_recurring_transaction(if new_account_id is None:raise ValueError("account_id is required")if new_account_id != recurring.account_id:- await _verify_account_owned(session, user_id, new_account_id)+ await _verify_account_in_workspace(session, workspace_id, new_account_id)for key, value in update_data.items():setattr(recurring, key, value)@@ -117,9 +121,9 @@ async def update_recurring_transaction(async def delete_recurring_transaction(- session: AsyncSession, recurring_id: uuid.UUID, user_id: uuid.UUID+ session: AsyncSession, recurring_id: uuid.UUID, workspace_id: uuid.UUID) -> bool:- recurring = await get_recurring_transaction(session, recurring_id, user_id)+ recurring = await get_recurring_transaction(session, recurring_id, workspace_id)if not recurring:return Falsediff --git a/backend/app/services/report_service.py b/backend/app/services/report_service.pyindex 8b52287d..404bd6b8 100644--- a/backend/app/services/report_service.py+++ b/backend/app/services/report_service.py@@ -37,22 +37,23 @@ CATEGORY_TREND_TOP_N = 11async def _asset_value_at(- session: AsyncSession, user_id: uuid.UUID, cutoff: date,+ session: AsyncSession, workspace_id: uuid.UUID, cutoff: date,primary_currency: str = "USD",) -> float:"""Sum of all active asset values at a given date, converted to primary currency."""_, total = await get_asset_values_at(- session, user_id, as_of_date=cutoff, primary_currency=primary_currency+ session, workspace_id, as_of_date=cutoff,+ primary_currency=primary_currency, by_workspace=True,)return totalasync def _net_worth_at(- session: AsyncSession, user_id: uuid.UUID, cutoff: date,+ session: AsyncSession, workspace_id: uuid.UUID, cutoff: date,primary_currency: str = "USD",) -> ReportDataPoint:"""Compute a single net worth snapshot at a given date, converted to primary currency."""- accounts = await _get_open_accounts(session, user_id)+ accounts = await _get_open_accounts(session, workspace_id)accounts_total = 0.0liabilities_total = 0.0@@ -72,7 +73,7 @@ async def _net_worth_at(else:accounts_total += converted_val- assets_total = await _asset_value_at(session, user_id, cutoff, primary_currency)+ assets_total = await _asset_value_at(session, workspace_id, cutoff, primary_currency)net_worth = accounts_total + assets_total - liabilities_totalreturn ReportDataPoint(@@ -147,6 +148,7 @@ def _date_points(async def get_net_worth_report(session: AsyncSession,+ workspace_id: uuid.UUID,user_id: uuid.UUID,months: int = 12,interval: str = "monthly",@@ -166,7 +168,7 @@ async def get_net_worth_report(# Compute snapshot at each date pointtrend: list[ReportDataPoint] = []for point in points:- dp = await _net_worth_at(session, user_id, point, primary_currency)+ dp = await _net_worth_at(session, workspace_id, point, primary_currency)dp.date = _format_date_label(point, interval)trend.append(dp)@@ -174,7 +176,7 @@ async def get_net_worth_report(current = trend[-1] if trend else ReportDataPoint(date="", value=0, breakdowns={"accounts": 0, "assets": 0, "liabilities": 0})- baseline = await _net_worth_at(session, user_id, start, primary_currency)+ baseline = await _net_worth_at(session, workspace_id, start, primary_currency)previous = baseline if trend else currentchange_amount = current.value - previous.value@@ -233,7 +235,7 @@ async def get_net_worth_report("other": "#6B7280",}composition: list[ReportCompositionItem] = []- accounts = await _get_open_accounts(session, user_id)+ accounts = await _get_open_accounts(session, workspace_id)for account in accounts:bal = await _account_balance_at(session, account, today)converted, _ = await convert(@@ -258,10 +260,10 @@ async def get_net_worth_report(group="accounts",))- # Assets+ # Assets — scoped to workspaceasset_result = await session.execute(select(Asset).where(- Asset.user_id == user_id,+ Asset.workspace_id == workspace_id,Asset.is_archived == False,Asset.sell_date.is_(None),)@@ -316,6 +318,7 @@ def _interval_label_expr(interval: str, date_col=None):async def get_income_expenses_report(session: AsyncSession,+ workspace_id: uuid.UUID,user_id: uuid.UUID,months: int = 12,interval: str = "monthly",@@ -347,7 +350,7 @@ async def get_income_expenses_report().join(Account, Transaction.account_id == Account.id).where(- Transaction.user_id == user_id,+ Transaction.workspace_id == workspace_id,Account.is_closed == False,report_date >= start,report_date <= today,@@ -403,6 +406,7 @@ async def get_income_expenses_report(.join(Transaction, _TS_.transaction_id == Transaction.id).where(Transaction.user_id == user_id,+ Transaction.workspace_id == workspace_id,_TS_.group_member_id.notin_(own_member_ids_sq),report_date >= start,report_date <= today,@@ -438,8 +442,11 @@ async def get_income_expenses_report(from app.models.group import GroupMemberfrom app.models.transaction_split import TransactionSplit+ # Exclude is_self memberships — the owner's own self-member must+ # not surface their in-Pessoal transactions in Trabalho's report.viewer_member_ids = select(GroupMember.id).where(- GroupMember.linked_user_id == user_id+ GroupMember.linked_user_id == user_id,+ GroupMember.is_self.is_(False),)shared_result = await session.execute(select(@@ -463,6 +470,7 @@ async def get_income_expenses_report(.where(TransactionSplit.group_member_id.in_(viewer_member_ids),Transaction.user_id != user_id,+ Transaction.workspace_id != workspace_id,report_date >= start,report_date <= today,Transaction.source != "opening_balance",@@ -497,7 +505,7 @@ async def get_income_expenses_report(cursor = startwhile cursor <= today:m_start, m_end = _month_range(cursor)- projections = await _get_recurring_projections(session, user_id, m_start, m_end)+ projections = await _get_recurring_projections(session, workspace_id, m_start, m_end)for proj in projections:# Convert to primary currencyconverted, _ = await fx_convert(@@ -595,7 +603,7 @@ async def get_income_expenses_report(.join(Account, Transaction.account_id == Account.id).outerjoin(Category, Transaction.category_id == Category.id).where(- Transaction.user_id == user_id,+ Transaction.workspace_id == workspace_id,Account.is_closed == False,report_date >= start,report_date <= today,@@ -651,7 +659,7 @@ async def get_income_expenses_report(.join(Account, Transaction.account_id == Account.id).outerjoin(Category, Transaction.category_id == Category.id).where(- Transaction.user_id == user_id,+ Transaction.workspace_id == workspace_id,Account.is_closed == False,report_date >= start,report_date <= today,@@ -696,6 +704,7 @@ async def get_income_expenses_report(.join(Transaction, _TS_.transaction_id == Transaction.id).where(Transaction.user_id == user_id,+ Transaction.workspace_id == workspace_id,Transaction.type == "debit",_TS_.group_member_id.notin_(own_member_ids_sq),report_date >= start,@@ -731,7 +740,7 @@ async def get_income_expenses_report(cursor2 = startwhile cursor2 <= today:m_start, m_end = _month_range(cursor2)- projections = await _get_recurring_projections(session, user_id, m_start, m_end)+ projections = await _get_recurring_projections(session, workspace_id, m_start, m_end)period_label = _format_date_label(cursor2, interval)for proj in projections:cat_id_str = str(proj["category_id"]) if proj["category_id"] else "uncategorized"@@ -875,7 +884,7 @@ _PAST_HISTORY_MONTHS = 1async def _get_baseline_projection(session: AsyncSession,- user_id: uuid.UUID,+ workspace_id: uuid.UUID,today: date,end: date,primary_currency: str,@@ -907,7 +916,7 @@ async def _get_baseline_projection(select(func.min(Transaction.date)).join(Account, Transaction.account_id == Account.id).where(- Transaction.user_id == user_id,+ Transaction.workspace_id == workspace_id,Account.is_closed == False,Transaction.date <= today,Transaction.source != "opening_balance",@@ -928,7 +937,7 @@ async def _get_baseline_projection().join(Account, Transaction.account_id == Account.id).where(- Transaction.user_id == user_id,+ Transaction.workspace_id == workspace_id,Account.is_closed == False,Transaction.date >= window_start,Transaction.date <= today,@@ -982,6 +991,7 @@ async def _get_baseline_projection(async def get_cash_flow_report(session: AsyncSession,+ workspace_id: uuid.UUID,user_id: uuid.UUID,months: int = 6,interval: str = "daily",@@ -1021,7 +1031,9 @@ async def get_cash_flow_report(# "Saldo Atual" shown in the hero card. The walk is anchored at this# value (not at balance-at-chart_start) so opening-balance transactions# inside the past-history window can't introduce drift.- current_balance = await _balance_at(session, user_id, today)+ current_balance = await _balance_at(+ session, workspace_id, today, primary_currency_hint=primary_currency+ )rate_cache: dict[str, Decimal] = {primary_currency: Decimal("1")}@@ -1057,7 +1069,7 @@ async def get_cash_flow_report().join(Account, Transaction.account_id == Account.id).where(- Transaction.user_id == user_id,+ Transaction.workspace_id == workspace_id,Account.is_closed == False,flow_date_col > chart_start,flow_date_col <= today,@@ -1085,7 +1097,7 @@ async def get_cash_flow_report().join(Account, Transaction.account_id == Account.id).where(- Transaction.user_id == user_id,+ Transaction.workspace_id == workspace_id,Account.is_closed == False,flow_date_col > today,flow_date_col <= end,@@ -1117,7 +1129,7 @@ async def get_cash_flow_report().join(Account, Transaction.account_id == Account.id).where(- Transaction.user_id == user_id,+ Transaction.workspace_id == workspace_id,Account.is_closed == False,Account.type == "credit_card",Transaction.date <= today,@@ -1149,11 +1161,11 @@ async def get_cash_flow_report(if baseline:projections, baseline_lookback_days = await _get_baseline_projection(- session, user_id, today, end, primary_currency, _to_primary,+ session, workspace_id, today, end, primary_currency, _to_primary,)else:projections = await _get_recurring_projections(- session, user_id, today + timedelta(days=1), end + timedelta(days=1),+ session, workspace_id, today + timedelta(days=1), end + timedelta(days=1),)for proj in projections:diff --git a/backend/app/services/rule_service.py b/backend/app/services/rule_service.pyindex a445851c..21ba9aae 100644--- a/backend/app/services/rule_service.py+++ b/backend/app/services/rule_service.py@@ -521,14 +521,27 @@ async def _get_existing_rule_names(session: AsyncSession, user_id: uuid.UUID) ->return {row[0] for row in result.all()}-async def create_default_rules(session: AsyncSession, user_id: uuid.UUID, lang: str = "pt-BR") -> list[Rule]:+async def create_default_rules(+ session: AsyncSession,+ user_id: uuid.UUID,+ lang: str = "pt-BR",+ workspace_id: Optional[uuid.UUID] = None,+) -> list[Rule]:"""Create universal default categorization rules for a new user.`lang` is accepted for backwards compatibility but no longer affectscategory resolution — categories are matched by internal key across alllanguage variants."""- result = await session.execute(select(Category).where(Category.user_id == user_id))+ # Scope category resolution to the target workspace so rules in a+ # newly-created workspace point at THAT workspace's categories+ # rather than the user's first workspace.+ cat_query = select(Category)+ if workspace_id is not None:+ cat_query = cat_query.where(Category.workspace_id == workspace_id)+ else:+ cat_query = cat_query.where(Category.user_id == user_id)+ result = await session.execute(cat_query)categories = {cat.name: str(cat.id) for cat in result.scalars().all()}key_to_id = _resolve_categories_by_internal_key(categories)@@ -538,6 +551,7 @@ async def create_default_rules(session: AsyncSession, user_id: uuid.UUID, lang:for rule_data in resolved:rule = Rule(user_id=user_id,+ workspace_id=workspace_id,name=rule_data["name"],conditions_op=rule_data["conditions_op"],conditions=rule_data["conditions"],@@ -734,29 +748,35 @@ async def get_installed_packs(session: AsyncSession, user_id: uuid.UUID) -> dictreturn result-async def get_rules(session: AsyncSession, user_id: uuid.UUID) -> list[Rule]:+async def get_rules(session: AsyncSession, workspace_id: uuid.UUID) -> list[Rule]:result = await session.execute(select(Rule)- .where(Rule.user_id == user_id)+ .where(Rule.workspace_id == workspace_id).order_by(Rule.priority, Rule.id))return list(result.scalars().all())-async def get_rule(session: AsyncSession, rule_id: uuid.UUID, user_id: uuid.UUID) -> Optional[Rule]:+async def get_rule(session: AsyncSession, rule_id: uuid.UUID, workspace_id: uuid.UUID) -> Optional[Rule]:result = await session.execute(- select(Rule).where(Rule.id == rule_id, Rule.user_id == user_id)+ select(Rule).where(Rule.id == rule_id, Rule.workspace_id == workspace_id))return result.scalar_one_or_none()-async def create_rule(session: AsyncSession, user_id: uuid.UUID, data: RuleCreate) -> Rule:- existing_names = await _get_existing_rule_names(session, user_id)+async def create_rule(+ session: AsyncSession,+ workspace_id: uuid.UUID,+ user_id: uuid.UUID,+ data: RuleCreate,+) -> Rule:+ existing_names = await _get_existing_rule_names_for_workspace(session, workspace_id)if data.name in existing_names:raise DuplicateRuleError(f"A rule named '{data.name}' already exists")rule = Rule(user_id=user_id,+ workspace_id=workspace_id,name=data.name,conditions_op=data.conditions_op,conditions=[c.model_dump() for c in data.conditions],@@ -771,16 +791,16 @@ async def create_rule(session: AsyncSession, user_id: uuid.UUID, data: RuleCreatasync def update_rule(- session: AsyncSession, rule_id: uuid.UUID, user_id: uuid.UUID, data: RuleUpdate+ session: AsyncSession, rule_id: uuid.UUID, workspace_id: uuid.UUID, data: RuleUpdate) -> Optional[Rule]:- rule = await get_rule(session, rule_id, user_id)+ rule = await get_rule(session, rule_id, workspace_id)if not rule:return Noneupdate_data = data.model_dump(exclude_unset=True)if "name" in update_data and update_data["name"] != rule.name:- existing_names = await _get_existing_rule_names(session, user_id)+ existing_names = await _get_existing_rule_names_for_workspace(session, workspace_id)if update_data["name"] in existing_names:raise DuplicateRuleError(f"A rule named '{update_data['name']}' already exists")@@ -797,8 +817,8 @@ async def update_rule(return rule-async def delete_rule(session: AsyncSession, rule_id: uuid.UUID, user_id: uuid.UUID) -> bool:- rule = await get_rule(session, rule_id, user_id)+async def delete_rule(session: AsyncSession, rule_id: uuid.UUID, workspace_id: uuid.UUID) -> bool:+ rule = await get_rule(session, rule_id, workspace_id)if not rule:return Falseawait session.delete(rule)@@ -806,14 +826,33 @@ async def delete_rule(session: AsyncSession, rule_id: uuid.UUID, user_id: uuid.Ureturn True+async def _get_existing_rule_names_for_workspace(+ session: AsyncSession, workspace_id: uuid.UUID+) -> set[str]:+ """Get the set of existing rule names in a workspace."""+ result = await session.execute(+ select(Rule.name).where(Rule.workspace_id == workspace_id)+ )+ return {row[0] for row in result.all()}++async def apply_rules_to_transaction(session: AsyncSession, user_id: uuid.UUID, transaction: Transaction,skip_category_rules: bool = False,) -> None:- """Apply all active rules to a transaction, modifying it in-place. Commits nothing."""+ """Apply all active rules to a transaction, modifying it in-place. Commits nothing.++ `user_id` is kept for backwards-compatibility with sync/import callers that+ haven't been migrated to pass workspace_id directly; rules are scoped by+ workspace via the transaction's own workspace_id when available, falling+ back to the legacy user filter so historical rows still match.+ """+ rule_filter = Rule.user_id == user_id+ if getattr(transaction, "workspace_id", None) is not None:+ rule_filter = Rule.workspace_id == transaction.workspace_idresult = await session.execute(select(Rule)- .where(Rule.user_id == user_id, Rule.is_active == True)+ .where(rule_filter, Rule.is_active == True).order_by(Rule.priority, Rule.id))rules = result.scalars().all()@@ -827,9 +866,8 @@ async def apply_rules_to_transaction(category_set = apply_rule_actions(actions, transaction, category_set)-async def apply_all_rules(session: AsyncSession, user_id: uuid.UUID) -> int:- """Re-apply all active rules to all user transactions. Returns count of affected transactions."""- from sqlalchemy import or_+async def apply_all_rules(session: AsyncSession, workspace_id: uuid.UUID) -> int:+ """Re-apply all active rules to all workspace transactions. Returns count of affected transactions."""from app.models.account import Accountfrom app.models.bank_connection import BankConnection@@ -838,10 +876,7 @@ async def apply_all_rules(session: AsyncSession, user_id: uuid.UUID) -> int:.outerjoin(Account).outerjoin(BankConnection).where(- or_(- Transaction.user_id == user_id,- BankConnection.user_id == user_id,- ),+ Transaction.workspace_id == workspace_id,Transaction.source != "opening_balance",))@@ -849,7 +884,7 @@ async def apply_all_rules(session: AsyncSession, user_id: uuid.UUID) -> int:rules_result = await session.execute(select(Rule)- .where(Rule.user_id == user_id, Rule.is_active == True)+ .where(Rule.workspace_id == workspace_id, Rule.is_active == True).order_by(Rule.priority, Rule.id))rules = rules_result.scalars().all()diff --git a/backend/app/services/search_service.py b/backend/app/services/search_service.pyindex 86d6df92..82954230 100644--- a/backend/app/services/search_service.py+++ b/backend/app/services/search_service.py@@ -71,15 +71,21 @@ def _like(term: str) -> str:async def search_all(session: AsyncSession,+ workspace_id: uuid.UUID,user_id: uuid.UUID,query: str,per_type_limit: int = 5,) -> list[dict[str, Any]]:- """Search across all entity types for the given user.+ """Search across all entity types in the current workspace.Returns a flat list of hits ordered by entity type, newest first withineach group. Matching is case-insensitive ILIKE on the most useful stringcolumns per model.++ Transaction search additionally pulls in cross-workspace rows the+ caller participates in via group splits (the Splitwise projection+ — "concert" finds the parent that someone else paid for but is on+ the caller's settlement ledger)."""term = (query or "").strip()if len(term) < 1:@@ -89,14 +95,12 @@ async def search_all(hits: list[SearchHit] = []# -- Transactions -------------------------------------------------------- # Search returns the user's own transactions PLUS transactions- # they participate in via group splits — so "concert" finds the- # parent that someone else paid for but is on the user's ledger.from app.models.group import GroupMemberfrom app.models.transaction_split import TransactionSplitviewer_member_ids = select(GroupMember.id).where(- GroupMember.linked_user_id == user_id+ GroupMember.linked_user_id == user_id,+ GroupMember.is_self.is_(False),)shared_tx_ids = (select(TransactionSplit.transaction_id)@@ -107,7 +111,7 @@ async def search_all(select(Transaction).where(or_(- Transaction.user_id == user_id,+ Transaction.workspace_id == workspace_id,Transaction.id.in_(shared_tx_ids),),or_(@@ -141,7 +145,7 @@ async def search_all(acc_result = await session.execute(select(Account).where(- Account.user_id == user_id,+ Account.workspace_id == workspace_id,Account.name.ilike(pattern, escape="\\"),).order_by(Account.is_closed.asc(), Account.name.asc())@@ -164,7 +168,7 @@ async def search_all(payee_result = await session.execute(select(Payee).where(- Payee.user_id == user_id,+ Payee.workspace_id == workspace_id,or_(Payee.name.ilike(pattern, escape="\\"),Payee.notes.ilike(pattern, escape="\\"),@@ -188,7 +192,7 @@ async def search_all(cat_result = await session.execute(select(Category).where(- Category.user_id == user_id,+ Category.workspace_id == workspace_id,Category.name.ilike(pattern, escape="\\"),).order_by(Category.name.asc())@@ -209,7 +213,7 @@ async def search_all(goal_result = await session.execute(select(Goal).where(- Goal.user_id == user_id,+ Goal.workspace_id == workspace_id,Goal.name.ilike(pattern, escape="\\"),).order_by(Goal.position.asc(), Goal.name.asc())@@ -233,7 +237,7 @@ async def search_all(asset_result = await session.execute(select(Asset).where(- Asset.user_id == user_id,+ Asset.workspace_id == workspace_id,Asset.name.ilike(pattern, escape="\\"),).order_by(Asset.is_archived.asc(), Asset.position.asc(), Asset.name.asc())diff --git a/backend/app/services/settlement_service.py b/backend/app/services/settlement_service.pyindex 96e8ed81..114aa742 100644--- a/backend/app/services/settlement_service.py+++ b/backend/app/services/settlement_service.py@@ -2,11 +2,10 @@ import uuidfrom datetime import datetime, timezonefrom typing import Optional-from sqlalchemy import or_, select+from sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom app.models.account import Account-from app.models.bank_connection import BankConnectionfrom app.models.group import Group, GroupMemberfrom app.models.group_settlement import GroupSettlementfrom app.models.transaction import Transaction@@ -16,23 +15,17 @@ from app.schemas.group_settlement import ()-async def _ensure_group_owned(- session: AsyncSession, group_id: uuid.UUID, user_id: uuid.UUID-) -> Optional[Group]:- """Owner-only access — used when only the owner may proceed."""- result = await session.execute(- select(Group).where(Group.id == group_id, Group.user_id == user_id)- )- return result.scalar_one_or_none()--async def _ensure_group_visible(- session: AsyncSession, group_id: uuid.UUID, user_id: uuid.UUID+ session: AsyncSession,+ group_id: uuid.UUID,+ workspace_id: uuid.UUID,+ user_id: uuid.UUID,) -> Optional[Group]:- """Visible to the owner OR any linked member — for read endpoints."""+ """Visible when the group lives in the current workspace OR the+ caller is linked as a cross-workspace member — for read endpoints."""from app.services.group_service import get_group_visible- return await get_group_visible(session, group_id, user_id)+ return await get_group_visible(session, group_id, workspace_id, user_id)async def _user_member_id(@@ -69,6 +62,7 @@ async def _can_settle_from(async def _create_payment_transaction(session: AsyncSession,user_id: uuid.UUID,+ workspace_id: uuid.UUID,account_id: uuid.UUID,amount,currency: str,@@ -76,13 +70,12 @@ async def _create_payment_transaction(description: str,) -> Transaction:"""Create a debit transaction on the user's account representing a- settlement payment. Validates account ownership."""+ settlement payment. Validates that the account belongs to the+ current workspace."""account_result = await session.execute(- select(Account)- .outerjoin(BankConnection)- .where(+ select(Account).where(Account.id == account_id,- or_(Account.user_id == user_id, BankConnection.user_id == user_id),+ Account.workspace_id == workspace_id,))account = account_result.scalar_one_or_none()@@ -92,6 +85,7 @@ async def _create_payment_transaction(tx = Transaction(id=uuid.uuid4(),user_id=user_id,+ workspace_id=workspace_id,account_id=account.id,description=description,amount=amount,@@ -118,13 +112,21 @@ async def _create_payment_transaction(async def _pick_default_account_for_user(session: AsyncSession, user_id: uuid.UUID) -> Optional[Account]:- """Return the user's first non-archived checking/savings account.- Used as the auto-target for receiver-side settlement credits."""+ """Return the user's first non-archived checking/savings account+ across any workspace they belong to. Used as the auto-target for+ receiver-side settlement credits — the receiver may sit in a+ different workspace than where the settlement was recorded."""+ from app.models.workspace import WorkspaceMember++ # Resolve the workspaces the user can write to. Pick the first+ # account that lives in any of them; ties broken by name.+ user_workspaces_subq = select(WorkspaceMember.workspace_id).where(+ WorkspaceMember.user_id == user_id+ )result = await session.execute(select(Account)- .outerjoin(BankConnection).where(- or_(Account.user_id == user_id, BankConnection.user_id == user_id),+ Account.workspace_id.in_(user_workspaces_subq),Account.is_closed.is_(False),Account.type.in_(("checking", "savings")),)@@ -143,7 +145,8 @@ async def _create_receiver_credit() -> Optional[Transaction]:"""Mirror a settlement credit on the receiver's side.- Picks the receiver's first checking/savings account. Returns None+ Picks the receiver's first checking/savings account from any+ workspace they belong to and stamps the credit there. Returns Nonesilently when the receiver has no suitable account — they can doit manually or the next time they reconcile from their bank sync."""@@ -153,6 +156,7 @@ async def _create_receiver_credit(tx = Transaction(id=uuid.uuid4(),user_id=receiver_user_id,+ workspace_id=account.workspace_id,account_id=account.id,description=description,amount=amount,@@ -188,20 +192,14 @@ async def _validate_members_in_group(async def _validate_transaction(session: AsyncSession,transaction_id: Optional[uuid.UUID],- user_id: uuid.UUID,+ workspace_id: uuid.UUID,) -> None:if transaction_id is None:returnresult = await session.execute(- select(Transaction)- .outerjoin(Account)- .outerjoin(BankConnection)- .where(+ select(Transaction).where(Transaction.id == transaction_id,- or_(- Transaction.user_id == user_id,- BankConnection.user_id == user_id,- ),+ Transaction.workspace_id == workspace_id,))if result.scalar_one_or_none() is None:@@ -209,9 +207,12 @@ async def _validate_transaction(async def list_settlements(- session: AsyncSession, group_id: uuid.UUID, user_id: uuid.UUID+ session: AsyncSession,+ group_id: uuid.UUID,+ workspace_id: uuid.UUID,+ user_id: uuid.UUID,) -> Optional[list[GroupSettlement]]:- if not await _ensure_group_visible(session, group_id, user_id):+ if not await _ensure_group_visible(session, group_id, workspace_id, user_id):return Noneresult = await session.execute(select(GroupSettlement)@@ -224,10 +225,11 @@ async def list_settlements(async def create_settlement(session: AsyncSession,group_id: uuid.UUID,+ workspace_id: uuid.UUID,user_id: uuid.UUID,data: GroupSettlementCreate,) -> Optional[GroupSettlement]:- group = await _ensure_group_visible(session, group_id, user_id)+ group = await _ensure_group_visible(session, group_id, workspace_id, user_id)if not group:return None@@ -240,7 +242,7 @@ async def create_settlement(await _validate_members_in_group(session, group_id, [data.from_member_id, data.to_member_id])- await _validate_transaction(session, data.transaction_id, user_id)+ await _validate_transaction(session, data.transaction_id, workspace_id)payload = data.model_dump()account_id = payload.pop("account_id", None)@@ -281,6 +283,7 @@ async def create_settlement(tx = await _create_payment_transaction(session,user_id,+ workspace_id,account_id,data.amount,data.currency,@@ -307,7 +310,9 @@ async def create_settlement(receiver_tx_id = receiver_tx.idpayload["receiver_transaction_id"] = receiver_tx_id- settlement = GroupSettlement(group_id=group_id, **payload)+ settlement = GroupSettlement(+ group_id=group_id, workspace_id=workspace_id, **payload+ )session.add(settlement)await session.commit()await session.refresh(settlement)@@ -318,10 +323,11 @@ async def update_settlement(session: AsyncSession,group_id: uuid.UUID,settlement_id: uuid.UUID,+ workspace_id: uuid.UUID,user_id: uuid.UUID,data: GroupSettlementUpdate,) -> Optional[GroupSettlement]:- group = await _ensure_group_visible(session, group_id, user_id)+ group = await _ensure_group_visible(session, group_id, workspace_id, user_id)if not group:return None@@ -356,7 +362,7 @@ async def update_settlement(await _validate_members_in_group(session, group_id, member_check)if "transaction_id" in update_data:- await _validate_transaction(session, update_data["transaction_id"], user_id)+ await _validate_transaction(session, update_data["transaction_id"], workspace_id)for key, value in update_data.items():setattr(settlement, key, value)@@ -370,9 +376,10 @@ async def delete_settlement(session: AsyncSession,group_id: uuid.UUID,settlement_id: uuid.UUID,+ workspace_id: uuid.UUID,user_id: uuid.UUID,) -> bool:- group = await _ensure_group_visible(session, group_id, user_id)+ group = await _ensure_group_visible(session, group_id, workspace_id, user_id)if not group:return Falseresult = await session.execute(diff --git a/backend/app/services/transaction_service.py b/backend/app/services/transaction_service.pyindex ce179249..20bb5203 100644--- a/backend/app/services/transaction_service.py+++ b/backend/app/services/transaction_service.py@@ -51,6 +51,7 @@ def _apply_fx_override(transaction, amount, amount_primary=None, fx_rate_used=Noasync def get_transactions(session: AsyncSession,+ workspace_id: uuid.UUID,user_id: uuid.UUID,account_id: Optional[uuid.UUID] = None,category_id: Optional[uuid.UUID] = None,@@ -81,6 +82,12 @@ async def get_transactions(account_types: Optional[list[str]] = None,include_summary: bool = False,) -> tuple[list[Transaction], int, Optional[dict]]:+ """List transactions for a workspace.++ `workspace_id` scopes the tenant (which transactions are visible). `user_id`+ is the *viewer* — used for Splitwise projection (linked-member visibility,+ is-shared tagging) which is identity-based, not tenancy-based.+ """# In "accrual" mode, bucket/order by effective_date so list filters# line up with the cash-flow view used by the dashboard and reports.# When the user has set a manual cycle override (effective_bill_date)@@ -99,7 +106,7 @@ async def get_transactions(if group_id is not None:from app.services.group_service import get_group_visible- accessible = await get_group_visible(session, group_id, user_id)+ accessible = await get_group_visible(session, group_id, workspace_id, user_id)if accessible is None:return [], 0use_group_scope = True@@ -147,27 +154,39 @@ async def get_transactions()base_query = base_query.where(Transaction.id.in_(tx_ids_subq))else:- # Default scope: own transactions PLUS transactions shared- # with the user via group splits. Shared rows surface in the- # viewer's ledger so their `Concert Tickets · share $90` shows- # up alongside their own expenses; account-balance integrity- # is preserved because the transaction's account_id still- # belongs to the original owner.+ # Default scope: transactions in this workspace PLUS cross-workspace+ # shares the viewer participates in. The union surfaces the+ # viewer's "Concert Tickets · share $90" from another workspace+ # alongside their own expenses; account-balance integrity is+ # preserved because the parent tx's account still belongs to the+ # original owner. The shared-id subquery EXCLUDES rows already+ # in this workspace — otherwise self-membership in an+ # in-workspace group double-surfaces the owner's own+ # transactions when they switch to another workspace.from app.models.group import GroupMemberfrom app.models.transaction_split import TransactionSplit+ # Exclude is_self memberships — those represent the viewer's+ # OWN self-member in groups they created, not invitations from+ # someone else's workspace. Without this exclusion, the owner's+ # own transactions get double-projected when they switch into+ # a different workspace.viewer_member_ids = select(GroupMember.id).where(- GroupMember.linked_user_id == user_id+ GroupMember.linked_user_id == user_id,+ GroupMember.is_self.is_(False),)shared_tx_ids = (select(TransactionSplit.transaction_id)- .where(TransactionSplit.group_member_id.in_(viewer_member_ids))+ .join(Transaction, Transaction.id == TransactionSplit.transaction_id)+ .where(+ TransactionSplit.group_member_id.in_(viewer_member_ids),+ Transaction.workspace_id != workspace_id,+ ).distinct())base_query = base_query.where(or_(- Transaction.user_id == user_id,- BankConnection.user_id == user_id,+ Transaction.workspace_id == workspace_id,Transaction.id.in_(shared_tx_ids),))@@ -463,7 +482,8 @@ async def _tag_shared_view(member_rows = await session.execute(select(GroupMember.id, GroupMember.group_id).where(- GroupMember.linked_user_id == user_id+ GroupMember.linked_user_id == user_id,+ GroupMember.is_self.is_(False),))member_to_group = {row.id: row.group_id for row in member_rows}@@ -564,18 +584,16 @@ async def _tag_shared_view(async def get_transaction(- session: AsyncSession, transaction_id: uuid.UUID, user_id: uuid.UUID+ session: AsyncSession,+ transaction_id: uuid.UUID,+ workspace_id: uuid.UUID,) -> Optional[Transaction]:+ """Fetch a single transaction by id, scoped to the workspace."""result = await session.execute(select(Transaction)- .outerjoin(Account)- .outerjoin(BankConnection).where(Transaction.id == transaction_id,- or_(- Transaction.user_id == user_id,- BankConnection.user_id == user_id,- ),+ Transaction.workspace_id == workspace_id,).options(selectinload(Transaction.category),@@ -596,17 +614,20 @@ async def get_transaction(async def create_transaction(- session: AsyncSession, user_id: uuid.UUID, data: TransactionCreate+ session: AsyncSession,+ workspace_id: uuid.UUID,+ user_id: uuid.UUID,+ data: TransactionCreate,) -> Transaction:- # Verify account belongs to user+ # Verify account belongs to the workspaceaccount_result = await session.execute(select(Account).outerjoin(BankConnection).where(Account.id == data.account_id,or_(- Account.user_id == user_id,- BankConnection.user_id == user_id,+ Account.workspace_id == workspace_id,+ BankConnection.workspace_id == workspace_id,),))@@ -619,6 +640,7 @@ async def create_transaction(transaction = Transaction(user_id=user_id,+ workspace_id=workspace_id,account_id=data.account_id,category_id=data.category_id, # use provided category if givenpayee_id=data.payee_id,@@ -653,18 +675,24 @@ async def create_transaction(async def create_transfer(- session: AsyncSession, user_id: uuid.UUID, data: TransferCreate+ session: AsyncSession,+ workspace_id: uuid.UUID,+ user_id: uuid.UUID,+ data: TransferCreate,) -> tuple[Transaction, Transaction]:if data.from_account_id == data.to_account_id:raise ValueError("Cannot transfer to the same account")- # Verify both accounts belong to user+ # Verify both accounts belong to the workspacefrom_result = await session.execute(select(Account).outerjoin(BankConnection).where(Account.id == data.from_account_id,- or_(Account.user_id == user_id, BankConnection.user_id == user_id),+ or_(+ Account.workspace_id == workspace_id,+ BankConnection.workspace_id == workspace_id,+ ),))from_account = from_result.scalar_one_or_none()@@ -676,7 +704,10 @@ async def create_transfer(.outerjoin(BankConnection).where(Account.id == data.to_account_id,- or_(Account.user_id == user_id, BankConnection.user_id == user_id),+ or_(+ Account.workspace_id == workspace_id,+ BankConnection.workspace_id == workspace_id,+ ),))to_account = to_result.scalar_one_or_none()@@ -689,6 +720,7 @@ async def create_transfer(# Debit transaction (from account)debit_tx = Transaction(user_id=user_id,+ workspace_id=workspace_id,account_id=data.from_account_id,description=data.description,amount=data.amount,@@ -719,6 +751,7 @@ async def create_transfer(credit_tx = Transaction(user_id=user_id,+ workspace_id=workspace_id,account_id=data.to_account_id,description=data.description,amount=credit_amount,@@ -751,7 +784,7 @@ async def create_transfer(async def get_transfer_candidates(session: AsyncSession,- user_id: uuid.UUID,+ workspace_id: uuid.UUID,transaction_id: uuid.UUID,limit: int = 10,window_days: int = 30,@@ -765,7 +798,7 @@ async def get_transfer_candidates(from datetime import timedeltafrom decimal import Decimal- anchor = await get_transaction(session, transaction_id, user_id)+ anchor = await get_transaction(session, transaction_id, workspace_id)if not anchor:return []if anchor.transfer_pair_id is not None:@@ -777,13 +810,8 @@ async def get_transfer_candidates(result = await session.execute(select(Transaction)- .outerjoin(Account)- .outerjoin(BankConnection).where(- or_(- Transaction.user_id == user_id,- BankConnection.user_id == user_id,- ),+ Transaction.workspace_id == workspace_id,Transaction.id != anchor.id,Transaction.account_id != anchor.account_id,Transaction.type == opposing_type,@@ -842,13 +870,15 @@ async def get_transfer_candidates(async def link_existing_as_transfer(- session: AsyncSession, user_id: uuid.UUID, transaction_ids: list[uuid.UUID]+ session: AsyncSession,+ workspace_id: uuid.UUID,+ transaction_ids: list[uuid.UUID],) -> tuple[Transaction, Transaction]:"""Link two existing transactions as a transfer pair.Permissive by design: amounts don't have to match. Validation enforces- ownership, opposing types, different accounts, and that neither side is- already part of an existing transfer.+ workspace ownership, opposing types, different accounts, and that+ neither side is already part of an existing transfer."""if len(transaction_ids) != 2:raise ValueError("Exactly two transactions are required")@@ -857,14 +887,9 @@ async def link_existing_as_transfer(result = await session.execute(select(Transaction)- .outerjoin(Account)- .outerjoin(BankConnection).where(Transaction.id.in_(transaction_ids),- or_(- Transaction.user_id == user_id,- BankConnection.user_id == user_id,- ),+ Transaction.workspace_id == workspace_id,))txns = list(result.scalars().all())@@ -898,6 +923,7 @@ async def link_existing_as_transfer(async def create_transfer_counterpart(session: AsyncSession,+ workspace_id: uuid.UUID,user_id: uuid.UUID,transaction_id: uuid.UUID,to_account_id: uuid.UUID,@@ -912,7 +938,7 @@ async def create_transfer_counterpart("""from decimal import Decimal- anchor = await get_transaction(session, transaction_id, user_id)+ anchor = await get_transaction(session, transaction_id, workspace_id)if not anchor:raise ValueError("Transaction not found")if anchor.transfer_pair_id is not None:@@ -925,7 +951,10 @@ async def create_transfer_counterpart(.outerjoin(BankConnection).where(Account.id == to_account_id,- or_(Account.user_id == user_id, BankConnection.user_id == user_id),+ or_(+ Account.workspace_id == workspace_id,+ BankConnection.workspace_id == workspace_id,+ ),))to_account = to_result.scalar_one_or_none()@@ -946,6 +975,7 @@ async def create_transfer_counterpart(counterpart_tx = Transaction(user_id=user_id,+ workspace_id=workspace_id,account_id=to_account_id,description=anchor.description,amount=counterpart_amount,@@ -1029,9 +1059,13 @@ async def _resync_bill_link_from_override(async def update_transaction(- session: AsyncSession, transaction_id: uuid.UUID, user_id: uuid.UUID, data: TransactionUpdate+ session: AsyncSession,+ transaction_id: uuid.UUID,+ workspace_id: uuid.UUID,+ user_id: uuid.UUID,+ data: TransactionUpdate,) -> Optional[Transaction]:- transaction = await get_transaction(session, transaction_id, user_id)+ transaction = await get_transaction(session, transaction_id, workspace_id)if not transaction:return None@@ -1043,10 +1077,10 @@ async def update_transaction(splits_payload = data.splits if "splits" in update_data else Noneupdate_data.pop("splits", None)- # Verify the new account belongs to the user before touching the row.- # When changing the account on one side of a transfer pair, refuse to- # collide with the paired transaction's account (a transfer must have two- # distinct accounts).+ # Verify the new account belongs to the workspace before touching the+ # row. When changing the account on one side of a transfer pair,+ # refuse to collide with the paired transaction's account (a transfer+ # must have two distinct accounts).new_account_id = update_data.get("account_id")if new_account_id is not None and new_account_id != transaction.account_id:account_result = await session.execute(@@ -1055,8 +1089,8 @@ async def update_transaction(.where(Account.id == new_account_id,or_(- Account.user_id == user_id,- BankConnection.user_id == user_id,+ Account.workspace_id == workspace_id,+ BankConnection.workspace_id == workspace_id,),))@@ -1145,7 +1179,7 @@ async def update_transaction(async def bulk_update_category(session: AsyncSession,- user_id: uuid.UUID,+ workspace_id: uuid.UUID,transaction_ids: list[uuid.UUID],category_id: Optional[uuid.UUID] = None,) -> int:@@ -1153,7 +1187,7 @@ async def bulk_update_category(update(Transaction).where(Transaction.id.in_(transaction_ids),- Transaction.user_id == user_id,+ Transaction.workspace_id == workspace_id,).values(category_id=category_id))@@ -1177,7 +1211,7 @@ def _parse_hashtags(notes: Optional[str]) -> list[str]:async def bulk_add_tags(session: AsyncSession,- user_id: uuid.UUID,+ workspace_id: uuid.UUID,transaction_ids: list[uuid.UUID],tags: list[str],) -> int:@@ -1193,7 +1227,7 @@ async def bulk_add_tags(result = await session.execute(select(Transaction).where(Transaction.id.in_(transaction_ids),- Transaction.user_id == user_id,+ Transaction.workspace_id == workspace_id,))touched = 0@@ -1212,7 +1246,7 @@ async def bulk_add_tags(async def bulk_remove_tags(session: AsyncSession,- user_id: uuid.UUID,+ workspace_id: uuid.UUID,transaction_ids: list[uuid.UUID],tags: list[str],) -> int:@@ -1226,7 +1260,7 @@ async def bulk_remove_tags(result = await session.execute(select(Transaction).where(Transaction.id.in_(transaction_ids),- Transaction.user_id == user_id,+ Transaction.workspace_id == workspace_id,))touched = 0@@ -1254,6 +1288,7 @@ async def bulk_remove_tags(async def bulk_add_to_group(session: AsyncSession,+ workspace_id: uuid.UUID,user_id: uuid.UUID,transaction_ids: list[uuid.UUID],group_id: uuid.UUID,@@ -1323,7 +1358,7 @@ async def bulk_add_to_group(select(Transaction).where(Transaction.id.in_(transaction_ids),- Transaction.user_id == user_id,+ Transaction.workspace_id == workspace_id,).options(selectinload(Transaction.splits)))@@ -1346,13 +1381,15 @@ async def bulk_add_to_group(async def toggle_ignore_transaction(- session: AsyncSession, transaction_id: uuid.UUID, user_id: uuid.UUID+ session: AsyncSession,+ transaction_id: uuid.UUID,+ workspace_id: uuid.UUID,) -> Optional[Transaction]:"""Flip the is_ignored flag on a transaction. Acts immediately (noother field is touched) so the edit dialog can offer ignore as aone-click action alongside delete, instead of bundling it into theform's Salvar flow."""- transaction = await get_transaction(session, transaction_id, user_id)+ transaction = await get_transaction(session, transaction_id, workspace_id)if not transaction:return Nonetransaction.is_ignored = not transaction.is_ignored@@ -1362,9 +1399,11 @@ async def toggle_ignore_transaction(async def delete_transaction(- session: AsyncSession, transaction_id: uuid.UUID, user_id: uuid.UUID+ session: AsyncSession,+ transaction_id: uuid.UUID,+ workspace_id: uuid.UUID,) -> bool:- transaction = await get_transaction(session, transaction_id, user_id)+ transaction = await get_transaction(session, transaction_id, workspace_id)if not transaction:return Falsediff --git a/backend/app/services/transfer_detection_service.py b/backend/app/services/transfer_detection_service.pyindex 190cf53e..4d55db27 100644--- a/backend/app/services/transfer_detection_service.py+++ b/backend/app/services/transfer_detection_service.py@@ -10,7 +10,7 @@ from app.models.transaction import Transactionasync def detect_transfer_pairs(session: AsyncSession,- user_id: uuid.UUID,+ workspace_id: uuid.UUID,candidate_ids: Optional[list[uuid.UUID]] = None,date_tolerance_days: int = 2,) -> int:@@ -27,7 +27,7 @@ async def detect_transfer_pairs("""# Load candidate debits — filtered to candidate_ids when provideddebit_query = select(Transaction).where(- Transaction.user_id == user_id,+ Transaction.workspace_id == workspace_id,Transaction.type == "debit",Transaction.transfer_pair_id.is_(None),Transaction.source != "opening_balance",@@ -42,7 +42,7 @@ async def detect_transfer_pairs(# match new credits (the reverse direction).if candidate_ids:reverse_debit_query = select(Transaction).where(- Transaction.user_id == user_id,+ Transaction.workspace_id == workspace_id,Transaction.type == "debit",Transaction.transfer_pair_id.is_(None),Transaction.source != "opening_balance",@@ -60,7 +60,7 @@ async def detect_transfer_pairs(# Load all unpaired credits for the user (potential partners)credit_query = select(Transaction).where(- Transaction.user_id == user_id,+ Transaction.workspace_id == workspace_id,Transaction.type == "credit",Transaction.transfer_pair_id.is_(None),Transaction.source != "opening_balance",@@ -124,13 +124,13 @@ async def detect_transfer_pairs(async def unlink_transfer_pair(session: AsyncSession,- user_id: uuid.UUID,+ workspace_id: uuid.UUID,pair_id: uuid.UUID,) -> int:"""Remove a transfer pair link. Returns number of transactions unlinked."""result = await session.execute(select(Transaction).where(- Transaction.user_id == user_id,+ Transaction.workspace_id == workspace_id,Transaction.transfer_pair_id == pair_id,))diff --git a/backend/app/services/workspace_service.py b/backend/app/services/workspace_service.pynew file mode 100644index 00000000..871afb76--- /dev/null+++ b/backend/app/services/workspace_service.py@@ -0,0 +1,426 @@+"""Workspace lifecycle + membership helpers.++The Workspace entity sits between User and every financial entity. A+user always belongs to at least one workspace — their auto-created+Personal workspace from registration. Additional workspaces (Freelancer,+Small Business, etc.) can be created later via templates.+"""+import uuid+from typing import Optional++from fastapi import HTTPException+from sqlalchemy import func, select+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.user import User+from app.models.workspace import (+ MANAGER_VIRTUAL_ROLE,+ Workspace,+ WorkspaceMember,+ WORKSPACE_ROLES,+)+++def _resolve_personal_name(lang: Optional[str]) -> str:+ """Localized default name for the auto-created Personal workspace."""+ if lang and lang.lower().startswith("pt"):+ return "Pessoal"+ return "Personal"+++async def create_personal_workspace_for_user(+ session: AsyncSession,+ user: User,+ *,+ commit: bool = False,+) -> Workspace:+ """Create the user's auto-default Personal workspace + owner membership.++ Idempotent: if the user already owns a personal workspace (e.g. the+ migration ran), returns the existing one.++ Caller is responsible for committing unless `commit=True`. Defaults+ to flush-only because callers often want to bundle this with the+ user-create transaction.+ """+ existing = await session.execute(+ select(Workspace)+ .join(WorkspaceMember, WorkspaceMember.workspace_id == Workspace.id)+ .where(+ WorkspaceMember.user_id == user.id,+ Workspace.kind == "personal",+ Workspace.created_by_user_id == user.id,+ )+ .limit(1)+ )+ found = existing.scalar_one_or_none()+ if found:+ return found++ prefs = user.preferences or {}+ lang = prefs.get("language")+ workspace = Workspace(+ name=_resolve_personal_name(lang),+ kind="personal",+ created_by_user_id=user.id,+ default_currency=prefs.get("currency_display", "USD"),+ locale=lang,+ )+ session.add(workspace)+ await session.flush()++ membership = WorkspaceMember(+ workspace_id=workspace.id,+ user_id=user.id,+ role="owner",+ )+ session.add(membership)+ await session.flush()+ if commit:+ await session.commit()+ return workspace+++async def get_user_workspaces(session: AsyncSession, user_id: uuid.UUID) -> list[Workspace]:+ """Return every workspace the user is a member of, oldest first.++ Does NOT include workspaces the user only manages externally — those+ are listed separately by `get_managed_workspaces`. The listing+ endpoint unions the two so the frontend sees a single sorted set.+ """+ result = await session.execute(+ select(Workspace)+ .join(WorkspaceMember, WorkspaceMember.workspace_id == Workspace.id)+ .where(+ WorkspaceMember.user_id == user_id,+ Workspace.is_archived.is_(False),+ )+ .order_by(Workspace.created_at.asc())+ )+ return list(result.scalars().all())+++async def get_managed_workspaces(session: AsyncSession, user_id: uuid.UUID) -> list[Workspace]:+ """Return every workspace the user externally administers."""+ result = await session.execute(+ select(Workspace)+ .where(+ Workspace.managed_by_user_id == user_id,+ Workspace.is_archived.is_(False),+ )+ .order_by(Workspace.created_at.asc())+ )+ return list(result.scalars().all())+++async def is_workspace_manager(+ session: AsyncSession,+ workspace_id: uuid.UUID,+ user_id: uuid.UUID,+) -> bool:+ """True if `user_id` administers this workspace from outside membership."""+ result = await session.execute(+ select(Workspace.id).where(+ Workspace.id == workspace_id,+ Workspace.managed_by_user_id == user_id,+ )+ )+ return result.scalar_one_or_none() is not None+++async def get_default_workspace(session: AsyncSession, user_id: uuid.UUID) -> Optional[Workspace]:+ """The user's first (oldest) workspace — used when no X-Workspace-Id header is set.++ Falls back to a managed workspace if the user has no memberships+ (e.g. a manager who hasn't been invited to any of the workspaces+ they administer).+ """+ workspaces = await get_user_workspaces(session, user_id)+ if workspaces:+ return workspaces[0]+ managed = await get_managed_workspaces(session, user_id)+ return managed[0] if managed else None+++async def get_membership(+ session: AsyncSession,+ workspace_id: uuid.UUID,+ user_id: uuid.UUID,+) -> Optional[WorkspaceMember]:+ """Return the user's membership row for a workspace, or None."""+ result = await session.execute(+ select(WorkspaceMember).where(+ WorkspaceMember.workspace_id == workspace_id,+ WorkspaceMember.user_id == user_id,+ )+ )+ return result.scalar_one_or_none()+++def _virtual_manager_member(workspace_id: uuid.UUID, user_id: uuid.UUID) -> WorkspaceMember:+ """Construct an in-memory WorkspaceMember row representing manager+ access. NOT persisted — used only to flow through code paths that+ expect a `WorkspaceMember` value object."""+ virtual = WorkspaceMember(+ workspace_id=workspace_id,+ user_id=user_id,+ role=MANAGER_VIRTUAL_ROLE,+ )+ # Bypass the normal session lifecycle: this row never hits the DB.+ return virtual+++async def require_membership(+ session: AsyncSession,+ workspace_id: uuid.UUID,+ user_id: uuid.UUID,+ *,+ min_role: Optional[str] = None,+) -> WorkspaceMember:+ """Get the user's effective membership or raise 403/404.++ Accepts manager-of as a valid access path: if the user externally+ administers the workspace, returns a virtual `manager` membership+ with effective-owner rights.++ `min_role` enforces a role floor: 'viewer' (any access), 'editor'+ (no read-only), 'owner' (owner or manager).+ """+ member = await get_membership(session, workspace_id, user_id)+ if member is None:+ if await is_workspace_manager(session, workspace_id, user_id):+ member = _virtual_manager_member(workspace_id, user_id)+ else:+ raise HTTPException(status_code=404, detail="Workspace not found")+ if min_role is None:+ return member+ # `manager` is treated as effective owner for permission gates.+ role_rank = {"viewer": 1, "editor": 2, "owner": 3, "manager": 3}+ if role_rank.get(member.role, 0) < role_rank.get(min_role, 0):+ raise HTTPException(status_code=403, detail="Insufficient role")+ return member+++async def create_workspace(+ session: AsyncSession,+ *,+ name: str,+ creator: User,+ kind: str = "personal",+ default_currency: Optional[str] = None,+ locale: Optional[str] = None,+ icon: Optional[str] = None,+ color: Optional[str] = None,+ self_membership: bool = False,+ seed_defaults: bool = True,+) -> Workspace:+ """Create a new workspace administered by `creator`.++ By default the creator becomes the external manager (no+ `workspace_members` row). Pass `self_membership=True` to ALSO add+ them as an owner — useful when the creator is the human who'll+ actually use the workspace day-to-day.++ `seed_defaults=True` (the default) seeds the same starter+ categories + rules the Personal workspace gets. Without this every+ new workspace would force the user to rebuild their taxonomy from+ scratch.+ """+ prefs = creator.preferences or {}+ workspace_locale = locale or prefs.get("language") or "en"+ workspace = Workspace(+ name=name.strip() or "Workspace",+ kind=kind,+ created_by_user_id=creator.id,+ managed_by_user_id=creator.id,+ default_currency=default_currency or prefs.get("currency_display", "USD"),+ locale=workspace_locale,+ icon=icon,+ color=color,+ )+ session.add(workspace)+ await session.flush()+ if self_membership:+ session.add(+ WorkspaceMember(+ workspace_id=workspace.id,+ user_id=creator.id,+ role="owner",+ )+ )+ await session.flush()+ if seed_defaults:+ # Local imports to dodge circular dependencies — category_service+ # transitively pulls workspace_service through the autostamp+ # listener registration.+ from app.services.category_service import create_default_categories+ from app.services.rule_service import create_default_rules++ await create_default_categories(+ session, creator.id, workspace_locale, workspace_id=workspace.id+ )+ await create_default_rules(+ session, creator.id, workspace_locale, workspace_id=workspace.id+ )+ return workspace+++async def list_members(session: AsyncSession, workspace_id: uuid.UUID) -> list[tuple[WorkspaceMember, User]]:+ """Return (membership, user) tuples for everyone in the workspace.++ Implemented as two queries instead of a JOIN — the User table comes+ from fastapi-users with a portable `GUID` UUID type, while our own+ tables use Postgres-native `UUID`. Postgres handles the comparison+ transparently but SQLite stores them differently and the JOIN finds+ no matches under test.+ """+ member_rows = await session.execute(+ select(WorkspaceMember)+ .where(WorkspaceMember.workspace_id == workspace_id)+ .order_by(WorkspaceMember.joined_at.asc())+ )+ members = list(member_rows.scalars().all())+ if not members:+ return []+ user_ids = [m.user_id for m in members]+ user_rows = await session.execute(select(User).where(User.id.in_(user_ids)))+ users_by_id = {u.id: u for u in user_rows.scalars().all()}+ return [(m, users_by_id[m.user_id]) for m in members if m.user_id in users_by_id]+++async def add_member(+ session: AsyncSession,+ workspace_id: uuid.UUID,+ user_id: uuid.UUID,+ role: str = "editor",+ invited_by_user_id: Optional[uuid.UUID] = None,+) -> WorkspaceMember:+ """Insert a new membership. Caller validates the inviter's permission."""+ if role not in WORKSPACE_ROLES:+ raise HTTPException(status_code=400, detail=f"Invalid role: {role}")+ existing = await get_membership(session, workspace_id, user_id)+ if existing:+ raise HTTPException(status_code=409, detail="User is already a member")+ member = WorkspaceMember(+ workspace_id=workspace_id,+ user_id=user_id,+ role=role,+ invited_by_user_id=invited_by_user_id,+ )+ session.add(member)+ await session.flush()+ return member+++async def update_member_role(+ session: AsyncSession,+ workspace_id: uuid.UUID,+ user_id: uuid.UUID,+ new_role: str,+) -> WorkspaceMember:+ if new_role not in WORKSPACE_ROLES:+ raise HTTPException(status_code=400, detail=f"Invalid role: {new_role}")+ member = await get_membership(session, workspace_id, user_id)+ if member is None:+ raise HTTPException(status_code=404, detail="Member not found")+ # Block demoting the sole owner — leaves the workspace ownerless.+ if member.role == "owner" and new_role != "owner":+ owners = await session.execute(+ select(WorkspaceMember).where(+ WorkspaceMember.workspace_id == workspace_id,+ WorkspaceMember.role == "owner",+ )+ )+ owner_rows = owners.scalars().all()+ if len(owner_rows) <= 1:+ raise HTTPException(status_code=400, detail="Cannot demote the sole owner")+ member.role = new_role+ await session.flush()+ return member+++async def get_workspace_stats(+ session: AsyncSession, workspace_id: uuid.UUID+) -> dict:+ """Counts surfaced on the settings page header strip."""+ from sqlalchemy import func++ from app.models.account import Account+ from app.models.transaction import Transaction++ members_q = await session.execute(+ select(func.count(WorkspaceMember.id)).where(+ WorkspaceMember.workspace_id == workspace_id+ )+ )+ accounts_q = await session.execute(+ select(func.count(Account.id)).where(Account.workspace_id == workspace_id)+ )+ transactions_q = await session.execute(+ select(func.count(Transaction.id)).where(+ Transaction.workspace_id == workspace_id+ )+ )+ return {+ "members": int(members_q.scalar() or 0),+ "accounts": int(accounts_q.scalar() or 0),+ "transactions": int(transactions_q.scalar() or 0),+ }+++async def archive_workspace(+ session: AsyncSession, workspace_id: uuid.UUID, requester_id: uuid.UUID+) -> Workspace:+ """Soft-delete: flip is_archived. Refuses to archive the requester's+ LAST accessible workspace (they'd be locked out)."""+ workspace = await session.get(Workspace, workspace_id)+ if workspace is None:+ raise HTTPException(status_code=404, detail="Workspace not found")+ if workspace.is_archived:+ return workspace+ # Count this user's other workspaces (member OR manager).+ other_member = await session.execute(+ select(func.count(WorkspaceMember.id))+ .join(Workspace, Workspace.id == WorkspaceMember.workspace_id)+ .where(+ WorkspaceMember.user_id == requester_id,+ WorkspaceMember.workspace_id != workspace_id,+ Workspace.is_archived.is_(False),+ )+ )+ other_managed = await session.execute(+ select(func.count(Workspace.id)).where(+ Workspace.managed_by_user_id == requester_id,+ Workspace.id != workspace_id,+ Workspace.is_archived.is_(False),+ )+ )+ if int(other_member.scalar() or 0) + int(other_managed.scalar() or 0) == 0:+ raise HTTPException(+ status_code=400,+ detail="Cannot archive your last workspace",+ )+ workspace.is_archived = True+ await session.flush()+ return workspace+++async def remove_member(+ session: AsyncSession,+ workspace_id: uuid.UUID,+ user_id: uuid.UUID,+) -> None:+ member = await get_membership(session, workspace_id, user_id)+ if member is None:+ raise HTTPException(status_code=404, detail="Member not found")+ if member.role == "owner":+ owners = await session.execute(+ select(WorkspaceMember).where(+ WorkspaceMember.workspace_id == workspace_id,+ WorkspaceMember.role == "owner",+ )+ )+ if len(owners.scalars().all()) <= 1:+ raise HTTPException(status_code=400, detail="Cannot remove the sole owner")+ await session.delete(member)+ await session.flush()diff --git a/backend/mcp_server/auth.py b/backend/mcp_server/auth.pyindex 1dde4b14..0ae04885 100644--- a/backend/mcp_server/auth.py+++ b/backend/mcp_server/auth.py@@ -24,6 +24,11 @@ JWT_ALGO = "HS256"@dataclassclass CallContext:user_id: uuid.UUID+ # Workspace the tool call operates in. Populated from the JWT's+ # `ws_id` claim when present; otherwise resolved lazily by tools to+ # the user's default workspace (backwards-compat for tokens minted+ # before the workspace migration).+ workspace_id: Optional[uuid.UUID] = Noneconversation_id: Optional[uuid.UUID] = Noneagent_id: Optional[uuid.UUID] = None# True when the JWT was minted for an external agent (Claude Desktop,@@ -62,8 +67,10 @@ def verify_request(request: Request) -> CallContext:conv_raw = payload.get("conv_id")agent_raw = payload.get("agent_id")+ ws_raw = payload.get("ws_id")return CallContext(user_id=user_id,+ workspace_id=uuid.UUID(ws_raw) if ws_raw else None,conversation_id=uuid.UUID(conv_raw) if conv_raw else None,agent_id=uuid.UUID(agent_raw) if agent_raw else None,external=bool(payload.get("ext")),diff --git a/backend/mcp_server/tools/_helpers.py b/backend/mcp_server/tools/_helpers.pyindex f684eaa5..58f07490 100644--- a/backend/mcp_server/tools/_helpers.py+++ b/backend/mcp_server/tools/_helpers.py@@ -43,3 +43,21 @@ def num(x: Any) -> Optional[float]:if isinstance(x, Decimal):return float(x)return float(x)+++async def resolve_workspace_id(session, ctx) -> uuid.UUID:+ """Return the workspace the call operates in.++ Prefer the explicit `ws_id` claim from the JWT. Fall back to the+ caller's default (first) workspace — supports tokens minted before+ the workspace migration AND keeps single-workspace callers free of+ having to specify a workspace.+ """+ if ctx.workspace_id is not None:+ return ctx.workspace_id+ from app.services.workspace_service import get_default_workspace++ ws = await get_default_workspace(session, ctx.user_id)+ if ws is None:+ raise ValueError("No workspace available for this user")+ return ws.iddiff --git a/backend/mcp_server/tools/accounts.py b/backend/mcp_server/tools/accounts.pyindex 9f0916a8..c244582e 100644--- a/backend/mcp_server/tools/accounts.py+++ b/backend/mcp_server/tools/accounts.py@@ -7,7 +7,7 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom app.services import account_servicefrom mcp_server.auth import CallContextfrom mcp_server.registry import tool-from mcp_server.tools._helpers import num, parse_date, parse_uuid+from mcp_server.tools._helpers import num, parse_date, parse_uuid, resolve_workspace_id@tool(@@ -31,7 +31,8 @@ async def list_accounts(ctx: CallContext,include_closed: bool = False,) -> dict[str, Any]:- rows = await account_service.get_accounts(session, ctx.user_id, include_closed=include_closed)+ ws_id = await resolve_workspace_id(session, ctx)+ rows = await account_service.get_accounts(session, ws_id, include_closed=include_closed)# rows is already a list of dicts (per service contract), but normalize keys.items: list[dict[str, Any]] = []for r in rows:@@ -74,10 +75,11 @@ async def get_account_summary(from_date: str | None = None,to_date: str | None = None,) -> dict[str, Any]:+ ws_id = await resolve_workspace_id(session, ctx)summary = await account_service.get_account_summary(session,parse_uuid(account_id),- ctx.user_id,+ ws_id,date_from=parse_date(from_date),date_to=parse_date(to_date),)diff --git a/backend/mcp_server/tools/aggregate.py b/backend/mcp_server/tools/aggregate.pyindex b806cd3c..312712b3 100644--- a/backend/mcp_server/tools/aggregate.py+++ b/backend/mcp_server/tools/aggregate.py@@ -9,7 +9,7 @@ from app.models.transaction import Transactionfrom app.models.category import Categoryfrom mcp_server.auth import CallContextfrom mcp_server.registry import tool-from mcp_server.tools._helpers import num, parse_date, parse_uuid_list+from mcp_server.tools._helpers import num, parse_date, parse_uuid_list, resolve_workspace_id@tool(@@ -64,12 +64,13 @@ async def aggregate(# Hard cap regardless of LLM input — keeps payload small enough for# token-tight providers.limit = max(1, min(int(limit), 50))+ ws_id = await resolve_workspace_id(session, ctx)amount_col = func.coalesce(Transaction.amount_primary, Transaction.amount)# Group expression + label expression.if group_by == "category":bucket_id = Transaction.category_id- label_q = select(Category.id, Category.name).where(Category.user_id == ctx.user_id)+ label_q = select(Category.id, Category.name).where(Category.workspace_id == ws_id)elif group_by == "account":bucket_id = Transaction.account_idlabel_q = None@@ -94,7 +95,7 @@ async def aggregate(q = (select(bucket_id.label("bucket"), value_expr.label("value"), func.count(Transaction.id).label("count"))- .where(Transaction.user_id == ctx.user_id)+ .where(Transaction.workspace_id == ws_id))fd = parse_date(from_date)diff --git a/backend/mcp_server/tools/budgets.py b/backend/mcp_server/tools/budgets.pyindex 58a51f3f..036266d0 100644--- a/backend/mcp_server/tools/budgets.py+++ b/backend/mcp_server/tools/budgets.py@@ -8,7 +8,7 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom app.services import budget_servicefrom mcp_server.auth import CallContextfrom mcp_server.registry import tool-from mcp_server.tools._helpers import num, parse_date+from mcp_server.tools._helpers import num, parse_date, resolve_workspace_id@tool(@@ -33,7 +33,8 @@ async def get_budget_vs_actual(month: str | None = None,) -> dict[str, Any]:target = parse_date(month) or date.today().replace(day=1)- rows = await budget_service.get_budget_vs_actual(session, ctx.user_id, month=target)+ ws_id = await resolve_workspace_id(session, ctx)+ rows = await budget_service.get_budget_vs_actual(session, ws_id, ctx.user_id, month=target)items = []for r in rows:# BudgetVsActual is a Pydantic model; serialize defensively.diff --git a/backend/mcp_server/tools/categories.py b/backend/mcp_server/tools/categories.pyindex a8058d9f..9a99e169 100644--- a/backend/mcp_server/tools/categories.py+++ b/backend/mcp_server/tools/categories.py@@ -7,6 +7,7 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom app.services import category_servicefrom mcp_server.auth import CallContextfrom mcp_server.registry import tool+from mcp_server.tools._helpers import resolve_workspace_id@tool(@@ -24,7 +25,8 @@ async def list_categories(session: AsyncSession,ctx: CallContext,) -> dict[str, Any]:- cats = await category_service.get_categories(session, ctx.user_id)+ ws_id = await resolve_workspace_id(session, ctx)+ cats = await category_service.get_categories(session, ws_id)items = [{"id": str(c.id),diff --git a/backend/mcp_server/tools/groups.py b/backend/mcp_server/tools/groups.pyindex e8f930bd..606a2aff 100644--- a/backend/mcp_server/tools/groups.py+++ b/backend/mcp_server/tools/groups.py@@ -14,7 +14,7 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom app.services import balance_service, group_service, settlement_servicefrom mcp_server.auth import CallContextfrom mcp_server.registry import tool-from mcp_server.tools._helpers import num, parse_uuid+from mcp_server.tools._helpers import num, parse_uuid, resolve_workspace_id@tool(@@ -42,7 +42,8 @@ async def list_groups(ctx: CallContext,include_archived: bool = False,) -> dict[str, Any]:- groups = await group_service.list_groups(session, ctx.user_id, include_archived=include_archived)+ ws_id = await resolve_workspace_id(session, ctx)+ groups = await group_service.list_groups(session, ws_id, ctx.user_id, include_archived=include_archived)return {"items": [{@@ -95,7 +96,8 @@ async def get_group_balances(group_id: str,) -> dict[str, Any]:gid = parse_uuid(group_id)- result = await balance_service.compute_balances(session, gid, ctx.user_id)+ ws_id = await resolve_workspace_id(session, ctx)+ result = await balance_service.compute_balances(session, gid, ws_id, ctx.user_id)if result is None:return {"error": "group not found or not visible to this user"}@@ -154,7 +156,8 @@ async def list_group_settlements(group_id: str,) -> dict[str, Any]:gid = parse_uuid(group_id)- rows = await settlement_service.list_settlements(session, gid, ctx.user_id)+ ws_id = await resolve_workspace_id(session, ctx)+ rows = await settlement_service.list_settlements(session, gid, ws_id, ctx.user_id)if rows is None:return {"error": "group not found or not visible to this user"}diff --git a/backend/mcp_server/tools/lifecycle.py b/backend/mcp_server/tools/lifecycle.pyindex 7de84629..0489f7e8 100644--- a/backend/mcp_server/tools/lifecycle.py+++ b/backend/mcp_server/tools/lifecycle.py@@ -13,7 +13,7 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom app.services import asset_service, budget_service, goal_service, recurring_transaction_servicefrom mcp_server.auth import CallContextfrom mcp_server.registry import tool-from mcp_server.tools._helpers import num, parse_date+from mcp_server.tools._helpers import num, parse_date, resolve_workspace_id@tool(@@ -31,7 +31,8 @@ from mcp_server.tools._helpers import num, parse_dateasync def list_recurring_transactions(*, session: AsyncSession, ctx: CallContext) -> dict[str, Any]:- rows = await recurring_transaction_service.get_recurring_transactions(session, ctx.user_id)+ ws_id = await resolve_workspace_id(session, ctx)+ rows = await recurring_transaction_service.get_recurring_transactions(session, ws_id)items = [{"id": str(r.id),@@ -72,7 +73,8 @@ async def list_recurring_transactions(async def list_assets(*, session: AsyncSession, ctx: CallContext, include_archived: bool = False) -> dict[str, Any]:- rows = await asset_service.get_assets(session, ctx.user_id, include_archived=include_archived)+ ws_id = await resolve_workspace_id(session, ctx)+ rows = await asset_service.get_assets(session, ws_id, include_archived=include_archived)items: list[dict[str, Any]] = []for r in rows:d = r.model_dump(mode="json") if hasattr(r, "model_dump") else dict(r.__dict__)@@ -110,7 +112,8 @@ async def list_assets(async def list_goals(*, session: AsyncSession, ctx: CallContext, status: str | None = None) -> dict[str, Any]:- rows = await goal_service.get_goals(session, ctx.user_id, status=status)+ ws_id = await resolve_workspace_id(session, ctx)+ rows = await goal_service.get_goals(session, ws_id, ctx.user_id, status=status)items: list[dict[str, Any]] = []for r in rows:d = r.model_dump(mode="json") if hasattr(r, "model_dump") else dict(r.__dict__)@@ -147,7 +150,8 @@ async def list_budgets(*, session: AsyncSession, ctx: CallContext, month: str | None = None) -> dict[str, Any]:target = parse_date(month)- rows = await budget_service.get_budgets(session, ctx.user_id, month=target)+ ws_id = await resolve_workspace_id(session, ctx)+ rows = await budget_service.get_budgets(session, ws_id, month=target)items = [{"id": str(b.id),diff --git a/backend/mcp_server/tools/payees.py b/backend/mcp_server/tools/payees.pyindex f451a4b8..9a67a6d7 100644--- a/backend/mcp_server/tools/payees.py+++ b/backend/mcp_server/tools/payees.py@@ -7,6 +7,7 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom app.services import payee_servicefrom mcp_server.auth import CallContextfrom mcp_server.registry import tool+from mcp_server.tools._helpers import resolve_workspace_id@tool(@@ -20,7 +21,8 @@ async def list_payees(session: AsyncSession,ctx: CallContext,) -> dict[str, Any]:- payees = await payee_service.get_payees(session, ctx.user_id)+ ws_id = await resolve_workspace_id(session, ctx)+ payees = await payee_service.get_payees(session, ws_id)items = [{"id": str(p.id),diff --git a/backend/mcp_server/tools/proposals.py b/backend/mcp_server/tools/proposals.pyindex 7092f66a..1f0d4800 100644--- a/backend/mcp_server/tools/proposals.py+++ b/backend/mcp_server/tools/proposals.py@@ -46,7 +46,7 @@ from app.services import ()from mcp_server.auth import CallContextfrom mcp_server.registry import tool-from mcp_server.tools._helpers import num, parse_date, parse_uuid, parse_uuid_list+from mcp_server.tools._helpers import num, parse_date, parse_uuid, parse_uuid_list, resolve_workspace_id# Repeated in EVERY propose_* tool description. The LLM reads these when@@ -111,16 +111,17 @@ async def propose_categorize(category_id: str,apply: bool = False,) -> dict[str, Any]:+ ws_id = await resolve_workspace_id(session, ctx)cat_id = parse_uuid(category_id)cat = (await session.execute(- select(Category).where(Category.id == cat_id, Category.user_id == ctx.user_id)+ select(Category).where(Category.id == cat_id, Category.workspace_id == ws_id))).scalar_one_or_none()if cat is None:return {"error": "category not found"}tx_ids = parse_uuid_list(transaction_ids) or []txs = (await session.execute(- select(Transaction).where(Transaction.id.in_(tx_ids), Transaction.user_id == ctx.user_id)+ select(Transaction).where(Transaction.id.in_(tx_ids), Transaction.workspace_id == ws_id))).scalars().all()affected = [@@ -141,7 +142,7 @@ async def propose_categorize(if not affected:return {**preview, "error": "no matching transactions to update"}updated = await transaction_service.bulk_update_category(- session, ctx.user_id, [parse_uuid(a["id"]) for a in affected], cat.id+ session, ws_id, [parse_uuid(a["id"]) for a in affected], cat.id)return {**preview, "applied": True, "updated_count": updated}@@ -179,9 +180,10 @@ async def propose_create_category(color: str | None = None,apply: bool = False,) -> dict[str, Any]:+ ws_id = await resolve_workspace_id(session, ctx)existing = (await session.execute(select(Category.id, Category.name).where(- Category.user_id == ctx.user_id,+ Category.workspace_id == ws_id,Category.name.ilike(name.strip()),))).first()@@ -202,6 +204,7 @@ async def propose_create_category(return {**preview, "error": f"category named {existing.name!r} already exists"}created = await category_service.create_category(session,+ ws_id,ctx.user_id,CategoryCreate(name=preview["proposed"]["name"],@@ -253,11 +256,12 @@ async def propose_create_budget(is_recurring: bool = False,apply: bool = False,) -> dict[str, Any]:+ ws_id = await resolve_workspace_id(session, ctx)cat_id = parse_uuid(category_id)target_month = (parse_date(month) or date.today()).replace(day=1)cat = (await session.execute(- select(Category).where(Category.id == cat_id, Category.user_id == ctx.user_id)+ select(Category).where(Category.id == cat_id, Category.workspace_id == ws_id))).scalar_one_or_none()if cat is None:return {"error": "category not found"}@@ -278,6 +282,7 @@ async def propose_create_budget(if _can_apply(ctx, apply):created = await budget_service.create_budget(session,+ ws_id,ctx.user_id,BudgetCreate(category_id=cat.id,@@ -364,9 +369,10 @@ async def propose_create_transaction(splits: dict[str, Any] | None = None,apply: bool = False,) -> dict[str, Any]:+ ws_id = await resolve_workspace_id(session, ctx)acc_id = parse_uuid(account_id)acc = (await session.execute(- select(Account).where(Account.id == acc_id, Account.user_id == ctx.user_id)+ select(Account).where(Account.id == acc_id, Account.workspace_id == ws_id))).scalar_one_or_none()if acc is None:return {"error": "account not found"}@@ -374,7 +380,7 @@ async def propose_create_transaction(cat = Noneif category_id:cat = (await session.execute(- select(Category).where(Category.id == parse_uuid(category_id), Category.user_id == ctx.user_id)+ select(Category).where(Category.id == parse_uuid(category_id), Category.workspace_id == ws_id))).scalar_one_or_none()if cat is None:return {"error": "category not found"}@@ -386,6 +392,9 @@ async def propose_create_transaction(if not (group_id and splits):return {"error": "group_id and splits must be provided together"}gid = parse_uuid(group_id)+ # Group ownership stays user-scoped (Splitwise authorship check) —+ # the user_id column on `groups` represents the owner, not a+ # tenant filter.group = (await session.execute(select(Group).where(Group.id == gid, Group.user_id == ctx.user_id))).scalar_one_or_none()@@ -498,6 +507,7 @@ async def propose_create_transaction(try:created = await transaction_service.create_transaction(session,+ ws_id,ctx.user_id,TransactionCreate(description=proposed["description"],@@ -564,15 +574,16 @@ async def propose_create_recurring_transaction() -> dict[str, Any]:if frequency == "monthly" and not day_of_month:return {"error": "day_of_month is required for monthly frequency"}+ ws_id = await resolve_workspace_id(session, ctx)acc = (await session.execute(- select(Account).where(Account.id == parse_uuid(account_id), Account.user_id == ctx.user_id)+ select(Account).where(Account.id == parse_uuid(account_id), Account.workspace_id == ws_id))).scalar_one_or_none()if acc is None:return {"error": "account not found"}cat = Noneif category_id:cat = (await session.execute(- select(Category).where(Category.id == parse_uuid(category_id), Category.user_id == ctx.user_id)+ select(Category).where(Category.id == parse_uuid(category_id), Category.workspace_id == ws_id))).scalar_one_or_none()if cat is None:return {"error": "category not found"}@@ -602,6 +613,7 @@ async def propose_create_recurring_transaction(if _can_apply(ctx, apply):created = await recurring_transaction_service.create_recurring_transaction(session,+ ws_id,ctx.user_id,RecurringTransactionCreate(description=description.strip(),@@ -663,10 +675,11 @@ async def propose_update_recurring_transaction(is_active: bool | None = None,apply: bool = False,) -> dict[str, Any]:+ ws_id = await resolve_workspace_id(session, ctx)rid = parse_uuid(recurring_id)rt = (await session.execute(select(RecurringTransaction).where(- RecurringTransaction.id == rid, RecurringTransaction.user_id == ctx.user_id+ RecurringTransaction.id == rid, RecurringTransaction.workspace_id == ws_id))).scalar_one_or_none()if rt is None:@@ -675,7 +688,7 @@ async def propose_update_recurring_transaction(cat = Noneif category_id:cat = (await session.execute(- select(Category).where(Category.id == parse_uuid(category_id), Category.user_id == ctx.user_id)+ select(Category).where(Category.id == parse_uuid(category_id), Category.workspace_id == ws_id))).scalar_one_or_none()if cat is None:return {"error": "category not found"}@@ -731,7 +744,7 @@ async def propose_update_recurring_transaction(if "is_active" in changes:update_data["is_active"] = changes["is_active"]updated = await recurring_transaction_service.update_recurring_transaction(- session, rt.id, ctx.user_id, RecurringTransactionUpdate(**update_data)+ session, rt.id, ws_id, RecurringTransactionUpdate(**update_data))if updated is None:return {**preview, "error": "recurring transaction not found"}@@ -769,10 +782,11 @@ async def propose_cancel_recurring_transaction(mode: str = "deactivate",apply: bool = False,) -> dict[str, Any]:+ ws_id = await resolve_workspace_id(session, ctx)rt = (await session.execute(select(RecurringTransaction).where(RecurringTransaction.id == parse_uuid(recurring_id),- RecurringTransaction.user_id == ctx.user_id,+ RecurringTransaction.workspace_id == ws_id,))).scalar_one_or_none()if rt is None:@@ -800,14 +814,14 @@ async def propose_cancel_recurring_transaction(if _can_apply(ctx, apply):if mode == "delete":ok = await recurring_transaction_service.delete_recurring_transaction(- session, rt.id, ctx.user_id+ session, rt.id, ws_id)if not ok:return {**preview, "error": "recurring transaction not found"}return {**preview, "applied": True, "deleted": True}# deactivate pathupdated = await recurring_transaction_service.update_recurring_transaction(- session, rt.id, ctx.user_id, RecurringTransactionUpdate(is_active=False)+ session, rt.id, ws_id, RecurringTransactionUpdate(is_active=False))if updated is None:return {**preview, "error": "recurring transaction not found"}@@ -871,8 +885,10 @@ async def propose_create_goal(}if _can_apply(ctx, apply):+ ws_id = await resolve_workspace_id(session, ctx)created = await goal_service.create_goal(session,+ ws_id,ctx.user_id,GoalCreate(name=name.strip(),@@ -921,9 +937,10 @@ async def propose_create_payee_rule(category_id: str,apply: bool = False,) -> dict[str, Any]:+ ws_id = await resolve_workspace_id(session, ctx)cat_id = parse_uuid(category_id)cat = (await session.execute(- select(Category).where(Category.id == cat_id, Category.user_id == ctx.user_id)+ select(Category).where(Category.id == cat_id, Category.workspace_id == ws_id))).scalar_one_or_none()if cat is None:return {"error": "category not found"}@@ -941,6 +958,7 @@ async def propose_create_payee_rule(if _can_apply(ctx, apply):created = await rule_service.create_rule(session,+ ws_id,ctx.user_id,RuleCreate(name=f"Auto-categorize: {match_pattern}",diff --git a/backend/mcp_server/tools/reports.py b/backend/mcp_server/tools/reports.pyindex 100b8eb6..b00bfcbb 100644--- a/backend/mcp_server/tools/reports.py+++ b/backend/mcp_server/tools/reports.py@@ -8,7 +8,7 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom app.services import dashboard_service, report_servicefrom mcp_server.auth import CallContextfrom mcp_server.registry import tool-from mcp_server.tools._helpers import parse_date+from mcp_server.tools._helpers import parse_date, resolve_workspace_iddef _pri_currency(ctx: CallContext) -> str:@@ -43,8 +43,9 @@ async def get_net_worth(months: int = 12,interval: str = "monthly",) -> dict[str, Any]:+ ws_id = await resolve_workspace_id(session, ctx)rep = await report_service.get_net_worth_report(- session, ctx.user_id, months=int(months), interval=interval, currency=_pri_currency(ctx)+ session, ws_id, ctx.user_id, months=int(months), interval=interval, currency=_pri_currency(ctx))return _serialize_report(rep)@@ -69,8 +70,9 @@ async def get_income_expenses(months: int = 12,interval: str = "monthly",) -> dict[str, Any]:+ ws_id = await resolve_workspace_id(session, ctx)rep = await report_service.get_income_expenses_report(- session, ctx.user_id, months=int(months), interval=interval, currency=_pri_currency(ctx)+ session, ws_id, ctx.user_id, months=int(months), interval=interval, currency=_pri_currency(ctx))return _serialize_report(rep)@@ -95,8 +97,9 @@ async def get_cash_flow(months: int = 6,interval: str = "daily",) -> dict[str, Any]:+ ws_id = await resolve_workspace_id(session, ctx)rep = await report_service.get_cash_flow_report(- session, ctx.user_id, months=int(months), interval=interval, currency=_pri_currency(ctx)+ session, ws_id, ctx.user_id, months=int(months), interval=interval, currency=_pri_currency(ctx))return _serialize_report(rep)@@ -123,7 +126,8 @@ async def get_dashboard_snapshot(month: str | None = None,) -> dict[str, Any]:target = parse_date(month) or date.today().replace(day=1)- summary = await dashboard_service.get_summary(session, ctx.user_id, month=target)+ ws_id = await resolve_workspace_id(session, ctx)+ summary = await dashboard_service.get_summary(session, ws_id, ctx.user_id, month=target)if hasattr(summary, "model_dump"):return summary.model_dump(mode="json")return {"value": str(summary)}diff --git a/backend/mcp_server/tools/search.py b/backend/mcp_server/tools/search.pyindex 08dccac5..964f780c 100644--- a/backend/mcp_server/tools/search.py+++ b/backend/mcp_server/tools/search.py@@ -7,6 +7,7 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom app.services import search_servicefrom mcp_server.auth import CallContextfrom mcp_server.registry import tool+from mcp_server.tools._helpers import resolve_workspace_id@tool(@@ -33,5 +34,6 @@ async def search_all(query: str,per_type_limit: int = 5,) -> dict[str, Any]:- hits = await search_service.search_all(session, ctx.user_id, query, per_type_limit=int(per_type_limit))+ ws_id = await resolve_workspace_id(session, ctx)+ hits = await search_service.search_all(session, ws_id, ctx.user_id, query, per_type_limit=int(per_type_limit))return {"items": hits, "total": len(hits)}diff --git a/backend/mcp_server/tools/transactions.py b/backend/mcp_server/tools/transactions.pyindex 8632b60d..860a4a50 100644--- a/backend/mcp_server/tools/transactions.py+++ b/backend/mcp_server/tools/transactions.py@@ -9,7 +9,7 @@ from app.models.group import GroupMemberfrom app.services import transaction_servicefrom mcp_server.auth import CallContextfrom mcp_server.registry import tool-from mcp_server.tools._helpers import num, parse_date, parse_uuid, parse_uuid_list+from mcp_server.tools._helpers import num, parse_date, parse_uuid, parse_uuid_list, resolve_workspace_id@tool(@@ -120,8 +120,10 @@ async def list_transactions(# Hard cap regardless of what the LLM asks — the schema says 50 but# not every provider enforces additionalProperties / maximum.limit = max(1, min(int(limit), 50))+ ws_id = await resolve_workspace_id(session, ctx)txs, total, _ = await transaction_service.get_transactions(session,+ ws_id,ctx.user_id,account_ids=parse_uuid_list(account_ids),account_types=account_types or None,diff --git a/backend/pyproject.toml b/backend/pyproject.tomlindex dba50c51..34a934ff 100644--- a/backend/pyproject.toml+++ b/backend/pyproject.toml@@ -48,6 +48,8 @@ include = ["app*"][tool.pytest.ini_options]asyncio_mode = "auto"+asyncio_default_fixture_loop_scope = "session"+asyncio_default_test_loop_scope = "session"testpaths = ["tests"][tool.coverage.run]diff --git a/backend/tests/conftest.py b/backend/tests/conftest.pyindex a2af7008..d8be533d 100644--- a/backend/tests/conftest.py+++ b/backend/tests/conftest.py@@ -1,4 +1,3 @@-import asyncioimport osimport uuidfrom datetime import date, datetime, timezone@@ -62,6 +61,7 @@ from app.models.credit_card_bill import CreditCardBill # noqa: E402,F401from app.models.group import Group, GroupMember # noqa: E402,F401from app.models.transaction_split import TransactionSplit # noqa: E402,F401from app.models.group_settlement import GroupSettlement # noqa: E402,F401+from app.models.workspace import Workspace, WorkspaceMember # noqa: E402,F401# Agent models — gated by AGENTS_ENABLED above so tests always cover them.from app.agents.models import ( # noqa: E402,F401Agent,@@ -73,10 +73,22 @@ from app.agents.models import ( # noqa: E402,F401LlmUsage,)-# Use SQLite for tests — fast, no external dependency-TEST_DATABASE_URL = "sqlite+aiosqlite:///./test.db"--engine = create_async_engine(TEST_DATABASE_URL, echo=False)+# Use SQLite for tests — fast, no external dependency.+# Keep the DB file off the bind-mounted project dir (macOS bind mounts+# have known SQLite locking/journal quirks under aiosqlite) — /tmp is a+# tmpfs inside the container. StaticPool + a single shared connection+# is required so async fixtures and tests running on the shared+# session-scoped event loop see the same in-memory schema state.+from sqlalchemy.pool import StaticPool # noqa: E402++TEST_DATABASE_URL = "sqlite+aiosqlite:///:memory:"++engine = create_async_engine(+ TEST_DATABASE_URL,+ echo=False,+ connect_args={"check_same_thread": False},+ poolclass=StaticPool,+)TestSessionLocal = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)@@ -86,14 +98,7 @@ TestSessionLocal = async_sessionmaker(engine, class_=AsyncSession, expire_on_com# UUID comparisons.-@pytest_asyncio.fixture(scope="session")-def event_loop():- loop = asyncio.new_event_loop()- yield loop- loop.close()---@pytest_asyncio.fixture(scope="session", autouse=True)+@pytest_asyncio.fixture(scope="session", loop_scope="session", autouse=True)async def setup_database():"""Create all tables once for the test session."""async with engine.begin() as conn:@@ -104,7 +109,7 @@ async def setup_database():# Clean up test db fileimport ostry:- os.remove("./test.db")+ os.remove("/tmp/securo_test.db")except FileNotFoundError:pass@@ -145,7 +150,12 @@ async def client() -> AsyncGenerator[AsyncClient, None]:@pytest_asyncio.fixtureasync def test_user(session: AsyncSession, clean_db) -> User:- """Create a test user."""+ """Create a test user with an auto-created Personal workspace.++ Pre-creates the workspace so the auto-stamp listener (registered on+ the financial models) can resolve `workspace_id` from `user_id` for+ legacy test fixtures that construct rows without setting it.+ """import bcrypt as _bcrypthashed = _bcrypt.hashpw(b"testpass123", _bcrypt.gensalt()).decode()@@ -164,11 +174,45 @@ async def test_user(session: AsyncSession, clean_db) -> User:},)session.add(user)+ await session.flush()++ workspace = Workspace(+ id=uuid.uuid4(),+ name="Pessoal",+ kind="personal",+ created_by_user_id=user.id,+ default_currency="BRL",+ locale="pt-BR",+ )+ session.add(workspace)+ await session.flush()+ session.add(+ WorkspaceMember(+ id=uuid.uuid4(),+ workspace_id=workspace.id,+ user_id=user.id,+ role="owner",+ )+ )await session.commit()await session.refresh(user)return user+@pytest_asyncio.fixture+async def test_workspace(session: AsyncSession, test_user: User) -> Workspace:+ """Return the test user's default workspace (created by `test_user`)."""+ from sqlalchemy import select as _select+ result = await session.execute(+ _select(Workspace)+ .join(WorkspaceMember, WorkspaceMember.workspace_id == Workspace.id)+ .where(WorkspaceMember.user_id == test_user.id)+ .limit(1)+ )+ ws = result.scalar_one()+ return ws++@pytest_asyncio.fixtureasync def auth_token(client: AsyncClient, test_user: User) -> str:"""Get an auth token for the test user."""diff --git a/backend/tests/test_account_service.py b/backend/tests/test_account_service.pyindex e2fffa09..46bd6980 100644--- a/backend/tests/test_account_service.py+++ b/backend/tests/test_account_service.py@@ -93,10 +93,10 @@ async def _add_txn(@pytest.mark.asyncio-async def test_create_account_with_balance(session: AsyncSession, test_user):+async def test_create_account_with_balance(session: AsyncSession, test_user, test_workspace):"""Creating an account with balance > 0 creates an opening_balance transaction."""data = AccountCreate(name="Checking", type="checking", balance=Decimal("1000.00"), currency="BRL")- account = await create_account(session, test_user.id, data)+ account = await create_account(session, test_workspace.id, test_user.id, data)assert account.name == "Checking"assert account.balance == Decimal("1000.00")@@ -116,10 +116,10 @@ async def test_create_account_with_balance(session: AsyncSession, test_user):@pytest.mark.asyncio-async def test_create_credit_card_account_opening_is_debit(session: AsyncSession, test_user):+async def test_create_credit_card_account_opening_is_debit(session: AsyncSession, test_user, test_workspace):"""Credit card opening balance is recorded as debit (represents debt)."""data = AccountCreate(name="Nubank", type="credit_card", balance=Decimal("500.00"), currency="BRL")- account = await create_account(session, test_user.id, data)+ account = await create_account(session, test_workspace.id, test_user.id, data)from sqlalchemy import selectresult = await session.execute(@@ -134,10 +134,10 @@ async def test_create_credit_card_account_opening_is_debit(session: AsyncSession@pytest.mark.asyncio-async def test_create_account_zero_balance_no_opening(session: AsyncSession, test_user):+async def test_create_account_zero_balance_no_opening(session: AsyncSession, test_user, test_workspace):"""Creating an account with zero balance creates no opening transaction."""data = AccountCreate(name="Empty", type="checking", balance=Decimal("0.00"), currency="BRL")- account = await create_account(session, test_user.id, data)+ account = await create_account(session, test_workspace.id, test_user.id, data)from sqlalchemy import selectresult = await session.execute(@@ -150,14 +150,14 @@ async def test_create_account_zero_balance_no_opening(session: AsyncSession, tes@pytest.mark.asyncio-async def test_create_account_with_balance_date(session: AsyncSession, test_user):+async def test_create_account_with_balance_date(session: AsyncSession, test_user, test_workspace):"""Opening transaction uses the provided balance_date."""custom_date = date(2025, 1, 15)data = AccountCreate(name="Dated", type="checking", balance=Decimal("2000.00"),currency="BRL", balance_date=custom_date,)- account = await create_account(session, test_user.id, data)+ account = await create_account(session, test_workspace.id, test_user.id, data)from sqlalchemy import selectresult = await session.execute(@@ -176,22 +176,22 @@ async def test_create_account_with_balance_date(session: AsyncSession, test_user@pytest.mark.asyncio-async def test_update_account_name(session: AsyncSession, test_user):+async def test_update_account_name(session: AsyncSession, test_user, test_workspace):"""Updating account name works for manual accounts."""account = await _make_account(session, test_user.id, "Old Name")data = AccountUpdate(name="New Name")- updated = await update_account(session, account.id, test_user.id, data)+ updated = await update_account(session, account.id, test_workspace.id, data)assert updated is not Noneassert updated.name == "New Name"@pytest.mark.asyncio-async def test_update_account_balance_creates_opening(session: AsyncSession, test_user):+async def test_update_account_balance_creates_opening(session: AsyncSession, test_user, test_workspace):"""Updating balance on an account with no opening_balance creates one."""account = await _make_account(session, test_user.id, "No Balance", balance="0.00")data = AccountUpdate(balance=Decimal("500.00"))- updated = await update_account(session, account.id, test_user.id, data)+ updated = await update_account(session, account.id, test_workspace.id, data)assert updated is not Nonefrom sqlalchemy import select@@ -207,13 +207,13 @@ async def test_update_account_balance_creates_opening(session: AsyncSession, tes@pytest.mark.asyncio-async def test_update_account_balance_updates_existing_opening(session: AsyncSession, test_user):+async def test_update_account_balance_updates_existing_opening(session: AsyncSession, test_user, test_workspace):"""Updating balance when opening_balance exists updates it."""data = AccountCreate(name="Update Test", type="checking", balance=Decimal("1000.00"), currency="BRL")- account = await create_account(session, test_user.id, data)+ account = await create_account(session, test_workspace.id, test_user.id, data)update_data = AccountUpdate(balance=Decimal("2000.00"))- await update_account(session, account.id, test_user.id, update_data)+ await update_account(session, account.id, test_workspace.id, update_data)from sqlalchemy import selectresult = await session.execute(@@ -227,13 +227,13 @@ async def test_update_account_balance_updates_existing_opening(session: AsyncSes@pytest.mark.asyncio-async def test_update_account_balance_to_zero_removes_opening(session: AsyncSession, test_user):+async def test_update_account_balance_to_zero_removes_opening(session: AsyncSession, test_user, test_workspace):"""Setting balance to 0 removes the opening_balance transaction."""data = AccountCreate(name="Zero Test", type="checking", balance=Decimal("500.00"), currency="BRL")- account = await create_account(session, test_user.id, data)+ account = await create_account(session, test_workspace.id, test_user.id, data)update_data = AccountUpdate(balance=Decimal("0.00"))- await update_account(session, account.id, test_user.id, update_data)+ await update_account(session, account.id, test_workspace.id, update_data)from sqlalchemy import selectresult = await session.execute(@@ -246,14 +246,14 @@ async def test_update_account_balance_to_zero_removes_opening(session: AsyncSess@pytest.mark.asyncio-async def test_update_account_balance_with_date(session: AsyncSession, test_user):+async def test_update_account_balance_with_date(session: AsyncSession, test_user, test_workspace):"""Updating balance with balance_date updates the opening tx date."""data = AccountCreate(name="Date Test", type="checking", balance=Decimal("1000.00"), currency="BRL")- account = await create_account(session, test_user.id, data)+ account = await create_account(session, test_workspace.id, test_user.id, data)new_date = date(2025, 6, 15)update_data = AccountUpdate(balance=Decimal("1500.00"), balance_date=new_date)- await update_account(session, account.id, test_user.id, update_data)+ await update_account(session, account.id, test_workspace.id, update_data)from sqlalchemy import selectresult = await session.execute(@@ -268,7 +268,7 @@ async def test_update_account_balance_with_date(session: AsyncSession, test_user@pytest.mark.asyncio-async def test_update_bank_connected_raises(session: AsyncSession, test_user, test_connection):+async def test_update_bank_connected_raises(session: AsyncSession, test_user, test_workspace, test_connection):"""Updating a bank-connected account raises ValueError."""account = await _make_account(session, test_user.id, "Connected",@@ -276,14 +276,14 @@ async def test_update_bank_connected_raises(session: AsyncSession, test_user, te)data = AccountUpdate(name="Hacked")with pytest.raises(ValueError, match="bank-connected"):- await update_account(session, account.id, test_user.id, data)+ await update_account(session, account.id, test_workspace.id, data)@pytest.mark.asyncio-async def test_update_account_not_found(session: AsyncSession, test_user):+async def test_update_account_not_found(session: AsyncSession, test_user, test_workspace):"""Updating nonexistent account returns None."""data = AccountUpdate(name="Ghost")- result = await update_account(session, uuid.uuid4(), test_user.id, data)+ result = await update_account(session, uuid.uuid4(), test_workspace.id, data)assert result is None@@ -293,36 +293,36 @@ async def test_update_account_not_found(session: AsyncSession, test_user):@pytest.mark.asyncio-async def test_delete_manual_account(session: AsyncSession, test_user):+async def test_delete_manual_account(session: AsyncSession, test_user, test_workspace):"""Deleting a manual account returns True."""account = await _make_account(session, test_user.id, "To Delete")- result = await delete_account(session, account.id, test_user.id)+ result = await delete_account(session, account.id, test_workspace.id)assert result is True# Verify it's gone- assert await get_account(session, account.id, test_user.id) is None+ assert await get_account(session, account.id, test_workspace.id) is None@pytest.mark.asyncio-async def test_delete_bank_connected_raises(session: AsyncSession, test_user, test_connection):+async def test_delete_bank_connected_raises(session: AsyncSession, test_user, test_workspace, test_connection):"""Deleting a bank-connected account raises ValueError."""account = await _make_account(session, test_user.id, "Connected",connection_id=test_connection.id, external_id="ext-del",)with pytest.raises(ValueError, match="bank-connected"):- await delete_account(session, account.id, test_user.id)+ await delete_account(session, account.id, test_workspace.id)@pytest.mark.asyncio-async def test_delete_account_not_found(session: AsyncSession, test_user):+async def test_delete_account_not_found(session: AsyncSession, test_user, test_workspace):"""Deleting nonexistent account returns False."""- result = await delete_account(session, uuid.uuid4(), test_user.id)+ result = await delete_account(session, uuid.uuid4(), test_workspace.id)assert result is False@pytest.mark.asyncio-async def test_delete_account_with_import_logs(session: AsyncSession, test_user):+async def test_delete_account_with_import_logs(session: AsyncSession, test_user, test_workspace):"""Regression (#110): deleting an account with import_logs must succeed andcascade-delete the orphaned log rows instead of tripping the FK constraint."""from sqlalchemy import select@@ -336,10 +336,10 @@ async def test_delete_account_with_import_logs(session: AsyncSession, test_user)await session.commit()log_id = log.id- result = await delete_account(session, account.id, test_user.id)+ result = await delete_account(session, account.id, test_workspace.id)assert result is True- assert await get_account(session, account.id, test_user.id) is None+ assert await get_account(session, account.id, test_workspace.id) is Noneorphan = await session.execute(select(ImportLog).where(ImportLog.id == log_id))@@ -347,7 +347,7 @@ async def test_delete_account_with_import_logs(session: AsyncSession, test_user)@pytest.mark.asyncio-async def test_delete_account_with_recurring_transactions(session: AsyncSession, test_user):+async def test_delete_account_with_recurring_transactions(session: AsyncSession, test_user, test_workspace):"""Regression (#110, @stanleyndachi): deleting an account with a recurringtransaction must succeed; the recurring rows cascade away since a schedulewithout an account can't post."""@@ -364,7 +364,7 @@ async def test_delete_account_with_recurring_transactions(session: AsyncSession,await session.commit()rec_id = rec.id- result = await delete_account(session, account.id, test_user.id)+ result = await delete_account(session, account.id, test_workspace.id)assert result is Trueorphan = await session.execute(@@ -374,7 +374,7 @@ async def test_delete_account_with_recurring_transactions(session: AsyncSession,@pytest.mark.asyncio-async def test_delete_account_with_imported_transactions(session: AsyncSession, test_user):+async def test_delete_account_with_imported_transactions(session: AsyncSession, test_user, test_workspace):"""Regression (#110 v2, @ivancarlosti): deleting an account whose transactionswere imported from a file must succeed. The imported rows reference theimport_log via transactions.import_id — deleting import_logs first would@@ -399,10 +399,10 @@ async def test_delete_account_with_imported_transactions(session: AsyncSession,log_id = log.idtx_id = tx.id- result = await delete_account(session, account.id, test_user.id)+ result = await delete_account(session, account.id, test_workspace.id)assert result is True- assert await get_account(session, account.id, test_user.id) is None+ assert await get_account(session, account.id, test_workspace.id) is Nonesession.expire_all()orphan_log = await session.execute(@@ -416,7 +416,7 @@ async def test_delete_account_with_imported_transactions(session: AsyncSession,@pytest.mark.asyncio-async def test_delete_account_with_linked_goal(session: AsyncSession, test_user):+async def test_delete_account_with_linked_goal(session: AsyncSession, test_user, test_workspace):"""Regression (#110): deleting an account tracked by a goal must succeed;the goal survives with account_id nulled out (progress history is kept)."""from sqlalchemy import select@@ -431,7 +431,7 @@ async def test_delete_account_with_linked_goal(session: AsyncSession, test_user)await session.commit()goal_id = goal.id- result = await delete_account(session, account.id, test_user.id)+ result = await delete_account(session, account.id, test_workspace.id)assert result is Truesession.expire_all()@@ -449,10 +449,10 @@ async def test_delete_account_with_linked_goal(session: AsyncSession, test_user)@pytest.mark.asyncio-async def test_close_account(session: AsyncSession, test_user):+async def test_close_account(session: AsyncSession, test_user, test_workspace):"""Closing a manual account sets is_closed and closed_at."""account = await _make_account(session, test_user.id, "To Close")- closed = await close_account(session, account.id, test_user.id)+ closed = await close_account(session, account.id, test_workspace.id)assert closed is not Noneassert closed.is_closed is True@@ -460,7 +460,7 @@ async def test_close_account(session: AsyncSession, test_user):@pytest.mark.asyncio-async def test_close_bank_connected_keeps_link(session: AsyncSession, test_user, test_connection):+async def test_close_bank_connected_keeps_link(session: AsyncSession, test_user, test_workspace, test_connection):"""Closing a bank-connected account keeps its connection link.Sync uses (connection_id, external_id) to find the row; unlinking on close@@ -471,52 +471,52 @@ async def test_close_bank_connected_keeps_link(session: AsyncSession, test_user,session, test_user.id, "Connected Close",connection_id=test_connection.id, external_id="ext-close",)- closed = await close_account(session, account.id, test_user.id)+ closed = await close_account(session, account.id, test_workspace.id)assert closed.connection_id == test_connection.idassert closed.is_closed is True@pytest.mark.asyncio-async def test_close_already_closed_raises(session: AsyncSession, test_user):+async def test_close_already_closed_raises(session: AsyncSession, test_user, test_workspace):"""Closing an already-closed account raises ValueError."""account = await _make_account(session, test_user.id, "Already Closed")- await close_account(session, account.id, test_user.id)+ await close_account(session, account.id, test_workspace.id)with pytest.raises(ValueError, match="already closed"):- await close_account(session, account.id, test_user.id)+ await close_account(session, account.id, test_workspace.id)@pytest.mark.asyncio-async def test_close_not_found(session: AsyncSession, test_user):+async def test_close_not_found(session: AsyncSession, test_user, test_workspace):"""Closing nonexistent account returns None."""- result = await close_account(session, uuid.uuid4(), test_user.id)+ result = await close_account(session, uuid.uuid4(), test_workspace.id)assert result is None@pytest.mark.asyncio-async def test_reopen_account(session: AsyncSession, test_user):+async def test_reopen_account(session: AsyncSession, test_user, test_workspace):"""Reopening a closed account clears is_closed and closed_at."""account = await _make_account(session, test_user.id, "Reopen Test")- await close_account(session, account.id, test_user.id)+ await close_account(session, account.id, test_workspace.id)- reopened = await reopen_account(session, account.id, test_user.id)+ reopened = await reopen_account(session, account.id, test_workspace.id)assert reopened is not Noneassert reopened.is_closed is Falseassert reopened.closed_at is None@pytest.mark.asyncio-async def test_reopen_not_closed_raises(session: AsyncSession, test_user):+async def test_reopen_not_closed_raises(session: AsyncSession, test_user, test_workspace):"""Reopening a non-closed account raises ValueError."""account = await _make_account(session, test_user.id, "Open")with pytest.raises(ValueError, match="not closed"):- await reopen_account(session, account.id, test_user.id)+ await reopen_account(session, account.id, test_workspace.id)@pytest.mark.asyncio-async def test_reopen_not_found(session: AsyncSession, test_user):+async def test_reopen_not_found(session: AsyncSession, test_user, test_workspace):"""Reopening nonexistent account returns None."""- result = await reopen_account(session, uuid.uuid4(), test_user.id)+ result = await reopen_account(session, uuid.uuid4(), test_workspace.id)assert result is None@@ -526,12 +526,12 @@ async def test_reopen_not_found(session: AsyncSession, test_user):@pytest.mark.asyncio-async def test_get_accounts_returns_list(session: AsyncSession, test_user):+async def test_get_accounts_returns_list(session: AsyncSession, test_user, test_workspace):"""get_accounts returns list with current_balance and previous_balance."""account = await _make_account(session, test_user.id, "List Test", balance="1000.00")await _add_txn(session, test_user.id, account.id, 1000, "credit", date.today(), source="opening_balance")- accounts = await get_accounts(session, test_user.id)+ accounts = await get_accounts(session, test_workspace.id)assert len(accounts) >= 1acc = next(a for a in accounts if a["id"] == account.id)assert acc["name"] == "List Test"@@ -540,36 +540,36 @@ async def test_get_accounts_returns_list(session: AsyncSession, test_user):@pytest.mark.asyncio-async def test_get_accounts_excludes_closed(session: AsyncSession, test_user):+async def test_get_accounts_excludes_closed(session: AsyncSession, test_user, test_workspace):"""get_accounts excludes closed accounts by default."""account = await _make_account(session, test_user.id, "Closed Account")- await close_account(session, account.id, test_user.id)+ await close_account(session, account.id, test_workspace.id)- accounts = await get_accounts(session, test_user.id)+ accounts = await get_accounts(session, test_workspace.id)ids = [a["id"] for a in accounts]assert account.id not in ids@pytest.mark.asyncio-async def test_get_accounts_includes_closed_when_requested(session: AsyncSession, test_user):+async def test_get_accounts_includes_closed_when_requested(session: AsyncSession, test_user, test_workspace):"""get_accounts includes closed accounts when include_closed=True."""account = await _make_account(session, test_user.id, "Closed Visible")- await close_account(session, account.id, test_user.id)+ await close_account(session, account.id, test_workspace.id)- accounts = await get_accounts(session, test_user.id, include_closed=True)+ accounts = await get_accounts(session, test_workspace.id, include_closed=True)ids = [a["id"] for a in accounts]assert account.id in ids@pytest.mark.asyncio-async def test_get_accounts_credit_card_negated_balance(session: AsyncSession, test_user, test_connection):+async def test_get_accounts_credit_card_negated_balance(session: AsyncSession, test_user, test_workspace, test_connection):"""Bank-connected credit_card current_balance is negated."""account = await _make_account(session, test_user.id, "CC Connected",acc_type="credit_card", balance="3000.00",connection_id=test_connection.id, external_id="ext-cc",)- accounts = await get_accounts(session, test_user.id)+ accounts = await get_accounts(session, test_workspace.id)cc = next(a for a in accounts if a["id"] == account.id)# For bank-connected CC: current_balance = -balanceassert cc["current_balance"] == pytest.approx(-3000.0)@@ -581,7 +581,7 @@ async def test_get_accounts_credit_card_negated_balance(session: AsyncSession, t@pytest.mark.asyncio-async def test_get_account_summary_manual(session: AsyncSession, test_user):+async def test_get_account_summary_manual(session: AsyncSession, test_user, test_workspace):"""Summary for manual account computes balance from transactions."""account = await _make_account(session, test_user.id, "Summary Test")today = date.today()@@ -591,7 +591,7 @@ async def test_get_account_summary_manual(session: AsyncSession, test_user):await _add_txn(session, test_user.id, account.id, 200, "debit", today)await _add_txn(session, test_user.id, account.id, 100, "credit", today)- summary = await get_account_summary(session, account.id, test_user.id)+ summary = await get_account_summary(session, account.id, test_workspace.id)assert summary is not Noneassert summary["current_balance"] == pytest.approx(4900.0) # 5000 - 200 + 100assert summary["monthly_income"] == pytest.approx(100.0) # excludes opening_balance@@ -599,33 +599,33 @@ async def test_get_account_summary_manual(session: AsyncSession, test_user):@pytest.mark.asyncio-async def test_get_account_summary_bank_connected(session: AsyncSession, test_user, test_connection):+async def test_get_account_summary_bank_connected(session: AsyncSession, test_user, test_workspace, test_connection):"""Summary for bank-connected account uses stored balance."""account = await _make_account(session, test_user.id, "Connected Summary",balance="7500.00",connection_id=test_connection.id, external_id="ext-sum",)- summary = await get_account_summary(session, account.id, test_user.id)+ summary = await get_account_summary(session, account.id, test_workspace.id)assert summary is not Noneassert summary["current_balance"] == pytest.approx(7500.0)@pytest.mark.asyncio-async def test_get_account_summary_credit_card_bank(session: AsyncSession, test_user, test_connection):+async def test_get_account_summary_credit_card_bank(session: AsyncSession, test_user, test_workspace, test_connection):"""Bank-connected credit_card summary negates balance."""account = await _make_account(session, test_user.id, "CC Bank",acc_type="credit_card", balance="2000.00",connection_id=test_connection.id, external_id="ext-cc-sum",)- summary = await get_account_summary(session, account.id, test_user.id)+ summary = await get_account_summary(session, account.id, test_workspace.id)assert summary is not Noneassert summary["current_balance"] == pytest.approx(-2000.0)@pytest.mark.asyncio-async def test_get_account_summary_with_date_range(session: AsyncSession, test_user):+async def test_get_account_summary_with_date_range(session: AsyncSession, test_user, test_workspace):"""Summary filters income/expenses by date range."""account = await _make_account(session, test_user.id, "Date Range Test")today = date.today()@@ -636,7 +636,7 @@ async def test_get_account_summary_with_date_range(session: AsyncSession, test_u# Query only this monthsummary = await get_account_summary(- session, account.id, test_user.id,+ session, account.id, test_workspace.id,date_from=today.replace(day=1), date_to=today,)assert summary is not None@@ -644,7 +644,7 @@ async def test_get_account_summary_with_date_range(session: AsyncSession, test_u@pytest.mark.asyncio-async def test_get_account_summary_excludes_transfers(session: AsyncSession, test_user):+async def test_get_account_summary_excludes_transfers(session: AsyncSession, test_user, test_workspace):"""Summary excludes transfer pair transactions from income/expenses."""account = await _make_account(session, test_user.id, "Transfer Exclude")today = date.today()@@ -653,16 +653,16 @@ async def test_get_account_summary_excludes_transfers(session: AsyncSession, tesawait _add_txn(session, test_user.id, account.id, 300, "debit", today, transfer_pair_id=pair_id)await _add_txn(session, test_user.id, account.id, 100, "debit", today)- summary = await get_account_summary(session, account.id, test_user.id)+ summary = await get_account_summary(session, account.id, test_workspace.id)assert summary is not None# Only the non-transfer debit countsassert summary["monthly_expenses"] == pytest.approx(100.0)@pytest.mark.asyncio-async def test_get_account_summary_not_found(session: AsyncSession, test_user):+async def test_get_account_summary_not_found(session: AsyncSession, test_user, test_workspace):"""Summary for nonexistent account returns None."""- result = await get_account_summary(session, uuid.uuid4(), test_user.id)+ result = await get_account_summary(session, uuid.uuid4(), test_workspace.id)assert result is None@@ -672,7 +672,7 @@ async def test_get_account_summary_not_found(session: AsyncSession, test_user):@pytest.mark.asyncio-async def test_get_account_balance_history(session: AsyncSession, test_user):+async def test_get_account_balance_history(session: AsyncSession, test_user, test_workspace):"""Balance history returns daily balance series."""account = await _make_account(session, test_user.id, "History Test")today = date.today()@@ -681,7 +681,7 @@ async def test_get_account_balance_history(session: AsyncSession, test_user):await _add_txn(session, test_user.id, account.id, 200, "debit", today.replace(day=min(5, today.day)))history = await get_account_balance_history(- session, account.id, test_user.id,+ session, account.id, test_workspace.id,date_from=today.replace(day=1), date_to=today,)assert history is not None@@ -692,26 +692,26 @@ async def test_get_account_balance_history(session: AsyncSession, test_user):@pytest.mark.asyncio-async def test_get_account_balance_history_not_found(session: AsyncSession, test_user):+async def test_get_account_balance_history_not_found(session: AsyncSession, test_user, test_workspace):"""Balance history for nonexistent account returns None."""- result = await get_account_balance_history(session, uuid.uuid4(), test_user.id)+ result = await get_account_balance_history(session, uuid.uuid4(), test_workspace.id)assert result is None@pytest.mark.asyncio-async def test_get_account_balance_history_default_dates(session: AsyncSession, test_user):+async def test_get_account_balance_history_default_dates(session: AsyncSession, test_user, test_workspace):"""Balance history uses current month if no dates provided."""account = await _make_account(session, test_user.id, "Default Dates")await _add_txn(session, test_user.id, account.id, 1000, "credit", date.today(), source="opening_balance")- history = await get_account_balance_history(session, account.id, test_user.id)+ history = await get_account_balance_history(session, account.id, test_workspace.id)assert history is not Noneassert len(history) > 0@pytest.mark.asyncioasync def test_get_account_balance_history_credit_card_negated(- session: AsyncSession, test_user, test_connection,+ session: AsyncSession, test_user, test_workspace, test_connection,):"""Balance history for bank-connected credit_card applies sign negation."""account = await _make_account(@@ -723,7 +723,7 @@ async def test_get_account_balance_history_credit_card_negated(await _add_txn(session, test_user.id, account.id, 500, "debit", today)history = await get_account_balance_history(- session, account.id, test_user.id,+ session, account.id, test_workspace.id,date_from=today, date_to=today,)assert history is not Nonediff --git a/backend/tests/test_admin_service.py b/backend/tests/test_admin_service.pyindex 87b92ccc..5745afc2 100644--- a/backend/tests/test_admin_service.py+++ b/backend/tests/test_admin_service.py@@ -41,6 +41,8 @@ pytestmark = pytest.mark.asyncioasync def _make_user(session: AsyncSession, email: str, is_superuser: bool = False) -> User:import bcrypt as _bcrypt+ from app.services.workspace_service import create_personal_workspace_for_user+hashed = _bcrypt.hashpw(b"password123", _bcrypt.gensalt()).decode()user = User(id=uuid.uuid4(),@@ -53,6 +55,11 @@ async def _make_user(session: AsyncSession, email: str, is_superuser: bool = Fal)session.add(user)await session.commit()+ # Every user needs a workspace so the autostamp listener can resolve+ # workspace_id when downstream rows (accounts, connections, etc.) are+ # inserted without it — the cascade test relies on this.+ await create_personal_workspace_for_user(session, user)+ await session.commit()await session.refresh(user)return userdiff --git a/backend/tests/test_agents_api.py b/backend/tests/test_agents_api.pyindex 554082c3..518fa0ff 100644--- a/backend/tests/test_agents_api.py+++ b/backend/tests/test_agents_api.py@@ -20,7 +20,7 @@ pytestmark = pytest.mark.asyncio# real MCP server during HTTP tests. Returns an empty tool list.@pytest.fixture(autouse=True)def _mock_mcp_discover():- async def _empty_discover(self, *, user_id, conversation_id=None):+ async def _empty_discover(self, *, user_id, workspace_id=None, conversation_id=None, agent_id=None):return []with patch("app.agents.api.agents.MCPRegistry.discover", new=_empty_discover):yield@@ -29,6 +29,8 @@ def _mock_mcp_discover():@pytest_asyncio.fixtureasync def other_user(session: AsyncSession) -> User:"""A second user in the same DB to verify cross-tenant isolation."""+ from app.services.workspace_service import create_personal_workspace_for_user+hashed = _bcrypt.hashpw(b"otherpass123", _bcrypt.gensalt()).decode()user = User(id=uuid.uuid4(),@@ -40,6 +42,8 @@ async def other_user(session: AsyncSession) -> User:preferences={"language": "en", "currency_display": "USD"},)session.add(user)+ await session.flush()+ await create_personal_workspace_for_user(session, user)await session.commit()await session.refresh(user)return userdiff --git a/backend/tests/test_agents_conversation_service.py b/backend/tests/test_agents_conversation_service.pyindex 7baa17cf..4744d766 100644--- a/backend/tests/test_agents_conversation_service.py+++ b/backend/tests/test_agents_conversation_service.py@@ -12,9 +12,9 @@ from app.agents.services import conversation_service as svc@pytest.mark.asyncio-async def test_create_conversation_persists_with_defaults(session, test_user, test_agent):+async def test_create_conversation_persists_with_defaults(session, test_user, test_workspace, test_agent):conv = await svc.create_conversation(- session, user_id=test_user.id, agent_id=test_agent.id,+ session, workspace_id=test_workspace.id, user_id=test_user.id, agent_id=test_agent.id,)assert conv.id is not Noneassert conv.user_id == test_user.id@@ -24,9 +24,9 @@ async def test_create_conversation_persists_with_defaults(session, test_user, te@pytest.mark.asyncio-async def test_list_conversations_filters_by_agent_and_user(session, test_user, test_agent):+async def test_list_conversations_filters_by_agent_and_user(session, test_user, test_workspace, test_agent):a = await svc.create_conversation(- session, user_id=test_user.id, agent_id=test_agent.id, title="A",+ session, workspace_id=test_workspace.id, user_id=test_user.id, agent_id=test_agent.id, title="A",)# Conversation for a different agent → should be filtered out.other_agent_id = uuid.uuid4()@@ -35,25 +35,25 @@ async def test_list_conversations_filters_by_agent_and_user(session, test_user,session.add(other_agent)await session.commit()b = await svc.create_conversation(- session, user_id=test_user.id, agent_id=other_agent_id, title="B",+ session, workspace_id=test_workspace.id, user_id=test_user.id, agent_id=other_agent_id, title="B",)- rows_a = await svc.list_conversations(session, test_user.id, agent_id=test_agent.id)+ rows_a = await svc.list_conversations(session, test_workspace.id, agent_id=test_agent.id)assert {c.id for c in rows_a} == {a.id}# All of test_user's convs.- rows_all = await svc.list_conversations(session, test_user.id)+ rows_all = await svc.list_conversations(session, test_workspace.id)assert {a.id, b.id} <= {c.id for c in rows_all}# Foreign user → empty.foreign = uuid.uuid4()- assert await svc.list_conversations(session, foreign) == []+ assert await svc.list_conversations(session, foreign) == [] # foreign workspace_id@pytest.mark.asyncio-async def test_append_message_assigns_monotonic_ordinals(session, test_user, test_agent):+async def test_append_message_assigns_monotonic_ordinals(session, test_user, test_workspace, test_agent):conv = await svc.create_conversation(- session, user_id=test_user.id, agent_id=test_agent.id,+ session, workspace_id=test_workspace.id, user_id=test_user.id, agent_id=test_agent.id,)a = await svc.append_message(session, conversation_id=conv.id, role="user", content="one")b = await svc.append_message(session, conversation_id=conv.id, role="assistant", content="two")@@ -62,9 +62,9 @@ async def test_append_message_assigns_monotonic_ordinals(session, test_user, tes@pytest.mark.asyncio-async def test_list_messages_ordered_by_ordinal(session, test_user, test_agent):+async def test_list_messages_ordered_by_ordinal(session, test_user, test_workspace, test_agent):conv = await svc.create_conversation(- session, user_id=test_user.id, agent_id=test_agent.id,+ session, workspace_id=test_workspace.id, user_id=test_user.id, agent_id=test_agent.id,)await svc.append_message(session, conversation_id=conv.id, role="user", content="one")await svc.append_message(session, conversation_id=conv.id, role="assistant", content="two")@@ -73,9 +73,9 @@ async def test_list_messages_ordered_by_ordinal(session, test_user, test_agent):@pytest.mark.asyncio-async def test_append_message_persists_tool_payloads(session, test_user, test_agent):+async def test_append_message_persists_tool_payloads(session, test_user, test_workspace, test_agent):conv = await svc.create_conversation(- session, user_id=test_user.id, agent_id=test_agent.id,+ session, workspace_id=test_workspace.id, user_id=test_user.id, agent_id=test_agent.id,)msg = await svc.append_message(session,@@ -96,19 +96,19 @@ async def test_append_message_persists_tool_payloads(session, test_user, test_ag@pytest.mark.asyncio-async def test_update_title_if_empty_only_writes_when_blank(session, test_user, test_agent):+async def test_update_title_if_empty_only_writes_when_blank(session, test_user, test_workspace, test_agent):conv = await svc.create_conversation(- session, user_id=test_user.id, agent_id=test_agent.id,+ session, workspace_id=test_workspace.id, user_id=test_user.id, agent_id=test_agent.id,)# First call: title is None → should fill in.await svc.update_title_if_empty(session, conv.id, "Auto generated")- refreshed = await svc.get_conversation(session, conv.id, test_user.id)+ refreshed = await svc.get_conversation(session, conv.id, test_workspace.id)await session.refresh(refreshed)assert refreshed.title == "Auto generated"# Second call: title already set → should NOT overwrite.await svc.update_title_if_empty(session, conv.id, "Different title")- refreshed = await svc.get_conversation(session, conv.id, test_user.id)+ refreshed = await svc.get_conversation(session, conv.id, test_workspace.id)await session.refresh(refreshed)assert refreshed.title == "Auto generated"@@ -120,41 +120,41 @@ async def test_update_title_if_empty_silent_on_missing_conv(session):@pytest.mark.asyncio-async def test_update_title_truncates_to_200_chars(session, test_user, test_agent):+async def test_update_title_truncates_to_200_chars(session, test_user, test_workspace, test_agent):conv = await svc.create_conversation(- session, user_id=test_user.id, agent_id=test_agent.id,+ session, workspace_id=test_workspace.id, user_id=test_user.id, agent_id=test_agent.id,)long_title = "x" * 500- out = await svc.update_title(session, conv.id, test_user.id, long_title)+ out = await svc.update_title(session, conv.id, test_workspace.id,long_title)assert out is not Noneassert len(out.title) == 200@pytest.mark.asyncio-async def test_update_title_returns_none_on_missing(session, test_user):- out = await svc.update_title(session, uuid.uuid4(), test_user.id, "x")+async def test_update_title_returns_none_on_missing(session, test_workspace):+ out = await svc.update_title(session, uuid.uuid4(), test_workspace.id, "x")assert out is None@pytest.mark.asyncio-async def test_update_title_blank_clears_to_none(session, test_user, test_agent):+async def test_update_title_blank_clears_to_none(session, test_user, test_workspace, test_agent):conv = await svc.create_conversation(- session, user_id=test_user.id, agent_id=test_agent.id, title="Existing",+ session, workspace_id=test_workspace.id, user_id=test_user.id, agent_id=test_agent.id, title="Existing",)- out = await svc.update_title(session, conv.id, test_user.id, " ")+ out = await svc.update_title(session, conv.id, test_workspace.id," ")assert out is not Noneassert out.title is None@pytest.mark.asyncio-async def test_delete_conversation_returns_false_on_missing(session, test_user):- assert await svc.delete_conversation(session, uuid.uuid4(), test_user.id) is False+async def test_delete_conversation_returns_false_on_missing(session, test_workspace):+ assert await svc.delete_conversation(session, uuid.uuid4(), test_workspace.id) is False@pytest.mark.asyncio-async def test_delete_conversation_removes_row(session, test_user, test_agent):+async def test_delete_conversation_removes_row(session, test_user, test_workspace, test_agent):conv = await svc.create_conversation(- session, user_id=test_user.id, agent_id=test_agent.id,+ session, workspace_id=test_workspace.id, user_id=test_user.id, agent_id=test_agent.id,)- assert await svc.delete_conversation(session, conv.id, test_user.id) is True- assert await svc.get_conversation(session, conv.id, test_user.id) is None+ assert await svc.delete_conversation(session, conv.id, test_workspace.id) is True+ assert await svc.get_conversation(session, conv.id, test_workspace.id) is Nonediff --git a/backend/tests/test_agents_coverage_gaps.py b/backend/tests/test_agents_coverage_gaps.pyindex a9006f8e..387e56d2 100644--- a/backend/tests/test_agents_coverage_gaps.py+++ b/backend/tests/test_agents_coverage_gaps.py@@ -17,7 +17,7 @@ from app.agents.services import agent_service@pytest.mark.asyncioasync def test_list_agents_populates_conversation_and_knowledge_counts(- session, test_user, test_agent+ session, test_user, test_workspace, test_agent):"""Ensures the GROUP BY count queries (lines 23-43) run."""from app.agents.models.conversation import Conversation@@ -34,7 +34,7 @@ async def test_list_agents_populates_conversation_and_knowledge_counts(])await session.commit()- rows = await agent_service.list_agents(session, test_user.id)+ rows = await agent_service.list_agents(session, test_workspace.id)assert len(rows) == 1assert rows[0].conversation_count == 2 # type: ignore[attr-defined]assert rows[0].knowledge_count == 1 # type: ignore[attr-defined]@@ -127,7 +127,7 @@ async def test_get_agent_tools_returns_merged_state(in api/agents.py without a live MCP server."""from app.agents.mcp.client import ToolHandle- async def fake_discover(self, *, user_id, conversation_id=None, agent_id=None):+ async def fake_discover(self, *, user_id, workspace_id=None, conversation_id=None, agent_id=None):return [ToolHandle(server="securo", name="list_accounts", description="d", parameters={}),ToolHandle(server="securo", name="propose_x", description="d", parameters={}, is_proposal=True),diff --git a/backend/tests/test_agents_executor.py b/backend/tests/test_agents_executor.pyindex b3b16965..9771f8b2 100644--- a/backend/tests/test_agents_executor.py+++ b/backend/tests/test_agents_executor.py@@ -74,10 +74,10 @@ class _FakeMCP(MCPRegistry):def server_names(self):return ["securo"]- async def discover(self, *, user_id, conversation_id=None, agent_id=None):+ async def discover(self, *, workspace_id=None, user_id, conversation_id=None, agent_id=None):return list(self._tools)- async def call(self, *, wire_name, arguments, user_id, conversation_id=None, agent_id=None):+ async def call(self, *, wire_name, arguments, workspace_id=None, user_id, conversation_id=None, agent_id=None):self.calls.append((wire_name, arguments))return self._canneddiff --git a/backend/tests/test_asset_group_service.py b/backend/tests/test_asset_group_service.pyindex 945d4458..0001a9e4 100644--- a/backend/tests/test_asset_group_service.py+++ b/backend/tests/test_asset_group_service.py@@ -11,7 +11,7 @@ from app.services.asset_group_service import get_groups@pytest.mark.asyncioasync def test_get_groups_hides_empty_synced_wallets(- session: AsyncSession, test_user+ session: AsyncSession, test_user, test_workspace):active_connection = BankConnection(id=uuid.uuid4(),@@ -48,7 +48,7 @@ async def test_get_groups_hides_empty_synced_wallets(session.add_all([manual_group, orphan_synced_group, active_synced_group])await session.commit()- groups = await get_groups(session, test_user.id)+ groups = await get_groups(session, test_workspace.id, test_user.id)names = {g.name for g in groups}assert "Manual Wallet" in namesdiff --git a/backend/tests/test_asset_service.py b/backend/tests/test_asset_service.pyindex 2e35a3c6..6dda41de 100644--- a/backend/tests/test_asset_service.py+++ b/backend/tests/test_asset_service.py@@ -62,9 +62,9 @@ async def test_asset_with_values(session: AsyncSession, test_asset: Asset) -> As@pytest.mark.asyncio-async def test_create_asset(session: AsyncSession, test_user: User):+async def test_create_asset(session: AsyncSession, test_user: User, test_workspace):data = AssetCreate(name="Car", type="vehicle", currency="BRL")- result = await asset_service.create_asset(session, test_user.id, data)+ result = await asset_service.create_asset(session, test_workspace.id, test_user.id, data)assert result.name == "Car"assert result.type == "vehicle"assert result.current_value is None@@ -72,28 +72,28 @@ async def test_create_asset(session: AsyncSession, test_user: User):@pytest.mark.asyncio-async def test_create_asset_with_initial_value(session: AsyncSession, test_user: User):+async def test_create_asset_with_initial_value(session: AsyncSession, test_user: User, test_workspace):data = AssetCreate(name="Watch", type="valuable", currency="BRL",current_value=Decimal("15000.00"),purchase_price=Decimal("12000.00"),)- result = await asset_service.create_asset(session, test_user.id, data)+ result = await asset_service.create_asset(session, test_workspace.id, test_user.id, data)assert result.current_value == 15000.0assert result.gain_loss == 3000.0assert result.value_count == 1@pytest.mark.asyncio-async def test_list_assets(session: AsyncSession, test_user: User, test_asset: Asset):- results = await asset_service.get_assets(session, test_user.id)+async def test_list_assets(session: AsyncSession, test_user: User, test_workspace, test_asset: Asset):+ results = await asset_service.get_assets(session, test_workspace.id)assert len(results) >= 1names = [a.name for a in results]assert "Test Property" in names@pytest.mark.asyncio-async def test_list_assets_excludes_archived(session: AsyncSession, test_user: User):+async def test_list_assets_excludes_archived(session: AsyncSession, test_user: User, test_workspace):asset = Asset(id=uuid.uuid4(),user_id=test_user.id,@@ -106,46 +106,46 @@ async def test_list_assets_excludes_archived(session: AsyncSession, test_user: Usession.add(asset)await session.commit()- results = await asset_service.get_assets(session, test_user.id, include_archived=False)+ results = await asset_service.get_assets(session, test_workspace.id, include_archived=False)names = [a.name for a in results]assert "Archived Asset" not in names- results_all = await asset_service.get_assets(session, test_user.id, include_archived=True)+ results_all = await asset_service.get_assets(session, test_workspace.id, include_archived=True)names_all = [a.name for a in results_all]assert "Archived Asset" in names_all@pytest.mark.asyncio-async def test_get_asset(session: AsyncSession, test_user: User, test_asset: Asset):- result = await asset_service.get_asset(session, test_asset.id, test_user.id)+async def test_get_asset(session: AsyncSession, test_user: User, test_workspace, test_asset: Asset):+ result = await asset_service.get_asset(session, test_asset.id, test_workspace.id)assert result is not Noneassert result.name == "Test Property"@pytest.mark.asyncio-async def test_get_asset_not_found(session: AsyncSession, test_user: User):- result = await asset_service.get_asset(session, uuid.uuid4(), test_user.id)+async def test_get_asset_not_found(session: AsyncSession, test_user: User, test_workspace):+ result = await asset_service.get_asset(session, uuid.uuid4(), test_workspace.id)assert result is None@pytest.mark.asyncio-async def test_update_asset(session: AsyncSession, test_user: User, test_asset: Asset):+async def test_update_asset(session: AsyncSession, test_user: User, test_workspace, test_asset: Asset):data = AssetUpdate(name="Updated Property", type="investment")- result = await asset_service.update_asset(session, test_asset.id, test_user.id, data)+ result = await asset_service.update_asset(session, test_asset.id, test_workspace.id, test_user.id, data)assert result is not Noneassert result.name == "Updated Property"assert result.type == "investment"@pytest.mark.asyncio-async def test_update_asset_not_found(session: AsyncSession, test_user: User):+async def test_update_asset_not_found(session: AsyncSession, test_user: User, test_workspace):data = AssetUpdate(name="Nope")- result = await asset_service.update_asset(session, uuid.uuid4(), test_user.id, data)+ result = await asset_service.update_asset(session, uuid.uuid4(), test_workspace.id, test_user.id, data)assert result is None@pytest.mark.asyncio-async def test_delete_asset(session: AsyncSession, test_user: User):+async def test_delete_asset(session: AsyncSession, test_user: User, test_workspace):asset = Asset(id=uuid.uuid4(),user_id=test_user.id,@@ -157,15 +157,15 @@ async def test_delete_asset(session: AsyncSession, test_user: User):session.add(asset)await session.commit()- deleted = await asset_service.delete_asset(session, asset.id, test_user.id)+ deleted = await asset_service.delete_asset(session, asset.id, test_workspace.id)assert deleted is True- result = await asset_service.get_asset(session, asset.id, test_user.id)+ result = await asset_service.get_asset(session, asset.id, test_workspace.id)assert result is None@pytest.mark.asyncio-async def test_delete_asset_cascades_values(session: AsyncSession, test_user: User):+async def test_delete_asset_cascades_values(session: AsyncSession, test_user: User, test_workspace):asset = Asset(id=uuid.uuid4(),user_id=test_user.id,@@ -187,14 +187,14 @@ async def test_delete_asset_cascades_values(session: AsyncSession, test_user: Ussession.add(v)await session.commit()- deleted = await asset_service.delete_asset(session, asset.id, test_user.id)+ deleted = await asset_service.delete_asset(session, asset.id, test_workspace.id)assert deleted is True@pytest.mark.asyncio-async def test_add_asset_value(session: AsyncSession, test_user: User, test_asset: Asset):+async def test_add_asset_value(session: AsyncSession, test_user: User, test_workspace, test_asset: Asset):data = AssetValueCreate(amount=Decimal("600000.00"), date=date.today())- result = await asset_service.add_asset_value(session, test_asset.id, test_user.id, data)+ result = await asset_service.add_asset_value(session, test_asset.id, test_workspace.id, data)assert result is not Noneassert result.amount == 600000.0assert result.source == "manual"@@ -202,15 +202,15 @@ async def test_add_asset_value(session: AsyncSession, test_user: User, test_asse@pytest.mark.asyncioasync def test_add_asset_value_not_owned(session: AsyncSession, test_asset: Asset):- other_user_id = uuid.uuid4()+ other_workspace_id = uuid.uuid4()data = AssetValueCreate(amount=Decimal("100.00"), date=date.today())- result = await asset_service.add_asset_value(session, test_asset.id, other_user_id, data)+ result = await asset_service.add_asset_value(session, test_asset.id, other_workspace_id, data)assert result is None@pytest.mark.asyncio-async def test_get_asset_values(session: AsyncSession, test_user: User, test_asset_with_values: Asset):- values = await asset_service.get_asset_values(session, test_asset_with_values.id, test_user.id)+async def test_get_asset_values(session: AsyncSession, test_user: User, test_workspace, test_asset_with_values: Asset):+ values = await asset_service.get_asset_values(session, test_asset_with_values.id, test_workspace.id)assert values is not Noneassert len(values) == 3# Should be ordered most recent first@@ -218,7 +218,7 @@ async def test_get_asset_values(session: AsyncSession, test_user: User, test_ass@pytest.mark.asyncio-async def test_delete_asset_value(session: AsyncSession, test_user: User, test_asset: Asset):+async def test_delete_asset_value(session: AsyncSession, test_user: User, test_workspace, test_asset: Asset):v = AssetValue(id=uuid.uuid4(),asset_id=test_asset.id,@@ -229,27 +229,27 @@ async def test_delete_asset_value(session: AsyncSession, test_user: User, test_asession.add(v)await session.commit()- deleted = await asset_service.delete_asset_value(session, v.id, test_user.id)+ deleted = await asset_service.delete_asset_value(session, v.id, test_workspace.id)assert deleted is True@pytest.mark.asyncio-async def test_get_asset_value_trend(session: AsyncSession, test_user: User, test_asset_with_values: Asset):- trend = await asset_service.get_asset_value_trend(session, test_asset_with_values.id, test_user.id)+async def test_get_asset_value_trend(session: AsyncSession, test_user: User, test_workspace, test_asset_with_values: Asset):+ trend = await asset_service.get_asset_value_trend(session, test_asset_with_values.id, test_workspace.id)assert trend is not Noneassert len(trend) == 3assert trend[0]["date"] <= trend[1]["date"] # ordered by date asc@pytest.mark.asyncio-async def test_get_total_asset_value(session: AsyncSession, test_user: User, test_asset_with_values: Asset):- totals, _ = await asset_service.get_asset_values_at(session, test_user.id)+async def test_get_total_asset_value(session: AsyncSession, test_user: User, test_workspace, test_asset_with_values: Asset):+ totals, _ = await asset_service.get_asset_values_at(session, test_workspace.id, by_workspace=True)assert "BRL" in totalsassert totals["BRL"] >= 550000.0 # latest value@pytest.mark.asyncio-async def test_total_asset_value_excludes_sold(session: AsyncSession, test_user: User):+async def test_total_asset_value_excludes_sold(session: AsyncSession, test_user: User, test_workspace):"""Sold assets should not count in total."""asset = Asset(id=uuid.uuid4(),@@ -273,7 +273,7 @@ async def test_total_asset_value_excludes_sold(session: AsyncSession, test_user:session.add(v)await session.commit()- totals, _ = await asset_service.get_asset_values_at(session, test_user.id)+ totals, _ = await asset_service.get_asset_values_at(session, test_workspace.id, by_workspace=True)assert isinstance(totals, dict)@@ -315,37 +315,37 @@ async def test_growth_rule_task(session: AsyncSession, test_user: User):# ---------------------------------------------------------------------------@pytest.mark.asyncio-async def test_current_value_falls_back_to_purchase_price(session: AsyncSession, test_user: User):+async def test_current_value_falls_back_to_purchase_price(session: AsyncSession, test_user: User, test_workspace):"""When no AssetValue rows exist, current_value should equal purchase_price."""data = AssetCreate(name="New Car", type="vehicle", currency="BRL",purchase_price=Decimal("80000.00"),purchase_date=date(2025, 6, 1),)- result = await asset_service.create_asset(session, test_user.id, data)+ result = await asset_service.create_asset(session, test_workspace.id, test_user.id, data)assert result.current_value == 80000.0assert result.gain_loss == 0.0assert result.value_count == 0@pytest.mark.asyncio-async def test_current_value_none_when_no_price_no_values(session: AsyncSession, test_user: User):+async def test_current_value_none_when_no_price_no_values(session: AsyncSession, test_user: User, test_workspace):"""When no purchase_price and no AssetValue, current_value should be None."""data = AssetCreate(name="Empty Asset", type="other", currency="BRL")- result = await asset_service.create_asset(session, test_user.id, data)+ result = await asset_service.create_asset(session, test_workspace.id, test_user.id, data)assert result.current_value is Noneassert result.gain_loss is None@pytest.mark.asyncio-async def test_current_value_prefers_latest_value_over_purchase(session: AsyncSession, test_user: User):+async def test_current_value_prefers_latest_value_over_purchase(session: AsyncSession, test_user: User, test_workspace):"""When AssetValue rows exist, current_value should use the latest one, not purchase_price."""data = AssetCreate(name="Appreciated Watch", type="valuable", currency="BRL",purchase_price=Decimal("5000.00"),current_value=Decimal("7500.00"),)- result = await asset_service.create_asset(session, test_user.id, data)+ result = await asset_service.create_asset(session, test_workspace.id, test_user.id, data)assert result.current_value == 7500.0assert result.gain_loss == 2500.0@@ -355,7 +355,7 @@ async def test_current_value_prefers_latest_value_over_purchase(session: AsyncSe# ---------------------------------------------------------------------------@pytest.mark.asyncio-async def test_growth_rule_backfills_values_on_create(session: AsyncSession, test_user: User):+async def test_growth_rule_backfills_values_on_create(session: AsyncSession, test_user: User, test_workspace):"""Creating a growth_rule asset starting in the past should generate all intermediate values."""start = date.today() - timedelta(days=90)data = AssetCreate(@@ -368,7 +368,7 @@ async def test_growth_rule_backfills_values_on_create(session: AsyncSession, tesgrowth_frequency="monthly",growth_start_date=start,)- result = await asset_service.create_asset(session, test_user.id, data)+ result = await asset_service.create_asset(session, test_workspace.id, test_user.id, data)# Should have the seed value + at least 2 monthly rule values (90 days ~ 3 months)assert result.value_count >= 3@@ -378,7 +378,7 @@ async def test_growth_rule_backfills_values_on_create(session: AsyncSession, tes@pytest.mark.asyncio-async def test_growth_rule_percentage_backfill_math(session: AsyncSession, test_user: User):+async def test_growth_rule_percentage_backfill_math(session: AsyncSession, test_user: User, test_workspace):"""Verify the exact math for percentage growth backfill."""# Start exactly 3 months ago on the 1sttoday = date.today()@@ -394,7 +394,7 @@ async def test_growth_rule_percentage_backfill_math(session: AsyncSession, test_growth_frequency="monthly",growth_start_date=start,)- result = await asset_service.create_asset(session, test_user.id, data)+ result = await asset_service.create_asset(session, test_workspace.id, test_user.id, data)# 1000 * 1.1 * 1.1 * 1.1 = 1331.0assert result.current_value is not None@@ -405,7 +405,7 @@ async def test_growth_rule_percentage_backfill_math(session: AsyncSession, test_@pytest.mark.asyncio-async def test_growth_rule_absolute_backfill(session: AsyncSession, test_user: User):+async def test_growth_rule_absolute_backfill(session: AsyncSession, test_user: User, test_workspace):"""Verify absolute growth type adds a fixed amount each period."""today = date.today()start = date(today.year if today.month > 3 else today.year - 1,@@ -420,7 +420,7 @@ async def test_growth_rule_absolute_backfill(session: AsyncSession, test_user: Ugrowth_frequency="monthly",growth_start_date=start,)- result = await asset_service.create_asset(session, test_user.id, data)+ result = await asset_service.create_asset(session, test_workspace.id, test_user.id, data)# 5000 + 500 + 500 + 500 = 6500assert result.current_value is not None@@ -429,7 +429,7 @@ async def test_growth_rule_absolute_backfill(session: AsyncSession, test_user: U@pytest.mark.asyncio-async def test_growth_rule_future_start_no_backfill(session: AsyncSession, test_user: User):+async def test_growth_rule_future_start_no_backfill(session: AsyncSession, test_user: User, test_workspace):"""If growth_start_date is in the future, no rule values should be generated."""future = date.today() + timedelta(days=30)data = AssetCreate(@@ -442,7 +442,7 @@ async def test_growth_rule_future_start_no_backfill(session: AsyncSession, test_growth_frequency="monthly",growth_start_date=future,)- result = await asset_service.create_asset(session, test_user.id, data)+ result = await asset_service.create_asset(session, test_workspace.id, test_user.id, data)# Only the seed value, no rule-generated valuesassert result.value_count == 1@@ -450,7 +450,7 @@ async def test_growth_rule_future_start_no_backfill(session: AsyncSession, test_@pytest.mark.asyncio-async def test_growth_rule_daily_backfill(session: AsyncSession, test_user: User):+async def test_growth_rule_daily_backfill(session: AsyncSession, test_user: User, test_workspace):"""Daily growth rule should generate one value per day."""start = date.today() - timedelta(days=5)data = AssetCreate(@@ -463,7 +463,7 @@ async def test_growth_rule_daily_backfill(session: AsyncSession, test_user: Usergrowth_frequency="daily",growth_start_date=start,)- result = await asset_service.create_asset(session, test_user.id, data)+ result = await asset_service.create_asset(session, test_workspace.id, test_user.id, data)# seed + 5 daily values = 6assert result.value_count == 6@@ -473,7 +473,7 @@ async def test_growth_rule_daily_backfill(session: AsyncSession, test_user: User@pytest.mark.asyncio-async def test_growth_rule_weekly_backfill(session: AsyncSession, test_user: User):+async def test_growth_rule_weekly_backfill(session: AsyncSession, test_user: User, test_workspace):"""Weekly growth rule should generate one value per week."""start = date.today() - timedelta(weeks=3)data = AssetCreate(@@ -486,7 +486,7 @@ async def test_growth_rule_weekly_backfill(session: AsyncSession, test_user: Usegrowth_frequency="weekly",growth_start_date=start,)- result = await asset_service.create_asset(session, test_user.id, data)+ result = await asset_service.create_asset(session, test_workspace.id, test_user.id, data)# seed + 3 weekly values = 4assert result.value_count == 4@@ -500,49 +500,49 @@ async def test_growth_rule_weekly_backfill(session: AsyncSession, test_user: Use# ---------------------------------------------------------------------------@pytest.mark.asyncio-async def test_gain_loss_positive(session: AsyncSession, test_user: User):+async def test_gain_loss_positive(session: AsyncSession, test_user: User, test_workspace):"""Gain/loss should be positive when current value exceeds purchase price."""data = AssetCreate(name="Gainer", type="valuable", currency="BRL",purchase_price=Decimal("1000.00"),current_value=Decimal("1500.00"),)- result = await asset_service.create_asset(session, test_user.id, data)+ result = await asset_service.create_asset(session, test_workspace.id, test_user.id, data)assert result.gain_loss == 500.0@pytest.mark.asyncio-async def test_gain_loss_negative(session: AsyncSession, test_user: User):+async def test_gain_loss_negative(session: AsyncSession, test_user: User, test_workspace):"""Gain/loss should be negative when current value is below purchase price."""data = AssetCreate(name="Loser", type="vehicle", currency="BRL",purchase_price=Decimal("20000.00"),current_value=Decimal("15000.00"),)- result = await asset_service.create_asset(session, test_user.id, data)+ result = await asset_service.create_asset(session, test_workspace.id, test_user.id, data)assert result.gain_loss == -5000.0@pytest.mark.asyncio-async def test_gain_loss_zero_at_purchase_fallback(session: AsyncSession, test_user: User):+async def test_gain_loss_zero_at_purchase_fallback(session: AsyncSession, test_user: User, test_workspace):"""When falling back to purchase_price (no values), gain/loss should be 0."""data = AssetCreate(name="No Values", type="other", currency="BRL",purchase_price=Decimal("3000.00"),)- result = await asset_service.create_asset(session, test_user.id, data)+ result = await asset_service.create_asset(session, test_workspace.id, test_user.id, data)assert result.current_value == 3000.0assert result.gain_loss == 0.0@pytest.mark.asyncio-async def test_gain_loss_none_without_purchase_price(session: AsyncSession, test_user: User):+async def test_gain_loss_none_without_purchase_price(session: AsyncSession, test_user: User, test_workspace):"""Without a purchase_price, gain_loss should be None even if there's a current value."""data = AssetCreate(name="No Purchase", type="other", currency="BRL",current_value=Decimal("5000.00"),)- result = await asset_service.create_asset(session, test_user.id, data)+ result = await asset_service.create_asset(session, test_workspace.id, test_user.id, data)assert result.current_value == 5000.0assert result.gain_loss is None@@ -552,7 +552,7 @@ async def test_gain_loss_none_without_purchase_price(session: AsyncSession, test# ---------------------------------------------------------------------------@pytest.mark.asyncio-async def test_total_asset_value_includes_purchase_fallback(session: AsyncSession, test_user: User):+async def test_total_asset_value_includes_purchase_fallback(session: AsyncSession, test_user: User, test_workspace):"""Assets with only purchase_price (no values) should be included in totals."""asset = Asset(id=uuid.uuid4(),@@ -566,13 +566,13 @@ async def test_total_asset_value_includes_purchase_fallback(session: AsyncSessiosession.add(asset)await session.commit()- totals, _ = await asset_service.get_asset_values_at(session, test_user.id)+ totals, _ = await asset_service.get_asset_values_at(session, test_workspace.id, by_workspace=True)assert "BRL" in totalsassert totals["BRL"] >= 200000.0@pytest.mark.asyncio-async def test_total_asset_value_excludes_archived(session: AsyncSession, test_user: User):+async def test_total_asset_value_excludes_archived(session: AsyncSession, test_user: User, test_workspace):"""Archived assets should not count in total."""asset = Asset(id=uuid.uuid4(),@@ -587,7 +587,7 @@ async def test_total_asset_value_excludes_archived(session: AsyncSession, test_usession.add(asset)await session.commit()- totals, _ = await asset_service.get_asset_values_at(session, test_user.id)+ totals, _ = await asset_service.get_asset_values_at(session, test_workspace.id, by_workspace=True)# If this is the only asset, BRL should not be in totals (or should not include 999999)assert totals.get("BRL", 0) < 999999.0@@ -716,7 +716,7 @@ def test_compute_current_value_none_without_data():@pytest.mark.asyncio-async def test_update_asset_regenerate_growth(session: AsyncSession, test_user: User):+async def test_update_asset_regenerate_growth(session: AsyncSession, test_user: User, test_workspace):purchase_date = date.today() - timedelta(days=60)data = AssetCreate(name="Regen Asset", type="investment", currency="BRL",@@ -724,62 +724,62 @@ async def test_update_asset_regenerate_growth(session: AsyncSession, test_user:purchase_date=purchase_date, purchase_price=Decimal("5000"),growth_type="percentage", growth_rate=Decimal("3"), growth_frequency="monthly",)- created = await asset_service.create_asset(session, test_user.id, data)+ created = await asset_service.create_asset(session, test_workspace.id, test_user.id, data)update_data = AssetUpdate(growth_rate=Decimal("5"))updated = await asset_service.update_asset(- session, created.id, test_user.id, update_data, regenerate_growth=True,+ session, created.id, test_workspace.id, test_user.id, update_data, regenerate_growth=True,)assert updated is not Noneassert updated.name == "Regen Asset"@pytest.mark.asyncio-async def test_update_asset_purchase_price(session: AsyncSession, test_user: User):+async def test_update_asset_purchase_price(session: AsyncSession, test_user: User, test_workspace):data = AssetCreate(name="Price Update", type="other", currency="BRL",purchase_price=Decimal("1000"),)- created = await asset_service.create_asset(session, test_user.id, data)+ created = await asset_service.create_asset(session, test_workspace.id, test_user.id, data)update_data = AssetUpdate(purchase_price=Decimal("2000"))- updated = await asset_service.update_asset(session, created.id, test_user.id, update_data)+ updated = await asset_service.update_asset(session, created.id, test_workspace.id, test_user.id, update_data)assert updated.purchase_price == 2000.0@pytest.mark.asyncio-async def test_get_asset_values_not_found(session: AsyncSession, test_user: User):- result = await asset_service.get_asset_values(session, uuid.uuid4(), test_user.id)+async def test_get_asset_values_not_found(session: AsyncSession, test_user: User, test_workspace):+ result = await asset_service.get_asset_values(session, uuid.uuid4(), test_workspace.id)assert result is None@pytest.mark.asyncio-async def test_add_asset_value_not_found(session: AsyncSession, test_user: User):+async def test_add_asset_value_not_found(session: AsyncSession, test_user: User, test_workspace):val_data = AssetValueCreate(amount=Decimal("100"), date=date.today())- result = await asset_service.add_asset_value(session, uuid.uuid4(), test_user.id, val_data)+ result = await asset_service.add_asset_value(session, uuid.uuid4(), test_workspace.id, val_data)assert result is None@pytest.mark.asyncio-async def test_delete_asset_value_not_found(session: AsyncSession, test_user: User):- assert await asset_service.delete_asset_value(session, uuid.uuid4(), test_user.id) is False+async def test_delete_asset_value_not_found(session: AsyncSession, test_user: User, test_workspace):+ assert await asset_service.delete_asset_value(session, uuid.uuid4(), test_workspace.id) is False@pytest.mark.asyncio-async def test_get_asset_value_trend_not_found(session: AsyncSession, test_user: User):- result = await asset_service.get_asset_value_trend(session, uuid.uuid4(), test_user.id)+async def test_get_asset_value_trend_not_found(session: AsyncSession, test_user: User, test_workspace):+ result = await asset_service.get_asset_value_trend(session, uuid.uuid4(), test_workspace.id)assert result is None@pytest.mark.asyncio-async def test_portfolio_trend_empty(session: AsyncSession, test_user: User):- result = await get_portfolio_trend(session, test_user.id)+async def test_portfolio_trend_empty(session: AsyncSession, test_user: User, test_workspace):+ result = await get_portfolio_trend(session, test_workspace.id, test_user.id)assert result["assets"] == []assert result["trend"] == []assert result["total"] == 0.0@pytest.mark.asyncio-async def test_portfolio_trend_with_assets(session: AsyncSession, test_user: User):+async def test_portfolio_trend_with_assets(session: AsyncSession, test_user: User, test_workspace):a1 = AssetCreate(name="House", type="real_estate", currency="BRL",purchase_date=date.today() - timedelta(days=30),@@ -790,10 +790,10 @@ async def test_portfolio_trend_with_assets(session: AsyncSession, test_user: Usepurchase_date=date.today() - timedelta(days=10),purchase_price=Decimal("50000"), current_value=Decimal("45000"),)- await asset_service.create_asset(session, test_user.id, a1)- await asset_service.create_asset(session, test_user.id, a2)+ await asset_service.create_asset(session, test_workspace.id, test_user.id, a1)+ await asset_service.create_asset(session, test_workspace.id, test_user.id, a2)- result = await get_portfolio_trend(session, test_user.id)+ result = await get_portfolio_trend(session, test_workspace.id, test_user.id)assert len(result["assets"]) == 2assert len(result["trend"]) > 0assert result["total"] > 0@@ -801,7 +801,7 @@ async def test_portfolio_trend_with_assets(session: AsyncSession, test_user: Use@pytest.mark.asyncioasync def test_portfolio_trend_total_consistent_with_get_asset_values_at(- session: AsyncSession, test_user: User+ session: AsyncSession, test_user: User, test_workspace,):"""portfolio trend _total must match get_asset_values_at at the same date.@@ -853,10 +853,11 @@ async def test_portfolio_trend_total_consistent_with_get_asset_values_at(await session.commit()- trend_result = await get_portfolio_trend(session, test_user.id)+ trend_result = await get_portfolio_trend(session, test_workspace.id, test_user.id)_, values_at_total = await asset_service.get_asset_values_at(- session, test_user.id, as_of_date=date_mar,+ session, test_workspace.id, as_of_date=date_mar,primary_currency=test_user.primary_currency,+ by_workspace=True,)# At date_mar: USD 100 @ 6.0 = BRL 600, plus BRL 1000 = 1600@@ -866,29 +867,29 @@ async def test_portfolio_trend_total_consistent_with_get_asset_values_at(@pytest.mark.asyncio-async def test_get_assets_include_archived(session: AsyncSession, test_user: User):+async def test_get_assets_include_archived(session: AsyncSession, test_user: User, test_workspace):await asset_service.create_asset(- session, test_user.id, AssetCreate(name="A1", type="other", currency="BRL"),+ session, test_workspace.id, test_user.id, AssetCreate(name="A1", type="other", currency="BRL"),)await asset_service.create_asset(- session, test_user.id, AssetCreate(name="A2", type="other", currency="BRL", is_archived=True),+ session, test_workspace.id, test_user.id, AssetCreate(name="A2", type="other", currency="BRL", is_archived=True),)- assets = await asset_service.get_assets(session, test_user.id, include_archived=True)+ assets = await asset_service.get_assets(session, test_workspace.id, include_archived=True)names = [a.name for a in assets]assert "A1" in namesassert "A2" in names@pytest.mark.asyncio-async def test_get_assets_excludes_archived_by_default(session: AsyncSession, test_user: User):+async def test_get_assets_excludes_archived_by_default(session: AsyncSession, test_user: User, test_workspace):await asset_service.create_asset(- session, test_user.id, AssetCreate(name="Visible", type="other", currency="BRL"),+ session, test_workspace.id, test_user.id, AssetCreate(name="Visible", type="other", currency="BRL"),)await asset_service.create_asset(- session, test_user.id, AssetCreate(name="Archived", type="other", currency="BRL", is_archived=True),+ session, test_workspace.id, test_user.id, AssetCreate(name="Archived", type="other", currency="BRL", is_archived=True),)- assets = await asset_service.get_assets(session, test_user.id)+ assets = await asset_service.get_assets(session, test_workspace.id)names = [a.name for a in assets]assert "Visible" in namesassert "Archived" not in namesdiff --git a/backend/tests/test_attachment_service.py b/backend/tests/test_attachment_service.pyindex 7c264b87..9742773e 100644--- a/backend/tests/test_attachment_service.py+++ b/backend/tests/test_attachment_service.py@@ -117,21 +117,21 @@ async def txn_for_attach(session: AsyncSession, test_user, txn_account):# ----------------------------------------------------------------------------async def test_upload_attachment(session: AsyncSession, test_user, txn_for_attach):+async def test_upload_attachment(session: AsyncSession, test_user, test_workspace, txn_for_attach):mock_storage = AsyncMock()mock_storage.upload = AsyncMock(return_value=StoredFile(storage_key="test/key", size=100, content_type="application/pdf",))with patch("app.services.attachment_service.get_storage_provider", return_value=mock_storage):att = await upload_attachment(- session, test_user.id, txn_for_attach.id,+ session, test_workspace.id, test_user.id, txn_for_attach.id,"receipt.pdf", "application/pdf", b"fake-data",)assert att.filename == "receipt.pdf"assert att.transaction_id == txn_for_attach.id-async def test_upload_attachment_max_limit(session: AsyncSession, test_user, txn_for_attach):+async def test_upload_attachment_max_limit(session: AsyncSession, test_user, test_workspace, txn_for_attach):"""Exceeding max attachments per transaction raises ValueError."""# Pre-seed attachments up to the limitfrom app.core.config import get_settings@@ -151,18 +151,18 @@ async def test_upload_attachment_max_limit(session: AsyncSession, test_user, txnwith patch("app.services.attachment_service.get_storage_provider", return_value=mock_storage):with pytest.raises(ValueError, match="Maximum"):await upload_attachment(- session, test_user.id, txn_for_attach.id,+ session, test_workspace.id, test_user.id, txn_for_attach.id,"extra.pdf", "application/pdf", b"data",)-async def test_upload_wrong_transaction(session: AsyncSession, test_user, txn_for_attach):+async def test_upload_wrong_transaction(session: AsyncSession, test_user, test_workspace, txn_for_attach):"""Uploading to a non-existent transaction raises LookupError."""mock_storage = AsyncMock()with patch("app.services.attachment_service.get_storage_provider", return_value=mock_storage):with pytest.raises(LookupError, match="not found"):await upload_attachment(- session, test_user.id, uuid.uuid4(),+ session, test_workspace.id, test_user.id, uuid.uuid4(),"file.pdf", "application/pdf", b"data",)@@ -172,8 +172,8 @@ async def test_upload_wrong_transaction(session: AsyncSession, test_user, txn_fo# ----------------------------------------------------------------------------async def test_list_attachments_empty(session: AsyncSession, test_user, txn_for_attach):- result = await list_attachments(session, test_user.id, txn_for_attach.id)+async def test_list_attachments_empty(session: AsyncSession, test_user, test_workspace, txn_for_attach):+ result = await list_attachments(session, test_workspace.id, txn_for_attach.id)assert result == []@@ -182,7 +182,7 @@ async def test_list_attachments_empty(session: AsyncSession, test_user, txn_for_# ----------------------------------------------------------------------------async def test_download_attachment(session: AsyncSession, test_user, txn_for_attach):+async def test_download_attachment(session: AsyncSession, test_user, test_workspace, txn_for_attach):att = TransactionAttachment(id=uuid.uuid4(), user_id=test_user.id, transaction_id=txn_for_attach.id,filename="dl.pdf", storage_key="dl/key", content_type="application/pdf", size=5,@@ -193,14 +193,14 @@ async def test_download_attachment(session: AsyncSession, test_user, txn_for_attmock_storage = AsyncMock()mock_storage.download = AsyncMock(return_value=b"pdf-bytes")with patch("app.services.attachment_service.get_storage_provider", return_value=mock_storage):- result_att, data = await download_attachment(session, att.id, test_user.id)+ result_att, data = await download_attachment(session, att.id, test_workspace.id)assert data == b"pdf-bytes"assert result_att.filename == "dl.pdf"-async def test_download_attachment_not_found(session: AsyncSession, test_user):+async def test_download_attachment_not_found(session: AsyncSession, test_user, test_workspace):with pytest.raises(LookupError, match="not found"):- await download_attachment(session, uuid.uuid4(), test_user.id)+ await download_attachment(session, uuid.uuid4(), test_workspace.id)# ---------------------------------------------------------------------------@@ -208,7 +208,7 @@ async def test_download_attachment_not_found(session: AsyncSession, test_user):# ----------------------------------------------------------------------------async def test_rename_preserves_extension(session: AsyncSession, test_user, txn_for_attach):+async def test_rename_preserves_extension(session: AsyncSession, test_user, test_workspace, txn_for_attach):att = TransactionAttachment(id=uuid.uuid4(), user_id=test_user.id, transaction_id=txn_for_attach.id,filename="original.pdf", storage_key="ren/key", content_type="application/pdf", size=5,@@ -216,12 +216,12 @@ async def test_rename_preserves_extension(session: AsyncSession, test_user, txn_session.add(att)await session.commit()- result = await rename_attachment(session, att.id, test_user.id, "newname.txt")+ result = await rename_attachment(session, att.id, test_workspace.id, "newname.txt")# Original extension .pdf should be preservedassert result.filename == "newname.pdf"-async def test_rename_same_extension(session: AsyncSession, test_user, txn_for_attach):+async def test_rename_same_extension(session: AsyncSession, test_user, test_workspace, txn_for_attach):att = TransactionAttachment(id=uuid.uuid4(), user_id=test_user.id, transaction_id=txn_for_attach.id,filename="doc.pdf", storage_key="ren2/key", content_type="application/pdf", size=5,@@ -229,13 +229,13 @@ async def test_rename_same_extension(session: AsyncSession, test_user, txn_for_asession.add(att)await session.commit()- result = await rename_attachment(session, att.id, test_user.id, "renamed.pdf")+ result = await rename_attachment(session, att.id, test_workspace.id, "renamed.pdf")assert result.filename == "renamed.pdf"-async def test_rename_not_found(session: AsyncSession, test_user):+async def test_rename_not_found(session: AsyncSession, test_user, test_workspace):with pytest.raises(LookupError, match="not found"):- await rename_attachment(session, uuid.uuid4(), test_user.id, "x.pdf")+ await rename_attachment(session, uuid.uuid4(), test_workspace.id, "x.pdf")# ---------------------------------------------------------------------------@@ -243,7 +243,7 @@ async def test_rename_not_found(session: AsyncSession, test_user):# ----------------------------------------------------------------------------async def test_delete_attachment(session: AsyncSession, test_user, txn_for_attach):+async def test_delete_attachment(session: AsyncSession, test_user, test_workspace, txn_for_attach):att = TransactionAttachment(id=uuid.uuid4(), user_id=test_user.id, transaction_id=txn_for_attach.id,filename="del.pdf", storage_key="del/key", content_type="application/pdf", size=5,@@ -253,15 +253,15 @@ async def test_delete_attachment(session: AsyncSession, test_user, txn_for_attacmock_storage = AsyncMock()with patch("app.services.attachment_service.get_storage_provider", return_value=mock_storage):- await delete_attachment(session, att.id, test_user.id)+ await delete_attachment(session, att.id, test_workspace.id)mock_storage.delete.assert_called_once_with("del/key")-async def test_delete_attachment_not_found(session: AsyncSession, test_user):+async def test_delete_attachment_not_found(session: AsyncSession, test_user, test_workspace):mock_storage = AsyncMock()with patch("app.services.attachment_service.get_storage_provider", return_value=mock_storage):with pytest.raises(LookupError, match="not found"):- await delete_attachment(session, uuid.uuid4(), test_user.id)+ await delete_attachment(session, uuid.uuid4(), test_workspace.id)# ---------------------------------------------------------------------------diff --git a/backend/tests/test_balance_service.py b/backend/tests/test_balance_service.pyindex d2842fd6..84009479 100644--- a/backend/tests/test_balance_service.py+++ b/backend/tests/test_balance_service.py@@ -52,25 +52,35 @@ async def _make_tx(session, user_id, account_id, amount, currency="USD") -> Tranreturn tx-async def _setup(session, test_user, n_others=2):+async def _setup(session, test_user, workspace_id, n_others=2):group = await group_service.create_group(- session, test_user.id, GroupCreate(name="Trip")+ session, workspace_id, test_user.id, GroupCreate(name="Trip"))self_member = await group_service.create_member(- session, group.id, test_user.id, GroupMemberCreate(name="Me", is_self=True)+ session,+ group.id,+ workspace_id,+ GroupMemberCreate(name="Me", is_self=True),)others = []for i in range(n_others):m = await group_service.create_member(- session, group.id, test_user.id, GroupMemberCreate(name=f"Friend{i}")+ session,+ group.id,+ workspace_id,+ GroupMemberCreate(name=f"Friend{i}"),)others.append(m)return group, self_member, others@pytest.mark.asyncio-async def test_balances_each_friend_owes_their_share(session: AsyncSession, test_user):- group, self_m, friends = await _setup(session, test_user, n_others=3)+async def test_balances_each_friend_owes_their_share(+ session: AsyncSession, test_user, test_workspace+):+ group, self_m, friends = await _setup(+ session, test_user, test_workspace.id, n_others=3+ )account = await _make_account(session, test_user.id)tx = await _make_tx(session, test_user.id, account.id, "120.00")@@ -84,7 +94,9 @@ async def test_balances_each_friend_owes_their_share(session: AsyncSession, testawait split_service.replace_splits(session, tx, payload, test_user.id)await session.commit()- balances = await balance_service.compute_balances(session, group.id, test_user.id)+ balances = await balance_service.compute_balances(+ session, group.id, test_workspace.id, test_user.id+ )assert balances is not Noneby_member = {ln["member_id"]: ln["amount"] for ln in balances["lines"]}# Each friend owes 30.00, self balance line excluded.@@ -94,8 +106,12 @@ async def test_balances_each_friend_owes_their_share(session: AsyncSession, test@pytest.mark.asyncio-async def test_settlement_reduces_balance(session: AsyncSession, test_user):- group, self_m, friends = await _setup(session, test_user, n_others=2)+async def test_settlement_reduces_balance(+ session: AsyncSession, test_user, test_workspace+):+ group, self_m, friends = await _setup(+ session, test_user, test_workspace.id, n_others=2+ )friend = friends[0]account = await _make_account(session, test_user.id)tx = await _make_tx(session, test_user.id, account.id, "100.00")@@ -120,6 +136,7 @@ async def test_settlement_reduces_balance(session: AsyncSession, test_user):await settlement_service.create_settlement(session,group.id,+ test_workspace.id,test_user.id,GroupSettlementCreate(from_member_id=friend.id,@@ -131,21 +148,28 @@ async def test_settlement_reduces_balance(session: AsyncSession, test_user):)await session.commit()- balances = await balance_service.compute_balances(session, group.id, test_user.id)+ balances = await balance_service.compute_balances(+ session, group.id, test_workspace.id, test_user.id+ )by_member = {ln["member_id"]: ln["amount"] for ln in balances["lines"]}assert by_member[friend.id] == Decimal("15.00")@pytest.mark.asyncio-async def test_self_loan_increases_balance_owed(session: AsyncSession, test_user):+async def test_self_loan_increases_balance_owed(+ session: AsyncSession, test_user, test_workspace+):"""Self lending money to a friend should make them owe more, evenwithout an associated split (e.g. a direct cash advance)."""- group, self_m, friends = await _setup(session, test_user, n_others=1)+ group, self_m, friends = await _setup(+ session, test_user, test_workspace.id, n_others=1+ )friend = friends[0]await settlement_service.create_settlement(session,group.id,+ test_workspace.id,test_user.id,GroupSettlementCreate(from_member_id=self_m.id,@@ -157,14 +181,20 @@ async def test_self_loan_increases_balance_owed(session: AsyncSession, test_user)await session.commit()- balances = await balance_service.compute_balances(session, group.id, test_user.id)+ balances = await balance_service.compute_balances(+ session, group.id, test_workspace.id, test_user.id+ )by_member = {ln["member_id"]: ln["amount"] for ln in balances["lines"]}assert by_member[friend.id] == Decimal("50.00")@pytest.mark.asyncio-async def test_balances_segregated_by_currency(session: AsyncSession, test_user):- group, self_m, friends = await _setup(session, test_user, n_others=1)+async def test_balances_segregated_by_currency(+ session: AsyncSession, test_user, test_workspace+):+ group, self_m, friends = await _setup(+ session, test_user, test_workspace.id, n_others=1+ )friend = friends[0]account = await _make_account(session, test_user.id)@@ -186,19 +216,27 @@ async def test_balances_segregated_by_currency(session: AsyncSession, test_user))await session.commit()- balances = await balance_service.compute_balances(session, group.id, test_user.id)- by_currency = {ln["currency"]: ln["amount"] for ln in balances["lines"] if ln["member_id"] == friend.id}+ balances = await balance_service.compute_balances(+ session, group.id, test_workspace.id, test_user.id+ )+ by_currency = {+ ln["currency"]: ln["amount"]+ for ln in balances["lines"]+ if ln["member_id"] == friend.id+ }assert by_currency["USD"] == Decimal("30.00")assert by_currency["EUR"] == Decimal("20.00")@pytest.mark.asyncioasync def test_balance_line_dropped_when_settlement_zeroes_out_split(- session: AsyncSession, test_user+ session: AsyncSession, test_user, test_workspace):"""A friend who pays back exactly their share should drop off thebalance ledger — no zero-amount line should be returned."""- group, self_m, friends = await _setup(session, test_user, n_others=1)+ group, self_m, friends = await _setup(+ session, test_user, test_workspace.id, n_others=1+ )friend = friends[0]account = await _make_account(session, test_user.id)tx = await _make_tx(session, test_user.id, account.id, "40.00")@@ -219,6 +257,7 @@ async def test_balance_line_dropped_when_settlement_zeroes_out_split(await settlement_service.create_settlement(session,group.id,+ test_workspace.id,test_user.id,GroupSettlementCreate(from_member_id=friend.id,@@ -231,7 +270,7 @@ async def test_balance_line_dropped_when_settlement_zeroes_out_split(await session.commit()balances = await balance_service.compute_balances(- session, group.id, test_user.id+ session, group.id, test_workspace.id, test_user.id)friend_lines = [ln for ln in balances["lines"] if ln["member_id"] == friend.id]assert friend_lines == []@@ -239,11 +278,13 @@ async def test_balance_line_dropped_when_settlement_zeroes_out_split(@pytest.mark.asyncioasync def test_cross_member_settlements_are_ignored_in_owner_ledger(- session: AsyncSession, test_user+ session: AsyncSession, test_user, test_workspace):"""Settlements between two non-self members don't affect theowner-ledger view (balance_service is owner-centric in v1)."""- group, self_m, friends = await _setup(session, test_user, n_others=2)+ group, self_m, friends = await _setup(+ session, test_user, test_workspace.id, n_others=2+ )a, b = friendsaccount = await _make_account(session, test_user.id)@@ -266,6 +307,7 @@ async def test_cross_member_settlements_are_ignored_in_owner_ledger(await settlement_service.create_settlement(session,group.id,+ test_workspace.id,test_user.id,GroupSettlementCreate(from_member_id=a.id,@@ -278,7 +320,7 @@ async def test_cross_member_settlements_are_ignored_in_owner_ledger(await session.commit()balances = await balance_service.compute_balances(- session, group.id, test_user.id+ session, group.id, test_workspace.id, test_user.id)by_member = {ln["member_id"]: ln["amount"] for ln in balances["lines"]}# A still owes their original $15 — not adjusted by the cross-member tx.@@ -289,18 +331,18 @@ async def test_cross_member_settlements_are_ignored_in_owner_ledger(@pytest.mark.asyncioasync def test_no_self_member_means_only_split_totals(- session: AsyncSession, test_user+ session: AsyncSession, test_user, test_workspace):"""Without a self member, settlements can't be applied (cross-membersettlements are out of scope for v1) — only split shares accumulate."""group = await group_service.create_group(- session, test_user.id, GroupCreate(name="NoSelf")+ session, test_workspace.id, test_user.id, GroupCreate(name="NoSelf"))a = await group_service.create_member(- session, group.id, test_user.id, GroupMemberCreate(name="A")+ session, group.id, test_workspace.id, GroupMemberCreate(name="A"))b = await group_service.create_member(- session, group.id, test_user.id, GroupMemberCreate(name="B")+ session, group.id, test_workspace.id, GroupMemberCreate(name="B"))account = await _make_account(session, test_user.id)tx = await _make_tx(session, test_user.id, account.id, "20.00")@@ -318,7 +360,9 @@ async def test_no_self_member_means_only_split_totals()await session.commit()- balances = await balance_service.compute_balances(session, group.id, test_user.id)+ balances = await balance_service.compute_balances(+ session, group.id, test_workspace.id, test_user.id+ )by_member = {ln["member_id"]: ln["amount"] for ln in balances["lines"]}assert by_member[a.id] == Decimal("10.00")assert by_member[b.id] == Decimal("10.00")diff --git a/backend/tests/test_budget_service.py b/backend/tests/test_budget_service.pyindex 7bdd1d18..7e919742 100644--- a/backend/tests/test_budget_service.py+++ b/backend/tests/test_budget_service.py@@ -25,13 +25,13 @@ from app.services.budget_service import (@pytest.mark.asyncio-async def test_create_budget(session: AsyncSession, test_user, test_categories):+async def test_create_budget(session: AsyncSession, test_user, test_workspace, test_categories):data = BudgetCreate(category_id=test_categories[0].id,amount=Decimal("500.00"),month=date(2025, 3, 15), # mid-month — should normalize to day=1)- budget = await create_budget(session, test_user.id, data)+ budget = await create_budget(session, test_workspace.id, test_user.id, data)assert budget.id is not Noneassert budget.amount == Decimal("500.00")@@ -40,14 +40,14 @@ async def test_create_budget(session: AsyncSession, test_user, test_categories):@pytest.mark.asyncio-async def test_create_recurring_budget(session: AsyncSession, test_user, test_categories):+async def test_create_recurring_budget(session: AsyncSession, test_user, test_workspace, test_categories):data = BudgetCreate(category_id=test_categories[0].id,amount=Decimal("300.00"),month=date(2025, 1, 1),is_recurring=True,)- budget = await create_budget(session, test_user.id, data)+ budget = await create_budget(session, test_workspace.id, test_user.id, data)assert budget.is_recurring is Trueassert budget.month == date(2025, 1, 1)@@ -59,9 +59,10 @@ async def test_create_recurring_budget(session: AsyncSession, test_user, test_ca@pytest.mark.asyncio-async def test_get_budgets_all(session: AsyncSession, test_user, test_categories):+async def test_get_budgets_all(session: AsyncSession, test_user, test_workspace, test_categories):await create_budget(session,+ test_workspace.id,test_user.id,BudgetCreate(category_id=test_categories[0].id,@@ -71,6 +72,7 @@ async def test_get_budgets_all(session: AsyncSession, test_user, test_categories)await create_budget(session,+ test_workspace.id,test_user.id,BudgetCreate(category_id=test_categories[1].id,@@ -79,15 +81,16 @@ async def test_get_budgets_all(session: AsyncSession, test_user, test_categories),)- budgets = await get_budgets(session, test_user.id)+ budgets = await get_budgets(session, test_workspace.id)assert len(budgets) >= 2@pytest.mark.asyncio-async def test_get_budgets_with_month_filter(session: AsyncSession, test_user, test_categories):+async def test_get_budgets_with_month_filter(session: AsyncSession, test_user, test_workspace, test_categories):# Recurring default for Janawait create_budget(session,+ test_workspace.id,test_user.id,BudgetCreate(category_id=test_categories[0].id,@@ -99,6 +102,7 @@ async def test_get_budgets_with_month_filter(session: AsyncSession, test_user, t# Month-specific override for Marchawait create_budget(session,+ test_workspace.id,test_user.id,BudgetCreate(category_id=test_categories[0].id,@@ -109,7 +113,7 @@ async def test_get_budgets_with_month_filter(session: AsyncSession, test_user, t)# Querying March should get the override, not the recurring- budgets = await get_budgets(session, test_user.id, month=date(2025, 3, 1))+ budgets = await get_budgets(session, test_workspace.id, month=date(2025, 3, 1))cat0_budgets = [b for b in budgets if b.category_id == test_categories[0].id]assert len(cat0_budgets) == 1assert cat0_budgets[0].amount == Decimal("999")@@ -118,11 +122,12 @@ async def test_get_budgets_with_month_filter(session: AsyncSession, test_user, t@pytest.mark.asyncioasync def test_get_budgets_recurring_default_for_future(- session: AsyncSession, test_user, test_categories+ session: AsyncSession, test_user, test_workspace, test_categories):# Recurring from Jan carries forward to Juneawait create_budget(session,+ test_workspace.id,test_user.id,BudgetCreate(category_id=test_categories[1].id,@@ -132,7 +137,7 @@ async def test_get_budgets_recurring_default_for_future(),)- budgets = await get_budgets(session, test_user.id, month=date(2025, 6, 1))+ budgets = await get_budgets(session, test_workspace.id, month=date(2025, 6, 1))cat1_budgets = [b for b in budgets if b.category_id == test_categories[1].id]assert len(cat1_budgets) == 1assert cat1_budgets[0].amount == Decimal("250")@@ -144,9 +149,10 @@ async def test_get_budgets_recurring_default_for_future(@pytest.mark.asyncio-async def test_get_budget_by_id(session: AsyncSession, test_user, test_categories):+async def test_get_budget_by_id(session: AsyncSession, test_user, test_workspace, test_categories):created = await create_budget(session,+ test_workspace.id,test_user.id,BudgetCreate(category_id=test_categories[0].id,@@ -154,14 +160,14 @@ async def test_get_budget_by_id(session: AsyncSession, test_user, test_categoriemonth=date(2025, 4, 1),),)- fetched = await get_budget(session, created.id, test_user.id)+ fetched = await get_budget(session, created.id, test_workspace.id)assert fetched is not Noneassert fetched.id == created.id@pytest.mark.asyncio-async def test_get_budget_not_found(session: AsyncSession, test_user):- result = await get_budget(session, uuid.uuid4(), test_user.id)+async def test_get_budget_not_found(session: AsyncSession, test_user, test_workspace):+ result = await get_budget(session, uuid.uuid4(), test_workspace.id)assert result is None@@ -171,9 +177,10 @@ async def test_get_budget_not_found(session: AsyncSession, test_user):@pytest.mark.asyncio-async def test_update_budget_in_place(session: AsyncSession, test_user, test_categories):+async def test_update_budget_in_place(session: AsyncSession, test_user, test_workspace, test_categories):budget = await create_budget(session,+ test_workspace.id,test_user.id,BudgetCreate(category_id=test_categories[0].id,@@ -182,7 +189,7 @@ async def test_update_budget_in_place(session: AsyncSession, test_user, test_cat),)updated = await update_budget(- session, budget.id, test_user.id, BudgetUpdate(amount=Decimal("777"))+ session, budget.id, test_workspace.id, BudgetUpdate(amount=Decimal("777")))assert updated is not None@@ -192,10 +199,11 @@ async def test_update_budget_in_place(session: AsyncSession, test_user, test_cat@pytest.mark.asyncioasync def test_update_recurring_different_effective_month_creates_new(- session: AsyncSession, test_user, test_categories+ session: AsyncSession, test_user, test_workspace, test_categories):budget = await create_budget(session,+ test_workspace.id,test_user.id,BudgetCreate(category_id=test_categories[0].id,@@ -207,7 +215,7 @@ async def test_update_recurring_different_effective_month_creates_new(updated = await update_budget(session,budget.id,- test_user.id,+ test_workspace.id,BudgetUpdate(amount=Decimal("200"), effective_month=date(2025, 6, 1)),)@@ -219,9 +227,9 @@ async def test_update_recurring_different_effective_month_creates_new(@pytest.mark.asyncio-async def test_update_budget_not_found(session: AsyncSession, test_user):+async def test_update_budget_not_found(session: AsyncSession, test_user, test_workspace):result = await update_budget(- session, uuid.uuid4(), test_user.id, BudgetUpdate(amount=Decimal("1"))+ session, uuid.uuid4(), test_workspace.id, BudgetUpdate(amount=Decimal("1")))assert result is None@@ -232,9 +240,10 @@ async def test_update_budget_not_found(session: AsyncSession, test_user):@pytest.mark.asyncio-async def test_delete_budget(session: AsyncSession, test_user, test_categories):+async def test_delete_budget(session: AsyncSession, test_user, test_workspace, test_categories):budget = await create_budget(session,+ test_workspace.id,test_user.id,BudgetCreate(category_id=test_categories[0].id,@@ -242,13 +251,13 @@ async def test_delete_budget(session: AsyncSession, test_user, test_categories):month=date(2025, 7, 1),),)- assert await delete_budget(session, budget.id, test_user.id) is True- assert await get_budget(session, budget.id, test_user.id) is None+ assert await delete_budget(session, budget.id, test_workspace.id) is True+ assert await get_budget(session, budget.id, test_workspace.id) is None@pytest.mark.asyncio-async def test_delete_budget_not_found(session: AsyncSession, test_user):- assert await delete_budget(session, uuid.uuid4(), test_user.id) is False+async def test_delete_budget_not_found(session: AsyncSession, test_user, test_workspace):+ assert await delete_budget(session, uuid.uuid4(), test_workspace.id) is False# ---------------------------------------------------------------------------@@ -257,7 +266,7 @@ async def test_delete_budget_not_found(session: AsyncSession, test_user):@pytest.mark.asyncio-async def test_get_budget_vs_actual(session: AsyncSession, test_user, test_categories):+async def test_get_budget_vs_actual(session: AsyncSession, test_user, test_workspace, test_categories):# Need a category group for budget_vs_actual joingroup = CategoryGroup(id=uuid.uuid4(),@@ -290,6 +299,7 @@ async def test_get_budget_vs_actual(session: AsyncSession, test_user, test_categ# Create budget for March 2025await create_budget(session,+ test_workspace.id,test_user.id,BudgetCreate(category_id=test_categories[0].id,@@ -314,7 +324,7 @@ async def test_get_budget_vs_actual(session: AsyncSession, test_user, test_categsession.add(txn)await session.commit()- comparisons = await get_budget_vs_actual(session, test_user.id, month=date(2025, 3, 1))+ comparisons = await get_budget_vs_actual(session, test_workspace.id, test_user.id, month=date(2025, 3, 1))assert len(comparisons) > 0cat0_comp = [c for c in comparisons if c.category_id == test_categories[0].id]@@ -326,7 +336,7 @@ async def test_get_budget_vs_actual(session: AsyncSession, test_user, test_categ@pytest.mark.asyncioasync def test_budget_vs_actual_excludes_transfers(- session: AsyncSession, test_user, test_categories+ session: AsyncSession, test_user, test_workspace, test_categories):account = Account(id=uuid.uuid4(),@@ -370,7 +380,7 @@ async def test_budget_vs_actual_excludes_transfers(session.add_all(txns)await session.commit()- comparisons = await get_budget_vs_actual(session, test_user.id, month=date(2025, 4, 1))+ comparisons = await get_budget_vs_actual(session, test_workspace.id, test_user.id, month=date(2025, 4, 1))cat0 = [c for c in comparisons if c.category_id == test_categories[0].id]if cat0:assert cat0[0].actual_amount == Decimal("50")@@ -378,7 +388,7 @@ async def test_budget_vs_actual_excludes_transfers(@pytest.mark.asyncioasync def test_budget_vs_actual_includes_prev_month(- session: AsyncSession, test_user, test_categories+ session: AsyncSession, test_user, test_workspace, test_categories):account = Account(id=uuid.uuid4(),@@ -420,7 +430,7 @@ async def test_budget_vs_actual_includes_prev_month(session.add_all([txn_prev, txn_curr])await session.commit()- comparisons = await get_budget_vs_actual(session, test_user.id, month=date(2025, 3, 1))+ comparisons = await get_budget_vs_actual(session, test_workspace.id, test_user.id, month=date(2025, 3, 1))cat0 = [c for c in comparisons if c.category_id == test_categories[0].id]if cat0:assert cat0[0].prev_month_amount == Decimal("75")diff --git a/backend/tests/test_category_group_service.py b/backend/tests/test_category_group_service.pyindex 0ba241a4..dcaae54b 100644--- a/backend/tests/test_category_group_service.py+++ b/backend/tests/test_category_group_service.py@@ -23,7 +23,7 @@ from app.services.category_group_service import (@pytest.mark.asyncio-async def test_create_default_groups(session: AsyncSession, test_user):+async def test_create_default_groups(session: AsyncSession, test_user, test_workspace):groups = await create_default_groups(session, test_user.id, lang="pt-BR")await session.commit()@@ -43,7 +43,7 @@ async def test_create_default_groups(session: AsyncSession, test_user):@pytest.mark.asyncio-async def test_create_default_groups_english(session: AsyncSession, test_user):+async def test_create_default_groups_english(session: AsyncSession, test_user, test_workspace):groups = await create_default_groups(session, test_user.id, lang="en")await session.commit()@@ -57,11 +57,11 @@ async def test_create_default_groups_english(session: AsyncSession, test_user):@pytest.mark.asyncio-async def test_get_groups_ordered_by_position(session: AsyncSession, test_user):+async def test_get_groups_ordered_by_position(session: AsyncSession, test_user, test_workspace):await create_default_groups(session, test_user.id)await session.commit()- groups = await get_groups(session, test_user.id)+ groups = await get_groups(session, test_workspace.id)assert len(groups) == len(DEFAULT_GROUPS_I18N)positions = [g.position for g in groups]@@ -69,7 +69,7 @@ async def test_get_groups_ordered_by_position(session: AsyncSession, test_user):@pytest.mark.asyncio-async def test_get_groups_loads_categories(session: AsyncSession, test_user):+async def test_get_groups_loads_categories(session: AsyncSession, test_user, test_workspace):groups_map = await create_default_groups(session, test_user.id)await session.commit()@@ -86,7 +86,7 @@ async def test_get_groups_loads_categories(session: AsyncSession, test_user):session.add(cat)await session.commit()- groups = await get_groups(session, test_user.id)+ groups = await get_groups(session, test_workspace.id)food_group = [g for g in groups if g.name == "Alimentação"][0]assert len(food_group.categories) >= 1@@ -97,9 +97,9 @@ async def test_get_groups_loads_categories(session: AsyncSession, test_user):@pytest.mark.asyncio-async def test_create_custom_group(session: AsyncSession, test_user):+async def test_create_custom_group(session: AsyncSession, test_user, test_workspace):data = CategoryGroupCreate(name="Pets", icon="paw-print", color="#FF5733", position=10)- group = await create_group(session, test_user.id, data)+ group = await create_group(session, test_workspace.id, test_user.id, data)assert group.name == "Pets"assert group.icon == "paw-print"@@ -107,34 +107,34 @@ async def test_create_custom_group(session: AsyncSession, test_user):@pytest.mark.asyncio-async def test_get_group_by_id(session: AsyncSession, test_user):+async def test_get_group_by_id(session: AsyncSession, test_user, test_workspace):created = await create_group(session,- test_user.id,+ test_workspace.id, test_user.id,CategoryGroupCreate(name="Lookup", icon="search", color="#000000"),)- fetched = await get_group(session, created.id, test_user.id)+ fetched = await get_group(session, created.id, test_workspace.id)assert fetched is not Noneassert fetched.id == created.id@pytest.mark.asyncio-async def test_get_group_not_found(session: AsyncSession, test_user):- result = await get_group(session, uuid.uuid4(), test_user.id)+async def test_get_group_not_found(session: AsyncSession, test_user, test_workspace):+ result = await get_group(session, uuid.uuid4(), test_workspace.id)assert result is None@pytest.mark.asyncio-async def test_update_group(session: AsyncSession, test_user):+async def test_update_group(session: AsyncSession, test_user, test_workspace):group = await create_group(session,- test_user.id,+ test_workspace.id, test_user.id,CategoryGroupCreate(name="Old", icon="x", color="#111111"),)updated = await update_group(session,group.id,- test_user.id,+ test_workspace.id,CategoryGroupUpdate(name="New", color="#222222"),)assert updated is not None@@ -144,11 +144,11 @@ async def test_update_group(session: AsyncSession, test_user):@pytest.mark.asyncio-async def test_update_group_not_found(session: AsyncSession, test_user):+async def test_update_group_not_found(session: AsyncSession, test_user, test_workspace):result = await update_group(session,uuid.uuid4(),- test_user.id,+ test_workspace.id,CategoryGroupUpdate(name="Nope"),)assert result is None@@ -160,33 +160,33 @@ async def test_update_group_not_found(session: AsyncSession, test_user):@pytest.mark.asyncio-async def test_delete_custom_group(session: AsyncSession, test_user):+async def test_delete_custom_group(session: AsyncSession, test_user, test_workspace):group = await create_group(session,- test_user.id,+ test_workspace.id, test_user.id,CategoryGroupCreate(name="ToDelete", icon="trash", color="#FF0000"),)- assert await delete_group(session, group.id, test_user.id) is True- assert await get_group(session, group.id, test_user.id) is None+ assert await delete_group(session, group.id, test_workspace.id) is True+ assert await get_group(session, group.id, test_workspace.id) is None@pytest.mark.asyncio-async def test_delete_system_group_rejected(session: AsyncSession, test_user):+async def test_delete_system_group_rejected(session: AsyncSession, test_user, test_workspace):groups = await create_default_groups(session, test_user.id)await session.commit()# Try deleting a system groupsystem_group = groups["housing"]- assert await delete_group(session, system_group.id, test_user.id) is False+ assert await delete_group(session, system_group.id, test_workspace.id) is False# Should still exist- assert await get_group(session, system_group.id, test_user.id) is not None+ assert await get_group(session, system_group.id, test_workspace.id) is not None@pytest.mark.asyncio-async def test_delete_group_unlinks_categories(session: AsyncSession, test_user):+async def test_delete_group_unlinks_categories(session: AsyncSession, test_user, test_workspace):group = await create_group(session,- test_user.id,+ test_workspace.id, test_user.id,CategoryGroupCreate(name="UnlinkMe", icon="link", color="#00FF00"),)cat = Category(@@ -201,7 +201,7 @@ async def test_delete_group_unlinks_categories(session: AsyncSession, test_user)session.add(cat)await session.commit()- assert await delete_group(session, group.id, test_user.id) is True+ assert await delete_group(session, group.id, test_workspace.id) is True# Category should still exist but group_id should be Noneresult = await session.execute(select(Category).where(Category.id == cat.id))@@ -211,5 +211,5 @@ async def test_delete_group_unlinks_categories(session: AsyncSession, test_user)@pytest.mark.asyncio-async def test_delete_group_not_found(session: AsyncSession, test_user):- assert await delete_group(session, uuid.uuid4(), test_user.id) is False+async def test_delete_group_not_found(session: AsyncSession, test_user, test_workspace):+ assert await delete_group(session, uuid.uuid4(), test_workspace.id) is Falsediff --git a/backend/tests/test_category_service.py b/backend/tests/test_category_service.pyindex 4caf1e76..f402a310 100644--- a/backend/tests/test_category_service.py+++ b/backend/tests/test_category_service.py@@ -24,7 +24,7 @@ from app.services.category_service import (@pytest.mark.asyncio-async def test_create_default_categories(session: AsyncSession, test_user):+async def test_create_default_categories(session: AsyncSession, test_user, test_workspace):categories = await create_default_categories(session, test_user.id, lang="pt-BR")assert len(categories) == len(DEFAULT_CATEGORIES_I18N)@@ -40,7 +40,7 @@ async def test_create_default_categories(session: AsyncSession, test_user):@pytest.mark.asyncio-async def test_create_default_categories_creates_groups(session: AsyncSession, test_user):+async def test_create_default_categories_creates_groups(session: AsyncSession, test_user, test_workspace):await create_default_categories(session, test_user.id, lang="pt-BR")result = await session.execute(@@ -51,7 +51,7 @@ async def test_create_default_categories_creates_groups(session: AsyncSession, t@pytest.mark.asyncio-async def test_create_default_categories_links_to_groups(session: AsyncSession, test_user):+async def test_create_default_categories_links_to_groups(session: AsyncSession, test_user, test_workspace):categories = await create_default_categories(session, test_user.id, lang="pt-BR")with_group = [c for c in categories if c.group_id is not None]@@ -59,7 +59,7 @@ async def test_create_default_categories_links_to_groups(session: AsyncSession,@pytest.mark.asyncio-async def test_create_default_categories_english(session: AsyncSession, test_user):+async def test_create_default_categories_english(session: AsyncSession, test_user, test_workspace):categories = await create_default_categories(session, test_user.id, lang="en")names = {c.name for c in categories}@@ -69,7 +69,7 @@ async def test_create_default_categories_english(session: AsyncSession, test_use@pytest.mark.asyncio-async def test_create_default_categories_race_guard(session: AsyncSession, test_user):+async def test_create_default_categories_race_guard(session: AsyncSession, test_user, test_workspace):"""Second call should return existing instead of duplicating."""first = await create_default_categories(session, test_user.id, lang="pt-BR")second = await create_default_categories(session, test_user.id, lang="pt-BR")@@ -86,7 +86,7 @@ async def test_create_default_categories_race_guard(session: AsyncSession, test_@pytest.mark.asyncio-async def test_get_categories_ordered(session: AsyncSession, test_user):+async def test_get_categories_ordered(session: AsyncSession, test_user, test_workspace):await create_default_categories(session, test_user.id)custom = Category(@@ -100,7 +100,7 @@ async def test_get_categories_ordered(session: AsyncSession, test_user):session.add(custom)await session.commit()- categories = await get_categories(session, test_user.id)+ categories = await get_categories(session, test_workspace.id)system_cats = [c for c in categories if c.is_system]custom_cats = [c for c in categories if not c.is_system]@@ -112,7 +112,7 @@ async def test_get_categories_ordered(session: AsyncSession, test_user):@pytest.mark.asyncioasync def test_get_categories_excludes_other_users(- session: AsyncSession, test_user, test_categories+ session: AsyncSession, test_user, test_workspace, test_categories):categories = await get_categories(session, uuid.uuid4())assert len(categories) == 0@@ -124,9 +124,9 @@ async def test_get_categories_excludes_other_users(@pytest.mark.asyncio-async def test_create_custom_category(session: AsyncSession, test_user):+async def test_create_custom_category(session: AsyncSession, test_user, test_workspace):data = CategoryCreate(name="Pets", icon="paw-print", color="#8B4513")- cat = await create_category(session, test_user.id, data)+ cat = await create_category(session, test_workspace.id, test_user.id, data)assert cat.name == "Pets"assert cat.icon == "paw-print"@@ -134,52 +134,52 @@ async def test_create_custom_category(session: AsyncSession, test_user):@pytest.mark.asyncio-async def test_create_category_with_group(session: AsyncSession, test_user):+async def test_create_category_with_group(session: AsyncSession, test_user, test_workspace):from app.services.category_group_service import create_groupfrom app.schemas.category_group import CategoryGroupCreategroup = await create_group(session,- test_user.id,+ test_workspace.id, test_user.id,CategoryGroupCreate(name="CustomGroup", icon="folder", color="#000"),)cat = await create_category(session,- test_user.id,+ test_workspace.id, test_user.id,CategoryCreate(name="WithGroup", icon="star", color="#FFF", group_id=group.id),)assert cat.group_id == group.id@pytest.mark.asyncio-async def test_get_category_by_id(session: AsyncSession, test_user):+async def test_get_category_by_id(session: AsyncSession, test_user, test_workspace):created = await create_category(session,- test_user.id,+ test_workspace.id, test_user.id,CategoryCreate(name="Lookup", icon="search", color="#000000"),)- fetched = await get_category(session, created.id, test_user.id)+ fetched = await get_category(session, created.id, test_workspace.id)assert fetched is not Noneassert fetched.id == created.id@pytest.mark.asyncio-async def test_get_category_not_found(session: AsyncSession, test_user):- result = await get_category(session, uuid.uuid4(), test_user.id)+async def test_get_category_not_found(session: AsyncSession, test_user, test_workspace):+ result = await get_category(session, uuid.uuid4(), test_workspace.id)assert result is None@pytest.mark.asyncio-async def test_update_category(session: AsyncSession, test_user):+async def test_update_category(session: AsyncSession, test_user, test_workspace):cat = await create_category(session,- test_user.id,+ test_workspace.id, test_user.id,CategoryCreate(name="OldName", icon="x", color="#111111"),)updated = await update_category(session,cat.id,- test_user.id,+ test_workspace.id,CategoryUpdate(name="NewName", color="#222222"),)assert updated is not None@@ -189,14 +189,14 @@ async def test_update_category(session: AsyncSession, test_user):@pytest.mark.asyncio-async def test_update_category_partial(session: AsyncSession, test_user, test_categories):+async def test_update_category_partial(session: AsyncSession, test_user, test_workspace, test_categories):cat = test_categories[1]original_icon = cat.iconoriginal_color = cat.colorupdated = await update_category(session,cat.id,- test_user.id,+ test_workspace.id,CategoryUpdate(name="Mobilidade"),)assert updated is not None@@ -206,11 +206,11 @@ async def test_update_category_partial(session: AsyncSession, test_user, test_ca@pytest.mark.asyncio-async def test_update_category_not_found(session: AsyncSession, test_user):+async def test_update_category_not_found(session: AsyncSession, test_user, test_workspace):result = await update_category(session,uuid.uuid4(),- test_user.id,+ test_workspace.id,CategoryUpdate(name="Nope"),)assert result is None@@ -222,26 +222,26 @@ async def test_update_category_not_found(session: AsyncSession, test_user):@pytest.mark.asyncio-async def test_delete_custom_category(session: AsyncSession, test_user):+async def test_delete_custom_category(session: AsyncSession, test_user, test_workspace):cat = await create_category(session,- test_user.id,+ test_workspace.id, test_user.id,CategoryCreate(name="ToDelete", icon="trash", color="#FF0000"),)- assert await delete_category(session, cat.id, test_user.id) is True- assert await get_category(session, cat.id, test_user.id) is None+ assert await delete_category(session, cat.id, test_workspace.id) is True+ assert await get_category(session, cat.id, test_workspace.id) is None@pytest.mark.asyncio-async def test_delete_system_category_rejected(session: AsyncSession, test_user):+async def test_delete_system_category_rejected(session: AsyncSession, test_user, test_workspace):categories = await create_default_categories(session, test_user.id)system_cat = categories[0]assert system_cat.is_system is True- assert await delete_category(session, system_cat.id, test_user.id) is False- assert await get_category(session, system_cat.id, test_user.id) is not None+ assert await delete_category(session, system_cat.id, test_workspace.id) is False+ assert await get_category(session, system_cat.id, test_workspace.id) is not None@pytest.mark.asyncio-async def test_delete_category_not_found(session: AsyncSession, test_user):- assert await delete_category(session, uuid.uuid4(), test_user.id) is False+async def test_delete_category_not_found(session: AsyncSession, test_user, test_workspace):+ assert await delete_category(session, uuid.uuid4(), test_workspace.id) is Falsediff --git a/backend/tests/test_connection_service.py b/backend/tests/test_connection_service.pyindex 4cdd6df3..e10fe46c 100644--- a/backend/tests/test_connection_service.py+++ b/backend/tests/test_connection_service.py@@ -163,12 +163,12 @@ async def test_match_pluggy_user_has_no_category(session: AsyncSession, test_use@pytest.mark.asyncio-async def test_get_connections_returns_list(session: AsyncSession, test_user):+async def test_get_connections_returns_list(session: AsyncSession, test_user, test_workspace):"""Returns list of connections for user."""await _make_connection(session, test_user.id, "Bank A")await _make_connection(session, test_user.id, "Bank B")- connections = await get_connections(session, test_user.id)+ connections = await get_connections(session, test_workspace.id)assert len(connections) >= 2names = {c.institution_name for c in connections}assert "Bank A" in names@@ -176,31 +176,31 @@ async def test_get_connections_returns_list(session: AsyncSession, test_user):@pytest.mark.asyncio-async def test_get_connections_empty(session: AsyncSession, test_user):+async def test_get_connections_empty(session: AsyncSession, test_user, test_workspace):"""Returns empty list when no connections."""- connections = await get_connections(session, test_user.id)+ connections = await get_connections(session, test_workspace.id)# May have connections from other fixtures; just verify it's a listassert isinstance(connections, list)@pytest.mark.asyncio-async def test_get_connection_found(session: AsyncSession, test_user):+async def test_get_connection_found(session: AsyncSession, test_user, test_workspace):"""Returns a specific connection."""conn = await _make_connection(session, test_user.id, "Specific Bank")- result = await get_connection(session, conn.id, test_user.id)+ result = await get_connection(session, conn.id, test_workspace.id)assert result is not Noneassert result.institution_name == "Specific Bank"@pytest.mark.asyncio-async def test_get_connection_not_found(session: AsyncSession, test_user):+async def test_get_connection_not_found(session: AsyncSession, test_user, test_workspace):"""Returns None for nonexistent connection."""- result = await get_connection(session, uuid.uuid4(), test_user.id)+ result = await get_connection(session, uuid.uuid4(), test_workspace.id)assert result is None@pytest.mark.asyncio-async def test_get_connection_wrong_user(session: AsyncSession, test_user):+async def test_get_connection_wrong_user(session: AsyncSession, test_user, test_workspace):"""Returns None when connection belongs to another user."""conn = await _make_connection(session, test_user.id, "Other User Bank")result = await get_connection(session, conn.id, uuid.uuid4())@@ -213,19 +213,19 @@ async def test_get_connection_wrong_user(session: AsyncSession, test_user):@pytest.mark.asyncio-async def test_update_settings_new(session: AsyncSession, test_user):+async def test_update_settings_new(session: AsyncSession, test_user, test_workspace):"""Updates settings on a connection with no prior settings."""conn = await _make_connection(session, test_user.id, "Settings Test")updated = await update_connection_settings(- session, conn.id, test_user.id, {"payee_source": "merchant"},+ session, conn.id, test_workspace.id, {"payee_source": "merchant"},)assert updated is not Noneassert updated.settings["payee_source"] == "merchant"@pytest.mark.asyncio-async def test_update_settings_preserves_existing(session: AsyncSession, test_user):+async def test_update_settings_preserves_existing(session: AsyncSession, test_user, test_workspace):"""Updates one setting without clobbering others."""conn = await _make_connection(session, test_user.id, "Preserve Test",@@ -233,7 +233,7 @@ async def test_update_settings_preserves_existing(session: AsyncSession, test_us)updated = await update_connection_settings(- session, conn.id, test_user.id, {"import_pending": False},+ session, conn.id, test_workspace.id, {"import_pending": False},)assert updated is not Noneassert updated.settings["payee_source"] == "auto"@@ -241,24 +241,24 @@ async def test_update_settings_preserves_existing(session: AsyncSession, test_us@pytest.mark.asyncio-async def test_update_settings_ignores_none(session: AsyncSession, test_user):+async def test_update_settings_ignores_none(session: AsyncSession, test_user, test_workspace):"""None values in settings_update are not written."""conn = await _make_connection(session, test_user.id, "None Test",settings={"payee_source": "auto"},)updated = await update_connection_settings(- session, conn.id, test_user.id, {"payee_source": None},+ session, conn.id, test_workspace.id, {"payee_source": None},)assert updated is not Noneassert updated.settings["payee_source"] == "auto"@pytest.mark.asyncio-async def test_update_settings_not_found(session: AsyncSession, test_user):+async def test_update_settings_not_found(session: AsyncSession, test_user, test_workspace):"""Returns None when connection not found."""result = await update_connection_settings(- session, uuid.uuid4(), test_user.id, {"payee_source": "auto"},+ session, uuid.uuid4(), test_workspace.id, {"payee_source": "auto"},)assert result is None@@ -269,24 +269,24 @@ async def test_update_settings_not_found(session: AsyncSession, test_user):@pytest.mark.asyncio-async def test_delete_connection_found(session: AsyncSession, test_user):+async def test_delete_connection_found(session: AsyncSession, test_user, test_workspace):"""Deletes an existing connection."""conn = await _make_connection(session, test_user.id, "To Delete")- result = await delete_connection(session, conn.id, test_user.id)+ result = await delete_connection(session, conn.id, test_workspace.id)assert result is True- assert await get_connection(session, conn.id, test_user.id) is None+ assert await get_connection(session, conn.id, test_workspace.id) is None@pytest.mark.asyncio-async def test_delete_connection_not_found(session: AsyncSession, test_user):+async def test_delete_connection_not_found(session: AsyncSession, test_user, test_workspace):"""Returns False for nonexistent connection."""- result = await delete_connection(session, uuid.uuid4(), test_user.id)+ result = await delete_connection(session, uuid.uuid4(), test_workspace.id)assert result is False@pytest.mark.asyncio-async def test_delete_connection_archives_linked_assets(session: AsyncSession, test_user):+async def test_delete_connection_archives_linked_assets(session: AsyncSession, test_user, test_workspace):"""Deleting a connection archives linked assets before removing the connection."""from app.models.asset import Asset@@ -305,7 +305,7 @@ async def test_delete_connection_archives_linked_assets(session: AsyncSession, tsession.add(asset)await session.commit()- result = await delete_connection(session, conn.id, test_user.id)+ result = await delete_connection(session, conn.id, test_workspace.id)assert result is Truerefreshed = (await session.execute(select(Asset).where(Asset.id == asset.id))).scalar_one()@@ -313,7 +313,7 @@ async def test_delete_connection_archives_linked_assets(session: AsyncSession, t@pytest.mark.asyncio-async def test_delete_connection_deletes_orphan_payees(session: AsyncSession, test_user):+async def test_delete_connection_deletes_orphan_payees(session: AsyncSession, test_user, test_workspace):"""Unlink should remove payees that become orphaned after tx deletion."""from app.models.account import Accountfrom app.models.payee import Payee@@ -348,14 +348,14 @@ async def test_delete_connection_deletes_orphan_payees(session: AsyncSession, te)await session.commit()- assert await delete_connection(session, conn.id, test_user.id) is True+ assert await delete_connection(session, conn.id, test_workspace.id) is Truerefreshed = (await session.execute(select(Payee).where(Payee.id == payee.id))).scalar_one_or_none()assert refreshed is None@pytest.mark.asyncio-async def test_delete_connection_keeps_payees_with_external_mappings(session: AsyncSession, test_user):+async def test_delete_connection_keeps_payees_with_external_mappings(session: AsyncSession, test_user, test_workspace):"""Unlink should not remove payees that still have external mappings."""from app.models.account import Accountfrom app.models.payee import Payee, PayeeMapping@@ -394,7 +394,7 @@ async def test_delete_connection_keeps_payees_with_external_mappings(session: As)await session.commit()- assert await delete_connection(session, conn.id, test_user.id) is True+ assert await delete_connection(session, conn.id, test_workspace.id) is Truerefreshed = (await session.execute(select(Payee).where(Payee.id == payee.id))).scalar_one_or_none()assert refreshed is not None@@ -422,7 +422,7 @@ async def test_create_connect_token_success(test_user):@pytest.mark.asyncio-async def test_handle_oauth_callback_creates_connection(session: AsyncSession, test_user):+async def test_handle_oauth_callback_creates_connection(session: AsyncSession, test_user, test_workspace):mock_provider = AsyncMock()mock_provider.handle_oauth_callback = AsyncMock(return_value=ConnectionData(external_id="ext-oauth-1",@@ -446,7 +446,7 @@ async def test_handle_oauth_callback_creates_connection(session: AsyncSession, tpatch("app.services.connection_service.detect_transfer_pairs", new_callable=AsyncMock), \patch("app.services.connection_service.stamp_primary_amount", new_callable=AsyncMock), \patch("app.services.connection_service.apply_rules_to_transaction", new_callable=AsyncMock):- conn = await handle_oauth_callback(session, test_user.id, "auth-code", "pluggy")+ conn = await handle_oauth_callback(session, test_workspace.id, test_user.id, "auth-code", "pluggy")assert conn.institution_name == "Test Bank"assert conn.external_id == "ext-oauth-1"@@ -454,7 +454,7 @@ async def test_handle_oauth_callback_creates_connection(session: AsyncSession, t@pytest.mark.asyncio-async def test_handle_oauth_callback_with_payee(session: AsyncSession, test_user):+async def test_handle_oauth_callback_with_payee(session: AsyncSession, test_user, test_workspace):mock_provider = AsyncMock()mock_provider.handle_oauth_callback = AsyncMock(return_value=ConnectionData(external_id="ext-oauth-2",@@ -479,7 +479,7 @@ async def test_handle_oauth_callback_with_payee(session: AsyncSession, test_userpatch("app.services.connection_service.detect_transfer_pairs", new_callable=AsyncMock), \patch("app.services.connection_service.stamp_primary_amount", new_callable=AsyncMock), \patch("app.services.connection_service.apply_rules_to_transaction", new_callable=AsyncMock):- conn = await handle_oauth_callback(session, test_user.id, "code2", "pluggy")+ conn = await handle_oauth_callback(session, test_workspace.id, test_user.id, "code2", "pluggy")assert conn.institution_name == "Payee Bank"@@ -490,7 +490,7 @@ async def test_handle_oauth_callback_with_payee(session: AsyncSession, test_user@pytest.mark.asyncio-async def test_sync_connection_new_transactions(session: AsyncSession, test_user):+async def test_sync_connection_new_transactions(session: AsyncSession, test_user, test_workspace):conn = await _make_connection(session, test_user.id, "Sync Bank")mock_provider = AsyncMock()mock_provider.refresh_credentials = AsyncMock(return_value={"token": "refreshed"})@@ -511,20 +511,20 @@ async def test_sync_connection_new_transactions(session: AsyncSession, test_userpatch("app.services.connection_service.detect_transfer_pairs", new_callable=AsyncMock), \patch("app.services.connection_service.stamp_primary_amount", new_callable=AsyncMock), \patch("app.services.connection_service.apply_rules_to_transaction", new_callable=AsyncMock):- result_conn, merged = await sync_connection(session, conn.id, test_user.id)+ result_conn, merged = await sync_connection(session, conn.id, test_workspace.id, test_user.id)assert result_conn.status == "active"assert merged == 0@pytest.mark.asyncio-async def test_sync_connection_not_found(session: AsyncSession, test_user):+async def test_sync_connection_not_found(session: AsyncSession, test_user, test_workspace):with pytest.raises(ValueError, match="not found"):- await sync_connection(session, uuid.uuid4(), test_user.id)+ await sync_connection(session, uuid.uuid4(), test_workspace.id, test_user.id)@pytest.mark.asyncio-async def test_sync_connection_with_category_mapping(session: AsyncSession, test_user):+async def test_sync_connection_with_category_mapping(session: AsyncSession, test_user, test_workspace):conn = await _make_connection(session, test_user.id, "Cat Bank")await _make_category(session, test_user.id, "Alimentação")@@ -547,24 +547,24 @@ async def test_sync_connection_with_category_mapping(session: AsyncSession, testwith patch("app.services.connection_service.get_provider", return_value=mock_provider), \patch("app.services.connection_service.detect_transfer_pairs", new_callable=AsyncMock), \patch("app.services.connection_service.stamp_primary_amount", new_callable=AsyncMock):- result_conn, _ = await sync_connection(session, conn.id, test_user.id)+ result_conn, _ = await sync_connection(session, conn.id, test_workspace.id, test_user.id)assert result_conn.status == "active"@pytest.mark.asyncio-async def test_sync_connection_error_raises(session: AsyncSession, test_user):+async def test_sync_connection_error_raises(session: AsyncSession, test_user, test_workspace):conn = await _make_connection(session, test_user.id, "Error Bank")mock_provider = AsyncMock()mock_provider.refresh_credentials = AsyncMock(side_effect=RuntimeError("API down"))with patch("app.services.connection_service.get_provider", return_value=mock_provider):with pytest.raises(RuntimeError, match="API down"):- await sync_connection(session, conn.id, test_user.id)+ await sync_connection(session, conn.id, test_workspace.id, test_user.id)@pytest.mark.asyncio-async def test_sync_connection_skips_pending(session: AsyncSession, test_user):+async def test_sync_connection_skips_pending(session: AsyncSession, test_user, test_workspace):conn = await _make_connection(session, test_user.id, "Pending Bank",settings={"import_pending": False},@@ -594,14 +594,14 @@ async def test_sync_connection_skips_pending(session: AsyncSession, test_user):patch("app.services.connection_service.detect_transfer_pairs", new_callable=AsyncMock), \patch("app.services.connection_service.stamp_primary_amount", new_callable=AsyncMock), \patch("app.services.connection_service.apply_rules_to_transaction", new_callable=AsyncMock):- result_conn, _ = await sync_connection(session, conn.id, test_user.id)+ result_conn, _ = await sync_connection(session, conn.id, test_workspace.id, test_user.id)assert result_conn.status == "active"@pytest.mark.asyncioasync def test_sync_connection_does_not_revive_ignored_transaction(- session: AsyncSession, test_user,+ session: AsyncSession, test_user, test_workspace,):"""Issue #200: a transaction the user flagged is_ignored=True must not bemutated by a subsequent sync, even when Pluggy returns the same external_id@@ -648,7 +648,7 @@ async def test_sync_connection_does_not_revive_ignored_transaction(patch("app.services.connection_service.detect_transfer_pairs", new_callable=AsyncMock), \patch("app.services.connection_service.stamp_primary_amount", new_callable=AsyncMock), \patch("app.services.connection_service.apply_rules_to_transaction", new_callable=AsyncMock):- await sync_connection(session, conn.id, test_user.id)+ await sync_connection(session, conn.id, test_workspace.id, test_user.id)refreshed = (await session.execute(select(Transaction).where(Transaction.external_id == "ign-tx-1")@@ -664,7 +664,7 @@ async def test_sync_connection_does_not_revive_ignored_transaction(@pytest.mark.asyncioasync def test_oauth_callback_persists_installment_metadata(- session: AsyncSession, test_user,+ session: AsyncSession, test_user, test_workspace,):"""handle_oauth_callback must store all 4 installment fields on theTransaction row exactly as the provider returned them."""@@ -702,7 +702,7 @@ async def test_oauth_callback_persists_installment_metadata(patch("app.services.connection_service.detect_transfer_pairs", new_callable=AsyncMock), \patch("app.services.connection_service.stamp_primary_amount", new_callable=AsyncMock), \patch("app.services.connection_service.apply_rules_to_transaction", new_callable=AsyncMock):- await handle_oauth_callback(session, test_user.id, "code", "pluggy")+ await handle_oauth_callback(session, test_workspace.id, test_user.id, "code", "pluggy")rows = (await session.execute(select(Transaction).where(@@ -728,7 +728,7 @@ async def test_oauth_callback_persists_installment_metadata(@pytest.mark.asyncioasync def test_sync_connection_persists_installment_metadata(- session: AsyncSession, test_user,+ session: AsyncSession, test_user, test_workspace,):"""Incremental sync path must also persist installment fields."""conn = await _make_connection(session, test_user.id, "Sync Inst Bank")@@ -756,7 +756,7 @@ async def test_sync_connection_persists_installment_metadata(patch("app.services.connection_service.detect_transfer_pairs", new_callable=AsyncMock), \patch("app.services.connection_service.stamp_primary_amount", new_callable=AsyncMock), \patch("app.services.connection_service.apply_rules_to_transaction", new_callable=AsyncMock):- await sync_connection(session, conn.id, test_user.id)+ await sync_connection(session, conn.id, test_workspace.id, test_user.id)row = (await session.execute(select(Transaction).where(Transaction.external_id == "sync-inst-tx-1")@@ -768,7 +768,7 @@ async def test_sync_connection_persists_installment_metadata(@pytest.mark.asyncio-async def test_sync_connection_preserves_display_name(session: AsyncSession, test_user):+async def test_sync_connection_preserves_display_name(session: AsyncSession, test_user, test_workspace):"""Resyncing a connection must update the provider name but never overwrite display_name."""from app.models.account import Account@@ -787,7 +787,7 @@ async def test_sync_connection_preserves_display_name(session: AsyncSession, tespatch("app.services.connection_service.detect_transfer_pairs", new_callable=AsyncMock), \patch("app.services.connection_service.stamp_primary_amount", new_callable=AsyncMock), \patch("app.services.connection_service.apply_rules_to_transaction", new_callable=AsyncMock):- await sync_connection(session, conn.id, test_user.id)+ await sync_connection(session, conn.id, test_workspace.id, test_user.id)# Set a display_name after the first syncaccount = (await session.execute(@@ -808,7 +808,7 @@ async def test_sync_connection_preserves_display_name(session: AsyncSession, tespatch("app.services.connection_service.detect_transfer_pairs", new_callable=AsyncMock), \patch("app.services.connection_service.stamp_primary_amount", new_callable=AsyncMock), \patch("app.services.connection_service.apply_rules_to_transaction", new_callable=AsyncMock):- await sync_connection(session, conn.id, test_user.id)+ await sync_connection(session, conn.id, test_workspace.id, test_user.id)await session.refresh(account)assert account.name == "BANCO ATUALIZADO"@@ -817,7 +817,7 @@ async def test_sync_connection_preserves_display_name(session: AsyncSession, tes@pytest.mark.asyncioasync def test_sync_connection_does_not_recreate_closed_accounts(- session: AsyncSession, test_user,+ session: AsyncSession, test_user, test_workspace,):"""Closing a connected account then resyncing must NOT create a duplicateactive row for the same provider account, and the original closed row must@@ -841,14 +841,14 @@ async def test_sync_connection_does_not_recreate_closed_accounts(patch("app.services.connection_service.detect_transfer_pairs", new_callable=AsyncMock), \patch("app.services.connection_service.stamp_primary_amount", new_callable=AsyncMock), \patch("app.services.connection_service.apply_rules_to_transaction", new_callable=AsyncMock):- await sync_connection(session, conn.id, test_user.id)+ await sync_connection(session, conn.id, test_workspace.id, test_user.id)account = (await session.execute(select(Account).where(Account.external_id == "closed-acc-1"))).scalar_one()assert account.connection_id == conn.id- await close_account(session, account.id, test_user.id)+ await close_account(session, account.id, test_workspace.id)await session.refresh(account)assert account.is_closed is Trueassert account.connection_id == conn.id # link preserved@@ -865,7 +865,7 @@ async def test_sync_connection_does_not_recreate_closed_accounts(patch("app.services.connection_service.detect_transfer_pairs", new_callable=AsyncMock), \patch("app.services.connection_service.stamp_primary_amount", new_callable=AsyncMock), \patch("app.services.connection_service.apply_rules_to_transaction", new_callable=AsyncMock):- await sync_connection(session, conn.id, test_user.id)+ await sync_connection(session, conn.id, test_workspace.id, test_user.id)rows = (await session.execute(select(Account).where(Account.external_id == "closed-acc-1")@@ -921,7 +921,7 @@ def _patch_sync_helpers():@pytest.mark.asyncioasync def test_sync_persists_bills_for_credit_card_account(- session: AsyncSession, test_user,+ session: AsyncSession, test_user, test_workspace,):"""First sync of a CC account upserts bills returned by /bills."""from app.models.credit_card_bill import CreditCardBill@@ -942,7 +942,7 @@ async def test_sync_persists_bills_for_credit_card_account(p1, p2, p3 = _patch_sync_helpers()with patch("app.services.connection_service.get_provider", return_value=mock_provider), \p1, p2, p3:- await sync_connection(session, conn.id, test_user.id)+ await sync_connection(session, conn.id, test_workspace.id, test_user.id)rows = (await session.execute(select(CreditCardBill).where(CreditCardBill.user_id == test_user.id)@@ -957,7 +957,7 @@ async def test_sync_persists_bills_for_credit_card_account(@pytest.mark.asyncioasync def test_sync_links_transaction_to_matching_bill(- session: AsyncSession, test_user,+ session: AsyncSession, test_user, test_workspace,):"""Transactions whose bill_external_id matches a synced bill get bill_idset and effective_date = bill.due_date (the bank-truth path, issue #92)."""@@ -984,7 +984,7 @@ async def test_sync_links_transaction_to_matching_bill(p1, p2, p3 = _patch_sync_helpers()with patch("app.services.connection_service.get_provider", return_value=mock_provider), \p1, p2, p3:- await sync_connection(session, conn.id, test_user.id)+ await sync_connection(session, conn.id, test_workspace.id, test_user.id)bill_row = (await session.execute(select(CreditCardBill).where(CreditCardBill.external_id == "bill-99")@@ -999,7 +999,7 @@ async def test_sync_links_transaction_to_matching_bill(@pytest.mark.asyncioasync def test_sync_falls_back_to_cycle_math_when_bill_missing(- session: AsyncSession, test_user,+ session: AsyncSession, test_user, test_workspace,):"""A tx with bill_external_id that isn't in the bills feed (older bill,bills 4xx, etc.) leaves bill_id null and uses local cycle math —@@ -1030,7 +1030,7 @@ async def test_sync_falls_back_to_cycle_math_when_bill_missing(p1, p2, p3 = _patch_sync_helpers()with patch("app.services.connection_service.get_provider", return_value=mock_provider), \p1, p2, p3:- await sync_connection(session, conn.id, test_user.id)+ await sync_connection(session, conn.id, test_workspace.id, test_user.id)tx_row = (await session.execute(select(Transaction).where(Transaction.external_id == "tx-orphan")@@ -1042,7 +1042,7 @@ async def test_sync_falls_back_to_cycle_math_when_bill_missing(@pytest.mark.asyncioasync def test_sync_swallows_get_bills_error(- session: AsyncSession, test_user,+ session: AsyncSession, test_user, test_workspace,):"""Non-regulado Pluggy connections 4xx on /bills. Sync must keep goingand persist transactions via the cycle-math fallback."""@@ -1063,7 +1063,7 @@ async def test_sync_swallows_get_bills_error(p1, p2, p3 = _patch_sync_helpers()with patch("app.services.connection_service.get_provider", return_value=mock_provider), \p1, p2, p3:- result, _ = await sync_connection(session, conn.id, test_user.id)+ result, _ = await sync_connection(session, conn.id, test_workspace.id, test_user.id)assert result.status == "active"tx_row = (await session.execute(@@ -1074,7 +1074,7 @@ async def test_sync_swallows_get_bills_error(@pytest.mark.asyncioasync def test_sync_skips_get_bills_for_non_credit_card_account(- session: AsyncSession, test_user,+ session: AsyncSession, test_user, test_workspace,):"""Checking accounts must not hit /bills — saves an HTTP roundtrip andavoids 4xx noise on providers that scope bills to credit accounts."""@@ -1093,14 +1093,14 @@ async def test_sync_skips_get_bills_for_non_credit_card_account(p1, p2, p3 = _patch_sync_helpers()with patch("app.services.connection_service.get_provider", return_value=mock_provider), \p1, p2, p3:- await sync_connection(session, conn.id, test_user.id)+ await sync_connection(session, conn.id, test_workspace.id, test_user.id)mock_provider.get_bills.assert_not_called()@pytest.mark.asyncioasync def test_sync_backfills_bill_link_on_existing_transaction(- session: AsyncSession, test_user,+ session: AsyncSession, test_user, test_workspace,):"""A transaction synced before the /bills feature must self-heal: on thenext sync, when the matching bill is in the feed, bill_id and@@ -1124,7 +1124,7 @@ async def test_sync_backfills_bill_link_on_existing_transaction(p1, p2, p3 = _patch_sync_helpers()with patch("app.services.connection_service.get_provider", return_value=mock_provider), \p1, p2, p3:- await sync_connection(session, conn.id, test_user.id)+ await sync_connection(session, conn.id, test_workspace.id, test_user.id)pre = (await session.execute(select(Transaction).where(Transaction.external_id == "tx-preexisting")@@ -1143,7 +1143,7 @@ async def test_sync_backfills_bill_link_on_existing_transaction(with patch("app.services.connection_service.get_provider", return_value=mock_provider), \p1, p2, p3:- await sync_connection(session, conn.id, test_user.id)+ await sync_connection(session, conn.id, test_workspace.id, test_user.id)bill_row = (await session.execute(select(CreditCardBill).where(CreditCardBill.external_id == "bill-future-1")@@ -1159,7 +1159,7 @@ async def test_sync_backfills_bill_link_on_existing_transaction(@pytest.mark.asyncioasync def test_sync_relinks_transaction_when_bank_moves_it_to_another_bill(- session: AsyncSession, test_user,+ session: AsyncSession, test_user, test_workspace,):"""If the bank later re-buckets a tx (chargeback, billing dispute), thenext sync must update bill_id and effective_date — same row, new link."""@@ -1186,7 +1186,7 @@ async def test_sync_relinks_transaction_when_bank_moves_it_to_another_bill(p1, p2, p3 = _patch_sync_helpers()with patch("app.services.connection_service.get_provider", return_value=mock_provider), \p1, p2, p3:- await sync_connection(session, conn.id, test_user.id)+ await sync_connection(session, conn.id, test_workspace.id, test_user.id)# Bank moves the tx to bill_b on the next synctxn_to_b = TransactionData(@@ -1198,7 +1198,7 @@ async def test_sync_relinks_transaction_when_bank_moves_it_to_another_bill(with patch("app.services.connection_service.get_provider", return_value=mock_provider), \p1, p2, p3:- await sync_connection(session, conn.id, test_user.id)+ await sync_connection(session, conn.id, test_workspace.id, test_user.id)bill_b_row = (await session.execute(select(CreditCardBill).where(CreditCardBill.external_id == "bill-b")@@ -1212,7 +1212,7 @@ async def test_sync_relinks_transaction_when_bank_moves_it_to_another_bill(@pytest.mark.asyncioasync def test_sync_creates_synthetic_transactions_for_finance_charges(- session: AsyncSession, test_user,+ session: AsyncSession, test_user, test_workspace,):"""A bill carrying IOF / multa / juros lines that don't exist as standalonetransactions must yield synthetic txs so the cycle sum reconciles to@@ -1237,7 +1237,7 @@ async def test_sync_creates_synthetic_transactions_for_finance_charges(p1, p2, p3 = _patch_sync_helpers()with patch("app.services.connection_service.get_provider", return_value=mock_provider), \p1, p2, p3:- await sync_connection(session, conn.id, test_user.id)+ await sync_connection(session, conn.id, test_workspace.id, test_user.id)rows = (await session.execute(select(Transaction)@@ -1263,7 +1263,7 @@ async def test_sync_creates_synthetic_transactions_for_finance_charges(@pytest.mark.asyncioasync def test_sync_dates_charges_at_cycle_close_when_close_day_known(- session: AsyncSession, test_user,+ session: AsyncSession, test_user, test_workspace,):"""Synthetic finance charges should be dated at the cycle close (thebank's snapshot moment) rather than the bill's due date — otherwise@@ -1298,7 +1298,7 @@ async def test_sync_dates_charges_at_cycle_close_when_close_day_known(p1, p2, p3 = _patch_sync_helpers()with patch("app.services.connection_service.get_provider", return_value=mock_provider), \p1, p2, p3:- await sync_connection(session, conn.id, test_user.id)+ await sync_connection(session, conn.id, test_workspace.id, test_user.id)tx = (await session.execute(select(Transaction).where(@@ -1314,7 +1314,7 @@ async def test_sync_dates_charges_at_cycle_close_when_close_day_known(@pytest.mark.asyncioasync def test_sync_skips_carry_over_balance_finance_charge(- session: AsyncSession, test_user,+ session: AsyncSession, test_user, test_workspace,):"""`Saldo em atraso` is the prior bill's unpaid balance carried into thisbill — informational only, NOT part of bill.total_amount, so we must not@@ -1338,7 +1338,7 @@ async def test_sync_skips_carry_over_balance_finance_charge(p1, p2, p3 = _patch_sync_helpers()with patch("app.services.connection_service.get_provider", return_value=mock_provider), \p1, p2, p3:- await sync_connection(session, conn.id, test_user.id)+ await sync_connection(session, conn.id, test_workspace.id, test_user.id)rows = (await session.execute(select(Transaction).where(@@ -1353,7 +1353,7 @@ async def test_sync_skips_carry_over_balance_finance_charge(@pytest.mark.asyncioasync def test_sync_skips_juros_aggregate_finance_charge(- session: AsyncSession, test_user,+ session: AsyncSession, test_user, test_workspace,):"""`Juros de dívida encerrada` is an aggregate that equals the sum of thedetailed late-charge lines Pluggy ALSO emits — including it would@@ -1378,7 +1378,7 @@ async def test_sync_skips_juros_aggregate_finance_charge(p1, p2, p3 = _patch_sync_helpers()with patch("app.services.connection_service.get_provider", return_value=mock_provider), \p1, p2, p3:- await sync_connection(session, conn.id, test_user.id)+ await sync_connection(session, conn.id, test_workspace.id, test_user.id)rows = (await session.execute(select(Transaction).where(@@ -1393,7 +1393,7 @@ async def test_sync_skips_juros_aggregate_finance_charge(@pytest.mark.asyncioasync def test_sync_finance_charges_are_idempotent(- session: AsyncSession, test_user,+ session: AsyncSession, test_user, test_workspace,):"""Re-syncing the same bill must not duplicate synthetic charges."""conn = await _make_connection(session, test_user.id, "IdemFC")@@ -1415,7 +1415,7 @@ async def test_sync_finance_charges_are_idempotent(for _ in range(2):with patch("app.services.connection_service.get_provider", return_value=mock_provider), \p1, p2, p3:- await sync_connection(session, conn.id, test_user.id)+ await sync_connection(session, conn.id, test_workspace.id, test_user.id)rows = (await session.execute(select(Transaction).where(@@ -1428,7 +1428,7 @@ async def test_sync_finance_charges_are_idempotent(@pytest.mark.asyncioasync def test_sync_removes_orphaned_finance_charges_on_resync(- session: AsyncSession, test_user,+ session: AsyncSession, test_user, test_workspace,):"""If a charge disappears from the bill on the next sync (e.g. bankreversed it), the synthetic tx must be removed."""@@ -1451,7 +1451,7 @@ async def test_sync_removes_orphaned_finance_charges_on_resync(with patch("app.services.connection_service.get_provider", return_value=mock_provider), \p1, p2, p3:- await sync_connection(session, conn.id, test_user.id)+ await sync_connection(session, conn.id, test_workspace.id, test_user.id)# Second sync — the LATE_PAYMENT_FEE charge is gone (bank reversed it)bill_v2 = BillData(@@ -1470,7 +1470,7 @@ async def test_sync_removes_orphaned_finance_charges_on_resync(with patch("app.services.connection_service.get_provider", return_value=mock_provider), \p1, p2, p3:- await sync_connection(session, conn.id, test_user.id)+ await sync_connection(session, conn.id, test_workspace.id, test_user.id)rows = (await session.execute(select(Transaction).where(@@ -1484,7 +1484,7 @@ async def test_sync_removes_orphaned_finance_charges_on_resync(@pytest.mark.asyncioasync def test_sync_does_not_overwrite_manual_effective_bill_date(- session: AsyncSession, test_user,+ session: AsyncSession, test_user, test_workspace,):"""When the user has manually set effective_bill_date on a tx, the nextsync must NOT relink bill_id or recompute effective_date — the user is@@ -1511,7 +1511,7 @@ async def test_sync_does_not_overwrite_manual_effective_bill_date(with patch("app.services.connection_service.get_provider", return_value=mock_provider), \p1, p2, p3:- await sync_connection(session, conn.id, test_user.id)+ await sync_connection(session, conn.id, test_workspace.id, test_user.id)# User overrides: this tx belongs to a different bill (May 5, manually).tx_row = (await session.execute(@@ -1526,7 +1526,7 @@ async def test_sync_does_not_overwrite_manual_effective_bill_date(# Re-sync — provider still says bill A. Override must be preserved.with patch("app.services.connection_service.get_provider", return_value=mock_provider), \p1, p2, p3:- await sync_connection(session, conn.id, test_user.id)+ await sync_connection(session, conn.id, test_workspace.id, test_user.id)tx_row = (await session.execute(select(Transaction).where(Transaction.external_id == "tx-overridden")@@ -1539,7 +1539,7 @@ async def test_sync_does_not_overwrite_manual_effective_bill_date(@pytest.mark.asyncioasync def test_sync_updates_existing_bill_idempotently(- session: AsyncSession, test_user,+ session: AsyncSession, test_user, test_workspace,):"""A second sync that returns the same bill id with updated totals mustupdate in place, not insert a duplicate (the unique(account_id,@@ -1558,7 +1558,7 @@ async def test_sync_updates_existing_bill_idempotently(p1, p2, p3 = _patch_sync_helpers()with patch("app.services.connection_service.get_provider", return_value=mock_provider), \p1, p2, p3:- await sync_connection(session, conn.id, test_user.id)+ await sync_connection(session, conn.id, test_workspace.id, test_user.id)# Second sync: same id, new totals (e.g. mid-cycle adjustment)bill_v2 = BillData(@@ -1571,7 +1571,7 @@ async def test_sync_updates_existing_bill_idempotently(with patch("app.services.connection_service.get_provider", return_value=mock_provider), \p1, p2, p3:- await sync_connection(session, conn.id, test_user.id)+ await sync_connection(session, conn.id, test_workspace.id, test_user.id)rows = (await session.execute(select(CreditCardBill).where(CreditCardBill.user_id == test_user.id)@@ -1588,7 +1588,7 @@ async def test_sync_updates_existing_bill_idempotently(@pytest.mark.asyncioasync def test_sync_dedupes_pending_posted_twin_in_same_fetch(- session: AsyncSession, test_user,+ session: AsyncSession, test_user, test_workspace,):"""A provider emits the same operation twice in a single fetch — oncepending (the scheduled row) and once posted (the executed row) — under@@ -1621,7 +1621,7 @@ async def test_sync_dedupes_pending_posted_twin_in_same_fetch(patch("app.services.connection_service.detect_transfer_pairs", new_callable=AsyncMock), \patch("app.services.connection_service.stamp_primary_amount", new_callable=AsyncMock), \patch("app.services.connection_service.apply_rules_to_transaction", new_callable=AsyncMock):- await sync_connection(session, conn.id, test_user.id)+ await sync_connection(session, conn.id, test_workspace.id, test_user.id)rows = (await session.execute(select(Transaction).where(@@ -1636,7 +1636,7 @@ async def test_sync_dedupes_pending_posted_twin_in_same_fetch(@pytest.mark.asyncioasync def test_sync_dedupes_pending_posted_twin_with_identical_descriptions(- session: AsyncSession, test_user,+ session: AsyncSession, test_user, test_workspace,):"""Same case as above but the descriptions are byte-identical — thestatus differential alone is enough to collapse them."""@@ -1668,7 +1668,7 @@ async def test_sync_dedupes_pending_posted_twin_with_identical_descriptions(patch("app.services.connection_service.detect_transfer_pairs", new_callable=AsyncMock), \patch("app.services.connection_service.stamp_primary_amount", new_callable=AsyncMock), \patch("app.services.connection_service.apply_rules_to_transaction", new_callable=AsyncMock):- await sync_connection(session, conn.id, test_user.id)+ await sync_connection(session, conn.id, test_workspace.id, test_user.id)rows = (await session.execute(select(Transaction).where(@@ -1682,7 +1682,7 @@ async def test_sync_dedupes_pending_posted_twin_with_identical_descriptions(@pytest.mark.asyncioasync def test_sync_keeps_unrelated_pending_and_posted_with_different_descriptions(- session: AsyncSession, test_user,+ session: AsyncSession, test_user, test_workspace,):"""Two unrelated transactions that happen to share a date and amount —one pending, one posted, completely different merchants — must NOT be@@ -1716,7 +1716,7 @@ async def test_sync_keeps_unrelated_pending_and_posted_with_different_descriptiopatch("app.services.connection_service.detect_transfer_pairs", new_callable=AsyncMock), \patch("app.services.connection_service.stamp_primary_amount", new_callable=AsyncMock), \patch("app.services.connection_service.apply_rules_to_transaction", new_callable=AsyncMock):- await sync_connection(session, conn.id, test_user.id)+ await sync_connection(session, conn.id, test_workspace.id, test_user.id)rows = (await session.execute(select(Transaction).where(@@ -1729,7 +1729,7 @@ async def test_sync_keeps_unrelated_pending_and_posted_with_different_descriptio@pytest.mark.asyncioasync def test_sync_upgrades_pending_to_posted_when_twin_arrives(- session: AsyncSession, test_user,+ session: AsyncSession, test_user, test_workspace,):"""When the pending row was synced first and the posted twin arrives onthe next sync with a different external_id, the existing row must be@@ -1755,7 +1755,7 @@ async def test_sync_upgrades_pending_to_posted_when_twin_arrives(patch("app.services.connection_service.detect_transfer_pairs", new_callable=AsyncMock), \patch("app.services.connection_service.stamp_primary_amount", new_callable=AsyncMock), \patch("app.services.connection_service.apply_rules_to_transaction", new_callable=AsyncMock):- await sync_connection(session, conn.id, test_user.id)+ await sync_connection(session, conn.id, test_workspace.id, test_user.id)# Second sync: posted twin arrives with a new id and identifier; the# pending row is also still in the feed (providers don't always drop the@@ -1772,7 +1772,7 @@ async def test_sync_upgrades_pending_to_posted_when_twin_arrives(patch("app.services.connection_service.detect_transfer_pairs", new_callable=AsyncMock), \patch("app.services.connection_service.stamp_primary_amount", new_callable=AsyncMock), \patch("app.services.connection_service.apply_rules_to_transaction", new_callable=AsyncMock):- await sync_connection(session, conn.id, test_user.id)+ await sync_connection(session, conn.id, test_workspace.id, test_user.id)rows = (await session.execute(select(Transaction).where(@@ -1789,7 +1789,7 @@ async def test_sync_upgrades_pending_to_posted_when_twin_arrives(@pytest.mark.asyncioasync def test_sync_dedupes_advanced_installment_payment(- session: AsyncSession, test_user,+ session: AsyncSession, test_user, test_workspace,):"""A credit-card installment paid in advance shows up as posted on thecurrent bill *and* pending on the next bill. Two different external@@ -1842,7 +1842,7 @@ async def test_sync_dedupes_advanced_installment_payment(p1, p2, p3 = _patch_sync_helpers()with patch("app.services.connection_service.get_provider", return_value=mock_provider), \p1, p2, p3:- await sync_connection(session, conn.id, test_user.id)+ await sync_connection(session, conn.id, test_workspace.id, test_user.id)rows = (await session.execute(select(Transaction).where(@@ -1869,7 +1869,7 @@ async def test_sync_dedupes_advanced_installment_payment(@pytest.mark.asyncioasync def test_sync_dedupes_advanced_installment_when_pending_lands_first(- session: AsyncSession, test_user,+ session: AsyncSession, test_user, test_workspace,):"""Same as the previous test but the pending next-bill row arrivesbefore the posted current-bill row in the fetch list. Order must not@@ -1916,7 +1916,7 @@ async def test_sync_dedupes_advanced_installment_when_pending_lands_first(p1, p2, p3 = _patch_sync_helpers()with patch("app.services.connection_service.get_provider", return_value=mock_provider), \p1, p2, p3:- await sync_connection(session, conn.id, test_user.id)+ await sync_connection(session, conn.id, test_workspace.id, test_user.id)rows = (await session.execute(select(Transaction).where(@@ -1931,7 +1931,7 @@ async def test_sync_dedupes_advanced_installment_when_pending_lands_first(@pytest.mark.asyncioasync def test_sync_keeps_genuine_same_day_repeats(- session: AsyncSession, test_user,+ session: AsyncSession, test_user, test_workspace,):"""Two genuine same-day same-amount transactions with byte-identicaldescriptions and identical statuses must NOT be collapsed — those are@@ -1966,7 +1966,7 @@ async def test_sync_keeps_genuine_same_day_repeats(patch("app.services.connection_service.detect_transfer_pairs", new_callable=AsyncMock), \patch("app.services.connection_service.stamp_primary_amount", new_callable=AsyncMock), \patch("app.services.connection_service.apply_rules_to_transaction", new_callable=AsyncMock):- await sync_connection(session, conn.id, test_user.id)+ await sync_connection(session, conn.id, test_workspace.id, test_user.id)rows = (await session.execute(select(Transaction).where(diff --git a/backend/tests/test_credit_card_accounting_mode.py b/backend/tests/test_credit_card_accounting_mode.pyindex 677628c8..463f1336 100644--- a/backend/tests/test_credit_card_accounting_mode.py+++ b/backend/tests/test_credit_card_accounting_mode.py@@ -427,54 +427,54 @@ class TestDashboardSummary:await session.commit()@pytest.mark.asyncio- async def test_cash_mode_april_totals(self, session, test_user, seeded):+ async def test_cash_mode_april_totals(self, session, test_user, test_workspace, seeded):await _set_mode(session, "cash")summary = await dashboard_service.get_summary(- session, test_user.id, month=date(2026, 4, 1)+ session, test_workspace.id, test_user.id, month=date(2026, 4, 1))# Cash: Apr 5 (50) + Apr 12 (30) + Apr 20 (20) = 100assert summary.monthly_expenses == 100.0@pytest.mark.asyncio- async def test_accrual_mode_april_totals(self, session, test_user, seeded):+ async def test_accrual_mode_april_totals(self, session, test_user, test_workspace, seeded):await _set_mode(session, "accrual")summary = await dashboard_service.get_summary(- session, test_user.id, month=date(2026, 4, 1)+ session, test_workspace.id, test_user.id, month=date(2026, 4, 1))# Accrual: Mar 30 (100) + Apr 5 (50) = 150# (both bills hit Apr 16, land in the April month bucket)assert summary.monthly_expenses == 150.0@pytest.mark.asyncio- async def test_cash_mode_may_totals(self, session, test_user, seeded):+ async def test_cash_mode_may_totals(self, session, test_user, test_workspace, seeded):await _set_mode(session, "cash")summary = await dashboard_service.get_summary(- session, test_user.id, month=date(2026, 5, 1)+ session, test_workspace.id, test_user.id, month=date(2026, 5, 1))# Cash: no May purchasesassert summary.monthly_expenses == 0.0@pytest.mark.asyncio- async def test_accrual_mode_may_totals(self, session, test_user, seeded):+ async def test_accrual_mode_may_totals(self, session, test_user, test_workspace, seeded):await _set_mode(session, "accrual")summary = await dashboard_service.get_summary(- session, test_user.id, month=date(2026, 5, 1)+ session, test_workspace.id, test_user.id, month=date(2026, 5, 1))# Accrual: Apr 12 (30) + Apr 20 (20) = 50 — bills due May 16assert summary.monthly_expenses == 50.0@pytest.mark.asyncio- async def test_total_conserved_across_modes(self, session, test_user, seeded):+ async def test_total_conserved_across_modes(self, session, test_user, test_workspace, seeded):"""The grand total across enough months must match regardless of mode."""await _set_mode(session, "cash")cash_total = 0.0for m in [date(2026, 3, 1), date(2026, 4, 1), date(2026, 5, 1), date(2026, 6, 1)]:- s = await dashboard_service.get_summary(session, test_user.id, month=m)+ s = await dashboard_service.get_summary(session, test_workspace.id, test_user.id, month=m)cash_total += s.monthly_expensesawait _set_mode(session, "accrual")accrual_total = 0.0for m in [date(2026, 3, 1), date(2026, 4, 1), date(2026, 5, 1), date(2026, 6, 1)]:- s = await dashboard_service.get_summary(session, test_user.id, month=m)+ s = await dashboard_service.get_summary(session, test_workspace.id, test_user.id, month=m)accrual_total += s.monthly_expenses# All 4 charges account for R$200 total regardless of which month buckets them.assert cash_total == 200.0@@ -489,7 +489,7 @@ class TestDashboardSummary:class TestSpendingByCategory:@pytest.mark.asyncioasync def test_category_breakdown_follows_mode(- self, session, test_user, cc_account, test_categories+ self, session, test_user, test_workspace, cc_account, test_categories):food = test_categories[0]transport = test_categories[1]@@ -507,7 +507,7 @@ class TestSpendingByCategory:await _set_mode(session, "cash")cash = await dashboard_service.get_spending_by_category(- session, test_user.id, month=date(2026, 4, 1)+ session, test_workspace.id, test_user.id, month=date(2026, 4, 1))cash_map = {c.category_name: c.total for c in cash}# Cash April: only Apr 12 transport R$40 counts@@ -516,7 +516,7 @@ class TestSpendingByCategory:await _set_mode(session, "accrual")accrual = await dashboard_service.get_spending_by_category(- session, test_user.id, month=date(2026, 4, 1)+ session, test_workspace.id, test_user.id, month=date(2026, 4, 1))accrual_map = {c.category_name: c.total for c in accrual}# Accrual April: Mar 30 food R$100 bills Apr 16@@ -532,7 +532,7 @@ class TestSpendingByCategory:class TestBudgetVsActual:@pytest.mark.asyncioasync def test_budget_spending_follows_mode(- self, session, test_user, cc_account, test_categories+ self, session, test_user, test_workspace, cc_account, test_categories):from app.models.budget import Budgetfood = test_categories[0]@@ -566,7 +566,7 @@ class TestBudgetVsActual:await _set_mode(session, "cash")cash = await budget_service.get_budget_vs_actual(- session, test_user.id, date(2026, 4, 1)+ session, test_workspace.id, test_user.id, date(2026, 4, 1))cash_food = next((c for c in cash if c.category_id == food.id), None)# Cash April: Apr 5 (30) + Apr 15 (20) = 50@@ -575,7 +575,7 @@ class TestBudgetVsActual:await _set_mode(session, "accrual")accrual = await budget_service.get_budget_vs_actual(- session, test_user.id, date(2026, 4, 1)+ session, test_workspace.id, test_user.id, date(2026, 4, 1))accrual_food = next((c for c in accrual if c.category_id == food.id), None)# Accrual April: Mar 30 (150) + Apr 5 (30) = 180@@ -614,7 +614,7 @@ class TestAccountBalanceInvariant:@pytest.mark.asyncioasync def test_account_balance_history_unchanged_by_mode(- self, session, test_user, test_account+ self, session, test_user, test_workspace, test_account):"""Non-CC account: effective_date == date so both modes are identical."""await _make_tx(@@ -625,12 +625,12 @@ class TestAccountBalanceInvariant:await _set_mode(session, "cash")cash = await account_service.get_account_balance_history(- session, test_account.id, test_user.id,+ session, test_account.id, test_workspace.id,date_from=date(2026, 4, 1), date_to=date(2026, 4, 30),)await _set_mode(session, "accrual")accrual = await account_service.get_account_balance_history(- session, test_account.id, test_user.id,+ session, test_account.id, test_workspace.id,date_from=date(2026, 4, 1), date_to=date(2026, 4, 30),)assert cash == accrual@@ -644,14 +644,14 @@ class TestAccountBalanceInvariant:class TestTransactionUpdateRefreshesEffectiveDate:@pytest.mark.asyncioasync def test_changing_date_on_cc_tx_refreshes_effective_date(- self, session, test_user, cc_account+ self, session, test_user, test_workspace, cc_account):from app.schemas.transaction import TransactionUpdatefrom app.services.transaction_service import create_transaction, update_transactionfrom app.schemas.transaction import TransactionCreatecreated = await create_transaction(- session, test_user.id,+ session, test_workspace.id, test_user.id,TransactionCreate(account_id=cc_account.id,description="test",@@ -664,7 +664,7 @@ class TestTransactionUpdateRefreshesEffectiveDate:assert created.effective_date == date(2026, 4, 16)updated = await update_transaction(- session, created.id, test_user.id,+ session, created.id, test_workspace.id, test_user.id,TransactionUpdate(date=date(2026, 4, 12)) # Apr 12 → effective May 16)assert updated is not None@@ -679,7 +679,7 @@ class TestTransactionUpdateRefreshesEffectiveDate:class TestAccountCycleEditRecomputesEffectiveDates:@pytest.mark.asyncioasync def test_changing_close_day_rebuckets_historical_txs(- self, session, test_user, cc_account+ self, session, test_user, test_workspace, cc_account):from app.schemas.account import AccountUpdate@@ -699,7 +699,7 @@ class TestAccountCycleEditRecomputesEffectiveDates:# Mar 5 → cycle Feb 26..Mar 25 → bill due Apr 16# Mar 20 → cycle Feb 26..Mar 25 → bill due Apr 16await account_service.update_account(- session, cc_account.id, test_user.id,+ session, cc_account.id, test_workspace.id,AccountUpdate(statement_close_day=25))result = await session.execute(@@ -719,7 +719,7 @@ class TestAccountCycleEditRecomputesEffectiveDates:class TestEffectiveBillDateFiltersList:@pytest.mark.asyncioasync def test_override_moves_tx_between_cycles_in_cash_mode(- self, session, test_user, cc_account+ self, session, test_user, test_workspace, cc_account):"""A tx whose natural date falls in May, but with an effective_bill_datein March, must be returned for a March-window query AND excluded from@@ -737,7 +737,7 @@ class TestEffectiveBillDateFiltersList:# March window: should include the override'd tx.march_txs, _, _ = await get_transactions(- session, test_user.id, account_id=cc_account.id,+ session, test_workspace.id, test_user.id, account_id=cc_account.id,from_date=date(2026, 2, 16), to_date=date(2026, 3, 15),accounting_mode="cash",)@@ -745,7 +745,7 @@ class TestEffectiveBillDateFiltersList:# May window: should NOT include it anymore.may_txs, _, _ = await get_transactions(- session, test_user.id, account_id=cc_account.id,+ session, test_workspace.id, test_user.id, account_id=cc_account.id,from_date=date(2026, 4, 16), to_date=date(2026, 5, 15),accounting_mode="cash",)@@ -753,7 +753,7 @@ class TestEffectiveBillDateFiltersList:@pytest.mark.asyncioasync def test_override_moves_tx_between_cycles_in_accrual_mode(- self, session, test_user, cc_account+ self, session, test_user, test_workspace, cc_account):"""Same behavior in accrual mode — override must beat both modes'default columns."""@@ -768,7 +768,7 @@ class TestEffectiveBillDateFiltersList:await session.commit()march_txs, _, _ = await get_transactions(- session, test_user.id, account_id=cc_account.id,+ session, test_workspace.id, test_user.id, account_id=cc_account.id,from_date=date(2026, 2, 16), to_date=date(2026, 3, 15),accounting_mode="accrual",)@@ -776,7 +776,7 @@ class TestEffectiveBillDateFiltersList:@pytest.mark.asyncioasync def test_bill_id_filter_includes_unlinked_txs_in_cycle_window(- self, session, test_user, cc_account+ self, session, test_user, test_workspace, cc_account):"""When a tx is NOT linked to the bill via bill_id (e.g. a manualrecurring entry the user added to compensate for a tx Pluggy failed@@ -816,7 +816,7 @@ class TestEffectiveBillDateFiltersList:# Cycle window for this bill = [Mar 17, Apr 16]txs, _, _ = await get_transactions(- session, test_user.id, account_id=cc_account.id,+ session, test_workspace.id, test_user.id, account_id=cc_account.id,bill_id=bill.id,from_date=date(2026, 3, 17), to_date=date(2026, 4, 16),accounting_mode="cash",@@ -830,7 +830,7 @@ class TestEffectiveBillDateFiltersList:@pytest.mark.asyncioasync def test_pending_sync_included_when_effective_date_matches_active_bill(- self, session, test_user, cc_account+ self, session, test_user, test_workspace, cc_account):"""Pending sync tx with bill_id NULL but effective_date == activebill's due_date IS included — cycle math pre-classified it to this@@ -862,7 +862,7 @@ class TestEffectiveBillDateFiltersList:await session.commit()txs, _, _ = await get_transactions(- session, test_user.id, account_id=cc_account.id,+ session, test_workspace.id, test_user.id, account_id=cc_account.id,bill_id=may_bill.id,from_date=date(2026, 4, 11), to_date=date(2026, 5, 10),accounting_mode="cash",@@ -871,7 +871,7 @@ class TestEffectiveBillDateFiltersList:@pytest.mark.asyncioasync def test_inprogress_cycle_includes_prev_close_day_tx_per_brazilian_convention(- self, session, test_user, cc_account+ self, session, test_user, test_workspace, cc_account):"""Brazilian convention: a tx ON the previous close day belongs to theNEXT cycle. Cycle math sets effective_date accordingly, but the@@ -894,7 +894,7 @@ class TestEffectiveBillDateFiltersList:# In-progress June cycle (cycle-math fallback, no bill_id passed)# range = [April 30, May 29] — the start INCLUDES the prev close day.txs, _, _ = await get_transactions(- session, test_user.id, account_id=cc_account.id,+ session, test_workspace.id, test_user.id, account_id=cc_account.id,from_date=date(2026, 4, 30), to_date=date(2026, 5, 29),accounting_mode="cash",)@@ -902,7 +902,7 @@ class TestEffectiveBillDateFiltersList:@pytest.mark.asyncioasync def test_inprogress_cycle_excludes_already_billed_txs(- self, session, test_user, cc_account+ self, session, test_user, test_workspace, cc_account):"""When the user views the in-progress cycle (no bill_id passed) butthe date window overlaps a closed bill's range, txs already linked@@ -936,7 +936,7 @@ class TestEffectiveBillDateFiltersList:# `unbilled_only` flag set (which account-detail uses for the# in-progress cycle), the prior-bill tx must NOT appear.txs, _, _ = await get_transactions(- session, test_user.id, account_id=cc_account.id,+ session, test_workspace.id, test_user.id, account_id=cc_account.id,from_date=date(2026, 4, 30), to_date=date(2026, 5, 29),accounting_mode="cash",unbilled_only=True,@@ -946,7 +946,7 @@ class TestEffectiveBillDateFiltersList:# Without unbilled_only (e.g., the global /transactions list page),# the same tx IS visible — the flag is opt-in.txs_unfiltered, _, _ = await get_transactions(- session, test_user.id, account_id=cc_account.id,+ session, test_workspace.id, test_user.id, account_id=cc_account.id,from_date=date(2026, 4, 30), to_date=date(2026, 5, 29),accounting_mode="cash",)@@ -954,7 +954,7 @@ class TestEffectiveBillDateFiltersList:@pytest.mark.asyncioasync def test_bill_view_filter_is_mode_independent(- self, session, test_user, cc_account+ self, session, test_user, test_workspace, cc_account):"""Bill view = bank-truth: a 4/30 charge with effective_date 6/10must show in the in-progress June cycle in BOTH cash and accrual@@ -978,7 +978,7 @@ class TestEffectiveBillDateFiltersList:for mode in ("cash", "accrual"):txs, _, _ = await get_transactions(- session, test_user.id, account_id=cc_account.id,+ session, test_workspace.id, test_user.id, account_id=cc_account.id,from_date=date(2026, 4, 30), to_date=date(2026, 5, 29),accounting_mode=mode,unbilled_only=True,@@ -989,7 +989,7 @@ class TestEffectiveBillDateFiltersList:@pytest.mark.asyncioasync def test_global_list_still_mode_aware_outside_bill_view(- self, session, test_user, cc_account+ self, session, test_user, test_workspace, cc_account):"""Regression guard: outside the bill view (no bill_id, nounbilled_only), the global list MUST still respect accounting@@ -1009,7 +1009,7 @@ class TestEffectiveBillDateFiltersList:# Cash mode: filtered by purchase date → in April windowtxs_cash_apr, _, _ = await get_transactions(- session, test_user.id, account_id=cc_account.id,+ session, test_workspace.id, test_user.id, account_id=cc_account.id,from_date=date(2026, 4, 1), to_date=date(2026, 4, 30),accounting_mode="cash",)@@ -1019,14 +1019,14 @@ class TestEffectiveBillDateFiltersList:# but IS in June window. This is the existing mode-aware semantic# callers outside the bill view rely on.txs_accrual_apr, _, _ = await get_transactions(- session, test_user.id, account_id=cc_account.id,+ session, test_workspace.id, test_user.id, account_id=cc_account.id,from_date=date(2026, 4, 1), to_date=date(2026, 4, 30),accounting_mode="accrual",)assert tx.id not in {t.id for t in txs_accrual_apr}txs_accrual_jun, _, _ = await get_transactions(- session, test_user.id, account_id=cc_account.id,+ session, test_workspace.id, test_user.id, account_id=cc_account.id,from_date=date(2026, 6, 1), to_date=date(2026, 6, 30),accounting_mode="accrual",)@@ -1034,7 +1034,7 @@ class TestEffectiveBillDateFiltersList:@pytest.mark.asyncioasync def test_pending_sync_excluded_from_past_bill_when_effective_date_points_elsewhere(- self, session, test_user, cc_account+ self, session, test_user, test_workspace, cc_account):"""Reverse case: pending sync tx whose effective_date points to aFUTURE bill must NOT show in a past closed bill. Keeps ingrid's@@ -1065,7 +1065,7 @@ class TestEffectiveBillDateFiltersList:# Viewing April bill — must NOT include this pending txtxs, _, _ = await get_transactions(- session, test_user.id, account_id=cc_account.id,+ session, test_workspace.id, test_user.id, account_id=cc_account.id,bill_id=april_bill.id,from_date=date(2026, 3, 11), to_date=date(2026, 4, 10),accounting_mode="cash",@@ -1074,7 +1074,7 @@ class TestEffectiveBillDateFiltersList:@pytest.mark.asyncioasync def test_bill_id_filter_excludes_pending_sync_pointing_to_other_bill(- self, session, test_user, cc_account+ self, session, test_user, test_workspace, cc_account):"""Pending sync txs whose effective_date points to a DIFFERENT bill(cycle math classified them elsewhere) must NOT auto-bucket into@@ -1126,7 +1126,7 @@ class TestEffectiveBillDateFiltersList:await session.commit()txs, _, _ = await get_transactions(- session, test_user.id, account_id=cc_account.id,+ session, test_workspace.id, test_user.id, account_id=cc_account.id,bill_id=april.id,from_date=date(2026, 3, 17), to_date=date(2026, 4, 16),accounting_mode="cash",@@ -1141,7 +1141,7 @@ class TestEffectiveBillDateFiltersList:@pytest.mark.asyncioasync def test_bill_id_filter_excludes_unlinked_txs_outside_window(- self, session, test_user, cc_account+ self, session, test_user, test_workspace, cc_account):"""An unlinked tx with a date outside the cycle window must NOT becounted — otherwise we'd pick up unrelated manual entries."""@@ -1168,7 +1168,7 @@ class TestEffectiveBillDateFiltersList:await session.commit()txs, _, _ = await get_transactions(- session, test_user.id, account_id=cc_account.id,+ session, test_workspace.id, test_user.id, account_id=cc_account.id,bill_id=bill.id,from_date=date(2026, 3, 17), to_date=date(2026, 4, 16),accounting_mode="cash",@@ -1177,7 +1177,7 @@ class TestEffectiveBillDateFiltersList:@pytest.mark.asyncioasync def test_bill_id_filter_includes_pending_tx_with_bill_id_set(- self, session, test_user, cc_account+ self, session, test_user, test_workspace, cc_account):"""The pending-sync exclusion only applies when bill_id IS NULL.A pending tx that Pluggy already tagged with a billId is still@@ -1209,7 +1209,7 @@ class TestEffectiveBillDateFiltersList:await session.commit()txs, _, _ = await get_transactions(- session, test_user.id, account_id=cc_account.id,+ session, test_workspace.id, test_user.id, account_id=cc_account.id,bill_id=bill.id,from_date=date(2026, 3, 17), to_date=date(2026, 4, 16),accounting_mode="cash",@@ -1218,7 +1218,7 @@ class TestEffectiveBillDateFiltersList:@pytest.mark.asyncioasync def test_bill_id_filter_includes_posted_sync_unlinked_in_window(- self, session, test_user, cc_account+ self, session, test_user, test_workspace, cc_account):"""Posted sync tx without billId is the rare case where the providerreturned the tx but didn't tag a bill. Date-window inclusion is@@ -1249,7 +1249,7 @@ class TestEffectiveBillDateFiltersList:await session.commit()txs, _, _ = await get_transactions(- session, test_user.id, account_id=cc_account.id,+ session, test_workspace.id, test_user.id, account_id=cc_account.id,bill_id=bill.id,from_date=date(2026, 3, 17), to_date=date(2026, 4, 16),accounting_mode="cash",@@ -1258,7 +1258,7 @@ class TestEffectiveBillDateFiltersList:@pytest.mark.asyncioasync def test_bill_id_filter_includes_ofx_imported_in_window(- self, session, test_user, cc_account+ self, session, test_user, test_workspace, cc_account):"""An OFX import is a definitive user intent — must count toward thebill cycle whose window contains its date. Confirms the pending-sync@@ -1286,7 +1286,7 @@ class TestEffectiveBillDateFiltersList:await session.commit()txs, _, _ = await get_transactions(- session, test_user.id, account_id=cc_account.id,+ session, test_workspace.id, test_user.id, account_id=cc_account.id,bill_id=bill.id,from_date=date(2026, 3, 17), to_date=date(2026, 4, 16),accounting_mode="cash",@@ -1295,7 +1295,7 @@ class TestEffectiveBillDateFiltersList:@pytest.mark.asyncioasync def test_override_to_date_with_no_matching_bill_keeps_bill_id_null(- self, session, test_user, cc_account+ self, session, test_user, test_workspace, cc_account):"""The user can pick any date as effective_bill_date — including onethat doesn't correspond to a known bill (e.g. a far-future statement@@ -1314,7 +1314,7 @@ class TestEffectiveBillDateFiltersList:# No bill exists for 2099-01-01 — override still takes effectawait update_transaction(- session, tx.id, test_user.id,+ session, tx.id, test_workspace.id, test_user.id,TransactionUpdate(effective_bill_date=date(2099, 1, 1)),)await session.commit()@@ -1326,7 +1326,7 @@ class TestEffectiveBillDateFiltersList:@pytest.mark.asyncioasync def test_credit_tx_with_bill_id_counts_as_income(- self, session, test_user, cc_account+ self, session, test_user, test_workspace, cc_account):"""Refund/return txs are type=credit. Per-bill summary must includethem in monthly_income when their bill_id matches — otherwise CC@@ -1355,7 +1355,7 @@ class TestEffectiveBillDateFiltersList:await session.commit()summary = await get_account_summary(- session, cc_account.id, test_user.id,+ session, cc_account.id, test_workspace.id,date_from=date(2026, 3, 17), date_to=date(2026, 4, 16),bill_id=bill.id,)@@ -1363,7 +1363,7 @@ class TestEffectiveBillDateFiltersList:@pytest.mark.asyncioasync def test_cc_refund_credit_nets_against_debits_in_bill_total(- self, session, test_user, cc_account+ self, session, test_user, test_workspace, cc_account):"""For CC accounts, refund credits must subtract from the cycle'smonthly_expenses so 'Total da fatura' matches the bank's bill (which@@ -1411,7 +1411,7 @@ class TestEffectiveBillDateFiltersList:await session.commit()summary = await get_account_summary(- session, cc_account.id, test_user.id,+ session, cc_account.id, test_workspace.id,date_from=date(2026, 3, 17), date_to=date(2026, 4, 16),bill_id=bill.id,)@@ -1420,7 +1420,7 @@ class TestEffectiveBillDateFiltersList:@pytest.mark.asyncioasync def test_non_cc_account_keeps_debit_only_expenses(- self, session, test_user, test_connection+ self, session, test_user, test_workspace, test_connection):"""For non-CC accounts (checking, etc.), monthly_expenses must STAYas sum-of-debits — credits there are income, not refunds. Confirms@@ -1451,7 +1451,7 @@ class TestEffectiveBillDateFiltersList:await session.commit()summary = await get_account_summary(- session, checking.id, test_user.id,+ session, checking.id, test_workspace.id,date_from=date(2026, 4, 1), date_to=date(2026, 4, 30),)assert summary["monthly_expenses"] == 50.0@@ -1459,7 +1459,7 @@ class TestEffectiveBillDateFiltersList:@pytest.mark.asyncioasync def test_year_boundary_cycle_buckets_correctly(- self, session, test_user, cc_account+ self, session, test_user, test_workspace, cc_account):"""December → January cycle: a tx dated 27/12 with override 5/1 mustbucket into the January cycle, not December. Catches off-by-month@@ -1477,7 +1477,7 @@ class TestEffectiveBillDateFiltersList:# December window: tx must NOT appear (override moved it to Jan)dec_txs, _, _ = await get_transactions(- session, test_user.id, account_id=cc_account.id,+ session, test_workspace.id, test_user.id, account_id=cc_account.id,from_date=date(2025, 12, 1), to_date=date(2025, 12, 31),accounting_mode="cash",)@@ -1485,7 +1485,7 @@ class TestEffectiveBillDateFiltersList:# January window: tx must appearjan_txs, _, _ = await get_transactions(- session, test_user.id, account_id=cc_account.id,+ session, test_workspace.id, test_user.id, account_id=cc_account.id,from_date=date(2026, 1, 1), to_date=date(2026, 1, 31),accounting_mode="cash",)@@ -1493,7 +1493,7 @@ class TestEffectiveBillDateFiltersList:@pytest.mark.asyncioasync def test_summary_excludes_pending_sync_pointing_to_other_bill(- self, session, test_user, cc_account+ self, session, test_user, test_workspace, cc_account):"""get_account_summary applies the same effective_date-aware pendingrule as get_transactions — pending sync pointing to a DIFFERENT bill@@ -1532,7 +1532,7 @@ class TestEffectiveBillDateFiltersList:await session.commit()summary = await get_account_summary(- session, cc_account.id, test_user.id,+ session, cc_account.id, test_workspace.id,date_from=date(2026, 3, 17), date_to=date(2026, 4, 16),bill_id=bill.id,)@@ -1541,7 +1541,7 @@ class TestEffectiveBillDateFiltersList:@pytest.mark.asyncioasync def test_override_unset_falls_back_to_mode_column(- self, session, test_user, cc_account+ self, session, test_user, test_workspace, cc_account):"""Without an override, the configured accounting mode's column(date for cash, effective_date for accrual) drives bucketing."""@@ -1556,7 +1556,7 @@ class TestEffectiveBillDateFiltersList:# April window: cash mode uses date (Apr 18), should includeapr_txs, _, _ = await get_transactions(- session, test_user.id, account_id=cc_account.id,+ session, test_workspace.id, test_user.id, account_id=cc_account.id,from_date=date(2026, 4, 1), to_date=date(2026, 4, 30),accounting_mode="cash",)@@ -1564,7 +1564,7 @@ class TestEffectiveBillDateFiltersList:@pytest.mark.asyncioasync def test_override_on_pending_sync_tx_shows_in_target_bill(- self, session, test_user, cc_account+ self, session, test_user, test_workspace, cc_account):"""A pending sync tx with a manual `effective_bill_date` whose valuedoes NOT exactly match any bill's due_date (so `bill_id` stays null)@@ -1601,7 +1601,7 @@ class TestEffectiveBillDateFiltersList:await session.commit()may_txs, _, _ = await get_transactions(- session, test_user.id, account_id=cc_account.id,+ session, test_workspace.id, test_user.id, account_id=cc_account.id,bill_id=may.id,from_date=date(2026, 4, 17), to_date=date(2026, 5, 16),accounting_mode="cash",@@ -1613,7 +1613,7 @@ class TestEffectiveBillDateFiltersList:@pytest.mark.asyncioasync def test_summary_includes_pending_sync_with_override(- self, session, test_user, cc_account+ self, session, test_user, test_workspace, cc_account):"""get_account_summary mirrors get_transactions: a pending sync txwith `effective_bill_date` in the cycle window must contribute to@@ -1645,7 +1645,7 @@ class TestEffectiveBillDateFiltersList:await session.commit()summary = await get_account_summary(- session, cc_account.id, test_user.id,+ session, cc_account.id, test_workspace.id,date_from=date(2026, 4, 17), date_to=date(2026, 5, 16),bill_id=may.id,)@@ -1653,7 +1653,7 @@ class TestEffectiveBillDateFiltersList:@pytest.mark.asyncioasync def test_override_past_in_progress_window_lands_in_in_progress(- self, session, test_user, cc_account+ self, session, test_user, test_workspace, cc_account):"""User sets `effective_bill_date` to a date past the in-progresscycle's right edge — typically because they want the tx on a future@@ -1678,7 +1678,7 @@ class TestEffectiveBillDateFiltersList:# In-progress cycle window for close=11/due=16 around early May:# cycle = [Apr 12, May 11]. Override 6/11 lies past 5/11.in_prog_txs, _, _ = await get_transactions(- session, test_user.id, account_id=cc_account.id,+ session, test_workspace.id, test_user.id, account_id=cc_account.id,from_date=date(2026, 4, 12), to_date=date(2026, 5, 11),unbilled_only=True,accounting_mode="cash",@@ -1689,7 +1689,7 @@ class TestEffectiveBillDateFiltersList:)summary = await get_account_summary(- session, cc_account.id, test_user.id,+ session, cc_account.id, test_workspace.id,date_from=date(2026, 4, 12), date_to=date(2026, 5, 11),unbilled_only=True,)diff --git a/backend/tests/test_dashboard_service.py b/backend/tests/test_dashboard_service.pyindex 302ddb5d..d6d60bbc 100644--- a/backend/tests/test_dashboard_service.py+++ b/backend/tests/test_dashboard_service.py@@ -110,12 +110,12 @@ def test_month_range_january():@pytest.mark.asyncio-async def test_get_open_accounts(session: AsyncSession, test_user):+async def test_get_open_accounts(session: AsyncSession, test_user, test_workspace):"""Returns only non-closed accounts."""open_acc = await _make_account(session, test_user.id, "Open")closed_acc = await _make_account(session, test_user.id, "Closed", is_closed=True)- accounts = await _get_open_accounts(session, test_user.id)+ accounts = await _get_open_accounts(session, test_workspace.id)ids = [a.id for a in accounts]assert open_acc.id in idsassert closed_acc.id not in ids@@ -194,7 +194,7 @@ async def test_account_balance_at_credit_card_connected(session: AsyncSession, t@pytest.mark.asyncio-async def test_total_balance_by_currency(session: AsyncSession, test_user):+async def test_total_balance_by_currency(session: AsyncSession, test_user, test_workspace):"""Total balance groups by currency."""brl_acc = await _make_account(session, test_user.id, "BRL", currency="BRL")usd_acc = await _make_account(session, test_user.id, "USD", currency="USD")@@ -203,7 +203,7 @@ async def test_total_balance_by_currency(session: AsyncSession, test_user):await _add_txn(session, test_user.id, brl_acc.id, 1000, "credit", today, source="opening_balance")await _add_txn(session, test_user.id, usd_acc.id, 500, "credit", today, source="opening_balance")- totals = await _total_balance_by_currency(session, test_user.id, today)+ totals = await _total_balance_by_currency(session, test_workspace.id, today)assert totals.get("BRL", 0) == pytest.approx(1000.0)assert totals.get("USD", 0) == pytest.approx(500.0)@@ -214,7 +214,7 @@ async def test_total_balance_by_currency(session: AsyncSession, test_user):@pytest.mark.asyncio-async def test_get_summary_basic(session: AsyncSession, test_user):+async def test_get_summary_basic(session: AsyncSession, test_user, test_workspace):"""Summary returns correct structure with balances and counts."""account = await _make_account(session, test_user.id, "Summary Acc")today = date.today()@@ -223,24 +223,24 @@ async def test_get_summary_basic(session: AsyncSession, test_user):await _add_txn(session, test_user.id, account.id, 200, "debit", today)await _add_txn(session, test_user.id, account.id, 100, "credit", today)- summary = await get_summary(session, test_user.id)+ summary = await get_summary(session, test_workspace.id, test_user.id)assert summary.monthly_income == pytest.approx(100.0)assert summary.monthly_expenses == pytest.approx(200.0)assert summary.accounts_count >= 1@pytest.mark.asyncio-async def test_get_summary_excludes_opening_balance_from_income(session: AsyncSession, test_user):+async def test_get_summary_excludes_opening_balance_from_income(session: AsyncSession, test_user, test_workspace):"""Opening balance does not count as monthly income."""account = await _make_account(session, test_user.id, "No OB Income")await _add_txn(session, test_user.id, account.id, 10000, "credit", date.today(), source="opening_balance")- summary = await get_summary(session, test_user.id)+ summary = await get_summary(session, test_workspace.id, test_user.id)assert summary.monthly_income == pytest.approx(0.0)@pytest.mark.asyncio-async def test_get_summary_excludes_transfers(session: AsyncSession, test_user):+async def test_get_summary_excludes_transfers(session: AsyncSession, test_user, test_workspace):"""Transfer pair transactions excluded from income/expenses."""account = await _make_account(session, test_user.id, "Transfer Excl")today = date.today()@@ -249,12 +249,12 @@ async def test_get_summary_excludes_transfers(session: AsyncSession, test_user):await _add_txn(session, test_user.id, account.id, 500, "debit", today, transfer_pair_id=pair_id)await _add_txn(session, test_user.id, account.id, 100, "debit", today)- summary = await get_summary(session, test_user.id)+ summary = await get_summary(session, test_workspace.id, test_user.id)assert summary.monthly_expenses == pytest.approx(100.0)@pytest.mark.asyncio-async def test_get_summary_pending_categorization(session: AsyncSession, test_user):+async def test_get_summary_pending_categorization(session: AsyncSession, test_user, test_workspace):"""Summary counts uncategorized transactions."""account = await _make_account(session, test_user.id, "Pending Cat")today = date.today()@@ -264,12 +264,12 @@ async def test_get_summary_pending_categorization(session: AsyncSession, test_usawait _add_txn(session, test_user.id, account.id, 200, "debit", today)await _add_txn(session, test_user.id, account.id, 5000, "credit", today, source="opening_balance")- summary = await get_summary(session, test_user.id)+ summary = await get_summary(session, test_workspace.id, test_user.id)assert summary.pending_categorization >= 2@pytest.mark.asyncio-async def test_get_summary_with_specific_month(session: AsyncSession, test_user):+async def test_get_summary_with_specific_month(session: AsyncSession, test_user, test_workspace):"""Summary uses the specified month."""account = await _make_account(session, test_user.id, "Month Test")today = date.today()@@ -278,14 +278,14 @@ async def test_get_summary_with_specific_month(session: AsyncSession, test_user)await _add_txn(session, test_user.id, account.id, 300, "debit", past)# Current month - no transactions- await get_summary(session, test_user.id, month=today.replace(day=1))+ await get_summary(session, test_workspace.id, test_user.id, month=today.replace(day=1))# Past month - has 300 debit- summary_past = await get_summary(session, test_user.id, month=past.replace(day=1))+ summary_past = await get_summary(session, test_workspace.id, test_user.id, month=past.replace(day=1))assert summary_past.monthly_expenses >= 300.0@pytest.mark.asyncio-async def test_get_summary_with_balance_date(session: AsyncSession, test_user):+async def test_get_summary_with_balance_date(session: AsyncSession, test_user, test_workspace):"""balance_date overrides the default cutoff for balance calculation."""account = await _make_account(session, test_user.id, "Balance Date")today = date.today()@@ -295,7 +295,7 @@ async def test_get_summary_with_balance_date(session: AsyncSession, test_user):# With cutoff 5 days ago, the 500 debit shouldn't be includedsummary = await get_summary(- session, test_user.id, month=today.replace(day=1),+ session, test_workspace.id, test_user.id, month=today.replace(day=1),balance_date=today - timedelta(days=5),)total = sum(summary.total_balance.values())@@ -308,7 +308,7 @@ async def test_get_summary_with_balance_date(session: AsyncSession, test_user):@pytest.mark.asyncio-async def test_spending_by_category_basic(session: AsyncSession, test_user):+async def test_spending_by_category_basic(session: AsyncSession, test_user, test_workspace):"""Returns spending grouped by category."""cat = await _make_category(session, test_user.id, "Food", color="#F00")account = await _make_account(session, test_user.id, "Spend Test")@@ -317,7 +317,7 @@ async def test_spending_by_category_basic(session: AsyncSession, test_user):await _add_txn(session, test_user.id, account.id, 100, "debit", today, category_id=cat.id)await _add_txn(session, test_user.id, account.id, 50, "debit", today, category_id=cat.id)- spending = await get_spending_by_category(session, test_user.id)+ spending = await get_spending_by_category(session, test_workspace.id, test_user.id)assert len(spending) > 0food = next((s for s in spending if s.category_id == str(cat.id)), None)assert food is not None@@ -325,21 +325,21 @@ async def test_spending_by_category_basic(session: AsyncSession, test_user):@pytest.mark.asyncio-async def test_spending_by_category_uncategorized(session: AsyncSession, test_user):+async def test_spending_by_category_uncategorized(session: AsyncSession, test_user, test_workspace):"""Uncategorized transactions show as 'Sem categoria'."""account = await _make_account(session, test_user.id, "Uncat Spend")today = date.today()await _add_txn(session, test_user.id, account.id, 75, "debit", today)- spending = await get_spending_by_category(session, test_user.id)+ spending = await get_spending_by_category(session, test_workspace.id, test_user.id)uncat = next((s for s in spending if s.category_id is None), None)assert uncat is not Noneassert uncat.category_name == "Sem categoria"@pytest.mark.asyncio-async def test_spending_excludes_credits(session: AsyncSession, test_user):+async def test_spending_excludes_credits(session: AsyncSession, test_user, test_workspace):"""Spending by category only includes debit transactions."""cat = await _make_category(session, test_user.id, "Income Cat")account = await _make_account(session, test_user.id, "Credit Excl")@@ -347,13 +347,13 @@ async def test_spending_excludes_credits(session: AsyncSession, test_user):await _add_txn(session, test_user.id, account.id, 1000, "credit", today, category_id=cat.id)- spending = await get_spending_by_category(session, test_user.id)+ spending = await get_spending_by_category(session, test_workspace.id, test_user.id)income = next((s for s in spending if s.category_id == str(cat.id)), None)assert income is None@pytest.mark.asyncio-async def test_spending_excludes_transfers(session: AsyncSession, test_user):+async def test_spending_excludes_transfers(session: AsyncSession, test_user, test_workspace):"""Transfer pairs are excluded from spending."""account = await _make_account(session, test_user.id, "Transfer Spend")today = date.today()@@ -361,14 +361,14 @@ async def test_spending_excludes_transfers(session: AsyncSession, test_user):await _add_txn(session, test_user.id, account.id, 500, "debit", today, transfer_pair_id=pair_id)- spending = await get_spending_by_category(session, test_user.id)+ spending = await get_spending_by_category(session, test_workspace.id, test_user.id)# No spending should include the transfertotal = sum(s.total for s in spending)assert 500 not in [s.total for s in spending] or total == 0@pytest.mark.asyncio-async def test_spending_percentage(session: AsyncSession, test_user):+async def test_spending_percentage(session: AsyncSession, test_user, test_workspace):"""Percentages sum to approximately 100%."""cat1 = await _make_category(session, test_user.id, "Cat A")cat2 = await _make_category(session, test_user.id, "Cat B")@@ -378,7 +378,7 @@ async def test_spending_percentage(session: AsyncSession, test_user):await _add_txn(session, test_user.id, account.id, 300, "debit", today, category_id=cat1.id)await _add_txn(session, test_user.id, account.id, 700, "debit", today, category_id=cat2.id)- spending = await get_spending_by_category(session, test_user.id)+ spending = await get_spending_by_category(session, test_workspace.id, test_user.id)total_pct = sum(s.percentage for s in spending)assert total_pct == pytest.approx(100.0, abs=0.1)@@ -389,7 +389,7 @@ async def test_spending_percentage(session: AsyncSession, test_user):@pytest.mark.asyncio-async def test_get_projected_transactions(session: AsyncSession, test_user):+async def test_get_projected_transactions(session: AsyncSession, test_user, test_workspace):"""Projected transactions include recurring template details."""cat = await _make_category(session, test_user.id, "Recurring Cat")@@ -412,7 +412,7 @@ async def test_get_projected_transactions(session: AsyncSession, test_user):session.add(rec)await session.commit()- projections = await get_projected_transactions(session, test_user.id, month=next_month)+ projections = await get_projected_transactions(session, test_workspace.id, test_user.id, month=next_month)assert len(projections) >= 4 # Weekly = at least 4 occurrencesfor proj in projections:@@ -422,7 +422,7 @@ async def test_get_projected_transactions(session: AsyncSession, test_user):@pytest.mark.asyncio-async def test_get_projected_transactions_no_category(session: AsyncSession, test_user):+async def test_get_projected_transactions_no_category(session: AsyncSession, test_user, test_workspace):"""Projected transactions work without category."""next_month = date.today().replace(day=1)if next_month.month == 12:@@ -442,7 +442,7 @@ async def test_get_projected_transactions_no_category(session: AsyncSession, tessession.add(rec)await session.commit()- projections = await get_projected_transactions(session, test_user.id, month=next_month)+ projections = await get_projected_transactions(session, test_workspace.id, test_user.id, month=next_month)assert len(projections) >= 1proj = projections[0]assert proj.category_name is None@@ -500,19 +500,19 @@ async def test_account_balance_bank_credit_card(session, test_user):@pytest.mark.asyncio-async def test_get_open_accounts_excludes_closed(session, test_user):+async def test_get_open_accounts_excludes_closed(session, test_user, test_workspace):closed = Account(id=uuid.uuid4(), user_id=test_user.id, name="Closed",type="checking", balance=Decimal("0"), currency="BRL", is_closed=True,)session.add(closed)await session.commit()- accounts = await _get_open_accounts(session, test_user.id)+ accounts = await _get_open_accounts(session, test_workspace.id)assert all(a.id != closed.id for a in accounts)@pytest.mark.asyncio-async def test_balance_at_single_currency(session, test_user):+async def test_balance_at_single_currency(session, test_user, test_workspace):acct = Account(id=uuid.uuid4(), user_id=test_user.id, name="BalAt",type="checking", balance=Decimal("0"), currency="BRL",@@ -529,20 +529,20 @@ async def test_balance_at_single_currency(session, test_user):session.add(txn)await session.commit()- bal = await _balance_at(session, test_user.id, date.today())+ bal = await _balance_at(session, test_workspace.id, date.today())assert bal >= 3000.0@pytest.mark.asyncio-async def test_get_summary_past_month(session, test_user):+async def test_get_summary_past_month(session, test_user, test_workspace):past = date.today().replace(day=1) - timedelta(days=30)past_month = past.replace(day=1)- summary = await get_summary(session, test_user.id, month=past_month)+ summary = await get_summary(session, test_workspace.id, test_user.id, month=past_month)assert summary is not None@pytest.mark.asyncio-async def test_spending_by_category_with_categorized(session, test_user, test_categories):+async def test_spending_by_category_with_categorized(session, test_user, test_workspace, test_categories):acct = Account(id=uuid.uuid4(), user_id=test_user.id, name="SpendCat",type="checking", balance=Decimal("0"), currency="BRL",@@ -560,13 +560,13 @@ async def test_spending_by_category_with_categorized(session, test_user, test_casession.add(txn)await session.commit()- result = await get_spending_by_category(session, test_user.id)+ result = await get_spending_by_category(session, test_workspace.id, test_user.id)cat_names = [s.category_name for s in result]assert test_categories[0].name in cat_names@pytest.mark.asyncio-async def test_get_recurring_projections(session, test_user):+async def test_get_recurring_projections(session, test_user, test_workspace):today = date.today()month_start = today.replace(day=1)if today.month == 12:@@ -583,13 +583,13 @@ async def test_get_recurring_projections(session, test_user):session.add(rec)await session.commit()- projections = await _get_recurring_projections(session, test_user.id, month_start, month_end)+ projections = await _get_recurring_projections(session, test_workspace.id, month_start, month_end)assert len(projections) >= 1assert projections[0]["amount"] == 2000.0@pytest.mark.asyncio-async def test_balance_history_basic(session, test_user):+async def test_balance_history_basic(session, test_user, test_workspace):acct = Account(id=uuid.uuid4(), user_id=test_user.id, name="BH",type="checking", balance=Decimal("0"), currency="BRL",@@ -606,16 +606,16 @@ async def test_balance_history_basic(session, test_user):session.add(txn)await session.commit()- history = await get_balance_history(session, test_user.id)+ history = await get_balance_history(session, test_workspace.id, test_user.id)assert len(history.current) > 0assert len(history.previous) > 0@pytest.mark.asyncio-async def test_balance_history_past_month(session, test_user):+async def test_balance_history_past_month(session, test_user, test_workspace):past = date.today().replace(day=1) - timedelta(days=15)past_month = past.replace(day=1)- history = await get_balance_history(session, test_user.id, month=past_month)+ history = await get_balance_history(session, test_workspace.id, test_user.id, month=past_month)assert len(history.current) > 0@@ -625,13 +625,13 @@ async def test_balance_history_past_month(session, test_user):@pytest.mark.asyncio-async def test_get_projected_transactions_empty(session, test_user):- result = await get_projected_transactions(session, test_user.id)+async def test_get_projected_transactions_empty(session, test_user, test_workspace):+ result = await get_projected_transactions(session, test_workspace.id, test_user.id)assert result == []@pytest.mark.asyncio-async def test_get_projected_transactions_with_recurring(session, test_user):+async def test_get_projected_transactions_with_recurring(session, test_user, test_workspace):today = date.today()month_start = today.replace(day=1)cat = Category(@@ -649,7 +649,7 @@ async def test_get_projected_transactions_with_recurring(session, test_user):session.add(rec)await session.commit()- result = await get_projected_transactions(session, test_user.id, month=month_start)+ result = await get_projected_transactions(session, test_workspace.id, test_user.id, month=month_start)assert len(result) >= 1assert result[0].description == "Monthly Rent"assert result[0].category_name == "Rent"@@ -662,7 +662,7 @@ async def test_get_projected_transactions_with_recurring(session, test_user):@pytest.mark.asyncio-async def test_get_summary_includes_recurring_projections(session, test_user):+async def test_get_summary_includes_recurring_projections(session, test_user, test_workspace):today = date.today()month_start = today.replace(day=1)@@ -680,7 +680,7 @@ async def test_get_summary_includes_recurring_projections(session, test_user):session.add(rec)await session.commit()- summary = await get_summary(session, test_user.id, month=month_start)+ summary = await get_summary(session, test_workspace.id, test_user.id, month=month_start)assert summary.monthly_income >= 10000.0@@ -690,7 +690,7 @@ async def test_get_summary_includes_recurring_projections(session, test_user):@pytest.mark.asyncio-async def test_spending_by_category_includes_recurring(session, test_user):+async def test_spending_by_category_includes_recurring(session, test_user, test_workspace):today = date.today()month_start = today.replace(day=1)@@ -716,7 +716,7 @@ async def test_spending_by_category_includes_recurring(session, test_user):session.add(rec)await session.commit()- spending = await get_spending_by_category(session, test_user.id, month=month_start)+ spending = await get_spending_by_category(session, test_workspace.id, test_user.id, month=month_start)assert len(spending) >= 1transport = next((s for s in spending if s.category_name == "Transport"), None)assert transport is not None@@ -729,7 +729,7 @@ async def test_spending_by_category_includes_recurring(session, test_user):@pytest.mark.asyncio-async def test_balance_at_multi_currency(session, test_user):+async def test_balance_at_multi_currency(session, test_user, test_workspace):acct_brl = Account(id=uuid.uuid4(), user_id=test_user.id, name="BRL Acct",type="checking", balance=Decimal("0"), currency="BRL",@@ -751,7 +751,7 @@ async def test_balance_at_multi_currency(session, test_user):session.add(txn)await session.commit()- total = await _balance_at(session, test_user.id, date.today())+ total = await _balance_at(session, test_workspace.id, date.today())assert total > 0diff --git a/backend/tests/test_fx_rates.py b/backend/tests/test_fx_rates.pyindex a3f32e78..052c048e 100644--- a/backend/tests/test_fx_rates.py+++ b/backend/tests/test_fx_rates.py@@ -416,6 +416,7 @@ class TestDashboardMultiCurrency:self,session: AsyncSession,test_user: User,+ test_workspace,test_account: Account,fx_rates,):@@ -441,7 +442,7 @@ class TestDashboardMultiCurrency:session.add(txn)await session.commit()- summary = await get_summary(session, test_user.id)+ summary = await get_summary(session, test_workspace.id, test_user.id)assert summary.primary_currency == "BRL"# USD balance: 200 * 5.0 = 1000 in BRL@@ -794,6 +795,7 @@ class TestReportNetWorthMultiCurrency:self,session: AsyncSession,test_user: User,+ test_workspace,test_account: Account,fx_rates,):@@ -817,7 +819,7 @@ class TestReportNetWorthMultiCurrency:session.add(txn)await session.commit()- dp = await _net_worth_at(session, test_user.id, date.today(), "BRL")+ dp = await _net_worth_at(session, test_workspace.id, date.today(), "BRL")# USD: 300 * 5.0 = 1500 BRL# Total should include the USD portion@@ -829,12 +831,13 @@ class TestReportNetWorthMultiCurrency:self,session: AsyncSession,test_user: User,+ test_workspace,test_account: Account,):"""get_net_worth_report reads the user's currency preference."""from app.services.report_service import get_net_worth_report- report = await get_net_worth_report(session, test_user.id, months=1)+ report = await get_net_worth_report(session, test_workspace.id, test_user.id, months=1)# test_user has currency_display=BRLassert report is not None@@ -854,6 +857,7 @@ class TestRecurringTransactionStamping:self,session: AsyncSession,test_user: User,+ test_workspace,test_account: Account,fx_rates,):@@ -870,7 +874,7 @@ class TestRecurringTransactionStamping:account_id=test_account.id,currency="USD",)- rec = await create_recurring_transaction(session, test_user.id, data)+ rec = await create_recurring_transaction(session, test_workspace.id, test_user.id, data)assert rec.amount_primary is not None# USD→BRL: 10 * 5.0 = 50@@ -882,6 +886,7 @@ class TestRecurringTransactionStamping:self,session: AsyncSession,test_user: User,+ test_workspace,test_account: Account,):"""Recurring in BRL (user primary=BRL) → rate = 1."""@@ -897,7 +902,7 @@ class TestRecurringTransactionStamping:account_id=test_account.id,currency="BRL",)- rec = await create_recurring_transaction(session, test_user.id, data)+ rec = await create_recurring_transaction(session, test_workspace.id, test_user.id, data)assert rec.amount_primary == Decimal("2000.00")assert rec.fx_rate_used == Decimal("1")@@ -907,6 +912,7 @@ class TestRecurringTransactionStamping:self,session: AsyncSession,test_user: User,+ test_workspace,test_account: Account,):"""generate_pending creates transactions with amount_primary stamped."""@@ -928,7 +934,7 @@ class TestRecurringTransactionStamping:account_id=test_account.id,currency="BRL",)- await create_recurring_transaction(session, test_user.id, data)+ await create_recurring_transaction(session, test_workspace.id, test_user.id, data)count = await generate_pending(session, test_user.id, up_to=date.today())assert count >= 1@@ -1049,6 +1055,7 @@ class TestRecurringFxRestamp:self,session: AsyncSession,test_user: User,+ test_workspace,test_account: Account,fx_rates,):@@ -1066,7 +1073,7 @@ class TestRecurringFxRestamp:account_id=test_account.id,currency="USD",)- rec = await create_recurring_transaction(session, test_user.id, data)+ rec = await create_recurring_transaction(session, test_workspace.id, test_user.id, data)assert rec.amount_primary == Decimal("50.00") # 10 * 5.0# Simulate rate change: update the USD rate to 5.5@@ -1091,6 +1098,7 @@ class TestRecurringFxRestamp:self,session: AsyncSession,test_user: User,+ test_workspace,test_account: Account,):"""BRL recurring transaction is not affected by re-stamp (rate stays 1)."""@@ -1106,7 +1114,7 @@ class TestRecurringFxRestamp:account_id=test_account.id,currency="BRL",)- rec = await create_recurring_transaction(session, test_user.id, data)+ rec = await create_recurring_transaction(session, test_workspace.id, test_user.id, data)assert rec.amount_primary == Decimal("2000.00")assert rec.fx_rate_used == Decimal("1")diff --git a/backend/tests/test_goals_api.py b/backend/tests/test_goals_api.pyindex f049662d..3f99010f 100644--- a/backend/tests/test_goals_api.py+++ b/backend/tests/test_goals_api.py@@ -366,6 +366,7 @@ async def test_goal_ownership_isolation(hashed = _bcrypt.hashpw(b"otherpass123", _bcrypt.gensalt()).decode()from app.models.user import User as UserModel+ from app.services.workspace_service import create_personal_workspace_for_userother_user = UserModel(id=uuid.uuid4(),@@ -377,6 +378,8 @@ async def test_goal_ownership_isolation(preferences={"language": "en", "date_format": "MM/DD/YYYY", "timezone": "UTC", "currency_display": "USD"},)session.add(other_user)+ await session.flush()+ await create_personal_workspace_for_user(session, other_user)await session.commit()# Login as other userdiff --git a/backend/tests/test_group_service.py b/backend/tests/test_group_service.pyindex 1dd14ed3..b8458763 100644--- a/backend/tests/test_group_service.py+++ b/backend/tests/test_group_service.py@@ -13,9 +13,9 @@ from app.services import group_service@pytest.mark.asyncio-async def test_create_group_defaults(session: AsyncSession, test_user):+async def test_create_group_defaults(session: AsyncSession, test_user, test_workspace):group = await group_service.create_group(- session, test_user.id, GroupCreate(name="Roommates")+ session, test_workspace.id, test_user.id, GroupCreate(name="Roommates"))assert group.name == "Roommates"assert group.kind == "social"@@ -25,9 +25,10 @@ async def test_create_group_defaults(session: AsyncSession, test_user):@pytest.mark.asyncio-async def test_create_group_b2b_kind(session: AsyncSession, test_user):+async def test_create_group_b2b_kind(session: AsyncSession, test_user, test_workspace):group = await group_service.create_group(session,+ test_workspace.id,test_user.id,GroupCreate(name="Marketing", kind="cost_center", default_currency="EUR"),)@@ -36,67 +37,96 @@ async def test_create_group_b2b_kind(session: AsyncSession, test_user):@pytest.mark.asyncio-async def test_duplicate_group_name_rejected(session: AsyncSession, test_user):- await group_service.create_group(session, test_user.id, GroupCreate(name="Trip"))+async def test_duplicate_group_name_rejected(+ session: AsyncSession, test_user, test_workspace+):+ await group_service.create_group(+ session, test_workspace.id, test_user.id, GroupCreate(name="Trip")+ )with pytest.raises(ValueError, match="already exists"):await group_service.create_group(- session, test_user.id, GroupCreate(name="Trip")+ session, test_workspace.id, test_user.id, GroupCreate(name="Trip"))@pytest.mark.asyncioasync def test_list_groups_excludes_archived_by_default(- session: AsyncSession, test_user+ session: AsyncSession, test_user, test_workspace):- g1 = await group_service.create_group(session, test_user.id, GroupCreate(name="A"))- await group_service.create_group(session, test_user.id, GroupCreate(name="B"))+ g1 = await group_service.create_group(+ session, test_workspace.id, test_user.id, GroupCreate(name="A")+ )+ await group_service.create_group(+ session, test_workspace.id, test_user.id, GroupCreate(name="B")+ )await group_service.update_group(- session, g1.id, test_user.id, GroupUpdate(is_archived=True)+ session, g1.id, test_workspace.id, test_user.id, GroupUpdate(is_archived=True))- visible = await group_service.list_groups(session, test_user.id)+ visible = await group_service.list_groups(session, test_workspace.id, test_user.id)assert {g.name for g in visible} == {"B"}all_groups = await group_service.list_groups(- session, test_user.id, include_archived=True+ session, test_workspace.id, test_user.id, include_archived=True)assert {g.name for g in all_groups} == {"A", "B"}@pytest.mark.asyncio-async def test_get_group_scoped_to_owner(session: AsyncSession, test_user):- group = await group_service.create_group(session, test_user.id, GroupCreate(name="X"))- other_user = uuid.uuid4()- fetched = await group_service.get_group(session, group.id, other_user)+async def test_get_group_scoped_to_owner(+ session: AsyncSession, test_user, test_workspace+):+ group = await group_service.create_group(+ session, test_workspace.id, test_user.id, GroupCreate(name="X")+ )+ # A bogus workspace must not be able to see the group via get_group.+ other_workspace = uuid.uuid4()+ fetched = await group_service.get_group(session, group.id, other_workspace)assert fetched is None@pytest.mark.asyncio-async def test_create_member_and_unique_name(session: AsyncSession, test_user):- group = await group_service.create_group(session, test_user.id, GroupCreate(name="G"))+async def test_create_member_and_unique_name(+ session: AsyncSession, test_user, test_workspace+):+ group = await group_service.create_group(+ session, test_workspace.id, test_user.id, GroupCreate(name="G")+ )member = await group_service.create_member(- session, group.id, test_user.id, GroupMemberCreate(name="Alice", is_self=True)+ session,+ group.id,+ test_workspace.id,+ GroupMemberCreate(name="Alice", is_self=True),)assert member.name == "Alice"assert member.is_self is Truewith pytest.raises(ValueError, match="already exists"):await group_service.create_member(- session, group.id, test_user.id, GroupMemberCreate(name="Alice")+ session, group.id, test_workspace.id, GroupMemberCreate(name="Alice"))@pytest.mark.asyncio-async def test_only_one_self_member_allowed(session: AsyncSession, test_user):- group = await group_service.create_group(session, test_user.id, GroupCreate(name="G"))+async def test_only_one_self_member_allowed(+ session: AsyncSession, test_user, test_workspace+):+ group = await group_service.create_group(+ session, test_workspace.id, test_user.id, GroupCreate(name="G")+ )m1 = await group_service.create_member(- session, group.id, test_user.id, GroupMemberCreate(name="Me", is_self=True)+ session, group.id, test_workspace.id, GroupMemberCreate(name="Me", is_self=True))m2 = await group_service.create_member(- session, group.id, test_user.id, GroupMemberCreate(name="Also Me", is_self=True)+ session,+ group.id,+ test_workspace.id,+ GroupMemberCreate(name="Also Me", is_self=True),)# m1 should have been demoted automatically.- refreshed = await group_service.list_members(session, group.id, test_user.id)+ refreshed = await group_service.list_members(+ session, group.id, test_workspace.id, test_user.id+ )by_id = {m.id: m for m in refreshed}assert by_id[m1.id].is_self is Falseassert by_id[m2.id].is_self is True@@ -104,30 +134,42 @@ async def test_only_one_self_member_allowed(session: AsyncSession, test_user):@pytest.mark.asyncioasync def test_update_member_promotes_to_self_demotes_others(- session: AsyncSession, test_user+ session: AsyncSession, test_user, test_workspace):- group = await group_service.create_group(session, test_user.id, GroupCreate(name="G"))+ group = await group_service.create_group(+ session, test_workspace.id, test_user.id, GroupCreate(name="G")+ )m1 = await group_service.create_member(- session, group.id, test_user.id, GroupMemberCreate(name="A", is_self=True)+ session, group.id, test_workspace.id, GroupMemberCreate(name="A", is_self=True))m2 = await group_service.create_member(- session, group.id, test_user.id, GroupMemberCreate(name="B")+ session, group.id, test_workspace.id, GroupMemberCreate(name="B"))await group_service.update_member(- session, group.id, m2.id, test_user.id, GroupMemberUpdate(is_self=True)+ session,+ group.id,+ m2.id,+ test_workspace.id,+ GroupMemberUpdate(is_self=True),+ )+ refreshed = await group_service.list_members(+ session, group.id, test_workspace.id, test_user.id)- refreshed = await group_service.list_members(session, group.id, test_user.id)by_id = {m.id: m for m in refreshed}assert by_id[m1.id].is_self is Falseassert by_id[m2.id].is_self is True@pytest.mark.asyncio-async def test_member_operations_isolated_per_owner(session: AsyncSession, test_user):- group = await group_service.create_group(session, test_user.id, GroupCreate(name="G"))- other = uuid.uuid4()+async def test_member_operations_isolated_per_owner(+ session: AsyncSession, test_user, test_workspace+):+ group = await group_service.create_group(+ session, test_workspace.id, test_user.id, GroupCreate(name="G")+ )+ other_workspace = uuid.uuid4()result = await group_service.create_member(- session, group.id, other, GroupMemberCreate(name="Bob")+ session, group.id, other_workspace, GroupMemberCreate(name="Bob"))- assert result is None # group not visible to other user+ assert result is None # group not visible from a different workspacediff --git a/backend/tests/test_group_visibility.py b/backend/tests/test_group_visibility.pyindex 5829c8a9..1eb7bba5 100644--- a/backend/tests/test_group_visibility.py+++ b/backend/tests/test_group_visibility.py@@ -11,12 +11,14 @@ import pytestfrom sqlalchemy.ext.asyncio import AsyncSessionfrom app.models.user import User+from app.models.workspace import Workspacefrom app.schemas.group import GroupCreate, GroupMemberCreatefrom app.schemas.group_settlement import GroupSettlementCreatefrom app.services import (balance_service,group_service,settlement_service,+ workspace_service,)@@ -35,30 +37,44 @@ async def _make_user(session: AsyncSession, email: str) -> User:return user+async def _make_user_with_workspace(+ session: AsyncSession, email: str+) -> tuple[User, Workspace]:+ user = await _make_user(session, email)+ workspace = await workspace_service.create_personal_workspace_for_user(+ session, user, commit=True+ )+ return user, workspace++@pytest.mark.asyncio-async def test_email_auto_resolves_to_linked_user(session: AsyncSession, test_user):+async def test_email_auto_resolves_to_linked_user(+ session: AsyncSession, test_user, test_workspace+):other = await _make_user(session, "[email protected]")group = await group_service.create_group(- session, test_user.id, GroupCreate(name="Trip")+ session, test_workspace.id, test_user.id, GroupCreate(name="Trip"))member = await group_service.create_member(session,group.id,- test_user.id,+ test_workspace.id,GroupMemberCreate(name="Friend", email="[email protected]"),)assert member.linked_user_id == other.id@pytest.mark.asyncio-async def test_email_unknown_creates_shadow(session: AsyncSession, test_user):+async def test_email_unknown_creates_shadow(+ session: AsyncSession, test_user, test_workspace+):group = await group_service.create_group(- session, test_user.id, GroupCreate(name="Trip")+ session, test_workspace.id, test_user.id, GroupCreate(name="Trip"))member = await group_service.create_member(session,group.id,- test_user.id,+ test_workspace.id,GroupMemberCreate(name="Stranger", email="[email protected]"),)assert member.linked_user_id is None@@ -66,139 +82,160 @@ async def test_email_unknown_creates_shadow(session: AsyncSession, test_user):@pytest.mark.asyncio-async def test_linked_member_sees_group_in_list(session: AsyncSession, test_user):- other = await _make_user(session, "[email protected]")+async def test_linked_member_sees_group_in_list(+ session: AsyncSession, test_user, test_workspace+):+ other, other_ws = await _make_user_with_workspace(session, "[email protected]")group = await group_service.create_group(- session, test_user.id, GroupCreate(name="Shared")+ session, test_workspace.id, test_user.id, GroupCreate(name="Shared"))await group_service.create_member(session,group.id,- test_user.id,+ test_workspace.id,GroupMemberCreate(name="Viewer", email="[email protected]"),)- visible = await group_service.list_groups(session, other.id)+ visible = await group_service.list_groups(session, other_ws.id, other.id)assert {g.id for g in visible} == {group.id}# Linked member sees is_owner=False; the original owner sees True.assert visible[0].is_owner is False- owners_view = await group_service.list_groups(session, test_user.id)+ owners_view = await group_service.list_groups(+ session, test_workspace.id, test_user.id+ )assert owners_view[0].is_owner is True@pytest.mark.asyncio-async def test_unrelated_user_does_not_see_group(session: AsyncSession, test_user):- stranger = await _make_user(session, "[email protected]")- await group_service.create_group(session, test_user.id, GroupCreate(name="Private"))+async def test_unrelated_user_does_not_see_group(+ session: AsyncSession, test_user, test_workspace+):+ stranger, stranger_ws = await _make_user_with_workspace(+ session, "[email protected]"+ )+ await group_service.create_group(+ session, test_workspace.id, test_user.id, GroupCreate(name="Private")+ )- visible = await group_service.list_groups(session, stranger.id)+ visible = await group_service.list_groups(session, stranger_ws.id, stranger.id)assert visible == []@pytest.mark.asyncio-async def test_visible_get_works_for_linked_member(session: AsyncSession, test_user):- other = await _make_user(session, "[email protected]")+async def test_visible_get_works_for_linked_member(+ session: AsyncSession, test_user, test_workspace+):+ other, other_ws = await _make_user_with_workspace(session, "[email protected]")group = await group_service.create_group(- session, test_user.id, GroupCreate(name="Shared")+ session, test_workspace.id, test_user.id, GroupCreate(name="Shared"))await group_service.create_member(session,group.id,- test_user.id,+ test_workspace.id,GroupMemberCreate(name="V", email="[email protected]"),)- via_visible = await group_service.get_group_visible(session, group.id, other.id)+ via_visible = await group_service.get_group_visible(+ session, group.id, other_ws.id, other.id+ )assert via_visible is not Noneassert via_visible.is_owner is False- # Owner-only get returns None for the linked member, ensuring that- # edit paths reject non-owners cleanly.- via_owned = await group_service.get_group(session, group.id, other.id)+ # Owner-only get returns None when scoped to the linked member's+ # workspace — edit paths reject non-owners cleanly.+ via_owned = await group_service.get_group(session, group.id, other_ws.id)assert via_owned is None@pytest.mark.asyncio-async def test_linked_member_cannot_modify_group(session: AsyncSession, test_user):- other = await _make_user(session, "[email protected]")+async def test_linked_member_cannot_modify_group(+ session: AsyncSession, test_user, test_workspace+):+ other, other_ws = await _make_user_with_workspace(session, "[email protected]")group = await group_service.create_group(- session, test_user.id, GroupCreate(name="Shared")+ session, test_workspace.id, test_user.id, GroupCreate(name="Shared"))await group_service.create_member(session,group.id,- test_user.id,+ test_workspace.id,GroupMemberCreate(name="V", email="[email protected]"),)- # Updates via the linked member's user_id resolve to None (no-op).+ # Updates from the linked member's own workspace resolve to None (no-op).from app.schemas.group import GroupUpdateupdated = await group_service.update_group(- session, group.id, other.id, GroupUpdate(name="Hijacked")+ session, group.id, other_ws.id, other.id, GroupUpdate(name="Hijacked"))assert updated is None- # Member-add by linked viewer also rejected.+ # Member-add scoped to the linked viewer's workspace is also rejected.add = await group_service.create_member(- session, group.id, other.id, GroupMemberCreate(name="Bob")+ session, group.id, other_ws.id, GroupMemberCreate(name="Bob"))assert add is None@pytest.mark.asyncioasync def test_linked_member_can_read_balances_and_settlements(- session: AsyncSession, test_user+ session: AsyncSession, test_user, test_workspace):- other = await _make_user(session, "[email protected]")+ other, other_ws = await _make_user_with_workspace(session, "[email protected]")group = await group_service.create_group(- session, test_user.id, GroupCreate(name="Shared")+ session, test_workspace.id, test_user.id, GroupCreate(name="Shared"))await group_service.create_member(session,group.id,- test_user.id,+ test_workspace.id,GroupMemberCreate(name="Me", is_self=True),)await group_service.create_member(session,group.id,- test_user.id,+ test_workspace.id,GroupMemberCreate(name="V", email="[email protected]"),)- balances = await balance_service.compute_balances(session, group.id, other.id)+ balances = await balance_service.compute_balances(+ session, group.id, other_ws.id, other.id+ )assert balances is not Noneassert balances["lines"] == []- settlements = await settlement_service.list_settlements(session, group.id, other.id)+ settlements = await settlement_service.list_settlements(+ session, group.id, other_ws.id, other.id+ )assert settlements == []@pytest.mark.asyncioasync def test_linked_member_can_settle_own_debt(- session: AsyncSession, test_user+ session: AsyncSession, test_user, test_workspace):"""A linked member CAN record a settlement when they are thefrom_member (i.e., they're recording a payment they made)."""- other = await _make_user(session, "[email protected]")+ other, other_ws = await _make_user_with_workspace(session, "[email protected]")group = await group_service.create_group(- session, test_user.id, GroupCreate(name="Shared")+ session, test_workspace.id, test_user.id, GroupCreate(name="Shared"))self_m = await group_service.create_member(- session, group.id, test_user.id, GroupMemberCreate(name="Me", is_self=True)+ session, group.id, test_workspace.id, GroupMemberCreate(name="Me", is_self=True))a = await group_service.create_member(session,group.id,- test_user.id,+ test_workspace.id,GroupMemberCreate(name="A", email="[email protected]"),)settlement = await settlement_service.create_settlement(session,group.id,+ other_ws.id,other.id,GroupSettlementCreate(from_member_id=a.id, # the linked member themself@@ -214,27 +251,28 @@ async def test_linked_member_can_settle_own_debt(@pytest.mark.asyncioasync def test_linked_member_cannot_settle_someone_elses_debt(- session: AsyncSession, test_user+ session: AsyncSession, test_user, test_workspace):"""A linked member CANNOT speak for another member."""- other = await _make_user(session, "[email protected]")+ other, other_ws = await _make_user_with_workspace(session, "[email protected]")group = await group_service.create_group(- session, test_user.id, GroupCreate(name="Shared")+ session, test_workspace.id, test_user.id, GroupCreate(name="Shared"))a = await group_service.create_member(session,group.id,- test_user.id,+ test_workspace.id,GroupMemberCreate(name="A", email="[email protected]"),)b = await group_service.create_member(- session, group.id, test_user.id, GroupMemberCreate(name="B")+ session, group.id, test_workspace.id, GroupMemberCreate(name="B"))with pytest.raises(PermissionError):await settlement_service.create_settlement(session,group.id,+ other_ws.id,other.id,GroupSettlementCreate(from_member_id=b.id, # NOT the linked member's own iddiff --git a/backend/tests/test_import_service.py b/backend/tests/test_import_service.pyindex 678ec4e6..636e4a40 100644--- a/backend/tests/test_import_service.py+++ b/backend/tests/test_import_service.py@@ -547,6 +547,22 @@ class TestParseQif:assert len(transactions) == 1assert transactions[0].description == "Valid"+ def test_parse_qif_windows_1252_encoding(self):+ """QIF with accented characters encoded in Windows-1252 (Microsoft Money)."""+ qif_text = (+ "D01/10/2026\n"+ "T-300.00\n"+ "PPagamento cartão\n"+ "MCompra em São Paulo\n"+ "^\n"+ )+ transactions = parse_qif(qif_text.encode("cp1252"))++ assert len(transactions) == 1+ assert transactions[0].description == "Pagamento cartão"+ assert transactions[0].amount == Decimal("300.00")+ assert transactions[0].type == "debit"+def test_parse_qif_comma_in_amount(self):"""QIF amounts with comma thousands separator."""qif_content = (@@ -1012,7 +1028,7 @@ class TestImportTransactionsFx:@pytest.mark.asyncio@patch("app.services.fx_rate_service._provider")- async def test_import_with_fx_rate_from_csv(self, mock_provider, session: AsyncSession, test_user: User, test_account: Account):+ async def test_import_with_fx_rate_from_csv(self, mock_provider, session: AsyncSession, test_user: User, test_workspace, test_account: Account):"""When CSV provides fx_rate, it should be used directly without calling FX service."""from app.schemas.transaction import TransactionImportfrom app.models.transaction import Transaction@@ -1030,7 +1046,7 @@ class TestImportTransactionsFx:]imported, skipped, _, _ = await import_transactions(- session, test_user.id, test_account.id, txns, "csv",+ session, test_workspace.id, test_user.id, test_account.id, txns, "csv",)assert imported == 1@@ -1052,7 +1068,7 @@ class TestImportTransactionsFx:@pytest.mark.asyncio@patch("app.services.fx_rate_service._provider")async def test_import_foreign_currency_without_fx_rate_auto_converts(- self, mock_provider, session: AsyncSession, test_user: User, test_account: Account,+ self, mock_provider, session: AsyncSession, test_user: User, test_workspace, test_account: Account,):"""When no fx_rate is provided, stamp_primary_amount should auto-convert using DB rates."""from app.schemas.transaction import TransactionImport@@ -1078,7 +1094,7 @@ class TestImportTransactionsFx:]imported, _, _, _ = await import_transactions(- session, test_user.id, test_account.id, txns, "csv",+ session, test_workspace.id, test_user.id, test_account.id, txns, "csv",)assert imported == 1@@ -1096,7 +1112,7 @@ class TestImportTransactionsFx:@pytest.mark.asyncio@patch("app.services.fx_rate_service._provider")async def test_import_uses_account_currency_as_default(- self, mock_provider, session: AsyncSession, test_user: User,+ self, mock_provider, session: AsyncSession, test_user: User, test_workspace,):"""When transaction has no currency, the account's currency should be used."""from app.schemas.transaction import TransactionImport@@ -1133,7 +1149,7 @@ class TestImportTransactionsFx:]imported, _, _, _ = await import_transactions(- session, test_user.id, usd_account.id, txns, "csv",+ session, test_workspace.id, test_user.id, usd_account.id, txns, "csv",)assert imported == 1@@ -1148,7 +1164,7 @@ class TestImportTransactionsFx:@pytest.mark.asyncio@patch("app.services.fx_rate_service._provider")async def test_import_brl_into_brl_account_no_fx(- self, mock_provider, session: AsyncSession, test_user: User, test_account: Account,+ self, mock_provider, session: AsyncSession, test_user: User, test_workspace, test_account: Account,):"""Importing BRL transactions into a BRL account should not trigger FX conversion."""from app.schemas.transaction import TransactionImport@@ -1166,7 +1182,7 @@ class TestImportTransactionsFx:]imported, _, _, _ = await import_transactions(- session, test_user.id, test_account.id, txns, "csv",+ session, test_workspace.id, test_user.id, test_account.id, txns, "csv",)assert imported == 1@@ -1186,7 +1202,7 @@ class TestImportTransactionsFx:@pytest.mark.asyncio@patch("app.services.fx_rate_service._provider")async def test_import_csv_currency_overrides_account_currency(- self, mock_provider, session: AsyncSession, test_user: User, test_account: Account,+ self, mock_provider, session: AsyncSession, test_user: User, test_workspace, test_account: Account,):"""CSV-provided currency should take priority over account currency."""from app.schemas.transaction import TransactionImport@@ -1210,7 +1226,7 @@ class TestImportTransactionsFx:]imported, _, _, _ = await import_transactions(- session, test_user.id, test_account.id, txns, "csv",+ session, test_workspace.id, test_user.id, test_account.id, txns, "csv",)assert imported == 1@@ -1356,7 +1372,7 @@ class TestImportTransactionsWithCategory:@pytest.mark.asyncio@patch("app.services.fx_rate_service._provider")async def test_known_category_name_resolved_to_id(- self, mock_provider, session: AsyncSession, test_user: User, test_account: Account,+ self, mock_provider, session: AsyncSession, test_user: User, test_workspace, test_account: Account,):"""When category_name matches a user category, category_id should be set."""from app.models.category import Category@@ -1380,7 +1396,7 @@ class TestImportTransactionsWithCategory:)]imported, skipped, _, _ = await import_transactions(- session, test_user.id, test_account.id, txns, "import",+ session, test_workspace.id, test_user.id, test_account.id, txns, "import",)assert imported == 1@@ -1394,7 +1410,7 @@ class TestImportTransactionsWithCategory:@pytest.mark.asyncio@patch("app.services.fx_rate_service._provider")async def test_unknown_category_name_leaves_uncategorized(- self, mock_provider, session: AsyncSession, test_user: User, test_account: Account,+ self, mock_provider, session: AsyncSession, test_user: User, test_workspace, test_account: Account,):"""When category_name has no match, category_id should be None."""from app.schemas.transaction import TransactionImport@@ -1410,7 +1426,7 @@ class TestImportTransactionsWithCategory:)]imported, _, _, _ = await import_transactions(- session, test_user.id, test_account.id, txns, "import",+ session, test_workspace.id, test_user.id, test_account.id, txns, "import",)assert imported == 1@@ -1423,7 +1439,7 @@ class TestImportTransactionsWithCategory:@pytest.mark.asyncio@patch("app.services.fx_rate_service._provider")async def test_no_category_name_leaves_uncategorized(- self, mock_provider, session: AsyncSession, test_user: User, test_account: Account,+ self, mock_provider, session: AsyncSession, test_user: User, test_workspace, test_account: Account,):"""When category_name is None, category_id should be None."""from app.schemas.transaction import TransactionImport@@ -1438,7 +1454,7 @@ class TestImportTransactionsWithCategory:)]imported, _, _, _ = await import_transactions(- session, test_user.id, test_account.id, txns, "import",+ session, test_workspace.id, test_user.id, test_account.id, txns, "import",)assert imported == 1@@ -1451,7 +1467,7 @@ class TestImportTransactionsWithCategory:@pytest.mark.asyncio@patch("app.services.fx_rate_service._provider")async def test_multiple_categories_resolved_correctly(- self, mock_provider, session: AsyncSession, test_user: User, test_account: Account,+ self, mock_provider, session: AsyncSession, test_user: User, test_workspace, test_account: Account,):"""Multiple transactions with different categories should each resolve correctly."""from app.models.category import Category@@ -1496,7 +1512,7 @@ class TestImportTransactionsWithCategory:]imported, skipped, _, _ = await import_transactions(- session, test_user.id, test_account.id, txns, "import",+ session, test_workspace.id, test_user.id, test_account.id, txns, "import",)assert imported == 3@@ -1519,7 +1535,7 @@ class TestImportTransactionsWithCategory:@pytest.mark.asyncio@patch("app.services.fx_rate_service._provider")async def test_end_to_end_parse_and_import_with_type_and_category(- self, mock_provider, session: AsyncSession, test_user: User, test_account: Account,+ self, mock_provider, session: AsyncSession, test_user: User, test_workspace, test_account: Account,):"""Full flow: parse_csv reads type+category columns, import_transactions resolves them."""from app.models.category import Category@@ -1551,7 +1567,7 @@ class TestImportTransactionsWithCategory:assert transactions[1].category_name == "Moradia"imported, skipped, _, _ = await import_transactions(- session, test_user.id, test_account.id, transactions, "import",+ session, test_workspace.id, test_user.id, test_account.id, transactions, "import",)assert imported == 2@@ -1577,7 +1593,7 @@ class TestOfxInstallmentDedup:@pytest.mark.asyncioasync def test_same_external_id_different_dates_both_imported(- self, session: AsyncSession, test_user: User, test_account: Account,+ self, session: AsyncSession, test_user: User, test_workspace, test_account: Account,):from app.schemas.transaction import TransactionImportfrom app.models.transaction import Transaction@@ -1593,7 +1609,7 @@ class TestOfxInstallmentDedup:),]imported, skipped, _, _ = await import_transactions(- session, test_user.id, test_account.id, first, "ofx",+ session, test_workspace.id, test_user.id, test_account.id, first, "ofx",)assert imported == 1assert skipped == 0@@ -1608,7 +1624,7 @@ class TestOfxInstallmentDedup:),]imported2, skipped2, _, _ = await import_transactions(- session, test_user.id, test_account.id, second, "ofx",+ session, test_workspace.id, test_user.id, test_account.id, second, "ofx",)assert imported2 == 1assert skipped2 == 0@@ -1621,7 +1637,7 @@ class TestOfxInstallmentDedup:@pytest.mark.asyncioasync def test_same_external_id_same_date_dedups(- self, session: AsyncSession, test_user: User, test_account: Account,+ self, session: AsyncSession, test_user: User, test_workspace, test_account: Account,):"""Re-importing the same OFX file must still dedup — same FITID + samedate is the strict duplicate case."""@@ -1634,9 +1650,9 @@ class TestOfxInstallmentDedup:type="debit",external_id="DEDUP_ME",)- await import_transactions(session, test_user.id, test_account.id, [txn], "ofx")+ await import_transactions(session, test_workspace.id, test_user.id, test_account.id, [txn], "ofx")imported, skipped, _, _ = await import_transactions(- session, test_user.id, test_account.id, [txn], "ofx",+ session, test_workspace.id, test_user.id, test_account.id, [txn], "ofx",)assert imported == 0assert skipped == 1@@ -1645,7 +1661,7 @@ class TestOfxInstallmentDedup:class TestCsvDuplicateDetectionToggle:@pytest.mark.asyncioasync def test_csv_detect_duplicates_false_allows_duplicates(- self, session: AsyncSession, test_user: User, test_account: Account,+ self, session: AsyncSession, test_user: User, test_workspace, test_account: Account,):from app.schemas.transaction import TransactionImport@@ -1658,6 +1674,7 @@ class TestCsvDuplicateDetectionToggle:await import_transactions(session,+ test_workspace.id,test_user.id,test_account.id,[txn],@@ -1667,6 +1684,7 @@ class TestCsvDuplicateDetectionToggle:)imported, skipped, _, _ = await import_transactions(session,+ test_workspace.id,test_user.id,test_account.id,[txn],@@ -1679,7 +1697,7 @@ class TestCsvDuplicateDetectionToggle:@pytest.mark.asyncioasync def test_non_csv_ignores_toggle_and_still_dedups(- self, session: AsyncSession, test_user: User, test_account: Account,+ self, session: AsyncSession, test_user: User, test_workspace, test_account: Account,):from app.schemas.transaction import TransactionImport@@ -1693,6 +1711,7 @@ class TestCsvDuplicateDetectionToggle:await import_transactions(session,+ test_workspace.id,test_user.id,test_account.id,[txn],@@ -1702,6 +1721,7 @@ class TestCsvDuplicateDetectionToggle:)imported, skipped, _, _ = await import_transactions(session,+ test_workspace.id,test_user.id,test_account.id,[txn],@@ -1716,7 +1736,7 @@ class TestCsvDuplicateDetectionToggle:class TestApplyRuleEngineCorrectly:@pytest.mark.asyncioasync def test_should_not_override_category(- self, session: AsyncSession, test_user: User, test_account: Account+ self, session: AsyncSession, test_user: User, test_workspace, test_account: Account):from app.schemas.transaction import TransactionImportfrom app.schemas.rule import RuleCreate, RuleCondition, RuleAction@@ -1734,7 +1754,7 @@ class TestApplyRuleEngineCorrectly:actions=[RuleAction(op="set_category", value=str(test_categories[2].id))],priority=10,)- await create_rule(session, test_user.id, data)+ await create_rule(session, test_workspace.id, test_user.id, data)txn = TransactionImport(description="NOOVERRIDE",@@ -1746,6 +1766,7 @@ class TestApplyRuleEngineCorrectly:imported, _, _, import_log_id = await import_transactions(session,+ test_workspace.id,test_user.id,test_account.id,[txn],@@ -1763,7 +1784,7 @@ class TestApplyRuleEngineCorrectly:@pytest.mark.asyncioasync def test_should_set_category_from_rule_when_no_suggested(- self, session: AsyncSession, test_user: User, test_account: Account+ self, session: AsyncSession, test_user: User, test_workspace, test_account: Account):from app.schemas.transaction import TransactionImportfrom app.schemas.rule import RuleCreate, RuleCondition, RuleAction@@ -1781,7 +1802,7 @@ class TestApplyRuleEngineCorrectly:priority=10,)- await create_rule(session, test_user.id, data)+ await create_rule(session, test_workspace.id, test_user.id, data)txn = TransactionImport(description="SETCAT",@@ -1793,6 +1814,7 @@ class TestApplyRuleEngineCorrectly:imported, _, _, import_log_id = await import_transactions(session,+ test_workspace.id,test_user.id,test_account.id,[txn],@@ -1811,7 +1833,7 @@ class TestApplyRuleEngineCorrectly:@pytest.mark.asyncioasync def test_should_set_payee_but_not_override_category(- self, session: AsyncSession, test_user: User, test_account: Account+ self, session: AsyncSession, test_user: User, test_workspace, test_account: Account):from app.models.payee import Payeefrom app.schemas.transaction import TransactionImport@@ -1847,8 +1869,8 @@ class TestApplyRuleEngineCorrectly:actions=[RuleAction(op="set_payee", value=str(payee.id))],priority=10,)- await create_rule(session, test_user.id, data)- await create_rule(session, test_user.id, cat_rule)+ await create_rule(session, test_workspace.id, test_user.id, data)+ await create_rule(session, test_workspace.id, test_user.id, cat_rule)txn = TransactionImport(@@ -1860,6 +1882,7 @@ class TestApplyRuleEngineCorrectly:)imported, _, _, import_log_id = await import_transactions(session,+ test_workspace.id,test_user.id,test_account.id,[txn],@@ -1883,7 +1906,7 @@ class TestForceUncategorized:@pytest.mark.asyncioasync def test_force_uncategorized_ignores_suggestion(- self, session: AsyncSession, test_user: User, test_account: Account+ self, session: AsyncSession, test_user: User, test_workspace, test_account: Account):from app.schemas.transaction import TransactionImportfrom app.models.transaction import Transaction@@ -1907,7 +1930,7 @@ class TestForceUncategorized:)imported, _, _, import_log_id = await import_transactions(- session, test_user.id, test_account.id, [txn], "import",+ session, test_workspace.id, test_user.id, test_account.id, [txn], "import",)assert imported == 1@@ -1919,7 +1942,7 @@ class TestForceUncategorized:@pytest.mark.asyncioasync def test_force_uncategorized_prevents_rule_override(- self, session: AsyncSession, test_user: User, test_account: Account+ self, session: AsyncSession, test_user: User, test_workspace, test_account: Account):from app.schemas.transaction import TransactionImportfrom app.models.transaction import Transaction@@ -1937,7 +1960,7 @@ class TestForceUncategorized:actions=[RuleAction(op="set_category", value=str(test_categories[1].id))],priority=10,)- await create_rule(session, test_user.id, data)+ await create_rule(session, test_workspace.id, test_user.id, data)txn = TransactionImport(description="FORCED NO CAT",@@ -1949,7 +1972,7 @@ class TestForceUncategorized:)imported, _, _, import_log_id = await import_transactions(- session, test_user.id, test_account.id, [txn], "import",+ session, test_workspace.id, test_user.id, test_account.id, [txn], "import",)assert imported == 1@@ -1961,7 +1984,7 @@ class TestForceUncategorized:@pytest.mark.asyncioasync def test_force_uncategorized_still_applies_payee_rules(- self, session: AsyncSession, test_user: User, test_account: Account+ self, session: AsyncSession, test_user: User, test_workspace, test_account: Account):from app.models.payee import Payeefrom app.schemas.transaction import TransactionImport@@ -1993,7 +2016,7 @@ class TestForceUncategorized:],priority=10,)- await create_rule(session, test_user.id, data)+ await create_rule(session, test_workspace.id, test_user.id, data)txn = TransactionImport(description="PAYEEFORCE TXN",@@ -2005,7 +2028,7 @@ class TestForceUncategorized:)imported, _, _, import_log_id = await import_transactions(- session, test_user.id, test_account.id, [txn], "import",+ session, test_workspace.id, test_user.id, test_account.id, [txn], "import",)assert imported == 1@@ -2018,7 +2041,7 @@ class TestForceUncategorized:@pytest.mark.asyncioasync def test_without_force_uncategorized_suggestion_is_used(- self, session: AsyncSession, test_user: User, test_account: Account+ self, session: AsyncSession, test_user: User, test_workspace, test_account: Account):from app.schemas.transaction import TransactionImportfrom app.models.transaction import Transaction@@ -2041,7 +2064,7 @@ class TestForceUncategorized:)imported, _, _, import_log_id = await import_transactions(- session, test_user.id, test_account.id, [txn], "import",+ session, test_workspace.id, test_user.id, test_account.id, [txn], "import",)assert imported == 1diff --git a/backend/tests/test_market_price_assets.py b/backend/tests/test_market_price_assets.pyindex 5016e59c..1306ac61 100644--- a/backend/tests/test_market_price_assets.py+++ b/backend/tests/test_market_price_assets.py@@ -102,7 +102,7 @@ def _quote(symbol: str, price: float, currency: str = "USD") -> MarketSymbolQuot@pytest.mark.asyncioasync def test_create_market_price_asset_seeds_quote_and_initial_value(- session: AsyncSession, test_user: User+ session: AsyncSession, test_user: User, test_workspace):provider = FakeMarketProvider({"AAPL": _quote("AAPL", 180.25)})data = AssetCreate(@@ -115,7 +115,7 @@ async def test_create_market_price_asset_seeds_quote_and_initial_value()created = await asset_service.create_asset(- session, test_user.id, data, market_provider=provider+ session, test_workspace.id, test_user.id, data, market_provider=provider)assert created.valuation_method == "market_price"@@ -131,7 +131,7 @@ async def test_create_market_price_asset_seeds_quote_and_initial_value(@pytest.mark.asyncioasync def test_create_market_price_asset_rejects_missing_ticker(- session: AsyncSession, test_user: User+ session: AsyncSession, test_user: User, test_workspace):provider = FakeMarketProvider({})data = AssetCreate(@@ -143,14 +143,14 @@ async def test_create_market_price_asset_rejects_missing_ticker(with pytest.raises(Exception) as excinfo: # FastAPI's HTTPExceptionawait asset_service.create_asset(- session, test_user.id, data, market_provider=provider+ session, test_workspace.id, test_user.id, data, market_provider=provider)assert "ticker" in str(excinfo.value).lower()@pytest.mark.asyncioasync def test_create_market_price_asset_rejects_zero_units(- session: AsyncSession, test_user: User+ session: AsyncSession, test_user: User, test_workspace):provider = FakeMarketProvider({"AAPL": _quote("AAPL", 180.0)})data = AssetCreate(@@ -163,14 +163,14 @@ async def test_create_market_price_asset_rejects_zero_units(with pytest.raises(Exception) as excinfo:await asset_service.create_asset(- session, test_user.id, data, market_provider=provider+ session, test_workspace.id, test_user.id, data, market_provider=provider)assert "units" in str(excinfo.value).lower()@pytest.mark.asyncioasync def test_create_market_price_asset_errors_when_quote_unavailable(- session: AsyncSession, test_user: User+ session: AsyncSession, test_user: User, test_workspace):provider = FakeMarketProvider({}) # no canned quote for any symboldata = AssetCreate(@@ -183,14 +183,14 @@ async def test_create_market_price_asset_errors_when_quote_unavailable(with pytest.raises(Exception) as excinfo:await asset_service.create_asset(- session, test_user.id, data, market_provider=provider+ session, test_workspace.id, test_user.id, data, market_provider=provider)assert "quote" in str(excinfo.value).lower()@pytest.mark.asyncioasync def test_refresh_market_price_updates_cached_price_and_upserts_today(- session: AsyncSession, test_user: User+ session: AsyncSession, test_user: User, test_workspace):# First create with an initial quote, then bump the quote and refresh.initial = FakeMarketProvider({"AAPL": _quote("AAPL", 180.00)})@@ -202,7 +202,7 @@ async def test_refresh_market_price_updates_cached_price_and_upserts_today(units=Decimal("10"),)created = await asset_service.create_asset(- session, test_user.id, data, market_provider=initial+ session, test_workspace.id, test_user.id, data, market_provider=initial)# Reload the ORM entity (service returned a schema, not the model).@@ -231,7 +231,7 @@ async def test_refresh_market_price_updates_cached_price_and_upserts_today(@pytest.mark.asyncioasync def test_refresh_all_uses_batch_endpoint(- session: AsyncSession, test_user: User+ session: AsyncSession, test_user: User, test_workspace):"""Scheduled refresh should hit the batch path once, not N single quotes."""provider = FakeMarketProvider(@@ -244,6 +244,7 @@ async def test_refresh_all_uses_batch_endpoint(for ticker in ("AAPL", "MSFT", "GOOG"):await asset_service.create_asset(session,+ test_workspace.id,test_user.id,AssetCreate(name=ticker,@@ -270,7 +271,7 @@ async def test_refresh_all_uses_batch_endpoint(@pytest.mark.asyncioasync def test_refresh_all_falls_back_when_batch_misses_symbol(- session: AsyncSession, test_user: User+ session: AsyncSession, test_user: User, test_workspace):"""If a symbol is missing from the batch response, per-asset path picks it up."""provider = FakeMarketProvider(@@ -279,6 +280,7 @@ async def test_refresh_all_falls_back_when_batch_misses_symbol(for ticker in ("AAPL", "MSFT"):await asset_service.create_asset(session,+ test_workspace.id,test_user.id,AssetCreate(name=ticker,@@ -306,13 +308,14 @@ async def test_refresh_all_falls_back_when_batch_misses_symbol(@pytest.mark.asyncioasync def test_refresh_all_halts_on_rate_limit(- session: AsyncSession, test_user: User+ session: AsyncSession, test_user: User, test_workspace):# Create two market-priced assetsprovider = FakeMarketProvider({"AAPL": _quote("AAPL", 180.0), "MSFT": _quote("MSFT", 400.0)})for ticker in ("AAPL", "MSFT"):await asset_service.create_asset(session,+ test_workspace.id,test_user.id,AssetCreate(name=ticker,diff --git a/backend/tests/test_mcp_server_groups.py b/backend/tests/test_mcp_server_groups.pyindex 423e9f89..bd579692 100644--- a/backend/tests/test_mcp_server_groups.py+++ b/backend/tests/test_mcp_server_groups.py@@ -39,7 +39,7 @@ async def test_list_groups_serializes_group_with_members(session, test_user, mon],)- async def fake_list_groups(s, uid, *, include_archived):+ async def fake_list_groups(s, ws_id, uid, *, include_archived):assert uid == test_user.idassert include_archived is Truereturn [fake_group]@@ -73,7 +73,7 @@ async def test_list_groups_handles_missing_members(session, test_user, monkeypatmembers=None,)- async def fake(s, uid, *, include_archived):+ async def fake(s, ws_id, uid, *, include_archived):return [fake_group]monkeypatch.setattr(groups_tool.group_service, "list_groups", fake)@@ -85,7 +85,7 @@ async def test_list_groups_handles_missing_members(session, test_user, monkeypatasync def test_list_groups_defaults_include_archived_false(session, test_user, monkeypatch):captured = {}- async def fake(s, uid, *, include_archived):+ async def fake(s, ws_id, uid, *, include_archived):captured["include_archived"] = include_archivedreturn []@@ -98,7 +98,7 @@ async def test_list_groups_defaults_include_archived_false(session, test_user, m@pytest.mark.asyncioasync def test_get_group_balances_returns_error_when_group_missing(session, test_user, monkeypatch):- async def fake_compute(s, gid, uid):+ async def fake_compute(s, gid, ws_id, uid):return None # service signals not-visible/not-found via Nonemonkeypatch.setattr(groups_tool.balance_service, "compute_balances", fake_compute)@@ -123,7 +123,7 @@ async def test_get_group_balances_resolves_member_names(session, test_user, monksession.add_all([g, me, them])await session.commit()- async def fake_compute(s, gid, uid):+ async def fake_compute(s, gid, ws_id, uid):assert gid == g.idreturn {"group_id": g.id,@@ -158,7 +158,7 @@ async def test_get_group_balances_handles_none_self_member(session, test_user, mmust serialize that as null, not crash."""gid = uuid.uuid4()- async def fake_compute(s, g, u):+ async def fake_compute(s, g, ws_id, u):return {"group_id": gid, "self_member_id": None, "default_currency": "BRL","lines": [],@@ -174,7 +174,7 @@ async def test_get_group_balances_handles_none_self_member(session, test_user, m@pytest.mark.asyncioasync def test_list_group_settlements_returns_error_when_group_missing(session, test_user, monkeypatch):- async def fake_list(s, gid, uid):+ async def fake_list(s, gid, ws_id, uid):return Nonemonkeypatch.setattr(groups_tool.settlement_service, "list_settlements", fake_list)@@ -209,7 +209,7 @@ async def test_list_group_settlements_serializes_rows(session, test_user, monkeytransaction_id=None, # exercise the None-txn branch)- async def fake(s, gid, uid):+ async def fake(s, gid, ws_id, uid):return [s1, s2]monkeypatch.setattr(groups_tool.settlement_service, "list_settlements", fake)diff --git a/backend/tests/test_new_rules_api.py b/backend/tests/test_new_rules_api.pyindex 569c3c88..02422772 100644--- a/backend/tests/test_new_rules_api.py+++ b/backend/tests/test_new_rules_api.py@@ -285,6 +285,7 @@ async def test_rule_user_isolation():"""One user's rules don't affect another user's transactions."""import bcrypt as _bcrypt+ from app.services.workspace_service import create_personal_workspace_for_user# Create second userhashed = _bcrypt.hashpw(b"otherpass123", _bcrypt.gensalt()).decode()@@ -299,6 +300,8 @@ async def test_rule_user_isolation("timezone": "America/Sao_Paulo", "currency_display": "BRL"},)session.add(user2)+ await session.flush()+ await create_personal_workspace_for_user(session, user2)await session.commit()# Login as user2diff --git a/backend/tests/test_payee_service.py b/backend/tests/test_payee_service.pyindex 7e626031..5c658a98 100644--- a/backend/tests/test_payee_service.py+++ b/backend/tests/test_payee_service.py@@ -47,9 +47,9 @@ async def _make_account(session: AsyncSession, user: User) -> Account:@pytest.mark.asyncio-async def test_create_payee(session: AsyncSession, test_user):+async def test_create_payee(session: AsyncSession, test_user, test_workspace):data = PayeeCreate(name="Starbucks", type="merchant")- payee = await create_payee(session, test_user.id, data)+ payee = await create_payee(session, test_workspace.id, test_user.id, data)assert payee.name == "Starbucks"assert payee.type == "merchant"@@ -59,23 +59,23 @@ async def test_create_payee(session: AsyncSession, test_user):@pytest.mark.asyncio-async def test_create_payee_with_notes(session: AsyncSession, test_user):+async def test_create_payee_with_notes(session: AsyncSession, test_user, test_workspace):data = PayeeCreate(name="Coffee Shop", type="merchant", notes="Morning coffee")- payee = await create_payee(session, test_user.id, data)+ payee = await create_payee(session, test_workspace.id, test_user.id, data)assert payee.notes == "Morning coffee"@pytest.mark.asyncio-async def test_create_payee_duplicate_name_rejected(session: AsyncSession, test_user):- await create_payee(session, test_user.id, PayeeCreate(name="Starbucks"))+async def test_create_payee_duplicate_name_rejected(session: AsyncSession, test_user, test_workspace):+ await create_payee(session, test_workspace.id, test_user.id, PayeeCreate(name="Starbucks"))with pytest.raises(ValueError, match="already exists"):- await create_payee(session, test_user.id, PayeeCreate(name="starbucks")) # case-insensitive+ await create_payee(session, test_workspace.id, test_user.id, PayeeCreate(name="starbucks")) # case-insensitive@pytest.mark.asyncio-async def test_create_payee_creates_self_mapping(session: AsyncSession, test_user):- payee = await create_payee(session, test_user.id, PayeeCreate(name="Mapped"))+async def test_create_payee_creates_self_mapping(session: AsyncSession, test_user, test_workspace):+ payee = await create_payee(session, test_workspace.id, test_user.id, PayeeCreate(name="Mapped"))from sqlalchemy import selectresult = await session.execute(select(PayeeMapping).where(PayeeMapping.id == payee.id)@@ -91,9 +91,9 @@ async def test_create_payee_creates_self_mapping(session: AsyncSession, test_use@pytest.mark.asyncio-async def test_get_payee(session: AsyncSession, test_user):- created = await create_payee(session, test_user.id, PayeeCreate(name="Target"))- fetched = await get_payee(session, created.id, test_user.id)+async def test_get_payee(session: AsyncSession, test_user, test_workspace):+ created = await create_payee(session, test_workspace.id, test_user.id, PayeeCreate(name="Target"))+ fetched = await get_payee(session, created.id, test_workspace.id)assert fetched is not Noneassert fetched.id == created.id@@ -101,21 +101,21 @@ async def test_get_payee(session: AsyncSession, test_user):@pytest.mark.asyncio-async def test_get_payee_not_found(session: AsyncSession, test_user):- result = await get_payee(session, uuid.uuid4(), test_user.id)+async def test_get_payee_not_found(session: AsyncSession, test_user, test_workspace):+ result = await get_payee(session, uuid.uuid4(), test_workspace.id)assert result is None@pytest.mark.asyncio-async def test_get_payees_empty(session: AsyncSession, test_user):- payees = await get_payees(session, test_user.id)+async def test_get_payees_empty(session: AsyncSession, test_user, test_workspace):+ payees = await get_payees(session, test_workspace.id)assert payees == []@pytest.mark.asyncio-async def test_get_payees_with_transaction_counts(session: AsyncSession, test_user):- p1 = await create_payee(session, test_user.id, PayeeCreate(name="Payee A"))- p2 = await create_payee(session, test_user.id, PayeeCreate(name="Payee B"))+async def test_get_payees_with_transaction_counts(session: AsyncSession, test_user, test_workspace):+ p1 = await create_payee(session, test_workspace.id, test_user.id, PayeeCreate(name="Payee A"))+ p2 = await create_payee(session, test_workspace.id, test_user.id, PayeeCreate(name="Payee B"))account = await _make_account(session, test_user)@@ -135,7 +135,7 @@ async def test_get_payees_with_transaction_counts(session: AsyncSession, test_us))await session.commit()- payees = await get_payees(session, test_user.id)+ payees = await get_payees(session, test_workspace.id)payees_by_name = {p.name: p for p in payees}assert payees_by_name["Payee A"].transaction_count == 2@@ -143,20 +143,20 @@ async def test_get_payees_with_transaction_counts(session: AsyncSession, test_us@pytest.mark.asyncio-async def test_get_payees_ordered_by_name(session: AsyncSession, test_user):- await create_payee(session, test_user.id, PayeeCreate(name="Zebra"))- await create_payee(session, test_user.id, PayeeCreate(name="Apple"))- await create_payee(session, test_user.id, PayeeCreate(name="Mango"))+async def test_get_payees_ordered_by_name(session: AsyncSession, test_user, test_workspace):+ await create_payee(session, test_workspace.id, test_user.id, PayeeCreate(name="Zebra"))+ await create_payee(session, test_workspace.id, test_user.id, PayeeCreate(name="Apple"))+ await create_payee(session, test_workspace.id, test_user.id, PayeeCreate(name="Mango"))- payees = await get_payees(session, test_user.id)+ payees = await get_payees(session, test_workspace.id)names = [p.name for p in payees]assert names == sorted(names)@pytest.mark.asyncio-async def test_get_payees_includes_zero_transaction_payees(session: AsyncSession, test_user):- orphan = await create_payee(session, test_user.id, PayeeCreate(name="No Tx"))- active = await create_payee(session, test_user.id, PayeeCreate(name="Has Tx"))+async def test_get_payees_includes_zero_transaction_payees(session: AsyncSession, test_user, test_workspace):+ orphan = await create_payee(session, test_workspace.id, test_user.id, PayeeCreate(name="No Tx"))+ active = await create_payee(session, test_workspace.id, test_user.id, PayeeCreate(name="Has Tx"))account = await _make_account(session, test_user)session.add(Transaction(@@ -167,7 +167,7 @@ async def test_get_payees_includes_zero_transaction_payees(session: AsyncSession))await session.commit()- payees = await get_payees(session, test_user.id)+ payees = await get_payees(session, test_workspace.id)ids = {p.id for p in payees}assert active.id in ids@@ -184,27 +184,27 @@ async def test_get_payees_includes_zero_transaction_payees(session: AsyncSession@pytest.mark.asyncio-async def test_get_or_create_payee_creates_new(session: AsyncSession, test_user):+async def test_get_or_create_payee_creates_new(session: AsyncSession, test_user, test_workspace):payee = await get_or_create_payee(session, test_user.id, "New Payee")assert payee.name == "New Payee"assert payee.user_id == test_user.id@pytest.mark.asyncio-async def test_get_or_create_payee_returns_existing(session: AsyncSession, test_user):- original = await create_payee(session, test_user.id, PayeeCreate(name="Existing"))+async def test_get_or_create_payee_returns_existing(session: AsyncSession, test_user, test_workspace):+ original = await create_payee(session, test_workspace.id, test_user.id, PayeeCreate(name="Existing"))found = await get_or_create_payee(session, test_user.id, "existing") # case-insensitiveassert found.id == original.id@pytest.mark.asyncio-async def test_get_or_create_payee_strips_whitespace(session: AsyncSession, test_user):+async def test_get_or_create_payee_strips_whitespace(session: AsyncSession, test_user, test_workspace):payee = await get_or_create_payee(session, test_user.id, " Trimmed ")assert payee.name == "Trimmed"@pytest.mark.asyncio-async def test_get_or_create_payee_empty_raises(session: AsyncSession, test_user):+async def test_get_or_create_payee_empty_raises(session: AsyncSession, test_user, test_workspace):with pytest.raises(ValueError, match="cannot be empty"):await get_or_create_payee(session, test_user.id, " ")@@ -215,10 +215,10 @@ async def test_get_or_create_payee_empty_raises(session: AsyncSession, test_user@pytest.mark.asyncio-async def test_update_payee(session: AsyncSession, test_user):- payee = await create_payee(session, test_user.id, PayeeCreate(name="Old Name"))+async def test_update_payee(session: AsyncSession, test_user, test_workspace):+ payee = await create_payee(session, test_workspace.id, test_user.id, PayeeCreate(name="Old Name"))updated = await update_payee(- session, payee.id, test_user.id,+ session, payee.id, test_workspace.id,PayeeUpdate(name="New Name", is_favorite=True),)@@ -229,20 +229,20 @@ async def test_update_payee(session: AsyncSession, test_user):@pytest.mark.asyncio-async def test_update_payee_not_found(session: AsyncSession, test_user):+async def test_update_payee_not_found(session: AsyncSession, test_user, test_workspace):result = await update_payee(- session, uuid.uuid4(), test_user.id, PayeeUpdate(name="Nope")+ session, uuid.uuid4(), test_workspace.id, PayeeUpdate(name="Nope"))assert result is None@pytest.mark.asyncio-async def test_update_payee_duplicate_name_rejected(session: AsyncSession, test_user):- await create_payee(session, test_user.id, PayeeCreate(name="A"))- b = await create_payee(session, test_user.id, PayeeCreate(name="B"))+async def test_update_payee_duplicate_name_rejected(session: AsyncSession, test_user, test_workspace):+ await create_payee(session, test_workspace.id, test_user.id, PayeeCreate(name="A"))+ b = await create_payee(session, test_workspace.id, test_user.id, PayeeCreate(name="B"))with pytest.raises(ValueError, match="already exists"):- await update_payee(session, b.id, test_user.id, PayeeUpdate(name="A"))+ await update_payee(session, b.id, test_workspace.id, PayeeUpdate(name="A"))# ---------------------------------------------------------------------------@@ -251,20 +251,20 @@ async def test_update_payee_duplicate_name_rejected(session: AsyncSession, test_@pytest.mark.asyncio-async def test_delete_payee(session: AsyncSession, test_user):- payee = await create_payee(session, test_user.id, PayeeCreate(name="ToDelete"))- assert await delete_payee(session, payee.id, test_user.id) is True- assert await get_payee(session, payee.id, test_user.id) is None+async def test_delete_payee(session: AsyncSession, test_user, test_workspace):+ payee = await create_payee(session, test_workspace.id, test_user.id, PayeeCreate(name="ToDelete"))+ assert await delete_payee(session, payee.id, test_workspace.id) is True+ assert await get_payee(session, payee.id, test_workspace.id) is None@pytest.mark.asyncio-async def test_delete_payee_not_found(session: AsyncSession, test_user):- assert await delete_payee(session, uuid.uuid4(), test_user.id) is False+async def test_delete_payee_not_found(session: AsyncSession, test_user, test_workspace):+ assert await delete_payee(session, uuid.uuid4(), test_workspace.id) is False@pytest.mark.asyncio-async def test_delete_payee_nulls_transaction_refs(session: AsyncSession, test_user):- payee = await create_payee(session, test_user.id, PayeeCreate(name="Linked"))+async def test_delete_payee_nulls_transaction_refs(session: AsyncSession, test_user, test_workspace):+ payee = await create_payee(session, test_workspace.id, test_user.id, PayeeCreate(name="Linked"))account = await _make_account(session, test_user)tx = Transaction(@@ -276,7 +276,7 @@ async def test_delete_payee_nulls_transaction_refs(session: AsyncSession, test_usession.add(tx)await session.commit()- await delete_payee(session, payee.id, test_user.id)+ await delete_payee(session, payee.id, test_workspace.id)await session.refresh(tx)assert tx.payee_id is None@@ -288,10 +288,10 @@ async def test_delete_payee_nulls_transaction_refs(session: AsyncSession, test_u@pytest.mark.asyncio-async def test_merge_payees(session: AsyncSession, test_user):- target = await create_payee(session, test_user.id, PayeeCreate(name="Target"))- source1 = await create_payee(session, test_user.id, PayeeCreate(name="Source1"))- source2 = await create_payee(session, test_user.id, PayeeCreate(name="Source2"))+async def test_merge_payees(session: AsyncSession, test_user, test_workspace):+ target = await create_payee(session, test_workspace.id, test_user.id, PayeeCreate(name="Target"))+ source1 = await create_payee(session, test_workspace.id, test_user.id, PayeeCreate(name="Source1"))+ source2 = await create_payee(session, test_workspace.id, test_user.id, PayeeCreate(name="Source2"))account = await _make_account(session, test_user)@@ -306,31 +306,31 @@ async def test_merge_payees(session: AsyncSession, test_user):await session.commit()reassigned = await merge_payees(- session, test_user.id, target.id, [source1.id, source2.id]+ session, test_workspace.id, target.id, [source1.id, source2.id])assert reassigned == 2# Sources should be deleted- assert await get_payee(session, source1.id, test_user.id) is None- assert await get_payee(session, source2.id, test_user.id) is None+ assert await get_payee(session, source1.id, test_workspace.id) is None+ assert await get_payee(session, source2.id, test_workspace.id) is None# Target should still exist- assert await get_payee(session, target.id, test_user.id) is not None+ assert await get_payee(session, target.id, test_workspace.id) is not None@pytest.mark.asyncio-async def test_merge_payees_target_not_found(session: AsyncSession, test_user):- source = await create_payee(session, test_user.id, PayeeCreate(name="Source"))+async def test_merge_payees_target_not_found(session: AsyncSession, test_user, test_workspace):+ source = await create_payee(session, test_workspace.id, test_user.id, PayeeCreate(name="Source"))with pytest.raises(ValueError, match="Target payee not found"):- await merge_payees(session, test_user.id, uuid.uuid4(), [source.id])+ await merge_payees(session, test_workspace.id, uuid.uuid4(), [source.id])@pytest.mark.asyncio-async def test_merge_payees_source_not_found(session: AsyncSession, test_user):- target = await create_payee(session, test_user.id, PayeeCreate(name="Target"))+async def test_merge_payees_source_not_found(session: AsyncSession, test_user, test_workspace):+ target = await create_payee(session, test_workspace.id, test_user.id, PayeeCreate(name="Target"))with pytest.raises(ValueError, match="Source payee"):- await merge_payees(session, test_user.id, target.id, [uuid.uuid4()])+ await merge_payees(session, test_workspace.id, target.id, [uuid.uuid4()])# ---------------------------------------------------------------------------@@ -339,8 +339,8 @@ async def test_merge_payees_source_not_found(session: AsyncSession, test_user):@pytest.mark.asyncio-async def test_get_payee_summary(session: AsyncSession, test_user, test_categories):- payee = await create_payee(session, test_user.id, PayeeCreate(name="Summary"))+async def test_get_payee_summary(session: AsyncSession, test_user, test_workspace, test_categories):+ payee = await create_payee(session, test_workspace.id, test_user.id, PayeeCreate(name="Summary"))account = await _make_account(session, test_user)cat = test_categories[0]@@ -359,7 +359,7 @@ async def test_get_payee_summary(session: AsyncSession, test_user, test_categori))await session.commit()- summary = await get_payee_summary(session, payee.id, test_user.id)+ summary = await get_payee_summary(session, payee.id, test_workspace.id)assert summary["total_spent"] == Decimal("150")assert summary["total_received"] == Decimal("30")@@ -370,15 +370,15 @@ async def test_get_payee_summary(session: AsyncSession, test_user, test_categori@pytest.mark.asyncio-async def test_get_payee_summary_not_found(session: AsyncSession, test_user):+async def test_get_payee_summary_not_found(session: AsyncSession, test_user, test_workspace):with pytest.raises(ValueError, match="Payee not found"):- await get_payee_summary(session, uuid.uuid4(), test_user.id)+ await get_payee_summary(session, uuid.uuid4(), test_workspace.id)@pytest.mark.asyncio-async def test_get_payee_summary_no_transactions(session: AsyncSession, test_user):- payee = await create_payee(session, test_user.id, PayeeCreate(name="Empty"))- summary = await get_payee_summary(session, payee.id, test_user.id)+async def test_get_payee_summary_no_transactions(session: AsyncSession, test_user, test_workspace):+ payee = await create_payee(session, test_workspace.id, test_user.id, PayeeCreate(name="Empty"))+ summary = await get_payee_summary(session, payee.id, test_workspace.id)assert summary["total_spent"] == Decimal("0")assert summary["total_received"] == Decimal("0")diff --git a/backend/tests/test_recurring_transaction_service.py b/backend/tests/test_recurring_transaction_service.pyindex 39e73f39..7d68b03c 100644--- a/backend/tests/test_recurring_transaction_service.py+++ b/backend/tests/test_recurring_transaction_service.py@@ -45,7 +45,7 @@ async def test_account_for_recurring(session: AsyncSession, test_user) -> Accoun@pytest.mark.asyncioasync def test_create_recurring_transaction(- session: AsyncSession, test_user, test_account_for_recurring+ session: AsyncSession, test_user, test_workspace, test_account_for_recurring):data = RecurringTransactionCreate(description="Netflix",@@ -55,7 +55,7 @@ async def test_create_recurring_transaction(start_date=date(2025, 1, 15),account_id=test_account_for_recurring.id,)- rec = await create_recurring_transaction(session, test_user.id, data)+ rec = await create_recurring_transaction(session, test_workspace.id, test_user.id, data)assert rec.id is not Noneassert rec.description == "Netflix"@@ -66,7 +66,7 @@ async def test_create_recurring_transaction(@pytest.mark.asyncio-async def test_create_with_skip_first(session: AsyncSession, test_user, test_account_for_recurring):+async def test_create_with_skip_first(session: AsyncSession, test_user, test_workspace, test_account_for_recurring):data = RecurringTransactionCreate(description="Rent",amount=Decimal("2000"),@@ -76,7 +76,7 @@ async def test_create_with_skip_first(session: AsyncSession, test_user, test_accaccount_id=test_account_for_recurring.id,skip_first=True,)- rec = await create_recurring_transaction(session, test_user.id, data)+ rec = await create_recurring_transaction(session, test_workspace.id, test_user.id, data)# skip_first should advance to next monthassert rec.start_date == date(2025, 3, 1)@@ -85,12 +85,12 @@ async def test_create_with_skip_first(session: AsyncSession, test_user, test_acc@pytest.mark.asyncioasync def test_get_recurring_transactions(- session: AsyncSession, test_user, test_account_for_recurring+ session: AsyncSession, test_user, test_workspace, test_account_for_recurring):for desc, dt in [("Sub1", date(2025, 1, 1)), ("Sub2", date(2025, 2, 1))]:await create_recurring_transaction(session,- test_user.id,+ test_workspace.id, test_user.id,RecurringTransactionCreate(description=desc,amount=Decimal("10"),@@ -101,7 +101,7 @@ async def test_get_recurring_transactions(),)- result = await get_recurring_transactions(session, test_user.id)+ result = await get_recurring_transactions(session, test_workspace.id)assert len(result) >= 2# Ordered by next_occurrence@@ -111,11 +111,11 @@ async def test_get_recurring_transactions(@pytest.mark.asyncioasync def test_get_recurring_transaction_by_id(- session: AsyncSession, test_user, test_account_for_recurring+ session: AsyncSession, test_user, test_workspace, test_account_for_recurring):created = await create_recurring_transaction(session,- test_user.id,+ test_workspace.id, test_user.id,RecurringTransactionCreate(description="Lookup",amount=Decimal("50"),@@ -125,24 +125,24 @@ async def test_get_recurring_transaction_by_id(account_id=test_account_for_recurring.id,),)- fetched = await get_recurring_transaction(session, created.id, test_user.id)+ fetched = await get_recurring_transaction(session, created.id, test_workspace.id)assert fetched is not Noneassert fetched.id == created.id@pytest.mark.asyncio-async def test_get_recurring_transaction_not_found(session: AsyncSession, test_user):- result = await get_recurring_transaction(session, uuid.uuid4(), test_user.id)+async def test_get_recurring_transaction_not_found(session: AsyncSession, test_user, test_workspace):+ result = await get_recurring_transaction(session, uuid.uuid4(), test_workspace.id)assert result is None@pytest.mark.asyncioasync def test_update_recurring_transaction(- session: AsyncSession, test_user, test_account_for_recurring+ session: AsyncSession, test_user, test_workspace, test_account_for_recurring):rec = await create_recurring_transaction(session,- test_user.id,+ test_workspace.id, test_user.id,RecurringTransactionCreate(description="Old",amount=Decimal("100"),@@ -155,7 +155,7 @@ async def test_update_recurring_transaction(updated = await update_recurring_transaction(session,rec.id,- test_user.id,+ test_workspace.id,RecurringTransactionUpdate(description="Updated", amount=Decimal("150")),)assert updated is not None@@ -164,11 +164,11 @@ async def test_update_recurring_transaction(@pytest.mark.asyncio-async def test_update_recurring_not_found(session: AsyncSession, test_user):+async def test_update_recurring_not_found(session: AsyncSession, test_user, test_workspace):result = await update_recurring_transaction(session,uuid.uuid4(),- test_user.id,+ test_workspace.id,RecurringTransactionUpdate(description="Nope"),)assert result is None@@ -176,11 +176,11 @@ async def test_update_recurring_not_found(session: AsyncSession, test_user):@pytest.mark.asyncioasync def test_delete_recurring_transaction(- session: AsyncSession, test_user, test_account_for_recurring+ session: AsyncSession, test_user, test_workspace, test_account_for_recurring):rec = await create_recurring_transaction(session,- test_user.id,+ test_workspace.id, test_user.id,RecurringTransactionCreate(description="ToDelete",amount=Decimal("10"),@@ -190,13 +190,13 @@ async def test_delete_recurring_transaction(account_id=test_account_for_recurring.id,),)- assert await delete_recurring_transaction(session, rec.id, test_user.id) is True- assert await get_recurring_transaction(session, rec.id, test_user.id) is None+ assert await delete_recurring_transaction(session, rec.id, test_workspace.id) is True+ assert await get_recurring_transaction(session, rec.id, test_workspace.id) is None@pytest.mark.asyncio-async def test_delete_recurring_not_found(session: AsyncSession, test_user):- assert await delete_recurring_transaction(session, uuid.uuid4(), test_user.id) is False+async def test_delete_recurring_not_found(session: AsyncSession, test_user, test_workspace):+ assert await delete_recurring_transaction(session, uuid.uuid4(), test_workspace.id) is False# ---------------------------------------------------------------------------@@ -373,10 +373,10 @@ def test_get_occurrences_in_range_monthly_day_29_does_not_drift():@pytest.mark.asyncio-async def test_generate_pending(session: AsyncSession, test_user, test_account_for_recurring):+async def test_generate_pending(session: AsyncSession, test_user, test_workspace, test_account_for_recurring):rec = await create_recurring_transaction(session,- test_user.id,+ test_workspace.id, test_user.id,RecurringTransactionCreate(description="Monthly Sub",amount=Decimal("29.90"),@@ -408,11 +408,11 @@ async def test_generate_pending(session: AsyncSession, test_user, test_account_f@pytest.mark.asyncioasync def test_generate_pending_deactivates_past_end_date(- session: AsyncSession, test_user, test_account_for_recurring+ session: AsyncSession, test_user, test_workspace, test_account_for_recurring):rec = await create_recurring_transaction(session,- test_user.id,+ test_workspace.id, test_user.id,RecurringTransactionCreate(description="Short Sub",amount=Decimal("10"),@@ -434,11 +434,11 @@ async def test_generate_pending_deactivates_past_end_date(@pytest.mark.asyncioasync def test_generate_pending_no_duplicates(- session: AsyncSession, test_user, test_account_for_recurring+ session: AsyncSession, test_user, test_workspace, test_account_for_recurring):await create_recurring_transaction(session,- test_user.id,+ test_workspace.id, test_user.id,RecurringTransactionCreate(description="NoDup",amount=Decimal("5"),diff --git a/backend/tests/test_report_service.py b/backend/tests/test_report_service.pyindex d8290950..ad498b9e 100644--- a/backend/tests/test_report_service.py+++ b/backend/tests/test_report_service.py@@ -211,14 +211,14 @@ async def _create_transaction(@pytest.mark.asyncio-async def test_net_worth_report_structure(session: AsyncSession, test_user):+async def test_net_worth_report_structure(session: AsyncSession, test_user, test_workspace):"""Net worth report returns correct ReportResponse structure."""account = await _create_manual_account(session, test_user.id, "NW Test")await _create_transaction(session, test_user.id, account.id, 5000, "credit", date.today(), source="opening_balance")- report = await get_net_worth_report(session, test_user.id, months=6, interval="monthly")+ report = await get_net_worth_report(session, test_workspace.id, test_user.id, months=6, interval="monthly")assert report.meta.type == "net_worth"assert report.meta.series_keys == ["accounts", "assets", "liabilities"]@@ -236,7 +236,7 @@ async def test_net_worth_report_structure(session: AsyncSession, test_user):@pytest.mark.asyncio-async def test_net_worth_report_reflects_balance(session: AsyncSession, test_user):+async def test_net_worth_report_reflects_balance(session: AsyncSession, test_user, test_workspace):"""Net worth report reflects actual account balance."""account = await _create_manual_account(session, test_user.id, "NW Balance Test")await _create_transaction(@@ -246,7 +246,7 @@ async def test_net_worth_report_reflects_balance(session: AsyncSession, test_usesession, test_user.id, account.id, 3000, "debit", date.today())- report = await get_net_worth_report(session, test_user.id, months=1, interval="monthly")+ report = await get_net_worth_report(session, test_workspace.id, test_user.id, months=1, interval="monthly")# Current net worth should be 10000 - 3000 = 7000assert report.summary.primary_value == 7000.0@@ -255,7 +255,7 @@ async def test_net_worth_report_reflects_balance(session: AsyncSession, test_use@pytest.mark.asyncio-async def test_net_worth_report_change_amount(session: AsyncSession, test_user):+async def test_net_worth_report_change_amount(session: AsyncSession, test_user, test_workspace):"""Net worth report computes change between first and last trend points."""account = await _create_manual_account(session, test_user.id, "NW Change Test")@@ -269,14 +269,14 @@ async def test_net_worth_report_change_amount(session: AsyncSession, test_user):session, test_user.id, account.id, 2000, "credit", date.today())- report = await get_net_worth_report(session, test_user.id, months=6, interval="monthly")+ report = await get_net_worth_report(session, test_workspace.id, test_user.id, months=6, interval="monthly")# change_amount = last.value - first.value; should be positiveassert report.summary.change_amount >= 0@pytest.mark.asyncio-async def test_net_worth_report_excludes_closed_accounts(session: AsyncSession, test_user):+async def test_net_worth_report_excludes_closed_accounts(session: AsyncSession, test_user, test_workspace):"""Closed accounts are excluded from net worth."""# Open account with 5000open_acct = await _create_manual_account(session, test_user.id, "NW Open")@@ -300,14 +300,14 @@ async def test_net_worth_report_excludes_closed_accounts(session: AsyncSession,session, test_user.id, closed_acct.id, 3000, "credit", date.today(), source="opening_balance")- report = await get_net_worth_report(session, test_user.id, months=1, interval="monthly")+ report = await get_net_worth_report(session, test_workspace.id, test_user.id, months=1, interval="monthly")# Should only include the open accountassert report.summary.primary_value == 5000.0@pytest.mark.asyncio-async def test_net_worth_report_intervals(session: AsyncSession, test_user):+async def test_net_worth_report_intervals(session: AsyncSession, test_user, test_workspace):"""Net worth report works with different interval options."""account = await _create_manual_account(session, test_user.id, "NW Interval Test")await _create_transaction(@@ -315,7 +315,7 @@ async def test_net_worth_report_intervals(session: AsyncSession, test_user):)for interval in ["daily", "weekly", "monthly", "yearly"]:- report = await get_net_worth_report(session, test_user.id, months=6, interval=interval)+ report = await get_net_worth_report(session, test_workspace.id, test_user.id, months=6, interval=interval)assert report.meta.interval == intervalassert len(report.trend) > 0@@ -537,14 +537,14 @@ def test_report_response_includes_category_trend():@pytest.mark.asyncio-async def test_net_worth_report_has_empty_category_trend(session: AsyncSession, test_user):+async def test_net_worth_report_has_empty_category_trend(session: AsyncSession, test_user, test_workspace):"""Net worth report returns empty category_trend (only used by income_expenses)."""account = await _create_manual_account(session, test_user.id, "NW CatTrend Test")await _create_transaction(session, test_user.id, account.id, 1000, "credit", date.today(), source="opening_balance")- report = await get_net_worth_report(session, test_user.id, months=3, interval="monthly")+ report = await get_net_worth_report(session, test_workspace.id, test_user.id, months=3, interval="monthly")assert report.category_trend == []@@ -612,7 +612,7 @@ async def _add_txn(session, user_id, account_id, amount, txn_type, txn_date, sou@pytest.mark.asyncio-async def test_asset_value_at_with_entries(session: AsyncSession, test_user: User):+async def test_asset_value_at_with_entries(session: AsyncSession, test_user, test_workspace: User):asset = Asset(id=uuid.uuid4(), user_id=test_user.id, name="House",type="real_estate", currency="BRL",@@ -631,12 +631,12 @@ async def test_asset_value_at_with_entries(session: AsyncSession, test_user: Usesession.add_all([v1, v2])await session.commit()- total = await _asset_value_at(session, test_user.id, date.today(), "BRL")+ total = await _asset_value_at(session, test_workspace.id, date.today(), "BRL")assert total == 110000.0@pytest.mark.asyncio-async def test_asset_value_at_fallback_purchase_price(session: AsyncSession, test_user: User):+async def test_asset_value_at_fallback_purchase_price(session: AsyncSession, test_user, test_workspace: User):asset = Asset(id=uuid.uuid4(), user_id=test_user.id, name="Car",type="vehicle", currency="BRL",@@ -646,12 +646,12 @@ async def test_asset_value_at_fallback_purchase_price(session: AsyncSession, tessession.add(asset)await session.commit()- total = await _asset_value_at(session, test_user.id, date.today(), "BRL")+ total = await _asset_value_at(session, test_workspace.id, date.today(), "BRL")assert total == 50000.0@pytest.mark.asyncio-async def test_asset_value_at_excludes_archived(session: AsyncSession, test_user: User):+async def test_asset_value_at_excludes_archived(session: AsyncSession, test_user, test_workspace: User):asset = Asset(id=uuid.uuid4(), user_id=test_user.id, name="Sold Car",type="vehicle", currency="BRL",@@ -660,12 +660,12 @@ async def test_asset_value_at_excludes_archived(session: AsyncSession, test_usersession.add(asset)await session.commit()- total = await _asset_value_at(session, test_user.id, date.today(), "BRL")+ total = await _asset_value_at(session, test_workspace.id, date.today(), "BRL")assert total == 0.0@pytest.mark.asyncio-async def test_asset_value_at_excludes_sold(session: AsyncSession, test_user: User):+async def test_asset_value_at_excludes_sold(session: AsyncSession, test_user, test_workspace: User):asset = Asset(id=uuid.uuid4(), user_id=test_user.id, name="Sold Asset",type="vehicle", currency="BRL",@@ -675,12 +675,12 @@ async def test_asset_value_at_excludes_sold(session: AsyncSession, test_user: Ussession.add(asset)await session.commit()- total = await _asset_value_at(session, test_user.id, date.today(), "BRL")+ total = await _asset_value_at(session, test_workspace.id, date.today(), "BRL")assert total == 0.0@pytest.mark.asyncio-async def test_asset_value_at_purchase_date_after_cutoff(session: AsyncSession, test_user: User):+async def test_asset_value_at_purchase_date_after_cutoff(session: AsyncSession, test_user, test_workspace: User):asset = Asset(id=uuid.uuid4(), user_id=test_user.id, name="Future Asset",type="other", currency="BRL",@@ -690,7 +690,7 @@ async def test_asset_value_at_purchase_date_after_cutoff(session: AsyncSession,session.add(asset)await session.commit()- total = await _asset_value_at(session, test_user.id, date.today(), "BRL")+ total = await _asset_value_at(session, test_workspace.id, date.today(), "BRL")assert total == 0.0@@ -700,7 +700,7 @@ async def test_asset_value_at_purchase_date_after_cutoff(session: AsyncSession,@pytest.mark.asyncio-async def test_net_worth_with_credit_card(session: AsyncSession, test_user: User):+async def test_net_worth_with_credit_card(session: AsyncSession, test_user, test_workspace: User):checking = await _make_manual_account(session, test_user.id, "NW Check")await _add_txn(session, test_user.id, checking.id, 5000, "credit", date.today())@@ -720,14 +720,14 @@ async def test_net_worth_with_credit_card(session: AsyncSession, test_user: Usersession.add(cc)await session.commit()- dp = await _net_worth_at(session, test_user.id, date.today(), "BRL")+ dp = await _net_worth_at(session, test_workspace.id, date.today(), "BRL")assert dp.breakdowns["accounts"] == 5000.0assert dp.breakdowns["liabilities"] == 1000.0assert dp.value == 4000.0@pytest.mark.asyncio-async def test_net_worth_with_assets(session: AsyncSession, test_user: User):+async def test_net_worth_with_assets(session: AsyncSession, test_user, test_workspace: User):checking = await _make_manual_account(session, test_user.id, "NW Assets Check")await _add_txn(session, test_user.id, checking.id, 3000, "credit", date.today())@@ -740,18 +740,18 @@ async def test_net_worth_with_assets(session: AsyncSession, test_user: User):session.add(asset)await session.commit()- dp = await _net_worth_at(session, test_user.id, date.today(), "BRL")+ dp = await _net_worth_at(session, test_workspace.id, date.today(), "BRL")assert dp.breakdowns["accounts"] == 3000.0assert dp.breakdowns["assets"] == 200000.0assert dp.value == 203000.0@pytest.mark.asyncio-async def test_net_worth_negative_manual_balance(session: AsyncSession, test_user: User):+async def test_net_worth_negative_manual_balance(session: AsyncSession, test_user, test_workspace: User):acct = await _make_manual_account(session, test_user.id, "NW Negative")await _add_txn(session, test_user.id, acct.id, 1000, "debit", date.today())- dp = await _net_worth_at(session, test_user.id, date.today(), "BRL")+ dp = await _net_worth_at(session, test_workspace.id, date.today(), "BRL")assert dp.breakdowns["accounts"] == -1000.0@@ -761,17 +761,17 @@ async def test_net_worth_negative_manual_balance(session: AsyncSession, test_use@pytest.mark.asyncio-async def test_net_worth_composition_includes_accounts(session: AsyncSession, test_user: User):+async def test_net_worth_composition_includes_accounts(session: AsyncSession, test_user, test_workspace: User):acct = await _make_manual_account(session, test_user.id, "Comp Acct")await _add_txn(session, test_user.id, acct.id, 10000, "credit", date.today())- report = await get_net_worth_report(session, test_user.id, months=1, interval="monthly")+ report = await get_net_worth_report(session, test_workspace.id, test_user.id, months=1, interval="monthly")comp_labels = [c.label for c in report.composition]assert "Comp Acct" in comp_labels@pytest.mark.asyncio-async def test_net_worth_composition_includes_assets(session: AsyncSession, test_user: User):+async def test_net_worth_composition_includes_assets(session: AsyncSession, test_user, test_workspace: User):asset = Asset(id=uuid.uuid4(), user_id=test_user.id, name="Comp Asset",type="investment", currency="BRL",@@ -781,48 +781,48 @@ async def test_net_worth_composition_includes_assets(session: AsyncSession, testsession.add(asset)await session.commit()- report = await get_net_worth_report(session, test_user.id, months=1, interval="monthly")+ report = await get_net_worth_report(session, test_workspace.id, test_user.id, months=1, interval="monthly")comp_labels = [c.label for c in report.composition]assert "Comp Asset" in comp_labels@pytest.mark.asyncio-async def test_net_worth_composition_uses_display_name(session: AsyncSession, test_user: User):+async def test_net_worth_composition_uses_display_name(session: AsyncSession, test_user, test_workspace: User):"""Composition labels must use display_name when set, falling back to name."""acct = await _make_manual_account(session, test_user.id, "Provider Name")acct.display_name = "My Nickname"await session.commit()await _add_txn(session, test_user.id, acct.id, 10000, "credit", date.today())- report = await get_net_worth_report(session, test_user.id, months=1, interval="monthly")+ report = await get_net_worth_report(session, test_workspace.id, test_user.id, months=1, interval="monthly")comp_labels = [c.label for c in report.composition]assert "My Nickname" in comp_labelsassert "Provider Name" not in comp_labels@pytest.mark.asyncio-async def test_net_worth_weekly_interval(session: AsyncSession, test_user: User):+async def test_net_worth_weekly_interval(session: AsyncSession, test_user, test_workspace: User):acct = await _make_manual_account(session, test_user.id, "Weekly Test")await _add_txn(session, test_user.id, acct.id, 1000, "credit", date.today())- report = await get_net_worth_report(session, test_user.id, months=2, interval="weekly")+ report = await get_net_worth_report(session, test_workspace.id, test_user.id, months=2, interval="weekly")assert report.meta.interval == "weekly"assert len(report.trend) > 1@pytest.mark.asyncio-async def test_net_worth_daily_interval(session: AsyncSession, test_user: User):+async def test_net_worth_daily_interval(session: AsyncSession, test_user, test_workspace: User):acct = await _make_manual_account(session, test_user.id, "Daily Test")await _add_txn(session, test_user.id, acct.id, 500, "credit", date.today())- report = await get_net_worth_report(session, test_user.id, months=1, interval="daily")+ report = await get_net_worth_report(session, test_workspace.id, test_user.id, months=1, interval="daily")assert report.meta.interval == "daily"assert len(report.trend) > 10@pytest.mark.asyncio-async def test_net_worth_change_percent_zero_previous(session: AsyncSession, test_user: User):- report = await get_net_worth_report(session, test_user.id, months=1, interval="monthly")+async def test_net_worth_change_percent_zero_previous(session: AsyncSession, test_user, test_workspace: User):+ report = await get_net_worth_report(session, test_workspace.id, test_user.id, months=1, interval="monthly")if report.summary.primary_value == 0:assert report.summary.change_percent is None@@ -902,7 +902,7 @@ async def _make_recurring(@pytest.mark.asyncio-async def test_cash_flow_report_structure(session: AsyncSession, test_user: User):+async def test_cash_flow_report_structure(session: AsyncSession, test_user, test_workspace: User):"""Cash flow report returns a well-formed ReportResponse."""account = await _make_manual_account(session, test_user.id, "CF Structure")await _add_txn(@@ -910,7 +910,7 @@ async def test_cash_flow_report_structure(session: AsyncSession, test_user: Userdate.today(), source="opening_balance",)- report = await get_cash_flow_report(session, test_user.id, months=6, interval="daily")+ report = await get_cash_flow_report(session, test_workspace.id, test_user.id, months=6, interval="daily")assert report.meta.type == "cash_flow"assert report.meta.series_keys == ["balance"]@@ -924,7 +924,7 @@ async def test_cash_flow_report_structure(session: AsyncSession, test_user: User@pytest.mark.asyncioasync def test_cash_flow_starting_balance_matches_today(- session: AsyncSession, test_user: User+ session: AsyncSession, test_user, test_workspace: User):"""startingBalance breakdown == sum of account balances at today."""account = await _make_manual_account(session, test_user.id, "CF Start")@@ -933,17 +933,17 @@ async def test_cash_flow_starting_balance_matches_today(date.today(), source="opening_balance",)- report = await get_cash_flow_report(session, test_user.id, months=3, interval="daily")+ report = await get_cash_flow_report(session, test_workspace.id, test_user.id, months=3, interval="daily")starting = next(b for b in report.summary.breakdowns if b.key == "startingBalance")assert starting.value == 1234.56@pytest.mark.asyncioasync def test_cash_flow_no_data_is_flat_at_zero(- session: AsyncSession, test_user: User+ session: AsyncSession, test_user, test_workspace: User):"""User with no accounts → flat line at 0."""- report = await get_cash_flow_report(session, test_user.id, months=3, interval="daily")+ report = await get_cash_flow_report(session, test_workspace.id, test_user.id, months=3, interval="daily")assert report.summary.primary_value == 0.0assert report.summary.change_amount == 0.0assert report.summary.change_percent is None # zero starting → percent undefined@@ -954,7 +954,7 @@ async def test_cash_flow_no_data_is_flat_at_zero(@pytest.mark.asyncioasync def test_cash_flow_no_data_with_balance_is_flat(- session: AsyncSession, test_user: User+ session: AsyncSession, test_user, test_workspace: User):"""Account with balance but no recurring → flat line at starting balance."""account = await _make_manual_account(session, test_user.id, "CF Flat")@@ -963,7 +963,7 @@ async def test_cash_flow_no_data_with_balance_is_flat(date.today(), source="opening_balance",)- report = await get_cash_flow_report(session, test_user.id, months=3, interval="daily")+ report = await get_cash_flow_report(session, test_workspace.id, test_user.id, months=3, interval="daily")assert report.summary.primary_value == 2500.0assert report.summary.change_amount == 0.0@@ -973,7 +973,7 @@ async def test_cash_flow_no_data_with_balance_is_flat(@pytest.mark.asyncioasync def test_cash_flow_recurring_credit_increases_balance(- session: AsyncSession, test_user: User+ session: AsyncSession, test_user, test_workspace: User):"""Monthly salary credit should drive ending balance above starting."""account = await _make_manual_account(session, test_user.id, "CF Salary")@@ -990,7 +990,7 @@ async def test_cash_flow_recurring_credit_increases_balance(day_of_month=today.day, next_occurrence=salary_day,)- report = await get_cash_flow_report(session, test_user.id, months=3, interval="daily")+ report = await get_cash_flow_report(session, test_workspace.id, test_user.id, months=3, interval="daily")proj_income = next(b for b in report.summary.breakdowns if b.key == "projectedIncome")proj_exp = next(b for b in report.summary.breakdowns if b.key == "projectedExpenses")@@ -1005,7 +1005,7 @@ async def test_cash_flow_recurring_credit_increases_balance(@pytest.mark.asyncioasync def test_cash_flow_recurring_debit_decreases_balance(- session: AsyncSession, test_user: User+ session: AsyncSession, test_user, test_workspace: User):"""Monthly rent debit should drive ending balance below starting."""account = await _make_manual_account(session, test_user.id, "CF Rent")@@ -1022,7 +1022,7 @@ async def test_cash_flow_recurring_debit_decreases_balance(day_of_month=nxt.day, next_occurrence=nxt,)- report = await get_cash_flow_report(session, test_user.id, months=3, interval="daily")+ report = await get_cash_flow_report(session, test_workspace.id, test_user.id, months=3, interval="daily")proj_exp = next(b for b in report.summary.breakdowns if b.key == "projectedExpenses")ending = next(b for b in report.summary.breakdowns if b.key == "endingBalance")@@ -1034,7 +1034,7 @@ async def test_cash_flow_recurring_debit_decreases_balance(@pytest.mark.asyncioasync def test_cash_flow_inactive_recurring_excluded(- session: AsyncSession, test_user: User+ session: AsyncSession, test_user, test_workspace: User):"""is_active=False recurring should not contribute to projection."""account = await _make_manual_account(session, test_user.id, "CF Inactive")@@ -1050,14 +1050,14 @@ async def test_cash_flow_inactive_recurring_excluded(next_occurrence=today + timedelta(days=2), is_active=False,)- report = await get_cash_flow_report(session, test_user.id, months=3, interval="daily")+ report = await get_cash_flow_report(session, test_workspace.id, test_user.id, months=3, interval="daily")proj_exp = next(b for b in report.summary.breakdowns if b.key == "projectedExpenses")assert proj_exp.value == 0.0@pytest.mark.asyncioasync def test_cash_flow_recurring_end_date_stops_contribution(- session: AsyncSession, test_user: User+ session: AsyncSession, test_user, test_workspace: User):"""Recurring with end_date in window should stop contributing past that date."""account = await _make_manual_account(session, test_user.id, "CF EndDate")@@ -1076,8 +1076,8 @@ async def test_cash_flow_recurring_end_date_stops_contribution(day_of_month=nxt.day, next_occurrence=nxt, end_date=end,)- short_report = await get_cash_flow_report(session, test_user.id, months=2, interval="daily")- long_report = await get_cash_flow_report(session, test_user.id, months=6, interval="daily")+ short_report = await get_cash_flow_report(session, test_workspace.id, test_user.id, months=2, interval="daily")+ long_report = await get_cash_flow_report(session, test_workspace.id, test_user.id, months=6, interval="daily")short_inc = next(b for b in short_report.summary.breakdowns if b.key == "projectedIncome")long_inc = next(b for b in long_report.summary.breakdowns if b.key == "projectedIncome")@@ -1087,7 +1087,7 @@ async def test_cash_flow_recurring_end_date_stops_contribution(@pytest.mark.asyncioasync def test_cash_flow_future_dated_booked_transaction_included(- session: AsyncSession, test_user: User+ session: AsyncSession, test_user, test_workspace: User):"""A Transaction with date > today is folded into the projection."""account = await _make_manual_account(session, test_user.id, "CF Future Tx")@@ -1101,7 +1101,7 @@ async def test_cash_flow_future_dated_booked_transaction_included(date.today() + timedelta(days=10),)- report = await get_cash_flow_report(session, test_user.id, months=3, interval="daily")+ report = await get_cash_flow_report(session, test_workspace.id, test_user.id, months=3, interval="daily")proj_income = next(b for b in report.summary.breakdowns if b.key == "projectedIncome")ending = next(b for b in report.summary.breakdowns if b.key == "endingBalance")@@ -1111,7 +1111,7 @@ async def test_cash_flow_future_dated_booked_transaction_included(@pytest.mark.asyncioasync def test_cash_flow_opening_balance_excluded_from_inflow(- session: AsyncSession, test_user: User+ session: AsyncSession, test_user, test_workspace: User):"""opening_balance txns sit in starting balance and never count as inflow."""account = await _make_manual_account(session, test_user.id, "CF OB")@@ -1121,14 +1121,14 @@ async def test_cash_flow_opening_balance_excluded_from_inflow(date.today() + timedelta(days=5), source="opening_balance",)- report = await get_cash_flow_report(session, test_user.id, months=2, interval="daily")+ report = await get_cash_flow_report(session, test_workspace.id, test_user.id, months=2, interval="daily")proj_income = next(b for b in report.summary.breakdowns if b.key == "projectedIncome")assert proj_income.value == 0.0@pytest.mark.asyncioasync def test_cash_flow_closed_account_excluded(- session: AsyncSession, test_user: User+ session: AsyncSession, test_user, test_workspace: User):"""Future-dated transactions on closed accounts are excluded."""open_acct = await _make_manual_account(session, test_user.id, "CF Open")@@ -1149,13 +1149,13 @@ async def test_cash_flow_closed_account_excluded(date.today() + timedelta(days=3),)- report = await get_cash_flow_report(session, test_user.id, months=2, interval="daily")+ report = await get_cash_flow_report(session, test_workspace.id, test_user.id, months=2, interval="daily")proj_income = next(b for b in report.summary.breakdowns if b.key == "projectedIncome")assert proj_income.value == 0.0@pytest.mark.asyncio-async def test_cash_flow_intervals(session: AsyncSession, test_user: User):+async def test_cash_flow_intervals(session: AsyncSession, test_user, test_workspace: User):"""All supported intervals produce valid trends."""account = await _make_manual_account(session, test_user.id, "CF Intervals")await _add_txn(@@ -1171,7 +1171,7 @@ async def test_cash_flow_intervals(session: AsyncSession, test_user: User):intervals_seen = {}for interval in ["daily", "weekly", "monthly"]:- rep = await get_cash_flow_report(session, test_user.id, months=2, interval=interval)+ rep = await get_cash_flow_report(session, test_workspace.id, test_user.id, months=2, interval=interval)assert rep.meta.interval == intervalassert len(rep.trend) > 0intervals_seen[interval] = rep.summary.breakdowns@@ -1186,7 +1186,7 @@ async def test_cash_flow_intervals(session: AsyncSession, test_user: User):@pytest.mark.asyncio-async def test_cash_flow_months_range(session: AsyncSession, test_user: User):+async def test_cash_flow_months_range(session: AsyncSession, test_user, test_workspace: User):"""Different `months` values produce trends ending at different dates."""account = await _make_manual_account(session, test_user.id, "CF Months")await _add_txn(@@ -1194,9 +1194,9 @@ async def test_cash_flow_months_range(session: AsyncSession, test_user: User):date.today(), source="opening_balance",)- rep_1 = await get_cash_flow_report(session, test_user.id, months=1, interval="daily")- rep_6 = await get_cash_flow_report(session, test_user.id, months=6, interval="daily")- rep_12 = await get_cash_flow_report(session, test_user.id, months=12, interval="daily")+ rep_1 = await get_cash_flow_report(session, test_workspace.id, test_user.id, months=1, interval="daily")+ rep_6 = await get_cash_flow_report(session, test_workspace.id, test_user.id, months=6, interval="daily")+ rep_12 = await get_cash_flow_report(session, test_workspace.id, test_user.id, months=12, interval="daily")# Daily intervals → 1mo ≈ 30 points, 6mo ≈ 184, 12mo ≈ 366assert len(rep_1.trend) < len(rep_6.trend) < len(rep_12.trend)@@ -1204,7 +1204,7 @@ async def test_cash_flow_months_range(session: AsyncSession, test_user: User):@pytest.mark.asyncioasync def test_cash_flow_balance_is_running_cumulative(- session: AsyncSession, test_user: User+ session: AsyncSession, test_user, test_workspace: User):"""Each subsequent trend point's value reflects accumulated flows."""account = await _make_manual_account(session, test_user.id, "CF Cumul")@@ -1221,7 +1221,7 @@ async def test_cash_flow_balance_is_running_cumulative(next_occurrence=today + timedelta(days=2),)- report = await get_cash_flow_report(session, test_user.id, months=2, interval="daily")+ report = await get_cash_flow_report(session, test_workspace.id, test_user.id, months=2, interval="daily")# The trend should be monotonically non-decreasing (no debits, only credits)values = [p.value for p in report.trend]for prev, curr in zip(values, values[1:]):@@ -1229,7 +1229,7 @@ async def test_cash_flow_balance_is_running_cumulative(@pytest.mark.asyncio-async def test_cash_flow_composition_groups(session: AsyncSession, test_user: User):+async def test_cash_flow_composition_groups(session: AsyncSession, test_user, test_workspace: User):"""Composition splits recurring projections into income/expenses groups."""account = await _make_manual_account(session, test_user.id, "CF Comp")await _add_txn(@@ -1250,7 +1250,7 @@ async def test_cash_flow_composition_groups(session: AsyncSession, test_user: Usdescription="Expense recurring",)- report = await get_cash_flow_report(session, test_user.id, months=3, interval="daily")+ report = await get_cash_flow_report(session, test_workspace.id, test_user.id, months=3, interval="daily")groups = {c.group for c in report.composition}assert "income" in groups@@ -1262,7 +1262,7 @@ async def test_cash_flow_composition_groups(session: AsyncSession, test_user: Us@pytest.mark.asyncioasync def test_cash_flow_change_percent_zero_starting(- session: AsyncSession, test_user: User+ session: AsyncSession, test_user, test_workspace: User):"""When starting balance is 0, change_percent is None."""account = await _make_manual_account(session, test_user.id, "CF Zero")@@ -1273,12 +1273,12 @@ async def test_cash_flow_change_percent_zero_starting(next_occurrence=today + timedelta(days=2),)- report = await get_cash_flow_report(session, test_user.id, months=3, interval="daily")+ report = await get_cash_flow_report(session, test_workspace.id, test_user.id, months=3, interval="daily")assert report.summary.change_percent is None@pytest.mark.asyncio-async def test_cash_flow_weekly_recurring(session: AsyncSession, test_user: User):+async def test_cash_flow_weekly_recurring(session: AsyncSession, test_user, test_workspace: User):"""Weekly frequency expands into multiple occurrences in window."""account = await _make_manual_account(session, test_user.id, "CF Weekly")await _add_txn(@@ -1292,7 +1292,7 @@ async def test_cash_flow_weekly_recurring(session: AsyncSession, test_user: Usernext_occurrence=today + timedelta(days=1),)- report = await get_cash_flow_report(session, test_user.id, months=1, interval="daily")+ report = await get_cash_flow_report(session, test_workspace.id, test_user.id, months=1, interval="daily")proj_exp = next(b for b in report.summary.breakdowns if b.key == "projectedExpenses")# ~4-5 weekly occurrences in 1 monthassert 240.0 <= proj_exp.value <= 480.0@@ -1300,7 +1300,7 @@ async def test_cash_flow_weekly_recurring(session: AsyncSession, test_user: User@pytest.mark.asyncioasync def test_cash_flow_only_recurrings_after_today(- session: AsyncSession, test_user: User+ session: AsyncSession, test_user, test_workspace: User):"""Recurring with next_occurrence == today is NOT counted (today is starting)."""account = await _make_manual_account(session, test_user.id, "CF Today")@@ -1317,7 +1317,7 @@ async def test_cash_flow_only_recurrings_after_today(next_occurrence=today,)- report = await get_cash_flow_report(session, test_user.id, months=2, interval="daily")+ report = await get_cash_flow_report(session, test_workspace.id, test_user.id, months=2, interval="daily")proj_income = next(b for b in report.summary.breakdowns if b.key == "projectedIncome")# Over 2 months: 3 raw monthly occurrences (today, +1mo, +2mo) but the# one ON today is excluded — so we expect exactly 2 × 999 = 1998.@@ -1453,7 +1453,7 @@ async def _set_accounting_mode(session: AsyncSession, mode: str) -> None:@pytest.mark.asyncioasync def test_cash_flow_cash_mode_uses_transaction_date(- session: AsyncSession, test_user: User+ session: AsyncSession, test_user, test_workspace: User):"""In cash mode: a CC purchase made today (effective_date in future) isalready counted in starting balance via the CC liability — and is NOT@@ -1479,7 +1479,7 @@ async def test_cash_flow_cash_mode_uses_transaction_date(session.add(cc_purchase)await session.commit()- report = await get_cash_flow_report(session, test_user.id, months=2, interval="daily")+ report = await get_cash_flow_report(session, test_workspace.id, test_user.id, months=2, interval="daily")starting = next(b for b in report.summary.breakdowns if b.key == "startingBalance")proj_exp = next(b for b in report.summary.breakdowns if b.key == "projectedExpenses")@@ -1494,7 +1494,7 @@ async def test_cash_flow_cash_mode_uses_transaction_date(@pytest.mark.asyncioasync def test_cash_flow_accrual_mode_projects_cc_on_effective_date(- session: AsyncSession, test_user: User+ session: AsyncSession, test_user, test_workspace: User):"""In accrual mode: a CC purchase with effective_date > today is addedback to starting balance (so it represents 'cash on hand right now') and@@ -1518,7 +1518,7 @@ async def test_cash_flow_accrual_mode_projects_cc_on_effective_date(session.add(cc_purchase)await session.commit()- report = await get_cash_flow_report(session, test_user.id, months=2, interval="daily")+ report = await get_cash_flow_report(session, test_workspace.id, test_user.id, months=2, interval="daily")starting = next(b for b in report.summary.breakdowns if b.key == "startingBalance")proj_exp = next(b for b in report.summary.breakdowns if b.key == "projectedExpenses")@@ -1544,7 +1544,7 @@ async def test_cash_flow_accrual_mode_projects_cc_on_effective_date(@pytest.mark.asyncioasync def test_cash_flow_accrual_mode_no_double_count(- session: AsyncSession, test_user: User+ session: AsyncSession, test_user, test_workspace: User):"""Accrual mode: the same CC purchase must not appear in both startingbalance AND future flows — sum of (starting + inflow - outflow) over the@@ -1569,7 +1569,7 @@ async def test_cash_flow_accrual_mode_no_double_count())await session.commit()- report = await get_cash_flow_report(session, test_user.id, months=2, interval="daily")+ report = await get_cash_flow_report(session, test_workspace.id, test_user.id, months=2, interval="daily")starting = next(b for b in report.summary.breakdowns if b.key == "startingBalance")proj_exp = next(b for b in report.summary.breakdowns if b.key == "projectedExpenses")@@ -1585,7 +1585,7 @@ async def test_cash_flow_accrual_mode_no_double_count(@pytest.mark.asyncioasync def test_cash_flow_accrual_mode_cc_purchase_outside_window_ignored(- session: AsyncSession, test_user: User+ session: AsyncSession, test_user, test_workspace: User):"""A CC purchase whose effective_date falls past the projection window isnot added back nor projected — its impact remains in starting balance."""@@ -1608,7 +1608,7 @@ async def test_cash_flow_accrual_mode_cc_purchase_outside_window_ignored())await session.commit()- report = await get_cash_flow_report(session, test_user.id, months=2, interval="daily")+ report = await get_cash_flow_report(session, test_workspace.id, test_user.id, months=2, interval="daily")starting = next(b for b in report.summary.breakdowns if b.key == "startingBalance")proj_exp = next(b for b in report.summary.breakdowns if b.key == "projectedExpenses")@@ -1646,7 +1646,7 @@ def _next_first_of_month(d: date) -> date:@pytest.mark.asyncioasync def test_cash_flow_recurring_in_foreign_currency(- session: AsyncSession, test_user: User+ session: AsyncSession, test_user, test_workspace: User):"""A recurring in USD with primary BRL is converted via the FX rate."""# Primary currency for test_user is BRL. Seed USD->BRL = 5.0.@@ -1668,14 +1668,14 @@ async def test_cash_flow_recurring_in_foreign_currency()# 3-month window from today. Window covers exactly 3 "1st of month" anchors.- report = await get_cash_flow_report(session, test_user.id, months=3, interval="daily")+ report = await get_cash_flow_report(session, test_workspace.id, test_user.id, months=3, interval="daily")proj_income = next(b for b in report.summary.breakdowns if b.key == "projectedIncome")# 3 occurrences × 200 USD × 5.0 = 3000 BRLassert proj_income.value == 3000.0@pytest.mark.asyncio-async def test_cash_flow_mixed_currencies(session: AsyncSession, test_user: User):+async def test_cash_flow_mixed_currencies(session: AsyncSession, test_user, test_workspace: User):"""Recurrings in multiple currencies converted correctly using cached rates."""# Primary is BRL. Seed cross rates via USD anchor.# USD->BRL = 5.0, USD->EUR = 0.5 ⇒ EUR->BRL = 5.0 / 0.5 = 10.0@@ -1704,7 +1704,7 @@ async def test_cash_flow_mixed_currencies(session: AsyncSession, test_user: Userdescription="BRL expense",)- report = await get_cash_flow_report(session, test_user.id, months=2, interval="daily")+ report = await get_cash_flow_report(session, test_workspace.id, test_user.id, months=2, interval="daily")proj_income = next(b for b in report.summary.breakdowns if b.key == "projectedIncome")proj_exp = next(b for b in report.summary.breakdowns if b.key == "projectedExpenses")@@ -1717,7 +1717,7 @@ async def test_cash_flow_mixed_currencies(session: AsyncSession, test_user: User@pytest.mark.asyncioasync def test_cash_flow_currency_conversion_uses_amount_primary_when_present(- session: AsyncSession, test_user: User+ session: AsyncSession, test_user, test_workspace: User):"""A future-dated transaction with amount_primary set uses that value,skipping FX conversion."""@@ -1740,7 +1740,7 @@ async def test_cash_flow_currency_conversion_uses_amount_primary_when_present(session.add(txn)await session.commit()- report = await get_cash_flow_report(session, test_user.id, months=1, interval="daily")+ report = await get_cash_flow_report(session, test_workspace.id, test_user.id, months=1, interval="daily")proj_income = next(b for b in report.summary.breakdowns if b.key == "projectedIncome")assert proj_income.value == 777.77@@ -1752,7 +1752,7 @@ async def test_cash_flow_currency_conversion_uses_amount_primary_when_present(@pytest.mark.asyncioasync def test_cash_flow_end_date_exact_occurrence_count(- session: AsyncSession, test_user: User+ session: AsyncSession, test_user, test_workspace: User):"""When end_date falls mid-window, exactly the expected number ofoccurrences is projected — not more, not fewer."""@@ -1774,7 +1774,7 @@ async def test_cash_flow_end_date_exact_occurrence_count()# Window of 6 months — well past end_date- report = await get_cash_flow_report(session, test_user.id, months=6, interval="daily")+ report = await get_cash_flow_report(session, test_workspace.id, test_user.id, months=6, interval="daily")proj_income = next(b for b in report.summary.breakdowns if b.key == "projectedIncome")# Exactly 3 × 50 = 150assert proj_income.value == 150.0@@ -1782,7 +1782,7 @@ async def test_cash_flow_end_date_exact_occurrence_count(@pytest.mark.asyncioasync def test_cash_flow_end_date_balance_freezes_after(- session: AsyncSession, test_user: User+ session: AsyncSession, test_user, test_workspace: User):"""After the recurring's end_date, the running balance stops changing."""account = await _make_manual_account(session, test_user.id, "CF EndDateFreeze")@@ -1800,7 +1800,7 @@ async def test_cash_flow_end_date_balance_freezes_after(next_occurrence=nxt, end_date=end_d,)- report = await get_cash_flow_report(session, test_user.id, months=4, interval="daily")+ report = await get_cash_flow_report(session, test_workspace.id, test_user.id, months=4, interval="daily")# Balance after end_date should match ending balance — it shouldn't keep# growing once the recurring stops contributing.@@ -1814,7 +1814,7 @@ async def test_cash_flow_end_date_balance_freezes_after(@pytest.mark.asyncioasync def test_cash_flow_end_date_at_exact_occurrence(- session: AsyncSession, test_user: User+ session: AsyncSession, test_user, test_workspace: User):"""end_date == an occurrence date — that occurrence should still count."""account = await _make_manual_account(session, test_user.id, "CF EndDateExactDay")@@ -1831,7 +1831,7 @@ async def test_cash_flow_end_date_at_exact_occurrence(end_date=today + timedelta(days=14),)- report = await get_cash_flow_report(session, test_user.id, months=2, interval="daily")+ report = await get_cash_flow_report(session, test_workspace.id, test_user.id, months=2, interval="daily")proj_income = next(b for b in report.summary.breakdowns if b.key == "projectedIncome")# 2 occurrences × $10 = $20assert proj_income.value == 20.0@@ -1839,7 +1839,7 @@ async def test_cash_flow_end_date_at_exact_occurrence(@pytest.mark.asyncioasync def test_cash_flow_end_date_in_past_no_contribution(- session: AsyncSession, test_user: User+ session: AsyncSession, test_user, test_workspace: User):"""If end_date is in the past, no occurrences project."""account = await _make_manual_account(session, test_user.id, "CF EndDatePast")@@ -1855,7 +1855,7 @@ async def test_cash_flow_end_date_in_past_no_contribution(end_date=today - timedelta(days=10),)- report = await get_cash_flow_report(session, test_user.id, months=3, interval="daily")+ report = await get_cash_flow_report(session, test_workspace.id, test_user.id, months=3, interval="daily")proj_income = next(b for b in report.summary.breakdowns if b.key == "projectedIncome")assert proj_income.value == 0.0@@ -1863,7 +1863,7 @@ async def test_cash_flow_end_date_in_past_no_contribution(@pytest.mark.asyncioasync def test_cash_flow_overdraft_crunch_point_goes_negative(- session: AsyncSession, test_user: User+ session: AsyncSession, test_user, test_workspace: User):"""Cash crunch / overdraft: when projected outflows exceed inflows + start,the running balance must go negative (not be clamped at 0)."""@@ -1881,7 +1881,7 @@ async def test_cash_flow_overdraft_crunch_point_goes_negative(day_of_month=1, next_occurrence=nxt,)- report = await get_cash_flow_report(session, test_user.id, months=3, interval="daily")+ report = await get_cash_flow_report(session, test_workspace.id, test_user.id, months=3, interval="daily")negative_points = [p for p in report.trend if p.value < 0]assert len(negative_points) > 0, "Trend never dips below zero — clamped?"@@ -1892,7 +1892,7 @@ async def test_cash_flow_overdraft_crunch_point_goes_negative(@pytest.mark.asyncioasync def test_cash_flow_paycheck_timing_dip(- session: AsyncSession, test_user: User+ session: AsyncSession, test_user, test_workspace: User):"""Classic paycheck-timing dip: rent on day 5, salary on day 15. End ofmonth is positive, but mid-month should drop below the starting balance@@ -1924,7 +1924,7 @@ async def test_cash_flow_paycheck_timing_dip(description="Salary",)- report = await get_cash_flow_report(session, test_user.id, months=2, interval="daily")+ report = await get_cash_flow_report(session, test_workspace.id, test_user.id, months=2, interval="daily")# Fetch balance on rent day (after rent hit) and salary day (after salary hit)rent_pt = next(p for p in report.trend if p.date == rent_day.isoformat())@@ -1941,7 +1941,7 @@ async def test_cash_flow_paycheck_timing_dip(@pytest.mark.asyncioasync def test_cash_flow_large_one_off_purchase(- session: AsyncSession, test_user: User+ session: AsyncSession, test_user, test_workspace: User):"""User wants to plan a single large purchase (e.g., new laptop on day +20).The chart must show a single dip on that exact day and recover for the@@ -1957,7 +1957,7 @@ async def test_cash_flow_large_one_off_purchase(session, test_user.id, account.id, 1800, "debit", purchase_day,)- report = await get_cash_flow_report(session, test_user.id, months=2, interval="daily")+ report = await get_cash_flow_report(session, test_workspace.id, test_user.id, months=2, interval="daily")# Day before purchase: full starting balancepre_pt = next(p for p in report.trend if p.date == (purchase_day - timedelta(days=1)).isoformat())@@ -1973,7 +1973,7 @@ async def test_cash_flow_large_one_off_purchase(@pytest.mark.asyncioasync def test_cash_flow_multiple_recurrings_same_day(- session: AsyncSession, test_user: User+ session: AsyncSession, test_user, test_workspace: User):"""Multiple bills that hit the same day must be summed into one outflowbucket on that day, not represented as separate days."""@@ -1993,7 +1993,7 @@ async def test_cash_flow_multiple_recurrings_same_day(day_of_month=1, next_occurrence=nxt, description=desc,)- report = await get_cash_flow_report(session, test_user.id, months=1, interval="daily")+ report = await get_cash_flow_report(session, test_workspace.id, test_user.id, months=1, interval="daily")bill_day = next(p for p in report.trend if p.date == nxt.isoformat())# All three bills stacked on the same day = 800 + 120 + 60 = 980@@ -2007,7 +2007,7 @@ async def test_cash_flow_multiple_recurrings_same_day(@pytest.mark.asyncio-async def test_cash_flow_yearly_recurring(session: AsyncSession, test_user: User):+async def test_cash_flow_yearly_recurring(session: AsyncSession, test_user, test_workspace: User):"""Yearly recurring (e.g., annual car insurance): expansion in a 12-monthwindow should yield exactly one occurrence."""account = await _make_manual_account(session, test_user.id, "CF Yearly")@@ -2024,19 +2024,19 @@ async def test_cash_flow_yearly_recurring(session: AsyncSession, test_user: Userday_of_month=nxt.day, next_occurrence=nxt,)- rep_12 = await get_cash_flow_report(session, test_user.id, months=12, interval="daily")+ rep_12 = await get_cash_flow_report(session, test_workspace.id, test_user.id, months=12, interval="daily")proj_exp_12 = next(b for b in rep_12.summary.breakdowns if b.key == "projectedExpenses")assert proj_exp_12.value == 1200.0 # exactly one occurrence in 12 months# In a 1-month window: also 1 (since nxt is +30 days)- rep_1 = await get_cash_flow_report(session, test_user.id, months=2, interval="daily")+ rep_1 = await get_cash_flow_report(session, test_workspace.id, test_user.id, months=2, interval="daily")proj_exp_1 = next(b for b in rep_1.summary.breakdowns if b.key == "projectedExpenses")assert proj_exp_1.value == 1200.0@pytest.mark.asyncioasync def test_cash_flow_recurring_starting_in_future(- session: AsyncSession, test_user: User+ session: AsyncSession, test_user, test_workspace: User):"""A recurring whose start_date is in the future (e.g., a new subscriptionstarting next month) must be projected from its start_date forward."""@@ -2055,7 +2055,7 @@ async def test_cash_flow_recurring_starting_in_future(description="Future subscription",)- report = await get_cash_flow_report(session, test_user.id, months=4, interval="daily")+ report = await get_cash_flow_report(session, test_workspace.id, test_user.id, months=4, interval="daily")proj_exp = next(b for b in report.summary.breakdowns if b.key == "projectedExpenses")# The subscription starts 1-2 months out; at month=4 we expect ~2-3 hits.@@ -2067,7 +2067,7 @@ async def test_cash_flow_recurring_starting_in_future(@pytest.mark.asyncioasync def test_cash_flow_running_balance_arithmetic(- session: AsyncSession, test_user: User+ session: AsyncSession, test_user, test_workspace: User):"""Strict arithmetic: balance on day N == starting + sum(flows up to day N).Anchors the math so refactors can't silently break the cumulative sum."""@@ -2088,7 +2088,7 @@ async def test_cash_flow_running_balance_arithmetic(for d, amt, typ in flows:await _add_txn(session, test_user.id, account.id, amt, typ, d)- report = await get_cash_flow_report(session, test_user.id, months=1, interval="daily")+ report = await get_cash_flow_report(session, test_workspace.id, test_user.id, months=1, interval="daily")by_date = {p.date: p for p in report.trend}# Reconstruct expected running balance day by day.@@ -2113,7 +2113,7 @@ async def test_cash_flow_running_balance_arithmetic(@pytest.mark.asyncioasync def test_cash_flow_baseline_off_uses_recurring(- session: AsyncSession, test_user: User+ session: AsyncSession, test_user, test_workspace: User):"""baseline=False is the legacy behavior: only recurring rules project."""account = await _make_manual_account(session, test_user.id, "CF Baseline Off")@@ -2136,7 +2136,7 @@ async def test_cash_flow_baseline_off_uses_recurring()report = await get_cash_flow_report(- session, test_user.id, months=3, interval="daily", baseline=False,+ session, test_workspace.id, test_user.id, months=3, interval="daily", baseline=False,)assert report.meta.baseline_active is False@@ -2150,7 +2150,7 @@ async def test_cash_flow_baseline_off_uses_recurring(@pytest.mark.asyncioasync def test_cash_flow_baseline_on_replaces_recurring_with_mean(- session: AsyncSession, test_user: User+ session: AsyncSession, test_user, test_workspace: User):"""baseline=True ignores recurring rules and projects from historical mean.@@ -2177,7 +2177,7 @@ async def test_cash_flow_baseline_on_replaces_recurring_with_mean()report = await get_cash_flow_report(- session, test_user.id, months=3, interval="daily", baseline=True,+ session, test_workspace.id, test_user.id, months=3, interval="daily", baseline=True,)assert report.meta.baseline_active is True@@ -2195,7 +2195,7 @@ async def test_cash_flow_baseline_on_replaces_recurring_with_mean(@pytest.mark.asyncioasync def test_cash_flow_baseline_lookback_caps_at_twelve_months(- session: AsyncSession, test_user: User+ session: AsyncSession, test_user, test_workspace: User):"""User with >12 months of history sees lookback capped at 365 days."""account = await _make_manual_account(session, test_user.id, "CF Baseline Cap")@@ -2215,7 +2215,7 @@ async def test_cash_flow_baseline_lookback_caps_at_twelve_months()report = await get_cash_flow_report(- session, test_user.id, months=3, interval="daily", baseline=True,+ session, test_workspace.id, test_user.id, months=3, interval="daily", baseline=True,)# Window is bounded by `today - 365 days`, not by the 540-days-ago tx.@@ -2226,7 +2226,7 @@ async def test_cash_flow_baseline_lookback_caps_at_twelve_months(@pytest.mark.asyncioasync def test_cash_flow_baseline_lookback_adapts_to_short_history(- session: AsyncSession, test_user: User+ session: AsyncSession, test_user, test_workspace: User):"""User with only N days of history sees lookback shrink to N."""account = await _make_manual_account(session, test_user.id, "CF Baseline Short")@@ -2243,7 +2243,7 @@ async def test_cash_flow_baseline_lookback_adapts_to_short_history()report = await get_cash_flow_report(- session, test_user.id, months=3, interval="daily", baseline=True,+ session, test_workspace.id, test_user.id, months=3, interval="daily", baseline=True,)# Earliest tx is 7 days ago, so lookback is 7 days.@@ -2256,7 +2256,7 @@ async def test_cash_flow_baseline_lookback_adapts_to_short_history(@pytest.mark.asyncioasync def test_cash_flow_baseline_no_history_returns_empty_projection(- session: AsyncSession, test_user: User+ session: AsyncSession, test_user, test_workspace: User):"""User with no qualifying transactions → baseline contributes zero.@@ -2269,7 +2269,7 @@ async def test_cash_flow_baseline_no_history_returns_empty_projection()report = await get_cash_flow_report(- session, test_user.id, months=3, interval="daily", baseline=True,+ session, test_workspace.id, test_user.id, months=3, interval="daily", baseline=True,)assert report.meta.baseline_active is True@@ -2284,7 +2284,7 @@ async def test_cash_flow_baseline_no_history_returns_empty_projection(@pytest.mark.asyncioasync def test_cash_flow_meta_carries_forecast_start_date(- session: AsyncSession, test_user: User+ session: AsyncSession, test_user, test_workspace: User):"""forecast_start_date in meta lets the UI split solid vs dashed at today."""account = await _make_manual_account(session, test_user.id, "CF Forecast Start")@@ -2294,7 +2294,7 @@ async def test_cash_flow_meta_carries_forecast_start_date()report = await get_cash_flow_report(- session, test_user.id, months=3, interval="daily",+ session, test_workspace.id, test_user.id, months=3, interval="daily",)assert report.meta.forecast_start_date == date.today().isoformat()@@ -2302,7 +2302,7 @@ async def test_cash_flow_meta_carries_forecast_start_date(@pytest.mark.asyncioasync def test_cash_flow_chart_includes_past_history(- session: AsyncSession, test_user: User+ session: AsyncSession, test_user, test_workspace: User):"""Trend starts ~1 month before today so the today-marker has context."""account = await _make_manual_account(session, test_user.id, "CF Past")@@ -2312,7 +2312,7 @@ async def test_cash_flow_chart_includes_past_history()report = await get_cash_flow_report(- session, test_user.id, months=3, interval="daily",+ session, test_workspace.id, test_user.id, months=3, interval="daily",)# First trend point should be ~30 days before today.diff --git a/backend/tests/test_rule_service.py b/backend/tests/test_rule_service.pyindex aa60622d..81d69ef1 100644--- a/backend/tests/test_rule_service.py+++ b/backend/tests/test_rule_service.py@@ -31,7 +31,7 @@ from app.services.category_service import create_default_categories@pytest.mark.asyncio-async def test_create_rule(session: AsyncSession, test_user, test_categories):+async def test_create_rule(session: AsyncSession, test_user, test_workspace, test_categories):data = RuleCreate(name="My Rule",conditions_op="or",@@ -39,7 +39,7 @@ async def test_create_rule(session: AsyncSession, test_user, test_categories):actions=[RuleAction(op="set_category", value=str(test_categories[1].id))],priority=10,)- rule = await create_rule(session, test_user.id, data)+ rule = await create_rule(session, test_workspace.id, test_user.id, data)assert rule.id is not Noneassert rule.name == "My Rule"@@ -50,11 +50,11 @@ async def test_create_rule(session: AsyncSession, test_user, test_categories):@pytest.mark.asyncio-async def test_get_rules(session: AsyncSession, test_user, test_categories):+async def test_get_rules(session: AsyncSession, test_user, test_workspace, test_categories):for name in ["Rule A", "Rule B"]:await create_rule(session,- test_user.id,+ test_workspace.id, test_user.id,RuleCreate(name=name,conditions=[RuleCondition(field="description", op="contains", value="X")],@@ -62,7 +62,7 @@ async def test_get_rules(session: AsyncSession, test_user, test_categories):),)- rules = await get_rules(session, test_user.id)+ rules = await get_rules(session, test_workspace.id)assert len(rules) >= 2names = {r.name for r in rules}assert "Rule A" in names@@ -70,32 +70,32 @@ async def test_get_rules(session: AsyncSession, test_user, test_categories):@pytest.mark.asyncio-async def test_get_rule_by_id(session: AsyncSession, test_user, test_categories):+async def test_get_rule_by_id(session: AsyncSession, test_user, test_workspace, test_categories):created = await create_rule(session,- test_user.id,+ test_workspace.id, test_user.id,RuleCreate(name="Lookup Rule",conditions=[RuleCondition(field="description", op="contains", value="X")],actions=[RuleAction(op="set_category", value=str(test_categories[0].id))],),)- fetched = await get_rule(session, created.id, test_user.id)+ fetched = await get_rule(session, created.id, test_workspace.id)assert fetched is not Noneassert fetched.id == created.id@pytest.mark.asyncio-async def test_get_rule_not_found(session: AsyncSession, test_user):- result = await get_rule(session, uuid.uuid4(), test_user.id)+async def test_get_rule_not_found(session: AsyncSession, test_user, test_workspace):+ result = await get_rule(session, uuid.uuid4(), test_workspace.id)assert result is None@pytest.mark.asyncio-async def test_update_rule(session: AsyncSession, test_user, test_categories):+async def test_update_rule(session: AsyncSession, test_user, test_workspace, test_categories):rule = await create_rule(session,- test_user.id,+ test_workspace.id, test_user.id,RuleCreate(name="Original",conditions=[RuleCondition(field="description", op="contains", value="OLD")],@@ -106,7 +106,7 @@ async def test_update_rule(session: AsyncSession, test_user, test_categories):updated = await update_rule(session,rule.id,- test_user.id,+ test_workspace.id,RuleUpdate(name="Updated", priority=20),)assert updated is not None@@ -115,34 +115,34 @@ async def test_update_rule(session: AsyncSession, test_user, test_categories):@pytest.mark.asyncio-async def test_update_rule_not_found(session: AsyncSession, test_user):+async def test_update_rule_not_found(session: AsyncSession, test_user, test_workspace):result = await update_rule(session,uuid.uuid4(),- test_user.id,+ test_workspace.id,RuleUpdate(name="Nope"),)assert result is None@pytest.mark.asyncio-async def test_delete_rule(session: AsyncSession, test_user, test_categories):+async def test_delete_rule(session: AsyncSession, test_user, test_workspace, test_categories):rule = await create_rule(session,- test_user.id,+ test_workspace.id, test_user.id,RuleCreate(name="ToDelete",conditions=[RuleCondition(field="description", op="contains", value="X")],actions=[RuleAction(op="set_category", value=str(test_categories[0].id))],),)- assert await delete_rule(session, rule.id, test_user.id) is True- assert await get_rule(session, rule.id, test_user.id) is None+ assert await delete_rule(session, rule.id, test_workspace.id) is True+ assert await get_rule(session, rule.id, test_workspace.id) is None@pytest.mark.asyncio-async def test_delete_rule_not_found(session: AsyncSession, test_user):- assert await delete_rule(session, uuid.uuid4(), test_user.id) is False+async def test_delete_rule_not_found(session: AsyncSession, test_user, test_workspace):+ assert await delete_rule(session, uuid.uuid4(), test_workspace.id) is False# ---------------------------------------------------------------------------@@ -151,23 +151,23 @@ async def test_delete_rule_not_found(session: AsyncSession, test_user):@pytest.mark.asyncio-async def test_create_duplicate_rule_raises(session: AsyncSession, test_user, test_categories):+async def test_create_duplicate_rule_raises(session: AsyncSession, test_user, test_workspace, test_categories):data = RuleCreate(name="Unique Name",conditions=[RuleCondition(field="description", op="contains", value="X")],actions=[RuleAction(op="set_category", value=str(test_categories[0].id))],)- await create_rule(session, test_user.id, data)+ await create_rule(session, test_workspace.id, test_user.id, data)with pytest.raises(DuplicateRuleError):- await create_rule(session, test_user.id, data)+ await create_rule(session, test_workspace.id, test_user.id, data)@pytest.mark.asyncio-async def test_update_rule_duplicate_name_raises(session: AsyncSession, test_user, test_categories):+async def test_update_rule_duplicate_name_raises(session: AsyncSession, test_user, test_workspace, test_categories):rule_a = await create_rule(session,- test_user.id,+ test_workspace.id, test_user.id,RuleCreate(name="Name A",conditions=[RuleCondition(field="description", op="contains", value="X")],@@ -176,7 +176,7 @@ async def test_update_rule_duplicate_name_raises(session: AsyncSession, test_use)await create_rule(session,- test_user.id,+ test_workspace.id, test_user.id,RuleCreate(name="Name B",conditions=[RuleCondition(field="description", op="contains", value="Y")],@@ -188,7 +188,7 @@ async def test_update_rule_duplicate_name_raises(session: AsyncSession, test_useawait update_rule(session,rule_a.id,- test_user.id,+ test_workspace.id,RuleUpdate(name="Name B"),)@@ -199,11 +199,11 @@ async def test_update_rule_duplicate_name_raises(session: AsyncSession, test_use@pytest.mark.asyncio-async def test_apply_rules_to_transaction(session: AsyncSession, test_user, test_categories):+async def test_apply_rules_to_transaction(session: AsyncSession, test_user, test_workspace, test_categories):# Create a rule matching UBERawait create_rule(session,- test_user.id,+ test_workspace.id, test_user.id,RuleCreate(name="UBER Rule",conditions_op="or",@@ -244,10 +244,10 @@ async def test_apply_rules_to_transaction(session: AsyncSession, test_user, test@pytest.mark.asyncio-async def test_apply_rules_no_match(session: AsyncSession, test_user, test_categories):+async def test_apply_rules_no_match(session: AsyncSession, test_user, test_workspace, test_categories):await create_rule(session,- test_user.id,+ test_workspace.id, test_user.id,RuleCreate(name="IFOOD Only",conditions_op="or",@@ -291,7 +291,7 @@ async def test_apply_rules_no_match(session: AsyncSession, test_user, test_categ@pytest.mark.asyncio-async def test_apply_all_rules(session: AsyncSession, test_user, test_categories):+async def test_apply_all_rules(session: AsyncSession, test_user, test_workspace, test_categories):account = Account(id=uuid.uuid4(),user_id=test_user.id,@@ -332,7 +332,7 @@ async def test_apply_all_rules(session: AsyncSession, test_user, test_categories# Create rulesawait create_rule(session,- test_user.id,+ test_workspace.id, test_user.id,RuleCreate(name="UBER apply-all",conditions_op="or",@@ -343,7 +343,7 @@ async def test_apply_all_rules(session: AsyncSession, test_user, test_categories)await create_rule(session,- test_user.id,+ test_workspace.id, test_user.id,RuleCreate(name="IFOOD apply-all",conditions_op="or",@@ -353,7 +353,7 @@ async def test_apply_all_rules(session: AsyncSession, test_user, test_categories),)- count = await apply_all_rules(session, test_user.id)+ count = await apply_all_rules(session, test_workspace.id)assert count >= 2await session.refresh(txn1)@@ -364,7 +364,7 @@ async def test_apply_all_rules(session: AsyncSession, test_user, test_categories@pytest.mark.asyncioasync def test_apply_all_rules_preserves_manual_categories(- session: AsyncSession, test_user, test_categories+ session: AsyncSession, test_user, test_workspace, test_categories):"""Manually categorized transactions that don't match any rule must keep their category."""account = Account(@@ -425,7 +425,7 @@ async def test_apply_all_rules_preserves_manual_categories(# Only one rule: matches UBERawait create_rule(session,- test_user.id,+ test_workspace.id, test_user.id,RuleCreate(name="UBER preserve-test",conditions_op="or",@@ -435,7 +435,7 @@ async def test_apply_all_rules_preserves_manual_categories(),)- count = await apply_all_rules(session, test_user.id)+ count = await apply_all_rules(session, test_workspace.id)await session.refresh(txn_manual)await session.refresh(txn_rule)@@ -461,7 +461,7 @@ async def test_apply_all_rules_preserves_manual_categories(@pytest.mark.asyncio-async def test_create_default_rules(session: AsyncSession, test_user):+async def test_create_default_rules(session: AsyncSession, test_user, test_workspace):# Need default categories first so rule templates can resolveawait create_default_categories(session, test_user.id, lang="pt-BR")@@ -474,7 +474,7 @@ async def test_create_default_rules(session: AsyncSession, test_user):@pytest.mark.asyncio-async def test_install_rule_pack_br(session: AsyncSession, test_user):+async def test_install_rule_pack_br(session: AsyncSession, test_user, test_workspace):await create_default_categories(session, test_user.id, lang="pt-BR")result = await install_rule_pack(session, test_user.id, "BR", lang="pt-BR")@@ -486,7 +486,7 @@ async def test_install_rule_pack_br(session: AsyncSession, test_user):@pytest.mark.asyncio-async def test_install_rule_pack_skips_duplicates(session: AsyncSession, test_user):+async def test_install_rule_pack_skips_duplicates(session: AsyncSession, test_user, test_workspace):await create_default_categories(session, test_user.id, lang="pt-BR")first = await install_rule_pack(session, test_user.id, "BR", lang="pt-BR")@@ -500,7 +500,7 @@ async def test_install_rule_pack_skips_duplicates(session: AsyncSession, test_us@pytest.mark.asyncio-async def test_install_rule_pack_works_across_languages(session: AsyncSession, test_user):+async def test_install_rule_pack_works_across_languages(session: AsyncSession, test_user, test_workspace):# Regression for #154: user registers in English, switches UI to pt-BR,# then installs the BR pack. Categories ("Transport") and template# language ("pt-BR" → "Transporte") would mismatch — install should@@ -517,7 +517,7 @@ async def test_install_rule_pack_works_across_languages(session: AsyncSession, t@pytest.mark.asyncioasync def test_install_rule_pack_reports_unresolved_when_categories_missing(- session: AsyncSession, test_user+ session: AsyncSession, test_user, test_workspace):# User in a degenerate state with no default categories — every pack# rule's set_category target is missing, so the install can't actually@@ -532,7 +532,7 @@ async def test_install_rule_pack_reports_unresolved_when_categories_missing(@pytest.mark.asyncioasync def test_install_rule_pack_creates_missing_categories_when_opted_in(- session: AsyncSession, test_user+ session: AsyncSession, test_user, test_workspace):# Same degenerate user, but they tick the "create missing categories"# checkbox in the modal. Pack must seed the categories it needs and@@ -551,14 +551,14 @@ async def test_install_rule_pack_creates_missing_categories_when_opted_in(@pytest.mark.asyncio-async def test_install_rule_pack_unknown_returns_empty(session: AsyncSession, test_user):+async def test_install_rule_pack_unknown_returns_empty(session: AsyncSession, test_user, test_workspace):result = await install_rule_pack(session, test_user.id, "ZZ")assert result.rules == []assert result.unresolved == 0@pytest.mark.asyncio-async def test_get_installed_packs(session: AsyncSession, test_user):+async def test_get_installed_packs(session: AsyncSession, test_user, test_workspace):await create_default_categories(session, test_user.id, lang="pt-BR")packs_before = await get_installed_packs(session, test_user.id)diff --git a/backend/tests/test_search_api.py b/backend/tests/test_search_api.pyindex ebe8d8fc..56d40a9b 100644--- a/backend/tests/test_search_api.py+++ b/backend/tests/test_search_api.py@@ -174,10 +174,28 @@ async def test_search_respects_user_scope(client: AsyncClient, auth_headers: dict, session: AsyncSession, test_user: User) -> None:# Create an account owned by a different user — should NOT appear in results.- other_user_id = uuid.uuid4()+ import bcrypt as _bcrypt+ from app.services.workspace_service import create_personal_workspace_for_user++ hashed = _bcrypt.hashpw(b"otherpass", _bcrypt.gensalt()).decode()+ other_user = User(+ id=uuid.uuid4(),+ email="[email protected]",+ hashed_password=hashed,+ is_active=True,+ is_superuser=False,+ is_verified=True,+ preferences={"language": "en", "currency_display": "USD"},+ )+ session.add(other_user)+ await session.flush()+ other_ws = await create_personal_workspace_for_user(session, other_user)+ await session.commit()+other_account = Account(id=uuid.uuid4(),- user_id=other_user_id,+ user_id=other_user.id,+ workspace_id=other_ws.id,name="Other User Secret Account",type="checking",balance=Decimal("0"),diff --git a/backend/tests/test_settlement_service.py b/backend/tests/test_settlement_service.pyindex ea2b81cb..91282135 100644--- a/backend/tests/test_settlement_service.py+++ b/backend/tests/test_settlement_service.py@@ -14,23 +14,23 @@ from app.schemas.group_settlement import (GroupSettlementCreate,GroupSettlementUpdate,)-from app.services import group_service, settlement_service+from app.services import group_service, settlement_service, workspace_service-async def _setup_group(session, user_id):+async def _setup_group(session, user_id, workspace_id):group = await group_service.create_group(- session, user_id, GroupCreate(name=f"S-{uuid.uuid4().hex[:6]}")+ session, workspace_id, user_id, GroupCreate(name=f"S-{uuid.uuid4().hex[:6]}"))a = await group_service.create_member(- session, group.id, user_id, GroupMemberCreate(name="Alice")+ session, group.id, workspace_id, GroupMemberCreate(name="Alice"))b = await group_service.create_member(- session, group.id, user_id, GroupMemberCreate(name="Bob")+ session, group.id, workspace_id, GroupMemberCreate(name="Bob"))return group, a, b-async def _make_user(session, email):+async def _make_user_with_workspace(session, email):hashed = _bcrypt.hashpw(b"x", _bcrypt.gensalt()).decode()user = User(id=uuid.uuid4(),@@ -43,7 +43,10 @@ async def _make_user(session, email):)session.add(user)await session.flush()- return user+ workspace = await workspace_service.create_personal_workspace_for_user(+ session, user, commit=True+ )+ return user, workspaceasync def _make_account(session, user_id, account_type="checking"):@@ -61,11 +64,14 @@ async def _make_account(session, user_id, account_type="checking"):@pytest.mark.asyncio-async def test_create_settlement_happy_path(session: AsyncSession, test_user):- group, a, b = await _setup_group(session, test_user.id)+async def test_create_settlement_happy_path(+ session: AsyncSession, test_user, test_workspace+):+ group, a, b = await _setup_group(session, test_user.id, test_workspace.id)s = await settlement_service.create_settlement(session,group.id,+ test_workspace.id,test_user.id,GroupSettlementCreate(from_member_id=a.id,@@ -82,15 +88,16 @@ async def test_create_settlement_happy_path(session: AsyncSession, test_user):@pytest.mark.asyncioasync def test_settlement_members_must_belong_to_group(- session: AsyncSession, test_user+ session: AsyncSession, test_user, test_workspace):- group, a, _b = await _setup_group(session, test_user.id)- other_group, _x, y = await _setup_group(session, test_user.id)+ group, a, _b = await _setup_group(session, test_user.id, test_workspace.id)+ other_group, _x, y = await _setup_group(session, test_user.id, test_workspace.id)with pytest.raises(ValueError, match="must belong to the group"):await settlement_service.create_settlement(session,group.id,+ test_workspace.id,test_user.id,GroupSettlementCreate(from_member_id=a.id,@@ -104,9 +111,9 @@ async def test_settlement_members_must_belong_to_group(@pytest.mark.asyncioasync def test_settlement_from_to_must_differ_at_creation(- session: AsyncSession, test_user+ session: AsyncSession, test_user, test_workspace):- group, a, _b = await _setup_group(session, test_user.id)+ group, a, _b = await _setup_group(session, test_user.id, test_workspace.id)# Pydantic-level validation rejects from == to before service runs.with pytest.raises(ValueError, match="must differ"):GroupSettlementCreate(@@ -119,11 +126,14 @@ async def test_settlement_from_to_must_differ_at_creation(@pytest.mark.asyncio-async def test_settlement_update_keeps_invariants(session: AsyncSession, test_user):- group, a, b = await _setup_group(session, test_user.id)+async def test_settlement_update_keeps_invariants(+ session: AsyncSession, test_user, test_workspace+):+ group, a, b = await _setup_group(session, test_user.id, test_workspace.id)s = await settlement_service.create_settlement(session,group.id,+ test_workspace.id,test_user.id,GroupSettlementCreate(from_member_id=a.id,@@ -138,6 +148,7 @@ async def test_settlement_update_keeps_invariants(session: AsyncSession, test_ussession,group.id,s.id,+ test_workspace.id,test_user.id,GroupSettlementUpdate(amount=Decimal("12.00"), notes="adjusted"),)@@ -150,19 +161,27 @@ async def test_settlement_update_keeps_invariants(session: AsyncSession, test_ussession,group.id,s.id,+ test_workspace.id,test_user.id,GroupSettlementUpdate(to_member_id=a.id),)@pytest.mark.asyncio-async def test_settlement_owner_isolation(session: AsyncSession, test_user):- group, a, b = await _setup_group(session, test_user.id)- other_user = uuid.uuid4()+async def test_settlement_owner_isolation(+ session: AsyncSession, test_user, test_workspace+):+ group, a, b = await _setup_group(session, test_user.id, test_workspace.id)+ # A different workspace with a different user — neither can see the+ # group through their own scope.+ other_user, other_ws = await _make_user_with_workspace(+ session, "[email protected]"+ )result = await settlement_service.create_settlement(session,group.id,- other_user,+ other_ws.id,+ other_user.id,GroupSettlementCreate(from_member_id=a.id,to_member_id=b.id,@@ -184,28 +203,34 @@ async def test_settlement_owner_isolation(session: AsyncSession, test_user):@pytest.mark.asyncioasync def test_receiver_credit_created_when_to_member_is_linked_with_account(- session: AsyncSession, test_user+ session: AsyncSession, test_user, test_workspace):- receiver = await _make_user(session, "[email protected]")+ receiver, _receiver_ws = await _make_user_with_workspace(+ session, "[email protected]"+ )receiver_account = await _make_account(session, receiver.id)payer_account = await _make_account(session, test_user.id)group = await group_service.create_group(- session, test_user.id, GroupCreate(name="LinkedReceiver")+ session, test_workspace.id, test_user.id, GroupCreate(name="LinkedReceiver"))me = await group_service.create_member(- session, group.id, test_user.id, GroupMemberCreate(name="Me", is_self=True)+ session,+ group.id,+ test_workspace.id,+ GroupMemberCreate(name="Me", is_self=True),)bob = await group_service.create_member(session,group.id,- test_user.id,+ test_workspace.id,GroupMemberCreate(name="Bob", linked_user_id=receiver.id),)s = await settlement_service.create_settlement(session,group.id,+ test_workspace.id,test_user.id,GroupSettlementCreate(from_member_id=me.id,@@ -231,24 +256,28 @@ async def test_receiver_credit_created_when_to_member_is_linked_with_account(@pytest.mark.asyncioasync def test_receiver_credit_skipped_when_to_member_is_shadow(- session: AsyncSession, test_user+ session: AsyncSession, test_user, test_workspace):"""Shadow member (no linked_user_id, not is_self) — there's no realuser on the receiving side, so no credit transaction is created."""payer_account = await _make_account(session, test_user.id)group = await group_service.create_group(- session, test_user.id, GroupCreate(name="ShadowReceiver")+ session, test_workspace.id, test_user.id, GroupCreate(name="ShadowReceiver"))me = await group_service.create_member(- session, group.id, test_user.id, GroupMemberCreate(name="Me", is_self=True)+ session,+ group.id,+ test_workspace.id,+ GroupMemberCreate(name="Me", is_self=True),)shadow = await group_service.create_member(- session, group.id, test_user.id, GroupMemberCreate(name="Shadow")+ session, group.id, test_workspace.id, GroupMemberCreate(name="Shadow"))s = await settlement_service.create_settlement(session,group.id,+ test_workspace.id,test_user.id,GroupSettlementCreate(from_member_id=me.id,@@ -265,31 +294,37 @@ async def test_receiver_credit_skipped_when_to_member_is_shadow(@pytest.mark.asyncioasync def test_receiver_credit_skipped_when_linked_user_has_no_cash_account(- session: AsyncSession, test_user+ session: AsyncSession, test_user, test_workspace):"""Linked receiver, but their only account is a credit card (notchecking/savings). The mirror credit can't be placed and is silentlyskipped — settlement is still recorded."""- receiver = await _make_user(session, "[email protected]")+ receiver, _receiver_ws = await _make_user_with_workspace(+ session, "[email protected]"+ )await _make_account(session, receiver.id, account_type="credit_card")payer_account = await _make_account(session, test_user.id)group = await group_service.create_group(- session, test_user.id, GroupCreate(name="CCOnly")+ session, test_workspace.id, test_user.id, GroupCreate(name="CCOnly"))me = await group_service.create_member(- session, group.id, test_user.id, GroupMemberCreate(name="Me", is_self=True)+ session,+ group.id,+ test_workspace.id,+ GroupMemberCreate(name="Me", is_self=True),)bob = await group_service.create_member(session,group.id,- test_user.id,+ test_workspace.id,GroupMemberCreate(name="Bob", linked_user_id=receiver.id),)s = await settlement_service.create_settlement(session,group.id,+ test_workspace.id,test_user.id,GroupSettlementCreate(from_member_id=me.id,@@ -306,20 +341,23 @@ async def test_receiver_credit_skipped_when_linked_user_has_no_cash_account(@pytest.mark.asyncioasync def test_receiver_credit_lands_on_owner_when_self_member_unlinked(- session: AsyncSession, test_user+ session: AsyncSession, test_user, test_workspace):"""When the to_member is the owner's self-member with nolinked_user_id, the service falls back to group.user_id — thecredit lands on the owner's checking account."""owner_account = await _make_account(session, test_user.id)group = await group_service.create_group(- session, test_user.id, GroupCreate(name="SelfFallback")+ session, test_workspace.id, test_user.id, GroupCreate(name="SelfFallback"))owner_self = await group_service.create_member(- session, group.id, test_user.id, GroupMemberCreate(name="Me", is_self=True)+ session,+ group.id,+ test_workspace.id,+ GroupMemberCreate(name="Me", is_self=True),)friend = await group_service.create_member(- session, group.id, test_user.id, GroupMemberCreate(name="Friend")+ session, group.id, test_workspace.id, GroupMemberCreate(name="Friend"))# Friend pays the owner back. Caller is the owner (allowed to record@@ -328,6 +366,7 @@ async def test_receiver_credit_lands_on_owner_when_self_member_unlinked(s = await settlement_service.create_settlement(session,group.id,+ test_workspace.id,test_user.id,GroupSettlementCreate(from_member_id=friend.id,diff --git a/backend/tests/test_share_only_model.py b/backend/tests/test_share_only_model.pyindex 8bf9a62a..f2054409 100644--- a/backend/tests/test_share_only_model.py+++ b/backend/tests/test_share_only_model.py@@ -93,10 +93,15 @@ async def _make_tx(async def _setup_group(- session: AsyncSession, user, *member_names: str, default_currency: str = "USD"+ session: AsyncSession,+ user,+ workspace_id,+ *member_names: str,+ default_currency: str = "USD",):group = await group_service.create_group(session,+ workspace_id,user.id,GroupCreate(name=f"G-{uuid.uuid4().hex[:6]}", default_currency=default_currency),)@@ -105,7 +110,7 @@ async def _setup_group(m = await group_service.create_member(session,group.id,- user.id,+ workspace_id,GroupMemberCreate(name=name, is_self=(i == 0)),)members.append(m)@@ -135,7 +140,7 @@ def _month_window(d: date) -> tuple[date, date]:@pytest.mark.asyncioasync def test_summary_owner_share_caps_expense(- session: AsyncSession, test_user+ session: AsyncSession, test_user, test_workspace):"""Owner pays $150 split equally with two friends ($50 share). Thedashboard should report a $50 expense, not $150."""@@ -143,7 +148,9 @@ async def test_summary_owner_share_caps_expense(today = date.today()account = await _make_account(session, test_user.id)tx = await _make_tx(session, test_user.id, account.id, "150.00", when=today)- _, members = await _setup_group(session, test_user, "Me", "A", "B")+ _, members = await _setup_group(+ session, test_user, test_workspace.id, "Me", "A", "B"+ )await split_service.replace_splits(session,@@ -157,21 +164,25 @@ async def test_summary_owner_share_caps_expense(await session.commit()summary = await dashboard_service.get_summary(- session, test_user.id, today.replace(day=1)+ session, test_workspace.id, test_user.id, today.replace(day=1))assert summary.monthly_expenses_primary == pytest.approx(50.0, abs=0.01)assert summary.monthly_income_primary == 0.0@pytest.mark.asyncio-async def test_summary_owner_with_zero_share(session: AsyncSession, test_user):+async def test_summary_owner_with_zero_share(+ session: AsyncSession, test_user, test_workspace+):"""Owner fronts a $150 expense entirely for two friends. They eachhave a $75 share; owner has no share. Expense should be $0."""await _force_user_currency(session, test_user, "USD")today = date.today()account = await _make_account(session, test_user.id)tx = await _make_tx(session, test_user.id, account.id, "150.00", when=today)- _, members = await _setup_group(session, test_user, "Me", "A", "B")+ _, members = await _setup_group(+ session, test_user, test_workspace.id, "Me", "A", "B"+ )me, friend_a, friend_b = membersawait split_service.replace_splits(@@ -193,14 +204,14 @@ async def test_summary_owner_with_zero_share(session: AsyncSession, test_user):await session.commit()summary = await dashboard_service.get_summary(- session, test_user.id, today.replace(day=1)+ session, test_workspace.id, test_user.id, today.replace(day=1))assert summary.monthly_expenses_primary == 0.0@pytest.mark.asyncioasync def test_summary_no_split_full_amount_counts(- session: AsyncSession, test_user+ session: AsyncSession, test_user, test_workspace):"""A regular non-split transaction must still count its full amount —the offset only applies when splits exist."""@@ -211,14 +222,14 @@ async def test_summary_no_split_full_amount_counts(await session.commit()summary = await dashboard_service.get_summary(- session, test_user.id, today.replace(day=1)+ session, test_workspace.id, test_user.id, today.replace(day=1))assert summary.monthly_expenses_primary == pytest.approx(80.0, abs=0.01)@pytest.mark.asyncioasync def test_summary_drops_settlement_credits_from_income(- session: AsyncSession, test_user+ session: AsyncSession, test_user, test_workspace):"""Receiver-side settlement credits no longer count as income — theparent share already booked the expense, so the credit would@@ -227,7 +238,9 @@ async def test_summary_drops_settlement_credits_from_income(today = date.today()account = await _make_account(session, test_user.id)tx = await _make_tx(session, test_user.id, account.id, "60.00", when=today)- _, members = await _setup_group(session, test_user, "Me", "Friend")+ _, members = await _setup_group(+ session, test_user, test_workspace.id, "Me", "Friend"+ )me, friend = membersawait split_service.replace_splits(@@ -247,6 +260,7 @@ async def test_summary_drops_settlement_credits_from_income(await settlement_service.create_settlement(session,members[0].group_id,+ test_workspace.id,test_user.id,GroupSettlementCreate(from_member_id=friend.id,@@ -258,7 +272,7 @@ async def test_summary_drops_settlement_credits_from_income()summary = await dashboard_service.get_summary(- session, test_user.id, today.replace(day=1)+ session, test_workspace.id, test_user.id, today.replace(day=1))# Owner's expense = $30 share. No income from the settlement credit.assert summary.monthly_expenses_primary == pytest.approx(30.0, abs=0.01)@@ -267,7 +281,7 @@ async def test_summary_drops_settlement_credits_from_income(@pytest.mark.asyncioasync def test_summary_settlement_debit_excluded_for_payer(- session: AsyncSession, test_user+ session: AsyncSession, test_user, test_workspace):"""Linked-member side: paying back a debt is not an expense — theshare already captured it."""@@ -286,7 +300,7 @@ async def test_summary_settlement_debit_excluded_for_payer(await session.commit()summary = await dashboard_service.get_summary(- session, test_user.id, today.replace(day=1)+ session, test_workspace.id, test_user.id, today.replace(day=1))assert summary.monthly_expenses_primary == 0.0@@ -296,7 +310,7 @@ async def test_summary_settlement_debit_excluded_for_payer(@pytest.mark.asyncioasync def test_spending_by_category_uses_owner_share(- session: AsyncSession, test_user, test_categories+ session: AsyncSession, test_user, test_workspace, test_categories):"""A categorized split contributes only the owner's share to itsbucket. No share → category drops out."""@@ -315,7 +329,9 @@ async def test_spending_by_category_uses_owner_share(description="Brunch",when=today,)- _, members = await _setup_group(session, test_user, "Me", "Friend")+ _, members = await _setup_group(+ session, test_user, test_workspace.id, "Me", "Friend"+ )me, friend = membersawait split_service.replace_splits(session,@@ -332,7 +348,7 @@ async def test_spending_by_category_uses_owner_share(await session.commit()spending = await dashboard_service.get_spending_by_category(- session, test_user.id, today.replace(day=1)+ session, test_workspace.id, test_user.id, today.replace(day=1))food_row = next(s for s in spending if s.category_name == "Alimentação")assert food_row.total == pytest.approx(25.0, abs=0.01)@@ -340,7 +356,7 @@ async def test_spending_by_category_uses_owner_share(@pytest.mark.asyncioasync def test_spending_by_category_drops_zero_share_category(- session: AsyncSession, test_user, test_categories+ session: AsyncSession, test_user, test_workspace, test_categories):"""A split where the owner has no share = category contributes $0and should not appear in the breakdown at all."""@@ -356,7 +372,9 @@ async def test_spending_by_category_drops_zero_share_category(category_id=food.id,when=today,)- _, members = await _setup_group(session, test_user, "Me", "A")+ _, members = await _setup_group(+ session, test_user, test_workspace.id, "Me", "A"+ )me, friend = membersawait split_service.replace_splits(session,@@ -374,7 +392,7 @@ async def test_spending_by_category_drops_zero_share_category(await session.commit()spending = await dashboard_service.get_spending_by_category(- session, test_user.id, today.replace(day=1)+ session, test_workspace.id, test_user.id, today.replace(day=1))assert all(s.category_name != "Alimentação" for s in spending)@@ -384,7 +402,7 @@ async def test_spending_by_category_drops_zero_share_category(@pytest.mark.asyncioasync def test_owner_self_member_recognized_without_link(- session: AsyncSession, test_user+ session: AsyncSession, test_user, test_workspace):"""The owner's GroupMember has is_self=True but linked_user_id=NULL.The offset query must still recognize it as the owner's own share —@@ -395,7 +413,9 @@ async def test_owner_self_member_recognized_without_link(today = date.today()account = await _make_account(session, test_user.id)tx = await _make_tx(session, test_user.id, account.id, "90.00", when=today)- _, members = await _setup_group(session, test_user, "Me", "Friend")+ _, members = await _setup_group(+ session, test_user, test_workspace.id, "Me", "Friend"+ )me, friend = members# Sanity-check the schema invariant the bug exploited.assert me.is_self is True@@ -416,7 +436,7 @@ async def test_owner_self_member_recognized_without_link(await session.commit()summary = await dashboard_service.get_summary(- session, test_user.id, today.replace(day=1)+ session, test_workspace.id, test_user.id, today.replace(day=1))# Owner's $45 share survives; the previous bug would have returned 0.assert summary.monthly_expenses_primary == pytest.approx(45.0, abs=0.01)@@ -443,7 +463,7 @@ async def _seed_eur_rate(session: AsyncSession, when: date) -> None:@pytest.mark.asyncioasync def test_balance_line_includes_fx_converted_amount(- session: AsyncSession, test_user+ session: AsyncSession, test_user, test_workspace):"""A EUR-denominated debt line on a USD-default group must surface`amount_in_default_currency` so the frontend can sum cross-currency@@ -455,7 +475,7 @@ async def test_balance_line_includes_fx_converted_amount(session, test_user.id, account.id, "100.00", currency="EUR", when=today)_, members = await _setup_group(- session, test_user, "Me", "Friend", default_currency="USD"+ session, test_user, test_workspace.id, "Me", "Friend", default_currency="USD")me, friend = members@@ -475,7 +495,7 @@ async def test_balance_line_includes_fx_converted_amount(await session.commit()balances = await balance_service.compute_balances(- session, members[0].group_id, test_user.id+ session, members[0].group_id, test_workspace.id, test_user.id)assert balances is not Noneassert balances["default_currency"] == "USD"@@ -491,14 +511,16 @@ async def test_balance_line_includes_fx_converted_amount(@pytest.mark.asyncioasync def test_balance_line_default_currency_passthrough(- session: AsyncSession, test_user+ session: AsyncSession, test_user, test_workspace):"""Same-currency line: amount_in_default_currency should equal amount(no FX needed). Guards against accidental rounding."""today = date.today()account = await _make_account(session, test_user.id)tx = await _make_tx(session, test_user.id, account.id, "60.00", when=today)- _, members = await _setup_group(session, test_user, "Me", "Friend")+ _, members = await _setup_group(+ session, test_user, test_workspace.id, "Me", "Friend"+ )me, friend = membersawait split_service.replace_splits(session,@@ -516,7 +538,7 @@ async def test_balance_line_default_currency_passthrough(await session.commit()balances = await balance_service.compute_balances(- session, members[0].group_id, test_user.id+ session, members[0].group_id, test_workspace.id, test_user.id)line = balances["lines"][0]assert Decimal(str(line["amount"])) == Decimal(str(line["amount_in_default_currency"]))@@ -526,7 +548,9 @@ async def test_balance_line_default_currency_passthrough(@pytest.mark.asyncio-async def test_owner_split_offset_pnl_helper(session: AsyncSession, test_user):+async def test_owner_split_offset_pnl_helper(+ session: AsyncSession, test_user, test_workspace+):"""The income/expenses report uses Postgres `to_char`, so we can'texercise it under SQLite. Instead pin its underlying helper — thesame one the dashboard uses — directly."""@@ -536,7 +560,9 @@ async def test_owner_split_offset_pnl_helper(session: AsyncSession, test_user):today = date.today()account = await _make_account(session, test_user.id)tx = await _make_tx(session, test_user.id, account.id, "120.00", when=today)- _, members = await _setup_group(session, test_user, "Me", "A", "B", "C")+ _, members = await _setup_group(+ session, test_user, test_workspace.id, "Me", "A", "B", "C"+ )await split_service.replace_splits(session,@@ -561,7 +587,7 @@ async def test_owner_split_offset_pnl_helper(session: AsyncSession, test_user):@pytest.mark.asyncioasync def test_budget_actual_uses_share_only(- session: AsyncSession, test_user, test_categories+ session: AsyncSession, test_user, test_workspace, test_categories):"""Budget vs. actual: a category's "actual" spent should be theuser's share, not the full amount fronted."""@@ -577,7 +603,9 @@ async def test_budget_actual_uses_share_only(category_id=food.id,when=today,)- _, members = await _setup_group(session, test_user, "Me", "A", "B")+ _, members = await _setup_group(+ session, test_user, test_workspace.id, "Me", "A", "B"+ )me, *friends = membersawait split_service.replace_splits(session,@@ -606,7 +634,7 @@ async def test_budget_actual_uses_share_only(await session.commit()rows = await budget_service.get_budget_vs_actual(- session, test_user.id, today.replace(day=1)+ session, test_workspace.id, test_user.id, today.replace(day=1))food_row = next(r for r in rows if r.category_id == food.id)# Owner's share is $20 (60/3); the full $60 would be the bug.diff --git a/backend/tests/test_split_service.py b/backend/tests/test_split_service.pyindex a31c0943..a5b00082 100644--- a/backend/tests/test_split_service.py+++ b/backend/tests/test_split_service.py@@ -49,14 +49,14 @@ async def _make_tx(session: AsyncSession, user_id, account_id, amount: Decimal)return tx-async def _make_group_with_members(session, user_id, names):+async def _make_group_with_members(session, user_id, workspace_id, names):group = await group_service.create_group(- session, user_id, GroupCreate(name=f"G-{uuid.uuid4().hex[:6]}")+ session, workspace_id, user_id, GroupCreate(name=f"G-{uuid.uuid4().hex[:6]}"))members = []for n in names:m = await group_service.create_member(- session, group.id, user_id, GroupMemberCreate(name=n)+ session, group.id, workspace_id, GroupMemberCreate(name=n))members.append(m)return group, members@@ -75,11 +75,13 @@ async def _read_splits(session, transaction_id):@pytest.mark.asyncioasync def test_equal_split_three_ways_assigns_residual_to_last(- session: AsyncSession, test_user+ session: AsyncSession, test_user, test_workspace):account = await _make_account(session, test_user.id)tx = await _make_tx(session, test_user.id, account.id, Decimal("100.00"))- _, members = await _make_group_with_members(session, test_user.id, ["A", "B", "C"])+ _, members = await _make_group_with_members(+ session, test_user.id, test_workspace.id, ["A", "B", "C"]+ )payload = TransactionSplitsInput(share_type="equal",@@ -97,10 +99,14 @@ async def test_equal_split_three_ways_assigns_residual_to_last(@pytest.mark.asyncio-async def test_percent_split_residual_on_last(session: AsyncSession, test_user):+async def test_percent_split_residual_on_last(+ session: AsyncSession, test_user, test_workspace+):account = await _make_account(session, test_user.id)tx = await _make_tx(session, test_user.id, account.id, Decimal("100.00"))- _, members = await _make_group_with_members(session, test_user.id, ["A", "B", "C"])+ _, members = await _make_group_with_members(+ session, test_user.id, test_workspace.id, ["A", "B", "C"]+ )payload = TransactionSplitsInput(share_type="percent",@@ -122,10 +128,14 @@ async def test_percent_split_residual_on_last(session: AsyncSession, test_user):@pytest.mark.asyncio-async def test_percent_must_sum_to_100(session: AsyncSession, test_user):+async def test_percent_must_sum_to_100(+ session: AsyncSession, test_user, test_workspace+):account = await _make_account(session, test_user.id)tx = await _make_tx(session, test_user.id, account.id, Decimal("100.00"))- _, members = await _make_group_with_members(session, test_user.id, ["A", "B"])+ _, members = await _make_group_with_members(+ session, test_user.id, test_workspace.id, ["A", "B"]+ )payload = TransactionSplitsInput(share_type="percent",@@ -139,10 +149,14 @@ async def test_percent_must_sum_to_100(session: AsyncSession, test_user):@pytest.mark.asyncio-async def test_exact_amounts_must_sum_to_total(session: AsyncSession, test_user):+async def test_exact_amounts_must_sum_to_total(+ session: AsyncSession, test_user, test_workspace+):account = await _make_account(session, test_user.id)tx = await _make_tx(session, test_user.id, account.id, Decimal("100.00"))- _, members = await _make_group_with_members(session, test_user.id, ["A", "B"])+ _, members = await _make_group_with_members(+ session, test_user.id, test_workspace.id, ["A", "B"]+ )payload = TransactionSplitsInput(share_type="exact",@@ -161,13 +175,15 @@ async def test_exact_amounts_must_sum_to_total(session: AsyncSession, test_user)@pytest.mark.asyncioasync def test_exact_amounts_credit_transaction_uses_absolute_total(- session: AsyncSession, test_user+ session: AsyncSession, test_user, test_workspace):"""Income splits work the same as expense splits — sign-agnostic."""account = await _make_account(session, test_user.id)tx = await _make_tx(session, test_user.id, account.id, Decimal("200.00"))tx.type = "credit"- _, members = await _make_group_with_members(session, test_user.id, ["A", "B"])+ _, members = await _make_group_with_members(+ session, test_user.id, test_workspace.id, ["A", "B"]+ )payload = TransactionSplitsInput(share_type="exact",@@ -186,10 +202,14 @@ async def test_exact_amounts_credit_transaction_uses_absolute_total(@pytest.mark.asyncio-async def test_replace_splits_clears_previous(session: AsyncSession, test_user):+async def test_replace_splits_clears_previous(+ session: AsyncSession, test_user, test_workspace+):account = await _make_account(session, test_user.id)tx = await _make_tx(session, test_user.id, account.id, Decimal("60.00"))- _, members = await _make_group_with_members(session, test_user.id, ["A", "B", "C"])+ _, members = await _make_group_with_members(+ session, test_user.id, test_workspace.id, ["A", "B", "C"]+ )# First, equal split across 3await split_service.replace_splits(@@ -226,11 +246,17 @@ async def test_replace_splits_clears_previous(session: AsyncSession, test_user):@pytest.mark.asyncio-async def test_members_must_share_one_group(session: AsyncSession, test_user):+async def test_members_must_share_one_group(+ session: AsyncSession, test_user, test_workspace+):account = await _make_account(session, test_user.id)tx = await _make_tx(session, test_user.id, account.id, Decimal("50.00"))- _, members_a = await _make_group_with_members(session, test_user.id, ["A"])- _, members_b = await _make_group_with_members(session, test_user.id, ["B"])+ _, members_a = await _make_group_with_members(+ session, test_user.id, test_workspace.id, ["A"]+ )+ _, members_b = await _make_group_with_members(+ session, test_user.id, test_workspace.id, ["B"]+ )payload = TransactionSplitsInput(share_type="equal",@@ -244,10 +270,14 @@ async def test_members_must_share_one_group(session: AsyncSession, test_user):@pytest.mark.asyncio-async def test_members_must_belong_to_owner(session: AsyncSession, test_user):+async def test_members_must_belong_to_owner(+ session: AsyncSession, test_user, test_workspace+):account = await _make_account(session, test_user.id)tx = await _make_tx(session, test_user.id, account.id, Decimal("50.00"))- _, members = await _make_group_with_members(session, test_user.id, ["A"])+ _, members = await _make_group_with_members(+ session, test_user.id, test_workspace.id, ["A"]+ )other_user = uuid.uuid4()payload = TransactionSplitsInput(@@ -259,10 +289,14 @@ async def test_members_must_belong_to_owner(session: AsyncSession, test_user):@pytest.mark.asyncio-async def test_no_duplicate_member_per_transaction(session: AsyncSession, test_user):+async def test_no_duplicate_member_per_transaction(+ session: AsyncSession, test_user, test_workspace+):account = await _make_account(session, test_user.id)tx = await _make_tx(session, test_user.id, account.id, Decimal("50.00"))- _, members = await _make_group_with_members(session, test_user.id, ["A"])+ _, members = await _make_group_with_members(+ session, test_user.id, test_workspace.id, ["A"]+ )payload = TransactionSplitsInput(share_type="equal",diff --git a/backend/tests/test_transaction_service.py b/backend/tests/test_transaction_service.pyindex d36ec782..fd2a3561 100644--- a/backend/tests/test_transaction_service.py+++ b/backend/tests/test_transaction_service.py@@ -48,7 +48,7 @@ async def txn_account(session: AsyncSession, test_user) -> Account:@pytest.mark.asyncioasync def test_create_transaction_manual(- session: AsyncSession, test_user, test_categories, txn_account+ session: AsyncSession, test_user, test_workspace, test_categories, txn_account):data = TransactionCreate(description="Lunch",@@ -58,7 +58,7 @@ async def test_create_transaction_manual(account_id=txn_account.id,category_id=test_categories[0].id,)- txn = await create_transaction(session, test_user.id, data)+ txn = await create_transaction(session, test_workspace.id, test_user.id, data)assert txn.id is not Noneassert txn.description == "Lunch"@@ -68,7 +68,7 @@ async def test_create_transaction_manual(@pytest.mark.asyncioasync def test_create_transaction_applies_rules(- session: AsyncSession, test_user, test_categories, txn_account+ session: AsyncSession, test_user, test_workspace, test_categories, txn_account):# Create a rulerule = Rule(@@ -92,14 +92,14 @@ async def test_create_transaction_applies_rules(type="debit",account_id=txn_account.id,)- txn = await create_transaction(session, test_user.id, data)+ txn = await create_transaction(session, test_workspace.id, test_user.id, data)assert txn.category_id == test_categories[1].id@pytest.mark.asyncioasync def test_create_transaction_with_category_skips_rules(- session: AsyncSession, test_user, test_categories, txn_account+ session: AsyncSession, test_user, test_workspace, test_categories, txn_account):rule = Rule(id=uuid.uuid4(),@@ -123,12 +123,12 @@ async def test_create_transaction_with_category_skips_rules(account_id=txn_account.id,category_id=test_categories[0].id,)- txn = await create_transaction(session, test_user.id, data)+ txn = await create_transaction(session, test_workspace.id, test_user.id, data)assert txn.category_id == test_categories[0].id@pytest.mark.asyncio-async def test_create_transaction_invalid_account(session: AsyncSession, test_user):+async def test_create_transaction_invalid_account(session: AsyncSession, test_user, test_workspace):data = TransactionCreate(description="Orphan",amount=Decimal("10"),@@ -137,7 +137,7 @@ async def test_create_transaction_invalid_account(session: AsyncSession, test_usaccount_id=uuid.uuid4(),)with pytest.raises(ValueError, match="Account not found"):- await create_transaction(session, test_user.id, data)+ await create_transaction(session, test_workspace.id, test_user.id, data)# ---------------------------------------------------------------------------@@ -146,7 +146,7 @@ async def test_create_transaction_invalid_account(session: AsyncSession, test_us@pytest.mark.asyncio-async def test_get_transactions_pagination(session: AsyncSession, test_user, txn_account):+async def test_get_transactions_pagination(session: AsyncSession, test_user, test_workspace, txn_account):# Create 5 transactionsfor i in range(5):txn = Transaction(@@ -163,11 +163,11 @@ async def test_get_transactions_pagination(session: AsyncSession, test_user, txnsession.add(txn)await session.commit()- page1, total, _ = await get_transactions(session, test_user.id, limit=2, page=1)+ page1, total, _ = await get_transactions(session, test_workspace.id, test_user.id, limit=2, page=1)assert total >= 5assert len(page1) == 2- page2, _, _ = await get_transactions(session, test_user.id, limit=2, page=2)+ page2, _, _ = await get_transactions(session, test_workspace.id, test_user.id, limit=2, page=2)assert len(page2) == 2# No overlap@@ -177,7 +177,7 @@ async def test_get_transactions_pagination(session: AsyncSession, test_user, txn@pytest.mark.asyncio-async def test_get_transactions_filter_by_account(session: AsyncSession, test_user, txn_account):+async def test_get_transactions_filter_by_account(session: AsyncSession, test_user, test_workspace, txn_account):other_account = Account(id=uuid.uuid4(),user_id=test_user.id,@@ -214,7 +214,7 @@ async def test_get_transactions_filter_by_account(session: AsyncSession, test_ussession.add_all([txn1, txn2])await session.commit()- results, _, _ = await get_transactions(session, test_user.id, account_id=txn_account.id)+ results, _, _ = await get_transactions(session, test_workspace.id, test_user.id, account_id=txn_account.id)descs = {t.description for t in results}assert "In main" in descsassert "In other" not in descs@@ -222,7 +222,7 @@ async def test_get_transactions_filter_by_account(session: AsyncSession, test_us@pytest.mark.asyncioasync def test_get_transactions_filter_by_category(- session: AsyncSession, test_user, test_categories, txn_account+ session: AsyncSession, test_user, test_workspace, test_categories, txn_account):txn1 = Transaction(id=uuid.uuid4(),@@ -251,14 +251,14 @@ async def test_get_transactions_filter_by_category(session.add_all([txn1, txn2])await session.commit()- results, _, _ = await get_transactions(session, test_user.id, category_id=test_categories[0].id)+ results, _, _ = await get_transactions(session, test_workspace.id, test_user.id, category_id=test_categories[0].id)descs = {t.description for t in results}assert "Cat A" in descsassert "Cat B" not in descs@pytest.mark.asyncio-async def test_get_transactions_filter_by_date_range(session: AsyncSession, test_user, txn_account):+async def test_get_transactions_filter_by_date_range(session: AsyncSession, test_user, test_workspace, txn_account):txn_jan = Transaction(id=uuid.uuid4(),user_id=test_user.id,@@ -286,7 +286,7 @@ async def test_get_transactions_filter_by_date_range(session: AsyncSession, testresults, _, _ = await get_transactions(session,- test_user.id,+ test_workspace.id, test_user.id,from_date=date(2025, 3, 1),to_date=date(2025, 3, 31),)@@ -297,7 +297,7 @@ async def test_get_transactions_filter_by_date_range(session: AsyncSession, test@pytest.mark.asyncioasync def test_get_transactions_date_filter_respects_accounting_mode(- session: AsyncSession, test_user, txn_account+ session: AsyncSession, test_user, test_workspace, txn_account):# CC purchase on Mar 25 that bills on Apr 15 (effective_date shifted).cc_purchase = Transaction(@@ -332,26 +332,26 @@ async def test_get_transactions_date_filter_respects_accounting_mode(march_window = dict(from_date=date(2025, 3, 1), to_date=date(2025, 3, 31))# Cash mode (default): the CC purchase lives in March, regular in April.- cash_april, _, _ = await get_transactions(session, test_user.id, **april_window)+ cash_april, _, _ = await get_transactions(session, test_workspace.id, test_user.id, **april_window)assert {t.description for t in cash_april} == {"Regular"}- cash_march, _, _ = await get_transactions(session, test_user.id, **march_window)+ cash_march, _, _ = await get_transactions(session, test_workspace.id, test_user.id, **march_window)assert {t.description for t in cash_march} == {"CC purchase"}# Accrual mode: both buckets shift to the bill-due month.accrual_april, _, _ = await get_transactions(- session, test_user.id, accounting_mode="accrual", **april_window+ session, test_workspace.id, test_user.id, accounting_mode="accrual", **april_window)assert {t.description for t in accrual_april} == {"CC purchase", "Regular"}accrual_march, _, _ = await get_transactions(- session, test_user.id, accounting_mode="accrual", **march_window+ session, test_workspace.id, test_user.id, accounting_mode="accrual", **march_window)assert {t.description for t in accrual_march} == set()@pytest.mark.asyncio-async def test_get_transactions_filter_by_search(session: AsyncSession, test_user, txn_account):+async def test_get_transactions_filter_by_search(session: AsyncSession, test_user, test_workspace, txn_account):txn = Transaction(id=uuid.uuid4(),user_id=test_user.id,@@ -366,13 +366,13 @@ async def test_get_transactions_filter_by_search(session: AsyncSession, test_usesession.add(txn)await session.commit()- results, _, _ = await get_transactions(session, test_user.id, search="netflix")+ results, _, _ = await get_transactions(session, test_workspace.id, test_user.id, search="netflix")descs = {t.description for t in results}assert "NETFLIX SUBSCRIPTION" in descs@pytest.mark.asyncio-async def test_get_transactions_filter_by_type(session: AsyncSession, test_user, txn_account):+async def test_get_transactions_filter_by_type(session: AsyncSession, test_user, test_workspace, txn_account):txn_debit = Transaction(id=uuid.uuid4(),user_id=test_user.id,@@ -398,7 +398,7 @@ async def test_get_transactions_filter_by_type(session: AsyncSession, test_user,session.add_all([txn_debit, txn_credit])await session.commit()- results, _, _ = await get_transactions(session, test_user.id, txn_type="credit")+ results, _, _ = await get_transactions(session, test_workspace.id, test_user.id, txn_type="credit")types = {t.type for t in results}assert "credit" in typesassert all(t.type == "credit" for t in results)@@ -410,7 +410,7 @@ async def test_get_transactions_filter_by_type(session: AsyncSession, test_user,@pytest.mark.asyncio-async def test_get_transaction_by_id(session: AsyncSession, test_user, txn_account):+async def test_get_transaction_by_id(session: AsyncSession, test_user, test_workspace, txn_account):txn = Transaction(id=uuid.uuid4(),user_id=test_user.id,@@ -425,19 +425,19 @@ async def test_get_transaction_by_id(session: AsyncSession, test_user, txn_accousession.add(txn)await session.commit()- fetched = await get_transaction(session, txn.id, test_user.id)+ fetched = await get_transaction(session, txn.id, test_workspace.id)assert fetched is not Noneassert fetched.id == txn.id@pytest.mark.asyncio-async def test_get_transaction_not_found(session: AsyncSession, test_user):- result = await get_transaction(session, uuid.uuid4(), test_user.id)+async def test_get_transaction_not_found(session: AsyncSession, test_user, test_workspace):+ result = await get_transaction(session, uuid.uuid4(), test_workspace.id)assert result is None@pytest.mark.asyncio-async def test_update_transaction(session: AsyncSession, test_user, txn_account):+async def test_update_transaction(session: AsyncSession, test_user, test_workspace, txn_account):txn = Transaction(id=uuid.uuid4(),user_id=test_user.id,@@ -455,7 +455,7 @@ async def test_update_transaction(session: AsyncSession, test_user, txn_account)updated = await update_transaction(session,txn.id,- test_user.id,+ test_workspace.id, test_user.id,TransactionUpdate(description="New", amount=Decimal("99")),)assert updated is not None@@ -464,10 +464,11 @@ async def test_update_transaction(session: AsyncSession, test_user, txn_account)@pytest.mark.asyncio-async def test_update_transaction_not_found(session: AsyncSession, test_user):+async def test_update_transaction_not_found(session: AsyncSession, test_user, test_workspace):result = await update_transaction(session,uuid.uuid4(),+ test_workspace.id,test_user.id,TransactionUpdate(description="Ghost"),)@@ -475,7 +476,7 @@ async def test_update_transaction_not_found(session: AsyncSession, test_user):@pytest.mark.asyncio-async def test_delete_transaction(session: AsyncSession, test_user, txn_account):+async def test_delete_transaction(session: AsyncSession, test_user, test_workspace, txn_account):txn = Transaction(id=uuid.uuid4(),user_id=test_user.id,@@ -490,17 +491,17 @@ async def test_delete_transaction(session: AsyncSession, test_user, txn_account)session.add(txn)await session.commit()- assert await delete_transaction(session, txn.id, test_user.id) is True- assert await get_transaction(session, txn.id, test_user.id) is None+ assert await delete_transaction(session, txn.id, test_workspace.id) is True+ assert await get_transaction(session, txn.id, test_workspace.id) is None@pytest.mark.asyncio-async def test_delete_transaction_not_found(session: AsyncSession, test_user):- assert await delete_transaction(session, uuid.uuid4(), test_user.id) is False+async def test_delete_transaction_not_found(session: AsyncSession, test_user, test_workspace):+ assert await delete_transaction(session, uuid.uuid4(), test_workspace.id) is False@pytest.mark.asyncio-async def test_toggle_ignore_transaction(session: AsyncSession, test_user, txn_account):+async def test_toggle_ignore_transaction(session: AsyncSession, test_user, test_workspace, txn_account):txn = Transaction(id=uuid.uuid4(),user_id=test_user.id,@@ -516,19 +517,19 @@ async def test_toggle_ignore_transaction(session: AsyncSession, test_user, txn_aawait session.commit()# First toggle: false → true- result = await toggle_ignore_transaction(session, txn.id, test_user.id)+ result = await toggle_ignore_transaction(session, txn.id, test_workspace.id)assert result is not Noneassert result.is_ignored is True# Second toggle: true → false- result = await toggle_ignore_transaction(session, txn.id, test_user.id)+ result = await toggle_ignore_transaction(session, txn.id, test_workspace.id)assert result is not Noneassert result.is_ignored is False@pytest.mark.asyncio-async def test_toggle_ignore_transaction_not_found(session: AsyncSession, test_user):- assert await toggle_ignore_transaction(session, uuid.uuid4(), test_user.id) is None+async def test_toggle_ignore_transaction_not_found(session: AsyncSession, test_user, test_workspace):+ assert await toggle_ignore_transaction(session, uuid.uuid4(), test_workspace.id) is None# ---------------------------------------------------------------------------@@ -537,7 +538,7 @@ async def test_toggle_ignore_transaction_not_found(session: AsyncSession, test_u@pytest.mark.asyncio-async def test_bulk_update_category(session: AsyncSession, test_user, test_categories, txn_account):+async def test_bulk_update_category(session: AsyncSession, test_user, test_workspace, test_categories, txn_account):txns = []for i in range(3):txn = Transaction(@@ -556,7 +557,7 @@ async def test_bulk_update_category(session: AsyncSession, test_user, test_categawait session.commit()ids = [t.id for t in txns]- count = await bulk_update_category(session, test_user.id, ids, test_categories[0].id)+ count = await bulk_update_category(session, test_workspace.id, ids, test_categories[0].id)assert count == 3for txn in txns:@@ -566,7 +567,7 @@ async def test_bulk_update_category(session: AsyncSession, test_user, test_categ@pytest.mark.asyncioasync def test_bulk_update_category_clear(- session: AsyncSession, test_user, test_categories, txn_account+ session: AsyncSession, test_user, test_workspace, test_categories, txn_account):txn = Transaction(id=uuid.uuid4(),@@ -583,7 +584,7 @@ async def test_bulk_update_category_clear(session.add(txn)await session.commit()- count = await bulk_update_category(session, test_user.id, [txn.id], category_id=None)+ count = await bulk_update_category(session, test_workspace.id, [txn.id], category_id=None)assert count == 1await session.refresh(txn)@@ -645,13 +646,13 @@ def test_apply_fx_override_zero_amount():@pytest.mark.asyncio-async def test_create_transaction_with_fx_override(session: AsyncSession, test_user, txn_account):+async def test_create_transaction_with_fx_override(session: AsyncSession, test_user, test_workspace, txn_account):data = TransactionCreate(account_id=txn_account.id, description="USD Purchase",amount=Decimal("100"), date=date.today(), type="debit",amount_primary=Decimal("500"), fx_rate_used=Decimal("5"),)- txn = await create_transaction(session, test_user.id, data)+ txn = await create_transaction(session, test_workspace.id, test_user.id, data)assert txn.amount_primary == Decimal("500")assert txn.fx_rate_used == Decimal("5")@@ -674,7 +675,7 @@ async def txn_account_usd(session: AsyncSession, test_user) -> Account:@pytest.mark.asyncio-async def test_create_transfer_same_currency(session: AsyncSession, test_user, txn_account):+async def test_create_transfer_same_currency(session: AsyncSession, test_user, test_workspace, txn_account):acct2 = Account(id=uuid.uuid4(), user_id=test_user.id, name="Savings",type="savings", balance=Decimal("0"), currency="BRL",@@ -686,7 +687,7 @@ async def test_create_transfer_same_currency(session: AsyncSession, test_user, tfrom_account_id=txn_account.id, to_account_id=acct2.id,description="Transfer", amount=Decimal("1000"), date=date.today(),)- debit_tx, credit_tx = await create_transfer(session, test_user.id, data)+ debit_tx, credit_tx = await create_transfer(session, test_workspace.id, test_user.id, data)assert debit_tx.type == "debit"assert credit_tx.type == "credit"assert debit_tx.transfer_pair_id == credit_tx.transfer_pair_id@@ -694,57 +695,57 @@ async def test_create_transfer_same_currency(session: AsyncSession, test_user, t@pytest.mark.asyncio-async def test_create_transfer_same_account(session: AsyncSession, test_user, txn_account):+async def test_create_transfer_same_account(session: AsyncSession, test_user, test_workspace, txn_account):data = TransferCreate(from_account_id=txn_account.id, to_account_id=txn_account.id,description="Self", amount=Decimal("100"), date=date.today(),)with pytest.raises(ValueError, match="same account"):- await create_transfer(session, test_user.id, data)+ await create_transfer(session, test_workspace.id, test_user.id, data)@pytest.mark.asyncio-async def test_create_transfer_cross_currency(session: AsyncSession, test_user, txn_account, txn_account_usd):+async def test_create_transfer_cross_currency(session: AsyncSession, test_user, test_workspace, txn_account, txn_account_usd):data = TransferCreate(from_account_id=txn_account.id, to_account_id=txn_account_usd.id,description="Cross-currency", amount=Decimal("500"), date=date.today(),fx_rate=Decimal("0.2"),)- debit_tx, credit_tx = await create_transfer(session, test_user.id, data)+ debit_tx, credit_tx = await create_transfer(session, test_workspace.id, test_user.id, data)assert debit_tx.currency == "BRL"assert credit_tx.currency == "USD"assert credit_tx.amount == Decimal("100.00")@pytest.mark.asyncio-async def test_create_transfer_cross_currency_auto_fx(session: AsyncSession, test_user, txn_account, txn_account_usd):+async def test_create_transfer_cross_currency_auto_fx(session: AsyncSession, test_user, test_workspace, txn_account, txn_account_usd):data = TransferCreate(from_account_id=txn_account.id, to_account_id=txn_account_usd.id,description="Auto FX", amount=Decimal("500"), date=date.today(),)- debit_tx, credit_tx = await create_transfer(session, test_user.id, data)+ debit_tx, credit_tx = await create_transfer(session, test_workspace.id, test_user.id, data)assert debit_tx.type == "debit"assert credit_tx.type == "credit"@pytest.mark.asyncio-async def test_create_transfer_invalid_from_account(session: AsyncSession, test_user, txn_account):+async def test_create_transfer_invalid_from_account(session: AsyncSession, test_user, test_workspace, txn_account):data = TransferCreate(from_account_id=uuid.uuid4(), to_account_id=txn_account.id,description="Bad from", amount=Decimal("100"), date=date.today(),)with pytest.raises(ValueError, match="Source account not found"):- await create_transfer(session, test_user.id, data)+ await create_transfer(session, test_workspace.id, test_user.id, data)@pytest.mark.asyncio-async def test_create_transfer_invalid_to_account(session: AsyncSession, test_user, txn_account):+async def test_create_transfer_invalid_to_account(session: AsyncSession, test_user, test_workspace, txn_account):data = TransferCreate(from_account_id=txn_account.id, to_account_id=uuid.uuid4(),description="Bad to", amount=Decimal("100"), date=date.today(),)with pytest.raises(ValueError, match="Destination account not found"):- await create_transfer(session, test_user.id, data)+ await create_transfer(session, test_workspace.id, test_user.id, data)# ---------------------------------------------------------------------------@@ -753,43 +754,43 @@ async def test_create_transfer_invalid_to_account(session: AsyncSession, test_us@pytest.mark.asyncio-async def test_get_transactions_uncategorized(session: AsyncSession, test_user, txn_account, test_categories):- await create_transaction(session, test_user.id, TransactionCreate(+async def test_get_transactions_uncategorized(session: AsyncSession, test_user, test_workspace, txn_account, test_categories):+ await create_transaction(session, test_workspace.id, test_user.id, TransactionCreate(account_id=txn_account.id, description="Uncategorized",amount=Decimal("50"), date=date.today(), type="debit",))- await create_transaction(session, test_user.id, TransactionCreate(+ await create_transaction(session, test_workspace.id, test_user.id, TransactionCreate(account_id=txn_account.id, description="Categorized",amount=Decimal("50"), date=date.today(), type="debit",category_id=test_categories[0].id,))- txns, _, _ = await get_transactions(session, test_user.id, uncategorized=True)+ txns, _, _ = await get_transactions(session, test_workspace.id, test_user.id, uncategorized=True)descs = [t.description for t in txns]assert "Uncategorized" in descsassert "Categorized" not in descs@pytest.mark.asyncio-async def test_get_transactions_date_filter(session: AsyncSession, test_user, txn_account):+async def test_get_transactions_date_filter(session: AsyncSession, test_user, test_workspace, txn_account):from datetime import timedeltatoday = date.today()yesterday = today - timedelta(days=1)- await create_transaction(session, test_user.id, TransactionCreate(+ await create_transaction(session, test_workspace.id, test_user.id, TransactionCreate(account_id=txn_account.id, description="Today",amount=Decimal("10"), date=today, type="debit",))- await create_transaction(session, test_user.id, TransactionCreate(+ await create_transaction(session, test_workspace.id, test_user.id, TransactionCreate(account_id=txn_account.id, description="Yesterday",amount=Decimal("10"), date=yesterday, type="debit",))- txns, _, _ = await get_transactions(session, test_user.id, from_date=today, to_date=today)+ txns, _, _ = await get_transactions(session, test_workspace.id, test_user.id, from_date=today, to_date=today)descs = [t.description for t in txns]assert "Today" in descsassert "Yesterday" not in descs@pytest.mark.asyncio-async def test_get_transactions_exclude_transfers(session: AsyncSession, test_user, txn_account):+async def test_get_transactions_exclude_transfers(session: AsyncSession, test_user, test_workspace, txn_account):acct2 = Account(id=uuid.uuid4(), user_id=test_user.id, name="Sav",type="savings", balance=Decimal("0"), currency="BRL",@@ -797,27 +798,27 @@ async def test_get_transactions_exclude_transfers(session: AsyncSession, test_ussession.add(acct2)await session.commit()- await create_transfer(session, test_user.id, TransferCreate(+ await create_transfer(session, test_workspace.id, test_user.id, TransferCreate(from_account_id=txn_account.id, to_account_id=acct2.id,description="Xfer", amount=Decimal("100"), date=date.today(),))- await create_transaction(session, test_user.id, TransactionCreate(+ await create_transaction(session, test_workspace.id, test_user.id, TransactionCreate(account_id=txn_account.id, description="Regular",amount=Decimal("50"), date=date.today(), type="debit",))- txns, _, _ = await get_transactions(session, test_user.id, exclude_transfers=True)+ txns, _, _ = await get_transactions(session, test_workspace.id, test_user.id, exclude_transfers=True)descs = [t.description for t in txns]assert "Regular" in descs@pytest.mark.asyncio-async def test_get_transactions_skip_pagination(session: AsyncSession, test_user, txn_account):+async def test_get_transactions_skip_pagination(session: AsyncSession, test_user, test_workspace, txn_account):for i in range(5):- await create_transaction(session, test_user.id, TransactionCreate(+ await create_transaction(session, test_workspace.id, test_user.id, TransactionCreate(account_id=txn_account.id, description=f"Txn{i}",amount=Decimal("10"), date=date.today(), type="debit",))- txns, total, _ = await get_transactions(session, test_user.id, skip_pagination=True, limit=2)+ txns, total, _ = await get_transactions(session, test_workspace.id, test_user.id, skip_pagination=True, limit=2)assert len(txns) == total@@ -827,29 +828,29 @@ async def test_get_transactions_skip_pagination(session: AsyncSession, test_user@pytest.mark.asyncio-async def test_update_transaction_fx_override(session: AsyncSession, test_user, txn_account):- txn = await create_transaction(session, test_user.id, TransactionCreate(+async def test_update_transaction_fx_override(session: AsyncSession, test_user, test_workspace, txn_account):+ txn = await create_transaction(session, test_workspace.id, test_user.id, TransactionCreate(account_id=txn_account.id, description="FX Test",amount=Decimal("100"), date=date.today(), type="debit",))data = TransactionUpdate(amount_primary=Decimal("500"), fx_rate_used=Decimal("5"))- updated = await update_transaction(session, txn.id, test_user.id, data)+ updated = await update_transaction(session, txn.id, test_workspace.id, test_user.id, data)assert updated.amount_primary == Decimal("500")@pytest.mark.asyncio-async def test_update_transaction_restamp_on_amount_change(session: AsyncSession, test_user, txn_account):- txn = await create_transaction(session, test_user.id, TransactionCreate(+async def test_update_transaction_restamp_on_amount_change(session: AsyncSession, test_user, test_workspace, txn_account):+ txn = await create_transaction(session, test_workspace.id, test_user.id, TransactionCreate(account_id=txn_account.id, description="Restamp",amount=Decimal("100"), date=date.today(), type="debit",))data = TransactionUpdate(amount=Decimal("200"))- updated = await update_transaction(session, txn.id, test_user.id, data)+ updated = await update_transaction(session, txn.id, test_workspace.id, test_user.id, data)assert updated.amount == Decimal("200")@pytest.mark.asyncio-async def test_update_transfer_cascades(session: AsyncSession, test_user, txn_account):+async def test_update_transfer_cascades(session: AsyncSession, test_user, test_workspace, txn_account):acct2 = Account(id=uuid.uuid4(), user_id=test_user.id, name="CascSav",type="savings", balance=Decimal("0"), currency="BRL",@@ -857,15 +858,15 @@ async def test_update_transfer_cascades(session: AsyncSession, test_user, txn_acsession.add(acct2)await session.commit()- debit_tx, credit_tx = await create_transfer(session, test_user.id, TransferCreate(+ debit_tx, credit_tx = await create_transfer(session, test_workspace.id, test_user.id, TransferCreate(from_account_id=txn_account.id, to_account_id=acct2.id,description="Cascade Xfer", amount=Decimal("200"), date=date.today(),))data = TransactionUpdate(description="Updated Xfer")- updated = await update_transaction(session, debit_tx.id, test_user.id, data)+ updated = await update_transaction(session, debit_tx.id, test_workspace.id, test_user.id, data)assert updated.description == "Updated Xfer"- paired = await get_transaction(session, credit_tx.id, test_user.id)+ paired = await get_transaction(session, credit_tx.id, test_workspace.id)assert paired.description == "Updated Xfer"@@ -875,7 +876,7 @@ async def test_update_transfer_cascades(session: AsyncSession, test_user, txn_ac@pytest.mark.asyncio-async def test_delete_transfer_cascades(session: AsyncSession, test_user, txn_account):+async def test_delete_transfer_cascades(session: AsyncSession, test_user, test_workspace, txn_account):acct2 = Account(id=uuid.uuid4(), user_id=test_user.id, name="DelSav",type="savings", balance=Decimal("0"), currency="BRL",@@ -883,12 +884,12 @@ async def test_delete_transfer_cascades(session: AsyncSession, test_user, txn_acsession.add(acct2)await session.commit()- debit_tx, credit_tx = await create_transfer(session, test_user.id, TransferCreate(+ debit_tx, credit_tx = await create_transfer(session, test_workspace.id, test_user.id, TransferCreate(from_account_id=txn_account.id, to_account_id=acct2.id,description="Del Xfer", amount=Decimal("300"), date=date.today(),))- assert await delete_transaction(session, debit_tx.id, test_user.id) is True- assert await get_transaction(session, credit_tx.id, test_user.id) is None+ assert await delete_transaction(session, debit_tx.id, test_workspace.id) is True+ assert await get_transaction(session, credit_tx.id, test_workspace.id) is None# ---------------------------------------------------------------------------@@ -898,7 +899,7 @@ async def test_delete_transfer_cascades(session: AsyncSession, test_user, txn_ac@pytest.mark.asyncioasync def test_update_transaction_changes_account(- session: AsyncSession, test_user, txn_account+ session: AsyncSession, test_user, test_workspace, txn_account):other_account = Account(id=uuid.uuid4(), user_id=test_user.id, name="OtherAcc",@@ -907,30 +908,32 @@ async def test_update_transaction_changes_account(session.add(other_account)await session.commit()- txn = await create_transaction(session, test_user.id, TransactionCreate(+ txn = await create_transaction(session, test_workspace.id, test_user.id, TransactionCreate(account_id=txn_account.id, description="Move me",amount=Decimal("42"), date=date.today(), type="debit",))updated = await update_transaction(- session, txn.id, test_user.id,+ session, txn.id, test_workspace.id, test_user.id,TransactionUpdate(account_id=other_account.id),)assert updated is not Noneassert updated.account_id == other_account.id# Re-fetch to make sure the change was committed, not just set in memory.- reloaded = await get_transaction(session, txn.id, test_user.id)+ reloaded = await get_transaction(session, txn.id, test_workspace.id)assert reloaded.account_id == other_account.id@pytest.mark.asyncioasync def test_update_transaction_rejects_foreign_account(- session: AsyncSession, test_user, txn_account+ session: AsyncSession, test_user, test_workspace, txn_account):from app.models.user import Userimport bcrypt as _bcrypt+ from app.services.workspace_service import create_personal_workspace_for_user+other_user = User(id=uuid.uuid4(),email="[email protected]",@@ -938,28 +941,31 @@ async def test_update_transaction_rejects_foreign_account(is_active=True, is_superuser=False, is_verified=True,)session.add(other_user)+ await session.commit()+ other_ws = await create_personal_workspace_for_user(session, other_user)+ await session.commit()foreign_account = Account(- id=uuid.uuid4(), user_id=other_user.id, name="ForeignAcc",+ id=uuid.uuid4(), user_id=other_user.id, workspace_id=other_ws.id, name="ForeignAcc",type="checking", balance=Decimal("0"), currency="BRL",)session.add(foreign_account)await session.commit()- txn = await create_transaction(session, test_user.id, TransactionCreate(+ txn = await create_transaction(session, test_workspace.id, test_user.id, TransactionCreate(account_id=txn_account.id, description="Stay put",amount=Decimal("10"), date=date.today(), type="debit",))with pytest.raises(ValueError, match="Account not found"):await update_transaction(- session, txn.id, test_user.id,+ session, txn.id, test_workspace.id, test_user.id,TransactionUpdate(account_id=foreign_account.id),)@pytest.mark.asyncioasync def test_update_transfer_rejects_collapsing_accounts(- session: AsyncSession, test_user, txn_account+ session: AsyncSession, test_user, test_workspace, txn_account):acct2 = Account(id=uuid.uuid4(), user_id=test_user.id, name="XferSav",@@ -968,7 +974,7 @@ async def test_update_transfer_rejects_collapsing_accounts(session.add(acct2)await session.commit()- debit_tx, credit_tx = await create_transfer(session, test_user.id, TransferCreate(+ debit_tx, credit_tx = await create_transfer(session, test_workspace.id, test_user.id, TransferCreate(from_account_id=txn_account.id, to_account_id=acct2.id,description="Xfer", amount=Decimal("100"), date=date.today(),))@@ -977,7 +983,7 @@ async def test_update_transfer_rejects_collapsing_accounts(# in the same account, which is invalid.with pytest.raises(ValueError, match="same account"):await update_transaction(- session, debit_tx.id, test_user.id,+ session, debit_tx.id, test_workspace.id, test_user.id,TransactionUpdate(account_id=acct2.id),)@@ -989,7 +995,7 @@ async def test_update_transfer_rejects_collapsing_accounts(@pytest.mark.asyncioasync def test_get_transactions_filters_tags_with_exact_match(- session: AsyncSession, test_user, txn_account+ session: AsyncSession, test_user, test_workspace, txn_account):"""Filtering by `#test` must NOT match `#test2` — exact tag boundaries."""txns = [@@ -1011,7 +1017,7 @@ async def test_get_transactions_filters_tags_with_exact_match(await session.commit()matches, total, _ = await get_transactions(- session, test_user.id, tags=["#test"]+ session, test_workspace.id, test_user.id, tags=["#test"])descriptions = {tx.description for tx in matches}assert descriptions == {"A", "C", "E"}@@ -1020,7 +1026,7 @@ async def test_get_transactions_filters_tags_with_exact_match(@pytest.mark.asyncioasync def test_get_transactions_filters_multiple_tags_with_or(- session: AsyncSession, test_user, txn_account+ session: AsyncSession, test_user, test_workspace, txn_account):"""Multiple `tags` are OR-combined: a row matches if it carries ANYof the requested tags — issue #88."""@@ -1042,14 +1048,14 @@ async def test_get_transactions_filters_multiple_tags_with_or(await session.commit()matches, _, _ = await get_transactions(- session, test_user.id, tags=["#test", "#hey"]+ session, test_workspace.id, test_user.id, tags=["#test", "#hey"])assert {tx.description for tx in matches} == {"A", "B", "C"}@pytest.mark.asyncioasync def test_bulk_add_tags_appends_to_each_transaction(- session: AsyncSession, test_user, txn_account+ session: AsyncSession, test_user, test_workspace, txn_account):"""bulk_add_tags must add the given tags to each tx, skipping duplicates."""t1 = Transaction(@@ -1074,7 +1080,7 @@ async def test_bulk_add_tags_appends_to_each_transaction(await session.commit()touched = await bulk_add_tags(- session, test_user.id, [t1.id, t2.id, t3.id], ["#groceries"]+ session, test_workspace.id, [t1.id, t2.id, t3.id], ["#groceries"])assert touched == 2 # t3 already has it@@ -1088,7 +1094,7 @@ async def test_bulk_add_tags_appends_to_each_transaction(@pytest.mark.asyncioasync def test_bulk_remove_tags_clears_only_exact_matches(- session: AsyncSession, test_user, txn_account+ session: AsyncSession, test_user, test_workspace, txn_account):"""Removing `#test` must NOT touch `#test2` — exact match boundary."""t1 = Transaction(@@ -1107,7 +1113,7 @@ async def test_bulk_remove_tags_clears_only_exact_matches(await session.commit()touched = await bulk_remove_tags(- session, test_user.id, [t1.id, t2.id], ["#test"]+ session, test_workspace.id, [t1.id, t2.id], ["#test"])assert touched == 1diff --git a/backend/tests/test_transfer_detection.py b/backend/tests/test_transfer_detection.pyindex f5b6e1b1..72d8564e 100644--- a/backend/tests/test_transfer_detection.py+++ b/backend/tests/test_transfer_detection.py@@ -60,7 +60,7 @@ async def _add_txn(@pytest.mark.asyncio-async def test_detect_basic_pair(session: AsyncSession, test_user):+async def test_detect_basic_pair(session: AsyncSession, test_user, test_workspace):"""Detects a simple debit-credit pair across two accounts."""acc1 = await _make_account(session, test_user.id, "Account A")acc2 = await _make_account(session, test_user.id, "Account B")@@ -69,7 +69,7 @@ async def test_detect_basic_pair(session: AsyncSession, test_user):debit = await _add_txn(session, test_user.id, acc1.id, 500, "debit", today)credit = await _add_txn(session, test_user.id, acc2.id, 500, "credit", today)- pairs_created = await detect_transfer_pairs(session, test_user.id)+ pairs_created = await detect_transfer_pairs(session, test_workspace.id)await session.commit()assert pairs_created == 1@@ -81,7 +81,7 @@ async def test_detect_basic_pair(session: AsyncSession, test_user):@pytest.mark.asyncio-async def test_detect_with_candidate_ids(session: AsyncSession, test_user):+async def test_detect_with_candidate_ids(session: AsyncSession, test_user, test_workspace):"""Only considers candidate debits when candidate_ids is provided."""acc1 = await _make_account(session, test_user.id, "Cand A")acc2 = await _make_account(session, test_user.id, "Cand B")@@ -93,7 +93,7 @@ async def test_detect_with_candidate_ids(session: AsyncSession, test_user):await _add_txn(session, test_user.id, acc2.id, 200, "credit", today)# Only consider debit1 as candidate- pairs = await detect_transfer_pairs(session, test_user.id, candidate_ids=[debit1.id])+ pairs = await detect_transfer_pairs(session, test_workspace.id, candidate_ids=[debit1.id])await session.commit()assert pairs == 1@@ -104,27 +104,27 @@ async def test_detect_with_candidate_ids(session: AsyncSession, test_user):@pytest.mark.asyncio-async def test_detect_no_debits(session: AsyncSession, test_user):+async def test_detect_no_debits(session: AsyncSession, test_user, test_workspace):"""Returns 0 when there are no debits."""acc = await _make_account(session, test_user.id, "No Debits")await _add_txn(session, test_user.id, acc.id, 100, "credit", date.today())- pairs = await detect_transfer_pairs(session, test_user.id)+ pairs = await detect_transfer_pairs(session, test_workspace.id)assert pairs == 0@pytest.mark.asyncio-async def test_detect_no_credits(session: AsyncSession, test_user):+async def test_detect_no_credits(session: AsyncSession, test_user, test_workspace):"""Returns 0 when there are no credits."""acc = await _make_account(session, test_user.id, "No Credits")await _add_txn(session, test_user.id, acc.id, 100, "debit", date.today())- pairs = await detect_transfer_pairs(session, test_user.id)+ pairs = await detect_transfer_pairs(session, test_workspace.id)assert pairs == 0@pytest.mark.asyncio-async def test_detect_respects_date_tolerance(session: AsyncSession, test_user):+async def test_detect_respects_date_tolerance(session: AsyncSession, test_user, test_workspace):"""Only pairs transactions within date_tolerance_days."""acc1 = await _make_account(session, test_user.id, "Tol A")acc2 = await _make_account(session, test_user.id, "Tol B")@@ -134,12 +134,12 @@ async def test_detect_respects_date_tolerance(session: AsyncSession, test_user):# Credit too far away (5 days)await _add_txn(session, test_user.id, acc2.id, 300, "credit", today + timedelta(days=5))- pairs = await detect_transfer_pairs(session, test_user.id, date_tolerance_days=2)+ pairs = await detect_transfer_pairs(session, test_workspace.id, date_tolerance_days=2)assert pairs == 0@pytest.mark.asyncio-async def test_detect_within_tolerance(session: AsyncSession, test_user):+async def test_detect_within_tolerance(session: AsyncSession, test_user, test_workspace):"""Pairs transactions within tolerance."""acc1 = await _make_account(session, test_user.id, "In Tol A")acc2 = await _make_account(session, test_user.id, "In Tol B")@@ -148,7 +148,7 @@ async def test_detect_within_tolerance(session: AsyncSession, test_user):debit = await _add_txn(session, test_user.id, acc1.id, 400, "debit", today)credit = await _add_txn(session, test_user.id, acc2.id, 400, "credit", today + timedelta(days=1))- pairs = await detect_transfer_pairs(session, test_user.id, date_tolerance_days=2)+ pairs = await detect_transfer_pairs(session, test_workspace.id, date_tolerance_days=2)await session.commit()assert pairs == 1@@ -158,7 +158,7 @@ async def test_detect_within_tolerance(session: AsyncSession, test_user):@pytest.mark.asyncio-async def test_detect_ignores_same_account(session: AsyncSession, test_user):+async def test_detect_ignores_same_account(session: AsyncSession, test_user, test_workspace):"""Does not pair debit and credit in the same account."""acc = await _make_account(session, test_user.id, "Same Acc")today = date.today()@@ -166,12 +166,12 @@ async def test_detect_ignores_same_account(session: AsyncSession, test_user):await _add_txn(session, test_user.id, acc.id, 100, "debit", today)await _add_txn(session, test_user.id, acc.id, 100, "credit", today)- pairs = await detect_transfer_pairs(session, test_user.id)+ pairs = await detect_transfer_pairs(session, test_workspace.id)assert pairs == 0@pytest.mark.asyncio-async def test_detect_different_amounts_no_pair(session: AsyncSession, test_user):+async def test_detect_different_amounts_no_pair(session: AsyncSession, test_user, test_workspace):"""Does not pair transactions with different amounts."""acc1 = await _make_account(session, test_user.id, "Diff A")acc2 = await _make_account(session, test_user.id, "Diff B")@@ -180,12 +180,12 @@ async def test_detect_different_amounts_no_pair(session: AsyncSession, test_userawait _add_txn(session, test_user.id, acc1.id, 100, "debit", today)await _add_txn(session, test_user.id, acc2.id, 200, "credit", today)- pairs = await detect_transfer_pairs(session, test_user.id)+ pairs = await detect_transfer_pairs(session, test_workspace.id)assert pairs == 0@pytest.mark.asyncio-async def test_detect_excludes_opening_balance(session: AsyncSession, test_user):+async def test_detect_excludes_opening_balance(session: AsyncSession, test_user, test_workspace):"""Opening balance transactions are excluded from pairing."""acc1 = await _make_account(session, test_user.id, "OB A")acc2 = await _make_account(session, test_user.id, "OB B")@@ -194,12 +194,12 @@ async def test_detect_excludes_opening_balance(session: AsyncSession, test_user)await _add_txn(session, test_user.id, acc1.id, 1000, "debit", today, source="opening_balance")await _add_txn(session, test_user.id, acc2.id, 1000, "credit", today)- pairs = await detect_transfer_pairs(session, test_user.id)+ pairs = await detect_transfer_pairs(session, test_workspace.id)assert pairs == 0@pytest.mark.asyncio-async def test_detect_greedy_closest_date(session: AsyncSession, test_user):+async def test_detect_greedy_closest_date(session: AsyncSession, test_user, test_workspace):"""Greedy matching picks the closest date first."""acc1 = await _make_account(session, test_user.id, "Greedy A")acc2 = await _make_account(session, test_user.id, "Greedy B")@@ -209,7 +209,7 @@ async def test_detect_greedy_closest_date(session: AsyncSession, test_user):await _add_txn(session, test_user.id, acc2.id, 500, "credit", today + timedelta(days=2))close_credit = await _add_txn(session, test_user.id, acc2.id, 500, "credit", today)- pairs = await detect_transfer_pairs(session, test_user.id)+ pairs = await detect_transfer_pairs(session, test_workspace.id)await session.commit()assert pairs == 1@@ -224,7 +224,7 @@ async def test_detect_greedy_closest_date(session: AsyncSession, test_user):@pytest.mark.asyncio-async def test_unlink_transfer_pair(session: AsyncSession, test_user):+async def test_unlink_transfer_pair(session: AsyncSession, test_user, test_workspace):"""Unlinks a transfer pair, clearing transfer_pair_id on both."""acc1 = await _make_account(session, test_user.id, "Unlink A")acc2 = await _make_account(session, test_user.id, "Unlink B")@@ -233,13 +233,13 @@ async def test_unlink_transfer_pair(session: AsyncSession, test_user):debit = await _add_txn(session, test_user.id, acc1.id, 250, "debit", today)credit = await _add_txn(session, test_user.id, acc2.id, 250, "credit", today)- await detect_transfer_pairs(session, test_user.id)+ await detect_transfer_pairs(session, test_workspace.id)await session.commit()await session.refresh(debit)pair_id = debit.transfer_pair_idassert pair_id is not None- unlinked = await unlink_transfer_pair(session, test_user.id, pair_id)+ unlinked = await unlink_transfer_pair(session, test_workspace.id,pair_id)await session.commit()assert unlinked == 2@@ -250,9 +250,9 @@ async def test_unlink_transfer_pair(session: AsyncSession, test_user):@pytest.mark.asyncio-async def test_unlink_nonexistent_pair(session: AsyncSession, test_user):+async def test_unlink_nonexistent_pair(session: AsyncSession, test_user, test_workspace):"""Unlinking a nonexistent pair returns 0."""- unlinked = await unlink_transfer_pair(session, test_user.id, uuid.uuid4())+ unlinked = await unlink_transfer_pair(session, test_workspace.id,uuid.uuid4())assert unlinked == 0@@ -262,7 +262,7 @@ async def test_unlink_nonexistent_pair(session: AsyncSession, test_user):@pytest.mark.asyncio-async def test_candidate_credit_matches_existing_debit(session: AsyncSession, test_user):+async def test_candidate_credit_matches_existing_debit(session: AsyncSession, test_user, test_workspace):"""When candidate_ids contains only a credit, it pairs with an existing debit.Simulates: Account A synced first (debit already exists), then Account B@@ -279,7 +279,7 @@ async def test_candidate_credit_matches_existing_debit(session: AsyncSession, tecredit = await _add_txn(session, test_user.id, acc2.id, 750, "credit", today)# Only the credit is in candidate_ids (second sync)- pairs = await detect_transfer_pairs(session, test_user.id, candidate_ids=[credit.id])+ pairs = await detect_transfer_pairs(session, test_workspace.id, candidate_ids=[credit.id])await session.commit()assert pairs == 1@@ -290,7 +290,7 @@ async def test_candidate_credit_matches_existing_debit(session: AsyncSession, te@pytest.mark.asyncio-async def test_candidate_debit_matches_existing_credit(session: AsyncSession, test_user):+async def test_candidate_debit_matches_existing_credit(session: AsyncSession, test_user, test_workspace):"""When candidate_ids contains only a debit, it pairs with an existing credit.Simulates: Account B synced first (credit already exists), then Account A@@ -307,7 +307,7 @@ async def test_candidate_debit_matches_existing_credit(session: AsyncSession, tedebit = await _add_txn(session, test_user.id, acc1.id, 600, "debit", today)# Only the debit is in candidate_ids (second sync)- pairs = await detect_transfer_pairs(session, test_user.id, candidate_ids=[debit.id])+ pairs = await detect_transfer_pairs(session, test_workspace.id, candidate_ids=[debit.id])await session.commit()assert pairs == 1@@ -318,7 +318,7 @@ async def test_candidate_debit_matches_existing_credit(session: AsyncSession, te@pytest.mark.asyncio-async def test_reverse_detection_does_not_pair_two_old_transactions(session: AsyncSession, test_user):+async def test_reverse_detection_does_not_pair_two_old_transactions(session: AsyncSession, test_user, test_workspace):"""Reverse detection must not pair two transactions that are both outside candidate_ids."""acc1 = await _make_account(session, test_user.id, "Guard A")acc2 = await _make_account(session, test_user.id, "Guard B")@@ -332,7 +332,7 @@ async def test_reverse_detection_does_not_pair_two_old_transactions(session: Asy# A new unrelated credit (different amount) triggers detectionnew_credit = await _add_txn(session, test_user.id, acc3.id, 999, "credit", today)- pairs = await detect_transfer_pairs(session, test_user.id, candidate_ids=[new_credit.id])+ pairs = await detect_transfer_pairs(session, test_workspace.id, candidate_ids=[new_credit.id])await session.commit()assert pairs == 0@@ -344,7 +344,7 @@ async def test_reverse_detection_does_not_pair_two_old_transactions(session: Asy@pytest.mark.asyncio-async def test_both_sides_imported_together(session: AsyncSession, test_user):+async def test_both_sides_imported_together(session: AsyncSession, test_user, test_workspace):"""When both debit and credit are new (same sync), both are in candidate_ids."""acc1 = await _make_account(session, test_user.id, "Both A")acc2 = await _make_account(session, test_user.id, "Both B")@@ -354,7 +354,7 @@ async def test_both_sides_imported_together(session: AsyncSession, test_user):credit = await _add_txn(session, test_user.id, acc2.id, 200, "credit", today)pairs = await detect_transfer_pairs(- session, test_user.id, candidate_ids=[debit.id, credit.id],+ session, test_workspace.id, candidate_ids=[debit.id, credit.id],)await session.commit()assert pairs == 1diff --git a/backend/tests/test_workspace_service.py b/backend/tests/test_workspace_service.pynew file mode 100644index 00000000..3b9a4c59--- /dev/null+++ b/backend/tests/test_workspace_service.py@@ -0,0 +1,187 @@+"""Unit tests for the workspace service + membership helpers.++Covers the happy paths the registration flow + invite API rely on:+ - Personal workspace auto-creation is idempotent+ - Membership listing returns the right shape+ - Role floor enforcement (require_membership(min_role=...))+ - Manager virtual access (managed_by_user_id)+ - Sole-owner protection on demote + remove+"""+import uuid++import pytest+from fastapi import HTTPException++from app.models.user import User+from app.models.workspace import Workspace+from app.services import workspace_service+++async def test_create_personal_workspace_is_idempotent(session, test_user: User):+ """Calling twice returns the same workspace, doesn't duplicate."""+ ws1 = await workspace_service.create_personal_workspace_for_user(session, test_user)+ await session.commit()+ ws2 = await workspace_service.create_personal_workspace_for_user(session, test_user)+ await session.commit()+ assert ws1.id == ws2.id++ workspaces = await workspace_service.get_user_workspaces(session, test_user.id)+ assert len(workspaces) == 1+ assert workspaces[0].kind == "personal"+++async def test_personal_workspace_localizes_name_from_user_prefs(session, test_user: User):+ """Portuguese-speaking user gets 'Pessoal' not 'Personal'."""+ ws = await workspace_service.create_personal_workspace_for_user(session, test_user)+ await session.commit()+ # test_user has language='pt-BR' in conftest+ assert ws.name == "Pessoal"+ assert ws.default_currency == "BRL"+++async def test_require_membership_enforces_role_floor(session, test_user: User):+ ws = await workspace_service.create_personal_workspace_for_user(session, test_user)+ await session.commit()++ # Owner-floor passes for the owner.+ member = await workspace_service.require_membership(+ session, ws.id, test_user.id, min_role="owner"+ )+ assert member.role == "owner"++ # Non-member gets 404, not 403 (don't leak existence).+ stranger_id = uuid.uuid4()+ with pytest.raises(HTTPException) as exc:+ await workspace_service.require_membership(session, ws.id, stranger_id)+ assert exc.value.status_code == 404+++async def test_viewer_role_blocks_write_min_role(session, test_user: User):+ """A viewer's require_membership(min_role='editor') raises 403."""+ ws = await workspace_service.create_personal_workspace_for_user(session, test_user)+ await session.commit()++ # Add a second user as a viewer.+ other = User(+ id=uuid.uuid4(),+ email="[email protected]",+ hashed_password="x",+ is_active=True,+ )+ session.add(other)+ await session.flush()+ await workspace_service.add_member(+ session, workspace_id=ws.id, user_id=other.id, role="viewer"+ )+ await session.commit()++ # Viewer can read.+ member = await workspace_service.require_membership(+ session, ws.id, other.id, min_role="viewer"+ )+ assert member.role == "viewer"++ # But not write.+ with pytest.raises(HTTPException) as exc:+ await workspace_service.require_membership(+ session, ws.id, other.id, min_role="editor"+ )+ assert exc.value.status_code == 403+++async def test_manager_gets_virtual_owner_access(session, test_user: User):+ """A user named on managed_by_user_id gets manager role without a membership row."""+ # Create a workspace whose manager is `test_user` but no membership row.+ ws = Workspace(+ name="Managed",+ kind="personal",+ created_by_user_id=test_user.id,+ managed_by_user_id=test_user.id,+ default_currency="USD",+ )+ session.add(ws)+ await session.commit()++ # No `workspace_members` row exists for test_user; require_membership+ # should still succeed via the manager path.+ member = await workspace_service.require_membership(session, ws.id, test_user.id)+ assert member.role == "manager"++ # Manager passes the owner-floor.+ member = await workspace_service.require_membership(+ session, ws.id, test_user.id, min_role="owner"+ )+ assert member.role == "manager"+++async def test_cannot_demote_sole_owner(session, test_user: User):+ ws = await workspace_service.create_personal_workspace_for_user(session, test_user)+ await session.commit()++ with pytest.raises(HTTPException) as exc:+ await workspace_service.update_member_role(+ session, ws.id, test_user.id, "viewer"+ )+ assert exc.value.status_code == 400+ assert "sole owner" in exc.value.detail.lower()+++async def test_cannot_remove_sole_owner(session, test_user: User):+ ws = await workspace_service.create_personal_workspace_for_user(session, test_user)+ await session.commit()++ with pytest.raises(HTTPException) as exc:+ await workspace_service.remove_member(session, ws.id, test_user.id)+ assert exc.value.status_code == 400+++async def test_list_members_includes_invited_users(session, test_user: User):+ ws = await workspace_service.create_personal_workspace_for_user(session, test_user)+ await session.commit()++ other = User(+ id=uuid.uuid4(),+ email="[email protected]",+ hashed_password="x",+ is_active=True,+ )+ session.add(other)+ await session.flush()+ await workspace_service.add_member(+ session, workspace_id=ws.id, user_id=other.id, role="editor"+ )+ await session.commit()++ members = await workspace_service.list_members(session, ws.id)+ assert len(members) == 2+ emails = {u.email for _, u in members}+ assert emails == {"[email protected]", "[email protected]"}+++async def test_create_workspace_makes_creator_the_manager(session, test_user: User):+ ws = await workspace_service.create_workspace(+ session,+ name="Client books",+ creator=test_user,+ kind="personal",+ )+ await session.commit()++ assert ws.managed_by_user_id == test_user.id+ assert ws.created_by_user_id == test_user.id+ # Default `self_membership=False` means no member row was added.+ members = await workspace_service.list_members(session, ws.id)+ assert len(members) == 0++ # And yet the creator can access via the manager path.+ member = await workspace_service.require_membership(session, ws.id, test_user.id)+ assert member.role == "manager"diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex 3be06da1..2e87f869 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -4,6 +4,7 @@ import { BrowserRouter, Routes, Route } from 'react-router-dom'import { Toaster } from '@/components/ui/sonner'import { ThemeProvider } from '@/components/theme-provider'import { AuthProvider } from '@/contexts/auth-context'+import { WorkspaceProvider } from '@/contexts/workspace-context'import { ProtectedRoute } from '@/components/protected-route'import { AdminRoute } from '@/components/admin-route'import { AgentsRoute } from '@/components/agents-route'@@ -31,6 +32,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 WorkspaceSettingsPage = lazy(() => import('@/pages/workspace-settings'))const queryClient = new QueryClient({defaultOptions: {@@ -55,6 +57,7 @@ function App() {<QueryClientProvider client={queryClient}><BrowserRouter><AuthProvider>+ <WorkspaceProvider><Suspense fallback={<LoadingFallback />}><Routes><Route path="/setup" element={<SetupPage />} />@@ -82,6 +85,7 @@ function App() {<Route path="/payees" element={<PayeesPage />} /><Route path="/groups" element={<GroupsPage />} /><Route path="/groups/:id" element={<GroupDetailPage />} />+ <Route path="/workspace/settings" element={<WorkspaceSettingsPage />} /><Route path="/admin" element={<AdminRoute><AdminSettingsPage /></AdminRoute>} /><Route path="/agents" element={<AgentsRoute><AgentsListPage /></AgentsRoute>} /><Route path="/agents/connections" element={<AgentsRoute><AgentConnectionsPage /></AgentsRoute>} />@@ -90,6 +94,7 @@ function App() {</Routes></Suspense><Toaster />+ </WorkspaceProvider></AuthProvider></BrowserRouter></QueryClientProvider>diff --git a/frontend/src/components/agents/knowledge-section.tsx b/frontend/src/components/agents/knowledge-section.tsxindex dfab185b..7bfd8c2a 100644--- a/frontend/src/components/agents/knowledge-section.tsx+++ b/frontend/src/components/agents/knowledge-section.tsx@@ -6,6 +6,7 @@ import { toast } from 'sonner'import { Button } from '@/components/ui/button'import { agents } from '@/lib/api'import type { KnowledgeDoc } from '@/lib/api'+import { useWorkspace } from '@/contexts/workspace-context'function StatusBadge({ d }: { d: KnowledgeDoc }) {const { t } = useTranslation()@@ -31,6 +32,7 @@ function StatusBadge({ d }: { d: KnowledgeDoc }) {export function KnowledgeSection({ agentId }: { agentId: string }) {const { t } = useTranslation()const qc = useQueryClient()+ const { canWrite } = useWorkspace()const fileRef = useRef<HTMLInputElement>(null)const { data, isLoading } = useQuery({@@ -84,10 +86,12 @@ export function KnowledgeSection({ agentId }: { agentId: string }) {if (fileRef.current) fileRef.current.value = ''}}/>- <Button size="sm" onClick={() => fileRef.current?.click()} disabled={upload.isPending}>- <UploadIcon className="h-4 w-4 mr-1.5" />- {upload.isPending ? t('agents.knowledge.uploading') : t('agents.knowledge.upload')}- </Button>+ {canWrite && (+ <Button size="sm" onClick={() => fileRef.current?.click()} disabled={upload.isPending}>+ <UploadIcon className="h-4 w-4 mr-1.5" />+ {upload.isPending ? t('agents.knowledge.uploading') : t('agents.knowledge.upload')}+ </Button>+ )}</div>{isLoading ? (@@ -108,17 +112,21 @@ export function KnowledgeSection({ agentId }: { agentId: string }) {<span className="text-xs text-muted-foreground">{(d.size_bytes / 1024).toFixed(0)} KB</span></div></div>- <Button- size="icon"- variant="ghost"- title={d.pinned ? t('agents.knowledge.unpinTitle') : t('agents.knowledge.pinTitle')}- onClick={() => pin.mutate({ id: d.id, pinned: !d.pinned })}- >- {d.pinned ? <Pin className="h-4 w-4 text-amber-500" /> : <PinOff className="h-4 w-4" />}- </Button>- <Button size="icon" variant="ghost" onClick={() => remove.mutate(d.id)}>- <Trash2 className="h-4 w-4 text-rose-500" />- </Button>+ {canWrite && (+ <>+ <Button+ size="icon"+ variant="ghost"+ title={d.pinned ? t('agents.knowledge.unpinTitle') : t('agents.knowledge.pinTitle')}+ onClick={() => pin.mutate({ id: d.id, pinned: !d.pinned })}+ >+ {d.pinned ? <Pin className="h-4 w-4 text-amber-500" /> : <PinOff className="h-4 w-4" />}+ </Button>+ <Button size="icon" variant="ghost" onClick={() => remove.mutate(d.id)}>+ <Trash2 className="h-4 w-4 text-rose-500" />+ </Button>+ </>+ )}</div>))}</div>diff --git a/frontend/src/components/agents/tools-section.tsx b/frontend/src/components/agents/tools-section.tsxindex addfc5ce..4d89da7e 100644--- a/frontend/src/components/agents/tools-section.tsx+++ b/frontend/src/components/agents/tools-section.tsx@@ -6,10 +6,12 @@ import { Button } from '@/components/ui/button'import { Switch } from '@/components/ui/switch'import { agents } from '@/lib/api'import type { AgentToolHandle } from '@/lib/api'+import { useWorkspace } from '@/contexts/workspace-context'export function ToolsSection({ agentId }: { agentId: string }) {const { t } = useTranslation()const qc = useQueryClient()+ const { canWrite } = useWorkspace()const { data, isLoading } = useQuery({queryKey: ['agent-tools', agentId],queryFn: () => agents.tools(agentId),@@ -45,9 +47,11 @@ export function ToolsSection({ agentId }: { agentId: string }) {<h3 className="text-sm font-semibold">{t('agents.tools.title')}</h3><p className="text-xs text-muted-foreground">{t('agents.tools.subtitle')}</p></div>- <Button size="sm" disabled={!dirty || save.isPending} onClick={() => save.mutate()}>- {save.isPending ? t('agents.tools.saving') : t('agents.tools.save')}- </Button>+ {canWrite && (+ <Button size="sm" disabled={!dirty || save.isPending} onClick={() => save.mutate()}>+ {save.isPending ? t('agents.tools.saving') : t('agents.tools.save')}+ </Button>+ )}</div>{Object.keys(grouped).length === 0 ? (@@ -75,6 +79,7 @@ export function ToolsSection({ agentId }: { agentId: string }) {</div><Switchchecked={tool.enabled}+ disabled={!canWrite}onCheckedChange={(v) => {setDraft((d) => d.map((x) => (x.server === tool.server && x.name === tool.name ? { ...x, enabled: !!v } : x)))}}diff --git a/frontend/src/components/app-layout.tsx b/frontend/src/components/app-layout.tsxindex 534e6a06..e7b0b444 100644--- a/frontend/src/components/app-layout.tsx+++ b/frontend/src/components/app-layout.tsx@@ -28,12 +28,12 @@ import { APP_VERSION } from '@/lib/build-info'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 {ArrowLeftRight,Building2,SlidersHorizontal,Upload,- LogOut,Menu,ChevronRight,Tag,@@ -54,7 +54,6 @@ import {HardDriveDownload,Shield,ShieldCheck,- Download,} from 'lucide-react'import { usePrivacyMode } from '@/hooks/use-privacy-mode'import { ChangePasswordDialog } from '@/components/change-password-dialog'@@ -104,7 +103,6 @@ export function AppLayout() {const locale = i18n.language === 'en' ? 'en-US' : i18n.languageconst { theme, setTheme } = useTheme()const location = useLocation()- const navigate = useNavigate()const [sidebarOpen, setSidebarOpen] = useState(false)const [accountsExpanded, setAccountsExpanded] = useState(true)const [accountsShowAll, setAccountsShowAll] = useState(false)@@ -162,7 +160,6 @@ export function AppLayout() {}, [user, updateUser])const userInitial = user?.email?.charAt(0).toUpperCase() ?? '?'- const currentLang = i18n.languageconst resolvedTheme = theme === 'system' ? undefined : themeconst isDark = resolvedTheme? resolvedTheme === 'dark'@@ -487,126 +484,30 @@ export function AppLayout() {<UpdateAvailableBanner onOpen={() => setUpdateDialogOpen(true)} />- {/* User section */}+ {/* Merged account + workspace menu — one trigger at the+ bottom of the sidebar shows the active workspace as the+ primary identity, the user email + role as the secondary+ line, and combines workspace switching with all the+ account actions that used to live in a separate dropdown. */}<div className="px-3 pt-1">- <DropdownMenu>- <DropdownMenuTrigger asChild>- <button className="flex items-center gap-3 w-full rounded-lg px-3 py-2.5 text-sm hover:bg-sidebar-accent transition-colors text-left">- <Avatar className="h-7 w-7 shrink-0">- <AvatarFallback className="bg-primary/20 text-primary text-xs font-semibold">- {userInitial}- </AvatarFallback>- </Avatar>- <span className="text-xs text-sidebar-muted truncate flex-1">- {user?.email}- </span>- </button>- </DropdownMenuTrigger>- <DropdownMenuContent align="end" className="w-48" side="top">- {user?.is_superuser && (- <>- <DropdownMenuItem- onClick={() => navigate('/admin')}- className="flex items-center gap-2"- >- <Shield size={14} />- {t('nav.groupAdmin')}- </DropdownMenuItem>- <DropdownMenuSeparator />- </>- )}- <DropdownMenuItem- onClick={() => setChangePasswordOpen(true)}- className="flex items-center gap-2"- >- <KeyRound size={14} />- {t('auth.changePassword')}- </DropdownMenuItem>- <DropdownMenuItem- onClick={() => setTwoFactorOpen(true)}- className="flex items-center gap-2"- >- <ShieldCheck size={14} />- {t('auth.twoFactorTitle')}- </DropdownMenuItem>- <DropdownMenuItem- disabled={backingUp}- onClick={async () => {- setBackingUp(true)- try {- await backupApi.download()- toast.success(t('backup.success'))- } catch {- toast.error(t('backup.error'))- } finally {- setBackingUp(false)- }- }}- className="flex items-center gap-2"- >- <HardDriveDownload size={14} />- {backingUp ? t('backup.downloading') : t('backup.button')}- </DropdownMenuItem>- {agentsEnabled && (- <DropdownMenuItem- onClick={() => navigate('/agents')}- className="flex items-center gap-2"- >- <Sparkles size={14} />- {t('nav.aiAgents')}- </DropdownMenuItem>- )}- <DropdownMenuItem- onClick={() => setUpdateDialogOpen(true)}- className="flex items-center gap-2"- >- <Download size={14} />- {t('update.menuItem')}- </DropdownMenuItem>- <DropdownMenuSub>- <DropdownMenuSubTrigger className="flex items-center gap-2">- <Languages size={14} />- <span className="flex-1">{t('setup.language')}</span>- <span className="text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">- {currentLang === 'pt-BR' ? 'PT' : 'EN'}- </span>- </DropdownMenuSubTrigger>- <DropdownMenuPortal>- <DropdownMenuSubContent className="w-40">- <DropdownMenuLabel className="px-2 py-1 text-[10.5px] font-semibold uppercase tracking-[0.08em] text-muted-foreground/70">- {t('setup.language')}- </DropdownMenuLabel>- <DropdownMenuItem- onClick={() => i18n.changeLanguage('pt-BR')}- className="flex items-center gap-2"- >- <span className="flex-1">Português</span>- {currentLang === 'pt-BR' && (- <Check size={13} className="text-primary" />- )}- </DropdownMenuItem>- <DropdownMenuItem- onClick={() => i18n.changeLanguage('en')}- className="flex items-center gap-2"- >- <span className="flex-1">English</span>- {currentLang === 'en' && (- <Check size={13} className="text-primary" />- )}- </DropdownMenuItem>- </DropdownMenuSubContent>- </DropdownMenuPortal>- </DropdownMenuSub>- <DropdownMenuSeparator />- <DropdownMenuItem- onClick={logout}- className="flex items-center gap-2 text-rose-600 focus:text-rose-600"- >- <LogOut size={14} />- {t('auth.logout')}- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>+ <WorkspaceSwitcher+ backingUp={backingUp}+ onChangePassword={() => setChangePasswordOpen(true)}+ onTwoFactor={() => setTwoFactorOpen(true)}+ onBackup={async () => {+ setBackingUp(true)+ try {+ await backupApi.download()+ toast.success(t('backup.success'))+ } catch {+ toast.error(t('backup.error'))+ } finally {+ setBackingUp(false)+ }+ }}+ onUpdateAvailable={() => setUpdateDialogOpen(true)}+ agentsEnabled={agentsEnabled}+ /></div><div className="px-3 pb-3 pt-1">diff --git a/frontend/src/components/workspace-switcher.tsx b/frontend/src/components/workspace-switcher.tsxnew file mode 100644index 00000000..de753ee1--- /dev/null+++ b/frontend/src/components/workspace-switcher.tsx@@ -0,0 +1,361 @@+import { useState } from 'react'+import { useNavigate } from 'react-router-dom'+import { useTranslation } from 'react-i18next'+import { useMutation } from '@tanstack/react-query'+import { toast } from 'sonner'+import { useAuth } from '@/contexts/auth-context'+import { useWorkspace } from '@/contexts/workspace-context'+import { workspaces as workspacesApi } from '@/lib/api'+import { Button } from '@/components/ui/button'+import { Input } from '@/components/ui/input'+import { Label } from '@/components/ui/label'+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuPortal,+ DropdownMenuSeparator,+ DropdownMenuSub,+ DropdownMenuSubContent,+ DropdownMenuSubTrigger,+ DropdownMenuTrigger,+} from '@/components/ui/dropdown-menu'+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog'+import {+ Check,+ ChevronsUpDown,+ Download,+ HardDriveDownload,+ KeyRound,+ Languages,+ LogOut,+ Plus,+ Settings,+ Shield,+ ShieldCheck,+ Sparkles,+} from 'lucide-react'+import { CategoryIcon } from '@/components/category-icon'+import type { Workspace } from '@/types'++const ROLE_LABEL_KEY: Record<string, string> = {+ owner: 'workspace.roleOwner',+ editor: 'workspace.roleEditor',+ viewer: 'workspace.roleViewer',+ manager: 'workspace.roleManager',+}++// Fallbacks when a workspace hasn't set its own icon/color yet.+const DEFAULT_ICON_BY_KIND: Record<string, string> = {+ personal: 'user',+ freelancer: 'briefcase',+ small_business: 'building-2',+ accountant_firm: 'landmark',+}+const DEFAULT_COLOR = '#6366F1'++function workspaceIcon(w: Workspace): string {+ return w.icon || DEFAULT_ICON_BY_KIND[w.kind] || 'briefcase'+}+function workspaceColor(w: Workspace): string {+ return w.color || DEFAULT_COLOR+}++interface AccountMenuProps {+ /** Backup download in progress — disables the menu item. */+ backingUp: boolean+ /** Open the change-password dialog. */+ onChangePassword: () => void+ /** Open the 2FA setup dialog. */+ onTwoFactor: () => void+ /** Trigger a backup download. */+ onBackup: () => void+ /** Open the "Update available" dialog. */+ onUpdateAvailable: () => void+ /** True when the AGENTS_ENABLED env flag is on. */+ agentsEnabled: boolean+}++/**+ * Unified account menu: workspace identity on the trigger, all+ * workspace + account actions in one dropdown. Replaces the previous+ * standalone workspace switcher + separate user dropdown.+ *+ * Dialogs (change password, 2FA, update available) stay owned by the+ * parent layout — they're shared with other surfaces and the menu+ * only needs to trigger them.+ */+export function WorkspaceSwitcher({+ backingUp,+ onChangePassword,+ onTwoFactor,+ onBackup,+ onUpdateAvailable,+ agentsEnabled,+}: AccountMenuProps) {+ const { t, i18n } = useTranslation()+ const navigate = useNavigate()+ const { current, workspaces, switchWorkspace, refresh } = useWorkspace()+ const { user, logout } = useAuth()+ const [createOpen, setCreateOpen] = useState(false)+ const [newName, setNewName] = useState('')++ const currentLang = i18n.language?.startsWith('pt') ? 'pt-BR' : 'en'++ const createMutation = useMutation({+ mutationFn: () =>+ workspacesApi.create({+ name: newName.trim(),+ self_membership: true,+ }),+ onSuccess: async (ws) => {+ toast.success(t('workspace.createSuccess', 'Workspace created'))+ await refresh()+ await switchWorkspace(ws.id)+ setCreateOpen(false)+ setNewName('')+ navigate('/workspace/settings')+ },+ onError: (e: unknown) => {+ const detail =+ (e as { response?: { data?: { detail?: string } } })?.response?.data?.detail ||+ (e instanceof Error ? e.message : 'Failed to create workspace')+ toast.error(detail)+ },+ })++ if (!current || !user) return null++ const hasMultipleWorkspaces = workspaces.length > 1+ const roleLabel = current.role && ROLE_LABEL_KEY[current.role]+ ? t(ROLE_LABEL_KEY[current.role])+ : null++ return (+ <>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button className="flex items-center gap-3 w-full rounded-lg px-3 py-2.5 text-sm hover:bg-sidebar-accent transition-colors text-left">+ <CategoryIcon+ icon={workspaceIcon(current)}+ color={workspaceColor(current)}+ size="sm"+ className="shrink-0"+ />+ <div className="flex-1 min-w-0">+ <p className="text-xs font-semibold truncate">{current.name}</p>+ <p className="text-[10px] text-sidebar-muted/70 truncate">+ {user.email}+ {roleLabel && (+ <span className="ml-1 uppercase tracking-wide">· {roleLabel}</span>+ )}+ </p>+ </div>+ <ChevronsUpDown size={13} className="text-sidebar-muted/60 shrink-0" />+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start" className="w-64" side="top">+ {/* Workspaces — only show the switcher list when there's more than one. */}+ {hasMultipleWorkspaces && (+ <>+ <DropdownMenuLabel className="px-2 py-1 text-[10.5px] font-semibold uppercase tracking-[0.08em] text-muted-foreground/70">+ {t('workspace.switcherTitle', 'Switch workspace')}+ </DropdownMenuLabel>+ {workspaces.map((w) => {+ const isActive = w.id === current.id+ return (+ <DropdownMenuItem+ key={w.id}+ onClick={() => void switchWorkspace(w.id)}+ className="flex items-center gap-2"+ >+ <CategoryIcon+ icon={workspaceIcon(w)}+ color={workspaceColor(w)}+ size="sm"+ className="shrink-0"+ />+ <span className="flex-1 truncate">{w.name}</span>+ <span className="text-[10px] uppercase tracking-wide text-muted-foreground">+ {w.role && ROLE_LABEL_KEY[w.role] && t(ROLE_LABEL_KEY[w.role])}+ </span>+ {isActive && <Check size={12} className="text-primary ml-1" />}+ </DropdownMenuItem>+ )+ })}+ <DropdownMenuSeparator />+ </>+ )}++ {/* Workspace actions */}+ <DropdownMenuItem+ onClick={() => navigate('/workspace/settings')}+ className="flex items-center gap-2"+ >+ <Settings size={14} />+ <span className="flex-1">{t('workspace.settingsMenu', 'Workspace settings')}</span>+ </DropdownMenuItem>+ <DropdownMenuItem+ onClick={() => setCreateOpen(true)}+ className="flex items-center gap-2"+ >+ <Plus size={14} />+ <span className="flex-1">{t('workspace.create', 'New workspace')}</span>+ </DropdownMenuItem>++ <DropdownMenuSeparator />++ {/* Admin */}+ {user.is_superuser && (+ <DropdownMenuItem+ onClick={() => navigate('/admin')}+ className="flex items-center gap-2"+ >+ <Shield size={14} />+ {t('nav.groupAdmin')}+ </DropdownMenuItem>+ )}++ {/* Account actions */}+ <DropdownMenuItem+ onClick={onChangePassword}+ className="flex items-center gap-2"+ >+ <KeyRound size={14} />+ {t('auth.changePassword')}+ </DropdownMenuItem>+ <DropdownMenuItem+ onClick={onTwoFactor}+ className="flex items-center gap-2"+ >+ <ShieldCheck size={14} />+ {t('auth.twoFactorTitle')}+ </DropdownMenuItem>+ <DropdownMenuItem+ disabled={backingUp}+ onClick={onBackup}+ className="flex items-center gap-2"+ >+ <HardDriveDownload size={14} />+ {backingUp ? t('backup.downloading') : t('backup.button')}+ </DropdownMenuItem>++ {agentsEnabled && (+ <DropdownMenuItem+ onClick={() => navigate('/agents')}+ className="flex items-center gap-2"+ >+ <Sparkles size={14} />+ {t('nav.aiAgents')}+ </DropdownMenuItem>+ )}++ <DropdownMenuItem+ onClick={onUpdateAvailable}+ className="flex items-center gap-2"+ >+ <Download size={14} />+ {t('update.menuItem')}+ </DropdownMenuItem>++ {/* Language sub-menu */}+ <DropdownMenuSub>+ <DropdownMenuSubTrigger className="flex items-center gap-2">+ <Languages size={14} />+ <span className="flex-1">{t('setup.language')}</span>+ <span className="text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">+ {currentLang === 'pt-BR' ? 'PT' : 'EN'}+ </span>+ </DropdownMenuSubTrigger>+ <DropdownMenuPortal>+ <DropdownMenuSubContent className="w-40">+ <DropdownMenuLabel className="px-2 py-1 text-[10.5px] font-semibold uppercase tracking-[0.08em] text-muted-foreground/70">+ {t('setup.language')}+ </DropdownMenuLabel>+ <DropdownMenuItem+ onClick={() => i18n.changeLanguage('pt-BR')}+ className="flex items-center gap-2"+ >+ <span className="flex-1">Português</span>+ {currentLang === 'pt-BR' && <Check size={13} className="text-primary" />}+ </DropdownMenuItem>+ <DropdownMenuItem+ onClick={() => i18n.changeLanguage('en')}+ className="flex items-center gap-2"+ >+ <span className="flex-1">English</span>+ {currentLang === 'en' && <Check size={13} className="text-primary" />}+ </DropdownMenuItem>+ </DropdownMenuSubContent>+ </DropdownMenuPortal>+ </DropdownMenuSub>++ <DropdownMenuSeparator />++ <DropdownMenuItem+ onClick={logout}+ className="flex items-center gap-2 text-rose-600 focus:text-rose-600"+ >+ <LogOut size={14} />+ {t('auth.logout')}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>++ {/* New workspace dialog */}+ <Dialog open={createOpen} onOpenChange={setCreateOpen}>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>{t('workspace.createTitle', 'New workspace')}</DialogTitle>+ <DialogDescription>+ {t(+ 'workspace.createDescription',+ 'A workspace holds its own accounts, categories, budgets, and goals. You can invite people into it from the workspace settings page.',+ )}+ </DialogDescription>+ </DialogHeader>+ <div className="space-y-4">+ <div className="space-y-1.5">+ <Label htmlFor="ws-create-name" className="text-[13px]">+ {t('common.name', 'Name')}+ </Label>+ <Input+ id="ws-create-name"+ value={newName}+ onChange={(e) => setNewName(e.target.value)}+ placeholder={t('workspace.createPlaceholder', 'e.g. Side project, Family')}+ className="h-10 rounded-lg"+ autoFocus+ maxLength={100}+ />+ </div>+ </div>+ <DialogFooter className="mt-2">+ <Button+ variant="outline"+ onClick={() => setCreateOpen(false)}+ className="rounded-lg"+ >+ {t('common.cancel')}+ </Button>+ <Button+ onClick={() => createMutation.mutate()}+ disabled={createMutation.isPending || !newName.trim()}+ className="rounded-lg"+ >+ {createMutation.isPending ? t('common.loading') : t('common.create', 'Create')}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </>+ )+}diff --git a/frontend/src/contexts/workspace-context.tsx b/frontend/src/contexts/workspace-context.tsxnew file mode 100644index 00000000..a65e7e86--- /dev/null+++ b/frontend/src/contexts/workspace-context.tsx@@ -0,0 +1,121 @@+import { createContext, useCallback, useContext, useEffect, useMemo, useState, type ReactNode } from 'react'+import { useQueryClient } from '@tanstack/react-query'+import { useAuth } from '@/contexts/auth-context'+import { workspaces as workspacesApi, WORKSPACE_STORAGE_KEY } from '@/lib/api'+import type { Workspace, WorkspaceRole } from '@/types'++interface WorkspaceContextType {+ current: Workspace | null+ workspaces: Workspace[]+ isLoading: boolean+ /** Switch the active workspace. Persists to localStorage and invalidates queries. */+ switchWorkspace: (id: string) => Promise<void>+ /** Re-fetch the list of workspaces the user can access. */+ refresh: () => Promise<void>+ /** Role of the current user inside the active workspace, or null if no active workspace. */+ role: WorkspaceRole | null+ /** True for owner OR manager (the manager has effective owner rights). */+ canManage: boolean+ /** True for owner, manager, OR editor — anyone allowed to mutate financial data. */+ canWrite: boolean+}++const WorkspaceContext = createContext<WorkspaceContextType | null>(null)++export function WorkspaceProvider({ children }: { children: ReactNode }) {+ const { user, token } = useAuth()+ const [list, setList] = useState<Workspace[]>([])+ const [currentId, setCurrentId] = useState<string | null>(() => localStorage.getItem(WORKSPACE_STORAGE_KEY))+ const [isLoading, setIsLoading] = useState(true)+ const queryClient = useQueryClient()++ const loadWorkspaces = useCallback(async () => {+ setIsLoading(true)+ try {+ const fetched = await workspacesApi.list()+ setList(fetched)+ // Reconcile the stored selection against what's actually accessible.+ // If the stored ID is stale (workspace archived, user removed, etc.)+ // fall back to the first one.+ const storedId = localStorage.getItem(WORKSPACE_STORAGE_KEY)+ const found = fetched.find((w) => w.id === storedId)+ if (found) {+ setCurrentId(found.id)+ } else if (fetched.length > 0) {+ const fallbackId = fetched[0].id+ localStorage.setItem(WORKSPACE_STORAGE_KEY, fallbackId)+ setCurrentId(fallbackId)+ } else {+ localStorage.removeItem(WORKSPACE_STORAGE_KEY)+ setCurrentId(null)+ }+ } catch {+ // 401s are handled by the global interceptor; other failures we+ // just surface as no-data — the user can retry from the UI.+ setList([])+ } finally {+ setIsLoading(false)+ }+ }, [])++ useEffect(() => {+ if (!user || !token) {+ setList([])+ setCurrentId(null)+ setIsLoading(false)+ return+ }+ void loadWorkspaces()+ }, [user, token, loadWorkspaces])++ const switchWorkspace = useCallback(+ async (id: string) => {+ if (id === currentId) return+ // Persist FIRST so the axios interceptor sends the new+ // workspace_id on every refetch fired below.+ localStorage.setItem(WORKSPACE_STORAGE_KEY, id)+ setCurrentId(id)+ // Every cached query was scoped to the previous workspace.+ // `resetQueries` flushes cached data AND refetches active+ // observers in one call — `clear()` alone removed data without+ // triggering refetches (mounted components kept their previous+ // render until a manual reload).+ await queryClient.resetQueries()+ },+ [currentId, queryClient],+ )++ const current = useMemo(+ () => list.find((w) => w.id === currentId) ?? null,+ [list, currentId],+ )++ const role = current?.role ?? null+ const canManage = role === 'owner' || role === 'manager'+ const canWrite = role === 'owner' || role === 'manager' || role === 'editor'++ return (+ <WorkspaceContext.Provider+ value={{+ current,+ workspaces: list,+ isLoading,+ switchWorkspace,+ refresh: loadWorkspaces,+ role,+ canManage,+ canWrite,+ }}+ >+ {children}+ </WorkspaceContext.Provider>+ )+}++export function useWorkspace() {+ const ctx = useContext(WorkspaceContext)+ if (!ctx) {+ throw new Error('useWorkspace must be used within a WorkspaceProvider')+ }+ return ctx+}diff --git a/frontend/src/lib/agents-stream.ts b/frontend/src/lib/agents-stream.tsindex 24720299..d1283bfb 100644--- a/frontend/src/lib/agents-stream.ts+++ b/frontend/src/lib/agents-stream.ts@@ -5,6 +5,7 @@* Authorization header. Instead we POST with fetch, then parse the SSE* response stream by hand.*/+import { WORKSPACE_STORAGE_KEY } from '@/lib/api'export type AgentStreamEvent =| { kind: 'conversation'; conversation_id: string }@@ -29,13 +30,19 @@ export interface SendMessageOptions {export async function streamChat(opts: SendMessageOptions): Promise<void> {const token = localStorage.getItem('token') || ''+ // SSE uses raw fetch, so we have to set the workspace header here+ // — the axios interceptor that adds it for the rest of the app+ // doesn't run on this code path.+ const workspaceId = localStorage.getItem(WORKSPACE_STORAGE_KEY) || ''+ const headers: Record<string, string> = {+ 'Content-Type': 'application/json',+ Authorization: token ? `Bearer ${token}` : '',+ }+ if (workspaceId) headers['X-Workspace-Id'] = workspaceIdconst res = await fetch(`/api/agents/${opts.agentId}/chat`, {method: 'POST',signal: opts.signal,- headers: {- 'Content-Type': 'application/json',- Authorization: token ? `Bearer ${token}` : '',- },+ headers,body: JSON.stringify({content: opts.content,conversation_id: opts.conversationId ?? null,diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex eca150e2..dc6050a8 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -21,6 +21,9 @@ import type {Rule,ImportLog,ImportPreviewTransaction,+ Workspace,+ WorkspaceMember,+ WorkspaceRole,Asset,AssetGroup,AssetValue,@@ -47,12 +50,21 @@ const api = axios.create({baseURL: '/api',})-// Add auth token to requests+// Storage key for the currently-selected workspace ID. Lives in+// localStorage so reloads + new tabs stay on the same workspace until+// the user picks another one.+export const WORKSPACE_STORAGE_KEY = 'workspace_id'++// Add auth token + active workspace header to requestsapi.interceptors.request.use((config) => {const token = localStorage.getItem('token')if (token) {config.headers.Authorization = `Bearer ${token}`}+ const workspaceId = localStorage.getItem(WORKSPACE_STORAGE_KEY)+ if (workspaceId) {+ config.headers['X-Workspace-Id'] = workspaceId+ }return config})@@ -68,6 +80,57 @@ api.interceptors.response.use(})+// Workspaces+export const workspaces = {+ list: async (): Promise<Workspace[]> => {+ const { data } = await api.get('/workspaces')+ return data+ },+ current: async (): Promise<Workspace> => {+ const { data } = await api.get('/workspaces/current')+ return data+ },+ create: async (payload: {+ name: string+ kind?: string+ default_currency?: string+ locale?: string+ icon?: string+ color?: string+ self_membership?: boolean+ }): Promise<Workspace> => {+ const { data } = await api.post('/workspaces', payload)+ return data+ },+ update: async (id: string, payload: Partial<Pick<Workspace, 'name' | 'icon' | 'color' | 'default_currency' | 'locale'>>): Promise<Workspace> => {+ const { data } = await api.patch(`/workspaces/${id}`, payload)+ return data+ },+ listMembers: async (id: string): Promise<WorkspaceMember[]> => {+ const { data } = await api.get(`/workspaces/${id}/members`)+ return data+ },+ invite: async (id: string, payload: { email: string; role?: WorkspaceRole; password?: string }): Promise<WorkspaceMember> => {+ const { data } = await api.post(`/workspaces/${id}/members`, payload)+ return data+ },+ changeRole: async (id: string, memberUserId: string, role: WorkspaceRole): Promise<WorkspaceMember> => {+ const { data } = await api.patch(`/workspaces/${id}/members/${memberUserId}`, { role })+ return data+ },+ removeMember: async (id: string, memberUserId: string): Promise<void> => {+ await api.delete(`/workspaces/${id}/members/${memberUserId}`)+ },+ stats: async (id: string): Promise<{ members: number; accounts: number; transactions: number }> => {+ const { data } = await api.get(`/workspaces/${id}/stats`)+ return data+ },+ archive: async (id: string): Promise<Workspace> => {+ const { data } = await api.post(`/workspaces/${id}/archive`)+ return data+ },+}+// Setupexport const setup = {status: async (): Promise<{ has_users: boolean }> => {diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.jsonindex f97c66be..c269bfce 100644--- a/frontend/src/locales/en.json+++ b/frontend/src/locales/en.json@@ -1,4 +1,63 @@{+ "workspace": {+ "settingsTitle": "Workspace settings",+ "settingsDescription": "Manage workspace details and who has access.",+ "settingsMenu": "Workspace settings",+ "details": "Details",+ "name": "Name",+ "kind": "Type",+ "kindPersonal": "Personal",+ "kindFreelancer": "Freelancer",+ "kindSmallBusiness": "Small business",+ "kindAccountantFirm": "Accountant firm",+ "defaultCurrency": "Default currency",+ "locale": "Language",+ "members": "Members",+ "addMember": "Add member",+ "addMemberTitle": "Add member",+ "addMemberDescription": "Invite an existing user by email, or create a new account by providing a password.",+ "role": "Role",+ "roleOwner": "Owner",+ "roleEditor": "Editor",+ "roleViewer": "Viewer",+ "roleManager": "Manager",+ "roleOwnerHint": "Full access — can manage members, settings, and all data",+ "roleEditorHint": "Can read and write all financial data",+ "roleViewerHint": "Read-only access",+ "roleManagerHint": "External administrator with effective owner rights",+ "passwordForNewUsers": "Password (only for new users)",+ "passwordHint": "If the email isn't registered yet, this password creates the account. They can change it after logging in.",+ "you": "you",+ "remove": "Remove member",+ "removeConfirmTitle": "Remove member",+ "removeConfirmDescription": "Remove {{email}} from this workspace? They'll lose access to all data inside it. This does not delete their user account.",+ "noMembersHint": "Click \"Add member\" to invite someone.",+ "noMembers": "No members yet.",+ "externallyManaged": "Externally managed",+ "youManageThis": "You manage this workspace",+ "saveSuccess": "Workspace updated",+ "saveError": "Could not update workspace",+ "addSuccess": "Member added",+ "removeSuccess": "Member removed",+ "roleUpdated": "Role updated",+ "switcherTitle": "Switch workspace",+ "create": "New workspace",+ "createTitle": "New workspace",+ "createDescription": "A workspace holds its own accounts, categories, budgets, and goals. You can invite people into it from the workspace settings page.",+ "createSuccess": "Workspace created",+ "createPlaceholder": "e.g. Side project, Family",+ "icon": "Icon",+ "statAccounts": "Accounts",+ "statTransactions": "Transactions",+ "statCreatedAt": "Created",+ "dangerZone": "Danger zone",+ "archive": "Archive",+ "archiveAction": "Archive workspace",+ "archiveHint": "The workspace is hidden from the list and switcher. Data is preserved.",+ "archiveSuccess": "Workspace archived",+ "archiveConfirmTitle": "Archive workspace?",+ "archiveConfirmDescription": "The workspace \"{{name}}\" will be removed from your list. Data is preserved and an admin can restore it later."+ },"app": {"name": "Securo","versionAriaLabel": "Running version {{version}}",@@ -913,6 +972,8 @@"delete": "Delete","edit": "Edit","back": "Back",+ "name": "Name",+ "create": "Create","loading": "Loading...","error": "Error","success": "Success",diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.jsonindex 47b76215..2838a548 100644--- a/frontend/src/locales/pt-BR.json+++ b/frontend/src/locales/pt-BR.json@@ -1,4 +1,63 @@{+ "workspace": {+ "settingsTitle": "Configurações do workspace",+ "settingsDescription": "Gerencie os detalhes do workspace e quem tem acesso.",+ "settingsMenu": "Workspace",+ "details": "Detalhes",+ "name": "Nome",+ "kind": "Tipo",+ "kindPersonal": "Pessoal",+ "kindFreelancer": "Freelancer",+ "kindSmallBusiness": "Pequena empresa",+ "kindAccountantFirm": "Escritório contábil",+ "defaultCurrency": "Moeda padrão",+ "locale": "Idioma",+ "members": "Membros",+ "addMember": "Adicionar membro",+ "addMemberTitle": "Adicionar membro",+ "addMemberDescription": "Convide um usuário existente por email, ou crie uma nova conta fornecendo uma senha.",+ "role": "Papel",+ "roleOwner": "Dono",+ "roleEditor": "Editor",+ "roleViewer": "Leitor",+ "roleManager": "Gerente",+ "roleOwnerHint": "Acesso total — pode gerenciar membros, configurações e todos os dados",+ "roleEditorHint": "Pode ler e escrever todos os dados financeiros",+ "roleViewerHint": "Acesso somente leitura",+ "roleManagerHint": "Administrador externo com direitos efetivos de dono",+ "passwordForNewUsers": "Senha (apenas para novos usuários)",+ "passwordHint": "Se o email ainda não estiver registrado, essa senha cria a conta. O usuário pode alterá-la após o primeiro login.",+ "you": "você",+ "remove": "Remover membro",+ "removeConfirmTitle": "Remover membro",+ "removeConfirmDescription": "Remover {{email}} deste workspace? O usuário perderá acesso a todos os dados aqui. Isso não exclui a conta dele.",+ "noMembersHint": "Clique em \"Adicionar membro\" para convidar alguém.",+ "noMembers": "Nenhum membro ainda.",+ "externallyManaged": "Gerenciado externamente",+ "youManageThis": "Você gerencia este workspace",+ "saveSuccess": "Workspace atualizado",+ "saveError": "Não foi possível atualizar o workspace",+ "addSuccess": "Membro adicionado",+ "removeSuccess": "Membro removido",+ "roleUpdated": "Papel atualizado",+ "switcherTitle": "Trocar de workspace",+ "create": "Novo workspace",+ "createTitle": "Novo workspace",+ "createDescription": "Um workspace contém suas próprias contas, categorias, orçamentos e metas. Você pode convidar pessoas pela página de configurações do workspace.",+ "createSuccess": "Workspace criado",+ "createPlaceholder": "ex.: Projeto pessoal, Família",+ "icon": "Ícone",+ "statAccounts": "Contas",+ "statTransactions": "Transações",+ "statCreatedAt": "Criado em",+ "dangerZone": "Zona de perigo",+ "archive": "Arquivar",+ "archiveAction": "Arquivar workspace",+ "archiveHint": "O workspace fica oculto da lista e do switcher. Os dados continuam preservados.",+ "archiveSuccess": "Workspace arquivado",+ "archiveConfirmTitle": "Arquivar workspace?",+ "archiveConfirmDescription": "O workspace \"{{name}}\" será removido da sua lista. Os dados ficam preservados e um admin pode restaurar mais tarde."+ },"app": {"name": "Securo","versionAriaLabel": "Versão em execução {{version}}",@@ -913,6 +972,8 @@"delete": "Excluir","edit": "Editar","back": "Voltar",+ "name": "Nome",+ "create": "Criar","loading": "Carregando...","error": "Erro","success": "Sucesso",diff --git a/frontend/src/pages/account-detail.tsx b/frontend/src/pages/account-detail.tsxindex 5a989ec3..983982c2 100644--- a/frontend/src/pages/account-detail.tsx+++ b/frontend/src/pages/account-detail.tsx@@ -22,6 +22,7 @@ import { Label } from '@/components/ui/label'import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'import { usePrivacyMode } from '@/hooks/use-privacy-mode'import { useAuth } from '@/contexts/auth-context'+import { useWorkspace } from '@/contexts/workspace-context'import {AreaChart,Area,@@ -265,6 +266,7 @@ export default function AccountDetailPage() {const { t, i18n } = useTranslation()const { mask, privacyMode, MASK } = usePrivacyMode()const { user } = useAuth()+ const { canWrite } = useWorkspace()const userCurrency = user?.preferences?.currency_display ?? 'USD'const locale = i18n.language === 'en' ? 'en-US' : i18n.languageconst queryClient = useQueryClient()@@ -780,7 +782,7 @@ export default function AccountDetailPage() {</>)})()}- {isCreditCard && (!account.statement_close_day || !account.payment_due_day) && (+ {isCreditCard && canWrite && (!account.statement_close_day || !account.payment_due_day) && (<><span className="text-muted-foreground text-xs">·</span><button@@ -796,7 +798,7 @@ export default function AccountDetailPage() {)}</div></div>- {!account.is_closed && (+ {!account.is_closed && canWrite && (<Buttonvariant="outline"size="sm"@@ -927,14 +929,16 @@ export default function AccountDetailPage() {{account.is_closed && (<div className="flex items-center justify-between rounded-lg border border-border bg-muted px-4 py-3 mb-6"><span className="text-sm text-muted-foreground">{t('accounts.closedBanner')}</span>- <Button- variant="outline"- size="sm"- onClick={() => reopenMutation.mutate()}- disabled={reopenMutation.isPending}- >- {t('accounts.reopen')}- </Button>+ {canWrite && (+ <Button+ variant="outline"+ size="sm"+ onClick={() => reopenMutation.mutate()}+ disabled={reopenMutation.isPending}+ >+ {t('accounts.reopen')}+ </Button>+ )}</div>)}@@ -1176,14 +1180,16 @@ export default function AccountDetailPage() {</p>)}</div>- <button- type="button"- onClick={() => setCcSettingsOpen(true)}- className="p-1.5 rounded-md text-muted-foreground hover:text-foreground hover:bg-muted transition-colors"- title={t('common.edit')}- >- <Pencil size={13} />- </button>+ {canWrite && (+ <button+ type="button"+ onClick={() => setCcSettingsOpen(true)}+ className="p-1.5 rounded-md text-muted-foreground hover:text-foreground hover:bg-muted transition-colors"+ title={t('common.edit')}+ >+ <Pencil size={13} />+ </button>+ )}</div>{limit != null && pct != null && rawPct != null && (<>@@ -1357,9 +1363,9 @@ export default function AccountDetailPage() {return (<trkey={tx.id}- className={`border-b last:border-0 transition-colors ${isOpening ? 'bg-muted/60' : isPending ? 'opacity-60' : 'hover:bg-muted cursor-pointer'}`}+ className={`border-b last:border-0 transition-colors ${isOpening ? 'bg-muted/60' : isPending ? 'opacity-60' : canWrite ? 'hover:bg-muted cursor-pointer' : ''}`}onClick={() => {- if (!isOpening) {+ if (!isOpening && canWrite) {setEditingTx(tx)setDialogOpen(true)}diff --git a/frontend/src/pages/accounts.tsx b/frontend/src/pages/accounts.tsxindex 1e4bbe20..c60e37df 100644--- a/frontend/src/pages/accounts.tsx+++ b/frontend/src/pages/accounts.tsx@@ -41,6 +41,7 @@ import { ConnectorSelectDialog } from '@/components/connector-select-dialog'import { ConnectionSettingsDialog } from '@/components/connection-settings-dialog'import { usePrivacyMode } from '@/hooks/use-privacy-mode'import { useAuth } from '@/contexts/auth-context'+import { useWorkspace } from '@/contexts/workspace-context'function formatCurrency(value: number, currency = 'USD', locale = 'en-US') {return new Intl.NumberFormat(locale, { style: 'currency', currency }).format(value)@@ -71,6 +72,7 @@ export default function AccountsPage() {const locale = i18n.language === 'en' ? 'en-US' : i18n.languageconst { mask } = usePrivacyMode()const { user } = useAuth()+ const { canWrite } = useWorkspace()const userCurrency = user?.preferences?.currency_display ?? 'USD'const queryClient = useQueryClient()const [dialogOpen, setDialogOpen] = useState(false)@@ -190,16 +192,18 @@ export default function AccountsPage() {section={t('accounts.title')}title={t('accounts.title')}action={- <div className="flex gap-2">- <Button variant="outline" className="gap-1.5" onClick={() => setConnectorSelectOpen(true)}>- <Plus size={16} />- {t('accounts.connectBank')}- </Button>- <Button onClick={() => { setEditingAccount(null); setDialogOpen(true) }} className="gap-1.5">- <Plus size={16} />- {t('accounts.addManual')}- </Button>- </div>+ canWrite ? (+ <div className="flex gap-2">+ <Button variant="outline" className="gap-1.5" onClick={() => setConnectorSelectOpen(true)}>+ <Plus size={16} />+ {t('accounts.connectBank')}+ </Button>+ <Button onClick={() => { setEditingAccount(null); setDialogOpen(true) }} className="gap-1.5">+ <Plus size={16} />+ {t('accounts.addManual')}+ </Button>+ </div>+ ) : undefined}/>@@ -242,30 +246,32 @@ export default function AccountsPage() {</p></div></Link>- <div className="flex items-center gap-1 mr-3 opacity-0 group-hover:opacity-100 transition-opacity">- <button- className="p-1.5 rounded-md text-muted-foreground hover:text-foreground hover:bg-muted transition-colors"- onClick={() => { setEditingAccount(acc); setDialogOpen(true) }}- title={t('common.edit')}- >- <Pencil size={13} />- </button>- <button- className="p-1.5 rounded-md text-muted-foreground hover:text-amber-600 hover:bg-amber-50 transition-colors"- onClick={() => setClosingAccountId(acc.id)}- title={t('accounts.close')}- >- <Archive size={13} />- </button>- <button- className="p-1.5 rounded-md text-muted-foreground hover:text-rose-500 hover:bg-rose-50 transition-colors"- onClick={() => setDeletingId(acc.id)}- disabled={deleteMutation.isPending}- title={t('common.delete')}- >- <Trash2 size={13} />- </button>- </div>+ {canWrite && (+ <div className="flex items-center gap-1 mr-3 opacity-0 group-hover:opacity-100 transition-opacity">+ <button+ className="p-1.5 rounded-md text-muted-foreground hover:text-foreground hover:bg-muted transition-colors"+ onClick={() => { setEditingAccount(acc); setDialogOpen(true) }}+ title={t('common.edit')}+ >+ <Pencil size={13} />+ </button>+ <button+ className="p-1.5 rounded-md text-muted-foreground hover:text-amber-600 hover:bg-amber-50 transition-colors"+ onClick={() => setClosingAccountId(acc.id)}+ title={t('accounts.close')}+ >+ <Archive size={13} />+ </button>+ <button+ className="p-1.5 rounded-md text-muted-foreground hover:text-rose-500 hover:bg-rose-50 transition-colors"+ onClick={() => setDeletingId(acc.id)}+ disabled={deleteMutation.isPending}+ title={t('common.delete')}+ >+ <Trash2 size={13} />+ </button>+ </div>+ )}<div className="text-right"><p className={`text-xs sm:text-sm font-semibold tabular-nums ${(acc.type === 'credit_card' ? bal > 0 : bal < 0) ? 'text-rose-500' : 'text-foreground'}`}>{mask(formatCurrency(bal, acc.currency, locale))}@@ -321,34 +327,36 @@ export default function AccountsPage() {)}</div></div>- <div className="flex items-center gap-1.5">- <Button- variant="ghost"- size="sm"- className="h-8 w-8 p-0 text-muted-foreground hover:text-foreground"- onClick={() => setSettingsConnection(conn)}- >- <Settings size={14} />- </Button>- <Button- variant="ghost"- size="sm"- className="h-8 w-8 p-0 text-muted-foreground hover:text-foreground"- onClick={() => syncMutation.mutate(conn.id)}- disabled={syncMutation.isPending}- >- <RefreshCw size={14} className={syncMutation.isPending ? 'animate-spin' : ''} />- </Button>- <Button- variant="ghost"- size="sm"- className="h-8 w-8 p-0 text-muted-foreground hover:text-rose-500"- onClick={() => setDisconnectingConnection(conn)}- disabled={disconnectMutation.isPending}- >- <Unlink size={14} />- </Button>- </div>+ {canWrite && (+ <div className="flex items-center gap-1.5">+ <Button+ variant="ghost"+ size="sm"+ className="h-8 w-8 p-0 text-muted-foreground hover:text-foreground"+ onClick={() => setSettingsConnection(conn)}+ >+ <Settings size={14} />+ </Button>+ <Button+ variant="ghost"+ size="sm"+ className="h-8 w-8 p-0 text-muted-foreground hover:text-foreground"+ onClick={() => syncMutation.mutate(conn.id)}+ disabled={syncMutation.isPending}+ >+ <RefreshCw size={14} className={syncMutation.isPending ? 'animate-spin' : ''} />+ </Button>+ <Button+ variant="ghost"+ size="sm"+ className="h-8 w-8 p-0 text-muted-foreground hover:text-rose-500"+ onClick={() => setDisconnectingConnection(conn)}+ disabled={disconnectMutation.isPending}+ >+ <Unlink size={14} />+ </Button>+ </div>+ )}</div>{/* Reconnect banner */}{conn.status !== 'active' && (@@ -356,18 +364,20 @@ export default function AccountsPage() {<span className="text-sm text-amber-800">{t('accounts.connectionError')}</span>- <Button- variant="outline"- size="sm"- className="border-amber-300 text-amber-700 hover:bg-amber-100 gap-1.5 h-8"- onClick={() => {- setReconnectConnId(conn.id)- setReconnectItemId(conn.external_id)- }}- >- <RefreshCw size={12} />- {t('accounts.reconnect')}- </Button>+ {canWrite && (+ <Button+ variant="outline"+ size="sm"+ className="border-amber-300 text-amber-700 hover:bg-amber-100 gap-1.5 h-8"+ onClick={() => {+ setReconnectConnId(conn.id)+ setReconnectItemId(conn.external_id)+ }}+ >+ <RefreshCw size={12} />+ {t('accounts.reconnect')}+ </Button>+ )}</div>)}{/* Accounts list */}@@ -399,22 +409,24 @@ export default function AccountsPage() {</p></div></Link>- <div className="flex items-center gap-1 mr-3 opacity-0 group-hover:opacity-100 transition-opacity">- <button- className="p-1.5 rounded-md text-muted-foreground hover:text-foreground hover:bg-muted transition-colors"- onClick={(e) => { e.preventDefault(); setEditingAccount(acc); setDialogOpen(true) }}- title={t('common.edit')}- >- <Pencil size={13} />- </button>- <button- className="p-1.5 rounded-md text-muted-foreground hover:text-amber-600 hover:bg-amber-50 transition-colors"- onClick={(e) => { e.preventDefault(); setClosingAccountId(acc.id) }}- title={t('accounts.close')}- >- <Archive size={13} />- </button>- </div>+ {canWrite && (+ <div className="flex items-center gap-1 mr-3 opacity-0 group-hover:opacity-100 transition-opacity">+ <button+ className="p-1.5 rounded-md text-muted-foreground hover:text-foreground hover:bg-muted transition-colors"+ onClick={(e) => { e.preventDefault(); setEditingAccount(acc); setDialogOpen(true) }}+ title={t('common.edit')}+ >+ <Pencil size={13} />+ </button>+ <button+ className="p-1.5 rounded-md text-muted-foreground hover:text-amber-600 hover:bg-amber-50 transition-colors"+ onClick={(e) => { e.preventDefault(); setClosingAccountId(acc.id) }}+ title={t('accounts.close')}+ >+ <Archive size={13} />+ </button>+ </div>+ )}<div className="text-right"><p className={`text-xs sm:text-sm font-semibold tabular-nums ${(acc.type === 'credit_card' ? bal > 0 : bal < 0) ? 'text-rose-500' : 'text-foreground'}`}>{mask(formatCurrency(bal, acc.currency, locale))}@@ -466,15 +478,17 @@ export default function AccountsPage() {</div><p className="text-sm font-medium text-muted-foreground truncate">{getAccountName(acc)}</p></div>- <Button- variant="ghost"- size="sm"- className="text-xs text-muted-foreground hover:text-foreground h-7 px-2 mr-3"- onClick={() => reopenMutation.mutate(acc.id)}- disabled={reopenMutation.isPending}- >- {t('accounts.reopen')}- </Button>+ {canWrite && (+ <Button+ variant="ghost"+ size="sm"+ className="text-xs text-muted-foreground hover:text-foreground h-7 px-2 mr-3"+ onClick={() => reopenMutation.mutate(acc.id)}+ disabled={reopenMutation.isPending}+ >+ {t('accounts.reopen')}+ </Button>+ )}<p className="text-sm font-semibold tabular-nums text-muted-foreground w-32 text-right">{mask(formatCurrency(Number(acc.current_balance), acc.currency, locale))}</p>diff --git a/frontend/src/pages/agent-connections.tsx b/frontend/src/pages/agent-connections.tsxindex 1d55b927..eac4fbcb 100644--- a/frontend/src/pages/agent-connections.tsx+++ b/frontend/src/pages/agent-connections.tsx@@ -11,10 +11,12 @@ import { agents } from '@/lib/api'import type { LlmConnection } from '@/lib/api'import { ConnectionFormDialog } from '@/components/agents/connection-form-dialog'import { McpExternalPanel } from '@/components/agents/mcp-external-panel'+import { useWorkspace } from '@/contexts/workspace-context'export default function AgentConnectionsPage() {const { t } = useTranslation()const qc = useQueryClient()+ const { canWrite } = useWorkspace()const [editing, setEditing] = useState<LlmConnection | null>(null)const [createOpen, setCreateOpen] = useState(false)const [testResults, setTestResults] = useState<Record<string, { ok: boolean; detail: string }>>({})@@ -52,9 +54,11 @@ export default function AgentConnectionsPage() {section={t('agents.title')}title={t('agents.connections.title')}action={- <Button size="sm" className="gap-1.5 h-8" onClick={() => setCreateOpen(true)}>- <Plus size={13} /> {t('agents.connections.add')}- </Button>+ canWrite ? (+ <Button size="sm" className="gap-1.5 h-8" onClick={() => setCreateOpen(true)}>+ <Plus size={13} /> {t('agents.connections.add')}+ </Button>+ ) : undefined}/>@@ -73,9 +77,11 @@ export default function AgentConnectionsPage() {<p className="text-sm text-muted-foreground mt-1 max-w-md mx-auto">{t('agents.connections.empty.subtitle')}</p>- <Button size="sm" className="gap-1.5 h-8 mt-4" onClick={() => setCreateOpen(true)}>- <Plus size={13} /> {t('agents.connections.add')}- </Button>+ {canWrite && (+ <Button size="sm" className="gap-1.5 h-8 mt-4" onClick={() => setCreateOpen(true)}>+ <Plus size={13} /> {t('agents.connections.add')}+ </Button>+ )}</div>) : (<div className="bg-card rounded-xl border border-border shadow-sm overflow-hidden">@@ -117,35 +123,37 @@ export default function AgentConnectionsPage() {</div>)}</div>- <div className="flex items-center gap-1 shrink-0">- <Button- size="sm"- variant="outline"- className="h-8 text-xs"- onClick={() => testMut.mutate(c.id)}- disabled={testMut.isPending}- >- {t('agents.connections.test')}- </Button>- <button- type="button"- onClick={() => setEditing(c)}- className="p-1.5 rounded-md text-muted-foreground hover:text-primary hover:bg-primary/5 transition-colors"- >- <Edit2 className="h-4 w-4" />- </button>- <button- type="button"- onClick={() => {- if (confirm(t('agents.connections.deleteConfirm', { name: c.name }))) {- removeMut.mutate(c.id)- }- }}- className="p-1.5 rounded-md text-muted-foreground hover:text-rose-500 hover:bg-rose-50 dark:hover:bg-rose-950/30 transition-colors"- >- <Trash2 className="h-4 w-4" />- </button>- </div>+ {canWrite && (+ <div className="flex items-center gap-1 shrink-0">+ <Button+ size="sm"+ variant="outline"+ className="h-8 text-xs"+ onClick={() => testMut.mutate(c.id)}+ disabled={testMut.isPending}+ >+ {t('agents.connections.test')}+ </Button>+ <button+ type="button"+ onClick={() => setEditing(c)}+ className="p-1.5 rounded-md text-muted-foreground hover:text-primary hover:bg-primary/5 transition-colors"+ >+ <Edit2 className="h-4 w-4" />+ </button>+ <button+ type="button"+ onClick={() => {+ if (confirm(t('agents.connections.deleteConfirm', { name: c.name }))) {+ removeMut.mutate(c.id)+ }+ }}+ className="p-1.5 rounded-md text-muted-foreground hover:text-rose-500 hover:bg-rose-50 dark:hover:bg-rose-950/30 transition-colors"+ >+ <Trash2 className="h-4 w-4" />+ </button>+ </div>+ )}</div>)})}diff --git a/frontend/src/pages/agent-detail.tsx b/frontend/src/pages/agent-detail.tsxindex bd05805d..fcc69269 100644--- a/frontend/src/pages/agent-detail.tsx+++ b/frontend/src/pages/agent-detail.tsx@@ -12,12 +12,14 @@ import { AgentFormDialog } from '@/components/agents/agent-form-dialog'import { ChatPanel } from '@/components/agents/chat-panel'import { KnowledgeSection } from '@/components/agents/knowledge-section'import { ToolsSection } from '@/components/agents/tools-section'+import { useWorkspace } from '@/contexts/workspace-context'export default function AgentDetailPage() {const { t } = useTranslation()const { id = '' } = useParams<{ id: string }>()const navigate = useNavigate()const qc = useQueryClient()+ const { canWrite } = useWorkspace()const [editOpen, setEditOpen] = useState(false)const [conversationId, setConversationId] = useState<string | null>(null)// Increments on every sidebar click so the chat input refocuses even@@ -90,20 +92,24 @@ export default function AgentDetailPage() {{providerLabel} · {modelLabel} · temp {agent.temperature}</div></div>- <Button size="sm" variant="outline" onClick={() => setEditOpen(true)}>- <Edit2 className="h-3.5 w-3.5 mr-1.5" /> {t('agents.detail.edit')}- </Button>- <Button- size="sm"- variant="outline"- onClick={() => {- if (confirm(t('agents.detail.deleteConfirm'))) {- removeMut.mutate()- }- }}- >- <Trash2 className="h-3.5 w-3.5 mr-1.5" /> {t('agents.detail.delete')}- </Button>+ {canWrite && (+ <>+ <Button size="sm" variant="outline" onClick={() => setEditOpen(true)}>+ <Edit2 className="h-3.5 w-3.5 mr-1.5" /> {t('agents.detail.edit')}+ </Button>+ <Button+ size="sm"+ variant="outline"+ onClick={() => {+ if (confirm(t('agents.detail.deleteConfirm'))) {+ removeMut.mutate()+ }+ }}+ >+ <Trash2 className="h-3.5 w-3.5 mr-1.5" /> {t('agents.detail.delete')}+ </Button>+ </>+ )}</div><Tabs defaultValue="chat" className="flex-1 flex flex-col min-h-0">diff --git a/frontend/src/pages/agents-list.tsx b/frontend/src/pages/agents-list.tsxindex 6cb8474b..03068a65 100644--- a/frontend/src/pages/agents-list.tsx+++ b/frontend/src/pages/agents-list.tsx@@ -9,10 +9,12 @@ import { Switch } from '@/components/ui/switch'import { PageHeader } from '@/components/page-header'import { agents } from '@/lib/api'import { AgentFormDialog } from '@/components/agents/agent-form-dialog'+import { useWorkspace } from '@/contexts/workspace-context'export default function AgentsListPage() {const { t } = useTranslation()const qc = useQueryClient()+ const { canWrite } = useWorkspace()const [createOpen, setCreateOpen] = useState(false)const { data: info } = useQuery({ queryKey: ['agents-info'], queryFn: () => agents.info() })const { data: list, isLoading } = useQuery({ queryKey: ['agents'], queryFn: () => agents.list() })@@ -39,16 +41,18 @@ export default function AgentsListPage() {section={t('agents.title')}title={t('agents.title')}action={- <div className="flex items-center gap-2">- <Link to="/agents/connections">- <Button variant="outline" size="sm" className="gap-1.5 h-8">- <Plug size={13} /> {t('agents.connections.manage')}+ canWrite ? (+ <div className="flex items-center gap-2">+ <Link to="/agents/connections">+ <Button variant="outline" size="sm" className="gap-1.5 h-8">+ <Plug size={13} /> {t('agents.connections.manage')}+ </Button>+ </Link>+ <Button size="sm" className="gap-1.5 h-8" onClick={() => setCreateOpen(true)}>+ <Plus size={13} /> {t('agents.newAgent')}</Button>- </Link>- <Button size="sm" className="gap-1.5 h-8" onClick={() => setCreateOpen(true)}>- <Plus size={13} /> {t('agents.newAgent')}- </Button>- </div>+ </div>+ ) : undefined}/>@@ -65,9 +69,11 @@ export default function AgentsListPage() {</div><h2 className="text-base font-semibold">{t('agents.empty.title')}</h2><p className="text-sm text-muted-foreground mt-1 max-w-md mx-auto">{t('agents.empty.subtitle')}</p>- <Button size="sm" className="gap-1.5 h-8 mt-4" onClick={() => setCreateOpen(true)}>- <Plus size={13} /> {t('agents.empty.create')}- </Button>+ {canWrite && (+ <Button size="sm" className="gap-1.5 h-8 mt-4" onClick={() => setCreateOpen(true)}>+ <Plus size={13} /> {t('agents.empty.create')}+ </Button>+ )}</div>) : (<div className="bg-card rounded-xl border border-border shadow-sm overflow-hidden">@@ -135,26 +141,28 @@ export default function AgentsListPage() {</Link>{/* Default toggle — wrapper stops the click bubbling soflipping the switch doesn't navigate into the agent. */}- <div- className="flex items-center gap-2 shrink-0"- onClick={(e) => e.stopPropagation()}- title={t(- 'agents.form.isDefaultHint',- 'Used by the global slide-over chat (⌘J). Only one agent can be the default — turning this on clears it on others.',- )}- >- <span className="text-xs text-muted-foreground hidden sm:inline">- {t('agents.defaultLabel', 'Default')}- </span>- <Switch- checked={a.is_default}- onCheckedChange={(value) =>- setDefaultMut.mutate({ id: a.id, value: !!value })- }- disabled={setDefaultMut.isPending}- aria-label={t('agents.defaultLabel', 'Default')}- />- </div>+ {canWrite && (+ <div+ className="flex items-center gap-2 shrink-0"+ onClick={(e) => e.stopPropagation()}+ title={t(+ 'agents.form.isDefaultHint',+ 'Used by the global slide-over chat (⌘J). Only one agent can be the default — turning this on clears it on others.',+ )}+ >+ <span className="text-xs text-muted-foreground hidden sm:inline">+ {t('agents.defaultLabel', 'Default')}+ </span>+ <Switch+ checked={a.is_default}+ onCheckedChange={(value) =>+ setDefaultMut.mutate({ id: a.id, value: !!value })+ }+ disabled={setDefaultMut.isPending}+ aria-label={t('agents.defaultLabel', 'Default')}+ />+ </div>+ )}<Linkto={`/agents/${a.id}`}className="shrink-0 text-muted-foreground/60 hover:text-muted-foreground"diff --git a/frontend/src/pages/assets.tsx b/frontend/src/pages/assets.tsxindex 14c75920..ba236319 100644--- a/frontend/src/pages/assets.tsx+++ b/frontend/src/pages/assets.tsx@@ -50,6 +50,7 @@ import {import { PageHeader } from '@/components/page-header'import { usePrivacyMode } from '@/hooks/use-privacy-mode'import { useAuth } from '@/contexts/auth-context'+import { useWorkspace } from '@/contexts/workspace-context'function formatCurrency(value: number, currency = 'USD', locale = 'en-US') {try {@@ -172,6 +173,7 @@ export default function AssetsPage() {const locale = i18n.language === 'en' ? 'en-US' : i18n.languageconst { mask } = usePrivacyMode()const { user } = useAuth()+ const { canWrite } = useWorkspace()const userCurrency = user?.preferences?.currency_display ?? 'USD'const queryClient = useQueryClient()@@ -707,34 +709,38 @@ export default function AssetsPage() {)}</div><div className="flex items-center gap-1 shrink-0">- <button- onClick={(e) => { e.stopPropagation(); setMovingAsset(asset) }}- title={t('assets.moveToWallet')}- className="p-1.5 rounded-lg text-muted-foreground hover:text-foreground hover:bg-muted transition-colors"- >- <FolderInput size={14} />- </button>- <button- onClick={(e) => { e.stopPropagation(); if (!isProviderOwned) openEdit(asset) }}- disabled={isProviderOwned}- title={isProviderOwned ? t('assets.syncedReadOnly') : undefined}- className="p-1.5 rounded-lg text-muted-foreground hover:text-foreground hover:bg-muted transition-colors disabled:opacity-30 disabled:cursor-not-allowed disabled:hover:bg-transparent"- >- <Pencil size={14} />- </button>- <button- onClick={(e) => { e.stopPropagation(); if (!isProviderOwned) setDeletingId(asset.id) }}- disabled={isProviderOwned}- title={isProviderOwned ? t('assets.syncedReadOnly') : undefined}- className="p-1.5 rounded-lg text-muted-foreground hover:text-rose-600 hover:bg-rose-50 transition-colors disabled:opacity-30 disabled:cursor-not-allowed disabled:hover:bg-transparent"- >- <Trash2 size={14} />- </button>+ {canWrite && (+ <>+ <button+ onClick={(e) => { e.stopPropagation(); setMovingAsset(asset) }}+ title={t('assets.moveToWallet')}+ className="p-1.5 rounded-lg text-muted-foreground hover:text-foreground hover:bg-muted transition-colors"+ >+ <FolderInput size={14} />+ </button>+ <button+ onClick={(e) => { e.stopPropagation(); if (!isProviderOwned) openEdit(asset) }}+ disabled={isProviderOwned}+ title={isProviderOwned ? t('assets.syncedReadOnly') : undefined}+ className="p-1.5 rounded-lg text-muted-foreground hover:text-foreground hover:bg-muted transition-colors disabled:opacity-30 disabled:cursor-not-allowed disabled:hover:bg-transparent"+ >+ <Pencil size={14} />+ </button>+ <button+ onClick={(e) => { e.stopPropagation(); if (!isProviderOwned) setDeletingId(asset.id) }}+ disabled={isProviderOwned}+ title={isProviderOwned ? t('assets.syncedReadOnly') : undefined}+ className="p-1.5 rounded-lg text-muted-foreground hover:text-rose-600 hover:bg-rose-50 transition-colors disabled:opacity-30 disabled:cursor-not-allowed disabled:hover:bg-transparent"+ >+ <Trash2 size={14} />+ </button>+ </>+ )}{isExpanded ? <ChevronUp size={16} className="text-muted-foreground" /> : <ChevronDown size={16} className="text-muted-foreground" />}</div></div>- {isExpanded && <AssetDetail assetId={asset.id} currency={asset.currency} locale={locale} purchasePrice={asset.purchase_price} purchaseDate={asset.purchase_date} valuationMethod={asset.valuation_method} />}+ {isExpanded && <AssetDetail assetId={asset.id} currency={asset.currency} locale={locale} purchasePrice={asset.purchase_price} purchaseDate={asset.purchase_date} valuationMethod={asset.valuation_method} canWrite={canWrite} />}</div>)}@@ -841,21 +847,25 @@ export default function AssetsPage() {<span className="text-sm font-bold tabular-nums text-foreground shrink-0">{mask(formatCurrency(total, userCurrency, locale))}</span>- <button- onClick={() => openEditWallet(wallet)}- className="p-1 rounded-lg text-muted-foreground hover:text-foreground hover:bg-muted transition-colors"- title={t('assets.editWallet')}- >- <Pencil size={12} />- </button>- {!isSynced && (- <button- onClick={() => setDeletingWalletId(wallet.id)}- className="p-1 rounded-lg text-muted-foreground hover:text-rose-600 hover:bg-rose-50 transition-colors"- title={t('assets.deleteWallet')}- >- <Trash2 size={12} />- </button>+ {canWrite && (+ <>+ <button+ onClick={() => openEditWallet(wallet)}+ className="p-1 rounded-lg text-muted-foreground hover:text-foreground hover:bg-muted transition-colors"+ title={t('assets.editWallet')}+ >+ <Pencil size={12} />+ </button>+ {!isSynced && (+ <button+ onClick={() => setDeletingWalletId(wallet.id)}+ className="p-1 rounded-lg text-muted-foreground hover:text-rose-600 hover:bg-rose-50 transition-colors"+ title={t('assets.deleteWallet')}+ >+ <Trash2 size={12} />+ </button>+ )}+ </>)}</div>{!isCollapsed && walletAssets.length > 0 && (@@ -878,16 +888,18 @@ export default function AssetsPage() {section={t('assets.title')}title={t('assets.title')}action={- <div className="flex items-center gap-2">- <Button onClick={openCreateWallet} variant="outline" className="gap-1.5">- <Wallet size={16} />- {t('assets.newWallet')}- </Button>- <Button onClick={openCreate} className="gap-1.5">- <Plus size={16} />- {t('assets.addAsset')}- </Button>- </div>+ canWrite ? (+ <div className="flex items-center gap-2">+ <Button onClick={openCreateWallet} variant="outline" className="gap-1.5">+ <Wallet size={16} />+ {t('assets.newWallet')}+ </Button>+ <Button onClick={openCreate} className="gap-1.5">+ <Plus size={16} />+ {t('assets.addAsset')}+ </Button>+ </div>+ ) : undefined}/>@@ -1690,10 +1702,11 @@ function PortfolioChart({ data, wallets, currency, locale: loc, mask }: {)}-function AssetDetail({ assetId, currency, locale: loc, purchasePrice, purchaseDate, valuationMethod }: {+function AssetDetail({ assetId, currency, locale: loc, purchasePrice, purchaseDate, valuationMethod, canWrite }: {assetId: string; currency: string; locale: stringpurchasePrice: number | null; purchaseDate: string | nullvaluationMethod: string+ canWrite: boolean}) {const { t } = useTranslation()const { mask } = usePrivacyMode()@@ -1843,7 +1856,7 @@ function AssetDetail({ assetId, currency, locale: loc, purchasePrice, purchaseDa)}{/* Add Value Form — only for manual assets */}- {valuationMethod === 'manual' && <div className="flex items-end gap-2">+ {valuationMethod === 'manual' && canWrite && <div className="flex items-end gap-2"><div className="flex-1"><Label className="text-[11px] text-muted-foreground">{t('assets.amount')}</Label><Input@@ -1912,7 +1925,7 @@ function AssetDetail({ assetId, currency, locale: loc, purchasePrice, purchaseDa<span className="text-[11px] text-muted-foreground tabular-nums">{new Date(v.date + 'T00:00:00').toLocaleDateString(loc)}</span>- {valuationMethod === 'manual' && v.source === 'manual' && (+ {valuationMethod === 'manual' && v.source === 'manual' && canWrite && (<buttononClick={() => deleteValueMutation.mutate(v.id)}className="p-1 rounded text-muted-foreground/40 hover:text-rose-600 transition-colors"diff --git a/frontend/src/pages/budgets.tsx b/frontend/src/pages/budgets.tsxindex c118cd9a..c5984165 100644--- a/frontend/src/pages/budgets.tsx+++ b/frontend/src/pages/budgets.tsx@@ -23,6 +23,7 @@ import { PageHeader } from '@/components/page-header'import { CategoryIcon } from '@/components/category-icon'import { usePrivacyMode } from '@/hooks/use-privacy-mode'import { useAuth } from '@/contexts/auth-context'+import { useWorkspace } from '@/contexts/workspace-context'function formatCurrency(value: number, currency = 'USD', locale = 'en-US') {return new Intl.NumberFormat(locale, { style: 'currency', currency }).format(value)@@ -55,6 +56,7 @@ export default function BudgetsPage() {const { t, i18n } = useTranslation()const { mask } = usePrivacyMode()const { user } = useAuth()+ const { canWrite } = useWorkspace()const userCurrency = user?.preferences?.currency_display ?? 'USD'const locale = i18n.language === 'en' ? 'en-US' : i18n.languageconst queryClient = useQueryClient()@@ -179,9 +181,11 @@ export default function BudgetsPage() {<SectionHeadertitle={t('budgets.title')}action={- <Button size="sm" className="gap-1.5 h-8" onClick={() => { setEditing(null); setDialogOpen(true) }}>- <Plus size={13} /> {t('budgets.add')}- </Button>+ canWrite ? (+ <Button size="sm" className="gap-1.5 h-8" onClick={() => { setEditing(null); setDialogOpen(true) }}>+ <Plus size={13} /> {t('budgets.add')}+ </Button>+ ) : undefined}/>{budgetsList && budgetsList.length > 0 ? (@@ -190,7 +194,7 @@ export default function BudgetsPage() {<tr className="border-b border-border"><th className={`${TH} pl-4 sm:pl-5 text-left`}>{t('budgets.category')}</th><th className={`${TH} text-left w-36`}>{t('budgets.amount')}</th>- <th className={`${TH} pr-4 sm:pr-5 text-right w-24`}>{t('budgets.actions')}</th>+ {canWrite && <th className={`${TH} pr-4 sm:pr-5 text-right w-24`}>{t('budgets.actions')}</th>}</tr></thead><tbody>@@ -207,23 +211,25 @@ export default function BudgetsPage() {</span></td><td className="py-3 text-sm font-semibold tabular-nums text-foreground">{mask(formatCurrency(budget.amount, userCurrency, locale))}</td>- <td className="py-3 pr-4 sm:pr-5">- <div className="flex items-center justify-end gap-1">- <button- className="p-1.5 rounded-md text-muted-foreground hover:text-primary hover:bg-primary/5 transition-colors"- onClick={() => { setEditing(budget); setDialogOpen(true) }}- >- <Pencil size={13} />- </button>- <button- className="p-1.5 rounded-md text-muted-foreground hover:text-rose-500 hover:bg-rose-50 transition-colors"- onClick={() => deleteMutation.mutate(budget.id)}- disabled={deleteMutation.isPending}- >- <Trash2 size={13} />- </button>- </div>- </td>+ {canWrite && (+ <td className="py-3 pr-4 sm:pr-5">+ <div className="flex items-center justify-end gap-1">+ <button+ className="p-1.5 rounded-md text-muted-foreground hover:text-primary hover:bg-primary/5 transition-colors"+ onClick={() => { setEditing(budget); setDialogOpen(true) }}+ >+ <Pencil size={13} />+ </button>+ <button+ className="p-1.5 rounded-md text-muted-foreground hover:text-rose-500 hover:bg-rose-50 transition-colors"+ onClick={() => deleteMutation.mutate(budget.id)}+ disabled={deleteMutation.isPending}+ >+ <Trash2 size={13} />+ </button>+ </div>+ </td>+ )}</tr>))}</tbody>diff --git a/frontend/src/pages/categories.tsx b/frontend/src/pages/categories.tsxindex 0c0f00b5..92a93bfb 100644--- a/frontend/src/pages/categories.tsx+++ b/frontend/src/pages/categories.tsx@@ -18,6 +18,7 @@ import { Pencil, Trash2, Plus, ChevronDown, ChevronRight, ChevronsUpDown } fromimport { PageHeader } from '@/components/page-header'import { CategoryIcon } from '@/components/category-icon'import { IconPicker } from '@/components/icon-picker'+import { useWorkspace } from '@/contexts/workspace-context'function SectionCard({ children }: { children: React.ReactNode }) {return (@@ -41,6 +42,7 @@ function SectionHeader({ title, titleExtra, action }: { title: string; titleExtrexport default function CategoriesPage() {const { t } = useTranslation()const queryClient = useQueryClient()+ const { canWrite } = useWorkspace()const [catDialogOpen, setCatDialogOpen] = useState(false)const [editingCat, setEditingCat] = useState<Category | null>(null)const [formIcon, setFormIcon] = useState('circle-help')@@ -147,25 +149,27 @@ export default function CategoriesPage() {<span className="inline-block w-3.5 h-3.5 rounded-full border border-black/10" style={{ backgroundColor: cat.color }} /><span className="text-xs text-muted-foreground font-mono">{cat.color}</span></div>- <div className="flex items-center gap-1 shrink-0 ml-2">- <button- className="p-1.5 rounded-md text-muted-foreground hover:text-primary hover:bg-primary/5 transition-colors"- onClick={() => openCatDialog(cat)}- title={t('common.edit')}- >- <Pencil size={13} />- </button>- {!cat.is_system && (+ {canWrite && (+ <div className="flex items-center gap-1 shrink-0 ml-2"><button- className="p-1.5 rounded-md text-muted-foreground hover:text-rose-500 hover:bg-rose-50 transition-colors"- onClick={() => deleteCatMutation.mutate(cat.id)}- disabled={deleteCatMutation.isPending}- title={t('common.delete')}+ className="p-1.5 rounded-md text-muted-foreground hover:text-primary hover:bg-primary/5 transition-colors"+ onClick={() => openCatDialog(cat)}+ title={t('common.edit')}>- <Trash2 size={13} />+ <Pencil size={13} /></button>- )}- </div>+ {!cat.is_system && (+ <button+ className="p-1.5 rounded-md text-muted-foreground hover:text-rose-500 hover:bg-rose-50 transition-colors"+ onClick={() => deleteCatMutation.mutate(cat.id)}+ disabled={deleteCatMutation.isPending}+ title={t('common.delete')}+ >+ <Trash2 size={13} />+ </button>+ )}+ </div>+ )}</div>)@@ -194,14 +198,16 @@ export default function CategoriesPage() {</button>}action={- <div className="flex gap-2">- <Button variant="outline" size="sm" className="gap-1.5 h-8" onClick={() => openGroupDialog(null)}>- <Plus size={13} /> <span className="hidden sm:inline">{t('groups.add')}</span>- </Button>- <Button size="sm" className="gap-1.5 h-8" onClick={() => openCatDialog(null)}>- <Plus size={13} /> <span className="hidden sm:inline">{t('categories.addCategory')}</span>- </Button>- </div>+ canWrite ? (+ <div className="flex gap-2">+ <Button variant="outline" size="sm" className="gap-1.5 h-8" onClick={() => openGroupDialog(null)}>+ <Plus size={13} /> <span className="hidden sm:inline">{t('groups.add')}</span>+ </Button>+ <Button size="sm" className="gap-1.5 h-8" onClick={() => openCatDialog(null)}>+ <Plus size={13} /> <span className="hidden sm:inline">{t('categories.addCategory')}</span>+ </Button>+ </div>+ ) : undefined}/><div>@@ -219,25 +225,27 @@ export default function CategoriesPage() {<span className="text-sm font-semibold" style={{ color: group.color }}>{group.name}</span><span className="text-xs text-muted-foreground">({group.categories.length})</span></button>- <div className="flex items-center gap-1 shrink-0">- <button- className="p-1.5 rounded-md text-muted-foreground hover:text-primary hover:bg-primary/5 transition-colors"- onClick={() => openGroupDialog(group)}- title={t('common.edit')}- >- <Pencil size={13} />- </button>- {!group.is_system && (+ {canWrite && (+ <div className="flex items-center gap-1 shrink-0"><button- className="p-1.5 rounded-md text-muted-foreground hover:text-rose-500 hover:bg-rose-50 transition-colors"- onClick={() => deleteGroupMutation.mutate(group.id)}- disabled={deleteGroupMutation.isPending}- title={t('common.delete')}+ className="p-1.5 rounded-md text-muted-foreground hover:text-primary hover:bg-primary/5 transition-colors"+ onClick={() => openGroupDialog(group)}+ title={t('common.edit')}>- <Trash2 size={13} />+ <Pencil size={13} /></button>- )}- </div>+ {!group.is_system && (+ <button+ className="p-1.5 rounded-md text-muted-foreground hover:text-rose-500 hover:bg-rose-50 transition-colors"+ onClick={() => deleteGroupMutation.mutate(group.id)}+ disabled={deleteGroupMutation.isPending}+ title={t('common.delete')}+ >+ <Trash2 size={13} />+ </button>+ )}+ </div>+ )}</div>{!isCollapsed && group.categories.map(renderCategoryItem)}</div>diff --git a/frontend/src/pages/goals.tsx b/frontend/src/pages/goals.tsxindex d1819197..12e043f4 100644--- a/frontend/src/pages/goals.tsx+++ b/frontend/src/pages/goals.tsx@@ -30,6 +30,7 @@ import { IconPicker } from '@/components/icon-picker'import { PageHeader } from '@/components/page-header'import { usePrivacyMode } from '@/hooks/use-privacy-mode'import { useAuth } from '@/contexts/auth-context'+import { useWorkspace } from '@/contexts/workspace-context'function formatCurrency(value: number, currency = 'USD', locale = 'en-US') {return new Intl.NumberFormat(locale, { style: 'currency', currency }).format(value)@@ -104,6 +105,7 @@ export default function GoalsPage() {const { t, i18n } = useTranslation()const { mask } = usePrivacyMode()const { user } = useAuth()+ const { canWrite } = useWorkspace()const userCurrency = user?.preferences?.currency_display ?? 'USD'const locale = i18n.language === 'en' ? 'en-US' : i18n.languageconst queryClient = useQueryClient()@@ -219,9 +221,11 @@ export default function GoalsPage() {<SectionHeadertitle={t('goals.title')}action={- <Button size="sm" className="gap-1.5 h-8" onClick={openCreateDialog}>- <Plus size={13} /> {t('goals.add')}- </Button>+ canWrite ? (+ <Button size="sm" className="gap-1.5 h-8" onClick={openCreateDialog}>+ <Plus size={13} /> {t('goals.add')}+ </Button>+ ) : undefined}/>{goalsList && goalsList.length > 0 ? (@@ -301,57 +305,59 @@ export default function GoalsPage() {</div>{/* Actions */}- <div className="flex items-center gap-1 shrink-0">- {goal.status === 'active' && (- <button- className="p-1.5 rounded-md text-muted-foreground hover:text-amber-500 hover:bg-amber-50 dark:hover:bg-amber-500/10 transition-colors"- onClick={() => statusMutation.mutate({ id: goal.id, status: 'paused' })}- title={t('goals.pause')}- >- <Pause size={13} />- </button>- )}- {goal.status === 'paused' && (- <button- className="p-1.5 rounded-md text-muted-foreground hover:text-emerald-500 hover:bg-emerald-50 dark:hover:bg-emerald-500/10 transition-colors"- onClick={() => statusMutation.mutate({ id: goal.id, status: 'active' })}- title={t('goals.resume')}- >- <Play size={13} />- </button>- )}- {(goal.status === 'active' || goal.status === 'paused') && (+ {canWrite && (+ <div className="flex items-center gap-1 shrink-0">+ {goal.status === 'active' && (+ <button+ className="p-1.5 rounded-md text-muted-foreground hover:text-amber-500 hover:bg-amber-50 dark:hover:bg-amber-500/10 transition-colors"+ onClick={() => statusMutation.mutate({ id: goal.id, status: 'paused' })}+ title={t('goals.pause')}+ >+ <Pause size={13} />+ </button>+ )}+ {goal.status === 'paused' && (+ <button+ className="p-1.5 rounded-md text-muted-foreground hover:text-emerald-500 hover:bg-emerald-50 dark:hover:bg-emerald-500/10 transition-colors"+ onClick={() => statusMutation.mutate({ id: goal.id, status: 'active' })}+ title={t('goals.resume')}+ >+ <Play size={13} />+ </button>+ )}+ {(goal.status === 'active' || goal.status === 'paused') && (+ <button+ className="p-1.5 rounded-md text-muted-foreground hover:text-blue-500 hover:bg-blue-50 dark:hover:bg-blue-500/10 transition-colors"+ onClick={() => statusMutation.mutate({ id: goal.id, status: 'completed' })}+ title={t('goals.complete')}+ >+ <CheckCircle2 size={13} />+ </button>+ )}+ {goal.status !== 'archived' && (+ <button+ className="p-1.5 rounded-md text-muted-foreground hover:text-muted-foreground/80 hover:bg-muted transition-colors"+ onClick={() => statusMutation.mutate({ id: goal.id, status: 'archived' })}+ title={t('goals.archive')}+ >+ <Archive size={13} />+ </button>+ )}<button- className="p-1.5 rounded-md text-muted-foreground hover:text-blue-500 hover:bg-blue-50 dark:hover:bg-blue-500/10 transition-colors"- onClick={() => statusMutation.mutate({ id: goal.id, status: 'completed' })}- title={t('goals.complete')}+ className="p-1.5 rounded-md text-muted-foreground hover:text-primary hover:bg-primary/5 transition-colors"+ onClick={() => openEditDialog(goal)}>- <CheckCircle2 size={13} />+ <Pencil size={13} /></button>- )}- {goal.status !== 'archived' && (<button- className="p-1.5 rounded-md text-muted-foreground hover:text-muted-foreground/80 hover:bg-muted transition-colors"- onClick={() => statusMutation.mutate({ id: goal.id, status: 'archived' })}- title={t('goals.archive')}+ className="p-1.5 rounded-md text-muted-foreground hover:text-rose-500 hover:bg-rose-50 dark:hover:bg-rose-500/10 transition-colors"+ onClick={() => deleteMutation.mutate(goal.id)}+ disabled={deleteMutation.isPending}>- <Archive size={13} />+ <Trash2 size={13} /></button>- )}- <button- className="p-1.5 rounded-md text-muted-foreground hover:text-primary hover:bg-primary/5 transition-colors"- onClick={() => openEditDialog(goal)}- >- <Pencil size={13} />- </button>- <button- className="p-1.5 rounded-md text-muted-foreground hover:text-rose-500 hover:bg-rose-50 dark:hover:bg-rose-500/10 transition-colors"- onClick={() => deleteMutation.mutate(goal.id)}- disabled={deleteMutation.isPending}- >- <Trash2 size={13} />- </button>- </div>+ </div>+ )}</div></div>)diff --git a/frontend/src/pages/group-detail.tsx b/frontend/src/pages/group-detail.tsxindex 089ac968..fdcbbdd7 100644--- a/frontend/src/pages/group-detail.tsx+++ b/frontend/src/pages/group-detail.tsx@@ -32,6 +32,7 @@ import {type GroupSettlementPayload,} from '@/lib/api'import { useAuth } from '@/contexts/auth-context'+import { useWorkspace } from '@/contexts/workspace-context'import { Button } from '@/components/ui/button'import { Input } from '@/components/ui/input'import { Label } from '@/components/ui/label'@@ -159,6 +160,7 @@ export default function GroupDetailPage() {const navigate = useNavigate()const queryClient = useQueryClient()const { user } = useAuth()+ const { canWrite } = useWorkspace()const { data: group, isLoading: loadingGroup } = useQuery({queryKey: ['groups', groupId],@@ -704,7 +706,7 @@ export default function GroupDetailPage() {<SectionHeadertitle={t('splitGroups.members')}action={- isOwner ? (+ isOwner && canWrite ? (<Button size="sm" className="gap-1.5 h-8" onClick={openCreateMember}><UserPlus size={13} />{t('splitGroups.addMember')}@@ -748,7 +750,7 @@ export default function GroupDetailPage() {</p>)}</div>- {isOwner && (+ {isOwner && canWrite && (<Button variant="ghost" size="sm" onClick={() => openEditMember(member)}>{t('common.edit')}</Button>@@ -808,6 +810,7 @@ export default function GroupDetailPage() {// (positive amount = they owe the owner)const canActLinked = !isOwner && isViewerLine && positiveif (!isOwner && !canActLinked) return null+ if (!canWrite) return nullreturn (<Buttonvariant="outline"@@ -911,7 +914,7 @@ export default function GroupDetailPage() {<SectionHeadertitle={t('splitGroups.settlements')}action={- isOwner ? (+ isOwner && canWrite ? (<Buttonsize="sm"variant="outline"@@ -942,7 +945,7 @@ export default function GroupDetailPage() {<span className="text-sm font-semibold tabular-nums">{formatCurrency(s.amount, s.currency, locale)}</span>- {isOwner && (+ {isOwner && canWrite && (<Buttonvariant="ghost"size="sm"diff --git a/frontend/src/pages/groups.tsx b/frontend/src/pages/groups.tsxindex 633a156f..f8c42dbd 100644--- a/frontend/src/pages/groups.tsx+++ b/frontend/src/pages/groups.tsx@@ -6,6 +6,7 @@ import { toast } from 'sonner'import { groups as groupsApi, currencies as currenciesApi, type GroupCreatePayload } from '@/lib/api'import { useAuth } from '@/contexts/auth-context'+import { useWorkspace } from '@/contexts/workspace-context'import { Button } from '@/components/ui/button'import { Input } from '@/components/ui/input'import { Label } from '@/components/ui/label'@@ -36,6 +37,7 @@ export default function GroupsPage() {const navigate = useNavigate()const queryClient = useQueryClient()const { user } = useAuth()+ const { canWrite } = useWorkspace()const userCurrency = user?.preferences?.currency_display ?? 'USD'const [statusFilter, setStatusFilter] = useState<StatusFilter>('active')const [dialogOpen, setDialogOpen] = useState(false)@@ -143,7 +145,7 @@ export default function GroupsPage() {section={t('splitGroups.section')}title={t('splitGroups.title')}action={- <Button onClick={openCreate}>+ {t('splitGroups.add')}</Button>+ canWrite ? <Button onClick={openCreate}>+ {t('splitGroups.add')}</Button> : undefined}/>@@ -215,7 +217,7 @@ export default function GroupsPage() {{t('splitGroups.memberCount', { count: group.members.length })} · {group.default_currency}</p></div>- {group.is_owner && (+ {group.is_owner && canWrite && (<Buttonvariant="ghost"size="sm"diff --git a/frontend/src/pages/import.tsx b/frontend/src/pages/import.tsxindex 716381b7..401319a5 100644--- a/frontend/src/pages/import.tsx+++ b/frontend/src/pages/import.tsx@@ -15,6 +15,7 @@ import { PageHeader } from '@/components/page-header'import { ImportSummaryBar } from '@/components/import-summary-bar'import { ImportReviewTable } from '@/components/import-review-table'import { useAuth } from '@/contexts/auth-context'+import { useWorkspace } from '@/contexts/workspace-context'const TYPE_LABELS: Record<string, string> = {checking: 'accounts.typeChecking',@@ -46,6 +47,7 @@ function toReviewTransactions(txns: ImportPreviewTransaction[]): ImportReviewTraexport default function ImportPage() {const { t, i18n } = useTranslation()const { user } = useAuth()+ const { canWrite } = useWorkspace()const userCurrency = user?.preferences?.currency_display ?? 'USD'const locale = i18n.language === 'en' ? 'en-US' : i18n.languageconst queryClient = useQueryClient()@@ -275,7 +277,7 @@ export default function ImportPage() {<PageHeader section={t('import.title')} title={t('import.subtitle')} />{/* Upload zone */}- <div+ {canWrite && <divclassName={`bg-card rounded-xl border-2 border-dashed transition-all cursor-pointer ${dragOver ? 'border-primary bg-primary/5' : 'border-border hover:border-border'}`}@@ -346,7 +348,7 @@ export default function ImportPage() {</>)}</div>- </div>+ </div>}{/* Review section */}{previewData && (@@ -610,13 +612,15 @@ export default function ImportPage() {{formatCurrency(log.total_debit, userCurrency, locale)}</td><td className="px-3 sm:px-4 py-3 text-right">- <button- onClick={() => setDeleteTarget(log)}- className="text-muted-foreground hover:text-rose-500 transition-colors"- title={t('import.undoImport')}- >- <Trash2 className="w-4 h-4" />- </button>+ {canWrite && (+ <button+ onClick={() => setDeleteTarget(log)}+ className="text-muted-foreground hover:text-rose-500 transition-colors"+ title={t('import.undoImport')}+ >+ <Trash2 className="w-4 h-4" />+ </button>+ )}</td></tr>))}diff --git a/frontend/src/pages/payees.tsx b/frontend/src/pages/payees.tsxindex a8c9488b..1003179e 100644--- a/frontend/src/pages/payees.tsx+++ b/frontend/src/pages/payees.tsx@@ -28,6 +28,7 @@ import { PageHeader } from '@/components/page-header'import { Search, Star, Merge, Trash2, ArrowRight } from 'lucide-react'import { usePrivacyMode } from '@/hooks/use-privacy-mode'import { useAuth } from '@/contexts/auth-context'+import { useWorkspace } from '@/contexts/workspace-context'import type { Payee } from '@/types'function formatCurrency(value: number, currency = 'USD', locale = 'en-US') {@@ -40,6 +41,7 @@ export default function PayeesPage() {const locale = i18n.language === 'en' ? 'en-US' : i18n.languageconst { mask } = usePrivacyMode()const { user } = useAuth()+ const { canWrite } = useWorkspace()const userCurrency = user?.preferences?.currency_display ?? 'USD'const typeLabels: Record<string, string> = {merchant: t('payees.typeMerchant'),@@ -175,17 +177,19 @@ export default function PayeesPage() {section={t('payees.section')}title={t('payees.title')}action={- <div className="flex items-center gap-2">- {selectedIds.size >= 2 && (- <Button variant="outline" onClick={() => { setMergeTargetId(''); setMergeDialogOpen(true) }}>- <Merge size={16} className="mr-1.5" />- {t('payees.merge')} ({selectedIds.size})+ canWrite ? (+ <div className="flex items-center gap-2">+ {selectedIds.size >= 2 && (+ <Button variant="outline" onClick={() => { setMergeTargetId(''); setMergeDialogOpen(true) }}>+ <Merge size={16} className="mr-1.5" />+ {t('payees.merge')} ({selectedIds.size})+ </Button>+ )}+ <Button onClick={openCreate}>+ + {t('payees.add')}</Button>- )}- <Button onClick={openCreate}>- + {t('payees.add')}- </Button>- </div>+ </div>+ ) : undefined}/>@@ -215,12 +219,12 @@ export default function PayeesPage() {<Table><TableHeader><TableRow className="border-b border-border hover:bg-transparent">- <TableHead className="w-[40px] py-3 pl-4 pr-0" />+ {canWrite && <TableHead className="w-[40px] py-3 pl-4 pr-0" />}<TableHead className="text-xs font-medium text-muted-foreground py-3 w-[32px]" /><TableHead className="text-xs font-medium text-muted-foreground py-3">{t('payees.name')}</TableHead><TableHead className="hidden md:table-cell text-xs font-medium text-muted-foreground py-3 w-[120px]">{t('payees.type')}</TableHead><TableHead className="text-xs font-medium text-muted-foreground py-3 text-right w-[120px]">{t('payees.transactionCount')}</TableHead>- <TableHead className="w-[60px]" />+ {canWrite && <TableHead className="w-[60px]" />}</TableRow></TableHeader><TableBody>@@ -232,28 +236,37 @@ export default function PayeesPage() {setSummaryPayee(summaryPayee === payee.id ? null : payee.id)}}>- <TableCell className="py-2.5 pl-4 pr-0 w-[40px]">- <input- type="checkbox"- checked={selectedIds.has(payee.id)}- onChange={() => toggleSelect(payee.id)}- onClick={(e) => e.stopPropagation()}- className="h-4 w-4 rounded border-border accent-primary cursor-pointer"- />- </TableCell>+ {canWrite && (+ <TableCell className="py-2.5 pl-4 pr-0 w-[40px]">+ <input+ type="checkbox"+ checked={selectedIds.has(payee.id)}+ onChange={() => toggleSelect(payee.id)}+ onClick={(e) => e.stopPropagation()}+ className="h-4 w-4 rounded border-border accent-primary cursor-pointer"+ />+ </TableCell>+ )}<TableCell className="py-2.5 w-[32px]">- <button- onClick={(e) => {- e.stopPropagation()- favoriteMutation.mutate({ id: payee.id, is_favorite: !payee.is_favorite })- }}- className="p-1 rounded hover:bg-accent"- >+ {canWrite ? (+ <button+ onClick={(e) => {+ e.stopPropagation()+ favoriteMutation.mutate({ id: payee.id, is_favorite: !payee.is_favorite })+ }}+ className="p-1 rounded hover:bg-accent"+ >+ <Star+ size={14}+ className={payee.is_favorite ? 'fill-amber-400 text-amber-400' : 'text-muted-foreground'}+ />+ </button>+ ) : (<Starsize={14}- className={payee.is_favorite ? 'fill-amber-400 text-amber-400' : 'text-muted-foreground'}+ className={payee.is_favorite ? 'fill-amber-400 text-amber-400' : 'text-muted-foreground opacity-50'}/>- </button>+ )}</TableCell><TableCell className="py-2.5"><span className="text-sm font-semibold text-foreground">{payee.name}</span>@@ -267,20 +280,22 @@ export default function PayeesPage() {<TableCell className="py-2.5 text-right"><span className="text-sm tabular-nums text-muted-foreground">{payee.transaction_count}</span></TableCell>- <TableCell className="py-2.5 pr-4">- <Button- variant="ghost"- size="sm"- onClick={(e) => { e.stopPropagation(); openEdit(payee) }}- >- {t('common.edit')}- </Button>- </TableCell>+ {canWrite && (+ <TableCell className="py-2.5 pr-4">+ <Button+ variant="ghost"+ size="sm"+ onClick={(e) => { e.stopPropagation(); openEdit(payee) }}+ >+ {t('common.edit')}+ </Button>+ </TableCell>+ )}</TableRow>))}{filtered.length === 0 && (<TableRow>- <TableCell colSpan={6} className="text-center py-16 text-muted-foreground">+ <TableCell colSpan={canWrite ? 6 : 4} className="text-center py-16 text-muted-foreground">{t('payees.empty')}</TableCell></TableRow>diff --git a/frontend/src/pages/recurring.tsx b/frontend/src/pages/recurring.tsxindex 0fa6ff69..50762a6a 100644--- a/frontend/src/pages/recurring.tsx+++ b/frontend/src/pages/recurring.tsx@@ -23,6 +23,7 @@ import { CategorySelect } from '@/components/category-select'import { DatePickerInput } from '@/components/ui/date-picker-input'import { usePrivacyMode } from '@/hooks/use-privacy-mode'import { useAuth } from '@/contexts/auth-context'+import { useWorkspace } from '@/contexts/workspace-context'function formatCurrency(value: number, currency = 'USD', locale = 'en-US') {return new Intl.NumberFormat(locale, { style: 'currency', currency }).format(value)@@ -63,6 +64,7 @@ function RecurringTab() {const locale = i18n.language === 'en' ? 'en-US' : i18n.languageconst { mask } = usePrivacyMode()const { user } = useAuth()+ const { canWrite } = useWorkspace()const userCurrency = user?.preferences?.currency_display ?? 'USD'const queryClient = useQueryClient()const [dialogOpen, setDialogOpen] = useState(false)@@ -142,21 +144,23 @@ function RecurringTab() {<SectionHeadertitle={t('recurring.title')}action={- <div className="flex gap-2">- <Button- variant="outline"- size="sm"- className="gap-1.5 h-8"- onClick={() => generateMutation.mutate()}- disabled={generateMutation.isPending}- >- <RefreshCw size={12} />- <span className="hidden sm:inline">{t('recurring.generatePending')}</span>- </Button>- <Button size="sm" className="gap-1.5 h-8" onClick={() => { setEditing(null); setDialogOpen(true) }}>- <Plus size={13} /> <span className="hidden sm:inline">{t('recurring.add')}</span>- </Button>- </div>+ canWrite ? (+ <div className="flex gap-2">+ <Button+ variant="outline"+ size="sm"+ className="gap-1.5 h-8"+ onClick={() => generateMutation.mutate()}+ disabled={generateMutation.isPending}+ >+ <RefreshCw size={12} />+ <span className="hidden sm:inline">{t('recurring.generatePending')}</span>+ </Button>+ <Button size="sm" className="gap-1.5 h-8" onClick={() => { setEditing(null); setDialogOpen(true) }}>+ <Plus size={13} /> <span className="hidden sm:inline">{t('recurring.add')}</span>+ </Button>+ </div>+ ) : undefined}/>{recurringList && recurringList.length > 0 ? (@@ -168,7 +172,7 @@ function RecurringTab() {<th className={`${TH} text-left w-28 hidden md:table-cell`}>{t('recurring.frequency')}</th><th className={`${TH} text-left w-32 hidden md:table-cell`}>{t('recurring.nextOccurrence')}</th><th className={`${TH} text-left w-24 hidden sm:table-cell`}>{t('recurring.status')}</th>- <th className={`${TH} pr-4 sm:pr-5 text-right w-24`}>{t('recurring.actions')}</th>+ {canWrite && <th className={`${TH} pr-4 sm:pr-5 text-right w-24`}>{t('recurring.actions')}</th>}</tr></thead><tbody>@@ -204,23 +208,25 @@ function RecurringTab() {{rt.is_active ? t('recurring.active') : t('recurring.inactive')}</span></td>- <td className="py-3 pr-4 sm:pr-5">- <div className="flex items-center justify-end gap-1">- <button- className="p-1.5 rounded-md text-muted-foreground hover:text-primary hover:bg-primary/5 transition-colors"- onClick={() => { setEditing(rt); setDialogOpen(true) }}- >- <Pencil size={13} />- </button>- <button- className="p-1.5 rounded-md text-muted-foreground hover:text-rose-500 hover:bg-rose-50 transition-colors"- onClick={() => deleteMutation.mutate(rt.id)}- disabled={deleteMutation.isPending}- >- <Trash2 size={13} />- </button>- </div>- </td>+ {canWrite && (+ <td className="py-3 pr-4 sm:pr-5">+ <div className="flex items-center justify-end gap-1">+ <button+ className="p-1.5 rounded-md text-muted-foreground hover:text-primary hover:bg-primary/5 transition-colors"+ onClick={() => { setEditing(rt); setDialogOpen(true) }}+ >+ <Pencil size={13} />+ </button>+ <button+ className="p-1.5 rounded-md text-muted-foreground hover:text-rose-500 hover:bg-rose-50 transition-colors"+ onClick={() => deleteMutation.mutate(rt.id)}+ disabled={deleteMutation.isPending}+ >+ <Trash2 size={13} />+ </button>+ </div>+ </td>+ )}</tr>))}</tbody>diff --git a/frontend/src/pages/rules.tsx b/frontend/src/pages/rules.tsxindex 5f1e4c04..071c674a 100644--- a/frontend/src/pages/rules.tsx+++ b/frontend/src/pages/rules.tsx@@ -20,6 +20,7 @@ import { Trash2, Plus, RefreshCw, X, Package, Check, ArrowUpDown, ArrowUp, Arrowimport { cn } from '@/lib/utils'import { CategorySelect } from '@/components/category-select'import { PageHeader } from '@/components/page-header'+import { useWorkspace } from '@/contexts/workspace-context'function SectionCard({ children }: { children: React.ReactNode }) {return (@@ -115,6 +116,7 @@ function actionSummary(actions: RuleAction[], categories: Category[], payeesListexport default function RulesPage() {const { t } = useTranslation()const queryClient = useQueryClient()+ const { canWrite } = useWorkspace()const [dialogOpen, setDialogOpen] = useState(false)const [packsDialogOpen, setPacksDialogOpen] = useState(false)const [editing, setEditing] = useState<Rule | null>(null)@@ -231,30 +233,32 @@ export default function RulesPage() {<SectionHeadertitle={t('rules.sectionTitle')}action={- <div className="flex gap-2">- <Button- variant="outline"- size="sm"- className="gap-1.5 h-8"- onClick={() => setPacksDialogOpen(true)}- >- <Package size={12} />- <span className="hidden sm:inline">{t('rules.packs')}</span>- </Button>- <Button- variant="outline"- size="sm"- className="gap-1.5 h-8"- onClick={() => applyAllMutation.mutate()}- disabled={applyAllMutation.isPending}- >- <RefreshCw size={12} />- <span className="hidden sm:inline">{t('rules.reapplyAll')}</span>- </Button>- <Button size="sm" className="gap-1.5 h-8" onClick={() => { setEditing(null); setDialogOpen(true) }}>- <Plus size={13} /> <span className="hidden sm:inline">{t('rules.add')}</span>- </Button>- </div>+ canWrite ? (+ <div className="flex gap-2">+ <Button+ variant="outline"+ size="sm"+ className="gap-1.5 h-8"+ onClick={() => setPacksDialogOpen(true)}+ >+ <Package size={12} />+ <span className="hidden sm:inline">{t('rules.packs')}</span>+ </Button>+ <Button+ variant="outline"+ size="sm"+ className="gap-1.5 h-8"+ onClick={() => applyAllMutation.mutate()}+ disabled={applyAllMutation.isPending}+ >+ <RefreshCw size={12} />+ <span className="hidden sm:inline">{t('rules.reapplyAll')}</span>+ </Button>+ <Button size="sm" className="gap-1.5 h-8" onClick={() => { setEditing(null); setDialogOpen(true) }}>+ <Plus size={13} /> <span className="hidden sm:inline">{t('rules.add')}</span>+ </Button>+ </div>+ ) : undefined}/><div className="px-4 sm:px-5 py-2 bg-muted/50 border-b border-border flex items-center gap-2">@@ -285,8 +289,11 @@ export default function RulesPage() {{sortedRules.map((rule) => (<divkey={rule.id}- className="px-4 sm:px-5 py-3 hover:bg-muted transition-colors cursor-pointer"- onClick={() => { setEditing(rule); setDialogOpen(true) }}+ className={cn(+ 'px-4 sm:px-5 py-3 hover:bg-muted transition-colors',+ canWrite && 'cursor-pointer',+ )}+ onClick={() => { if (canWrite) { setEditing(rule); setDialogOpen(true) } }}><div className="flex items-start justify-between gap-4"><div className="flex-1 min-w-0">@@ -308,15 +315,17 @@ export default function RulesPage() {{actionSummary(rule.actions, categories, payees, t)}</p></div>- <div className="flex items-center gap-1 shrink-0">- <button- className="p-1.5 rounded-md text-muted-foreground hover:text-rose-500 hover:bg-rose-50 transition-colors"- onClick={(e) => { e.stopPropagation(); deleteMutation.mutate(rule.id) }}- disabled={deleteMutation.isPending}- >- <Trash2 size={13} />- </button>- </div>+ {canWrite && (+ <div className="flex items-center gap-1 shrink-0">+ <button+ className="p-1.5 rounded-md text-muted-foreground hover:text-rose-500 hover:bg-rose-50 transition-colors"+ onClick={(e) => { e.stopPropagation(); deleteMutation.mutate(rule.id) }}+ disabled={deleteMutation.isPending}+ >+ <Trash2 size={13} />+ </button>+ </div>+ )}</div></div>))}diff --git a/frontend/src/pages/transactions.tsx b/frontend/src/pages/transactions.tsxindex f40eb721..31297dbb 100644--- a/frontend/src/pages/transactions.tsx+++ b/frontend/src/pages/transactions.tsx@@ -38,6 +38,7 @@ import { BulkAddToGroupDialog, type BulkAddToGroupSubmission } from '@/componentimport { TransactionsFilterBar } from '@/components/transactions-filter-bar'import { usePrivacyMode } from '@/hooks/use-privacy-mode'import { useAuth } from '@/contexts/auth-context'+import { useWorkspace } from '@/contexts/workspace-context'type TransactionUpdatePayload = Partial<Transaction> & {apply_to_transfer_pair?: boolean@@ -65,6 +66,7 @@ export default function TransactionsPage() {const locale = i18n.language === 'en' ? 'en-US' : i18n.languageconst { mask } = usePrivacyMode()const { user } = useAuth()+ const { canWrite } = useWorkspace()const userCurrency = user?.preferences?.currency_display ?? 'USD'const queryClient = useQueryClient()const [page, setPage] = useState(1)@@ -996,7 +998,7 @@ export default function TransactionsPage() {that row's fields; identity-bearing fields (id,transfer_pair_id, splits) are not copied. Hidden forshared rows and transfers — they can't be duplicated. */}- {selectedIds.size === 1 && (() => {+ {canWrite && selectedIds.size === 1 && (() => {const selectedTx = filteredItems.find(tx => selectedIds.has(tx.id))if (!selectedTx || selectedTx.is_shared || selectedTx.transfer_pair_id) return nullreturn (@@ -1009,13 +1011,17 @@ export default function TransactionsPage() {</Button>)})()}- <Button variant="outline" onClick={() => setTransferDialogOpen(true)}>- <ArrowLeftRight size={16} className="mr-1.5" />- {t('transactions.transfer')}- </Button>- <Button onClick={() => { setEditingTx(null); setDialogOpen(true) }}>- + {t('transactions.addManual')}- </Button>+ {canWrite && (+ <>+ <Button variant="outline" onClick={() => setTransferDialogOpen(true)}>+ <ArrowLeftRight size={16} className="mr-1.5" />+ {t('transactions.transfer')}+ </Button>+ <Button onClick={() => { setEditingTx(null); setDialogOpen(true) }}>+ + {t('transactions.addManual')}+ </Button>+ </>+ )}</div>}/>@@ -1131,13 +1137,15 @@ export default function TransactionsPage() {<TableHeader><TableRow className="border-b border-border hover:bg-transparent"><TableHead style={{ width: 40, minWidth: 40 }} className="py-3 pl-4 pr-0">- <input- type="checkbox"- checked={allSelected}- ref={(el) => { if (el) el.indeterminate = someSelected }}- onChange={toggleSelectAll}- className="h-4 w-4 rounded border-border accent-primary cursor-pointer"- />+ {canWrite && (+ <input+ type="checkbox"+ checked={allSelected}+ ref={(el) => { if (el) el.indeterminate = someSelected }}+ onChange={toggleSelectAll}+ className="h-4 w-4 rounded border-border accent-primary cursor-pointer"+ />+ )}</TableHead>{grid.visibleColumns.map(renderHeaderCell)}</TableRow>@@ -1149,13 +1157,14 @@ export default function TransactionsPage() {ref={tx.id === highlightId ? highlightedRowRef : undefined}className={`hover:bg-muted border-b border-border last:border-0 ${selectedIds.has(tx.id) ? 'bg-primary/5' : ''- } ${tx.is_shared ? 'cursor-default' : 'cursor-pointer'}`}+ } ${tx.is_shared || !canWrite ? 'cursor-default' : 'cursor-pointer'}`}onClick={() => {if (tx.is_shared) {// Owned by another user — view in the group context instead.if (tx.group_id) navigate(`/groups/${tx.group_id}`)return}+ if (!canWrite) returnsetEditingTx(tx)setDialogOpen(true)}}@@ -1164,7 +1173,7 @@ export default function TransactionsPage() {{/* Bulk operations are scoped to user.id so theysilently skip shared rows — hide the checkboxon those to avoid the dead-end UX. */}- {!tx.is_shared && (+ {canWrite && !tx.is_shared && (<inputtype="checkbox"checked={selectedIds.has(tx.id)}diff --git a/frontend/src/pages/workspace-settings.tsx b/frontend/src/pages/workspace-settings.tsxnew file mode 100644index 00000000..4a27a850--- /dev/null+++ b/frontend/src/pages/workspace-settings.tsx@@ -0,0 +1,686 @@+import { useEffect, useState } from 'react'+import { useNavigate } from 'react-router-dom'+import { useTranslation } from 'react-i18next'+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+import { toast } from 'sonner'+import { currencies as currenciesApi, workspaces as workspacesApi } from '@/lib/api'+import { useAuth } from '@/contexts/auth-context'+import { useWorkspace } from '@/contexts/workspace-context'+import { Button } from '@/components/ui/button'+import { Input } from '@/components/ui/input'+import { Label } from '@/components/ui/label'+import { Avatar, AvatarFallback } from '@/components/ui/avatar'+import { Badge } from '@/components/ui/badge'+import { Skeleton } from '@/components/ui/skeleton'+import { IconPicker } from '@/components/icon-picker'+import { CategoryIcon } from '@/components/category-icon'+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from '@/components/ui/popover'+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@/components/ui/select'+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog'+import { AlertTriangle, Archive, Plus, Save, Trash2, Users } from 'lucide-react'+import type { WorkspaceMember, WorkspaceRole } from '@/types'++function labelForRole(role: WorkspaceRole, t: (key: string) => string): string {+ return {+ owner: t('workspace.roleOwner'),+ editor: t('workspace.roleEditor'),+ viewer: t('workspace.roleViewer'),+ manager: t('workspace.roleManager'),+ }[role]+}++function hintForRole(role: WorkspaceRole, t: (key: string) => string): string {+ return {+ owner: t('workspace.roleOwnerHint'),+ editor: t('workspace.roleEditorHint'),+ viewer: t('workspace.roleViewerHint'),+ manager: t('workspace.roleManagerHint'),+ }[role]+}++function formatDate(iso: string, locale: string): string {+ try {+ return new Date(iso).toLocaleDateString(locale, {+ day: '2-digit',+ month: 'short',+ year: 'numeric',+ })+ } catch {+ return iso.slice(0, 10)+ }+}++const DEFAULT_WORKSPACE_COLOR = '#6366F1'+const DEFAULT_WORKSPACE_ICON = 'briefcase'++export default function WorkspaceSettingsPage() {+ const { t, i18n } = useTranslation()+ const navigate = useNavigate()+ const { current, canManage, workspaces: allWorkspaces, refresh, switchWorkspace } = useWorkspace()+ const { user: currentUser } = useAuth()+ const queryClient = useQueryClient()++ const [editName, setEditName] = useState('')+ const [editCurrency, setEditCurrency] = useState('')+ const [editLocale, setEditLocale] = useState('')+ const [editIcon, setEditIcon] = useState(DEFAULT_WORKSPACE_ICON)+ const [editColor, setEditColor] = useState(DEFAULT_WORKSPACE_COLOR)+ const [inviteOpen, setInviteOpen] = useState(false)+ const [inviteEmail, setInviteEmail] = useState('')+ const [invitePassword, setInvitePassword] = useState('')+ const [inviteRole, setInviteRole] = useState<WorkspaceRole>('editor')+ const [removeTarget, setRemoveTarget] = useState<WorkspaceMember | null>(null)+ const [archiveOpen, setArchiveOpen] = useState(false)++ useEffect(() => {+ if (!current) return+ setEditName(current.name)+ setEditCurrency(current.default_currency)+ setEditLocale(current.locale ?? '')+ setEditIcon(current.icon ?? DEFAULT_WORKSPACE_ICON)+ setEditColor(current.color ?? DEFAULT_WORKSPACE_COLOR)+ }, [current?.id, current?.name, current?.default_currency, current?.locale, current?.icon, current?.color])++ const membersQuery = useQuery({+ queryKey: ['workspace-members', current?.id],+ queryFn: () => (current ? workspacesApi.listMembers(current.id) : Promise.resolve([])),+ enabled: !!current,+ })++ const { data: supportedCurrencies } = useQuery({+ queryKey: ['currencies'],+ queryFn: currenciesApi.list,+ staleTime: Infinity,+ })++ const statsQuery = useQuery({+ queryKey: ['workspace-stats', current?.id],+ queryFn: () => (current ? workspacesApi.stats(current.id) : Promise.resolve({ members: 0, accounts: 0, transactions: 0 })),+ enabled: !!current,+ })++ const updateMutation = useMutation({+ mutationFn: () => {+ if (!current) throw new Error('No workspace')+ return workspacesApi.update(current.id, {+ name: editName,+ default_currency: editCurrency,+ locale: editLocale || (null as unknown as string),+ icon: editIcon,+ color: editColor,+ })+ },+ onSuccess: () => {+ toast.success(t('workspace.saveSuccess'))+ void refresh()+ },+ onError: (e: unknown) => {+ const detail =+ (e as { response?: { data?: { detail?: string } } })?.response?.data?.detail ||+ (e instanceof Error ? e.message : t('workspace.saveError'))+ toast.error(detail)+ },+ })++ const archiveMutation = useMutation({+ mutationFn: () => {+ if (!current) throw new Error('No workspace')+ return workspacesApi.archive(current.id)+ },+ onSuccess: async () => {+ toast.success(t('workspace.archiveSuccess', 'Workspace arquivado'))+ setArchiveOpen(false)+ await refresh()+ // Switch into another accessible workspace, then redirect home.+ const remaining = allWorkspaces.filter((w) => w.id !== current?.id)+ if (remaining.length > 0) {+ await switchWorkspace(remaining[0].id)+ }+ navigate('/')+ },+ onError: (e: unknown) => {+ const detail =+ (e as { response?: { data?: { detail?: string } } })?.response?.data?.detail ||+ (e instanceof Error ? e.message : 'Failed')+ toast.error(detail)+ },+ })++ const inviteMutation = useMutation({+ mutationFn: () => {+ if (!current) throw new Error('No workspace')+ return workspacesApi.invite(current.id, {+ email: inviteEmail.trim(),+ role: inviteRole,+ password: invitePassword || undefined,+ })+ },+ onSuccess: () => {+ toast.success(t('workspace.addSuccess'))+ setInviteOpen(false)+ setInviteEmail('')+ setInvitePassword('')+ setInviteRole('editor')+ queryClient.invalidateQueries({ queryKey: ['workspace-members', current?.id] })+ queryClient.invalidateQueries({ queryKey: ['workspace-stats', current?.id] })+ },+ onError: (e: unknown) => {+ const detail =+ (e as { response?: { data?: { detail?: string } } })?.response?.data?.detail ||+ (e instanceof Error ? e.message : 'Failed')+ toast.error(detail)+ },+ })++ const removeMutation = useMutation({+ mutationFn: (member: WorkspaceMember) => {+ if (!current) throw new Error('No workspace')+ return workspacesApi.removeMember(current.id, member.user_id)+ },+ onSuccess: () => {+ toast.success(t('workspace.removeSuccess'))+ setRemoveTarget(null)+ queryClient.invalidateQueries({ queryKey: ['workspace-members', current?.id] })+ queryClient.invalidateQueries({ queryKey: ['workspace-stats', current?.id] })+ },+ onError: (e: unknown) => {+ const detail =+ (e as { response?: { data?: { detail?: string } } })?.response?.data?.detail ||+ (e instanceof Error ? e.message : 'Failed')+ toast.error(detail)+ },+ })++ const roleChangeMutation = useMutation({+ mutationFn: ({ member, role }: { member: WorkspaceMember; role: WorkspaceRole }) => {+ if (!current) throw new Error('No workspace')+ return workspacesApi.changeRole(current.id, member.user_id, role)+ },+ onSuccess: () => {+ toast.success(t('workspace.roleUpdated'))+ queryClient.invalidateQueries({ queryKey: ['workspace-members', current?.id] })+ },+ onError: (e: unknown) => {+ const detail =+ (e as { response?: { data?: { detail?: string } } })?.response?.data?.detail ||+ (e instanceof Error ? e.message : 'Failed')+ toast.error(detail)+ },+ })++ if (!current) {+ return (+ <div className="container max-w-5xl py-8 space-y-4">+ <Skeleton className="h-24 w-full" />+ <Skeleton className="h-64 w-full" />+ </div>+ )+ }++ const members = membersQuery.data ?? []+ const stats = statsQuery.data ?? { members: 1, accounts: 0, transactions: 0 }+ const isManaged = !!current.managed_by_user_id+ const isManagerSelf = isManaged && current.managed_by_user_id === currentUser?.id+ const localeForFormat = i18n.language === 'pt-BR' ? 'pt-BR' : 'en-US'++ return (+ <div className="container max-w-5xl py-8 space-y-6">+ {/* Header card — identity + role + stats strip */}+ <section className="rounded-xl border bg-card overflow-hidden">+ <div className="p-6 flex items-center gap-5 border-b">+ <CategoryIcon+ icon={current.icon ?? DEFAULT_WORKSPACE_ICON}+ color={current.color ?? DEFAULT_WORKSPACE_COLOR}+ size="lg"+ className="shrink-0"+ />+ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-2 flex-wrap">+ <h1 className="text-xl font-semibold truncate">{current.name}</h1>+ {current.role && (+ <Badge variant="secondary" className="text-[11px]">+ {labelForRole(current.role, t)}+ </Badge>+ )}+ {isManaged && (+ <Badge variant="outline" className="text-[11px]">+ {isManagerSelf+ ? t('workspace.youManageThis')+ : t('workspace.externallyManaged')}+ </Badge>+ )}+ </div>+ <p className="text-sm text-muted-foreground mt-1">+ {t('workspace.settingsDescription')}+ </p>+ </div>+ </div>+ <div className="grid grid-cols-2 sm:grid-cols-4 divide-x divide-border">+ <StatTile label={t('workspace.members')} value={String(stats.members)} />+ <StatTile label={t('workspace.statAccounts', 'Contas')} value={String(stats.accounts)} />+ <StatTile label={t('workspace.statTransactions', 'Transações')} value={String(stats.transactions)} />+ <StatTile label={t('workspace.statCreatedAt', 'Criado em')} value={formatDate(current.created_at, localeForFormat)} />+ </div>+ </section>++ {/* Details card — 4-column form */}+ <section className="space-y-4 rounded-xl border bg-card p-6">+ <div className="flex items-center justify-between">+ <h2 className="text-base font-semibold">{t('workspace.details')}</h2>+ {canManage && (+ <Button+ onClick={() => updateMutation.mutate()}+ disabled={updateMutation.isPending}+ className="rounded-lg"+ size="sm"+ >+ <Save className="mr-2 h-4 w-4" />+ {updateMutation.isPending ? t('common.loading') : t('common.save')}+ </Button>+ )}+ </div>+ <div className="space-y-4">+ {/* Identity row — icon button + color swatch align with the+ input (not the label) so the label sits over the name+ field only. */}+ <div className="flex items-end gap-2">+ {canManage ? (+ <>+ <div className="space-y-1.5">+ <Label className="text-[13px]">+ {t('workspace.icon', 'Ícone')}+ </Label>+ <Popover>+ <PopoverTrigger asChild>+ <button+ type="button"+ className="h-10 w-10 rounded-lg border border-input flex items-center justify-center hover:bg-muted/40 transition-colors shrink-0"+ title={t('workspace.icon', 'Ícone')}+ >+ <CategoryIcon icon={editIcon} color={editColor} size="sm" />+ </button>+ </PopoverTrigger>+ <PopoverContent className="w-80 p-3" align="start">+ <IconPicker value={editIcon} color={editColor} onChange={setEditIcon} />+ </PopoverContent>+ </Popover>+ </div>+ <div className="space-y-1.5">+ <Label htmlFor="ws-color" className="text-[13px]">+ {t('groups.color', 'Cor')}+ </Label>+ <input+ id="ws-color"+ type="color"+ value={editColor}+ onChange={(e) => setEditColor(e.target.value)}+ className="h-10 w-10 p-1 rounded-lg cursor-pointer border border-input bg-background shrink-0"+ title={t('groups.color', 'Cor')}+ />+ </div>+ </>+ ) : (+ <div className="h-10 w-10 rounded-lg flex items-center justify-center shrink-0">+ <CategoryIcon icon={editIcon} color={editColor} size="sm" />+ </div>+ )}+ <div className="space-y-1.5 flex-1">+ <Label htmlFor="ws-name" className="text-[13px]">+ {t('workspace.name')}+ </Label>+ <Input+ id="ws-name"+ value={editName}+ onChange={(e) => setEditName(e.target.value)}+ disabled={!canManage}+ maxLength={100}+ className="h-10 rounded-lg w-full"+ />+ </div>+ </div>++ {/* Region row — currency + locale */}+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4">+ <div className="space-y-1.5">+ <Label htmlFor="ws-currency" className="text-[13px]">+ {t('workspace.defaultCurrency')}+ </Label>+ <Select+ value={editCurrency}+ onValueChange={setEditCurrency}+ disabled={!canManage}+ >+ <SelectTrigger id="ws-currency" className="h-10 rounded-lg w-full">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {(supportedCurrencies ?? [{ code: editCurrency, symbol: editCurrency, name: editCurrency, flag: '' }]).map((c) => (+ <SelectItem key={c.code} value={c.code}>+ <span className="mr-2">{c.flag}</span>+ {c.name}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ <div className="space-y-1.5">+ <Label htmlFor="ws-locale" className="text-[13px]">+ {t('workspace.locale')}+ </Label>+ <Select+ value={editLocale || '__none__'}+ onValueChange={(v) => setEditLocale(v === '__none__' ? '' : v)}+ disabled={!canManage}+ >+ <SelectTrigger id="ws-locale" className="h-10 rounded-lg w-full">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="__none__">—</SelectItem>+ <SelectItem value="en">English</SelectItem>+ <SelectItem value="pt-BR">Português (BR)</SelectItem>+ </SelectContent>+ </Select>+ </div>+ </div>+ </div>+ </section>++ {/* Members card */}+ <section className="space-y-4 rounded-xl border bg-card p-6">+ <div className="flex items-center justify-between">+ <div className="flex items-center gap-2">+ <Users className="h-4 w-4 text-muted-foreground" />+ <h2 className="text-base font-semibold">{t('workspace.members')}</h2>+ <Badge variant="outline" className="text-[11px]">+ {members.length}+ </Badge>+ </div>+ {canManage && (+ <Button onClick={() => setInviteOpen(true)} size="sm" className="rounded-lg">+ <Plus className="mr-2 h-4 w-4" />+ {t('workspace.addMember')}+ </Button>+ )}+ </div>++ {membersQuery.isLoading ? (+ <Skeleton className="h-16 w-full" />+ ) : members.length === 0 ? (+ <p className="text-sm text-muted-foreground">+ {t('workspace.noMembers')} {canManage && t('workspace.noMembersHint')}+ </p>+ ) : (+ <ul className="divide-y rounded-lg border">+ {members.map((m) => {+ const isMe = m.user_id === currentUser?.id+ return (+ <li+ key={m.id}+ className="py-3 px-4 flex items-center gap-3 hover:bg-muted/30 transition-colors"+ >+ <Avatar className="h-9 w-9">+ <AvatarFallback className="bg-primary/15 text-primary text-xs font-semibold">+ {(m.display_name || m.email).slice(0, 2).toUpperCase()}+ </AvatarFallback>+ </Avatar>+ <div className="flex-1 min-w-0">+ <p className="text-sm font-medium truncate">+ {m.display_name || m.email}+ {isMe && (+ <span className="ml-2 text-xs text-muted-foreground">+ ({t('workspace.you')})+ </span>+ )}+ </p>+ {m.display_name && (+ <p className="text-xs text-muted-foreground truncate">{m.email}</p>+ )}+ </div>+ {canManage && !isMe ? (+ <select+ value={m.role}+ onChange={(e) =>+ roleChangeMutation.mutate({+ member: m,+ role: e.target.value as WorkspaceRole,+ })+ }+ className="h-9 w-32 rounded-lg border border-input bg-background px-2 text-sm"+ >+ {(['owner', 'editor', 'viewer'] as WorkspaceRole[]).map((r) => (+ <option key={r} value={r}>+ {labelForRole(r, t)}+ </option>+ ))}+ </select>+ ) : (+ <Badge variant="secondary" className="text-[11px]">+ {labelForRole(m.role, t)}+ </Badge>+ )}+ {canManage && !isMe && (+ <Button+ variant="ghost"+ size="icon"+ onClick={() => setRemoveTarget(m)}+ title={t('workspace.remove')}+ className="rounded-lg"+ >+ <Trash2 className="h-4 w-4 text-destructive" />+ </Button>+ )}+ </li>+ )+ })}+ </ul>+ )}+ </section>++ {/* Danger zone — owners only */}+ {canManage && (+ <section className="space-y-4 rounded-xl border bg-card p-6">+ <div className="flex items-center justify-between">+ <div className="flex items-center gap-2">+ <AlertTriangle className="h-4 w-4 text-muted-foreground" />+ <h2 className="text-base font-semibold">+ {t('workspace.dangerZone', 'Zona de perigo')}+ </h2>+ </div>+ </div>+ <div className="flex items-center justify-between gap-4">+ <div>+ <p className="text-sm font-medium">+ {t('workspace.archiveAction', 'Arquivar workspace')}+ </p>+ <p className="text-xs text-muted-foreground mt-0.5">+ {t(+ 'workspace.archiveHint',+ 'O workspace fica oculto da lista e do switcher. Os dados continuam preservados.',+ )}+ </p>+ </div>+ <Button+ variant="outline"+ size="sm"+ className="rounded-lg text-destructive hover:bg-destructive/10 hover:text-destructive"+ onClick={() => setArchiveOpen(true)}+ >+ <Archive className="mr-2 h-4 w-4" />+ {t('workspace.archive', 'Arquivar')}+ </Button>+ </div>+ </section>+ )}++ {/* Invite dialog */}+ <Dialog open={inviteOpen} onOpenChange={setInviteOpen}>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>{t('workspace.addMemberTitle')}</DialogTitle>+ <DialogDescription>{t('workspace.addMemberDescription')}</DialogDescription>+ </DialogHeader>+ <div className="space-y-4 py-1">+ <div className="space-y-1.5">+ <Label htmlFor="invite-email" className="text-[13px]">+ {t('admin.users.email', 'Email')}+ </Label>+ <Input+ id="invite-email"+ type="email"+ value={inviteEmail}+ onChange={(e) => setInviteEmail(e.target.value)}+ autoFocus+ className="h-10 rounded-lg"+ placeholder="[email protected]"+ />+ </div>+ <div className="space-y-1.5">+ <Label htmlFor="invite-role" className="text-[13px]">+ {t('workspace.role')}+ </Label>+ <select+ id="invite-role"+ value={inviteRole}+ onChange={(e) => setInviteRole(e.target.value as WorkspaceRole)}+ className="w-full h-10 rounded-lg border border-input bg-background px-3 text-sm"+ >+ {(['owner', 'editor', 'viewer'] as WorkspaceRole[]).map((r) => (+ <option key={r} value={r}>+ {labelForRole(r, t)} — {hintForRole(r, t)}+ </option>+ ))}+ </select>+ </div>+ <div className="space-y-1.5">+ <Label htmlFor="invite-password" className="text-[13px]">+ {t('workspace.passwordForNewUsers')}+ </Label>+ <Input+ id="invite-password"+ type="password"+ value={invitePassword}+ onChange={(e) => setInvitePassword(e.target.value)}+ className="h-10 rounded-lg"+ placeholder=""+ />+ <p className="text-[11px] text-muted-foreground leading-relaxed">+ {t('workspace.passwordHint')}+ </p>+ </div>+ </div>+ <DialogFooter>+ <Button+ variant="outline"+ onClick={() => setInviteOpen(false)}+ className="rounded-lg"+ >+ {t('common.cancel')}+ </Button>+ <Button+ onClick={() => inviteMutation.mutate()}+ disabled={inviteMutation.isPending || !inviteEmail.trim()}+ className="rounded-lg"+ >+ {inviteMutation.isPending ? t('common.loading') : t('common.save')}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>++ {/* Remove member dialog */}+ <Dialog+ open={!!removeTarget}+ onOpenChange={(open) => !open && setRemoveTarget(null)}+ >+ <DialogContent>+ <DialogHeader>+ <DialogTitle>{t('workspace.removeConfirmTitle')}</DialogTitle>+ <DialogDescription>+ {t('workspace.removeConfirmDescription', { email: removeTarget?.email })}+ </DialogDescription>+ </DialogHeader>+ <DialogFooter>+ <Button+ variant="outline"+ onClick={() => setRemoveTarget(null)}+ className="rounded-lg"+ >+ {t('common.cancel')}+ </Button>+ <Button+ variant="destructive"+ onClick={() => removeTarget && removeMutation.mutate(removeTarget)}+ disabled={removeMutation.isPending}+ className="rounded-lg"+ >+ {removeMutation.isPending ? t('common.loading') : t('workspace.remove')}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>++ {/* Archive workspace dialog */}+ <Dialog open={archiveOpen} onOpenChange={setArchiveOpen}>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>+ {t('workspace.archiveConfirmTitle', 'Arquivar workspace?')}+ </DialogTitle>+ <DialogDescription>+ {t(+ 'workspace.archiveConfirmDescription',+ 'O workspace "{{name}}" será removido da sua lista. Os dados ficam preservados e um admin pode restaurar mais tarde.',+ { name: current.name },+ )}+ </DialogDescription>+ </DialogHeader>+ <DialogFooter>+ <Button+ variant="outline"+ onClick={() => setArchiveOpen(false)}+ className="rounded-lg"+ >+ {t('common.cancel')}+ </Button>+ <Button+ variant="destructive"+ onClick={() => archiveMutation.mutate()}+ disabled={archiveMutation.isPending}+ className="rounded-lg"+ >+ <Archive className="mr-2 h-4 w-4" />+ {archiveMutation.isPending ? t('common.loading') : t('workspace.archive', 'Arquivar')}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </div>+ )+}++function StatTile({ label, value }: { label: string; value: string }) {+ return (+ <div className="px-6 py-4">+ <p className="text-[11px] uppercase tracking-wider text-muted-foreground">{label}</p>+ <p className="text-lg font-semibold mt-1">{value}</p>+ </div>+ )+}diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.tsindex 99f08a82..28364933 100644--- a/frontend/src/types/index.ts+++ b/frontend/src/types/index.ts@@ -27,6 +27,32 @@ export interface AppSetting {value: string}+export type WorkspaceRole = 'owner' | 'editor' | 'viewer' | 'manager'++export interface Workspace {+ id: string+ name: string+ kind: string+ is_archived: boolean+ default_currency: string+ locale: string | null+ icon: string | null+ color: string | null+ created_at: string+ created_by_user_id: string | null+ managed_by_user_id: string | null+ role: WorkspaceRole | null+}++export interface WorkspaceMember {+ id: string+ user_id: string+ email: string+ display_name: string | null+ role: WorkspaceRole+ joined_at: string+}+export interface UserPreferences {language?: stringdate_format?: string