Exemplo n.º 1
0
    def __init__(self):
        self.URL_GETDATAQUESTION = "/preview/getDataPreview?idProject={0}"

        self.utility = Utility()

        dh = LogDBHandler(config=config, request=request)
        log.addHandler(dh)
Exemplo n.º 2
0
    def __init__(self):
        self.utility = Utility()
        self.registerService = RegisterService()
        dh = LogDBHandler(config=config, request=request)
        log.addHandler(dh)

        self.__getMasterData()
Exemplo n.º 3
0
    def __init__(self, models, session, config_type=None, translations=None):
        self.utility = Utility()
        self.model = models

        #         self.registerService = RegisterService();
        dh = LogDBHandler(config=config, request=request)
        log.addHandler(dh)
Exemplo n.º 4
0
 def __init__(self):
     self.utility = Utility();
     self.target_file_name = self.utility.getDefaultImagePath();
     
     dh = LogDBHandler( config=config,request=request);        
     log.addHandler(dh)
     
     pass;
Exemplo n.º 5
0
 def __init__(self):
     self.utility = Utility();
     self.urlUtility = URLUtility();
     self.UPLOAD_DIR = config['path_upload_file'] ;
     
     dh = LogDBHandler( config=config,request=request);
     
     log.addHandler(dh)
Exemplo n.º 6
0
 def __init__(self):
     dh = LogDBHandler( config=config,request=request);        
     log.addHandler(dh)
     
     self.registerService = RegisterService();
     self.sendMailService = SendMailService();
     
     self.utility = Utility();
     self.urlServer =  model.SystemEnvironment.getServerUrl();
 def __init__(self):
     self.utility = Utility();
     self.urlUtility = URLUtility();
      
     
     
     self.sourceHtml = model.SystemEnvironment.getScoreViewHtml();
     self.answerQuestionService = AnswerQuestionService(mymodel = model)
     
     dh = LogDBHandler( config=config,request=request);        
     log.addHandler(dh)
Exemplo n.º 8
0
 def __init__(self):
     self.utility = Utility();
     self.urlUtility = URLUtility();
      
     self.UPLOAD_DIR = config['path_upload_file'] ;
     self.CONVERT_DIR = config['path_convert_file'] ;
     
     self.utility.createPathFile(self.CONVERT_DIR);
     self.utility.createPathFile(self.UPLOAD_DIR);
     self.sourceHtml = model.SystemEnvironment.getScoreViewHtml();
     
     dh = LogDBHandler( config=config,request=request);        
     log.addHandler(dh)
Exemplo n.º 9
0
 def __init__(self, mymodel=None):
     
     self.utility = Utility();
     self.urlUtility = URLUtility();
     
     self.UPLOAD_DIR = config['path_upload_file'] ;
     self.CONVERT_DIR = config['path_convert_file'] ;
     self.utility.createPathFile(self.CONVERT_DIR);
     self.utility.createPathFile(self.UPLOAD_DIR);
     if mymodel is None:
         self.mymodel = model
     self.mymodel = mymodel
     
     self.urlServer = self.mymodel.SystemEnvironment.getServerUrl()
     
     dh = LogDBHandler( config=config,request=request);        
     log.addHandler(dh)
Exemplo n.º 10
0
 def __init__(self):
     print "init RegisterService"
     self.urlServer =  model.SystemEnvironment.getServerUrl();
     self.utility = Utility();
     pass;
Exemplo n.º 11
0
class RegisterService(object):

    def __init__(self):
        print "init RegisterService"
        self.urlServer =  model.SystemEnvironment.getServerUrl();
        self.utility = Utility();
        pass;
    
    def insertOrUpdateUserWithFacebook(self,user,fuser,accessToken):
        self.fullname = fuser['first_name']
        self.fulllastname = fuser['last_name']
        self.email =fuser['email']
        self.tnc = 1
        self.id_gender =  model.Gender.getIdGender(fuser['gender'])
        self.displayname  =  fuser['name']
        self.provider_user_id = fuser['id']
        self.access_token = accessToken['accessToken']
        self.profile_url =fuser['link']  
        self.expiresin = str(accessToken['expiresIn']) 
        self.singed_request = accessToken['signedRequest'] 
        
        locale = self.utility.spritValue(fuser['locale'], '_')
        self.language =  locale[0]
        self.country =  locale[1]
        
        self.insert = False;
        if(user is None):
            user = model.User()
            self.insert= True;
        user.user_name  = self.email
        user.email_address =  self.email
        user.display_name = self.displayname
        
        if(self.insert ):    
            user.save()
        
        self.user_id = user.user_id
        
        
        self.userservice = model.UserService.getByUserId(self.user_id)
        self.usersocial = model.UserSocialNetwork.getByUserIdAndSocialId(self.user_id, '1');  
        
        if(self.userservice is None):
            self.userservice = model.UserService();
            self.insert= True;
            
        self.userservice.user_name = self.email;
        self.userservice.email_address = self.email;
        self.userservice.display_name =  self.displayname ;
        #self.user._set_password(self.password); 
        self.userservice.first_name = self.fullname
        self.userservice.last_name = self.fulllastname
        #self.user.address =self.address
        #self.user.city =self.city
        #self.user.country = self.country
        self.userservice.id_gender = self.id_gender
        self.userservice.accept_tnc = self.tnc
        self.userservice.language = self.language
        self.userservice.country = self.country
        self.userservice.user_id = self.user_id
        
        if(self.insert ):
            self.userservice.save();
            self.userservice.updateGroupUserVoter();
        
        
        if (self.usersocial is None):
            self.usersocial = model.UserSocialNetwork();        
            self.insert= True;
            
               
        self.usersocial.user_id = self.user_id
        self.usersocial.id_social_type = 1
        self.usersocial.provider_user_id = self.provider_user_id
        self.usersocial.access_token = self.access_token
        
        self.usersocial.display_name = self.displayname 
        self.usersocial.profile_url =self.profile_url
        
        self.usersocial.expiresin =  self.expiresin 
        self.usersocial.singed_request = self.singed_request
        
        if(self.insert ):
            self.usersocial.save()
        
        
        return user;
        
    def createUserWithFacebook(self,fuser,accessToken):
        
        self.fullname = fuser['first_name']
        self.fulllastname = fuser['last_name']
        self.email =fuser['email']
        self.tnc = 1
        self.id_gender =  model.Gender.getIdGender(fuser['gender'])
        
        
        locale = self.utility.spritValue(fuser['locale'], '_')
        
        
        user = model.User()
        user.user_name  = self.email
        user.email_address =  self.email
        user.display_name = fuser['name']
        user.save()
        
        
        self.userservice = model.UserService();
        self.userservice.user_name = self.email;
        self.userservice.email_address = self.email;
        self.userservice.display_name =  fuser['name'];
        #self.user._set_password(self.password); 
        self.userservice.first_name = self.fullname
        self.userservice.last_name = self.fulllastname
        #self.user.address =self.address
        #self.user.city =self.city
        #self.user.country = self.country
        self.userservice.id_gender = self.id_gender;
        self.userservice.accept_tnc = self.tnc
        self.userservice.language = locale[0]
        self.userservice.country = locale[1]
        self.userservice.user_id = user.user_id        
        self.userservice.save();
        self.userservice.updateGroupUserVoter();
        
        
        self.usersocial = model.UserSocialNetwork();        
        self.usersocial.user_id = user.user_id
        self.usersocial.id_social_type = 1
        self.usersocial.provider_user_id = fuser['id']
        self.usersocial.access_token = accessToken['accessToken']
        
        self.usersocial.display_name = fuser['name']
        self.usersocial.profile_url =fuser['link']  
        
        self.usersocial.expiresin =  str(accessToken['expiresIn'])  
        self.usersocial.singed_request = accessToken['signedRequest']
        self.usersocial.save()
        
        
         
    
    def createUser(self, kw):
        
        self.registerObject = RegisterObject(**kw);
        
        self.user = self.registerObject.getUser()
        self.user.save(); 
        
        self.userservice = self.registerObject.getUserService();
        self.userservice.user_id = self.user.user_id
        self.userservice.accept_tnc = self.utility.convertToBit(self.userservice.accept_tnc);
        self.userservice.save();
        
        self.userservice.updateGroupUserVoter()
        self.userservice.updateGroupUserCreator()
        
        self.userGenCode = self.createUserGenCode(self.user);
        
        return self.user,self.userGenCode;
    
    def createUserGenCode(self,user):
        self.userGenCode = model.UserGenCode();
        self.userGenCode.user_id =  user.user_id;
        self.userGenCode.id_gen_code_type = 2 ;# register
        self.userGenCode.code = str(self.userGenCode.user_id)+ self.utility.my_random_string(15);
        self.userGenCode.expire_date =  self.utility.plusDate(datetime.today(),30);
        self.userGenCode.save();
        
        return self.userGenCode;
    
    def reActivateUserGenCode(self,userGenCode,user):
        if(userGenCode):
            self.userGenCode = userGenCode;
            
            self.userGenCode.code = str(self.userGenCode.user_id)+ self.utility.my_random_string(15);
            self.userGenCode.expire_date =  self.utility.plusDate(datetime.today(),30);
            self.userGenCode.create_date = datetime.today();
            self.userGenCode.count = self.userGenCode.count +1;
            self.userGenCode.success = 0;
            return self.userGenCode;
        
        return userGenCode;
    
    def deActivateUserGenCode(self,user):
        self.userGenCode = model.UserGenCode()
        self.userGenCode.user_id =  user.user_id
        self.userGenCode.id_gen_code_type = 6 ;# deactivate
        self.userGenCode.code = str(self.userGenCode.user_id)+ self.utility.my_random_string(15)
        self.userGenCode.expire_date =  self.utility.plusDate(datetime.today(),30)
        self.userGenCode.success = 1
        self.userGenCode.save()
        
        return self.userGenCode;
    def reActivateUser(self,user):
        self.userGenCode = None
        self.user = user
        if(self.user):
            self.userGenCode = self.createUserGenCode(self.user)
            
            self.emailValues={};
            self.emailValues['user_name'] = self.user.display_name;
            self.emailValues['email'] = self.user.email_address;
            self.emailValues['password'] = '';
            self.emailValues['activate_url'] =  request.scheme   + '://' + self.urlServer + "/activate/" + str(self.userGenCode.code);  #request.application_url
            
            self.sendMailService = SendMailService();
            self.sendMailService.sendreActivate(self.emailValues);
            self.sendMailService.start();
        return self.user, self.userGenCode
Exemplo n.º 12
0
 def __init__(self, models, session, config_type=None, translations=None):
     self.utility = Utility()
     self.model = models
 def __init__(self):
     dh = LogDBHandler( config=config,request=request);        
     log.addHandler(dh)
     self.utility = Utility();
     self.urlUtility = URLUtility();
     self.urlServer =  model.SystemEnvironment.getServerUrl();
Exemplo n.º 14
0
class AccountController(BaseController):
    def __init__(self):
        self.utility = Utility()
        self.registerService = RegisterService()
        dh = LogDBHandler(config=config, request=request)
        log.addHandler(dh)

        self.__getMasterData()

    def _before(self, *args, **kw):
        tmpl_context.project_name = "pollandsurvey"

    def __getMasterData(self):
        self.serviceType = model.SocialType.getAll(1)

    @expose("pollandsurvey.templates.account.index")
    @require(predicates.not_anonymous())
    def index(self, *args, **kw):

        userService = model.UserService()
        if request.identity:
            user = request.identity["user"]
            userService = model.UserService.getById(user.user_id)
            if userService is None:
                userService = model.UserService()

        listConutry = []
        self.country = model.FixCountry.getAll("1")
        for lang in self.country:
            listConutry.append(lang.to_json())

        listGender = model.Gender.getAll(1)
        listLanguage = []

        self.language = model.FixLanguage.getAll("1")
        for lang in self.language:
            listLanguage.append(lang.to_json())

        return dict(
            page="index",
            userService=userService,
            listConutry=listConutry,
            listGender=listGender,
            listLanguage=listLanguage,
        )

    @expose("pollandsurvey.templates.account.changepassword")
    @require(predicates.not_anonymous())
    def changepass(self, *args, **kw):
        """Handle the front-page."""
        return dict(page="changepassword")

    @expose("pollandsurvey.templates.account.socialmedia")
    @require(predicates.not_anonymous())
    def socialmedia(self, *args, **kw):
        user = request.identity["user"]
        self.userSocialNetwork = model.UserSocialNetwork.getSocialByUserId(user.user_id)
        return dict(page="socialmedia", userSocialNetwork=self.userSocialNetwork, socialType=self.serviceType)

    @expose("pollandsurvey.templates.account.cancellation")
    @require(predicates.not_anonymous())
    def cancellation(self, *args, **kw):
        """Handle the front-page."""
        return dict(page="cancellation")

    @expose()
    @require(predicates.not_anonymous())
    def deactivate(self):
        self.user = request.identity["user"]
        self.user.active = 0
        # user.deactivate()

        self.urlServer = model.SystemEnvironment.getServerUrl()
        self.userGenCode = self.registerService.deActivateUserGenCode(self.user)

        self.emailValues = {}
        self.emailValues["user_name"] = self.user.display_name
        self.emailValues["email"] = self.user.email_address
        self.emailValues["deactivate_url"] = (
            request.scheme + "://" + self.urlServer + "/activate/canceldeactive/" + str(self.userGenCode.code)
        )
        # request.application_url

        self.sendMailService = SendMailService()
        self.sendMailService.senddeActivate(self.emailValues)
        self.sendMailService.start()

        # model.User.deactivate()
        flash(_(LanguageObject.getdata("msg_thank_you")), "warning")
        redirect("/logout_handler")

    @expose()
    @require(predicates.not_anonymous())
    def updateprofile(self, *args, **kw):

        if request.identity:

            self.user = request.identity["user"]
            self.userService = model.UserService.getById(self.user.user_id)
            if self.userService is None:
                self.userService = model.UserService()
            self.userService.updateByValue(**kw)
            self.userService.accept_tnc = 1
            self.userService.user_id = self.user.user_id
            self.userService.birthdate = self.utility.convertToDateTime(self.userService.birthdate, "%d/%m/%Y")
            self.userService.updateall()

            flash(_(LanguageObject.getdata("msg_save_success")), "warning")
        else:

            log.warning("user cannot login, redirect to login")
            flash(_(LanguageObject.getdata("msg_not_login")), "warning")

        redirect("/account")

    @expose()
    # @expose('json')
    # @expose('json',content_type="text/plain"  )
    @require(predicates.not_anonymous())
    def rechangepass(self, *args, **kw):

        self.success = False
        self.message = ""
        if request.identity:
            self.current_password = kw.get("password")
            self.new_password = kw.get("newpassword")
            self.re_new_password = kw.get("rnewpassword")
            user = request.identity["user"]

            if user.validate_password(self.current_password):
                if str(self.new_password) == str(self.re_new_password):
                    user._set_password(self.new_password)
                    self.success = True
                    self.message = LanguageObject.getdata("msg_password_changed")
                else:
                    self.message = LanguageObject.getdata("msg_password_not_match")

            else:
                log.warning("user %s password not match : %s", user.user_name, self.current_password)
                self.message = LanguageObject.getdata("msg_password_not_match")
        else:
            self.message = LanguageObject.getdata("msg_not_login")
            log.warning("user cannot login, redirect to login")

        flash(_(self.message), "warning")
        # return dict(success=self.success, message = self.message);

        redirect("/account/changepass")
Exemplo n.º 15
0
 def __init__(self, models, session, config_type=None, translations=None):
     print "call VoterController(managepoll)"
     
     self.utility = Utility()           
     self.model = models       
Exemplo n.º 16
0
class AnswerController(BaseController):#RestController): #
    
    def __init__(self):
        self.utility = Utility();
        self.urlUtility = URLUtility();
         
        self.UPLOAD_DIR = config['path_upload_file'] ;
        self.CONVERT_DIR = config['path_convert_file'] ;
        
        self.utility.createPathFile(self.CONVERT_DIR);
        self.utility.createPathFile(self.UPLOAD_DIR);
        self.sourceHtml = model.SystemEnvironment.getScoreViewHtml();
        
        dh = LogDBHandler( config=config,request=request);        
        log.addHandler(dh)
        
       
    
    @expose()
    def _default(self, *args, **kw):
        return 'This page is not ready'
    
    def _before(self, *args, **kw):
        tmpl_context.project_name = 'pollandsurvey'
    
        

    
    @expose('pollandsurvey.templates.view.multiquestion')
    def questionnaire(self,key=0,ready='no',**kw):
        reload(sys).setdefaultencoding('utf8')
        log.info("key %s",key);
        
        self.header = '';
        self.footer = '';
        self.nextQuestion ='';
        self.template ='';
        
        
        self.respondents = model.Respondents.getByKey(key);
        if self.respondents :
            log.info("find key %s",key);
            self.urlServer =  model.SystemEnvironment.getServerUrl();
            
            self.urlReply = self.urlUtility.URL_REPLY.format(self.urlServer, str(self.respondents.id_question_project), str(self.respondents.id_question_option), str(self.respondents.id_voter))  ; #request.application_url
            log.info("iframe url to %s",self.urlReply);
            
            #check finish
            isRedirect = True
            if(self.respondents  is not None and self.respondents.finished == 1):
                log.info('voter finished in id public : %s', str(self.respondents.id_question_option) );
                self.redirect = self.urlUtility.URL_THANKYOU;
                if (isRedirect):
                    redirect(self.urlUtility.URL_THANKYOU) ;
            elif (self.respondents is None):
                log.error("System can not find idVoter : %s , idPublic : %s" , str(self.respondents.id_voter), str(self.respondents.id_question_option));
                redirect(self.urlUtility.URL_THANKYOU) ;
            
            #check Expire
            self.questionOption,self.redirect = self.__checkOptionExpired(self.respondents.id_question_option);    
                
            
            log.info("id_question_option : %s ", str(self.questionOption.id_question_option));
            log.info("ready : %s ", str(ready));
            
            if str(ready).lower() == 'no':    
                #check have welcome page
                if( not self.utility.isEmpty(self.questionOption.welcome_message) ) :
                    #redirect('/ans' + '/welcome?id='+ str(self.questionOption.id_question_option) );
                    log.info("show message welcome : ");
                    redirect( self.urlUtility.URL_WELCOME.format(key = str(key)) )#   self.URL_WELCOME_NEW.format(str(key))  );
                else:
                    log.info("show questionnaire : ");
                    self.template = self.questionOption.theme.template;
                    override_template(AnswerController.questionnaire, self.template) ;    
                    
            elif str(ready).lower() == 'yes':
                self.header = self.questionOption.header_message;
                self.footer = self.questionOption.footer_message;
                self.urlName = self.utility.spritValue(request.path_info,'/');
                self.template = self.questionOption.theme.template
                if(len(self.urlName) >= 1 ) :
                    self.nextQuestion = '/' + self.urlName[0] + '/saveQuestion' + '?id='+ str(self.questionOption.id_question_option);
                
                
                if(self.template is not None and len(self.template) > 0):    
                    log.info("template used : %s",  self.template );     
                    
                    override_template(AnswerController.questionnaire, self.template) 
                    
                self.ip=request.environ.get("X_FORWARDED_FOR", request.environ["REMOTE_ADDR"]);
                self.browser = request.environ.get('HTTP_USER_AGENT');
                
               
            
        else:
            log.warning("find not found key %s",str(key));
            redirect(self.urlUtility.URL_EXPIRED) ;       
        
        return dict(page='view',header = Markdown(self.header).convert() , 
                        footer = Markdown(self.footer).convert()  , 
                        action = self.nextQuestion,template= self.template,
                        #urldata = self.URL_GETDATAQUESTION.format(self.idPublic),
                        urldata =  self.urlUtility.URL_GETDATAQUESTION.format(key=str(key)),#  self.URL_GETDATAQUESTION.format(key),  
                        idproject = self.questionOption.id_question_option ,
                        idresp = self.respondents.id_respondents,
                        shownavigator = bool(self.questionOption.show_navigator) ); 
    
     
    
    @expose('pollandsurvey.templates.view.welcome')
    def welcome(self,key=0,came_from=lurl('/')):
        reload(sys).setdefaultencoding("utf-8");
         
        
        log.info('preview id : ' + str(key));
        
        self.respondents = model.Respondents.getByKey(key);
        #self.idProject,self.idPublic,self.idVoter,self.redirect = self.__checkExpire(id);
        if (self.respondents):
        
            self.welcome_message = '';
            
            self.questionOption,self.redirect = self.__checkOptionExpired(self.respondents.id_question_option);
                    
            self.welcome_message= self.questionOption.welcome_message;
            self.nextQuestion  = '';
             
            self.urlName = self.utility.spritValue(request.path_info,'/');
             
            if(len(self.urlName) >= 1 ) :
                #self.nextQuestion = '/' + self.urlName[0]+ '?id='+ str(self.questionOption.id_question_option);
                #self.nextQuestion = '/' + 'ans/reply/'+  str(self.questionOption.id_question_option);
                #self.nextQuestion = self.URL_REPLY.format(id)
                self.nextQuestion = self.urlUtility.URL_REPLY_QUESTIONNAIRE.format(key=str(key)); 
        else:
            log.error("find not found respondent with key %s ", str(key));
            redirect(self.urlUtility.URL_EXPIRED) ;       
            
               
            
        #self.welcome_message
        return dict(page='view', ready = 'yes',welcome_message = Markdown(self.welcome_message).convert(), nextQuestion= self.nextQuestion);
    
            
     
    
    @expose('pollandsurvey.templates.view.goodbye')
    def thankyou(self,key=0,came_from=lurl('/')):
        reload(sys).setdefaultencoding("utf-8");
        
        log.info('preview id : ' + str(key));
        
        
        #self.idProject,self.idPublic,self.idVoter,self.redirect = self.__checkExpire(key);
        self.respondents = model.Respondents.getByKey(key);
        if(self.respondents):
            self.idProject=self.respondents.id_question_project;
            self.idPublic=self.respondents.id_question_option;
            self.idVoter=self.respondents.id_voter;
            
            
            self.goodbye = '';
            
            self.questionOption,self.redirect = self.__checkOptionExpired(self.idPublic);
                    
            self.goodbye= self.questionOption.end_message;
            self.nextQuestion  = '';
            self.urlRedirect = ''; 
            self.urlName = self.utility.spritValue(request.path_info,'/');
            
            #self.respondents  = model.Respondents.getByVoterIdAndPublicId(self.idVoter,self.idPublic); 
            
            self.project = model.QuestionProject.getId(self.idProject) 
            
            self.projectType = self.project.id_question_project_type;
            
            if(len(self.urlName) >= 1 ) :
              
                self.urlRedirect = self.questionOption.redirect_url
        else:
            log.error("find not found respondent with key %s ", str(key));
            redirect(self.urlUtility.URL_EXPIRED) ;  
            
    
        return dict(page='goodbye', ready = 'yes',goodbye = Markdown(self.goodbye).convert(),nextQuestion = self.nextQuestion ,urlRedirect= self.urlRedirect,
                    option=self.questionOption,projectType = self.projectType,imageId = self.respondents.id_respondents);
    
    
    @expose('json')
    def getDataPreview(self, key=0,   *args, **kw): 
        reload(sys).setdefaultencoding("utf-8");
        log.info("function getDataPreview");
        
        log.info("key = %s", str(key));
        
        self.respondents = model.Respondents.getByKey(key);
        #idProject = kw.get('idProject');
        
        self.idProject=self.respondents.id_question_project;
        self.idPublic=self.respondents.id_question_option;
        self.idVoter=self.respondents.id_voter;
        self.redirect=None;
        
        #self.idProject,self.idPublic,self.idVoter,self.redirect = self.__checkExpire(self.respondents.id_question_project);
        
        log.info("idProject : %s,  idPublic : %s, idVoter : %s, redirect : %s  ", str(self.idProject), str(self.idPublic), str(self.idVoter), str(self.redirect));
       
        
        #self.respondents  = model.Respondents.getByVoterIdAndPublicId(self.idVoter,self.idPublic);    
        self.questionOption = model.QuestionOption.getId(self.idPublic);
        
        
        #get old question
        self.listReply = model.RespondentReply.listQuestionForUser(self.respondents.id_respondents);
        
        self.respondents.respondent_data = datetime.now();
        
        question = [];
        log.info("Random Question And Answer : " );
        if( len(self.listReply) >0 ):
            log.info("Random new");
            question = self.__getQuestionFromReply(self.listReply,self.questionOption);
            question = self.__randomQuestionAndAnswer(question,self.questionOption); #add 
        else:
             
            question = self.__getQuestion(self.idPublic,self.questionOption);
            log.info("get new Question and Random new, len question : %s", str(len(question)));
            #save to database
            question = self.__randomQuestionAndAnswer(question,self.questionOption);   #add
            model.RespondentReply.createQuestionForUser(question,self.respondents.id_respondents);
            log.info("Create Question And Answer to user : "******"utf-8");
        log.info( "function save Question answer");
        log.info( request.body);
        self.df = json.loads(request.body, encoding=request.charset);
        
        self.listAnswer = self.df.get('value');
        self.finished =self.df.get('finished');
        self.redirect = '';
        
         
        
        #from urlparse import urlparse;
        #parsed = urlparse(request.environ.get("HTTP_REFERER" ))
        #print 'path url : ', parsed.path
        if (len(self.listAnswer) >0):
            for value in self.listAnswer:
                 
                if(value):
                    self.idPublic =  value.get('idproject');
                    self.idResp =  value.get('idresp');
                    self.idQuestion = value.get('id');
                    self.values = value.get('value');
                    
                    print value.get('type');
                    
                    self.questionOption,self.redirect = self.__checkOptionExpired(self.idPublic,False);#check Expired
            
                    self.respondent,self.redirect = self.__checkRespondentFinished( None,  None,self.idResp,False);#check finished
                    
                    if(self.respondent):
                        self.question = model.Question.getById(self.idQuestion);#getQuestion
                         
                        self.respondent.finished = self.finished;
                        self.respondent.finished_date = datetime.now();
                        if(self.question):
                            self.respondentreply = model.RespondentReply.getByRespondentAndQuestion(self.idResp,self.idQuestion);
                            
                            if (self.respondentreply is None):
                                self.respondentreply = model.RespondentReply();
                                self.respondentreply.id_respondents = self.idResp;
                                self.respondentreply.id_question = self.idQuestion;
                                self.respondentreply.save();
                                log.info("save answer respondentreply : " +str( self.respondentreply.id_respondents ) + " and " + str( self.respondentreply.id_question ) + " success");
                                
                            
                            if (len(self.respondentreply.childenAnswer) == 0):
                                #save
                                for v in self.values:
                                    self.replyquestion = model.ReplyBasicQuestion(); 
                                    self.replyquestion.id_resp_reply = self.respondentreply.id_resp_reply; #error
                                    self.replyquestion.id_basic_data = v.get('id')
                                    self.replyquestion.answer_text = v.get('value')
                                    self.replyquestion.save();
                                 
                                    log.info("save answer replyquestion : " +str( self.respondentreply.id_resp_reply ) + " and " + str( self.replyquestion.id_basic_data ) + " success");
                                
                                
                            else:
                                log.info('user %s do this question : %s',self.idResp,self.idQuestion);
                                
                        else:
                            log.info('find not found question id : : %s',self.idQuestion);
                            
                    else:
                        log.info('find not found respondent id : : %s',self.idResp);
                    
            #calculate score        
            if(self.finished):  
                log.info('finished : calculate score ');
                model.Respondents.updateScoreByIdRespondents(self.idResp);
                self.__createScoreFile(self.idResp);
                
                self.redirect = self.urlUtility.URL_GOODBYE.format( key=  self.utility.splitNameWithOutExtention(basename(request.environ.get("HTTP_REFERER" )))  );
               
                    
                    
      
        return dict(success = True,redirect = self.redirect, finished = self.finished  );
    
     
    
    def __checkExpire(self,id):
        #sprint 10.2.1.0.html     idproject.idpublic.idvoter.
        self.value = self.utility.spritValue(id,'.');
         
        self.idProject =0;
        self.idPublic = 0;
        self.idVoter = 0;
        
        self.redirect = '';
        
        
        
        if(len(self.value)  == 4):
            self.idProject =self.value[0];
            self.idPublic = self.value[1];
            self.idVoter = self.value[2];
        else:
            self.idProject =None;
            self.idPublic = None;
            self.idVoter = None;
            
            log.info('parameter not have 4 parameter : %s', ','.join(self.value));
            self.redirect = self.urlUtility.URL_EXPIRED;
            redirect(self.urlUtility.URL_EXPIRED) ;
        
        self.voter = model.Voter.getId(self.idVoter);
        if(self.voter is None):
            log.info('find not voter in id : %s',self.idVoter);
            self.redirect = self.urlUtility.URL_HOME;
            redirect(self.urlUtility.URL_HOME) ;
        
        self.project = model.QuestionProject.getId(self.idProject);
        if(self.project is None):
            log.info('find not project in id project : %s',self.idProject);
            self.redirect = self.urlUtility.URL_HOME;
            redirect(self.urlUtility.URL_HOME) ;
            
        return self.idProject,self.idPublic,self.idVoter, self.redirect;
            
    def __checkOptionExpired(self,idPublic,isRedirect = True):
        #print 'public option id ',idPublic;
        self.questionOption = model.QuestionOption.getId( idPublic);           
        self.redirect = '';
        if  self.questionOption is None or ( not self.utility.isActiveFromDate(None,self.questionOption.activate_date,self.questionOption.expire_date) ):
            self.redirect = self.urlUtility.URL_EXPIRED;
            if (isRedirect):
                #print 'redirect ',self.URL_EXPIRED; 
                redirect(self.urlUtility.URL_EXPIRED) ;
      
                
        #print 'id option : ', self.questionOption.welcome_message;
        
        return self.questionOption,self.redirect;    
            
    def __checkRespondentFinished(self,idVoter,idPublic,idResp,isRedirect = True):
        self.respondent = None;
        self.redirect = '';
        if(idVoter and idPublic):
            self.respondent = model.Respondents.getByVoterAndPublicId(idVoter,idPublic);
        elif (idResp):
            self.respondent = model.Respondents.getId(idResp);
            
        if(self.respondent  is not None and self.respondent.finished == 1):
            log.info('voter finished in id public : %s',self.idPublic);
            self.redirect = self.urlUtility.URL_THANKYOU;
            if (isRedirect):
                redirect(self.urlUtility.URL_THANKYOU) ;
        elif (self.respondent is None):
            log.error("System can not find idVoter : %s , idPublic : %s" , idVoter, idPublic);
            
            redirect(self.urlUtility.URL_THANKYOU) ;
        
        return self.respondent,self.redirect;
    
    def __getQuestion(self,idPublic,questionOption):
        
        question = [];
        #get Project Option
        
        if self.questionOption :
            #get Question 
            self.listQuestions = model.Question.getByProjectId(questionOption.id_question_project);
            
            
            #get to object json
            for self.question in self.listQuestions:
                question.append(self.question.to_json(randomAnswer = questionOption.random_answer));
            
            
            
            #clear sequence 
               
        return question ;
    
    def __getQuestionFromReply(self,reply,questionOption):
        question = [];
        for re in reply:
            #re.question
            question.append(re.question.to_json(randomAnswer= questionOption.random_answer));
        
        return question;
    
    def __randomQuestionAndAnswer(self,question,questionOption):
        #option Randon Question
        if( questionOption.id_fix_random_type == 2):
            question = random.sample(question,len(question));#,self.questionOption.use_question_no );
        
        
        question = question[0:questionOption.use_question_no];
            
        return question;
    
    def __setSequenceQuestion(self,question):
        row = 1;
        for q in question:
            q['seq'] = row;
            row = row +1; 
        row =None;
        
        return question;
    
    def __createScoreFile(self,idResp):
        
        self.respondent = model.Respondents.getId(idResp);
        self.score = model.Respondents.getScoreByIdRespondents(self.idResp);
        self.voter = self.respondent.voter;
        
        self.convertHtml = ConvertHtml2Pdf();
        self.convertPNG = ConvertPdf2image();
        
        self.sourceHtml = model.SystemEnvironment.getScoreViewHtml();

        values = {};
        values['name'] = str(self.voter.prefix + ' ' + self.voter.firstname + ' ' + self.voter.lastname);
        values['score'] = str(self.score);
        
        self.outputPDFFilename = ("{0}\{1}-{2}-{3}-{4}.pdf").format(str(self.CONVERT_DIR), str(self.respondent.id_respondents), str(self.respondent.id_voter), str(self.respondent.id_question_project), str(self.respondent.id_question_option))  ;
        self.outputPNGFilename = ("{0}\{1}-{2}-{3}-{4}.png").format(str(self.CONVERT_DIR), str(self.respondent.id_respondents), str(self.respondent.id_voter), str(self.respondent.id_question_project), str(self.respondent.id_question_option))  ;
        
        self.result = self.convertHtml.convertHtmlToPdf(values, self.sourceHtml, self.outputPDFFilename);
        log.info("convert file %s is %s" %(self.outputPDFFilename, self.result));
        if(self.result == 0):
            self.result = self.convertPNG.convert(self.outputPDFFilename, self.outputPNGFilename)
            log.info("convert file %s is %s" %(self.outputPNGFilename, self.result));
            if(self.result):
                log.info("save image file %s is %s" %(self.outputPNGFilename, self.result));
                with open(self.outputPNGFilename,"rb") as f:
                    self.respondent.image_file = f.read(); 
        else:
            log.error("convert html to pdf error with id_resp=%s" %idResp)
Exemplo n.º 17
0
class PreviewController(BaseController):
   
    def __init__(self):
        self.URL_GETDATAQUESTION = '/preview/getDataPreview?idProject={0}';   
       
        self.utility = Utility();
        
        dh = LogDBHandler( config=config,request=request);        
        log.addHandler(dh)
        
    
    @expose('pollandsurvey.templates.view.multiquestion')
    @require(predicates.in_any_group('creator','managers', msg=l_('Only for creator')))
    def index(self ,id=0,ready='no' , came_from=lurl('/')):
        reload(sys).setdefaultencoding('utf8')
        
        userid = request.identity['repoze.who.userid']
        
       
        self.header = '';
        self.footer = '';
        self.nextQuestion ='';
        self.template =''; 
        self.questionOption = model.QuestionOption.getId(id);
        
        if self.questionOption : 
            print str(ready).lower()
            if str(ready).lower() == 'no':    
                #check have welcome page
                if( not self.utility.isEmpty(self.questionOption.welcome_message) ) :
                    redirect(request.path_info + '/welcome?id='+ str(self.questionOption.id_question_option) );
                else:
                    self.template = self.questionOption.theme.template;
                    override_template(PreviewController.index, self.template) ;    
                    
            elif str(ready).lower() == 'yes':
                self.header = self.questionOption.header_message;
                self.footer = self.questionOption.footer_message;
                self.urlName = self.utility.spritValue(request.path_info,'/');
                self.template = self.questionOption.theme.template
                if(len(self.urlName) >= 1 ) :
                    self.nextQuestion = '/' + self.urlName[0] + '/saveQuestion' + '?id='+ str(self.questionOption.id_question_option);
                
                
                if(self.template is not None and len(self.template) > 0):    
                    log.info("template used : %s",  self.template );                     
                    override_template(PreviewController.index, self.template) 
        
        #kw = {'idProject': str(id)}
        #self.dataView = self.getDataPreview(came_from,**kw)

        print "self.template " + self.template            
                
        #print 'idproject : ', id;     
        return dict(page='view',header = self.header, 
                    footer = self.footer, 
                    action = self.nextQuestion,
                    template= self.template,
                    urldata = self.URL_GETDATAQUESTION.format(id) , 
                    idproject = id , 
                    shownavigator = bool(self.questionOption.show_navigator),
                    idresp = "",
                    username=""); 
         
        
    
    @expose ("genshi:pollandsurvey.templates.view.firstTemplate")
    def sampleTemplate(self,id=0, **kw):        
        #print id;
        if(str(id) == str(2)):
            #print id;
            override_template(PreviewController.sampleTemplate, 'genshi:pollandsurvey.templates.view.changeTemplate') 
        return dict(title="Foobar", mybool=False, someval="foo"  ) #,tg_template="pollandsurvey.templates.view.changeTemplate"
        
   
    @expose('pollandsurvey.templates.view.welcome')
    def welcome(self,id=0,came_from=lurl('/')):
        reload(sys).setdefaultencoding('utf8')
        
        if not request.identity:
            login_counter = request.environ.get('repoze.who.logins', 0) + 1
            redirect('/login',   params=dict(came_from=came_from, __logins=login_counter))
        userid = request.identity['repoze.who.userid']
       
        
        log.info('preview id : ' + str(id));
        
        
        self.welcome_message = '';
        self.questionOption = model.QuestionOption.getId(id);
        if self.questionOption : 
            if datetime.now() <= self.questionOption.expire_date:
                log.info('not expire');
            else :
                log.info('expire');
                
            self.welcome_message= self.questionOption.welcome_message;
            self.nextQuestion  = '';
             
            self.urlName = self.utility.spritValue(request.path_info,'/');
             
            if(len(self.urlName) >= 1 ) :
                self.nextQuestion = '/' + self.urlName[0]+ '?id='+ str(self.questionOption.id_question_option);
        
            
                
            
        
        return dict(page='view', ready = 'yes',welcome_message = self.welcome_message, nextQuestion= self.nextQuestion);
    
    @expose('pollandsurvey.templates.view.singlequestion')
    def show(self ,id=0 , came_from=lurl('/')):
        reload(sys).setdefaultencoding('utf8')
        
        if not request.identity:
            login_counter = request.environ.get('repoze.who.logins', 0) + 1
            redirect('/login',   params=dict(came_from=came_from, __logins=login_counter))
        userid = request.identity['repoze.who.userid']
        #flash(_('Welcome back, %s!') % userid)
        
        log.info('preview id : ' + str(id));
        
        self.questionOption = model.QuestionOption.getId(id);
        
        log.info('expire date : ' + str(self.questionOption.expire_date));
        log.info('current : ' + str(datetime.now()) );
        
        if datetime.now() <= self.questionOption.expire_date:
            log.info('not expire');
        else :
            log.info('expire');
        
        return dict(page='view')
    
    @expose('json')
    def getDataPreview(self, came_from=lurl('/'),   *args, **kw): 
        reload(sys).setdefaultencoding("utf-8");
        
        idProject = kw.get('idProject');
        idRespondet = None;
        
        if( '.' in idProject):
            self.data =  self.utility.spritValue(idProject,".")
             
            idProject = self.data[0];
            if len(self.data) == 2:
                idRespondet = self.data[1];
            
        #print args;
        #print kw ;
        
        questions = [];
        question = [];
        self.order = 1;
        self.listquestion = []
        
        self.listquestion = [];
        if idRespondet :
            log.info("Query with respondent");
            self.listReply = model.RespondentReply.listQuestionForUser(self.data[1]);
            self.order = 1
            for re in self.listReply:                
                result = model.RespondentReply.getResultByRespondemtAndQuestion(idRespondet,re.question.id_question);
                self.listquestion.append(re.question.to_json(randomAnswer=False, showResult = result,initOrder =self.order ));
                self.order = self.order + 1
         
        else :
            log.info("Query with question");
            
            self.questionOption = model.QuestionOption.getId(idProject);
             
            if self.questionOption :
                self.questionGroups = model.QuestionGroup.getByProject(self.questionOption.id_question_project )
                for self.group in self.questionGroups:
                    self.group, self.order = self.group.tojsonview(randomAnswer = self.questionOption.random_answer,initOrder= self.order)
                    self.listquestion.append(self.group)
                
            self.order = self.order -1;
            
        
        questions.append({'id': idProject, 'question' : self.listquestion, 'total': self.order });
       
        
        return dict(questions = questions);
    
    
    @expose('pollandsurvey.templates.view.goodbye')
    def saveQuestion(self,id=0 , came_from=lurl('/'),   *args, **kw): 
        reload(sys).setdefaultencoding("utf-8");
        
        if not request.identity:
            login_counter = request.environ.get('repoze.who.logins', 0) + 1
            redirect('/login',   params=dict(came_from=came_from, __logins=login_counter))
        userid = request.identity['repoze.who.userid']
        
        
        self.success = True;
        self.message = "success";
        self.goodbye_message = '';
        self.nextQuestion = '';
         
        
        self.questionOption = model.QuestionOption.getId(id);
        if(self.questionOption):
            self.goodbye_message = self.questionOption.end_message;
            self.urlRedirect = self.questionOption.redirect_url;
        
        return dict(page='goodbye',success=self.success, message = self.message,goodbye = self.goodbye_message,nextQuestion = self.nextQuestion,urlRedirect = self.urlRedirect);
    
    
    @expose('pollandsurvey.templates.view.resultquestion')
    def showResult(self,id=0  ,ready='yes' , came_from=lurl('/'),   *args, **kw): 
        
        reload(sys).setdefaultencoding("utf-8");
        
        if not request.identity:
            login_counter = request.environ.get('repoze.who.logins', 0) + 1
            redirect('/login',   params=dict(came_from=came_from, __logins=login_counter))
        #userid = request.identity['repoze.who.userid']
        
        print id;
        self.data = self.utility.spritValue(id,".")
        
        if len(self.data) != 2:
            return dict(questions = []);
        
        log.info('preview id : ' + str(id) + '  ready : ' + str(ready));
         
        
        
        self.header = '';
        self.footer = '';
        self.nextQuestion ='';
        self.template ='';
        self.questionOption = model.QuestionOption.getId(self.data[0]);
        if self.questionOption : 
            #log.info('expire date : ' + str(self.questionOption.expire_date) + ', current date : ' +  str(datetime.now()));
            
            
            #if datetime.now() <= self.questionOption.expire_date:
            #    log.info('not expire');
            #else :
            #    log.info('expire');
            
            
            if str(ready).lower() == 'no':    
                #check have welcome page
                if( not self.utility.isEmpty(self.questionOption.welcome_message) ) :
                    redirect(request.path_info + '/welcome?id='+ str(self.questionOption.id_question_option) );
                else:
                    self.template =   self.questionOption.theme.template;
                    #override_template(PreviewController.index, self.template) ;    
                    
            elif str(ready).lower() == 'yes':
                self.header = self.questionOption.header_message;
                self.footer = self.questionOption.footer_message;
                self.urlName = self.utility.spritValue(request.path_info,'/');
                self.template =   self.questionOption.theme.template
                if(len(self.urlName) >= 1 ) :
                    self.nextQuestion = '/' + self.urlName[0] + '/saveQuestion' + '?id='+ str(self.questionOption.id_question_option);
                
                
                """if(self.template is not None and len(self.template) > 0):    
                    log.info("template used : %s",  self.template );                     
                    override_template(PreviewController.index, self.template) 
                """    
            print "return values";       
                            
        
        return dict(page='view',header = self.header, 
                    footer = self.footer, 
                    action = self.nextQuestion,
                    template= self.template,
                    urldata = self.URL_GETDATAQUESTION.format(id) , 
                    idproject = id ,
                    shownavigator = bool(self.questionOption.show_navigator),
                    idresp = ""); 
Exemplo n.º 18
0
class ActivateController(BaseController):
    # Uncomment this line if your controller requires an authenticated user
    # allow_only = predicates.not_anonymous()
    
    def __init__(self):
        dh = LogDBHandler( config=config,request=request);        
        log.addHandler(dh)
        
        self.registerService = RegisterService();
        self.sendMailService = SendMailService();
        
        self.utility = Utility();
        self.urlServer =  model.SystemEnvironment.getServerUrl();
        
        
    @expose()
    def index(self,*args,**kw):
        redirect( '/login')
    
     
    
    @expose('json')
    @expose('genshi:pollandsurvey.templates.register.activate_success')
    def value(self,*args, **kw):
        
        self.activate_code = args
        if(len(self.activate_code) > 0): 
            self.userGenCode =  model.UserGenCode.getByActivateCode(self.activate_code[0])
            self.message = "";
            
            if (self.userGenCode ):
                if ( not self.utility.convertToBool(self.userGenCode.success) ):
                    
                    if (self.utility.isActiveFromDate(self.utility.getCurrentDate() , self.userGenCode.create_date ,self.userGenCode.expire_date   ) ):
                        self.userGenCode.success = 1;
                        self.message =   LanguageObject.getdata("msg_success_activate")  
                        
                    else : 
                        self.message = LanguageObject.getdata("msg_expire_activate") 
                          
                        override_template(ActivateController.value, 'genshi:pollandsurvey.templates.register.reactivate') 
                         
                else:
                    self.message = LanguageObject.getdata("msg_already_activate")
                    
            
            else:
                self.message = LanguageObject.getdata("msg_not_found_activate")
                log.warning("Find not found activate code  %s", self.activate_code )
        else:
            #self.message = "Thank you!";
            log.warning("User income is wrong,have not activate code")
            redirect("/")
         
        
        #for key in request.environ:   print "%s --- %s"   %(  key, request.environ[key]);
         
        return dict(page='activate_success',message = self.message) 
        
    
    @expose('pollandsurvey.templates.register.register_success')
    def reactivate(self,*args,**kw):
         
        if(kw.get('activate_code')):
            self.userGenCode =  model.UserGenCode.getByActivateCode(kw.get('activate_code'));
            if self.userGenCode :
                self.user = model.UserService.getByUserId(self.userGenCode.user_id);
                
                self.userGenCode = self.registerService.reActivateUserGenCode(self.userGenCode,self.user);
                
                self.emailValues={};
                self.emailValues['user_name'] = self.user.display_name;
                self.emailValues['email'] = self.user.email_address;
                # self.emailValues['password'] = self.password;
                self.emailValues['activate_url'] = request.application_url + "/activate/value/" + str(self.userGenCode.code);
               
                self.sendMailService = SendMailService();
                self.sendMailService.sendreActivate(self.emailValues);
                self.sendMailService.start();
            else:
                log.warn("user gen code is not exits ")    
        
        return dict(page='register_success')

    @expose('pollandsurvey.templates.message.index')
    def canceldeactive(self,*args,**kw):
        
        self.title ="test"
        self.message =  LanguageObject.getdata("msg_already_deactivate")
        
        if(len(args) >0 and args[0] != None):
            self.userGenCode =  model.UserGenCode.getByDeactivateCode(args[0]);
            if self.userGenCode:
                self.user = model.User.getId(self.userGenCode.user_id)
                self.user.active = 1
                self.userGenCode.success = 0
                
                
                self.emailValues={};
                self.emailValues['user_name'] = self.user.display_name;
                self.emailValues['email'] = self.user.email_address;
                # self.emailValues['password'] = self.password;
                
               
                self.sendMailService = SendMailService();
                self.sendMailService.sendWelcomeActivate(self.emailValues);
                self.sendMailService.start();
                
                
                self.message =LanguageObject.getdata("msg_success_deactivate")  
        else:
            self.message = LanguageObject.getdata("failed")       
                
        
        
        return dict(page='canceldeactivate', title=self.title, message=self.message)
 def __init__(self, models, session, config_type=None, translations=None):
     self.utility = Utility()
     self.model = models       
     print "call init LoadDataControllers"
     print self.model
class PublicationController(TGController):
    
    allow_only = in_any_group('voter', 'managers', msg=l_('Only for people with the "manage" permission'))
    #has_any_permission('manage','creator', msg=l_('Only for people with the "manage" permission'))
     
    def __init__(self, models, session, config_type=None, translations=None):
        self.utility = Utility()
        self.model = models       
        print "call init LoadDataControllers"
        print self.model
        
    
    @expose('managepoll.templates.publication.index')   
    def index(self,**kw):
        print kw
        return dict(page = 'index',idproject = kw['idproject'] )
    
    
    @expose()
    def deletepublication(self,**kw): 
        print kw
        
        status, message = self.model.QuestionOption.deleteById(kw['idoption'])
        
        print status
        print message

        redirect('/managepoll/publication/indextest',params={'idproject':kw['idproject']})
    
    @expose('managepoll.templates.publication.publication')
    def publication(self,**kw):
        
        
        reload(sys).setdefaultencoding('utf8')      #set ค่า เป็น utf8 สำหรับฟังชั่นนี้
        user =  request.identity['user'];    

        
        questionoption = self.model.QuestionOption()
        questionoption.id_question_project = kw['idproject']
        
        questionoption.activate_date = datetime.today() #today for add option
        questionoption.expire_date = self.utility.plusDate(datetime.today(),30) #plusDate30day for add option
       
        emailtemplate = self.model.Invitation()
        randomtype = self.model.RandomType()
        closetype = self.model.CloseType()
        questionthem = self.model.QuestionTheme()
        
        if('idoption' in kw):
            print "Edit option"
            questionoption = self.model.QuestionOption.getId(kw['idoption'])
            
        questionthem = self.model.QuestionTheme.getAll(act = 1)    
        closetype = self.model.CloseType.getAll(active = 1)
        randomtype = self.model.RandomType.getAll(active = 1)
        emailtemplate, total = self.model.Invitation.getByUser(user.user_id)
        
        return dict(page='publication',
                    questionoption = questionoption,
                    emailtemplate = emailtemplate, 
                    randomtype=randomtype, 
                    closetype=closetype, 
                    questionthem=questionthem,
                    idproject = kw['idproject']
                     )
 
    @expose()
    def savepublication(self,**kw):
        print kw
        reload(sys).setdefaultencoding('utf8')    
          
        questionoption = self.model.QuestionOption(**kw)
         
        print questionoption.show_navigator  
        print questionoption.show_score 
        print questionoption.random_answer
        
        questionoption.activate_date = self.utility.startDate(questionoption.activate_date)
        questionoption.expire_date = self.utility.finishDate(questionoption.expire_date)
        questionoption.show_score = self.utility.convertToBit(questionoption.show_score)  
        questionoption.show_navigator = self.utility.convertToBit(questionoption.show_navigator)  
        questionoption.id_question_option = self.utility.setIfEmpty(questionoption.id_question_option)
        questionoption.random_answer = self.utility.convertToBit(questionoption.random_answer)
  
        print "show_navigator : %s" %questionoption.show_navigator  
        print "show_score : %s" %questionoption.show_score 
        print "random_answer : %s" %questionoption.random_answer
        
        if self.utility.isEmpty(questionoption.id_question_option) : 
            questionoption.save()
        else :
            questionoption.updateall()
       
        redirect('/managepoll/publication/indextest',params={'idproject':questionoption.id_question_project})
        
    
    @expose('managepoll.templates.publication.indextest')   
    def indextest(self,**kw):
        print kw
        return dict(page = 'indextest',idproject = kw['idproject'] )
    
    
    @expose('managepoll.templates.publication.publicationtest')
    def publicationtest(self,**kw):
        
        
        reload(sys).setdefaultencoding('utf8')      #set ค่า เป็น utf8 สำหรับฟังชั่นนี้
        user =  request.identity['user'];    

        
        questionoption = self.model.QuestionOption()
        questionoption.id_question_project = kw['idproject']
        
        questionoption.activate_date = datetime.today() #today for add option
        questionoption.expire_date = self.utility.plusDate(datetime.today(),30) #plusDate30day for add option
       
        emailtemplate = self.model.Invitation()
        randomtype = self.model.RandomType()
        closetype = self.model.CloseType()
        questionthem = self.model.QuestionTheme()
        
        if('idoption' in kw):
            print "Edit option"
            questionoption = self.model.QuestionOption.getId(kw['idoption'])
            
        questionthem = self.model.QuestionTheme.getAll(act = 1)    
        closetype = self.model.CloseType.getAll(active = 1)
        randomtype = self.model.RandomType.getAll(active = 1)
        emailtemplate, total = self.model.Invitation.getByUser(userid = user.user_id)
        
        return dict(page='publicationtest',
                    questionoption = questionoption,                  
                    emailtemplate = emailtemplate, 
                    randomtype=randomtype, 
                    closetype=closetype, 
                    questionthem=questionthem,
                    idproject = kw['idproject']
                     )
Exemplo n.º 21
0
 def __init__(self, models, session, config_type=None, translations=None):
     self.utility = Utility()
     self.model = models
     print "call init LoadDataControllers"
     print self.model
Exemplo n.º 22
0
class PublicationController(TGController):

    allow_only = in_any_group(
        'voter',
        'managers',
        msg=l_('Only for people with the "manage" permission'))

    #has_any_permission('manage','creator', msg=l_('Only for people with the "manage" permission'))

    def __init__(self, models, session, config_type=None, translations=None):
        self.utility = Utility()
        self.model = models
        print "call init LoadDataControllers"
        print self.model

    @expose('managepoll.templates.publication.index')
    def index(self, **kw):
        print kw
        return dict(page='index', idproject=kw['idproject'])

    @expose()
    def deletepublication(self, **kw):
        print kw

        status, message = self.model.QuestionOption.deleteById(kw['idoption'])

        print status
        print message

        redirect('/managepoll/publication/indextest',
                 params={'idproject': kw['idproject']})

    @expose('managepoll.templates.publication.publication')
    def publication(self, **kw):

        reload(sys).setdefaultencoding(
            'utf8')  #set ค่า เป็น utf8 สำหรับฟังชั่นนี้
        user = request.identity['user']

        questionoption = self.model.QuestionOption()
        questionoption.id_question_project = kw['idproject']

        questionoption.activate_date = datetime.today()  #today for add option
        questionoption.expire_date = self.utility.plusDate(
            datetime.today(), 30)  #plusDate30day for add option

        emailtemplate = self.model.Invitation()
        randomtype = self.model.RandomType()
        closetype = self.model.CloseType()
        questionthem = self.model.QuestionTheme()

        if ('idoption' in kw):
            print "Edit option"
            questionoption = self.model.QuestionOption.getId(kw['idoption'])

        questionthem = self.model.QuestionTheme.getAll(act=1)
        closetype = self.model.CloseType.getAll(active=1)
        randomtype = self.model.RandomType.getAll(active=1)
        emailtemplate, total = self.model.Invitation.getByUser(user.user_id)

        return dict(page='publication',
                    questionoption=questionoption,
                    emailtemplate=emailtemplate,
                    randomtype=randomtype,
                    closetype=closetype,
                    questionthem=questionthem,
                    idproject=kw['idproject'])

    @expose()
    def savepublication(self, **kw):
        print kw
        reload(sys).setdefaultencoding('utf8')

        questionoption = self.model.QuestionOption(**kw)

        print questionoption.show_navigator
        print questionoption.show_score
        print questionoption.random_answer

        questionoption.activate_date = self.utility.startDate(
            questionoption.activate_date)
        questionoption.expire_date = self.utility.finishDate(
            questionoption.expire_date)
        questionoption.show_score = self.utility.convertToBit(
            questionoption.show_score)
        questionoption.show_navigator = self.utility.convertToBit(
            questionoption.show_navigator)
        questionoption.id_question_option = self.utility.setIfEmpty(
            questionoption.id_question_option)
        questionoption.random_answer = self.utility.convertToBit(
            questionoption.random_answer)

        print "show_navigator : %s" % questionoption.show_navigator
        print "show_score : %s" % questionoption.show_score
        print "random_answer : %s" % questionoption.random_answer

        if self.utility.isEmpty(questionoption.id_question_option):
            questionoption.save()
        else:
            questionoption.updateall()

        redirect('/managepoll/publication/indextest',
                 params={'idproject': questionoption.id_question_project})

    @expose('managepoll.templates.publication.indextest')
    def indextest(self, **kw):
        print kw
        return dict(page='indextest', idproject=kw['idproject'])

    @expose('managepoll.templates.publication.publicationtest')
    def publicationtest(self, **kw):

        reload(sys).setdefaultencoding(
            'utf8')  #set ค่า เป็น utf8 สำหรับฟังชั่นนี้
        user = request.identity['user']

        questionoption = self.model.QuestionOption()
        questionoption.id_question_project = kw['idproject']

        questionoption.activate_date = datetime.today()  #today for add option
        questionoption.expire_date = self.utility.plusDate(
            datetime.today(), 30)  #plusDate30day for add option

        emailtemplate = self.model.Invitation()
        randomtype = self.model.RandomType()
        closetype = self.model.CloseType()
        questionthem = self.model.QuestionTheme()

        if ('idoption' in kw):
            print "Edit option"
            questionoption = self.model.QuestionOption.getId(kw['idoption'])

        questionthem = self.model.QuestionTheme.getAll(act=1)
        closetype = self.model.CloseType.getAll(active=1)
        randomtype = self.model.RandomType.getAll(active=1)
        emailtemplate, total = self.model.Invitation.getByUser(
            userid=user.user_id)

        return dict(page='publicationtest',
                    questionoption=questionoption,
                    emailtemplate=emailtemplate,
                    randomtype=randomtype,
                    closetype=closetype,
                    questionthem=questionthem,
                    idproject=kw['idproject'])
Exemplo n.º 23
0
class ImagesController(BaseController):
   
    def __init__(self):
        self.utility = Utility();
        self.target_file_name = self.utility.getDefaultImagePath();
        
        dh = LogDBHandler( config=config,request=request);        
        log.addHandler(dh)
        
        pass;
    
    @expose(content_type='image/png')
    def imagermc(self,key, **kw):
        reload(sys).setdefaultencoding("utf-8");
        self.result, self.message = model.SendMail.updateStatusReaded(key)
        log.info("readed mail code %s is %s(%s)" %(str(key), str(self.result), str(self.message)))
        image_file = os.path.join(  os.getcwd() +'/pollandsurvey/public/img/point.png'   );
        
        return file(image_file, "rb").read()
    
    @expose(content_type='image/png')
    def getImageScore(self,**kw):
        reload(sys).setdefaultencoding("utf-8");
        
        image_file = os.path.join('C:/temp/upload/track_feedback/images/27/issue_27.png' );
        imageId = kw.get('id');
        
        trackImage = model.Respondents.getId(imageId);
        
        return trackImage.image_file;
        
    
    @expose(content_type='image/png')
    def getImage(self,**kw):
        reload(sys).setdefaultencoding("utf-8");
        image_file = os.path.join('C:/temp/upload/track_feedback/images/27/issue_27.png' );
        imageId = kw.get('id');
        
        trackImage = model.QuestionMedia.getId(imageId);
        
     
        
       
        
        if trackImage:
            log.info( trackImage.media_path_file);
            image_file = os.path.join(trackImage.media_path_file );
            log.info( image_file);
            if not os.path.exists(image_file):
                log.info( "Found no %s" % image_file)
            else:
                
                return  file(image_file, "rb").read()
        
        
        
        return file(self.target_file_name, "rb").read()
    
    @expose(content_type='image/png')
    def getSubImage(self,**kw):
        reload(sys).setdefaultencoding("utf-8");
        image_file = os.path.join('C:/temp/upload/track_feedback/images/27/issue_27.png' );
        imageId = kw.get('id');
        
        trackImage = model.BasicMultimediaData.getByBasicDataId(imageId);
        log.info( "orig file path");
        log.info( os.path.abspath(__file__));
        if trackImage:
            log.info( trackImage.media_path_file);
            image_file = os.path.join(trackImage.media_path_file );
            log.info( image_file);
            if not os.path.exists(image_file):
                log.info( "Found no %s" % image_file)
            else:
                
                return  file(image_file, "rb").read()
           
        
        return file(self.target_file_name, "rb").read()
Exemplo n.º 24
0
class InvitationController(TGController):

    allow_only = in_any_group(
        'voter',
        'managers',
        msg=l_('Only for people with the "manage" permission'))

    #has_any_permission('manage','creator',msg=l_('Only for people with the "manage" permission'))

    def __init__(self, models, session, config_type=None, translations=None):
        self.utility = Utility()
        self.model = models

    #@require(predicates.in_any_group('creator','managers', msg=l_('Only for creator')))
    @expose('managepoll.templates.invitation.index')
    def index(self, **kw):
        user = request.identity['user']
        print user.user_id

        return dict(page='index', idproject=None)

    @expose('managepoll.templates.invitation.invitation')
    def invitation(self, **kw):

        print kw

        reload(sys).setdefaultencoding("utf-8")
        invitation = self.model.Invitation()
        self.emailtemplate = self.model.EmailTemplate()
        if ('idinvitation' in kw):
            print kw['idinvitation']
            #
            invitation = self.model.Invitation.getId(kw['idinvitation'])

        else:
            self.emailtemplate = self.model.EmailTemplate.getTemplateBy(5)

            invitation.name_content = self.emailtemplate.sender
            invitation.from_name = self.emailtemplate.sender
            invitation.subject = self.emailtemplate.subject
            invitation.content = self.emailtemplate.content_template

        return dict(page='invitation', invitation=invitation, idproject=None)

    @expose()
    def saveinvitation(self, **kw):
        user = request.identity['user']
        reload(sys).setdefaultencoding('utf8')

        invitation = self.model.Invitation(**kw)
        invitation.user_id = user.user_id

        invitation.id_question_invitation = self.utility.setIfEmpty(
            invitation.id_question_invitation)

        if self.utility.isEmpty(invitation.id_question_invitation):
            print "save"
            invitation.save()
        else:
            print "update"
            invitation.updateall()

        redirect('/managepoll/invitation/indextest')

    @expose('managepoll.templates.invitation.indextest')
    def indextest(self, **kw):
        user = request.identity['user']
        print user.user_id

        return dict(page='invitation', idproject=None)

    @expose('managepoll.templates.invitation.invitationtest')
    def invitationtest(self, **kw):

        print kw

        reload(sys).setdefaultencoding("utf-8")
        invitation = self.model.Invitation()
        self.emailtemplate = self.model.EmailTemplate()
        if ('idinvitation' in kw):
            print kw['idinvitation']
            #
            invitation = self.model.Invitation.getId(kw['idinvitation'])

        else:
            self.emailtemplate = self.model.EmailTemplate.getTemplateBy(5)

            invitation.name_content = self.emailtemplate.sender
            invitation.from_name = self.emailtemplate.sender
            invitation.subject = self.emailtemplate.subject
            invitation.content = self.emailtemplate.content_template

        return dict(page='invitationtest',
                    invitation=invitation,
                    idproject=None)

    @expose()
    def deleteinvitation(self, **kw):
        print kw
        self.model.Invitation.deleteById(kw['idinvitation'])

        redirect('/managepoll/invitation/indextest')
class AnswerQuestionController(BaseController):#RestController): #
    
    def __init__(self):
        self.utility = Utility();
        self.urlUtility = URLUtility();
         
        
        
        self.sourceHtml = model.SystemEnvironment.getScoreViewHtml();
        self.answerQuestionService = AnswerQuestionService(mymodel = model)
        
        dh = LogDBHandler( config=config,request=request);        
        log.addHandler(dh)
        
       
    
    @expose()
    def _default(self, *args, **kw):
        return 'This page is not ready'
    
    def _before(self, *args, **kw):
        tmpl_context.project_name = 'pollandsurvey'
    
            
    @expose('pollandsurvey.templates.view.multiquestion')
    def questionnaire(self,key=0,ready='no',**kw):
        reload(sys).setdefaultencoding('utf8')
        log.info("key %s , ready %s" %( key,ready) );
        print ("key %s , ready %s" %( key,ready) );
        self.header = '';
        self.footer = '';
        self.nextQuestion ='';
        self.template ='';
        self.userName='';
        
        
        self.respondents = model.Respondents.getByKey(keyGen=key);
        if self.respondents :
            
            self.urlReply = self.urlUtility.URL_REPLY.format( model.SystemEnvironment.getServerUrl() , str(self.respondents.id_question_project), str(self.respondents.id_question_option), str(self.respondents.id_voter))  ; #request.application_url
            log.info("iframe url to %s" %self.urlReply);
            
            #check finish
            self.isRedirect ,self.redirect  = self.answerQuestionService.checkFinish(respondent = self.respondents, urlUtility = self.urlUtility)
            if self.isRedirect:
                redirect(self.redirect) ;
            
            #check Expire
            self.questionOption,self.redirect = self.__checkOptionExpired(self.respondents.id_question_option);    
            
            
            if str(ready).lower() == 'no':    
                #check have welcome page
                if( not self.utility.isEmpty(self.questionOption.welcome_message) ) :
                    #redirect('/ans' + '/welcome?id='+ str(self.questionOption.id_question_option) );
                    log.info("show message welcome : ");
                    redirect( self.urlUtility.URL_WELCOME.format(key = str(key)) )#   self.URL_WELCOME_NEW.format(str(key))  );
                else:
                    log.info("show questionnaire : ");
                    self.template =  self.questionOption.theme.template;
                    override_template(AnswerQuestionController.questionnaire, self.template) ;    
                    
            elif str(ready).lower() == 'yes':
                self.header = self.questionOption.header_message;
                self.footer = self.questionOption.footer_message;
                self.urlName = self.utility.spritValue(request.path_info,'/');
                self.template =  self.questionOption.theme.template
                if(len(self.urlName) >= 1 ) :
                    self.nextQuestion = '/' + self.urlName[0] + '/saveQuestion' + '?id='+ str(self.questionOption.id_question_option);
                
                
                if(self.template is not None and len(self.template) > 0):    
                    log.info("template used : %s"   %self.template );     
                    
                    override_template(AnswerQuestionController.questionnaire, self.template) 
                    
                self.ip=request.environ.get("X_FORWARDED_FOR", request.environ["REMOTE_ADDR"]);
                self.browser = request.environ.get('HTTP_USER_AGENT');
                
            self.header = self.questionOption.header_message;
            self.footer = self.questionOption.footer_message;
            self.urlName = self.utility.spritValue(request.path_info,'/');
            self.template =  self.questionOption.theme.template 
            if self.respondents.voter:
                self.userName =  "******"%(self.respondents.voter.firstname,self.respondents.voter.lastname);            
        else:
            log.warning("find not found key %s" %str(key));
            redirect(self.urlUtility.URL_EXPIRED) ;       
        
        print "header : %s" %self.header
        return dict(page='view', header = Markdown(self.header).convert() , 
                        footer = Markdown(self.footer).convert()  , 
                        action = self.nextQuestion, template= self.template,
                        #urldata = self.URL_GETDATAQUESTION.format(self.idPublic),
                        urldata =  self.urlUtility.URL_GETDATAQUESTION.format(key=str(key)),#  self.URL_GETDATAQUESTION.format(key),  
                        idproject = self.questionOption.id_question_option ,
                        idresp = self.respondents.id_respondents,
                        username = self.userName,
                        shownavigator = bool(self.questionOption.show_navigator) ); 
    
     
    
    @expose('pollandsurvey.templates.view.welcome')
    def welcome(self,key=0,came_from=lurl('/')):
        reload(sys).setdefaultencoding("utf-8");
         
        
        log.info('preview id : ' + str(key));
        
        self.respondents = model.Respondents.getByKey(key);
        #self.idProject,self.idPublic,self.idVoter,self.redirect = self.__checkExpire(id);
        if (self.respondents):
        
            self.welcome_message = '';
            
            self.questionOption,self.redirect = self.__checkOptionExpired(self.respondents.id_question_option);
                    
            self.welcome_message= self.questionOption.welcome_message;
            self.nextQuestion  = '';
             
            self.urlName = self.utility.spritValue(request.path_info,'/');
             
            if(len(self.urlName) >= 1 ) :
                #self.nextQuestion = '/' + self.urlName[0]+ '?id='+ str(self.questionOption.id_question_option);
                #self.nextQuestion = '/' + 'ans/reply/'+  str(self.questionOption.id_question_option);
                #self.nextQuestion = self.URL_REPLY.format(id)
                self.nextQuestion = self.urlUtility.URL_REPLY_QUESTIONNAIRE.format(key=str(key)); 
        else:
            log.error("find not found respondent with key %s ", str(key));
            redirect(self.urlUtility.URL_EXPIRED) ;       
            
               
            
        #self.welcome_message
        return dict(page='view', ready = 'yes',welcome_message = Markdown(self.welcome_message).convert(), nextQuestion= self.nextQuestion);
    
            
     
    
    @expose('pollandsurvey.templates.view.goodbye')
    def thankyou(self,key=0,came_from=lurl('/')):
        reload(sys).setdefaultencoding("utf-8");
        
        log.info('thankyou preview id : %s' %str(key));
        self.isRedirect = True
        self.goodbye = '';
        self.nextQuestion  = '';
        self.urlRedirect = ''; 
        self.showScore = False
        self.respondents = model.Respondents.getByKey(keyGen=key);
        if(self.respondents):
            self.urlName = self.utility.spritValue(request.path_info,'/');
            log.info( "path %s" %self.urlName)
            self.questionOption = self.respondents.question_option
            if self.questionOption :
                self.goodbye= self.questionOption.end_message
                self.showScore = self.utility.convertToBool(self.questionOption.show_score)
                self.urlRedirect = self.questionOption.redirect_url
                if self.utility.convertToBool(self.respondents.redirect_other_url):
                    self.urlRedirect = self.questionOption.redirect_other_url
                
                self.isRedirect = False
            
            self.projectType = self.respondents.question_project.id_question_project_type
            del self.questionOption
        
        if self.isRedirect :
            log.error("find not found respondent with key %s " % str(key));
            redirect(self.urlUtility.URL_EXPIRED) ;  
            
    
        return dict(page='goodbye', ready = 'yes',goodbye = Markdown(self.goodbye).convert(),nextQuestion = self.nextQuestion ,urlRedirect= self.urlRedirect,
                    showScore = self.showScore  ,projectType = self.projectType,imageId = self.respondents.id_respondents);
    
    
    
    @expose('json')
    def getDataPreview(self, key=0,   *args, **kw):   
            
        reload(sys).setdefaultencoding("utf-8");
        log.info("function getDataPreview");
        
        self.respondents = model.Respondents.getByKey(key);
        
        if(self.respondents is None):
            return dict(questions = [],timer = 0);
        
        
        self.idProject=self.respondents.id_question_project;
        self.idPublic=self.respondents.id_question_option;
        self.questionOption = model.QuestionOption.getId(self.idPublic);
        
        log.info("idProject : %s,  idPublic : %s, idVoter : %s, id_respondents : %s"  %( str(self.idProject), str(self.idPublic), str(self.respondents.id_voter) , str(self.respondents.id_respondents) ) );
        
               
        #get old question
        self.answerQuestionService.renewQuestionForUser( respondents = self.respondents, id_close_type = self.questionOption.id_close_type)
        
        self.listReply = model.RespondentReply.listQuestionForUser(self.respondents.id_respondents); #questionobject by id_respondents
        self.respondents.respondent_data = datetime.now();
        
        question = [];
        self.listquestion = [];
        self.order =1
        log.info("Random Question And Answer : " );
        
        if( len(self.listReply) > 0 ):
            
            log.info("Random new");
            self.listquestion = self.answerQuestionService.getQuestionGroupWithReply(listReply= self.listReply)
        else:
          
            log.info( "Get New Question")             
            self.listquestion = self.answerQuestionService.getQuestionGroupWithQuestionOption(self.questionOption)
            self.answerQuestionService.createQuestionForUser(listQuestion=self.listquestion, id_close_type= self.questionOption.id_close_type)
            
        self.listquestion, self.order = self.answerQuestionService.genSeq(listQuestion = self.listquestion)
                 
        
        #question = self.__randomQuestionAndAnswer(question,self.questionOption);    
        #self.__setSequenceQuestion(question); 
        
         
        questions = [];
        questions.append({'id': self.idProject, 'question' : self.listquestion, 'total': self.order});
        
        return dict(questions = questions,timer = self.questionOption.duration_time);
    
    
    @expose('json')
    def saveQuestion(self, *args, **kw):
        reload(sys).setdefaultencoding("utf-8");
        log.info( "function save Question answer");
        log.info( request.body);
        
        self.saveQuests = JsontoObject(json.loads(request.body, encoding=request.charset))        
        self.finished = self.saveQuests.finished
        self.idresp = None
        self.redirect = ''
        
        if (len(self.saveQuests.value) >0):
            for item in self.saveQuests.value:
                if(item):
                    self.idresp = item.idresp
                    self.questionOption,self.redirect = self.__checkOptionExpired(item.idproject,False);#check Expired
                    self.respondent,self.redirect = self.__checkRespondentFinished( None,  None,item.idresp,False);#check finished
                    if(self.respondent):
                        self.respondent.finished = self.finished;
                        self.respondent.finished_date = datetime.now();
        
                        self.question = model.Question.getById(item.id);#getQuestion                         
                        if(self.question):
                            self.respondentreply = model.RespondentReply.getByRespondentAndQuestion(item.idresp,item.id);
                            
                            
                            if (self.respondentreply is None):
                                self.respondentreply = model.RespondentReply(id_respondents = item.idresp,id_question = item.id);                                
                                self.respondentreply.save();
                                
                                log.info("save answer respondentreply : " +str( self.respondentreply.id_respondents ) + " and " + str( self.respondentreply.id_question ) + " success");
                            
                            if (len(self.respondentreply.childenAnswer) == 0):
                                #save
                                for v in item.value:                                    
                                    self.replyquestion = model.ReplyBasicQuestion(id_resp_reply = self.respondentreply.id_resp_reply,
                                                                                  id_basic_data = v.id,
                                                                                  answer_text = v.value
                                                                                  ); 
                                    self.replyquestion.save();
                                    v = None
                                    del v
                                    log.info("save answer replyquestion : " +str( self.respondentreply.id_resp_reply ) + " and " + str( self.replyquestion.id_basic_data ) + " success");
                            else:
                                log.info('user %s do this question : %s Already'%(item.idresp,item.id));
                        else:
                            log.info('find not found question id : : %s' %(item.id));
                    else:
                        log.info('find not found respondent id : : %s' %(item.idresp));
                    
                    item = None
            
            model.DBSession.flush()
            #calculate score        
            if(self.finished):  
                log.info('finished : calculate score ')
                
                model.Respondents.updateScoreByIdRespondents(self.idresp)
                model.Respondents.updatePersonalityScoreByIdRespondents(self.idresp)
                transaction.commit()
                self.answerQuestionService.createScoreFileImage(self.idresp)
                #self.__createScoreFile(self.idresp);
                self.redirect = self.urlUtility.URL_GOODBYE.format( key=  self.utility.splitNameWithOutExtention(basename(request.environ.get("HTTP_REFERER" )))  );
        
        return dict(success = True,redirect = self.redirect, finished = self.finished  );
    
    
    @expose('json')
    def getresult(self, *args, **kw):
        reload(sys).setdefaultencoding("utf-8");
        self.result = model.Respondents.getResultPersonality(id_respondents=124)
        #for r in self.result:
        print   self.result
     
    
    
    @expose('pollandsurvey.templates.certificate.index')   
    def viewCertScore(self,key=0,**kw):
        reload(sys).setdefaultencoding('utf8')
        certificateUser = dict(
                               title='Certificate Of Jobsmatcher',
                               label_score='scored', 
                               label_date='Date', 
                               name='', 
                               score='0/0', 
                               type='', 
                               finishDate=''
                               )
        self.respondents = model.Respondents.getId(key)
        
        if self.respondents:
            self.result = model.Respondents.getScoreByIdRespondents(id_respondents=key)
            certificateUser['name'] =   (' ').join([self.respondents.voter.prefix, self.respondents.voter.firstname, self.respondents.voter.lastname])
            certificateUser['finishDate']  =  self.utility.getDateByFormat(date = self.respondents.finished_date)  
            certificateUser['score'] = self.result
            certificateUser['type'] = self.respondents.question_project.name
            log.info( "respondents %s , score %s" %(key, self.result))
        
        return dict(page = 'certificate',certificateUser = certificateUser)
    
    def __checkExpire(self,id):
        #sprint 10.2.1.0.html     idproject.idpublic.idvoter.
        self.value = self.utility.spritValue(id,'.');
         
        self.idProject =0;
        self.idPublic = 0;
        self.idVoter = 0;
        
        self.redirect = '';
        
        
        
        if(len(self.value)  == 4):
            self.idProject =self.value[0];
            self.idPublic = self.value[1];
            self.idVoter = self.value[2];
        else:
            self.idProject =None;
            self.idPublic = None;
            self.idVoter = None;
            
            log.info('parameter not have 4 parameter : %s', ','.join(self.value));
            self.redirect = self.urlUtility.URL_EXPIRED;
            redirect(self.urlUtility.URL_EXPIRED) ;
        
        self.voter = model.Voter.getId(self.idVoter);
        if(self.voter is None):
            log.info('find not voter in id : %s',self.idVoter);
            self.redirect = self.urlUtility.URL_HOME;
            redirect(self.urlUtility.URL_HOME) ;
        
        self.project = model.QuestionProject.getId(self.idProject);
        if(self.project is None):
            log.info('find not project in id project : %s',self.idProject);
            self.redirect = self.urlUtility.URL_HOME;
            redirect(self.urlUtility.URL_HOME) ;
            
        return self.idProject,self.idPublic,self.idVoter, self.redirect;
            
    def __checkOptionExpired(self,idPublic,isRedirect = True):
        #print 'public option id ',idPublic;
        self.questionOption = model.QuestionOption.getId( idPublic);           
        self.redirect = '';
        if  self.questionOption is None or ( not self.utility.isActiveFromDate(None,self.questionOption.activate_date,self.questionOption.expire_date) ):
            self.redirect = self.urlUtility.URL_EXPIRED;
            if (isRedirect):
                #print 'redirect ',self.URL_EXPIRED; 
                redirect(self.urlUtility.URL_EXPIRED) ;
      
                
        #print 'id option : ', self.questionOption.welcome_message;
        
        return self.questionOption,self.redirect;    
            
    def __checkRespondentFinished(self,idVoter,idPublic,idResp,isRedirect = True): 
        self.respondent = None;
        self.redirect = '';
        if(idVoter and idPublic):           
            self.respondent = model.Respondents.getByVoterAndPublicId(idVoter,idPublic);
        elif (idResp):           
            self.respondent = model.Respondents.getId(idResp);            
        if(self.respondent  is not None and self.respondent.finished == CheckFinish.finished.value): #finished = 1            
            log.info('voter finished in id public : %s',idPublic);
            self.redirect = self.urlUtility.URL_THANKYOU;
            if (isRedirect):
                redirect(self.urlUtility.URL_THANKYOU) ;
        elif (self.respondent is None):           
            log.error("System can not find idVoter : %s , idPublic : %s" , idVoter, idPublic);
            
            redirect(self.urlUtility.URL_THANKYOU) ;
        
        return self.respondent,self.redirect;
    
    def __getQuestion(self,idPublic,questionOption):
        
        question = [];
        #get Project Option
        
        if self.questionOption :
            #get Question 
            self.listQuestions = model.Question.getByProjectId(questionOption.id_question_project);
            
            
            #get to object json
            for self.question in self.listQuestions:
                question.append(self.question.to_json(randomAnswer = questionOption.random_answer));
            
            
            
            #clear sequence 
               
        return question ;
    
    def __getQuestionFromReply(self,reply,questionOption):
        question = [];
        for re in reply:
            #re.question
            question.append(re.question.to_json(randomAnswer= questionOption.random_answer));
        
        return question;
    
    def __randomQuestionAndAnswer(self,question,questionOption):       
        #option Randon Question       
        if( questionOption.id_fix_random_type == RandomType.simple_random.value):   #id_fix_random_type == 2          
            question = random.sample(question,len(question));#,self.questionOption.use_question_no );
        
        
        question = question[0:questionOption.use_question_no];
            
        return question;
    
    def __setSequenceQuestion(self,question):
        row = 1;
        for q in question:
            q['seq'] = row;
            row = row +1; 
        row =None;
        
        return question;
Exemplo n.º 26
0
class SurveyController(BaseController):
    
    def __init__(self):
        self.utility = Utility();
        self.urlUtility = URLUtility();
        self.UPLOAD_DIR = config['path_upload_file'] ;
        
        dh = LogDBHandler( config=config,request=request);
        
        log.addHandler(dh)
    
    def _before(self, *args, **kw):
        tmpl_context.project_name = "pollandsurvey"
    
    #proved
    @expose('pollandsurvey.templates.survey.index')
    @require(predicates.in_any_group('creator','managers', msg=l_('Only for creator')))
    def index(self, *args, **kw):
        """Handle the front-page."""
        reload(sys).setdefaultencoding("utf-8");
        log.info("survey controller index");
        return dict(page='index')
    
    #proved
    @expose('pollandsurvey.templates.surveyjs.index')
    #@expose('pollandsurvey.templates.listsurvey.index')
    @require(predicates.not_anonymous(  msg=l_('Only for Authen')))
    def listsetup(self, came_from=lurl('/'), *args, **kw):
        """Handle the front-page."""
        reload(sys).setdefaultencoding("utf-8");
         
        return dict(page='survey')
    
    @expose('pollandsurvey.templates.surveyjs.manageproject')
    @require(predicates.not_anonymous(  msg=l_('Only for Authen')))
    def manage(self,  projectId,came_from=lurl('/'), **kw):
        """Handle the front-page."""
        reload(sys).setdefaultencoding("utf-8");
      
        self.user =  request.identity['user']; 
        self.project, self.total = model.QuestionProject.getAllByUser(1,self.user.user_id,0,1 );
         
        if len(self.project) == 0:
            flash(_('Please create a project.'), 'warning')
            raise HTTPFound(location='/survey/listsetup');
        
        
        
        return dict(page='manageproject')

    #proved
    @expose('json')
    @require(predicates.not_anonymous(  msg=l_('Only for Authen')))
    def getProjectByUser(self, came_from=lurl('/'),*args, **kw):
        reload(sys).setdefaultencoding("utf-8");
        
        user =  request.identity['user']; 
        
        quest_project = model.QuestionProject.getAllByUser(1,user.user_id);
        
        log.info("getProjectByUser");
        
        return dict(survey=quest_project , total = len(quest_project));
    
    
    
    #proved        
    @expose('json')
    def deleteProject(self, came_from=lurl('/'), *args, **kw):
        reload(sys).setdefaultencoding("utf-8");
        self.success = True;
        self.message = "success";
        
        self.df = json.loads(request.body, encoding=request.charset);
        self.idProject = self.df.get('id_question_project');
        self.listQuestion = model.Question.getByProjectId(self.idProject);
        
        self.listQuestionGroup = model.QuestionGroup.getByProject(self.idProject);
        for questionGroup in self.listQuestionGroup:
            #remove sur_map_question_group
            model.MapQuestionGroup.deleteByQuestionGroup(questionGroup.id_question_group)
            #remove question_group
             
            model.QuestionGroup.delete(questionGroup)
            del questionGroup
        
        for self.question in self.listQuestion:
            if(self.question):
                self.idQuestion = self.question.id_question;
                model.Question.deleteQuestoin(self.idQuestion);
        
        
        
        model.QuestionProject.deleteById(self.idProject);
        
        return dict(success=self.success, message = self.message);
    
    #proved        
    @expose('json')
    @require(predicates.not_anonymous(  msg=l_('Only for Authen')))
    def saveProject(self, came_from=lurl('/'), *args, **kw):
        reload(sys).setdefaultencoding("utf-8");
        self.success = True;
        self.message = "success";
        
        print 'Session Language : %s' %(ManageSession.getLanguage())
        
        self.project = model.QuestionProject(**kw);
        self.project.id_question_project = self.utility.setIfEmpty(self.project.id_question_project)
        user =  request.identity['user']; 
        self.project.user_id =  user.user_id;
        
        if self.project.id_question_project :
            self.project.updateall();
        else:
            self.project.save();
            self.addQuestionGroup(  id_question_project=self.project.id_question_project, 
                                    question_group_name='default', 
                                    question_group_description='default',
                                    id_question_result_group = '', 
                                    order=0  );
            
        
        return dict(success=self.success, message = self.message, project_id=self.project.id_question_project);
    
    #proved
    @expose('json')
    def deleteQuestion(self, came_from=lurl('/'), *args, **kw):
        reload(sys).setdefaultencoding("utf-8");
        
        self.success = True;
        self.message = "Save Success";
        
        df = json.loads(request.body, encoding=request.charset);
        
        log.info(df);
        idQuestion = df.get('id_question');
        self.success, self.message = model.Question.deleteQuestoin(idQuestion);

        
        return dict(success=self.success, message = self.message);
   
    
    #proved    
    @expose('json',content_type="text/plain" )
    @require(predicates.not_anonymous(  msg=l_('Only for Authen')))
    def addQuestion(self, came_from=lurl('/'), *args, **kw):          
        reload(sys).setdefaultencoding("utf-8");
        self.success = True;
        self.message = "success";
        self.result = True;
        log.info("add Question");
        self.dataValue = kw;
        
        log.info(kw);
        log.info(args);
        
        user =  request.identity['user']; 
        #model.Question.createQuestion(self.dataValue,user.user_id);
        log.info("check");
        self.isCreate = self.dataValue.get('id_question') is None or ( len(self.dataValue.get('id_question')) == 0 );
        self.id_question_type  = self.dataValue.get('id_question_type')
        #create or update question       
        
        
        self.questionObject = QuestionObject(**kw)
        
        question = self.questionObject.question
        question.user_id = user.user_id;
        question.id_question = self.utility.setIfEmpty(question.id_question)
        
        if question.id_question :
            question.updateOrdering();
            question.updateall();
        else:
            question.save();
        
        
        log.info("save Question");
            
        # create or update questionMedia    
        imageFile =  self.questionObject.image_upload   #self.dataValue.get('image_upload'); 
        
        
        if type(imageFile) is types.InstanceType:
         
            self.file_name = imageFile.filename;
            self.file_data = imageFile.value;
            self.target_file_name = self.utility.joinPathFileAndCreatePath(self.UPLOAD_DIR, str(question.id_question), self.file_name);
              
            self.utility.saveFile(self.target_file_name,self.file_data);  
            
            questionMedia = model.QuestionMedia(id_question = question.id_question,  value = self.file_name, media_type = imageFile.type, media_path_file = self.target_file_name )
            
            
            
            questionMedia = model.QuestionMedia.getId(question.id_question);
            if(questionMedia is None):
                questionMedia = model.QuestionMedia();
                questionMedia.id_question = question.id_question;
            else:
                self.utility.removeFile(questionMedia.media_path_file);
                log.info('remove file : ' + questionMedia.media_path_file );
            questionMedia.value = self.file_name;
            questionMedia.media_type = imageFile.type;
            questionMedia.media_path_file = self.target_file_name;
            questionMedia.save();
            
            log.info("save questionMedia");
            
        
        
        #Step 2 create         
        datagrid  =    json.loads(self.questionObject.datagrid );    #json.loads(self.dataValue.get('datagrid'));   
        for basic_datas in datagrid:            
            log.info(basic_datas);
            self.isCreate = basic_datas.get('id_question') is not None and len( str(basic_datas.get('id_question')).strip() ) > 0 ;
            
            basicData = model.BasicData();
            basicQuestion = model.BasicQuestion();
            log.info("-----------------------Basic data-----------------------------------");
            if (not self.isCreate ):
                log.info ("create basic data");                
                basicData.id_basic_data_type = self.id_question_type; #image
                basicData.save();  
                
                log.info ("create basic question");
                basicQuestion.id_question = question.id_question;
                basicQuestion.id_basic_data = basicData.id_basic_data;
                basicQuestion.answer =   basic_datas.get('answer') ;# ({True: True, False: False}[ basic_datas.get('answer') in 'true']);
                basicQuestion.score =   basic_datas.get('score') ;
                basicQuestion.order = basic_datas.get('seq');            
                basicQuestion.id_question_result     = basic_datas.get('id_question_result');       
                basicQuestion.save();              
            else:
                log.info ("update basic data : " + str( basic_datas.get('id_basic_data')) );                
                basicData.id_basic_data = basic_datas.get('id_basic_data');
                basicQuestion  = model.BasicQuestion.getByQuestionAndBasic(question.id_question, basicData.id_basic_data);
                if(basicQuestion):
                    basicQuestion.answer =   basic_datas.get('answer') ; 
                    basicQuestion.score =   basic_datas.get('score') ;
                    basicQuestion.order = basic_datas.get('seq');  
                    basicQuestion.id_question_result     = basic_datas.get('id_question_result')  
                else:
                    log.info("error load basicQuestion");
           
            log.info("------------------------basic Data type----------------------------------" );
            log.info('self.id_question_type : ' + str(self.id_question_type)  + ' type : ' + type(self.id_question_type).__name__ ) ;
           
            if (self.id_question_type and int(self.id_question_type) in  [QuestionType.single_choice.value,
                                                                           QuestionType.multi_choice.value,
                                                                           QuestionType.drop_down_menu.value,
                                                                           QuestionType.text.value,
                                                                           QuestionType.multitext.value,
                                                                           QuestionType.number.value
                                                                           ]):  # 1,2,3,5,6,7              
                          
               
                log.info("case text");
                basicText = model.BasicTextData();
                if (not self.isCreate ):
                    log.info("create basic text");
                    basicText.id_basic_data = basicData.id_basic_data;
                    basicText.value = basic_datas.get('value');
                    basicText.save();
                else:
                    log.info("update basic text");
                    basicText = model.BasicTextData.getByBasicDataId(basicData.id_basic_data);
                    if(basicText):                
                        basicText.value = basic_datas.get('value');                       
                    else:
                        log.info("error load BasicTextData");    
                
            elif (self.id_question_type and int(self.id_question_type) == QuestionType.image.value   ): #4           
                log.info("case image");                
                answerimage = self.dataValue.get('answer_image'); #self.questionObject.answer_image
                log.info(basic_datas.get('answer_image'));
                log.info(type(answerimage));
                
                log.info('basicData.id_basic_data : ' + str(basicData.id_basic_data));
                
                if (type(answerimage) is types.InstanceType or  type(answerimage) is types.ListType) :
                    if  type(answerimage) is types.InstanceType:
                        log.info('single file');
                        log.info(answerimage.type);
                        file = answerimage;
                        if( self.utility.isPartOf(file.filename,basic_datas.get('answer_image')) ):
                        #if (basic_datas.get('answer_image') == file.filename ) :
                            basicMedia = model.BasicMultimediaData();
                            self.file_name = file.filename;
                            self.file_data = file.value;
                            self.media_type = file.type;
                            self.target_file_name= self.utility.joinPathFileAndCreatePath(self.UPLOAD_DIR, str(question.id_question), self.file_name);
                            self.utility.saveFile(self.target_file_name,self.file_data); 
                            
                            if ( not self.utility.isNumber( basic_datas.get('id_basic_data') ) ):
                                log.info('create basic media');
                                basicMedia.id_basic_data = basicData.id_basic_data;
                                basicMedia.value = self.file_name;
                                basicMedia.media_type = self.media_type;
                                basicMedia.media_path_file = self.target_file_name;
                                basicMedia.save();
                            else:
                                log.info('update basic media');
                                basicMedia = model.BasicMultimediaData.getByBasicDataId(basic_datas.get('id_basic_data') );
                                self.utility.removeFile(basicMedia.media_path_file);
                                basicMedia.value = self.file_name;
                                basicMedia.media_type = self.media_type;
                                basicMedia.media_path_file = self.target_file_name;
                                
                    else:
                        for file in answerimage:
                            log.info('type list file');
                            log.info(type(file));
                            if type(file) is not types.UnicodeType:
                                
                                #print file.type;
                                if( self.utility.isPartOf(file.filename,basic_datas.get('answer_image')) ):
                                #if (basic_datas.get('answer_image') == file.filename) :
                                    self.file_name = file.filename;
                                    self.file_data = file.value;
                                    self.media_type = file.type;
                                    self.target_file_name= self.utility.joinPathFileAndCreatePath(self.UPLOAD_DIR, str(question.id_question), self.file_name);
                                    self.utility.saveFile(self.target_file_name,self.file_data); 
                                    basicMedia = model.BasicMultimediaData();
                                    if ( not self.utility.isNumber( basic_datas.get('id_basic_data') ) ):
                                        log.info('create basic media');
                                        basicMedia.id_basic_data = basicData.id_basic_data;
                                        basicMedia.value = self.file_name;
                                        basicMedia.media_type = self.media_type;
                                        basicMedia.media_path_file = self.target_file_name;
                                        basicMedia.save();
                                    else:
                                        log.info('update basic media');
                                        basicMedia = model.BasicMultimediaData.getByBasicDataId(basic_datas.get('id_basic_data') );
                                        self.utility.removeFile(basicMedia.media_path_file);
                                        basicMedia.value = self.file_name;
                                        basicMedia.media_type = self.media_type;
                                        basicMedia.media_path_file = self.target_file_name;
                  
                else:
                    log.info("Other type");
                    
                pass;
             
            
        log.info("save object");
        
        
        
        return dict(success=self.success, message = self.message, result = self.result);
    
    
    #proved
    @expose('json')
    def updateQuestionData(self, **kw):
        reload(sys).setdefaultencoding("utf-8");
       
        self.success = True;
        self.message = "success";
        
        #log.info(request.method );
        #log.info(request.params );
        
        self.df = json.loads(request.body, encoding=request.charset);
        self.data = JsontoObject(self.df);
        
        for obj in self.data.dict:
            print obj.to_json()
            self.success, self.message = model.Question.updateOrderById(order=obj.order, id= obj.id_question );
            
        
        #for d in self.df:
        #    self.success, self.message = model.Question.updateOrderById(d.get(u'order'), d.get(u'id_question'));
        
        return dict(success=self.success, message = self.message,  survey = self.data.to_json());
    
    #proved
    @expose('json')
    def deleteMediaQuestion(self, came_from=lurl('/'), *args, **kw):
        reload(sys).setdefaultencoding("utf-8");
        self.success = True;
        self.message = "success";
        log.info('---------1--------------');
        
        df = json.loads(request.body, encoding=request.charset);
        
        model.QuestionMedia.deleteByQuestion(df.get('id'));
        del df
        return dict(success=self.success, message = self.message);
    
    #proved
    @expose('json')
    def deleteQuestionData(self, came_from=lurl('/'), *args, **kw):
        reload(sys).setdefaultencoding("utf-8");
        self.success = True;
        self.message = "success";
        log.info('---------1--------------');
        
        df = json.loads(request.body, encoding=request.charset);
        # remark : remove file
        self.success,self.message =  model.BasicQuestion.deleteData(df.get('id'), deleteBasicQuestion=True) ;
        del df
        return dict(success=self.success, message = self.message);
    
    #proved
    @expose('json')
    def addOptions(self, came_from=lurl('/'), *args, **kw):                   
        reload(sys).setdefaultencoding("utf-8");
        self.success = True;
        self.message = "success";
        self.result = True;   
        
        self.optionobject = OptionObject(**kw);    
        self.option = self.optionobject.options     
       
        self.option.random_answer = self.utility.convertToBit(self.option.random_answer)
        self.option.activate_date = self.utility.startDate( self.option.activate_date)
        self.option.expire_date = self.utility.finishDate( self.option.expire_date)
        self.option.show_score = self.utility.convertToBit( self.option.show_score ) 
        self.option.show_navigator = self.utility.convertToBit( self.option.show_navigator ) 
        self.option.id_question_option = self.utility.setIfEmpty(self.option.id_question_option)    
        
        if (self.utility.isEmpty(self.option.id_question_option)):
            log.info("save option")
            self.option.save()
        else:
            log.info("update option")
            self.option.updateall()
        
        self.groupamount = model.NumberQuestionGroup();        
        #number_question != 0        
        if self.optionobject.number_question:            
            for group_amount in self.optionobject.number_question :                
                data = JsontoObject(group_amount); 
                              
                if (not self.utility.isNumber(data.id_question_group_amount)) :                    
                    data.id_question_group_amount = None  
                                                    
                self.groupamount.id_question_group_amount = data.id_question_group_amount;
                self.groupamount.id_question_option = self.option.id_question_option;
                self.groupamount.id_question_group =  data.id_question_group;                
                if data.amount == '' :
                    data.amount = 0                    
                self.groupamount.amount = data.amount; 
                self.groupamount.updateall()           
                
        #number_question = 0        
        else :           
            self.numberquestiondata = []  
            self.group_project = []
            self.numberquestiondata = model.NumberQuestionGroup.getByOptionFirst(self.option.id_question_option); 
            self.group_project = model.QuestionGroup.getByProject(self.option.id_question_project);      
                 
            if self.optionobject.project_type == "1":#poll
                           
                #edit poll              
                if self.numberquestiondata:                    
                    self.groupamount.id_question_group_amount = self.numberquestiondata.id_question_group_amount;
                    self.groupamount.id_question_option = self.numberquestiondata.id_question_option;
                    self.groupamount.id_question_group =  self.numberquestiondata.id_question_group;
                    self.groupamount.amount = self.optionobject.use_question_no;                    
                    self.groupamount.updateall()                    
                #new poll 
                else : 
                    for question_group in self.group_project:                    
                        self.groupamount.id_question_group_amount = None;
                        self.groupamount.id_question_option = self.option.id_question_option;
                        self.groupamount.id_question_group =  question_group.id_question_group;
                        self.groupamount.amount = self.optionobject.use_question_no;                        
                        self.groupamount.updateall()
            else :  #not poll                               
                if (not self.numberquestiondata) :  #add                  
                    for question_group in self.group_project:                                       
                        self.groupamount.id_question_group_amount = None;
                        self.groupamount.id_question_option = self.option.id_question_option;
                        self.groupamount.id_question_group =  question_group.id_question_group;
                        self.groupamount.amount = len(question_group.questions);                          
                        self.groupamount.updateall()   
        return dict(success=self.success, message = self.message,result = self.result);
    
    #proved
    @expose('json')
    def deleteOptions(self, came_from=lurl('/'), *args, **kw):
        reload(sys).setdefaultencoding('utf8')
        
        self.success = True;
        self.message = "Save Success";
        df = json.loads(request.body, encoding=request.charset);
        log.info(df);
        
        idQuestion = df.get('id_question_option');
        self.success, self.message = model.QuestionOption.deleteById(idQuestion);
        del df
        return dict(success=self.success, message =self.message);
    
    #proved
    @expose('json')
    def addInvitation(self, **kw):
        reload(sys).setdefaultencoding('utf8')
        
        log.info( kw);
        
        self.success = True;
        self.message = "Save Success";
        self.result = True;
        try:
            user =  request.identity['user'];
            
            kw['user_id'] = user.user_id
            self.template = model.Invitation(**kw);
            self.template.id_question_invitation = self.utility.setIfEmpty(self.template.id_question_invitation)
            #self.template.create_date = self.utility.today( self.template.create_date)
            
            if (  self.utility.isEmpty(  self.template.id_question_invitation  )):
                log.info("save option")
                self.template.save()
            else:
                log.info("update option")
                self.template.updateall()
            
            
        except Exception as e:
            self.result = False;
            self.message = '' + str(e);
            
        log.info( self.message);        
        
        return dict(success=self.success, message = self.message, result= self.result);
    
    #proved
    @expose('json')
    @require(predicates.in_any_group('voter', 'managers', msg=l_('Only for voter')))
    def deleteInvitation(self, **kw):
        reload(sys).setdefaultencoding('utf8')
        self.success = True;
        self.result = True;
        self.message = 'Delete Success';
        try:
            df = json.loads(request.body, encoding=request.charset);
            
            log.info(df);
            
            
            self.result =model.Invitation.deleteById(df.get('id_question_invitation'));
            
            if not self.result:
                self.message = 'Can not Delete.'; 
            
            
        except Exception as e:
            self.result =False;
            self.message = '' + str(e);
            
        
        return dict(success=self.success, result =self.result, message =self.message);
    
    
    #proved
    @expose('json')
    @require(predicates.in_any_group('voter', 'managers', msg=l_('Only for voter')))
    def sendSurvey(self, **kw):
        reload(sys).setdefaultencoding('utf8')
        self.success = True;
        self.result = True;
        self.message = 'Send Success';
        
        
        try:
            df = json.loads(request.body, encoding=request.charset);
            
            log.info(df);
            
            self.option = model.QuestionOption.getId(df.get('id_question_option'));
            
            if self.option.send_status == 0:
                
                self.emailtemplate = model.Invitation.getId(df.get('id_question_invitation'));
                if(self.emailtemplate is not None):
                    
                    #self.sendSurveyService = SendSurveyService();
                    #self.sendSurveyService.setEmailToVoter(model,self.option,self.emailtemplate);
                    #self.sendSurveyService.start();
                    
                    user = request.identity['user'];
                    
                    self.voters, self.leng = model.Voter.getVoter(user.user_id, page=0, page_size=100); 
                    
                    self.urlServer =  model.SystemEnvironment.getServerUrl();
        
                    for v in self.voters:
                        #print v;
                        self.resp = model.Respondents.getByVoterIdAndPublicId(v.id_voter,self.option.id_question_option);
                        if (self.resp is None):
                            self.resp = model.Respondents();
                            self.resp.id_voter = v.id_voter;
                            self.resp.id_question_project = self.option.id_question_project;
                            self.resp.id_question_option =self.option.id_question_option;
                            self.resp.key_gen = self.utility.my_random_string(string_length=25)
                            self.resp.save();
                        
                        if (self.resp.key_gen is None):
                            self.resp.key_gen = self.utility.my_random_string(string_length=25)
                        
                        
                        self.emailValues={};
                        self.emailValues['name'] = str(v.firstname) + " " + str(v.lastname);
                        self.emailValues['email'] = v.email;
                        self.emailValues['subject'] = self.emailtemplate.subject;
                        self.emailValues['from'] =  self.emailtemplate.from_name;
                        #self.emailValues['url'] = self.urlUtility.URL_REPLY.format(self.urlServer, str(self.option.id_question_project), str(self.option.id_question_option), str(v.id_voter))  ; #request.application_url
                        self.emailValues['url'] = self.urlUtility.URL_QUESTIONNAIRE.format(nameserver=self.urlServer,key=self.resp.key_gen);  #self.urlUtility.URL_REPLY.format(self.urlServer, str(self.option.id_question_project), str(self.option.id_question_option), str(v.id_voter))  ; #request.application_url
                        self.emailValues['initialDate'] = str(self.option.activate_date);
                        self.emailValues['finishDate'] = str(self.option.expire_date);
                        
                         
                        
                        template = self.emailtemplate.content;
                        for k, va in  self.emailValues.iteritems():
                            template = template.replace('[%s]' % k, va)
                            
                        self.sendmail = model.SendMail(id_question_option = self.resp.id_question_option,
                                                       id_voter = self.resp.id_voter, 
                                                       user_id =None,
                                                       sender_name = self.emailtemplate.from_name,
                                                       receive =  v.email,
                                                       subject = self.emailtemplate.subject,
                                                       content = template,
                                                       gen_code = self.resp.key_gen );
                                                       
                        self.sendmail.save();
                        
                        #sendmail  = SendMailService();
                        #sendmail.sentEmail(self.emailValues, template);
                        
                        #self.sendmail.sended_date = datetime.now();
                        #self.sendmail.status = 'F';
                       
                        
                    
                else:
                    self.result = False;
                    self.message = "Please select template email.";
                
                
                #self.result,self.message =  model.QuestionOption.updateSendStatus(1,df.get('id_question_option'));
                
                log.info( "\n send to thread");
            else:
                self.result = False;
                self.message = "system found send already"; 
            
            #model.Invitation.deleteById(df.get('id_question_invitation'));
             
            
        except Exception as e:
            log.error(e);
            self.result = False;
            self.message = '' + str(e);
            
        
        return dict(success=self.success, result=self.result, message=self.message);
    
    #proved
    @expose('json')
    @require(predicates.in_any_group('voter', 'managers', msg=l_('Only for voter')))
    def addQuestionGroup(self,**kw):
        reload(sys).setdefaultencoding('utf8')
        log.info("add Question Group")
                
        self.questionGroup = model.QuestionGroup(**kw);
        self.questionGroup.id_question_group = self.utility.setIfEmpty(self.questionGroup.id_question_group)
        self.questionGroup.id_question_result_group = self.utility.setIfEmpty(kw['id_question_result_group'])
        
        if (self.utility.isEmpty(self.questionGroup.id_question_group)):
            log.info("save group")
            self.questionGroup.save()
        else:
            log.info("update group")
            self.questionGroup.updateall()
        
        return dict(success=True, result='success', message='sucess',questionGroup=self.questionGroup.json );
        
    @expose('json')
    @require(predicates.in_any_group('voter', 'managers', msg=l_('Only for voter')))
    def deleteGroupQuestion(self, *args, **kw):
        self.questionGroup = json.loads(request.body, encoding=request.charset, object_hook=model.QuestionGroup.setId)
        self.message = ""
        self.status = True
        if(self.questionGroup):
            self.questions = model.Question.getQuestionByGroupId(self.questionGroup.id_question_group)
            if(self.questions and len(self.questions) > 0):
                log.info("can not delete ");
                self.message = "Cann't delete. Please delete all questions."
                self.status = False
            else:
                model.QuestionGroup.delete(self.questionGroup);
   
        return dict(success=self.status, message=self.message);    
        
    @expose('json')
    def saveResultGroup(self,*args,**kw):       
        reload(sys).setdefaultencoding('utf8')
        self.message = "Save Success"
        self.status = True
        data = JsontoObject(kw);
        
        #model.QuestionResultGroup.load_data(data)
        
        questionResultGroup = model.QuestionResultGroup(
                                                        id_question_result_group = self.utility.setIfEmpty(data.id_question_result_group),
                                                        id_question_project = data.id_question_project,
                                                        question_result_group_description = data.question_result_group_description,
                                                        question_result_group_name = data.question_result_group_name)
        
        if questionResultGroup.id_question_result_group:
            questionResultGroup.updateall()
        else:
            questionResultGroup.save()
        
      
        
        datagrid = json.loads(data.datagrid,encoding='UTF-8')
         
        
        #datagrid = JsontoObject(datagrid);
        
        for value in datagrid:
            value = JsontoObject(value);
            questionResult = model.QuestionResult(id_question_result=self.utility.setIfEmpty(value.id_question_result),
                                                  question_result_name=value.question_result_name,
                                                  question_result_description=value.question_result_description,
                                                  id_question_result_group=questionResultGroup.id_question_result_group)
            questionResult.updateall()
            
        return dict(success= self.status, message = self.message);
    
    @expose('json')
    def deleteresultgroup(self, *args, **kw):
        reload(sys).setdefaultencoding('utf8')
        self.message = ""
        self.status = True
        
        self.df = json.loads(request.body, encoding=request.charset);
        
        data = JsontoObject(self.df);
        
        self.questionResult = model.QuestionResult.deleteByGroupId(data.id_question_result_group)
        self.questionResultGroup = model.QuestionResultGroup.deleteById(data.id_question_result_group)
        
        
        
        
        return dict(success= self.status, message = self.message);
    
    @expose('json')
    def deleteresult(self, *args, **kw):
        reload(sys).setdefaultencoding('utf8')
        self.message = ""
        self.status = True
        
        self.df = json.loads(request.body, encoding=request.charset);
        
        data = JsontoObject(self.df);
        
        print data
        self.questionResult = model.QuestionResult.deleteById(data.id_question_result)
        print self.questionResult
        #self.questionResultGroup = model.QuestionResultGroup.deleteById(data.id_question_result_group)
        #print self.questionResultGroup
        return dict(success= self.status, message = self.message);
    
    
    @expose('json')
    def deleteQuestionGeneralInformation(self, *args, **kw):
        reload(sys).setdefaultencoding('utf8')
        self.message = ""
        self.status = True
        self.df = json.loads(request.body, encoding=request.charset)
        data = JsontoObject(self.df)
        
        model.QuestionGeneralInformation.deleteById(data.id)
        
        return dict(success= self.status, message = self.message, survey = [])
    
    @expose('json')
    def updateQuestionGeneralInformation(self, *args, **kw):
        reload(sys).setdefaultencoding('utf8')
        self.message = ""
        self.status = True
        self.df = json.loads(request.body, encoding=request.charset);
        
        data = JsontoObject(self.df);
        
        for obj in data.dict:
            print obj.to_json()
            result = model.QuestionGeneralInformation.updateOrder(id=obj.id, order=obj.order)
            print "result %s " %result
        
        return dict(success= self.status, message = self.message, survey = data.to_json() )
    @expose('json')
    def createQuestionGeneralInformation(self, *args, **kw):
        reload(sys).setdefaultencoding('utf8')
        self.message = ""
        self.status = True
        self.df = json.loads(request.body, encoding=request.charset);
        
        data = JsontoObject(self.df);

        
        self.generalInformation =  model.QuestionGeneralInformation(id_question_general_information=None, id_data_profile_field=data.data_id, id_question_project=data.id_question_project, order=data.order, active=1)
        self.generalInformation.save()
        data.id = self.generalInformation.id_question_general_information
        
        
        
        
        return dict(success= self.status, message = self.message, survey =  {'id':data.id}   )#data.to_json())#data = {'data_id':data.data_id}  )
Exemplo n.º 27
0
class PreviewController(BaseController):
    def __init__(self):
        self.URL_GETDATAQUESTION = "/preview/getDataPreview?idProject={0}"

        self.utility = Utility()

        dh = LogDBHandler(config=config, request=request)
        log.addHandler(dh)

    @expose("pollandsurvey.templates.view.multiquestion")
    def index(self, id=0, ready="no", came_from=lurl("/")):

        reload(sys).setdefaultencoding("utf8")

        if not request.identity:
            login_counter = request.environ.get("repoze.who.logins", 0) + 1
            redirect("/login", params=dict(came_from=came_from, __logins=login_counter))
        userid = request.identity["repoze.who.userid"]

        log.info("preview id : " + str(id))
        log.info("ready : " + str(ready))

        self.header = ""
        self.footer = ""
        self.nextQuestion = ""
        self.template = ""
        self.questionOption = model.QuestionOption.getId(id)
        if self.questionOption:
            log.info("expire date : " + str(self.questionOption.expire_date))
            log.info("current : " + str(datetime.now()))

            if datetime.now() <= self.questionOption.expire_date:
                log.info("not expire")
            else:
                log.info("expire")

            if str(ready).lower() == "no":
                # check have welcome page
                if not self.utility.isEmpty(self.questionOption.welcome_message):
                    redirect(request.path_info + "/welcome?id=" + str(self.questionOption.id_question_option))
                else:
                    self.template = self.questionOption.theme.template
                    override_template(PreviewController.index, self.template)

            elif str(ready).lower() == "yes":
                self.header = self.questionOption.header_message
                self.footer = self.questionOption.footer_message
                self.urlName = self.utility.spritValue(request.path_info, "/")
                self.template = self.questionOption.theme.template
                if len(self.urlName) >= 1:
                    self.nextQuestion = (
                        "/" + self.urlName[0] + "/saveQuestion" + "?id=" + str(self.questionOption.id_question_option)
                    )

                if self.template is not None and len(self.template) > 0:
                    log.info("template used : %s", self.template)
                    override_template(PreviewController.index, self.template)

        # print 'idproject : ', id;
        return dict(
            page="view",
            header=self.header,
            footer=self.footer,
            action=self.nextQuestion,
            template=self.template,
            urldata=self.URL_GETDATAQUESTION.format(id),
            idproject=id,
            shownavigator=bool(self.questionOption.show_navigator),
            idresp="",
        )

    @expose("genshi:pollandsurvey.templates.view.firstTemplate")
    def sampleTemplate(self, id=0, **kw):
        # print id;
        if str(id) == str(2):
            # print id;
            override_template(PreviewController.sampleTemplate, "genshi:pollandsurvey.templates.view.changeTemplate")
        return dict(
            title="Foobar", mybool=False, someval="foo"
        )  # ,tg_template="pollandsurvey.templates.view.changeTemplate"

    @expose("pollandsurvey.templates.view.welcome")
    def welcome(self, id=0, came_from=lurl("/")):
        reload(sys).setdefaultencoding("utf8")

        if not request.identity:
            login_counter = request.environ.get("repoze.who.logins", 0) + 1
            redirect("/login", params=dict(came_from=came_from, __logins=login_counter))
        userid = request.identity["repoze.who.userid"]

        log.info("preview id : " + str(id))

        self.welcome_message = ""
        self.questionOption = model.QuestionOption.getId(id)
        if self.questionOption:
            if datetime.now() <= self.questionOption.expire_date:
                log.info("not expire")
            else:
                log.info("expire")

            self.welcome_message = self.questionOption.welcome_message
            self.nextQuestion = ""

            self.urlName = self.utility.spritValue(request.path_info, "/")

            if len(self.urlName) >= 1:
                self.nextQuestion = "/" + self.urlName[0] + "?id=" + str(self.questionOption.id_question_option)

        return dict(page="view", ready="yes", welcome_message=self.welcome_message, nextQuestion=self.nextQuestion)

    @expose("pollandsurvey.templates.view.singlequestion")
    def show(self, id=0, came_from=lurl("/")):
        reload(sys).setdefaultencoding("utf8")

        if not request.identity:
            login_counter = request.environ.get("repoze.who.logins", 0) + 1
            redirect("/login", params=dict(came_from=came_from, __logins=login_counter))
        userid = request.identity["repoze.who.userid"]
        # flash(_('Welcome back, %s!') % userid)

        log.info("preview id : " + str(id))

        self.questionOption = model.QuestionOption.getId(id)

        log.info("expire date : " + str(self.questionOption.expire_date))
        log.info("current : " + str(datetime.now()))

        if datetime.now() <= self.questionOption.expire_date:
            log.info("not expire")
        else:
            log.info("expire")

        return dict(page="view")

    @expose("json")
    def getDataPreview(self, came_from=lurl("/"), *args, **kw):
        reload(sys).setdefaultencoding("utf-8")

        idProject = kw.get("idProject")
        idRespondet = None

        if "." in idProject:
            self.data = self.utility.spritValue(idProject, ".")

            idProject = self.data[0]
            if len(self.data) == 2:
                idRespondet = self.data[1]

        # print args;
        # print kw ;

        questions = []

        question = []
        if idRespondet:
            log.info("Query with respondent")

            self.listReply = model.RespondentReply.listQuestionForUser(self.data[1])

            for re in self.listReply:

                result = model.RespondentReply.getResultByRespondemtAndQuestion(idRespondet, re.question.id_question)

                question.append(re.question.to_json(randomAnswer=False, showResult=result))

        else:
            log.info("Query with question")

            self.questionOption = model.QuestionOption.getId(idProject)

            if self.questionOption:
                self.listQuestions = model.Question.getByProjectId(self.questionOption.id_question_project)

                question = []
                for self.question in self.listQuestions:
                    # print self.question.id_question;
                    # print self.question.question;
                    # print self.question.question_type.type;
                    # print self.question.order;
                    question.append(self.question.to_json(randomAnswer=self.questionOption.random_answer))

        questions.append({"id": idProject, "question": question})

        return dict(questions=questions)

    @expose("pollandsurvey.templates.view.goodbye")
    def saveQuestion(self, id=0, came_from=lurl("/"), *args, **kw):
        reload(sys).setdefaultencoding("utf-8")

        if not request.identity:
            login_counter = request.environ.get("repoze.who.logins", 0) + 1
            redirect("/login", params=dict(came_from=came_from, __logins=login_counter))
        userid = request.identity["repoze.who.userid"]

        self.success = True
        self.message = "success"
        self.goodbye_message = ""
        self.nextQuestion = ""

        self.questionOption = model.QuestionOption.getId(id)
        if self.questionOption:
            self.goodbye_message = self.questionOption.end_message
            self.urlRedirect = self.questionOption.redirect_url

        return dict(
            page="goodbye",
            success=self.success,
            message=self.message,
            goodbye=self.goodbye_message,
            nextQuestion=self.nextQuestion,
            urlRedirect=self.urlRedirect,
        )

    @expose("pollandsurvey.templates.view.multiquestion")
    def showResult(self, id=0, ready="yes", came_from=lurl("/"), *args, **kw):

        reload(sys).setdefaultencoding("utf-8")

        if not request.identity:
            login_counter = request.environ.get("repoze.who.logins", 0) + 1
            redirect("/login", params=dict(came_from=came_from, __logins=login_counter))
        # userid = request.identity['repoze.who.userid']

        self.data = self.utility.spritValue(id, ".")

        if len(self.data) != 2:
            return dict(questions=[])

        log.info("preview id : " + str(id) + "  ready : " + str(ready))

        self.header = ""
        self.footer = ""
        self.nextQuestion = ""
        self.template = ""
        self.questionOption = model.QuestionOption.getId(self.data[0])
        if self.questionOption:
            # log.info('expire date : ' + str(self.questionOption.expire_date) + ', current date : ' +  str(datetime.now()));

            # if datetime.now() <= self.questionOption.expire_date:
            #    log.info('not expire');
            # else :
            #    log.info('expire');

            if str(ready).lower() == "no":
                # check have welcome page
                if not self.utility.isEmpty(self.questionOption.welcome_message):
                    redirect(request.path_info + "/welcome?id=" + str(self.questionOption.id_question_option))
                else:
                    self.template = self.questionOption.theme.template
                    override_template(PreviewController.index, self.template)

            elif str(ready).lower() == "yes":
                self.header = self.questionOption.header_message
                self.footer = self.questionOption.footer_message
                self.urlName = self.utility.spritValue(request.path_info, "/")
                self.template = self.questionOption.theme.template
                if len(self.urlName) >= 1:
                    self.nextQuestion = (
                        "/" + self.urlName[0] + "/saveQuestion" + "?id=" + str(self.questionOption.id_question_option)
                    )

                if self.template is not None and len(self.template) > 0:
                    log.info("template used : %s", self.template)
                    override_template(PreviewController.index, self.template)

        return dict(
            page="view",
            header=self.header,
            footer=self.footer,
            action=self.nextQuestion,
            template=self.template,
            urldata=self.URL_GETDATAQUESTION.format(id),
            idproject=id,
            shownavigator=bool(self.questionOption.show_navigator),
            idresp="",
        )
Exemplo n.º 28
0
class InvitationController(TGController):
    
    allow_only = in_any_group('voter', 'managers', msg=l_('Only for people with the "manage" permission'))
    #has_any_permission('manage','creator',msg=l_('Only for people with the "manage" permission'))
    
    def __init__(self, models, session, config_type=None, translations=None):
        self.utility = Utility()
        self.model = models       
         
        
        
        
    #@require(predicates.in_any_group('creator','managers', msg=l_('Only for creator')))
    @expose('managepoll.templates.invitation.index')
    def index(self,**kw):
        user =  request.identity['user'];
        print user.user_id
                
        return dict(page = 'index',idproject = None)
        
    @expose('managepoll.templates.invitation.invitation')
    def invitation(self,**kw):
       
        print kw 
        
        
        reload(sys).setdefaultencoding("utf-8");
        invitation = self.model.Invitation()
        self.emailtemplate = self.model.EmailTemplate()
        if('idinvitation' in kw):
            print kw['idinvitation']            
            #           
            invitation = self.model.Invitation.getId(kw['idinvitation'])  
            
            
        else:
            self.emailtemplate = self.model.EmailTemplate.getTemplateBy(5); 
            
            invitation.name_content  = self.emailtemplate.sender
            invitation.from_name =  self.emailtemplate.sender
            invitation.subject =  self.emailtemplate.subject
            invitation.content =  self.emailtemplate.content_template
         
        return dict(page='invitation', invitation = invitation,idproject = None)
       
    @expose()
    def saveinvitation(self,**kw):
        user =  request.identity['user'];
        reload(sys).setdefaultencoding('utf8') 
      
        
        invitation = self.model.Invitation(**kw)
        invitation.user_id = user.user_id
        
                
        invitation.id_question_invitation = self.utility.setIfEmpty(invitation.id_question_invitation)  
        
        if self.utility.isEmpty(invitation.id_question_invitation) :    
            print "save"
            invitation.save()
        else :
            print "update"
            invitation.updateall()
      
   

        redirect('/managepoll/invitation/indextest')
        
        
    @expose('managepoll.templates.invitation.indextest')
    def indextest(self,**kw):
        user =  request.identity['user'];
        print user.user_id
                
        return dict(page = 'invitation',idproject = None)
        
    @expose('managepoll.templates.invitation.invitationtest')
    def invitationtest(self,**kw):
       
        print kw 
        
        
        reload(sys).setdefaultencoding("utf-8");
        invitation = self.model.Invitation()
        self.emailtemplate = self.model.EmailTemplate()
        if('idinvitation' in kw):
            print kw['idinvitation']            
            #           
            invitation = self.model.Invitation.getId(kw['idinvitation'])  
            
            
        else:
            self.emailtemplate = self.model.EmailTemplate.getTemplateBy(5); 
            
            invitation.name_content  = self.emailtemplate.sender
            invitation.from_name =  self.emailtemplate.sender
            invitation.subject =  self.emailtemplate.subject
            invitation.content =  self.emailtemplate.content_template
         
        return dict(page='invitationtest', invitation = invitation,idproject = None)
    
    @expose()
    def deleteinvitation(self,**kw):  
        print kw  
        self.model.Invitation.deleteById(kw['idinvitation'])
       
        redirect('/managepoll/invitation/indextest')        
    
        
Exemplo n.º 29
0
class VoterController(TGController):
    
    allow_only = in_any_group('voter', 'managers', msg=l_('Only for people with the "manage" permission'))
    #has_any_permission('manage','creator', msg=l_('Only for people with the "manage" permission'))
    
    def __init__(self, models, session, config_type=None, translations=None):
        print "call VoterController(managepoll)"
        
        self.utility = Utility()           
        self.model = models       
        
        
    @expose('managepoll.templates.voter.index')
    def index(self):    
        return dict(page = 'index',idproject=None)
    
    
    @expose('managepoll.templates.voter.voter')
    def voters(self,*args,**kw):
        reload(sys).setdefaultencoding('utf8')   
        
        voterObject = VoterObject()        
        print kw
        
        if('idvoter' in kw):
            print kw
            print "Edit voter"
            voter = self.model.Voter.getId(kw['idvoter'])
            voterObject.setVoter(voter)
            #employment = model.EmploymentDetail.getId(kw['idvoter'])
            
        print "voters : lang"
        
        self.lang = self.model.Languages.getAll()
        print self.lang
        self.marriageStatus = self.model.MarriageStatus.getAll(act=1)
        self.gender = self.model.Gender.getAll(act=1)
        self.tel = self.model.TelephoneType.getAll(act=1)
        self.religion = self.model.ReligionType.getAll(act=1)
        self.national = self.model.NationalityType.getAll(act=1)
        self.race = self.model.RaceType.getAll(act=1)
        self.condition = self.model.LivingConditionType.getAll(act=1)
        self.employmentstatus = self.model.EmploymentType.getAll(act=1)
        self.listConutry = self.model.FixCountry.getAll(active=1)
        self.telephone = self.model.TelephoneType.getAll(act=1)
        self.education = self.model.EducationType.getAll(act=1)
        self.addresstype = self.model.AddressType.getAll(act=1)
            
        
        return dict(page = 'voters',
                    lang = self.lang,
                    marriageStatus = self.marriageStatus,
                    gender = self.gender,
                    tel = self.tel,
                    religion = self.religion,
                    national = self.national,
                    race = self.race,
                    condition = self.condition,
                    employmentstatus = self.employmentstatus,
                    listConutry = self.listConutry,
                    telephone = self.telephone,
                    education = self.education,
                    addresstype = self.addresstype,
                    
                    voter = voterObject,
                    idproject=None)
        
     
    @expose()   
    def savevoter(self,**kw):
        print kw
       
        user =  request.identity['user'];
        print "********************"
        print kw['id_voter']
        print kw['id_voter_map_type']
        print kw['id_telephone']
        print kw['id_address']
        print kw['id_employment']
        print "********************"   
        
        voter = self.model.Voter.getId(kw['id_voter'])
        
        if voter is None : 
            print "voter is none"
            voter = self.model.Voter()
                        
        
        voter.email = kw['email']
        voter.prefix = kw['prefix']
        voter.firstname = kw['firstname']
        voter.lastname = kw['lastname']          
       
        voter.id_marriage_status  = kw['id_marriage_status']
        
        #voter.birthdate = kw['birthdate'] 
            
        voter.birthdate = self.utility.convertToDateTime(kw['birthdate'], '%d/%m/%Y') 
        
        voter.id_gender = kw['id_gender']
           
        voter.id_living_condition = kw['id_living_condition']                                                        
        voter.size_family = kw['size_family']  
        voter.id_language = kw['id_language']
        voter.id_religion = kw['id_religion']
        voter.id_nationality = kw['id_nationality']
        voter.id_race = kw['id_race']
        voter.salary = kw['salary']
        voter.id_education = kw['id_education']
        voter.user_id_owner = user.user_id
        
        print "va %s" % (str( len(kw['id_voter'])))
        if (len(kw['id_voter']) == 0) :            
            voter.save()
         
         
        print "Voter id : %s" %voter.id_voter

        votermaptype =  self.model.VoterMapType.getId(kw['id_voter_map_type'])
        if votermaptype is None : 
            votermaptype = self.model.VoterMapType()
        
        votermaptype.id_voter = voter.id_voter
        votermaptype.id_voter_type = 5
                
        if (len(kw['id_voter_map_type'] ) == 0):
            votermaptype.save() 
        
        print "voter map type id : %s" %votermaptype.id_voter_map_type
        
        votertelephone = self.model.Telephone.getId(kw['id_telephone'])
        if votertelephone is None:
            votertelephone = self.model.Telephone()
        
         
        votertelephone.id_telephone_type = kw['id_telephone_type']
        votertelephone.description = kw['telephone']
        votertelephone.id_voter = voter.id_voter
        
        
        if (len(kw['id_telephone'] ) == 0):
            votertelephone.save()
        
        print "telephone : %s" %votertelephone.id_telephone
        
        voteraddress = self.model.Address.getId(kw['id_address'])
        if voteraddress is None:
            voteraddress = self.model.Address()
        
        voteraddress.id_address_type = kw['id_address_type']
        voteraddress.id_voter = voter.id_voter
        voteraddress.country = kw['id_country']
        voteraddress.province = kw['province']
        voteraddress.city = kw['city']
        voteraddress.county = kw['county']
        
        if (len(kw['id_address'] ) == 0):
            voteraddress.save()
        
          
        voteremployment = self.model.EmploymentDetail.getId(kw['id_employment'])
        if voteremployment is None:
            voteremployment = self.model.EmploymentDetail()
         
        
        voteremployment.id_voter = voter.id_voter
        voteremployment.id_employment_status_type = kw['id_employment_status_type']
        voteremployment.intructry_type = kw['intructry_type']
        voteremployment.job_catagory = kw['job_catagory']
         
        if (len(kw['id_employment'] ) == 0):
            voteremployment.save()
    
             
        redirect('/managepoll/voter/indextest')
        
    @expose('managepoll.templates.voter.indextest')
    def indextest(self):    
        return dict(page = 'voter',idproject=None)
    
    
    @expose('managepoll.templates.voter.votertest')
    def votertest(self,*args,**kw):
        print kw
        reload(sys).setdefaultencoding('utf8')   
        
        voterObject = VoterObject()        
        print kw
        
        if('idvoter' in kw):
            print kw
            print "Edit voter"
            voter = self.model.Voter.getId(kw['idvoter'])
            voterObject.setVoter(voter)
            #employment = model.EmploymentDetail.getId(kw['idvoter'])
            
        print "voters : lang"
        
        self.lang = self.model.Languages.getAll()
        
        print self.lang
        
        self.marriageStatus = self.model.MarriageStatus.getAll(act=1)        
        self.gender = self.model.Gender.getAll(act=1)        
        self.tel = self.model.TelephoneType.getAll(act=1)
        self.religion = self.model.ReligionType.getAll(act=1)
        self.national = self.model.NationalityType.getAll(act=1)
        self.race = self.model.RaceType.getAll(act=1)
        self.condition = self.model.LivingConditionType.getAll(act=1)
        self.employmentstatus = self.model.EmploymentType.getAll(act=1)
        self.listConutry = self.model.FixCountry.getAll(active=1)
        self.telephone = self.model.TelephoneType.getAll(act=1)
        self.education = self.model.EducationType.getAll(act=1)
        self.addresstype = self.model.AddressType.getAll(act=1)
        print "***************"
       
        print voterObject.birthdate
            
        
        return dict(page = 'votertest',
                    lang = self.lang,
                    marriageStatus = self.marriageStatus,
                    gender = self.gender,
                    tel = self.tel,
                    religion = self.religion,
                    national = self.national,
                    race = self.race,
                    condition = self.condition,
                    employmentstatus = self.employmentstatus,
                    listConutry = self.listConutry,
                    telephone = self.telephone,
                    education = self.education,
                    addresstype = self.addresstype,
                    
                    voter = voterObject,
                    idproject=None)

 
    @expose()
    def deletevoter(self,**kw):  
        print kw  
        self.model.Invitation.deleteById(kw['idinvitation'])
       
        redirect('/managepoll/invitation/indextest')        
Exemplo n.º 30
0
 def __init__(self, models, session, config_type=None, translations=None):
     self.utility = Utility()
     self.model = models       
Exemplo n.º 31
0
class AnswerQuestionService(object):
    
    def __init__(self, mymodel=None):
        
        self.utility = Utility();
        self.urlUtility = URLUtility();
        
        self.UPLOAD_DIR = config['path_upload_file'] ;
        self.CONVERT_DIR = config['path_convert_file'] ;
        self.utility.createPathFile(self.CONVERT_DIR);
        self.utility.createPathFile(self.UPLOAD_DIR);
        if mymodel is None:
            self.mymodel = model
        self.mymodel = mymodel
        
        self.urlServer = self.mymodel.SystemEnvironment.getServerUrl()
        
        dh = LogDBHandler( config=config,request=request);        
        log.addHandler(dh)
        
    def getQuestionGroupWithReply(self, listReply=None):
        self.groups = {}
        if listReply:
            print "len : %s" %(len(listReply)) 
            for self.reply in listReply:
                if self.reply.question.id_question_group not in self.groups:
                    questiongroup = self.reply.question.questiongroup.tojsonviewdata()
                else:
                    questiongroup = self.groups[self.reply.question.id_question_group]
                questiongroup['questions'].append(self.reply.question.to_json(randomAnswer=True,showResult = None,initOrder=1) )
                self.groups[self.reply.question.id_question_group] = questiongroup
                del questiongroup
                del self.reply
        
        return [self.groups[group]  for group in self.groups ]
    
    def getQuestionGroupWithQuestionOption(self, questionOption=None):
        self.listquestion = []
        self.order =1
        if questionOption:
            self.questionGroups = self.mymodel.QuestionGroup.getByProject(questionOption.id_question_project )            
            groupaount = {str(amount.id_question_group) : amount.amount for amount in questionOption.numberquestion }
            print "-----"
            print groupaount
            for g in groupaount:
                print "id : %s" %g
            for self.group in self.questionGroups:    
                self.group, self.order = self.group.tojsonview(randomAnswer = questionOption.random_answer,initOrder = self.order) 
                print str(self.group['id_question_group'])                
                if str(self.group['id_question_group']) in groupaount:
                    self.value_amount = groupaount[str(self.group['id_question_group'])]
                    if (self.value_amount > 0):
                        self.group['questions']  = random.sample(self.group['questions'], self.value_amount );
                        self.listquestion.append(self.group)            
        return self.listquestion
    
    def createQuestionForUser(self, listQuestion=None, id_close_type=0):
        if listQuestion:
            if id_close_type not in [ClossType.start_new.value] :
                self.mymodel.RespondentReply.createQuestionForUser(self.listquestion,self.respondents.id_respondents)
                
    def genSeq(self, listQuestion=None):
        self.order=1    
        if listQuestion:
            for listquest in listQuestion:
                for question in listquest['questions']:
                    question['seq'] = str(self.order)                    
                    self.order = self.order+1
                    del question
                del listquest
        return listQuestion,(self.order -1)
    
    def renewQuestionForUser(self, respondents=None, id_close_type=0):      
        if respondents and (id_close_type in [ClossType.start_new.value]) :
            respondents.image_file = None
            respondents.full_score = None
            respondents.score_exam = 0
            respondents.personality_score = None
           
            for respreply in respondents.childenRespReply:
                for answer in respreply.childenAnswer:
                    self.mymodel.DBSession.delete(answer)
                self.mymodel.DBSession.delete(respreply)
                
    
    def checkFinish(self,respondent, urlUtility):
        self.redirect=urlUtility.URL_THANKYOU
        self.isredirect = False
        if(respondent  is not None and respondent.finished == CheckFinish.finished.value): #finished = 1
            log.info('voter finished in id public : %s'  %str(respondent.id_question_option) );
            self.redirect  = self.urlUtility.URL_GOODBYE.format( key= respondent.key_gen   ) 
            self.isredirect = True
        
        return self.isredirect, self.redirect
                
                
    def createScoreFile(self,idResp):
        
        self.respondent = self.mymodel.Respondents.getId(idResp);
        self.score = self.mymodel.Respondents.getScoreByIdRespondents(idResp)#self.idResp);
        self.voter = self.respondent.voter;
        
        self.convertHtml = ConvertHtml2Pdf();
        self.convertPNG = ConvertPdf2image();
        
        self.sourceHtml = self.mymodel.SystemEnvironment.getScoreViewHtml();

        values = {};
        values['name'] = str(self.voter.prefix + ' ' + self.voter.firstname + ' ' + self.voter.lastname);
        values['score'] = str(self.score);
        
        #self.outputPDFFilename = ("{0}\{1}-{2}-{3}-{4}.pdf").format(str(self.CONVERT_DIR), str(self.respondent.id_respondents), str(self.respondent.id_voter), str(self.respondent.id_question_project), str(self.respondent.id_question_option))  ;
        #self.outputPNGFilename = ("{0}\{1}-{2}-{3}-{4}.png").format(str(self.CONVERT_DIR), str(self.respondent.id_respondents), str(self.respondent.id_voter), str(self.respondent.id_question_project), str(self.respondent.id_question_option))  ;
        self.outputPDFFilename = ("{0}-{1}-{2}-{3}.pdf").format( str(self.respondent.id_respondents), str(self.respondent.id_voter), str(self.respondent.id_question_project), str(self.respondent.id_question_option))  ;
        self.outputPNGFilename = ("{0}-{1}-{2}-{3}.png").format( str(self.respondent.id_respondents), str(self.respondent.id_voter), str(self.respondent.id_question_project), str(self.respondent.id_question_option))  ;
        
        self.outputPDFFilename = os.path.join( str(self.CONVERT_DIR), self.outputPDFFilename)
        self.outputPNGFilename = os.path.join( str(self.CONVERT_DIR), self.outputPNGFilename)
        
        
        self.result = self.convertHtml.convertHtmlToPdf(values, self.sourceHtml, self.outputPDFFilename);
        log.info("convert file %s is %s" %(self.outputPDFFilename, self.result));
        print ("convert file %s is %s" %(self.outputPDFFilename, self.result));
        if(self.result == 0):
            self.result = self.convertPNG.convert(self.outputPDFFilename, self.outputPNGFilename)
            log.info("convert file %s is %s" %(self.outputPNGFilename, self.result));
            if(self.result):
                log.info("save image file %s is %s" %(self.outputPNGFilename, self.result));
                with open(self.outputPNGFilename,"rb") as f:
                    self.respondent.image_file = f.read(); 
        else:
            log.error("convert html to pdf error with id_resp=%s" %idResp)     
            
        del self.respondent
        del self.score
        del self.voter
        del self.convertHtml  
        del self.convertPNG
        del self.sourceHtml
        del values
        del self.outputPDFFilename
        
    def createScoreFileImage(self,idResp):
        
        self.respondent = self.mymodel.Respondents.getId(idResp);
        
        self.outputPDFFilename = ("{0}-{1}-{2}-{3}.pdf").format( str(self.respondent.id_respondents), str(self.respondent.id_voter), str(self.respondent.id_question_project), str(self.respondent.id_question_option))  ;
        self.outputPNGFilename = ("{0}-{1}-{2}-{3}.jpg").format( str(self.respondent.id_respondents), str(self.respondent.id_voter), str(self.respondent.id_question_project), str(self.respondent.id_question_option))  ;
        
        self.outputPDFFilename = os.path.join( str(self.CONVERT_DIR), self.outputPDFFilename)
        self.outputPNGFilename = os.path.join( str(self.CONVERT_DIR), self.outputPNGFilename)
         
        self.urlscore = ("http://{0}/ans/viewCertScore/{1}").format(str(self.urlServer ), str(self.respondent.id_respondents))
        
        self.converthtml2image = ConvertHTML2Image()
        self.result = self.converthtml2image.convertURL2Image(self.urlscore, self.outputPNGFilename)
        log.info( "convert : %s result %s" %(self.outputPNGFilename, self.result))
        with open(self.outputPNGFilename,"rb") as f:
            self.respondent.image_file = f.read(); 
        
        del self.respondent
        del self.urlscore
        del self.converthtml2image
        del self.result
        del self.outputPDFFilename    
class InterfaceServiceController(RestController):
    
    def __init__(self):
        dh = LogDBHandler( config=config,request=request);        
        log.addHandler(dh)
        self.utility = Utility();
        self.urlUtility = URLUtility();
        self.urlServer =  model.SystemEnvironment.getServerUrl();
        
    @with_trailing_slash
    @expose('json')
    #@require(predicates.in_any_group('voter','managers', msg=l_('Only for voter')))
    def get_all(self,*args,**kw):
        log.info( "get_all");
        log.info( "args : %s ", args);
        log.info( "kw : %s", kw);
        
        #print len(request.headers);
        
        #for h in request.headers:
        #    print h ,  request.headers[h];
        #log.info( "body : %s" ,request.body);
        print ("body : %s" ,request.body);
        try:
         
            if (kw):
                self.client_id = kw['clientId'];
                self.client_secret = kw['clientSecret'];
                
                self.UserClientAuthen = model.UserClientAuthen.getUserClientAuthen(self.client_id, self.client_secret);
                samples = kw;
                
                if (self.UserClientAuthen):
                    log.info("user Client Auth %s" , str(self.UserClientAuthen.user_id)) ;
                    self.keyAuthorize =   self.utility.my_random_string(15);
                    samples['keyAuthorize'] =  self.keyAuthorize #; "#987654321";
                    
                    self.startDate = self.utility.getCurrentDate();
                    self.expireDate = self.utility.plusTime(self.startDate, 5)
                    model.UserSessionAuthen.createSessionAuthen( self.keyAuthorize,self.startDate, self.expireDate  ) ;
            
                     
            else:    
            
                if( request.body):
                    
                    self.df = json.loads(request.body, encoding=request.charset);
                    log.info( "get value : request.body " +  self.df);
                    #print self.df;
                    #set keyAuthorize
                    self.client_id = self.df['clientId'];
                    self.client_secret = self.df['clientSecret'];             
                
                
                
                
                    samples = self.df;
                else:
                    samples = {u'userName': u'tong', u'keyAuthorize': None, u'password': u'tong', u'dataTestSurfvey': None, u'passKey': u'#13456789'};
                    
                    self.client_id = kw['clientId'];
                    self.client_secret = kw['clientSecret'];
            
            
            
            
            
        except Exception as e:
            log.error(e);
            if kw:
                samples = kw;
                samples['keyAuthorize'] = "#987654321";
            
            #samples = {u'userName': u'tong', u'keyAuthorize': None, u'password': u'tong', u'dataTestSurfvey': None, u'passKey': u'#13456789'};
             
        return samples;#dict(surfveyAuthorize=samples);
    
    @with_trailing_slash
    @expose('json')
    def createTest(self,*args,**kw):
       
        print "args  "  ,args;
        print "kw  " ,kw;
        
        for h in request.headers:
            print "%s , %s "  %(h,request.headers[h]);
            
        self.Keyauthorize = request.headers['Keyauthorize'];
        
        samples = kw;
        
        print "createTest key authorize : " , self.Keyauthorize;
        
        if model.UserSessionAuthen.currentSessionAuthen(self.Keyauthorize):
        #if  self.Keyauthorize == "459987456":   
            self.userExtenal = model.UseExtenalLink(id_user =  kw.get("idUser"),
                                                    user_type =kw.get("userType"),
                                                    id_test  = kw.get("idTest"),
                                                   # id_theme  = kw.get("idTheme"),
                                                    no_test  =  kw.get("noTest"),
                                                    user_name  =  kw.get("userName")
                                                    );
            
            self.userExtenal.save();
            
            #x = json.loads(kw, object_hook=lambda d: namedtuple('X', d.keys())(*d.values()))
            
            
            #1 create public
            self.defaultOption = model.QuestionOption.getByProjectDefault(self.userExtenal.id_test,'1');
            if(self.defaultOption is None):
                print "defaultOption is null"
                self.defaultOption = model.QuestionOption();  
            
            self.activate_date = self.utility.getStartDate()
            self.option = model.QuestionOption(id_question_project = self.defaultOption.id_question_project,
                                               id_question_theme = self.defaultOption.id_question_theme,
                                               name_publication = str(self.defaultOption.name_publication.encode('utf8')) + "-" + str(self.userExtenal.user_name.encode('utf8')),
                                               id_fix_random_type = self.defaultOption.id_fix_random_type,
                                               activate_date = self.activate_date,
                                               expire_date = self.utility.plusDate(self.activate_date, 365),
                                               id_close_type = self.defaultOption.id_close_type,
                                               id_question_invitation =  self.defaultOption.id_question_invitation,
                                               header_message =self.defaultOption.header_message,
                                               footer_message = self.defaultOption.footer_message,
                                               welcome_message = self.defaultOption.welcome_message,
                                               end_message = self.defaultOption.end_message,
                                               use_question_no = self.defaultOption.use_question_no,
                                               duration_time   = self.defaultOption.duration_time,
                                               random_answer = self.defaultOption.random_answer,
                                               show_navigator = self.defaultOption.show_navigator,
                                               redirect_url = self.defaultOption.redirect_url,
                                               redirect_other_url = self.defaultOption.redirect_other_url,
                                               no_use = self.userExtenal.no_test,
                                               show_score = self.defaultOption.show_score,
                                               use_general_information = self.defaultOption.use_general_information
                                               );   
            
                 
            
            self.option.save();
            
            print "leng : %s " %(len(self.defaultOption.numberquestion))
            
            for defaultOp in self.defaultOption.numberquestion:
                self.numberQuestionGroup = model.NumberQuestionGroup(id_question_option = self.option.id_question_option,
                                                                     id_question_group = defaultOp.id_question_group,
                                                                     amount = defaultOp.amount)
                
                self.numberQuestionGroup.save()
                del defaultOp
            
            
            
            self.userExtenal.id_question_option = self.option.id_question_option;
            #2 
            
            samples['idPublic'] = self.option.id_question_option;
            samples['status'] = True;
            samples['message'] = "create success";
            samples['urlTest'] = "create success";
            samples['createDate'] =  self.option.activate_date ;#datetime.now() ; #"2015-06-23 12:02:57" ;#
            samples['expireDate'] = self.option.expire_date;#datetime.now() +   timedelta(days=30 ) ; #"2015-07-23 12:02:57";#
        else : 
            log.warning("Keyauthorize %s is expired" %self.Keyauthorize);
            
            
            samples['status'] = False;
            samples['message'] = "Keyauthorize %s is expired" %self.Keyauthorize;
        
        
        response.headers['KeyAuthorize'] = self.Keyauthorize
            
        return samples;
    
    @with_trailing_slash
    @expose('json')
    def evaluate(self,*args,**kw):
        log.info("evaluate")
        
        log.info( "---------evaluate-----------------")
         
        log.info( args);
        log.info ( "kw = %s  " %kw);
        samples = kw;
        if('Keyauthorize' in request.headers):
            self.Keyauthorize = request.headers['Keyauthorize'];
        else:
            self.Keyauthorize = '0000000000';
            
        log.info( "11 key authorize : " + self.Keyauthorize);
        
        
        
        if model.UserSessionAuthen.currentSessionAuthen(self.Keyauthorize): #self.Keyauthorize == "#987654321" :
            
            log.info( "idOwnerTest : %s , idTest : %s , idPublic : %s" %(kw.get("idOwnerTest") , kw.get("idTest"),kw.get("idPublic") ) );
            
            self.userExtenal = model.UseExtenalLink.getUserLinkBy( idUser= kw.get("idOwnerTest"),idTest = kw.get("idTest"),idPublic = kw.get("idPublic"));
            
            if self.userExtenal :
                log.info( "create userExtenal")
                #create sur_voter
                self.mapExtenal = model.MapVoterExtenalLink.getUserLinkVoterBy(self.userExtenal.id_use_external_link, kw.get("idUser"));
                 
                self.voter = model.Voter();
                if( self.mapExtenal is None or self.mapExtenal.voter is None):
                    log.info( "create voter")
                    log.info("user external is not voter %s",kw.get("email"));
                    self.voter = model.Voter.getVoterByEmail(kw.get("email"));
                    if self.voter is None:
                        log.info("voter %s is not existed",kw.get("email"));
                        self.voter = model.Voter(email = kw.get("email"), prefix = kw.get("idPrefix"), firstname = kw.get("firstname"), 
                                                 lastname = kw.get("lastname"), user_id_owner  = 3, id_marriage_status =  kw.get("idMarriageStatus"),
                                                 birthdate =   kw.get("birthdate"), id_gender = kw.get("idGender")
                                                 );
                        self.voter.save();
                    
                    
                    self.mapExternalLink = model.MapVoterExtenalLink(id_use_external_link =  self.userExtenal.id_use_external_link, 
                                                                     id_voter= self.voter.id_voter,
                                                                     id_user_ref= kw.get("idUser")
                                                                     );
                    self.mapExternalLink.save();
                    #self.userExtenal.id_voter = self.voter.id_voter; 
                #create sur_respondents
                
                    self.respondents = model.Respondents(id_voter = self.voter.id_voter,
                                                         id_question_project = kw.get("idTest"),
                                                         id_question_option  = kw.get("idPublic"),
                                                         key_gen = self.utility.my_random_string(string_length=25),
                                                         redirect_other_url = self.utility.convertToBit (kw.get("configUrlTest"))
                                                         );
                    
                     
                    #self.respondents.finished =0;
                    #self.respondents.score_exam =0;
                    
                    self.respondents.save();
                #create link
                else:
                    self.voter =  self.mapExtenal.voter;
                    self.respondents = model.Respondents.getByVoterIdAndPublicId(str(self.voter.id_voter), str(kw.get("idPublic")));
                                                                                 
                     
                    
                log.info( "id voter : %s"  %self.voter.id_voter);
                
                samples['urlTest'] =  self.urlUtility.URL_QUESTIONNAIRE.format(nameserver=self.urlServer,key=self.respondents.key_gen)  ;
                print samples['urlTest'] 
                #("{0}/ans/reply/{1}.{2}.{3}.0.html").format(request.application_url,str(kw.get("idTest")) ,str(kw.get("idPublic")) , str(self.voter.id_voter))  ;

                samples['status'] = True;
                samples['errorCode'] = 'S0001';            
                samples['message'] = "Create Success ";
            else:
                samples['status'] = False;
                samples['errorCode'] = 'E0002';            
                samples['message'] = "Find not found ";
                
        
        else:
            log.error( "Keyauthorize : is not same "  );
        
        response.headers['KeyAuthorize'] = self.Keyauthorize;
        
        print "------------end evaluate---------------------"
        print samples
         
        return samples;
    
    
    @with_trailing_slash
    @expose('json')
    def getScore(self,*args,**kw):
        log.info("getScore")
        samples = kw;
        print "-------------------------";
         
        print kw['idUser'];
        print kw['idPublic'];
        print "-------------------------";
        
        
        for h in request.headers:
            print "header : %s , %s "  %(h,request.headers[h]);
            
        self.Keyauthorize = request.headers['Keyauthorize'];
        
        
        if('Keyauthorize' in request.headers):
            self.Keyauthorize = request.headers['Keyauthorize'];
        else:
            self.Keyauthorize = '0000000000';
            
        log.info( "11 key authorize : " + self.Keyauthorize);
        
        samples['score'] = None;
        samples['urlscore'] = '';
                
        if model.UserSessionAuthen.currentSessionAuthen(self.Keyauthorize): #self.Keyauthorize == "#987654321" :
            print "success %s " %self.Keyauthorize ;
            
            self.respondents = model.Respondents.getByidUserandPublicId(kw['idUser'],kw['idPublic']);
            
            if (self.respondents):
                print 'score : %s, %s , %s' %(self.respondents.score_exam,self.respondents.full_score,self.respondents.personality_score) ;
                
                if self.respondents.personality_score is not None :
                    samples['score'] =  self.respondents.personality_score
                    samples['fullScore'] = None
                else:
                    samples['score'] =  self.respondents.score_exam
                    samples['fullScore'] = self.respondents.full_score
                    
                samples['urlScore'] = '';
                
            samples['status'] = True;
            samples['errorCode'] = 'S0001';            
            samples['message'] = "";
                
        else:
            samples['status'] = False;
            samples['errorCode'] = 'E0002';            
            samples['message'] = "Session is not match ";
        
        response.headers['KeyAuthorize'] = self.Keyauthorize;
        return samples;
            
Exemplo n.º 33
0
    def __init__(self):

        self.utility = Utility()
Exemplo n.º 34
0
    def __init__(self, models, session, config_type=None, translations=None):
        super(ProjectController, self).__init__()

        self.model = models
        self.utility = Utility()