Open-source personal finance manager. Self-hosted, privacy-first.
feat: add assets module with portfolio stacked area chart
Tássio Noronhab9ea87e58128
diff --git a/backend/alembic/versions/015_assets.py b/backend/alembic/versions/015_assets.pynew file mode 100644index 00000000..b9944145--- /dev/null+++ b/backend/alembic/versions/015_assets.py@@ -0,0 +1,61 @@+"""add assets and asset_values tables++Revision ID: 015+Revises: 014+Create Date: 2026-03-16+"""+from typing import Sequence, Union++import sqlalchemy as sa+from alembic import op++revision: str = "015"+down_revision: Union[str, None] = "014"+branch_labels: Union[str, Sequence[str], None] = None+depends_on: Union[str, Sequence[str], None] = None+++def upgrade() -> None:+ op.create_table(+ "assets",+ 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(255), nullable=False),+ sa.Column("type", sa.String(50), nullable=False),+ sa.Column("currency", sa.String(3), nullable=False, server_default="BRL"),+ sa.Column("units", sa.Numeric(precision=15, scale=6), nullable=True),+ sa.Column("valuation_method", sa.String(20), nullable=False, server_default="manual"),+ sa.Column("purchase_date", sa.Date(), nullable=True),+ sa.Column("purchase_price", sa.Numeric(precision=15, scale=2), nullable=True),+ sa.Column("sell_date", sa.Date(), nullable=True),+ sa.Column("sell_price", sa.Numeric(precision=15, scale=2), nullable=True),+ sa.Column("growth_type", sa.String(20), nullable=True),+ sa.Column("growth_rate", sa.Numeric(precision=15, scale=6), nullable=True),+ sa.Column("growth_frequency", sa.String(20), nullable=True),+ sa.Column("growth_start_date", sa.Date(), nullable=True),+ sa.Column("is_archived", sa.Boolean(), nullable=False, server_default="false"),+ sa.Column("position", sa.Integer(), nullable=False, server_default="0"),+ )+ op.create_index("ix_assets_user_id", "assets", ["user_id"])++ op.create_table(+ "asset_values",+ sa.Column("id", sa.UUID(), primary_key=True),+ sa.Column(+ "asset_id",+ sa.UUID(),+ sa.ForeignKey("assets.id", ondelete="CASCADE"),+ nullable=False,+ ),+ sa.Column("amount", sa.Numeric(precision=15, scale=6), nullable=False),+ sa.Column("date", sa.Date(), nullable=False),+ sa.Column("source", sa.String(20), nullable=False, server_default="manual"),+ )+ op.create_index("ix_asset_values_asset_date", "asset_values", ["asset_id", "date"])+++def downgrade() -> None:+ op.drop_index("ix_asset_values_asset_date", "asset_values")+ op.drop_table("asset_values")+ op.drop_index("ix_assets_user_id", "assets")+ op.drop_table("assets")diff --git a/backend/app/api/assets.py b/backend/app/api/assets.pynew file mode 100644index 00000000..c3bcd7ed--- /dev/null+++ b/backend/app/api/assets.py@@ -0,0 +1,124 @@+import uuid++from fastapi import APIRouter, Depends, HTTPException, Query, 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 import AssetCreate, AssetRead, AssetUpdate, AssetValueCreate, AssetValueRead+from app.services import asset_service++router = APIRouter(prefix="/api/assets", tags=["assets"])++[email protected]("", response_model=list[AssetRead])+async def list_assets(+ include_archived: bool = False,+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ return await asset_service.get_assets(session, user.id, include_archived=include_archived)++[email protected]("/portfolio-trend")+async def portfolio_trend(+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ return await asset_service.get_portfolio_trend(session, user.id)++[email protected]("/{asset_id}", response_model=AssetRead)+async def get_asset(+ asset_id: uuid.UUID,+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ asset = await asset_service.get_asset(session, asset_id, user.id)+ if not asset:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Asset not found")+ return asset++[email protected]("", response_model=AssetRead, status_code=status.HTTP_201_CREATED)+async def create_asset(+ data: AssetCreate,+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ return await asset_service.create_asset(session, user.id, data)++[email protected]("/{asset_id}", response_model=AssetRead)+async def update_asset(+ asset_id: uuid.UUID,+ data: AssetUpdate,+ regenerate_growth: bool = Query(False),+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ asset = await asset_service.update_asset(session, asset_id, user.id, data, regenerate_growth=regenerate_growth)+ if not asset:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Asset not found")+ return asset++[email protected]("/{asset_id}", status_code=status.HTTP_204_NO_CONTENT)+async def delete_asset(+ asset_id: uuid.UUID,+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ deleted = await asset_service.delete_asset(session, asset_id, user.id)+ if not deleted:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Asset not found")++[email protected]("/{asset_id}/values", response_model=list[AssetValueRead])+async def list_asset_values(+ asset_id: uuid.UUID,+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ values = await asset_service.get_asset_values(session, asset_id, user.id)+ if values is None:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Asset not found")+ return values++[email protected]("/{asset_id}/value-trend")+async def get_asset_value_trend(+ asset_id: uuid.UUID,+ months: int = Query(12, ge=1, le=120),+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ trend = await asset_service.get_asset_value_trend(session, asset_id, user.id, months=months)+ if trend is None:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Asset not found")+ return trend++[email protected]("/{asset_id}/values", response_model=AssetValueRead, status_code=status.HTTP_201_CREATED)+async def add_asset_value(+ asset_id: uuid.UUID,+ data: AssetValueCreate,+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ value = await asset_service.add_asset_value(session, asset_id, user.id, data)+ if value is None:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Asset not found")+ return value++[email protected]("/values/{value_id}", status_code=status.HTTP_204_NO_CONTENT)+async def delete_asset_value(+ value_id: uuid.UUID,+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ deleted = await asset_service.delete_asset_value(session, value_id, user.id)+ if not deleted:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Value not found")diff --git a/backend/app/main.py b/backend/app/main.pyindex 84d36e32..94956779 100644--- a/backend/app/main.py+++ b/backend/app/main.py@@ -14,6 +14,7 @@ from app.api.import_logs import router as import_logs_routerfrom app.api.import_transactions import router as import_routerfrom app.api.recurring_transactions import router as recurring_routerfrom app.api.rules import router as rules_router+from app.api.assets import router as assets_routerfrom app.api.setup import router as setup_routerfrom app.api.transactions import router as transactions_routerfrom app.core.auth import auth_backend, fastapi_users@@ -85,6 +86,7 @@ app.include_router(accounts_router)app.include_router(connections_router)app.include_router(recurring_router)app.include_router(budgets_router)+app.include_router(assets_router)app.include_router(dashboard_router)app.include_router(setup_router)diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.pyindex fda8af1d..084c0e51 100644--- a/backend/app/models/__init__.py+++ b/backend/app/models/__init__.py@@ -8,6 +8,8 @@ from app.models.rule import Rulefrom app.models.recurring_transaction import RecurringTransactionfrom app.models.budget import Budgetfrom app.models.import_log import ImportLog+from app.models.asset import Asset+from app.models.asset_value import AssetValue__all__ = ["User",@@ -20,4 +22,6 @@ __all__ = ["RecurringTransaction","Budget","ImportLog",+ "Asset",+ "AssetValue",]diff --git a/backend/app/models/asset.py b/backend/app/models/asset.pynew file mode 100644index 00000000..6f6a140a--- /dev/null+++ b/backend/app/models/asset.py@@ -0,0 +1,37 @@+import uuid+from datetime import date+from decimal import Decimal+from typing import TYPE_CHECKING, Optional++from sqlalchemy import 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_value import AssetValue+++class Asset(Base):+ __tablename__ = "assets"++ 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(255))+ type: Mapped[str] = mapped_column(String(50)) # real_estate, vehicle, valuable, investment, other+ currency: Mapped[str] = mapped_column(String(3), default="BRL")+ units: Mapped[Optional[Decimal]] = mapped_column(Numeric(precision=15, scale=6), nullable=True)+ valuation_method: Mapped[str] = mapped_column(String(20), default="manual") # manual, growth_rule+ purchase_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)+ purchase_price: Mapped[Optional[Decimal]] = mapped_column(Numeric(precision=15, scale=2), nullable=True)+ sell_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)+ sell_price: Mapped[Optional[Decimal]] = mapped_column(Numeric(precision=15, scale=2), nullable=True)+ growth_type: Mapped[Optional[str]] = mapped_column(String(20), nullable=True) # percentage, absolute+ growth_rate: Mapped[Optional[Decimal]] = mapped_column(Numeric(precision=15, scale=6), nullable=True)+ growth_frequency: Mapped[Optional[str]] = mapped_column(String(20), nullable=True) # daily, weekly, monthly, yearly+ growth_start_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)+ is_archived: Mapped[bool] = mapped_column(Boolean, default=False)+ position: Mapped[int] = mapped_column(Integer, default=0)++ values: Mapped[list["AssetValue"]] = relationship(back_populates="asset", cascade="all, delete-orphan")diff --git a/backend/app/models/asset_value.py b/backend/app/models/asset_value.pynew file mode 100644index 00000000..9d6ab9d8--- /dev/null+++ b/backend/app/models/asset_value.py@@ -0,0 +1,22 @@+import uuid+from datetime import date+from decimal import Decimal++from sqlalchemy import Date, ForeignKey, Numeric, String+from sqlalchemy.dialects.postgresql import UUID+from sqlalchemy.orm import Mapped, mapped_column, relationship++from app.core.database import Base+from app.models.asset import Asset+++class AssetValue(Base):+ __tablename__ = "asset_values"++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ asset_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("assets.id", ondelete="CASCADE"))+ amount: Mapped[Decimal] = mapped_column(Numeric(precision=15, scale=6))+ date: Mapped[date] = mapped_column(Date)+ source: Mapped[str] = mapped_column(String(20), default="manual") # manual, rule, sync++ asset: Mapped["Asset"] = relationship(back_populates="values")diff --git a/backend/app/schemas/asset.py b/backend/app/schemas/asset.pynew file mode 100644index 00000000..191d7488--- /dev/null+++ b/backend/app/schemas/asset.py@@ -0,0 +1,83 @@+import uuid+from datetime import date+from decimal import Decimal+from typing import Optional++from pydantic import BaseModel, ConfigDict+++class AssetCreate(BaseModel):+ name: str+ type: str+ currency: str = "BRL"+ units: Optional[Decimal] = None+ valuation_method: str = "manual"+ purchase_date: Optional[date] = None+ purchase_price: Optional[Decimal] = None+ sell_date: Optional[date] = None+ sell_price: Optional[Decimal] = None+ current_value: Optional[Decimal] = None # convenience: creates initial AssetValue+ growth_type: Optional[str] = None+ growth_rate: Optional[Decimal] = None+ growth_frequency: Optional[str] = None+ growth_start_date: Optional[date] = None+ is_archived: bool = False+ position: int = 0+++class AssetUpdate(BaseModel):+ name: Optional[str] = None+ type: Optional[str] = None+ currency: Optional[str] = None+ units: Optional[Decimal] = None+ valuation_method: Optional[str] = None+ purchase_date: Optional[date] = None+ purchase_price: Optional[Decimal] = None+ sell_date: Optional[date] = None+ sell_price: Optional[Decimal] = None+ growth_type: Optional[str] = None+ growth_rate: Optional[Decimal] = None+ growth_frequency: Optional[str] = None+ growth_start_date: Optional[date] = None+ is_archived: Optional[bool] = None+ position: Optional[int] = None+++class AssetRead(BaseModel):+ id: uuid.UUID+ user_id: uuid.UUID+ name: str+ type: str+ currency: str+ units: Optional[float] = None+ valuation_method: str+ purchase_date: Optional[date] = None+ purchase_price: Optional[float] = None+ sell_date: Optional[date] = None+ sell_price: Optional[float] = None+ growth_type: Optional[str] = None+ growth_rate: Optional[float] = None+ growth_frequency: Optional[str] = None+ growth_start_date: Optional[date] = None+ is_archived: bool+ position: int+ current_value: Optional[float] = None+ gain_loss: Optional[float] = None+ value_count: int = 0++ model_config = ConfigDict(from_attributes=True)+++class AssetValueCreate(BaseModel):+ amount: Decimal+ date: date+++class AssetValueRead(BaseModel):+ id: uuid.UUID+ asset_id: uuid.UUID+ amount: float+ date: date+ source: str++ model_config = ConfigDict(from_attributes=True)diff --git a/backend/app/schemas/dashboard.py b/backend/app/schemas/dashboard.pyindex 972b665c..14919b2e 100644--- a/backend/app/schemas/dashboard.py+++ b/backend/app/schemas/dashboard.py@@ -11,6 +11,7 @@ class DashboardSummary(BaseModel):accounts_count: intpending_categorization: intpending_categorization_amount: float+ assets_value: dict[str, float] = {} # currency -> total asset valueclass SpendingByCategory(BaseModel):diff --git a/backend/app/services/asset_service.py b/backend/app/services/asset_service.pynew file mode 100644index 00000000..f17d8fd3--- /dev/null+++ b/backend/app/services/asset_service.py@@ -0,0 +1,487 @@+import uuid+from datetime import date, timedelta+from decimal import Decimal+from typing import Optional++from sqlalchemy import select, func, desc+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.asset import Asset+from app.models.asset_value import AssetValue+from app.schemas.asset import AssetCreate, AssetUpdate, AssetValueCreate, AssetRead, AssetValueRead+++def _next_due_date(last_date: date, frequency: str) -> date:+ """Calculate the next due date based on frequency."""+ if frequency == "daily":+ return last_date + timedelta(days=1)+ elif frequency == "weekly":+ return last_date + timedelta(weeks=1)+ elif frequency == "monthly":+ month = last_date.month + 1+ year = last_date.year+ if month > 12:+ month = 1+ year += 1+ day = min(last_date.day, 28)+ return date(year, month, day)+ elif frequency == "yearly":+ return date(last_date.year + 1, last_date.month, last_date.day)+ return last_date + timedelta(days=1)+++def _compute_current_value(asset: Asset, latest_value: Optional[AssetValue]) -> Optional[float]:+ """Compute the current value of an asset from its latest AssetValue.+ Falls back to purchase_price if no value entries exist yet."""+ if latest_value is None:+ if asset.purchase_price is not None:+ return float(asset.purchase_price)+ return None+ return float(latest_value.amount)+++def _generate_growth_values(+ asset_id: uuid.UUID,+ base_amount: float,+ base_date: date,+ growth_type: str,+ growth_rate: float,+ growth_frequency: str,+ growth_start_date: Optional[date],+) -> list[AssetValue]:+ """Generate all AssetValue rows from base_date to today using the growth rule."""+ today = date.today()+ if growth_start_date and today < growth_start_date:+ return []++ values: list[AssetValue] = []+ current_amount = base_amount+ current_date = base_date++ while True:+ next_due = _next_due_date(current_date, growth_frequency)+ if next_due > today:+ break+ if growth_type == "percentage":+ current_amount = current_amount * (1 + growth_rate / 100)+ elif growth_type == "absolute":+ current_amount = current_amount + growth_rate+ else:+ break+ values.append(AssetValue(+ asset_id=asset_id,+ amount=Decimal(str(round(current_amount, 6))),+ date=next_due,+ source="rule",+ ))+ current_date = next_due+ if len(values) >= 10000:+ break++ return values+++def _asset_to_read(asset: Asset, latest_value: Optional[AssetValue], value_count: int) -> AssetRead:+ """Convert an Asset model + computed fields to AssetRead schema."""+ current_value = _compute_current_value(asset, latest_value)+ gain_loss = None+ if current_value is not None and asset.purchase_price is not None:+ gain_loss = current_value - float(asset.purchase_price)++ return AssetRead(+ id=asset.id,+ user_id=asset.user_id,+ name=asset.name,+ type=asset.type,+ currency=asset.currency,+ units=float(asset.units) if asset.units is not None else None,+ valuation_method=asset.valuation_method,+ purchase_date=asset.purchase_date,+ purchase_price=float(asset.purchase_price) if asset.purchase_price is not None else None,+ sell_date=asset.sell_date,+ sell_price=float(asset.sell_price) if asset.sell_price is not None else None,+ growth_type=asset.growth_type,+ growth_rate=float(asset.growth_rate) if asset.growth_rate is not None else None,+ growth_frequency=asset.growth_frequency,+ growth_start_date=asset.growth_start_date,+ is_archived=asset.is_archived,+ position=asset.position,+ current_value=current_value,+ gain_loss=gain_loss,+ value_count=value_count,+ )+++async def _get_latest_value(session: AsyncSession, asset_id: uuid.UUID) -> Optional[AssetValue]:+ """Get the most recent AssetValue for an asset."""+ result = await session.execute(+ select(AssetValue)+ .where(AssetValue.asset_id == asset_id)+ .order_by(desc(AssetValue.date), desc(AssetValue.id))+ .limit(1)+ )+ return result.scalar_one_or_none()+++async def _get_value_count(session: AsyncSession, asset_id: uuid.UUID) -> int:+ """Get the number of AssetValue entries for an asset."""+ result = await session.scalar(+ select(func.count()).select_from(AssetValue).where(AssetValue.asset_id == asset_id)+ )+ return result or 0+++async def get_assets(+ session: AsyncSession, user_id: uuid.UUID, include_archived: bool = False+) -> list[AssetRead]:+ """List all assets for a user with computed current_value."""+ query = select(Asset).where(Asset.user_id == user_id)+ if not include_archived:+ query = query.where(Asset.is_archived == False)+ query = query.order_by(Asset.position, Asset.name)++ result = await session.execute(query)+ assets = list(result.scalars().all())++ reads = []+ for asset in assets:+ latest = await _get_latest_value(session, asset.id)+ count = await _get_value_count(session, asset.id)+ reads.append(_asset_to_read(asset, latest, count))+ return reads+++async def get_asset(+ session: AsyncSession, asset_id: uuid.UUID, user_id: uuid.UUID+) -> Optional[AssetRead]:+ """Get a single asset with computed fields."""+ result = await session.execute(+ select(Asset).where(Asset.id == asset_id, Asset.user_id == user_id)+ )+ asset = result.scalar_one_or_none()+ if not asset:+ return None+ latest = await _get_latest_value(session, asset.id)+ count = await _get_value_count(session, asset.id)+ return _asset_to_read(asset, latest, count)+++async def create_asset(+ session: AsyncSession, user_id: uuid.UUID, data: AssetCreate+) -> AssetRead:+ """Create an asset, optionally with an initial value."""+ asset = Asset(+ user_id=user_id,+ name=data.name,+ type=data.type,+ currency=data.currency,+ units=data.units,+ valuation_method=data.valuation_method,+ purchase_date=data.purchase_date,+ purchase_price=data.purchase_price,+ sell_date=data.sell_date,+ sell_price=data.sell_price,+ growth_type=data.growth_type,+ growth_rate=data.growth_rate,+ growth_frequency=data.growth_frequency,+ growth_start_date=data.growth_start_date,+ is_archived=data.is_archived,+ position=data.position,+ )+ session.add(asset)+ await session.flush()++ # Create initial value if provided+ if data.current_value is not None:+ value = AssetValue(+ asset_id=asset.id,+ amount=data.current_value,+ date=date.today(),+ source="manual",+ )+ session.add(value)+ elif data.valuation_method == "growth_rule" and data.purchase_price is not None:+ # Seed the initial value from purchase price+ base_date = data.purchase_date or data.growth_start_date or date.today()+ seed = AssetValue(+ asset_id=asset.id,+ amount=data.purchase_price,+ date=base_date,+ source="manual",+ )+ session.add(seed)++ # Backfill all growth values from the seed date to today+ if data.growth_type and data.growth_rate and data.growth_frequency:+ backfill = _generate_growth_values(+ asset_id=asset.id,+ base_amount=float(data.purchase_price),+ base_date=base_date,+ growth_type=data.growth_type,+ growth_rate=float(data.growth_rate),+ growth_frequency=data.growth_frequency,+ growth_start_date=data.growth_start_date,+ )+ for v in backfill:+ session.add(v)++ await session.commit()+ await session.refresh(asset)+ latest = await _get_latest_value(session, asset.id)+ count = await _get_value_count(session, asset.id)+ return _asset_to_read(asset, latest, count)+++async def update_asset(+ session: AsyncSession, asset_id: uuid.UUID, user_id: uuid.UUID, data: AssetUpdate,+ regenerate_growth: bool = False,+) -> Optional[AssetRead]:+ """Partial update of an asset."""+ result = await session.execute(+ select(Asset).where(Asset.id == asset_id, Asset.user_id == user_id)+ )+ asset = result.scalar_one_or_none()+ if not asset:+ return None++ update_data = data.model_dump(exclude_unset=True)+ # Prevent changing valuation_method on existing assets+ update_data.pop("valuation_method", None)+ for key, value in update_data.items():+ setattr(asset, key, value)++ # Regenerate growth-rule values if requested+ if regenerate_growth and asset.valuation_method == "growth_rule":+ # Delete all rule-generated values+ await session.execute(+ select(AssetValue)+ .where(AssetValue.asset_id == asset.id, AssetValue.source == "rule")+ )+ from sqlalchemy import delete as sa_delete+ await session.execute(+ sa_delete(AssetValue).where(+ AssetValue.asset_id == asset.id,+ AssetValue.source == "rule",+ )+ )+ # Regenerate from purchase_price+ if asset.purchase_price and asset.growth_type and asset.growth_rate and asset.growth_frequency:+ base_date = asset.purchase_date or asset.growth_start_date or date.today()+ backfill = _generate_growth_values(+ asset_id=asset.id,+ base_amount=float(asset.purchase_price),+ base_date=base_date,+ growth_type=asset.growth_type,+ growth_rate=float(asset.growth_rate),+ growth_frequency=asset.growth_frequency,+ growth_start_date=asset.growth_start_date,+ )+ for v in backfill:+ session.add(v)++ await session.commit()+ await session.refresh(asset)+ latest = await _get_latest_value(session, asset.id)+ count = await _get_value_count(session, asset.id)+ return _asset_to_read(asset, latest, count)+++async def delete_asset(+ session: AsyncSession, asset_id: uuid.UUID, user_id: uuid.UUID+) -> bool:+ """Delete an asset (cascades to values)."""+ result = await session.execute(+ select(Asset).where(Asset.id == asset_id, Asset.user_id == user_id)+ )+ asset = result.scalar_one_or_none()+ if not asset:+ return False+ await session.delete(asset)+ await session.commit()+ return True+++async def get_asset_values(+ session: AsyncSession, asset_id: uuid.UUID, user_id: uuid.UUID+) -> Optional[list[AssetValueRead]]:+ """Get value history for an asset, most recent first."""+ # Verify ownership+ owner_check = await session.execute(+ select(Asset.id).where(Asset.id == asset_id, Asset.user_id == user_id)+ )+ if not owner_check.scalar_one_or_none():+ return None++ result = await session.execute(+ select(AssetValue)+ .where(AssetValue.asset_id == asset_id)+ .order_by(desc(AssetValue.date), desc(AssetValue.id))+ )+ values = result.scalars().all()+ return [AssetValueRead.model_validate(v) for v in values]+++async def add_asset_value(+ session: AsyncSession, asset_id: uuid.UUID, user_id: uuid.UUID, data: AssetValueCreate+) -> Optional[AssetValueRead]:+ """Add a new value entry for an asset."""+ # Verify ownership+ owner_check = await session.execute(+ select(Asset.id).where(Asset.id == asset_id, Asset.user_id == user_id)+ )+ if not owner_check.scalar_one_or_none():+ return None++ value = AssetValue(+ asset_id=asset_id,+ amount=data.amount,+ date=data.date,+ source="manual",+ )+ session.add(value)+ await session.commit()+ await session.refresh(value)+ return AssetValueRead.model_validate(value)+++async def delete_asset_value(+ session: AsyncSession, value_id: uuid.UUID, user_id: uuid.UUID+) -> bool:+ """Delete a specific asset value entry."""+ result = await session.execute(+ select(AssetValue)+ .join(Asset, AssetValue.asset_id == Asset.id)+ .where(AssetValue.id == value_id, Asset.user_id == user_id)+ )+ value = result.scalar_one_or_none()+ if not value:+ return False+ await session.delete(value)+ await session.commit()+ return True+++async def get_asset_value_trend(+ session: AsyncSession, asset_id: uuid.UUID, user_id: uuid.UUID, months: int = 12+) -> Optional[list[dict]]:+ """Get value trend data for charting."""+ # Verify ownership+ owner_check = await session.execute(+ select(Asset.id).where(Asset.id == asset_id, Asset.user_id == user_id)+ )+ if not owner_check.scalar_one_or_none():+ return None++ result = await session.execute(+ select(AssetValue.date, AssetValue.amount)+ .where(AssetValue.asset_id == asset_id)+ .order_by(AssetValue.date)+ )+ rows = result.all()+ return [{"date": row[0].isoformat(), "amount": float(row[1])} for row in rows]+++async def get_portfolio_trend(+ session: AsyncSession, user_id: uuid.UUID+) -> dict:+ """Get portfolio trend data for stacked area chart.+ Returns asset metadata + pivoted trend with fill-forward values."""+ result = await session.execute(+ select(Asset).where(+ Asset.user_id == user_id,+ Asset.is_archived == False,+ Asset.sell_date.is_(None),+ ).order_by(Asset.position, Asset.name)+ )+ active_assets = list(result.scalars().all())++ if not active_assets:+ return {"assets": [], "trend": [], "total": 0.0}++ # Collect all values per asset and all unique dates+ asset_meta = []+ asset_values_map: dict[str, list[tuple[date, float]]] = {}+ all_dates: set[date] = set()++ for asset in active_assets:+ aid = str(asset.id)+ asset_meta.append({"id": aid, "name": asset.name, "type": asset.type})++ rows = await session.execute(+ select(AssetValue.date, AssetValue.amount)+ .where(AssetValue.asset_id == asset.id)+ .order_by(AssetValue.date)+ )+ vals = [(r[0], float(r[1])) for r in rows.all()]++ # Prepend purchase_price as the first data point if it predates existing values+ if asset.purchase_price is not None and asset.purchase_date is not None:+ if not vals or asset.purchase_date < vals[0][0]:+ vals.insert(0, (asset.purchase_date, float(asset.purchase_price)))++ asset_values_map[aid] = vals+ for d, _ in vals:+ all_dates.add(d)++ if not all_dates:+ return {"assets": asset_meta, "trend": [], "total": 0.0}++ sorted_dates = sorted(all_dates)++ # Build lookup: aid -> {date: value}+ value_lookup: dict[str, dict[date, float]] = {}+ first_date: dict[str, date] = {}+ for aid in [a["id"] for a in asset_meta]:+ value_lookup[aid] = {d: v for d, v in asset_values_map[aid]}+ if asset_values_map[aid]:+ first_date[aid] = asset_values_map[aid][0][0]++ # Build trend with fill-forward; 0 before first date (for stacking)+ trend = []+ last_known: dict[str, float] = {}+ for aid in [a["id"] for a in asset_meta]:+ last_known[aid] = 0.0++ for d in sorted_dates:+ row: dict[str, object] = {"date": d.isoformat()}+ date_total = 0.0+ for aid in [a["id"] for a in asset_meta]:+ if d in value_lookup[aid]:+ last_known[aid] = value_lookup[aid][d]+ # Use 0 before asset exists (stacking needs numeric values)+ if aid in first_date and d >= first_date[aid]:+ val = round(last_known[aid], 2)+ else:+ val = 0+ row[aid] = val+ date_total += val+ row["_total"] = round(date_total, 2)+ trend.append(row)++ # Total = sum of last known values+ total = sum(last_known[a["id"]] for a in asset_meta)++ return {"assets": asset_meta, "trend": trend, "total": round(total, 2)}+++async def get_total_asset_value(+ session: AsyncSession, user_id: uuid.UUID+) -> dict[str, float]:+ """Get total asset value grouped by currency (for dashboard).+ Only includes non-archived assets that haven't been sold."""+ result = await session.execute(+ select(Asset).where(+ Asset.user_id == user_id,+ Asset.is_archived == False,+ Asset.sell_date.is_(None),+ )+ )+ assets = list(result.scalars().all())++ totals: dict[str, float] = {}+ for asset in assets:+ latest = await _get_latest_value(session, asset.id)+ current = _compute_current_value(asset, latest)+ if current is not None:+ totals[asset.currency] = totals.get(asset.currency, 0.0) + current+ return totalsdiff --git a/backend/app/services/dashboard_service.py b/backend/app/services/dashboard_service.pyindex c364361d..3e31154f 100644--- a/backend/app/services/dashboard_service.py+++ b/backend/app/services/dashboard_service.py@@ -12,6 +12,7 @@ from app.models.category import Categoryfrom app.models.recurring_transaction import RecurringTransactionfrom app.schemas.dashboard import DashboardSummary, SpendingByCategory, MonthlyTrend, ProjectedTransaction, DailyBalance, BalanceHistoryfrom app.services.recurring_transaction_service import get_occurrences_in_range+from app.services.asset_service import get_total_asset_valuedef _month_range(month: date) -> tuple[date, date]:@@ -148,6 +149,13 @@ async def get_summary(.where(*pending_cat_filters)) or 0))+ # Asset values+ assets_value = await get_total_asset_value(session, user_id)++ # Add asset values to total balance+ for currency, amount in assets_value.items():+ total_balance[currency] = total_balance.get(currency, 0.0) + amount+return DashboardSummary(total_balance=total_balance,balance_date=cutoff.isoformat(),@@ -156,6 +164,7 @@ async def get_summary(accounts_count=accounts_count,pending_categorization=pending_categorization,pending_categorization_amount=pending_categorization_amount,+ assets_value=assets_value,)diff --git a/backend/app/tasks/asset_tasks.py b/backend/app/tasks/asset_tasks.pynew file mode 100644index 00000000..778213e1--- /dev/null+++ b/backend/app/tasks/asset_tasks.py@@ -0,0 +1,129 @@+import asyncio+import logging+from datetime import date, timedelta+from decimal import Decimal++from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker++from app.worker import celery_app+from app.core.config import get_settings+from app.models.asset import Asset+from app.models.asset_value import AssetValue++logger = logging.getLogger(__name__)+++def _make_session_maker():+ """Create a fresh engine+session for the Celery worker event loop."""+ settings = get_settings()+ engine = create_async_engine(settings.database_url)+ return async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)+++def _next_due_date(last_date: date, frequency: str) -> date:+ """Calculate the next due date based on frequency."""+ if frequency == "daily":+ return last_date + timedelta(days=1)+ elif frequency == "weekly":+ return last_date + timedelta(weeks=1)+ elif frequency == "monthly":+ month = last_date.month + 1+ year = last_date.year+ if month > 12:+ month = 1+ year += 1+ day = min(last_date.day, 28) # safe for all months+ return date(year, month, day)+ elif frequency == "yearly":+ return date(last_date.year + 1, last_date.month, last_date.day)+ return last_date + timedelta(days=1)+++async def _apply_growth_rules() -> int:+ """Apply growth rules for all assets that have valuation_method='growth_rule'."""+ session_maker = _make_session_maker()+ today = date.today()+ total = 0++ async with session_maker() as session:+ result = await session.execute(+ select(Asset).where(+ Asset.valuation_method == "growth_rule",+ Asset.growth_type.isnot(None),+ Asset.growth_rate.isnot(None),+ Asset.growth_frequency.isnot(None),+ Asset.is_archived == False,+ Asset.sell_date.is_(None),+ )+ )+ assets = list(result.scalars().all())++ for asset in assets:+ try:+ async with session_maker() as session:+ # Get latest value+ val_result = await session.execute(+ select(AssetValue)+ .where(AssetValue.asset_id == asset.id)+ .order_by(AssetValue.date.desc(), AssetValue.id.desc())+ .limit(1)+ )+ latest = val_result.scalar_one_or_none()+ if not latest:+ continue++ # Check if growth should start+ if asset.growth_start_date and today < asset.growth_start_date:+ continue++ # Generate all missed periods in a loop+ current_date = latest.date+ current_amount = float(latest.amount)+ created = 0++ while True:+ next_due = _next_due_date(current_date, asset.growth_frequency)+ if next_due > today:+ break++ if asset.growth_type == "percentage":+ current_amount = current_amount * (1 + float(asset.growth_rate) / 100)+ elif asset.growth_type == "absolute":+ current_amount = current_amount + float(asset.growth_rate)+ else:+ break++ new_value = AssetValue(+ asset_id=asset.id,+ amount=Decimal(str(round(current_amount, 6))),+ date=next_due,+ source="rule",+ )+ session.add(new_value)+ current_date = next_due+ created += 1++ # Safety limit to avoid infinite loops+ if created >= 1000:+ break++ if created > 0:+ await session.commit()+ total += created+ logger.info(+ "Growth rule applied for asset %s: %d values created, latest=%.2f",+ asset.id, created, current_amount,+ )+ except Exception:+ logger.exception("Failed to apply growth rule for asset %s", asset.id)++ return total+++@celery_app.task(name="app.tasks.asset_tasks.apply_asset_growth_rules")+def apply_asset_growth_rules() -> dict:+ """Celery task: apply growth rules for all assets."""+ total = asyncio.run(_apply_growth_rules())+ logger.info("Asset growth rules complete: %d values created", total)+ return {"created": total}diff --git a/backend/app/worker.py b/backend/app/worker.pyindex c527783b..3bcf5888 100644--- a/backend/app/worker.py+++ b/backend/app/worker.py@@ -27,6 +27,10 @@ celery_app.conf.beat_schedule = {"task": "app.tasks.recurring_tasks.generate_all_recurring","schedule": 60 * 60, # every hour; generate_pending is idempotent (advances next_occurrence)},+ "apply-asset-growth-daily": {+ "task": "app.tasks.asset_tasks.apply_asset_growth_rules",+ "schedule": 60 * 60, # every hour; idempotent (checks last value date)+ },}-celery_app.conf.include = ["app.tasks.sync_tasks", "app.tasks.recurring_tasks"]+celery_app.conf.include = ["app.tasks.sync_tasks", "app.tasks.recurring_tasks", "app.tasks.asset_tasks"]diff --git a/backend/tests/conftest.py b/backend/tests/conftest.pyindex ee65eac6..c9aa4ebd 100644--- a/backend/tests/conftest.py+++ b/backend/tests/conftest.py@@ -16,6 +16,8 @@ from app.models.bank_connection import BankConnectionfrom app.models.account import Accountfrom app.models.transaction import Transactionfrom app.models.rule import Rule+from app.models.asset import Asset # noqa: F401+from app.models.asset_value import AssetValue # noqa: F401# Use SQLite for tests — fast, no external dependencyTEST_DATABASE_URL = "sqlite+aiosqlite:///./test.db"diff --git a/backend/tests/test_asset_service.py b/backend/tests/test_asset_service.pynew file mode 100644index 00000000..84b7f9cb--- /dev/null+++ b/backend/tests/test_asset_service.py@@ -0,0 +1,665 @@+import uuid+from datetime import date, timedelta+from decimal import Decimal++import pytest+import pytest_asyncio+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.asset import Asset+from app.models.asset_value import AssetValue+from app.models.user import User+from app.schemas.asset import AssetCreate, AssetUpdate, AssetValueCreate+from app.services import asset_service+++@pytest_asyncio.fixture+async def test_asset(session: AsyncSession, test_user: User) -> Asset:+ """Create a test asset."""+ asset = Asset(+ id=uuid.uuid4(),+ user_id=test_user.id,+ name="Test Property",+ type="real_estate",+ currency="BRL",+ valuation_method="manual",+ purchase_date=date(2025, 1, 1),+ purchase_price=Decimal("500000.00"),+ position=0,+ )+ session.add(asset)+ await session.commit()+ await session.refresh(asset)+ return asset+++@pytest_asyncio.fixture+async def test_asset_with_values(session: AsyncSession, test_asset: Asset) -> Asset:+ """Create test asset with some value entries."""+ values_data = [+ (Decimal("500000.00"), date(2025, 1, 1), "manual"),+ (Decimal("520000.00"), date(2025, 6, 1), "manual"),+ (Decimal("550000.00"), date(2026, 1, 1), "manual"),+ ]+ for amount, dt, source in values_data:+ v = AssetValue(+ id=uuid.uuid4(),+ asset_id=test_asset.id,+ amount=amount,+ date=dt,+ source=source,+ )+ session.add(v)+ await session.commit()+ return test_asset+++async def test_create_asset(session: AsyncSession, test_user: User):+ data = AssetCreate(name="Car", type="vehicle", currency="BRL")+ result = await asset_service.create_asset(session, test_user.id, data)+ assert result.name == "Car"+ assert result.type == "vehicle"+ assert result.current_value is None+ assert result.value_count == 0+++async def test_create_asset_with_initial_value(session: AsyncSession, test_user: User):+ data = AssetCreate(+ name="Watch", type="valuable", currency="BRL",+ current_value=Decimal("15000.00"),+ purchase_price=Decimal("12000.00"),+ )+ result = await asset_service.create_asset(session, test_user.id, data)+ assert result.current_value == 15000.0+ assert result.gain_loss == 3000.0+ assert result.value_count == 1+++async def test_list_assets(session: AsyncSession, test_user: User, test_asset: Asset):+ results = await asset_service.get_assets(session, test_user.id)+ assert len(results) >= 1+ names = [a.name for a in results]+ assert "Test Property" in names+++async def test_list_assets_excludes_archived(session: AsyncSession, test_user: User):+ asset = Asset(+ id=uuid.uuid4(),+ user_id=test_user.id,+ name="Archived Asset",+ type="other",+ currency="BRL",+ valuation_method="manual",+ is_archived=True,+ )+ session.add(asset)+ await session.commit()++ results = await asset_service.get_assets(session, test_user.id, include_archived=False)+ names = [a.name for a in results]+ assert "Archived Asset" not in names++ results_all = await asset_service.get_assets(session, test_user.id, include_archived=True)+ names_all = [a.name for a in results_all]+ assert "Archived Asset" in names_all+++async def test_get_asset(session: AsyncSession, test_user: User, test_asset: Asset):+ result = await asset_service.get_asset(session, test_asset.id, test_user.id)+ assert result is not None+ assert result.name == "Test Property"+++async def test_get_asset_not_found(session: AsyncSession, test_user: User):+ result = await asset_service.get_asset(session, uuid.uuid4(), test_user.id)+ assert result is None+++async def test_update_asset(session: AsyncSession, test_user: User, test_asset: Asset):+ data = AssetUpdate(name="Updated Property", type="investment")+ result = await asset_service.update_asset(session, test_asset.id, test_user.id, data)+ assert result is not None+ assert result.name == "Updated Property"+ assert result.type == "investment"+++async def test_update_asset_not_found(session: AsyncSession, test_user: User):+ data = AssetUpdate(name="Nope")+ result = await asset_service.update_asset(session, uuid.uuid4(), test_user.id, data)+ assert result is None+++async def test_delete_asset(session: AsyncSession, test_user: User):+ asset = Asset(+ id=uuid.uuid4(),+ user_id=test_user.id,+ name="To Delete",+ type="other",+ currency="BRL",+ valuation_method="manual",+ )+ session.add(asset)+ await session.commit()++ deleted = await asset_service.delete_asset(session, asset.id, test_user.id)+ assert deleted is True++ result = await asset_service.get_asset(session, asset.id, test_user.id)+ assert result is None+++async def test_delete_asset_cascades_values(session: AsyncSession, test_user: User):+ asset = Asset(+ id=uuid.uuid4(),+ user_id=test_user.id,+ name="Cascade Test",+ type="other",+ currency="BRL",+ valuation_method="manual",+ )+ session.add(asset)+ await session.flush()++ v = AssetValue(+ id=uuid.uuid4(),+ asset_id=asset.id,+ amount=Decimal("1000.00"),+ date=date.today(),+ source="manual",+ )+ session.add(v)+ await session.commit()++ deleted = await asset_service.delete_asset(session, asset.id, test_user.id)+ assert deleted is True+++async def test_add_asset_value(session: AsyncSession, test_user: User, test_asset: Asset):+ data = AssetValueCreate(amount=Decimal("600000.00"), date=date.today())+ result = await asset_service.add_asset_value(session, test_asset.id, test_user.id, data)+ assert result is not None+ assert result.amount == 600000.0+ assert result.source == "manual"+++async def test_add_asset_value_not_owned(session: AsyncSession, test_asset: Asset):+ other_user_id = uuid.uuid4()+ data = AssetValueCreate(amount=Decimal("100.00"), date=date.today())+ result = await asset_service.add_asset_value(session, test_asset.id, other_user_id, data)+ assert result is None+++async def test_get_asset_values(session: AsyncSession, test_user: User, test_asset_with_values: Asset):+ values = await asset_service.get_asset_values(session, test_asset_with_values.id, test_user.id)+ assert values is not None+ assert len(values) == 3+ # Should be ordered most recent first+ assert values[0].date >= values[1].date+++async def test_delete_asset_value(session: AsyncSession, test_user: User, test_asset: Asset):+ v = AssetValue(+ id=uuid.uuid4(),+ asset_id=test_asset.id,+ amount=Decimal("100.00"),+ date=date.today(),+ source="manual",+ )+ session.add(v)+ await session.commit()++ deleted = await asset_service.delete_asset_value(session, v.id, test_user.id)+ assert deleted is True+++async def test_get_asset_value_trend(session: AsyncSession, test_user: User, test_asset_with_values: Asset):+ trend = await asset_service.get_asset_value_trend(session, test_asset_with_values.id, test_user.id)+ assert trend is not None+ assert len(trend) == 3+ assert trend[0]["date"] <= trend[1]["date"] # ordered by date asc+++async def test_get_total_asset_value(session: AsyncSession, test_user: User, test_asset_with_values: Asset):+ totals = await asset_service.get_total_asset_value(session, test_user.id)+ assert "BRL" in totals+ assert totals["BRL"] >= 550000.0 # latest value+++async def test_total_asset_value_excludes_sold(session: AsyncSession, test_user: User):+ """Sold assets should not count in total."""+ asset = Asset(+ id=uuid.uuid4(),+ user_id=test_user.id,+ name="Sold Item",+ type="vehicle",+ currency="BRL",+ valuation_method="manual",+ sell_date=date.today(),+ sell_price=Decimal("20000.00"),+ )+ session.add(asset)+ await session.flush()+ v = AssetValue(+ id=uuid.uuid4(),+ asset_id=asset.id,+ amount=Decimal("20000.00"),+ date=date.today(),+ source="manual",+ )+ session.add(v)+ await session.commit()++ totals = await asset_service.get_total_asset_value(session, test_user.id)+ assert isinstance(totals, dict)+++async def test_growth_rule_task(session: AsyncSession, test_user: User):+ """Test growth rule application logic directly."""+ asset = Asset(+ id=uuid.uuid4(),+ user_id=test_user.id,+ name="Growth Test",+ type="investment",+ currency="BRL",+ valuation_method="growth_rule",+ growth_type="percentage",+ growth_rate=Decimal("10.0"),+ growth_frequency="daily",+ growth_start_date=date.today() - timedelta(days=30),+ )+ session.add(asset)+ await session.flush()++ v = AssetValue(+ id=uuid.uuid4(),+ asset_id=asset.id,+ amount=Decimal("1000.00"),+ date=date.today() - timedelta(days=2),+ source="manual",+ )+ session.add(v)+ await session.commit()++ from app.tasks.asset_tasks import _next_due_date+ next_due = _next_due_date(v.date, "daily")+ assert next_due <= date.today()+++# ---------------------------------------------------------------------------+# Current value fallback tests+# ---------------------------------------------------------------------------++async def test_current_value_falls_back_to_purchase_price(session: AsyncSession, test_user: User):+ """When no AssetValue rows exist, current_value should equal purchase_price."""+ data = AssetCreate(+ name="New Car", type="vehicle", currency="BRL",+ purchase_price=Decimal("80000.00"),+ purchase_date=date(2025, 6, 1),+ )+ result = await asset_service.create_asset(session, test_user.id, data)+ assert result.current_value == 80000.0+ assert result.gain_loss == 0.0+ assert result.value_count == 0+++async def test_current_value_none_when_no_price_no_values(session: AsyncSession, test_user: User):+ """When no purchase_price and no AssetValue, current_value should be None."""+ data = AssetCreate(name="Empty Asset", type="other", currency="BRL")+ result = await asset_service.create_asset(session, test_user.id, data)+ assert result.current_value is None+ assert result.gain_loss is None+++async def test_current_value_prefers_latest_value_over_purchase(session: AsyncSession, test_user: User):+ """When AssetValue rows exist, current_value should use the latest one, not purchase_price."""+ data = AssetCreate(+ name="Appreciated Watch", type="valuable", currency="BRL",+ purchase_price=Decimal("5000.00"),+ current_value=Decimal("7500.00"),+ )+ result = await asset_service.create_asset(session, test_user.id, data)+ assert result.current_value == 7500.0+ assert result.gain_loss == 2500.0+++# ---------------------------------------------------------------------------+# Growth rule creation backfill tests+# ---------------------------------------------------------------------------++async def test_growth_rule_backfills_values_on_create(session: AsyncSession, test_user: User):+ """Creating a growth_rule asset starting in the past should generate all intermediate values."""+ start = date.today() - timedelta(days=90)+ data = AssetCreate(+ name="Backfill Fund", type="investment", currency="BRL",+ valuation_method="growth_rule",+ purchase_price=Decimal("10000.00"),+ purchase_date=start,+ growth_type="percentage",+ growth_rate=Decimal("5.0"), # 5% per month+ growth_frequency="monthly",+ growth_start_date=start,+ )+ result = await asset_service.create_asset(session, test_user.id, data)++ # Should have the seed value + at least 2 monthly rule values (90 days ~ 3 months)+ assert result.value_count >= 3+ # Current value should be greater than purchase price after compounding+ assert result.current_value is not None+ assert result.current_value > 10000.0+++async def test_growth_rule_percentage_backfill_math(session: AsyncSession, test_user: User):+ """Verify the exact math for percentage growth backfill."""+ # Start exactly 3 months ago on the 1st+ today = date.today()+ start = date(today.year if today.month > 3 else today.year - 1,+ today.month - 3 if today.month > 3 else today.month + 9, 1)+ data = AssetCreate(+ name="Math Check", type="investment", currency="BRL",+ valuation_method="growth_rule",+ purchase_price=Decimal("1000.00"),+ purchase_date=start,+ growth_type="percentage",+ growth_rate=Decimal("10.0"), # 10% per month+ growth_frequency="monthly",+ growth_start_date=start,+ )+ result = await asset_service.create_asset(session, test_user.id, data)++ # 1000 * 1.1 * 1.1 * 1.1 = 1331.0+ assert result.current_value is not None+ assert abs(result.current_value - 1331.0) < 0.01++ # Should have seed + 3 rule values = 4 total+ assert result.value_count == 4+++async def test_growth_rule_absolute_backfill(session: AsyncSession, test_user: User):+ """Verify absolute growth type adds a fixed amount each period."""+ today = date.today()+ start = date(today.year if today.month > 3 else today.year - 1,+ today.month - 3 if today.month > 3 else today.month + 9, 1)+ data = AssetCreate(+ name="Absolute Growth", type="other", currency="BRL",+ valuation_method="growth_rule",+ purchase_price=Decimal("5000.00"),+ purchase_date=start,+ growth_type="absolute",+ growth_rate=Decimal("500.00"), # +500 per month+ growth_frequency="monthly",+ growth_start_date=start,+ )+ result = await asset_service.create_asset(session, test_user.id, data)++ # 5000 + 500 + 500 + 500 = 6500+ assert result.current_value is not None+ assert abs(result.current_value - 6500.0) < 0.01+ assert result.value_count == 4+++async def test_growth_rule_future_start_no_backfill(session: AsyncSession, test_user: User):+ """If growth_start_date is in the future, no rule values should be generated."""+ future = date.today() + timedelta(days=30)+ data = AssetCreate(+ name="Future Fund", type="investment", currency="BRL",+ valuation_method="growth_rule",+ purchase_price=Decimal("10000.00"),+ purchase_date=date.today(),+ growth_type="percentage",+ growth_rate=Decimal("5.0"),+ growth_frequency="monthly",+ growth_start_date=future,+ )+ result = await asset_service.create_asset(session, test_user.id, data)++ # Only the seed value, no rule-generated values+ assert result.value_count == 1+ assert result.current_value == 10000.0+++async def test_growth_rule_daily_backfill(session: AsyncSession, test_user: User):+ """Daily growth rule should generate one value per day."""+ start = date.today() - timedelta(days=5)+ data = AssetCreate(+ name="Daily Growth", type="investment", currency="BRL",+ valuation_method="growth_rule",+ purchase_price=Decimal("1000.00"),+ purchase_date=start,+ growth_type="percentage",+ growth_rate=Decimal("1.0"), # 1% per day+ growth_frequency="daily",+ growth_start_date=start,+ )+ result = await asset_service.create_asset(session, test_user.id, data)++ # seed + 5 daily values = 6+ assert result.value_count == 6+ # 1000 * 1.01^5 ≈ 1051.01+ assert result.current_value is not None+ assert abs(result.current_value - 1051.01) < 0.1+++async def test_growth_rule_weekly_backfill(session: AsyncSession, test_user: User):+ """Weekly growth rule should generate one value per week."""+ start = date.today() - timedelta(weeks=3)+ data = AssetCreate(+ name="Weekly Growth", type="investment", currency="BRL",+ valuation_method="growth_rule",+ purchase_price=Decimal("2000.00"),+ purchase_date=start,+ growth_type="absolute",+ growth_rate=Decimal("100.00"), # +100 per week+ growth_frequency="weekly",+ growth_start_date=start,+ )+ result = await asset_service.create_asset(session, test_user.id, data)++ # seed + 3 weekly values = 4+ assert result.value_count == 4+ # 2000 + 300 = 2300+ assert result.current_value is not None+ assert abs(result.current_value - 2300.0) < 0.01+++# ---------------------------------------------------------------------------+# Gain/loss computation tests+# ---------------------------------------------------------------------------++async def test_gain_loss_positive(session: AsyncSession, test_user: User):+ """Gain/loss should be positive when current value exceeds purchase price."""+ data = AssetCreate(+ name="Gainer", type="valuable", currency="BRL",+ purchase_price=Decimal("1000.00"),+ current_value=Decimal("1500.00"),+ )+ result = await asset_service.create_asset(session, test_user.id, data)+ assert result.gain_loss == 500.0+++async def test_gain_loss_negative(session: AsyncSession, test_user: User):+ """Gain/loss should be negative when current value is below purchase price."""+ data = AssetCreate(+ name="Loser", type="vehicle", currency="BRL",+ purchase_price=Decimal("20000.00"),+ current_value=Decimal("15000.00"),+ )+ result = await asset_service.create_asset(session, test_user.id, data)+ assert result.gain_loss == -5000.0+++async def test_gain_loss_zero_at_purchase_fallback(session: AsyncSession, test_user: User):+ """When falling back to purchase_price (no values), gain/loss should be 0."""+ data = AssetCreate(+ name="No Values", type="other", currency="BRL",+ purchase_price=Decimal("3000.00"),+ )+ result = await asset_service.create_asset(session, test_user.id, data)+ assert result.current_value == 3000.0+ assert result.gain_loss == 0.0+++async def test_gain_loss_none_without_purchase_price(session: AsyncSession, test_user: User):+ """Without a purchase_price, gain_loss should be None even if there's a current value."""+ data = AssetCreate(+ name="No Purchase", type="other", currency="BRL",+ current_value=Decimal("5000.00"),+ )+ result = await asset_service.create_asset(session, test_user.id, data)+ assert result.current_value == 5000.0+ assert result.gain_loss is None+++# ---------------------------------------------------------------------------+# Total asset value edge cases+# ---------------------------------------------------------------------------++async def test_total_asset_value_includes_purchase_fallback(session: AsyncSession, test_user: User):+ """Assets with only purchase_price (no values) should be included in totals."""+ asset = Asset(+ id=uuid.uuid4(),+ user_id=test_user.id,+ name="Fallback Total",+ type="real_estate",+ currency="BRL",+ valuation_method="manual",+ purchase_price=Decimal("200000.00"),+ )+ session.add(asset)+ await session.commit()++ totals = await asset_service.get_total_asset_value(session, test_user.id)+ assert "BRL" in totals+ assert totals["BRL"] >= 200000.0+++async def test_total_asset_value_excludes_archived(session: AsyncSession, test_user: User):+ """Archived assets should not count in total."""+ asset = Asset(+ id=uuid.uuid4(),+ user_id=test_user.id,+ name="Archived Total",+ type="other",+ currency="BRL",+ valuation_method="manual",+ purchase_price=Decimal("999999.00"),+ is_archived=True,+ )+ session.add(asset)+ await session.commit()++ totals = await asset_service.get_total_asset_value(session, test_user.id)+ # If this is the only asset, BRL should not be in totals (or should not include 999999)+ assert totals.get("BRL", 0) < 999999.0+++# ---------------------------------------------------------------------------+# Helper function tests+# ---------------------------------------------------------------------------++def test_next_due_date_daily():+ from app.services.asset_service import _next_due_date+ assert _next_due_date(date(2025, 3, 10), "daily") == date(2025, 3, 11)+++def test_next_due_date_weekly():+ from app.services.asset_service import _next_due_date+ assert _next_due_date(date(2025, 3, 10), "weekly") == date(2025, 3, 17)+++def test_next_due_date_monthly():+ from app.services.asset_service import _next_due_date+ assert _next_due_date(date(2025, 1, 15), "monthly") == date(2025, 2, 15)+++def test_next_due_date_monthly_year_rollover():+ from app.services.asset_service import _next_due_date+ assert _next_due_date(date(2025, 12, 10), "monthly") == date(2026, 1, 10)+++def test_next_due_date_monthly_clamps_day():+ """Day 31 should clamp to 28 for safety."""+ from app.services.asset_service import _next_due_date+ result = _next_due_date(date(2025, 1, 31), "monthly")+ assert result == date(2025, 2, 28)+++def test_next_due_date_yearly():+ from app.services.asset_service import _next_due_date+ assert _next_due_date(date(2025, 6, 15), "yearly") == date(2026, 6, 15)+++def test_generate_growth_values_empty_when_future():+ """No values generated when start date is in the future."""+ from app.services.asset_service import _generate_growth_values+ future = date.today() + timedelta(days=30)+ result = _generate_growth_values(+ asset_id=uuid.uuid4(), base_amount=1000.0, base_date=future,+ growth_type="percentage", growth_rate=5.0, growth_frequency="monthly",+ growth_start_date=future,+ )+ assert result == []+++def test_generate_growth_values_percentage():+ """Verify percentage growth generates correct values."""+ from app.services.asset_service import _generate_growth_values+ start = date.today() - timedelta(days=15)+ result = _generate_growth_values(+ asset_id=uuid.uuid4(), base_amount=1000.0, base_date=start,+ growth_type="percentage", growth_rate=1.0, growth_frequency="daily",+ growth_start_date=start,+ )+ # Should have ~15 daily values+ assert len(result) >= 14+ # Each value should be larger than the previous+ for i in range(1, len(result)):+ assert float(result[i].amount) > float(result[i - 1].amount)+ # All should have source="rule"+ assert all(v.source == "rule" for v in result)+++def test_generate_growth_values_absolute():+ """Verify absolute growth adds fixed amount."""+ from app.services.asset_service import _generate_growth_values+ start = date.today() - timedelta(days=7)+ result = _generate_growth_values(+ asset_id=uuid.uuid4(), base_amount=1000.0, base_date=start,+ growth_type="absolute", growth_rate=100.0, growth_frequency="daily",+ growth_start_date=start,+ )+ assert len(result) >= 6+ # First generated value: 1000 + 100 = 1100+ assert abs(float(result[0].amount) - 1100.0) < 0.01diff --git a/backend/tests/test_assets_api.py b/backend/tests/test_assets_api.pynew file mode 100644index 00000000..90cfd002--- /dev/null+++ b/backend/tests/test_assets_api.py@@ -0,0 +1,165 @@+import uuid+from datetime import date+from decimal import Decimal++import pytest+import pytest_asyncio+from httpx import AsyncClient+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.asset import Asset+from app.models.asset_value import AssetValue+from app.models.user import User+++@pytest_asyncio.fixture+async def test_asset_api(session: AsyncSession, test_user: User) -> Asset:+ """Create a test asset for API tests."""+ asset = Asset(+ id=uuid.uuid4(),+ user_id=test_user.id,+ name="API Test House",+ type="real_estate",+ currency="BRL",+ valuation_method="manual",+ purchase_price=Decimal("300000.00"),+ purchase_date=date(2025, 1, 1),+ position=0,+ )+ session.add(asset)+ await session.flush()++ v = AssetValue(+ id=uuid.uuid4(),+ asset_id=asset.id,+ amount=Decimal("350000.00"),+ date=date(2026, 1, 1),+ source="manual",+ )+ session.add(v)+ await session.commit()+ await session.refresh(asset)+ return asset+++async def test_list_assets(client: AsyncClient, auth_headers: dict, test_asset_api: Asset):+ response = await client.get("/api/assets", headers=auth_headers)+ assert response.status_code == 200+ data = response.json()+ assert isinstance(data, list)+ assert any(a["name"] == "API Test House" for a in data)+++async def test_get_asset(client: AsyncClient, auth_headers: dict, test_asset_api: Asset):+ response = await client.get(f"/api/assets/{test_asset_api.id}", headers=auth_headers)+ assert response.status_code == 200+ data = response.json()+ assert data["name"] == "API Test House"+ assert data["current_value"] == 350000.0+ assert data["gain_loss"] == 50000.0+++async def test_get_asset_not_found(client: AsyncClient, auth_headers: dict):+ response = await client.get(f"/api/assets/{uuid.uuid4()}", headers=auth_headers)+ assert response.status_code == 404+++async def test_create_asset(client: AsyncClient, auth_headers: dict):+ response = await client.post("/api/assets", headers=auth_headers, json={+ "name": "New Car",+ "type": "vehicle",+ "currency": "BRL",+ "current_value": 80000,+ "purchase_price": 75000,+ })+ assert response.status_code == 201+ data = response.json()+ assert data["name"] == "New Car"+ assert data["current_value"] == 80000.0+ assert data["value_count"] == 1+++async def test_update_asset(client: AsyncClient, auth_headers: dict, test_asset_api: Asset):+ response = await client.patch(+ f"/api/assets/{test_asset_api.id}",+ headers=auth_headers,+ json={"name": "Updated House"},+ )+ assert response.status_code == 200+ assert response.json()["name"] == "Updated House"+++async def test_delete_asset(client: AsyncClient, auth_headers: dict, session: AsyncSession, test_user: User):+ asset = Asset(+ id=uuid.uuid4(),+ user_id=test_user.id,+ name="To Delete API",+ type="other",+ currency="BRL",+ valuation_method="manual",+ )+ session.add(asset)+ await session.commit()++ response = await client.delete(f"/api/assets/{asset.id}", headers=auth_headers)+ assert response.status_code == 204+++async def test_list_asset_values(client: AsyncClient, auth_headers: dict, test_asset_api: Asset):+ response = await client.get(f"/api/assets/{test_asset_api.id}/values", headers=auth_headers)+ assert response.status_code == 200+ data = response.json()+ assert isinstance(data, list)+ assert len(data) >= 1+++async def test_add_asset_value(client: AsyncClient, auth_headers: dict, test_asset_api: Asset):+ response = await client.post(+ f"/api/assets/{test_asset_api.id}/values",+ headers=auth_headers,+ json={"amount": 400000, "date": "2026-03-01"},+ )+ assert response.status_code == 201+ data = response.json()+ assert data["amount"] == 400000.0+ assert data["source"] == "manual"+++async def test_delete_asset_value(+ client: AsyncClient, auth_headers: dict, session: AsyncSession, test_asset_api: Asset,+):+ v = AssetValue(+ id=uuid.uuid4(),+ asset_id=test_asset_api.id,+ amount=Decimal("999.00"),+ date=date.today(),+ source="manual",+ )+ session.add(v)+ await session.commit()++ response = await client.delete(f"/api/assets/values/{v.id}", headers=auth_headers)+ assert response.status_code == 204+++async def test_get_value_trend(client: AsyncClient, auth_headers: dict, test_asset_api: Asset):+ response = await client.get(f"/api/assets/{test_asset_api.id}/value-trend", headers=auth_headers)+ assert response.status_code == 200+ data = response.json()+ assert isinstance(data, list)+++async def test_unauthenticated_access(client: AsyncClient):+ response = await client.get("/api/assets")+ assert response.status_code == 401diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex fc1470ec..d087aeba 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -19,6 +19,7 @@ const RulesPage = lazy(() => import('@/pages/rules'))const CategoriesPage = lazy(() => import('@/pages/categories'))const BudgetsPage = lazy(() => import('@/pages/budgets'))const RecurringPage = lazy(() => import('@/pages/recurring'))+const AssetsPage = lazy(() => import('@/pages/assets'))const queryClient = new QueryClient({defaultOptions: {@@ -64,6 +65,7 @@ function App() {<Route path="/categories" element={<CategoriesPage />} /><Route path="/budgets" element={<BudgetsPage />} /><Route path="/recurring" element={<RecurringPage />} />+ <Route path="/assets" element={<AssetsPage />} /></Route></Routes></Suspense>diff --git a/frontend/src/components/app-layout.tsx b/frontend/src/components/app-layout.tsxindex 19f32398..e35de8dd 100644--- a/frontend/src/components/app-layout.tsx+++ b/frontend/src/components/app-layout.tsx@@ -31,6 +31,7 @@ import {Eye,EyeOff,Repeat,+ Landmark,Sun,Moon,} from 'lucide-react'@@ -42,6 +43,7 @@ const navItems = [{ key: 'accounts', path: '/accounts', icon: Building2 },{ key: 'categories', path: '/categories', icon: Tag },{ key: 'budgets', path: '/budgets', icon: PiggyBank },+ { key: 'assets', path: '/assets', icon: Landmark },{ key: 'recurring', path: '/recurring', icon: Repeat },{ key: 'rules', path: '/rules', icon: SlidersHorizontal },{ key: 'import', path: '/import', icon: Upload },diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 83cce334..78c753c6 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -14,6 +14,8 @@ import type {BudgetVsActual,Rule,ImportLog,+ Asset,+ AssetValue,DashboardSummary,SpendingByCategory,MonthlyTrend,@@ -380,6 +382,50 @@ export const dashboard = {},}+// Assets+export const assets = {+ list: async (includeArchived = false): Promise<Asset[]> => {+ const { data } = await api.get('/assets', { params: { include_archived: includeArchived } })+ return data+ },+ get: async (id: string): Promise<Asset> => {+ const { data } = await api.get(`/assets/${id}`)+ return data+ },+ create: async (asset: Partial<Asset> & { name: string; type: string; current_value?: number }): Promise<Asset> => {+ const { data } = await api.post('/assets', asset)+ return data+ },+ update: async (id: string, asset: Partial<Asset>, opts?: { regenerateGrowth?: boolean }): Promise<Asset> => {+ const { data } = await api.patch(`/assets/${id}`, asset, {+ params: opts?.regenerateGrowth ? { regenerate_growth: true } : undefined,+ })+ return data+ },+ delete: async (id: string): Promise<void> => {+ await api.delete(`/assets/${id}`)+ },+ values: async (id: string): Promise<AssetValue[]> => {+ const { data } = await api.get(`/assets/${id}/values`)+ return data+ },+ valueTrend: async (id: string, months = 12): Promise<{ date: string; amount: number }[]> => {+ const { data } = await api.get(`/assets/${id}/value-trend`, { params: { months } })+ return data+ },+ addValue: async (id: string, value: { amount: number; date: string }): Promise<AssetValue> => {+ const { data } = await api.post(`/assets/${id}/values`, value)+ return data+ },+ 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 }> => {+ const { data } = await api.get('/assets/portfolio-trend')+ return data+ },+}+// Import Logsexport const importLogs = {list: async (): Promise<ImportLog[]> => {diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.jsonindex 83c8a6c2..a026bfac 100644--- a/frontend/src/locales/en.json+++ b/frontend/src/locales/en.json@@ -11,7 +11,8 @@"categories": "Categories","budgets": "Budgets","settings": "Settings",- "recurring": "Recurring"+ "recurring": "Recurring",+ "assets": "Assets"},"auth": {"login": "Login",@@ -63,7 +64,8 @@"uncategorizedTotal": "{{amount}} in total","categorizeNow": "Categorize now","allCategorized": "All caught up!",- "allCategorizedDesc": "All transactions are categorized"+ "allCategorizedDesc": "All transactions are categorized",+ "assetsValue": "Assets"},"transactions": {"title": "Transactions",@@ -354,6 +356,65 @@"importError": "Error importing transactions","previewInfo": "{{count}} transactions · format {{format}}"},+ "assets": {+ "title": "Assets",+ "addAsset": "Add Asset",+ "editAsset": "Edit Asset",+ "name": "Name",+ "type": "Type",+ "currency": "Currency",+ "typeRealEstate": "Real Estate",+ "typeVehicle": "Vehicle",+ "typeValuable": "Valuable",+ "typeInvestment": "Investment",+ "typeOther": "Other",+ "valuationMethod": "Valuation Method",+ "manual": "Manual",+ "growthRule": "Growth Rule",+ "purchaseDate": "Purchase Date",+ "purchasePrice": "Purchase Price",+ "sellDate": "Sell Date",+ "sellPrice": "Sell Price",+ "currentValue": "Current Value",+ "gainLoss": "Gain/Loss",+ "growthType": "Growth Type",+ "growthRate": "Growth Rate",+ "growthFrequency": "Growth Frequency",+ "growthStartDate": "Growth Start Date",+ "percentage": "Percentage",+ "absolute": "Absolute",+ "daily": "Daily",+ "weekly": "Weekly",+ "monthly": "Monthly",+ "yearly": "Yearly",+ "activeAssets": "Active Assets",+ "soldAssets": "Sold Assets",+ "archivedAssets": "Archived Assets",+ "noAssets": "No assets yet",+ "created": "Asset created",+ "updated": "Asset updated",+ "deleted": "Asset deleted",+ "confirmDelete": "Are you sure you want to delete this asset and all its value history?",+ "confirmDeleteTitle": "Delete asset?",+ "addValue": "Add Value",+ "valueHistory": "Value History",+ "valueTrend": "Value Trend",+ "amount": "Amount",+ "date": "Date",+ "source": "Source",+ "sourceManual": "Manual",+ "sourceRule": "Rule",+ "sourceSync": "Sync",+ "sourcePurchase": "Purchase",+ "valueAdded": "Value added",+ "valueDeleted": "Value deleted",+ "sold": "Sold",+ "portfolioValue": "Portfolio Value",+ "total": "Total",+ "confirmRegenerateTitle": "Regenerate values?",+ "confirmRegenerate": "Growth parameters changed. All automatically generated values will be deleted and recalculated. Manual values will be kept.",+ "regenerate": "Regenerate"+ },"common": {"save": "Save","cancel": "Cancel",diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.jsonindex 2d1a377e..fc376287 100644--- a/frontend/src/locales/pt-BR.json+++ b/frontend/src/locales/pt-BR.json@@ -11,7 +11,8 @@"categories": "Categorias","budgets": "Orçamentos","settings": "Configurações",- "recurring": "Recorrentes"+ "recurring": "Recorrentes",+ "assets": "Patrimônio"},"auth": {"login": "Entrar",@@ -63,7 +64,8 @@"uncategorizedTotal": "{{amount}} no total","categorizeNow": "Categorizar agora","allCategorized": "Tudo em dia!",- "allCategorizedDesc": "Todas as transações estão categorizadas"+ "allCategorizedDesc": "Todas as transações estão categorizadas",+ "assetsValue": "Patrimônio"},"transactions": {"title": "Transações",@@ -354,6 +356,65 @@"importError": "Erro ao importar transações","previewInfo": "{{count}} transações · formato {{format}}"},+ "assets": {+ "title": "Patrimônio",+ "addAsset": "Adicionar Ativo",+ "editAsset": "Editar Ativo",+ "name": "Nome",+ "type": "Tipo",+ "currency": "Moeda",+ "typeRealEstate": "Imóvel",+ "typeVehicle": "Veículo",+ "typeValuable": "Bem de Valor",+ "typeInvestment": "Investimento",+ "typeOther": "Outro",+ "valuationMethod": "Método de Valuação",+ "manual": "Manual",+ "growthRule": "Regra de Crescimento",+ "purchaseDate": "Data de Compra",+ "purchasePrice": "Preço de Compra",+ "sellDate": "Data de Venda",+ "sellPrice": "Preço de Venda",+ "currentValue": "Valor Atual",+ "gainLoss": "Ganho/Perda",+ "growthType": "Tipo de Crescimento",+ "growthRate": "Taxa de Crescimento",+ "growthFrequency": "Frequência de Crescimento",+ "growthStartDate": "Data de Início do Crescimento",+ "percentage": "Percentual",+ "absolute": "Absoluto",+ "daily": "Diário",+ "weekly": "Semanal",+ "monthly": "Mensal",+ "yearly": "Anual",+ "activeAssets": "Ativos",+ "soldAssets": "Vendidos",+ "archivedAssets": "Arquivados",+ "noAssets": "Nenhum ativo ainda",+ "created": "Ativo criado",+ "updated": "Ativo atualizado",+ "deleted": "Ativo excluído",+ "confirmDelete": "Tem certeza que deseja excluir este ativo e todo o histórico de valores?",+ "confirmDeleteTitle": "Excluir ativo?",+ "addValue": "Adicionar Valor",+ "valueHistory": "Histórico de Valores",+ "valueTrend": "Tendência de Valor",+ "amount": "Valor",+ "date": "Data",+ "source": "Origem",+ "sourceManual": "Manual",+ "sourceRule": "Regra",+ "sourceSync": "Sincronizado",+ "sourcePurchase": "Compra",+ "valueAdded": "Valor adicionado",+ "valueDeleted": "Valor excluído",+ "sold": "Vendido",+ "portfolioValue": "Valor do Patrimônio",+ "total": "Total",+ "confirmRegenerateTitle": "Regenerar valores?",+ "confirmRegenerate": "Os parâmetros de crescimento foram alterados. Todos os valores gerados automaticamente serão excluídos e recalculados. Valores manuais serão mantidos.",+ "regenerate": "Regenerar"+ },"common": {"save": "Salvar","cancel": "Cancelar",diff --git a/frontend/src/pages/assets.tsx b/frontend/src/pages/assets.tsxnew file mode 100644index 00000000..d93f12c5--- /dev/null+++ b/frontend/src/pages/assets.tsx@@ -0,0 +1,1008 @@+import { useState, useMemo } from 'react'+import { useTranslation } from 'react-i18next'+import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'+import { assets } from '@/lib/api'+import { toast } from 'sonner'+import { Button } from '@/components/ui/button'+import { Input } from '@/components/ui/input'+import { Label } from '@/components/ui/label'+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogFooter,+} from '@/components/ui/dialog'+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 {+ Home,+ Car,+ Gem,+ TrendingUp,+ Package,+ Plus,+ Pencil,+ Trash2,+ ChevronDown,+ ChevronUp,+} from 'lucide-react'+import {+ AreaChart,+ Area,+ XAxis,+ YAxis,+ Tooltip as RechartsTooltip,+ ResponsiveContainer,+ CartesianGrid,+} from 'recharts'+import { PageHeader } from '@/components/page-header'+import { usePrivacyMode } from '@/hooks/use-privacy-mode'+import { useAuth } from '@/contexts/auth-context'++function formatCurrency(value: number, currency = 'BRL', locale = 'pt-BR') {+ try {+ return new Intl.NumberFormat(locale, { style: 'currency', currency: currency || 'BRL' }).format(value)+ } catch {+ return new Intl.NumberFormat(locale, { style: 'currency', currency: 'BRL' }).format(value)+ }+}++const ASSET_TYPE_CONFIG: Record<string, { icon: React.ElementType; color: string; bg: string }> = {+ real_estate: { icon: Home, color: 'text-blue-600', bg: 'bg-blue-100' },+ vehicle: { icon: Car, color: 'text-violet-600', bg: 'bg-violet-100' },+ valuable: { icon: Gem, color: 'text-amber-600', bg: 'bg-amber-100' },+ investment: { icon: TrendingUp, color: 'text-emerald-600', bg: 'bg-emerald-100' },+ other: { icon: Package, color: 'text-slate-600', bg: 'bg-slate-100' },+}++function getTypeConfig(type: string) {+ return ASSET_TYPE_CONFIG[type] ?? ASSET_TYPE_CONFIG['other']+}++const ASSET_TYPES = ['real_estate', 'vehicle', 'valuable', 'investment', 'other'] as const+const VALUATION_METHODS = ['manual', 'growth_rule'] as const+const GROWTH_TYPES = ['percentage', 'absolute'] as const+const GROWTH_FREQUENCIES = ['daily', 'weekly', 'monthly', 'yearly'] as const++export default function AssetsPage() {+ const { t, i18n } = useTranslation()+ const locale = i18n.language === 'en' ? 'en-US' : i18n.language+ const { mask } = usePrivacyMode()+ const { user } = useAuth()+ const userCurrency = user?.preferences?.currency_display ?? 'BRL'+ const queryClient = useQueryClient()++ const [dialogOpen, setDialogOpen] = useState(false)+ const [editingAsset, setEditingAsset] = useState<Asset | null>(null)+ const [deletingId, setDeletingId] = useState<string | null>(null)+ const [pendingGrowthSave, setPendingGrowthSave] = useState<Record<string, unknown> | null>(null)+ const [expandedId, setExpandedId] = useState<string | null>(null)++ // Form state+ const [formName, setFormName] = useState('')+ const [formType, setFormType] = useState<string>('other')+ const [formCurrency, setFormCurrency] = useState(userCurrency)+ const [formMethod, setFormMethod] = useState<string>('manual')+ const [formPurchaseDate, setFormPurchaseDate] = useState<string>('')+ const [formPurchasePrice, setFormPurchasePrice] = useState('')+ const [formSellDate, setFormSellDate] = useState<string>('')+ const [formSellPrice, setFormSellPrice] = useState('')+ const [formCurrentValue, setFormCurrentValue] = useState('')+ const [formGrowthType, setFormGrowthType] = useState<string>('percentage')+ const [formGrowthRate, setFormGrowthRate] = useState('')+ const [formGrowthFrequency, setFormGrowthFrequency] = useState<string>('monthly')+ const [formGrowthStartDate, setFormGrowthStartDate] = useState<string>('')++ const { data: assetsList, isLoading } = useQuery({+ queryKey: ['assets'],+ queryFn: () => assets.list(true),+ })++ const { data: portfolioData } = useQuery({+ queryKey: ['portfolio-trend'],+ queryFn: () => assets.portfolioTrend(),+ })++ const createMutation = useMutation({+ mutationFn: (data: Parameters<typeof assets.create>[0]) => assets.create(data),+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: ['assets'] })+ queryClient.invalidateQueries({ queryKey: ['portfolio-trend'] })+ queryClient.invalidateQueries({ queryKey: ['dashboard'] })+ setDialogOpen(false)+ toast.success(t('assets.created'))+ },+ onError: () => toast.error(t('common.error')),+ })++ const updateMutation = useMutation({+ mutationFn: ({ id, _regenerateGrowth, ...data }: Partial<Asset> & { id: string; _regenerateGrowth?: boolean }) =>+ assets.update(id, data, { regenerateGrowth: _regenerateGrowth }),+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: ['assets'] })+ queryClient.invalidateQueries({ queryKey: ['portfolio-trend'] })+ queryClient.invalidateQueries({ queryKey: ['dashboard'] })+ setDialogOpen(false)+ setEditingAsset(null)+ toast.success(t('assets.updated'))+ },+ onError: () => toast.error(t('common.error')),+ })++ const deleteMutation = useMutation({+ mutationFn: (id: string) => assets.delete(id),+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: ['assets'] })+ queryClient.invalidateQueries({ queryKey: ['portfolio-trend'] })+ queryClient.invalidateQueries({ queryKey: ['dashboard'] })+ setDeletingId(null)+ if (expandedId === deletingId) setExpandedId(null)+ toast.success(t('assets.deleted'))+ },+ 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+ const baseAmount = parseFloat(formPurchasePrice)+ const rate = parseFloat(formGrowthRate)+ if (!baseAmount || !rate || !formGrowthFrequency) return null++ const startDate = formGrowthStartDate || formPurchaseDate+ if (!startDate) return null++ const today = new Date()+ today.setHours(0, 0, 0, 0)+ let current = baseAmount+ let d = new Date(startDate + 'T00:00:00')++ let iterations = 0+ while (iterations < 10000) {+ const next = new Date(d)+ if (formGrowthFrequency === 'daily') next.setDate(next.getDate() + 1)+ else if (formGrowthFrequency === 'weekly') next.setDate(next.getDate() + 7)+ else if (formGrowthFrequency === 'monthly') next.setMonth(next.getMonth() + 1)+ else if (formGrowthFrequency === 'yearly') next.setFullYear(next.getFullYear() + 1)+ else break+ if (next > today) break+ if (formGrowthType === 'percentage') {+ current = current * (1 + rate / 100)+ } else {+ current = current + rate+ }+ d = next+ iterations+++ }+ return Math.round(current * 100) / 100+ }, [formMethod, formPurchasePrice, formGrowthRate, formGrowthType, formGrowthFrequency, formGrowthStartDate, formPurchaseDate])++ const activeAssets = assetsList?.filter(a => !a.sell_date && !a.is_archived) ?? []+ const soldAssets = assetsList?.filter(a => a.sell_date) ?? []++ function openCreate() {+ setEditingAsset(null)+ setFormName('')+ setFormType('other')+ setFormCurrency(userCurrency)+ setFormMethod('manual')+ setFormPurchaseDate('')+ setFormPurchasePrice('')+ setFormSellDate('')+ setFormSellPrice('')+ setFormCurrentValue('')+ setFormGrowthType('percentage')+ setFormGrowthRate('')+ setFormGrowthFrequency('monthly')+ setFormGrowthStartDate('')+ setDialogOpen(true)+ }++ function openEdit(asset: Asset) {+ setEditingAsset(asset)+ setFormName(asset.name)+ setFormType(asset.type)+ setFormCurrency(asset.currency)+ setFormMethod(asset.valuation_method)+ setFormPurchaseDate(asset.purchase_date ?? '')+ setFormPurchasePrice(asset.purchase_price?.toString() ?? '')+ setFormSellDate(asset.sell_date ?? '')+ setFormSellPrice(asset.sell_price?.toString() ?? '')+ setFormCurrentValue('')+ setFormGrowthType(asset.growth_type ?? 'percentage')+ setFormGrowthRate(asset.growth_rate?.toString() ?? '')+ setFormGrowthFrequency(asset.growth_frequency ?? 'monthly')+ setFormGrowthStartDate(asset.growth_start_date ?? '')+ setDialogOpen(true)+ }++ function buildPayload() {+ const payload: Record<string, unknown> = {+ name: formName,+ type: formType,+ currency: formCurrency,+ valuation_method: formMethod,+ purchase_date: formPurchaseDate || null,+ purchase_price: formPurchasePrice ? parseFloat(formPurchasePrice) : null,+ sell_date: formSellDate || null,+ sell_price: formSellPrice ? parseFloat(formSellPrice) : null,+ }++ if (formMethod === 'growth_rule') {+ payload.growth_type = formGrowthType+ payload.growth_rate = formGrowthRate ? parseFloat(formGrowthRate) : null+ payload.growth_frequency = formGrowthFrequency+ payload.growth_start_date = formGrowthStartDate || null+ }++ if (!editingAsset && formCurrentValue) {+ payload.current_value = parseFloat(formCurrentValue)+ }++ return payload+ }++ function hasGrowthParamsChanged(): boolean {+ if (!editingAsset || editingAsset.valuation_method !== 'growth_rule') return false+ return (+ formGrowthType !== (editingAsset.growth_type ?? 'percentage') ||+ formGrowthRate !== (editingAsset.growth_rate?.toString() ?? '') ||+ formGrowthFrequency !== (editingAsset.growth_frequency ?? 'monthly') ||+ formGrowthStartDate !== (editingAsset.growth_start_date ?? '') ||+ formPurchasePrice !== (editingAsset.purchase_price?.toString() ?? '') ||+ formPurchaseDate !== (editingAsset.purchase_date ?? '')+ )+ }++ function handleSave() {+ const payload = buildPayload()++ if (editingAsset) {+ // If growth params changed, ask confirmation before regenerating+ if (hasGrowthParamsChanged() && editingAsset.value_count > 0) {+ setPendingGrowthSave(payload)+ return+ }+ updateMutation.mutate({ id: editingAsset.id, ...payload } as Partial<Asset> & { id: string })+ } else {+ createMutation.mutate(payload as Parameters<typeof assets.create>[0])+ }+ }++ function confirmRegenerateGrowth() {+ if (!editingAsset || !pendingGrowthSave) return+ updateMutation.mutate(+ { id: editingAsset.id, ...pendingGrowthSave, _regenerateGrowth: true } as Partial<Asset> & { id: string },+ )+ setPendingGrowthSave(null)+ }++ function renderAssetCard(asset: Asset) {+ const config = getTypeConfig(asset.type)+ const Icon = config.icon+ const isExpanded = expandedId === asset.id++ return (+ <div key={asset.id} className="border border-border rounded-xl bg-card shadow-sm overflow-hidden">+ <div+ className="flex items-center gap-4 px-5 py-4 cursor-pointer hover:bg-muted/30 transition-colors"+ onClick={() => setExpandedId(isExpanded ? null : asset.id)}+ >+ <div className={`w-10 h-10 rounded-lg flex items-center justify-center ${config.bg}`}>+ <Icon size={20} className={config.color} />+ </div>+ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-2">+ <span className="text-sm font-semibold text-foreground truncate">{asset.name}</span>+ <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>+ {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)}+ /{t(`assets.${asset.growth_frequency}`).toLowerCase().charAt(0)}+ </Badge>+ )}+ {asset.sell_date && (+ <Badge variant="outline" className="text-[10px] px-1.5 py-0 text-rose-600 border-rose-200">+ {t('assets.sold')}+ </Badge>+ )}+ </div>+ </div>+ <div className="text-right shrink-0">+ {asset.current_value != null ? (+ <>+ <p className="text-sm font-bold tabular-nums text-foreground">+ {mask(formatCurrency(asset.current_value, asset.currency, locale))}+ </p>+ {asset.gain_loss != null && (+ <p className={`text-xs font-medium tabular-nums ${asset.gain_loss >= 0 ? 'text-emerald-600' : 'text-rose-500'}`}>+ {mask(`${asset.gain_loss >= 0 ? '+' : ''}${formatCurrency(asset.gain_loss, asset.currency, locale)}`)}+ </p>+ )}+ </>+ ) : (+ <p className="text-sm text-muted-foreground">—</p>+ )}+ </div>+ <div className="flex items-center gap-1 shrink-0">+ <button+ onClick={(e) => { e.stopPropagation(); openEdit(asset) }}+ className="p-1.5 rounded-lg text-muted-foreground hover:text-foreground hover:bg-muted transition-colors"+ >+ <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"+ >+ <Trash2 size={14} />+ </button>+ {isExpanded ? <ChevronUp size={16} className="text-muted-foreground" /> : <ChevronDown size={16} className="text-muted-foreground" />}+ </div>+ </div>++ {isExpanded && <AssetDetail assetId={asset.id} currency={asset.currency} locale={locale} purchasePrice={asset.purchase_price} purchaseDate={asset.purchase_date} valuationMethod={asset.valuation_method} />}+ </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>+ }+ />++ {/* Portfolio Stacked Area Chart */}+ {portfolioData && portfolioData.trend.length > 1 && (+ <PortfolioChart+ data={portfolioData}+ currency={userCurrency}+ locale={locale}+ mask={mask}+ />+ )}++ {isLoading ? (+ <div className="space-y-3">+ {Array.from({ length: 3 }).map((_, i) => <Skeleton key={i} className="h-16 rounded-xl" />)}+ </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>+ </div>+ )}++ {/* Sold Assets */}+ {soldAssets.length > 0 && (+ <div className="space-y-2">+ <h3 className="text-xs font-semibold text-muted-foreground uppercase tracking-wider px-1">+ {t('assets.soldAssets')}+ </h3>+ <div className="space-y-2">+ {soldAssets.map(renderAssetCard)}+ </div>+ </div>+ )}++ {activeAssets.length === 0 && soldAssets.length === 0 && (+ <div className="text-center py-16">+ <Package className="mx-auto h-12 w-12 text-muted-foreground/40 mb-3" />+ <p className="text-muted-foreground">{t('assets.noAssets')}</p>+ </div>+ )}+ </div>+ )}++ {/* Create/Edit Dialog */}+ <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>+ <DialogContent className="max-w-lg max-h-[90vh] overflow-y-auto">+ <DialogHeader>+ <DialogTitle>{editingAsset ? t('assets.editAsset') : t('assets.addAsset')}</DialogTitle>+ </DialogHeader>+ <div className="space-y-4">+ {/* Name */}+ <div className="space-y-2">+ <Label>{t('assets.name')}</Label>+ <Input value={formName} onChange={e => setFormName(e.target.value)} />+ </div>++ {/* Type + Currency */}+ <div className="grid grid-cols-2 gap-4">+ <div className="space-y-2">+ <Label>{t('assets.type')}</Label>+ <select+ className="flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm"+ value={formType}+ onChange={e => setFormType(e.target.value)}+ >+ {ASSET_TYPES.map(at => (+ <option key={at} value={at}>+ {t(`assets.type${at.replace(/_([a-z])/g, (_, c: string) => c.toUpperCase()).replace(/^./, c => c.toUpperCase())}`)}+ </option>+ ))}+ </select>+ </div>+ <div className="space-y-2">+ <Label>{t('assets.currency')}</Label>+ <select+ className="flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm"+ value={formCurrency}+ onChange={e => setFormCurrency(e.target.value)}+ >+ <option value={userCurrency}>{userCurrency} ({({ BRL: 'R$', USD: '$', EUR: '€', GBP: '£' } as Record<string, string>)[userCurrency] ?? userCurrency})</option>+ </select>+ </div>+ </div>++ {/* Valuation Method — locked on edit */}+ <div className="space-y-2">+ <Label>{t('assets.valuationMethod')}</Label>+ <div className="grid grid-cols-2 gap-2">+ {VALUATION_METHODS.map(m => (+ <button+ key={m}+ type="button"+ disabled={!!editingAsset}+ className={`px-3 py-2.5 rounded-lg text-sm font-medium border transition-all ${+ formMethod === m+ ? 'border-primary bg-primary/10 text-primary shadow-sm'+ : 'border-border text-muted-foreground hover:border-primary/50 hover:bg-muted/50'+ } ${editingAsset ? 'opacity-50 cursor-not-allowed' : ''}`}+ onClick={() => !editingAsset && setFormMethod(m)}+ >+ {t(`assets.${m === 'growth_rule' ? 'growthRule' : 'manual'}`)}+ </button>+ ))}+ </div>+ </div>++ {/* Growth Rule Settings */}+ {formMethod === 'growth_rule' && (+ <div className="space-y-3 p-3.5 rounded-xl border border-primary/20 bg-primary/5">+ <div className="grid grid-cols-2 gap-4">+ <div className="space-y-2">+ <Label>{t('assets.growthType')}</Label>+ <select+ className="flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm"+ value={formGrowthType}+ onChange={e => setFormGrowthType(e.target.value)}+ >+ {GROWTH_TYPES.map(gt => (+ <option key={gt} value={gt}>{t(`assets.${gt}`)}</option>+ ))}+ </select>+ </div>+ <div className="space-y-2">+ <Label>{t('assets.growthRate')}</Label>+ <div className="relative">+ <Input type="number" step="any" value={formGrowthRate} onChange={e => setFormGrowthRate(e.target.value)} className={formGrowthType === 'percentage' ? 'pr-8' : ''} />+ {formGrowthType === 'percentage' && (+ <span className="absolute right-3 top-1/2 -translate-y-1/2 text-sm text-muted-foreground pointer-events-none">%</span>+ )}+ </div>+ </div>+ </div>+ <div className="grid grid-cols-2 gap-4">+ <div className="space-y-2">+ <Label>{t('assets.growthFrequency')}</Label>+ <select+ className="flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm"+ value={formGrowthFrequency}+ onChange={e => setFormGrowthFrequency(e.target.value)}+ >+ {GROWTH_FREQUENCIES.map(gf => (+ <option key={gf} value={gf}>{t(`assets.${gf}`)}</option>+ ))}+ </select>+ </div>+ <div className="space-y-2">+ <Label>{t('assets.growthStartDate')}</Label>+ <DatePickerInput value={formGrowthStartDate} onChange={setFormGrowthStartDate} />+ </div>+ </div>+ </div>+ )}++ {/* Purchase Info */}+ <div className="grid grid-cols-2 gap-4">+ <div className="space-y-2">+ <Label>{t('assets.purchaseDate')}</Label>+ <DatePickerInput value={formPurchaseDate} onChange={setFormPurchaseDate} />+ </div>+ <div className="space-y-2">+ <Label>{t('assets.purchasePrice')}</Label>+ <Input type="number" step="0.01" value={formPurchasePrice} onChange={e => setFormPurchasePrice(e.target.value)} />+ </div>+ </div>++ {/* Sell Info */}+ <div className="grid grid-cols-2 gap-4">+ <div className="space-y-2">+ <Label>{t('assets.sellDate')}</Label>+ <DatePickerInput value={formSellDate} onChange={setFormSellDate} />+ </div>+ <div className="space-y-2">+ <Label>{t('assets.sellPrice')}</Label>+ <Input type="number" step="0.01" value={formSellPrice} onChange={e => setFormSellPrice(e.target.value)} />+ </div>+ </div>++ {/* Current Value — manual only */}+ {!editingAsset && formMethod === 'manual' && (+ <div className="space-y-2">+ <Label>{t('assets.currentValue')}</Label>+ <Input+ type="number"+ step="any"+ value={formCurrentValue}+ onChange={e => setFormCurrentValue(e.target.value)}+ />+ </div>+ )}++ {/* Projected Value — growth rule preview */}+ {formMethod === 'growth_rule' && projectedGrowthValue != null && (() => {+ const base = parseFloat(formPurchasePrice) || 0+ const isLoss = projectedGrowthValue < base+ const diff = projectedGrowthValue - base+ return (+ <div className={`flex items-center justify-between p-3.5 rounded-xl border ${isLoss ? 'bg-rose-50 dark:bg-rose-950/30 border-rose-200 dark:border-rose-800' : 'bg-emerald-50 dark:bg-emerald-950/30 border-emerald-200 dark:border-emerald-800'}`}>+ <div>+ <span className="text-xs font-medium text-muted-foreground">{t('assets.currentValue')}</span>+ {base > 0 && (+ <p className={`text-[11px] tabular-nums font-medium mt-0.5 ${isLoss ? 'text-rose-500' : 'text-emerald-600'}`}>+ {diff >= 0 ? '+' : ''}{formatCurrency(diff, formCurrency, locale)}+ </p>+ )}+ </div>+ <span className={`text-xl font-bold tabular-nums ${isLoss ? 'text-rose-600' : 'text-emerald-600'}`}>+ {formatCurrency(projectedGrowthValue, formCurrency, locale)}+ </span>+ </div>+ )+ })()}+ </div>+ <DialogFooter>+ <Button variant="outline" onClick={() => setDialogOpen(false)}>+ {t('common.cancel')}+ </Button>+ <Button+ onClick={handleSave}+ disabled={!formName || createMutation.isPending || updateMutation.isPending}+ >+ {t('common.save')}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>++ {/* Regenerate Growth Confirmation */}+ <Dialog open={!!pendingGrowthSave} onOpenChange={() => setPendingGrowthSave(null)}>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>{t('assets.confirmRegenerateTitle')}</DialogTitle>+ </DialogHeader>+ <p className="text-sm text-muted-foreground">{t('assets.confirmRegenerate')}</p>+ <DialogFooter>+ <Button variant="outline" onClick={() => setPendingGrowthSave(null)}>+ {t('common.cancel')}+ </Button>+ <Button+ onClick={confirmRegenerateGrowth}+ disabled={updateMutation.isPending}+ >+ {t('assets.regenerate')}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>++ {/* Delete Confirmation */}+ <Dialog open={!!deletingId} onOpenChange={() => setDeletingId(null)}>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>{t('assets.confirmDeleteTitle')}</DialogTitle>+ </DialogHeader>+ <p className="text-sm text-muted-foreground">{t('assets.confirmDelete')}</p>+ <DialogFooter>+ <Button variant="outline" onClick={() => setDeletingId(null)}>+ {t('common.cancel')}+ </Button>+ <Button+ variant="destructive"+ onClick={() => deletingId && deleteMutation.mutate(deletingId)}+ disabled={deleteMutation.isPending}+ >+ {t('common.delete')}+ </Button>+ </DialogFooter>+ </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 }+ currency: string+ locale: string+ mask: (v: string) => string+}) {+ const { t } = useTranslation()++ const formatCompact = (v: number) => {+ const abs = Math.abs(v)+ if (abs >= 1_000_000) return `${(v / 1_000_000).toFixed(1)}M`+ if (abs >= 1_000) return `${(v / 1_000).toFixed(abs >= 10_000 ? 0 : 1)}k`+ return v.toLocaleString(loc, { maximumFractionDigits: 0 })+ }++ 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="text-right">+ <span className="text-xs text-muted-foreground">{t('assets.total')}</span>+ <p className="text-lg font-bold tabular-nums text-foreground">+ {mask(formatCurrency(data.total, currency, loc))}+ </p>+ </div>+ </div>+ <div className="h-56">+ <ResponsiveContainer width="100%" height="100%">+ <AreaChart data={data.trend} 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} />+ </linearGradient>+ ))}+ </defs>+ <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="var(--border)" strokeOpacity={0.5} />+ <XAxis+ dataKey="date"+ tick={{ fontSize: 10, fill: 'var(--muted-foreground)' }}+ axisLine={false}+ tickLine={false}+ tickFormatter={(v: string) => new Date(v + 'T00:00:00').toLocaleDateString(loc, { month: 'short', year: '2-digit' })}+ />+ <YAxis+ tick={{ fontSize: 10, fill: 'var(--muted-foreground)' }}+ axisLine={false}+ tickLine={false}+ width={56}+ tickFormatter={(v: number) => mask(formatCompact(v))}+ />+ <RechartsTooltip+ content={({ active, payload, label }) => {+ 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] }+ })+ .filter(item => item.value !== 0)+ .sort((a, b) => Math.abs(b.value) - Math.abs(a.value))+ if (items.length === 0) return null+ return (+ <div style={{ background: 'var(--card)', color: 'var(--foreground)', border: '1px solid var(--border)', borderRadius: '0.75rem', fontSize: '12px', boxShadow: '0 4px 12px rgba(0,0,0,0.08)', padding: '10px 12px' }}>+ <p style={{ fontWeight: 600, marginBottom: 6 }}>+ {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 }}>+ <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}>+ <span style={{ width: 8, height: 8, borderRadius: '50%', backgroundColor: item.color, display: 'inline-block' }} />+ {item.name}+ </span>+ <span style={{ fontWeight: 500, fontVariantNumeric: 'tabular-nums' }}>{mask(formatCurrency(item.value, currency, loc))}</span>+ </div>+ ))}+ <div style={{ borderTop: '1px solid var(--border)', marginTop: 6, paddingTop: 6, display: 'flex', justifyContent: 'space-between', fontWeight: 700 }}>+ <span>{t('assets.total')}</span>+ <span style={{ fontVariantNumeric: 'tabular-nums' }}>{mask(formatCurrency(dateTotal, currency, loc))}</span>+ </div>+ </div>+ )+ }}+ />+ {/* Stacked areas — each asset is a colored band */}+ {data.assets.map((asset, i) => (+ <Area+ key={asset.id}+ type="monotone"+ dataKey={asset.id}+ stackId="portfolio"+ stroke={PORTFOLIO_COLORS[i % PORTFOLIO_COLORS.length]}+ strokeWidth={1}+ fill={`url(#portfolio-grad-${asset.id})`}+ dot={false}+ activeDot={{ r: 3, strokeWidth: 1.5, fill: 'var(--card)' }}+ />+ ))}+ {/* Hidden total for tooltip */}+ <Area dataKey="_total" stroke="none" fill="none" dot={false} activeDot={false} />+ </AreaChart>+ </ResponsiveContainer>+ </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>+ </div>+ ))}+ </div>+ </div>+ )+}++function AssetDetail({ assetId, currency, locale: loc, purchasePrice, purchaseDate, valuationMethod }: {+ assetId: string; currency: string; locale: string+ purchasePrice: number | null; purchaseDate: string | null+ valuationMethod: string+}) {+ const { t } = useTranslation()+ const { mask } = usePrivacyMode()+ const queryClient = useQueryClient()++ const [valueAmount, setValueAmount] = useState('')+ const [valueDate, setValueDate] = useState(new Date().toISOString().slice(0, 10))++ const { data: values, isLoading: valuesLoading } = useQuery({+ queryKey: ['asset-values', assetId],+ queryFn: () => assets.values(assetId),+ })++ const { data: trend } = useQuery({+ queryKey: ['asset-trend', assetId],+ queryFn: () => assets.valueTrend(assetId),+ })++ // Build full trend: purchase point + stored values+ const trendWithPurchase = useMemo(() => {+ if (!trend) return []+ let result = [...trend]++ // Prepend purchase point if it predates the first value+ if (purchasePrice && purchaseDate) {+ if (result.length === 0 || purchaseDate < result[0].date) {+ result = [{ date: purchaseDate, amount: purchasePrice }, ...result]+ }+ }++ return result+ }, [trend, purchasePrice, purchaseDate])++ // Build value history with purchase as the initial entry+ const valuesWithPurchase = useMemo(() => {+ if (!values) return []+ if (!purchasePrice || !purchaseDate) return values+ const hasPurchaseValue = values.some(v => v.date === purchaseDate && v.amount === purchasePrice)+ if (hasPurchaseValue) return values+ const purchaseEntry: AssetValue = {+ id: 'purchase',+ asset_id: assetId,+ amount: purchasePrice,+ date: purchaseDate,+ source: 'purchase',+ }+ return [...values, purchaseEntry]+ }, [values, purchasePrice, purchaseDate, assetId])++ const addValueMutation = useMutation({+ mutationFn: ({ assetId: id, ...data }: { assetId: string; amount: number; date: string }) =>+ assets.addValue(id, data),+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: ['assets'] })+ queryClient.invalidateQueries({ queryKey: ['asset-values', assetId] })+ queryClient.invalidateQueries({ queryKey: ['asset-trend', assetId] })+ queryClient.invalidateQueries({ queryKey: ['dashboard'] })+ setValueAmount('')+ toast.success(t('assets.valueAdded'))+ },+ onError: () => toast.error(t('common.error')),+ })++ const deleteValueMutation = useMutation({+ mutationFn: (valueId: string) => assets.deleteValue(valueId),+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: ['assets'] })+ queryClient.invalidateQueries({ queryKey: ['asset-values', assetId] })+ queryClient.invalidateQueries({ queryKey: ['asset-trend', assetId] })+ queryClient.invalidateQueries({ queryKey: ['dashboard'] })+ toast.success(t('assets.valueDeleted'))+ },+ onError: () => toast.error(t('common.error')),+ })++ // Determine chart color based on trend direction+ const trendIsPositive = trendWithPurchase.length >= 2+ ? trendWithPurchase[trendWithPurchase.length - 1].amount >= trendWithPurchase[0].amount+ : true+ const chartColor = trendIsPositive ? '#10B981' : '#F43F5E'++ return (+ <div className="border-t border-border px-5 py-5 space-y-5 bg-muted/5">+ {/* Value Trend Chart */}+ {trendWithPurchase.length > 1 && (+ <div>+ <p className="text-[11px] font-semibold text-muted-foreground uppercase tracking-wider mb-3">{t('assets.valueTrend')}</p>+ <div className="h-44 -mx-1">+ <ResponsiveContainer width="100%" height="100%">+ <AreaChart data={trendWithPurchase} margin={{ top: 4, right: 12, left: 0, bottom: 0 }}>+ <defs>+ <linearGradient id={`gradient-${assetId}`} x1="0" y1="0" x2="0" y2="1">+ <stop offset="0%" stopColor={chartColor} stopOpacity={0.2} />+ <stop offset="100%" stopColor={chartColor} stopOpacity={0} />+ </linearGradient>+ </defs>+ <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="var(--border)" strokeOpacity={0.5} />+ <XAxis+ dataKey="date"+ tick={{ fontSize: 10, fill: 'var(--muted-foreground)' }}+ axisLine={false}+ tickLine={false}+ tickFormatter={(v: string) => new Date(v + 'T00:00:00').toLocaleDateString(loc, { month: 'short', year: '2-digit' })}+ />+ <YAxis+ tick={{ fontSize: 10, fill: 'var(--muted-foreground)' }}+ axisLine={false}+ tickLine={false}+ width={56}+ domain={['dataMin', 'dataMax']}+ tickFormatter={(v: number) => {+ const abs = Math.abs(v)+ let formatted: string+ if (abs >= 1_000_000) formatted = `${(v / 1_000_000).toFixed(1)}M`+ else if (abs >= 1_000) formatted = `${(v / 1_000).toFixed(abs >= 10_000 ? 0 : 1)}k`+ else formatted = v.toLocaleString(loc, { maximumFractionDigits: 0 })+ return mask(formatted)+ }}+ />+ <RechartsTooltip+ formatter={(value: number | undefined) => [mask(formatCurrency(value ?? 0, currency, loc)), t('assets.currentValue')]}+ labelFormatter={(label: unknown) => new Date(String(label) + 'T00:00:00').toLocaleDateString(loc, { day: 'numeric', month: 'long', year: 'numeric' })}+ contentStyle={{+ background: 'var(--card)',+ color: 'var(--foreground)',+ border: '1px solid var(--border)',+ borderRadius: '0.75rem',+ fontSize: '12px',+ boxShadow: '0 4px 12px rgba(0,0,0,0.08)',+ }}+ />+ <Area+ type="monotone"+ dataKey="amount"+ stroke={chartColor}+ strokeWidth={2}+ fill={`url(#gradient-${assetId})`}+ dot={false}+ activeDot={{ r: 4, strokeWidth: 2, fill: 'var(--card)', stroke: chartColor }}+ />+ </AreaChart>+ </ResponsiveContainer>+ </div>+ </div>+ )}++ {/* Add Value Form — only for manual assets */}+ {valuationMethod === 'manual' && <div className="flex items-end gap-2">+ <div className="flex-1">+ <Label className="text-[11px] text-muted-foreground">{t('assets.amount')}</Label>+ <Input+ type="number"+ step="any"+ value={valueAmount}+ onChange={e => setValueAmount(e.target.value)}+ placeholder="0.00"+ className="h-8 text-sm"+ />+ </div>+ <div className="w-36">+ <Label className="text-[11px] text-muted-foreground">{t('assets.date')}</Label>+ <DatePickerInput value={valueDate} onChange={setValueDate} />+ </div>+ <Button+ size="sm"+ className="h-8 px-3 text-xs"+ disabled={!valueAmount || addValueMutation.isPending}+ onClick={() => {+ if (valueAmount) {+ addValueMutation.mutate({+ assetId,+ amount: parseFloat(valueAmount),+ date: valueDate,+ })+ }+ }}+ >+ <Plus size={14} className="mr-1" />+ {t('assets.addValue')}+ </Button>+ </div>}++ {/* Value History */}+ <div>+ <p className="text-[11px] font-semibold text-muted-foreground uppercase tracking-wider mb-2">{t('assets.valueHistory')}</p>+ {valuesLoading ? (+ <Skeleton className="h-20 w-full rounded-lg" />+ ) : valuesWithPurchase.length > 0 ? (+ <div className="rounded-lg border border-border overflow-hidden divide-y divide-border">+ {valuesWithPurchase.map((v: AssetValue, idx: number) => {+ const isPurchase = v.source === 'purchase'+ // Calculate change from previous entry (next in array since sorted desc)+ const prev = valuesWithPurchase[idx + 1]+ const change = prev ? v.amount - prev.amount : null+ const changePct = prev && prev.amount !== 0 ? (change! / prev.amount) * 100 : null++ return (+ <div key={v.id} className={`flex items-center justify-between py-2 px-3 transition-colors ${isPurchase ? 'bg-primary/5' : 'hover:bg-muted/30'}`}>+ <div className="flex items-center gap-3 min-w-0">+ <span className="text-sm tabular-nums font-semibold text-foreground">+ {mask(formatCurrency(v.amount, currency, loc))}+ </span>+ {change != null && (+ <span className={`text-[11px] tabular-nums font-medium ${change >= 0 ? 'text-emerald-600' : 'text-rose-500'}`}>+ {change >= 0 ? '+' : ''}{mask(formatCurrency(change, currency, loc))}+ {changePct != null && ` (${changePct >= 0 ? '+' : ''}${changePct.toFixed(2)}%)`}+ </span>+ )}+ </div>+ <div className="flex items-center gap-2 shrink-0">+ <Badge variant={isPurchase ? 'default' : 'outline'} className={`text-[10px] px-1.5 py-0 ${isPurchase ? 'bg-primary/15 text-primary border-primary/30' : ''}`}>+ {t(`assets.source${v.source.charAt(0).toUpperCase() + v.source.slice(1)}`)}+ </Badge>+ <span className="text-[11px] text-muted-foreground tabular-nums">+ {new Date(v.date + 'T00:00:00').toLocaleDateString(loc)}+ </span>+ {valuationMethod === 'manual' && v.source === 'manual' && (+ <button+ onClick={() => deleteValueMutation.mutate(v.id)}+ className="p-1 rounded text-muted-foreground/40 hover:text-rose-600 transition-colors"+ disabled={deleteValueMutation.isPending}+ >+ <Trash2 size={12} />+ </button>+ )}+ </div>+ </div>+ )+ })}+ </div>+ ) : (+ <p className="text-xs text-muted-foreground py-3 text-center">{t('dashboard.noData')}</p>+ )}+ </div>+ </div>+ )+}diff --git a/frontend/src/pages/dashboard.tsx b/frontend/src/pages/dashboard.tsxindex 7106eb0d..3476fa6a 100644--- a/frontend/src/pages/dashboard.tsx+++ b/frontend/src/pages/dashboard.tsx@@ -458,6 +458,16 @@ export default function DashboardPage() {</p>)}</div>++ {/* Assets Value */}+ {!summaryLoading && summary?.assets_value && Object.values(summary.assets_value).reduce((a, b) => a + b, 0) > 0 && (+ <div className="min-w-0">+ <p className="text-xs font-medium text-muted-foreground mb-0.5">{t('dashboard.assetsValue')}</p>+ <p className="text-lg font-bold tabular-nums text-blue-600">+ {mask(formatCurrency(Object.values(summary.assets_value).reduce((a, b) => a + b, 0), userCurrency, locale))}+ </p>+ </div>+ )}</div>{/* Spending projection */}diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.tsindex 0c75592b..b5d7d9d1 100644--- a/frontend/src/types/index.ts+++ b/frontend/src/types/index.ts@@ -165,6 +165,7 @@ export interface DashboardSummary {accounts_count: numberpending_categorization: numberpending_categorization_amount: number+ assets_value: Record<string, number>}export interface SpendingByCategory {@@ -215,6 +216,37 @@ export interface BudgetVsActual {is_recurring: boolean}+export interface Asset {+ id: string+ user_id: string+ name: string+ type: string+ currency: string+ units: number | null+ valuation_method: string+ purchase_date: string | null+ purchase_price: number | null+ sell_date: string | null+ sell_price: number | null+ growth_type: string | null+ growth_rate: number | null+ growth_frequency: string | null+ growth_start_date: string | null+ is_archived: boolean+ position: number+ current_value: number | null+ gain_loss: number | null+ value_count: number+}++export interface AssetValue {+ id: string+ asset_id: string+ amount: number+ date: string+ source: string+}+export interface PaginatedResponse<T> {items: T[]total: number