Add the handlers for markets, transactions, lots, prices and settings
This commit is contained in:
1 parent
2b77512ff0
commit
c7bcc54154
1 file changed
+268
@@ -425,6 +425,274 @@ class SkuldHandler(BaseHTTPRequestHandler):
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
# -- accounts ---------------------------------------------------------
|
||||
|
||||
def markets_list(self, params, query, body):
|
||||
conn = database.connect()
|
||||
try:
|
||||
markets = _market_rows(conn)
|
||||
on_hand = ledger.sats_on_hand(conn)
|
||||
finally:
|
||||
conn.close()
|
||||
for market in markets:
|
||||
market["sats"] = on_hand.get(market["id"], 0)
|
||||
return markets
|
||||
|
||||
def markets_create(self, params, query, body):
|
||||
conn = database.connect()
|
||||
try:
|
||||
market, errors = validation.validate_market(body, _load_markets(conn))
|
||||
if errors:
|
||||
_raise_errors(errors)
|
||||
cursor = conn.execute(
|
||||
"INSERT INTO markets (name, kind, taxable, custody_market_id, note,"
|
||||
" sort_order, archived) VALUES (?, ?, ?, ?, ?, ?, ?)",
|
||||
(market["name"], market["kind"], market["taxable"],
|
||||
market["custody_market_id"], market["note"], market["sort_order"],
|
||||
market["archived"]),
|
||||
)
|
||||
conn.commit()
|
||||
market["id"] = cursor.lastrowid
|
||||
market["sats"] = 0
|
||||
finally:
|
||||
conn.close()
|
||||
return market
|
||||
|
||||
def markets_update(self, params, query, body):
|
||||
market_id = _as_int(params["id"], "id")
|
||||
conn = database.connect()
|
||||
try:
|
||||
markets = _load_markets(conn)
|
||||
if market_id not in markets:
|
||||
raise ApiError(404, "Fann ikkje kontoen.")
|
||||
merged = dict(markets[market_id])
|
||||
merged.update({key: body[key] for key in body if key in merged})
|
||||
market, errors = validation.validate_market(merged, markets, market_id)
|
||||
if errors:
|
||||
_raise_errors(errors)
|
||||
taxable_changed = market["taxable"] != markets[market_id]["taxable"]
|
||||
conn.execute(
|
||||
"UPDATE markets SET name = ?, kind = ?, taxable = ?, custody_market_id = ?,"
|
||||
" note = ?, sort_order = ?, archived = ? WHERE id = ?",
|
||||
(market["name"], market["kind"], market["taxable"],
|
||||
market["custody_market_id"], market["note"], market["sort_order"],
|
||||
market["archived"], market_id),
|
||||
)
|
||||
if taxable_changed:
|
||||
ledger.rebuild(conn)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
return market
|
||||
|
||||
def markets_delete(self, params, query, body):
|
||||
market_id = _as_int(params["id"], "id")
|
||||
conn = database.connect()
|
||||
try:
|
||||
row = conn.execute(
|
||||
"SELECT 1 FROM markets WHERE id = ?", (market_id,)
|
||||
).fetchone()
|
||||
if row is None:
|
||||
raise ApiError(404, "Fann ikkje kontoen.")
|
||||
used = conn.execute(
|
||||
"SELECT 1 FROM transactions WHERE market_id = ? OR to_market_id = ? LIMIT 1",
|
||||
(market_id, market_id),
|
||||
).fetchone()
|
||||
if used:
|
||||
raise ApiError(400, "Kontoen har transaksjonar og kan ikkje slettast.")
|
||||
custodian = conn.execute(
|
||||
"SELECT 1 FROM markets WHERE custody_market_id = ? LIMIT 1", (market_id,)
|
||||
).fetchone()
|
||||
if custodian:
|
||||
raise ApiError(
|
||||
400, "Kontoen er oppbevarar for andre kontoar og kan ikkje slettast."
|
||||
)
|
||||
conn.execute("DELETE FROM markets WHERE id = ?", (market_id,))
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
return {"status": "ok"}
|
||||
|
||||
# -- transactions -----------------------------------------------------
|
||||
|
||||
def transactions_list(self, params, query, body):
|
||||
where = []
|
||||
values = []
|
||||
if query.get("year", [""])[0]:
|
||||
year = _parse_year(query["year"][0])
|
||||
where.append("t.date >= ? AND t.date <= ?")
|
||||
values += ["%04d-01-01" % year, "%04d-12-31" % year]
|
||||
if query.get("market_id", [""])[0]:
|
||||
where.append("t.market_id = ?")
|
||||
values.append(_as_int(query["market_id"][0], "market_id"))
|
||||
if query.get("type", [""])[0]:
|
||||
where.append("t.type = ?")
|
||||
values.append(query["type"][0])
|
||||
sql = (
|
||||
"SELECT t.*, m.name AS market_name, d.name AS to_market_name,"
|
||||
" COALESCE(SUM(c.cost_ore), 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"
|
||||
" LEFT JOIN lot_consumptions c ON c.tx_id = t.id"
|
||||
)
|
||||
if where:
|
||||
sql += " WHERE " + " AND ".join(where)
|
||||
sql += " GROUP BY t.id ORDER BY t.date DESC, t.id DESC"
|
||||
conn = database.connect()
|
||||
try:
|
||||
rows = conn.execute(sql, values).fetchall()
|
||||
finally:
|
||||
conn.close()
|
||||
return [dict(row) for row in rows]
|
||||
|
||||
def transactions_get(self, params, query, body):
|
||||
tx_id = _as_int(params["id"], "id")
|
||||
conn = database.connect()
|
||||
try:
|
||||
transaction = _load_transaction(conn, tx_id)
|
||||
consumptions = [dict(row) for row in conn.execute(
|
||||
"SELECT c.id, c.lot_id, c.sats, c.cost_ore, c.auto, l.acquired_date"
|
||||
" FROM lot_consumptions c JOIN lots l ON l.id = c.lot_id"
|
||||
" WHERE c.tx_id = ? ORDER BY c.id",
|
||||
(tx_id,),
|
||||
).fetchall()]
|
||||
picks = [dict(row) for row in conn.execute(
|
||||
"SELECT origin_tx_id, origin_seq, sats FROM lot_picks WHERE tx_id = ?"
|
||||
" ORDER BY id",
|
||||
(tx_id,),
|
||||
).fetchall()]
|
||||
candidates = (
|
||||
ledger.candidate_lots(transaction["market_id"], transaction["date"], conn)
|
||||
if transaction["type"] in ledger.CONSUMING_TYPES
|
||||
else []
|
||||
)
|
||||
finally:
|
||||
conn.close()
|
||||
return {
|
||||
"transaction": transaction,
|
||||
"consumptions": consumptions,
|
||||
"picks": picks,
|
||||
"candidate_lots": candidates,
|
||||
}
|
||||
|
||||
def transactions_create(self, params, query, body):
|
||||
return self._transaction_payload(self._save_transaction(None, body))
|
||||
|
||||
def transactions_update(self, params, query, body):
|
||||
tx_id = _as_int(params["id"], "id")
|
||||
return self._transaction_payload(self._save_transaction(tx_id, body))
|
||||
|
||||
def transactions_delete(self, params, query, body):
|
||||
tx_id = _as_int(params["id"], "id")
|
||||
conn = database.connect()
|
||||
try:
|
||||
row = conn.execute(
|
||||
"SELECT id, type, transfer_group FROM transactions WHERE id = ?", (tx_id,)
|
||||
).fetchone()
|
||||
if row is None:
|
||||
raise ApiError(404, "Fann ikkje transaksjonen.")
|
||||
if row["type"] == "transfer_in":
|
||||
raise ApiError(
|
||||
400, "Overføring inn kan berre slettast saman med overføringa ut."
|
||||
)
|
||||
with conn:
|
||||
_drop_ledger(conn)
|
||||
if row["transfer_group"]:
|
||||
conn.execute(
|
||||
"DELETE FROM transactions WHERE transfer_group = ?",
|
||||
(row["transfer_group"],),
|
||||
)
|
||||
else:
|
||||
conn.execute("DELETE FROM transactions WHERE id = ?", (tx_id,))
|
||||
ledger.rebuild(conn)
|
||||
finally:
|
||||
conn.close()
|
||||
return {"status": "ok"}
|
||||
|
||||
def _save_transaction(self, tx_id, body):
|
||||
picks, error = validation.validate_lot_picks(body.get("lot_picks"))
|
||||
if error:
|
||||
raise ApiError(400, error, "lot_picks")
|
||||
conn = database.connect()
|
||||
try:
|
||||
tx, errors = validation.validate_transaction(body, _load_markets(conn))
|
||||
if errors:
|
||||
_raise_errors(errors)
|
||||
previous = None
|
||||
if tx_id is not None:
|
||||
row = conn.execute(
|
||||
"SELECT id, type, transfer_group FROM transactions WHERE id = ?",
|
||||
(tx_id,),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
raise ApiError(404, "Fann ikkje transaksjonen.")
|
||||
if row["type"] == "transfer_in":
|
||||
raise ApiError(
|
||||
400,
|
||||
"Overføring inn kan berre sjåast og slettast saman med overføringa ut.",
|
||||
)
|
||||
previous = dict(row)
|
||||
try:
|
||||
with conn:
|
||||
tx_id = _write_transaction(conn, tx_id, tx, picks)
|
||||
_sync_transfer_pair(conn, tx_id, previous, tx)
|
||||
ledger.rebuild(conn)
|
||||
except ledger.LedgerError as ledger_error:
|
||||
raise ApiError(400, str(ledger_error), "leg_out_sats")
|
||||
return tx_id
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def _transaction_payload(self, tx_id):
|
||||
conn = database.connect()
|
||||
try:
|
||||
return _load_transaction(conn, tx_id)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
# -- lots, prices and settings ----------------------------------------
|
||||
|
||||
def lots_list(self, params, query, body):
|
||||
market_id = _as_int(query.get("market_id", [""])[0], "market_id")
|
||||
wanted = query.get("date", [""])[0] or _today()
|
||||
return ledger.candidate_lots(market_id, wanted)
|
||||
|
||||
def prices_list(self, params, query, body):
|
||||
return rates.list_rates()
|
||||
|
||||
def prices_put(self, params, query, body):
|
||||
if str(body.get("nok_per_btc") or "").strip():
|
||||
ore, error = validation.validate_ore(body["nok_per_btc"])
|
||||
if error:
|
||||
raise ApiError(400, error, "nok_per_btc")
|
||||
elif body.get("nok_per_btc_ore") is not None:
|
||||
ore = _as_int(body["nok_per_btc_ore"], "nok_per_btc_ore",
|
||||
"Kursen må vere eit heiltal i øre.")
|
||||
if ore <= 0:
|
||||
raise ApiError(400, "Kursen må vere større enn null.", "nok_per_btc_ore")
|
||||
else:
|
||||
raise ApiError(400, "Fyll ut kursen.", "nok_per_btc")
|
||||
source = body.get("source")
|
||||
rates.set_rate(
|
||||
params["date"], ore, "" if source is None else str(source).strip()
|
||||
)
|
||||
return rates.list_rates()
|
||||
|
||||
def settings_get(self, params, query, body):
|
||||
return database.all_settings()
|
||||
|
||||
def settings_patch(self, params, query, body):
|
||||
settings, errors = validation.validate_settings(body)
|
||||
if errors:
|
||||
_raise_errors(errors)
|
||||
before = database.get_setting("lot_method")
|
||||
for key, value in settings.items():
|
||||
database.set_setting(key, value)
|
||||
if settings.get("lot_method") and settings["lot_method"] != before:
|
||||
ledger.rebuild()
|
||||
return database.all_settings()
|
||||
|
||||
|
||||
def main():
|
||||
"""Serve until the process is stopped."""
|
||||
port = int(os.environ.get("PORT") or DEFAULT_PORT)
|
||||
|
||||
Reference in new issue
Block a user