feat: implement backend localization infrastructure
- Add internal/locale package: Parse(Accept-Language), FromContext/WithLang helpers, 12 supported languages - Add Language middleware that reads Accept-Language header and stores lang in context - Register Language middleware globally in server router (after CORS) Database migrations: - 009: create recipe_translations, saved_recipe_translations, ingredient_translations tables; migrate existing _ru data - 010: drop legacy _ru columns (title_ru, description_ru, canonical_name_ru); update FTS index Models: remove all _ru fields (TitleRu, DescriptionRu, NameRu, UnitRu, CanonicalNameRu) Repositories: - recipe: Upsert drops _ru params; GetByID does LEFT JOIN COALESCE on recipe_translations; ListMissingTranslation(lang); UpsertTranslation - ingredient: same pattern with ingredient_translations; Search now queries translated names/aliases - savedrecipe: List/GetByID LEFT JOIN COALESCE on saved_recipe_translations; UpsertTranslation Gemini: - RecipeRequest/MenuRequest gain Lang field - buildRecipePrompt rewritten in English with target-language content instruction; image_query always in English - GenerateMenu propagates Lang to GenerateRecipes Handlers: - recommendation/menu: pass locale.FromContext(ctx) as Lang - recognition: saveClassification stores Russian translation via UpsertTranslation instead of _ru column Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -6,22 +6,23 @@ import (
|
||||
)
|
||||
|
||||
// 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).
|
||||
type Recipe struct {
|
||||
ID string `json:"id"`
|
||||
Source string `json:"source"` // spoonacular | ai | user
|
||||
SpoonacularID *int `json:"spoonacular_id"`
|
||||
ID string `json:"id"`
|
||||
Source string `json:"source"` // spoonacular | ai | user
|
||||
SpoonacularID *int `json:"spoonacular_id"`
|
||||
|
||||
Title string `json:"title"`
|
||||
TitleRu *string `json:"title_ru"`
|
||||
Description *string `json:"description"`
|
||||
DescriptionRu *string `json:"description_ru"`
|
||||
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"`
|
||||
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"`
|
||||
|
||||
CaloriesPerServing *float64 `json:"calories_per_serving"`
|
||||
ProteinPerServing *float64 `json:"protein_per_serving"`
|
||||
@@ -45,18 +46,15 @@ type RecipeIngredient struct {
|
||||
SpoonacularID *int `json:"spoonacular_id"`
|
||||
MappingID *string `json:"mapping_id"`
|
||||
Name string `json:"name"`
|
||||
NameRu *string `json:"name_ru"`
|
||||
Amount float64 `json:"amount"`
|
||||
Unit string `json:"unit"`
|
||||
UnitRu *string `json:"unit_ru"`
|
||||
Optional bool `json:"optional"`
|
||||
}
|
||||
|
||||
// RecipeStep is a single step in a recipe's JSONB array.
|
||||
type RecipeStep struct {
|
||||
Number int `json:"number"`
|
||||
Description string `json:"description"`
|
||||
DescriptionRu *string `json:"description_ru"`
|
||||
TimerSeconds *int `json:"timer_seconds"`
|
||||
ImageURL *string `json:"image_url"`
|
||||
Number int `json:"number"`
|
||||
Description string `json:"description"`
|
||||
TimerSeconds *int `json:"timer_seconds"`
|
||||
ImageURL *string `json:"image_url"`
|
||||
}
|
||||
|
||||
@@ -6,11 +6,12 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/food-ai/backend/internal/locale"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// Repository handles persistence for recipes.
|
||||
// Repository handles persistence for recipes and their translations.
|
||||
type Repository struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
@@ -20,17 +21,17 @@ func NewRepository(pool *pgxpool.Pool) *Repository {
|
||||
return &Repository{pool: pool}
|
||||
}
|
||||
|
||||
// Upsert inserts or updates a recipe.
|
||||
// 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, title_ru, description_ru,
|
||||
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, $19, $20)
|
||||
) 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,
|
||||
@@ -50,7 +51,7 @@ func (r *Repository) Upsert(ctx context.Context, recipe *Recipe) (*Recipe, error
|
||||
tags = EXCLUDED.tags,
|
||||
updated_at = now()
|
||||
RETURNING id, source, spoonacular_id,
|
||||
title, description, title_ru, description_ru,
|
||||
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,
|
||||
@@ -58,7 +59,7 @@ func (r *Repository) Upsert(ctx context.Context, recipe *Recipe) (*Recipe, error
|
||||
|
||||
row := r.pool.QueryRow(ctx, query,
|
||||
recipe.Source, recipe.SpoonacularID,
|
||||
recipe.Title, recipe.Description, recipe.TitleRu, recipe.DescriptionRu,
|
||||
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,
|
||||
@@ -66,6 +67,33 @@ func (r *Repository) Upsert(ctx context.Context, recipe *Recipe) (*Recipe, error
|
||||
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).
|
||||
// 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
|
||||
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)
|
||||
rec, err := scanRecipe(row)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
return rec, err
|
||||
}
|
||||
|
||||
// Count returns the total number of recipes.
|
||||
func (r *Repository) Count(ctx context.Context) (int, error) {
|
||||
var n int
|
||||
@@ -75,40 +103,51 @@ func (r *Repository) Count(ctx context.Context) (int, error) {
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// ListUntranslated returns recipes without a Russian title, ordered by review_count DESC.
|
||||
func (r *Repository) ListUntranslated(ctx context.Context, limit, offset int) ([]*Recipe, error) {
|
||||
// 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, title_ru, description_ru,
|
||||
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 title_ru IS NULL AND source = 'spoonacular'
|
||||
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)
|
||||
rows, err := r.pool.Query(ctx, query, limit, offset, lang)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list untranslated recipes: %w", err)
|
||||
return nil, fmt.Errorf("list missing translation (%s): %w", lang, err)
|
||||
}
|
||||
defer rows.Close()
|
||||
return collectRecipes(rows)
|
||||
}
|
||||
|
||||
// UpdateTranslation saves the Russian title, description, and step translations.
|
||||
func (r *Repository) UpdateTranslation(ctx context.Context, id string, titleRu, descriptionRu *string, steps json.RawMessage) error {
|
||||
// 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 := `
|
||||
UPDATE recipes SET
|
||||
title_ru = $2,
|
||||
description_ru = $3,
|
||||
steps = $4,
|
||||
updated_at = now()
|
||||
WHERE id = $1`
|
||||
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, titleRu, descriptionRu, steps); err != nil {
|
||||
return fmt.Errorf("update recipe translation %s: %w", id, err)
|
||||
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)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -121,7 +160,7 @@ func scanRecipe(row pgx.Row) (*Recipe, error) {
|
||||
|
||||
err := row.Scan(
|
||||
&rec.ID, &rec.Source, &rec.SpoonacularID,
|
||||
&rec.Title, &rec.Description, &rec.TitleRu, &rec.DescriptionRu,
|
||||
&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,
|
||||
@@ -143,7 +182,7 @@ func collectRecipes(rows pgx.Rows) ([]*Recipe, error) {
|
||||
var ingredients, steps, tags []byte
|
||||
if err := rows.Scan(
|
||||
&rec.ID, &rec.Source, &rec.SpoonacularID,
|
||||
&rec.Title, &rec.Description, &rec.TitleRu, &rec.DescriptionRu,
|
||||
&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,
|
||||
@@ -158,24 +197,3 @@ func collectRecipes(rows pgx.Rows) ([]*Recipe, error) {
|
||||
}
|
||||
return result, rows.Err()
|
||||
}
|
||||
|
||||
// GetByID returns a recipe by UUID.
|
||||
// Returns nil, nil if not found.
|
||||
func (r *Repository) GetByID(ctx context.Context, id string) (*Recipe, error) {
|
||||
query := `
|
||||
SELECT id, source, spoonacular_id,
|
||||
title, description, title_ru, description_ru,
|
||||
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 id = $1`
|
||||
|
||||
row := r.pool.QueryRow(ctx, query, id)
|
||||
rec, err := scanRecipe(row)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
return rec, err
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/food-ai/backend/internal/locale"
|
||||
"github.com/food-ai/backend/internal/testutil"
|
||||
)
|
||||
|
||||
@@ -143,7 +144,7 @@ func TestRecipeRepository_GetByID_NotFound(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecipeRepository_ListUntranslated_Pagination(t *testing.T) {
|
||||
func TestRecipeRepository_ListMissingTranslation_Pagination(t *testing.T) {
|
||||
pool := testutil.SetupTestDB(t)
|
||||
repo := NewRepository(pool)
|
||||
ctx := context.Background()
|
||||
@@ -165,16 +166,16 @@ func TestRecipeRepository_ListUntranslated_Pagination(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
untranslated, err := repo.ListUntranslated(ctx, 3, 0)
|
||||
missing, err := repo.ListMissingTranslation(ctx, "ru", 3, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("list untranslated: %v", err)
|
||||
t.Fatalf("list missing translation: %v", err)
|
||||
}
|
||||
if len(untranslated) != 3 {
|
||||
t.Errorf("expected 3 results with limit=3, got %d", len(untranslated))
|
||||
if len(missing) != 3 {
|
||||
t.Errorf("expected 3 results with limit=3, got %d", len(missing))
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecipeRepository_UpdateTranslation(t *testing.T) {
|
||||
func TestRecipeRepository_UpsertTranslation(t *testing.T) {
|
||||
pool := testutil.SetupTestDB(t)
|
||||
repo := NewRepository(pool)
|
||||
ctx := context.Background()
|
||||
@@ -196,40 +197,52 @@ func TestRecipeRepository_UpdateTranslation(t *testing.T) {
|
||||
|
||||
titleRu := "Курица Тикка Масала"
|
||||
descRu := "Классическое индийское блюдо"
|
||||
stepsRu := json.RawMessage(`[{"number":1,"description":"Heat oil","description_ru":"Разогрейте масло"}]`)
|
||||
stepsRu := json.RawMessage(`[{"number":1,"description":"Разогрейте масло"}]`)
|
||||
|
||||
if err := repo.UpdateTranslation(ctx, saved.ID, &titleRu, &descRu, stepsRu); err != nil {
|
||||
t.Fatalf("update translation: %v", err)
|
||||
if err := repo.UpsertTranslation(ctx, saved.ID, "ru", &titleRu, &descRu, nil, stepsRu); err != nil {
|
||||
t.Fatalf("upsert translation: %v", err)
|
||||
}
|
||||
|
||||
got, err := repo.GetByID(ctx, saved.ID)
|
||||
// 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.TitleRu == nil || *got.TitleRu != titleRu {
|
||||
t.Errorf("expected title_ru=%q, got %v", titleRu, got.TitleRu)
|
||||
if got.Title != titleRu {
|
||||
t.Errorf("expected title=%q, got %q", titleRu, got.Title)
|
||||
}
|
||||
if got.DescriptionRu == nil || *got.DescriptionRu != descRu {
|
||||
t.Errorf("expected description_ru=%q, got %v", descRu, got.DescriptionRu)
|
||||
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].DescriptionRu == nil || *steps[0].DescriptionRu != "Разогрейте масло" {
|
||||
t.Errorf("expected description_ru in steps, got %v", steps)
|
||||
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_ListUntranslated_ExcludesTranslated(t *testing.T) {
|
||||
func TestRecipeRepository_ListMissingTranslation_ExcludesTranslated(t *testing.T) {
|
||||
pool := testutil.SetupTestDB(t)
|
||||
repo := NewRepository(pool)
|
||||
ctx := context.Background()
|
||||
|
||||
diff := "easy"
|
||||
|
||||
// Insert untranslated
|
||||
// Insert untranslated recipes.
|
||||
for i := 0; i < 3; i++ {
|
||||
spID := 60000 + i
|
||||
_, err := repo.Upsert(ctx, &Recipe{
|
||||
@@ -246,7 +259,7 @@ func TestRecipeRepository_ListUntranslated_ExcludesTranslated(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// Insert translated
|
||||
// Insert one recipe and add a Russian translation.
|
||||
spID := 60100
|
||||
translated, err := repo.Upsert(ctx, &Recipe{
|
||||
Source: "spoonacular",
|
||||
@@ -261,21 +274,21 @@ func TestRecipeRepository_ListUntranslated_ExcludesTranslated(t *testing.T) {
|
||||
t.Fatalf("upsert translated: %v", err)
|
||||
}
|
||||
titleRu := "Переведённый рецепт"
|
||||
if err := repo.UpdateTranslation(ctx, translated.ID, &titleRu, nil, translated.Steps); err != nil {
|
||||
t.Fatalf("update translation: %v", err)
|
||||
if err := repo.UpsertTranslation(ctx, translated.ID, "ru", &titleRu, nil, nil, nil); err != nil {
|
||||
t.Fatalf("upsert translation: %v", err)
|
||||
}
|
||||
|
||||
untranslated, err := repo.ListUntranslated(ctx, 10, 0)
|
||||
missing, err := repo.ListMissingTranslation(ctx, "ru", 10, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("list untranslated: %v", err)
|
||||
t.Fatalf("list missing translation: %v", err)
|
||||
}
|
||||
for _, r := range untranslated {
|
||||
for _, r := range missing {
|
||||
if r.Title == "Translated Recipe" {
|
||||
t.Error("translated recipe should not appear in ListUntranslated")
|
||||
t.Error("translated recipe should not appear in ListMissingTranslation")
|
||||
}
|
||||
}
|
||||
if len(untranslated) < 3 {
|
||||
t.Errorf("expected at least 3 untranslated, got %d", len(untranslated))
|
||||
if len(missing) < 3 {
|
||||
t.Errorf("expected at least 3 missing, got %d", len(missing))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user