First commit
This commit is contained in:
@@ -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", "*"]
|
||||
@@ -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"(?<![a-z0-9])" + re.escape(pattern.lower()) + r"(?![a-z0-9])", re.I)
|
||||
|
||||
|
||||
def rule_matches(rule: Rule, tx: Transaction) -> 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()
|
||||
Binary file not shown.
@@ -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()
|
||||
@@ -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
|
||||
@@ -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 "",
|
||||
)
|
||||
+747
@@ -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'<svg class="ico {cls}" aria-hidden="true"><use href="#i-{name}"></use></svg>')
|
||||
|
||||
|
||||
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}
|
||||
+165
@@ -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:<regex>"
|
||||
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="")
|
||||
@@ -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
|
||||
+120
@@ -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()
|
||||
@@ -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"))
|
||||
@@ -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
|
||||
+180
@@ -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)
|
||||
@@ -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 · <a href="">reload</a>' : "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 = `<span class="dot" style="background:${ds.backgroundColor[i]}"></span><span>${label}</span><span class="v">${eur(ds.data[i])} · ${nf(0).format((ds.data[i] / total) * 100)}%</span>`;
|
||||
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());
|
||||
});
|
||||
@@ -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; }
|
||||
@@ -0,0 +1,19 @@
|
||||
{% macro debt_form(x=None) %}
|
||||
<form method="post" action="/debts/save" class="form-grid">
|
||||
<input type="hidden" name="id" value="{{ x.id if x else '' }}">
|
||||
<label>Name<input name="name" required value="{{ x.name if x else '' }}" placeholder="DUO study loan / Loan to Sam"></label>
|
||||
<label>Direction<select name="direction">
|
||||
<option value="i_owe" {{ 'selected' if x and x.direction == 'i_owe' }}>I owe them</option>
|
||||
<option value="owed_to_me" {{ 'selected' if x and x.direction == 'owed_to_me' }}>They owe me</option></select></label>
|
||||
<label>Counterparty<input name="counterparty" value="{{ x.counterparty if x else '' }}"></label>
|
||||
<label>Amount (€)<input name="principal" inputmode="decimal" required value="{{ x.principal if x else '' }}"></label>
|
||||
<label>Start date<input type="date" name="start_date" value="{{ x.start_date.isoformat() if x else today().isoformat() }}"></label>
|
||||
<label>Monthly payment (€)<input name="monthly_payment" inputmode="decimal" value="{{ x.monthly_payment if x and x.monthly_payment else '' }}" placeholder="optional"></label>
|
||||
<label>Due day of month<input name="due_day" type="number" min="1" max="31" value="{{ x.due_day if x and x.due_day else '' }}" placeholder="optional"></label>
|
||||
<label>Interest % / year<input name="interest_rate" inputmode="decimal" value="{{ x.interest_rate if x and x.interest_rate is not none else '' }}" placeholder="informational"></label>
|
||||
<label title="Bank transactions whose name/description contains this are counted as payments automatically">Auto-match bank text
|
||||
<input name="match_pattern" value="{{ x.match_pattern if x and x.match_pattern else '' }}" placeholder="e.g. DUO or S. Jansen"></label>
|
||||
<label>Notes<input name="notes" value="{{ x.notes if x else '' }}"></label>
|
||||
<div><button>{{ 'Save' if x else 'Add' }}</button></div>
|
||||
</form>
|
||||
{% endmacro %}
|
||||
@@ -0,0 +1,150 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" style="display:none">
|
||||
<!-- Lucide icons, ISC License, https://lucide.dev -->
|
||||
<symbol id="i-layout-dashboard" viewBox="0 0 24 24"><rect width="7" height="9" x="3" y="3" rx="1" />
|
||||
<rect width="7" height="5" x="14" y="3" rx="1" />
|
||||
<rect width="7" height="9" x="14" y="12" rx="1" />
|
||||
<rect width="7" height="5" x="3" y="16" rx="1" /></symbol>
|
||||
<symbol id="i-receipt" viewBox="0 0 24 24"><path d="M12 17V7" />
|
||||
<path d="M16 8h-6a2 2 0 0 0 0 4h4a2 2 0 0 1 0 4H8" />
|
||||
<path d="M4 3a1 1 0 0 1 1-1 1.3 1.3 0 0 1 .7.2l.933.6a1.3 1.3 0 0 0 1.4 0l.934-.6a1.3 1.3 0 0 1 1.4 0l.933.6a1.3 1.3 0 0 0 1.4 0l.933-.6a1.3 1.3 0 0 1 1.4 0l.934.6a1.3 1.3 0 0 0 1.4 0l.933-.6A1.3 1.3 0 0 1 19 2a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1 1.3 1.3 0 0 1-.7-.2l-.933-.6a1.3 1.3 0 0 0-1.4 0l-.934.6a1.3 1.3 0 0 1-1.4 0l-.933-.6a1.3 1.3 0 0 0-1.4 0l-.933.6a1.3 1.3 0 0 1-1.4 0l-.934-.6a1.3 1.3 0 0 0-1.4 0l-.933.6a1.3 1.3 0 0 1-.7.2 1 1 0 0 1-1-1z" /></symbol>
|
||||
<symbol id="i-repeat" viewBox="0 0 24 24"><path d="m17 2 4 4-4 4" />
|
||||
<path d="M3 11v-1a4 4 0 0 1 4-4h14" />
|
||||
<path d="m7 22-4-4 4-4" />
|
||||
<path d="M21 13v1a4 4 0 0 1-4 4H3" /></symbol>
|
||||
<symbol id="i-trending-up" viewBox="0 0 24 24"><path d="M16 7h6v6" />
|
||||
<path d="m22 7-8.5 8.5-5-5L2 17" /></symbol>
|
||||
<symbol id="i-gem" viewBox="0 0 24 24"><path d="M10.5 3 8 9l4 13 4-13-2.5-6" />
|
||||
<path d="M17 3a2 2 0 0 1 1.6.8l3 4a2 2 0 0 1 .013 2.382l-7.99 10.986a2 2 0 0 1-3.247 0l-7.99-10.986A2 2 0 0 1 2.4 7.8l2.998-3.997A2 2 0 0 1 7 3z" />
|
||||
<path d="M2 9h20" /></symbol>
|
||||
<symbol id="i-handshake" viewBox="0 0 24 24"><path d="m11 17 2 2a1 1 0 1 0 3-3" />
|
||||
<path d="m14 14 2.5 2.5a1 1 0 1 0 3-3l-3.88-3.88a3 3 0 0 0-4.24 0l-.88.88a1 1 0 1 1-3-3l2.81-2.81a5.79 5.79 0 0 1 7.06-.87l.47.28a2 2 0 0 0 1.42.25L21 4" />
|
||||
<path d="m21 3 1 11h-2" />
|
||||
<path d="M3 3 2 14l6.5 6.5a1 1 0 1 0 3-3" />
|
||||
<path d="M3 4h8" /></symbol>
|
||||
<symbol id="i-upload" viewBox="0 0 24 24"><path d="M12 3v12" />
|
||||
<path d="m17 8-5-5-5 5" />
|
||||
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" /></symbol>
|
||||
<symbol id="i-settings" viewBox="0 0 24 24"><path d="M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915" />
|
||||
<circle cx="12" cy="12" r="3" /></symbol>
|
||||
<symbol id="i-log-out" viewBox="0 0 24 24"><path d="m16 17 5-5-5-5" />
|
||||
<path d="M21 12H9" />
|
||||
<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" /></symbol>
|
||||
<symbol id="i-sun" viewBox="0 0 24 24"><circle cx="12" cy="12" r="4" />
|
||||
<path d="M12 2v2" />
|
||||
<path d="M12 20v2" />
|
||||
<path d="m4.93 4.93 1.41 1.41" />
|
||||
<path d="m17.66 17.66 1.41 1.41" />
|
||||
<path d="M2 12h2" />
|
||||
<path d="M20 12h2" />
|
||||
<path d="m6.34 17.66-1.41 1.41" />
|
||||
<path d="m19.07 4.93-1.41 1.41" /></symbol>
|
||||
<symbol id="i-moon" viewBox="0 0 24 24"><path d="M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401" /></symbol>
|
||||
<symbol id="i-monitor" viewBox="0 0 24 24"><rect width="20" height="14" x="2" y="3" rx="2" />
|
||||
<line x1="8" x2="16" y1="21" y2="21" />
|
||||
<line x1="12" x2="12" y1="17" y2="21" /></symbol>
|
||||
<symbol id="i-wallet" viewBox="0 0 24 24"><path d="M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1" />
|
||||
<path d="M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4" /></symbol>
|
||||
<symbol id="i-shopping-cart" viewBox="0 0 24 24"><path d="m2.05 2.05 1.099-.028a1 1 0 0 1 1.008.815l2.69 14.347A1 1 0 0 0 7.83 18H18" />
|
||||
<path d="M4.563 5h16.435a1 1 0 0 1 .981 1.204l-1.026 6.226A2 2 0 0 1 18.962 14H6.25" />
|
||||
<circle cx="18" cy="20" r="2" />
|
||||
<circle cx="8" cy="20" r="2" /></symbol>
|
||||
<symbol id="i-landmark" viewBox="0 0 24 24"><path d="M10 18v-7" />
|
||||
<path d="M11.119 2.205a2 2 0 0 1 1.762 0l7.84 3.846A.5.5 0 0 1 20.5 7h-17a.5.5 0 0 1-.22-.949z" />
|
||||
<path d="M14 18v-7" />
|
||||
<path d="M18 18v-7" />
|
||||
<path d="M3 22h18" />
|
||||
<path d="M6 18v-7" /></symbol>
|
||||
<symbol id="i-alert-triangle" viewBox="0 0 24 24"><path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3" />
|
||||
<path d="M12 9v4" />
|
||||
<path d="M12 17h.01" /></symbol>
|
||||
<symbol id="i-calendar-clock" viewBox="0 0 24 24"><path d="M16 14v2.2l1.6 1" />
|
||||
<path d="M16 2v3" />
|
||||
<path d="M21 7.338V5a2 2 0 00-2-2H5a2 2 0 00-2 2v14a2 2 0 002 2h2.338" />
|
||||
<path d="M3 9h5.859" />
|
||||
<path d="M8 2v3" />
|
||||
<circle cx="16" cy="16" r="6" /></symbol>
|
||||
<symbol id="i-refresh-cw" viewBox="0 0 24 24"><path d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8" />
|
||||
<path d="M21 3v5h-5" />
|
||||
<path d="M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16" />
|
||||
<path d="M8 16H3v5" /></symbol>
|
||||
<symbol id="i-search" viewBox="0 0 24 24"><path d="m21 21-4.34-4.34" />
|
||||
<circle cx="11" cy="11" r="8" /></symbol>
|
||||
<symbol id="i-plus" viewBox="0 0 24 24"><path d="M5 12h14" />
|
||||
<path d="M12 5v14" /></symbol>
|
||||
<symbol id="i-check" viewBox="0 0 24 24"><path d="M20 6 9 17l-5-5" /></symbol>
|
||||
<symbol id="i-x" viewBox="0 0 24 24"><path d="M18 6 6 18" />
|
||||
<path d="m6 6 12 12" /></symbol>
|
||||
<symbol id="i-trash-2" viewBox="0 0 24 24"><path d="M10 11v6" />
|
||||
<path d="M14 11v6" />
|
||||
<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6" />
|
||||
<path d="M3 6h18" />
|
||||
<path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" /></symbol>
|
||||
<symbol id="i-pencil" viewBox="0 0 24 24"><path d="M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z" />
|
||||
<path d="m15 5 4 4" /></symbol>
|
||||
<symbol id="i-chevron-left" viewBox="0 0 24 24"><path d="m15 18-6-6 6-6" /></symbol>
|
||||
<symbol id="i-chevron-right" viewBox="0 0 24 24"><path d="m9 18 6-6-6-6" /></symbol>
|
||||
<symbol id="i-arrow-up-right" viewBox="0 0 24 24"><path d="M7 7h10v10" />
|
||||
<path d="M7 17 17 7" /></symbol>
|
||||
<symbol id="i-arrow-down-right" viewBox="0 0 24 24"><path d="m7 7 10 10" />
|
||||
<path d="M17 7v10H7" /></symbol>
|
||||
<symbol id="i-piggy-bank" viewBox="0 0 24 24"><path d="M11 17h3v2a1 1 0 0 0 1 1h2a1 1 0 0 0 1-1v-3a3.16 3.16 0 0 0 2-2h1a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1h-1a5 5 0 0 0-2-4V3a4 4 0 0 0-3.2 1.6l-.3.4H11a6 6 0 0 0-6 6v1a5 5 0 0 0 2 4v3a1 1 0 0 0 1 1h2a1 1 0 0 0 1-1z" />
|
||||
<path d="M16 10h.01" />
|
||||
<path d="M2 8v1a2 2 0 0 0 2 2h1" /></symbol>
|
||||
<symbol id="i-coins" viewBox="0 0 24 24"><path d="M13.744 17.736a6 6 0 1 1-7.48-7.48" />
|
||||
<path d="M15 6h1v4" />
|
||||
<path d="m6.134 14.768.866-.5 2 3.464" />
|
||||
<circle cx="16" cy="8" r="6" /></symbol>
|
||||
<symbol id="i-bitcoin" viewBox="0 0 24 24"><path d="M11.767 19.089c4.924.868 6.14-6.025 1.216-6.894m-1.216 6.894L5.86 18.047m5.908 1.042-.347 1.97m1.563-8.864c4.924.869 6.14-6.025 1.215-6.893m-1.215 6.893-3.94-.694m5.155-6.2L8.29 4.26m5.908 1.042.348-1.97M7.48 20.364l3.126-17.727" /></symbol>
|
||||
<symbol id="i-line-chart" viewBox="0 0 24 24"><path d="M3 3v16a2 2 0 0 0 2 2h16" />
|
||||
<path d="m19 9-5 5-4-4-3 3" /></symbol>
|
||||
<symbol id="i-pie-chart" viewBox="0 0 24 24"><path d="M21 12c.552 0 1.005-.449.95-.998a10 10 0 0 0-8.953-8.951c-.55-.055-.998.398-.998.95v8a1 1 0 0 0 1 1z" />
|
||||
<path d="M21.21 15.89A10 10 0 1 1 8 2.83" /></symbol>
|
||||
<symbol id="i-bar-chart-3" viewBox="0 0 24 24"><path d="M3 3v16a2 2 0 0 0 2 2h16" />
|
||||
<path d="M18 17V9" />
|
||||
<path d="M13 17V5" />
|
||||
<path d="M8 17v-3" /></symbol>
|
||||
<symbol id="i-lock" viewBox="0 0 24 24"><rect width="18" height="11" x="3" y="11" rx="2" ry="2" />
|
||||
<path d="M7 11V7a5 5 0 0 1 10 0v4" /></symbol>
|
||||
<symbol id="i-link" viewBox="0 0 24 24"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71" />
|
||||
<path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71" /></symbol>
|
||||
<symbol id="i-file-up" viewBox="0 0 24 24"><path d="M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z" />
|
||||
<path d="M14 2v5a1 1 0 0 0 1 1h5" />
|
||||
<path d="M12 12v6" />
|
||||
<path d="m15 15-3-3-3 3" /></symbol>
|
||||
<symbol id="i-circle-alert" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10" />
|
||||
<line x1="12" x2="12" y1="8" y2="12" />
|
||||
<line x1="12" x2="12.01" y1="16" y2="16" /></symbol>
|
||||
<symbol id="i-eye-off" viewBox="0 0 24 24"><path d="M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49" />
|
||||
<path d="M14.084 14.158a3 3 0 0 1-4.242-4.242" />
|
||||
<path d="M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143" />
|
||||
<path d="m2 2 20 20" /></symbol>
|
||||
<symbol id="i-building-2" viewBox="0 0 24 24"><path d="M10 12h4" />
|
||||
<path d="M10 8h4" />
|
||||
<path d="M14 21v-3a2 2 0 0 0-4 0v3" />
|
||||
<path d="M6 10H4a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-2" />
|
||||
<path d="M6 21V5a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v16" /></symbol>
|
||||
<symbol id="i-credit-card" viewBox="0 0 24 24"><rect width="20" height="14" x="2" y="5" rx="2" />
|
||||
<line x1="2" x2="22" y1="10" y2="10" />
|
||||
<path d="M6 14h2" /></symbol>
|
||||
<symbol id="i-banknote" viewBox="0 0 24 24"><rect width="20" height="12" x="2" y="6" rx="2" />
|
||||
<circle cx="12" cy="12" r="2" />
|
||||
<path d="M6 12h.01M18 12h.01" /></symbol>
|
||||
<symbol id="i-scale" viewBox="0 0 24 24"><path d="M12 3v18" />
|
||||
<path d="m19 8 3 8a5 5 0 0 1-6 0zV7" />
|
||||
<path d="M3 7h1a17 17 0 0 0 8-2 17 17 0 0 0 8 2h1" />
|
||||
<path d="m5 8 3 8a5 5 0 0 1-6 0zV7" />
|
||||
<path d="M7 21h10" /></symbol>
|
||||
<symbol id="i-clock" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10" />
|
||||
<path d="M12 6v6l4 2" /></symbol>
|
||||
<symbol id="i-menu" viewBox="0 0 24 24"><path d="M4 5h16" />
|
||||
<path d="M4 12h16" />
|
||||
<path d="M4 19h16" /></symbol>
|
||||
<symbol id="i-filter" viewBox="0 0 24 24"><path d="M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z" /></symbol>
|
||||
<symbol id="i-download" viewBox="0 0 24 24"><path d="M12 15V3" />
|
||||
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
|
||||
<path d="m7 10 5 5 5-5" /></symbol>
|
||||
<symbol id="i-sparkles" viewBox="0 0 24 24"><path d="M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z" />
|
||||
<path d="M20 2v4" />
|
||||
<path d="M22 4h-4" />
|
||||
<circle cx="4" cy="20" r="2" /></symbol>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 10 KiB |
@@ -0,0 +1,73 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
||||
<meta name="robots" content="noindex">
|
||||
<title>{% block title %}Finance{% endblock %} · Finance</title>
|
||||
<script>try{var t=localStorage.getItem("theme");if(t==="dark"||t==="light")document.documentElement.dataset.theme=t;}catch(e){}</script>
|
||||
<link rel="stylesheet" href="/static/style.css">
|
||||
<script src="/static/chart.umd.min.js" defer></script>
|
||||
<script src="/static/app.js" defer></script>
|
||||
</head>
|
||||
<body>
|
||||
{% include "_icons.svg" %}
|
||||
{% set path = request.url.path %}
|
||||
{% macro navlink(href, ico, label, active, count=0) -%}
|
||||
<a href="{{ href }}" class="nav-link {{ 'active' if active }}">{{ icon(ico) }}<span>{{ label }}</span>{% if count %}<span class="nav-count">{{ count }}</span>{% endif %}</a>
|
||||
{%- endmacro %}
|
||||
|
||||
<div class="layout">
|
||||
<nav class="side" aria-label="Main">
|
||||
<div class="brand"><span class="logo">{{ icon('wallet') }}</span> Finance</div>
|
||||
|
||||
<div class="nav-section">Overview</div>
|
||||
{{ navlink('/', 'layout-dashboard', 'Dashboard', path == '/') }}
|
||||
{{ navlink('/transactions', 'receipt', 'Transactions', path.startswith('/transactions')) }}
|
||||
{{ navlink('/recurring', 'repeat', 'Recurring', path.startswith('/recurring'), nav_missed) }}
|
||||
|
||||
<div class="nav-section">Wealth</div>
|
||||
{{ navlink('/investments', 'trending-up', 'Investments', path.startswith('/investments')) }}
|
||||
{{ navlink('/gold', 'gem', 'Gold', path.startswith('/gold')) }}
|
||||
{{ navlink('/debts', 'handshake', 'Debts', path.startswith('/debts')) }}
|
||||
|
||||
<div class="nav-section">Data</div>
|
||||
{{ navlink('/import', 'upload', 'Import', path.startswith('/import')) }}
|
||||
{{ navlink('/settings', 'settings', 'Settings', path.startswith('/settings')) }}
|
||||
|
||||
<div class="nav-foot">
|
||||
<div class="theme-toggle" role="group" aria-label="Theme">
|
||||
<button type="button" data-theme-set="auto" title="Follow system">{{ icon('monitor', 'sm') }}</button>
|
||||
<button type="button" data-theme-set="light" title="Light">{{ icon('sun', 'sm') }}</button>
|
||||
<button type="button" data-theme-set="dark" title="Dark">{{ icon('moon', 'sm') }}</button>
|
||||
</div>
|
||||
<div class="user-chip">
|
||||
<span class="avatar">{{ (user or 'Me')[:1]|upper }}</span>
|
||||
<span class="who">{{ user or 'Signed in' }}</span>
|
||||
<a href="/outpost.goauthentik.io/sign_out" title="Sign out">{{ icon('log-out', 'sm') }}</a>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
<div class="scrim" data-nav-close></div>
|
||||
|
||||
<div style="min-width:0">
|
||||
<header class="topbar">
|
||||
<button class="icon-btn" data-nav-toggle aria-label="Menu">{{ icon('menu') }}</button>
|
||||
<div class="brand"><span class="logo">{{ icon('wallet', 'sm') }}</span> Finance</div>
|
||||
</header>
|
||||
<main>
|
||||
{% if msg %}<div class="flash">{{ icon('circle-alert') }}<span>{{ msg }}</span></div>{% endif %}
|
||||
{% block content %}{% endblock %}
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<nav class="tabbar" aria-label="Quick">
|
||||
<a href="/" class="{{ 'active' if path == '/' }}">{{ icon('layout-dashboard') }}Home</a>
|
||||
<a href="/transactions" class="{{ 'active' if path.startswith('/transactions') }}">{{ icon('receipt') }}Activity</a>
|
||||
<a href="/recurring" class="{{ 'active' if path.startswith('/recurring') }}">{{ icon('repeat') }}Recurring{% if nav_missed %}<span class="dot-count"></span>{% endif %}</a>
|
||||
<a href="/investments" class="{{ 'active' if path.startswith('/investments') or path.startswith('/gold') }}">{{ icon('trending-up') }}Wealth</a>
|
||||
<a href="/debts" class="{{ 'active' if path.startswith('/debts') }}">{{ icon('handshake') }}Debts</a>
|
||||
</nav>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,146 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Dashboard{% endblock %}
|
||||
{% block content %}
|
||||
{% set acc_q = '&account=%s' % account if account else '' %}
|
||||
<div class="page-head">
|
||||
<div>
|
||||
<h1>Dashboard</h1>
|
||||
<div class="sub">{{ start.strftime('%B %Y') }} · <span class="live-status"></span></div>
|
||||
</div>
|
||||
<form class="actions" method="get">
|
||||
{% if start.strftime('%Y-%m') != today().strftime('%Y-%m') %}<input type="hidden" name="month" value="{{ start.strftime('%Y-%m') }}">{% endif %}
|
||||
<select name="account" data-autosubmit aria-label="Account">
|
||||
<option value="">All accounts</option>
|
||||
{% for a in accounts %}<option value="{{ a.id }}" {{ 'selected' if account == a.id }}>{{ a.name }}</option>{% endfor %}
|
||||
</select>
|
||||
<div class="seg">
|
||||
<a href="?month={{ prev_month }}{{ acc_q }}" title="Previous month">{{ icon('chevron-left', 'sm') }}</a>
|
||||
<a class="on" href="?{{ acc_q[1:] }}">{{ start.strftime('%b %Y') }}</a>
|
||||
{% if next_month %}<a href="?month={{ next_month }}{{ acc_q }}" title="Next month">{{ icon('chevron-right', 'sm') }}</a>{% endif %}
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
{% if missed %}
|
||||
<div class="card alert mb">
|
||||
<div class="card-head"><h2>{{ icon('alert-triangle') }} {{ missed|length }} missed recurring payment{{ 's' if missed|length > 1 }}</h2>
|
||||
<a class="btn secondary sm" href="/recurring">Review</a></div>
|
||||
<ul class="list">
|
||||
{% for r in missed %}
|
||||
<li><span><strong>{{ r.name }}</strong> <span class="muted small">· {{ r.frequency }} · expected {{ r.next_date.strftime('%d %b') }} ({{ (today() - r.next_date).days }} days ago)</span></span>
|
||||
<span class="num">{{ r.amount|eur }}</span></li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<div class="grid cols-4 mb">
|
||||
<div class="card kpi">
|
||||
<div class="kpi-ico tint-accent">{{ icon('wallet') }}</div>
|
||||
<div class="label">Net worth</div>
|
||||
<div class="value" data-live="net_worth" data-fmt="eur0">{{ net_worth|eur(0) }}</div>
|
||||
<div class="sub">Cash <span data-live="cash" data-fmt="eur0">{{ cash|eur(0) }}</span> · Invested <span data-live="all_value" data-fmt="eur0">{{ invest_value|eur(0) }}</span></div>
|
||||
</div>
|
||||
<div class="card kpi">
|
||||
<div class="kpi-ico tint-bad">{{ icon('shopping-cart') }}</div>
|
||||
<div class="label">Spent in {{ start.strftime('%B') }}</div>
|
||||
<div class="value" data-live="spent" data-fmt="eur0">{{ cur.expense|eur(0) }}</div>
|
||||
<div class="sub">Income <span data-live="income" data-fmt="eur0">{{ cur.income|eur(0) }}</span> ·
|
||||
<span class="delta {{ 'good' if cur.income - cur.expense >= 0 else 'bad' }}" data-live="net_month" data-fmt="eur0s" data-color>{{ (cur.income - cur.expense)|eur(0, true) }}</span></div>
|
||||
</div>
|
||||
<div class="card kpi">
|
||||
{% set a = pt.get('all') %}
|
||||
<div class="kpi-ico tint-good">{{ icon('trending-up') }}</div>
|
||||
<div class="label">Investments + gold</div>
|
||||
<div class="value" data-live="all_value" data-fmt="eur0">{{ (a.value if a else 0)|eur(0) }}</div>
|
||||
<div class="sub">{% if a %}Paid <span data-live="all_cost" data-fmt="eur0">{{ a.cost|eur(0) }}</span> ·
|
||||
<span class="delta {{ 'good' if a.pnl >= 0 else 'bad' }}" data-live="all_pnl_pct" data-fmt="pct" data-color>{{ a.pnl_pct|pct }}</span>{% else %}<a href="/investments">Add holdings</a>{% endif %}</div>
|
||||
</div>
|
||||
<div class="card kpi">
|
||||
<div class="kpi-ico tint-warn">{{ icon('handshake') }}</div>
|
||||
<div class="label">Debts (net)</div>
|
||||
<div class="value" data-live="debt_net" data-fmt="eur0s">{{ (owed - i_owe)|eur(0, true) }}</div>
|
||||
<div class="sub">I owe <span data-live="i_owe" data-fmt="eur0">{{ i_owe|eur(0) }}</span> · Owed to me <span data-live="owed" data-fmt="eur0">{{ owed|eur(0) }}</span></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid cols-3 mb">
|
||||
<div class="card span-2">
|
||||
<div class="card-head">
|
||||
<h2>{{ icon('bar-chart-3') }} Income vs expenses</h2>
|
||||
<span class="small muted">Click a month to open it</span>
|
||||
</div>
|
||||
<div class="chart-box tall"><canvas data-chart="months" data-link="?month={label}{{ acc_q }}"
|
||||
data-json='{{ {"labels": charts.months.labels, "income": charts.months.income, "expense": charts.months.expense, "current": start.strftime("%Y-%m")}|tojson }}'></canvas></div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<div class="card-head"><h2>{{ icon('pie-chart') }} Spending · {{ start.strftime('%b') }}</h2></div>
|
||||
{% if cats %}
|
||||
<div class="chart-box sm"><canvas data-chart="donut" data-legend="cat-legend" data-center="spent"
|
||||
data-json='{{ {"labels": charts.cats.labels, "data": charts.cats.data, "colors": charts.cats.colors,
|
||||
"links": charts.cats.links}|tojson }}'></canvas></div>
|
||||
<div class="legend" id="cat-legend" style="margin-top:.6rem"></div>
|
||||
{% else %}<div class="empty">{{ icon('pie-chart') }}<br>No spending this month yet.</div>{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid cols-3 mb">
|
||||
<div class="card">
|
||||
<div class="card-head"><h2>{{ icon('receipt') }} Top categories</h2>
|
||||
{% if uncategorised %}<a class="badge warn" href="/transactions?category=none">{{ uncategorised }} uncategorised</a>{% endif %}</div>
|
||||
<ul class="list">
|
||||
{% set top = cats[0].total if cats else 1 %}
|
||||
{% for c in cats[:8] %}
|
||||
<li style="display:block">
|
||||
<div class="row spread"><a class="cat" href="/transactions?month={{ start.strftime('%Y-%m') }}&category={{ c.id if c.id else 'none' }}{{ acc_q }}"><span class="dot" style="background:{{ c.color }}"></span>{{ c.name }} <span class="muted small" style="margin-left:.35rem">{{ c.count }}×</span></a>
|
||||
<span class="num">{{ c.total|eur }}</span></div>
|
||||
<div class="bar"><div style="width:{{ (c.total / top * 100)|round(1) }}%; background:{{ c.color }}"></div></div>
|
||||
</li>
|
||||
{% else %}<li class="empty" style="display:block">Nothing yet. <a href="/import">Import a statement</a>.</li>{% endfor %}
|
||||
</ul>
|
||||
</div>
|
||||
<div class="card">
|
||||
<div class="card-head"><h2>{{ icon('calendar-clock') }} Coming up</h2><a class="small" href="/recurring">All recurring</a></div>
|
||||
<ul class="list">
|
||||
{% for r in due %}<li><span class="cell-main"><span class="tx-ico tint-accent">{{ icon('repeat', 'sm') }}</span>
|
||||
<span><strong>{{ r.name }}</strong><br><span class="muted small">{{ r.next_date.strftime('%a %d %b') }}</span></span></span><span class="num">{{ r.amount|eur }}</span></li>
|
||||
{% else %}<li class="muted">Nothing due in the next 7 days.</li>{% endfor %}
|
||||
</ul>
|
||||
<p class="small muted" style="margin:.8rem 0 0">Fixed costs ≈ <strong style="color:var(--text)">{{ subs_month|eur }}</strong> per month</p>
|
||||
</div>
|
||||
<div class="card">
|
||||
<div class="card-head"><h2>{{ icon('landmark') }} Accounts</h2><a class="small" href="/import">Import</a></div>
|
||||
<ul class="list">
|
||||
{% for a in accounts %}<li><span class="cell-main"><span class="tx-ico tint-accent">{{ icon('credit-card' if a.bank == 'revolut' else 'building-2', 'sm') }}</span>
|
||||
<span><strong>{{ a.name }}</strong>{% if a.share_pct < 100 %} <span class="badge accent">{{ a.share_pct }}% mine</span>{% endif %}
|
||||
<br><span class="muted small">{{ 'Updated ' + a.balance_date.strftime('%d %b') if a.balance_date else 'No balance yet' }}</span></span></span>
|
||||
<span class="num" data-live="acc{{ a.id }}_balance" data-fmt="eur">{{ a.balance|eur }}</span></li>
|
||||
{% else %}<li class="muted">No accounts yet.</li>{% endfor %}
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid cols-3">
|
||||
<div class="card span-2">
|
||||
<div class="card-head"><h2>{{ icon('line-chart') }} Portfolio value vs paid</h2>
|
||||
<div class="seg" data-range-for="pf-history">
|
||||
<button type="button" data-days="30">1M</button><button type="button" data-days="90">3M</button>
|
||||
<button type="button" data-days="180">6M</button><button type="button" data-days="365" class="on">1Y</button><button type="button" data-days="0">All</button>
|
||||
</div></div>
|
||||
{% if charts.portfolio.labels %}
|
||||
<div class="chart-box"><canvas id="pf-history" data-chart="history" data-json='{{ charts.portfolio|tojson }}'></canvas></div>
|
||||
{% else %}<div class="empty">{{ icon('line-chart') }}<br>History builds up automatically once you add holdings.</div>{% endif %}
|
||||
</div>
|
||||
<div class="card">
|
||||
<div class="card-head"><h2>{{ icon('handshake') }} Debts</h2><a class="small" href="/debts">Manage</a></div>
|
||||
<ul class="list">
|
||||
{% for x, s in dstat %}<li style="display:block">
|
||||
<div class="row spread"><span><a href="/debts/{{ x.id }}"><strong>{{ x.name }}</strong></a>
|
||||
<span class="badge {{ 'bad' if s.status == 'behind' else ('good' if s.status in ('ahead','on track') else '') }}">{{ s.status }}</span></span>
|
||||
<span class="num {{ 'bad' if x.direction == 'i_owe' else 'good' }}" data-live="d{{ x.id }}_remaining" data-fmt="eur0">{{ s.remaining|eur(0) }}</span></div>
|
||||
<div class="progress" style="margin-top:.45rem"><div style="width:{{ [s.pct, 100]|min }}%"></div></div>
|
||||
</li>{% else %}<li class="muted">No open debts.</li>{% endfor %}
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,52 @@
|
||||
{% extends "base.html" %}
|
||||
{% from "_debt_form.html" import debt_form with context %}
|
||||
{% block title %}{{ d.name }}{% endblock %}
|
||||
{% block content %}
|
||||
<p><a class="btn ghost sm" href="/debts">{{ icon('chevron-left', 'sm') }} All debts</a></p>
|
||||
<div class="page-head">
|
||||
<h1>{{ d.name }} <span class="badge">{{ 'I owe' if d.direction == 'i_owe' else 'owed to me' }}</span>
|
||||
{% if d.closed %}<span class="badge">closed</span>{% endif %}</h1>
|
||||
<div class="actions">
|
||||
{% if d.match_pattern %}<form method="post" action="/debts/{{ d.id }}/rematch"><button class="secondary sm">{{ icon('link', 'sm') }} Re-match bank</button></form>{% endif %}
|
||||
<form method="post" action="/debts/{{ d.id }}/toggle"><button class="secondary sm">{{ 'Re-open' if d.closed else 'Close' }}</button></form>
|
||||
<form method="post" action="/debts/{{ d.id }}/delete" data-confirm="Delete this debt and its payment history?"><button class="danger sm">{{ icon('trash-2', 'sm') }} Delete</button></form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid cols-4 mb">
|
||||
<div class="card kpi"><div class="label">Remaining</div><div class="value">{{ s.remaining|eur }}</div><div class="sub">of {{ d.principal|eur }}</div></div>
|
||||
<div class="card kpi"><div class="label">Paid</div><div class="value">{{ s.paid|eur }}</div>
|
||||
<div class="progress"><div style="width:{{ [s.pct,100]|min }}%"></div></div></div>
|
||||
<div class="card kpi"><div class="label">Status</div>
|
||||
<div class="value {{ 'bad' if s.status == 'behind' else 'good' }}">{{ s.status }}</div>
|
||||
<div class="sub">{% 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 %}</div></div>
|
||||
<div class="card kpi"><div class="label">Next due</div><div class="value">{{ s.next_due.strftime('%d %b') if s.next_due else '—' }}</div>
|
||||
<div class="sub">{{ 'paid off ≈ ' + s.payoff.strftime('%b %Y') if s.payoff }}</div></div>
|
||||
</div>
|
||||
|
||||
<div class="grid cols-2">
|
||||
<div class="card">
|
||||
<h2>{{ icon('banknote') }} Payments</h2>
|
||||
<form method="post" action="/debts/{{ d.id }}/payment" class="row mb">
|
||||
<input type="date" name="date" value="{{ today().isoformat() }}">
|
||||
<input name="amount" inputmode="decimal" placeholder="€" required style="width:110px">
|
||||
<input name="notes" placeholder="note" style="width:140px">
|
||||
<button class="sm">{{ icon('plus', 'sm') }} Add payment</button>
|
||||
</form>
|
||||
<div class="table-wrap"><table>
|
||||
<thead><tr><th>Date</th><th class="num">Amount</th><th class="num">Balance after</th><th>Note</th><th></th></tr></thead>
|
||||
<tbody>
|
||||
{% for p, bal in running %}
|
||||
<tr><td>{{ p.date.strftime('%d-%m-%Y') }}</td><td class="num">{{ p.amount|eur }}</td><td class="num">{{ bal|eur }}</td>
|
||||
<td class="small">{{ p.notes }}{% if p.transaction_id %} <span class="badge accent" title="Matched from bank">{{ icon('landmark', 'sm') }} bank</span>{% endif %}</td>
|
||||
<td><form method="post" action="/payments/{{ p.id }}/delete" data-confirm="Remove this payment?"><button class="sm ghost icon" title="Remove">{{ icon('trash-2', 'sm') }}</button></form></td></tr>
|
||||
{% else %}<tr><td colspan="5" class="muted">No payments yet.</td></tr>{% endfor %}
|
||||
</tbody>
|
||||
</table></div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h2>{{ icon('pencil') }} Details</h2>
|
||||
{{ debt_form(d) }}
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,49 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Debts{% endblock %}
|
||||
{% from "_debt_form.html" import debt_form with context %}
|
||||
|
||||
{% block content %}
|
||||
<div class="page-head"><div><h1>Debts</h1><div class="sub">What you owe and what others owe you</div></div>
|
||||
<div class="actions"><a class="btn" href="#add-debt" onclick="document.getElementById('add-debt').open=true">{{ icon('plus', 'sm') }} Add debt</a></div></div>
|
||||
<div class="grid cols-3 mb">
|
||||
<div class="card kpi"><div class="kpi-ico tint-bad">{{ icon('arrow-up-right') }}</div><div class="label">I owe</div><div class="value bad" data-live="i_owe" data-fmt="eur">{{ sums.i_owe|eur }}</div></div>
|
||||
<div class="card kpi"><div class="kpi-ico tint-good">{{ icon('arrow-down-right') }}</div><div class="label">Owed to me</div><div class="value good" data-live="owed" data-fmt="eur">{{ sums.owed_to_me|eur }}</div></div>
|
||||
<div class="card kpi"><div class="kpi-ico tint-accent">{{ icon('scale') }}</div><div class="label">Net</div><div class="value" data-live="debt_net" data-fmt="eurs">{{ (sums.owed_to_me - sums.i_owe)|eur(2, true) }}</div></div>
|
||||
</div>
|
||||
|
||||
{% for dir, label in [('i_owe', 'Debts I have'), ('owed_to_me', 'Money people owe me')] %}
|
||||
<div class="card mb">
|
||||
<h2>{{ icon('landmark' if dir == 'i_owe' else 'handshake') }} {{ label }}</h2>
|
||||
<div class="table-wrap"><table>
|
||||
<thead><tr><th>Name</th><th>Status</th><th style="min-width:140px">Progress</th><th class="num">Total</th><th class="num">Paid</th><th class="num">Remaining</th>
|
||||
<th class="num">Monthly</th><th>Next due</th><th>Last payment</th><th>Paid off ≈</th></tr></thead>
|
||||
<tbody>
|
||||
{% for x, s in debts if x.direction == dir %}
|
||||
<tr>
|
||||
<td><a href="/debts/{{ x.id }}"><strong>{{ x.name }}</strong></a><div class="desc">{{ x.counterparty }}</div></td>
|
||||
<td>{% set cls = {'behind':'bad','on track':'good','ahead':'good','paid off':'good'}.get(s.status, '') %}
|
||||
<span class="badge {{ cls }}">{{ s.status }}{% if s.missed %} · {{ s.missed }} missed{% endif %}</span></td>
|
||||
<td><div class="progress"><div style="width:{{ [s.pct, 100]|min }}%"></div></div><span class="small muted">{{ '%.0f'|format(s.pct) }}%</span></td>
|
||||
<td class="num">{{ x.principal|eur }}</td>
|
||||
<td class="num" data-live="d{{ x.id }}_paid" data-fmt="eur">{{ s.paid|eur }}</td>
|
||||
<td class="num"><strong data-live="d{{ x.id }}_remaining" data-fmt="eur">{{ s.remaining|eur }}</strong></td>
|
||||
<td class="num">{{ x.monthly_payment|eur if x.monthly_payment else '—' }}</td>
|
||||
<td class="small">{{ s.next_due.strftime('%d-%m-%Y') if s.next_due else '—' }}</td>
|
||||
<td class="small">{{ s.last_payment.strftime('%d-%m-%Y') if s.last_payment else 'never' }}</td>
|
||||
<td class="small">{{ s.payoff.strftime('%b %Y') if s.payoff else '—' }}</td>
|
||||
</tr>
|
||||
{% else %}<tr><td colspan="10" class="muted">None.</td></tr>{% endfor %}
|
||||
</tbody>
|
||||
</table></div>
|
||||
</div>
|
||||
{% endfor %}
|
||||
|
||||
<p><a href="?show_closed={{ 0 if show_closed else 1 }}">{{ 'Hide' if show_closed else 'Show' }} closed debts</a></p>
|
||||
|
||||
<details class="card" id="add-debt" {{ 'open' if not debts }}>
|
||||
<summary>{{ icon('plus') }} Add a debt</summary>
|
||||
{{ debt_form() }}
|
||||
<p class="small muted">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).</p>
|
||||
</details>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,48 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Import{% endblock %}
|
||||
{% block content %}
|
||||
<div class="page-head"><div><h1>Import statements</h1><div class="sub">ING (NL) and Revolut CSV exports · duplicates are skipped automatically</div></div></div>
|
||||
<div class="grid cols-2">
|
||||
<form class="card" method="post" enctype="multipart/form-data">
|
||||
<h2>{{ icon('file-up') }} Upload CSV files</h2>
|
||||
<p class="muted small">You can select several files at once. Re-importing overlapping periods is safe: duplicates are skipped.</p>
|
||||
<div class="form-grid" style="grid-template-columns:1fr">
|
||||
<label>Files<input type="file" name="files" accept=".csv,text/csv" multiple required></label>
|
||||
<label>Account
|
||||
<select name="account_id">
|
||||
<option value="auto">Auto-detect (ING uses the IBAN in the file; Revolut goes to your Revolut account)</option>
|
||||
{% for a in accounts %}<option value="{{ a.id }}">{{ a.name }}{{ ' · ' + a.iban if a.iban }}</option>{% endfor %}
|
||||
</select></label>
|
||||
<div><button>{{ icon('upload', 'sm') }} Import</button></div>
|
||||
</div>
|
||||
</form>
|
||||
<div class="card">
|
||||
<h2>{{ icon('download') }} Where to get the files</h2>
|
||||
<p><strong>ING (main and shared):</strong> Mijn ING → account → <em>Af- en bijschrijvingen downloaden</em> → format
|
||||
<em>Kommagescheiden CSV</em> or <em>Puntkomma-gescheiden</em>, pick a date range. Both formats work, Dutch or English headers.</p>
|
||||
<p><strong>Revolut:</strong> app → account → ⋯ → <em>Statement</em> → <em>Excel</em>/<em>CSV</em>, pick the period. Only completed
|
||||
transactions from the <em>Current</em> account are imported.</p>
|
||||
<p class="muted small">Prefer automatic syncing? Set up Enable Banking under <a href="/settings#bank">Settings</a>.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{% if results %}
|
||||
<div class="card" style="margin-top:1rem">
|
||||
<h2>Result</h2>
|
||||
<div class="table-wrap"><table>
|
||||
<thead><tr><th>File</th><th>Account</th><th class="num">New</th><th class="num">Duplicates</th><th class="num">Skipped</th><th class="num">Debt payments</th></tr></thead>
|
||||
<tbody>
|
||||
{% for r in results %}
|
||||
{% if r.ok %}
|
||||
<tr><td>{{ r.file }} <span class="badge">{{ r.fmt }}</span></td><td>{{ r.account }}</td><td class="num">{{ r.inserted }}</td>
|
||||
<td class="num">{{ r.duplicates }}</td><td class="num">{{ r.skipped }}</td><td class="num">{{ r.debt_payments }}</td></tr>
|
||||
{% else %}
|
||||
<tr><td>{{ r.file }}</td><td colspan="5" class="bad">{{ r.error }}</td></tr>
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table></div>
|
||||
<p><a href="/transactions?category=none">Review uncategorised</a> · <a href="/recurring">Check recurring</a> · <a href="/">Dashboard</a></p>
|
||||
</div>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
@@ -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 %}
|
||||
<div class="page-head">
|
||||
<div><h1>{{ title }}</h1>
|
||||
<div class="sub">{{ 'Physical gold valued at live spot price' if is_gold else 'Stocks, ETFs and crypto at live prices' }} · <span class="live-status"></span></div></div>
|
||||
<div class="actions">
|
||||
<a class="btn secondary" href="#add-trade">{{ icon('plus', 'sm') }} {{ 'Purchase' if is_gold else 'Trade' }}</a>
|
||||
<form method="post" action="/prices/refresh" data-ajax-refresh><button>{{ icon('refresh-cw', 'sm') }}<span> Refresh prices</span></button></form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid cols-4 mb">
|
||||
{% set a = t.get('all') %}
|
||||
<div class="card kpi"><div class="kpi-ico tint-accent">{{ icon('gem' if is_gold else 'line-chart') }}</div><div class="label">Current value</div><div class="value" data-live="{{ P }}_value" data-fmt="eur">{{ (a.value if a else 0)|eur }}</div>
|
||||
<div class="sub">{% if a and a.missing_price %}<span class="warn">{{ a.missing_price }} without price (counted at cost)</span>{% else %}live prices{% endif %}</div></div>
|
||||
<div class="card kpi"><div class="kpi-ico tint-warn">{{ icon('banknote') }}</div><div class="label">Paid</div><div class="value" data-live="{{ P }}_cost" data-fmt="eur">{{ (a.cost if a else 0)|eur }}</div><div class="sub">incl. fees, open positions</div></div>
|
||||
<div class="card kpi"><div class="kpi-ico {{ 'tint-good' if a and a.pnl >= 0 else 'tint-bad' }}">{{ icon('arrow-up-right' if a and a.pnl >= 0 else 'arrow-down-right') }}</div><div class="label">Unrealised P/L</div>
|
||||
<div class="value {{ 'good' if a and a.pnl >= 0 else 'bad' }}" data-live="{{ P }}_pnl" data-fmt="eurs" data-color>{{ (a.pnl if a else 0)|eur(2, true) }}</div><div class="sub" data-live="{{ P }}_pnl_pct" data-fmt="pct">{{ (a.pnl_pct if a else None)|pct }}</div></div>
|
||||
<div class="card kpi"><div class="kpi-ico tint-accent">{{ icon('check') }}</div><div class="label">Realised P/L</div><div class="value" data-live="{{ P }}_realized" data-fmt="eurs">{{ (a.realized if a else 0)|eur(2, true) }}</div><div class="sub">from sells</div></div>
|
||||
</div>
|
||||
|
||||
{% if not is_gold %}
|
||||
<div class="grid cols-2 mb">
|
||||
{% for k, label in [('stock','Stocks & ETFs'),('crypto','Crypto')] %}{% set x = t.get(k) %}
|
||||
<div class="card kpi"><div class="kpi-ico tint-accent">{{ icon('bitcoin' if k == 'crypto' else 'bar-chart-3') }}</div><div class="label">{{ label }}</div>
|
||||
<div class="value" data-live="{{ k }}_value" data-fmt="eur">{{ (x.value if x else 0)|eur }}</div>
|
||||
<div class="sub">paid <span data-live="{{ k }}_cost" data-fmt="eur">{{ (x.cost if x else 0)|eur }}</span> · <span data-live="{{ k }}_pnl" data-fmt="eurs" data-color class="{{ 'good' if x and x.pnl >= 0 else 'bad' }}">{{ (x.pnl if x else 0)|eur(2, true) }}</span> (<span data-live="{{ k }}_pnl_pct" data-fmt="pct" data-color>{{ (x.pnl_pct if x else None)|pct }}</span>)</div></div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<div class="card mb">
|
||||
<h2>{{ icon('coins') }} Holdings</h2>
|
||||
<div class="table-wrap"><table>
|
||||
<thead><tr><th>Asset</th>{% if not is_gold %}<th>Type</th>{% endif %}<th class="num">Quantity</th>{% if is_gold %}<th class="num">Fine gold</th>{% endif %}
|
||||
<th class="num">Avg paid</th><th class="num">Price</th><th class="num">Paid</th><th class="num">Value</th><th class="num">P/L</th><th class="num">%</th><th></th></tr></thead>
|
||||
<tbody>
|
||||
{% for r in rows %}{% set as = r.asset %}
|
||||
<tr>
|
||||
<td><strong>{{ as.name }}</strong><div class="desc">{{ as.symbol }}{% if as.price_error %} · <span class="bad" title="{{ as.price_error }}">price error</span>{% endif %}
|
||||
{% if as.manual_price is not none %} · <span class="warn">manual price</span>{% elif as.last_price_at %} · {{ as.last_price_at.strftime('%d-%m %H:%M') }}{% endif %}</div></td>
|
||||
{% if not is_gold %}<td><span class="badge">{{ as.kind }}</span></td>{% endif %}
|
||||
<td class="num">{{ r.qty|num }} {{ as.unit if as.unit != 'unit' }}{% if is_gold and as.purity != 1 %} <span class="muted small">@{{ as.purity|num }}</span>{% endif %}</td>
|
||||
{% if is_gold %}<td class="num">{{ r.grams|num(2) }} g</td>{% endif %}
|
||||
<td class="num">{{ r.avg|eur }}</td>
|
||||
<td class="num" data-live="a{{ as.id }}_price" data-fmt="eur">{{ r.price|eur }}</td>
|
||||
<td class="num">{{ r.cost|eur }}</td>
|
||||
<td class="num"><strong data-live="a{{ as.id }}_value" data-fmt="eur">{{ r.value|eur }}</strong></td>
|
||||
<td class="num {{ 'good' if r.pnl and r.pnl >= 0 else 'bad' }}" data-live="a{{ as.id }}_pnl" data-fmt="eurs" data-color>{{ r.pnl|eur(2, true) }}</td>
|
||||
<td class="num {{ 'good' if r.pnl and r.pnl >= 0 else 'bad' }}" data-live="a{{ as.id }}_pnl_pct" data-fmt="pct" data-color>{{ r.pnl_pct|pct }}</td>
|
||||
<td style="white-space:nowrap">
|
||||
<details><summary class="small muted">{{ icon('pencil', 'sm') }}</summary>
|
||||
<form method="post" action="/assets/{{ as.id }}/update" class="row small" style="margin:.4rem 0">
|
||||
<input name="symbol" value="{{ as.symbol }}" style="width:110px" title="Ticker / CoinGecko id">
|
||||
<input name="manual_price" value="{{ as.manual_price if as.manual_price is not none else '' }}" placeholder="manual €/unit" style="width:110px">
|
||||
<button class="sm">Save</button></form>
|
||||
<form method="post" action="/assets/{{ as.id }}/delete" data-confirm="Delete {{ as.name }} and all its trades?"><button class="sm danger">Delete</button></form>
|
||||
</details></td>
|
||||
</tr>
|
||||
{% else %}<tr><td colspan="11" class="muted">No holdings yet. Add an asset below, then record your purchases.</td></tr>{% endfor %}
|
||||
</tbody>
|
||||
</table></div>
|
||||
</div>
|
||||
|
||||
<div class="grid cols-3 mb">
|
||||
<div class="card span-2">
|
||||
<div class="card-head"><h2>{{ icon('line-chart') }} Value vs paid</h2>
|
||||
<div class="seg" data-range-for="inv-history">
|
||||
<button type="button" data-days="30">1M</button><button type="button" data-days="90">3M</button>
|
||||
<button type="button" data-days="180">6M</button><button type="button" data-days="365" class="on">1Y</button><button type="button" data-days="0">All</button>
|
||||
</div></div>
|
||||
{% if chart.labels %}
|
||||
<div class="chart-box tall"><canvas id="inv-history" data-chart="history" data-json='{{ {"labels": chart.labels, "value": chart.value, "cost": chart.cost}|tojson }}'></canvas></div>
|
||||
{% else %}<div class="empty">{{ icon('line-chart') }}<br>A data point is stored each time prices refresh.</div>{% endif %}
|
||||
</div>
|
||||
<div class="card">
|
||||
<div class="card-head"><h2>{{ icon('pie-chart') }} Allocation</h2></div>
|
||||
{% if chart.alloc_values %}
|
||||
<div class="chart-box sm"><canvas data-chart="donut" data-legend="alloc-legend" data-json='{{ {"labels": chart.alloc_labels, "data": chart.alloc_values}|tojson }}'></canvas></div>
|
||||
<div class="legend" id="alloc-legend" style="margin-top:.6rem"></div>
|
||||
{% else %}<div class="empty">{{ icon('pie-chart') }}<br>No priced holdings yet.</div>{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid cols-2 mb">
|
||||
<form class="card" method="post" action="/trades/add" id="add-trade">
|
||||
<h2>{{ icon('plus') }} Record a {{ 'purchase' if is_gold else 'trade' }}</h2>
|
||||
{% if assets %}
|
||||
<div class="form-grid">
|
||||
<label>Asset<select name="asset_id">{% for as in assets %}<option value="{{ as.id }}">{{ as.name }}</option>{% endfor %}</select></label>
|
||||
<label>Buy / sell<select name="side"><option value="buy">Buy</option><option value="sell">Sell</option></select></label>
|
||||
<label>Date<input type="date" name="date" value="{{ today().isoformat() }}"></label>
|
||||
<label>Quantity{{ ' (grams/oz/pieces)' if is_gold }}<input name="quantity" inputmode="decimal" required></label>
|
||||
<label>Price per unit (€)<input name="price" inputmode="decimal" placeholder="or fill total →"></label>
|
||||
<label>…or total paid (€)<input name="total" inputmode="decimal"></label>
|
||||
<label>Fees (€)<input name="fees" inputmode="decimal" value="0"></label>
|
||||
<label>Note<input name="notes"></label>
|
||||
<div><button>Save</button></div>
|
||||
</div>
|
||||
{% else %}<p class="muted">Add an asset first →</p>{% endif %}
|
||||
</form>
|
||||
|
||||
<form class="card" method="post" action="/assets/add">
|
||||
<h2>{{ icon('sparkles') }} Add an asset</h2>
|
||||
{% if is_gold %}
|
||||
<input type="hidden" name="kind" value="gold">
|
||||
<div class="form-grid">
|
||||
<label>Name<input name="name" required placeholder="Gold bar 100g / Krugerrand"></label>
|
||||
<label>Unit<select name="unit"><option value="gram">gram</option><option value="oz">troy ounce</option></select></label>
|
||||
<label>Purity<select name="purity"><option value="0.9999">24k · 999,9</option><option value="0.9167">22k · 916 (Krugerrand, Sovereign)</option>
|
||||
<option value="0.900">900 (Gulden/Napoleon)</option><option value="0.750">18k · 750</option><option value="0.585">14k · 585</option><option value="0.333">8k · 333</option></select></label>
|
||||
<label>Price source<input name="symbol" value="GC=F" title="Yahoo symbol, USD/oz. GC=F = gold, SI=F = silver"></label>
|
||||
<div><button>Add</button></div>
|
||||
</div>
|
||||
<p class="small muted">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).</p>
|
||||
{% else %}
|
||||
<div class="form-grid">
|
||||
<label>Name<input name="name" required placeholder="Vanguard FTSE All-World"></label>
|
||||
<label>Type<select name="kind"><option value="stock">Stock / ETF</option><option value="crypto">Crypto</option></select></label>
|
||||
<label>Symbol<input name="symbol" required placeholder="VWRL.AS · bitcoin"></label>
|
||||
<div><button>Add</button></div>
|
||||
</div>
|
||||
<p class="small muted"><strong>Stocks/ETFs:</strong> Yahoo Finance ticker incl. exchange suffix (VWRL.AS, IWDA.AS, ASML.AS, AAPL), converted to EUR.
|
||||
<strong>Crypto:</strong> CoinGecko id (bitcoin, ethereum, solana, cardano…) — find it in the coin's URL on coingecko.com.</p>
|
||||
{% endif %}
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h2>{{ icon('clock') }} History</h2>
|
||||
<div class="table-wrap"><table>
|
||||
<thead><tr><th>Date</th><th>Asset</th><th>Side</th><th class="num">Qty</th><th class="num">Price</th><th class="num">Fees</th><th class="num">Total</th><th>Note</th><th></th></tr></thead>
|
||||
<tbody>
|
||||
{% for tr in trades %}
|
||||
<tr><td>{{ tr.date.strftime('%d-%m-%Y') }}</td><td>{{ tr.asset.name }}</td><td><span class="badge {{ 'good' if tr.side == 'buy' else 'warn' }}">{{ tr.side }}</span></td>
|
||||
<td class="num">{{ tr.quantity|num }}</td><td class="num">{{ tr.price|eur }}</td><td class="num">{{ tr.fees|eur }}</td>
|
||||
<td class="num">{{ (tr.quantity * tr.price + (tr.fees if tr.side == 'buy' else -tr.fees))|eur }}</td><td class="small">{{ tr.notes }}</td>
|
||||
<td><form method="post" action="/trades/{{ tr.id }}/delete" data-confirm="Delete this trade?"><button class="sm ghost icon" title="Delete">{{ icon('trash-2', 'sm') }}</button></form></td></tr>
|
||||
{% else %}<tr><td colspan="9" class="muted">No trades yet.</td></tr>{% endfor %}
|
||||
</tbody>
|
||||
</table></div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,63 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Recurring{% endblock %}
|
||||
{% block content %}
|
||||
<div class="page-head">
|
||||
<div><h1>Recurring payments</h1><div class="sub">Subscriptions and fixed costs, detected from your statements</div></div>
|
||||
<div class="actions"><a class="btn secondary" href="#add-recurring">{{ icon('plus', 'sm') }} Add manually</a>
|
||||
<form method="post" action="/recurring/detect"><button>{{ icon('search', 'sm') }} Re-scan</button></form></div>
|
||||
</div>
|
||||
|
||||
<div class="grid cols-3 mb">
|
||||
<div class="card kpi"><div class="kpi-ico tint-accent">{{ icon('calendar-clock') }}</div><div class="label">Fixed costs / month</div><div class="value">{{ out_total|eur }}</div><div class="sub">{{ (out_total*12)|eur(0) }} per year</div></div>
|
||||
<div class="card kpi"><div class="kpi-ico tint-good">{{ icon('piggy-bank') }}</div><div class="label">Recurring income / month</div><div class="value">{{ in_total|eur }}</div><div class="sub">add salary manually below</div></div>
|
||||
<div class="card kpi"><div class="kpi-ico tint-bad">{{ icon('alert-triangle') }}</div><div class="label">Missed</div>
|
||||
{% set ns = namespace(m=0) %}{% for r in recs %}{% if rec_state(r) == 'missed' %}{% set ns.m = ns.m + 1 %}{% endif %}{% endfor %}
|
||||
<div class="value {{ 'bad' if ns.m }}">{{ ns.m }}</div><div class="sub">past expected date + grace period</div></div>
|
||||
</div>
|
||||
|
||||
<div class="card mb">
|
||||
<div class="card-head"><h2>{{ icon('repeat') }} Payments</h2>
|
||||
<div class="seg"><a class="{{ 'on' if show == 'active' }}" href="?show=active">Active</a><a class="{{ 'on' if show == 'ignored' }}" href="?show=ignored">Ignored</a><a class="{{ 'on' if show == 'all' }}" href="?show=all">All</a></div>
|
||||
</div>
|
||||
<div class="table-wrap"><table>
|
||||
<thead><tr><th>Name</th><th>State</th><th>Every</th><th class="num">Amount</th><th class="num">/ month</th><th>Last paid</th><th>Next expected</th><th>Account</th><th></th></tr></thead>
|
||||
<tbody>
|
||||
{% for r in recs %}{% set st = rec_state(r) %}
|
||||
<tr>
|
||||
<td><strong>{{ r.name }}</strong> {% if r.status == 'detected' %}<span class="badge" title="auto-detected, not confirmed yet">new</span>{% endif %}
|
||||
<div class="desc">match: “{{ r.match }}” · {{ r.occurrences }}× {{ '· ' + r.category.name if r.category }}</div></td>
|
||||
<td>{% if st == 'missed' %}<span class="badge bad">missed</span>{% elif st == 'due-soon' %}<span class="badge warn">due soon</span>
|
||||
{% elif st == 'ignored' %}<span class="badge">ignored</span>{% else %}<span class="badge good">ok</span>{% endif %}</td>
|
||||
<td>
|
||||
<form method="post" action="/recurring/{{ r.id }}/update" class="inline">
|
||||
<select name="frequency" data-autosubmit>{% for fq in ['weekly','monthly','quarterly','yearly'] %}<option {{ 'selected' if r.frequency == fq }}>{{ fq }}</option>{% endfor %}</select>
|
||||
</form></td>
|
||||
<td class="num">{{ r.amount|eur }}</td>
|
||||
<td class="num muted">{{ monthly_eq(r)|eur }}</td>
|
||||
<td class="small">{{ r.last_date.strftime('%d-%m-%Y') if r.last_date else '—' }}</td>
|
||||
<td class="small">{{ r.next_date.strftime('%d-%m-%Y') if r.next_date else '—' }}</td>
|
||||
<td class="small">{{ r.account.name if r.account else '' }}</td>
|
||||
<td style="white-space:nowrap">
|
||||
{% if r.status != 'confirmed' %}<form class="inline" method="post" action="/recurring/{{ r.id }}/update"><input type="hidden" name="status" value="confirmed"><button class="sm ghost icon" title="Confirm">{{ icon('check', 'sm') }}</button></form>{% endif %}
|
||||
{% if r.status != 'ignored' %}<form class="inline" method="post" action="/recurring/{{ r.id }}/update"><input type="hidden" name="status" value="ignored"><button class="sm ghost icon" title="Ignore (cancelled / not recurring)">{{ icon('eye-off', 'sm') }}</button></form>{% endif %}
|
||||
<a class="btn ghost sm icon" title="Show transactions" href="/transactions?q={{ r.match|urlencode }}">{{ icon('receipt', 'sm') }}</a>
|
||||
</td>
|
||||
</tr>
|
||||
{% else %}<tr><td colspan="9" class="muted">Nothing detected yet. Import at least 3 months of statements, then re-scan.</td></tr>{% endfor %}
|
||||
</tbody>
|
||||
</table></div>
|
||||
</div>
|
||||
|
||||
<details class="card" id="add-recurring">
|
||||
<summary>{{ icon('plus') }} Add a recurring payment manually <span class="muted small">(rent, salary, yearly insurance…)</span></summary>
|
||||
<form method="post" action="/recurring/add" class="form-grid">
|
||||
<label>Name<input name="name" required placeholder="Rent"></label>
|
||||
<label>Matches counterparty text<input name="match" required placeholder="woonstichting"></label>
|
||||
<label>Direction<select name="direction"><option value="out">Money out</option><option value="in">Money in</option></select></label>
|
||||
<label>Amount (€)<input name="amount" inputmode="decimal" required></label>
|
||||
<label>Frequency<select name="frequency"><option>monthly</option><option>weekly</option><option>quarterly</option><option>yearly</option></select></label>
|
||||
<label>Next due date<input type="date" name="next_date" required></label>
|
||||
<div><button>Add</button></div>
|
||||
</form>
|
||||
</details>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,114 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Settings{% endblock %}
|
||||
{% block content %}
|
||||
<div class="page-head"><div><h1>Settings</h1><div class="sub">Accounts, bank sync, categories and rules</div></div></div>
|
||||
|
||||
<div class="card mb" id="accounts">
|
||||
<h2>{{ icon('landmark') }} Accounts</h2>
|
||||
<p class="small muted">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.</p>
|
||||
<div class="table-wrap"><table>
|
||||
<thead><tr><th>Name</th><th>Bank</th><th>IBAN</th><th>Your share %</th><th class="num">Balance</th><th>Bank sync</th><th></th></tr></thead>
|
||||
<tbody>
|
||||
{% for a in accounts %}
|
||||
<tr>
|
||||
<td><form id="acc{{ a.id }}" method="post" action="/accounts/save"><input type="hidden" name="id" value="{{ a.id }}"></form>
|
||||
<input form="acc{{ a.id }}" name="name" value="{{ a.name }}" required style="width:160px"></td>
|
||||
<td><select form="acc{{ a.id }}" name="bank">{% for b in ['ing','revolut','other'] %}<option {{ 'selected' if a.bank == b }}>{{ b }}</option>{% endfor %}</select></td>
|
||||
<td><input form="acc{{ a.id }}" name="iban" value="{{ a.iban or '' }}" style="width:200px"></td>
|
||||
<td><input form="acc{{ a.id }}" name="share_pct" type="number" min="0" max="100" value="{{ a.share_pct }}" style="width:80px"></td>
|
||||
<td class="num">{{ a.balance|eur }}</td>
|
||||
<td class="small">{{ ('linked · ' + (a.eb_last_sync.strftime('%d-%m %H:%M') if a.eb_last_sync else 'never synced')) if a.eb_account_uid else '—' }}</td>
|
||||
<td style="white-space:nowrap"><button form="acc{{ a.id }}" class="sm">Save</button>
|
||||
<form class="inline" method="post" action="/accounts/{{ a.id }}/delete" data-confirm="Delete {{ a.name }} AND all its transactions?"><button class="sm ghost icon" title="Delete">{{ icon('trash-2', 'sm') }}</button></form></td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
<tr>
|
||||
<td><form id="accnew" method="post" action="/accounts/save"></form><input form="accnew" name="name" required placeholder="ING shared (house)" style="width:160px"></td>
|
||||
<td><select form="accnew" name="bank"><option>ing</option><option>revolut</option><option>other</option></select></td>
|
||||
<td><input form="accnew" name="iban" placeholder="NL00INGB0000000000" style="width:200px"></td>
|
||||
<td><input form="accnew" name="share_pct" type="number" min="0" max="100" value="100" style="width:80px"></td>
|
||||
<td></td><td></td><td><button form="accnew" class="sm">Add</button></td></tr>
|
||||
</tbody>
|
||||
</table></div>
|
||||
</div>
|
||||
|
||||
<div class="card mb" id="bank">
|
||||
<h2>{{ icon('refresh-cw') }} Automatic bank sync (Enable Banking)</h2>
|
||||
{% if eb_configured %}
|
||||
<p class="small">Configured ✓. New transactions are pulled every few hours. Bank consent expires (usually after 90–180 days); reconnect when it does.</p>
|
||||
{% if eb_valid %}<ul class="list small">{% for k, v in eb_valid.items() %}<li><span>{{ k }}</span><span>consent valid until {{ v[:10] }}</span></li>{% endfor %}</ul>{% endif %}
|
||||
<div class="row" style="margin-top:.75rem">
|
||||
<form method="post" action="/eb/connect" class="row">
|
||||
<select name="aspsp" id="aspsp"><option>ING</option><option>Revolut</option></select>
|
||||
<select name="country"><option>NL</option><option>LT</option></select>
|
||||
<button>Connect / renew</button>
|
||||
</form>
|
||||
<form method="post" action="/eb/sync"><button class="secondary">Sync now</button></form>
|
||||
</div>
|
||||
<p class="small muted">Bank names must match Enable Banking's list exactly (<a href="/eb/banks?country=NL" target="_blank">NL list</a>).
|
||||
Revolut may be listed under LT. In free restricted mode, first link the same accounts in the Enable Banking control panel.</p>
|
||||
{% else %}
|
||||
<p class="small">Not configured. You can keep importing CSVs, or enable sync:</p>
|
||||
<ol class="small">
|
||||
<li>Sign up at enablebanking.com and create an application (environment: <em>Production</em>, redirect URL: <code>{{ request.base_url }}eb/callback</code>).</li>
|
||||
<li>Download the private key to <code>./secrets/enablebanking.pem</code> and put the application ID in <code>.env</code> as <code>EB_APP_ID</code>.</li>
|
||||
<li>In the Enable Banking control panel, use <em>Link accounts</em> for ING and Revolut (needed for the free restricted mode).</li>
|
||||
<li><code>docker compose up -d</code>, then come back here and press Connect.</li>
|
||||
</ol>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<div class="grid cols-2">
|
||||
<div class="card" id="categories">
|
||||
<h2>{{ icon('pie-chart') }} Categories</h2>
|
||||
<p class="small muted">Kind “transfer” is excluded from income/expense totals (own-account moves, investing, savings).</p>
|
||||
<div class="table-wrap"><table>
|
||||
<thead><tr><th></th><th>Name</th><th>Kind</th><th class="num">Txns</th><th></th></tr></thead>
|
||||
<tbody>
|
||||
{% for c in categories %}
|
||||
<tr>
|
||||
<td><form id="cat{{ c.id }}" method="post" action="/categories/save"><input type="hidden" name="id" value="{{ c.id }}"></form>
|
||||
<input form="cat{{ c.id }}" type="color" name="color" value="{{ c.color }}"></td>
|
||||
<td><input form="cat{{ c.id }}" name="name" value="{{ c.name }}" style="width:140px"></td>
|
||||
<td><select form="cat{{ c.id }}" name="kind">{% for k in ['expense','income','transfer'] %}<option {{ 'selected' if c.kind == k }}>{{ k }}</option>{% endfor %}</select></td>
|
||||
<td class="num"><a href="/transactions?category={{ c.id }}">{{ counts.get(c.id, 0) }}</a></td>
|
||||
<td style="white-space:nowrap"><button form="cat{{ c.id }}" class="sm">Save</button>
|
||||
<form class="inline" method="post" action="/categories/{{ c.id }}/delete" data-confirm="Delete category {{ c.name }}? Its rules go too; transactions become uncategorised."><button class="sm ghost icon" title="Delete">{{ icon('trash-2', 'sm') }}</button></form></td></tr>
|
||||
{% endfor %}
|
||||
<tr><td><form id="catnew" method="post" action="/categories/save"></form><input form="catnew" type="color" name="color" value="#888888"></td>
|
||||
<td><input form="catnew" name="name" required placeholder="New category" style="width:140px"></td>
|
||||
<td><select form="catnew" name="kind"><option>expense</option><option>income</option><option>transfer</option></select></td><td></td>
|
||||
<td><button form="catnew" class="sm">Add</button></td></tr>
|
||||
</tbody>
|
||||
</table></div>
|
||||
</div>
|
||||
|
||||
<div class="card" id="rules">
|
||||
<h2>{{ icon('sparkles') }} Categorisation rules</h2>
|
||||
<form method="post" action="/rules/add" class="form-grid mb">
|
||||
<label>Text to match<input name="pattern" required value="{{ prefill.get('rule', '') }}" placeholder="albert heijn or re:^ah\b"></label>
|
||||
<label>In<select name="field"><option value="any">name + description</option><option value="counterparty">name</option>
|
||||
<option value="description">description</option><option value="iban">counter IBAN (exact)</option></select></label>
|
||||
<label>Category<select name="category_id">{% for c in categories %}<option value="{{ c.id }}">{{ c.name }}</option>{% endfor %}</select></label>
|
||||
<label>Priority<input type="number" name="priority" value="10" title="lower runs first"></label>
|
||||
<div><button>Add & apply</button></div>
|
||||
</form>
|
||||
<p class="small muted">Matches whole words, case-insensitive. Prefix with <code>re:</code> for a regular expression. Lower priority wins.</p>
|
||||
<div class="row mb">
|
||||
<form method="post" action="/rules/apply"><input type="hidden" name="only_uncategorised" value="1"><button class="secondary sm">Apply to uncategorised</button></form>
|
||||
<form method="post" action="/rules/apply" data-confirm="Re-run all rules on every transaction that wasn't set manually?"><button class="secondary sm">Re-apply to all (except locked)</button></form>
|
||||
</div>
|
||||
<div class="table-wrap" style="max-height:480px; overflow-y:auto"><table>
|
||||
<thead><tr><th>Pattern</th><th>In</th><th>Category</th><th class="num">Prio</th><th></th></tr></thead>
|
||||
<tbody>
|
||||
{% for r in rules %}
|
||||
<tr><td><code>{{ r.pattern }}</code></td><td class="small">{{ r.field }}</td><td><span class="dot" style="background:{{ r.category.color }}"></span>{{ r.category.name }}</td>
|
||||
<td class="num">{{ r.priority }}</td>
|
||||
<td><form method="post" action="/rules/{{ r.id }}/delete"><button class="sm ghost icon" title="Delete">{{ icon('trash-2', 'sm') }}</button></form></td></tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table></div>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,49 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Transactions{% endblock %}
|
||||
{% block content %}
|
||||
<div class="page-head"><div><h1>Transactions</h1><div class="sub">{{ total }} transactions · net <strong>{{ total_amount|eur }}</strong></div></div>
|
||||
<div class="actions"><a class="btn secondary" href="/transactions?category=none">{{ icon('filter', 'sm') }} Uncategorised</a><a class="btn" href="/import">{{ icon('upload', 'sm') }} Import</a></div></div>
|
||||
<form class="card mb form-grid" method="get">
|
||||
<label>Search<input name="q" value="{{ f.q }}" placeholder="name, description, note"></label>
|
||||
<label>Account<select name="account"><option value="">All</option>
|
||||
{% for a in accounts %}<option value="{{ a.id }}" {{ 'selected' if f.account == a.id|string }}>{{ a.name }}</option>{% endfor %}</select></label>
|
||||
<label>Category<select name="category"><option value="">All</option><option value="none" {{ 'selected' if f.category == 'none' }}>— Uncategorised —</option>
|
||||
{% for c in categories %}<option value="{{ c.id }}" {{ 'selected' if f.category == c.id|string }}>{{ c.name }}</option>{% endfor %}</select></label>
|
||||
<label>Month<input type="month" name="month" value="{{ f.month }}"></label>
|
||||
<div class="row"><button>{{ icon('search', 'sm') }} Filter</button><a class="btn ghost" href="/transactions">Reset</a></div>
|
||||
</form>
|
||||
|
||||
<div class="card">
|
||||
<div class="card-head"><h2>{{ icon('receipt') }} Activity</h2><span class="small muted">{{ icon('lock', 'sm') }} Changing a category locks it so rules won't overwrite it.</span></div>
|
||||
<div class="table-wrap">
|
||||
<table>
|
||||
<thead><tr><th>Date</th><th>Counterparty</th><th>Account</th><th>Category</th><th class="num">Amount</th><th>Note</th><th></th></tr></thead>
|
||||
<tbody>
|
||||
{% for t in txs %}
|
||||
<tr>
|
||||
<td class="small" style="white-space:nowrap">{{ t.date.strftime('%d-%m-%Y') }}</td>
|
||||
<td><div class="cell-main"><span class="tx-ico {{ 'tint-good' if t.amount > 0 else 'tint-accent' }}">{{ icon('arrow-down-right' if t.amount > 0 else 'arrow-up-right', 'sm') }}</span>
|
||||
<div><strong>{{ t.counterparty or '—' }}</strong>{% if t.recurring_id %} <span class="badge accent" title="Recurring">{{ icon('repeat', 'sm') }}</span>{% endif %}{% if t.debt_id %} <a class="badge warn" href="/debts/{{ t.debt_id }}" title="Debt payment">{{ icon('handshake', 'sm') }}</a>{% endif %}
|
||||
<div class="desc" title="{{ t.description }}">{{ t.counter_iban or '' }} {{ t.description }}</div></div></div></td>
|
||||
<td class="small">{{ t.account.name }}</td>
|
||||
<td style="white-space:nowrap"><span class="dot" style="background:{{ t.category.color if t.category else 'transparent' }}; outline:1px solid var(--line)"></span><select data-tx="{{ t.id }}"><option value="">—</option>
|
||||
{% for c in categories %}<option value="{{ c.id }}" data-color="{{ c.color }}" {{ 'selected' if t.category_id == c.id }}>{{ c.name }}</option>{% endfor %}</select>
|
||||
{% if t.category_locked %}<span class="muted" title="Set manually">{{ icon('lock', 'sm') }}</span>{% endif %}</td>
|
||||
<td class="num {{ 'good' if t.amount > 0 else '' }}" style="font-weight:600">{{ t.amount|eur }}{% if t.currency != 'EUR' %} <span class="muted small">{{ t.currency }}</span>{% endif %}</td>
|
||||
<td><input data-notes="{{ t.id }}" value="{{ t.notes }}" placeholder="…" style="width:120px"></td>
|
||||
<td><a class="btn ghost sm" title="Create a rule from this" href="/settings?rule={{ (t.counterparty or '')|urlencode }}#rules">{{ icon('plus', 'sm') }} Rule</a></td>
|
||||
</tr>
|
||||
{% else %}<tr><td colspan="7" class="muted">No transactions match.</td></tr>{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% if pages > 1 %}
|
||||
<div class="pager">
|
||||
{% set qs = 'q=%s&account=%s&category=%s&month=%s'|format(f.q|urlencode, f.account, f.category, f.month) %}
|
||||
{% if page > 1 %}<a class="btn secondary sm" href="?{{ qs }}&page={{ page-1 }}">‹ Prev</a>{% endif %}
|
||||
<span class="muted">Page {{ page }} / {{ pages }}</span>
|
||||
{% if page < pages %}<a class="btn secondary sm" href="?{{ qs }}&page={{ page+1 }}">Next ›</a>{% endif %}
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endblock %}
|
||||
Reference in New Issue
Block a user