Spaces:
Running
Running
File size: 2,511 Bytes
d951fea 07fa724 d951fea 07fa724 d951fea 07fa724 d951fea 07fa724 d951fea 07fa724 d951fea 07fa724 d951fea 07fa724 d951fea 07fa724 d951fea 07fa724 d951fea 07fa724 d951fea |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
from pymongo import MongoClient
from datetime import datetime, timedelta
from typing import Dict, Union
def get_current_date() -> str:
# Get the current date and return it in YYYY-MM-DD format
return datetime.now().date().isoformat()
def get_another_date(day: int) -> str:
# Get the current date and add specified days 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) -> Union[bool, str]:
"""
Manage user streaks in MongoDB.
Args:
db_uri: MongoDB connection string
document: Dictionary containing user data with 'user_id' key
Returns:
Union[bool, str]: True if successful, "User Already Exists" if streak is reset
"""
client = MongoClient(db_uri)
try:
db = client["crayonics"]
collection = db["Streaks"]
# Check for existing user
found_user = collection.find_one({"user_id": document.get('user_id')})
current_date = get_current_date()
document['streak_dates'] = [current_date]
if found_user is None:
# New user case
collection.insert_one(document)
return True
else:
is_a_streak = check_date_streak(
start_date=found_user['streak_dates'][-1],
end_date=current_date
)
if is_a_streak:
print("its a streak guys")
# Extend existing streak
dates = found_user["streak_dates"] + [current_date]
collection.update_one(
{"user_id": document.get("user_id")},
{"$set": {"streak_dates": dates}}
)
return True
else:
# Reset streak if not consecutive
collection.find_one_and_replace(
{"user_id": document.get('user_id')},
document
)
return "User Already Exists"
except Exception as e:
print(f"Error: {str(e)}")
raise
finally:
client.close()
|