Add handle-overdue-bills

This commit is contained in:
fnux 2020-02-28 10:18:24 +01:00
parent e12575e1de
commit c0512e54b0

View file

@ -0,0 +1,43 @@
from django.core.management.base import BaseCommand
from uncloud_auth.models import User
from uncloud_pay.models import Order, Bill
from uncloud_pay.helpers import get_balance_for, get_payment_method_for
from datetime import timedelta
from django.utils import timezone
class Command(BaseCommand):
help = 'Generate bills and charge customers if necessary.'
def add_arguments(self, parser):
pass
def handle(self, *args, **options):
users = User.objects.all()
print("Processing {} users.".format(users.count()))
for user in users:
balance = get_balance_for(user)
if balance < 0:
print("User {} has negative balance ({}), checking for overdue bills."
.format(user.username, balance))
# Get bills DESCENDING by creation date (= latest at top).
bills = Bill.objects.filter(
owner=user,
due_date__lt=timezone.now()
).order_by('-creation_date')
overdue_balance = abs(balance)
overdue_bills = []
for bill in bills:
if overdue_balance < 0:
break # XXX: I'm (fnux) not fond of breaks!
overdue_balance -= bill.amount
overdue_bills.append(bill)
for bill in overdue_bills:
print("/!\ Overdue bill for {}, {} with amount {}"
.format(user.username, bill.uuid, bill.amount))
# TODO: take action?
print("=> Done.")