Files
leleka/scripts/e2e/codex/tasks/fixbug-ledger/reference/overlay/ledger/accounts.py
T

103 lines
3.1 KiB
Python

"""Accounts and the chart of accounts."""
from __future__ import annotations
from enum import Enum
from typing import Dict, Iterable, Iterator, List, Optional
class AccountKind(Enum):
ASSET = "asset"
LIABILITY = "liability"
EQUITY = "equity"
INCOME = "income"
EXPENSE = "expense"
@property
def normal_side(self) -> str:
"""The side on which the account normally grows."""
if self in (AccountKind.ASSET, AccountKind.EXPENSE):
return "debit"
return "credit"
class UnknownAccount(KeyError):
"""Raised when an account code is not in the chart."""
class DuplicateAccount(ValueError):
"""Raised when an account code is added twice."""
class Account:
def __init__(self, code: str, name: str, kind: AccountKind, labels: Optional[Iterable[str]] = None) -> None:
self.code = code
self.name = name
self.kind = kind
self.labels: List[str] = list(labels or [])
def add_label(self, label: str) -> None:
if label not in self.labels:
self.labels.append(label)
def has_label(self, label: str) -> bool:
return label in self.labels
def __repr__(self) -> str:
return "Account(%r, %r, %s)" % (self.code, self.name, self.kind.name)
class Chart:
"""A chart of accounts, indexed by account code."""
def __init__(self, accounts: Iterable[Account] = ()) -> None:
self._accounts: Dict[str, Account] = {}
for account in accounts:
self.add(account)
def add(self, account: Account) -> Account:
if account.code in self._accounts:
raise DuplicateAccount(account.code)
self._accounts[account.code] = account
return account
def get(self, code: str) -> Account:
try:
return self._accounts[code]
except KeyError:
raise UnknownAccount(code) from None
def __contains__(self, code: object) -> bool:
return code in self._accounts
def __len__(self) -> int:
return len(self._accounts)
def __iter__(self) -> Iterator[Account]:
for code in sorted(self._accounts):
yield self._accounts[code]
def by_kind(self, kind: AccountKind) -> List[Account]:
return [a for a in self if a.kind is kind]
def by_label(self, label: str) -> List[Account]:
return [a for a in self if a.has_label(label)]
def default_chart() -> Chart:
"""The chart used by the command line tool."""
rows = [
("1000", "Bank", AccountKind.ASSET),
("1100", "Receivables", AccountKind.ASSET),
("2000", "Payables", AccountKind.LIABILITY),
("3000", "Owner equity", AccountKind.EQUITY),
("4000", "Sales", AccountKind.INCOME),
("4100", "Interest income", AccountKind.INCOME),
("4900", "Other income", AccountKind.INCOME),
("5000", "Rent", AccountKind.EXPENSE),
("5100", "Groceries", AccountKind.EXPENSE),
("5200", "Utilities", AccountKind.EXPENSE),
("5900", "Other expenses", AccountKind.EXPENSE),
]
return Chart(Account(code, name, kind) for code, name, kind in rows)