4
4
import pendulum
5
5
6
6
from tqdm import tqdm
7
+ from ledgertools .checks import transaction_checks , CheckFailed
8
+
7
9
8
10
# regex copied from https://github.com/Tagirijus/ledger-parse
9
11
PAT_TRANSACTION_DATA = re .compile (r'(?P<year>\d{4})[/|-](?P<month>\d{2})[/|-](?P<day>\d{2})(?:=(?P<year_aux>\d{4})[/|-](?P<month_aux>\d{2})[/|-](?P<day_aux>\d{2}))? (?P<state>[\*|!])?[ ]?(\((?P<code>[^\)].+)\) )?(?P<payee>.+)' )
@@ -15,10 +17,10 @@ class Ledger():
15
17
"""
16
18
def __init__ (self , ledger_filename = None , raw_transactions = None ):
17
19
self ._transactions = []
18
- if raw_transactions is not None :
19
- self ._transactions = self ._import_raw_transactions (raw_transactions )
20
20
if ledger_filename is not None :
21
21
self ._transactions = self .import_ledger_file (ledger_filename )
22
+ if raw_transactions is not None :
23
+ self ._transactions = self ._import_raw_transactions (raw_transactions )
22
24
23
25
@property
24
26
def json (self ):
@@ -28,6 +30,17 @@ def json(self):
28
30
def transactions (self ):
29
31
return self ._transactions
30
32
33
+ def run_checks (self , strict = True ):
34
+ n_checks_failed = 0
35
+ for transaction in self ._transactions :
36
+ for check in transaction_checks ():
37
+ success , info = transaction .run_checks (check )
38
+ if not success :
39
+ n_checks_failed += 1
40
+ print (f'{ check .__name__ } failed for transaction\n { transaction } { info } ' )
41
+ if n_checks_failed > 0 and strict :
42
+ raise CheckFailed (f'{ n_checks_failed } checks failed' )
43
+
31
44
def _parse_tags (self , string ):
32
45
tags = {}
33
46
# split string in parts
@@ -187,7 +200,7 @@ def json(self):
187
200
status = self .status ,
188
201
code = self .code ,
189
202
description = self .description ,
190
- transactions = [p .json for p in self .postings ],
203
+ postings = [p .json for p in self .postings ],
191
204
comment = self .comment )
192
205
193
206
@property
@@ -234,6 +247,9 @@ def postings(self):
234
247
def add_posting (self , posting ):
235
248
self ._postings .append (posting )
236
249
250
+ def run_checks (self , check ):
251
+ return check (self )
252
+
237
253
238
254
class Posting ():
239
255
"""Represents a single posting
@@ -275,5 +291,8 @@ def date(self):
275
291
return self ._primary_date .isoformat ()
276
292
277
293
278
- def read_file (in_file ):
279
- return Ledger (ledger_filename = in_file ).json
294
+ def read_file (in_file , run_checks = False ):
295
+ ledger = Ledger (ledger_filename = in_file )
296
+ if run_checks :
297
+ ledger .run_checks (strict = False )
298
+ return ledger .json
0 commit comments