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

import (
	"context"
	"fmt"
	"html/template"
	"log"
	"net/http"
	"net/url"
	"sort"
	"strings"

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

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

// HandleTabShopping renders the Shopping tab (Trello Shopping board + PlanToEat + User items)
func (h *Handler) HandleTabShopping(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()
	stores := h.aggregateShoppingLists(ctx)
	grouped := r.URL.Query().Get("grouped") != "false" // Default to grouped
	HTMLResponse(w, h.renderer, "shopping-tab", struct {
		Stores  []models.ShoppingStore
		Grouped bool
	}{stores, grouped})
}

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

	name := strings.TrimSpace(r.FormValue("name"))
	storeName := strings.TrimSpace(r.FormValue("store"))
	mode := r.FormValue("mode") // "shopping-mode" if from shopping mode page

	if name == "" {
		JSONError(w, http.StatusBadRequest, "Name is required", nil)
		return
	}
	if storeName == "" {
		JSONError(w, http.StatusBadRequest, "Store is required", nil)
		return
	}

	if err := h.store.SaveUserShoppingItem(name, storeName); err != nil {
		JSONError(w, http.StatusInternalServerError, "Failed to save item", err)
		return
	}

	ctx := r.Context()
	allStores := h.aggregateShoppingLists(ctx)

	// If called from shopping mode, return just the items for that store
	if mode == "shopping-mode" {
		items := models.FlattenItemsForStore(allStores, storeName)
		HTMLResponse(w, h.renderer, "shopping-mode-items", struct {
			StoreName string
			Items     []models.UnifiedShoppingItem
		}{storeName, items})
		return
	}

	// Return just the items content (not the entire tab) to preserve scroll position
	grouped := r.FormValue("grouped") != "false"
	HTMLResponse(w, h.renderer, "shopping-items-content", struct {
		Stores  []models.ShoppingStore
		Grouped bool
	}{allStores, grouped})
}

// HandleShoppingMode renders the focused shopping mode for a single store
func (h *Handler) HandleShoppingMode(w http.ResponseWriter, r *http.Request) {
	storeName := chi.URLParam(r, "store")
	if storeName == "" {
		http.Redirect(w, r, "/?tab=shopping", http.StatusFound)
		return
	}

	// URL decode the store name
	storeName, _ = url.QueryUnescape(storeName)

	ctx := r.Context()
	allStores := h.aggregateShoppingLists(ctx)

	data := struct {
		StoreName  string
		Items      []models.UnifiedShoppingItem
		StoreNames []string
		CSRFToken  string
	}{
		StoreName:  storeName,
		Items:      models.FlattenItemsForStore(allStores, storeName),
		StoreNames: models.StoreNames(allStores),
		CSRFToken:  auth.GetCSRFTokenFromContext(ctx),
	}

	HTMLResponse(w, h.renderer, "shopping-mode.html", data)
}

// HandleShoppingModeComplete removes an item from the shopping list
func (h *Handler) HandleShoppingModeComplete(w http.ResponseWriter, r *http.Request) {
	storeName := chi.URLParam(r, "store")
	if err := r.ParseForm(); err != nil {
		JSONError(w, http.StatusBadRequest, "Failed to parse form", err)
		return
	}

	id := r.FormValue("id")
	source := r.FormValue("source")

	// Complete (remove) the item
	switch source {
	case "user":
		var userID int64
		if _, err := fmt.Sscanf(id, "user-%d", &userID); err != nil {
			JSONError(w, http.StatusBadRequest, "Invalid user item ID", err)
			return
		}
		if err := h.store.DeleteUserShoppingItem(userID); err != nil {
			JSONError(w, http.StatusInternalServerError, "Failed to delete item", err)
			return
		}
	case "trello", "plantoeat":
		// Mark as checked (will be filtered out of view)
		if err := h.store.SetShoppingItemChecked(source, id, true); err != nil {
			JSONError(w, http.StatusInternalServerError, "Failed to complete item", err)
			return
		}
	}

	// URL decode the store name
	storeName, _ = url.QueryUnescape(storeName)

	// Return updated item list partial
	ctx := r.Context()
	allStores := h.aggregateShoppingLists(ctx)

	var items []models.UnifiedShoppingItem
	for _, store := range allStores {
		if strings.EqualFold(store.Name, storeName) {
			for _, cat := range store.Categories {
				items = append(items, cat.Items...)
			}
		}
	}

	// Sort alphabetically (checked items already filtered in template)
	sort.Slice(items, func(i, j int) bool {
		return items[i].Name < items[j].Name
	})

	HTMLResponse(w, h.renderer, "shopping-mode-items", struct {
		StoreName string
		Items     []models.UnifiedShoppingItem
	}{storeName, items})
}

// HandleGetShoppingLists returns the lists from the Shopping board for quick-add
func (h *Handler) HandleGetShoppingLists(w http.ResponseWriter, r *http.Request) {
	boards, err := h.store.GetBoards()
	if err != nil {
		JSONError(w, http.StatusInternalServerError, "Failed to get boards", err)
		return
	}

	var shoppingBoardID string
	for _, b := range boards {
		if strings.EqualFold(b.Name, "Shopping") {
			shoppingBoardID = b.ID
			break
		}
	}

	if shoppingBoardID == "" {
		JSONError(w, http.StatusNotFound, "Shopping board not found", nil)
		return
	}

	lists, err := h.trelloClient.GetLists(r.Context(), shoppingBoardID)
	if err != nil {
		JSONError(w, http.StatusInternalServerError, "Failed to get lists", err)
		return
	}

	w.Header().Set("Content-Type", "text/html")
	for _, list := range lists {
		_, _ = fmt.Fprintf(w, `<option value="%s">%s</option>`,
			template.HTMLEscapeString(list.ID),
			template.HTMLEscapeString(list.Name))
	}
}

// aggregateShoppingLists combines Trello, PlanToEat, and user shopping items by store
func (h *Handler) aggregateShoppingLists(ctx context.Context) []models.ShoppingStore {
	storeMap := make(map[string]map[string][]models.UnifiedShoppingItem)

	// Fetch locally stored checked states for external sources
	trelloChecks, _ := h.store.GetShoppingItemChecks("trello")
	plantoeatChecks, _ := h.store.GetShoppingItemChecks("plantoeat")

	// 1. Fetch Trello "Shopping" board cards
	boards, err := h.store.GetBoards()
	if err != nil {
		log.Printf("ERROR [Shopping/Trello]: %v", err)
	} else {
		for _, board := range boards {
			if strings.EqualFold(board.Name, "Shopping") {
				log.Printf("DEBUG [Shopping]: Found Shopping board with %d cards", len(board.Cards))
				for _, card := range board.Cards {
					storeName := card.ListName
					if storeName == "" {
						storeName = "Uncategorized"
					}

					if storeMap[storeName] == nil {
						storeMap[storeName] = make(map[string][]models.UnifiedShoppingItem)
					}

					item := models.UnifiedShoppingItem{
						ID:      card.ID,
						Name:    card.Name,
						Store:   storeName,
						Source:  "trello",
						Checked: trelloChecks[card.ID],
					}
					storeMap[storeName][""] = append(storeMap[storeName][""], item)
				}
			}
		}
	}

	// 2. Fetch PlanToEat shopping list
	if h.planToEatClient != nil {
		items, err := h.planToEatClient.GetShoppingList(ctx)
		if err != nil {
			log.Printf("ERROR [Shopping/PlanToEat]: %v", err)
		} else {
			log.Printf("DEBUG [Shopping/PlanToEat]: Found %d items", len(items))
			for _, item := range items {
				storeName := item.Store
				if storeName == "" {
					storeName = "PlanToEat"
				}

				if storeMap[storeName] == nil {
					storeMap[storeName] = make(map[string][]models.UnifiedShoppingItem)
				}

				// Use locally stored check state if available, otherwise use scraped state
				checked := item.Checked
				if localChecked, ok := plantoeatChecks[item.ID]; ok {
					checked = localChecked
				}
				unified := models.UnifiedShoppingItem{
					ID:       item.ID,
					Name:     item.Name,
					Quantity: item.Quantity,
					Category: item.Category,
					Store:    storeName,
					Source:   "plantoeat",
					Checked:  checked,
				}
				storeMap[storeName][item.Category] = append(storeMap[storeName][item.Category], unified)
			}
		}
	} else {
		log.Printf("DEBUG [Shopping/PlanToEat]: Client not configured")
	}

	// 3. Fetch user-added shopping items
	userItems, err := h.store.GetUserShoppingItems()
	if err != nil {
		log.Printf("ERROR [Shopping/User]: %v", err)
	} else {
		for _, item := range userItems {
			storeName := item.Store
			if storeName == "" {
				continue // Skip items without a store
			}

			if storeMap[storeName] == nil {
				storeMap[storeName] = make(map[string][]models.UnifiedShoppingItem)
			}

			unified := models.UnifiedShoppingItem{
				ID:      fmt.Sprintf("user-%d", item.ID),
				Name:    item.Name,
				Store:   storeName,
				Source:  "user",
				Checked: item.Checked,
			}
			storeMap[storeName][""] = append(storeMap[storeName][""], unified)
		}
	}

	// 4. Convert map to sorted slice
	var stores []models.ShoppingStore
	for storeName, categories := range storeMap {
		store := models.ShoppingStore{Name: storeName}

		// Get sorted category names
		var catNames []string
		for catName := range categories {
			catNames = append(catNames, catName)
		}
		sort.Strings(catNames)

		for _, catName := range catNames {
			items := categories[catName]
			sort.Slice(items, func(i, j int) bool {
				return items[i].Name < items[j].Name
			})
			store.Categories = append(store.Categories, models.ShoppingCategory{
				Name:  catName,
				Items: items,
			})
		}
		stores = append(stores, store)
	}

	// Sort stores alphabetically
	sort.Slice(stores, func(i, j int) bool {
		return stores[i].Name < stores[j].Name
	})

	return stores
}