You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

313 lines
13 KiB
Python

# SplitBuddy — Flask app with ratio-based splits (You vs Idan)
from __future__ import annotations
import os, sqlite3, csv, io, datetime as dt
from typing import Optional
from flask import Flask, g, request, redirect, url_for, render_template_string, send_file
app = Flask(__name__)
DB_PATH = os.environ.get("SPLITBUDDY_DB", "splitbuddy.db")
CURRENCY = ""
PERSON_A = os.environ.get("SPLITBUDDY_ME", "Me") # you
PERSON_B = os.environ.get("SPLITBUDDY_ROOMIE", "Idan") # roommate
# ------------------------- DB helpers --------------------------- #
def get_db() -> sqlite3.Connection:
if "db" not in g:
g.db = sqlite3.connect(DB_PATH)
g.db.row_factory = sqlite3.Row
return g.db
@app.teardown_appcontext
def close_db(_=None):
db = g.pop("db", None)
if db is not None:
db.close()
def init_db():
db = get_db()
# Base table
db.execute("""
CREATE TABLE IF NOT EXISTS entries (
id INTEGER PRIMARY KEY AUTOINCREMENT,
created_at TEXT NOT NULL,
total REAL NOT NULL DEFAULT 0, -- total bill amount
payer TEXT NOT NULL DEFAULT 'A', -- 'A' (you) or 'B' (Idan)
a_share REAL NOT NULL DEFAULT 0.5, -- your share as fraction (0..1)
method TEXT NOT NULL DEFAULT 'cash',
note TEXT
)
""")
# Migrate older schema (from signed amount version)
# If old columns exist, add new if missing
try:
db.execute("ALTER TABLE entries ADD COLUMN total REAL")
except sqlite3.OperationalError:
pass
try:
db.execute("ALTER TABLE entries ADD COLUMN payer TEXT")
except sqlite3.OperationalError:
pass
try:
db.execute("ALTER TABLE entries ADD COLUMN a_share REAL")
except sqlite3.OperationalError:
pass
# If we had old 'amount' signed records and 'total' is NULL, map amount→total and infer payer/a_share=0.5
db.execute("""
UPDATE entries
SET total = COALESCE(total, 0),
payer = COALESCE(payer, CASE WHEN total IS NOT NULL THEN 'A' ELSE 'A' END),
a_share = COALESCE(a_share, 0.5)
""")
db.commit()
# --------------------------- Template --------------------------- #
BASE = r"""
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" />
<title>SplitBuddy</title>
<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap" rel="stylesheet">
<style>
:root{ --bg:#0f1115; --card:#141822; --muted:#8c93a6; --ok:#19c37d; --bad:#ef4444; --fg:#e6e7eb; --acc:#4ea1ff; --edge:#202637;}
*{ box-sizing:border-box } body{ margin:0; font-family:Inter,system-ui; background:var(--bg); color:var(--fg) }
.wrap{ max-width:980px; margin:24px auto; padding:0 16px } header{ display:flex; gap:12px; align-items:center; justify-content:space-between; margin-bottom:16px }
.h1{ font-size:24px; font-weight:700 } .pill{ display:inline-flex; gap:8px; padding:8px 12px; border-radius:999px; background:var(--card); border:1px solid var(--edge); font-size:14px }
.pill.ok{ background:rgba(25,195,125,.12); border-color:#1f7a58 } .pill.bad{ background:rgba(239,68,68,.12); border-color:#7a1f1f }
.muted{ color:var(--muted) } .grid{ display:grid; grid-template-columns:1.2fr .8fr; gap:16px } @media (max-width:900px){ .grid{ grid-template-columns:1fr } }
.card{ background:var(--card); border:1px solid var(--edge); border-radius:14px; padding:16px } h2{ font-size:16px; margin:0 0 10px }
form .row{ display:flex; gap:10px; flex-wrap:wrap }
input, select{ background:#0d1117; border:1px solid #263041; color:var(--fg); border-radius:10px; padding:10px; outline:none }
input[type="number"]{ max-width:160px } input[type="text"]{ flex:1 }
.seg{ display:inline-flex; border:1px solid #263041; border-radius:10px; overflow:hidden } .seg input{ display:none } .seg label{ padding:8px 10px; cursor:pointer; background:#0d1117 }
.seg input:checked + label{ background:#182033; color:#b6d1ff }
button.btn{ background:#1f6fe8; border:none; color:#fff; padding:10px 14px; border-radius:10px; cursor:pointer }
button.btn.secondary{ background:#273244 } button.btn.danger{ background:#c92a2a }
table{ width:100%; border-collapse:collapse } th, td{ border-bottom:1px solid #222b3b; padding:10px; text-align:left; font-size:14px }
th{ color:#aab3c4 } td.num{ font-variant-numeric:tabular-nums; text-align:right }
.pos{ color:#ef9a9a } .neg{ color:#9ae6b4 }
.tag{ font-size:12px; padding:2px 8px; border-radius:999px; background:#1a2332; border:1px solid #243046 }
</style>
<script>
function setShare(pct) {
const el = document.getElementById('a_share');
el.value = pct.toFixed(2);
}
</script>
</head>
<body>
<div class="wrap">
<header>
<div class="h1">SplitBuddy</div>
<div>
<span class="pill {{ 'bad' if summary.total>0 else ('ok' if summary.total<0 else '') }}">
{% if summary.total > 0 %}
{{ A }} owes {{ B }} <strong>{{ currency }}{{ '%.2f'|format(summary.total) }}</strong>
{% elif summary.total < 0 %}
{{ B }} owes {{ A }} <strong>{{ currency }}{{ '%.2f'|format(-summary.total) }}</strong>
{% else %}All settled ✨{% endif %}
</span>
<span class="pill muted">Balance: {{ currency }}{{ '%.2f'|format(summary.total) }}</span>
<a class="pill" href="{{ url_for('export_csv') }}">Export CSV</a>
</div>
</header>
<div class="grid">
<section class="card">
<h2>Add entry</h2>
<form method="post" action="{{ url_for('add') }}">
<div class="row">
<input type="number" step="0.01" min="0" name="total" placeholder="Total amount" required>
<select name="payer">
<option value="A">{{ A }} paid</option>
<option value="B">{{ B }} paid</option>
</select>
<input id="a_share" type="number" step="0.01" min="0" max="100" name="a_share_pct" placeholder="{{ A }} share %" value="50.00" title="{{ A }}'s share (%)">
</div>
<div class="row" style="margin-top:8px">
<div class="seg" title="Quick presets">
<input type="radio" id="p50" name="preset" onclick="setShare(50)" checked><label for="p50">50/50</label>
<input type="radio" id="p66" name="preset" onclick="setShare(66.6667)"><label for="p66">{{ A }} 2/3</label>
<input type="radio" id="p33" name="preset" onclick="setShare(33.3333)"><label for="p33">{{ A }} 1/3</label>
</div>
<select name="method">
<option>cash</option><option>transfer</option><option>other</option>
</select>
<input type="text" name="note" placeholder="Reason (e.g. rent, groceries, washer)">
<input type="datetime-local" name="created_at" value="{{ now_local }}">
<button class="btn" type="submit">Add</button>
</div>
</form>
</section>
<section class="card">
<h2>Stats</h2>
<div class="muted">Entries: {{ summary.count }}</div>
<div class="muted">Latest: {{ summary.latest or '' }}</div>
<div style="margin-top:8px">
<span class="tag">Cash Δ: {{ currency }}{{ '%.2f'|format(summary.by_method.cash) }}</span>
<span class="tag">Transfer Δ: {{ currency }}{{ '%.2f'|format(summary.by_method.transfer) }}</span>
<span class="tag">Other Δ: {{ currency }}{{ '%.2f'|format(summary.by_method.other) }}</span>
</div>
</section>
</div>
<section class="card" style="margin-top:16px">
<h2>Ledger</h2>
<table>
<thead>
<tr>
<th style="width:160px">Time</th>
<th>Payer</th>
<th>Reason</th>
<th>Method</th>
<th class="num">Your share %</th>
<th class="num">Total</th>
<th class="num">Δ Balance</th>
<th style="width:120px"></th>
</tr>
</thead>
<tbody>
{% for e in entries %}
<tr>
<td>{{ e.created_at }}</td>
<td>{{ A if e.payer=='A' else B }}</td>
<td>{{ e.note or '' }}</td>
<td>{{ e.method }}</td>
<td class="num">{{ '%.2f'|format(e.a_share*100) }}%</td>
<td class="num">{{ currency }}{{ '%.2f'|format(e.total) }}</td>
<td class="num {{ 'pos' if e.delta>0 else 'neg' if e.delta<0 else '' }}">
{{ currency }}{{ '%.2f'|format(e.delta) }}
</td>
<td>
<form method="post" action="{{ url_for('delete', entry_id=e.id) }}" onsubmit="return confirm('Delete this entry?');">
<button class="btn danger" type="submit">Delete</button>
</form>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</section>
</div>
</body>
</html>
"""
# --------------------------- Utilities -------------------------- #
def _now_local_iso_min() -> str:
return dt.datetime.now().replace(second=0, microsecond=0).isoformat(timespec="minutes")
class ByMethod:
def __init__(self, cash=0.0, transfer=0.0, other=0.0):
self.cash = cash; self.transfer = transfer; self.other = other
class Summary:
def __init__(self, total: float, count: int, latest: Optional[str], by_method: ByMethod):
self.total = total; self.count = count; self.latest = latest; self.by_method = by_method
def _delta_for_entry(total: float, payer: str, a_share: float) -> float:
"""
Positive => YOU owe Idan. Negative => Idan owes YOU.
delta = (your_share * total) - (total if YOU paid else 0)
"""
paid_by_a = total if payer == "A" else 0.0
return a_share * total - paid_by_a
# ----------------------------- Routes --------------------------- #
@app.before_request
def _ensure_db():
init_db()
@app.get("/")
def index():
db = get_db()
rows = db.execute("""
SELECT id, created_at, total, payer, a_share, method, note
FROM entries
ORDER BY datetime(created_at) DESC, id DESC
""").fetchall()
entries = []
for r in rows:
e = dict(r)
e["delta"] = _delta_for_entry(e["total"], e["payer"], e["a_share"])
entries.append(e)
total_balance = sum(e["delta"] for e in entries) if entries else 0.0
latest = entries[0]["created_at"] if entries else None
bm = ByMethod(
cash=sum(e["delta"] for e in entries if e["method"] == "cash"),
transfer=sum(e["delta"] for e in entries if e["method"] == "transfer"),
other=sum(e["delta"] for e in entries if e["method"] == "other"),
)
summary = Summary(total=total_balance, count=len(entries), latest=latest, by_method=bm)
return render_template_string(
BASE,
entries=entries,
summary=summary,
A=PERSON_A, B=PERSON_B,
currency=CURRENCY,
now_local=_now_local_iso_min(),
)
@app.post("/add")
def add():
total = request.form.get("total", type=float)
payer = request.form.get("payer", "A").strip().upper()
a_share_pct = request.form.get("a_share_pct", type=float)
method = (request.form.get("method") or "cash").strip().lower()
note = (request.form.get("note") or "").strip()
created_at = request.form.get("created_at") or _now_local_iso_min()
if total is None or total < 0:
return redirect(url_for("index"))
if payer not in ("A", "B"):
payer = "A"
if a_share_pct is None:
a_share_pct = 50.0
a_share = max(0.0, min(100.0, a_share_pct)) / 100.0
db = get_db()
db.execute(
"INSERT INTO entries (created_at, total, payer, a_share, method, note) VALUES (?, ?, ?, ?, ?, ?)",
(created_at, total, payer, a_share, method, note),
)
db.commit()
return redirect(url_for("index"))
@app.post("/delete/<int:entry_id>")
def delete(entry_id: int):
db = get_db()
db.execute("DELETE FROM entries WHERE id = ?", (entry_id,))
db.commit()
return redirect(url_for("index"))
@app.get("/export.csv")
def export_csv():
db = get_db()
rows = db.execute("""
SELECT id, created_at, total, payer, a_share, method, note
FROM entries
ORDER BY datetime(created_at) DESC, id DESC
""").fetchall()
buff = io.StringIO()
w = csv.writer(buff)
w.writerow(["id","created_at","payer","a_share_pct","total","method","note","delta"])
for r in rows:
a_share_pct = float(r["a_share"]) * 100.0
delta = _delta_for_entry(r["total"], r["payer"], r["a_share"])
w.writerow([r["id"], r["created_at"], r["payer"], f"{a_share_pct:.2f}", f"{r['total']:.2f}", r["method"], r["note"] or "", f"{delta:.2f}"])
buff.seek(0)
return send_file(io.BytesIO(buff.read().encode("utf-8")), mimetype="text/csv",
as_attachment=True, download_name="splitbuddy_export.csv")
# --------------------------- Entrypoint -------------------------- #
if __name__ == "__main__":
os.makedirs(os.path.dirname(DB_PATH) or ".", exist_ok=True)
with app.app_context():
init_db()
app.run(debug=True)