Pull the account name from the db so it can process multiple accounts. Change print statements to proper logging statements

This commit is contained in:
2022-01-13 14:14:25 +10:00
parent f694a67b2d
commit 2aec216e66
2 changed files with 29 additions and 13 deletions

9
.vscode/launch.json vendored
View File

@@ -10,7 +10,14 @@
"request": "launch", "request": "launch",
"program": "${file}", "program": "${file}",
"console": "integratedTerminal", "console": "integratedTerminal",
"justMyCode": false "justMyCode": false,
"env": {
"DB_HOST": "192.168.0.2",
"DB_PORT": "27017",
"DB_NAME": "hsbc_converter",
"DB_COL": "imported_transactions",
"WATCH_DIR": "/mnt/d/tmp/hsbc/"
}
} }
] ]
} }

View File

@@ -9,7 +9,7 @@ from pathlib import Path
from decimal import Decimal from decimal import Decimal
from bson.decimal128 import Decimal128 from bson.decimal128 import Decimal128
import logging
import os import os
import pymongo import pymongo
import time import time
@@ -30,12 +30,17 @@ CONVERTED_DIR = 'Converted'
MONGO_URL = os.environ['DB_HOST'] MONGO_URL = os.environ['DB_HOST']
MONGO_PORT = os.environ['DB_PORT'] MONGO_PORT = os.environ['DB_PORT']
MONGO_DB = os.environ['DB_NAME'] MONGO_DB = os.environ['DB_NAME']
MONGO_COL = os.environ['DB_COL'] MONGO_COL = 'hsbc_converter'
ACCOUNT_COL = 'accounts'
MONGO_URL = "mongodb://{}:{}".format(MONGO_URL, MONGO_PORT) MONGO_URL = "mongodb://{}:{}".format(MONGO_URL, MONGO_PORT)
myclient = pymongo.MongoClient(MONGO_URL) myclient = pymongo.MongoClient(MONGO_URL)
mydb = myclient[MONGO_DB] mydb = myclient[MONGO_DB]
mongo_col = mydb[MONGO_COL] mongo_col = mydb[MONGO_COL]
account_col = mydb[ACCOUNT_COL]
logging.basicConfig(format='%(asctime)s - %(message)s', level=logging.INFO)
logging.basicConfig(format='ERROR: %(asctime)s - %(message)s', level=logging.ERROR)
class Handler(watchdog.events.PatternMatchingEventHandler): class Handler(watchdog.events.PatternMatchingEventHandler):
def __init__(self): def __init__(self):
@@ -45,10 +50,10 @@ class Handler(watchdog.events.PatternMatchingEventHandler):
@staticmethod @staticmethod
def write_csv(statement, out_file): def write_csv(statement, out_file):
print("Writing: " + out_file) logging.info("Writing: " + out_file)
if len(statement) == 0: if len(statement) == 0:
print("No transactions to write.") logging.info("No transactions to write.")
return return
fields = ['date', 'memo', 'category', 'amount', 'name'] fields = ['date', 'memo', 'category', 'amount', 'name']
@@ -85,6 +90,10 @@ class Handler(watchdog.events.PatternMatchingEventHandler):
@staticmethod @staticmethod
def get_statement_from_qfx(qfx): def get_statement_from_qfx(qfx):
account = account_col.find_one({"number": qfx.account.number})
if account is None:
logging.error("No account for account number {} exists. Create one and re-process the file".format(qfx.account.number))
statement = [] statement = []
for transaction in qfx.account.statement.transactions: for transaction in qfx.account.statement.transactions:
@@ -96,7 +105,7 @@ class Handler(watchdog.events.PatternMatchingEventHandler):
'memo' : transaction.memo, 'memo' : transaction.memo,
'category': 'Uncategorised', 'category': 'Uncategorised',
'amount': transaction.amount, 'amount': transaction.amount,
'name': 'HSBC Everyday Global' 'name': account['name']
} }
#mongo needs the decimal values in Decimal128, so create a version for it #mongo needs the decimal values in Decimal128, so create a version for it
@@ -107,7 +116,7 @@ class Handler(watchdog.events.PatternMatchingEventHandler):
statement.append(line) statement.append(line)
result = mongo_col.insert_one(line_d128) result = mongo_col.insert_one(line_d128)
print("New db entry stored: {}".format(result.inserted_id)) logging.info("New db entry stored: {}".format(result.inserted_id))
return statement return statement
@@ -121,7 +130,7 @@ class Handler(watchdog.events.PatternMatchingEventHandler):
return path return path
def on_created(self, event): def on_created(self, event):
print('File found: {}'.format(event.src_path)) logging.info('File found: {}'.format(event.src_path))
fileExists = False fileExists = False
timeout = 0 timeout = 0
@@ -131,15 +140,15 @@ class Handler(watchdog.events.PatternMatchingEventHandler):
timeout += 1 timeout += 1
if timeout > 10: if timeout > 10:
print('Timeout waiting for file {} to exist. Aborting processing.'.format(event.src_path)) logging.error('Timeout waiting for file {} to exist. Aborting processing.'.format(event.src_path))
return return
historicalSize = -1 historicalSize = -1
while (historicalSize != os.path.getsize(event.src_path)): while (historicalSize != os.path.getsize(event.src_path)):
historicalSize = os.path.getsize(event.src_path) historicalSize = os.path.getsize(event.src_path)
print('waiting for copy to finish....') logging.info('waiting for copy to finish....')
time.sleep(1) time.sleep(1)
print("file copy has now finished") logging.info("file copy has now finished")
with open(event.src_path, 'r') as file: with open(event.src_path, 'r') as file:
@@ -167,7 +176,7 @@ class Handler(watchdog.events.PatternMatchingEventHandler):
if not destination.exists(): if not destination.exists():
path.replace(destination) path.replace(destination)
print("Processing successfully finished for {}".format(event.src_path)) logging.info("Processing successfully finished for {}".format(event.src_path))
if __name__ == "__main__": if __name__ == "__main__":
event_handler = Handler() event_handler = Handler()
@@ -175,7 +184,7 @@ if __name__ == "__main__":
observer.schedule(event_handler, path=WATCH_DIR, recursive=False) observer.schedule(event_handler, path=WATCH_DIR, recursive=False)
observer.start() observer.start()
print('Converter running, waiting for files in {}'.format(WATCH_DIR)) logging.info('Converter running, waiting for files in {}'.format(WATCH_DIR))
try: try:
while True: while True:
time.sleep(1) time.sleep(1)