aboutsummaryrefslogtreecommitdiff
path: root/geldschieberbot.py
blob: 39352d2c291697381fc90aa50a35629e492cb7e4 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
#!/usr/bin/env python3
"""Bot to manage a groups finances"""

import argparse
from datetime import date, datetime, timedelta
from dataclasses import dataclass, field
import json
import os
import subprocess
import sys
import typing as T

# Path where our data is stored persistent on disk
STATE_FILE = os.environ["GSB_STATE_FILE"]

GROUP_ID = os.environ["GSB_GROUP_ID"]

SEND_CMD = os.environ["GSB_SEND_CMD"]
GROUP_SEND_CMD = SEND_CMD + GROUP_ID


@dataclass
class MessageContext:
    """Class representing the context of a message passed to a command function"""
    sender_number: str
    sender: T.Optional[str]
    args: list[str]
    body: list[str]
    timestamp: str


@dataclass
class Modification:
    """Class representing a single modification to the balance

    Amount is transfered from donor to the recipient.
    """
    recipient: str
    donor: str
    amount: int

    def in_string(self) -> str:
        """Format the change using the recipient as initiator"""
        return f'{self.recipient} {"->" if self.amount < 0 else "<-"} {to_euro(abs(self.amount))} {self.donor}'

    def out_string(self) -> str:
        """Format the change using the donor as initiator"""
        return f'{self.donor} {"->" if self.amount < 0 else "<-"} {to_euro(abs(self.amount))} {self.recipient}'


@dataclass
class Change:
    """Class representing a change to the state caused by a single command"""
    cmd: list[str]
    modifications: list[Modification]
    timestamp: str
    rewind_cmds: list[list[str]] = field(default_factory=lambda: [])


@dataclass
class Quote:
    """Class representing a message to quote"""
    timestamp: str
    author: str


class GeldschieberbotJSONEncoder(json.JSONEncoder):
    """Custom JSONEncoder supporting our dataclasses"""

    def default(self, o):
        if isinstance(o, (Modification, Change)):
            return o.__dict__
        return json.JSONEncoder.default(self, o)


def to_cent(euro) -> int:
    """Parse string containing euros into a cent value"""
    if '.' in euro:
        euro = euro.split('.')
    else:
        euro = euro.split(',')
    if len(euro) > 2:
        raise TypeError
    euro[0] = int(euro[0])
    if len(euro) < 2:
        euro.append(0)
    else:
        if len(euro[1]) == 1:
            euro[1] = int(euro[1]) * 10
        else:
            euro[1] = int(euro[1])
    amount = euro[0] * 100 + euro[1]
    if amount < 0:
        raise ValueError
    return amount


def to_euro(cents) -> str:
    """Format cents as euro"""
    return f"{cents/100:.2f}"


class Geldschieberbot:
    """
    State of the geldschieberbot

    The state is stored in a central dict for convenient writing to and
    reading from disk.

    The state contains:
    * balance - dict of dicts associating two persons to an amount
    * name2num, num2name - dicts associating numbers to names and vice versa
    * cars - dict associating car names to their service charge
    * scheduled_cmds - dict associating names to cmds, their schedule,
                       and their last execution
    * changes - dict associating users with their changes
    * aliases - list of names mapping to multiple other names

    The central component of the geldschieberbot's state is the balance dictionary
    assigning a cent amount to each pair of participants (following A and B).
    The tracked amount represents the money the first component has to provide
    to the second to even out the balance.
    If money is transferred from A to B it is expected from B to give the same amount
    of money back to A.
    Moving money from A to B is tracked in both balances A->B and B->A.
    The amount is subtracted from the A->B balance and added to the B->A balance
    meaning that B has to give A money to even out the balance.

    """

    STATE_KEYS = ("balance", "name2num", "num2name", "available_cars",
                  "scheduled_cmds", "changes", "aliases")

    def load_state(self, state_path=STATE_FILE):
        """Load state from disk"""
        if os.path.isfile(state_path):
            with open(state_path, 'r', encoding='utf-8') as state_f:
                self.state = json.load(state_f)
        else:
            self.state = {key: {} for key in self.STATE_KEYS}

        try:
            # decode JSON changes
            self.state['changes'] = {
                name: [
                    Change(ch['cmd'], [
                        Modification(*mod.values())
                        for mod in ch['modifications']
                    ], ch['timestamp'], ch['rewind_cmds']) for ch in changes
                ]
                for name, changes in self.state['changes'].items()
            }
        except (KeyError, TypeError):
            # convert from old plain changes format
            if isinstance(list(self.state['changes'].values())[0], list):
                self.state['changes'] = {
                    name: [
                        Change(ch[0],
                               [Modification(r, d, a)
                                for r, d, a in ch[1:]], None) for ch in changes
                    ]
                    for name, changes in self.state['changes'].items()
                }

        for key in self.STATE_KEYS:
            # add missing keys to an existsing state
            setattr(self, key, self.state.setdefault(key, {}))

        # Do this simply to allow pylint to lint the Geldschieberbot and
        # prevent false positive 'no-member' errors.
        self.balance = self.state["balance"]
        self.name2num = self.state["name2num"]
        self.num2name = self.state["num2name"]
        # Workaround old states using the cars key instead of available_cars
        if 'cars' in self.state:
            all_cars = self.state['cars']
            del self.state['cars']
            all_cars.update(self.state['available_cars'])
            self.state['available_cars'] = all_cars
        self.available_cars = self.state["available_cars"]
        self.scheduled_cmds = self.state["scheduled_cmds"]
        self.changes = self.state["changes"]
        self.aliases = self.state["aliases"]

    def save_state(self, state_path=STATE_FILE):
        """Load state from disk"""
        with open(state_path, 'w', encoding='utf-8') as state_file:
            json.dump(self.state, state_file, cls=GeldschieberbotJSONEncoder)

    def record(self, recipient: str, donor: str,
               amount: int) -> T.Optional[Modification]:
        """Apply changes to the balance"""

        return self.apply(Modification(recipient, donor, amount))

    def apply(self, mod: Modification) -> T.Optional[Modification]:
        """Apply a single modification to the balance"""

        # Only change anything if this is not a dry run
        if self.dry_run:
            return None

        self.balance[mod.donor][mod.recipient] += mod.amount
        self.balance[mod.recipient][mod.donor] -= mod.amount

        return mod

    def reverse(self, mod: Modification) -> Modification:
        """Reverse the effect of a single modification to the balance"""

        self.balance[mod.donor][mod.recipient] -= mod.amount
        self.balance[mod.recipient][mod.donor] += mod.amount

        return Modification(mod.donor, mod.recipient, mod.amount)

    def send(self,
             msg,
             attachment=None,
             cmd=SEND_CMD,
             quote: T.Optional[Quote] = None):
        """Send a message with optional attachment"""
        if not self.quiet:
            if attachment:
                cmd += f' -a {attachment}'
            if quote:
                cmd += f' --quote-timestamp={quote.timestamp} --quote-author={quote.author}'
            subprocess.run(cmd.split(' '), input=msg.encode(), check=False)

    def create_summary(self, user, include=None) -> str:
        """Create a summary for a user"""
        msg = ''
        cars_summary = ""
        total = 0
        cars_total = 0
        p_balances = self.balance[user]  # failes if user is not in balance
        for person in p_balances:
            if include and not person in include:
                continue

            amount = p_balances[person]
            if amount == 0:
                continue
            if person in self.available_cars:
                cars_total -= amount
                cars_summary += f'\t{"<-" if amount < 0 else "->"} {person} {to_euro(abs(amount))}\n'
            else:
                total -= amount
                msg += f'\t{"<-" if amount < 0 else "->"} {person} {to_euro(abs(amount))}\n'

        if not msg:
            msg = '\tAll fine :)'
        else:
            msg += f'\tBalance: {to_euro(total)}'

        ret_summary = f'{user}:\n{msg}'

        if cars_summary:
            cars_summary += f'\tLiability: {to_euro(cars_total)}'
            ret_summary += f'\n\tCars:\n{cars_summary}'

        return ret_summary

    def create_total_summary(self) -> str:
        """Create a summary of all balances"""
        msg = 'Summary:'

        cars_summary = ''
        for person in self.balance:
            p_summary = self.create_summary(person)
            if person in self.available_cars:
                cars_summary += f'\n{p_summary}'
            else:
                msg += f'\n{p_summary}'

        if cars_summary:
            msg += f'\nCars:{cars_summary}'
        return msg

    def create_members(self) -> str:
        """Create a list of all group members"""
        out = ""
        for member in self.name2num:
            out += f'{member}: {self.name2num[member]}\n'
        return out

    def add_to_balance(self, name: str):
        """Add a new user balance"""
        new_balance = {}
        for member in self.balance:
            self.balance[member][name] = 0
            new_balance[member] = 0
        self.balance[name] = new_balance

    def remove_from_balance(self, name: str):
        """Remove a user balance"""
        del self.balance[name]
        for member in self.balance:
            del self.balance[member][name]

    def expand_aliases(self,
                       users: list[str],
                       exclude_users=None) -> list[str]:
        """Expand any alias

        Any user name in exclude_users will not be expanded. This is usefull
        when using aliases with commands implicitly adding a user like !split.
        """
        ret = []
        for user in users:
            if not user in self.aliases and user != 'all':
                ret.append(user)
                continue

            expanded_users = []
            if user in self.aliases:
                expanded_users += self.aliases[user]
            else:
                expanded_users += list(self.name2num.keys())

            ret.extend([
                u for u in expanded_users
                if not exclude_users or u not in exclude_users
            ])

        return ret

    @classmethod
    def create_help(cls) -> str:
        """Return a help message explaining how to use geldschieberbot"""
        return """
    Usage: send a message starting with '!' followed by a command
    Commands:
    ls | list - print all registered members
    help - print this help message
    reg name - register the sender with the name: name
    sum [name] - print summary of specific users
    full-sum - print summary of all users

    alias - list registered aliases
    alias name person [persons] - create an alias for one or multiple persons
    alias remove name - remove an alias

    split amount person [persons] - split amount between the sender and persons
    teil amount person [persons] - split amount between the sender and persons

    schieb amount recipient [recipients ...] - give money to one or more recipients
    gib amount recipient [recipients ...] - give money to one or more recipients
    zieh amount donor [donor ...] - get money from one or more donors
    nimm amount donor [donor ...] - get money from one or more donors

    transfer amount source destination - transfer amount of your balance from source to destination

    cars [cmd] - interact with the available cars
    cars [list | ls] - list available cars and their service charge
    cars add car-name service-charge - add new car
    cars new car-name service-charge - add new car
    cars remove car-name - remove a car
    cars pay car-name amount - pay a bill for the specified car

    tanken amount [person] [car] [info] - calculate fuel costs, service charge and add them to the person's and car's balance respectively

    fuck [change] - rewind last or specific change
    list-changes [n] [first] - list the last n changes starting at first

    export-state - send the state file

    weekly name cmd -  repeat cmd each week
    monthly name cmd - repeat cmd each month
    yearly name cmd - repeat cmd each year
    cancel name - stop repeating cmd

    Happy Geldschieben!
    """

    def register(self, msg: MessageContext) -> dict[str, str]:
        """Register a new user"""
        if len(msg.args) != 2:
            return {'err': f'not in form "{msg.args[0]} name"'}
        name = msg.args[1]

        try:
            to_cent(name)
            return {'err': 'pure numerical names are not allowed'}
        except (ValueError, TypeError):
            pass

        if name in self.name2num:
            return {'err': f'{name} already registered'}

        if msg.sender:
            return {'err': f'you are already registered as {msg.sender}'}

        self.num2name[msg.sender_number] = name
        self.name2num[name] = msg.sender_number

        self.add_to_balance(name)

        # add changes list
        self.changes[name] = []
        return {'msg': f'Happy geldschiebing {name}!'}

    def summary(self, msg: MessageContext) -> dict[str, str]:
        """Print summary for one or multiple balances"""
        if len(msg.args) == 1:
            if not msg.sender:
                return {'err': 'You must register first to print your summary'}
            return {'msg': f'Summary:\n{self.create_summary(msg.sender)}'}

        out = "Summary:\n"
        for name in self.expand_aliases(msg.args[1:]):
            if name in self.name2num or name in self.available_cars:
                out += self.create_summary(name) + "\n"
            else:
                return {'err': f'name "{name}" not registered'}
        return {'msg': out}

    def full_summary(self, msg: MessageContext) -> dict[str, str]:
        """Print a summary of all balances"""
        if len(msg.args) == 1:
            return {'msg': self.create_total_summary()}

        return {'err': f'{msg.args[0][1:]} takes no arguments'}

    def list_users(self, msg: MessageContext) -> dict[str, str]:  # pylint: disable=unused-argument
        """List all registered users"""
        return {'msg': self.create_members()}

    @classmethod
    def usage(cls, msg: MessageContext) -> dict[str, str]:  # pylint: disable=unused-argument
        """Return the usage"""
        return {'msg': cls.create_help()}

    def split(self, msg: MessageContext) -> dict[str, str]:
        """Split a fixed amount across multiple persons"""
        if not msg.sender:
            return {'err': 'you must register first'}

        if len(msg.args) < 3:
            return {'err': f'not in form "{msg.args[0]} amount [name]+"'}

        try:
            amount = to_cent(msg.args[1])
            persons = msg.args[2:]
        except (ValueError, TypeError):
            # support !split name amount
            if len(msg.args) == 3:
                try:
                    amount = to_cent(msg.args[2])
                    persons = [msg.args[1]]
                except (ValueError, TypeError):
                    return {'err': 'amount must be a positive number'}
            else:
                return {'err': 'amount must be a positive number'}

        recipient = msg.sender
        # exclude the implicit recipient from alias expension
        persons = self.expand_aliases(persons, exclude_users=[recipient])
        # persons + sender
        npersons = len(persons) + 1
        amount_per_person = int(amount / npersons)

        output = f"Split {to_euro(amount)} between {npersons} -> {to_euro(amount_per_person)} each\n"
        modifications: list[Modification] = []
        for person in persons:
            if person in self.name2num:
                if person == recipient:
                    output += (
                        f'{person}, you will be charged multiple times. '
                        'This may not be what you want\n')
                else:
                    modification = self.record(recipient, person,
                                               amount_per_person)
                    if modification:
                        modifications.append(modification)
            else:
                output += f"{person} not known. Please take care manually\n"

        self.may_record_change(recipient,
                               Change(msg.args, modifications, msg.timestamp))

        output += "New Balance:\n"
        output += self.create_summary(recipient)
        return {'msg': output}

    def _transaction(self, initiator: str, recipients: list[str],
                     amount: int) -> tuple[str, list[Modification]]:
        """Record a transaction"""
        transaction_sum = ''

        modifications: list[Modification] = []
        for recipient in recipients:
            modification = self.record(initiator, recipient, amount)
            if modification:
                modifications.append(modification)

            p_balance = self.balance[initiator][recipient]

            transaction_sum += f'{"->" if amount > 0 else "<-"} {recipient} {to_euro(abs(amount))}\n'

        output = ''
        if len(recipients) > 1:
            output += transaction_sum
            output += 'New Balance:\n'
            output += self.create_summary(initiator, recipients)
        else:
            output = f'New Balance: {initiator} {"->" if p_balance > 0 else "<-"} {to_euro(abs(p_balance))} {recipients[0]}\n'
        return output, modifications

    def transaction(self, msg: MessageContext) -> dict[str, str]:
        """Record a transaction received in a message"""
        if len(msg.args) < 3:
            return {
                'err':
                f'not in form "{msg.args[0]} amount recipient [recipient ...]"'
            }

        if not msg.sender:
            return {'err': 'you must register first'}

        if len(msg.args) == 3:
            if msg.args[1] in self.balance or msg.args[1] in self.aliases:
                recipient, _amount = msg.args[1:3]
            elif msg.args[2] in self.balance or msg.args[2] in self.aliases:
                _amount, recipient = msg.args[1:3]
            else:
                return {'err': 'recipient not known'}

            recipients = self.expand_aliases([recipient])
        else:
            _amount, recipients = msg.args[1], msg.args[2:]

        if msg.sender in recipients:
            return {'err': 'you can not transfer money to or from yourself'}

        try:
            amount = to_cent(_amount)
        except (ValueError, TypeError):
            return {'err': 'amount must be a positive number'}

        for recipient in recipients:
            if recipient not in self.balance:
                return {'err': f'recipient "{recipient}" not known'}

        if msg.args[0] in ["!zieh", "!nimm"]:
            amount *= -1

        output, modifications = self._transaction(msg.sender, recipients,
                                                  amount)
        self.may_record_change(msg.sender,
                               Change(msg.args, modifications, msg.timestamp))
        return {'msg': output}

    def _transfer(self, sender: str, source: str, destination: str,
                  amount: int) -> tuple[str, list[Modification]]:
        """Transfer amount from one balance to another"""
        # Sender <- X Source
        output, modifications = self._transaction(sender, [source], -amount)

        # Sender -> X Destination
        out, modification = self._transaction(sender, [destination], amount)
        output += out
        modifications += modification

        # Destination -> X Source
        out, modification = self._transaction(source, [destination], -amount)
        output += out
        modifications += modification

        return output, modifications

    def transfer(self, msg: MessageContext) -> dict[str, str]:
        """Message handler wrapping the transfer function"""
        if len(msg.args) < 4:
            return {
                'err': f'not in form "{msg.args[0]} amount source destination"'
            }

        if not msg.sender:
            return {'err': 'you must register first'}

        try:
            amount_raw = msg.args[1]
            amount_cent = to_cent(amount_raw)
        except (ValueError, TypeError):
            return {'err': 'amount must be a positive number'}

        source, destination = msg.args[2:4]
        if source not in self.balance:
            return {'err': f'source "{source}" not known'}

        if destination not in self.balance:
            return {'err': f'destination "{destination}" not known'}

        out, modifications = self._transfer(msg.sender, source, destination,
                                            amount_cent)
        self.may_record_change(msg.sender,
                               Change(msg.args, modifications, msg.timestamp))
        return {'msg': out}

    def cars(self, msg: MessageContext) -> dict[str, str]:
        """Manage available cars

        List, add, remove or pay a bill for a car.
        """
        # list cars
        if len(msg.args) < 2 or msg.args[1] in ["ls", "list"]:
            if len(self.available_cars) == 0:
                return {'msg': 'No cars registered yet.'}

            ret_msg = ""

            if len(msg.args) > 2:
                cars_to_list = msg.args[2:]
            else:
                cars_to_list = self.available_cars

            for car in cars_to_list:
                if car in self.available_cars:
                    ret_msg += f"{car} - service charge {self.available_cars[car]}ct/km\n"
                    ret_msg += self.create_summary(car) + "\n"
                else:
                    return {'err': f'"{car}" is no available car\n'}

            return {'msg': ret_msg[:-1]}

        # add car
        if msg.args[1] in ["add", "new"]:
            if len(msg.args) < 4:
                return {
                    'err':
                    f'not in form "{msg.args[0]} {msg.args[1]} car-name service-charge"'
                }

            car = msg.args[2]
            if car in self.available_cars:
                return {'err': f'"{car}" already registered'}

            if car in self.balance:
                return {
                    'err':
                    f'A user named "{car}" already exists. Please use a different name for this car'
                }

            try:
                service_charge = to_cent(msg.args[3])
            except (ValueError, TypeError):
                return {'err': 'service-charge must be a positive number'}

            self.available_cars[car] = service_charge
            self.add_to_balance(car)
            return {'msg': f'added "{car}" as an available car'}

        # remove car
        if msg.args[1] in ["rm", "remove"]:
            if len(msg.args) < 3:
                return {
                    'err':
                    f'not in form "{msg.args[0]} {msg.args[1]} car-name"'
                }

            car = msg.args[2]
            if car not in self.available_cars:
                return {'err': f'A car with the name "{car}" does not exists'}

            del self.available_cars[car]
            self.remove_from_balance(car)
            return {'msg': f'removed "{car}" from the available cars'}

        # pay bill
        if msg.args[1] in ["pay"]:
            if len(msg.args) < 4:
                return {
                    'err':
                    f'not in form "{msg.args[0]} {msg.args[1]} car-name amount"'
                }

            if not msg.sender:
                return {'err': 'you must register first'}

            car = msg.args[2]
            # print(self.state, self.available_cars)
            if car not in self.available_cars:
                return {'err': f'car "{car}" not known'}

            try:
                amount = to_cent(msg.args[3])
                amount_euro = to_euro(amount)
            except (ValueError, TypeError):
                return {'err': 'amount must be a positive number'}

            output = ""

            total_available_charge = 0
            available_charges = []
            for person in self.balance[car]:
                _amount = self.balance[car][person]
                if _amount < 0:
                    total_available_charge -= _amount
                    available_charges.append((person, _amount))

            proportion = -1.0
            if amount < total_available_charge:
                proportion = -1 * (amount / total_available_charge)

            _, modifications = self._transaction(msg.sender, [car], amount)
            output += f"{msg.sender} payed {amount_euro}\n"

            # transfer money
            output += f"Transferring {proportion * -100:.2f}% of everybody's charges\n"
            for person, _amount in available_charges:
                if person == msg.sender or _amount >= 0:
                    continue

                to_move = int(_amount * proportion)
                to_move_euro = to_euro(to_move)
                _, modification = self._transfer(msg.sender, car, person,
                                                 to_move)
                modifications += modification

                output += f'Transfer {to_move_euro} from {person} to {msg.sender}\n'

            output += "New Balances:\n"
            output += self.create_summary(msg.sender) + "\n"
            output += self.create_summary(car)

            self.may_record_change(
                msg.sender, Change(msg.args, modifications, msg.timestamp))

            return {'msg': output}

        return {'err': f'unknown car subcommand "{msg.args[1]}".'}

    def parse_tank_bill(self, _drives: list[str], fuel_charge: int,
                        service_charge: int):
        """Parse and distribute the tank bill across all passangers"""
        passengers: dict[str, dict[str, int]] = {}
        distance = 0.
        drives = [d.split(' ') for d in _drives]

        for drive in drives:
            try:
                drive_distance = int(drive[0])
            except (IndexError, ValueError):
                return None, "Lines have to start with the driven distance!"

            # calculate overall distance
            distance += drive_distance

            # collect distances per passenger
            drive_passengers = self.expand_aliases(drive[1:])
            for passenger in drive_passengers:
                passengers.setdefault(passenger, {
                    "distance": 0,
                    "cost": 0,
                    "service_charge": 0
                })["distance"] += drive_distance

        # calculate cost per kilometer
        if distance <= 0:
            return None, "Driven distance must be greater than 0!"

        c_km = fuel_charge / distance

        for drive in drives:
            drive_distance = int(drive[0])
            drive_passengers = self.expand_aliases(drive[1:])
            # calculate cost per drive split among passengers
            c_d = int(c_km * drive_distance / (len(drive_passengers)))
            sc_d = int(service_charge * drive_distance /
                       (len(drive_passengers)))
            for passenger in drive_passengers:
                passengers[passenger]["cost"] += c_d
                passengers[passenger]["service_charge"] += sc_d

        return passengers, None

    def tanken(self, msg: MessageContext) -> dict[str, str]:
        """Split a tank across all passengers"""
        if len(msg.args) < 2:
            return {
                'err':
                f'not in form "{msg.args[0]} amount [person] [car] [info]"'
            }
        try:
            amount = to_cent(msg.args[1])
        except (ValueError, TypeError):
            return {'err': 'amount must be a number'}

        # find recipient
        if len(msg.args) > 2 and msg.args[2] in self.name2num:
            recipient = msg.args[2]
        elif msg.sender:
            recipient = msg.sender
        else:
            return {'err': 'recipient unknown'}

        # find car
        car = None
        if len(msg.args) > 2 and msg.args[2] in self.available_cars:
            car = msg.args[2]
        elif len(msg.args) > 3 and msg.args[3] in self.available_cars:
            car = msg.args[3]

        service_charge = self.available_cars.get(car, 0)

        parts, err = self.parse_tank_bill(msg.body[1:], amount, service_charge)
        if err:
            return {'err': err}

        assert parts

        output = ""
        modifications: list[Modification] = []
        for pname, values in parts.items():
            output += f'{pname}: {values["distance"]}km = fuel: {to_euro(values["cost"])}, service charge: {to_euro(values["service_charge"])}\n'
            # record service charges
            if pname not in self.name2num:
                output += f'{pname} not known.'
            if car:
                person_to_charge = pname
                if pname not in self.name2num:
                    person_to_charge = recipient
                    output += f" {recipient} held accountable for service charge."

                modification = self.record(car, person_to_charge,
                                           values["service_charge"])
                if modification:
                    modifications.append(modification)

            # recipient paid the fuel -> don't charge them
            if pname == recipient:
                continue

            if pname in self.name2num:
                modification = self.record(recipient, pname, values["cost"])
                if modification:
                    modifications.append(modification)
            else:
                output += " Please collect fuel cost manually\n"

        if msg.sender:
            self.may_record_change(
                msg.sender, Change(msg.args, modifications, msg.timestamp))

        output += "New Balance:\n"
        output += self.create_summary(recipient)
        if car:
            output += "\nCar "
            output += self.create_summary(car)
        return {'msg': output}

    def fuck(self, msg: MessageContext) -> dict[str, str]:
        """Rewind past changes"""
        if not msg.sender:
            return {'err': 'you must register first'}

        name = msg.sender

        nchanges = len(self.changes[name])
        if nchanges == 0:
            return {'msg': 'Nothing to rewind'}

        change_to_rewind = -1
        if len(msg.args) >= 2:
            try:
                change_to_rewind = int(msg.args[1]) - 1
            except ValueError:
                return {'err': 'change to rewind must be a number'}

            if change_to_rewind > nchanges:
                return {
                    'err': 'change to rewind is bigger than there are changes'
                }

        # pop last item
        change = self.changes[name].pop(change_to_rewind)

        output = name + ": sorry I fucked up!\nRewinding:\n"
        output += ' '.join(change.cmd) + "\n"
        for mod in change.modifications:
            output += f'{self.reverse(mod).out_string()}\n'

        for cmd_args in change.rewind_cmds:
            ret = self.cmds[cmd_args[0]](MessageContext(
                msg.sender_number, msg.sender, cmd_args, [''.join(cmd_args)],
                msg.timestamp))
            if 'err' in ret:
                output += "ERROR: " + ret['err']
            else:
                output += ret['msg']

        return {'msg': output}

    def list_changes(self, msg: MessageContext) -> dict[str, str]:
        """List changes made by the sender"""
        if not msg.sender:
            return {'err': 'you must register first'}

        changes_to_list = 5
        if len(msg.args) >= 2:
            try:
                changes_to_list = int(msg.args[1])
            except ValueError:
                return {
                    'err': 'the amount of changes to list must be a number'
                }

        nchanges = len(self.changes[msg.sender])
        if nchanges == 0:
            return {'msg': 'Nothing to list'}

        first_to_list = max(nchanges - changes_to_list, 0)

        if len(msg.args) == 3:
            try:
                first_to_list = int(msg.args[2]) - 1
            except ValueError:
                return {'err': 'the first change to list must be a number'}

            if first_to_list > nchanges:
                return {
                    'err':
                    'the first change to list is bigger than there are changes'
                }

        out = ""
        i = 0
        for i, change in enumerate(self.changes[msg.sender]):
            if i < first_to_list:
                continue

            if i >= first_to_list + changes_to_list:
                # i is used to track how many changes we listed
                # This change will not be listed so decrement i before extiting the loop.
                i -= 1
                break

            out += f'Change {i + 1}:\n'
            out += f'\t{" ".join(change.cmd)}\n'
            for mod in change.modifications:
                out += f'\t{mod.in_string()}\n'

        # prepend message header because we want to know how much changes we actually listed
        out = f'Changes from {msg.sender} {first_to_list + 1}-{i + 1}\n' + out

        return {'msg': out}

    @classmethod
    def export_state(cls, msg: MessageContext) -> dict[str, str]:
        """Send the state file as attachment"""
        if not msg.sender:
            return {'err': 'you must register first'}

        out = f'State from {datetime.now().date().isoformat()}'
        return {'msg': out, 'attachment': STATE_FILE}

    def schedule(self, msg: MessageContext) -> dict[str, str]:
        """Schedule a command for periodic execution"""
        if not msg.sender:
            return {'err': 'you must register first'}

        if len(msg.args) < 3:
            return {'err': f'not in form "{msg.args[0]} name cmd"'}

        name = msg.args[1]
        cmd = msg.args[2:]

        if not cmd[0] in self.cmds:
            return {
                'err':
                f'the command "{name}" can not be registered because "{cmd[0]}" is unknown'
            }
        initial_commad_msg = MessageContext(msg.sender_number, msg.sender, cmd,
                                            [], msg.timestamp)

        if name in self.scheduled_cmds:
            return {
                'err': f'there is already a scheduled command named "{name}"'
            }

        # Test the command
        saved_dry_run = self.enable_dry_run()
        ret = self.cmds[cmd[0]](initial_commad_msg)
        self.restore_dry_run(saved_dry_run)

        if 'err' in ret:
            return {
                'err':
                f'the command "{name}" failed with "{ret["err"]}" and will not be recorded'
            }

        scheduled_cmd = {
            "schedule": msg.args[0][1:],
            "last_time": None,
            "sender": msg.sender,
            "cmd": cmd
        }

        self.scheduled_cmds[name] = scheduled_cmd
        output = f'Recorded the {msg.args[0][1:]} command "{" ".join(cmd)}" as "{name}"\n'
        output += f'Running {scheduled_cmd["schedule"]} command {name} for {msg.sender} initially\n'

        previous_change_count = len(self.changes[msg.sender])
        ret = self.cmds[cmd[0]](initial_commad_msg)
        if 'err' in ret:
            output += 'ERROR: ' + ret['err']
        else:
            output += ret['msg']

        # The executed command did not create a new Change
        # -> create a dummy change to cancel the scheduled command
        if previous_change_count == len(self.changes[msg.sender]):
            self.changes[msg.sender].append(Change(cmd, [], msg.timestamp))
        self.changes[msg.sender][-1].rewind_cmds.append(["cancel", name])

        now = datetime.now().date()
        scheduled_cmd["last_time"] = now.isoformat()

        return {'msg': output}

    def cancel(self, msg: MessageContext) -> dict[str, str]:
        """Cancel a previously scheduled command"""
        cmd_name = msg.args[1]
        if not cmd_name in self.scheduled_cmds:
            return {'err': f'"{cmd_name}" is not a scheduled command'}
        cmd = self.scheduled_cmds[cmd_name]

        if not cmd["sender"] == msg.sender:
            return {'err': 'only the original creator can cancel this command'}

        del self.scheduled_cmds[cmd_name]
        return {'msg': f'Cancelled the {cmd["schedule"]} cmd "{cmd_name}"'}

    @classmethod
    def thanks(cls, msg: MessageContext) -> dict[str, str]:
        """Thank geldschieberbot for its loyal service"""
        sender_name = msg.sender or msg.sender_number
        out = f'You are welcome. It is a pleasure to work with you, {sender_name}.'
        nick = None if len(msg.args) == 1 else msg.args[1]
        if nick:
            out = f"{out}\nBut don't call me {nick}."

        return {'msg': out}

    def alias(self, msg: MessageContext) -> dict[str, str]:
        """List or create aliases"""

        if len(msg.args) == 1:
            out = ''
            for alias, users in self.aliases.items():
                out += f'\n\t{alias}: {" ".join(users)}'
            return {'msg': f'Aliases:\n\tall: {" ".join(self.name2num)}{out}'}

        if len(msg.args) == 2:
            return {'err': 'Not a valid alias command'}

        if msg.args[1] == 'remove':
            alias = msg.args[2]
            if alias not in self.aliases:
                return {'err': f'Alias "{alias}" not registered'}

            del self.aliases[alias]
            return {'msg': f'Alias "{alias}" removed'}

        # create a new alias
        alias = msg.args[1]
        if alias in self.aliases or alias == 'all':
            return {'err': f'Alias "{alias}" is already registered'}

        if alias in self.name2num:
            return {'err': f'A user "{alias}" is already registered'}

        try:
            to_cent(alias)
            return {'err': 'Pure numerical aliases are not allowed'}
        except (ValueError, TypeError):
            pass

        users = msg.args[2:]
        for user in users:
            if user not in self.name2num:
                return {'err': f'User {user} is not registered'}

        self.aliases[alias] = users
        return {'msg': f'New alias "{alias}" registered'}

    def __init__(self, dry_run=False, quote_cmd=True):
        self.dry_run = dry_run  # Run without changing the stored state
        self.quote_cmd = quote_cmd  # Quote the message causing the reply
        self.load_state()
        self.quiet = False  # Run without sending messages
        self.record_changes = True  # Should changes be recorded

        # Command dispatch table
        self.cmds = {
            'reg': self.register,
            'register': self.register,
            'alias': self.alias,
            'sum': self.summary,
            'summary': self.summary,
            'balance': self.summary,
            'full-sum': self.full_summary,
            'full-summary': self.full_summary,
            'ls': self.list_users,
            'list': self.list_users,
            'split': self.split,
            'teil': self.split,
            'schieb': self.transaction,
            'gib': self.transaction,
            'zieh': self.transaction,
            'nimm': self.transaction,
            'help': self.usage,
            'usage': self.usage,
            'transfer': self.transfer,
            'cars': self.cars,
            'tanken': self.tanken,
            'fuck': self.fuck,
            'rewind': self.fuck,
            'undo': self.fuck,
            'list-changes': self.list_changes,
            'export-state': self.export_state,
            'weekly': self.schedule,
            'monthly': self.schedule,
            'yearly': self.schedule,
            'cancel': self.cancel,
            'thanks': self.thanks,
        }

    def __del__(self):
        self.save_state()

    def enable_dry_run(self) -> bool:
        """Enable dry run"""
        old_value = self.dry_run
        self.dry_run = True
        return old_value

    def restore_dry_run(self, old_value: bool):
        """Restore dry run setting to old value"""
        self.dry_run = old_value

    def disable_record_changes(self) -> bool:
        """Disable change recording and return previous value"""
        old_value = self.record_changes
        self.record_changes = False
        return old_value

    def restore_record_changes(self, old_value: bool):
        """Restore record change setting to old value"""
        self.record_changes = old_value

    def may_record_change(self, user: str, change: Change):
        """Record a change for a user if change recording is enabled"""
        if self.record_changes and not self.dry_run:
            self.changes[user].append(change)

    def handle(self, envelope: dict):
        """Parse and respond to a message"""
        sender_number = envelope["source"]
        if not "dataMessage" in envelope or not envelope[
                "dataMessage"] or not envelope["dataMessage"]["message"]:
            return

        message = envelope["dataMessage"]
        if message["groupInfo"] and message["groupInfo"]["groupId"] != GROUP_ID:
            return

        body = [l.strip() for l in message["message"].lower().splitlines()]

        if len(body) == 0 or not body[0].startswith('!'):
            return

        quote = Quote(timestamp=message["timestamp"], author=sender_number)
        args = body[0].split(' ')
        msg_context = MessageContext(sender_number,
                                     self.num2name.get(sender_number, None),
                                     args, body, message['timestamp'])
        cmd = args[0][1:]
        if cmd in self.cmds:
            ret = self.cmds[cmd](msg_context)
            if 'err' in ret:
                self.send(f'ERROR: {ret["err"]}')
            else:
                if not 'msg' in ret:
                    print(ret)
                self.send(ret['msg'],
                          attachment=ret.get('attachment', None),
                          quote=quote if self.quote_cmd else None)
        else:
            self.send(
                'ERROR: unknown cmd. Enter !help for a list of commands.')

        self.save_state()

    def run_scheduled_cmds(self):
        """Progress the scheduled commands"""
        self.record_changes = False

        now = datetime.now().date()
        week_delta = timedelta(days=7)
        for name, scheduled_cmd in self.scheduled_cmds.items():

            last_time, interval = scheduled_cmd["last_time"], scheduled_cmd[
                "schedule"]
            if hasattr(date, "fromisoformat"):
                last_time = date.fromisoformat(last_time)
            else:
                last_time = date(*map(int, last_time.split("-")))

            d = last_time
            while True:
                if interval == "yearly":
                    d = date(d.year + 1, d.month, d.day)
                elif interval == "monthly":
                    if d.day > 28:
                        d = date(d.year, d.month, 28)
                    if d.month == 12:
                        d = date(d.year + 1, 1, d.day)
                    else:
                        d = date(d.year, d.month + 1, d.day)
                else:
                    d = d + week_delta

                if d <= now:
                    cmd_args, runas = scheduled_cmd['cmd'], scheduled_cmd[
                        'sender']
                    out = f'Running {interval} command {name} for {runas} triggered on {d.isoformat()}'
                    # TODO: use d as timestamp
                    cmd_ctx = MessageContext(self.name2num[runas], runas,
                                             cmd_args, [], None)
                    ret = self.cmds[cmd_args[0]](cmd_ctx)

                    if 'err' in ret:
                        self.send(f'{out}\nERROR: {ret["err"]}')
                    else:
                        self.send(f'{out}\n{ret["msg"]}',
                                  attachment=ret.get('attachment', None))

                    scheduled_cmd["last_time"] = d.isoformat()
                else:
                    break


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-d',
                        '--dry-run',
                        help='do not persist changes',
                        action='store_true')
    parser.add_argument('-nq',
                        '--no-quote',
                        help='not quote the message causing the reply',
                        action='store_true')
    args = parser.parse_args()

    if args.dry_run:
        print("Dry Run no changes will apply!")

    bot = Geldschieberbot(dry_run=args.dry_run, quote_cmd=not args.no_quote)

    # Read cmds from stdin
    for line in sys.stdin.read().splitlines():
        try:
            message = json.loads(line)["envelope"]
        except json.JSONDecodeError:
            print(datetime.now(), line, "not valid json")
            continue

        bot.handle(message)

    bot.run_scheduled_cmds()


if __name__ == "__main__":
    main()