-
-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathimporter.py
More file actions
72 lines (63 loc) · 2.47 KB
/
importer.py
File metadata and controls
72 lines (63 loc) · 2.47 KB
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
import csv
import logging
import re
from datetime import timedelta
from decimal import Decimal
import beangulp
import dateutil.parser
from beancount.core import data
class Importer(beangulp.Importer):
"""An importer for PostFinance CSV."""
def __init__(self, filepattern: str, account: data.Account, currency: str = "CHF"):
self._filepattern = filepattern
self._account = account
self.currency = currency
def identify(self, filepath: str) -> bool:
return re.search(self._filepattern, filepath) is not None
def account(self, filepath: str) -> data.Account:
return self._account
def extract(self, filepath: str, existing: data.Entries) -> data.Entries:
csvfile = open(file=filepath, encoding="windows_1252")
reader = csv.reader(csvfile, delimiter=";")
meta = data.new_metadata(filepath, 0)
entries = []
for row in reader:
try:
book_date_str, text, credit, debit, val_date, balance_str = tuple(row)
book_date = dateutil.parser.parse(book_date_str).date()
if credit:
amount = data.Amount(Decimal(credit), self.currency)
elif debit:
amount = data.Amount(Decimal(debit), self.currency)
else:
amount = None
if balance_str:
balance = data.Amount(Decimal(balance_str), self.currency)
else:
balance = None
except Exception as e:
logging.debug(e)
else:
logging.debug((book_date, text, amount, val_date, balance))
posting = data.Posting(self._account, amount, None, None, None, None)
entry = data.Transaction(
meta,
book_date,
"*",
"",
text,
data.EMPTY_SET,
data.EMPTY_SET,
[posting],
)
entries.append(entry)
# only add balance on SOM
book_date = book_date + timedelta(days=1)
if balance and book_date.day == 1:
entry = data.Balance(
meta, book_date, self._account, balance, None, None
)
entries.append(entry)
csvfile.close()
entries = data.sorted(entries)
return entries