summaryrefslogtreecommitdiff
path: root/internal/handlers/shopping.go
blob: 69cb2b7d0cad4db9ece0ecb408a5afbef500adbb (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
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 (PlanToEat + user-added 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 "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})
}

// HandleGetShoppingStores returns the current store names as <option> elements
// for the quick-action modal's store picker.
//
// This replaces the Trello-lists endpoint the modal used to call. Note the
// store names come from the items themselves — there is no separate store
// registry yet, so a store with nothing in it does not appear here.
func (h *Handler) HandleGetShoppingStores(w http.ResponseWriter, r *http.Request) {
	stores := h.aggregateShoppingLists(r.Context())

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

// aggregateShoppingLists combines 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 the remaining external source.
	// Trello is no longer a shopping source: its items were read-only here and
	// its list names were doubling as an accidental store registry. See
	// migration 032 for the one-time import that preceded removing it.
	plantoeatChecks, _ := h.store.GetShoppingItemChecks("plantoeat")

	// 1. 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")
	}

	// 2. 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,
				Category: item.Section,
				Store:    storeName,
				Source:   "user",
				Checked:  item.Checked,
			}
			storeMap[storeName][item.Section] = append(storeMap[storeName][item.Section], unified)
		}
	}

	// 3. Every registered store appears even when empty. Without this you
	// cannot move an item into a store that has nothing in it yet, and moving
	// the last item out of a store makes it vanish mid-edit.
	registered, err := h.store.GetShoppingStores()
	if err != nil {
		log.Printf("ERROR [Shopping/Stores]: %v", err)
	} else {
		for _, st := range registered {
			if storeMap[st.Name] == nil {
				storeMap[st.Name] = make(map[string][]models.UnifiedShoppingItem)
			}
			// Likewise for sections: an empty section still needs to be a
			// destination in the edit form.
			for _, sec := range st.Sections {
				if _, ok := storeMap[st.Name][sec.Name]; !ok {
					storeMap[st.Name][sec.Name] = nil
				}
			}
		}
	}

	// 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
}