Debian Codegraph @

beancount_periodic/recur.py

raw
1 import datetime
2 from decimal import Decimal
3
4 from beancount.core import data, account, account_types
5 from beancount.parser import options
6
7 from .common.utils import create_meta
8 from .common.utils import create_step_entry
9 from .common.config import parse, PluginConfig
10
11 __plugins__ = ('recur',)
12
13
14 def recur(entries: data.Entries, unused_options_map, config_string=""):
15 plugin_config = PluginConfig.from_string(config_string)
16 new_entries = []
17 errors = []
18 account_types_option = options.get_account_types(unused_options_map)
19 entries_to_remove = []
20 for entry in entries:
21 if isinstance(entry, data.Transaction):
22 entry_config_str = entry.meta.get('recur') if entry.meta else None
23 if entry_config_str:
24 entry_config, entry_config_err = parse(entry_config_str, Decimal('0'), entry.date, 'M', 'D', Decimal('0'),'line')
25
26 if entry_config:
27 new_entry_meta = create_meta(entry.meta, deletions= ['recur', 'narration'])
28 start_date = entry_config.start
29 new_entry_narration_template = (entry.narration + ' ' if entry.narration else '') + 'Recurring(%d/%d)'
30
31 for step_i, (step_days, step_ratio) in enumerate(entry_config.steps):
32 # skip all steps that are past the given date
33 if plugin_config.generate_until and start_date > plugin_config.generate_until:
34 break
35
36 new_entry_narration = new_entry_narration_template % (step_i + 1, len(entry_config.steps))
37 end_date = start_date + datetime.timedelta(days=step_days)
38
39 new_entry = create_step_entry(entry, start_date, new_entry_meta, new_entry_narration, entry.postings)
40 new_entries.append(new_entry)
41 start_date = end_date
42 pass
43 pass
44 entries_to_remove.append(entry)
45 else:
46 errors.append(entry_config_err._replace(source=entry.meta))
47 continue
48 pass
49 pass
50
51 for entry_to_remove in entries_to_remove:
52 entries.remove(entry_to_remove)
53
54 if new_entries:
55 entries.extend(new_entries)
56 entries.sort(key=data.entry_sortkey)
57
58 return entries, errors