Beispiel #1
0
def index(request):
    if request.user.is_authenticated:
        Venue_list = list(Venue.objects.values())
        venue_details = []
        rownumber = 1
        for ven in Venue_list:
            ven['row'] = rownumber
            venType = Functions.getVenueName(ven['type'],
                                             Functions.getVenueTypes())
            if ven['type'] == 0:
                ven['type'] = '<label class="badge badge-danger">' + venType + '</label>'
            elif ven['type'] == 1:
                ven['type'] = '<label class="badge badge-success">' + venType + '</label>'
            elif ven['type'] == 2:
                ven['type'] = '<label class="badge badge-warning">' + venType + '</label>'
            elif ven['type'] == 3:
                ven['type'] = '<label class="badge badge-info">' + venType + '</label>'

            venue_details.append(ven)
            ven['row']
            rownumber += 1

        context = {
            'venue_list': venue_details,
            'idnum': 0,
            'pagedata': {
                'pageicon': 'fireplace-off',
                'pagetitle': 'Venues Management',
            }
        }
        return render(request, 'admin/venues/index.html', context)
    else:
        return redirect('../login')
Beispiel #2
0
def index(request):
    if request.user.is_authenticated:
        reg_list = list(Enrolment.objects.values())
        reg_details = []
        rownumber = 1
        for reg in reg_list:
            reg['row'] = rownumber
            reg['course_code'] = Functions.getSingleValueByCode(Course, reg['course_code_id'])
            reg['department'] = Functions.getSingleValueByCode(Department, reg['department_id'])
            reg['semesterType'] = Functions.getSemesterName(reg['semesterType'])
            reg_details.append(reg)
            rownumber += 1


        context = {
            'reg_details': reg_details,
            'idnum': 0,
            'pagedata':{
                'pageicon':'table-row-plus-before',
                'pagetitle':'Student Enrolments',
            }
        }
        return render(request, 'admin/registration/index.html', context)
    else:
        return redirect('../login')
Beispiel #3
0
def index(request):
    if request.user.is_authenticated:
        Lecturers_list = list(Lecturers.objects.values())
        lec_details = []
        rownumber = 1
        for lec_row in Lecturers_list:
            lec_row['row'] = rownumber
            lec_row['facultyLec'] = Functions.getSingleValueByCode(
                Faculty, str(lec_row['facultyLec_id']))
            lec_row['departmentLec'] = Functions.getSingleValueByCode(
                Department, str(lec_row['departmentLec_id']))
            lec_row['cousesTaken'] = Functions.getCourseTakenCount(
                Course, str(lec_row['code']))
            lec_row['priorityNumber'] = lec_row[
                'priorityNumber_id']  #staffTypes.objects.get(id=lec_row['priorityNumber_id']).type
            lec_details.append(lec_row)
            rownumber += 1

        context = {
            'lecturers': Lecturers_list,
            'maximumpriority': Functions.getMaxPriority() - 1,
            'pagedata': {
                'pageicon': 'teach',
                'pagetitle': 'Lecturers Management',
            }
        }
        return render(request, 'admin/lecturer/index.html', context)
    else:
        return redirect('../login')
Beispiel #4
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        newid = Functions.getNewId(Enrolment, 'ENR', "{:07}")
        self.fields["code"].initial = newid

        SESSION = Functions.SessionList()
        self.fields["session"] = forms.ChoiceField(
            choices=SESSION,
            required=False,
            widget=forms.Select(attrs={'class': 'form-control p-input'}))

        SEMESTERNAME = Functions.getSemesterAlias()
        self.fields["semesterName"] = forms.ChoiceField(
            label='Semester Name',
            choices=SEMESTERNAME,
            required=False,
            widget=forms.Select(attrs={'class': 'form-control p-input'}))

        SEMESTERTYPE = Functions.getSemestersList()
        self.fields["semesterType"] = forms.ChoiceField(
            label='Semester Type',
            choices=SEMESTERTYPE,
            required=False,
            widget=forms.Select(attrs={'class': 'form-control p-input'}))

        LEVEL = Functions.getStudentLevels()
        self.fields["level"] = forms.ChoiceField(
            choices=LEVEL,
            required=False,
            widget=forms.Select(attrs={'class': 'form-control p-input'}))
Beispiel #5
0
def index(request):
    if request.user.is_authenticated:
        course_list = list(Course.objects.values())

        course_details = []
        rownumber = 1

        for cos_row in course_list:
            cos_row['row'] = rownumber
            # print(cos_row['officer'])
            cos_row['semester'] = Functions.getSemesterName(
                int(cos_row['semester']))
            cos_row['departments'] = len(
                cos_row['departments']
            )  #Functions.StyleList(Functions, Department, cos_row['departments'])
            cos_row['lecturers'] = Functions.StyleList(Functions, Lecturers,
                                                       cos_row['lecturers'])
            course_details.append(cos_row)
            rownumber += 1

        context = {
            'courses_list': course_details,
            'pagedata': {
                'pageicon': 'text-subject',
                'pagetitle': 'Courses Management',
            }
        }
        return render(request, 'admin/courses/index.html', context)
    else:
        return redirect('../login')
Beispiel #6
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        newid = Functions.getNewId(Lecturers, 'LEC', "{:04}")
        self.fields["code"].initial = newid

        PRIORITY = []
        for x in range(1, Functions.getMaxPriority()):
            PRIORITY.append((x, x))
        # self.fields["priorityNumber"] = forms.ChoiceField(label='Priority Number', choices=PRIORITY, required=True, widget=forms.Select(attrs={'class':'form-control p-input'}))
        self.fields["facultyLec"].queryset = Faculty.objects.filter()
        self.fields["departmentLec"].queryset = Department.objects.filter()
Beispiel #7
0
def index(request):
    if request.user.is_authenticated:
        faculty_list = list(Faculty.objects.values())

        fac_details = []
        rownumber = 1

        for fac_row in faculty_list:
            fac_row['row'] = rownumber
            print(fac_row['officer'])
            fac_row['officer'] = fac_row['officer']#Functions.getSingleValueByCode(Lecturers, str(fac_row['officer']))
            fac_row['totaldpt'] = Functions.getTotalDptInFac(Department, str(fac_row['code']))
            fac_details.append(fac_row)
            rownumber += 1

        context = {
            'faculty_list': fac_details,
            'pagedata':{
                'pageicon':'domain',
                'pagetitle':'Faculties Management',
            }
        }
        return render(request, 'admin/faculty/index.html', context)
    else:
        return redirect('../login')
Beispiel #8
0
def mainRountingSystem(request):
    if request.user.is_authenticated:
        source =request.GET.get("source", None)
        value = (request.GET.get("value", None)).split(",")
        target = request.GET.get("target", None)
        type = request.GET.get("type", None)
        if source != None:
            typeInpu = ''
            if int(type) == 0:
                typeInpu = 'multiple="multiple"'

            listOutput = '<select name="'+target+'" class="form-control p-input" '+typeInpu+' id="id_'+target+'">'

            for code in value:
                CHOICES = []
                if source == 'faculty':
                    CHOICES = Department.objects.filter(faculty=code).values("code","name")
                elif source == 'department':
                    # FURTHER TO FILTER FOR LECTURERS WITH LESS THAN MAXIMUM COURSES
                    OPTIONS = Lecturers.objects.filter(departmentLec=code).values("code","name","priorityNumber")
                    CHOICES = Functions.getLectConfirm(OPTIONS, Course)

                for option in CHOICES:
                    listOutput += '<option value="'+option['code']+'">'+option['name']+'</option>'

            listOutput += '</select>'
            return HttpResponse(listOutput)


    else:
        return redirect('../login')
Beispiel #9
0
def newcoursesedit(request):
    if request.user.is_authenticated:
        id = request.GET.get("id", None)
        if id != None:
            instance = Course.objects.get(id=id)
            form = newCourseForm(instance=instance)
            context = {
                'form': form,
                'submiturl': 'updatecourses',
                'coursesForm': True,
                'semesterRequire': not (Functions.getSemesterReq()),
                'modal': {
                    'modalicon': 'text-subject',
                    'title': 'Update Course',
                    'button': 'Update Course',
                    'style': '',
                }
            }
            return render(request,
                          'admin/includes/modalcontents/newfaculty.html',
                          context)

        #deleting record by id
        id = request.GET.get("delete", None)
        if id != None:
            instance = Course.objects.get(id=id)
            instance.delete()
            result = '<div class="alert alert-success col-12" role="alert"><i class="mdi mdi-checkbox-marked-circle-outline"></i> Course deleted successfully!</div>'
            return HttpResponse(result)

    else:
        return redirect('../login')
Beispiel #10
0
def index(request):
    if request.user.is_authenticated:
        department_list = list(Department.objects.values())

        dpt_details = []
        rownumber = 1
        for dpt_row in department_list:
            dpt_row['row'] = rownumber
            dpt_row['facutly_name'] = Functions.getSingleValueByCode(
                Faculty, str(dpt_row['faculty_id']))
            dpt_row[
                'officer'] = '-'  #Functions.getSingleValueByCode(Faculty, str(dpt_row['officer']))
            dpt_details.append(dpt_row)
            rownumber += 1

        context = {
            'department_list': dpt_details,
            'idnum': 0,
            'pagedata': {
                'pageicon': 'school',
                'pagetitle': 'Departments Management',
            }
        }
        return render(request, 'admin/department/index.html', context)
    else:
        return redirect('../login')
Beispiel #11
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        DAYS = Functions.getDaysAvailable()
        self.fields["lectureday"] = forms.ChoiceField(choices=DAYS, required=True, widget=forms.Select(attrs={'class':'form-control p-input'}))

        VENUES = getVenueList()
        self.fields["venue"] = forms.ChoiceField(choices=VENUES, required=True, widget=forms.Select(attrs={'class':'form-control p-input'}))
Beispiel #12
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        newid = Functions.getNewId(Department, 'DPT', "{:03}")
        self.fields["code"].initial = newid

        CHOICES = Functions.getOfficersList()
        self.fields["officer"] = forms.ChoiceField(
            choices=CHOICES,
            required=False,
            widget=forms.Select(attrs={
                'data-live-search': 'true',
                'class': 'form-control p-input'
            }))

        self.fields["faculty"].queryset = Faculty.objects.filter()
Beispiel #13
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.fields['image'].widget.attrs['data-default-file'] = ''
        self.fields['image'].widget.attrs['class'] = 'dropify'

        newid = Functions.getNewId(Faculty, 'FAC', "{:02}")
        self.fields["code"].initial = newid

        CHOICES = Functions.getOfficersList()
        self.fields["officer"] = forms.ChoiceField(
            choices=CHOICES,
            required=False,
            widget=forms.Select(attrs={
                'data-live-search': 'true',
                'class': 'form-control p-input'
            }))
Beispiel #14
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.fields['code'].widget.attrs['data-default-file'] = ''
        self.fields['code'].widget.attrs['class'] = 'dropify'

        SESSION = Functions.SessionList()
        self.fields["session"] = forms.ChoiceField(
            label='Session',
            choices=SESSION,
            required=False,
            widget=forms.Select(attrs={'class': 'form-control p-input'}))

        SEMESTERTYPE = Functions.getSemestersList()
        self.fields["semesterType"] = forms.ChoiceField(
            label='Semester Type',
            choices=SEMESTERTYPE,
            required=False,
            widget=forms.Select(attrs={'class': 'form-control p-input'}))
Beispiel #15
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        SUBJECTTYPE = Functions.subjectType()
        self.fields["subjecttype"] = forms.ChoiceField(
            label='Subject Type',
            choices=SUBJECTTYPE,
            required=True,
            widget=forms.Select(attrs={'class': 'form-control p-input'}))

        SEMESTER = Functions.getSemestersList()
        self.fields["semester"] = forms.ChoiceField(
            label='Semester',
            choices=SEMESTER,
            required=Functions.getSemesterReq(),
            widget=forms.Select(attrs={'class': 'form-control p-input'}))

        DEPARTMENTS = Functions.getDepartmentList()
        self.fields["departments"] = forms.MultipleChoiceField(
            label='Department(s)',
            choices=DEPARTMENTS,
            required=True,
            widget=forms.SelectMultiple(
                attrs={
                    'class': 'form-control p-input populate-drop',
                    'singular': '0',
                    'data-source': 'department',
                    'data-link': 'lecturers',
                    'data-live-search': 'true',
                }))

        LECTURERS = Functions.getLecturerList(
        )  #Functions.getLectConfirm(Functions.getLecturerList(), Course)
        self.fields["lecturers"] = forms.MultipleChoiceField(
            label='Lecturer(s)',
            choices=LECTURERS,
            required=False,
            widget=forms.SelectMultiple(attrs={
                'class': 'form-control p-input',
                'data-live-search': 'true'
            }))
Beispiel #16
0
def manualscheduler(request):

    schedulerid = request.GET.get("scheduler", None)
    studentgroupid = request.GET.get("groupid", None)
    studentgroup = request.GET.get("studentgroup", None)
    print(schedulerid, ' - ', studentgroup)
    if schedulerid != None and studentgroup != None:
        instance = TablesGenerated.objects.get(groupid=studentgroupid)
        manualschedulerForm = manualSchedulerForm(instance=instance)
        result = '<div class="alert alert-danger col-12" role="alert" style="margin-bottom: 0;"><i class="mdi mdi-checkbox-marked-circle-outline"></i> Invalid request, please reload and try again!</div>'
        courseData = getCourseDataScheduler(studentgroupid)
        context = {
            'coursedata':
            courseData,
            'remarks':
            '',
            'generationForm_1':
            True,
            'generationForm':
            'True',
            'backtablescheduler':
            schedulerid,
            'backtablestudents':
            studentgroup,
            'timetabletitle':
            studentgroupid,
            'semesterRequire':
            Functions.getSemesterReq(),
            'manualschedulerForm':
            manualschedulerForm,
            'matchesSugestion':
            ManualScheduler.getAvailableMatches(schedulerid, studentgroupid,
                                                instance.venue),
            'pagedata': {
                'pageicon': 'timetable',
                # 'pagetitle': studentgroup,
            },
            'modal': {
                'modalicon': 'timetable',
                'title': 'TIMETABLE: ',  #+studentgroup,
                'button': 'Create Scheduler',
                'size': 'modal-lg'
            }
        }
        return render(request, 'admin/generator/manualscheduler.html', context)
    else:
        result = '<div class="alert alert-danger col-12" role="alert" style="margin-bottom: 0;"><i class="mdi mdi-checkbox-marked-circle-outline"></i> Invalid request, make sure Course has been scheduled and try again!</div>'
        return HttpResponse(result)
Beispiel #17
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        newid =  Functions.getNewId(TableRegister, 'TBL', "{:07}")
        self.fields["code"].initial = newid

        SESSION = Functions.SessionList()
        self.fields["session"] = forms.ChoiceField(initial=Functions.getSettingsData('session'), choices=SESSION, required=True, widget=forms.Select(attrs={'class':'form-control p-input'}))

        SEMESTERNAME = Functions.getSemesterAlias()
        self.fields["semestername"] = forms.ChoiceField(label='Semester', initial=Functions.getSettingsData('semname'), choices=SEMESTERNAME, required=not(Functions.getSemesterReq()), widget=forms.Select(attrs={'class':'form-control p-input'}))

        SEMESTERTYPE = Functions.getSemestersList()
        self.fields["semestertype"] = forms.ChoiceField(label='Semester', initial=Functions.getSettingsData('semtype'), choices=SEMESTERTYPE, required=Functions.getSemesterReq(), widget=forms.Select(attrs={'class':'form-control p-input'}))
Beispiel #18
0
def index(request):
    if request.user.is_authenticated:
        form = AppSettingsForm(instance=appSettings.objects.get(id=1))
        appLecturer = list(staffTypes.objects.values())
        context = {
            'form': form,
            'appLecturer': appLecturer,
            'semesterRequire': Functions.getSemesterReq(),
            'pagedata': {
                'pageicon': 'settings-outline',
                'pagetitle': 'Other Settings',
            }
        }
        return render(request, 'admin/appsettings/index.html', context)
    else:
        return redirect('../login')
Beispiel #19
0
def openscheduler(request):
    if request.user.is_authenticated:
        id = request.GET.get("id", None)
        if id != None:
            instance = TableRegister.objects.get(code=id)
            form = generateForm(instance=instance)
            tableData = {
                'id': id,
                'gendate': getTableRegistry(id, 'gendate'),
                'semester': getTableRegistry(id, 'semestername'),
                'totalgen': getTableRegistry(id, 'totalgen'),
            }
            context = {
                'form': form,
                'tableData': tableData,
                'generationForm': True,
                'generationForm_1': True,
                'genFormDisplay': 'none',
                'genFormCardStyle': {
                    'modalbody': 'padding-bottom: 0;margin-bottom: -1px;',
                    'cardbody': 'padding-bottom: 0;',
                },
                'semesterRequire': not (Functions.getSemesterReq()),
                'submiturl': 'startgeneration',
                'modal': {
                    'modalicon': 'animation',
                    'title': 'Generate Timetable',
                    'button': 'Generate Timetables',
                }
            }

            return render(request,
                          'admin/includes/modalcontents/newfaculty.html',
                          context)

        #deleting record by id
        id = request.GET.get("delete", None)
        if id != None:
            instance = TableRegister.objects.get(code=id)
            instance.delete()
            result = '<div class="alert alert-success col-12" role="alert" style="margin-bottom: 0;"><i class="mdi mdi-checkbox-marked-circle-outline"></i> Scheduler: ' + str(
                instance) + ' deleted successfully!</div>'
            return HttpResponse(result)

    else:
        return redirect('../login')
Beispiel #20
0
def newRegistration(request):
    if request.user.is_authenticated:
        form = EnrolmentForm()
        context = {
            'form': form,
            'registrationForm': True,
            'semesterRequire': Functions.getSemesterReq(),
            'submiturl':'addRegistration',
            'modal':{
                'modalicon': 'table-row-plus-before',
                'title': 'New Course Registration',
                'button': 'Save Registration',
            }
        }
        return render(request, 'admin/includes/modalcontents/newfaculty.html', context)
    else:
        return redirect('../login')
Beispiel #21
0
def newcourses(request):
    if request.user.is_authenticated:
        form = newCourseForm()
        context = {
            'form': form,
            'coursesForm': True,
            'semesterRequire': not (Functions.getSemesterReq()),
            'submiturl': 'addcourses',
            'modal': {
                'modalicon': 'text-subject',
                'title': 'New Course',
                'button': 'Save Course',
            }
        }
        return render(request, 'admin/includes/modalcontents/newfaculty.html',
                      context)
    else:
        return redirect('../login')
Beispiel #22
0
def newgenerator(request):
    if request.user.is_authenticated:
        form = generateForm()
        context = {
            'form': form,
            'generationForm': True,
            'semesterRequire': not (Functions.getSemesterReq()),
            'genFormDisplay': '',
            'submiturl': 'addgenerator',
            'modal': {
                'modalicon': 'animation',
                'title': 'Create Scheduler',
                'button': 'Create Scheduler'
            }
        }
        return render(request, 'admin/includes/modalcontents/newfaculty.html',
                      context)
    else:
        return redirect('../login')
Beispiel #23
0
class newFacultyForm(forms.ModelForm):
    CHOICES = Functions.getOfficersList()
    officer = forms.ChoiceField(
        choices=CHOICES,
        required=False,
        widget=forms.Select(attrs={'class': 'form-control p-input'}))

    class Meta:
        model = Faculty
        fields = ["code", "name", "officer", "image"]
        labels = {
            'code': 'Faculty ID',
            'name': 'Faculty Name',
            'officer_list': 'Officer',
            'image': 'Display Image',
        }
        widgets = {
            'code':
            forms.TextInput(attrs={
                'class': 'form-control p-input',
                'readonly': ""
            }),
            'name':
            forms.TextInput(attrs={'class': 'form-control p-input'}),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.fields['image'].widget.attrs['data-default-file'] = ''
        self.fields['image'].widget.attrs['class'] = 'dropify'

        newid = Functions.getNewId(Faculty, 'FAC', "{:02}")
        self.fields["code"].initial = newid

        CHOICES = Functions.getOfficersList()
        self.fields["officer"] = forms.ChoiceField(
            choices=CHOICES,
            required=False,
            widget=forms.Select(attrs={
                'data-live-search': 'true',
                'class': 'form-control p-input'
            }))
Beispiel #24
0
def newLecturer(request):
    if request.user.is_authenticated:
        form = newLecturerForm()
        tabler = Functions.getWorkingDays()
        visitingCheck = UserConstraints.objects.get(id=1).visiting
        context = {
            'form': form,
            'visiting': visitingCheck,
            'lecturerForm': True,
            'Available': tabler,
            'Saturday': constraintsValues('AssignSaturdays'),
            'submiturl': 'addLecturer',
            'modal': {
                'modalicon': 'teach',
                'title': 'New Lecturer',
                'button': 'Save Lecturer',
            }
        }
        return render(request, 'admin/includes/modalcontents/newfaculty.html',
                      context)
    else:
        return redirect('../login')
Beispiel #25
0
def newLectureredit(request):
    if request.user.is_authenticated:
        id = request.GET.get("id", None)
        if id != None:
            instance = Lecturers.objects.get(id=id)
            form = newLecturerForm(instance=instance)
            tabler = Functions.getWorkingDays()
            visitingCheck = UserConstraints.objects.get(id=1).visiting
            context = {
                'form': form,
                'lecturerForm': True,
                'visiting': visitingCheck,
                'Saturday': constraintsValues('AssignSaturdays'),
                'Available': tabler,
                'submiturl': 'updateLecturer',
                'modal': {
                    'modalicon': 'teach',
                    'title': 'Update Lecturer',
                    'button': 'Update Lecturer',
                    'style': '',
                }
            }
            return render(request,
                          'admin/includes/modalcontents/newfaculty.html',
                          context)

        #deleting record by id
        id = request.GET.get("delete", None)
        if id != None:
            instance = Lecturers.objects.get(id=id)
            instance.delete()
            result = '<div class="alert alert-success col-12" role="alert"><i class="mdi mdi-checkbox-marked-circle-outline"></i> Lecturer: deleted successfully!</div>'
            return HttpResponse(result)

    else:
        return redirect('../login')
Beispiel #26
0
from django.db import models
from multiselectfield import MultiSelectField
from admin.models import Functions
# Create your models here.
LEVELS = Functions.getStudentLevels()
DAYS = Functions.getDaysAvailable()
FACULTIES = Functions.getFacultyList()
DEPARTMENTS = Functions.getDepartmentList()


class Venue(models.Model):

    code = models.CharField(max_length=10, unique=True)
    name = models.CharField(max_length=10, unique=True)
    capacity = models.IntegerField(default=50)
    type = models.IntegerField(default=0)
    reservedFaculty = MultiSelectField(choices=FACULTIES, max_length=2048)
    reservedDepartment = MultiSelectField(choices=DEPARTMENTS, max_length=2048)
    reservedLevel = MultiSelectField(choices=LEVELS, max_length=2048)
    reservedDays = MultiSelectField(choices=DAYS, max_length=2048)
Beispiel #27
0
from django.db import models
from multiselectfield import MultiSelectField
from admin.models import Functions

DEPARTMENTS = Functions.getDepartmentList()
LECTURERS = Functions.getLecturerList()


class Course(models.Model):

    code = models.CharField(max_length=15, unique=True)
    name = models.CharField(max_length=255)
    coursehourperweek = models.IntegerField(default=2)
    semester = models.IntegerField(default=0)
    subjecttype = models.IntegerField(default=0)
    departments = MultiSelectField(choices=DEPARTMENTS, max_length=2048)
    lecturers = MultiSelectField(choices=LECTURERS, max_length=2048)

    def __str__(self):
        return self.name

    def lecturer(self):
        return self.lecturers

    def contacthour(self):
        return self.coursehourperweek
Beispiel #28
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        newid = Functions.getNewId(Venue, 'VEN', "{:03}")
        self.fields["code"].initial = newid

        CAPACITY = Functions.getVenueTypes()
        self.fields["type"] = forms.ChoiceField(
            label='Type',
            choices=CAPACITY,
            required=False,
            widget=forms.Select(attrs={'class': 'form-control p-input'}))

        LEVELS = Functions.getStudentLevels()
        AVAILABLEDAYS = Functions.getDaysAvailable()
        FACULTIES = Functions.getFacultyList()
        DEPARTMENTS = Functions.getDepartmentList()

        self.fields["reservedDays"] = forms.MultipleChoiceField(
            label='Days',
            choices=AVAILABLEDAYS,
            widget=forms.SelectMultiple(
                attrs={
                    'class': 'selectpicker w-100',
                    'multiple': 'multiple',
                    'style': 'width:100%',
                }))

        self.fields["reservedLevel"] = forms.MultipleChoiceField(
            label='Levels',
            choices=LEVELS,
            widget=forms.SelectMultiple(
                attrs={
                    'class': 'selectpicker w-100',
                    'multiple': 'multiple',
                    'style': 'width:100%',
                }))

        self.fields["reservedFaculty"] = forms.MultipleChoiceField(
            label='Faculties',
            choices=FACULTIES,
            widget=forms.SelectMultiple(
                attrs={
                    'class': 'selectpicker w-100 populate-drop',
                    'multiple': 'multiple',
                    'data-live-search': 'true',
                    'style': 'width:100%',
                    'data-source': 'faculty',
                    'data-link': 'reservedDepartment',
                    'singular': '0',
                }))

        self.fields["reservedDepartment"] = forms.MultipleChoiceField(
            label='Departments',
            choices=DEPARTMENTS,
            widget=forms.SelectMultiple(
                attrs={
                    'class': 'selectpicker w-100',
                    'multiple': 'multiple',
                    'data-live-search': 'true',
                    'style': 'width:100%',
                }))
Beispiel #29
0
    def startgen(gendata, dbinstance):
        genStartat = datetime.datetime.now()
        print('START TIME: ', genStartat)
        result = '<div class="alert alert-success col-12" role="alert"><i class="mdi mdi-checkbox-marked-circle-outline"></i>  ' + str(
            gendata) + ' </div>'
        tableCode = dbinstance  #gendata['code']
        tableData = pd.DataFrame()
        message = ''

        # start registration data collection
        if gendata['semestername'] != '' and gendata['semestertype'] == '':
            tableData = pd.DataFrame(
                list(Enrolment.objects.values().filter(
                    session=gendata['session'],
                    semesterName=gendata['semestername']).order_by(
                        'course_code_id')))
        elif gendata['semestername'] == '' and int(
                gendata['semestertype']) > 0:
            tableData = pd.DataFrame(
                list(Enrolment.objects.values().filter(
                    session=gendata['session'],
                    semesterType=gendata['semestertype']).order_by(
                        'course_code_id')))
        # end registration data collection

        # check if there is registration
        if len(tableData) > 0:
            venuesDF = pd.DataFrame(list(Venue.objects.values()))
            # start data preparation
            df = pd.DataFrame()
            if gendata['semestername'] != '' and gendata['semestertype'] == '':
                df = tableData[[
                    'session', 'semesterName', 'semesterType',
                    'course_code_id', 'level', 'department_id'
                ]].groupby(['course_code_id']).apply(lambda x: x.tail(1))
                df['groupid'] = df['session'] + df['semesterName'] + df[
                    'course_code_id']

            elif gendata['semestername'] == '' and int(
                    gendata['semestertype']) > 0:
                df = tableData[[
                    'session', 'semesterType', 'course_code_id', 'level',
                    'department_id'
                ]].groupby(['course_code_id']).apply(lambda x: x.tail(1))
                df['groupid'] = df['session'] + df['semesterType'].astype(
                    str) + df['course_code_id']

            tableData['students_x'] = tableData[
                'department_id'] + '-' + tableData['level'].astype(
                    str) + '-' + tableData['semesterType'].astype(str)
            studentGroup = tableData.groupby('course_code_id')[
                'students_x'].agg(lambda x: x[x != 0].tolist()).reset_index()
            studentGroup['student'] = studentGroup['students_x'].apply(
                getUniquemembers)

            def getStudents(cousecode):
                return ",".join(
                    list(studentGroup.loc[studentGroup['course_code_id'] ==
                                          cousecode]['student'])[0])

            df['student'] = df['course_code_id'].apply(getStudents)
            df['totalenrol'] = list(
                tableData['course_code_id'].value_counts().sort_index())
            df['courseunit'] = df['course_code_id'].apply(courseunit)
            df['lecturers'] = df['course_code_id'].apply(getLecturer)
            df['lecpriority'] = df['lecturers'].apply(lecPriority)
            df['visiting'] = df['lecturers'].apply(visitingLecturer)
            df['lecavail'] = df['lecturers'].apply(getLecturerAvail)
            df['subjecttype'] = df['course_code_id'].apply(getSubjectType)
            df['lectureday'] = ''
            df['starttime'] = datetime.time(0, 0)
            df['endtime'] = datetime.time(0, 0)
            df['venue'] = ''
            df['status'] = False
            df['comment'] = 'Not Assigned'
            #

            df = df.sort_values(by=['lecpriority'], ascending=False)
            if constraints('visitingLecturer'):
                df = df.sort_values(by=['lecpriority', 'visiting'],
                                    ascending=[False, False])

            # # end data preparation

            # begin generation algorithm
            # print(df[['visiting', 'lecpriority']])
            # # .....NEXT IS HERE.....
            lineindex = 0
            scheduleRegistry = []
            for row in df.itertuples():
                assertPd = df
                student = row.student.split(",")
                lecturers = row.lecturers
                for pos, studentx in enumerate(student):
                    if not (row.groupid in scheduleRegistry):
                        print(str(lineindex), ' - ', row.groupid)
                        print('REGISTRY LENGTH: ', str(len(scheduleRegistry)))

                        venuedfs = df[df['venue'] != '']
                        approvedschedules = df[df['status'] == True]
                        lecturerFree = getLecturerFreePeriods(
                            df, row.lecavail, lecturers,
                            constraints('LecMaxClassPerDay'),
                            constraints('LecMinBtwClasses'))
                        # check when student is free in lecturer free time
                        studentNotFree = getStudentNotFreePeriods(
                            df, getStudentTime(), studentx,
                            constraints('StuMaxClassPerDay'),
                            constraints('StuMinBtwClasses'))
                        venueData = {
                            'VenueDB': venuesDF,
                            'lecturer': row.lecturers,
                            'student': studentx,
                            'size': row.totalenrol,
                            'dpt': row.department_id,
                            'fac': Functions.getDptFac(row.department_id),
                            'level': row.level,
                            'type': row.subjecttype,
                            'course': row.course_code_id,
                        }

                        schedule = evaluateSchedule(
                            venuedfs, approvedschedules, row.visiting,
                            lecturers, studentx, row.courseunit, lecturerFree,
                            studentNotFree, venueData, 0, [])

                        if len(df[(df['lectureday'] == schedule['day'])
                                  & (((df['starttime'] >= schedule['start']) &
                                      (df['starttime'] <= schedule['end']))
                                     | ((df['endtime'] >= schedule['start']) &
                                        (df['endtime'] >= schedule['end']))) &
                                  (df['student'].str.contains(studentx)
                                   == True)]) == 0:

                            df.at[row.Index, 'starttime'] = schedule['start']
                            df.at[row.Index, 'endtime'] = schedule['end']
                            df.at[row.Index, 'lectureday'] = schedule['day']
                            df.at[row.Index, 'status'] = schedule['status']
                            df.at[row.Index, 'venue'] = schedule['venue']
                            df.at[row.Index, 'comment'] = schedule['comment']
                            # print(datetime.datetime.now())
                            scheduleRegistry.append(row.groupid)
                            lineindex += 1

                    else:
                        break

            df_gen = df[[
                'groupid', 'course_code_id', 'lecturers', 'student',
                'totalenrol', 'lectureday', 'starttime', 'endtime', 'venue',
                'status', 'department_id', 'comment'
            ]]

            for schedule in df_gen.itertuples():
                # check if record exist

                venueinstance = None
                try:
                    venueinstance = Venue.objects.get(code=schedule.venue)
                except Venue.DoesNotExist:
                    venueinstance = None

                departmentinstance = None
                try:
                    departmentinstance = Department.objects.get(
                        code=schedule.department_id)
                except Department.DoesNotExist:
                    departmentinstance = None

                lecturerx = ''
                if len(schedule.lecturers) > 0 and schedule.lecturers[0] != '':
                    lecturerx = schedule.lecturers[0]

                courseinstance = Course.objects.get(
                    code=schedule.course_code_id)

                defaults = {
                    'totalenrol': schedule.totalenrol,
                    'starttime': schedule.starttime,
                    'endtime': schedule.endtime,
                    'lecturers': lecturerx,
                    'lectureday': schedule.lectureday,
                    'code': tableCode,
                    'venue': venueinstance,
                    'course': courseinstance,
                    'remarks': schedule.comment,
                    'status': schedule.status,
                    'students': schedule.student,
                    'department': departmentinstance,
                }
                try:
                    obj = TablesGenerated.objects.get(groupid=schedule.groupid)
                    for key, value in defaults.items():
                        setattr(obj, key, value)
                    obj.save()

                except TablesGenerated.DoesNotExist:
                    new_values = {'groupid': schedule.groupid}
                    new_values.update(defaults)
                    obj = TablesGenerated(**new_values)
                    obj.save()

            totaltable = len(df_gen)
            successSchedule = len(df_gen[df_gen['status'] == True])
            successVenue = 0  #len(df_gen[['venue']])
            print(
                'NO VENUE: ',
                str(
                    len(df_gen[[
                        'totalenrol', 'lectureday', 'starttime', 'endtime',
                        'venue', 'status', 'venue'
                    ]].loc[df_gen['venue'] == ''])))
            print(df_gen[[
                'totalenrol', 'lectureday', 'starttime', 'endtime', 'venue',
                'status', 'venue'
            ]].loc[df_gen['venue'].str.contains('V') == False])
            totalTimeSpentgen = timeDiff(datetime.datetime.now(),
                                         genStartat) * 60
            print('FINISHED TIME: ', datetime.datetime.now())
            print('TIME SPENT: ', totalTimeSpentgen, 'seconds')
            # print(df_gen)
            message = '<div class="alert alert-success col-12" role="alert" style="margin-bottom: 0;line-height: 1.2;font-size: 14px;"><i class="mdi mdi-checkbox-marked-circle-outline"></i> ' + str(
                successSchedule
            ) + ' out of ' + str(
                totaltable
            ) + ' courses have been successfully scheduled. ' + str(
                successVenue
            ) + ' have venues. Click view Tables to manage timetable!</div>'
        else:
            message = '<div class="alert alert-danger col-12" role="alert" style="margin-bottom: 0;line-height: 1.2;font-size: 14px;"><i class="mdi mdi-alert-outline" style="font-size: 34px;float: left;margin-right: 15px;margin-top: -10px;"></i> No registration data found for the selected session and semester, please register students for courses and try again!</div>'

        # print(str(tableData[0]['level']))
        return HttpResponse(message)
Beispiel #30
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        newid = Functions.getNewId(staffTypes, '', "{:01}")
        self.fields["type"].initial = newid