Debian Codegraph @

beancount_periodic/amortize.py

raw
1 from beancount.core import data, account, account_types
2 from beancount.parser import options
3
4 from .common.config import PluginConfig
5 from .common.utils import build_steps
6 from .common.utils import create_meta
7 from .common.utils import select_periodic_posting_groups
8
9 __plugins__ = ('amortize',)
10
11
12 def amortize(entries: data.Entries, unused_options_map, config_string=""):
13 plugin_config = PluginConfig.from_string(config_string)
14 new_entries = []
15 errors = []
16 account_types_option = options.get_account_types(unused_options_map)
17 for entry in entries:
18 if isinstance(entry, data.Transaction):
19 selected_postings_groups = select_periodic_posting_groups(entry, 'amortize', errors)
20 postings_to_insert_original_entry = []
21 for selected_postings in selected_postings_groups:
22 new_postings_config = []
23 for i, config, config_str in selected_postings:
24 posting: data.Posting = entry.postings[i]
25 if account_types.is_account_type(account_types_option.expenses, posting.account):
26 new_account = str.join(account.sep,
27 [account_types_option.equity, 'Amortization',
28 account.sans_root(posting.account)])
29 elif account_types.is_account_type(account_types_option.income, posting.account):
30 new_account = str.join(account.sep,
31 [account_types_option.equity, 'Received',
32 account.sans_root(posting.account)])
33 else:
34 continue
35 total = config.total - config.salvage_value
36
37 new_posting_meta = create_meta(posting.meta, deletions=['amortize', 'narration'])
38
39 if total == posting.units.number:
40 entry.postings[i] = posting._replace(account=new_account)
41 else:
42 entry.postings[i] = posting._replace(
43 units=data.Amount(posting.units.number - total, posting.units.currency))
44 postings_to_insert_original_entry.append((
45 i + 1,
46 posting._replace(account=new_account,
47 units=data.Amount(total, posting.units.currency),
48 meta=new_posting_meta)
49 ))
50 new_postings_config.append((config, posting, new_account))
51
52 new_entries.extend(
53 build_steps('amortize', entry, new_postings_config, positive=True,
54 narration_suffix='Amortized(%d/%d)', generate_until=plugin_config.generate_until))
55
56 postings_to_insert_original_entry.reverse()
57 for i, element in postings_to_insert_original_entry:
58 entry.postings.insert(i, element)
59
60 if new_entries:
61 entries.extend(new_entries)
62 entries.sort(key=data.entry_sortkey)
63
64 return entries, errors