Example #1
0
    def expandCourse(idCourse, idTimePeriod):
        """
         Returns a list of dicts containig the keys: courseName, courseAbbreviation,
         courseCode. Where each one is a possible subgroup of the given course. It could
         be only the practical offers, only the offers given by one professor ...

        @param int idCourse : The database assossiated key to the wanted course
        @param int idTimePeriod : The idTimePeriod of the wanted subgroup's timePeriod.
        @return {} :
        @author
        """
        course = Course.pickById(idCourse)
        offers = Offer.find(course=course,
                            timePeriod=TimePeriod.pickById(idTimePeriod))
        subgroups = Offer.possibleNames(offers)
        finalList = []
        for subgroup in subgroups:
            subgroupDict = {}
            subgroupDict['courseName'] = course.name + subgroup['name']
            subgroupDict[
                'courseAbbreviation'] = course.abbreviation + subgroup['name']
            subgroupDict['courseCode'] = course.courseCode + subgroup['name']
            subgroupDict['idCourse'] = course.idCourse
            finalList.append(subgroupDict)
        return finalList
Example #2
0
def generateCourses(request):
    data = request.GET
    idCourses = json.loads(data['idCourses']) #Do something with this list
    idCourses = [int(idCourse) for idCourse in idCourses]
    if int(data['useProfessorsName']) == 1:
        useProfessorsName = True
    else:
        useProfessorsName = False
    if int(data['byOffer']) == 1:
        byOffer = 1
    elif int(data['byOffer']) == 2:
        byOffer = 2
    elif int(data['byOffer']) == 0:
        byOffer = 0
    idTimePeriod = int(data['idTimePeriod'])
    idFaculty = int(data['idFaculty'])
    assessmentNumber = int(data['assessmentNumber'])
    user= request.user
    user_name = request.user.username
    time = get_time()
    timePeriod = str(TimePeriod.pickById(idTimePeriod))
    courses = [str(Course.pickById(idCourse).courseCode) for idCourse in idCourses]
    cycle = Cycle.pickById(int(data['idCycle'])).name
    action = u"Usuário " + str(user_name) + u" gerou relatório: " \
    + u"{ Curso: " + cycle \
    + u"; Semestre: " + data['term'] \
    + u"; Matérias: " + str(courses) \
    + u"; Período: " + timePeriod \
    + u"; Avaliação: " + data['assessmentNumber'] + " }"
    report_generate_log = Log(user=user, action=action, time=time)
    report_generate_log.save()
    CourseReportGenerator(idTimePeriod, idCourses, useProfessorsName, byOffer, idFaculty, assessmentNumber)
    return HttpResponse('Relatórios Gerados')
Example #3
0
    def __init__(self, idTimePeriod,
        idCourses,
        useProfessorsName,
        byOffer,
        idFaculty,
        assessmentNumber):

        outputDirectory = settings.PASTA_RELATORIOS

        timePeriod = TimePeriod.pickById(idTimePeriod)
        faculty = Faculty.pickById(idFaculty)

        for idCourse in idCourses:
            course = Course.pickById(idCourse)
            
            courseReport = CourseReport(course, timePeriod, settings.TEMPLATE_RELATORIOS)
            courseReport.setReportInstructions(faculty, assessmentNumber, byOffer, useProfessorsName)
            courseReport.writeDocument(outputDirectory + "/" + str(idCourse))
            timePeriodStr = str(timePeriod.year)
            if timePeriod.length == 1:
                timePeriodStr += "s"
            elif timePeriod.length == 2:
                timePeriodStr += "q"
            else: raise TimePeriodError("Invalid timePeriod length")
            timePeriodStr += str(timePeriod.session)
            try:
                subprocess.check_call(['cp', outputDirectory + '/' + str(idCourse) + '/' + courseReport.generateTitle() + ".pdf", settings.PASTA_RELATORIOS_SEPARADO + timePeriodStr + '/'])  # Copia o relatorio para a pasta com os relatorios separados por semestres... por algum motivo
            except CalledProcessError:
                print 'Relatorio nao foi copiado para a disciplina ' + unicode(course)
Example #4
0
def possibleCodifications(request):
    data = request.GET
    opticalSheets = OpticalSheet.find(timePeriod = TimePeriod.pickById(data['idTimePeriod']))
    encodedOpticalSheets = [opticalSheet for opticalSheet in opticalSheets if opticalSheet.encodingName != None]
    opticalSheet_dict = []
    for opticalSheet in encodedOpticalSheets:
        opticalSheet_dict.append({'idOpticalSheet':opticalSheet.idOpticalSheet, 'encodingName':opticalSheet.encodingName})
    return HttpResponse(json.dumps(opticalSheet_dict))
Example #5
0
def offer_list_generate(request):
    if request.method  == 'POST':
        form = OfferListForm(request.POST)
        form.updateForm()
        if form.is_valid():
            timePeriod = TimePeriod.pickById(int(form.cleaned_data['dropDownTimePeriod']))
            cycleId = int(form.cleaned_data['dropDownCycle'])
            term = int(form.cleaned_data['dropDownTerm'])
            return createPDF(timePeriod, cycleId, term)
    else:
        return HttpResponseRedirect('/interface/offerList')
Example #6
0
def offer(request):
    if request.method  == 'POST':
        form = IndexForm(request.POST)
        form.updateForm()
        if form.is_valid():
            timePeriod = TimePeriod.pickById(form.cleaned_data['dropDownTimePeriod'])
            course = Course.pickById(form.cleaned_data['dropDownCourse'])
            offers = Offer.find(timePeriod=timePeriod, course=course)
            rendered_page = render(request, 'offer.html', {'offers': offers, 'timePeriod': timePeriod, 'course': course})
            return rendered_page
    else:
        return HttpResponseRedirect('/interface/')
Example #7
0
def offer_list_generate(request):
    if request.method == 'POST':
        form = OfferListForm(request.POST)
        form.updateForm()
        if form.is_valid():
            timePeriod = TimePeriod.pickById(
                int(form.cleaned_data['dropDownTimePeriod']))
            cycleId = int(form.cleaned_data['dropDownCycle'])
            term = int(form.cleaned_data['dropDownTerm'])
            return createPDF(timePeriod, cycleId, term)
    else:
        return HttpResponseRedirect('/interface/offerList')
Example #8
0
def deleteEncoding(request):
    data = request.GET
    opticalSheet = OpticalSheet.pickById(int(data['idOpticalSheet']))
    user= request.user
    user_name = request.user.username
    time = get_time()
    timePeriod = str(TimePeriod.pickById(int(data['idTimePeriod'])))
    action = u"Usuário " + str(user_name) + u" deletou codificação " + opticalSheet.encodingName \
    + u" { Periodo: " + timePeriod + " }"
    encoding_delete_log = Log(user=user, action=action, time=time)
    encoding_delete_log.save()
    opticalSheet.delete()
    return HttpResponseRedirect('/encoder/')
 def fillPossibleOffers(self, idCycle, term):
     cycle = Cycle.pickById(idCycle)
     cycle.completeMandatoryIdealTerms()
     cycle.completeElectiveIdealTerms()
     possibleCourses = []
     for term in cycle.mandatoryIdealTerms:
         for course in cycle.mandatoryIdealTerms[term]:
             possibleCourses.append(course)
     for term in cycle.electiveIdealTerms:
         for course in cycle.electiveIdealTerms[term]:
             possibleCourses.append(course)
     for idealTermCourse in possibleCourses:
         for offer in Offer.find(course = idealTermCourse.course, timePeriod = TimePeriod.pickById(self.idTimePeriod)):
             self.possibleOffers.append(offer)
Example #10
0
def offer_create(request, idTimePeriod, idCourse):
    timePeriod = TimePeriod.pickById(idTimePeriod)
    course = Course.pickById(idCourse)
    if request.method == 'POST':
        form = OfferForm(request.POST)
        form.updateForm()
        if form.is_valid():
            idProfessor = form.cleaned_data['dropDownProfessor']
            classNumber = form.cleaned_data['classNumber']
            practical = form.cleaned_data['dropDownTeoricaPratica']
            numberOfRegistrations = form.cleaned_data['numberOfRegistrations']
            schedulesIds = form.cleaned_data['listSchedules']
            schedules = [
                Schedule.pickById(schedule) for schedule in schedulesIds
            ]
            professor = Professor.pickById(idProfessor)
            practical = (practical == 1)
            offer = Offer(timePeriod, course, classNumber, practical,
                          professor)
            offer.setSchedules(schedules)
            offer.setNumberOfRegistrations(numberOfRegistrations)
            offer.store()
            user = request.user
            user_name = request.user.username
            time = get_time()
            schedules_string = '[ '
            for schedule in schedules:
                schedules_string += str(schedule).replace('ç', 'c') + " "
            schedules_string += ']'
            action = u"Usuário " + user_name + u" criou o oferecimento id: " + str(offer.idOffer) + " {" \
            + u" Código do Curso: " + str(course.courseCode) \
            + u"; Turma: T" + str(classNumber) \
            + u"; Professor: " + professor.name \
            + u"; Periodo: " + str(timePeriod) \
            + u"; Horários: " + schedules_string + " }"
            offer_create_log = Log(user=user, action=action, time=time)
            offer_create_log.save()
            return HttpResponseRedirect('/interface/offer/' +
                                        str(offer.idOffer))
    else:
        form = OfferForm()
        form.updateForm()
    rendered_page = render(request, 'offer_create.html', {
        'form': form,
        'timePeriod': timePeriod,
        'course': course
    })
    return rendered_page
def store(request):
    data = request.POST
    data = json.loads(data['json'])
    user= request.user
    user_name = request.user.username
    time = get_time()
    cycle_name = Cycle.pickById(int(data['idCycle'])).name
    timePeriod = str(TimePeriod.pickById(int(data['idTimePeriod'])))
    response = OpticalSheetController.storeOpticalSheet(data['idOpticalSheet'], data['surveyType'], data['idCycle'], data['term'], data['idTimePeriod'], data['fields'], data['surveys'], data['encoded'])
    action = u"Usuário " + str(user_name) + u" salvou idOpticalSheet " + str(data['idOpticalSheet']) \
    + u" { Periodo: " + timePeriod \
    + u"; Curso: " + cycle_name \
    + u"; Semestre: " + str(data['term']) + " }"
    opticalSheet_store_log = Log(user=user, action=action, time=time)
    opticalSheet_store_log.save()
    return HttpResponse(json.dumps(response))
    def __init__(self, idTimePeriod, idCycle, term):
        """
         Initialization method.

        @param int idTimPeriod : The database id of the timePeriod if this QualitativeQuestionnaire.
        @param int idCycle : The database id of the cycle if this QualitativeQuestionnaire.
        @param int term : The term this QualitativeQuestionnaire.
        @return  :
        @author
        """

        Printer.__init__(self)
        self.cycle = Cycle.pickById(idCycle)
        self.timePeriod = TimePeriod.pickById(idTimePeriod)
        self.term = term
        self.createName()
Example #13
0
    def __init__(self,idCycle, term, idTimePeriod):
        """
         Initialization method.

        @param int idTimPeriod : The database id of the timePeriod if this QualitativeQuestionnaire.
        @param int idCycle : The database id of the cycle if this QualitativeQuestionnaire.
        @param int term : The term this QualitativeQuestionnaire.
        @return  :
        @author
        """

        Printer.__init__(self)
        self.timePeriod = TimePeriod.pickById(idTimePeriod)
        self.cycle = Cycle.pickById(idCycle)
        self.term = term
        self.createName()
Example #14
0
    def getOffers(courseCode, idTimePeriod):
        """
         Returns the set of idOffers defined by this courseCode as is defined in expandCourse method.

        @param string courseCode : If it is a normal course this is not used, if this is a subgroup of a course, this courseCode is going to define the offers.Ex PTC3011(P)[ProfName] = only practical offers given by ProfName in course PTC3011.
        @param int idTimePeriod : The idTimePeriod of the wanted offer's timePeriod.
        @return  :
        @author
        """
        professor = None
        practical = None
        if courseCode.find('[') != -1:
            professorName = courseCode.rsplit('[')[1].rsplit(']')[0]
            professor = Professor.find(name_equal=professorName)[0]
            courseCode = courseCode.rsplit('[')[0] + courseCode.rsplit(']')[1]
        if courseCode.find('(') != -1:
            practical = courseCode.rsplit('(')[1].rsplit(')')[0]
            if practical == 'P':
                practical = True
            elif practical == 'T':
                practical = False
            else:
                raise ColumnsControllerError(
                    "The parameter given between the '()' must be equal to 'P' or 'T'."
                )
            courseCode = courseCode.rsplit('(')[0] + courseCode.rsplit(')')[1]

        course = Course.find(courseCode_equal=courseCode,
                             endDate_equal='0000-00-00')[0]
        timePeriod = TimePeriod.pickById(idTimePeriod)
        if professor and practical != None:
            offers = Offer.find(course=course,
                                practical=practical,
                                professor=professor,
                                timePeriod=timePeriod)
        elif professor:
            offers = Offer.find(course=course,
                                professor=professor,
                                timePeriod=timePeriod)
        elif practical != None:
            offers = Offer.find(course=course,
                                practical=practical,
                                timePeriod=timePeriod)
        else:
            offers = Offer.find(course=course, timePeriod=timePeriod)
        idOffers = [offer.idOffer for offer in offers]
        return idOffers
Example #15
0
    def findOpticalSheetByTimePeriod_Cycle_Term(idTimePeriod, idCycle, term):
        """
         Returns the getOpticalSheetData of the opticalSheet belonging to the given
         idTimePeriod, idCycle and term. If the number of opticalSheets found by those
         parameters is different than 1 the return is the number of opticalSheets found.

        @param int idTimePeriod : The database id of the timePeriod of the wanted opticalSheet.
        @param int idCycle : The database id of the cycle of the wanted opticalSheet.
        @param int term : The term of the wanted opticalSheet.
        @return [] :
        @author
        """
        opticalSheet = OpticalSheet.find(timePeriod = TimePeriod.pickById(idTimePeriod), cycles = [Cycle.pickById(idCycle)], term = term)
        if len(opticalSheet) != 1:
            return len(opticalSheet)
        opticalSheet = opticalSheet[0]
        return OpticalSheetController.getOpticalSheetData(opticalSheet)
Example #16
0
def offer(request):
    if request.method == 'POST':
        form = IndexForm(request.POST)
        form.updateForm()
        if form.is_valid():
            timePeriod = TimePeriod.pickById(
                form.cleaned_data['dropDownTimePeriod'])
            course = Course.pickById(form.cleaned_data['dropDownCourse'])
            offers = Offer.find(timePeriod=timePeriod, course=course)
            rendered_page = render(request, 'offer.html', {
                'offers': offers,
                'timePeriod': timePeriod,
                'course': course
            })
            return rendered_page
    else:
        return HttpResponseRedirect('/interface/')
Example #17
0
    def getOldOpticalSheets(idCycle):
        """
         Returns the a dict with the idOpticalSheet, the term and the TimePeriod string of the existing
         opticalSheets relatade to this cycle.

        @param Cycle cycle : The cycle related to the wanted opticalSheets
        @return  :
        @author
        """
        cursor = MySQLConnection()
        opticalSheets = cursor.execute('SELECT aggr_opticalSheetField.idOpticalSheet, rel_cycle_opticalSheet.term, aggr_offer.idTimePeriod FROM rel_cycle_opticalSheet JOIN aggr_opticalSheetField ON rel_cycle_opticalSheet.idOpticalSheet = aggr_opticalSheetField.idOpticalSheet JOIN aggr_offer ON aggr_offer.idOffer = aggr_opticalSheetField.idOffer WHERE rel_cycle_opticalSheet.idCycle = ' + str(idCycle) + ' GROUP BY aggr_opticalSheetField.idOpticalSheet ORDER BY aggr_offer.idTimePeriod DESC;')
        response = []
        for opticalSheet in opticalSheets:
            opticalSheetDict = {}
            opticalSheetDict['term'] = opticalSheet[1]
            opticalSheetDict['timePeriod'] = str(TimePeriod.pickById(opticalSheet[2]))
            opticalSheetDict['idOpticalSheet'] = opticalSheet[0]
            response.append(opticalSheetDict)
        return response
def store(request):
    data = request.POST
    data = json.loads(data['json'])
    user = request.user
    user_name = request.user.username
    time = get_time()
    cycle_name = Cycle.pickById(int(data['idCycle'])).name
    timePeriod = str(TimePeriod.pickById(int(data['idTimePeriod'])))
    response = OpticalSheetController.storeOpticalSheet(
        data['idOpticalSheet'], data['surveyType'], data['idCycle'],
        data['term'], data['idTimePeriod'], data['fields'], data['surveys'],
        data['encoded'])
    action = u"Usuário " + str(user_name) + u" salvou idOpticalSheet " + str(data['idOpticalSheet']) \
    + u" { Periodo: " + timePeriod \
    + u"; Curso: " + cycle_name \
    + u"; Semestre: " + str(data['term']) + " }"
    opticalSheet_store_log = Log(user=user, action=action, time=time)
    opticalSheet_store_log.save()
    return HttpResponse(json.dumps(response))
Example #19
0
def openSite(request):
    header = Header()
    header.setTermFunction('$("#file").show()')
    if request.method == 'POST':
        data = request.POST
        NoteReader.readNote(request.FILES['arq'].name, request.FILES['arq'].file.getvalue(),int(data['headerCycle']), int(data['headerTerm']), int(data['headerTimePeriod']), int(data['bSheet']), int(data['assessmentNumber']))
        user= request.user
        user_name = request.user.username
        time = get_time()
        cycle_name = Cycle.pickById(int(data['headerCycle'])).name
        timePeriod = str(TimePeriod.pickById(int(data['headerTimePeriod'])))
        b_sheet = "A" if int(data['bSheet']) == 0 else "B"
        action = u"Usuário " + str(user_name) + " inseriu datafile " + request.FILES['arq'].name \
        + u" { Curso: " + cycle_name \
        + u"; Semestre: " + data['headerTerm'] \
        + u"; Período: " + timePeriod \
        + u"; Folha(A ou B): " + b_sheet \
        + u"; Avaliação: " + data['assessmentNumber'] + " }"
        datafile_insert_log = Log(user=user, action=action, time=time)
        datafile_insert_log.save()
    return render_to_response('datafile.html',{'divs':header.getHtml()},context_instance=RequestContext(request))    
Example #20
0
def offer_create(request, idTimePeriod, idCourse):
    timePeriod = TimePeriod.pickById(idTimePeriod)
    course = Course.pickById(idCourse)
    if request.method  == 'POST':
        form = OfferForm(request.POST)
        form.updateForm()
        if form.is_valid():
            idProfessor = form.cleaned_data['dropDownProfessor']
            classNumber = form.cleaned_data['classNumber']
            practical = form.cleaned_data['dropDownTeoricaPratica']
            numberOfRegistrations = form.cleaned_data['numberOfRegistrations']
            schedulesIds = form.cleaned_data['listSchedules']
            schedules = [Schedule.pickById(schedule) for schedule in schedulesIds]
            professor = Professor.pickById(idProfessor)
            practical = (practical == 1)
            offer = Offer(timePeriod, course, classNumber, practical, professor)
            offer.setSchedules(schedules)
            offer.setNumberOfRegistrations(numberOfRegistrations)
            offer.store()
            user= request.user
            user_name = request.user.username
            time = get_time()
            schedules_string = '[ '
            for schedule in schedules:
                schedules_string += str(schedule).replace('ç','c') + " "
            schedules_string += ']'
            action = u"Usuário " + user_name + u" criou o oferecimento id: " + str(offer.idOffer) + " {" \
            + u" Código do Curso: " + str(course.courseCode) \
            + u"; Turma: T" + str(classNumber) \
            + u"; Professor: " + professor.name \
            + u"; Periodo: " + str(timePeriod) \
            + u"; Horários: " + schedules_string + " }"
            offer_create_log = Log(user=user, action=action, time=time)
            offer_create_log.save()
            return HttpResponseRedirect('/interface/offer/' + str(offer.idOffer))
    else:
        form = OfferForm()
        form.updateForm()
    rendered_page = render(request, 'offer_create.html', {'form': form, 'timePeriod': timePeriod, 'course': course})
    return rendered_page
    def expandCourse(idCourse, idTimePeriod):
        """
         Returns a list of dicts containig the keys: courseName, courseAbbreviation,
         courseCode. Where each one is a possible subgroup of the given course. It could
         be only the practical offers, only the offers given by one professor ...

        @param int idCourse : The database assossiated key to the wanted course
        @param int idTimePeriod : The idTimePeriod of the wanted subgroup's timePeriod.
        @return {} :
        @author
        """
        course = Course.pickById(idCourse)
        offers = Offer.find(course = course, timePeriod = TimePeriod.pickById(idTimePeriod))
        subgroups = Offer.possibleNames(offers)
        finalList = []
        for subgroup in subgroups:
            subgroupDict = {}
            subgroupDict['courseName'] = course.name + subgroup['name']
            subgroupDict['courseAbbreviation'] = course.abbreviation + subgroup['name']
            subgroupDict['courseCode'] = course.courseCode + subgroup['name']
            subgroupDict['idCourse'] = course.idCourse
            finalList.append(subgroupDict)
        return finalList
    def getOffers(courseCode, idTimePeriod):
        """
         Returns the set of idOffers defined by this courseCode as is defined in expandCourse method.

        @param string courseCode : If it is a normal course this is not used, if this is a subgroup of a course, this courseCode is going to define the offers.Ex PTC3011(P)[ProfName] = only practical offers given by ProfName in course PTC3011.
        @param int idTimePeriod : The idTimePeriod of the wanted offer's timePeriod.
        @return  :
        @author
        """
        professor = None
        practical = None
        if courseCode.find('[') != -1:
            professorName = courseCode.rsplit('[')[1].rsplit(']')[0]
            professor = Professor.find(name_equal = professorName)[0]
            courseCode = courseCode.rsplit('[')[0] + courseCode.rsplit(']')[1]
        if courseCode.find('(') != -1:
            practical = courseCode.rsplit('(')[1].rsplit(')')[0]
            if practical == 'P':
                practical = True
            elif practical == 'T':
                practical = False
            else:
                raise ColumnsControllerError("The parameter given between the '()' must be equal to 'P' or 'T'.")
            courseCode = courseCode.rsplit('(')[0] + courseCode.rsplit(')')[1]

        course = Course.find(courseCode_equal = courseCode, endDate_equal = '0000-00-00')[0]
        timePeriod = TimePeriod.pickById(idTimePeriod)
        if professor and practical != None:
            offers = Offer.find(course = course, practical = practical, professor = professor, timePeriod = timePeriod)
        elif professor:
            offers = Offer.find(course = course, professor = professor, timePeriod = timePeriod)
        elif practical != None:
            offers = Offer.find(course = course, practical = practical, timePeriod = timePeriod)
        else:
            offers = Offer.find(course = course, timePeriod = timePeriod)
        idOffers = [offer.idOffer for offer in offers]
        return idOffers
Example #23
0
def generateCourses(request):
    data = request.GET
    idCourses = json.loads(data['idCourses'])  #Do something with this list
    idCourses = [int(idCourse) for idCourse in idCourses]
    if int(data['useProfessorsName']) == 1:
        useProfessorsName = True
    else:
        useProfessorsName = False
    if int(data['byOffer']) == 1:
        byOffer = 1
    elif int(data['byOffer']) == 2:
        byOffer = 2
    elif int(data['byOffer']) == 0:
        byOffer = 0
    idTimePeriod = int(data['idTimePeriod'])
    idFaculty = int(data['idFaculty'])
    assessmentNumber = int(data['assessmentNumber'])
    user = request.user
    user_name = request.user.username
    time = get_time()
    timePeriod = str(TimePeriod.pickById(idTimePeriod))
    courses = [
        str(Course.pickById(idCourse).courseCode) for idCourse in idCourses
    ]
    cycle = Cycle.pickById(int(data['idCycle'])).name
    action = u"Usuário " + str(user_name) + u" gerou relatório: " \
    + u"{ Curso: " + cycle \
    + u"; Semestre: " + data['term'] \
    + u"; Matérias: " + str(courses) \
    + u"; Período: " + timePeriod \
    + u"; Avaliação: " + data['assessmentNumber'] + " }"
    report_generate_log = Log(user=user, action=action, time=time)
    report_generate_log.save()
    CourseReportGenerator(idTimePeriod, idCourses, useProfessorsName, byOffer,
                          idFaculty, assessmentNumber)
    return HttpResponse('Relatórios Gerados')
Example #24
0
 def settimeperiod(self, idtimeperiod):
     "Sets the timeperiod of this cycle by providing its id"
     self.timeperiod = idtimeperiod
     self.offerreader.timeperiod = TimePeriod.pickById(idtimeperiod)
Example #25
0
 def settimeperiod(self, idtimeperiod):
     "Sets the timeperiod of this cycle by providing its id"
     self.timeperiod = idtimeperiod
     self.offerreader.timeperiod = TimePeriod.pickById(idtimeperiod)
Example #26
0
    def storeOpticalSheet(idOpticalSheet, surveyType, idCycle, term, idTimePeriod, fields, surveys, encoded):
        """
         Tries to store the opticalSheet and returns a mensage explaning what happend.

        @param int idOpticalSheet : Id of the opticalSheet to be store, if it is a new one it should be None.
        @param string surveyType : A string defining the type of the opticalSheets survey, must be in minitableSurveyType.
        @param int idCycle : The database id of the cycle to be added in this opticalSheet, it can't be None, it is ok if this cycle is alredy related to this opticalSheet.
        @param int term : Term to be added in the relation cycle opticalSheet .
        @param int idTimePeriod : Database id of the timePeriod in which this opticalSheet exist.
        @param [] fields : If not encoded: A list of dicts, where each dict represent a field and contain the keys: idsOffer, courseIndex, abbreviation, idCourse.
                           Else is just the encoding name
        @param [] surveys : A list of dicts where each dict represents a survey with the keys: 
assessmentNumber, 
idQuestionnaire: None or the IdQuestionnaire,
questions: [{questionWording, questionIndex}
        @param string encoded : A boolean to define if this opticalSheet is encoded
        @return  string:
        @author
        """
        timePeriod = TimePeriod.pickById(idTimePeriod)
        cycle = Cycle.pickById(idCycle)
        storedFields = False
        storedQuestionnaire = False
        if idOpticalSheet != None:
            opticalSheet = OpticalSheet.pickById(idOpticalSheet)
            if opticalSheet.surveyType != surveyType:
                raise OpticalSheetError("ERROR: Given surveyType is different than opticalSheet's surveyType.")
            #clear opticalSheets surveys
            opticalSheet.surveys = []
        else:
            #Before creating a new one check if it already exist
            if encoded:
                if len(OpticalSheet.find(encodingName = fields)) > 0:
                    raise OpticalSheetError("There can only be one opticalSheet per encoding!")
            if len(OpticalSheet.find(cycles = [cycle], term = term, timePeriod = timePeriod)) > 0: #Even encoded opticalSheets have to pass through this
                raise OpticalSheetError("There can be only one opticalSheet per cycle, term and timePeriod")
            #Now it is ok to store
            opticalSheet = OpticalSheet(surveyType)
            if encoded:
                opticalSheet.setEncodingName(fields)
            opticalSheet.store()
        hasAnswers = False
        answers = Answer.countAnswers(opticalSheet = opticalSheet)
        for key in answers:
            if answers[key] > 0:
                hasAnswers = True
        if not hasAnswers: #Can't alter offers with answers
            #First deal with the fields
            if not encoded:
                for field in fields:
                    idsOffer = [int(offer) for offer in field['idOffers']]
                    if len(idsOffer) > 0:
                        course = Course.pickById(field['idCourse'])
                        abbreviation = field['abbreviation'].split('(')[0].split('[')[0]
                        course.setAbbreviation(abbreviation)
                        course.store()
                        opticalSheet.addOpticalSheetField(Offer.find(idOffer = idsOffer), int(field['courseIndex']) + 1)
                    else:
                        opticalSheet.removeOpticalSheetField(int(field['courseIndex']) + 1)
                    print field['courseIndex']
            storedFields = True
        #Next the cycle
        if not {'term':term, 'cycle':cycle} in opticalSheet.cycles:
            opticalSheet.addCycle_Term(cycle, term)

        for survey in surveys:
            hasAnswers = False
            answers = Answer.countAnswers(opticalSheet = opticalSheet, assessmentNumber = survey['assessmentNumber'])
            for key in answers:
                if answers[key] > 0:
                    hasAnswers = True
            if not hasAnswers: #Can't alter a survey with answers
                #prepare the questionDict
                questionDict = {}
                for questionData in survey['questions']:
                    if questionData['idQuestion'] != None:
                        question = Question.pickById(questionData['idQuestion'])
                        questionDict[int(questionData['questionIndex']) + 1] = question
                #Create or find the questionnaire
                if survey['idQuestionnaire'] != None:
                    questionnaire = Questionnaire.pickById(survey['idQuestionnaire'])
                    #If the questionnaire exist update its questions
                    if questionnaire.questions != questionDict:
                        questionnaire.questions = questionDict
                        questionnaire.store()
                else:
                    #Create it
                    if encoded: #this is only to know the questionnaire's discription
                        questionnaire = Questionnaire(questionDict, fields + str(timePeriod))
                    else:
                        questionnaire = Questionnaire(questionDict, cycle.name + '-' + str(term) + '-' + str(timePeriod))
                    questionnaire.store()
                #Now remove old survey of this assessment in this opticalSheet (this method works even if there are no surveys in this opticalSheet)
                opticalSheet.removeSurvey(survey['assessmentNumber'])
                opticalSheet.addSurvey(questionnaire, survey['assessmentNumber'])                        
                storedQuestionnaire = True
        if storedQuestionnaire or storedFields:
            opticalSheet.store()
        if storedFields:
            return 'OpticalSheet was stored'
        elif storedQuestionnaire:
            return 'Only Questionnaire was stored'
        else:
            raise OpticalSheetError("Can't save a opticalSheet with answers in the same assessment!!")