Skip to content

Commit

Permalink
code: nicer printing, but with subclasses
Browse files Browse the repository at this point in the history
  • Loading branch information
epogrebnyak committed Jan 5, 2024
1 parent 0fe962b commit 49788c6
Show file tree
Hide file tree
Showing 7 changed files with 234 additions and 197 deletions.
2 changes: 0 additions & 2 deletions abacus/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1 @@
from .core import Account, Chart, Report # noqa: F401
from .show import echo, show # noqa: F401
from .show_rich import rich_print # noqa: F401
34 changes: 0 additions & 34 deletions abacus/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,23 +203,6 @@ def cx_report(
# cx set --retained-earings-account re
# cx set --null-account null


# def promote(account_name: str):
# """Safe add account to chart."""
# try:
# chart_command().promote(account_name).echo().write()
# except AbacusError as e:
# sys.exit(str(e))


# def last(account_identifier: str) -> str:
# """Get last item of account identifier."""
# return account_identifier.split(":")[-1]


# @chart.command(name="add-many")
# @click.argument("account_labels", required=True, type=str, nargs=-1)
# @click.option("--prefix", type=str, required=False, help="Account type.")
# def add_many(account_labels, prefix):
# """Add several accounts to chart.

Expand All @@ -231,23 +214,6 @@ def cx_report(
# click.echo(account_labels, prefix)


# @chart.command(name="promote")
# @click.argument("account_names", required=True, type=str, nargs=-1)
# @click.option("--title", type=str, required=False, help="Account title.")
# def promote_command(account_names: list[str], title: str):
# """Add accounts to chart using labels like `asset:cash`.

# \b
# Example:
# abacus chart asset:cash capital:equity income:sales expense:cogs
# abacus chart promote contra:sales:refunds --title "Refunds and cashback"
# """
# for account_name in account_names:
# promote(account_name)
# if title and len(account_names) == 1:
# name(account_names[0], title)


@cx.group(name="extra")
def extra():
"""More commands."""
Expand Down
80 changes: 79 additions & 1 deletion abacus/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -357,9 +357,21 @@ def from_string(cls, line: str):
return cls(**json.loads(line))


def use_title(s: str, rename_dict: dict[str, str]) -> str:
return rename_dict.get(s, s).replace("_", " ").strip().capitalize()


class AccountBalances(UserDict[str, Amount]):
def rename(self, rename_dict: [str, str]):
def get(name):
return use_title(name, rename_dict)

return self.__class__({get(name): balance for name, balance in self.items()})

def nonzero(self):
return {name: balance for name, balance in self.items() if balance}
return self.__class__(
{name: balance for name, balance in self.items() if balance}
)

def total(self):
return sum(self.values())
Expand Down Expand Up @@ -520,6 +532,13 @@ def close(self):
class Report:
chart: Chart
ledger: Ledger
rename_dict: dict[str, str] = field(default_factory=dict)

def rename(self, key, value):
self.rename_dict[key] = value
return self

# FIXME: may condense chart after init

@property
def pipeline(self):
Expand Down Expand Up @@ -547,6 +566,17 @@ def trial_balance(self):
def account_balances(self):
return self.ledger.balances

def print_all(self):
b = self.balance_sheet.rename(self.rename_dict)
i = self.income_statement.rename(self.rename_dict)

def f(statement):
return str(statement.viewer().as_column()).split("\n")

width = max(map(len, f(b) + f(i)))
self.trial_balance.viewer().print()
b.viewer(rich=True).print(width)
i.viewer(rich=True).print(width)

class Statement:
...
Expand All @@ -566,6 +596,28 @@ def new(cls, ledger: Ledger):
liabilities=ledger.subset(Liability).balances,
)

def rename(self, rename_dict):
return self.__class__(
assets=self.assets.rename(rename_dict),
capital=self.capital.rename(rename_dict),
liabilities=self.liabilities.rename(rename_dict),
)

def viewer(self, rich=False, header="Balance sheet"):
from abacus.show import RichBalanceSheetViewer
from abacus.show import BalanceSheetViewer

if rich:
return RichBalanceSheetViewer(self, header)
else:
return BalanceSheetViewer(self, header)

def print_rich(self, width=80):
self.viewer(rich=True).print(width)

def print(self):
self.viewer(rich=False).print()


@dataclass
class IncomeStatement(Statement):
Expand All @@ -582,6 +634,27 @@ def new(cls, ledger: Ledger):
def current_profit(self):
return sum(self.income.values()) - sum(self.expenses.values())

def rename(self, rename_dict):
return self.__class__(
income=self.income.rename(rename_dict),
expenses=self.expenses.rename(rename_dict),
)

def viewer(self, rich=False, header="Income statement"):
from abacus.show import RichIncomeStatementViewer
from abacus.show import IncomeStatementViewer

if rich:
return RichIncomeStatementViewer(self, header)
else:
return IncomeStatementViewer(self, header)

def print_rich(self, width=80):
self.viewer(rich=True).print(width)

def print(self):
self.viewer(rich=False).print()


class TrialBalance(UserDict[str, tuple[Amount, Amount]], Statement):
"""Trial balance is a dictionary of account names and
Expand All @@ -597,6 +670,11 @@ def new(cls, ledger):
tb[name] = (0, balance)
return tb

def viewer(self, header="Trial balance"):
from abacus.show import TrialBalanceViewer as TB

return TB(self, header)


def sum_second(xs):
return sum(x for _, x in xs)
Expand Down
Loading

0 comments on commit 49788c6

Please sign in to comment.