Exemple #1
0
     def removeBeneficiary(self):
          result={}
          try:

               intermediary_id=self.myjson["Intermediaryid"]
                                  
          except Exception as e:
               #print "Content-type: text/html\n" 
               result["message"]=e.message
               return (json.JSONEncoder().encode(result)) 
               #sys.exit() 

          
          try:
               #engine=create_engine('mysql://*****:*****@localhost/wellness', echo=False) 
               engine=db
               # create a Session
               Session = sessionmaker(bind=engine)
               session = Session()
                                   
               
               # querying for a record in the physical_activity pattern table
               res= session.query(Beneficiary).filter(Beneficiary.intermediary_id==intermediary_id).first()
                           
               if res is None:
                    session.commit()
                    result["message"]="The Beneficiary's record doesn't exist hence it can't be deleted"
                    pass
               else:
                    session.delete(res)
                    
                    session.commit()

                    result["message"]="The Beneficiary's record  was deleted sucessfully"
               session.close()
               engine.dispose()    
               dbconn.close()

               return (json.JSONEncoder().encode(result))
                    
                                   
                                   
          except Exception as e:
               session.close()
               engine.dispose()          
               dbconn.close()

               #print "Content-type: text/html\n" 
                                   
               result["message"]="Error: %s"%e
               #print      
               return (json.JSONEncoder().encode(result))
Exemple #2
0
    def removeBeneficiary(self):
        result = {}
        try:

            intermediary_id = self.myjson["Intermediaryid"]

        except Exception as e:
            #print "Content-type: text/html\n"
            result["message"] = e.message
            return (json.JSONEncoder().encode(result))
            #sys.exit()

        try:
            #engine=create_engine('mysql://*****:*****@localhost/wellness', echo=False)
            engine = db
            # create a Session
            Session = sessionmaker(bind=engine)
            session = Session()

            # querying for a record in the physical_activity pattern table
            res = session.query(Beneficiary).filter(
                Beneficiary.intermediary_id == intermediary_id).first()

            if res is None:
                session.commit()
                result[
                    "message"] = "The Beneficiary's record doesn't exist hence it can't be deleted"
                pass
            else:
                session.delete(res)

                session.commit()

                result[
                    "message"] = "The Beneficiary's record  was deleted sucessfully"
            session.close()
            engine.dispose()
            dbconn.close()

            return (json.JSONEncoder().encode(result))

        except Exception as e:
            session.close()
            engine.dispose()
            dbconn.close()

            #print "Content-type: text/html\n"

            result["message"] = "Error: %s" % e
            #print
            return (json.JSONEncoder().encode(result))
 def isAssignedBeneficiary(self):
      result={}
      try:
          
           intermediary_id=self.myjson["Username"]
                              
      except Exception as e:
           #print "Content-type: text/html\n" 
           result["message"]="Error%s"%e.message
           return (json.JSONEncoder().encode(result))
      
      
      try:
           #engine=create_engine('mysql://*****:*****@localhost/wellness', echo=False) 
           engine=db
           # create a Session
           Session = sessionmaker(bind=engine)
           session = Session()
                               
           # querying for a record in the physical_activity pattern table
           res= session.query(Intermediary,Beneficiary).filter(Intermediary.intermediary_id==Beneficiary.intermediary_id).filter(Beneficiary.intermediary_id==intermediary_id).first()
           if res is None:
                result["message"]="This intermediary is not yet assigned a Beneficary."
                result["Id"]=None
           else: 
                interm,ben=res
                result["message"]="This intermediary is arleady assigned a Beneficary. Continuing with this intermediary will override details of an existing beneficiary"
                result["Fname"]=ben.beneficiary_fname
                result["Lname"]=ben.beneficiary_lname
                result["Mobile"]=ben.beneficiary_mobile
                result["Id"]=ben.id
           
           session.close()
           engine.dispose()
           dbconn.close()
                
           return (json.JSONEncoder().encode(result))                   
                               
      except Exception as e:
           session.close()
           engine.dispose() 
           dbconn.close()
                     
           #print "Content-type: text/html\n" 
                               
           result["message"]="Error: %s"%e
           result["Id"]=None
           #print      
           return (json.JSONEncoder().encode(result))
     def countIntermediaries(self):
          result={}              
          
          counter=0
          intermediary_records={}          
          
          try:
               #engine=create_engine('mysql://*****:*****@localhost/wellness', echo=False) 
               engine=db
               # create a Session
               Session = sessionmaker(bind=engine)
               session = Session()

               data={}
               intermediaries_ids=[]
               # querying for intermediaries who have been assigned beneficiaries
               #res= session.query(Intermediary,Beneficiary).filter(Intermediary.intermediary_id==Beneficiary.intermediary_id).all()
               res= session.query(func.count(Intermediary.intermediary_id).label("count_interm")).filter(Intermediary.intermediary_id==Beneficiary.intermediary_id).first()
             
               if res.count_interm is None:
                    counter=0
               else: 
                    counter=res.count_interm
               
               result["counter"]=counter
               session.close()
               engine.dispose()
               dbconn.close()


               return(json.JSONEncoder().encode(OrderedDict(sorted(result.items(), key=lambda t: t[0]))))
     
                                   
                                   
          except Exception as e:
                         
               #print "Content-type: text/html\n" 
               session.close()
               engine.dispose()
               dbconn.close()
                                   
               intermediary_records["R00"]=e
               #print      
               return (json.JSONEncoder().encode(intermediary_records))
     def retrieveIntermediaryInDB(self):       
          result={}              
          
          counter=0
          intermediary_records={}          
          
          try:
               #engine=create_engine('mysql://*****:*****@localhost/wellness', echo=False) 
               engine=db
               # create a Session
               Session = sessionmaker(bind=engine)
               session = Session()

               data={}
               intermediaries_ids=[]
               # querying for intermediaries who have been assigned beneficiaries
               res= session.query(Intermediary,Beneficiary).filter(Intermediary.intermediary_id==Beneficiary.intermediary_id).all()
               
               for interm_tuple,ben_tuple in res:
                    if counter<10:
                         Key1="R0"
                    else:
                         Key1="R"
                    
                    data["D0"]="%s %s"%(interm_tuple.intermediary_fname,interm_tuple.intermediary_lname)      
                    data["D1"]="%s"%interm_tuple.intermediary_id   
                    data["D2"]="%s %s. Mobile:%s"%(ben_tuple.beneficiary_fname,ben_tuple.beneficiary_lname,ben_tuple.beneficiary_mobile)
                    
                    data["D3"]="%s"%ben_tuple.id 
                    intermediary_records["%s%s"%(Key1,counter)]=OrderedDict(sorted(data.items(), key=lambda t: t[0]))
                                       
                    intermediaries_ids.append(ben_tuple.intermediary_id)
                    counter=counter+1
                    
                    data={}
                    
                    
                    #res= session.query(Intermediary,Beneficiary).filter(Intermediary.intermediary_id not in Beneficiary.intermediary_id).all()
               res= session.query(Intermediary).all()
                    
                                        
               prevcounter=counter
               data={}
               found=0
               for interm_tuple in res:
                         
                    if counter<10:
                         Key1="R0"
                    else:
                         Key1="R"
                              
                    if prevcounter>=0:
                              
                         #for intermediary_id in intermediaries_ids:
                         #     print intermediary_id,interm_tuple.intermediary_id
                         #     if intermediary_id==interm_tuple.intermediary_id:
                         #          print "Break"
                         #          found=1
                         #          break;
                         #if found ==0:
                         if interm_tuple.intermediary_id not in intermediaries_ids:
                              data["D0"]="%s %s"%(interm_tuple.intermediary_fname,interm_tuple.intermediary_lname)      
                              data["D1"]="%s"%interm_tuple.intermediary_id   
                              data["D2"]="None"
                              intermediary_records["%s%s"%(Key1,counter)]=OrderedDict(sorted(data.items(), key=lambda t: t[0]))
                              
                              counter=counter+1
                                   
                         data={}
                         found=0
                                             
                    
                    
               session.close()
               engine.dispose()
               dbconn.close()

               return(json.JSONEncoder().encode(OrderedDict(sorted(intermediary_records.items(), key=lambda t: t[0]))))
     
                                   
                                   
          except Exception as e:
                         
               #print "Content-type: text/html\n" 
               session.close()
               engine.dispose()
               dbconn.close()
                                   
               intermediary_records["R00"]=e
               #print      
               return (json.JSONEncoder().encode(intermediary_records))
     def retrieveOneIntermediaryDetail(self):       
          result={}              
          
          counter=0
          intermediary_record={}
          try:
              
               intermediary_id=self.myjson["Username"]
                                  
          except Exception as e:
               #print "Content-type: text/html\n" 
               result["message"]="Error%s"%e.message
               return (json.JSONEncoder().encode(result))
          
               
          
          try:
               #engine=create_engine('mysql://*****:*****@localhost/wellness', echo=False) 
               engine=db
               # create a Session
               Session = sessionmaker(bind=engine)
               session = Session()

               data={}
               intermediaries_ids=[]
               # querying for intermediaries who have been assigned beneficiaries
               res= session.query(Intermediary).filter(Intermediary.intermediary_id==intermediary_id).first()
                    
                                        
     
               data={}
               found=0
               
               if res is None:
                    pass
               else:
  
                              
                    
                    data["D0"]="%s %s"%(res.intermediary_fname,res.intermediary_lname)      
                    data["D1"]="%s"%res.intermediary_id   
               
                    
          
               intermediary_record["R00"]=data         
               data={}
                         
                                             
                    
                    
               session.close()
               engine.dispose()
               dbconn.close()

               return(json.JSONEncoder().encode(OrderedDict(sorted(intermediary_record.items(), key=lambda t: t[0]))))
     
                                   
                                   
          except Exception as e:
                         
               #print "Content-type: text/html\n" 
               session.close()
               engine.dispose()
               dbconn.close()
                                   
               intermediary_record["R00"]=e
               #print      
               return (json.JSONEncoder().encode(intermediary_records))
Exemple #7
0
class SaveIntermediary:
     def __init__(self,myjson):
          self.myjson=myjson
     def saveIntermediaryInDB(self):       
          datecaptured=""
          weight=""
          result={}
          allow_insert=1
          # Get data from fields
          try:
              
               fname=self.myjson["Fname"]
               lname=self.myjson["Lname"]
               username=self.myjson["Username"]
               
                        
                             
          except Exception:
               #print "Content-type: text/html\n" 
               result["message"]='There was an error in processing a JSON object'
               return (json.JSONEncoder().encode(result)) 
               #sys.exit() 
          
          
          if(fname==None) or (lname==None) or (username==None):
               #print "Content-type: text/html\n" 
               result["message"]="Error: Some fields are missing. Please fill in both fields"
               return (json.JSONEncoder().encode(result)) 
               #sys.exit()
               
          
          
          
          try:
               #engine=create_engine('mysql://*****:*****@localhost/wellness', echo=False) 
               engine=db
               # create a Session
               Session = sessionmaker(bind=engine)
               session = Session()
                                   
               # querying for a record in the physical_activity pattern table
               res= session.query(Intermediary).filter(Intermediary.intermediary_id==username).first()
               if res is None:
                    pass
               else:
                    intermediaryrecord=res
                    #previousfname=intermediaryrecord.intermediary_fname
                    intermediaryrecord.intermediary_fname=fname
                    
                    intermediaryrecord.intermediary_lname=lname
                    
                                
                                             
                    allow_insert=0
                    
                    session.commit()
                    result["message"]="The Intermediary's record  was updated sucessfully"
                
                                   
                                   
          except Exception as e:
               session.close()
               engine.dispose()          
               dbconn.close()

               #print "Content-type: text/html\n" 
                                   
               result["message"]="Error: %s"%e
               #print      
               return (json.JSONEncoder().encode(result))
               #sys.exit()
                                         
                         
                         
          if allow_insert==1:
               try:
                    #print "Content-Type: text/html\n"
                    #engine=db
                    # create a Session
                    #Session = sessionmaker(bind=engine)
               
                    #session = Session()
               
                    # Create weight
                    #new_food=FoodAndBeverage('KTLNTW00',datetime.date(1988,12,01))
                    new_record=Intermediary(username,fname,lname)
                         
                    session.add(new_record)
               
               
                    # commit the record the database
               
               
                    session.commit()
                    result["message"]="The Intermediary record was recorded sucessfully"
                    
               
               except Exception as e:
                    session.close()
                    engine.dispose()
               dbconn.close()

                    result["message"]=e
                    return (json.JSONEncoder().encode(result)) 
        
          
          session.close()
          engine.dispose()          
          dbconn.close()
          return (json.JSONEncoder().encode(result))
     def saveIntermediaryInDB(self):       
          datecaptured=""
          weight=""
          result={}
          allow_insert=1
          # Get data from fields
          try:
              
               fname=self.myjson["Fname"]
               lname=self.myjson["Lname"]
               username=self.myjson["Username"]
               
                        
                             
          except Exception:
               #print "Content-type: text/html\n" 
               result["message"]='There was an error in processing a JSON object'
               return (json.JSONEncoder().encode(result)) 
               #sys.exit() 
          
          
          if(fname==None) or (lname==None) or (username==None):
               #print "Content-type: text/html\n" 
               result["message"]="Error: Some fields are missing. Please fill in both fields"
               return (json.JSONEncoder().encode(result)) 
               #sys.exit()
               
          
          
          
          try:
               #engine=create_engine('mysql://*****:*****@localhost/wellness', echo=False) 
               engine=db
               # create a Session
               Session = sessionmaker(bind=engine)
               session = Session()
                                   
               # querying for a record in the physical_activity pattern table
               res= session.query(Intermediary).filter(Intermediary.intermediary_id==username).first()
               if res is None:
                    pass
               else:
                    intermediaryrecord=res
                    #previousfname=intermediaryrecord.intermediary_fname
                    intermediaryrecord.intermediary_fname=fname
                    
                    intermediaryrecord.intermediary_lname=lname
                    
                                
                                             
                    allow_insert=0
                    
                    session.commit()
                    result["message"]="The Intermediary's record  was updated sucessfully"
                
                                   
                                   
          except Exception as e:
               session.close()
               engine.dispose()          
               dbconn.close()

               #print "Content-type: text/html\n" 
                                   
               result["message"]="Error: %s"%e
               #print      
               return (json.JSONEncoder().encode(result))
               #sys.exit()
                                         
                         
                         
          if allow_insert==1:
               try:
                    #print "Content-Type: text/html\n"
                    #engine=db
                    # create a Session
                    #Session = sessionmaker(bind=engine)
               
                    #session = Session()
               
                    # Create weight
                    #new_food=FoodAndBeverage('KTLNTW00',datetime.date(1988,12,01))
                    new_record=Intermediary(username,fname,lname)
                         
                    session.add(new_record)
               
               
                    # commit the record the database
               
               
                    session.commit()
                    result["message"]="The Intermediary record was recorded sucessfully"
                    
               
               except Exception as e:
                    session.close()
                    engine.dispose()
               dbconn.close()

                    result["message"]=e
                    return (json.JSONEncoder().encode(result)) 
Exemple #9
0
     def saveCommentInDB(self):
          
          commentdetails="" 
          date_captured="" 
          time_captured="" 
          event_type=""
          message_sent_status=""
          result={}
          teamname=""
          allow_insert=1
          
          # Get data from fields
          try:
                            
               commentdetails=self.myjson["MessageBody"] 
               date_captured=datetime.date.today()# today's date
               time_captured=time.strftime("%H:%M:%S")
               teamname=self.myjson["TeamName"]
               optionaltext=self.myjson["OptionalText"]
               event_type=self.myjson["EventType"]
               message_sent_status=False          
               

               
                
          except Exception as e:
               #print "Content-type: text/html\n" 
               result["message"]='There was an error in processing a JSON object:%s'%e
               return (json.JSONEncoder().encode(result)) 
               #sys.exit() 
          

          if (commentdetails=="None")  and (event_type=="None"):
               #print "Content-type: text/html\n" 
               result["message"]="There is an error in saving your message due to missing of some information"
               return (json.JSONEncoder().encode(result)) 



               
          try:
            if teamname=="None":
              b_id=self.b_id
            else:
              #get beneficiary id of the team that owns an event being commmented
              engine=db
              Session = sessionmaker(bind=engine)
                    
              session = Session()

              res=session.query(Beneficiary).filter(Beneficiary.team_name==teamname).first()
              if res is None:
                result["message"]="The team you are trying to comment doesn't exist"
                return (json.JSONEncoder().encode(result))
              else:
                b_id=res.id






          except Exception as e:
            pass
          if allow_insert==1:           
               try:
                    
                    #print "Content-Type: text/html\n"
                    #engine=create_engine('mysql://*****:*****@localhost/wellness', echo=False)
                    engine=db
                    # create a Session
                    Session = sessionmaker(bind=engine)
                    
                    session = Session()
                    
                    # Create food
                    #new_food=FoodAndBeverage('KTLNTW00',datetime.date(1988,12,01))
                    
                    new_comment=Comment(b_id,self.i_id,commentdetails,date_captured,time_captured,event_type,message_sent_status)
                                            
                    
                    
                    session.add(new_comment)
                    
                    
                    # commit the record the database
                    
                    
                    session.commit()




                    if teamname=="None":

                      res=session.query(Intermediary,Beneficiary).filter(Intermediary.intermediary_id==Beneficiary.intermediary_id).filter(Intermediary.intermediary_id==self.i_id).first()
                      if res is None:
                        result["message"]="Error failed to send a message"
                        return (json.JSONEncoder().encode(result))
                      else:
                        interm,ben=res
                        ben_mobile=ben.beneficiary_mobile
                        interm_mobile=interm.mobile
                        feedback_message=commentdetails

                        myjson2={"recipient":ben_mobile,"message":feedback_message}
                        obj=QueueFeedback(myjson2)
                        res=obj.saveFeedbackInDB()
                        
                    
                    else:
                      res=session.query(Intermediary,Beneficiary).filter(Intermediary.intermediary_id==Beneficiary.intermediary_id).filter(Beneficiary.team_name==teamname).first()
                      if res is None:
                        result["message"]="Error: You can't leave a comment to this team since it doesn't exist"
                        return (json.JSONEncoder().encode(result))            
                      else:
                        interm,ben=res
                        interm_mobile=interm.mobile
                        ben_mobile=ben.beneficiary_mobile
                        team_name=ben.team_name
                        feedback_message=optionaltext
                        
                        myjson2={"recipient":interm_mobile,"message":feedback_message}
                        obj=QueueFeedback(myjson2)
                        res=obj.saveFeedbackInDB()
                       
                        myjson2={"recipient":ben_mobile,"message":feedback_message}
                        obj=QueueFeedback(myjson2)
                        res=obj.saveFeedbackInDB()


                    session.close()
                    engine.dispose()
                    dbconn.close()                 
                     
                    
               except Exception as e:
                    session.close()
                    engine.dispose()
                    dbconn.close()

                    result["message"]=e
                    return (json.JSONEncoder().encode(result)) 
               
               result["message"]="Your comment has been added. Also the message has been sent to team %s to notify them of your new comment"%team_name;
               return (json.JSONEncoder().encode(result))
Exemple #10
0
     def retrieveBeneficiaryInDB(self):       
          result={}              
          
          counter=0
          beneficiary_records={}
          try:
              
               fname=self.myjson["Fname"]
               lname=self.myjson["Lname"]
               mobile=self.myjson["Mobile"]
               intermediary_id=self.myjson["Intermediaryid"]
                                  
          except Exception as e:
               #print "Content-type: text/html\n" 
               result["message"]=e.message
               return (json.JSONEncoder().encode(result))          
          
          
          
          try:
               #engine=create_engine('mysql://*****:*****@localhost/wellness', echo=False) 
               engine=db
               # create a Session
               Session = sessionmaker(bind=engine)
               session = Session()

               data={}
               # querying for a record in the physical_activity pattern table
               res= session.query(Beneficiary).filter(Beneficiary.intermediary_id==intermediary_id).first()
               
               for ben_tuple in res:
                    if counter<10:
                         Key1="R0"
                    else:
                         Key1="R"
                    
                    data["D0"]="%s %s"%(ben_tuple.beneficiary_fname,ben_tuple.beneficiary_lname)      
                    data["D1"]="%s"%ben_tuple.beneficiary_mobile                   
                    beneficiary_records["%s%s"%(Key1,counter)]=data
               
                    counter=counter+1
                    
                    data={}            
                                             
                    
                    
               session.close()
               engine.dispose()
               dbconn.close()
               return(json.JSONEncoder().encode(OrderedDict(sorted(beneficiary_records.items(), key=lambda t: t[0]))))
     
                                   
                                   
          except Exception as e:
                         
               #print "Content-type: text/html\n" 
               session.close()
               engine.dispose()
               dbconn.close()                   
               beneficiary_records["R00"]=-1
               #print      
               return (json.JSONEncoder().encode(beneficiary_records))
Exemple #11
0
    def saveBeneficiaryInDB(self):
        result = {}
        allow_insert = 1
        # Get data from fields
        try:

            fname = self.myjson["Fname"]
            lname = self.myjson["Lname"]
            mobile = self.myjson["Mobile"]
            intermediary_id = self.myjson["Intermediaryid"]

        except Exception as e:
            #print "Content-type: text/html\n"
            result["message"] = e.message
            return (json.JSONEncoder().encode(result))
            #sys.exit()

        if (fname == "") or (lname == "") or (intermediary_id
                                              == "") or (mobile == ""):
            #print "Content-type: text/html\n"
            result[
                "message"] = "Error: Some fields are missing. Please fill in both fields"
            return (json.JSONEncoder().encode(result))
            #sys.exit()

        try:
            #engine=create_engine('mysql://*****:*****@localhost/wellness', echo=False)
            engine = db
            # create a Session
            Session = sessionmaker(bind=engine)
            session = Session()

            # querying for a record in the physical_activity pattern table
            res = session.query(Beneficiary).filter(
                Beneficiary.intermediary_id == intermediary_id).first()

            if res is None:
                session.commit()
                pass
            else:
                beneficiaryrecord = res

                #previousfname=intermediaryrecord.intermediary_fname
                beneficiaryrecord.beneficiary_fname = fname

                beneficiaryrecord.beneficiary_lname = lname
                #beneficiaryrecord.intermediary_id=intermediary_id

                allow_insert = 0

                session.commit()
                result[
                    "message"] = "The Beneficiary's record  was updated sucessfully"

        except Exception as e:
            session.close()
            engine.dispose()
            dbconn.close()

            #print "Content-type: text/html\n"

            result["message"] = "Error: %s" % e
            #print
            return (json.JSONEncoder().encode(result))
            #sys.exit()

        if allow_insert == 1:
            try:
                #print "Content-Type: text/html\n"
                #engine=db
                # create a Session
                #Session = sessionmaker(bind=engine)

                #session = Session()

                # Create weight
                #new_food=FoodAndBeverage('KTLNTW00',datetime.date(1988,12,01))
                new_record = Beneficiary(fname, lname, mobile, intermediary_id)

                session.add(new_record)

                # commit the record the database

                session.commit()

                result[
                    "message"] = "The Beneficiary's record was recorded sucessfully"

            except Exception as e:
                result["message"] = e
                return (json.JSONEncoder().encode(result))
        session.close()
        engine.dispose()
        dbconn.close()

        return (json.JSONEncoder().encode(result))
Exemple #12
0
     def saveCommentInDB(self):
          
          commentdetails="" 
          date_captured="" 
          time_captured="" 
          event_start_date=""
          event_end_date=""
          event_type=""
          message_sent_status=""
          result={}
          allow_insert=1
          
          # Get data from fields
          try:
                            
               commentdetails=self.myjson["MessageBody"] 
               date_captured=datetime.date.today()# today's date
               time_captured=time.strftime("%H:%M:%S")
               day=self.myjson["Day"]
               #event_start_date=self.myjson["StartDate"] 
               #event_end_date=self.myjson["EndDate"] 
               event_type=self.myjson["EventType"]
               message_sent_status=False          
               

               
                
          except Exception:
               #print "Content-type: text/html\n" 
               result["message"]='There was an error in processing a JSON object'
               return (json.JSONEncoder().encode(result)) 
               #sys.exit() 
          

          if (commentdetails=="None") and (day=="None") and (event_type=="None"):
               #print "Content-type: text/html\n" 
               result["message"]="There is an error in saving your message due to missing of some information"
               return (json.JSONEncoder().encode(result)) 
               #sys.exit()

               #sys.exit()



          if day=="Today":
               event_start_date = datetime.date.today()
               event_end_date = datetime.date.today()             
               
          elif day=="This week":
               #from monday up to sunday. 
               day_of_week = datetime.datetime.today().weekday()
               event_start_date =datetime.date.today()-datetime.timedelta(days=day_of_week)#monday
               event_end_date=event_start_date+datetime.timedelta(days=6)#sunday
     
              
          elif day=="Last week":
               day_of_week = datetime.datetime.today().weekday()
               event_end_date = datetime.date.today()-datetime.timedelta(days=(day_of_week+1))#last sunday. Subtract today from the number of days that have passed since sunday
               event_start_date  = event_end_date-datetime.timedelta(days=6)# Monday of the previous week.            
               
          elif day=="This month":
               #from 1st of this month to end of last month
               event_start_date =self.first_day_of_month(datetime.date.today())
               event_end_date=self.last_day_of_month(datetime.date.today())
          
               
          elif day=="Last month":
               #from 1st of last month to end of last month
               #startdate=self.first_day_of_month(first_day_of_month(datetime.date.today())-datetime.timedelta(days=1))
               event_start_date =self.first_day_of_month(self.first_day_of_month(datetime.date.today())-datetime.timedelta(days=1))               
               event_end_date=self.last_day_of_month(event_start_date)
          
          elif day=="Last three months":
               # go two months back
               first_day_last_month=self.first_day_of_month(self.first_day_of_month(datetime.date.today())-datetime.timedelta(days=1))
               event_start_date =self.first_day_of_month(first_day_last_month-datetime.timedelta(days=1))# subract 1 day to get to the end of a previous month before last month and get the first day of that month
               event_end_date=self.last_day_of_month(datetime.date.today())#
          else:
               result["message"]="Error: Failed to save a message."
               return (json.JSONEncoder().encode(result))              


               
          
          if allow_insert==1:           
               try:
                    
                    #print "Content-Type: text/html\n"
                    #engine=create_engine('mysql://*****:*****@localhost/wellness', echo=False)
                    engine=db
                    # create a Session
                    Session = sessionmaker(bind=engine)
                    
                    session = Session()
                    
                    # Create food
                    #new_food=FoodAndBeverage('KTLNTW00',datetime.date(1988,12,01))
                    
                    new_comment=Comment(self.b_id,commentdetails,date_captured,time_captured,event_start_date,event_end_date,event_type,message_sent_status)
                                            
                    
                    
                    session.add(new_comment)
                    
                    
                    # commit the record the database
                    
                    
                    session.commit()
                    session.close()
                    engine.dispose()
                    dbconn.close()                 
                     
                    
               except Exception as e:
                    session.close()
                    engine.dispose()
                    dbconn.close()

                    result["message"]=e
                    return (json.JSONEncoder().encode(result)) 
               
               result["message"]="The message was saved successfully. It will be delivered  later."
               return (json.JSONEncoder().encode(result))
Exemple #13
0
    def saveCommentInDB(self):

        commentdetails = ""
        date_captured = ""
        time_captured = ""
        event_start_date = ""
        event_end_date = ""
        event_type = ""
        message_sent_status = ""
        result = {}
        allow_insert = 1

        # Get data from fields
        try:

            commentdetails = self.myjson["MessageBody"]
            date_captured = datetime.date.today()  # today's date
            time_captured = time.strftime("%H:%M:%S")
            day = self.myjson["Day"]
            #event_start_date=self.myjson["StartDate"]
            #event_end_date=self.myjson["EndDate"]
            event_type = self.myjson["EventType"]
            message_sent_status = False

        except Exception:
            #print "Content-type: text/html\n"
            result[
                "message"] = 'There was an error in processing a JSON object'
            return (json.JSONEncoder().encode(result))
            #sys.exit()

        if (commentdetails == "None") and (day == "None") and (event_type
                                                               == "None"):
            #print "Content-type: text/html\n"
            result[
                "message"] = "There is an error in saving your message due to missing of some information"
            return (json.JSONEncoder().encode(result))
            #sys.exit()

            #sys.exit()

        if day == "Today":
            event_start_date = datetime.date.today()
            event_end_date = datetime.date.today()

        elif day == "This week":
            #from monday up to sunday.
            day_of_week = datetime.datetime.today().weekday()
            event_start_date = datetime.date.today() - datetime.timedelta(
                days=day_of_week)  #monday
            event_end_date = event_start_date + datetime.timedelta(
                days=6)  #sunday

        elif day == "Last week":
            day_of_week = datetime.datetime.today().weekday()
            event_end_date = datetime.date.today() - datetime.timedelta(
                days=(day_of_week + 1)
            )  #last sunday. Subtract today from the number of days that have passed since sunday
            event_start_date = event_end_date - datetime.timedelta(
                days=6)  # Monday of the previous week.

        elif day == "This month":
            #from 1st of this month to end of last month
            event_start_date = self.first_day_of_month(datetime.date.today())
            event_end_date = self.last_day_of_month(datetime.date.today())

        elif day == "Last month":
            #from 1st of last month to end of last month
            #startdate=self.first_day_of_month(first_day_of_month(datetime.date.today())-datetime.timedelta(days=1))
            event_start_date = self.first_day_of_month(
                self.first_day_of_month(datetime.date.today()) -
                datetime.timedelta(days=1))
            event_end_date = self.last_day_of_month(event_start_date)

        elif day == "Last three months":
            # go two months back
            first_day_last_month = self.first_day_of_month(
                self.first_day_of_month(datetime.date.today()) -
                datetime.timedelta(days=1))
            event_start_date = self.first_day_of_month(
                first_day_last_month - datetime.timedelta(days=1)
            )  # subract 1 day to get to the end of a previous month before last month and get the first day of that month
            event_end_date = self.last_day_of_month(datetime.date.today())  #
        else:
            result["message"] = "Error: Failed to save a message."
            return (json.JSONEncoder().encode(result))

        if allow_insert == 1:
            try:

                #print "Content-Type: text/html\n"
                #engine=create_engine('mysql://*****:*****@localhost/wellness', echo=False)
                engine = db
                # create a Session
                Session = sessionmaker(bind=engine)

                session = Session()

                # Create food
                #new_food=FoodAndBeverage('KTLNTW00',datetime.date(1988,12,01))

                new_comment = Comment(self.b_id, commentdetails, date_captured,
                                      time_captured, event_start_date,
                                      event_end_date, event_type,
                                      message_sent_status)

                session.add(new_comment)

                # commit the record the database

                session.commit()
                session.close()
                engine.dispose()
                dbconn.close()

            except Exception as e:
                session.close()
                engine.dispose()
                dbconn.close()

                result["message"] = e
                return (json.JSONEncoder().encode(result))

            result[
                "message"] = "The message was saved successfully. It will be delivered  later."
            return (json.JSONEncoder().encode(result))