nova-web/web/finances.py

64 lines
2.2 KiB
Python
Raw Normal View History

2023-09-22 01:00:00 +02:00
import os
import io
import time
import json
import flask
import requests
from dotenv import load_dotenv
load_dotenv()
2023-09-23 18:06:27 +02:00
# cache get_finances() for 5 minutes
2023-09-22 01:00:00 +02:00
def get_finances():
return requests.get(
url=f'{os.environ["CORE_API_URL"]}/finances',
headers={
'Authorization': f'{os.environ["CORE_API_KEY"]}'
},
timeout=5
).json()
def register(app):
@app.route('/finances')
def finances_view():
2023-09-23 17:08:19 +02:00
try:
data = get_finances()
except Exception:
return flask.Response('Error fetching finances from database. This might be cause the data is still being processed. Sorry.', status=500)
2023-09-22 01:00:00 +02:00
finances = {
2023-09-23 18:06:27 +02:00
'last_update': data['timestamp'],
2023-09-22 01:00:00 +02:00
'donations_total': round(sum([i['amount_usd'] for i in data['donations']])),
'donations_num': len(data['donations']),
'donations_avg': round(sum([i['amount_usd'] for i in data['donations']]) / len(data['donations']), 2),
'donations_max': round(max([i['amount_usd'] for i in data['donations']])),
'most_used_donation_currency': max(data['donations'], key=lambda x: x['amount_usd'])['currency'],
'expenses_total': round(sum([i['amount_usd'] for i in data['expenses']])),
'expenses_wages': round(sum([i['amount_usd'] for i in data['expenses'] if i['type'] == 'wage'])),
'most_used_expense_currency': max(data['expenses'], key=lambda x: x['amount_usd'])['currency'],
}
return flask.render_template('finances.html', finances=finances)
@app.route('/finances/json')
def finances_download():
2023-09-23 18:06:27 +02:00
try:
data = get_finances()
except Exception:
return flask.Response('Error fetching finances from database. This might be cause the data is still being processed. Sorry.', status=500)
2023-09-22 01:00:00 +02:00
virtual_file = io.StringIO()
2023-09-23 18:06:27 +02:00
json.dump(data, virtual_file, indent=4)
2023-09-22 01:00:00 +02:00
name = f'finances-{time.strftime("%Y-%m-%d")}.json'
virtual_file.seek(0)
return flask.send_file(
io.BytesIO(virtual_file.read().encode('utf-8')),
mimetype='application/json',
as_attachment=True,
download_name=name
)