Commit aafed233 authored by David Seaward's avatar David Seaward
Browse files

* Conservative adjustments for subscription-related WooCommerce connections.



* Refactor WooCommerce calls as a class method.
Signed-off-by: David Seaward's avatarDavid Seaward <david.seaward@puri.sm>
parent e7071c8e
Pipeline #54236 passed with stage
in 31 seconds
......@@ -77,11 +77,14 @@ class CartRegistrationView(RegistrationView):
if self.bundle == 'Basic':
user.account_type = AccountType.BASIC
SubscriptionManager.create_subscription(
user.save()
reward.save()
new_sub = SubscriptionManager.create_subscription(
user, paid=True,
status=SubscriptionStatus.ACTIVE,
billing_email=user.email
)
assert new_sub is not None, "Failed to create subscription for {}".format(user)
forced_update(user)
elif self.bundle == 'Complete':
......
......@@ -41,11 +41,16 @@ class SubscriptionError(Exception):
pass
class SubscriptionManager():
class SubscriptionManager:
woo = get_woo_connection()
@classmethod
def woo_get(cls, query):
woo = get_woo_connection()
return woo.get(query)
def create_subscription(user, account_type=AccountType.BASIC,
@classmethod
def create_subscription(cls, user, account_type=AccountType.BASIC,
billing_period=BillingPeriod.MONTHLY, paid=False,
next_payment_date=None, billing_email=None,
status=SubscriptionStatus.PENDING,
......@@ -78,13 +83,17 @@ class SubscriptionManager():
):
variation_id = k
break
if variation_id is None:
# TODO: raise exception saying there is not bundle with
# that account_type and billing_period
return None
user_wc_id = user.get_woocommerce_id()
# TODO: raise execption if user has not WC account
if user_wc_id is None:
message = "Cannot create subscription for user {} with missing WooCommerceID.".format(user)
raise Exception(message)
if next_payment_date is None:
next_payment_date = timezone.now() + timezone.timedelta(days=30)
......@@ -111,9 +120,8 @@ class SubscriptionManager():
order = user.woo_post_json('orders', order_data)
if order is None:
# TODO:
# raise could not create subscription due to WooCommerce error
return None
message = "Cannot create subscription for user {} because there was an error creating the associated order.".format(user)
raise Exception(message)
# Set billing period for subscription.
bill_p = 'month'
......@@ -138,11 +146,11 @@ class SubscriptionManager():
subs_data['status'] = status.value
if billing_email:
subs_data['billing'] = order_data['billing']
sub = user.woo_post_json('subscriptions', subs_data)
if sub is None:
# TODO:
# raise could not create subscription due to WooCommerce error
return None
message = "Cannot create subscription for user {} because there was an error posting the subscription command.".format(user)
raise Exception(message)
new_sub = Subscription.parse_subscription(sub, user)
# We save the order's order_key in the subscription for now
......@@ -165,15 +173,14 @@ class SubscriptionManager():
@classmethod
def search_subscriptions(cls, user, status=None):
if cls.woo is None:
cls.woo = get_woo_connection()
result = []
query = 'subscriptions?customer={}'.format(user.get_woocommerce_id())
if status is not None:
query += '&status={}'.format(status.value)
r = cls.woo.get(query)
r = cls.woo_get(query)
if r.status_code == 200:
q_subs = r.json()
for q_sub in q_subs:
......@@ -186,15 +193,15 @@ class SubscriptionManager():
finally:
if sub:
result.append(sub)
return result
@classmethod
def get_subscription(cls, sub_id):
if cls.woo is None:
cls.woo = get_woo_connection()
query = 'subscriptions/{}'.format(sub_id)
r = cls.woo.get(query)
r = cls.woo_get(query)
if r.status_code == 200:
q_sub = r.json()
try:
......@@ -206,9 +213,13 @@ class SubscriptionManager():
return sub
class Subscription():
class Subscription:
@classmethod
def woo_get(cls, query):
woo = get_woo_connection()
woo = get_woo_connection()
return woo.get(query)
def __init__(
self, user, subscription_id, product_id, variation_id,
......@@ -230,11 +241,10 @@ class Subscription():
self.order_id = order_id
self.price = price
self.coupons = coupons
self.woo = None
@classmethod
def parse_subscription(cls, json_entry, user=None):
if cls.woo is None:
cls.woo = get_woo_connection()
subscription_id = str(json_entry["id"])
......@@ -257,6 +267,7 @@ class Subscription():
price = float(line_item.get('price', 0))
coupons = json_entry['coupon_lines']
line_item_id = line_item['id']
# calculate next renewal date
if json_entry["next_payment_date"] != "":
next_renewal_naive = timezone.datetime.strptime(
......@@ -269,7 +280,7 @@ class Subscription():
if user is None:
try:
user_q = 'customers/' + str(json_entry['customer_id'])
user_r = cls.woo.get(user_q).json()
user_r = cls.woo_get(user_q).json()
# remove the domain part of the WC username
username = user_r['username'].split('@')[0]
user = User.objects.get(username=username)
......@@ -341,6 +352,9 @@ class Subscription():
return choices
def save(self):
if self.woo is None:
self.woo = get_woo_connection()
if self.billing_period == BillingPeriod.ANNUAL:
b_period = 'year'
elif self.billing_period == BillingPeriod.MONTHLY:
......@@ -390,6 +404,9 @@ class Subscription():
return False
def apply_coupon(self, code):
if self.woo is None:
self.woo = get_woo_connection()
# Get all coupons
req = self.woo.get('coupons')
if req.status_code != 200:
......
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