Select correct product (basic version)

This commit is contained in:
Christian Cueni 2020-01-28 15:28:32 +01:00
parent bc997bbeea
commit 9c4e2de296
7 changed files with 163 additions and 31 deletions

View File

@ -7,7 +7,7 @@
# #
# Created on 23.01.20 # Created on 23.01.20
# @author: chrigu <christian.cueni@iterativ.ch> # @author: chrigu <christian.cueni@iterativ.ch>
from datetime import datetime from datetime import datetime, timedelta
from django.conf import settings from django.conf import settings
import logging import logging
@ -18,6 +18,10 @@ logger = logging.getLogger(__name__)
MYSKILLBOX_TEACHER_EDITION_ISBN = "000-4-5678-9012-3" MYSKILLBOX_TEACHER_EDITION_ISBN = "000-4-5678-9012-3"
MYSKILLBOX_STUDENT_EDITION_ISBN = "123-4-5678-9012-3" MYSKILLBOX_STUDENT_EDITION_ISBN = "123-4-5678-9012-3"
TEACHER_EDITION_DURATION = 365
STUDENT_EDITION_DURATION = 4*365
class HepClientException(Exception): class HepClientException(Exception):
pass pass
@ -105,31 +109,64 @@ class HepClient:
def myskillbox_product_for_customer(self, admin_token, customer_id): def myskillbox_product_for_customer(self, admin_token, customer_id):
orders = self._customer_orders(admin_token, customer_id) orders = self._customer_orders(admin_token, customer_id)
# Todo return only relevant product products = self._extract_myskillbox_products(orders)
return self._extract_myskillbox_products(orders)
if len(products) == 0:
return None
else:
return self._get_relevant_product(products)
def _extract_myskillbox_products(self, orders): def _extract_myskillbox_products(self, orders):
# Todo retun all products products = []
product = None
for order_item in orders['items']: for order_item in orders['items']:
for item in order_item['items']: for item in order_item['items']:
if item['sku'] == MYSKILLBOX_TEACHER_EDITION_ISBN: if item['sku'] == MYSKILLBOX_TEACHER_EDITION_ISBN or item['sku'] == MYSKILLBOX_STUDENT_EDITION_ISBN:
product = { product = {
'edition': 'teacher',
'raw': item, 'raw': item,
'activated': self._get_item_activation(order_item) 'activated': self._get_item_activation(order_item)
} }
elif not product and item['sku'] == MYSKILLBOX_STUDENT_EDITION_ISBN: if item['sku'] == MYSKILLBOX_TEACHER_EDITION_ISBN:
product = { product['edition'] = 'teacher'
'edition': 'student',
'raw': item, else:
'activated': self._get_item_activation(order_item) product['edition'] = 'student'
}
products.append(product)
return products
return product
def _get_item_activation(self, item): def _get_item_activation(self, item):
for history in item['status_histories']: for history in item['status_histories']:
# todo can there be no date?
if history['comment'] == 'payed by couponcode': if history['comment'] == 'payed by couponcode':
return datetime.strptime(history['created_at'], '%Y-%m-%d %H:%M:%S') return datetime.strptime(history['created_at'], '%Y-%m-%d %H:%M:%S')
def _get_relevant_product(self, products):
def filter_inactive_products(product):
if product['edition'] == 'teacher':
expiry_delta = product['activated'] + timedelta(TEACHER_EDITION_DURATION)
else:
expiry_delta = product['activated'] + timedelta(STUDENT_EDITION_DURATION)
if HepClient.is_product_valid(expiry_delta):
return True
else:
return False
active_products = list(filter(filter_inactive_products, products))
print(active_products)
# todo can a teacher have multiple licenses?
# clarify with hep
if len(active_products) == 0:
return None
elif len(active_products) == 1:
return active_products[0]
@staticmethod
def is_product_valid(expiry_date):
return expiry_date >= datetime.now()

View File

@ -374,3 +374,4 @@ USE_LOCAL_REGISTRATION = False
# HEP # HEP
HEP_ADMIN_TOKEN = "asdf" HEP_ADMIN_TOKEN = "asdf"

View File

@ -8,10 +8,91 @@
# Created on 23.01.20 # Created on 23.01.20
# @author: chrigu <christian.cueni@iterativ.ch> # @author: chrigu <christian.cueni@iterativ.ch>
import json import json
from datetime import datetime, timedelta
from django.test import TestCase, Client from django.test import TestCase
from core.factories import UserFactory from core.hep_client import HepClient, TEACHER_EDITION_DURATION
class HepClientTestCases(TestCase): class HepClientTestCases(TestCase):
pass def setUp(self):
self.hep_client = HepClient()
self.now = datetime.now()
def test_has_no_valid_product(self):
products = [
{
'edition': 'teacher',
'raw': {},
'activated': self.now - timedelta(2*TEACHER_EDITION_DURATION)
},
{
'edition': 'teacher',
'raw': {},
'activated': self.now - timedelta(3 * TEACHER_EDITION_DURATION)
},
{
'edition': 'teacher',
'raw': {},
'activated': self.now - timedelta(4 * TEACHER_EDITION_DURATION)
}
]
relevant_product = self.hep_client._get_relevant_product(products)
self.assertIsNone(relevant_product)
def test_has_valid_product(self):
products = [
{
'edition': 'teacher',
'raw': {
'id': 0
},
'activated': self.now - timedelta(7)
},
{
'edition': 'teacher',
'raw': {
'id': 1
},
'activated': self.now - timedelta(3 * TEACHER_EDITION_DURATION)
},
{
'edition': 'teacher',
'raw': {
'id': 2
},
'activated': self.now - timedelta(4 * TEACHER_EDITION_DURATION)
}
]
relevant_product = self.hep_client._get_relevant_product(products)
self.assertEqual(relevant_product['raw']['id'], 0)
def test_has_multiple_valid_products(self):
products = [
{
'edition': 'teacher',
'raw': {
'id': 0
},
'activated': self.now - timedelta(7)
},
{
'edition': 'teacher',
'raw': {
'id': 1
},
'activated': self.now - timedelta(3 * TEACHER_EDITION_DURATION)
},
{
'edition': 'teacher',
'raw': {
'id': 2
},
'activated': self.now - timedelta(4 * TEACHER_EDITION_DURATION)
}
]
relevant_product = self.hep_client._get_relevant_product(products)
self.assertEqual(relevant_product['raw']['id'], 0)

View File

@ -10,10 +10,9 @@
from datetime import timedelta from datetime import timedelta
from django.db import models from django.db import models
from users.models import Role
TEACHER_EDITION_DURATION = 365 from core.hep_client import TEACHER_EDITION_DURATION, STUDENT_EDITION_DURATION
STUDENT_EDITION_DURATION = 4*365 from users.models import Role
class LicenseManager(models.Manager): class LicenseManager(models.Manager):

View File

@ -9,9 +9,9 @@
# @author: chrigu <christian.cueni@iterativ.ch> # @author: chrigu <christian.cueni@iterativ.ch>
from datetime import datetime from datetime import datetime
from django.utils.translation import ugettext_lazy as _
from django.db import models from django.db import models
from core.hep_client import HepClient
from registration.managers import LicenseManager from registration.managers import LicenseManager
from users.managers import RoleManager from users.managers import RoleManager
from users.models import Role, User from users.models import Role, User
@ -29,7 +29,7 @@ class License(models.Model):
return self.for_role.key == RoleManager.TEACHER_KEY return self.for_role.key == RoleManager.TEACHER_KEY
def is_valid(self): def is_valid(self):
return datetime(self.expire_date.year, self.expire_date.month, self.expire_date.day) <= datetime.now() return HepClient.is_product_valid(datetime(self.expire_date.year, self.expire_date.month, self.expire_date.day))
def __str__(self): def __str__(self):
return 'License for role: %s' % self.for_role return 'License for role: %s' % self.for_role

View File

@ -86,10 +86,11 @@ class Login(relay.ClientIDMutation):
# todo go to shop # todo go to shop
pass pass
UserRole.objects.create_role_for_user(user, license.for_role.key) if license.for_role.key == Role.objects.TEACHER_KEY:
default_class_name = SchoolClass.generate_default_group_name() UserRole.objects.create_role_for_user(user, license.for_role.key)
default_class = SchoolClass.objects.create(name=default_class_name) default_class_name = SchoolClass.generate_default_group_name()
user.school_classes.add(default_class) default_class = SchoolClass.objects.create(name=default_class_name)
user.school_classes.add(default_class)
# if teacher create class # if teacher create class
# if student add to class if exists??? # if student add to class if exists???

View File

@ -9,7 +9,7 @@
# @author: chrigu <christian.cueni@iterativ.ch> # @author: chrigu <christian.cueni@iterativ.ch>
import json import json
import os import os
from datetime import timedelta from datetime import timedelta, datetime
from unittest.mock import patch from unittest.mock import patch
from django.contrib.sessions.middleware import SessionMiddleware from django.contrib.sessions.middleware import SessionMiddleware
from django.test import TestCase, RequestFactory from django.test import TestCase, RequestFactory
@ -21,23 +21,33 @@ from core.factories import UserFactory
from core.hep_client import HepClient from core.hep_client import HepClient
from registration.factories import LicenseFactory from registration.factories import LicenseFactory
from registration.models import License from registration.models import License
from users.models import Role, MagentoToken, User from users.models import Role, MagentoToken, User, SchoolClass
FAKE_TOKEN = 'abcd12345!' FAKE_TOKEN = 'abcd12345!'
## Setup json data
dir_path = os.path.dirname(os.path.realpath(__file__)) dir_path = os.path.dirname(os.path.realpath(__file__))
with open('{}/valid_teacher_orders.json'.format(dir_path), 'r') as file: with open('{}/valid_teacher_orders.json'.format(dir_path), 'r') as file:
order_data = file.read() order_data = file.read()
ORDERS = json.loads(order_data)
with open('{}/me_data.json'.format(dir_path), 'r') as file: with open('{}/me_data.json'.format(dir_path), 'r') as file:
me_data = file.read() me_data = file.read()
ME_DATA = json.loads(me_data) ME_DATA = json.loads(me_data)
order_items = json.loads(order_data)
for order_item in order_items['items']:
for status in order_item['status_histories']:
if status['comment'] == 'payed by couponcode':
yesterday = datetime.now() - timedelta(1)
status['created_at'] = datetime.strftime(yesterday, '%Y-%m-%d %H:%M:%S')
ORDERS = order_items
class PasswordResetTests(TestCase): class PasswordResetTests(TestCase):
def setUp(self): def setUp(self):
@ -103,11 +113,14 @@ class PasswordResetTests(TestCase):
license = License.objects.get(licensee=user) license = License.objects.get(licensee=user)
self.assertEqual(license.for_role.key, Role.objects.TEACHER_KEY) self.assertEqual(license.for_role.key, Role.objects.TEACHER_KEY)
school_class = SchoolClass.objects.get(users__in=[user])
self.assertIsNotNone(school_class)
self.assertTrue(result.get('data').get('login').get('success')) self.assertTrue(result.get('data').get('login').get('success'))
self.assertTrue(self.user.is_authenticated) self.assertTrue(self.user.is_authenticated)
## can login with license and user ## can login with license and user
# can login with no user and license ## can login with no user and license
# can login with no user and local license # can login with no user and local license
# cannot login without user # cannot login without user
# cannot login with user and not verfied # cannot login with user and not verfied