-
Notifications
You must be signed in to change notification settings - Fork 0
/
S_06_user_initial_calendar_file_generation.py
196 lines (146 loc) · 6.58 KB
/
S_06_user_initial_calendar_file_generation.py
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
from datetime import date, datetime, timedelta
import re
import os
import json
import sqlite3
from currentUser import user_id
from config import db_path, feedback_questions, current_date_str, current_date
# Retrieve calendar information from the database for a given user
def retrieve_cal_info_from_db():
# Assuming this function fetches required data from the DB and returns a list of dictionaries
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
# Sample SQL to fetch calendar information - adjust as needed
cursor.execute("""
SELECT users.habit, users.username, users.habit_start_date, habit_cal.*
FROM users
JOIN habit_cal ON users.id = habit_cal.user_id
WHERE users.id = ?
AND (habit_cal.week_begins_on >= DATE('now') OR habit_cal.week_begins_on IS NULL);
""",
(user_id,))
# Fetch column names for dictionary keys
columns = [description[0] for description in cursor.description]
# Fetch all results and store them in a list of dictionaries
results = cursor.fetchall()
data_list = []
for row in results:
# Create a dictionary for each row
row_dict = dict(zip(columns, row))
data_list.append(row_dict)
# print(f'The row dict is: {row_dict}')
# # Print the list of dictionaries
# for item in data_list:
# print(f'The items in data_list are: {item}')
# # print(f'The data list is: {data_list}')
return data_list
# Checks and sets the start date if it’s missing
def add_start_date_if_missing(user_info):
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
first_week_starts_on_str = user_info.get('habit_start_date')
print(f"first_week_starts_on_str is called: {first_week_starts_on_str}")
if first_week_starts_on_str is not None:
first_week_starts_on = datetime.strptime(first_week_starts_on_str, '%Y-%m-%d')
if not user_info.get('habit_start_date'):
start_date = (current_date + timedelta(days=1)).strftime('%Y-%m-%d')
cursor.execute("""
UPDATE users
SET habit_start_date = ?
WHERE id = ?
""",
(start_date, user_id))
conn.commit()
first_week_starts_on = datetime.strptime(start_date, '%Y-%m-%d')
print(f'Added {first_week_starts_on} as habit start date into table.')
conn.close()
return first_week_starts_on
# Creates a single event dictionary for a given day
def create_event_for_day(week, day, first_week_starts_on, day_for_event):
day +=1
day_key = f"day_{day:02d}" # Format the day counter to be two digits
summary = week.get(f'{day_key}_summary')
description = week.get(f'{day_key}_description')
motivation = week.get(f'{day_key}_motivation')
duration = week.get(f'{day_key}_duration', 60)
first_week_starts_on = first_week_starts_on.date()
if not summary:
return None # Skip if no summary is provided
combined_description = f"{description}\n\n{motivation}\n\n{feedback_questions}"
if duration == 0:
combined_description = f"{description}\n\n{motivation}"
event_date = first_week_starts_on + timedelta(days=day_for_event)
start_datetime = datetime.combine(event_date, datetime.min.time()).replace(hour=9, minute=0, second=0)
end_datetime = start_datetime + timedelta(minutes=duration)
event = {
'summary': summary,
'description': combined_description,
'start': {
'dateTime': start_datetime.isoformat(),
'timeZone': 'Europe/Berlin'
},
'end': {
'dateTime': end_datetime.isoformat(),
'timeZone': 'Europe/Berlin'
},
'reminders': {
'useDefault': True
},
'eventType': 'default'
}
return event
# Generates the event list for each day from calendar dictionary data
def generate_event_list(cal_dict_list, first_week_starts_on):
event_list = []
# Open database connection
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
for week in cal_dict_list:
week_num = week['week']
# Check if week was already put into calendar
if week.get('week_begins_on'):
# If week_begins_on is not empty, skip this week and continue to the next
print(f"Week {week['week']} was already put into a gcal json. Will skip this week.")
continue
for day in range(0, 7):
day_for_event = day + (week_num - 1) * 7
event = create_event_for_day(week, day, first_week_starts_on, day_for_event)
# Adds timestamp to db when the week begins
if day == 1:
# first_week_starts_on = datetime.strptime(first_week_starts_on, '%Y-%m-%d').date()
date_to_add_here = first_week_starts_on + timedelta(days=day_for_event)
cursor.execute("""
UPDATE habit_cal SET week_begins_on = ?
WHERE week = ? AND user_id = ?
""",
(date_to_add_here, week_num, user_id))
conn.commit() # Commit each update
if event:
event_list.append(event)
conn.close()
return event_list
# Define the filename with the current date
filename = f"data/outputs/calendar/{user_id}_created_{current_date_str}.json"
def convert_cal_info_into_gcal_json(cal_dict_list):
today = current_date
default_activity_time = 9 # Set activity start time (9 AM UTC+1)
# Set metadata and file path for the JSON file
first_dict = cal_dict_list[0]
print(f"The username is: {first_dict['username']} and the user_id is {first_dict['user_id']}")
username = first_dict['username']
user_id = first_dict['user_id']
file_path = filename
first_week_starts_on = add_start_date_if_missing(first_dict)
event_list = generate_event_list(cal_dict_list, first_week_starts_on)
with open(file_path, 'w') as json_file:
json.dump(event_list, json_file, indent=4)
return file_path, username
# Main function to convert and save the calendar data as JSON
def create_calendar_for_user():
print('Wohoo made it to notebook S_06.')
data = retrieve_cal_info_from_db()
# print(f"Retrieved data for user {user_id}: {data[0]}")
file_path = convert_cal_info_into_gcal_json(data)
print(f"The calendar file for User_{user_id} was created successfully at {file_path}.")
if __name__ == "__main__":
create_calendar_for_user()