# myapp/tasks.py
from .models import Subscription, TenantBilling
from django.utils import timezone
from datetime import timedelta

def generate_billing():

    try:
        # print("generate billing")
        now = timezone.now()
        subscriptions = Subscription.objects.filter(end_date__gte=now)

        for subscription in subscriptions:
            # 检查是否已经在这个周期生成了账单
            if subscription.last_billed and subscription.last_billed > now - timedelta(days=30):
                continue  # 这个订阅的账单已经生成，跳过

            # 生成新的账单
            billing = TenantBilling(tenant=subscription.tenant, subscription=subscription)
            billing.calculate_total_price()

            # 更新上次账单生成日期
            subscription.last_billed = now
            subscription.save()
            print("new generate billing")
        return 'bill success'
    except Exception as e:
        # 记录异常
        print(f"Task failed with error: {e}")
        return None
