nova-web/web/finances.py

53 lines
1.7 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()
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():
data = get_finances()
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
)