Skip to content

Open-source personal finance manager. Self-hosted, privacy-first.

adding investments from connected accounts from Pluggy connector (#104)

Tássio Noronha83d87899bb50
diff --git a/backend/alembic/versions/032_assets_sync_fields.py b/backend/alembic/versions/032_assets_sync_fields.py
new file mode 100644
index 00000000..e241a9aa
--- /dev/null
+++ b/backend/alembic/versions/032_assets_sync_fields.py
@@ -0,0 +1,58 @@
+"""add sync fields to assets for provider-agnostic investment holdings
+
+Revision ID: 032
+Revises: 031
+Create Date: 2026-04-20
+"""
+from typing import Sequence, Union
+
+import sqlalchemy as sa
+from alembic import op
+
+revision: str = "032"
+down_revision: Union[str, None] = "031"
+branch_labels: Union[str, Sequence[str], None] = None
+depends_on: Union[str, Sequence[str], None] = None
+
+
+def upgrade() -> None:
+ op.add_column(
+ "assets",
+ sa.Column(
+ "connection_id",
+ sa.UUID(),
+ sa.ForeignKey("bank_connections.id", ondelete="SET NULL"),
+ nullable=True,
+ ),
+ )
+ op.add_column("assets", sa.Column("external_id", sa.String(255), nullable=True))
+ op.add_column(
+ "assets",
+ sa.Column("source", sa.String(50), nullable=False, server_default="manual"),
+ )
+ op.add_column("assets", sa.Column("isin", sa.String(20), nullable=True))
+ op.add_column("assets", sa.Column("maturity_date", sa.Date(), nullable=True))
+ op.add_column("assets", sa.Column("external_metadata", sa.JSON(), nullable=True))
+
+ # Partial unique index: one synced asset per (user, source, external_id).
+ # NULL external_ids (manual entries) are exempt so users can have many
+ # manual assets with the same name.
+ op.create_index(
+ "ux_assets_user_source_external",
+ "assets",
+ ["user_id", "source", "external_id"],
+ unique=True,
+ postgresql_where=sa.text("external_id IS NOT NULL"),
+ )
+ op.create_index("ix_assets_connection_id", "assets", ["connection_id"])
+
+
+def downgrade() -> None:
+ op.drop_index("ix_assets_connection_id", "assets")
+ op.drop_index("ux_assets_user_source_external", "assets")
+ op.drop_column("assets", "external_metadata")
+ op.drop_column("assets", "maturity_date")
+ op.drop_column("assets", "isin")
+ op.drop_column("assets", "source")
+ op.drop_column("assets", "external_id")
+ op.drop_column("assets", "connection_id")
diff --git a/backend/alembic/versions/033_categories_treat_as_transfer.py b/backend/alembic/versions/033_categories_treat_as_transfer.py
new file mode 100644
index 00000000..dd553768
--- /dev/null
+++ b/backend/alembic/versions/033_categories_treat_as_transfer.py
@@ -0,0 +1,197 @@
+"""add treat_as_transfer flag and seed Investimentos category + default rule
+
+Revision ID: 033
+Revises: 032
+Create Date: 2026-04-20
+
+Adds a boolean `treat_as_transfer` on categories. Categories with this
+flag are treated like paired transfers in report aggregations — their
+transactions are excluded from income/expense sums. This makes one-sided
+movements (investment applications/redemptions, loan repayments) stop
+polluting P&L figures without needing a real counterpart transaction.
+
+For every existing user we:
+ 1. Create an "Investments" / "Investimentos" category if missing, with
+ the flag set and is_system=true.
+ 2. Create a default rule matching PT investment keywords
+ (APLICACAO, RESGATE, CDB, TESOURO, ...) → that category.
+ 3. Backfill: apply the rule to existing uncategorized transactions.
+
+User intent is respected — already-categorized transactions are never
+touched. The PT rule is a harmless no-op for users whose bank data
+doesn't contain those patterns.
+"""
+from typing import Sequence, Union
+
+import sqlalchemy as sa
+from alembic import op
+
+revision: str = "033"
+down_revision: Union[str, None] = "032"
+branch_labels: Union[str, Sequence[str], None] = None
+depends_on: Union[str, Sequence[str], None] = None
+
+
+INVESTMENTS_CATEGORY_PT = "Investimentos"
+INVESTMENTS_CATEGORY_EN = "Investments"
+INVESTMENTS_ICON = "trending-up"
+INVESTMENTS_COLOR = "#0EA5E9"
+
+RULE_NAME = "Investimentos (Aplicação / Resgate)"
+# Keywords checked one-by-one as OR'd `contains` conditions. The rule engine
+# normalizes both sides (uppercase + strip accents) so "APLICACAO" matches
+# "Aplicação", "aplicacao", etc. — no need for per-accent variants.
+RULE_KEYWORDS = [
+ "APLICACAO",
+ "RESGATE",
+ "CDB",
+ "LCA",
+ "LCI",
+ "DEBENTURE",
+ "TESOURO",
+ "RENDA FIXA",
+ "FUNDO DE INVESTIMENTO",
+ "DEB FUNDO",
+ "CREDITO FUNDO",
+ "COE",
+]
+# Regex used only for the one-shot backfill SQL below. Postgres ~* is
+# case-insensitive but accent-sensitive; the app-side engine strips accents,
+# so we include both variants here to match the full historical set.
+BACKFILL_REGEX = (
+ r"APLICACAO|APLICAÇÃO|RESGATE|CDB|LCA|LCI|DEBENTURE|TESOURO|"
+ r"RENDA FIXA|FUNDO DE INVESTIMENTO|DEB FUNDO|"
+ r"CREDITO FUNDO|CRÉDITO FUNDO|COE"
+)
+
+
+def upgrade() -> None:
+ # 1. Column on categories.
+ op.add_column(
+ "categories",
+ sa.Column(
+ "treat_as_transfer",
+ sa.Boolean(),
+ nullable=False,
+ server_default=sa.false(),
+ ),
+ )
+
+ bind = op.get_bind()
+
+ # 2. Resolve each user's language from preferences JSON. Default to
+ # pt-BR if unreadable — the app is Brazilian-first and the rule
+ # patterns won't match EN descriptions anyway.
+ users = bind.execute(
+ sa.text("SELECT id, preferences FROM users")
+ ).fetchall()
+
+ for row in users:
+ user_id = row[0]
+ prefs = row[1] or {}
+ lang = (prefs.get("language") or "pt-BR") if isinstance(prefs, dict) else "pt-BR"
+ cat_name = INVESTMENTS_CATEGORY_EN if lang == "en" else INVESTMENTS_CATEGORY_PT
+
+ # Find "Other" group so the new category has a home; fall back to NULL.
+ group_id = bind.execute(
+ sa.text(
+ "SELECT id FROM category_groups WHERE user_id = :uid "
+ "AND name IN ('Outros', 'Other') LIMIT 1"
+ ),
+ {"uid": user_id},
+ ).scalar()
+
+ # 3. Upsert the category — idempotent on re-run; don't clobber
+ # an existing one the user may have renamed or customized.
+ category_id = bind.execute(
+ sa.text(
+ "SELECT id FROM categories WHERE user_id = :uid AND name = :name"
+ ),
+ {"uid": user_id, "name": cat_name},
+ ).scalar()
+
+ if category_id is None:
+ category_id = bind.execute(
+ sa.text(
+ "INSERT INTO categories "
+ "(id, user_id, group_id, name, icon, color, is_system, treat_as_transfer) "
+ "VALUES (gen_random_uuid(), :uid, :gid, :name, :icon, :color, true, true) "
+ "RETURNING id"
+ ),
+ {
+ "uid": user_id,
+ "gid": group_id,
+ "name": cat_name,
+ "icon": INVESTMENTS_ICON,
+ "color": INVESTMENTS_COLOR,
+ },
+ ).scalar()
+ else:
+ # Ensure the flag is set even if the category already existed.
+ bind.execute(
+ sa.text(
+ "UPDATE categories SET treat_as_transfer = true WHERE id = :cid"
+ ),
+ {"cid": category_id},
+ )
+
+ # 4. Seed the default rule if missing.
+ existing_rule = bind.execute(
+ sa.text(
+ "SELECT id FROM rules WHERE user_id = :uid AND name = :name"
+ ),
+ {"uid": user_id, "name": RULE_NAME},
+ ).scalar()
+
+ if existing_rule is None:
+ import json
+
+ conditions = json.dumps([
+ {"field": "description", "op": "contains", "value": kw}
+ for kw in RULE_KEYWORDS
+ ])
+ actions = json.dumps([
+ {"op": "set_category", "value": str(category_id)},
+ ])
+ bind.execute(
+ sa.text(
+ "INSERT INTO rules "
+ "(id, user_id, name, conditions_op, conditions, actions, priority, is_active) "
+ "VALUES (gen_random_uuid(), :uid, :name, 'or', "
+ "CAST(:cond AS jsonb), CAST(:act AS jsonb), 20, true)"
+ ),
+ {
+ "uid": user_id,
+ "name": RULE_NAME,
+ "cond": conditions,
+ "act": actions,
+ },
+ )
+
+ # 5. Backfill — assign the new category to uncategorized transactions
+ # whose description matches the regex. Only touches uncategorized
+ # rows so a user who manually categorized an APLICACAO into
+ # "Poupança" or similar keeps their choice. Postgres regex
+ # matches are case-sensitive by default; use ~* for case-insensitive
+ # so lowercase variants ("aplicação") also match.
+ bind.execute(
+ sa.text(
+ "UPDATE transactions "
+ "SET category_id = :cid "
+ "WHERE user_id = :uid "
+ "AND category_id IS NULL "
+ "AND description ~* :pattern "
+ "AND source != 'opening_balance'"
+ ),
+ {
+ "cid": category_id,
+ "uid": user_id,
+ "pattern": BACKFILL_REGEX,
+ },
+ )
+
+
+def downgrade() -> None:
+ # Keep seeded categories and rules — users may have re-categorized
+ # transactions against them. Only drop the column.
+ op.drop_column("categories", "treat_as_transfer")
diff --git a/backend/alembic/versions/034_asset_groups.py b/backend/alembic/versions/034_asset_groups.py
new file mode 100644
index 00000000..d66e5ed9
--- /dev/null
+++ b/backend/alembic/versions/034_asset_groups.py
@@ -0,0 +1,115 @@
+"""add asset_groups (wallets) and asset.group_id; backfill per connection
+
+Revision ID: 034
+Revises: 033
+Create Date: 2026-04-20
+
+Introduces user-defined "wallets" that bundle related assets under one
+total. Synced assets get auto-grouped by their provider connection so
+brokerages with many holdings collapse into a single expandable row
+instead of many sibling cards.
+
+Existing data is migrated: for every bank connection that has at least
+one synced asset, a group is created (named after the institution) and
+its assets are linked into it. Manual assets stay ungrouped unless the
+user moves them in themselves.
+"""
+from typing import Sequence, Union
+
+import sqlalchemy as sa
+from alembic import op
+
+revision: str = "034"
+down_revision: Union[str, None] = "033"
+branch_labels: Union[str, Sequence[str], None] = None
+depends_on: Union[str, Sequence[str], None] = None
+
+
+def upgrade() -> None:
+ op.create_table(
+ "asset_groups",
+ sa.Column("id", sa.UUID(), primary_key=True),
+ sa.Column("user_id", sa.UUID(), sa.ForeignKey("users.id"), nullable=False),
+ sa.Column("name", sa.String(100), nullable=False),
+ sa.Column("icon", sa.String(50), nullable=False, server_default="wallet"),
+ sa.Column("color", sa.String(7), nullable=False, server_default="#0EA5E9"),
+ sa.Column("position", sa.Integer(), nullable=False, server_default="0"),
+ sa.Column("source", sa.String(50), nullable=False, server_default="manual"),
+ sa.Column(
+ "connection_id",
+ sa.UUID(),
+ sa.ForeignKey("bank_connections.id", ondelete="SET NULL"),
+ nullable=True,
+ ),
+ sa.Column("external_id", sa.String(255), nullable=True),
+ )
+ op.create_index("ix_asset_groups_user_id", "asset_groups", ["user_id"])
+ op.create_index(
+ "ux_asset_groups_user_source_external",
+ "asset_groups",
+ ["user_id", "source", "external_id"],
+ unique=True,
+ postgresql_where=sa.text("external_id IS NOT NULL"),
+ )
+
+ op.add_column(
+ "assets",
+ sa.Column(
+ "group_id",
+ sa.UUID(),
+ sa.ForeignKey("asset_groups.id", ondelete="SET NULL"),
+ nullable=True,
+ ),
+ )
+ op.create_index("ix_assets_group_id", "assets", ["group_id"])
+
+ # Backfill: one group per connection that has synced assets. Named
+ # after the institution; positioned after any existing groups. We
+ # re-use the provider key (connection.external_id = Pluggy item id)
+ # as the group's external_id so subsequent syncs upsert it in place.
+ bind = op.get_bind()
+ bind.execute(
+ sa.text(
+ """
+ INSERT INTO asset_groups
+ (id, user_id, name, icon, color, position, source, connection_id, external_id)
+ SELECT
+ gen_random_uuid(),
+ bc.user_id,
+ bc.institution_name,
+ 'wallet',
+ '#0EA5E9',
+ ROW_NUMBER() OVER (PARTITION BY bc.user_id ORDER BY bc.created_at) - 1,
+ bc.provider,
+ bc.id,
+ bc.external_id
+ FROM bank_connections bc
+ WHERE EXISTS (
+ SELECT 1 FROM assets a
+ WHERE a.connection_id = bc.id
+ AND a.source != 'manual'
+ )
+ """
+ )
+ )
+ bind.execute(
+ sa.text(
+ """
+ UPDATE assets a
+ SET group_id = g.id
+ FROM asset_groups g
+ WHERE a.connection_id = g.connection_id
+ AND a.user_id = g.user_id
+ AND a.source = g.source
+ AND a.group_id IS NULL
+ """
+ )
+ )
+
+
+def downgrade() -> None:
+ op.drop_index("ix_assets_group_id", "assets")
+ op.drop_column("assets", "group_id")
+ op.drop_index("ux_asset_groups_user_source_external", "asset_groups")
+ op.drop_index("ix_asset_groups_user_id", "asset_groups")
+ op.drop_table("asset_groups")
diff --git a/backend/alembic/versions/035_deduplicate_wallet_names.py b/backend/alembic/versions/035_deduplicate_wallet_names.py
new file mode 100644
index 00000000..f580b395
--- /dev/null
+++ b/backend/alembic/versions/035_deduplicate_wallet_names.py
@@ -0,0 +1,64 @@
+"""disambiguate existing synced wallets with duplicate names
+
+Revision ID: 035
+Revises: 034
+Create Date: 2026-04-20
+
+Migration 034 auto-created one wallet per bank connection named after
+the institution. Sandbox users hit the case where several connections
+come back with the same institution_name (e.g. "MeuPluggy"), leaving
+multiple identically-named wallets that are hard to tell apart.
+
+This migration appends " 2", " 3", ... to the second+ occurrence of any
+duplicated wallet name per user. Oldest wallet keeps the bare name (by
+created-like order: the `id` UUIDv4 isn't time-ordered, so we fall back
+to sort by `position` which was set by creation order in 034).
+
+Runs once and is safe to re-run — it only touches rows whose name is
+still exactly the duplicate base; wallets the user already renamed are
+left alone.
+"""
+from typing import Sequence, Union
+
+import sqlalchemy as sa
+from alembic import op
+
+revision: str = "035"
+down_revision: Union[str, None] = "034"
+branch_labels: Union[str, Sequence[str], None] = None
+depends_on: Union[str, Sequence[str], None] = None
+
+
+def upgrade() -> None:
+ # For each (user_id, name) with multiple rows, rename the 2nd, 3rd, ...
+ # by appending a numeric suffix. Uses window functions for a single pass.
+ op.execute(
+ sa.text(
+ """
+ WITH ranked AS (
+ SELECT
+ id,
+ name,
+ ROW_NUMBER() OVER (
+ PARTITION BY user_id, name
+ ORDER BY position, id
+ ) AS rn,
+ COUNT(*) OVER (PARTITION BY user_id, name) AS total
+ FROM asset_groups
+ )
+ UPDATE asset_groups ag
+ SET name = ranked.name || ' ' || ranked.rn
+ FROM ranked
+ WHERE ag.id = ranked.id
+ AND ranked.total > 1
+ AND ranked.rn > 1
+ """
+ )
+ )
+
+
+def downgrade() -> None:
+ # No reliable inverse — we can't tell which wallets were renamed by
+ # this migration vs the user. Leaving as a no-op is safer than
+ # stripping suffixes and potentially clobbering user edits.
+ pass
diff --git a/backend/alembic/versions/036_rewrite_investments_rule_conditions.py b/backend/alembic/versions/036_rewrite_investments_rule_conditions.py
new file mode 100644
index 00000000..4d156c1a
--- /dev/null
+++ b/backend/alembic/versions/036_rewrite_investments_rule_conditions.py
@@ -0,0 +1,82 @@
+"""rewrite Investimentos rule from a single regex to OR'd `contains` conditions
+
+Revision ID: 036
+Revises: 035
+Create Date: 2026-04-20
+
+The seed in 033 created one condition using a long pipe-separated regex.
+That works but reads poorly in the rules UI — an unreadable wall of tokens
+that users can't meaningfully edit. This migration rewrites any rule still
+in that form into a list of OR'd `contains` conditions, one per keyword.
+Semantically identical (the rule engine normalizes accents/case on both
+sides), much easier to skim and tweak. Idempotent: rules already in the
+new shape are left alone, and user-edited rules are only touched if they
+still match the original single-regex signature.
+"""
+from typing import Sequence, Union
+
+import json
+import sqlalchemy as sa
+from alembic import op
+
+revision: str = "036"
+down_revision: Union[str, None] = "035"
+branch_labels: Union[str, Sequence[str], None] = None
+depends_on: Union[str, Sequence[str], None] = None
+
+
+RULE_NAME = "Investimentos (Aplicação / Resgate)"
+NEW_KEYWORDS = [
+ "APLICACAO",
+ "RESGATE",
+ "CDB",
+ "LCA",
+ "LCI",
+ "DEBENTURE",
+ "TESOURO",
+ "RENDA FIXA",
+ "FUNDO DE INVESTIMENTO",
+ "DEB FUNDO",
+ "CREDITO FUNDO",
+ "COE",
+]
+
+
+def upgrade() -> None:
+ bind = op.get_bind()
+
+ rows = bind.execute(
+ sa.text(
+ "SELECT id, conditions, conditions_op FROM rules WHERE name = :name"
+ ),
+ {"name": RULE_NAME},
+ ).fetchall()
+
+ new_conditions = [
+ {"field": "description", "op": "contains", "value": kw}
+ for kw in NEW_KEYWORDS
+ ]
+ payload = json.dumps(new_conditions)
+
+ for row in rows:
+ rule_id, conditions, _ = row
+ # Only rewrite rules still in the legacy single-regex shape. If a
+ # user has already edited this rule by hand, their version wins.
+ if (
+ isinstance(conditions, list)
+ and len(conditions) == 1
+ and conditions[0].get("op") == "regex"
+ ):
+ bind.execute(
+ sa.text(
+ "UPDATE rules SET conditions = CAST(:c AS jsonb), "
+ "conditions_op = 'or' WHERE id = :id"
+ ),
+ {"c": payload, "id": rule_id},
+ )
+
+
+def downgrade() -> None:
+ # No-op: the regex form is a worse UX and we don't want to restore it.
+ # Users who want it back can edit the rule by hand.
+ pass
diff --git a/backend/app/api/asset_groups.py b/backend/app/api/asset_groups.py
new file mode 100644
index 00000000..10fec124
--- /dev/null
+++ b/backend/app/api/asset_groups.py
@@ -0,0 +1,56 @@
+import uuid
+
+from fastapi import APIRouter, Depends, HTTPException, status
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.core.auth import current_active_user
+from app.core.database import get_async_session
+from app.models.user import User
+from app.schemas.asset_group import AssetGroupCreate, AssetGroupRead, AssetGroupUpdate
+from app.services import asset_group_service
+
+router = APIRouter(prefix="/api/asset-groups", tags=["asset-groups"])
+
+
[email protected]("", response_model=list[AssetGroupRead])
+async def list_groups(
+ session: AsyncSession = Depends(get_async_session),
+ user: User = Depends(current_active_user),
+):
+ return await asset_group_service.get_groups(session, user.id)
+
+
[email protected]("", response_model=AssetGroupRead, status_code=status.HTTP_201_CREATED)
+async def create_group(
+ data: AssetGroupCreate,
+ session: AsyncSession = Depends(get_async_session),
+ user: User = Depends(current_active_user),
+):
+ return await asset_group_service.create_group(session, user.id, data)
+
+
[email protected]("/{group_id}", response_model=AssetGroupRead)
+async def update_group(
+ group_id: uuid.UUID,
+ data: AssetGroupUpdate,
+ session: AsyncSession = Depends(get_async_session),
+ user: User = Depends(current_active_user),
+):
+ group = await asset_group_service.update_group(session, group_id, user.id, data)
+ if not group:
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Group not found")
+ return group
+
+
[email protected]("/{group_id}", status_code=status.HTTP_204_NO_CONTENT)
+async def delete_group(
+ group_id: uuid.UUID,
+ session: AsyncSession = Depends(get_async_session),
+ user: User = Depends(current_active_user),
+):
+ deleted = await asset_group_service.delete_group(session, group_id, user.id)
+ if not deleted:
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail="Group not found",
+ )
diff --git a/backend/app/main.py b/backend/app/main.py
index c08cd948..5db46b0f 100644
--- a/backend/app/main.py
+++ b/backend/app/main.py
@@ -17,6 +17,7 @@ from app.api.import_transactions import router as import_router
from app.api.recurring_transactions import router as recurring_router
from app.api.rules import router as rules_router
from app.api.assets import router as assets_router
+from app.api.asset_groups import router as asset_groups_router
from app.api.reports import router as reports_router
from app.api.search import router as search_router
from app.api.setup import router as setup_router
@@ -112,6 +113,7 @@ app.include_router(recurring_router)
app.include_router(budgets_router)
app.include_router(goals_router)
app.include_router(assets_router)
+app.include_router(asset_groups_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__.py
index 2e5a3711..dfd097e2 100644
--- a/backend/app/models/__init__.py
+++ b/backend/app/models/__init__.py
@@ -9,6 +9,7 @@ from app.models.recurring_transaction import RecurringTransaction
from app.models.budget import Budget
from app.models.import_log import ImportLog
from app.models.asset import Asset
+from app.models.asset_group import AssetGroup
from app.models.asset_value import AssetValue
from app.models.fx_rate import FxRate
from app.models.transaction_attachment import TransactionAttachment
@@ -28,6 +29,7 @@ __all__ = [
"Budget",
"ImportLog",
"Asset",
+ "AssetGroup",
"AssetValue",
"FxRate",
"TransactionAttachment",
diff --git a/backend/app/models/asset.py b/backend/app/models/asset.py
index df4c1e89..cd7f2bc8 100644
--- a/backend/app/models/asset.py
+++ b/backend/app/models/asset.py
@@ -1,15 +1,16 @@
import uuid
from datetime import date
from decimal import Decimal
-from typing import TYPE_CHECKING, Optional
+from typing import TYPE_CHECKING, Any, Optional
-from sqlalchemy import Boolean, Date, ForeignKey, Integer, Numeric, String
+from sqlalchemy import JSON, Boolean, Date, ForeignKey, Integer, Numeric, String
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.asset_group import AssetGroup
from app.models.asset_value import AssetValue
@@ -35,4 +36,24 @@ class Asset(Base):
is_archived: Mapped[bool] = mapped_column(Boolean, default=False)
position: Mapped[int] = mapped_column(Integer, default=0)
+ # Provider-agnostic sync fields. `source` tags where the asset came from
+ # ("manual", "pluggy", ...). `external_id` is the source's stable ID for
+ # the same logical holding across syncs. `connection_id` links back to the
+ # provider connection when the source requires authentication.
+ connection_id: Mapped[Optional[uuid.UUID]] = mapped_column(
+ UUID(as_uuid=True), ForeignKey("bank_connections.id", ondelete="SET NULL"), nullable=True
+ )
+ external_id: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
+ source: Mapped[str] = mapped_column(String(50), default="manual")
+ isin: Mapped[Optional[str]] = mapped_column(String(20), nullable=True)
+ maturity_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
+ external_metadata: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
+
+ # Optional parent group ("wallet"). NULL means ungrouped. Deleting a
+ # group nullifies this field rather than removing the asset.
+ group_id: Mapped[Optional[uuid.UUID]] = mapped_column(
+ UUID(as_uuid=True), ForeignKey("asset_groups.id", ondelete="SET NULL"), nullable=True
+ )
+
values: Mapped[list["AssetValue"]] = relationship(back_populates="asset", cascade="all, delete-orphan")
+ group: Mapped[Optional["AssetGroup"]] = relationship(back_populates="assets")
diff --git a/backend/app/models/asset_group.py b/backend/app/models/asset_group.py
new file mode 100644
index 00000000..7acb57ad
--- /dev/null
+++ b/backend/app/models/asset_group.py
@@ -0,0 +1,45 @@
+import uuid
+from typing import TYPE_CHECKING, Optional
+
+from sqlalchemy import ForeignKey, Integer, String
+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.asset import Asset
+ from app.models.user import User
+
+
+class AssetGroup(Base):
+ """A user-facing "wallet" that bundles related assets under one total.
+
+ Groups can be manually created (the user picks a name like "US Stocks"
+ or "Long-term fixed income") or auto-created when a provider syncs:
+ each Pluggy item becomes one group so brokerage positions collapse
+ into a single expandable row instead of 20 sibling cards.
+
+ Assets link via nullable `group_id` — deleting a group leaves its
+ assets behind ungrouped rather than cascading away real user data.
+ """
+
+ __tablename__ = "asset_groups"
+
+ 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"))
+ name: Mapped[str] = mapped_column(String(100))
+ icon: Mapped[str] = mapped_column(String(50), default="wallet")
+ color: Mapped[str] = mapped_column(String(7), default="#0EA5E9")
+ position: Mapped[int] = mapped_column(Integer, default=0)
+
+ # Provenance fields — mirror Asset's sync fields so sync code can
+ # upsert groups idempotently by (user_id, source, external_id).
+ source: Mapped[str] = mapped_column(String(50), default="manual")
+ connection_id: Mapped[Optional[uuid.UUID]] = mapped_column(
+ UUID(as_uuid=True), ForeignKey("bank_connections.id", ondelete="SET NULL"), nullable=True
+ )
+ external_id: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
+
+ user: Mapped["User"] = relationship()
+ assets: Mapped[list["Asset"]] = relationship(back_populates="group")
diff --git a/backend/app/models/category.py b/backend/app/models/category.py
index 67015d67..dfa01c82 100644
--- a/backend/app/models/category.py
+++ b/backend/app/models/category.py
@@ -23,5 +23,13 @@ class Category(Base):
color: Mapped[str] = mapped_column(String(7), default="#6B7280")
is_system: Mapped[bool] = mapped_column(Boolean, default=False)
+ # Flag for "money that moves rather than money earned or spent".
+ # Transactions in these categories are excluded from income/expense
+ # aggregations in dashboards and reports — same treatment as paired
+ # transfers (transfer_pair_id IS NOT NULL), but category-based so we
+ # can catch one-sided movements like an investment application where
+ # the counterpart lives in Assets, not Accounts.
+ treat_as_transfer: Mapped[bool] = mapped_column(Boolean, default=False, server_default="false")
+
user: Mapped["User"] = relationship(back_populates="categories")
group: Mapped[Optional["CategoryGroup"]] = relationship(back_populates="categories")
diff --git a/backend/app/providers/__init__.py b/backend/app/providers/__init__.py
index 1b7d0afb..415b40e1 100644
--- a/backend/app/providers/__init__.py
+++ b/backend/app/providers/__init__.py
@@ -1,4 +1,11 @@
-from app.providers.base import BankProvider, AccountData, TransactionData, ConnectionData, ConnectTokenData
+from app.providers.base import (
+ AccountData,
+ BankProvider,
+ ConnectTokenData,
+ ConnectionData,
+ HoldingData,
+ TransactionData,
+)
# Registry of available providers.
_PROVIDERS: dict[str, type[BankProvider]] = {}
@@ -85,6 +92,7 @@ __all__ = [
"TransactionData",
"ConnectionData",
"ConnectTokenData",
+ "HoldingData",
"register_provider",
"get_provider",
"list_providers",
diff --git a/backend/app/providers/base.py b/backend/app/providers/base.py
index 364c9a12..0f3c8410 100644
--- a/backend/app/providers/base.py
+++ b/backend/app/providers/base.py
@@ -53,6 +53,31 @@ class ConnectTokenData:
access_token: str
+@dataclass
+class HoldingData:
+ """A normalized investment holding, provider-agnostic.
+
+ Providers that don't expose holdings-style data return an empty list
+ from `get_holdings`. Provider-specific fields that don't fit the common
+ shape (rate, profit, issuer, status, type/subtype labels, etc.) go in
+ `metadata` as-is — the sync layer stores it on Asset.external_metadata
+ without trying to normalize it.
+ """
+
+ external_id: str
+ name: str
+ currency: str
+ current_value: Decimal
+ quantity: Optional[Decimal] = None
+ unit_price: Optional[Decimal] = None
+ purchase_price: Optional[Decimal] = None
+ purchase_date: Optional[date] = None
+ isin: Optional[str] = None
+ maturity_date: Optional[date] = None
+ is_withdrawn: bool = False # provider signaled the position was sold/transferred
+ metadata: Optional[dict] = None
+
+
class FxRateProvider(ABC):
"""Abstract interface for FX rate providers."""
@@ -124,3 +149,12 @@ class BankProvider(ABC):
async def refresh_credentials(self, credentials: dict) -> dict:
"""Refresh access token if needed."""
...
+
+ async def get_holdings(self, credentials: dict) -> list[HoldingData]:
+ """Fetch investment holdings for a connection.
+
+ Providers that don't expose holdings (cash-only accounts, custom
+ script providers without brokerage data, etc.) can rely on the
+ default empty list.
+ """
+ return []
diff --git a/backend/app/providers/pluggy.py b/backend/app/providers/pluggy.py
index e058c994..7b8a2902 100644
--- a/backend/app/providers/pluggy.py
+++ b/backend/app/providers/pluggy.py
@@ -11,6 +11,7 @@ from app.providers.base import (
BankProvider,
ConnectionData,
ConnectTokenData,
+ HoldingData,
TransactionData,
)
@@ -27,6 +28,74 @@ def _parse_day(value) -> Optional[int]:
return None
+def _decimal_or_none(value) -> Optional[Decimal]:
+ if value is None:
+ return None
+ try:
+ return Decimal(str(value))
+ except (ValueError, TypeError):
+ return None
+
+
+def _date_or_none(value) -> Optional[date]:
+ if not value:
+ return None
+ try:
+ return date.fromisoformat(str(value)[:10])
+ except ValueError:
+ return None
+
+
+# Fields from Pluggy /investments we promote to HoldingData top-level.
+# Everything else is preserved verbatim in `metadata` so we don't lose
+# information we might want later (status, rates, issuer, institution,
+# nested `metadata` for pensions, etc.) without tying our schema to Pluggy.
+_HOLDING_PROMOTED_KEYS = {
+ "id", "balance", "currencyCode", "quantity", "value",
+ "amountOriginal", "dueDate", "isin", "issueDate",
+}
+
+# Pluggy `type` values where `issueDate` equals the user's purchase date.
+# For EQUITY/MUTUAL_FUND/ETF, issueDate is when the fund/stock was created
+# — potentially years before the user bought in. Using it as purchase_date
+# would produce badly-wrong evolution charts, so we skip it for those.
+_ISSUE_DATE_IS_PURCHASE_DATE = {"FIXED_INCOME", "COE"}
+
+
+def _build_holding_data(inv: dict) -> HoldingData:
+ """Map a Pluggy investment payload to HoldingData.
+
+ `balance` is chosen over `amount` for current value: Pluggy documents
+ balance as net of taxes/fees (what a user could actually withdraw),
+ while amount is gross. The gross figure is kept in metadata for users
+ who care about the distinction.
+ """
+ current_value = _decimal_or_none(inv.get("balance")) or Decimal("0")
+ pluggy_status = (inv.get("status") or "").upper()
+ pluggy_type = (inv.get("type") or "").upper()
+
+ purchase_date: Optional[date] = None
+ if pluggy_type in _ISSUE_DATE_IS_PURCHASE_DATE:
+ purchase_date = _date_or_none(inv.get("issueDate"))
+
+ metadata = {k: v for k, v in inv.items() if k not in _HOLDING_PROMOTED_KEYS}
+
+ return HoldingData(
+ external_id=str(inv["id"]),
+ name=inv.get("name") or "Investment",
+ currency=inv.get("currencyCode") or "BRL",
+ current_value=current_value,
+ quantity=_decimal_or_none(inv.get("quantity")),
+ unit_price=_decimal_or_none(inv.get("value")),
+ purchase_price=_decimal_or_none(inv.get("amountOriginal")),
+ purchase_date=purchase_date,
+ isin=inv.get("isin") or None,
+ maturity_date=_date_or_none(inv.get("dueDate")),
+ is_withdrawn=pluggy_status == "TOTAL_WITHDRAWAL",
+ metadata=metadata or None,
+ )
+
+
def _build_account_data(acc: dict, type_mapper) -> AccountData:
"""Map a Pluggy account payload to AccountData, including creditData when present."""
account_type = type_mapper(acc.get("type", ""))
@@ -309,6 +378,41 @@ class PluggyProvider(BankProvider):
# Pluggy manages API keys at the provider level, not per-connection
return credentials
+ async def get_holdings(self, credentials: dict) -> list[HoldingData]:
+ """Fetch investment holdings from Pluggy's /investments endpoint.
+
+ /accounts only returns BANK/CREDIT types — brokerage positions,
+ fixed income, funds, pensions, etc. live under /investments and
+ come back with richer fields (quantity, unit price, profit,
+ maturity). We normalize to HoldingData; the rest goes into
+ `metadata` so downstream code doesn't leak Pluggy specifics.
+ """
+ item_id = credentials["item_id"]
+ headers = await self._headers()
+ holdings: list[HoldingData] = []
+ page = 1
+
+ async with httpx.AsyncClient(timeout=30.0) as client:
+ while True:
+ resp = await client.get(
+ f"{PLUGGY_API_BASE}/investments",
+ headers=headers,
+ params={"itemId": item_id, "pageSize": 500, "page": page},
+ )
+ resp.raise_for_status()
+ data = resp.json()
+
+ results = data.get("results", [])
+ for inv in results:
+ holdings.append(_build_holding_data(inv))
+
+ total_pages = data.get("totalPages", 1)
+ if page >= total_pages or not results:
+ break
+ page += 1
+
+ return holdings
+
@staticmethod
def _extract_payee(txn: dict, txn_type: str, payee_source: str = "auto") -> Optional[str]:
"""Extract payee name based on configured source."""
diff --git a/backend/app/schemas/asset.py b/backend/app/schemas/asset.py
index d86529e9..642dfa5e 100644
--- a/backend/app/schemas/asset.py
+++ b/backend/app/schemas/asset.py
@@ -23,6 +23,7 @@ class AssetCreate(BaseModel):
growth_start_date: Optional[date] = None
is_archived: bool = False
position: int = 0
+ group_id: Optional[uuid.UUID] = None
class AssetUpdate(BaseModel):
@@ -41,6 +42,10 @@ class AssetUpdate(BaseModel):
growth_start_date: Optional[date] = None
is_archived: Optional[bool] = None
position: Optional[int] = None
+ # Use a sentinel to differentiate "don't change group" (field omitted)
+ # from "remove from group" (explicit null). Pydantic's exclude_unset
+ # already handles this via model_dump.
+ group_id: Optional[uuid.UUID] = None
class AssetRead(BaseModel):
@@ -66,6 +71,11 @@ class AssetRead(BaseModel):
gain_loss: Optional[float] = None
gain_loss_primary: Optional[float] = None
value_count: int = 0
+ source: str = "manual"
+ connection_id: Optional[uuid.UUID] = None
+ isin: Optional[str] = None
+ maturity_date: Optional[date] = None
+ group_id: Optional[uuid.UUID] = None
model_config = ConfigDict(from_attributes=True)
diff --git a/backend/app/schemas/asset_group.py b/backend/app/schemas/asset_group.py
new file mode 100644
index 00000000..b56ab576
--- /dev/null
+++ b/backend/app/schemas/asset_group.py
@@ -0,0 +1,41 @@
+import uuid
+from typing import Optional
+
+from pydantic import BaseModel, ConfigDict
+
+
+class AssetGroupBase(BaseModel):
+ name: str
+ icon: str = "wallet"
+ color: str = "#0EA5E9"
+ position: int = 0
+
+
+class AssetGroupCreate(AssetGroupBase):
+ pass
+
+
+class AssetGroupUpdate(BaseModel):
+ name: Optional[str] = None
+ icon: Optional[str] = None
+ color: Optional[str] = None
+ position: Optional[int] = None
+
+
+class AssetGroupRead(AssetGroupBase):
+ id: uuid.UUID
+ user_id: uuid.UUID
+ source: str = "manual"
+ connection_id: Optional[uuid.UUID] = None
+ # The originating institution — preserved as context even if the user
+ # renames the wallet to something like "Renda Fixa Longo Prazo".
+ # Null for manual wallets, a bank/broker name for synced ones.
+ institution_name: Optional[str] = None
+ # Convenience rollup — filled by the service. Expressed in the group's
+ # asset currencies without conversion; the frontend already handles
+ # multi-currency totals.
+ asset_count: int = 0
+ current_value: float = 0.0
+ current_value_primary: float = 0.0
+
+ model_config = ConfigDict(from_attributes=True)
diff --git a/backend/app/schemas/category.py b/backend/app/schemas/category.py
index ff204e78..d2c340b3 100644
--- a/backend/app/schemas/category.py
+++ b/backend/app/schemas/category.py
@@ -12,6 +12,7 @@ class CategoryBase(BaseModel):
class CategoryCreate(CategoryBase):
group_id: Optional[uuid.UUID] = None
+ treat_as_transfer: bool = False
class CategoryUpdate(BaseModel):
@@ -19,6 +20,7 @@ class CategoryUpdate(BaseModel):
icon: Optional[str] = None
color: Optional[str] = None
group_id: Optional[uuid.UUID] = None
+ treat_as_transfer: Optional[bool] = None
class CategoryRead(CategoryBase):
@@ -26,5 +28,6 @@ class CategoryRead(CategoryBase):
user_id: uuid.UUID
group_id: Optional[uuid.UUID] = None
is_system: bool
+ treat_as_transfer: bool = False
model_config = ConfigDict(from_attributes=True)
diff --git a/backend/app/services/_query_filters.py b/backend/app/services/_query_filters.py
new file mode 100644
index 00000000..cc8b2c0b
--- /dev/null
+++ b/backend/app/services/_query_filters.py
@@ -0,0 +1,34 @@
+"""Shared SQLAlchemy filter fragments for report/dashboard queries.
+
+Centralizes the "what counts as real income/expense" definition so every
+aggregation site agrees. Changes to the rule (e.g. adding a new exclusion
+signal) only need to be made here.
+"""
+from sqlalchemy import and_, or_, select
+
+from app.models.category import Category
+from app.models.transaction import Transaction
+
+
+def counts_as_pnl():
+ """SQL filter: True when a transaction should contribute to income/expense totals.
+
+ Excludes:
+ - paired transfers (both legs were matched; already cancel out),
+ - transactions in categories flagged `treat_as_transfer` (one-sided
+ movements like investment applications where the counterpart is
+ an Asset/Holding, not another Account).
+
+ Does NOT exclude `source='opening_balance'` — callers that already
+ filter those keep doing so; this helper only handles the transfer-like
+ exclusion family so both rules stay visible at each call site.
+ """
+ return and_(
+ Transaction.transfer_pair_id.is_(None),
+ or_(
+ Transaction.category_id.is_(None),
+ Transaction.category_id.not_in(
+ select(Category.id).where(Category.treat_as_transfer.is_(True))
+ ),
+ ),
+ )
diff --git a/backend/app/services/account_service.py b/backend/app/services/account_service.py
index 0f3ed5e1..01b5c0cc 100644
--- a/backend/app/services/account_service.py
+++ b/backend/app/services/account_service.py
@@ -10,6 +10,7 @@ from app.models.account import Account
from app.models.bank_connection import BankConnection
from app.models.transaction import Transaction
from app.schemas.account import AccountCreate, AccountUpdate
+from app.services._query_filters import counts_as_pnl
from app.services.credit_card_service import apply_effective_date, compute_available_credit, get_cycle_dates
@@ -498,25 +499,26 @@ async def get_account_summary(
if account.type == "credit_card" and account.connection_id:
current_balance = -current_balance
- # Income = SUM of credit transactions in [date_from, date_to] (excluding opening_balance and transfers)
+ # Income = SUM of credit transactions in [date_from, date_to] (excluding
+ # opening_balance, paired transfers, and transfer-like categories).
income_result = await session.execute(
select(func.coalesce(func.sum(effective_amount), 0)).where(
Transaction.account_id == account_id,
Transaction.type == "credit",
Transaction.source != "opening_balance",
- Transaction.transfer_pair_id.is_(None),
+ counts_as_pnl(),
Transaction.date >= date_from,
Transaction.date <= date_to,
)
)
monthly_income = float(income_result.scalar())
- # Expenses = SUM of debit transactions in [date_from, date_to] (as positive value, excluding transfers)
+ # Expenses = SUM of debit transactions in [date_from, date_to] (same exclusions)
expenses_result = await session.execute(
select(func.coalesce(func.sum(func.abs(effective_amount)), 0)).where(
Transaction.account_id == account_id,
Transaction.type == "debit",
- Transaction.transfer_pair_id.is_(None),
+ counts_as_pnl(),
Transaction.date >= date_from,
Transaction.date <= date_to,
)
diff --git a/backend/app/services/asset_group_service.py b/backend/app/services/asset_group_service.py
new file mode 100644
index 00000000..9a4a68da
--- /dev/null
+++ b/backend/app/services/asset_group_service.py
@@ -0,0 +1,291 @@
+import uuid
+from decimal import Decimal
+from typing import Optional
+
+from sqlalchemy import func, select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.core.config import get_settings
+from app.models.asset import Asset
+from app.models.asset_group import AssetGroup
+from app.models.asset_value import AssetValue
+from app.models.bank_connection import BankConnection
+from app.models.user import User
+from app.schemas.asset_group import AssetGroupCreate, AssetGroupRead, AssetGroupUpdate
+from app.services.fx_rate_service import convert
+
+
+async def _latest_value_amount(session: AsyncSession, asset_id: uuid.UUID) -> Optional[Decimal]:
+ """Return the most recent AssetValue.amount for an asset, or None."""
+ row = await session.execute(
+ select(AssetValue.amount)
+ .where(AssetValue.asset_id == asset_id)
+ .order_by(AssetValue.date.desc(), AssetValue.id.desc())
+ .limit(1)
+ )
+ return row.scalar_one_or_none()
+
+
+def _group_to_read(
+ group: AssetGroup,
+ asset_count: int,
+ current_value: Decimal,
+ current_value_primary: Decimal,
+ institution_name: Optional[str] = None,
+) -> AssetGroupRead:
+ return AssetGroupRead(
+ id=group.id,
+ user_id=group.user_id,
+ name=group.name,
+ icon=group.icon,
+ color=group.color,
+ position=group.position,
+ source=group.source,
+ connection_id=group.connection_id,
+ institution_name=institution_name,
+ asset_count=asset_count,
+ # Decimal → round to 2dp → float at the API boundary. Precision is
+ # preserved inside the sum; the float conversion is only for the
+ # JSON response shape and is bounded to 2 decimals.
+ current_value=float(current_value.quantize(Decimal("0.01"))),
+ current_value_primary=float(current_value_primary.quantize(Decimal("0.01"))),
+ )
+
+
+async def _rollup(
+ session: AsyncSession, group: AssetGroup, primary_currency: str
+) -> tuple[int, Decimal, Decimal]:
+ """Compute (asset_count, current_value, current_value_primary) for a group.
+
+ Mirrors the filters used by dashboard net worth so wallet headers
+ agree with the top-level total: excludes archived assets AND sold
+ assets (sell_date is not null). Primary-currency totals use the
+ same `fx_rate_service.convert` the dashboard does — no crude
+ ratio tricks — so BRL/USD/EUR wallets all sum consistently.
+
+ Aggregates in Decimal end-to-end to avoid float drift on portfolios
+ with many small-value holdings (e.g. crypto) or when Pluggy
+ publishes AssetValue amounts at 6-decimal precision.
+ """
+ assets = await session.execute(
+ select(Asset).where(
+ Asset.group_id == group.id,
+ Asset.is_archived == False,
+ Asset.sell_date.is_(None),
+ )
+ )
+ asset_list = list(assets.scalars().all())
+ asset_count = len(asset_list)
+ current_value = Decimal("0")
+ current_value_primary = Decimal("0")
+
+ for asset in asset_list:
+ latest = await _latest_value_amount(session, asset.id)
+ if latest is None:
+ # Fall back to purchase_price if no value history yet — same
+ # logic _compute_current_value uses on the asset read path.
+ latest = asset.purchase_price
+ if latest is None:
+ continue
+
+ current_value += latest
+ if asset.currency == primary_currency:
+ current_value_primary += latest
+ else:
+ converted, _ = await convert(
+ session, latest, asset.currency, primary_currency
+ )
+ current_value_primary += converted
+ return asset_count, current_value, current_value_primary
+
+
+async def _institution_name_for(
+ session: AsyncSession, connection_id: Optional[uuid.UUID]
+) -> Optional[str]:
+ """Fetch the bank/broker institution name for a synced wallet.
+
+ Returns None for manual wallets (no connection) or if the connection
+ was deleted — callers render the subtitle conditionally on this.
+ """
+ if connection_id is None:
+ return None
+ row = await session.execute(
+ select(BankConnection.institution_name).where(BankConnection.id == connection_id)
+ )
+ return row.scalar_one_or_none()
+
+
+async def _primary_currency_for(session: AsyncSession, user_id: uuid.UUID) -> str:
+ user = await session.get(User, user_id)
+ if user:
+ return user.primary_currency
+ return get_settings().default_currency
+
+
+async def get_groups(session: AsyncSession, user_id: uuid.UUID) -> list[AssetGroupRead]:
+ result = await session.execute(
+ select(AssetGroup)
+ .where(AssetGroup.user_id == user_id)
+ .order_by(AssetGroup.position, AssetGroup.name)
+ )
+ groups = list(result.scalars().all())
+ if not groups:
+ return []
+ primary = await _primary_currency_for(session, user_id)
+ reads = []
+ for g in groups:
+ count, cv, cvp = await _rollup(session, g, primary)
+ institution = await _institution_name_for(session, g.connection_id)
+ reads.append(_group_to_read(g, count, cv, cvp, institution))
+ return reads
+
+
+async def get_group(
+ session: AsyncSession, group_id: uuid.UUID, user_id: uuid.UUID
+) -> Optional[AssetGroupRead]:
+ result = await session.execute(
+ select(AssetGroup).where(AssetGroup.id == group_id, AssetGroup.user_id == user_id)
+ )
+ group = result.scalar_one_or_none()
+ if not group:
+ return None
+ primary = await _primary_currency_for(session, user_id)
+ count, cv, cvp = await _rollup(session, group, primary)
+ institution = await _institution_name_for(session, group.connection_id)
+ return _group_to_read(group, count, cv, cvp, institution)
+
+
+async def _next_position(session: AsyncSession, user_id: uuid.UUID) -> int:
+ row = await session.execute(
+ select(func.coalesce(func.max(AssetGroup.position), -1) + 1).where(
+ AssetGroup.user_id == user_id
+ )
+ )
+ return int(row.scalar() or 0)
+
+
+async def create_group(
+ session: AsyncSession, user_id: uuid.UUID, data: AssetGroupCreate
+) -> AssetGroupRead:
+ # Let the caller supply a position, otherwise append to the end so new
+ # groups don't fight with existing drag-ordered ones.
+ position = data.position
+ if position == 0:
+ position = await _next_position(session, user_id)
+ group = AssetGroup(
+ user_id=user_id,
+ name=data.name,
+ icon=data.icon,
+ color=data.color,
+ position=position,
+ source="manual",
+ )
+ session.add(group)
+ await session.commit()
+ await session.refresh(group)
+ return _group_to_read(group, 0, Decimal("0"), Decimal("0"), None)
+
+
+async def update_group(
+ session: AsyncSession, group_id: uuid.UUID, user_id: uuid.UUID, data: AssetGroupUpdate
+) -> Optional[AssetGroupRead]:
+ result = await session.execute(
+ select(AssetGroup).where(AssetGroup.id == group_id, AssetGroup.user_id == user_id)
+ )
+ group = result.scalar_one_or_none()
+ if not group:
+ return None
+ for key, value in data.model_dump(exclude_unset=True).items():
+ setattr(group, key, value)
+ await session.commit()
+ await session.refresh(group)
+ primary = await _primary_currency_for(session, user_id)
+ count, cv, cvp = await _rollup(session, group, primary)
+ institution = await _institution_name_for(session, group.connection_id)
+ return _group_to_read(group, count, cv, cvp, institution)
+
+
+async def delete_group(session: AsyncSession, group_id: uuid.UUID, user_id: uuid.UUID) -> bool:
+ result = await session.execute(
+ select(AssetGroup).where(AssetGroup.id == group_id, AssetGroup.user_id == user_id)
+ )
+ group = result.scalar_one_or_none()
+ if not group:
+ return False
+ await session.delete(group)
+ await session.commit()
+ return True
+
+
+async def ensure_group_for_connection(
+ session: AsyncSession,
+ user_id: uuid.UUID,
+ connection_id: uuid.UUID,
+ source: str,
+ external_id: Optional[str],
+ default_name: str,
+) -> AssetGroup:
+ """Return (creating if absent) the group that owns a connection's assets.
+
+ Called during sync before holdings are upserted so newly-created
+ Assets can attach to the group in the same transaction. Matching
+ prefers (user_id, source, external_id) when external_id is set;
+ otherwise (user_id, source, connection_id). The name is only applied
+ on creation — users are free to rename synced groups later.
+ """
+ # Prefer matching by external_id (Pluggy item id). Falls back to
+ # connection_id which is less stable (connection can be deleted/recreated).
+ query = select(AssetGroup).where(
+ AssetGroup.user_id == user_id,
+ AssetGroup.source == source,
+ )
+ if external_id:
+ query = query.where(AssetGroup.external_id == external_id)
+ else:
+ query = query.where(AssetGroup.connection_id == connection_id)
+
+ result = await session.execute(query)
+ group = result.scalar_one_or_none()
+ if group:
+ # Re-link if the connection was recreated. Name is preserved.
+ if group.connection_id != connection_id:
+ group.connection_id = connection_id
+ return group
+
+ position = await _next_position(session, user_id)
+ # Disambiguate when the user has multiple connections from the same
+ # institution (common with Pluggy sandbox, where every item comes back
+ # as "MeuPluggy"). Appends " 2", " 3", etc. until we find a free name.
+ # User can rename freely afterwards without affecting sync matching,
+ # which keys on external_id, not on name.
+ unique_name = await _unique_default_name(session, user_id, default_name)
+ group = AssetGroup(
+ user_id=user_id,
+ name=unique_name,
+ icon="wallet",
+ color="#0EA5E9",
+ position=position,
+ source=source,
+ connection_id=connection_id,
+ external_id=external_id,
+ )
+ session.add(group)
+ await session.flush()
+ return group
+
+
+async def _unique_default_name(
+ session: AsyncSession, user_id: uuid.UUID, base: str
+) -> str:
+ """Return `base` or the first free `base N` for this user."""
+ existing_rows = await session.execute(
+ select(AssetGroup.name).where(AssetGroup.user_id == user_id)
+ )
+ taken = {row[0] for row in existing_rows.all()}
+ if base not in taken:
+ return base
+ # Start at 2 — "Nubank" and "Nubank 2" read naturally; "Nubank 1" looks wrong.
+ i = 2
+ while f"{base} {i}" in taken:
+ i += 1
+ return f"{base} {i}"
diff --git a/backend/app/services/asset_service.py b/backend/app/services/asset_service.py
index f7632f8f..f6e1bb62 100644
--- a/backend/app/services/asset_service.py
+++ b/backend/app/services/asset_service.py
@@ -112,6 +112,11 @@ def _asset_to_read(asset: Asset, latest_value: Optional[AssetValue], value_count
current_value=current_value,
gain_loss=gain_loss,
value_count=value_count,
+ source=asset.source,
+ connection_id=asset.connection_id,
+ isin=asset.isin,
+ maturity_date=asset.maturity_date,
+ group_id=asset.group_id,
)
@@ -190,6 +195,7 @@ async def create_asset(
growth_start_date=data.growth_start_date,
is_archived=data.is_archived,
position=data.position,
+ group_id=data.group_id,
)
session.add(asset)
await session.flush()
@@ -436,7 +442,12 @@ async def get_portfolio_trend(
for asset in active_assets:
aid = str(asset.id)
- asset_meta.append({"id": aid, "name": asset.name, "type": asset.type})
+ asset_meta.append({
+ "id": aid,
+ "name": asset.name,
+ "type": asset.type,
+ "group_id": str(asset.group_id) if asset.group_id else None,
+ })
asset_currency[aid] = asset.currency
rows = await session.execute(
diff --git a/backend/app/services/budget_service.py b/backend/app/services/budget_service.py
index 491a91df..832e873e 100644
--- a/backend/app/services/budget_service.py
+++ b/backend/app/services/budget_service.py
@@ -12,6 +12,7 @@ from app.models.category_group import CategoryGroup
from app.models.transaction import Transaction
from app.models.user import User
from app.schemas.budget import BudgetCreate, BudgetUpdate, BudgetVsActual
+from app.services._query_filters import counts_as_pnl
from app.services.admin_service import get_credit_card_accounting_mode
from app.services.dashboard_service import _get_recurring_projections
from app.services.fx_rate_service import convert
@@ -262,7 +263,7 @@ async def get_budget_vs_actual(
report_date >= month_start,
report_date < month_end,
Transaction.category_id.isnot(None),
- Transaction.transfer_pair_id.is_(None),
+ counts_as_pnl(),
)
.group_by(Transaction.category_id)
)
@@ -294,7 +295,7 @@ async def get_budget_vs_actual(
report_date >= prev_month_start,
report_date < prev_month_end,
Transaction.category_id.isnot(None),
- Transaction.transfer_pair_id.is_(None),
+ counts_as_pnl(),
)
.group_by(Transaction.category_id)
)
diff --git a/backend/app/services/category_group_service.py b/backend/app/services/category_group_service.py
index b37fba20..2fbec17b 100644
--- a/backend/app/services/category_group_service.py
+++ b/backend/app/services/category_group_service.py
@@ -37,6 +37,7 @@ CATEGORY_TO_GROUP = {
"personal_care": "lifestyle",
"taxes": "other",
"transfers": "other",
+ "investments": "other",
"other": "other",
}
diff --git a/backend/app/services/category_service.py b/backend/app/services/category_service.py
index 372dad4c..61eb0b9f 100644
--- a/backend/app/services/category_service.py
+++ b/backend/app/services/category_service.py
@@ -10,7 +10,10 @@ from app.services.category_group_service import CATEGORY_TO_GROUP, create_defaul
# Language-keyed translations for default categories
-# Keys are internal identifiers used to map to groups and rules
+# Keys are internal identifiers used to map to groups and rules.
+# `treat_as_transfer` marks categories whose transactions are flows, not
+# income/expense — they're excluded from report aggregations like paired
+# transfers are.
DEFAULT_CATEGORIES_I18N = {
"housing": {"en": "Housing", "pt-BR": "Moradia", "icon": "house", "color": "#8B5CF6"},
"food": {"en": "Food & Dining", "pt-BR": "Alimentação", "icon": "utensils-crossed", "color": "#F59E0B"},
@@ -20,7 +23,8 @@ DEFAULT_CATEGORIES_I18N = {
"leisure": {"en": "Leisure", "pt-BR": "Lazer", "icon": "gamepad-2", "color": "#EC4899"},
"subscriptions": {"en": "Subscriptions", "pt-BR": "Assinaturas", "icon": "smartphone", "color": "#6366F1"},
"education": {"en": "Education", "pt-BR": "Educação", "icon": "book-open", "color": "#22C55E"},
- "transfers": {"en": "Transfers", "pt-BR": "Transferências", "icon": "arrow-left-right", "color": "#64748B"},
+ "transfers": {"en": "Transfers", "pt-BR": "Transferências", "icon": "arrow-left-right", "color": "#64748B", "treat_as_transfer": True},
+ "investments": {"en": "Investments", "pt-BR": "Investimentos", "icon": "trending-up", "color": "#0EA5E9", "treat_as_transfer": True},
"salary": {"en": "Salary & Income", "pt-BR": "Salário & Renda", "icon": "banknote", "color": "#16A34A"},
"shopping": {"en": "Shopping", "pt-BR": "Compras", "icon": "shopping-bag", "color": "#F97316"},
"donations": {"en": "Donations", "pt-BR": "Doações", "icon": "heart-handshake", "color": "#D946EF"},
@@ -53,6 +57,7 @@ async def create_default_categories(session: AsyncSession, user_id: uuid.UUID, l
color=data["color"],
is_system=True,
group_id=group.id if group else None,
+ treat_as_transfer=data.get("treat_as_transfer", False),
)
session.add(category)
categories.append(category)
diff --git a/backend/app/services/connection_service.py b/backend/app/services/connection_service.py
index ff08fd48..e953aa32 100644
--- a/backend/app/services/connection_service.py
+++ b/backend/app/services/connection_service.py
@@ -1,25 +1,33 @@
+import logging
import uuid
-from datetime import datetime, timedelta, timezone
+from datetime import date, datetime, timedelta, timezone
from typing import Optional
-from sqlalchemy import select
+from sqlalchemy import or_, select, update
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload
from app.core.config import get_settings
+from app.models.asset import Asset
+from app.models.asset_group import AssetGroup
+from app.models.asset_value import AssetValue
from app.models.bank_connection import BankConnection
from app.models.account import Account
from app.models.category import Category
from app.models.transaction import Transaction
from app.models.user import User
from app.providers import get_provider
+from app.providers.base import HoldingData
from app.services.account_service import sync_opening_balance_for_connected_account
+from app.services.asset_group_service import ensure_group_for_connection
from app.services.credit_card_service import apply_effective_date
from app.services.rule_service import apply_rules_to_transaction
from app.services.transfer_detection_service import detect_transfer_pairs
from app.services.fx_rate_service import stamp_primary_amount
from app.services.payee_service import get_or_create_payee
+logger = logging.getLogger(__name__)
+
settings = get_settings()
PLUGGY_CATEGORY_MAP = {
@@ -48,6 +56,248 @@ PLUGGY_CATEGORY_MAP = {
}
+async def _sync_holdings(
+ session: AsyncSession,
+ user_id: uuid.UUID,
+ connection: BankConnection,
+ credentials: dict,
+) -> None:
+ """Fetch investment holdings from the provider and upsert them as Assets.
+
+ Each holding becomes one Asset (type="investment") keyed by
+ (user_id, source, external_id). Every sync appends an AssetValue row
+ dated today; if a row for today already exists (same day re-sync) it
+ is updated in place rather than creating a duplicate.
+
+ Holdings that disappear from the provider response (e.g. fully
+ redeemed fixed income) get archived rather than deleted so the user
+ keeps their value history.
+
+ Failures here are swallowed: not all Pluggy connectors expose
+ investment data, and we don't want a brokerage hiccup to break the
+ bank-account sync that just succeeded.
+ """
+ # Tolerate provider-side failures (e.g. Pluggy returning 500 for a
+ # specific connector, a bank that doesn't expose /investments).
+ # Storage errors below are intentionally not caught — they indicate
+ # a schema/invariant bug we want to surface, not a hiccup to swallow.
+ try:
+ provider = get_provider(connection.provider)
+ holdings = await provider.get_holdings(credentials)
+ except Exception: # noqa: BLE001
+ logger.exception(
+ "Failed to fetch holdings for connection %s", connection.id
+ )
+ return
+
+ source = connection.provider
+ today = date.today()
+
+ # Find-or-create the wallet that will own this connection's holdings.
+ # Name defaults to the institution; users can rename freely without
+ # breaking future syncs (matching is by external_id).
+ group: Optional[AssetGroup] = None
+ if holdings:
+ group = await ensure_group_for_connection(
+ session,
+ user_id=user_id,
+ connection_id=connection.id,
+ source=source,
+ external_id=connection.external_id,
+ default_name=connection.institution_name,
+ )
+
+ # Also pull orphans (connection_id IS NULL) with the same source —
+ # those are assets archived by a prior disconnect. Re-matching on
+ # external_id lets users re-link their investment history when they
+ # re-add a connection without creating duplicate rows.
+ existing_rows = await session.execute(
+ select(Asset).where(
+ Asset.user_id == user_id,
+ Asset.source == source,
+ or_(Asset.connection_id == connection.id, Asset.connection_id.is_(None)),
+ )
+ )
+ existing_by_external: dict[str, Asset] = {
+ a.external_id: a for a in existing_rows.scalars().all() if a.external_id
+ }
+ seen: set[str] = set()
+
+ for holding in holdings:
+ seen.add(holding.external_id)
+ existing = existing_by_external.get(holding.external_id)
+
+ # Provider-reported closure (Pluggy TOTAL_WITHDRAWAL). Two cases:
+ # - New + withdrawn: skip entirely. A dead zero-balance asset
+ # with no history is noise; the user never saw this position
+ # while it was active, no reason to surface it closed.
+ # - Existing + withdrawn: mark sell_date (if not already set by
+ # the user) so it drops out of current totals but historical
+ # AssetValues remain visible in reports. No new AssetValue —
+ # appending today's zero would bury the real closing value.
+ if holding.is_withdrawn:
+ if existing is None:
+ continue
+ if existing.sell_date is None:
+ existing.sell_date = today
+ # Keep descriptive fields fresh in case the provider still
+ # updates them post-closure, but don't touch valuation.
+ existing.name = holding.name
+ existing.external_metadata = holding.metadata
+ existing.connection_id = connection.id
+ continue
+
+ asset = await _upsert_asset_from_holding(
+ session, existing, holding, user_id, connection.id, source,
+ )
+ # Attach to the connection's wallet. We only set group_id when
+ # it's currently null so a user who moved this holding to a
+ # custom wallet ("US Stocks") doesn't get overridden back on
+ # every sync.
+ if group is not None and asset.group_id is None:
+ asset.group_id = group.id
+ # Seed a historical value at purchase_date so users get a real
+ # evolution curve from day one — not just today's snapshot.
+ # Idempotent: skips if any AssetValue already exists at that date.
+ if holding.purchase_date and holding.purchase_price is not None:
+ await _ensure_historical_seed(
+ session, asset, holding.purchase_date, holding.purchase_price
+ )
+ # Respect a user-set sell_date: if they've marked the asset as
+ # sold we stop recording new values even when the provider still
+ # reports the position. Historical values stay; current totals
+ # already exclude it via the sell_date filter in rollups.
+ if asset.sell_date is None:
+ await _upsert_asset_value_for_today(session, asset, holding.current_value, today)
+
+ for ext_id, asset in existing_by_external.items():
+ if ext_id not in seen and not asset.is_archived:
+ asset.is_archived = True
+
+
+async def _upsert_asset_from_holding(
+ session: AsyncSession,
+ asset: Optional[Asset],
+ holding: HoldingData,
+ user_id: uuid.UUID,
+ connection_id: uuid.UUID,
+ source: str,
+) -> Asset:
+ """Create or update an Asset from a HoldingData payload.
+
+ Synced fields (name, currency, quantity, purchase_price, maturity,
+ metadata) are always overwritten — the UI disables editing these on
+ synced assets. Provider-reported withdrawal is handled by the caller
+ via `sell_date`, not here, so this function only ever sees ACTIVE
+ holdings and never flips `is_archived` on its own.
+ """
+ if asset is None:
+ asset = Asset(
+ user_id=user_id,
+ connection_id=connection_id,
+ source=source,
+ external_id=holding.external_id,
+ name=holding.name,
+ type="investment",
+ currency=holding.currency,
+ units=holding.quantity,
+ purchase_price=holding.purchase_price,
+ purchase_date=holding.purchase_date,
+ isin=holding.isin,
+ maturity_date=holding.maturity_date,
+ external_metadata=holding.metadata,
+ valuation_method="manual",
+ )
+ session.add(asset)
+ await session.flush()
+ return asset
+
+ # Fields Pluggy consistently returns — safe to overwrite each sync.
+ asset.name = holding.name
+ asset.currency = holding.currency
+ # external_metadata is a snapshot blob: we want the latest every time.
+ asset.external_metadata = holding.metadata
+ asset.connection_id = connection_id
+
+ # Sparse fields — merge, don't clobber. Pluggy sometimes returns
+ # these on first sync and null on later ones (e.g. amountOriginal
+ # present at creation, missing on daily rebalances). Keeping the
+ # first-seen value is better than wiping data we already have.
+ if holding.quantity is not None:
+ asset.units = holding.quantity
+ if holding.purchase_price is not None:
+ asset.purchase_price = holding.purchase_price
+ if holding.purchase_date:
+ asset.purchase_date = holding.purchase_date
+ if holding.isin:
+ asset.isin = holding.isin
+ if holding.maturity_date:
+ asset.maturity_date = holding.maturity_date
+ return asset
+
+
+async def _ensure_historical_seed(
+ session: AsyncSession,
+ asset: Asset,
+ purchase_date: date,
+ purchase_price,
+) -> None:
+ """Insert a one-time AssetValue at purchase_date with purchase_price.
+
+ Called on every sync but a no-op once the seed exists. Skips if ANY
+ AssetValue already exists on that date (even a manual one) — we don't
+ want to stomp a value the user may have entered themselves.
+ """
+ existing = await session.execute(
+ select(AssetValue).where(
+ AssetValue.asset_id == asset.id,
+ AssetValue.date == purchase_date,
+ )
+ )
+ if existing.scalar_one_or_none() is not None:
+ return
+ session.add(
+ AssetValue(
+ asset_id=asset.id,
+ amount=purchase_price,
+ date=purchase_date,
+ source="sync",
+ )
+ )
+
+
+async def _upsert_asset_value_for_today(
+ session: AsyncSession,
+ asset: Asset,
+ amount,
+ today: date,
+) -> None:
+ """One sync-sourced AssetValue per asset per day.
+
+ Re-syncing the same day updates the amount in place; a later day
+ creates a new row so we build a daily valuation history over time.
+ """
+ existing = await session.execute(
+ select(AssetValue).where(
+ AssetValue.asset_id == asset.id,
+ AssetValue.date == today,
+ AssetValue.source == "sync",
+ )
+ )
+ row = existing.scalar_one_or_none()
+ if row is not None:
+ row.amount = amount
+ else:
+ session.add(
+ AssetValue(
+ asset_id=asset.id,
+ amount=amount,
+ date=today,
+ source="sync",
+ )
+ )
+
+
async def _match_pluggy_category(
session: AsyncSession, user_id: uuid.UUID, pluggy_category: Optional[str]
) -> Optional[uuid.UUID]:
@@ -225,6 +475,11 @@ async def handle_oauth_callback(
# Detect transfer pairs among newly synced transactions
await detect_transfer_pairs(session, user_id, candidate_ids=new_tx_ids)
+ # Investment holdings live on /investments — separate endpoint from
+ # /accounts. Pulled after account setup so holdings are available on
+ # the Assets page immediately after the widget closes.
+ await _sync_holdings(session, user_id, connection, connection_data.credentials)
+
connection.last_sync_at = datetime.now(timezone.utc)
await session.commit()
await session.refresh(connection)
@@ -521,6 +776,12 @@ async def sync_connection(
# the real one, the orphan twin gets removed here.
await _cleanup_phantom_duplicates(session, connection.id)
+ # Refresh investment holdings (brokerage, fixed income, funds,
+ # etc.). Errors here are logged but don't fail the sync; a bank
+ # connector that doesn't expose /investments shouldn't block the
+ # transaction sync that just succeeded.
+ await _sync_holdings(session, user_id, connection, credentials)
+
connection.last_sync_at = datetime.now(timezone.utc)
connection.status = "active"
await session.commit()
@@ -544,6 +805,17 @@ async def delete_connection(
if not connection:
return False
+ # Archive synced investment assets rather than deleting them: the user
+ # may still want to see their historical AssetValue trend, and if they
+ # re-connect the same provider later we can un-archive by matching
+ # (user_id, source, external_id). The FK's ON DELETE SET NULL will
+ # then clear connection_id when the row is removed below.
+ await session.execute(
+ update(Asset)
+ .where(Asset.connection_id == connection.id)
+ .values(is_archived=True)
+ )
+
await session.delete(connection)
await session.commit()
return True
diff --git a/backend/app/services/dashboard_service.py b/backend/app/services/dashboard_service.py
index ee99ecde..3ab89673 100644
--- a/backend/app/services/dashboard_service.py
+++ b/backend/app/services/dashboard_service.py
@@ -13,6 +13,7 @@ from app.models.transaction import Transaction
from app.models.category import Category
from app.models.recurring_transaction import RecurringTransaction
from app.schemas.dashboard import DashboardSummary, SpendingByCategory, MonthlyTrend, ProjectedTransaction, DailyBalance, BalanceHistory
+from app.services._query_filters import counts_as_pnl
from app.services.admin_service import get_credit_card_accounting_mode
from app.services.recurring_transaction_service import get_occurrences_in_range
from app.services.asset_service import get_total_asset_value
@@ -111,7 +112,8 @@ async def get_summary(
total_balance[proj["currency"]] = total_balance.get(proj["currency"], 0.0) + signed
# Monthly income and expenses — exclude opening_balance so initial deposits
- # don't inflate the month's income figure. Also exclude transfer pairs.
+ # don't inflate the month's income figure. counts_as_pnl() also skips
+ # paired transfers and transfer-like categories (e.g. Investimentos).
monthly_result = await session.execute(
select(
func.sum(case((Transaction.type == "credit", Transaction.amount), else_=0)),
@@ -124,7 +126,7 @@ async def get_summary(
report_date >= month_start,
report_date < month_end,
Transaction.source != "opening_balance",
- Transaction.transfer_pair_id.is_(None),
+ counts_as_pnl(),
)
)
monthly_row = monthly_result.one()
@@ -204,7 +206,7 @@ async def get_summary(
report_date >= month_start,
report_date < month_end,
Transaction.source != "opening_balance",
- Transaction.transfer_pair_id.is_(None),
+ counts_as_pnl(),
Transaction.amount_primary.isnot(None),
)
)
@@ -261,8 +263,8 @@ async def get_spending_by_category(
Transaction.effective_date if accounting_mode == "accrual" else Transaction.date
)
- # Real transactions grouped by category (exclude transfer pairs and closed accounts)
- # Use amount_primary for multi-currency support
+ # Real transactions grouped by category (exclude transfer-like movements
+ # and closed accounts). Use amount_primary for multi-currency support.
result = await session.execute(
select(
Category.id,
@@ -280,7 +282,7 @@ async def get_spending_by_category(
Transaction.type == "debit",
report_date >= month_start,
report_date < month_end,
- Transaction.transfer_pair_id.is_(None),
+ counts_as_pnl(),
)
.group_by(Category.id, Category.name, Category.icon, Category.color)
.order_by(func.sum(_primary_amount_expr()).desc())
@@ -371,7 +373,7 @@ async def get_monthly_trend(
Transaction.user_id == user_id,
Account.is_closed == False,
Transaction.source != "opening_balance",
- Transaction.transfer_pair_id.is_(None),
+ counts_as_pnl(),
)
.group_by(month_label)
.order_by(month_label.desc())
diff --git a/backend/app/services/report_service.py b/backend/app/services/report_service.py
index 3ecc74c8..f44d8060 100644
--- a/backend/app/services/report_service.py
+++ b/backend/app/services/report_service.py
@@ -12,6 +12,7 @@ from app.models.asset_value import AssetValue
from app.models.transaction import Transaction
from app.models.category import Category
from app.models.user import User
+from app.services._query_filters import counts_as_pnl
from app.services.admin_service import get_credit_card_accounting_mode
from app.services.account_service import get_account_name
from app.services.fx_rate_service import convert
@@ -381,7 +382,7 @@ async def get_income_expenses_report(
report_date >= start,
report_date <= today,
Transaction.source != "opening_balance",
- Transaction.transfer_pair_id.is_(None),
+ counts_as_pnl(),
)
.group_by(label_expr)
.order_by(label_expr)
@@ -504,7 +505,7 @@ async def get_income_expenses_report(
report_date >= start,
report_date <= today,
Transaction.source != "opening_balance",
- Transaction.transfer_pair_id.is_(None),
+ counts_as_pnl(),
)
.group_by(Category.id, Category.name, Category.color, Transaction.type)
)
@@ -544,7 +545,7 @@ async def get_income_expenses_report(
report_date >= start,
report_date <= today,
Transaction.source != "opening_balance",
- Transaction.transfer_pair_id.is_(None),
+ counts_as_pnl(),
)
.group_by(label_expr, Category.id, Category.name, Category.color, Transaction.type)
)
diff --git a/backend/app/services/rule_service.py b/backend/app/services/rule_service.py
index 50870adf..e41c4e0c 100644
--- a/backend/app/services/rule_service.py
+++ b/backend/app/services/rule_service.py
@@ -44,6 +44,17 @@ UNIVERSAL_RULES = [
{"name": "Salary / Payroll", "conditions_op": "and", "conditions": [
{"field": "description", "op": "regex", "value": "SALARY|PAYROLL|DIRECT DEPOSIT"},
], "actions": [{"op": "set_category", "value": "salary"}], "priority": 10},
+
+ # Investment movements (aplicação/resgate, CDBs, Tesouro, funds). The target
+ # category is flagged `treat_as_transfer=true` so reports exclude these
+ # from income/expense — the "other side" of the movement is the Asset
+ # (holding) that grew or shrank, not a real gain or cost.
+ # Patterns are PT-first since Pluggy (our primary connector) is Brazilian;
+ # they're harmless no-ops against English descriptions.
+ {"name": "Investimentos (Aplicação / Resgate)", "conditions_op": "or", "conditions": [
+ {"field": "description", "op": "regex",
+ "value": r"APLICACAO|APLICAÇÃO|RESGATE|DEB FUNDO|CREDITO FUNDO|CRÉDITO FUNDO|COMPRA CDB|VENDA CDB|TESOURO DIRETO|RENDA FIXA|\bCDB\b|\bLCA\b|\bLCI\b|DEBENTURE|FUNDO DE INVESTIMENTO"},
+ ], "actions": [{"op": "set_category", "value": "investments"}], "priority": 20},
]
# ─── Country-specific rule packs (optional, not auto-applied) ───
diff --git a/backend/tests/test_categories_api.py b/backend/tests/test_categories_api.py
index d419b00e..262c7402 100644
--- a/backend/tests/test_categories_api.py
+++ b/backend/tests/test_categories_api.py
@@ -25,11 +25,12 @@ async def test_list_categories_with_defaults(
response = await client.get("/api/categories", headers=auth_headers)
assert response.status_code == 200
data = response.json()
- assert len(data) == 15
+ assert len(data) == 16
names = {c["name"] for c in data}
assert "Alimentação" in names
assert "Transporte" in names
assert "Outros" in names
+ assert "Investimentos" in names
@pytest.mark.asyncio
diff --git a/backend/tests/test_sync_holdings.py b/backend/tests/test_sync_holdings.py
new file mode 100644
index 00000000..d6895431
--- /dev/null
+++ b/backend/tests/test_sync_holdings.py
@@ -0,0 +1,534 @@
+"""Cover the Asset lifecycle through `_sync_holdings`.
+
+The sync contract is a bit subtle: provider data drives creation *and*
+closure of Assets, but user-set fields (sell_date, group_id) are load-
+bearing and must never be overwritten. These tests pin the full matrix:
+new/existing × active/withdrawn, same-day vs next-day re-syncs,
+historical seeding idempotency, and sparse-field merging.
+"""
+from __future__ import annotations
+
+import uuid
+from datetime import date, datetime, timedelta, timezone
+from decimal import Decimal
+from typing import Optional
+
+import pytest
+import pytest_asyncio
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.models.asset import Asset
+from app.models.asset_group import AssetGroup
+from app.models.asset_value import AssetValue
+from app.models.bank_connection import BankConnection
+from app.models.user import User
+from app.providers import register_provider
+from app.providers.base import (
+ AccountData,
+ BankProvider,
+ ConnectionData,
+ HoldingData,
+ TransactionData,
+)
+from app.services.connection_service import _sync_holdings
+
+
+# ---------------------------------------------------------------------------
+# Mock provider — deterministic replacement for Pluggy/Belvo in tests.
+# ---------------------------------------------------------------------------
+
+
+class _MockProvider(BankProvider):
+ """BankProvider that returns a caller-supplied list of holdings.
+
+ We store the list on a class-level mutable slot so each test can
+ reconfigure the response without juggling singleton re-registration.
+ """
+
+ _holdings: list[HoldingData] = []
+ _raise: Optional[Exception] = None
+
+ @property
+ def name(self) -> str:
+ return "mock"
+
+ def get_oauth_url(self, redirect_uri: str, state: str) -> str: # pragma: no cover
+ return "http://mock"
+
+ async def handle_oauth_callback(self, code: str) -> ConnectionData: # pragma: no cover
+ raise NotImplementedError
+
+ async def get_accounts(self, credentials: dict) -> list[AccountData]: # pragma: no cover
+ return []
+
+ async def get_transactions(self, credentials: dict, account_external_id: str, since=None, payee_source: str = "auto") -> list[TransactionData]: # pragma: no cover
+ return []
+
+ async def refresh_credentials(self, credentials: dict) -> dict: # pragma: no cover
+ return credentials
+
+ async def get_holdings(self, credentials: dict) -> list[HoldingData]:
+ if _MockProvider._raise is not None:
+ raise _MockProvider._raise
+ return list(_MockProvider._holdings)
+
+
[email protected](autouse=True)
+def _register_mock_provider():
+ """Auto-register mock provider for every test in this module."""
+ register_provider("mock", _MockProvider)
+ _MockProvider._holdings = []
+ _MockProvider._raise = None
+ yield
+
+
+# ---------------------------------------------------------------------------
+# Fixtures specific to holdings sync.
+# ---------------------------------------------------------------------------
+
+
+@pytest_asyncio.fixture
+async def mock_connection(session: AsyncSession, test_user: User) -> BankConnection:
+ conn = BankConnection(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ provider="mock",
+ external_id="item-abc",
+ institution_name="Mock Bank",
+ credentials={"item_id": "item-abc"},
+ status="active",
+ created_at=datetime.now(timezone.utc),
+ )
+ session.add(conn)
+ await session.commit()
+ await session.refresh(conn)
+ return conn
+
+
+def _holding(
+ *,
+ external_id: str = "h-1",
+ name: str = "CDB NU",
+ current_value: Decimal = Decimal("1000.00"),
+ purchase_price: Optional[Decimal] = Decimal("900.00"),
+ purchase_date: Optional[date] = None,
+ quantity: Optional[Decimal] = Decimal("1"),
+ is_withdrawn: bool = False,
+ metadata: Optional[dict] = None,
+) -> HoldingData:
+ return HoldingData(
+ external_id=external_id,
+ name=name,
+ currency="BRL",
+ current_value=current_value,
+ quantity=quantity,
+ purchase_price=purchase_price,
+ purchase_date=purchase_date,
+ is_withdrawn=is_withdrawn,
+ metadata=metadata or {"status": "ACTIVE"},
+ )
+
+
+async def _assets_for(session: AsyncSession, user: User) -> list[Asset]:
+ rows = await session.execute(select(Asset).where(Asset.user_id == user.id))
+ return list(rows.scalars().all())
+
+
+async def _values_for(session: AsyncSession, asset_id) -> list[AssetValue]:
+ rows = await session.execute(
+ select(AssetValue).where(AssetValue.asset_id == asset_id).order_by(AssetValue.date)
+ )
+ return list(rows.scalars().all())
+
+
+# ---------------------------------------------------------------------------
+# Tests
+# ---------------------------------------------------------------------------
+
+
+async def test_new_active_holding_creates_asset_wallet_and_today_value(
+ session: AsyncSession, test_user: User, mock_connection: BankConnection
+):
+ """Happy path: one fresh ACTIVE holding → Asset + wallet + today's value."""
+ today = date.today()
+ _MockProvider._holdings = [
+ _holding(current_value=Decimal("1234.56"), purchase_date=today - timedelta(days=10)),
+ ]
+
+ await _sync_holdings(session, test_user.id, mock_connection, mock_connection.credentials)
+ await session.commit()
+
+ assets = await _assets_for(session, test_user)
+ assert len(assets) == 1
+ asset = assets[0]
+ assert asset.external_id == "h-1"
+ assert asset.source == "mock"
+ assert asset.connection_id == mock_connection.id
+ assert asset.sell_date is None
+ assert asset.is_archived is False
+
+ # Wallet auto-created and the asset attached.
+ assert asset.group_id is not None
+ wallet = await session.get(AssetGroup, asset.group_id)
+ assert wallet is not None
+ assert wallet.connection_id == mock_connection.id
+
+ values = await _values_for(session, asset.id)
+ # Historical seed at purchase_date + today's snapshot.
+ dates = [v.date for v in values]
+ assert today - timedelta(days=10) in dates
+ assert today in dates
+
+
+async def test_new_withdrawn_holding_is_skipped_entirely(
+ session: AsyncSession, test_user: User, mock_connection: BankConnection
+):
+ """A holding that's already TOTAL_WITHDRAWAL on first sight should not
+ create a zero-balance Asset — there's no meaningful history to show."""
+ _MockProvider._holdings = [
+ _holding(external_id="dead-1", current_value=Decimal("0"), is_withdrawn=True),
+ ]
+
+ await _sync_holdings(session, test_user.id, mock_connection, mock_connection.credentials)
+ await session.commit()
+
+ assert await _assets_for(session, test_user) == []
+
+
+async def test_withdrawn_existing_asset_gets_sell_date(
+ session: AsyncSession, test_user: User, mock_connection: BankConnection
+):
+ """Position was ACTIVE on a prior sync, now TOTAL_WITHDRAWAL. We set
+ sell_date to today, leave historical AssetValues intact, and do not
+ append a fresh zero value."""
+ today = date.today()
+
+ # First sync: active.
+ _MockProvider._holdings = [_holding(external_id="h-1", current_value=Decimal("500"))]
+ await _sync_holdings(session, test_user.id, mock_connection, mock_connection.credentials)
+ await session.commit()
+ [asset] = await _assets_for(session, test_user)
+ values_before = await _values_for(session, asset.id)
+ assert asset.sell_date is None
+ assert len(values_before) >= 1
+
+ # Second sync: withdrawn.
+ _MockProvider._holdings = [
+ _holding(external_id="h-1", current_value=Decimal("0"), is_withdrawn=True)
+ ]
+ await _sync_holdings(session, test_user.id, mock_connection, mock_connection.credentials)
+ await session.commit()
+ await session.refresh(asset)
+
+ assert asset.sell_date == today
+ values_after = await _values_for(session, asset.id)
+ # Historical values preserved; no zero appended.
+ assert len(values_after) == len(values_before)
+ assert all(v.amount != Decimal("0") for v in values_after)
+
+
+async def test_withdrawn_existing_does_not_overwrite_user_sell_date(
+ session: AsyncSession, test_user: User, mock_connection: BankConnection
+):
+ """If the user manually marked sell_date (e.g. they know the exact
+ redemption date), a later provider-reported withdrawal must not clobber it."""
+ user_sell_date = date.today() - timedelta(days=30)
+
+ asset = Asset(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ connection_id=mock_connection.id,
+ source="mock",
+ external_id="h-1",
+ name="CDB NU",
+ type="investment",
+ currency="BRL",
+ sell_date=user_sell_date,
+ )
+ session.add(asset)
+ await session.commit()
+
+ _MockProvider._holdings = [
+ _holding(external_id="h-1", current_value=Decimal("0"), is_withdrawn=True)
+ ]
+ await _sync_holdings(session, test_user.id, mock_connection, mock_connection.credentials)
+ await session.commit()
+ await session.refresh(asset)
+
+ assert asset.sell_date == user_sell_date
+
+
+async def test_user_sold_active_on_provider_stops_value_updates(
+ session: AsyncSession, test_user: User, mock_connection: BankConnection
+):
+ """User marked the asset sold but the provider still reports it active.
+ Respect the user: no new AssetValues should be appended, so dashboards
+ don't keep moving for a position the user considers closed."""
+ user_sell_date = date.today() - timedelta(days=5)
+
+ asset = Asset(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ connection_id=mock_connection.id,
+ source="mock",
+ external_id="h-1",
+ name="CDB NU",
+ type="investment",
+ currency="BRL",
+ sell_date=user_sell_date,
+ )
+ session.add(asset)
+ await session.commit()
+
+ _MockProvider._holdings = [
+ _holding(external_id="h-1", current_value=Decimal("999.99"))
+ ]
+ await _sync_holdings(session, test_user.id, mock_connection, mock_connection.credentials)
+ await session.commit()
+ await session.refresh(asset)
+
+ assert asset.sell_date == user_sell_date # untouched
+ values = await _values_for(session, asset.id)
+ assert values == [] # no new values recorded
+
+
+async def test_same_day_resync_updates_asset_value_in_place(
+ session: AsyncSession, test_user: User, mock_connection: BankConnection
+):
+ """Running sync twice in one day must not duplicate the day's AssetValue —
+ the second pass updates the amount in the existing row."""
+ _MockProvider._holdings = [_holding(external_id="h-1", current_value=Decimal("100"))]
+ await _sync_holdings(session, test_user.id, mock_connection, mock_connection.credentials)
+ await session.commit()
+ [asset] = await _assets_for(session, test_user)
+
+ _MockProvider._holdings = [_holding(external_id="h-1", current_value=Decimal("110"))]
+ await _sync_holdings(session, test_user.id, mock_connection, mock_connection.credentials)
+ await session.commit()
+
+ values = await _values_for(session, asset.id)
+ today = date.today()
+ today_rows = [v for v in values if v.date == today]
+ assert len(today_rows) == 1
+ assert today_rows[0].amount == Decimal("110")
+
+
+async def test_sparse_fields_are_preserved_on_later_sync(
+ session: AsyncSession, test_user: User, mock_connection: BankConnection
+):
+ """Pluggy returns purchase_price/purchase_date/units on some syncs and
+ null on others. Earlier non-null values must not be clobbered by later
+ nulls — otherwise the user loses provenance data permanently."""
+ _MockProvider._holdings = [
+ _holding(
+ external_id="h-1",
+ current_value=Decimal("500"),
+ purchase_price=Decimal("450"),
+ quantity=Decimal("10"),
+ purchase_date=date.today() - timedelta(days=100),
+ )
+ ]
+ await _sync_holdings(session, test_user.id, mock_connection, mock_connection.credentials)
+ await session.commit()
+ [asset] = await _assets_for(session, test_user)
+ assert asset.purchase_price == Decimal("450")
+ assert asset.units == Decimal("10")
+
+ _MockProvider._holdings = [
+ _holding(
+ external_id="h-1",
+ current_value=Decimal("520"),
+ purchase_price=None,
+ quantity=None,
+ purchase_date=None,
+ )
+ ]
+ await _sync_holdings(session, test_user.id, mock_connection, mock_connection.credentials)
+ await session.commit()
+ await session.refresh(asset)
+
+ assert asset.purchase_price == Decimal("450")
+ assert asset.units == Decimal("10")
+
+
+async def test_historical_seed_is_idempotent(
+ session: AsyncSession, test_user: User, mock_connection: BankConnection
+):
+ """Historical seed at purchase_date should be inserted exactly once —
+ running sync 3× still leaves a single row at that date."""
+ purchase = date.today() - timedelta(days=60)
+ _MockProvider._holdings = [
+ _holding(
+ external_id="h-1",
+ current_value=Decimal("1000"),
+ purchase_price=Decimal("900"),
+ purchase_date=purchase,
+ )
+ ]
+ for _ in range(3):
+ await _sync_holdings(session, test_user.id, mock_connection, mock_connection.credentials)
+ await session.commit()
+
+ [asset] = await _assets_for(session, test_user)
+ purchase_rows = [v for v in await _values_for(session, asset.id) if v.date == purchase]
+ assert len(purchase_rows) == 1
+ assert purchase_rows[0].amount == Decimal("900")
+
+
+async def test_historical_seed_respects_prior_manual_value(
+ session: AsyncSession, test_user: User, mock_connection: BankConnection
+):
+ """If a manual AssetValue already exists at purchase_date, the seed must
+ not overwrite it. Users' numbers always win over provider defaults."""
+ purchase = date.today() - timedelta(days=60)
+ asset = Asset(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ connection_id=mock_connection.id,
+ source="mock",
+ external_id="h-1",
+ name="CDB NU",
+ type="investment",
+ currency="BRL",
+ )
+ session.add(asset)
+ session.add(
+ AssetValue(
+ asset_id=asset.id,
+ amount=Decimal("777"),
+ date=purchase,
+ source="manual",
+ )
+ )
+ await session.commit()
+
+ _MockProvider._holdings = [
+ _holding(
+ external_id="h-1",
+ current_value=Decimal("1000"),
+ purchase_price=Decimal("900"),
+ purchase_date=purchase,
+ )
+ ]
+ await _sync_holdings(session, test_user.id, mock_connection, mock_connection.credentials)
+ await session.commit()
+
+ rows = [v for v in await _values_for(session, asset.id) if v.date == purchase]
+ assert len(rows) == 1
+ assert rows[0].amount == Decimal("777")
+ assert rows[0].source == "manual"
+
+
+async def test_disappeared_holding_gets_archived(
+ session: AsyncSession, test_user: User, mock_connection: BankConnection
+):
+ """If a previously-synced holding is no longer in the provider response
+ at all (e.g. broker removed it), archive the Asset so it stops cluttering
+ the UI — but don't delete it, history matters."""
+ _MockProvider._holdings = [
+ _holding(external_id="h-1", current_value=Decimal("500")),
+ _holding(external_id="h-2", current_value=Decimal("200")),
+ ]
+ await _sync_holdings(session, test_user.id, mock_connection, mock_connection.credentials)
+ await session.commit()
+
+ # Only h-1 comes back on the next sync. h-2 must be archived.
+ _MockProvider._holdings = [_holding(external_id="h-1", current_value=Decimal("510"))]
+ await _sync_holdings(session, test_user.id, mock_connection, mock_connection.credentials)
+ await session.commit()
+
+ assets = {a.external_id: a for a in await _assets_for(session, test_user)}
+ assert assets["h-1"].is_archived is False
+ assert assets["h-2"].is_archived is True
+
+
+async def test_user_moved_asset_to_custom_wallet_not_overridden(
+ session: AsyncSession, test_user: User, mock_connection: BankConnection
+):
+ """If the user moves a synced asset to a custom wallet, later syncs must
+ not drag it back to the provider's default wallet."""
+ _MockProvider._holdings = [_holding(external_id="h-1", current_value=Decimal("500"))]
+ await _sync_holdings(session, test_user.id, mock_connection, mock_connection.credentials)
+ await session.commit()
+ [asset] = await _assets_for(session, test_user)
+ default_wallet_id = asset.group_id
+
+ # Simulate user moving to a custom wallet.
+ custom_wallet = AssetGroup(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ name="US Stocks",
+ icon="briefcase",
+ color="#000",
+ position=5,
+ source="manual",
+ )
+ session.add(custom_wallet)
+ await session.commit()
+ asset.group_id = custom_wallet.id
+ await session.commit()
+
+ _MockProvider._holdings = [_holding(external_id="h-1", current_value=Decimal("520"))]
+ await _sync_holdings(session, test_user.id, mock_connection, mock_connection.credentials)
+ await session.commit()
+ await session.refresh(asset)
+
+ assert asset.group_id == custom_wallet.id
+ assert asset.group_id != default_wallet_id
+
+
+async def test_provider_error_is_swallowed_without_side_effects(
+ session: AsyncSession, test_user: User, mock_connection: BankConnection
+):
+ """/investments errors must not crash the account/transaction sync that
+ just succeeded — silent failure here is intentional."""
+ _MockProvider._raise = RuntimeError("provider 500")
+ await _sync_holdings(session, test_user.id, mock_connection, mock_connection.credentials)
+ # No assets, no exception.
+ assert await _assets_for(session, test_user) == []
+
+
+async def test_next_day_sync_appends_new_asset_value(
+ session: AsyncSession, test_user: User, mock_connection: BankConnection
+):
+ """Value history accumulates: a pre-existing yesterday row must remain
+ alongside today's new row."""
+ yesterday = date.today() - timedelta(days=1)
+ asset = Asset(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ connection_id=mock_connection.id,
+ source="mock",
+ external_id="h-1",
+ name="CDB NU",
+ type="investment",
+ currency="BRL",
+ )
+ session.add(asset)
+ session.add(
+ AssetValue(asset_id=asset.id, amount=Decimal("100"), date=yesterday, source="sync")
+ )
+ await session.commit()
+
+ _MockProvider._holdings = [_holding(external_id="h-1", current_value=Decimal("105"))]
+ await _sync_holdings(session, test_user.id, mock_connection, mock_connection.credentials)
+ await session.commit()
+
+ rows = await _values_for(session, asset.id)
+ assert len(rows) == 2
+ assert rows[0].date == yesterday and rows[0].amount == Decimal("100")
+ assert rows[1].date == date.today() and rows[1].amount == Decimal("105")
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index ce4e25d2..2d43562a 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -20,6 +20,7 @@ import type {
Rule,
ImportLog,
Asset,
+ AssetGroup,
AssetValue,
Attachment,
Goal,
@@ -577,12 +578,31 @@ export const assets = {
deleteValue: async (valueId: string): Promise<void> => {
await api.delete(`/assets/values/${valueId}`)
},
- portfolioTrend: async (): Promise<{ assets: { id: string; name: string; type: string }[]; trend: Record<string, unknown>[]; total: number }> => {
+ portfolioTrend: async (): Promise<{ assets: { id: string; name: string; type: string; group_id: string | null }[]; trend: Record<string, unknown>[]; total: number }> => {
const { data } = await api.get('/assets/portfolio-trend')
return data
},
}
+// Asset Groups ("wallets")
+export const assetGroups = {
+ list: async (): Promise<AssetGroup[]> => {
+ const { data } = await api.get('/asset-groups')
+ return data
+ },
+ create: async (group: Partial<AssetGroup> & { name: string }): Promise<AssetGroup> => {
+ const { data } = await api.post('/asset-groups', group)
+ return data
+ },
+ update: async (id: string, group: Partial<AssetGroup>): Promise<AssetGroup> => {
+ const { data } = await api.patch(`/asset-groups/${id}`, group)
+ return data
+ },
+ delete: async (id: string): Promise<void> => {
+ await api.delete(`/asset-groups/${id}`)
+ },
+}
+
// Reports
export const reports = {
netWorth: async (months = 12, interval = 'monthly'): Promise<ReportResponse> => {
diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.json
index 6122421d..4ddba50a 100644
--- a/frontend/src/locales/en.json
+++ b/frontend/src/locales/en.json
@@ -548,7 +548,10 @@
"updated": "Category updated",
"deleted": "Category deleted",
"expandAll": "Expand all",
- "collapseAll": "Collapse all"
+ "collapseAll": "Collapse all",
+ "treatAsTransfer": "Treat as transfer",
+ "treatAsTransferDesc": "Transactions in this category won't count as income or expense in reports. Use this for movements between your own accounts (investments, savings deposits, loan repayments).",
+ "treatAsTransferBadge": "Transfer"
},
"groups": {
"title": "Category Groups",
@@ -661,6 +664,31 @@
"valueAdded": "Value added",
"valueDeleted": "Value deleted",
"sold": "Sold",
+ "synced": "Synced",
+ "syncedFrom": "Synced from {{source}}",
+ "syncedReadOnly": "Synced assets are managed by the connection",
+ "maturesOn": "Matures {{date}}",
+ "newWallet": "New Wallet",
+ "editWallet": "Edit wallet",
+ "deleteWallet": "Delete wallet",
+ "walletName": "Name",
+ "walletNamePlaceholder": "e.g. US Stocks, Long-term fixed income",
+ "walletColor": "Color",
+ "walletCreated": "Wallet created",
+ "walletUpdated": "Wallet updated",
+ "walletDeleted": "Wallet deleted",
+ "confirmDeleteWalletTitle": "Delete wallet?",
+ "confirmDeleteWallet": "The wallet will be removed and its assets become ungrouped. No asset data is lost.",
+ "ungrouped": "Ungrouped",
+ "emptyWallet": "No assets in this wallet yet",
+ "itemsCount": "items",
+ "moveToWallet": "Move to wallet",
+ "moved": "Asset moved",
+ "noWallet": "No wallet",
+ "noWalletsHint": "Create a wallet first with the \"New Wallet\" button",
+ "syncedFromHint": "Originally synced from {{source}} — you can rename freely, sync matching uses the connection ID.",
+ "chartByWallet": "By Wallet",
+ "chartByAsset": "By Asset",
"portfolioValue": "Portfolio Value",
"total": "Total",
"confirmRegenerateTitle": "Regenerate values?",
diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.json
index 012ca76b..0e6aa937 100644
--- a/frontend/src/locales/pt-BR.json
+++ b/frontend/src/locales/pt-BR.json
@@ -548,7 +548,10 @@
"updated": "Categoria atualizada",
"deleted": "Categoria excluída",
"expandAll": "Expandir tudo",
- "collapseAll": "Recolher tudo"
+ "collapseAll": "Recolher tudo",
+ "treatAsTransfer": "Tratar como transferência",
+ "treatAsTransferDesc": "Transações nesta categoria não contarão como receita ou despesa nos relatórios. Use para movimentações entre suas próprias contas (investimentos, depósitos em poupança, pagamentos de empréstimo).",
+ "treatAsTransferBadge": "Transferência"
},
"groups": {
"title": "Grupos de Categorias",
@@ -661,6 +664,31 @@
"valueAdded": "Valor adicionado",
"valueDeleted": "Valor excluído",
"sold": "Vendido",
+ "synced": "Sincronizado",
+ "syncedFrom": "Sincronizado via {{source}}",
+ "syncedReadOnly": "Ativos sincronizados são gerenciados pela conexão",
+ "maturesOn": "Vence em {{date}}",
+ "newWallet": "Nova Carteira",
+ "editWallet": "Editar carteira",
+ "deleteWallet": "Excluir carteira",
+ "walletName": "Nome",
+ "walletNamePlaceholder": "ex: Ações EUA, Renda Fixa Longo Prazo",
+ "walletColor": "Cor",
+ "walletCreated": "Carteira criada",
+ "walletUpdated": "Carteira atualizada",
+ "walletDeleted": "Carteira excluída",
+ "confirmDeleteWalletTitle": "Excluir carteira?",
+ "confirmDeleteWallet": "A carteira será removida e seus ativos ficarão sem agrupamento. Nenhum dado de ativo é perdido.",
+ "ungrouped": "Sem carteira",
+ "emptyWallet": "Nenhum ativo nesta carteira ainda",
+ "itemsCount": "itens",
+ "moveToWallet": "Mover para carteira",
+ "moved": "Ativo movido",
+ "noWallet": "Sem carteira",
+ "noWalletsHint": "Crie uma carteira primeiro com o botão \"Nova Carteira\"",
+ "syncedFromHint": "Sincronizada originalmente de {{source}} — pode renomear livremente, a sincronização não usa o nome.",
+ "chartByWallet": "Por Carteira",
+ "chartByAsset": "Por Ativo",
"portfolioValue": "Valor do Patrimônio",
"total": "Total",
"confirmRegenerateTitle": "Regenerar valores?",
diff --git a/frontend/src/pages/assets.tsx b/frontend/src/pages/assets.tsx
index 37a29594..5d2055fb 100644
--- a/frontend/src/pages/assets.tsx
+++ b/frontend/src/pages/assets.tsx
@@ -1,7 +1,7 @@
import { useState, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
-import { assets, currencies as currenciesApi } from '@/lib/api'
+import { assets, assetGroups, currencies as currenciesApi } from '@/lib/api'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
@@ -16,7 +16,7 @@ import {
import { Badge } from '@/components/ui/badge'
import { Skeleton } from '@/components/ui/skeleton'
import { DatePickerInput } from '@/components/ui/date-picker-input'
-import type { Asset, AssetValue } from '@/types'
+import type { Asset, AssetGroup, AssetValue } from '@/types'
import {
Home,
Car,
@@ -28,6 +28,10 @@ import {
Trash2,
ChevronDown,
ChevronUp,
+ ChevronRight,
+ RefreshCw,
+ Wallet,
+ FolderInput,
} from 'lucide-react'
import {
AreaChart,
@@ -87,6 +91,17 @@ export default function AssetsPage() {
const [pendingGrowthSave, setPendingGrowthSave] = useState<Record<string, unknown> | null>(null)
const [expandedId, setExpandedId] = useState<string | null>(null)
+ // Wallet (AssetGroup) dialog state
+ const [walletDialogOpen, setWalletDialogOpen] = useState(false)
+ const [editingWallet, setEditingWallet] = useState<AssetGroup | null>(null)
+ const [walletFormName, setWalletFormName] = useState('')
+ const [walletFormColor, setWalletFormColor] = useState('#0EA5E9')
+ const [deletingWalletId, setDeletingWalletId] = useState<string | null>(null)
+ // Collapsed wallet IDs — default is expanded (empty set), user can collapse manually
+ const [collapsedWallets, setCollapsedWallets] = useState<Set<string>>(new Set())
+ // Asset being moved to a wallet (null = no picker open)
+ const [movingAsset, setMovingAsset] = useState<Asset | null>(null)
+
// Form state
const [formName, setFormName] = useState('')
const [formType, setFormType] = useState<string>('other')
@@ -151,6 +166,59 @@ export default function AssetsPage() {
onError: () => toast.error(t('common.error')),
})
+ const { data: walletsList } = useQuery({
+ queryKey: ['asset-groups'],
+ queryFn: () => assetGroups.list(),
+ })
+
+ const createWalletMutation = useMutation({
+ mutationFn: (data: { name: string; color: string }) =>
+ assetGroups.create({ name: data.name, color: data.color, icon: 'wallet' }),
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: ['asset-groups'] })
+ setWalletDialogOpen(false)
+ setEditingWallet(null)
+ toast.success(t('assets.walletCreated'))
+ },
+ onError: () => toast.error(t('common.error')),
+ })
+
+ const updateWalletMutation = useMutation({
+ mutationFn: ({ id, ...data }: { id: string; name: string; color: string }) =>
+ assetGroups.update(id, { name: data.name, color: data.color }),
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: ['asset-groups'] })
+ setWalletDialogOpen(false)
+ setEditingWallet(null)
+ toast.success(t('assets.walletUpdated'))
+ },
+ onError: () => toast.error(t('common.error')),
+ })
+
+ const deleteWalletMutation = useMutation({
+ mutationFn: (id: string) => assetGroups.delete(id),
+ onSuccess: () => {
+ // Deleting a wallet un-groups its assets (backend sets group_id=null).
+ queryClient.invalidateQueries({ queryKey: ['asset-groups'] })
+ queryClient.invalidateQueries({ queryKey: ['assets'] })
+ setDeletingWalletId(null)
+ toast.success(t('assets.walletDeleted'))
+ },
+ onError: () => toast.error(t('common.error')),
+ })
+
+ const moveAssetMutation = useMutation({
+ mutationFn: ({ id, groupId }: { id: string; groupId: string | null }) =>
+ assets.update(id, { group_id: groupId } as Partial<Asset>),
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: ['assets'] })
+ queryClient.invalidateQueries({ queryKey: ['asset-groups'] })
+ setMovingAsset(null)
+ toast.success(t('assets.moved'))
+ },
+ onError: () => toast.error(t('common.error')),
+ })
+
// Compute projected current value for growth_rule preview in the form
const projectedGrowthValue = useMemo(() => {
if (formMethod !== 'growth_rule') return null
@@ -290,6 +358,7 @@ export default function AssetsPage() {
const config = getTypeConfig(asset.type)
const Icon = config.icon
const isExpanded = expandedId === asset.id
+ const isSynced = asset.source !== 'manual'
return (
<div key={asset.id} className="border border-border rounded-xl bg-card shadow-sm overflow-hidden">
@@ -306,6 +375,21 @@ export default function AssetsPage() {
<Badge variant="secondary" className="text-[10px] px-1.5 py-0">
{t(`assets.type${asset.type.replace(/_([a-z])/g, (_, c: string) => c.toUpperCase()).replace(/^./, c => c.toUpperCase())}`)}
</Badge>
+ {isSynced && (
+ <Badge
+ variant="outline"
+ className="text-[10px] px-1.5 py-0 text-sky-600 border-sky-200 gap-1"
+ title={t('assets.syncedFrom', { source: asset.source })}
+ >
+ <RefreshCw size={9} />
+ {t('assets.synced')}
+ </Badge>
+ )}
+ {asset.maturity_date && (
+ <Badge variant="outline" className="text-[10px] px-1.5 py-0 text-muted-foreground">
+ {t('assets.maturesOn', { date: new Date(asset.maturity_date).toLocaleDateString(locale) })}
+ </Badge>
+ )}
{asset.valuation_method === 'growth_rule' && asset.growth_rate && (
<Badge variant="outline" className="text-[10px] px-1.5 py-0 text-emerald-600 border-emerald-200">
+{asset.growth_type === 'percentage' ? `${asset.growth_rate}%` : formatCurrency(asset.growth_rate, asset.currency, locale)}
@@ -347,14 +431,25 @@ export default function AssetsPage() {
</div>
<div className="flex items-center gap-1 shrink-0">
<button
- onClick={(e) => { e.stopPropagation(); openEdit(asset) }}
+ onClick={(e) => { e.stopPropagation(); setMovingAsset(asset) }}
+ title={t('assets.moveToWallet')}
className="p-1.5 rounded-lg text-muted-foreground hover:text-foreground hover:bg-muted transition-colors"
+ >
+ <FolderInput size={14} />
+ </button>
+ <button
+ onClick={(e) => { e.stopPropagation(); if (!isSynced) openEdit(asset) }}
+ disabled={isSynced}
+ title={isSynced ? t('assets.syncedReadOnly') : undefined}
+ className="p-1.5 rounded-lg text-muted-foreground hover:text-foreground hover:bg-muted transition-colors disabled:opacity-30 disabled:cursor-not-allowed disabled:hover:bg-transparent"
>
<Pencil size={14} />
</button>
<button
- onClick={(e) => { e.stopPropagation(); setDeletingId(asset.id) }}
- className="p-1.5 rounded-lg text-muted-foreground hover:text-rose-600 hover:bg-rose-50 transition-colors"
+ onClick={(e) => { e.stopPropagation(); if (!isSynced) setDeletingId(asset.id) }}
+ disabled={isSynced}
+ title={isSynced ? t('assets.syncedReadOnly') : undefined}
+ className="p-1.5 rounded-lg text-muted-foreground hover:text-rose-600 hover:bg-rose-50 transition-colors disabled:opacity-30 disabled:cursor-not-allowed disabled:hover:bg-transparent"
>
<Trash2 size={14} />
</button>
@@ -367,16 +462,155 @@ export default function AssetsPage() {
)
}
+ // Bucket active assets by group_id so each wallet renders with its
+ // total and collapse toggle. Un-grouped actives go under a synthetic
+ // bucket rendered at the end.
+ const assetsByGroup = useMemo(() => {
+ const map = new Map<string | null, Asset[]>()
+ for (const a of activeAssets) {
+ const key = a.group_id ?? null
+ if (!map.has(key)) map.set(key, [])
+ map.get(key)!.push(a)
+ }
+ return map
+ }, [activeAssets])
+
+ const sortedWallets = useMemo(() => {
+ return (walletsList ?? []).slice().sort((a, b) => a.position - b.position || a.name.localeCompare(b.name))
+ }, [walletsList])
+
+ const ungroupedAssets = assetsByGroup.get(null) ?? []
+
+ function toggleWalletCollapse(id: string) {
+ setCollapsedWallets(prev => {
+ const next = new Set(prev)
+ if (next.has(id)) next.delete(id)
+ else next.add(id)
+ return next
+ })
+ }
+
+ function openCreateWallet() {
+ setEditingWallet(null)
+ setWalletFormName('')
+ setWalletFormColor('#0EA5E9')
+ setWalletDialogOpen(true)
+ }
+
+ function openEditWallet(wallet: AssetGroup) {
+ setEditingWallet(wallet)
+ setWalletFormName(wallet.name)
+ setWalletFormColor(wallet.color)
+ setWalletDialogOpen(true)
+ }
+
+ function handleSaveWallet() {
+ const name = walletFormName.trim()
+ if (!name) return
+ if (editingWallet) {
+ updateWalletMutation.mutate({ id: editingWallet.id, name, color: walletFormColor })
+ } else {
+ createWalletMutation.mutate({ name, color: walletFormColor })
+ }
+ }
+
+ function renderWalletSection(wallet: AssetGroup, walletAssets: Asset[]) {
+ const isCollapsed = collapsedWallets.has(wallet.id)
+ const isSynced = wallet.source !== 'manual'
+ // Sum in wallet's reported current_value (already computed by backend).
+ // Fall back to per-asset sum if the rollup is stale after a move.
+ const total = walletAssets.reduce((s, a) => s + (a.current_value_primary ?? a.current_value ?? 0), 0) || wallet.current_value_primary || wallet.current_value
+
+ // Only show the institution as a subtitle when it's actually
+ // additional information — if the user hasn't renamed the wallet,
+ // name and institution are identical and the subtitle would be
+ // redundant noise.
+ const showInstitutionSubtitle =
+ !!wallet.institution_name && wallet.institution_name !== wallet.name
+
+ return (
+ <div key={wallet.id} className="space-y-2">
+ <div className="flex items-center gap-3 px-1">
+ <button
+ onClick={() => toggleWalletCollapse(wallet.id)}
+ className="flex items-center gap-2 flex-1 min-w-0 group"
+ >
+ {isCollapsed ? (
+ <ChevronRight size={14} className="text-muted-foreground" />
+ ) : (
+ <ChevronDown size={14} className="text-muted-foreground" />
+ )}
+ <div
+ className="w-6 h-6 rounded-md flex items-center justify-center shrink-0"
+ style={{ backgroundColor: `${wallet.color}20` }}
+ >
+ <Wallet size={13} style={{ color: wallet.color }} />
+ </div>
+ <div className="flex flex-col items-start min-w-0 flex-1">
+ <div className="flex items-center gap-2 min-w-0 w-full">
+ <span className="text-sm font-semibold text-foreground truncate">{wallet.name}</span>
+ <span className="text-xs text-muted-foreground shrink-0">
+ · {walletAssets.length} {t('assets.itemsCount')}
+ </span>
+ </div>
+ {showInstitutionSubtitle && (
+ <span className="text-[11px] text-muted-foreground truncate flex items-center gap-1">
+ <RefreshCw size={9} />
+ {t('assets.syncedFrom', { source: wallet.institution_name })}
+ </span>
+ )}
+ </div>
+ </button>
+ <span className="text-sm font-bold tabular-nums text-foreground shrink-0">
+ {mask(formatCurrency(total, userCurrency, locale))}
+ </span>
+ <button
+ onClick={() => openEditWallet(wallet)}
+ className="p-1 rounded-lg text-muted-foreground hover:text-foreground hover:bg-muted transition-colors"
+ title={t('assets.editWallet')}
+ >
+ <Pencil size={12} />
+ </button>
+ {!isSynced && (
+ <button
+ onClick={() => setDeletingWalletId(wallet.id)}
+ className="p-1 rounded-lg text-muted-foreground hover:text-rose-600 hover:bg-rose-50 transition-colors"
+ title={t('assets.deleteWallet')}
+ >
+ <Trash2 size={12} />
+ </button>
+ )}
+ </div>
+ {!isCollapsed && walletAssets.length > 0 && (
+ <div className="space-y-2 pl-4">
+ {walletAssets.map(renderAssetCard)}
+ </div>
+ )}
+ {!isCollapsed && walletAssets.length === 0 && (
+ <div className="pl-4 py-3 text-xs text-muted-foreground italic">
+ {t('assets.emptyWallet')}
+ </div>
+ )}
+ </div>
+ )
+ }
+
return (
<div className="space-y-6">
<PageHeader
section={t('assets.title')}
title={t('assets.title')}
action={
- <Button onClick={openCreate} className="gap-1.5">
- <Plus size={16} />
- {t('assets.addAsset')}
- </Button>
+ <div className="flex items-center gap-2">
+ <Button onClick={openCreateWallet} variant="outline" className="gap-1.5">
+ <Wallet size={16} />
+ {t('assets.newWallet')}
+ </Button>
+ <Button onClick={openCreate} className="gap-1.5">
+ <Plus size={16} />
+ {t('assets.addAsset')}
+ </Button>
+ </div>
}
/>
@@ -384,6 +618,7 @@ export default function AssetsPage() {
{portfolioData && portfolioData.trend.length > 1 && (
<PortfolioChart
data={portfolioData}
+ wallets={sortedWallets}
currency={userCurrency}
locale={locale}
mask={mask}
@@ -396,15 +631,21 @@ export default function AssetsPage() {
</div>
) : (
<div className="space-y-6">
- {/* Active Assets */}
- {activeAssets.length > 0 && (
- <div className="space-y-2">
- <h3 className="text-xs font-semibold text-muted-foreground uppercase tracking-wider px-1">
- {t('assets.activeAssets')}
- </h3>
- <div className="space-y-2">
- {activeAssets.map(renderAssetCard)}
- </div>
+ {/* Wallets (active assets grouped) */}
+ {(sortedWallets.length > 0 || ungroupedAssets.length > 0) && (
+ <div className="space-y-4">
+ {sortedWallets.map(w => renderWalletSection(w, assetsByGroup.get(w.id) ?? []))}
+
+ {ungroupedAssets.length > 0 && (
+ <div className="space-y-2">
+ <h3 className="text-xs font-semibold text-muted-foreground uppercase tracking-wider px-1">
+ {sortedWallets.length > 0 ? t('assets.ungrouped') : t('assets.activeAssets')}
+ </h3>
+ <div className="space-y-2">
+ {ungroupedAssets.map(renderAssetCard)}
+ </div>
+ </div>
+ )}
</div>
)}
@@ -656,19 +897,136 @@ export default function AssetsPage() {
</DialogFooter>
</DialogContent>
</Dialog>
+
+ {/* Wallet Create/Edit Dialog */}
+ <Dialog open={walletDialogOpen} onOpenChange={setWalletDialogOpen}>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>
+ {editingWallet ? t('assets.editWallet') : t('assets.newWallet')}
+ </DialogTitle>
+ </DialogHeader>
+ <div className="space-y-4">
+ <div className="space-y-2">
+ <Label>{t('assets.walletName')}</Label>
+ <Input
+ value={walletFormName}
+ onChange={e => setWalletFormName(e.target.value)}
+ placeholder={t('assets.walletNamePlaceholder')}
+ autoFocus
+ />
+ {editingWallet?.institution_name && editingWallet.source !== 'manual' && (
+ <p className="text-[11px] text-muted-foreground flex items-center gap-1">
+ <RefreshCw size={10} />
+ {t('assets.syncedFromHint', { source: editingWallet.institution_name })}
+ </p>
+ )}
+ </div>
+ <div className="space-y-2">
+ <Label>{t('assets.walletColor')}</Label>
+ <Input
+ type="color"
+ value={walletFormColor}
+ onChange={e => setWalletFormColor(e.target.value)}
+ className="h-9 w-20 px-1 py-1"
+ />
+ </div>
+ </div>
+ <DialogFooter>
+ <Button variant="outline" onClick={() => setWalletDialogOpen(false)}>
+ {t('common.cancel')}
+ </Button>
+ <Button
+ onClick={handleSaveWallet}
+ disabled={!walletFormName.trim() || createWalletMutation.isPending || updateWalletMutation.isPending}
+ >
+ {t('common.save')}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+
+ {/* Delete Wallet Confirmation */}
+ <Dialog open={!!deletingWalletId} onOpenChange={() => setDeletingWalletId(null)}>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>{t('assets.confirmDeleteWalletTitle')}</DialogTitle>
+ </DialogHeader>
+ <p className="text-sm text-muted-foreground">{t('assets.confirmDeleteWallet')}</p>
+ <DialogFooter>
+ <Button variant="outline" onClick={() => setDeletingWalletId(null)}>
+ {t('common.cancel')}
+ </Button>
+ <Button
+ variant="destructive"
+ onClick={() => deletingWalletId && deleteWalletMutation.mutate(deletingWalletId)}
+ disabled={deleteWalletMutation.isPending}
+ >
+ {t('common.delete')}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+
+ {/* Move Asset to Wallet Picker */}
+ <Dialog open={!!movingAsset} onOpenChange={() => setMovingAsset(null)}>
+ <DialogContent className="max-w-md">
+ <DialogHeader>
+ <DialogTitle>{t('assets.moveToWallet')}</DialogTitle>
+ </DialogHeader>
+ <div className="space-y-1 max-h-80 overflow-y-auto">
+ <button
+ onClick={() => movingAsset && moveAssetMutation.mutate({ id: movingAsset.id, groupId: null })}
+ disabled={!movingAsset?.group_id || moveAssetMutation.isPending}
+ className="w-full flex items-center gap-3 px-3 py-2.5 rounded-lg hover:bg-muted disabled:opacity-50 disabled:cursor-not-allowed transition-colors text-left"
+ >
+ <div className="w-6 h-6 rounded-md flex items-center justify-center bg-muted">
+ <Package size={13} className="text-muted-foreground" />
+ </div>
+ <span className="text-sm text-foreground">{t('assets.noWallet')}</span>
+ </button>
+ {sortedWallets.map(w => (
+ <button
+ key={w.id}
+ onClick={() => movingAsset && moveAssetMutation.mutate({ id: movingAsset.id, groupId: w.id })}
+ disabled={movingAsset?.group_id === w.id || moveAssetMutation.isPending}
+ className="w-full flex items-center gap-3 px-3 py-2.5 rounded-lg hover:bg-muted disabled:opacity-50 disabled:cursor-not-allowed transition-colors text-left"
+ >
+ <div
+ className="w-6 h-6 rounded-md flex items-center justify-center"
+ style={{ backgroundColor: `${w.color}20` }}
+ >
+ <Wallet size={13} style={{ color: w.color }} />
+ </div>
+ <span className="text-sm text-foreground flex-1 truncate">{w.name}</span>
+ <span className="text-xs text-muted-foreground">{w.asset_count}</span>
+ </button>
+ ))}
+ {sortedWallets.length === 0 && (
+ <p className="text-xs text-muted-foreground italic px-3 py-2">
+ {t('assets.noWalletsHint')}
+ </p>
+ )}
+ </div>
+ </DialogContent>
+ </Dialog>
</div>
)
}
const PORTFOLIO_COLORS = ['#6366F1', '#F43F5E', '#F59E0B', '#10B981', '#8B5CF6', '#EC4899', '#06B6D4', '#84CC16']
-function PortfolioChart({ data, currency, locale: loc, mask }: {
- data: { assets: { id: string; name: string; type: string }[]; trend: Record<string, unknown>[]; total: number }
+function PortfolioChart({ data, wallets, currency, locale: loc, mask }: {
+ data: { assets: { id: string; name: string; type: string; group_id: string | null }[]; trend: Record<string, unknown>[]; total: number }
+ wallets: AssetGroup[]
currency: string
locale: string
mask: (v: string) => string
}) {
const { t } = useTranslation()
+ // Default to wallet mode: with many synced CDBs the asset view turns
+ // into a cluttered rainbow legend that's hard to parse.
+ const [mode, setMode] = useState<'wallet' | 'asset'>('wallet')
const formatCompact = (v: number) => {
const abs = Math.abs(v)
@@ -677,10 +1035,100 @@ function PortfolioChart({ data, currency, locale: loc, mask }: {
return v.toLocaleString(loc, { maximumFractionDigits: 0 })
}
+ // Compute the series list and rewrite trend rows based on the selected
+ // mode. Wallet mode rolls all assets sharing a group_id into a single
+ // series (using the wallet's own color); ungrouped assets keep their
+ // individual lines so nothing disappears from the chart.
+ const { series, displayTrend } = useMemo(() => {
+ if (mode === 'asset') {
+ const s = data.assets.map((a, i) => ({
+ key: a.id,
+ name: a.name,
+ color: PORTFOLIO_COLORS[i % PORTFOLIO_COLORS.length],
+ sourceAssetIds: [a.id],
+ }))
+ return { series: s, displayTrend: data.trend }
+ }
+
+ const walletById = new Map<string, AssetGroup>()
+ for (const w of wallets) walletById.set(w.id, w)
+
+ const groupBuckets = new Map<string, string[]>()
+ const ungroupedAssetIds: string[] = []
+ for (const a of data.assets) {
+ if (a.group_id) {
+ if (!groupBuckets.has(a.group_id)) groupBuckets.set(a.group_id, [])
+ groupBuckets.get(a.group_id)!.push(a.id)
+ } else {
+ ungroupedAssetIds.push(a.id)
+ }
+ }
+
+ // Preserve wallet display order. Falls back to insertion order for
+ // wallets that show up in the data but aren't in the wallets list
+ // (e.g. race conditions between queries).
+ const orderedGroupIds = [
+ ...wallets.map(w => w.id).filter(id => groupBuckets.has(id)),
+ ...Array.from(groupBuckets.keys()).filter(id => !walletById.has(id)),
+ ]
+
+ const s: { key: string; name: string; color: string; sourceAssetIds: string[] }[] = []
+ let fallbackColorIdx = 0
+ for (const gid of orderedGroupIds) {
+ const wallet = walletById.get(gid)
+ const assetIds = groupBuckets.get(gid)!
+ s.push({
+ key: `w_${gid}`,
+ name: wallet?.name ?? t('assets.ungrouped'),
+ color: wallet?.color ?? PORTFOLIO_COLORS[fallbackColorIdx++ % PORTFOLIO_COLORS.length],
+ sourceAssetIds: assetIds,
+ })
+ }
+ for (const aid of ungroupedAssetIds) {
+ const asset = data.assets.find(a => a.id === aid)
+ s.push({
+ key: aid,
+ name: asset?.name ?? aid,
+ color: PORTFOLIO_COLORS[fallbackColorIdx++ % PORTFOLIO_COLORS.length],
+ sourceAssetIds: [aid],
+ })
+ }
+
+ const newTrend = data.trend.map(row => {
+ const newRow: Record<string, unknown> = { date: row.date, _total: row._total }
+ for (const entry of s) {
+ let sum = 0
+ for (const aid of entry.sourceAssetIds) {
+ sum += (row[aid] as number) ?? 0
+ }
+ newRow[entry.key] = sum
+ }
+ return newRow
+ })
+
+ return { series: s, displayTrend: newTrend }
+ }, [mode, data, wallets, t])
+
return (
<div className="border border-border rounded-xl bg-card shadow-sm p-5">
- <div className="flex items-center justify-between mb-4">
- <h3 className="text-sm font-semibold text-foreground">{t('assets.portfolioValue')}</h3>
+ <div className="flex items-center justify-between mb-4 gap-4">
+ <div className="flex items-center gap-3">
+ <h3 className="text-sm font-semibold text-foreground">{t('assets.portfolioValue')}</h3>
+ <div className="inline-flex items-center rounded-lg border border-border p-0.5 bg-muted/40">
+ <button
+ onClick={() => setMode('wallet')}
+ className={`px-2.5 py-1 rounded-md text-[11px] font-medium transition-colors ${mode === 'wallet' ? 'bg-card text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground'}`}
+ >
+ {t('assets.chartByWallet')}
+ </button>
+ <button
+ onClick={() => setMode('asset')}
+ className={`px-2.5 py-1 rounded-md text-[11px] font-medium transition-colors ${mode === 'asset' ? 'bg-card text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground'}`}
+ >
+ {t('assets.chartByAsset')}
+ </button>
+ </div>
+ </div>
<div className="text-right">
<span className="text-xs text-muted-foreground">{t('assets.total')}</span>
<p className="text-lg font-bold tabular-nums text-foreground">
@@ -690,12 +1138,12 @@ function PortfolioChart({ data, currency, locale: loc, mask }: {
</div>
<div className="h-56">
<ResponsiveContainer width="100%" height="100%">
- <AreaChart data={data.trend} margin={{ top: 4, right: 12, left: 0, bottom: 0 }}>
+ <AreaChart data={displayTrend} margin={{ top: 4, right: 12, left: 0, bottom: 0 }}>
<defs>
- {data.assets.map((asset, i) => (
- <linearGradient key={asset.id} id={`portfolio-grad-${asset.id}`} x1="0" y1="0" x2="0" y2="1">
- <stop offset="0%" stopColor={PORTFOLIO_COLORS[i % PORTFOLIO_COLORS.length]} stopOpacity={0.5} />
- <stop offset="100%" stopColor={PORTFOLIO_COLORS[i % PORTFOLIO_COLORS.length]} stopOpacity={0.1} />
+ {series.map(s => (
+ <linearGradient key={s.key} id={`portfolio-grad-${s.key}`} x1="0" y1="0" x2="0" y2="1">
+ <stop offset="0%" stopColor={s.color} stopOpacity={0.5} />
+ <stop offset="100%" stopColor={s.color} stopOpacity={0.1} />
</linearGradient>
))}
</defs>
@@ -719,12 +1167,11 @@ function PortfolioChart({ data, currency, locale: loc, mask }: {
if (!active || !payload?.length) return null
const totalEntry = payload.find(p => p.dataKey === '_total')
const dateTotal = totalEntry?.value as number ?? 0
- // Show real asset values (from original keys, not _neg_ keys)
- const items = data.assets
- .map((a, i) => {
- const row = data.trend.find(r => r.date === label)
- const val = row ? (row[a.id] as number ?? 0) : 0
- return { id: a.id, name: a.name, value: val, color: PORTFOLIO_COLORS[i % PORTFOLIO_COLORS.length] }
+ const items = series
+ .map(s => {
+ const row = displayTrend.find(r => r.date === label)
+ const val = row ? ((row[s.key] as number) ?? 0) : 0
+ return { key: s.key, name: s.name, value: val, color: s.color }
})
.filter(item => item.value !== 0)
.sort((a, b) => Math.abs(b.value) - Math.abs(a.value))
@@ -735,7 +1182,7 @@ function PortfolioChart({ data, currency, locale: loc, mask }: {
{new Date(label + 'T00:00:00').toLocaleDateString(loc, { day: 'numeric', month: 'long', year: 'numeric' })}
</p>
{items.map(item => (
- <div key={item.id} style={{ display: 'flex', justifyContent: 'space-between', gap: 16, marginBottom: 2 }}>
+ <div key={item.key} style={{ display: 'flex', justifyContent: 'space-between', gap: 16, marginBottom: 2 }}>
<span style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<span style={{ width: 8, height: 8, borderRadius: '50%', backgroundColor: item.color, display: 'inline-block' }} />
{item.name}
@@ -751,16 +1198,16 @@ function PortfolioChart({ data, currency, locale: loc, mask }: {
)
}}
/>
- {/* Stacked areas — each asset is a colored band */}
- {data.assets.map((asset, i) => (
+ {/* Stacked areas — one colored band per series */}
+ {series.map(s => (
<Area
- key={asset.id}
+ key={s.key}
type="monotone"
- dataKey={asset.id}
+ dataKey={s.key}
stackId="portfolio"
- stroke={PORTFOLIO_COLORS[i % PORTFOLIO_COLORS.length]}
+ stroke={s.color}
strokeWidth={1}
- fill={`url(#portfolio-grad-${asset.id})`}
+ fill={`url(#portfolio-grad-${s.key})`}
dot={false}
activeDot={{ r: 3, strokeWidth: 1.5, fill: 'var(--card)' }}
/>
@@ -772,10 +1219,10 @@ function PortfolioChart({ data, currency, locale: loc, mask }: {
</div>
{/* Legend */}
<div className="flex flex-wrap gap-x-4 gap-y-1 mt-3 px-1">
- {data.assets.map((asset, i) => (
- <div key={asset.id} className="flex items-center gap-1.5">
- <div className="w-2.5 h-2.5 rounded-full" style={{ backgroundColor: PORTFOLIO_COLORS[i % PORTFOLIO_COLORS.length] }} />
- <span className="text-[11px] text-muted-foreground">{asset.name}</span>
+ {series.map(s => (
+ <div key={s.key} className="flex items-center gap-1.5">
+ <div className="w-2.5 h-2.5 rounded-full" style={{ backgroundColor: s.color }} />
+ <span className="text-[11px] text-muted-foreground">{s.name}</span>
</div>
))}
</div>
diff --git a/frontend/src/pages/categories.tsx b/frontend/src/pages/categories.tsx
index 15d91cad..d289e57f 100644
--- a/frontend/src/pages/categories.tsx
+++ b/frontend/src/pages/categories.tsx
@@ -45,6 +45,7 @@ export default function CategoriesPage() {
const [editingCat, setEditingCat] = useState<Category | null>(null)
const [formIcon, setFormIcon] = useState('circle-help')
const [formColor, setFormColor] = useState('#6366f1')
+ const [formTreatAsTransfer, setFormTreatAsTransfer] = useState(false)
const [groupDialogOpen, setGroupDialogOpen] = useState(false)
const [editingGroup, setEditingGroup] = useState<CategoryGroup | null>(null)
const [groupFormIcon, setGroupFormIcon] = useState('folder')
@@ -108,6 +109,7 @@ export default function CategoriesPage() {
setEditingCat(cat)
setFormIcon(cat?.icon ?? 'circle-help')
setFormColor(cat?.color ?? '#6366f1')
+ setFormTreatAsTransfer(cat?.treat_as_transfer ?? false)
setCatDialogOpen(true)
}
@@ -121,7 +123,17 @@ export default function CategoriesPage() {
const renderCategoryItem = (cat: Category) => (
<div key={cat.id} className="flex items-center gap-3 px-4 sm:px-5 pl-6 sm:pl-12 py-2.5 border-b border-border last:border-0 hover:bg-muted transition-colors">
<CategoryIcon icon={cat.icon} color={cat.color} size="md" />
- <span className="text-sm font-medium text-foreground flex-1 min-w-0 truncate">{cat.name}</span>
+ <div className="flex-1 min-w-0 flex items-center gap-2">
+ <span className="text-sm font-medium text-foreground truncate">{cat.name}</span>
+ {cat.treat_as_transfer && (
+ <span
+ className="text-[10px] font-medium px-1.5 py-0.5 rounded bg-muted text-muted-foreground border border-border shrink-0"
+ title={t('categories.treatAsTransferDesc')}
+ >
+ {t('categories.treatAsTransferBadge')}
+ </span>
+ )}
+ </div>
<div className="hidden sm:flex items-center gap-2 shrink-0">
<span className="inline-block w-3.5 h-3.5 rounded-full border border-black/10" style={{ backgroundColor: cat.color }} />
<span className="text-xs text-muted-foreground font-mono">{cat.color}</span>
@@ -249,6 +261,7 @@ export default function CategoriesPage() {
icon: formData.get('icon') as string,
color: formData.get('color') as string,
group_id: (formData.get('group_id') as string) || null,
+ treat_as_transfer: formTreatAsTransfer,
}
if (editingCat) {
updateCatMutation.mutate({ id: editingCat.id, ...data })
@@ -284,6 +297,20 @@ export default function CategoriesPage() {
<IconPicker value={formIcon} color={formColor} onChange={setFormIcon} />
<input type="hidden" name="icon" value={formIcon} />
</div>
+ <div className="pt-2 border-t border-border">
+ <label className="flex items-start gap-3 cursor-pointer">
+ <input
+ type="checkbox"
+ checked={formTreatAsTransfer}
+ onChange={(e) => setFormTreatAsTransfer(e.target.checked)}
+ className="h-4 w-4 mt-0.5 rounded border-border shrink-0"
+ />
+ <div className="flex-1 min-w-0">
+ <span className="text-sm font-medium text-foreground">{t('categories.treatAsTransfer')}</span>
+ <p className="text-xs text-muted-foreground mt-0.5">{t('categories.treatAsTransferDesc')}</p>
+ </div>
+ </label>
+ </div>
<DialogFooter>
<Button type="button" variant="outline" onClick={() => { setCatDialogOpen(false); setEditingCat(null) }}>
{t('common.cancel')}
diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts
index 18646c88..5708bc0f 100644
--- a/frontend/src/types/index.ts
+++ b/frontend/src/types/index.ts
@@ -44,6 +44,7 @@ export interface Category {
icon: string
color: string
is_system: boolean
+ treat_as_transfer: boolean
}
export interface CategoryGroup {
@@ -314,6 +315,26 @@ export interface Asset {
gain_loss: number | null
gain_loss_primary: number | null
value_count: number
+ source: string
+ connection_id: string | null
+ isin: string | null
+ maturity_date: string | null
+ group_id: string | null
+}
+
+export interface AssetGroup {
+ id: string
+ user_id: string
+ name: string
+ icon: string
+ color: string
+ position: number
+ source: string
+ connection_id: string | null
+ institution_name: string | null
+ asset_count: number
+ current_value: number
+ current_value_primary: number
}
export interface AssetValue {