Open-source personal finance manager. Self-hosted, privacy-first.
feat: add collections to filter the app by account & wallet groups (#276)
Tássio Noronha52d7303b2f2b
diff --git a/backend/alembic/versions/055_collections.py b/backend/alembic/versions/055_collections.pynew file mode 100644index 00000000..3b07d4c8--- /dev/null+++ b/backend/alembic/versions/055_collections.py@@ -0,0 +1,48 @@+"""add collections (account groups for reporting/filtering)++Revision ID: 055+Revises: 054+Create Date: 2026-06-05+"""++from alembic import op+import sqlalchemy as sa+from sqlalchemy.dialects.postgresql import UUID++revision = "055"+down_revision = "054"+branch_labels = None+depends_on = None+++def upgrade() -> None:+ op.create_table(+ "collections",+ sa.Column("id", UUID(as_uuid=True), nullable=False),+ sa.Column("user_id", UUID(as_uuid=True), nullable=False),+ sa.Column("workspace_id", UUID(as_uuid=True), nullable=False),+ sa.Column("name", sa.String(length=100), nullable=False),+ sa.Column("icon", sa.String(length=50), nullable=False, server_default="folder"),+ sa.Column("color", sa.String(length=7), nullable=False, server_default="#6366F1"),+ sa.Column("position", sa.Integer(), nullable=False, server_default="0"),+ sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),+ sa.ForeignKeyConstraint(["user_id"], ["users.id"]),+ sa.ForeignKeyConstraint(["workspace_id"], ["workspaces.id"], ondelete="CASCADE"),+ sa.PrimaryKeyConstraint("id"),+ )+ op.create_index("ix_collections_workspace_id", "collections", ["workspace_id"])++ op.create_table(+ "collection_accounts",+ sa.Column("collection_id", UUID(as_uuid=True), nullable=False),+ sa.Column("account_id", UUID(as_uuid=True), nullable=False),+ sa.ForeignKeyConstraint(["collection_id"], ["collections.id"], ondelete="CASCADE"),+ sa.ForeignKeyConstraint(["account_id"], ["accounts.id"], ondelete="CASCADE"),+ sa.PrimaryKeyConstraint("collection_id", "account_id"),+ )+++def downgrade() -> None:+ op.drop_table("collection_accounts")+ op.drop_index("ix_collections_workspace_id", table_name="collections")+ op.drop_table("collections")diff --git a/backend/alembic/versions/056_collection_wallets.py b/backend/alembic/versions/056_collection_wallets.pynew file mode 100644index 00000000..759e0855--- /dev/null+++ b/backend/alembic/versions/056_collection_wallets.py@@ -0,0 +1,30 @@+"""add collection <-> wallet (asset_group) membership++Revision ID: 056+Revises: 055+Create Date: 2026-06-05+"""++from alembic import op+import sqlalchemy as sa+from sqlalchemy.dialects.postgresql import UUID++revision = "056"+down_revision = "055"+branch_labels = None+depends_on = None+++def upgrade() -> None:+ op.create_table(+ "collection_asset_groups",+ sa.Column("collection_id", UUID(as_uuid=True), nullable=False),+ sa.Column("asset_group_id", UUID(as_uuid=True), nullable=False),+ sa.ForeignKeyConstraint(["collection_id"], ["collections.id"], ondelete="CASCADE"),+ sa.ForeignKeyConstraint(["asset_group_id"], ["asset_groups.id"], ondelete="CASCADE"),+ sa.PrimaryKeyConstraint("collection_id", "asset_group_id"),+ )+++def downgrade() -> None:+ op.drop_table("collection_asset_groups")diff --git a/backend/app/api/collections.py b/backend/app/api/collections.pynew file mode 100644index 00000000..255bad54--- /dev/null+++ b/backend/app/api/collections.py@@ -0,0 +1,58 @@+import uuid++from fastapi import APIRouter, Depends, HTTPException, status+from sqlalchemy.ext.asyncio import AsyncSession++from app.core.database import get_async_session+from app.core.workspace_context import (+ WorkspaceContext,+ current_workspace,+ current_writable_workspace,+)+from app.schemas.collection import CollectionCreate, CollectionRead, CollectionUpdate+from app.services import collection_service++router = APIRouter(prefix="/api/collections", tags=["collections"])++[email protected]("", response_model=list[CollectionRead])+async def list_collections(+ ctx: WorkspaceContext = Depends(current_workspace),+ session: AsyncSession = Depends(get_async_session),+):+ return await collection_service.get_collections(session, ctx.workspace.id)++[email protected]("", response_model=CollectionRead, status_code=status.HTTP_201_CREATED)+async def create_collection(+ data: CollectionCreate,+ ctx: WorkspaceContext = Depends(current_writable_workspace),+ session: AsyncSession = Depends(get_async_session),+):+ return await collection_service.create_collection(session, ctx.workspace.id, ctx.user_id, data)++[email protected]("/{collection_id}", response_model=CollectionRead)+async def update_collection(+ collection_id: uuid.UUID,+ data: CollectionUpdate,+ ctx: WorkspaceContext = Depends(current_writable_workspace),+ session: AsyncSession = Depends(get_async_session),+):+ collection = await collection_service.update_collection(+ session, collection_id, ctx.workspace.id, data+ )+ if not collection:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Collection not found")+ return collection++[email protected]("/{collection_id}", status_code=status.HTTP_204_NO_CONTENT)+async def delete_collection(+ collection_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(current_writable_workspace),+ session: AsyncSession = Depends(get_async_session),+):+ deleted = await collection_service.delete_collection(session, collection_id, ctx.workspace.id)+ if not deleted:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Collection not found")diff --git a/backend/app/api/dashboard.py b/backend/app/api/dashboard.pyindex b4cc99c1..f3540061 100644--- a/backend/app/api/dashboard.py+++ b/backend/app/api/dashboard.py@@ -1,3 +1,4 @@+import uuidfrom datetime import datefrom typing import Optional@@ -16,44 +17,50 @@ router = APIRouter(prefix="/api/dashboard", tags=["dashboard"])async def get_summary(month: Optional[date] = Query(None),balance_date: Optional[date] = Query(None),+ account_ids: Optional[list[uuid.UUID]] = Query(None),+ asset_group_ids: Optional[list[uuid.UUID]] = Query(None),ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),):return await dashboard_service.get_summary(- session, ctx.workspace.id, ctx.user_id, month, balance_date+ session, ctx.workspace.id, ctx.user_id, month, balance_date, account_ids,+ asset_group_ids,)@router.get("/spending-by-category", response_model=list[SpendingByCategory])async def get_spending_by_category(month: Optional[date] = Query(None),+ account_ids: Optional[list[uuid.UUID]] = Query(None),ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),):return await dashboard_service.get_spending_by_category(- session, ctx.workspace.id, ctx.user_id, month+ session, ctx.workspace.id, ctx.user_id, month, account_ids)@router.get("/monthly-trend", response_model=list[MonthlyTrend])async def get_monthly_trend(months: int = Query(6, ge=1, le=12),+ account_ids: Optional[list[uuid.UUID]] = Query(None),ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),):return await dashboard_service.get_monthly_trend(- session, ctx.workspace.id, ctx.user_id, months+ session, ctx.workspace.id, ctx.user_id, months, account_ids)@router.get("/balance-history", response_model=BalanceHistory)async def get_balance_history(month: Optional[date] = Query(None),+ account_ids: Optional[list[uuid.UUID]] = Query(None),ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),):return await dashboard_service.get_balance_history(- session, ctx.workspace.id, ctx.user_id, month+ session, ctx.workspace.id, ctx.user_id, month, account_ids)diff --git a/backend/app/api/reports.py b/backend/app/api/reports.pyindex 1772c4f6..9ad98f81 100644--- a/backend/app/api/reports.py+++ b/backend/app/api/reports.py@@ -1,3 +1,6 @@+import uuid+from typing import Optional+from fastapi import APIRouter, Depends, Queryfrom sqlalchemy.ext.asyncio import AsyncSession@@ -13,18 +16,15 @@ 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)$"),+ account_ids: Optional[list[uuid.UUID]] = Query(None),+ asset_group_ids: Optional[list[uuid.UUID]] = Query(None),period: str | None = Query(None, pattern="^ytd$"),ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),):return await report_service.get_net_worth_report(- session,- ctx.workspace.id,- ctx.user_id,- months,- interval,- ctx.user.primary_currency,- period=period,+ session, ctx.workspace.id, ctx.user_id, months, interval, ctx.user.primary_currency,+ account_ids=account_ids, asset_group_ids=asset_group_ids, period=period,)@@ -32,18 +32,14 @@ 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)$"),+ account_ids: Optional[list[uuid.UUID]] = Query(None),period: str | None = Query(None, pattern="^ytd$"),ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),):return await report_service.get_income_expenses_report(- session,- ctx.workspace.id,- ctx.user_id,- months,- interval,- ctx.user.primary_currency,- period=period,+ session, ctx.workspace.id, ctx.user_id, months, interval, ctx.user.primary_currency,+ account_ids=account_ids, period=period,)@@ -52,9 +48,11 @@ 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),+ account_ids: Optional[list[uuid.UUID]] = Query(None),ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),):return await report_service.get_cash_flow_report(- session, ctx.workspace.id, ctx.user_id, months, interval, ctx.user.primary_currency, baseline=baseline,+ session, ctx.workspace.id, ctx.user_id, months, interval, ctx.user.primary_currency,+ baseline=baseline, account_ids=account_ids,)diff --git a/backend/app/main.py b/backend/app/main.pyindex 9f0a735a..286d1fce 100644--- a/backend/app/main.py+++ b/backend/app/main.py@@ -21,6 +21,7 @@ from app.api.recurring_transactions import router as recurring_routerfrom app.api.rules import router as rules_routerfrom app.api.assets import router as assets_routerfrom app.api.asset_groups import router as asset_groups_router+from app.api.collections import router as collections_routerfrom app.api.reports import router as reports_routerfrom app.api.search import router as search_routerfrom app.api.setup import router as setup_router@@ -124,6 +125,7 @@ app.include_router(goals_router)app.include_router(groups_router)app.include_router(assets_router)app.include_router(asset_groups_router)+app.include_router(collections_router)app.include_router(dashboard_router)app.include_router(reports_router)app.include_router(search_router)diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.pyindex e4f4aa67..7087066a 100644--- a/backend/app/models/__init__.py+++ b/backend/app/models/__init__.py@@ -21,6 +21,7 @@ from app.models.credit_card_bill import CreditCardBillfrom app.models.group import Group, GroupMemberfrom app.models.transaction_split import TransactionSplitfrom app.models.group_settlement import GroupSettlement+from app.models.collection import Collection, collection_accounts, collection_asset_groups# Side-effect import: register the before_insert listener that auto-stamps# workspace_id from user_id on financial entities. Imported last so all@@ -54,4 +55,7 @@ __all__ = ["GroupMember","TransactionSplit","GroupSettlement",+ "Collection",+ "collection_accounts",+ "collection_asset_groups",]diff --git a/backend/app/models/collection.py b/backend/app/models/collection.pynew file mode 100644index 00000000..ba58bc28--- /dev/null+++ b/backend/app/models/collection.py@@ -0,0 +1,90 @@+import uuid+from datetime import datetime+from typing import TYPE_CHECKING++from sqlalchemy import Column, DateTime, ForeignKey, Integer, String, Table, func+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.account import Account+ from app.models.asset_group import AssetGroup+ from app.models.user import User+++# Many-to-many: a collection bundles accounts; an account can belong to many+# collections. Rows cascade-delete with either side so deleting a collection+# or an account never leaves dangling membership.+collection_accounts = Table(+ "collection_accounts",+ Base.metadata,+ Column(+ "collection_id",+ UUID(as_uuid=True),+ ForeignKey("collections.id", ondelete="CASCADE"),+ primary_key=True,+ ),+ Column(+ "account_id",+ UUID(as_uuid=True),+ ForeignKey("accounts.id", ondelete="CASCADE"),+ primary_key=True,+ ),+)+++# Many-to-many: a collection can also bundle asset "wallets" (asset_groups),+# so net-worth/reports for the collection include those wallets' assets.+# Individual assets aren't added directly — only wallets — which keeps+# membership stable as assets flow in/out of a wallet.+collection_asset_groups = Table(+ "collection_asset_groups",+ Base.metadata,+ Column(+ "collection_id",+ UUID(as_uuid=True),+ ForeignKey("collections.id", ondelete="CASCADE"),+ primary_key=True,+ ),+ Column(+ "asset_group_id",+ UUID(as_uuid=True),+ ForeignKey("asset_groups.id", ondelete="CASCADE"),+ primary_key=True,+ ),+)+++class Collection(Base):+ """A user-defined, named group of accounts used to filter the app's+ views (dashboard, reports, transactions) — issue #105.++ Cross-cutting and many-to-many: an account can belong to several+ collections simultaneously. Workspace-scoped. Deliberately distinct from+ expense-splitting "Groups" (people) and asset "Wallets" (asset_groups):+ this is a reporting/filter lens over the accounts you already have.+ """++ __tablename__ = "collections"++ 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="#6366F1")+ position: Mapped[int] = mapped_column(Integer, default=0)+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())++ # Eager-load members so reads can expose account_ids without an N+1.+ accounts: Mapped[list["Account"]] = relationship(+ secondary=collection_accounts, lazy="selectin"+ )+ asset_groups: Mapped[list["AssetGroup"]] = relationship(+ secondary=collection_asset_groups, lazy="selectin"+ )+ user: Mapped["User"] = relationship()diff --git a/backend/app/schemas/collection.py b/backend/app/schemas/collection.pynew file mode 100644index 00000000..6e9f5a1a--- /dev/null+++ b/backend/app/schemas/collection.py@@ -0,0 +1,39 @@+import uuid+from typing import Optional++from pydantic import BaseModel, ConfigDict, Field+++class CollectionBase(BaseModel):+ name: str = Field(min_length=1, max_length=100)+ icon: str = "folder"+ color: str = "#6366F1"+ position: int = 0+++class CollectionCreate(CollectionBase):+ # Accounts and wallets (asset_groups) to include. Empty is allowed.+ account_ids: list[uuid.UUID] = []+ wallet_ids: list[uuid.UUID] = []+++class CollectionUpdate(BaseModel):+ name: Optional[str] = Field(default=None, min_length=1, max_length=100)+ icon: Optional[str] = None+ color: Optional[str] = None+ position: Optional[int] = None+ # When provided, replaces that membership wholesale. None leaves it untouched.+ account_ids: Optional[list[uuid.UUID]] = None+ wallet_ids: Optional[list[uuid.UUID]] = None+++class CollectionRead(CollectionBase):+ id: uuid.UUID+ user_id: uuid.UUID+ account_ids: list[uuid.UUID] = []+ account_count: int = 0+ # Asset wallets (asset_groups) in this collection.+ wallet_ids: list[uuid.UUID] = []+ wallet_count: int = 0++ model_config = ConfigDict(from_attributes=True)diff --git a/backend/app/services/asset_service.py b/backend/app/services/asset_service.pyindex 82624641..eea8a9f1 100644--- a/backend/app/services/asset_service.py+++ b/backend/app/services/asset_service.py@@ -716,6 +716,7 @@ async def get_asset_values_at(primary_currency: Optional[str] = None,*,by_workspace: bool = False,+ group_ids: Optional[list[uuid.UUID]] = None,) -> tuple[dict[str, float], float]:"""Return (per_currency_totals, primary_total) for all active assets.@@ -732,13 +733,18 @@ async def get_asset_values_at(scope_filter = (Asset.workspace_id == scope_id if by_workspace else Asset.user_id == scope_id)- result = await session.execute(- select(Asset).where(- scope_filter,- Asset.is_archived == False,- Asset.sell_date.is_(None),- )+ # `group_ids` restricts to assets in a Collection's wallets (issue #105).+ # An empty list means "no wallets in this collection" → no assets.+ if group_ids is not None and len(group_ids) == 0:+ return {}, 0.0+ stmt = select(Asset).where(+ scope_filter,+ Asset.is_archived == False,+ Asset.sell_date.is_(None),)+ if group_ids:+ stmt = stmt.where(Asset.group_id.in_(group_ids))+ result = await session.execute(stmt)assets = list(result.scalars().all())totals: dict[str, float] = {}diff --git a/backend/app/services/collection_service.py b/backend/app/services/collection_service.pynew file mode 100644index 00000000..1106bba1--- /dev/null+++ b/backend/app/services/collection_service.py@@ -0,0 +1,150 @@+import uuid+from typing import Optional++from sqlalchemy import func, select+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.account import Account+from app.models.asset_group import AssetGroup+from app.models.collection import Collection+from app.schemas.collection import CollectionCreate, CollectionRead, CollectionUpdate+++def _to_read(collection: Collection) -> CollectionRead:+ # Members are eager-loaded (selectin) so this is N+1-free.+ account_ids = [a.id for a in collection.accounts]+ wallet_ids = [g.id for g in collection.asset_groups]+ return CollectionRead(+ id=collection.id,+ user_id=collection.user_id,+ name=collection.name,+ icon=collection.icon,+ color=collection.color,+ position=collection.position,+ account_ids=account_ids,+ account_count=len(account_ids),+ wallet_ids=wallet_ids,+ wallet_count=len(wallet_ids),+ )+++async def _accounts_in_workspace(+ session: AsyncSession, workspace_id: uuid.UUID, account_ids: list[uuid.UUID]+) -> list[Account]:+ """Resolve account ids to Account rows, scoped to the workspace so a+ collection can never reference accounts from another workspace."""+ if not account_ids:+ return []+ result = await session.execute(+ select(Account).where(+ Account.workspace_id == workspace_id,+ Account.id.in_(account_ids),+ )+ )+ return list(result.scalars().all())+++async def _wallets_in_workspace(+ session: AsyncSession, workspace_id: uuid.UUID, wallet_ids: list[uuid.UUID]+) -> list[AssetGroup]:+ """Resolve wallet (asset_group) ids to rows, scoped to the workspace."""+ if not wallet_ids:+ return []+ result = await session.execute(+ select(AssetGroup).where(+ AssetGroup.workspace_id == workspace_id,+ AssetGroup.id.in_(wallet_ids),+ )+ )+ return list(result.scalars().all())+++async def get_collections(+ session: AsyncSession, workspace_id: uuid.UUID+) -> list[CollectionRead]:+ result = await session.execute(+ select(Collection)+ .where(Collection.workspace_id == workspace_id)+ .order_by(Collection.position, Collection.name)+ )+ return [_to_read(c) for c in result.scalars().all()]+++async def _get(+ session: AsyncSession, collection_id: uuid.UUID, workspace_id: uuid.UUID+) -> Optional[Collection]:+ result = await session.execute(+ select(Collection).where(+ Collection.id == collection_id,+ Collection.workspace_id == workspace_id,+ )+ )+ return result.scalar_one_or_none()+++async def _next_position(session: AsyncSession, workspace_id: uuid.UUID) -> int:+ row = await session.execute(+ select(func.coalesce(func.max(Collection.position), -1) + 1).where(+ Collection.workspace_id == workspace_id+ )+ )+ return int(row.scalar() or 0)+++async def create_collection(+ session: AsyncSession,+ workspace_id: uuid.UUID,+ user_id: uuid.UUID,+ data: CollectionCreate,+) -> CollectionRead:+ position = data.position or await _next_position(session, workspace_id)+ collection = Collection(+ user_id=user_id,+ workspace_id=workspace_id,+ name=data.name,+ icon=data.icon,+ color=data.color,+ position=position,+ )+ collection.accounts = await _accounts_in_workspace(session, workspace_id, data.account_ids)+ collection.asset_groups = await _wallets_in_workspace(session, workspace_id, data.wallet_ids)+ session.add(collection)+ await session.commit()+ await session.refresh(collection)+ return _to_read(collection)+++async def update_collection(+ session: AsyncSession,+ collection_id: uuid.UUID,+ workspace_id: uuid.UUID,+ data: CollectionUpdate,+) -> Optional[CollectionRead]:+ collection = await _get(session, collection_id, workspace_id)+ if not collection:+ return None++ fields = data.model_dump(exclude_unset=True)+ account_ids = fields.pop("account_ids", None)+ wallet_ids = fields.pop("wallet_ids", None)+ for key, value in fields.items():+ setattr(collection, key, value)+ if account_ids is not None:+ collection.accounts = await _accounts_in_workspace(session, workspace_id, account_ids)+ if wallet_ids is not None:+ collection.asset_groups = await _wallets_in_workspace(session, workspace_id, wallet_ids)++ await session.commit()+ await session.refresh(collection)+ return _to_read(collection)+++async def delete_collection(+ session: AsyncSession, collection_id: uuid.UUID, workspace_id: uuid.UUID+) -> bool:+ collection = await _get(session, collection_id, workspace_id)+ if not collection:+ return False+ await session.delete(collection)+ await session.commit()+ return Truediff --git a/backend/app/services/dashboard_service.py b/backend/app/services/dashboard_service.pyindex 83eb2b47..f0d99466 100644--- a/backend/app/services/dashboard_service.py+++ b/backend/app/services/dashboard_service.py@@ -42,10 +42,16 @@ async def _get_recurring_projections(workspace_id: uuid.UUID,month_start: date,month_end: date,+ account_ids: Optional[list[uuid.UUID]] = None,) -> 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(+ Pure read — no DB writes. Returns list of dicts with category_id, amount, type, currency.++ When ``account_ids`` is given (Collection filter), only recurring rules on+ those accounts are projected. Empty list → no projections."""+ if account_ids is not None and len(account_ids) == 0:+ return []+ stmt = (select(RecurringTransaction).where(RecurringTransaction.workspace_id == workspace_id,@@ -53,6 +59,9 @@ async def _get_recurring_projections(RecurringTransaction.start_date < month_end,))+ if account_ids:+ stmt = stmt.where(RecurringTransaction.account_id.in_(account_ids))+ result = await session.execute(stmt)recurring_list = list(result.scalars().all())projections = []@@ -83,6 +92,8 @@ async def get_summary(user_id: uuid.UUID,month: Optional[date] = None,balance_date: Optional[date] = None,+ account_ids: Optional[list[uuid.UUID]] = None,+ asset_group_ids: Optional[list[uuid.UUID]] = None,) -> DashboardSummary:if not month:month = date.today().replace(day=1)@@ -90,6 +101,16 @@ async def get_summary(month_start, month_end = _month_range(month)today = date.today()+ # Collection filter (issue #105): show the *raw* P&L/balances of the+ # collection's accounts, plus the assets in its wallets (asset_group_ids);+ # group-split redistribution and cross-group shares are gated off so the+ # filtered numbers stay self-consistent. A wallet-only collection (wallets+ # but no accounts) still filters — coerce accounts to empty.+ if asset_group_ids is not None and account_ids is None:+ account_ids = []+ filtered = account_ids is not None+ acct_filter = [Transaction.account_id.in_(account_ids)] if filtered else []+# Reporting mode is a global app setting (admin-controlled). When "accrual",# aggregation queries bucket credit card transactions by the bill's due# date (effective_date) instead of the purchase date — gives a true@@ -110,14 +131,14 @@ async def get_summary(# Current or future month: todaycutoff = today- total_balance = await _total_balance_by_currency(session, workspace_id, cutoff)+ total_balance = await _total_balance_by_currency(session, workspace_id, cutoff, account_ids)# 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, workspace_id, projection_start, month_end+ session, workspace_id, projection_start, month_end, account_ids)for proj in balance_projections:signed = proj["amount"] if proj["type"] == "credit" else -proj["amount"]@@ -140,52 +161,60 @@ async def get_summary(report_date < month_end,Transaction.source != "opening_balance",counts_as_user_pnl(),+ *acct_filter,))monthly_row = monthly_result.one()monthly_income = float(monthly_row[0] or 0)monthly_expenses = float(monthly_row[1] or 0)- # 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,- workspace_id=workspace_id,- )- monthly_income -= own_offset_inc- monthly_expenses -= own_offset_exp-- # Add the viewer's share from group splits where they're a linked- # member but not the owner. Their concert ticket paid by a friend- # is a real expense in their P/L picture.- shared_income, shared_expenses = await viewer_shared_pnl(- session, user_id, month_start, month_end, use_effective_date=False- )- monthly_income += shared_income- monthly_expenses += shared_expenses+ if not filtered:+ # 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,+ workspace_id=workspace_id,+ )+ monthly_income -= own_offset_inc+ monthly_expenses -= own_offset_exp++ # Add the viewer's share from group splits where they're a linked+ # member but not the owner. Their concert ticket paid by a friend+ # is a real expense in their P/L picture.+ shared_income, shared_expenses = await viewer_shared_pnl(+ session, user_id, month_start, month_end, use_effective_date=False+ )+ monthly_income += shared_income+ monthly_expenses += shared_expenses# Save real-only totals before adding projections (used for primary init)real_monthly_income = monthly_incomereal_monthly_expenses = monthly_expenses# Add virtual recurring projections- projections = await _get_recurring_projections(session, workspace_id, month_start, month_end)+ projections = await _get_recurring_projections(+ session, workspace_id, month_start, month_end, account_ids+ )for proj in projections:if proj["type"] == "credit":monthly_income += proj["amount"]else:monthly_expenses += proj["amount"]- # Account count — all accounts in this workspace (manual + bank-connected)- accounts_count = await session.scalar(- select(func.count())- .select_from(Account)- .where(Account.workspace_id == workspace_id)- ) or 0+ # Account count — the active collection's accounts when filtered, else all+ # accounts in this workspace (manual + bank-connected).+ if filtered:+ accounts_count = len(account_ids)+ else:+ accounts_count = await session.scalar(+ select(func.count())+ .select_from(Account)+ .where(Account.workspace_id == workspace_id)+ ) or 0# Pending categorization — exclude opening_balance and transfer pairspending_cat_filters = [@@ -197,6 +226,7 @@ async def get_summary(# income that need a category, so exclude them.Transaction.source != "settlement",Transaction.transfer_pair_id.is_(None),+ *acct_filter,]pending_categorization = await session.scalar(select(func.count())@@ -213,10 +243,13 @@ async def get_summary(# Get user's primary currency (user already loaded above for reporting mode)primary_currency = user.primary_currency if user else get_settings().default_currency- # Asset values — use cutoff so past months show historical values+ # Asset values — use cutoff so past months show historical values. Under a+ # collection filter, include only assets in the collection's wallets+ # (asset_group_ids); a collection with no wallets → no assets.assets_value, assets_value_primary = await get_asset_values_at(session, workspace_id, as_of_date=cutoff, primary_currency=primary_currency,by_workspace=True,+ group_ids=(asset_group_ids or []) if filtered else None,)# Add asset values to total balance@@ -250,6 +283,7 @@ async def get_summary(Transaction.source != "opening_balance",counts_as_user_pnl(),Transaction.amount_primary.isnot(None),+ *acct_filter,))primary_row = primary_result.one()@@ -257,72 +291,76 @@ async def get_summary(monthly_income_primary = float(primary_row[0] or 0)monthly_expenses_primary = abs(float(primary_row[1] or 0))- # Apply share-only offset in primary currency (FX-converted).- own_offset_inc_pri, own_offset_exp_pri = await owner_split_offset_pnl(- session,- user_id,- month_start,- month_end,- use_effective_date=False,- primary_currency=primary_currency,- workspace_id=workspace_id,- )- monthly_income_primary -= own_offset_inc_pri- monthly_expenses_primary -= own_offset_exp_pri+ if not filtered:+ # Apply share-only offset in primary currency (FX-converted).+ own_offset_inc_pri, own_offset_exp_pri = await owner_split_offset_pnl(+ session,+ user_id,+ month_start,+ month_end,+ use_effective_date=False,+ primary_currency=primary_currency,+ workspace_id=workspace_id,+ )+ monthly_income_primary -= own_offset_inc_pri+ monthly_expenses_primary -= own_offset_exp_pri# Add the viewer's shared shares to primary totals too. The shares# are stored in the parent transaction's currency, so we convert# each currency bucket separately rather than re-using shared_income# / shared_expenses (which were summed without conversion).- from app.models.group import GroupMember- from app.models.transaction_split import TransactionSplit+ # Gated under a collection filter — those parent transactions live in+ # other users'/workspaces' accounts, outside the filtered account set.+ if not filtered:+ from app.models.group import GroupMember+ from app.models.transaction_split import TransactionSplit- viewer_member_ids = select(GroupMember.id).where(- GroupMember.linked_user_id == user_id,- GroupMember.is_self.is_(False),- )- shared_currency_rows = await session.execute(- select(- Transaction.currency,- func.sum(- case(- (Transaction.type == "credit", TransactionSplit.share_amount),- else_=0,- )- ),- func.sum(- case(- (Transaction.type == "debit", TransactionSplit.share_amount),- else_=0,- )- ),- )- .select_from(TransactionSplit)- .join(Transaction, TransactionSplit.transaction_id == Transaction.id)- .where(- TransactionSplit.group_member_id.in_(viewer_member_ids),- Transaction.user_id != user_id,- Transaction.source != "opening_balance",- report_date >= month_start,- report_date < month_end,- counts_as_user_pnl(),+ viewer_member_ids = select(GroupMember.id).where(+ GroupMember.linked_user_id == user_id,+ GroupMember.is_self.is_(False),)- .group_by(Transaction.currency)- )- for row in shared_currency_rows.all():- cur = row[0]- in_credit = float(row[1] or 0)- in_debit = float(row[2] or 0)- if in_credit:- credit_pri, _ = await convert(- session, Decimal(str(in_credit)), cur, primary_currency+ shared_currency_rows = await session.execute(+ select(+ Transaction.currency,+ func.sum(+ case(+ (Transaction.type == "credit", TransactionSplit.share_amount),+ else_=0,+ )+ ),+ func.sum(+ case(+ (Transaction.type == "debit", TransactionSplit.share_amount),+ else_=0,+ )+ ),)- monthly_income_primary += float(credit_pri)- if in_debit:- debit_pri, _ = await convert(- session, Decimal(str(in_debit)), cur, primary_currency+ .select_from(TransactionSplit)+ .join(Transaction, TransactionSplit.transaction_id == Transaction.id)+ .where(+ TransactionSplit.group_member_id.in_(viewer_member_ids),+ Transaction.user_id != user_id,+ Transaction.source != "opening_balance",+ report_date >= month_start,+ report_date < month_end,+ counts_as_user_pnl(),)- monthly_expenses_primary += abs(float(debit_pri))+ .group_by(Transaction.currency)+ )+ for row in shared_currency_rows.all():+ cur = row[0]+ in_credit = float(row[1] or 0)+ in_debit = float(row[2] or 0)+ if in_credit:+ credit_pri, _ = await convert(+ session, Decimal(str(in_credit)), cur, primary_currency+ )+ monthly_income_primary += float(credit_pri)+ if in_debit:+ debit_pri, _ = await convert(+ session, Decimal(str(in_debit)), cur, primary_currency+ )+ monthly_expenses_primary += abs(float(debit_pri))# Add recurring projections to primary totals (convert each)for proj in projections:@@ -338,8 +376,12 @@ async def get_summary(# Aggregate the user's net pending balance across all groups they# participate in. We reuse the group balance computation so partial# settlements are already netted out.- pending_shares_net = await _compute_pending_shares_net(- session, workspace_id, user_id, primary_currency+ pending_shares_net = (+ 0.0+ if filtered+ else await _compute_pending_shares_net(+ session, workspace_id, user_id, primary_currency+ ))return DashboardSummary(@@ -432,11 +474,14 @@ async def get_spending_by_category(workspace_id: uuid.UUID,user_id: uuid.UUID,month: Optional[date] = None,+ account_ids: Optional[list[uuid.UUID]] = None,) -> list[SpendingByCategory]:if not month:month = date.today().replace(day=1)month_start, month_end = _month_range(month)+ filtered = account_ids is not None+ acct_filter = [Transaction.account_id.in_(account_ids)] if filtered else []user = await session.get(User, user_id)accounting_mode = await get_credit_card_accounting_mode(session)@@ -465,6 +510,7 @@ async def get_spending_by_category(report_date >= month_start,report_date < month_end,counts_as_user_pnl(),+ *acct_filter,).group_by(Category.id, Category.name, Category.icon, Category.color).order_by(func.sum(_primary_amount_expr()).desc())@@ -483,7 +529,7 @@ async def get_spending_by_category(# Subtract non-owner shares per category — owner-side splits should# contribute only the owner's share, not the full amount.- owner_offset = await owner_split_offset_by_category(+ owner_offset = {} if filtered else await owner_split_offset_by_category(session,user_id,month_start,@@ -502,7 +548,7 @@ async def get_spending_by_category(# Add shared shares — the viewer's portion of group-split debits# they participate in but don't own. The category comes from the# parent transaction.- shared_by_cat = await viewer_shared_spending_by_category(+ shared_by_cat = {} if filtered else await viewer_shared_spending_by_category(session, user_id, month_start, month_end,use_effective_date=accounting_mode == "accrual",primary_currency=primary_currency,@@ -540,7 +586,9 @@ async def get_spending_by_category(}# Add virtual recurring projections (debit only), converted to primary currency- projections = await _get_recurring_projections(session, workspace_id, month_start, month_end)+ projections = await _get_recurring_projections(+ session, workspace_id, month_start, month_end, account_ids+ )# We need category info for recurring projections — fetch categoriescat_cache: dict[str, dict] = {}for proj in projections:@@ -597,7 +645,10 @@ async def get_monthly_trend(workspace_id: uuid.UUID,user_id: uuid.UUID,months: int = 6,+ account_ids: Optional[list[uuid.UUID]] = None,) -> list[MonthlyTrend]:+ filtered = account_ids is not None+ acct_filter = [Transaction.account_id.in_(account_ids)] if filtered else []accounting_mode = await get_credit_card_accounting_mode(session)report_date = (Transaction.effective_date if accounting_mode == "accrual" else Transaction.date@@ -616,6 +667,7 @@ async def get_monthly_trend(Account.is_closed == False,Transaction.source != "opening_balance",counts_as_user_pnl(),+ *acct_filter,).group_by(month_label).order_by(month_label.desc())@@ -640,17 +692,20 @@ async def get_monthly_trend(if int(mnum) < 12else date(int(year) + 1, 1, 1))- own_inc, own_exp = await owner_split_offset_pnl(- 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,- use_effective_date=accounting_mode == "accrual",- primary_currency=primary_currency,- )+ if filtered:+ own_inc, own_exp, shared_inc, shared_exp = 0.0, 0.0, 0.0, 0.0+ else:+ own_inc, own_exp = await owner_split_offset_pnl(+ 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,+ use_effective_date=accounting_mode == "accrual",+ primary_currency=primary_currency,+ )adjusted.append(MonthlyTrend(month=month_str,@@ -769,10 +824,19 @@ def _signed_primary_expr():async def _get_open_accounts(- session: AsyncSession, workspace_id: uuid.UUID+ session: AsyncSession,+ workspace_id: uuid.UUID,+ account_ids: Optional[list[uuid.UUID]] = None,) -> list[Account]:- """Get all non-closed accounts for a workspace."""- result = await session.execute(+ """Get all non-closed accounts for a workspace.++ When ``account_ids`` is provided (an active Collection filter, issue #105),+ restrict to that subset. An empty list returns no accounts — a collection+ with no members shows nothing rather than everything.+ """+ if account_ids is not None and len(account_ids) == 0:+ return []+ stmt = (select(Account).outerjoin(BankConnection).where(@@ -783,6 +847,9 @@ async def _get_open_accounts(Account.is_closed == False,))+ if account_ids:+ stmt = stmt.where(Account.id.in_(account_ids))+ result = await session.execute(stmt)return [row[0] for row in result.all()]@@ -826,10 +893,11 @@ async def _account_balance_at(async def _total_balance_by_currency(- session: AsyncSession, workspace_id: uuid.UUID, cutoff: date+ session: AsyncSession, workspace_id: uuid.UUID, cutoff: date,+ account_ids: Optional[list[uuid.UUID]] = None,) -> dict[str, float]:"""Get total balance across all open accounts at a date, grouped by currency."""- accounts = await _get_open_accounts(session, workspace_id)+ accounts = await _get_open_accounts(session, workspace_id, account_ids)totals: dict[str, float] = {}for account in accounts:bal = await _account_balance_at(session, account, cutoff)@@ -840,13 +908,14 @@ async def _total_balance_by_currency(async def _balance_at(session: AsyncSession, workspace_id: uuid.UUID, cutoff: date,*, primary_currency_hint: Optional[str] = None,+ account_ids: Optional[list[uuid.UUID]] = None,) -> float:"""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 theyalready know the workspace's primary currency."""- totals = await _total_balance_by_currency(session, workspace_id, cutoff)+ totals = await _total_balance_by_currency(session, workspace_id, cutoff, account_ids)# If all same currency, just sumif len(totals) <= 1:@@ -868,6 +937,7 @@ async def _daily_deltas(end: date,*,primary_currency_hint: Optional[str] = None,+ account_ids: Optional[list[uuid.UUID]] = 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@@ -900,6 +970,7 @@ async def _daily_deltas(Transaction.category_id.is_(None),Category.is_ignored == False,),+ *( [Transaction.account_id.in_(account_ids)] if account_ids is not None else [] ),).group_by("day", Account.currency))@@ -930,6 +1001,7 @@ async def get_balance_history(workspace_id: uuid.UUID,user_id: uuid.UUID,month: Optional[date] = None,+ account_ids: Optional[list[uuid.UUID]] = None,) -> BalanceHistory:if not month:month = date.today().replace(day=1)@@ -953,28 +1025,30 @@ async def get_balance_history(# Starting balancescurrent_start = await _balance_at(session, workspace_id, month_start - timedelta(days=1),- primary_currency_hint=primary_currency,+ primary_currency_hint=primary_currency, account_ids=account_ids,)prev_start = await _balance_at(session, workspace_id, prev_month_start - timedelta(days=1),- primary_currency_hint=primary_currency,+ primary_currency_hint=primary_currency, account_ids=account_ids,)# Daily deltas from real transactionscurrent_deltas = await _daily_deltas(session, workspace_id, month_start, month_end,- primary_currency_hint=primary_currency,+ primary_currency_hint=primary_currency, account_ids=account_ids,)prev_deltas = await _daily_deltas(session, workspace_id, prev_month_start, prev_month_end,- primary_currency_hint=primary_currency,+ primary_currency_hint=primary_currency, account_ids=account_ids,)# Recurring projections for future days of current month (converted to primary currency)proj_deltas: dict[int, float] = {}if month_end > today:proj_start = max(month_start, today + timedelta(days=1))- projections = await _get_recurring_projections(session, workspace_id, proj_start, month_end)+ projections = await _get_recurring_projections(+ session, workspace_id, proj_start, month_end, account_ids+ )for proj in projections:day = proj["date"].dayproj_converted, _ = await convert(diff --git a/backend/app/services/report_service.py b/backend/app/services/report_service.pyindex 7ef28bea..9563a0c3 100644--- a/backend/app/services/report_service.py+++ b/backend/app/services/report_service.py@@ -2,6 +2,7 @@ import calendarimport uuidfrom datetime import date, timedeltafrom decimal import Decimal+from typing import Optionalfrom sqlalchemy import String, select, desc, func, casefrom sqlalchemy.ext.asyncio import AsyncSession@@ -48,11 +49,13 @@ def _report_start_date(today: date, months: int, period: str | None = None) -> dasync def _asset_value_at(session: AsyncSession, workspace_id: uuid.UUID, cutoff: date,primary_currency: str = "USD",+ group_ids: Optional[list[uuid.UUID]] = None,) -> float:"""Sum of all active asset values at a given date, converted to primary currency."""_, total = await get_asset_values_at(session, workspace_id, as_of_date=cutoff,primary_currency=primary_currency, by_workspace=True,+ group_ids=group_ids,)return total@@ -60,9 +63,15 @@ async def _asset_value_at(async def _net_worth_at(session: AsyncSession, workspace_id: uuid.UUID, cutoff: date,primary_currency: str = "USD",+ account_ids: Optional[list[uuid.UUID]] = None,+ asset_group_ids: Optional[list[uuid.UUID]] = None,) -> ReportDataPoint:- """Compute a single net worth snapshot at a given date, converted to primary currency."""- accounts = await _get_open_accounts(session, workspace_id)+ """Compute a single net worth snapshot at a given date, converted to primary currency.++ Under a Collection filter (``account_ids`` set), only those accounts are+ summed and only assets in the collection's wallets (``asset_group_ids``)+ are included."""+ accounts = await _get_open_accounts(session, workspace_id, account_ids)accounts_total = 0.0liabilities_total = 0.0@@ -79,7 +88,10 @@ async def _net_worth_at(else:accounts_total += converted_val- assets_total = await _asset_value_at(session, workspace_id, cutoff, primary_currency)+ assets_total = await _asset_value_at(+ session, workspace_id, cutoff, primary_currency,+ group_ids=(asset_group_ids or []) if account_ids is not None else None,+ )net_worth = accounts_total + assets_total - liabilities_totalreturn ReportDataPoint(@@ -159,9 +171,15 @@ async def get_net_worth_report(months: int = 12,interval: str = "monthly",currency: str = "USD",+ account_ids: Optional[list[uuid.UUID]] = None,+ asset_group_ids: Optional[list[uuid.UUID]] = None,period: str | None = None,) -> ReportResponse:"""Build a full ReportResponse for net worth over time."""+ # A wallet-only collection (wallets, no accounts) still filters.+ if asset_group_ids is not None and account_ids is None:+ account_ids = []+ filtered = account_ids is not Nonetoday = date.today()start = _report_start_date(today, months, period)@@ -174,7 +192,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, workspace_id, point, primary_currency)+ dp = await _net_worth_at(session, workspace_id, point, primary_currency, account_ids, asset_group_ids)dp.date = _format_date_label(point, interval)dp.change = round(dp.value - trend[-1].value, 2) if trend else Nonetrend.append(dp)@@ -183,7 +201,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, workspace_id, start, primary_currency)+ baseline = await _net_worth_at(session, workspace_id, start, primary_currency, account_ids, asset_group_ids)previous = baseline if trend else currentchange_amount = current.value - previous.value@@ -242,7 +260,7 @@ async def get_net_worth_report("other": "#6B7280",}composition: list[ReportCompositionItem] = []- accounts = await _get_open_accounts(session, workspace_id)+ accounts = await _get_open_accounts(session, workspace_id, account_ids)for account in accounts:bal = await _account_balance_at(session, account, today)converted, _ = await convert(@@ -275,14 +293,16 @@ async def get_net_worth_report(group="liabilities",))- # Assets — scoped to workspace- asset_result = await session.execute(- select(Asset).where(- Asset.workspace_id == workspace_id,- Asset.is_archived == False,- Asset.sell_date.is_(None),- )+ # Assets — scoped to workspace, or (under a collection filter) to the+ # assets in the collection's wallets. An empty wallet set → no assets.+ asset_stmt = select(Asset).where(+ Asset.workspace_id == workspace_id,+ Asset.is_archived == False,+ Asset.sell_date.is_(None),)+ if filtered:+ asset_stmt = asset_stmt.where(Asset.group_id.in_(asset_group_ids or []))+ asset_result = await session.execute(asset_stmt)for asset in asset_result.scalars().all():val_result = await session.execute(select(AssetValue.amount)@@ -338,9 +358,12 @@ async def get_income_expenses_report(months: int = 12,interval: str = "monthly",currency: str = "USD",+ account_ids: Optional[list[uuid.UUID]] = None,period: str | None = None,) -> ReportResponse:"""Build a ReportResponse for income vs expenses over time."""+ filtered = account_ids is not None+ acct_filter = [Transaction.account_id.in_(account_ids)] if filtered else []today = date.today()start = _report_start_date(today, months, period)@@ -371,6 +394,7 @@ async def get_income_expenses_report(report_date <= today,Transaction.source != "opening_balance",counts_as_user_pnl(),+ *acct_filter,).group_by(label_expr).order_by(label_expr)@@ -430,7 +454,7 @@ async def get_income_expenses_report().group_by(label_expr, Transaction.currency))- for row in owner_offset_result.all():+ for row in (owner_offset_result.all() if not filtered else []):period, currency, raw_credit, raw_debit = rowsub_inc = 0.0sub_exp = 0.0@@ -494,7 +518,7 @@ async def get_income_expenses_report(.group_by(label_expr, Transaction.currency))from app.services.fx_rate_service import convert as fx_convert- for row in shared_result.all():+ for row in (shared_result.all() if not filtered else []):period, currency, raw_credit, raw_debit = rowshare_income_pri = 0.0share_expenses_pri = 0.0@@ -520,7 +544,7 @@ async def get_income_expenses_report(cursor = startwhile cursor <= today:m_start, m_end = _month_range(cursor)- projections = await _get_recurring_projections(session, workspace_id, m_start, m_end)+ projections = await _get_recurring_projections(session, workspace_id, m_start, m_end, account_ids)for proj in projections:# Convert to primary currencyconverted, _ = await fx_convert(@@ -624,6 +648,7 @@ async def get_income_expenses_report(report_date <= today,Transaction.source != "opening_balance",counts_as_user_pnl(),+ *acct_filter,).group_by(Category.id, Category.name, Category.color, Transaction.type))@@ -647,7 +672,7 @@ async def get_income_expenses_report(# Subtract non-owner shares of own splits from composition (debit only —# owner_split_offset_by_category is debit-only). Keeps the report's# composition consistent with summary totals under share-only model.- full_range_offset = await owner_split_offset_by_category(+ full_range_offset = {} if filtered else await owner_split_offset_by_category(session, user_id, start, today + timedelta(days=1),use_effective_date=accounting_mode == "accrual",primary_currency=primary_currency,@@ -680,6 +705,7 @@ async def get_income_expenses_report(report_date <= today,Transaction.source != "opening_balance",counts_as_user_pnl(),+ *acct_filter,).group_by(label_expr, Category.id, Category.name, Category.color, Transaction.type))@@ -729,7 +755,7 @@ async def get_income_expenses_report().group_by(label_expr, Transaction.category_id, Transaction.currency))- for period_label, cat_id, currency, raw_total in cat_offset_result.all():+ for period_label, cat_id, currency, raw_total in (cat_offset_result.all() if not filtered else []):if not raw_total:continuecat_key = str(cat_id) if cat_id else "uncategorized"@@ -755,7 +781,7 @@ async def get_income_expenses_report(cursor2 = startwhile cursor2 <= today:m_start, m_end = _month_range(cursor2)- projections = await _get_recurring_projections(session, workspace_id, m_start, m_end)+ projections = await _get_recurring_projections(session, workspace_id, m_start, m_end, account_ids)period_label = _format_date_label(cursor2, interval)for proj in projections:cat_id_str = str(proj["category_id"]) if proj["category_id"] else "uncategorized"@@ -904,6 +930,7 @@ async def _get_baseline_projection(end: date,primary_currency: str,to_primary,+ account_ids: Optional[list[uuid.UUID]] = None,) -> tuple[list[dict], int]:"""Estimate future flows by averaging the user's recent transaction history.@@ -926,6 +953,7 @@ async def _get_baseline_projection(Returns ``(projections, lookback_days)`` so the caller can surface theactual window used in the response (zero when there's no history)."""+ acct_filter = [Transaction.account_id.in_(account_ids)] if account_ids is not None else []cap_start = _add_months(today, -_BASELINE_MAX_LOOKBACK_MONTHS)earliest_result = await session.execute(select(func.min(Transaction.date))@@ -936,6 +964,7 @@ async def _get_baseline_projection(Transaction.date <= today,Transaction.source != "opening_balance",counts_as_pnl(),+ *acct_filter,))earliest_date = earliest_result.scalar_one_or_none()@@ -958,6 +987,7 @@ async def _get_baseline_projection(Transaction.date <= today,Transaction.source != "opening_balance",counts_as_pnl(),+ *acct_filter,))total_inflow_primary = 0.0@@ -1012,6 +1042,7 @@ async def get_cash_flow_report(interval: str = "daily",currency: str = "USD",baseline: bool = False,+ account_ids: Optional[list[uuid.UUID]] = None,) -> ReportResponse:"""Cash flow chart with a short past window plus a forward projection.@@ -1033,6 +1064,7 @@ async def get_cash_flow_report(from app.services.dashboard_service import _balance_at, _get_recurring_projectionsfrom app.services.fx_rate_service import get_rate+ acct_filter = [Transaction.account_id.in_(account_ids)] if account_ids is not None else []today = date.today()end = _add_months(today, months)chart_start = _add_months(today, -_PAST_HISTORY_MONTHS)@@ -1047,7 +1079,8 @@ async def get_cash_flow_report(# 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, workspace_id, today, primary_currency_hint=primary_currency+ session, workspace_id, today, primary_currency_hint=primary_currency,+ account_ids=account_ids,)rate_cache: dict[str, Decimal] = {primary_currency: Decimal("1")}@@ -1090,6 +1123,7 @@ async def get_cash_flow_report(flow_date_col <= today,Transaction.source != "opening_balance",counts_as_pnl(),+ *acct_filter,))for flow_date, tx_type, amt, amt_primary, ccy in past_result.all():@@ -1118,6 +1152,7 @@ async def get_cash_flow_report(flow_date_col <= end,Transaction.source != "opening_balance",counts_as_pnl(),+ *acct_filter,))for row in booked_result.all():@@ -1152,6 +1187,7 @@ async def get_cash_flow_report(Transaction.effective_date <= end,Transaction.source != "opening_balance",counts_as_pnl(),+ *acct_filter,))for tx_type, amt, amt_primary, ccy in pending_cc.all():@@ -1176,11 +1212,12 @@ async def get_cash_flow_report(if baseline:projections, baseline_lookback_days = await _get_baseline_projection(- session, workspace_id, today, end, primary_currency, _to_primary,+ session, workspace_id, today, end, primary_currency, _to_primary, account_ids,)else:projections = await _get_recurring_projections(session, workspace_id, today + timedelta(days=1), end + timedelta(days=1),+ account_ids,)for proj in projections:diff --git a/backend/tests/test_collection_filtering.py b/backend/tests/test_collection_filtering.pynew file mode 100644index 00000000..102ba1bc--- /dev/null+++ b/backend/tests/test_collection_filtering.py@@ -0,0 +1,213 @@+"""Collection account-filter (issue #105) — verifies dashboard & reports+aggregations scope to the active collection's accounts.++The contract: passing ``account_ids`` restricts balances and P&L to those+accounts. Assets are excluded (collections hold accounts only) and the+unfiltered path is unchanged.+"""++import uuid+from datetime import date, datetime, timezone+from decimal import Decimal++import pytest+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.account import Account+from app.models.asset import Asset+from app.models.asset_group import AssetGroup+from app.models.transaction import Transaction+from app.models.user import User+from app.services import dashboard_service, report_service+++async def _account(session, user, name) -> Account:+ acc = Account(+ id=uuid.uuid4(), user_id=user.id, name=name, type="checking",+ balance=Decimal("0"), currency="BRL",+ )+ session.add(acc)+ await session.commit()+ await session.refresh(acc)+ return acc+++async def _txn(session, user, account, amount, typ):+ session.add(Transaction(+ id=uuid.uuid4(), user_id=user.id, account_id=account.id,+ description="t", amount=Decimal(str(amount)),+ date=date.today().replace(day=min(5, date.today().day)),+ type=typ, source="manual", created_at=datetime.now(timezone.utc),+ ))+ await session.commit()+++async def test_summary_balances_and_pnl_filter_by_collection(+ session: AsyncSession, test_user: User, test_workspace+):+ a = await _account(session, test_user, "A")+ b = await _account(session, test_user, "B")+ # A: +1000 income, -100 expense → balance 900. B: +500 income → balance 500.+ await _txn(session, test_user, a, 1000, "credit")+ await _txn(session, test_user, a, 100, "debit")+ await _txn(session, test_user, b, 500, "credit")++ ws = test_workspace.id+ all_ = await dashboard_service.get_summary(session, ws, test_user.id)+ only_a = await dashboard_service.get_summary(session, ws, test_user.id, account_ids=[a.id])+ only_b = await dashboard_service.get_summary(session, ws, test_user.id, account_ids=[b.id])++ # Unfiltered = both accounts.+ assert all_.total_balance.get("BRL") == 1400.0+ assert all_.monthly_income == 1500.0+ assert all_.monthly_expenses == 100.0++ # Filtered to A.+ assert only_a.total_balance.get("BRL") == 900.0+ assert only_a.monthly_income == 1000.0+ assert only_a.monthly_expenses == 100.0+ assert only_a.accounts_count == 1++ # Filtered to B.+ assert only_b.total_balance.get("BRL") == 500.0+ assert only_b.monthly_income == 500.0+ assert only_b.monthly_expenses == 0.0+++async def test_empty_collection_yields_zero(+ session: AsyncSession, test_user: User, test_workspace+):+ a = await _account(session, test_user, "A")+ await _txn(session, test_user, a, 1000, "credit")++ empty = await dashboard_service.get_summary(+ session, test_workspace.id, test_user.id, account_ids=[]+ )+ assert empty.total_balance.get("BRL", 0.0) in (0.0, None) or empty.total_balance == {}+ assert empty.monthly_income == 0.0+ assert empty.accounts_count == 0+++async def test_net_worth_excludes_assets_when_filtered(+ session: AsyncSession, test_user: User, test_workspace+):+ a = await _account(session, test_user, "A")+ await _txn(session, test_user, a, 1000, "credit") # balance 1000++ # An asset that should count toward unfiltered net worth but be excluded+ # under a collection filter.+ session.add(Asset(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ name="House", type="real_estate", currency="BRL",+ purchase_price=Decimal("5000"), purchase_date=date.today().replace(day=1),+ valuation_method="manual",+ ))+ await session.commit()++ ws = test_workspace.id+ unfiltered = await report_service.get_net_worth_report(session, ws, test_user.id)+ filtered = await report_service.get_net_worth_report(session, ws, test_user.id, account_ids=[a.id])++ # Asset present unfiltered, gone when filtered.+ assert unfiltered.summary.breakdowns[1].key == "assets"+ assert unfiltered.summary.breakdowns[1].value > 0+ assert filtered.summary.breakdowns[1].value == 0+ # Composition under the filter has no asset items.+ assert all(item.group != "assets" for item in filtered.composition)+++async def test_net_worth_includes_collection_wallet_assets(+ session: AsyncSession, test_user: User, test_workspace+):+ """A collection with a wallet includes that wallet's assets in net worth,+ but not assets outside the wallet."""+ a = await _account(session, test_user, "A")+ await _txn(session, test_user, a, 1000, "credit") # account balance 1000++ wallet = AssetGroup(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ name="Investments",+ )+ session.add(wallet)+ await session.commit()+ # Asset inside the wallet (counts) vs. one outside (excluded).+ session.add(Asset(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ name="In wallet", type="investment", currency="BRL", group_id=wallet.id,+ purchase_price=Decimal("3000"), purchase_date=date.today().replace(day=1),+ valuation_method="manual",+ ))+ session.add(Asset(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ name="Outside", type="investment", currency="BRL", group_id=None,+ purchase_price=Decimal("9999"), purchase_date=date.today().replace(day=1),+ valuation_method="manual",+ ))+ await session.commit()++ ws = test_workspace.id+ # Collection = account A + the wallet.+ rep = await report_service.get_net_worth_report(+ session, ws, test_user.id, account_ids=[a.id], asset_group_ids=[wallet.id]+ )+ assets_bd = next(b for b in rep.summary.breakdowns if b.key == "assets")+ assert assets_bd.value == 3000.0 # only the in-wallet asset, not the 9999 one+ assert rep.summary.breakdowns[0].value == 1000.0 # account A+ # Net worth = account + wallet asset.+ assert rep.summary.primary_value == 4000.0+ # Dashboard summary mirrors it (assets = wallet asset only).+ summ = await dashboard_service.get_summary(+ session, ws, test_user.id, account_ids=[a.id], asset_group_ids=[wallet.id]+ )+ assert summ.assets_value_primary == 3000.0+ # total_balance includes asset values by design: account 1000 + wallet 3000.+ assert summ.total_balance.get("BRL") == 4000.0+++async def test_wallet_only_collection_shows_assets_no_accounts(+ session: AsyncSession, test_user: User, test_workspace+):+ """A wallet-only collection (no accounts) filters accounts to none and+ shows only the wallet's assets — driven by asset_group_ids with+ account_ids omitted, the way the frontend sends it."""+ # An account with a balance that must NOT appear (it's not in the collection).+ other = await _account(session, test_user, "Not in collection")+ await _txn(session, test_user, other, 7777, "credit")++ wallet = AssetGroup(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ name="Crypto",+ )+ session.add(wallet)+ await session.commit()+ session.add(Asset(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ name="BTC", type="crypto", currency="BRL", group_id=wallet.id,+ purchase_price=Decimal("2500"), purchase_date=date.today().replace(day=1),+ valuation_method="manual",+ ))+ await session.commit()++ ws = test_workspace.id+ # Frontend sends asset_group_ids only (empty account list isn't transmittable);+ # the service coerces accounts to empty so the 7777 account is excluded.+ summ = await dashboard_service.get_summary(+ session, ws, test_user.id, asset_group_ids=[wallet.id]+ )+ assert summ.accounts_count == 0+ assert summ.monthly_income == 0.0+ assert summ.assets_value_primary == 2500.0+ assert summ.total_balance.get("BRL") == 2500.0 # only the wallet asset++ rep = await report_service.get_net_worth_report(+ session, ws, test_user.id, asset_group_ids=[wallet.id]+ )+ assert rep.summary.breakdowns[0].value == 0.0 # accounts+ assets_bd = next(b for b in rep.summary.breakdowns if b.key == "assets")+ assert assets_bd.value == 2500.0+ assert rep.summary.primary_value == 2500.0diff --git a/backend/tests/test_collections_api.py b/backend/tests/test_collections_api.pynew file mode 100644index 00000000..fb848d84--- /dev/null+++ b/backend/tests/test_collections_api.py@@ -0,0 +1,242 @@+"""Collections feature (issue #105) — API + service coverage.++Collections are user-defined, workspace-scoped, many-to-many groups of+accounts used to filter the app. These tests exercise CRUD, membership+replacement, account-count rollup and workspace isolation.+"""++import uuid+from decimal import Decimal++import pytest+from httpx import AsyncClient+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.account import Account+from app.models.asset_group import AssetGroup+from app.models.user import User+from app.models.workspace import Workspace+++async def _make_wallet(session: AsyncSession, user: User, name: str) -> AssetGroup:+ wallet = AssetGroup(id=uuid.uuid4(), user_id=user.id, name=name)+ session.add(wallet)+ await session.commit()+ await session.refresh(wallet)+ return wallet+++async def _make_account(session: AsyncSession, user: User, name: str) -> Account:+ acc = Account(+ id=uuid.uuid4(),+ user_id=user.id,+ name=name,+ type="checking",+ balance=Decimal("100.00"),+ currency="BRL",+ )+ session.add(acc)+ await session.commit()+ await session.refresh(acc)+ return acc+++async def test_create_and_list_collection(+ client: AsyncClient, auth_headers, test_user: User, session: AsyncSession+):+ a1 = await _make_account(session, test_user, "Acct A")+ a2 = await _make_account(session, test_user, "Acct B")++ resp = await client.post(+ "/api/collections",+ headers=auth_headers,+ json={"name": "Business", "color": "#10B981", "account_ids": [str(a1.id), str(a2.id)]},+ )+ assert resp.status_code == 201, resp.text+ created = resp.json()+ assert created["name"] == "Business"+ assert created["color"] == "#10B981"+ assert created["account_count"] == 2+ assert set(created["account_ids"]) == {str(a1.id), str(a2.id)}++ listed = (await client.get("/api/collections", headers=auth_headers)).json()+ assert len(listed) == 1+ assert listed[0]["account_count"] == 2+++async def test_create_empty_collection_allowed(+ client: AsyncClient, auth_headers, test_user: User+):+ resp = await client.post(+ "/api/collections", headers=auth_headers, json={"name": "Empty"}+ )+ assert resp.status_code == 201, resp.text+ assert resp.json()["account_count"] == 0+ assert resp.json()["account_ids"] == []+++async def test_update_replaces_membership(+ client: AsyncClient, auth_headers, test_user: User, session: AsyncSession+):+ a1 = await _make_account(session, test_user, "A1")+ a2 = await _make_account(session, test_user, "A2")+ a3 = await _make_account(session, test_user, "A3")++ cid = (await client.post(+ "/api/collections", headers=auth_headers,+ json={"name": "C", "account_ids": [str(a1.id), str(a2.id)]},+ )).json()["id"]++ # Replace membership with a different set + rename.+ resp = await client.patch(+ f"/api/collections/{cid}", headers=auth_headers,+ json={"name": "Renamed", "account_ids": [str(a3.id)]},+ )+ assert resp.status_code == 200, resp.text+ body = resp.json()+ assert body["name"] == "Renamed"+ assert body["account_ids"] == [str(a3.id)]+ assert body["account_count"] == 1++ # Omitting account_ids leaves membership untouched.+ resp2 = await client.patch(+ f"/api/collections/{cid}", headers=auth_headers, json={"color": "#EF4444"}+ )+ assert resp2.status_code == 200+ assert resp2.json()["account_ids"] == [str(a3.id)]+ assert resp2.json()["color"] == "#EF4444"+++async def test_delete_collection(client: AsyncClient, auth_headers, test_user: User):+ cid = (await client.post(+ "/api/collections", headers=auth_headers, json={"name": "Temp"}+ )).json()["id"]++ assert (await client.delete(f"/api/collections/{cid}", headers=auth_headers)).status_code == 204+ assert (await client.get("/api/collections", headers=auth_headers)).json() == []+ # Deleting again is a 404.+ assert (await client.delete(f"/api/collections/{cid}", headers=auth_headers)).status_code == 404+++async def test_membership_scoped_to_workspace(+ client: AsyncClient, auth_headers, test_user: User, session: AsyncSession+):+ """An account from another workspace can't be added — it's silently dropped+ so a collection can never reference cross-workspace accounts."""+ # Account in the user's workspace.+ mine = await _make_account(session, test_user, "Mine")++ # Account in a *different* workspace (not the user's).+ other_ws = Workspace(id=uuid.uuid4(), name="Other", created_by_user_id=test_user.id)+ session.add(other_ws)+ await session.commit()+ foreign = Account(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=other_ws.id,+ name="Foreign", type="checking", balance=Decimal("0"), currency="BRL",+ )+ session.add(foreign)+ await session.commit()++ resp = await client.post(+ "/api/collections", headers=auth_headers,+ json={"name": "Scoped", "account_ids": [str(mine.id), str(foreign.id)]},+ )+ assert resp.status_code == 201, resp.text+ # Only the in-workspace account survived.+ assert resp.json()["account_ids"] == [str(mine.id)]+ assert resp.json()["account_count"] == 1+++async def test_collection_with_wallets(+ client: AsyncClient, auth_headers, test_user: User, session: AsyncSession+):+ acc = await _make_account(session, test_user, "Acct")+ w1 = await _make_wallet(session, test_user, "Investments")+ w2 = await _make_wallet(session, test_user, "Crypto")++ resp = await client.post(+ "/api/collections", headers=auth_headers,+ json={"name": "Wealth", "account_ids": [str(acc.id)], "wallet_ids": [str(w1.id), str(w2.id)]},+ )+ assert resp.status_code == 201, resp.text+ body = resp.json()+ assert body["account_count"] == 1+ assert body["wallet_count"] == 2+ assert set(body["wallet_ids"]) == {str(w1.id), str(w2.id)}++ cid = body["id"]+ # Replace wallets, leave accounts untouched (account_ids omitted).+ upd = await client.patch(+ f"/api/collections/{cid}", headers=auth_headers, json={"wallet_ids": [str(w1.id)]}+ )+ assert upd.status_code == 200+ assert upd.json()["wallet_ids"] == [str(w1.id)]+ assert upd.json()["account_ids"] == [str(acc.id)] # untouched++ # Clear wallets.+ cleared = await client.patch(+ f"/api/collections/{cid}", headers=auth_headers, json={"wallet_ids": []}+ )+ assert cleared.json()["wallet_count"] == 0+++async def test_same_account_and_wallet_shared_across_collections(+ client: AsyncClient, auth_headers, test_user: User, session: AsyncSession+):+ """Membership is many-to-many: the same account or wallet can belong to+ any number of collections simultaneously."""+ acc = await _make_account(session, test_user, "Shared acct")+ wallet = await _make_wallet(session, test_user, "Shared wallet")++ payload = {"account_ids": [str(acc.id)], "wallet_ids": [str(wallet.id)]}+ c1 = (await client.post("/api/collections", headers=auth_headers, json={"name": "C1", **payload})).json()+ c2 = (await client.post("/api/collections", headers=auth_headers, json={"name": "C2", **payload})).json()+ c3 = (await client.post("/api/collections", headers=auth_headers, json={"name": "C3", **payload})).json()++ # All three independently reference the same account + wallet.+ for c in (c1, c2, c3):+ assert c["account_ids"] == [str(acc.id)]+ assert c["wallet_ids"] == [str(wallet.id)]++ listed = (await client.get("/api/collections", headers=auth_headers)).json()+ assert len(listed) == 3+ # Deleting one collection leaves the shared members intact in the others.+ await client.delete(f"/api/collections/{c1['id']}", headers=auth_headers)+ remaining = (await client.get("/api/collections", headers=auth_headers)).json()+ assert {c["name"] for c in remaining} == {"C2", "C3"}+ for c in remaining:+ assert c["account_ids"] == [str(acc.id)]+ assert c["wallet_ids"] == [str(wallet.id)]+++async def test_wallet_only_collection(+ client: AsyncClient, auth_headers, test_user: User, session: AsyncSession+):+ """A collection can hold only wallets (no accounts)."""+ w = await _make_wallet(session, test_user, "Only wallet")+ resp = await client.post(+ "/api/collections", headers=auth_headers,+ json={"name": "Wallet-only", "wallet_ids": [str(w.id)]},+ )+ assert resp.status_code == 201, resp.text+ body = resp.json()+ assert body["account_count"] == 0+ assert body["account_ids"] == []+ assert body["wallet_count"] == 1+ assert body["wallet_ids"] == [str(w.id)]+++async def test_update_missing_collection_404(client: AsyncClient, auth_headers, test_user: User):+ resp = await client.patch(+ f"/api/collections/{uuid.uuid4()}", headers=auth_headers, json={"name": "x"}+ )+ assert resp.status_code == 404diff --git a/backend/tests/test_report_service.py b/backend/tests/test_report_service.pyindex 17e5eb3b..41c84963 100644--- a/backend/tests/test_report_service.py+++ b/backend/tests/test_report_service.py@@ -534,7 +534,7 @@ async def test_income_expenses_api_validation(client, auth_headers):async def test_income_expenses_api_accepts_ytd_period(client, auth_headers, monkeypatch):"""GET /reports/income-expenses passes period=ytd to service."""- async def fake_report(session, workspace_id, user_id, months, interval, currency, period=None):+ async def fake_report(session, workspace_id, user_id, months, interval, currency, account_ids=None, period=None):assert months == 12assert interval == "monthly"assert period == "ytd"diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex d7d6c900..931994a8 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -5,6 +5,7 @@ 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 { CollectionFilterProvider } from '@/contexts/collection-filter-context'import { ProtectedRoute } from '@/components/protected-route'import { AdminRoute } from '@/components/admin-route'import { AgentsRoute } from '@/components/agents-route'@@ -20,6 +21,7 @@ const AccountDetailPage = lazy(() => import('@/pages/account-detail'))const ImportPage = lazy(() => import('@/pages/import'))const RulesPage = lazy(() => import('@/pages/rules'))const CategoriesPage = lazy(() => import('@/pages/categories'))+const CollectionsPage = lazy(() => import('@/pages/collections'))const BudgetsPage = lazy(() => import('@/pages/budgets'))const RecurringPage = lazy(() => import('@/pages/recurring'))const GoalsPage = lazy(() => import('@/pages/goals'))@@ -67,7 +69,9 @@ function App() {<Routeelement={<ProtectedRoute>- <AppLayout />+ <CollectionFilterProvider>+ <AppLayout />+ </CollectionFilterProvider></ProtectedRoute>}>@@ -80,6 +84,7 @@ function App() {<Route path="/import" element={<ImportPage />} /><Route path="/rules" element={<RulesPage />} /><Route path="/categories" element={<CategoriesPage />} />+ <Route path="/collections" element={<CollectionsPage />} /><Route path="/budgets" element={<BudgetsPage />} /><Route path="/goals" element={<GoalsPage />} /><Route path="/recurring" element={<RecurringPage />} />diff --git a/frontend/src/components/app-layout.tsx b/frontend/src/components/app-layout.tsxindex f0928c28..65f8e471 100644--- a/frontend/src/components/app-layout.tsx+++ b/frontend/src/components/app-layout.tsx@@ -5,6 +5,8 @@ import { useTranslation } from 'react-i18next'import { useDisplayLocale } from '@/hooks/use-display-locale'import { useQuery } from '@tanstack/react-query'import { useAuth } from '@/contexts/auth-context'+import { useCollectionFilter } from '@/contexts/collection-filter-context'+import { CollectionSelector } from '@/components/collection-selector'import { auth as authApi, backup as backupApi, admin as adminApi } from '@/lib/api'import { resolveSupportedLang } from '@/lib/i18n'import { toast } from 'sonner'@@ -102,6 +104,7 @@ function formatCurrency(value: number, currency = 'USD', locale = 'en-US') {export function AppLayout() {const { t } = useTranslation()const { user, logout, updateUser } = useAuth()+ const { activeAccountIds } = useCollectionFilter()const userCurrency = user?.preferences?.currency_display ?? 'USD'const locale = useDisplayLocale()const { theme, setTheme, resolvedTheme } = useTheme()@@ -181,7 +184,12 @@ export function AppLayout() {})const allAccounts = accountsList ?? []- const totalBalance = allAccounts.reduce((sum, a) => {+ // When a collection is active, the sidebar list + total reflect only its+ // accounts (issue #105). null = all accounts.+ const visibleAccounts = activeAccountIds+ ? allAccounts.filter((a) => activeAccountIds.includes(a.id))+ : allAccounts+ const totalBalance = visibleAccounts.reduce((sum, a) => {return sum + Number(a.balance_primary ?? a.current_balance)}, 0)const versionA11yLabel = t('app.versionAriaLabel', { version: APP_VERSION })@@ -437,7 +445,7 @@ export function AppLayout() {</button>{accountsExpanded && (<div className="mt-1 space-y-0.5">- {[...allAccounts].sort((a, b) => Math.abs(Number(b.current_balance)) - Math.abs(Number(a.current_balance))).slice(0, accountsShowAll ? allAccounts.length : 3).map((acc) => {+ {[...visibleAccounts].sort((a, b) => Math.abs(Number(b.current_balance)) - Math.abs(Number(a.current_balance))).slice(0, accountsShowAll ? visibleAccounts.length : 3).map((acc) => {const balance = Number(acc.current_balance)const prevBalance = acc.previous_balance ?? 0const pctChange = prevBalance !== 0@@ -471,7 +479,7 @@ export function AppLayout() {</Link>)})}- {allAccounts.length > 3 && (+ {visibleAccounts.length > 3 && (<buttononClick={() => setAccountsShowAll(!accountsShowAll)}className="w-full px-3 py-1.5 text-[11px] font-medium text-sidebar-muted/70 hover:text-sidebar-foreground transition-colors text-center"@@ -479,8 +487,8 @@ export function AppLayout() {{accountsShowAll? t('common.showLess', { defaultValue: 'Show less' }): t('common.showMore', {- count: allAccounts.length - 3,- defaultValue: `+${allAccounts.length - 3} more`,+ count: visibleAccounts.length - 3,+ defaultValue: `+${visibleAccounts.length - 3} more`,})}</button>)}@@ -534,6 +542,9 @@ export function AppLayout() {{/* Main content */}<main className="flex-1 min-h-screen overflow-x-hidden lg:ml-60"><div className="p-6 max-w-7xl mx-auto">+ {/* Active-collection filter (issue #105): sticky bar above the+ content so the scope is visible right where the data is. */}+ <CollectionSelector variant="header" /><Outlet /></div></main>diff --git a/frontend/src/components/collection-selector.tsx b/frontend/src/components/collection-selector.tsxnew file mode 100644index 00000000..988029ee--- /dev/null+++ b/frontend/src/components/collection-selector.tsx@@ -0,0 +1,137 @@+import { useTranslation } from 'react-i18next'+import { useNavigate } from 'react-router-dom'+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from '@/components/ui/dropdown-menu'+import { useCollectionFilter } from '@/contexts/collection-filter-context'+import { Check, ChevronsUpDown, Layers, Settings2, X } from 'lucide-react'++/**+ * Global "active collection" selector (issue #105). Filters the app to the+ * accounts (and wallets) of the chosen collection.+ *+ * Two placements:+ * - `sidebar` legacy spot in the left nav.+ * - `header` a sticky bar at the top of the content area, so the active+ * filter is visible right above the data it scopes (and reads+ * as a peer of the workspace switcher rather than a list filter).+ *+ * Hidden entirely until the user has at least one collection, so it never+ * clutters the UI for people who don't use the feature.+ */+export function CollectionSelector({ variant = 'sidebar' }: { variant?: 'sidebar' | 'header' }) {+ const { t } = useTranslation()+ const nav = useNavigate()+ const { collections, activeCollection, setActiveCollectionId } = useCollectionFilter()++ if (collections.length === 0) return null++ const menu = (+ <DropdownMenuContent align={variant === 'header' ? 'start' : 'start'} className="w-60">+ <DropdownMenuItem onClick={() => setActiveCollectionId(null)} className="flex items-center gap-2">+ <Layers size={14} className="text-muted-foreground" />+ <span className="flex-1">{t('collections.allAccounts')}</span>+ {!activeCollection && <Check size={14} className="text-primary" />}+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ {collections.map((c) => (+ <DropdownMenuItem key={c.id} onClick={() => setActiveCollectionId(c.id)} className="flex items-center gap-2">+ <span className="h-2.5 w-2.5 shrink-0 rounded-full" style={{ backgroundColor: c.color }} />+ <span className="flex-1 truncate">{c.name}</span>+ <span className="text-[10.5px] tabular-nums text-muted-foreground/70">+ {c.account_count > 0 && `${c.account_count}a`}+ {c.account_count > 0 && c.wallet_count > 0 && ' · '}+ {c.wallet_count > 0 && `${c.wallet_count}w`}+ </span>+ {activeCollection?.id === c.id && <Check size={14} className="text-primary" />}+ </DropdownMenuItem>+ ))}+ <DropdownMenuSeparator />+ <DropdownMenuItem onClick={() => nav('/collections')} className="flex items-center gap-2 text-muted-foreground">+ <Settings2 size={14} />+ {t('collections.manage')}+ </DropdownMenuItem>+ </DropdownMenuContent>+ )++ // ── Sidebar placement (legacy) ──────────────────────────────────────────+ if (variant === 'sidebar') {+ return (+ <div className="px-3 pt-2">+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button className="flex items-center gap-2 w-full rounded-lg border border-sidebar-border/60 bg-sidebar-accent/30 px-2.5 py-1.5 text-left hover:bg-sidebar-accent/50 transition-colors">+ {activeCollection ? (+ <span className="h-2.5 w-2.5 shrink-0 rounded-full" style={{ backgroundColor: activeCollection.color }} />+ ) : (+ <Layers size={13} className="shrink-0 text-sidebar-muted" />+ )}+ <span className="flex-1 min-w-0 truncate text-xs font-medium text-sidebar-foreground">+ {activeCollection?.name ?? t('collections.allAccounts')}+ </span>+ <ChevronsUpDown size={13} className="shrink-0 text-sidebar-muted" />+ </button>+ </DropdownMenuTrigger>+ {menu}+ </DropdownMenu>+ </div>+ )+ }++ // ── Header placement (sticky content-area bar) ──────────────────────────+ // When a collection is active the trigger is tinted with the collection+ // color and gains a one-click clear, so the filtered state is impossible to+ // miss. Idle ("All accounts") it stays quiet.+ return (+ <div className="sticky top-0 z-30 -mx-6 mb-6 border-b border-border/60 bg-background/80 px-6 backdrop-blur supports-[backdrop-filter]:bg-background/65 lg:-mx-6">+ <div className="flex h-12 max-w-7xl items-center gap-2">+ <span className="text-[11px] font-medium uppercase tracking-[0.1em] text-muted-foreground/70">+ {t('collections.viewing')}+ </span>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button+ className="group inline-flex items-center gap-2 rounded-full border border-border/60 px-3 py-1.5 text-[13px] transition-colors hover:bg-muted/50"+ style={+ activeCollection+ ? { borderColor: `${activeCollection.color}55`, backgroundColor: `${activeCollection.color}14` }+ : undefined+ }+ >+ {activeCollection ? (+ <span className="h-2.5 w-2.5 shrink-0 rounded-full" style={{ backgroundColor: activeCollection.color }} />+ ) : (+ <Layers size={14} className="shrink-0 text-muted-foreground" />+ )}+ <span+ className={+ activeCollection+ ? 'font-medium text-foreground'+ : 'text-muted-foreground group-hover:text-foreground'+ }+ >+ {activeCollection?.name ?? t('collections.allAccounts')}+ </span>+ <ChevronsUpDown size={13} className="shrink-0 text-muted-foreground/70" />+ </button>+ </DropdownMenuTrigger>+ {menu}+ </DropdownMenu>+ {activeCollection && (+ <button+ onClick={() => setActiveCollectionId(null)}+ className="inline-flex items-center gap-1 rounded-full px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"+ aria-label={t('collections.clearFilter')}+ >+ <X size={13} />+ {t('collections.clearFilter')}+ </button>+ )}+ </div>+ </div>+ )+}diff --git a/frontend/src/components/transaction-drill-down.tsx b/frontend/src/components/transaction-drill-down.tsxindex ceb7d8c4..704a4cd6 100644--- a/frontend/src/components/transaction-drill-down.tsx+++ b/frontend/src/components/transaction-drill-down.tsx@@ -14,6 +14,8 @@ export type DrillDownFilter = {category_id?: stringuncategorized?: booleanaccount_id?: string+ // Scope to a set of accounts (e.g. the active collection's accounts).+ account_ids?: string[]type?: 'credit' | 'debit'from?: stringto?: string@@ -63,6 +65,7 @@ export function TransactionDrillDown({category_id: filter?.category_id,uncategorized: filter?.uncategorized,account_id: filter?.account_id,+ account_ids: filter?.account_ids,type: filter?.type,from: filter?.from,to: filter?.to,diff --git a/frontend/src/contexts/collection-filter-context.tsx b/frontend/src/contexts/collection-filter-context.tsxnew file mode 100644index 00000000..f260fd37--- /dev/null+++ b/frontend/src/contexts/collection-filter-context.tsx@@ -0,0 +1,81 @@+import { createContext, useContext, useEffect, useMemo, useState, type ReactNode } from 'react'+import { useQuery } from '@tanstack/react-query'+import { collections as collectionsApi } from '@/lib/api'+import { useWorkspace } from '@/contexts/workspace-context'+import type { Collection } from '@/types'++type CollectionFilterValue = {+ collections: Collection[]+ activeCollectionId: string | null+ activeCollection: Collection | null+ setActiveCollectionId: (id: string | null) => void+ // null = all accounts (no filter); otherwise the active collection's account ids.+ activeAccountIds: string[] | null+ // null = no filter; otherwise the active collection's wallet (asset_group) ids.+ activeWalletIds: string[] | null+}++const CollectionFilterContext = createContext<CollectionFilterValue | null>(null)+const STORAGE_PREFIX = 'securo.activeCollection.'++export function CollectionFilterProvider({ children }: { children: ReactNode }) {+ const { current } = useWorkspace()+ const wsId = current?.id ?? ''++ const { data } = useQuery({+ queryKey: ['collections'],+ queryFn: collectionsApi.list,+ })+ const collections = useMemo(() => data ?? [], [data])++ const [activeCollectionId, setActiveId] = useState<string | null>(null)++ // The active selection is persisted per workspace — switching workspaces+ // restores that workspace's last-used collection (or "all").+ const [loadedWsId, setLoadedWsId] = useState<string | null>(null)+ if (wsId && wsId !== loadedWsId) {+ setLoadedWsId(wsId)+ setActiveId(localStorage.getItem(STORAGE_PREFIX + wsId) || null)+ }++ const setActiveCollectionId = (id: string | null) => {+ setActiveId(id)+ if (!wsId) return+ if (id) localStorage.setItem(STORAGE_PREFIX + wsId, id)+ else localStorage.removeItem(STORAGE_PREFIX + wsId)+ }++ const activeCollection = useMemo(+ () => collections.find((c) => c.id === activeCollectionId) ?? null,+ [collections, activeCollectionId],+ )++ // If the active collection was deleted elsewhere, fall back to "all".+ useEffect(() => {+ if (activeCollectionId && collections.length > 0 && !activeCollection) {+ setActiveCollectionId(null)+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [activeCollectionId, collections, activeCollection])++ const value: CollectionFilterValue = {+ collections,+ activeCollectionId,+ activeCollection,+ setActiveCollectionId,+ activeAccountIds: activeCollection ? activeCollection.account_ids : null,+ activeWalletIds: activeCollection ? activeCollection.wallet_ids : null,+ }++ return (+ <CollectionFilterContext.Provider value={value}>{children}</CollectionFilterContext.Provider>+ )+}++export function useCollectionFilter(): CollectionFilterValue {+ const ctx = useContext(CollectionFilterContext)+ if (!ctx) {+ throw new Error('useCollectionFilter must be used within a CollectionFilterProvider')+ }+ return ctx+}diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 1d7f032d..bdf8987f 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -11,6 +11,7 @@ import type {ConnectionSettings,Account,AccountSummary,+ Collection,CreditCardBill,Transaction,Payee,@@ -831,25 +832,43 @@ export const goals = {}// Dashboard+// Repeated `account_ids=a&account_ids=b` (no [] brackets) so FastAPI's+// list[UUID] query param parses them. Only attached when a filter is active.+const acctIdsParam = (accountIds?: string[]) =>+ accountIds && accountIds.length > 0+ ? { params: { account_ids: accountIds }, paramsSerializer: { indexes: null as null } }+ : {}+export const dashboard = {- summary: async (month?: string, balanceDate?: string): Promise<DashboardSummary> => {- const { data } = await api.get('/dashboard/summary', { params: { month, balance_date: balanceDate } })+ summary: async (month?: string, balanceDate?: string, accountIds?: string[], assetGroupIds?: string[]): Promise<DashboardSummary> => {+ const hasFilter = (accountIds && accountIds.length > 0) || (assetGroupIds && assetGroupIds.length > 0)+ const { data } = await api.get('/dashboard/summary', {+ params: {+ month, balance_date: balanceDate,+ ...(accountIds && accountIds.length > 0 ? { account_ids: accountIds } : {}),+ ...(assetGroupIds && assetGroupIds.length > 0 ? { asset_group_ids: assetGroupIds } : {}),+ },+ ...(hasFilter ? { paramsSerializer: { indexes: null as null } } : {}),+ })return data},- spendingByCategory: async (month?: string): Promise<SpendingByCategory[]> => {- const { data } = await api.get('/dashboard/spending-by-category', { params: { month } })+ spendingByCategory: async (month?: string, accountIds?: string[]): Promise<SpendingByCategory[]> => {+ const extra = acctIdsParam(accountIds)+ const { data } = await api.get('/dashboard/spending-by-category', { params: { month, ...(extra.params ?? {}) }, ...(extra.paramsSerializer ? { paramsSerializer: extra.paramsSerializer } : {}) })return data},- monthlyTrend: async (months = 6): Promise<MonthlyTrend[]> => {- const { data } = await api.get('/dashboard/monthly-trend', { params: { months } })+ monthlyTrend: async (months = 6, accountIds?: string[]): Promise<MonthlyTrend[]> => {+ const extra = acctIdsParam(accountIds)+ const { data } = await api.get('/dashboard/monthly-trend', { params: { months, ...(extra.params ?? {}) }, ...(extra.paramsSerializer ? { paramsSerializer: extra.paramsSerializer } : {}) })return data},projectedTransactions: async (month?: string): Promise<ProjectedTransaction[]> => {const { data } = await api.get('/dashboard/projected-transactions', { params: { month } })return data},- balanceHistory: async (month?: string): Promise<BalanceHistory> => {- const { data } = await api.get('/dashboard/balance-history', { params: { month } })+ balanceHistory: async (month?: string, accountIds?: string[]): Promise<BalanceHistory> => {+ const extra = acctIdsParam(accountIds)+ const { data } = await api.get('/dashboard/balance-history', { params: { month, ...(extra.params ?? {}) }, ...(extra.paramsSerializer ? { paramsSerializer: extra.paramsSerializer } : {}) })return data},}@@ -929,18 +948,47 @@ export const assetGroups = {},}+// Collections — user-defined account groups for filtering (issue #105)+export const collections = {+ list: async (): Promise<Collection[]> => {+ const { data } = await api.get('/collections')+ return data+ },+ create: async (payload: { name: string; icon?: string; color?: string; account_ids?: string[]; wallet_ids?: string[] }): Promise<Collection> => {+ const { data } = await api.post('/collections', payload)+ return data+ },+ update: async (id: string, payload: Partial<{ name: string; icon: string; color: string; position: number; account_ids: string[]; wallet_ids: string[] }>): Promise<Collection> => {+ const { data } = await api.patch(`/collections/${id}`, payload)+ return data+ },+ delete: async (id: string): Promise<void> => {+ await api.delete(`/collections/${id}`)+ },+}+// Reportsexport const reports = {- netWorth: async (months = 12, interval = 'monthly', period?: 'ytd'): Promise<ReportResponse> => {- const { data } = await api.get('/reports/net-worth', { params: { months, interval, period } })+ netWorth: async (months = 12, interval = 'monthly', accountIds?: string[], assetGroupIds?: string[], period?: 'ytd'): Promise<ReportResponse> => {+ const hasFilter = (accountIds && accountIds.length > 0) || (assetGroupIds && assetGroupIds.length > 0)+ const { data } = await api.get('/reports/net-worth', {+ params: {+ months, interval, period,+ ...(accountIds && accountIds.length > 0 ? { account_ids: accountIds } : {}),+ ...(assetGroupIds && assetGroupIds.length > 0 ? { asset_group_ids: assetGroupIds } : {}),+ },+ ...(hasFilter ? { paramsSerializer: { indexes: null as null } } : {}),+ })return data},- incomeExpenses: async (months = 12, interval = 'monthly', period?: 'ytd'): Promise<ReportResponse> => {- const { data } = await api.get('/reports/income-expenses', { params: { months, interval, period } })+ incomeExpenses: async (months = 12, interval = 'monthly', accountIds?: string[], period?: 'ytd'): Promise<ReportResponse> => {+ const extra = acctIdsParam(accountIds)+ const { data } = await api.get('/reports/income-expenses', { params: { months, interval, period, ...(extra.params ?? {}) }, ...(extra.paramsSerializer ? { paramsSerializer: extra.paramsSerializer } : {}) })return data},- cashFlow: async (months = 6, interval = 'daily', baseline = false): Promise<ReportResponse> => {- const { data } = await api.get('/reports/cash-flow', { params: { months, interval, baseline } })+ cashFlow: async (months = 6, interval = 'daily', baseline = false, accountIds?: string[]): Promise<ReportResponse> => {+ const extra = acctIdsParam(accountIds)+ const { data } = await api.get('/reports/cash-flow', { params: { months, interval, baseline, ...(extra.params ?? {}) }, ...(extra.paramsSerializer ? { paramsSerializer: extra.paramsSerializer } : {}) })return data},}diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.jsonindex fb060cec..db793781 100644--- a/frontend/src/locales/en.json+++ b/frontend/src/locales/en.json@@ -105,6 +105,7 @@"dashboard": "Dashboard","transactions": "Transactions","accounts": "Accounts",+ "collections": "Collections","import": "Import","rules": "Rules","categories": "Categories",@@ -124,6 +125,32 @@"agents": "Agents","aiAgents": "AI Agents"},+ "collections": {+ "title": "Collections",+ "subtitle": "Group your accounts into named collections (e.g. Business, Long-term, Daily) to filter your dashboard, reports and transactions.",+ "allAccounts": "All accounts",+ "viewing": "Viewing",+ "clearFilter": "Clear",+ "manage": "Manage collections",+ "add": "New collection",+ "edit": "Edit collection",+ "empty": "No collections yet. Create one to group your accounts.",+ "accountCount": "{{count}} accounts",+ "name": "Name",+ "namePlaceholder": "e.g. Business, Long-term, Emergency fund",+ "color": "Color",+ "accounts": "Accounts",+ "accountsHint": "{{count}} selected",+ "wallets": "Wallets",+ "walletsHint": "{{count}} selected",+ "walletCount": "{{count}} wallets",+ "noAccounts": "No accounts yet.",+ "created": "Collection created",+ "updated": "Collection updated",+ "deleted": "Collection deleted",+ "confirmDeleteTitle": "Delete collection?",+ "confirmDeleteDesc": "\"{{name}}\" will be removed. Your accounts and data are not affected."+ },"auth": {"login": "Login","register": "Create account",diff --git a/frontend/src/locales/es.json b/frontend/src/locales/es.jsonindex 5ab50d87..411bdd24 100644--- a/frontend/src/locales/es.json+++ b/frontend/src/locales/es.json@@ -105,6 +105,7 @@"dashboard": "Inicio","transactions": "Transacciones","accounts": "Cuentas",+ "collections": "Colecciones","import": "Importar","rules": "Reglas","categories": "Categorías",@@ -124,6 +125,32 @@"agents": "Agentes","aiAgents": "Agentes IA"},+ "collections": {+ "title": "Colecciones",+ "subtitle": "Agrupa tus cuentas en colecciones con nombre (p. ej. Empresa, Largo plazo, Diario) para filtrar el panel, los informes y las transacciones.",+ "allAccounts": "Todas las cuentas",+ "viewing": "Viendo",+ "clearFilter": "Limpiar",+ "manage": "Gestionar colecciones",+ "add": "Nueva colección",+ "edit": "Editar colección",+ "empty": "Aún no hay colecciones. Crea una para agrupar tus cuentas.",+ "accountCount": "{{count}} cuentas",+ "name": "Nombre",+ "namePlaceholder": "p. ej. Empresa, Largo plazo, Fondo de emergencia",+ "color": "Color",+ "accounts": "Cuentas",+ "accountsHint": "{{count}} seleccionada(s)",+ "wallets": "Carteras",+ "walletsHint": "{{count}} seleccionada(s)",+ "walletCount": "{{count}} carteras",+ "noAccounts": "Aún no hay cuentas.",+ "created": "Colección creada",+ "updated": "Colección actualizada",+ "deleted": "Colección eliminada",+ "confirmDeleteTitle": "¿Eliminar colección?",+ "confirmDeleteDesc": "Se eliminará \"{{name}}\". Tus cuentas y datos no se ven afectados."+ },"auth": {"login": "Iniciar sesión","register": "Crear cuenta",diff --git a/frontend/src/locales/pl.json b/frontend/src/locales/pl.jsonindex 65eef5c8..450ec78d 100644--- a/frontend/src/locales/pl.json+++ b/frontend/src/locales/pl.json@@ -122,7 +122,34 @@"groupAdmin": "Administracja","groupAgents": "AI","agents": "Agenci",- "aiAgents": "Agenci AI"+ "aiAgents": "Agenci AI",+ "collections": "Kolekcje"+ },+ "collections": {+ "title": "Kolekcje",+ "subtitle": "Pogrupuj swoje konta w nazwane kolekcje (np. Firma, Długoterminowe, Codzienne), aby filtrować pulpit, raporty i transakcje.",+ "allAccounts": "Wszystkie konta",+ "viewing": "Wyświetlanie",+ "clearFilter": "Wyczyść",+ "manage": "Zarządzaj kolekcjami",+ "add": "Nowa kolekcja",+ "edit": "Edytuj kolekcję",+ "empty": "Brak kolekcji. Utwórz jedną, aby pogrupować konta.",+ "accountCount": "{{count}} kont",+ "name": "Nazwa",+ "namePlaceholder": "np. Firma, Długoterminowe, Fundusz awaryjny",+ "color": "Kolor",+ "accounts": "Konta",+ "accountsHint": "Wybrano: {{count}}",+ "wallets": "Portfele",+ "walletsHint": "Wybrano: {{count}}",+ "walletCount": "{{count}} portfeli",+ "noAccounts": "Brak kont.",+ "created": "Utworzono kolekcję",+ "updated": "Zaktualizowano kolekcję",+ "deleted": "Usunięto kolekcję",+ "confirmDeleteTitle": "Usunąć kolekcję?",+ "confirmDeleteDesc": "„{{name}}” zostanie usunięta. Twoje konta i dane nie zostaną naruszone."},"auth": {"login": "Zaloguj się",diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.jsonindex 9408c896..cc1cc287 100644--- a/frontend/src/locales/pt-BR.json+++ b/frontend/src/locales/pt-BR.json@@ -105,6 +105,7 @@"dashboard": "Painel","transactions": "Transações","accounts": "Contas",+ "collections": "Coleções","import": "Importar","rules": "Regras","categories": "Categorias",@@ -124,6 +125,32 @@"agents": "Agentes","aiAgents": "Agentes IA"},+ "collections": {+ "title": "Coleções",+ "subtitle": "Agrupe suas contas em coleções nomeadas (ex.: Empresa, Longo prazo, Dia a dia) para filtrar o painel, relatórios e transações.",+ "allAccounts": "Todas as contas",+ "viewing": "Vendo",+ "clearFilter": "Limpar",+ "manage": "Gerenciar coleções",+ "add": "Nova coleção",+ "edit": "Editar coleção",+ "empty": "Nenhuma coleção ainda. Crie uma para agrupar suas contas.",+ "accountCount": "{{count}} contas",+ "name": "Nome",+ "namePlaceholder": "ex.: Empresa, Longo prazo, Reserva",+ "color": "Cor",+ "accounts": "Contas",+ "accountsHint": "{{count}} selecionada(s)",+ "wallets": "Carteiras",+ "walletsHint": "{{count}} selecionada(s)",+ "walletCount": "{{count}} carteiras",+ "noAccounts": "Nenhuma conta ainda.",+ "created": "Coleção criada",+ "updated": "Coleção atualizada",+ "deleted": "Coleção excluída",+ "confirmDeleteTitle": "Excluir coleção?",+ "confirmDeleteDesc": "\"{{name}}\" será removida. Suas contas e dados não são afetados."+ },"auth": {"login": "Entrar","register": "Criar conta",diff --git a/frontend/src/pages/accounts.tsx b/frontend/src/pages/accounts.tsxindex ad240fac..be36a13e 100644--- a/frontend/src/pages/accounts.tsx+++ b/frontend/src/pages/accounts.tsx@@ -1,7 +1,7 @@import { useEffect, useMemo, useState } from 'react'import { getAccountName } from '@/lib/account-utils'import { getConnectionName } from '@/lib/connection-utils'-import { Link } from 'react-router-dom'+import { Link, useNavigate } from 'react-router-dom'import { useTranslation } from 'react-i18next'import { useDisplayLocale, useDateLocale } from '@/hooks/use-display-locale'import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'@@ -35,6 +35,7 @@ import {Plus,Settings,Archive,+ Layers,} from 'lucide-react'import { PageHeader } from '@/components/page-header'import { BankConnectDialog } from '@/components/bank-connect-dialog'@@ -72,6 +73,7 @@ function getTypeConfig(type: string) {export default function AccountsPage() {const { t } = useTranslation()+ const navigate = useNavigate()const locale = useDisplayLocale()const dateLocale = useDateLocale()const { mask } = usePrivacyMode()@@ -225,18 +227,24 @@ export default function AccountsPage() {section={t('accounts.title')}title={t('accounts.title')}action={- 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+ <div className="flex gap-2">+ <Button variant="outline" className="gap-1.5" onClick={() => navigate('/collections')}>+ <Layers size={16} />+ {t('collections.title')}+ </Button>+ {canWrite && (+ <>+ <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>}/>diff --git a/frontend/src/pages/assets.tsx b/frontend/src/pages/assets.tsxindex f4c3f2e7..9ac493d9 100644--- a/frontend/src/pages/assets.tsx+++ b/frontend/src/pages/assets.tsx@@ -52,6 +52,7 @@ 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'+import { useCollectionFilter } from '@/contexts/collection-filter-context'function formatCurrency(value: number, currency = 'USD', locale = 'en-US') {try {@@ -228,15 +229,49 @@ export default function AssetsPage() {const [formUnits, setFormUnits] = useState('')const [quoteLoading, setQuoteLoading] = useState(false)- const { data: assetsList, isLoading } = useQuery({+ const { data: rawAssetsList, isLoading } = useQuery({queryKey: ['assets'],queryFn: () => assets.list(false),})- const { data: portfolioData } = useQuery({+ // Active Collection filter (issue #105): when a collection is active, scope+ // the Assets page to the assets in its wallets (asset_groups). A collection+ // with no wallets → no assets shown. "All accounts" (null) → show everything.+ const { activeWalletIds } = useCollectionFilter()+ const assetsList = useMemo(() => {+ if (!activeWalletIds) return rawAssetsList+ const allowed = new Set(activeWalletIds)+ return (rawAssetsList ?? []).filter((a) => a.group_id && allowed.has(a.group_id))+ }, [rawAssetsList, activeWalletIds])++ const { data: rawPortfolioData } = useQuery({queryKey: ['portfolio-trend'],queryFn: () => assets.portfolioTrend(),})+ // Scope the portfolio chart + total to the active collection's wallets too.+ // Trend rows are keyed by asset id, so we keep only the in-collection asset+ // columns and recompute each row's `_total`.+ const portfolioData = useMemo(() => {+ if (!activeWalletIds || !rawPortfolioData) return rawPortfolioData+ const allowed = new Set(activeWalletIds)+ const keptAssets = rawPortfolioData.assets.filter((a) => a.group_id && allowed.has(a.group_id))+ const keptIds = new Set(keptAssets.map((a) => a.id))+ const trend = rawPortfolioData.trend.map((row) => {+ const next: Record<string, unknown> = { date: (row as { date: unknown }).date }+ let total = 0+ for (const [k, v] of Object.entries(row)) {+ if (k === 'date' || k === '_total') continue+ if (keptIds.has(k)) {+ next[k] = v+ total += Number(v) || 0+ }+ }+ next._total = total+ return next+ })+ const lastTotal = trend.length ? Number((trend[trend.length - 1] as { _total?: number })._total) || 0 : 0+ return { ...rawPortfolioData, assets: keptAssets, trend, total: lastTotal }+ }, [rawPortfolioData, activeWalletIds])// Publish a snapshot of what's on the Assets page so the global chat// (⌘J) can answer "what does this chart mean / what are these@@ -332,10 +367,15 @@ export default function AssetsPage() {onError: () => toast.error(t('common.error')),})- const { data: walletsList } = useQuery({+ const { data: rawWalletsList } = useQuery({queryKey: ['asset-groups'],queryFn: () => assetGroups.list(),})+ const walletsList = useMemo(() => {+ if (!activeWalletIds) return rawWalletsList+ const allowed = new Set(activeWalletIds)+ return (rawWalletsList ?? []).filter((w) => allowed.has(w.id))+ }, [rawWalletsList, activeWalletIds])const createWalletMutation = useMutation({mutationFn: (data: { name: string; color: string }) =>diff --git a/frontend/src/pages/collections.tsx b/frontend/src/pages/collections.tsxnew file mode 100644index 00000000..69647397--- /dev/null+++ b/frontend/src/pages/collections.tsx@@ -0,0 +1,276 @@+import { useEffect, useMemo, useState } from 'react'+import { useTranslation } from 'react-i18next'+import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'+import { toast } from 'sonner'+import { collections as collectionsApi, accounts as accountsApi, assetGroups as assetGroupsApi } from '@/lib/api'+import { getAccountName } from '@/lib/account-utils'+import { PageHeader } from '@/components/page-header'+import { Button } from '@/components/ui/button'+import { Input } from '@/components/ui/input'+import { Label } from '@/components/ui/label'+import { Skeleton } from '@/components/ui/skeleton'+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogFooter,+ DialogDescription,+} from '@/components/ui/dialog'+import { FolderOpen, Plus, Pencil, Trash2 } from 'lucide-react'+import type { Collection } from '@/types'++const SWATCHES = ['#6366F1', '#0EA5E9', '#10B981', '#F59E0B', '#EF4444', '#EC4899', '#8B5CF6', '#64748B']++export default function CollectionsPage() {+ const { t } = useTranslation()+ const queryClient = useQueryClient()+ const [dialogOpen, setDialogOpen] = useState(false)+ const [editing, setEditing] = useState<Collection | null>(null)+ const [deleting, setDeleting] = useState<Collection | null>(null)++ const { data: collections, isLoading } = useQuery({+ queryKey: ['collections'],+ queryFn: collectionsApi.list,+ })+ const { data: accounts } = useQuery({+ queryKey: ['accounts'],+ queryFn: () => accountsApi.list(),+ })+ const { data: wallets } = useQuery({+ queryKey: ['asset-groups'],+ queryFn: assetGroupsApi.list,+ })++ const invalidate = () => queryClient.invalidateQueries({ queryKey: ['collections'] })++ const createMutation = useMutation({+ mutationFn: collectionsApi.create,+ onSuccess: () => { invalidate(); setDialogOpen(false); toast.success(t('collections.created')) },+ onError: () => toast.error(t('common.error')),+ })+ const updateMutation = useMutation({+ mutationFn: ({ id, ...payload }: { id: string } & Record<string, unknown>) => collectionsApi.update(id, payload),+ onSuccess: () => { invalidate(); setDialogOpen(false); setEditing(null); toast.success(t('collections.updated')) },+ onError: () => toast.error(t('common.error')),+ })+ const deleteMutation = useMutation({+ mutationFn: (id: string) => collectionsApi.delete(id),+ onSuccess: () => { invalidate(); setDeleting(null); toast.success(t('collections.deleted')) },+ onError: () => toast.error(t('common.error')),+ })++ const accountName = useMemo(() => {+ const map = new Map<string, string>()+ ;(accounts ?? []).forEach((a) => map.set(a.id, getAccountName(a)))+ return map+ }, [accounts])++ const list = collections ?? []++ return (+ <div>+ <PageHeader+ section={t('nav.groupSetup')}+ title={t('collections.title')}+ action={+ <Button onClick={() => { setEditing(null); setDialogOpen(true) }}>+ <Plus size={16} className="mr-1.5" />+ {t('collections.add')}+ </Button>+ }+ />+ <p className="text-sm text-muted-foreground mb-5 max-w-2xl">{t('collections.subtitle')}</p>++ <div className="rounded-xl border border-border/60 bg-card overflow-hidden">+ {isLoading ? (+ <div className="p-4 space-y-3">{[...Array(3)].map((_, i) => <Skeleton key={i} className="h-14 w-full rounded-lg" />)}</div>+ ) : list.length === 0 ? (+ <div className="flex flex-col items-center justify-center py-16 text-muted-foreground">+ <FolderOpen size={32} className="mb-3 opacity-40" />+ <p className="text-sm">{t('collections.empty')}</p>+ </div>+ ) : (+ <div className="divide-y divide-border/40">+ {list.map((c) => (+ <div key={c.id} className="flex items-center gap-4 px-5 py-3.5 hover:bg-muted/30 transition-colors">+ <span className="h-8 w-8 shrink-0 rounded-lg" style={{ backgroundColor: `${c.color}22` }}>+ <span className="flex h-full w-full items-center justify-center">+ <FolderOpen size={16} style={{ color: c.color }} />+ </span>+ </span>+ <div className="flex-1 min-w-0">+ <p className="text-sm font-medium text-foreground truncate">{c.name}</p>+ <p className="text-xs text-muted-foreground">+ {t('collections.accountCount', { count: c.account_count })}+ {c.wallet_count > 0 && ` · ${t('collections.walletCount', { count: c.wallet_count })}`}+ </p>+ </div>+ <div className="flex items-center gap-1 shrink-0">+ <Button variant="ghost" size="icon" onClick={() => { setEditing(c); setDialogOpen(true) }} aria-label={t('common.edit')}>+ <Pencil size={15} />+ </Button>+ <Button variant="ghost" size="icon" onClick={() => setDeleting(c)} aria-label={t('common.delete')} className="text-muted-foreground/60 hover:text-destructive">+ <Trash2 size={15} />+ </Button>+ </div>+ </div>+ ))}+ </div>+ )}+ </div>++ <CollectionDialog+ open={dialogOpen}+ onClose={() => { setDialogOpen(false); setEditing(null) }}+ collection={editing}+ accounts={(accounts ?? []).map((a) => ({ id: a.id, label: accountName.get(a.id) ?? a.name, currency: a.currency }))}+ wallets={(wallets ?? []).map((w) => ({ id: w.id, label: w.name }))}+ loading={createMutation.isPending || updateMutation.isPending}+ onSave={(payload) => {+ if (editing) updateMutation.mutate({ id: editing.id, ...payload })+ else createMutation.mutate(payload)+ }}+ />++ <Dialog open={!!deleting} onOpenChange={(o) => !o && setDeleting(null)}>+ <DialogContent className="sm:max-w-sm">+ <DialogHeader>+ <DialogTitle>{t('collections.confirmDeleteTitle')}</DialogTitle>+ <DialogDescription>{t('collections.confirmDeleteDesc', { name: deleting?.name })}</DialogDescription>+ </DialogHeader>+ <DialogFooter className="mt-2">+ <Button variant="outline" onClick={() => setDeleting(null)}>{t('common.cancel')}</Button>+ <Button variant="destructive" disabled={deleteMutation.isPending} onClick={() => deleting && deleteMutation.mutate(deleting.id)}>+ {deleteMutation.isPending ? t('common.loading') : t('common.delete')}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </div>+ )+}++function CollectionDialog({+ open, onClose, collection, accounts, wallets, loading, onSave,+}: {+ open: boolean+ onClose: () => void+ collection: Collection | null+ accounts: { id: string; label: string; currency: string }[]+ wallets: { id: string; label: string }[]+ loading: boolean+ onSave: (payload: { name: string; color: string; account_ids: string[]; wallet_ids: string[] }) => void+}) {+ const { t } = useTranslation()+ const [name, setName] = useState('')+ const [color, setColor] = useState(SWATCHES[0])+ const [selected, setSelected] = useState<Set<string>>(new Set())+ const [selectedWallets, setSelectedWallets] = useState<Set<string>>(new Set())++ useEffect(() => {+ setName(collection?.name ?? '')+ setColor(collection?.color ?? SWATCHES[0])+ setSelected(new Set(collection?.account_ids ?? []))+ setSelectedWallets(new Set(collection?.wallet_ids ?? []))+ }, [collection, open])++ const toggleIn = (setter: typeof setSelected) => (id: string) =>+ setter((prev) => {+ const next = new Set(prev)+ if (next.has(id)) next.delete(id)+ else next.add(id)+ return next+ })+ const toggle = toggleIn(setSelected)+ const toggleWallet = toggleIn(setSelectedWallets)++ return (+ <Dialog open={open} onOpenChange={(o) => !o && onClose()}>+ <DialogContent className="sm:max-w-md">+ <DialogHeader>+ <DialogTitle>{collection ? t('collections.edit') : t('collections.add')}</DialogTitle>+ </DialogHeader>+ <form+ onSubmit={(e) => {+ e.preventDefault()+ if (!name.trim()) return+ onSave({ name: name.trim(), color, account_ids: [...selected], wallet_ids: [...selectedWallets] })+ }}+ className="space-y-4"+ >+ <div className="space-y-1.5">+ <Label>{t('collections.name')}</Label>+ <Input value={name} onChange={(e) => setName(e.target.value)} required autoFocus placeholder={t('collections.namePlaceholder')} />+ </div>++ <div className="space-y-1.5">+ <Label>{t('collections.color')}</Label>+ <div className="flex flex-wrap gap-2">+ {SWATCHES.map((s) => (+ <button+ key={s}+ type="button"+ onClick={() => setColor(s)}+ className={`h-7 w-7 rounded-full transition-transform ${color === s ? 'ring-2 ring-offset-2 ring-offset-background scale-110' : ''}`}+ style={{ backgroundColor: s, boxShadow: color === s ? `0 0 0 2px ${s}` : undefined }}+ aria-label={s}+ />+ ))}+ </div>+ </div>++ <div className="space-y-1.5">+ <Label>{t('collections.accounts')}</Label>+ <div className="max-h-56 overflow-y-auto rounded-lg border border-border/60 divide-y divide-border/40">+ {accounts.length === 0 ? (+ <p className="px-3 py-3 text-xs text-muted-foreground">{t('collections.noAccounts')}</p>+ ) : (+ accounts.map((a) => (+ <label key={a.id} className="flex items-center gap-2.5 px-3 py-2 text-sm cursor-pointer hover:bg-muted/40">+ <input+ type="checkbox"+ checked={selected.has(a.id)}+ onChange={() => toggle(a.id)}+ className="h-4 w-4 rounded border-border accent-primary"+ />+ <span className="flex-1 truncate">{a.label}</span>+ <span className="text-[10.5px] uppercase tracking-wide text-muted-foreground/70">{a.currency}</span>+ </label>+ ))+ )}+ </div>+ <p className="text-xs text-muted-foreground">{t('collections.accountsHint', { count: selected.size })}</p>+ </div>++ {wallets.length > 0 && (+ <div className="space-y-1.5">+ <Label>{t('collections.wallets')}</Label>+ <div className="max-h-44 overflow-y-auto rounded-lg border border-border/60 divide-y divide-border/40">+ {wallets.map((w) => (+ <label key={w.id} className="flex items-center gap-2.5 px-3 py-2 text-sm cursor-pointer hover:bg-muted/40">+ <input+ type="checkbox"+ checked={selectedWallets.has(w.id)}+ onChange={() => toggleWallet(w.id)}+ className="h-4 w-4 rounded border-border accent-primary"+ />+ <span className="flex-1 truncate">{w.label}</span>+ </label>+ ))}+ </div>+ <p className="text-xs text-muted-foreground">{t('collections.walletsHint', { count: selectedWallets.size })}</p>+ </div>+ )}++ <DialogFooter>+ <Button type="button" variant="outline" onClick={onClose}>{t('common.cancel')}</Button>+ <Button type="submit" disabled={loading || !name.trim()}>+ {loading ? t('common.loading') : t('common.save')}+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>+ )+}diff --git a/frontend/src/pages/dashboard.tsx b/frontend/src/pages/dashboard.tsxindex 7716f489..3d87d029 100644--- a/frontend/src/pages/dashboard.tsx+++ b/frontend/src/pages/dashboard.tsx@@ -38,6 +38,7 @@ import { TransactionDrillDown, type DrillDownFilter } from '@/components/transacimport { TransactionDialog, extractApiError } from '@/components/transaction-dialog'import { usePrivacyMode } from '@/hooks/use-privacy-mode'import { useAuth } from '@/contexts/auth-context'+import { useCollectionFilter } from '@/contexts/collection-filter-context'import type { Transaction } from '@/types'function formatCurrency(value: number, currency = 'USD', locale = 'en-US') {@@ -82,31 +83,45 @@ export default function DashboardPage() {setSelectedMonth(newMonth)}+ // Active Collection filter (issue #105): scope dashboard cards to its+ // accounts. undefined when "All accounts".+ const { activeAccountIds, activeWalletIds } = useCollectionFilter()+ const acctIds = activeAccountIds ?? undefined+ const walletIds = activeWalletIds ?? undefined+ // A wallet-only collection (active, but with zero accounts) has no account+ // data — skip the account-only cards so they render empty instead of+ // silently falling back to "all accounts".+ const noAccounts = activeAccountIds !== null && activeAccountIds.length === 0+const { data: summary, isLoading: summaryLoading } = useQuery({- queryKey: ['dashboard', 'summary', selectedMonth],- queryFn: () => dashboard.summary(monthParam),+ queryKey: ['dashboard', 'summary', selectedMonth, activeAccountIds, activeWalletIds],+ queryFn: () => dashboard.summary(monthParam, undefined, acctIds, walletIds),})const { data: spending, isLoading: spendingLoading } = useQuery({- queryKey: ['dashboard', 'spending', selectedMonth],- queryFn: () => dashboard.spendingByCategory(monthParam),+ queryKey: ['dashboard', 'spending', selectedMonth, activeAccountIds],+ queryFn: () => dashboard.spendingByCategory(monthParam, acctIds),+ enabled: !noAccounts,})const prevMonth = shiftMonth(selectedMonth, -1)const { data: balanceHistory, isLoading: balanceHistoryLoading } = useQuery({- queryKey: ['dashboard', 'balance-history', selectedMonth],- queryFn: () => dashboard.balanceHistory(monthParam),+ queryKey: ['dashboard', 'balance-history', selectedMonth, activeAccountIds],+ queryFn: () => dashboard.balanceHistory(monthParam, acctIds),+ enabled: !noAccounts,})const { data: currentMonthTxs, isLoading: currentTxLoading } = useQuery({- queryKey: ['transactions', 'cumulative', selectedMonth],+ queryKey: ['transactions', 'cumulative', selectedMonth, activeAccountIds],queryFn: () => transactions.list({from: monthStart,to: monthEnd,limit: 500,exclude_transfers: true,+ account_ids: acctIds,}),+ enabled: !noAccounts,})// Resolve group_id → name for the badge on split transactions.@@ -1031,7 +1046,17 @@ export default function DashboardPage() {</div><TransactionDrillDown- filter={drillDown}+ filter={+ drillDown+ ? {+ ...drillDown,+ // Keep drill-downs consistent with the collection-scoped cards+ // they open from (e.g. "Categorize now").+ account_ids:+ drillDown.account_ids ?? (acctIds && acctIds.length > 0 ? acctIds : undefined),+ }+ : null+ }onClose={() => setDrillDown(null)}onTransactionClick={(tx) => { setEditingTx(tx); setDialogOpen(true) }}/>diff --git a/frontend/src/pages/reports.tsx b/frontend/src/pages/reports.tsxindex 13c9ddf7..c8b8bb6c 100644--- a/frontend/src/pages/reports.tsx+++ b/frontend/src/pages/reports.tsx@@ -24,6 +24,7 @@ import { Skeleton } from '@/components/ui/skeleton'import { PageHeader } from '@/components/page-header'import { usePrivacyMode } from '@/hooks/use-privacy-mode'import { useAuth } from '@/contexts/auth-context'+import { useCollectionFilter } from '@/contexts/collection-filter-context'import type { ReportResponse, CategoryTrendItem } from '@/types'function formatCurrency(value: number, currency = 'USD', locale = 'en-US') {@@ -88,14 +89,13 @@ const RANGE_LABELS: Record<string, string> = {interface ReportTab {key: stringlabelKey: string- fetch: (months: number, interval: string, period?: 'ytd') => Promise<ReportResponse>enabled: boolean}const REPORT_TABS: ReportTab[] = [- { key: 'net_worth', labelKey: 'reports.netWorth', fetch: (m, i, p) => reports.netWorth(m, i, p), enabled: true },- { key: 'income_expenses', labelKey: 'reports.incomeExpenses', fetch: (m, i, p) => reports.incomeExpenses(m, i, p), enabled: true },- { key: 'cash_flow', labelKey: 'reports.cashFlow', fetch: (m, i) => reports.cashFlow(m, i), enabled: true },+ { key: 'net_worth', labelKey: 'reports.netWorth', enabled: true },+ { key: 'income_expenses', labelKey: 'reports.incomeExpenses', enabled: true },+ { key: 'cash_flow', labelKey: 'reports.cashFlow', enabled: true },]export default function ReportsPage() {@@ -112,6 +112,15 @@ export default function ReportsPage() {const [sparklineView, setSparklineView] = useState<'byExpenses' | 'byIncome'>('byExpenses')const [sparklinePage, setSparklinePage] = useState(0)const [cashFlowBaseline, setCashFlowBaseline] = useState(false)+ // Active Collection filter (issue #105): scope all report tabs to its+ // accounts; net worth also includes the collection's wallets' assets.+ const { activeAccountIds, activeWalletIds } = useCollectionFilter()+ const acctIds = activeAccountIds ?? undefined+ const walletIds = activeWalletIds ?? undefined+ // Wallet-only collection (active, zero accounts): the account-based reports+ // (income/expenses, cash flow) have no data — only net worth (which includes+ // the wallets' assets) is meaningful.+ const noAccounts = activeAccountIds !== null && activeAccountIds.length === 0const currentTab = REPORT_TABS.find((tab) => tab.key === activeTab) ?? REPORT_TABS[0]@@ -138,12 +147,14 @@ export default function ReportsPage() {}const { data, isLoading } = useQuery<ReportResponse>({- queryKey: ['reports', activeTab, rangeKey, months, period ?? null, interval, isCashFlow ? cashFlowBaseline : false],+ queryKey: ['reports', activeTab, rangeKey, months, period ?? null, interval, isCashFlow ? cashFlowBaseline : false, activeAccountIds, activeWalletIds],queryFn: () =>isCashFlow- ? reports.cashFlow(months, interval, cashFlowBaseline)- : currentTab.fetch(months, interval, period),- enabled: currentTab.enabled,+ ? reports.cashFlow(months, interval, cashFlowBaseline, acctIds)+ : activeTab === 'income_expenses'+ ? reports.incomeExpenses(months, interval, acctIds, period)+ : reports.netWorth(months, interval, acctIds, walletIds, period),+ enabled: currentTab.enabled && !(noAccounts && activeTab !== 'net_worth'),})const summary = data?.summarydiff --git a/frontend/src/pages/transactions.tsx b/frontend/src/pages/transactions.tsxindex a2d86a34..93dca7e1 100644--- a/frontend/src/pages/transactions.tsx+++ b/frontend/src/pages/transactions.tsx@@ -49,6 +49,7 @@ import { 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'+import { useCollectionFilter } from '@/contexts/collection-filter-context'type TransactionUpdatePayload = Partial<Transaction> & {apply_to_transfer_pair?: boolean@@ -77,6 +78,7 @@ export default function TransactionsPage() {const dateLocale = useDateLocale()const { mask } = usePrivacyMode()const { user } = useAuth()+ const { activeAccountIds } = useCollectionFilter()const { canWrite } = useWorkspace()const userCurrency = user?.preferences?.currency_display ?? 'USD'const queryClient = useQueryClient()@@ -297,13 +299,26 @@ export default function TransactionsPage() {}}, [highlightId, searchQuery, filterPayee, filterCategoryIds, page])+ // Merge the global active-collection filter with the page's own account+ // filter (issue #105): an explicit on-page account selection wins; otherwise+ // scope to the active collection's accounts. null collection = all accounts.+ const effectiveAccountIds = filterAccountIds.length > 0+ ? filterAccountIds+ : (activeAccountIds ?? [])+ // Wallet-only collection active (zero accounts) and no explicit on-page+ // account filter → there are no matching transactions; show empty rather+ // than falling back to all accounts.+ const noAccounts = filterAccountIds.length === 0+ && activeAccountIds !== null && activeAccountIds.length === 0+const { data, isLoading } = useQuery({- queryKey: ['transactions', page, filterAccountIds, filterCategoryIds, filterUncategorized, filterPayee, filterGroupId, filterType, filterFrom, filterTo, filterMinAmount, filterMaxAmount, searchQuery, tagFilters, grid.sortBy, grid.sortDir],+ queryKey: ['transactions', page, effectiveAccountIds, filterCategoryIds, filterUncategorized, filterPayee, filterGroupId, filterType, filterFrom, filterTo, filterMinAmount, filterMaxAmount, searchQuery, tagFilters, grid.sortBy, grid.sortDir],+ enabled: !noAccounts,queryFn: () =>transactions.list({page,limit: 20,- account_ids: filterAccountIds.length > 0 ? filterAccountIds : undefined,+ account_ids: effectiveAccountIds.length > 0 ? effectiveAccountIds : undefined,category_ids: filterCategoryIds.length > 0 ? filterCategoryIds : undefined,payee_id: filterPayee || undefined,group_id: filterGroupId || undefined,@@ -325,7 +340,7 @@ export default function TransactionsPage() {// entire history. Free-form blob — backend turns it into a primer.const ctxFilters = {search: searchQuery || undefined,- account_ids: filterAccountIds.length ? filterAccountIds : undefined,+ account_ids: effectiveAccountIds.length ? effectiveAccountIds : undefined,category_ids: filterCategoryIds.length ? filterCategoryIds : undefined,payee_id: filterPayee || undefined,group_id: filterGroupId || undefined,@@ -749,7 +764,7 @@ export default function TransactionsPage() {await transactions.export({ transaction_ids: Array.from(selectedIds) })} else {await transactions.export({- account_ids: filterAccountIds.length > 0 ? filterAccountIds : undefined,+ account_ids: effectiveAccountIds.length > 0 ? effectiveAccountIds : undefined,category_ids: filterCategoryIds.length > 0 ? filterCategoryIds : undefined,uncategorized: filterUncategorized ? true : undefined,from: filterFrom || undefined,diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.tsindex f80dde2f..d81ea19d 100644--- a/frontend/src/types/index.ts+++ b/frontend/src/types/index.ts@@ -139,6 +139,19 @@ export interface CreditCardBill {minimum_payment: number | null}+export interface Collection {+ id: string+ user_id: string+ name: string+ icon: string+ color: string+ position: number+ account_ids: string[]+ account_count: number+ wallet_ids: string[]+ wallet_count: number+}+export interface AccountSummary {account_id: stringcurrent_balance: number