Debian Codegraph @

beancount_periodic/depreciate.py

raw
1 from typing import Dict, Tuple
2
3 import beancount.core.getters
4 from beancount.core import data, account, account_types
5 from beancount.parser import options
6
7 from .common.config import PluginConfig
8 from .common.utils import build_steps
9 from .common.utils import select_periodic_posting_groups
10
11 __plugins__ = ('depreciate',)
12
13
14 def get_depreciation_account(
15 accounts_open_close: Dict[str, Tuple[beancount.core.data.Open, beancount.core.data.Close]],
16 expenses_parent: str,
17 asset_account: beancount.core.data.Account,
18 ) -> str:
19 new_account = str.join(
20 account.sep,
21 [expenses_parent, 'Depreciation', account.sans_root(asset_account)]
22 )
23
24 asset_account_open_statement = accounts_open_close.get(asset_account, None)[0]
25 open_meta = asset_account_open_statement.meta
26 depreciate_account = open_meta.get('depreciate_account', None)
27
28 if depreciate_account:
29 return depreciate_account
30
31 return new_account
32
33
34 def depreciate(entries: data.Entries, unused_options_map, config_string=""):
35 plugin_config = PluginConfig.from_string(config_string)
36 new_entries = []
37 errors = []
38 account_types_option = options.get_account_types(unused_options_map)
39 accounts_open_close = beancount.core.getters.get_account_open_close(entries)
40 for entry in entries:
41 if isinstance(entry, data.Transaction):
42 selected_postings_groups = select_periodic_posting_groups(entry, 'depreciate', errors)
43 for selected_postings in selected_postings_groups:
44 new_postings_config = []
45 for i, config, config_str in selected_postings:
46 posting: data.Posting = entry.postings[i]
47 if account_types.is_account_type(account_types_option.assets, posting.account):
48 new_account = get_depreciation_account(
49 accounts_open_close,
50 account_types_option.expenses,
51 posting.account
52 )
53 else:
54 continue
55 new_postings_config.append((config, posting, new_account))
56
57 new_entries.extend(
58 build_steps('depreciate', entry, new_postings_config,
59 positive=False,
60 narration_suffix='Depreciated(%d/%d)',
61 generate_until=plugin_config.generate_until))
62
63 if new_entries:
64 entries.extend(new_entries)
65 entries.sort(key=data.entry_sortkey)
66
67 return entries, errors