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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
|
package handlers
import (
"context"
"fmt"
"html/template"
"log"
"net/http"
"path/filepath"
"sort"
"strings"
"sync"
"time"
"task-dashboard/internal/api"
"task-dashboard/internal/auth"
"task-dashboard/internal/config"
"task-dashboard/internal/models"
"task-dashboard/internal/store"
)
// Handler holds dependencies for HTTP handlers
type Handler struct {
store *store.Store
todoistClient api.TodoistAPI
trelloClient api.TrelloAPI
planToEatClient api.PlanToEatAPI
googleCalendarClient api.GoogleCalendarAPI
googleTasksClient api.GoogleTasksAPI
config *config.Config
renderer Renderer
}
// New creates a new Handler instance
func New(s *store.Store, todoist api.TodoistAPI, trello api.TrelloAPI, planToEat api.PlanToEatAPI, googleCalendar api.GoogleCalendarAPI, googleTasks api.GoogleTasksAPI, cfg *config.Config) *Handler {
// Template functions
funcMap := template.FuncMap{
"subtract": func(a, b int) int { return a - b },
}
// Parse templates including partials
tmpl, err := template.New("").Funcs(funcMap).ParseGlob(filepath.Join(cfg.TemplateDir, "*.html"))
if err != nil {
log.Printf("Warning: failed to parse templates: %v", err)
}
// Also parse partials
tmpl, err = tmpl.ParseGlob(filepath.Join(cfg.TemplateDir, "partials", "*.html"))
if err != nil {
log.Printf("Warning: failed to parse partial templates: %v", err)
}
return &Handler{
store: s,
todoistClient: todoist,
trelloClient: trello,
planToEatClient: planToEat,
googleCalendarClient: googleCalendar,
googleTasksClient: googleTasks,
config: cfg,
renderer: NewTemplateRenderer(tmpl),
}
}
// HandleDashboard renders the main dashboard view
func (h *Handler) HandleDashboard(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
// Extract tab query parameter for state persistence
tab := r.URL.Query().Get("tab")
if tab == "" {
tab = "timeline"
}
// Aggregate data from all sources
dashboardData, err := h.aggregateData(ctx, false)
if err != nil {
http.Error(w, "Failed to load dashboard data", http.StatusInternalServerError)
log.Printf("Error aggregating data: %v", err)
return
}
// Render template
if h.renderer == nil {
http.Error(w, "Renderer not configured", http.StatusInternalServerError)
return
}
// Generate random background URL (Lorem Picsum - CORS-friendly)
// Add random seed to get different image each load
backgroundURL := fmt.Sprintf("https://picsum.photos/1920/1080?random=%d", time.Now().UnixNano())
// Wrap dashboard data with active tab for template
data := struct {
*models.DashboardData
ActiveTab string
CSRFToken string
BackgroundURL string
}{
DashboardData: dashboardData,
ActiveTab: tab,
CSRFToken: auth.GetCSRFTokenFromContext(ctx),
BackgroundURL: backgroundURL,
}
if err := h.renderer.Render(w, "index.html", data); err != nil {
http.Error(w, "Failed to render template", http.StatusInternalServerError)
log.Printf("Error rendering template: %v", err)
}
}
// HandleRefresh forces a refresh of all data
func (h *Handler) HandleRefresh(w http.ResponseWriter, r *http.Request) {
data, err := h.aggregateData(r.Context(), true)
if err != nil {
JSONError(w, http.StatusInternalServerError, "Failed to refresh data", err)
return
}
JSONResponse(w, data)
}
// HandleGetTasks returns tasks as JSON
func (h *Handler) HandleGetTasks(w http.ResponseWriter, r *http.Request) {
tasks, err := h.store.GetTasks()
if err != nil {
JSONError(w, http.StatusInternalServerError, "Failed to get tasks", err)
return
}
JSONResponse(w, tasks)
}
// HandleGetMeals returns meals as JSON
func (h *Handler) HandleGetMeals(w http.ResponseWriter, r *http.Request) {
startDate := config.Now()
endDate := startDate.AddDate(0, 0, 7)
meals, err := h.store.GetMeals(startDate, endDate)
if err != nil {
JSONError(w, http.StatusInternalServerError, "Failed to get meals", err)
return
}
JSONResponse(w, meals)
}
// HandleGetBoards returns Trello boards with cards as JSON
func (h *Handler) HandleGetBoards(w http.ResponseWriter, r *http.Request) {
boards, err := h.store.GetBoards()
if err != nil {
JSONError(w, http.StatusInternalServerError, "Failed to get boards", err)
return
}
JSONResponse(w, boards)
}
// HandleGetShoppingList returns PlanToEat shopping list as JSON
func (h *Handler) HandleGetShoppingList(w http.ResponseWriter, r *http.Request) {
if h.planToEatClient == nil {
JSONError(w, http.StatusServiceUnavailable, "PlanToEat not configured", nil)
return
}
items, err := h.planToEatClient.GetShoppingList(r.Context())
if err != nil {
JSONError(w, http.StatusInternalServerError, "Failed to get shopping list", err)
return
}
JSONResponse(w, items)
}
// HandleTasksTab renders the tasks tab content (Trello + Todoist + PlanToEat)
func (h *Handler) HandleTasksTab(w http.ResponseWriter, r *http.Request) {
data, err := h.aggregateData(r.Context(), false)
if err != nil {
JSONError(w, http.StatusInternalServerError, "Failed to load tasks", err)
return
}
HTMLResponse(w, h.renderer, "tasks-tab", data)
}
// HandleRefreshTab refreshes and re-renders the specified tab
func (h *Handler) HandleRefreshTab(w http.ResponseWriter, r *http.Request) {
data, err := h.aggregateData(r.Context(), true)
if err != nil {
JSONError(w, http.StatusInternalServerError, "Failed to refresh", err)
return
}
HTMLResponse(w, h.renderer, "tasks-tab", data)
}
// aggregateData fetches and caches data from all sources concurrently
func (h *Handler) aggregateData(ctx context.Context, forceRefresh bool) (*models.DashboardData, error) {
data := &models.DashboardData{
LastUpdated: config.Now(),
Errors: make([]string, 0),
}
var wg sync.WaitGroup
var mu sync.Mutex
// Helper to run fetch in goroutine with error collection
fetch := func(name string, fn func() error) {
wg.Add(1)
go func() {
defer wg.Done()
select {
case <-ctx.Done():
return
default:
}
if err := fn(); err != nil {
log.Printf("ERROR [%s]: %v", name, err)
mu.Lock()
data.Errors = append(data.Errors, name+": "+err.Error())
mu.Unlock()
}
}()
}
fetch("Trello", func() error {
boards, err := h.fetchBoards(ctx, forceRefresh)
if err == nil {
mu.Lock()
data.Boards = boards
mu.Unlock()
}
return err
})
fetch("Todoist", func() error {
tasks, err := h.fetchTasks(ctx, forceRefresh)
if err == nil {
sortTasksByUrgency(tasks)
mu.Lock()
data.Tasks = tasks
mu.Unlock()
}
return err
})
fetch("Projects", func() error {
projects, err := h.todoistClient.GetProjects(ctx)
if err == nil {
mu.Lock()
data.Projects = projects
mu.Unlock()
}
return err
})
if h.planToEatClient != nil {
fetch("PlanToEat", func() error {
meals, err := h.fetchMeals(ctx, forceRefresh)
if err == nil {
mu.Lock()
data.Meals = meals
mu.Unlock()
}
return err
})
}
if h.googleCalendarClient != nil {
fetch("Google Calendar", func() error {
events, err := h.googleCalendarClient.GetUpcomingEvents(ctx, 10)
if err == nil {
mu.Lock()
data.Events = events
mu.Unlock()
}
return err
})
}
wg.Wait()
// Extract and sort Trello tasks
data.TrelloTasks = filterAndSortTrelloTasks(data.Boards)
return data, nil
}
// sortTasksByUrgency sorts tasks by due date then priority
func sortTasksByUrgency(tasks []models.Task) {
sort.Slice(tasks, func(i, j int) bool {
if tasks[i].DueDate == nil && tasks[j].DueDate != nil {
return false
}
if tasks[i].DueDate != nil && tasks[j].DueDate == nil {
return true
}
if tasks[i].DueDate != nil && tasks[j].DueDate != nil {
if !tasks[i].DueDate.Equal(*tasks[j].DueDate) {
return tasks[i].DueDate.Before(*tasks[j].DueDate)
}
}
return tasks[i].Priority > tasks[j].Priority
})
}
// filterAndSortTrelloTasks extracts task-like cards from boards
func filterAndSortTrelloTasks(boards []models.Board) []models.Card {
var tasks []models.Card
for _, board := range boards {
for _, card := range board.Cards {
if card.DueDate != nil || isActionableList(card.ListName) {
tasks = append(tasks, card)
}
}
}
sort.Slice(tasks, func(i, j int) bool {
if tasks[i].DueDate != nil && tasks[j].DueDate != nil {
if !tasks[i].DueDate.Equal(*tasks[j].DueDate) {
return tasks[i].DueDate.Before(*tasks[j].DueDate)
}
}
if tasks[i].DueDate != nil && tasks[j].DueDate == nil {
return true
}
if tasks[i].DueDate == nil && tasks[j].DueDate != nil {
return false
}
return tasks[i].BoardName < tasks[j].BoardName
})
return tasks
}
// fetchTasks fetches tasks from cache or API using incremental sync
func (h *Handler) fetchTasks(ctx context.Context, forceRefresh bool) ([]models.Task, error) {
cacheKey := store.CacheKeyTodoistTasks
syncService := "todoist"
// Check cache validity
if !forceRefresh {
valid, err := h.store.IsCacheValid(cacheKey)
if err == nil && valid {
return h.store.GetTasks()
}
}
// Get stored sync token (empty string means full sync)
syncToken, err := h.store.GetSyncToken(syncService)
if err != nil {
log.Printf("Failed to get sync token, will do full sync: %v", err)
syncToken = ""
}
// Force full sync if requested
if forceRefresh {
syncToken = ""
}
// Fetch using Sync API
syncResp, err := h.todoistClient.Sync(ctx, syncToken)
if err != nil {
// Try to return cached data even if stale
cachedTasks, cacheErr := h.store.GetTasks()
if cacheErr == nil && len(cachedTasks) > 0 {
return cachedTasks, nil
}
return nil, err
}
// Build project map from sync response
projectMap := api.BuildProjectMapFromSync(syncResp.Projects)
// Process sync response
if syncResp.FullSync {
// Full sync: replace all tasks
tasks := api.ConvertSyncItemsToTasks(syncResp.Items, projectMap)
if err := h.store.SaveTasks(tasks); err != nil {
log.Printf("Failed to save tasks to cache: %v", err)
}
} else {
// Incremental sync: merge changes
var deletedIDs []string
for _, item := range syncResp.Items {
if item.IsDeleted || item.IsCompleted {
deletedIDs = append(deletedIDs, item.ID)
} else {
// Upsert active task
task := h.convertSyncItemToTask(item, projectMap)
if err := h.store.UpsertTask(task); err != nil {
log.Printf("Failed to upsert task %s: %v", item.ID, err)
}
}
}
// Delete removed tasks
if len(deletedIDs) > 0 {
if err := h.store.DeleteTasksByIDs(deletedIDs); err != nil {
log.Printf("Failed to delete tasks: %v", err)
}
}
}
// Store the new sync token
if err := h.store.SetSyncToken(syncService, syncResp.SyncToken); err != nil {
log.Printf("Failed to save sync token: %v", err)
}
// Update cache metadata
if err := h.store.UpdateCacheMetadata(cacheKey, h.config.CacheTTLMinutes); err != nil {
log.Printf("Failed to update cache metadata: %v", err)
}
return h.store.GetTasks()
}
// convertSyncItemToTask converts a sync item to a Task model
func (h *Handler) convertSyncItemToTask(item api.SyncItemResponse, projectMap map[string]string) models.Task {
// Use the ConvertSyncItemsToTasks helper for single item conversion
items := api.ConvertSyncItemsToTasks([]api.SyncItemResponse{item}, projectMap)
if len(items) > 0 {
return items[0]
}
// Fallback for completed/deleted items (shouldn't happen in practice)
return models.Task{
ID: item.ID,
Content: item.Content,
Description: item.Description,
ProjectID: item.ProjectID,
ProjectName: projectMap[item.ProjectID],
Priority: item.Priority,
Completed: item.IsCompleted,
Labels: item.Labels,
URL: fmt.Sprintf("https://todoist.com/app/task/%s", item.ID),
}
}
// fetchMeals fetches meals from cache or API
func (h *Handler) fetchMeals(ctx context.Context, forceRefresh bool) ([]models.Meal, error) {
startDate := config.Now()
endDate := startDate.AddDate(0, 0, 7)
fetcher := &CacheFetcher[models.Meal]{
Store: h.store,
CacheKey: store.CacheKeyPlanToEatMeals,
TTLMinutes: h.config.CacheTTLMinutes,
Fetch: func(ctx context.Context) ([]models.Meal, error) { return h.planToEatClient.GetUpcomingMeals(ctx, 7) },
GetFromCache: func() ([]models.Meal, error) { return h.store.GetMeals(startDate, endDate) },
SaveToCache: h.store.SaveMeals,
}
return fetcher.FetchWithCache(ctx, forceRefresh)
}
// fetchBoards fetches Trello boards from cache or API
func (h *Handler) fetchBoards(ctx context.Context, forceRefresh bool) ([]models.Board, error) {
fetcher := &CacheFetcher[models.Board]{
Store: h.store,
CacheKey: store.CacheKeyTrelloBoards,
TTLMinutes: h.config.CacheTTLMinutes,
Fetch: func(ctx context.Context) ([]models.Board, error) {
boards, err := h.trelloClient.GetBoardsWithCards(ctx)
if err == nil {
// Debug logging
totalCards := 0
for _, b := range boards {
totalCards += len(b.Cards)
if len(b.Cards) > 0 {
log.Printf("Trello API: Board %q has %d cards", b.Name, len(b.Cards))
}
}
log.Printf("Trello API: Fetched %d boards with %d total cards", len(boards), totalCards)
}
return boards, err
},
GetFromCache: h.store.GetBoards,
SaveToCache: h.store.SaveBoards,
}
return fetcher.FetchWithCache(ctx, forceRefresh)
}
// HandleCreateCard creates a new Trello card
func (h *Handler) HandleCreateCard(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
if err := r.ParseForm(); err != nil {
JSONError(w, http.StatusBadRequest, "Failed to parse form", err)
return
}
boardID := r.FormValue("board_id")
listID := r.FormValue("list_id")
name := r.FormValue("name")
if boardID == "" || listID == "" || name == "" {
JSONError(w, http.StatusBadRequest, "Missing required fields", nil)
return
}
if _, err := h.trelloClient.CreateCard(ctx, listID, name, "", nil); err != nil {
JSONError(w, http.StatusInternalServerError, "Failed to create card", err)
return
}
data, err := h.aggregateData(ctx, true)
if err != nil {
JSONError(w, http.StatusInternalServerError, "Failed to refresh data", err)
return
}
var targetBoard *models.Board
for i := range data.Boards {
if data.Boards[i].ID == boardID {
targetBoard = &data.Boards[i]
break
}
}
if targetBoard == nil {
JSONError(w, http.StatusNotFound, "Board not found", nil)
return
}
HTMLResponse(w, h.renderer, "trello-board", targetBoard)
}
// HandleCompleteCard marks a Trello card as complete
func (h *Handler) HandleCompleteCard(w http.ResponseWriter, r *http.Request) {
if !parseFormOr400(w, r) {
return
}
cardID := r.FormValue("card_id")
if cardID == "" {
JSONError(w, http.StatusBadRequest, "Missing card_id", nil)
return
}
if err := h.trelloClient.UpdateCard(r.Context(), cardID, map[string]interface{}{"closed": true}); err != nil {
JSONError(w, http.StatusInternalServerError, "Failed to complete card", err)
return
}
w.WriteHeader(http.StatusOK)
}
// HandleCreateTask creates a new Todoist task
func (h *Handler) HandleCreateTask(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
if err := r.ParseForm(); err != nil {
JSONError(w, http.StatusBadRequest, "Failed to parse form", err)
return
}
content := r.FormValue("content")
projectID := r.FormValue("project_id")
if content == "" {
JSONError(w, http.StatusBadRequest, "Missing content", nil)
return
}
if _, err := h.todoistClient.CreateTask(ctx, content, projectID, nil, 0); err != nil {
JSONError(w, http.StatusInternalServerError, "Failed to create task", err)
return
}
tasks, err := h.fetchTasks(ctx, true)
if err != nil {
JSONError(w, http.StatusInternalServerError, "Failed to refresh tasks", err)
return
}
projects, _ := h.todoistClient.GetProjects(ctx)
data := struct {
Tasks []models.Task
Projects []models.Project
}{Tasks: tasks, Projects: projects}
HTMLResponse(w, h.renderer, "todoist-tasks", data)
}
// HandleCompleteTask marks a Todoist task as complete
func (h *Handler) HandleCompleteTask(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
JSONError(w, http.StatusBadRequest, "Failed to parse form", err)
return
}
taskID := r.FormValue("task_id")
if taskID == "" {
JSONError(w, http.StatusBadRequest, "Missing task_id", nil)
return
}
if err := h.todoistClient.CompleteTask(r.Context(), taskID); err != nil {
JSONError(w, http.StatusInternalServerError, "Failed to complete task", err)
return
}
w.WriteHeader(http.StatusOK)
}
// HandleCompleteAtom handles completion of a unified task (Atom)
func (h *Handler) HandleCompleteAtom(w http.ResponseWriter, r *http.Request) {
h.handleAtomToggle(w, r, true)
}
// HandleUncompleteAtom handles reopening a completed task
func (h *Handler) HandleUncompleteAtom(w http.ResponseWriter, r *http.Request) {
h.handleAtomToggle(w, r, false)
}
// handleAtomToggle handles both complete and uncomplete operations
func (h *Handler) handleAtomToggle(w http.ResponseWriter, r *http.Request, complete bool) {
ctx := r.Context()
if err := r.ParseForm(); err != nil {
JSONError(w, http.StatusBadRequest, "Failed to parse form", err)
return
}
id := r.FormValue("id")
source := r.FormValue("source")
if id == "" || source == "" {
JSONError(w, http.StatusBadRequest, "Missing id or source", nil)
return
}
var err error
switch source {
case "todoist":
if complete {
err = h.todoistClient.CompleteTask(ctx, id)
} else {
err = h.todoistClient.ReopenTask(ctx, id)
}
case "trello":
err = h.trelloClient.UpdateCard(ctx, id, map[string]interface{}{"closed": complete})
case "bug":
// Bug IDs are prefixed with "bug-", extract the numeric ID
var bugID int64
if _, parseErr := fmt.Sscanf(id, "bug-%d", &bugID); parseErr != nil {
JSONError(w, http.StatusBadRequest, "Invalid bug ID format", parseErr)
return
}
if complete {
err = h.store.ResolveBug(bugID)
} else {
err = h.store.UnresolveBug(bugID)
}
case "gtasks":
// Google Tasks - need list ID from form or use default
listID := r.FormValue("listId")
if listID == "" {
listID = "@default"
}
if h.googleTasksClient != nil {
if complete {
err = h.googleTasksClient.CompleteTask(ctx, listID, id)
} else {
err = h.googleTasksClient.UncompleteTask(ctx, listID, id)
}
} else {
JSONError(w, http.StatusServiceUnavailable, "Google Tasks not configured", nil)
return
}
default:
JSONError(w, http.StatusBadRequest, "Unknown source: "+source, nil)
return
}
if err != nil {
action := "complete"
if !complete {
action = "reopen"
}
JSONError(w, http.StatusInternalServerError, "Failed to "+action+" task", err)
return
}
if complete {
// Get task details before removing from cache
title, dueDate := h.getAtomDetails(id, source)
// Log to completed tasks
_ = h.store.SaveCompletedTask(source, id, title, dueDate)
// Remove from local cache
switch source {
case "todoist":
_ = h.store.DeleteTask(id)
case "trello":
_ = h.store.DeleteCard(id)
}
// Return completed task HTML with uncomplete option
data := struct {
ID string
Source string
Title string
}{id, source, title}
HTMLResponse(w, h.renderer, "completed-atom", data)
} else {
// Invalidate cache to force refresh
switch source {
case "todoist":
_ = h.store.InvalidateCache(store.CacheKeyTodoistTasks)
case "trello":
_ = h.store.InvalidateCache(store.CacheKeyTrelloBoards)
}
// Don't swap empty response - just trigger refresh
w.Header().Set("HX-Reswap", "none")
w.Header().Set("HX-Trigger", "refresh-tasks")
w.WriteHeader(http.StatusOK)
}
}
// getAtomDetails retrieves title and due date for a task/card/bug from the store
func (h *Handler) getAtomDetails(id, source string) (string, *time.Time) {
switch source {
case "todoist":
if tasks, err := h.store.GetTasks(); err == nil {
for _, t := range tasks {
if t.ID == id {
return t.Content, t.DueDate
}
}
}
case "trello":
if boards, err := h.store.GetBoards(); err == nil {
for _, b := range boards {
for _, c := range b.Cards {
if c.ID == id {
return c.Name, c.DueDate
}
}
}
}
case "bug":
if bugs, err := h.store.GetBugs(); err == nil {
var bugID int64
if _, err := fmt.Sscanf(id, "bug-%d", &bugID); err == nil {
for _, b := range bugs {
if b.ID == bugID {
return b.Description, nil
}
}
}
}
case "gtasks":
// Google Tasks don't have local cache, return generic title
return "Google Task", nil
}
return "Task", nil
}
// getAtomTitle retrieves the title for a task/card/bug from the store (legacy)
func (h *Handler) getAtomTitle(id, source string) string {
title, _ := h.getAtomDetails(id, source)
return title
}
// HandleUnifiedAdd creates a task in Todoist or a card in Trello from the Quick Add form
func (h *Handler) HandleUnifiedAdd(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
if err := r.ParseForm(); err != nil {
JSONError(w, http.StatusBadRequest, "Failed to parse form", err)
return
}
title := r.FormValue("title")
source := r.FormValue("source")
dueDateStr := r.FormValue("due_date")
if title == "" {
JSONError(w, http.StatusBadRequest, "Title is required", nil)
return
}
var dueDate *time.Time
if dueDateStr != "" {
if parsed, err := config.ParseDateInDisplayTZ(dueDateStr); err == nil {
dueDate = &parsed
}
}
switch source {
case "todoist":
if _, err := h.todoistClient.CreateTask(ctx, title, "", dueDate, 1); err != nil {
JSONError(w, http.StatusInternalServerError, "Failed to create Todoist task", err)
return
}
_ = h.store.InvalidateCache(store.CacheKeyTodoistTasks)
case "trello":
listID := r.FormValue("list_id")
if listID == "" {
JSONError(w, http.StatusBadRequest, "List is required for Trello", nil)
return
}
if _, err := h.trelloClient.CreateCard(ctx, listID, title, "", dueDate); err != nil {
JSONError(w, http.StatusInternalServerError, "Failed to create Trello card", err)
return
}
_ = h.store.InvalidateCache(store.CacheKeyTrelloBoards)
default:
JSONError(w, http.StatusBadRequest, "Invalid source", nil)
return
}
w.Header().Set("HX-Trigger", "refresh-tasks")
w.WriteHeader(http.StatusOK)
}
// HandleGetListsOptions returns HTML options for lists in a given board
func (h *Handler) HandleGetListsOptions(w http.ResponseWriter, r *http.Request) {
boardID := r.URL.Query().Get("board_id")
if boardID == "" {
JSONError(w, http.StatusBadRequest, "board_id is required", nil)
return
}
lists, err := h.trelloClient.GetLists(r.Context(), boardID)
if err != nil {
JSONError(w, http.StatusInternalServerError, "Failed to fetch lists", err)
return
}
w.Header().Set("Content-Type", "text/html")
for _, list := range lists {
_, _ = fmt.Fprintf(w, `<option value="%s">%s</option>`,
template.HTMLEscapeString(list.ID),
template.HTMLEscapeString(list.Name))
}
}
// HandleGetBugs returns the list of reported bugs
func (h *Handler) HandleGetBugs(w http.ResponseWriter, r *http.Request) {
bugs, err := h.store.GetBugs()
if err != nil {
JSONError(w, http.StatusInternalServerError, "Failed to fetch bugs", err)
return
}
w.Header().Set("Content-Type", "text/html")
if len(bugs) == 0 {
_, _ = fmt.Fprint(w, `<p class="text-gray-500 text-sm">No bugs reported yet.</p>`)
return
}
for _, bug := range bugs {
_, _ = fmt.Fprintf(w, `<div class="text-sm border-b border-gray-100 py-2">
<p class="text-gray-900">%s</p>
<p class="text-gray-400 text-xs">%s</p>
</div>`, template.HTMLEscapeString(bug.Description), bug.CreatedAt.Format("Jan 2, 3:04 PM"))
}
}
// HandleReportBug saves a new bug report
func (h *Handler) HandleReportBug(w http.ResponseWriter, r *http.Request) {
if !parseFormOr400(w, r) {
return
}
description := strings.TrimSpace(r.FormValue("description"))
if description == "" {
JSONError(w, http.StatusBadRequest, "Description is required", nil)
return
}
if err := h.store.SaveBug(description); err != nil {
JSONError(w, http.StatusInternalServerError, "Failed to save bug", err)
return
}
h.HandleGetBugs(w, r)
}
// HandleGetTaskDetail returns task details as HTML for modal
func (h *Handler) HandleGetTaskDetail(w http.ResponseWriter, r *http.Request) {
id := r.URL.Query().Get("id")
source := r.URL.Query().Get("source")
if id == "" || source == "" {
JSONError(w, http.StatusBadRequest, "Missing id or source", nil)
return
}
var title, description string
switch source {
case "todoist":
if tasks, err := h.store.GetTasks(); err == nil {
for _, t := range tasks {
if t.ID == id {
title, description = t.Content, t.Description
break
}
}
}
case "trello":
if boards, err := h.store.GetBoards(); err == nil {
for _, b := range boards {
for _, c := range b.Cards {
if c.ID == id {
title = c.Name
break
}
}
}
}
}
html := fmt.Sprintf(`
<div class="p-4">
<h3 class="font-semibold text-gray-900 mb-3">%s</h3>
<form hx-post="/tasks/update" hx-swap="none" hx-on::after-request="if(event.detail.successful) { closeTaskModal(); htmx.trigger(document.body, 'refresh-tasks'); }">
<input type="hidden" name="id" value="%s">
<input type="hidden" name="source" value="%s">
<label class="block text-sm font-medium text-gray-700 mb-1">Description</label>
<textarea name="description" class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm mb-3 h-32">%s</textarea>
<button type="submit" class="w-full bg-primary-600 hover:bg-primary-700 text-white px-4 py-2 rounded-lg text-sm font-medium">Save</button>
</form>
</div>
`, template.HTMLEscapeString(title), template.HTMLEscapeString(id), template.HTMLEscapeString(source), template.HTMLEscapeString(description))
HTMLString(w, html)
}
// HandleUpdateTask updates a task description
func (h *Handler) HandleUpdateTask(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
JSONError(w, http.StatusBadRequest, "Failed to parse form", err)
return
}
id := r.FormValue("id")
source := r.FormValue("source")
description := r.FormValue("description")
if id == "" || source == "" {
JSONError(w, http.StatusBadRequest, "Missing id or source", nil)
return
}
var err error
switch source {
case "todoist":
err = h.todoistClient.UpdateTask(r.Context(), id, map[string]interface{}{"description": description})
case "trello":
err = h.trelloClient.UpdateCard(r.Context(), id, map[string]interface{}{"desc": description})
default:
JSONError(w, http.StatusBadRequest, "Unknown source", nil)
return
}
if err != nil {
JSONError(w, http.StatusInternalServerError, "Failed to update task", err)
return
}
w.WriteHeader(http.StatusOK)
}
// HandleTabTasks renders the unified Tasks tab (Todoist + Trello cards with due dates + Bugs)
func (h *Handler) HandleTabTasks(w http.ResponseWriter, r *http.Request) {
atoms, boards, err := BuildUnifiedAtomList(h.store)
if err != nil {
JSONError(w, http.StatusInternalServerError, "Failed to fetch tasks", err)
return
}
SortAtomsByUrgency(atoms)
currentAtoms, futureAtoms := PartitionAtomsByTime(atoms)
data := struct {
Atoms []models.Atom
FutureAtoms []models.Atom
Boards []models.Board
Today string
}{
Atoms: currentAtoms,
FutureAtoms: futureAtoms,
Boards: boards,
Today: config.Now().Format("2006-01-02"),
}
HTMLResponse(w, h.renderer, "tasks-tab", data)
}
// HandleTabPlanning renders the Planning tab with structured sections
func (h *Handler) HandleTabPlanning(w http.ResponseWriter, r *http.Request) {
today := config.Today()
tomorrow := today.AddDate(0, 0, 1)
in3Days := today.AddDate(0, 0, 4)
boards, _ := h.store.GetBoards()
tasks, _ := h.store.GetTasks()
var events []models.CalendarEvent
if h.googleCalendarClient != nil {
events, _ = h.googleCalendarClient.GetUpcomingEvents(r.Context(), 20)
}
var scheduled []ScheduledItem
var unscheduled []models.Atom
var upcoming []ScheduledItem
for _, event := range events {
item := ScheduledItem{
Type: "event",
ID: event.ID,
Title: event.Summary,
Start: event.Start,
End: event.End,
URL: event.HTMLLink,
Source: "calendar",
SourceIcon: "🗓️",
}
if event.Start.Before(tomorrow) {
scheduled = append(scheduled, item)
} else if event.Start.Before(in3Days) {
upcoming = append(upcoming, item)
}
}
for _, task := range tasks {
if task.Completed || task.DueDate == nil {
continue
}
dueDate := *task.DueDate
hasTime := dueDate.Hour() != 0 || dueDate.Minute() != 0
if dueDate.Before(tomorrow) {
if hasTime {
scheduled = append(scheduled, ScheduledItem{
Type: "task",
ID: task.ID,
Title: task.Content,
Start: dueDate,
URL: task.URL,
Source: "todoist",
SourceIcon: "✓",
Priority: task.Priority,
})
} else {
atom := models.TaskToAtom(task)
atom.ComputeUIFields()
unscheduled = append(unscheduled, atom)
}
} else if dueDate.Before(in3Days) {
upcoming = append(upcoming, ScheduledItem{
Type: "task",
ID: task.ID,
Title: task.Content,
Start: dueDate,
URL: task.URL,
Source: "todoist",
SourceIcon: "✓",
Priority: task.Priority,
})
}
}
for _, board := range boards {
for _, card := range board.Cards {
if card.DueDate == nil {
continue
}
dueDate := *card.DueDate
hasTime := dueDate.Hour() != 0 || dueDate.Minute() != 0
if dueDate.Before(tomorrow) {
if hasTime {
scheduled = append(scheduled, ScheduledItem{
Type: "task",
ID: card.ID,
Title: card.Name,
Start: dueDate,
URL: card.URL,
Source: "trello",
SourceIcon: "📋",
})
} else {
atom := models.CardToAtom(card)
atom.ComputeUIFields()
unscheduled = append(unscheduled, atom)
}
} else if dueDate.Before(in3Days) {
upcoming = append(upcoming, ScheduledItem{
Type: "task",
ID: card.ID,
Title: card.Name,
Start: dueDate,
URL: card.URL,
Source: "trello",
SourceIcon: "📋",
})
}
}
}
sort.Slice(scheduled, func(i, j int) bool { return scheduled[i].Start.Before(scheduled[j].Start) })
sort.Slice(unscheduled, func(i, j int) bool { return unscheduled[i].Priority > unscheduled[j].Priority })
sort.Slice(upcoming, func(i, j int) bool { return upcoming[i].Start.Before(upcoming[j].Start) })
data := struct {
Scheduled []ScheduledItem
Unscheduled []models.Atom
Upcoming []ScheduledItem
Boards []models.Board
Today string
}{
Scheduled: scheduled,
Unscheduled: unscheduled,
Upcoming: upcoming,
Boards: boards,
Today: today.Format("2006-01-02"),
}
HTMLResponse(w, h.renderer, "planning-tab", data)
}
// CombinedMeal represents multiple meals combined for same date+mealType
type CombinedMeal struct {
RecipeNames []string
Date time.Time
MealType string
RecipeURL string // URL of first meal
}
// HandleTabMeals renders the Meals tab (PlanToEat)
func (h *Handler) HandleTabMeals(w http.ResponseWriter, r *http.Request) {
startDate := config.Now()
endDate := startDate.AddDate(0, 0, 7)
meals, err := h.store.GetMeals(startDate, endDate)
if err != nil {
JSONError(w, http.StatusInternalServerError, "Failed to fetch meals", err)
return
}
// Group meals by date+mealType
type mealKey struct {
date string
mealType string
}
mealGroups := make(map[mealKey][]models.Meal)
for _, meal := range meals {
key := mealKey{
date: meal.Date.Format("2006-01-02"),
mealType: meal.MealType,
}
mealGroups[key] = append(mealGroups[key], meal)
}
// Convert to combined meals
var combined []CombinedMeal
for _, group := range mealGroups {
if len(group) == 0 {
continue
}
cm := CombinedMeal{
Date: group[0].Date,
MealType: group[0].MealType,
RecipeURL: group[0].RecipeURL,
}
for _, m := range group {
cm.RecipeNames = append(cm.RecipeNames, m.RecipeName)
}
combined = append(combined, cm)
}
// Sort by date then meal type order
sort.Slice(combined, func(i, j int) bool {
if !combined[i].Date.Equal(combined[j].Date) {
return combined[i].Date.Before(combined[j].Date)
}
return mealTypeOrder(combined[i].MealType) < mealTypeOrder(combined[j].MealType)
})
HTMLResponse(w, h.renderer, "meals-tab", struct{ Meals []CombinedMeal }{combined})
}
// mealTypeOrder returns sort order for meal types
func mealTypeOrder(mealType string) int {
switch mealType {
case "breakfast":
return 0
case "lunch":
return 1
case "dinner":
return 2
default:
return 3
}
}
// HandleTabConditions renders the Conditions tab with live feeds
func (h *Handler) HandleTabConditions(w http.ResponseWriter, r *http.Request) {
HTMLResponse(w, h.renderer, "conditions-tab", nil)
}
// HandleConditionsPage renders the standalone Conditions page with live feeds
func (h *Handler) HandleConditionsPage(w http.ResponseWriter, r *http.Request) {
if err := h.renderer.Render(w, "conditions.html", nil); err != nil {
http.Error(w, "Failed to render conditions page", http.StatusInternalServerError)
log.Printf("Error rendering conditions page: %v", err)
}
}
// isActionableList returns true if the list name indicates an actionable list
func isActionableList(name string) bool {
lower := strings.ToLower(name)
return strings.Contains(lower, "doing") ||
strings.Contains(lower, "in progress") ||
strings.Contains(lower, "to do") ||
strings.Contains(lower, "todo") ||
strings.Contains(lower, "tasks") ||
strings.Contains(lower, "next") ||
strings.Contains(lower, "today")
}
// ScheduledItem represents a scheduled event or task for the planning view
type ScheduledItem struct {
Type string
ID string
Title string
Start time.Time
End time.Time
URL string
Source string
SourceIcon string
Priority int
}
|