shamimjony1000 commited on
Commit
2315e7a
1 Parent(s): cac4a15

Update task_operations.py

Browse files
Files changed (1) hide show
  1. task_operations.py +66 -73
task_operations.py CHANGED
@@ -1,95 +1,88 @@
1
- import os
 
 
2
  import pandas as pd
3
  from datetime import datetime
4
  import streamlit as st
5
- import uuid # For generating unique IDs
6
- import shutil # To create a backup of the file
7
 
8
  class TaskManager:
9
- TASKS_FILE = "tasks.csv"
10
- BACKUP_FILE = "tasks_backup.csv"
11
  CATEGORIES = ['Learning', 'Gym', 'Personal', 'Family', 'Work', 'Prayer']
12
 
13
  def __init__(self):
14
- if 'tasks' not in st.session_state:
15
- st.session_state.tasks = self.load_tasks()
16
-
17
- def backup_csv(self):
18
- """Create a backup of the current tasks file."""
19
- if os.path.exists(self.TASKS_FILE):
20
- shutil.copy(self.TASKS_FILE, self.BACKUP_FILE)
21
 
22
- def restore_from_backup(self):
23
- """Restore tasks from backup if needed."""
24
- if os.path.exists(self.BACKUP_FILE):
25
- shutil.copy(self.BACKUP_FILE, self.TASKS_FILE)
 
 
 
 
 
 
 
 
 
 
26
 
27
  def load_tasks(self):
28
- # Check if the file exists and has data
29
- if os.path.exists(self.TASKS_FILE) and os.path.getsize(self.TASKS_FILE) > 0:
30
- try:
31
- return pd.read_csv(self.TASKS_FILE, parse_dates=['Task Time']).to_dict(orient='records')
32
- except pd.errors.EmptyDataError:
33
- return [] # Return empty list if CSV is empty
 
 
 
 
 
 
 
 
 
 
 
34
  else:
35
- # If file doesn't exist, initialize it with an empty DataFrame and correct columns
36
- df = pd.DataFrame(columns=["Task ID", "Task Name", "Task Time", "Task Duration (hours)", "Task Duration (minutes)", "Category"])
37
- df.to_csv(self.TASKS_FILE, index=False)
38
- return [] # Return an empty list to the session state
39
 
40
- def save_tasks(self, tasks):
41
- """Save tasks to the CSV file after making a backup."""
42
- if tasks: # Only save if tasks are not empty
43
- # Backup the current file before saving
44
- self.backup_csv()
45
- df = pd.DataFrame(tasks)
46
- df.to_csv(self.TASKS_FILE, index=False)
47
- else:
48
- # Prevent overwriting the file with an empty DataFrame
49
- st.warning("No tasks to save. File write skipped to prevent data loss.")
50
 
51
  def add_task(self, task_name, task_time, task_duration_hours, task_duration_minutes, task_category):
52
- # Ensure valid task details are being added
53
- if task_name and task_category:
54
- task_time_full = datetime.combine(datetime.today(), task_time)
55
- task_id = str(uuid.uuid4()) # Generate a unique ID using uuid4
56
- task_entry = {
57
- "Task ID": task_id,
58
- "Task Name": task_name,
59
- "Task Time": task_time_full,
60
- "Task Duration (hours)": int(task_duration_hours),
61
- "Task Duration (minutes)": int(task_duration_minutes),
62
- "Category": task_category
63
- }
64
- st.session_state.tasks.append(task_entry)
65
- self.save_tasks(st.session_state.tasks)
66
- st.success(f"Task '{task_name}' added successfully!")
67
- # Reload tasks to ensure consistency
68
- st.session_state.tasks = self.load_tasks()
69
- else:
70
- st.error("Task name and category are required.")
71
 
72
  def delete_task_by_id(self, task_id):
73
- task_found = False
74
- for index, task in enumerate(st.session_state.tasks):
75
- if task['Task ID'] == task_id:
76
- st.session_state.tasks.pop(index)
77
- task_found = True
78
- break
79
- if task_found:
80
- self.save_tasks(st.session_state.tasks)
81
- st.success(f"Task with ID '{task_id}' deleted.")
82
- # Reload tasks to ensure consistency
83
- st.session_state.tasks = self.load_tasks()
84
- else:
85
- st.error(f"Task with ID '{task_id}' not found.")
86
 
87
  def generate_report(self, timeframe):
88
- df = pd.DataFrame(st.session_state.tasks)
89
  if df.empty:
90
- return pd.DataFrame() # Return empty DataFrame if no tasks are present
91
-
92
- # Ensure the 'Task Time' is in datetime format
93
  df['Task Time'] = pd.to_datetime(df['Task Time'])
94
 
95
  if timeframe == 'daily':
@@ -102,7 +95,7 @@ class TaskManager:
102
  elif timeframe == 'yearly':
103
  report = df[df['Task Time'].dt.year == pd.Timestamp.today().year]
104
  else:
105
- report = pd.DataFrame() # Empty DataFrame for unsupported timeframes
106
 
107
  report['Total Duration'] = report['Task Duration (hours)'] + report['Task Duration (minutes)'] / 60.0
108
  return report
 
1
+ # components/task_operations.py
2
+
3
+ import sqlite3
4
  import pandas as pd
5
  from datetime import datetime
6
  import streamlit as st
 
 
7
 
8
  class TaskManager:
9
+ DB_FILE = "tasks.db"
 
10
  CATEGORIES = ['Learning', 'Gym', 'Personal', 'Family', 'Work', 'Prayer']
11
 
12
  def __init__(self):
13
+ self.conn = sqlite3.connect(self.DB_FILE)
14
+ self.create_table()
 
 
 
 
 
15
 
16
+ def create_table(self):
17
+ # Create tasks table with unique id
18
+ query = """
19
+ CREATE TABLE IF NOT EXISTS tasks (
20
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
21
+ task_name TEXT,
22
+ task_time TEXT,
23
+ task_duration_hours INTEGER,
24
+ task_duration_minutes INTEGER,
25
+ category TEXT
26
+ );
27
+ """
28
+ self.conn.execute(query)
29
+ self.conn.commit()
30
 
31
  def load_tasks(self):
32
+ # Load tasks from the database
33
+ query = "SELECT * FROM tasks;"
34
+ df = pd.read_sql_query(query, self.conn)
35
+
36
+ if not df.empty:
37
+ # Ensure 'Task Time' is in datetime format and id is an integer
38
+ df['Task Time'] = pd.to_datetime(df['task_time']) # Convert task_time to datetime
39
+ df['id'] = df['id'].astype(int) # Ensure id is an integer
40
+ df = df.rename(columns={
41
+ 'task_name': 'Task Name',
42
+ 'task_time': 'Task Time',
43
+ 'task_duration_hours': 'Task Duration (hours)',
44
+ 'task_duration_minutes': 'Task Duration (minutes)',
45
+ 'category': 'Category',
46
+ 'id': 'Task ID' # Rename id to 'Task ID'
47
+ })
48
+ return df.to_dict(orient='records')
49
  else:
50
+ return []
 
 
 
51
 
52
+ def save_task(self, task):
53
+ # Save task into the database
54
+ query = """
55
+ INSERT INTO tasks (task_name, task_time, task_duration_hours, task_duration_minutes, category)
56
+ VALUES (?, ?, ?, ?, ?);
57
+ """
58
+ self.conn.execute(query, (task['Task Name'], task['Task Time'], task['Task Duration (hours)'],
59
+ task['Task Duration (minutes)'], task['Category']))
60
+ self.conn.commit()
 
61
 
62
  def add_task(self, task_name, task_time, task_duration_hours, task_duration_minutes, task_category):
63
+ task_time_full = datetime.combine(datetime.today(), task_time)
64
+ task_entry = {
65
+ "Task Name": task_name,
66
+ "Task Time": task_time_full,
67
+ "Task Duration (hours)": int(task_duration_hours),
68
+ "Task Duration (minutes)": int(task_duration_minutes),
69
+ "Category": task_category
70
+ }
71
+ self.save_task(task_entry)
72
+ st.session_state.tasks.append(task_entry)
 
 
 
 
 
 
 
 
 
73
 
74
  def delete_task_by_id(self, task_id):
75
+ # Delete task by its ID
76
+ query = "DELETE FROM tasks WHERE id = ?;"
77
+ self.conn.execute(query, (task_id,))
78
+ self.conn.commit()
79
+ return True
 
 
 
 
 
 
 
 
80
 
81
  def generate_report(self, timeframe):
82
+ df = pd.DataFrame(self.load_tasks())
83
  if df.empty:
84
+ return pd.DataFrame()
85
+
 
86
  df['Task Time'] = pd.to_datetime(df['Task Time'])
87
 
88
  if timeframe == 'daily':
 
95
  elif timeframe == 'yearly':
96
  report = df[df['Task Time'].dt.year == pd.Timestamp.today().year]
97
  else:
98
+ report = pd.DataFrame()
99
 
100
  report['Total Duration'] = report['Task Duration (hours)'] + report['Task Duration (minutes)'] / 60.0
101
  return report