base feature

This commit is contained in:
2025-10-25 15:40:28 +02:00
commit 72c50549d7
15 changed files with 2104 additions and 0 deletions

113
handlers/ingredients.go Normal file
View File

@@ -0,0 +1,113 @@
package handlers
import (
"html/template"
"mealprep/database"
"net/http"
"strconv"
"strings"
)
// IngredientsHandler handles the ingredients page
func IngredientsHandler(w http.ResponseWriter, r *http.Request) {
ingredients, err := database.GetAllIngredients()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
tmpl := `
<div id="ingredients-content">
<h2>Ingredients</h2>
<form hx-post="/ingredients" hx-target="#ingredients-list" hx-swap="beforeend" class="add-form">
<input type="text" name="name" placeholder="Ingredient name" required />
<input type="text" name="unit" placeholder="Unit (e.g., grams, cups)" required />
<button type="submit">Add Ingredient</button>
</form>
<div id="ingredients-list" class="items-list">
{{range .}}
<div class="item" id="ingredient-{{.ID}}">
<span class="item-name">{{.Name}}</span>
<span class="item-unit">({{.Unit}})</span>
<button
hx-delete="/ingredients/{{.ID}}"
hx-target="#ingredient-{{.ID}}"
hx-swap="outerHTML"
hx-confirm="Are you sure you want to delete this ingredient?"
class="delete-btn">
Delete
</button>
</div>
{{end}}
</div>
</div>
`
t := template.Must(template.New("ingredients").Parse(tmpl))
t.Execute(w, ingredients)
}
// AddIngredientHandler handles adding a new ingredient
func AddIngredientHandler(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
name := strings.TrimSpace(r.FormValue("name"))
unit := strings.TrimSpace(r.FormValue("unit"))
if name == "" || unit == "" {
http.Error(w, "Name and unit are required", http.StatusBadRequest)
return
}
id, err := database.AddIngredient(name, unit)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
tmpl := `
<div class="item" id="ingredient-{{.ID}}">
<span class="item-name">{{.Name}}</span>
<span class="item-unit">({{.Unit}})</span>
<button
hx-delete="/ingredients/{{.ID}}"
hx-target="#ingredient-{{.ID}}"
hx-swap="outerHTML"
hx-confirm="Are you sure you want to delete this ingredient?"
class="delete-btn">
Delete
</button>
</div>
`
data := struct {
ID int64
Name string
Unit string
}{id, name, unit}
t := template.Must(template.New("ingredient").Parse(tmpl))
t.Execute(w, data)
}
// DeleteIngredientHandler handles deleting an ingredient
func DeleteIngredientHandler(w http.ResponseWriter, r *http.Request) {
idStr := strings.TrimPrefix(r.URL.Path, "/ingredients/")
id, err := strconv.Atoi(idStr)
if err != nil {
http.Error(w, "Invalid ID", http.StatusBadRequest)
return
}
if err := database.DeleteIngredient(id); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}