Ejemplo n.º 1
0
    def test_get_courses_by_org(self):
        """
        Verify that org filtering performs as expected, and that an empty result
        is returned if the org passed by the caller does not match the designated
        org.
        """
        primary = 'primary'
        alternate = 'alternate'

        def _fake_get_value(value, default=None):
            """Used to stub out site_configuration.helpers.get_value()."""
            if value == 'course_org_filter':
                return alternate

            return default

        user = UserFactory.create()

        # Pass `emit_signals=True` so that these courses are cached with CourseOverviews.
        primary_course = CourseFactory.create(org=primary, emit_signals=True)
        alternate_course = CourseFactory.create(org=alternate, emit_signals=True)

        self.assertNotEqual(primary_course.org, alternate_course.org)

        unfiltered_courses = get_courses(user)
        for org in [primary_course.org, alternate_course.org]:
            self.assertTrue(
                any(course.org == org for course in unfiltered_courses)
            )

        filtered_courses = get_courses(user, org=primary)
        self.assertTrue(
            all(course.org == primary_course.org for course in filtered_courses)
        )

        with mock.patch(
            'openedx.core.djangoapps.site_configuration.helpers.get_value',
            autospec=True,
        ) as mock_get_value:
            mock_get_value.side_effect = _fake_get_value

            # Request filtering for an org distinct from the designated org.
            no_courses = get_courses(user, org=primary)
            self.assertEqual(no_courses, [])

            # Request filtering for an org matching the designated org.
            site_courses = get_courses(user, org=alternate)
            self.assertTrue(
                all(course.org == alternate_course.org for course in site_courses)
            )
Ejemplo n.º 2
0
    def test_get_courses_by_org(self):
        """
        Verify that org filtering performs as expected, and that an empty result
        is returned if the org passed by the caller does not match the designated
        org.
        """
        primary = 'primary'
        alternate = 'alternate'

        def _fake_get_value(value, default=None):
            """Used to stub out site_configuration.helpers.get_value()."""
            if value == 'course_org_filter':
                return alternate

            return default

        user = UserFactory.create()

        # Pass `emit_signals=True` so that these courses are cached with CourseOverviews.
        primary_course = CourseFactory.create(org=primary, emit_signals=True)
        alternate_course = CourseFactory.create(org=alternate,
                                                emit_signals=True)

        self.assertNotEqual(primary_course.org, alternate_course.org)

        unfiltered_courses = get_courses(user)
        for org in [primary_course.org, alternate_course.org]:
            self.assertTrue(
                any(course.org == org for course in unfiltered_courses))

        filtered_courses = get_courses(user, org=primary)
        self.assertTrue(
            all(course.org == primary_course.org
                for course in filtered_courses))

        with mock.patch(
                'openedx.core.djangoapps.site_configuration.helpers.get_value',
                autospec=True,
        ) as mock_get_value:
            mock_get_value.side_effect = _fake_get_value

            # Request filtering for an org distinct from the designated org.
            no_courses = get_courses(user, org=primary)
            self.assertEqual(list(no_courses), [])

            # Request filtering for an org matching the designated org.
            site_courses = get_courses(user, org=alternate)
            self.assertTrue(
                all(course.org == alternate_course.org
                    for course in site_courses))
Ejemplo n.º 3
0
def search_courses(request):
    """
    Render "find courses" page.  The course selection work is done in courseware.courses.
    """
    courses = get_courses1(request,request.user, request.META.get('HTTP_HOST'))
    courses = sort_by_announcement(courses)
    c_list=[]
    c_num=[]
    c_len=CourseCategory.objects.all().count()
    for i in range(1,c_len+1):
	    c_name=CourseCategory.objects.get(id = i).category_name
	    c_list.append(c_name)
    all_courses = get_courses(request.user, request.META.get('HTTP_HOST'))
    all_c_num = len(all_courses)
    for j in range(1,17):
	    c_num.append(0)
    for c in all_courses:
        c_category = c.display_number_with_default[0:2]
        c_category_no = int(c_category)
        num_t=c_num[c_category_no-1]
        c_num[c_category_no-1]=num_t+1
    name_list=[]
    category_list=[]
    category_num=[]
    for i in range (0,len(c_num)):
        if c_num[i]!=0:
            if i<9:
                num='0'+str(int(i+1))
                name_list.append(num)
            else:
                name_list.append(i+1)
            category_list.append(c_list[i])
            category_num.append(c_num[i])
    none_zero=len(category_num)
    return render_to_response("courseware/courses.html", {'courses': courses,'name_list':name_list,'category_list':category_list,'category_num':category_num,'all_c_num':all_c_num,'none_zero':none_zero})
Ejemplo n.º 4
0
def courses_search(request):
    """
    Render "find courses" page.  The course selection work is done in courseware.courses.
    """
    if request.is_ajax():
        query_string = ""
        courses = []
        query_string = request.GET['search_string']
        if query_string is not None:
            print "----------------------------------" + query_string + "\n"
            entry_query = normalize_query(query_string)
            allCourses = get_courses(request.user,
                                     request.META.get('HTTP_HOST'))
            for course in allCourses:
                title = get_course_about_section(course, 'title').lower()
                flag = True
                for query in entry_query:
                    if not query.lower() in title:
                        flag = False
                        break
                if flag:
                    courses.append(course)
            courses = sort_by_announcement(courses)

            if courses:
                return render_to_response("courseware/courses_search.html",
                                          {'courses': courses})
            else:
                return HttpResponse("No Courses Found")
Ejemplo n.º 5
0
def index(request, extra_context=None, user=AnonymousUser()):
    """
    Render the edX main page.

    extra_context is used to allow immediate display of certain modal windows, eg signup,
    as used by external_auth.
    """
    if extra_context is None:
        extra_context = {}

    courses = get_courses(user)

    if configuration_helpers.get_value(
            "ENABLE_COURSE_SORTING_BY_START_DATE",
            settings.FEATURES["ENABLE_COURSE_SORTING_BY_START_DATE"],
    ):
        courses = sort_by_start_date(courses)
    else:
        courses = sort_by_announcement(courses)

    context = {'courses': courses}

    context['homepage_overlay_html'] = configuration_helpers.get_value(
        'homepage_overlay_html')

    # This appears to be an unused context parameter, at least for the master templates...
    context['show_partners'] = configuration_helpers.get_value(
        'show_partners', True)

    # TO DISPLAY A YOUTUBE WELCOME VIDEO
    # 1) Change False to True
    context['show_homepage_promo_video'] = configuration_helpers.get_value(
        'show_homepage_promo_video', False)

    # Maximum number of courses to display on the homepage.
    context['homepage_course_max'] = configuration_helpers.get_value(
        'HOMEPAGE_COURSE_MAX', settings.HOMEPAGE_COURSE_MAX)

    # 2) Add your video's YouTube ID (11 chars, eg "123456789xX"), or specify via site configuration
    # Note: This value should be moved into a configuration setting and plumbed-through to the
    # context via the site configuration workflow, versus living here
    youtube_video_id = configuration_helpers.get_value(
        'homepage_promo_video_youtube_id', "your-youtube-id")
    context['homepage_promo_video_youtube_id'] = youtube_video_id

    # allow for theme override of the courses list
    context['courses_list'] = theming_helpers.get_template_path(
        'courses_list.html')

    # Insert additional context for use in the template
    context.update(extra_context)

    # Add marketable programs to the context.
    context['programs_list'] = get_programs_with_type(request.site,
                                                      include_hidden=False)

    # TODO: Course Listing Plugin required
    context['journal_info'] = get_journals_context(request)

    return render_to_response('index.html', context)
Ejemplo n.º 6
0
def get_search_category(request):
    courses = get_courses2(request,request.user, request.META.get('HTTP_HOST'))
    courses = sort_by_announcement(courses)
    json_list=json_courses(request,courses)
    decodejson = json.loads(json_list)
    c_list=[]
    c_num=[]
    c_len=CourseCategory.objects.all().count()
    for i in range(1,c_len+1):
	    c_name=CourseCategory.objects.get(id = i).category_name
	    c_list.append(c_name)
    all_courses = get_courses(request.user, request.META.get('HTTP_HOST'))
    all_c_num = len(all_courses)
    for j in range(1,17):
	    c_num.append(0)
    for c in all_courses:
        c_category = c.display_number_with_default[0:2]
        c_category_no = int(c_category)
        num_t=c_num[c_category_no-1]
        c_num[c_category_no-1]=num_t+1
    decodejson.append(c_list)
    decodejson.append(c_num)
    decodejson.append(all_c_num)
    decodejson.append(c_len)

    return JsonResponse(decodejson)
Ejemplo n.º 7
0
def search_category(request):
    courses = get_courses2(request, request.user,
                           request.META.get('HTTP_HOST'))
    courses = sort_by_announcement(courses)
    c_list = []
    c_num = []
    c_len = CourseCategory.objects.all().count()
    for i in range(1, c_len + 1):
        c_name = CourseCategory.objects.get(id=i).category_name
        c_list.append(c_name)
    all_courses = get_courses(request.user, request.META.get('HTTP_HOST'))
    all_c_num = len(all_courses)
    for j in range(1, 17):
        c_num.append(0)
    for c in all_courses:
        c_category = c.display_number_with_default[0:2]
        c_category_no = int(c_category)
        num_t = c_num[c_category_no - 1]
        c_num[c_category_no - 1] = num_t + 1

    return render_to_response(
        "courseware/courses.html", {
            'courses': courses,
            'c_list': c_list,
            'c_num': c_num,
            'all_c_num': all_c_num
        })
Ejemplo n.º 8
0
def get_recommended_xmodule_courses(user):
    """
    Helper function to get recommended courses based on the user interests and add details from xmodule to
    the recommended courses
    """
    recommended_courses = []
    all_courses = get_courses(user)
    user_interests = user.extended_profile.get_user_selected_interests()
    if not user_interests:
        return []

    for course in all_courses:
        settings = CustomSettings.objects.filter(id=course.id).first()
        if not settings:
            continue

        tags = settings.tags
        if not tags:
            continue

        tags = tags.split('|')
        tags = [tag.strip() for tag in tags]
        matched_interests = set(user_interests) & set(tags)
        if matched_interests and not CourseEnrollment.is_enrolled(user, course.id):
            detailed_course = modulestore().get_course(course.id)
            detailed_course.short_description = course.short_description
            detailed_course.interests = '/ '.join(list(matched_interests))
            recommended_courses.append(detailed_course)

    return recommended_courses
Ejemplo n.º 9
0
def courses_search(request):
    """
    Render "find courses" page.  The course selection work is done in courseware.courses.
    """
    if request.is_ajax():
        query_string=""
        courses=[]
        query_string = request.GET['search_string']
        if query_string is not None:
            print "----------------------------------"+query_string+"\n"
            entry_query=normalize_query(query_string)
            allCourses = get_courses(request.user, request.META.get('HTTP_HOST'))
            for course in allCourses:
                title=get_course_about_section(course,'title').lower()
                flag=True
                for query in entry_query:
                    if not query.lower() in title:
                        flag=False
                        break
                if flag:
                    courses.append(course)
            courses = sort_by_announcement(courses)
            
            if courses:
                return render_to_response("courseware/courses_search.html", {'courses': courses})
            else:
                return HttpResponse("No Courses Found")
Ejemplo n.º 10
0
def get_search_category(request):
    courses = get_courses2(request, request.user,
                           request.META.get('HTTP_HOST'))
    courses = sort_by_announcement(courses)
    json_list = json_courses(request, courses)
    decodejson = json.loads(json_list)
    c_list = []
    c_num = []
    c_len = CourseCategory.objects.all().count()
    for i in range(1, c_len + 1):
        c_name = CourseCategory.objects.get(id=i).category_name
        c_list.append(c_name)
    all_courses = get_courses(request.user, request.META.get('HTTP_HOST'))
    all_c_num = len(all_courses)
    for j in range(1, 17):
        c_num.append(0)
    for c in all_courses:
        c_category = c.display_number_with_default[0:2]
        c_category_no = int(c_category)
        num_t = c_num[c_category_no - 1]
        c_num[c_category_no - 1] = num_t + 1
    decodejson.append(c_list)
    decodejson.append(c_num)
    decodejson.append(all_c_num)
    decodejson.append(c_len)

    return JsonResponse(decodejson)
Ejemplo n.º 11
0
def course_kinds_about(request, course_kind):
    """this is to show the kinds of course page"""
    #print course_kind
    global s_plist
    global s_mlist
    global s_slist

    courses = get_courses(request.user, request.META.get('HTTP_HOST'))
    plist = get_primary_course(courses, course_kind)
    s_plist = plist
    mlist = get_Intermediate_course(courses, course_kind)
    s_mlist = mlist
    slist = get_senior_course(courses, course_kind)
    s_slist = slist

    plen = len(plist)
    mlen = len(mlist)
    slen = len(slist)

    content = {
        'course_kind': course_kind,
        'slist': slist,
        'plist': plist,
        'mlist': mlist,
        'plen': plen,
        'mlen': mlen,
        'slen': slen,
    }
    return render_to_response('courseware/course_kinds.html', content)
def drop_courses(request):
    r = list()
    courses = get_courses(None)
    for course in courses:
        course = course_from_id(course.id)
        r.append({"id": course.id, "name": str(course.display_coursenumber) + ' ' + course.display_name})
    r.sort(key=lambda x: x['name'], reverse=False)
    return HttpResponse(json.dumps(r), content_type="application/json")
Ejemplo n.º 13
0
def courses(request):
    """
    Render "find courses" page.  The course selection work is done in courseware.courses.
    """
    courses = get_courses(request.user, request.META.get('HTTP_HOST'))
    courses = sort_by_announcement(courses)

    return render_to_response("courseware/courses.html", {'courses': courses})
Ejemplo n.º 14
0
def courses(request):
    """
    Render "find courses" page.  The course selection work is done in courseware.courses.
    """
    courses = get_courses(request.user, request.META.get('HTTP_HOST'))
    courses = sort_by_announcement(courses)

    return render_to_response("courseware/courses.html", {'courses': courses})
Ejemplo n.º 15
0
def courses(request):
    """
    Render "find courses" page.  The course selection work is done in courseware.courses.
    """
    courses = get_courses(request.user, request.META.get('HTTP_HOST'))[:9]
    courses = sort_by_announcement(courses)

    return render_to_response("courseware/courses.html", {'courses': courses, 'homepage_promo_video_youtube_id': 'yY2gsC8bL3U'})
Ejemplo n.º 16
0
def courses_list_handler(request, action):
    """
    Return courses based on request params
    """
    try:
        user = request.user
    except:
        user = AnonymousUser()

    if action not in ["homefalls", "all", "hot", "latest", "my", "search", "rolling", "sync"]:
        return JsonResponse({"success": False, "errmsg": "not support other actions except homefalls all hot latest rolling and my"})

    def get_courses_depend_action(courses):
        """
        Return courses depend on action
            action: [homefalls, hot, lastest, my, search]
                homefalls: get all courses
                hot: Number of attended people > ?
                lastest: News last week
                my: I registered
                all: like 'homefalls'
        """
        courses = sort_and_audited_items(courses)
        courses_list = []

        if action == "latest":
            default_count = 20
            if len(courses) < default_count:
                default_count = len(courses)

            courses_list = courses[0:default_count]
        elif action == "my":
            # filter my registered courses
            for course in courses:
                if registered_for_course(course, user):
                    courses_list.append(course)
        elif action == "rolling":
            default_count = 5
            courses_list = courses[0:default_count]
        elif action == 'search':
            keyword = request.GET.get("keyword")

            if keyword:
                for c in courses:
                    if keyword in c.org or keyword in c.id or keyword in c.display_name_with_default:
                        courses_list.append(c)
        else:
            courses_list = courses

        return courses_list

    courses = get_courses(user, request.META.get('HTTP_HOST'))
    if action != "sync":
        courses = get_courses_depend_action(courses)

    return return_fixed_courses(request, courses, action)
Ejemplo n.º 17
0
def audit_courses(request, user=AnonymousUser()):
    # The course selection work is done in courseware.courses.
    domain = settings.FEATURES.get('FORCE_UNIVERSITY_DOMAIN')  # normally False
    # do explicit check, because domain=None is valid
    if domain is False:
        domain = request.META.get('HTTP_HOST')

    courses = get_courses(user, domain=domain)

    return filter_audited_items(sort_by_announcement(courses))
Ejemplo n.º 18
0
def get_filtered_course_infos(request):
    course_infos = get_course_infos(get_courses(request.user))
    pattern = request.GET.get('search')

    if pattern:
        course_infos = [course for course in course_infos
                if pattern in course.title
                or pattern in course.course.id.to_deprecated_string()]

    return course_infos, pattern
Ejemplo n.º 19
0
def index(request, extra_context=None, user=AnonymousUser()):
    """
    Render the edX main page.

    extra_context is used to allow immediate display of certain modal windows, eg signup,
    as used by external_auth.
    """
    if extra_context is None:
        extra_context = {}

    courses = get_courses(user)

    if configuration_helpers.get_value(
            "ENABLE_COURSE_SORTING_BY_START_DATE",
            settings.FEATURES["ENABLE_COURSE_SORTING_BY_START_DATE"],
    ):
        courses = sort_by_start_date(courses)
    else:
        courses = sort_by_announcement(courses)

    context = {'courses': courses}

    context['homepage_overlay_html'] = configuration_helpers.get_value('homepage_overlay_html')

    # This appears to be an unused context parameter, at least for the master templates...
    context['show_partners'] = configuration_helpers.get_value('show_partners', True)

    # TO DISPLAY A YOUTUBE WELCOME VIDEO
    # 1) Change False to True
    context['show_homepage_promo_video'] = configuration_helpers.get_value('show_homepage_promo_video', False)

    # Maximum number of courses to display on the homepage.
    context['homepage_course_max'] = configuration_helpers.get_value(
        'HOMEPAGE_COURSE_MAX', settings.HOMEPAGE_COURSE_MAX
    )

    # 2) Add your video's YouTube ID (11 chars, eg "123456789xX"), or specify via site configuration
    # Note: This value should be moved into a configuration setting and plumbed-through to the
    # context via the site configuration workflow, versus living here
    youtube_video_id = configuration_helpers.get_value('homepage_promo_video_youtube_id', "your-youtube-id")
    context['homepage_promo_video_youtube_id'] = youtube_video_id

    # allow for theme override of the courses list
    context['courses_list'] = theming_helpers.get_template_path('courses_list.html')

    # Insert additional context for use in the template
    context.update(extra_context)

    # Add marketable programs to the context.
    context['programs_list'] = get_programs_with_type(request.site, include_hidden=False)

    # TODO: Course Listing Plugin required
    context['journal_info'] = get_journals_context(request)

    return render_to_response('index.html', context)
Ejemplo n.º 20
0
def jump_to(request, school_key_string):
    org = school_key_string
    course_list = []
    courses = get_courses(request.user, request.META.get('HTTP_HOST'))
    for course in courses:
        if course.display_org_with_default == org:
            course_list.append(course)
    return render_to_response("colleges/school_about.html", {
        "course_list": course_list,
        "org": org,
    })
Ejemplo n.º 21
0
def jump_to(request, school_key_string):
    org = school_key_string
    course_list = []
    courses = get_courses(request.user, request.META.get('HTTP_HOST'))
    for course in courses:
        if course.display_org_with_default == org:
             course_list.append(course)
    return render_to_response("colleges/school_about.html", {
        "course_list": course_list,
        "org": org,
    })
Ejemplo n.º 22
0
def courses(request):
    """
    Render "find courses" page.  The course selection work is done in courseware.courses.
    """
    courses = get_courses(request.user, request.META.get('HTTP_HOST'))

    if microsite.get_value("ENABLE_COURSE_SORTING_BY_START_DATE",
                           settings.FEATURES["ENABLE_COURSE_SORTING_BY_START_DATE"]):
        courses = sort_by_start_date(courses)
    else:
        courses = sort_by_announcement(courses)

    return render_to_response("courseware/courses.html", {'courses': courses})
Ejemplo n.º 23
0
def courses(request):
    """
    Render "find courses" page.  The course selection work is done in courseware.courses.
    """
    courses = get_courses(request.user, request.META.get('HTTP_HOST'))
    courses = sort_by_announcement(courses)
    universities = []
    for course in courses:
        university = get_course_about_section(course,'university')
        if not university in universities:
            universities.append(university)
    universities.sort()
    return render_to_response("courseware/courses.html", {'courses': courses,'universities':universities})
Ejemplo n.º 24
0
def courses(request):
    """
    Render "find courses" page.  The course selection work is done in courseware.courses.
    """
    courses = get_courses(request.user, request.META.get('HTTP_HOST'))

    if microsite.get_value("ENABLE_COURSE_SORTING_BY_START_DATE",
                           settings.FEATURES["ENABLE_COURSE_SORTING_BY_START_DATE"]):
        courses = sort_by_start_date(courses)
    else:
        courses = sort_by_announcement(courses)

    return render_to_response("courseware/courses.html", {'courses': courses})
Ejemplo n.º 25
0
def get_featured_courses(user):
    featured_courses = []

    courses = get_courses(user)
    featured_custom_settings = CustomSettings.objects.filter(is_featured=True).values_list('id', flat=True)
    for course in courses:
        if unicode(course.id) in featured_custom_settings:
            course_details = modulestore().get_course(course.id)
            instructors = course_details.instructor_info.get('instructors')
            course.instructors = instructors if instructors else []
            featured_courses += [course]

    return featured_courses
Ejemplo n.º 26
0
def university_search(request,org_id=""):
    if request.is_ajax():
        query_university=org_id
        courses = []
        allCourses = get_courses(request.user, request.META.get('HTTP_HOST'))
        if query_university is not None:
            for course in allCourses:
                university=get_course_about_section(course,'university')
                if (query_university.lower() in university.lower()) and (university.lower() in query_university.lower()):
                    courses.append(course) 
        if courses:
            return render_to_response("courseware/courses_search.html",{'courses':courses})
        else:
            return HttpResponse("No Courses Found")
Ejemplo n.º 27
0
def course_list(request, extra_context={}, user=AnonymousUser()):
    def course_filter(course,org='ncepu',subject=''):
        #print request    
        if course.org == org:
            return True
        return False	
    domain = settings.FEATURES.get('FORCE_UNIVERSITY_DOMAIN')
    if domain is False:
        domain = request.META.get('HTTP_HOST')
    courses = get_courses(user, domain=domain)
    courses = filter(course_filter,courses)
    courses = sort_by_announcement(courses)
    context = {'courses': courses,'request':request}
    #return render_to_response('murp/selects.html',context)
    return render_to_response('murp/mytest.html',context)
Ejemplo n.º 28
0
def get_university_courses(user, university_code):
    """
    Returns an array containing courses object for the given
    organization.
    """
    courses = get_courses(user)
    if university_code == "other":
        # "other" courses that are associated to organizations that are not
        # listed in the university page.
        university_codes = University.objects.values_list('code', flat=True)
        courses = [c for c in courses if c.org not in university_codes]
    else:
        courses = [c for c in courses if c.org == university_code]
    courses = sort_by_announcement(courses)
    return courses
Ejemplo n.º 29
0
def university_search(request, org_id=""):
    if request.is_ajax():
        query_university = org_id
        courses = []
        allCourses = get_courses(request.user, request.META.get('HTTP_HOST'))
        if query_university is not None:
            for course in allCourses:
                university = get_course_about_section(course, 'university')
                if (query_university.lower() in university.lower()) and (
                        university.lower() in query_university.lower()):
                    courses.append(course)
        if courses:
            return render_to_response("courseware/courses_search.html",
                                      {'courses': courses})
        else:
            return HttpResponse("No Courses Found")
Ejemplo n.º 30
0
def course_attr_list_handler(request, course_category, course_level=None):

    courses = get_courses(request.user, request.META.get('HTTP_HOST'))
    courses = sort_and_audited_items(courses)
    courses_list = []

    for course in courses:
        if course_level:
            if course.course_level == course_level and course.course_category == course_category:
                courses_list.append(course)
        elif course.course_category == course_category:
            courses_list.append(course)
        else:
            continue

    return return_fixed_courses(request, courses_list, None)
Ejemplo n.º 31
0
def courses(request):
    """
    Render "find courses" page.  The course selection work is done in courseware.courses.
    """
    courses = get_courses(request.user, request.META.get('HTTP_HOST'))
    courses = sort_by_announcement(courses)
    universities = []
    for course in courses:
        university = get_course_about_section(course, 'university')
        if not university in universities:
            universities.append(university)
    universities.sort()
    return render_to_response("courseware/courses.html", {
        'courses': courses,
        'universities': universities
    })
Ejemplo n.º 32
0
def course_attr_list_handler(request, course_category, course_level=None):

    courses = get_courses(request.user, request.META.get('HTTP_HOST'))
    courses = sort_and_audited_items(courses)
    courses_list = []

    for course in courses:
        if course_level:
            if course.course_level == course_level and course.course_category == course_category:
                courses_list.append(course)
        elif course.course_category == course_category:
            courses_list.append(course)
        else:
            continue

    return return_fixed_courses(request, courses_list, None)
Ejemplo n.º 33
0
def major_search(request):
    major_result = request.POST
    major_s = major_result.get('search').lower()
    major_m = major_result.get('major_name').lower()#choise major
    major_g = major_result.get('grade').lower()#choice grade
    course_select=[]
    courses_L = get_courses(request.user, request.META.get('HTTP_HOST'))

    courses_L = sort_by_announcement(courses_L)
    if major_s==None:
        return render_to_response("courseware/courses.html", {'courses': courses_L})
    else:
        for course in courses_L:
            major_title=get_course_about_section(course, 'title').lower()
            if major_s in major_title:
                course_select.append(course)
        return render_to_response("courseware/courses.html", {'courses': course_select})
Ejemplo n.º 34
0
def search_courses(request):
    """
    Render "find courses" page.  The course selection work is done in courseware.courses.
    """
    courses = get_courses1(request, request.user,
                           request.META.get('HTTP_HOST'))
    courses = sort_by_announcement(courses)
    c_list = []
    c_num = []
    c_len = CourseCategory.objects.all().count()
    for i in range(1, c_len + 1):
        c_name = CourseCategory.objects.get(id=i).category_name
        c_list.append(c_name)
    all_courses = get_courses(request.user, request.META.get('HTTP_HOST'))
    all_c_num = len(all_courses)
    for j in range(1, 17):
        c_num.append(0)
    for c in all_courses:
        c_category = c.display_number_with_default[0:2]
        c_category_no = int(c_category)
        num_t = c_num[c_category_no - 1]
        c_num[c_category_no - 1] = num_t + 1
    name_list = []
    category_list = []
    category_num = []
    for i in range(0, len(c_num)):
        if c_num[i] != 0:
            if i < 9:
                num = '0' + str(int(i + 1))
                name_list.append(num)
            else:
                name_list.append(i + 1)
            category_list.append(c_list[i])
            category_num.append(c_num[i])
    none_zero = len(category_num)
    return render_to_response(
        "courseware/courses.html", {
            'courses': courses,
            'name_list': name_list,
            'category_list': category_list,
            'category_num': category_num,
            'all_c_num': all_c_num,
            'none_zero': none_zero
        })
Ejemplo n.º 35
0
    def test_get_courses_with_filter(self):
        """
        Verify that filtering performs as expected.
        """
        user = UserFactory.create()
        non_mobile_course = CourseFactory.create(emit_signals=True)
        mobile_course = CourseFactory.create(mobile_available=True, emit_signals=True)

        test_cases = (
            (None, {non_mobile_course.id, mobile_course.id}),
            (dict(mobile_available=True), {mobile_course.id}),
            (dict(mobile_available=False), {non_mobile_course.id}),
        )
        for filter_, expected_courses in test_cases:
            self.assertEqual(
                {course.id for course in get_courses(user, filter_=filter_)},
                expected_courses,
                "testing get_courses with filter_={}".format(filter_),
            )
Ejemplo n.º 36
0
def courses(request):
    """
    Render "find courses" page.  The course selection work is done in courseware.courses.
    """
    courses = sort_by_announcement(get_courses(request.user, request.META.get('HTTP_HOST')))
    course_list = []
    for course in courses:
        course_item = {
            "display_number": course.display_number_with_default,
            "course_title": get_course_about_section(course, 'title'),
            "course_description": get_course_about_section(course, 'short_description'),
            "display_organization": get_course_about_section(course, 'university'),
            "course_image_url": course_image_url(course),
            "course_start": course.start,
            "course_id": course.id.to_deprecated_string(),
        }
        course_list.append(course_item)

    return JsonResponse(course_list)
Ejemplo n.º 37
0
def get_recommended_courses(user):
    """
    Helper function to get recommended courses for a user based on his interests
    """
    recommended_courses = []
    all_courses = get_courses(user)
    try:
        user_interests = user.extended_profile.get_user_selected_interests()
        for course in all_courses:
            try:
                tags = CustomSettings.objects.filter(id=course.id).first().tags
                tags = tags.split('|')
                tags = [tag.strip() for tag in tags]
                if set(user_interests) & set(tags) and not CourseEnrollment.is_enrolled(user, course.id):
                    recommended_courses.append(course)
            except AttributeError:
                pass
    except ObjectDoesNotExist:
        pass
    return recommended_courses
Ejemplo n.º 38
0
def search_category(request):
    courses = get_courses2(request,request.user, request.META.get('HTTP_HOST'))
    courses = sort_by_announcement(courses)
    c_list=[]
    c_num=[]
    c_len=CourseCategory.objects.all().count()
    for i in range(1,c_len+1):
	    c_name=CourseCategory.objects.get(id = i).category_name
	    c_list.append(c_name)
    all_courses = get_courses(request.user, request.META.get('HTTP_HOST'))
    all_c_num = len(all_courses)
    for j in range(1,17):
	    c_num.append(0)
    for c in all_courses:
        c_category = c.display_number_with_default[0:2]
        c_category_no = int(c_category)
        num_t=c_num[c_category_no-1]
        c_num[c_category_no-1]=num_t+1
    
    return render_to_response("courseware/courses.html", {'courses': courses,'c_list':c_list,'c_num':c_num,'all_c_num':all_c_num})
Ejemplo n.º 39
0
def major_search(request):
    major_result = request.POST
    major_s = major_result.get('search').lower()
    major_m = major_result.get('major_name').lower()  #choise major
    major_g = major_result.get('grade').lower()  #choice grade
    course_select = []

    courses_L = get_courses(request.user, request.META.get('HTTP_HOST'))
    courses_L = sort_by_announcement(courses_L)

    if major_s == None and major_g == None and major_m == None:
        return render_to_response("courseware/courses.html",
                                  {'courses': courses_L})
    elif major_s is not None:
        for course in courses_L:
            major_title = get_course_about_section(course, 'title').lower()
            if major_s in major_title:
                course_select.append(course)
        return render_to_response("courseware/courses.html",
                                  {'courses': course_select})
Ejemplo n.º 40
0
def index(request, extra_context={}, user=None):
    '''
    Render the edX main page.

    extra_context is used to allow immediate display of certain modal windows, eg signup,
    as used by external_auth.
    '''

    # The course selection work is done in courseware.courses.
    domain = settings.MITX_FEATURES.get('FORCE_UNIVERSITY_DOMAIN')  # normally False
    # do explicit check, because domain=None is valid
    if domain == False:
        domain = request.META.get('HTTP_HOST')

    courses = get_courses(None, domain=domain)
    courses = sort_by_announcement(courses)

    context = {'courses': courses}
    context.update(extra_context)
    return render_to_response('index.html', context)
Ejemplo n.º 41
0
def courses_list(request, status = "all", subject="all", destiny="all"):
    all_courses =  get_courses(request.user)
    courses = []
    for course in all_courses:
        if (status == "new"):
            if (not course.is_newish): continue
        elif (status ==  "past"):
            if (not course.has_ended()): continue
        elif (status == "current"):
            if (not course.has_started()): continue
        elif (status != "all"):
            continue
        if (subject != "all"):
            if not (subject in course.tags or dict(SUBJECTS).get(subject, '') in course.tags): continue
        if (destiny != "all"):
            if not (destiny in course.tags or dict(DESTINY).get(destiny, '') in course.tags): continue
        courses += [course]
    courses = sort_by_announcement(courses)
    context = {'courses': courses, 'destiny': destiny, 'subject': subject}
    return render_to_response("courses_list.html", context)
Ejemplo n.º 42
0
    def get_courses_depend_action():
        """
        Return courses depend on action
            action: [homefalls, hot, lastest, my, search]
                homefalls: get all courses
                hot: Number of attended people > ?
                lastest: News last week
                my: I registered
                all: like 'homefalls'
        """

        courses = get_courses(user, request.META.get('HTTP_HOST'))
        courses = sort_by_announcement(courses)
        courses_list = []

        if action == "latest":
            default_count = 20
            if len(courses) < default_count:
                default_count = len(courses)

            courses_list = courses[0:default_count]
        elif action == "my":
            # filter my registered courses
            for course in courses:
                if registered_for_course(course, user):
                    courses_list.append(course)
        elif action == "rolling":
            default_count = 5
            courses_list = courses[0:default_count]
        elif action == 'search':
            keyword = request.GET.get("keyword")

            if keyword:
                for c in courses:
                    print (keyword in c.org or keyword in c.id or keyword in c.display_name_with_default)
                    if keyword in c.org or keyword in c.id or keyword in c.display_name_with_default:
                        courses_list.append(c)
        else:
            courses_list = courses

        return courses_list
Ejemplo n.º 43
0
    def get_courses_depend_action():
        """
        Return courses depend on action
            action: [homefalls, hot, lastest, my, search]
                homefalls: get all courses
                hot: Number of attended people > ?
                lastest: News last week
                my: I registered
                all: like 'homefalls'
        """

        courses = get_courses(user, request.META.get('HTTP_HOST'))
        courses = sort_by_announcement(courses)
        courses_list = []

        if action == "latest":
            default_count = 20
            if len(courses) < default_count:
                default_count = len(courses)

            courses_list = courses[0:default_count]
        elif action == "my":
            # filter my registered courses
            for course in courses:
                if registered_for_course(course, user):
                    courses_list.append(course)
        elif action == "rolling":
            default_count = 5
            courses_list = courses[0:default_count]
        elif action == 'search':
            keyword = request.GET.get("keyword")

            if keyword:
                for c in courses:
                    print (keyword in c.org or keyword in c.id or keyword in c.display_name_with_default)
                    if keyword in c.org or keyword in c.id or keyword in c.display_name_with_default:
                        courses_list.append(c)
        else:
            courses_list = courses

        return courses_list
Ejemplo n.º 44
0
def grade_report_generation(request):
    """
    For generating the reports of all the courses.
    """
    user = User.objects.get(pk=1)
    courses_list = []
    courses_list = get_courses(user)
    for course in courses_list:
        course_key =course.id
        try:
            instructor_task.api.submit_calculate_grades_csv(request, course_key)
            success_status = ("The grade report is being created."
                              " To view the status of the report, see Pending Tasks below.")

        except Exception as e:
            already_running_status = ("The grade report is currently being created."
                                       " To view the status of the report, see Pending Tasks below."
                                       " You will be able to download the report when it is complete.")
            print e.message
    merge_reports()
    return JsonResponse({"Reports Merged":"TRUE"})
Ejemplo n.º 45
0
    def test_get_courses_with_filter(self):
        """
        Verify that filtering performs as expected.
        """
        user = UserFactory.create()
        mobile_course = CourseFactory.create(emit_signals=True)
        non_mobile_course =\
            CourseFactory.create(mobile_available=False, emit_signals=True)

        test_cases = (
            (None, {non_mobile_course.id, mobile_course.id}),
            (dict(mobile_available=True), {mobile_course.id}),
            (dict(mobile_available=False), {non_mobile_course.id}),
        )
        for filter_, expected_courses in test_cases:
            self.assertEqual(
                {course.id
                 for course in get_courses(user, filter_=filter_)},
                expected_courses,
                u"testing get_courses with filter_={}".format(filter_),
            )
Ejemplo n.º 46
0
def courses_index(request):
    courses = [_dates_description(course) for course in get_courses(request.user)]
    form = CourseFilteringForm(request.GET or None)
    by = request.GET.get('by', COURSES_BY_PAGE)  # override default page size

    if form.is_valid():
        if form.cleaned_data['university']:
            university = University.objects.get(code=form.cleaned_data['university'])
            children = [child.code for child in university.children.all()]
            courses = [c for c in courses if c.org == form.cleaned_data['university'] or c.org in children]
        if form.cleaned_data['state']:
            now = timezone.make_aware(datetime.datetime.utcnow(), timezone.get_current_timezone())
            if form.cleaned_data['state'] == 'future':
                courses = [c for c in courses if c.start and c.start > now]
            elif form.cleaned_data['state'] == 'current':
                courses = [c for c in courses if c.start and c.start < now and c.end and c.end > now]
            elif form.cleaned_data['state'] == 'past':
                courses = [c for c in courses if c.end and c.end < now]
    elif form.errors:
        return redirect(course_index)
    courses = _sort_courses(courses)

    # paginate courses
    paginator = Paginator(courses, by, orphans=3)
    page = request.GET.get('page')

    try:
        courses = paginator.page(page)
    except PageNotAnInteger:
        courses = paginator.page(1)
    except EmptyPage:
        courses = paginator.page(paginator.num_pages)

    return render(request, 'courses/index.html', {
        'form': form,
        'courses': courses,
        'current_language': translation.get_language(),
    })
Ejemplo n.º 47
0
def index(request, extra_context={}, user=None):
    '''
    Render the edX main page.

    extra_context is used to allow immediate display of certain modal windows, eg signup,
    as used by external_auth.
    '''

    # The course selection work is done in courseware.courses.
    domain = settings.MITX_FEATURES.get('FORCE_UNIVERSITY_DOMAIN')     # normally False
    # do explicit check, because domain=None is valid
    if domain == False:
        domain = request.META.get('HTTP_HOST')

    courses = get_courses(None, domain=domain)
    courses = sort_by_announcement(courses)

    # Get the 3 most recent news
    top_news = _get_news(top=3)

    context = {'courses': courses, 'news': top_news}
    context.update(extra_context)
    return render_to_response('index.html', context)
Ejemplo n.º 48
0
def course_kinds_about(request, course_kind):
    """this is to show the kinds of course page"""
    #print course_kind
    courses = get_courses(request.user, request.META.get('HTTP_HOST'))
    plist = get_primary_course(courses, course_kind)
    mlist = get_Intermediate_course(courses, course_kind)
    slist = get_senior_course(courses, course_kind)

    plen = len(plist)
    mlen = len(mlist)
    slen = len(slist)

    content = {
        'course_kind': course_kind,
        'slist': slist,
        'plist': plist,
        'mlist': mlist,
        'plen': plen,
        'mlen': mlen,
        'slen': slen,

    }
    return render_to_response('courseware/course_kinds.html', content)
Ejemplo n.º 49
0
def index_list(request):
    state_temp = []
    district_temp = []
    district_name = {}
    district_list = []
    
    courses = get_courses(request.user, request.META.get('HTTP_HOST'))
    courses = sort_by_custom(courses)
    
    for course in courses:
        if request.user.is_superuser is False:
            if request.user.profile.district.state.name in course.display_state:
                state_temp.append(request.user.profile.district.state.name)

            if request.user.profile.district.code in course.display_district:
                district = District.objects.filter(code=request.user.profile.district.code)[0]
                district_temp.append(request.user.profile.district.code)
                district_name[request.user.profile.district.code] = district.name
        else:
            if len(course.display_state) > 0 and is_all(course, 'state') is False:
                state_temp.extend(course.display_state)

            if len(course.display_district) > 0 and is_all(course, 'district') is False:
                districts = District.objects.filter(code__in=course.display_district)
                district_temp.extend(course.display_district)
                for district in districts:
                    district_name[district.code] = district.name

        state_list = sorted(set(state_temp), key=lambda x: x[0])
        district_temp = sorted(set(district_temp), key=lambda x: x[0])
        for dl in district_temp:
            district_list.append({'id': dl, 'name': district_name[dl]})
    
    return render_to_response('access_resource_library_list.html', {
                                                          "states": state_list,
                                                          "districts": district_list})
Ejemplo n.º 50
0
def all_courses(request, extra_context={}, user=AnonymousUser()):
    """
    Render the edX main page.

    extra_context is used to allow immediate display of certain modal windows, eg signup,
    as used by external_auth.
    """

    # The course selection work is done in courseware.courses.
    domain = settings.FEATURES.get('FORCE_UNIVERSITY_DOMAIN')  # normally False
    # do explicit check, because domain=None is valid
    if domain is False:
        domain = request.META.get('HTTP_HOST')

    # Hardcoded `AnonymousUser()` to hide unpublished courses always
    courses = get_courses(AnonymousUser(), domain=domain)
    courses = sort_by_announcement(courses)

    courses = edraak_courses_logic(courses)

    context = {'courses': courses}

    context.update(extra_context)
    return render_to_response('all_courses.html', context)
Ejemplo n.º 51
0
    def tma_users_registered(self):
        context = {}
        enrolled_to_current_course = False
        user_email = self.request.POST['user_email']

        if User.objects.filter(email=user_email).exists():
            user = User.objects.get(email=user_email)
            #Get preprofile info
            userprofile = UserProfile.objects.get(user=user)
            try:
                custom_field = json.loads(user.profile.custom_field)
                first_name = custom_field['first_name']
                last_name = custom_field['last_name']
            except:
                custom_field = {}
                last_name = 'Undefined'
                first_name = 'Undefined'

            #Get courses enrollments
            microsite_courses = get_courses(
                user=user,
                org=configuration_helpers.get_value('course_org_filter'))

            user_ms_course_list = {}
            for course in microsite_courses:
                if CourseEnrollment.objects.filter(
                        user=user, course_id=course.id).exists():
                    user_ms_course_list[str(course.id)] = {
                        'course_name':
                        course.display_name_with_default,
                        'course_grades':
                        '/courses/' + str(course.id) + '/progress/' +
                        str(user.id),
                        'opened_enrollments':
                        is_enrollment_opened(course),
                        'opened_course':
                        is_course_opened(course),
                        'on_invitation':
                        course.invitation_only,
                    }

            #Get user grade for this course
            course_key = SlashSeparatedCourseKey.from_deprecated_string(
                self.course_id)
            current_course = get_course_by_id(course_key)
            grade = CourseGradeFactory().create(user, current_course)

            #User dates
            if user.last_login is not None:
                last_login = user.date_joined.strftime("%d-%b-%Y %H:%M:%S")
            else:
                last_login = _('User has not logged in yet')

            context = {
                'email': str(user_email),
                'id': str(user.id),
                'inscription':
                str(user.date_joined.strftime("%d-%b-%Y %H:%M:%S")),
                'last_login': last_login,
                'first_name': first_name,
                'last_name': last_name,
                'user_ms_course_list': user_ms_course_list,
                'custom_field': custom_field,
                'grade': grade.grade_value['percent'],
                'passed': grade.grade_value['grade'],
                'active': user.is_active,
                'login_failure': LoginFailures.is_user_locked_out(user),
            }

            #Check if user is registered to this course
            course_key = SlashSeparatedCourseKey.from_deprecated_string(
                self.course_id)
            if CourseEnrollment.objects.filter(user=user,
                                               course_id=course_key,
                                               is_active=1).exists():
                current_course_grades = '/courses/' + str(
                    self.course_id) + '/progress/' + str(user.id)
                context['enrolled_to_current_course'] = True
                context['current_course_grades'] = current_course_grades
            else:
                context['enrolled_to_current_course'] = False

        else:
            context = {
                'error':
                'Le participant n\'a pas de compte sur nos plateformes.'
            }

        return context
Ejemplo n.º 52
0
def student_dashboard(request):
    """
    Provides the LMS dashboard view

    TODO: This is lms specific and does not belong in common code.

    Arguments:
        request: The request object.

    Returns:
        The dashboard response.

    """
    user = request.user
    userNewData = UserProfile.objects.filter(user=user)
    if not UserProfile.objects.filter(user=user).exists():
        return redirect(reverse('account_settings'))

    platform_name = configuration_helpers.get_value("platform_name",
                                                    settings.PLATFORM_NAME)

    enable_verified_certificates = configuration_helpers.get_value(
        'ENABLE_VERIFIED_CERTIFICATES',
        settings.FEATURES.get('ENABLE_VERIFIED_CERTIFICATES'))
    display_course_modes_on_dashboard = configuration_helpers.get_value(
        'DISPLAY_COURSE_MODES_ON_DASHBOARD',
        settings.FEATURES.get('DISPLAY_COURSE_MODES_ON_DASHBOARD', True))
    activation_email_support_link = configuration_helpers.get_value(
        'ACTIVATION_EMAIL_SUPPORT_LINK',
        settings.ACTIVATION_EMAIL_SUPPORT_LINK) or settings.SUPPORT_SITE_LINK
    hide_dashboard_courses_until_activated = configuration_helpers.get_value(
        'HIDE_DASHBOARD_COURSES_UNTIL_ACTIVATED',
        settings.FEATURES.get('HIDE_DASHBOARD_COURSES_UNTIL_ACTIVATED', False))
    empty_dashboard_message = configuration_helpers.get_value(
        'EMPTY_DASHBOARD_MESSAGE', None)

    # Get the org whitelist or the org blacklist for the current site
    site_org_whitelist, site_org_blacklist = get_org_black_and_whitelist_for_site(
    )
    course_enrollments = list(
        get_course_enrollments(user, site_org_whitelist, site_org_blacklist))

    # Get the entitlements for the user and a mapping to all available sessions for that entitlement
    # If an entitlement has no available sessions, pass through a mock course overview object
    (course_entitlements, course_entitlement_available_sessions,
     unfulfilled_entitlement_pseudo_sessions
     ) = get_filtered_course_entitlements(user, site_org_whitelist,
                                          site_org_blacklist)

    # Record how many courses there are so that we can get a better
    # understanding of usage patterns on prod.
    monitoring_utils.accumulate('num_courses', len(course_enrollments))

    # Sort the enrollment pairs by the enrollment date
    course_enrollments.sort(key=lambda x: x.created, reverse=True)

    # Retrieve the course modes for each course
    enrolled_course_ids = [
        enrollment.course_id for enrollment in course_enrollments
    ]
    __, unexpired_course_modes = CourseMode.all_and_unexpired_modes_for_courses(
        enrolled_course_ids)
    course_modes_by_course = {
        course_id: {mode.slug: mode
                    for mode in modes}
        for course_id, modes in iteritems(unexpired_course_modes)
    }

    # Check to see if the student has recently enrolled in a course.
    # If so, display a notification message confirming the enrollment.
    enrollment_message = _create_recent_enrollment_message(
        course_enrollments, course_modes_by_course)
    course_optouts = Optout.objects.filter(user=user).values_list('course_id',
                                                                  flat=True)

    # Display activation message
    activate_account_message = ''
    if not user.is_active:
        activate_account_message = Text(
            _("Check your {email_start}{email}{email_end} inbox for an account activation link from {platform_name}. "
              "If you need help, contact {link_start}{platform_name} Support{link_end}."
              )
        ).format(
            platform_name=platform_name,
            email_start=HTML("<strong>"),
            email_end=HTML("</strong>"),
            email=user.email,
            link_start=HTML(
                "<a target='_blank' href='{activation_email_support_link}'>").
            format(
                activation_email_support_link=activation_email_support_link, ),
            link_end=HTML("</a>"),
        )

    enterprise_message = get_dashboard_consent_notification(
        request, user, course_enrollments)

    recovery_email_message = recovery_email_activation_message = None
    if is_secondary_email_feature_enabled_for_user(user=user):
        try:
            account_recovery_obj = AccountRecovery.objects.get(user=user)
        except AccountRecovery.DoesNotExist:
            recovery_email_message = Text(
                _("Add a recovery email to retain access when single-sign on is not available. "
                  "Go to {link_start}your Account Settings{link_end}.")
            ).format(link_start=HTML(
                "<a target='_blank' href='{account_setting_page}'>").format(
                    account_setting_page=reverse('account_settings'), ),
                     link_end=HTML("</a>"))
        else:
            if not account_recovery_obj.is_active:
                recovery_email_activation_message = Text(
                    _("Recovery email is not activated yet. "
                      "Kindly visit your email and follow the instructions to activate it."
                      ))

    # Disable lookup of Enterprise consent_required_course due to ENT-727
    # Will re-enable after fixing WL-1315
    consent_required_courses = set()
    enterprise_customer_name = None

    # Account activation message
    account_activation_messages = [
        message for message in messages.get_messages(request)
        if 'account-activation' in message.tags
    ]

    # Global staff can see what courses encountered an error on their dashboard
    staff_access = False
    errored_courses = {}
    if has_access(user, 'staff', 'global'):
        # Show any courses that encountered an error on load
        staff_access = True
        errored_courses = modulestore().get_errored_courses()

    show_courseware_links_for = {
        enrollment.course_id: has_access(request.user, 'load',
                                         enrollment.course_overview)
        for enrollment in course_enrollments
    }

    # Find programs associated with course runs being displayed. This information
    # is passed in the template context to allow rendering of program-related
    # information on the dashboard.
    meter = ProgramProgressMeter(request.site,
                                 user,
                                 enrollments=course_enrollments)
    ecommerce_service = EcommerceService()
    inverted_programs = meter.invert_programs()

    urls, programs_data = {}, {}
    bundles_on_dashboard_flag = WaffleFlag(
        WaffleFlagNamespace(name=u'student.experiments'),
        u'bundles_on_dashboard')

    # TODO: Delete this code and the relevant HTML code after testing LEARNER-3072 is complete
    if bundles_on_dashboard_flag.is_enabled(
    ) and inverted_programs and inverted_programs.items():
        if len(course_enrollments) < 4:
            for program in inverted_programs.values():
                try:
                    program_uuid = program[0]['uuid']
                    program_data = get_programs(request.site,
                                                uuid=program_uuid)
                    program_data = ProgramDataExtender(program_data,
                                                       request.user).extend()
                    skus = program_data.get('skus')
                    checkout_page_url = ecommerce_service.get_checkout_page_url(
                        *skus)
                    program_data[
                        'completeProgramURL'] = checkout_page_url + '&bundle=' + program_data.get(
                            'uuid')
                    programs_data[program_uuid] = program_data
                except:  # pylint: disable=bare-except
                    pass

    # Construct a dictionary of course mode information
    # used to render the course list.  We re-use the course modes dict
    # we loaded earlier to avoid hitting the database.
    course_mode_info = {
        enrollment.course_id: complete_course_mode_info(
            enrollment.course_id,
            enrollment,
            modes=course_modes_by_course[enrollment.course_id])
        for enrollment in course_enrollments
    }

    # Determine the per-course verification status
    # This is a dictionary in which the keys are course locators
    # and the values are one of:
    #
    # VERIFY_STATUS_NEED_TO_VERIFY
    # VERIFY_STATUS_SUBMITTED
    # VERIFY_STATUS_APPROVED
    # VERIFY_STATUS_MISSED_DEADLINE
    #
    # Each of which correspond to a particular message to display
    # next to the course on the dashboard.
    #
    # If a course is not included in this dictionary,
    # there is no verification messaging to display.
    verify_status_by_course = check_verify_status_by_course(
        user, course_enrollments)
    cert_statuses = {
        enrollment.course_id: cert_info(request.user,
                                        enrollment.course_overview)
        for enrollment in course_enrollments
    }

    # only show email settings for Mongo course and when bulk email is turned on
    show_email_settings_for = frozenset(
        enrollment.course_id for enrollment in course_enrollments
        if (BulkEmailFlag.feature_enabled(enrollment.course_id)))

    # Verification Attempts
    # Used to generate the "you must reverify for course x" banner
    verification_status = IDVerificationService.user_status(user)
    verification_errors = get_verification_error_reasons_for_display(
        verification_status['error'])

    # Gets data for midcourse reverifications, if any are necessary or have failed
    statuses = ["approved", "denied", "pending", "must_reverify"]
    reverifications = reverification_info(statuses)

    block_courses = frozenset(
        enrollment.course_id for enrollment in course_enrollments
        if is_course_blocked(
            request,
            CourseRegistrationCode.objects.filter(
                course_id=enrollment.course_id,
                registrationcoderedemption__redeemed_by=request.user),
            enrollment.course_id))

    enrolled_courses_either_paid = frozenset(
        enrollment.course_id for enrollment in course_enrollments
        if enrollment.is_paid_course())

    # If there are *any* denied reverifications that have not been toggled off,
    # we'll display the banner
    denied_banner = any(item.display for item in reverifications["denied"])

    # Populate the Order History for the side-bar.
    order_history_list = order_history(user,
                                       course_org_filter=site_org_whitelist,
                                       org_filter_out_set=site_org_blacklist)

    # get list of courses having pre-requisites yet to be completed
    courses_having_prerequisites = frozenset(
        enrollment.course_id for enrollment in course_enrollments
        if enrollment.course_overview.pre_requisite_courses)
    courses_requirements_not_met = get_pre_requisite_courses_not_completed(
        user, courses_having_prerequisites)

    if 'notlive' in request.GET:
        redirect_message = _(
            "The course you are looking for does not start until {date}."
        ).format(date=request.GET['notlive'])
    elif 'course_closed' in request.GET:
        redirect_message = _(
            "The course you are looking for is closed for enrollment as of {date}."
        ).format(date=request.GET['course_closed'])
    elif 'access_response_error' in request.GET:
        # This can be populated in a generalized way with fields from access response errors
        redirect_message = request.GET['access_response_error']
    else:
        redirect_message = ''

    valid_verification_statuses = [
        'approved', 'must_reverify', 'pending', 'expired'
    ]
    display_sidebar_on_dashboard = (
        len(order_history_list)
        or (verification_status['status'] in valid_verification_statuses
            and verification_status['should_display']))

    # Filter out any course enrollment course cards that are associated with fulfilled entitlements
    for entitlement in [
            e for e in course_entitlements
            if e.enrollment_course_run is not None
    ]:
        course_enrollments = [
            enr for enr in course_enrollments
            if entitlement.enrollment_course_run.course_id != enr.course_id
        ]

    context = {
        'journal_info':
        get_journals_context(request),  # TODO: Course Listing Plugin required
        'courses':
        get_courses(user),
        'urls':
        urls,
        'programs_data':
        programs_data,
        'enterprise_message':
        enterprise_message,
        'consent_required_courses':
        consent_required_courses,
        'enterprise_customer_name':
        enterprise_customer_name,
        'enrollment_message':
        enrollment_message,
        'redirect_message':
        Text(redirect_message),
        'account_activation_messages':
        account_activation_messages,
        'activate_account_message':
        activate_account_message,
        'course_enrollments':
        course_enrollments,
        'course_entitlements':
        course_entitlements,
        'course_entitlement_available_sessions':
        course_entitlement_available_sessions,
        'unfulfilled_entitlement_pseudo_sessions':
        unfulfilled_entitlement_pseudo_sessions,
        'course_optouts':
        course_optouts,
        'staff_access':
        staff_access,
        'errored_courses':
        errored_courses,
        'show_courseware_links_for':
        show_courseware_links_for,
        'all_course_modes':
        course_mode_info,
        'cert_statuses':
        cert_statuses,
        'credit_statuses':
        _credit_statuses(user, course_enrollments),
        'show_email_settings_for':
        show_email_settings_for,
        'reverifications':
        reverifications,
        'verification_display':
        verification_status['should_display'],
        'verification_status':
        verification_status['status'],
        'verification_status_by_course':
        verify_status_by_course,
        'verification_errors':
        verification_errors,
        'block_courses':
        block_courses,
        'denied_banner':
        denied_banner,
        'billing_email':
        settings.PAYMENT_SUPPORT_EMAIL,
        'user':
        user,
        'logout_url':
        reverse('logout'),
        'platform_name':
        platform_name,
        'enrolled_courses_either_paid':
        enrolled_courses_either_paid,
        'provider_states': [],
        'order_history_list':
        order_history_list,
        'courses_requirements_not_met':
        courses_requirements_not_met,
        'nav_hidden':
        True,
        'inverted_programs':
        inverted_programs,
        'show_program_listing':
        ProgramsApiConfig.is_enabled(),
        'show_journal_listing':
        journals_enabled(),  # TODO: Dashboard Plugin required
        'show_dashboard_tabs':
        True,
        'disable_courseware_js':
        True,
        'display_course_modes_on_dashboard':
        enable_verified_certificates and display_course_modes_on_dashboard,
        'display_sidebar_on_dashboard':
        display_sidebar_on_dashboard,
        'display_sidebar_account_activation_message':
        not (user.is_active or hide_dashboard_courses_until_activated),
        'display_dashboard_courses':
        (user.is_active or not hide_dashboard_courses_until_activated),
        'empty_dashboard_message':
        empty_dashboard_message,
        'recovery_email_message':
        recovery_email_message,
        'recovery_email_activation_message':
        recovery_email_activation_message,
        'data':
        userNewData,
    }

    if ecommerce_service.is_enabled(request.user):
        context.update({
            'use_ecommerce_payment_flow':
            True,
            'ecommerce_payment_page':
            ecommerce_service.payment_page_url(),
        })

    # Gather urls for course card resume buttons.
    resume_button_urls = ['' for entitlement in course_entitlements]
    for url in _get_urls_for_resume_buttons(user, course_enrollments):
        resume_button_urls.append(url)
    # There must be enough urls for dashboard.html. Template creates course
    # cards for "enrollments + entitlements".
    context.update({'resume_button_urls': resume_button_urls})

    response = render_to_response('dashboard.html', context)
    set_logged_in_cookies(request, response, user)
    return response
Ejemplo n.º 53
0
 def items(self, request):
     return courses.utils.sort_courses(get_courses(None))[:16]
Ejemplo n.º 54
0
def colleges(request):

    courses = get_courses(request.user, request.META.get('HTTP_HOST'))
    return render_to_response("colleges/schools.html", {"courses": courses})
Ejemplo n.º 55
0
def courses_list_handler(request, action):
    """
    Return courses based on request params
    """
    try:
        user = request.user
    except:
        user = AnonymousUser()

    if action not in [
            "homefalls", "all", "hot", "latest", "my", "search", "rolling",
            "sync"
    ]:
        return JsonResponse({
            "success":
            False,
            "errmsg":
            "not support other actions except homefalls all hot latest rolling and my"
        })

    def get_courses_depend_action(courses):
        """
        Return courses depend on action
            action: [homefalls, hot, lastest, my, search]
                homefalls: get all courses
                hot: Number of attended people > ?
                lastest: News last week
                my: I registered
                all: like 'homefalls'
        """
        courses = sort_and_audited_items(courses)
        courses_list = []

        if action == "latest":
            default_count = 20
            if len(courses) < default_count:
                default_count = len(courses)

            courses_list = courses[0:default_count]
        elif action == "my":
            # filter my registered courses
            for course in courses:
                if registered_for_course(course, user):
                    courses_list.append(course)
        elif action == "rolling":
            default_count = 5
            courses_list = courses[0:default_count]
        elif action == 'search':
            keyword = request.GET.get("keyword")

            if keyword:
                for c in courses:
                    if keyword in c.org or keyword in c.id or keyword in c.display_name_with_default:
                        courses_list.append(c)
        else:
            courses_list = courses

        return courses_list

    courses = get_courses(user, request.META.get('HTTP_HOST'))
    if action != "sync":
        courses = get_courses_depend_action(courses)

    return return_fixed_courses(request, courses, action)