-
Notifications
You must be signed in to change notification settings - Fork 0
/
lalloc.py
executable file
·1558 lines (1287 loc) · 48.9 KB
/
lalloc.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python3
from typing import Tuple, Any, Dict, Sequence, List, TextIO, Optional, Mapping, Union
from dataclasses import dataclass, field
from dateutil import relativedelta
from decimal import Decimal, ROUND_HALF_UP
from datetime import datetime, timedelta, date
import logging, argparse
import json, re, jinja2
import ledger
OneDay = timedelta(days=1) - timedelta(seconds=1)
Cents = Decimal("0.01")
def money_id_factory(prefix: str):
counters: Dict[str, int] = {}
def get():
v = counters.setdefault(prefix, 0)
counters[prefix] += 1
return f"{prefix}_{v}"
return get
PaymentId = money_id_factory("P")
def get_income_template(name: str):
with open(name + ".template.ledger") as f:
return jinja2.Template(f.read())
def get_generated_template():
with open("generated.template.ledger") as f:
return jinja2.Template(f.read())
def flatten(a):
return [leaf for sl in a for leaf in sl]
def quantize(d):
return d.quantize(Cents, ROUND_HALF_UP)
def datetime_today_that_is_sane() -> datetime:
return datetime.combine(date.today(), datetime.min.time())
def fail():
raise Exception("fail")
@dataclass
class Names:
available: str = "allocations:checking:available"
refunded: str = "allocations:checking:refunded"
emergency: str = "allocations:checking:savings:emergency"
taxes: str = "allocations:checking:savings:main"
reserved: str = "assets:checking:reserved"
early: str = "allocations:checking:early"
class Handler:
def expand(self, tx: ledger.Transaction, posting: ledger.Posting):
return []
@dataclass
class HandlerPath:
path: str
handler: Handler
compiled: Optional[re.Pattern] = None
def matches(self, path: str) -> bool:
if not self.compiled:
self.compiled = re.compile(self.path)
return self.compiled.match(path) is not None
def apply_handlers(self: ledger.Transactions, paths: List[HandlerPath]) -> List[Any]:
cache: Dict[str, Handler] = {}
returning: List[Any] = []
for tx in self.txs:
for p in tx.postings:
account = p.account
if account not in cache:
cache[account] = NoopHandler()
for hp in paths:
if hp.matches(account):
log.info(
f"{tx.date.date()} handler {account} ({hp.path}): {hp.handler}"
)
cache[account] = hp.handler
break
for p in cache[account].expand(tx, p):
returning.append(p)
return returning
@dataclass
class IncomeDefinition:
name: str
epoch: datetime
factor: Decimal
class Move:
def txns(self):
return []
def compensate(self, names: Names):
return []
@dataclass
class SimpleMove(Move):
date: datetime
value: Decimal
from_path: str
to_path: str
payee: str
cleared: bool = True
tags: List[str] = field(default_factory=list)
refs: List[str] = field(default_factory=list)
def txns(self):
postings = [
ledger.Posting("[" + self.from_path + "]", -self.value, "", tags=[]),
ledger.Posting("[" + self.to_path + "]", self.value, "", tags=[]),
]
return [
ledger.Transaction(
self.date,
self.payee,
self.cleared,
postings=postings,
tags=self.tags,
refs=self.refs,
)
]
def compensate(self, names: Names):
if self.to_path == names.emergency: # HACK
log.info(f"{self.date.date()} {self.to_path:50} {self.value:10} returning")
return {self.to_path: self.value}
return {}
@dataclass
class Taken:
total: Decimal
after: "DatedMoney"
moves: Sequence[Move]
payments: Sequence["Payment"] = field(default_factory=list)
@dataclass
class DatedMoney:
date: datetime
total: Decimal
path: str
note: str
tags: List[str] = field(default_factory=list)
taken: Decimal = Decimal(0)
where: Dict[str, Decimal] = field(default_factory=dict)
refs: Optional[List[str]] = None
mid: str = field(default_factory=PaymentId)
original_date: Optional[datetime] = None
def has_tag(self, name: str) -> bool:
return name in self.tags
def left(self) -> Decimal:
return self.total - self.taken
def redate(self, date: datetime) -> "DatedMoney":
return DatedMoney(
date,
self.left(),
path=self.path,
note=self.note,
tags=self.tags,
refs=self.refs,
)
def take(
self,
money: "DatedMoney",
verb: Optional[str] = None,
partial: bool = False,
refs: Optional[List[str]] = None,
) -> Taken:
assert money.total >= 0
assert quantize(money.total) == money.total
assert verb
refs = (refs or []) + (money.refs or []) + (self.refs or [])
taking = money.total
if partial:
left = self.left()
if taking > left:
taking = left
else:
assert self.taken + taking <= self.total
log.debug(
f"{money.date.date()} {money.path:50} {money.total:10} take total={self.total:8} taken={self.taken:8} {taking=:8} after={self.total - self.taken - taking:8} {self.path} refs={refs} tags={self.tags}+{money.tags}"
)
self.taken += taking
self.where[money.path] = taking
after = DatedMoney(
date=money.date,
total=money.total - taking,
path=money.path,
note=money.note,
where=money.where,
tags=money.tags,
refs=money.refs,
)
moves = [
SimpleMove(
money.date,
taking,
self.path,
money.path,
payee=f"{verb} '{money.date.date()} {money.note}'",
tags=money.tags + self.tags,
refs=refs,
)
]
return Taken(taking, after, moves)
def move(
self,
path: str,
verb: str,
date: Optional[datetime] = None,
tags: Optional[List[str]] = None,
) -> Tuple[Optional["DatedMoney"], List[Move]]:
left = self.left()
if left == 0:
return (None, [])
assert self.refs
self.taken = self.total
effective_date = date if date else self.date
moved = DatedMoney(
date=effective_date,
total=left,
path=path,
note=f"{verb} '{self.note}'",
tags=self.tags,
refs=self.refs,
)
return (
moved,
[
SimpleMove(
effective_date,
left,
self.path,
path,
payee=f"{verb} '{self.note}'",
tags=self.tags + ["debug: 1"] + (tags or []),
refs=self.refs,
)
],
)
@dataclass
class PaysInFuture(DatedMoney):
pass
@dataclass
class RequirePayback(DatedMoney):
def take(
self,
money: DatedMoney,
verb: Optional[str] = None,
partial: bool = False,
refs: Optional[List[str]] = None,
) -> Taken:
assert refs is None
taken = super().take(money, verb=verb, partial=partial)
log.info(
f"{money.date.date()} {self.path:50} {taken.total:10} require-payback refs={money.refs} mid={money.mid} '{money.note}'"
)
payments = [
Payment(
date=money.date,
total=taken.total,
path=self.path,
note=f"borrowing for '{money.date.date()} {money.note}'",
tags=self.tags + ["debug: require-payback"],
refs=money.refs,
)
]
return Taken(taken.total, taken.after, taken.moves, payments)
def move_all_dated_money(
dms: List[DatedMoney],
note: str,
path: str,
date: Optional[datetime] = None,
tags: Optional[List[str]] = None,
) -> Tuple[List[DatedMoney], List[Move]]:
tuples = [dm.move(path, note, date, tags=tags) for dm in dms]
new_money = [dm for dm, m in tuples if dm]
moves = flatten([m for dm, m in tuples])
return (new_money, moves)
def redate_all_dated_money(dms: List[DatedMoney], date: datetime) -> List[DatedMoney]:
return [dm.redate(date) for dm in dms]
class InsufficientFundsError(Exception):
payment: DatedMoney
@dataclass
class MoneyPool:
names: Names = field(repr=False)
money: List[DatedMoney] = field(default_factory=list)
def add(
self,
note: str,
date: datetime,
total: Decimal,
path: str,
tags: Optional[List[str]] = None,
refs: Optional[List[str]] = None,
):
assert refs
self.money.append(
DatedMoney(
date=date, total=total, path=path, note=note, tags=tags or [], refs=refs
)
)
def include(self, more: List[DatedMoney]):
self.money += more
def left(self) -> Decimal:
return Decimal(sum([dm.left() for dm in self.money]))
def _only_income(self, date: datetime, names: Names) -> "MoneyPool":
return MoneyPool(
self.names,
[dm for dm in self.money if dm.date >= date and dm.path != names.emergency],
)
def only_early_payoff(self, date: datetime, names: Names) -> "MoneyPool":
return MoneyPool(
self.names,
[dm for dm in self.money if dm.date <= date and dm.path == names.early],
)
def _only_emergency(self, date: datetime, names: Names) -> "MoneyPool":
return MoneyPool(
self.names,
[dm for dm in self.money if dm.date >= date and dm.path == names.emergency],
)
def _can_use(self, taking: DatedMoney, available: DatedMoney) -> bool:
if taking.path == available.path:
return False
return available.left() > 0 and taking.date >= available.date
def _total_available(self, date: datetime) -> Decimal:
available = [dm for dm in self.money if dm.date >= date]
return Decimal(sum([dm.left() for dm in available]))
def can_take(self, taking: DatedMoney) -> bool:
available = [dm for dm in self.money if self._can_use(taking, dm)]
total_available = sum([dm.left() for dm in available])
return total_available >= taking.total
def take(self, taking: DatedMoney) -> Taken:
if not self.can_take(taking):
for dm in self.money:
using = self._can_use(taking, dm)
log.warning(
f"{dm.date.date()} {dm.path:50} {dm.left():10} / {dm.total:10} taking={taking.path} using={using}"
)
total_available = self._total_available(taking.date)
log.warning(
f"{taking.date.date()} {taking.path:50} {taking.total:10} insufficient available {total_available}"
)
raise InsufficientFundsError(taking)
available = [dm for dm in self.money if self._can_use(taking, dm)]
moves: List[Move] = []
payments: List[Payment] = []
remaining = taking
for available_money in available:
verb = (
"borrowing"
if available_money.path == self.names.emergency
else "payback"
)
taken = available_money.take(remaining, verb=verb, partial=True)
remaining = taken.after
if taken.moves:
moves += taken.moves
payments += taken.payments
if remaining.total == 0:
break
assert remaining.total == 0
return Taken(
taking.total,
DatedMoney(taking.date, Decimal(), "error", "error"),
moves,
payments,
)
def log(self):
log.info(f" {'ACCOUNT':50} {'LEFT':>10} / {'TOTAL':>10}")
for money in self.money:
left = money.left()
if left > 0:
log.info(
f"{money.date.date()} {money.path:50} {left:10} / {money.total:10}"
)
else:
log.debug(
f"{money.date.date()} {money.path:50} {left:10} / {money.total:10}"
)
@dataclass
class Tax:
date: datetime
rate: Decimal
note: Optional[str] = None
path: Optional[str] = None
compiled: Optional[re.Pattern] = None
def matches(self, p: DatedMoney) -> bool:
if not self.compiled:
self.compiled = re.compile(self.path if self.path else self.note)
if self.note:
return self.compiled.match(p.note) is not None
return self.compiled.match(p.path) is not None
@dataclass
class TaxSystem:
names: Names
taxes: List[Tax] = field(default_factory=list)
def add(
self,
date: datetime,
rate: Decimal,
note: Optional[str] = None,
path: Optional[str] = None,
):
log.info(f"{date.date()} {path or note:50} {'':10} taxing {rate:.2}")
self.taxes.append(Tax(date, rate, note=note, path=path))
def tax(self, payment: "DatedMoney", taken_value: Decimal) -> List["Payment"]:
for tax in self.taxes:
if payment.date >= tax.date:
if tax.rate > 0 and tax.matches(payment):
taxed = quantize(tax.rate * taken_value)
log.info(
f"{payment.date.date()} {payment.path:50} {payment.total:10} taxing {taxed:10} {self.names.taxes}"
)
return [
Payment(
date=payment.date,
total=taxed,
path=self.names.taxes,
note=f"{tax.rate:.2} taxes on {taken_value} from {payment.date.date()} {payment.note}",
tags=["debug: tax"],
refs=payment.refs,
)
]
return []
@dataclass
class Period(DatedMoney):
tax_system: TaxSystem = field(default_factory=fail)
income: IncomeDefinition = field(default_factory=fail)
def after(self, spec: str) -> bool:
testing = datetime.strptime(spec, "%m/%d/%Y")
return self.date >= testing
def before(self, spec: str) -> bool:
testing = datetime.strptime(spec, "%m/%d/%Y")
return self.date < testing
def between(self, after: str, before: str) -> bool:
return self.after(after) and self.before(before)
def references(self) -> str:
assert self.refs
return ",".join(self.refs)
def yearly(self, value: Decimal) -> str:
v = quantize(value / Decimal(Decimal(12.0) * self.income.factor))
taken = self.take(
DatedMoney(
date=self.date,
total=v,
path=self.income.name,
note="yearly-ignored",
tags=["debug: monthly-ignored"],
),
verb="yearly",
)
assert taken.after.total == 0
return f"{v:.2f}"
def monthly(self, value: Decimal) -> str:
v = quantize(value / self.income.factor)
taken = self.take(
DatedMoney(
date=self.date,
total=v,
path=self.income.name,
note="monthly-ignored",
tags=["debug: monthly-ignored"],
),
verb="monthly",
)
assert taken.after.total == 0
return f"{v:.2f}"
def done(self) -> str:
l = self.left()
if l < 0.0:
raise Exception(f"overallocated ({l})")
return f"{l:.2f}"
def display(self) -> str:
return f"{self.left():.2f}"
def tax(
self,
rate: Optional[float] = None,
path: Optional[str] = None,
note: Optional[str] = None,
):
assert path or note
self.tax_system.add(
self.date, Decimal(rate if rate else 0), path=path, note=note
)
return f"; tax {path} {rate}"
def __str__(self) -> str:
return self.date.strftime("%Y/%m/%d")
def __repr__(self) -> str:
return str(self)
@dataclass
class Allocator:
period: Period
moves: List[Move] = field(default_factory=list)
def yearly(self, path: str, value: float, note: str) -> str:
v = quantize(
Decimal(value) / Decimal(Decimal(12.0) * self.period.income.factor)
)
taken = self.period.take(
DatedMoney(
date=self.period.date,
total=v,
path=path,
note=f"yearly '{note}' {path}",
tags=["frequency: yearly", f"yearly: {value}"],
refs=self.period.refs,
),
verb="preallocating",
)
self.moves += taken.moves
return f"; yearly ${value:6} paycheck ${v:8} '{note}' {path}"
def monthly(self, path: str, value: float, note: str) -> str:
v = quantize(Decimal(value) / self.period.income.factor)
taken = self.period.take(
DatedMoney(
date=self.period.date,
total=v,
path=path,
note=f"monthly '{note}' {path}",
tags=["frequency: monthly", f"monthly: {value}"],
refs=self.period.refs,
),
verb="preallocating",
)
self.moves += taken.moves
return f"; monthly ${value:6} paycheck ${v:8} '{note}' {path}"
@dataclass
class Expense:
date: datetime
value: Decimal
note: str
path: str
refs: List[str]
@dataclass
class Payment(DatedMoney):
def redate(self, date: Optional[datetime]) -> "Payment":
if date and date != self.date:
log.debug(
f"{self.date.date()} {self.path:50} {self.total:10} payment redate {date.date()}"
)
return Payment(
date,
self.left(),
self.path,
note=self.note,
tags=self.tags,
refs=self.refs,
)
return self
@dataclass
class Paid:
moves: List[Move]
available: List[DatedMoney]
def combine(self, other: "Paid") -> "Paid":
return Paid(self.moves + other.moves, self.available + other.available)
@dataclass
class Spending:
names: Names
today: datetime
payments: List[Payment]
tax_system: TaxSystem
paid: List[Payment] = field(default_factory=list)
verbose: bool = False
def balance(self, path: str) -> Decimal:
return Decimal(sum([p.total for p in self.paid if p.path == path]))
def total_payments_due_on(self, date: datetime) -> Decimal:
payments = sum([p.total for p in self.payments_due_on(date)])
return Decimal(payments)
def payments_due_on(self, date: datetime) -> List[Payment]:
return [p for p in self.payments if p.date == date]
def dates_after_today(self) -> List[datetime]:
unique: Dict[datetime, bool] = {
p.date: True for p in self.payments if self.today <= p.date
}
return list(unique.keys())
def dates_through_today(self) -> List[datetime]:
unique: Dict[datetime, bool] = {
p.date: True for p in self.payments if p.date <= self.today
}
return list(unique.keys())
def dates(self) -> List[datetime]:
unique: Dict[datetime, bool] = {p.date: True for p in self.payments}
return list(unique.keys())
def _make_payments(
self,
date: datetime,
money: MoneyPool,
upcoming_payments: Optional[datetime],
payments: List[Payment],
partial: bool = False,
) -> Paid:
moves: List[Move] = []
available: Dict[str, Decimal] = {}
for p in payments:
# In partial moded we're allowed to exit early, without handling
# every payment we were given so bail if this one can't be handled.
if partial:
if not money.can_take(p):
break
# This is here because spending money keeps the original date, so
# bump to the income date so that the income can be used.
redated = p.redate(date)
# Pay for the thing.
taken = money.take(redated)
if len(taken.moves) > 0:
assert taken.total > 0
self.payments.remove(p)
self.paid.append(p)
need_sort = False
for tax in self.tax_system.tax(redated, taken.total):
self.payments.append(tax)
need_sort = True
for p in taken.payments:
self.payments.append(p.redate(upcoming_payments))
need_sort = True
if need_sort:
self._sort()
for m in taken.moves:
for key, value in m.compensate(self.names).items():
available[key] = available.setdefault(key, Decimal(0)) + value
moves += taken.moves
else:
break
# Be sure and maintain the RequirePayback behavior of money that's returned.
return Paid(
moves,
[
RequirePayback(
date,
total,
path,
"debug: borrowing (ignored note)",
tags=["debug: borrowing"],
refs=[],
)
for path, total in available.items()
],
)
def _get_payments(
self, date: datetime
) -> Tuple[List[Payment], List[Payment], List[Payment]]:
emergency: List[Payment] = []
expenses: List[Payment] = []
future_expenses: List[Payment] = []
for payment in self.payments:
if payment.date <= date and payment.date <= self.today:
if payment.path == self.names.emergency:
emergency.append(payment)
else:
expenses.append(payment)
if payment.has_tag(DebugTagScheduled) and payment.date >= date:
future_expenses.append(payment)
future_expenses.reverse()
return (emergency, expenses, future_expenses)
def pay_from(
self,
date: datetime,
money: MoneyPool,
upcoming_payments: Optional[datetime],
paranoid: bool = False,
) -> Paid:
assert upcoming_payments != date
log.info(
f"{date.date()} ------------------------------------------------------------------------------------------"
)
emergency, expenses, future_expenses = self._get_payments(date)
total_expenses = sum([p.left() for p in expenses])
total_emergency = sum([p.left() for p in emergency])
logged_upcoming = upcoming_payments.date() if upcoming_payments else ""
log.info(
f"{date.date()} {'':50} {'':10} pay-from expenses={total_expenses:10} emergency={total_emergency:10} {len(expenses):2}/{len(emergency):2} upcoming={logged_upcoming} today={self.today.date()}"
)
if self.verbose:
for dm in money.money:
log.debug(
f"{dm.date.date()} {dm.path:50} {dm.left():10} / {dm.total:10}"
)
log.debug(f"{date.date()}")
# Pay off whatever we can from, partially if we're paranoid and covering
# from emergency so only errors if not paranoid and we can't cover everything.
paid = self._make_payments(
date, money, upcoming_payments, emergency + expenses, partial=paranoid
)
only_future = money.only_early_payoff(date, self.names)
log.info(f"{date.date()} {only_future}")
paid_towards_future = self._make_payments(
date, only_future, upcoming_payments, future_expenses, partial=True
)
log.info(f"{date.date()} {paid_towards_future}")
paid = paid.combine(paid_towards_future)
if paranoid:
# Now, get whatever can still be paid, this is a little more
# expensive performance wise though way easier to maintain and work
# with because there's only the one function to maintain.
emergency, expenses, future_expenses = self._get_payments(date)
# If we have a pay date coming up, we can be more flexible with when
# emergency gets paid back.
if upcoming_payments:
# Move emergency payments to the upcoming pay date, we can never
# have outstanding payments in the past because they'll never
# get paid because we require payment dates to be after income
# dates, so if an emergency payment can't be made we gotta redate.
for p in emergency:
self.payments.remove(p)
self.payments.append(p.redate(upcoming_payments))
# Now we require all expenses to be paid, this should fall back on
# emergency to cover everything.
return paid.combine(
self._make_payments(date, money, upcoming_payments, expenses)
)
log.info(f"{date.date()} no upcoming-payments date")
# No unpaid payments allowed.
return paid
def _sort(self):
self.payments.sort(key=lambda p: (p.date, p.total))
DebugTagScheduled = "debug: schedule-handler"
@dataclass
class Schedule(Handler):
today: datetime
maximum: Optional[Decimal] = None
def expand(self, tx: ledger.Transaction, posting: ledger.Posting):
if posting.value > 0:
return []
assert tx.mid
expense = Expense(
date=tx.date,
value=posting.value.copy_abs(),
path=posting.account,
note=tx.payee,
refs=[tx.mid],
)
from_payee = False
if m := re.search("payoff:(\d+)", tx.payee):
self.maximum = Decimal(m.group(1))
from_payee = True
if self.maximum:
payments: List[Payment] = []
remaining = expense.value
date = expense.date
while remaining > 0:
taking = self.maximum if remaining > self.maximum else remaining
if from_payee:
log.debug(
f"payee-schedule: date={date} {taking} note={expense.note}"
)
else:
log.debug(f"schedule: date={date} {taking} note={expense.note}")
payments.append(
Payment(
date=date,
original_date=expense.date,
total=taking,
path=expense.path,
note=expense.note,
tags=[DebugTagScheduled],
refs=[PaymentId()] + expense.refs,
)
)
remaining -= taking
date += relativedelta.relativedelta(months=1)
return payments
log.debug(
f"{expense.date.date()} schedule: {expense.value:10} note='{expense.note}'"
)
return [
Payment(
date=expense.date,
total=expense.value,
path=expense.path,
note=expense.note,
tags=["debug: schedule-handler"],
refs=[PaymentId()] + expense.refs,
)
]
@dataclass
class NoopHandler(Handler):
def expand(self, tx: ledger.Transaction, posting: ledger.Posting):
return []
@dataclass
class IncomeHandler(Handler):
income: IncomeDefinition
path: str
tax_system: TaxSystem
def expand(self, tx: ledger.Transaction, posting: ledger.Posting):
log.info(f"{tx.date.date()} income: {posting} {posting.value} refs=[{tx.mid}]")
assert tx.mid
return [
Period(
note=tx.payee,
path=self.path,
date=tx.date,
total=posting.value.copy_abs(),
income=self.income,
tax_system=self.tax_system,
tags=[f"income: {self.income.name}"],
refs=[tx.mid],
)
]
@dataclass
class DatedMoneyHandler(Handler):
positive_only = True
def expand(self, tx: ledger.Transaction, posting: ledger.Posting):
if self.positive_only:
if posting.value < 0:
return []
log.info(f"{tx.date.date()} dated-money: {posting} {posting.value}")
assert tx.mid
return [
DatedMoney(
date=tx.date,
total=posting.value.copy_abs(),
path=posting.account,
note=tx.payee,
tags=["debug: dated-money-handler"],
refs=[tx.mid],
)
]
@dataclass
class EnvelopeDatedMoney(DatedMoney):
envelope: Optional[str] = None
source: Optional[str] = None
cleared: bool = False
paid: bool = False
def allocated(self) -> List[Payment]:
assert self.envelope
assert self.note
assert self.refs
if self.total > 0:
if self.paid:
log.info(
f"{self.date.date()} {self.source:50} {self.total:10} paid refs={self.refs} mid={self.mid} '{self.note}'"
)
return []
log.info(
f"{self.date.date()} {self.source:50} {self.total:10} allocated refs={self.refs} mid={self.mid} '{self.note}'"
)
return [
Payment(
self.date,
self.total,
self.envelope,
note=self.note,
tags=self.tags + ["debug: envelope-allocated"],
refs=self.refs + [self.mid],