def registerStudent(self, request):
        user = endpoints.get_current_user()
        user_id = helper.getUserId()
        registeredUser = helper.getRegisteredUser()
        if not registeredUser:
            raise endpoints.NotFoundException(
                'User is not registered to perform operation')
        namespace_manager.set_namespace(self._getNamespace(registeredUser))
        organization = registeredUser.orgKey.get()
        if request.studentWebSafeKey:
            student = ndb.Key(urlsafe=request.studentWebSafeKey).get()
        else:
            student = Student()
            organization.studentCount = organization.studentCount + 1
            setattr(student, 'serialNumber', organization.studentCount)
            setattr(student, 'key', ndb.Key(Student,
                                            organization.studentCount))
        if request:
            if request.studentName:
                setattr(student, 'studentName', str(request.studentName))
            else:
                raise endpoints.BadRequestException(
                    "studentName Name Required")
            if request.studentAge:
                setattr(student, 'studentAge', str(request.studentAge))
            else:
                raise endpoints.BadRequestException("studentAge Name Required")
            if request.gradeWebSafeKey:
                setattr(student, 'gradeKey',
                        ndb.Key(urlsafe=request.gradeWebSafeKey))
            if request.sectionWebSafeKey:
                setattr(student, 'sectionKey',
                        ndb.Key(urlsafe=request.sectionWebSafeKey))
            if request.subjectWebSafeKey:
                for subjectWebSafeKey in request.subjectWebSafeKey:
                    if ndb.Key(urlsafe=subjectWebSafeKey
                               ) not in student.subjectKey:
                        student.subjectKey.append(
                            ndb.Key(urlsafe=subjectWebSafeKey))
        setattr(student, 'createdBy', registeredUser.key)
        setattr(student, 'createdOn', datetime.datetime.now())

        kind = []
        kind.append(student)
        kind.append(organization)
        self._saveKinds(kind)
        d = self._create_document()
        d.studentAge = student.studentAge
        d.studentName = student.studentAge
        index = search.Index('student')
        index.put(d)
        return message_types.VoidMessage()
 def giveAttendenceToStudent(self, request):
     user = endpoints.get_current_user()
     user_id = helper.getUserId()
     registeredUser = helper.getRegisteredUser()
     if not registeredUser:
         raise endpoints.ForbiddenException("Not Allowed to update user")
     if not (registeredUser.isAdmin == True or registeredUser.isOwner
             == True or registeredUser.isTeacher == True):
         raise endpoints.ForbiddenException("Not Allowed to update user")
     namespace_manager.set_namespace(self._getNamespace(registeredUser))
     print request.studentWebSafeKey
     studentAttendenceKey = ndb.Key(
         StudentAttendence,
         request.date,
         parent=ndb.Key(urlsafe=request.studentWebSafeKey))
     print studentAttendenceKey
     studentAttendence = studentAttendenceKey.get()
     print studentAttendence
     if not studentAttendence:
         studentAttendence = StudentAttendence()
     print studentAttendence
     studentAttendence.isPresent = True if request.isPresent == True else False
     studentAttendence.date = datetime.datetime.strptime(
         request.date, '%d-%m-%Y').date()
     studentAttendence.employeeKey = registeredUser.key
     studentAttendence.key = studentAttendenceKey
     studentAttendence.studentKey = ndb.Key(
         urlsafe=request.studentWebSafeKey)
     #         student = ndb.Key(urlsafe=request.studentWebSafeKey).get()
     #         attendencePercentage = StudentAttendence.all()
     #         attendencePercentage = attendencePercentage.ancestor(ndb.Key(urlsafe=request.studentWebSafeKey))
     studentAttendence1 = StudentAttendence.query(ancestor=ndb.Key(
         urlsafe=request.studentWebSafeKey))
     totalAttendence = 0.0
     totalPresent = 0.0
     for s in studentAttendence1:
         totalAttendence = totalAttendence + 1
         print s.isPresent
         if s.isPresent == True:
             totalPresent = totalPresent + 1
     print totalAttendence
     print totalPresent
     attendencePercentage = (totalPresent / totalAttendence) * 100
     student = ndb.Key(urlsafe=request.studentWebSafeKey).get()
     student.attendencePercentage = attendencePercentage
     kind = []
     kind.append(student)
     kind.append(studentAttendence)
     self._saveKinds(kind)
     print datetime.date.today()
     print studentAttendence
     return message_types.VoidMessage()
    def registerSection(self, request):
        user = endpoints.get_current_user()
        user_id = helper.getUserId()
        registeredUser = helper.getRegisteredUser()
        if not registeredUser:
            raise endpoints.NotFoundException(
                'User is not registered to perform operation')
        namespace_manager.set_namespace(self._getNamespace(registeredUser))
        if request.delete == True:
            if request.sectionWebSafeKey:
                section_key = ndb.Key(urlsafe=request.sectionWebSafeKey)
                section_key.delete()
            else:
                endpoints.NotFoundException('Not a valid section key')
            return message_types.VoidMessage()
        if request.sectionWebSafeKey:
            section = ndb.Key(urlsafe=request.sectionWebSafeKey).get()
        else:
            if request.gradeWebSafeKey:
                section = Section()
                section_id = Section.allocate_ids(
                    size=1,
                    parent=ndb.Key(
                        urlsafe=getattr(request, 'gradeWebSafeKey')))[0]
                section_key = ndb.Key(
                    Section,
                    section_id,
                    parent=ndb.Key(
                        urlsafe=getattr(request, 'gradeWebSafeKey')))
                section.key = section_key
            else:
                raise endpoints.NotFoundException('Not a valid Grade')

        if request:
            for field in ('name', 'none'):
                if hasattr(request, field):
                    if field == 'name':
                        val = getattr(request, field)
                        if val:
                            setattr(section, field, str(val))
                            section.nameUpper = str(val).upper()
                        else:
                            raise endpoints.NotFoundException(
                                'Not a valid name')
                    else:
                        val = getattr(request, field)
                        if val:
                            setattr(section, field, str(val))
        section.organizerUserId = registeredUser.orgKey
        section.put()
        return message_types.VoidMessage()
 def getUser(self, request):
     user = endpoints.get_current_user()
     user_id = helper.getUserId()
     registeredUser = helper.getRegisteredUser()
     registeredUsersOutputForm = RegisteredUsersOutputForm()
     if not registeredUser:
         registeredUsersOutputForm.isUser = False
     else:
         registeredUsersOutputForm.userName = registeredUser.userName
         registeredUsersOutputForm.mainEmail = registeredUser.mainEmail
         # registeredUsersOutputForm.userAddress = registeredUser.userAddress
         # registeredUsersOutputForm.isOwner = True if registeredUser.isOwner else False
         registeredUsersOutputForm.isPrincipal = True if registeredUser.isPrincipal else False
         registeredUsersOutputForm.isAdmin = True if registeredUser.isAdmin else False
         registeredUsersOutputForm.isStudent = True if registeredUser.isStudent else False
         registeredUsersOutputForm.isActive = True if registeredUser.isActive else False
     return registeredUsersOutputForm
    def approveUser(self, request):
        user = endpoints.get_current_user()
        user_id = helper.getUserId()
        registeredUser = helper.getRegisteredUser()
        if not registeredUser:
            raise endpoints.ForbiddenException("Not Allowed to update user")
        if not (registeredUser.isAdmin == True
                or registeredUser.isOwner == True):
            raise endpoints.ForbiddenException("Not Allowed to update user")


#         tokenFromDatabase = Token.query(ndb.GenericProperty(str(Token.employeeKey)) == str(request.registeredUserKey)).fetch(projection=["tokenNumber"])
        tokenFromDatabaseQuery = Token.query()
        print tokenFromDatabaseQuery
        if request.empId:
            regiteredUserToApprove = RegisteredUsers.query(
                RegisteredUsers.orgKey == registeredUser.orgKey
                and RegisteredUsers.employeeKey == ndb.Key(
                    Employee, request.empId)).fetch()
            tokenFromDatabase = tokenFromDatabaseQuery.filter(
                Token.employeeKey == ndb.Key(Employee, request.empId)).fetch(
                    projection=["tokenNumber"])
            if not tokenFromDatabase:
                raise endpoints.BadRequestException("Not a valid tEnployee ID")
        elif request.studentId:
            regiteredUserToApprove = RegisteredUsers.query(
                RegisteredUsers.orgKey == registeredUser.orgKey
                and RegisteredUsers.studentKey == ndb.Key(
                    Student, request.studentId)).fetch()
            tokenFromDatabase = tokenFromDatabaseQuery.filter(
                Token.studentKey == ndb.Key(Student, request.studentId)).fetch(
                    projection=["tokenNumber"])
            if not tokenFromDatabase:
                raise endpoints.BadRequestException("Not a valid tEnployee ID")
        regiteredUserToApprove = regiteredUserToApprove[0]
        tokenFromDatabase = tokenFromDatabase[0]
        if tokenFromDatabase.tokenNumber == request.tokenNumber:
            print
            regiteredUserToApprove.isActive = True
            regiteredUserToApprove.put()
            tokenFromDatabaseQuery.fetch()[0].key.delete()
        else:
            raise endpoints.BadRequestException("Not a valid token Number")

        return message_types.VoidMessage()
 def giveRolesToUser(self, request):
     user = endpoints.get_current_user()
     user_id = helper.getUserId()
     registeredUser = helper.getRegisteredUser()
     if not registeredUser:
         raise endpoints.ForbiddenException("Not Allowed to update user")
     if not (registeredUser.isAdmin == True
             or registeredUser.isOwner == True):
         raise endpoints.ForbiddenException("Not Allowed to update user")
     userToUpdate = RegisteredUsers.query(RegisteredUsers.key == ndb.Key(
         urlsafe=request.registeredUserKey)).fetch()
     if not userToUpdate:
         raise endpoints.ForbiddenException("Enter Correct Key")
     userToUpdate = userToUpdate[0]
     userToUpdate.isAdmin = True if request.isAdmin == True else False
     userToUpdate.isTeacher = True if request.isTeacher == True else False
     userToUpdate.isStudent = True if request.isStudent == True else False
     userToUpdate.isPrincipal = True if request.isPrincipal == True else False
     userToUpdate.put()
    def addSubjectsToGrade(self, request):
        """Configure the school classes"""
        registeredUser = helper.getRegisteredUser()
        if not registeredUser:
            raise endpoints.NotFoundException(
                'User is not registered to perform operation')
        namespace_manager.set_namespace(self._getNamespace(registeredUser))
        if request.gradeWebSafeKey:
            grade_key = ndb.Key(urlsafe=request.gradeWebSafeKey)
            grade = grade_key.get()
        else:
            raise endpoints.PreconditionFailedException("Not a valid Grade")

        if request.subjectWebSafeKey:
            for subjectWebSafeKey in request.subjectWebSafeKey:
                if ndb.Key(urlsafe=subjectWebSafeKey) not in grade.subjectKey:
                    grade.subjectKey.append(ndb.Key(urlsafe=subjectWebSafeKey))

        grade.put()
        return message_types.VoidMessage()
    def registerGrade(self, request):
        print "regiter grade started nipun"
        """Configure the school classes"""
        registeredUser = helper.getRegisteredUser()
        if not registeredUser:
            raise endpoints.NotFoundException(
                'User is not registered to perform operation')
        namespace_manager.set_namespace(self._getNamespace(registeredUser))
        print request.name
        print request.name.number
        grade = Grade()
        _key = ndb.Key(Grade, str(request.name))
        print _key
        if _key.get():
            grade = _key.get()
        else:
            grade = Grade()
        if request.gradeWebSafeKey:
            grade_key = ndb.Key(urlsafe=request.gradeWebSafeKey)
            grade = grade_key.get()
        if request:
            if request.name:
                setattr(grade, 'name', str(request.name))
                setattr(grade, 'number', request.name.number)

            else:
                raise endpoints.BadRequestException("Class Name Required")
            if request.orgSpecificName:
                setattr(grade, 'orgSpecificName', request.orgSpecificName)
            else:
                grade.orgSpecificName = grade.name
        grade.orgKey = registeredUser.orgKey
        grade.key = ndb.Key(Grade, grade.name)
        grade.number = request.name.number
        print grade.key
        print grade.key.id()
        print grade.key.get()
        grade.put()
        return message_types.VoidMessage()
    def registerStudent(self, request):
        user = endpoints.get_current_user()
        user_id = helper.getUserId()
        registeredUser = helper.getRegisteredUser()
        if not registeredUser:
            raise endpoints.NotFoundException(
                'User is not registered to perform operation')
        namespace_manager.set_namespace(self._getNamespace(registeredUser))
        organization = registeredUser.orgKey.get()
        if request.studentWebSafeKey:
            student = ndb.Key(urlsafe=request.studentWebSafeKey).get()
        else:
            student = Student()
            organization.studentCount = organization.studentCount + 1
            student.rollNumber = organization.studentCount
        if request:
            for field in ('studentFees', 'studentName', 'studentAge',
                          'sectionWebSafeKey', 'subjectWebSafeKey'):
                if hasattr(request, field):
                    val = getattr(request, field)
                    if val:
                        setattr(student, field, str(val))
            if request.gradeWebSafeKey:
                student.gradeKey = ndb.Key(urlsafe=request.gradeWebSafeKey)
            if request.sectionWebSafeKey:
                student.sectionKey = ndb.Key(urlsafe=request.sectionWebSafeKey)
            subject_keys = []
            if request.subjectWebSafeKey:
                for key in request.subjectWebSafeKey:
                    print key
                    if ndb.Key(urlsafe=key) not in subject_keys:
                        subject_keys.append(ndb.Key(urlsafe=key))
                student.subjectKey = subject_keys

        student.orgKey = registeredUser.orgKey
        student.createdBy = registeredUser.key
        self._saveStudent(student, organization)
        return message_types.VoidMessage()