diff --git a/export.py b/export.py new file mode 100644 index 0000000..5823f39 --- /dev/null +++ b/export.py @@ -0,0 +1,183 @@ +"""CSV export of docs/spec.md section 8. + +Semicolon separated with a UTF-8 BOM and Norwegian number formatting, so the +file opens directly in a Norwegian spreadsheet. `report_csv()` starts the file +and carries the BOM; `transactions_csv()` is appended after it. +""" + +import database +import rates +import tax + +BOM = "\ufeff" +SEPARATOR = ";" + +TYPE_LABELS = { + "trade": "Handel", + "income": "Inntekt", + "spend": "Forbruk", + "loss": "Tap", + "transfer_out": "Overføring ut", + "transfer_in": "Overføring inn", + "gift_received": "Gåve (motteke)", + "gift_given": "Gåve (gjeven)", + "admin_cost": "Forvaltningskostnad", +} + +TRANSACTION_HEADINGS = ( + "Dato", + "Type", + "Konto", + "Til konto", + "Antall inn (BTC)", + "Antall ut (BTC)", + "Beløp inn (kr)", + "Beløp ut (kr)", + "Verdi (kr)", + "Avgift (sats)", + "Avgift (kr)", + "Inngangsverdi (kr)", + "Skattepliktig", + "Notat", +) + + +def _cell(value): + """Escape one text cell. Numbers are passed through unquoted.""" + text = "" if value is None else str(value) + text = text.replace("\r\n", " ").replace("\n", " ").replace("\r", " ") + if SEPARATOR in text or '"' in text: + return '"' + text.replace('"', '""') + '"' + return text + + +def _amount(ore): + """An amount in kroner, with Norwegian formatting.""" + return "" if ore is None else rates.ore_to_nok(ore) + + +def _btc(sats): + """A BTC quantity, empty when there is none.""" + return "" if not sats else rates.sats_to_btc(sats) + + +def _percent(value): + """A percentage with one decimal and a decimal comma.""" + return ("%.1f" % value).replace(".", ",") + + +def report_csv(year): + """The report block, with the UTF-8 BOM. Append transactions_csv() to it.""" + year = int(year) + data = tax.report(year) + totals = data["totals"] + price = data["year_end_price_ore"] + + lines = [_cell("Skuld – skattegrunnlag %d" % year), ""] + lines.append("Nøkkel" + SEPARATOR + "Verdi") + lines.append("Metode" + SEPARATOR + _cell(totals["lot_method"])) + lines.append( + "Kurs %s (NOK per BTC)" % rates.year_end_date(year) + + SEPARATOR + + _amount(price) + ) + lines.append("Formue (kr)" + SEPARATOR + _amount(totals["formue_ore"])) + lines.append("Gevinst (kr)" + SEPARATOR + _amount(totals["gevinst_ore"])) + lines.append("Tap (kr)" + SEPARATOR + _amount(totals["tap_ore"])) + lines.append("Brukt inngangsverdi (kr)" + SEPARATOR + _amount(totals["brukt_ore"])) + lines.append("Netto (kr)" + SEPARATOR + _amount(totals["netto_ore"])) + lines.append("Inntekt (kr)" + SEPARATOR + _amount(totals["inntekt_ore"])) + lines.append("Skatt (kr)" + SEPARATOR + _amount(totals["skatt_ore"])) + lines.append("Formuesskatt (kr)" + SEPARATOR + _amount(totals["formuesskatt_ore"])) + lines.append( + "Forvaltningskostnad (kr)" + SEPARATOR + _amount(totals["admin_cost_ore"]) + ) + lines.append("") + + lines.append(SEPARATOR.join(( + "Konto", + "Behaldning %", + "Antall (BTC)", + "Formue (kr)", + "Gevinst (kr)", + "Tap (kr)", + "Brukt (kr)", + "Gevinst %", + ))) + for account in data["accounts"]: + lines.append(SEPARATOR.join(( + _cell(account["name"]), + _percent(account["share_percent"]), + _btc(account["sats"]), + _amount(account["formue_ore"]), + _amount(account["gevinst_ore"]), + _amount(account["tap_ore"]), + _amount(account["brukt_ore"]), + _percent(account["gevinst_percent"]), + ))) + lines.append("") + + if data["non_taxable"]: + lines.append(SEPARATOR.join(( + "Ikkje skattepliktig", "Antall (BTC)", "Gevinst (kr)", "Tap (kr)" + ))) + for row in data["non_taxable"]: + lines.append(SEPARATOR.join(( + _cell(row["name"]), + _btc(row["sats"]), + _amount(row["gevinst_ore"]), + _amount(row["tap_ore"]), + ))) + lines.append("") + + if data["custody_totals"]: + lines.append("TOT (fysisk behaldning)" + SEPARATOR + "Antall (BTC)") + for row in data["custody_totals"]: + lines.append(_cell(row["name"]) + SEPARATOR + _btc(row["sats"])) + lines.append("") + + lines.append(_cell(data["skattemelding"]["note"])) + return BOM + "\r\n".join(lines) + "\r\n" + + +def transactions_csv(year): + """The year's transactions with the cost basis each one consumed.""" + year = int(year) + conn = database.connect() + try: + rows = conn.execute( + "SELECT t.date, t.type, t.taxable, t.note, t.leg_in_sats, t.leg_in_ore," + " t.leg_out_sats, t.leg_out_ore, t.value_ore, t.fee_sats, t.fee_ore," + " 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" + " WHERE t.date >= ? AND t.date <= ?" + " GROUP BY t.id ORDER BY t.date, t.id", + ("%04d-01-01" % year, "%04d-12-31" % year), + ).fetchall() + finally: + conn.close() + + lines = [SEPARATOR.join(("Transaksjonar %d" % year,))] + lines.append(SEPARATOR.join(TRANSACTION_HEADINGS)) + for row in rows: + lines.append(SEPARATOR.join(( + row["date"], + _cell(TYPE_LABELS.get(row["type"], row["type"])), + _cell(row["market_name"]), + _cell(row["to_market_name"]), + _btc(row["leg_in_sats"]), + _btc(row["leg_out_sats"]), + _amount(row["leg_in_ore"]), + _amount(row["leg_out_ore"]), + _amount(row["value_ore"]), + _btc(row["fee_sats"]), + _amount(row["fee_ore"]), + _amount(row["cost_ore"]), + "Ja" if row["taxable"] else "Nei", + _cell(row["note"]), + ))) + return "\r\n".join(lines) + "\r\n"