Skip to content

Commit

Permalink
Merge pull request #49 from utmgdsc/bugs/recommendation-integration
Browse files Browse the repository at this point in the history
Bugs/recommendation integration
  • Loading branch information
Eileenchen02 authored Dec 16, 2023
2 parents 77e11d8 + 97be938 commit ba58c16
Show file tree
Hide file tree
Showing 17 changed files with 577 additions and 423 deletions.
6 changes: 3 additions & 3 deletions backend/models/energy.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,9 +124,9 @@ def from_json(doc: json) -> EnergyEntry:

def from_energy_entry(energy_entry: EnergyEntry) -> EnergyEntryRecommendation:
submetric_threshold = EnergyEntry.metric_threshold/3
heating_oil_recommendation = ""
natural_gas_recommendation = ""
electricity_recommendation = ""
heating_oil_recommendation = "Heating oil emissions look good!"
natural_gas_recommendation = "Natural gas emissions look good!"
electricity_recommendation = "Electricity emissions look good!"

heating_oil_carbon_emissions = energy_entry.heating_oil * 2.753
natural_gas_carbon_emissions = energy_entry.natural_gas * 1.96
Expand Down
16 changes: 8 additions & 8 deletions backend/models/food.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,14 +141,14 @@ def from_json(doc: json) -> FoodEntry:
@staticmethod
def from_food_entry(food_entry: FoodEntry) -> FoodEntryRecomendation:
submetric_threshold = FoodEntry.metric_threshold/8
beef_recommendation = ""
lamb_recommendation = ""
pork_recommendation = ""
chicken_recommendation = ""
fish_recommendation = ""
cheese_recommendation = ""
milk_recommendation = ""
food_waste_recommendation = ""
beef_recommendation = "Beef emissions look good!"
lamb_recommendation = "Lamb emissions look good!"
pork_recommendation = "Pork emissions look good!"
chicken_recommendation = "Chicken emissions look good!"
fish_recommendation = "Fish emissions look good!"
cheese_recommendation = "Cheese emissions look good!"
milk_recommendation = "Milk emissions look good!"
food_waste_recommendation = "Food waste emissions look good!"

beef_carbon_emissions = food_entry.beef * 15.5
lamb_carbon_emissions = food_entry.lamb * 5.84
Expand Down
10 changes: 5 additions & 5 deletions backend/models/transportation.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,11 +115,11 @@ def from_json(doc: json) -> TransportationEntry:
@staticmethod
def from_transportation_entry(transportation_entry: TransportationEntry) -> TransportationEntryRecommendation:
submetric_threshold = TransportationEntry.metric_threshold/5
bus_recommendation = ""
train_recommendation = ""
motorbike_recommendation = ""
electric_car_recommendation = ""
gasoline_car_recommendation = ""
bus_recommendation = "Bus emissions look good!"
train_recommendation = "Train emissions look good!"
motorbike_recommendation = "Motorbike emissions look good!"
electric_car_recommendation = "Electric car emissions look good!"
gasoline_car_recommendation = "Gasoline emissions look good!"

bus_carbon_emissions = transportation_entry.bus * 0.103
train_carbon_emissions = transportation_entry.train * 0.037
Expand Down
113 changes: 75 additions & 38 deletions backend/routes/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

users = Blueprint("/users", __name__)


@users.route("/user/<user_id>", methods=["GET"])
@carbon_auth.auth.login_required
def get_user(user_id: str) -> Response:
Expand All @@ -21,67 +22,78 @@ def get_user(user_id: str) -> Response:
except CarbonTrackError as e:
abort(code=400, description=f"{e}")

@users.route("/get_top_users", methods=['POST'])

@users.route("/get_top_users", methods=["POST"])
@carbon_auth.auth.login_required
def get_top_users() -> Response:
#try:
try:
count = request.get_json()["count"]

# Monthly
_top_monthly_users = CarbonTrackDB.users_coll.find().sort("monthly_score", -1).limit(count)
_top_monthly_users = (
CarbonTrackDB.users_coll.find().sort("monthly_score", -1).limit(count)
)
top_monthly_users = []
rank = 1
for user in _top_monthly_users:
obj = User.from_json(user)
user = {
'rank': rank,
'name': obj.full_name,
'footprint': 0,
'score': obj.overall_score,
"rank": rank,
"name": obj.full_name,
"footprint": 0,
"score": obj.overall_score,
}
rank += 1
top_monthly_users.append(user)

# Yearly
_top_yearly_users = CarbonTrackDB.users_coll.find().sort("yearly_score", -1).limit(count)
_top_yearly_users = (
CarbonTrackDB.users_coll.find().sort("yearly_score", -1).limit(count)
)
top_yearly_users = []
rank = 1
for user in _top_yearly_users:
obj = User.from_json(user)
user = {
'rank': rank,
'name': obj.full_name,
'footprint': 0,
'score': obj.overall_score,
"rank": rank,
"name": obj.full_name,
"footprint": 0,
"score": obj.overall_score,
}
rank += 1
top_yearly_users.append(user)

# Overall
_top_overall_users = CarbonTrackDB.users_coll.find().sort("overall_score", -1).limit(count)
_top_overall_users = (
CarbonTrackDB.users_coll.find().sort("overall_score", -1).limit(count)
)
top_overall_users = []
rank = 1
for user in _top_overall_users:
obj = User.from_json(user)
user = {
'rank': rank,
'name': obj.full_name,
'footprint': 0,
'score': obj.overall_score,
"rank": rank,
"name": obj.full_name,
"footprint": 0,
"score": obj.overall_score,
}
rank += 1
top_overall_users.append(user)

return jsonify({
'top_monthly_users': top_monthly_users,
'top_yearly_users': top_yearly_users,
'top_overall_users': top_overall_users,
})
#except CarbonTrackError as e:
# abort(code=400, description=f"{e}")
return jsonify(
{
"top_monthly_users": top_monthly_users,
"top_yearly_users": top_yearly_users,
"top_overall_users": top_overall_users,
}
)


except CarbonTrackError as e:
abort(code=400, description=f"{e}")


@users.route("/user_email/<user_email>", methods=['GET'])
@users.route("/user_email/<user_email>", methods=["GET"])
@carbon_auth.auth.login_required
def get_user_by_email(user_email: str) -> Response:
try:
Expand Down Expand Up @@ -128,7 +140,7 @@ def get_current_user() -> Response:
@users.route("/user", methods=["PUT"])
@carbon_auth.auth.login_required
def create_user() -> Response:
#try:
try:
res: dict = request.get_json()["user"]
user = User.from_json(res)
user.email = user.email.lower()
Expand All @@ -143,11 +155,11 @@ def create_user() -> Response:
).to_json()
return jsonify({"user": user})
else:
return jsonify(
{"error": "User Already Exits With Same Email, Please Log In"}
)
# except CarbonTrackError as e:
# abort(code=400, description=f"{e}")
return jsonify({"error": "User Already Exits With Same Email, Please Log In"})


except CarbonTrackError as e:
abort(code=400, description=f"{e}")


@users.route("/user/<user_id>", methods=["DELETE"])
Expand Down Expand Up @@ -199,14 +211,15 @@ def update_user_email(uid: str) -> Response:
except CarbonTrackError as e:
abort(code=400, description=f"{e}")


@users.route("/user/update_name/<user_id>", methods=["PATCH"])
@carbon_auth.auth.login_required
def update_user_name(user_id: str) -> Response:
try:
new_name = request.get_json().get("newName", "")

query = {"uid": user_id}

current_user = carbon_auth.auth.current_user()
print(current_user)

Expand All @@ -219,7 +232,7 @@ def update_user_name(user_id: str) -> Response:
return jsonify({"user": item}), 200
except CarbonTrackError as e:
abort(code=400, description=f"{e}")


@users.route("/user/update_province/<user_id>", methods=["PATCH"])
def update_user_province(user_id: str) -> Response:
Expand All @@ -228,11 +241,32 @@ def update_user_province(user_id: str) -> Response:
new_province = request.get_json().get("newProvince", "")
print("Updating province...")
query = {"uid": user_id}

updated_user = CarbonTrackDB.users_coll.find_one_and_update(
query,
{"$set": {"province": new_province}},
return_document=ReturnDocument.AFTER
return_document=ReturnDocument.AFTER,
)

updated_user = User.from_json(updated_user).to_json()

return jsonify({"user": updated_user}), 200
except CarbonTrackError as e:
abort(code=400, description=f"{e}")


@users.route("/user/update_fuel_efficiency/<user_id>", methods=["PATCH"])
def update_user_fuel_efficiency(user_id: str) -> Response:
try:
print("Updating fuel efficiency...")
new_fuel_efficiency = request.get_json().get("newFuelEfficiency", "")
print("Updating province...")
query = {"uid": user_id}

updated_user = CarbonTrackDB.users_coll.find_one_and_update(
query,
{"$set": {"fuel_efficiency": new_fuel_efficiency}},
return_document=ReturnDocument.AFTER,
)

updated_user = User.from_json(updated_user).to_json()
Expand All @@ -241,20 +275,23 @@ def update_user_province(user_id: str) -> Response:
except CarbonTrackError as e:
abort(code=400, description=f"{e}")


@users.route("/user/update_occupancy/<user_id>", methods=["PATCH"])
def update_user_occupancy(user_id: str) -> Response:
try:
print("Updating occupancy...")
print(request.get_json())
new_occupancy = request.get_json().get("newOccupancy", 0)
query = {"uid": user_id}

current_user = carbon_auth.auth.current_user()
print(current_user)

print(f"Updating occupancy for user {user_id} to {new_occupancy}")

CarbonTrackDB.users_coll.update_one(query, {"$set": {"household": new_occupancy}})
CarbonTrackDB.users_coll.update_one(
query, {"$set": {"household": new_occupancy}}
)

item = CarbonTrackDB.users_coll.find_one(query)

Expand Down
32 changes: 22 additions & 10 deletions frontend/src/APIs/UsersAPI.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@ export const UsersAPI = {
return undefined;
}
},
getTopUsers: async (count: number)=> {

getTopUsers: async (count: number) => {
try {
const res = await FLASK_HTTPS.post(routeName + '/get_top_users', {
count,
Expand All @@ -47,7 +47,7 @@ export const UsersAPI = {
return undefined;
}
},

getUserByEmail: async (email: string) => {
try {
const res = await FLASK_HTTPS.get(routeName + '/user_email/' + email);
Expand Down Expand Up @@ -143,10 +143,9 @@ export const UsersAPI = {
},
updateUserName: async (user: User, newName: string) => {
try {
const res = await FLASK_HTTPS.patch(
routeName + `/user/update_name/${user.uid.toString()}`,
{ newName },
);
const res = await FLASK_HTTPS.patch(routeName + `/user/update_name/${user.uid.toString()}`, {
newName,
});

return res.data.user as User;
} catch (error) {
Expand All @@ -158,7 +157,7 @@ export const UsersAPI = {
try {
const res = await FLASK_HTTPS.patch(
routeName + `/user/update_province/${user.uid.toString()}`,
{ newProvince },
{ newProvince }
);

return res.data.user as User;
Expand All @@ -171,13 +170,26 @@ export const UsersAPI = {
try {
const res = await FLASK_HTTPS.patch(
routeName + `/user/update_occupancy/${user.uid.toString()}`,
{ newOccupancy },
{ newOccupancy }
);

return res.data.user as User;
} catch (error) {
console.error('UsersAPI(frontend): updateUserOccupancyError:', error);
return undefined;
}
}
},
updateUserFuelEfficiency: async (user: User, newFuelEfficiency: GLfloat) => {
try {
const res = await FLASK_HTTPS.patch(
routeName + `/user/update_fuel_efficiency/${user.uid.toString()}`,
{ newFuelEfficiency }
);

return res.data.user as User;
} catch (error) {
console.error('UsersAPI(frontend): updateUserFuelEfficiencyError:', error);
return undefined;
}
},
};
1 change: 1 addition & 0 deletions frontend/src/models/Transportation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export interface TransportationEntry {
motorbike: number;
electric_car: number;
gasoline_car: number;
fuel_efficiency: number;
}

export interface MonthlyEntry {
Expand Down
Loading

0 comments on commit ba58c16

Please sign in to comment.