Exemple #1
0
def course_getListForOffset(request, offset, limit):
    """
    Hàm trả về  các row trong unit theo offset
    Trả về số lượng page mà chia theo limit
    """
    if checkInUrl(request, 'course') is False:
        listFunction = request.user.list_function()
        return HttpResponseRedirect(reverse(listFunction[0]))
    if request.method == 'GET':
        unitRole = request.user.unit_role
        if unitRole == 0:
            courses = Courses.objects.order_by('-courseID').all()
        else:
            courses = Courses.objects.order_by('-courseID').filter(unit=unitRole).all()
        courseList = courses[offset:offset + limit].select_related('unit')
        courseCount = courses.count()
        courseSerializer = CoursesSerializer(courseList, many = True)
        page = math.ceil(courseCount/limit)
        for cS, cL in zip(courseSerializer.data, courseList):
            cS['unit'] = cL.unit.unitName
        data = {
            'data': courseSerializer.data,
            'numberOfPage': page,
        }
        createLog(request, 'VIEW - Môn học', '')
        return Response(data)
Exemple #2
0
def user_form(request, id=0):

    if checkInUrl(request, 'user') is False:
        listFunction = request.user.list_function()
        return HttpResponseRedirect(reverse(listFunction[0]))
    try:
        if request.method == 'GET':
            if id == 0:
                userForm = CustomUserForm()
            else:
                user = CustomUser.objects.get(pk=id)
                userForm = CustomUserForm(instance=user)
            return TemplateResponse(request, 'adminuet/userform.html',
                                    {'form': userForm})
        else:
            contentLog = 'UPDATE - Người dùng'
            if id == 0:
                userForm = CustomUserForm(request.POST)
                contentLog = 'INSERT - Người dùng'
            else:
                user = CustomUser.objects.get(pk=id)
                userForm = CustomUserForm(request.POST, instance=user)
            if userForm.is_valid():
                userForm.save()
                createLog(request, contentLog, '')
    except Exception as error:
        print(error)
    return redirect('/adminuet/user/')
Exemple #3
0
def trainingframework_getListForOffset(request, offset, limit):
    """
    Hàm trả về  các row trong unit theo offset
    Trả về số lượng page mà chia theo limit
    """
    if checkInUrl(request, 'trainingframework') is False:
        listFunction = request.user.list_function()
        return HttpResponseRedirect(reverse(listFunction[0]))
    if request.method == 'GET':
        unitRole = request.user.unit_role
        if unitRole == 0:
            trainingframeworks = Major_Course.objects.order_by('-ID').all()
        else:
            trainingframeworks = Major_Course.objects.filter(
                major__unit=unitRole).order_by('-ID').all()
        trainingframeworkList = trainingframeworks[offset:offset +
                                                   limit].select_related(
                                                       'course', 'major')
        trainingframeworkCount = trainingframeworks.count()
        trainingframeworkSerializer = TrainingframeworkSerializer(
            trainingframeworkList, many=True)
        for t, ts in zip(trainingframeworkList,
                         trainingframeworkSerializer.data):
            ts['course'] = t.course.courseName
            ts['major'] = t.major.majorName
        page = math.ceil(trainingframeworkCount / limit)
        data = {
            'data': trainingframeworkSerializer.data,
            'numberOfPage': page,
        }
        createLog(request, 'VIEW - Khung đào tạo', '')
        return Response(data)
def export_page(request):
    """
    Thuộc tính của file csv: stt, roleName, roleDescription
    """

    if checkInUrl(request, 'learningoutcome') is False:
        listFunction = request.user.list_function()
        return HttpResponseRedirect(reverse(listFunction[0]))
    try:
        nameFileExport = 'attachment; filename="{}.csv"'.format(
            "ListTranscript")
        unitRole = request.user.unit_role
        if unitRole == 0:
            transcript = Transcript.objects.all()
        else:
            transcript = Transcript.objects.filter(
                student__major__unit=unitRole).all()
        rows = ([i + 1, t.student, t.course, t.semester, t.grade]
                for t, i in zip(transcript, range(transcript.count())))
        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = nameFileExport
        response.write(u'\ufeff'.encode('utf8'))
        writer = csv.writer(response)
        writer.writerow(['stt', 'student', 'course', 'semeste', 'grade'])
        [
            writer.writerow([row[0], row[1], row[2], row[3], row[4]])
            for row in rows
        ]
        createLog(request, 'EXPORT - Kết quả học tập', '')
        return response
    except Exception as error:
        print(error)
        messages.error(request, "Thao tác thất bại.")
    return redirect('/adminuet/learningoutcome/')
Exemple #5
0
def export_page(request):
    """
    Thực hiện xuất file csv các khóa
    """
    if checkInUrl(request, 'generation') is False:
        listFunction = request.user.list_function()
        return HttpResponseRedirect(reverse(listFunction[0]))
    try:
        nameFileExport = 'attachment; filename="{}.csv"'.format(
            "ListGeneration")
        unitRole = request.user.unit_role
        # Rule admin
        if unitRole == 0:
            list_generation = Generations.objects.all()
        else:  # Rule quản trị cấp trường
            list_generation = Generations.objects.filter(unit=unitRole).all()
        rows = ([
            i + 1, generation.generationName, generation.beginningYear,
            generation.unit
        ] for generation, i in zip(list_generation,
                                   range(list_generation.count())))
        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = nameFileExport
        writer = csv.writer(response)
        writer.writerow(['stt', 'generationName', 'beginningYear', 'unit'])
        [writer.writerow([row[0], row[1], row[2], row[3]]) for row in rows]
        createLog(request, 'EXPORT - Khóa', '')
        return response
    except Exception as error:
        print(error)
        messages.error(request, "Thao tác thất bại.")
    return redirect('/adminuet/generation/')
Exemple #6
0
def export_page(request):
    if checkInUrl(request, 'major') is False:
        listFunction = request.user.list_function()
        return HttpResponseRedirect(reverse(listFunction[0]))
    try:
        unitRole = request.user.unit_role
        nameFileExport = 'attachment; filename="{}.csv"'.format("ListMajor")
        if unitRole == 0:
            list_major = Majors.objects.all()
        else:
            list_major = Majors.objects.filter(unit=unitRole)
        rows = ([i+1, major.majorName, major.unit, major.majorDescription] for major, i in zip(list_major, range(list_major.count())))
        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = nameFileExport
        writer = csv.writer(response)
        rows, rowCopy = tee(rows)
        # Ghi log
        createLog(request, 'EXPORT - Ngành', str(len(list(rowCopy))) + ' bản ghi')
        writer.writerow(['stt', 'majorName', 'unit', 'majorDescription'])
        [writer.writerow([row[0], row[1], row[2], row[3]]) for row in rows]
        createLog(request, 'EXPORT - Ngành', '')
        return response
    except Exception as error:
        print(error)
        messages.error(request, "Thao tác thất bại.")
    return redirect('/adminuet/major/')
def transcript_file_upload(request):
    """
    Thực hiện upload file điểm csv
    """
    if checkInUrl(request, 'learningoutcome') is False:
        listFunction = request.user.list_function()
        return HttpResponseRedirect(reverse(listFunction[0]))
    group_id = request.POST['group_id']
    major_id = request.POST['major_id']
    semester_id = request.POST['semester_id']
    transcriptFile = request.FILES['transcriptFile']
    obj, created = DBModel.TranscriptFiles.objects.get_or_create(
        group_id=group_id,
        major_id=major_id,
        semester_id=semester_id,
        defaults={"extracted": False})
    if ~created:
        try:
            obj.extracted = False
            os.remove(obj.transcript.path)
        except Exception as e:
            print("error learningoutcomeview.py: ", e)

    obj.transcript.save(transcriptFile.name, transcriptFile)
    return obj
Exemple #8
0
def import_page(request):
    """Thực hiện nhập các chức năng từ file csv
    Hàm nhập từ file csv các trường stt, functionName vào model functions
    """
    if checkInUrl(request, 'function') is False:
        listFunction = request.user.list_function()
        return HttpResponseRedirect(reverse(listFunction[0]))
    template = 'adminuet/functionimport.html'
    if request.method == 'GET':
        return TemplateResponse(request, template)
    try:
        csv_file = request.FILES['document']
    except (Exception) as error:
        messages.error(request,'Lỗi: Chưa chọn tệp dữ liệu.')
        return TemplateResponse(request, template)
    if not csv_file.name.endswith('.csv'):
        messages.error(request,'Lỗi: Sai định dạng tệp. Vui lòng chọn lại tệp')
        return TemplateResponse(request, template)
    try:
        df = pd.read_csv(csv_file)
        create_from_DF(df=df, model=Functions, searching_cols=['functionName'])
    except (Exception) as error:
        print(error)
        messages.error(request,'Lỗi: Dữ liệu không đúng định dạng.')
        return TemplateResponse(request, template)
    return redirect('/adminuet/function/')
Exemple #9
0
def export_page(request):
    """
    Xuất danh sách năm học ra file csv
    Hàm xuất từ danh sách năm học ra file csv
    """
    if checkInUrl(request, 'year') is False:
        listFunction = request.user.list_function()
        return HttpResponseRedirect(reverse(listFunction[0]))
    try:
        nameFileExport = 'attachment; filename="{}.csv"'.format("ListYear")
        list_year = Years.objects.all()
        rows = ([i + 1, year.yearName, year.active]
                for year, i in zip(list_year, range(list_year.count())))
        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = nameFileExport
        writer = csv.writer(response)
        writer.writerow(['stt', 'yearName', 'active'])
        for row in rows:
            if str(row[2]).lower() == 'true': row[2] = 'Kích hoạt'
            elif str(row[2]).lower() == 'false': row[2] = 'Không kích hoạt'
            writer.writerow([row[0], row[1], row[2]])
        createLog(request, 'EXPORT - Năm học', '')
        return response
    except Exception as error:
        print(error)
        messages.error(request, "Thao tác thất bại.")
    return redirect('/adminuet/year/')
Exemple #10
0
def gpa_generation(request):
    if checkInUrl(request, 'statistical-gpa') is False:
        listFunction = request.user.list_function()
        return HttpResponseRedirect(reverse(listFunction[0]))
    if request.method == 'GET':
        unitRole = request.user.unit_role
        if unitRole == 0:
            units = Units.objects.all()
        elif unitRole is None:
            # units = Profiles.objects.filter(user=request.user).select_related("major__unit")
            unitIdQuery = Profiles.objects.filter(user=request.user)
            unitId = 1
            for i in unitIdQuery:
                unitId = i.major.unit.unitID
            units = Units.objects.filter(unitID=unitId).all()
        else:
            units = Units.objects.filter(pk=unitRole)

        majors = Majors.objects.all()
        generations = Generations.objects.all()
        context = {
            'units': units,
            'generations': generations,
            'majors': majors,
        }
        createLog(request, 'VIEW - Thống kê', 'GPA')
        return TemplateResponse(request,
                                'adminuet/gpageneration.html',
                                context=context)
def transcript_file_process(request):
    if checkInUrl(request, 'learningoutcome') is False:
        listFunction = request.user.list_function()
        return HttpResponseRedirect(reverse(listFunction[0]))
    units = DBModel.Units.objects.all()
    generations = DBModel.Generations.objects.all()
    student_groups = DBModel.StudentGroups.objects.all()
    majors = DBModel.Majors.objects.all()
    semesters = DBModel.Semesters.objects.all()
    transcript_files = DBModel.TranscriptFiles.objects.filter(extracted=False)

    context = {'units': units,
               'generations': generations,
               'student_groups': student_groups,
               'majors': majors,
               'semesters': semesters,
               'transcript_files': transcript_files,
               }

    if request.method == 'POST':
        if request.POST['action'] == 'upload':
            try:
                obj = transcript_file_upload(request)
                context['uploaded_file_url'] = obj.transcript.name
            except Exception as e:
                print(e)
                context['uploaded_file_url'] = "error"
        elif request.POST['action'] == 'extract':
            num_of_Grade = DBModel.Transcript.objects.filter().count()
            extract_success = extract_transcript_file(request)
            num_of_Grade_added = DBModel.Transcript.objects.filter().count() - num_of_Grade

            context['extract_result'] = "success, add {} score(s)".format(num_of_Grade_added) if extract_success else "failed"

    return TemplateResponse(request, 'adminuet/learningoutcomeimport.html', context=context)
Exemple #12
0
def course_avg_transcript(request):
    if checkInUrl(request, 'course-avg') is False:
        listFunction = request.user.list_function()
        return HttpResponseRedirect(reverse(listFunction[0]))
    if request.method == 'GET':
        unitRole = request.user.unit_role
        if unitRole == 0:
            units = Units.objects.all()
        elif unitRole is None:
            # units = Profiles.objects.filter(user=request.user).select_related("major__unit")
            unitIdQuery = Profiles.objects.filter(user=request.user)
            unitId = 1
            for i in unitIdQuery:
                unitId = i.major.unit.unitID
            units = Units.objects.filter(unitID=unitId).all()
        else:
            units = Units.objects.filter(pk=unitRole)

        context = {
            'units': units,
        }
        createLog(request, 'VIEW - Thống kê', 'Điểm trung bình')
        return TemplateResponse(request,
                                'adminuet/courseavg.html',
                                context=context)
Exemple #13
0
def distribute_transcript(request):
    if checkInUrl(request, 'statistical') is False:
        listFunction = request.user.list_function()
        return HttpResponseRedirect(reverse(listFunction[0]))
    curruntUser = request.user
    if request.method == 'GET':
        unitRole = request.user.unit_role
        if unitRole == 0:
            units = Units.objects.all()
        elif unitRole is None:
            # units = Profiles.objects.filter(user=request.user).select_related("major__unit")
            unitIdQuery = Profiles.objects.filter(user=request.user)
            unitId = 1
            for i in unitIdQuery:
                unitId = i.major.unit.unitID
            units = Units.objects.filter(unitID=unitId).all()
        else:
            units = Units.objects.filter(pk=unitRole)
        semesters = Semesters.objects.all()
        context = {
            'units': units,
            'semesters': semesters,
        }
        createLog(request, 'VIEW - Thống kê', 'Phổ điểm')
        return TemplateResponse(request,
                                'adminuet/statistical.html',
                                context=context)
Exemple #14
0
def gpa_student(request):
    if checkInUrl(request, 'statistical-gpa-student') is False:
        listFunction = request.user.list_function()
        return HttpResponseRedirect(reverse(listFunction[0]))
    if request.method == 'GET':
        unitRole = request.user.unit_role
        if unitRole == 0:
            profiles = Profiles.objects.all().select_related('user')
        elif unitRole is None:
            profiles = Profiles.objects.filter(
                user_id=request.user.id).select_related('user')
        else:
            profiles = Profiles.objects.filter(
                major__unit_id=unitRole).select_related('user')
        # else:
        #     roleId = request.user.role_id

        # print(profiles)
        semesters = Semesters.objects.all()
        dict_semesters = {}
        for semester in semesters:
            dict_semesters[semester.semesterID] = semester.semesterName
        context = {
            'profiles': profiles,
            'semesters': dumps(dict_semesters),
        }
        createLog(request, 'VIEW - Thống kê', 'GPA Sinh viên')
        return TemplateResponse(request,
                                'adminuet/gpastudent.html',
                                context=context)
Exemple #15
0
def import_page_new(request):
    """
    Thực hiện đọc file csv để nhập vào DB
    Thuộc tính của file csv stt, roleName, roleDescription, functions
    """
    if checkInUrl(request, 'role') is False:
        listFunction = request.user.list_function()
        return HttpResponseRedirect(reverse(listFunction[0]))
    template = 'adminuet/roleimport.html'
    if request.method == 'GET':
        return TemplateResponse(request, template)
    try:
        csv_file = request.FILES['document']
    except (Exception) as error:
        messages.error(request, 'Lỗi: Chưa chọn tệp dữ liệu.')
        return TemplateResponse(request, template)
    if not csv_file.name.endswith('.csv'):
        messages.error(request,
                       'Lỗi: Sai định dạng tệp. Vui lòng chọn lại tệp')
        return TemplateResponse(request, template)
    try:
        df = pd.read_csv(csv_file).set_index("stt")
        functions = Functions.objects.all()
        roles = Roles.objects.all()
        # List các functionName để so sanh sự tồn tại
        list_function = {}
        for function in functions:
            list_function[function.functionName] = function.functionID
        for i, row in df.iterrows():
            roleName = row['roleName']
            roleDescription = row['roleDescription']
            functionInput = row['funcitons']
            if roles.filter(roleName=roleName).exists():
                messages.error(request, 'Lỗi: Tên vai trò đã trùng.')
                return TemplateResponse(request, template)
            else:
                role = Roles(roleName=roleName,
                             roleDescription=roleDescription)
                role.save()
                roleIdNew = role.roleID
                listFunctionInFile = functionInput.split(", ")
                for itemFunction in listFunctionInFile:
                    # Nếu itemFunction không có trong list_function thì báo lỗi luôn
                    if not itemFunction in list_function:
                        messages.error(
                            request,
                            'Lỗi: Trong hệ thống không tồn tại chức năng ' +
                            itemFunction + '.')
                        return TemplateResponse(request, template)
                    else:
                        role_function = Role_Function(
                            role_id=roleIdNew,
                            function_id=list_function[itemFunction])
                        role_function.save()

    except (Exception) as error:
        print(error)
        messages.error(request, 'Lỗi: Dữ liệu không đúng định dạng.')
        return TemplateResponse(request, template)
    return redirect('/adminuet/role/')
Exemple #16
0
def year_getListForOffset(request, offset, limit):
    """
    Lấy danh sách các năm học từ vị trí và limit bản ghi
    Hàm trả về  các row trong year theo offset
    Trả về số lượng page mà chia theo limit
    """
    if checkInUrl(request, 'year') is False:
        listFunction = request.user.list_function()
        return HttpResponseRedirect(reverse(listFunction[0]))
    if request.method == 'GET':
        years = Years.objects.order_by('-yearID').all()
        yearList = years[offset:offset + limit]
        yearCount = years.count()
        yearSerializer = YearSerializer(yearList, many=True)
        page = math.ceil(yearCount / limit)
        for year in yearSerializer.data:
            if str(year['active']).lower() == 'true':
                year['active'] = 'Kích hoạt'
            else:
                year['active'] = 'Không kích hoạt'
        data = {
            'data': yearSerializer.data,
            'numberOfPage': page,
        }
        createLog(request, 'VIEW - Năm học', '')
        return Response(data)
Exemple #17
0
def semester_getListForOffset(request, offset, limit):
    """
    Hàm trả về  các row trong semester theo offset
    Trả về số lượng page mà chia theo limit
    """
    if checkInUrl(request, 'semester') is False:
        listFunction = request.user.list_function()
        return HttpResponseRedirect(reverse(listFunction[0]))
    if request.method == 'GET':
        semesters = Semesters.objects.order_by('semesterID').all()
        semesterList = semesters[offset:offset + limit].select_related('year')
        semesterCount = semesters.count()
        semesterSerializer = SemesterSerializer(semesterList, many=True)
        for sS, sL in zip(semesterSerializer.data, semesterList):
            sS['year'] = sL.year.yearName
            if sS['beginDay'] is None:
                sS['beginDay'] = "Chưa có dữ liệu"
            if sS['endDay'] is None:
                sS['endDay'] = "Chưa có dữ liệu"
        page = math.ceil(semesterCount / limit)
        data = {
            'data': semesterSerializer.data,
            'numberOfPage': page,
        }
        createLog(request, 'VIEW - Học kỳ', '')
        return Response(data)
def scoreforecast_generation_page(request):
    """
    Hiển thị trang tính dự báo điểm
    """
    context = None
    if checkInUrl(request, 'scoreforecast') is False:
        listFunction = request.user.list_function()
        return HttpResponseRedirect(reverse(listFunction[0]))
    if request.method == 'GET':
        unitRole = request.user.unit_role
        if unitRole == 0:
            generations = Generations.objects.order_by('unit').all()
            majors = Majors.objects.order_by('unit').all()
        else:
            generations = Generations.objects.filter(unit=unitRole).all()
            majors = Majors.objects.filter(
                unit=unitRole).order_by('unit').all()
        context = {
            'generations': generations,
            'majors': majors,
        }
        # createLog(request, 'VIEW - Tính dự đoán theo khóa', '')
        return TemplateResponse(request,
                                'adminuet/scoreforecastgeneration.html',
                                context=context)
Exemple #19
0
def major_getListForOffset(request, offset, limit):
    """
    Hàm trả về  các row trong major theo offset
    Trả về số lượng page mà chia theo limit
    """
    if checkInUrl(request, 'major') is False:
        listFunction = request.user.list_function()
        return HttpResponseRedirect(reverse(listFunction[0]))
    if request.method == 'GET':
        unitRole = request.user.unit_role
        if unitRole == 0:
            majors = Majors.objects.order_by('-majorID').all()
        else:
            majors = Majors.objects.order_by('-majorID').filter(unit=unitRole).all()
        majorList = majors[offset:offset + limit].select_related('unit')
        majorCount = majors.count()
        majorSerializer = MajorSerializer(majorList, many = True)
        page = math.ceil(majorCount/limit)
        for mS, mL in zip(majorSerializer.data, majorList):
            mS['unit'] = mL.unit.unitName
        data = {
            'data': majorSerializer.data,
            'numberOfPage': page,
        }
        # Ghi log
        createLog(request, 'VIEW - Ngành', '')
        return Response(data)
def import_page(request):
    """
    Thực hiện đọc file csv để thêm vào DB
    """
    if checkInUrl(request, 'major') is False:
        listFunction = request.user.list_function()
        return HttpResponseRedirect(reverse(listFunction[0]))
    template = 'adminuet/majorimport.html'
    units = Units.objects.all()
    context = {
        'units': units,
    }
    if request.method == 'GET':
        return TemplateResponse(request, template, context=context)
    if request.method == 'POST':
        unitInput = request.POST['unit']
        checkUnit = Units.objects.filter(unitID=unitInput)
        # Kiểm tra unitID client gửi lên có tồn tại không
        if checkUnit.exists():
            try:
                csv_file = request.FILES['document']
            except (Exception) as error:
                messages.error(request, 'Lỗi: Chưa chọn tệp dữ liệu.')
                context['lastUnitInput'] = unitInput
                return TemplateResponse(request, template, context=context)
            if not csv_file.name.endswith('.csv'):
                context['lastUnitInput'] = unitInput
                messages.error(
                    request, 'Lỗi: Sai định dạng tệp. Vui lòng chọn lại tệp')
                return TemplateResponse(request, template, context=context)
            try:
                df = pd.read_csv(csv_file)
                unitId = -1
                for u in checkUnit:
                    unitId = u.unitID
                count = 0
                # đọc từng dòng có trong file csv
                for i, row in df.iterrows():
                    majorName = row['Major']
                    majorDescription = row['Major_Description']
                    try:
                        toDatabase = Majors(unit_id=unitId,
                                            majorName=majorName,
                                            majorDescription=majorDescription)
                        toDatabase.save()
                        count += 1
                    except (Exception) as error:
                        print(error)
                # Ghi log
                createLog(request, 'IMPORT - Ngành', str(count) + ' bản ghi')
            except (Exception) as error:
                print(error)
                messages.error(request, 'Lỗi: Dữ liệu không đúng định dạng.')
                context['lastUnitInput'] = unitInput
                return TemplateResponse(request, template, context=context)
            return redirect('/adminuet/major/')
        else:
            messages.error(request, 'Lỗi: Đã xảy ra lỗi vui lòng thử lại.')
            context['lastUnitInput'] = unitInput
            return TemplateResponse(request, template, context=context)
def transcript_getListForOffset(request, offset, limit):
    """
    Hàm trả về  các row trong unit theo offset
    Trả về số lượng page mà chia theo limit
    """
    if checkInUrl(request, 'learningoutcome') is False:
        listFunction = request.user.list_function()
        return HttpResponseRedirect(reverse(listFunction[0]))
    if request.method == 'GET':
        unitRole = request.user.unit_role
        if unitRole == 0:
            transcripts = Transcript.objects.order_by('-transcriptID').all()
        else:
            transcripts = Transcript.objects.filter(
                student__major__unit=unitRole).order_by('-transcriptID').all()
        transcriptList = transcripts[offset:offset + limit].select_related(
            'student', 'course', 'semester')
        transcriptCount = transcripts.count()
        transcriptSerializer = TranscriptSerializer(transcriptList, many=True)
        for tl, ts in zip(transcriptList, transcriptSerializer.data):
            ts['studentCode'] = tl.student.MSSV
            ts['student'] = str(tl.student.lastName) + ' ' + str(
                tl.student.firstName)
            ts['course'] = tl.course.courseName
            ts['semester'] = tl.semester.semesterName
        page = math.ceil(transcriptCount / limit)
        data = {
            'data': transcriptSerializer.data,
            'numberOfPage': page,
        }
        createLog(request, 'VIEW - Kết quả học tập', '')
        return Response(data)
Exemple #22
0
def suggestioncourse_page(request):
    if checkInUrl(request, 'suggestioncourse') is False:
        listFunction = request.user.list_function()
        return HttpResponseRedirect(reverse(listFunction[0]))
    if request.method == 'GET':
        unitRole = request.user.unit_role
        profiles = []
        isStudent = False
        if unitRole == 0:
            profiles = Profiles.objects.all().values('profileID', 'firstName',
                                                     'lastName', 'MSSV')
        elif unitRole is None:
            profiles = Profiles.objects.filter(user_id=request.user.id).values(
                'profileID', 'firstName', 'lastName', 'MSSV')
            isStudent = True
        else:
            profiles = Profiles.objects.filter(major__unit_id=unitRole).values(
                'profileID', 'firstName', 'lastName', 'MSSV')
        context = {
            'profiles': profiles,
            'isStudent': isStudent,
        }
        createLog(request, 'VIEW - Gợi ý môn học', '')
    return TemplateResponse(request,
                            'adminuet/suggestioncourse.html',
                            context=context)
Exemple #23
0
def log_page(request, offset, limit):
    if checkInUrl(request, 'logs') is False:
        listFunction = request.user.list_function()
        return HttpResponseRedirect(reverse(listFunction[0]))
    if request.method == 'GET':
        logs = Logs.objects.order_by('-logID').all()
        logList = logs[offset:offset + limit].select_related('user')
        logCount = logs.count()
        logSerializer = LogSerializer(logList, many=True)
        for log, logS in zip(logList, logSerializer.data):
            logS['user'] = log.user.username
            timeInDB = log.time
            tz = pytz.timezone('Asia/Ho_Chi_Minh')
            timeInDB = timeInDB.replace(tzinfo=pytz.UTC)
            resultTime = timeInDB.astimezone(tz)
            logS['time'] = resultTime.strftime('%Y-%m-%d %H:%M:%S')
        page = math.ceil(logCount/limit)
        data = {
            'data': logSerializer.data,
            'numberOfPage': page,
        }
        hostname = socket.gethostname()
        ip_address = socket.gethostbyname(hostname)
        
        time = datetime.now(pytz.timezone('Asia/Ho_Chi_Minh')).strftime('%Y-%m-%d %H:%M:%S')
        currentUser = request.user
        record_logs(currentUser.id, ip_address, time, 'VIEW', 'Log page')
        return Response(data)
def export_page(request):
    """
    Thực hiện xuất file các môn học
    """
    if checkInUrl(request, 'course') is False:
        listFunction = request.user.list_function()
        return HttpResponseRedirect(reverse(listFunction[0]))
    nameFileExport = 'attachment; filename="{}.csv"'.format("ListCourse")
    unitRole = request.user.unit_role
    if unitRole == 0:
        list_course = Courses.objects.all().select_related('unit')
    else:
        list_course = Courses.objects.filter(
            unit=unitRole).all().select_related('unit')
    rows = ([
        i + 1, course.courseCode, course.courseName, course.unit.unitName,
        course.credit
    ] for course, i in zip(list_course, range(list_course.count())))

    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = nameFileExport
    response.write(u'\ufeff'.encode('utf8'))
    writer = csv.writer(response)
    writer.writerow(['stt', 'courseCode', 'courseName', 'unit', 'credit'])

    for r in rows:
        writer.writerow([r[0], r[1], r[2], r[3], r[4]])
    createLog(request, 'EXPORT - Môn học', '')
    return response
Exemple #25
0
def generation_getListForOffset(request, offset, limit):
    """Lấy danh sách các khóa từ vị trí offset limit số bản ghi
    Hàm trả về  các row trong unit theo offset
    Trả về số lượng page mà chia theo limit
    """
    if checkInUrl(request, 'generation') is False:
        listFunction = request.user.list_function()
        return HttpResponseRedirect(reverse(listFunction[0]))
    if request.method == 'GET':
        unitRole = request.user.unit_role
        # Rule admin
        if unitRole == 0:
            generations = Generations.objects.order_by('-generationID').all()
        else:  # Rule quản trị cấp trường
            generations = Generations.objects.order_by('-generationID').filter(
                unit=unitRole).all()
        generationList = generations[offset:offset + limit].select_related(
            'beginningYear', 'unit')
        generationCount = generations.count()
        generationSerializer = GenerationSerializer(generationList, many=True)
        for p, row in zip(generationList, generationSerializer.data):
            row['beginningYear'] = p.beginningYear.yearName
            row['unit'] = p.unit.unitName
        page = math.ceil(generationCount / limit)
        data = {
            'data': generationSerializer.data,
            'numberOfPage': page,
        }
        createLog(request, 'VIEW - Khóa', '')
        return Response(data)
def course_getListForOffset(request, offset, limit):
    """
    Lấy danh sách các môn học có số lượng và từ vị trí offset
    Phụ thuộc vào vai trò
    """
    if checkInUrl(request, 'course') is False:
        listFunction = request.user.list_function()
        return HttpResponseRedirect(reverse(listFunction[0]))
    if request.method == 'GET':
        unitRole = request.user.unit_role
        # Rule admin
        if unitRole == 0:
            courses = Courses.objects.order_by('-courseID').all()
        else:  # Quản trị cấp trường
            courses = Courses.objects.order_by('-courseID').filter(
                unit=unitRole).all()
        courseList = courses[offset:offset + limit].select_related('unit')
        courseCount = courses.count()
        courseSerializer = CoursesSerializer(courseList, many=True)
        page = math.ceil(courseCount / limit)
        for cS, cL in zip(courseSerializer.data, courseList):
            cS['unit'] = cL.unit.unitName
        data = {
            'data': courseSerializer.data,
            'numberOfPage': page,
        }
        createLog(request, 'VIEW - Môn học', '')
        return Response(data)
Exemple #27
0
def export_page(request):
    """
    Hàm xuất từ danh sách trường ra file csv
    """
    if checkInUrl(request, 'trainingframework') is False:
        listFunction = request.user.list_function()
        return HttpResponseRedirect(reverse(listFunction[0]))
    try:
        unitRole = request.user.unit_role
        nameFileExport = 'attachment; filename="{}.csv"'.format(
            "ListTrainingframework")
        if unitRole == 0:
            list_majorcourse = Major_Course.objects.all()
        else:
            list_majorcourse = Major_Course.objects.filter(
                major__unit=unitRole).all()
        rows = ([
            i + 1, majorcourse.course, majorcourse.major,
            majorcourse.semesterRecommended
        ] for majorcourse, i in zip(list_majorcourse,
                                    range(list_majorcourse.count())))
        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = nameFileExport
        writer = csv.writer(response)
        writer.writerow(['stt', 'course', 'major', 'semesterRecommended'])
        for row in rows:
            writer.writerow([row[0], row[1], row[2], row[3]])
        createLog(request, 'EXPORT - Khung đào tạo', '')
        return response
    except (Exception) as error:
        print(error)
    return redirect('/adminuet/trainingframework/')
Exemple #28
0
def export_page(request):
    """
    xuất danh sách các role ra file csv
    Thuộc tính của file csv: stt, roleName, roleDescription
    """
    if checkInUrl(request, 'role') is False:
        listFunction = request.user.list_function()
        return HttpResponseRedirect(reverse(listFunction[0]))
    try:
        nameFileExport = 'attachment; filename="{}.csv"'.format("ListRole")
        list_role = Roles.objects.all()
        rows = ([i + 1, role.roleName, role.roleDescription]
                for role, i in zip(list_role, range(list_role.count())))
        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = nameFileExport
        response.write(u'\ufeff'.encode('utf8'))
        writer = csv.writer(response)
        writer.writerow(['stt', 'roleName', 'roleDescription'])
        [writer.writerow([row[0], row[1], row[2]]) for row in rows]
        createLog(request, 'EXPORT - Vai trò', '')
        return response
    except (Exception) as error:
        print(error)
        messages.error(request, "Thao tác thất bại.")
    return redirect('/adminuet/role/')
Exemple #29
0
def role_getListForOffset(request, offset, limit):
    """
    Hàm trả về  các row trong role theo offset
    Trả về số lượng page mà chia theo limit
    """
    if checkInUrl(request, 'role') is False:
        listFunction = request.user.list_function()
        return HttpResponseRedirect(reverse(listFunction[0]))
    if request.method == 'GET':
        role_functions = Role_Function.objects.order_by(
            '-ID').all()[offset:offset + limit].select_related(
                'function', 'role')
        roleFunctionSerializer = RoleFunctionSerializer(role_functions,
                                                        many=True)
        roles = Roles.objects.order_by('-roleID').all()
        roleResult = roles[offset:offset + limit]

        page = math.ceil(roles.count() / limit)
        roleSerializer = RoleSerializer(roleResult, many=True)
        data = {
            'data': roleSerializer.data,
            'numberOfPage': page,
        }
        createLog(request, 'VIEW - Vai trò', '')
        return Response(data)
def export_page(request):
    """
    Xuất danh sách các trường ra file csv
    Hàm xuất từ danh sách trường ra file csv
    """
    if checkInUrl(request, 'unit') is False:
        listFunction = request.user.list_function()
        return HttpResponseRedirect(reverse(listFunction[0]))
    try:
        nameFileExport = 'attachment; filename="{}.csv"'.format("ListUnit")
        list_unit = Units.objects.all()
        rows = ([i+1, unit.unitName, unit.unitDescription] for unit, i in zip(list_unit, range(list_unit.count())))
        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = nameFileExport
        writer = csv.writer(response)
        rows, rowCopy = tee(rows)
        # Ghi log
        createLog(request, 'EXPORT - Trường', str(len(list(rowCopy))) + ' bản ghi')
        writer.writerow(['stt', 'unitName', 'unitDescription'])
        [writer.writerow([row[0], row[1], row[2]]) for row in rows]
        createLog(request, 'EXPORT - Trường', '')
        return response
    except (Exception) as error:
        print(error)
        messages.error(request, "Thao tác thất bại.")
    return redirect('/adminuet/unit/')