Repository navigation
Expand file tree
/
Copy pathbackend.py
More file actions
1003 lines (855 loc) · 43.2 KB
/
Copy pathbackend.py
File metadata and controls
1003 lines (855 loc) · 43.2 KB
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from flask import Flask, request, session, jsonify
from flask_cors import CORS
from user import user_bp
import json
import os
import requests
from werkzeug.utils import secure_filename
from db import get_db_connection, ALLOWED_EXTENSIONS, create_notification
app = Flask(__name__)
app.secret_key = "your_secret_key_here" # TODO: move to env var before shipping
# --- CORS + session cookie config for the React SPA ---
# The Vite dev server runs on a different port (5173) than Flask (5000),
# which browsers treat as a different origin. Cookies won't cross that
# boundary by default, so both sides need explicit config:
CORS(app, supports_credentials=True, origins=["http://localhost:5173"])
app.config.update(
SESSION_COOKIE_SAMESITE="Lax", # "None" + Secure=True only if you move to HTTPS
SESSION_COOKIE_SECURE=False, # set True once you're on HTTPS in production
)
app.register_blueprint(user_bp, url_prefix='/api')
# ══════════════════════════════════════════════════════════════════════════
# GET /dashboard_data — unchanged, was already JSON in the original.
# ══════════════════════════════════════════════════════════════════════════
@app.route('/api/dashboard_data')
def dashboard_data():
if 'user_id' not in session:
return jsonify({'success': False, 'message': 'Unauthorized'}), 401
user_id = session['user_id']
connection = get_db_connection()
cursor = connection.cursor(dictionary=True)
cursor.execute("""
SELECT id, task, description, completed, due_date, importance, related, created_at
FROM tasks WHERE user_id = %s
""", (user_id,))
tasks = cursor.fetchall()
for t in tasks:
cursor.execute("""
SELECT sid, step_description, difficulty, status
FROM steps WHERE fid = %s
""", (t['id'],))
t['steps'] = cursor.fetchall()
t['created_at'] = str(t['created_at'])
if t['due_date']:
t['due_date'] = str(t['due_date'])
cursor.close()
connection.close()
return jsonify({'success': True, 'tasks': tasks})
# ══════════════════════════════════════════════════════════════════════════
# GET /home_data — NEW route replacing the old `index()` page render.
# The old `/` route computed username/profile_pic/prompts/missing_fields
# and handed them to Jinja. React needs the same data via fetch on mount.
# ══════════════════════════════════════════════════════════════════════════
@app.route('/api/home_data')
def home_data():
if 'user_id' not in session:
return jsonify({'success': False, 'message': 'Unauthorized'}), 401
user_id = session['user_id']
connection = get_db_connection()
cursor = connection.cursor()
cursor.execute("SELECT * FROM users WHERE id = %s", (user_id,))
user = cursor.fetchone()
prompts = []
missing_fields = []
if user:
username = user[1]
email = user[2]
profile_pic = user[7]
if email is None:
prompts.append("Verify Email ⚡")
if None in (user[3], user[4], user[5]):
prompts.append("Setup Profile 🛠️")
if user[3] is None: missing_fields.append('position')
if user[4] is None: missing_fields.append('age')
if user[5] is None: missing_fields.append('gender')
if user[7] is None: missing_fields.append('pic')
else:
username = "Unknown"
profile_pic = None
if user:
cursor.execute("SELECT dismissed_prompts FROM users WHERE id = %s", (user_id,))
d_row = cursor.fetchone()
dismissed = json.loads(d_row[0]) if d_row and d_row[0] else []
prompts = [p for p in prompts if not any(p.startswith(d) for d in dismissed)]
cursor.close()
connection.close()
return jsonify({
'success': True,
'username': username,
'profile_pic': profile_pic,
'prompts': prompts,
'missing_fields': missing_fields
})
# ══════════════════════════════════════════════════════════════════════════
# POST /api/dismiss_prompt — permanently dismiss a home-page prompt bubble
# ══════════════════════════════════════════════════════════════════════════
@app.route('/api/dismiss_prompt', methods=['POST'])
def dismiss_prompt():
if 'user_id' not in session:
return jsonify({'success': False, 'message': 'Unauthorized'}), 401
data = request.get_json(silent=True) or {}
prompt_key = data.get('prompt_key')
if not prompt_key:
return jsonify({'success': False, 'message': 'prompt_key is required'}), 400
user_id = session['user_id']
connection = get_db_connection()
cursor = connection.cursor()
try:
cursor.execute("SELECT dismissed_prompts FROM users WHERE id = %s", (user_id,))
row = cursor.fetchone()
dismissed = json.loads(row[0]) if row and row[0] else []
if prompt_key not in dismissed:
dismissed.append(prompt_key)
cursor.execute(
"UPDATE users SET dismissed_prompts = %s WHERE id = %s",
(json.dumps(dismissed), user_id)
)
connection.commit()
return jsonify({'success': True, 'dismissed_prompts': dismissed})
finally:
cursor.close()
connection.close()
# ══════════════════════════════════════════════════════════════════════════
# GET /task_details_data — replaces task_details(). Was: render_template
# with raw tuples + a `table_type` query param that picked a template.
# Now: one JSON payload with everything; React decides what to show.
# The `table` query param is kept (optional) in case you still want the
# API to filter server-side, but it's no longer required for two templates
# to exist — there's only one route now.
# ══════════════════════════════════════════════════════════════════════════
@app.route('/api/task_details_data')
def task_details_data():
if 'user_id' not in session:
return jsonify({'success': False, 'message': 'Unauthorized'}), 401
user_id = session['user_id']
connection = get_db_connection()
cursor = connection.cursor(dictionary=True)
cursor.execute("SELECT username FROM users WHERE id = %s", (user_id,))
user = cursor.fetchone()
username = user['username'] if user else "Unknown"
cursor.execute(
"SELECT id, task, completed, created_at, due_date FROM tasks WHERE user_id = %s",
(user_id,)
)
tasks = cursor.fetchall()
for t in tasks:
t['created_at'] = str(t['created_at'])
if t['due_date']:
t['due_date'] = str(t['due_date'])
cursor.execute(
"SELECT task, completed_at FROM completed_tasks WHERE fid IN (SELECT id FROM tasks WHERE user_id = %s)",
(user_id,)
)
completed_tasks = cursor.fetchall()
for c in completed_tasks:
if c.get('completed_at'):
c['completed_at'] = str(c['completed_at'])
cursor.execute("""
SELECT DISTINCT fid
FROM steps
WHERE status = 0
AND fid IN (SELECT id FROM tasks WHERE user_id = %s)
""", (user_id,))
tasks_with_unfinished_steps = [row['fid'] for row in cursor.fetchall()]
cursor.close()
connection.close()
return jsonify({
'success': True,
'username': username,
'tasks': tasks,
'completed_tasks': completed_tasks,
'tasks_with_unfinished_steps': tasks_with_unfinished_steps
})
# ══════════════════════════════════════════════════════════════════════════
# POST /api/add_task — was: form POST -> redirect('/'). Now: JSON in, JSON out.
# React sends the same field names via FormData (steps[] included), gets
# the new task back so it can update local state without a full refetch.
# ══════════════════════════════════════════════════════════════════════════
@app.route('/api/add_task', methods=['POST'])
def add_task():
if 'user_id' not in session:
return jsonify({'success': False, 'message': 'Unauthorized'}), 401
task = request.form.get('task')
description = request.form.get('description', '')
due_date = request.form.get('due_date')
steps = request.form.getlist('steps[]')
user_id = session['user_id']
importance = request.form.get('importance', 'Medium')
related = request.form.get('related', 'Other')
if not task:
return jsonify({'success': False, 'message': 'Task name is required'}), 400
connection = get_db_connection()
cursor = connection.cursor()
try:
if due_date:
cursor.execute(
"INSERT INTO tasks (task, description, completed, user_id, due_date, importance, related) VALUES (%s, %s, %s, %s, %s, %s, %s)",
(task, description, 0, user_id, due_date, importance, related)
)
else:
cursor.execute(
"INSERT INTO tasks (task, description, completed, user_id, importance, related) VALUES (%s, %s, %s, %s, %s, %s)",
(task, description, 0, user_id, importance, related)
)
task_id = cursor.lastrowid
cursor.execute("SELECT task FROM tasks WHERE id = %s", (task_id,))
task_name = cursor.fetchone()[0]
inserted_steps = []
for step in steps:
step_data = step.split("|")
if len(step_data) == 2:
step_description, difficulty = step_data
cursor.execute(
"INSERT INTO steps (fid, step_description, difficulty, status, task) VALUES (%s, %s, %s, %s, %s)",
(task_id, step_description, difficulty, 0, task_name)
)
inserted_steps.append({
'sid': cursor.lastrowid,
'step_description': step_description,
'difficulty': difficulty,
'status': 0
})
connection.commit()
return jsonify({
'success': True,
'task': {
'id': task_id,
'task': task_name,
'description': description,
'completed': 0,
'due_date': due_date,
'importance': importance,
'related': related,
'steps': inserted_steps
}
})
except Exception as e:
connection.rollback()
return jsonify({'success': False, 'message': str(e)}), 500
finally:
cursor.close()
connection.close()
# ══════════════════════════════════════════════════════════════════════════
# POST /api/complete/<int:task_id> — unchanged, was already JSON.
# ══════════════════════════════════════════════════════════════════════════
@app.route('/api/complete/<int:task_id>', methods=['POST'])
def complete_task(task_id):
if 'user_id' not in session:
return jsonify({'success': False, 'message': 'Unauthorized'}), 401
connection = get_db_connection()
cursor = connection.cursor()
try:
cursor.execute("UPDATE tasks SET completed = 1 WHERE id = %s", (task_id,))
connection.commit()
cursor.execute(
"INSERT INTO completed_tasks (fid, task, completed_at) SELECT id, task, NOW() FROM tasks WHERE id = %s",
(task_id,)
)
connection.commit()
return jsonify({'success': True})
except Exception as e:
connection.rollback()
return jsonify({'success': False, 'message': str(e)}), 500
finally:
cursor.close()
connection.close()
# ══════════════════════════════════════════════════════════════════════════
# GET /api/setup_step_data/<int:fid> — replaces setup_step() page render.
# ══════════════════════════════════════════════════════════════════════════
@app.route('/api/setup_step_data/<int:fid>')
def setup_step_data(fid):
if 'user_id' not in session:
return jsonify({'success': False, 'message': 'Unauthorized'}), 401
connection = get_db_connection()
cursor = connection.cursor(dictionary=True)
try:
cursor.execute("SELECT task FROM tasks WHERE id = %s", (fid,))
row = cursor.fetchone()
if not row:
return jsonify({'success': False, 'message': 'Task not found'}), 404
task_name = row['task']
cursor.execute("SELECT * FROM steps WHERE fid = %s", (fid,))
steps = cursor.fetchall()
return jsonify({'success': True, 'fid': fid, 'task_name': task_name, 'steps': steps})
finally:
cursor.close()
connection.close()
# ══════════════════════════════════════════════════════════════════════════
# POST /add_step/<fid> — was: form POST -> redirect back to setup_step page.
# Now: JSON in/out, returns the created step so React can append it locally.
# ══════════════════════════════════════════════════════════════════════════
@app.route('/api/add_step/<int:fid>', methods=['POST'])
def add_step(fid):
if 'user_id' not in session:
return jsonify({'success': False, 'message': 'Unauthorized'}), 401
step_description = request.form.get('step_description')
difficulty = request.form.get('difficulty')
if not step_description or not difficulty:
return jsonify({'success': False, 'message': 'step_description and difficulty are required'}), 400
connection = get_db_connection()
cursor = connection.cursor()
try:
cursor.execute("SELECT task FROM tasks WHERE id = %s", (fid,))
row = cursor.fetchone()
if not row:
return jsonify({'success': False, 'message': 'Task not found'}), 404
task_name = row[0]
cursor.execute(
"INSERT INTO steps (fid, step_description, difficulty, status, task) VALUES (%s, %s, %s, %s, %s)",
(fid, step_description, difficulty, 0, task_name)
)
connection.commit()
return jsonify({
'success': True,
'step': {
'sid': cursor.lastrowid,
'step_description': step_description,
'difficulty': difficulty,
'status': 0
}
})
except Exception as e:
connection.rollback()
return jsonify({'success': False, 'message': str(e)}), 500
finally:
cursor.close()
connection.close()
# ══════════════════════════════════════════════════════════════════════════
# POST /complete_step/<id> — was: redirect(request.referrer), which doesn't
# make sense at all for an SPA (there's no "referring page" to bounce back
# to). Now: JSON confirmation, React updates its own local state.
# ══════════════════════════════════════════════════════════════════════════
@app.route('/api/complete_step/<int:step_id>', methods=['POST'])
def complete_step(step_id):
if 'user_id' not in session:
return jsonify({'success': False, 'message': 'Unauthorized'}), 401
connection = get_db_connection()
cursor = connection.cursor()
try:
cursor.execute("UPDATE steps SET status = 1 WHERE sid = %s", (step_id,))
connection.commit()
return jsonify({'success': True})
except Exception as e:
connection.rollback()
return jsonify({'success': False, 'message': str(e)}), 500
finally:
cursor.close()
connection.close()
# ══════════════════════════════════════════════════════════════════════════
# GET /api/calendar_tasks — returns every task belonging to the logged-in
# user that HAS a due_date set, for plotting on the Calendar page.
# Steps are intentionally NOT included here (keeps this endpoint light —
# the frontend fetches steps for one task at a time, on click, via the
# existing /api/setup_step_data/<fid>).
# ══════════════════════════════════════════════════════════════════════════
@app.route('/api/calendar_tasks')
def calendar_tasks():
if 'user_id' not in session:
return jsonify({'success': False, 'message': 'Unauthorized'}), 401
user_id = session['user_id']
connection = get_db_connection()
cursor = connection.cursor(dictionary=True)
try:
cursor.execute(
"""SELECT id, task, description, completed, due_date, importance, related
FROM tasks
WHERE user_id = %s AND due_date IS NOT NULL
ORDER BY due_date ASC""",
(user_id,)
)
tasks = cursor.fetchall()
# due_date comes back as a datetime.date from the driver — make it
# JSON-safe and predictable for the frontend (YYYY-MM-DD, matches
# what <input type="date"> / the calendar grid keys expect).
for t in tasks:
if t.get('due_date') is not None:
t['due_date'] = t['due_date'].isoformat()
return jsonify({'success': True, 'tasks': tasks})
finally:
cursor.close()
connection.close()
@app.route('/api/calendar_meetings')
def calendar_meetings():
if 'user_id' not in session:
return jsonify({'success': False, 'message': 'Unauthorized'}), 401
user_id = session['user_id']
connection = get_db_connection()
cursor = connection.cursor(dictionary=True)
try:
cursor.execute(
"""SELECT id, title, description, location_type, location_text,
location_lat, location_lng, meeting_link, start_time,
end_time, importance, related, status, project_meeting
FROM meetings
WHERE user_id = %s
ORDER BY start_time ASC""",
(user_id,)
)
meetings = cursor.fetchall()
# start_time / end_time come back as datetime from the driver —
# stringify for JSON, and derive a plain YYYY-MM-DD date_key so the
# frontend can bucket meetings the same way it buckets tasks
# (by due_date), keyed off the meeting's start date.
for m in meetings:
start = m.get('start_time')
if start is not None:
m['date_key'] = start.date().isoformat() if hasattr(start, 'date') else str(start)[:10]
m['start_time'] = str(start)
else:
m['date_key'] = None
if m.get('end_time') is not None:
m['end_time'] = str(m['end_time'])
m['project_meeting'] = bool(m['project_meeting'])
return jsonify({'success': True, 'meetings': meetings})
finally:
cursor.close()
connection.close()
# ══════════════════════════════════════════════════════════════════════════
# Geocoding helper — turns a free-text address into (lat, lng) using
# OpenStreetMap's Nominatim, no API key required. Called once per meeting
# save; result is cached in the row so the map never re-geocodes on read.
# ══════════════════════════════════════════════════════════════════════════
def geocode_address(address):
if not address:
return None, None
try:
resp = requests.get(
"https://nominatim.openstreetmap.org/search",
params={"q": address, "format": "json", "limit": 1},
headers={"User-Agent": "TodoListDashboard/1.0"},
timeout=5
)
print("Nominatim status:", resp.status_code) # TEMP DEBUG
print("Nominatim response:", resp.text[:300]) # TEMP DEBUG
results = resp.json()
if results:
return float(results[0]["lat"]), float(results[0]["lon"])
except Exception as e:
print("Geocode error:", e) # TEMP DEBUG
return None, None
# ══════════════════════════════════════════════════════════════════════════
# POST /api/add_meeting — mirrors /api/add_task. Accepts FormData, geocodes
# the address server-side if physical/hybrid, inserts meeting + agenda
# items, returns the created meeting as JSON.
# ══════════════════════════════════════════════════════════════════════════
@app.route('/api/add_meeting', methods=['POST'])
def add_meeting():
if 'user_id' not in session:
return jsonify({'success': False, 'message': 'Unauthorized'}), 401
user_id = session['user_id']
title = request.form.get('title', '').strip()
description = request.form.get('description', '').strip()
location_type = request.form.get('location_type', 'physical')
location_text = request.form.get('location_text', '').strip() or None
meeting_link = request.form.get('meeting_link', '').strip() or None
start_time = request.form.get('start_time')
end_time = request.form.get('end_time') or None
importance = request.form.get('importance', 'Medium')
related = request.form.get('related', 'Other')
project_meeting = request.form.get('project_meeting', 'false').lower() == 'true'
if not title:
return jsonify({'success': False, 'message': 'Title is required'}), 400
if not start_time:
return jsonify({'success': False, 'message': 'Start time is required'}), 400
# Geocode only when there's an actual address to resolve
lat, lng = (None, None)
if location_type in ('physical', 'hybrid') and location_text:
lat, lng = geocode_address(location_text)
# agenda_items[] arrive as "description|duration|presenter" strings,
# same encoding convention as steps[] in /add_task
raw_items = request.form.getlist('agenda_items[]')
connection = get_db_connection()
cursor = connection.cursor(dictionary=True)
try:
cursor.execute("""
INSERT INTO meetings
(user_id, title, description, location_type, location_text,
location_lat, location_lng, meeting_link, start_time, end_time,
importance, related, project_meeting)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
""", (
user_id, title, description, location_type, location_text,
lat, lng, meeting_link, start_time, end_time,
importance, related, project_meeting
))
meeting_id = cursor.lastrowid
agenda_items = []
for idx, raw in enumerate(raw_items):
parts = raw.split('|')
desc = parts[0] if len(parts) > 0 else ''
duration = parts[1] if len(parts) > 1 and parts[1] else None
presenter = parts[2] if len(parts) > 2 and parts[2] else None
if not desc.strip():
continue
cursor.execute("""
INSERT INTO meeting_agenda_items
(meeting_id, order_index, description, duration_minutes, presenter)
VALUES (%s, %s, %s, %s, %s)
""", (meeting_id, idx, desc.strip(), duration, presenter))
agenda_items.append({
'order_index': idx, 'description': desc.strip(),
'duration_minutes': duration, 'presenter': presenter
})
connection.commit()
return jsonify({
'success': True,
'meeting': {
'id': meeting_id,
'title': title,
'description': description,
'location_type': location_type,
'location_text': location_text,
'location_lat': lat,
'location_lng': lng,
'meeting_link': meeting_link,
'start_time': start_time,
'end_time': end_time,
'importance': importance,
'related': related,
'project_meeting': project_meeting,
'status': 'scheduled',
'agenda_items': agenda_items
}
})
except Exception as e:
connection.rollback()
return jsonify({'success': False, 'message': str(e)}), 500
finally:
cursor.close()
connection.close()
# ══════════════════════════════════════════════════════════════════════════
# GET /api/meetings_data — mirrors dashboard_data's task fetch, but for
# meetings + their agenda items.
# ══════════════════════════════════════════════════════════════════════════
@app.route('/api/meetings_data')
def meetings_data():
if 'user_id' not in session:
return jsonify({'success': False, 'message': 'Unauthorized'}), 401
user_id = session['user_id']
connection = get_db_connection()
cursor = connection.cursor(dictionary=True)
cursor.execute("""
SELECT id, title, description, location_type, location_text,
location_lat, location_lng, meeting_link, start_time, end_time,
importance, related, status, project_meeting, created_at
FROM meetings WHERE user_id = %s
ORDER BY start_time ASC
""", (user_id,))
meetings = cursor.fetchall()
for m in meetings:
cursor.execute("""
SELECT id, order_index, description, duration_minutes, presenter
FROM meeting_agenda_items WHERE meeting_id = %s
ORDER BY order_index ASC
""", (m['id'],))
m['agenda_items'] = cursor.fetchall()
m['created_at'] = str(m['created_at'])
m['start_time'] = str(m['start_time'])
if m['end_time']:
m['end_time'] = str(m['end_time'])
m['project_meeting'] = bool(m['project_meeting'])
cursor.close()
connection.close()
return jsonify({'success': True, 'meetings': meetings})
# ══════════════════════════════════════════════════════════════════════════
# POST /api/meetings/<id>/status — mark a meeting completed or cancelled
# ══════════════════════════════════════════════════════════════════════════
@app.route('/api/meetings/<int:meeting_id>/status', methods=['POST'])
def update_meeting_status(meeting_id):
if 'user_id' not in session:
return jsonify({'success': False, 'message': 'Unauthorized'}), 401
data = request.get_json(silent=True) or {}
new_status = data.get('status')
if new_status not in ('scheduled', 'completed', 'cancelled'):
return jsonify({'success': False, 'message': 'Invalid status'}), 400
connection = get_db_connection()
cursor = connection.cursor()
try:
cursor.execute(
"UPDATE meetings SET status = %s WHERE id = %s AND user_id = %s",
(new_status, meeting_id, session['user_id'])
)
connection.commit()
return jsonify({'success': True, 'status': new_status})
finally:
cursor.close()
connection.close()
# ══════════════════════════════════════════════════════════════════════════
# GET /feedback/<task_id> — was: render_template, and returned a raw HTML
# error string ("Error: ...", 400) on failure. Now: JSON both paths.
# ══════════════════════════════════════════════════════════════════════════
@app.route('/api/feedback/<int:task_id>')
def feedback(task_id):
if 'user_id' not in session:
return jsonify({'success': False, 'message': 'Unauthorized'}), 401
connection = get_db_connection()
cursor = connection.cursor()
try:
cursor.execute("SELECT created_at FROM tasks WHERE id = %s", (task_id,))
result = cursor.fetchone()
created_at = result[0] if result else None
cursor.execute("SELECT completed_at FROM completed_tasks WHERE fid = %s", (task_id,))
result = cursor.fetchone()
completed_at = result[0] if result else None
if not created_at or not completed_at:
return jsonify({'success': False, 'message': 'Missing timestamps for this task.'}), 400
time_difference = (completed_at - created_at).total_seconds() / 3600
if time_difference < 2:
rating, icon = "Excellent", "✅"
elif time_difference < 6:
rating, icon = "Good", "👍"
elif time_difference < 24:
rating, icon = "Normal", "😐"
else:
rating, icon = "Need Work", "⚠️"
return jsonify({
'success': True,
'rating': rating,
'icon': icon,
'created_at': str(created_at),
'completed_at': str(completed_at),
'time_difference': round(time_difference, 2)
})
finally:
cursor.close()
connection.close()
# ══════════════════════════════════════════════════════════════════════════
# POST /save_profile_setup — unchanged, was already JSON.
# ══════════════════════════════════════════════════════════════════════════
@app.route('/api/save_profile_setup', methods=['POST'])
def save_profile_setup():
if 'user_id' not in session:
return jsonify({'success': False, 'message': 'Unauthorized'}), 401
user_id = session['user_id']
position = request.form.get('position') or None
age_raw = request.form.get('age') or None
gender = request.form.get('gender') or None
pic_file = request.files.get('profile_pic')
age = None
if age_raw:
try:
age = int(age_raw)
except ValueError:
return jsonify({'success': False, 'message': 'Invalid age value'}), 400
connection = get_db_connection()
cursor = connection.cursor()
try:
updates = []
params = []
if position is not None:
updates.append("position = %s")
params.append(position)
if age is not None:
updates.append("age = %s")
params.append(age)
if gender is not None:
updates.append("gender = %s")
params.append(gender)
if pic_file and pic_file.filename:
ext = pic_file.filename.rsplit('.', 1)[-1].lower() if '.' in pic_file.filename else ''
if ext in ALLOWED_EXTENSIONS:
upload_folder = 'static/uploads/profile_pics'
os.makedirs(upload_folder, exist_ok=True)
filename = secure_filename(pic_file.filename)
unique_name = f"{user_id}_setup_{filename}"
pic_file.save(os.path.join(upload_folder, unique_name))
db_path = f"uploads/profile_pics/{unique_name}"
updates.append("profile_pic = %s")
params.append(db_path)
if updates:
sql = f"UPDATE users SET {', '.join(updates)} WHERE id = %s"
params.append(user_id)
cursor.execute(sql, tuple(params))
connection.commit()
return jsonify({'success': True})
except Exception as e:
connection.rollback()
return jsonify({'success': False, 'message': str(e)}), 500
finally:
cursor.close()
connection.close()
def save_upload(file, subfolder, prefix):
"""Helper: saves an uploaded file, returns the db-ready relative path or None."""
if not file or not file.filename:
return None
ext = file.filename.rsplit('.', 1)[-1].lower() if '.' in file.filename else ''
if ext not in ALLOWED_EXTENSIONS:
return None
folder = os.path.join('static', 'uploads', subfolder)
os.makedirs(folder, exist_ok=True)
filename = secure_filename(file.filename)
unique_name = f"{prefix}_{filename}"
file.save(os.path.join(folder, unique_name))
return f"uploads/{subfolder}/{unique_name}"
@app.route('/api/search_user_by_email')
def search_user_by_email():
if 'user_id' not in session:
return jsonify({'success': False, 'message': 'Unauthorized'}), 401
email = request.args.get('email', '').strip()
if not email:
return jsonify({'success': False, 'message': 'Email is required'}), 400
connection = get_db_connection()
cursor = connection.cursor()
try:
cursor.execute(
"SELECT id, username, email, profile_pic, position FROM users WHERE email = %s",
(email,)
)
user = cursor.fetchone()
if not user:
return jsonify({'success': False, 'message': 'User not found'}), 404
return jsonify({
'success': True,
'user': {
'id': user[0],
'username': user[1],
'email': user[2],
'profile_pic': user[3],
'position': user[4]
}
})
finally:
cursor.close()
connection.close()
# ══════════════════════════════════════════════════════════════════════════
# GET /api/notifications — list the logged-in user's notifications
# ══════════════════════════════════════════════════════════════════════════
@app.route('/api/notifications')
def get_notifications():
if 'user_id' not in session:
return jsonify({'success': False, 'message': 'Unauthorized'}), 401
connection = get_db_connection()
cursor = connection.cursor(dictionary=True)
try:
cursor.execute("""
SELECT id, type, title, message, related_id, is_read, created_at
FROM notifications
WHERE user_id = %s
ORDER BY created_at DESC
LIMIT 100
""", (session['user_id'],))
rows = cursor.fetchall()
for r in rows:
r['created_at'] = str(r['created_at'])
r['is_read'] = bool(r['is_read'])
cursor.execute(
"SELECT COUNT(*) AS n FROM notifications WHERE user_id = %s AND is_read = 0",
(session['user_id'],)
)
unread = cursor.fetchone()['n']
return jsonify({'success': True, 'notifications': rows, 'unread_count': unread})
finally:
cursor.close()
connection.close()
# ══════════════════════════════════════════════════════════════════════════
# POST /api/mark_notification_read/<id>
# ══════════════════════════════════════════════════════════════════════════
@app.route('/api/mark_notification_read/<int:notification_id>', methods=['POST'])
def mark_notification_read(notification_id):
if 'user_id' not in session:
return jsonify({'success': False, 'message': 'Unauthorized'}), 401
connection = get_db_connection()
cursor = connection.cursor()
try:
cursor.execute(
"UPDATE notifications SET is_read = 1 WHERE id = %s AND user_id = %s",
(notification_id, session['user_id'])
)
connection.commit()
return jsonify({'success': True})
finally:
cursor.close()
connection.close()
# ══════════════════════════════════════════════════════════════════════════
# POST /api/mark_all_notifications_read
# ══════════════════════════════════════════════════════════════════════════
@app.route('/api/mark_all_notifications_read', methods=['POST'])
def mark_all_notifications_read():
if 'user_id' not in session:
return jsonify({'success': False, 'message': 'Unauthorized'}), 401
connection = get_db_connection()
cursor = connection.cursor()
try:
cursor.execute(
"UPDATE notifications SET is_read = 1 WHERE user_id = %s",
(session['user_id'],)
)
connection.commit()
return jsonify({'success': True})
finally:
cursor.close()
connection.close()
# ══════════════════════════════════════════════════════════════════════════
# POST /api/generate_due_notifications
# Call this from a cron job / scheduler (once every few hours is fine).
# It scans tasks due within the next 24h and creates one notification per
# (user, task) pair — deduped so it doesn't spam on every run.
# ══════════════════════════════════════════════════════════════════════════
@app.route('/api/generate_due_notifications', methods=['POST'])
def generate_due_notifications():
connection = get_db_connection()
cursor = connection.cursor(dictionary=True)
try:
# Tasks due within the next 24 hours, not completed
cursor.execute("""
SELECT id, user_id, task, due_date
FROM tasks
WHERE completed = 0
AND due_date IS NOT NULL
AND due_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 1 DAY)
""")
due_tasks = cursor.fetchall()
created = 0
for t in due_tasks:
# Dedup: one 'task_due_soon' notification per task, ever
cursor.execute("""
SELECT id FROM notifications
WHERE user_id = %s AND type = 'task_due_soon' AND related_id = %s
LIMIT 1
""", (t['user_id'], t['id']))
if cursor.fetchone():
continue
create_notification(
cursor,
t['user_id'],
'task_due_soon',
"Task Due Soon",
f"Your task \"{t['task']}\" is due on {t['due_date']}.",
t['id']
)
created += 1
connection.commit()
return jsonify({'success': True, 'created': created})
except Exception as e:
connection.rollback()
return jsonify({'success': False, 'message': str(e)}), 500
finally:
cursor.close()
connection.close()
# ══════════════════════════════════════════════════════════════════════════
# ── ROUTE MAP CHANGELOG (old -> new) ─────────────────────────────────────
# GET / -> GET /home_data
# GET /task_details -> GET /task_details_data (table_type param dropped)
# GET /setup_step/<fid> -> GET /setup_step_data/<fid>
# GET /project_setup -> GET /project_setup_page (now near-vestigial)
# GET /notifications_page -> GET /notifications_page_data
# POST /add_task -> same URL, JSON response instead of redirect
# POST /add_step/<fid> -> same URL, JSON response instead of redirect
# POST /complete_step/<id> -> same URL, JSON response instead of referrer redirect
# GET /feedback/<id> -> same URL, JSON response instead of HTML/template
# Everything else -> unchanged URL, was already JSON
#
# NEW: GET /me (user.py) -> session check for the SPA on page load
# ══════════════════════════════════════════════════════════════════════════