ajdt / task_operations.py
shamimjony1000's picture
Upload 7 files
e9739ea verified
# 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