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
|
package handlers
import (
"encoding/json"
"errors"
"log"
"net/http"
"strings"
"time"
"github.com/go-chi/chi/v5"
"task-dashboard/internal/config"
"task-dashboard/internal/models"
"task-dashboard/internal/store"
)
// WidgetAuthMiddleware validates the static bearer token for widget API endpoints.
func WidgetAuthMiddleware(token string, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if token == "" {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
auth := r.Header.Get("Authorization")
if !strings.HasPrefix(auth, "Bearer ") || strings.TrimPrefix(auth, "Bearer ") != token {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
})
}
// TimelineItemToWidgetItem converts a TimelineItem to a WidgetItem for the widget API.
// Exported for testability.
func TimelineItemToWidgetItem(item models.TimelineItem) models.WidgetItem {
wi := models.WidgetItem{
ID: item.ID,
Title: item.Title,
Source: item.Source,
IsAllDay: item.IsAllDay,
IsOverdue: item.IsOverdue,
URL: item.URL,
RecurringEventID: item.RecurringEventID,
ChainPosition: item.ChainPosition,
ChainTotal: item.ChainTotal,
BucketState: item.BucketState,
}
switch item.Type {
case models.TimelineItemTypeEvent:
wi.Type = "event"
case models.TimelineItemTypeMeal:
wi.Type = "event"
case models.TimelineItemTypeCard:
wi.Type = "task"
wi.Completable = true
case models.TimelineItemTypeGTask:
wi.Type = "task"
wi.Completable = true
default:
wi.Type = "task"
wi.Completable = item.Source == "doot"
}
// Only populate Start/End for items with a real time. All-day CALENDAR
// EVENTS (not undated doot/gtask tasks, which are also flagged IsAllDay
// as a "no specific time" fallback -- see TimelineItem.ComputeDaySection)
// get Start populated too, using their real event date, so the widget
// client can pin them to the top of the correct day's section instead of
// losing them in the floating-task hourly-slot packer, which has no
// concept of "all day" and can push a slot past the visible grid range
// entirely.
//
// Dated Task/GTask items (item.Undated == false) get the same Start
// treatment as Events, for the same reason -- their client-side day
// bucketing (Android's WidgetRoot todayScheduledEvents/tomorrowItems
// split) is keyed entirely off Start, so a nil Start drops them into the
// undated/floating pool regardless of their actual due date. That pool
// has zero day-awareness (see DootWidget.kt's `floating` list), so a
// task due tomorrow rendered as if due today (2026-08-10 report). This
// is deliberately gated on Undated, not IsAllDay -- IsAllDay stays true
// for these tasks (doot-native/Google Tasks due dates are ALWAYS
// midnight-anchored even with a real due date, see
// reference_google_tasks_due_date_utc_quirk), which is why the simpler
// "just check IsAllDay" fix doesn't work here: Card and truly-undated
// Task/GTask items must keep the exact opposite behavior (nil Start),
// and only Undated tells them apart.
isDatedTask := (item.Type == models.TimelineItemTypeTask || item.Type == models.TimelineItemTypeGTask) && !item.Undated
if !item.Time.IsZero() && (!item.IsAllDay || item.Type == models.TimelineItemTypeEvent || isDatedTask) {
t := item.Time
wi.Start = &t
if item.Type == models.TimelineItemTypeEvent {
// Events always forward End when known, even when IsAllDay --
// a multi-day all-day event (e.g. a 3-day conference) needs its
// End date reaching the client so it can detect the span and
// render "starts"/"ends"/spans-through labels per rendered day.
if item.EndTime != nil {
wi.End = item.EndTime
}
} else if !item.IsAllDay {
if item.EndTime != nil {
wi.End = item.EndTime
} else {
end := item.Time.Add(time.Hour)
wi.End = &end
}
}
}
// DueDate is a separate signal from Start/IsAllDay -- populated whenever
// a doot task genuinely has a due date (Undated == false), regardless of
// whether Start also got set above, so the Android detail popup can
// display/reschedule it. Guarding on !item.Undated (not just
// !item.Time.IsZero()) matters because nativeUndated tasks use Time=now
// as a layout placeholder, not a zero value -- without this guard,
// an undated task's detail popup would show a fabricated "due" date of
// whatever moment the request happened to run.
if item.Type == models.TimelineItemTypeTask && item.Source == "doot" && !item.Time.IsZero() && !item.Undated {
due := item.Time
wi.DueDate = &due
}
if item.ProjectColor != "" {
wi.ProjectColor = &item.ProjectColor
}
return wi
}
// HandleWidgetGet returns today's timeline items as JSON for the Android widget.
func (h *Handler) HandleWidgetGet(w http.ResponseWriter, r *http.Request) {
now := config.Now()
tz := config.GetDisplayTimezone()
start := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, tz)
end := start.Add(48 * time.Hour)
items, err := BuildTimeline(r.Context(), h.store, start, end)
if err != nil {
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
widgetItems := make([]models.WidgetItem, 0, len(items))
for _, item := range items {
if item.DaySection == models.DaySectionToday ||
item.DaySection == models.DaySectionTomorrow ||
item.IsOverdue {
widgetItems = append(widgetItems, TimelineItemToWidgetItem(item))
}
}
budgetStatus, err := h.computeBudgetStatus(now)
if err != nil {
log.Printf("Warning: failed to compute budget status: %v", err)
}
resp := models.WidgetResponse{
Now: now,
Items: widgetItems,
BudgetStatus: budgetStatus,
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(resp)
}
// computeBudgetStatus returns budget status for "today" and a rolling
// 7-day "week" window starting today, or nil if no budget-tracked task
// falls in the week window (per the spec: the field is absent unless
// budget-tracked tasks exist, so an unconfigured user sees no new UI).
func (h *Handler) computeBudgetStatus(now time.Time) (*models.BudgetStatus, error) {
tz := config.GetDisplayTimezone()
todayStart := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, tz)
todayEnd := todayStart.Add(24 * time.Hour)
weekEnd := todayStart.AddDate(0, 0, 7)
blocks, err := h.store.GetAvailabilityBlocks()
if err != nil {
return nil, err
}
trackedProjects, err := h.store.GetBudgetTrackedProjectIDs()
if err != nil {
return nil, err
}
trackedLabels, err := h.store.GetBudgetTrackedLabelNames()
if err != nil {
return nil, err
}
events, err := h.store.GetCalendarEventsByDateRange(todayStart, weekEnd)
if err != nil {
return nil, err
}
overdue, err := h.store.GetOverdueNativeTasks(todayStart)
if err != nil {
return nil, err
}
weekTasks, err := h.store.GetNativeTasksByDateRange(todayStart, weekEnd)
if err != nil {
return nil, err
}
allTasks := append(append([]models.Task{}, overdue...), weekTasks...)
hasTracked := false
for _, task := range allTasks {
if isBudgetTracked(task, trackedProjects, trackedLabels) && !task.Completed {
hasTracked = true
break
}
}
if !hasTracked {
return nil, nil
}
today := ComputeBudgetPeriod(blocks, events, allTasks, trackedProjects, trackedLabels, todayStart, todayEnd)
week := ComputeBudgetPeriod(blocks, events, allTasks, trackedProjects, trackedLabels, todayStart, weekEnd)
return &models.BudgetStatus{Today: today, Week: week}, nil
}
type widgetCompleteRequest struct {
ID string `json:"id"`
Source string `json:"source"`
}
type widgetAddRequest struct {
Title string `json:"title"`
}
type widgetRescheduleRequest struct {
ID string `json:"id"`
Source string `json:"source"`
Date string `json:"date"` // YYYY-MM-DD
}
// HandleWidgetReschedule updates the due date of a native task.
func (h *Handler) HandleWidgetReschedule(w http.ResponseWriter, r *http.Request) {
var req widgetRescheduleRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
if req.Source != "doot" {
http.Error(w, "only doot tasks can be rescheduled via widget", http.StatusBadRequest)
return
}
parsed, err := time.Parse("2006-01-02", req.Date)
if err != nil {
http.Error(w, "invalid date", http.StatusBadRequest)
return
}
tz := config.GetDisplayTimezone()
dueDate := time.Date(parsed.Year(), parsed.Month(), parsed.Day(), 0, 0, 0, 0, tz)
if err := h.store.RescheduleNativeTask(req.ID, dueDate); err != nil {
if errors.Is(err, store.ErrNativeTaskNotFound) {
http.Error(w, "task not found", http.StatusNotFound)
return
}
http.Error(w, "failed to reschedule", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
// findGoogleTask looks up a cached Google Task by ID.
func (h *Handler) findGoogleTask(id string) (models.GoogleTask, bool) {
gTasks, err := h.store.GetGoogleTasks()
if err != nil {
return models.GoogleTask{}, false
}
for _, t := range gTasks {
if t.ID == id {
return t, true
}
}
return models.GoogleTask{}, false
}
// findCard looks up a cached Trello card by ID.
func (h *Handler) findCard(id string) (models.Card, bool) {
boards, err := h.store.GetBoards()
if err != nil {
return models.Card{}, false
}
for _, b := range boards {
for _, c := range b.Cards {
if c.ID == id {
return c, true
}
}
}
return models.Card{}, false
}
type widgetDetailResponse struct {
Title string `json:"title"`
Description string `json:"description"`
Editable bool `json:"editable"`
}
// HandleWidgetDetail returns a task's title/description for the widget's edit popup.
func (h *Handler) HandleWidgetDetail(w http.ResponseWriter, r *http.Request) {
id := r.URL.Query().Get("id")
source := r.URL.Query().Get("source")
if id == "" || source == "" {
http.Error(w, "missing id or source", http.StatusBadRequest)
return
}
var resp widgetDetailResponse
switch source {
case "doot":
tasks, err := h.store.GetNativeTasks()
if err != nil {
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
for _, t := range tasks {
if t.ID == id {
resp = widgetDetailResponse{Title: t.Content, Description: t.Description, Editable: true}
break
}
}
case "gtasks":
if t, ok := h.findGoogleTask(id); ok {
resp = widgetDetailResponse{Title: t.Title, Description: t.Notes, Editable: h.googleTasksClient != nil}
}
case "trello":
if c, ok := h.findCard(id); ok {
resp = widgetDetailResponse{Title: c.Name, Description: c.Description, Editable: h.trelloClient != nil}
}
default:
http.Error(w, "unsupported source", http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(resp)
}
type widgetUpdateRequest struct {
ID string `json:"id"`
Source string `json:"source"`
Description string `json:"description"`
}
// HandleWidgetUpdate saves an edited description from the widget's edit popup.
func (h *Handler) HandleWidgetUpdate(w http.ResponseWriter, r *http.Request) {
var req widgetUpdateRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
switch req.Source {
case "doot":
if err := h.store.UpdateNativeTaskDescription(req.ID, req.Description); err != nil {
http.Error(w, "failed to update task", http.StatusInternalServerError)
return
}
case "gtasks":
if h.googleTasksClient == nil {
http.Error(w, "google tasks not configured", http.StatusServiceUnavailable)
return
}
t, ok := h.findGoogleTask(req.ID)
if !ok {
http.Error(w, "task not found", http.StatusNotFound)
return
}
if err := h.googleTasksClient.UpdateTaskNotes(r.Context(), t.ListID, req.ID, req.Description); err != nil {
http.Error(w, "failed to update task", http.StatusInternalServerError)
return
}
_ = h.store.InvalidateCache(store.CacheKeyGoogleTasks)
case "trello":
if h.trelloClient == nil {
http.Error(w, "trello not configured", http.StatusServiceUnavailable)
return
}
if err := h.trelloClient.UpdateCard(r.Context(), req.ID, map[string]interface{}{"desc": req.Description}); err != nil {
http.Error(w, "failed to update task", http.StatusInternalServerError)
return
}
_ = h.store.InvalidateCache(store.CacheKeyTrelloBoards)
default:
http.Error(w, "source not editable", http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusOK)
}
// HandleWidgetComplete proxies a task completion to the source API or native store.
func (h *Handler) HandleWidgetComplete(w http.ResponseWriter, r *http.Request) {
var req widgetCompleteRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
switch req.Source {
case "doot":
if err := h.store.CompleteNativeTask(req.ID); err != nil {
if errors.Is(err, store.ErrNativeTaskNotFound) {
// Surfaced as 404 (not a silent 200) so the caller -- the
// Android widget -- can tell "nothing changed" apart from
// "it worked", instead of the previous behavior where a
// stale/wrong id looked identical to a real completion.
http.Error(w, "task not found", http.StatusNotFound)
return
}
if errors.Is(err, store.ErrChainTaskLocked) {
http.Error(w, "task is locked in its chain", http.StatusBadRequest)
return
}
http.Error(w, "failed to complete task", http.StatusInternalServerError)
return
}
_ = h.store.SaveCompletedTask("doot", req.ID, "", nil)
case "gtasks":
if h.googleTasksClient == nil {
http.Error(w, "google tasks not configured", http.StatusServiceUnavailable)
return
}
t, ok := h.findGoogleTask(req.ID)
if !ok {
http.Error(w, "task not found", http.StatusNotFound)
return
}
if err := h.googleTasksClient.CompleteTask(r.Context(), t.ListID, req.ID); err != nil {
http.Error(w, "failed to complete task", http.StatusInternalServerError)
return
}
_ = h.store.SaveCompletedTask("gtasks", req.ID, t.Title, t.DueDate)
_ = h.store.InvalidateCache(store.CacheKeyGoogleTasks)
case "trello":
if h.trelloClient == nil {
http.Error(w, "trello not configured", http.StatusServiceUnavailable)
return
}
c, ok := h.findCard(req.ID)
if !ok {
http.Error(w, "task not found", http.StatusNotFound)
return
}
if err := h.trelloClient.UpdateCard(r.Context(), req.ID, map[string]interface{}{"closed": true}); err != nil {
http.Error(w, "failed to complete task", http.StatusInternalServerError)
return
}
_ = h.store.SaveCompletedTask("trello", req.ID, c.Name, c.DueDate)
_ = h.store.DeleteCard(req.ID)
default:
http.Error(w, "source not completable", http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusOK)
}
type widgetAddResponse struct {
ID string `json:"id"`
}
// HandleWidgetAdd creates a new undated native task from the widget's quick-add
// sheet and returns its id, so the client can follow up with the same
// project/labels/recurrence/due-date setter calls the edit popup uses.
func (h *Handler) HandleWidgetAdd(w http.ResponseWriter, r *http.Request) {
var req widgetAddRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
title := strings.TrimSpace(req.Title)
if title == "" {
http.Error(w, "title is required", http.StatusBadRequest)
return
}
task := models.Task{
ID: newID(),
Content: title,
Priority: 1,
}
if err := h.store.CreateNativeTask(task); err != nil {
http.Error(w, "failed to create task", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(widgetAddResponse{ID: task.ID})
}
type recurrenceResponse struct {
Freq string `json:"freq"`
Interval int `json:"interval"`
Weekdays []int `json:"weekdays,omitempty"`
}
type projectResponse struct {
ID string `json:"id"`
Name string `json:"name"`
Color string `json:"color"`
CreatedAt time.Time `json:"created_at"`
}
func projectToResponse(p models.Project) projectResponse {
return projectResponse{ID: p.ID, Name: p.Name, Color: p.Color, CreatedAt: p.CreatedAt}
}
// HandleWidgetProjectsGet returns all non-archived projects.
func (h *Handler) HandleWidgetProjectsGet(w http.ResponseWriter, r *http.Request) {
projects, err := h.store.GetProjects()
if err != nil {
http.Error(w, "failed to load projects", http.StatusInternalServerError)
return
}
resp := make([]projectResponse, 0, len(projects))
for _, p := range projects {
resp = append(resp, projectToResponse(p))
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(resp)
}
type projectCreateRequest struct {
Name string `json:"name"`
Color string `json:"color"`
}
// HandleWidgetProjectsCreate creates a new project.
func (h *Handler) HandleWidgetProjectsCreate(w http.ResponseWriter, r *http.Request) {
var req projectCreateRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
if req.Name == "" || req.Color == "" {
http.Error(w, "name and color are required", http.StatusBadRequest)
return
}
project, err := h.store.CreateProject(req.Name, req.Color)
if err != nil {
http.Error(w, "failed to create project", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(projectToResponse(*project))
}
type taskProjectRequest struct {
ID string `json:"id"`
ProjectID string `json:"project_id"`
}
// HandleWidgetTaskProject sets or clears a task's project.
func (h *Handler) HandleWidgetTaskProject(w http.ResponseWriter, r *http.Request) {
var req taskProjectRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
if req.ID == "" {
http.Error(w, "id is required", http.StatusBadRequest)
return
}
if err := h.store.SetTaskProject(req.ID, req.ProjectID); err != nil {
if errors.Is(err, store.ErrNativeTaskNotFound) {
http.Error(w, "task not found", http.StatusNotFound)
return
}
http.Error(w, "failed to set project", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
type taskLabelsRequest struct {
ID string `json:"id"`
Labels []string `json:"labels"`
}
// HandleWidgetTaskLabels replaces a task's label set.
func (h *Handler) HandleWidgetTaskLabels(w http.ResponseWriter, r *http.Request) {
var req taskLabelsRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
if req.ID == "" {
http.Error(w, "id is required", http.StatusBadRequest)
return
}
if err := h.store.SetTaskLabels(req.ID, req.Labels); err != nil {
if errors.Is(err, store.ErrNativeTaskNotFound) {
http.Error(w, "task not found", http.StatusNotFound)
return
}
http.Error(w, "failed to set labels", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
type labelColorResponse struct {
Name string `json:"name"`
Color string `json:"color"`
}
// HandleWidgetLabelsGet returns every label that has an assigned color.
func (h *Handler) HandleWidgetLabelsGet(w http.ResponseWriter, r *http.Request) {
colors, err := h.store.GetLabelColors()
if err != nil {
http.Error(w, "failed to load label colors", http.StatusInternalServerError)
return
}
resp := make([]labelColorResponse, 0, len(colors))
for _, c := range colors {
resp = append(resp, labelColorResponse{Name: c.Name, Color: c.Color})
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(resp)
}
type labelColorSetRequest struct {
Name string `json:"name"`
Color string `json:"color"`
}
// HandleWidgetLabelsColorSet assigns a label's display color.
func (h *Handler) HandleWidgetLabelsColorSet(w http.ResponseWriter, r *http.Request) {
var req labelColorSetRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
if req.Name == "" || req.Color == "" {
http.Error(w, "name and color are required", http.StatusBadRequest)
return
}
if err := h.store.SetLabelColor(req.Name, req.Color); err != nil {
http.Error(w, "failed to set label color", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
type taskDetailResponse struct {
ID string `json:"id"`
Title string `json:"title"`
Description string `json:"description"`
DueDate *time.Time `json:"due_date,omitempty"`
Completed bool `json:"completed"`
Recurrence *recurrenceResponse `json:"recurrence,omitempty"`
NextDate *time.Time `json:"next_date,omitempty"`
Project *projectResponse `json:"project,omitempty"`
Labels []string `json:"labels,omitempty"`
EstimatedMinutes int `json:"estimated_minutes,omitempty"`
SuggestedEstimateMinutes *int `json:"suggested_estimate_minutes,omitempty"`
}
// HandleWidgetTaskDetail returns full detail for a single doot-native task,
// including its recurrence pattern and computed next-occurrence date.
func (h *Handler) HandleWidgetTaskDetail(w http.ResponseWriter, r *http.Request) {
id := r.URL.Query().Get("id")
source := r.URL.Query().Get("source")
if id == "" || source != "doot" {
http.Error(w, "id required and source must be doot", http.StatusBadRequest)
return
}
task, err := h.store.GetNativeTaskByID(id)
if err != nil {
if errors.Is(err, store.ErrNativeTaskNotFound) {
http.Error(w, "task not found", http.StatusNotFound)
return
}
http.Error(w, "failed to load task", http.StatusInternalServerError)
return
}
resp := taskDetailResponse{
ID: task.ID,
Title: task.Content,
Description: task.Description,
DueDate: task.DueDate,
Completed: task.Completed,
Labels: task.Labels,
}
if task.ProjectID != "" {
if project, err := h.store.GetProjectByID(task.ProjectID); err == nil {
resp.Project = &projectResponse{ID: project.ID, Name: project.Name, Color: project.Color}
}
}
if task.RecurrenceSeriesID != "" {
resp.Recurrence = &recurrenceResponse{
Freq: task.RecurrenceFreq,
Interval: task.RecurrenceInterval,
Weekdays: task.RecurrenceWeekdays,
}
if task.NextOccurrenceOverride != nil {
resp.NextDate = task.NextOccurrenceOverride
} else if task.DueDate != nil {
next := models.ComputeNextOccurrence(*task.DueDate, task.RecurrenceFreq, task.RecurrenceInterval, task.RecurrenceWeekdays)
resp.NextDate = &next
}
}
resp.EstimatedMinutes = task.EstimatedMinutes
if task.EstimatedMinutes == 0 {
if task.ProjectID != "" {
if avg, ok, err := h.store.AverageEstimateForProject(task.ProjectID); err == nil && ok {
resp.SuggestedEstimateMinutes = &avg
}
}
if resp.SuggestedEstimateMinutes == nil {
for _, label := range task.Labels {
if avg, ok, err := h.store.AverageEstimateForLabel(label); err == nil && ok {
resp.SuggestedEstimateMinutes = &avg
break
}
}
}
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(resp)
}
type taskUpdateRequest struct {
ID string `json:"id"`
Title string `json:"title"`
Description string `json:"description"`
}
// HandleWidgetTaskUpdate updates a doot-native task's title and description.
func (h *Handler) HandleWidgetTaskUpdate(w http.ResponseWriter, r *http.Request) {
var req taskUpdateRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
if req.ID == "" || req.Title == "" {
http.Error(w, "id and title are required", http.StatusBadRequest)
return
}
if err := h.store.UpdateNativeTask(req.ID, req.Title, req.Description); err != nil {
if errors.Is(err, store.ErrNativeTaskNotFound) {
http.Error(w, "task not found", http.StatusNotFound)
return
}
http.Error(w, "failed to update task", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
type taskRecurrenceRequest struct {
ID string `json:"id"`
Freq string `json:"freq"`
Interval int `json:"interval"`
Weekdays []int `json:"weekdays"`
}
// HandleWidgetTaskRecurrence sets or clears a doot-native task's recurrence
// pattern. freq == "" clears recurrence.
func (h *Handler) HandleWidgetTaskRecurrence(w http.ResponseWriter, r *http.Request) {
var req taskRecurrenceRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
if req.ID == "" {
http.Error(w, "id is required", http.StatusBadRequest)
return
}
if req.Freq != "" && req.Freq != "daily" && req.Freq != "weekly" && req.Freq != "monthly" && req.Freq != "yearly" {
http.Error(w, "invalid freq", http.StatusBadRequest)
return
}
if err := h.store.SetTaskRecurrence(req.ID, req.Freq, req.Interval, req.Weekdays); err != nil {
if errors.Is(err, store.ErrNativeTaskNotFound) {
http.Error(w, "task not found", http.StatusNotFound)
return
}
http.Error(w, "failed to update recurrence", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
type taskNextDateRequest struct {
ID string `json:"id"`
Date string `json:"date"` // YYYY-MM-DD
}
// HandleWidgetTaskNextDate sets a one-shot override for a recurring task's
// next occurrence. 400 if the task has no active recurrence.
func (h *Handler) HandleWidgetTaskNextDate(w http.ResponseWriter, r *http.Request) {
var req taskNextDateRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
parsed, err := time.Parse("2006-01-02", req.Date)
if err != nil {
http.Error(w, "invalid date", http.StatusBadRequest)
return
}
task, err := h.store.GetNativeTaskByID(req.ID)
if err != nil {
if errors.Is(err, store.ErrNativeTaskNotFound) {
http.Error(w, "task not found", http.StatusNotFound)
return
}
http.Error(w, "failed to load task", http.StatusInternalServerError)
return
}
if task.RecurrenceSeriesID == "" {
http.Error(w, "task has no active recurrence", http.StatusBadRequest)
return
}
tz := config.GetDisplayTimezone()
dueDate := time.Date(parsed.Year(), parsed.Month(), parsed.Day(), 0, 0, 0, 0, tz)
if err := h.store.SetNextOccurrenceOverride(req.ID, dueDate); err != nil {
http.Error(w, "failed to set next date", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
type availabilityBlockResponse struct {
ID string `json:"id"`
Weekday int `json:"weekday"`
StartTime string `json:"start_time"`
EndTime string `json:"end_time"`
Label string `json:"label"`
}
func availabilityBlockToResponse(b models.AvailabilityBlock) availabilityBlockResponse {
return availabilityBlockResponse{ID: b.ID, Weekday: b.Weekday, StartTime: b.StartTime, EndTime: b.EndTime, Label: b.Label}
}
// HandleWidgetAvailabilityGet returns every configured availability block.
func (h *Handler) HandleWidgetAvailabilityGet(w http.ResponseWriter, r *http.Request) {
blocks, err := h.store.GetAvailabilityBlocks()
if err != nil {
http.Error(w, "failed to load availability", http.StatusInternalServerError)
return
}
resp := make([]availabilityBlockResponse, 0, len(blocks))
for _, b := range blocks {
resp = append(resp, availabilityBlockToResponse(b))
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(resp)
}
type availabilityCreateRequest struct {
Weekday int `json:"weekday"`
StartTime string `json:"start_time"`
EndTime string `json:"end_time"`
Label string `json:"label"`
}
// HandleWidgetAvailabilityCreate creates a new weekly availability block.
func (h *Handler) HandleWidgetAvailabilityCreate(w http.ResponseWriter, r *http.Request) {
var req availabilityCreateRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
if req.Weekday < 0 || req.Weekday > 6 || req.StartTime == "" || req.EndTime == "" {
http.Error(w, "weekday (0-6), start_time, and end_time are required", http.StatusBadRequest)
return
}
block, err := h.store.CreateAvailabilityBlock(req.Weekday, req.StartTime, req.EndTime, req.Label)
if err != nil {
http.Error(w, "failed to create availability block", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(availabilityBlockToResponse(*block))
}
type availabilityDeleteRequest struct {
ID string `json:"id"`
}
// HandleWidgetAvailabilityDelete deletes an availability block.
func (h *Handler) HandleWidgetAvailabilityDelete(w http.ResponseWriter, r *http.Request) {
var req availabilityDeleteRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
if err := h.store.DeleteAvailabilityBlock(req.ID); err != nil {
if errors.Is(err, store.ErrNativeTaskNotFound) {
http.Error(w, "availability block not found", http.StatusNotFound)
return
}
http.Error(w, "failed to delete availability block", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
type taskEstimateRequest struct {
ID string `json:"id"`
EstimatedMinutes int `json:"estimated_minutes"`
}
// HandleWidgetTaskEstimate sets a task's estimated duration in minutes.
func (h *Handler) HandleWidgetTaskEstimate(w http.ResponseWriter, r *http.Request) {
var req taskEstimateRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
if req.ID == "" {
http.Error(w, "id is required", http.StatusBadRequest)
return
}
if err := h.store.SetTaskEstimate(req.ID, req.EstimatedMinutes); err != nil {
if errors.Is(err, store.ErrNativeTaskNotFound) {
http.Error(w, "task not found", http.StatusNotFound)
return
}
http.Error(w, "failed to set estimate", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
type projectBudgetTrackedRequest struct {
ID string `json:"id"`
Tracked bool `json:"tracked"`
}
// HandleWidgetProjectsBudgetTracked opts a project in or out of budget tracking.
func (h *Handler) HandleWidgetProjectsBudgetTracked(w http.ResponseWriter, r *http.Request) {
var req projectBudgetTrackedRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
if req.ID == "" {
http.Error(w, "id is required", http.StatusBadRequest)
return
}
if err := h.store.SetProjectBudgetTracked(req.ID, req.Tracked); err != nil {
if errors.Is(err, store.ErrNativeTaskNotFound) {
http.Error(w, "project not found", http.StatusNotFound)
return
}
http.Error(w, "failed to update project", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
type labelBudgetTrackedRequest struct {
Name string `json:"name"`
Tracked bool `json:"tracked"`
}
// HandleWidgetLabelsBudgetTracked opts a label in or out of budget tracking.
func (h *Handler) HandleWidgetLabelsBudgetTracked(w http.ResponseWriter, r *http.Request) {
var req labelBudgetTrackedRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
if req.Name == "" {
http.Error(w, "name is required", http.StatusBadRequest)
return
}
if err := h.store.SetLabelBudgetTracked(req.Name, req.Tracked); err != nil {
http.Error(w, "failed to update label", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
type chainCreateRequest struct {
Name string `json:"name"`
Tasks []models.ChainTaskInput `json:"tasks"`
}
type chainCreateResponse struct {
ID string `json:"id"`
}
// HandleWidgetChainsCreate creates a linear task chain: a backing project
// plus one native_tasks row per entry in req.Tasks (content required;
// description and priority optional, priority defaulting to 1), position 0
// unlocked and due now, the rest locked with no due date.
func (h *Handler) HandleWidgetChainsCreate(w http.ResponseWriter, r *http.Request) {
var req chainCreateRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
if strings.TrimSpace(req.Name) == "" || len(req.Tasks) == 0 {
http.Error(w, "name and at least one task are required", http.StatusBadRequest)
return
}
for _, t := range req.Tasks {
if strings.TrimSpace(t.Content) == "" {
http.Error(w, "every task requires non-empty content", http.StatusBadRequest)
return
}
}
chain, err := h.store.CreateChain(req.Name, req.Tasks)
if err != nil {
http.Error(w, "failed to create chain", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(chainCreateResponse{ID: chain.ID})
}
// handleWidgetChainSetStatus is the shared body for pause/resume/abandon --
// each just sets a different status string on the chain named by the {id}
// URL param.
func (h *Handler) handleWidgetChainSetStatus(w http.ResponseWriter, r *http.Request, status string) {
id := chi.URLParam(r, "id")
if err := h.store.SetChainStatus(id, status); err != nil {
if errors.Is(err, store.ErrNativeTaskNotFound) {
http.Error(w, "chain not found", http.StatusNotFound)
return
}
http.Error(w, "failed to update chain", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
// HandleWidgetChainsPause pauses a chain: the currently-unlocked task stays
// actionable, but completing it will not auto-advance until resumed.
func (h *Handler) HandleWidgetChainsPause(w http.ResponseWriter, r *http.Request) {
h.handleWidgetChainSetStatus(w, r, "paused")
}
// HandleWidgetChainsResume reactivates a paused chain.
func (h *Handler) HandleWidgetChainsResume(w http.ResponseWriter, r *http.Request) {
h.handleWidgetChainSetStatus(w, r, "active")
}
// HandleWidgetChainsAbandon marks a chain abandoned -- a terminal state
// distinguishable from "completed" in queries/reporting.
func (h *Handler) HandleWidgetChainsAbandon(w http.ResponseWriter, r *http.Request) {
h.handleWidgetChainSetStatus(w, r, "abandoned")
}
type chainGetResponse struct {
Chain models.Chain `json:"chain"`
Tasks []models.Task `json:"tasks"`
}
// HandleWidgetChainGet returns the full ordered checklist for a chain --
// locked and unlocked tasks both, per the design's "visible in the tasks
// list" requirement met via this dedicated surface.
func (h *Handler) HandleWidgetChainGet(w http.ResponseWriter, r *http.Request) {
id := chi.URLParam(r, "id")
chain, err := h.store.GetChain(id)
if err != nil {
if errors.Is(err, store.ErrNativeTaskNotFound) {
http.Error(w, "chain not found", http.StatusNotFound)
return
}
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
tasks, err := h.store.GetChainTasks(id)
if err != nil {
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(chainGetResponse{Chain: *chain, Tasks: tasks})
}
type bucketCreateRequest struct {
Name string `json:"name"`
CycleDays int `json:"cycle_days"`
PickN int `json:"pick_n"`
}
// HandleWidgetBucketsGet returns every maintenance bucket.
func (h *Handler) HandleWidgetBucketsGet(w http.ResponseWriter, r *http.Request) {
buckets, err := h.store.GetBuckets()
if err != nil {
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(buckets)
}
// HandleWidgetBucketsCreate creates a new maintenance bucket.
func (h *Handler) HandleWidgetBucketsCreate(w http.ResponseWriter, r *http.Request) {
var req bucketCreateRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
if strings.TrimSpace(req.Name) == "" || req.CycleDays <= 0 || req.PickN <= 0 {
http.Error(w, "name, a positive cycle_days, and a positive pick_n are required", http.StatusBadRequest)
return
}
bucket, err := h.store.CreateBucket(req.Name, req.CycleDays, req.PickN)
if err != nil {
http.Error(w, "failed to create bucket", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(bucket)
}
type bucketItemRequest struct {
TaskID string `json:"task_id"`
}
// HandleWidgetBucketItemsAdd assigns an existing task to a bucket's pool.
func (h *Handler) HandleWidgetBucketItemsAdd(w http.ResponseWriter, r *http.Request) {
bucketID := chi.URLParam(r, "id")
var req bucketItemRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
if err := h.store.AddBucketItem(bucketID, req.TaskID); err != nil {
if errors.Is(err, store.ErrNativeTaskNotFound) {
http.Error(w, "task not found", http.StatusNotFound)
return
}
http.Error(w, "failed to add bucket item", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
// HandleWidgetBucketItemsRemove clears a task's bucket membership.
func (h *Handler) HandleWidgetBucketItemsRemove(w http.ResponseWriter, r *http.Request) {
var req bucketItemRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
if err := h.store.RemoveBucketItem(req.TaskID); err != nil {
if errors.Is(err, store.ErrNativeTaskNotFound) {
http.Error(w, "task not found", http.StatusNotFound)
return
}
http.Error(w, "failed to remove bucket item", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
type taskDeferRequest struct {
ID string `json:"id"`
}
// HandleWidgetTaskDefer returns an active bucket item to its pool without
// crediting it as done -- distinct from Complete -- and triggers a fresh
// selection to backfill the freed slot.
func (h *Handler) HandleWidgetTaskDefer(w http.ResponseWriter, r *http.Request) {
var req taskDeferRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
if err := h.store.DeferNativeTask(req.ID); err != nil {
if errors.Is(err, store.ErrNativeTaskNotFound) {
http.Error(w, "task not found or not an active bucket item", http.StatusNotFound)
return
}
http.Error(w, "failed to defer task", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
|