Output:
Chunk ID: 32752d
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 5596
Output:
from __future__ import annotations

import json
from collections.abc import Mapping
from decimal import Decimal
from sqlite3 import Connection

from fastapi import HTTPException

from jarvis_finance.api.schemas.positions import EquityPortfolioSummary, EquityPosition
from jarvis_finance.dashboard import data as dashboard_data
from jarvis_finance.services.api_helpers import optional_decimal_text

def _asset_class_label(value: object) -> str:
    return "ETF" if str(value or "").lower() == "etf" else "Aktie"

def _account_label(row: dict[str, str]) -> str:
    platform = str(row.get("platform") or "").strip()
    account = str(row.get("account_name") or "").strip()
    if "postfinance" in platform.lower():
        if not account or "manual" in account.lower():
            return "PostFinance E-Trading"
        return account if "postfinance" in account.lower() or "e-trading" in account.lower() else f"PostFinance · {account}"
    return account or platform

def _latest_analysis(conn: Connection) -> tuple[dict[str, object] | None, dict[tuple[str, str], dict[str, object]], dict[str, str]]:
    row = conn.execute(
        """SELECT pas.*,mdr.completed_at,mdr.missing_instruments_json
             FROM portfolio_analysis_snapshots pas
             JOIN market_data_runs mdr ON mdr.run_id=pas.run_id
            ORDER BY pas.as_of DESC,pas.created_at DESC LIMIT 1"""
    ).fetchone()
    if not row:
        return None, {}, {}
    try:
        payload = json.loads(row["summary_json"] or "{}")
    except json.JSONDecodeError:
        payload = {}
    values = {
        (str(item.get("account_id") or ""), str(item.get("instrument_id") or "")): item
        for item in payload.get("positions", [])
        if isinstance(item, dict)
    }
    try:
        missing_rows = json.loads(row["missing_instruments_json"] or "[]")
    except json.JSONDecodeError:
        missing_rows = []
    missing = {
        str(item.get("instrument_id") or ""): str(item.get("reason_code") or "price_missing")
        for item in missing_rows
        if isinstance(item, dict)
    }
    return dict(row), values, missing

def _status_reason(code: str) -> str:
    labels = {
        "fmp_endpoint_restricted": "Der primäre Provider beschränkt diesen historischen Kurs im aktuellen Tarif.",
        "plan_restricted": "Der Provider beschränkt diesen historischen Kurs im aktuellen Tarif.",
        "fmp_rate_limited": "Das Provider-Limit wurde erreicht. Der Lauf kann kontrolliert fortgesetzt werden.",
        "rate_limited": "Das Provider-Limit wurde erreicht. Der Lauf kann kontrolliert fortgesetzt werden.",
        "currency_mismatch": "Die Kurswährung stimmt nicht mit der bestätigten Instrumentwährung überein.",
        "exchange_mismatch": "Der Handelsplatz des Provider-Ergebnisses ist nicht bestätigt.",
        "future_price_rejected": "Der gelieferte Kurs liegt nach dem zulässigen Börsenstichtag.",
        "stale_price": "Der letzte bestätigte Kurs ist für den Börsenstichtag zu alt und wird nicht bewertet.",
        "mapping_required": "Die Provider-Zuordnung ist noch nicht eindeutig bestätigt.",
        "fx_rate_missing": "Für die CHF-Bewertung fehlt ein bestätigter FX-Kurs.",
    }
    return labels.get(code, "Für den Börsenstichtag konnte noch kein bestätigter Kurs geladen werden.")

def _position_status(row: Mapping[str, object]) -> str:
    """Compatibility status when no audited market-analysis snapshot exists yet."""

    if "quantity" in row and Decimal(str(row.get("quantity") or "0")) <= 0:
        return "Einstand unvollständig"
    market_value = row.get("market_value_chf")
    warnings = str(row.get("quality_warnings") or "")
    if market_value not in {None, ""}:
        if "missing_cost_basis" in warnings or "missing_fx" in warnings:
            return "Einstand unvollständig"
        return "Bewertet"
    if str(row.get("price_status") or "") != "ok":
        return "Kurs fehlt"
    if str(row.get("fx_status") or "") == "missing_fx":
        return "FX fehlt für Bewertung"
    return "Bewertung unvollständig"

def _mapping_details(conn: Connection, instrument_id: str) -> dict[str, str | None]:
    row = conn.execute(
        """SELECT provider,provider_symbol,provider_market,upper(COALESCE(trading_currency,currency,'')) currency
             FROM instrument_price_mappings
            WHERE instrument_id=? AND mapping_status='mapped'
            ORDER BY updated_at DESC,mapping_id LIMIT 1""",
        (instrument_id,),
    ).fetchone()
    return dict(row) if row else {"provider": None, "provider_symbol": None, "provider_market": None, "currency": None}

def list_equity_positions(conn: Connection) -> list[EquityPosition]:
    source_rows = [
        row for row in dashboard_data.get_positions(conn)
        if row.get("asset_class", "").lower() in {"stock", "equity", "etf"}
        and row.get("instrument_status", "").lower() != "inactive"
    ]
    analysis, values, missing = _latest_analysis(conn)
    effective_values: dict[tuple[str, str], Decimal | None] = {}
    for row in source_rows:
        key = (str(row.get("account_id") or ""), str(row.get("instrument_id") or ""))
        candidate = values.get(key)
        row_is_audited = row.get("valuation_source") in {
            "postfinance_official_import",
            "audited_market_run",
        }
        candidate_is_newer = bool(
            analysis
            and candidate
            and str(analysis.get("as_of") or "") > str(row.get("valuation_as_of") or row.get("price_date") or "")
            and candidate.get("quality_status") == "fresh"
        )
        raw = (
            candidate.get("value_chf")
            if candidate_is_newer and candidate
            else row.get("market_value_chf") if analysis is None or row_is_audited else None
        )
        effective_values[key] = Decimal(str(raw)) if raw not in {None, ""} else None
    complete = bool(source_rows) and all(value is not None for value in effective_values.values())
    total = sum((value or Decimal("0") for value in effective_values.values()), Decimal("0"))
    positions: list[EquityPosition] = []
    for row in source_rows:
        account_id = str(row.get("account_id") or "")
        instrument_id = str(row.get("instrument_id") or "")
        snapshot_value = values.get((account_id, instrument_id))
        value = (
            snapshot_value
            if analysis
            and snapshot_value
            and snapshot_value.get("quality_status") == "fresh"
            and str(analysis.get("as_of") or "") > str(row.get("valuation_as_of") or row.get("price_date") or "")
            else None
        )
        row_fallback_allowed = analysis is None or row.get("valuation_source") in {
            "postfinance_official_import",
            "audited_market_run",
        }
        mapping = _mapping_details(conn, instrument_id)
        raw_market_value = (
            value.get("value_chf")
            if value
            else row.get("market_value_chf") if row_fallback_allowed else None
        )
        if Decimal(str(row.get("quantity") or "0")) <= 0:
            raw_market_value = None
        market_value = Decimal(str(raw_market_value)) if raw_market_value not in {None, ""} else None
        share = (market_value / total * Decimal("100")) if complete and market_value is not None and total > 0 else None
        code = "valued" if market_value is not None else ("stale_price" if snapshot_value else missing.get(instrument_id, "price_missing"))
        status = "Bewertet" if market_value is not None else ("Kurs veraltet" if snapshot_value else _position_status(row))
        provenance = value.get("price_input_provenance") if value else None
        provenance_provider = provenance.get("provider") if isinstance(provenance, dict) else None
        positions.append(EquityPosition(
            position_id=f"{account_id}:{instrument_id}",
            instrument_id=instrument_id,
            name=str(row.get("name") or ""),
            ticker=str(row.get("ticker") or ""),
            isin=str(row.get("isin") or ""),
            account=_account_label(row),
            asset_class=_asset_class_label(row.get("asset_class")),
            quantity=optional_decimal_text(row.get("quantity")) or "0",
            currency=str(value.get("currency") if value else mapping.get("currency") or row.get("price_currency") or row.get("currency") or ""),
            price=(
                optional_decimal_text(value.get("close"))
                if value
                else optional_decimal_text(row.get("market_price_original") or row.get("price"))
                if row_fallback_allowed
                else None
            ),
            market_value_chf=optional_decimal_text(market_value, 2) if market_value is not None else None,
            portfolio_share_pct=optional_decimal_text(share, 2) if share is not None else None,
            price_date=(
                str(analysis.get("as_of"))
                if value and analysis
                else str(row.get("valuation_as_of") or row.get("price_date") or "") or None
                if row_fallback_allowed
                else str(analysis.get("as_of")) if analysis else None
            ),
            provider=str((value.get("provider") if value else None) or provenance_provider or row.get("price_provider") or mapping.get("provider") or ""),
            provider_symbol=str(mapping.get("provider_symbol") or ""),
            exchange=str(mapping.get("provider_market") or ""),
            price_currency=str(value.get("currency") if value else mapping.get("currency") or row.get("price_currency") or row.get("currency") or ""),
            data_status="fresh" if market_value is not None else "missing",
            status_code=code,
            status_reason=None if market_value is not None else _status_reason(code),
            status=status,
        ))
    return sorted(positions, key=lambda item: Decimal(item.market_value_chf or "-1"), reverse=True)

def get_equity_summary(conn: Connection) -> EquityPortfolioSummary:
    positions = list_equity_positions(conn)
    valued = [item for item in positions if item.market_value_chf is not None]
    partial = sum((Decimal(item.market_value_chf or "0") for item in valued), Decimal("0"))
    complete = bool(positions) and len(valued) == len(positions)
    analysis, _, _ = _latest_analysis(conn)
    status = "complete" if complete else ("partial" if positions else "unavailable")
    effective_as_of = max((item.price_date or "" for item in valued), default="") or None
    analysis_as_of = str(analysis.get("as_of") or "") if analysis else ""
    response_as_of = effective_as_of or analysis_as_of or None
    last_successful = (
        str(analysis.get("completed_at"))
        if analysis and (not effective_as_of or analysis_as_of >= str(effective_as_of)[:10])
        else effective_as_of
    )
    return EquityPortfolioSummary(
        total_positions=len(positions),
        valued_positions=len(valued),
        unvalued_positions=len(positions) - len(valued),
        coverage_complete=complete,
        equity_value_chf=optional_decimal_text(partial, 2) if complete else None,
        valued_partial_chf=optional_decimal_text(partial, 2) or "0.00",
        value_label="Aktien-/ETF-Gesamtwert" if complete else "Bewerteter Teilwert",
        as_of=response_as_of,
        last_successful_run=last_successful,
        status=status,
        status_label=f"{len(valued)}/{len(positions)} bewertet" if positions else "Keine Aktien-/ETF-Positionen",
        unvalued_tickers=[item.ticker for item in positions if item.market_value_chf is None],
    )

def get_equity_position(conn: Connection, position_id: str) -> EquityPosition:
    position = next((p for p in list_equity_positions(conn) if p.position_id == position_id), None)
    if position is None:
        raise HTTPException(status_code=404, detail="Equity position not found")
    return position
            "ticker": row["ticker"] if row else "",
            "isin": row["isin"] if row else "",
            "quantity": dec_text(quantity),
            "cost_basis_chf": dec_text(pos.cost_basis_chf, "0.01"),
            "market_price_original": dec_text(market_price, "0.01") if market_price is not None else "",
            "price_currency": price_currency,
            "price_date": price_date,
            "price_provider": price_provider,
            "market_value_chf": dec_text(market_value_chf, "0.01") if market_value_chf is not None else "",
            "price_status": "ok" if market_price is not None else "missing_market_price",
            "valuation_source": valuation_source,
            "valuation_as_of": price_date,
            "provider_symbol_status": "mapped" if conn.execute("SELECT 1 FROM instrument_price_mappings WHERE instrument_id=? AND mapping_status IN ('mapped','confirmed','user_confirmed') AND provider_symbol IS NOT NULL LIMIT 1", (instrument_id,)).fetchone() else "missing_provider_symbol",
            "hedge_status": row["hedge_status"] if row else pos.hedge_status,
            "instrument_status": row["instrument_status"] if row else pos.instrument_status,
            "valuation_policy": row["valuation_policy"] if row else pos.valuation_policy,
            "fx_status": "ok" if "missing_fx" not in pos.quality_warnings else "missing_fx",
            "market_price_status": "ok" if market_price is not None else "missing_market_price",
            "valuation_timestamp_status": pos.valuation_timestamp_status,
            "corporate_action_status": row["corporate_action_status"] if row else pos.corporate_action_status,
            "valuation_status": pos.valuation_status,
            "total_return_chf": dec_text(pos.total_return_chf, "0.01") if pos.total_return_chf is not None else "",
            "total_return_status": "complete" if pos.total_return_chf is not None else "incomplete",
            "quality_warnings": ",".join(pos.quality_warnings),
            "data_quality_status": pos.data_quality_status,
        })
    return rows

def get_portfolio_positions_user(conn: Connection) -> list[dict[str, str]]:
    rows: list[dict[str, str]] = []
    for row in get_positions(conn):
        if row.get("asset_class", "").lower() not in {"stock", "equity", "etf"}:
            continue
        rows.append({
            "name": row.get("name", ""),
            "ticker": row.get("ticker", ""),
            "isin": row.get("isin", ""),
            "depot": row.get("account_name", ""),
            "assettyp": "ETF" if row.get("asset_class", "").lower() == "etf" else "Aktie",
            "menge": row.get("quantity", ""),
            "kurs": row.get("market_price_original") or "Preis noch nicht verfügbar",
            "kurswaehrung": row.get("price_currency", ""),
            "marktwert_chf": chf_text(row.get("market_value_chf")) if row.get("market_value_chf") else "nicht bewertet",
            "einstand_chf": chf_text(row.get("cost_basis_chf")) if row.get("cost_basis_chf") else "unvollständig",
            "p_l_chf": chf_text(row.get("total_return_chf")) if row.get("total_return_chf") else "nicht berechenbar",
            "status": translate_status(row.get("price_status") or row.get("data_quality_status")),
        })
    return rows

def get_portfolio_asset_class_chart(conn: Connection) -> list[dict[str, str]]:
    summary = get_command_center_summary(conn)
    return [
        {"label": "Crypto", "value_chf": summary["crypto_total_chf"]},
        {"label": "Aktien/ETF", "value_chf": summary["equity_etf_total_chf"]},
        {"label": "Cash", "value_chf": summary["cash_total_chf"]},
    ]

def get_platform_value_chart(conn: Connection) -> list[dict[str, str]]:
    totals: dict[str, Decimal] = {}
    for row in get_cash_overview(conn):
        totals[row["platform"]] = totals.get(row["platform"], Decimal("0")) + d(row.get("amount_chf"))
    for row in get_positions(conn):
        totals[row["platform"]] = totals.get(row["platform"], Decimal("0")) + d(row.get("market_value_chf"))
    crypto_total = d(get_crypto_summary_cards(conn)["total_value_chf"])
    if crypto_total:
        totals["Crypto Wallets"] = totals.get("Crypto Wallets", Decimal("0")) + crypto_total
    return [{"label": k, "value_chf": dec_text(v, "0.01")} for k, v in sorted(totals.items(), key=lambda item: item[1], reverse=True)]

def get_ledger_transactions(conn: Connection, limit: int = 200) -> list[dict[str, str]]:
    return rowdicts(conn.execute(
        """
        SELECT t.trade_date, p.name AS platform, a.account_name, t.transaction_type,
               i.name AS instrument, i.ticker, t.quantity, t.gross_amount_original,
               t.net_amount_original, t.currency_original, t.fx_status, t.quality_status,
               t.source_type, t.source_id
        FROM transactions t
        LEFT JOIN accounts a ON a.account_id=t.account_id
        LEFT JOIN platforms p ON p.platform_id=a.platform_id
        LEFT JOIN instruments i ON i.instrument_id=t.instrument_id
        ORDER BY t.trade_date DESC, t.created_at DESC LIMIT ?
        """, (limit,)
    ).fetchall())

def get_watchlist(conn: Connection) -> list[dict[str, str]]:
    return rowdicts(conn.execute("SELECT name, asset_class, reason, status, target_entry_price, target_entry_currency, investment_case, bear_case, next_review_date FROM watchlist ORDER BY name").fetchall())

def resolve_alert_entity_label(conn: Connection, entity_type: str | None, entity_id: str | None) -> str:
    if not entity_id:
        return entity_type or "Portfolio"
    if entity_type == "instrument" or str(entity_id).startswith("instrument-"):
        row = conn.execute("SELECT name, ticker FROM instruments WHERE instrument_id=?", (entity_id,)).fetchone()
        if row:
            return f"{row['name']} ({row['ticker']})" if row["ticker"] else row["name"]
        return "Unbekanntes Instrument"
    if entity_type == "crypto_asset":
    if entity_type == "crypto_asset":
        row = conn.execute("SELECT coin_name, symbol FROM crypto_assets WHERE asset_id=?", (entity_id,)).fetchone()
        if row:
            return f"{row['coin_name']} ({row['symbol']})"
    if entity_type == "crypto_wallet":
        row = conn.execute("SELECT wallet_name FROM crypto_wallets WHERE wallet_id=?", (entity_id,)).fetchone()
        if row:
            return row["wallet_name"]
    return entity_type or "Portfolio"

def alert_title(rule_id: str, message: str = "", entity: str = "") -> str:
    labels = {
        "missing_fx": "FX-Kurs fehlt",
        "stale_fx": "FX-Kurs veraltet",
        "missing_market_price": "Marktpreis fehlt",
        "stale_market_price": "Marktpreis veraltet",
        "missing_provider_symbol": "Marktdaten-Zuordnung fehlt",
        "manual_fx_override_required": "Manueller FX-Kurs nötig",
        "historical_fx_unavailable": "Historischer FX-Kurs fehlt",
        "candidate_review_required": "Mapping muss geprüft werden",
        "cost_basis_uncertain": "Einstand unvollständig",
        "snapshot_only": "Nur Snapshot-Historie vorhanden",
        "missing_crypto_price": "Crypto-Preis fehlt",
        "crypto_price_missing": "Crypto-Preis fehlt",
    }
    title = labels.get(rule_id, translate_status(rule_id))
    return f"{title} für {entity}" if entity else title

def alert_description(rule_id: str, message: str = "") -> str:
    descriptions = {
        "missing_fx": "Ein historischer FX-Kurs fehlt. CHF-Performance ist daher unvollständig.",
        "stale_fx": "Ein FX-Kurs ist veraltet und sollte aktualisiert werden.",
        "missing_market_price": "Für diese Position fehlt ein lokaler Marktpreis. Bewertung bleibt unvollständig.",
        "stale_market_price": "Der lokale Marktpreis ist veraltet. Bitte Preisupdate ausführen.",
        "missing_provider_symbol": "Für diese Position fehlt oder fehlt noch die bestätigte Marktdaten-Zuordnung.",
        "candidate_review_required": "Es gibt Marktdaten-Kandidaten, die manuell bestätigt werden müssen.",
        "cost_basis_uncertain": "Die Kaufhistorie oder Einstandsdaten sind unvollständig.",
        "snapshot_only": "Diese Position basiert auf einem Snapshot und nicht auf kompletter Historie.",
    }
    return descriptions.get(rule_id, message.replace("_", " ") if message else "Bitte im Review-Bereich prüfen.")

def get_alert_summary_cards(conn: Connection) -> dict[str, str]:
    rows = conn.execute("SELECT priority, COUNT(*) AS c FROM alerts WHERE status='active' GROUP BY priority").fetchall()
    out = {"kritisch": "0", "wichtig": "0", "info": "0"}
    for row in rows:
        key = "kritisch" if row["priority"] == "kritisch" else ("info" if row["priority"] == "info" else "wichtig")
        out[key] = str(int(out[key]) + int(row["c"] or 0))
    return out

def get_alert_cards(conn: Connection, limit: int = 5) -> list[dict[str, str]]:
    rows = conn.execute(
        """
        SELECT alert_id, priority, category, entity_type, entity_id, rule_id, message, occurrence_count, last_seen_at
        FROM alerts WHERE status='active'
        ORDER BY CASE priority WHEN 'kritisch' THEN 0 WHEN 'warnung' THEN 1 ELSE 2 END, last_seen_at DESC, created_at DESC
        LIMIT ?
        """,
        (limit,),
    ).fetchall()
    cards = []
    for row in rows:
        affected = resolve_alert_entity_label(conn, row["entity_type"], row["entity_id"])
        cards.append({
            "_alert_id": row["alert_id"],
            "title": alert_title(row["rule_id"], row["message"], affected),
            "description": alert_description(row["rule_id"], row["message"]),
            "affected": affected,
            "severity": translate_status(row["priority"]),
            "last_seen": date_text(row["last_seen_at"]),
            "actions": "Prüfen · Ignorieren · Details",
        })
    return cards

def get_alerts(conn: Connection) -> list[dict[str, str]]:
    return rowdicts(conn.execute(
        """
        SELECT priority, status, category, entity_type, entity_id, rule_id, message,
               occurrence_count, last_seen_at, resolved_at, muted_until, fingerprint, dedup_key, created_at
        FROM alerts
        ORDER BY CASE priority WHEN 'kritisch' THEN 0 WHEN 'warnung' THEN 1 ELSE 2 END, status, created_at DESC
        """
    ).fetchall())

def get_audit_events(conn: Connection, limit: int = 200) -> list[dict[str, str]]:
    rows = conn.execute(


grep -R "def _money\|def _text" -n src/jarvis_finance/services/postfinance_service.py src/jarvis_finance/imports/postfinance_documents.py && grep -R "get_postfinance_summary" -n src tests


Output:
Chunk ID: 14a393
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 327
Output:
src/jarvis_finance/services/postfinance_service.py:47:def _text(value: Decimal | None) -> str | None:
src/jarvis_finance/services/postfinance_service.py:51:def _money(value: Decimal) -> str:
grep: src/jarvis_finance/api/routers/__pycache__/postfinance.cpython-311.pyc: binary file matches
grep: src/jarvis_finance/services/__pycache__/postfinance_service.cpython-311.pyc: binary file matches
src/jarvis_finance/api/routers/postfinance.py:12:    get_postfinance_summary,
src/jarvis_finance/api/routers/postfinance.py:40:    return _run(get_postfinance_summary, conn)
grep: src/jarvis_finance/services/__pycache__/postfinance_service.cpython-312.pyc: binary file matches
grep: tests/__pycache__/test_postfinance_sprint13.cpython-311-pytest-9.1.1.pyc: binary file matches
src/jarvis_finance/services/postfinance_service.py:869:def get_postfinance_summary(conn: Connection) -> dict[str, Any]:
grep: tests/__pycache__/test_postfinance_sprint13.cpython-311.pyc: binary file matches
grep: tests/__pycache__/test_postfinance_sprint13.cpython-311-pytest-9.0.2.pyc: binary file matches
tests/test_postfinance_sprint13.py:269:    safe_summary = service.get_postfinance_summary(conn)
tests/test_postfinance_sprint13.py:603:    assert service.get_postfinance_summary(conn)["latest_snapshot"]["total_chf"] == "321149.23"


sed -n '35,60p' src/jarvis_finance/services/postfinance_service.py && sed -n '850,940p' src/jarvis_finance/services/postfinance_service.py


Output:
Chunk ID: 6d1c6b
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 1198
Output:

def _id(prefix: str) -> str:
    return f"{prefix}_{uuid4().hex[:20]}"

def _hash(*values: object) -> str:
    return sha256(
        json.dumps(values, sort_keys=True, separators=(",", ":"), default=str).encode()
    ).hexdigest()

def _text(value: Decimal | None) -> str | None:
    return format(value, "f") if value is not None else None

def _money(value: Decimal) -> str:
    return format(value.quantize(Decimal("0.01")), "f")

def _decode(value: str, label: str) -> bytes:
    try:
        return base64.b64decode(value, validate=True)
    except (binascii.Error, ValueError) as exc:
        raise ValueError(f"PostFinance {label} is not valid base64") from exc

        for ref, created in archive_refs:
            if created:
                _remove_archive(ref)
        raise ValueError("PostFinance import conflicted with immutable data") from exc
    except Exception:
        conn.rollback()
        for ref, created in archive_refs:
            if created:
                _remove_archive(ref)
        raise
    return {
        "status": "confirmed",
        "batch_id": batch_id,
        "snapshot_id": snapshot_id,
        "audit_id": audit_id,
        "idempotent": False,
    }

def get_postfinance_summary(conn: Connection) -> dict[str, Any]:
    latest = conn.execute(
        """SELECT snapshot_id,snapshot_at,total_chf,securities_chf,cash_chf,stocks_chf,etfs_chf,
                  position_count,cash_count,open_orders,difference_chf,reconciliation_status,created_at
           FROM postfinance_snapshots ORDER BY snapshot_at DESC,created_at DESC LIMIT 1"""
    ).fetchone()
    if not latest:
        return {
            "latest_snapshot": None,
            "positions": [],
            "cash": [],
            "event_counts": {},
            "imports": [],
        }
    official_position_values = {
        override.instrument_id: override.market_value_chf
        for override in latest_official_postfinance_positions(conn).values()
    }
    positions = [
        {
            "row_key": _hash("position", row["instrument_name"], row["quantity"])[:16],
            "instrument_name": row["instrument_name"],
            "ticker": row["ticker"],
            "asset_class": row["asset_class"],
            "quantity": row["quantity"],
            "provider_average_cost_original": row["provider_average_cost_original"],
            "provider_cost_total_original": row["provider_cost_total_original"],
            "price_original": row["price_original"],
            "price_currency": row["price_currency"],
            "value_chf": _money(official_position_values.get(row["instrument_id"], Decimal(str(row["value_chf"])))),
            "weight_pct": row["weight_pct"],
            "computed_cost_basis_original": row["computed_cost_basis_original"],
            "computed_cost_basis_status": row["computed_cost_basis_status"],
        }
        for row in conn.execute(
            """SELECT p.instrument_id,p.asset_class,p.quantity,p.provider_average_cost_original,
                      p.provider_cost_total_original,p.price_original,p.price_currency,p.value_chf,
                      p.weight_pct,p.computed_cost_basis_original,p.computed_cost_basis_status,
                      i.name AS instrument_name,i.ticker
               FROM postfinance_snapshot_positions p
               JOIN instruments i ON i.instrument_id=p.instrument_id
               WHERE p.snapshot_id=? ORDER BY CAST(p.value_chf AS REAL) DESC""",
            (latest["snapshot_id"],),
        ).fetchall()
    ]
    cash = [
        {
            "row_key": _hash("cash", component.currency)[:16],
            "currency": component.currency,
            "amount_original": _text(component.amount_original),
            "fx_rate_to_chf": _text(component.source_fx_rate_to_chf),
            "value_chf": _money(component.amount_chf),
        }
        for component in latest_official_postfinance_cash(conn)
    ]
    events = {
        str(row["event_type"]): int(row["c"])
        for row in conn.execute(
            "SELECT event_type,COUNT(*) c FROM postfinance_ledger_events GROUP BY event_type ORDER BY event_type"
        ).fetchall()
    }
    imports = [
        dict(row)
        for row in conn.execute(
            """SELECT b.snapshot_at,b.parser_id,b.parser_version,b.confirmed_at,b.status,
                      s.total_chf,s.securities_chf,s.cash_chf,s.position_count,s.cash_count,
                      s.difference_chf,s.reconciliation_status,
                      (SELECT COUNT(*) FROM postfinance_batch_documents d WHERE d.batch_id=b.batch_id) AS document_count
               FROM postfinance_import_batches b JOIN postfinance_snapshots s ON s.batch_id=b.batch_id
               ORDER BY b.snapshot_at DESC,b.confirmed_at DESC"""
        ).fetchall()
    ]


git diff -- tests/test_postfinance_sprint13.py | sed -n '1,260p'


Output:
Chunk ID: 0ea9b7
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 3190
Output:
diff --git a/tests/test_postfinance_sprint13.py b/tests/test_postfinance_sprint13.py
index ecf37e7..5ea2c5f 100644
--- a/tests/test_postfinance_sprint13.py
+++ b/tests/test_postfinance_sprint13.py
@@ -1,12 +1,14 @@
 from __future__ import annotations

 import base64
+import json
 from dataclasses import replace
 from decimal import Decimal
 from hashlib import sha256

 import pytest

+from jarvis_finance.dashboard.data import get_command_center_summary, get_positions
 from jarvis_finance.imports.postfinance_documents import (
     PFBundle,
     PFDocument,
@@ -16,6 +18,14 @@ from jarvis_finance.imports.postfinance_documents import (
     PFSnapshotPosition,
 )
 from jarvis_finance.services import postfinance_service as service
+from jarvis_finance.services.cash_service import get_cash_position_detail, get_cash_summary
+from jarvis_finance.services.equity_service import get_equity_summary
+from jarvis_finance.services.portfolio_aggregation import (
+    latest_official_postfinance_cash,
+    latest_official_postfinance_positions,
+)
+from jarvis_finance.services.portfolio_data import build_portfolio_reconciliation
+from jarvis_finance.services.portfolio_service import get_overview
 from jarvis_finance.storage.database import connect_memory
 from jarvis_finance.storage.migrations import apply_migrations

@@ -461,3 +471,246 @@ def test_immutable_postfinance_source_and_snapshot_rows(monkeypatch, tmp_path):
             conn.execute(f"UPDATE {table} SET created_at=created_at WHERE {predicate}")
         with pytest.raises(Exception, match="cannot be deleted"):
             conn.execute(f"DELETE FROM {table} WHERE {predicate}")
+
+
+def test_global_read_model_counts_official_postfinance_components_once(monkeypatch, tmp_path):
+    """Reproduce the production placeholder/exposure/settlement-position collision."""
+    conn = make_conn()
+    monkeypatch.setenv("JARVIS_FINANCE_RUNTIME_DIR", str(tmp_path))
+    original = bundle()
+    stock_total = Decimal("255791.97")
+    etf_total = Decimal("37673.19")
+
+    def split_total(total: Decimal) -> list[Decimal]:
+        values = [(total / Decimal("11")).quantize(Decimal("0.01")) for _ in range(11)]
+        values[-1] += total - sum(values, Decimal("0"))
+        return values
+
+    source_values = split_total(stock_total) + split_total(etf_total)
+    positions = tuple(
+        replace(item, quantity=Decimal("1"), market_price_original=value, market_value_chf=value)
+        for item, value in zip(original.snapshot.positions, source_values, strict=True)
+    )
+    realistic = replace(
+        original,
+        snapshot=replace(
+            original.snapshot,
+            positions=positions,
+            cash=(
+                PFSnapshotCash("EUR", Decimal("21693.27"), Decimal("0.9293"), Decimal("71623.09")),
+                PFSnapshotCash("USD", Decimal("9235.55"), Decimal("0.8146"), Decimal("249526.14")),
+            ),
+            securities_total_chf=Decimal("293465.16"),
+            cash_total_chf=Decimal("27684.07"),
+            total_value_chf=Decimal("321149.23"),
+            stock_total_chf=stock_total,
+            etf_total_chf=etf_total,
+        ),
+    )
+    monkeypatch.setattr(service, "parse_postfinance_bundle", lambda _zip, _overview: realistic)
+    conn.execute(
+        """INSERT INTO cash_account_snapshots(snapshot_id,account_id,snapshot_type,balance_date,
+               amount_original,currency,amount_chf,source,note,created_at,created_by)
+           VALUES('legacy-total',?,'manual_balance','2026-07-26','321149.23','CHF',
+                  '321149.23','manual','historical depot total placeholder',
+                  '2026-07-26T00:00:00Z','synthetic')""",
+        (CASH,),
+    )
+    conn.execute(
+        "INSERT INTO platforms(platform_id,name,platform_type,country,default_currency,is_active,created_at) VALUES('tw','True Wealth','wealth','CH','CHF',1,'2026-01-01')"
+    )
+    conn.execute(
+        """INSERT INTO accounts(account_id,platform_id,account_name,account_type,currency,
+               performance_included,is_active,created_at,portfolio_bucket)
+           VALUES('account_tw','tw','True Wealth','brokerage','CHF',1,1,'2026-01-01','truewealth')"""
+    )
+    conn.execute(
+        """INSERT INTO account_value_snapshots(snapshot_id,account_id,valuation_date,
+               total_value_chf,currency,source_type,quality_status,created_at,is_active)
+           VALUES('tw-value','account_tw','2026-07-27','152845.00','CHF',
+                  'synthetic_truewealth','complete','2026-07-27T00:00:00Z',1)"""
+    )
+    conn.commit()
+
+    payload = request()
+    preview = service.preview_postfinance_import(conn, payload)
+    service.confirm_postfinance_import(
+        conn,
+        {**payload, "preview_id": preview["preview_id"],
+         "confirmation_id": preview["confirmation_id"], "confirm": True},
+    )
+    before_gets = conn.total_changes
+    cash = get_cash_summary(conn)
+    equity = get_equity_summary(conn)
+    overview = get_overview(conn)
+    command = get_command_center_summary(conn)
+    reconciliation = build_portfolio_reconciliation(conn, as_of="2026-07-27")
+    rows = get_positions(conn)
+
+    assert conn.total_changes == before_gets
+    assert cash.cash_chf == "27684.07"
+    assert sum(Decimal(item.used_value_chf) for item in cash.positions if item.account_id == CASH) == Decimal("27684.07")
+    usd_position = next(item for item in cash.positions if item.account_id == CASH and item.currency == "USD")
+    assert get_cash_position_detail(conn, usd_position.id).currency == "USD"
+    assert equity.equity_value_chf == "293465.16"
+    assert equity.as_of == "2026-07-27T09:14:30+02:00"
+    assert sum(Decimal(row["market_value_chf"]) for row in rows if row["account_id"] == DEPOT) == Decimal("293465.16")
+    assert not [row for row in rows if row["account_id"] == CASH and row["asset_class"] in {"stock", "equity", "etf"}]
+    assert Decimal(cash.cash_chf) + Decimal(equity.equity_value_chf) == Decimal("321149.23")
+    assert overview.truewealth_value_chf == "152845.00"
+    assert command["cash_total_chf"] == "27684.07"
+    pf_reconciliation = next(
+        item for item in reconciliation["account_totals"]
+        if item["reported_total"] == "321149.23"
+    )
+    assert pf_reconciliation["derived_total"] == "321149.23"
+    assert pf_reconciliation["status"] == "matched"
+    assert conn.execute("SELECT amount_chf FROM cash_account_snapshots WHERE snapshot_id='legacy-total'").fetchone()[0] == "321149.23"
+    assert conn.execute("SELECT COUNT(*) FROM transactions WHERE internal_transfer_group_id IS NOT NULL").fetchone()[0] == 2
+
+    market_positions = []
+    for row, value in zip(
+        [row for row in rows if row["account_id"] == DEPOT],
+        split_total(Decimal("160000")) + split_total(Decimal("140000")),
+        strict=True,
+    ):
+        market_positions.append({
+            "account_id": DEPOT, "instrument_id": row["instrument_id"],
+            "quality_status": "fresh", "value_chf": str(value), "close": str(value),
+            "currency": "CHF", "provider": "synthetic-market",
+        })
+    conn.execute(
+        """INSERT INTO market_data_runs(run_id,source_key,as_of,input_fingerprint,status,
+               started_at,completed_at,price_total,price_stored,fx_total,fx_stored,
+               benchmark_total,benchmark_stored,valuation_stored,missing_instruments_json,
+               reason_codes_json)
+           VALUES('newer-run','synthetic','2026-07-28','fp','complete','2026-07-28T00:00:00Z',
+                  '2026-07-28T00:01:00Z',22,22,0,0,0,0,22,'[]','[]')"""
+    )
+    conn.execute(
+        """INSERT INTO portfolio_analysis_snapshots(analysis_snapshot_id,run_id,as_of,
+               base_currency,total_value_chf,price_coverage_pct,fx_coverage_pct,
+               benchmark_coverage_pct,quality_status,reason_codes_json,summary_json,created_at)
+           VALUES('newer-analysis','newer-run','2026-07-28','CHF','300000','100','100','0',
+                  'complete','[]',?,'2026-07-28T00:01:00Z')""",
+        (json.dumps({"positions": market_positions}),),
+    )
+    conn.commit()
+    newer = get_equity_summary(conn)
+    assert newer.equity_value_chf == "300000.00"
+    assert newer.as_of == "2026-07-28"
+    assert get_cash_summary(conn).cash_chf == "27684.07"
+    assert service.get_postfinance_summary(conn)["latest_snapshot"]["total_chf"] == "321149.23"
+
+    duplicate = service.preview_postfinance_import(conn, payload)
+    second = service.confirm_postfinance_import(
+        conn,
+        {**payload, "preview_id": duplicate["preview_id"],
+         "confirmation_id": duplicate["confirmation_id"], "confirm": True},
+    )
+    assert duplicate["duplicate"] is True and duplicate["conflict"] is False
+    assert second["idempotent"] is True
+    assert conn.execute("SELECT COUNT(*) FROM postfinance_import_batches").fetchone()[0] == 1
+
+
+def test_official_snapshot_resolvers_honor_historical_as_of_and_cutoff(monkeypatch, tmp_path):
+    conn = make_conn()
+    monkeypatch.setenv("JARVIS_FINANCE_RUNTIME_DIR", str(tmp_path))
+    monkeypatch.setattr(service, "parse_postfinance_bundle", lambda _zip, _overview: bundle())
+    payload = request()
+    preview = service.preview_postfinance_import(conn, payload)
+    service.confirm_postfinance_import(
+        conn,
+        {**payload, "preview_id": preview["preview_id"],
+         "confirmation_id": preview["confirmation_id"], "confirm": True},
+    )
+    original_cash_total = sum(
+        (item.amount_chf for item in latest_official_postfinance_cash(conn)), Decimal("0")
+    )
+    original_position_total = sum(
+        (
+            item.market_value_chf
+            for item in latest_official_postfinance_positions(conn).values()
+        ),
+        Decimal("0"),
+    )
+    conn.execute("UPDATE accounts SET account_type='checking' WHERE account_id=?", (CASH,))
+    assert sum(
+        (
+            Decimal(item.used_value_chf)
+            for item in get_cash_summary(conn).positions
+            if item.account_id == CASH
+        ),
+        Decimal("0"),
+    ) == original_cash_total
+
+    batch = dict(conn.execute("SELECT * FROM postfinance_import_batches LIMIT 1").fetchone())
+    batch.update(
+        batch_id="future-batch",
+        bundle_sha256=sha256(b"future-bundle").hexdigest(),
+        snapshot_at="2026-08-01T09:14:30+02:00",
+        confirmed_at="2026-08-01T10:00:00Z",
+    )
+    columns = list(batch)
+    conn.execute(
+        f"INSERT INTO postfinance_import_batches({','.join(columns)}) VALUES({','.join('?' for _ in columns)})",
+        [batch[column] for column in columns],
+    )
+    source_snapshot = dict(conn.execute("SELECT * FROM postfinance_snapshots LIMIT 1").fetchone())
+    source_snapshot.update(
+        snapshot_id="future-snapshot",
+        batch_id="future-batch",
+        snapshot_at="2026-08-01T09:14:30+02:00",
+        total_chf="1299.00",
+        securities_chf="300.00",
+        cash_chf="999.00",
+        stocks_chf="100.00",
+        etfs_chf="200.00",
+        component_total_chf="1299.00",
+        difference_chf="0.00",
+        created_at="2026-08-01T10:00:00Z",
+    )
+    columns = list(source_snapshot)
+    conn.execute(
+        f"INSERT INTO postfinance_snapshots({','.join(columns)}) VALUES({','.join('?' for _ in columns)})",
+        [source_snapshot[column] for column in columns],
+    )
+    conn.execute(
+        """INSERT INTO postfinance_snapshot_positions(
+               snapshot_position_id,snapshot_id,source_row_reference,instrument_id,asset_class,
+               quantity,provider_average_cost_original,provider_cost_total_original,
+               price_original,price_currency,value_chf,weight_pct,computed_cost_basis_original,
+               computed_cost_basis_status,provenance_json,created_at)
+           SELECT 'future-'||snapshot_position_id,'future-snapshot',source_row_reference,
+                  instrument_id,asset_class,quantity,provider_average_cost_original,
+                  provider_cost_total_original,price_original,price_currency,value_chf,weight_pct,
+                  computed_cost_basis_original,computed_cost_basis_status,provenance_json,
+                  '2026-08-01T10:00:00Z'
+           FROM postfinance_snapshot_positions WHERE snapshot_id<> 'future-snapshot'"""
+    )
+    conn.execute(
+        """INSERT INTO postfinance_snapshot_cash(
+               snapshot_cash_id,snapshot_id,currency,amount_original,fx_rate_to_chf,value_chf,created_at)
+           SELECT 'future-'||snapshot_cash_id,'future-snapshot',currency,amount_original,
+                  fx_rate_to_chf,value_chf,'2026-08-01T10:00:00Z'


git diff -- tests/test_postfinance_sprint13.py | sed -n '260,520p'


Output:
Chunk ID: dc040c
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 339
Output:
+                  fx_rate_to_chf,value_chf,'2026-08-01T10:00:00Z'
+           FROM postfinance_snapshot_cash WHERE snapshot_id<> 'future-snapshot'"""
+    )
+    conn.commit()
+
+    assert sum((item.amount_chf for item in latest_official_postfinance_cash(conn)), Decimal("0")) == Decimal("999.00")
+    historical_cash = latest_official_postfinance_cash(conn, as_of="2026-07-27")
+    assert sum((item.amount_chf for item in historical_cash), Decimal("0")) == original_cash_total
+    cutoff_cash = latest_official_postfinance_cash(
+        conn,
+        as_of="2026-08-01",
+        data_cutoff="2026-07-31T23:59:59Z",
+    )
+    assert sum((item.amount_chf for item in cutoff_cash), Decimal("0")) == original_cash_total
+    historical_positions = latest_official_postfinance_positions(conn, as_of="2026-07-27")
+    assert sum(
+        (item.market_value_chf for item in historical_positions.values()), Decimal("0")
+    ) == original_position_total
+    assert {item.valuation_at for item in historical_positions.values()} == {"2026-07-27T09:14:30+02:00"}
+    current_positions = latest_official_postfinance_positions(conn)
+    assert sum((item.market_value_chf for item in current_positions.values()), Decimal("0")) == Decimal("300.00")
+    assert {item.valuation_at for item in current_positions.values()} == {"2026-08-01T09:14:30+02:00"}


grep -R "postfinance_account_roles\|postfinance_snapshots\|postfinance_snapshot_cash" -n src/jarvis_finance/storage tests/test_postfinance_sprint13.py | head -80


Output:
Chunk ID: 12461f
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 654
Output:
grep: src/jarvis_finance/storage/__pycache__/postfinance_schema.cpython-311.pyc: binary file matches
src/jarvis_finance/storage/postfinance_schema.py:15:        CREATE TABLE IF NOT EXISTS postfinance_account_roles (
src/jarvis_finance/storage/postfinance_schema.py:56:        CREATE TABLE IF NOT EXISTS postfinance_snapshots (
src/jarvis_finance/storage/postfinance_schema.py:77:            snapshot_id TEXT NOT NULL REFERENCES postfinance_snapshots(snapshot_id),
src/jarvis_finance/storage/postfinance_schema.py:95:        CREATE TABLE IF NOT EXISTS postfinance_snapshot_cash (
src/jarvis_finance/storage/postfinance_schema.py:97:            snapshot_id TEXT NOT NULL REFERENCES postfinance_snapshots(snapshot_id),
src/jarvis_finance/storage/postfinance_schema.py:172:        CREATE TRIGGER IF NOT EXISTS postfinance_snapshots_immutable BEFORE UPDATE ON postfinance_snapshots
src/jarvis_finance/storage/postfinance_schema.py:174:        CREATE TRIGGER IF NOT EXISTS postfinance_snapshots_no_delete BEFORE DELETE ON postfinance_snapshots
src/jarvis_finance/storage/postfinance_schema.py:180:        CREATE TRIGGER IF NOT EXISTS postfinance_snapshot_cash_immutable BEFORE UPDATE ON postfinance_snapshot_cash
src/jarvis_finance/storage/postfinance_schema.py:182:        CREATE TRIGGER IF NOT EXISTS postfinance_snapshot_cash_no_delete BEFORE DELETE ON postfinance_snapshot_cash
tests/test_postfinance_sprint13.py:276:    assert conn.execute("SELECT COUNT(*) FROM postfinance_snapshots").fetchone()[0] == 1
tests/test_postfinance_sprint13.py:278:    assert conn.execute("SELECT COUNT(*) FROM postfinance_account_roles").fetchone()[0] == 3
tests/test_postfinance_sprint13.py:279:    roles = dict(conn.execute("SELECT role,account_id FROM postfinance_account_roles"))
tests/test_postfinance_sprint13.py:446:            "UPDATE postfinance_snapshots SET total_chf='0' WHERE snapshot_id=?",
tests/test_postfinance_sprint13.py:451:            "DELETE FROM postfinance_snapshots WHERE snapshot_id=?", (result["snapshot_id"],)
tests/test_postfinance_sprint13.py:456:        "postfinance_snapshot_cash": "created_at=created_at",
tests/test_postfinance_sprint13.py:659:    source_snapshot = dict(conn.execute("SELECT * FROM postfinance_snapshots LIMIT 1").fetchone())
tests/test_postfinance_sprint13.py:675:        f"INSERT INTO postfinance_snapshots({','.join(columns)}) VALUES({','.join('?' for _ in columns)})",
tests/test_postfinance_sprint13.py:692:        """INSERT INTO postfinance_snapshot_cash(
tests/test_postfinance_sprint13.py:696:           FROM postfinance_snapshot_cash WHERE snapshot_id<> 'future-snapshot'"""


sed -n '1,120p' src/jarvis_finance/storage/postfinance_schema.py && sed -n '700,820p' src/jarvis_finance/services/postfinance_service.py


Output:
Chunk ID: f7a052
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 3150
Output:
from __future__ import annotations

from sqlite3 import Connection

def create_postfinance_ledger_import_v1(conn: Connection) -> None:
    """Create immutable PostFinance source, ledger, snapshot and cost-basis tables."""
    position_columns = {row[1] for row in conn.execute("PRAGMA table_info(positions_snapshot)")}
    if "source_type" not in position_columns:
        conn.execute("ALTER TABLE positions_snapshot ADD COLUMN source_type TEXT")
    if "source_reference" not in position_columns:
        conn.execute("ALTER TABLE positions_snapshot ADD COLUMN source_reference TEXT")
    conn.executescript(
        """
        CREATE TABLE IF NOT EXISTS postfinance_account_roles (
            role TEXT PRIMARY KEY CHECK(role IN ('efinance','etrading_depot','etrading_cash')),
            account_id TEXT NOT NULL REFERENCES accounts(account_id),
            source_reference_hash TEXT,
            created_at TEXT NOT NULL,
            UNIQUE(account_id, role)
        );
        CREATE TABLE IF NOT EXISTS postfinance_import_batches (
            batch_id TEXT PRIMARY KEY,
            bundle_sha256 TEXT NOT NULL UNIQUE CHECK(length(bundle_sha256)=64),
            zip_sha256 TEXT NOT NULL CHECK(length(zip_sha256)=64),
            overview_sha256 TEXT NOT NULL CHECK(length(overview_sha256)=64),
            parser_id TEXT NOT NULL,
            parser_version TEXT NOT NULL,
            db_revision TEXT NOT NULL,
            archive_reference TEXT NOT NULL,
            snapshot_at TEXT NOT NULL,
            status TEXT NOT NULL CHECK(status='confirmed'),
            audit_id TEXT NOT NULL,
            confirmed_at TEXT NOT NULL,
            confirmed_by TEXT NOT NULL DEFAULT 'user'
        );
        CREATE TABLE IF NOT EXISTS postfinance_documents (
            document_hash TEXT PRIMARY KEY CHECK(length(document_hash)=64),
            filename_hash TEXT NOT NULL CHECK(length(filename_hash)=64),
            semantic_identity TEXT NOT NULL UNIQUE CHECK(length(semantic_identity)=64),
            semantic_reference_hash TEXT NOT NULL CHECK(length(semantic_reference_hash)=64),
            document_type TEXT NOT NULL,
            document_date TEXT,
            account_reference_hash TEXT,
            account_role TEXT NOT NULL CHECK(account_role IN ('efinance','etrading_depot','etrading_cash')),
            page_count INTEGER NOT NULL CHECK(page_count > 0),
            archive_reference TEXT NOT NULL,
            parser_version TEXT NOT NULL,
            created_at TEXT NOT NULL
        );
        CREATE TABLE IF NOT EXISTS postfinance_batch_documents (
            batch_id TEXT NOT NULL REFERENCES postfinance_import_batches(batch_id),
            document_hash TEXT NOT NULL REFERENCES postfinance_documents(document_hash),
            PRIMARY KEY(batch_id, document_hash)
        );
        CREATE TABLE IF NOT EXISTS postfinance_snapshots (
            snapshot_id TEXT PRIMARY KEY,
            batch_id TEXT NOT NULL UNIQUE REFERENCES postfinance_import_batches(batch_id),
            account_id TEXT NOT NULL REFERENCES accounts(account_id),
            snapshot_at TEXT NOT NULL,
            total_chf TEXT NOT NULL,
            securities_chf TEXT NOT NULL,
            cash_chf TEXT NOT NULL,
            stocks_chf TEXT NOT NULL,
            etfs_chf TEXT NOT NULL,
            component_total_chf TEXT NOT NULL,
            difference_chf TEXT NOT NULL,
            tolerance_chf TEXT NOT NULL,
            position_count INTEGER NOT NULL,
            cash_count INTEGER NOT NULL,
            open_orders INTEGER NOT NULL,
            reconciliation_status TEXT NOT NULL CHECK(reconciliation_status IN ('matched','within_tolerance')),
            created_at TEXT NOT NULL
        );
        CREATE TABLE IF NOT EXISTS postfinance_snapshot_positions (
            snapshot_position_id TEXT PRIMARY KEY,
            snapshot_id TEXT NOT NULL REFERENCES postfinance_snapshots(snapshot_id),
            source_row_reference TEXT NOT NULL,
            instrument_id TEXT NOT NULL REFERENCES instruments(instrument_id),
            asset_class TEXT NOT NULL CHECK(asset_class IN ('stock','etf')),
            quantity TEXT NOT NULL,
            provider_average_cost_original TEXT,
            provider_cost_total_original TEXT,
            price_original TEXT NOT NULL,
            price_currency TEXT NOT NULL,
            value_chf TEXT NOT NULL,
            weight_pct TEXT NOT NULL,
            computed_cost_basis_original TEXT,
            computed_cost_basis_status TEXT NOT NULL CHECK(computed_cost_basis_status IN ('complete','partial','unavailable')),
            provenance_json TEXT NOT NULL CHECK(json_valid(provenance_json)),
            created_at TEXT NOT NULL,
            UNIQUE(snapshot_id, source_row_reference),
            UNIQUE(snapshot_id, instrument_id)
        );
        CREATE TABLE IF NOT EXISTS postfinance_snapshot_cash (
            snapshot_cash_id TEXT PRIMARY KEY,
            snapshot_id TEXT NOT NULL REFERENCES postfinance_snapshots(snapshot_id),
            currency TEXT NOT NULL,
            amount_original TEXT NOT NULL,
            fx_rate_to_chf TEXT NOT NULL,
            value_chf TEXT NOT NULL,
            created_at TEXT NOT NULL,
            UNIQUE(snapshot_id, currency)
        );
        CREATE TABLE IF NOT EXISTS postfinance_ledger_events (
            event_id TEXT PRIMARY KEY,
            event_fingerprint TEXT NOT NULL UNIQUE CHECK(length(event_fingerprint)=64),
            document_hash TEXT NOT NULL REFERENCES postfinance_documents(document_hash),
            semantic_reference_hash TEXT NOT NULL CHECK(length(semantic_reference_hash)=64),
            event_type TEXT NOT NULL CHECK(event_type IN ('buy','sell','dividend','interest','fee','internal_transfer','fx','split','corporate_action')),
            account_role TEXT NOT NULL CHECK(account_role IN ('efinance','etrading_depot','etrading_cash')),
            account_id TEXT NOT NULL REFERENCES accounts(account_id),
            occurred_on TEXT NOT NULL,
            settlement_on TEXT,
            direction TEXT NOT NULL CHECK(direction IN ('in','out','neutral')),
            instrument_id TEXT REFERENCES instruments(instrument_id),
            quantity TEXT,
            price_original TEXT,
            gross_original TEXT,
            fee_original TEXT NOT NULL DEFAULT '0',
                    to_consume -= consumed
        for instrument_id, instrument_lots in lots.items():
            for lot in instrument_lots:
                event = lot["event"]
                conn.execute(
                    """INSERT INTO postfinance_cost_basis_lots(lot_id,event_id,instrument_id,acquired_on,quantity_acquired,quantity_remaining,unit_cost_original,fees_original,currency,method,provenance_document_hash,created_at) VALUES(?,?,?,?,?,?,?,?,?,'documented_trade_fifo',?,?)""",
                    (
                        _id("pflot"),
                        f"pfevent_{event.event_fingerprint[:24]}",
                        instrument_id,
                        event.occurred_on,
                        _text(event.quantity),
                        _text(lot["remaining"]),
                        _text(event.price_original),
                        _text(event.fee_original) or "0",
                        event.currency,
                        event.document_hash,
                        now,
                    ),
                )
        for position in snapshot.positions:
            instrument_id = position_map[position.row_reference]
            matched_lots = lots.get(instrument_id, [])
            quantity = sum((lot["remaining"] for lot in matched_lots), Decimal("0"))
            complete = (
                bool(matched_lots)
                and quantity == position.quantity
                and len({lot["event"].currency for lot in matched_lots}) == 1
            )
            calculated = (
                sum(
                    (
                        lot["remaining"] * (lot["event"].price_original or 0)
                        + (lot["event"].fee_original + lot["event"].tax_original)
                        * (lot["remaining"] / lot["event"].quantity)
                        for lot in matched_lots
                        if lot["event"].quantity
                    ),
                    Decimal("0"),
                )
                if complete
                else None
            )
            status = "complete" if complete else "partial" if matched_lots else "unavailable"
            conn.execute(
                """INSERT INTO postfinance_snapshot_positions(snapshot_position_id,snapshot_id,source_row_reference,instrument_id,asset_class,quantity,provider_average_cost_original,provider_cost_total_original,price_original,price_currency,value_chf,weight_pct,computed_cost_basis_original,computed_cost_basis_status,provenance_json,created_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
                (
                    _id("pfposition"),
                    snapshot_id,
                    position.row_reference,
                    instrument_id,
                    position.asset_class,
                    _text(position.quantity),
                    _text(position.provider_average_cost_original),
                    _text(position.provider_cost_total_original),
                    _text(position.market_price_original),
                    position.price_currency,
                    _money(position.market_value_chf),
                    _text(position.weight_pct),
                    _text(calculated),
                    status,
                    json.dumps(
                        {
                            "provider": "official_account_overview",
                            "calculated": "documented_trade_fifo",
                            "estimated": False,
                        },
                        sort_keys=True,
                    ),
                    now,
                ),
            )
            conn.execute(
                """INSERT INTO positions_snapshot(position_snapshot_id,snapshot_date,account_id,platform_id,instrument_id,quantity,average_cost_original,cost_basis_original,market_price_original,market_value_original,market_fx_rate_to_chf,market_value_chf,portfolio_weight_pct,category,data_quality_status,source_type,source_reference,created_at) SELECT ?,?,?,a.platform_id,?,?,?,?,?,?,?,?,?,?,?,?,?,? FROM accounts a WHERE a.account_id=?""",
                (
                    _id("position"),
                    snapshot.valuation_at[:10],
                    accounts["etrading_depot"],
                    instrument_id,
                    _text(position.quantity),
                    _text(position.provider_average_cost_original),
                    _text(position.provider_cost_total_original),
                    _text(position.market_price_original),
                    _text(position.quantity * position.market_price_original),
                    None,
                    _money(position.market_value_chf),
                    _text(position.weight_pct),
                    position.asset_class,
                    "verified",
                    "postfinance_official_import",
                    snapshot_id,
                    now,
                    accounts["etrading_depot"],
                ),
            )
        for cash in snapshot.cash:
            conn.execute(
                "INSERT INTO postfinance_snapshot_cash(snapshot_cash_id,snapshot_id,currency,amount_original,fx_rate_to_chf,value_chf,created_at) VALUES(?,?,?,?,?,?,?)",
                (
                    _id("pfcash"),
                    snapshot_id,
                    cash.currency,
                    _text(cash.amount_original),
                    _text(cash.fx_rate_to_chf),
                    _money(cash.source_value_chf),
                    now,
                ),
            )
            conn.execute(
                "INSERT INTO cash_balances(cash_balance_id,account_id,balance_date,currency,amount_original,fx_rate_to_chf,amount_chf,source_type,quality_status,notes,created_at) VALUES(?,?,?,?,?,?,?,?,?,?,?)",
                (
                    _id("cash"),
                    accounts["etrading_cash"],
                    snapshot.valuation_at[:10],
                    cash.currency,
                    _text(cash.amount_original),
                    _text(cash.fx_rate_to_chf),
                    _money(cash.source_value_chf),
                    "postfinance_official_import",
                    "verified",
                    "Official PostFinance account overview",


sed -n '820,900p' src/jarvis_finance/services/postfinance_service.py


Output:
Chunk ID: e6b9d6
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 838
Output:
                    "Official PostFinance account overview",
                    now,
                ),
            )
        conn.execute(
            "INSERT INTO account_value_snapshots(snapshot_id,account_id,valuation_date,total_value_chf,currency,source_type,quality_status,notes,created_at,valuation_at,source_reference,is_active) VALUES(?,?,?,?,'CHF','postfinance_official_import','ok','Official PostFinance account overview',?,?,?,1)",
            (
                _id("acctval"),
                accounts["etrading_depot"],
                snapshot.valuation_at[:10],
                _money(snapshot.total_value_chf),
                now,
                snapshot.valuation_at,
                snapshot_id,
            ),
        )
        conn.commit()
    except IntegrityError as exc:
        conn.rollback()
        duplicate = conn.execute(
            "SELECT batch_id,audit_id FROM postfinance_import_batches WHERE bundle_sha256=?",
            (bundle.bundle_hash,),
        ).fetchone()
        if duplicate:
            return {
                "status": "confirmed",
                "batch_id": duplicate["batch_id"],
                "audit_id": duplicate["audit_id"],
                "idempotent": True,
            }
        for ref, created in archive_refs:
            if created:
                _remove_archive(ref)
        raise ValueError("PostFinance import conflicted with immutable data") from exc
    except Exception:
        conn.rollback()
        for ref, created in archive_refs:
            if created:
                _remove_archive(ref)
        raise
    return {
        "status": "confirmed",
        "batch_id": batch_id,
        "snapshot_id": snapshot_id,
        "audit_id": audit_id,
        "idempotent": False,
    }

def get_postfinance_summary(conn: Connection) -> dict[str, Any]:
    latest = conn.execute(
        """SELECT snapshot_id,snapshot_at,total_chf,securities_chf,cash_chf,stocks_chf,etfs_chf,
                  position_count,cash_count,open_orders,difference_chf,reconciliation_status,created_at
           FROM postfinance_snapshots ORDER BY snapshot_at DESC,created_at DESC LIMIT 1"""
    ).fetchone()
    if not latest:
        return {
            "latest_snapshot": None,
            "positions": [],
            "cash": [],
            "event_counts": {},
            "imports": [],
        }
    official_position_values = {
        override.instrument_id: override.market_value_chf
        for override in latest_official_postfinance_positions(conn).values()
    }
    positions = [
        {
            "row_key": _hash("position", row["instrument_name"], row["quantity"])[:16],
            "instrument_name": row["instrument_name"],
            "ticker": row["ticker"],
            "asset_class": row["asset_class"],
            "quantity": row["quantity"],
            "provider_average_cost_original": row["provider_average_cost_original"],
            "provider_cost_total_original": row["provider_cost_total_original"],
            "price_original": row["price_original"],
            "price_currency": row["price_currency"],
            "value_chf": _money(official_position_values.get(row["instrument_id"], Decimal(str(row["value_chf"])))),
            "weight_pct": row["weight_pct"],
            "computed_cost_basis_original": row["computed_cost_basis_original"],


Output:
Chunk ID: 4a496d
Wall time: 30.0011 seconds
Process running with session ID 51776
Original token count: 7
Output:
...........................


Output:
Chunk ID: f3b41a
Wall time: 30.0004 seconds
Process running with session ID 51776
Original token count: 0
Output:


Output:
Chunk ID: 179526
Wall time: 30.0011 seconds
Process running with session ID 51776
Original token count: 0
Output:


sed -n '1,220p' src/jarvis_finance/services/portfolio_service.py && grep -R "get_cash_summary\|cash_chf" -n src/jarvis_finance/services src/jarvis_finance/dashboard | head -80


Output:
Chunk ID: 58c531
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 1849
Output:
from __future__ import annotations

from decimal import Decimal
from sqlite3 import Connection

from jarvis_finance.api.schemas.overview import PortfolioSummary
from jarvis_finance.dashboard import data as dashboard_data
from jarvis_finance.services.api_helpers import decimal_text, user_quality_status
from jarvis_finance.services.cash_service import get_cash_summary
from jarvis_finance.services.equity_service import get_equity_summary

def _latest_truewealth_value(conn: Connection) -> Decimal:
    row = conn.execute(
        """
        SELECT avs.total_value_chf
        FROM account_value_snapshots avs
        JOIN accounts a ON a.account_id = avs.account_id
        JOIN platforms p ON p.platform_id = a.platform_id
        WHERE a.is_active = 1
          AND COALESCE(avs.is_active,1) = 1
          AND (lower(p.name || ' ' || a.account_name) LIKE '%true%wealth%' OR lower(a.account_type) IN ('managed_portfolio','robo_portfolio'))
        ORDER BY avs.valuation_date DESC,
                 CASE avs.source_type WHEN 'truewealth_official_import' THEN 3 WHEN 'truewealth_manual_provisional' THEN 2 ELSE 1 END DESC,
                 COALESCE(avs.valuation_at,avs.created_at) DESC, avs.created_at DESC
        LIMIT 1
        """
    ).fetchone()
    return dashboard_data.d(row["total_value_chf"]) if row else Decimal("0")

def _postfinance_equity_value(conn: Connection) -> Decimal:
    row = conn.execute(
        """
        SELECT COALESCE(SUM(CAST(t.gross_amount_chf AS REAL)), 0) AS value_chf
        FROM transactions t
        JOIN accounts a ON a.account_id = t.account_id
        JOIN platforms p ON p.platform_id = a.platform_id
        JOIN instruments i ON i.instrument_id = t.instrument_id
        WHERE COALESCE(t.is_voided,0)=0
          AND COALESCE(a.is_active,1)=1
          AND lower(i.asset_class) IN ('stock','etf')
          AND lower(p.name || ' ' || a.account_name) NOT LIKE '%true%wealth%'
          AND lower(a.account_type) NOT IN ('managed_portfolio','robo_portfolio')
        """
    ).fetchone()
    return dashboard_data.d(row["value_chf"]) if row else Decimal("0")

def get_overview(conn: Connection) -> PortfolioSummary:
    summary = dashboard_data.get_command_center_summary(conn)
    truewealth = _latest_truewealth_value(conn)
    equity_summary = get_equity_summary(conn)
    if equity_summary.as_of is None:
        # Legacy/read-model compatibility before the first audited market run.
        equity = _postfinance_equity_value(conn)
        equity_partial = equity
        equity_complete = True
    else:
        equity_partial = dashboard_data.d(equity_summary.valued_partial_chf)
        equity = dashboard_data.d(equity_summary.equity_value_chf) if equity_summary.coverage_complete else None
        equity_complete = equity_summary.coverage_complete
    crypto = dashboard_data.d(summary.get("crypto_total_chf"))
    cash = dashboard_data.d(get_cash_summary(conn).cash_chf)
    partial_total = cash + crypto + equity_partial + truewealth
    total = partial_total if equity is not None else None
    return PortfolioSummary(
        total_value_chf=decimal_text(total, 2) if total is not None else None,
        crypto_value_chf=decimal_text(crypto, 2),
        equity_value_chf=decimal_text(equity, 2) if equity is not None else None,
        postfinance_equity_value_chf=decimal_text(equity, 2) if equity is not None else None,
        truewealth_value_chf=decimal_text(truewealth, 2),
        cash_value_chf=decimal_text(cash, 2),
        unpriced_positions_count=equity_summary.unvalued_positions,
        critical_alerts_count=int(summary.get("critical_alert_count") or 0),
        last_price_update=equity_summary.last_successful_run or summary.get("last_price_update_at") or None,
        data_quality_status="ok" if equity_complete else user_quality_status("partial"),
    )
grep: src/jarvis_finance/services/__pycache__/postfinance_service.cpython-311.pyc: binary file matches
grep: src/jarvis_finance/services/__pycache__/portfolio_service.cpython-312.pyc: binary file matches
grep: src/jarvis_finance/services/__pycache__/portfolio_service.cpython-311.pyc: binary file matches
grep: src/jarvis_finance/services/__pycache__/portfolio_data.cpython-311.pyc: binary file matches
grep: src/jarvis_finance/services/__pycache__/finance_command_center.cpython-311.pyc: binary file matches
grep: src/jarvis_finance/services/__pycache__/cash_service.cpython-311.pyc: binary file matches
grep: src/jarvis_finance/services/__pycache__/portfolio_aggregation.cpython-311.pyc: binary file matches
grep: src/jarvis_finance/services/__pycache__/manual_entry_service.cpython-311.pyc: binary file matches
grep: src/jarvis_finance/services/__pycache__/reports_v1.cpython-311.pyc: binary file matches
grep: src/jarvis_finance/services/__pycache__/portfolio_aggregation.cpython-312.pyc: binary file matches
grep: src/jarvis_finance/services/__pycache__/postfinance_service.cpython-312.pyc: binary file matches
grep: src/jarvis_finance/services/__pycache__/cash_service.cpython-312.pyc: binary file matches
src/jarvis_finance/services/manual_entry_service.py:54:from jarvis_finance.services.cash_service import get_cash_summary
src/jarvis_finance/services/manual_entry_service.py:572:    position = next((p for p in get_cash_summary(conn).positions if p.id == position_id), None)
src/jarvis_finance/services/portfolio_aggregation.py:113:        f"""SELECT snapshot_id,snapshot_at,cash_chf
src/jarvis_finance/services/portfolio_aggregation.py:129:    target = _money(_decimal(snapshot["cash_chf"]))
src/jarvis_finance/services/finance_command_center.py:15:from jarvis_finance.services.cash_service import get_cash_summary
src/jarvis_finance/services/finance_command_center.py:187:        cash_summary = get_cash_summary(conn)
src/jarvis_finance/services/portfolio_data.py:1043:                "reported_cash_chf": postfinance_decimal_text(postfinance_document.reported_cash_value_chf),
src/jarvis_finance/services/reports_v1.py:164:            "cash_chf": str(overview.get("cash_value_chf") or "0.00"),
src/jarvis_finance/services/portfolio_service.py:9:from jarvis_finance.services.cash_service import get_cash_summary
src/jarvis_finance/services/portfolio_service.py:64:    cash = dashboard_data.d(get_cash_summary(conn).cash_chf)
src/jarvis_finance/services/postfinance_service.py:295:        "cash_chf": _money(snapshot.cash_total_chf),
src/jarvis_finance/services/postfinance_service.py:602:            """INSERT INTO postfinance_snapshots(snapshot_id,batch_id,account_id,snapshot_at,total_chf,securities_chf,cash_chf,stocks_chf,etfs_chf,component_total_chf,difference_chf,tolerance_chf,position_count,cash_count,open_orders,reconciliation_status,created_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,? ,?,?,?,?,?)""",
src/jarvis_finance/services/postfinance_service.py:871:        """SELECT snapshot_id,snapshot_at,total_chf,securities_chf,cash_chf,stocks_chf,etfs_chf,
src/jarvis_finance/services/postfinance_service.py:934:                      s.total_chf,s.securities_chf,s.cash_chf,s.position_count,s.cash_count,
src/jarvis_finance/services/cash_service.py:258:def get_cash_summary(conn: Connection) -> CashSummary:
src/jarvis_finance/services/cash_service.py:265:        cash_chf=decimal_text(total, 2),
src/jarvis_finance/services/cash_service.py:305:    position = next((p for p in get_cash_summary(conn).positions if p.id == position_id), None)


sed -n '240,280p' src/jarvis_finance/services/cash_service.py && sed -n '120,230p' src/jarvis_finance/services/cash_service.py


Output:
Chunk ID: 76059c
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 1830
Output:
                account_type=row["account_type"],
                currency=row["currency"],
                balance_mode=mode,
                amount=decimal_text(used, 2),
                amount_chf=decimal_text(used, 2),
                calculated_balance_chf=decimal_text(calculated, 2),
                manual_balance_chf=decimal_text(manual_amount, 2) if manual_amount is not None else None,
                csv_anchor_balance_chf=decimal_text(anchor["amount_chf"], 2) if anchor else None,
                used_value_chf=decimal_text(used, 2),
                difference_chf=decimal_text(difference, 2),
                last_manual_reconciliation=manual["balance_date"] if manual else None,
                last_imported_booking=_last_imported_booking(conn, account_id),
                status=status,
            )
        )
    return positions

def get_cash_summary(conn: Connection) -> CashSummary:
    # Read paths must never seed or refresh accounts; setup is an explicit Confirm action.
    positions = list_cash_positions(conn)
    total = sum(Decimal(p.used_value_chf) for p in positions)
    last_dates = [p.last_manual_reconciliation for p in positions if p.last_manual_reconciliation]
    return CashSummary(
        base_currency="CHF",
        cash_chf=decimal_text(total, 2),
        manual_accounts_count=sum(1 for p in positions if p.balance_mode == "manual"),
        csv_calculated_accounts_count=sum(1 for p in positions if p.balance_mode == "csv_calculated"),
        open_reconciliation_count=sum(1 for p in positions if p.status == "Abgleich offen"),
        last_reconciliation_at=max(last_dates) if last_dates else None,
        positions=positions,
    )

def preview_cash_snapshot(conn: Connection, request: CashSnapshotPreviewRequest) -> PreviewResponse:
    row = conn.execute("SELECT account_id, account_type FROM accounts WHERE account_id=?", (request.account_id,)).fetchone()
    if not row or row["account_type"] != "cash":
        raise HTTPException(status_code=404, detail="Cash account not found")
    if request.snapshot_type not in {"manual_balance", "csv_anchor_balance", "calculated_balance", "reconciliation"}:
        raise HTTPException(status_code=422, detail="Invalid snapshot_type")
    amount = _decimal(request.amount_chf, "amount_chf")
def _latest_snapshot(conn: Connection, account_id: str, snapshot_type: str):
    return conn.execute(
        """
        SELECT * FROM cash_account_snapshots
        WHERE account_id=? AND snapshot_type=?
        ORDER BY balance_date DESC, created_at DESC
        LIMIT 1
        """,
        (account_id, snapshot_type),
    ).fetchone()

def _cash_movements_after_anchor(conn: Connection, account_id: str, anchor_date: str | None) -> Decimal:
    if not anchor_date:
        return Decimal("0")
    row = conn.execute(
        """
        SELECT COALESCE(SUM(CAST(net_amount_chf AS TEXT)), '0') AS movement
        FROM transactions
        WHERE account_id=? AND COALESCE(is_voided,0)=0 AND COALESCE(is_confirmed,1)=1
          AND source_type LIKE '%csv%'
          AND trade_date > ?
        """,
        (account_id, anchor_date),
    ).fetchone()
    return Decimal(str(row["movement"] or "0"))

def _calculated_balance(conn: Connection, account_id: str) -> Decimal:
    anchor = _latest_snapshot(conn, account_id, "csv_anchor_balance")
    if anchor:
        return Decimal(str(anchor["amount_chf"])) + _cash_movements_after_anchor(conn, account_id, anchor["balance_date"])
    rows = conn.execute(
        "SELECT amount_chf FROM cash_balances WHERE account_id=?",
        (account_id,),
    ).fetchall()
    if rows:
        return sum((Decimal(str(row["amount_chf"])) for row in rows), Decimal("0"))
    # Legacy/demo datasets can have a transaction ledger without materialized
    # cash_balances. Keep the shared read model compatible without overriding an
    # explicit snapshot projection.
    ledger = calculate_cash_balances(conn, persist_alerts=False)
    return sum(
        (
            balance.amount_chf
            for (ledger_account_id, _currency), balance in ledger.balances.items()
            if ledger_account_id == account_id and balance.amount_chf is not None
        ),
        Decimal("0"),
    )

def _last_imported_booking(conn: Connection, account_id: str) -> str | None:
    row = conn.execute("SELECT MAX(trade_date) AS last_date FROM transactions WHERE account_id=? AND source_type LIKE '%csv%'", (account_id,)).fetchone()
    return row["last_date"] if row else None

def list_cash_positions(conn: Connection) -> list[CashPosition]:
    rows = conn.execute(
        """
        SELECT a.account_id, a.account_name, a.account_type, a.currency, COALESCE(a.balance_mode,'manual') AS balance_mode, p.name AS platform
        FROM accounts a JOIN platforms p ON p.platform_id=a.platform_id
        WHERE a.is_active=1
          AND (
              a.account_type='cash'
              OR a.account_id IN (
                  SELECT account_id FROM postfinance_account_roles
                  WHERE role='etrading_cash'
              )
          )
        ORDER BY p.name, a.account_name
        """
    ).fetchall()
    positions: list[CashPosition] = []
    official_components = latest_official_postfinance_cash(conn)
    official_by_account: dict[str, list] = {}
    for component in official_components:
        official_by_account.setdefault(component.account_id, []).append(component)
    for row in rows:
        account_id = row["account_id"]
        if account_id in official_by_account:
            for component in official_by_account[account_id]:
                positions.append(
                    CashPosition(
                        id=f"{account_id}:{component.currency}",
                        account_id=account_id,
                        platform=row["platform"],
                        account_label=row["account_name"],
                        account_type=row["account_type"],
                        currency=component.currency,
                        balance_mode="official_components",
                        amount=decimal_text(component.amount_original, 2),
                        amount_chf=decimal_text(component.amount_chf, 2),
                        calculated_balance_chf=decimal_text(component.amount_chf, 2),
                        manual_balance_chf=None,
                        csv_anchor_balance_chf=None,
                        used_value_chf=decimal_text(component.amount_chf, 2),
                        difference_chf="0.00",
                        last_manual_reconciliation=component.snapshot_date,
                        last_imported_booking=_last_imported_booking(conn, account_id),
                        status="Offiziell abgeglichen",
                    )
                )
            continue
        manual = _latest_snapshot(conn, account_id, "manual_balance")
        anchor = _latest_snapshot(conn, account_id, "csv_anchor_balance")
        calculated = _calculated_balance(conn, account_id)
        manual_amount = Decimal(str(manual["amount_chf"])) if manual else None
        mode = row["balance_mode"] or "manual"
        used = manual_amount if mode == "manual" and manual_amount is not None else calculated
        difference = (manual_amount - calculated) if manual_amount is not None else Decimal("0")


grep -R "confirmed_canonical_positions" -n src tests && sed -n '180,260p' src/jarvis_finance/services/portfolio_analytics.py && sed -n '260,360p' src/jarvis_finance/services/portfolio_analytics.py


Output:
Chunk ID: d0304a
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 2544
Output:
grep: src/jarvis_finance/services/__pycache__/portfolio_analytics.cpython-312.pyc: binary file matches
grep: src/jarvis_finance/services/__pycache__/portfolio_analytics.cpython-311.pyc: binary file matches
grep: tests/unit/__pycache__/test_portfolio_market_analytics_v1.cpython-311.pyc: binary file matches
src/jarvis_finance/services/portfolio_analytics.py:201:def confirmed_canonical_positions(conn: Connection, *, as_of: str | None = None) -> list[ConfirmedPosition]:
src/jarvis_finance/services/portfolio_analytics.py:396:        positions = confirmed_canonical_positions(conn, as_of=effective.isoformat())
grep: tests/unit/__pycache__/test_portfolio_market_analytics_v1.cpython-311-pytest-9.0.2.pyc: binary file matches
grep: tests/unit/__pycache__/test_sprint11_portfolio_completeness.cpython-311-pytest-9.0.2.pyc: binary file matches
grep: tests/unit/__pycache__/test_portfolio_market_analytics_v1.cpython-311-pytest-9.1.1.pyc: binary file matches
grep: tests/unit/__pycache__/test_sprint11_portfolio_completeness.cpython-311.pyc: binary file matches
grep: tests/unit/__pycache__/test_sprint11_portfolio_completeness.cpython-311-pytest-9.1.1.pyc: binary file matches
tests/unit/test_sprint11_portfolio_completeness.py:17:from jarvis_finance.services.portfolio_analytics import confirmed_canonical_positions, run_daily_market_valuation
tests/unit/test_sprint11_portfolio_completeness.py:133:    assert batch.total == 0 and confirmed_canonical_positions(conn, as_of=TARGET.isoformat()) == []
tests/unit/test_portfolio_market_analytics_v1.py:19:    confirmed_canonical_positions,
tests/unit/test_portfolio_market_analytics_v1.py:183:    assert {item.instrument_id for item in confirmed_canonical_positions(conn)} == {"chf", "eur", "usd"}
        close=close,
        adjusted_close=_decimal(row["adjusted_close"]) if row["adjusted_close"] not in {None, ""} else None,
        provider=str(row["provider"]),
        provider_market=row["provider_market"],
        price_timestamp=row["price_timestamp"] or actual_price_date.isoformat(),
        quality_status=str(row["quality_status"]),
        error_message=row["error_message"],
    )
    provenance = {
        "market_price_id": str(row["market_price_id"]),
        "provider": str(row["provider"]),
        "provider_symbol": str(row["provider_symbol"]),
        "provider_market": str(row["provider_market"] or ""),
        "price_date": actual_price_date.isoformat(),
        "original_run_id": str(row["run_id"]) if row["run_id"] else None,
        "fetched_at": str(row["fetched_at"]) if row["fetched_at"] else None,
        "created_at": str(row["created_at"]) if row["created_at"] else None,
    }
    return quote, provenance

def confirmed_canonical_positions(conn: Connection, *, as_of: str | None = None) -> list[ConfirmedPosition]:
    """Return only active, confirmed ledger positions. Preview and ingestion staging tables are never read."""

    rows = conn.execute(
        """
        SELECT t.account_id, t.instrument_id, i.isin, i.name, lower(i.asset_class) AS asset_class,
               upper(COALESCE(i.trading_currency, i.currency, '')) AS instrument_currency,
               t.transaction_type, t.quantity
        FROM transactions t
        JOIN instruments i ON i.instrument_id=t.instrument_id
        JOIN accounts a ON a.account_id=t.account_id
        WHERE t.instrument_id IS NOT NULL
          AND COALESCE(t.is_confirmed, 0)=1
          AND COALESCE(t.is_voided, 0)=0
          AND i.is_active=1 AND a.is_active=1
          AND COALESCE(i.instrument_status,'active') NOT IN ('inactive','delisted','suspended','merged')
          AND COALESCE(i.valuation_policy,'')!='exclude_from_auto_price_update'
          AND lower(i.asset_class) IN ('stock','equity','etf')
          AND lower(t.transaction_type) IN ('initial_position_snapshot','buy','sell','partial_sell','full_sell')
          AND t.trade_date<=?
        ORDER BY t.account_id, t.instrument_id, t.trade_date, t.created_at
        """,
        (as_of or datetime.now(timezone.utc).date().isoformat(),),
    ).fetchall()
    grouped: dict[tuple[str, str], dict[str, Any]] = {}
    for row in rows:
        key = (str(row["account_id"]), str(row["instrument_id"]))
        item = grouped.setdefault(key, dict(row) | {"quantity_total": ZERO})
        quantity = _decimal(row["quantity"])
        item["quantity_total"] += -abs(quantity) if str(row["transaction_type"]).lower() in SELL_TYPES else quantity
    official = latest_official_postfinance_positions(conn, as_of=as_of)
    trading_cash_id = postfinance_account_roles(conn).get("etrading_cash")
    official_instruments = {key[1] for key in official}
    for key in list(grouped):
        if key[0] == trading_cash_id and key[1] in official_instruments:
            grouped.pop(key)
    for key, override in official.items():
        item = grouped.get(key)
        if item is None:
            instrument = conn.execute(
                """SELECT isin,name,lower(asset_class) asset_class,
                          upper(COALESCE(trading_currency,currency,'')) instrument_currency
                   FROM instruments WHERE instrument_id=? AND is_active=1""",
                (override.instrument_id,),
            ).fetchone()
            if not instrument:
                continue
            item = {
                "account_id": override.account_id,
                "instrument_id": override.instrument_id,
                "isin": instrument["isin"],
                "name": instrument["name"],
                "asset_class": instrument["asset_class"],
                "instrument_currency": instrument["instrument_currency"],
            }
            grouped[key] = item
        # The latest official snapshot is the authoritative holding quantity. Historical
        # buys already represented by the old baseline snapshot must not be added twice.
        item["quantity_total"] = override.quantity
    return [
    return [
        ConfirmedPosition(
            account_id=item["account_id"],
            instrument_id=item["instrument_id"],
            isin=item["isin"],
            name=item["name"],
            asset_class=item["asset_class"],
            instrument_currency=item["instrument_currency"],
            quantity=item["quantity_total"],
        )
        for item in grouped.values()
        if item["quantity_total"] > ZERO
    ]

def _mapping(conn: Connection, position: ConfirmedPosition) -> tuple[dict[str, str] | None, str | None]:
    if not position.isin:
        return None, "mapping_required"
    rows = conn.execute(
        """
        SELECT provider, provider_symbol, provider_market,
               upper(COALESCE(trading_currency, currency, '')) AS mapping_currency
        FROM instrument_price_mappings
        WHERE instrument_id=? AND mapping_status='mapped'
          AND provider_symbol IS NOT NULL AND trim(provider_symbol)!=''
        ORDER BY updated_at DESC, mapping_id
        """,
        (position.instrument_id,),
    ).fetchall()
    if len(rows) != 1:
        return None, "mapping_required"
    row = dict(rows[0])
    if row["mapping_currency"] and position.instrument_currency and row["mapping_currency"] != position.instrument_currency:
        return None, "currency_mismatch"
    return {key: str(value or "") for key, value in row.items()}, None

def _active_policy(conn: Connection) -> dict[str, Any] | None:
    row = conn.execute("SELECT * FROM portfolio_policies WHERE is_active=1 ORDER BY version DESC LIMIT 1").fetchone()
    if not row:
        return None
    result = dict(row)
    try:
        result["benchmarks"] = json.loads(result.get("benchmarks_json") or "[]")
    except json.JSONDecodeError:
        result["benchmarks"] = []
    try:
        result["restrictions"] = json.loads(result.get("restrictions_json") or "[]")
    except json.JSONDecodeError:
        result["restrictions"] = []
    return result

def _benchmark_mapping(conn: Connection, policy: dict[str, Any] | None) -> tuple[dict[str, Any] | None, str | None]:
    if not policy or not policy.get("benchmarks"):
        return None, "benchmark_not_configured"
    benchmarks = policy["benchmarks"]
    if len(benchmarks) != 1 or not isinstance(benchmarks[0], dict):
        return None, "benchmark_mapping_required"
    reference = str(benchmarks[0].get("reference") or "").strip()
    if not reference:
        return None, "benchmark_mapping_required"
    rows = conn.execute(
        """
        SELECT i.instrument_id, i.isin, lower(i.asset_class) AS asset_class,
               m.provider, m.provider_symbol, m.provider_market,
               upper(COALESCE(m.trading_currency, m.currency, i.trading_currency, i.currency, '')) AS currency
        FROM instruments i JOIN instrument_price_mappings m ON m.instrument_id=i.instrument_id
        WHERE i.is_active=1 AND m.mapping_status='mapped'
          AND COALESCE(i.instrument_status,'active') NOT IN ('inactive','delisted','suspended','merged')
          AND COALESCE(i.valuation_policy,'')!='exclude_from_auto_price_update'
          AND (i.isin=? OR i.instrument_id=? OR lower(i.name)=lower(?))
          AND m.provider_symbol IS NOT NULL AND trim(m.provider_symbol)!=''
        ORDER BY m.updated_at DESC, m.mapping_id
        """,
        (reference, reference, reference),
    ).fetchall()
    if len(rows) != 1:
        return None, "benchmark_mapping_required"
    result = dict(rows[0])
    result["reference"] = reference
    return result, None

def _fingerprint(positions: list[ConfirmedPosition], policy: dict[str, Any] | None) -> str:
    payload = {
        "positions": [
            {"account_id": p.account_id, "instrument_id": p.instrument_id, "isin": p.isin, "quantity": _fmt(p.quantity)}
            for p in positions
        ],
        "policy_id": policy.get("policy_id") if policy else None,
        "benchmarks": policy.get("benchmarks") if policy else [],
    }
    return hashlib.sha256(json.dumps(payload, sort_keys=True, separators=(",", ":")).encode()).hexdigest()

@contextmanager
def _exclusive_lock(lock_path: Path):
    lock_path.parent.mkdir(parents=True, exist_ok=True)
    with lock_path.open("a+") as handle:
        try:


nl -ba src/jarvis_finance/services/portfolio_analytics.py | sed -n '235,255p'


Output:
Chunk ID: 14231f
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 279
Output:
   235	        if key[0] == trading_cash_id and key[1] in official_instruments:
   236	            grouped.pop(key)
   237	    for key, override in official.items():
   238	        item = grouped.get(key)
   239	        if item is None:
   240	            instrument = conn.execute(
   241	                """SELECT isin,name,lower(asset_class) asset_class,
   242	                          upper(COALESCE(trading_currency,currency,'')) instrument_currency
   243	                   FROM instruments WHERE instrument_id=? AND is_active=1""",
   244	                (override.instrument_id,),
   245	            ).fetchone()
   246	            if not instrument:
   247	                continue
   248	            item = {
   249	                "account_id": override.account_id,
   250	                "instrument_id": override.instrument_id,
   251	                "isin": instrument["isin"],
   252	                "name": instrument["name"],
   253	                "asset_class": instrument["asset_class"],
   254	                "instrument_currency": instrument["instrument_currency"],
   255	            }


nl -ba src/jarvis_finance/services/portfolio_analytics.py | sed -n '255,275p'


Output:
Chunk ID: a85f86
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 242
Output:
   255	            }
   256	            grouped[key] = item
   257	        # The latest official snapshot is the authoritative holding quantity. Historical
   258	        # buys already represented by the old baseline snapshot must not be added twice.
   259	        item["quantity_total"] = override.quantity
   260	    return [
   261	        ConfirmedPosition(
   262	            account_id=item["account_id"],
   263	            instrument_id=item["instrument_id"],
   264	            isin=item["isin"],
   265	            name=item["name"],
   266	            asset_class=item["asset_class"],
   267	            instrument_currency=item["instrument_currency"],
   268	            quantity=item["quantity_total"],
   269	        )
   270	        for item in grouped.values()
   271	        if item["quantity_total"] > ZERO
   272	    ]
   273
   274
   275	def _mapping(conn: Connection, position: ConfirmedPosition) -> tuple[dict[str, str] | None, str | None]:


sed -n '1400,1510p' src/jarvis_finance/services/portfolio_data.py && sed -n '1510,1665p' src/jarvis_finance/services/portfolio_data.py