Debian Codegraph @

beancount_periodic/split.py

raw
1 import datetime
2 from decimal import Decimal
3 from typing import List, Tuple, Optional
4
5 from beancount.core import data, account, account_types
6 from beancount.parser import options
7
8 from .common.utils import create_meta
9 from .common.utils import create_step_entry
10 from .common.config import parse, PluginConfig, PeriodicConfig
11
12 __plugins__ = ("split",)
13
14
15 def _create_split_step(entry, step_i, total_steps, date, step_multiplier, entry_meta):
16 new_entry_narration = (entry.narration + " " if entry.narration else "") + f"Split({step_i + 1}/{total_steps})"
17
18 return create_step_entry(
19 entry,
20 date,
21 entry_meta,
22 new_entry_narration,
23 [
24 posting._replace(
25 units=data.Amount(
26 posting.units.number * step_multiplier,
27 posting.units.currency,
28 )
29 )
30 for posting in entry.postings
31 ],
32 )
33
34
35 def _split_entry(entry: data.Transaction, plugin_config: PluginConfig) -> Tuple[List[data.Transaction], List[str]]:
36 entry_config, entry_config_err = parse(
37 entry.meta.get("split"),
38 Decimal("0"),
39 entry.date,
40 "M",
41 "D",
42 Decimal("0"),
43 "line",
44 )
45 if not entry_config:
46 return [], [entry_config_err._replace(source=entry.meta)]
47
48 new_entries = []
49 new_entry_meta = create_meta(entry.meta, deletions=["split", "narration"])
50 start_date = entry_config.start
51 total_days = Decimal(sum(step_days for (step_days, _) in entry_config.steps))
52
53 for step_i, (step_days, step_ratio) in enumerate(entry_config.steps):
54 # skip all steps that are past the given date
55 if plugin_config.generate_until and start_date > plugin_config.generate_until:
56 break
57
58 new_entry = _create_split_step(
59 entry,
60 step_i,
61 len(entry_config.steps),
62 start_date,
63 step_days / total_days,
64 new_entry_meta,
65 )
66 new_entries.append(new_entry)
67 start_date += datetime.timedelta(days=step_days)
68
69 return new_entries, []
70
71
72 def split(entries: data.Entries, unused_options_map, config_string=""):
73 plugin_config = PluginConfig.from_string(config_string)
74 new_entries = []
75 errors = []
76 entries_to_remove = []
77 splittable_entries = [
78 entry
79 for entry in entries
80 if isinstance(entry, data.Transaction) and entry.meta and "split" in entry.meta
81 ]
82
83 for entry in splittable_entries:
84 entry_new_entries, entry_errors = _split_entry(entry, plugin_config)
85 new_entries.extend(entry_new_entries)
86 errors.extend(entry_errors)
87 if entry_new_entries: # Only remove the original entry if we created new ones
88 entries_to_remove.append(entry)
89
90 for entry_to_remove in entries_to_remove:
91 entries.remove(entry_to_remove)
92
93 if new_entries:
94 entries.extend(new_entries)
95 entries.sort(key=data.entry_sortkey)
96
97 return entries, errors