File size: 2,352 Bytes
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

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