diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..9d0285f --- /dev/null +++ b/.env.example @@ -0,0 +1,26 @@ +# --- Hostnames (point these at the Docker host, e.g. in your router/Pi-hole DNS) --- +FINANCE_HOST=finance.home.lan +AUTH_HOST=auth.home.lan +TZ=Europe/Amsterdam + +# --- Secrets: generate with openssl rand -base64 48 | tr -d '\n' --- +AUTHENTIK_SECRET_KEY=change-me +AUTHENTIK_DB_PASSWORD=change-me +FINANCE_DB_PASSWORD=change-me + +# --- Versions --- +AUTHENTIK_TAG=2026.8.5 +TRAEFIK_TAG=v3.6 + +# --- Enable Banking (optional automatic sync for ING + Revolut) --- +# App ID from https://enablebanking.com/cp/applications ; put the private key at ./secrets/enablebanking.pem +EB_APP_ID= +EB_SYNC_HOURS=6 + +# --- Prices --- +# Optional free "Demo" key from CoinGecko for higher rate limits +COINGECKO_API_KEY= +PRICE_REFRESH_MINUTES=60 + +# Only if you enable the Let's Encrypt DNS challenge in traefik/traefik.yml +CF_DNS_API_TOKEN= diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..cbdce3f --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +.env +secrets/*.pem +authentik/ +traefik/certs/* +!traefik/certs/.gitkeep +__pycache__/ diff --git a/README.md b/README.md index 968924d..9756066 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,85 @@ -# Spendr +# Finance: a self-hosted dashboard for ING, Revolut, investments, gold and debts +``` +browser ──https──▶ Traefik ──forward-auth──▶ authentik (login, MFA) + │ + └──▶ finance (FastAPI) ──▶ Postgres + │ + ├─ Yahoo Finance (stocks/ETFs, gold spot, FX) + ├─ CoinGecko (crypto) + └─ Enable Banking (optional automatic ING/Revolut sync) +``` + +## What it does + +| Feature | How | +|---|---| +| **Categories** | ~200 seed rules for Dutch merchants (AH, Jumbo, NS, Ziggo, Vattenfall, CZ, Belastingdienst…). Fix one in the table and it gets a 🔒 lock. Click **+rule** to turn a fix into a rule. Moves between your own IBANs are auto-tagged *Transfers* and left out of spending. | +| **Subscriptions / monthly costs** | Detects weekly, monthly, quarterly and yearly payments from regular gaps and similar amounts (price increases are tolerated). You can confirm, ignore, or add an item by hand (rent, salary, yearly insurance). | +| **Missed payment alert** | A recurring item whose next date + grace period (6 days for monthly) has passed shows as **missed** on the dashboard. | +| **Investments** | You log buys and sells; cost is tracked with the average-cost method. Shows value vs paid, unrealised and realised P/L, allocation, and history. Stocks/ETFs use Yahoo tickers (`VWRL.AS`, `IWDA.AS`, `ASML.AS`), crypto uses CoinGecko ids (`bitcoin`). Everything is in EUR. | +| **Gold** | Grams or troy oz × purity (24k, 22k Krugerrand, 18k jewellery…) × spot (COMEX `GC=F` → EUR). A manual price override is available for dealer buyback prices. Silver works too: use symbol `SI=F`. | +| **Debts** | Covers both directions (what you owe and what you're owed). With a monthly amount and due day set, it shows **on track / ahead / behind (n missed)**, the next due date and an estimated payoff date. Payments are matched from bank transactions automatically by a text pattern, or you can add them by hand. | +| **Joint account** | Give the ING shared account a "your share %" (e.g. 50) and its spending is scaled in the totals. | +| **Live numbers** | Every 30 s (and whenever you come back to the tab) the page fetches `/api/live`. Changed totals, prices and P/L count up or down and flash green or red, with no reload. *Refresh prices* runs in place. When new transactions arrive, a "new data · reload" hint appears so charts can be redrawn. | +| **Dark mode** | Auto (follows the system), Light or Dark toggle in the sidebar, remembered per browser. | +| **Mobile** | Desktop-first layout. On phones the sidebar turns into a scrolling top bar and tables scroll sideways. | + +## Setup + +1. **DNS**: point `finance.home.lan` and `auth.home.lan` (or your own names) at the Docker host, e.g. in Pi-hole, AdGuard or your router. +2. **Configure** + ```bash + cp .env.example .env + # fill in hostnames + three secrets: openssl rand -base64 48 | tr -d '\n' + mkdir -p authentik/data authentik/certs authentik/custom-templates secrets + docker compose up -d --build + ``` +3. **authentik first run**: open `https://auth.home.lan/if/flow/initial-setup/` and create the admin user. Turn on TOTP or a passkey for it, because this app holds your bank data. +4. **Protect the app in authentik** (Admin → Applications → *Create with provider*): + - Provider type: **Proxy Provider** → **Forward auth (single application)** + - External host: `https://finance.home.lan` + - Then go to **Outposts → authentik Embedded Outpost → edit** and add the application. + - Optional: bind a policy or group so only you (and your partner, if you like) can open it. +5. Open `https://finance.home.lan`. You should be sent to the authentik login and then back to the app. + +### TLS +By default Traefik serves a self-signed certificate, so the browser shows a warning. You have two options: +- **mkcert** (LAN only): `mkcert "*.home.lan"`, save the files as `traefik/certs/local.crt` / `local.key`, then uncomment `traefik/dynamic/tls.yml`. +- **Let's Encrypt DNS challenge** (if you own a domain): uncomment the resolver in `traefik/traefik.yml` and set `CF_DNS_API_TOKEN` (or use another provider). This works even when the hosts are only reachable on your LAN. + +## Getting data in + +**CSV (always works).** Use *Import* and select several files at once. Overlapping periods are deduplicated. +- ING: Mijn ING → *Af- en bijschrijvingen downloaden* → CSV (comma or semicolon, NL or EN headers). The account is detected from the IBAN in the file. +- Revolut: app → ⋯ → *Statement* → CSV. Only completed transactions from the *Current* account are imported. + +First go to **Settings → Accounts** and add the IBANs of all three accounts (Revolut's too). Transfers between them are then recognised, and the shared account gets its share %. + +**Automatic sync (Enable Banking, free for your own accounts):** +1. Sign up at enablebanking.com → *Applications* → create one (Production). Set the redirect URL to `https://finance.home.lan/eb/callback`. +2. Save the downloaded private key as `secrets/enablebanking.pem` and put the app id in `.env` → `EB_APP_ID`. +3. In their control panel, use **Link accounts** for ING and Revolut. Free "restricted mode" only returns accounts you linked there. +4. `docker compose up -d`, then go to Settings → *Connect* (ING / NL, then Revolut; Revolut may be listed under LT). +5. The app syncs every `EB_SYNC_HOURS`. Bank consent (PSD2) expires after 90–180 days, so you'll need to click *Connect* again now and then. The expiry date is shown in Settings. + +CSV and API imports share the same dedupe key (account + date + amount + n-th of that day), so you can mix them. + +## Operations + +- **Backup**: `docker compose exec finance-db pg_dump -U finance finance | gzip > finance-$(date +%F).sql.gz`. Back up `authentik-db` the same way. +- **Logs**: `docker compose logs -f finance` +- **Not exposed**: the app has no published port. It is only reachable through Traefik and authentik. Keep it that way. +- Prices refresh every `PRICE_REFRESH_MINUTES`. Yahoo's endpoint is unofficial. If a ticker fails, the holding shows "price error" and you can set a manual price. +- The schema is created on start (`create_all`). Add Alembic if you start changing models. + +## UI +- Icons are [Lucide](https://lucide.dev) (ISC licence), stored inside the app as an SVG sprite (`templates/_icons.svg`), so no CDN is needed. +- Charts use Chart.js and have hover tooltips: savings rate per month, and P/L at each point on the value line. + - Click a bar to open that month, or a doughnut slice to see its transactions. + - Click legend entries to hide or show them. + - Range buttons (1M–All) on the history charts. +- On phones: bottom tab bar plus a slide-out menu. + +## Ideas for later +Budgets per category, splitting shared-house costs with your partner, DEGIRO/Bitvavo CSV import for trades, ntfy/Telegram push for missed payments, salary-missed alerts. diff --git a/app/Dockerfile b/app/Dockerfile new file mode 100644 index 0000000..4c22616 --- /dev/null +++ b/app/Dockerfile @@ -0,0 +1,18 @@ +FROM python:3.12-slim + +ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 +WORKDIR /app + +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +COPY . . +# Vendor Chart.js at build time so the running app needs no CDN +ADD https://cdn.jsdelivr.net/npm/chart.js@4.4.6/dist/chart.umd.min.js /app/static/chart.umd.min.js + +RUN useradd -u 1000 -m app && chown -R app /app +USER app + +EXPOSE 8000 +# Single worker on purpose: the background scheduler (price refresh, bank sync) runs in-process. +CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000", "--proxy-headers", "--forwarded-allow-ips", "*"] diff --git a/app/categorize.py b/app/categorize.py new file mode 100644 index 0000000..d7054dc --- /dev/null +++ b/app/categorize.py @@ -0,0 +1,140 @@ +"""Rule-based categorisation + seed data tuned for Dutch merchants.""" +import re +from functools import lru_cache + +from sqlalchemy import select +from sqlalchemy.orm import Session + +from models import Category, Rule, Transaction + +_PREFIXES = re.compile( + r"^(bea|gea|sepa|ccv\*|zettle_\*|sumup \*|sumup\*|pay\.nl\*|mollie\*|stichting|paypal \*|paypal\*|apple pay|" + r"google pay|ideal|betaalverzoek|tikkie)\s*[,:*]?\s*", re.I) + + +def normalize(text: str) -> str: + """Stable key for a counterparty: lower-case, no digits/punctuation/payment-processor prefixes.""" + s = (text or "").lower() + for _ in range(2): + s = _PREFIXES.sub("", s) + s = re.sub(r"[^a-z\s.&']", " ", s) + s = re.sub(r"\b(nl|bv|b\.v\.|n\.v\.|nv|the|via)\b", " ", s) + s = re.sub(r"\s+", " ", s).strip(" .") + return " ".join(s.split()[:4]) + + +@lru_cache(maxsize=2048) +def _compile(pattern: str) -> re.Pattern: + if pattern.startswith("re:"): + return re.compile(pattern[3:], re.I) + return re.compile(r"(? bool: + if rule.field == "iban": + return bool(tx.counter_iban) and tx.counter_iban.replace(" ", "").upper() == rule.pattern.replace(" ", "").upper() + if rule.field == "counterparty": + text = tx.counterparty or "" + elif rule.field == "description": + text = tx.description or "" + else: + text = f"{tx.counterparty} {tx.description}" + return bool(_compile(rule.pattern).search(text)) + + +def load_rules(db: Session) -> list[Rule]: + return list(db.scalars(select(Rule).order_by(Rule.priority, Rule.id))) + + +def categorize(db: Session, txs: list[Transaction], own_ibans: set[str] | None = None, + rules: list[Rule] | None = None) -> int: + """Assign categories to unlocked transactions. Returns how many got a category.""" + rules = rules if rules is not None else load_rules(db) + own_ibans = own_ibans or set() + transfer = db.scalar(select(Category).where(Category.name == "Transfers")) + n = 0 + for tx in txs: + if tx.category_locked: + continue + if transfer and tx.counter_iban and tx.counter_iban.replace(" ", "").upper() in own_ibans: + tx.category_id = transfer.id + n += 1 + continue + for r in rules: + if rule_matches(r, tx): + tx.category_id = r.category_id + n += 1 + break + return n + + +SEED: dict[str, tuple[str, str, list[str]]] = { + # name: (kind, color, patterns) + "Salary": ("income", "#2e7d32", ["salaris", "salary", "loon", "re:\\bsal\\.?\\b"]), + "Other income": ("income", "#66bb6a", ["belastingdienst teruggaaf", "toeslag", "zorgtoeslag", "huurtoeslag"]), + "Transfers": ("transfer", "#9e9e9e", ["top-up", "topup", "oranje spaarrekening", "spaarrekening", + "re:^to (eur|savings)", "re:revolut\\b.*top"]), + "Housing": ("expense", "#6d4c41", ["huur", "hypotheek", "vve", "woningstichting", "woonbron", "ymere", + "eigen haard", "de alliantie", "vesteda"]), + "Utilities": ("expense", "#f9a825", ["vattenfall", "eneco", "essent", "greenchoice", "budget energie", + "vandebron", "energiedirect", "pure energie", "frank energie", "tibber", + "waternet", "vitens", "evides", "brabant water", "pwn", "dunea", + "oasen", "wml"]), + "Internet & phone": ("expense", "#0288d1", ["ziggo", "kpn", "odido", "t-mobile", "vodafone", "simyo", "lebara", + "youfone", "delta fiber", "tele2", "re:\\bben\\b"]), + "Insurance": ("expense", "#5e35b1", ["zilveren kruis", "re:\\bcz\\b", "vgz", "menzis", "ohra", "centraal beheer", + "fbto", "interpolis", "nationale-nederlanden", "nationale nederlanden", + "a.s.r", "asr", "unive", "inshared", "dsw", "anderzorg", "zekur", + "promovendum", "allianz"]), + "Taxes": ("expense", "#455a64", ["belastingdienst", "gemeentelijke belastingen", "waterschap", "cjib", + "rdw", "re:^gemeente\\b", "bsgw", "gbt"]), + "Groceries": ("expense", "#43a047", ["albert heijn", "jumbo", "lidl", "aldi", "re:\\bplus\\b", "dirk", + "picnic", "ekoplaza", "vomar", "hoogvliet", "re:\\bcoop\\b", "spar", + "crisp", "flink", "dekamarkt", "nettorama", "re:\\bah\\b"]), + "Eating out": ("expense", "#ef6c00", ["thuisbezorgd", "uber eats", "deliveroo", "mcdonalds", "starbucks", + "burger king", "kfc", "dominos", "new york pizza", "febo", "restaurant", + "cafe", "eetcafe", "brasserie", "lunchroom"]), + "Transport": ("expense", "#00897b", ["ns groep", "ns reizigers", "re:\\bns\\b", "ov-chipkaart", "translink", + "gvb", "re:\\bret\\b", "htm", "arriva", "qbuzz", "connexxion", "keolis", + "uber", "bolt", "swapfiets", "felyx", "check technologies"]), + "Car": ("expense", "#546e7a", ["shell", "re:\\bbp\\b", "esso", "tinq", "tango", "totalenergies", "texaco", + "parkeren", "q-park", "anwb", "yellowbrick", "parkmobile", "easypark", + "fastned", "allego", "vandebron laad"]), + "Subscriptions": ("expense", "#d81b60", ["netflix", "spotify", "disney plus", "disneyplus", "videoland", + "apple.com/bill", "apple.com", "itunes", "google one", + "youtube premium", "amazon prime", "prime video", "hbo max", + "max.com", "chatgpt", "openai", "anthropic", "claude.ai", "icloud", + "patreon", "nlziet", "viaplay", "storytel", "audible", + "basic-fit", "basic fit", "sportcity", "trainmore"]), + "Shopping": ("expense", "#8e24aa", ["bol.com", "coolblue", "amazon", "zalando", "ikea", "action", "hema", + "kruidvat", "etos", "mediamarkt", "gamma", "praxis", "karwei", + "hornbach", "blokker", "primark", "h&m", "decathlon", "temu", + "aliexpress", "wehkamp", "intertoys"]), + "Health": ("expense", "#e53935", ["apotheek", "tandarts", "huisarts", "fysio", "mondzorg", "ziekenhuis", + "opticien", "pearle", "hans anders"]), + "Entertainment": ("expense", "#fb8c00", ["pathe", "vue", "kinepolis", "ticketmaster", "eventim", + "steam", "playstation", "nintendo", "xbox"]), + "Travel": ("expense", "#1e88e5", ["booking.com", "airbnb", "klm", "transavia", "ryanair", "easyjet", + "vueling", "schiphol", "hotel", "flixbus"]), + "Investments": ("transfer", "#3949ab", ["degiro", "trade republic", "bux", "bitvavo", "coinbase", "kraken", + "meesman", "brand new day", "peaks", "lynx", "saxo", "binance", + "goud", "holland gold", "goudwisselkantoor"]), + "Debt": ("expense", "#c62828", ["duo", "dienst uitvoering onderwijs", "aflossing", "lening"]), + "Cash": ("expense", "#757575", ["geldautomaat", "re:\\batm\\b", "cash withdrawal", "geldopname"]), + "Fees & interest": ("expense", "#9e9e9e", ["kosten oranjepakket", "kosten betaalpakket", "basic fee", + "premium plan fee", "metal plan fee", "rente", "interest"]), + "Other": ("expense", "#bdbdbd", []), +} + + +def seed(db: Session) -> None: + if db.scalar(select(Category.id).limit(1)) is not None: + return + for name, (kind, color, patterns) in SEED.items(): + cat = Category(name=name, kind=kind, color=color) + db.add(cat) + db.flush() + prio = 50 if name in ("Transfers", "Investments", "Salary") else 100 + for p in patterns: + db.add(Rule(pattern=p, field="any", category_id=cat.id, priority=prio)) + db.commit() diff --git a/app/chart.js-4.4.6.tgz b/app/chart.js-4.4.6.tgz new file mode 100644 index 0000000..ed3290f Binary files /dev/null and b/app/chart.js-4.4.6.tgz differ diff --git a/app/db.py b/app/db.py new file mode 100644 index 0000000..207f25b --- /dev/null +++ b/app/db.py @@ -0,0 +1,17 @@ +import os + +from sqlalchemy import create_engine +from sqlalchemy.orm import sessionmaker + +DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///./finance.db") + +engine = create_engine(DATABASE_URL, pool_pre_ping=True) +SessionLocal = sessionmaker(engine, expire_on_commit=False) + + +def get_db(): + db = SessionLocal() + try: + yield db + finally: + db.close() diff --git a/app/enablebanking.py b/app/enablebanking.py new file mode 100644 index 0000000..0aa66f0 --- /dev/null +++ b/app/enablebanking.py @@ -0,0 +1,144 @@ +"""Enable Banking (PSD2 aggregator) client: link ING / Revolut and pull transactions automatically. + +Free "restricted mode": create an application at https://enablebanking.com/cp/applications, +link your own accounts there, download the private key, set EB_APP_ID and mount the .pem. +""" +import logging +import os +import secrets +import time +from datetime import date, datetime, timedelta, timezone + +import httpx +import jwt +from sqlalchemy import func, select +from sqlalchemy.orm import Session + +from importers import parse_enablebanking +from models import Account, Setting, Transaction +from services import ingest + +API = "https://api.enablebanking.com" +log = logging.getLogger("enablebanking") + + +def configured() -> bool: + return bool(os.getenv("EB_APP_ID")) and os.path.exists(os.getenv("EB_KEY_PATH", "/run/secrets/enablebanking.pem")) + + +def _headers() -> dict: + app_id = os.environ["EB_APP_ID"] + with open(os.getenv("EB_KEY_PATH", "/run/secrets/enablebanking.pem")) as f: + key = f.read() + iat = int(time.time()) + token = jwt.encode({"iss": "enablebanking.com", "aud": "api.enablebanking.com", "iat": iat, "exp": iat + 3600}, + key, algorithm="RS256", headers={"kid": app_id}) + return {"Authorization": f"Bearer {token}"} + + +def _req(method: str, path: str, **kw) -> dict: + with httpx.Client(timeout=30) as c: + r = c.request(method, API + path, headers=_headers(), **kw) + if r.status_code >= 400: + raise RuntimeError(f"Enable Banking {method} {path}: {r.status_code} {r.text[:300]}") + return r.json() + + +def _set(db: Session, key: str, value: str) -> None: + row = db.get(Setting, key) or Setting(key=key) + row.value = value + db.add(row) + + +def get_setting(db: Session, key: str, default: str = "") -> str: + row = db.get(Setting, key) + return row.value if row else default + + +def aspsps(country: str = "NL") -> list[dict]: + return _req("GET", "/aspsps", params={"country": country, "psu_type": "personal"}).get("aspsps", []) + + +def start_auth(db: Session, name: str, country: str, redirect_url: str) -> str: + """Returns the bank's consent URL to redirect the browser to.""" + max_days = 90 + for a in aspsps(country): + if a["name"] == name: + max_days = max(1, int(a.get("maximum_consent_validity", 90 * 86400)) // 86400) + break + valid_until = datetime.now(timezone.utc) + timedelta(days=min(max_days, 180)) + state = secrets.token_urlsafe(24) + _set(db, "eb_state", state) + db.commit() + body = {"access": {"valid_until": valid_until.isoformat()}, + "aspsp": {"name": name, "country": country}, + "state": state, "redirect_url": redirect_url, "psu_type": "personal"} + return _req("POST", "/auth", json=body)["url"] + + +def finish_auth(db: Session, code: str, state: str) -> list[Account]: + if not state or state != get_setting(db, "eb_state"): + raise RuntimeError("Invalid state; start the bank connection again.") + s = _req("POST", "/sessions", json={"code": code}) + aspsp = (s.get("aspsp") or {}).get("name", "bank") + valid_until = (s.get("access") or {}).get("valid_until", "") + linked = [] + for acc in s.get("accounts", []): + iban = ((acc.get("account_id") or {}).get("iban") or "").replace(" ", "").upper() or None + a = db.scalar(select(Account).where(Account.iban == iban)) if iban else None + if a is None: + bank = "revolut" if "revolut" in aspsp.lower() else ("ing" if "ing" in aspsp.lower() else "other") + a = Account(name=acc.get("name") or f"{aspsp} {iban or ''}".strip(), bank=bank, iban=iban) + db.add(a) + a.eb_account_uid = acc["uid"] + linked.append(a) + _set(db, f"eb_valid_until:{aspsp}", valid_until) + _set(db, "eb_state", "") + db.commit() + return linked + + +def _transactions(uid: str, date_from: date) -> list[dict]: + out, cont = [], None + for _ in range(50): + params = {"date_from": date_from.isoformat()} + if cont: + params["continuation_key"] = cont + page = _req("GET", f"/accounts/{uid}/transactions", params=params) + out += page.get("transactions", []) + cont = page.get("continuation_key") + if not cont: + break + return out + + +def _balance(uid: str): + from decimal import Decimal + bals = _req("GET", f"/accounts/{uid}/balances").get("balances", []) + pref = ["CLBD", "ITBD", "ITAV", "XPCD", "CLAV"] + bals.sort(key=lambda b: pref.index(b.get("balance_type")) if b.get("balance_type") in pref else 99) + return Decimal(str(bals[0]["balance_amount"]["amount"])) if bals else None + + +def sync(db: Session) -> list[str]: + """Pull new transactions for every linked account. Returns human-readable results.""" + if not configured(): + return ["Enable Banking is not configured."] + msgs = [] + for a in db.scalars(select(Account).where(Account.eb_account_uid.is_not(None))): + try: + last = db.scalar(select(func.max(Transaction.date)).where(Transaction.account_id == a.id)) + date_from = (last - timedelta(days=3)) if last else date.today() - timedelta(days=89) + raw = [t for t in _transactions(a.eb_account_uid, date_from) + if (t.get("status") or "BOOK") == "BOOK"] + parsed = [parse_enablebanking(t) for t in raw] + bal = _balance(a.eb_account_uid) + r = ingest(db, a, parsed, source="api", balance=bal, balance_date=date.today() if bal is not None else None) + a.eb_last_sync = datetime.now() + db.commit() + msgs.append(f"{a.name}: {r['inserted']} new, {r['duplicates']} already known") + except Exception as e: # noqa: BLE001 + db.rollback() + log.warning("sync %s failed: %s", a.name, e) + msgs.append(f"{a.name}: {e}") + return msgs diff --git a/app/importers.py b/app/importers.py new file mode 100644 index 0000000..0e686c4 --- /dev/null +++ b/app/importers.py @@ -0,0 +1,159 @@ +"""Parsers for bank CSV exports (ING NL, Revolut) into a common shape.""" +import csv +import io +from dataclasses import dataclass, field +from datetime import date, datetime +from decimal import Decimal, InvalidOperation + + +@dataclass +class ParsedTx: + date: date + amount: Decimal # negative = out + counterparty: str + description: str + counter_iban: str | None = None + currency: str = "EUR" + raw_type: str = "" + + +@dataclass +class ParseResult: + fmt: str + txs: list[ParsedTx] = field(default_factory=list) + own_iban: str | None = None + balance: Decimal | None = None + balance_date: date | None = None + skipped: int = 0 + + +def to_decimal(s: str) -> Decimal: + s = (s or "").strip().replace(" ", "").replace("€", "").replace("−", "-") + if not s: + return Decimal("0") + if "," in s and "." in s: # 1.234,56 or 1,234.56 + if s.rfind(",") > s.rfind("."): + s = s.replace(".", "").replace(",", ".") + else: + s = s.replace(",", "") + elif "," in s: + s = s.replace(",", ".") + try: + return Decimal(s) + except InvalidOperation as e: + raise ValueError(f"Cannot parse amount {s!r}") from e + + +def _date(s: str) -> date: + s = s.strip() + for fmt in ("%Y%m%d", "%Y-%m-%d", "%d-%m-%Y", "%d/%m/%Y"): + try: + return datetime.strptime(s[:10] if "-" in s[:10] else s, fmt).date() + except ValueError: + continue + raise ValueError(f"Cannot parse date {s!r}") + + +def _rows(text: str): + first = text.splitlines()[0] if text else "" + delim = ";" if first.count(";") > first.count(",") else "," + reader = csv.DictReader(io.StringIO(text), delimiter=delim) + headers = [h.strip().lower() for h in (reader.fieldnames or [])] + rows = [{(k or "").strip().lower(): (v or "").strip() for k, v in r.items()} for r in reader] + return headers, rows + + +def _g(row: dict, *names: str) -> str: + for n in names: + if n in row and row[n] is not None: + return row[n] + return "" + + +def parse(content: bytes) -> ParseResult: + text = content.decode("utf-8-sig", errors="replace") + headers, rows = _rows(text) + hs = set(headers) + if {"started date", "amount", "state"} <= hs: + return parse_revolut(rows) + if "naam / omschrijving" in hs or "name / description" in hs: + return parse_ing(rows) + raise ValueError("Unrecognised CSV. Expected an ING (NL) or Revolut export. Headers found: " + + ", ".join(headers)) + + +def parse_ing(rows: list[dict]) -> ParseResult: + res = ParseResult(fmt="ing") + latest: tuple[date, int] | None = None + for i, row in enumerate(rows): + d = _date(_g(row, "datum", "date")) + direction = _g(row, "af bij", "debit/credit").lower() + amount = to_decimal(_g(row, "bedrag (eur)", "amount (eur)")) + if direction in ("af", "debit"): + amount = -abs(amount) + else: + amount = abs(amount) + own = _g(row, "rekening", "account") or None + res.own_iban = res.own_iban or own + res.txs.append(ParsedTx( + date=d, + amount=amount, + counterparty=_g(row, "naam / omschrijving", "name / description"), + description=_g(row, "mededelingen", "notifications"), + counter_iban=_g(row, "tegenrekening", "counterparty") or None, + raw_type=_g(row, "mutatiesoort", "transaction type") or _g(row, "code"), + )) + bal = _g(row, "saldo na mutatie", "resulting balance") + # ING lists newest first: the first row of the newest date carries the current balance + if bal and (latest is None or d > latest[0]): + latest = (d, i) + res.balance, res.balance_date = to_decimal(bal), d + return res + + +def parse_revolut(rows: list[dict]) -> ParseResult: + res = ParseResult(fmt="revolut") + latest: str | None = None + for row in rows: + if _g(row, "state").upper() != "COMPLETED": + res.skipped += 1 + continue + product = _g(row, "product").lower() + if product and product != "current": # savings vaults, deposits, etc. + res.skipped += 1 + continue + ts = _g(row, "completed date") or _g(row, "started date") + amount = to_decimal(_g(row, "amount")) - to_decimal(_g(row, "fee")) + desc = _g(row, "description") + res.txs.append(ParsedTx( + date=_date(ts), + amount=amount, + counterparty=desc, + description=desc, + currency=(_g(row, "currency") or "EUR").upper(), + raw_type=_g(row, "type"), + )) + bal = _g(row, "balance") + if bal and (_g(row, "currency") or "EUR").upper() == "EUR" and (latest is None or ts >= latest): + latest = ts + res.balance, res.balance_date = to_decimal(bal), _date(ts) + return res + + +def parse_enablebanking(t: dict) -> ParsedTx: + """Map one Enable Banking transaction object to ParsedTx.""" + amt = Decimal(str(t["transaction_amount"]["amount"])) + out = t.get("credit_debit_indicator") == "DBIT" + party = (t.get("creditor") if out else t.get("debtor")) or {} + party_acc = (t.get("creditor_account") if out else t.get("debtor_account")) or {} + d = t.get("booking_date") or t.get("value_date") or t.get("transaction_date") + info = t.get("remittance_information") or [] + return ParsedTx( + date=date.fromisoformat(d), + amount=-abs(amt) if out else abs(amt), + counterparty=party.get("name") or (info[0] if info else ""), + description=" ".join(info), + counter_iban=party_acc.get("iban"), + currency=t["transaction_amount"].get("currency", "EUR"), + raw_type=(t.get("bank_transaction_code") or {}).get("description") or "", + ) diff --git a/app/main.py b/app/main.py new file mode 100644 index 0000000..03efea4 --- /dev/null +++ b/app/main.py @@ -0,0 +1,747 @@ +import logging +import os +from contextlib import asynccontextmanager +from datetime import date, datetime, timedelta +from decimal import Decimal, InvalidOperation +from urllib.parse import quote + +from apscheduler.schedulers.background import BackgroundScheduler +from dateutil.relativedelta import relativedelta +from fastapi import Depends, FastAPI, File, Form, HTTPException, Request, UploadFile +from fastapi.responses import JSONResponse, RedirectResponse +from fastapi.staticfiles import StaticFiles +from fastapi.templating import Jinja2Templates +from markupsafe import Markup +from sqlalchemy import func, or_, select +from sqlalchemy.orm import Session, selectinload + +import enablebanking as eb +import prices +import recurring as rec_mod +from categorize import load_rules, rule_matches, seed, categorize, normalize +from db import SessionLocal, engine, get_db +from importers import parse +from models import (Account, Asset, Base, Category, Debt, DebtPayment, PortfolioSnapshot, Recurring, Rule, Trade, + Transaction) +from portfolio import holdings, totals +from services import category_totals, debt_status, ingest, match_debt_payments, monthly_totals, own_ibans + +logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s") +log = logging.getLogger("finance") +BASE_DIR = os.path.dirname(os.path.abspath(__file__)) + + +# ------------------------------------------------------------------ background jobs + +def _job(fn, name): + def run(): + db = SessionLocal() + try: + fn(db) + except Exception: # noqa: BLE001 + log.exception("job %s failed", name) + finally: + db.close() + return run + + +def _sync_and_detect(db): + if eb.configured(): + for m in eb.sync(db): + log.info("bank sync: %s", m) + rec_mod.detect(db) + + +@asynccontextmanager +async def lifespan(app: FastAPI): + Base.metadata.create_all(engine) + with SessionLocal() as db: + seed(db) + sched = None + if os.getenv("DISABLE_SCHEDULER") != "1": + sched = BackgroundScheduler(timezone=os.getenv("TZ", "Europe/Amsterdam")) + sched.add_job(_job(prices.refresh_prices, "prices"), "interval", + minutes=int(os.getenv("PRICE_REFRESH_MINUTES", "60")), next_run_time=datetime.now()) + sched.add_job(_job(_sync_and_detect, "sync"), "interval", hours=int(os.getenv("EB_SYNC_HOURS", "6")), + next_run_time=datetime.now() + timedelta(minutes=1)) + sched.start() + yield + if sched: + sched.shutdown(wait=False) + + +app = FastAPI(title="Finance", lifespan=lifespan, docs_url=None, redoc_url=None) +app.mount("/static", StaticFiles(directory=os.path.join(BASE_DIR, "static")), name="static") +templates = Jinja2Templates(directory=os.path.join(BASE_DIR, "templates")) + + +def eur(v, decimals=2, sign=False): + if v is None: + return "–" + v = Decimal(v) + s = f"{abs(v):,.{decimals}f}".replace(",", "X").replace(".", ",").replace("X", ".") + prefix = "-" if v < 0 else ("+" if sign and v > 0 else "") + return f"{prefix}€ {s}" + + +def num(v, decimals=4): + if v is None: + return "–" + s = f"{Decimal(v):,.{decimals}f}".rstrip("0").rstrip(".") if decimals else f"{Decimal(v):,.0f}" + return s.replace(",", "X").replace(".", ",").replace("X", ".") + + +def pct(v): + return "–" if v is None else f"{v:+.1f}%".replace(".", ",") + + +def icon(name: str, cls: str = "") -> Markup: + return Markup(f'') + + +templates.env.filters.update(eur=eur, num=num, pct=pct) +templates.env.globals.update(icon=icon) +templates.env.globals.update(today=date.today, rec_state=rec_mod.state, monthly_eq=rec_mod.monthly_equivalent) + + +def render(request: Request, name: str, **ctx): + ctx.setdefault("msg", request.query_params.get("msg")) + ctx.setdefault("user", request.headers.get("X-authentik-name") or request.headers.get("X-authentik-username")) + with SessionLocal() as db: # badge counter for the nav + recs = db.scalars(select(Recurring).where(Recurring.status != "ignored")) + ctx.setdefault("nav_missed", sum(1 for r in recs if rec_mod.state(r) == "missed")) + return templates.TemplateResponse(request, name, ctx) + + +def back(url: str, msg: str | None = None): + if msg: + url += ("&" if "?" in url else "?") + "msg=" + quote(msg) + return RedirectResponse(url, status_code=303) + + +def dec(s: str | None, default=None) -> Decimal | None: + if s is None or str(s).strip() == "": + return default + try: + return Decimal(str(s).strip().replace(" ", "").replace(",", ".")) + except InvalidOperation: + raise HTTPException(400, f"Not a number: {s!r}") + + +def d(s: str | None) -> date: + return date.fromisoformat(s) if s else date.today() + + +def get_or_404(db: Session, model, id_): + obj = db.get(model, id_) + if obj is None: + raise HTTPException(404, f"{model.__name__} {id_} not found") + return obj + + +def f(v) -> float: + return float(v or 0) + + +# ------------------------------------------------------------------ dashboard + +@app.get("/") +def dashboard(request: Request, account: int | None = None, month: str | None = None, db: Session = Depends(get_db)): + today = date.today() + start = date.fromisoformat(month + "-01") if month else today.replace(day=1) + end = start + relativedelta(months=1) + accounts = list(db.scalars(select(Account).order_by(Account.name))) + + cats = category_totals(db, start, end, account) + months = monthly_totals(db, 12, account) + cur = next((m for m in months if m["month"] == start.strftime("%Y-%m")), {"income": 0, "expense": 0}) + + rows = holdings(db) + pt = totals(rows) + debts = list(db.scalars(select(Debt).options(selectinload(Debt.payments)).where(Debt.closed.is_(False)))) + dstat = [(x, debt_status(x)) for x in debts] + i_owe = sum((s["remaining"] for x, s in dstat if x.direction == "i_owe"), Decimal(0)) + owed = sum((s["remaining"] for x, s in dstat if x.direction == "owed_to_me"), Decimal(0)) + cash = sum((a.balance * a.share_pct / 100 for a in accounts if a.balance is not None), Decimal(0)) + invest_value = pt.get("all", {}).get("value", Decimal(0)) + + recs = list(db.scalars(select(Recurring).where(Recurring.status != "ignored"))) + missed = [r for r in recs if rec_mod.state(r) == "missed"] + due = sorted([r for r in recs if rec_mod.state(r) == "due-soon"], key=lambda r: r.next_date) + subs_month = sum((rec_mod.monthly_equivalent(r) for r in recs if r.amount < 0), Decimal(0)) + uncategorised = db.scalar(select(func.count(Transaction.id)).where(Transaction.category_id.is_(None))) or 0 + + snaps = list(db.scalars(select(PortfolioSnapshot).where(PortfolioSnapshot.date >= today - timedelta(days=365)) + .order_by(PortfolioSnapshot.date))) + hist: dict[str, dict] = {} + for s in snaps: + h = hist.setdefault(s.date.isoformat(), {"value": 0.0, "cost": 0.0}) + h["value"] += f(s.value) + h["cost"] += f(s.cost) + + charts = { + "months": {"labels": [m["month"] for m in months], "income": [f(m["income"]) for m in months], + "expense": [f(m["expense"]) for m in months]}, + "cats": {"labels": [c["name"] for c in cats], "data": [f(c["total"]) for c in cats], + "colors": [c["color"] for c in cats], + "links": [f"/transactions?month={start:%Y-%m}&category={c['id'] or 'none'}" + + (f"&account={account}" if account else "") for c in cats]}, + "portfolio": {"labels": list(hist), "value": [h["value"] for h in hist.values()], + "cost": [h["cost"] for h in hist.values()]}, + } + return render(request, "dashboard.html", accounts=accounts, account=account, start=start, cats=cats, cur=cur, + pt=pt, i_owe=i_owe, owed=owed, cash=cash, invest_value=invest_value, + net_worth=cash + invest_value + owed - i_owe, missed=missed, due=due, subs_month=subs_month, + dstat=dstat, uncategorised=uncategorised, charts=charts, + prev_month=(start - relativedelta(months=1)).strftime("%Y-%m"), + next_month=end.strftime("%Y-%m") if end <= today else None) + + +# ------------------------------------------------------------------ transactions + +PAGE = 100 + + +@app.get("/transactions") +def transactions(request: Request, account: str = "", category: str = "", month: str = "", q: str = "", + page: int = 1, db: Session = Depends(get_db)): + query = select(Transaction).options(selectinload(Transaction.account), selectinload(Transaction.category)) + if account: + query = query.where(Transaction.account_id == int(account)) + if category == "none": + query = query.where(Transaction.category_id.is_(None)) + elif category: + query = query.where(Transaction.category_id == int(category)) + if month: + s = date.fromisoformat(month + "-01") + query = query.where(Transaction.date >= s, Transaction.date < s + relativedelta(months=1)) + if q: + like = f"%{q}%" + query = query.where(or_(Transaction.counterparty.ilike(like), Transaction.description.ilike(like), + Transaction.notes.ilike(like))) + total = db.scalar(select(func.count()).select_from(query.subquery())) + total_amount = db.scalar(select(func.sum(query.subquery().c.amount))) or 0 + txs = list(db.scalars(query.order_by(Transaction.date.desc(), Transaction.id.desc()) + .offset((page - 1) * PAGE).limit(PAGE))) + return render(request, "transactions.html", txs=txs, total=total, total_amount=total_amount, page=page, + pages=max(1, -(-total // PAGE)), + accounts=list(db.scalars(select(Account).order_by(Account.name))), + categories=list(db.scalars(select(Category).order_by(Category.name))), + f={"account": account, "category": category, "month": month, "q": q}) + + +@app.post("/transactions/{tx_id}/category") +def set_category(tx_id: int, category_id: str = Form(""), db: Session = Depends(get_db)): + tx = get_or_404(db, Transaction, tx_id) + tx.category_id = int(category_id) if category_id else None + tx.category_locked = bool(category_id) + db.commit() + return JSONResponse({"ok": True}) + + +@app.post("/transactions/{tx_id}/notes") +def set_notes(tx_id: int, notes: str = Form(""), db: Session = Depends(get_db)): + tx = get_or_404(db, Transaction, tx_id) + tx.notes = notes + db.commit() + return JSONResponse({"ok": True}) + + +# ------------------------------------------------------------------ import + +@app.get("/import") +def import_page(request: Request, db: Session = Depends(get_db)): + return render(request, "import.html", accounts=list(db.scalars(select(Account).order_by(Account.name))), + results=None) + + +@app.post("/import") +async def import_upload(request: Request, files: list[UploadFile] = File(...), account_id: str = Form("auto"), + db: Session = Depends(get_db)): + results = [] + for up in files: + name = up.filename or "file" + try: + res = parse(await up.read()) + if account_id != "auto": + acc = db.get(Account, int(account_id)) + elif res.own_iban: + iban = res.own_iban.replace(" ", "").upper() + acc = db.scalar(select(Account).where(Account.iban == iban)) + if acc is None: + acc = Account(name=f"ING {iban[-4:]}", bank="ing", iban=iban) + db.add(acc) + db.flush() + else: + acc = db.scalar(select(Account).where(Account.bank == res.fmt).order_by(Account.id)) + if acc is None: + acc = Account(name="Revolut" if res.fmt == "revolut" else name, bank=res.fmt) + db.add(acc) + db.flush() + r = ingest(db, acc, res.txs, "csv", res.balance, res.balance_date) + results.append({"file": name, "ok": True, "account": acc.name, "fmt": res.fmt, "skipped": res.skipped, **r}) + except Exception as e: # noqa: BLE001 + db.rollback() + results.append({"file": name, "ok": False, "error": str(e)}) + try: + rec_mod.detect(db) + except Exception: # noqa: BLE001 + log.exception("recurring detection failed") + return render(request, "import.html", accounts=list(db.scalars(select(Account).order_by(Account.name))), + results=results) + + +# ------------------------------------------------------------------ recurring + +@app.get("/recurring") +def recurring_page(request: Request, show: str = "active", db: Session = Depends(get_db)): + q = select(Recurring).options(selectinload(Recurring.account), selectinload(Recurring.category)) + if show == "active": + q = q.where(Recurring.status != "ignored") + elif show == "ignored": + q = q.where(Recurring.status == "ignored") + recs = list(db.scalars(q)) + order = {"missed": 0, "due-soon": 1, "ok": 2, "ignored": 3} + recs.sort(key=lambda r: (order[rec_mod.state(r)], r.next_date or date.max)) + out_total = sum((rec_mod.monthly_equivalent(r) for r in recs if r.amount < 0 and r.status != "ignored"), Decimal(0)) + in_total = sum((rec_mod.monthly_equivalent(r) for r in recs if r.amount > 0 and r.status != "ignored"), Decimal(0)) + return render(request, "recurring.html", recs=recs, show=show, out_total=out_total, in_total=in_total, + accounts=list(db.scalars(select(Account))), + categories=list(db.scalars(select(Category).order_by(Category.name)))) + + +@app.post("/recurring/detect") +def recurring_detect(db: Session = Depends(get_db)): + n = rec_mod.detect(db) + return back("/recurring", f"Detection finished: {n} new recurring payment(s) found.") + + +@app.post("/recurring/add") +def recurring_add(name: str = Form(...), match: str = Form(...), amount: str = Form(...), + frequency: str = Form("monthly"), next_date: str = Form(...), direction: str = Form("out"), + db: Session = Depends(get_db)): + amt = abs(dec(amount)) * (-1 if direction == "out" else 1) + r = Recurring(name=name, match=normalize(match) or match.lower(), amount=amt, frequency=frequency, + next_date=d(next_date), source="manual", status="confirmed") + db.add(r) + db.flush() + rec_mod.refresh(db) + db.commit() + return back("/recurring", f"Added {name}.") + + +@app.post("/recurring/{rid}/update") +def recurring_update(rid: int, status: str = Form(None), name: str = Form(None), frequency: str = Form(None), + amount: str = Form(None), db: Session = Depends(get_db)): + r = db.get(Recurring, rid) + if status: + r.status = status + if name: + r.name = name + if frequency: + r.frequency = frequency + if r.last_date: + r.next_date = r.last_date + rec_mod.step(frequency) + if amount: + r.amount = -abs(dec(amount)) if r.amount < 0 else abs(dec(amount)) + if frequency or amount: + r.source = "manual" # stop auto-detection from overwriting your edits + db.commit() + return back("/recurring") + + +@app.post("/recurring/{rid}/delete") +def recurring_delete(rid: int, db: Session = Depends(get_db)): + db.delete(db.get(Recurring, rid)) + db.commit() + return back("/recurring", "Removed. (Detected items may come back on the next scan; use Ignore to hide for good.)") + + +# ------------------------------------------------------------------ investments & gold + +def _portfolio(request, db, kinds: list[str], template: str, title: str): + rows = [r for r in holdings(db) if r["asset"].kind in kinds] + t = totals(rows) + snaps = list(db.scalars(select(PortfolioSnapshot).where(PortfolioSnapshot.kind.in_(kinds)) + .order_by(PortfolioSnapshot.date))) + hist: dict[str, dict] = {} + for s in snaps: + h = hist.setdefault(s.date.isoformat(), {"value": 0.0, "cost": 0.0}) + h["value"] += f(s.value) + h["cost"] += f(s.cost) + chart = {"labels": list(hist), "value": [h["value"] for h in hist.values()], + "cost": [h["cost"] for h in hist.values()], + "alloc_labels": [r["asset"].name for r in rows if r["value"]], + "alloc_values": [f(r["value"]) for r in rows if r["value"]]} + assets = list(db.scalars(select(Asset).where(Asset.kind.in_(kinds)).order_by(Asset.name))) + trades = list(db.scalars(select(Trade).join(Asset).where(Asset.kind.in_(kinds)) + .options(selectinload(Trade.asset)).order_by(Trade.date.desc()))) + return render(request, template, rows=rows, t=t, kinds=kinds, chart=chart, assets=assets, trades=trades, + title=title) + + +@app.get("/investments") +def investments(request: Request, db: Session = Depends(get_db)): + return _portfolio(request, db, ["stock", "crypto"], "investments.html", "Investments") + + +@app.get("/gold") +def gold(request: Request, db: Session = Depends(get_db)): + return _portfolio(request, db, ["gold"], "investments.html", "Gold") + + +@app.post("/assets/add") +def asset_add(request: Request, name: str = Form(...), kind: str = Form(...), symbol: str = Form(""), + unit: str = Form("unit"), purity: str = Form("1"), db: Session = Depends(get_db)): + if kind == "gold": + symbol = symbol or "GC=F" + unit = unit if unit in ("gram", "oz") else "gram" + a = Asset(name=name, kind=kind, symbol=symbol.strip(), unit=unit, purity=dec(purity, Decimal(1))) + db.add(a) + db.commit() + try: + prices.refresh_prices(db) + except Exception: # noqa: BLE001 + log.exception("price refresh failed") + return back("/gold" if kind == "gold" else "/investments", f"Added {name}. Now add your purchases.") + + +@app.post("/assets/{aid}/update") +def asset_update(aid: int, manual_price: str = Form(""), symbol: str = Form(None), db: Session = Depends(get_db)): + a = db.get(Asset, aid) + a.manual_price = dec(manual_price) + if a.manual_price is not None: + a.price_error = None + if symbol: + a.symbol = symbol.strip() + db.commit() + prices.snapshot(db) + return back("/gold" if a.kind == "gold" else "/investments", "Saved.") + + +@app.post("/assets/{aid}/delete") +def asset_delete(aid: int, db: Session = Depends(get_db)): + a = db.get(Asset, aid) + kind = a.kind + db.delete(a) + db.commit() + return back("/gold" if kind == "gold" else "/investments", "Deleted.") + + +@app.post("/trades/add") +def trade_add(asset_id: int = Form(...), side: str = Form("buy"), date_: str = Form(..., alias="date"), + quantity: str = Form(...), price: str = Form(""), total: str = Form(""), fees: str = Form("0"), + notes: str = Form(""), db: Session = Depends(get_db)): + a = db.get(Asset, asset_id) + qty = dec(quantity) + p = dec(price) + if p is None: + tot = dec(total) + if tot is None or not qty: + raise HTTPException(400, "Give either a price per unit or a total amount.") + p = tot / qty + db.add(Trade(asset_id=a.id, side=side, date=d(date_), quantity=qty, price=p, fees=dec(fees, Decimal(0)), + notes=notes)) + db.commit() + prices.snapshot(db) + return back("/gold" if a.kind == "gold" else "/investments", "Saved.") + + +@app.post("/trades/{tid}/delete") +def trade_delete(tid: int, db: Session = Depends(get_db)): + t = db.get(Trade, tid) + kind = t.asset.kind + db.delete(t) + db.commit() + return back("/gold" if kind == "gold" else "/investments", "Deleted.") + + +@app.post("/prices/refresh") +def prices_refresh(request: Request, db: Session = Depends(get_db)): + errors = prices.refresh_prices(db) + ref = request.headers.get("referer") or "/investments" + path = "/" + ref.split("/", 3)[3].split("?")[0] if ref.count("/") >= 3 else "/investments" + return back(path, "Prices updated." if not errors else "Some prices failed: " + "; ".join(errors)[:400]) + + +# ------------------------------------------------------------------ debts + +@app.get("/debts") +def debts_page(request: Request, show_closed: int = 0, db: Session = Depends(get_db)): + q = select(Debt).options(selectinload(Debt.payments)).order_by(Debt.name) + if not show_closed: + q = q.where(Debt.closed.is_(False)) + debts = [(x, debt_status(x)) for x in db.scalars(q)] + sums = {k: sum((s["remaining"] for x, s in debts if x.direction == k), Decimal(0)) for k in ("i_owe", "owed_to_me")} + return render(request, "debts.html", debts=debts, sums=sums, show_closed=show_closed) + + +@app.get("/debts/{did}") +def debt_detail(request: Request, did: int, db: Session = Depends(get_db)): + x = get_or_404(db, Debt, did) + s = debt_status(x) + running, bal = [], x.principal + for p in x.payments: + bal -= p.amount + running.append((p, bal)) + return render(request, "debt_detail.html", d=x, s=s, running=list(reversed(running))) + + +def _debt_fields(name, counterparty, direction, principal, start_date, interest_rate, monthly_payment, due_day, + match_pattern, notes): + return dict(name=name, counterparty=counterparty, direction=direction, principal=dec(principal), + start_date=d(start_date), interest_rate=dec(interest_rate), monthly_payment=dec(monthly_payment), + due_day=int(due_day) if due_day else None, match_pattern=(match_pattern or "").strip() or None, + notes=notes) + + +@app.post("/debts/save") +def debt_save(id: str = Form(""), name: str = Form(...), counterparty: str = Form(""), direction: str = Form(...), + principal: str = Form(...), start_date: str = Form(""), interest_rate: str = Form(""), + monthly_payment: str = Form(""), due_day: str = Form(""), match_pattern: str = Form(""), + notes: str = Form(""), db: Session = Depends(get_db)): + fields = _debt_fields(name, counterparty, direction, principal, start_date, interest_rate, monthly_payment, + due_day, match_pattern, notes) + x = db.get(Debt, int(id)) if id else Debt() + for k, v in fields.items(): + setattr(x, k, v) + db.add(x) + db.commit() + n = _rematch(db, x) + return back(f"/debts/{x.id}", f"Saved. {n} payment(s) matched from bank transactions." if n else "Saved.") + + +def _rematch(db: Session, x: Debt) -> int: + if not x.match_pattern: + return 0 + txs = list(db.scalars(select(Transaction).where(Transaction.date >= x.start_date))) + n = match_debt_payments(db, txs) + db.commit() + return n + + +@app.post("/debts/{did}/rematch") +def debt_rematch(did: int, db: Session = Depends(get_db)): + n = _rematch(db, db.get(Debt, did)) + return back(f"/debts/{did}", f"{n} new payment(s) matched.") + + +@app.post("/debts/{did}/payment") +def debt_payment(did: int, date_: str = Form("", alias="date"), amount: str = Form(...), notes: str = Form(""), + db: Session = Depends(get_db)): + db.add(DebtPayment(debt_id=did, date=d(date_), amount=abs(dec(amount)), notes=notes)) + db.commit() + return back(f"/debts/{did}", "Payment added.") + + +@app.post("/debts/{did}/toggle") +def debt_toggle(did: int, db: Session = Depends(get_db)): + x = db.get(Debt, did) + x.closed = not x.closed + db.commit() + return back(f"/debts/{did}") + + +@app.post("/debts/{did}/delete") +def debt_delete(did: int, db: Session = Depends(get_db)): + db.delete(db.get(Debt, did)) + db.commit() + return back("/debts", "Deleted.") + + +@app.post("/payments/{pid}/delete") +def payment_delete(pid: int, db: Session = Depends(get_db)): + p = db.get(DebtPayment, pid) + did = p.debt_id + if p.transaction_id: + tx = db.get(Transaction, p.transaction_id) + if tx: + tx.debt_id = None + db.delete(p) + db.commit() + return back(f"/debts/{did}", "Payment removed.") + + +# ------------------------------------------------------------------ settings: accounts, categories, rules, bank sync + +@app.get("/settings") +def settings_page(request: Request, db: Session = Depends(get_db)): + from models import Setting + eb_valid = {s.key.split(":", 1)[1]: s.value for s in db.scalars(select(Setting).where(Setting.key.like("eb_valid_until:%")))} + rules = list(db.scalars(select(Rule).options(selectinload(Rule.category)).order_by(Rule.priority, Rule.id))) + counts = dict(db.execute(select(Transaction.category_id, func.count()).group_by(Transaction.category_id)).all()) + return render(request, "settings.html", accounts=list(db.scalars(select(Account).order_by(Account.name))), + categories=list(db.scalars(select(Category).order_by(Category.kind, Category.name))), + rules=rules, counts=counts, eb_configured=eb.configured(), eb_valid=eb_valid, + prefill=request.query_params) + + +@app.post("/accounts/save") +def account_save(id: str = Form(""), name: str = Form(...), bank: str = Form("ing"), iban: str = Form(""), + share_pct: int = Form(100), db: Session = Depends(get_db)): + a = db.get(Account, int(id)) if id else Account() + a.name, a.bank, a.share_pct = name, bank, max(0, min(100, share_pct)) + a.iban = iban.replace(" ", "").upper() or None + db.add(a) + db.commit() + return back("/settings", "Account saved.") + + +@app.post("/accounts/{aid}/delete") +def account_delete(aid: int, db: Session = Depends(get_db)): + a = db.get(Account, aid) + for tx in db.scalars(select(Transaction).where(Transaction.account_id == aid)): + db.delete(tx) + db.delete(a) + db.commit() + return back("/settings", "Account and its transactions deleted.") + + +@app.post("/categories/save") +def category_save(id: str = Form(""), name: str = Form(...), kind: str = Form("expense"), color: str = Form("#888888"), + db: Session = Depends(get_db)): + c = db.get(Category, int(id)) if id else Category() + c.name, c.kind, c.color = name, kind, color + db.add(c) + db.commit() + return back("/settings#categories", "Category saved.") + + +@app.post("/categories/{cid}/delete") +def category_delete(cid: int, db: Session = Depends(get_db)): + db.delete(db.get(Category, cid)) + db.commit() + return back("/settings#categories", "Category deleted.") + + +@app.post("/rules/add") +def rule_add(pattern: str = Form(...), field: str = Form("any"), category_id: int = Form(...), + priority: int = Form(10), apply: str = Form("1"), db: Session = Depends(get_db)): + r = Rule(pattern=pattern.strip(), field=field, category_id=category_id, priority=priority) + db.add(r) + db.flush() + n = 0 + if apply: + for tx in db.scalars(select(Transaction).where(Transaction.category_locked.is_(False))): + if rule_matches(r, tx): + tx.category_id = category_id + n += 1 + db.commit() + return back("/settings#rules", f"Rule added and applied to {n} transaction(s).") + + +@app.post("/rules/{rid}/delete") +def rule_delete(rid: int, db: Session = Depends(get_db)): + db.delete(db.get(Rule, rid)) + db.commit() + return back("/settings#rules", "Rule deleted.") + + +@app.post("/rules/apply") +def rules_apply(only_uncategorised: str = Form(""), db: Session = Depends(get_db)): + q = select(Transaction).where(Transaction.category_locked.is_(False)) + if only_uncategorised: + q = q.where(Transaction.category_id.is_(None)) + txs = list(db.scalars(q)) + if not only_uncategorised: + for tx in txs: + tx.category_id = None + n = categorize(db, txs, own_ibans(db), load_rules(db)) + db.commit() + return back("/settings#rules", f"Re-categorised: {n} of {len(txs)} transactions matched a rule.") + + +@app.post("/eb/connect") +def eb_connect(request: Request, aspsp: str = Form(...), country: str = Form("NL"), db: Session = Depends(get_db)): + base = os.getenv("PUBLIC_URL") or str(request.base_url).rstrip("/") + try: + url = eb.start_auth(db, aspsp, country, f"{base}/eb/callback") + except Exception as e: # noqa: BLE001 + return back("/settings#bank", f"Could not start: {e}") + return RedirectResponse(url, status_code=303) + + +@app.get("/eb/callback") +def eb_callback(code: str = "", state: str = "", error: str = "", error_description: str = "", + db: Session = Depends(get_db)): + if error: + return back("/settings#bank", f"Bank returned an error: {error} {error_description}") + try: + linked = eb.finish_auth(db, code, state) + msgs = eb.sync(db) + rec_mod.detect(db) + except Exception as e: # noqa: BLE001 + return back("/settings#bank", f"Linking failed: {e}") + return back("/settings#bank", f"Linked {len(linked)} account(s). " + " | ".join(msgs)) + + +@app.post("/eb/sync") +def eb_sync(db: Session = Depends(get_db)): + msgs = eb.sync(db) + rec_mod.detect(db) + return back("/settings#bank", " | ".join(msgs) or "Nothing to sync.") + + +@app.get("/eb/banks") +def eb_banks(country: str = "NL"): + try: + return JSONResponse([a["name"] for a in eb.aspsps(country)]) + except Exception as e: # noqa: BLE001 + return JSONResponse({"error": str(e)}, status_code=502) + + +# ------------------------------------------------------------------ live numbers (polled by app.js) + +@app.get("/api/live") +def live(account: int | None = None, month: str | None = None, db: Session = Depends(get_db)): + """Every number the pages can update in place, keyed by the data-live attribute.""" + today = date.today() + start = date.fromisoformat(month + "-01") if month else today.replace(day=1) + months = monthly_totals(db, 12, account) + cur = next((m for m in months if m["month"] == start.strftime("%Y-%m")), None) + if cur is None: # month outside the 12-month window + cur = monthly_totals(db, (today.year - start.year) * 12 + today.month - start.month + 1, account)[0] + rows = holdings(db) + pt = totals(rows) + accounts = list(db.scalars(select(Account))) + debts = [(x, debt_status(x)) for x in db.scalars(select(Debt).options(selectinload(Debt.payments)) + .where(Debt.closed.is_(False)))] + i_owe = sum((s["remaining"] for x, s in debts if x.direction == "i_owe"), Decimal(0)) + owed = sum((s["remaining"] for x, s in debts if x.direction == "owed_to_me"), Decimal(0)) + cash = sum((a.balance * a.share_pct / 100 for a in accounts if a.balance is not None), Decimal(0)) + v = {"cash": cash, "i_owe": i_owe, "owed": owed, "debt_net": owed - i_owe, + "spent": cur["expense"], "income": cur["income"], "net_month": cur["income"] - cur["expense"]} + for kind in ("all", "stock", "crypto", "gold"): + t = pt.get(kind) or {"value": 0, "cost": 0, "pnl": 0, "pnl_pct": None, "realized": 0} + for k in ("value", "cost", "pnl", "pnl_pct", "realized"): + v[f"{kind}_{k}"] = t[k] + for k in ("value", "cost", "pnl", "realized"): + v[f"inv_{k}"] = Decimal(str(v[f"stock_{k}"])) + Decimal(str(v[f"crypto_{k}"])) + v["inv_pnl_pct"] = float(v["inv_pnl"] / v["inv_cost"] * 100) if v["inv_cost"] else None + v["net_worth"] = cash + v["all_value"] + owed - i_owe + for r in rows: + a = r["asset"].id + v.update({f"a{a}_price": r["price"], f"a{a}_value": r["value"], f"a{a}_pnl": r["pnl"], + f"a{a}_pnl_pct": r["pnl_pct"]}) + for a in accounts: + v[f"acc{a.id}_balance"] = a.balance + for x, s in debts: + v[f"d{x.id}_remaining"] = s["remaining"] + v[f"d{x.id}_paid"] = s["paid"] + recs = [r for r in db.scalars(select(Recurring)) if rec_mod.state(r) == "missed"] + v["missed_count"] = len(recs) + newest = db.scalar(select(func.max(Transaction.id))) or 0 + priced = db.scalar(select(func.max(Asset.last_price_at))) + return JSONResponse({"values": {k: (None if x is None else float(x)) for k, x in v.items()}, + "version": f"{newest}:{priced}", "at": datetime.now().strftime("%H:%M:%S")}) + + +@app.post("/api/prices/refresh") +def api_prices_refresh(db: Session = Depends(get_db)): + errors = prices.refresh_prices(db) + return JSONResponse({"ok": not errors, "errors": errors}) + + +@app.get("/healthz") +def healthz(): + return {"ok": True} diff --git a/app/models.py b/app/models.py new file mode 100644 index 0000000..93db8f2 --- /dev/null +++ b/app/models.py @@ -0,0 +1,165 @@ +from datetime import date, datetime +from decimal import Decimal + +from sqlalchemy import Boolean, Date, DateTime, ForeignKey, Integer, Numeric, String, Text +from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship + +MONEY = Numeric(14, 2) +QTY = Numeric(24, 8) +PRICE = Numeric(20, 6) + + +class Base(DeclarativeBase): + pass + + +class Account(Base): + __tablename__ = "accounts" + id: Mapped[int] = mapped_column(primary_key=True) + name: Mapped[str] = mapped_column(String(100)) + bank: Mapped[str] = mapped_column(String(20), default="ing") # ing | revolut | other + iban: Mapped[str | None] = mapped_column(String(40), unique=True) + share_pct: Mapped[int] = mapped_column(Integer, default=100) # your share of a joint account + balance: Mapped[Decimal | None] = mapped_column(MONEY) + balance_date: Mapped[date | None] = mapped_column(Date) + eb_account_uid: Mapped[str | None] = mapped_column(String(100)) + eb_last_sync: Mapped[datetime | None] = mapped_column(DateTime) + + +class Category(Base): + __tablename__ = "categories" + id: Mapped[int] = mapped_column(primary_key=True) + name: Mapped[str] = mapped_column(String(60), unique=True) + kind: Mapped[str] = mapped_column(String(10), default="expense") # expense | income | transfer + color: Mapped[str] = mapped_column(String(9), default="#888888") + + +class Rule(Base): + __tablename__ = "rules" + id: Mapped[int] = mapped_column(primary_key=True) + pattern: Mapped[str] = mapped_column(String(200)) # words, or "re:" + field: Mapped[str] = mapped_column(String(20), default="any") # any | counterparty | description | iban + category_id: Mapped[int] = mapped_column(ForeignKey("categories.id", ondelete="CASCADE")) + priority: Mapped[int] = mapped_column(Integer, default=100) # lower wins + category: Mapped[Category] = relationship() + + +class Transaction(Base): + __tablename__ = "transactions" + id: Mapped[int] = mapped_column(primary_key=True) + account_id: Mapped[int] = mapped_column(ForeignKey("accounts.id", ondelete="CASCADE"), index=True) + date: Mapped[date] = mapped_column(Date, index=True) + amount: Mapped[Decimal] = mapped_column(MONEY) # negative = money out + currency: Mapped[str] = mapped_column(String(3), default="EUR") + counterparty: Mapped[str] = mapped_column(String(200), default="") + counter_iban: Mapped[str | None] = mapped_column(String(40)) + description: Mapped[str] = mapped_column(Text, default="") + raw_type: Mapped[str] = mapped_column(String(60), default="") + source: Mapped[str] = mapped_column(String(20), default="csv") + hash: Mapped[str] = mapped_column(String(64), unique=True) + category_id: Mapped[int | None] = mapped_column(ForeignKey("categories.id", ondelete="SET NULL"), index=True) + category_locked: Mapped[bool] = mapped_column(Boolean, default=False) + recurring_id: Mapped[int | None] = mapped_column(ForeignKey("recurring.id", ondelete="SET NULL")) + debt_id: Mapped[int | None] = mapped_column(ForeignKey("debts.id", ondelete="SET NULL")) + notes: Mapped[str] = mapped_column(Text, default="") + + account: Mapped[Account] = relationship() + category: Mapped[Category | None] = relationship() + + +class Recurring(Base): + __tablename__ = "recurring" + id: Mapped[int] = mapped_column(primary_key=True) + name: Mapped[str] = mapped_column(String(120)) + match: Mapped[str] = mapped_column(String(200)) # normalised counterparty text + source: Mapped[str] = mapped_column(String(10), default="detected") # detected | manual + status: Mapped[str] = mapped_column(String(10), default="detected") # detected | confirmed | ignored + frequency: Mapped[str] = mapped_column(String(10), default="monthly") + amount: Mapped[Decimal] = mapped_column(MONEY) # typical amount, negative = out + tolerance_pct: Mapped[int] = mapped_column(Integer, default=30) + last_date: Mapped[date | None] = mapped_column(Date) + next_date: Mapped[date | None] = mapped_column(Date) + occurrences: Mapped[int] = mapped_column(Integer, default=0) + account_id: Mapped[int | None] = mapped_column(ForeignKey("accounts.id", ondelete="SET NULL")) + category_id: Mapped[int | None] = mapped_column(ForeignKey("categories.id", ondelete="SET NULL")) + + account: Mapped[Account | None] = relationship() + category: Mapped[Category | None] = relationship() + + +class Asset(Base): + __tablename__ = "assets" + id: Mapped[int] = mapped_column(primary_key=True) + name: Mapped[str] = mapped_column(String(120)) + kind: Mapped[str] = mapped_column(String(10)) # stock | crypto | gold + symbol: Mapped[str] = mapped_column(String(60)) # Yahoo ticker / CoinGecko id / GC=F + unit: Mapped[str] = mapped_column(String(10), default="unit") # unit | gram | oz + purity: Mapped[Decimal] = mapped_column(Numeric(6, 4), default=Decimal("1")) # gold: 0.9999, 0.9167 (22k)... + last_price: Mapped[Decimal | None] = mapped_column(PRICE) # EUR per unit + last_price_at: Mapped[datetime | None] = mapped_column(DateTime) + manual_price: Mapped[Decimal | None] = mapped_column(PRICE) + price_error: Mapped[str | None] = mapped_column(String(300)) + + trades: Mapped[list["Trade"]] = relationship(back_populates="asset", cascade="all, delete-orphan", + order_by="Trade.date") + + +class Trade(Base): + __tablename__ = "trades" + id: Mapped[int] = mapped_column(primary_key=True) + asset_id: Mapped[int] = mapped_column(ForeignKey("assets.id", ondelete="CASCADE")) + date: Mapped[date] = mapped_column(Date) + side: Mapped[str] = mapped_column(String(4), default="buy") # buy | sell + quantity: Mapped[Decimal] = mapped_column(QTY) + price: Mapped[Decimal] = mapped_column(PRICE) # EUR per unit + fees: Mapped[Decimal] = mapped_column(MONEY, default=Decimal("0")) + notes: Mapped[str] = mapped_column(Text, default="") + + asset: Mapped[Asset] = relationship(back_populates="trades") + + +class PortfolioSnapshot(Base): + __tablename__ = "portfolio_snapshots" + id: Mapped[int] = mapped_column(primary_key=True) + date: Mapped[date] = mapped_column(Date, index=True) + kind: Mapped[str] = mapped_column(String(10)) + value: Mapped[Decimal] = mapped_column(MONEY) + cost: Mapped[Decimal] = mapped_column(MONEY) + + +class Debt(Base): + __tablename__ = "debts" + id: Mapped[int] = mapped_column(primary_key=True) + name: Mapped[str] = mapped_column(String(120)) + counterparty: Mapped[str] = mapped_column(String(120), default="") + direction: Mapped[str] = mapped_column(String(12)) # i_owe | owed_to_me + principal: Mapped[Decimal] = mapped_column(MONEY) + start_date: Mapped[date] = mapped_column(Date) + interest_rate: Mapped[Decimal | None] = mapped_column(Numeric(6, 3)) + monthly_payment: Mapped[Decimal | None] = mapped_column(MONEY) + due_day: Mapped[int | None] = mapped_column(Integer) + match_pattern: Mapped[str | None] = mapped_column(String(200)) + closed: Mapped[bool] = mapped_column(Boolean, default=False) + notes: Mapped[str] = mapped_column(Text, default="") + + payments: Mapped[list["DebtPayment"]] = relationship(back_populates="debt", cascade="all, delete-orphan", + order_by="DebtPayment.date") + + +class DebtPayment(Base): + __tablename__ = "debt_payments" + id: Mapped[int] = mapped_column(primary_key=True) + debt_id: Mapped[int] = mapped_column(ForeignKey("debts.id", ondelete="CASCADE")) + date: Mapped[date] = mapped_column(Date) + amount: Mapped[Decimal] = mapped_column(MONEY) # always positive + transaction_id: Mapped[int | None] = mapped_column(ForeignKey("transactions.id", ondelete="SET NULL"), + unique=True) + notes: Mapped[str] = mapped_column(Text, default="") + + debt: Mapped[Debt] = relationship(back_populates="payments") + + +class Setting(Base): + __tablename__ = "settings" + key: Mapped[str] = mapped_column(String(60), primary_key=True) + value: Mapped[str] = mapped_column(Text, default="") diff --git a/app/portfolio.py b/app/portfolio.py new file mode 100644 index 0000000..3162ed9 --- /dev/null +++ b/app/portfolio.py @@ -0,0 +1,68 @@ +"""Holdings, cost basis (average-cost method) and profit/loss.""" +from decimal import Decimal + +from sqlalchemy import select +from sqlalchemy.orm import Session, selectinload + +from models import Asset + +ZERO = Decimal("0") + + +def position(asset: Asset) -> dict: + qty = cost = realized = ZERO + for t in asset.trades: + if t.side == "buy": + qty += t.quantity + cost += t.quantity * t.price + (t.fees or ZERO) + else: + avg = cost / qty if qty else ZERO + sold = min(t.quantity, qty) + realized += sold * t.price - (t.fees or ZERO) - avg * sold + cost -= avg * sold + qty -= sold + price = asset.manual_price if asset.manual_price is not None else asset.last_price + value = (qty * price) if price is not None else None + pnl = (value - cost) if value is not None else None + return { + "asset": asset, + "qty": qty, + "cost": cost.quantize(Decimal("0.01")), + "avg": (cost / qty) if qty else None, + "price": price, + "value": value.quantize(Decimal("0.01")) if value is not None else None, + "pnl": pnl.quantize(Decimal("0.01")) if pnl is not None else None, + "pnl_pct": float(pnl / cost * 100) if pnl is not None and cost else None, + "realized": realized.quantize(Decimal("0.01")), + "grams": (qty * (Decimal("31.1034768") if asset.unit == "oz" else 1) * (asset.purity or 1)) + if asset.kind == "gold" else None, + } + + +def holdings(db: Session, kind: str | None = None) -> list[dict]: + q = select(Asset).options(selectinload(Asset.trades)).order_by(Asset.kind, Asset.name) + if kind: + q = q.where(Asset.kind == kind) + return [position(a) for a in db.scalars(q)] + + +def totals(rows: list[dict]) -> dict: + out: dict[str, dict] = {} + for r in rows: + for k in (r["asset"].kind, "all"): + t = out.setdefault(k, {"cost": ZERO, "value": ZERO, "realized": ZERO, "missing_price": 0}) + if r["qty"] <= 0 and not r["realized"]: + continue + t["realized"] += r["realized"] + if r["qty"] <= 0: + continue + t["cost"] += r["cost"] + if r["value"] is None: + t["missing_price"] += 1 + t["value"] += r["cost"] # fall back to cost so totals stay meaningful + else: + t["value"] += r["value"] + for t in out.values(): + t["pnl"] = t["value"] - t["cost"] + t["pnl_pct"] = float(t["pnl"] / t["cost"] * 100) if t["cost"] else None + return out diff --git a/app/prices.py b/app/prices.py new file mode 100644 index 0000000..ca3e808 --- /dev/null +++ b/app/prices.py @@ -0,0 +1,120 @@ +"""Live prices: Yahoo Finance (stocks/ETFs, gold futures, FX) and CoinGecko (crypto). All values in EUR.""" +import logging +import os +from datetime import date, datetime +from decimal import Decimal + +import httpx +from sqlalchemy import select +from sqlalchemy.orm import Session + +from models import Asset, PortfolioSnapshot + +log = logging.getLogger("prices") +UA = {"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) finance-dashboard"} +TROY_OUNCE_G = Decimal("31.1034768") + + +def _client() -> httpx.Client: + return httpx.Client(timeout=15, headers=UA, follow_redirects=True) + + +def yahoo_quote(c: httpx.Client, symbol: str) -> tuple[Decimal, str]: + r = c.get(f"https://query1.finance.yahoo.com/v8/finance/chart/{symbol}", params={"interval": "1d", "range": "5d"}) + r.raise_for_status() + res = (r.json().get("chart") or {}).get("result") + if not res: + raise ValueError(f"Yahoo has no data for {symbol!r}") + meta = res[0]["meta"] + return Decimal(str(meta["regularMarketPrice"])), meta.get("currency") or "USD" + + +def fx_to_eur(c: httpx.Client, currency: str, cache: dict) -> Decimal: + if currency == "EUR": + return Decimal(1) + divisor = Decimal(1) + if currency in ("GBp", "GBX"): # London quotes in pence + currency, divisor = "GBP", Decimal(100) + if currency not in cache: + cache[currency], _ = yahoo_quote(c, f"{currency}EUR=X") + return cache[currency] / divisor + + +def gold_eur_per_gram(c: httpx.Client, symbol: str, cache: dict) -> Decimal: + key = f"metal:{symbol}" + if key not in cache: + usd_oz, cur = yahoo_quote(c, symbol or "GC=F") + cache[key] = usd_oz * fx_to_eur(c, cur, cache) / TROY_OUNCE_G + return cache[key] + + +def coingecko(c: httpx.Client, ids: list[str]) -> dict[str, Decimal]: + if not ids: + return {} + headers = {} + if key := os.getenv("COINGECKO_API_KEY"): + headers["x-cg-demo-api-key"] = key + r = c.get("https://api.coingecko.com/api/v3/simple/price", + params={"ids": ",".join(ids), "vs_currencies": "eur"}, headers=headers) + r.raise_for_status() + return {k: Decimal(str(v["eur"])) for k, v in r.json().items() if "eur" in v} + + +def unit_price(asset: Asset, c: httpx.Client, cache: dict, crypto: dict) -> Decimal: + if asset.kind == "crypto": + if not crypto: + raise ValueError("no CoinGecko prices available right now") + if asset.symbol.lower() not in crypto: + raise ValueError(f"CoinGecko id {asset.symbol!r} not found (use ids like 'bitcoin', 'ethereum')") + return crypto[asset.symbol.lower()] + if asset.kind == "gold": + per_gram = gold_eur_per_gram(c, asset.symbol, cache) + grams = TROY_OUNCE_G if asset.unit == "oz" else Decimal(1) + return per_gram * grams * (asset.purity or Decimal(1)) + price, cur = yahoo_quote(c, asset.symbol) + return price * fx_to_eur(c, cur, cache) + + +def refresh_prices(db: Session) -> list[str]: + assets = list(db.scalars(select(Asset))) + errors: list[str] = [] + cache: dict = {} + with _client() as c: + try: + crypto = coingecko(c, sorted({a.symbol.lower() for a in assets if a.kind == "crypto"})) + except Exception as e: # noqa: BLE001 + crypto = {} + errors.append(f"CoinGecko: {e}") + for a in assets: + if a.manual_price is not None: + continue + try: + a.last_price = unit_price(a, c, cache, crypto).quantize(Decimal("0.000001")) + a.last_price_at = datetime.now() + a.price_error = None + except Exception as e: # noqa: BLE001 + a.price_error = str(e)[:300] + errors.append(f"{a.name}: {e}") + db.commit() + snapshot(db) + for e in errors: + log.warning(e) + return errors + + +def snapshot(db: Session) -> None: + """Store today's value/cost per asset kind (one row per kind per day) for the history chart.""" + from portfolio import holdings, totals # local import to avoid a cycle + + today = date.today() + t = totals(holdings(db)) + for kind, v in t.items(): + if kind == "all": + continue + row = db.scalar(select(PortfolioSnapshot).where(PortfolioSnapshot.date == today, + PortfolioSnapshot.kind == kind)) + if row is None: + row = PortfolioSnapshot(date=today, kind=kind, value=0, cost=0) + db.add(row) + row.value, row.cost = v["value"], v["cost"] + db.commit() diff --git a/app/recurring.py b/app/recurring.py new file mode 100644 index 0000000..a40de8b --- /dev/null +++ b/app/recurring.py @@ -0,0 +1,161 @@ +"""Detect recurring payments (subscriptions, rent, insurance...) and flag missed ones.""" +from collections import Counter, defaultdict +from datetime import date, timedelta +from decimal import Decimal +from statistics import median + +from dateutil.relativedelta import relativedelta +from sqlalchemy import select +from sqlalchemy.orm import Session + +from categorize import normalize +from models import Category, Recurring, Transaction + +# name, (min gap, max gap) in days, min occurrences, grace days before "missed" +FREQUENCIES = { + "weekly": ((5, 9), 4, 3), + "monthly": ((25, 36), 3, 6), + "quarterly": ((80, 100), 3, 14), + "yearly": ((350, 380), 2, 21), +} + + +def step(freq: str) -> relativedelta: + return {"weekly": relativedelta(weeks=1), "monthly": relativedelta(months=1), + "quarterly": relativedelta(months=3), "yearly": relativedelta(years=1)}[freq] + + +def grace(freq: str) -> int: + return FREQUENCIES[freq][2] + + +def tx_key(tx: Transaction) -> str: + return normalize(tx.counterparty) or normalize(tx.description) + + +def _clusters(txs: list[Transaction], tol: float = 0.25) -> list[list[Transaction]]: + """Split one counterparty's payments into groups of similar amounts.""" + out: list[list[Transaction]] = [] + for tx in sorted(txs, key=lambda t: abs(t.amount)): + if out: + ref = median([abs(t.amount) for t in out[-1]]) + if ref and abs(abs(tx.amount) - ref) / ref <= Decimal(str(tol)): + out[-1].append(tx) + continue + out.append([tx]) + return out + + +def _classify(dates: list[date]) -> str | None: + gaps = [(b - a).days for a, b in zip(dates, dates[1:])] + if not gaps: + return None + med = median(gaps) + for name, ((lo, hi), min_n, _) in FREQUENCIES.items(): + if lo <= med <= hi and len(dates) >= min_n: + regular = sum(lo <= g <= hi for g in gaps) / len(gaps) + if regular >= 0.7: + return name + return None + + +def _excluded_category_ids(db: Session) -> set[int]: + return set(db.scalars(select(Category.id).where(Category.kind == "transfer"))) + + +def detect(db: Session, today: date | None = None) -> int: + """Scan the last ~13 months of outgoing payments and create/update Recurring rows.""" + today = today or date.today() + excluded = _excluded_category_ids(db) + txs = db.scalars(select(Transaction).where(Transaction.amount < 0, + Transaction.date >= today - timedelta(days=400))) + groups: dict[str, list[Transaction]] = defaultdict(list) + for tx in txs: + if tx.category_id in excluded: + continue + k = tx_key(tx) + if k: + groups[k].append(tx) + + existing = list(db.scalars(select(Recurring))) + created = 0 + for key, items in groups.items(): + for cl in _clusters(items): + # one payment per day is enough to establish the rhythm + by_day = {t.date: t for t in cl} + dates = sorted(by_day) + freq = _classify(dates) + if not freq: + continue + last = dates[-1] + if last + step(freq) * 3 + timedelta(days=grace(freq)) < today: + continue # stopped more than ~3 cycles ago: probably cancelled + amount = Decimal(median([t.amount for t in sorted(cl, key=lambda t: t.date)[-3:]])).quantize(Decimal("0.01")) + rec = next((r for r in existing if r.match == key and r.amount + and abs(abs(r.amount) - abs(amount)) / abs(r.amount) <= Decimal("0.3")), None) + if rec is None: + rec = Recurring(name=cl[-1].counterparty[:120] or key, match=key, source="detected", + status="detected", amount=amount) + db.add(rec) + existing.append(rec) + created += 1 + if rec.source == "detected": + rec.frequency = freq + rec.amount = amount + rec.occurrences = len(dates) + rec.last_date = max(last, rec.last_date or last) + rec.next_date = rec.last_date + step(rec.frequency) + rec.account_id = Counter(t.account_id for t in cl).most_common(1)[0][0] + cats = [t.category_id for t in cl if t.category_id] + rec.category_id = Counter(cats).most_common(1)[0][0] if cats else rec.category_id + db.flush() + for t in cl: + t.recurring_id = rec.id + db.flush() + refresh(db, today) + db.commit() + return created + + +def refresh(db: Session, today: date | None = None) -> None: + """Advance last/next dates for every recurring item using the newest matching payment.""" + today = today or date.today() + for rec in db.scalars(select(Recurring)): + since = rec.last_date or (rec.next_date - timedelta(days=grace(rec.frequency) * 2) if rec.next_date else None) + q = select(Transaction).where(Transaction.amount < 0 if rec.amount < 0 else Transaction.amount > 0) + if since: + q = q.where(Transaction.date > since - timedelta(days=0 if rec.last_date else 1)) + tol = Decimal(rec.tolerance_pct) / 100 + hits = [t for t in db.scalars(q.order_by(Transaction.date)) + if rec.match in tx_key(t) or rec.match in normalize(t.description)] + hits = [t for t in hits if abs(abs(t.amount) - abs(rec.amount)) <= abs(rec.amount) * max(tol, Decimal("0.5"))] + for t in hits: + t.recurring_id = rec.id + if rec.last_date is None or t.date > rec.last_date: + rec.last_date = t.date + rec.occurrences = (rec.occurrences or 0) + 1 + if rec.last_date: + nxt = rec.last_date + step(rec.frequency) + if rec.next_date is None or nxt > rec.next_date or rec.source == "detected": + rec.next_date = nxt + db.flush() + + +def state(rec: Recurring, today: date | None = None) -> str: + """ok | due-soon | missed | ignored""" + today = today or date.today() + if rec.status == "ignored": + return "ignored" + if not rec.next_date: + return "ok" + if today > rec.next_date + timedelta(days=grace(rec.frequency)): + return "missed" + if rec.next_date - today <= timedelta(days=7): + return "due-soon" + return "ok" + + +def monthly_equivalent(rec: Recurring) -> Decimal: + f = {"weekly": Decimal("52") / 12, "monthly": Decimal(1), "quarterly": Decimal(1) / 3, + "yearly": Decimal(1) / 12}[rec.frequency] + return (abs(rec.amount) * f).quantize(Decimal("0.01")) diff --git a/app/requirements.txt b/app/requirements.txt new file mode 100644 index 0000000..f70b2f0 --- /dev/null +++ b/app/requirements.txt @@ -0,0 +1,10 @@ +fastapi==0.115.6 +uvicorn[standard]==0.32.1 +jinja2==3.1.4 +python-multipart==0.0.20 +sqlalchemy==2.0.36 +psycopg[binary]==3.2.3 +httpx==0.28.1 +python-dateutil==2.9.0.post0 +apscheduler==3.11.0 +pyjwt[crypto]==2.10.1 diff --git a/app/services.py b/app/services.py new file mode 100644 index 0000000..d784984 --- /dev/null +++ b/app/services.py @@ -0,0 +1,180 @@ +"""Import pipeline, debt matching and reporting helpers.""" +import hashlib +import math +from collections import defaultdict +from datetime import date +from decimal import Decimal + +from dateutil.relativedelta import relativedelta +from sqlalchemy import select +from sqlalchemy.orm import Session + +from categorize import _compile, categorize +from importers import ParsedTx +from models import Account, Category, Debt, DebtPayment, Transaction + + +def own_ibans(db: Session) -> set[str]: + return {a.iban.replace(" ", "").upper() for a in db.scalars(select(Account)) if a.iban} + + +def ingest(db: Session, account: Account, parsed: list[ParsedTx], source: str = "csv", + balance: Decimal | None = None, balance_date: date | None = None) -> dict: + """Insert parsed transactions, skipping ones already present. + + The dedupe key is (account, date, amount, n-th occurrence that day) so the same transaction + imported from a CSV and from the bank API is only stored once. + """ + seen: dict[str, int] = defaultdict(int) + keyed = [] + for p in sorted(parsed, key=lambda p: p.date): + base = f"{account.id}|{p.date.isoformat()}|{p.amount:.2f}|{p.currency}" + h = hashlib.sha256(f"{base}|{seen[base]}".encode()).hexdigest() + seen[base] += 1 + keyed.append((h, p)) + + existing = set() + hashes = [h for h, _ in keyed] + for i in range(0, len(hashes), 500): + existing |= set(db.scalars(select(Transaction.hash).where(Transaction.hash.in_(hashes[i:i + 500])))) + + new: list[Transaction] = [] + for h, p in keyed: + if h in existing: + continue + tx = Transaction(account_id=account.id, date=p.date, amount=p.amount, currency=p.currency, + counterparty=p.counterparty[:200], counter_iban=(p.counter_iban or None), + description=p.description, raw_type=p.raw_type[:60], source=source, hash=h) + db.add(tx) + new.append(tx) + db.flush() + + categorize(db, new, own_ibans(db)) + matched = match_debt_payments(db, new) + + if balance is not None and (account.balance_date is None or (balance_date and balance_date >= account.balance_date)): + account.balance, account.balance_date = balance, balance_date + db.commit() + return {"inserted": len(new), "duplicates": len(keyed) - len(new), "debt_payments": matched} + + +# ---------------------------------------------------------------- debts + +def match_debt_payments(db: Session, txs: list[Transaction]) -> int: + debts = [d for d in db.scalars(select(Debt).where(Debt.closed.is_(False))) if d.match_pattern] + if not debts or not txs: + return 0 + debt_cat = db.scalar(select(Category).where(Category.name == "Debt")) + linked = set(db.scalars(select(DebtPayment.transaction_id).where(DebtPayment.transaction_id.is_not(None)))) + n = 0 + for tx in txs: + if tx.id in linked: + continue + for d in debts: + if tx.date < d.start_date: + continue + if (d.direction == "i_owe") != (tx.amount < 0): + continue + if not _compile(d.match_pattern).search(f"{tx.counterparty} {tx.description} {tx.counter_iban or ''}"): + continue + db.add(DebtPayment(debt_id=d.id, date=tx.date, amount=abs(tx.amount), transaction_id=tx.id, + notes="auto-matched")) + tx.debt_id = d.id + if debt_cat and not tx.category_locked and d.direction == "i_owe": + tx.category_id = debt_cat.id + n += 1 + break + db.flush() + return n + + +def _due_dates(d: Debt): + first = d.start_date + relativedelta(months=1) + if d.due_day: + first = first.replace(day=1) + relativedelta(day=d.due_day) # clamps to month end + i = 0 + while True: + dd = first + relativedelta(months=i) + if d.due_day: + dd = dd.replace(day=1) + relativedelta(day=d.due_day) + yield dd + i += 1 + + +def debt_status(d: Debt, today: date | None = None) -> dict: + today = today or date.today() + paid = sum((p.amount for p in d.payments), Decimal("0")) + remaining = max(d.principal - paid, Decimal("0")) + out = {"paid": paid, "remaining": remaining, "pct": float(paid / d.principal * 100) if d.principal else 100.0, + "expected": None, "diff": None, "missed": 0, "next_due": None, "payoff": None, "status": "open", + "last_payment": d.payments[-1].date if d.payments else None} + if remaining <= 0 or d.closed: + out["status"] = "paid off" + return out + if d.monthly_payment and d.monthly_payment > 0: + n_due = 0 + for dd in _due_dates(d): + if dd > today: + out["next_due"] = dd + break + n_due += 1 + if n_due * d.monthly_payment >= d.principal: + break + expected = min(n_due * d.monthly_payment, d.principal) + diff = paid - expected + out["expected"], out["diff"] = expected, diff + months_left = math.ceil(remaining / d.monthly_payment) + out["payoff"] = today + relativedelta(months=int(months_left)) + half = d.monthly_payment / 2 + if diff <= -half: + out["status"] = "behind" + out["missed"] = math.ceil(-diff / d.monthly_payment) + elif diff >= half: + out["status"] = "ahead" + else: + out["status"] = "on track" + return out + + +# ---------------------------------------------------------------- reporting + +def _spend_rows(db: Session, start: date, end: date, account_id: int | None = None): + q = (select(Transaction, Category, Account) + .join(Account, Transaction.account_id == Account.id) + .outerjoin(Category, Transaction.category_id == Category.id) + .where(Transaction.date >= start, Transaction.date < end, Transaction.currency == "EUR")) + if account_id: + q = q.where(Transaction.account_id == account_id) + for tx, cat, acc in db.execute(q): + if cat is not None and cat.kind == "transfer": + continue + share = Decimal(acc.share_pct) / 100 + yield tx, cat, tx.amount * share + + +def monthly_totals(db: Session, months: int = 12, account_id: int | None = None) -> list[dict]: + first = date.today().replace(day=1) - relativedelta(months=months - 1) + buckets = {(first + relativedelta(months=i)).strftime("%Y-%m"): {"income": Decimal(0), "expense": Decimal(0)} + for i in range(months)} + for tx, cat, amt in _spend_rows(db, first, date.today() + relativedelta(days=1), account_id): + b = buckets.get(tx.date.strftime("%Y-%m")) + if b is None: + continue + if amt >= 0: + b["income"] += amt + else: + b["expense"] += -amt + return [{"month": k, **v} for k, v in buckets.items()] + + +def category_totals(db: Session, start: date, end: date, account_id: int | None = None) -> list[dict]: + totals: dict[str, dict] = {} + for tx, cat, amt in _spend_rows(db, start, end, account_id): + if amt >= 0: + continue + name = cat.name if cat else "Uncategorised" + t = totals.setdefault(name, {"name": name, "color": cat.color if cat else "#cccccc", + "total": Decimal(0), "count": 0, "id": cat.id if cat else None}) + t["total"] += -amt + t["count"] += 1 + return sorted(totals.values(), key=lambda x: x["total"], reverse=True) diff --git a/app/static/app.js b/app/static/app.js new file mode 100644 index 0000000..dd384d9 --- /dev/null +++ b/app/static/app.js @@ -0,0 +1,357 @@ +/* Finance UI: theme, nav drawer, inline edits, live numbers, charts. No framework needed. */ +"use strict"; + +// ------------------------------------------------------------------ helpers +const $ = (sel, root = document) => root.querySelector(sel); +const $$ = (sel, root = document) => Array.from(root.querySelectorAll(sel)); +const css = (name) => getComputedStyle(document.documentElement).getPropertyValue(name).trim(); +const nf = (d) => new Intl.NumberFormat("nl-NL", { minimumFractionDigits: d, maximumFractionDigits: d }); +const eur = (v, d = 0) => (v < 0 ? "-" : "") + "€ " + nf(d).format(Math.abs(v)); +const eurCompact = (v) => { + const a = Math.abs(v); + if (a >= 1e6) return (v < 0 ? "-" : "") + "€ " + nf(1).format(a / 1e6) + "M"; + if (a >= 1e4) return (v < 0 ? "-" : "") + "€ " + nf(a >= 1e5 ? 0 : 1).format(a / 1e3) + "k"; + return eur(v); +}; +const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; +const monthLabel = (ym, withYear) => { const [y, m] = ym.split("-"); return MONTHS[+m - 1] + (withYear ? " " + y : ""); }; +const dateLabel = (iso) => { const d = new Date(iso); return d.getDate() + " " + MONTHS[d.getMonth()] + " " + d.getFullYear(); }; + +// ------------------------------------------------------------------ theme +function currentTheme() { try { return localStorage.getItem("theme") || "auto"; } catch (e) { return "auto"; } } +function markTheme() { $$("[data-theme-set]").forEach((b) => b.classList.toggle("on", b.dataset.themeSet === currentTheme())); } +document.addEventListener("click", (e) => { + const b = e.target.closest("[data-theme-set]"); + if (!b) return; + const t = b.dataset.themeSet; + try { t === "auto" ? localStorage.removeItem("theme") : localStorage.setItem("theme", t); } catch (err) {} + if (t === "auto") delete document.documentElement.dataset.theme; else document.documentElement.dataset.theme = t; + markTheme(); + redrawCharts(); // pick up the new colours without a reload +}); + +// ------------------------------------------------------------------ mobile nav drawer +document.addEventListener("click", (e) => { + if (e.target.closest("[data-nav-toggle]")) document.body.classList.toggle("nav-open"); + else if (e.target.closest("[data-nav-close]")) document.body.classList.remove("nav-open"); +}); +document.addEventListener("keydown", (e) => e.key === "Escape" && document.body.classList.remove("nav-open")); + +// ------------------------------------------------------------------ inline edits & small UX +document.addEventListener("change", async (e) => { + const el = e.target; + if (el.matches("select[data-tx]")) { + const body = new FormData(); + body.append("category_id", el.value); + const r = await fetch(`/transactions/${el.dataset.tx}/category`, { method: "POST", body }); + el.style.boxShadow = `0 0 0 3px ${r.ok ? css("--good") : css("--bad")}55`; + const dot = el.closest("td")?.querySelector(".dot"); + if (dot && el.selectedOptions[0]) dot.style.background = el.selectedOptions[0].dataset.color || "transparent"; + setTimeout(() => (el.style.boxShadow = ""), 900); + setTimeout(pollLive, 300); + } + if (el.matches("input[data-notes]")) { + const body = new FormData(); + body.append("notes", el.value); + await fetch(`/transactions/${el.dataset.notes}/notes`, { method: "POST", body }); + } + if (el.matches("[data-autosubmit]")) el.form.submit(); +}); +document.addEventListener("submit", (e) => { + const msg = e.target.dataset.confirm; + if (msg && !confirm(msg)) e.preventDefault(); +}); + +// ------------------------------------------------------------------ live numbers +// Elements with data-live="key" refresh from /api/live. data-fmt: eur | eur0 | eurs | eur0s | pct ; data-color = good/bad by sign. +const LIVE_INTERVAL = 30000; +function fmt(v, kind) { + if (v === null || v === undefined || Number.isNaN(v)) return "–"; + if (kind === "pct") return (v < 0 ? "-" : "+") + nf(1).format(Math.abs(v)) + "%"; + const sign = v < 0 ? "-" : kind.endsWith("s") && v > 0 ? "+" : ""; + return `${sign}€ ${nf(kind.startsWith("eur0") ? 0 : 2).format(Math.abs(v))}`; +} +function animate(el, from, to, kind) { + const t0 = performance.now(), dur = 700; + const step = (now) => { + const p = Math.min(1, (now - t0) / dur), k = 1 - Math.pow(1 - p, 3); + el.textContent = fmt(from + (to - from) * k, kind); + if (p < 1) requestAnimationFrame(step); + }; + requestAnimationFrame(step); +} +function applyLive(values) { + $$("[data-live]").forEach((el) => { + const key = el.dataset.live; + if (!(key in values)) return; + const to = values[key], kind = el.dataset.fmt || "eur"; + const from = el.dataset.v !== undefined && el.dataset.v !== "" ? parseFloat(el.dataset.v) : null; + el.dataset.v = to ?? ""; + if (el.hasAttribute("data-color") && to !== null) { el.classList.toggle("good", to >= 0); el.classList.toggle("bad", to < 0); } + if (from === null) { el.textContent = fmt(to, kind); return; } + if (to === null || Math.abs(to - from) < 0.005) return; + animate(el, from, to, kind); + el.classList.remove("flash-up", "flash-down"); + void el.offsetWidth; + el.classList.add(to > from ? "flash-up" : "flash-down"); + }); +} +let liveVersion = null; +async function pollLive() { + if (!$("[data-live]") || document.hidden) return; + const qs = new URLSearchParams(location.search), params = new URLSearchParams(); + ["account", "month"].forEach((k) => qs.get(k) && params.set(k, qs.get(k))); + try { + const r = await fetch("/api/live?" + params, { headers: { Accept: "application/json" } }); + if (!r.ok) return; + const data = await r.json(); + applyLive(data.values); + const changed = liveVersion && data.version.split(":")[0] !== liveVersion.split(":")[0]; + $$(".live-status").forEach((s) => (s.innerHTML = changed ? 'New data · reload' : "Live · " + data.at)); + liveVersion = data.version; + } catch (e) { /* offline / session expired: keep last numbers */ } +} + +// Refresh prices in place +document.addEventListener("submit", async (e) => { + const form = e.target; + if (!form.matches("[data-ajax-refresh]")) return; + e.preventDefault(); + const btn = $("button", form), label = btn.innerHTML; + btn.disabled = true; + btn.lastChild.textContent = " Refreshing…"; + try { + const r = await (await fetch("/api/prices/refresh", { method: "POST" })).json(); + await pollLive(); + btn.lastChild.textContent = r.ok ? " Updated" : " Some failed"; + if (!r.ok) btn.title = r.errors.join("\n"); + } catch (err) { btn.lastChild.textContent = " Failed"; } + setTimeout(() => { btn.disabled = false; btn.innerHTML = label; }, 2200); +}); + +// ------------------------------------------------------------------ charts +const PALETTE = ["#6366f1", "#22c55e", "#f59e0b", "#ec4899", "#06b6d4", "#8b5cf6", "#ef4444", "#84cc16", "#14b8a6", "#f97316"]; +const charts = []; + +const solid = (ds, i) => { + const c = Array.isArray(ds.backgroundColor) ? ds.backgroundColor[i] : ds.borderColor || ds.backgroundColor; + return typeof c === "string" ? c : ds.borderColor; +}; +function baseOptions() { + return { + responsive: true, maintainAspectRatio: false, animation: { duration: 500 }, + interaction: { mode: "index", intersect: false }, + plugins: { + legend: { display: false }, + tooltip: { + backgroundColor: css("--panel"), titleColor: css("--text"), bodyColor: css("--text"), footerColor: css("--muted"), + borderColor: css("--line"), borderWidth: 1, padding: 12, cornerRadius: 10, boxPadding: 5, usePointStyle: true, + titleFont: { weight: "600" }, footerFont: { weight: "500" }, + callbacks: {}, + }, + }, + scales: { + x: { grid: { display: false }, border: { display: false }, ticks: { color: css("--muted"), maxRotation: 0, autoSkipPadding: 14 } }, + y: { grid: { color: css("--line"), drawTicks: false }, border: { display: false }, + ticks: { color: css("--muted"), padding: 8, maxTicksLimit: 6, callback: (v) => eurCompact(v) } }, + }, + }; +} + +// Text in the middle of a doughnut; follows the hovered slice. +const centerText = { + id: "centerText", + afterDraw(chart, _args, opts) { + if (!opts || !opts.label) return; + const { ctx, chartArea: a } = chart; + const active = chart.getActiveElements()[0]; + const ds = chart.data.datasets[0]; + const total = ds.data.reduce((s, v, i) => s + (chart.getDataVisibility(i) ? v : 0), 0); + let top = opts.label, big = eur(total), small = ""; + if (active) { + const v = ds.data[active.index]; + top = chart.data.labels[active.index]; + big = eur(v); + small = total ? nf(1).format((v / total) * 100) + "%" : ""; + } + const x = (a.left + a.right) / 2, y = (a.top + a.bottom) / 2; + ctx.save(); + ctx.textAlign = "center"; ctx.textBaseline = "middle"; + ctx.fillStyle = css("--muted"); ctx.font = `500 12px ${getComputedStyle(document.body).fontFamily}`; + ctx.fillText(top.length > 18 ? top.slice(0, 17) + "…" : top, x, y - 18); + ctx.fillStyle = css("--text"); ctx.font = `700 19px ${getComputedStyle(document.body).fontFamily}`; + ctx.fillText(big, x, y + 3); + if (small) { ctx.fillStyle = css("--muted"); ctx.font = `600 12px ${getComputedStyle(document.body).fontFamily}`; ctx.fillText(small, x, y + 23); } + ctx.restore(); + }, +}; + +// Vertical hover line for line charts +const crosshair = { + id: "crosshair", + afterDatasetsDraw(chart) { + const act = chart.tooltip && chart.tooltip.getActiveElements(); + if (!act || !act.length || chart.config.type !== "line") return; + const x = act[0].element.x, { top, bottom } = chart.chartArea, ctx = chart.ctx; + ctx.save(); ctx.strokeStyle = css("--muted"); ctx.globalAlpha = 0.35; ctx.setLineDash([4, 4]); + ctx.beginPath(); ctx.moveTo(x, top); ctx.lineTo(x, bottom); ctx.stroke(); ctx.restore(); + }, +}; + +function gradient(chart, color) { + const { ctx, chartArea } = chart; + if (!chartArea) return color + "33"; + const g = ctx.createLinearGradient(0, chartArea.top, 0, chartArea.bottom); + g.addColorStop(0, color + "55"); g.addColorStop(1, color + "00"); + return g; +} + +const builders = { + // Income/expense bars + net line; click a month to drill in. + months(canvas, d) { + const good = css("--good"), bad = css("--bad"), accent = css("--accent"); + const net = d.income.map((v, i) => v - d.expense[i]); + const o = baseOptions(); + o.scales.x.ticks.callback = function (v) { const l = this.getLabelForValue(v); return monthLabel(l, l.endsWith("-01")); }; + o.plugins.tooltip.callbacks = { + labelColor: (c) => ({ borderColor: solid(c.dataset, c.dataIndex), backgroundColor: solid(c.dataset, c.dataIndex), borderRadius: 3 }), + title: (items) => monthLabel(items[0].label, true), + label: (c) => ` ${c.dataset.label}: ${eur(c.parsed.y)}`, + footer: (items) => { const i = items[0].dataIndex, r = d.income[i] ? (net[i] / d.income[i]) * 100 : null; + return r === null ? "" : `Savings rate ${nf(0).format(r)}%`; }, + }; + o.plugins.legend = { display: true, position: "bottom", labels: { usePointStyle: true, pointStyle: "rectRounded", boxWidth: 10, boxHeight: 10, color: css("--muted"), padding: 16 } }; + o.onClick = (_e, els) => { if (els.length && canvas.dataset.link) location.href = canvas.dataset.link.replace("{label}", d.labels[els[0].index]); }; + o.onHover = (e, els) => (e.native.target.style.cursor = els.length ? "pointer" : "default"); + const dim = (c) => d.labels.map((l) => (l === d.current ? c : c + "99")); + return { + type: "bar", + data: { labels: d.labels, datasets: [ + { label: "Income", data: d.income, backgroundColor: dim(good), borderRadius: 6, maxBarThickness: 22, order: 2 }, + { label: "Expenses", data: d.expense, backgroundColor: dim(bad), borderRadius: 6, maxBarThickness: 22, order: 2 }, + { label: "Net", data: net, type: "line", borderColor: accent, backgroundColor: accent, borderWidth: 2, tension: 0.35, + pointRadius: 3, pointHoverRadius: 5, pointBackgroundColor: css("--panel"), order: 1 }, + ] }, + options: o, + }; + }, + + // Doughnut with centre total, custom clickable legend, click-through links. + donut(canvas, d) { + const o = baseOptions(); + delete o.scales; o.interaction = { mode: "nearest", intersect: true }; + o.cutout = "72%"; o.layout = { padding: 6 }; + o.plugins.centerText = { label: canvas.dataset.center === "spent" ? "Total spent" : "Total" }; + o.plugins.tooltip.enabled = false; // the centre shows the hovered slice + o.onClick = (_e, els) => { if (els.length && d.links && d.links[els[0].index]) location.href = d.links[els[0].index]; }; + o.onHover = (e, els) => (e.native.target.style.cursor = els.length && d.links ? "pointer" : "default"); + const colors = d.colors || d.labels.map((_, i) => PALETTE[i % PALETTE.length]); + return { + type: "doughnut", + data: { labels: d.labels, datasets: [{ data: d.data, backgroundColor: colors, borderColor: css("--panel"), borderWidth: 3, hoverOffset: 8, borderRadius: 4 }] }, + options: o, plugins: [centerText], + }; + }, + + // Value vs paid over time; gradient fill, range filter, P/L in tooltip. + history(canvas, d) { + const accent = css("--accent"), muted = css("--muted"); + const o = baseOptions(); + o.scales.x.ticks.maxTicksLimit = 7; + o.scales.x.ticks.callback = function (v) { const l = this.getLabelForValue(v); const dt = new Date(l); return dt.getDate() + " " + MONTHS[dt.getMonth()]; }; + o.plugins.tooltip.callbacks = { + labelColor: (c) => ({ borderColor: c.dataset.borderColor, backgroundColor: c.dataset.borderColor, borderRadius: 3 }), + title: (items) => dateLabel(items[0].label), + label: (c) => ` ${c.dataset.label}: ${eur(c.parsed.y)}`, + footer: (items) => { + const v = items.find((i) => i.datasetIndex === 0), c = items.find((i) => i.datasetIndex === 1); + if (!v || !c) return ""; + const pl = v.parsed.y - c.parsed.y, pct = c.parsed.y ? (pl / c.parsed.y) * 100 : 0; + return `P/L ${pl >= 0 ? "+" : ""}${eur(pl)} (${pct >= 0 ? "+" : ""}${nf(1).format(pct)}%)`; + }, + }; + o.plugins.legend = { display: true, position: "bottom", labels: { usePointStyle: true, pointStyle: "line", color: muted, padding: 16 } }; + canvas._full = d; + return { + type: "line", + data: { labels: d.labels, datasets: [ + { label: "Value", data: d.value, borderColor: accent, borderWidth: 2.5, tension: 0.3, pointRadius: 0, pointHoverRadius: 5, + pointHoverBackgroundColor: accent, pointHoverBorderColor: css("--panel"), pointHoverBorderWidth: 2, + fill: true, backgroundColor: (ctx) => gradient(ctx.chart, accent) }, + { label: "Paid", data: d.cost, borderColor: muted, borderWidth: 1.5, borderDash: [5, 5], pointRadius: 0, pointHoverRadius: 0, stepped: true, fill: false }, + ] }, + options: o, plugins: [crosshair], + }; + }, +}; + +function buildLegend(chart, id) { + const box = document.getElementById(id); + if (!box) return; + box.innerHTML = ""; + const ds = chart.data.datasets[0]; + const total = ds.data.reduce((a, b) => a + b, 0); + chart.data.labels.forEach((label, i) => { + const b = document.createElement("button"); + b.type = "button"; + b.innerHTML = `${label}${eur(ds.data[i])} · ${nf(0).format((ds.data[i] / total) * 100)}%`; + b.title = "Click to hide/show"; + b.onclick = () => { chart.toggleDataVisibility(i); b.classList.toggle("off", !chart.getDataVisibility(i)); chart.update(); }; + b.onmouseenter = () => { chart.setActiveElements([{ datasetIndex: 0, index: i }]); chart.update("none"); }; + b.onmouseleave = () => { chart.setActiveElements([]); chart.update("none"); }; + box.appendChild(b); + }); +} + +function applyRange(canvas, days) { + const chart = Chart.getChart(canvas), d = canvas._full; + if (!chart || !d) return; + let from = 0; + if (days > 0 && d.labels.length) { + const cutoff = new Date(d.labels[d.labels.length - 1]); + cutoff.setDate(cutoff.getDate() - days); + from = d.labels.findIndex((l) => new Date(l) >= cutoff); + if (from < 0) from = 0; + } + chart.data.labels = d.labels.slice(from); + chart.data.datasets[0].data = d.value.slice(from); + chart.data.datasets[1].data = d.cost.slice(from); + chart.update(); +} +document.addEventListener("click", (e) => { + const b = e.target.closest("[data-range-for] button"); + if (!b) return; + const seg = b.parentElement; + $$("button", seg).forEach((x) => x.classList.toggle("on", x === b)); + const canvas = document.getElementById(seg.dataset.rangeFor); + if (canvas) { canvas._days = +b.dataset.days; applyRange(canvas, canvas._days); } +}); + +function drawCharts() { + if (!window.Chart) return; + Chart.defaults.font.family = getComputedStyle(document.body).fontFamily; + Chart.defaults.color = css("--muted"); + $$("canvas[data-chart]").forEach((canvas) => { + const build = builders[canvas.dataset.chart]; + if (!build) return; + const chart = new Chart(canvas, build(canvas, JSON.parse(canvas.dataset.json))); + charts.push(chart); + if (canvas.dataset.legend) buildLegend(chart, canvas.dataset.legend); + if (canvas.dataset.chart === "history") { + const seg = $(`[data-range-for="${canvas.id}"] .on`); + applyRange(canvas, canvas._days ?? (seg ? +seg.dataset.days : 0)); + } + }); +} +function redrawCharts() { while (charts.length) charts.pop().destroy(); drawCharts(); } + +// ------------------------------------------------------------------ boot +window.addEventListener("DOMContentLoaded", () => { + markTheme(); + drawCharts(); + pollLive(); + setInterval(pollLive, LIVE_INTERVAL); + document.addEventListener("visibilitychange", () => !document.hidden && pollLive()); + // follow OS theme changes live when on "auto" + window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change", () => currentTheme() === "auto" && redrawCharts()); +}); diff --git a/app/static/style.css b/app/static/style.css new file mode 100644 index 0000000..16706ab --- /dev/null +++ b/app/static/style.css @@ -0,0 +1,236 @@ +/* ============================================================ theme */ +:root { + --bg: #f4f5f9; --panel: #ffffff; --panel-2: #f8f9fc; --text: #161b26; --muted: #6b7385; --line: #e6e8ef; + --accent: #4f46e5; --accent-2: #6366f1; --accent-soft: #eef0ff; --on-accent: #fff; + --good: #15803d; --good-soft: #e8f6ee; --bad: #c2312f; --bad-soft: #fdecec; --warn: #b45309; --warn-soft: #fdf3e3; + --chip: #eef0f6; --radius: 14px; --radius-sm: 9px; + --shadow: 0 1px 2px rgba(16,24,40,.04), 0 4px 16px rgba(16,24,40,.04); + --shadow-lg: 0 10px 40px rgba(16,24,40,.12); + --nav-w: 248px; + color-scheme: light; +} +:root[data-theme=dark] { + --bg: #0c0f16; --panel: #141923; --panel-2: #10141c; --text: #e7e9f0; --muted: #8e97aa; --line: #232a37; + --accent: #818cf8; --accent-2: #a5b4fc; --accent-soft: #1d2140; --on-accent: #0c0f16; + --good: #4ade80; --good-soft: #10291c; --bad: #f87171; --bad-soft: #2f1517; --warn: #fbbf24; --warn-soft: #2d230c; + --chip: #1b2130; --shadow: 0 1px 2px rgba(0,0,0,.3); --shadow-lg: 0 10px 40px rgba(0,0,0,.5); + color-scheme: dark; +} +@media (prefers-color-scheme: dark) { + :root:not([data-theme=light]) { + --bg: #0c0f16; --panel: #141923; --panel-2: #10141c; --text: #e7e9f0; --muted: #8e97aa; --line: #232a37; + --accent: #818cf8; --accent-2: #a5b4fc; --accent-soft: #1d2140; --on-accent: #0c0f16; + --good: #4ade80; --good-soft: #10291c; --bad: #f87171; --bad-soft: #2f1517; --warn: #fbbf24; --warn-soft: #2d230c; + --chip: #1b2130; --shadow: 0 1px 2px rgba(0,0,0,.3); --shadow-lg: 0 10px 40px rgba(0,0,0,.5); + color-scheme: dark; + } +} + +/* ============================================================ base */ +* { box-sizing: border-box; } +html { font-size: 15px; -webkit-text-size-adjust: 100%; } +body { margin: 0; font-family: "Inter", system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; background: var(--bg); + color: var(--text); min-height: 100vh; font-feature-settings: "cv11", "ss01"; } +a { color: var(--accent); text-decoration: none; } +a:hover { text-decoration: underline; } +h1 { font-size: 1.55rem; margin: 0; letter-spacing: -.02em; } +h2 { font-size: 1rem; margin: 0 0 .9rem; letter-spacing: -.01em; display: flex; align-items: center; gap: .5rem; } +h2 .ico { color: var(--muted); } +code { font-size: .85em; background: var(--chip); padding: .1rem .35rem; border-radius: 5px; } +.ico { width: 18px; height: 18px; flex: none; stroke: currentColor; fill: none; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; vertical-align: -3px; } +.ico.sm { width: 15px; height: 15px; vertical-align: -2px; } +.ico.lg { width: 22px; height: 22px; } + +/* ============================================================ sidebar */ +.layout { display: grid; grid-template-columns: var(--nav-w) 1fr; min-height: 100vh; + background: linear-gradient(to right, var(--panel) calc(var(--nav-w) - 1px), var(--line) 0 var(--nav-w), transparent 0); } +@media (max-width: 860px) { .layout { background: none; } } +nav.side { background: var(--panel); border-right: 1px solid var(--line); padding: 1.1rem .85rem; position: sticky; top: 0; + height: 100vh; display: flex; flex-direction: column; gap: 2px; overflow-y: auto; z-index: 40; } +.brand { display: flex; align-items: center; gap: .65rem; padding: .2rem .55rem 1.1rem; font-weight: 700; font-size: 1.08rem; letter-spacing: -.02em; } +.brand .logo { width: 34px; height: 34px; border-radius: 10px; display: grid; place-items: center; color: #fff; + background: linear-gradient(135deg, #6366f1, #22c55e); box-shadow: 0 4px 14px rgba(99,102,241,.35); } +.nav-section { font-size: .7rem; font-weight: 700; text-transform: uppercase; letter-spacing: .08em; color: var(--muted); + padding: 1rem .7rem .4rem; } +.nav-link { position: relative; display: flex; align-items: center; gap: .75rem; padding: .55rem .7rem; border-radius: var(--radius-sm); + color: var(--text); font-weight: 500; transition: background .15s, color .15s; } +.nav-link .ico { color: var(--muted); transition: color .15s, transform .15s; } +.nav-link:hover { background: var(--chip); text-decoration: none; } +.nav-link:hover .ico { color: var(--text); transform: translateX(1px); } +.nav-link.active { background: var(--accent-soft); color: var(--accent); font-weight: 600; } +.nav-link.active .ico { color: var(--accent); } +.nav-link.active::before { content: ""; position: absolute; left: -.85rem; top: 22%; bottom: 22%; width: 3px; border-radius: 0 3px 3px 0; background: var(--accent); } +.nav-count { margin-left: auto; min-width: 1.35rem; height: 1.35rem; padding: 0 .4rem; border-radius: 99px; font-size: .72rem; font-weight: 700; + display: grid; place-items: center; background: var(--bad); color: #fff; } +.nav-foot { margin-top: auto; padding-top: 1rem; display: flex; flex-direction: column; gap: .6rem; } +.user-chip { display: flex; align-items: center; gap: .6rem; padding: .55rem .6rem; border-radius: var(--radius-sm); background: var(--panel-2); border: 1px solid var(--line); } +.avatar { width: 30px; height: 30px; border-radius: 50%; display: grid; place-items: center; font-weight: 700; font-size: .85rem; + background: var(--accent-soft); color: var(--accent); flex: none; } +.user-chip .who { font-size: .85rem; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.user-chip a { margin-left: auto; color: var(--muted); display: grid; place-items: center; padding: .25rem; border-radius: 6px; } +.user-chip a:hover { background: var(--chip); color: var(--text); } + +.theme-toggle { display: grid; grid-template-columns: repeat(3, 1fr); gap: 2px; background: var(--panel-2); border: 1px solid var(--line); border-radius: var(--radius-sm); padding: 3px; } +.theme-toggle button { background: none; border: 0; color: var(--muted); padding: .35rem; border-radius: 7px; cursor: pointer; display: grid; place-items: center; } +.theme-toggle button:hover { color: var(--text); } +.theme-toggle button.on { background: var(--panel); color: var(--text); box-shadow: var(--shadow); } + +/* mobile: top bar + bottom tabs + drawer */ +.topbar, .tabbar, .scrim { display: none; } +@media (max-width: 860px) { + .layout { grid-template-columns: 1fr; } + nav.side { position: fixed; left: 0; top: 0; bottom: 0; width: 280px; transform: translateX(-102%); transition: transform .25s ease; box-shadow: var(--shadow-lg); } + body.nav-open nav.side { transform: none; } + .scrim { display: block; position: fixed; inset: 0; background: rgba(0,0,0,.35); opacity: 0; pointer-events: none; transition: opacity .2s; z-index: 30; } + body.nav-open .scrim { opacity: 1; pointer-events: auto; } + .topbar { display: flex; align-items: center; gap: .6rem; position: sticky; top: 0; z-index: 20; padding: .6rem .9rem; + background: color-mix(in srgb, var(--panel) 88%, transparent); backdrop-filter: blur(10px); border-bottom: 1px solid var(--line); } + .topbar .brand { padding: 0; font-size: 1rem; } + .topbar .brand .logo { width: 28px; height: 28px; border-radius: 8px; } + .icon-btn { background: none; border: 0; color: var(--text); padding: .4rem; border-radius: 8px; cursor: pointer; display: grid; place-items: center; } + .icon-btn:hover { background: var(--chip); } + .tabbar { display: grid; grid-template-columns: repeat(5, 1fr); position: fixed; left: 0; right: 0; bottom: 0; z-index: 20; + background: color-mix(in srgb, var(--panel) 92%, transparent); backdrop-filter: blur(10px); border-top: 1px solid var(--line); + padding: .35rem .25rem calc(.35rem + env(safe-area-inset-bottom)); } + .tabbar a { display: flex; flex-direction: column; align-items: center; gap: 3px; font-size: .68rem; color: var(--muted); padding: .3rem 0; border-radius: 8px; position: relative; } + .tabbar a:hover { text-decoration: none; } + .tabbar a.active { color: var(--accent); font-weight: 600; } + .tabbar a .dot-count { position: absolute; top: 0; right: calc(50% - 18px); width: 8px; height: 8px; border-radius: 50%; background: var(--bad); } + main { padding-bottom: 5.5rem !important; } +} + +/* ============================================================ page */ +main { padding: 1.6rem 2.2rem 3rem; max-width: 1440px; width: 100%; min-width: 0; } +.page-head { display: flex; align-items: flex-end; justify-content: space-between; gap: 1rem; flex-wrap: wrap; margin-bottom: 1.3rem; } +.page-head .sub { color: var(--muted); font-size: .9rem; margin-top: .25rem; } +.page-head .actions { display: flex; gap: .5rem; align-items: center; flex-wrap: wrap; } +@media (max-width: 860px) { main { padding: 1rem .8rem; } h1 { font-size: 1.3rem; } } + +.grid { display: grid; gap: 1rem; } +.cols-4 { grid-template-columns: repeat(4, minmax(0, 1fr)); } +.cols-3 { grid-template-columns: repeat(3, minmax(0, 1fr)); } +.cols-2 { grid-template-columns: repeat(2, minmax(0, 1fr)); } +.span-2 { grid-column: span 2; } +@media (max-width: 1150px) { .cols-4 { grid-template-columns: repeat(2, minmax(0, 1fr)); } .cols-3 { grid-template-columns: 1fr 1fr; } } +@media (max-width: 860px) { .cols-3, .cols-2 { grid-template-columns: 1fr; } .span-2 { grid-column: auto; } } +@media (max-width: 480px) { .cols-4 { grid-template-columns: 1fr 1fr; gap: .6rem; } } +.card { background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius); padding: 1.1rem 1.2rem; box-shadow: var(--shadow); min-width: 0; } +.card-head { display: flex; align-items: center; justify-content: space-between; gap: .75rem; margin-bottom: .9rem; flex-wrap: wrap; } +.card-head h2 { margin: 0; } +.mb { margin-bottom: 1rem; } +.row { display: flex; gap: .6rem; align-items: center; flex-wrap: wrap; } +.spread { justify-content: space-between; } +.muted { color: var(--muted); } +.small { font-size: .85rem; } +.right { text-align: right; } +.good { color: var(--good); } .bad { color: var(--bad); } .warn { color: var(--warn); } + +/* KPI tiles */ +.kpi { position: relative; overflow: hidden; } +.kpi .label { color: var(--muted); font-size: .82rem; font-weight: 500; display: flex; align-items: center; gap: .5rem; } +.kpi .value { font-size: 1.65rem; font-weight: 700; margin: .35rem 0 .2rem; letter-spacing: -.02em; font-variant-numeric: tabular-nums; } +.kpi .sub { font-size: .82rem; color: var(--muted); line-height: 1.45; } +.kpi .kpi-ico { position: absolute; top: 1rem; right: 1rem; width: 38px; height: 38px; border-radius: 11px; display: grid; place-items: center; } +.tint-accent { background: var(--accent-soft); color: var(--accent); } +.tint-good { background: var(--good-soft); color: var(--good); } +.tint-bad { background: var(--bad-soft); color: var(--bad); } +.tint-warn { background: var(--warn-soft); color: var(--warn); } +.delta { display: inline-flex; align-items: center; gap: 2px; font-weight: 600; padding: .05rem .4rem; border-radius: 6px; font-size: .78rem; } +.delta.good { background: var(--good-soft); } .delta.bad { background: var(--bad-soft); } +@media (max-width: 480px) { .kpi .value { font-size: 1.2rem; } .kpi .kpi-ico { width: 30px; height: 30px; top: .8rem; right: .8rem; } .kpi .kpi-ico .ico { width: 15px; height: 15px; } } + +/* tables */ +.table-wrap { overflow-x: auto; -webkit-overflow-scrolling: touch; margin: 0 -1.2rem; padding: 0 1.2rem; } +table { width: 100%; border-collapse: collapse; font-size: .9rem; } +th, td { padding: .6rem .6rem; border-bottom: 1px solid var(--line); text-align: left; vertical-align: middle; } +th { font-size: .72rem; text-transform: uppercase; letter-spacing: .05em; color: var(--muted); font-weight: 600; white-space: nowrap; background: var(--panel-2); } +thead th:first-child { border-top-left-radius: 8px; } thead th:last-child { border-top-right-radius: 8px; } +th { border-bottom: 1px solid var(--line); } +td.num, th.num { text-align: right; font-variant-numeric: tabular-nums; white-space: nowrap; } +tbody tr { transition: background .12s; } +tbody tr:hover td { background: var(--panel-2); } +tbody tr:last-child td { border-bottom: 0; } +td .desc { color: var(--muted); font-size: .78rem; max-width: 520px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; margin-top: 2px; } +.tx-ico { width: 32px; height: 32px; border-radius: 9px; display: grid; place-items: center; flex: none; } +.cell-main { display: flex; align-items: center; gap: .7rem; min-width: 0; } +.cell-main > div { min-width: 0; } + +/* forms + buttons */ +input, select, textarea, button { font: inherit; color: inherit; } +input, select, textarea { background: var(--panel-2); border: 1px solid var(--line); border-radius: var(--radius-sm); padding: .5rem .65rem; min-width: 0; + transition: border-color .15s, box-shadow .15s; } +input:focus, select:focus, textarea:focus { outline: none; border-color: var(--accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 22%, transparent); } +input[type=color] { padding: 2px; width: 2.4rem; height: 2.2rem; } +button, .btn { display: inline-flex; align-items: center; justify-content: center; gap: .45rem; background: var(--accent); color: var(--on-accent); + border: 1px solid transparent; border-radius: var(--radius-sm); padding: .5rem .95rem; cursor: pointer; font-weight: 600; font-size: .9rem; + transition: filter .15s, background .15s, transform .05s; white-space: nowrap; text-decoration: none !important; } +button:hover, .btn:hover { filter: brightness(1.08); } +button:active, .btn:active { transform: translateY(1px); } +button:disabled { opacity: .6; cursor: progress; } +button.secondary, .btn.secondary { background: var(--panel); color: var(--text); border-color: var(--line); box-shadow: var(--shadow); } +button.secondary:hover, .btn.secondary:hover { background: var(--panel-2); filter: none; } +button.danger, .btn.danger { background: transparent; color: var(--bad); border-color: var(--line); } +button.danger:hover { background: var(--bad-soft); filter: none; } +button.ghost, .btn.ghost { background: transparent; color: var(--muted); border-color: transparent; } +button.ghost:hover, .btn.ghost:hover { background: var(--chip); color: var(--text); filter: none; } +button.sm, .btn.sm { padding: .3rem .6rem; font-size: .8rem; border-radius: 7px; } +button.icon, .btn.icon { padding: .4rem; } +form.inline { display: inline; } +.form-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(170px, 1fr)); gap: .7rem; align-items: end; } +.form-grid label, label.f { display: flex; flex-direction: column; gap: .3rem; font-size: .8rem; color: var(--muted); font-weight: 500; } +details > summary { cursor: pointer; font-weight: 600; list-style: none; display: flex; align-items: center; gap: .5rem; } +details > summary::-webkit-details-marker { display: none; } +details[open] > summary { margin-bottom: .9rem; } +td select { padding: .3rem .4rem; font-size: .82rem; max-width: 175px; } + +/* segmented control (range buttons, filters) */ +.seg { display: inline-flex; background: var(--panel-2); border: 1px solid var(--line); border-radius: var(--radius-sm); padding: 3px; gap: 2px; } +.seg button, .seg a { background: none; border: 0; color: var(--muted); padding: .28rem .65rem; border-radius: 7px; font-size: .8rem; font-weight: 600; box-shadow: none; } +.seg button:hover, .seg a:hover { color: var(--text); filter: none; text-decoration: none; } +.seg .on { background: var(--panel); color: var(--text); box-shadow: var(--shadow); } + +/* bits */ +.badge { display: inline-flex; align-items: center; gap: .3rem; padding: .14rem .55rem; border-radius: 99px; font-size: .72rem; font-weight: 600; background: var(--chip); color: var(--muted); white-space: nowrap; } +.badge.bad { background: var(--bad-soft); color: var(--bad); } +.badge.good { background: var(--good-soft); color: var(--good); } +.badge.warn { background: var(--warn-soft); color: var(--warn); } +.badge.accent { background: var(--accent-soft); color: var(--accent); } +.dot { display: inline-block; width: .6rem; height: .6rem; border-radius: 3px; margin-right: .45rem; vertical-align: middle; flex: none; } +.flash { display: flex; align-items: center; gap: .6rem; background: var(--accent-soft); color: var(--text); border: 1px solid color-mix(in srgb, var(--accent) 25%, transparent); + padding: .7rem 1rem; border-radius: var(--radius); margin-bottom: 1rem; } +.flash .ico { color: var(--accent); } +.alert { border: 1px solid color-mix(in srgb, var(--bad) 35%, var(--line)); background: linear-gradient(90deg, var(--bad-soft), var(--panel) 60%); } +.alert h2 { color: var(--bad); } +.progress { height: 8px; background: var(--chip); border-radius: 99px; overflow: hidden; } +.progress > div { height: 100%; border-radius: 99px; background: linear-gradient(90deg, var(--good), color-mix(in srgb, var(--good) 70%, #22d3ee)); transition: width .6s ease; } +.list { list-style: none; margin: 0; padding: 0; } +.list li { display: flex; justify-content: space-between; align-items: center; gap: .6rem; padding: .55rem 0; border-bottom: 1px solid var(--line); } +.list li:last-child { border-bottom: 0; } +.list li .num, .list li > span:last-child { white-space: nowrap; font-variant-numeric: tabular-nums; } +.list a.cat { color: var(--text); display: flex; align-items: center; min-width: 0; } +.list .bar { height: 4px; border-radius: 4px; background: var(--chip); margin-top: 5px; overflow: hidden; } +.list .bar > div { height: 100%; border-radius: 4px; } +.pager { display: flex; gap: .5rem; align-items: center; justify-content: center; margin-top: 1rem; } +.empty { text-align: center; color: var(--muted); padding: 2rem 1rem; } +.empty .ico { width: 34px; height: 34px; opacity: .5; margin-bottom: .4rem; } + +/* charts */ +.chart-box { position: relative; height: 290px; } +.chart-box.sm { height: 230px; } +.chart-box.tall { height: 330px; } +.donut-wrap { display: grid; grid-template-columns: minmax(0, 1fr); gap: .8rem; } +.legend { display: flex; flex-direction: column; gap: .25rem; max-height: 210px; overflow-y: auto; } +.legend button { display: flex; align-items: center; gap: .5rem; background: none; border: 0; padding: .3rem .4rem; border-radius: 7px; color: var(--text); font-weight: 500; font-size: .84rem; text-align: left; box-shadow: none; justify-content: flex-start; } +.legend button:hover { background: var(--chip); filter: none; } +.legend button.off { opacity: .4; text-decoration: line-through; } +.legend button .v { margin-left: auto; color: var(--muted); font-variant-numeric: tabular-nums; } + +/* live numbers */ +@keyframes flashUp { from { background: color-mix(in srgb, var(--good) 30%, transparent); } to { background: transparent; } } +@keyframes flashDown { from { background: color-mix(in srgb, var(--bad) 30%, transparent); } to { background: transparent; } } +.flash-up { animation: flashUp 1.6s ease-out; border-radius: 4px; } +.flash-down { animation: flashDown 1.6s ease-out; border-radius: 4px; } +.live-status { display: inline-flex; align-items: center; gap: .4rem; font-size: .78rem; color: var(--muted); white-space: nowrap; } +.live-status::before { content: ""; width: 7px; height: 7px; border-radius: 50%; background: var(--good); box-shadow: 0 0 0 3px var(--good-soft); animation: pulse 2s infinite; } +@keyframes pulse { 50% { box-shadow: 0 0 0 6px transparent; } } +.live-status:empty { display: none; } diff --git a/app/templates/_debt_form.html b/app/templates/_debt_form.html new file mode 100644 index 0000000..0c091ed --- /dev/null +++ b/app/templates/_debt_form.html @@ -0,0 +1,19 @@ +{% macro debt_form(x=None) %} +
+ + + + + + + + + + + +
+
+{% endmacro %} diff --git a/app/templates/_icons.svg b/app/templates/_icons.svg new file mode 100644 index 0000000..b10846e --- /dev/null +++ b/app/templates/_icons.svg @@ -0,0 +1,150 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/templates/base.html b/app/templates/base.html new file mode 100644 index 0000000..5d40c04 --- /dev/null +++ b/app/templates/base.html @@ -0,0 +1,73 @@ + + + + + + + {% block title %}Finance{% endblock %} · Finance + + + + + + +{% include "_icons.svg" %} +{% set path = request.url.path %} +{% macro navlink(href, ico, label, active, count=0) -%} + {{ icon(ico) }}{{ label }}{% if count %}{{ count }}{% endif %} +{%- endmacro %} + +
+ +
+ +
+
+ +
Finance
+
+
+ {% if msg %}
{{ icon('circle-alert') }}{{ msg }}
{% endif %} + {% block content %}{% endblock %} +
+
+
+ + + + diff --git a/app/templates/dashboard.html b/app/templates/dashboard.html new file mode 100644 index 0000000..02eb61d --- /dev/null +++ b/app/templates/dashboard.html @@ -0,0 +1,146 @@ +{% extends "base.html" %} +{% block title %}Dashboard{% endblock %} +{% block content %} +{% set acc_q = '&account=%s' % account if account else '' %} +
+
+

Dashboard

+
{{ start.strftime('%B %Y') }} ·
+
+
+ {% if start.strftime('%Y-%m') != today().strftime('%Y-%m') %}{% endif %} + + +
+
+ +{% if missed %} +
+

{{ icon('alert-triangle') }} {{ missed|length }} missed recurring payment{{ 's' if missed|length > 1 }}

+ Review
+ +
+{% endif %} + +
+
+
{{ icon('wallet') }}
+
Net worth
+
{{ net_worth|eur(0) }}
+
Cash {{ cash|eur(0) }} · Invested {{ invest_value|eur(0) }}
+
+
+
{{ icon('shopping-cart') }}
+
Spent in {{ start.strftime('%B') }}
+
{{ cur.expense|eur(0) }}
+
Income {{ cur.income|eur(0) }} · + {{ (cur.income - cur.expense)|eur(0, true) }}
+
+
+ {% set a = pt.get('all') %} +
{{ icon('trending-up') }}
+
Investments + gold
+
{{ (a.value if a else 0)|eur(0) }}
+
{% if a %}Paid {{ a.cost|eur(0) }} · + {{ a.pnl_pct|pct }}{% else %}Add holdings{% endif %}
+
+
+
{{ icon('handshake') }}
+
Debts (net)
+
{{ (owed - i_owe)|eur(0, true) }}
+
I owe {{ i_owe|eur(0) }} · Owed to me {{ owed|eur(0) }}
+
+
+ +
+
+
+

{{ icon('bar-chart-3') }} Income vs expenses

+ Click a month to open it +
+
+
+
+

{{ icon('pie-chart') }} Spending · {{ start.strftime('%b') }}

+ {% if cats %} +
+
+ {% else %}
{{ icon('pie-chart') }}
No spending this month yet.
{% endif %} +
+
+ +
+
+

{{ icon('receipt') }} Top categories

+ {% if uncategorised %}{{ uncategorised }} uncategorised{% endif %}
+ +
+
+

{{ icon('calendar-clock') }} Coming up

All recurring
+
    + {% for r in due %}
  • {{ icon('repeat', 'sm') }} + {{ r.name }}
    {{ r.next_date.strftime('%a %d %b') }}
    {{ r.amount|eur }}
  • + {% else %}
  • Nothing due in the next 7 days.
  • {% endfor %} +
+

Fixed costs ≈ {{ subs_month|eur }} per month

+
+
+

{{ icon('landmark') }} Accounts

Import
+
    + {% for a in accounts %}
  • {{ icon('credit-card' if a.bank == 'revolut' else 'building-2', 'sm') }} + {{ a.name }}{% if a.share_pct < 100 %} {{ a.share_pct }}% mine{% endif %} +
    {{ 'Updated ' + a.balance_date.strftime('%d %b') if a.balance_date else 'No balance yet' }}
    + {{ a.balance|eur }}
  • + {% else %}
  • No accounts yet.
  • {% endfor %} +
+
+
+ +
+
+

{{ icon('line-chart') }} Portfolio value vs paid

+
+ + +
+ {% if charts.portfolio.labels %} +
+ {% else %}
{{ icon('line-chart') }}
History builds up automatically once you add holdings.
{% endif %} +
+
+

{{ icon('handshake') }} Debts

Manage
+
    + {% for x, s in dstat %}
  • +
    {{ x.name }} + {{ s.status }} + {{ s.remaining|eur(0) }}
    +
    +
  • {% else %}
  • No open debts.
  • {% endfor %} +
+
+
+{% endblock %} diff --git a/app/templates/debt_detail.html b/app/templates/debt_detail.html new file mode 100644 index 0000000..7117d2c --- /dev/null +++ b/app/templates/debt_detail.html @@ -0,0 +1,52 @@ +{% extends "base.html" %} +{% from "_debt_form.html" import debt_form with context %} +{% block title %}{{ d.name }}{% endblock %} +{% block content %} +

{{ icon('chevron-left', 'sm') }} All debts

+
+

{{ d.name }} {{ 'I owe' if d.direction == 'i_owe' else 'owed to me' }} + {% if d.closed %}closed{% endif %}

+
+ {% if d.match_pattern %}
{% endif %} +
+
+
+
+ +
+
Remaining
{{ s.remaining|eur }}
of {{ d.principal|eur }}
+
Paid
{{ s.paid|eur }}
+
+
Status
+
{{ s.status }}
+
{% if s.expected is not none %}expected by now {{ s.expected|eur }} ({{ s.diff|eur(2, true) }}){% else %}set a monthly payment to track schedule{% endif %}
+
Next due
{{ s.next_due.strftime('%d %b') if s.next_due else '—' }}
+
{{ 'paid off ≈ ' + s.payoff.strftime('%b %Y') if s.payoff }}
+
+ +
+
+

{{ icon('banknote') }} Payments

+
+ + + + +
+
+ + + {% for p, bal in running %} + + + + {% else %}{% endfor %} + +
DateAmountBalance afterNote
{{ p.date.strftime('%d-%m-%Y') }}{{ p.amount|eur }}{{ bal|eur }}{{ p.notes }}{% if p.transaction_id %} {{ icon('landmark', 'sm') }} bank{% endif %}
No payments yet.
+
+
+

{{ icon('pencil') }} Details

+ {{ debt_form(d) }} +
+
+{% endblock %} diff --git a/app/templates/debts.html b/app/templates/debts.html new file mode 100644 index 0000000..5c2d51a --- /dev/null +++ b/app/templates/debts.html @@ -0,0 +1,49 @@ +{% extends "base.html" %} +{% block title %}Debts{% endblock %} +{% from "_debt_form.html" import debt_form with context %} + +{% block content %} +

Debts

What you owe and what others owe you
+
+
+
{{ icon('arrow-up-right') }}
I owe
{{ sums.i_owe|eur }}
+
{{ icon('arrow-down-right') }}
Owed to me
{{ sums.owed_to_me|eur }}
+
{{ icon('scale') }}
Net
{{ (sums.owed_to_me - sums.i_owe)|eur(2, true) }}
+
+ +{% for dir, label in [('i_owe', 'Debts I have'), ('owed_to_me', 'Money people owe me')] %} +
+

{{ icon('landmark' if dir == 'i_owe' else 'handshake') }} {{ label }}

+
+ + + + {% for x, s in debts if x.direction == dir %} + + + + + + + + + + + + + {% else %}{% endfor %} + +
NameStatusProgressTotalPaidRemainingMonthlyNext dueLast paymentPaid off ≈
{{ x.name }}
{{ x.counterparty }}
{% set cls = {'behind':'bad','on track':'good','ahead':'good','paid off':'good'}.get(s.status, '') %} + {{ s.status }}{% if s.missed %} · {{ s.missed }} missed{% endif %}
{{ '%.0f'|format(s.pct) }}%
{{ x.principal|eur }}{{ s.paid|eur }}{{ s.remaining|eur }}{{ x.monthly_payment|eur if x.monthly_payment else '—' }}{{ s.next_due.strftime('%d-%m-%Y') if s.next_due else '—' }}{{ s.last_payment.strftime('%d-%m-%Y') if s.last_payment else 'never' }}{{ s.payoff.strftime('%b %Y') if s.payoff else '—' }}
None.
+
+{% endfor %} + +

{{ 'Hide' if show_closed else 'Show' }} closed debts

+ +
+ {{ icon('plus') }} Add a debt + {{ debt_form() }} +

With a monthly payment set, the status compares what should have been paid by now with what was paid. + The “auto-match” text links bank transactions automatically (outgoing for debts you have, incoming for money owed to you).

+
+{% endblock %} diff --git a/app/templates/import.html b/app/templates/import.html new file mode 100644 index 0000000..73fd258 --- /dev/null +++ b/app/templates/import.html @@ -0,0 +1,48 @@ +{% extends "base.html" %} +{% block title %}Import{% endblock %} +{% block content %} +

Import statements

ING (NL) and Revolut CSV exports · duplicates are skipped automatically
+
+
+

{{ icon('file-up') }} Upload CSV files

+

You can select several files at once. Re-importing overlapping periods is safe: duplicates are skipped.

+
+ + +
+
+
+
+

{{ icon('download') }} Where to get the files

+

ING (main and shared): Mijn ING → account → Af- en bijschrijvingen downloaden → format + Kommagescheiden CSV or Puntkomma-gescheiden, pick a date range. Both formats work, Dutch or English headers.

+

Revolut: app → account → ⋯ → Statement → Excel/CSV, pick the period. Only completed + transactions from the Current account are imported.

+

Prefer automatic syncing? Set up Enable Banking under Settings.

+
+
+ +{% if results %} +
+

Result

+
+ + + {% for r in results %} + {% if r.ok %} + + + {% else %} + + {% endif %} + {% endfor %} + +
FileAccountNewDuplicatesSkippedDebt payments
{{ r.file }} {{ r.fmt }}{{ r.account }}{{ r.inserted }}{{ r.duplicates }}{{ r.skipped }}{{ r.debt_payments }}
{{ r.file }}{{ r.error }}
+

Review uncategorised · Check recurring · Dashboard

+
+{% endif %} +{% endblock %} diff --git a/app/templates/investments.html b/app/templates/investments.html new file mode 100644 index 0000000..2023375 --- /dev/null +++ b/app/templates/investments.html @@ -0,0 +1,146 @@ +{% extends "base.html" %} +{% block title %}{{ title }}{% endblock %} +{% set is_gold = kinds == ['gold'] %}{% set P = 'gold' if is_gold else 'inv' %} +{% block content %} +
+

{{ title }}

+
{{ 'Physical gold valued at live spot price' if is_gold else 'Stocks, ETFs and crypto at live prices' }} ·
+
+ {{ icon('plus', 'sm') }} {{ 'Purchase' if is_gold else 'Trade' }} +
+
+
+ +
+ {% set a = t.get('all') %} +
{{ icon('gem' if is_gold else 'line-chart') }}
Current value
{{ (a.value if a else 0)|eur }}
+
{% if a and a.missing_price %}{{ a.missing_price }} without price (counted at cost){% else %}live prices{% endif %}
+
{{ icon('banknote') }}
Paid
{{ (a.cost if a else 0)|eur }}
incl. fees, open positions
+
{{ icon('arrow-up-right' if a and a.pnl >= 0 else 'arrow-down-right') }}
Unrealised P/L
+
{{ (a.pnl if a else 0)|eur(2, true) }}
{{ (a.pnl_pct if a else None)|pct }}
+
{{ icon('check') }}
Realised P/L
{{ (a.realized if a else 0)|eur(2, true) }}
from sells
+
+ +{% if not is_gold %} +
+ {% for k, label in [('stock','Stocks & ETFs'),('crypto','Crypto')] %}{% set x = t.get(k) %} +
{{ icon('bitcoin' if k == 'crypto' else 'bar-chart-3') }}
{{ label }}
+
{{ (x.value if x else 0)|eur }}
+
paid {{ (x.cost if x else 0)|eur }} · {{ (x.pnl if x else 0)|eur(2, true) }} ({{ (x.pnl_pct if x else None)|pct }})
+ {% endfor %} +
+{% endif %} + +
+

{{ icon('coins') }} Holdings

+
+ {% if not is_gold %}{% endif %}{% if is_gold %}{% endif %} + + + {% for r in rows %}{% set as = r.asset %} + + + {% if not is_gold %}{% endif %} + + {% if is_gold %}{% endif %} + + + + + + + + + {% else %}{% endfor %} + +
AssetTypeQuantityFine goldAvg paidPricePaidValueP/L%
{{ as.name }}
{{ as.symbol }}{% if as.price_error %} · price error{% endif %} + {% if as.manual_price is not none %} · manual price{% elif as.last_price_at %} · {{ as.last_price_at.strftime('%d-%m %H:%M') }}{% endif %}
{{ as.kind }}{{ r.qty|num }} {{ as.unit if as.unit != 'unit' }}{% if is_gold and as.purity != 1 %} @{{ as.purity|num }}{% endif %}{{ r.grams|num(2) }} g{{ r.avg|eur }}{{ r.price|eur }}{{ r.cost|eur }}{{ r.value|eur }}{{ r.pnl|eur(2, true) }}{{ r.pnl_pct|pct }} +
{{ icon('pencil', 'sm') }} +
+ + +
+
+
No holdings yet. Add an asset below, then record your purchases.
+
+ +
+
+

{{ icon('line-chart') }} Value vs paid

+
+ + +
+ {% if chart.labels %} +
+ {% else %}
{{ icon('line-chart') }}
A data point is stored each time prices refresh.
{% endif %} +
+
+

{{ icon('pie-chart') }} Allocation

+ {% if chart.alloc_values %} +
+
+ {% else %}
{{ icon('pie-chart') }}
No priced holdings yet.
{% endif %} +
+
+ +
+
+

{{ icon('plus') }} Record a {{ 'purchase' if is_gold else 'trade' }}

+ {% if assets %} +
+ + + + + + + + +
+
+ {% else %}

Add an asset first →

{% endif %} +
+ +
+

{{ icon('sparkles') }} Add an asset

+ {% if is_gold %} + +
+ + + + +
+
+

Quantity is the item's total weight in the chosen unit; value = weight × purity × spot. Spot is the COMEX gold price + converted to EUR; dealers usually buy back 1–3 % below spot (set a manual price per item if you want to be conservative).

+ {% else %} +
+ + + +
+
+

Stocks/ETFs: Yahoo Finance ticker incl. exchange suffix (VWRL.AS, IWDA.AS, ASML.AS, AAPL), converted to EUR. + Crypto: CoinGecko id (bitcoin, ethereum, solana, cardano…) — find it in the coin's URL on coingecko.com.

+ {% endif %} +
+
+ +
+

{{ icon('clock') }} History

+
+ + + {% for tr in trades %} + + + + + {% else %}{% endfor %} + +
DateAssetSideQtyPriceFeesTotalNote
{{ tr.date.strftime('%d-%m-%Y') }}{{ tr.asset.name }}{{ tr.side }}{{ tr.quantity|num }}{{ tr.price|eur }}{{ tr.fees|eur }}{{ (tr.quantity * tr.price + (tr.fees if tr.side == 'buy' else -tr.fees))|eur }}{{ tr.notes }}
No trades yet.
+
+{% endblock %} diff --git a/app/templates/recurring.html b/app/templates/recurring.html new file mode 100644 index 0000000..24ac1bb --- /dev/null +++ b/app/templates/recurring.html @@ -0,0 +1,63 @@ +{% extends "base.html" %} +{% block title %}Recurring{% endblock %} +{% block content %} +
+

Recurring payments

Subscriptions and fixed costs, detected from your statements
+
{{ icon('plus', 'sm') }} Add manually +
+
+ +
+
{{ icon('calendar-clock') }}
Fixed costs / month
{{ out_total|eur }}
{{ (out_total*12)|eur(0) }} per year
+
{{ icon('piggy-bank') }}
Recurring income / month
{{ in_total|eur }}
add salary manually below
+
{{ icon('alert-triangle') }}
Missed
+ {% set ns = namespace(m=0) %}{% for r in recs %}{% if rec_state(r) == 'missed' %}{% set ns.m = ns.m + 1 %}{% endif %}{% endfor %} +
{{ ns.m }}
past expected date + grace period
+
+ +
+

{{ icon('repeat') }} Payments

+ +
+
+ + + {% for r in recs %}{% set st = rec_state(r) %} + + + + + + + + + + + + {% else %}{% endfor %} + +
NameStateEveryAmount/ monthLast paidNext expectedAccount
{{ r.name }} {% if r.status == 'detected' %}new{% endif %} +
match: “{{ r.match }}” · {{ r.occurrences }}× {{ '· ' + r.category.name if r.category }}
{% if st == 'missed' %}missed{% elif st == 'due-soon' %}due soon + {% elif st == 'ignored' %}ignored{% else %}ok{% endif %} +
+ +
{{ r.amount|eur }}{{ monthly_eq(r)|eur }}{{ r.last_date.strftime('%d-%m-%Y') if r.last_date else '—' }}{{ r.next_date.strftime('%d-%m-%Y') if r.next_date else '—' }}{{ r.account.name if r.account else '' }} + {% if r.status != 'confirmed' %}
{% endif %} + {% if r.status != 'ignored' %}
{% endif %} + {{ icon('receipt', 'sm') }} +
Nothing detected yet. Import at least 3 months of statements, then re-scan.
+
+ +
+ {{ icon('plus') }} Add a recurring payment manually (rent, salary, yearly insurance…) +
+ + + + + + +
+
+
+{% endblock %} diff --git a/app/templates/settings.html b/app/templates/settings.html new file mode 100644 index 0000000..9f4a5ca --- /dev/null +++ b/app/templates/settings.html @@ -0,0 +1,114 @@ +{% extends "base.html" %} +{% block title %}Settings{% endblock %} +{% block content %} +

Settings

Accounts, bank sync, categories and rules
+ +
+

{{ icon('landmark') }} Accounts

+

Add the IBANs of all your own accounts (including Revolut's) so transfers between them are recognised and not counted as spending. + “Your share” scales a joint account's spending, e.g. 50 for the shared house account.

+
+ + + {% for a in accounts %} + + + + + + + + + + {% endfor %} + + + + + + + +
NameBankIBANYour share %BalanceBank sync
+
{{ a.balance|eur }}{{ ('linked · ' + (a.eb_last_sync.strftime('%d-%m %H:%M') if a.eb_last_sync else 'never synced')) if a.eb_account_uid else '—' }} +
+
+ +
+

{{ icon('refresh-cw') }} Automatic bank sync (Enable Banking)

+ {% if eb_configured %} +

Configured ✓. New transactions are pulled every few hours. Bank consent expires (usually after 90–180 days); reconnect when it does.

+ {% if eb_valid %}{% endif %} +
+
+ + + +
+
+
+

Bank names must match Enable Banking's list exactly (NL list). + Revolut may be listed under LT. In free restricted mode, first link the same accounts in the Enable Banking control panel.

+ {% else %} +

Not configured. You can keep importing CSVs, or enable sync:

+
    +
  1. Sign up at enablebanking.com and create an application (environment: Production, redirect URL: {{ request.base_url }}eb/callback).
  2. +
  3. Download the private key to ./secrets/enablebanking.pem and put the application ID in .env as EB_APP_ID.
  4. +
  5. In the Enable Banking control panel, use Link accounts for ING and Revolut (needed for the free restricted mode).
  6. +
  7. docker compose up -d, then come back here and press Connect.
  8. +
+ {% endif %} +
+ +
+
+

{{ icon('pie-chart') }} Categories

+

Kind “transfer” is excluded from income/expense totals (own-account moves, investing, savings).

+
+ + + {% for c in categories %} + + + + + + + {% endfor %} + + + + + +
NameKindTxns
+
{{ counts.get(c.id, 0) }} +
+
+ +
+

{{ icon('sparkles') }} Categorisation rules

+
+ + + + +
+
+

Matches whole words, case-insensitive. Prefix with re: for a regular expression. Lower priority wins.

+
+
+
+
+
+ + + {% for r in rules %} + + + + {% endfor %} + +
PatternInCategoryPrio
{{ r.pattern }}{{ r.field }}{{ r.category.name }}{{ r.priority }}
+
+
+{% endblock %} diff --git a/app/templates/transactions.html b/app/templates/transactions.html new file mode 100644 index 0000000..7bacf93 --- /dev/null +++ b/app/templates/transactions.html @@ -0,0 +1,49 @@ +{% extends "base.html" %} +{% block title %}Transactions{% endblock %} +{% block content %} +

Transactions

{{ total }} transactions · net {{ total_amount|eur }}
+
+
+ + + + +
Reset
+
+ +
+

{{ icon('receipt') }} Activity

{{ icon('lock', 'sm') }} Changing a category locks it so rules won't overwrite it.
+
+ + + + {% for t in txs %} + + + + + + + + + + {% else %}{% endfor %} + +
DateCounterpartyAccountCategoryAmountNote
{{ t.date.strftime('%d-%m-%Y') }}
{{ icon('arrow-down-right' if t.amount > 0 else 'arrow-up-right', 'sm') }} +
{{ t.counterparty or '—' }}{% if t.recurring_id %} {{ icon('repeat', 'sm') }}{% endif %}{% if t.debt_id %} {{ icon('handshake', 'sm') }}{% endif %} +
{{ t.counter_iban or '' }} {{ t.description }}
{{ t.account.name }} + {% if t.category_locked %}{{ icon('lock', 'sm') }}{% endif %}{{ t.amount|eur }}{% if t.currency != 'EUR' %} {{ t.currency }}{% endif %}{{ icon('plus', 'sm') }} Rule
No transactions match.
+
+ {% if pages > 1 %} +
+ {% set qs = 'q=%s&account=%s&category=%s&month=%s'|format(f.q|urlencode, f.account, f.category, f.month) %} + {% if page > 1 %}‹ Prev{% endif %} + Page {{ page }} / {{ pages }} + {% if page < pages %}Next ›{% endif %} +
+ {% endif %} +
+{% endblock %} diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..bb0c48f --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,148 @@ +# Self-hosted personal finance stack +# traefik -> reverse proxy + TLS, forward-auth to authentik +# authentik -> SSO / login (server + worker + postgres; no Redis needed since 2025.10) +# finance -> the app (FastAPI) + its own postgres +# +# Usage: cp .env.example .env && edit && docker compose up -d --build + +name: finance + +x-authentik-env: &authentik-env + AUTHENTIK_SECRET_KEY: ${AUTHENTIK_SECRET_KEY:?set AUTHENTIK_SECRET_KEY in .env} + AUTHENTIK_ERROR_REPORTING__ENABLED: "false" + AUTHENTIK_POSTGRESQL__HOST: authentik-db + AUTHENTIK_POSTGRESQL__USER: authentik + AUTHENTIK_POSTGRESQL__NAME: authentik + AUTHENTIK_POSTGRESQL__PASSWORD: ${AUTHENTIK_DB_PASSWORD:?set AUTHENTIK_DB_PASSWORD in .env} + +services: + traefik: + image: traefik:${TRAEFIK_TAG:-v3.6} + restart: unless-stopped + ports: + - "80:80" + - "443:443" + environment: + # Only needed if you use the Let's Encrypt DNS challenge (see traefik/traefik.yml) + CF_DNS_API_TOKEN: ${CF_DNS_API_TOKEN:-} + volumes: + - /var/run/docker.sock:/var/run/docker.sock:ro + - ./traefik/traefik.yml:/etc/traefik/traefik.yml:ro + - ./traefik/dynamic:/etc/traefik/dynamic:ro + - ./traefik/certs:/certs:ro + - traefik-acme:/acme + networks: [proxy] + + authentik-db: + image: postgres:16-alpine + restart: unless-stopped + environment: + POSTGRES_USER: authentik + POSTGRES_DB: authentik + POSTGRES_PASSWORD: ${AUTHENTIK_DB_PASSWORD} + volumes: + - authentik-db:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -d authentik -U authentik"] + interval: 10s + timeout: 5s + retries: 5 + networks: [authentik] + + authentik-server: + image: ghcr.io/goauthentik/server:${AUTHENTIK_TAG:-2026.8.5} + restart: unless-stopped + command: server + environment: *authentik-env + volumes: + - ./authentik/data:/data + - ./authentik/custom-templates:/templates + depends_on: + authentik-db: + condition: service_healthy + networks: [proxy, authentik] + labels: + - traefik.enable=true + - traefik.docker.network=finance_proxy + - traefik.http.routers.authentik.rule=Host(`${AUTH_HOST}`) + - traefik.http.routers.authentik.entrypoints=websecure + - traefik.http.routers.authentik.tls=true + - traefik.http.services.authentik.loadbalancer.server.port=9000 + + authentik-worker: + image: ghcr.io/goauthentik/server:${AUTHENTIK_TAG:-2026.8.5} + restart: unless-stopped + command: worker + user: root + environment: *authentik-env + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ./authentik/data:/data + - ./authentik/certs:/certs + - ./authentik/custom-templates:/templates + depends_on: + authentik-db: + condition: service_healthy + networks: [authentik] + + finance-db: + image: postgres:16-alpine + restart: unless-stopped + environment: + POSTGRES_USER: finance + POSTGRES_DB: finance + POSTGRES_PASSWORD: ${FINANCE_DB_PASSWORD:?set FINANCE_DB_PASSWORD in .env} + volumes: + - finance-db:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -d finance -U finance"] + interval: 10s + timeout: 5s + retries: 5 + networks: [finance] + + finance: + build: ./app + restart: unless-stopped + environment: + DATABASE_URL: postgresql+psycopg://finance:${FINANCE_DB_PASSWORD}@finance-db:5432/finance + TZ: ${TZ:-Europe/Amsterdam} + PUBLIC_URL: https://${FINANCE_HOST} + # Enable Banking (optional, see README) + EB_APP_ID: ${EB_APP_ID:-} + EB_KEY_PATH: /run/secrets/enablebanking.pem + EB_SYNC_HOURS: ${EB_SYNC_HOURS:-6} + # Prices + COINGECKO_API_KEY: ${COINGECKO_API_KEY:-} + PRICE_REFRESH_MINUTES: ${PRICE_REFRESH_MINUTES:-60} + volumes: + - ./secrets:/run/secrets:ro + depends_on: + finance-db: + condition: service_healthy + networks: [proxy, finance] + labels: + - traefik.enable=true + - traefik.docker.network=finance_proxy + # The app itself, protected by authentik forward-auth + - traefik.http.routers.finance.rule=Host(`${FINANCE_HOST}`) + - traefik.http.routers.finance.entrypoints=websecure + - traefik.http.routers.finance.tls=true + - traefik.http.routers.finance.middlewares=authentik@file,secure-headers@file + - traefik.http.services.finance.loadbalancer.server.port=8000 + # authentik's embedded outpost must answer /outpost.goauthentik.io/ on the app's host + - traefik.http.routers.finance-outpost.rule=Host(`${FINANCE_HOST}`) && PathPrefix(`/outpost.goauthentik.io/`) + - traefik.http.routers.finance-outpost.entrypoints=websecure + - traefik.http.routers.finance-outpost.tls=true + - traefik.http.routers.finance-outpost.priority=100 + - traefik.http.routers.finance-outpost.service=authentik@docker + +networks: + proxy: + authentik: + finance: + +volumes: + traefik-acme: + authentik-db: + finance-db: diff --git a/secrets/.gitkeep b/secrets/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/traefik/certs/.gitkeep b/traefik/certs/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/traefik/dynamic/middlewares.yml b/traefik/dynamic/middlewares.yml new file mode 100644 index 0000000..d822786 --- /dev/null +++ b/traefik/dynamic/middlewares.yml @@ -0,0 +1,22 @@ +http: + middlewares: + # Forward every request to authentik's embedded outpost; unauthenticated users get redirected to login. + authentik: + forwardAuth: + address: http://authentik-server:9000/outpost.goauthentik.io/auth/traefik + trustForwardHeader: true + authResponseHeaders: + - X-authentik-username + - X-authentik-groups + - X-authentik-email + - X-authentik-name + - X-authentik-uid + + secure-headers: + headers: + frameDeny: true + contentTypeNosniff: true + referrerPolicy: same-origin + stsSeconds: 31536000 + customResponseHeaders: + X-Robots-Tag: "noindex, nofollow" diff --git a/traefik/dynamic/tls.yml b/traefik/dynamic/tls.yml new file mode 100644 index 0000000..61f2acf --- /dev/null +++ b/traefik/dynamic/tls.yml @@ -0,0 +1,10 @@ +# Optional: use your own certificate (e.g. made with mkcert for *.home.lan). +# Put the files in ./traefik/certs and uncomment. Without this (and without Let's Encrypt) +# Traefik serves its built-in self-signed certificate. +# +# tls: +# stores: +# default: +# defaultCertificate: +# certFile: /certs/local.crt +# keyFile: /certs/local.key diff --git a/traefik/traefik.yml b/traefik/traefik.yml new file mode 100644 index 0000000..0797a29 --- /dev/null +++ b/traefik/traefik.yml @@ -0,0 +1,43 @@ +# Traefik static configuration +api: + dashboard: false + +log: + level: INFO + +entryPoints: + web: + address: ":80" + http: + redirections: + entryPoint: + to: websecure + scheme: https + websecure: + address: ":443" + http: + tls: {} + # Uncomment to get real certificates via Let's Encrypt DNS challenge + # (works for LAN-only hosts as long as you own the domain): + # tls: + # certResolver: letsencrypt + # domains: + # - main: "example.com" + # sans: ["*.example.com"] + +providers: + docker: + exposedByDefault: false + network: finance_proxy + file: + directory: /etc/traefik/dynamic + watch: true + +# certificatesResolvers: +# letsencrypt: +# acme: +# email: you@example.com +# storage: /acme/acme.json +# dnsChallenge: +# provider: cloudflare # set CF_DNS_API_TOKEN in .env (or use another provider) +# resolvers: ["1.1.1.1:53"]