feat: core schema redesign — dishes, structured recipes, cuisines, tags (iteration 7)

Replaces the flat JSONB-based recipe schema with a normalized relational model:

Schema (migrations consolidated to 001_initial_schema + 002_seed_data):
- New: dishes, dish_translations, dish_tags — canonical dish catalog
- New: cuisines, tags, dish_categories with _translations tables + full seed data
- New: recipe_ingredients, recipe_steps with _translations (replaces JSONB blobs)
- New: user_saved_recipes thin bookmark (drops saved_recipes + saved_recipe_translations)
- New: product_ingredients M2M table
- recipes: now a cooking variant of a dish (dish_id FK, no title/JSONB columns)
- recipe_translations: repurposed to per-language notes only
- products: mapping_id → primary_ingredient_id
- menu_items: recipe_id FK → recipes; adds dish_id
- meal_diary: adds dish_id, recipe_id → recipes, portion_g

Backend (Go):
- New packages: internal/cuisine, internal/tag, internal/dish (registry + handler + repo)
- New GET /cuisines, GET /tags (public), GET /dishes, GET /dishes/{id}, GET /recipes/{id}
- recipe, savedrecipe, menu, diary, product, ingredient packages updated for new schema

Flutter:
- New models: Cuisine, Tag; new providers: cuisineNamesProvider, tagNamesProvider
- recipe.dart: RecipeIngredient gains unit_code + effectiveUnit getter
- saved_recipe.dart: thin model, manual fromJson, computed nutrition getter
- diary_entry.dart: adds dishId, recipeId, portionG
- recipe_detail_screen.dart: localized cuisine/tag names via providers

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
dbastrikin
2026-03-15 18:01:24 +02:00
parent 55d01400b0
commit 61feb91bba
52 changed files with 2479 additions and 1492 deletions

View File

@@ -0,0 +1,58 @@
package recipe
import (
"encoding/json"
"log/slog"
"net/http"
"github.com/food-ai/backend/internal/middleware"
"github.com/go-chi/chi/v5"
)
// Handler handles HTTP requests for recipes.
type Handler struct {
repo *Repository
}
// NewHandler creates a new Handler.
func NewHandler(repo *Repository) *Handler {
return &Handler{repo: repo}
}
// GetByID handles GET /recipes/{id}.
func (h *Handler) GetByID(w http.ResponseWriter, r *http.Request) {
userID := middleware.UserIDFromCtx(r.Context())
if userID == "" {
writeErrorJSON(w, http.StatusUnauthorized, "unauthorized")
return
}
id := chi.URLParam(r, "id")
rec, err := h.repo.GetByID(r.Context(), id)
if err != nil {
slog.Error("get recipe", "id", id, "err", err)
writeErrorJSON(w, http.StatusInternalServerError, "failed to get recipe")
return
}
if rec == nil {
writeErrorJSON(w, http.StatusNotFound, "recipe not found")
return
}
writeJSON(w, http.StatusOK, rec)
}
type errorResponse struct {
Error string `json:"error"`
}
func writeErrorJSON(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)
}

View File

@@ -1,28 +1,18 @@
package recipe
import (
"encoding/json"
"time"
)
import "time"
// Recipe is a recipe record in the database.
// Title, Description, Ingredients, and Steps hold the content for the language
// resolved at query time (English by default, or from recipe_translations when
// a matching row exists for the requested language).
// Recipe is a cooking variant of a Dish in the catalog.
// It links to a Dish for all presentational data (name, image, cuisine, tags).
type Recipe struct {
ID string `json:"id"`
Source string `json:"source"` // spoonacular | ai | user
SpoonacularID *int `json:"spoonacular_id"`
ID string `json:"id"`
DishID string `json:"dish_id"`
Source string `json:"source"` // ai | user | spoonacular
Title string `json:"title"`
Description *string `json:"description"`
Cuisine *string `json:"cuisine"`
Difficulty *string `json:"difficulty"` // easy | medium | hard
PrepTimeMin *int `json:"prep_time_min"`
CookTimeMin *int `json:"cook_time_min"`
Servings *int `json:"servings"`
ImageURL *string `json:"image_url"`
Difficulty *string `json:"difficulty"`
PrepTimeMin *int `json:"prep_time_min"`
CookTimeMin *int `json:"cook_time_min"`
Servings *int `json:"servings"`
CaloriesPerServing *float64 `json:"calories_per_serving"`
ProteinPerServing *float64 `json:"protein_per_serving"`
@@ -30,29 +20,29 @@ type Recipe struct {
CarbsPerServing *float64 `json:"carbs_per_serving"`
FiberPerServing *float64 `json:"fiber_per_serving"`
Ingredients json.RawMessage `json:"ingredients"` // []RecipeIngredient
Steps json.RawMessage `json:"steps"` // []RecipeStep
Tags json.RawMessage `json:"tags"` // []string
Ingredients []RecipeIngredient `json:"ingredients"`
Steps []RecipeStep `json:"steps"`
Notes *string `json:"notes,omitempty"`
AvgRating float64 `json:"avg_rating"`
ReviewCount int `json:"review_count"`
CreatedBy *string `json:"created_by"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// RecipeIngredient is a single ingredient in a recipe's JSONB array.
// RecipeIngredient is a single ingredient row from recipe_ingredients.
type RecipeIngredient struct {
MappingID *string `json:"mapping_id"`
Name string `json:"name"`
Amount float64 `json:"amount"`
Unit string `json:"unit"`
Optional bool `json:"optional"`
ID string `json:"id"`
IngredientID *string `json:"ingredient_id"`
Name string `json:"name"`
Amount float64 `json:"amount"`
UnitCode *string `json:"unit_code"`
IsOptional bool `json:"is_optional"`
SortOrder int `json:"sort_order"`
}
// RecipeStep is a single step in a recipe's JSONB array.
// RecipeStep is a single step row from recipe_steps.
type RecipeStep struct {
Number int `json:"number"`
ID string `json:"id"`
StepNumber int `json:"step_number"`
Description string `json:"description"`
TimerSeconds *int `json:"timer_seconds"`
ImageURL *string `json:"image_url"`

View File

@@ -2,7 +2,6 @@ package recipe
import (
"context"
"encoding/json"
"errors"
"fmt"
@@ -11,7 +10,7 @@ import (
"github.com/jackc/pgx/v5/pgxpool"
)
// Repository handles persistence for recipes and their translations.
// Repository handles persistence for recipes and their relational sub-tables.
type Repository struct {
pool *pgxpool.Pool
}
@@ -21,77 +20,39 @@ func NewRepository(pool *pgxpool.Pool) *Repository {
return &Repository{pool: pool}
}
// Upsert inserts or updates a recipe (English canonical content only).
// Conflict is resolved on spoonacular_id.
func (r *Repository) Upsert(ctx context.Context, recipe *Recipe) (*Recipe, error) {
query := `
INSERT INTO recipes (
source, spoonacular_id,
title, description,
cuisine, difficulty, prep_time_min, cook_time_min, servings, image_url,
calories_per_serving, protein_per_serving, fat_per_serving, carbs_per_serving, fiber_per_serving,
ingredients, steps, tags
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18)
ON CONFLICT (spoonacular_id) DO UPDATE SET
title = EXCLUDED.title,
description = EXCLUDED.description,
cuisine = EXCLUDED.cuisine,
difficulty = EXCLUDED.difficulty,
prep_time_min = EXCLUDED.prep_time_min,
cook_time_min = EXCLUDED.cook_time_min,
servings = EXCLUDED.servings,
image_url = EXCLUDED.image_url,
calories_per_serving = EXCLUDED.calories_per_serving,
protein_per_serving = EXCLUDED.protein_per_serving,
fat_per_serving = EXCLUDED.fat_per_serving,
carbs_per_serving = EXCLUDED.carbs_per_serving,
fiber_per_serving = EXCLUDED.fiber_per_serving,
ingredients = EXCLUDED.ingredients,
steps = EXCLUDED.steps,
tags = EXCLUDED.tags,
updated_at = now()
RETURNING id, source, spoonacular_id,
title, description,
cuisine, difficulty, prep_time_min, cook_time_min, servings, image_url,
calories_per_serving, protein_per_serving, fat_per_serving, carbs_per_serving, fiber_per_serving,
ingredients, steps, tags,
avg_rating, review_count, created_by, created_at, updated_at`
row := r.pool.QueryRow(ctx, query,
recipe.Source, recipe.SpoonacularID,
recipe.Title, recipe.Description,
recipe.Cuisine, recipe.Difficulty, recipe.PrepTimeMin, recipe.CookTimeMin, recipe.Servings, recipe.ImageURL,
recipe.CaloriesPerServing, recipe.ProteinPerServing, recipe.FatPerServing, recipe.CarbsPerServing, recipe.FiberPerServing,
recipe.Ingredients, recipe.Steps, recipe.Tags,
)
return scanRecipe(row)
}
// GetByID returns a recipe by UUID, with content resolved for the language
// stored in ctx (falls back to English when no translation exists).
// GetByID returns a recipe with its ingredients and steps.
// Text is resolved for the language stored in ctx (English fallback).
// Returns nil, nil if not found.
func (r *Repository) GetByID(ctx context.Context, id string) (*Recipe, error) {
lang := locale.FromContext(ctx)
query := `
SELECT r.id, r.source, r.spoonacular_id,
COALESCE(rt.title, r.title) AS title,
COALESCE(rt.description, r.description) AS description,
r.cuisine, r.difficulty, r.prep_time_min, r.cook_time_min, r.servings, r.image_url,
r.calories_per_serving, r.protein_per_serving, r.fat_per_serving, r.carbs_per_serving, r.fiber_per_serving,
COALESCE(rt.ingredients, r.ingredients) AS ingredients,
COALESCE(rt.steps, r.steps) AS steps,
r.tags,
r.avg_rating, r.review_count, r.created_by, r.created_at, r.updated_at
const q = `
SELECT r.id, r.dish_id, r.source, r.difficulty,
r.prep_time_min, r.cook_time_min, r.servings,
r.calories_per_serving, r.protein_per_serving, r.fat_per_serving,
r.carbs_per_serving, r.fiber_per_serving,
rt.notes,
r.created_at, r.updated_at
FROM recipes r
LEFT JOIN recipe_translations rt ON rt.recipe_id = r.id AND rt.lang = $2
WHERE r.id = $1`
row := r.pool.QueryRow(ctx, query, id, lang)
row := r.pool.QueryRow(ctx, q, id, lang)
rec, err := scanRecipe(row)
if errors.Is(err, pgx.ErrNoRows) {
return nil, nil
}
return rec, err
if err != nil {
return nil, fmt.Errorf("get recipe %s: %w", id, err)
}
if err := r.loadIngredients(ctx, rec, lang); err != nil {
return nil, err
}
if err := r.loadSteps(ctx, rec, lang); err != nil {
return nil, err
}
return rec, nil
}
// Count returns the total number of recipes.
@@ -103,97 +64,79 @@ func (r *Repository) Count(ctx context.Context) (int, error) {
return n, nil
}
// ListMissingTranslation returns Spoonacular recipes that have no translation
// for the given language, ordered by review_count DESC.
func (r *Repository) ListMissingTranslation(ctx context.Context, lang string, limit, offset int) ([]*Recipe, error) {
query := `
SELECT id, source, spoonacular_id,
title, description,
cuisine, difficulty, prep_time_min, cook_time_min, servings, image_url,
calories_per_serving, protein_per_serving, fat_per_serving, carbs_per_serving, fiber_per_serving,
ingredients, steps, tags,
avg_rating, review_count, created_by, created_at, updated_at
FROM recipes
WHERE source = 'spoonacular'
AND NOT EXISTS (
SELECT 1 FROM recipe_translations rt
WHERE rt.recipe_id = recipes.id AND rt.lang = $3
)
ORDER BY review_count DESC
LIMIT $1 OFFSET $2`
rows, err := r.pool.Query(ctx, query, limit, offset, lang)
// loadIngredients fills rec.Ingredients from recipe_ingredients.
func (r *Repository) loadIngredients(ctx context.Context, rec *Recipe, lang string) error {
rows, err := r.pool.Query(ctx, `
SELECT ri.id, ri.ingredient_id,
COALESCE(rit.name, ri.name) AS name,
ri.amount, ri.unit_code, ri.is_optional, ri.sort_order
FROM recipe_ingredients ri
LEFT JOIN recipe_ingredient_translations rit
ON rit.ri_id = ri.id AND rit.lang = $2
WHERE ri.recipe_id = $1
ORDER BY ri.sort_order`, rec.ID, lang)
if err != nil {
return nil, fmt.Errorf("list missing translation (%s): %w", lang, err)
return fmt.Errorf("load ingredients for recipe %s: %w", rec.ID, err)
}
defer rows.Close()
return collectRecipes(rows)
}
// UpsertTranslation inserts or replaces a recipe translation for a specific language.
func (r *Repository) UpsertTranslation(
ctx context.Context,
id, lang string,
title, description *string,
ingredients, steps json.RawMessage,
) error {
query := `
INSERT INTO recipe_translations (recipe_id, lang, title, description, ingredients, steps)
VALUES ($1, $2, $3, $4, $5, $6)
ON CONFLICT (recipe_id, lang) DO UPDATE SET
title = EXCLUDED.title,
description = EXCLUDED.description,
ingredients = EXCLUDED.ingredients,
steps = EXCLUDED.steps`
if _, err := r.pool.Exec(ctx, query, id, lang, title, description, ingredients, steps); err != nil {
return fmt.Errorf("upsert recipe translation %s/%s: %w", id, lang, err)
for rows.Next() {
var ing RecipeIngredient
if err := rows.Scan(
&ing.ID, &ing.IngredientID, &ing.Name,
&ing.Amount, &ing.UnitCode, &ing.IsOptional, &ing.SortOrder,
); err != nil {
return fmt.Errorf("scan ingredient: %w", err)
}
rec.Ingredients = append(rec.Ingredients, ing)
}
return nil
return rows.Err()
}
// --- helpers ---
// loadSteps fills rec.Steps from recipe_steps.
func (r *Repository) loadSteps(ctx context.Context, rec *Recipe, lang string) error {
rows, err := r.pool.Query(ctx, `
SELECT rs.id, rs.step_number,
COALESCE(rst.description, rs.description) AS description,
rs.timer_seconds, rs.image_url
FROM recipe_steps rs
LEFT JOIN recipe_step_translations rst
ON rst.step_id = rs.id AND rst.lang = $2
WHERE rs.recipe_id = $1
ORDER BY rs.step_number`, rec.ID, lang)
if err != nil {
return fmt.Errorf("load steps for recipe %s: %w", rec.ID, err)
}
defer rows.Close()
for rows.Next() {
var s RecipeStep
if err := rows.Scan(
&s.ID, &s.StepNumber, &s.Description, &s.TimerSeconds, &s.ImageURL,
); err != nil {
return fmt.Errorf("scan step: %w", err)
}
rec.Steps = append(rec.Steps, s)
}
return rows.Err()
}
// --- scan helpers ---
func scanRecipe(row pgx.Row) (*Recipe, error) {
var rec Recipe
var ingredients, steps, tags []byte
err := row.Scan(
&rec.ID, &rec.Source, &rec.SpoonacularID,
&rec.Title, &rec.Description,
&rec.Cuisine, &rec.Difficulty, &rec.PrepTimeMin, &rec.CookTimeMin, &rec.Servings, &rec.ImageURL,
&rec.CaloriesPerServing, &rec.ProteinPerServing, &rec.FatPerServing, &rec.CarbsPerServing, &rec.FiberPerServing,
&ingredients, &steps, &tags,
&rec.AvgRating, &rec.ReviewCount, &rec.CreatedBy, &rec.CreatedAt, &rec.UpdatedAt,
&rec.ID, &rec.DishID, &rec.Source, &rec.Difficulty,
&rec.PrepTimeMin, &rec.CookTimeMin, &rec.Servings,
&rec.CaloriesPerServing, &rec.ProteinPerServing, &rec.FatPerServing,
&rec.CarbsPerServing, &rec.FiberPerServing,
&rec.Notes,
&rec.CreatedAt, &rec.UpdatedAt,
)
if err != nil {
return nil, err
}
rec.Ingredients = json.RawMessage(ingredients)
rec.Steps = json.RawMessage(steps)
rec.Tags = json.RawMessage(tags)
rec.Ingredients = []RecipeIngredient{}
rec.Steps = []RecipeStep{}
return &rec, nil
}
func collectRecipes(rows pgx.Rows) ([]*Recipe, error) {
var result []*Recipe
for rows.Next() {
var rec Recipe
var ingredients, steps, tags []byte
if err := rows.Scan(
&rec.ID, &rec.Source, &rec.SpoonacularID,
&rec.Title, &rec.Description,
&rec.Cuisine, &rec.Difficulty, &rec.PrepTimeMin, &rec.CookTimeMin, &rec.Servings, &rec.ImageURL,
&rec.CaloriesPerServing, &rec.ProteinPerServing, &rec.FatPerServing, &rec.CarbsPerServing, &rec.FiberPerServing,
&ingredients, &steps, &tags,
&rec.AvgRating, &rec.ReviewCount, &rec.CreatedBy, &rec.CreatedAt, &rec.UpdatedAt,
); err != nil {
return nil, fmt.Errorf("scan recipe: %w", err)
}
rec.Ingredients = json.RawMessage(ingredients)
rec.Steps = json.RawMessage(steps)
rec.Tags = json.RawMessage(tags)
result = append(result, &rec)
}
return result, rows.Err()
}

View File

@@ -4,132 +4,11 @@ package recipe
import (
"context"
"encoding/json"
"testing"
"github.com/food-ai/backend/internal/locale"
"github.com/food-ai/backend/internal/testutil"
)
func TestRecipeRepository_Upsert_Insert(t *testing.T) {
pool := testutil.SetupTestDB(t)
repo := NewRepository(pool)
ctx := context.Background()
id := 10001
cuisine := "italian"
diff := "easy"
cookTime := 30
servings := 4
rec := &Recipe{
Source: "spoonacular",
SpoonacularID: &id,
Title: "Pasta Carbonara",
Cuisine: &cuisine,
Difficulty: &diff,
CookTimeMin: &cookTime,
Servings: &servings,
Ingredients: json.RawMessage(`[{"name":"pasta","amount":200,"unit":"g"}]`),
Steps: json.RawMessage(`[{"number":1,"description":"Boil pasta"}]`),
Tags: json.RawMessage(`["italian"]`),
}
got, err := repo.Upsert(ctx, rec)
if err != nil {
t.Fatalf("upsert: %v", err)
}
if got.ID == "" {
t.Error("expected non-empty ID")
}
if got.Title != "Pasta Carbonara" {
t.Errorf("title: want Pasta Carbonara, got %s", got.Title)
}
if got.SpoonacularID == nil || *got.SpoonacularID != id {
t.Errorf("spoonacular_id: want %d, got %v", id, got.SpoonacularID)
}
}
func TestRecipeRepository_Upsert_ConflictUpdates(t *testing.T) {
pool := testutil.SetupTestDB(t)
repo := NewRepository(pool)
ctx := context.Background()
id := 20001
cuisine := "mexican"
diff := "medium"
first := &Recipe{
Source: "spoonacular",
SpoonacularID: &id,
Title: "Tacos",
Cuisine: &cuisine,
Difficulty: &diff,
Ingredients: json.RawMessage(`[]`),
Steps: json.RawMessage(`[]`),
Tags: json.RawMessage(`[]`),
}
got1, err := repo.Upsert(ctx, first)
if err != nil {
t.Fatalf("first upsert: %v", err)
}
second := &Recipe{
Source: "spoonacular",
SpoonacularID: &id,
Title: "Beef Tacos",
Cuisine: &cuisine,
Difficulty: &diff,
Ingredients: json.RawMessage(`[{"name":"beef","amount":300,"unit":"g"}]`),
Steps: json.RawMessage(`[]`),
Tags: json.RawMessage(`[]`),
}
got2, err := repo.Upsert(ctx, second)
if err != nil {
t.Fatalf("second upsert: %v", err)
}
if got1.ID != got2.ID {
t.Errorf("ID changed on conflict update: %s != %s", got1.ID, got2.ID)
}
if got2.Title != "Beef Tacos" {
t.Errorf("title not updated: got %s", got2.Title)
}
}
func TestRecipeRepository_GetByID_Found(t *testing.T) {
pool := testutil.SetupTestDB(t)
repo := NewRepository(pool)
ctx := context.Background()
id := 30001
diff := "easy"
rec := &Recipe{
Source: "spoonacular",
SpoonacularID: &id,
Title: "Greek Salad",
Difficulty: &diff,
Ingredients: json.RawMessage(`[]`),
Steps: json.RawMessage(`[]`),
Tags: json.RawMessage(`["vegetarian"]`),
}
saved, err := repo.Upsert(ctx, rec)
if err != nil {
t.Fatalf("upsert: %v", err)
}
got, err := repo.GetByID(ctx, saved.ID)
if err != nil {
t.Fatalf("get by id: %v", err)
}
if got == nil {
t.Fatal("expected non-nil result")
}
if got.Title != "Greek Salad" {
t.Errorf("want Greek Salad, got %s", got.Title)
}
}
func TestRecipeRepository_GetByID_NotFound(t *testing.T) {
pool := testutil.SetupTestDB(t)
repo := NewRepository(pool)
@@ -144,181 +23,13 @@ func TestRecipeRepository_GetByID_NotFound(t *testing.T) {
}
}
func TestRecipeRepository_ListMissingTranslation_Pagination(t *testing.T) {
func TestRecipeRepository_Count(t *testing.T) {
pool := testutil.SetupTestDB(t)
repo := NewRepository(pool)
ctx := context.Background()
diff := "easy"
for i := 0; i < 5; i++ {
spID := 40000 + i
_, err := repo.Upsert(ctx, &Recipe{
Source: "spoonacular",
SpoonacularID: &spID,
Title: "Recipe " + string(rune('A'+i)),
Difficulty: &diff,
Ingredients: json.RawMessage(`[]`),
Steps: json.RawMessage(`[]`),
Tags: json.RawMessage(`[]`),
})
if err != nil {
t.Fatalf("upsert recipe %d: %v", i, err)
}
}
missing, err := repo.ListMissingTranslation(ctx, "ru", 3, 0)
_, err := repo.Count(ctx)
if err != nil {
t.Fatalf("list missing translation: %v", err)
}
if len(missing) != 3 {
t.Errorf("expected 3 results with limit=3, got %d", len(missing))
}
}
func TestRecipeRepository_UpsertTranslation(t *testing.T) {
pool := testutil.SetupTestDB(t)
repo := NewRepository(pool)
ctx := context.Background()
id := 50001
diff := "medium"
saved, err := repo.Upsert(ctx, &Recipe{
Source: "spoonacular",
SpoonacularID: &id,
Title: "Chicken Tikka Masala",
Difficulty: &diff,
Ingredients: json.RawMessage(`[]`),
Steps: json.RawMessage(`[{"number":1,"description":"Heat oil"}]`),
Tags: json.RawMessage(`[]`),
})
if err != nil {
t.Fatalf("upsert: %v", err)
}
titleRu := "Курица Тикка Масала"
descRu := "Классическое индийское блюдо"
stepsRu := json.RawMessage(`[{"number":1,"description":"Разогрейте масло"}]`)
if err := repo.UpsertTranslation(ctx, saved.ID, "ru", &titleRu, &descRu, nil, stepsRu); err != nil {
t.Fatalf("upsert translation: %v", err)
}
// Retrieve with Russian context — title and steps should be translated.
ruCtx := locale.WithLang(ctx, "ru")
got, err := repo.GetByID(ruCtx, saved.ID)
if err != nil {
t.Fatalf("get by id: %v", err)
}
if got.Title != titleRu {
t.Errorf("expected title=%q, got %q", titleRu, got.Title)
}
if got.Description == nil || *got.Description != descRu {
t.Errorf("expected description=%q, got %v", descRu, got.Description)
}
var steps []RecipeStep
if err := json.Unmarshal(got.Steps, &steps); err != nil {
t.Fatalf("unmarshal steps: %v", err)
}
if len(steps) == 0 || steps[0].Description != "Разогрейте масло" {
t.Errorf("expected Russian step description, got %v", steps)
}
// Retrieve with English context — should return original English content.
enCtx := locale.WithLang(ctx, "en")
gotEn, err := repo.GetByID(enCtx, saved.ID)
if err != nil {
t.Fatalf("get by id (en): %v", err)
}
if gotEn.Title != "Chicken Tikka Masala" {
t.Errorf("expected English title, got %q", gotEn.Title)
}
}
func TestRecipeRepository_ListMissingTranslation_ExcludesTranslated(t *testing.T) {
pool := testutil.SetupTestDB(t)
repo := NewRepository(pool)
ctx := context.Background()
diff := "easy"
// Insert untranslated recipes.
for i := 0; i < 3; i++ {
spID := 60000 + i
_, err := repo.Upsert(ctx, &Recipe{
Source: "spoonacular",
SpoonacularID: &spID,
Title: "Untranslated " + string(rune('A'+i)),
Difficulty: &diff,
Ingredients: json.RawMessage(`[]`),
Steps: json.RawMessage(`[]`),
Tags: json.RawMessage(`[]`),
})
if err != nil {
t.Fatalf("upsert: %v", err)
}
}
// Insert one recipe and add a Russian translation.
spID := 60100
translated, err := repo.Upsert(ctx, &Recipe{
Source: "spoonacular",
SpoonacularID: &spID,
Title: "Translated Recipe",
Difficulty: &diff,
Ingredients: json.RawMessage(`[]`),
Steps: json.RawMessage(`[]`),
Tags: json.RawMessage(`[]`),
})
if err != nil {
t.Fatalf("upsert translated: %v", err)
}
titleRu := "Переведённый рецепт"
if err := repo.UpsertTranslation(ctx, translated.ID, "ru", &titleRu, nil, nil, nil); err != nil {
t.Fatalf("upsert translation: %v", err)
}
missing, err := repo.ListMissingTranslation(ctx, "ru", 10, 0)
if err != nil {
t.Fatalf("list missing translation: %v", err)
}
for _, r := range missing {
if r.Title == "Translated Recipe" {
t.Error("translated recipe should not appear in ListMissingTranslation")
}
}
if len(missing) < 3 {
t.Errorf("expected at least 3 missing, got %d", len(missing))
}
}
func TestRecipeRepository_GIN_Tags(t *testing.T) {
pool := testutil.SetupTestDB(t)
repo := NewRepository(pool)
ctx := context.Background()
id := 70001
diff := "easy"
_, err := repo.Upsert(ctx, &Recipe{
Source: "spoonacular",
SpoonacularID: &id,
Title: "Veggie Bowl",
Difficulty: &diff,
Ingredients: json.RawMessage(`[]`),
Steps: json.RawMessage(`[]`),
Tags: json.RawMessage(`["vegetarian","gluten-free"]`),
})
if err != nil {
t.Fatalf("upsert: %v", err)
}
// GIN index query: tags @> '["vegetarian"]'
var count int
row := pool.QueryRow(ctx, `SELECT count(*) FROM recipes WHERE tags @> '["vegetarian"]'::jsonb AND spoonacular_id = $1`, id)
if err := row.Scan(&count); err != nil {
t.Fatalf("query: %v", err)
}
if count != 1 {
t.Errorf("expected 1 vegetarian recipe, got %d", count)
t.Fatalf("count: %v", err)
}
}