Files
dbastrikin 5096df2102 fix: fix menu generation errors and show planned meals on home screen
Backend fixes:
- migration 003: add 'menu' value to recipe_source enum (was causing SQLSTATE 22P02)
- migration 004: rename recipe_products→recipe_ingredients, product_id→ingredient_id (was causing SQLSTATE 42P01)
- dish/repository.go: fix INSERT INTO tags using $1/$1 for two columns → $1/$2 (was causing SQLSTATE 42P08)
- home/handler.go: replace non-existent saved_recipes table with correct joins (recipes→dishes→dish_translations, user_saved_recipes) so today's plan and recommendations load correctly
- reqlog: new slog.Handler wrapper that adds request_id and stack trace to ERROR-level logs
- all handlers: slog.Error→slog.ErrorContext so error logs include request context; writeError includes request_id in response body

Client:
- home_screen.dart: extend home screen to future dates, show planned meals as ghost entries
- l10n: add new localisation keys for home screen date navigation and planned meal UI

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-22 00:35:11 +02:00

189 lines
5.9 KiB
Go

package diary
import (
"context"
"encoding/json"
"log/slog"
"net/http"
"strconv"
"github.com/food-ai/backend/internal/infra/middleware"
"github.com/go-chi/chi/v5"
)
// DiaryRepository is the data layer interface used by Handler.
type DiaryRepository interface {
ListByDate(ctx context.Context, userID, date string) ([]*Entry, error)
Create(ctx context.Context, userID string, req CreateRequest) (*Entry, error)
Delete(ctx context.Context, id, userID string) error
GetRecent(ctx context.Context, userID string, limit int) ([]*RecentDiaryItem, error)
}
// DishRepository is the subset of dish.Repository used by Handler to resolve dish IDs.
type DishRepository interface {
FindOrCreate(ctx context.Context, name string) (string, bool, error)
}
// RecipeRepository is the subset of dish.Repository used by Handler to resolve recipe IDs.
type RecipeRepository interface {
FindOrCreateRecipe(ctx context.Context, dishID string, calories, proteinG, fatG, carbsG float64) (string, bool, error)
}
// Handler handles diary endpoints.
type Handler struct {
repo DiaryRepository
dishRepo DishRepository
recipeRepo RecipeRepository
}
// NewHandler creates a new Handler.
func NewHandler(repo DiaryRepository, dishRepo DishRepository, recipeRepo RecipeRepository) *Handler {
return &Handler{repo: repo, dishRepo: dishRepo, recipeRepo: recipeRepo}
}
// GetByDate handles GET /diary?date=YYYY-MM-DD
func (h *Handler) GetByDate(w http.ResponseWriter, r *http.Request) {
userID := middleware.UserIDFromCtx(r.Context())
if userID == "" {
writeError(w, r, http.StatusUnauthorized, "unauthorized")
return
}
date := r.URL.Query().Get("date")
if date == "" {
writeError(w, r, http.StatusBadRequest, "date query parameter required (YYYY-MM-DD)")
return
}
entries, listError := h.repo.ListByDate(r.Context(), userID, date)
if listError != nil {
slog.ErrorContext(r.Context(), "list diary by date", "err", listError)
writeError(w, r, http.StatusInternalServerError, "failed to load diary")
return
}
if entries == nil {
entries = []*Entry{}
}
writeJSON(w, http.StatusOK, entries)
}
// Create handles POST /diary
func (h *Handler) Create(w http.ResponseWriter, r *http.Request) {
userID := middleware.UserIDFromCtx(r.Context())
if userID == "" {
writeError(w, r, http.StatusUnauthorized, "unauthorized")
return
}
var req CreateRequest
if decodeError := json.NewDecoder(r.Body).Decode(&req); decodeError != nil {
writeError(w, r, http.StatusBadRequest, "invalid request body")
return
}
if req.Date == "" || req.MealType == "" {
writeError(w, r, http.StatusBadRequest, "date and meal_type are required")
return
}
if req.DishID == nil && req.ProductID == nil && req.Name == "" {
writeError(w, r, http.StatusBadRequest, "dish_id, product_id, or name is required")
return
}
// Product-based entry: skip dish/recipe resolution entirely.
if req.ProductID == nil {
if req.DishID == nil {
dishID, _, resolveError := h.dishRepo.FindOrCreate(r.Context(), req.Name)
if resolveError != nil {
slog.ErrorContext(r.Context(), "resolve dish for diary entry", "name", req.Name, "err", resolveError)
writeError(w, r, http.StatusInternalServerError, "failed to resolve dish")
return
}
req.DishID = &dishID
}
if req.RecipeID == nil {
recipeID, _, recipeError := h.recipeRepo.FindOrCreateRecipe(r.Context(), *req.DishID, 0, 0, 0, 0)
if recipeError != nil {
slog.ErrorContext(r.Context(), "find or create recipe for diary entry", "dish_id", *req.DishID, "err", recipeError)
writeError(w, r, http.StatusInternalServerError, "failed to resolve recipe")
return
}
req.RecipeID = &recipeID
}
}
entry, createError := h.repo.Create(r.Context(), userID, req)
if createError != nil {
slog.ErrorContext(r.Context(), "create diary entry", "err", createError)
writeError(w, r, http.StatusInternalServerError, "failed to create diary entry")
return
}
writeJSON(w, http.StatusCreated, entry)
}
// GetRecent handles GET /diary/recent?limit=<n>
func (h *Handler) GetRecent(w http.ResponseWriter, r *http.Request) {
userID := middleware.UserIDFromCtx(r.Context())
if userID == "" {
writeError(w, r, http.StatusUnauthorized, "unauthorized")
return
}
limit := 10
if limitStr := r.URL.Query().Get("limit"); limitStr != "" {
if parsed, parseError := strconv.Atoi(limitStr); parseError == nil && parsed > 0 && parsed <= 20 {
limit = parsed
}
}
items, queryError := h.repo.GetRecent(r.Context(), userID, limit)
if queryError != nil {
slog.ErrorContext(r.Context(), "get recent diary items", "err", queryError)
writeError(w, r, http.StatusInternalServerError, "failed to get recent items")
return
}
if items == nil {
items = []*RecentDiaryItem{}
}
writeJSON(w, http.StatusOK, items)
}
// Delete handles DELETE /diary/{id}
func (h *Handler) Delete(w http.ResponseWriter, r *http.Request) {
userID := middleware.UserIDFromCtx(r.Context())
if userID == "" {
writeError(w, r, http.StatusUnauthorized, "unauthorized")
return
}
id := chi.URLParam(r, "id")
if deleteError := h.repo.Delete(r.Context(), id, userID); deleteError != nil {
if deleteError == ErrNotFound {
writeError(w, r, http.StatusNotFound, "diary entry not found")
return
}
slog.ErrorContext(r.Context(), "delete diary entry", "err", deleteError)
writeError(w, r, http.StatusInternalServerError, "failed to delete diary entry")
return
}
w.WriteHeader(http.StatusNoContent)
}
type errorResponse struct {
Error string `json:"error"`
RequestID string `json:"request_id,omitempty"`
}
func writeError(w http.ResponseWriter, r *http.Request, status int, msg string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(errorResponse{
Error: msg,
RequestID: middleware.RequestIDFromCtx(r.Context()),
})
}
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(v)
}