From 9a87f9db5af943ea253b814d4196020341e3c2ba Mon Sep 17 00:00:00 2001 From: Peter Stone Date: Sun, 12 Jul 2026 05:36:32 +0000 Subject: fix(widget): surface unmatched task IDs instead of silently no-opping CompleteNativeTask/UncompleteNativeTask/RescheduleNativeTask ran a plain UPDATE ... WHERE id = ? and returned whatever error Exec gave back -- which is nil even when 0 rows match, since that's not a SQL error. A stale or wrong id from the widget looked identical to a real completion: HTTP 200, nothing changed in the database. Real incident: 1 of 3 widget completeTask taps silently no-opped this way. Now checks RowsAffected() and returns ErrNativeTaskNotFound (mirrors the existing pattern in sqlite.go's ApproveAgentSession/DenyAgentSession). HandleWidgetComplete and HandleWidgetReschedule surface this as 404 instead of a fake 200, so the widget can tell 'nothing changed' apart from 'it worked.' --- internal/handlers/widget.go | 14 ++++++++++++++ 1 file changed, 14 insertions(+) (limited to 'internal/handlers/widget.go') diff --git a/internal/handlers/widget.go b/internal/handlers/widget.go index 876aaad..6c3b455 100644 --- a/internal/handlers/widget.go +++ b/internal/handlers/widget.go @@ -2,12 +2,14 @@ package handlers import ( "encoding/json" + "errors" "net/http" "strings" "time" "task-dashboard/internal/config" "task-dashboard/internal/models" + "task-dashboard/internal/store" ) // WidgetAuthMiddleware validates the static bearer token for widget API endpoints. @@ -126,6 +128,10 @@ func (h *Handler) HandleWidgetReschedule(w http.ResponseWriter, r *http.Request) 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 } @@ -143,6 +149,14 @@ func (h *Handler) HandleWidgetComplete(w http.ResponseWriter, r *http.Request) { 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 + } http.Error(w, "failed to complete task", http.StatusInternalServerError) return } -- cgit v1.2.3 From 84252756c687044d73a0ea5cebf8088c7c9ed3e8 Mon Sep 17 00:00:00 2001 From: Peter Stone Date: Sun, 12 Jul 2026 06:21:40 +0000 Subject: fix(widget): pin all-day calendar events to the top instead of losing them WidgetItem.isAllDay was carried by the client's data model but nothing ever read it. All-day events had no Start at all, so they fell into the same floating-task queue as ordinary untimed tasks; if enough tasks were ahead of one in the queue, SlotPacker could assign it an hour slot past the visible grid range entirely -- not merely unpinned, actually invisible. Server: TimelineItemToWidgetItem now populates Start for all-day CALENDAR EVENTS specifically (their real event date), while leaving undated doot/gtask tasks -- also flagged IsAllDay as a "no specific time" fallback, a different concept -- on the existing nil-Start floating behavior. Client: all-day events are filtered out of the hourly grid/floating-task pipeline entirely, bucketed by day using the new Start date, and rendered in a new pinned AllDayRow section right after the TODAY/TOMORROW headers. --- .../java/org/terst/doot/widget/ui/DootWidget.kt | 60 ++++++++++++++++++--- internal/handlers/widget.go | 25 ++++++--- internal/handlers/widget_test.go | 61 ++++++++++++++++++++++ 3 files changed, 132 insertions(+), 14 deletions(-) (limited to 'internal/handlers/widget.go') diff --git a/android/app/src/main/java/org/terst/doot/widget/ui/DootWidget.kt b/android/app/src/main/java/org/terst/doot/widget/ui/DootWidget.kt index d8f1140..7674ddb 100644 --- a/android/app/src/main/java/org/terst/doot/widget/ui/DootWidget.kt +++ b/android/app/src/main/java/org/terst/doot/widget/ui/DootWidget.kt @@ -63,17 +63,39 @@ class DootWidget : GlanceAppWidget() { fun WidgetRoot(items: List, now: Instant) { val zone = ZoneId.systemDefault() val nowZoned: ZonedDateTime = now.atZone(zone) - val allScheduled = items.filter { it.start != null }.sortedBy { Instant.parse(it.start!!) } + val todayStart = nowZoned.toLocalDate().atStartOfDay(zone).toInstant() + val tomorrowStart = nowZoned.toLocalDate().plusDays(1).atStartOfDay(zone).toInstant() + val tomorrowEnd = tomorrowStart.plus(1, ChronoUnit.DAYS) + + // All-day CALENDAR EVENTS (isAllDay && type == "event" -- see + // TimelineItemToWidgetItem's doc comment for why undated doot/gtask + // tasks, which are also flagged isAllDay, are deliberately excluded + // here) are pinned to the top of their day's section and never compete + // for hourly grid slots or floating-task packing. Previously they had + // no Start at all and fell into the same floating-task queue as + // ordinary untimed tasks, where enough tasks ahead of them in the queue + // could push their assigned slot past the visible grid range entirely + // -- not merely unpinned, actually invisible. + val allDayEvents = items.filter { it.isAllDay && it.type == "event" } + val rest = items.filter { !(it.isAllDay && it.type == "event") } + val todayAllDay = allDayEvents.filter { item -> + val s = item.start?.let { runCatching { Instant.parse(it) }.getOrNull() } + s == null || (s >= todayStart && s < tomorrowStart) + } + val tomorrowAllDay = allDayEvents.filter { item -> + val s = item.start?.let { runCatching { Instant.parse(it) }.getOrNull() } + s != null && s >= tomorrowStart && s < tomorrowEnd + } + + val allScheduled = rest.filter { it.start != null }.sortedBy { Instant.parse(it.start!!) } // Past tasks float at now (before untimed tasks); past events stay in the grid at 50% alpha val pastTasks = allScheduled.filter { it.type == "task" && Instant.parse(it.start!!) < now } val scheduledEvents = allScheduled.filter { it.type != "task" || Instant.parse(it.start!!) >= now } - val floating = items.filter { it.start == null } + val floating = rest.filter { it.start == null } val fragments = SlotPacker.pack(pastTasks + floating, scheduledEvents, now) val gridStart = calcGridStart(scheduledEvents, nowZoned.hour) val gridEnd = calcGridEnd(scheduledEvents, nowZoned.hour) - val tomorrowStart = nowZoned.toLocalDate().plusDays(1).atStartOfDay(zone).toInstant() - val tomorrowEnd = tomorrowStart.plus(1, ChronoUnit.DAYS) val tomorrowItems = scheduledEvents .filter { Instant.parse(it.start!!) >= tomorrowStart && Instant.parse(it.start!!) < tomorrowEnd } val tomorrowFrags = fragments @@ -96,16 +118,38 @@ fun WidgetRoot(items: List, now: Instant) { ) } + todayAllDay.forEach { AllDayRow(it) } + for (hour in gridStart..gridEnd) { HourRow(hour, nowZoned, scheduledEvents, fragments, zone) } - if (tomorrowItems.isNotEmpty() || tomorrowFrags.any { it.slots.isNotEmpty() }) { - TomorrowSection(tomorrowItems, tomorrowFrags, zone) + if (tomorrowItems.isNotEmpty() || tomorrowFrags.any { it.slots.isNotEmpty() } || tomorrowAllDay.isNotEmpty()) { + TomorrowSection(tomorrowItems, tomorrowFrags, tomorrowAllDay, zone) } } } +@Composable +fun AllDayRow(event: WidgetItem) { + val color = sourceColor(event.source) + Row( + modifier = GlanceModifier + .fillMaxWidth() + .padding(vertical = 3.dp) + .clickable(actionStartActivity(Intent(Intent.ACTION_VIEW, Uri.parse(event.url.ifEmpty { "https://calendar.google.com" })))), + verticalAlignment = Alignment.CenterVertically + ) { + Box(modifier = GlanceModifier.width(3.dp).height(16.dp).background(color)) {} + Text( + text = event.title, + style = TextStyle(color = ColorProvider(Color.White.copy(alpha = 0.9f)), fontSize = 13.sp, fontWeight = FontWeight.Medium), + modifier = GlanceModifier.padding(start = 8.dp), + maxLines = 1 + ) + } +} + @Composable fun HourRow( hour: Int, @@ -284,7 +328,7 @@ fun TaskRow(task: WidgetItem) { } @Composable -fun TomorrowSection(items: List, fragments: List, zone: ZoneId) { +fun TomorrowSection(items: List, fragments: List, allDayEvents: List, zone: ZoneId) { Box(modifier = GlanceModifier.fillMaxWidth().height(1.dp).padding(vertical = 4.dp).background(Color(0x1AFFFFFF))) {} Row(modifier = GlanceModifier.fillMaxWidth().padding(top = 6.dp, bottom = 2.dp)) { @@ -298,6 +342,8 @@ fun TomorrowSection(items: List, fragments: List, zone ) } + allDayEvents.forEach { AllDayRow(it) } + items.forEach { item -> val isPast = false if (item.type == "event") { diff --git a/internal/handlers/widget.go b/internal/handlers/widget.go index 6c3b455..dc10db6 100644 --- a/internal/handlers/widget.go +++ b/internal/handlers/widget.go @@ -52,15 +52,26 @@ func TimelineItemToWidgetItem(item models.TimelineItem) models.WidgetItem { wi.Completable = item.Source == "doot" } - // Only populate Start/End for items with a real time (non-all-day, non-zero) - if !item.IsAllDay && !item.Time.IsZero() { + // 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. Tasks keep the existing nil-Start "floating" treatment + // regardless of IsAllDay -- only Start is set for them (never End), and + // only when they have a real time. + if !item.Time.IsZero() && (!item.IsAllDay || item.Type == models.TimelineItemTypeEvent) { t := item.Time wi.Start = &t - if item.EndTime != nil { - wi.End = item.EndTime - } else { - end := item.Time.Add(time.Hour) - wi.End = &end + if !item.IsAllDay { + if item.EndTime != nil { + wi.End = item.EndTime + } else { + end := item.Time.Add(time.Hour) + wi.End = &end + } } } diff --git a/internal/handlers/widget_test.go b/internal/handlers/widget_test.go index 850dc07..6d741d2 100644 --- a/internal/handlers/widget_test.go +++ b/internal/handlers/widget_test.go @@ -109,6 +109,67 @@ func TestTimelineItemToWidgetItem_Event(t *testing.T) { } } +// TestTimelineItemToWidgetItem_AllDayEvent proves the 2026-07-12 fix: an +// all-day CALENDAR EVENT (Type == event, IsAllDay == true) must get Start +// populated with its real date -- previously Start was nil for every +// IsAllDay item regardless of type, which meant the widget client's +// hourly-slot packer had no date information to pin all-day events to the +// top of the correct day and they could silently fall outside the visible +// grid range instead. End stays nil since there's no meaningful end time to +// show for an all-day item. +func TestTimelineItemToWidgetItem_AllDayEvent(t *testing.T) { + day := time.Date(2026, 7, 12, 0, 0, 0, 0, time.Local) + item := models.TimelineItem{ + ID: "cal-holiday", + Title: "Company Holiday", + Source: "calendar", + Type: models.TimelineItemTypeEvent, + Time: day, + IsAllDay: true, + } + + wi := TimelineItemToWidgetItem(item) + + if wi.Type != "event" { + t.Errorf("Type: got %q, want %q", wi.Type, "event") + } + if !wi.IsAllDay { + t.Error("expected IsAllDay to be true") + } + if wi.Start == nil { + t.Fatal("all-day event should have non-nil Start (needed to pin it to the correct day)") + } + if !wi.Start.Equal(day) { + t.Errorf("Start = %v, want %v", *wi.Start, day) + } + if wi.End != nil { + t.Error("all-day event should have nil End") + } +} + +// TestTimelineItemToWidgetItem_AllDayTask_KeepsFloatingBehavior proves the +// same fix does NOT change behavior for undated doot/gtask tasks, which are +// also flagged IsAllDay as a "no specific time" fallback (see +// TimelineItem.ComputeDaySection) but are a different concept from a real +// all-day calendar event -- they must keep the existing nil-Start +// "floating" treatment so the hourly-slot packer still places them. +func TestTimelineItemToWidgetItem_AllDayTask_KeepsFloatingBehavior(t *testing.T) { + item := models.TimelineItem{ + ID: "undated-task", + Title: "Someday task", + Source: "doot", + Type: models.TimelineItemTypeTask, + Time: time.Now(), + IsAllDay: true, + } + + wi := TimelineItemToWidgetItem(item) + + if wi.Start != nil { + t.Error("an undated task (IsAllDay as a fallback, not a real all-day event) should still have nil Start") + } +} + func TestHandleWidgetComplete_NonCompletable(t *testing.T) { h := &Handler{} body := `{"id":"x","source":"calendar"}` -- cgit v1.2.3 From 3ada2fc17fd1bc8f4203eaa6fde2ea23d49b87a4 Mon Sep 17 00:00:00 2001 From: Peter Stone Date: Sun, 12 Jul 2026 09:48:34 +0000 Subject: feat(widget): forward IsOverdue from TimelineItem to WidgetItem API --- internal/handlers/widget.go | 11 ++++++----- internal/handlers/widget_test.go | 40 ++++++++++++++++++++++++++++++++++++++++ internal/models/widget.go | 1 + 3 files changed, 47 insertions(+), 5 deletions(-) (limited to 'internal/handlers/widget.go') diff --git a/internal/handlers/widget.go b/internal/handlers/widget.go index dc10db6..f8a63a0 100644 --- a/internal/handlers/widget.go +++ b/internal/handlers/widget.go @@ -32,11 +32,12 @@ func WidgetAuthMiddleware(token string, next http.Handler) http.Handler { // 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, - URL: item.URL, + ID: item.ID, + Title: item.Title, + Source: item.Source, + IsAllDay: item.IsAllDay, + IsOverdue: item.IsOverdue, + URL: item.URL, } switch item.Type { diff --git a/internal/handlers/widget_test.go b/internal/handlers/widget_test.go index 6d741d2..06e1749 100644 --- a/internal/handlers/widget_test.go +++ b/internal/handlers/widget_test.go @@ -170,6 +170,46 @@ func TestTimelineItemToWidgetItem_AllDayTask_KeepsFloatingBehavior(t *testing.T) } } +// TestTimelineItemToWidgetItem_ForwardsIsOverdue proves the 2026-07-12 +// overdue-badge fix: TimelineItem.IsOverdue (already computed correctly by +// ComputeDaySection, confirmed by the earlier fix that made overdue tasks +// appear in the timeline at all) must be forwarded onto WidgetItem so the +// Android client can render it distinctly -- previously it was silently +// dropped, so an overdue task looked identical to a normal one on the +// widget. +func TestTimelineItemToWidgetItem_ForwardsIsOverdue(t *testing.T) { + item := models.TimelineItem{ + ID: "overdue-1", + Title: "Pay the water bill", + Source: "doot", + Type: models.TimelineItemTypeTask, + Time: time.Now(), + IsOverdue: true, + } + + wi := TimelineItemToWidgetItem(item) + + if !wi.IsOverdue { + t.Error("expected IsOverdue to be forwarded as true") + } +} + +func TestTimelineItemToWidgetItem_NotOverdueByDefault(t *testing.T) { + item := models.TimelineItem{ + ID: "today-1", + Title: "Water the plants", + Source: "doot", + Type: models.TimelineItemTypeTask, + Time: time.Now(), + } + + wi := TimelineItemToWidgetItem(item) + + if wi.IsOverdue { + t.Error("expected IsOverdue to be false when the source item isn't overdue") + } +} + func TestHandleWidgetComplete_NonCompletable(t *testing.T) { h := &Handler{} body := `{"id":"x","source":"calendar"}` diff --git a/internal/models/widget.go b/internal/models/widget.go index 8d0bdd6..e2876b0 100644 --- a/internal/models/widget.go +++ b/internal/models/widget.go @@ -13,6 +13,7 @@ type WidgetItem struct { Start *time.Time `json:"start,omitempty"` // nil = no specific time (floating task) End *time.Time `json:"end,omitempty"` IsAllDay bool `json:"is_all_day"` + IsOverdue bool `json:"is_overdue"` URL string `json:"url,omitempty"` Completable bool `json:"completable"` // true = doot task (checkbox shown) } -- cgit v1.2.3 From 437ee6b10462909fb2db677a64be264d811a2e1c Mon Sep 17 00:00:00 2001 From: Peter Stone Date: Sun, 12 Jul 2026 10:21:36 +0000 Subject: feat(widget): add DueDate field for doot tasks to the widget API --- internal/handlers/widget.go | 9 +++++ internal/handlers/widget_test.go | 71 ++++++++++++++++++++++++++++++++++++++++ internal/models/widget.go | 1 + 3 files changed, 81 insertions(+) (limited to 'internal/handlers/widget.go') diff --git a/internal/handlers/widget.go b/internal/handlers/widget.go index f8a63a0..3a30fcf 100644 --- a/internal/handlers/widget.go +++ b/internal/handlers/widget.go @@ -76,6 +76,15 @@ func TimelineItemToWidgetItem(item models.TimelineItem) models.WidgetItem { } } + // DueDate is independent of Start/IsAllDay -- doot tasks deliberately + // keep Start nil (see the "floating task" doc comment above) so the + // client's SlotPacker positions them, but the Android detail popup + // still needs to know the real due date to display and reschedule it. + if item.Type == models.TimelineItemTypeTask && item.Source == "doot" && !item.Time.IsZero() { + due := item.Time + wi.DueDate = &due + } + return wi } diff --git a/internal/handlers/widget_test.go b/internal/handlers/widget_test.go index 06e1749..14dd396 100644 --- a/internal/handlers/widget_test.go +++ b/internal/handlers/widget_test.go @@ -210,6 +210,77 @@ func TestTimelineItemToWidgetItem_NotOverdueByDefault(t *testing.T) { } } +// TestTimelineItemToWidgetItem_DootTaskGetsDueDate proves the 2026-07-12 +// clickable-reschedule fix: a doot task's raw due date must reach the +// client via a NEW field (DueDate) that is independent of Start/IsAllDay -- +// Start is deliberately left nil for doot tasks (see +// TestTimelineItemToWidgetItem_AllDayTask_KeepsFloatingBehavior) so the +// client's floating-task SlotPacker can position it, and that must keep +// working unchanged. Before this fix there was no way for the Android +// detail popup to know a doot task's current due date at all. +func TestTimelineItemToWidgetItem_DootTaskGetsDueDate(t *testing.T) { + due := time.Date(2026, 7, 15, 0, 0, 0, 0, time.Local) + item := models.TimelineItem{ + ID: "doot-1", + Title: "Pay the water bill", + Source: "doot", + Type: models.TimelineItemTypeTask, + Time: due, + IsAllDay: true, + } + + wi := TimelineItemToWidgetItem(item) + + if wi.DueDate == nil { + t.Fatal("expected DueDate to be set for a doot task with a real due date") + } + if !wi.DueDate.Equal(due) { + t.Errorf("DueDate = %v, want %v", *wi.DueDate, due) + } + // Start must stay nil -- this is the pre-existing floating-task + // behavior and this feature must not change it. + if wi.Start != nil { + t.Error("Start must remain nil for a doot task -- DueDate is a separate field, not a replacement") + } +} + +func TestTimelineItemToWidgetItem_UndatedDootTask_NilDueDate(t *testing.T) { + item := models.TimelineItem{ + ID: "doot-undated", + Title: "Someday task", + Source: "doot", + Type: models.TimelineItemTypeTask, + Time: time.Now(), + IsAllDay: true, + } + // Zero Time simulates the "no real due date" case at the field level; + // TimelineItemToWidgetItem's DueDate logic must guard on !Time.IsZero(). + item.Time = time.Time{} + + wi := TimelineItemToWidgetItem(item) + + if wi.DueDate != nil { + t.Error("expected DueDate to be nil when the source item has a zero Time") + } +} + +func TestTimelineItemToWidgetItem_CalendarEvent_NilDueDate(t *testing.T) { + start := time.Now() + item := models.TimelineItem{ + ID: "cal-1", + Title: "Team sync", + Source: "calendar", + Type: models.TimelineItemTypeEvent, + Time: start, + } + + wi := TimelineItemToWidgetItem(item) + + if wi.DueDate != nil { + t.Error("expected DueDate to stay nil for a non-doot item (calendar event)") + } +} + func TestHandleWidgetComplete_NonCompletable(t *testing.T) { h := &Handler{} body := `{"id":"x","source":"calendar"}` diff --git a/internal/models/widget.go b/internal/models/widget.go index e2876b0..54a6eee 100644 --- a/internal/models/widget.go +++ b/internal/models/widget.go @@ -14,6 +14,7 @@ type WidgetItem struct { End *time.Time `json:"end,omitempty"` IsAllDay bool `json:"is_all_day"` IsOverdue bool `json:"is_overdue"` + DueDate *time.Time `json:"due_date,omitempty"` // doot tasks only -- see TimelineItemToWidgetItem URL string `json:"url,omitempty"` Completable bool `json:"completable"` // true = doot task (checkbox shown) } -- cgit v1.2.3 From dfb06e896b92003d219979cbb1476ed16b7734a3 Mon Sep 17 00:00:00 2001 From: Peter Stone Date: Sun, 12 Jul 2026 10:34:34 +0000 Subject: feat(widget): add POST /api/widget/add for quick-add --- cmd/dashboard/main.go | 1 + internal/handlers/widget.go | 31 +++++++++++++++++++++ internal/handlers/widget_test.go | 60 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 92 insertions(+) (limited to 'internal/handlers/widget.go') diff --git a/cmd/dashboard/main.go b/cmd/dashboard/main.go index b38b9e1..5414a9d 100644 --- a/cmd/dashboard/main.go +++ b/cmd/dashboard/main.go @@ -371,6 +371,7 @@ func main() { r.With(widgetAuth).Get("/api/widget", h.HandleWidgetGet) r.With(widgetAuth).Post("/api/widget/complete", h.HandleWidgetComplete) r.With(widgetAuth).Post("/api/widget/reschedule", h.HandleWidgetReschedule) + r.With(widgetAuth).Post("/api/widget/add", h.HandleWidgetAdd) } else { log.Println("WIDGET_TOKEN not set — /api/widget disabled") } diff --git a/internal/handlers/widget.go b/internal/handlers/widget.go index 3a30fcf..0c88c16 100644 --- a/internal/handlers/widget.go +++ b/internal/handlers/widget.go @@ -124,6 +124,10 @@ type widgetCompleteRequest struct { Source string `json:"source"` } +type widgetAddRequest struct { + Title string `json:"title"` +} + type widgetRescheduleRequest struct { ID string `json:"id"` Source string `json:"source"` @@ -189,3 +193,30 @@ func (h *Handler) HandleWidgetComplete(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) } + +// HandleWidgetAdd creates a new undated native task from the widget's quick-add sheet. +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.WriteHeader(http.StatusOK) +} diff --git a/internal/handlers/widget_test.go b/internal/handlers/widget_test.go index 14dd396..e4a1d16 100644 --- a/internal/handlers/widget_test.go +++ b/internal/handlers/widget_test.go @@ -313,6 +313,66 @@ func TestHandleWidgetComplete_UnknownID_Returns404(t *testing.T) { } } +// TestHandleWidgetAdd_CreatesTask proves the quick-add feature: POSTing a +// title to /api/widget/add creates an undated native task the same way the +// web UI's HandleUnifiedAdd does, but via the widget's bearer-token JSON +// API instead of a session-authenticated HTML form. +func TestHandleWidgetAdd_CreatesTask(t *testing.T) { + s, cleanup := setupTestDB(t) + defer cleanup() + h := &Handler{store: s} + body := `{"title":"Buy milk"}` + req := httptest.NewRequest("POST", "/api/widget/add", strings.NewReader(body)) + w := httptest.NewRecorder() + http.HandlerFunc(h.HandleWidgetAdd).ServeHTTP(w, req) + + if w.Code != http.StatusOK { + t.Fatalf("expected 200, got %d", w.Code) + } + + tasks, err := s.GetUndatedNativeTasks() + if err != nil { + t.Fatalf("failed to read back tasks: %v", err) + } + found := false + for _, task := range tasks { + if task.Content == "Buy milk" { + found = true + } + } + if !found { + t.Error("expected a task with content 'Buy milk' to have been created") + } +} + +func TestHandleWidgetAdd_EmptyTitle_Returns400(t *testing.T) { + s, cleanup := setupTestDB(t) + defer cleanup() + h := &Handler{store: s} + body := `{"title":""}` + req := httptest.NewRequest("POST", "/api/widget/add", strings.NewReader(body)) + w := httptest.NewRecorder() + http.HandlerFunc(h.HandleWidgetAdd).ServeHTTP(w, req) + + if w.Code != http.StatusBadRequest { + t.Fatalf("expected 400, got %d", w.Code) + } +} + +func TestHandleWidgetAdd_WhitespaceOnlyTitle_Returns400(t *testing.T) { + s, cleanup := setupTestDB(t) + defer cleanup() + h := &Handler{store: s} + body := `{"title":" "}` + req := httptest.NewRequest("POST", "/api/widget/add", strings.NewReader(body)) + w := httptest.NewRecorder() + http.HandlerFunc(h.HandleWidgetAdd).ServeHTTP(w, req) + + if w.Code != http.StatusBadRequest { + t.Fatalf("expected 400, got %d", w.Code) + } +} + func TestWidgetAuthMiddleware_EmptyToken(t *testing.T) { inner := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}) h := WidgetAuthMiddleware("", inner) -- cgit v1.2.3 From f31b4722243b8b69564c94e47e07678153c31815 Mon Sep 17 00:00:00 2001 From: Peter Stone Date: Sun, 12 Jul 2026 11:06:32 +0000 Subject: feat(widget): capture and forward RecurringEventID for calendar events --- internal/api/google_calendar.go | 26 +++++++++-------- internal/handlers/timeline_logic.go | 21 +++++++------- internal/handlers/timeline_logic_test.go | 1 + internal/handlers/widget.go | 13 +++++---- internal/handlers/widget_test.go | 38 +++++++++++++++++++++++++ internal/models/timeline.go | 13 +++++---- internal/models/types.go | 25 ++++++++-------- internal/models/widget.go | 23 ++++++++------- internal/store/sqlite.go | 10 +++---- migrations/022_calendar_events_recurring_id.sql | 1 + 10 files changed, 109 insertions(+), 62 deletions(-) create mode 100644 migrations/022_calendar_events_recurring_id.sql (limited to 'internal/handlers/widget.go') diff --git a/internal/api/google_calendar.go b/internal/api/google_calendar.go index 8bb3143..7381527 100644 --- a/internal/api/google_calendar.go +++ b/internal/api/google_calendar.go @@ -130,12 +130,13 @@ func (c *GoogleCalendarClient) GetUpcomingEvents(ctx context.Context, maxResults for _, item := range events.Items { start, end := c.parseEventTime(item) allEvents = append(allEvents, models.CalendarEvent{ - ID: item.Id, - Summary: item.Summary, - Description: item.Description, - Start: start, - End: end, - HTMLLink: item.HtmlLink, + ID: item.Id, + Summary: item.Summary, + Description: item.Description, + Start: start, + End: end, + HTMLLink: item.HtmlLink, + RecurringEventID: item.RecurringEventId, }) } } @@ -163,12 +164,13 @@ func (c *GoogleCalendarClient) GetEventsByDateRange(ctx context.Context, start, for _, item := range events.Items { evtStart, evtEnd := c.parseEventTime(item) allEvents = append(allEvents, models.CalendarEvent{ - ID: item.Id, - Summary: item.Summary, - Description: item.Description, - Start: evtStart, - End: evtEnd, - HTMLLink: item.HtmlLink, + ID: item.Id, + Summary: item.Summary, + Description: item.Description, + Start: evtStart, + End: evtEnd, + HTMLLink: item.HtmlLink, + RecurringEventID: item.RecurringEventId, }) } } diff --git a/internal/handlers/timeline_logic.go b/internal/handlers/timeline_logic.go index e7c1279..6fddd1d 100644 --- a/internal/handlers/timeline_logic.go +++ b/internal/handlers/timeline_logic.go @@ -81,16 +81,17 @@ func BuildTimeline(ctx context.Context, s *store.Store, start, end time.Time) ([ for _, event := range events { endTime := event.End item := models.TimelineItem{ - ID: event.ID, - Type: models.TimelineItemTypeEvent, - Title: event.Summary, - Time: event.Start, - EndTime: &endTime, - Description: event.Description, - URL: event.HTMLLink, - OriginalItem: event, - IsCompleted: false, - Source: "calendar", + ID: event.ID, + Type: models.TimelineItemTypeEvent, + Title: event.Summary, + Time: event.Start, + EndTime: &endTime, + Description: event.Description, + URL: event.HTMLLink, + OriginalItem: event, + IsCompleted: false, + Source: "calendar", + RecurringEventID: event.RecurringEventID, } item.ComputeDaySection(now) items = append(items, item) diff --git a/internal/handlers/timeline_logic_test.go b/internal/handlers/timeline_logic_test.go index 7d3f6b5..9ddaeda 100644 --- a/internal/handlers/timeline_logic_test.go +++ b/internal/handlers/timeline_logic_test.go @@ -82,6 +82,7 @@ func setupTestStore(t *testing.T) *store.Store { start_time DATETIME NOT NULL, end_time DATETIME NOT NULL, html_link TEXT, + recurring_event_id TEXT DEFAULT '', updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ); CREATE TABLE IF NOT EXISTS google_tasks ( diff --git a/internal/handlers/widget.go b/internal/handlers/widget.go index 0c88c16..29124fb 100644 --- a/internal/handlers/widget.go +++ b/internal/handlers/widget.go @@ -32,12 +32,13 @@ func WidgetAuthMiddleware(token string, next http.Handler) http.Handler { // 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, + ID: item.ID, + Title: item.Title, + Source: item.Source, + IsAllDay: item.IsAllDay, + IsOverdue: item.IsOverdue, + URL: item.URL, + RecurringEventID: item.RecurringEventID, } switch item.Type { diff --git a/internal/handlers/widget_test.go b/internal/handlers/widget_test.go index e4a1d16..efe6858 100644 --- a/internal/handlers/widget_test.go +++ b/internal/handlers/widget_test.go @@ -386,3 +386,41 @@ func TestWidgetAuthMiddleware_EmptyToken(t *testing.T) { t.Fatalf("expected 401 with empty token, got %d", w.Code) } } + +// TestTimelineItemToWidgetItem_ForwardsRecurringEventID proves the +// 2026-07-12 recurrence-display fix's data plumbing: a calendar event's +// RecurringEventId (captured from Google's API, which only puts the RRULE +// itself on the master event, not on expanded instances) must reach the +// client so it can look up the human-readable schedule on demand. +func TestTimelineItemToWidgetItem_ForwardsRecurringEventID(t *testing.T) { + item := models.TimelineItem{ + ID: "cal-1", + Title: "Team sync", + Source: "calendar", + Type: models.TimelineItemTypeEvent, + Time: time.Now(), + RecurringEventID: "master-123", + } + + wi := TimelineItemToWidgetItem(item) + + if wi.RecurringEventID != "master-123" { + t.Errorf("RecurringEventID = %q, want %q", wi.RecurringEventID, "master-123") + } +} + +func TestTimelineItemToWidgetItem_NonRecurring_EmptyRecurringEventID(t *testing.T) { + item := models.TimelineItem{ + ID: "cal-2", + Title: "One-off meeting", + Source: "calendar", + Type: models.TimelineItemTypeEvent, + Time: time.Now(), + } + + wi := TimelineItemToWidgetItem(item) + + if wi.RecurringEventID != "" { + t.Errorf("expected empty RecurringEventID for a non-recurring event, got %q", wi.RecurringEventID) + } +} diff --git a/internal/models/timeline.go b/internal/models/timeline.go index ab486a8..6e48f91 100644 --- a/internal/models/timeline.go +++ b/internal/models/timeline.go @@ -9,11 +9,11 @@ import ( type TimelineItemType string const ( - TimelineItemTypeTask TimelineItemType = "task" - TimelineItemTypeMeal TimelineItemType = "meal" - TimelineItemTypeCard TimelineItemType = "card" - TimelineItemTypeEvent TimelineItemType = "event" - TimelineItemTypeGTask TimelineItemType = "gtask" // Google Tasks + TimelineItemTypeTask TimelineItemType = "task" + TimelineItemTypeMeal TimelineItemType = "meal" + TimelineItemTypeCard TimelineItemType = "card" + TimelineItemTypeEvent TimelineItemType = "event" + TimelineItemTypeGTask TimelineItemType = "gtask" // Google Tasks ) type DaySection string @@ -42,7 +42,8 @@ type TimelineItem struct { Source string `json:"source"` // "trello", "plantoeat", "calendar", "gtasks" // Source-specific metadata - ListID string `json:"list_id,omitempty"` // For Google Tasks + ListID string `json:"list_id,omitempty"` // For Google Tasks + RecurringEventID string `json:"recurring_event_id,omitempty"` // For calendar events } // ComputeDaySection sets the DaySection, IsOverdue, and IsAllDay based on the item's time diff --git a/internal/models/types.go b/internal/models/types.go index d9dd515..b3f3a22 100644 --- a/internal/models/types.go +++ b/internal/models/types.go @@ -126,12 +126,13 @@ type Project struct { // CalendarEvent represents a Google Calendar event type CalendarEvent struct { - ID string `json:"id"` - Summary string `json:"summary"` - Description string `json:"description"` - Start time.Time `json:"start"` - End time.Time `json:"end"` - HTMLLink string `json:"html_link"` + ID string `json:"id"` + Summary string `json:"summary"` + Description string `json:"description"` + Start time.Time `json:"start"` + End time.Time `json:"end"` + HTMLLink string `json:"html_link"` + RecurringEventID string `json:"recurring_event_id,omitempty"` // empty = not a recurring instance } // GoogleTask represents a task from Google Tasks @@ -248,12 +249,12 @@ type CompletedTask struct { // SourceConfig represents a configurable item from a data source type SourceConfig struct { - ID int64 `json:"id"` - Source string `json:"source"` // trello, gcal, gtasks - ItemType string `json:"item_type"` // board, project, calendar, tasklist - ItemID string `json:"item_id"` - ItemName string `json:"item_name"` - Enabled bool `json:"enabled"` + ID int64 `json:"id"` + Source string `json:"source"` // trello, gcal, gtasks + ItemType string `json:"item_type"` // board, project, calendar, tasklist + ItemID string `json:"item_id"` + ItemName string `json:"item_name"` + Enabled bool `json:"enabled"` } // FeatureToggle represents a feature flag diff --git a/internal/models/widget.go b/internal/models/widget.go index 54a6eee..cbaf19c 100644 --- a/internal/models/widget.go +++ b/internal/models/widget.go @@ -6,17 +6,18 @@ import "time" // Source values: "doot", "trello", "plantoeat", "calendar", "gtasks" // Type values: "task", "event" type WidgetItem struct { - ID string `json:"id"` - Title string `json:"title"` - Source string `json:"source"` - Type string `json:"type"` - Start *time.Time `json:"start,omitempty"` // nil = no specific time (floating task) - End *time.Time `json:"end,omitempty"` - IsAllDay bool `json:"is_all_day"` - IsOverdue bool `json:"is_overdue"` - DueDate *time.Time `json:"due_date,omitempty"` // doot tasks only -- see TimelineItemToWidgetItem - URL string `json:"url,omitempty"` - Completable bool `json:"completable"` // true = doot task (checkbox shown) + ID string `json:"id"` + Title string `json:"title"` + Source string `json:"source"` + Type string `json:"type"` + Start *time.Time `json:"start,omitempty"` // nil = no specific time (floating task) + End *time.Time `json:"end,omitempty"` + IsAllDay bool `json:"is_all_day"` + IsOverdue bool `json:"is_overdue"` + DueDate *time.Time `json:"due_date,omitempty"` // doot tasks only -- see TimelineItemToWidgetItem + URL string `json:"url,omitempty"` + Completable bool `json:"completable"` // true = doot task (checkbox shown) + RecurringEventID string `json:"recurring_event_id,omitempty"` } // WidgetResponse is the full /api/widget response body. diff --git a/internal/store/sqlite.go b/internal/store/sqlite.go index a6e9fd4..f08e9bd 100644 --- a/internal/store/sqlite.go +++ b/internal/store/sqlite.go @@ -598,8 +598,8 @@ func (s *Store) SaveCalendarEvents(events []models.CalendarEvent) error { } stmt, err := tx.Prepare(` - INSERT INTO calendar_events (id, summary, description, start_time, end_time, html_link) - VALUES (?, ?, ?, ?, ?, ?) + INSERT INTO calendar_events (id, summary, description, start_time, end_time, html_link, recurring_event_id) + VALUES (?, ?, ?, ?, ?, ?, ?) `) if err != nil { return err @@ -607,7 +607,7 @@ func (s *Store) SaveCalendarEvents(events []models.CalendarEvent) error { defer func() { _ = stmt.Close() }() for _, e := range events { - _, err = stmt.Exec(e.ID, e.Summary, e.Description, e.Start, e.End, e.HTMLLink) + _, err = stmt.Exec(e.ID, e.Summary, e.Description, e.Start, e.End, e.HTMLLink, e.RecurringEventID) if err != nil { return err } @@ -642,7 +642,7 @@ func (s *Store) GetCalendarEvents() ([]models.CalendarEvent, error) { // GetCalendarEventsByDateRange retrieves cached calendar events within a date range func (s *Store) GetCalendarEventsByDateRange(start, end time.Time) ([]models.CalendarEvent, error) { rows, err := s.db.Query(` - SELECT id, summary, description, start_time, end_time, html_link + SELECT id, summary, description, start_time, end_time, html_link, recurring_event_id FROM calendar_events WHERE start_time >= ? AND start_time <= ? ORDER BY start_time ASC @@ -655,7 +655,7 @@ func (s *Store) GetCalendarEventsByDateRange(start, end time.Time) ([]models.Cal var events []models.CalendarEvent for rows.Next() { var e models.CalendarEvent - if err := rows.Scan(&e.ID, &e.Summary, &e.Description, &e.Start, &e.End, &e.HTMLLink); err != nil { + if err := rows.Scan(&e.ID, &e.Summary, &e.Description, &e.Start, &e.End, &e.HTMLLink, &e.RecurringEventID); err != nil { return nil, err } events = append(events, e) diff --git a/migrations/022_calendar_events_recurring_id.sql b/migrations/022_calendar_events_recurring_id.sql new file mode 100644 index 0000000..e77ddb2 --- /dev/null +++ b/migrations/022_calendar_events_recurring_id.sql @@ -0,0 +1 @@ +ALTER TABLE calendar_events ADD COLUMN recurring_event_id TEXT DEFAULT ''; -- cgit v1.2.3 From 6fdd09bfe030ce91ee188f18c198fd6a57c7b42f Mon Sep 17 00:00:00 2001 From: Peter Stone Date: Sun, 12 Jul 2026 11:12:55 +0000 Subject: feat(widget): add recurrence lookup endpoint (GET /api/widget/recurrence) --- cmd/dashboard/main.go | 1 + internal/api/google_calendar.go | 99 ++++++++++++++++++++++++++++++++ internal/api/google_calendar_test.go | 30 ++++++++++ internal/api/interfaces.go | 1 + internal/handlers/timeline_logic_test.go | 7 +++ internal/handlers/widget.go | 22 +++++++ internal/handlers/widget_test.go | 49 ++++++++++++++++ 7 files changed, 209 insertions(+) (limited to 'internal/handlers/widget.go') diff --git a/cmd/dashboard/main.go b/cmd/dashboard/main.go index 5414a9d..d4e4dcb 100644 --- a/cmd/dashboard/main.go +++ b/cmd/dashboard/main.go @@ -371,6 +371,7 @@ func main() { r.With(widgetAuth).Get("/api/widget", h.HandleWidgetGet) r.With(widgetAuth).Post("/api/widget/complete", h.HandleWidgetComplete) r.With(widgetAuth).Post("/api/widget/reschedule", h.HandleWidgetReschedule) + r.With(widgetAuth).Get("/api/widget/recurrence", h.HandleWidgetRecurrence) r.With(widgetAuth).Post("/api/widget/add", h.HandleWidgetAdd) } else { log.Println("WIDGET_TOKEN not set — /api/widget disabled") diff --git a/internal/api/google_calendar.go b/internal/api/google_calendar.go index 7381527..bb17812 100644 --- a/internal/api/google_calendar.go +++ b/internal/api/google_calendar.go @@ -5,6 +5,7 @@ import ( "fmt" "log" "sort" + "strconv" "strings" "time" @@ -83,6 +84,86 @@ func deduplicateEvents(events []models.CalendarEvent) []models.CalendarEvent { return unique } +var recurrenceFreqNames = map[string]string{ + "DAILY": "daily", + "WEEKLY": "weekly", + "MONTHLY": "monthly", + "YEARLY": "yearly", +} + +var recurrenceFreqUnits = map[string]string{ + "DAILY": "day", + "WEEKLY": "week", + "MONTHLY": "month", + "YEARLY": "year", +} + +var recurrenceWeekdayNames = map[string]string{ + "SU": "Sunday", + "MO": "Monday", + "TU": "Tuesday", + "WE": "Wednesday", + "TH": "Thursday", + "FR": "Friday", + "SA": "Saturday", +} + +// formatRecurrence turns Google Calendar RRULE strings into short English. +// This intentionally covers only the common cases (FREQ, INTERVAL, BYDAY) -- +// not a full RFC 5545 parser. Anything it can't confidently describe falls +// back to "Recurring event" rather than showing nothing or an error. +func formatRecurrence(rrules []string) string { + for _, rule := range rrules { + rule = strings.TrimPrefix(rule, "RRULE:") + parts := make(map[string]string) + for _, kv := range strings.Split(rule, ";") { + pieces := strings.SplitN(kv, "=", 2) + if len(pieces) == 2 { + parts[pieces[0]] = pieces[1] + } + } + + freqKey := parts["FREQ"] + unit, ok := recurrenceFreqUnits[freqKey] + if !ok { + continue + } + + interval := 1 + if iv := parts["INTERVAL"]; iv != "" { + if n, err := strconv.Atoi(iv); err == nil && n > 0 { + interval = n + } + } + + var phrase string + if interval == 1 { + phrase = "Repeats " + recurrenceFreqNames[freqKey] + } else { + phrase = fmt.Sprintf("Repeats every %d %ss", interval, unit) + } + + if byday := parts["BYDAY"]; byday != "" { + var days []string + for _, code := range strings.Split(byday, ",") { + code = strings.TrimSpace(code) + if len(code) >= 2 { + code = code[len(code)-2:] + } + if name, ok := recurrenceWeekdayNames[code]; ok { + days = append(days, name) + } + } + if len(days) > 0 { + phrase += " on " + strings.Join(days, ", ") + } + } + + return phrase + } + return "Recurring event" +} + // NewGoogleCalendarClient creates a client that fetches from multiple calendars. // calendarIDs can be comma-separated (e.g., "cal1@group.calendar.google.com,cal2@group.calendar.google.com") // timezone is the IANA timezone name for display (e.g., "Pacific/Honolulu") @@ -203,3 +284,21 @@ func (c *GoogleCalendarClient) GetCalendarList(ctx context.Context) ([]models.Ca } return calendars, nil } + +// GetRecurrenceRule looks up a recurring event's master record and returns +// its formatted recurrence schedule. Google's API only puts the RRULE on +// the master event, not on expanded instances (see parseEventTime's +// SingleEvents(true) callers), so this does a live lookup by the instance's +// RecurringEventId. There's no per-event calendar attribution stored today +// (events from all configured calendars are merged without recording which +// one they came from), so this tries each configured calendar in turn. +func (c *GoogleCalendarClient) GetRecurrenceRule(ctx context.Context, recurringEventID string) (string, error) { + for _, calendarID := range c.calendarIDs { + event, err := c.srv.Events.Get(calendarID, recurringEventID).Do() + if err != nil { + continue + } + return formatRecurrence(event.Recurrence), nil + } + return "", fmt.Errorf("recurring event %s not found on any configured calendar", recurringEventID) +} diff --git a/internal/api/google_calendar_test.go b/internal/api/google_calendar_test.go index 3cf0dbd..efbab0d 100644 --- a/internal/api/google_calendar_test.go +++ b/internal/api/google_calendar_test.go @@ -272,3 +272,33 @@ func TestGetUpcomingEvents_APIError_ReturnsEmptyNotError(t *testing.T) { t.Errorf("expected 0 events on API error, got %d", len(events)) } } + +// --- formatRecurrence --- + +func TestFormatRecurrence(t *testing.T) { + tests := []struct { + name string + rules []string + want string + }{ + {"weekly single day", []string{"RRULE:FREQ=WEEKLY;BYDAY=MO"}, "Repeats weekly on Monday"}, + {"weekly multiple days", []string{"RRULE:FREQ=WEEKLY;BYDAY=MO,WE,FR"}, "Repeats weekly on Monday, Wednesday, Friday"}, + {"daily", []string{"RRULE:FREQ=DAILY"}, "Repeats daily"}, + {"monthly", []string{"RRULE:FREQ=MONTHLY"}, "Repeats monthly"}, + {"yearly", []string{"RRULE:FREQ=YEARLY"}, "Repeats yearly"}, + {"interval weekly", []string{"RRULE:FREQ=WEEKLY;INTERVAL=2;BYDAY=SU"}, "Repeats every 2 weeks on Sunday"}, + {"interval daily", []string{"RRULE:FREQ=DAILY;INTERVAL=3"}, "Repeats every 3 days"}, + {"unrecognized frequency", []string{"RRULE:FREQ=HOURLY"}, "Recurring event"}, + {"empty", []string{}, "Recurring event"}, + {"unparseable", []string{"not a valid rule"}, "Recurring event"}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + got := formatRecurrence(tc.rules) + if got != tc.want { + t.Errorf("formatRecurrence(%v) = %q, want %q", tc.rules, got, tc.want) + } + }) + } +} diff --git a/internal/api/interfaces.go b/internal/api/interfaces.go index c5e154d..9a607bb 100644 --- a/internal/api/interfaces.go +++ b/internal/api/interfaces.go @@ -30,6 +30,7 @@ type GoogleCalendarAPI interface { GetEventsByDateRange(ctx context.Context, start, end time.Time) ([]models.CalendarEvent, error) GetCalendarList(ctx context.Context) ([]models.CalendarInfo, error) SetCalendarIDs(ids []string) + GetRecurrenceRule(ctx context.Context, recurringEventID string) (string, error) } // GoogleTasksAPI defines the interface for Google Tasks operations diff --git a/internal/handlers/timeline_logic_test.go b/internal/handlers/timeline_logic_test.go index 9ddaeda..5e7cb27 100644 --- a/internal/handlers/timeline_logic_test.go +++ b/internal/handlers/timeline_logic_test.go @@ -23,6 +23,9 @@ type MockCalendarClient struct { // with, for tests that need to assert on how the caller resolved its // calendar ID list (e.g. fetchCalendarEvents' comma-split fallback). SetCalendarIDsCalls [][]string + // RecurrenceRule is returned by GetRecurrenceRule for any id when RecurrenceErr is nil. + RecurrenceRule string + RecurrenceErr error } func (m *MockCalendarClient) GetUpcomingEvents(ctx context.Context, maxResults int) ([]models.CalendarEvent, error) { @@ -41,6 +44,10 @@ func (m *MockCalendarClient) SetCalendarIDs(ids []string) { m.SetCalendarIDsCalls = append(m.SetCalendarIDsCalls, ids) } +func (m *MockCalendarClient) GetRecurrenceRule(ctx context.Context, recurringEventID string) (string, error) { + return m.RecurrenceRule, m.RecurrenceErr +} + func setupTestStore(t *testing.T) *store.Store { t.Helper() tempDir := t.TempDir() diff --git a/internal/handlers/widget.go b/internal/handlers/widget.go index 29124fb..6b1e774 100644 --- a/internal/handlers/widget.go +++ b/internal/handlers/widget.go @@ -195,6 +195,28 @@ func (h *Handler) HandleWidgetComplete(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) } +// HandleWidgetRecurrence looks up and formats a recurring calendar event's schedule. +func (h *Handler) HandleWidgetRecurrence(w http.ResponseWriter, r *http.Request) { + recurringEventID := r.URL.Query().Get("recurring_event_id") + if recurringEventID == "" { + http.Error(w, "recurring_event_id is required", http.StatusBadRequest) + return + } + + recurrence, err := h.googleCalendarClient.GetRecurrenceRule(r.Context(), recurringEventID) + if err != nil { + http.Error(w, "recurring event not found", http.StatusNotFound) + return + } + + resp := struct { + Recurrence string `json:"recurrence"` + }{Recurrence: recurrence} + + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(resp) +} + // HandleWidgetAdd creates a new undated native task from the widget's quick-add sheet. func (h *Handler) HandleWidgetAdd(w http.ResponseWriter, r *http.Request) { var req widgetAddRequest diff --git a/internal/handlers/widget_test.go b/internal/handlers/widget_test.go index efe6858..610a55c 100644 --- a/internal/handlers/widget_test.go +++ b/internal/handlers/widget_test.go @@ -1,6 +1,8 @@ package handlers import ( + "encoding/json" + "fmt" "net/http" "net/http/httptest" "strings" @@ -424,3 +426,50 @@ func TestTimelineItemToWidgetItem_NonRecurring_EmptyRecurringEventID(t *testing. t.Errorf("expected empty RecurringEventID for a non-recurring event, got %q", wi.RecurringEventID) } } + +// TestHandleWidgetRecurrence_ReturnsFormattedSchedule proves the recurrence +// lookup endpoint: given a recurring_event_id query param, it calls the +// calendar client's GetRecurrenceRule and returns the formatted text. +func TestHandleWidgetRecurrence_ReturnsFormattedSchedule(t *testing.T) { + mock := &MockCalendarClient{RecurrenceRule: "Repeats weekly on Monday"} + h := &Handler{googleCalendarClient: mock} + req := httptest.NewRequest("GET", "/api/widget/recurrence?recurring_event_id=master-1", nil) + w := httptest.NewRecorder() + http.HandlerFunc(h.HandleWidgetRecurrence).ServeHTTP(w, req) + + if w.Code != http.StatusOK { + t.Fatalf("expected 200, got %d", w.Code) + } + var resp struct { + Recurrence string `json:"recurrence"` + } + if err := json.NewDecoder(w.Body).Decode(&resp); err != nil { + t.Fatalf("failed to decode response: %v", err) + } + if resp.Recurrence != "Repeats weekly on Monday" { + t.Errorf("recurrence = %q, want %q", resp.Recurrence, "Repeats weekly on Monday") + } +} + +func TestHandleWidgetRecurrence_NotFound_Returns404(t *testing.T) { + mock := &MockCalendarClient{RecurrenceErr: fmt.Errorf("not found")} + h := &Handler{googleCalendarClient: mock} + req := httptest.NewRequest("GET", "/api/widget/recurrence?recurring_event_id=missing", nil) + w := httptest.NewRecorder() + http.HandlerFunc(h.HandleWidgetRecurrence).ServeHTTP(w, req) + + if w.Code != http.StatusNotFound { + t.Fatalf("expected 404, got %d", w.Code) + } +} + +func TestHandleWidgetRecurrence_MissingParam_Returns400(t *testing.T) { + h := &Handler{} + req := httptest.NewRequest("GET", "/api/widget/recurrence", nil) + w := httptest.NewRecorder() + http.HandlerFunc(h.HandleWidgetRecurrence).ServeHTTP(w, req) + + if w.Code != http.StatusBadRequest { + t.Fatalf("expected 400, got %d", w.Code) + } +} -- cgit v1.2.3