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.

345 lines
15 KiB
Python

2 months ago
# SplitBuddy — Flask app with bills/transfer + payer toggle
2 months ago
from __future__ import annotations
import os, sqlite3, csv, io, datetime as dt
from typing import Optional
2 months ago
from flask import Flask, g, request, redirect, url_for, render_template_string, send_file
2 months ago
app = Flask(__name__)
2 months ago
DB_PATH = os.environ.get("SPLITBUDDY_DB", "splitbuddy.db")
CURRENCY = ""
2 months ago
PERSON_A = os.environ.get("SPLITBUDDY_ME", "Me") # you
2 months ago
PERSON_B = os.environ.get("SPLITBUDDY_ROOMIE", "Idan") # roommate
2 months ago
# ------------------------- 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()
2 months ago
db.execute("""
2 months ago
CREATE TABLE IF NOT EXISTS entries (
id INTEGER PRIMARY KEY AUTOINCREMENT,
created_at TEXT NOT NULL,
2 months ago
kind TEXT NOT NULL DEFAULT 'bill', -- 'bill' | 'transfer'
total REAL NOT NULL DEFAULT 0, -- total amount
payer TEXT NOT NULL DEFAULT 'A', -- 'A' (you) or 'B' (Idan)
a_share REAL NOT NULL DEFAULT 0.5, -- your share (0..1), only for bills
2 months ago
method TEXT NOT NULL DEFAULT 'cash',
note TEXT
2 months ago
)
2 months ago
""")
2 months ago
# Migrations for older versions
for col, ddl in [
("kind", "ALTER TABLE entries ADD COLUMN kind TEXT NOT NULL DEFAULT 'bill'"),
("total", "ALTER TABLE entries ADD COLUMN total REAL"),
("payer", "ALTER TABLE entries ADD COLUMN payer TEXT"),
("a_share","ALTER TABLE entries ADD COLUMN a_share REAL"),
]:
try:
db.execute(ddl)
except sqlite3.OperationalError:
pass
# Normalize NULLs from legacy rows
2 months ago
db.execute("""
UPDATE entries
2 months ago
SET kind = COALESCE(kind, 'bill'),
total = COALESCE(total, 0),
payer = COALESCE(payer, 'A'),
a_share= COALESCE(a_share, 0.5)
2 months ago
""")
2 months ago
db.commit()
2 months ago
# --------------------------- Template --------------------------- #
2 months ago
BASE = r"""
<!doctype html>
<html lang="en">
<head>
2 months ago
<meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" />
2 months ago
<title>SplitBuddy</title>
2 months ago
<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
2 months ago
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap" rel="stylesheet">
<style>
2 months ago
:root{ --bg:#0f1115; --card:#141822; --muted:#8c93a6; --ok:#19c37d; --bad:#ef4444; --fg:#e6e7eb; --edge:#202637;}
2 months ago
*{ 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 }
2 months ago
form .row{ display:flex; gap:10px; flex-wrap:wrap }
2 months ago
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 }
2 months ago
.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; user-select:none }
2 months ago
.seg input:checked + label{ background:#182033; color:#b6d1ff }
2 months ago
.toggle{ display:inline-flex; border:1px solid #263041; border-radius:10px; overflow:hidden }
.toggle input{ display:none } .toggle label{ padding:8px 12px; cursor:pointer; background:#0d1117; user-select:none; min-width:100px; text-align:center }
.toggle input:checked + label{ background:#183033; color:#b6d1ff }
2 months ago
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 }
2 months ago
.tag{ font-size:12px; padding:2px 8px; border-radius:999px; background:#1a2332; border:1px solid #243046 }
</style>
2 months ago
<script>
function setShare(pct) {
const el = document.getElementById('a_share');
el.value = pct.toFixed(2);
}
2 months ago
function onKindChange(kind) {
const shareWrap = document.getElementById('share-wrap');
const presets = document.getElementById('presets');
if (kind === 'transfer') {
shareWrap.style.display = 'none';
presets.style.display = 'none';
} else {
shareWrap.style.display = '';
presets.style.display = '';
}
}
document.addEventListener('DOMContentLoaded', () => {
const kindRadios = document.querySelectorAll('input[name="kind"]');
kindRadios.forEach(r => r.addEventListener('change', () => onKindChange(r.value)));
onKindChange(document.querySelector('input[name="kind"]:checked').value);
});
2 months ago
</script>
2 months ago
</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>
2 months ago
{% else %}All settled {% endif %}
2 months ago
</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">
2 months ago
<div class="seg" title="Entry type">
<input type="radio" id="k_bill" name="kind" value="bill" checked><label for="k_bill">Bill</label>
<input type="radio" id="k_xfer" name="kind" value="transfer"><label for="k_xfer">Transfer</label>
</div>
<div class="toggle" title="Who paid / who sent">
<input type="radio" id="payer_a" name="payer" value="A" checked><label for="payer_a">{{ A }}</label>
<input type="radio" id="payer_b" name="payer" value="B"><label for="payer_b">{{ B }}</label>
</div>
<input type="number" step="0.01" min="0" name="total" placeholder="Amount" required>
<select name="method">
<option>cash</option><option>transfer</option><option>other</option>
2 months ago
</select>
2 months ago
</div>
<div class="row" id="share-wrap" style="margin-top:8px">
2 months ago
<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 (%)">
2 months ago
<input type="text" name="note" placeholder="Reason (e.g. rent, groceries, washer)" style="flex:1">
<input type="datetime-local" name="created_at" value="{{ now_local }}">
<button class="btn" type="submit">Add</button>
2 months ago
</div>
2 months ago
<div class="row" id="presets" style="margin-top:8px">
2 months ago
<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>
2 months ago
</div>
</form>
</section>
<section class="card">
<h2>Stats</h2>
2 months ago
<div class="muted">Entries: {{ summary.count }}</div>
2 months ago
<div class="muted">Latest: {{ summary.latest or '' }}</div>
<div style="margin-top:8px">
2 months ago
<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>
2 months ago
</div>
</section>
</div>
<section class="card" style="margin-top:16px">
<h2>Ledger</h2>
<table>
<thead>
<tr>
<th style="width:160px">Time</th>
2 months ago
<th>Type</th>
<th>Payer/Sender</th>
2 months ago
<th>Reason</th>
<th>Method</th>
2 months ago
<th class="num">Your share %</th>
2 months ago
<th class="num">Amount</th>
2 months ago
<th class="num">Δ Balance</th>
2 months ago
<th style="width:120px"></th>
</tr>
</thead>
<tbody>
{% for e in entries %}
<tr>
<td>{{ e.created_at }}</td>
2 months ago
<td>{{ e.kind }}</td>
2 months ago
<td>{{ A if e.payer=='A' else B }}</td>
2 months ago
<td>{{ e.note or '' }}</td>
<td>{{ e.method }}</td>
2 months ago
<td class="num">{{ e.kind == 'bill' and ('%.2f'|format(e.a_share*100) ~ '%') or '' }}</td>
2 months ago
<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>
2 months ago
<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:
2 months ago
return dt.datetime.now().replace(second=0, microsecond=0).isoformat(timespec="minutes")
2 months ago
class ByMethod:
def __init__(self, cash=0.0, transfer=0.0, other=0.0):
2 months ago
self.cash = cash; self.transfer = transfer; self.other = other
2 months ago
class Summary:
def __init__(self, total: float, count: int, latest: Optional[str], by_method: ByMethod):
2 months ago
self.total = total; self.count = count; self.latest = latest; self.by_method = by_method
2 months ago
def _delta_for_entry(kind: str, total: float, payer: str, a_share: float) -> float:
2 months ago
"""
Positive => YOU owe Idan. Negative => Idan owes YOU.
2 months ago
- bill: delta = (your_share * total) - (total if YOU paid else 0)
- transfer: delta = -total if YOU sent; +total if Idan sent
2 months ago
"""
2 months ago
if kind == "transfer":
return -total if payer == "A" else total
# bill
2 months ago
paid_by_a = total if payer == "A" else 0.0
return a_share * total - paid_by_a
2 months ago
# ----------------------------- Routes --------------------------- #
@app.before_request
def _ensure_db():
init_db()
@app.get("/")
def index():
db = get_db()
2 months ago
rows = db.execute("""
2 months ago
SELECT id, created_at, kind, total, payer, a_share, method, note
2 months ago
FROM entries
ORDER BY datetime(created_at) DESC, id DESC
""").fetchall()
entries = []
for r in rows:
e = dict(r)
2 months ago
e["delta"] = _delta_for_entry(e["kind"], e["total"], e["payer"], e["a_share"])
2 months ago
entries.append(e)
2 months ago
2 months ago
total_balance = sum(e["delta"] for e in entries) if entries else 0.0
2 months ago
latest = entries[0]["created_at"] if entries else None
bm = ByMethod(
2 months ago
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"),
2 months ago
)
2 months ago
summary = Summary(total=total_balance, count=len(entries), latest=latest, by_method=bm)
2 months ago
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():
2 months ago
kind = (request.form.get("kind") or "bill").strip().lower()
payer = (request.form.get("payer") or "A").strip().upper()
2 months ago
total = request.form.get("total", type=float)
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()
2 months ago
created_at = request.form.get("created_at") or _now_local_iso_min()
2 months ago
if total is None or total < 0: return redirect(url_for("index"))
if payer not in ("A","B"): payer = "A"
if kind not in ("bill","transfer"): kind = "bill"
a_share = 0.5
if kind == "bill":
if a_share_pct is None: a_share_pct = 50.0
a_share = max(0.0, min(100.0, a_share_pct)) / 100.0
2 months ago
db = get_db()
db.execute(
2 months ago
"INSERT INTO entries (created_at, kind, total, payer, a_share, method, note) VALUES (?, ?, ?, ?, ?, ?, ?)",
(created_at, kind, total, payer, a_share, method, note),
2 months ago
)
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()
2 months ago
rows = db.execute("""
2 months ago
SELECT id, created_at, kind, total, payer, a_share, method, note
2 months ago
FROM entries
ORDER BY datetime(created_at) DESC, id DESC
""").fetchall()
2 months ago
buff = io.StringIO()
2 months ago
w = csv.writer(buff)
2 months ago
w.writerow(["id","created_at","kind","payer","a_share_pct","total","method","note","delta"])
2 months ago
for r in rows:
2 months ago
a_share_pct = float(r["a_share"]) * 100.0
2 months ago
delta = _delta_for_entry(r["kind"], r["total"], r["payer"], r["a_share"])
w.writerow([r["id"], r["created_at"], r["kind"], r["payer"], f"{a_share_pct:.2f}",
f"{r['total']:.2f}", r["method"], r["note"] or "", f"{delta:.2f}"])
2 months ago
buff.seek(0)
2 months ago
return send_file(io.BytesIO(buff.read().encode("utf-8")), mimetype="text/csv",
as_attachment=True, download_name="splitbuddy_export.csv")
2 months ago
# --------------------------- Entrypoint -------------------------- #
if __name__ == "__main__":
os.makedirs(os.path.dirname(DB_PATH) or ".", exist_ok=True)
with app.app_context():
init_db()
2 months ago
app.run(debug=True)