"""Export journal data as text.""" from __future__ import annotations import csv import datetime as dt import io import json from typing import Iterable, Optional from .journal import Journal from .money import Money, minor_units from .reports import trial_balance_rows from .transactions import Transaction _SWAP_SEPARATORS = str.maketrans({",": ".", ".": ","}) def format_amount(money: Money, style: str = "plain") -> str: """Format an amount without currency code. ``plain`` gives ``-1234.50``, ``parens`` gives ``(1234.50)`` for negative values and ``german`` gives ``-1.234,50``. """ places = minor_units(money.currency) value = money.rounded().amount if style == "plain": return format(value, "f") if style == "parens": text = format(abs(value), "f") return "(%s)" % text if value < 0 else text if style == "german": text = format(abs(value), ",.%df" % places).translate(_SWAP_SEPARATORS) return "-" + text if value < 0 else text raise ValueError("unknown style: %s" % style) def transactions_to_csv(transactions: Iterable[Transaction]) -> str: """One CSV row per posting: ``id,date,description,account,amount,currency``.""" buffer = io.StringIO() writer = csv.writer(buffer, lineterminator="\n") writer.writerow(["id", "date", "description", "account", "amount", "currency"]) for tx in transactions: for posting in tx.postings: writer.writerow([ tx.id, tx.date.isoformat(), tx.description, posting.account, format_amount(posting.amount), posting.amount.currency, ]) return buffer.getvalue() def trial_balance_to_csv(journal: Journal, as_of: Optional[dt.date] = None) -> str: """The trial balance as ``code,name,debit,credit`` rows.""" buffer = io.StringIO() writer = csv.writer(buffer, lineterminator="\n") writer.writerow(["code", "name", "debit", "credit"]) for code, name, debit, credit in trial_balance_rows(journal, as_of): writer.writerow([code, name, format_amount(debit), format_amount(credit)]) return buffer.getvalue() def journal_to_json(journal: Journal) -> str: """The whole journal as indented JSON with sorted keys.""" payload = { "base_currency": journal.base_currency, "transactions": [ { "id": tx.id, "date": tx.date.isoformat(), "description": tx.description, "tags": list(tx.tags), "postings": [ { "account": p.account, "amount": format_amount(p.amount), "currency": p.amount.currency, } for p in tx.postings ], } for tx in journal.transactions() ], } return json.dumps(payload, indent=2, sort_keys=True)