"""The journal: an ordered collection of validated transactions.""" from __future__ import annotations import datetime as dt from typing import Dict, Iterable, List, NamedTuple, Optional, Set from .accounts import AccountKind, Chart from .money import Money from .transactions import Transaction class DuplicateTransaction(ValueError): """Raised when a transaction id is posted twice.""" class StatementLine(NamedTuple): date: dt.date tx_id: str description: str amount: Money balance: Money class Journal: def __init__(self, chart: Chart, base_currency: str = "EUR") -> None: self.chart = chart self.base_currency = base_currency self._transactions: List[Transaction] = [] self._ids: Set[str] = set() def __len__(self) -> int: return len(self._transactions) def post(self, tx: Transaction) -> None: """Validate ``tx`` and add it to the journal.""" tx.validate() if tx.id in self._ids: raise DuplicateTransaction(tx.id) for code in tx.accounts(): self.chart.get(code) self._ids.add(tx.id) self._transactions.append(tx) def post_all(self, transactions: Iterable[Transaction]) -> None: for tx in transactions: self.post(tx) def transactions( self, start: Optional[dt.date] = None, end: Optional[dt.date] = None, account: Optional[str] = None, ) -> List[Transaction]: """Transactions in ``[start, end]`` (inclusive) touching ``account``, ordered by date then id.""" selected = [ tx for tx in self._transactions if (start is None or tx.date >= start) and (end is None or tx.date <= end) and (account is None or account in tx.accounts()) ] return sorted(selected, key=lambda tx: (tx.date, tx.id)) def movement( self, code: str, start: Optional[dt.date] = None, end: Optional[dt.date] = None, currency: Optional[str] = None, ) -> Money: """Net debit (positive) or credit (negative) posted to ``code`` in the period.""" self.chart.get(code) currency = currency or self.base_currency total = Money.zero(currency) for tx in self.transactions(start, end, code): total = total + tx.amount_for(code, currency) return total def balance(self, code: str, as_of: Optional[dt.date] = None, currency: Optional[str] = None) -> Money: """Balance of ``code`` including everything posted up to and on ``as_of``.""" return self.movement(code, None, as_of, currency) def natural_balance(self, code: str, as_of: Optional[dt.date] = None, currency: Optional[str] = None) -> Money: """Balance with the sign of the account's normal side (income and liabilities are positive).""" value = self.balance(code, as_of, currency) if self.chart.get(code).kind.normal_side == "credit": return -value return value def trial_balance(self, as_of: Optional[dt.date] = None, currency: Optional[str] = None) -> Dict[str, Money]: """Non-zero balances by account code.""" result: Dict[str, Money] = {} for account in self.chart: value = self.balance(account.code, as_of, currency) if not value.is_zero(): result[account.code] = value return result def statement(self, code: str, currency: Optional[str] = None) -> List[StatementLine]: """Every transaction touching ``code`` with a running balance.""" currency = currency or self.base_currency running = Money.zero(currency) lines: List[StatementLine] = [] for tx in self.transactions(account=code): amount = tx.amount_for(code, currency) running = running + amount lines.append(StatementLine(tx.date, tx.id, tx.description, amount, running)) return lines def kind_totals(self, as_of: Optional[dt.date] = None, currency: Optional[str] = None) -> Dict[AccountKind, Money]: """Sum of balances per account kind.""" totals = {kind: Money.zero(currency or self.base_currency) for kind in AccountKind} for account in self.chart: totals[account.kind] = totals[account.kind] + self.balance(account.code, as_of, currency) return totals