File size: 4,387 Bytes
e9739ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
# components/task_operations.py

import sqlite3
import pandas as pd
from datetime import datetime
import streamlit as st

class TaskManager:
    DB_FILE = "tasks.db"
    CATEGORIES = ['Learning', 'Gym', 'Personal', 'Family', 'Work', 'Prayer']

    def __init__(self):
        self.conn = sqlite3.connect(self.DB_FILE)
        self.create_table()

    def create_table(self):
        # Create tasks table with essential fields
        query = """

        CREATE TABLE IF NOT EXISTS tasks (

            id INTEGER PRIMARY KEY AUTOINCREMENT,

            task_name TEXT NOT NULL,

            task_time TEXT NOT NULL,

            task_duration_hours INTEGER NOT NULL,

            task_duration_minutes INTEGER NOT NULL,

            category TEXT NOT NULL

        );

        """
        self.conn.execute(query)
        self.conn.commit()

    def load_tasks(self):
        # Load tasks from the database
        query = "SELECT * FROM tasks;"
        df = pd.read_sql_query(query, self.conn)

        if not df.empty:
            # Rename columns explicitly to avoid conflicts
            column_mapping = {
                'task_name': 'Task Name', 
                'task_time': 'Task Time',
                'task_duration_hours': 'Task Duration (hours)',
                'task_duration_minutes': 'Task Duration (minutes)', 
                'category': 'Category', 
                'id': 'Task ID'
            }

            # Check for any conflicts before renaming
            existing_columns = set(df.columns)
            for original, new_name in column_mapping.items():
                if new_name in existing_columns and original != new_name:
                    raise ValueError(f"Conflict detected: Column '{new_name}' already exists in the DataFrame.")

            # Rename columns in the DataFrame
            df.rename(columns=column_mapping, inplace=True)

            # Convert 'task_time' to datetime after renaming
            df['Task Time'] = pd.to_datetime(df['Task Time'])

            return df.to_dict(orient='records')
        else:
            return []

    def save_task(self, task):
        # Save task into the database
        query = """

        INSERT INTO tasks (task_name, task_time, task_duration_hours, task_duration_minutes, category)

        VALUES (?, ?, ?, ?, ?);

        """
        self.conn.execute(query, (task['Task Name'], task['Task Time'], task['Task Duration (hours)'], 
                                  task['Task Duration (minutes)'], task['Category']))
        self.conn.commit()

    def add_task(self, task_name, task_time, task_duration_hours, task_duration_minutes, task_category):
        task_time_full = datetime.combine(datetime.today(), task_time)
        task_entry = {
            "Task Name": task_name,
            "Task Time": task_time_full,
            "Task Duration (hours)": int(task_duration_hours),
            "Task Duration (minutes)": int(task_duration_minutes),
            "Category": task_category
        }
        self.save_task(task_entry)
        st.session_state.tasks.append(task_entry)

    def delete_task_by_id(self, task_id):
        # Delete task by its ID
        query = "DELETE FROM tasks WHERE id = ?;"
        self.conn.execute(query, (task_id,))
        self.conn.commit()
        return True

    def generate_report(self, timeframe):
        df = pd.DataFrame(self.load_tasks())
        if df.empty:
            return pd.DataFrame()

        df['Task Time'] = pd.to_datetime(df['Task Time'])

        if timeframe == 'daily':
            report = df[df['Task Time'].dt.date == pd.Timestamp.today().date()]
        elif timeframe == 'weekly':
            week_start = pd.Timestamp.today() - pd.DateOffset(days=pd.Timestamp.today().dayofweek)
            report = df[(df['Task Time'] >= week_start) & (df['Task Time'] < pd.Timestamp.today() + pd.DateOffset(days=1))]
        elif timeframe == 'monthly':
            report = df[df['Task Time'].dt.month == pd.Timestamp.today().month]
        elif timeframe == 'yearly':
            report = df[df['Task Time'].dt.year == pd.Timestamp.today().year]
        else:
            report = pd.DataFrame()

        report['Total Duration'] = report['Task Duration (hours)'] + report['Task Duration (minutes)'] / 60.0
        return report