Commit ef4eaa92 authored by Birin Sanchez's avatar Birin Sanchez

Add new subscription registration logic using pending ChosenRewards.

Signed-off-by: Birin Sanchez's avatarBirin Sanchez <birin.sanchez@puri.sm>
parent 730a3745
......@@ -136,6 +136,28 @@ class Limit(models.Model):
return True
return False
def enable(self, ren_date):
if self.service == settings.LM_SERVICES.TUNNEL:
# TUNNEL special case requires user manual activation
self.is_active = False
elif self.service == settings.LM_SERVICES.CHAT:
self.user.set_ldap_group("chat")
self.is_active = True
elif self.service == settings.LM_SERVICES.MAIL:
self.user.set_ldap_group("mail")
self.is_active = True
elif self.service == settings.LM_SERVICES.SOCIAL:
self.user.set_ldap_group("social")
self.is_active = True
elif self.service == settings.LM_SERVICES.XMPP:
self.user.set_ldap_group("xmpp")
self.is_active = True
elif self.service == settings.LM_SERVICES.GROUP:
self.is_active = True
else:
raise Exception(
"Invalid activation attempt. Service not recognised.")
self.renewal_date = ren_date
class ExternalBundle(models.Model):
"""Class used to represent external bundles that exist in external
......
import datetime
from django.utils import timezone
from django.conf import settings
from purist.models import get_woo_connection
from celery.utils.log import get_task_logger
from limitmonitor.models import ExternalCredit, ExternalBundle
from cart.models import ChosenReward
logger = get_task_logger(__name__)
def get_username_from_woo_customer_id(customer_id, woo=None):
if woo is None:
woo = get_woo_connection()
try:
query = "customers/" + str(customer_id)
result = woo.get(query).json()
return result["username"]
except Exception:
logger.exception(
"Could not retrieve username for customer_id " + str(customer_id))
return "invalid"
def parse_subscription(json_entry):
subscription_id = str(json_entry["id"])
# validation
if len(json_entry["line_items"]) != 1:
raise Exception("Too many line items in subscription %s" % (id, ))
line_item = json_entry["line_items"][0]
quantity = line_item["quantity"]
if quantity != 1:
raise Exception("Bad quantity %s in subscription %s"
% (quantity, id, ))
# calculate next renewal date
next_renewal_naive = datetime.datetime.strptime(
json_entry["next_payment_date"], "%Y-%m-%dT%H:%M:%S")
next_renewal = timezone.make_aware(next_renewal_naive)
# get account name
username = get_username_from_woo_customer_id(json_entry["customer_id"])
# bundle_key value is different depending on the subscription
# having variations or not
if line_item.get('variation_id') != 0:
bundle_key = line_item.get('variation_id')
else:
bundle_key = line_item.get('product_id')
# create result
result = {
# FIXME: this is WOO_SUBSCRIPTION_V1 from purist.limitmonitor
"parser": 2,
"external_key": subscription_id,
"label": json_entry["number"],
"bundle_key": bundle_key,
"bundle_label": str(line_item["name"]),
"quantity": 1,
"account": username,
"next_renewal": next_renewal,
"status": json_entry["status"]
}
return result
def get_user_subscriptions(user):
user_wc_id = user.get_woocommerce_id()
woo = get_woo_connection()
subscriptions = woo.get(
'subscriptions?customer={}'.format(user_wc_id)).json()
if len(subscriptions) >= 1:
return subscriptions
else:
return None
def subscription_was_processed(parsed_sub):
"""Returns an ExternalCredit fron the DB if the subscription was
already processed. If the subscription was not already
processed it returns a new ExternalCredit created from parsed_sub
data with is_converted=False
"""
try:
ext_cred = ExternalCredit.objects.get(
external_key=parsed_sub['external_key'])
except ExternalCredit.DoesNotExist:
ext_cred = ExternalCredit(
parser=parsed_sub["parser"],
external_key=parsed_sub["external_key"],
label=parsed_sub["label"],
bundle_key=parsed_sub["bundle_key"],
bundle_label=parsed_sub["bundle_label"],
quantity=parsed_sub["quantity"],
account_name=parsed_sub["account"],
additional_data="None",
is_converted=False,
)
return ext_cred
def get_services_from_bundle(bundle_key):
ext_buns = ExternalBundle.objects.filter(external_key=bundle_key)
result = []
for ext_bun in ext_buns:
result.append(ext_bun.service)
return result
def process_pending_registrations_user(user):
subscriptions = get_user_subscriptions(user)
if subscriptions is None:
logger.info('User {} has no subscriptions.'.format(user.username))
return
for sub in subscriptions:
parsed_sub = parse_subscription(sub)
if parsed_sub['bundle_key'] not in settings.WOOSUB1_PRODUCT_LIST:
continue # Skip this subscription as is not a product we care of
ext_cred = subscription_was_processed(parsed_sub)
if ext_cred.is_converted:
logger.info('Subscription {} for user {} was already '
'processed'.format(parsed_sub['label'], user.username))
continue # Skip this subscription as it was processed already
services = get_services_from_bundle(parsed_sub['bundle_key'])
if parsed_sub['status'] == 'active':
error = ''
is_pending = True
try:
for service in services:
serv = user.limit_set.get(service=service)
serv.enable(parsed_sub['next_renewal'])
serv.save()
ext_cred.is_converted = True
is_pending = False
except Exception as e:
error = repr(e)
ext_cred.error_message = '{}: {}'.format(
ext_cred.external_key,
error)
ext_cred.is_converted = False
is_pending = True
finally:
if hasattr(user, 'chosenreward'):
user.chosenreward.is_pending = is_pending
user.chosenreward.save()
ext_cred.save()
if is_pending:
logger.info('Subscription {} for user {} found error: '
'{}'.format(parsed_sub['label'], user.username,
error))
else:
logger.info('Subscription {} for user {} was processed '
'successfully'.format(
parsed_sub['label'], user.username))
else:
# Log this subscription is not active
logger.info('Subscription {} for user {} status is: {}'.format(
parsed_sub['label'], user.username, parsed_sub['status']))
def process_pending_registrations():
pending_regs = ChosenReward.objects.filter(is_pending=True)
for reg in pending_regs:
process_pending_registrations_user(reg.user)
......@@ -3,7 +3,7 @@ from celery import shared_task
from .task_resources import common
from .task_resources import tunnel_credit
from .task_resources import tunnel_subscription
from .task_resources import subscription
@shared_task
def tunnel_refresh_subscription():
......@@ -33,3 +33,8 @@ def debug_connection_task():
@shared_task
def purge_users_pending_cart_task():
common.purge_users_pending_cart()
@shared_task
def process_pending_registrations():
subscription.process_pending_registrations()
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment