"""Postings and balanced transactions.""" from __future__ import annotations import datetime as dt from dataclasses import dataclass, field from decimal import Decimal from typing import Dict, Iterable, List, Mapping, Optional from .money import Money from .utils import ensure_date, group_by class UnbalancedTransaction(ValueError): """Raised when the postings of a transaction do not add up to zero.""" @dataclass(frozen=True) class Posting: """One line of a transaction. Positive amounts are debits, negative amounts credits.""" account: str amount: Money memo: str = "" @dataclass class Transaction: id: str date: dt.date description: str postings: List[Posting] tags: List[str] = field(default_factory=list) def __post_init__(self) -> None: self.date = ensure_date(self.date) @classmethod def transfer( cls, id: str, date: dt.date, description: str, debit: str, credit: str, amount: Money, tags: Iterable[str] = (), ) -> "Transaction": """Move ``amount`` from the ``credit`` account to the ``debit`` account.""" postings = [Posting(debit, amount), Posting(credit, -amount)] return cls(id, date, description, postings, list(tags)) @classmethod def from_split( cls, id: str, date: dt.date, description: str, source: str, targets: Mapping[str, int], amount: Money, ) -> "Transaction": """Distribute ``amount`` from ``source`` over several accounts in proportion to ``targets``.""" codes = list(targets) shares = amount.allocate([targets[code] for code in codes]) postings = [Posting(code, share) for code, share in zip(codes, shares)] postings.append(Posting(source, -amount)) return cls(id, date, description, postings) def imbalance(self) -> Dict[str, Decimal]: """Non-zero sums of the postings, per currency.""" sums: Dict[str, Decimal] = {} for currency, items in group_by(self.postings, lambda p: p.amount.currency).items(): total = sum((p.amount.amount for p in items), Decimal(0)) if total != 0: sums[currency] = total return sums def is_balanced(self) -> bool: return not self.imbalance() def validate(self) -> None: if len(self.postings) < 2: raise ValueError("transaction %s needs at least two postings" % self.id) gap = self.imbalance() if gap: detail = ", ".join("%s %s" % (value, cur) for cur, value in sorted(gap.items())) raise UnbalancedTransaction("transaction %s is off by %s" % (self.id, detail)) def accounts(self) -> List[str]: """Distinct account codes in order of first appearance.""" seen: List[str] = [] for posting in self.postings: if posting.account not in seen: seen.append(posting.account) return seen def amount_for(self, account: str, currency: Optional[str] = None) -> Money: """Net amount posted to ``account`` (in ``currency``, default: the first posting's).""" currency = currency or self.postings[0].amount.currency total = Money.zero(currency) for posting in self.postings: if posting.account == account and posting.amount.currency == currency: total = total + posting.amount return total def reversed(self, new_id: str, on: Optional[dt.date] = None) -> "Transaction": """The opposite transaction, used to cancel this one.""" postings = [Posting(p.account, -p.amount, p.memo) for p in self.postings] return Transaction( new_id, on or self.date, "Reversal of %s" % self.description, postings, list(self.tags), )