Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
4417 lines (3997 loc) · 201 KB
/
Copy pathapp.py
File metadata and controls
4417 lines (3997 loc) · 201 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
#!/usr/bin/env python3
"""Browser-based task manager for research Google Sheet."""
import time
import datetime
import threading
import webbrowser
import json
import os
import re
import sys
import shlex
import subprocess
import pathlib
import shutil
from flask import Flask, jsonify, request, render_template_string
try:
from google.oauth2.service_account import Credentials
import gspread
_GSPREAD_AVAILABLE = True
except ImportError:
_GSPREAD_AVAILABLE = False
try:
from config import SHEET_ID, CREDS_FILE
except (ImportError, AttributeError):
import os
SHEET_ID = os.environ.get("SHEET_ID", "")
CREDS_FILE = os.environ.get("CREDS_FILE", "service_account.json")
TASK_HEADERS = ["Deadline", "Task", "Hours", "Status", "Completed Date", "Assignee"]
_DATA_DIR = pathlib.Path.home() / ".research-tasks"
_DATA_DIR.mkdir(exist_ok=True)
LOCAL_DATA_FILE = str(_DATA_DIR / "local_data.json")
# One-time migration: move old in-folder local_data.json to the user data dir
_OLD_LOCAL = pathlib.Path("local_data.json")
if _OLD_LOCAL.exists() and not pathlib.Path(LOCAL_DATA_FILE).exists():
shutil.move(str(_OLD_LOCAL), LOCAL_DATA_FILE)
# REMOTE_ENABLED: a Google Sheet is configured AND gspread is importable, so we
# can mirror to Sheets. When True the app runs in DUAL mode (local mirror is the
# read/source of truth; every edit is also written to Sheets live, or journalled
# to a pending queue and replayed when the connection returns). When False the
# app is pure-local (LOCAL_MODE) exactly as before.
REMOTE_ENABLED = bool(SHEET_ID) and _GSPREAD_AVAILABLE
LOCAL_MODE = not REMOTE_ENABLED
SCOPES = ["https://www.googleapis.com/auth/spreadsheets"]
STATUSES = ["Not Started", "In Progress", "Pending", "Completed"]
ACTIVE_STATUSES = {"Not Started", "In Progress", "Pending"}
DATA_CACHE_TTL = float('inf') # never auto-expire; use /api/sync to force refresh
SYNC_INTERVAL = 20 # seconds between background attempts to drain the pending queue
NOTES_SHEET = "_notes"
COLLABS_SHEET = "_collabs"
LIT_SHEET = "_literature"
PLAN_SHEET = "_plan"
META_SHEETS = {NOTES_SHEET, COLLABS_SHEET, LIT_SHEET, PLAN_SHEET}
NOTE_COLORS = ["#FFF9C4", "#C8E6C9", "#BBDEFB", "#F8BBD0", "#E1BEE7", "#FFE0B2"]
IMPORTANCES = ["High", "Medium", "Low"]
PURPOSES = ["Design", "Writing", "Analysis", "Planning", "Other"]
NOTE_HEADERS = ["Project", "Note", "Importance", "Purpose", "Color", "Created", "Modified"]
COLLAB_HEADERS = ["Project", "Name", "Role"]
LIT_HEADERS = ["Project", "Title", "Link", "Authors", "Year", "Notes", "Created", "Modified", "Read"]
PLAN_HEADERS = ["Project", "TaskRow", "Day", "Order", "Hours", "Created", "Modified"]
app = Flask(__name__)
_sheet_cache = None
_fetch_lock = threading.Lock()
_sync_lock = threading.RLock() # guards _pending_ops + remote writes
_ws_cache = {} # {title: _LocalWS/_DualWS} — write handles returned to routes
_remote_ws_cache = {} # {title: gspread Worksheet} — real remote handles (dual mode)
_data_cache = {} # {title: [rows]} — project sheets only
_notes_cache = [] # rows from _notes sheet
_collabs_cache= [] # rows from _collabs sheet
_lit_cache = [] # rows from _literature sheet
_plan_cache = [] # rows from _plan sheet
_data_cache_ts= 0.0
# Offline journal + sync state (dual mode only)
_pending_ops = [] # ordered list of {kind, title, ...} not yet applied to Sheets
_online = True # last known reachability of Google Sheets
_last_synced = None # ISO timestamp of the last successful full drain
_sync_thread_started = False
# ── Local storage shim ────────────────────────────────────────────────────
# The in-memory caches are the single source of truth for reads. _LocalWS makes
# a mutation route write to those caches + the on-disk mirror using the same
# ws.update()/append_row()/delete_rows() calls it would make against gspread.
def _meta_cache_for(title):
"""Return the module-level cache list for a meta sheet, or None for a project sheet."""
if title == NOTES_SHEET: return _notes_cache
if title == COLLABS_SHEET: return _collabs_cache
if title == LIT_SHEET: return _lit_cache
if title == PLAN_SHEET: return _plan_cache
return None
class _LocalWS:
"""Mimics a gspread Worksheet so mutation routes work unchanged with no network."""
def __init__(self, title, is_notes=False, is_collabs=False, is_lit=False, is_plan=False):
self.title = title
self._notes = is_notes
self._collabs = is_collabs
self._lit = is_lit
self._plan = is_plan
def _row_num(self, range_name):
m = re.search(r'\d+', range_name)
return int(m.group()) if m else 1
def _meta_list(self):
return _meta_cache_for(self.title)
def update(self, range_name, values):
row = self._row_num(range_name)
target = self._meta_list()
if target is not None:
while len(target) < row: target.append([])
target[row - 1] = list(values[0])
else:
patch_cache(self.title, row, values[0])
_local_save()
def append_row(self, values):
target = self._meta_list()
if target is not None:
target.append(list(values))
else:
_data_cache.setdefault(self.title, []).append(list(values))
_local_save()
def delete_rows(self, row):
target = self._meta_list()
if target is None:
target = _data_cache.get(self.title, [])
if 0 < row <= len(target):
target.pop(row - 1)
_local_save()
class _DualWS(_LocalWS):
"""Dual mode: apply the mutation to the local mirror (via _LocalWS) AND mirror
it to Google Sheets — immediately when online, or onto the pending journal when
offline. Reads never come from here; they come from the caches _LocalWS fills."""
def update(self, range_name, values):
super().update(range_name, values)
_enqueue_or_apply({"kind": "update", "title": self.title,
"range": range_name, "values": values})
def append_row(self, values):
super().append_row(values)
_enqueue_or_apply({"kind": "append", "title": self.title, "values": list(values)})
def delete_rows(self, row):
super().delete_rows(row)
_enqueue_or_apply({"kind": "delete", "title": self.title, "row": row})
def _now_iso():
return datetime.datetime.now().isoformat(timespec="seconds")
MIRROR_SCHEMA = 2 # bump when the mirror layout changes; v1 predates dual/offline mode
_loaded_schema = 0 # schema of the mirror last read by _local_load()
def _local_load():
"""Populate caches (and the pending journal) from the on-disk mirror.
Returns True if the mirror existed and held any data."""
global _data_cache, _notes_cache, _collabs_cache, _lit_cache, _plan_cache
global _pending_ops, _last_synced, _loaded_schema
_loaded_schema = 0
if not os.path.exists(LOCAL_DATA_FILE):
return False
with open(LOCAL_DATA_FILE) as f:
d = json.load(f)
_data_cache = d.get("projects", {})
_notes_cache = d.get("notes", [])
_collabs_cache = d.get("collabs", [])
_lit_cache = d.get("literature", [])
_plan_cache = d.get("plan", [])
_pending_ops = d.get("pending", [])
_last_synced = d.get("last_synced")
_loaded_schema = d.get("schema", 1) # files written before this feature have no schema key
return bool(_data_cache or _notes_cache or _collabs_cache or _lit_cache or _plan_cache)
def _local_save():
"""Atomically persist all caches + the pending journal to the mirror file.
Uses a per-thread temp name so a concurrent writer (e.g. the sync daemon) can't
clobber our temp file; os.replace makes the final swap atomic, last write wins."""
tmp = f"{LOCAL_DATA_FILE}.{os.getpid()}.{threading.get_ident()}.tmp"
with open(tmp, "w") as f:
json.dump({"schema": MIRROR_SCHEMA,
"projects": _data_cache, "notes": _notes_cache,
"collabs": _collabs_cache, "literature": _lit_cache,
"plan": _plan_cache, "pending": _pending_ops,
"last_synced": _last_synced}, f, indent=2)
os.replace(tmp, LOCAL_DATA_FILE) # atomic: a crash mid-write can't corrupt the mirror
# ── Google Sheets helpers ─────────────────────────────────────────────────
def get_sheet():
global _sheet_cache
if _sheet_cache is None:
creds = Credentials.from_service_account_file(CREDS_FILE, scopes=SCOPES)
gc = gspread.authorize(creds)
_sheet_cache = gc.open_by_key(SHEET_ID)
return _sheet_cache
def _headers_for(title):
return {NOTES_SHEET: NOTE_HEADERS, COLLABS_SHEET: COLLAB_HEADERS,
LIT_SHEET: LIT_HEADERS, PLAN_SHEET: PLAN_HEADERS}.get(title, TASK_HEADERS)
def _remote_ws(title):
"""Real gspread worksheet for `title`, creating the tab (with headers) if missing."""
if title in _remote_ws_cache:
return _remote_ws_cache[title]
sh = get_sheet()
try:
ws = sh.worksheet(title)
except gspread.exceptions.WorksheetNotFound:
headers = _headers_for(title)
ws = sh.add_worksheet(title=title, rows=1000, cols=max(10, len(headers)))
ws.update(range_name="A1", values=[headers])
_remote_ws_cache[title] = ws
return ws
def _apply_remote_op(op):
"""Perform one journalled op against Google Sheets. Raises on failure."""
kind = op["kind"]
if kind == "update":
_remote_ws(op["title"]).update(range_name=op["range"], values=op["values"])
elif kind == "append":
_remote_ws(op["title"]).append_row(op["values"])
elif kind == "delete":
_remote_ws(op["title"]).delete_rows(op["row"])
elif kind == "create_sheet":
_remote_ws(op["title"]) # creation (with headers) is the whole operation
elif kind == "delete_sheet":
sh = get_sheet()
try:
sh.del_worksheet(sh.worksheet(op["title"]))
except gspread.exceptions.WorksheetNotFound:
pass
_remote_ws_cache.pop(op["title"], None)
def _mark_online(v):
global _online
_online = v
def _enqueue_or_apply(op):
"""Mirror one op to Sheets now if we're caught up and online; else journal it."""
if not REMOTE_ENABLED:
return
with _sync_lock:
if _pending_ops: # already behind — preserve strict ordering
_pending_ops.append(op)
_local_save()
return
try:
_apply_remote_op(op)
_mark_online(True)
except Exception as e: # noqa: BLE001 — any failure means "not now", never lose the edit
_pending_ops.append(op)
_local_save()
_mark_online(False)
print(f"[sync] queued {op.get('kind')} on {op.get('title')} ({e.__class__.__name__})", file=sys.stderr)
def _drain_pending():
"""Replay the journal to Sheets in order. Stops at the first failure, keeping the rest queued."""
global _last_synced
if not REMOTE_ENABLED:
return
with _sync_lock:
if not _pending_ops:
return
while _pending_ops:
op = _pending_ops[0]
try:
_apply_remote_op(op)
except Exception as e: # noqa: BLE001 — still offline / transient; try again later
_mark_online(False)
print(f"[sync] drain paused: {e.__class__.__name__}", file=sys.stderr)
return
_pending_ops.pop(0)
_local_save()
_mark_online(True)
_last_synced = _now_iso()
_local_save()
def _try_pull_from_remote():
"""One-time seed: pull every tab from Sheets into the caches + mirror.
Used only when the local mirror is empty (first run / fresh machine)."""
global _data_cache, _notes_cache, _collabs_cache, _lit_cache, _plan_cache
for attempt in range(5):
try:
sh = get_sheet()
worksheets = sh.worksheets()
_remote_ws_cache.clear()
_remote_ws_cache.update({ws.title: ws for ws in worksheets})
raw = {ws.title: ws.get_all_values() for ws in worksheets}
_data_cache = {k: v for k, v in raw.items() if k not in META_SHEETS}
_notes_cache = raw.get(NOTES_SHEET, [])
_collabs_cache = raw.get(COLLABS_SHEET, [])
_lit_cache = raw.get(LIT_SHEET, [])
_plan_cache = raw.get(PLAN_SHEET, [])
_mark_online(True)
_local_save()
return True
except gspread.exceptions.APIError as e:
if getattr(e, "response", None) is not None and e.response.status_code == 429 and attempt < 4:
time.sleep(2 ** attempt)
else:
_mark_online(False)
return False
except Exception: # noqa: BLE001 — offline first run
_mark_online(False)
return False
return False
def _sync_loop():
while True:
time.sleep(SYNC_INTERVAL)
try:
if _pending_ops:
_drain_pending()
except Exception as e: # noqa: BLE001 — never let the daemon die
print(f"[sync] loop error: {e.__class__.__name__}", file=sys.stderr)
def _start_sync_thread_once():
global _sync_thread_started
if _sync_thread_started or not REMOTE_ENABLED:
return
_sync_thread_started = True
threading.Thread(target=_sync_loop, daemon=True).start()
def _ensure_loaded():
"""Load caches from the mirror on first use; seed from Sheets if the mirror is empty."""
global _data_cache_ts
if _data_cache_ts > 0:
return
with _fetch_lock:
if _data_cache_ts > 0:
return
had = _local_load()
if REMOTE_ENABLED:
# Trust the mirror only if it was written by this dual/offline version.
# A pre-dual mirror (schema < 2) is ignored so the first dual launch
# re-seeds cleanly from the real Sheet instead of showing stale data.
if not had or _loaded_schema < MIRROR_SCHEMA:
_reset_caches() # drop any stale pre-dual rows before seeding
_try_pull_from_remote() # offline first run just leaves it empty until a later sync
_start_sync_thread_once()
_drain_pending() # catch up anything journalled before a restart
_data_cache_ts = time.time()
def _fetch_all():
"""Back-compat shim: ensure caches are loaded (no forced network re-read)."""
_ensure_loaded()
def get_all_sheet_data():
_ensure_loaded()
return _data_cache
def get_notes_data():
_ensure_loaded()
return _notes_cache
def get_collabs_data():
_ensure_loaded()
return _collabs_cache
def get_literature_data():
_ensure_loaded()
return _lit_cache
def get_plan_data():
_ensure_loaded()
return _plan_cache
def _make_ws(title, **flags):
return _DualWS(title, **flags) if REMOTE_ENABLED else _LocalWS(title, **flags)
def get_worksheet(title):
_ensure_loaded()
if title not in _data_cache:
raise KeyError(title)
return _make_ws(title)
def ensure_meta_ws(title, headers):
"""Get a write handle for a meta sheet, seeding its header row locally if new."""
_ensure_loaded()
flags = {"is_notes": title == NOTES_SHEET, "is_collabs": title == COLLABS_SHEET,
"is_lit": title == LIT_SHEET, "is_plan": title == PLAN_SHEET}
cache = _meta_cache_for(title)
if cache is not None and not cache:
cache.append(list(headers)) # seed header row in place (row 1)
_local_save()
# Remote tab (with the same header row) is created lazily by _remote_ws on
# the first journalled op, so no header op needs to be enqueued here.
return _make_ws(title, **flags)
def sync_status():
return {
"remote_enabled": REMOTE_ENABLED,
"local_mode": LOCAL_MODE,
"online": _online,
"pending": len(_pending_ops),
"last_synced": _last_synced,
}
def _reset_caches():
"""Empty the data caches (not the pending journal or timestamp)."""
global _data_cache, _notes_cache, _collabs_cache, _lit_cache, _plan_cache
_data_cache = {}
_notes_cache = []
_collabs_cache = []
_lit_cache = []
_plan_cache = []
def invalidate_cache():
global _data_cache_ts
_reset_caches()
_data_cache_ts = 0.0
def patch_cache(sheet_name, row, values):
"""Update a single task row in-memory without an API read."""
if sheet_name not in _data_cache:
return
rows = _data_cache[sheet_name]
idx = row - 1
while len(rows) <= idx:
rows.append([])
while len(rows[idx]) < len(values):
rows[idx].append("")
rows[idx] = list(values)
# ── Meta-cache helpers (notes/collabs/literature) ───────────────────────────
# Let a single note/collab/literature edit patch its own cache array in place
# instead of invalidate_cache() forcing a full re-fetch of every worksheet on
# the next request.
#
# patch_meta_cache is idempotent (same row, same values) so it's safe to call
# unconditionally after ws.update() — same as patch_cache() already being
# called unconditionally after both real and _LocalWS task updates, even
# though _LocalWS.update() also patches the cache itself.
#
# append/delete are NOT idempotent — calling them twice would duplicate or
# over-remove a row — and _LocalWS.append_row()/delete_rows() already apply
# the same mutation to the cache as a side effect in local mode. So these two
# only need to run for the real-Sheets `ws` (a plain gspread Worksheet has no
# such side effect).
def patch_meta_cache(cache_list, row, values):
idx = row - 1
while len(cache_list) <= idx:
cache_list.append([])
cache_list[idx] = list(values)
def append_meta_cache(cache_list, ws, values):
if not isinstance(ws, _LocalWS):
cache_list.append(list(values))
def delete_meta_cache_row(cache_list, ws, row):
if not isinstance(ws, _LocalWS) and 0 < row <= len(cache_list):
cache_list.pop(row - 1)
def _yesterday():
return (datetime.date.today() - datetime.timedelta(days=1)).strftime("%d %b %Y")
def _today():
return datetime.date.today().strftime("%d %b %Y")
def parse_tasks(rows):
tasks = []
for i, row in enumerate(rows[1:], start=2):
task = row[1].strip() if len(row) > 1 else ""
if not task:
continue
status = row[3].strip() if len(row) > 3 else "Not Started"
completed_date = row[4].strip() if len(row) > 4 else ""
if status == "Completed" and not completed_date:
completed_date = _yesterday()
tasks.append({
"row": i,
"deadline": row[0].strip() if len(row) > 0 else "",
"task": task,
"hours": row[2].strip() if len(row) > 2 else "",
"status": status,
"completed_date": completed_date,
"assignee": row[5].strip() if len(row) > 5 else "",
})
return tasks
def parse_notes(rows):
notes = []
for i, row in enumerate(rows[1:], start=2):
if len(row) < 2 or not row[1].strip():
continue
notes.append({
"row": i,
"project": row[0].strip() if len(row) > 0 else "",
"note": row[1].strip(),
"importance": row[2].strip() if len(row) > 2 else "Medium",
"purpose": row[3].strip() if len(row) > 3 else "Other",
"color": row[4].strip() if len(row) > 4 else NOTE_COLORS[0],
"created": row[5].strip() if len(row) > 5 else "",
"modified": row[6].strip() if len(row) > 6 else "",
})
return notes
def parse_collabs(rows):
collabs = []
for i, row in enumerate(rows[1:], start=2):
if len(row) < 2 or not row[1].strip():
continue
collabs.append({
"row": i,
"project": row[0].strip() if len(row) > 0 else "",
"name": row[1].strip(),
"role": row[2].strip() if len(row) > 2 else "",
})
return collabs
def parse_literature(rows):
lit = []
for i, row in enumerate(rows[1:], start=2):
if len(row) < 2 or not row[1].strip():
continue
lit.append({
"row": i,
"project": row[0].strip() if len(row) > 0 else "",
"title": row[1].strip(),
"link": row[2].strip() if len(row) > 2 else "",
"authors": row[3].strip() if len(row) > 3 else "",
"year": row[4].strip() if len(row) > 4 else "",
"notes": row[5].strip() if len(row) > 5 else "",
"created": row[6].strip() if len(row) > 6 else "",
"modified": row[7].strip() if len(row) > 7 else "",
"read": (row[8].strip().lower() in ("1", "true", "yes", "y", "x")) if len(row) > 8 else False,
})
return lit
def parse_plan(rows):
plan = []
for i, row in enumerate(rows[1:], start=2):
# Project, TaskRow, Day, Order, Hours, Created, Modified
if len(row) < 3 or not row[0].strip() or not row[2].strip():
continue
def _int(v, d=0):
try: return int(float(v))
except (TypeError, ValueError): return d
plan.append({
"row": i,
"project": row[0].strip(),
"task_row": _int(row[1].strip() if len(row) > 1 else "", 0),
"day": row[2].strip(), # ISO date "YYYY-MM-DD"
"order": _int(row[3].strip() if len(row) > 3 else "", 0),
"hours": row[4].strip() if len(row) > 4 else "",
"created": row[5].strip() if len(row) > 5 else "",
"modified": row[6].strip() if len(row) > 6 else "",
})
return plan
# ── API ──────────────────────────────────────────────────────────────────────
@app.route("/api/sheets")
def api_sheets():
data = get_all_sheet_data()
result = []
for title, rows in data.items():
tasks = parse_tasks(rows)
result.append({
"name": title,
"active": sum(1 for t in tasks if t["status"] in ACTIVE_STATUSES),
"total": len(tasks),
})
return jsonify(result)
@app.route("/api/tasks")
def api_tasks():
sheet_filter = request.args.get("sheet")
status_filter = request.args.getlist("status") or None
data = get_all_sheet_data()
result = {}
for title, rows in data.items():
if sheet_filter and title != sheet_filter:
continue
tasks = parse_tasks(rows)
if status_filter:
tasks = [t for t in tasks if t["status"] in status_filter]
if tasks:
result[title] = tasks
return jsonify(result)
@app.route("/api/tasks", methods=["POST"])
def api_add_task():
data = request.get_json(silent=True) or {}
if not data.get("task") or not data.get("sheet"):
return jsonify({"error": "sheet and task required"}), 400
try:
ws = get_worksheet(data["sheet"])
except KeyError:
return jsonify({"error": "Sheet not found"}), 404
cached_rows = get_all_sheet_data().get(data["sheet"], [])
col_b = [r[1] if len(r) > 1 else "" for r in cached_rows]
next_row = len(col_b) + 1
for i, val in enumerate(col_b[1:], start=2):
if not val.strip():
next_row = i
break
status = data.get("status", "Not Started")
completed_date = _today() if status == "Completed" else ""
new_row = [data.get("deadline", ""), data["task"], data.get("hours", ""),
status, completed_date, data.get("assignee", "")]
ws.update(range_name=f"A{next_row}:F{next_row}", values=[new_row])
patch_cache(data["sheet"], next_row, new_row)
return jsonify({"row": next_row, "task": data["task"], "status": status})
@app.route("/api/tasks/<sheet_name>/<int:row>", methods=["PUT"])
def api_update_task(sheet_name, row):
data = request.get_json(silent=True) or {}
try:
ws = get_worksheet(sheet_name)
except KeyError:
return jsonify({"error": "Sheet not found"}), 404
sheet_rows = get_all_sheet_data().get(sheet_name, [])
current = list(sheet_rows[row - 1]) if row - 1 < len(sheet_rows) else []
while len(current) < 6:
current.append("")
old_status = current[3]
new_status = data.get("status", old_status)
if new_status == "Completed" and old_status != "Completed":
completed_date = _today()
else:
completed_date = current[4]
updated = [
data.get("deadline", current[0]),
data.get("task", current[1]),
data.get("hours", current[2]),
new_status,
completed_date,
data.get("assignee", current[5]),
]
ws.update(range_name=f"A{row}:F{row}", values=[updated])
patch_cache(sheet_name, row, updated)
return jsonify({"row": row, "updated": updated})
@app.route("/api/tasks/<sheet_name>/<int:row>", methods=["DELETE"])
def api_delete_task(sheet_name, row):
try:
ws = get_worksheet(sheet_name)
except KeyError:
return jsonify({"error": "Sheet not found"}), 404
cleared = ["", "", "", "Not Started", "", ""]
ws.update(range_name=f"A{row}:F{row}", values=[cleared])
patch_cache(sheet_name, row, cleared)
return jsonify({"deleted": row})
# ── Notes API ────────────────────────────────────────────────────────────────
@app.route("/api/notes")
def api_notes():
project = request.args.get("project")
notes = parse_notes(get_notes_data())
if project:
notes = [n for n in notes if n["project"] == project]
return jsonify(notes)
@app.route("/api/notes", methods=["POST"])
def api_add_note():
data = request.get_json(silent=True) or {}
ws = ensure_meta_ws(NOTES_SHEET, NOTE_HEADERS)
today = _today()
new_row = [
data.get("project", ""), data.get("note", ""),
data.get("importance", "Medium"), data.get("purpose", "Other"),
data.get("color", NOTE_COLORS[0]), today, today,
]
ws.append_row(new_row)
append_meta_cache(_notes_cache, ws, new_row)
return jsonify({"ok": True})
@app.route("/api/notes/<int:row>", methods=["PUT"])
def api_update_note(row):
data = request.get_json(silent=True) or {}
ws = ensure_meta_ws(NOTES_SHEET, NOTE_HEADERS)
rows = get_notes_data()
current = list(rows[row - 1]) if row - 1 < len(rows) else []
while len(current) < 7:
current.append("")
updated = [
data.get("project", current[0]),
data.get("note", current[1]),
data.get("importance", current[2]),
data.get("purpose", current[3]),
data.get("color", current[4]),
current[5], # created unchanged
_today(), # modified = today
]
ws.update(range_name=f"A{row}:G{row}", values=[updated])
patch_meta_cache(_notes_cache, row, updated)
return jsonify({"ok": True})
@app.route("/api/notes/<int:row>", methods=["DELETE"])
def api_delete_note(row):
ws = ensure_meta_ws(NOTES_SHEET, NOTE_HEADERS)
ws.delete_rows(row)
delete_meta_cache_row(_notes_cache, ws, row)
return jsonify({"ok": True})
# ── Collaborators API ─────────────────────────────────────────────────────────
@app.route("/api/collaborators")
def api_collaborators():
project = request.args.get("project")
collabs = parse_collabs(get_collabs_data())
if project:
collabs = [c for c in collabs if c["project"] == project]
return jsonify(collabs)
@app.route("/api/collaborators", methods=["POST"])
def api_add_collaborator():
data = request.get_json(silent=True) or {}
ws = ensure_meta_ws(COLLABS_SHEET, COLLAB_HEADERS)
names = data.get("names") or ([data.get("name")] if data.get("name") else [])
role = data.get("role", "")
project = data.get("project", "")
existing = {r[1].strip().lower() for r in get_collabs_data()[1:] if len(r) > 1 and r[0].strip() == project}
for name in names:
name = name.strip()
if name and name.lower() not in existing:
new_row = [project, name, role]
ws.append_row(new_row)
append_meta_cache(_collabs_cache, ws, new_row)
existing.add(name.lower())
return jsonify({"ok": True})
@app.route("/api/collaborators/<int:row>", methods=["DELETE"])
def api_delete_collaborator(row):
ws = ensure_meta_ws(COLLABS_SHEET, COLLAB_HEADERS)
ws.delete_rows(row)
delete_meta_cache_row(_collabs_cache, ws, row)
return jsonify({"ok": True})
# ── Literature API ─────────────────────────────────────────────────────────
@app.route("/api/literature")
def api_literature():
project = request.args.get("project")
lit = parse_literature(get_literature_data())
if project:
lit = [l for l in lit if l["project"] == project]
return jsonify(lit)
@app.route("/api/literature", methods=["POST"])
def api_add_literature():
data = request.get_json(silent=True) or {}
if not data.get("title") or not data.get("project"):
return jsonify({"error": "project and title required"}), 400
ws = ensure_meta_ws(LIT_SHEET, LIT_HEADERS)
today = _today()
new_row = [
data["project"], data["title"], data.get("link", ""),
data.get("authors", ""), data.get("year", ""), data.get("notes", ""),
today, today, ("1" if data.get("read") else ""),
]
ws.append_row(new_row)
append_meta_cache(_lit_cache, ws, new_row)
return jsonify({"ok": True})
@app.route("/api/literature/<int:row>", methods=["PUT"])
def api_update_literature(row):
data = request.get_json(silent=True) or {}
ws = ensure_meta_ws(LIT_SHEET, LIT_HEADERS)
rows = get_literature_data()
current = list(rows[row - 1]) if row - 1 < len(rows) else []
while len(current) < 9:
current.append("")
read_val = ("1" if data["read"] else "") if "read" in data else current[8]
updated = [
data.get("project", current[0]),
data.get("title", current[1]),
data.get("link", current[2]),
data.get("authors", current[3]),
data.get("year", current[4]),
data.get("notes", current[5]),
current[6], # created unchanged
_today(), # modified = today
read_val,
]
ws.update(range_name=f"A{row}:I{row}", values=[updated])
patch_meta_cache(_lit_cache, row, updated)
return jsonify({"ok": True})
@app.route("/api/literature/<int:row>", methods=["DELETE"])
def api_delete_literature(row):
ws = ensure_meta_ws(LIT_SHEET, LIT_HEADERS)
ws.delete_rows(row)
delete_meta_cache_row(_lit_cache, ws, row)
return jsonify({"ok": True})
# ── Plan API (weekly planner: which task on which day, priority order, est. hours) ──
@app.route("/api/plan")
def api_plan():
return jsonify(parse_plan(get_plan_data()))
@app.route("/api/plan", methods=["POST"])
def api_add_plan():
data = request.get_json(silent=True) or {}
project = (data.get("project") or "").strip()
day = (data.get("day") or "").strip()
if not project or not day:
return jsonify({"error": "project and day required"}), 400
ws = ensure_meta_ws(PLAN_SHEET, PLAN_HEADERS)
today = _today()
new_row = [
project, str(data.get("task_row", "")), day,
str(data.get("order", 0)), str(data.get("hours", "")),
today, today,
]
ws.append_row(new_row)
append_meta_cache(_plan_cache, ws, new_row)
return jsonify({"ok": True})
@app.route("/api/plan/<int:row>", methods=["PUT"])
def api_update_plan(row):
data = request.get_json(silent=True) or {}
ws = ensure_meta_ws(PLAN_SHEET, PLAN_HEADERS)
rows = get_plan_data()
current = list(rows[row - 1]) if row - 1 < len(rows) else []
while len(current) < 7:
current.append("")
updated = [
data.get("project", current[0]),
str(data.get("task_row", current[1])),
data.get("day", current[2]),
str(data.get("order", current[3])),
str(data.get("hours", current[4])),
current[5], # created unchanged
_today(), # modified
]
ws.update(range_name=f"A{row}:G{row}", values=[updated])
patch_meta_cache(_plan_cache, row, updated)
return jsonify({"ok": True})
@app.route("/api/plan/<int:row>", methods=["DELETE"])
def api_delete_plan(row):
ws = ensure_meta_ws(PLAN_SHEET, PLAN_HEADERS)
ws.delete_rows(row)
delete_meta_cache_row(_plan_cache, ws, row)
return jsonify({"ok": True})
# ── Sync API ──────────────────────────────────────────────────────────────────
@app.route("/api/sync", methods=["POST"])
def api_sync():
"""Push any pending offline changes to Sheets and report sync state.
Never overwrites the local mirror from Sheets — the mirror is the source of truth.
(If the mirror is somehow still empty, do the one-time seed pull.)"""
_ensure_loaded()
if REMOTE_ENABLED:
if not (_data_cache or _notes_cache or _collabs_cache or _lit_cache or _plan_cache):
_try_pull_from_remote()
_drain_pending()
return jsonify({"ok": True, **sync_status()})
@app.route("/api/status")
def api_status():
_ensure_loaded()
return jsonify(sync_status())
@app.route("/api/restart", methods=["POST"])
def api_restart():
"""Relaunch the app so it reloads app.py from disk. Data is safe (mirror +
pending journal persist). We can't os.execv() in-place because werkzeug's
listening socket would be inherited and the relaunch couldn't rebind the port.
Instead: spawn a detached launcher that retries the original command until the
port frees, then exit this process (releasing the port)."""
def _restart():
time.sleep(0.4) # let this response flush to the browser first
try:
if REMOTE_ENABLED:
_drain_pending()
except Exception:
pass
cmd = " ".join(shlex.quote(a) for a in [sys.executable] + sys.argv)
# Retry the launch for ~30s so it binds as soon as we release the socket.
script = f"for i in $(seq 1 60); do {cmd} && break; sleep 0.5; done"
subprocess.Popen(["/bin/sh", "-c", script], start_new_session=True,
cwd=os.getcwd(), env={**os.environ, "KAAMKAAJ_NO_BROWSER": "1"})
os._exit(0) # release the port; the detached launcher will bind next
threading.Thread(target=_restart, daemon=True).start()
return jsonify({"ok": True})
# ── Projects API ──────────────────────────────────────────────────────────────
@app.route("/api/projects", methods=["POST"])
def api_create_project():
name = (request.get_json(silent=True) or {}).get("name", "").strip()
if not name:
return jsonify({"error": "Name required"}), 400
_ensure_loaded()
if name in _data_cache:
return jsonify({"error": "Project already exists"}), 409
if name in META_SHEETS:
return jsonify({"error": "Reserved name"}), 400
_data_cache[name] = [list(TASK_HEADERS)] # header row prevents row-1 collision
_local_save()
if REMOTE_ENABLED:
_enqueue_or_apply({"kind": "create_sheet", "title": name})
return jsonify({"ok": True, "name": name})
@app.route("/api/projects/<name>", methods=["DELETE"])
def api_delete_project(name):
_ensure_loaded()
if name not in _data_cache:
return jsonify({"error": "Project not found"}), 404
if name in META_SHEETS:
return jsonify({"error": "Cannot delete meta sheet"}), 400
_data_cache.pop(name, None)
_local_save()
if REMOTE_ENABLED:
_enqueue_or_apply({"kind": "delete_sheet", "title": name})
return jsonify({"ok": True})
# ── UI ───────────────────────────────────────────────────────────────────────
HTML = r"""<!DOCTYPE html>
<html lang="en">
<head>