Skip to content

Commit

Permalink
Adding code for retrieving praise data for feedback
Browse files Browse the repository at this point in the history
  • Loading branch information
AndrewHUNGNguyen committed Sep 26, 2024
1 parent d0f8b76 commit 185c266
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 26 deletions.
29 changes: 22 additions & 7 deletions api/messages/messages_service.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from common.utils import safe_get_env_var
from common.utils.slack import send_slack_audit, create_slack_channel, send_slack, invite_user_to_channel
from common.utils.firebase import get_hackathon_by_event_id, upsert_news, upsert_praise, get_github_contributions_for_user
from common.utils.firebase import get_hackathon_by_event_id, upsert_news, upsert_praise, get_github_contributions_for_user, get_praises_by_user_id
from common.utils.openai_api import generate_and_save_image_to_cdn
from common.utils.github import create_github_repo
from api.messages.message import Message
Expand Down Expand Up @@ -1236,26 +1236,41 @@ def save_news(json):

return Message("Saved News")

# -------------------- Praises methods begin here --------------------------- #
def save_praise(json):
logger.debug(f"Attempting to save the praise with the json object {json}")
# Take in Slack message and summarize it using GPT-3.5
# Make sure these fields exist praise_receiver, praise_channel, praise_message
check_fields = ["praise_receiver", "praise_channel", "praise_message"]

# Make sure the fields exist praise_receiver, praise_channel, praise_message
check_fields = ["praise_channel", "praise_message"]
for field in check_fields:
if field not in json:
logger.error(f"Missing field {field} in {json}")
return Message("Missing field")

json["timestamp"] = datetime.now().isoformat()

logger.debug(f"Detected required fields, attempting to save praise")
logger.debug("Received valid request, preparing to upsert.")

upsert_praise(json)

logger.info("Updated praise successfully")

#get_news.cache_clear()
#logger.info("Cleared cache for get_news")
get_praises_about_user.cache_clear()
logger.info("Cleared cache for get_praises_by_user_id")

return Message("Saved praise")

@cached(cache=TTLCache(maxsize=100, ttl=600))
def get_praises_about_user(user_id):

# Get the praises about user with user_id
results = get_praises_by_user_id(user_id)

logger.info(f"Here are all praises related to {user_id}: {results}")
return Message(results)

# -------------------- Praises methods end here --------------------------- #

async def save_lead(json):
token = json["token"]

Expand Down
23 changes: 12 additions & 11 deletions api/messages/messages_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
get_npo_applications,
update_npo_application,
get_github_profile,
get_praises_about_user,
save_praise,
save_feedback,
get_user_feedback
Expand Down Expand Up @@ -270,23 +271,23 @@ async def store_lead():
# -------------------- Praises routes begin here --------------------------- #
@bp.route("/praise", methods=["POST"])
def store_praise():
# Check header for token
# if token is valid, store news
# else return 401

token = request.headers.get("X-Api-Key")

# Check BACKEND_NEWS_TOKEN
json = request.get_json()

# Check BACKEND_PRAISE_TOKEN. If token is not valid, return 401
if token == None or token != os.getenv("BACKEND_PRAISE_TOKEN"):
return "Unauthorized", 401
# If praise_sender and praise_receiver are the same, return 400
elif json["praise_sender"] == json["praise_receiver"]:
logger.error("You cannot write a praise to yourself")
return "Cannot write a praise to yourself", 400
else:
logger.debug(f"Hre is the request object {request.get_json()}")
# try:
# logger.debug(f"Here is the request object: {request.get_json()}")
# except Exception as e:
# logger.error(f"Error logging request object: {e}")
return vars(save_praise(request.get_json()))

@bp.route("/praise/<user_id>", methods=["GET"])
def get_praises_about_self(user_id):
# return all praise data about user with user_id in route
return vars(get_praises_about_user(user_id))
# -------------------- Praises routes end here --------------------------- #

# -------------------- Problem Statement routes to be deleted --------------------------- #
Expand Down
25 changes: 17 additions & 8 deletions common/utils/firebase.py
Original file line number Diff line number Diff line change
Expand Up @@ -1048,14 +1048,23 @@ def upsert_news(news):

def upsert_praise(praise):
db = get_db() # this connects to our Firestore database
logger.info(f"Adding praise {praise}")

#Check if the vibe field exists.
if "praise_gif" not in praise:
logger.info("vibe field not found, setting praise['vibe'] to None")
praise["praise_gif"] = None

logger.info(f"Adding refined praise {praise} into the database")
logger.info(f"Adding praise {praise} into the collections database")

db.collection("praises").add(praise)
logger.info("praise successfully saved")

def get_praises_by_user_id(user_id):
# Gets all documents with user_id in its database attribute
db = get_db()
#docs = db.collection('hackathons').where("end_date", ">=", today_str).order_by("end_date", direction=firestore.Query.DESCENDING).stream()
praises= db.collection("praises").where("praise_receiver","==",user_id).get()
#praises = db.collection('praises').where("praise_receiver", "==", user_id).order_by("timestamp", direction=firestore.Query.DESCENDING).stream()
# convert each document to a python dictionary
praise_list = []
for doc in praises:
doc_json = doc.to_dict()
doc_json["id"] = doc.id
praise_list.append(doc_json)

# return the praise_list sorted in descending order by timestamp
return sorted(praise_list, key=lambda x: x["timestamp"], reverse=True)

0 comments on commit 185c266

Please sign in to comment.