Search is not available for this dataset
text
stringlengths
75
104k
def render_page_with_error_code_message(request, context_data, error_code, log_message): """ Return a 404 page with specified error_code after logging error and adding message to django messages. """ LOGGER.error(log_message) messages.add_generic_error_message_with_code(request, error_code) return render( request, ENTERPRISE_GENERAL_ERROR_PAGE, context=context_data, status=404, )
def course_or_program_exist(self, course_id, program_uuid): """ Return whether the input course or program exist. """ course_exists = course_id and CourseApiClient().get_course_details(course_id) program_exists = program_uuid and CourseCatalogApiServiceClient().program_exists(program_uuid) return course_exists or program_exists
def get_default_context(self, enterprise_customer, platform_name): """ Get the set of variables that will populate the template by default. """ context_data = { 'page_title': _('Data sharing consent required'), 'consent_message_header': _('Consent to share your data'), 'requested_permissions_header': _( 'Per the {start_link}Data Sharing Policy{end_link}, ' '{bold_start}{enterprise_customer_name}{bold_end} would like to know about:' ).format( enterprise_customer_name=enterprise_customer.name, bold_start='<b>', bold_end='</b>', start_link='<a href="#consent-policy-dropdown-bar" ' 'class="policy-dropdown-link background-input" id="policy-dropdown-link">', end_link='</a>', ), 'agreement_text': _( 'I agree to allow {platform_name} to share data about my enrollment, completion and performance in all ' '{platform_name} courses and programs where my enrollment is sponsored by {enterprise_customer_name}.' ).format( enterprise_customer_name=enterprise_customer.name, platform_name=platform_name, ), 'continue_text': _('Yes, continue'), 'abort_text': _('No, take me back.'), 'policy_dropdown_header': _('Data Sharing Policy'), 'sharable_items_header': _( 'Enrollment, completion, and performance data that may be shared with {enterprise_customer_name} ' '(or its designee) for these courses and programs are limited to the following:' ).format( enterprise_customer_name=enterprise_customer.name ), 'sharable_items': [ _( 'My email address for my {platform_name} account, ' 'and the date when I created my {platform_name} account' ).format( platform_name=platform_name ), _( 'My {platform_name} ID, and if I log in via single sign-on, ' 'my {enterprise_customer_name} SSO user-ID' ).format( platform_name=platform_name, enterprise_customer_name=enterprise_customer.name, ), _('My {platform_name} username').format(platform_name=platform_name), _('My country or region of residence'), _( 'What courses and/or programs I\'ve enrolled in or unenrolled from, what track I ' 'enrolled in (audit or verified) and the date when I enrolled in each course or program' ), _( 'Information about each course or program I\'ve enrolled in, ' 'including its duration and level of effort required' ), _( 'Whether I completed specific parts of each course or program (for example, whether ' 'I watched a given video or completed a given homework assignment)' ), _( 'My overall percentage completion of each course or program on a periodic basis, ' 'including the total time spent in each course or program and the date when I last ' 'logged in to each course or program' ), _('My performance in each course or program'), _('My final grade in each course or program, and the date when I completed each course or program'), _('Whether I received a certificate in each course or program'), ], 'sharable_items_footer': _( 'My permission applies only to data from courses or programs that are sponsored by ' '{enterprise_customer_name}, and not to data from any {platform_name} courses or programs that ' 'I take on my own. I understand that I may withdraw my permission only by fully unenrolling ' 'from any courses or programs that are sponsored by {enterprise_customer_name}.' ).format( enterprise_customer_name=enterprise_customer.name, platform_name=platform_name, ), 'sharable_items_note_header': _('Please note'), 'sharable_items_notes': [ _('If you decline to consent, that fact may be shared with {enterprise_customer_name}.').format( enterprise_customer_name=enterprise_customer.name ), ], 'confirmation_modal_header': _('Are you aware...'), 'confirmation_modal_affirm_decline_text': _('I decline'), 'confirmation_modal_abort_decline_text': _('View the data sharing policy'), 'policy_link_template': _('View the {start_link}data sharing policy{end_link}.').format( start_link='<a href="#consent-policy-dropdown-bar" class="policy-dropdown-link background-input" ' 'id="policy-dropdown-link">', end_link='</a>', ), 'policy_return_link_text': _('Return to Top'), } return context_data
def get_context_from_db(self, consent_page, platform_name, item, context): """ Make set of variables(populated from db) that will be used in data sharing consent page. """ enterprise_customer = consent_page.enterprise_customer course_title = context.get('course_title', None) course_start_date = context.get('course_start_date', None) context_data = { 'text_override_available': True, 'page_title': consent_page.page_title, 'left_sidebar_text': consent_page.left_sidebar_text.format( enterprise_customer_name=enterprise_customer.name, platform_name=platform_name, item=item, course_title=course_title, course_start_date=course_start_date, ), 'top_paragraph': consent_page.top_paragraph.format( enterprise_customer_name=enterprise_customer.name, platform_name=platform_name, item=item, course_title=course_title, course_start_date=course_start_date, ), 'agreement_text': consent_page.agreement_text.format( enterprise_customer_name=enterprise_customer.name, platform_name=platform_name, item=item, course_title=course_title, course_start_date=course_start_date, ), 'continue_text': consent_page.continue_text, 'abort_text': consent_page.abort_text, 'policy_dropdown_header': consent_page.policy_dropdown_header, 'policy_paragraph': consent_page.policy_paragraph.format( enterprise_customer_name=enterprise_customer.name, platform_name=platform_name, item=item, course_title=course_title, course_start_date=course_start_date, ), 'confirmation_modal_header': consent_page.confirmation_modal_header.format( enterprise_customer_name=enterprise_customer.name, platform_name=platform_name, item=item, course_title=course_title, course_start_date=course_start_date, ), 'confirmation_alert_prompt': consent_page.confirmation_modal_text.format( enterprise_customer_name=enterprise_customer.name, platform_name=platform_name, item=item, course_title=course_title, course_start_date=course_start_date, ), 'confirmation_modal_affirm_decline_text': consent_page.modal_affirm_decline_text, 'confirmation_modal_abort_decline_text': consent_page.modal_abort_decline_text, } return context_data
def get_course_or_program_context(self, enterprise_customer, course_id=None, program_uuid=None): """ Return a dict having course or program specific keys for data sharing consent page. """ context_data = {} if course_id: context_data.update({'course_id': course_id, 'course_specific': True}) if not self.preview_mode: try: catalog_api_client = CourseCatalogApiServiceClient(enterprise_customer.site) except ImproperlyConfigured: raise Http404 course_run_details = catalog_api_client.get_course_run(course_id) course_start_date = '' if course_run_details['start']: course_start_date = parse(course_run_details['start']).strftime('%B %d, %Y') context_data.update({ 'course_title': course_run_details['title'], 'course_start_date': course_start_date, }) else: context_data.update({ 'course_title': 'Demo Course', 'course_start_date': datetime.datetime.now().strftime('%B %d, %Y'), }) else: context_data.update({ 'program_uuid': program_uuid, 'program_specific': True, }) return context_data
def get(self, request): """ Render a form to collect user input about data sharing consent. """ enterprise_customer_uuid = request.GET.get('enterprise_customer_uuid') success_url = request.GET.get('next') failure_url = request.GET.get('failure_url') course_id = request.GET.get('course_id', '') program_uuid = request.GET.get('program_uuid', '') self.preview_mode = bool(request.GET.get('preview_mode', False)) # Get enterprise_customer to start in case we need to render a custom 404 page # Then go through other business logic to determine (and potentially overwrite) the enterprise customer enterprise_customer = get_enterprise_customer_or_404(enterprise_customer_uuid) context_data = get_global_context(request, enterprise_customer) if not self.preview_mode: if not self.course_or_program_exist(course_id, program_uuid): error_code = 'ENTGDS000' log_message = ( 'Neither the course with course_id: {course_id} ' 'or program with {program_uuid} exist for ' 'enterprise customer {enterprise_customer_uuid}' 'Error code {error_code} presented to user {userid}'.format( course_id=course_id, program_uuid=program_uuid, error_code=error_code, userid=request.user.id, enterprise_customer_uuid=enterprise_customer_uuid, ) ) return render_page_with_error_code_message(request, context_data, error_code, log_message) try: consent_record = get_data_sharing_consent( request.user.username, enterprise_customer_uuid, program_uuid=program_uuid, course_id=course_id ) except NotConnectedToOpenEdX as error: error_code = 'ENTGDS001' log_message = ( 'The was a problem with getting the consent record of user {userid} with ' 'uuid {enterprise_customer_uuid}. get_data_sharing_consent threw ' 'the following NotConnectedToOpenEdX error: {error}' 'for course_id {course_id}.' 'Error code {error_code} presented to user'.format( userid=request.user.id, enterprise_customer_uuid=enterprise_customer_uuid, error=error, error_code=error_code, course_id=course_id, ) ) return render_page_with_error_code_message(request, context_data, error_code, log_message) try: consent_required = consent_record.consent_required() except AttributeError: consent_required = None if consent_record is None or not consent_required: error_code = 'ENTGDS002' log_message = ( 'The was a problem with the consent record of user {userid} with ' 'enterprise_customer_uuid {enterprise_customer_uuid}. consent_record has a value ' 'of {consent_record} and consent_record.consent_required() a ' 'value of {consent_required} for course_id {course_id}. ' 'Error code {error_code} presented to user'.format( userid=request.user.id, enterprise_customer_uuid=enterprise_customer_uuid, consent_record=consent_record, consent_required=consent_required, error_code=error_code, course_id=course_id, ) ) return render_page_with_error_code_message(request, context_data, error_code, log_message) else: enterprise_customer = consent_record.enterprise_customer elif not request.user.is_staff: raise PermissionDenied() # Retrieve context data again now that enterprise_customer logic has been run context_data = get_global_context(request, enterprise_customer) if not (enterprise_customer_uuid and success_url and failure_url): error_code = 'ENTGDS003' log_message = ( 'Error: one or more of the following values was falsy: ' 'enterprise_customer_uuid: {enterprise_customer_uuid}, ' 'success_url: {success_url}, ' 'failure_url: {failure_url} for course id {course_id}' 'The following error code was reported to user {userid}: {error_code}'.format( userid=request.user.id, enterprise_customer_uuid=enterprise_customer_uuid, success_url=success_url, failure_url=failure_url, error_code=error_code, course_id=course_id, ) ) return render_page_with_error_code_message(request, context_data, error_code, log_message) try: updated_context_dict = self.get_course_or_program_context( enterprise_customer, course_id=course_id, program_uuid=program_uuid ) context_data.update(updated_context_dict) except Http404: error_code = 'ENTGDS004' log_message = ( 'CourseCatalogApiServiceClient is improperly configured. ' 'Returned error code {error_code} to user {userid} ' 'and enterprise_customer {enterprise_customer} ' 'for course_id {course_id}'.format( error_code=error_code, userid=request.user.id, enterprise_customer=enterprise_customer.uuid, course_id=course_id, ) ) return render_page_with_error_code_message(request, context_data, error_code, log_message) item = 'course' if course_id else 'program' # Translators: bold_start and bold_end are HTML tags for specifying enterprise name in bold text. context_data.update({ 'consent_request_prompt': _( 'To access this {item}, you must first consent to share your learning achievements ' 'with {bold_start}{enterprise_customer_name}{bold_end}.' ).format( enterprise_customer_name=enterprise_customer.name, bold_start='<b>', bold_end='</b>', item=item, ), 'confirmation_alert_prompt': _( 'In order to start this {item} and use your discount, {bold_start}you must{bold_end} consent ' 'to share your {item} data with {enterprise_customer_name}.' ).format( enterprise_customer_name=enterprise_customer.name, bold_start='<b>', bold_end='</b>', item=item, ), 'redirect_url': success_url, 'failure_url': failure_url, 'defer_creation': request.GET.get('defer_creation') is not None, 'requested_permissions': [ _('your enrollment in this {item}').format(item=item), _('your learning progress'), _('course completion'), ], 'policy_link_template': '', }) platform_name = context_data['platform_name'] published_only = False if self.preview_mode else True enterprise_consent_page = enterprise_customer.get_data_sharing_consent_text_overrides( published_only=published_only ) if enterprise_consent_page: context_data.update(self.get_context_from_db(enterprise_consent_page, platform_name, item, context_data)) else: context_data.update(self.get_default_context(enterprise_customer, platform_name)) return render(request, 'enterprise/grant_data_sharing_permissions.html', context=context_data)
def post(self, request): """ Process the above form. """ enterprise_uuid = request.POST.get('enterprise_customer_uuid') success_url = request.POST.get('redirect_url') failure_url = request.POST.get('failure_url') course_id = request.POST.get('course_id', '') program_uuid = request.POST.get('program_uuid', '') enterprise_customer = get_enterprise_customer_or_404(enterprise_uuid) context_data = get_global_context(request, enterprise_customer) if not (enterprise_uuid and success_url and failure_url): error_code = 'ENTGDS005' log_message = ( 'Error: one or more of the following values was falsy: ' 'enterprise_uuid: {enterprise_uuid}, ' 'success_url: {success_url}, ' 'failure_url: {failure_url} for course_id {course_id}. ' 'The following error code was reported to the user {userid}: {error_code}'.format( userid=request.user.id, enterprise_uuid=enterprise_uuid, success_url=success_url, failure_url=failure_url, error_code=error_code, course_id=course_id, ) ) return render_page_with_error_code_message(request, context_data, error_code, log_message) if not self.course_or_program_exist(course_id, program_uuid): error_code = 'ENTGDS006' log_message = ( 'Neither the course with course_id: {course_id} ' 'or program with {program_uuid} exist for ' 'enterprise customer {enterprise_uuid}' 'Error code {error_code} presented to user {userid}'.format( course_id=course_id, program_uuid=program_uuid, error_code=error_code, userid=request.user.id, enterprise_uuid=enterprise_uuid, ) ) return render_page_with_error_code_message(request, context_data, error_code, log_message) consent_record = get_data_sharing_consent( request.user.username, enterprise_uuid, program_uuid=program_uuid, course_id=course_id ) if consent_record is None: error_code = 'ENTGDS007' log_message = ( 'The was a problem with the consent record of user {userid} with ' 'enterprise_uuid {enterprise_uuid}. consent_record has a value ' 'of {consent_record} and a ' 'value for course_id {course_id}. ' 'Error code {error_code} presented to user'.format( userid=request.user.id, enterprise_uuid=enterprise_uuid, consent_record=consent_record, error_code=error_code, course_id=course_id, ) ) return render_page_with_error_code_message(request, context_data, error_code, log_message) defer_creation = request.POST.get('defer_creation') consent_provided = bool(request.POST.get('data_sharing_consent', False)) if defer_creation is None and consent_record.consent_required(): if course_id: enterprise_customer_user, __ = EnterpriseCustomerUser.objects.get_or_create( enterprise_customer=consent_record.enterprise_customer, user_id=request.user.id ) enterprise_customer_user.update_session(request) __, created = EnterpriseCourseEnrollment.objects.get_or_create( enterprise_customer_user=enterprise_customer_user, course_id=course_id, ) if created: track_enrollment('data-consent-page-enrollment', request.user.id, course_id, request.path) consent_record.granted = consent_provided consent_record.save() return redirect(success_url if consent_provided else failure_url)
def get(self, request, enterprise_uuid, course_id): """ Handle the enrollment of enterprise learner in the provided course. Based on `enterprise_uuid` in URL, the view will decide which enterprise customer's course enrollment record should be created. Depending on the value of query parameter `course_mode` then learner will be either redirected to LMS dashboard for audit modes or redirected to ecommerce basket flow for payment of premium modes. """ enrollment_course_mode = request.GET.get('course_mode') enterprise_catalog_uuid = request.GET.get('catalog') # Redirect the learner to LMS dashboard in case no course mode is # provided as query parameter `course_mode` if not enrollment_course_mode: return redirect(LMS_DASHBOARD_URL) enrollment_api_client = EnrollmentApiClient() course_modes = enrollment_api_client.get_course_modes(course_id) # Verify that the request user belongs to the enterprise against the # provided `enterprise_uuid`. enterprise_customer = get_enterprise_customer_or_404(enterprise_uuid) enterprise_customer_user = get_enterprise_customer_user(request.user.id, enterprise_customer.uuid) if not course_modes: context_data = get_global_context(request, enterprise_customer) error_code = 'ENTHCE000' log_message = ( 'No course_modes for course_id {course_id} for enterprise_catalog_uuid ' '{enterprise_catalog_uuid}.' 'The following error was presented to ' 'user {userid}: {error_code}'.format( userid=request.user.id, enterprise_catalog_uuid=enterprise_catalog_uuid, course_id=course_id, error_code=error_code ) ) return render_page_with_error_code_message(request, context_data, error_code, log_message) selected_course_mode = None for course_mode in course_modes: if course_mode['slug'] == enrollment_course_mode: selected_course_mode = course_mode break if not selected_course_mode: return redirect(LMS_DASHBOARD_URL) # Create the Enterprise backend database records for this course # enrollment __, created = EnterpriseCourseEnrollment.objects.get_or_create( enterprise_customer_user=enterprise_customer_user, course_id=course_id, ) if created: track_enrollment('course-landing-page-enrollment', request.user.id, course_id, request.get_full_path()) DataSharingConsent.objects.update_or_create( username=enterprise_customer_user.username, course_id=course_id, enterprise_customer=enterprise_customer_user.enterprise_customer, defaults={ 'granted': True }, ) audit_modes = getattr(settings, 'ENTERPRISE_COURSE_ENROLLMENT_AUDIT_MODES', ['audit', 'honor']) if selected_course_mode['slug'] in audit_modes: # In case of Audit course modes enroll the learner directly through # enrollment API client and redirect the learner to dashboard. enrollment_api_client.enroll_user_in_course( request.user.username, course_id, selected_course_mode['slug'] ) return redirect(LMS_COURSEWARE_URL.format(course_id=course_id)) # redirect the enterprise learner to the ecommerce flow in LMS # Note: LMS start flow automatically detects the paid mode premium_flow = LMS_START_PREMIUM_COURSE_FLOW_URL.format(course_id=course_id) if enterprise_catalog_uuid: premium_flow += '?catalog={catalog_uuid}'.format( catalog_uuid=enterprise_catalog_uuid ) return redirect(premium_flow)
def set_final_prices(self, modes, request): """ Set the final discounted price on each premium mode. """ result = [] for mode in modes: if mode['premium']: mode['final_price'] = EcommerceApiClient(request.user).get_course_final_price( mode=mode, enterprise_catalog_uuid=request.GET.get( 'catalog' ) if request.method == 'GET' else None, ) result.append(mode) return result
def get_available_course_modes(self, request, course_run_id, enterprise_catalog): """ Return the available course modes for the course run. The provided EnterpriseCustomerCatalog is used to filter and order the course modes returned using the EnterpriseCustomerCatalog's field "enabled_course_modes". """ modes = EnrollmentApiClient().get_course_modes(course_run_id) if not modes: LOGGER.warning('Unable to get course modes for course run id {course_run_id}.'.format( course_run_id=course_run_id )) messages.add_generic_info_message_for_error(request) if enterprise_catalog: # filter and order course modes according to the enterprise catalog modes = [mode for mode in modes if mode['slug'] in enterprise_catalog.enabled_course_modes] modes.sort(key=lambda course_mode: enterprise_catalog.enabled_course_modes.index(course_mode['slug'])) if not modes: LOGGER.info( 'No matching course modes found for course run {course_run_id} in ' 'EnterpriseCustomerCatalog [{enterprise_catalog_uuid}]'.format( course_run_id=course_run_id, enterprise_catalog_uuid=enterprise_catalog, ) ) messages.add_generic_info_message_for_error(request) return modes
def get_base_details(self, request, enterprise_uuid, course_run_id): """ Retrieve fundamental details used by both POST and GET versions of this view. Specifically, take an EnterpriseCustomer UUID and a course run ID, and transform those into an actual EnterpriseCustomer, a set of details about the course, and a list of the available course modes for that course run. """ enterprise_customer = get_enterprise_customer_or_404(enterprise_uuid) # If the catalog query parameter was provided, we need to scope # this request to the specified EnterpriseCustomerCatalog. enterprise_catalog_uuid = request.GET.get('catalog') enterprise_catalog = None if enterprise_catalog_uuid: try: enterprise_catalog_uuid = UUID(enterprise_catalog_uuid) enterprise_catalog = enterprise_customer.enterprise_customer_catalogs.get( uuid=enterprise_catalog_uuid ) except (ValueError, EnterpriseCustomerCatalog.DoesNotExist): LOGGER.warning( 'EnterpriseCustomerCatalog [{enterprise_catalog_uuid}] does not exist'.format( enterprise_catalog_uuid=enterprise_catalog_uuid, ) ) messages.add_generic_info_message_for_error(request) course = None course_run = None course_modes = [] if enterprise_catalog: course, course_run = enterprise_catalog.get_course_and_course_run(course_run_id) else: try: course, course_run = CourseCatalogApiServiceClient( enterprise_customer.site ).get_course_and_course_run(course_run_id) except ImproperlyConfigured: LOGGER.warning('CourseCatalogApiServiceClient is improperly configured.') messages.add_generic_info_message_for_error(request) return enterprise_customer, course, course_run, course_modes if not course or not course_run: course_id = course['key'] if course else "Not Found" course_title = course['title'] if course else "Not Found" course_run_title = course_run['title'] if course_run else "Not Found" enterprise_catalog_title = enterprise_catalog.title if enterprise_catalog else "Not Found" # The specified course either does not exist in the specified # EnterpriseCustomerCatalog, or does not exist at all in the # discovery service. LOGGER.warning( 'Failed to fetch details for course "{course_title}" [{course_id}] ' 'or course run "{course_run_title}" [{course_run_id}] ' 'for enterprise "{enterprise_name}" [{enterprise_uuid}] ' 'with catalog "{enterprise_catalog_title}" [{enterprise_catalog_uuid}]'.format( course_title=course_title, course_id=course_id, course_run_title=course_run_title, course_run_id=course_run_id, enterprise_name=enterprise_customer.name, enterprise_uuid=enterprise_customer.uuid, enterprise_catalog_title=enterprise_catalog_title, enterprise_catalog_uuid=enterprise_catalog_uuid, ) ) messages.add_generic_info_message_for_error(request) return enterprise_customer, course, course_run, course_modes if enterprise_catalog_uuid and not enterprise_catalog: # A catalog query parameter was given, but the specified # EnterpriseCustomerCatalog does not exist, so just return and # display the generic error message. return enterprise_customer, course, course_run, course_modes modes = self.get_available_course_modes(request, course_run_id, enterprise_catalog) audit_modes = getattr( settings, 'ENTERPRISE_COURSE_ENROLLMENT_AUDIT_MODES', ['audit', 'honor'] ) for mode in modes: if mode['min_price']: price_text = get_price_text(mode['min_price'], request) else: price_text = _('FREE') if mode['slug'] in audit_modes: description = _('Not eligible for a certificate.') else: description = _('Earn a verified certificate!') course_modes.append({ 'mode': mode['slug'], 'min_price': mode['min_price'], 'sku': mode['sku'], 'title': mode['name'], 'original_price': price_text, 'final_price': price_text, 'description': description, 'premium': mode['slug'] not in audit_modes }) return enterprise_customer, course, course_run, course_modes
def get_enterprise_course_enrollment_page( self, request, enterprise_customer, course, course_run, course_modes, enterprise_course_enrollment, data_sharing_consent ): """ Render enterprise-specific course track selection page. """ context_data = get_global_context(request, enterprise_customer) enterprise_catalog_uuid = request.GET.get( 'catalog' ) if request.method == 'GET' else None html_template_for_rendering = ENTERPRISE_GENERAL_ERROR_PAGE if course and course_run: course_enrollable = True course_start_date = '' course_in_future = False organization_name = '' organization_logo = '' expected_learning_items = course['expected_learning_items'] # Parse organization name and logo. if course['owners']: # The owners key contains the organizations associated with the course. # We pick the first one in the list here to meet UX requirements. organization = course['owners'][0] organization_name = organization['name'] organization_logo = organization['logo_image_url'] course_title = course_run['title'] course_short_description = course_run['short_description'] or '' course_full_description = clean_html_for_template_rendering(course_run['full_description'] or '') course_pacing = self.PACING_FORMAT.get(course_run['pacing_type'], '') if course_run['start']: course_start_date = parse(course_run['start']).strftime('%B %d, %Y') now = datetime.datetime.now(pytz.UTC) course_in_future = parse(course_run['start']) > now course_level_type = course_run.get('level_type', '') staff = course_run['staff'] # Format the course effort string using the min/max effort fields for the course run. course_effort = ungettext_min_max( '{} hour per week', '{} hours per week', '{}-{} hours per week', course_run['min_effort'] or None, course_run['max_effort'] or None, ) or '' # Parse course run image. course_run_image = course_run['image'] or {} course_image_uri = course_run_image.get('src', '') # Retrieve the enterprise-discounted price from ecommerce. course_modes = self.set_final_prices(course_modes, request) premium_modes = [mode for mode in course_modes if mode['premium']] # Filter audit course modes. course_modes = filter_audit_course_modes(enterprise_customer, course_modes) # Allows automatic assignment to a cohort upon enrollment. cohort = request.GET.get('cohort') # Add a message to the message display queue if the learner # has gone through the data sharing consent flow and declined # to give data sharing consent. if enterprise_course_enrollment and not data_sharing_consent.granted: messages.add_consent_declined_message(request, enterprise_customer, course_run.get('title', '')) if not is_course_run_enrollable(course_run): messages.add_unenrollable_item_message(request, 'course') course_enrollable = False context_data.update({ 'course_enrollable': course_enrollable, 'course_title': course_title, 'course_short_description': course_short_description, 'course_pacing': course_pacing, 'course_start_date': course_start_date, 'course_in_future': course_in_future, 'course_image_uri': course_image_uri, 'course_modes': course_modes, 'course_effort': course_effort, 'course_full_description': course_full_description, 'cohort': cohort, 'organization_logo': organization_logo, 'organization_name': organization_name, 'course_level_type': course_level_type, 'premium_modes': premium_modes, 'expected_learning_items': expected_learning_items, 'catalog': enterprise_catalog_uuid, 'staff': staff, 'discount_text': _('Discount provided by {strong_start}{enterprise_customer_name}{strong_end}').format( enterprise_customer_name=enterprise_customer.name, strong_start='<strong>', strong_end='</strong>', ), 'hide_course_original_price': enterprise_customer.hide_course_original_price }) html_template_for_rendering = 'enterprise/enterprise_course_enrollment_page.html' context_data.update({ 'page_title': _('Confirm your course'), 'confirmation_text': _('Confirm your course'), 'starts_at_text': _('Starts'), 'view_course_details_text': _('View Course Details'), 'select_mode_text': _('Please select one:'), 'price_text': _('Price'), 'continue_link_text': _('Continue'), 'level_text': _('Level'), 'effort_text': _('Effort'), 'close_modal_button_text': _('Close'), 'expected_learning_items_text': _("What you'll learn"), 'course_full_description_text': _('About This Course'), 'staff_text': _('Course Staff'), }) return render(request, html_template_for_rendering, context=context_data)
def post(self, request, enterprise_uuid, course_id): """ Process a submitted track selection form for the enterprise. """ enterprise_customer, course, course_run, course_modes = self.get_base_details( request, enterprise_uuid, course_id ) # Create a link between the user and the enterprise customer if it does not already exist. enterprise_customer_user, __ = EnterpriseCustomerUser.objects.get_or_create( enterprise_customer=enterprise_customer, user_id=request.user.id ) enterprise_customer_user.update_session(request) data_sharing_consent = DataSharingConsent.objects.proxied_get( username=enterprise_customer_user.username, course_id=course_id, enterprise_customer=enterprise_customer ) try: enterprise_course_enrollment = EnterpriseCourseEnrollment.objects.get( enterprise_customer_user__enterprise_customer=enterprise_customer, enterprise_customer_user__user_id=request.user.id, course_id=course_id ) except EnterpriseCourseEnrollment.DoesNotExist: enterprise_course_enrollment = None enterprise_catalog_uuid = request.POST.get('catalog') selected_course_mode_name = request.POST.get('course_mode') cohort_name = request.POST.get('cohort') selected_course_mode = None for course_mode in course_modes: if course_mode['mode'] == selected_course_mode_name: selected_course_mode = course_mode break if not selected_course_mode: return self.get_enterprise_course_enrollment_page( request, enterprise_customer, course, course_run, course_modes, enterprise_course_enrollment, data_sharing_consent ) user_consent_needed = get_data_sharing_consent( enterprise_customer_user.username, enterprise_customer.uuid, course_id=course_id ).consent_required() if not selected_course_mode.get('premium') and not user_consent_needed: # For the audit course modes (audit, honor), where DSC is not # required, enroll the learner directly through enrollment API # client and redirect the learner to LMS courseware page. if not enterprise_course_enrollment: # Create the Enterprise backend database records for this course enrollment. enterprise_course_enrollment = EnterpriseCourseEnrollment.objects.create( enterprise_customer_user=enterprise_customer_user, course_id=course_id, ) track_enrollment('course-landing-page-enrollment', request.user.id, course_id, request.get_full_path()) client = EnrollmentApiClient() client.enroll_user_in_course( request.user.username, course_id, selected_course_mode_name, cohort=cohort_name ) return redirect(LMS_COURSEWARE_URL.format(course_id=course_id)) if user_consent_needed: # For the audit course modes (audit, honor) or for the premium # course modes (Verified, Prof Ed) where DSC is required, redirect # the learner to course specific DSC with enterprise UUID from # there the learner will be directed to the ecommerce flow after # providing DSC. query_string_params = { 'course_mode': selected_course_mode_name, } if enterprise_catalog_uuid: query_string_params.update({'catalog': enterprise_catalog_uuid}) next_url = '{handle_consent_enrollment_url}?{query_string}'.format( handle_consent_enrollment_url=reverse( 'enterprise_handle_consent_enrollment', args=[enterprise_customer.uuid, course_id] ), query_string=urlencode(query_string_params) ) failure_url = reverse('enterprise_course_run_enrollment_page', args=[enterprise_customer.uuid, course_id]) if request.META['QUERY_STRING']: # Preserve all querystring parameters in the request to build # failure url, so that learner views the same enterprise course # enrollment page (after redirect) as for the first time. # Since this is a POST view so use `request.META` to get # querystring instead of `request.GET`. # https://docs.djangoproject.com/en/1.11/ref/request-response/#django.http.HttpRequest.META failure_url = '{course_enrollment_url}?{query_string}'.format( course_enrollment_url=reverse( 'enterprise_course_run_enrollment_page', args=[enterprise_customer.uuid, course_id] ), query_string=request.META['QUERY_STRING'] ) return redirect( '{grant_data_sharing_url}?{params}'.format( grant_data_sharing_url=reverse('grant_data_sharing_permissions'), params=urlencode( { 'next': next_url, 'failure_url': failure_url, 'enterprise_customer_uuid': enterprise_customer.uuid, 'course_id': course_id, } ) ) ) # For the premium course modes (Verified, Prof Ed) where DSC is # not required, redirect the enterprise learner to the ecommerce # flow in LMS. # Note: LMS start flow automatically detects the paid mode premium_flow = LMS_START_PREMIUM_COURSE_FLOW_URL.format(course_id=course_id) if enterprise_catalog_uuid: premium_flow += '?catalog={catalog_uuid}'.format( catalog_uuid=enterprise_catalog_uuid ) return redirect(premium_flow)
def get(self, request, enterprise_uuid, course_id): """ Show course track selection page for the enterprise. Based on `enterprise_uuid` in URL, the view will decide which enterprise customer's course enrollment page is to use. Unauthenticated learners will be redirected to enterprise-linked SSO. A 404 will be raised if any of the following conditions are met: * No enterprise customer uuid kwarg `enterprise_uuid` in request. * No enterprise customer found against the enterprise customer uuid `enterprise_uuid` in the request kwargs. * No course is found in database against the provided `course_id`. """ # Check to see if access to the course run is restricted for this user. embargo_url = EmbargoApiClient.redirect_if_blocked([course_id], request.user, get_ip(request), request.path) if embargo_url: return redirect(embargo_url) enterprise_customer, course, course_run, modes = self.get_base_details( request, enterprise_uuid, course_id ) enterprise_customer_user = get_enterprise_customer_user(request.user.id, enterprise_uuid) data_sharing_consent = DataSharingConsent.objects.proxied_get( username=enterprise_customer_user.username, course_id=course_id, enterprise_customer=enterprise_customer ) enrollment_client = EnrollmentApiClient() enrolled_course = enrollment_client.get_course_enrollment(request.user.username, course_id) try: enterprise_course_enrollment = EnterpriseCourseEnrollment.objects.get( enterprise_customer_user__enterprise_customer=enterprise_customer, enterprise_customer_user__user_id=request.user.id, course_id=course_id ) except EnterpriseCourseEnrollment.DoesNotExist: enterprise_course_enrollment = None if enrolled_course and enterprise_course_enrollment: # The user is already enrolled in the course through the Enterprise Customer, so redirect to the course # info page. return redirect(LMS_COURSEWARE_URL.format(course_id=course_id)) return self.get_enterprise_course_enrollment_page( request, enterprise_customer, course, course_run, modes, enterprise_course_enrollment, data_sharing_consent, )
def extend_course(course, enterprise_customer, request): """ Extend a course with more details needed for the program landing page. In particular, we add the following: * `course_image_uri` * `course_title` * `course_level_type` * `course_short_description` * `course_full_description` * `course_effort` * `expected_learning_items` * `staff` """ course_run_id = course['course_runs'][0]['key'] try: catalog_api_client = CourseCatalogApiServiceClient(enterprise_customer.site) except ImproperlyConfigured: error_code = 'ENTPEV000' LOGGER.error( 'CourseCatalogApiServiceClient is improperly configured. ' 'Returned error code {error_code} to user {userid} ' 'and enterprise_customer {enterprise_customer} ' 'for course_run_id {course_run_id}'.format( error_code=error_code, userid=request.user.id, enterprise_customer=enterprise_customer.uuid, course_run_id=course_run_id, ) ) messages.add_generic_error_message_with_code(request, error_code) return ({}, error_code) course_details, course_run_details = catalog_api_client.get_course_and_course_run(course_run_id) if not course_details or not course_run_details: error_code = 'ENTPEV001' LOGGER.error( 'User {userid} of enterprise customer {enterprise_customer} encountered an error.' 'No course_details or course_run_details found for ' 'course_run_id {course_run_id}. ' 'The following error code reported to the user: {error_code}'.format( userid=request.user.id, enterprise_customer=enterprise_customer.uuid, course_run_id=course_run_id, error_code=error_code, ) ) messages.add_generic_error_message_with_code(request, error_code) return ({}, error_code) weeks_to_complete = course_run_details['weeks_to_complete'] course_run_image = course_run_details['image'] or {} course.update({ 'course_image_uri': course_run_image.get('src', ''), 'course_title': course_run_details['title'], 'course_level_type': course_run_details.get('level_type', ''), 'course_short_description': course_run_details['short_description'] or '', 'course_full_description': clean_html_for_template_rendering(course_run_details['full_description'] or ''), 'expected_learning_items': course_details.get('expected_learning_items', []), 'staff': course_run_details.get('staff', []), 'course_effort': ungettext_min_max( '{} hour per week', '{} hours per week', '{}-{} hours per week', course_run_details['min_effort'] or None, course_run_details['max_effort'] or None, ) or '', 'weeks_to_complete': ungettext( '{} week', '{} weeks', weeks_to_complete ).format(weeks_to_complete) if weeks_to_complete else '', }) return course, None
def get_program_details(self, request, program_uuid, enterprise_customer): """ Retrieve fundamental details used by both POST and GET versions of this view. Specifically: * Take the program UUID and get specific details about the program. * Determine whether the learner is enrolled in the program. * Determine whether the learner is certificate eligible for the program. """ try: course_catalog_api_client = CourseCatalogApiServiceClient(enterprise_customer.site) except ImproperlyConfigured: error_code = 'ENTPEV002' LOGGER.error( 'CourseCatalogApiServiceClient is improperly configured. ' 'Returned error code {error_code} to user {userid} ' 'and enterprise_customer {enterprise_customer} ' 'for program {program_uuid}'.format( error_code=error_code, userid=request.user.id, enterprise_customer=enterprise_customer.uuid, program_uuid=program_uuid, ) ) messages.add_generic_error_message_with_code(request, error_code) return ({}, error_code) program_details = course_catalog_api_client.get_program_by_uuid(program_uuid) if program_details is None: error_code = 'ENTPEV003' LOGGER.error( 'User {userid} of enterprise customer {enterprise_customer} encountered an error. ' 'program_details is None for program_uuid {program_uuid}. ' 'Returned error code {error_code} to user'.format( userid=request.user.id, enterprise_customer=enterprise_customer.uuid, program_uuid=program_uuid, error_code=error_code, ) ) messages.add_generic_error_message_with_code(request, error_code) return ({}, error_code) program_type = course_catalog_api_client.get_program_type_by_slug(slugify(program_details['type'])) if program_type is None: error_code = 'ENTPEV004' LOGGER.error( 'User {userid} of enterprise customer {enterprise_customer} encountered an error. ' 'program_type is None for program_details of program_uuid {program_uuid}. ' 'Returned error code {error_code} to user'.format( userid=request.user.id, enterprise_customer=enterprise_customer.uuid, program_uuid=program_uuid, error_code=error_code, ) ) messages.add_generic_error_message_with_code(request, error_code) return ({}, error_code) # Extend our program details with context we'll need for display or for deciding redirects. program_details = ProgramDataExtender(program_details, request.user).extend() # TODO: Upstream this additional context to the platform's `ProgramDataExtender` so we can avoid this here. program_details['enrolled_in_program'] = False enrollment_count = 0 for extended_course in program_details['courses']: # We need to extend our course data further for modals and other displays. extended_data, error_code = ProgramEnrollmentView.extend_course( extended_course, enterprise_customer, request ) if error_code: return ({}, error_code) extended_course.update(extended_data) # We're enrolled in the program if we have certificate-eligible enrollment in even 1 of its courses. extended_course_run = extended_course['course_runs'][0] if extended_course_run['is_enrolled'] and extended_course_run['upgrade_url'] is None: program_details['enrolled_in_program'] = True enrollment_count += 1 # We're certificate eligible for the program if we have certificate-eligible enrollment in all of its courses. program_details['certificate_eligible_for_program'] = (enrollment_count == len(program_details['courses'])) program_details['type_details'] = program_type return program_details, None
def get_enterprise_program_enrollment_page(self, request, enterprise_customer, program_details): """ Render Enterprise-specific program enrollment page. """ # Safely make the assumption that we can use the first authoring organization. organizations = program_details['authoring_organizations'] organization = organizations[0] if organizations else {} platform_name = get_configuration_value('PLATFORM_NAME', settings.PLATFORM_NAME) program_title = program_details['title'] program_type_details = program_details['type_details'] program_type = program_type_details['name'] # Make any modifications for singular/plural-dependent text. program_courses = program_details['courses'] course_count = len(program_courses) course_count_text = ungettext( '{count} Course', '{count} Courses', course_count, ).format(count=course_count) effort_info_text = ungettext_min_max( '{} hour per week, per course', '{} hours per week, per course', _('{}-{} hours per week, per course'), program_details.get('min_hours_effort_per_week'), program_details.get('max_hours_effort_per_week'), ) length_info_text = ungettext_min_max( '{} week per course', '{} weeks per course', _('{}-{} weeks per course'), program_details.get('weeks_to_complete_min'), program_details.get('weeks_to_complete_max'), ) # Update some enrollment-related text requirements. if program_details['enrolled_in_program']: purchase_action = _('Purchase all unenrolled courses') item = _('enrollment') else: purchase_action = _('Pursue the program') item = _('program enrollment') # Add any DSC warning messages. program_data_sharing_consent = get_data_sharing_consent( request.user.username, enterprise_customer.uuid, program_uuid=program_details['uuid'], ) if program_data_sharing_consent.exists and not program_data_sharing_consent.granted: messages.add_consent_declined_message(request, enterprise_customer, program_title) discount_data = program_details.get('discount_data', {}) one_click_purchase_eligibility = program_details.get('is_learner_eligible_for_one_click_purchase', False) # The following messages shouldn't both appear at the same time, and we prefer the eligibility message. if not one_click_purchase_eligibility: messages.add_unenrollable_item_message(request, 'program') elif discount_data.get('total_incl_tax_excl_discounts') is None: messages.add_missing_price_information_message(request, program_title) context_data = get_global_context(request, enterprise_customer) context_data.update({ 'enrolled_in_course_and_paid_text': _('enrolled'), 'enrolled_in_course_and_unpaid_text': _('already enrolled, must pay for certificate'), 'expected_learning_items_text': _("What you'll learn"), 'expected_learning_items_show_count': 2, 'corporate_endorsements_text': _('Real Career Impact'), 'corporate_endorsements_show_count': 1, 'see_more_text': _('See More'), 'see_less_text': _('See Less'), 'confirm_button_text': _('Confirm Program'), 'summary_header': _('Program Summary'), 'price_text': _('Price'), 'length_text': _('Length'), 'effort_text': _('Effort'), 'level_text': _('Level'), 'course_full_description_text': _('About This Course'), 'staff_text': _('Course Staff'), 'close_modal_button_text': _('Close'), 'program_not_eligible_for_one_click_purchase_text': _('Program not eligible for one-click purchase.'), 'program_type_description_header': _('What is an {platform_name} {program_type}?').format( platform_name=platform_name, program_type=program_type, ), 'platform_description_header': _('What is {platform_name}?').format( platform_name=platform_name ), 'organization_name': organization.get('name'), 'organization_logo': organization.get('logo_image_url'), 'organization_text': _('Presented by {organization}').format(organization=organization.get('name')), 'page_title': _('Confirm your {item}').format(item=item), 'program_type_logo': program_type_details['logo_image'].get('medium', {}).get('url', ''), 'program_type': program_type, 'program_type_description': get_program_type_description(program_type), 'program_title': program_title, 'program_subtitle': program_details['subtitle'], 'program_overview': program_details['overview'], 'program_price': get_price_text(discount_data.get('total_incl_tax_excl_discounts', 0), request), 'program_discounted_price': get_price_text(discount_data.get('total_incl_tax', 0), request), 'is_discounted': discount_data.get('is_discounted', False), 'courses': program_courses, 'item_bullet_points': [ _('Credit- and Certificate-eligible'), _('Self-paced; courses can be taken in any order'), ], 'purchase_text': _('{purchase_action} for').format(purchase_action=purchase_action), 'expected_learning_items': program_details['expected_learning_items'], 'corporate_endorsements': program_details['corporate_endorsements'], 'course_count_text': course_count_text, 'length_info_text': length_info_text, 'effort_info_text': effort_info_text, 'is_learner_eligible_for_one_click_purchase': one_click_purchase_eligibility, }) return render(request, 'enterprise/enterprise_program_enrollment_page.html', context=context_data)
def get(self, request, enterprise_uuid, program_uuid): """ Show Program Landing page for the Enterprise's Program. Render the Enterprise's Program Enrollment page for a specific program. The Enterprise and Program are both selected by their respective UUIDs. Unauthenticated learners will be redirected to enterprise-linked SSO. A 404 will be raised if any of the following conditions are met: * No enterprise customer UUID query parameter ``enterprise_uuid`` found in request. * No enterprise customer found against the enterprise customer uuid ``enterprise_uuid`` in the request kwargs. * No Program can be found given ``program_uuid`` either at all or associated with the Enterprise.. """ verify_edx_resources() enterprise_customer = get_enterprise_customer_or_404(enterprise_uuid) context_data = get_global_context(request, enterprise_customer) program_details, error_code = self.get_program_details(request, program_uuid, enterprise_customer) if error_code: return render( request, ENTERPRISE_GENERAL_ERROR_PAGE, context=context_data, status=404, ) if program_details['certificate_eligible_for_program']: # The user is already enrolled in the program, so redirect to the program's dashboard. return redirect(LMS_PROGRAMS_DASHBOARD_URL.format(uuid=program_uuid)) # Check to see if access to any of the course runs in the program are restricted for this user. course_run_ids = [] for course in program_details['courses']: for course_run in course['course_runs']: course_run_ids.append(course_run['key']) embargo_url = EmbargoApiClient.redirect_if_blocked(course_run_ids, request.user, get_ip(request), request.path) if embargo_url: return redirect(embargo_url) return self.get_enterprise_program_enrollment_page(request, enterprise_customer, program_details)
def post(self, request, enterprise_uuid, program_uuid): """ Process a submitted track selection form for the enterprise. """ verify_edx_resources() # Create a link between the user and the enterprise customer if it does not already exist. enterprise_customer = get_enterprise_customer_or_404(enterprise_uuid) with transaction.atomic(): enterprise_customer_user, __ = EnterpriseCustomerUser.objects.get_or_create( enterprise_customer=enterprise_customer, user_id=request.user.id ) enterprise_customer_user.update_session(request) context_data = get_global_context(request, enterprise_customer) program_details, error_code = self.get_program_details(request, program_uuid, enterprise_customer) if error_code: return render( request, ENTERPRISE_GENERAL_ERROR_PAGE, context=context_data, status=404, ) if program_details['certificate_eligible_for_program']: # The user is already enrolled in the program, so redirect to the program's dashboard. return redirect(LMS_PROGRAMS_DASHBOARD_URL.format(uuid=program_uuid)) basket_page = '{basket_url}?{params}'.format( basket_url=BASKET_URL, params=urlencode( [tuple(['sku', sku]) for sku in program_details['skus']] + [tuple(['bundle', program_uuid])] ) ) if get_data_sharing_consent( enterprise_customer_user.username, enterprise_customer.uuid, program_uuid=program_uuid, ).consent_required(): return redirect( '{grant_data_sharing_url}?{params}'.format( grant_data_sharing_url=reverse('grant_data_sharing_permissions'), params=urlencode( { 'next': basket_page, 'failure_url': reverse( 'enterprise_program_enrollment_page', args=[enterprise_customer.uuid, program_uuid] ), 'enterprise_customer_uuid': enterprise_customer.uuid, 'program_uuid': program_uuid, } ) ) ) return redirect(basket_page)
def get_path_variables(**kwargs): """ Get the base variables for any view to route to. Currently gets: - `enterprise_uuid` - the UUID of the enterprise customer. - `course_run_id` - the ID of the course, if applicable. - `program_uuid` - the UUID of the program, if applicable. """ enterprise_customer_uuid = kwargs.get('enterprise_uuid', '') course_run_id = kwargs.get('course_id', '') course_key = kwargs.get('course_key', '') program_uuid = kwargs.get('program_uuid', '') return enterprise_customer_uuid, course_run_id, course_key, program_uuid
def get_course_run_id(user, enterprise_customer, course_key): """ User is requesting a course, we need to translate that into the current course run. :param user: :param enterprise_customer: :param course_key: :return: course_run_id """ try: course = CourseCatalogApiServiceClient(enterprise_customer.site).get_course_details(course_key) except ImproperlyConfigured: raise Http404 users_all_enrolled_courses = EnrollmentApiClient().get_enrolled_courses(user.username) users_active_course_runs = get_active_course_runs( course, users_all_enrolled_courses ) if users_all_enrolled_courses else [] course_run = get_current_course_run(course, users_active_course_runs) if course_run: course_run_id = course_run['key'] return course_run_id else: raise Http404
def eligible_for_direct_audit_enrollment(self, request, enterprise_customer, resource_id, course_key=None): """ Return whether a request is eligible for direct audit enrollment for a particular enterprise customer. 'resource_id' can be either course_run_id or program_uuid. We check for the following criteria: - The `audit` query parameter. - The user's being routed to the course enrollment landing page. - The customer's catalog contains the course in question. - The audit track is an available mode for the course. """ course_identifier = course_key if course_key else resource_id # Return it in one big statement to utilize short-circuiting behavior. Avoid the API call if possible. return request.GET.get('audit') and \ request.path == self.COURSE_ENROLLMENT_VIEW_URL.format(enterprise_customer.uuid, course_identifier) and \ enterprise_customer.catalog_contains_course(resource_id) and \ EnrollmentApiClient().has_course_mode(resource_id, 'audit')
def redirect(self, request, *args, **kwargs): """ Redirects to the appropriate view depending on where the user came from. """ enterprise_customer_uuid, course_run_id, course_key, program_uuid = RouterView.get_path_variables(**kwargs) resource_id = course_key or course_run_id or program_uuid # Replace enterprise UUID and resource ID with '{}', to easily match with a path in RouterView.VIEWS. Example: # /enterprise/fake-uuid/course/course-v1:cool+course+2017/enroll/ -> /enterprise/{}/course/{}/enroll/ path = re.sub('{}|{}'.format(enterprise_customer_uuid, re.escape(resource_id)), '{}', request.path) # Remove course_key from kwargs if it exists because delegate views are not expecting it. kwargs.pop('course_key', None) return self.VIEWS[path].as_view()(request, *args, **kwargs)
def get(self, request, *args, **kwargs): """ Run some custom GET logic for Enterprise workflows before routing the user through existing views. In particular, before routing to existing views: - If the requested resource is a course, find the current course run for that course, and make that course run the requested resource instead. - Look to see whether a request is eligible for direct audit enrollment, and if so, directly enroll the user. """ enterprise_customer_uuid, course_run_id, course_key, program_uuid = RouterView.get_path_variables(**kwargs) enterprise_customer = get_enterprise_customer_or_404(enterprise_customer_uuid) if course_key: try: course_run_id = RouterView.get_course_run_id(request.user, enterprise_customer, course_key) except Http404: context_data = get_global_context(request, enterprise_customer) error_code = 'ENTRV000' log_message = ( 'Could not find course run with id {course_run_id} ' 'for course key {course_key} and program_uuid {program_uuid} ' 'for enterprise_customer_uuid {enterprise_customer_uuid} ' 'Returned error code {error_code} to user {userid}'.format( course_key=course_key, course_run_id=course_run_id, enterprise_customer_uuid=enterprise_customer_uuid, error_code=error_code, userid=request.user.id, program_uuid=program_uuid, ) ) return render_page_with_error_code_message(request, context_data, error_code, log_message) kwargs['course_id'] = course_run_id # Ensure that the link is saved to the database prior to making some call in a downstream view # which may need to know that the user belongs to an enterprise customer. with transaction.atomic(): enterprise_customer_user, __ = EnterpriseCustomerUser.objects.get_or_create( enterprise_customer=enterprise_customer, user_id=request.user.id ) enterprise_customer_user.update_session(request) # Directly enroll in audit mode if the request in question has full direct audit enrollment eligibility. resource_id = course_run_id or program_uuid if self.eligible_for_direct_audit_enrollment(request, enterprise_customer, resource_id, course_key): try: enterprise_customer_user.enroll(resource_id, 'audit', cohort=request.GET.get('cohort', None)) track_enrollment('direct-audit-enrollment', request.user.id, resource_id, request.get_full_path()) except (CourseEnrollmentDowngradeError, CourseEnrollmentPermissionError): pass # The courseware view logic will check for DSC requirements, and route to the DSC page if necessary. return redirect(LMS_COURSEWARE_URL.format(course_id=resource_id)) return self.redirect(request, *args, **kwargs)
def post(self, request, *args, **kwargs): """ Run some custom POST logic for Enterprise workflows before routing the user through existing views. """ # pylint: disable=unused-variable enterprise_customer_uuid, course_run_id, course_key, program_uuid = RouterView.get_path_variables(**kwargs) enterprise_customer = get_enterprise_customer_or_404(enterprise_customer_uuid) if course_key: context_data = get_global_context(request, enterprise_customer) try: kwargs['course_id'] = RouterView.get_course_run_id(request.user, enterprise_customer, course_key) except Http404: error_code = 'ENTRV001' log_message = ( 'Could not find course run with id {course_run_id} ' 'for course key {course_key} and ' 'for enterprise_customer_uuid {enterprise_customer_uuid} ' 'and program {program_uuid}. ' 'Returned error code {error_code} to user {userid}'.format( course_key=course_key, course_run_id=course_run_id, enterprise_customer_uuid=enterprise_customer_uuid, error_code=error_code, userid=request.user.id, program_uuid=program_uuid, ) ) return render_page_with_error_code_message(request, context_data, error_code, log_message) return self.redirect(request, *args, **kwargs)
def transmit_content_metadata(username, channel_code, channel_pk): """ Task to send content metadata to each linked integrated channel. Arguments: username (str): The username of the User to be used for making API requests to retrieve content metadata. channel_code (str): Capitalized identifier for the integrated channel. channel_pk (str): Primary key for identifying integrated channel. """ start = time.time() api_user = User.objects.get(username=username) integrated_channel = INTEGRATED_CHANNEL_CHOICES[channel_code].objects.get(pk=channel_pk) LOGGER.info('Transmitting content metadata to integrated channel using configuration: [%s]', integrated_channel) try: integrated_channel.transmit_content_metadata(api_user) except Exception: # pylint: disable=broad-except LOGGER.exception( 'Transmission of content metadata failed for user [%s] and for integrated ' 'channel with code [%s] and id [%s].', username, channel_code, channel_pk ) duration = time.time() - start LOGGER.info( 'Content metadata transmission task for integrated channel configuration [%s] took [%s] seconds', integrated_channel, duration )
def transmit_learner_data(username, channel_code, channel_pk): """ Task to send learner data to each linked integrated channel. Arguments: username (str): The username of the User to be used for making API requests for learner data. channel_code (str): Capitalized identifier for the integrated channel channel_pk (str): Primary key for identifying integrated channel """ start = time.time() api_user = User.objects.get(username=username) integrated_channel = INTEGRATED_CHANNEL_CHOICES[channel_code].objects.get(pk=channel_pk) LOGGER.info('Processing learners for integrated channel using configuration: [%s]', integrated_channel) # Note: learner data transmission code paths don't raise any uncaught exception, so we don't need a broad # try-except block here. integrated_channel.transmit_learner_data(api_user) duration = time.time() - start LOGGER.info( 'Learner data transmission task for integrated channel configuration [%s] took [%s] seconds', integrated_channel, duration )
def unlink_inactive_learners(channel_code, channel_pk): """ Task to unlink inactive learners of provided integrated channel. Arguments: channel_code (str): Capitalized identifier for the integrated channel channel_pk (str): Primary key for identifying integrated channel """ start = time.time() integrated_channel = INTEGRATED_CHANNEL_CHOICES[channel_code].objects.get(pk=channel_pk) LOGGER.info('Processing learners to unlink inactive users using configuration: [%s]', integrated_channel) # Note: learner data transmission code paths don't raise any uncaught exception, so we don't need a broad # try-except block here. integrated_channel.unlink_inactive_learners() duration = time.time() - start LOGGER.info( 'Unlink inactive learners task for integrated channel configuration [%s] took [%s] seconds', integrated_channel, duration )
def handle_user_post_save(sender, **kwargs): # pylint: disable=unused-argument """ Handle User model changes - checks if pending enterprise customer user record exists and upgrades it to actual link. If there are pending enrollments attached to the PendingEnterpriseCustomerUser, then this signal also takes the newly-created users and enrolls them in the relevant courses. """ created = kwargs.get("created", False) user_instance = kwargs.get("instance", None) if user_instance is None: return # should never happen, but better safe than 500 error try: pending_ecu = PendingEnterpriseCustomerUser.objects.get(user_email=user_instance.email) except PendingEnterpriseCustomerUser.DoesNotExist: return # nothing to do in this case if not created: # existing user changed his email to match one of pending link records - try linking him to EC try: existing_record = EnterpriseCustomerUser.objects.get(user_id=user_instance.id) message_template = "User {user} have changed email to match pending Enterprise Customer link, " \ "but was already linked to Enterprise Customer {enterprise_customer} - " \ "deleting pending link record" logger.info(message_template.format( user=user_instance, enterprise_customer=existing_record.enterprise_customer )) pending_ecu.delete() return except EnterpriseCustomerUser.DoesNotExist: pass # everything ok - current user is not linked to other ECs enterprise_customer_user = EnterpriseCustomerUser.objects.create( enterprise_customer=pending_ecu.enterprise_customer, user_id=user_instance.id ) pending_enrollments = list(pending_ecu.pendingenrollment_set.all()) if pending_enrollments: def _complete_user_enrollment(): # pylint: disable=missing-docstring for enrollment in pending_enrollments: # EnterpriseCustomers may enroll users in courses before the users themselves # actually exist in the system; in such a case, the enrollment for each such # course is finalized when the user registers with the OpenEdX platform. enterprise_customer_user.enroll( enrollment.course_id, enrollment.course_mode, cohort=enrollment.cohort_name) track_enrollment('pending-admin-enrollment', user_instance.id, enrollment.course_id) pending_ecu.delete() transaction.on_commit(_complete_user_enrollment) else: pending_ecu.delete()
def default_content_filter(sender, instance, **kwargs): # pylint: disable=unused-argument """ Set default value for `EnterpriseCustomerCatalog.content_filter` if not already set. """ if kwargs['created'] and not instance.content_filter: instance.content_filter = get_default_catalog_content_filter() instance.save()
def assign_enterprise_learner_role(sender, instance, **kwargs): # pylint: disable=unused-argument """ Assign an enterprise learner role to EnterpriseCustomerUser whenever a new record is created. """ if kwargs['created'] and instance.user: enterprise_learner_role, __ = SystemWideEnterpriseRole.objects.get_or_create(name=ENTERPRISE_LEARNER_ROLE) SystemWideEnterpriseUserRoleAssignment.objects.get_or_create( user=instance.user, role=enterprise_learner_role )
def delete_enterprise_learner_role_assignment(sender, instance, **kwargs): # pylint: disable=unused-argument """ Delete the associated enterprise learner role assignment record when deleting an EnterpriseCustomerUser record. """ if instance.user: enterprise_learner_role, __ = SystemWideEnterpriseRole.objects.get_or_create(name=ENTERPRISE_LEARNER_ROLE) try: SystemWideEnterpriseUserRoleAssignment.objects.get( user=instance.user, role=enterprise_learner_role ).delete() except SystemWideEnterpriseUserRoleAssignment.DoesNotExist: # Do nothing if no role assignment is present for the enterprise customer user. pass
def enterprise_customer_required(view): """ 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 ... """ @wraps(view) def wrapper(request, *args, **kwargs): """ Checks for an enterprise customer associated with the user, calls the view function if one exists, raises PermissionDenied if not. """ user = request.user enterprise_customer = get_enterprise_customer_for_user(user) if enterprise_customer: args = args + (enterprise_customer,) return view(request, *args, **kwargs) else: raise PermissionDenied( 'User {username} is not associated with an EnterpriseCustomer.'.format( username=user.username ) ) return wrapper
def require_at_least_one_query_parameter(*query_parameter_names): """ 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 ... """ def outer_wrapper(view): """ Allow the passing of parameters to require_at_least_one_query_parameter. """ @wraps(view) def wrapper(request, *args, **kwargs): """ Checks for the existence of the specified query parameters, raises a ValidationError if none of them were included in the request. """ requirement_satisfied = False for query_parameter_name in query_parameter_names: query_parameter_values = request.query_params.getlist(query_parameter_name) kwargs[query_parameter_name] = query_parameter_values if query_parameter_values: requirement_satisfied = True if not requirement_satisfied: raise ValidationError( detail='You must provide at least one of the following query parameters: {params}.'.format( params=', '.join(query_parameter_names) ) ) return view(request, *args, **kwargs) return wrapper return outer_wrapper
def handle(self, *args, **options): """ Transmit the courseware data for the EnterpriseCustomer(s) to the active integration channels. """ username = options['catalog_user'] # Before we do a whole bunch of database queries, make sure that the user we were passed exists. try: User.objects.get(username=username) except User.DoesNotExist: raise CommandError('A user with the username {} was not found.'.format(username)) channels = self.get_integrated_channels(options) for channel in channels: channel_code = channel.channel_code() channel_pk = channel.pk transmit_content_metadata.delay(username, channel_code, channel_pk)
def create_roles(apps, schema_editor): """Create the enterprise roles if they do not already exist.""" SystemWideEnterpriseRole = apps.get_model('enterprise', 'SystemWideEnterpriseRole') SystemWideEnterpriseRole.objects.update_or_create(name=ENTERPRISE_ADMIN_ROLE) SystemWideEnterpriseRole.objects.update_or_create(name=ENTERPRISE_LEARNER_ROLE)
def delete_roles(apps, schema_editor): """Delete the enterprise roles.""" SystemWideEnterpriseRole = apps.get_model('enterprise', 'SystemWideEnterpriseRole') SystemWideEnterpriseRole.objects.filter( name__in=[ENTERPRISE_ADMIN_ROLE, ENTERPRISE_LEARNER_ROLE] ).delete()
def _get_enterprise_admin_users_batch(self, start, end): """ Returns a batched queryset of User objects. """ LOGGER.info('Fetching new batch of enterprise admin users from indexes: %s to %s', start, end) return User.objects.filter(groups__name=ENTERPRISE_DATA_API_ACCESS_GROUP, is_staff=False)[start:end]
def _get_enterprise_operator_users_batch(self, start, end): """ Returns a batched queryset of User objects. """ LOGGER.info('Fetching new batch of enterprise operator users from indexes: %s to %s', start, end) return User.objects.filter(groups__name=ENTERPRISE_DATA_API_ACCESS_GROUP, is_staff=True)[start:end]
def _get_enterprise_customer_users_batch(self, start, end): """ Returns a batched queryset of EnterpriseCustomerUser objects. """ LOGGER.info('Fetching new batch of enterprise customer users from indexes: %s to %s', start, end) return User.objects.filter(pk__in=self._get_enterprise_customer_user_ids())[start:end]
def _get_enterprise_enrollment_api_admin_users_batch(self, start, end): # pylint: disable=invalid-name """ Returns a batched queryset of User objects. """ LOGGER.info('Fetching new batch of enterprise enrollment admin users from indexes: %s to %s', start, end) return User.objects.filter(groups__name=ENTERPRISE_ENROLLMENT_API_ACCESS_GROUP, is_staff=False)[start:end]
def _get_enterprise_catalog_admin_users_batch(self, start, end): """ Returns a batched queryset of User objects. """ Application = apps.get_model(OAUTH2_PROVIDER_APPLICATION_MODEL) # pylint: disable=invalid-name LOGGER.info('Fetching new batch of enterprise catalog admin users from indexes: %s to %s', start, end) catalog_admin_user_ids = Application.objects.filter( user_id__in=self._get_enterprise_customer_user_ids() ).exclude(name=EDX_ORG_NAME).values('user_id') return User.objects.filter(pk__in=catalog_admin_user_ids)[start:end]
def _assign_enterprise_role_to_users(self, _get_batch_method, options, is_feature_role=False): """ Assigns enterprise role to users. """ role_name = options['role'] batch_limit = options['batch_limit'] batch_sleep = options['batch_sleep'] batch_offset = options['batch_offset'] current_batch_index = batch_offset users_batch = _get_batch_method( batch_offset, batch_offset + batch_limit ) role_class = SystemWideEnterpriseRole role_assignment_class = SystemWideEnterpriseUserRoleAssignment if is_feature_role: role_class = EnterpriseFeatureRole role_assignment_class = EnterpriseFeatureUserRoleAssignment enterprise_role = role_class.objects.get(name=role_name) while users_batch.count() > 0: for index, user in enumerate(users_batch): LOGGER.info( 'Processing user with index %s and id %s', current_batch_index + index, user.id ) role_assignment_class.objects.get_or_create( user=user, role=enterprise_role ) sleep(batch_sleep) current_batch_index += len(users_batch) users_batch = _get_batch_method( current_batch_index, current_batch_index + batch_limit )
def handle(self, *args, **options): """ Entry point for managment command execution. """ LOGGER.info('Starting assigning enterprise roles to users!') role = options['role'] if role == ENTERPRISE_ADMIN_ROLE: # Assign admin role to non-staff users with enterprise data api access. self._assign_enterprise_role_to_users(self._get_enterprise_admin_users_batch, options) elif role == ENTERPRISE_OPERATOR_ROLE: # Assign operator role to staff users with enterprise data api access. self._assign_enterprise_role_to_users(self._get_enterprise_operator_users_batch, options) elif role == ENTERPRISE_LEARNER_ROLE: # Assign enterprise learner role to enterprise customer users. self._assign_enterprise_role_to_users(self._get_enterprise_customer_users_batch, options) elif role == ENTERPRISE_ENROLLMENT_API_ADMIN_ROLE: # Assign enterprise enrollment api admin to non-staff users with enterprise data api access. self._assign_enterprise_role_to_users(self._get_enterprise_enrollment_api_admin_users_batch, options, True) elif role == ENTERPRISE_CATALOG_ADMIN_ROLE: # Assign enterprise catalog admin role to users with having credentials in catalog. self._assign_enterprise_role_to_users(self._get_enterprise_catalog_admin_users_batch, options, True) else: raise CommandError('Please provide a valid role name. Supported roles are {admin} and {learner}'.format( admin=ENTERPRISE_ADMIN_ROLE, learner=ENTERPRISE_LEARNER_ROLE )) LOGGER.info('Successfully finished assigning enterprise roles to users!')
def transmit(self, payload, **kwargs): """ Send a completion status call to Degreed using the client. Args: payload: The learner completion data payload to send to Degreed """ kwargs['app_label'] = 'degreed' kwargs['model_name'] = 'DegreedLearnerDataTransmissionAudit' kwargs['remote_user_id'] = 'degreed_user_email' super(DegreedLearnerTransmitter, self).transmit(payload, **kwargs)
def get_enterprise_customer_for_running_pipeline(request, pipeline): # pylint: disable=invalid-name """ Get the EnterpriseCustomer associated with a running pipeline. """ sso_provider_id = request.GET.get('tpa_hint') if pipeline: sso_provider_id = Registry.get_from_pipeline(pipeline).provider_id return get_enterprise_customer_for_sso(sso_provider_id)
def handle_enterprise_logistration(backend, user, **kwargs): """ Perform the linking of user in the process of logging to the Enterprise Customer. Args: backend: The class handling the SSO interaction (SAML, OAuth, etc) user: The user object in the process of being logged in with **kwargs: Any remaining pipeline variables """ request = backend.strategy.request enterprise_customer = get_enterprise_customer_for_running_pipeline( request, { 'backend': backend.name, 'kwargs': kwargs } ) if enterprise_customer is None: # This pipeline element is not being activated as a part of an Enterprise logistration return # proceed with the creation of a link between the user and the enterprise customer, then exit. enterprise_customer_user, _ = EnterpriseCustomerUser.objects.update_or_create( enterprise_customer=enterprise_customer, user_id=user.id ) enterprise_customer_user.update_session(request)
def get_user_from_social_auth(tpa_provider, tpa_username): """ 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 """ user_social_auth = UserSocialAuth.objects.select_related('user').filter( user__username=tpa_username, provider=tpa_provider.backend_name ).first() return user_social_auth.user if user_social_auth else None
def get_oauth_access_token(url_base, client_id, client_secret, company_id, user_id, user_type): """ Retrieves OAuth 2.0 access token using the client credentials grant. Args: url_base (str): Oauth2 access token endpoint client_id (str): client ID client_secret (str): client secret company_id (str): SAP company ID user_id (str): SAP user ID user_type (str): type of SAP user (admin or user) Returns: tuple: Tuple containing access token string and expiration datetime. Raises: HTTPError: If we received a failure response code from SAP SuccessFactors. RequestException: If an unexpected response format was received that we could not parse. """ SAPSuccessFactorsGlobalConfiguration = apps.get_model( # pylint: disable=invalid-name 'sap_success_factors', 'SAPSuccessFactorsGlobalConfiguration' ) global_sap_config = SAPSuccessFactorsGlobalConfiguration.current() url = url_base + global_sap_config.oauth_api_path response = requests.post( url, json={ 'grant_type': 'client_credentials', 'scope': { 'userId': user_id, 'companyId': company_id, 'userType': user_type, 'resourceType': 'learning_public_api', } }, auth=(client_id, client_secret), headers={'content-type': 'application/json'} ) response.raise_for_status() data = response.json() try: return data['access_token'], datetime.datetime.utcfromtimestamp(data['expires_in'] + int(time.time())) except KeyError: raise requests.RequestException(response=response)
def _create_session(self): """ Instantiate a new session object for use in connecting with SAP SuccessFactors """ session = requests.Session() session.timeout = self.SESSION_TIMEOUT oauth_access_token, expires_at = SAPSuccessFactorsAPIClient.get_oauth_access_token( self.enterprise_configuration.sapsf_base_url, self.enterprise_configuration.key, self.enterprise_configuration.secret, self.enterprise_configuration.sapsf_company_id, self.enterprise_configuration.sapsf_user_id, self.enterprise_configuration.user_type ) session.headers['Authorization'] = 'Bearer {}'.format(oauth_access_token) session.headers['content-type'] = 'application/json' self.session = session self.expires_at = expires_at
def create_course_completion(self, user_id, payload): """ Send a completion status payload to the SuccessFactors OCN Completion Status endpoint Args: user_id (str): The sap user id that the completion status is being sent for. payload (str): JSON encoded object (serialized from SapSuccessFactorsLearnerDataTransmissionAudit) containing completion status fields per SuccessFactors documentation. Returns: The body of the response from SAP SuccessFactors, if successful Raises: HTTPError: if we received a failure response code from SAP SuccessFactors """ url = self.enterprise_configuration.sapsf_base_url + self.global_sap_config.completion_status_api_path return self._call_post_with_user_override(user_id, url, payload)
def _sync_content_metadata(self, serialized_data): """ Create/update/delete content metadata records using the SuccessFactors OCN Course Import API endpoint. Arguments: serialized_data: Serialized JSON string representing a list of content metadata items. Raises: ClientError: If SuccessFactors API call fails. """ url = self.enterprise_configuration.sapsf_base_url + self.global_sap_config.course_api_path try: status_code, response_body = self._call_post_with_session(url, serialized_data) except requests.exceptions.RequestException as exc: raise ClientError( 'SAPSuccessFactorsAPIClient request failed: {error} {message}'.format( error=exc.__class__.__name__, message=str(exc) ) ) if status_code >= 400: raise ClientError( 'SAPSuccessFactorsAPIClient request failed with status {status_code}: {message}'.format( status_code=status_code, message=response_body ) )
def _call_post_with_user_override(self, sap_user_id, url, payload): """ Make a post request with an auth token acquired for a specific user to a SuccessFactors endpoint. Args: sap_user_id (str): The user to use to retrieve an auth token. url (str): The url to post to. payload (str): The json encoded payload to post. """ SAPSuccessFactorsEnterpriseCustomerConfiguration = apps.get_model( # pylint: disable=invalid-name 'sap_success_factors', 'SAPSuccessFactorsEnterpriseCustomerConfiguration' ) oauth_access_token, _ = SAPSuccessFactorsAPIClient.get_oauth_access_token( self.enterprise_configuration.sapsf_base_url, self.enterprise_configuration.key, self.enterprise_configuration.secret, self.enterprise_configuration.sapsf_company_id, sap_user_id, SAPSuccessFactorsEnterpriseCustomerConfiguration.USER_TYPE_USER ) response = requests.post( url, data=payload, headers={ 'Authorization': 'Bearer {}'.format(oauth_access_token), 'content-type': 'application/json' } ) return response.status_code, response.text
def _call_post_with_session(self, url, payload): """ Make a post request using the session object to a SuccessFactors endpoint. Args: url (str): The url to post to. payload (str): The json encoded payload to post. """ now = datetime.datetime.utcnow() if now >= self.expires_at: # Create a new session with a valid token self.session.close() self._create_session() response = self.session.post(url, data=payload) return response.status_code, response.text
def get_inactive_sap_learners(self): """ Make a GET request using the session object to a SuccessFactors endpoint for inactive learners. Example: sap_search_student_url: "/learning/odatav4/searchStudent/v1/Students? $filter=criteria/isActive eq False&$select=studentID" SAP API response: { u'@odata.metadataEtag': u'W/"17090d86-20fa-49c8-8de0-de1d308c8b55"', u'value': [ { u'studentID': u'admint6', }, { u'studentID': u'adminsap1', } ] } Returns: List of inactive learners [ { u'studentID': u'admint6' }, { u'studentID': u'adminsap1' } ] """ now = datetime.datetime.utcnow() if now >= self.expires_at: # Create a new session with a valid token self.session.close() self._create_session() sap_search_student_url = '{sapsf_base_url}/{search_students_path}?$filter={search_filter}'.format( sapsf_base_url=self.enterprise_configuration.sapsf_base_url.rstrip('/'), search_students_path=self.global_sap_config.search_student_api_path.rstrip('/'), search_filter='criteria/isActive eq False&$select=studentID', ) all_inactive_learners = self._call_search_students_recursively( sap_search_student_url, all_inactive_learners=[], page_size=500, start_at=0 ) return all_inactive_learners
def _call_search_students_recursively(self, sap_search_student_url, all_inactive_learners, page_size, start_at): """ Make recursive GET calls to traverse the paginated API response for search students. """ search_student_paginated_url = '{sap_search_student_url}&{pagination_criterion}'.format( sap_search_student_url=sap_search_student_url, pagination_criterion='$count=true&$top={page_size}&$skip={start_at}'.format( page_size=page_size, start_at=start_at, ), ) try: response = self.session.get(search_student_paginated_url) sap_inactive_learners = response.json() except (ConnectionError, Timeout): LOGGER.warning( 'Unable to fetch inactive learners from SAP searchStudent API with url ' '"{%s}".', search_student_paginated_url, ) return None if 'error' in sap_inactive_learners: LOGGER.warning( 'SAP searchStudent API for customer %s and base url %s returned response with ' 'error message "%s" and with error code "%s".', self.enterprise_configuration.enterprise_customer.name, self.enterprise_configuration.sapsf_base_url, sap_inactive_learners['error'].get('message'), sap_inactive_learners['error'].get('code'), ) return None new_page_start_at = page_size + start_at all_inactive_learners += sap_inactive_learners['value'] if sap_inactive_learners['@odata.count'] > new_page_start_at: return self._call_search_students_recursively( sap_search_student_url, all_inactive_learners, page_size=page_size, start_at=new_page_start_at, ) return all_inactive_learners
def filter_queryset(self, request, queryset, view): """ Filter only for the user's ID if non-staff. """ if not request.user.is_staff: filter_kwargs = {view.USER_ID_FILTER: request.user.id} queryset = queryset.filter(**filter_kwargs) return queryset
def filter_queryset(self, request, queryset, view): """ Apply incoming filters only if user is staff. If not, only filter by user's ID. """ if request.user.is_staff: email = request.query_params.get('email', None) username = request.query_params.get('username', None) query_parameters = {} if email: query_parameters.update(email=email) if username: query_parameters.update(username=username) if query_parameters: users = User.objects.filter(**query_parameters).values_list('id', flat=True) queryset = queryset.filter(user_id__in=users) else: queryset = queryset.filter(user_id=request.user.id) return queryset
def transmit(self, payload, **kwargs): """ Send a completion status call to the integrated channel using the client. Args: payload: The learner completion data payload to send to the integrated channel. kwargs: Contains integrated channel-specific information for customized transmission variables. - app_label: The app label of the integrated channel for whom to store learner data records for. - model_name: The name of the specific learner data record model to use. - remote_user_id: The remote ID field name of the learner on the audit model. """ IntegratedChannelLearnerDataTransmissionAudit = apps.get_model( # pylint: disable=invalid-name app_label=kwargs.get('app_label', 'integrated_channel'), model_name=kwargs.get('model_name', 'LearnerDataTransmissionAudit'), ) # Since we have started sending courses to integrated channels instead of course runs, # we need to attempt to send transmissions with course keys and course run ids in order to # ensure that we account for whether courses or course runs exist in the integrated channel. # The exporters have been changed to return multiple transmission records to attempt, # one by course key and one by course run id. # If the transmission with the course key succeeds, the next one will get skipped. # If it fails, the one with the course run id will be attempted and (presumably) succeed. for learner_data in payload.export(): serialized_payload = learner_data.serialize(enterprise_configuration=self.enterprise_configuration) LOGGER.debug('Attempting to transmit serialized payload: %s', serialized_payload) enterprise_enrollment_id = learner_data.enterprise_course_enrollment_id if learner_data.completed_timestamp is None: # The user has not completed the course, so we shouldn't send a completion status call LOGGER.info('Skipping in-progress enterprise enrollment {}'.format(enterprise_enrollment_id)) continue previous_transmissions = IntegratedChannelLearnerDataTransmissionAudit.objects.filter( enterprise_course_enrollment_id=enterprise_enrollment_id, error_message='' ) if previous_transmissions.exists(): # We've already sent a completion status call for this enrollment LOGGER.info('Skipping previously sent enterprise enrollment {}'.format(enterprise_enrollment_id)) continue try: code, body = self.client.create_course_completion( getattr(learner_data, kwargs.get('remote_user_id')), serialized_payload ) LOGGER.info( 'Successfully sent completion status call for enterprise enrollment {}'.format( enterprise_enrollment_id, ) ) except RequestException as request_exception: code = 500 body = str(request_exception) self.handle_transmission_error(learner_data, request_exception) learner_data.status = str(code) learner_data.error_message = body if code >= 400 else '' learner_data.save()
def handle_transmission_error(self, learner_data, request_exception): """Handle the case where the transmission fails.""" try: sys_msg = request_exception.response.content except AttributeError: sys_msg = 'Not available' LOGGER.error( ( 'Failed to send completion status call for enterprise enrollment %s' 'with payload %s' '\nError message: %s' '\nSystem message: %s' ), learner_data.enterprise_course_enrollment_id, learner_data, str(request_exception), sys_msg )
def add_missing_price_information_message(request, item): """ Add a message to the Django messages store indicating that we failed to retrieve price information about an item. :param request: The current request. :param item: The item for which price information is missing. Example: a program title, or a course. """ messages.warning( request, _( '{strong_start}We could not gather price information for {em_start}{item}{em_end}.{strong_end} ' '{span_start}If you continue to have these issues, please contact ' '{link_start}{platform_name} support{link_end}.{span_end}' ).format( item=item, em_start='<em>', em_end='</em>', link_start='<a href="{support_link}" target="_blank">'.format( support_link=get_configuration_value('ENTERPRISE_SUPPORT_URL', settings.ENTERPRISE_SUPPORT_URL), ), platform_name=get_configuration_value('PLATFORM_NAME', settings.PLATFORM_NAME), link_end='</a>', span_start='<span>', span_end='</span>', strong_start='<strong>', strong_end='</strong>', ) )
def add_unenrollable_item_message(request, item): """ Add a message to the Django message store indicating that the item (i.e. course run, program) is unenrollable. :param request: The current request. :param item: The item that is unenrollable (i.e. a course run). """ messages.info( request, _( '{strong_start}Something happened.{strong_end} ' '{span_start}This {item} is not currently open to new learners. Please start over and select a different ' '{item}.{span_end}' ).format( item=item, strong_start='<strong>', strong_end='</strong>', span_start='<span>', span_end='</span>', ) )
def add_generic_info_message_for_error(request): """ Add message to request indicating that there was an issue processing request. Arguments: request: The current request. """ messages.info( request, _( '{strong_start}Something happened.{strong_end} ' '{span_start}This course link is currently invalid. ' 'Please reach out to your Administrator for assistance to this course.{span_end}' ).format( span_start='<span>', span_end='</span>', strong_start='<strong>', strong_end='</strong>', ) )
def add_generic_error_message_with_code(request, error_code): """ Add message to request indicating that there was an issue processing request. Arguments: request: The current request. error_code: A string error code to be used to point devs to the spot in the code where this error occurred. """ messages.error( request, _( '{strong_start}Something happened.{strong_end} ' '{span_start}Please reach out to your learning administrator with ' 'the following error code and they will be able to help you out.{span_end}' '{span_start}Error code: {error_code}{span_end}' ).format( error_code=error_code, strong_start='<strong>', strong_end='</strong>', span_start='<span>', span_end='</span>', ) )
def validate_image_extension(value): """ Validate that a particular image extension. """ config = get_app_config() ext = os.path.splitext(value.name)[1] if config and not ext.lower() in config.valid_image_extensions: raise ValidationError(_("Unsupported file extension."))
def validate_image_size(image): """ Validate that a particular image size. """ config = get_app_config() valid_max_image_size_in_bytes = config.valid_max_image_size * 1024 if config and not image.size <= valid_max_image_size_in_bytes: raise ValidationError( _("The logo image file size must be less than or equal to %s KB.") % config.valid_max_image_size)
def get_enterprise_customer_from_catalog_id(catalog_id): """ Get the enterprise customer id given an enterprise customer catalog id. """ try: return str(EnterpriseCustomerCatalog.objects.get(pk=catalog_id).enterprise_customer.uuid) except EnterpriseCustomerCatalog.DoesNotExist: return None
def on_init(app): # pylint: disable=unused-argument """ Run sphinx-apidoc after Sphinx initialization. Read the Docs won't run tox or custom shell commands, so we need this to avoid checking in the generated reStructuredText files. """ docs_path = os.path.abspath(os.path.dirname(__file__)) root_path = os.path.abspath(os.path.join(docs_path, '..')) apidoc_path = 'sphinx-apidoc' if hasattr(sys, 'real_prefix'): # Check to see if we are in a virtualenv # If we are, assemble the path manually bin_path = os.path.abspath(os.path.join(sys.prefix, 'bin')) apidoc_path = os.path.join(bin_path, apidoc_path) check_call([apidoc_path, '-o', docs_path, os.path.join(root_path, 'enterprise'), os.path.join(root_path, 'enterprise/migrations')])
def setup(app): """Sphinx extension: run sphinx-apidoc.""" event = 'builder-inited' if six.PY3 else b'builder-inited' app.connect(event, on_init)
def add_arguments(self, parser): """ Adds the optional arguments: ``--enterprise_customer``, ``--channel`` """ parser.add_argument( '--enterprise_customer', dest='enterprise_customer', default=None, metavar='ENTERPRISE_CUSTOMER_UUID', help=_('Transmit data for only this EnterpriseCustomer. ' 'Omit this option to transmit to all EnterpriseCustomers with active integrated channels.'), ) parser.add_argument( '--channel', dest='channel', default='', metavar='INTEGRATED_CHANNEL', help=_('Transmit data to this IntegrateChannel. ' 'Omit this option to transmit to all configured, active integrated channels.'), choices=INTEGRATED_CHANNEL_CHOICES.keys(), )
def get_integrated_channels(self, options): """ Generates a list of active integrated channels for active customers, filtered from the given options. Raises errors when invalid options are encountered. See ``add_arguments`` for the accepted options. """ channel_classes = self.get_channel_classes(options.get('channel')) filter_kwargs = { 'active': True, 'enterprise_customer__active': True, } enterprise_customer = self.get_enterprise_customer(options.get('enterprise_customer')) if enterprise_customer: filter_kwargs['enterprise_customer'] = enterprise_customer for channel_class in channel_classes: for integrated_channel in channel_class.objects.filter(**filter_kwargs): yield integrated_channel
def get_enterprise_customer(uuid): """ Returns the enterprise customer requested for the given uuid, None if not. Raises CommandError if uuid is invalid. """ if uuid is None: return None try: return EnterpriseCustomer.active_customers.get(uuid=uuid) except EnterpriseCustomer.DoesNotExist: raise CommandError( _('Enterprise customer {uuid} not found, or not active').format(uuid=uuid))
def get_channel_classes(channel_code): """ Assemble a list of integrated channel classes to transmit to. If a valid channel type was provided, use it. Otherwise, use all the available channel types. """ if channel_code: # Channel code is case-insensitive channel_code = channel_code.upper() if channel_code not in INTEGRATED_CHANNEL_CHOICES: raise CommandError(_('Invalid integrated channel: {channel}').format(channel=channel_code)) channel_classes = [INTEGRATED_CHANNEL_CHOICES[channel_code]] else: channel_classes = INTEGRATED_CHANNEL_CHOICES.values() return channel_classes
def get_result(self, course_grade): """ Get result for the statement. Arguments: course_grade (CourseGrade): Course grade. """ return Result( score=Score( scaled=course_grade.percent, raw=course_grade.percent * 100, min=MIN_SCORE, max=MAX_SCORE, ), success=course_grade.passed, completion=course_grade.passed )
def get_requirements(requirements_file): """ Get the contents of a file listing the requirements """ lines = open(requirements_file).readlines() dependencies = [] dependency_links = [] for line in lines: package = line.strip() if package.startswith('#'): # Skip pure comment lines continue if any(package.startswith(prefix) for prefix in VCS_PREFIXES): # VCS reference for dev purposes, expect a trailing comment # with the normal requirement package_link, __, package = package.rpartition('#') # Remove -e <version_control> string package_link = re.sub(r'(.*)(?P<dependency_link>https?.*$)', r'\g<dependency_link>', package_link) package = re.sub(r'(egg=)?(?P<package_name>.*)==.*$', r'\g<package_name>', package) package_version = re.sub(r'.*[^=]==', '', line.strip()) if package: dependency_links.append( '{package_link}#egg={package}-{package_version}'.format( package_link=package_link, package=package, package_version=package_version, ) ) else: # Ignore any trailing comment package, __, __ = package.partition('#') # Remove any whitespace and assume non-empty results are dependencies package = package.strip() if package: dependencies.append(package) return dependencies, dependency_links
def transmit_learner_data(self, user): """ Iterate over each learner data record and transmit it to the integrated channel. """ exporter = self.get_learner_data_exporter(user) transmitter = self.get_learner_data_transmitter() transmitter.transmit(exporter)
def transmit_content_metadata(self, user): """ Transmit content metadata to integrated channel. """ exporter = self.get_content_metadata_exporter(user) transmitter = self.get_content_metadata_transmitter() transmitter.transmit(exporter.export())
def get_learner_data_records( self, enterprise_enrollment, completed_date=None, is_passing=False, **kwargs ): # pylint: disable=arguments-differ,unused-argument """ Return a DegreedLearnerDataTransmissionAudit with the given enrollment and course completion data. If completed_date is None, then course completion has not been met. If no remote ID can be found, return None. """ # Degreed expects completion dates of the form 'yyyy-mm-dd'. completed_timestamp = completed_date.strftime("%F") if isinstance(completed_date, datetime) else None if enterprise_enrollment.enterprise_customer_user.get_remote_id() is not None: DegreedLearnerDataTransmissionAudit = apps.get_model( # pylint: disable=invalid-name 'degreed', 'DegreedLearnerDataTransmissionAudit' ) # We return two records here, one with the course key and one with the course run id, to account for # uncertainty about the type of content (course vs. course run) that was sent to the integrated channel. return [ DegreedLearnerDataTransmissionAudit( enterprise_course_enrollment_id=enterprise_enrollment.id, degreed_user_email=enterprise_enrollment.enterprise_customer_user.user_email, course_id=parse_course_key(enterprise_enrollment.course_id), course_completed=completed_date is not None and is_passing, completed_timestamp=completed_timestamp, ), DegreedLearnerDataTransmissionAudit( enterprise_course_enrollment_id=enterprise_enrollment.id, degreed_user_email=enterprise_enrollment.enterprise_customer_user.user_email, course_id=enterprise_enrollment.course_id, course_completed=completed_date is not None and is_passing, completed_timestamp=completed_timestamp, ) ] else: LOGGER.debug( 'No learner data was sent for user [%s] because a Degreed user ID could not be found.', enterprise_enrollment.enterprise_customer_user.username )
def get(self, request, template_id, view_type): """ Render the given template with the stock data. """ template = get_object_or_404(EnrollmentNotificationEmailTemplate, pk=template_id) if view_type not in self.view_type_contexts: return HttpResponse(status=404) base_context = self.view_type_contexts[view_type].copy() base_context.update({'user_name': self.get_user_name(request)}) return HttpResponse(template.render_html_template(base_context), content_type='text/html')
def _build_admin_context(request, customer): """ Build common admin context. """ opts = customer._meta codename = get_permission_codename('change', opts) has_change_permission = request.user.has_perm('%s.%s' % (opts.app_label, codename)) return { 'has_change_permission': has_change_permission, 'opts': opts }
def _build_context(self, request, enterprise_customer_uuid): """ Build common context parts used by different handlers in this view. """ enterprise_customer = EnterpriseCustomer.objects.get(uuid=enterprise_customer_uuid) # pylint: disable=no-member context = { self.ContextParameters.ENTERPRISE_CUSTOMER: enterprise_customer, } context.update(admin.site.each_context(request)) context.update(self._build_admin_context(request, enterprise_customer)) return context
def get(self, request, enterprise_customer_uuid): """ 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 """ context = self._build_context(request, enterprise_customer_uuid) transmit_courses_metadata_form = TransmitEnterpriseCoursesForm() context.update({self.ContextParameters.TRANSMIT_COURSES_METADATA_FORM: transmit_courses_metadata_form}) return render(request, self.template, context)
def post(self, request, enterprise_customer_uuid): """ Handle POST request - handle form submissions. Arguments: request (django.http.request.HttpRequest): Request instance enterprise_customer_uuid (str): Enterprise Customer UUID """ transmit_courses_metadata_form = TransmitEnterpriseCoursesForm(request.POST) # check that form data is well-formed if transmit_courses_metadata_form.is_valid(): channel_worker_username = transmit_courses_metadata_form.cleaned_data['channel_worker_username'] # call `transmit_content_metadata` management command to trigger # transmission of enterprise courses metadata call_command( 'transmit_content_metadata', '--catalog_user', channel_worker_username, enterprise_customer=enterprise_customer_uuid ) # Redirect to GET return HttpResponseRedirect('') context = self._build_context(request, enterprise_customer_uuid) context.update({self.ContextParameters.TRANSMIT_COURSES_METADATA_FORM: transmit_courses_metadata_form}) return render(request, self.template, context)
def _build_context(self, request, customer_uuid): """ Build common context parts used by different handlers in this view. """ # TODO: pylint acts stupid - find a way around it without suppressing enterprise_customer = EnterpriseCustomer.objects.get(uuid=customer_uuid) # pylint: disable=no-member search_keyword = self.get_search_keyword(request) linked_learners = self.get_enterprise_customer_user_queryset(request, search_keyword, customer_uuid) pending_linked_learners = self.get_pending_users_queryset(search_keyword, customer_uuid) context = { self.ContextParameters.ENTERPRISE_CUSTOMER: enterprise_customer, self.ContextParameters.PENDING_LEARNERS: pending_linked_learners, self.ContextParameters.LEARNERS: linked_learners, self.ContextParameters.SEARCH_KEYWORD: search_keyword or '', self.ContextParameters.ENROLLMENT_URL: settings.LMS_ENROLLMENT_API_PATH, } context.update(admin.site.each_context(request)) context.update(self._build_admin_context(request, enterprise_customer)) return context
def get_enterprise_customer_user_queryset(self, request, search_keyword, customer_uuid, page_size=PAGE_SIZE): """ Get the list of EnterpriseCustomerUsers we want to render. Arguments: request (HttpRequest): HTTP Request instance. search_keyword (str): The keyword to search for in users' email addresses and usernames. customer_uuid (str): A unique identifier to filter down to only users linked to a particular EnterpriseCustomer. page_size (int): Number of learners displayed in each paginated set. """ page = request.GET.get('page', 1) learners = EnterpriseCustomerUser.objects.filter(enterprise_customer__uuid=customer_uuid) user_ids = learners.values_list('user_id', flat=True) matching_users = User.objects.filter(pk__in=user_ids) if search_keyword is not None: matching_users = matching_users.filter( Q(email__icontains=search_keyword) | Q(username__icontains=search_keyword) ) matching_user_ids = matching_users.values_list('pk', flat=True) learners = learners.filter(user_id__in=matching_user_ids) return paginated_list(learners, page, page_size)
def get_pending_users_queryset(self, search_keyword, customer_uuid): """ Get the list of PendingEnterpriseCustomerUsers we want to render. Args: search_keyword (str): The keyword to search for in pending users' email addresses. customer_uuid (str): A unique identifier to filter down to only pending users linked to a particular EnterpriseCustomer. """ queryset = PendingEnterpriseCustomerUser.objects.filter( enterprise_customer__uuid=customer_uuid ) if search_keyword is not None: queryset = queryset.filter(user_email__icontains=search_keyword) return queryset
def _handle_singular(cls, enterprise_customer, manage_learners_form): """ Link single user by email or username. Arguments: enterprise_customer (EnterpriseCustomer): learners will be linked to this Enterprise Customer instance manage_learners_form (ManageLearnersForm): bound ManageLearners form instance """ form_field_value = manage_learners_form.cleaned_data[ManageLearnersForm.Fields.EMAIL_OR_USERNAME] email = email_or_username__to__email(form_field_value) try: validate_email_to_link(email, form_field_value, ValidationMessages.INVALID_EMAIL_OR_USERNAME, True) except ValidationError as exc: manage_learners_form.add_error(ManageLearnersForm.Fields.EMAIL_OR_USERNAME, exc) else: EnterpriseCustomerUser.objects.link_user(enterprise_customer, email) return [email]
def _handle_bulk_upload(cls, enterprise_customer, manage_learners_form, request, email_list=None): """ Bulk link users by email. Arguments: enterprise_customer (EnterpriseCustomer): learners will be linked to this Enterprise Customer instance manage_learners_form (ManageLearnersForm): bound ManageLearners form instance request (django.http.request.HttpRequest): HTTP Request instance email_list (iterable): A list of pre-processed email addresses to handle using the form """ errors = [] emails = set() already_linked_emails = [] duplicate_emails = [] csv_file = manage_learners_form.cleaned_data[ManageLearnersForm.Fields.BULK_UPLOAD] if email_list: parsed_csv = [{ManageLearnersForm.CsvColumns.EMAIL: email} for email in email_list] else: parsed_csv = parse_csv(csv_file, expected_columns={ManageLearnersForm.CsvColumns.EMAIL}) try: for index, row in enumerate(parsed_csv): email = row[ManageLearnersForm.CsvColumns.EMAIL] try: already_linked = validate_email_to_link(email, ignore_existing=True) except ValidationError as exc: message = _("Error at line {line}: {message}\n").format(line=index + 1, message=exc) errors.append(message) else: if already_linked: already_linked_emails.append((email, already_linked.enterprise_customer)) elif email in emails: duplicate_emails.append(email) else: emails.add(email) except ValidationError as exc: errors.append(exc) if errors: manage_learners_form.add_error( ManageLearnersForm.Fields.GENERAL_ERRORS, ValidationMessages.BULK_LINK_FAILED ) for error in errors: manage_learners_form.add_error(ManageLearnersForm.Fields.BULK_UPLOAD, error) return # There were no errors. Now do the actual linking: for email in emails: EnterpriseCustomerUser.objects.link_user(enterprise_customer, email) # Report what happened: count = len(emails) messages.success(request, ungettext( "{count} new learner was added to {enterprise_customer_name}.", "{count} new learners were added to {enterprise_customer_name}.", count ).format(count=count, enterprise_customer_name=enterprise_customer.name)) this_customer_linked_emails = [ email for email, customer in already_linked_emails if customer == enterprise_customer ] other_customer_linked_emails = [ email for email, __ in already_linked_emails if email not in this_customer_linked_emails ] if this_customer_linked_emails: messages.warning( request, _( "The following learners were already associated with this Enterprise " "Customer: {list_of_emails}" ).format( list_of_emails=", ".join(this_customer_linked_emails) ) ) if other_customer_linked_emails: messages.warning( request, _( "The following learners are already associated with " "another Enterprise Customer. These learners were not " "added to {enterprise_customer_name}: {list_of_emails}" ).format( enterprise_customer_name=enterprise_customer.name, list_of_emails=", ".join(other_customer_linked_emails), ) ) if duplicate_emails: messages.warning( request, _( "The following duplicate email addresses were not added: " "{list_of_emails}" ).format( list_of_emails=", ".join(duplicate_emails) ) ) # Build a list of all the emails that we can act on further; that is, # emails that we either linked to this customer, or that were linked already. all_processable_emails = list(emails) + this_customer_linked_emails return all_processable_emails
def enroll_user(cls, enterprise_customer, user, course_mode, *course_ids): """ 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 """ enterprise_customer_user, __ = EnterpriseCustomerUser.objects.get_or_create( enterprise_customer=enterprise_customer, user_id=user.id ) enrollment_client = EnrollmentApiClient() succeeded = True for course_id in course_ids: try: enrollment_client.enroll_user_in_course(user.username, course_id, course_mode) except HttpClientError as exc: # Check if user is already enrolled then we should ignore exception if cls.is_user_enrolled(user, course_id, course_mode): succeeded = True else: succeeded = False default_message = 'No error message provided' try: error_message = json.loads(exc.content.decode()).get('message', default_message) except ValueError: error_message = default_message logging.error( 'Error while enrolling user %(user)s: %(message)s', dict(user=user.username, message=error_message) ) if succeeded: __, created = EnterpriseCourseEnrollment.objects.get_or_create( enterprise_customer_user=enterprise_customer_user, course_id=course_id ) if created: track_enrollment('admin-enrollment', user.id, course_id) return succeeded
def is_user_enrolled(cls, user, course_id, course_mode): """ Query the enrollment API and determine if a learner is enrolled in a given course run track. Args: user: The user whose enrollment needs to be checked course_mode: The mode with which the enrollment should be checked course_id: course id of the course where enrollment should be checked. Returns: Boolean: Whether or not enrollment exists """ enrollment_client = EnrollmentApiClient() try: enrollments = enrollment_client.get_course_enrollment(user.username, course_id) if enrollments and course_mode == enrollments.get('mode'): return True except HttpClientError as exc: logging.error( 'Error while checking enrollment status of user %(user)s: %(message)s', dict(user=user.username, message=str(exc)) ) except KeyError as exc: logging.warning( 'Error while parsing enrollment data of user %(user)s: %(message)s', dict(user=user.username, message=str(exc)) ) return False
def get_users_by_email(cls, emails): """ 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 """ users = User.objects.filter(email__in=emails) present_emails = users.values_list('email', flat=True) missing_emails = list(set(emails) - set(present_emails)) return users, missing_emails
def enroll_users_in_program(cls, enterprise_customer, program_details, course_mode, emails, cohort=None): """ 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 """ existing_users, unregistered_emails = cls.get_users_by_email(emails) course_ids = get_course_runs_from_program(program_details) successes = [] pending = [] failures = [] for user in existing_users: succeeded = cls.enroll_user(enterprise_customer, user, course_mode, *course_ids) if succeeded: successes.append(user) else: failures.append(user) for email in unregistered_emails: pending_user = enterprise_customer.enroll_user_pending_registration( email, course_mode, *course_ids, cohort=cohort ) pending.append(pending_user) return successes, pending, failures
def enroll_users_in_course(cls, enterprise_customer, course_id, course_mode, emails): """ Enroll existing users in a course, and create a pending enrollment for nonexisting users. Args: enterprise_customer: The EnterpriseCustomer which is sponsoring the enrollment course_id (str): The unique identifier of the course in which we're enrolling course_mode (str): The mode with which we're enrolling in the course emails: An iterable of email addresses which need to be enrolled Returns: successes: A list of users who were successfully enrolled in the course 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 course """ existing_users, unregistered_emails = cls.get_users_by_email(emails) successes = [] pending = [] failures = [] for user in existing_users: succeeded = cls.enroll_user(enterprise_customer, user, course_mode, course_id) if succeeded: successes.append(user) else: failures.append(user) for email in unregistered_emails: pending_user = enterprise_customer.enroll_user_pending_registration( email, course_mode, course_id ) pending.append(pending_user) return successes, pending, failures
def send_messages(cls, http_request, message_requests): """ Deduplicate any outgoing message requests, and send the remainder. Args: http_request: The HTTP request in whose response we want to embed the messages message_requests: A list of undeduplicated messages in the form of tuples of message type and text- for example, ('error', 'Something went wrong') """ deduplicated_messages = set(message_requests) for msg_type, text in deduplicated_messages: message_function = getattr(messages, msg_type) message_function(http_request, text)
def notify_program_learners(cls, enterprise_customer, program_details, users): """ Notify learners about a program in which they've been enrolled. Args: enterprise_customer: The EnterpriseCustomer being linked to program_details: Details about the specific program the learners were enrolled in users: An iterable of the users or pending users who were enrolled """ program_name = program_details.get('title') program_branding = program_details.get('type') program_uuid = program_details.get('uuid') lms_root_url = get_configuration_value_for_site( enterprise_customer.site, 'LMS_ROOT_URL', settings.LMS_ROOT_URL ) program_path = urlquote( '/dashboard/programs/{program_uuid}/?tpa_hint={tpa_hint}'.format( program_uuid=program_uuid, tpa_hint=enterprise_customer.identity_provider, ) ) destination_url = '{site}/{login_or_register}?next={program_path}'.format( site=lms_root_url, login_or_register='{login_or_register}', program_path=program_path ) program_type = 'program' program_start = get_earliest_start_date_from_program(program_details) with mail.get_connection() as email_conn: for user in users: login_or_register = 'register' if isinstance(user, PendingEnterpriseCustomerUser) else 'login' destination_url = destination_url.format(login_or_register=login_or_register) send_email_notification_message( user=user, enrolled_in={ 'name': program_name, 'url': destination_url, 'type': program_type, 'start': program_start, 'branding': program_branding, }, enterprise_customer=enterprise_customer, email_connection=email_conn )
def get_success_enrollment_message(cls, users, enrolled_in): """ 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 """ enrolled_count = len(users) return ( 'success', ungettext( '{enrolled_count} learner was enrolled in {enrolled_in}.', '{enrolled_count} learners were enrolled in {enrolled_in}.', enrolled_count, ).format( enrolled_count=enrolled_count, enrolled_in=enrolled_in, ) )
def get_failed_enrollment_message(cls, users, enrolled_in): """ 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 """ failed_emails = [user.email for user in users] return ( 'error', _( 'The following learners could not be enrolled in {enrolled_in}: {user_list}' ).format( enrolled_in=enrolled_in, user_list=', '.join(failed_emails), ) )
def get_pending_enrollment_message(cls, pending_users, enrolled_in): """ Create message for the users who were enrolled in a course or program. Args: users: An iterable of PendingEnterpriseCustomerUsers who were successfully linked with a pending enrollment enrolled_in (str): A string identifier for the course or program the pending users were linked to Returns: tuple: A 2-tuple containing a message type and message text """ pending_emails = [pending_user.user_email for pending_user in pending_users] return ( 'warning', _( "The following learners do not have an account on " "{platform_name}. They have not been enrolled in " "{enrolled_in}. When these learners create an account, they will " "be enrolled automatically: {pending_email_list}" ).format( platform_name=settings.PLATFORM_NAME, enrolled_in=enrolled_in, pending_email_list=', '.join(pending_emails), ) )
def _enroll_users( cls, request, enterprise_customer, emails, mode, course_id=None, program_details=None, notify=True ): """ 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 """ pending_messages = [] if course_id: succeeded, pending, failed = cls.enroll_users_in_course( enterprise_customer=enterprise_customer, course_id=course_id, course_mode=mode, emails=emails, ) all_successes = succeeded + pending if notify: enterprise_customer.notify_enrolled_learners( catalog_api_user=request.user, course_id=course_id, users=all_successes, ) if succeeded: pending_messages.append(cls.get_success_enrollment_message(succeeded, course_id)) if failed: pending_messages.append(cls.get_failed_enrollment_message(failed, course_id)) if pending: pending_messages.append(cls.get_pending_enrollment_message(pending, course_id)) if program_details: succeeded, pending, failed = cls.enroll_users_in_program( enterprise_customer=enterprise_customer, program_details=program_details, course_mode=mode, emails=emails, ) all_successes = succeeded + pending if notify: cls.notify_program_learners( enterprise_customer=enterprise_customer, program_details=program_details, users=all_successes ) program_identifier = program_details.get('title', program_details.get('uuid', _('the program'))) if succeeded: pending_messages.append(cls.get_success_enrollment_message(succeeded, program_identifier)) if failed: pending_messages.append(cls.get_failed_enrollment_message(failed, program_identifier)) if pending: pending_messages.append(cls.get_pending_enrollment_message(pending, program_identifier)) cls.send_messages(request, pending_messages)
def get(self, request, customer_uuid): """ Handle GET request - render linked learners list and "Link learner" form. Arguments: request (django.http.request.HttpRequest): Request instance customer_uuid (str): Enterprise Customer UUID Returns: django.http.response.HttpResponse: HttpResponse """ context = self._build_context(request, customer_uuid) manage_learners_form = ManageLearnersForm( user=request.user, enterprise_customer=context[self.ContextParameters.ENTERPRISE_CUSTOMER] ) context.update({self.ContextParameters.MANAGE_LEARNERS_FORM: manage_learners_form}) return render(request, self.template, context)