45 lines
1.3 KiB
Python
45 lines
1.3 KiB
Python
#! /usr/bin/env python3
|
|
import csv
|
|
from datetime import datetime
|
|
from sqlalchemy import create_engine, desc
|
|
from sqlalchemy.ext.declarative import declarative_base
|
|
from sqlalchemy.orm import sessionmaker
|
|
from models import Transaction
|
|
import sys
|
|
|
|
|
|
def convert_amount(s):
|
|
s = s.replace(",", "")
|
|
return int(float(s) * 100)
|
|
|
|
|
|
engine = create_engine("sqlite:///app.db")
|
|
Base = declarative_base()
|
|
|
|
Session = sessionmaker(bind=engine)
|
|
session = Session()
|
|
|
|
latest = session.query(Transaction).order_by(desc(Transaction.date)).first()
|
|
|
|
with open("transactions.csv") as fh:
|
|
fh.readline() # Get rid of first line
|
|
csv_reader = csv.reader(fh, delimiter=";")
|
|
count = 0
|
|
for line in csv_reader:
|
|
date = datetime.strptime(line[0], "%Y-%m-%d")
|
|
amount = line[2]
|
|
iban = line[4]
|
|
name = line[5]
|
|
description = line[6]
|
|
|
|
if latest and date < latest.date:
|
|
print("Found transaction older than then oldest transction in the DB. Aborting")
|
|
sys.exit(1)
|
|
|
|
t = Transaction(date=date, name=name, iban=iban, amount=convert_amount(amount), description=description)
|
|
session.add(t)
|
|
session.commit()
|
|
count += 1
|
|
print(".", end="", flush=True)
|
|
print()
|
|
print(f"Imported {count} transactions")
|