Exemplo n.º 1
0
    def post(self, request):
        """
        Audit enrolls the user in a course in edx
        """
        course_id = request.data.get('course_id')
        if course_id is None:
            raise ValidationError('course id missing in the request')
        # get the credentials for the current user for edX
        user_social = get_social_auth(request.user)
        try:
            utils.refresh_user_token(user_social)
        except utils.InvalidCredentialStored as exc:
            log.error(
                "Error while refreshing credentials for user %s",
                get_social_username(request.user),
            )
            return Response(
                status=exc.http_status_code,
                data={'error': str(exc)}
            )

        # create an instance of the client to query edX
        edx_client = EdxApi(user_social.extra_data, settings.EDXORG_BASE_URL)

        try:
            enrollment = edx_client.enrollments.create_audit_student_enrollment(course_id)
        except HTTPError as exc:
            if exc.response.status_code == status.HTTP_400_BAD_REQUEST:
                raise PossiblyImproperlyConfigured(
                    'Got a 400 status code from edX server while trying to create '
                    'audit enrollment. This might happen if the course is improperly '
                    'configured on MicroMasters. Course key '
                    '{course_key}, edX user "{edX_user}"'.format(
                        edX_user=get_social_username(request.user),
                        course_key=course_id,
                    )
                )
            log.error(
                "Http error from edX while creating audit enrollment for course key %s for edX user %s",
                course_id,
                get_social_username(request.user),
            )
            return Response(
                status=status.HTTP_500_INTERNAL_SERVER_ERROR,
                data={'error': str(exc)}
            )
        except Exception as exc:  # pylint: disable=broad-except
            log.exception(
                "Error creating audit enrollment for course key %s for edX user %s",
                course_id,
                get_social_username(request.user),
            )
            return Response(
                status=status.HTTP_500_INTERNAL_SERVER_ERROR,
                data={'error': str(exc)}
            )
        CachedEdxDataApi.update_cached_enrollment(request.user, enrollment, enrollment.course_id, index_user=True)
        return Response(
            data=enrollment.json
        )
Exemplo n.º 2
0
    def test_update_cached_enrollment(self, mocked_index):
        """Test for update_cached_enrollment"""
        course_id = list(self.enrollment_ids)[0]
        enrollment = self.enrollments.get_enrollment_for_course(course_id)
        self.assert_cache_in_db()

        # normal update that creates also the entry
        CachedEdxDataApi.update_cached_enrollment(self.user, enrollment, course_id, False)
        self.assert_cache_in_db(enrollment_keys=[course_id])
        cached_enr = CachedEnrollment.objects.get(user=self.user, course_run__edx_course_key=course_id)
        assert cached_enr.data == enrollment.json
        assert mocked_index.delay.called is False
        # update of different data with indexing
        enr_json = {
            "course_details": {
                "course_id": course_id,
            },
            "is_active": True,
            "mode": "verified",
            "user": self.user.username
        }
        enrollment_new = Enrollment(enr_json)
        CachedEdxDataApi.update_cached_enrollment(self.user, enrollment_new, course_id, True)
        self.assert_cache_in_db(enrollment_keys=[course_id])
        cached_enr.refresh_from_db()
        assert cached_enr.data == enr_json
        mocked_index.delay.assert_any_call([self.user.id], check_if_changed=True)
    def test_update_cached_enrollment(self, mocked_index):
        """Test for update_cached_enrollment"""
        course_id = list(self.enrollment_ids)[0]
        enrollment = self.enrollments.get_enrollment_for_course(course_id)
        self.assert_cache_in_db()

        # normal update that creates also the entry
        CachedEdxDataApi.update_cached_enrollment(self.user, enrollment,
                                                  course_id, False)
        self.assert_cache_in_db(enrollment_keys=[course_id])
        cached_enr = CachedEnrollment.objects.get(
            user=self.user, course_run__edx_course_key=course_id)
        assert cached_enr.data == enrollment.json
        assert mocked_index.delay.called is False
        # update of different data with indexing
        enr_json = {
            "course_details": {
                "course_id": course_id,
            },
            "is_active": True,
            "mode": "verified",
            "user": self.user.username
        }
        enrollment_new = Enrollment(enr_json)
        CachedEdxDataApi.update_cached_enrollment(self.user, enrollment_new,
                                                  course_id, True)
        self.assert_cache_in_db(enrollment_keys=[course_id])
        cached_enr.refresh_from_db()
        assert cached_enr.data == enr_json
        mocked_index.delay.assert_any_call([self.user.id],
                                           check_if_changed=True)
Exemplo n.º 4
0
    def post(self, request):
        """
        Audit enrolls the user in a course in edx
        """
        course_id = request.data.get('course_id')
        if course_id is None:
            raise ValidationError('course id missing in the request')
        # get the credentials for the current user for edX
        user_social = get_social_auth(request.user)
        try:
            utils.refresh_user_token(user_social)
        except utils.InvalidCredentialStored as exc:
            log.error(
                "Error while refreshing credentials for user %s",
                get_social_username(request.user),
            )
            return Response(
                status=exc.http_status_code,
                data={'error': str(exc)}
            )

        # create an instance of the client to query edX
        edx_client = EdxApi(user_social.extra_data, settings.EDXORG_BASE_URL)

        try:
            enrollment = edx_client.enrollments.create_audit_student_enrollment(course_id)
        except HTTPError as exc:
            if exc.response.status_code == status.HTTP_400_BAD_REQUEST:
                raise PossiblyImproperlyConfigured(
                    'Got a 400 status code from edX server while trying to create '
                    'audit enrollment. This might happen if the course is improperly '
                    'configured on MicroMasters. Course key '
                    '{course_key}, edX user "{edX_user}"'.format(
                        edX_user=get_social_username(request.user),
                        course_key=course_id,
                    )
                )
            log.error(
                "Http error from edX while creating audit enrollment for course key %s for edX user %s",
                course_id,
                get_social_username(request.user),
            )
            return Response(
                status=status.HTTP_500_INTERNAL_SERVER_ERROR,
                data={'error': str(exc)}
            )
        except Exception as exc:  # pylint: disable=broad-except
            log.exception(
                "Error creating audit enrollment for course key %s for edX user %s",
                course_id,
                get_social_username(request.user),
            )
            return Response(
                status=status.HTTP_500_INTERNAL_SERVER_ERROR,
                data={'error': str(exc)}
            )
        CachedEdxDataApi.update_cached_enrollment(request.user, enrollment, enrollment.course_id, index_user=True)
        return Response(
            data=enrollment.json
        )
Exemplo n.º 5
0
def enroll_user_on_success(order):
    """
    Enroll user after they made a successful purchase.

    Args:
        order (Order): An order to be fulfilled

    Returns:
         None
    """
    user_social = get_social_auth(order.user)
    enrollments_client = EdxApi(user_social.extra_data,
                                settings.EDXORG_BASE_URL).enrollments
    existing_enrollments = enrollments_client.get_student_enrollments()

    exceptions = []
    enrollments = []
    for line in order.line_set.all():
        course_key = line.course_key
        try:
            if not existing_enrollments.is_enrolled_in(course_key):
                enrollments.append(
                    enrollments_client.create_audit_student_enrollment(
                        course_key))
        except Exception as ex:  # pylint: disable=broad-except
            log.exception(
                "Error creating audit enrollment for course key %s for user %s",
                course_key,
                get_social_username(order.user),
            )
            exceptions.append(ex)

    for enrollment in enrollments:
        CachedEdxDataApi.update_cached_enrollment(
            order.user,
            enrollment,
            enrollment.course_id,
            index_user=True,
        )

    if exceptions:
        raise EcommerceEdxApiException(exceptions)
Exemplo n.º 6
0
def enroll_user_on_success(order):
    """
    Enroll user after they made a successful purchase.

    Args:
        order (Order): An order to be fulfilled

    Returns:
         None
    """
    user_social = get_social_auth(order.user)
    enrollments_client = EdxApi(user_social.extra_data, settings.EDXORG_BASE_URL).enrollments
    existing_enrollments = enrollments_client.get_student_enrollments()

    exceptions = []
    enrollments = []
    for line in order.line_set.all():
        course_key = line.course_key
        try:
            if not existing_enrollments.is_enrolled_in(course_key):
                enrollments.append(enrollments_client.create_audit_student_enrollment(course_key))
        except Exception as ex:  # pylint: disable=broad-except
            log.exception(
                "Error creating audit enrollment for course key %s for user %s",
                course_key,
                get_social_username(order.user),
            )
            exceptions.append(ex)

    for enrollment in enrollments:
        CachedEdxDataApi.update_cached_enrollment(
            order.user,
            enrollment,
            enrollment.course_id,
            index_user=True,
        )

    if exceptions:
        raise EcommerceEdxApiException(exceptions)