Debian Codegraph @

beancount_periodic/common/utils.py

raw
1 import datetime
2 from decimal import Decimal
3 from typing import Optional
4
5 from beancount.core import data
6
7 from .config import parse
8 from .number import remove_exponent_zero
9 from .number import round_and_remainder
10 from .number import smart_place_num
11
12
13 def select_periodic_posting_groups(entry, meta_name, errors):
14 config_group_postings = {}
15 entry_config_str = entry.meta.get(meta_name) if entry.meta else None
16 if entry_config_str:
17 entry_config, entry_config_err = parse(entry_config_str, Decimal('0'), entry.date, 'M', 'D', Decimal('0'),
18 'line')
19 if entry_config:
20 config_group_postings[entry_config_str] = []
21 else:
22 errors.append(entry_config_err._replace(source=entry.meta))
23
24 for i, posting in enumerate(entry.postings):
25 config_str = posting.meta.get(meta_name) if posting.meta else None
26 if config_str:
27 config, config_err = parse(config_str, posting.units.number, entry.date, 'M', 'D', Decimal('0'),
28 'line')
29 if config:
30 if config_str not in config_group_postings:
31 config_group_postings[config_str] = []
32 config_group_postings[config_str].append((i, config, config_str))
33 else:
34 errors.append(config_err._replace(source=posting.meta))
35 continue
36 elif entry_config_str and entry_config:
37 config_group_postings[entry_config_str].append(
38 (i, entry_config._replace(total=posting.units.number), entry_config_str))
39
40 return [v for k, v in config_group_postings.items()]
41
42
43 def build_steps(meta_key, entry, new_postings_config, positive=True,
44 narration_suffix='(% d / % d)',
45 generate_until: Optional[datetime.date] = None):
46 new_entries = []
47
48 if len(new_postings_config) == 1:
49 posting = new_postings_config[0][1];
50 narration = next(
51 n for n in [posting.meta.get('narration') if posting.meta else None, entry.narration]
52 if n is not None)
53 new_entry_meta = create_meta(entry.meta, deletions=[meta_key],
54 extends={'lineno': posting.meta['lineno']})
55 else:
56 narration = entry.narration
57 new_entry_meta = create_meta(entry.meta, deletions=[meta_key])
58
59 new_entry_narration_template = (narration + ' ' if narration else '') + narration_suffix
60
61 for config, posting, new_account in new_postings_config:
62 total = config.total - config.salvage_value
63 amount_remainder = remove_exponent_zero(total)
64 start_date = config.start
65
66 new_posting_meta = create_meta(posting.meta, deletions=[meta_key, 'narration'])
67
68 if config.equal_amount:
69 place_num = smart_place_num(total, len(config.steps))
70 else:
71 place_num = smart_place_num(total, config.duration)
72
73 round_remainder = Decimal('0')
74 step_num = sum_step_ratio(config)
75 for step_i, (step_days, step_ratio) in enumerate(config.steps):
76 # skip all steps that are past the given date
77 if generate_until and start_date > generate_until:
78 break
79
80 if step_i < len(config.steps) - 1:
81 if config.equal_amount:
82 step_amount, remainder = round_and_remainder(step_ratio * total / step_num, place_num)
83 else:
84 step_amount, remainder = round_and_remainder(Decimal(step_days) / config.duration * total,
85 place_num)
86
87 round_remainder_amount, round_remainder_remainder = round_and_remainder(round_remainder,
88 place_num)
89 if abs(round_remainder_amount) > 0:
90 step_amount += round_remainder_amount
91 round_remainder = round_remainder_remainder
92
93 round_remainder += remainder
94 amount_remainder -= step_amount
95 else: # the last step
96 step_amount = amount_remainder
97 step_amount = remove_exponent_zero(step_amount)
98 end_date = start_date + datetime.timedelta(days=step_days)
99
100 new_entry_narration = new_entry_narration_template % (step_i + 1, len(config.steps))
101 new_postings = create_step_postings(posting,
102 new_account, new_posting_meta,
103 step_amount if positive else -step_amount)
104 if len(new_entries) > step_i and new_entries[step_i]:
105 new_entry = new_entries[step_i]
106 combine_to_entry_posting(new_entry, new_postings, new_account)
107 else:
108 new_entry = create_step_entry(entry, start_date, new_entry_meta, new_entry_narration, new_postings)
109 new_entries.append(new_entry)
110 start_date = end_date
111
112 return new_entries
113
114
115 def combine_to_entry_posting(entry: data.Transaction, new_postings, new_account):
116 existing_index = next(
117 (i for i, posting in enumerate(entry.postings) if posting.account == new_account), None)
118 if existing_index is not None:
119 new_postings_to_extended = []
120 for new_posting in new_postings:
121 existing_posting: data.Posting = entry.postings[existing_index]
122 if new_posting.account == new_account \
123 and new_posting.units.currency == existing_posting.units.currency \
124 and new_posting.cost == existing_posting.cost \
125 and new_posting.price == existing_posting.price:
126 entry.postings[existing_index] = existing_posting._replace(
127 units=data.Amount(existing_posting.units.number + new_posting.units.number,
128 existing_posting.units.currency))
129 else:
130 new_postings_to_extended.append(new_posting)
131 entry.postings.extend(new_postings_to_extended)
132 else:
133 entry.postings.extend(new_postings)
134
135
136 def sum_step_ratio(config):
137 step_num = Decimal('0')
138 for step_days, step_ratio in config.steps:
139 step_num += step_ratio
140 return step_num
141
142
143 def create_step_postings(posting_template: data.Posting,
144 new_account,
145 posting_meta, amount):
146 amount = remove_exponent_zero(amount)
147 new_postings = [data.Posting(
148 account=new_account,
149 units=data.Amount(-amount, posting_template.units.currency),
150 cost=posting_template.cost,
151 price=posting_template.price,
152 flag=posting_template.flag,
153 meta=data.new_metadata(posting_template.meta['filename'], posting_template.meta['lineno'])
154 ), posting_template._replace(units=data.Amount(amount, posting_template.units.currency),
155 meta=posting_meta)]
156
157 return new_postings
158
159
160 def create_step_entry(entry_template, entry_date, entry_meta, entry_narration, entry_postings):
161 new_entry = data.Transaction(
162 date=entry_date,
163 meta=entry_meta,
164 flag=entry_template.flag,
165 payee=entry_template.payee,
166 narration=entry_narration,
167 tags=entry_template.tags,
168 links=entry_template.links,
169 postings=entry_postings
170 )
171 return new_entry
172
173
174 def create_meta(template_meta, deletions, extends={}):
175 new_meta = {}
176 new_meta.update(template_meta)
177 for key in deletions:
178 if key in new_meta:
179 del new_meta[key]
180 for k, v in extends.items():
181 new_meta[k] = v
182 return new_meta