feat: slim meal_diary — derive name and nutrition from dish/recipe

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>
This commit is contained in:
dbastrikin
2026-03-18 13:28:37 +02:00
parent a32d2960c4
commit ad00998344
16 changed files with 503 additions and 109 deletions

View File

@@ -7,14 +7,14 @@ type Entry struct {
ID string `json:"id"`
Date string `json:"date"` // YYYY-MM-DD
MealType string `json:"meal_type"`
Name string `json:"name"`
Name string `json:"name"` // from dishes JOIN
Portions float64 `json:"portions"`
Calories *float64 `json:"calories,omitempty"`
Calories *float64 `json:"calories,omitempty"` // recipe.calories_per_serving * portions
ProteinG *float64 `json:"protein_g,omitempty"`
FatG *float64 `json:"fat_g,omitempty"`
CarbsG *float64 `json:"carbs_g,omitempty"`
Source string `json:"source"`
DishID *string `json:"dish_id,omitempty"`
DishID string `json:"dish_id"`
RecipeID *string `json:"recipe_id,omitempty"`
PortionG *float64 `json:"portion_g,omitempty"`
CreatedAt time.Time `json:"created_at"`
@@ -24,12 +24,8 @@ type Entry struct {
type CreateRequest struct {
Date string `json:"date"`
MealType string `json:"meal_type"`
Name string `json:"name"`
Name string `json:"name"` // input-only; used if DishID is nil
Portions float64 `json:"portions"`
Calories *float64 `json:"calories"`
ProteinG *float64 `json:"protein_g"`
FatG *float64 `json:"fat_g"`
CarbsG *float64 `json:"carbs_g"`
Source string `json:"source"`
DishID *string `json:"dish_id"`
RecipeID *string `json:"recipe_id"`

View File

@@ -17,14 +17,26 @@ type DiaryRepository interface {
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
repo DiaryRepository
dishRepo DishRepository
recipeRepo RecipeRepository
}
// NewHandler creates a new Handler.
func NewHandler(repo DiaryRepository) *Handler {
return &Handler{repo: repo}
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
@@ -41,9 +53,9 @@ func (h *Handler) GetByDate(w http.ResponseWriter, r *http.Request) {
return
}
entries, err := h.repo.ListByDate(r.Context(), userID, date)
if err != nil {
slog.Error("list diary by date", "err", err)
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
}
@@ -62,18 +74,42 @@ func (h *Handler) Create(w http.ResponseWriter, r *http.Request) {
}
var req CreateRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
if decodeError := json.NewDecoder(r.Body).Decode(&req); decodeError != nil {
writeError(w, http.StatusBadRequest, "invalid request body")
return
}
if req.Date == "" || req.Name == "" || req.MealType == "" {
writeError(w, http.StatusBadRequest, "date, meal_type and name are required")
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
}
entry, err := h.repo.Create(r.Context(), userID, req)
if err != nil {
slog.Error("create diary entry", "err", err)
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
}
@@ -89,12 +125,12 @@ func (h *Handler) Delete(w http.ResponseWriter, r *http.Request) {
}
id := chi.URLParam(r, "id")
if err := h.repo.Delete(r.Context(), id, userID); err != nil {
if err == ErrNotFound {
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", err)
slog.Error("delete diary entry", "err", deleteError)
writeError(w, http.StatusInternalServerError, "failed to delete diary entry")
return
}

View File

@@ -6,6 +6,30 @@ import (
"github.com/food-ai/backend/internal/domain/diary"
)
// MockDishRepository is a test double implementing diary.DishRepository.
type MockDishRepository struct {
FindOrCreateFn func(ctx context.Context, name string) (string, bool, error)
}
func (m *MockDishRepository) FindOrCreate(ctx context.Context, name string) (string, bool, error) {
if m.FindOrCreateFn != nil {
return m.FindOrCreateFn(ctx, name)
}
return "", false, nil
}
// MockRecipeRepository is a test double implementing diary.RecipeRepository.
type MockRecipeRepository struct {
FindOrCreateRecipeFn func(ctx context.Context, dishID string, calories, proteinG, fatG, carbsG float64) (string, bool, error)
}
func (m *MockRecipeRepository) FindOrCreateRecipe(ctx context.Context, dishID string, calories, proteinG, fatG, carbsG float64) (string, bool, error) {
if m.FindOrCreateRecipeFn != nil {
return m.FindOrCreateRecipeFn(ctx, dishID, calories, proteinG, fatG, carbsG)
}
return "", false, nil
}
// MockDiaryRepository is a test double implementing diary.DiaryRepository.
type MockDiaryRepository struct {
ListByDateFn func(ctx context.Context, userID, date string) ([]*diary.Entry, error)

View File

@@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"github.com/food-ai/backend/internal/infra/locale"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
@@ -23,14 +24,24 @@ func NewRepository(pool *pgxpool.Pool) *Repository {
}
// ListByDate returns all diary entries for a user on a given date (YYYY-MM-DD).
// Dish name and macros are computed via JOIN with dishes and recipes.
func (r *Repository) ListByDate(ctx context.Context, userID, date string) ([]*Entry, error) {
lang := locale.FromContext(ctx)
rows, err := r.pool.Query(ctx, `
SELECT id, date::text, meal_type, name, portions,
calories, protein_g, fat_g, carbs_g,
source, dish_id, recipe_id, portion_g, created_at
FROM meal_diary
WHERE user_id = $1 AND date = $2::date
ORDER BY created_at ASC`, userID, date)
SELECT
md.id, md.date::text, md.meal_type, md.portions,
md.source, md.dish_id::text, md.recipe_id::text, md.portion_g, md.created_at,
COALESCE(dt.name, d.name) AS dish_name,
r.calories_per_serving * md.portions,
r.protein_per_serving * md.portions,
r.fat_per_serving * md.portions,
r.carbs_per_serving * md.portions
FROM meal_diary md
JOIN dishes d ON d.id = md.dish_id
LEFT JOIN dish_translations dt ON dt.dish_id = d.id AND dt.lang = $3
LEFT JOIN recipes r ON r.id = md.recipe_id
WHERE md.user_id = $1 AND md.date = $2::date
ORDER BY md.created_at ASC`, userID, date, lang)
if err != nil {
return nil, fmt.Errorf("list diary: %w", err)
}
@@ -38,17 +49,18 @@ func (r *Repository) ListByDate(ctx context.Context, userID, date string) ([]*En
var result []*Entry
for rows.Next() {
e, err := scanEntry(rows)
if err != nil {
return nil, fmt.Errorf("scan diary entry: %w", err)
entry, scanError := scanEntry(rows)
if scanError != nil {
return nil, fmt.Errorf("scan diary entry: %w", scanError)
}
result = append(result, e)
result = append(result, entry)
}
return result, rows.Err()
}
// Create inserts a new diary entry and returns the stored record.
// Create inserts a new diary entry and returns the stored record (with computed macros).
func (r *Repository) Create(ctx context.Context, userID string, req CreateRequest) (*Entry, error) {
lang := locale.FromContext(ctx)
portions := req.Portions
if portions <= 0 {
portions = 1
@@ -58,25 +70,40 @@ func (r *Repository) Create(ctx context.Context, userID string, req CreateReques
source = "manual"
}
var entryID string
insertError := r.pool.QueryRow(ctx, `
INSERT INTO meal_diary (user_id, date, meal_type, portions, source, dish_id, recipe_id, portion_g)
VALUES ($1, $2::date, $3, $4, $5, $6, $7, $8)
RETURNING id`,
userID, req.Date, req.MealType, portions, source, req.DishID, req.RecipeID, req.PortionG,
).Scan(&entryID)
if insertError != nil {
return nil, fmt.Errorf("insert diary entry: %w", insertError)
}
row := r.pool.QueryRow(ctx, `
INSERT INTO meal_diary (user_id, date, meal_type, name, portions,
calories, protein_g, fat_g, carbs_g, source, dish_id, recipe_id, portion_g)
VALUES ($1, $2::date, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)
RETURNING id, date::text, meal_type, name, portions,
calories, protein_g, fat_g, carbs_g, source, dish_id, recipe_id, portion_g, created_at`,
userID, req.Date, req.MealType, req.Name, portions,
req.Calories, req.ProteinG, req.FatG, req.CarbsG,
source, req.DishID, req.RecipeID, req.PortionG,
)
SELECT
md.id, md.date::text, md.meal_type, md.portions,
md.source, md.dish_id::text, md.recipe_id::text, md.portion_g, md.created_at,
COALESCE(dt.name, d.name) AS dish_name,
r.calories_per_serving * md.portions,
r.protein_per_serving * md.portions,
r.fat_per_serving * md.portions,
r.carbs_per_serving * md.portions
FROM meal_diary md
JOIN dishes d ON d.id = md.dish_id
LEFT JOIN dish_translations dt ON dt.dish_id = d.id AND dt.lang = $2
LEFT JOIN recipes r ON r.id = md.recipe_id
WHERE md.id = $1`, entryID, lang)
return scanEntry(row)
}
// Delete removes a diary entry for the given user.
func (r *Repository) Delete(ctx context.Context, id, userID string) error {
tag, err := r.pool.Exec(ctx,
tag, deleteError := r.pool.Exec(ctx,
`DELETE FROM meal_diary WHERE id = $1 AND user_id = $2`, id, userID)
if err != nil {
return fmt.Errorf("delete diary entry: %w", err)
if deleteError != nil {
return fmt.Errorf("delete diary entry: %w", deleteError)
}
if tag.RowsAffected() == 0 {
return ErrNotFound
@@ -91,14 +118,15 @@ type scannable interface {
}
func scanEntry(s scannable) (*Entry, error) {
var e Entry
err := s.Scan(
&e.ID, &e.Date, &e.MealType, &e.Name, &e.Portions,
&e.Calories, &e.ProteinG, &e.FatG, &e.CarbsG,
&e.Source, &e.DishID, &e.RecipeID, &e.PortionG, &e.CreatedAt,
var entry Entry
scanError := s.Scan(
&entry.ID, &entry.Date, &entry.MealType, &entry.Portions,
&entry.Source, &entry.DishID, &entry.RecipeID, &entry.PortionG, &entry.CreatedAt,
&entry.Name,
&entry.Calories, &entry.ProteinG, &entry.FatG, &entry.CarbsG,
)
if errors.Is(err, pgx.ErrNoRows) {
if errors.Is(scanError, pgx.ErrNoRows) {
return nil, ErrNotFound
}
return &e, err
return &entry, scanError
}