diff --git a/app.py b/app.py index c42d887..77ac6e3 100644 --- a/app.py +++ b/app.py @@ -111,6 +111,124 @@ def _as_int(value, field, message="Verdien må vere eit heiltal."): raise ApiError(400, message, field) +def _now_stamp(): + return datetime.now(timezone.utc).isoformat(timespec="seconds") + + +def _today(): + return date.today().isoformat() + + +def _raise_errors(errors): + """Send the first validation error, with the field it belongs to.""" + field = next(iter(errors)) + raise ApiError(400, errors[field], field) + + +def _market_rows(conn): + rows = conn.execute( + "SELECT id, name, kind, taxable, custody_market_id, note, sort_order, archived" + " FROM markets ORDER BY sort_order, name" + ).fetchall() + return [dict(row) for row in rows] + + +def _load_markets(conn): + rows = conn.execute("SELECT * FROM markets").fetchall() + return {row["id"]: dict(row) for row in rows} + + +def _load_transaction(conn, tx_id): + row = conn.execute( + "SELECT t.*, m.name AS market_name, d.name AS to_market_name," + " COALESCE((SELECT SUM(c.cost_ore) FROM lot_consumptions c WHERE c.tx_id = t.id), 0)" + " AS cost_ore FROM transactions t JOIN markets m ON m.id = t.market_id" + " LEFT JOIN markets d ON d.id = t.to_market_id WHERE t.id = ?", + (tx_id,), + ).fetchone() + if row is None: + raise ApiError(404, "Fann ikkje transaksjonen.") + return dict(row) + + +def _drop_ledger(conn): + """Throw the derived ledger away; rebuild() puts it back from the transactions.""" + conn.execute("DELETE FROM lot_consumptions") + conn.execute("DELETE FROM lots") + + +def _write_transaction(conn, tx_id, tx, picks): + now = _now_stamp() + if tx_id is None: + cursor = conn.execute( + "INSERT INTO transactions (date, type, market_id, taxable, note, leg_in_sats," + " leg_in_ore, leg_out_sats, leg_out_ore, value_ore, fee_sats, fee_ore," + " to_market_id, created_at, updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", + (tx["date"], tx["type"], tx["market_id"], tx["taxable"], tx["note"], + tx["leg_in_sats"], tx["leg_in_ore"], tx["leg_out_sats"], tx["leg_out_ore"], + tx["value_ore"], tx["fee_sats"], tx["fee_ore"], tx["to_market_id"], now, now), + ) + tx_id = cursor.lastrowid + else: + conn.execute( + "UPDATE transactions SET date=?, type=?, market_id=?, taxable=?, note=?," + " leg_in_sats=?, leg_in_ore=?, leg_out_sats=?, leg_out_ore=?, value_ore=?," + " fee_sats=?, fee_ore=?, to_market_id=?, updated_at=? WHERE id=?", + (tx["date"], tx["type"], tx["market_id"], tx["taxable"], tx["note"], + tx["leg_in_sats"], tx["leg_in_ore"], tx["leg_out_sats"], tx["leg_out_ore"], + tx["value_ore"], tx["fee_sats"], tx["fee_ore"], tx["to_market_id"], now, tx_id), + ) + conn.execute("DELETE FROM lot_picks WHERE tx_id = ?", (tx_id,)) + for pick in picks: + conn.execute( + "INSERT INTO lot_picks (tx_id, origin_tx_id, origin_seq, sats) VALUES (?,?,?,?)", + (tx_id, pick["origin_tx_id"], pick["origin_seq"], pick["sats"]), + ) + return tx_id + + +def _sync_transfer_pair(conn, tx_id, previous, tx): + """Keep the generated transfer_in in step with its transfer_out.""" + group = previous["transfer_group"] if previous else None + if tx["type"] == "transfer_out": + if not group: + group = uuid.uuid4().hex + conn.execute( + "UPDATE transactions SET transfer_group = ? WHERE id = ?", (group, tx_id) + ) + arrived = (tx["leg_out_sats"] or 0) - (tx["fee_sats"] or 0) + now = _now_stamp() + row = conn.execute( + "SELECT id FROM transactions WHERE type = 'transfer_in' AND transfer_group = ?", + (group,), + ).fetchone() + if row is None: + conn.execute( + "INSERT INTO transactions (date, type, market_id, taxable, note, leg_in_sats," + " fee_sats, fee_ore, to_market_id, transfer_group, generated, created_at," + " updated_at) VALUES (?, 'transfer_in', ?, ?, '', ?, ?, ?, ?, ?, 1, ?, ?)", + (tx["date"], tx["to_market_id"], tx["taxable"], arrived, tx["fee_sats"], + tx["fee_ore"], tx["market_id"], group, now, now), + ) + else: + conn.execute( + "UPDATE transactions SET date = ?, market_id = ?, taxable = ?," + " leg_in_sats = ?, fee_sats = ?, fee_ore = ?, to_market_id = ?," + " generated = 1, updated_at = ? WHERE id = ?", + (tx["date"], tx["to_market_id"], tx["taxable"], arrived, tx["fee_sats"], + tx["fee_ore"], tx["market_id"], now, row["id"]), + ) + elif group: + _drop_ledger(conn) + conn.execute( + "DELETE FROM transactions WHERE type = 'transfer_in' AND transfer_group = ?", + (group,), + ) + conn.execute( + "UPDATE transactions SET transfer_group = NULL WHERE id = ?", (tx_id,) + ) + + class SkuldHandler(BaseHTTPRequestHandler): """One HTTP request."""