Skip to content

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

47.3 KB
Raw Blame
import logging
import uuid
from datetime import date, datetime, timezone, timedelta
from decimal import Decimal
from typing import Any, Optional, cast

from fastapi import HTTPException, status
from sqlalchemy import select, func, desc, update as sa_update
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession

from app.core.app_clock import app_today
from app.models.account import Account
from app.models.asset import ASSET_PRICE_DECIMALS, LOAN_COLLATERAL_TYPES, Asset
from app.models.asset_transaction import AssetTransaction
from app.models.asset_value import AssetValue
from app.models.user import User
from app.core.config import get_settings
from app.providers.market_price import (
    MarketPriceProvider,
    MarketPriceRateLimitedError,
    get_market_price_provider,
)
from app.schemas.asset import AssetCreate, AssetUpdate, AssetValueCreate, AssetRead, AssetValueRead
from app.services.asset_group_service import ensure_group_in_workspace
from app.services.fx_rate_service import convert, has_rate, stamp_primary_amount

logger = logging.getLogger(__name__)

ValueRecord = tuple[date, Decimal, Optional[Decimal]]  # (date, amount, price_per_share)
TxRecord = tuple[date, str, Decimal, Optional[Decimal]]  # (date, kind, quantity, price_per_share)


def _next_due_date(last_date: date, frequency: str) -> date:
    """Calculate the next due date based on frequency."""
    if frequency == "daily":
        return last_date + timedelta(days=1)
    elif frequency == "weekly":
        return last_date + timedelta(weeks=1)
    elif frequency == "monthly":
        month = last_date.month + 1
        year = last_date.year
        if month > 12:
            month = 1
            year += 1
        day = min(last_date.day, 28)
        return date(year, month, day)
    elif frequency == "yearly":
        return date(last_date.year + 1, last_date.month, last_date.day)
    return last_date + timedelta(days=1)


def _compute_current_value(asset: Asset, latest_value: Optional[AssetValue]) -> Optional[float]:
    """Compute the current value of an asset from its latest AssetValue.
    Falls back to purchase_price if no value entries exist yet."""
    # Market-priced assets are authoritative on (units × last_price). The
    # AssetValue history exists for the chart, but the "live" number users
    # see should reflect the most recent quote even between scheduled syncs.
    if asset.valuation_method == "market_price":
        if asset.last_price is not None and asset.units is not None:
            return float(Decimal(str(asset.last_price)) * Decimal(str(asset.units)))
        if latest_value is not None:
            return float(latest_value.amount)
        return None
    if latest_value is None:
        if asset.purchase_price is not None:
            return float(asset.purchase_price)
        return None
    return float(latest_value.amount)


def _generate_growth_values(
    asset_id: uuid.UUID,
    base_amount: float,
    base_date: date,
    growth_type: str,
    growth_rate: float,
    growth_frequency: str,
    growth_start_date: Optional[date],
) -> list[AssetValue]:
    """Generate all AssetValue rows from base_date to today using the growth rule.
    When growth_start_date is set, growth iteration begins from that date — not
    from base_date — so the asset accrues no growth for the gap between
    purchase and the configured growth start."""
    today = app_today()
    if growth_start_date and today < growth_start_date:
        return []

    values: list[AssetValue] = []
    current_amount = base_amount
    # Match the frontend preview: `growth_start_date or base_date`. Otherwise
    # backfill applied growth periods between purchase_date and
    # growth_start_date that the form said wouldn't accrue, leaving the
    # list-page total exactly N growth periods higher than the edit
    # dialog's calculated value.
    current_date = growth_start_date if growth_start_date else base_date

    while True:
        next_due = _next_due_date(current_date, growth_frequency)
        if next_due > today:
            break
        if growth_type == "percentage":
            current_amount = current_amount * (1 + growth_rate / 100)
        elif growth_type == "absolute":
            current_amount = current_amount + growth_rate
        else:
            break
        values.append(AssetValue(
            asset_id=asset_id,
            amount=Decimal(str(round(current_amount, 6))),
            date=next_due,
            source="rule",
        ))
        current_date = next_due
        if len(values) >= 10000:
            break

    return values


def _asset_to_read(
    asset: Asset,
    latest_value: Optional[AssetValue],
    value_count: int,
    transaction_count: int = 0,
) -> AssetRead:
    """Convert an Asset model + computed fields to AssetRead schema."""
    current_value = _compute_current_value(asset, latest_value)
    gain_loss = None
    if current_value is not None and asset.purchase_price is not None:
        gain_loss = current_value - float(asset.purchase_price)

    # 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,
        name=asset.name,
        type=asset.type,
        currency=asset.currency,
        units=float(asset.units) if asset.units is not None else None,
        valuation_method=asset.valuation_method,
        purchase_date=asset.purchase_date,
        purchase_price=float(asset.purchase_price) if asset.purchase_price is not None else None,
        sell_date=asset.sell_date,
        sell_price=float(asset.sell_price) if asset.sell_price is not None else None,
        growth_type=asset.growth_type,
        growth_rate=float(asset.growth_rate) if asset.growth_rate is not None else None,
        growth_frequency=asset.growth_frequency,
        growth_start_date=asset.growth_start_date,
        is_archived=asset.is_archived,
        position=asset.position,
        current_value=current_value,
        gain_loss=gain_loss,
        value_count=value_count,
        source=asset.source,
        external_id=asset.external_id,
        connection_id=asset.connection_id,
        isin=asset.isin,
        maturity_date=asset.maturity_date,
        group_id=asset.group_id,
        ticker=asset.ticker,
        ticker_exchange=asset.ticker_exchange,
        last_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,
    )


async def _get_latest_value(session: AsyncSession, asset_id: uuid.UUID) -> Optional[AssetValue]:
    """Get the most recent AssetValue for an asset."""
    result = await session.execute(
        select(AssetValue)
        .where(AssetValue.asset_id == asset_id)
        .order_by(desc(AssetValue.date), desc(AssetValue.id))
        .limit(1)
    )
    return result.scalar_one_or_none()


async def _get_value_as_of(
    session: AsyncSession, asset_id: uuid.UUID, as_of_date: date
) -> Optional[AssetValue]:
    """Get the most recent AssetValue for an asset on or before as_of_date."""
    result = await session.execute(
        select(AssetValue)
        .where(AssetValue.asset_id == asset_id, AssetValue.date <= as_of_date)
        .order_by(desc(AssetValue.date), desc(AssetValue.id))
        .limit(1)
    )
    return result.scalar_one_or_none()


def build_market_value_series(
    value_rows: list[ValueRecord],
    txs: list[TxRecord],
) -> 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
    most recent 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
    trade's own price on dates that predate any recorded market price (backdated
    trades entered before price tracking began), and to the baked amount when
    neither a price nor a later market price exists.

    A point is emitted at every stored-value date *and* every trade date, so a
    quantity change shows up on the chart at the date it happened. Without the
    trade-date points, a holding whose stored prices only start recently (the
    common case — prices are recorded daily from when the holding was added)
    collapses every backdated trade onto a single early anchor and renders one
    long straight interpolation across the gap. `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]

    # Net quantity change per trade date, plus a representative per-share price
    # (the day's last trade) used to value points that predate any market price.
    tx_delta: dict[date, Decimal] = {}
    tx_price: dict[date, Decimal] = {}
    for d, kind, q, p in sorted(txs, key=lambda t: t[0]):
        tx_delta[d] = tx_delta.get(d, Decimal("0")) + (q if kind == "buy" else -q)
        if p is not None:
            tx_price[d] = p

    # Stored value points by date (last write wins on duplicate dates).
    value_by_date: dict[date, tuple[Decimal, Optional[Decimal]]] = {
        d: (amount, price) for d, amount, price in value_rows
    }

    out: list[tuple[date, float]] = []
    qty = Decimal("0")
    last_price: Optional[Decimal] = None  # most recent known per-share price
    seen_market = False  # has a stored market price been reached yet?
    for d in sorted(set(value_by_date) | set(tx_delta)):
        qty += tx_delta.get(d, Decimal("0"))
        held = qty if qty > 0 else Decimal("0")

        amount, price = value_by_date.get(d, (0.0, None))
        if price is not None:
            last_price = price  # a recorded market price always wins
            seen_market = True
        elif not seen_market and d in tx_price:
            # Before any market price is recorded, value each trade at its own
            # price so backdated points aren't flattened onto a single anchor.
            # Once market prices begin they take over and carry forward.
            last_price = tx_price[d]

        if d in value_by_date and price is None:
            out.append((d, float(amount)))  # stored point with no per-share price
        elif last_price is not None:
            out.append((d, float(last_price * held)))
        else:
            out.append((d, 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 each asset's value series (native currency).

    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, AssetValue.price)
        .where(AssetValue.asset_id.in_(asset_ids))
        .order_by(AssetValue.asset_id, AssetValue.date, AssetValue.id)
    )
    if up_to_date is not None:
        q = q.where(AssetValue.date <= up_to_date)

    rows = (await session.execute(q)).all()
    raw: dict[str, list[ValueRecord]] = {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[TxRecord]] = {}
    if market_ids:
        tq = select(
            AssetTransaction.asset_id, AssetTransaction.date,
            AssetTransaction.kind, AssetTransaction.quantity, AssetTransaction.price,
        ).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, price in (await session.execute(tq)).all():
            txs_by_aid.setdefault(str(aid), []).append(
                (d, kind, Decimal(str(qty)), Decimal(str(price)) if price is not None else None)
            )

    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)
        vals = values_map[aid]
        if asset.purchase_price is not None and asset.purchase_date is not None:
            if not vals or asset.purchase_date < vals[0][0]:
                vals.insert(0, (asset.purchase_date, float(asset.purchase_price)))

    return values_map


def _fill_forward_at(
    asset: Asset,
    sorted_vals: list[tuple[date, float]],
    as_of: date,
) -> Optional[float]:
    """Return the fill-forwarded native value of asset at as_of, or None.

    Scans sorted_vals for the latest entry on or before as_of. Falls back
    to purchase_price when purchase_date is None (asset predates any known
    date) and no value history is available for the requested date.
    """
    result = None
    for d, v in sorted_vals:
        if d <= as_of:
            result = v
        else:
            break
    if result is None and asset.purchase_price is not None and asset.purchase_date is None:
        result = float(asset.purchase_price)
    return result


async def _get_value_count(session: AsyncSession, asset_id: uuid.UUID) -> int:
    """Get the number of AssetValue entries for an asset."""
    result = await session.scalar(
        select(func.count()).select_from(AssetValue).where(AssetValue.asset_id == asset_id)
    )
    return result or 0


async def _get_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]:
    """List all assets in a workspace with computed current_value."""
    query = select(Asset).where(Asset.workspace_id == workspace_id)
    if not include_archived:
        query = query.where(Asset.is_archived == False)
    query = query.order_by(Asset.position, Asset.name)

    result = await session.execute(query)
    assets = list(result.scalars().all())

    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, tx_counts.get(asset.id, 0)))
    return reads


async def get_asset(
    session: AsyncSession, asset_id: uuid.UUID, workspace_id: uuid.UUID
) -> Optional[AssetRead]:
    """Get a single asset with computed fields."""
    result = await session.execute(
        select(Asset).where(Asset.id == asset_id, Asset.workspace_id == workspace_id)
    )
    asset = result.scalar_one_or_none()
    if not asset:
        return None
    latest = await _get_latest_value(session, asset.id)
    count = await _get_value_count(session, asset.id)
    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(
    session: AsyncSession,
    workspace_id: uuid.UUID,
    user_id: uuid.UUID,
    data: AssetCreate,
    *,
    market_provider: Optional[MarketPriceProvider] = None,
) -> AssetRead:
    """Create an asset, optionally with an initial value."""
    await ensure_group_in_workspace(session, data.group_id, workspace_id)
    # Market-priced path: fetch a live quote first so we can derive currency
    # and the initial value from the ticker. Validate up-front rather than
    # half-creating an asset and failing on a 5xx from Yahoo.
    quote = None
    if data.valuation_method == "market_price":
        if not data.ticker:
            raise HTTPException(
                status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
                detail="ticker is required for market_price assets",
            )
        if data.units is None or data.units <= 0:
            raise HTTPException(
                status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
                detail="units (quantity) must be > 0 for market_price assets",
            )
        provider = market_provider or get_market_price_provider()
        quote = await provider.get_quote(data.ticker)
        if quote is None:
            raise HTTPException(
                status_code=status.HTTP_502_BAD_GATEWAY,
                detail=f"Could not fetch quote for {data.ticker}",
            )

    source = (
        "tesouro_direto"
        if quote and quote.exchange == "Tesouro Direto"
        else ("yfinance" if data.valuation_method == "market_price" else "manual")
    )
    if data.external_id is not None:
        existing_result = await session.execute(
            select(Asset).where(
                Asset.workspace_id == workspace_id,
                Asset.source == source,
                Asset.external_id == data.external_id,
            )
        )
        existing = existing_result.scalar_one_or_none()
        if existing is not None:
            existing_read = await get_asset(session, existing.id, workspace_id)
            assert existing_read is not None
            return existing_read

    asset = Asset(
        user_id=user_id,
        workspace_id=workspace_id,
        name=data.name,
        type=data.type,
        # For market_price, the quote's currency is authoritative — a user
        # entering PETR4.SA from an English-language form shouldn't end up
        # with USD just because the dropdown defaulted to USD.
        currency=quote.currency if quote else data.currency,
        units=data.units,
        valuation_method=data.valuation_method,
        purchase_date=data.purchase_date,
        purchase_price=data.purchase_price,
        sell_date=data.sell_date,
        sell_price=data.sell_price,
        growth_type=data.growth_type,
        growth_rate=data.growth_rate,
        growth_frequency=data.growth_frequency,
        growth_start_date=data.growth_start_date,
        maturity_date=data.maturity_date,
        is_archived=data.is_archived,
        position=data.position,
        group_id=data.group_id,
        ticker=data.ticker.upper() if data.ticker else None,
        ticker_exchange=data.ticker_exchange or (quote.exchange if quote else None),
        last_price=Decimal(str(quote.price)) if quote else None,
        last_price_at=datetime.now(timezone.utc) if quote else None,
        logo_url=quote.logo_url if quote else None,
        external_id=data.external_id,
        source=source,
    )
    session.add(asset)
    try:
        await session.flush()
    except IntegrityError:
        # Return the winner when concurrent requests use the same external ID.
        await session.rollback()
        if data.external_id is not None:
            existing_result = await session.execute(
                select(Asset).where(
                    Asset.workspace_id == workspace_id,
                    Asset.source == source,
                    Asset.external_id == data.external_id,
                )
            )
            existing = existing_result.scalar_one_or_none()
            if existing is not None:
                existing_read = await get_asset(session, existing.id, workspace_id)
                assert existing_read is not None
                return existing_read
        raise

    # Seed the first AssetValue from the live quote so the portfolio chart
    # has a starting data point without waiting for the scheduled refresh.
    if data.valuation_method == "market_price" and quote is not None:
        initial_amount = Decimal(str(quote.price)) * Decimal(str(data.units))
        session.add(
            AssetValue(
                asset_id=asset.id,
                amount=initial_amount,
                price=Decimal(str(quote.price)),
                date=app_today(),
                source="sync",
            )
        )


    # Create initial value if provided
    if data.current_value is not None:
        value = AssetValue(
            asset_id=asset.id,
            amount=data.current_value,
            date=app_today(),
            source="manual",
        )
        session.add(value)
    elif data.valuation_method == "growth_rule" and data.purchase_price is not None:
        # Seed the initial value from purchase price
        base_date = data.purchase_date or data.growth_start_date or app_today()
        seed = AssetValue(
            asset_id=asset.id,
            amount=data.purchase_price,
            date=base_date,
            source="manual",
        )
        session.add(seed)

        # Backfill all growth values from the seed date to today
        if data.growth_type and data.growth_rate and data.growth_frequency:
            backfill = _generate_growth_values(
                asset_id=asset.id,
                base_amount=float(data.purchase_price),
                base_date=base_date,
                growth_type=data.growth_type,
                growth_rate=float(data.growth_rate),
                growth_frequency=data.growth_frequency,
                growth_start_date=data.growth_start_date,
            )
            for v in backfill:
                session.add(v)

    # 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

        # 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.unit_price))
            if data.unit_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 app_today(),
                source="manual",
            )
        )
        await session.flush()
        await asset_transaction_service.recompute_and_cache(session, asset)

    # Stamp purchase_price_primary
    if asset.purchase_price is not None:
        await stamp_primary_amount(
            session, user_id, asset,
            amount_field="purchase_price",
            primary_field="purchase_price_primary",
            rate_field="_no_rate",  # Asset has no rate field
            date_field="purchase_date",
        )

    await session.commit()
    await session.refresh(asset)
    latest = await _get_latest_value(session, asset.id)
    count = await _get_value_count(session, asset.id)
    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)


# Fields a ledger-backed holding derives from its transactions (see
# asset_transaction_service.recompute_and_cache); an asset update ignores them.
_LEDGER_DERIVED_FIELDS = (
    "units",
    "purchase_price",
    "purchase_date",
    "sell_date",
    "sell_price",
)


async def update_asset(
    session: AsyncSession,
    asset_id: uuid.UUID,
    workspace_id: uuid.UUID,
    user_id: uuid.UUID,
    data: AssetUpdate,
    regenerate_growth: bool = False,
) -> Optional[AssetRead]:
    """Partial update of an asset."""
    result = await session.execute(
        select(Asset).where(Asset.id == asset_id, Asset.workspace_id == workspace_id)
    )
    asset = result.scalar_one_or_none()
    if not asset:
        return None

    update_data = data.model_dump(exclude_unset=True)
    if "group_id" in update_data:
        await ensure_group_in_workspace(session, update_data["group_id"], workspace_id)
    # Prevent changing valuation_method on existing assets
    update_data.pop("valuation_method", None)

    tx_count = await session.scalar(
        select(func.count()).select_from(AssetTransaction).where(AssetTransaction.asset_id == asset.id)
    ) or 0
    # Ledger-backed holdings derive their position (units, cost basis, buy and
    # sell dates) from the transactions ledger. Editing the holding itself
    # (e.g. renaming it) must never overwrite those cached values, or the cost
    # basis is lost and the holding looks like it has no buys (issue #965).
    is_ledger = asset.average_price is not None or tx_count > 0
    if is_ledger:
        for key in _LEDGER_DERIVED_FIELDS:
            update_data.pop(key, None)

    for key, value in update_data.items():
        setattr(asset, key, value)

    # Only a property or a vehicle can secure a loan, so an asset that changes
    # to another type releases its loans instead of leaving them linked to it.
    if asset.type not in LOAN_COLLATERAL_TYPES:
        await session.execute(
            sa_update(Account)
            .where(Account.secured_asset_id == asset.id)
            .values(secured_asset_id=None)
        )

    # Regenerate growth-rule values if requested
    if regenerate_growth and asset.valuation_method == "growth_rule":
        # Delete all rule-generated values
        await session.execute(
            select(AssetValue)
            .where(AssetValue.asset_id == asset.id, AssetValue.source == "rule")
        )
        from sqlalchemy import delete as sa_delete
        await session.execute(
            sa_delete(AssetValue).where(
                AssetValue.asset_id == asset.id,
                AssetValue.source == "rule",
            )
        )
        # Regenerate from purchase_price
        if asset.purchase_price and asset.growth_type and asset.growth_rate and asset.growth_frequency:
            base_date = asset.purchase_date or asset.growth_start_date or app_today()
            backfill = _generate_growth_values(
                asset_id=asset.id,
                base_amount=float(asset.purchase_price),
                base_date=base_date,
                growth_type=asset.growth_type,
                growth_rate=float(asset.growth_rate),
                growth_frequency=asset.growth_frequency,
                growth_start_date=asset.growth_start_date,
            )
            for v in backfill:
                session.add(v)

    # Re-stamp purchase_price_primary if purchase_price or currency changed
    if "purchase_price" in update_data or "currency" in update_data:
        if asset.purchase_price is not None:
            await stamp_primary_amount(
                session, user_id, asset,
                amount_field="purchase_price",
                primary_field="purchase_price_primary",
                rate_field="_no_rate",
                date_field="purchase_date",
            )

    # If units change on a market-priced asset, rewrite today's AssetValue with
    # the new (units × last_price). Without this, the portfolio chart keeps
    # plotting the old position size even though the header and wallet totals
    # (computed live) already reflect the new units — the two disagree until
    # the next scheduled refresh overwrites today's row.
    if (
        "units" in update_data
        and asset.valuation_method == "market_price"
        and asset.last_price is not None
        and asset.units is not None
        and asset.units > 0
    ):
        await _apply_price_to_asset(session, asset, Decimal(str(asset.last_price)))

    await session.commit()
    await session.refresh(asset)
    latest = await _get_latest_value(session, asset.id)
    count = await _get_value_count(session, asset.id)
    return _asset_to_read(asset, latest, count, tx_count)


async def delete_asset(
    session: AsyncSession, asset_id: uuid.UUID, workspace_id: uuid.UUID
) -> bool:
    """Delete an asset (cascades to values)."""
    result = await session.execute(
        select(Asset).where(Asset.id == asset_id, Asset.workspace_id == workspace_id)
    )
    asset = result.scalar_one_or_none()
    if not asset:
        return False
    await session.delete(asset)
    await session.commit()
    return True


async def get_asset_values(
    session: AsyncSession, asset_id: uuid.UUID, workspace_id: uuid.UUID
) -> Optional[list[AssetValueRead]]:
    """Get value history for an asset, most recent first."""
    # Verify ownership
    owner_check = await session.execute(
        select(Asset.id).where(Asset.id == asset_id, Asset.workspace_id == workspace_id)
    )
    if not owner_check.scalar_one_or_none():
        return None

    result = await session.execute(
        select(AssetValue)
        .where(AssetValue.asset_id == asset_id)
        .order_by(desc(AssetValue.date), desc(AssetValue.id))
    )
    values = result.scalars().all()
    return [AssetValueRead.model_validate(v) for v in values]


async def add_asset_value(
    session: AsyncSession, asset_id: uuid.UUID, workspace_id: uuid.UUID, data: AssetValueCreate
) -> Optional[AssetValueRead]:
    """Add a new value entry for an asset."""
    # Verify ownership
    owner_check = await session.execute(
        select(Asset.id).where(Asset.id == asset_id, Asset.workspace_id == workspace_id)
    )
    if not owner_check.scalar_one_or_none():
        return None

    value = AssetValue(
        asset_id=asset_id,
        amount=data.amount,
        date=data.date,
        source="manual",
    )
    session.add(value)
    await session.commit()
    await session.refresh(value)
    return AssetValueRead.model_validate(value)


async def delete_asset_value(
    session: AsyncSession, value_id: uuid.UUID, workspace_id: uuid.UUID
) -> bool:
    """Delete a specific asset value entry."""
    result = await session.execute(
        select(AssetValue)
        .join(Asset, AssetValue.asset_id == Asset.id)
        .where(AssetValue.id == value_id, Asset.workspace_id == workspace_id)
    )
    value = result.scalar_one_or_none()
    if not value:
        return False
    await session.delete(value)
    await session.commit()
    return True


async def get_asset_value_trend(
    session: AsyncSession, asset_id: uuid.UUID, workspace_id: uuid.UUID, months: int = 12
) -> Optional[list[dict]]:
    """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

    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, AssetTransaction.price,
                )
                .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)), Decimal(str(pr)) if pr is not None else None) for d, k, q, pr 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(
    session: AsyncSession,
    workspace_id: uuid.UUID,
    user_id: Optional[uuid.UUID] = None,
) -> dict:
    """Get portfolio trend data for stacked area chart.
    Returns asset metadata + pivoted trend with fill-forward values.
    Sold assets are included so their pre-sell history still contributes
    to the historical total; their contribution drops to 0 the day after
    sell_date.

    `user_id` is only used to resolve the user's primary_currency for the
    chart's converted totals; it falls back to the workspace's default when
    not supplied.
    """
    result = await session.execute(
        select(Asset).where(
            Asset.workspace_id == workspace_id,
            Asset.is_archived == False,
        ).order_by(Asset.position, Asset.name)
    )
    active_assets = list(result.scalars().all())

    if not active_assets:
        return {"assets": [], "trend": [], "total": 0.0}

    # Get user's primary currency for conversion
    user = await session.get(User, user_id) if user_id is not None else None
    primary_currency = user.primary_currency if user else get_settings().default_currency

    # Assets whose currency has no resolvable FX rate cannot be expressed in
    # the primary currency. Excluding them keeps the chart's total honest
    # instead of summing raw foreign amounts at a fake 1:1 rate (issue
    # #574); the holdings table still shows them in their original currency
    # flagged as unconverted.
    # One lookup per distinct currency: a missing rate can trigger a
    # provider sync, which must not repeat for every asset in it.
    convertible_currencies = {primary_currency}
    for currency in {asset.currency for asset in active_assets} - {primary_currency}:
        if await has_rate(session, currency, primary_currency):
            convertible_currencies.add(currency)
    convertible_assets = [
        asset for asset in active_assets if asset.currency in convertible_currencies
    ]
    if not convertible_assets:
        return {"assets": [], "trend": [], "total": 0.0}
    active_assets = convertible_assets

    values_map = await _load_asset_native_values(session, active_assets)

    asset_meta: list[dict[str, Any]] = []
    asset_currency: dict[str, str] = {}
    sell_date_by_aid: dict[str, date] = {}
    all_dates: set[date] = set()

    for asset in active_assets:
        aid = str(asset.id)
        asset_meta.append({
            "id": aid,
            "name": asset.name,
            "type": asset.type,
            "group_id": str(asset.group_id) if asset.group_id else None,
        })
        asset_currency[aid] = asset.currency

        vals = values_map[aid]

        # If the asset was sold and a sell_price is recorded, treat it as the
        # asset's terminal value on sell_date so the chart reflects the
        # realized value before dropping to 0.
        if asset.sell_date is not None:
            sell_date_by_aid[aid] = asset.sell_date
            if asset.sell_price is not None:
                vals = [(d, v) for d, v in vals if d <= asset.sell_date]
                if not vals or vals[-1][0] != asset.sell_date:
                    vals.append((asset.sell_date, float(asset.sell_price)))
                values_map[aid] = vals

        for d, _ in vals:
            all_dates.add(d)

    if not all_dates:
        return {"assets": asset_meta, "trend": [], "total": 0.0}

    sorted_dates = sorted(all_dates)

    # Build lookup: aid -> {date: value}
    value_lookup: dict[str, dict[date, float]] = {}
    first_date: dict[str, date] = {}
    for aid in [a["id"] for a in asset_meta]:
        value_lookup[aid] = dict(values_map[aid])
        if values_map[aid]:
            first_date[aid] = values_map[aid][0][0]

    # Build trend with fill-forward; 0 before first date (for stacking).
    # Each native-currency amount is converted at the display date `d` so that
    # fill-forwarded values reflect current FX rates — consistent with
    # get_asset_values_at(as_of_date=d).
    trend = []
    last_known: dict[str, float] = {}  # native currency amounts
    for aid in [a["id"] for a in asset_meta]:
        last_known[aid] = 0.0

    for d in sorted_dates:
        row: dict[str, object] = {"date": d.isoformat()}
        date_total = Decimal("0")
        for aid in [a["id"] for a in asset_meta]:
            if d in value_lookup[aid]:
                last_known[aid] = value_lookup[aid][d]
            # Use 0 before asset exists (stacking needs numeric values)
            if aid in first_date and d >= first_date[aid]:
                native = last_known[aid]
            else:
                native = 0.0
            # After sell_date, the asset has been liquidated — drop to 0 so
            # it stops contributing to the portfolio total going forward.
            if aid in sell_date_by_aid and d > sell_date_by_aid[aid]:
                native = 0.0
                last_known[aid] = 0.0

            # Convert native amount to primary currency at this display date
            currency = asset_currency[aid]
            if native != 0.0 and currency != primary_currency:
                converted, _ = await convert(
                    session, Decimal(str(native)), currency, primary_currency, d,
                    decimals=ASSET_PRICE_DECIMALS,
                )
                val = converted
            else:
                val = Decimal(str(native))

            # Each series point is shown in monetary decimals, but the total
            # sums the unrounded values so sub-cent holdings still add up.
            row[aid] = round(float(val), 2)
            date_total += val
        row["_total"] = float(date_total.quantize(Decimal("0.01")))
        trend.append(row)

    # The header total matches the last row's _total — both use the same
    # per-display-date conversion so no second conversion is needed.
    total: float = cast(float, trend[-1]["_total"]) if trend else 0.0

    return {"assets": asset_meta, "trend": trend, "total": round(total, 2)}


async def get_asset_values_at(
    session: AsyncSession,
    scope_id: uuid.UUID,
    as_of_date: Optional[date] = None,
    primary_currency: Optional[str] = None,
    *,
    by_workspace: bool = False,
    group_ids: Optional[list[uuid.UUID]] = None,
) -> tuple[dict[str, float], float]:
    """Return (per_currency_totals, primary_total) for all active assets.

    `scope_id` is a workspace_id when `by_workspace=True` (preferred for
    multi-tenant code paths), otherwise treated as a legacy user_id
    filter. Both branches honor the `is_archived=False` + `sell_date is None`
    filters.

    - as_of_date=None: uses live prices (current view).
    - as_of_date set: uses the latest AssetValue on or before that date,
      falling back to purchase_price only if the asset existed by that date.
    - primary_currency=None: primary_total is 0.0.
    """
    scope_filter = (
        Asset.workspace_id == scope_id if by_workspace else Asset.user_id == scope_id
    )
    # `group_ids` restricts to assets in a Collection's wallets (issue #105).
    # An empty list means "no wallets in this collection" → no assets.
    if group_ids is not None and len(group_ids) == 0:
        return {}, 0.0
    stmt = select(Asset).where(
        scope_filter,
        Asset.is_archived == False,
        Asset.sell_date.is_(None),
    )
    if group_ids:
        stmt = stmt.where(Asset.group_id.in_(group_ids))
    result = await session.execute(stmt)
    assets = list(result.scalars().all())

    totals: dict[str, float] = {}
    primary_total = 0.0

    if as_of_date is not None:
        values_map = await _load_asset_native_values(session, assets, up_to_date=as_of_date)

    for asset in assets:
        if as_of_date is not None:
            amount: Optional[float] = _fill_forward_at(asset, values_map[str(asset.id)], as_of_date)
        else:
            latest = await _get_latest_value(session, asset.id)
            amount = _compute_current_value(asset, latest)

        if not amount:
            continue

        totals[asset.currency] = totals.get(asset.currency, 0.0) + amount

        if primary_currency is not None:
            converted, _ = await convert(
                session, Decimal(str(amount)), asset.currency, primary_currency, as_of_date,
                decimals=ASSET_PRICE_DECIMALS,
            )
            primary_total += float(converted)

    return totals, primary_total


# ============================================================================
# Market-price refresh
# ============================================================================


async def _apply_price_to_asset(
    session: AsyncSession, asset: Asset, new_price: Decimal, *, value_date: date | None = None
) -> None:
    """Update the cached price and upsert today's AssetValue.

    Shared by the single-asset and batch refresh paths so both behave
    identically: price + timestamp get stamped; today's value gets
    inserted or overwritten so running the task multiple times per day
    doesn't pile up duplicate rows.
    """
    asset.last_price = new_price
    asset.last_price_at = datetime.now(timezone.utc)

    if not asset.units or asset.units <= 0:
        return

    today = value_date or app_today()
    new_amount = new_price * Decimal(str(asset.units))
    existing = await session.execute(
        select(AssetValue)
        .where(AssetValue.asset_id == asset.id, AssetValue.date == today)
        .order_by(desc(AssetValue.id))
        .limit(1)
    )
    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",
            )
        )


async def refresh_market_price_asset(
    session: AsyncSession,
    asset: Asset,
    *,
    market_provider: Optional[MarketPriceProvider] = None,
) -> bool:
    """Re-quote a single market-priced asset and update its cached price.

    Returns True when a new quote was persisted, False otherwise (no quote
    available, stale price unchanged, or missing fields).
    """
    if asset.valuation_method != "market_price" or not asset.ticker:
        return False

    provider = market_provider or get_market_price_provider()
    try:
        quote = await provider.get_quote(asset.ticker)
    except MarketPriceRateLimitedError:
        # Let the scheduler see this explicitly so it can back off globally.
        raise
    except Exception as e:
        logger.warning("Market price refresh failed for %s: %s", asset.ticker, e)
        return False

    if quote is None or quote.price is None:
        return False

    await _apply_price_to_asset(session, asset, Decimal(str(quote.price)))
    # Opportunistic logo backfill: assets created before Brandfetch was
    # configured have no logo_url. On the next single-asset refresh (which
    # goes through the full get_quote → website lookup), stamp it in.
    # The batch refresh path doesn't have website info so it leaves logos
    # alone; manual refreshes and creates cover the fill-in.
    if not asset.logo_url and quote.logo_url:
        asset.logo_url = quote.logo_url
    await session.flush()
    return True


async def refresh_all_market_prices(
    session: AsyncSession,
    *,
    market_provider: Optional[MarketPriceProvider] = None,
) -> dict[str, int]:
    """Refresh every non-archived market-priced asset in the database.

    Uses the provider's batch ``get_latest_prices`` endpoint when possible —
    one HTTP request covers the whole portfolio via ``yfinance.download``
    instead of one call per asset. Falls back silently to per-asset refresh
    if the batch returns nothing (provider without bulk support, or a hard
    failure on Yahoo's end).

    Returns a summary counting successes, skips, and rate-limit halts —
    surfaced as the Celery task's return payload for observability.
    """
    result = await session.execute(
        select(Asset).where(
            Asset.valuation_method == "market_price",
            Asset.is_archived == False,
            Asset.sell_date.is_(None),
            Asset.ticker.isnot(None),
        )
    )
    assets = list(result.scalars().all())

    if not assets:
        return {"refreshed": 0, "skipped": 0, "rate_limited": 0}

    provider = market_provider or get_market_price_provider()
    tickers = [a.ticker for a in assets if a.ticker]

    # Batch path: one request → dict[SYMBOL, price]. On rate-limit we halt
    # immediately — retrying within the same task would just pile on 429s
    # and risk an IP-level cookie ban.
    try:
        prices = await provider.get_latest_prices(tickers)
    except MarketPriceRateLimitedError:
        logger.warning("Yahoo rate-limited the batch fetch; skipping this cycle")
        return {"refreshed": 0, "skipped": len(assets), "rate_limited": 1}
    except Exception as e:
        logger.warning("Batch price fetch failed, falling back to per-asset: %s", e)
        prices = {}

    refreshed = 0
    skipped = 0

    for asset in assets:
        if not asset.ticker:
            skipped += 1
            continue
        price = prices.get(asset.ticker.upper()) if prices else None
        if price is None:
            # Per-asset fallback: the batch missed this symbol (delisted
            # ticker, one-off provider error, etc.). Try the full quote
            # path which also populates name/currency if needed.
            try:
                ok = await refresh_market_price_asset(
                    session, asset, market_provider=provider
                )
            except MarketPriceRateLimitedError:
                logger.warning(
                    "Yahoo rate-limited mid-refresh after %d assets; halting",
                    refreshed,
                )
                await session.commit()
                return {
                    "refreshed": refreshed,
                    "skipped": skipped + (len(assets) - refreshed - skipped),
                    "rate_limited": 1,
                }
            if ok:
                refreshed += 1
            else:
                skipped += 1
            continue

        await _apply_price_to_asset(session, asset, price)
        refreshed += 1

    await session.commit()
    return {"refreshed": refreshed, "skipped": skipped, "rate_limited": 0}