bitvend: make hall of addicts windowed

master
bitvend 2023-10-02 20:18:05 +02:00
parent 404a4a5903
commit ed247af604
3 changed files with 25 additions and 9 deletions

View File

@ -2,6 +2,7 @@ from prometheus_client import start_http_server, Counter
from bitvend.models import User, Transaction
from sqlalchemy import func, text
import cachetools
import datetime
coin_counter = Counter("coins_inserted", "Number of coins inserted into machine")
purchase_counter = Counter("purchases", "Number of purchases")
@ -31,23 +32,26 @@ def hall_of_shame():
@cachetools.cached(cachetools.TTLCache(32, 600))
def hall_of_addicts():
def hall_of_addicts(window=None):
balance = func.sum(Transaction.amount).label("balance")
candidates = (
Transaction.query.with_entities(Transaction.uid)
Transaction.query.with_entities(
Transaction.uid,
func.sum(Transaction.amount * -1),
func.count(),
)
.group_by(Transaction.uid)
.filter(Transaction.amount < 0)
.filter(Transaction.type == "purchase")
.having(balance < 0)
.order_by(balance.asc())
.limit(10)
.all()
)
if window is not None:
start_time = datetime.date.today() - datetime.timedelta(hours=window)
candidates = candidates.filter(Transaction.created >= start_time)
return (
User.query.with_entities(User, User.purchase_amount, User.purchase_count)
.filter(User.uid.in_([c for (c,) in candidates]))
.order_by(User.purchase_amount.desc())
candidates
.limit(5)
.all()
)

View File

@ -60,7 +60,18 @@
{% endfor %}
</table>
<h3 class="page-header">Hall of Addicts</h3>
<h3 class="page-header">Hall of Addicts (last 30 days)</h3>
<table class="table table-hover table-striped">
<thead><tr>
<th>Name</th><th class="text-right">Amount</th><th>Purchases</th>
</tr></thead>
{% for user, purchase_amount, purchase_count in hallofaddicts_30d %}
<tr><td>{{ user }}</td><td class="text-right">{{ format_currency(purchase_amount) }}</td><td>{{ purchase_count }}</td></tr>
{% else %}
<tr><td colspan=3 class="placeholder">Huh?</td></tr>
{% endfor %}
</table>
<h3 class="page-header">Hall of Addicts (all time superstars)</h3>
<table class="table table-hover table-striped">
<thead><tr>
<th>Name</th><th class="text-right">Amount</th><th>Purchases</th>

View File

@ -32,6 +32,7 @@ def index():
transfer_form=TransferForm(),
hallofshame=hall_of_shame(),
hallofaddicts=hall_of_addicts(),
hallofaddicts_30d=hall_of_addicts(window=24*30),
bottles_purchased=bottles_purchased(),
)