Skip to content

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

feat: adding goals and targets (#60)

Tássio Noronhaa12a24645494
diff --git a/backend/alembic/versions/022_goals.py b/backend/alembic/versions/022_goals.py
new file mode 100644
index 00000000..e7a4a8da
--- /dev/null
+++ b/backend/alembic/versions/022_goals.py
@@ -0,0 +1,48 @@
+"""create goals table
+
+Revision ID: 022
+Revises: 021
+Create Date: 2026-04-08
+"""
+
+from typing import Sequence, Union
+
+import sqlalchemy as sa
+from alembic import op
+
+revision: str = "022"
+down_revision: Union[str, None] = "021"
+branch_labels: Union[str, Sequence[str], None] = None
+depends_on: Union[str, Sequence[str], None] = None
+
+
+def upgrade() -> None:
+ op.create_table(
+ "goals",
+ sa.Column("id", sa.dialects.postgresql.UUID(as_uuid=True), primary_key=True),
+ sa.Column("user_id", sa.dialects.postgresql.UUID(as_uuid=True), sa.ForeignKey("users.id"), nullable=False),
+ sa.Column("name", sa.String(255), nullable=False),
+ sa.Column("target_amount", sa.Numeric(precision=15, scale=2), nullable=False),
+ sa.Column("current_amount", sa.Numeric(precision=15, scale=2), nullable=False, server_default="0"),
+ sa.Column("currency", sa.String(3), nullable=False, server_default="USD"),
+ sa.Column("target_amount_primary", sa.Numeric(precision=15, scale=2), nullable=True),
+ sa.Column("current_amount_primary", sa.Numeric(precision=15, scale=2), nullable=True),
+ sa.Column("target_date", sa.Date(), nullable=True),
+ sa.Column("tracking_type", sa.String(20), nullable=False, server_default="manual"),
+ sa.Column("account_id", sa.dialects.postgresql.UUID(as_uuid=True), sa.ForeignKey("accounts.id"), nullable=True),
+ sa.Column("status", sa.String(20), nullable=False, server_default="active"),
+ sa.Column("icon", sa.String(50), nullable=True),
+ sa.Column("color", sa.String(7), nullable=True),
+ sa.Column("position", sa.Integer(), nullable=False, server_default="0"),
+ sa.Column("metadata_json", sa.JSON(), nullable=True),
+ sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now()),
+ sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.func.now()),
+ )
+ op.create_index("ix_goals_user_id", "goals", ["user_id"])
+ op.create_index("ix_goals_user_status", "goals", ["user_id", "status"])
+
+
+def downgrade() -> None:
+ op.drop_index("ix_goals_user_status", table_name="goals")
+ op.drop_index("ix_goals_user_id", table_name="goals")
+ op.drop_table("goals")
diff --git a/backend/alembic/versions/023_goals_initial_amount.py b/backend/alembic/versions/023_goals_initial_amount.py
new file mode 100644
index 00000000..7475b8ca
--- /dev/null
+++ b/backend/alembic/versions/023_goals_initial_amount.py
@@ -0,0 +1,25 @@
+"""add initial_amount to goals
+
+Revision ID: 023
+Revises: 022
+Create Date: 2026-04-08
+"""
+
+from alembic import op
+import sqlalchemy as sa
+
+revision = "023"
+down_revision = "022"
+branch_labels = None
+depends_on = None
+
+
+def upgrade() -> None:
+ op.add_column("goals", sa.Column("initial_amount", sa.Numeric(precision=15, scale=2), nullable=False, server_default="0.00"))
+ # Backfill existing goals: set initial_amount = current_amount so existing
+ # goals don't falsely show progress from zero.
+ op.execute("UPDATE goals SET initial_amount = current_amount")
+
+
+def downgrade() -> None:
+ op.drop_column("goals", "initial_amount")
diff --git a/backend/alembic/versions/024_goals_asset_tracking.py b/backend/alembic/versions/024_goals_asset_tracking.py
new file mode 100644
index 00000000..4ce2afe6
--- /dev/null
+++ b/backend/alembic/versions/024_goals_asset_tracking.py
@@ -0,0 +1,23 @@
+"""add asset_id to goals for asset tracking
+
+Revision ID: 024
+Revises: 023
+Create Date: 2026-04-08
+"""
+
+from alembic import op
+import sqlalchemy as sa
+from sqlalchemy.dialects.postgresql import UUID
+
+revision = "024"
+down_revision = "023"
+branch_labels = None
+depends_on = None
+
+
+def upgrade() -> None:
+ op.add_column("goals", sa.Column("asset_id", UUID(as_uuid=True), sa.ForeignKey("assets.id"), nullable=True))
+
+
+def downgrade() -> None:
+ op.drop_column("goals", "asset_id")
diff --git a/backend/app/api/goals.py b/backend/app/api/goals.py
new file mode 100644
index 00000000..2ca7ecab
--- /dev/null
+++ b/backend/app/api/goals.py
@@ -0,0 +1,79 @@
+import uuid
+from typing import Optional
+
+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.goal import GoalCreate, GoalRead, GoalSummary, GoalUpdate
+from app.services import goal_service
+
+router = APIRouter(prefix="/api/goals", tags=["goals"])
+
+
[email protected]("", response_model=list[GoalRead])
+async def list_goals(
+ status: Optional[str] = Query(None),
+ session: AsyncSession = Depends(get_async_session),
+ user: User = Depends(current_active_user),
+):
+ return await goal_service.get_goals(session, user.id, status)
+
+
[email protected]("/summary", response_model=list[GoalSummary])
+async def goal_summary(
+ limit: int = Query(3, ge=1, le=10),
+ session: AsyncSession = Depends(get_async_session),
+ user: User = Depends(current_active_user),
+):
+ return await goal_service.get_goal_summary(session, user.id, limit)
+
+
[email protected]("", response_model=GoalRead, status_code=status.HTTP_201_CREATED)
+async def create_goal(
+ data: GoalCreate,
+ session: AsyncSession = Depends(get_async_session),
+ user: User = Depends(current_active_user),
+):
+ try:
+ return await goal_service.create_goal(session, user.id, data)
+ except Exception as e:
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
+
+
[email protected]("/{goal_id}", response_model=GoalRead)
+async def get_goal(
+ goal_id: uuid.UUID,
+ session: AsyncSession = Depends(get_async_session),
+ user: User = Depends(current_active_user),
+):
+ goal = await goal_service.get_goal(session, goal_id, user.id)
+ if not goal:
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Goal not found")
+ return goal
+
+
[email protected]("/{goal_id}", response_model=GoalRead)
+async def update_goal(
+ goal_id: uuid.UUID,
+ data: GoalUpdate,
+ session: AsyncSession = Depends(get_async_session),
+ user: User = Depends(current_active_user),
+):
+ goal = await goal_service.update_goal(session, goal_id, user.id, data)
+ if not goal:
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Goal not found")
+ return goal
+
+
[email protected]("/{goal_id}", status_code=status.HTTP_204_NO_CONTENT)
+async def delete_goal(
+ goal_id: uuid.UUID,
+ session: AsyncSession = Depends(get_async_session),
+ user: User = Depends(current_active_user),
+):
+ deleted = await goal_service.delete_goal(session, goal_id, user.id)
+ if not deleted:
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Goal not found")
diff --git a/backend/app/main.py b/backend/app/main.py
index 2d77a89d..e1d7da48 100644
--- a/backend/app/main.py
+++ b/backend/app/main.py
@@ -6,6 +6,7 @@ from fastapi.middleware.cors import CORSMiddleware
from app.api.accounts import router as accounts_router
from app.api.budgets import router as budgets_router
+from app.api.goals import router as goals_router
from app.api.categories import router as categories_router
from app.api.category_groups import router as category_groups_router
from app.api.connections import router as connections_router
@@ -108,6 +109,7 @@ app.include_router(accounts_router)
app.include_router(connections_router)
app.include_router(recurring_router)
app.include_router(budgets_router)
+app.include_router(goals_router)
app.include_router(assets_router)
app.include_router(dashboard_router)
app.include_router(reports_router)
diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py
index 7c284a4d..2e5a3711 100644
--- a/backend/app/models/__init__.py
+++ b/backend/app/models/__init__.py
@@ -14,6 +14,7 @@ from app.models.fx_rate import FxRate
from app.models.transaction_attachment import TransactionAttachment
from app.models.payee import Payee, PayeeMapping
from app.models.app_settings import AppSetting
+from app.models.goal import Goal
__all__ = [
"User",
@@ -33,4 +34,5 @@ __all__ = [
"Payee",
"PayeeMapping",
"AppSetting",
+ "Goal",
]
diff --git a/backend/app/models/goal.py b/backend/app/models/goal.py
new file mode 100644
index 00000000..8b9107e8
--- /dev/null
+++ b/backend/app/models/goal.py
@@ -0,0 +1,46 @@
+import uuid
+from datetime import date, datetime
+from decimal import Decimal
+from typing import TYPE_CHECKING, Any, Optional
+
+from sqlalchemy import Date, DateTime, ForeignKey, Integer, Numeric, String
+from sqlalchemy.dialects.postgresql import UUID
+from sqlalchemy.orm import Mapped, mapped_column, relationship
+from sqlalchemy.sql import func
+from sqlalchemy.types import JSON
+
+from app.core.database import Base
+
+if TYPE_CHECKING:
+ from app.models.account import Account
+ from app.models.asset import Asset
+ from app.models.user import User
+
+
+class Goal(Base):
+ __tablename__ = "goals"
+
+ 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))
+ target_amount: Mapped[Decimal] = mapped_column(Numeric(precision=15, scale=2))
+ current_amount: Mapped[Decimal] = mapped_column(Numeric(precision=15, scale=2), default=Decimal("0.00"))
+ initial_amount: Mapped[Decimal] = mapped_column(Numeric(precision=15, scale=2), default=Decimal("0.00"))
+ currency: Mapped[str] = mapped_column(String(3), default="USD")
+ target_amount_primary: Mapped[Optional[Decimal]] = mapped_column(Numeric(precision=15, scale=2), nullable=True)
+ current_amount_primary: Mapped[Optional[Decimal]] = mapped_column(Numeric(precision=15, scale=2), nullable=True)
+ target_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
+ tracking_type: Mapped[str] = mapped_column(String(20), default="manual") # manual, account, asset, net_worth
+ account_id: Mapped[Optional[uuid.UUID]] = mapped_column(UUID(as_uuid=True), ForeignKey("accounts.id"), nullable=True)
+ asset_id: Mapped[Optional[uuid.UUID]] = mapped_column(UUID(as_uuid=True), ForeignKey("assets.id"), nullable=True)
+ status: Mapped[str] = mapped_column(String(20), default="active") # active, completed, paused, archived
+ icon: Mapped[Optional[str]] = mapped_column(String(50), nullable=True)
+ color: Mapped[Optional[str]] = mapped_column(String(7), nullable=True)
+ position: Mapped[int] = mapped_column(Integer, default=0)
+ metadata_json: Mapped[Optional[Any]] = mapped_column(JSON, nullable=True)
+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
+ updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
+
+ user: Mapped["User"] = relationship()
+ account: Mapped[Optional["Account"]] = relationship()
+ asset: Mapped[Optional["Asset"]] = relationship()
diff --git a/backend/app/schemas/goal.py b/backend/app/schemas/goal.py
new file mode 100644
index 00000000..48772c80
--- /dev/null
+++ b/backend/app/schemas/goal.py
@@ -0,0 +1,105 @@
+import uuid
+from datetime import date as _Date, datetime
+from decimal import Decimal
+from typing import Any, Optional
+
+from pydantic import BaseModel, ConfigDict, field_validator
+
+
+class GoalCreate(BaseModel):
+ name: str
+ target_amount: Decimal
+ current_amount: Decimal = Decimal("0")
+ currency: str = "USD"
+ target_date: Optional[_Date] = None
+ tracking_type: str = "manual"
+ account_id: Optional[uuid.UUID] = None
+ asset_id: Optional[uuid.UUID] = None
+ icon: Optional[str] = None
+ color: Optional[str] = None
+ metadata_json: Optional[Any] = None
+
+ @field_validator("tracking_type")
+ @classmethod
+ def validate_tracking_type(cls, v: str) -> str:
+ if v not in ("manual", "account", "asset", "net_worth"):
+ raise ValueError("tracking_type must be manual, account, asset, or net_worth")
+ return v
+
+
+class GoalUpdate(BaseModel):
+ name: Optional[str] = None
+ target_amount: Optional[Decimal] = None
+ current_amount: Optional[Decimal] = None
+ currency: Optional[str] = None
+ target_date: Optional[_Date] = None
+ tracking_type: Optional[str] = None
+ account_id: Optional[uuid.UUID] = None
+ asset_id: Optional[uuid.UUID] = None
+ status: Optional[str] = None
+ icon: Optional[str] = None
+ color: Optional[str] = None
+ position: Optional[int] = None
+ metadata_json: Optional[Any] = None
+
+ @field_validator("status")
+ @classmethod
+ def validate_status(cls, v: Optional[str]) -> Optional[str]:
+ if v is not None and v not in ("active", "completed", "paused", "archived"):
+ raise ValueError("status must be active, completed, paused, or archived")
+ return v
+
+ @field_validator("tracking_type")
+ @classmethod
+ def validate_tracking_type(cls, v: Optional[str]) -> Optional[str]:
+ if v is not None and v not in ("manual", "account", "net_worth"):
+ raise ValueError("tracking_type must be manual, account, or net_worth")
+ return v
+
+
+class GoalRead(BaseModel):
+ id: uuid.UUID
+ user_id: uuid.UUID
+ name: str
+ target_amount: Decimal
+ current_amount: Decimal
+ currency: str
+ target_amount_primary: Optional[Decimal] = None
+ current_amount_primary: Optional[Decimal] = None
+ target_date: Optional[_Date] = None
+ tracking_type: str
+ account_id: Optional[uuid.UUID] = None
+ asset_id: Optional[uuid.UUID] = None
+ status: str
+ icon: Optional[str] = None
+ color: Optional[str] = None
+ position: int
+ metadata_json: Optional[Any] = None
+ created_at: datetime
+ updated_at: datetime
+
+ # Computed fields
+ percentage: float = 0
+ monthly_contribution: Optional[float] = None
+ on_track: Optional[str] = None # ahead, on_track, behind, overdue, achieved
+
+ # Linked account/asset info
+ account_name: Optional[str] = None
+ asset_name: Optional[str] = None
+
+ model_config = ConfigDict(from_attributes=True)
+
+
+class GoalSummary(BaseModel):
+ id: uuid.UUID
+ name: str
+ target_amount: Decimal
+ current_amount: Decimal
+ currency: str
+ target_date: Optional[_Date] = None
+ status: str
+ icon: Optional[str] = None
+ color: Optional[str] = None
+ percentage: float = 0
+ monthly_contribution: Optional[float] = None
+ on_track: Optional[str] = None
diff --git a/backend/app/services/goal_service.py b/backend/app/services/goal_service.py
new file mode 100644
index 00000000..6137db6a
--- /dev/null
+++ b/backend/app/services/goal_service.py
@@ -0,0 +1,331 @@
+import uuid
+from datetime import date
+from decimal import Decimal
+from typing import Optional
+
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.core.config import get_settings
+from app.models.account import Account
+from app.models.asset import Asset
+from app.models.goal import Goal
+from app.models.user import User
+from app.schemas.goal import GoalCreate, GoalRead, GoalSummary, GoalUpdate
+from app.services.asset_service import _compute_current_value, _get_latest_value, get_total_asset_value
+from app.services.dashboard_service import _account_balance_at, _get_open_accounts
+from app.services.fx_rate_service import convert
+
+
+async def _get_primary_currency(session: AsyncSession, user_id: uuid.UUID) -> str:
+ user = await session.get(User, user_id)
+ return user.primary_currency if user else get_settings().default_currency
+
+
+async def _resolve_current_amount(
+ session: AsyncSession, goal: Goal, user_id: uuid.UUID
+) -> Decimal:
+ """Resolve the current_amount based on tracking_type.
+
+ Returns the amount in the goal's currency.
+ """
+ goal_currency = goal.currency
+
+ if goal.tracking_type == "account" and goal.account_id:
+ account = await session.get(Account, goal.account_id)
+ if account:
+ # Use dashboard's balance logic so manual accounts are computed correctly
+ bal = Decimal(str(await _account_balance_at(session, account, date.today())))
+ if account.currency != goal_currency:
+ converted, _ = await convert(
+ session, bal, account.currency, goal_currency
+ )
+ return converted
+ return bal
+ return goal.current_amount
+ elif goal.tracking_type == "asset" and goal.asset_id:
+ asset = await session.get(Asset, goal.asset_id)
+ if asset:
+ latest = await _get_latest_value(session, asset.id)
+ value = _compute_current_value(asset, latest)
+ if value is not None:
+ bal = Decimal(str(value))
+ if asset.currency != goal_currency:
+ converted, _ = await convert(
+ session, bal, asset.currency, goal_currency
+ )
+ return converted
+ return bal
+ return goal.current_amount
+ elif goal.tracking_type == "net_worth":
+ # Reuse dashboard's account query and balance logic so manual accounts
+ # (whose balance is computed from transactions) are handled correctly.
+ accounts = await _get_open_accounts(session, user_id)
+ today = date.today()
+ total = Decimal("0")
+ for acc in accounts:
+ bal = Decimal(str(await _account_balance_at(session, acc, today)))
+ if acc.currency == goal_currency:
+ total += bal
+ else:
+ converted, _ = await convert(session, bal, acc.currency, goal_currency)
+ total += converted
+
+ # Add asset values
+ assets_by_currency = await get_total_asset_value(session, user_id)
+ for currency, amount in assets_by_currency.items():
+ if currency == goal_currency:
+ total += Decimal(str(amount))
+ else:
+ converted, _ = await convert(session, Decimal(str(amount)), currency, goal_currency)
+ total += converted
+
+ return total
+ else:
+ return goal.current_amount
+
+
+def _compute_percentage(current: Decimal, target: Decimal) -> float:
+ if target <= 0:
+ return 100.0 if current > 0 else 0.0
+ return round(float(current / target) * 100, 1)
+
+
+def _compute_monthly_contribution(
+ current: Decimal, target: Decimal, target_date: Optional[date]
+) -> Optional[float]:
+ if not target_date:
+ return None
+ today = date.today()
+ if today >= target_date:
+ return 0.0
+ remaining = target - current
+ if remaining <= 0:
+ return 0.0
+ # Calculate months remaining (approximate)
+ months = (target_date.year - today.year) * 12 + (target_date.month - today.month)
+ if months <= 0:
+ months = 1
+ return round(float(remaining / months), 2)
+
+
+def _compute_on_track(
+ current: Decimal, target: Decimal, target_date: Optional[date],
+ created_at: Optional[date] = None, initial_amount: Decimal = Decimal("0"),
+) -> Optional[str]:
+ if not target_date:
+ return None
+ if current >= target:
+ return "achieved"
+ today = date.today()
+ if today > target_date:
+ return "overdue"
+
+ # Use created_at as start date; fall back to today (no progress expected yet)
+ start = created_at if created_at else today
+ total_days = (target_date - start).days
+ if total_days <= 0:
+ return "on_track"
+
+ # Measure progress relative to the starting baseline, not from zero.
+ # total_needed = how much needs to be saved from initial to target
+ # actual_progress = how much has been saved since creation
+ total_needed = target - initial_amount
+ if total_needed <= 0:
+ return "achieved"
+
+ elapsed_days = (today - start).days
+ expected_progress = total_needed * Decimal(str(elapsed_days / total_days))
+ actual_progress = current - initial_amount
+
+ diff = actual_progress - expected_progress
+ # Express tolerance as percentage of total_needed
+ tolerance = total_needed * Decimal("0.05")
+
+ if diff >= tolerance * 2:
+ return "ahead"
+ if diff >= -tolerance:
+ return "on_track"
+ return "behind"
+
+
+async def _enrich_goal(
+ session: AsyncSession, goal: Goal, user_id: uuid.UUID
+) -> GoalRead:
+ """Enrich a goal with computed fields."""
+ current = await _resolve_current_amount(session, goal, user_id)
+ percentage = _compute_percentage(current, goal.target_amount)
+ monthly = _compute_monthly_contribution(current, goal.target_amount, goal.target_date)
+ goal_start = goal.created_at.date() if goal.created_at else None
+ on_track = _compute_on_track(
+ current, goal.target_amount, goal.target_date, goal_start, goal.initial_amount
+ )
+
+ # Get linked account/asset name
+ account_name = None
+ if goal.account_id:
+ account = await session.get(Account, goal.account_id)
+ if account:
+ account_name = account.name
+ asset_name = None
+ if goal.asset_id:
+ asset = await session.get(Asset, goal.asset_id)
+ if asset:
+ asset_name = asset.name
+
+ # Convert to primary currency if needed
+ primary_currency = await _get_primary_currency(session, user_id)
+ target_primary = None
+ current_primary = None
+ if goal.currency != primary_currency:
+ target_converted, _ = await convert(
+ session, goal.target_amount, goal.currency, primary_currency
+ )
+ current_converted, _ = await convert(
+ session, current, goal.currency, primary_currency
+ )
+ target_primary = target_converted
+ current_primary = current_converted
+
+ return GoalRead(
+ id=goal.id,
+ user_id=goal.user_id,
+ name=goal.name,
+ target_amount=goal.target_amount,
+ current_amount=current,
+ currency=goal.currency,
+ target_amount_primary=target_primary,
+ current_amount_primary=current_primary,
+ target_date=goal.target_date,
+ tracking_type=goal.tracking_type,
+ account_id=goal.account_id,
+ asset_id=goal.asset_id,
+ status=goal.status,
+ icon=goal.icon,
+ color=goal.color,
+ position=goal.position,
+ metadata_json=goal.metadata_json,
+ created_at=goal.created_at,
+ updated_at=goal.updated_at,
+ percentage=percentage,
+ monthly_contribution=monthly,
+ on_track=on_track,
+ account_name=account_name,
+ asset_name=asset_name,
+ )
+
+
+async def get_goals(
+ session: AsyncSession, user_id: uuid.UUID, status: Optional[str] = None
+) -> list[GoalRead]:
+ query = select(Goal).where(Goal.user_id == user_id).order_by(Goal.position, Goal.created_at)
+ if status:
+ query = query.where(Goal.status == status)
+ result = await session.execute(query)
+ goals = list(result.scalars().all())
+ return [await _enrich_goal(session, g, user_id) for g in goals]
+
+
+async def get_goal(
+ session: AsyncSession, goal_id: uuid.UUID, user_id: uuid.UUID
+) -> Optional[GoalRead]:
+ result = await session.execute(
+ select(Goal).where(Goal.id == goal_id, Goal.user_id == user_id)
+ )
+ goal = result.scalar_one_or_none()
+ if not goal:
+ return None
+ return await _enrich_goal(session, goal, user_id)
+
+
+async def create_goal(
+ session: AsyncSession, user_id: uuid.UUID, data: GoalCreate
+) -> GoalRead:
+ goal = Goal(
+ user_id=user_id,
+ name=data.name,
+ target_amount=data.target_amount,
+ current_amount=data.current_amount,
+ currency=data.currency,
+ target_date=data.target_date,
+ tracking_type=data.tracking_type,
+ account_id=data.account_id,
+ asset_id=data.asset_id,
+ icon=data.icon,
+ color=data.color,
+ metadata_json=data.metadata_json,
+ )
+ # Capture the starting balance so on-track logic measures progress from baseline
+ initial = await _resolve_current_amount(session, goal, user_id)
+ goal.initial_amount = initial
+ session.add(goal)
+ await session.commit()
+ await session.refresh(goal)
+ return await _enrich_goal(session, goal, user_id)
+
+
+async def update_goal(
+ session: AsyncSession, goal_id: uuid.UUID, user_id: uuid.UUID, data: GoalUpdate
+) -> Optional[GoalRead]:
+ result = await session.execute(
+ select(Goal).where(Goal.id == goal_id, Goal.user_id == user_id)
+ )
+ goal = result.scalar_one_or_none()
+ if not goal:
+ return None
+ for field, value in data.model_dump(exclude_unset=True).items():
+ setattr(goal, field, value)
+ await session.commit()
+ await session.refresh(goal)
+ return await _enrich_goal(session, goal, user_id)
+
+
+async def delete_goal(
+ session: AsyncSession, goal_id: uuid.UUID, user_id: uuid.UUID
+) -> bool:
+ result = await session.execute(
+ select(Goal).where(Goal.id == goal_id, Goal.user_id == user_id)
+ )
+ goal = result.scalar_one_or_none()
+ if not goal:
+ return False
+ await session.delete(goal)
+ await session.commit()
+ return True
+
+
+async def get_goal_summary(
+ session: AsyncSession, user_id: uuid.UUID, limit: int = 3
+) -> list[GoalSummary]:
+ """Get a summary of active goals for the dashboard widget."""
+ result = await session.execute(
+ select(Goal)
+ .where(Goal.user_id == user_id, Goal.status == "active")
+ .order_by(Goal.position, Goal.created_at)
+ .limit(limit)
+ )
+ goals = list(result.scalars().all())
+ summaries = []
+ for goal in goals:
+ current = await _resolve_current_amount(session, goal, user_id)
+ percentage = _compute_percentage(current, goal.target_amount)
+ monthly = _compute_monthly_contribution(current, goal.target_amount, goal.target_date)
+ goal_start = goal.created_at.date() if goal.created_at else None
+ on_track = _compute_on_track(
+ current, goal.target_amount, goal.target_date, goal_start, goal.initial_amount
+ )
+ summaries.append(GoalSummary(
+ id=goal.id,
+ name=goal.name,
+ target_amount=goal.target_amount,
+ current_amount=current,
+ currency=goal.currency,
+ target_date=goal.target_date,
+ status=goal.status,
+ icon=goal.icon,
+ color=goal.color,
+ percentage=percentage,
+ monthly_contribution=monthly,
+ on_track=on_track,
+ ))
+ return summaries
diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py
index 70d4d5bd..07bb6a9f 100644
--- a/backend/tests/conftest.py
+++ b/backend/tests/conftest.py
@@ -23,6 +23,7 @@ from app.models.asset_value import AssetValue # noqa: F401
from app.models.transaction_attachment import TransactionAttachment # noqa: F401
from app.models.payee import Payee, PayeeMapping # noqa: F401
from app.models.app_settings import AppSetting # noqa: F401
+from app.models.goal import Goal # noqa: F401
# Use SQLite for tests — fast, no external dependency
TEST_DATABASE_URL = "sqlite+aiosqlite:///./test.db"
diff --git a/backend/tests/test_goals_api.py b/backend/tests/test_goals_api.py
new file mode 100644
index 00000000..f049662d
--- /dev/null
+++ b/backend/tests/test_goals_api.py
@@ -0,0 +1,617 @@
+import uuid
+from datetime import date, timedelta
+from decimal import Decimal
+
+import pytest
+from httpx import AsyncClient
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.models.account import Account
+from app.models.asset import Asset
+from app.models.fx_rate import FxRate
+from app.models.user import User
+
+
+async def test_create_goal_manual(client: AsyncClient, auth_headers: dict, test_user: User):
+ response = await client.post(
+ "/api/goals",
+ json={
+ "name": "Emergency Fund",
+ "target_amount": "10000.00",
+ "current_amount": "2500.00",
+ "currency": "BRL",
+ "tracking_type": "manual",
+ },
+ headers=auth_headers,
+ )
+ assert response.status_code == 201
+ data = response.json()
+ assert data["name"] == "Emergency Fund"
+ assert float(data["target_amount"]) == 10000.00
+ assert float(data["current_amount"]) == 2500.00
+ assert data["currency"] == "BRL"
+ assert data["tracking_type"] == "manual"
+ assert data["status"] == "active"
+ assert data["percentage"] == 25.0
+
+
+async def test_create_goal_with_target_date(client: AsyncClient, auth_headers: dict, test_user: User):
+ future_date = (date.today() + timedelta(days=365)).isoformat()
+ response = await client.post(
+ "/api/goals",
+ json={
+ "name": "Vacation",
+ "target_amount": "5000.00",
+ "current_amount": "1000.00",
+ "currency": "BRL",
+ "target_date": future_date,
+ "tracking_type": "manual",
+ "icon": "plane",
+ "color": "#3B82F6",
+ },
+ headers=auth_headers,
+ )
+ assert response.status_code == 201
+ data = response.json()
+ assert data["target_date"] == future_date
+ assert data["icon"] == "plane"
+ assert data["color"] == "#3B82F6"
+ assert data["monthly_contribution"] is not None
+ assert data["monthly_contribution"] > 0
+ assert data["on_track"] is not None
+
+
+async def test_create_goal_account_tracking(
+ client: AsyncClient, auth_headers: dict, test_user: User, test_account: Account
+):
+ response = await client.post(
+ "/api/goals",
+ json={
+ "name": "Savings Account Goal",
+ "target_amount": "5000.00",
+ "currency": "BRL",
+ "tracking_type": "account",
+ "account_id": str(test_account.id),
+ },
+ headers=auth_headers,
+ )
+ assert response.status_code == 201
+ data = response.json()
+ assert data["tracking_type"] == "account"
+ assert data["account_id"] == str(test_account.id)
+ # current_amount should reflect account balance (1500.00 from test_account)
+ assert float(data["current_amount"]) == 1500.00
+ assert data["account_name"] == "Conta Corrente"
+
+
+async def test_create_goal_invalid_tracking_type(client: AsyncClient, auth_headers: dict, test_user: User):
+ response = await client.post(
+ "/api/goals",
+ json={
+ "name": "Bad Goal",
+ "target_amount": "1000.00",
+ "tracking_type": "invalid",
+ },
+ headers=auth_headers,
+ )
+ assert response.status_code == 422
+
+
+async def test_list_goals(client: AsyncClient, auth_headers: dict, test_user: User):
+ # Create two goals
+ await client.post(
+ "/api/goals",
+ json={"name": "Goal A", "target_amount": "1000.00", "tracking_type": "manual"},
+ headers=auth_headers,
+ )
+ await client.post(
+ "/api/goals",
+ json={"name": "Goal B", "target_amount": "2000.00", "tracking_type": "manual"},
+ headers=auth_headers,
+ )
+
+ response = await client.get("/api/goals", headers=auth_headers)
+ assert response.status_code == 200
+ data = response.json()
+ assert len(data) >= 2
+ names = [g["name"] for g in data]
+ assert "Goal A" in names
+ assert "Goal B" in names
+
+
+async def test_list_goals_filter_by_status(client: AsyncClient, auth_headers: dict, test_user: User):
+ # Create an active goal
+ resp = await client.post(
+ "/api/goals",
+ json={"name": "Active Goal", "target_amount": "1000.00", "tracking_type": "manual"},
+ headers=auth_headers,
+ )
+ goal_id = resp.json()["id"]
+
+ # Pause it
+ await client.patch(
+ f"/api/goals/{goal_id}",
+ json={"status": "paused"},
+ headers=auth_headers,
+ )
+
+ # Filter active only
+ response = await client.get("/api/goals?status=active", headers=auth_headers)
+ assert response.status_code == 200
+ data = response.json()
+ paused_goals = [g for g in data if g["id"] == goal_id]
+ assert len(paused_goals) == 0
+
+
+async def test_get_goal(client: AsyncClient, auth_headers: dict, test_user: User):
+ resp = await client.post(
+ "/api/goals",
+ json={"name": "Single Goal", "target_amount": "3000.00", "tracking_type": "manual"},
+ headers=auth_headers,
+ )
+ goal_id = resp.json()["id"]
+
+ response = await client.get(f"/api/goals/{goal_id}", headers=auth_headers)
+ assert response.status_code == 200
+ assert response.json()["name"] == "Single Goal"
+
+
+async def test_get_goal_not_found(client: AsyncClient, auth_headers: dict, test_user: User):
+ fake_id = str(uuid.uuid4())
+ response = await client.get(f"/api/goals/{fake_id}", headers=auth_headers)
+ assert response.status_code == 404
+
+
+async def test_update_goal(client: AsyncClient, auth_headers: dict, test_user: User):
+ resp = await client.post(
+ "/api/goals",
+ json={"name": "Update Me", "target_amount": "1000.00", "tracking_type": "manual"},
+ headers=auth_headers,
+ )
+ goal_id = resp.json()["id"]
+
+ response = await client.patch(
+ f"/api/goals/{goal_id}",
+ json={"name": "Updated Name", "target_amount": "2000.00", "current_amount": "500.00"},
+ headers=auth_headers,
+ )
+ assert response.status_code == 200
+ data = response.json()
+ assert data["name"] == "Updated Name"
+ assert float(data["target_amount"]) == 2000.00
+ assert float(data["current_amount"]) == 500.00
+ assert data["percentage"] == 25.0
+
+
+async def test_update_goal_status(client: AsyncClient, auth_headers: dict, test_user: User):
+ resp = await client.post(
+ "/api/goals",
+ json={"name": "Status Goal", "target_amount": "1000.00", "tracking_type": "manual"},
+ headers=auth_headers,
+ )
+ goal_id = resp.json()["id"]
+
+ # Pause
+ response = await client.patch(
+ f"/api/goals/{goal_id}",
+ json={"status": "paused"},
+ headers=auth_headers,
+ )
+ assert response.status_code == 200
+ assert response.json()["status"] == "paused"
+
+ # Complete
+ response = await client.patch(
+ f"/api/goals/{goal_id}",
+ json={"status": "completed"},
+ headers=auth_headers,
+ )
+ assert response.status_code == 200
+ assert response.json()["status"] == "completed"
+
+ # Archive
+ response = await client.patch(
+ f"/api/goals/{goal_id}",
+ json={"status": "archived"},
+ headers=auth_headers,
+ )
+ assert response.status_code == 200
+ assert response.json()["status"] == "archived"
+
+
+async def test_update_goal_invalid_status(client: AsyncClient, auth_headers: dict, test_user: User):
+ resp = await client.post(
+ "/api/goals",
+ json={"name": "Bad Status", "target_amount": "1000.00", "tracking_type": "manual"},
+ headers=auth_headers,
+ )
+ goal_id = resp.json()["id"]
+
+ response = await client.patch(
+ f"/api/goals/{goal_id}",
+ json={"status": "invalid_status"},
+ headers=auth_headers,
+ )
+ assert response.status_code == 422
+
+
+async def test_delete_goal(client: AsyncClient, auth_headers: dict, test_user: User):
+ resp = await client.post(
+ "/api/goals",
+ json={"name": "Delete Me", "target_amount": "1000.00", "tracking_type": "manual"},
+ headers=auth_headers,
+ )
+ goal_id = resp.json()["id"]
+
+ response = await client.delete(f"/api/goals/{goal_id}", headers=auth_headers)
+ assert response.status_code == 204
+
+ # Verify deleted
+ response = await client.get(f"/api/goals/{goal_id}", headers=auth_headers)
+ assert response.status_code == 404
+
+
+async def test_delete_goal_not_found(client: AsyncClient, auth_headers: dict, test_user: User):
+ fake_id = str(uuid.uuid4())
+ response = await client.delete(f"/api/goals/{fake_id}", headers=auth_headers)
+ assert response.status_code == 404
+
+
+async def test_goal_summary(client: AsyncClient, auth_headers: dict, test_user: User):
+ # Create a few goals
+ for name in ["Goal 1", "Goal 2", "Goal 3", "Goal 4"]:
+ await client.post(
+ "/api/goals",
+ json={"name": name, "target_amount": "1000.00", "current_amount": "250.00", "tracking_type": "manual"},
+ headers=auth_headers,
+ )
+
+ response = await client.get("/api/goals/summary?limit=3", headers=auth_headers)
+ assert response.status_code == 200
+ data = response.json()
+ assert len(data) <= 3
+ for item in data:
+ assert "percentage" in item
+ assert "monthly_contribution" in item
+ assert item["percentage"] == 25.0
+
+
+async def test_goal_percentage_100(client: AsyncClient, auth_headers: dict, test_user: User):
+ response = await client.post(
+ "/api/goals",
+ json={
+ "name": "Achieved Goal",
+ "target_amount": "1000.00",
+ "current_amount": "1500.00",
+ "tracking_type": "manual",
+ },
+ headers=auth_headers,
+ )
+ assert response.status_code == 201
+ data = response.json()
+ assert data["percentage"] == 150.0
+
+
+async def test_goal_on_track_overdue(client: AsyncClient, auth_headers: dict, test_user: User):
+ past_date = (date.today() - timedelta(days=30)).isoformat()
+ response = await client.post(
+ "/api/goals",
+ json={
+ "name": "Overdue Goal",
+ "target_amount": "5000.00",
+ "current_amount": "100.00",
+ "target_date": past_date,
+ "tracking_type": "manual",
+ },
+ headers=auth_headers,
+ )
+ assert response.status_code == 201
+ data = response.json()
+ assert data["on_track"] == "overdue"
+ assert data["monthly_contribution"] == 0.0
+
+
+async def test_goal_on_track_achieved(client: AsyncClient, auth_headers: dict, test_user: User):
+ future_date = (date.today() + timedelta(days=365)).isoformat()
+ response = await client.post(
+ "/api/goals",
+ json={
+ "name": "Achieved Goal",
+ "target_amount": "1000.00",
+ "current_amount": "1500.00",
+ "target_date": future_date,
+ "tracking_type": "manual",
+ },
+ headers=auth_headers,
+ )
+ assert response.status_code == 201
+ data = response.json()
+ assert data["on_track"] == "achieved"
+ assert data["monthly_contribution"] == 0.0
+
+
+async def test_goal_ownership_isolation(
+ client: AsyncClient, auth_headers: dict, test_user: User, session: AsyncSession
+):
+ """Goals should not be visible to other users."""
+ # Create a goal for test_user
+ resp = await client.post(
+ "/api/goals",
+ json={"name": "My Goal", "target_amount": "1000.00", "tracking_type": "manual"},
+ headers=auth_headers,
+ )
+ assert resp.status_code == 201
+ goal_id = resp.json()["id"]
+
+ # Create another user
+ import bcrypt as _bcrypt
+
+ hashed = _bcrypt.hashpw(b"otherpass123", _bcrypt.gensalt()).decode()
+ from app.models.user import User as UserModel
+
+ other_user = UserModel(
+ id=uuid.uuid4(),
+ hashed_password=hashed,
+ is_active=True,
+ is_superuser=False,
+ is_verified=True,
+ preferences={"language": "en", "date_format": "MM/DD/YYYY", "timezone": "UTC", "currency_display": "USD"},
+ )
+ session.add(other_user)
+ await session.commit()
+
+ # Login as other user
+ login_resp = await client.post(
+ "/api/auth/login",
+ data={"username": "[email protected]", "password": "otherpass123"},
+ headers={"Content-Type": "application/x-www-form-urlencoded"},
+ )
+ other_token = login_resp.json()["access_token"]
+ other_headers = {"Authorization": f"Bearer {other_token}"}
+
+ # Other user should not see the goal
+ response = await client.get(f"/api/goals/{goal_id}", headers=other_headers)
+ assert response.status_code == 404
+
+ # Other user's list should be empty
+ response = await client.get("/api/goals", headers=other_headers)
+ assert response.status_code == 200
+ assert len(response.json()) == 0
+
+
+async def test_goal_with_metadata(client: AsyncClient, auth_headers: dict, test_user: User):
+ response = await client.post(
+ "/api/goals",
+ json={
+ "name": "Team Goal",
+ "target_amount": "50000.00",
+ "tracking_type": "manual",
+ "metadata_json": {"department": "Engineering", "tags": ["q2", "hiring"]},
+ },
+ headers=auth_headers,
+ )
+ assert response.status_code == 201
+ data = response.json()
+ assert data["metadata_json"]["department"] == "Engineering"
+ assert "hiring" in data["metadata_json"]["tags"]
+
+
+async def test_goal_net_worth_tracking(
+ client: AsyncClient, auth_headers: dict, test_user: User, test_account: Account
+):
+ response = await client.post(
+ "/api/goals",
+ json={
+ "name": "Net Worth Target",
+ "target_amount": "100000.00",
+ "currency": "BRL",
+ "tracking_type": "net_worth",
+ },
+ headers=auth_headers,
+ )
+ assert response.status_code == 201
+ data = response.json()
+ assert data["tracking_type"] == "net_worth"
+ # current_amount should reflect total balance (at least test_account balance)
+ assert float(data["current_amount"]) > 0
+
+
+async def test_goal_asset_tracking(
+ client: AsyncClient, auth_headers: dict, test_user: User, session: AsyncSession
+):
+ """Goal with tracking_type=asset should resolve current_amount from asset value."""
+ # Create an asset with a purchase price
+ asset = Asset(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ name="Investment Portfolio",
+ type="investment",
+ currency="BRL",
+ purchase_price=Decimal("50000.00"),
+ )
+ session.add(asset)
+ await session.commit()
+
+ response = await client.post(
+ "/api/goals",
+ json={
+ "name": "Grow Portfolio",
+ "target_amount": "100000.00",
+ "currency": "BRL",
+ "tracking_type": "asset",
+ "asset_id": str(asset.id),
+ },
+ headers=auth_headers,
+ )
+ assert response.status_code == 201
+ data = response.json()
+ assert data["tracking_type"] == "asset"
+ assert data["asset_id"] == str(asset.id)
+ assert data["asset_name"] == "Investment Portfolio"
+ # current_amount should reflect asset value (purchase_price as fallback)
+ assert float(data["current_amount"]) == 50000.00
+ assert data["percentage"] == 50.0
+
+
+async def test_goal_asset_tracking_with_currency_conversion(
+ client: AsyncClient, auth_headers: dict, test_user: User, session: AsyncSession
+):
+ """Asset-linked goal should convert asset value to goal currency."""
+ asset = Asset(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ name="EUR Property",
+ type="real_estate",
+ currency="EUR",
+ purchase_price=Decimal("200000.00"),
+ )
+ session.add(asset)
+ await session.commit()
+
+ response = await client.post(
+ "/api/goals",
+ json={
+ "name": "Property Goal",
+ "target_amount": "500000.00",
+ "currency": "BRL", # Goal in BRL, asset in EUR
+ "tracking_type": "asset",
+ "asset_id": str(asset.id),
+ },
+ headers=auth_headers,
+ )
+ assert response.status_code == 201
+ data = response.json()
+ # Should be converted from EUR to BRL (exact rate depends on FX mock)
+ assert float(data["current_amount"]) > 0
+
+
+async def test_goal_account_tracking_cross_currency(
+ client: AsyncClient, auth_headers: dict, test_user: User, test_account: Account, session: AsyncSession
+):
+ """EUR goal linked to a BRL account should convert account balance to EUR."""
+ # Seed FX rates: USD→BRL = 5.0, USD→EUR = 0.9
+ # So BRL 1500 → USD 300 → EUR 270
+ today = date.today()
+ for quote, rate in [("BRL", "5.0"), ("EUR", "0.9")]:
+ session.add(FxRate(
+ base_currency="USD", quote_currency=quote,
+ date=today, rate=Decimal(rate), source="test",
+ ))
+ await session.commit()
+
+ response = await client.post(
+ "/api/goals",
+ json={
+ "name": "EUR Savings from BRL",
+ "target_amount": "5000.00",
+ "currency": "EUR", # Goal in EUR, account in BRL
+ "tracking_type": "account",
+ "account_id": str(test_account.id),
+ },
+ headers=auth_headers,
+ )
+ assert response.status_code == 201
+ data = response.json()
+ assert data["tracking_type"] == "account"
+ assert data["currency"] == "EUR"
+ # BRL 1500 / 5.0 * 0.9 = EUR 270
+ current = float(data["current_amount"])
+ assert current == pytest.approx(270.0, abs=1.0)
+
+
+async def test_goal_account_tracking_same_currency(
+ client: AsyncClient, auth_headers: dict, test_user: User, test_account: Account
+):
+ """BRL goal linked to a BRL account should show the exact account balance."""
+ response = await client.post(
+ "/api/goals",
+ json={
+ "name": "BRL Account Goal",
+ "target_amount": "10000.00",
+ "currency": "BRL", # Same currency as account
+ "tracking_type": "account",
+ "account_id": str(test_account.id),
+ },
+ headers=auth_headers,
+ )
+ assert response.status_code == 201
+ data = response.json()
+ assert data["currency"] == "BRL"
+ # No conversion needed — should be exact account balance
+ assert float(data["current_amount"]) == 1500.00
+ assert data["percentage"] == 15.0
+
+
+async def test_goal_asset_tracking_eur_goal_usd_asset(
+ client: AsyncClient, auth_headers: dict, test_user: User, session: AsyncSession
+):
+ """EUR goal linked to a USD asset should convert asset value to EUR."""
+ # Seed FX rates: USD→EUR = 0.9
+ today = date.today()
+ session.add(FxRate(
+ base_currency="USD", quote_currency="EUR",
+ date=today, rate=Decimal("0.9"), source="test",
+ ))
+
+ asset = Asset(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ name="US Stock",
+ type="investment",
+ currency="USD",
+ purchase_price=Decimal("8000.00"),
+ )
+ session.add(asset)
+ await session.commit()
+
+ response = await client.post(
+ "/api/goals",
+ json={
+ "name": "EUR Growth from USD",
+ "target_amount": "50000.00",
+ "currency": "EUR", # Goal in EUR, asset in USD
+ "tracking_type": "asset",
+ "asset_id": str(asset.id),
+ },
+ headers=auth_headers,
+ )
+ assert response.status_code == 201
+ data = response.json()
+ assert data["tracking_type"] == "asset"
+ assert data["currency"] == "EUR"
+ assert data["asset_name"] == "US Stock"
+ # USD 8000 * 0.9 = EUR 7200
+ current = float(data["current_amount"])
+ assert current == pytest.approx(7200.0, abs=1.0)
+
+
+async def test_unauthenticated_access(client: AsyncClient):
+ response = await client.get("/api/goals")
+ assert response.status_code == 401
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 5aaaad52..a02b0f1f 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -20,6 +20,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 GoalsPage = lazy(() => import('@/pages/goals'))
const AssetsPage = lazy(() => import('@/pages/assets'))
const ReportsPage = lazy(() => import('@/pages/reports'))
const PayeesPage = lazy(() => import('@/pages/payees'))
@@ -68,6 +69,7 @@ function App() {
<Route path="/rules" element={<RulesPage />} />
<Route path="/categories" element={<CategoriesPage />} />
<Route path="/budgets" element={<BudgetsPage />} />
+ <Route path="/goals" element={<GoalsPage />} />
<Route path="/recurring" element={<RecurringPage />} />
<Route path="/assets" element={<AssetsPage />} />
<Route path="/reports" element={<ReportsPage />} />
diff --git a/frontend/src/components/app-layout.tsx b/frontend/src/components/app-layout.tsx
index df6e65a4..7611ec52 100644
--- a/frontend/src/components/app-layout.tsx
+++ b/frontend/src/components/app-layout.tsx
@@ -30,6 +30,7 @@ import {
ChevronRight,
Tag,
PiggyBank,
+ Target,
Eye,
EyeOff,
Repeat,
@@ -62,6 +63,7 @@ const navItems: NavItem[] = [
{ type: 'link', key: 'assets', path: '/assets', icon: Landmark },
{ type: 'separator', labelKey: 'nav.groupSetup' },
{ type: 'link', key: 'budgets', path: '/budgets', icon: PiggyBank },
+ { type: 'link', key: 'goals', path: '/goals', icon: Target },
{ type: 'link', key: 'recurring', path: '/recurring', icon: Repeat },
{ type: 'link', key: 'categories', path: '/categories', icon: Tag },
{ type: 'link', key: 'payees', path: '/payees', icon: Users },
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index cc3fc626..20565a12 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -22,6 +22,8 @@ import type {
Asset,
AssetValue,
Attachment,
+ Goal,
+ GoalSummary,
DashboardSummary,
SpendingByCategory,
MonthlyTrend,
@@ -453,6 +455,33 @@ export const budgets = {
},
}
+// Goals
+export const goals = {
+ list: async (status?: string): Promise<Goal[]> => {
+ const { data } = await api.get('/goals', { params: { status } })
+ return data
+ },
+ get: async (id: string): Promise<Goal> => {
+ const { data } = await api.get(`/goals/${id}`)
+ return data
+ },
+ create: async (goal: Partial<Goal>): Promise<Goal> => {
+ const { data } = await api.post('/goals', goal)
+ return data
+ },
+ update: async (id: string, goal: Partial<Goal>): Promise<Goal> => {
+ const { data } = await api.patch(`/goals/${id}`, goal)
+ return data
+ },
+ delete: async (id: string): Promise<void> => {
+ await api.delete(`/goals/${id}`)
+ },
+ summary: async (limit = 3): Promise<GoalSummary[]> => {
+ const { data } = await api.get('/goals/summary', { params: { limit } })
+ return data
+ },
+}
+
// Dashboard
export const dashboard = {
summary: async (month?: string, balanceDate?: string): Promise<DashboardSummary> => {
diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.json
index b28e3c53..7c0bb74d 100644
--- a/frontend/src/locales/en.json
+++ b/frontend/src/locales/en.json
@@ -14,6 +14,7 @@
"recurring": "Recurring",
"assets": "Assets",
"payees": "Payees",
+ "goals": "Goals",
"reports": "Reports",
"groupAnalysis": "Analysis",
"groupSetup": "Setup",
@@ -275,6 +276,57 @@
"repeatEveryMonth": "Repeat every month",
"recurringLabel": "Recurring"
},
+ "goals": {
+ "title": "Goals",
+ "add": "Add Goal",
+ "edit": "Edit Goal",
+ "name": "Name",
+ "targetAmount": "Target Amount",
+ "currentAmount": "Current Amount",
+ "currency": "Currency",
+ "targetDate": "Target Date",
+ "trackingType": "Tracking Type",
+ "trackingManual": "Manual",
+ "trackingAccount": "Linked Account",
+ "trackingAsset": "Linked Asset",
+ "trackingNetWorth": "Net Worth",
+ "account": "Account",
+ "selectAccount": "Select account",
+ "asset": "Asset",
+ "selectAsset": "Select asset",
+ "chooseIconColor": "Choose icon & color",
+ "status": "Status",
+ "statusActive": "Active",
+ "statusCompleted": "Completed",
+ "statusPaused": "Paused",
+ "statusArchived": "Archived",
+ "progress": "Progress",
+ "monthlyContribution": "Monthly needed",
+ "onTrack": "On Track",
+ "onTrackAhead": "Ahead",
+ "onTrackOnTrack": "On Track",
+ "onTrackBehind": "Behind",
+ "onTrackOverdue": "Overdue",
+ "onTrackAchieved": "Achieved",
+ "daysRemaining": "{{count}} days left",
+ "daysOverdue": "{{count}} days overdue",
+ "perMonth": "/mo",
+ "icon": "Icon",
+ "color": "Color",
+ "actions": "Actions",
+ "empty": "No goals yet. Create your first goal to start tracking!",
+ "created": "Goal created",
+ "updated": "Goal updated",
+ "deleted": "Goal deleted",
+ "pause": "Pause",
+ "resume": "Resume",
+ "complete": "Mark Complete",
+ "archive": "Archive",
+ "viewAll": "View all goals",
+ "dashboardTitle": "Goals Progress",
+ "noTargetDate": "No deadline",
+ "dashboardEmpty": "No goals yet. Set a target and start tracking your progress!"
+ },
"recurring": {
"title": "Recurring Transactions",
"add": "Add Recurring",
diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.json
index fb4cec88..4f175077 100644
--- a/frontend/src/locales/pt-BR.json
+++ b/frontend/src/locales/pt-BR.json
@@ -14,6 +14,7 @@
"recurring": "Recorrentes",
"assets": "Patrimônio",
"payees": "Beneficiários",
+ "goals": "Metas",
"reports": "Relatórios",
"groupAnalysis": "Análise",
"groupSetup": "Configuração",
@@ -275,6 +276,57 @@
"repeatEveryMonth": "Repetir todo mês",
"recurringLabel": "Recorrente"
},
+ "goals": {
+ "title": "Metas",
+ "add": "Adicionar Meta",
+ "edit": "Editar Meta",
+ "name": "Nome",
+ "targetAmount": "Valor Alvo",
+ "currentAmount": "Valor Atual",
+ "currency": "Moeda",
+ "targetDate": "Data Alvo",
+ "trackingType": "Tipo de Acompanhamento",
+ "trackingManual": "Manual",
+ "trackingAccount": "Conta Vinculada",
+ "trackingAsset": "Ativo Vinculado",
+ "trackingNetWorth": "Patrimônio Líquido",
+ "account": "Conta",
+ "selectAccount": "Selecionar conta",
+ "asset": "Ativo",
+ "selectAsset": "Selecionar ativo",
+ "chooseIconColor": "Escolher ícone e cor",
+ "status": "Status",
+ "statusActive": "Ativa",
+ "statusCompleted": "Concluída",
+ "statusPaused": "Pausada",
+ "statusArchived": "Arquivada",
+ "progress": "Progresso",
+ "monthlyContribution": "Mensal necessário",
+ "onTrack": "Progresso",
+ "onTrackAhead": "Adiantado",
+ "onTrackOnTrack": "No Prazo",
+ "onTrackBehind": "Atrasado",
+ "onTrackOverdue": "Vencido",
+ "onTrackAchieved": "Alcançado",
+ "daysRemaining": "{{count}} dias restantes",
+ "daysOverdue": "{{count}} dias em atraso",
+ "perMonth": "/mês",
+ "icon": "Ícone",
+ "color": "Cor",
+ "actions": "Ações",
+ "empty": "Nenhuma meta ainda. Crie sua primeira meta para começar!",
+ "created": "Meta criada",
+ "updated": "Meta atualizada",
+ "deleted": "Meta excluída",
+ "pause": "Pausar",
+ "resume": "Retomar",
+ "complete": "Marcar Concluída",
+ "archive": "Arquivar",
+ "viewAll": "Ver todas as metas",
+ "dashboardTitle": "Progresso das Metas",
+ "noTargetDate": "Sem prazo",
+ "dashboardEmpty": "Nenhuma meta ainda. Defina um objetivo e comece a acompanhar seu progresso!"
+ },
"recurring": {
"title": "Transações Recorrentes",
"add": "Adicionar Recorrente",
diff --git a/frontend/src/pages/dashboard.tsx b/frontend/src/pages/dashboard.tsx
index e3f323b6..7da4adcb 100644
--- a/frontend/src/pages/dashboard.tsx
+++ b/frontend/src/pages/dashboard.tsx
@@ -3,7 +3,7 @@ import { useTranslation } from 'react-i18next'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { format } from 'date-fns'
import { ptBR, enUS } from 'date-fns/locale'
-import { dashboard, transactions, budgets, categories as categoriesApi, accounts as accountsApi } from '@/lib/api'
+import { dashboard, transactions, budgets, categories as categoriesApi, accounts as accountsApi, goals as goalsApi } from '@/lib/api'
import { Skeleton } from '@/components/ui/skeleton'
import { Button } from '@/components/ui/button'
import { Popover, PopoverTrigger, PopoverContent } from '@/components/ui/popover'
@@ -25,7 +25,9 @@ import {
Tooltip,
ResponsiveContainer,
} from 'recharts'
-import { CheckCircle2, CalendarIcon, Paperclip } from 'lucide-react'
+import { CheckCircle2, CalendarIcon, Paperclip, Target } from 'lucide-react'
+import { Link } from 'react-router-dom'
+import { ICON_MAP } from '@/lib/category-icons'
import { PageHeader } from '@/components/page-header'
import { CategoryIcon } from '@/components/category-icon'
import { TransactionDrillDown, type DrillDownFilter } from '@/components/transaction-drill-down'
@@ -142,6 +144,11 @@ export default function DashboardPage() {
queryFn: () => accountsApi.list(),
})
+ const { data: goalsSummary } = useQuery({
+ queryKey: ['goals', 'summary'],
+ queryFn: () => goalsApi.summary(3),
+ })
+
const updateMutation = useMutation({
mutationFn: ({ id, ...data }: Partial<Transaction> & { id: string }) =>
transactions.update(id, data),
@@ -731,6 +738,77 @@ export default function DashboardPage() {
</div>
</div>
+ {/* Goals Progress Widget */}
+ {goalsSummary && goalsSummary.length > 0 && (
+ <div className="bg-card rounded-xl border border-border shadow-sm mb-5">
+ <div className="px-5 py-4 border-b border-border flex items-center justify-between">
+ <p className="text-sm font-semibold text-foreground">{t('goals.dashboardTitle')}</p>
+ <Link to="/goals" className="text-xs font-medium text-primary hover:underline">
+ {t('goals.viewAll')} &rarr;
+ </Link>
+ </div>
+ <div className="divide-y divide-border">
+ {goalsSummary.map((goal) => {
+ const progressColor = goal.percentage >= 100
+ ? 'bg-emerald-500'
+ : goal.percentage >= 60
+ ? 'bg-blue-500'
+ : goal.percentage >= 30
+ ? 'bg-amber-400'
+ : 'bg-muted-foreground/30'
+ const onTrackConfig: Record<string, { cls: string; key: string }> = {
+ ahead: { cls: 'text-emerald-600', key: 'goals.onTrackAhead' },
+ on_track: { cls: 'text-blue-600', key: 'goals.onTrackOnTrack' },
+ behind: { cls: 'text-amber-600', key: 'goals.onTrackBehind' },
+ overdue: { cls: 'text-rose-600', key: 'goals.onTrackOverdue' },
+ achieved: { cls: 'text-emerald-600', key: 'goals.onTrackAchieved' },
+ }
+ const otc = goal.on_track ? onTrackConfig[goal.on_track] : null
+ const GoalIcon = (goal.icon && ICON_MAP[goal.icon]) || Target
+ return (
+ <div key={goal.id} className="px-5 py-3 flex items-center gap-4">
+ <div
+ className="w-8 h-8 rounded-lg flex items-center justify-center shrink-0 text-white"
+ style={{ backgroundColor: goal.color ?? '#6B7280' }}
+ >
+ <GoalIcon size={14} />
+ </div>
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center justify-between gap-2 mb-1">
+ <span className="text-sm font-medium text-foreground truncate">{goal.name}</span>
+ <span className="text-xs font-bold tabular-nums text-foreground shrink-0">
+ {mask(formatCurrency(goal.current_amount, goal.currency, locale))} / {mask(formatCurrency(goal.target_amount, goal.currency, locale))}
+ </span>
+ </div>
+ <div className="flex items-center gap-2">
+ <div className="flex-1 h-1.5 bg-muted/60 rounded-full overflow-hidden">
+ <div
+ className={`h-full rounded-full transition-all ${progressColor}`}
+ style={{ width: `${Math.min(goal.percentage, 100)}%` }}
+ />
+ </div>
+ <span className="text-[11px] font-bold tabular-nums text-muted-foreground shrink-0">
+ {goal.percentage.toFixed(0)}%
+ </span>
+ </div>
+ <div className="flex items-center gap-3 mt-1 text-[11px] text-muted-foreground">
+ {goal.monthly_contribution != null && goal.monthly_contribution > 0 && (
+ <span className="tabular-nums">
+ {mask(formatCurrency(goal.monthly_contribution, goal.currency, locale))}{t('goals.perMonth')}
+ </span>
+ )}
+ {otc && (
+ <span className={`font-medium ${otc.cls}`}>{t(otc.key)}</span>
+ )}
+ </div>
+ </div>
+ </div>
+ )
+ })}
+ </div>
+ </div>
+ )}
+
{/* Period Transactions */}
<div>
<div className="bg-card rounded-xl border border-border shadow-sm overflow-hidden">
diff --git a/frontend/src/pages/goals.tsx b/frontend/src/pages/goals.tsx
new file mode 100644
index 00000000..b788e277
--- /dev/null
+++ b/frontend/src/pages/goals.tsx
@@ -0,0 +1,565 @@
+import { createElement, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
+import { goals as goalsApi, accounts as accountsApi, assets as assetsApi, currencies as currenciesApi } 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 {
+ Popover,
+ PopoverTrigger,
+ PopoverContent,
+} from '@/components/ui/popover'
+import type { Goal } from '@/types'
+import {
+ Pencil, Trash2, Plus, Pause, Play, CheckCircle2, Archive, Target,
+ ChevronDown,
+} from 'lucide-react'
+import { ICON_MAP } from '@/lib/category-icons'
+import { IconPicker } from '@/components/icon-picker'
+import { PageHeader } from '@/components/page-header'
+import { usePrivacyMode } from '@/hooks/use-privacy-mode'
+import { useAuth } from '@/contexts/auth-context'
+
+function formatCurrency(value: number, currency = 'USD', locale = 'en-US') {
+ return new Intl.NumberFormat(locale, { style: 'currency', currency }).format(value)
+}
+
+function getGoalIcon(iconKey: string | null) {
+ return (iconKey && ICON_MAP[iconKey]) || Target
+}
+
+const PRESET_COLORS = [
+ '#3B82F6', '#10B981', '#F59E0B', '#EF4444',
+ '#8B5CF6', '#EC4899', '#06B6D4', '#F97316',
+]
+
+function SectionCard({ children }: { children: React.ReactNode }) {
+ return (
+ <div className="bg-card rounded-xl border border-border shadow-sm overflow-hidden">
+ {children}
+ </div>
+ )
+}
+function SectionHeader({ title, action }: { title: string; action?: React.ReactNode }) {
+ return (
+ <div className="px-4 sm:px-5 py-4 border-b border-border flex flex-wrap items-center justify-between gap-2">
+ <p className="text-sm font-semibold text-foreground">{title}</p>
+ {action}
+ </div>
+ )
+}
+
+function OnTrackBadge({ status, t }: { status: string | null; t: (key: string) => string }) {
+ if (!status) return null
+ const config: Record<string, { bg: string; text: string; key: string }> = {
+ ahead: { bg: 'bg-emerald-100 dark:bg-emerald-500/20', text: 'text-emerald-700 dark:text-emerald-400', key: 'goals.onTrackAhead' },
+ on_track: { bg: 'bg-blue-100 dark:bg-blue-500/20', text: 'text-blue-700 dark:text-blue-400', key: 'goals.onTrackOnTrack' },
+ behind: { bg: 'bg-amber-100 dark:bg-amber-500/20', text: 'text-amber-700 dark:text-amber-400', key: 'goals.onTrackBehind' },
+ overdue: { bg: 'bg-rose-100 dark:bg-rose-500/20', text: 'text-rose-700 dark:text-rose-400', key: 'goals.onTrackOverdue' },
+ achieved: { bg: 'bg-emerald-100 dark:bg-emerald-500/20', text: 'text-emerald-700 dark:text-emerald-400', key: 'goals.onTrackAchieved' },
+ }
+ const c = config[status]
+ if (!c) return null
+ return (
+ <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-bold ${c.bg} ${c.text}`}>
+ {t(c.key)}
+ </span>
+ )
+}
+
+function StatusBadge({ status, t }: { status: string; t: (key: string) => string }) {
+ const config: Record<string, { bg: string; text: string; key: string }> = {
+ active: { bg: 'bg-emerald-100 dark:bg-emerald-500/20', text: 'text-emerald-700 dark:text-emerald-400', key: 'goals.statusActive' },
+ completed: { bg: 'bg-blue-100 dark:bg-blue-500/20', text: 'text-blue-700 dark:text-blue-400', key: 'goals.statusCompleted' },
+ paused: { bg: 'bg-amber-100 dark:bg-amber-500/20', text: 'text-amber-700 dark:text-amber-400', key: 'goals.statusPaused' },
+ archived: { bg: 'bg-muted', text: 'text-muted-foreground', key: 'goals.statusArchived' },
+ }
+ const c = config[status] ?? config.active
+ return (
+ <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-bold ${c.bg} ${c.text}`}>
+ {t(c.key)}
+ </span>
+ )
+}
+
+function daysUntil(dateStr: string): number {
+ const target = new Date(dateStr + 'T00:00:00')
+ const today = new Date()
+ today.setHours(0, 0, 0, 0)
+ return Math.ceil((target.getTime() - today.getTime()) / (1000 * 60 * 60 * 24))
+}
+
+export default function GoalsPage() {
+ const { t, i18n } = useTranslation()
+ const { mask } = usePrivacyMode()
+ const { user } = useAuth()
+ const userCurrency = user?.preferences?.currency_display ?? 'USD'
+ const locale = i18n.language === 'en' ? 'en-US' : i18n.language
+ const queryClient = useQueryClient()
+ const [dialogOpen, setDialogOpen] = useState(false)
+ const [editing, setEditing] = useState<Goal | null>(null)
+ const [trackingType, setTrackingType] = useState('manual')
+ const [statusFilter, setStatusFilter] = useState<string>('active')
+ const [selectedIcon, setSelectedIcon] = useState('target')
+ const [selectedColor, setSelectedColor] = useState('#3B82F6')
+
+ const { data: goalsList } = useQuery({
+ queryKey: ['goals', statusFilter],
+ queryFn: () => goalsApi.list(statusFilter || undefined),
+ })
+
+ const { data: accountsList } = useQuery({
+ queryKey: ['accounts'],
+ queryFn: () => accountsApi.list(),
+ })
+
+ const { data: assetsList } = useQuery({
+ queryKey: ['assets'],
+ queryFn: () => assetsApi.list(),
+ })
+
+ const { data: supportedCurrencies } = useQuery({
+ queryKey: ['currencies'],
+ queryFn: currenciesApi.list,
+ staleTime: Infinity,
+ })
+
+ const createMutation = useMutation({
+ mutationFn: (data: Partial<Goal>) => goalsApi.create(data),
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: ['goals'] })
+ setDialogOpen(false)
+ toast.success(t('goals.created'))
+ },
+ onError: () => toast.error(t('common.error')),
+ })
+
+ const updateMutation = useMutation({
+ mutationFn: ({ id, ...data }: Partial<Goal> & { id: string }) => goalsApi.update(id, data),
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: ['goals'] })
+ setDialogOpen(false)
+ setEditing(null)
+ toast.success(t('goals.updated'))
+ },
+ onError: () => toast.error(t('common.error')),
+ })
+
+ const deleteMutation = useMutation({
+ mutationFn: (id: string) => goalsApi.delete(id),
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: ['goals'] })
+ toast.success(t('goals.deleted'))
+ },
+ })
+
+ const statusMutation = useMutation({
+ mutationFn: ({ id, status }: { id: string; status: string }) => goalsApi.update(id, { status } as Partial<Goal>),
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: ['goals'] })
+ toast.success(t('goals.updated'))
+ },
+ })
+
+ const openCreateDialog = () => {
+ setEditing(null)
+ setTrackingType('manual')
+ setSelectedIcon('target')
+ setSelectedColor('#3B82F6')
+ setDialogOpen(true)
+ }
+
+ const openEditDialog = (goal: Goal) => {
+ setEditing(goal)
+ setTrackingType(goal.tracking_type)
+ setSelectedIcon(goal.icon ?? 'target')
+ setSelectedColor(goal.color ?? '#3B82F6')
+ setDialogOpen(true)
+ }
+
+ return (
+ <div>
+ <PageHeader
+ section={t('goals.title')}
+ title={t('goals.title')}
+ />
+
+ {/* Status filter */}
+ <div className="flex items-center gap-2 mb-4">
+ {['active', 'completed', 'paused', 'archived', ''].map((s) => (
+ <button
+ key={s}
+ onClick={() => setStatusFilter(s)}
+ className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${
+ statusFilter === s
+ ? 'bg-primary text-primary-foreground'
+ : 'bg-muted text-muted-foreground hover:text-foreground'
+ }`}
+ >
+ {s ? t(`goals.status${s.charAt(0).toUpperCase() + s.slice(1)}`) : t('transactions.all')}
+ </button>
+ ))}
+ </div>
+
+ <SectionCard>
+ <SectionHeader
+ title={t('goals.title')}
+ action={
+ <Button size="sm" className="gap-1.5 h-8" onClick={openCreateDialog}>
+ <Plus size={13} /> {t('goals.add')}
+ </Button>
+ }
+ />
+ {goalsList && goalsList.length > 0 ? (
+ <div className="divide-y divide-border">
+ {goalsList.map((goal) => {
+ const days = goal.target_date ? daysUntil(goal.target_date) : null
+ const progressColor = goal.percentage >= 100
+ ? 'bg-emerald-500'
+ : goal.percentage >= 60
+ ? 'bg-blue-500'
+ : goal.percentage >= 30
+ ? 'bg-amber-400'
+ : 'bg-muted-foreground/30'
+
+ const GoalIcon = getGoalIcon(goal.icon)
+ return (
+ <div key={goal.id} className="px-4 sm:px-5 py-4 hover:bg-muted/50 transition-colors">
+ <div className="flex items-start gap-4">
+ {/* Icon */}
+ <div
+ className="w-10 h-10 rounded-xl flex items-center justify-center shrink-0 text-white"
+ style={{ backgroundColor: goal.color ?? '#6B7280' }}
+ >
+ <GoalIcon size={18} />
+ </div>
+
+ {/* Content */}
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center gap-2 mb-1">
+ <span className="text-sm font-semibold text-foreground truncate">{goal.name}</span>
+ <StatusBadge status={goal.status} t={t} />
+ <OnTrackBadge status={goal.on_track} t={t} />
+ </div>
+
+ {/* Progress bar */}
+ <div className="flex items-center gap-3 mb-1.5">
+ <div className="flex-1 h-2 bg-muted/60 rounded-full overflow-hidden">
+ <div
+ className={`h-full rounded-full transition-all ${progressColor}`}
+ style={{ width: `${Math.min(goal.percentage, 100)}%` }}
+ />
+ </div>
+ <span className="text-xs font-bold tabular-nums text-foreground shrink-0">
+ {goal.percentage.toFixed(0)}%
+ </span>
+ </div>
+
+ {/* Details row */}
+ <div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-muted-foreground">
+ <span className="tabular-nums font-medium">
+ {mask(formatCurrency(goal.current_amount, goal.currency, locale))}
+ {' / '}
+ {mask(formatCurrency(goal.target_amount, goal.currency, locale))}
+ </span>
+ {goal.monthly_contribution != null && goal.monthly_contribution > 0 && (
+ <span className="tabular-nums">
+ {mask(formatCurrency(goal.monthly_contribution, goal.currency, locale))}{t('goals.perMonth')}
+ </span>
+ )}
+ {days !== null && (
+ <span className={days < 0 ? 'text-rose-500' : ''}>
+ {days >= 0
+ ? t('goals.daysRemaining', { count: days })
+ : t('goals.daysOverdue', { count: Math.abs(days) })}
+ </span>
+ )}
+ {!goal.target_date && (
+ <span>{t('goals.noTargetDate')}</span>
+ )}
+ {goal.account_name && (
+ <span>{goal.account_name}</span>
+ )}
+ {goal.asset_name && (
+ <span>{goal.asset_name}</span>
+ )}
+ </div>
+ </div>
+
+ {/* Actions */}
+ <div className="flex items-center gap-1 shrink-0">
+ {goal.status === 'active' && (
+ <button
+ className="p-1.5 rounded-md text-muted-foreground hover:text-amber-500 hover:bg-amber-50 dark:hover:bg-amber-500/10 transition-colors"
+ onClick={() => statusMutation.mutate({ id: goal.id, status: 'paused' })}
+ title={t('goals.pause')}
+ >
+ <Pause size={13} />
+ </button>
+ )}
+ {goal.status === 'paused' && (
+ <button
+ className="p-1.5 rounded-md text-muted-foreground hover:text-emerald-500 hover:bg-emerald-50 dark:hover:bg-emerald-500/10 transition-colors"
+ onClick={() => statusMutation.mutate({ id: goal.id, status: 'active' })}
+ title={t('goals.resume')}
+ >
+ <Play size={13} />
+ </button>
+ )}
+ {(goal.status === 'active' || goal.status === 'paused') && (
+ <button
+ className="p-1.5 rounded-md text-muted-foreground hover:text-blue-500 hover:bg-blue-50 dark:hover:bg-blue-500/10 transition-colors"
+ onClick={() => statusMutation.mutate({ id: goal.id, status: 'completed' })}
+ title={t('goals.complete')}
+ >
+ <CheckCircle2 size={13} />
+ </button>
+ )}
+ {goal.status !== 'archived' && (
+ <button
+ className="p-1.5 rounded-md text-muted-foreground hover:text-muted-foreground/80 hover:bg-muted transition-colors"
+ onClick={() => statusMutation.mutate({ id: goal.id, status: 'archived' })}
+ title={t('goals.archive')}
+ >
+ <Archive size={13} />
+ </button>
+ )}
+ <button
+ className="p-1.5 rounded-md text-muted-foreground hover:text-primary hover:bg-primary/5 transition-colors"
+ onClick={() => openEditDialog(goal)}
+ >
+ <Pencil size={13} />
+ </button>
+ <button
+ className="p-1.5 rounded-md text-muted-foreground hover:text-rose-500 hover:bg-rose-50 dark:hover:bg-rose-500/10 transition-colors"
+ onClick={() => deleteMutation.mutate(goal.id)}
+ disabled={deleteMutation.isPending}
+ >
+ <Trash2 size={13} />
+ </button>
+ </div>
+ </div>
+ </div>
+ )
+ })}
+ </div>
+ ) : (
+ <p className="text-sm text-muted-foreground text-center py-10">{t('goals.empty')}</p>
+ )}
+ </SectionCard>
+
+ {/* Create/Edit Dialog */}
+ <Dialog open={dialogOpen} onOpenChange={() => { setDialogOpen(false); setEditing(null) }}>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>{editing ? t('goals.edit') : t('goals.add')}</DialogTitle>
+ </DialogHeader>
+ <form
+ key={editing?.id ?? 'new'}
+ onSubmit={(e) => {
+ e.preventDefault()
+ const formData = new FormData(e.currentTarget)
+ const payload: Record<string, unknown> = {
+ name: formData.get('name') as string,
+ target_amount: parseFloat(formData.get('target_amount') as string),
+ currency: (formData.get('currency') as string) || userCurrency,
+ tracking_type: formData.get('tracking_type') as string,
+ target_date: (formData.get('target_date') as string) || null,
+ icon: selectedIcon || null,
+ color: selectedColor || null,
+ }
+
+ const tt = formData.get('tracking_type') as string
+ if (tt === 'manual') {
+ payload.current_amount = parseFloat((formData.get('current_amount') as string) || '0')
+ }
+ if (tt === 'account') {
+ payload.account_id = (formData.get('account_id') as string) || null
+ }
+ if (tt === 'asset') {
+ payload.asset_id = (formData.get('asset_id') as string) || null
+ }
+
+ if (editing) {
+ updateMutation.mutate({ id: editing.id, ...payload } as Partial<Goal> & { id: string })
+ } else {
+ createMutation.mutate(payload as Partial<Goal>)
+ }
+ }}
+ className="space-y-4"
+ >
+ <div className="space-y-2">
+ <Label>{t('goals.name')}</Label>
+ <Input name="name" defaultValue={editing?.name ?? ''} required />
+ </div>
+
+ <div className="grid grid-cols-2 gap-4">
+ <div className="space-y-2">
+ <Label>{t('goals.targetAmount')}</Label>
+ <Input
+ name="target_amount"
+ type="number"
+ step="0.01"
+ defaultValue={editing?.target_amount?.toString() ?? ''}
+ required
+ />
+ </div>
+ <div className="space-y-2">
+ <Label>{t('goals.currency')}</Label>
+ <select
+ name="currency"
+ defaultValue={editing?.currency ?? userCurrency}
+ className="w-full border border-border rounded-lg px-3 py-2 text-sm bg-card text-foreground focus:outline-none focus:ring-2 focus:ring-primary"
+ >
+ {supportedCurrencies?.map((c: { code: string; name: string; flag: string }) => (
+ <option key={c.code} value={c.code}>
+ {c.flag} {c.name} ({c.code})
+ </option>
+ ))}
+ </select>
+ </div>
+ </div>
+
+ <div className="space-y-2">
+ <Label>{t('goals.targetDate')}</Label>
+ <Input
+ name="target_date"
+ type="date"
+ defaultValue={editing?.target_date ?? ''}
+ />
+ </div>
+
+ <div className="space-y-2">
+ <Label>{t('goals.trackingType')}</Label>
+ <select
+ name="tracking_type"
+ value={trackingType}
+ onChange={(e) => setTrackingType(e.target.value)}
+ className="w-full border border-border rounded-lg px-3 py-2 text-sm bg-card text-foreground focus:outline-none focus:ring-2 focus:ring-primary"
+ >
+ <option value="manual">{t('goals.trackingManual')}</option>
+ <option value="account">{t('goals.trackingAccount')}</option>
+ <option value="asset">{t('goals.trackingAsset')}</option>
+ <option value="net_worth">{t('goals.trackingNetWorth')}</option>
+ </select>
+ </div>
+
+ {trackingType === 'manual' && (
+ <div className="space-y-2">
+ <Label>{t('goals.currentAmount')}</Label>
+ <Input
+ name="current_amount"
+ type="number"
+ step="0.01"
+ defaultValue={editing?.tracking_type === 'manual' ? editing?.current_amount?.toString() : '0'}
+ />
+ </div>
+ )}
+
+ {trackingType === 'account' && (
+ <div className="space-y-2">
+ <Label>{t('goals.account')}</Label>
+ <select
+ name="account_id"
+ defaultValue={editing?.account_id ?? ''}
+ className="w-full border border-border rounded-lg px-3 py-2 text-sm bg-card text-foreground focus:outline-none focus:ring-2 focus:ring-primary"
+ required
+ >
+ <option value="">{t('goals.selectAccount')}</option>
+ {accountsList?.map((acc) => (
+ <option key={acc.id} value={acc.id}>
+ {acc.name} ({acc.currency})
+ </option>
+ ))}
+ </select>
+ </div>
+ )}
+
+ {trackingType === 'asset' && (
+ <div className="space-y-2">
+ <Label>{t('goals.asset')}</Label>
+ <select
+ name="asset_id"
+ defaultValue={editing?.asset_id ?? ''}
+ className="w-full border border-border rounded-lg px-3 py-2 text-sm bg-card text-foreground focus:outline-none focus:ring-2 focus:ring-primary"
+ required
+ >
+ <option value="">{t('goals.selectAsset')}</option>
+ {assetsList?.map((asset: { id: string; name: string; currency: string }) => (
+ <option key={asset.id} value={asset.id}>
+ {asset.name} ({asset.currency})
+ </option>
+ ))}
+ </select>
+ </div>
+ )}
+
+ {/* Icon & Color */}
+ <div className="space-y-2">
+ <Label>{t('goals.icon')}</Label>
+ <Popover>
+ <PopoverTrigger asChild>
+ <button
+ type="button"
+ className="w-full flex items-center gap-3 border border-border rounded-lg px-3 py-2 text-sm bg-card hover:bg-muted/50 transition-colors text-left"
+ >
+ <div
+ className="w-9 h-9 rounded-lg flex items-center justify-center shrink-0 text-white"
+ style={{ backgroundColor: selectedColor }}
+ >
+ {createElement(getGoalIcon(selectedIcon), { size: 18 })}
+ </div>
+ <span className="flex-1 text-muted-foreground">{t('goals.chooseIconColor')}</span>
+ <ChevronDown size={14} className="text-muted-foreground" />
+ </button>
+ </PopoverTrigger>
+ <PopoverContent align="start" className="w-80 p-3 space-y-3">
+ {/* Color presets */}
+ <div className="flex items-center gap-1.5">
+ {PRESET_COLORS.map((c) => (
+ <button
+ key={c}
+ type="button"
+ onClick={() => setSelectedColor(c)}
+ className={`w-7 h-7 rounded-full transition-all ${
+ selectedColor === c ? 'ring-2 ring-offset-1 ring-primary scale-110' : 'hover:scale-110'
+ }`}
+ style={{ backgroundColor: c }}
+ />
+ ))}
+ <input
+ type="color"
+ value={selectedColor}
+ onChange={(e) => setSelectedColor(e.target.value)}
+ className="w-7 h-7 rounded-full cursor-pointer border-0 p-0"
+ />
+ </div>
+ {/* Icon picker */}
+ <IconPicker value={selectedIcon} color={selectedColor} onChange={setSelectedIcon} />
+ </PopoverContent>
+ </Popover>
+ </div>
+
+ <DialogFooter>
+ <Button type="button" variant="outline" onClick={() => { setDialogOpen(false); setEditing(null) }}>
+ {t('common.cancel')}
+ </Button>
+ <Button type="submit" disabled={createMutation.isPending || updateMutation.isPending}>
+ {t('common.save')}
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+ </div>
+ )
+}
diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts
index 3fedd102..40d942f6 100644
--- a/frontend/src/types/index.ts
+++ b/frontend/src/types/index.ts
@@ -310,6 +310,48 @@ export interface AssetValue {
source: string
}
+export interface Goal {
+ id: string
+ user_id: string
+ name: string
+ target_amount: number
+ current_amount: number
+ currency: string
+ target_amount_primary: number | null
+ current_amount_primary: number | null
+ target_date: string | null
+ tracking_type: 'manual' | 'account' | 'asset' | 'net_worth'
+ account_id: string | null
+ asset_id: string | null
+ status: 'active' | 'completed' | 'paused' | 'archived'
+ icon: string | null
+ color: string | null
+ position: number
+ metadata_json: Record<string, unknown> | null
+ created_at: string
+ updated_at: string
+ percentage: number
+ monthly_contribution: number | null
+ on_track: 'ahead' | 'on_track' | 'behind' | 'overdue' | 'achieved' | null
+ account_name: string | null
+ asset_name: string | null
+}
+
+export interface GoalSummary {
+ id: string
+ name: string
+ target_amount: number
+ current_amount: number
+ currency: string
+ target_date: string | null
+ status: string
+ icon: string | null
+ color: string | null
+ percentage: number
+ monthly_contribution: number | null
+ on_track: string | null
+}
+
export interface PaginatedResponse<T> {
items: T[]
total: number