def countRecordedMeals(self,beneficiary_id):
      result={}

      try:
        
        engine=db
        #create a Session
        Session = sessionmaker(bind=engine)
        session = Session()
        res = session.query(func.count(FoodAndBeverage.id).label("mealscounter")).filter(FoodAndBeverage.beneficiary_id==beneficiary_id).first()
        if res.mealscounter is None:
          awarded_points=0;
        else:
          awarded_points=res.mealscounter



        result["NumberOfMeals"]=awarded_points
        result["Message"]="Meals count obtained successfully"


      except Exception as e:
        result["NumberOfMeals"]=-1
        result["Message"]=e

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

      return (json.JSONEncoder().encode(result))
Exemple #2
0
    def saveMealInDB(self):

        starch = ""
        fruitsveg = ""
        dairy = ""
        fat = ""
        protein = ""
        result = {}
        allow_insert = 1

        # Get data from fields
        try:

            starch = self.myjson["Starch"]
            fruitsveg = self.myjson["Fruits"]
            dairy = self.myjson["Dairy"]
            fat = self.myjson["Fat"]
            protein = self.myjson["Protein"]
            date_eaten = self.myjson["DateEaten"]
            meal_type = self.myjson["MealType"]
            '''
               starch="Medium"
               fruitsveg="None"
               dairy="Large" 
               fat="None"
               protein="None" 
               date_eaten="2013-02-23"
               meal_type="Lunch"
               '''

        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 (starch == "None") and (fruitsveg == "None") and (
                dairy == "None") and (fat == "None") and (protein == "None"):
            #print "Content-type: text/html\n"
            result[
                "message"] = "Error: You have not specified any portion size in your meal"
            return (json.JSONEncoder().encode(result))
            #sys.exit()

        #check if a meal type exists
        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(
                FoodAndBeverage,
                Meal).filter(FoodAndBeverage.id == Meal.food_id).filter(
                    FoodAndBeverage.date_consumed == date_eaten).filter(
                        FoodAndBeverage.beneficiary_id == self.b_id).first()
            if res is None:
                session.close()
                engine.dispose()
                dbconn.close()
            else:
                food_record, meal_record = res
                meal_record_id = meal_record.id
                res = session.query(MealComposition).filter(
                    MealComposition.meal_id == meal_record_id).all()
                for portion_tuple in res:

                    if (portion_tuple.meal_group == "Starch"):
                        portion_tuple.portion_size = starch
                    elif portion_tuple.meal_group == "Fruits and Vegetables":
                        portion_tuple.portion_size = fruitsveg
                    elif portion_tuple.meal_group == "Fat":
                        portion_tuple.portion_size = fat
                    elif portion_tuple.meal_group == "Dairy":
                        portion_tuple.portion_size = dairy
                    elif portion_tuple.meal_group == "Protein":
                        portion_tuple.portion_size = protein

                allow_insert = 0
                #size=size-1 #ignore the last value because it has arleady been updated
                session.commit()
                result[
                    "message"] = "The following meal %s that was eaten on this date %s already existed in the database and it was updated" % (
                        meal_type, date_eaten)
                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))
            #sys.exit()

        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_food = FoodAndBeverage(self.b_id, date_eaten)
                new_meal = Meal(meal_type)
                meal_portions = [
                    MealComposition("High Carbs", starch, "Starch"),
                    MealComposition("Low Carbs", fruitsveg,
                                    "Fruits and Vegetables"),
                    MealComposition("Low Carbs", fat, "Fat Foods"),
                    MealComposition("Low Carbs", protein, "Protein Foods"),
                    MealComposition("Low Carbs", dairy, "Dairy")
                ]
                #meal_portions=[MealComposition("High Carbs",starch,"Starch"),MealComposition("Low Carbs",fat,"Fat Foods")]#,MealComposition("Low Carbs",protein,"Protein Foods"),MealComposition("Low Carbs",dairy,"Dairy")]

                new_meal.meal_composition = []
                new_meal.meal_composition.extend(meal_portions)
                new_food.meal = [new_meal]

                #result["message"]="%s%s%s%s%s"%(starch,fruitsveg,fat,dairy,protein)
                #return (json.JSONEncoder().encode(result))

                session.add(new_food)

                # commit the record the database

                session.commit()

            except Exception as e:
                session.close()
                engine.dispose()
                result["R00"] = {"F1": -6, "F0": e.message}
                dbconn.close()
                return (json.JSONEncoder().encode(result))
            session.close()
            engine.dispose()
            dbconn.close()

            result["R00"] = {
                "F1": 1,
                "F0": "The meal was recorded sucessfully"
            }
            return (json.JSONEncoder().encode(result))
Exemple #3
0
     def saveMealInDB(self):
          
          starch="" 
          fruitsveg="" 
          dairy="" 
          fat=""
          protein="" 
          result={}
          allow_insert=1
          
          # Get data from fields
          try:
                            
               starch=self.myjson["Starch"] 
               fruitsveg=self.myjson["Fruits"] 
               dairy=self.myjson["Dairy"] 
               fat=self.myjson["Fat"] 
               protein=self.myjson["Protein"] 
               date_eaten=self.myjson["DateEaten"]
               meal_type=self.myjson["MealType"]          
               
               
               '''
               starch="Medium"
               fruitsveg="None"
               dairy="Large" 
               fat="None"
               protein="None" 
               date_eaten="2013-02-23"
               meal_type="Lunch"
               '''
               
                
          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(starch=="None") and (fruitsveg=="None") and (dairy=="None") and (fat=="None") and (protein=="None"):
               #print "Content-type: text/html\n" 
               result["message"]="Error: You have not specified any portion size in your meal"
               return (json.JSONEncoder().encode(result)) 
               #sys.exit()


          #check if a meal type exists
          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(FoodAndBeverage,Meal).filter(FoodAndBeverage.id==Meal.food_id).filter(FoodAndBeverage.date_consumed==date_eaten).filter(FoodAndBeverage.beneficiary_id==self.b_id).first()
               if res is None:
                    pass
               else:
                    food_record,meal_record=res
                    meal_record_id=meal_record.id
                    res= session.query(MealComposition).filter(MealComposition.meal_id==meal_record_id).all()
                    for portion_tuple in res:
                         
                         if( portion_tuple.meal_group== "Starch") :
                              portion_tuple.portion_size=starch;
                         elif portion_tuple.meal_group== "Fruits and Vegetables" :
                              portion_tuple.portion_size=fruitsveg
                         elif portion_tuple.meal_group== "Fat" :
                              portion_tuple.portion_size=fat
                         elif portion_tuple.meal_group== "Dairy" :
                              portion_tuple.portion_size=dairy
                         elif portion_tuple.meal_group== "Protein" :
                              portion_tuple.portion_size=protein
                                
                                             
                    allow_insert=0
                    #size=size-1 #ignore the last value because it has arleady been updated
                    session.commit()
                    result["message"]="The following meal %s that was eaten on this date %s already existed in the database and it was updated"%(meal_type,date_eaten)
                    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))
               #sys.exit()
               
          
          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_food=FoodAndBeverage(self.b_id,date_eaten)
                    new_meal=Meal(meal_type)
                    meal_portions=[MealComposition("High Carbs",starch,"Starch"),MealComposition("Low Carbs",fruitsveg,"Fruits and Vegetables"),MealComposition("Low Carbs",fat,"Fat Foods"),MealComposition("Low Carbs",protein,"Protein Foods"),MealComposition("Low Carbs",dairy,"Dairy")]
                    #meal_portions=[MealComposition("High Carbs",starch,"Starch"),MealComposition("Low Carbs",fat,"Fat Foods")]#,MealComposition("Low Carbs",protein,"Protein Foods"),MealComposition("Low Carbs",dairy,"Dairy")]
                    
                    new_meal.meal_composition=[]
                    new_meal.meal_composition.extend(meal_portions)
                    new_food.meal=[new_meal]
                   
                    #result["message"]="%s%s%s%s%s"%(starch,fruitsveg,fat,dairy,protein)
                    #return (json.JSONEncoder().encode(result))                                               
                                 
                    
                    
                    session.add(new_food)
                    
                    
                    # commit the record the database
                    
                    
                    session.commit()
      
                                     
                     
                    
               except Exception as e:
                    session.close()
                    engine.dispose()
                    result["R00"]={"F1":-6,"F0":e.message}
                    dbconn.close()
                    return (json.JSONEncoder().encode(result)) 
               session.close()
               engine.dispose()
               dbconn.close()

               result["R00"]={"F1":1,"F0":"The meal was recorded sucessfully"}
               return (json.JSONEncoder().encode(result))
          def getDataPoints(self):
                    
                    # Get data from fields
                    try:
                              
                              day=self.myjson["Day"] 
                              #food_content=self.myjson["FoodContent"] 
                              #meal_type=self.myjson["MealType"]
                              #if day=="By date":
                              #     startdate=self.myjson["Date1"]
                              #     enddate=self.myjson["Date2"]
                              #pass
                    
                    except Exception:
                              
                              errorcode["error"]=-1      
                              return (json.JSONEncoder().encode(errorcode))         
                         
                    beneficiary_id=self.b_id
                    #food_content="Starch"
                    #meal_type="Lunch" 
                    #day="This week"
                    #startdate="2013-09-09"
                    #kunenddate="2013-09-15"
                    #print "Content-Type: text/html\n"
                    if day=="Today":
                              
                              startdate = datetime.date.today()
                              enddate = datetime.date.today()
                              
                    elif day=="This week":
                              
                              #from monday up to today's date. 
                              day_of_week = datetime.datetime.today().weekday()
                              enddate = datetime.date.today()
                              startdate = enddate-datetime.timedelta(days=day_of_week)
                                         
                    elif day=="Last week":
                              day_of_week = datetime.datetime.today().weekday()
                              enddate = datetime.date.today()-datetime.timedelta(days=(day_of_week+1))#last sunday
                              startdate = enddate-datetime.timedelta(days=6)# last monday


                    elif day=="This month":
                              #from 1st of this month to end of last month
                              startdate=self.first_day_of_month(datetime.date.today())
                              enddate=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))
                              startdate=self.first_day_of_month(self.first_day_of_month(datetime.date.today())-datetime.timedelta(days=1))               
                              enddate=self.last_day_of_month(startdate)
                              
                    
                    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))
                              startdate=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
                              enddate=self.last_day_of_month(datetime.date.today())#
                    else:
                              meals_tuples={}
                              meals_tuple={}
                    
                              key1="P"
                              key2="D"
                              first_posn=0
                              second_posn=0
                              meals_tuple[key2+"%d"%second_posn]="The system cannot recognize the period of time you have entered"
                              second_posn=second_posn+1
                                                                                                                                                                                            
                                                                                                                                                                                            
                              meals_tuple[key2+"%d"%second_posn]=-1
                              second_posn=0 
                              if first_posn<10:
                                   key1="P0"
                              else:
                                   key1="P"
                                                                                                                                                           
                              meals_tuples[key1+"%d"%first_posn]=meals_tuple
                                                                                                                                                         
                              first_posn=first_posn+1 
                              meals_tuple={}
                              return(json.JSONEncoder().encode(OrderedDict(sorted(meals_tuples.items(), key=lambda t: t[0]))))                             

                               
                       

                    
                    try:
                              
                              #engine=create_engine('mysql://*****:*****@localhost/wellness', echo=False)
                              engine=db
                              # create a Session
                              Session = sessionmaker(bind=engine)
                              
                              session = Session()
                              
                              
                              food_ids=[]
                              food_dates=[]
                              
                              meals={}
                              meals_id=[]
                              meals_counter=0.0# for counting the number of meals eaten
                              
                              
                              res = session.query(FoodAndBeverage).filter(FoodAndBeverage.beneficiary_id==beneficiary_id).filter(FoodAndBeverage.date_consumed>=startdate).filter(FoodAndBeverage.date_consumed<=enddate).order_by(FoodAndBeverage.date_consumed).all()
                              #get all the food_ids for the specified date range
                              for food in res:
          
                                        food_ids.append(food.id)
                                        food_dates.append(food.date_consumed)
                                        meals_counter=meals_counter+1.0
                              
                             
                              #print "Meals Counter%s"%meals_counter
                              
                              total_fruits_veg_sizes=0
                              total_starch_sizes=0
                              total_protein_sizes=0
                              total_fat_sizes=0
                              total_dairy_sizes=0
                              
                              if meals_counter == 0.0:
                                        meals_tuples={}
                                        meals_tuple={}
                              
                                        key1="P"
                                        key2="D"
                                        first_posn=0
                                        second_posn=0
                                        meals_tuple[key2+"%d"%second_posn]="No meals recorded in the specified period of time"
                                        second_posn=second_posn+1
                                                                                                                                                                                                      
                                                                                                                                                                                                      
                                        meals_tuple[key2+"%d"%second_posn]=-4
                                        second_posn=0 
                                        if first_posn<10:
                                             key1="P0"
                                        else:
                                             key1="P"
                                                                                                                                                                     
                                        meals_tuples[key1+"%d"%first_posn]=meals_tuple
                                                                                                                                                                   
                                        first_posn=first_posn+1 
                                        meals_tuple={}
                                        return(json.JSONEncoder().encode(OrderedDict(sorted(meals_tuples.items(), key=lambda t: t[0]))))                                          
                              
                             
                              for fid in food_ids:
                                        
                                        
                                        res2 = session.query(Meal,MealComposition).filter(Meal.food_id==fid).filter(Meal.id==MealComposition.meal_id).all()
                                        meal_portion_tuples={}     
                                        if res2 is None:
                                                  pass
                                        
                                        else:
                                                  
                                                  previous_id=None
                                                  meal_type=""
                                                  for m,c in res2:
                                                                                                                   
                                    
                                                  
                                                            if switch(c.getMealGroup()):
                                                                    
                                                                      if case("Fruits and Vegetables"):

                                                                                total_fruits_veg_sizes=total_fruits_veg_sizes+c.getPortionSize()
                                                                      
                                                                                continue
                                                                      if case("Starch"):
                                                                                
                                                                                total_starch_sizes=total_starch_sizes+c.getPortionSize()
                                                                                continue
                                                                      if case("Protein Foods"):
                                                                                
                                                                                total_protein_sizes=total_protein_sizes+c.getPortionSize()
                                                                                
                                                                                continue
                                                                      if case("Fat Foods"):
                                                                                
                                                                                total_fat_sizes=total_fat_sizes+c.getPortionSize()
                                                                                
                                                                                continue
                                                                      if case("Dairy"):
                                                                                
                                                                                total_dairy_sizes=total_dairy_sizes+c.getPortionSize()
                                                                                
                                                                                continue 
                                                                      
                                                                                                              
                                                  
                                 
                                        
                              
                              portion_names=["Fruits and Vegetables","Starch","Protein Foods","Fat Foods","Dairy" ]
                              key1="P" #for different portions
                              key2="D" #for data in each portion                              
                              
                              first_posn=0
                              
                              
                              meal_portion_average_sizes={}# for storing all portions with their sizes
                              
                                                           
                              
                              
                              if meals_counter>0.0:
                                        # get the sum of each portion and compute the average. The avrage is computed using the sum of portion sizes of a different food group divided by the total number of meals
                                        for food_portion_name in portion_names:
                                                 
                                                  second_posn=0
                                                  meal_portion_average_size={} # for storing one portion with its size
                                                  
                                                  
                                                                                                                  
                                                  if food_portion_name=="Fruits and Vegetables":
                                                            
                                                                                                                                           
                                                            meal_portion_average_size[key2+"%d"%second_posn]="Fruits & Veg"
                                                            second_posn=second_posn+1
                                                            meal_portion_average_size[key2+"%d"%second_posn]=float("{0:.2f}".format(total_fruits_veg_sizes/meals_counter))
                                                            second_posn=second_posn+1 
                                                                      
                                                            
                                                  elif food_portion_name=="Starch":
                                                                     
                                                            meal_portion_average_size[key2+"%d"%second_posn]="Starch"
                                                            second_posn=second_posn+1
                                                            print total_starch_sizes
                                                            meal_portion_average_size[key2+"%d"%second_posn]=float("{0:.2f}".format(total_starch_sizes/meals_counter))
                                                            second_posn=second_posn+1                                                            
                                                  
                                                            
                                                  elif food_portion_name=="Protein Foods":
                                                                      
                                                            meal_portion_average_size[key2+"%d"%second_posn]="Protein"
                                                            second_posn=second_posn+1
                                                            meal_portion_average_size[key2+"%d"%second_posn]=float("{0:.2f}".format(total_protein_sizes/meals_counter))
                                                            second_posn=second_posn+1 
                                                            
                                                           
                                                  if food_portion_name=="Fat Foods":
                                                                      
                                                            meal_portion_average_size[key2+"%d"%second_posn]="Fat"
                                                            second_posn=second_posn+1
                                                            meal_portion_average_size[key2+"%d"%second_posn]=float("{0:.2f}".format(total_fat_sizes/meals_counter))
                                                            second_posn=second_posn+1
                                                  
                                                            
                                                  if food_portion_name=="Dairy":
          
                                                            meal_portion_average_size[key2+"%d"%second_posn]="Dairy"
                                                            second_posn=second_posn+1
                                                            meal_portion_average_size[key2+"%d"%second_posn]=float("{0:.2f}".format(total_dairy_sizes/meals_counter))
                                                            second_posn=second_posn+1
                                                  if first_posn<10:
                                                                
                                                            key1="P0"
                                                  else:
                                                            key1="P"                                                  
                                                                                                              
                                                  meal_portion_average_sizes[key1+"%d"%first_posn]=meal_portion_average_size
                                                  first_posn=first_posn+1
                                        
                            
                              session.close()
                              engine.dispose()
                              dbconn.close()

                              return(json.JSONEncoder().encode(OrderedDict(sorted(meal_portion_average_sizes.items(), key=lambda t: t[0]))))
                    except Exception as e:
                              session.close()
                              engine.dispose()
                              dbconn.close()
               
                              key1="P" #for different portions
                              key2="D" #for data in each portion 
                              second_posn=0 
                              meal_portion_average_size={}
    
                              meal_portion_average_size[key2+"%d"%second_posn]="%s"%e
                              second_posn=second_posn+1
                                                                                                                                                                             
                                                                                                                                                                             
                              meal_portion_average_size[key2+"%d"%second_posn]=-1
                              second_posn=0 
                              if first_posn<10:
                                  
                                  key1="P0"
                              else:
                                  key1="P"
                                                                                                                                            
                              meal_portion_average_sizes[key1+"%d"%first_posn]=meal_portion_average_size
                                                                                                                                          
                              first_posn=first_posn+1 
                              meal_portion_average_size={}
                              return(json.JSONEncoder().encode( meal_portion_average_sizes))                    
    def getSteps(self,beneficiary_id):
         
     
        try:
            engine=db
            #create a Session
            Session = sessionmaker(bind=engine)
            session = Session()

            pilotdateres=session.query(PilotCommencement).first()

            if pilotdateres is None:
                sys.exit
            else:
                datestarted=pilotdateres.datestarted




            if self.last_date_specified==1:
                day=self.myjson["Day"]
                if day == "Today":
                    day=datetime.date.today()
                res=session.query(func.sum(PhysicalActivity.stepscounter).label("sum_steps")).filter(PhysicalActivity.beneficiary_id==beneficiary_id).filter(PhysicalActivity.datecaptured>=datestarted).filter(PhysicalActivity.datecaptured<=day).first()
         
            else:
 
                res=session.query(func.sum(PhysicalActivity.stepscounter).label("sum_steps")).filter(PhysicalActivity.beneficiary_id==beneficiary_id).filter(PhysicalActivity.datecaptured>=datestarted).first()
            
            if res.sum_steps==None:
                sum_steps=0
            else:
                sum_steps=int(res.sum_steps)
            result={}
            result["steps"]=sum_steps
            
            if self.last_date_specified==1:
                res=session.query(func.min(PhysicalActivity.datecaptured).label("min_date")).filter(PhysicalActivity.beneficiary_id==beneficiary_id).filter(PhysicalActivity.datecaptured<=day).first()
            else: 
                res=session.query(func.min(PhysicalActivity.datecaptured).label("min_date")).filter(PhysicalActivity.beneficiary_id==beneficiary_id).first()
            
            min_date=res.min_date 

            

            if self.last_date_specified==1:
                max_date=self.myjson["Day"]
                if max_date=="Today":
                    max_date=datetime.date.today()
                else:
                    max_date=datetime.datetime.strptime(max_date , '%Y-%m-%d').date()
            else:
                max_date=datetime.date.today()

            
            if min_date is None:
                dates_difference=1
            else:
                delta=max_date-min_date
                dates_difference=delta.days+1
                if min_date>max_date:
                    dates_difference=1
        
            result["dates_counter"]=dates_difference
                      
 
        except Exception as e:
            print "Exception thrown in function getSteps(): %s"%e 
            result["steps"]=0
            result["dates_counter"]=1
          
        
        #self.steps=sum_steps
        session.close()
        engine.dispose()
        dbconn.close()
        
        return (json.JSONEncoder().encode(result))
    def retrieveIntermediaryClickPoints(self):
        result={}       
        try:
                         
            #engine=create_engine('mysql://*****:*****@localhost/wellness', echo=False) 
            engine=db
            # create a Session
            Session = sessionmaker(bind=engine)
            session = Session()
                                


            #res=session.query(func.count(distinct(Points.datecaptured)).label("sum_points")).filter(Points.intermediary_id==self.intermediary_id).first()

            if self.last_date_specified==1:
                day=self.myjson["Day"]
                if day=="Today":
                   day=datetime.date.today()
                
                #res=session.query(func.count((Points.datecaptured)).label("sum_points")).filter(Points.intermediary_id==self.intermediary_id).filter(Points.datecaptured<=day).first() 
                res=session.query(func.count((Points.datecaptured)).label("sum_points")).filter(Points.intermediary_id==self.intermediary_id).filter(Points.datecaptured<=day).first()   
                 #res= session.query(func.sum(Points.scoredpoints).label("sum_points")).filter(Points.intermediary_id==self.intermediary_id).filter(Points.datecaptured<=day).first()
            #get points by number of days an application has been used.
            #res=session.query(func.count(distinct(Points.datecaptured)).label("sum_points")).filter(Points.intermediary_id==self.intermediary_id).filter(Points.datecaptured<=day).first()
            else:
                #res= session.query(func.sum(Points.scoredpoints).label("sum_points")).filter(Points.intermediary_id==self.intermediary_id).first()
                res=session.query(func.count((Points.datecaptured)).label("sum_points")).filter(Points.intermediary_id==self.intermediary_id).first()

            

            
            
            retrieved_points_sum=0# initialize how many distinct dates are in the database
                      
            
            
            if res.sum_points is None:
                
                 
                retrieved_points_sum="0"
                result["message"]="You have no points"
                result["points"]=int(retrieved_points_sum)
            else: 
                result["message"]="You have some points so far."
                retrieved_points_sum=int(res.sum_points)
                result["points"]=int(retrieved_points_sum)




            session.close()
            engine.dispose()
            dbconn.close()
                 
            return (json.JSONEncoder().encode(result))                   
                                 
        except Exception as e:
                       
            #print "Content-type: text/html\n" 
            session.close()
            engine.dispose() 
            dbconn.close()
                              
            result["message"]="Error: %s"%e
            print "Exception thrown in function getIntermediaryClickPoints(): %s"%e
            print "The day captured=%s"%day
            return (json.JSONEncoder().encode(result))
Exemple #7
0
    def getDataPoints(self):

        # Get data from fields
        try:

            day = self.myjson["Day"]
            #food_content=self.myjson["FoodContent"]
            #meal_type=self.myjson["MealType"]
            #if day=="By date":
            #     startdate=self.myjson["Date1"]
            #     enddate=self.myjson["Date2"]
            #pass

        except Exception:

            errorcode["error"] = -1
            return (json.JSONEncoder().encode(errorcode))

        beneficiary_id = self.b_id
        #food_content="Starch"
        #meal_type="Lunch"
        #day="This week"
        #startdate="2013-09-09"
        #kunenddate="2013-09-15"
        #print "Content-Type: text/html\n"
        if day == "Today":

            startdate = datetime.date.today()
            enddate = datetime.date.today()

        elif day == "This week":

            #from monday up to today's date.
            day_of_week = datetime.datetime.today().weekday()
            enddate = datetime.date.today()
            startdate = enddate - datetime.timedelta(days=day_of_week)

        elif day == "Last week":
            day_of_week = datetime.datetime.today().weekday()
            enddate = datetime.date.today() - datetime.timedelta(
                days=(day_of_week + 1))  #last sunday
            startdate = enddate - datetime.timedelta(days=6)  # last monday

        elif day == "This month":
            #from 1st of this month to end of last month
            startdate = self.first_day_of_month(datetime.date.today())
            enddate = 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))
            startdate = self.first_day_of_month(
                self.first_day_of_month(datetime.date.today()) -
                datetime.timedelta(days=1))
            enddate = self.last_day_of_month(startdate)

        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))
            startdate = 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
            enddate = self.last_day_of_month(datetime.date.today())  #
        else:
            meals_tuples = {}
            meals_tuple = {}

            key1 = "P"
            key2 = "D"
            first_posn = 0
            second_posn = 0
            meals_tuple[
                key2 + "%d" %
                second_posn] = "The system cannot recognize the period of time you have entered"
            second_posn = second_posn + 1

            meals_tuple[key2 + "%d" % second_posn] = -1
            second_posn = 0
            if first_posn < 10:
                key1 = "P0"
            else:
                key1 = "P"

            meals_tuples[key1 + "%d" % first_posn] = meals_tuple

            first_posn = first_posn + 1
            meals_tuple = {}
            return (json.JSONEncoder().encode(
                OrderedDict(sorted(meals_tuples.items(), key=lambda t: t[0]))))

        try:

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

            session = Session()

            food_ids = []
            food_dates = []

            meals = {}
            meals_id = []
            meals_counter = 0.0  # for counting the number of meals eaten

            res = session.query(FoodAndBeverage).filter(
                FoodAndBeverage.beneficiary_id == beneficiary_id).filter(
                    FoodAndBeverage.date_consumed >= startdate).filter(
                        FoodAndBeverage.date_consumed <= enddate).order_by(
                            FoodAndBeverage.date_consumed).all()
            #get all the food_ids for the specified date range
            for food in res:

                food_ids.append(food.id)
                food_dates.append(food.date_consumed)
                meals_counter = meals_counter + 1.0

            #print "Meals Counter%s"%meals_counter

            total_fruits_veg_sizes = 0
            total_starch_sizes = 0
            total_protein_sizes = 0
            total_fat_sizes = 0
            total_dairy_sizes = 0

            if meals_counter == 0.0:
                meals_tuples = {}
                meals_tuple = {}

                key1 = "P"
                key2 = "D"
                first_posn = 0
                second_posn = 0
                meals_tuple[
                    key2 + "%d" %
                    second_posn] = "No meals recorded in the specified period of time"
                second_posn = second_posn + 1

                meals_tuple[key2 + "%d" % second_posn] = -4
                second_posn = 0
                if first_posn < 10:
                    key1 = "P0"
                else:
                    key1 = "P"

                meals_tuples[key1 + "%d" % first_posn] = meals_tuple

                first_posn = first_posn + 1
                meals_tuple = {}
                return (json.JSONEncoder().encode(
                    OrderedDict(
                        sorted(meals_tuples.items(), key=lambda t: t[0]))))

            for fid in food_ids:

                res2 = session.query(
                    Meal, MealComposition).filter(Meal.food_id == fid).filter(
                        Meal.id == MealComposition.meal_id).all()
                meal_portion_tuples = {}
                if res2 is None:
                    pass

                else:

                    previous_id = None
                    meal_type = ""
                    for m, c in res2:

                        if switch(c.getMealGroup()):

                            if case("Fruits and Vegetables"):

                                total_fruits_veg_sizes = total_fruits_veg_sizes + c.getPortionSize(
                                )

                                continue
                            if case("Starch"):

                                total_starch_sizes = total_starch_sizes + c.getPortionSize(
                                )
                                continue
                            if case("Protein Foods"):

                                total_protein_sizes = total_protein_sizes + c.getPortionSize(
                                )

                                continue
                            if case("Fat Foods"):

                                total_fat_sizes = total_fat_sizes + c.getPortionSize(
                                )

                                continue
                            if case("Dairy"):

                                total_dairy_sizes = total_dairy_sizes + c.getPortionSize(
                                )

                                continue

            portion_names = [
                "Fruits and Vegetables", "Starch", "Protein Foods",
                "Fat Foods", "Dairy"
            ]
            key1 = "P"  #for different portions
            key2 = "D"  #for data in each portion

            first_posn = 0

            meal_portion_average_sizes = {
            }  # for storing all portions with their sizes

            if meals_counter > 0.0:
                # get the sum of each portion and compute the average. The avrage is computed using the sum of portion sizes of a different food group divided by the total number of meals
                for food_portion_name in portion_names:

                    second_posn = 0
                    meal_portion_average_size = {
                    }  # for storing one portion with its size

                    if food_portion_name == "Fruits and Vegetables":

                        meal_portion_average_size[key2 + "%d" %
                                                  second_posn] = "Fruits & Veg"
                        second_posn = second_posn + 1
                        meal_portion_average_size[
                            key2 + "%d" % second_posn] = float(
                                "{0:.2f}".format(total_fruits_veg_sizes /
                                                 meals_counter))
                        second_posn = second_posn + 1

                    elif food_portion_name == "Starch":

                        meal_portion_average_size[key2 + "%d" %
                                                  second_posn] = "Starch"
                        second_posn = second_posn + 1
                        print total_starch_sizes
                        meal_portion_average_size[key2 +
                                                  "%d" % second_posn] = float(
                                                      "{0:.2f}".format(
                                                          total_starch_sizes /
                                                          meals_counter))
                        second_posn = second_posn + 1

                    elif food_portion_name == "Protein Foods":

                        meal_portion_average_size[key2 + "%d" %
                                                  second_posn] = "Protein"
                        second_posn = second_posn + 1
                        meal_portion_average_size[key2 +
                                                  "%d" % second_posn] = float(
                                                      "{0:.2f}".format(
                                                          total_protein_sizes /
                                                          meals_counter))
                        second_posn = second_posn + 1

                    if food_portion_name == "Fat Foods":

                        meal_portion_average_size[key2 +
                                                  "%d" % second_posn] = "Fat"
                        second_posn = second_posn + 1
                        meal_portion_average_size[key2 +
                                                  "%d" % second_posn] = float(
                                                      "{0:.2f}".format(
                                                          total_fat_sizes /
                                                          meals_counter))
                        second_posn = second_posn + 1

                    if food_portion_name == "Dairy":

                        meal_portion_average_size[key2 +
                                                  "%d" % second_posn] = "Dairy"
                        second_posn = second_posn + 1
                        meal_portion_average_size[key2 +
                                                  "%d" % second_posn] = float(
                                                      "{0:.2f}".format(
                                                          total_dairy_sizes /
                                                          meals_counter))
                        second_posn = second_posn + 1
                    if first_posn < 10:

                        key1 = "P0"
                    else:
                        key1 = "P"

                    meal_portion_average_sizes[
                        key1 + "%d" % first_posn] = meal_portion_average_size
                    first_posn = first_posn + 1

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

            return (json.JSONEncoder().encode(
                OrderedDict(
                    sorted(meal_portion_average_sizes.items(),
                           key=lambda t: t[0]))))
        except Exception as e:
            session.close()
            engine.dispose()
            dbconn.close()

            key1 = "P"  #for different portions
            key2 = "D"  #for data in each portion
            second_posn = 0
            meal_portion_average_size = {}

            meal_portion_average_size[key2 + "%d" % second_posn] = "%s" % e
            second_posn = second_posn + 1

            meal_portion_average_size[key2 + "%d" % second_posn] = -1
            second_posn = 0
            if first_posn < 10:

                key1 = "P0"
            else:
                key1 = "P"

            meal_portion_average_sizes[key1 + "%d" %
                                       first_posn] = meal_portion_average_size

            first_posn = first_posn + 1
            meal_portion_average_size = {}
            return (json.JSONEncoder().encode(meal_portion_average_sizes))