コード例 #1
0
    def test_filter_inactive_user_partitions(self):
        """
        Tests supplying the `active_only` parameter.
        """
        self.user_partition = UserPartition(self.TEST_ID,
                                            self.TEST_NAME,
                                            self.TEST_DESCRIPTION,
                                            self.TEST_GROUPS,
                                            self.non_random_scheme,
                                            self.TEST_PARAMETERS,
                                            active=False)
        self.course.user_partitions = [self.user_partition]

        all_partitions = get_all_partitions_for_course(self.course,
                                                       active_only=True)
        self.assertEqual(1, len(all_partitions))
        self.assertEqual(self.ENROLLMENT_TRACK_SCHEME_NAME,
                         all_partitions[0].scheme.name)

        all_partitions = get_all_partitions_for_course(self.course,
                                                       active_only=False)
        self.assertEqual(2, len(all_partitions))
        self.assertEqual(self.TEST_SCHEME_NAME, all_partitions[0].scheme.name)
        self.assertEqual(self.ENROLLMENT_TRACK_SCHEME_NAME,
                         all_partitions[1].scheme.name)
コード例 #2
0
ファイル: utils.py プロジェクト: valutac/edx-platform
def get_experiment_user_metadata_context(course, user):
    """
    Return a context dictionary with the keys used by the user_metadata.html.
    """
    enrollment_mode = None
    enrollment_time = None
    enrollment = None
    # TODO: clean up as part of REVO-28 (START)
    has_non_audit_enrollments = None
    # TODO: clean up as part of REVO-28 (END)
    try:
        # TODO: clean up as part of REVO-28 (START)
        user_enrollments = CourseEnrollment.objects.select_related(
            'course').filter(user_id=user.id)
        audit_enrollments = user_enrollments.filter(mode='audit')
        has_non_audit_enrollments = (len(audit_enrollments) !=
                                     len(user_enrollments))
        # TODO: clean up as part of REVO-28 (END)
        enrollment = CourseEnrollment.objects.select_related('course').get(
            user_id=user.id, course_id=course.id)
        if enrollment.is_active:
            enrollment_mode = enrollment.mode
            enrollment_time = enrollment.created
    except CourseEnrollment.DoesNotExist:
        pass  # Not enrolled, used the default None values

    upgrade_link, upgrade_date = check_and_get_upgrade_link_and_date(
        user, enrollment, course)
    has_staff_access = has_staff_access_to_preview_mode(user, course.id)
    forum_roles = []
    if user.is_authenticated:
        forum_roles = list(
            Role.objects.filter(
                users=user,
                course_id=course.id).values_list('name').distinct())

    # get user partition data
    partition_groups = get_all_partitions_for_course(course)
    user_partitions = get_user_partition_groups(course.id, partition_groups,
                                                user, 'name')

    return {
        'upgrade_link': upgrade_link,
        'upgrade_price': unicode(get_cosmetic_verified_display_price(course)),
        'enrollment_mode': enrollment_mode,
        'enrollment_time': enrollment_time,
        'pacing_type':
        'self_paced' if course.self_paced else 'instructor_paced',
        'upgrade_deadline': upgrade_date,
        'course_key': course.id,
        'course_start': course.start,
        'course_end': course.end,
        'has_staff_access': has_staff_access,
        'forum_roles': forum_roles,
        'partition_groups': user_partitions,
        # TODO: clean up as part of REVO-28 (START)
        'has_non_audit_enrollments': has_non_audit_enrollments,
        # TODO: clean up as part of REVO-28 (END)
    }
コード例 #3
0
ファイル: masquerade.py プロジェクト: saltfun/edx-platform
 def get(self, request, course_key_string):
     """
     Retrieve data on the active and available masquerade options
     """
     course_key = CourseKey.from_string(course_key_string)
     is_staff = has_staff_roles(request.user, course_key)
     if not is_staff:
         return JsonResponse({
             'success': False,
         })
     masquerade_settings = request.session.get(MASQUERADE_SETTINGS_KEY, {})
     course = masquerade_settings.get(course_key, None)
     course = course or CourseMasquerade(
         course_key,
         role='staff',
         user_partition_id=None,
         group_id=None,
         user_name=None,
     )
     descriptor = modulestore().get_course(course_key)
     partitions = get_all_partitions_for_course(descriptor,
                                                active_only=True)
     data = {
         'success':
         True,
         'active': {
             'course_key': course_key_string,
             'group_id': course.group_id,
             'role': course.role,
             'user_name': course.user_name or None,
             'user_partition_id': course.user_partition_id,
         },
         'available': [
             {
                 'name': 'Staff',
                 'role': 'staff',
             },
             {
                 'name': 'Learner',
                 'role': 'student',
             },
             {
                 'name': 'Specific Student...',
                 'role': 'student',
                 'user_name': course.user_name or '',
             },
         ],
     }
     for partition in partitions:
         if partition.active:
             data['available'].extend([{
                 'group_id': group.id,
                 'name': group.name,
                 'role': 'student',
                 'user_partition_id': partition.id,
             } for group in partition.groups])
     data['active']['group_name'] = course.get_active_group_name(
         data['available'])
     return JsonResponse(data)
コード例 #4
0
 def test_enrollment_track_partition_not_added_if_disabled(self):
     """
     Test that the dynamic enrollment track scheme is NOT added if the settings FEATURE flag is disabled.
     """
     TestGetCourseUserPartitions._enable_enrollment_track_partition(False)
     all_partitions = get_all_partitions_for_course(self.course)
     self.assertEqual(1, len(all_partitions))
     self.assertEqual(self.TEST_SCHEME_NAME, all_partitions[0].scheme.name)
コード例 #5
0
 def test_enrollment_track_partition_not_added_if_disabled(self):
     """
     Test that the dynamic enrollment track scheme is NOT added if the settings FEATURE flag is disabled.
     """
     TestGetCourseUserPartitions._enable_enrollment_track_partition(False)
     all_partitions = get_all_partitions_for_course(self.course)
     self.assertEqual(1, len(all_partitions))
     self.assertEqual(self.TEST_SCHEME_NAME, all_partitions[0].scheme.name)
コード例 #6
0
 def assign_group_ids(self):
     """
     Assign ids for the group_configuration's groups.
     """
     used_ids = [g.id for p in get_all_partitions_for_course(self.course) for g in p.groups]
     # Assign ids to every group in configuration.
     for group in self.configuration.get('groups', []):
         if group.get('id') is None:
             group["id"] = generate_int_id(MINIMUM_GROUP_ID, MYSQL_MAX_INT, used_ids)
             used_ids.append(group["id"])
コード例 #7
0
 def assign_group_ids(self):
     """
     Assign ids for the group_configuration's groups.
     """
     used_ids = [g.id for p in get_all_partitions_for_course(self.course) for g in p.groups]
     # Assign ids to every group in configuration.
     for group in self.configuration.get('groups', []):
         if group.get('id') is None:
             group["id"] = generate_int_id(MINIMUM_GROUP_ID, MYSQL_MAX_INT, used_ids)
             used_ids.append(group["id"])
コード例 #8
0
ファイル: test_partitions.py プロジェクト: sliva/edx-platform
 def test_enrollment_track_partition_added(self):
     """
     Test that the dynamic enrollment track scheme is added if there is no conflict with the user partition ID.
     """
     all_partitions = get_all_partitions_for_course(self.course)
     self.assertEqual(2, len(all_partitions))
     self.assertEqual(self.TEST_SCHEME_NAME, all_partitions[0].scheme.name)
     enrollment_track_partition = all_partitions[1]
     self.assertEqual(self.ENROLLMENT_TRACK_SCHEME_NAME, enrollment_track_partition.scheme.name)
     self.assertEqual(six.text_type(self.course.id), enrollment_track_partition.parameters['course_id'])
     self.assertEqual(ENROLLMENT_TRACK_PARTITION_ID, enrollment_track_partition.id)
コード例 #9
0
 def test_enrollment_track_partition_added(self):
     """
     Test that the dynamic enrollment track scheme is added if there is no conflict with the user partition ID.
     """
     all_partitions = get_all_partitions_for_course(self.course)
     assert 2 == len(all_partitions)
     assert self.TEST_SCHEME_NAME == all_partitions[0].scheme.name
     enrollment_track_partition = all_partitions[1]
     assert self.ENROLLMENT_TRACK_SCHEME_NAME == enrollment_track_partition.scheme.name
     assert str(self.course.id) == enrollment_track_partition.parameters['course_id']
     assert ENROLLMENT_TRACK_PARTITION_ID == enrollment_track_partition.id
コード例 #10
0
 def test_enrollment_track_partition_added(self):
     """
     Test that the dynamic enrollment track scheme is added if there is no conflict with the user partition ID.
     """
     all_partitions = get_all_partitions_for_course(self.course)
     self.assertEqual(2, len(all_partitions))
     self.assertEqual(self.TEST_SCHEME_NAME, all_partitions[0].scheme.name)
     enrollment_track_partition = all_partitions[1]
     self.assertEqual(self.ENROLLMENT_TRACK_SCHEME_NAME, enrollment_track_partition.scheme.name)
     self.assertEqual(unicode(self.course.id), enrollment_track_partition.parameters['course_id'])
     self.assertEqual(ENROLLMENT_TRACK_PARTITION_ID, enrollment_track_partition.id)
コード例 #11
0
    def get_all_user_partition_details(store, course):
        """
        Returns all the available partitions with updated usage information

        :return: list of all partitions available with details
        """
        all_partitions = get_all_partitions_for_course(course)
        all_updated_partitions = []
        for partition in all_partitions:
            configuration = GroupConfiguration.update_partition_usage_info(
                store, course, partition)
            all_updated_partitions.append(configuration)
        return all_updated_partitions
コード例 #12
0
ファイル: utils.py プロジェクト: saad-waqar/edx-platform
def get_experiment_user_metadata_context(course, user):
    """
    Return a context dictionary with the keys used by the user_metadata.html.
    """
    enrollment = None
    # TODO: clean up as part of REVO-28 (START)
    user_enrollments = None
    audit_enrollments = None
    has_non_audit_enrollments = False
    try:
        user_enrollments = CourseEnrollment.objects.select_related(
            'course', 'schedule').filter(user_id=user.id)
        has_non_audit_enrollments = user_enrollments.exclude(
            mode__in=CourseMode.UPSELL_TO_VERIFIED_MODES).exists()
        # TODO: clean up as part of REVO-28 (END)
        enrollment = CourseEnrollment.objects.select_related(
            'course', 'schedule').get(user_id=user.id, course_id=course.id)
    except CourseEnrollment.DoesNotExist:
        pass  # Not enrolled, use the default values

    has_entitlements = False
    if user.is_authenticated():
        has_entitlements = CourseEntitlement.objects.filter(user=user).exists()

    context = get_base_experiment_metadata_context(course, user, enrollment,
                                                   user_enrollments)
    has_staff_access = has_staff_access_to_preview_mode(user, course.id)
    forum_roles = []
    if user.is_authenticated:
        forum_roles = list(
            Role.objects.filter(
                users=user,
                course_id=course.id).values_list('name').distinct())

    # get user partition data
    if user.is_authenticated():
        partition_groups = get_all_partitions_for_course(course)
        user_partitions = get_user_partition_groups(course.id,
                                                    partition_groups, user,
                                                    'name')
    else:
        user_partitions = {}

    # TODO: clean up as part of REVO-28 (START)
    context[
        'has_non_audit_enrollments'] = has_non_audit_enrollments or has_entitlements
    # TODO: clean up as part of REVO-28 (END)
    context['has_staff_access'] = has_staff_access
    context['forum_roles'] = forum_roles
    context['partition_groups'] = user_partitions
    return context
コード例 #13
0
def get_experiment_user_metadata_context(course, user):
    """
    Return a context dictionary with the keys used by the user_metadata.html.
    """
    if DEPRECATED_METADATA.is_enabled():
        return get_deprecated_experiment_user_metadata_context(course, user)

    enrollment = None
    # TODO: clean up as part of REVO-28 (START)
    user_enrollments = None
    audit_enrollments = None
    has_non_audit_enrollments = False
    try:
        user_enrollments = CourseEnrollment.objects.select_related(
            'course').filter(user_id=user.id)
        audit_enrollments = user_enrollments.filter(mode='audit')
        has_non_audit_enrollments = (len(audit_enrollments) !=
                                     len(user_enrollments))
        # TODO: clean up as part of REVO-28 (END)
        enrollment = CourseEnrollment.objects.select_related('course').get(
            user_id=user.id, course_id=course.id)
    except CourseEnrollment.DoesNotExist:
        pass  # Not enrolled, use the default values

    context = get_base_experiment_metadata_context(course, user, enrollment,
                                                   user_enrollments,
                                                   audit_enrollments)
    has_staff_access = has_staff_access_to_preview_mode(user, course.id)
    forum_roles = []
    if user.is_authenticated:
        forum_roles = list(
            Role.objects.filter(
                users=user,
                course_id=course.id).values_list('name').distinct())

    # get user partition data
    if user.is_authenticated():
        partition_groups = get_all_partitions_for_course(course)
        user_partitions = get_user_partition_groups(course.id,
                                                    partition_groups, user,
                                                    'name')
    else:
        user_partitions = {}

    # TODO: clean up as part of REVO-28 (START)
    context['has_non_audit_enrollments'] = has_non_audit_enrollments
    # TODO: clean up as part of REVO-28 (END)
    context['has_staff_access'] = has_staff_access
    context['forum_roles'] = forum_roles
    context['partition_groups'] = user_partitions
    return context
コード例 #14
0
    def test_filter_inactive_user_partitions(self):
        """
        Tests supplying the `active_only` parameter.
        """
        self.user_partition = UserPartition(
            self.TEST_ID,
            self.TEST_NAME,
            self.TEST_DESCRIPTION,
            self.TEST_GROUPS,
            self.non_random_scheme,
            self.TEST_PARAMETERS,
            active=False
        )
        self.course.user_partitions = [self.user_partition]

        all_partitions = get_all_partitions_for_course(self.course, active_only=True)
        self.assertEqual(1, len(all_partitions))
        self.assertEqual(self.ENROLLMENT_TRACK_SCHEME_NAME, all_partitions[0].scheme.name)

        all_partitions = get_all_partitions_for_course(self.course, active_only=False)
        self.assertEqual(2, len(all_partitions))
        self.assertEqual(self.TEST_SCHEME_NAME, all_partitions[0].scheme.name)
        self.assertEqual(self.ENROLLMENT_TRACK_SCHEME_NAME, all_partitions[1].scheme.name)
コード例 #15
0
    def get_all_user_partition_details(store, course):
        """
        Returns all the available partitions with updated usage information

        :return: list of all partitions available with details
        """
        all_partitions = get_all_partitions_for_course(course)
        all_updated_partitions = []
        for partition in all_partitions:
            configuration = GroupConfiguration.update_partition_usage_info(
                store,
                course,
                partition
            )
            all_updated_partitions.append(configuration)
        return all_updated_partitions
コード例 #16
0
 def test_enrollment_track_partition_not_added_if_conflict(self):
     """
     Test that the dynamic enrollment track scheme is NOT added if a UserPartition exists with that ID.
     """
     self.user_partition = UserPartition(
         ENROLLMENT_TRACK_PARTITION_ID,
         self.TEST_NAME,
         self.TEST_DESCRIPTION,
         self.TEST_GROUPS,
         self.non_random_scheme,
         self.TEST_PARAMETERS,
     )
     self.course.user_partitions = [self.user_partition]
     all_partitions = get_all_partitions_for_course(self.course)
     self.assertEqual(1, len(all_partitions))
     self.assertEqual(self.TEST_SCHEME_NAME, all_partitions[0].scheme.name)
コード例 #17
0
 def test_enrollment_track_partition_not_added_if_conflict(self):
     """
     Test that the dynamic enrollment track scheme is NOT added if a UserPartition exists with that ID.
     """
     self.user_partition = UserPartition(
         ENROLLMENT_TRACK_PARTITION_ID,
         self.TEST_NAME,
         self.TEST_DESCRIPTION,
         self.TEST_GROUPS,
         self.non_random_scheme,
         self.TEST_PARAMETERS,
     )
     self.course.user_partitions = [self.user_partition]
     all_partitions = get_all_partitions_for_course(self.course)
     self.assertEqual(1, len(all_partitions))
     self.assertEqual(self.TEST_SCHEME_NAME, all_partitions[0].scheme.name)
コード例 #18
0
    def _iterate_items_and_group_ids(course, items):
        """
        Iterate through items and group IDs in a course.

        This will yield group IDs for all user partitions except those with a scheme of random.

        Yields: tuple of (item, group_id)
        """
        all_partitions = get_all_partitions_for_course(course)
        for config in all_partitions:
            if config is not None and config.scheme.name != RANDOM_SCHEME:
                for item in items:
                    if hasattr(item, 'group_access') and item.group_access:
                        group_ids = item.group_access.get(config.id, [])

                        for group_id in group_ids:
                            yield item, group_id
コード例 #19
0
    def _iterate_items_and_group_ids(course, items):
        """
        Iterate through items and group IDs in a course.

        This will yield group IDs for all user partitions except those with a scheme of random.

        Yields: tuple of (item, group_id)
        """
        all_partitions = get_all_partitions_for_course(course)
        for config in all_partitions:
            if config is not None and config.scheme.name != RANDOM_SCHEME:
                for item in items:
                    if hasattr(item, 'group_access') and item.group_access:
                        group_ids = item.group_access.get(config.id, [])

                        for group_id in group_ids:
                            yield item, group_id
コード例 #20
0
ファイル: utils.py プロジェクト: edx/edx-platform
def get_experiment_user_metadata_context(course, user):
    """
    Return a context dictionary with the keys used by the user_metadata.html.
    """
    if DEPRECATED_METADATA.is_enabled():
        return get_deprecated_experiment_user_metadata_context(course, user)

    enrollment = None
    # TODO: clean up as part of REVO-28 (START)
    user_enrollments = None
    audit_enrollments = None
    has_non_audit_enrollments = False
    try:
        user_enrollments = CourseEnrollment.objects.select_related('course').filter(user_id=user.id)
        audit_enrollments = user_enrollments.filter(mode='audit')
        has_non_audit_enrollments = (len(audit_enrollments) != len(user_enrollments))
        # TODO: clean up as part of REVO-28 (END)
        enrollment = CourseEnrollment.objects.select_related(
            'course'
        ).get(user_id=user.id, course_id=course.id)
    except CourseEnrollment.DoesNotExist:
        pass  # Not enrolled, use the default values

    context = get_base_experiment_metadata_context(course, user, enrollment, user_enrollments, audit_enrollments)
    has_staff_access = has_staff_access_to_preview_mode(user, course.id)
    forum_roles = []
    if user.is_authenticated:
        forum_roles = list(Role.objects.filter(users=user, course_id=course.id).values_list('name').distinct())

    # get user partition data
    if user.is_authenticated():
        partition_groups = get_all_partitions_for_course(course)
        user_partitions = get_user_partition_groups(course.id, partition_groups, user, 'name')
    else:
        user_partitions = {}

    # TODO: clean up as part of REVO-28 (START)
    context['has_non_audit_enrollments'] = has_non_audit_enrollments
    # TODO: clean up as part of REVO-28 (END)
    context['has_staff_access'] = has_staff_access
    context['forum_roles'] = forum_roles
    context['partition_groups'] = user_partitions
    return context
コード例 #21
0
    def setUpClass(cls):
        super(EnrollmentTrackTestCase, cls).setUpClass()
        cls.course = CourseFactory.create()
        cls.course_key = cls.course.id
        CourseMode.objects.create(course_id=cls.course_key, mode_slug=CourseMode.AUDIT, mode_display_name='Audit')
        CourseMode.objects.create(
            course_id=cls.course_key,
            mode_slug=CourseMode.VERIFIED,
            mode_display_name='Verified',
            min_price=1.5,
        )

        cls.partitions = partitions_service.get_all_partitions_for_course(cls.course)
        verified_track_partition_id = 2  # This is determined by the order CourseMode objects are created.
        with cls.store.bulk_operations(cls.course.id):
            cls.chapter = ItemFactory.create(
                parent=cls.course,
                category="chapter",
            )
            cls.vertical1 = ItemFactory.create(
                parent=cls.chapter,
                category="vertical",
                group_access={ENROLLMENT_TRACK_PARTITION_ID: [verified_track_partition_id]},
            )

            cls.vertical2 = ItemFactory.create(
                parent=cls.chapter,
                category="vertical",
            )
            cls.problem1 = ItemFactory.create(
                parent=cls.vertical1,
                category="problem",
            )
            cls.problem2 = ItemFactory.create(
                parent=cls.vertical2,
                category="problem",
            )
            cls.problem3 = ItemFactory.create(
                parent=cls.vertical2,
                category="problem",
                group_access={ENROLLMENT_TRACK_PARTITION_ID: [verified_track_partition_id]},
            )
コード例 #22
0
ファイル: user_partitions.py プロジェクト: yf/edx-platform
    def collect(cls, block_structure):
        """
        Computes any information for each XBlock that's necessary to
        execute this transformer's transform method.

        Arguments:
            block_structure (BlockStructureCollectedData)
        """
        # First have the split test transformer setup its group access
        # data for each block.
        SplitTestTransformer.collect(block_structure)

        # Because user partitions are course-wide, only store data for
        # them on the root block.
        root_block = block_structure.get_xblock(
            block_structure.root_block_usage_key)
        user_partitions = get_all_partitions_for_course(root_block,
                                                        active_only=True)
        block_structure.set_transformer_data(cls, 'user_partitions',
                                             user_partitions)

        # If there are no user partitions, this transformation is a
        # no-op, so there is nothing to collect.
        if not user_partitions:
            return

        # For each block, compute merged group access. Because this is a
        # topological sort, we know a block's parents are guaranteed to
        # already have merged group access computed before the block
        # itself.
        for block_key in block_structure.topological_traversal():
            xblock = block_structure.get_xblock(block_key)
            parent_keys = block_structure.get_parents(block_key)
            merged_parent_access_list = [
                block_structure.get_transformer_block_field(
                    parent_key, cls, 'merged_group_access')
                for parent_key in parent_keys
            ]
            merged_group_access = _MergedGroupAccess(
                user_partitions, xblock, merged_parent_access_list)
            block_structure.set_transformer_block_field(
                block_key, cls, 'merged_group_access', merged_group_access)
コード例 #23
0
    def setUpClass(cls):
        super(EnrollmentTrackTestCase, cls).setUpClass()
        cls.course = CourseFactory.create()
        cls.course_key = cls.course.id
        CourseMode.objects.create(course_id=cls.course_key, mode_slug=CourseMode.AUDIT, mode_display_name='Audit')
        CourseMode.objects.create(
            course_id=cls.course_key,
            mode_slug=CourseMode.VERIFIED,
            mode_display_name='Verified',
            min_price=1.5,
        )

        cls.partitions = partitions_service.get_all_partitions_for_course(cls.course)
        verified_track_partition_id = 2  # This is determined by the order CourseMode objects are created.
        with cls.store.bulk_operations(cls.course.id):
            cls.chapter = ItemFactory.create(
                parent=cls.course,
                category="chapter",
            )
            cls.vertical1 = ItemFactory.create(
                parent=cls.chapter,
                category="vertical",
                group_access={ENROLLMENT_TRACK_PARTITION_ID: [verified_track_partition_id]},
            )

            cls.vertical2 = ItemFactory.create(
                parent=cls.chapter,
                category="vertical",
            )
            cls.problem1 = ItemFactory.create(
                parent=cls.vertical1,
                category="problem",
            )
            cls.problem2 = ItemFactory.create(
                parent=cls.vertical2,
                category="problem",
            )
            cls.problem3 = ItemFactory.create(
                parent=cls.vertical2,
                category="problem",
                group_access={ENROLLMENT_TRACK_PARTITION_ID: [verified_track_partition_id]},
            )
コード例 #24
0
ファイル: utils.py プロジェクト: mitocw/edx-platform
def get_experiment_user_metadata_context(course, user):
    """
    Return a context dictionary with the keys used by the user_metadata.html.
    """
    enrollment_mode = None
    enrollment_time = None
    enrollment = None
    try:
        enrollment = CourseEnrollment.objects.select_related(
            'course'
        ).get(user_id=user.id, course_id=course.id)
        if enrollment.is_active:
            enrollment_mode = enrollment.mode
            enrollment_time = enrollment.created
    except CourseEnrollment.DoesNotExist:
        pass  # Not enrolled, used the default None values

    upgrade_link, upgrade_date = check_and_get_upgrade_link_and_date(user, enrollment, course)
    has_staff_access = has_staff_access_to_preview_mode(user, course.id)
    forum_roles = []
    if user.is_authenticated:
        forum_roles = list(Role.objects.filter(users=user, course_id=course.id).values_list('name').distinct())

    # get user partition data
    partition_groups = get_all_partitions_for_course(course)
    user_partitions = get_user_partition_groups(course.id, partition_groups, user, 'name')

    return {
        'upgrade_link': upgrade_link,
        'upgrade_price': unicode(get_cosmetic_verified_display_price(course)),
        'enrollment_mode': enrollment_mode,
        'enrollment_time': enrollment_time,
        'pacing_type': 'self_paced' if course.self_paced else 'instructor_paced',
        'upgrade_deadline': upgrade_date,
        'course_key': course.id,
        'course_start': course.start,
        'course_end': course.end,
        'has_staff_access': has_staff_access,
        'forum_roles': forum_roles,
        'partition_groups': user_partitions,
    }
コード例 #25
0
ファイル: user_partitions.py プロジェクト: edx/edx-platform
    def collect(cls, block_structure):
        """
        Computes any information for each XBlock that's necessary to
        execute this transformer's transform method.

        Arguments:
            block_structure (BlockStructureCollectedData)
        """
        # First have the split test transformer setup its group access
        # data for each block.
        SplitTestTransformer.collect(block_structure)

        # Because user partitions are course-wide, only store data for
        # them on the root block.
        root_block = block_structure.get_xblock(block_structure.root_block_usage_key)
        user_partitions = get_all_partitions_for_course(root_block, active_only=True)
        block_structure.set_transformer_data(cls, 'user_partitions', user_partitions)

        # If there are no user partitions, this transformation is a
        # no-op, so there is nothing to collect.
        if not user_partitions:
            return

        # For each block, compute merged group access. Because this is a
        # topological sort, we know a block's parents are guaranteed to
        # already have merged group access computed before the block
        # itself.
        for block_key in block_structure.topological_traversal():
            xblock = block_structure.get_xblock(block_key)
            parent_keys = block_structure.get_parents(block_key)
            merged_parent_access_list = [
                block_structure.get_transformer_block_field(parent_key, cls, 'merged_group_access')
                for parent_key in parent_keys
            ]
            merged_group_access = _MergedGroupAccess(user_partitions, xblock, merged_parent_access_list)
            block_structure.set_transformer_block_field(block_key, cls, 'merged_group_access', merged_group_access)
コード例 #26
0
 def get_used_ids(course):
     """
     Return a list of IDs that already in use.
     """
     return set([p.id for p in get_all_partitions_for_course(course)])  # lint-amnesty, pylint: disable=consider-using-set-comprehension
コード例 #27
0
def get_experiment_user_metadata_context(course, user):
    """
    Return a context dictionary with the keys used by the user_metadata.html.
    """
    enrollment_mode = None
    enrollment_time = None
    enrollment = None
    # TODO: clean up as part of REVO-28 (START)
    has_non_audit_enrollments = None
    # TODO: clean up as part of REVO-28 (END)
    # TODO: clean up as part of REVEM-106 (START)
    program_key = None
    # TODO: clean up as part of REVEM-106 (END)
    try:
        # TODO: clean up as part of REVO-28 (START)
        user_enrollments = CourseEnrollment.objects.select_related(
            'course').filter(user_id=user.id)
        audit_enrollments = user_enrollments.filter(mode='audit')
        has_non_audit_enrollments = (len(audit_enrollments) !=
                                     len(user_enrollments))
        # TODO: clean up as part of REVO-28 (END)
        enrollment = CourseEnrollment.objects.select_related('course').get(
            user_id=user.id, course_id=course.id)
        if enrollment.is_active:
            enrollment_mode = enrollment.mode
            enrollment_time = enrollment.created

            # TODO: clean up as part of REVEM-106 (START)
            # get program data for this course
            request = get_current_request()
            if request:
                enrollment_list = [enrollment]
                meter = ProgramProgressMeter(request.site,
                                             user,
                                             enrollments=enrollment_list)
                if meter.engaged_programs and meter.engaged_programs[0]:
                    org_name = None
                    courses_not_started = 0
                    courses_in_progress = 0
                    courses_completed = 0
                    program_data = meter.engaged_programs[0]
                    program_data = ProgramDataExtender(
                        program_data, user, mobile_only=False).extend()
                    program_orgs = program_data.get(
                        'credit_backing_organizations')
                    if program_orgs and program_orgs[0]:
                        org = program_orgs[0]
                        org_name = org.get('name')
                    if meter.progress() and meter.progress()[0]:
                        progress = meter.progress()[0]
                        courses_not_started = progress.get('not_started')
                        courses_in_progress = progress.get('in_progress')
                        courses_completed = progress.get('completed')
                    program_key = {
                        'uuid': program_data.get('uuid'),
                        'title': program_data.get('title'),
                        'marketing_url': program_data.get('marketing_url'),
                        'org_name': org_name,
                        'courses_not_started': courses_not_started,
                        'courses_in_progress': courses_in_progress,
                        'courses_completed': courses_completed,
                    }
            # TODO: clean up as part of REVEM-106 (END)
    except CourseEnrollment.DoesNotExist:
        pass  # Not enrolled, used the default None values

    # upgrade_link and upgrade_date should be None if user has passed their dynamic pacing deadline.
    upgrade_link, upgrade_date = check_and_get_upgrade_link_and_date(
        user, enrollment, course)
    has_staff_access = has_staff_access_to_preview_mode(user, course.id)
    forum_roles = []
    if user.is_authenticated:
        forum_roles = list(
            Role.objects.filter(
                users=user,
                course_id=course.id).values_list('name').distinct())

    # get user partition data
    if user.is_authenticated():
        partition_groups = get_all_partitions_for_course(course)
        user_partitions = get_user_partition_groups(course.id,
                                                    partition_groups, user,
                                                    'name')
    else:
        user_partitions = {}

    return {
        'upgrade_link': upgrade_link,
        'upgrade_price': unicode(get_cosmetic_verified_display_price(course)),
        'enrollment_mode': enrollment_mode,
        'enrollment_time': enrollment_time,
        'pacing_type':
        'self_paced' if course.self_paced else 'instructor_paced',
        'upgrade_deadline': upgrade_date,
        'course_key': course.id,
        'course_start': course.start,
        'course_end': course.end,
        'has_staff_access': has_staff_access,
        'forum_roles': forum_roles,
        'partition_groups': user_partitions,
        # TODO: clean up as part of REVO-28 (START)
        'has_non_audit_enrollments': has_non_audit_enrollments,
        # TODO: clean up as part of REVO-28 (END)
        # TODO: clean up as part of REVEM-106 (START)
        'program_key_fields': program_key,
        # TODO: clean up as part of REVEM-106 (END)
    }
コード例 #28
0
 def get_used_ids(course):
     """
     Return a list of IDs that already in use.
     """
     return set([p.id for p in get_all_partitions_for_course(course)])
コード例 #29
0
ファイル: utils.py プロジェクト: musmanmalik/edx-platform
def get_user_partition_info(xblock, schemes=None, course=None):
    """
    Retrieve user partition information for an XBlock for display in editors.

    * If a partition has been disabled, it will be excluded from the results.

    * If a group within a partition is referenced by the XBlock, but the group has been deleted,
      the group will be marked as deleted in the results.

    Arguments:
        xblock (XBlock): The courseware component being edited.

    Keyword Arguments:
        schemes (iterable of str): If provided, filter partitions to include only
            schemes with the provided names.

        course (XBlock): The course descriptor.  If provided, uses this to look up the user partitions
            instead of loading the course.  This is useful if we're calling this function multiple
            times for the same course want to minimize queries to the modulestore.

    Returns: list

    Example Usage:
    >>> get_user_partition_info(block, schemes=["cohort", "verification"])
    [
        {
            "id": 12345,
            "name": "Cohorts"
            "scheme": "cohort",
            "groups": [
                {
                    "id": 7890,
                    "name": "Foo",
                    "selected": True,
                    "deleted": False,
                }
            ]
        },
        {
            "id": 7292,
            "name": "Midterm A",
            "scheme": "verification",
            "groups": [
                {
                    "id": 1,
                    "name": "Completed verification at Midterm A",
                    "selected": False,
                    "deleted": False
                },
                {
                    "id": 0,
                    "name": "Did not complete verification at Midterm A",
                    "selected": False,
                    "deleted": False,
                }
            ]
        }
    ]

    """
    course = course or modulestore().get_course(xblock.location.course_key)

    if course is None:
        log.warning(
            u"Could not find course %s to retrieve user partition information",
            xblock.location.course_key)
        return []

    if schemes is not None:
        schemes = set(schemes)

    partitions = []
    for p in sorted(get_all_partitions_for_course(course, active_only=True),
                    key=lambda p: p.name):

        # Exclude disabled partitions, partitions with no groups defined
        # The exception to this case is when there is a selected group within that partition, which means there is
        # a deleted group
        # Also filter by scheme name if there's a filter defined.
        selected_groups = set(xblock.group_access.get(p.id, []) or [])
        if (p.groups or selected_groups) and (schemes is None
                                              or p.scheme.name in schemes):

            # First, add groups defined by the partition
            groups = []
            for g in p.groups:
                # Falsey group access for a partition mean that all groups
                # are selected.  In the UI, though, we don't show the particular
                # groups selected, since there's a separate option for "all users".
                groups.append({
                    "id": g.id,
                    "name": g.name,
                    "selected": g.id in selected_groups,
                    "deleted": False,
                })

            # Next, add any groups set on the XBlock that have been deleted
            all_groups = set(g.id for g in p.groups)
            missing_group_ids = selected_groups - all_groups
            for gid in missing_group_ids:
                groups.append({
                    "id": gid,
                    "name": _("Deleted Group"),
                    "selected": True,
                    "deleted": True,
                })

            # Put together the entire partition dictionary
            partitions.append({
                "id": p.id,
                "name": six.text_type(
                    p.name
                ),  # Convert into a string in case ugettext_lazy was used
                "scheme": p.scheme.name,
                "groups": groups,
            })

    return partitions
コード例 #30
0
ファイル: utils.py プロジェクト: Stanford-Online/edx-platform
def get_user_partition_info(xblock, schemes=None, course=None):
    """
    Retrieve user partition information for an XBlock for display in editors.

    * If a partition has been disabled, it will be excluded from the results.

    * If a group within a partition is referenced by the XBlock, but the group has been deleted,
      the group will be marked as deleted in the results.

    Arguments:
        xblock (XBlock): The courseware component being edited.

    Keyword Arguments:
        schemes (iterable of str): If provided, filter partitions to include only
            schemes with the provided names.

        course (XBlock): The course descriptor.  If provided, uses this to look up the user partitions
            instead of loading the course.  This is useful if we're calling this function multiple
            times for the same course want to minimize queries to the modulestore.

    Returns: list

    Example Usage:
    >>> get_user_partition_info(block, schemes=["cohort", "verification"])
    [
        {
            "id": 12345,
            "name": "Cohorts"
            "scheme": "cohort",
            "groups": [
                {
                    "id": 7890,
                    "name": "Foo",
                    "selected": True,
                    "deleted": False,
                }
            ]
        },
        {
            "id": 7292,
            "name": "Midterm A",
            "scheme": "verification",
            "groups": [
                {
                    "id": 1,
                    "name": "Completed verification at Midterm A",
                    "selected": False,
                    "deleted": False
                },
                {
                    "id": 0,
                    "name": "Did not complete verification at Midterm A",
                    "selected": False,
                    "deleted": False,
                }
            ]
        }
    ]

    """
    course = course or modulestore().get_course(xblock.location.course_key)

    if course is None:
        log.warning(
            "Could not find course %s to retrieve user partition information",
            xblock.location.course_key
        )
        return []

    if schemes is not None:
        schemes = set(schemes)

    partitions = []
    for p in sorted(get_all_partitions_for_course(course, active_only=True), key=lambda p: p.name):

        # Exclude disabled partitions, partitions with no groups defined
        # Also filter by scheme name if there's a filter defined.
        if p.groups and (schemes is None or p.scheme.name in schemes):

            # First, add groups defined by the partition
            groups = []
            for g in p.groups:

                # Falsey group access for a partition mean that all groups
                # are selected.  In the UI, though, we don't show the particular
                # groups selected, since there's a separate option for "all users".
                selected_groups = set(xblock.group_access.get(p.id, []) or [])
                groups.append({
                    "id": g.id,
                    "name": g.name,
                    "selected": g.id in selected_groups,
                    "deleted": False,
                })

            # Next, add any groups set on the XBlock that have been deleted
            all_groups = set(g.id for g in p.groups)
            missing_group_ids = selected_groups - all_groups
            for gid in missing_group_ids:
                groups.append({
                    "id": gid,
                    "name": _("Deleted Group"),
                    "selected": True,
                    "deleted": True,
                })

            # Put together the entire partition dictionary
            partitions.append({
                "id": p.id,
                "name": unicode(p.name),  # Convert into a string in case ugettext_lazy was used
                "scheme": p.scheme.name,
                "groups": groups,
            })

    return partitions
コード例 #31
0
def render_body(context, active_page=None, **pageargs):
    __M_caller = context.caller_stack._push_frame()
    try:
        __M_locals = __M_dict_builtin(pageargs=pageargs,
                                      active_page=active_page)
        masquerade = context.get('masquerade', UNDEFINED)
        supports_preview_menu = context.get('supports_preview_menu', UNDEFINED)
        course = context.get('course', UNDEFINED)
        static = _mako_get_namespace(context, 'static')
        sorted = context.get('sorted', UNDEFINED)
        disable_student_access = context.get('disable_student_access',
                                             UNDEFINED)
        staff_access = context.get('staff_access', UNDEFINED)
        __M_writer = context.writer()
        __M_writer(u'\n')
        __M_writer(u'\n')
        __M_writer(u'\n')
        __M_writer(u'\n\n')

        show_preview_menu = course and staff_access and supports_preview_menu

        __M_locals_builtin_stored = __M_locals_builtin()
        __M_locals.update(
            __M_dict_builtin([(__M_key, __M_locals_builtin_stored[__M_key])
                              for __M_key in ['show_preview_menu']
                              if __M_key in __M_locals_builtin_stored]))
        __M_writer(u'\n\n')
        if show_preview_menu:
            __M_writer(u'    ')

            def selected(is_selected):
                return "selected" if is_selected else ""

            course_partitions = get_all_partitions_for_course(course)
            masquerade_user_name = masquerade.user_name if masquerade else None
            masquerade_group_id = masquerade.group_id if masquerade else None
            masquerade_user_partition_id = masquerade.user_partition_id if masquerade else None
            staff_selected = selected(not masquerade
                                      or masquerade.role != "student")
            specific_student_selected = selected(not staff_selected
                                                 and masquerade.user_name)
            student_selected = selected(not staff_selected
                                        and not specific_student_selected
                                        and not masquerade_group_id)

            __M_locals_builtin_stored = __M_locals_builtin()
            __M_locals.update(
                __M_dict_builtin([
                    (__M_key, __M_locals_builtin_stored[__M_key])
                    for __M_key in [
                        'masquerade_user_name', 'selected',
                        'specific_student_selected', 'course_partitions',
                        'staff_selected', 'masquerade_user_partition_id',
                        'masquerade_group_id', 'student_selected'
                    ] if __M_key in __M_locals_builtin_stored
                ]))
            __M_writer(u'\n    <nav class="wrapper-preview-menu" aria-label="')
            __M_writer(
                filters.html_escape(filters.decode.utf8(_('Course View'))))
            __M_writer(
                u'">\n        <div class="preview-menu">\n            <ol class="preview-actions">\n                <li class="action-preview">\n                    <form action="#" class="action-preview-form" method="post">\n                        <label for="action-preview-select" class="action-preview-label">'
            )
            __M_writer(
                filters.html_escape(
                    filters.decode.utf8(_("View this course as:"))))
            __M_writer(
                u'</label>\n                        <select class="action-preview-select" id="action-preview-select" name="select">\n                            <option value="staff" '
            )
            __M_writer(filters.html_escape(
                filters.decode.utf8(staff_selected)))
            __M_writer(u'>')
            __M_writer(filters.html_escape(filters.decode.utf8(_("Staff"))))
            __M_writer(
                u'</option>\n                            <option value="student" '
            )
            __M_writer(
                filters.html_escape(filters.decode.utf8(student_selected)))
            __M_writer(u'>')
            __M_writer(filters.html_escape(filters.decode.utf8(_("Learner"))))
            __M_writer(
                u'</option>\n                            <option value="specific student" '
            )
            __M_writer(
                filters.html_escape(
                    filters.decode.utf8(specific_student_selected)))
            __M_writer(u'>')
            __M_writer(
                filters.html_escape(filters.decode.utf8(
                    _("Specific learner"))))
            __M_writer(u'</option>\n')
            if course_partitions:
                for course_partition in course_partitions:
                    for group in sorted(course_partition.groups,
                                        key=lambda group: group.name):
                        __M_writer(
                            u'                                    <option value="group.id" data-group-id="'
                        )
                        __M_writer(
                            filters.html_escape(filters.decode.utf8(group.id)))
                        __M_writer(u'" data-partition-id="')
                        __M_writer(
                            filters.html_escape(
                                filters.decode.utf8(course_partition.id)))
                        __M_writer(u'" ')
                        __M_writer(
                            filters.html_escape(
                                filters.decode.utf8(
                                    selected(
                                        masquerade_user_partition_id
                                        == course_partition.id
                                        and masquerade_group_id == group.id))))
                        __M_writer(
                            u'>\n                                        ')
                        __M_writer(
                            filters.html_escape(
                                filters.decode.utf8(
                                    _("Learner in {content_group}").format(
                                        content_group=group.name))))
                        __M_writer(
                            u'\n                                    </option>\n'
                        )
            __M_writer(
                u'                        </select>\n                        <div class="action-preview-username-container">\n                          <label for="action-preview-username" class="action-preview-label">'
            )
            __M_writer(
                filters.html_escape(
                    filters.decode.utf8(_("Username or email:"))))
            __M_writer(
                u'</label>\n                          <input type="text" class="action-preview-username" id="action-preview-username">\n                        </div>\n                        <button type="submit" class="sr-only" name="submit" value="submit">'
            )
            __M_writer(
                filters.html_escape(filters.decode.utf8(
                    _("Set preview mode"))))
            __M_writer(
                u'</button>\n                    </form>\n                </li>\n            </ol>\n'
            )
            if specific_student_selected:
                __M_writer(
                    u'                <div class="preview-specific-student-notice">\n                    <p>\n                        '
                )
                __M_writer(
                    filters.html_escape(
                        filters.decode.utf8(
                            Text(
                                _("You are now viewing the course as {i_start}{user_name}{i_end}."
                                  )).format(
                                      user_name=masquerade_user_name,
                                      i_start=HTML(u'<i>'),
                                      i_end=HTML(u'</i>'),
                                  ))))
                __M_writer(
                    u'\n                    </p>\n                </div>\n')
            __M_writer(u'        </div>\n    </nav>\n\n    ')

            preview_options = {
                "courseId":
                course.id,
                "disableStudentAccess":
                disable_student_access
                if disable_student_access is not UNDEFINED else False,
                "specificStudentSelected":
                specific_student_selected,
                "masqueradeUsername":
                masquerade_user_name
                if masquerade_user_name is not UNDEFINED else None,
            }

            __M_locals_builtin_stored = __M_locals_builtin()
            __M_locals.update(
                __M_dict_builtin([(__M_key, __M_locals_builtin_stored[__M_key])
                                  for __M_key in ['preview_options']
                                  if __M_key in __M_locals_builtin_stored]))
            __M_writer(u'\n    ')

            def ccall(caller):
                def body():
                    __M_writer = context.writer()
                    __M_writer(u'\n        PreviewFactory(')
                    __M_writer(dump_js_escaped_json(preview_options))
                    __M_writer(u');\n    ')
                    return ''

                return [body]

            context.caller_stack.nextcaller = runtime.Namespace(
                'caller', context, callables=ccall(__M_caller))
            try:
                __M_writer(
                    filters.html_escape(
                        filters.decode.utf8(
                            static.require_module_async(
                                class_name=u'PreviewFactory',
                                module_name=u'lms/js/preview/preview_factory'))
                    ))
            finally:
                context.caller_stack.nextcaller = None
            __M_writer(u'\n')
        return ''
    finally:
        context.caller_stack._pop_frame()
コード例 #32
0
def get_experiment_user_metadata_context(course, user):
    """
    Return a context dictionary with the keys used by the user_metadata.html.
    """
    enrollment_mode = None
    enrollment_time = None
    enrollment = None
    # TODO: clean up as part of REVO-28 (START)
    has_non_audit_enrollments = None
    # TODO: clean up as part of REVO-28 (END)

    # TODO: clean up as part of REVEM-199 (START)
    program_key = None
    # TODO: clean up as part of REVEM-199 (END)
    try:
        # TODO: clean up as part of REVO-28 (START)
        user_enrollments = CourseEnrollment.objects.select_related(
            'course').filter(user_id=user.id)
        audit_enrollments = user_enrollments.filter(mode='audit')
        has_non_audit_enrollments = (len(audit_enrollments) !=
                                     len(user_enrollments))
        # TODO: clean up as part of REVO-28 (END)
        enrollment = CourseEnrollment.objects.select_related('course').get(
            user_id=user.id, course_id=course.id)
        if enrollment.is_active:
            enrollment_mode = enrollment.mode
            enrollment_time = enrollment.created

            # TODO: clean up as part of REVEM-199 (START)
            if PROGRAM_INFO_FLAG.is_enabled():
                programs = get_programs(course=course.id)
                if programs:
                    # A course can be in multiple programs, but we're just grabbing the first one
                    program = programs[0]
                    complete_enrollment = False
                    total_courses = None
                    courses = program.get('courses')
                    if courses is not None:
                        total_courses = len(courses)
                        complete_enrollment = is_enrolled_in_all_courses_in_program(
                            courses, user_enrollments)

                    program_key = {
                        'uuid': program.get('uuid'),
                        'title': program.get('title'),
                        'marketing_url': program.get('marketing_url'),
                        'total_courses': total_courses,
                        'complete_enrollment': complete_enrollment,
                    }
            # TODO: clean up as part of REVEM-199 (END)
    except CourseEnrollment.DoesNotExist:
        pass  # Not enrolled, used the default None values

    # upgrade_link and upgrade_date should be None if user has passed their dynamic pacing deadline.
    upgrade_link, upgrade_date = check_and_get_upgrade_link_and_date(
        user, enrollment, course)
    has_staff_access = has_staff_access_to_preview_mode(user, course.id)
    forum_roles = []
    if user.is_authenticated:
        forum_roles = list(
            Role.objects.filter(
                users=user,
                course_id=course.id).values_list('name').distinct())

    # get user partition data
    if user.is_authenticated():
        partition_groups = get_all_partitions_for_course(course)
        user_partitions = get_user_partition_groups(course.id,
                                                    partition_groups, user,
                                                    'name')
    else:
        user_partitions = {}

    return {
        'upgrade_link': upgrade_link,
        'upgrade_price': unicode(get_cosmetic_verified_display_price(course)),
        'enrollment_mode': enrollment_mode,
        'enrollment_time': enrollment_time,
        'pacing_type':
        'self_paced' if course.self_paced else 'instructor_paced',
        'upgrade_deadline': upgrade_date,
        'course_key': course.id,
        'course_start': course.start,
        'course_end': course.end,
        'has_staff_access': has_staff_access,
        'forum_roles': forum_roles,
        'partition_groups': user_partitions,
        # TODO: clean up as part of REVO-28 (START)
        'has_non_audit_enrollments': has_non_audit_enrollments,
        # TODO: clean up as part of REVO-28 (END)
        # TODO: clean up as part of REVEM-199 (START)
        'program_key_fields': program_key,
        # TODO: clean up as part of REVEM-199 (END)
    }
コード例 #33
0
def get_experiment_user_metadata_context(course, user):
    """
    Return a context dictionary with the keys used for Optimizely experiments, exposed via user_metadata.html:
    view from the DOM in those calling views using: JSON.parse($("#user-metadata").text());
    Most views call this function with both parameters, but student dashboard has only a user
    """
    enrollment = None
    # TODO: clean up as part of REVO-28 (START)
    user_enrollments = None
    audit_enrollments = None
    has_non_audit_enrollments = False
    context = {}
    if course is not None:
        try:
            user_enrollments = CourseEnrollment.objects.select_related('course', 'schedule').filter(user_id=user.id)
            has_non_audit_enrollments = user_enrollments.exclude(mode__in=CourseMode.UPSELL_TO_VERIFIED_MODES).exists()
            # TODO: clean up as part of REVO-28 (END)
            enrollment = CourseEnrollment.objects.select_related(
                'course', 'schedule'
            ).get(user_id=user.id, course_id=course.id)
        except CourseEnrollment.DoesNotExist:
            pass  # Not enrolled, use the default values

        has_entitlements = False
        if user.is_authenticated:
            has_entitlements = CourseEntitlement.objects.filter(user=user).exists()

        context = get_base_experiment_metadata_context(course, user, enrollment, user_enrollments)
        has_staff_access = has_staff_access_to_preview_mode(user, course.id)
        forum_roles = []
        if user.is_authenticated:
            forum_roles = list(Role.objects.filter(users=user, course_id=course.id).values_list('name').distinct())

        # get user partition data
        if user.is_authenticated:
            partition_groups = get_all_partitions_for_course(course)
            user_partitions = get_user_partition_groups(course.id, partition_groups, user, 'name')
        else:
            user_partitions = {}

        # TODO: clean up as part of REVO-28 (START)
        context['has_non_audit_enrollments'] = has_non_audit_enrollments or has_entitlements
        # TODO: clean up as part of REVO-28 (END)
        context['has_staff_access'] = has_staff_access
        context['forum_roles'] = forum_roles
        context['partition_groups'] = user_partitions

    user_metadata = {
        key: context.get(key)
        for key in (
            'username',
            'user_id',
            'course_id',
            'course_display_name',
            'enrollment_mode',
            'upgrade_link',
            'upgrade_price',
            'audit_access_deadline',
            'course_duration',
            'pacing_type',
            'has_staff_access',
            'forum_roles',
            'partition_groups',
            # TODO: clean up as part of REVO-28 (START)
            'has_non_audit_enrollments',
            # TODO: clean up as part of REVO-28 (END)
            # TODO: clean up as part of REVEM-199 (START)
            'program_key_fields',
            # TODO: clean up as part of REVEM-199 (END)
        )
    }

    if user:
        user_metadata['username'] = user.username
        user_metadata['user_id'] = user.id
        if hasattr(user, 'email'):
            user_metadata['email'] = user.email

    for datekey in (
            'schedule_start',
            'enrollment_time',
            'course_start',
            'course_end',
            'dynamic_upgrade_deadline',
            'course_upgrade_deadline',
            'audit_access_deadline',
    ):
        user_metadata[datekey] = (
            context.get(datekey).isoformat() if context.get(datekey) else None
        )

    for timedeltakey in (
        'course_duration',
    ):
        user_metadata[timedeltakey] = (
            context.get(timedeltakey).total_seconds() if context.get(timedeltakey) else None
        )

    course_key = context.get('course_key')
    if course and not course_key:
        course_key = course.id

    if course_key:
        if isinstance(course_key, CourseKey):
            user_metadata['course_key_fields'] = {
                'org': course_key.org,
                'course': course_key.course,
                'run': course_key.run,
            }

            if not context.get('course_id'):
                user_metadata['course_id'] = six.text_type(course_key)
        elif isinstance(course_key, six.string_types):
            user_metadata['course_id'] = course_key

    context['user_metadata'] = user_metadata
    return context
コード例 #34
0
 def get_used_ids(course):
     """
     Return a list of IDs that already in use.
     """
     return set([p.id for p in get_all_partitions_for_course(course)])
コード例 #35
0
def get_deprecated_experiment_user_metadata_context(course, user):
    """
    Return a context dictionary with the keys used by the user_metadata.html. This is deprecated and will be removed
    once we have confirmed that its replacement functions as intended.
    """
    enrollment_mode = None
    enrollment_time = None
    enrollment = None
    # TODO: clean up as part of REVO-28 (START)
    has_non_audit_enrollments = None
    # TODO: clean up as part of REVO-28 (END)
    # TODO: clean up as part of REVEM-199 (START)
    program_key = None
    # TODO: clean up as part of REVEM-199 (END)
    try:
        # TODO: clean up as part of REVO-28 (START)
        user_enrollments = CourseEnrollment.objects.select_related('course').filter(user_id=user.id)
        audit_enrollments = user_enrollments.filter(mode='audit')
        has_non_audit_enrollments = (len(audit_enrollments) != len(user_enrollments))
        # TODO: clean up as part of REVO-28 (END)
        # TODO: clean up as part of REVEM-199 (START)
        if PROGRAM_INFO_FLAG.is_enabled():
            programs = get_programs(course=course.id)
            if programs:
                # A course can be in multiple programs, but we're just grabbing the first one
                program = programs[0]
                complete_enrollment = False
                has_courses_left_to_purchase = False
                total_courses = None
                courses = program.get('courses')
                courses_left_to_purchase_price = None
                courses_left_to_purchase_url = None
                program_uuid = program.get('uuid')
                status = None
                is_eligible_for_one_click_purchase = None
                if courses is not None:
                    total_courses = len(courses)
                    complete_enrollment = is_enrolled_in_all_courses(courses, user_enrollments)
                    status = program.get('status')
                    is_eligible_for_one_click_purchase = program.get('is_program_eligible_for_one_click_purchase')
                    # Get the price and purchase URL of the program courses the user has yet to purchase. Say a
                    # program has 3 courses (A, B and C), and the user previously purchased a certificate for A.
                    # The user is enrolled in audit mode for B. The "left to purchase price" should be the price of
                    # B+C.
                    non_audit_enrollments = [en for en in user_enrollments if en not in
                                             audit_enrollments]
                    courses_left_to_purchase = get_unenrolled_courses(courses, non_audit_enrollments)
                    if courses_left_to_purchase:
                        has_courses_left_to_purchase = True
                        if is_eligible_for_one_click_purchase:
                            courses_left_to_purchase_price, courses_left_to_purchase_skus = \
                                get_program_price_and_skus(courses_left_to_purchase)
                            if courses_left_to_purchase_skus:
                                courses_left_to_purchase_url = EcommerceService().get_checkout_page_url(
                                    *courses_left_to_purchase_skus, program_uuid=program_uuid)

                program_key = {
                    'uuid': program_uuid,
                    'title': program.get('title'),
                    'marketing_url': program.get('marketing_url'),
                    'status': status,
                    'is_eligible_for_one_click_purchase': is_eligible_for_one_click_purchase,
                    'total_courses': total_courses,
                    'complete_enrollment': complete_enrollment,
                    'has_courses_left_to_purchase': has_courses_left_to_purchase,
                    'courses_left_to_purchase_price': courses_left_to_purchase_price,
                    'courses_left_to_purchase_url': courses_left_to_purchase_url,
                }
        # TODO: clean up as part of REVEM-199 (END)
        enrollment = CourseEnrollment.objects.select_related(
            'course'
        ).get(user_id=user.id, course_id=course.id)
        if enrollment.is_active:
            enrollment_mode = enrollment.mode
            enrollment_time = enrollment.created
    except CourseEnrollment.DoesNotExist:
        pass  # Not enrolled, used the default None values

    # upgrade_link and upgrade_date should be None if user has passed their dynamic pacing deadline.
    upgrade_link, upgrade_date = check_and_get_upgrade_link_and_date(user, enrollment, course)
    has_staff_access = has_staff_access_to_preview_mode(user, course.id)
    forum_roles = []
    if user.is_authenticated:
        forum_roles = list(Role.objects.filter(users=user, course_id=course.id).values_list('name').distinct())

    # get user partition data
    if user.is_authenticated():
        partition_groups = get_all_partitions_for_course(course)
        user_partitions = get_user_partition_groups(course.id, partition_groups, user, 'name')
    else:
        user_partitions = {}

    return {
        'upgrade_link': upgrade_link,
        'upgrade_price': six.text_type(get_cosmetic_verified_display_price(course)),
        'enrollment_mode': enrollment_mode,
        'enrollment_time': enrollment_time,
        'pacing_type': 'self_paced' if course.self_paced else 'instructor_paced',
        'upgrade_deadline': upgrade_date,
        'audit_access_deadline': get_audit_access_expiration(user, course),
        'course_key': course.id,
        'course_start': course.start,
        'course_end': course.end,
        'has_staff_access': has_staff_access,
        'forum_roles': forum_roles,
        'partition_groups': user_partitions,
        # TODO: clean up as part of REVO-28 (START)
        'has_non_audit_enrollments': has_non_audit_enrollments,
        # TODO: clean up as part of REVO-28 (END)
        # TODO: clean up as part of REVEM-199 (START)
        'program_key_fields': program_key,
        # TODO: clean up as part of REVEM-199 (END)
    }