resume-api / streaksManagement.py
Nattyboi's picture
very scripted
c644472
raw
history blame
2.35 kB
from pymongo import MongoClient
from datetime import datetime,timedelta
def get_current_date():
# Get the current date and return it in YYYY-MM-DD format
return datetime.now().date().isoformat()
def get_another_date(day:int):
# Get the current date and add one day to it
tomorrow = datetime.now() + timedelta(days=day)
return tomorrow.date().isoformat()
def check_date_streak(start_date: str, end_date: str) -> bool:
# Convert ISO strings to datetime objects
start_date = datetime.fromisoformat(start_date)
end_date = datetime.fromisoformat(end_date)
# Compare the dates to check if they are consecutive (1 day apart)
return end_date - start_date == timedelta(days=1)
def streaks_manager(db_uri: str, document: dict) -> str:
"""
Inserts a new document into the specified MongoDB collection.
Parameters:
db_uri (str): MongoDB connection URI.
db_name (str): Name of the database.
collection_name (str): Name of the collection.
document (dict): The document to insert.
Returns:
str: The ID of the inserted document.
"""
# Connect to MongoDB
client = MongoClient(db_uri)
db = client["crayonics"]
collection = db["Streaks"]
# Insert the document
foundUser = collection.find_one({"user_id":document.get('user_id')})
streak_dates=get_current_date()
document['streak_dates']= [streak_dates]
if foundUser==None:
result = collection.insert_one(document)
client.close()
return True
else:
print("user has a streak record")
is_a_streak=check_date_streak(start_date=foundUser['streak_dates'][-1],end_date=get_current_date())
if is_a_streak:
print("its a streak guys")
dates = []
for d in foundUser["streak_dates"]:
dates.append(d)
dates.append(get_current_date())
collection.update_one(filter={"user_id":document.get("user_id")},update={
"$set":{"streak_dates":dates}
}
)
client.close()
return True
else:
collection.find_one_and_replace(filter={"user_id":document.get('user_id')},replacement=document)
return "User Already Exists"
# Close the connection