nova-web/web/finances.py
2023-09-23 17:08:19 +02:00

57 lines
1.9 KiB
Python
Executable file

import os
import io
import time
import json
import flask
import requests
from dotenv import load_dotenv
load_dotenv()
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():
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)
finances = {
'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():
virtual_file = io.StringIO()
json.dump(get_finances(), virtual_file, indent=4)
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
)