Remove denormalized columns (name, calories, protein_g, fat_g, carbs_g) from meal_diary. Name is now resolved via JOIN with dishes/dish_translations; macros are computed as recipe.*_per_serving * portions at query time. - Add dish.Repository.FindOrCreateRecipe: finds or creates a minimal recipe stub seeded with AI-estimated macros - recognition/handler: resolve recipe_id synchronously per candidate; simplify enrichDishInBackground to translations-only - diary/handler: accept dish_id OR name; always resolve recipe_id via FindOrCreateRecipe before INSERT - diary/entity: DishID is now non-nullable string; CreateRequest drops macros - diary/repository: ListByDate and Create use JOIN to return computed macros - ai/types: add RecipeID field to DishCandidate - Update tests and wire_gen accordingly Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
155 lines
4.6 KiB
Go
155 lines
4.6 KiB
Go
package diary
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"log/slog"
|
|
"net/http"
|
|
|
|
"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
|
|
}
|
|
|
|
// 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, http.StatusUnauthorized, "unauthorized")
|
|
return
|
|
}
|
|
|
|
date := r.URL.Query().Get("date")
|
|
if date == "" {
|
|
writeError(w, http.StatusBadRequest, "date query parameter required (YYYY-MM-DD)")
|
|
return
|
|
}
|
|
|
|
entries, listError := h.repo.ListByDate(r.Context(), userID, date)
|
|
if listError != nil {
|
|
slog.Error("list diary by date", "err", listError)
|
|
writeError(w, 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, http.StatusUnauthorized, "unauthorized")
|
|
return
|
|
}
|
|
|
|
var req CreateRequest
|
|
if decodeError := json.NewDecoder(r.Body).Decode(&req); decodeError != nil {
|
|
writeError(w, http.StatusBadRequest, "invalid request body")
|
|
return
|
|
}
|
|
if req.Date == "" || req.MealType == "" {
|
|
writeError(w, http.StatusBadRequest, "date and meal_type are required")
|
|
return
|
|
}
|
|
if req.DishID == nil && req.Name == "" {
|
|
writeError(w, http.StatusBadRequest, "dish_id or name is required")
|
|
return
|
|
}
|
|
|
|
if req.DishID == nil {
|
|
dishID, _, resolveError := h.dishRepo.FindOrCreate(r.Context(), req.Name)
|
|
if resolveError != nil {
|
|
slog.Error("resolve dish for diary entry", "name", req.Name, "err", resolveError)
|
|
writeError(w, 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.Error("find or create recipe for diary entry", "dish_id", *req.DishID, "err", recipeError)
|
|
writeError(w, http.StatusInternalServerError, "failed to resolve recipe")
|
|
return
|
|
}
|
|
req.RecipeID = &recipeID
|
|
}
|
|
|
|
entry, createError := h.repo.Create(r.Context(), userID, req)
|
|
if createError != nil {
|
|
slog.Error("create diary entry", "err", createError)
|
|
writeError(w, http.StatusInternalServerError, "failed to create diary entry")
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusCreated, entry)
|
|
}
|
|
|
|
// Delete handles DELETE /diary/{id}
|
|
func (h *Handler) Delete(w http.ResponseWriter, r *http.Request) {
|
|
userID := middleware.UserIDFromCtx(r.Context())
|
|
if userID == "" {
|
|
writeError(w, 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, http.StatusNotFound, "diary entry not found")
|
|
return
|
|
}
|
|
slog.Error("delete diary entry", "err", deleteError)
|
|
writeError(w, http.StatusInternalServerError, "failed to delete diary entry")
|
|
return
|
|
}
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|
|
|
|
type errorResponse struct {
|
|
Error string `json:"error"`
|
|
}
|
|
|
|
func writeError(w http.ResponseWriter, status int, msg string) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(status)
|
|
_ = json.NewEncoder(w).Encode(errorResponse{Error: msg})
|
|
}
|
|
|
|
func writeJSON(w http.ResponseWriter, status int, v any) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(status)
|
|
_ = json.NewEncoder(w).Encode(v)
|
|
}
|