summaryrefslogtreecommitdiff
path: root/internal/handlers/settings.go
blob: d140aafa6f03135423e650b8c166468bfb0296cc (plain)
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
package handlers

import (
	"encoding/json"
	"net/http"

	"task-dashboard/internal/api"
	"task-dashboard/internal/auth"
	"task-dashboard/internal/models"
	"task-dashboard/internal/store"
)

// HandleSettingsPage renders the settings page
func (h *Handler) HandleSettingsPage(w http.ResponseWriter, r *http.Request) {
	configs, _ := h.store.GetSourceConfigs()
	syncLog, _ := h.store.GetRecentSyncLog(20)
	agents, _ := h.store.GetAllAgents()

	// Group configs by source
	bySource := make(map[string][]models.SourceConfig)
	for _, cfg := range configs {
		bySource[cfg.Source] = append(bySource[cfg.Source], cfg)
	}

	googleTasksToken, _ := h.store.GetOAuthToken(api.GoogleTasksOAuthSource)

	data := struct {
		Configs               map[string][]models.SourceConfig
		Sources               []string
		SyncLog               []store.SyncLogEntry
		Agents                []models.Agent
		CSRFToken             string
		WebAuthnEnabled       bool
		GoogleTasksOAuthReady bool
		GoogleTasksConnected  bool
		GoogleTasksError      string
	}{
		Configs:               bySource,
		Sources:               []string{"trello", "gcal", "gtasks"},
		SyncLog:               syncLog,
		Agents:                agents,
		CSRFToken:             auth.GetCSRFTokenFromContext(r.Context()),
		WebAuthnEnabled:       h.WebAuthnEnabled,
		GoogleTasksOAuthReady: h.googleTasksOAuthConfig != nil,
		GoogleTasksConnected:  googleTasksToken != nil,
		GoogleTasksError:      r.URL.Query().Get("google_tasks_error"),
	}

	if err := h.renderer.Render(w, "settings.html", data); err != nil {
		JSONError(w, http.StatusInternalServerError, "Failed to render settings", err)
	}
}

// HandleSyncSources fetches available items from all sources and syncs to config
func (h *Handler) HandleSyncSources(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

	// Sync Trello boards
	if h.trelloClient != nil {
		boards, err := h.trelloClient.GetBoards(ctx)
		if err == nil {
			var items []models.SourceConfig
			for _, b := range boards {
				items = append(items, models.SourceConfig{
					Source:   "trello",
					ItemType: "board",
					ItemID:   b.ID,
					ItemName: b.Name,
				})
			}
			_ = h.store.SyncSourceConfigs("trello", "board", items)
		}
	}

	// Sync Google Calendar calendars
	if h.googleCalendarClient != nil {
		calendars, err := h.googleCalendarClient.GetCalendarList(ctx)
		if err == nil {
			var items []models.SourceConfig
			for _, c := range calendars {
				items = append(items, models.SourceConfig{
					Source:   "gcal",
					ItemType: "calendar",
					ItemID:   c.ID,
					ItemName: c.Name,
				})
			}
			_ = h.store.SyncSourceConfigs("gcal", "calendar", items)
		}
	}

	// Sync Google Tasks lists
	if h.googleTasksClient != nil {
		lists, err := h.googleTasksClient.GetTaskLists(ctx)
		if err == nil {
			var items []models.SourceConfig
			for _, l := range lists {
				items = append(items, models.SourceConfig{
					Source:   "gtasks",
					ItemType: "tasklist",
					ItemID:   l.ID,
					ItemName: l.Name,
				})
			}
			_ = h.store.SyncSourceConfigs("gtasks", "tasklist", items)
		}
	}

	_ = h.store.AddSyncLogEntry("sync", "Sources synced")

	// Return updated configs
	h.HandleSettingsPage(w, r)
}

// HandleClearCache invalidates all caches
func (h *Handler) HandleClearCache(w http.ResponseWriter, r *http.Request) {
	if err := h.store.InvalidateAllCaches(); err != nil {
		JSONError(w, http.StatusInternalServerError, "Failed to clear cache", err)
		return
	}

	_ = h.store.AddSyncLogEntry("cache_clear", "Cache cleared — next load fetches fresh data")

	syncLog, _ := h.store.GetRecentSyncLog(20)
	w.Header().Set("HX-Trigger", "refresh-tasks")
	HTMLResponse(w, h.renderer, "sync-log", syncLog)
}

// HandleToggleSourceConfig toggles a source config item
func (h *Handler) HandleToggleSourceConfig(w http.ResponseWriter, r *http.Request) {
	if err := r.ParseForm(); err != nil {
		JSONError(w, http.StatusBadRequest, "Failed to parse form", err)
		return
	}

	source := r.FormValue("source")
	itemType := r.FormValue("item_type")
	itemID := r.FormValue("item_id")
	enabled := r.FormValue("enabled") == "true"

	if source == "" || itemType == "" || itemID == "" {
		JSONError(w, http.StatusBadRequest, "Missing required fields", nil)
		return
	}

	if err := h.store.SetSourceConfigEnabled(source, itemType, itemID, enabled); err != nil {
		JSONError(w, http.StatusInternalServerError, "Failed to update config", err)
		return
	}

	// Invalidate relevant cache
	switch source {
	case "trello":
		_ = h.store.InvalidateCache("trello_boards")
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(map[string]bool{"enabled": enabled})
}