def api_user(request): if request.method == "GET": name = request.GET.get("name", "").lower() status = request.GET.get("status", "") page = int(request.GET.get("page", 1)) offset = (page - 1) * 30 limit = offset + 30 users = User.objects.filter(blocked_at=None) if name == "" else \ User.objects.annotate(lower_name=Lower("name")).filter(lower_name__contains=name.lower(), blocked_at=None) results = [] for user in users: if status == "" or status == body.clasify_bmi(user): results.append({ "id": user.id, "name": user.name, "gender": user.gender.id, "status": body.clasify_bmi(user), }) total = len(results) pages = ceil(total / 30) users = results[offset:limit] return JsonResponse( {"results": { "total": total, "pages": pages, "users": users }}) return JsonResponse({"message": "Not Found"}, status=404)
def api_dashboard(request): if request.method == "GET": today = datetime.now().date() last30 = today + timedelta(-30) date_start = datetime.combine(last30, time()) date_end = datetime.combine(today, time()) normal = 0 overweight = 0 underweight = 0 total_user = User.objects.filter(role=2) for user in total_user: bmi = body.calculate_bmi(user) if bmi < 18.5: underweight += 1 elif bmi < 25.0: normal += 1 else: overweight += 1 top_food = dashboard.top_food() top_user = dashboard.top_user(date_start, date_end) incorrect = CalorieBurnt.objects.filter(deleted_at__isnull=False) correct = CalorieBurnt.objects.filter(deleted_at__isnull=True) list_new_user = [] new_user = User.objects.filter(role=2, created_at__gte=date_start, created_at__lte=date_end) for user in new_user: list_new_user.append({ "name": user.name, "category": body.clasify_bmi(user), }) return JsonResponse({ "results": { "total_users": len(total_user), "new_users": list_new_user, "insight": { "normal": normal, "overweight": overweight, "underweight": underweight, }, "top_food": top_food, "top_user": top_user, "algorithm_accuracy": { "correct": len(correct), "incorrect": len(incorrect) } } }) return JsonResponse({"message": "Not Found"}, status=404)
def api_member_evaluation(request): bearer, token = request.META.get('HTTP_AUTHORIZATION').split() user = JWT().decode(token) if user is None: return JsonResponse({"message": "Unauthorized"}, status=401) if request.method == "GET": today = datetime.now() total_calorie = 0 for i in range(30): date_start = datetime.combine(today + timedelta((i + 0) * -1), time()) date_end = datetime.combine(today + timedelta((i - 1) * -1), time()) calorie_burnt = CalorieBurnt.objects.filter( user=user, created_at__gte=date_start, created_at__lte=date_end, deleted_at__isnull=True) month_calorie = 0 total_duration = 0 for calorie in calorie_burnt: month_calorie += calorie.activity_label.met * user.weight * calorie.duration / 3600 total_duration += calorie.duration if total_duration / (24 * 3600) >= 24: sitting = ((24 * 3600) - (total_duration / (24 * 3600))) * user.weight total_calorie += sitting total_calorie += (month_calorie / 24) total_calorie = (total_calorie / 30) result = clasify_activity_factor(total_calorie) tdee = total_calorie * calculate_bmr(user) # ActivityLevel.objects.create( # level=result, # tdee=tdee, # user=user # ) return JsonResponse({"results": clasify_bmi(user)}) return JsonResponse({"message": "Not Found"}, status=404)
def api_new_user(request): if request.method == "GET": today = datetime.now().date() last30 = today + timedelta(-30) date_start = datetime.combine(last30, time()) date_end = datetime.combine(today, time()) new_user = User.objects.filter(role=2, created_at__gte=date_start, created_at__lte=date_end) list_new_user = [] for user in new_user: list_new_user.append({ "name": user.name, "category": body.clasify_bmi(user), }) return JsonResponse({"results": { "new_users": list_new_user, }}) return JsonResponse({"message": "Not Found"}, status=404)
def user_detail_api(request, user_id): if request.method == "GET": user = User.objects.get(id=user_id) activity_level = ActivityLevel.objects.filter(user=user.id) today = datetime.now().date() tomorrow = today + timedelta(1) today_start = datetime.combine(today, time()) today_end = datetime.combine(tomorrow, time()) intakes = CalorieIntake.objects.filter(user=user.id, created_at__gte=today_start, created_at__lte=today_end) carbohydrate = 0 protein = 0 fat = 0 for intake in intakes: fat += intake.food.fat protein += intake.food.protein carbohydrate += intake.food.carbohydrate return JsonResponse({ "results": { "name": user.name, "old": datetime.now().year - user.birth_year, "email": user.email, "weight": user.weight, "height": user.height, "category": body.clasify_bmi(user), "activity": activity_level[-1].level if len(activity_level) != 0 else "none", "carbohydrate": carbohydrate, "protein": protein, "fat": fat, "max_carbohydrate": (0.6 * activity_level[-1].tdee / 4) if len(activity_level) != 0 else 0, "max_protein": (0.15 * activity_level[-1].tdee / 4) if len(activity_level) != 0 else 0, "max_fat": (0.25 * activity_level[-1].tdee / 9) if len(activity_level) != 0 else 0, } }) if request.method == "PUT": user = User.objects.get(id=user_id) json_request = json.loads(request.body) input_name = json_request.get("name", user.name) input_email = json_request.get("email", user.email) input_weight = json_request.get("weight", user.weight) input_height = json_request.get("height", user.height) input_gender = json_request.get("gender", user.gender.id) input_birth_year = json_request.get("birth_year", user.birth_year) gender = Gender.objects.get(id=input_gender) if "password" in json_request: input_password = json_request["password"] input_re_password = json_request["re_password"] if input_re_password != input_password: return JsonResponse({ "message": "Password and Confirm Password should be same" }) input_password = bcrypt.hashpw( json_request["password"].encode("utf-8"), bcrypt.gensalt()).decode("utf-8") else: input_password = user.password user.name = input_name user.email = input_email user.weight = input_weight user.height = input_height user.gender = gender user.birth_year = input_birth_year user.password = input_password user.save() return JsonResponse({"message": "Success"}) if request.method == "DELETE": user = User.objects.get(id=user_id) json_request = json.loads(request.body) input_reason_block = json_request.get("reason_block", user.name) if input_reason_block == "none": user.reason_block = None user.blocked_at = None user.save() else: user.reason_block = input_reason_block user.blocked_at = datetime.now() user.save() return JsonResponse({"message": "Success"}) return JsonResponse({"message": "Invalid method"})
def api_member_user_detail(request): bearer, token = request.META.get('HTTP_AUTHORIZATION').split() user = JWT().decode(token) if user is None: return JsonResponse({"message": "Unauthorized"}, status=401) if request.method == "GET": today = datetime.now().date() tomorrow = today + timedelta(+1) date_start = datetime.combine(today, time()) date_end = datetime.combine(tomorrow, time()) activity_level = list( ActivityLevel.objects.filter(user=user).order_by("-created_at"))[0] fat = 0.25 * activity_level.tdee / 9 protein = 0.15 * activity_level.tdee / 4 carbohydrate = 0.6 * activity_level.tdee / 4 return JsonResponse({ "results": { "name": user.name, "email": user.email, "gender": user.gender.id, "birth_year": user.birth_year, "status": clasify_bmi(user), "weight": user.weight, "height": user.height, "bmi": calculate_bmi(user), "carbohydrate": carbohydrate, "protein": protein, "fat": fat, "activity_level": activity_level.level, } }) if request.method == "PUT": json_request = json.loads(request.body) input_name = json_request.get("name", user.name) input_email = json_request.get("email", user.email) input_weight = json_request.get("weight", user.weight) input_height = json_request.get("height", user.height) input_gender = json_request.get("gender", user.gender.id) input_birth_year = json_request.get("birth_year", user.birth_year) gender = Gender.objects.get(id=input_gender) try: validate_email(input_email) except ValidationError: return JsonResponse({"message": "Invalid email"}, status=400) if "password" in json_request: input_password = json_request["password"] input_re_password = json_request["re_password"] input_old_password = json_request["old_password"] hashed = user.password.encode("utf-8") if not bcrypt.checkpw(input_old_password.encode("utf-8"), hashed): return JsonResponse({"message": "Wrong Current Password"}) if input_password == input_old_password: return JsonResponse( {"message": "New Password can’t be same with current"}) if input_password != input_re_password: return JsonResponse({ "message": "New Password and Confirm New Password should be same" }) input_password = bcrypt.hashpw( json_request["password"].encode("utf-8"), bcrypt.gensalt()).decode("utf-8") else: input_password = user.password user.name = input_name user.email = input_email user.weight = input_weight user.height = input_height user.gender = gender user.birth_year = input_birth_year user.password = input_password user.confirm_email = None user.forgot_password = None user.save() return JsonResponse({"message": "Success"}) return JsonResponse({"message": "Invalid method"})
def top_user(date_start, date_end, top=5): calorie_food = CalorieIntake.objects.filter(created_at__gte=date_start, created_at__lte=date_end) calorie_activity = CalorieBurnt.objects.filter(created_at__gte=date_start, created_at__lte=date_end) dict_list_user_intake = {} dict_list_user_burnt = {} dict_user_tdee = {} dict_user = {} dict_username = {} dict_status = {} for calorie in calorie_food: user_id = calorie.user.id day = calorie.created_at.day - 1 if user_id not in dict_user_tdee: last_date_activity = ActivityLevel.objects.filter( user=user_id).latest("created_at") dict_user_tdee[user_id] = last_date_activity.tdee if user_id not in dict_list_user_intake: dict_list_user_intake[user_id] = [0] * 31 # 31 days if user_id not in dict_user: dict_user[user_id] = 0 dict_status[user_id] = clasify_bmi(calorie.user) dict_username[user_id] = calorie.user.name if dict_user[user_id] == 1: continue if calorie.food is not None: dict_list_user_intake[user_id][ day] += calorie.food.calorie * calorie.qty else: meals = MealDetail.objects.filter(meal=calorie.meal.id) for meal in meals: dict_list_user_intake[user_id][ day] += meal.food.calorie * meal.qty * calorie.qty if dict_user_tdee[user_id] - 100 <= dict_list_user_intake[user_id][ day] <= dict_user_tdee[user_id] + 100: dict_user[user_id] += 1 for calorie in calorie_activity: user_id = calorie.user.id day = calorie.created_at.day - 1 if user_id not in dict_user_tdee: last_date_activity = ActivityLevel.objects.filter( user=user_id).latest("created_at") dict_user_tdee[user_id] = last_date_activity.tdee if user_id not in dict_list_user_burnt: dict_list_user_burnt[user_id] = [0] * 31 # 31 days if user_id not in dict_user or dict_user[user_id] == 2: continue dict_list_user_burnt[user_id][ day] += calorie.activity_label.met * calorie.user.weight * calorie.duration / 3600 if dict_user_tdee[user_id] - 100 <= dict_list_user_burnt[user_id][ day] <= dict_user_tdee[user_id] + 100: dict_user[user_id] += 1 list_user = [] for key, value in dict_user.items(): list_user.append((value, dict_username[key], dict_status[key])) list_user.sort(reverse=True) return list_user[:top]