79 lines
2.6 KiB
Python
79 lines
2.6 KiB
Python
from datetime import timedelta
|
|
from django.utils import timezone
|
|
import datetime
|
|
from manage_subscriptions.models import PrincipalSubscription, SubscriptionStatus
|
|
|
|
|
|
class SubscriptionService:
|
|
def __init__(self):
|
|
self._principal_subscription = None
|
|
|
|
@property
|
|
def principal_subscription(self):
|
|
"""Get the current principal subscription."""
|
|
return self._principal_subscription
|
|
|
|
@principal_subscription.setter
|
|
def principal_subscription(self, value):
|
|
"""Set the current principal subscription."""
|
|
self._principal_subscription = value
|
|
|
|
def create_principal_subscription(
|
|
self,
|
|
principal,
|
|
subscription,
|
|
stripe_subscription,
|
|
order_id,
|
|
current_period_start,
|
|
current_period_end,
|
|
coupon=None,
|
|
):
|
|
"""Create a principal subscription and return it."""
|
|
start_date, end_date = self._calculate_dates(
|
|
current_period_start, current_period_end, subscription.calculate_days()
|
|
)
|
|
|
|
PrincipalSubscription.objects.filter(principal=principal, status=SubscriptionStatus.ACTIVE).update(status=SubscriptionStatus.EXPIRED, active=False)
|
|
|
|
principal_subscription = PrincipalSubscription.objects.create(
|
|
principal=principal,
|
|
subscription=subscription,
|
|
stripe_subscription_id=stripe_subscription,
|
|
is_paid=True,
|
|
auto_renew=bool(stripe_subscription),
|
|
order_id=order_id,
|
|
start_date=start_date,
|
|
end_date=end_date,
|
|
grace_period_end_date=PrincipalSubscription.generate_grace_period_end_date(end_date),
|
|
coupon_code=coupon.coupon_code if coupon else None,
|
|
)
|
|
|
|
if coupon:
|
|
self._update_coupon(coupon)
|
|
|
|
self.principal_subscription = principal_subscription
|
|
return principal_subscription
|
|
|
|
def _calculate_dates(
|
|
self, current_period_start, current_period_end, subscription_days
|
|
):
|
|
"""Calculate subscription start and end dates."""
|
|
today = timezone.now().date()
|
|
start_date = (
|
|
datetime.datetime.fromtimestamp(current_period_start).date()
|
|
if current_period_start
|
|
else today
|
|
)
|
|
end_date = (
|
|
datetime.datetime.fromtimestamp(current_period_end).date()
|
|
if current_period_end
|
|
else (today + timedelta(days=subscription_days))
|
|
)
|
|
return start_date, end_date
|
|
|
|
def _update_coupon(self, coupon):
|
|
"""Update coupon usage count."""
|
|
coupon.no_of_redeems += 1
|
|
coupon.save()
|
|
print("Coupon Saved Successfully!!!")
|