Open-source personal finance manager. Self-hosted, privacy-first.
feat(assets): investment ledger — ticker grouping, average price, holdings vs transactions (#235) (#308)
Tássio Noronha2ad8269fc307
diff --git a/backend/alembic/versions/059_asset_transactions.py b/backend/alembic/versions/059_asset_transactions.pynew file mode 100644index 00000000..95197f4d--- /dev/null+++ b/backend/alembic/versions/059_asset_transactions.py@@ -0,0 +1,131 @@+"""add asset_transactions ledger + cached average_price/realized_gain++Revision ID: 059+Revises: 058+Create Date: 2026-06-10++Introduces a buy/sell ledger for market-priced holdings so a position can be+consolidated by ticker with a weighted-average cost (preço médio) and a+separate transactions view (issue #235).++Purely additive: a new `asset_transactions` table plus two nullable cache+columns on `assets` (`average_price`, `realized_gain`). No existing column is+dropped or overwritten; `asset_values` history is untouched. The backfill only+reads existing `purchase_price`/`units`/`purchase_date`/`sell_*` to reconstruct+the initial buy (and a sell when the holding was already sold), so existing+displayed numbers stay identical. Synced (valuation_method='manual') holdings+are not touched.+"""+from typing import Sequence, Union++import sqlalchemy as sa+from alembic import op++revision: str = "059"+down_revision: Union[str, None] = "058"+branch_labels: Union[str, Sequence[str], None] = None+depends_on: Union[str, Sequence[str], None] = None+++def upgrade() -> None:+ op.create_table(+ "asset_transactions",+ sa.Column("id", sa.UUID(), primary_key=True),+ sa.Column(+ "asset_id",+ sa.UUID(),+ sa.ForeignKey("assets.id", ondelete="CASCADE"),+ nullable=False,+ ),+ sa.Column(+ "workspace_id",+ sa.UUID(),+ sa.ForeignKey("workspaces.id", ondelete="CASCADE"),+ nullable=False,+ ),+ sa.Column("kind", sa.String(8), nullable=False), # buy, sell+ sa.Column("quantity", sa.Numeric(precision=18, scale=6), nullable=False),+ sa.Column("price", sa.Numeric(precision=18, scale=6), nullable=False),+ sa.Column("fee", sa.Numeric(precision=15, scale=2), nullable=False, server_default="0"),+ sa.Column("date", sa.Date(), nullable=False),+ sa.Column("source", sa.String(20), nullable=False, server_default="manual"),+ sa.Column("external_id", sa.String(255), nullable=True),+ sa.Column("notes", sa.String(500), nullable=True),+ sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("now()")),+ )+ op.create_index("ix_asset_transactions_asset_id", "asset_transactions", ["asset_id"])+ op.create_index("ix_asset_transactions_workspace_id", "asset_transactions", ["workspace_id"])+ op.create_index("ix_asset_transactions_date", "asset_transactions", ["date"])++ op.add_column("assets", sa.Column("average_price", sa.Numeric(precision=18, scale=6), nullable=True))+ op.add_column("assets", sa.Column("realized_gain", sa.Numeric(precision=18, scale=2), nullable=True))++ bind = op.get_bind()++ # Reconstruct an initial buy from each market-priced holding that has a+ # known cost basis. `purchase_price` is the *total* paid, so per-share+ # price = purchase_price / units. Source 'import' flags the backfill.+ bind.execute(+ sa.text(+ """+ INSERT INTO asset_transactions+ (id, asset_id, workspace_id, kind, quantity, price, fee, date, source, created_at)+ SELECT gen_random_uuid(), a.id, a.workspace_id, 'buy', a.units,+ ROUND(a.purchase_price / a.units, 6), 0,+ COALESCE(a.purchase_date, CURRENT_DATE), 'import', now()+ FROM assets a+ WHERE a.valuation_method = 'market_price'+ AND a.units IS NOT NULL AND a.units > 0+ AND a.purchase_price IS NOT NULL+ """+ )+ )++ # Holdings that were already fully sold get a matching sell entry.+ bind.execute(+ sa.text(+ """+ INSERT INTO asset_transactions+ (id, asset_id, workspace_id, kind, quantity, price, fee, date, source, created_at)+ SELECT gen_random_uuid(), a.id, a.workspace_id, 'sell', a.units,+ ROUND(a.sell_price / a.units, 6), 0,+ a.sell_date, 'import', now()+ FROM assets a+ WHERE a.valuation_method = 'market_price'+ AND a.units IS NOT NULL AND a.units > 0+ AND a.sell_price IS NOT NULL AND a.sell_date IS NOT NULL+ """+ )+ )++ # Cache the derived average price (preço médio) and realized gain.+ bind.execute(+ sa.text(+ """+ UPDATE assets a+ SET average_price = ROUND(a.purchase_price / a.units, 6)+ WHERE a.valuation_method = 'market_price'+ AND a.units IS NOT NULL AND a.units > 0+ AND a.purchase_price IS NOT NULL+ """+ )+ )+ bind.execute(+ sa.text(+ """+ UPDATE assets a+ SET realized_gain = a.sell_price - a.purchase_price+ WHERE a.valuation_method = 'market_price'+ AND a.sell_price IS NOT NULL AND a.purchase_price IS NOT NULL+ """+ )+ )+++def downgrade() -> None:+ op.drop_column("assets", "realized_gain")+ op.drop_column("assets", "average_price")+ op.drop_index("ix_asset_transactions_date", "asset_transactions")+ op.drop_index("ix_asset_transactions_workspace_id", "asset_transactions")+ op.drop_index("ix_asset_transactions_asset_id", "asset_transactions")+ op.drop_table("asset_transactions")diff --git a/backend/app/api/assets.py b/backend/app/api/assets.pyindex b36ad3c3..34747c69 100644--- a/backend/app/api/assets.py+++ b/backend/app/api/assets.py@@ -18,15 +18,19 @@ from app.providers.market_price import (get_market_price_provider,)from app.schemas.asset import (+ AssetBuyCreate,AssetCreate,AssetRead,+ AssetTransactionCreate,+ AssetTransactionRead,+ AssetTransactionUpdate,AssetUpdate,AssetValueCreate,AssetValueRead,MarketSymbolMatch,MarketSymbolQuote,)-from app.services import asset_service+from app.services import asset_service, asset_transaction_servicefrom app.services.fx_rate_service import convertlogger = logging.getLogger(__name__)@@ -186,6 +190,107 @@ async def portfolio_trend(return await asset_service.get_portfolio_trend(session, ctx.workspace.id, ctx.user_id)+# ----------------------------------------------------------------------------+# Transaction ledger (issue #235)+# ----------------------------------------------------------------------------+#+# These specific routes are declared before the `/{asset_id}` catch-all so a+# path like `/transactions` is never swallowed by the UUID param.++[email protected]("/transactions", response_model=list[AssetTransactionRead])+async def list_workspace_transactions(+ ticker: str | None = Query(None, max_length=32),+ kind: str | None = Query(None, pattern="^(buy|sell)$"),+ limit: int = Query(500, ge=1, le=2000),+ ctx: WorkspaceContext = Depends(current_workspace),+ session: AsyncSession = Depends(get_async_session),+):+ """All buy/sell transactions in the workspace — powers the Transactions tab."""+ return await asset_transaction_service.list_workspace_transactions(+ session, ctx.workspace.id, ticker=ticker, kind=kind, limit=limit+ )++[email protected]("/buy", response_model=AssetRead, status_code=status.HTTP_201_CREATED)+async def buy_into_holding(+ data: AssetBuyCreate,+ ctx: WorkspaceContext = Depends(current_writable_workspace),+ session: AsyncSession = Depends(get_async_session),+):+ """Record a buy, consolidating onto the existing ticker holding (in the+ chosen wallet) or creating a new market-priced one."""+ try:+ return await asset_transaction_service.buy_into_holding(+ session, ctx.workspace.id, ctx.user_id, data+ )+ except MarketPriceRateLimitedError:+ raise HTTPException(+ status_code=status.HTTP_429_TOO_MANY_REQUESTS,+ detail="Market data provider is currently rate-limiting. Try again in a minute.",+ )++[email protected]("/{asset_id}/transactions", response_model=list[AssetTransactionRead])+async def list_asset_transactions(+ asset_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(current_workspace),+ session: AsyncSession = Depends(get_async_session),+):+ txs = await asset_transaction_service.list_asset_transactions(+ session, asset_id, ctx.workspace.id+ )+ if txs is None:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Asset not found")+ return txs+++ "/{asset_id}/transactions", response_model=AssetRead, status_code=status.HTTP_201_CREATED+)+async def add_asset_transaction(+ asset_id: uuid.UUID,+ data: AssetTransactionCreate,+ ctx: WorkspaceContext = Depends(current_writable_workspace),+ session: AsyncSession = Depends(get_async_session),+):+ asset = await asset_transaction_service.add_transaction(+ session, asset_id, ctx.workspace.id, data+ )+ if asset is None:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Asset not found")+ return asset++[email protected]("/transactions/{tx_id}", response_model=AssetRead)+async def update_asset_transaction(+ tx_id: uuid.UUID,+ data: AssetTransactionUpdate,+ ctx: WorkspaceContext = Depends(current_writable_workspace),+ session: AsyncSession = Depends(get_async_session),+):+ asset = await asset_transaction_service.update_transaction(+ session, tx_id, ctx.workspace.id, data+ )+ if asset is None:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Transaction not found")+ return asset++[email protected]("/transactions/{tx_id}", response_model=AssetRead)+async def delete_asset_transaction(+ tx_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(current_writable_workspace),+ session: AsyncSession = Depends(get_async_session),+):+ asset = await asset_transaction_service.delete_transaction(+ session, tx_id, ctx.workspace.id+ )+ if asset is None:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Transaction not found")+ return asset++@router.get("/{asset_id}", response_model=AssetRead)async def get_asset(asset_id: uuid.UUID,diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.pyindex 7087066a..741f1bcf 100644--- a/backend/app/models/__init__.py+++ b/backend/app/models/__init__.py@@ -11,6 +11,7 @@ from app.models.budget import Budgetfrom app.models.import_log import ImportLogfrom app.models.asset import Assetfrom app.models.asset_group import AssetGroup+from app.models.asset_transaction import AssetTransactionfrom app.models.asset_value import AssetValuefrom app.models.fx_rate import FxRatefrom app.models.transaction_attachment import TransactionAttachment@@ -43,6 +44,7 @@ __all__ = ["ImportLog","Asset","AssetGroup",+ "AssetTransaction","AssetValue","FxRate","TransactionAttachment",diff --git a/backend/app/models/asset.py b/backend/app/models/asset.pyindex fe6ea0a5..1fde64c8 100644--- a/backend/app/models/asset.py+++ b/backend/app/models/asset.py@@ -11,6 +11,7 @@ from app.core.database import Baseif TYPE_CHECKING:from app.models.asset_group import AssetGroup+ from app.models.asset_transaction import AssetTransactionfrom app.models.asset_value import AssetValue@@ -67,10 +68,25 @@ class Asset(Base):Numeric(precision=18, scale=6), nullable=True)last_price_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)+ # Weighted-average cost per unit (preço médio), derived from the+ # asset_transactions ledger and cached here for cheap list reads. For+ # ledger-backed holdings `purchase_price` caches the total cost basis of+ # the currently-held units, so `gain_loss = current_value - purchase_price`+ # stays meaningful as the unrealized gain (issue #235).+ average_price: Mapped[Optional[Decimal]] = mapped_column(+ Numeric(precision=18, scale=6), nullable=True+ )+ # Cumulative realized gain/loss from sell transactions, in asset currency.+ realized_gain: Mapped[Optional[Decimal]] = mapped_column(+ Numeric(precision=18, scale=2), nullable=True+ )# Fully-formed logo URL — populated at create time for market-priced# assets when a logo provider is configured. Null means "no logo, use# the type icon". Frontend swaps to the type icon on <img> load error.logo_url: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)values: Mapped[list["AssetValue"]] = relationship(back_populates="asset", cascade="all, delete-orphan")+ transactions: Mapped[list["AssetTransaction"]] = relationship(+ back_populates="asset", cascade="all, delete-orphan"+ )group: Mapped[Optional["AssetGroup"]] = relationship(back_populates="assets")diff --git a/backend/app/models/asset_transaction.py b/backend/app/models/asset_transaction.pynew file mode 100644index 00000000..191549c1--- /dev/null+++ b/backend/app/models/asset_transaction.py@@ -0,0 +1,45 @@+import uuid+from datetime import date, datetime+from decimal import Decimal+from typing import TYPE_CHECKING, Optional++from sqlalchemy import Date, DateTime, ForeignKey, Numeric, String, func+from sqlalchemy.dialects.postgresql import UUID+from sqlalchemy.orm import Mapped, mapped_column, relationship++from app.core.database import Base++if TYPE_CHECKING:+ from app.models.asset import Asset+++class AssetTransaction(Base):+ """A single buy/sell entry in an asset's ledger.++ Transactions are the source of truth for a market-priced holding: the+ asset's current `units`, `average_price` (preço médio) and cost basis are+ derived by replaying the ledger in date order (see+ `asset_transaction_service.recompute_position`). This is what powers+ ticker-grouped holdings + a separate transactions view (issue #235).+ """++ __tablename__ = "asset_transactions"++ 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"), index=True+ )+ workspace_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True), ForeignKey("workspaces.id", ondelete="CASCADE"), index=True+ )+ kind: Mapped[str] = mapped_column(String(8)) # buy, sell+ quantity: Mapped[Decimal] = mapped_column(Numeric(precision=18, scale=6))+ price: Mapped[Decimal] = mapped_column(Numeric(precision=18, scale=6)) # per-share, asset currency+ fee: Mapped[Decimal] = mapped_column(Numeric(precision=15, scale=2), default=Decimal("0"))+ date: Mapped[date] = mapped_column(Date, index=True)+ source: Mapped[str] = mapped_column(String(20), default="manual") # manual, import, pluggy+ external_id: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)+ notes: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())++ asset: Mapped["Asset"] = relationship(back_populates="transactions")diff --git a/backend/app/schemas/asset.py b/backend/app/schemas/asset.pyindex a25800be..84066219 100644--- a/backend/app/schemas/asset.py+++ b/backend/app/schemas/asset.py@@ -87,6 +87,65 @@ class AssetRead(BaseModel):last_price: Optional[float] = Nonelast_price_at: Optional[datetime] = Nonelogo_url: Optional[str] = None+ # Ledger-derived fields (issue #235). average_price = weighted-average cost+ # per unit (preço médio); total_invested = cost basis of the held units;+ # realized_gain = cumulative gain/loss from sells; transaction_count lets+ # the UI know whether a holding is ledger-backed.+ average_price: Optional[float] = None+ total_invested: Optional[float] = None+ realized_gain: Optional[float] = None+ transaction_count: int = 0++ model_config = ConfigDict(from_attributes=True)+++class AssetTransactionCreate(BaseModel):+ kind: str # buy | sell+ quantity: Decimal+ price: Decimal+ fee: Decimal = Decimal("0")+ date: date+ notes: Optional[str] = None+++class AssetTransactionUpdate(BaseModel):+ kind: Optional[str] = None+ quantity: Optional[Decimal] = None+ price: Optional[Decimal] = None+ fee: Optional[Decimal] = None+ date: Optional[date] = None+ notes: Optional[str] = None+++class AssetBuyCreate(BaseModel):+ """Find-or-create a ticker holding (in `group_id`) and record a buy."""++ ticker: str+ quantity: Decimal+ price: Decimal+ fee: Decimal = Decimal("0")+ date: date+ name: Optional[str] = None+ group_id: Optional[uuid.UUID] = None+ notes: Optional[str] = None+++class AssetTransactionRead(BaseModel):+ id: uuid.UUID+ asset_id: uuid.UUID+ kind: str+ quantity: float+ price: float+ fee: float+ date: date+ source: str+ notes: Optional[str] = None+ # Denormalized holding context so the global transactions tab can render+ # rows without an extra per-row asset lookup.+ asset_name: Optional[str] = None+ ticker: Optional[str] = None+ currency: Optional[str] = None+ logo_url: Optional[str] = Nonemodel_config = ConfigDict(from_attributes=True)diff --git a/backend/app/services/asset_service.py b/backend/app/services/asset_service.pyindex eea8a9f1..a9549e31 100644--- a/backend/app/services/asset_service.py+++ b/backend/app/services/asset_service.py@@ -10,6 +10,7 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom app.core.config import get_settingsfrom app.models.asset import Asset+from app.models.asset_transaction import AssetTransactionfrom app.models.asset_value import AssetValuefrom app.models.user import Userfrom app.providers.market_price import (@@ -110,13 +111,28 @@ def _generate_growth_values(return values-def _asset_to_read(asset: Asset, latest_value: Optional[AssetValue], value_count: int) -> AssetRead:+def _asset_to_read(+ asset: Asset,+ latest_value: Optional[AssetValue],+ value_count: int,+ transaction_count: int = 0,+) -> AssetRead:"""Convert an Asset model + computed fields to AssetRead schema."""current_value = _compute_current_value(asset, latest_value)gain_loss = Noneif current_value is not None and asset.purchase_price is not None:gain_loss = current_value - float(asset.purchase_price)+ # For ledger-backed holdings `purchase_price` caches the cost basis of the+ # held units, so it doubles as `total_invested`. `average_price != None`+ # is the signal that the holding is driven by the transactions ledger.+ is_ledger = asset.average_price is not None+ total_invested = (+ float(asset.purchase_price)+ if is_ledger and asset.purchase_price is not None+ else None+ )+return AssetRead(id=asset.id,user_id=asset.user_id,@@ -148,6 +164,10 @@ def _asset_to_read(asset: Asset, latest_value: Optional[AssetValue], value_countlast_price=float(asset.last_price) if asset.last_price is not None else None,last_price_at=asset.last_price_at,logo_url=asset.logo_url,+ average_price=float(asset.average_price) if asset.average_price is not None else None,+ total_invested=total_invested,+ realized_gain=float(asset.realized_gain) if asset.realized_gain is not None else None,+ transaction_count=transaction_count,)@@ -244,6 +264,18 @@ async def _get_value_count(session: AsyncSession, asset_id: uuid.UUID) -> int:return result or 0+async def _get_transaction_counts(+ session: AsyncSession, workspace_id: uuid.UUID+) -> dict[uuid.UUID, int]:+ """Number of ledger transactions per asset in a workspace (one query)."""+ result = await session.execute(+ select(AssetTransaction.asset_id, func.count())+ .where(AssetTransaction.workspace_id == workspace_id)+ .group_by(AssetTransaction.asset_id)+ )+ return {row[0]: row[1] for row in result.all()}++async def get_assets(session: AsyncSession, workspace_id: uuid.UUID, include_archived: bool = False) -> list[AssetRead]:@@ -256,11 +288,12 @@ async def get_assets(result = await session.execute(query)assets = list(result.scalars().all())+ tx_counts = await _get_transaction_counts(session, workspace_id)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))+ reads.append(_asset_to_read(asset, latest, count, tx_counts.get(asset.id, 0)))return reads@@ -276,7 +309,12 @@ async def get_asset(return Nonelatest = await _get_latest_value(session, asset.id)count = await _get_value_count(session, asset.id)- return _asset_to_read(asset, latest, count)+ tx_count = await session.scalar(+ select(func.count())+ .select_from(AssetTransaction)+ .where(AssetTransaction.asset_id == asset.id)+ )+ return _asset_to_read(asset, latest, count, tx_count or 0)async def create_asset(@@ -390,6 +428,34 @@ async def create_asset(for v in backfill:session.add(v)+ # Seed the opening buy so market-priced holdings are ledger-backed from+ # the start (issue #235): units/average_price/cost basis are then derived+ # from the transactions, consistently with later edits. `purchase_price`+ # is the total paid, so per-share = purchase_price / units; absent that we+ # fall back to the live quote (cost basis ≈ current value, gain ≈ 0).+ if data.valuation_method == "market_price" and quote is not None and data.units and data.units > 0:+ from app.services import asset_transaction_service++ buy_price = (+ Decimal(str(data.purchase_price)) / Decimal(str(data.units))+ if data.purchase_price is not None+ else Decimal(str(quote.price))+ )+ session.add(+ AssetTransaction(+ asset_id=asset.id,+ workspace_id=workspace_id,+ kind="buy",+ quantity=Decimal(str(data.units)),+ price=buy_price,+ fee=Decimal("0"),+ date=data.purchase_date or date.today(),+ source="manual",+ )+ )+ await session.flush()+ await asset_transaction_service.recompute_and_cache(session, asset)+# Stamp purchase_price_primaryif asset.purchase_price is not None:await stamp_primary_amount(@@ -404,7 +470,10 @@ async def create_asset(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)+ tx_count = await session.scalar(+ select(func.count()).select_from(AssetTransaction).where(AssetTransaction.asset_id == asset.id)+ )+ return _asset_to_read(asset, latest, count, tx_count or 0)async def update_asset(diff --git a/backend/app/services/asset_transaction_service.py b/backend/app/services/asset_transaction_service.pynew file mode 100644index 00000000..f48b2629--- /dev/null+++ b/backend/app/services/asset_transaction_service.py@@ -0,0 +1,417 @@+"""Buy/sell ledger for market-priced holdings (issue #235).++Transactions are the source of truth; a holding's `units`, `average_price`+(preço médio), cost basis and realized gain are *derived* by replaying the+ledger in date order and cached on the asset row so list views stay cheap.++Average price uses the weighted-average method (the Brazilian preço médio+convention), not FIFO/LIFO: a sell realizes `(price - avg) * qty` and lowers+the cost basis proportionally, leaving the per-unit average unchanged.+"""+import logging+import uuid+from datetime import date, datetime, timezone+from decimal import Decimal+from typing import Optional++from fastapi import HTTPException, status+from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.asset import Asset+from app.models.asset_transaction import AssetTransaction+from app.providers.market_price import MarketPriceProvider, get_market_price_provider+from app.schemas.asset import (+ AssetBuyCreate,+ AssetRead,+ AssetTransactionCreate,+ AssetTransactionRead,+ AssetTransactionUpdate,+)+from app.services import asset_service++logger = logging.getLogger(__name__)++_VALID_KINDS = {"buy", "sell"}+++def _d(value) -> Decimal:+ return Decimal(str(value or 0))+++def _recompute(transactions: list[AssetTransaction]) -> dict:+ """Replay a holding's ledger in date order → derived position.++ Returns units (current quantity), average_price (per unit, None when flat),+ cost_basis (of held units), realized_gain, first_buy/last_sell dates.+ """+ txs = sorted(transactions, key=lambda t: (t.date, t.created_at or datetime.min.replace(tzinfo=timezone.utc)))+ qty = Decimal("0")+ cost = Decimal("0")+ realized = Decimal("0")+ first_buy: Optional[date] = None+ last_sell: Optional[date] = None++ for tx in txs:+ q = _d(tx.quantity)+ p = _d(tx.price)+ fee = _d(tx.fee)+ if tx.kind == "buy":+ cost += q * p + fee+ qty += q+ if first_buy is None:+ first_buy = tx.date+ elif tx.kind == "sell":+ avg = (cost / qty) if qty > 0 else Decimal("0")+ sell_qty = q if q <= qty else qty # clamp oversell defensively+ realized += (p - avg) * sell_qty - fee+ cost -= avg * sell_qty+ qty -= sell_qty+ last_sell = tx.date++ avg_price = (cost / qty) if qty > 0 else None+ return {+ "units": qty,+ "average_price": avg_price,+ "cost_basis": cost if qty > 0 else Decimal("0"),+ "realized_gain": realized,+ "first_buy": first_buy,+ "last_sell": last_sell,+ }+++def _detect_oversell(transactions: list[AssetTransaction]) -> Optional[tuple[Decimal, Decimal]]:+ """Replay the ledger in date order and return the first sell that exceeds+ the units held at that point as (attempted, available), else None.++ We keep the portfolio buy-and-hold: a position can't go negative (no+ shorting), so an over-sell is rejected rather than silently clamped.+ """+ txs = sorted(+ transactions,+ key=lambda t: (t.date, t.created_at or datetime.min.replace(tzinfo=timezone.utc)),+ )+ qty = Decimal("0")+ for tx in txs:+ q = _d(tx.quantity)+ if tx.kind == "buy":+ qty += q+ elif tx.kind == "sell":+ if q > qty:+ return (q, qty)+ qty -= q+ return None+++async def _load_txs(session: AsyncSession, asset_id: uuid.UUID) -> list[AssetTransaction]:+ result = await session.execute(+ select(AssetTransaction).where(AssetTransaction.asset_id == asset_id)+ )+ return list(result.scalars().all())+++def _raise_if_oversell(transactions: list[AssetTransaction]) -> None:+ """Reject a ledger that would drive the position negative (no shorting).++ Checked in-memory on the prospective ledger before any insert, so a+ rejected transaction never touches the DB.+ """+ over = _detect_oversell(transactions)+ if over is not None:+ attempted, available = over+ fmt = lambda q: f"{q:.6f}".rstrip("0").rstrip(".") # noqa: E731+ raise HTTPException(+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,+ detail=(+ f"Cannot sell {fmt(attempted)} units — only {fmt(available)} held at that date. "+ "Short positions aren't supported."+ ),+ )+++async def recompute_and_cache(session: AsyncSession, asset: Asset) -> None:+ """Recompute the derived position from the ledger and cache it on the asset.++ Keeps `purchase_price` as the cost basis of the held units so the existing+ `gain_loss = current_value - purchase_price` math reads as the unrealized+ gain, and refreshes today's AssetValue so the portfolio chart matches the+ new quantity.+ """+ result = await session.execute(+ select(AssetTransaction).where(AssetTransaction.asset_id == asset.id)+ )+ txs = list(result.scalars().all())+ pos = _recompute(txs)++ asset.units = pos["units"]+ asset.average_price = pos["average_price"]+ asset.realized_gain = pos["realized_gain"].quantize(Decimal("0.01"))+ asset.purchase_price = (+ pos["cost_basis"].quantize(Decimal("0.01")) if pos["units"] > 0 else None+ )+ asset.purchase_date = pos["first_buy"]++ if pos["units"] > 0:+ # Re-opened position (or still open): clear any prior full-exit marker.+ asset.sell_date = None+ asset.sell_price = None+ elif txs and pos["last_sell"] is not None:+ # Fully exited — mark sold so it drops out of the active portfolio.+ asset.sell_date = pos["last_sell"]++ # Keep today's chart point in step with the new quantity.+ if asset.valuation_method == "market_price" and asset.last_price is not None:+ await asset_service._apply_price_to_asset(session, asset, Decimal(str(asset.last_price)))+++def _tx_to_read(tx: AssetTransaction, asset: Optional[Asset] = None) -> AssetTransactionRead:+ return AssetTransactionRead(+ id=tx.id,+ asset_id=tx.asset_id,+ kind=tx.kind,+ quantity=float(tx.quantity),+ price=float(tx.price),+ fee=float(tx.fee or 0),+ date=tx.date,+ source=tx.source,+ notes=tx.notes,+ asset_name=asset.name if asset else None,+ ticker=asset.ticker if asset else None,+ currency=asset.currency if asset else None,+ logo_url=asset.logo_url if asset else None,+ )+++async def _load_asset(+ session: AsyncSession, asset_id: uuid.UUID, workspace_id: uuid.UUID+) -> Optional[Asset]:+ result = await session.execute(+ select(Asset).where(Asset.id == asset_id, Asset.workspace_id == workspace_id)+ )+ return result.scalar_one_or_none()+++async def list_asset_transactions(+ session: AsyncSession, asset_id: uuid.UUID, workspace_id: uuid.UUID+) -> Optional[list[AssetTransactionRead]]:+ asset = await _load_asset(session, asset_id, workspace_id)+ if asset is None:+ return None+ result = await session.execute(+ select(AssetTransaction)+ .where(AssetTransaction.asset_id == asset_id)+ .order_by(AssetTransaction.date.desc(), AssetTransaction.created_at.desc())+ )+ return [_tx_to_read(tx, asset) for tx in result.scalars().all()]+++async def list_workspace_transactions(+ session: AsyncSession,+ workspace_id: uuid.UUID,+ *,+ ticker: Optional[str] = None,+ kind: Optional[str] = None,+ limit: int = 500,+) -> list[AssetTransactionRead]:+ """All ledger transactions in a workspace — powers the Transactions tab."""+ query = (+ select(AssetTransaction, Asset)+ .join(Asset, AssetTransaction.asset_id == Asset.id)+ .where(AssetTransaction.workspace_id == workspace_id)+ )+ if ticker:+ query = query.where(Asset.ticker == ticker.upper())+ if kind in _VALID_KINDS:+ query = query.where(AssetTransaction.kind == kind)+ query = query.order_by(+ AssetTransaction.date.desc(), AssetTransaction.created_at.desc()+ ).limit(limit)+ result = await session.execute(query)+ return [_tx_to_read(tx, asset) for tx, asset in result.all()]+++def _validate(kind: str, quantity: Decimal, price: Decimal) -> None:+ if kind not in _VALID_KINDS:+ raise HTTPException(+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,+ detail="kind must be 'buy' or 'sell'",+ )+ if quantity is None or quantity <= 0:+ raise HTTPException(+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,+ detail="quantity must be > 0",+ )+ if price is None or price < 0:+ raise HTTPException(+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,+ detail="price must be >= 0",+ )+++async def add_transaction(+ session: AsyncSession,+ asset_id: uuid.UUID,+ workspace_id: uuid.UUID,+ data: AssetTransactionCreate,+) -> Optional[AssetRead]:+ asset = await _load_asset(session, asset_id, workspace_id)+ if asset is None:+ return None+ _validate(data.kind, data.quantity, data.price)+ new_tx = AssetTransaction(+ asset_id=asset.id,+ workspace_id=workspace_id,+ kind=data.kind,+ quantity=data.quantity,+ price=data.price,+ fee=data.fee or Decimal("0"),+ date=data.date,+ source="manual",+ notes=data.notes,+ created_at=datetime.now(timezone.utc),+ )+ if data.kind == "sell":+ _raise_if_oversell(await _load_txs(session, asset.id) + [new_tx])+ session.add(new_tx)+ await session.flush()+ await recompute_and_cache(session, asset)+ await session.commit()+ return await asset_service.get_asset(session, asset.id, workspace_id)+++async def update_transaction(+ session: AsyncSession,+ tx_id: uuid.UUID,+ workspace_id: uuid.UUID,+ data: AssetTransactionUpdate,+) -> Optional[AssetRead]:+ result = await session.execute(+ select(AssetTransaction).where(+ AssetTransaction.id == tx_id, AssetTransaction.workspace_id == workspace_id+ )+ )+ tx = result.scalar_one_or_none()+ if tx is None:+ return None+ fields = data.model_dump(exclude_unset=True)+ # Validate the prospective ledger before mutating the row — editing a buy+ # down or a sell up could drive the position negative.+ others = [t for t in await _load_txs(session, tx.asset_id) if t.id != tx.id]+ edited = AssetTransaction(+ asset_id=tx.asset_id,+ kind=fields.get("kind", tx.kind),+ quantity=fields.get("quantity", tx.quantity),+ price=fields.get("price", tx.price),+ date=fields.get("date", tx.date),+ created_at=tx.created_at,+ )+ _raise_if_oversell(others + [edited])++ for key, value in fields.items():+ setattr(tx, key, value)+ _validate(tx.kind, _d(tx.quantity), _d(tx.price))+ asset = await _load_asset(session, tx.asset_id, workspace_id)+ await session.flush()+ await recompute_and_cache(session, asset)+ await session.commit()+ return await asset_service.get_asset(session, asset.id, workspace_id)+++async def delete_transaction(+ session: AsyncSession, tx_id: uuid.UUID, workspace_id: uuid.UUID+) -> Optional[AssetRead]:+ result = await session.execute(+ select(AssetTransaction).where(+ AssetTransaction.id == tx_id, AssetTransaction.workspace_id == workspace_id+ )+ )+ tx = result.scalar_one_or_none()+ if tx is None:+ return None+ asset = await _load_asset(session, tx.asset_id, workspace_id)+ await session.delete(tx)+ await session.flush()+ await recompute_and_cache(session, asset)+ await session.commit()+ return await asset_service.get_asset(session, asset.id, workspace_id)+++async def buy_into_holding(+ session: AsyncSession,+ workspace_id: uuid.UUID,+ user_id: uuid.UUID,+ data: AssetBuyCreate,+ *,+ market_provider: Optional[MarketPriceProvider] = None,+) -> AssetRead:+ """Record a buy, consolidating onto the existing ticker holding in the+ chosen wallet (`group_id`) or creating a new market-priced holding."""+ _validate("buy", data.quantity, data.price)+ ticker = data.ticker.upper()++ result = await session.execute(+ select(Asset).where(+ Asset.workspace_id == workspace_id,+ Asset.ticker == ticker,+ Asset.valuation_method == "market_price",+ Asset.group_id == data.group_id,+ )+ )+ asset = result.scalar_one_or_none()++ if asset is None:+ provider = market_provider or get_market_price_provider()+ quote = await provider.get_quote(ticker)+ if quote is None:+ raise HTTPException(+ status_code=status.HTTP_502_BAD_GATEWAY,+ detail=f"Could not fetch quote for {ticker}",+ )+ asset = Asset(+ user_id=user_id,+ workspace_id=workspace_id,+ name=data.name or quote.name or ticker,+ type=_type_from_quote(quote.quote_type),+ currency=quote.currency,+ valuation_method="market_price",+ group_id=data.group_id,+ ticker=ticker,+ ticker_exchange=quote.exchange,+ last_price=Decimal(str(quote.price)),+ last_price_at=datetime.now(timezone.utc),+ logo_url=quote.logo_url,+ source="yfinance",+ )+ session.add(asset)+ await session.flush()++ session.add(+ AssetTransaction(+ asset_id=asset.id,+ workspace_id=workspace_id,+ kind="buy",+ quantity=data.quantity,+ price=data.price,+ fee=data.fee or Decimal("0"),+ date=data.date,+ source="manual",+ notes=data.notes,+ )+ )+ await session.flush()+ await recompute_and_cache(session, asset)+ await session.commit()+ return await asset_service.get_asset(session, asset.id, workspace_id)+++def _type_from_quote(quote_type: Optional[str]) -> str:+ """Mirror the frontend's quoteType → asset type mapping so a holding+ created from the ledger lands on a sensible icon/type."""+ mapping = {+ "EQUITY": "stock",+ "ETF": "etf",+ "CRYPTOCURRENCY": "crypto",+ "MUTUALFUND": "fund",+ "INDEX": "fund",+ }+ return mapping.get((quote_type or "").upper(), "investment")diff --git a/backend/tests/test_asset_transaction_service.py b/backend/tests/test_asset_transaction_service.pynew file mode 100644index 00000000..3d667eea--- /dev/null+++ b/backend/tests/test_asset_transaction_service.py@@ -0,0 +1,359 @@+"""Tests for the investment transaction ledger (issue #235).++Covers the weighted-average (preço médio) algorithm and the service paths:+buy/sell recompute, realized gains, find-or-create consolidation by ticker.+"""+import uuid+from datetime import date+from decimal import Decimal+from typing import Optional++import pytest+import pytest_asyncio+from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.asset import Asset+from app.models.asset_transaction import AssetTransaction+from app.models.user import User+from app.providers.market_price import MarketPriceProvider+from app.schemas.asset import (+ AssetBuyCreate,+ AssetTransactionCreate,+ AssetTransactionUpdate,+ MarketSymbolMatch,+ MarketSymbolQuote,+)+from app.services import asset_transaction_service+from app.services.asset_transaction_service import _recompute+++# ---------------------------------------------------------------------------+# Pure algorithm: _recompute (no DB)+# ---------------------------------------------------------------------------++def _tx(kind: str, qty: str, price: str, d: date, fee: str = "0") -> AssetTransaction:+ return AssetTransaction(+ id=uuid.uuid4(), asset_id=uuid.uuid4(), workspace_id=uuid.uuid4(),+ kind=kind, quantity=Decimal(qty), price=Decimal(price), fee=Decimal(fee), date=d,+ )+++def test_recompute_weighted_average_across_buys():+ # 10 @ 100 then 5 @ 110 → avg = (1000 + 550) / 15 = 103.3333...+ pos = _recompute([+ _tx("buy", "10", "100", date(2026, 1, 1)),+ _tx("buy", "5", "110", date(2026, 2, 1)),+ ])+ assert pos["units"] == Decimal("15")+ assert pos["average_price"].quantize(Decimal("0.0001")) == Decimal("103.3333")+ assert pos["cost_basis"] == Decimal("1550")+ assert pos["realized_gain"] == Decimal("0")+++def test_recompute_partial_sell_keeps_average_and_realizes():+ # buy 10 @ 100, buy 5 @ 110 (avg 103.3333), sell 6 @ 130+ # realized = (130 - 103.3333) * 6 = 160.0002 (≈ 160), avg unchanged+ pos = _recompute([+ _tx("buy", "10", "100", date(2026, 1, 1)),+ _tx("buy", "5", "110", date(2026, 1, 2)),+ _tx("sell", "6", "130", date(2026, 3, 1)),+ ])+ assert pos["units"] == Decimal("9")+ assert pos["average_price"].quantize(Decimal("0.0001")) == Decimal("103.3333")+ assert pos["realized_gain"].quantize(Decimal("0.01")) == Decimal("160.00")+++def test_recompute_sell_all_flattens_position():+ pos = _recompute([+ _tx("buy", "10", "100", date(2026, 1, 1)),+ _tx("sell", "10", "120", date(2026, 2, 1)),+ ])+ assert pos["units"] == Decimal("0")+ assert pos["average_price"] is None+ assert pos["cost_basis"] == Decimal("0")+ assert pos["realized_gain"].quantize(Decimal("0.01")) == Decimal("200.00")+++def test_recompute_includes_fees_in_cost_basis():+ # buy 10 @ 100 with 9.90 fee → cost basis 1009.90, avg 100.99+ pos = _recompute([_tx("buy", "10", "100", date(2026, 1, 1), fee="9.90")])+ assert pos["cost_basis"] == Decimal("1009.90")+ assert pos["average_price"].quantize(Decimal("0.0001")) == Decimal("100.9900")+++def test_recompute_clamps_oversell():+ # Selling more than held shouldn't drive quantity negative.+ pos = _recompute([+ _tx("buy", "5", "100", date(2026, 1, 1)),+ _tx("sell", "10", "120", date(2026, 2, 1)),+ ])+ assert pos["units"] == Decimal("0")+ assert pos["average_price"] is None+++def test_recompute_orders_by_date_not_insertion():+ # A backdated buy must be processed first.+ pos = _recompute([+ _tx("sell", "5", "130", date(2026, 3, 1)),+ _tx("buy", "10", "100", date(2026, 1, 1)),+ ])+ assert pos["units"] == Decimal("5")+ assert pos["average_price"].quantize(Decimal("0.01")) == Decimal("100.00")+++# ---------------------------------------------------------------------------+# Service paths (DB)+# ---------------------------------------------------------------------------++class _FakeProvider(MarketPriceProvider):+ name = "fake"++ def __init__(self, quotes: dict[str, MarketSymbolQuote]):+ self._quotes = quotes++ async def search(self, query: str, limit: int = 20) -> list[MarketSymbolMatch]:+ return []++ async def get_quote(self, symbol: str) -> Optional[MarketSymbolQuote]:+ return self._quotes.get(symbol.upper())++ async def get_latest_prices(self, symbols: list[str]) -> dict[str, Optional[Decimal]]:+ return {s.upper(): Decimal(str(self._quotes[s.upper()].price)) for s in symbols if s.upper() in self._quotes}+++def _quote(symbol: str, price: float, currency: str = "BRL") -> MarketSymbolQuote:+ return MarketSymbolQuote(+ symbol=symbol, name=f"{symbol} SA", exchange="SAO",+ currency=currency, price=price, quote_type="EQUITY",+ )+++@pytest_asyncio.fixture+async def market_asset(session: AsyncSession, test_user: User, test_workspace) -> Asset:+ asset = Asset(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ name="Petrobras", type="stock", currency="BRL",+ valuation_method="market_price", ticker="PETR4.SA",+ last_price=Decimal("30.00"),+ )+ session.add(asset)+ await session.commit()+ await session.refresh(asset)+ return asset+++async def test_add_buys_sets_units_average_and_cost_basis(session, test_workspace, market_asset):+ await asset_transaction_service.add_transaction(+ session, market_asset.id, test_workspace.id,+ AssetTransactionCreate(kind="buy", quantity=Decimal("10"), price=Decimal("20"), date=date(2026, 1, 1)),+ )+ read = await asset_transaction_service.add_transaction(+ session, market_asset.id, test_workspace.id,+ AssetTransactionCreate(kind="buy", quantity=Decimal("5"), price=Decimal("26"), date=date(2026, 2, 1)),+ )+ # avg = (200 + 130) / 15 = 22.00+ assert read.units == 15+ assert round(read.average_price, 2) == 22.00+ assert round(read.total_invested, 2) == 330.00+ assert read.transaction_count == 2+++async def test_sell_records_realized_gain(session, test_workspace, market_asset):+ await asset_transaction_service.add_transaction(+ session, market_asset.id, test_workspace.id,+ AssetTransactionCreate(kind="buy", quantity=Decimal("10"), price=Decimal("20"), date=date(2026, 1, 1)),+ )+ read = await asset_transaction_service.add_transaction(+ session, market_asset.id, test_workspace.id,+ AssetTransactionCreate(kind="sell", quantity=Decimal("4"), price=Decimal("30"), date=date(2026, 3, 1)),+ )+ assert read.units == 6+ assert round(read.average_price, 2) == 20.00 # average unchanged by sell+ assert round(read.realized_gain, 2) == 40.00 # (30 - 20) * 4+++async def test_delete_transaction_recomputes(session, test_workspace, market_asset):+ await asset_transaction_service.add_transaction(+ session, market_asset.id, test_workspace.id,+ AssetTransactionCreate(kind="buy", quantity=Decimal("10"), price=Decimal("20"), date=date(2026, 1, 1)),+ )+ txs = await asset_transaction_service.list_asset_transactions(session, market_asset.id, test_workspace.id)+ read = await asset_transaction_service.delete_transaction(session, txs[0].id, test_workspace.id)+ assert read.units == 0+ assert read.average_price is None+++async def test_update_transaction_recomputes(session, test_workspace, market_asset):+ await asset_transaction_service.add_transaction(+ session, market_asset.id, test_workspace.id,+ AssetTransactionCreate(kind="buy", quantity=Decimal("10"), price=Decimal("20"), date=date(2026, 1, 1)),+ )+ txs = await asset_transaction_service.list_asset_transactions(session, market_asset.id, test_workspace.id)+ read = await asset_transaction_service.update_transaction(+ session, txs[0].id, test_workspace.id, AssetTransactionUpdate(quantity=Decimal("20")),+ )+ assert read.units == 20+ assert round(read.average_price, 2) == 20.00+++async def test_oversell_is_rejected(session, test_workspace, market_asset):+ from fastapi import HTTPException++ await asset_transaction_service.add_transaction(+ session, market_asset.id, test_workspace.id,+ AssetTransactionCreate(kind="buy", quantity=Decimal("10"), price=Decimal("20"), date=date(2026, 1, 1)),+ )+ with pytest.raises(HTTPException) as exc:+ await asset_transaction_service.add_transaction(+ session, market_asset.id, test_workspace.id,+ AssetTransactionCreate(kind="sell", quantity=Decimal("11"), price=Decimal("30"), date=date(2026, 2, 1)),+ )+ assert exc.value.status_code == 422+ # The rejected sell must not have changed the position.+ txs = await asset_transaction_service.list_asset_transactions(session, market_asset.id, test_workspace.id)+ assert len(txs) == 1+++async def test_sell_exact_holding_is_allowed(session, test_workspace, market_asset):+ await asset_transaction_service.add_transaction(+ session, market_asset.id, test_workspace.id,+ AssetTransactionCreate(kind="buy", quantity=Decimal("10"), price=Decimal("20"), date=date(2026, 1, 1)),+ )+ read = await asset_transaction_service.add_transaction(+ session, market_asset.id, test_workspace.id,+ AssetTransactionCreate(kind="sell", quantity=Decimal("10"), price=Decimal("30"), date=date(2026, 2, 1)),+ )+ assert read.units == 0+++async def test_sell_before_any_buy_is_rejected(session, test_workspace, market_asset):+ from fastapi import HTTPException++ with pytest.raises(HTTPException) as exc:+ await asset_transaction_service.add_transaction(+ session, market_asset.id, test_workspace.id,+ AssetTransactionCreate(kind="sell", quantity=Decimal("5"), price=Decimal("30"), date=date(2026, 1, 1)),+ )+ assert exc.value.status_code == 422+++async def test_full_exit_marks_sold(session, test_workspace, market_asset):+ await asset_transaction_service.add_transaction(+ session, market_asset.id, test_workspace.id,+ AssetTransactionCreate(kind="buy", quantity=Decimal("10"), price=Decimal("20"), date=date(2026, 1, 1)),+ )+ read = await asset_transaction_service.add_transaction(+ session, market_asset.id, test_workspace.id,+ AssetTransactionCreate(kind="sell", quantity=Decimal("10"), price=Decimal("30"), date=date(2026, 6, 1)),+ )+ assert read.units == 0+ assert read.average_price is None+ assert read.sell_date == date(2026, 6, 1) # drops out of the active portfolio+ assert round(read.realized_gain, 2) == 100.00+++async def test_rebuy_after_full_exit_resets_position(session, test_workspace, market_asset):+ await asset_transaction_service.add_transaction(+ session, market_asset.id, test_workspace.id,+ AssetTransactionCreate(kind="buy", quantity=Decimal("10"), price=Decimal("20"), date=date(2026, 1, 1)),+ )+ await asset_transaction_service.add_transaction(+ session, market_asset.id, test_workspace.id,+ AssetTransactionCreate(kind="sell", quantity=Decimal("10"), price=Decimal("30"), date=date(2026, 2, 1)),+ )+ read = await asset_transaction_service.add_transaction(+ session, market_asset.id, test_workspace.id,+ AssetTransactionCreate(kind="buy", quantity=Decimal("5"), price=Decimal("40"), date=date(2026, 3, 1)),+ )+ assert read.units == 5+ assert round(read.average_price, 2) == 40.00+ assert read.sell_date is None # re-entered → no longer "sold"+ # Realized gain from the earlier round-trip is retained.+ assert round(read.realized_gain, 2) == 100.00+++async def test_multiple_sells_accumulate_realized_gain(session, test_workspace, market_asset):+ await asset_transaction_service.add_transaction(+ session, market_asset.id, test_workspace.id,+ AssetTransactionCreate(kind="buy", quantity=Decimal("10"), price=Decimal("20"), date=date(2026, 1, 1)),+ )+ await asset_transaction_service.add_transaction(+ session, market_asset.id, test_workspace.id,+ AssetTransactionCreate(kind="sell", quantity=Decimal("3"), price=Decimal("30"), date=date(2026, 2, 1)),+ )+ read = await asset_transaction_service.add_transaction(+ session, market_asset.id, test_workspace.id,+ AssetTransactionCreate(kind="sell", quantity=Decimal("2"), price=Decimal("25"), date=date(2026, 3, 1)),+ )+ # (30-20)*3 + (25-20)*2 = 30 + 10 = 40+ assert read.units == 5+ assert round(read.realized_gain, 2) == 40.00+++async def test_buy_into_holding_separate_across_wallets(session, test_workspace, test_user):+ from app.models.asset_group import AssetGroup++ wallet = AssetGroup(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ name="Broker A", icon="wallet", color="#0EA5E9", position=0, source="manual",+ )+ session.add(wallet)+ await session.commit()++ provider = _FakeProvider({"ITUB4.SA": _quote("ITUB4.SA", 30.0)})+ ungrouped = await asset_transaction_service.buy_into_holding(+ session, test_workspace.id, test_user.id,+ AssetBuyCreate(ticker="ITUB4.SA", quantity=Decimal("10"), price=Decimal("28"), date=date(2026, 1, 1)),+ market_provider=provider,+ )+ walleted = await asset_transaction_service.buy_into_holding(+ session, test_workspace.id, test_user.id,+ AssetBuyCreate(ticker="ITUB4.SA", quantity=Decimal("5"), price=Decimal("32"), date=date(2026, 2, 1), group_id=wallet.id),+ market_provider=provider,+ )+ # Same ticker, different wallet → distinct holdings (not consolidated).+ assert ungrouped.id != walleted.id+ rows = (+ await session.execute(+ select(Asset).where(Asset.workspace_id == test_workspace.id, Asset.ticker == "ITUB4.SA")+ )+ ).scalars().all()+ assert len(rows) == 2+++async def test_buy_into_holding_consolidates_by_ticker(session, test_workspace, test_user):+ provider = _FakeProvider({"VALE3.SA": _quote("VALE3.SA", 60.0)})+ first = await asset_transaction_service.buy_into_holding(+ session, test_workspace.id, test_user.id,+ AssetBuyCreate(ticker="VALE3.SA", quantity=Decimal("10"), price=Decimal("50"), date=date(2026, 1, 1)),+ market_provider=provider,+ )+ second = await asset_transaction_service.buy_into_holding(+ session, test_workspace.id, test_user.id,+ AssetBuyCreate(ticker="VALE3.SA", quantity=Decimal("10"), price=Decimal("70"), date=date(2026, 2, 1)),+ market_provider=provider,+ )+ # Same logical holding — not two assets.+ assert first.id == second.id+ assert second.units == 20+ assert round(second.average_price, 2) == 60.00++ all_vale = (+ await session.execute(+ select(Asset).where(Asset.workspace_id == test_workspace.id, Asset.ticker == "VALE3.SA")+ )+ ).scalars().all()+ assert len(all_vale) == 1diff --git a/backend/tests/test_asset_transactions_api.py b/backend/tests/test_asset_transactions_api.pynew file mode 100644index 00000000..50b86860--- /dev/null+++ b/backend/tests/test_asset_transactions_api.py@@ -0,0 +1,180 @@+"""API-level tests for the investment transaction ledger (issue #235).++Exercises the HTTP surface: per-asset CRUD, the workspace-wide list + filters,+the find-or-create buy endpoint, validation, 404s and auth.+"""+import uuid+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.user import User+++@pytest_asyncio.fixture+async def market_asset_api(session: AsyncSession, test_user: User) -> Asset:+ """A market-priced holding with a cached last price (no provider needed)."""+ asset = Asset(+ id=uuid.uuid4(),+ user_id=test_user.id,+ name="Petrobras",+ type="stock",+ currency="BRL",+ valuation_method="market_price",+ ticker="PETR4.SA",+ last_price=Decimal("30.00"),+ position=0,+ )+ session.add(asset)+ await session.commit()+ await session.refresh(asset)+ return asset+++async def test_add_transaction_via_api(client: AsyncClient, auth_headers: dict, market_asset_api: Asset):+ resp = await client.post(+ f"/api/assets/{market_asset_api.id}/transactions",+ headers=auth_headers,+ json={"kind": "buy", "quantity": 10, "price": 20, "date": "2026-01-01"},+ )+ assert resp.status_code == 201+ body = resp.json()+ assert body["units"] == 10+ assert round(body["average_price"], 2) == 20.00+ assert body["transaction_count"] == 1+++async def test_transaction_list_and_filters(client: AsyncClient, auth_headers: dict, market_asset_api: Asset):+ for tx in [+ {"kind": "buy", "quantity": 10, "price": 20, "date": "2026-01-01"},+ {"kind": "sell", "quantity": 4, "price": 30, "date": "2026-03-01"},+ ]:+ r = await client.post(f"/api/assets/{market_asset_api.id}/transactions", headers=auth_headers, json=tx)+ assert r.status_code == 201++ # Per-asset list+ r = await client.get(f"/api/assets/{market_asset_api.id}/transactions", headers=auth_headers)+ assert r.status_code == 200+ assert len(r.json()) == 2++ # Workspace-wide list+ r = await client.get("/api/assets/transactions", headers=auth_headers)+ assert r.status_code == 200+ rows = r.json()+ assert len(rows) == 2+ assert all(row["ticker"] == "PETR4.SA" for row in rows)++ # Filter by kind+ r = await client.get("/api/assets/transactions", headers=auth_headers, params={"kind": "sell"})+ assert [row["kind"] for row in r.json()] == ["sell"]++ # Filter by ticker+ r = await client.get("/api/assets/transactions", headers=auth_headers, params={"ticker": "PETR4.SA"})+ assert len(r.json()) == 2+ r = await client.get("/api/assets/transactions", headers=auth_headers, params={"ticker": "NOPE"})+ assert r.json() == []+++async def test_update_and_delete_transaction_via_api(+ client: AsyncClient, auth_headers: dict, market_asset_api: Asset+):+ r = await client.post(+ f"/api/assets/{market_asset_api.id}/transactions",+ headers=auth_headers,+ json={"kind": "buy", "quantity": 10, "price": 20, "date": "2026-01-01"},+ )+ assert r.status_code == 201+ tx_id = (await client.get(f"/api/assets/{market_asset_api.id}/transactions", headers=auth_headers)).json()[0]["id"]++ r = await client.patch(f"/api/assets/transactions/{tx_id}", headers=auth_headers, json={"quantity": 25})+ assert r.status_code == 200+ assert r.json()["units"] == 25++ r = await client.delete(f"/api/assets/transactions/{tx_id}", headers=auth_headers)+ assert r.status_code == 200+ assert r.json()["units"] == 0+ assert r.json()["average_price"] is None+++async def test_buy_consolidates_existing_ticker_via_api(+ client: AsyncClient, auth_headers: dict, session: AsyncSession, market_asset_api: Asset+):+ # First seed a buy so the holding has a position.+ await client.post(+ f"/api/assets/{market_asset_api.id}/transactions",+ headers=auth_headers,+ json={"kind": "buy", "quantity": 10, "price": 20, "date": "2026-01-01"},+ )+ # /assets/buy on the SAME ticker hits the find path (no provider call needed).+ r = await client.post(+ "/api/assets/buy",+ headers=auth_headers,+ json={"ticker": "PETR4.SA", "quantity": 10, "price": 30, "date": "2026-02-01"},+ )+ assert r.status_code == 201+ body = r.json()+ assert body["id"] == str(market_asset_api.id) # consolidated, not a new asset+ assert body["units"] == 20+ assert round(body["average_price"], 2) == 25.00+++async def test_add_transaction_unknown_asset_404(client: AsyncClient, auth_headers: dict):+ r = await client.post(+ f"/api/assets/{uuid.uuid4()}/transactions",+ headers=auth_headers,+ json={"kind": "buy", "quantity": 1, "price": 1, "date": "2026-01-01"},+ )+ assert r.status_code == 404+++async def test_add_transaction_invalid_kind_422(client: AsyncClient, auth_headers: dict, market_asset_api: Asset):+ r = await client.post(+ f"/api/assets/{market_asset_api.id}/transactions",+ headers=auth_headers,+ json={"kind": "gift", "quantity": 1, "price": 1, "date": "2026-01-01"},+ )+ assert r.status_code == 422+++async def test_add_transaction_zero_quantity_422(client: AsyncClient, auth_headers: dict, market_asset_api: Asset):+ r = await client.post(+ f"/api/assets/{market_asset_api.id}/transactions",+ headers=auth_headers,+ json={"kind": "buy", "quantity": 0, "price": 10, "date": "2026-01-01"},+ )+ assert r.status_code == 422+++async def test_oversell_rejected_via_api(client: AsyncClient, auth_headers: dict, market_asset_api: Asset):+ await client.post(+ f"/api/assets/{market_asset_api.id}/transactions",+ headers=auth_headers,+ json={"kind": "buy", "quantity": 10, "price": 20, "date": "2026-01-01"},+ )+ r = await client.post(+ f"/api/assets/{market_asset_api.id}/transactions",+ headers=auth_headers,+ json={"kind": "sell", "quantity": 11, "price": 30, "date": "2026-02-01"},+ )+ assert r.status_code == 422+ assert "only" in r.json()["detail"].lower()+ # Rejected sell left no trace — still just the one buy.+ r2 = await client.get(f"/api/assets/{market_asset_api.id}/transactions", headers=auth_headers)+ assert len(r2.json()) == 1+++async def test_transactions_require_auth(client: AsyncClient):+ assert (await client.get("/api/assets/transactions")).status_code == 401diff --git a/docs/rfc-235-investment-ledger.md b/docs/rfc-235-investment-ledger.mdnew file mode 100644index 00000000..5e296fe0--- /dev/null+++ b/docs/rfc-235-investment-ledger.md@@ -0,0 +1,72 @@+# RFC #235 — Investment ledger: ticker grouping, average price, holdings vs. transactions++Status: in progress · Issue: [#235](https://github.com/securo-finance/securo/issues/235)++## Problem++BR investors (Status Invest / Investidor10 style) need their portfolio+**consolidated by ticker** with an **average price** (preço médio), and a+**separate list of buy/sell transactions** for income-tax (IR) reporting.+Today each `Asset` is a single position with one `purchase_price` — there is no+transaction ledger, no average across multiple buys, and no ticker grouping.++## Approach++Adopt the trades-are-source-of-truth model (inspired by Maybe/"sure"): a+market-priced `Asset` is the **consolidated holding for one ticker (per+wallet)**, and a new `asset_transactions` ledger sits underneath it. The+position (`units`, `average_price`, cost basis, realized gain) is **derived**+from the transactions and cached on the asset row so list views and the+portfolio chart stay cheap and unchanged.++### Average price — weighted average (preço médio, not FIFO)++Process a ticker's transactions in date order:++- **buy:** `total_cost += qty*price + fee`; `qty += quantity`+- **sell:** `avg = total_cost/qty`; `realized += (price - avg)*sell_qty - fee`;+ `total_cost -= avg*sell_qty`; `qty -= sell_qty` (avg per-share unchanged)+- Derived: `average_price = total_cost/qty`, cost basis = `total_cost`,+ `unrealized = units*last_price - total_cost`, `realized` accumulated above.++### Consolidation = find-or-create++Adding a buy for `PETR4` attaches a transaction to the existing PETR4 holding+in the chosen wallet instead of creating a duplicate asset. That is the ticker+grouping.++## Data model++New table `asset_transactions` (migration `059`, chained from `058`):+`id, asset_id, workspace_id, kind(buy|sell), quantity, price, fee, date,+source, external_id, notes, created_at`.++Two cached, additive columns on `assets`: `average_price`, `realized_gain`.+`units` is repurposed as the cached current quantity; `purchase_price` is+repurposed as the cached cost basis of the held position (keeps the existing+`gain_loss = current_value - purchase_price` math working as unrealized gain).++### No data loss++Purely additive: new table + two nullable columns. No column is dropped,+renamed, or overwritten; `AssetValue` history is untouched. The backfill only+reads existing `purchase_price`/`units`/`purchase_date`/`sell_*` to emit the+initial buy/sell rows and is idempotent. `downgrade()` drops the new table and+columns. Synced (Pluggy) holdings are unaffected in this PR.++## Scope++- **In:** manual + market-priced equity assets (stock/etf/crypto/fund) get the+ ledger, average price, realized/unrealized gains, a consolidated holdings+ view, and a transactions tab.+- **Out (this PR):** synced Pluggy holdings stay provider-owned single+ positions; ceiling-price suggestions (Graham/Lynch/Klarman/Bazin) are a+ follow-up (need fundamentals not yet plumbed).++## Surface++- Backend: `AssetTransaction` model, migration `059` (+ backfill),+ `asset_transaction_service` (recompute + CRUD + find-or-create buy), new+ fields on `AssetRead`, endpoints under `/api/assets/...`.+- Frontend: "Holdings" (consolidated, with preço médio) and "Transactions"+ tabs on the Assets page; add/edit/delete transactions; i18n (en/pt-BR/es/it/pl).diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 43d79106..f390e34c 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -28,6 +28,7 @@ import type {WorkspaceRole,Asset,AssetGroup,+ AssetTransaction,AssetValue,MarketSymbolMatch,MarketSymbolQuote,@@ -927,6 +928,39 @@ export const assets = {const { data } = await api.post(`/assets/${id}/refresh-price`)return data},+ // Transaction ledger (issue #235)+ transactions: async (id: string): Promise<AssetTransaction[]> => {+ const { data } = await api.get(`/assets/${id}/transactions`)+ return data+ },+ allTransactions: async (params?: { ticker?: string; kind?: 'buy' | 'sell' }): Promise<AssetTransaction[]> => {+ const { data } = await api.get('/assets/transactions', { params })+ return data+ },+ addTransaction: async (+ id: string,+ tx: { kind: 'buy' | 'sell'; quantity: number; price: number; fee?: number; date: string; notes?: string },+ ): Promise<Asset> => {+ const { data } = await api.post(`/assets/${id}/transactions`, tx)+ return data+ },+ updateTransaction: async (+ txId: string,+ tx: Partial<{ kind: 'buy' | 'sell'; quantity: number; price: number; fee: number; date: string; notes: string }>,+ ): Promise<Asset> => {+ const { data } = await api.patch(`/assets/transactions/${txId}`, tx)+ return data+ },+ deleteTransaction: async (txId: string): Promise<Asset> => {+ const { data } = await api.delete(`/assets/transactions/${txId}`)+ return data+ },+ buy: async (+ tx: { ticker: string; quantity: number; price: number; fee?: number; date: string; name?: string; group_id?: string | null; notes?: string },+ ): Promise<Asset> => {+ const { data } = await api.post('/assets/buy', tx)+ return data+ },}// Asset Groups ("wallets")diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.jsonindex 3e0673a5..f91e5def 100644--- a/frontend/src/locales/en.json+++ b/frontend/src/locales/en.json@@ -869,6 +869,40 @@"assets": {"title": "Assets","addAsset": "Add Asset",+ "oversellWarning": "You only hold {{available}} units — short positions aren’t supported.",+ "noPriceBadge": "no cost",+ "noPriceWarning": "Added without a purchase price — add your buys to track average price and return.",+ "colAsset": "Asset",+ "colQuantity": "Qty",+ "colAvgPrice": "Avg price",+ "colCurrentPrice": "Current",+ "colReturn": "Return",+ "colBalance": "Total",+ "colPortfolioPct": "% port.",+ "addBuys": "add buys",+ "ledgerTitle": "Transactions",+ "noLedgerYet": "No transactions for this holding yet.",+ "unitsShort": "units",+ "avgPriceShort": "avg",+ "tabHoldings": "Holdings",+ "tabTransactions": "Transactions",+ "txTabHint": "Every buy and sell behind your consolidated holdings.",+ "addTransaction": "Add transaction",+ "noTransactions": "No transactions yet",+ "txBuy": "Buy",+ "txSell": "Sell",+ "txFee": "Fee",+ "txSaved": "Transaction saved",+ "txDeleted": "Transaction deleted",+ "editTransaction": "Edit transaction",+ "holding": "Holding",+ "newTicker": "New ticker…",+ "txType": "Type",+ "unitPrice": "Unit price",+ "fee": "Fee",+ "txTotal": "Total",+ "confirmDeleteTxTitle": "Delete transaction?",+ "confirmDeleteTx": "This removes the entry and recalculates the holding's average price.","editAsset": "Edit Asset","name": "Name","type": "Type",diff --git a/frontend/src/locales/es.json b/frontend/src/locales/es.jsonindex 9235d8c2..62909293 100644--- a/frontend/src/locales/es.json+++ b/frontend/src/locales/es.json@@ -867,6 +867,40 @@"assets": {"title": "Activos","addAsset": "Agregar activo",+ "oversellWarning": "Solo tienes {{available}} unidades — no se admiten posiciones cortas.",+ "noPriceBadge": "sin precio",+ "noPriceWarning": "Añadido sin precio de compra — añade tus compras para seguir el precio medio y la rentabilidad.",+ "colAsset": "Activo",+ "colQuantity": "Cant.",+ "colAvgPrice": "Precio medio",+ "colCurrentPrice": "Precio actual",+ "colReturn": "Rentab.",+ "colBalance": "Saldo",+ "colPortfolioPct": "% cartera",+ "addBuys": "add compras",+ "ledgerTitle": "Movimientos",+ "noLedgerYet": "Aún no hay movimientos para este activo.",+ "unitsShort": "ud",+ "avgPriceShort": "PM",+ "tabHoldings": "Cartera",+ "tabTransactions": "Transacciones",+ "txTabHint": "Cada compra y venta detrás de tu cartera consolidada.",+ "addTransaction": "Añadir transacción",+ "noTransactions": "Aún no hay transacciones",+ "txBuy": "Compra",+ "txSell": "Venta",+ "txFee": "Comisión",+ "txSaved": "Transacción guardada",+ "txDeleted": "Transacción eliminada",+ "editTransaction": "Editar transacción",+ "holding": "Activo",+ "newTicker": "Nuevo ticker…",+ "txType": "Tipo",+ "unitPrice": "Precio unitario",+ "fee": "Comisión",+ "txTotal": "Total",+ "confirmDeleteTxTitle": "¿Eliminar transacción?",+ "confirmDeleteTx": "Esto elimina el registro y recalcula el precio medio del activo.","editAsset": "Editar activo","name": "Nombre","type": "Tipo",diff --git a/frontend/src/locales/it.json b/frontend/src/locales/it.jsonindex a2c54b74..31bc50ff 100644--- a/frontend/src/locales/it.json+++ b/frontend/src/locales/it.json@@ -842,6 +842,40 @@"assets": {"title": "Beni","addAsset": "Aggiungi bene",+ "oversellWarning": "Possiedi solo {{available}} unità — le posizioni corte non sono supportate.",+ "noPriceBadge": "senza prezzo",+ "noPriceWarning": "Aggiunto senza prezzo di acquisto — aggiungi i tuoi acquisti per tracciare prezzo medio e rendimento.",+ "colAsset": "Attività",+ "colQuantity": "Qtà",+ "colAvgPrice": "Prezzo medio",+ "colCurrentPrice": "Prezzo attuale",+ "colReturn": "Rendim.",+ "colBalance": "Saldo",+ "colPortfolioPct": "% portaf.",+ "addBuys": "agg. acquisti",+ "ledgerTitle": "Movimenti",+ "noLedgerYet": "Ancora nessun movimento per questa posizione.",+ "unitsShort": "un",+ "avgPriceShort": "PM",+ "tabHoldings": "Portafoglio",+ "tabTransactions": "Transazioni",+ "txTabHint": "Ogni acquisto e vendita dietro le tue posizioni consolidate.",+ "addTransaction": "Aggiungi transazione",+ "noTransactions": "Ancora nessuna transazione",+ "txBuy": "Acquisto",+ "txSell": "Vendita",+ "txFee": "Commissione",+ "txSaved": "Transazione salvata",+ "txDeleted": "Transazione eliminata",+ "editTransaction": "Modifica transazione",+ "holding": "Posizione",+ "newTicker": "Nuovo ticker…",+ "txType": "Tipo",+ "unitPrice": "Prezzo unitario",+ "fee": "Commissione",+ "txTotal": "Totale",+ "confirmDeleteTxTitle": "Eliminare la transazione?",+ "confirmDeleteTx": "Rimuove la voce e ricalcola il prezzo medio della posizione.","editAsset": "Modifica bene","name": "Nome","type": "Tipo",diff --git a/frontend/src/locales/pl.json b/frontend/src/locales/pl.jsonindex c8502f80..f66bc574 100644--- a/frontend/src/locales/pl.json+++ b/frontend/src/locales/pl.json@@ -938,6 +938,40 @@"assets": {"title": "Aktywa","addAsset": "Dodaj aktywo",+ "oversellWarning": "Masz tylko {{available}} jednostek — pozycje krótkie nie są obsługiwane.",+ "noPriceBadge": "bez ceny",+ "noPriceWarning": "Dodano bez ceny zakupu — dodaj swoje zakupy, aby śledzić średnią cenę i zwrot.",+ "colAsset": "Aktywo",+ "colQuantity": "Ilość",+ "colAvgPrice": "Śr. cena",+ "colCurrentPrice": "Aktualna",+ "colReturn": "Zwrot",+ "colBalance": "Saldo",+ "colPortfolioPct": "% portfela",+ "addBuys": "dodaj zakupy",+ "ledgerTitle": "Transakcje",+ "noLedgerYet": "Brak transakcji dla tej pozycji.",+ "unitsShort": "szt",+ "avgPriceShort": "śr",+ "tabHoldings": "Portfel",+ "tabTransactions": "Transakcje",+ "txTabHint": "Każde kupno i sprzedaż za Twoimi skonsolidowanymi pozycjami.",+ "addTransaction": "Dodaj transakcję",+ "noTransactions": "Brak transakcji",+ "txBuy": "Kupno",+ "txSell": "Sprzedaż",+ "txFee": "Opłata",+ "txSaved": "Transakcja zapisana",+ "txDeleted": "Transakcja usunięta",+ "editTransaction": "Edytuj transakcję",+ "holding": "Pozycja",+ "newTicker": "Nowy ticker…",+ "txType": "Typ",+ "unitPrice": "Cena jednostkowa",+ "fee": "Opłata",+ "txTotal": "Razem",+ "confirmDeleteTxTitle": "Usunąć transakcję?",+ "confirmDeleteTx": "Usuwa wpis i przelicza średnią cenę pozycji.","editAsset": "Edytuj aktywo","name": "Nazwa","type": "Typ",diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.jsonindex 62e604f4..bffcb055 100644--- a/frontend/src/locales/pt-BR.json+++ b/frontend/src/locales/pt-BR.json@@ -869,6 +869,40 @@"assets": {"title": "Patrimônio","addAsset": "Adicionar Ativo",+ "oversellWarning": "Você só possui {{available}} unidades — posições vendidas (short) não são suportadas.",+ "noPriceBadge": "sem preço",+ "noPriceWarning": "Adicionado sem preço de compra — adicione suas compras para acompanhar o preço médio e a rentabilidade.",+ "colAsset": "Ativo",+ "colQuantity": "Qtd.",+ "colAvgPrice": "Preço médio",+ "colCurrentPrice": "Preço atual",+ "colReturn": "Rentab.",+ "colBalance": "Saldo",+ "colPortfolioPct": "% carteira",+ "addBuys": "add compras",+ "ledgerTitle": "Lançamentos",+ "noLedgerYet": "Nenhum lançamento para este ativo ainda.",+ "unitsShort": "un",+ "avgPriceShort": "PM",+ "tabHoldings": "Carteira",+ "tabTransactions": "Transações",+ "txTabHint": "Cada compra e venda por trás da sua carteira consolidada.",+ "addTransaction": "Adicionar transação",+ "noTransactions": "Nenhuma transação ainda",+ "txBuy": "Compra",+ "txSell": "Venda",+ "txFee": "Taxa",+ "txSaved": "Transação salva",+ "txDeleted": "Transação excluída",+ "editTransaction": "Editar transação",+ "holding": "Ativo",+ "newTicker": "Novo ativo…",+ "txType": "Tipo",+ "unitPrice": "Preço unitário",+ "fee": "Taxa",+ "txTotal": "Total",+ "confirmDeleteTxTitle": "Excluir transação?",+ "confirmDeleteTx": "Isso remove o lançamento e recalcula o preço médio do ativo.","editAsset": "Editar Ativo","name": "Nome","type": "Tipo",diff --git a/frontend/src/pages/assets.tsx b/frontend/src/pages/assets.tsxindex 9ac493d9..386d68ec 100644--- a/frontend/src/pages/assets.tsx+++ b/frontend/src/pages/assets.tsx@@ -18,7 +18,7 @@ import {import { Badge } from '@/components/ui/badge'import { Skeleton } from '@/components/ui/skeleton'import { DatePickerInput } from '@/components/ui/date-picker-input'-import type { Asset, AssetGroup, AssetValue, MarketSymbolMatch, MarketSymbolQuote } from '@/types'+import type { Asset, AssetGroup, AssetTransaction, AssetValue, MarketSymbolMatch, MarketSymbolQuote } from '@/types'import {Home,Car,@@ -38,6 +38,7 @@ import {Layers,Bitcoin,PieChart,+ AlertTriangle,} from 'lucide-react'import {AreaChart,@@ -170,6 +171,10 @@ const VALUATION_METHODS = ['manual', 'growth_rule', 'market_price'] as constconst GROWTH_TYPES = ['percentage', 'absolute'] as constconst GROWTH_FREQUENCIES = ['daily', 'weekly', 'monthly', 'yearly'] as const+// Column template shared by the holdings table header + rows so they align:+// Ativo · Quant. · Preço Médio · Preço Atual · Rentab. · Saldo · % · actions.+const HOLDINGS_GRID = 'minmax(0,2.4fr) 0.7fr 1.1fr 1fr 0.9fr 1.3fr 0.6fr 4.5rem'+export default function AssetsPage() {const { t } = useTranslation()const locale = useDisplayLocale()@@ -186,6 +191,11 @@ export default function AssetsPage() {staleTime: Infinity,})+ const [activeTab, setActiveTab] = useState<'holdings' | 'transactions'>('holdings')+ // Holding id for the lightweight "add transaction to this holding" dialog,+ // opened from the holdings table ("+ add buys") and the inline ledger.+ const [addTxAssetId, setAddTxAssetId] = useState<string | null>(null)+ const openAddTransaction = (id: string) => setAddTxAssetId(id)const [dialogOpen, setDialogOpen] = useState(false)const [editingAsset, setEditingAsset] = useState<Asset | null>(null)const [deletingId, setDeletingId] = useState<string | null>(null)@@ -280,6 +290,12 @@ export default function AssetsPage() {(acc: number, a: { current_value?: number | null }) => acc + Number(a.current_value || 0),0,)+ // Portfolio total in the user's primary currency — denominator for the+ // "% da carteira" column in the holdings table.+ const portfolioTotalPrimary = (assetsList ?? []).reduce(+ (acc, a) => acc + Number(a.current_value_primary ?? a.current_value ?? 0),+ 0,+ )const byType: Record<string, number> = {}for (const a of (assetsList ?? []) as Array<{ type?: string; current_value?: number | null }>) {if (!a.type) continue@@ -656,133 +672,172 @@ export default function AssetsPage() {setPendingGrowthSave(null)}- function renderAssetCard(asset: Asset) {+ // Consolidated holdings table (issue #235). One row per holding (ticker),+ // Investidor10/Status Invest style: Ativo · Quant. · Preço Médio ·+ // Preço Atual · Rentabilidade · Saldo · % da carteira. Market-priced rows+ // are fully populated; holdings with no recorded cost show "—" for the+ // cost-based columns and offer a one-tap way to add their buys.+ function renderHoldingRow(asset: Asset) {const config = getTypeConfig(asset.type)const Icon = config.iconconst isExpanded = expandedId === asset.idconst isSynced = asset.source !== 'manual'- // Split "externally-owned" (bank/brokerage record — gets overwritten on- // re-sync, so read-only for users) from "market-priced" (user-created- // record where only the cached price syncs). We key on valuation_method- // rather than the concrete source string so swapping the price provider- // (yfinance → anything else) doesn't break this logic.const isMarketPriced = asset.valuation_method === 'market_price'const isProviderOwned = isSynced && !isMarketPriced+ const hasCost = asset.average_price != null && asset.total_invested != null+ const returnPct =+ hasCost && asset.gain_loss != null && asset.total_invested+ ? (asset.gain_loss / asset.total_invested) * 100+ : null+ const pctOfPortfolio =+ portfolioTotalPrimary > 0 && asset.current_value_primary != null+ ? (asset.current_value_primary / portfolioTotalPrimary) * 100+ : null+ const needsBuys = isMarketPriced && !hasCost && !asset.sell_datereturn (- <div key={asset.id} className="border border-border rounded-xl bg-card shadow-sm overflow-hidden">+ <div key={asset.id} className="border-b border-border last:border-b-0"><div- className="flex items-center gap-4 px-5 py-4 cursor-pointer hover:bg-muted/30 transition-colors"+ className="grid items-center gap-2 px-3 py-3 cursor-pointer hover:bg-muted/20 transition-colors text-sm"+ style={{ gridTemplateColumns: HOLDINGS_GRID }}onClick={() => setExpandedId(isExpanded ? null : asset.id)}>- <AssetIcon- logoUrl={asset.logo_url}- Icon={Icon}- colorClass={config.color}- bgClass={config.bg}- />- <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>- {isMarketPriced ? (- <Badge- variant="outline"- className="text-[10px] px-1.5 py-0 text-primary border-primary/30 gap-1"- title={t('assets.marketPriceSourceTooltip')}- >- <TrendingUp size={9} />- {t('assets.marketPriceSource')}- </Badge>- ) : isSynced ? (- <Badge- variant="outline"- className="text-[10px] px-1.5 py-0 text-sky-600 border-sky-200 gap-1"- title={t('assets.syncedFrom', { source: asset.source })}- >- <RefreshCw size={9} />- {t('assets.synced')}- </Badge>- ) : null}- {asset.maturity_date && (- <Badge variant="outline" className="text-[10px] px-1.5 py-0 text-muted-foreground">- {t('assets.maturesOn', { date: new Date(asset.maturity_date).toLocaleDateString(dateLocale) })}- </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>- )}+ {/* Ativo */}+ <div className="flex items-center gap-2.5 min-w-0">+ <AssetIcon logoUrl={asset.logo_url} Icon={Icon} colorClass={config.color} bgClass={config.bg} size={16} tile="w-8 h-8" />+ <div className="min-w-0">+ <div className="flex items-center gap-1.5">+ <span className="font-semibold text-foreground truncate">{asset.ticker || asset.name}</span>+ {needsBuys && (+ <Badge+ variant="outline"+ className="text-[9px] px-1 py-0 text-amber-600 border-amber-300 bg-amber-50 dark:bg-amber-950/30 gap-0.5 shrink-0"+ title={t('assets.noPriceWarning')}+ >+ <AlertTriangle size={9} />+ {t('assets.noPriceBadge')}+ </Badge>+ )}+ {asset.sell_date && (+ <Badge variant="outline" className="text-[9px] px-1 py-0 text-rose-600 border-rose-200">{t('assets.sold')}</Badge>+ )}+ {isSynced && !isMarketPriced && (+ <Badge variant="outline" className="text-[9px] px-1 py-0 text-sky-600 border-sky-200">{t('assets.synced')}</Badge>+ )}+ </div>+ <span className="text-[11px] text-muted-foreground truncate block">{asset.ticker ? asset.name : t(`assets.type${asset.type.replace(/_([a-z])/g, (_, c: string) => c.toUpperCase()).replace(/^./, c => c.toUpperCase())}`)}</span></div></div>- <div className="text-right shrink-0">+ {/* Quant. */}+ <div className="text-right tabular-nums text-muted-foreground">+ {asset.units != null ? mask(`${asset.units}`) : '—'}+ </div>+ {/* Preço Médio */}+ <div className="text-right tabular-nums">+ {asset.average_price != null ? mask(formatCurrency(asset.average_price, asset.currency, locale)) : (+ needsBuys && canWrite ? (+ <button+ onClick={(e) => { e.stopPropagation(); openAddTransaction(asset.id) }}+ className="text-[11px] font-medium text-primary hover:underline"+ >+ + {t('assets.addBuys')}+ </button>+ ) : <span className="text-muted-foreground">—</span>+ )}+ </div>+ {/* Preço Atual */}+ <div className="text-right tabular-nums text-muted-foreground">+ {asset.last_price != null ? mask(formatCurrency(asset.last_price, asset.currency, locale)) : '—'}+ </div>+ {/* Rentabilidade */}+ <div className="text-right tabular-nums">+ {returnPct != null ? (+ <span className={returnPct >= 0 ? 'text-emerald-600' : 'text-rose-500'}>+ {returnPct >= 0 ? '+' : ''}{returnPct.toFixed(1)}%+ </span>+ ) : <span className="text-muted-foreground">—</span>}+ </div>+ {/* Saldo */}+ <div className="text-right tabular-nums">{asset.current_value != null ? (<>- <p className="text-sm font-bold tabular-nums text-foreground">- {mask(formatCurrency(asset.current_value, asset.currency, locale))}- {asset.current_value_primary != null && (- <span className="text-[10px] font-medium text-muted-foreground ml-1">- ({mask(formatCurrency(asset.current_value_primary, userCurrency, locale))})- </span>- )}- </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)}`)}- {asset.gain_loss_primary != null && (- <span className="text-[10px] text-muted-foreground ml-1">- ({mask(formatCurrency(asset.gain_loss_primary, userCurrency, locale))})- </span>- )}- </p>+ <span className="font-semibold text-foreground">{mask(formatCurrency(asset.current_value, asset.currency, locale))}</span>+ {asset.current_value_primary != null && asset.currency !== userCurrency && (+ <span className="block text-[10px] text-muted-foreground">{mask(formatCurrency(asset.current_value_primary, userCurrency, locale))}</span>)}</>- ) : (- <p className="text-sm text-muted-foreground">—</p>- )}+ ) : <span className="text-muted-foreground">—</span>}+ </div>+ {/* % carteira */}+ <div className="text-right tabular-nums text-muted-foreground">+ {pctOfPortfolio != null ? `${pctOfPortfolio.toFixed(1)}%` : '—'}</div>- <div className="flex items-center gap-1 shrink-0">+ {/* actions */}+ <div className="flex items-center justify-end gap-0.5">{canWrite && (<>- <button- onClick={(e) => { e.stopPropagation(); setMovingAsset(asset) }}- title={t('assets.moveToWallet')}- className="p-1.5 rounded-lg text-muted-foreground hover:text-foreground hover:bg-muted transition-colors"- >- <FolderInput size={14} />+ <button onClick={(e) => { e.stopPropagation(); setMovingAsset(asset) }} title={t('assets.moveToWallet')} className="p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted transition-colors">+ <FolderInput size={13} /></button>- <button- onClick={(e) => { e.stopPropagation(); if (!isProviderOwned) openEdit(asset) }}- disabled={isProviderOwned}- title={isProviderOwned ? t('assets.syncedReadOnly') : undefined}- className="p-1.5 rounded-lg text-muted-foreground hover:text-foreground hover:bg-muted transition-colors disabled:opacity-30 disabled:cursor-not-allowed disabled:hover:bg-transparent"- >- <Pencil size={14} />+ <button onClick={(e) => { e.stopPropagation(); if (!isProviderOwned) openEdit(asset) }} disabled={isProviderOwned} title={isProviderOwned ? t('assets.syncedReadOnly') : undefined} className="p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted transition-colors disabled:opacity-30 disabled:cursor-not-allowed">+ <Pencil size={13} /></button>- <button- onClick={(e) => { e.stopPropagation(); if (!isProviderOwned) setDeletingId(asset.id) }}- disabled={isProviderOwned}- title={isProviderOwned ? t('assets.syncedReadOnly') : undefined}- className="p-1.5 rounded-lg text-muted-foreground hover:text-rose-600 hover:bg-rose-50 transition-colors disabled:opacity-30 disabled:cursor-not-allowed disabled:hover:bg-transparent"- >- <Trash2 size={14} />+ <button onClick={(e) => { e.stopPropagation(); if (!isProviderOwned) setDeletingId(asset.id) }} disabled={isProviderOwned} title={isProviderOwned ? t('assets.syncedReadOnly') : undefined} className="p-1 rounded text-muted-foreground hover:text-rose-600 hover:bg-rose-50 transition-colors disabled:opacity-30 disabled:cursor-not-allowed">+ <Trash2 size={13} /></button></>)}- {isExpanded ? <ChevronUp size={16} className="text-muted-foreground" /> : <ChevronDown size={16} className="text-muted-foreground" />}+ {isExpanded ? <ChevronUp size={15} className="text-muted-foreground" /> : <ChevronDown size={15} className="text-muted-foreground" />}</div></div>- {isExpanded && <AssetDetail assetId={asset.id} currency={asset.currency} locale={locale} dateLocale={dateLocale} purchasePrice={asset.purchase_price} purchaseDate={asset.purchase_date} valuationMethod={asset.valuation_method} canWrite={canWrite} />}+ {isExpanded && (+ isMarketPriced ? (+ <HoldingLedger+ asset={asset}+ locale={locale}+ dateLocale={dateLocale}+ mask={mask}+ canWrite={canWrite}+ onAdd={() => openAddTransaction(asset.id)}+ onChanged={refetchAssetViews}+ />+ ) : (+ <AssetDetail assetId={asset.id} currency={asset.currency} locale={locale} dateLocale={dateLocale} purchasePrice={asset.purchase_price} purchaseDate={asset.purchase_date} valuationMethod={asset.valuation_method} canWrite={canWrite} />+ )+ )}+ </div>+ )+ }++ // Column header for a holdings section — same grid template as the rows.+ function renderHoldingsHeader() {+ return (+ <div+ className="grid items-center gap-2 px-3 py-2 text-[10px] font-semibold text-muted-foreground uppercase tracking-wider border-b border-border"+ style={{ gridTemplateColumns: HOLDINGS_GRID }}+ >+ <div>{t('assets.colAsset')}</div>+ <div className="text-right">{t('assets.colQuantity')}</div>+ <div className="text-right">{t('assets.colAvgPrice')}</div>+ <div className="text-right">{t('assets.colCurrentPrice')}</div>+ <div className="text-right">{t('assets.colReturn')}</div>+ <div className="text-right">{t('assets.colBalance')}</div>+ <div className="text-right">{t('assets.colPortfolioPct')}</div>+ <div />+ </div>+ )+ }++ // Wrap a set of holding rows in a horizontally-scrollable table shell so the+ // columns stay aligned (and usable on narrow screens).+ function renderHoldingsTable(rows: Asset[]) {+ return (+ <div className="rounded-xl border border-border bg-card shadow-sm overflow-x-auto">+ <div className="min-w-[720px]">+ {renderHoldingsHeader()}+ {rows.map(renderHoldingRow)}+ </div></div>)}@@ -911,8 +966,8 @@ export default function AssetsPage() {)}</div>{!isCollapsed && walletAssets.length > 0 && (- <div className="space-y-2 pl-4">- {walletAssets.map(renderAssetCard)}+ <div className="pl-4">+ {renderHoldingsTable(walletAssets)}</div>)}{!isCollapsed && walletAssets.length === 0 && (@@ -945,6 +1000,34 @@ export default function AssetsPage() {}/>+ {/* Holdings (consolidated by ticker) vs. the buy/sell ledger (#235) */}+ <div className="inline-flex items-center rounded-lg border border-border p-0.5 bg-muted/40">+ <button+ onClick={() => setActiveTab('holdings')}+ className={`px-3 py-1.5 rounded-md text-xs font-medium transition-colors ${activeTab === 'holdings' ? 'bg-card text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground'}`}+ >+ {t('assets.tabHoldings')}+ </button>+ <button+ onClick={() => setActiveTab('transactions')}+ className={`px-3 py-1.5 rounded-md text-xs font-medium transition-colors ${activeTab === 'transactions' ? 'bg-card text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground'}`}+ >+ {t('assets.tabTransactions')}+ </button>+ </div>++ {activeTab === 'transactions' ? (+ <AssetTransactionsTab+ holdings={assetsList ?? []}+ wallets={sortedWallets}+ locale={locale}+ dateLocale={dateLocale}+ mask={mask}+ canWrite={canWrite}+ onChanged={refetchAssetViews}+ />+ ) : (+ <>{/* Portfolio Stacked Area Chart */}{portfolioData && portfolioData.trend.length > 0 && (<PortfolioChart@@ -973,9 +1056,7 @@ export default function AssetsPage() {<h3 className="text-xs font-semibold text-muted-foreground uppercase tracking-wider px-1">{sortedWallets.length > 0 ? t('assets.ungrouped') : t('assets.activeAssets')}</h3>- <div className="space-y-2">- {ungroupedAssets.map(renderAssetCard)}- </div>+ {renderHoldingsTable(ungroupedAssets)}</div>)}</div>@@ -987,9 +1068,7 @@ export default function AssetsPage() {<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>+ {renderHoldingsTable(soldAssets)}</div>)}@@ -1001,6 +1080,8 @@ export default function AssetsPage() {)}</div>)}+ </>+ )}{/* Create/Edit Dialog */}<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>@@ -1518,6 +1599,17 @@ export default function AssetsPage() {</div></DialogContent></Dialog>++ {/* Add a buy/sell to an existing holding (from the holdings table /+ inline ledger). Brand-new tickers go through Add Asset / the+ Transactions tab. */}+ <AddHoldingTransactionDialog+ assetId={addTxAssetId}+ holding={(assetsList ?? []).find((a) => a.id === addTxAssetId) ?? null}+ locale={locale}+ onClose={() => setAddTxAssetId(null)}+ onChanged={refetchAssetViews}+ /></div>)}@@ -1990,3 +2082,625 @@ function AssetDetail({ assetId, currency, locale: loc, dateLocale: dateLoc, purc</div>)}++// Transactions tab (issue #235): the buy/sell ledger behind the consolidated+// holdings. Lists every transaction across the portfolio and lets users add a+// buy (to a new or existing ticker), record a sell, or edit/delete entries.+// Each mutation recomputes the affected holding's preço médio server-side.+function AssetTransactionsTab({+ holdings,+ wallets,+ locale,+ dateLocale,+ mask,+ canWrite,+ onChanged,+}: {+ holdings: Asset[]+ wallets: AssetGroup[]+ locale: string+ dateLocale: string+ mask: (v: string) => string+ canWrite: boolean+ onChanged: () => void+}) {+ const { t } = useTranslation()+ const queryClient = useQueryClient()++ const { data: txs, isLoading } = useQuery({+ queryKey: ['asset-transactions'],+ queryFn: () => assets.allTransactions(),+ })++ const marketHoldings = useMemo(+ () => holdings.filter((h) => h.valuation_method === 'market_price' && !h.sell_date),+ [holdings],+ )+ // Market holdings that exist but have no recorded buys → flagged in amber so+ // the user knows their average price / return can't be computed yet.+ const holdingsWithoutCost = useMemo(+ () => marketHoldings.filter((h) => h.average_price == null && h.units != null),+ [marketHoldings],+ )++ const [dialogOpen, setDialogOpen] = useState(false)+ const [editingTx, setEditingTx] = useState<AssetTransaction | null>(null)+ const [deletingId, setDeletingId] = useState<string | null>(null)++ // Form state+ const [formKind, setFormKind] = useState<'buy' | 'sell'>('buy')+ const [formHolding, setFormHolding] = useState<string>('__new__')+ const [formTicker, setFormTicker] = useState('')+ const [formGroupId, setFormGroupId] = useState<string>('')+ const [formQuantity, setFormQuantity] = useState('')+ const [formPrice, setFormPrice] = useState('')+ const [formFee, setFormFee] = useState('')+ const [formDate, setFormDate] = useState<string>(new Date().toISOString().slice(0, 10))++ function afterChange() {+ queryClient.refetchQueries({ queryKey: ['asset-transactions'] })+ onChanged()+ }++ const saveMutation = useMutation({+ mutationFn: async () => {+ const quantity = parseFloat(formQuantity)+ const price = parseFloat(formPrice)+ const fee = formFee ? parseFloat(formFee) : 0+ if (editingTx) {+ return assets.updateTransaction(editingTx.id, {+ kind: formKind,+ quantity,+ price,+ fee,+ date: formDate,+ })+ }+ if (formHolding === '__new__') {+ return assets.buy({+ ticker: formTicker.trim().toUpperCase(),+ quantity,+ price,+ fee,+ date: formDate,+ group_id: formGroupId || null,+ })+ }+ return assets.addTransaction(formHolding, { kind: formKind, quantity, price, fee, date: formDate })+ },+ onSuccess: () => {+ afterChange()+ setDialogOpen(false)+ setEditingTx(null)+ toast.success(t('assets.txSaved'))+ },+ onError: () => toast.error(t('common.error')),+ })++ const deleteMutation = useMutation({+ mutationFn: (id: string) => assets.deleteTransaction(id),+ onSuccess: () => {+ afterChange()+ setDeletingId(null)+ toast.success(t('assets.txDeleted'))+ },+ onError: () => toast.error(t('common.error')),+ })++ function openAdd() {+ setEditingTx(null)+ setFormKind('buy')+ setFormHolding(marketHoldings.length > 0 ? marketHoldings[0].id : '__new__')+ setFormTicker('')+ setFormGroupId('')+ setFormQuantity('')+ setFormPrice('')+ setFormFee('')+ setFormDate(new Date().toISOString().slice(0, 10))+ setDialogOpen(true)+ }++ function openEdit(tx: AssetTransaction) {+ setEditingTx(tx)+ setFormKind(tx.kind)+ setFormHolding(tx.asset_id)+ setFormQuantity(`${tx.quantity}`)+ setFormPrice(`${tx.price}`)+ setFormFee(tx.fee ? `${tx.fee}` : '')+ setFormDate(tx.date)+ setDialogOpen(true)+ }++ function openAddForHolding(holdingId: string) {+ setEditingTx(null)+ setFormKind('buy')+ setFormHolding(holdingId)+ setFormTicker('')+ setFormGroupId('')+ setFormQuantity('')+ setFormPrice('')+ setFormFee('')+ setFormDate(new Date().toISOString().slice(0, 10))+ setDialogOpen(true)+ }++ const isNewTicker = !editingTx && formHolding === '__new__'+ // Warn before a sell that exceeds the held quantity (no shorting). Only on a+ // fresh sell into an existing holding; edits are validated server-side.+ const selectedHeldUnits = marketHoldings.find((h) => h.id === formHolding)?.units ?? 0+ const oversell =+ !editingTx && !isNewTicker && formKind === 'sell' && !!formQuantity && parseFloat(formQuantity) > selectedHeldUnits+ const canSave =+ !!formQuantity &&+ parseFloat(formQuantity) > 0 &&+ !!formPrice &&+ (isNewTicker ? !!formTicker.trim() : true) &&+ !oversell &&+ !saveMutation.isPending++ return (+ <div className="space-y-4">+ <div className="flex items-center justify-between">+ <p className="text-xs text-muted-foreground">{t('assets.txTabHint')}</p>+ {canWrite && (+ <Button onClick={openAdd} className="gap-1.5">+ <Plus size={16} />+ {t('assets.addTransaction')}+ </Button>+ )}+ </div>++ {/* Holdings with no recorded buys — flagged in amber so the user knows+ the average price / return is missing until they add their purchases. */}+ {holdingsWithoutCost.length > 0 && (+ <div className="space-y-1.5">+ {holdingsWithoutCost.map((h) => (+ <div+ key={h.id}+ className="flex items-center gap-3 px-4 py-2.5 rounded-lg border border-amber-300 bg-amber-50 dark:border-amber-800 dark:bg-amber-950/20"+ >+ <AlertTriangle size={16} className="text-amber-500 shrink-0" />+ <div className="flex-1 min-w-0">+ <p className="text-sm font-medium text-amber-900 dark:text-amber-200 truncate">+ {h.ticker || h.name}+ </p>+ <p className="text-[11px] text-amber-700 dark:text-amber-300/80">+ {t('assets.noPriceWarning')}+ </p>+ </div>+ {canWrite && (+ <Button+ size="sm"+ variant="outline"+ className="h-7 px-2.5 text-xs border-amber-400 text-amber-700 hover:bg-amber-100 dark:text-amber-300 dark:hover:bg-amber-900/40 shrink-0"+ onClick={() => openAddForHolding(h.id)}+ >+ {t('assets.addBuys')}+ </Button>+ )}+ </div>+ ))}+ </div>+ )}++ {isLoading ? (+ <div className="space-y-2">+ {Array.from({ length: 4 }).map((_, i) => <Skeleton key={i} className="h-12 rounded-lg" />)}+ </div>+ ) : (txs ?? []).length === 0 ? (+ holdingsWithoutCost.length === 0 ? (+ <div className="text-center py-16">+ <TrendingUp className="mx-auto h-12 w-12 text-muted-foreground/40 mb-3" />+ <p className="text-muted-foreground">{t('assets.noTransactions')}</p>+ </div>+ ) : null+ ) : (+ <div className="rounded-xl border border-border overflow-hidden divide-y divide-border">+ {(txs ?? []).map((tx) => {+ const total = tx.quantity * tx.price+ const cur = tx.currency ?? 'USD'+ return (+ <div key={tx.id} className="flex items-center gap-3 px-4 py-3 hover:bg-muted/20 transition-colors">+ <Badge+ variant="outline"+ className={`text-[10px] px-1.5 py-0 shrink-0 ${tx.kind === 'buy' ? 'text-emerald-600 border-emerald-200' : 'text-rose-600 border-rose-200'}`}+ >+ {tx.kind === 'buy' ? t('assets.txBuy') : t('assets.txSell')}+ </Badge>+ <div className="flex-1 min-w-0">+ <p className="text-sm font-medium text-foreground truncate">+ {tx.ticker || tx.asset_name}+ </p>+ <p className="text-[11px] text-muted-foreground tabular-nums">+ {new Date(tx.date + 'T00:00:00').toLocaleDateString(dateLocale)} ·{' '}+ {mask(`${tx.quantity}`)} × {mask(formatCurrency(tx.price, cur, locale))}+ </p>+ </div>+ <div className="text-right shrink-0">+ <p className="text-sm font-semibold tabular-nums text-foreground">+ {mask(formatCurrency(total, cur, locale))}+ </p>+ {tx.fee > 0 && (+ <p className="text-[10px] text-muted-foreground tabular-nums">+ {t('assets.txFee')} {mask(formatCurrency(tx.fee, cur, locale))}+ </p>+ )}+ </div>+ {canWrite && (+ <div className="flex items-center gap-1 shrink-0">+ <button+ onClick={() => openEdit(tx)}+ title={t('common.edit')}+ className="p-1.5 rounded-lg text-muted-foreground hover:text-foreground hover:bg-muted transition-colors"+ >+ <Pencil size={14} />+ </button>+ <button+ onClick={() => setDeletingId(tx.id)}+ title={t('common.delete')}+ className="p-1.5 rounded-lg text-muted-foreground hover:text-rose-600 hover:bg-rose-50 transition-colors"+ >+ <Trash2 size={14} />+ </button>+ </div>+ )}+ </div>+ )+ })}+ </div>+ )}++ {/* Add / Edit transaction dialog */}+ <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>+ <DialogContent className="max-w-md">+ <DialogHeader>+ <DialogTitle>{editingTx ? t('assets.editTransaction') : t('assets.addTransaction')}</DialogTitle>+ </DialogHeader>+ <div className="space-y-4">+ {/* Holding picker — only when adding (kind is locked on edit too) */}+ {!editingTx && (+ <div className="space-y-2">+ <Label>{t('assets.holding')}</Label>+ <select+ className="bg-card border border-border focus:outline-none focus:ring-2 focus:ring-primary px-3 py-2 rounded-lg text-foreground text-sm w-full"+ value={formHolding}+ onChange={(e) => {+ setFormHolding(e.target.value)+ if (e.target.value === '__new__') setFormKind('buy')+ }}+ >+ <option value="__new__">{t('assets.newTicker')}</option>+ {marketHoldings.map((h) => (+ <option key={h.id} value={h.id}>+ {h.ticker || h.name}+ </option>+ ))}+ </select>+ </div>+ )}++ {isNewTicker && (+ <div className="grid grid-cols-2 gap-4">+ <div className="space-y-2">+ <Label>{t('assets.ticker')}</Label>+ <Input+ value={formTicker}+ onChange={(e) => setFormTicker(e.target.value)}+ placeholder={t('assets.tickerPlaceholder')}+ />+ </div>+ <div className="space-y-2">+ <Label>{t('assets.wallet')}</Label>+ <select+ className="bg-card border border-border focus:outline-none focus:ring-2 focus:ring-primary px-3 py-2 rounded-lg text-foreground text-sm w-full"+ value={formGroupId}+ onChange={(e) => setFormGroupId(e.target.value)}+ >+ <option value="">{t('assets.noWallet')}</option>+ {wallets.map((w) => (+ <option key={w.id} value={w.id}>{w.name}</option>+ ))}+ </select>+ </div>+ </div>+ )}++ {/* Buy/Sell toggle — only for existing holdings (can't sell a new ticker) */}+ {!isNewTicker && (+ <div className="space-y-2">+ <Label>{t('assets.txType')}</Label>+ <div className="grid grid-cols-2 gap-2">+ {(['buy', 'sell'] as const).map((k) => (+ <button+ key={k}+ type="button"+ className={`px-3 py-2 rounded-lg text-sm font-medium border transition-all ${formKind === k ? 'border-primary bg-primary/10 text-primary' : 'border-border text-muted-foreground hover:border-primary/50'}`}+ onClick={() => setFormKind(k)}+ >+ {k === 'buy' ? t('assets.txBuy') : t('assets.txSell')}+ </button>+ ))}+ </div>+ </div>+ )}++ <div className="grid grid-cols-2 gap-4">+ <div className="space-y-2">+ <Label>{t('assets.quantity')}</Label>+ <Input type="number" step="any" min="0" value={formQuantity} onChange={(e) => setFormQuantity(e.target.value)} />+ </div>+ <div className="space-y-2">+ <Label>{t('assets.unitPrice')}</Label>+ <Input type="number" step="any" min="0" value={formPrice} onChange={(e) => setFormPrice(e.target.value)} />+ </div>+ </div>++ <div className="grid grid-cols-2 gap-4">+ <div className="space-y-2">+ <Label>{t('assets.fee')}</Label>+ <Input type="number" step="any" min="0" value={formFee} onChange={(e) => setFormFee(e.target.value)} placeholder="0" />+ </div>+ <div className="space-y-2">+ <Label>{t('assets.date')}</Label>+ <DatePickerInput value={formDate} onChange={setFormDate} />+ </div>+ </div>++ {oversell && (+ <p className="flex items-center gap-1.5 text-xs text-amber-600 dark:text-amber-400">+ <AlertTriangle size={13} className="shrink-0" />+ {t('assets.oversellWarning', { available: selectedHeldUnits })}+ </p>+ )}+ {formQuantity && formPrice && parseFloat(formQuantity) > 0 && (+ <div className="flex items-center justify-between p-3 rounded-lg border border-border bg-muted/30">+ <span className="text-xs font-medium text-muted-foreground">{t('assets.txTotal')}</span>+ <span className="text-sm font-bold tabular-nums text-foreground">+ {formatCurrency(+ parseFloat(formQuantity) * parseFloat(formPrice) + (formFee ? parseFloat(formFee) : 0) * (formKind === 'buy' ? 1 : -1),+ 'USD',+ locale,+ )}+ </span>+ </div>+ )}+ </div>+ <DialogFooter>+ <Button variant="outline" onClick={() => setDialogOpen(false)}>{t('common.cancel')}</Button>+ <Button onClick={() => saveMutation.mutate()} disabled={!canSave}>{t('common.save')}</Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>++ {/* Delete confirmation */}+ <Dialog open={!!deletingId} onOpenChange={() => setDeletingId(null)}>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>{t('assets.confirmDeleteTxTitle')}</DialogTitle>+ </DialogHeader>+ <p className="text-sm text-muted-foreground">{t('assets.confirmDeleteTx')}</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>+ )+}++// Inline buy/sell ledger shown when a holding row is expanded (the+// "Lançamentos" of the reference). Lists the holding's transactions and+// offers a one-tap add — the consolidated row above is recomputed server-side.+function HoldingLedger({+ asset,+ locale,+ dateLocale,+ mask,+ canWrite,+ onAdd,+ onChanged,+}: {+ asset: Asset+ locale: string+ dateLocale: string+ mask: (v: string) => string+ canWrite: boolean+ onAdd: () => void+ onChanged: () => void+}) {+ const { t } = useTranslation()+ const queryClient = useQueryClient()+ const { data: txs, isLoading } = useQuery({+ queryKey: ['asset-transactions', asset.id],+ queryFn: () => assets.transactions(asset.id),+ })++ const deleteMutation = useMutation({+ mutationFn: (id: string) => assets.deleteTransaction(id),+ onSuccess: () => {+ queryClient.refetchQueries({ queryKey: ['asset-transactions', asset.id] })+ queryClient.refetchQueries({ queryKey: ['asset-transactions'] })+ onChanged()+ toast.success(t('assets.txDeleted'))+ },+ onError: () => toast.error(t('common.error')),+ })++ return (+ <div className="border-t border-border bg-muted/10 px-4 py-4 space-y-3">+ <div className="flex items-center justify-between">+ <p className="text-[11px] font-semibold text-muted-foreground uppercase tracking-wider">+ {t('assets.ledgerTitle')}+ </p>+ {canWrite && (+ <Button size="sm" variant="outline" className="h-7 px-2 text-xs gap-1" onClick={onAdd}>+ <Plus size={13} />+ {t('assets.addTransaction')}+ </Button>+ )}+ </div>+ {isLoading ? (+ <Skeleton className="h-16 w-full rounded-lg" />+ ) : (txs ?? []).length === 0 ? (+ <p className="text-xs text-muted-foreground py-2">{t('assets.noLedgerYet')}</p>+ ) : (+ <div className="rounded-lg border border-border overflow-hidden divide-y divide-border bg-card">+ {(txs ?? []).map((tx) => (+ <div key={tx.id} className="flex items-center gap-3 px-3 py-2">+ <Badge+ variant="outline"+ className={`text-[9px] px-1 py-0 shrink-0 ${tx.kind === 'buy' ? 'text-emerald-600 border-emerald-200' : 'text-rose-600 border-rose-200'}`}+ >+ {tx.kind === 'buy' ? t('assets.txBuy') : t('assets.txSell')}+ </Badge>+ <span className="text-[11px] text-muted-foreground tabular-nums flex-1">+ {new Date(tx.date + 'T00:00:00').toLocaleDateString(dateLocale)} ·{' '}+ {mask(`${tx.quantity}`)} × {mask(formatCurrency(tx.price, asset.currency, locale))}+ </span>+ <span className="text-xs font-semibold tabular-nums text-foreground">+ {mask(formatCurrency(tx.quantity * tx.price, asset.currency, locale))}+ </span>+ {canWrite && (+ <button+ onClick={() => deleteMutation.mutate(tx.id)}+ disabled={deleteMutation.isPending}+ className="p-1 rounded text-muted-foreground/50 hover:text-rose-600 transition-colors"+ >+ <Trash2 size={12} />+ </button>+ )}+ </div>+ ))}+ </div>+ )}+ </div>+ )+}++// Lightweight dialog to add a buy/sell to an already-existing holding. Used by+// the holdings table ("+ add buys") and the inline ledger.+function AddHoldingTransactionDialog({+ assetId,+ holding,+ locale,+ onClose,+ onChanged,+}: {+ assetId: string | null+ holding: Asset | null+ locale: string+ onClose: () => void+ onChanged: () => void+}) {+ const { t } = useTranslation()+ const queryClient = useQueryClient()+ const [kind, setKind] = useState<'buy' | 'sell'>('buy')+ const [quantity, setQuantity] = useState('')+ const [price, setPrice] = useState('')+ const [fee, setFee] = useState('')+ const [date, setDate] = useState(new Date().toISOString().slice(0, 10))++ useEffect(() => {+ if (assetId) {+ setKind('buy')+ setQuantity('')+ setPrice('')+ setFee('')+ setDate(new Date().toISOString().slice(0, 10))+ }+ }, [assetId])++ const saveMutation = useMutation({+ mutationFn: () =>+ assets.addTransaction(assetId!, {+ kind,+ quantity: parseFloat(quantity),+ price: parseFloat(price),+ fee: fee ? parseFloat(fee) : 0,+ date,+ }),+ onSuccess: () => {+ queryClient.refetchQueries({ queryKey: ['asset-transactions'] })+ if (assetId) queryClient.refetchQueries({ queryKey: ['asset-transactions', assetId] })+ onChanged()+ onClose()+ toast.success(t('assets.txSaved'))+ },+ onError: () => toast.error(t('common.error')),+ })++ const cur = holding?.currency ?? 'USD'+ const heldUnits = holding?.units ?? 0+ const oversell = kind === 'sell' && !!quantity && parseFloat(quantity) > heldUnits+ const canSave = !!quantity && parseFloat(quantity) > 0 && !!price && !oversell && !saveMutation.isPending++ return (+ <Dialog open={!!assetId} onOpenChange={(o) => { if (!o) onClose() }}>+ <DialogContent className="max-w-md">+ <DialogHeader>+ <DialogTitle>+ {t('assets.addTransaction')}{holding ? ` · ${holding.ticker || holding.name}` : ''}+ </DialogTitle>+ </DialogHeader>+ <div className="space-y-4">+ <div className="space-y-2">+ <Label>{t('assets.txType')}</Label>+ <div className="grid grid-cols-2 gap-2">+ {(['buy', 'sell'] as const).map((k) => (+ <button+ key={k}+ type="button"+ className={`px-3 py-2 rounded-lg text-sm font-medium border transition-all ${kind === k ? 'border-primary bg-primary/10 text-primary' : 'border-border text-muted-foreground hover:border-primary/50'}`}+ onClick={() => setKind(k)}+ >+ {k === 'buy' ? t('assets.txBuy') : t('assets.txSell')}+ </button>+ ))}+ </div>+ </div>+ <div className="grid grid-cols-2 gap-4">+ <div className="space-y-2">+ <Label>{t('assets.quantity')}</Label>+ <Input type="number" step="any" min="0" value={quantity} onChange={(e) => setQuantity(e.target.value)} />+ </div>+ <div className="space-y-2">+ <Label>{t('assets.unitPrice')}</Label>+ <Input type="number" step="any" min="0" value={price} onChange={(e) => setPrice(e.target.value)} />+ </div>+ </div>+ <div className="grid grid-cols-2 gap-4">+ <div className="space-y-2">+ <Label>{t('assets.fee')}</Label>+ <Input type="number" step="any" min="0" value={fee} onChange={(e) => setFee(e.target.value)} placeholder="0" />+ </div>+ <div className="space-y-2">+ <Label>{t('assets.date')}</Label>+ <DatePickerInput value={date} onChange={setDate} />+ </div>+ </div>+ {oversell && (+ <p className="flex items-center gap-1.5 text-xs text-amber-600 dark:text-amber-400">+ <AlertTriangle size={13} className="shrink-0" />+ {t('assets.oversellWarning', { available: heldUnits })}+ </p>+ )}+ {quantity && price && parseFloat(quantity) > 0 && (+ <div className="flex items-center justify-between p-3 rounded-lg border border-border bg-muted/30">+ <span className="text-xs font-medium text-muted-foreground">{t('assets.txTotal')}</span>+ <span className="text-sm font-bold tabular-nums text-foreground">+ {formatCurrency(parseFloat(quantity) * parseFloat(price) + (fee ? parseFloat(fee) : 0) * (kind === 'buy' ? 1 : -1), cur, locale)}+ </span>+ </div>+ )}+ </div>+ <DialogFooter>+ <Button variant="outline" onClick={onClose}>{t('common.cancel')}</Button>+ <Button onClick={() => saveMutation.mutate()} disabled={!canSave}>{t('common.save')}</Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ )+}diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.tsindex f042db61..e7e20ec3 100644--- a/frontend/src/types/index.ts+++ b/frontend/src/types/index.ts@@ -511,6 +511,29 @@ export interface Asset {last_price: number | nulllast_price_at: string | nulllogo_url: string | null+ // Ledger-derived (issue #235): weighted-average cost per unit (preço médio),+ // cost basis of held units, cumulative realized gain, and whether the holding+ // is driven by the transactions ledger.+ average_price: number | null+ total_invested: number | null+ realized_gain: number | null+ transaction_count: number+}++export interface AssetTransaction {+ id: string+ asset_id: string+ kind: 'buy' | 'sell'+ quantity: number+ price: number+ fee: number+ date: string+ source: string+ notes: string | null+ asset_name: string | null+ ticker: string | null+ currency: string | null+ logo_url: string | null}export interface MarketSymbolMatch {