Ejemplo n.º 1
0
 def createAccessControl(self,*args,**kw):         
     reload(sys).setdefaultencoding('utf8')
     self.success = True;
     self.result = False;
     self.message = 'Create Success';        
  
     self.accesscontrol = AccessControlObject(**kw);
     self.acc = self.accesscontrol.accesscontrol
             
     self.mapvoter = model.MapAccessControlVoter();       
     
     print self.acc  
                                    
     if (self.utility.isEmpty(self.acc.id_access_control_group)): 
         self.acc.id_access_control_group=None                  
         self.acc.save()   
     else :
         self.acc.updateall()        
         
     for dataselect in self.accesscontrol.data_select :                          
         data = JsontoObject(dataselect);            
         if (not self.utility.isNumber(data.id_map_access_control_voter)) :                    
                 data.id_map_access_control_voter = None            
              
         self.mapvoter.id_map_access_control_voter = data.id_map_access_control_voter
         self.mapvoter.id_voter = data.id_voter
         self.mapvoter.id_access_control_group = self.acc.id_access_control_group 
                 
         self.mapvoter.updateall()  
         
     self.result = True; 
     return dict(success=self.success, result = self.result , message = self.message);
Ejemplo n.º 2
0
 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() )
Ejemplo n.º 3
0
    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}  )
Ejemplo n.º 4
0
 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());
Ejemplo n.º 5
0
 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);
Ejemplo n.º 6
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}  )