pending_messages = []<EOL>if course_id:<EOL><INDENT>succeeded, pending, failed = cls.enroll_users_in_course(<EOL>enterprise_customer=enterprise_customer,<EOL>course_id=course_id,<EOL>course_mode=mode,<EOL>emails=emails,<EOL>)<EOL>all_successes = succeeded + pending<EOL>if notify:<EOL><INDENT>enterprise_customer.notify_enrolled_learners(<EOL>catalog_api_user=request.user,<EOL>course_id=course_id,<EOL>users=all_successes,<EOL>)<EOL><DEDENT>if succeeded:<EOL><INDENT>pending_messages.append(cls.get_success_enrollment_message(succeeded, course_id))<EOL><DEDENT>if failed:<EOL><INDENT>pending_messages.append(cls.get_failed_enrollment_message(failed, course_id))<EOL><DEDENT>if pending:<EOL><INDENT>pending_messages.append(cls.get_pending_enrollment_message(pending, course_id))<EOL><DEDENT><DEDENT>if program_details:<EOL><INDENT>succeeded, pending, failed = cls.enroll_users_in_program(<EOL>enterprise_customer=enterprise_customer,<EOL>program_details=program_details,<EOL>course_mode=mode,<EOL>emails=emails,<EOL>)<EOL>all_successes = succeeded + pending<EOL>if notify:<EOL><INDENT>cls.notify_program_learners(<EOL>enterprise_customer=enterprise_customer,<EOL>program_details=program_details,<EOL>users=all_successes<EOL>)<EOL><DEDENT>program_identifier = program_details.get('<STR_LIT:title>', program_details.get('<STR_LIT>', _('<STR_LIT>')))<EOL>if succeeded:<EOL><INDENT>pending_messages.append(cls.get_success_enrollment_message(succeeded, program_identifier))<EOL><DEDENT>if failed:<EOL><INDENT>pending_messages.append(cls.get_failed_enrollment_message(failed, program_identifier))<EOL><DEDENT>if pending:<EOL><INDENT>pending_messages.append(cls.get_pending_enrollment_message(pending, program_identifier))<EOL><DEDENT><DEDENT>cls.send_messages(request, pending_messages)<EOL>

Enroll the users with the given email addresses to the courses specified, either specifically or by program.

Args:
    cls (type): The EnterpriseCustomerManageLearnersView class itself
    request: The HTTP request the enrollment is being created by
    enterprise_customer: The instance of EnterpriseCustomer whose attached users we're enrolling
    emails: An iterable of strings containing email addresses to enroll in a course
    mode: The enrollment mode the users will be enrolled in the course with
    course_id: The ID of the course in which we want to enroll
    program_details: Details about a program in which we want to enroll
    notify: Whether to notify (by email) the users that have been enrolled


def get(self, request, enterprise_customer_uuid):

context = self._build_context(request, enterprise_customer_uuid)<EOL>transmit_courses_metadata_form = TransmitEnterpriseCoursesForm()<EOL>context.update({self.ContextParameters.TRANSMIT_COURSES_METADATA_FORM: transmit_courses_metadata_form})<EOL>return render(request, self.template, context)<EOL>

Handle GET request - render "Transmit courses metadata" form.

Arguments:
    request (django.http.request.HttpRequest): Request instance
    enterprise_customer_uuid (str): Enterprise Customer UUID

Returns:
    django.http.response.HttpResponse: HttpResponse


@classmethod<EOL><INDENT>def enroll_users_in_program(cls, enterprise_customer, program_details, course_mode, emails, cohort=None):<DEDENT>

existing_users, unregistered_emails = cls.get_users_by_email(emails)<EOL>course_ids = get_course_runs_from_program(program_details)<EOL>successes = []<EOL>pending = []<EOL>failures = []<EOL>for user in existing_users:<EOL><INDENT>succeeded = cls.enroll_user(enterprise_customer, user, course_mode, *course_ids)<EOL>if succeeded:<EOL><INDENT>successes.append(user)<EOL><DEDENT>else:<EOL><INDENT>failures.append(user)<EOL><DEDENT><DEDENT>for email in unregistered_emails:<EOL><INDENT>pending_user = enterprise_customer.enroll_user_pending_registration(<EOL>email,<EOL>course_mode,<EOL>*course_ids,<EOL>cohort=cohort<EOL>)<EOL>pending.append(pending_user)<EOL><DEDENT>return successes, pending, failures<EOL>

Enroll existing users in all courses in a program, and create pending enrollments for nonexisting users.

Args:
    enterprise_customer: The EnterpriseCustomer which is sponsoring the enrollment
    program_details: The details of the program in which we're enrolling
    course_mode (str): The mode with which we're enrolling in the program
    emails: An iterable of email addresses which need to be enrolled

Returns:
    successes: A list of users who were successfully enrolled in all courses of the program
    pending: A list of PendingEnterpriseCustomerUsers who were successfully linked and had
        pending enrollments created for them in the database
    failures: A list of users who could not be enrolled in the program


@classmethod<EOL><INDENT>def get_failed_enrollment_message(cls, users, enrolled_in):<DEDENT>

failed_emails = [user.email for user in users]<EOL>return (<EOL>'<STR_LIT:error>',<EOL>_(<EOL>'<STR_LIT>'<EOL>).format(<EOL>enrolled_in=enrolled_in,<EOL>user_list='<STR_LIT:U+002CU+0020>'.join(failed_emails),<EOL>)<EOL>)<EOL>

Create message for the users who were not able to be enrolled in a course or program.

Args:
    users: An iterable of users who were not successfully enrolled
    enrolled_in (str): A string identifier for the course or program with which enrollment was attempted

Returns:
tuple: A 2-tuple containing a message type and message text


@classmethod<EOL><INDENT>def enroll_user(cls, enterprise_customer, user, course_mode, *course_ids):<DEDENT>

enterprise_customer_user, __ = EnterpriseCustomerUser.objects.get_or_create(<EOL>enterprise_customer=enterprise_customer,<EOL>user_id=user.id<EOL>)<EOL>enrollment_client = EnrollmentApiClient()<EOL>succeeded = True<EOL>for course_id in course_ids:<EOL><INDENT>try:<EOL><INDENT>enrollment_client.enroll_user_in_course(user.username, course_id, course_mode)<EOL><DEDENT>except HttpClientError as exc:<EOL><INDENT>if cls.is_user_enrolled(user, course_id, course_mode):<EOL><INDENT>succeeded = True<EOL><DEDENT>else:<EOL><INDENT>succeeded = False<EOL>default_message = '<STR_LIT>'<EOL>try:<EOL><INDENT>error_message = json.loads(exc.content.decode()).get('<STR_LIT:message>', default_message)<EOL><DEDENT>except ValueError:<EOL><INDENT>error_message = default_message<EOL><DEDENT>logging.error(<EOL>'<STR_LIT>',<EOL>dict(user=user.username, message=error_message)<EOL>)<EOL><DEDENT><DEDENT>if succeeded:<EOL><INDENT>__, created = EnterpriseCourseEnrollment.objects.get_or_create(<EOL>enterprise_customer_user=enterprise_customer_user,<EOL>course_id=course_id<EOL>)<EOL>if created:<EOL><INDENT>track_enrollment('<STR_LIT>', user.id, course_id)<EOL><DEDENT><DEDENT><DEDENT>return succeeded<EOL>

Enroll a single user in any number of courses using a particular course mode.

Args:
    enterprise_customer: The EnterpriseCustomer which is sponsoring the enrollment
    user: The user who needs to be enrolled in the course
    course_mode: The mode with which the enrollment should be created
    *course_ids: An iterable containing any number of course IDs to eventually enroll the user in.

Returns:
    Boolean: Whether or not enrollment succeeded for all courses specified


def _build_context(self, request, customer_uuid):

<EOL>enterprise_customer = EnterpriseCustomer.objects.get(uuid=customer_uuid)  <EOL>search_keyword = self.get_search_keyword(request)<EOL>linked_learners = self.get_enterprise_customer_user_queryset(request, search_keyword, customer_uuid)<EOL>pending_linked_learners = self.get_pending_users_queryset(search_keyword, customer_uuid)<EOL>context = {<EOL>self.ContextParameters.ENTERPRISE_CUSTOMER: enterprise_customer,<EOL>self.ContextParameters.PENDING_LEARNERS: pending_linked_learners,<EOL>self.ContextParameters.LEARNERS: linked_learners,<EOL>self.ContextParameters.SEARCH_KEYWORD: search_keyword or '<STR_LIT>',<EOL>self.ContextParameters.ENROLLMENT_URL: settings.LMS_ENROLLMENT_API_PATH,<EOL>}<EOL>context.update(admin.site.each_context(request))<EOL>context.update(self._build_admin_context(request, enterprise_customer))<EOL>return context<EOL>

Build common context parts used by different handlers in this view.


@classmethod<EOL><INDENT>def get_success_enrollment_message(cls, users, enrolled_in):<DEDENT>

Create message for the users who were enrolled in a course or program.

Args:
    users: An iterable of users who were successfully enrolled
    enrolled_in (str): A string identifier for the course or program the users were enrolled in

Returns:
    tuple: A 2-tuple containing a message type and message text


def get(self, request, template_id, view_type):

template = get_object_or_404(EnrollmentNotificationEmailTemplate, pk=template_id)<EOL>if view_type not in self.view_type_contexts:<EOL><INDENT>return HttpResponse(status=<NUM_LIT>)<EOL><DEDENT>base_context = self.view_type_contexts[view_type].copy()<EOL>base_context.update({'<STR_LIT>': self.get_user_name(request)})<EOL>return HttpResponse(template.render_html_template(base_context), content_type='<STR_LIT>')<EOL>

Render the given template with the stock data.


opts = customer._meta<EOL>codename = get_permission_codename('<STR_LIT>', opts)<EOL>has_change_permission = request.user.has_perm('<STR_LIT>' % (opts.app_label, codename))<EOL>return {<EOL>'<STR_LIT>': has_change_permission,<EOL>'<STR_LIT>': opts<EOL>}<EOL>


users = User.objects.filter(email__in=emails)<EOL>present_emails = users.values_list('<STR_LIT:email>', flat=True)<EOL>missing_emails = list(set(emails) - set(present_emails))<EOL>return users, missing_emails<EOL>

Accept a list of emails, and separate them into users that exist on OpenEdX and users who don't.

Args:
    emails: An iterable of email addresses to split between existing and nonexisting

Returns:
    users: Queryset of users who exist in the OpenEdX platform and who were in the list of email addresses
    missing_emails: List of unique emails which were in the original list, but do not yet exist as users


Initialize the form.

Substitute a ChoiceField in for the catalog field that would
normally be set up as a plain number entry field.


super(EnterpriseCustomerIdentityProviderAdminForm, self).__init__(*args, **kwargs)<EOL>idp_choices = utils.get_idp_choices()<EOL>help_text = '<STR_LIT>'<EOL>if saml_provider_configuration:<EOL><INDENT>provider_id = self.instance.provider_id<EOL>url = reverse('<STR_LIT>'.format(<EOL>saml_provider_configuration._meta.app_label,<EOL>saml_provider_configuration._meta.model_name))<EOL>if provider_id:<EOL><INDENT>identity_provider = utils.get_identity_provider(provider_id)<EOL>if identity_provider:<EOL><INDENT>update_url = url + '<STR_LIT>'.format(identity_provider.pk)<EOL>help_text = '<STR_LIT>'.format(update_url=update_url, identity_provider=identity_provider.name)<EOL><DEDENT>else:<EOL><INDENT>help_text += '<STR_LIT>'<EOL><DEDENT><DEDENT>else:<EOL><INDENT>help_text += '<STR_LIT>''<STR_LIT>'.format(add_url=url)<EOL><DEDENT><DEDENT>if idp_choices is not None:<EOL><INDENT>self.fields['<STR_LIT>'] = forms.TypedChoiceField(<EOL>choices=idp_choices,<EOL>label=_('<STR_LIT>'),<EOL>help_text=mark_safe(help_text),<EOL>)<EOL><DEDENT>

Initialize the form.

Substitutes CharField with TypedChoiceField for the provider_id field.


<EOL>course_details = self.cleaned_data.get(self.Fields.COURSE)<EOL>if course_details:<EOL><INDENT>course_mode = self.cleaned_data.get(self.Fields.COURSE_MODE)<EOL>if not course_mode:<EOL><INDENT>raise ValidationError(ValidationMessages.COURSE_WITHOUT_COURSE_MODE)<EOL><DEDENT>valid_course_modes = course_details["<STR_LIT>"]<EOL>if all(course_mode != mode["<STR_LIT>"] for mode in valid_course_modes):<EOL><INDENT>error = ValidationError(ValidationMessages.COURSE_MODE_INVALID_FOR_COURSE.format(<EOL>course_mode=course_mode,<EOL>course_id=course_details["<STR_LIT>"],<EOL>))<EOL>raise ValidationError({self.Fields.COURSE_MODE: error})<EOL><DEDENT><DEDENT>

Verify that the selected mode is valid for the given course .


program_id = self.cleaned_data[self.Fields.PROGRAM].strip()<EOL>if not program_id:<EOL><INDENT>return None<EOL><DEDENT>try:<EOL><INDENT>client = CourseCatalogApiClient(self._user, self._enterprise_customer.site)<EOL>program = client.get_program_by_uuid(program_id) or client.get_program_by_title(program_id)<EOL><DEDENT>except MultipleProgramMatchError as exc:<EOL><INDENT>raise ValidationError(ValidationMessages.MULTIPLE_PROGRAM_MATCH.format(program_count=exc.programs_matched))<EOL><DEDENT>except (HttpClientError, HttpServerError):<EOL><INDENT>raise ValidationError(ValidationMessages.INVALID_PROGRAM_ID.format(program_id=program_id))<EOL><DEDENT>if not program:<EOL><INDENT>raise ValidationError(ValidationMessages.INVALID_PROGRAM_ID.format(program_id=program_id))<EOL><DEDENT>if program['<STR_LIT:status>'] != ProgramStatuses.ACTIVE:<EOL><INDENT>raise ValidationError(<EOL>ValidationMessages.PROGRAM_IS_INACTIVE.format(program_id=program_id, status=program['<STR_LIT:status>'])<EOL>)<EOL><DEDENT>return program<EOL>

Clean program.

Try obtaining program treating form value as program UUID or title.

Returns:
    dict: Program information if program found


email_or_username = self.cleaned_data[self.Fields.EMAIL_OR_USERNAME].strip()<EOL>if not email_or_username:<EOL><INDENT>return email_or_username<EOL><DEDENT>email = email_or_username__to__email(email_or_username)<EOL>bulk_entry = len(split_usernames_and_emails(email)) > <NUM_LIT:1><EOL>if bulk_entry:<EOL><INDENT>for email in split_usernames_and_emails(email):<EOL><INDENT>validate_email_to_link(<EOL>email,<EOL>None,<EOL>ValidationMessages.INVALID_EMAIL_OR_USERNAME,<EOL>ignore_existing=True<EOL>)<EOL><DEDENT>email = email_or_username<EOL><DEDENT>else:<EOL><INDENT>validate_email_to_link(<EOL>email,<EOL>email_or_username,<EOL>ValidationMessages.INVALID_EMAIL_OR_USERNAME,<EOL>ignore_existing=True<EOL>)<EOL><DEDENT>return email<EOL>

Clean email form field

Returns:
    str: the cleaned value, converted to an email address (or an empty string)


Clean enterprise channel worker user form field

Returns:
    str: the cleaned value of channel user username for transmitting courses metadata.


<EOL>if hasattr(self.instance, '<STR_LIT>'):<EOL><INDENT>catalog_api = CourseCatalogApiClient(self.user, self.instance.site)<EOL><DEDENT>else:<EOL><INDENT>catalog_api = CourseCatalogApiClient(self.user)<EOL><DEDENT>catalogs = catalog_api.get_all_catalogs()<EOL>catalogs = sorted(catalogs, key=lambda catalog: catalog.get('<STR_LIT:name>', '<STR_LIT>').lower())<EOL>return BLANK_CHOICE_DASH + [<EOL>(catalog['<STR_LIT:id>'], catalog['<STR_LIT:name>'],)<EOL>for catalog in catalogs<EOL>]<EOL>

Retrieve a list of catalog ID and name pairs.

Once retrieved, these name pairs can be used directly as a value
for the `choices` argument to a ChoiceField.


return instance.catalog is not None<EOL>

Return True if EnterpriseCustomer has catalog id with a link to catalog details page.

Arguments:
    instance (enterprise.models.EnterpriseCustomer): `EnterpriseCustomer` model instance


def has_delete_permission(self, request, obj=None):

return False<EOL>


enrollment_client = EnrollmentApiClient()<EOL>enrolled_courses = enrollment_client.get_enrolled_courses(enterprise_customer_user.username)<EOL>course_details = []<EOL>courses_client = CourseApiClient()<EOL>for course in enrolled_courses:<EOL><INDENT>course_id = course['<STR_LIT>']['<STR_LIT>']<EOL>name = courses_client.get_course_details(course_id)['<STR_LIT:name>']<EOL>course_details.append({'<STR_LIT>': course_id, '<STR_LIT>': name})<EOL><DEDENT>template = '<STR_LIT>'<EOL>joiner = '<STR_LIT>'<EOL>return joiner.join(<EOL>template.format(<EOL>url=reverse('<STR_LIT>', args=[course['<STR_LIT>']]),<EOL>course_name=course['<STR_LIT>'],<EOL>)<EOL>for course in course_details<EOL>)<EOL>

Get an HTML string representing the courses the user is enrolled in.


return format_html('<STR_LIT>'.format(uuid=obj.uuid))<EOL>


if not instance.entitlement_id:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>return format_html(<EOL>'<STR_LIT>',<EOL>base_url=settings.ECOMMERCE_PUBLIC_URL_ROOT, id=instance.entitlement_id<EOL>)<EOL>

Instance is EnterpriseCustomer. Return e-commerce coupon urls.


def get_form(self, request, obj=None, **kwargs):

form = super(EnterpriseCustomerAdmin, self).get_form(request, obj, **kwargs)<EOL>form.user = request.user<EOL>return form<EOL>

Retrieve the appropriate form to use, saving the request user
into the form for use in loading catalog details


courses_string = mark_safe(self.get_enrolled_course_string(enterprise_customer_user))<EOL>return courses_string or '<STR_LIT:None>'<EOL>

Return a string representing the courses a given EnterpriseCustomerUser is enrolled in

Args:
    enterprise_customer_user: The instance of EnterpriseCustomerUser
        being rendered with this admin form.


return False<EOL>

Disable add permission for PendingEnrollment.


def get_readonly_fields(self, request, obj=None):

readonly_fields = super(EnterpriseCustomerUserAdmin, self).get_readonly_fields(request, obj=obj)<EOL>if obj:  <EOL><INDENT>return readonly_fields + tuple(get_all_field_names(self.model))<EOL><DEDENT>return readonly_fields<EOL>

Make all fields readonly when editing existing model.


def manage_learners(self, request, obj):

<EOL>manage_learners_url = reverse("<STR_LIT>" + UrlNames.MANAGE_LEARNERS, args=(obj.uuid,))<EOL>return HttpResponseRedirect(manage_learners_url)<EOL>

Object tool handler method - redirects to "Manage Learners" view


def paginated_list(object_list, page, page_size=<NUM_LIT>):

paginator = CustomPaginator(object_list, page_size)<EOL>try:<EOL><INDENT>object_list = paginator.page(page)<EOL><DEDENT>except PageNotAnInteger:<EOL><INDENT>object_list = paginator.page(<NUM_LIT:1>)<EOL><DEDENT>except EmptyPage:<EOL><INDENT>object_list = paginator.page(paginator.num_pages)<EOL><DEDENT>page_range = []<EOL>page_num = object_list.number<EOL>if paginator.num_pages <= <NUM_LIT:10>:<EOL><INDENT>page_range = range(paginator.num_pages)<EOL><DEDENT>else:<EOL><INDENT>if page_num > (PAGES_ON_EACH_SIDE + PAGES_ON_ENDS + <NUM_LIT:1>):<EOL><INDENT>page_range.extend(range(<NUM_LIT:1>, PAGES_ON_ENDS + <NUM_LIT:1>))<EOL>page_range.append(DOT)<EOL>page_range.extend(range(page_num - PAGES_ON_EACH_SIDE, page_num + <NUM_LIT:1>))<EOL><DEDENT>else:<EOL><INDENT>page_range.extend(range(<NUM_LIT:1>, page_num + <NUM_LIT:1>))<EOL><DEDENT>if page_num < (paginator.num_pages - PAGES_ON_EACH_SIDE - PAGES_ON_ENDS):<EOL><INDENT>page_range.extend(range(page_num + <NUM_LIT:1>, page_num + PAGES_ON_EACH_SIDE + <NUM_LIT:1>))<EOL>page_range.append(DOT)<EOL>page_range.extend(range(paginator.num_pages + <NUM_LIT:1> - PAGES_ON_ENDS, paginator.num_pages + <NUM_LIT:1>))<EOL><DEDENT>else:<EOL><INDENT>page_range.extend(range(page_num + <NUM_LIT:1>, paginator.num_pages + <NUM_LIT:1>))<EOL><DEDENT>object_list.paginator.page_range = page_range<EOL><DEDENT>return object_list<EOL>

Returns paginated list.

Arguments:
    object_list (QuerySet): A list of records to be paginated.
    page (int): Current page number.
    page_size (int): Number of records displayed in each paginated set.
    show_all (bool): Whether to show all records.

Adopted from django/contrib/admin/templatetags/admin_list.py
https://github.com/django/django/blob/1.11.1/django/contrib/admin/templatetags/admin_list.py#L50


def validate_email_to_link(email, raw_email=None, message_template=None, ignore_existing=False):

raw_email = raw_email if raw_email is not None else email<EOL>message_template = message_template if message_template is not None else ValidationMessages.INVALID_EMAIL<EOL>try:<EOL><INDENT>validate_email(email)<EOL><DEDENT>except ValidationError:<EOL><INDENT>raise ValidationError(message_template.format(argument=raw_email))<EOL><DEDENT>existing_record = EnterpriseCustomerUser.objects.get_link_by_email(email)<EOL>if existing_record and not ignore_existing:<EOL><INDENT>raise ValidationError(ValidationMessages.USER_ALREADY_REGISTERED.format(<EOL>email=email, ec_name=existing_record.enterprise_customer.name<EOL>))<EOL><DEDENT>return existing_record or False<EOL>

Validate email to be linked to Enterprise Customer.

Performs two checks:
    * Checks that email is valid
    * Checks that it is not already linked to any Enterprise Customer

Arguments:
    email (str): user email to link
    raw_email (str): raw value as it was passed by user - used in error message.
    message_template (str): Validation error template string.
    ignore_existing (bool): If True to skip the check for an existing Enterprise Customer

Raises:
    ValidationError: if email is invalid or already linked to Enterprise Customer.

Returns:
    bool: Whether or not there is an existing record with the same email address.


try:<EOL><INDENT>user = User.objects.get(username=email_or_username)<EOL>return user.email<EOL><DEDENT>except User.DoesNotExist:<EOL><INDENT>return email_or_username<EOL><DEDENT>

Convert email_or_username to email.

Returns:
    str: If `email_or_username` was a username returns user's email, otherwise assumes it was an email and returns
         as is.


def export_as_csv_action(description="<STR_LIT>", fields=None, header=True):

<EOL>def export_as_csv(modeladmin, request, queryset):  <EOL><INDENT>"""<STR_LIT>"""<EOL>opts = modeladmin.model._meta<EOL>if not fields:<EOL><INDENT>field_names = [field.name for field in opts.fields]<EOL><DEDENT>else:<EOL><INDENT>field_names = fields<EOL><DEDENT>response = HttpResponse(content_type="<STR_LIT>")<EOL>response["<STR_LIT>"] = "<STR_LIT>".format(<EOL>filename=str(opts).replace("<STR_LIT:.>", "<STR_LIT:_>")<EOL>)<EOL>writer = unicodecsv.writer(response, encoding="<STR_LIT:utf-8>")<EOL>if header:<EOL><INDENT>writer.writerow(field_names)<EOL><DEDENT>for obj in queryset:<EOL><INDENT>row = []<EOL>for field_name in field_names:<EOL><INDENT>field = getattr(obj, field_name)<EOL>if callable(field):<EOL><INDENT>value = field()<EOL><DEDENT>else:<EOL><INDENT>value = field<EOL><DEDENT>if value is None:<EOL><INDENT>row.append("<STR_LIT>")<EOL><DEDENT>elif not value and isinstance(value, string_types):<EOL><INDENT>row.append("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>row.append(value)<EOL><DEDENT><DEDENT>writer.writerow(row)<EOL><DEDENT>return response<EOL><DEDENT>export_as_csv.short_description = description<EOL>return export_as_csv<EOL>

Return an export csv action.

Arguments:
    description (string): action description
    fields ([string]): list of model fields to include
    header (bool): whether or not to output the column names as the first row


self._page_range = value<EOL>

We have introduced a setter method here, so as to set value for page_range property.
This was not present in Paginator class.


return apps.get_app_config("<STR_LIT>").get_model("<STR_LIT>")<EOL>

Return User model for django.contrib.auth.


from enterprise.signals import handle_user_post_save<EOL>from django.db.models.signals import pre_migrate, post_save<EOL>post_save.connect(handle_user_post_save, sender=self.auth_user_model, dispatch_uid=USER_POST_SAVE_DISPATCH_UID)<EOL>pre_migrate.connect(self._disconnect_user_post_save_for_migrations)<EOL>

Perform other one-time initialization steps.


return not waffle.switch_is_active(ENTERPRISE_ROLE_BASED_ACCESS_CONTROL_SWITCH)<EOL>

Temporary check for rbac based permissions being enabled.


request = get_request_or_stub()<EOL>decoded_jwt = get_decoded_jwt_from_request(request)<EOL>return request_user_has_implicit_access_via_jwt(decoded_jwt, ENTERPRISE_DASHBOARD_ADMIN_ROLE)<EOL>

Check that if request user has implicit access to `ENTERPRISE_DASHBOARD_ADMIN_ROLE` feature role.

Returns:
    boolean: whether the request user has access or not


return user_has_access_via_database(<EOL>user,<EOL>ENTERPRISE_DASHBOARD_ADMIN_ROLE,<EOL>EnterpriseFeatureUserRoleAssignment<EOL>)<EOL>

Check that if request user has explicit access to `ENTERPRISE_DASHBOARD_ADMIN_ROLE` feature role.

Returns:
    boolean: whether the request user has access or not


return user_has_access_via_database(<EOL>user,<EOL>ENTERPRISE_CATALOG_ADMIN_ROLE,<EOL>EnterpriseFeatureUserRoleAssignment,<EOL>obj<EOL>)<EOL>

Check that if request user has explicit access to `ENTERPRISE_CATALOG_ADMIN_ROLE` feature role.

Returns:
    boolean: whether the request user has access or not


return user_has_access_via_database(<EOL>user,<EOL>ENTERPRISE_ENROLLMENT_API_ADMIN_ROLE,<EOL>EnterpriseFeatureUserRoleAssignment,<EOL>obj<EOL>)<EOL>

Check that if request user has explicit access to `ENTERPRISE_ENROLLMENT_API_ADMIN_ROLE` feature role.

Returns:
    boolean: whether the request user has access or not


def update_enterprise_courses(self, enterprise_customer, course_container_key='<STR_LIT>', **kwargs):

enterprise_context = {<EOL>'<STR_LIT>': enterprise_customer and enterprise_customer.identity_provider,<EOL>'<STR_LIT>': enterprise_customer and str(enterprise_customer.uuid),<EOL>}<EOL>enterprise_context.update(**kwargs)<EOL>courses = []<EOL>for course in self.data[course_container_key]:<EOL><INDENT>courses.append(<EOL>self.update_course(course, enterprise_customer, enterprise_context)<EOL>)<EOL><DEDENT>self.data[course_container_key] = courses<EOL>

This method adds enterprise-specific metadata for each course.

We are adding following field in all the courses.
    tpa_hint: a string for identifying Identity Provider.
    enterprise_id: the UUID of the enterprise
    **kwargs: any additional data one would like to add on a per-use basis.

Arguments:
    enterprise_customer: The customer whose data will be used to fill the enterprise context.
    course_container_key: The key used to find the container for courses in the serializer's data dictionary.


def update(self, instance, validated_data):

pass<EOL>

Do not perform any operations for state changing requests.


try:<EOL><INDENT>self.user = User.objects.get(username=value)<EOL><DEDENT>except User.DoesNotExist:<EOL><INDENT>raise serializers.ValidationError("<STR_LIT>")<EOL><DEDENT>return value<EOL>

Verify that the username has a matching user.


return [<EOL>self.child.to_representation(item) if '<STR_LIT>' in item else item for item in data<EOL>]<EOL>

This selectively calls to_representation on each result that was processed by create.


enterprise_customer = self.validated_data['<STR_LIT>']<EOL>ecu = models.EnterpriseCustomerUser(<EOL>user_id=self.user.pk,<EOL>enterprise_customer=enterprise_customer,<EOL>)<EOL>ecu.save()<EOL>


enterprise_customer = self.context.get('<STR_LIT>')<EOL>if not enterprise_customer.catalog_contains_course(value):<EOL><INDENT>raise serializers.ValidationError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'.format(<EOL>course_run_id=value,<EOL>enterprise_customer=enterprise_customer.name,<EOL>)<EOL>)<EOL><DEDENT>return value<EOL>

Validates that the course run id is part of the Enterprise Customer's catalog.


updated_course = copy.deepcopy(instance)<EOL>enterprise_customer_catalog = self.context['<STR_LIT>']<EOL>updated_course['<STR_LIT>'] = enterprise_customer_catalog.get_course_enrollment_url(<EOL>updated_course['<STR_LIT:key>']<EOL>)<EOL>for course_run in updated_course['<STR_LIT>']:<EOL><INDENT>course_run['<STR_LIT>'] = enterprise_customer_catalog.get_course_run_enrollment_url(<EOL>course_run['<STR_LIT:key>']<EOL>)<EOL><DEDENT>return updated_course<EOL>

Return the updated course data dictionary.

Arguments:
    instance (dict): The course data.

Returns:
    dict: The updated course data.


pass<EOL>


enterprise_customer = self.context.get('<STR_LIT>')<EOL>try:<EOL><INDENT>user = User.objects.get(email=value)<EOL>return models.EnterpriseCustomerUser.objects.get(<EOL>user_id=user.id,<EOL>enterprise_customer=enterprise_customer<EOL>)<EOL><DEDENT>except (models.EnterpriseCustomerUser.DoesNotExist, User.DoesNotExist):<EOL><INDENT>pass<EOL><DEDENT>return value<EOL>

Validates the user_email, if given, to see if an existing EnterpriseCustomerUser exists for it.

If it does not, it does not fail validation, unlike for the other field validation methods above.


lms_user_id = data.get('<STR_LIT>')<EOL>tpa_user_id = data.get('<STR_LIT>')<EOL>user_email = data.get('<STR_LIT>')<EOL>if not lms_user_id and not tpa_user_id and not user_email:<EOL><INDENT>raise serializers.ValidationError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>)<EOL><DEDENT>return data<EOL>

Validate that at least one of the user identifier fields has been passed in.


return [record.serialize() for record in obj.data_sharing_consent_records]<EOL>

Return serialization of EnterpriseCustomerUser.data_sharing_consent_records property.

Arguments:
    EnterpriseCustomerUser: The EnterpriseCustomerUser.

Returns:
    list of dict: The serialized DataSharingConsent records associated with the EnterpriseCustomerUser.


try:<EOL><INDENT>user = User.objects.get(username=value)<EOL><DEDENT>except User.DoesNotExist:<EOL><INDENT>raise serializers.ValidationError("<STR_LIT>")<EOL><DEDENT>try:<EOL><INDENT>enterprise_customer_user = models.EnterpriseCustomerUser.objects.get(user_id=user.pk)<EOL><DEDENT>except models.EnterpriseCustomerUser.DoesNotExist:<EOL><INDENT>raise serializers.ValidationError("<STR_LIT>")<EOL><DEDENT>self.enterprise_customer_user = enterprise_customer_user<EOL>return value<EOL>

Verify that the username has a matching user, and that the user has an associated EnterpriseCustomerUser.


request = self.context['<STR_LIT>']<EOL>enterprise_customer = instance.enterprise_customer<EOL>representation = super(EnterpriseCustomerCatalogDetailSerializer, self).to_representation(instance)<EOL>paginated_content = instance.get_paginated_content(request.GET)<EOL>count = paginated_content['<STR_LIT:count>']<EOL>search_results = paginated_content['<STR_LIT>']<EOL>for item in search_results:<EOL><INDENT>content_type = item['<STR_LIT>']<EOL>marketing_url = item.get('<STR_LIT>')<EOL>if marketing_url:<EOL><INDENT>item['<STR_LIT>'] = utils.update_query_parameters(<EOL>marketing_url, utils.get_enterprise_utm_context(enterprise_customer)<EOL>)<EOL><DEDENT>if content_type == '<STR_LIT>':<EOL><INDENT>item['<STR_LIT>'] = instance.get_course_enrollment_url(item['<STR_LIT:key>'])<EOL><DEDENT>if content_type == '<STR_LIT>':<EOL><INDENT>item['<STR_LIT>'] = instance.get_course_run_enrollment_url(item['<STR_LIT:key>'])<EOL><DEDENT>if content_type == '<STR_LIT>':<EOL><INDENT>item['<STR_LIT>'] = instance.get_program_enrollment_url(item['<STR_LIT>'])<EOL><DEDENT><DEDENT>previous_url = None<EOL>next_url = None<EOL>page = int(request.GET.get('<STR_LIT>', '<STR_LIT:1>'))<EOL>request_uri = request.build_absolute_uri()<EOL>if paginated_content['<STR_LIT>']:<EOL><INDENT>previous_url = utils.update_query_parameters(request_uri, {'<STR_LIT>': page - <NUM_LIT:1>})<EOL><DEDENT>if paginated_content['<STR_LIT>']:<EOL><INDENT>next_url = utils.update_query_parameters(request_uri, {'<STR_LIT>': page + <NUM_LIT:1>})<EOL><DEDENT>representation['<STR_LIT:count>'] = count<EOL>representation['<STR_LIT>'] = previous_url<EOL>representation['<STR_LIT>'] = next_url<EOL>representation['<STR_LIT>'] = search_results<EOL>return representation<EOL>

Serialize the EnterpriseCustomerCatalog object.

Arguments:
    instance (EnterpriseCustomerCatalog): The EnterpriseCustomerCatalog to serialize.

Returns:
    dict: The EnterpriseCustomerCatalog converted to a dict.


self.queryset = self.queryset.order_by('<STR_LIT:name>')<EOL>enterprise_id = self.request.query_params.get('<STR_LIT>', None)<EOL>enterprise_slug = self.request.query_params.get('<STR_LIT>', None)<EOL>enterprise_name = self.request.query_params.get('<STR_LIT>', None)<EOL>if enterprise_id is not None:<EOL><INDENT>self.queryset = self.queryset.filter(uuid=enterprise_id)<EOL><DEDENT>elif enterprise_slug is not None:<EOL><INDENT>self.queryset = self.queryset.filter(slug=enterprise_slug)<EOL><DEDENT>elif enterprise_name is not None:<EOL><INDENT>self.queryset = self.queryset.filter(name__icontains=enterprise_name)<EOL><DEDENT>return self.list(request, *args, **kwargs)<EOL>

Returns the list of enterprise customers the user has a specified group permission access to.


@method_decorator(enterprise_customer_required)<EOL><INDENT>@detail_route()<EOL>def courses(self, request, enterprise_customer, pk=None):  <DEDENT>

catalog_api = CourseCatalogApiClient(request.user, enterprise_customer.site)<EOL>courses = catalog_api.get_paginated_catalog_courses(pk, request.GET)<EOL>self.ensure_data_exists(<EOL>request,<EOL>courses,<EOL>error_message=(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(endpoint=request.get_full_path())<EOL>)<EOL>)<EOL>serializer = serializers.EnterpriseCatalogCoursesReadOnlySerializer(courses)<EOL>serializer.update_enterprise_courses(enterprise_customer, catalog_id=pk)<EOL>return get_paginated_response(serializer.data, request)<EOL>

Retrieve the list of courses contained within this catalog.

Only courses with active course runs are returned. A course run is considered active if it is currently
open for enrollment, or will open in the future.


try:<EOL><INDENT>email, enterprise_name, number_of_codes = self.get_required_query_params(request)<EOL><DEDENT>except CodesAPIRequestError as invalid_request:<EOL><INDENT>return Response({'<STR_LIT:error>': str(invalid_request)}, status=HTTP_400_BAD_REQUEST)<EOL><DEDENT>subject_line = _('<STR_LIT>').format(<EOL>token_enterprise_name=enterprise_name<EOL>)<EOL>msg_with_codes = _('<STR_LIT>'<EOL>'<STR_LIT>').format(<EOL>token_email=email,<EOL>token_enterprise_name=enterprise_name,<EOL>token_number_codes=number_of_codes)<EOL>msg_without_codes = _('<STR_LIT>'<EOL>'<STR_LIT>').format(<EOL>token_email=email,<EOL>token_enterprise_name=enterprise_name)<EOL>app_config = apps.get_app_config("<STR_LIT>")<EOL>from_email_address = app_config.customer_success_email<EOL>cs_email = app_config.customer_success_email<EOL>data = {<EOL>self.REQUIRED_PARAM_EMAIL: email,<EOL>self.REQUIRED_PARAM_ENTERPRISE_NAME: enterprise_name,<EOL>self.OPTIONAL_PARAM_NUMBER_OF_CODES: number_of_codes,<EOL>}<EOL>try:<EOL><INDENT>mail.send_mail(<EOL>subject_line,<EOL>msg_with_codes if number_of_codes else msg_without_codes,<EOL>from_email_address,<EOL>[cs_email],<EOL>fail_silently=False<EOL>)<EOL>return Response(data, status=HTTP_200_OK)<EOL><DEDENT>except SMTPException:<EOL><INDENT>error_message = _(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>).format(<EOL>token_cs_email=cs_email,<EOL>token_email=email,<EOL>token_enterprise_name=enterprise_name<EOL>)<EOL>LOGGER.error(error_message)<EOL>return Response(<EOL>{'<STR_LIT:error>': str('<STR_LIT>')},<EOL>status=HTTP_500_INTERNAL_SERVER_ERROR<EOL>)<EOL><DEDENT>

POST /enterprise/api/v1/request_codes

Requires a JSON object of the following format:
>>> {
>>>     "email": "bob@alice.com",
>>>     "enterprise_name": "IBM",
>>>     "number_of_codes": "50"
>>> }

Keys:
*email*
    Email of the customer who has requested more codes.
*enterprise_name*
    The name of the enterprise requesting more codes.
*number_of_codes*
    The number of codes requested.


if self.request.method in ('<STR_LIT:GET>', ):<EOL><INDENT>return serializers.EnterpriseCourseEnrollmentReadOnlySerializer<EOL><DEDENT>return serializers.EnterpriseCourseEnrollmentWriteSerializer<EOL>

Use a special serializer for any requests that aren't read-only.


def ensure_data_exists(self, request, data, error_message=None):

if not data:<EOL><INDENT>error_message = (<EOL>error_message or "<STR_LIT>".format(request.get_full_path())<EOL>)<EOL>LOGGER.error(error_message)<EOL>raise NotFound(error_message)<EOL><DEDENT>

Ensure that the wrapped API client's response brings us valid data. If not, raise an error and log it.


@detail_route(url_path='<STR_LIT>'.format(COURSE_KEY_URL_PATTERN))<EOL><INDENT>@permission_required(<EOL>'<STR_LIT>',<EOL>fn=lambda request, pk, course_key: get_enterprise_customer_from_catalog_id(pk))<EOL>def course_detail(self, request, pk, course_key):  <DEDENT>

enterprise_customer_catalog = self.get_object()<EOL>course = enterprise_customer_catalog.get_course(course_key)<EOL>if not course:<EOL><INDENT>raise Http404<EOL><DEDENT>context = self.get_serializer_context()<EOL>context['<STR_LIT>'] = enterprise_customer_catalog<EOL>serializer = serializers.CourseDetailSerializer(course, context=context)<EOL>return Response(serializer.data)<EOL>

Return the metadata for the specified course.

The course needs to be included in the specified EnterpriseCustomerCatalog
in order for metadata to be returned from this endpoint.


@list_route()<EOL><INDENT>@permission_required('<STR_LIT>')<EOL>def dashboard_list(self, request, *args, **kwargs):  <DEDENT>

Supports listing dashboard enterprises for edx-portal frontend.


@detail_route()<EOL><INDENT>def entitlements(self, request, pk=None):  <DEDENT>

enterprise_customer_user = self.get_object()<EOL>instance = {"<STR_LIT>": enterprise_customer_user.entitlements}<EOL>serializer = serializers.EnterpriseCustomerUserEntitlementSerializer(instance, context={'<STR_LIT>': request})<EOL>return Response(serializer.data)<EOL>

Retrieve the list of entitlements available to this learner.

Only those entitlements are returned that satisfy enterprise customer's data sharing setting.

Arguments:
    request (HttpRequest): Reference to in-progress request instance.
    pk (Int): Primary key value of the selected enterprise learner.

Returns:
    (HttpResponse): Response object containing a list of learner's entitlements.


catalog_api = CourseCatalogApiClient(request.user)<EOL>catalogs = catalog_api.get_paginated_catalogs(request.GET)<EOL>self.ensure_data_exists(request, catalogs)<EOL>serializer = serializers.ResponsePaginationSerializer(catalogs)<EOL>return get_paginated_response(serializer.data, request)<EOL>

DRF view to list all catalogs.

Arguments:
    request (HttpRequest): Current request

Returns:
    (Response): DRF response object containing course catalogs.


email = get_request_value(request, self.REQUIRED_PARAM_EMAIL, '<STR_LIT>')<EOL>enterprise_name = get_request_value(request, self.REQUIRED_PARAM_ENTERPRISE_NAME, '<STR_LIT>')<EOL>number_of_codes = get_request_value(request, self.OPTIONAL_PARAM_NUMBER_OF_CODES, '<STR_LIT>')<EOL>if not (email and enterprise_name):<EOL><INDENT>raise CodesAPIRequestError(<EOL>self.get_missing_params_message([<EOL>(self.REQUIRED_PARAM_EMAIL, bool(email)),<EOL>(self.REQUIRED_PARAM_ENTERPRISE_NAME, bool(enterprise_name)),<EOL>])<EOL>)<EOL><DEDENT>return email, enterprise_name, number_of_codes<EOL>

Gets ``email``, ``enterprise_name``, and ``number_of_codes``,
which are the relevant parameters for this API endpoint.

:param request: The request to this endpoint.
:return: The ``email``, ``enterprise_name``, and ``number_of_codes`` from the request.


@detail_route()<EOL><INDENT>@permission_required('<STR_LIT>', fn=lambda request, pk: pk)<EOL>def courses(self, request, pk=None):  <DEDENT>

Retrieve the list of courses contained within the catalog linked to this enterprise.

Only courses with active course runs are returned. A course run is considered active if it is currently
open for enrollment, or will open in the future.


@method_decorator(require_at_least_one_query_parameter('<STR_LIT>', '<STR_LIT>'))<EOL><INDENT>@detail_route()<EOL>def contains_content_items(self, request, pk, course_run_ids, program_uuids):<DEDENT>

enterprise_customer_catalog = self.get_object()<EOL>course_run_ids = [unquote(quote_plus(course_run_id)) for course_run_id in course_run_ids]<EOL>contains_content_items = True<EOL>if course_run_ids:<EOL><INDENT>contains_content_items = enterprise_customer_catalog.contains_courses(course_run_ids)<EOL><DEDENT>if program_uuids:<EOL><INDENT>contains_content_items = (<EOL>contains_content_items and<EOL>enterprise_customer_catalog.contains_programs(program_uuids)<EOL>)<EOL><DEDENT>return Response({'<STR_LIT>': contains_content_items})<EOL>

Return whether or not the EnterpriseCustomerCatalog contains the specified content.

Multiple course_run_ids and/or program_uuids query parameters can be sent to this view to check
for their existence in the EnterpriseCustomerCatalog. At least one course run key
or program UUID value must be included in the request.


@detail_route(methods=['<STR_LIT>'], permission_classes=[<EOL>permissions.IsAuthenticated,<EOL>HasEnterpriseEnrollmentAPIAccess,<EOL>])<EOL><INDENT>@permission_required('<STR_LIT>', fn=lambda request, pk: pk)<EOL>def course_enrollments(self, request, pk):<DEDENT>

enterprise_customer = self.get_object()<EOL>serializer = serializers.EnterpriseCustomerCourseEnrollmentsSerializer(<EOL>data=request.data,<EOL>many=True,<EOL>context={<EOL>'<STR_LIT>': enterprise_customer,<EOL>'<STR_LIT>': request.user,<EOL>}<EOL>)<EOL>if serializer.is_valid():<EOL><INDENT>serializer.save()<EOL>return Response(serializer.data, status=HTTP_200_OK)<EOL><DEDENT>return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)<EOL>

Creates a course enrollment for an EnterpriseCustomerUser.


@wraps(view)<EOL>def wrapper(request, *args, **kwargs):<EOL><INDENT>"""<STR_LIT>"""<EOL>user = request.user<EOL>enterprise_customer = get_enterprise_customer_for_user(user)<EOL>if enterprise_customer:<EOL><INDENT>args = args + (enterprise_customer,)<EOL>return view(request, *args, **kwargs)<EOL><DEDENT>else:<EOL><INDENT>raise PermissionDenied(<EOL>'<STR_LIT>'.format(<EOL>username=user.username<EOL>)<EOL>)<EOL><DEDENT><DEDENT>return wrapper<EOL>

Ensure the user making the API request is associated with an EnterpriseCustomer.

This decorator attempts to find an EnterpriseCustomer associated with the requesting
user and passes that EnterpriseCustomer to the view as a parameter. It will return a
PermissionDenied error if an EnterpriseCustomer cannot be found.

Usage::
    @enterprise_customer_required()
    def my_view(request, enterprise_customer):
        # Some functionality ...

    OR

    class MyView(View):
        ...
        @method_decorator(enterprise_customer_required)
        def get(self, request, enterprise_customer):
            # Some functionality ...


def outer_wrapper(view):<EOL><INDENT>"""<STR_LIT>"""<EOL>@wraps(view)<EOL>def wrapper(request, *args, **kwargs):<EOL><INDENT>"""<STR_LIT>"""<EOL>requirement_satisfied = False<EOL>for query_parameter_name in query_parameter_names:<EOL><INDENT>query_parameter_values = request.query_params.getlist(query_parameter_name)<EOL>kwargs[query_parameter_name] = query_parameter_values<EOL>if query_parameter_values:<EOL><INDENT>requirement_satisfied = True<EOL><DEDENT><DEDENT>if not requirement_satisfied:<EOL><INDENT>raise ValidationError(<EOL>detail='<STR_LIT>'.format(<EOL>params='<STR_LIT:U+002CU+0020>'.join(query_parameter_names)<EOL>)<EOL>)<EOL><DEDENT>return view(request, *args, **kwargs)<EOL><DEDENT>return wrapper<EOL><DEDENT>return outer_wrapper<EOL>

Ensure at least one of the specified query parameters are included in the request.

This decorator checks for the existence of at least one of the specified query
parameters and passes the values as function parameters to the decorated view.
If none of the specified query parameters are included in the request, a
ValidationError is raised.

Usage::
    @require_at_least_one_query_parameter('program_uuids', 'course_run_ids')
    def my_view(request, program_uuids, course_run_ids):
        # Some functionality ...


self.ALLOWED_API_GROUPS = [u'<STR_LIT>', ]<EOL>

Initialize the class with a API_ALLOWED_GROUPS


url = urlparse(request.build_absolute_uri())._replace(query=None).geturl()<EOL>next_page = None<EOL>previous_page = None<EOL>if data['<STR_LIT>']:<EOL><INDENT>next_page = "<STR_LIT>".format(<EOL>base_url=url,<EOL>query_parameters=urlparse(data['<STR_LIT>']).query,<EOL>)<EOL>next_page = next_page.rstrip('<STR_LIT:?>')<EOL><DEDENT>if data['<STR_LIT>']:<EOL><INDENT>previous_page = "<STR_LIT>".format(<EOL>base_url=url,<EOL>query_parameters=urlparse(data['<STR_LIT>'] or "<STR_LIT>").query,<EOL>)<EOL>previous_page = previous_page.rstrip('<STR_LIT:?>')<EOL><DEDENT>return Response(OrderedDict([<EOL>('<STR_LIT:count>', data['<STR_LIT:count>']),<EOL>('<STR_LIT>', next_page),<EOL>('<STR_LIT>', previous_page),<EOL>('<STR_LIT>', data['<STR_LIT>'])<EOL>]))<EOL>

Update pagination links in course catalog data and return DRF Response.

Arguments:
    data (dict): Dictionary containing catalog courses.
    request (HttpRequest): Current request object.

Returns:
    (Response): DRF response object containing pagination links.


Get the enterprise customer id given an enterprise customer catalog id.


def _get_enterprise_catalog_admin_users_batch(self, start, end):

Application = apps.get_model(OAUTH2_PROVIDER_APPLICATION_MODEL)     <EOL>LOGGER.info('<STR_LIT>', start, end)<EOL>catalog_admin_user_ids = Application.objects.filter(<EOL>user_id__in=self._get_enterprise_customer_user_ids()<EOL>).exclude(name=EDX_ORG_NAME).values('<STR_LIT>')<EOL>return User.objects.filter(pk__in=catalog_admin_user_ids)[start:end]<EOL>

Returns a batched queryset of User objects.


def _get_enterprise_admin_users_batch(self, start, end):

LOGGER.info('<STR_LIT>', start, end)<EOL>return User.objects.filter(groups__name=ENTERPRISE_DATA_API_ACCESS_GROUP, is_staff=False)[start:end]<EOL>


def _assign_enterprise_role_to_users(self, _get_batch_method, options, is_feature_role=False):

role_name = options['<STR_LIT>']<EOL>batch_limit = options['<STR_LIT>']<EOL>batch_sleep = options['<STR_LIT>']<EOL>batch_offset = options['<STR_LIT>']<EOL>current_batch_index = batch_offset<EOL>users_batch = _get_batch_method(<EOL>batch_offset,<EOL>batch_offset + batch_limit<EOL>)<EOL>role_class = SystemWideEnterpriseRole<EOL>role_assignment_class = SystemWideEnterpriseUserRoleAssignment<EOL>if is_feature_role:<EOL><INDENT>role_class = EnterpriseFeatureRole<EOL>role_assignment_class = EnterpriseFeatureUserRoleAssignment<EOL><DEDENT>enterprise_role = role_class.objects.get(name=role_name)<EOL>while users_batch.count() > <NUM_LIT:0>:<EOL><INDENT>for index, user in enumerate(users_batch):<EOL><INDENT>LOGGER.info(<EOL>'<STR_LIT>',<EOL>current_batch_index + index, user.id<EOL>)<EOL>role_assignment_class.objects.get_or_create(<EOL>user=user,<EOL>role=enterprise_role<EOL>)<EOL><DEDENT>sleep(batch_sleep)<EOL>current_batch_index += len(users_batch)<EOL>users_batch = _get_batch_method(<EOL>current_batch_index,<EOL>current_batch_index + batch_limit<EOL>)<EOL><DEDENT>


def _get_enterprise_customer_users_batch(self, start, end):

LOGGER.info('<STR_LIT>', start, end)<EOL>return User.objects.filter(pk__in=self._get_enterprise_customer_user_ids())[start:end]<EOL>

Returns a batched queryset of EnterpriseCustomerUser objects.


return EnterpriseCustomerUser.objects.values('<STR_LIT>')<EOL>


def _get_enterprise_enrollment_api_admin_users_batch(self, start, end):

LOGGER.info('<STR_LIT>', start, end)<EOL>return User.objects.filter(groups__name=ENTERPRISE_ENROLLMENT_API_ACCESS_GROUP, is_staff=False)[start:end]<EOL>


columns = [col[<NUM_LIT:0>] for col in cursor.description]<EOL>return [<EOL>dict(zip(columns, row))<EOL>for row in cursor.fetchall()<EOL>]<EOL>

Return all rows from a cursor as a dict.


query = '''<STR_LIT>'''<EOL>with connection.cursor() as cursor:<EOL><INDENT>if enterprise_customer_uuid:<EOL><INDENT>cursor.execute(<EOL>query.format(enterprise_customer_filter='<STR_LIT>'),<EOL>[enterprise_customer_uuid]<EOL>)<EOL><DEDENT>else:<EOL><INDENT>cursor.execute(<EOL>query.format(enterprise_customer_filter='<STR_LIT>')<EOL>)<EOL><DEDENT>return self._dictfetchall(cursor)<EOL><DEDENT>

Return enterprise customer UUID/user_id/course_run_id triples which represent CourseEnrollment records
which do not have a matching EnterpriseCourseEnrollment record.

The query used below looks for CourseEnrollment records that are associated with enterprise
learners where the enrollment data is after the creation of the link between the learner
and the enterprise. It also excludes learners with edx.org email addresses in order to
filter out test users.


try:<EOL><INDENT>return EnterpriseCustomer.objects.get(  <EOL>enterprise_customer_identity_provider__provider_id=sso_provider_id<EOL>)<EOL><DEDENT>except EnterpriseCustomer.DoesNotExist:<EOL><INDENT>return None<EOL><DEDENT>

Get the EnterpriseCustomer object tied to an identity provider.


user_social_auth = UserSocialAuth.objects.select_related('<STR_LIT:user>').filter(<EOL>user__username=tpa_username, provider=tpa_provider.backend_name<EOL>).first()<EOL>return user_social_auth.user if user_social_auth else None<EOL>

Find the LMS user from the LMS model `UserSocialAuth`.

Arguments:
    tpa_provider (third_party_auth.provider): third party auth provider object
    tpa_username (str): Username returned by the third party auth


try:<EOL><INDENT>from third_party_auth.provider import Registry   <EOL><DEDENT>except ImportError as exception:<EOL><INDENT>LOGGER.warning("<STR_LIT>")<EOL>LOGGER.warning(exception)<EOL>Registry = None  <EOL><DEDENT>first = [("<STR_LIT>", "<STR_LIT:->" * <NUM_LIT:7>)]<EOL>if Registry:<EOL><INDENT>return first + [(idp.provider_id, idp.name) for idp in Registry.enabled()]<EOL><DEDENT>return None<EOL>

Get a list of identity providers choices for enterprise customer.

Return:
    A list of choices of all identity providers, None if it can not get any available identity provider.


scheme, netloc, path, query_string, fragment = urlsplit(url)<EOL>url_params = parse_qs(query_string)<EOL>url_params.update(query_parameters)<EOL>return urlunsplit(<EOL>(scheme, netloc, path, urlencode(sorted(url_params.items()), doseq=True), fragment),<EOL>)<EOL>

Return url with updated query parameters.

Arguments:
    url (str): Original url whose query parameters need to be updated.
    query_parameters (dict): A dictionary containing query parameters to be added to course selection url.

Returns:
    (slug): slug identifier for the identity provider that can be used for identity verification of
        users associated the enterprise customer of the given user.


current_course_run = None<EOL>filtered_course_runs = []<EOL>all_course_runs = course['<STR_LIT>']<EOL>if users_active_course_runs:<EOL><INDENT>current_course_run = get_closest_course_run(users_active_course_runs)<EOL><DEDENT>else:<EOL><INDENT>for course_run in all_course_runs:<EOL><INDENT>if is_course_run_enrollable(course_run) and is_course_run_upgradeable(course_run):<EOL><INDENT>filtered_course_runs.append(course_run)<EOL><DEDENT><DEDENT>if not filtered_course_runs:<EOL><INDENT>filtered_course_runs = all_course_runs<EOL><DEDENT>if filtered_course_runs:<EOL><INDENT>current_course_run = get_closest_course_run(filtered_course_runs)<EOL><DEDENT><DEDENT>return current_course_run<EOL>

Return the current course run on the following conditions.

- If user has active course runs (already enrolled) then return course run with closest start date
Otherwise it will check the following logic:
- Course run is enrollable (see is_course_run_enrollable)
- Course run has a verified seat and the upgrade deadline has not expired.
- Course run start date is closer to now than any other enrollable/upgradeable course runs.
- If no enrollable/upgradeable course runs, return course run with most recent start date.


api_base_url = getattr(settings, "<STR_LIT>", "<STR_LIT>")<EOL>match = re.match(r"<STR_LIT>", api_base_url)<EOL>if not match:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>if mode == '<STR_LIT>':<EOL><INDENT>return match.group("<STR_LIT>").rstrip("<STR_LIT:/>") + "<STR_LIT>"<EOL><DEDENT>elif mode == '<STR_LIT>':<EOL><INDENT>return match.group("<STR_LIT>").rstrip("<STR_LIT:/>") + "<STR_LIT>"<EOL><DEDENT>

Get template of catalog admin url.

URL template will contain a placeholder '{catalog_id}' for catalog id.
Arguments:
    mode e.g. change/add.

Returns:
    A string containing template for catalog url.

Example:
    >>> get_catalog_admin_url_template('change')
    "http://localhost:18381/admin/catalogs/catalog/{catalog_id}/change/"


now = datetime.datetime.now(pytz.UTC)<EOL>end = parse_datetime_handle_invalid(course_run.get('<STR_LIT:end>'))<EOL>enrollment_start = parse_datetime_handle_invalid(course_run.get('<STR_LIT>'))<EOL>enrollment_end = parse_datetime_handle_invalid(course_run.get('<STR_LIT>'))<EOL>return (not end or end > now) and(not enrollment_start or enrollment_start < now) and(not enrollment_end or enrollment_end > now)<EOL>

Return true if the course run is enrollable, false otherwise.

We look for the following criteria:
- end is greater than now OR null
- enrollment_start is less than now OR null
- enrollment_end is greater than now OR null


key = '<STR_LIT>'.join(['<STR_LIT>'.format(item, value) for item, value in iteritems(kwargs)])<EOL>return hashlib.md5(key.encode('<STR_LIT:utf-8>')).hexdigest()<EOL>

Get MD5 encoded cache key for given arguments.

Here is the format of key before MD5 encryption.
    key1:value1__key2:value2 ...

Example:
    >>> get_cache_key(site_domain="example.com", resource="enterprise")
    # Here is key format for above call
    # "site_domain:example.com__resource:enterprise"
    a54349175618ff1659dee0978e3149ca

Arguments:
    **kwargs: Key word arguments that need to be present in cache key.

Returns:
     An MD5 encoded key uniquely identified by the key word arguments.


EnterpriseCustomerUser = apps.get_model('<STR_LIT>', '<STR_LIT>')  <EOL>try:<EOL><INDENT>return EnterpriseCustomerUser.objects.get(  <EOL>enterprise_customer__uuid=enterprise_uuid,<EOL>user_id=user_id<EOL>)<EOL><DEDENT>except EnterpriseCustomerUser.DoesNotExist:<EOL><INDENT>return None<EOL><DEDENT>

Return the object for EnterpriseCustomerUser.

Arguments:
    user_id (str): user identifier
    enterprise_uuid (UUID): Universally unique identifier for the enterprise customer.

Returns:
    (EnterpriseCustomerUser): enterprise customer user record


if len(course_runs) == <NUM_LIT:1>:<EOL><INDENT>return course_runs[<NUM_LIT:0>]<EOL><DEDENT>now = datetime.datetime.now(pytz.UTC)<EOL>never = now - datetime.timedelta(days=<NUM_LIT>)<EOL>return min(course_runs, key=lambda x: abs(get_course_run_start(x, never) - now))<EOL>

Return course run with start date closest to now.


return [f.name for f in model._meta.get_fields()]<EOL>

Return all fields' names from a model.

According to `Django documentation`_, ``get_all_field_names`` should become some monstrosity with chained
iterable ternary nested in a list comprehension. For now, a simpler version of iterating over fields and
getting their names work, but we might have to switch to full version in future.

.. _Django documentation: https://docs.djangoproject.com/en/1.8/ref/models/meta/


try:<EOL><INDENT>course_run_key = CourseKey.from_string(course_identifier)<EOL><DEDENT>except InvalidKeyError:<EOL><INDENT>return course_identifier<EOL><DEDENT>return quote_plus('<STR_LIT:U+0020>'.join([course_run_key.org, course_run_key.course]))<EOL>

Return the serialized course key given either a course run ID or course key.


<EOL>return text.replace('<STR_LIT>', '<STR_LIT>')<EOL>

Given html text that will be rendered as a variable in a template, strip out characters that impact rendering.

Arguments:
    text (str): The text to clean.

Returns:
    (str): The cleaned text.


EnterpriseCustomer = apps.get_model('<STR_LIT>', '<STR_LIT>')  <EOL>try:<EOL><INDENT>enterprise_uuid = UUID(enterprise_uuid)<EOL>return EnterpriseCustomer.objects.get(uuid=enterprise_uuid)  <EOL><DEDENT>except (TypeError, ValueError, EnterpriseCustomer.DoesNotExist):<EOL><INDENT>LOGGER.error('<STR_LIT>', enterprise_uuid)<EOL>raise Http404<EOL><DEDENT>

Given an EnterpriseCustomer UUID, return the corresponding EnterpriseCustomer or raise a 404.

Arguments:
    enterprise_uuid (str): The UUID (in string form) of the EnterpriseCustomer to fetch.

Returns:
    (EnterpriseCustomer): The EnterpriseCustomer given the UUID.


def __init__(self, programs_matched, *args, **kwargs):

super(MultipleProgramMatchError, self).__init__(*args, **kwargs)<EOL>self.programs_matched = programs_matched<EOL>

Initialize :class:`MultipleProgramMatchError`.

Arguments:
    programs_matched (int): number of programs matched where one  proram was expected.
    args (iterable): variable arguments
    kwargs (dict): keyword arguments


now = datetime.datetime.now(pytz.UTC)<EOL>for seat in course_run.get('<STR_LIT>', []):<EOL><INDENT>if seat.get('<STR_LIT:type>') == '<STR_LIT>':<EOL><INDENT>upgrade_deadline = parse_datetime_handle_invalid(seat.get('<STR_LIT>'))<EOL>return not upgrade_deadline or upgrade_deadline > now<EOL><DEDENT><DEDENT>return False<EOL>

Return true if the course run has a verified seat with an unexpired upgrade deadline, false otherwise.


def get_request_value(request, key, default=None):

if request.method in ['<STR_LIT:GET>', '<STR_LIT>']:<EOL><INDENT>return request.query_params.get(key, request.data.get(key, default))<EOL><DEDENT>return request.data.get(key, request.query_params.get(key, default))<EOL>

Get the value in the request, either through query parameters or posted data, from a key.

:param request: The request from which the value should be gotten.
:param key: The key to use to get the desired value.
:param default: The backup value to use in case the input key cannot help us get the value.
:return: The value we're looking for.


if content_metadata_item['<STR_LIT>'] == '<STR_LIT>':<EOL><INDENT>return content_metadata_item['<STR_LIT>']<EOL><DEDENT>return content_metadata_item['<STR_LIT:key>']<EOL>

Return the unique identifier given a content metadata item dictionary.


if text is None:<EOL><INDENT>return<EOL><DEDENT>if allowed_tags is None:<EOL><INDENT>allowed_tags = ALLOWED_TAGS<EOL><DEDENT>return bleach.clean(text, tags=allowed_tags, attributes=['<STR_LIT:id>', '<STR_LIT:class>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT:title>'], strip=True)<EOL>

Strip all tags from a string except those tags provided in `allowed_tags` parameter.

Args:
    text (str): string to strip html tags from
    allowed_tags (list): allowed list of html tags

Returns: a string without html tags


return get_catalog_admin_url_template().format(catalog_id=catalog_id)<EOL>

Get url to catalog details admin page.

Arguments:
    catalog_id (int): Catalog id for which to return catalog details url.

Returns:
     URL pointing to catalog details admin page for the give catalog id.

Example:
    >>> get_catalog_admin_url_template(2)
    "http://localhost:18381/admin/catalogs/catalog/2/change/"


if int(price) == price:<EOL><INDENT>return '<STR_LIT>'.format(currency, int(price))<EOL><DEDENT>return '<STR_LIT>'.format(currency, price)<EOL>

Format the price to have the appropriate currency and digits..

:param price: The price amount.
:param currency: The currency for the price.
:return: A formatted price string, i.e. '$10', '$10.52'.


def track_enrollment(pathway, user_id, course_run_id, url_path=None):

track_event(user_id, '<STR_LIT>', {<EOL>'<STR_LIT>': pathway,<EOL>'<STR_LIT>': url_path,<EOL>'<STR_LIT>': course_run_id,<EOL>})<EOL>

Emit a track event for enterprise course enrollment.


try:<EOL><INDENT>course_root = reverse('<STR_LIT>', kwargs={'<STR_LIT>': course_run['<STR_LIT:key>']})<EOL><DEDENT>except KeyError:<EOL><INDENT>LOGGER.exception(<EOL>"<STR_LIT>", course_run,<EOL>)<EOL>raise<EOL><DEDENT>url = '<STR_LIT>'.format(<EOL>settings.LMS_ROOT_URL,<EOL>course_root<EOL>)<EOL>course_run_url = update_query_parameters(url, query_parameters)<EOL>return course_run_url<EOL>

Return track selection url for the given course.

Arguments:
    course_run (dict): A dictionary containing course run metadata.
    query_parameters (dict): A dictionary containing query parameters to be added to course selection url.

Raises:
    (KeyError): Raised when course run dict does not have 'key' key.

Returns:
    (str): Course track selection url.


try:<EOL><INDENT>from third_party_auth.provider import Registry   <EOL><DEDENT>except ImportError as exception:<EOL><INDENT>LOGGER.warning("<STR_LIT>")<EOL>LOGGER.warning(exception)<EOL>Registry = None  <EOL><DEDENT>try:<EOL><INDENT>return Registry and Registry.get(provider_id)<EOL><DEDENT>except ValueError:<EOL><INDENT>return None<EOL><DEDENT>

Get Identity Provider with given id.

Return:
    Instance of ProviderConfig or None.


return {<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': slugify(enterprise_customer.name)<EOL>}<EOL>


return join(abspath(dirname(__file__)), *args)<EOL>

Return the absolute path to a directory from this file.


return abspath(join(abspath(here('<STR_LIT>')), *args))<EOL>

Return the absolute path to some file from the project's root.


def link_user(self, enterprise_customer, user_email):

Link user email to Enterprise Customer.

If :class:`django.contrib.auth.models.User` instance with specified email does not exist,
:class:`.PendingEnterpriseCustomerUser` instance is created instead.


<EOL>course_keys = {parse_course_key(k) for k in content_ids}<EOL>content_ids_in_catalog = self.content_filter_ids<EOL>if not content_ids_in_catalog:<EOL><INDENT>content_ids_in_catalog = self._filter_members('<STR_LIT:key>', list(course_keys))<EOL><DEDENT>return set(content_ids).issubset(content_ids_in_catalog) or course_keys.issubset(content_ids_in_catalog)<EOL>

Return true if this catalog contains the given courses.

The content_ids parameter should be a list containing course keys
and/or course run ids.


url = urljoin(<EOL>get_configuration_value('<STR_LIT>', settings.LMS_ROOT_URL),<EOL>reverse(<EOL>'<STR_LIT>',<EOL>kwargs={'<STR_LIT>': self.uuid, '<STR_LIT>': course_key}<EOL>)<EOL>)<EOL>return utils.update_query_parameters(url, utils.get_enterprise_utm_context(self))<EOL>

Return enterprise landing page url for the given course.

Arguments:
    course_key (str): The course key for the course to be displayed.
Returns:
    (str): Enterprise landing page url.


validation_errors = {}<EOL>if self.frequency == self.FREQUENCY_TYPE_DAILY:<EOL><INDENT>self.day_of_month = None<EOL>self.day_of_week = None<EOL><DEDENT>elif self.frequency == self.FREQUENCY_TYPE_WEEKLY:<EOL><INDENT>if self.day_of_week is None or self.day_of_week == '<STR_LIT>':<EOL><INDENT>validation_errors['<STR_LIT>'] = _('<STR_LIT>')<EOL><DEDENT>self.day_of_month = None<EOL><DEDENT>elif self.frequency == self.FREQUENCY_TYPE_MONTHLY:<EOL><INDENT>if not self.day_of_month:<EOL><INDENT>validation_errors['<STR_LIT>'] = _('<STR_LIT>')<EOL><DEDENT>self.day_of_week = None<EOL><DEDENT>else:<EOL><INDENT>validation_errors[NON_FIELD_ERRORS] = _('<STR_LIT>')<EOL><DEDENT>if self.delivery_method == self.DELIVERY_METHOD_EMAIL:<EOL><INDENT>if not self.email:<EOL><INDENT>validation_errors['<STR_LIT:email>'] = _(<EOL>'<STR_LIT>'<EOL>)<EOL><DEDENT>if not self.decrypted_password:<EOL><INDENT>validation_errors['<STR_LIT>'] = _(<EOL>'<STR_LIT>'<EOL>)<EOL><DEDENT><DEDENT>elif self.delivery_method == self.DELIVERY_METHOD_SFTP:<EOL><INDENT>if not self.sftp_hostname:<EOL><INDENT>validation_errors['<STR_LIT>'] = _('<STR_LIT>')<EOL><DEDENT>if not self.sftp_username:<EOL><INDENT>validation_errors['<STR_LIT>'] = _('<STR_LIT>')<EOL><DEDENT>if not self.sftp_file_path:<EOL><INDENT>validation_errors['<STR_LIT>'] = _('<STR_LIT>')<EOL><DEDENT>if not self.decrypted_sftp_password:<EOL><INDENT>validation_errors['<STR_LIT>'] = _(<EOL>'<STR_LIT>'<EOL>)<EOL><DEDENT><DEDENT>if validation_errors:<EOL><INDENT>raise ValidationError(validation_errors)<EOL><DEDENT>

Override of clean method to perform additional validation on frequency and day_of_month/day_of week.


DataSharingConsent = apps.get_model('<STR_LIT>', '<STR_LIT>')  <EOL>return DataSharingConsent.objects.filter(<EOL>enterprise_customer=self.enterprise_customer,<EOL>username=self.username<EOL>)<EOL>

Return the DataSharingConsent records associated with this EnterpriseCustomerUser.

Returns:
    QuerySet (DataSharingConsent): The filtered DataSharingConsent QuerySet.


enrollment_api_client = EnrollmentApiClient()<EOL>if enrollment_api_client.unenroll_user_from_course(self.username, course_run_id):<EOL><INDENT>EnterpriseCourseEnrollment.objects.filter(enterprise_customer_user=self, course_id=course_run_id).delete()<EOL>return True<EOL><DEDENT>return False<EOL>


return self.__str__()<EOL>

Return uniquely identifying string representation.


identity_provider = utils.get_identity_provider(self.provider_id)<EOL>return identity_provider and identity_provider.name<EOL>

Readable name for the identity provider.


return '<STR_LIT>'.format(<EOL>self.enterprise_customer_user.user.username,<EOL>self.course_id<EOL>)<EOL>

Create string representation of the enrollment.


return self.__str__()<EOL>


return self.__str__()<EOL>

Return string representation of the enrollment.


return self.name<EOL>

Return human-readable string representation.


enterprise_customer_type, __ = EnterpriseCustomerType.objects.get_or_create(<EOL>name='<STR_LIT>'<EOL>)<EOL>return enterprise_customer_type.id<EOL>

Get default enterprise customer type id to use when creating a new EnterpriseCustomer model.


url = self.enterprise_customer.get_course_enrollment_url(course_key)<EOL>if self.publish_audit_enrollment_urls:<EOL><INDENT>url = utils.update_query_parameters(url, {'<STR_LIT>': '<STR_LIT:true>'})<EOL><DEDENT>return utils.update_query_parameters(url, {'<STR_LIT>': self.uuid})<EOL>

Return enterprise course enrollment page url with the catalog information for the given course.

Arguments:
    course_key (str): The course key for the course to be displayed.

Returns:
    (str): Enterprise landing page url.


url = self.enterprise_customer.get_course_run_enrollment_url(course_run_key)<EOL>if self.publish_audit_enrollment_urls:<EOL><INDENT>url = utils.update_query_parameters(url, {'<STR_LIT>': '<STR_LIT:true>'})<EOL><DEDENT>return utils.update_query_parameters(url, {'<STR_LIT>': self.uuid})<EOL>

Return enterprise course enrollment page url with the catalog information for the given course.

Arguments:
    course_run_key (str): The course run id for the course to be displayed.

Returns:
    (str): Enterprise landing page url.


return self.render_template(self.plaintext_template, kwargs)<EOL>

Render just the plaintext template and return it as a string.


return (<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(<EOL>title=self.title,<EOL>uuid=self.uuid,<EOL>enterprise_customer_name=self.enterprise_customer.name<EOL>)<EOL>)<EOL>


url = self.enterprise_customer.get_program_enrollment_url(program_uuid)<EOL>if self.publish_audit_enrollment_urls:<EOL><INDENT>url = utils.update_query_parameters(url, {'<STR_LIT>': '<STR_LIT:true>'})<EOL><DEDENT>return utils.update_query_parameters(url, {'<STR_LIT>': self.uuid})<EOL>

Return enterprise program enrollment page url with the catalog information for the given program.

Arguments:
    program_uuid (str): The program UUID.

Returns:
    (str): Enterprise program landing page url.


return '<STR_LIT>'.format(<EOL>self.enterprise_customer.uuid<EOL>)<EOL>


<EOL>DataSharingConsentTextOverrides = apps.get_model('<STR_LIT>', '<STR_LIT>')<EOL>queryset = DataSharingConsentTextOverrides.objects.filter(enterprise_customer=self)<EOL>if published_only:<EOL><INDENT>queryset = queryset.filter(published=True)<EOL><DEDENT>return queryset.first()<EOL>

Return DataSharingConsentTextOverrides associated with this instance.


if self.catalog:<EOL><INDENT>client = CourseCatalogApiServiceClient(self.site)<EOL>if client.is_course_in_catalog(self.catalog, course_run_id):<EOL><INDENT>return True<EOL><DEDENT><DEDENT>for catalog in self.enterprise_customer_catalogs.all():<EOL><INDENT>if catalog.contains_courses([course_run_id]):<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False<EOL>

Determine if the specified course run is contained in at least one of the enterprise's catalogs.

Arguments:
    course_run_id (str): The string ID of the course or course run in question

Returns:
    bool: Whether the enterprise catalog includes the given course run.


<EOL>if self.role.name == ENTERPRISE_OPERATOR_ROLE:<EOL><INDENT>return ALL_ACCESS_CONTEXT<EOL><DEDENT>return super(SystemWideEnterpriseUserRoleAssignment, self).get_context()<EOL>

Return the context for this role assignment class.


return "<STR_LIT>".format(<EOL>customer=self.enterprise_customer,<EOL>id=self.entitlement_id<EOL>)<EOL>


return self.enable_audit_enrollment and self.enable_audit_data_reporting<EOL>

Determine whether the enterprise customer has enabled the ability to report/pass-back audit track data.


content_ids_in_catalog = self.content_filter_ids<EOL>if not content_ids_in_catalog:<EOL><INDENT>content_ids_in_catalog = self._filter_members('<STR_LIT>', program_uuids)<EOL><DEDENT>return set(program_uuids).issubset(content_ids_in_catalog)<EOL>

Return true if this catalog contains the given programs.


try:<EOL><INDENT>return self.enterprise_customer_identity_provider and self.enterprise_customer_identity_provider.provider_id<EOL><DEDENT>except ObjectDoesNotExist:<EOL><INDENT>return None<EOL><DEDENT>

Return the unique slug for the identity provider associated with this enterprise customer.

Returns `None` if enterprise customer does not have any identity provider.


return self.render_template(mark_safe(self.html_template), kwargs)<EOL>

Render just the HTML template and return it as a string.


def enroll(self, course_run_id, mode, cohort=None):

enrollment_api_client = EnrollmentApiClient()<EOL>course_enrollment = enrollment_api_client.get_course_enrollment(self.username, course_run_id) or {}<EOL>enrolled_in_course = course_enrollment and course_enrollment.get('<STR_LIT>', False)<EOL>audit_modes = getattr(settings, '<STR_LIT>', ['<STR_LIT>', '<STR_LIT>'])<EOL>paid_modes = ['<STR_LIT>', '<STR_LIT>']<EOL>is_upgrading = mode in paid_modes and course_enrollment.get('<STR_LIT>') in audit_modes<EOL>if not enrolled_in_course or is_upgrading:<EOL><INDENT>if cohort and not self.enterprise_customer.enable_autocohorting:<EOL><INDENT>raise CourseEnrollmentPermissionError("<STR_LIT>")<EOL><DEDENT>enrollment_api_client.enroll_user_in_course(self.username, course_run_id, mode, cohort=cohort)<EOL>utils.track_event(self.user_id, '<STR_LIT>', {<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT:label>': course_run_id,<EOL>'<STR_LIT>': str(self.enterprise_customer.uuid),<EOL>'<STR_LIT>': self.enterprise_customer.name,<EOL>'<STR_LIT>': mode,<EOL>'<STR_LIT>': cohort,<EOL>'<STR_LIT>': is_upgrading,<EOL>})<EOL>EnterpriseCourseEnrollment.objects.get_or_create(<EOL>enterprise_customer_user=self,<EOL>course_id=course_run_id<EOL>)<EOL><DEDENT>elif enrolled_in_course and course_enrollment.get('<STR_LIT>') in paid_modes and mode in audit_modes:<EOL><INDENT>raise CourseEnrollmentDowngradeError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'.format(<EOL>course_run_id=course_run_id,<EOL>current_mode=course_enrollment.get('<STR_LIT>'),<EOL>given_mode=mode,<EOL>)<EOL>)<EOL><DEDENT>

Enroll a user into a course track, and register an enterprise course enrollment.


return self.render_plaintext_template(kwargs), self.render_html_template(kwargs)<EOL>


return '<STR_LIT>'.format(self.user.user_email, self.course_id)<EOL>


return self.enable_data_sharing_consent and self.enforce_data_sharing_consent != self.EXTERNALLY_MANAGED<EOL>

Determine whether the enterprise customer has enabled the data sharing consent request.


return self.__str__()<EOL>


return self.__str__()<EOL>

Return uniquely identifying string representation.


if not self.contains_courses([course_key]):<EOL><INDENT>return None<EOL><DEDENT>return CourseCatalogApiServiceClient(self.enterprise_customer.site).get_course_details(course_key)<EOL>

Get all of the metadata for the given course.

Arguments:
    course_key (str): The course key which identifies the course.

Return:
    dict: The course metadata.


course_enrollment_api = EnrollmentApiClient()<EOL>course_enrollment = course_enrollment_api.get_course_enrollment(<EOL>self.enterprise_customer_user.username,<EOL>self.course_id<EOL>)<EOL>audit_modes = getattr(settings, '<STR_LIT>', ['<STR_LIT>', '<STR_LIT>'])<EOL>return course_enrollment and course_enrollment.get('<STR_LIT>') in audit_modes<EOL>

Specify whether the course enrollment associated with this ``EnterpriseCourseEnrollment`` is in audit mode.

:return: Whether the course enrollment mode is of an audit type.


return self.enterprise_customer_uuid<EOL>


return self._load_data(<EOL>self.CATALOGS_ENDPOINT,<EOL>default=[]<EOL>)<EOL>

Return a list of all course catalogs, including name and ID.

Returns:
    list: List of catalogs available for the user.


def _load_data(self, resource, default=DEFAULT_VALUE_SAFEGUARD, **kwargs):

default_val = default if default != self.DEFAULT_VALUE_SAFEGUARD else {}<EOL>try:<EOL><INDENT>return get_edx_api_data(<EOL>api_config=CatalogIntegration.current(),<EOL>resource=resource,<EOL>api=self.client,<EOL>**kwargs<EOL>) or default_val<EOL><DEDENT>except (SlumberBaseException, ConnectionError, Timeout) as exc:<EOL><INDENT>LOGGER.exception(<EOL>'<STR_LIT>',<EOL>resource, kwargs, str(exc)<EOL>)<EOL>return default_val<EOL><DEDENT>

Load data from API client.

Arguments:
    resource(string): type of resource to load
    default(any): value to return if API query returned empty result. Sensible values: [], {}, None etc.

Returns:
    dict: Deserialized response from Course Catalog API


if JwtBuilder is None:<EOL><INDENT>raise NotConnectedToOpenEdX(<EOL>_("<STR_LIT>"<EOL>"<STR_LIT>")<EOL>)<EOL><DEDENT>jwt = JwtBuilder.create_jwt_for_user(user)<EOL>return EdxRestApiClient(catalog_url, jwt=jwt)<EOL>

Return a Course Discovery API client setup with authentication for the specified user.


all_programs = self._load_data(self.PROGRAMS_ENDPOINT, default=[])<EOL>matching_programs = [program for program in all_programs if program.get('<STR_LIT:title>') == program_title]<EOL>if len(matching_programs) > <NUM_LIT:1>:<EOL><INDENT>raise MultipleProgramMatchError(len(matching_programs))<EOL><DEDENT>elif len(matching_programs) == <NUM_LIT:1>:<EOL><INDENT>return matching_programs[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT>

Return single program by name, or None if not found.

Arguments:
    program_title(string): Program title as seen by students and in Course Catalog Admin

Returns:
    dict: Program data provided by Course Catalog API


def get_course_final_price(self, mode, currency='<STR_LIT:$>', enterprise_catalog_uuid=None):

try:<EOL><INDENT>price_details = self.client.baskets.calculate.get(<EOL>sku=[mode['<STR_LIT>']],<EOL>username=self.user.username,<EOL>catalog=enterprise_catalog_uuid,<EOL>)<EOL><DEDENT>except (SlumberBaseException, ConnectionError, Timeout) as exc:<EOL><INDENT>LOGGER.exception('<STR_LIT>', mode['<STR_LIT>'], str(exc))<EOL>price_details = {}<EOL><DEDENT>price = price_details.get('<STR_LIT>', mode['<STR_LIT>'])<EOL>if price != mode['<STR_LIT>']:<EOL><INDENT>return format_price(price, currency)<EOL><DEDENT>return mode['<STR_LIT>']<EOL>

Get course mode's SKU discounted price after applying any entitlement available for this user.

Returns:
    str: Discounted price of the course mode.


content_metadata = OrderedDict()<EOL>if enterprise_customer.catalog:<EOL><INDENT>response = self._load_data(<EOL>self.ENTERPRISE_CUSTOMER_ENDPOINT,<EOL>detail_resource='<STR_LIT>',<EOL>resource_id=str(enterprise_customer.uuid),<EOL>traverse_pagination=True,<EOL>)<EOL>for course in response['<STR_LIT>']:<EOL><INDENT>for course_run in course['<STR_LIT>']:<EOL><INDENT>course_run['<STR_LIT>'] = '<STR_LIT>'  <EOL>content_metadata[course_run['<STR_LIT:key>']] = course_run<EOL><DEDENT><DEDENT><DEDENT>for enterprise_customer_catalog in enterprise_customer.enterprise_customer_catalogs.all():<EOL><INDENT>response = self._load_data(<EOL>self.ENTERPRISE_CUSTOMER_CATALOGS_ENDPOINT,<EOL>resource_id=str(enterprise_customer_catalog.uuid),<EOL>traverse_pagination=True,<EOL>querystring={'<STR_LIT>': <NUM_LIT:1000>},<EOL>)<EOL>for item in response['<STR_LIT>']:<EOL><INDENT>content_id = utils.get_content_metadata_item_id(item)<EOL>content_metadata[content_id] = item<EOL><DEDENT><DEDENT>return content_metadata.values()<EOL>

Return all content metadata contained in the catalogs associated with the EnterpriseCustomer.

Arguments:
    enterprise_customer (EnterpriseCustomer): The EnterpriseCustomer to return content metadata for.

Returns:
    list: List of dicts containing content metadata.


try:<EOL><INDENT>return self.client.course(course_id).get()<EOL><DEDENT>except (SlumberBaseException, ConnectionError, Timeout) as exc:<EOL><INDENT>LOGGER.exception(<EOL>'<STR_LIT>',<EOL>course_id, str(exc)<EOL>)<EOL>return {}<EOL><DEDENT>

Query the Enrollment API for the course details of the given course_id.

Args:
    course_id (str): The string value of the course's unique identifier

Returns:
    dict: A dictionary containing details about the course, in an enrollment context (allowed modes, etc.)


details = self.get_course_details(course_id)<EOL>modes = details.get('<STR_LIT>', [])<EOL>return self._sort_course_modes([mode for mode in modes if mode['<STR_LIT>'] not in EXCLUDED_COURSE_MODES])<EOL>

Query the Enrollment API for the specific course modes that are available for the given course_id.

Arguments:
    course_id (str): The string value of the course's unique identifier

Returns:
    list: A list of course mode dictionaries.


def unenroll_user_from_course(self, username, course_id):

enrollment = self.get_course_enrollment(username, course_id)<EOL>if enrollment and enrollment['<STR_LIT>']:<EOL><INDENT>response = self.client.enrollment.post({<EOL>'<STR_LIT:user>': username,<EOL>'<STR_LIT>': {'<STR_LIT>': course_id},<EOL>'<STR_LIT>': False,<EOL>'<STR_LIT>': enrollment['<STR_LIT>']<EOL>})<EOL>return not response['<STR_LIT>']<EOL><DEDENT>return False<EOL>

Call the enrollment API to unenroll the user in the course specified by course_id.
Args:
    username (str): The username by which the user goes on the OpenEdx platform
    course_id (str): The string value of the course's unique identifier
Returns:
    bool: Whether the unenrollment succeeded


return int(time()) > self.expires_at<EOL>

Return True if the JWT token has expired, False if not.


@JwtLmsApiClient.refresh_token<EOL><INDENT>def get_course_certificate(self, course_id, username):<DEDENT>

return self.client.certificates(username).courses(course_id).get()<EOL>

Retrieve the certificate for the given username for the given course_id.

Args:
* ``course_id`` (str): The string value of the course's unique identifier
* ``username`` (str): The username ID identifying the user for which to retrieve the certificate

Raises:

HttpNotFoundError if no certificate found for the given user+course.

Returns:

a dict containing:

* ``username``: A string representation of an user's username passed in the request.
* ``course_id``: A string representation of a Course ID.
* ``certificate_type``: A string representation of the certificate type.
* ``created_date`: Datetime the certificate was created (tz-aware).
* ``status``: A string representation of the certificate status.
* ``is_passing``: True if the certificate has a passing status, False if not.
* ``download_url``: A string representation of the certificate url.
* ``grade``: A string representation of a float for the user's course grade.


session = Session()<EOL>session.headers = {"<STR_LIT>": settings.EDX_API_KEY}<EOL>self.client = EdxRestApiClient(<EOL>self.API_BASE_URL, append_slash=self.APPEND_SLASH, session=session<EOL>)<EOL>

Create an LMS API client, authenticated with the API token from Django settings.


@staticmethod<EOL><INDENT>def redirect_if_blocked(course_run_ids, user=None, ip_address=None, url=None):<DEDENT>

for course_run_id in course_run_ids:<EOL><INDENT>redirect_url = embargo_api.redirect_if_blocked(<EOL>CourseKey.from_string(course_run_id),<EOL>user=user,<EOL>ip_address=ip_address,<EOL>url=url<EOL>)<EOL>if redirect_url:<EOL><INDENT>return redirect_url<EOL><DEDENT><DEDENT>

Return redirect to embargo error page if the given user is blocked.


def __init__(self, user, expires_in=settings.OAUTH_ID_TOKEN_EXPIRATION):

self.user = user<EOL>self.expires_in = expires_in<EOL>self.expires_at = <NUM_LIT:0><EOL>self.client = None<EOL>


@JwtLmsApiClient.refresh_token<EOL><INDENT>def get_course_grade(self, course_id, username):<DEDENT>

results = self.client.courses(course_id).get(username=username)<EOL>for row in results:<EOL><INDENT>if row.get('<STR_LIT:username>') == username:<EOL><INDENT>return row<EOL><DEDENT><DEDENT>raise HttpNotFoundError('<STR_LIT>'.format(course_id, username))<EOL>

Retrieve the grade for the given username for the given course_id.

Args:
* ``course_id`` (str): The string value of the course's unique identifier
* ``username`` (str): The username ID identifying the user for which to retrieve the grade.

Raises:

HttpNotFoundError if no grade found for the given user+course.

Returns:

a dict containing:

* ``username``: A string representation of a user's username passed in the request.
* ``course_key``: A string representation of a Course ID.
* ``passed``: Boolean representing whether the course has been passed according the course's grading policy.
* ``percent``: A float representing the overall grade for the course
* ``letter_grade``: A letter grade as defined in grading_policy (e.g. 'A' 'B' 'C' for 6.002x) or None


def get_remote_id(self, identity_provider, username):

return self._get_results(identity_provider, '<STR_LIT:username>', username, '<STR_LIT>')<EOL>

Retrieve the remote identifier for the given username.

Args:
* ``identity_provider`` (str): identifier slug for the third-party authentication service used during SSO.
* ``username`` (str): The username ID identifying the user for which to retrieve the remote name.

Returns:
    string or None: the remote name of the given user.  None if not found.


def enroll_user_in_course(self, username, course_id, mode, cohort=None):

return self.client.enrollment.post(<EOL>{<EOL>'<STR_LIT:user>': username,<EOL>'<STR_LIT>': {'<STR_LIT>': course_id},<EOL>'<STR_LIT>': mode,<EOL>'<STR_LIT>': cohort,<EOL>}<EOL>)<EOL>

Call the enrollment API to enroll the user in the course specified by course_id.

Args:
    username (str): The username by which the user goes on the OpenEdX platform
    course_id (str): The string value of the course's unique identifier
    mode (str): The enrollment mode which should be used for the enrollment
    cohort (str): Add the user to this named cohort

Returns:
    dict: A dictionary containing details of the enrollment, including course details, mode, username, etc.


def get_course_enrollment(self, username, course_id):

endpoint = getattr(<EOL>self.client.enrollment,<EOL>'<STR_LIT>'.format(username=username, course_id=course_id)<EOL>)<EOL>try:<EOL><INDENT>result = endpoint.get()<EOL><DEDENT>except HttpNotFoundError:<EOL><INDENT>LOGGER.error(<EOL>'<STR_LIT>',<EOL>username,<EOL>course_id<EOL>)<EOL>return None<EOL><DEDENT>if not result:<EOL><INDENT>LOGGER.info('<STR_LIT>', username, course_id)<EOL>return None<EOL><DEDENT>return result<EOL>

Query the enrollment API to get information about a single course enrollment.

Args:
    username (str): The username by which the user goes on the OpenEdX platform
    course_id (str): The string value of the course's unique identifier

Returns:
    dict: A dictionary containing details of the enrollment, including course details, mode, username, etc.


def decorator(func):<EOL><INDENT>"""<STR_LIT>"""<EOL>@wraps(func)<EOL>def wrapper(*args, **kwargs):<EOL><INDENT>"""<STR_LIT>"""<EOL>warnings.simplefilter('<STR_LIT:ignore>', warning)<EOL>return func(*args, **kwargs)<EOL><DEDENT>return wrapper<EOL><DEDENT>return decorator<EOL>

Ignore any emitted warnings from a function.

:param warning: The category of warning to ignore.


def decorator(func):<EOL><INDENT>"""<STR_LIT>"""<EOL>@wraps(func)<EOL>def wrapper(*args, **kwargs):<EOL><INDENT>"""<STR_LIT>"""<EOL>message = '<STR_LIT>'.format(<EOL>function=func.__name__,<EOL>extra=extra<EOL>)<EOL>frame = inspect.currentframe().f_back<EOL>warnings.warn_explicit(<EOL>message,<EOL>category=DeprecationWarning,<EOL>filename=inspect.getfile(frame.f_code),<EOL>lineno=frame.f_lineno<EOL>)<EOL>return func(*args, **kwargs)<EOL><DEDENT>return wrapper<EOL><DEDENT>return decorator<EOL>

Flag a method as deprecated.

:param extra: Extra text you'd like to display after the default text.


return func<EOL>

Use this decorator to stub out decorators for testing.

If we're unable to import social_core.pipeline.partial, which is the case in our CI platform,
we need to be able to wrap the function with something.


@wraps(view)<EOL>def wrapper(request, *args, **kwargs):<EOL><INDENT>"""<STR_LIT>"""<EOL>if not request.GET.get(FRESH_LOGIN_PARAMETER):<EOL><INDENT>enterprise_customer = get_enterprise_customer_or_404(kwargs.get('<STR_LIT>'))<EOL>provider_id = enterprise_customer.identity_provider or '<STR_LIT>'<EOL>sso_provider = get_identity_provider(provider_id)<EOL>if sso_provider:<EOL><INDENT>scheme, netloc, path, params, query, fragment = urlparse(request.get_full_path())<EOL>redirect_url = urlunparse((scheme, netloc, quote(path), params, query, fragment))<EOL>return redirect(<EOL>'<STR_LIT>'.format(<EOL>logout_url='<STR_LIT>',<EOL>params=urlencode(<EOL>{'<STR_LIT>': redirect_url}<EOL>)<EOL>)<EOL>)<EOL><DEDENT><DEDENT>return view(request, *args, **kwargs)<EOL><DEDENT>return wrapper<EOL>

View decorator which terminates stale TPA sessions.

This decorator forces the user to obtain a new session
the first time they access the decorated view. This prevents
TPA-authenticated users from hijacking the session of another
user who may have been previously logged in using the same
browser window.

This decorator should be used in conjunction with the
enterprise_login_required decorator.

Usage::
    @enterprise_login_required
    @force_fresh_session()
    def my_view(request, enterprise_uuid):
        # Some functionality ...

    OR

    class MyView(View):
        ...
        @method_decorator(enterprise_login_required)
        @method_decorator(force_fresh_session)
        def get(self, request, enterprise_uuid):
            # Some functionality ...


return self._exists or self.enterprise_enrollment_exists<EOL>

Determine whether a record related to the consent scenario exists.

First, check the instance's own `_exists` attribute; this is set to True
on database-backed instances that have a primary key, and may be manually
set to true on ProxyDataSharingConsent objects that have database-backed
children. If unsuccessful, check to see if an EnterpriseCourseEnrollment
related to this consent record exists; we treat that as though this record
exists for the purposes of serializable API responses.

We want to check for EnterpriseCourseEnrollment records because there are
cases where one will be created, but not the other. In particular, proxy
enrollments create an ECE but not any consent record. The LMS uses the
API's 'exists' key to determine if consent action should be taken for course
enrollments that have prior existence but for which consent has not been
granted. Thus, 'exists' is used as a proxy for the question "has any workflow
been entered which may involve a necessity for the learner to grant consent?"


return "<STR_LIT>".format(<EOL>class_name=self.__class__.__name__,<EOL>username=self.username,<EOL>enterprise_name=self.enterprise_customer.name,<EOL>)<EOL>

Return a human-readable string representation.


Determine whether there exists an EnterpriseCourseEnrollment related to this consent record.


DataSharingConsent = apps.get_model('<STR_LIT>', '<STR_LIT>')<EOL>EnterpriseCourseEnrollment = apps.get_model('<STR_LIT>', '<STR_LIT>')<EOL>User = apps.get_model('<STR_LIT>', '<STR_LIT>')<EOL>for enrollment in EnterpriseCourseEnrollment.objects.all():<EOL><INDENT>user = User.objects.get(pk=enrollment.enterprise_customer_user.user_id)<EOL>data_sharing_consent, __ = DataSharingConsent.objects.get_or_create(<EOL>username=user.username,<EOL>enterprise_customer=enrollment.enterprise_customer_user.enterprise_customer,<EOL>course_id=enrollment.course_id,<EOL>)<EOL>if enrollment.consent_granted is not None:<EOL><INDENT>data_sharing_consent.granted = enrollment.consent_granted<EOL><DEDENT>else:<EOL><INDENT>consent_state = enrollment.enterprise_customer_user.data_sharing_consent.first()<EOL>if consent_state is not None:<EOL><INDENT>data_sharing_consent.granted = consent_state.state in ['<STR_LIT>', '<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>data_sharing_consent.granted = False<EOL><DEDENT><DEDENT>data_sharing_consent.save()<EOL><DEDENT>

Populates the ``DataSharingConsent`` model with the ``enterprise`` application's consent data.

Consent data from the ``enterprise`` application come from the ``EnterpriseCourseEnrollment`` model.


def preview_as_program(self, request, consent_page):

return self.preview(consent_page, program_uuid='<STR_LIT>')<EOL>

Renders data sharing consent page in program context


params = '<STR_LIT:U+002CU+0020>'.join(name for name, present in parameter_state if not present)<EOL>return self.MISSING_REQUIRED_PARAMS_MSG.format(params)<EOL>

Get a user-friendly message indicating a missing parameter for the API endpoint.


username = get_request_value(request, self.REQUIRED_PARAM_USERNAME, '<STR_LIT>')<EOL>course_id = get_request_value(request, self.REQUIRED_PARAM_COURSE_ID, '<STR_LIT>')<EOL>program_uuid = get_request_value(request, self.REQUIRED_PARAM_PROGRAM_UUID, '<STR_LIT>')<EOL>enterprise_customer_uuid = get_request_value(request, self.REQUIRED_PARAM_ENTERPRISE_CUSTOMER)<EOL>if not (username and (course_id or program_uuid) and enterprise_customer_uuid):<EOL><INDENT>raise ConsentAPIRequestError(<EOL>self.get_missing_params_message([<EOL>("<STR_LIT>", bool(username)),<EOL>("<STR_LIT>", bool(enterprise_customer_uuid)),<EOL>("<STR_LIT>", bool(course_id or program_uuid)),<EOL>])<EOL>)<EOL><DEDENT>return username, course_id, program_uuid, enterprise_customer_uuid<EOL>

Gets ``username``, ``course_id``, and ``enterprise_customer_uuid``,
which are the relevant query parameters for this API endpoint.

:param request: The request to this endpoint.
:return: The ``username``, ``course_id``, and ``enterprise_customer_uuid`` from the request.


username, course_id, program_uuid, enterprise_customer_uuid = self.get_required_query_params(request)<EOL>return get_data_sharing_consent(<EOL>username,<EOL>enterprise_customer_uuid,<EOL>course_id=course_id,<EOL>program_uuid=program_uuid<EOL>)<EOL>

Get the consent record relevant to the request at hand.


def get_program_data_sharing_consent(username, program_uuid, enterprise_customer_uuid):

enterprise_customer = get_enterprise_customer(enterprise_customer_uuid)<EOL>discovery_client = CourseCatalogApiServiceClient(enterprise_customer.site)<EOL>course_ids = discovery_client.get_program_course_keys(program_uuid)<EOL>child_consents = (<EOL>get_data_sharing_consent(username, enterprise_customer_uuid, course_id=individual_course_id)<EOL>for individual_course_id in course_ids<EOL>)<EOL>return ProxyDataSharingConsent.from_children(program_uuid, *child_consents)<EOL>

Get the data sharing consent object associated with a certain user of a customer for a program.

:param username: The user that grants consent.
:param program_uuid: The program for which consent is granted.
:param enterprise_customer_uuid: The consent requester.
:return: The data sharing consent object


def get_data_sharing_consent(username, enterprise_customer_uuid, course_id=None, program_uuid=None):

EnterpriseCustomer = apps.get_model('<STR_LIT>', '<STR_LIT>')  <EOL>try:<EOL><INDENT>if course_id:<EOL><INDENT>return get_course_data_sharing_consent(username, course_id, enterprise_customer_uuid)<EOL><DEDENT>return get_program_data_sharing_consent(username, program_uuid, enterprise_customer_uuid)<EOL><DEDENT>except EnterpriseCustomer.DoesNotExist:<EOL><INDENT>return None<EOL><DEDENT>

Get the data sharing consent object associated with a certain user, enterprise customer, and other scope.

:param username: The user that grants consent
:param enterprise_customer_uuid: The consent requester
:param course_id (optional): A course ID to which consent may be related
:param program_uuid (optional): A program to which consent may be related
:return: The data sharing consent object, or None if the enterprise customer for the given UUID does not exist.


return bool(self.pk)<EOL>

Return whether the instance exists or not.


return self.commit()<EOL>


return self.__str__()<EOL>

Return uniquely identifying string representation.


if self._child_consents:<EOL><INDENT>consents = []<EOL>for consent in self._child_consents:<EOL><INDENT>consent.granted = self.granted<EOL>consents.append(consent.save() or consent)<EOL><DEDENT>return ProxyDataSharingConsent.from_children(self.program_uuid, *consents)<EOL><DEDENT>consent, _ = DataSharingConsent.objects.update_or_create(<EOL>enterprise_customer=self.enterprise_customer,<EOL>username=self.username,<EOL>course_id=self.course_id,<EOL>defaults={<EOL>'<STR_LIT>': self.granted<EOL>}<EOL>)<EOL>self._exists = consent.exists<EOL>return consent<EOL>

Commit a real ``DataSharingConsent`` object to the database, mirroring current field settings.

:return: A ``DataSharingConsent`` object if validation is successful, otherwise ``None``.


ec_keys = {}<EOL>for key in kwargs:<EOL><INDENT>if str(key).startswith('<STR_LIT>'):<EOL><INDENT>enterprise_customer_detail = key[len('<STR_LIT>'):]<EOL>ec_keys[enterprise_customer_detail] = kwargs[key]<EOL><DEDENT><DEDENT>if ec_keys:<EOL><INDENT>enterprise_customer = EnterpriseCustomer.objects.get(**ec_keys)  <EOL><DEDENT>self.enterprise_customer = enterprise_customer<EOL>self.username = username<EOL>self.course_id = course_id<EOL>self.program_uuid = program_uuid<EOL>self.granted = granted<EOL>self._exists = exists<EOL>self._child_consents = child_consents or []<EOL>

Initialize a proxy version of ``DataSharingConsent`` which behaves similarly but does not exist in the DB.


super(TestSAPSuccessFactorsConfig, self).setUp()<EOL>self.app_config = integrated_channels.sap_success_factors.apps.SAPSuccessFactorsConfig(<EOL>'<STR_LIT>', integrated_channels.sap_success_factors<EOL>)<EOL>


super(TestXAPIConfig, self).setUp()<EOL>self.app_config = integrated_channels.xapi.apps.XAPIConfig(<EOL>'<STR_LIT>', integrated_channels.xapi<EOL>)<EOL>


super(TestEnterpriseConfig, self).setUp()<EOL>self.post_save_mock = mock.Mock()<EOL>patcher = mock.patch('<STR_LIT>', self.post_save_mock)<EOL>patcher.start()<EOL>self.app_config = enterprise.apps.EnterpriseConfig('<STR_LIT>', enterprise)<EOL>self.addCleanup(patcher.stop)<EOL>


super(TestEnterpriseDecorators, self).setUp()<EOL>faker = FakerFactory.create()<EOL>self.provider_id = faker.slug()  <EOL>self.uuid = faker.uuid4()  <EOL>self.customer = EnterpriseCustomerFactory(uuid=self.uuid)<EOL>EnterpriseCustomerIdentityProviderFactory(provider_id=self.provider_id, enterprise_customer=self.customer)<EOL>self.session_engine = import_module(settings.SESSION_ENGINE)<EOL>


self.faker = FakerFactory.create()<EOL>self.catalog_uuid = self.faker.uuid4()  <EOL>self.enterprise_uuid = self.faker.uuid4()  <EOL>self.enterprise_name = '<STR_LIT>'<EOL>super(TestEnterpriseCustomerCatalog, self).setUp()<EOL>


def _():<EOL><INDENT>"""<STR_LIT>"""<EOL>idp_list = []<EOL>for idp in idps:<EOL><INDENT>mock_idp = mock.Mock()<EOL>mock_idp.configure_mock(provider_id=idp, name=idp)<EOL>idp_list.append(mock_idp)<EOL><DEDENT>return idp_list<EOL><DEDENT>return _<EOL>


super(TestEnterpriseUtils, self).setUp()<EOL>faker = FakerFactory.create()<EOL>self.provider_id = faker.slug()  <EOL>self.uuid = faker.uuid4()  <EOL>self.customer = EnterpriseCustomerFactory(uuid=self.uuid)<EOL>EnterpriseCustomerIdentityProviderFactory(provider_id=self.provider_id, enterprise_customer=self.customer)<EOL>


self.executor.loader.build_graph()<EOL>self.executor.migrate(self.migrate_origin)<EOL>

Performs the migration to the designated origin.

This only really does anything if you have migrated forward
in some way or no migrations were performed at all.


self.executor.loader.build_graph()<EOL>self.executor.migrate(self.migrate_dest)<EOL>

Performs the migration to the designated destination.


self.enterprise_learner_role, __ = SystemWideEnterpriseRole.objects.get_or_create(name=ENTERPRISE_LEARNER_ROLE)<EOL>self.learner_user = UserFactory(id=<NUM_LIT:2>, email='<STR_LIT>')<EOL>self.enterprise_customer = EnterpriseCustomerFactory(<EOL>catalog=<NUM_LIT:1>,<EOL>name='<STR_LIT>',<EOL>)<EOL>super(TestEnterpriseLearnerRoleSignals, self).setUp()<EOL>

Setup for `TestEnterpriseLearnerRoleSignals` test.


super(TestIsAdminUserOrInGroupPermissions, self).setUp()<EOL>self.user = UserFactory(email='<STR_LIT>', password='<STR_LIT:test>', is_staff=True)<EOL>


enterprise_customer = factories.EnterpriseCustomerFactory(<EOL>uuid=FAKE_UUIDS[<NUM_LIT:0>],<EOL>name="<STR_LIT>",<EOL>enable_autocohorting=enable_autocohorting<EOL>)<EOL>permission = Permission.objects.get(name='<STR_LIT>')<EOL>self.user.user_permissions.add(permission)<EOL>user = None<EOL>if user_exists:<EOL><INDENT>if lms_user_id:<EOL><INDENT>user = factories.UserFactory(id=lms_user_id)<EOL><DEDENT>elif tpa_user_id:<EOL><INDENT>user = factories.UserFactory(username=tpa_user_id)<EOL><DEDENT>elif user_email:<EOL><INDENT>user = factories.UserFactory(email=user_email)<EOL><DEDENT>factories.EnterpriseCustomerUserFactory(<EOL>user_id=user.id,<EOL>enterprise_customer=enterprise_customer,<EOL>)<EOL><DEDENT>if tpa_user_id:<EOL><INDENT>mock_tpa_client.return_value = mock.Mock()<EOL>mock_tpa_client.return_value.get_username_from_remote_id = mock.Mock()<EOL>mock_tpa_client.return_value.get_username_from_remote_id.return_value = tpa_user_id<EOL><DEDENT>mock_enrollment_client.return_value = mock.Mock(<EOL>get_course_enrollment=mock.Mock(return_value=course_enrollment),<EOL>enroll_user_in_course=mock.Mock()<EOL>)<EOL>mock_catalog_contains_course.return_value = course_in_catalog<EOL>return enterprise_customer, user<EOL>

Set up for tests that call the enterprise customer course enrollments detail route.


for item in items:<EOL><INDENT>factory.create(**item)<EOL><DEDENT>

Create model instances using given factory


request = RequestFactory().get(url)<EOL>request.user = user<EOL>session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME)<EOL>request.session = self.session_engine.SessionStore(session_key)<EOL>return request<EOL>


super(TestEnterpriseAPIDecorators, self).setUp()<EOL>faker = FakerFactory.create()<EOL>self.provider_id = faker.slug()  <EOL>self.uuid = faker.uuid4()  <EOL>self.customer = EnterpriseCustomerFactory(uuid=self.uuid)<EOL>self.user = UserFactory()<EOL>self.session_engine = import_module(settings.SESSION_ENGINE)<EOL>


super(TestCourseCatalogApiService, self).setUp()<EOL>self.user_mock = mock.Mock(spec=User)<EOL>self.get_data_mock = self._make_patch(self._make_catalog_api_location("<STR_LIT>"))<EOL>self.jwt_builder_mock = self._make_patch(self._make_catalog_api_location("<STR_LIT>"))<EOL>self.integration_config_mock = mock.Mock(enabled=True)<EOL>self.integration_config_mock.get_service_user.return_value = self.user_mock<EOL>self.integration_mock = self._make_patch(self._make_catalog_api_location("<STR_LIT>"))<EOL>self.integration_mock.current.return_value = self.integration_config_mock<EOL>self.api = CourseCatalogApiServiceClient()<EOL>


assert len(responses.calls) == expected_count<EOL>

DRY helper for verifying request counts.


self.enterprise_customer = EnterpriseCustomerFactory(<EOL>catalog=<NUM_LIT:1>,<EOL>name='<STR_LIT>',<EOL>)<EOL>super(TestEnterpriseApiClient, self).setUp()<EOL>self.catalog_api_config_mock = self._make_patch(self._make_catalog_api_location("<STR_LIT>"))<EOL>self.user = UserFactory(is_staff=True)<EOL>


def _setup_ecommerce_client(self, client_mock, total=<NUM_LIT:50>):

dummy_price_details_mock = mock.MagicMock()<EOL>dummy_price_details_mock.return_value = {<EOL>'<STR_LIT>': total,<EOL>}<EOL>price_details_mock = mock.MagicMock()<EOL>method_name = '<STR_LIT>'<EOL>attrs = {method_name: dummy_price_details_mock}<EOL>price_details_mock.configure_mock(**attrs)<EOL>client_mock.return_value = price_details_mock<EOL>