uncloud/uncloud/uncloud_pay/management/commands/handle-overdue-bills.py

43 lines
1.5 KiB
Python
Raw Normal View History

2020-02-28 09:18:24 +00:00
from django.core.management.base import BaseCommand
from uncloud_auth.models import User
from uncloud_pay.models import Order, Bill, get_balance_for
2020-02-28 09:18:24 +00:00
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.")