Skip to content

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

feat(assets): consistent unit-price flow, trade markers & ledger-accurate value chart (#317)

Tássio Noronha44c0c0550e5f
diff --git a/backend/alembic/versions/061_asset_value_price.py b/backend/alembic/versions/061_asset_value_price.py
new file mode 100644
index 00000000..4e0a5c01
--- /dev/null
+++ b/backend/alembic/versions/061_asset_value_price.py
@@ -0,0 +1,47 @@
+"""add per-share price to asset_values for ledger-accurate value charts
+
+Revision ID: 061
+Revises: 060
+Create Date: 2026-06-11
+
+Market-priced holdings stored their value history as `amount = units × price`
+using the *current* quantity, so entering a backdated buy/sell didn't reshape
+the historical line (the value chart became inconsistent with the ledger).
+
+We now keep a quantity-independent per-share `price` on each value row and
+rebuild the chart as `ledger_quantity(date) × price(date)`. This migration adds
+the column and backfills it for existing market-priced value rows as
+`amount / units` (units were constant at this point, so this recovers the true
+per-share price). Manual/growth assets keep `price` NULL and use `amount`.
+"""
+from typing import Sequence, Union
+
+import sqlalchemy as sa
+from alembic import op
+
+revision: str = "061"
+down_revision: Union[str, None] = "060"
+branch_labels: Union[str, Sequence[str], None] = None
+depends_on: Union[str, Sequence[str], None] = None
+
+
+def upgrade() -> None:
+ op.add_column("asset_values", sa.Column("price", sa.Numeric(precision=18, scale=6), nullable=True))
+
+ # Backfill per-share price for market-priced holdings: price = amount / units.
+ op.get_bind().execute(
+ sa.text(
+ """
+ UPDATE asset_values v
+ SET price = ROUND(v.amount / a.units, 6)
+ FROM assets a
+ WHERE v.asset_id = a.id
+ AND a.valuation_method = 'market_price'
+ AND a.units IS NOT NULL AND a.units > 0
+ """
+ )
+ )
+
+
+def downgrade() -> None:
+ op.drop_column("asset_values", "price")
diff --git a/backend/app/models/asset_value.py b/backend/app/models/asset_value.py
index 8acfcd73..9388f097 100644
--- a/backend/app/models/asset_value.py
+++ b/backend/app/models/asset_value.py
@@ -1,6 +1,7 @@
import uuid
from datetime import date
from decimal import Decimal
+from typing import Optional
from sqlalchemy import Date, ForeignKey, Numeric, String
from sqlalchemy.dialects.postgresql import UUID
@@ -19,6 +20,12 @@ class AssetValue(Base):
UUID(as_uuid=True), ForeignKey("workspaces.id", ondelete="CASCADE"), index=True
)
amount: Mapped[Decimal] = mapped_column(Numeric(precision=15, scale=6))
+ # Per-share price on `date` for market-priced holdings (quantity-independent).
+ # The value chart is rebuilt as ledger_quantity(date) × price(date) so that
+ # entering past buys/sells correctly reshapes the whole history (issue:
+ # backdated trades didn't update the baked `amount`). Null for manual/growth
+ # assets, where `amount` is the value directly.
+ price: Mapped[Optional[Decimal]] = mapped_column(Numeric(precision=18, scale=6), nullable=True)
date: Mapped[date] = mapped_column(Date)
source: Mapped[str] = mapped_column(String(20), default="manual") # manual, rule, sync
diff --git a/backend/app/schemas/asset.py b/backend/app/schemas/asset.py
index 84066219..6af9dcae 100644
--- a/backend/app/schemas/asset.py
+++ b/backend/app/schemas/asset.py
@@ -28,6 +28,10 @@ class AssetCreate(BaseModel):
# fetches the live quote on create and seeds the first AssetValue.
ticker: Optional[str] = None
ticker_exchange: Optional[str] = None
+ # Per-unit price for the opening buy of a market-priced holding (preço
+ # médio model, consistent with the transaction ledger). When omitted, the
+ # service seeds the buy at the live quote ("bought at market now").
+ unit_price: Optional[Decimal] = None
class AssetUpdate(BaseModel):
diff --git a/backend/app/services/asset_service.py b/backend/app/services/asset_service.py
index a9549e31..7a7f763a 100644
--- a/backend/app/services/asset_service.py
+++ b/backend/app/services/asset_service.py
@@ -195,23 +195,58 @@ async def _get_value_as_of(
return result.scalar_one_or_none()
+def build_market_value_series(
+ value_rows: list[tuple[date, Decimal, Optional[Decimal]]],
+ txs: list[tuple[date, str, Decimal]],
+) -> list[tuple[date, float]]:
+ """Rebuild a market-priced holding's value series from the ledger.
+
+ value(date) = quantity_held_on(date) × price(date), where quantity is the
+ cumulative buys − sells up to that date (from the ledger) and price is the
+ stored per-share price. This keeps the chart consistent with the ledger even
+ when past trades are entered after the fact. Falls back to the baked amount
+ when no per-share price is recorded. `value_rows` must be sorted by date.
+
+ A holding with no ledger at all (e.g. a pre-ledger "no cost" position that
+ still has a stored quantity) keeps its baked amounts — replaying an empty
+ ledger would wrongly zero it out.
+ """
+ if not txs:
+ return [(d, float(amount)) for d, amount, _ in value_rows]
+
+ txs_sorted = sorted(txs, key=lambda t: t[0])
+ out: list[tuple[date, float]] = []
+ qty = Decimal("0")
+ i = 0
+ for d, amount, price in value_rows:
+ while i < len(txs_sorted) and txs_sorted[i][0] <= d:
+ _, kind, q = txs_sorted[i]
+ qty += q if kind == "buy" else -q
+ i += 1
+ held = qty if qty > 0 else Decimal("0")
+ out.append((d, float(Decimal(str(price)) * held) if price is not None else float(amount)))
+ return out
+
+
async def _load_asset_native_values(
session: AsyncSession,
assets: list[Asset],
up_to_date: Optional[date] = None,
) -> dict[str, list[tuple[date, float]]]:
- """Bulk-load AssetValue rows for all assets in one query.
+ """Bulk-load each asset's value series (native currency).
- Returns {aid: [(date, amount), ...]} sorted ascending by (date, id).
- When purchase_price and purchase_date are both set and purchase_date
- predates the first recorded value, it is prepended as the earliest anchor.
+ Returns {aid: [(date, value), ...]} sorted ascending. Market-priced holdings
+ are rebuilt as ledger_quantity(date) × price(date) so backdated trades
+ reshape the whole history; other assets use the stored amount. When
+ purchase_price/purchase_date are set and predate the first value, that point
+ is prepended as the earliest anchor.
"""
if not assets:
return {}
asset_ids = [a.id for a in assets]
q = (
- select(AssetValue.asset_id, AssetValue.date, AssetValue.amount)
+ select(AssetValue.asset_id, AssetValue.date, AssetValue.amount, AssetValue.price)
.where(AssetValue.asset_id.in_(asset_ids))
.order_by(AssetValue.asset_id, AssetValue.date, AssetValue.id)
)
@@ -219,10 +254,30 @@ async def _load_asset_native_values(
q = q.where(AssetValue.date <= up_to_date)
rows = (await session.execute(q)).all()
-
- values_map: dict[str, list[tuple[date, float]]] = {str(a.id): [] for a in assets}
- for aid, d, amt in rows:
- values_map[str(aid)].append((d, float(amt)))
+ raw: dict[str, list[tuple[date, Decimal, Optional[Decimal]]]] = {str(a.id): [] for a in assets}
+ for aid, d, amt, price in rows:
+ raw[str(aid)].append((d, amt, price))
+
+ # Bulk-load the ledger for market-priced holdings (one query).
+ market_ids = [a.id for a in assets if a.valuation_method == "market_price"]
+ txs_by_aid: dict[str, list[tuple[date, str, Decimal]]] = {}
+ if market_ids:
+ tq = select(
+ AssetTransaction.asset_id, AssetTransaction.date,
+ AssetTransaction.kind, AssetTransaction.quantity,
+ ).where(AssetTransaction.asset_id.in_(market_ids))
+ if up_to_date is not None:
+ tq = tq.where(AssetTransaction.date <= up_to_date)
+ for aid, d, kind, qty in (await session.execute(tq)).all():
+ txs_by_aid.setdefault(str(aid), []).append((d, kind, Decimal(str(qty))))
+
+ values_map: dict[str, list[tuple[date, float]]] = {}
+ for asset in assets:
+ aid = str(asset.id)
+ if asset.valuation_method == "market_price":
+ values_map[aid] = build_market_value_series(raw[aid], txs_by_aid.get(aid, []))
+ else:
+ values_map[aid] = [(d, float(amt)) for d, amt, _ in raw[aid]]
for asset in assets:
aid = str(asset.id)
@@ -389,6 +444,7 @@ async def create_asset(
AssetValue(
asset_id=asset.id,
amount=initial_amount,
+ price=Decimal(str(quote.price)),
date=date.today(),
source="sync",
)
@@ -436,9 +492,12 @@ async def create_asset(
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
+ # Unit price is the per-unit cost of the opening buy (consistent with
+ # the ledger). Fall back to the live quote when the user didn't enter
+ # one ("bought at market now").
buy_price = (
- Decimal(str(data.purchase_price)) / Decimal(str(data.units))
- if data.purchase_price is not None
+ Decimal(str(data.unit_price))
+ if data.unit_price is not None
else Decimal(str(quote.price))
)
session.add(
@@ -637,21 +696,42 @@ async def delete_asset_value(
async def get_asset_value_trend(
session: AsyncSession, asset_id: uuid.UUID, workspace_id: uuid.UUID, months: int = 12
) -> Optional[list[dict]]:
- """Get value trend data for charting."""
- # Verify ownership
- owner_check = await session.execute(
- select(Asset.id).where(Asset.id == asset_id, Asset.workspace_id == workspace_id)
- )
- if not owner_check.scalar_one_or_none():
+ """Get value trend data for charting.
+
+ For market-priced holdings the series is rebuilt from the ledger
+ (quantity(date) × price(date)) so entering past trades reshapes the whole
+ line; other assets use their stored value points.
+ """
+ asset = (
+ await session.execute(
+ select(Asset).where(Asset.id == asset_id, Asset.workspace_id == workspace_id)
+ )
+ ).scalar_one_or_none()
+ if asset is None:
return None
- result = await session.execute(
- select(AssetValue.date, AssetValue.amount)
- .where(AssetValue.asset_id == asset_id)
- .order_by(AssetValue.date)
- )
- rows = result.all()
- return [{"date": row[0].isoformat(), "amount": float(row[1])} for row in rows]
+ rows = (
+ await session.execute(
+ select(AssetValue.date, AssetValue.amount, AssetValue.price)
+ .where(AssetValue.asset_id == asset_id)
+ .order_by(AssetValue.date)
+ )
+ ).all()
+
+ if asset.valuation_method == "market_price":
+ txs = (
+ await session.execute(
+ select(AssetTransaction.date, AssetTransaction.kind, AssetTransaction.quantity)
+ .where(AssetTransaction.asset_id == asset_id)
+ )
+ ).all()
+ series = build_market_value_series(
+ [(d, a, p) for d, a, p in rows],
+ [(d, k, Decimal(str(q))) for d, k, q in txs],
+ )
+ return [{"date": d.isoformat(), "amount": v} for d, v in series]
+
+ return [{"date": d.isoformat(), "amount": float(a)} for d, a, _ in rows]
async def get_portfolio_trend(
@@ -875,12 +955,14 @@ async def _apply_price_to_asset(
today_value = existing.scalar_one_or_none()
if today_value is not None:
today_value.amount = new_amount
+ today_value.price = new_price
today_value.source = "sync"
else:
session.add(
AssetValue(
asset_id=asset.id,
amount=new_amount,
+ price=new_price,
date=today,
source="sync",
)
diff --git a/backend/tests/test_asset_service.py b/backend/tests/test_asset_service.py
index 6dda41de..db8445fb 100644
--- a/backend/tests/test_asset_service.py
+++ b/backend/tests/test_asset_service.py
@@ -16,10 +16,55 @@ from app.services.asset_service import (
_compute_current_value,
_generate_growth_values,
_next_due_date,
+ build_market_value_series,
get_portfolio_trend,
)
+def test_build_market_value_series_reflects_quantity_over_time():
+ """A backdated buy steps the value up from its date, not just today."""
+ rows = [
+ (date(2026, 5, 12), Decimal("9286"), Decimal("46.43")),
+ (date(2026, 5, 17), Decimal("9094"), Decimal("45.47")),
+ (date(2026, 6, 11), Decimal("8330"), Decimal("41.65")),
+ ]
+ txs = [
+ (date(2025, 12, 1), "buy", Decimal("200")),
+ (date(2026, 5, 15), "buy", Decimal("50")), # backdated, between the value points
+ ]
+ out = dict(build_market_value_series(rows, txs))
+ assert round(out[date(2026, 5, 12)]) == round(200 * 46.43) # before the buy → 200 units
+ assert round(out[date(2026, 5, 17)]) == round(250 * 45.47) # after → 250 units
+ assert round(out[date(2026, 6, 11)]) == round(250 * 41.65)
+
+
+def test_build_market_value_series_handles_sell_and_missing_price():
+ rows = [
+ (date(2026, 1, 1), Decimal("1000"), Decimal("10")), # 100 units
+ (date(2026, 2, 1), Decimal("0"), Decimal("12")), # after selling 40 → 60 units
+ (date(2026, 3, 1), Decimal("777"), None), # no price → fall back to amount
+ ]
+ txs = [
+ (date(2026, 1, 1), "buy", Decimal("100")),
+ (date(2026, 1, 20), "sell", Decimal("40")),
+ ]
+ out = dict(build_market_value_series(rows, txs))
+ assert out[date(2026, 1, 1)] == 1000.0 # 100 × 10
+ assert out[date(2026, 2, 1)] == 720.0 # 60 × 12
+ assert out[date(2026, 3, 1)] == 777.0 # fallback to stored amount
+
+
+def test_build_market_value_series_no_ledger_keeps_amounts():
+ """A holding with no transactions must not be zeroed — keep stored amounts."""
+ rows = [
+ (date(2026, 1, 1), Decimal("500"), Decimal("5")),
+ (date(2026, 2, 1), Decimal("600"), Decimal("6")),
+ ]
+ out = dict(build_market_value_series(rows, []))
+ assert out[date(2026, 1, 1)] == 500.0
+ assert out[date(2026, 2, 1)] == 600.0
+
+
@pytest_asyncio.fixture
async def test_asset(session: AsyncSession, test_user: User) -> Asset:
"""Create a test asset."""
diff --git a/backend/tests/test_market_price_assets.py b/backend/tests/test_market_price_assets.py
index 1306ac61..b0eabd0c 100644
--- a/backend/tests/test_market_price_assets.py
+++ b/backend/tests/test_market_price_assets.py
@@ -129,6 +129,50 @@ async def test_create_market_price_asset_seeds_quote_and_initial_value(
assert created.value_count == 1
+async def test_create_market_price_seeds_opening_buy_at_unit_price(
+ session: AsyncSession, test_user: User, test_workspace
+):
+ """The opening buy uses the user's unit price (preço médio), not the quote."""
+ provider = FakeMarketProvider({"AAPL": _quote("AAPL", 200.0)}) # market = 200
+ data = AssetCreate(
+ name="Apple",
+ type="stock",
+ valuation_method="market_price",
+ ticker="AAPL",
+ units=Decimal("10"),
+ unit_price=Decimal("150"), # bought cheaper than today's price
+ )
+ created = await asset_service.create_asset(
+ session, test_workspace.id, test_user.id, data, market_provider=provider
+ )
+ assert created.average_price == pytest.approx(150.0) # cost, not the quote
+ assert created.total_invested == pytest.approx(1500.0) # 10 × 150
+ assert created.current_value == pytest.approx(2000.0) # 10 × 200 (live)
+ assert created.gain_loss == pytest.approx(500.0) # unrealized
+ assert created.transaction_count == 1
+
+
+async def test_create_market_price_without_unit_price_uses_quote(
+ session: AsyncSession, test_user: User, test_workspace
+):
+ """Omitting the unit price falls back to the live quote (bought at market)."""
+ provider = FakeMarketProvider({"AAPL": _quote("AAPL", 180.0)})
+ data = AssetCreate(
+ name="Apple",
+ type="stock",
+ valuation_method="market_price",
+ ticker="AAPL",
+ units=Decimal("10"),
+ )
+ created = await asset_service.create_asset(
+ session, test_workspace.id, test_user.id, data, market_provider=provider
+ )
+ assert created.average_price == pytest.approx(180.0)
+ assert created.gain_loss == pytest.approx(0.0) # cost == current value
+
+
@pytest.mark.asyncio
async def test_create_market_price_asset_rejects_missing_ticker(
session: AsyncSession, test_user: User, test_workspace
diff --git a/frontend/src/pages/assets.tsx b/frontend/src/pages/assets.tsx
index 386d68ec..a2184476 100644
--- a/frontend/src/pages/assets.tsx
+++ b/frontend/src/pages/assets.tsx
@@ -175,6 +175,18 @@ const GROWTH_FREQUENCIES = ['daily', 'weekly', 'monthly', 'yearly'] as const
// 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'
+// Surface the backend's actual error message (FastAPI puts it in
+// response.data.detail) instead of a generic toast. Makes failures
+// diagnosable — e.g. the oversell guard message, or a "Not Found" when a
+// transaction endpoint is missing because the backend is older than the
+// frontend (issue #315) — rather than a cryptic "Error".
+function assetErrorMessage(e: unknown, fallback: string): string {
+ const resp = (e as { response?: { data?: { detail?: unknown }; status?: number } })?.response
+ const detail = resp?.data?.detail
+ if (typeof detail === 'string' && detail.trim()) return detail
+ return resp?.status ? `${fallback} (${resp.status})` : fallback
+}
+
export default function AssetsPage() {
const { t } = useTranslation()
const locale = useDisplayLocale()
@@ -237,6 +249,11 @@ export default function AssetsPage() {
const [tickerSearchLoading, setTickerSearchLoading] = useState(false)
const [selectedQuote, setSelectedQuote] = useState<MarketSymbolQuote | null>(null)
const [formUnits, setFormUnits] = useState('')
+ // Per-unit purchase price for the opening buy of a market-priced holding.
+ // Defaults to the live quote (buying at market now) and is the SAME input
+ // model as the buy/sell ledger — no total-purchase-price for tickers, so
+ // "Add asset" and "Add transaction" stay consistent.
+ const [formUnitPrice, setFormUnitPrice] = useState('')
const [quoteLoading, setQuoteLoading] = useState(false)
const { data: rawAssetsList, isLoading } = useQuery({
@@ -336,7 +353,7 @@ export default function AssetsPage() {
setDialogOpen(false)
toast.success(t('assets.created'))
},
- onError: () => toast.error(t('common.error')),
+ onError: (e) => toast.error(assetErrorMessage(e, t('common.error'))),
})
const updateMutation = useMutation({
@@ -348,7 +365,7 @@ export default function AssetsPage() {
setEditingAsset(null)
toast.success(t('assets.updated'))
},
- onError: () => toast.error(t('common.error')),
+ onError: (e) => toast.error(assetErrorMessage(e, t('common.error'))),
})
const deleteMutation = useMutation({
@@ -359,7 +376,7 @@ export default function AssetsPage() {
if (expandedId === deletingId) setExpandedId(null)
toast.success(t('assets.deleted'))
},
- onError: () => toast.error(t('common.error')),
+ onError: (e) => toast.error(assetErrorMessage(e, t('common.error'))),
})
const refreshPriceMutation = useMutation({
@@ -380,7 +397,7 @@ export default function AssetsPage() {
refetchAssetViews()
toast.success(t('assets.priceRefreshed'))
},
- onError: () => toast.error(t('common.error')),
+ onError: (e) => toast.error(assetErrorMessage(e, t('common.error'))),
})
const { data: rawWalletsList } = useQuery({
@@ -406,7 +423,7 @@ export default function AssetsPage() {
}
toast.success(t('assets.walletCreated'))
},
- onError: () => toast.error(t('common.error')),
+ onError: (e) => toast.error(assetErrorMessage(e, t('common.error'))),
})
const updateWalletMutation = useMutation({
@@ -418,7 +435,7 @@ export default function AssetsPage() {
setEditingWallet(null)
toast.success(t('assets.walletUpdated'))
},
- onError: () => toast.error(t('common.error')),
+ onError: (e) => toast.error(assetErrorMessage(e, t('common.error'))),
})
const deleteWalletMutation = useMutation({
@@ -430,7 +447,7 @@ export default function AssetsPage() {
setDeletingWalletId(null)
toast.success(t('assets.walletDeleted'))
},
- onError: () => toast.error(t('common.error')),
+ onError: (e) => toast.error(assetErrorMessage(e, t('common.error'))),
})
const moveAssetMutation = useMutation({
@@ -442,7 +459,7 @@ export default function AssetsPage() {
setMovingAsset(null)
toast.success(t('assets.moved'))
},
- onError: () => toast.error(t('common.error')),
+ onError: (e) => toast.error(assetErrorMessage(e, t('common.error'))),
})
// Compute projected current value for growth_rule preview in the form
@@ -517,6 +534,10 @@ export default function AssetsPage() {
try {
const quote = await assets.marketQuote(match.symbol)
setSelectedQuote(quote)
+ // Prefill the unit price with the live quote — "buying at market now"
+ // is the common case; the user overrides it with their real cost.
+ // Trim float noise to the DB's 6-decimal scale (39.41999… → 39.42).
+ setFormUnitPrice(String(Number(quote.price.toFixed(6))))
// Auto-fill name/currency from the authoritative quote so the user
// doesn't have to think about it — they can still edit name after.
if (!formName || formName === (selectedQuote?.name ?? selectedQuote?.symbol ?? '')) {
@@ -544,6 +565,7 @@ export default function AssetsPage() {
setTickerMatches([])
setSelectedQuote(null)
setFormUnits('')
+ setFormUnitPrice('')
setQuoteLoading(false)
setTickerSearchLoading(false)
}
@@ -605,6 +627,7 @@ export default function AssetsPage() {
}
function buildPayload() {
+ const isMarket = formMethod === 'market_price'
const payload: Record<string, unknown> = {
name: formName,
type: formType,
@@ -612,9 +635,12 @@ export default function AssetsPage() {
group_id: formGroupId || null,
valuation_method: formMethod,
purchase_date: formPurchaseDate || null,
- purchase_price: formPurchasePrice ? parseFloat(formPurchasePrice) : null,
- sell_date: formSellDate || null,
- sell_price: formSellPrice ? parseFloat(formSellPrice) : null,
+ // Tickers have no total purchase price — the cost basis is derived from
+ // the unit-price buy (and then the ledger). Only manual/growth assets
+ // carry a total purchase price.
+ purchase_price: isMarket ? null : (formPurchasePrice ? parseFloat(formPurchasePrice) : null),
+ sell_date: isMarket ? null : (formSellDate || null),
+ sell_price: isMarket ? null : (formSellPrice ? parseFloat(formSellPrice) : null),
}
if (formMethod === 'growth_rule') {
@@ -624,10 +650,15 @@ export default function AssetsPage() {
payload.growth_start_date = formGrowthStartDate || null
}
- if (formMethod === 'market_price') {
+ if (isMarket) {
payload.ticker = (selectedQuote?.symbol || formTickerQuery || '').toUpperCase()
payload.ticker_exchange = selectedQuote?.exchange ?? null
payload.units = formUnits ? parseFloat(formUnits) : null
+ // Opening buy price per unit (defaults to the live quote on the server
+ // when omitted). Only meaningful on create.
+ if (!editingAsset) {
+ payload.unit_price = formUnitPrice ? parseFloat(formUnitPrice) : null
+ }
}
if (!editingAsset && formCurrentValue) {
@@ -793,15 +824,19 @@ export default function AssetsPage() {
{isExpanded && (
isMarketPriced ? (
- <HoldingLedger
- asset={asset}
- locale={locale}
- dateLocale={dateLocale}
- mask={mask}
- canWrite={canWrite}
- onAdd={() => openAddTransaction(asset.id)}
- onChanged={refetchAssetViews}
- />
+ <>
+ {/* Value-evolution chart on top, then the buy/sell ledger. */}
+ <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} chartOnly />
+ <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} />
)
@@ -1283,27 +1318,49 @@ export default function AssetsPage() {
</div>
)}
- <div className="space-y-2">
- <Label>{t('assets.quantity')}</Label>
- <Input
- type="number"
- step="any"
- min="0"
- value={formUnits}
- onChange={e => setFormUnits(e.target.value)}
- placeholder="10"
- />
- </div>
+ {!editingAsset ? (
+ <div className="grid grid-cols-2 gap-3">
+ <div className="space-y-2">
+ <Label>{t('assets.quantity')}</Label>
+ <Input
+ type="number"
+ step="any"
+ min="0"
+ value={formUnits}
+ onChange={e => setFormUnits(e.target.value)}
+ placeholder="10"
+ />
+ </div>
+ <div className="space-y-2">
+ <Label>{t('assets.unitPrice')}</Label>
+ <Input
+ type="number"
+ step="any"
+ min="0"
+ value={formUnitPrice}
+ onChange={e => setFormUnitPrice(e.target.value)}
+ placeholder={selectedQuote ? String(selectedQuote.price) : '0.00'}
+ />
+ </div>
+ </div>
+ ) : (
+ <div className="space-y-2">
+ <Label>{t('assets.quantity')}</Label>
+ <Input type="number" step="any" min="0" value={formUnits} onChange={e => setFormUnits(e.target.value)} placeholder="10" />
+ </div>
+ )}
- {selectedQuote && formUnits && parseFloat(formUnits) > 0 && (
+ {/* Buy total — same qty × unit price model as the ledger, so
+ the value matches the Add-transaction dialog exactly. */}
+ {!editingAsset && formUnits && parseFloat(formUnits) > 0 && (selectedQuote || formUnitPrice) && (
<div className="flex items-center justify-between p-3 rounded-lg border border-primary/30 bg-primary/10">
<span className="text-xs font-medium text-primary/80">
- {t('assets.currentValue')}
+ {t('assets.txTotal')}
</span>
<span className="text-lg font-bold tabular-nums text-primary">
{formatCurrency(
- selectedQuote.price * parseFloat(formUnits),
- selectedQuote.currency,
+ (parseFloat(formUnitPrice) || selectedQuote?.price || 0) * parseFloat(formUnits),
+ selectedQuote?.currency || formCurrency,
locale,
)}
</span>
@@ -1363,29 +1420,36 @@ export default function AssetsPage() {
</div>
)}
- {/* Purchase Info */}
+ {/* Purchase Info. For tickers the cost comes from the unit-price
+ buy above, so we only ask for the purchase (buy) date here and
+ hide the total-price field. Manual assets keep both. */}
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label>{t('assets.purchaseDate')}</Label>
<DatePickerInput value={formPurchaseDate} onChange={setFormPurchaseDate} />
</div>
- <div className="space-y-2">
- <Label>{t('assets.purchasePrice')}</Label>
- <Input type="number" step="0.01" value={formPurchasePrice} onChange={e => setFormPurchasePrice(e.target.value)} />
- </div>
+ {formMethod !== 'market_price' && (
+ <div className="space-y-2">
+ <Label>{t('assets.purchasePrice')}</Label>
+ <Input type="number" step="0.01" value={formPurchasePrice} onChange={e => setFormPurchasePrice(e.target.value)} />
+ </div>
+ )}
</div>
- {/* Sell Info */}
- <div className="grid grid-cols-2 gap-4">
- <div className="space-y-2">
- <Label>{t('assets.sellDate')}</Label>
- <DatePickerInput value={formSellDate} onChange={setFormSellDate} />
- </div>
- <div className="space-y-2">
- <Label>{t('assets.sellPrice')}</Label>
- <Input type="number" step="0.01" value={formSellPrice} onChange={e => setFormSellPrice(e.target.value)} />
+ {/* Sell Info — manual assets only. Tickers record sells through the
+ buy/sell ledger, not the create form. */}
+ {formMethod !== 'market_price' && (
+ <div className="grid grid-cols-2 gap-4">
+ <div className="space-y-2">
+ <Label>{t('assets.sellDate')}</Label>
+ <DatePickerInput value={formSellDate} onChange={setFormSellDate} />
+ </div>
+ <div className="space-y-2">
+ <Label>{t('assets.sellPrice')}</Label>
+ <Input type="number" step="0.01" value={formSellPrice} onChange={e => setFormSellPrice(e.target.value)} />
+ </div>
</div>
- </div>
+ )}
{/* Current Value — manual only */}
{!editingAsset && formMethod === 'manual' && (
@@ -1838,11 +1902,32 @@ function PortfolioChart({ data, wallets, currency, locale: loc, dateLocale: date
)
}
-function AssetDetail({ assetId, currency, locale: loc, dateLocale: dateLoc, purchasePrice, purchaseDate, valuationMethod, canWrite }: {
+// Marker drawn on the value chart where a buy (green) or sell (red) happened.
+// Recharts calls this per data point; non-trade points render an empty group.
+function renderAssetTradeDot(props: {
+ cx?: number; cy?: number; index?: number; payload?: { trades?: AssetTransaction[] }
+}) {
+ const { cx, cy, index, payload } = props
+ const trades = payload?.trades
+ if (cx == null || cy == null || !trades || trades.length === 0) {
+ return <g key={`td-${index}`} />
+ }
+ const hasBuy = trades.some(t => t.kind === 'buy')
+ const hasSell = trades.some(t => t.kind === 'sell')
+ const color = hasSell && !hasBuy ? '#F43F5E' : hasBuy && !hasSell ? '#10B981' : '#6366F1'
+ return (
+ <circle key={`td-${index}`} cx={cx} cy={cy} r={4} fill={color} stroke="var(--card)" strokeWidth={1.5} />
+ )
+}
+
+function AssetDetail({ assetId, currency, locale: loc, dateLocale: dateLoc, purchasePrice, purchaseDate, valuationMethod, canWrite, chartOnly = false }: {
assetId: string; currency: string; locale: string; dateLocale: string
purchasePrice: number | null; purchaseDate: string | null
valuationMethod: string
canWrite: boolean
+ // When true, render only the value-evolution chart (used above the ledger
+ // for market-priced holdings) — no manual value form / value-history list.
+ chartOnly?: boolean
}) {
const { t } = useTranslation()
const { mask } = usePrivacyMode()
@@ -1876,6 +1961,30 @@ function AssetDetail({ assetId, currency, locale: loc, dateLocale: dateLoc, purc
return result
}, [trend, purchasePrice, purchaseDate])
+ // Buy/sell markers on the value chart (shares the ledger's query cache).
+ // Without these, a jump in the line could be either a price move or a
+ // quantity change — the markers label "you bought/sold here".
+ const { data: assetTrades } = useQuery({
+ queryKey: ['asset-transactions', assetId],
+ queryFn: () => assets.transactions(assetId),
+ enabled: valuationMethod === 'market_price',
+ })
+ const chartData = useMemo(() => {
+ const pts = trendWithPurchase.map(p => ({ ...p, trades: [] as AssetTransaction[] }))
+ if (!assetTrades || pts.length === 0) return pts
+ for (const tx of assetTrades) {
+ const txTime = new Date(tx.date + 'T00:00:00').getTime()
+ let best = 0
+ let bestDiff = Infinity
+ for (let i = 0; i < pts.length; i++) {
+ const diff = Math.abs(new Date(pts[i].date + 'T00:00:00').getTime() - txTime)
+ if (diff < bestDiff) { bestDiff = diff; best = i }
+ }
+ pts[best].trades.push(tx)
+ }
+ return pts
+ }, [trendWithPurchase, assetTrades])
+
// Build value history with purchase as the initial entry
const valuesWithPurchase = useMemo(() => {
if (!values) return []
@@ -1904,7 +2013,7 @@ function AssetDetail({ assetId, currency, locale: loc, dateLocale: dateLoc, purc
setValueAmount('')
toast.success(t('assets.valueAdded'))
},
- onError: () => toast.error(t('common.error')),
+ onError: (e) => toast.error(assetErrorMessage(e, t('common.error'))),
})
const deleteValueMutation = useMutation({
@@ -1917,7 +2026,7 @@ function AssetDetail({ assetId, currency, locale: loc, dateLocale: dateLoc, purc
queryClient.refetchQueries({ queryKey: ['dashboard'] })
toast.success(t('assets.valueDeleted'))
},
- onError: () => toast.error(t('common.error')),
+ onError: (e) => toast.error(assetErrorMessage(e, t('common.error'))),
})
// Determine chart color based on trend direction
@@ -1926,15 +2035,20 @@ function AssetDetail({ assetId, currency, locale: loc, dateLocale: dateLoc, purc
: true
const chartColor = trendIsPositive ? '#10B981' : '#F43F5E'
+ const hasChart = trendWithPurchase.length > 1
+ // In chart-only mode (market-priced holdings, paired with the ledger) there's
+ // nothing to show until the value series has at least two points.
+ if (chartOnly && !hasChart) return null
+
return (
<div className="border-t border-border px-5 py-5 space-y-5 bg-muted/5">
{/* Value Trend Chart */}
- {trendWithPurchase.length > 1 && (
+ {hasChart && (
<div>
<p className="text-[11px] font-semibold text-muted-foreground uppercase tracking-wider mb-3">{t('assets.valueTrend')}</p>
<div className="h-44 -mx-1">
<ResponsiveContainer width="100%" height="100%">
- <AreaChart data={trendWithPurchase} margin={{ top: 4, right: 12, left: 0, bottom: 0 }}>
+ <AreaChart data={chartData} margin={{ top: 4, right: 12, left: 0, bottom: 0 }}>
<defs>
<linearGradient id={`gradient-${assetId}`} x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stopColor={chartColor} stopOpacity={0.2} />
@@ -1965,15 +2079,22 @@ function AssetDetail({ assetId, currency, locale: loc, dateLocale: dateLoc, purc
}}
/>
<RechartsTooltip
- formatter={(value: number | undefined) => [mask(formatCurrency(value ?? 0, currency, loc)), t('assets.currentValue')]}
- labelFormatter={(label: unknown) => new Date(String(label) + 'T00:00:00').toLocaleDateString(dateLoc, { day: 'numeric', month: 'long', year: 'numeric' })}
- contentStyle={{
- background: 'var(--card)',
- color: 'var(--foreground)',
- border: '1px solid var(--border)',
- borderRadius: '0.75rem',
- fontSize: '12px',
- boxShadow: '0 4px 12px rgba(0,0,0,0.08)',
+ content={({ active, payload, label }) => {
+ if (!active || !payload?.length) return null
+ const pt = payload[0].payload as { amount?: number; trades?: AssetTransaction[] }
+ return (
+ <div style={{ background: 'var(--card)', color: 'var(--foreground)', border: '1px solid var(--border)', borderRadius: '0.75rem', fontSize: '12px', boxShadow: '0 4px 12px rgba(0,0,0,0.08)', padding: '8px 10px' }}>
+ <p style={{ fontWeight: 600, marginBottom: 4 }}>
+ {new Date(String(label) + 'T00:00:00').toLocaleDateString(dateLoc, { day: 'numeric', month: 'long', year: 'numeric' })}
+ </p>
+ <div style={{ fontVariantNumeric: 'tabular-nums' }}>{mask(formatCurrency(pt.amount ?? 0, currency, loc))}</div>
+ {pt.trades?.map((tx) => (
+ <div key={tx.id} style={{ marginTop: 3, fontSize: 11, fontWeight: 500, color: tx.kind === 'buy' ? '#10B981' : '#F43F5E' }}>
+ {tx.kind === 'buy' ? t('assets.txBuy') : t('assets.txSell')} {mask(`${tx.quantity}`)} × {mask(formatCurrency(tx.price, currency, loc))}
+ </div>
+ ))}
+ </div>
+ )
}}
/>
<Area
@@ -1982,7 +2103,7 @@ function AssetDetail({ assetId, currency, locale: loc, dateLocale: dateLoc, purc
stroke={chartColor}
strokeWidth={2}
fill={`url(#gradient-${assetId})`}
- dot={false}
+ dot={renderAssetTradeDot}
activeDot={{ r: 4, strokeWidth: 2, fill: 'var(--card)', stroke: chartColor }}
/>
</AreaChart>
@@ -1992,7 +2113,7 @@ function AssetDetail({ assetId, currency, locale: loc, dateLocale: dateLoc, purc
)}
{/* Add Value Form — only for manual assets */}
- {valuationMethod === 'manual' && canWrite && <div className="flex items-end gap-2">
+ {!chartOnly && valuationMethod === 'manual' && canWrite && <div className="flex items-end gap-2">
<div className="flex-1">
<Label className="text-[11px] text-muted-foreground">{t('assets.amount')}</Label>
<Input
@@ -2028,7 +2149,7 @@ function AssetDetail({ assetId, currency, locale: loc, dateLocale: dateLoc, purc
</div>}
{/* Value History */}
- <div>
+ {!chartOnly && <div>
<p className="text-[11px] font-semibold text-muted-foreground uppercase tracking-wider mb-2">{t('assets.valueHistory')}</p>
{valuesLoading ? (
<Skeleton className="h-20 w-full rounded-lg" />
@@ -2078,7 +2199,7 @@ function AssetDetail({ assetId, currency, locale: loc, dateLocale: dateLoc, purc
) : (
<p className="text-xs text-muted-foreground py-3 text-center">{t('dashboard.noData')}</p>
)}
- </div>
+ </div>}
</div>
)
}
@@ -2174,7 +2295,7 @@ function AssetTransactionsTab({
setEditingTx(null)
toast.success(t('assets.txSaved'))
},
- onError: () => toast.error(t('common.error')),
+ onError: (e) => toast.error(assetErrorMessage(e, t('common.error'))),
})
const deleteMutation = useMutation({
@@ -2184,7 +2305,7 @@ function AssetTransactionsTab({
setDeletingId(null)
toast.success(t('assets.txDeleted'))
},
- onError: () => toast.error(t('common.error')),
+ onError: (e) => toast.error(assetErrorMessage(e, t('common.error'))),
})
function openAdd() {
@@ -2526,7 +2647,7 @@ function HoldingLedger({
onChanged()
toast.success(t('assets.txDeleted'))
},
- onError: () => toast.error(t('common.error')),
+ onError: (e) => toast.error(assetErrorMessage(e, t('common.error'))),
})
return (
@@ -2629,7 +2750,7 @@ function AddHoldingTransactionDialog({
onClose()
toast.success(t('assets.txSaved'))
},
- onError: () => toast.error(t('common.error')),
+ onError: (e) => toast.error(assetErrorMessage(e, t('common.error'))),
})
const cur = holding?.currency ?? 'USD'