from django.core.management.base import BaseCommand from django.utils import timezone from core.models import Profile from core.whatsapp import send_whatsapp_message from django.utils.translation import gettext as _ from datetime import timedelta class Command(BaseCommand): help = 'Checks for expiring subscriptions and sends reminders via WhatsApp' def handle(self, *args, **options): today = timezone.now().date() # Reminders for 7 days, 3 days, and 1 day before expiry reminder_days = [7, 3, 1] for days in reminder_days: expiry_date = today + timedelta(days=days) expiring_profiles = Profile.objects.filter( subscription_expiry=expiry_date, subscription_plan__in=['MONTHLY', 'ANNUAL'] ) for profile in expiring_profiles: full_phone = profile.full_phone_number if full_phone: message = _( "Hello %(user)s, your MASAR CARGO subscription (%(plan)s) will expire in %(days)s days on %(date)s. " "Please renew to avoid account suspension." ) % { 'user': profile.user.username, 'plan': profile.get_subscription_plan_display(), 'days': days, 'date': profile.subscription_expiry.strftime('%d/%m/%Y') } self.stdout.write(f"Sending reminder to {profile.user.username} ({full_phone}) - {days} days left") send_whatsapp_message(full_phone, message) # Also check for profiles that expired TODAY and send a notification expired_today = Profile.objects.filter( subscription_expiry=today, subscription_plan__in=['MONTHLY', 'ANNUAL'] ) for profile in expired_today: full_phone = profile.full_phone_number if full_phone: message = _( "Hello %(user)s, your MASAR CARGO subscription has EXPIRED today. " "Your account is now suspended. Please contact support to renew." ) % { 'user': profile.user.username } self.stdout.write(f"Sending expiry notice to {profile.user.username} ({full_phone})") send_whatsapp_message(full_phone, message) self.stdout.write(self.style.SUCCESS('Successfully checked subscriptions'))