budget/addfee.py

124 líneas
3.2 KiB
Python

from datetime import datetime, timezone, timedelta
import time
import threading
import os
import sys
import os.path
import psycopg2
import pytz
import dateutil
from dateutil.parser import parse
from decimal import *
getcontext().prec = 2
###############################################################################
# get fees rows
###############################################################################
def print_fees():
try:
conn = psycopg2.connect(database = budget_db, user = budget_db_user, password = "", host = "/var/run/postgresql", port = "5432")
cur = conn.cursor()
cur.execute("SELECT fee_description, payment_type, fee FROM fees")
rows = cur.fetchall()
for row in rows:
print('fee description: ' + str(row[0]), ', payment type: ' + str(row[1]), 'fee: ' + str(row[2]))
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
###################################################################################
# add fees to database
###################################################################################
def insert_fees(fee_description, payment_type, fee):
sql = "INSERT INTO fees(fee_description, payment_type, fee) VALUES(%s,%s,%s)"
try:
conn = psycopg2.connect(database = budget_db, user = budget_db_user, password = "", host = "/var/run/postgresql", port = "5432")
cur = conn.cursor()
cur.execute(sql, (fee_description, payment_type, fee))
print("\n")
print("Updating fees...")
conn.commit()
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
###############################################################################
# INITIALISATION
###############################################################################
# Returns the parameter from the specified file
def get_parameter( parameter, file_path ):
# Check if db_config.txt file exists
if not os.path.isfile(file_path):
if file_path == "config/db_config.txt":
print("File %s not found, exiting. Run db-setup.py."%file_path)
sys.exit(0)
# Find parameter in file
with open( file_path ) as f:
for line in f:
if line.startswith( parameter ):
return line.replace(parameter + ":", "").strip()
# Cannot find parameter, exit
print(file_path + " Missing parameter %s "%parameter)
print("Run setup.py")
sys.exit(0)
# Load configuration from config file
config_filepath = "config/db_config.txt"
budget_db = get_parameter("budget_db", config_filepath) # E.g., budget
budget_db_user = get_parameter("budget_db_user", config_filepath) # E.g., mastodon
###############################################################################
while True:
fee_description = input("Fee description? (q to quit) ")
if fee_description == 'q':
sys.exit("Bye")
fee_type = input("Fee type? (in ex. annual) ")
fee = input("Fee? ")
if fee == '':
fee = '0.00'
fee = round(float(fee),2)
insert_fees(fee_description, fee_type, fee)
print_fees()