<commit_before>"""
Helper methods for enterprise app.
"""


import hashlib
import hmac
import logging
from collections import OrderedDict
from functools import reduce  # pylint: disable=redefined-builtin
from urllib.parse import urlencode, urlparse

import crum
from django.conf import settings
from django.urls import reverse
from django.utils.translation import ugettext as _
from edx_django_utils.cache import TieredCache
from edx_rest_api_client.client import EdxRestApiClient
from edx_rest_framework_extensions.auth.jwt.cookies import get_decoded_jwt
from oscar.core.loading import get_model
from requests.exceptions import ConnectionError as ReqConnectionError
from requests.exceptions import Timeout
from slumber.exceptions import SlumberHttpBaseException

from ecommerce.core.constants import SYSTEM_ENTERPRISE_LEARNER_ROLE
from ecommerce.core.url_utils import absolute_url, get_lms_dashboard_url
from ecommerce.enterprise.exceptions import EnterpriseDoesNotExist
from ecommerce.extensions.offer.models import OFFER_PRIORITY_ENTERPRISE

ConditionalOffer = get_model('offer', 'ConditionalOffer')
StockRecord = get_model('partner', 'StockRecord')
Voucher = get_model('voucher', 'Voucher')
CONSENT_FAILED_PARAM = 'consent_failed'
log = logging.getLogger(__name__)

CUSTOMER_CATALOGS_DEFAULT_RESPONSE = {
    'count': 0,
    'num_pages': 0,
    'current_page': 0,
    'start': 0,
    'next': None,
    'previous': None,
    'results': [],
}


def get_enterprise_api_client(site):
    """
    Constructs a REST client for to communicate with the Open edX Enterprise Service
    """
    return EdxRestApiClient(
        site.siteconfiguration.enterprise_api_url,
        jwt=site.siteconfiguration.access_token
    )


def get_enterprise_customer(site, uuid):
    """
    Return a single enterprise customer
    """
    resource = 'enterprise-customer'
    cache_key = u'{site_domain}_{partner_code}_{resource}_{enterprise_uuid}'.format(
        site_domain=site.domain,
        partner_code=site.siteconfiguration.partner.short_code,
        resource=resource,
        enterprise_uuid=uuid,
    )
    cache_key = hashlib.md5(cache_key.encode('utf-8')).hexdigest()
    cached_response = TieredCache.get_cached_response(cache_key)
    if cached_response.is_found:
        return cached_response.value

    client = get_enterprise_api_client(site)
    path = [resource, str(uuid)]
    client = reduce(getattr, path, client)

    try:
        response = client.get()
    except (ReqConnectionError, SlumberHttpBaseException, Timeout):
        return None

    enterprise_customer_response = {
        'name': response['name'],
        'id': response['uuid'],
        'enable_data_sharing_consent': response['enable_data_sharing_consent'],
        'enforce_data_sharing_consent': response['enforce_data_sharing_consent'],
        'contact_email': response.get('contact_email', ''),
        'slug': response.get('slug')
    }

    TieredCache.set_all_tiers(
        cache_key,<commit_msg>ENT3709 Added enterprise customer sender alias which can be used in assign/remind/revoke emails (#3300)<commit_after>"""
Helper methods for enterprise app.
"""


import hashlib
import hmac
import logging
from collections import OrderedDict
from functools import reduce  # pylint: disable=redefined-builtin
from urllib.parse import urlencode, urlparse

import crum
from django.conf import settings
from django.urls import reverse
from django.utils.translation import ugettext as _
from edx_django_utils.cache import TieredCache
from edx_rest_api_client.client import EdxRestApiClient
from edx_rest_framework_extensions.auth.jwt.cookies import get_decoded_jwt
from oscar.core.loading import get_model
from requests.exceptions import ConnectionError as ReqConnectionError
from requests.exceptions import Timeout
from slumber.exceptions import SlumberHttpBaseException

from ecommerce.core.constants import SYSTEM_ENTERPRISE_LEARNER_ROLE
from ecommerce.core.url_utils import absolute_url, get_lms_dashboard_url
from ecommerce.enterprise.exceptions import EnterpriseDoesNotExist
from ecommerce.extensions.offer.models import OFFER_PRIORITY_ENTERPRISE

ConditionalOffer = get_model('offer', 'ConditionalOffer')
StockRecord = get_model('partner', 'StockRecord')
Voucher = get_model('voucher', 'Voucher')
CONSENT_FAILED_PARAM = 'consent_failed'
log = logging.getLogger(__name__)

CUSTOMER_CATALOGS_DEFAULT_RESPONSE = {
    'count': 0,
    'num_pages': 0,
    'current_page': 0,
    'start': 0,
    'next': None,
    'previous': None,
    'results': [],
}


def get_enterprise_api_client(site):
    """
    Constructs a REST client for to communicate with the Open edX Enterprise Service
    """
    return EdxRestApiClient(
        site.siteconfiguration.enterprise_api_url,
        jwt=site.siteconfiguration.access_token
    )


def get_enterprise_customer(site, uuid):
    """
    Return a single enterprise customer
    """
    resource = 'enterprise-customer'
    cache_key = u'{site_domain}_{partner_code}_{resource}_{enterprise_uuid}'.format(
        site_domain=site.domain,
        partner_code=site.siteconfiguration.partner.short_code,
        resource=resource,
        enterprise_uuid=uuid,
    )
    cache_key = hashlib.md5(cache_key.encode('utf-8')).hexdigest()
    cached_response = TieredCache.get_cached_response(cache_key)
    if cached_response.is_found:
        return cached_response.value

    client = get_enterprise_api_client(site)
    path = [resource, str(uuid)]
    client = reduce(getattr, path, client)

    try:
        response = client.get()
    except (ReqConnectionError, SlumberHttpBaseException, Timeout):
        return None

    enterprise_customer_response = {
        'name': response['name'],
        'id': response['uuid'],
        'enable_data_sharing_consent': response['enable_data_sharing_consent'],
        'enforce_data_sharing_consent': response['enforce_data_sharing_consent'],
        'contact_email': response.get('contact_email', ''),
        'slug': response.get('slug'),
        'sender_alias': response.get('sender_alias', ''),
    }

    TieredCache.set_all_tiers(
        cache_key,
{'fraction_non_alphanumeric': 0.08890341559078281, 'fraction_numerical': 0.0032685079261317207, 'mean_word_length': 4.645756457564576, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '217353', 'n_tokens_mistral': 1874, 'n_tokens_neox': 1846, 'n_words': 398}