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

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

	"github.com/go-chi/chi/v5"

	"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()
	toggles, _ := h.store.GetFeatureToggles()
	syncLog, _ := h.store.GetRecentSyncLog(20)

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

	data := struct {
		Configs         map[string][]models.SourceConfig
		Sources         []string
		Toggles         []models.FeatureToggle
		SyncLog         []store.SyncLogEntry
		CSRFToken       string
		WebAuthnEnabled bool
	}{
		Configs:         bySource,
		Sources:         []string{"trello", "todoist", "gcal", "gtasks"},
		Toggles:         toggles,
		SyncLog:         syncLog,
		CSRFToken:       auth.GetCSRFTokenFromContext(r.Context()),
		WebAuthnEnabled: h.WebAuthnEnabled,
	}

	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 Todoist projects from cached tasks (avoids deprecated REST API)
	if projects, err := h.store.GetProjectsFromTasks(); err == nil && len(projects) > 0 {
		var items []models.SourceConfig
		for _, p := range projects {
			items = append(items, models.SourceConfig{
				Source:   "todoist",
				ItemType: "project",
				ItemID:   p.ID,
				ItemName: p.Name,
			})
		}
		_ = h.store.SyncSourceConfigs("todoist", "project", 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 and clears the Todoist sync token
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
	}

	if err := h.store.ClearSyncToken("todoist"); err != nil {
		JSONError(w, http.StatusInternalServerError, "Failed to clear sync token", 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")
	case "todoist":
		_ = h.store.InvalidateCache("todoist_tasks")
	}

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

// HandleGetSourceOptions returns available options for a source (HTMX partial)
func (h *Handler) HandleGetSourceOptions(w http.ResponseWriter, r *http.Request) {
	source := chi.URLParam(r, "source")
	if source == "" {
		JSONError(w, http.StatusBadRequest, "Source required", nil)
		return
	}

	configs, err := h.store.GetSourceConfigsBySource(source)
	if err != nil {
		JSONError(w, http.StatusInternalServerError, "Failed to load configs", err)
		return
	}

	data := struct {
		Source  string
		Configs []models.SourceConfig
	}{source, configs}

	HTMLResponse(w, h.renderer, "settings-source-options", data)
}

// HandleToggleFeature toggles a feature flag
func (h *Handler) HandleToggleFeature(w http.ResponseWriter, r *http.Request) {
	name, ok := requireFormValue(w, r, "name")
	if !ok {
		return
	}
	enabled := r.FormValue("enabled") == "true"

	if err := h.store.SetFeatureEnabled(name, enabled); err != nil {
		JSONError(w, http.StatusInternalServerError, "Failed to update feature", err)
		return
	}

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

// HandleCreateFeature creates a new feature toggle
func (h *Handler) HandleCreateFeature(w http.ResponseWriter, r *http.Request) {
	name, ok := requireFormValue(w, r, "name")
	if !ok {
		return
	}
	description := r.FormValue("description")

	if err := h.store.CreateFeatureToggle(name, description, false); err != nil {
		JSONError(w, http.StatusInternalServerError, "Failed to create feature", err)
		return
	}

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

// HandleDeleteFeature removes a feature toggle
func (h *Handler) HandleDeleteFeature(w http.ResponseWriter, r *http.Request) {
	name := chi.URLParam(r, "name")
	if name == "" {
		JSONError(w, http.StatusBadRequest, "Feature name required", nil)
		return
	}

	if err := h.store.DeleteFeatureToggle(name); err != nil {
		JSONError(w, http.StatusInternalServerError, "Failed to delete feature", err)
		return
	}

	w.WriteHeader(http.StatusOK)
}