import graphene from django.utils.timezone import now from graphene import relay from oauth.hep_client import HepClient, HepClientException from oauth.user_signup_login_handler import create_role_for_user from users.models import License class Coupon(relay.ClientIDMutation): class Input: coupon_code = graphene.String() success = graphene.Boolean() @classmethod def mutate_and_get_payload(cls, root, info, **kwargs): coupon_code = kwargs.get('coupon_code').strip() hep_client = HepClient() try: hep_id = info.context.user.hep_id except AttributeError: raise Exception('not_authenticated') try: response = hep_client.redeem_coupon(coupon_code, hep_id, request=info) except HepClientException: raise Exception('unknown_error') if not response: raise Exception('invalid_coupon') product = hep_client.entry_to_product(response['data'], now(), 'coupon') if not product: raise Exception('non_myskillbox_product') license = License.objects.create_license_for_role(info.context.user, product['activated'], product['raw'], product['license']['edition'], product['order_id'], product['isbn']) create_role_for_user(info.context.user, license.for_role.key) return cls(success=True) class CouponMutations: redeem_coupon = Coupon.Field()