From 7955028d93fb44b01a2419e87d322cdc36461f39 Mon Sep 17 00:00:00 2001 From: PFGrande <2002.pedrogrande@gmail.com> Date: Thu, 5 Dec 2024 20:57:02 -0800 Subject: [PATCH 01/13] added comment detailing plans for sustainability score --- .../secondchance_backend/useraccount/models.py | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/application/backend/secondchance_backend/useraccount/models.py b/application/backend/secondchance_backend/useraccount/models.py index c28250f..58917dc 100644 --- a/application/backend/secondchance_backend/useraccount/models.py +++ b/application/backend/secondchance_backend/useraccount/models.py @@ -190,6 +190,17 @@ def calculate_sustainability_score(self): :return: None :rtype: None """ + # Concept for changes to the sustainability score: + # consider the type of item that is being sold and assign each item type a weight + # ex. clothing will have a higher weight than electronics because it can be + # wasteful to have 1 set of clothes for just 1 occassion + # It should provide a discount + # It should not be used to deminish anyone's contribution + # the way it is displayed already shows is as an overall positive attribute + # When computing the score we could also consider how many of the items are + # currently being rented + # con: score will constantly fluxuate + if self.date_joined: days_on_platform = (timezone.now() - self.date_joined).days else: From b552b5977c51d71cdd3a3d959419263bb748b248 Mon Sep 17 00:00:00 2001 From: PFGrande <2002.pedrogrande@gmail.com> Date: Fri, 6 Dec 2024 18:03:53 -0800 Subject: [PATCH 02/13] added functions to retrieve categories rented and listed by user --- .../item/utils/categories.py | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 application/backend/secondchance_backend/item/utils/categories.py diff --git a/application/backend/secondchance_backend/item/utils/categories.py b/application/backend/secondchance_backend/item/utils/categories.py new file mode 100644 index 0000000..f141702 --- /dev/null +++ b/application/backend/secondchance_backend/item/utils/categories.py @@ -0,0 +1,41 @@ +from item.models import Rental +from item.models import Item + +def get_user_rented_categories(user): + """ + Get the categories of items that a user has rented from + + args: + user instance + used to get items rented by user + + + return: list of categories + rtype: list? + """ + # convert QuerySet to list before returning + return list( + Rental.objects.filter(rentals__created_by=user) + .values_list('category', flat=True) # returns desired field + .distinct() # eliminate duplicate categories + ) + + + +def get_user_listed_categories(user): + """ + Get the categories of items that a user has listed + + args: + user instance + used to get items listed by user + + + return: list of categories + rtype: list? + """ + return list( + Item.objects.filter(seller=user) + .values_list('category', flat=True) + .distinct() + ) \ No newline at end of file From 45d7c27c0d813edd134276ee292ea68379228eda Mon Sep 17 00:00:00 2001 From: PFGrande <2002.pedrogrande@gmail.com> Date: Sat, 7 Dec 2024 04:13:04 -0800 Subject: [PATCH 03/13] fixed circular dependancy issues and allowed duplicates in categories.py functions --- .../secondchance_backend/item/utils/categories.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/application/backend/secondchance_backend/item/utils/categories.py b/application/backend/secondchance_backend/item/utils/categories.py index f141702..847143f 100644 --- a/application/backend/secondchance_backend/item/utils/categories.py +++ b/application/backend/secondchance_backend/item/utils/categories.py @@ -1,5 +1,5 @@ -from item.models import Rental -from item.models import Item +# from item.models import Rental +# from item.models import Item def get_user_rented_categories(user): """ @@ -13,11 +13,12 @@ def get_user_rented_categories(user): return: list of categories rtype: list? """ + from item.models import Rental # convert QuerySet to list before returning return list( Rental.objects.filter(rentals__created_by=user) .values_list('category', flat=True) # returns desired field - .distinct() # eliminate duplicate categories + # .distinct() # eliminate duplicate categories ) @@ -34,8 +35,9 @@ def get_user_listed_categories(user): return: list of categories rtype: list? """ + from item.models import Item return list( Item.objects.filter(seller=user) .values_list('category', flat=True) - .distinct() + # .distinct() ) \ No newline at end of file From b301dc01190a8d17808aa41192fbfe5de46ce8a4 Mon Sep 17 00:00:00 2001 From: PFGrande <2002.pedrogrande@gmail.com> Date: Sat, 7 Dec 2024 04:14:23 -0800 Subject: [PATCH 04/13] sucessfully retrieved category users have listed and rented from --- .../useraccount/models.py | 106 ++++++++++++++++++ 1 file changed, 106 insertions(+) diff --git a/application/backend/secondchance_backend/useraccount/models.py b/application/backend/secondchance_backend/useraccount/models.py index 58917dc..cbdc861 100644 --- a/application/backend/secondchance_backend/useraccount/models.py +++ b/application/backend/secondchance_backend/useraccount/models.py @@ -3,7 +3,12 @@ from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, UserManager from django.db import models from django.utils import timezone +from enum import Enum +# from item.utils.categories import get_user_listed_categories, get_user_rented_categories +# this breaks the code +# from item.models import Item +# from item.models import Rental class CustomUserManager(UserManager): """ @@ -190,6 +195,7 @@ def calculate_sustainability_score(self): :return: None :rtype: None """ + print("sustainability score computing...") # Concept for changes to the sustainability score: # consider the type of item that is being sold and assign each item type a weight # ex. clothing will have a higher weight than electronics because it can be @@ -201,11 +207,54 @@ def calculate_sustainability_score(self): # currently being rented # con: score will constantly fluxuate + + # 30% of total score = days since join date + if self.date_joined: days_on_platform = (timezone.now() - self.date_joined).days + + # compute how many days out of 2 years the user has been on the platform + # then normalize it + else: days_on_platform = 0 + max_points_date_joined = 730 # 2 years in days since the user joined the platform + time_score = min(days_on_platform / max_points_date_joined * 100, 100) + + # get the items listed by the user + print(self.items_rented_out) + if self.items_rented: + from item.utils.categories import get_user_rented_categories + + # listed_items = Item.objects.filter(seller=self.id) + print("items listed:") + # print(listed_items) + # for item in listed_items: + # print("item title: %s", item.title) + + rented_categories = get_user_rented_categories(self) + print("user rented:") + print(rented_categories) + + rented_items_weighted = 0 # temp + else: + rented_items_weighted = 0 + + rented_items_score = 0 # compute here + + print(self.items_rented) + if self.items_rented_out: + from item.utils.categories import get_user_listed_categories + listed_categories = get_user_listed_categories(self) + print("user listed:") + print(listed_categories) + else: + listed_items_weighted = 0 + + listed_items_score = 0 # compute here + + score = ( (self.items_rented_out * 2.5) + (self.items_rented * 1.5) @@ -214,6 +263,8 @@ def calculate_sustainability_score(self): max_score = 100 normalized_score = min(max(round(score), 1), max_score) + + # update user's score in DB self.sustainability_score = normalized_score def save(self, *args, **kwargs): @@ -226,3 +277,58 @@ def save(self, *args, **kwargs): """ self.calculate_sustainability_score() super().save(*args, **kwargs) + + +# used to map weights to the different item categories +# class ItemCategory(Enum): +# ELECTRONICS = "Electronics" +# FURNITURE = "Furniture" +# CLOTHING = "Clothing" +# BOOKS = "Books" +# APPLIANCES = "Appliances" +# SPORTS = "Sports" +# TOYS = "Toys" +# TOOLS = "Tools" +# VEHICLES = "Vehicles" +# PARTY = "Party" +# MUSIC = "Music" +# PHOTOGRAPHY = "Photography" +# GARDENING = "Gardening" +# OFFICE = "Office" +# OTHER = "Other" + +# Dictionary containing weights corresponding to each category +# CATEGORY_WEIGHTS = { +# "Electronics" = 2, +# "Furniture" = 1.5, +# "Clothing" = 3, +# "Books" = 3, +# "Appliances" = 2, +# "Sports" = 2.5, +# "Toys" = 2.5, +# "Tools" = 2, +# "Vehicles" = 2, +# "Party" = 2, +# "Music" = 1, +# "Photography" = 1, +# "Gardening" = 1.5, +# "Office" = 1, +# "Other" = 1, +# } +CATEGORY_WEIGHTS = { + "Electronics": 2, + "Furniture": 1.5, + "Clothing": 3, + "Books": 3, + "Appliances": 2, + "Sports": 2.5, + "Toys": 2.5, + "Tools": 2, + "Vehicles": 2, + "Party": 2, + "Music": 1, + "Photography": 1, + "Gardening": 1.5, + "Office": 1, + "Other": 1, +} \ No newline at end of file From e4d46c77689629514bb463234ebb959742152979 Mon Sep 17 00:00:00 2001 From: PFGrande <2002.pedrogrande@gmail.com> Date: Sat, 7 Dec 2024 12:51:16 -0800 Subject: [PATCH 05/13] removed unused fields in RentalSidebar.tsx, fixed datatype mismatches when receiving requests in rent_item() item api function --- .../backend/secondchance_backend/item/api.py | 35 +++++++++++++++---- .../app/components/items/RentalSidebar.tsx | 7 ++-- 2 files changed, 32 insertions(+), 10 deletions(-) diff --git a/application/backend/secondchance_backend/item/api.py b/application/backend/secondchance_backend/item/api.py index 04a55b9..4b1124b 100644 --- a/application/backend/secondchance_backend/item/api.py +++ b/application/backend/secondchance_backend/item/api.py @@ -10,7 +10,7 @@ from .serializers import ItemListSerializer, ItemDetailSerializer, RentalListSerializer from django.shortcuts import get_object_or_404 from useraccount.models import User - +from datetime import date, datetime @api_view(["GET"]) @authentication_classes([]) @@ -158,14 +158,27 @@ def rent_item(request, pk): :return: JSON response indicating success or failure. :rtype: JsonResponse """ + print("==CALLED: rent_item()==") + print("Incoming POST data:", request.data) try: start_date = request.POST.get("start_date", "") end_date = request.POST.get("end_date", "") - number_of_days = request.POST.get("number_of_days", "") - total_price = request.POST.get("total_price", "") - - item = Item.objects.get(pk=pk) - + number_of_days = int(request.POST.get("number_of_days", 0)) + total_price = int(request.POST.get("total_price", 0)) + + try: + start_date = datetime.strptime(start_date, "%Y-%m-%d").date() + end_date = datetime.strptime(end_date, "%Y-%m-%d").date() + except ValueError as err: + print("Date parsing error:", err) + return JsonResponse({"success": False, "error": "Error parsing dates."}, status=404) + + + try: + item = Item.objects.get(pk=pk) + except Item.DoesNotExist: + return JsonResponse({"success": False, "error": "Item not found."}, status=404) + Rental.objects.create( item=item, start_date=start_date, @@ -174,8 +187,16 @@ def rent_item(request, pk): total_price=total_price, created_by=request.user, ) - + print("rental object created") + + request.user.increment_items_rented() + print(request.user.items_rented) + print("request.user.items_rented before calling refresh_from_db()") + request.user.refresh_from_db() + print("request.user.items_rented AFTER calling refresh_from_db()") + print(request.user.items_rented) + return JsonResponse({"success": True}) except Exception as e: diff --git a/application/secondchance/app/components/items/RentalSidebar.tsx b/application/secondchance/app/components/items/RentalSidebar.tsx index 6344945..7f0b43b 100644 --- a/application/secondchance/app/components/items/RentalSidebar.tsx +++ b/application/secondchance/app/components/items/RentalSidebar.tsx @@ -44,9 +44,10 @@ const RentalSidebar: React.FC = ({ item, userId }) => { if (userId) { if (dateRange.startDate && dateRange.endDate) { const formData = new FormData(); - formData.append('location', item.location); - formData.append('condition', item.condition); - formData.append('category', item.category); + // removed fields not present in Rental Model + // formData.append('location', item.location); + // formData.append('condition', item.condition); + // formData.append('category', item.category); formData.append('start_date', format(dateRange.startDate, 'yyyy-MM-dd')); formData.append('end_date', format(dateRange.endDate, 'yyyy-MM-dd')); formData.append('number_of_days', days.toString()); From 626bfdd2fcb57c0ba576a62630a987d5eddf2486 Mon Sep 17 00:00:00 2001 From: PFGrande <2002.pedrogrande@gmail.com> Date: Sat, 7 Dec 2024 13:20:31 -0800 Subject: [PATCH 06/13] fixed issue with get_user_rented_categories() using broken query, success popup appears after booking and returns user to landing page --- .../backend/secondchance_backend/item/api.py | 14 +-- .../item/utils/categories.py | 5 +- .../useraccount/models.py | 93 +++++++++++++------ 3 files changed, 74 insertions(+), 38 deletions(-) diff --git a/application/backend/secondchance_backend/item/api.py b/application/backend/secondchance_backend/item/api.py index 4b1124b..d1c07af 100644 --- a/application/backend/secondchance_backend/item/api.py +++ b/application/backend/secondchance_backend/item/api.py @@ -169,8 +169,8 @@ def rent_item(request, pk): try: start_date = datetime.strptime(start_date, "%Y-%m-%d").date() end_date = datetime.strptime(end_date, "%Y-%m-%d").date() - except ValueError as err: - print("Date parsing error:", err) + except ValueError as e: + print("Date parsing error:", e) return JsonResponse({"success": False, "error": "Error parsing dates."}, status=404) @@ -191,11 +191,11 @@ def rent_item(request, pk): request.user.increment_items_rented() - print(request.user.items_rented) - print("request.user.items_rented before calling refresh_from_db()") - request.user.refresh_from_db() - print("request.user.items_rented AFTER calling refresh_from_db()") - print(request.user.items_rented) + # print(request.user.items_rented) + # print("request.user.items_rented before calling refresh_from_db()") + # request.user.refresh_from_db() + # print("request.user.items_rented AFTER calling refresh_from_db()") + # print(request.user.items_rented) return JsonResponse({"success": True}) diff --git a/application/backend/secondchance_backend/item/utils/categories.py b/application/backend/secondchance_backend/item/utils/categories.py index 847143f..d6bce44 100644 --- a/application/backend/secondchance_backend/item/utils/categories.py +++ b/application/backend/secondchance_backend/item/utils/categories.py @@ -13,11 +13,12 @@ def get_user_rented_categories(user): return: list of categories rtype: list? """ + print("==CALLED: get_user_rented_categories()==") from item.models import Rental # convert QuerySet to list before returning return list( - Rental.objects.filter(rentals__created_by=user) - .values_list('category', flat=True) # returns desired field + Rental.objects.filter(created_by=user) + .values_list('item__category', flat=True) # returns desired field # .distinct() # eliminate duplicate categories ) diff --git a/application/backend/secondchance_backend/useraccount/models.py b/application/backend/secondchance_backend/useraccount/models.py index cbdc861..83a32fb 100644 --- a/application/backend/secondchance_backend/useraccount/models.py +++ b/application/backend/secondchance_backend/useraccount/models.py @@ -179,9 +179,22 @@ def increment_items_rented(self): :return: None :rtype: None """ + print("==CALLED: increment_items_rented()==") + # self.refresh_from_db() + print("--userinfo--") + print(f"User ID: {self.id}") + print(f"User Email: {self.email}") + print(f"User Name: {self.name}") + + print(f"Before increment: {self.items_rented}") self.items_rented += 1 + print(f"After increment: {self.items_rented}") self.calculate_sustainability_score() + print(f"After score calculation: {self.sustainability_score}") self.save(update_fields=["items_rented", "sustainability_score"]) + print(self.items_rented) + print("Items rented and score saved successfully") + def calculate_sustainability_score(self): """ @@ -195,7 +208,7 @@ def calculate_sustainability_score(self): :return: None :rtype: None """ - print("sustainability score computing...") + print("==CALLED: calculate_sustainability_score==") # Concept for changes to the sustainability score: # consider the type of item that is being sold and assign each item type a weight # ex. clothing will have a higher weight than electronics because it can be @@ -209,6 +222,7 @@ def calculate_sustainability_score(self): # 30% of total score = days since join date + max_normalized_score = 100 if self.date_joined: days_on_platform = (timezone.now() - self.date_joined).days @@ -220,40 +234,59 @@ def calculate_sustainability_score(self): days_on_platform = 0 max_points_date_joined = 730 # 2 years in days since the user joined the platform - time_score = min(days_on_platform / max_points_date_joined * 100, 100) - - # get the items listed by the user - print(self.items_rented_out) - if self.items_rented: + time_score = min((days_on_platform / max_points_date_joined) * 100, 100) + print("--sustainability time score-- ", time_score) + # get the items rented by the user + + if self.items_rented or self.items_rented_out != 0: from item.utils.categories import get_user_rented_categories # listed_items = Item.objects.filter(seller=self.id) - print("items listed:") # print(listed_items) # for item in listed_items: # print("item title: %s", item.title) - rented_categories = get_user_rented_categories(self) - print("user rented:") + rented_categories = get_user_rented_categories(self) print(rented_categories) rented_items_weighted = 0 # temp + for category in rented_categories: + print(category) + print(CATEGORY_WEIGHTS[category.lower()]) + else: rented_items_weighted = 0 + print("--sustainability rented score-- PLACEHOLDER:", 0) + + max_rented_score = 30 + rented_items_score = 0 # compute here - print(self.items_rented) + # print(self.items_rented) + + # rented out = listed by user if self.items_rented_out: from item.utils.categories import get_user_listed_categories listed_categories = get_user_listed_categories(self) - print("user listed:") - print(listed_categories) + + # print(listed_categories) + listed_items_weighted = 0 + for category in listed_categories: + listed_items_weighted += CATEGORY_WEIGHTS[category.lower()] + else: listed_items_weighted = 0 - listed_items_score = 0 # compute here + max_listed_score = 50 + listed_items_score = min(max((listed_items_weighted / max_listed_score) * 100, 0), max_normalized_score) # compute here + print("--sustainability listed score-- ", listed_items_score) + # print("--TEST LISTED ITEM SCORE 100--") + # print(min(max((60 / max_listed_score) * 100, 0), max_normalized_score)) + # print("--TEST LISTED ITEM SCORE 3--") + # print(min(max((3 / max_listed_score) * 100, 0), max_normalized_score)) + score = ( (self.items_rented_out * 2.5) @@ -262,7 +295,9 @@ def calculate_sustainability_score(self): ) max_score = 100 - normalized_score = min(max(round(score), 1), max_score) + normalized_score = min(max(round(score), 0), max_score) + + # update user's score in DB self.sustainability_score = normalized_score @@ -316,19 +351,19 @@ def save(self, *args, **kwargs): # "Other" = 1, # } CATEGORY_WEIGHTS = { - "Electronics": 2, - "Furniture": 1.5, - "Clothing": 3, - "Books": 3, - "Appliances": 2, - "Sports": 2.5, - "Toys": 2.5, - "Tools": 2, - "Vehicles": 2, - "Party": 2, - "Music": 1, - "Photography": 1, - "Gardening": 1.5, - "Office": 1, - "Other": 1, + "electronics": 2, + "furniture": 1.5, + "clothing": 3, + "books": 3, + "appliances": 2, + "sports": 2.5, + "toys": 2.5, + "tools": 2, + "vehicles": 2, + "party": 2, + "music": 1, + "photography": 1, + "gardening": 1.5, + "office": 1, + "other": 1, } \ No newline at end of file From 76626e37f2969772e982f4e019d1fcb478840b27 Mon Sep 17 00:00:00 2001 From: PFGrande <2002.pedrogrande@gmail.com> Date: Sat, 7 Dec 2024 13:43:39 -0800 Subject: [PATCH 07/13] corrected field in the rent_item() function, fixing bug were user was only able to rent items when the total price was a whole number --- application/backend/secondchance_backend/item/api.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/application/backend/secondchance_backend/item/api.py b/application/backend/secondchance_backend/item/api.py index d1c07af..3f726df 100644 --- a/application/backend/secondchance_backend/item/api.py +++ b/application/backend/secondchance_backend/item/api.py @@ -164,7 +164,7 @@ def rent_item(request, pk): start_date = request.POST.get("start_date", "") end_date = request.POST.get("end_date", "") number_of_days = int(request.POST.get("number_of_days", 0)) - total_price = int(request.POST.get("total_price", 0)) + total_price = float(request.POST.get("total_price", 0)) try: start_date = datetime.strptime(start_date, "%Y-%m-%d").date() From 95c83faac4ddf1692833fa9e4e416456bf1a0a8f Mon Sep 17 00:00:00 2001 From: PFGrande <2002.pedrogrande@gmail.com> Date: Sat, 7 Dec 2024 14:31:24 -0800 Subject: [PATCH 08/13] successfully implemented counting of actively rented listings --- .../item/utils/categories.py | 27 ++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/application/backend/secondchance_backend/item/utils/categories.py b/application/backend/secondchance_backend/item/utils/categories.py index d6bce44..1e79095 100644 --- a/application/backend/secondchance_backend/item/utils/categories.py +++ b/application/backend/secondchance_backend/item/utils/categories.py @@ -41,4 +41,29 @@ def get_user_listed_categories(user): Item.objects.filter(seller=user) .values_list('category', flat=True) # .distinct() - ) \ No newline at end of file + ) + +def count_items_rented_from_user(user): + """ + Get the number of items that are currently being rented from the given user + Find the rentals that have an item that belongs to the user instance passed in + + args: + user instance + + return: number of items being rented from the user + rtype: int + """ + from datetime import date + from item.models import Rental, Item + + print("===CALLED: count_items_rented_from_user()") + + today = date.today() + + # count the number of listings belonging to the user that are being rented out + return Rental.objects.filter( + item__seller = user, # listings put up by user + start_date__lte = today, # listed items rented today or sooner + end_date__gte = today # listed items rented today or after + ).count() \ No newline at end of file From d2574a21173715a4a2792470cfbce70cac83bbf5 Mon Sep 17 00:00:00 2001 From: PFGrande <2002.pedrogrande@gmail.com> Date: Sat, 7 Dec 2024 14:54:18 -0800 Subject: [PATCH 09/13] sustainability score is now fully functional --- .../useraccount/models.py | 71 +++++++++++++------ 1 file changed, 51 insertions(+), 20 deletions(-) diff --git a/application/backend/secondchance_backend/useraccount/models.py b/application/backend/secondchance_backend/useraccount/models.py index 83a32fb..59e42d5 100644 --- a/application/backend/secondchance_backend/useraccount/models.py +++ b/application/backend/secondchance_backend/useraccount/models.py @@ -220,8 +220,11 @@ def calculate_sustainability_score(self): # currently being rented # con: score will constantly fluxuate - # 30% of total score = days since join date + # 25% items rented by user + # 30% items listed by user + # 15% popularity (items listed by the user currently being rented by other users) + max_normalized_score = 100 if self.date_joined: @@ -238,7 +241,7 @@ def calculate_sustainability_score(self): print("--sustainability time score-- ", time_score) # get the items rented by the user - if self.items_rented or self.items_rented_out != 0: + if self.items_rented or self.items_rented != 0: from item.utils.categories import get_user_rented_categories # listed_items = Item.objects.filter(seller=self.id) @@ -247,27 +250,32 @@ def calculate_sustainability_score(self): # print("item title: %s", item.title) rented_categories = get_user_rented_categories(self) - print(rented_categories) - - rented_items_weighted = 0 # temp + # print(rented_categories) + # print(rented_categories) + rented_items_weighted = 0 for category in rented_categories: - print(category) - print(CATEGORY_WEIGHTS[category.lower()]) + # print(category) + # print(CATEGORY_WEIGHTS[category.lower()]) + rented_items_weighted += CATEGORY_WEIGHTS[category.lower()] else: rented_items_weighted = 0 - print("--sustainability rented score-- PLACEHOLDER:", 0) - - max_rented_score = 30 - - rented_items_score = 0 # compute here + max_rented_score = 40 + + rented_items_score = min(max((rented_items_weighted / max_rented_score) * 100, 0), max_normalized_score) # compute here + print("--sustainability rented score-- ", rented_items_score) # print(self.items_rented) # rented out = listed by user if self.items_rented_out: from item.utils.categories import get_user_listed_categories + from item.utils.categories import count_items_rented_from_user + print("===LISTINGS RENTED FROM USER===") + + raw_popularity_score = count_items_rented_from_user(self) + listed_categories = get_user_listed_categories(self) # print(listed_categories) @@ -276,26 +284,49 @@ def calculate_sustainability_score(self): listed_items_weighted += CATEGORY_WEIGHTS[category.lower()] else: + raw_popularity_score = 0 listed_items_weighted = 0 max_listed_score = 50 - + max_raw_popularity_score = 80 + listed_items_score = min(max((listed_items_weighted / max_listed_score) * 100, 0), max_normalized_score) # compute here + + popularity_score = min(max(raw_popularity_score / max_raw_popularity_score * 100, 0), max_normalized_score) + print("--sustainability listed score-- ", listed_items_score) # print("--TEST LISTED ITEM SCORE 100--") # print(min(max((60 / max_listed_score) * 100, 0), max_normalized_score)) # print("--TEST LISTED ITEM SCORE 3--") # print(min(max((3 / max_listed_score) * 100, 0), max_normalized_score)) - - score = ( - (self.items_rented_out * 2.5) - + (self.items_rented * 1.5) - + (days_on_platform * 0.1) + print("time score: ") + print(time_score) + print("rented items score") + print(rented_items_score) + print("listed items score") + print(listed_items_score) + print("popularity score") + print(popularity_score) + + total_sustainability_score = ( + time_score * 0.3 + + rented_items_score * 0.25 + + listed_items_score * 0.3 + + popularity_score * 0.15 ) - max_score = 100 - normalized_score = min(max(round(score), 0), max_score) + normalized_score = min(max(round(total_sustainability_score), 0), max_score) + + + # score = ( + # (self.items_rented_out * 2.5) + # + (self.items_rented * 1.5) + # + (days_on_platform * 0.1) + # ) + + # max_score = 100 + # normalized_score = min(max(round(score), 0), max_score) From b874666bb465a4abb0401475b0a4510a31d59ada Mon Sep 17 00:00:00 2001 From: PFGrande <2002.pedrogrande@gmail.com> Date: Sat, 7 Dec 2024 17:34:53 -0800 Subject: [PATCH 10/13] successfully retrieved sustainability score on the Rental detailed view --- .../app/components/items/RentalSidebar.tsx | 31 ++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/application/secondchance/app/components/items/RentalSidebar.tsx b/application/secondchance/app/components/items/RentalSidebar.tsx index 7f0b43b..3484093 100644 --- a/application/secondchance/app/components/items/RentalSidebar.tsx +++ b/application/secondchance/app/components/items/RentalSidebar.tsx @@ -39,6 +39,7 @@ const RentalSidebar: React.FC = ({ item, userId }) => { const [dateRange, setDateRange] = useState(initialDateRange); const [minDate, setMinDate] = useState(new Date()); const [reservedDates, setReservedDates] = useState([]); + const [sustainabilityScore, setSustainabilityScore] = useState(0); const processRental = async () => { if (userId) { @@ -98,8 +99,27 @@ const RentalSidebar: React.FC = ({ item, userId }) => { setReservedDates(dates); }; + const fetchSustainabilityScore = async () => { + if (userId) { + try { + const userData = await apiService.get(`/api/auth/users/${userId}/`); + setSustainabilityScore(userData.sustainability_score || 0); + } catch (error) { + console.error('Error fetching sustainability score:', error); + } + } + }; + + // bug fix: made the second useEffect wait for the sustainabilityScore to change + // instead of executing before it useEffect(() => { getRentals(); + fetchSustainabilityScore(); + }, [userId]); + + useEffect(() => { + console.log("sustainability score:") + console.log(sustainabilityScore) if (dateRange.startDate && dateRange.endDate) { const dayCount = differenceInDays(dateRange.endDate, dateRange.startDate); @@ -107,6 +127,10 @@ const RentalSidebar: React.FC = ({ item, userId }) => { if (dayCount && item.price_per_day) { const _fee = ((dayCount * item.price_per_day) / 100) * 5; + let sustainabilityDiscount = sustainabilityScore * 0.3 + console.log("SUSTAINABILITY DISCOUNT:") + console.log(sustainabilityDiscount) + setFee(_fee); setTotalPrice(dayCount * item.price_per_day + _fee); setDays(dayCount); @@ -118,7 +142,7 @@ const RentalSidebar: React.FC = ({ item, userId }) => { setDays(1); } } - }, [dateRange]); + }, [dateRange, sustainabilityScore], ); return ( );