Files
food-ai/backend/internal/domain/diary/handler.go
dbastrikin 78f1c8bf76 feat: food search sheet with FTS+trgm, dish/recent endpoints, multilingual aliases
Backend:
- GET /dishes/search — hybrid FTS (english + simple) + trgm + ILIKE search
- GET /diary/recent — recently used dishes and products for the current user
- product search upgraded: FTS on canonical_name and product_aliases, ranked by GREATEST(ts_rank, similarity)
- importoff: collect product_name_ru/de/fr/... as product_aliases for multilingual search (e.g. "сникерс" → "Snickers")
- migrations: FTS + trgm indexes merged into 001_initial_schema.sql (002 removed)

Flutter:
- FoodSearchSheet: debounced search field, recently-used section, product/dish results, scan-photo and barcode chips
- DishPortionSheet: quick ½/1/1½/2 buttons + custom input
- + button in meal card now opens FoodSearchSheet instead of going directly to AI scan
- 7 new l10n keys across all 12 languages

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-21 15:28:29 +02:00

185 lines
5.6 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, 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.ProductID == nil && req.Name == "" {
writeError(w, 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.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)
}
// 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, 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.Error("get recent diary items", "err", queryError)
writeError(w, 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, 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)
}