Files
cs50-Final-Project/README.md
T

3.5 KiB

cs50-Final-Project

CLI calendar conflict tool

Code block for reverse engineering from datetime import datetime, timedelta import sqlite3 import typer

@app.command() def add(): while True: name = input("Event Name: ") date_input = input("Date of Event (DD-MM-YY): ") time = input("Time of Event (HH:MM): ") length_str = input("Length of Event (in minutes): ") description = input("Description of Event: ")

    try:
        # Try parsing the inputs
        parsed_date = datetime.strptime(date_input, "%d-%m-%y")
        db_date = parsed_date.strftime("%Y-%m-%d")
        start_datetime = datetime.strptime(f"{db_date} {time}", "%Y-%m-%d %H:%M")
        duration = int(length_str)
        end_datetime = start_datetime + timedelta(minutes=duration)
        
        # If parsing succeeds with no errors, break out of the retry loop
        break
        
    except ValueError:
        # If a typing mistake happens, show red error and loop back to the start
        error_message = "Error: Invalid format. Please use DD-MM-YY for date, HH:MM for time, and a number for length. Let's try again.\n"
        typer.echo(typer.style(error_message, fg=typer.colors.RED), err=True)

# 2. Query existing events using the verified db_date for clash detection
conn = sqlite3.connect("events")
cursor = conn.cursor()

cursor.execute("SELECT name, time, length FROM events WHERE date = ?", (db_date,))
existing_events = cursor.fetchall()

# 3. Check for clashes
for existing_name, existing_time, existing_length in existing_events:
    ex_start = datetime.strptime(f"{db_date} {existing_time}", "%Y-%m-%d %H:%M")
    ex_end = ex_start + timedelta(minutes=int(existing_length))

    if start_datetime < ex_end and ex_start < end_datetime:
        print(f"\n❌ Clash detected! Conflicts with existing event: '{existing_name}' ({existing_time} - {ex_end.strftime('%H:%M')})")
        conn.close()
        return  # Exit the command if there's a clash

# 4. Save to database if no clashes
cursor.execute(
    "INSERT INTO events (name, date, time, length, description) VALUES (?, ?, ?, ?, ?)",
    (name, db_date, time, duration, description)
)
conn.commit()
conn.close()

print("\n✅ Event successfully added without clashes!")

# 1. Open connection and use your helper to create the cursor
    conn = sqlite3.connect("events")
    cursor = create_cursor(conn)  # <--- Using your helper function here!
    
    # 2. Query existing events
    cursor.execute("SELECT name, time, length FROM events WHERE date = ?", (db_date,))
    existing_events = cursor.fetchall()

    # 3. Check for clashes
    for existing in existing_events:
        # Because of your helper, you can use column names instead of numbers!
        existing_name = existing["name"]
        existing_time = existing["time"]
        existing_length = existing["length"]

        ex_start = datetime.strptime(f"{db_date} {existing_time}", "%Y-%m-%d %H:%M")
        ex_end = ex_start + timedelta(minutes=int(existing_length))

        if start_datetime < ex_end and ex_start < end_datetime:
            print(f"\n❌ Clash detected! Conflicts with existing event: '{existing_name}' ({existing_time} - {ex_end.strftime('%H:%M')})")
            conn.close()
            return

    # Don't forget to close your connection when done
    conn.close()