read.markets/app/routers/pages.py
Giorgio Gilestro 8a155ef157 phase B (2/2): CSV upload endpoint + drag-drop UI
Completes Phase B. The full alternative-onboarding flow is now end-to-end:
drop a T212 pie CSV → parser → InstrumentMap resolver → PortfolioSnapshot
+ Position rows, all without ever asking the user for broker credentials.

- persist_pie() in app/services/csv_import.py: takes a ParsedPie, resolves
  each Slice via InstrumentMap, writes Portfolio + Snapshot + Position
  rows. Unmapped slices are still persisted using their CSV values and
  surfaced in the response for the UI to warn about.
- POST /api/portfolios/upload: multipart endpoint accepting CSV file +
  optional portfolio_name + currency. 2 MiB cap. Returns import summary.
- /upload page with drag-drop dropzone, file input fallback, and inline
  result panel showing invested/value/result + unmapped-slice warnings.
- New "Import" link in the header nav.

Verified end-to-end against the real T212 export: all 13 positions land
with correct T212 tickers (incl. FPp_EQ for the Paris TotalEnergies
listing the heuristic resolver picks), zero unmapped slices, totals
reconcile to the penny.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 11:00:42 +01:00

86 lines
2.8 KiB
Python

"""HTML page routes — server-rendered Jinja2 with HTMX-driven partial refresh."""
from __future__ import annotations
from datetime import date, datetime, timezone
from fastapi import APIRouter, Depends, Request
from fastapi.responses import HTMLResponse
from sqlalchemy import desc, func, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.auth import require_token
from app.config import get_settings, load_groups
from app.db import get_session
from app.models import StrategicLog
from app.templates_env import templates
router = APIRouter(dependencies=[Depends(require_token)])
@router.get("/", response_class=HTMLResponse)
async def dashboard(request: Request):
s = get_settings()
groups = load_groups(s.BASELINE_TOML, s.PORTFOLIO_TOML)
return templates.TemplateResponse(
request,
"dashboard.html",
{"groups": list(groups.keys()), "anchor": s.CASSANDRA_ANCHOR_DATE},
)
@router.get("/news", response_class=HTMLResponse)
async def news_page(request: Request):
return templates.TemplateResponse(request, "news.html", {})
@router.get("/upload", response_class=HTMLResponse)
async def upload_page(request: Request):
"""Drag-drop CSV import. Posts to /api/portfolios/upload."""
return templates.TemplateResponse(request, "upload.html", {})
async def _resolve_log_date(session: AsyncSession, day: str | None) -> date:
"""If `day` is YYYY-MM-DD use it; else fall back to the date of the most
recent generated log; else today."""
if day:
try:
return datetime.strptime(day, "%Y-%m-%d").date()
except ValueError:
pass
latest = (await session.execute(
select(StrategicLog.generated_at)
.order_by(desc(StrategicLog.generated_at))
.limit(1)
)).scalar_one_or_none()
if latest is not None:
return latest.date() if hasattr(latest, "date") else latest
return datetime.now(timezone.utc).date()
def _log_page_context(target: date) -> dict:
s = get_settings()
return {
"selected_iso": target.isoformat(),
"selected_month": target.strftime("%Y-%m"),
"current_tone": s.CASSANDRA_TONE.upper(),
"current_analysis": s.CASSANDRA_ANALYSIS.upper(),
}
@router.get("/log", response_class=HTMLResponse)
async def log_page(
request: Request,
session: AsyncSession = Depends(get_session),
):
target = await _resolve_log_date(session, None)
return templates.TemplateResponse(request, "log.html", _log_page_context(target))
@router.get("/log/{day}", response_class=HTMLResponse)
async def log_page_day(
request: Request,
day: str,
session: AsyncSession = Depends(get_session),
):
target = await _resolve_log_date(session, day)
return templates.TemplateResponse(request, "log.html", _log_page_context(target))