Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rating #118

Merged
merged 13 commits into from
May 26, 2024
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app).

## Running Unit Tests

`python backend/manage.py test backend/`

## Formatting Code

- For Python code run `black backend/**/*.py`
- For All other code run `bun run prettier * --write`
- For Python code run `black backend/*`
- For All other code run `bunx prettier * --write`

## Running Code

Expand Down
6 changes: 4 additions & 2 deletions app/locations/[location]/DH_Search/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,8 @@ const HelloWorld: React.FC = () => {
);

if (currentDiningHall) {
const allFoods: { food: Food; dhName: string; categoryName: string }[] = [];
const allFoods: { food: Food; dhName: string; categoryName: string }[] =
[];

// Collect all foods from the current dining hall only
currentDiningHall.categories.forEach((category) => {
Expand Down Expand Up @@ -247,7 +248,8 @@ const BarebonesComponent: React.FC = () => {
);

if (currentDiningHall) {
const allFoods: { food: Food; dhName: string; categoryName: string }[] = [];
const allFoods: { food: Food; dhName: string; categoryName: string }[] =
[];

// Collect all foods from the current dining hall only
currentDiningHall.categories.forEach((category) => {
Expand Down
57 changes: 57 additions & 0 deletions app/locations/[location]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,33 @@ import axios from "axios";
import LocationFood from "@/components/location/food";

import { Location } from "@/interfaces/Location";
import { reverse } from "dns";
import test from "node:test";
import { Average } from "next/font/google";

interface RestrictionImageMap {
[key: string]: string;
}

interface food_reviews {
user_id: string;
rating: number;
}

interface food_item {
user_ratings: Array<food_reviews>;
average: number;
}

interface test {
[key: string]: food_item;
}

export default function Page({ params }: { params: { location: number } }) {
const [location, setLocation] = useState<Location>();
const [showCategories, setShowCategories] = useState<boolean[]>([]);
// const [food_reviews, setReviews] = useState<food_item>();
const [food_reviews, setReviews] = useState<test>({});

const restrictionImageMap: RestrictionImageMap = {
eggs: "/Images/egg.jpg",
Expand All @@ -38,6 +57,18 @@ export default function Page({ params }: { params: { location: number } }) {
const locations = response.data.locations;
const location = locations[params.location];
setLocation(location);
axios
.post("http://localhost:8000/myapi/db_update/", {
dh_name: location.name,
})
.then((response) => {
//get diff?
console.log(response.data);
temp();
})
.catch((error) => {
console.log(error);
});

// Get current hour
const currentHour = new Date().getHours();
Expand Down Expand Up @@ -77,6 +108,31 @@ export default function Page({ params }: { params: { location: number } }) {
}
};

function temp() {
//call only once on opening page and rating change
axios
.get(
"http://localhost:8000/myapi/get_ratings/", //gets the user rating
) //need to get global

.then((response) => {
//get diff?
setReviews(response.data);
})
.catch((error) => {
console.log(error);
});
}

function temper(food_name: string) {
//get the average rating for the food and return 0 if no exist yet

if (food_reviews[food_name] != null) {
return food_reviews[food_name].average;
}
return 0;
}

return (
<main>
<div className="container mx-auto">
Expand Down Expand Up @@ -136,6 +192,7 @@ export default function Page({ params }: { params: { location: number } }) {
{subCategory.foods.map((food, k) => (
<LocationFood
key={k}
food_average={temper(food.name)}
food_name={food.name}
restriction_images={food.restrictions.map(
(restriction) => restrictionImageMap[restriction],
Expand Down
3 changes: 3 additions & 0 deletions app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,15 @@ export default function Home() {
.get("http://localhost:8000/myapi/locations/")
.then((response) => {
setLocations(response.data["locations"]);
// console.log(response.data["locations"][0]);
})
.catch((error) => {
console.log(error);
});
}, []);

// Just update the db?

return (
<main>
<div>
Expand Down
7 changes: 6 additions & 1 deletion app/profile/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,12 @@ const Page = () => {
<h1>Profile</h1>
{user && (
<div>
<Image src={user.picture} alt="User profile" width={imageWidth} height={imageHeight}/>
<Image
src={user.picture}
alt="User profile"
width={imageWidth}
height={imageHeight}
/>
<h2>
Welcome, {user.name} - {user.email}
</h2>
Expand Down
8 changes: 8 additions & 0 deletions backend/myapi/model_logic/foods/actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ def set_food(
"ratings": [],
"comments": [],
"images": [],
"average": 0,
}
foods_collection.insert_one(food)
return food
Expand Down Expand Up @@ -76,6 +77,13 @@ def update_food(
# update the ratings in the db
foods_collection.update_one({"name": name}, {"$set": {"ratings": ratings}})

# update average
total = 0
for user_rating in food["ratings"]:
total += user_rating["rating"]
# print(user_rating['rating'])
food["average"] = total / len(food["ratings"])

# update comment
if comment is not None and user_id is not None:
# get the current comments
Expand Down
90 changes: 90 additions & 0 deletions backend/myapi/model_logic/foods/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from urllib.parse import unquote

from ..locations.actions import get_locations, find_food_in_location
from ..users.actions import update_user


# Get request that takes parameter of food name and returns the food object
Expand Down Expand Up @@ -60,6 +61,95 @@ def get_food(request, name: str):
return Response(food)


##bulk food get?
@api_view(["POST"])
def bulk_update_db(request):
name = request.data.get("dh_name")

# get the location from the db
location = get_locations([name])[0]
if "categories" not in location:
print(f"-" * 20 + " Cat")
return Response(status=400)
for category in location["categories"]:
if "sub_categories" not in category:
continue
for subcategory in category["sub_categories"]:
if "foods" not in subcategory:
continue
for food in subcategory["foods"]:
if "name" not in food:
continue
db_food = get_food_db(food["name"])
if db_food != None: # check if the food name is in the dh dict

if (
db_food["restrictions"] != food["restrictions"]
): # udpate the restrinctions if not the same
update_food_db(food["name"], food["restrictions"])
continue
else:
# add food to db
set_food_db(food["name"], food["restrictions"])

return Response(200)


## Ratings

from ...models import foods_collection


@api_view(["GET"])
def get_ratings(request):

foods = {}
for rating in foods_collection.find():
if rating == None:
return Response(404)
# create
reviews = {}
reviews["user_ratings"] = rating["ratings"]
average = 0

for n in rating["ratings"]:
average += n["rating"]

if len(rating["ratings"]) != 0:
reviews["average"] = average / len(rating["ratings"])
else:
reviews["average"] = 0

foods[rating["name"]] = reviews

return Response(foods)


##update ratings


@api_view(["POST"])
def user_rating_update(request):
print("POST")
# get the food name from the request
food_name = request.data.get("food_name")
# get the user id from the request
user_id = request.data.get("user_id")

food_rating = request.data.get("food_rating")
if food_rating == None:
print("none?")
print("Food: " + food_name)
print("User: " + user_id)
print(f"", end="")
print(food_rating)

update_food_db(food_name, [], user_id, food_rating)

update_user(user_id, food_name, food_rating)
return Response(food_rating)


## Comments
@api_view(["POST"])
def add_comment(request):
Expand Down
1 change: 1 addition & 0 deletions backend/myapi/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@
ratings_schema_location = {
"bsonType": "array",
"items": {
"bsonType": "object",
"properties": {
"user_id": {"bsonType": "string"},
"rating": {"bsonType": "double"},
Expand Down
4 changes: 4 additions & 0 deletions backend/myapi/urls.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
from django.urls import path
from . import views
from .model_logic.foods import views as foods_views
from .model_logic.users import actions as user_funcs

urlpatterns = [
path("locations/", views.get_locations, name="locations"),
path("db_update/", foods_views.bulk_update_db, name="db_update"),
path("users", views.validate_user, name="users"),
path("logout/", views.current_logout, name="current_logout"),
path("foods/<str:name>/", foods_views.get_food, name="foods"),
path("comments/", foods_views.add_comment, name="comments"),
path("rating_update/", foods_views.user_rating_update, name="rating_update"),
path("get_ratings/", foods_views.get_ratings, name="get_ratings"),
]
9 changes: 9 additions & 0 deletions backend/myapi/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,3 +131,12 @@ def current_logout(request):

print("Current session after logout:", request.session.get("current_user"))
return JsonResponse({"message": "User has been logged out"})


# @api_view(["GET"])
# def get_user_rating(request):
# user = get_rating(request.user_ids)
# if(user==None):
# return Response({"message": "No user found"})
# else:
# return Response({"message": "User found: {user}", "user data": user})
1 change: 0 additions & 1 deletion backend/webscraper/food.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@


class Food:

restriction_image_map = {
"eggs": "app/locations/Images/egg.jpg",
"vegan": "app/locations/Images/vegan.jpg",
Expand Down
Loading