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,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 ingredient_mappings.
|
||||
// Repository handles persistence for ingredient_mappings and their translations.
|
||||
type Repository struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
@@ -20,16 +21,16 @@ func NewRepository(pool *pgxpool.Pool) *Repository {
|
||||
return &Repository{pool: pool}
|
||||
}
|
||||
|
||||
// Upsert inserts or updates an ingredient mapping.
|
||||
// Conflict is resolved on spoonacular_id when set; otherwise a simple insert is done.
|
||||
// Upsert inserts or updates an ingredient mapping (English canonical content).
|
||||
// Conflict is resolved on spoonacular_id when set.
|
||||
func (r *Repository) Upsert(ctx context.Context, m *IngredientMapping) (*IngredientMapping, error) {
|
||||
query := `
|
||||
INSERT INTO ingredient_mappings (
|
||||
canonical_name, canonical_name_ru, spoonacular_id, aliases,
|
||||
canonical_name, spoonacular_id, aliases,
|
||||
category, default_unit,
|
||||
calories_per_100g, protein_per_100g, fat_per_100g, carbs_per_100g, fiber_per_100g,
|
||||
storage_days
|
||||
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
|
||||
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
|
||||
ON CONFLICT (spoonacular_id) DO UPDATE SET
|
||||
canonical_name = EXCLUDED.canonical_name,
|
||||
aliases = EXCLUDED.aliases,
|
||||
@@ -42,13 +43,13 @@ func (r *Repository) Upsert(ctx context.Context, m *IngredientMapping) (*Ingredi
|
||||
fiber_per_100g = EXCLUDED.fiber_per_100g,
|
||||
storage_days = EXCLUDED.storage_days,
|
||||
updated_at = now()
|
||||
RETURNING id, canonical_name, canonical_name_ru, spoonacular_id, aliases,
|
||||
RETURNING id, canonical_name, spoonacular_id, aliases,
|
||||
category, default_unit,
|
||||
calories_per_100g, protein_per_100g, fat_per_100g, carbs_per_100g, fiber_per_100g,
|
||||
storage_days, created_at, updated_at`
|
||||
|
||||
row := r.pool.QueryRow(ctx, query,
|
||||
m.CanonicalName, m.CanonicalNameRu, m.SpoonacularID, m.Aliases,
|
||||
m.CanonicalName, m.SpoonacularID, m.Aliases,
|
||||
m.Category, m.DefaultUnit,
|
||||
m.CaloriesPer100g, m.ProteinPer100g, m.FatPer100g, m.CarbsPer100g, m.FiberPer100g,
|
||||
m.StorageDays,
|
||||
@@ -57,17 +58,22 @@ func (r *Repository) Upsert(ctx context.Context, m *IngredientMapping) (*Ingredi
|
||||
}
|
||||
|
||||
// GetBySpoonacularID returns an ingredient mapping by Spoonacular ID.
|
||||
// CanonicalName is resolved for the language stored in ctx.
|
||||
// Returns nil, nil if not found.
|
||||
func (r *Repository) GetBySpoonacularID(ctx context.Context, id int) (*IngredientMapping, error) {
|
||||
lang := locale.FromContext(ctx)
|
||||
query := `
|
||||
SELECT id, canonical_name, canonical_name_ru, spoonacular_id, aliases,
|
||||
category, default_unit,
|
||||
calories_per_100g, protein_per_100g, fat_per_100g, carbs_per_100g, fiber_per_100g,
|
||||
storage_days, created_at, updated_at
|
||||
FROM ingredient_mappings
|
||||
WHERE spoonacular_id = $1`
|
||||
SELECT im.id,
|
||||
COALESCE(it.name, im.canonical_name) AS canonical_name,
|
||||
im.spoonacular_id, im.aliases,
|
||||
im.category, im.default_unit,
|
||||
im.calories_per_100g, im.protein_per_100g, im.fat_per_100g, im.carbs_per_100g, im.fiber_per_100g,
|
||||
im.storage_days, im.created_at, im.updated_at
|
||||
FROM ingredient_mappings im
|
||||
LEFT JOIN ingredient_translations it ON it.ingredient_id = im.id AND it.lang = $2
|
||||
WHERE im.spoonacular_id = $1`
|
||||
|
||||
row := r.pool.QueryRow(ctx, query, id)
|
||||
row := r.pool.QueryRow(ctx, query, id, lang)
|
||||
m, err := scanMapping(row)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, nil
|
||||
@@ -76,17 +82,22 @@ func (r *Repository) GetBySpoonacularID(ctx context.Context, id int) (*Ingredien
|
||||
}
|
||||
|
||||
// GetByID returns an ingredient mapping by UUID.
|
||||
// CanonicalName is resolved for the language stored in ctx.
|
||||
// Returns nil, nil if not found.
|
||||
func (r *Repository) GetByID(ctx context.Context, id string) (*IngredientMapping, error) {
|
||||
lang := locale.FromContext(ctx)
|
||||
query := `
|
||||
SELECT id, canonical_name, canonical_name_ru, spoonacular_id, aliases,
|
||||
category, default_unit,
|
||||
calories_per_100g, protein_per_100g, fat_per_100g, carbs_per_100g, fiber_per_100g,
|
||||
storage_days, created_at, updated_at
|
||||
FROM ingredient_mappings
|
||||
WHERE id = $1`
|
||||
SELECT im.id,
|
||||
COALESCE(it.name, im.canonical_name) AS canonical_name,
|
||||
im.spoonacular_id, im.aliases,
|
||||
im.category, im.default_unit,
|
||||
im.calories_per_100g, im.protein_per_100g, im.fat_per_100g, im.carbs_per_100g, im.fiber_per_100g,
|
||||
im.storage_days, im.created_at, im.updated_at
|
||||
FROM ingredient_mappings im
|
||||
LEFT JOIN ingredient_translations it ON it.ingredient_id = im.id AND it.lang = $2
|
||||
WHERE im.id = $1`
|
||||
|
||||
row := r.pool.QueryRow(ctx, query, id)
|
||||
row := r.pool.QueryRow(ctx, query, id, lang)
|
||||
m, err := scanMapping(row)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, nil
|
||||
@@ -95,6 +106,7 @@ func (r *Repository) GetByID(ctx context.Context, id string) (*IngredientMapping
|
||||
}
|
||||
|
||||
// FuzzyMatch finds the single best matching ingredient mapping for a given name.
|
||||
// Searches both English and translated names for the language in ctx.
|
||||
// Returns nil, nil when no match is found.
|
||||
func (r *Repository) FuzzyMatch(ctx context.Context, name string) (*IngredientMapping, error) {
|
||||
results, err := r.Search(ctx, name, 1)
|
||||
@@ -108,24 +120,31 @@ func (r *Repository) FuzzyMatch(ctx context.Context, name string) (*IngredientMa
|
||||
}
|
||||
|
||||
// Search finds ingredient mappings matching the query string.
|
||||
// Searches English aliases/name and the translated name for the language in ctx.
|
||||
// Uses a three-level strategy: exact aliases match, ILIKE, and pg_trgm similarity.
|
||||
func (r *Repository) Search(ctx context.Context, query string, limit int) ([]*IngredientMapping, error) {
|
||||
if limit <= 0 {
|
||||
limit = 10
|
||||
}
|
||||
lang := locale.FromContext(ctx)
|
||||
q := `
|
||||
SELECT id, canonical_name, canonical_name_ru, spoonacular_id, aliases,
|
||||
category, default_unit,
|
||||
calories_per_100g, protein_per_100g, fat_per_100g, carbs_per_100g, fiber_per_100g,
|
||||
storage_days, created_at, updated_at
|
||||
FROM ingredient_mappings
|
||||
WHERE aliases @> to_jsonb(lower($1)::text)
|
||||
OR canonical_name_ru ILIKE '%' || $1 || '%'
|
||||
OR similarity(canonical_name_ru, $1) > 0.3
|
||||
ORDER BY similarity(canonical_name_ru, $1) DESC
|
||||
SELECT im.id,
|
||||
COALESCE(it.name, im.canonical_name) AS canonical_name,
|
||||
im.spoonacular_id, im.aliases,
|
||||
im.category, im.default_unit,
|
||||
im.calories_per_100g, im.protein_per_100g, im.fat_per_100g, im.carbs_per_100g, im.fiber_per_100g,
|
||||
im.storage_days, im.created_at, im.updated_at
|
||||
FROM ingredient_mappings im
|
||||
LEFT JOIN ingredient_translations it ON it.ingredient_id = im.id AND it.lang = $3
|
||||
WHERE im.aliases @> to_jsonb(lower($1)::text)
|
||||
OR it.aliases @> to_jsonb(lower($1)::text)
|
||||
OR im.canonical_name ILIKE '%' || $1 || '%'
|
||||
OR it.name ILIKE '%' || $1 || '%'
|
||||
OR similarity(COALESCE(it.name, im.canonical_name), $1) > 0.3
|
||||
ORDER BY similarity(COALESCE(it.name, im.canonical_name), $1) DESC
|
||||
LIMIT $2`
|
||||
|
||||
rows, err := r.pool.Query(ctx, q, query, limit)
|
||||
rows, err := r.pool.Query(ctx, q, query, limit, lang)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("search ingredient_mappings: %w", err)
|
||||
}
|
||||
@@ -142,45 +161,41 @@ func (r *Repository) Count(ctx context.Context) (int, error) {
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// ListUntranslated returns ingredients without a Russian name, ordered by id.
|
||||
func (r *Repository) ListUntranslated(ctx context.Context, limit, offset int) ([]*IngredientMapping, error) {
|
||||
// ListMissingTranslation returns ingredients that have no translation for the
|
||||
// given language, ordered by id.
|
||||
func (r *Repository) ListMissingTranslation(ctx context.Context, lang string, limit, offset int) ([]*IngredientMapping, error) {
|
||||
query := `
|
||||
SELECT id, canonical_name, canonical_name_ru, spoonacular_id, aliases,
|
||||
category, default_unit,
|
||||
calories_per_100g, protein_per_100g, fat_per_100g, carbs_per_100g, fiber_per_100g,
|
||||
storage_days, created_at, updated_at
|
||||
FROM ingredient_mappings
|
||||
WHERE canonical_name_ru IS NULL
|
||||
ORDER BY id
|
||||
SELECT im.id, im.canonical_name, im.spoonacular_id, im.aliases,
|
||||
im.category, im.default_unit,
|
||||
im.calories_per_100g, im.protein_per_100g, im.fat_per_100g, im.carbs_per_100g, im.fiber_per_100g,
|
||||
im.storage_days, im.created_at, im.updated_at
|
||||
FROM ingredient_mappings im
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM ingredient_translations it
|
||||
WHERE it.ingredient_id = im.id AND it.lang = $3
|
||||
)
|
||||
ORDER BY im.id
|
||||
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: %w", err)
|
||||
return nil, fmt.Errorf("list missing translation (%s): %w", lang, err)
|
||||
}
|
||||
defer rows.Close()
|
||||
return collectMappings(rows)
|
||||
}
|
||||
|
||||
// UpdateTranslation saves the Russian name and adds Russian aliases.
|
||||
func (r *Repository) UpdateTranslation(ctx context.Context, id, canonicalNameRu string, aliasesRu []string) error {
|
||||
// Merge new aliases into existing JSONB array without duplicates
|
||||
// UpsertTranslation inserts or replaces a translation for an ingredient mapping.
|
||||
func (r *Repository) UpsertTranslation(ctx context.Context, id, lang, name string, aliases json.RawMessage) error {
|
||||
query := `
|
||||
UPDATE ingredient_mappings SET
|
||||
canonical_name_ru = $2,
|
||||
aliases = (
|
||||
SELECT jsonb_agg(DISTINCT elem)
|
||||
FROM (
|
||||
SELECT jsonb_array_elements(aliases) AS elem
|
||||
UNION
|
||||
SELECT to_jsonb(unnest) FROM unnest($3::text[]) AS unnest
|
||||
) sub
|
||||
),
|
||||
updated_at = now()
|
||||
WHERE id = $1`
|
||||
INSERT INTO ingredient_translations (ingredient_id, lang, name, aliases)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
ON CONFLICT (ingredient_id, lang) DO UPDATE SET
|
||||
name = EXCLUDED.name,
|
||||
aliases = EXCLUDED.aliases`
|
||||
|
||||
if _, err := r.pool.Exec(ctx, query, id, canonicalNameRu, aliasesRu); err != nil {
|
||||
return fmt.Errorf("update translation %s: %w", id, err)
|
||||
if _, err := r.pool.Exec(ctx, query, id, lang, name, aliases); err != nil {
|
||||
return fmt.Errorf("upsert ingredient translation %s/%s: %w", id, lang, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -192,7 +207,7 @@ func scanMapping(row pgx.Row) (*IngredientMapping, error) {
|
||||
var aliases []byte
|
||||
|
||||
err := row.Scan(
|
||||
&m.ID, &m.CanonicalName, &m.CanonicalNameRu, &m.SpoonacularID, &aliases,
|
||||
&m.ID, &m.CanonicalName, &m.SpoonacularID, &aliases,
|
||||
&m.Category, &m.DefaultUnit,
|
||||
&m.CaloriesPer100g, &m.ProteinPer100g, &m.FatPer100g, &m.CarbsPer100g, &m.FiberPer100g,
|
||||
&m.StorageDays, &m.CreatedAt, &m.UpdatedAt,
|
||||
@@ -210,7 +225,7 @@ func collectMappings(rows pgx.Rows) ([]*IngredientMapping, error) {
|
||||
var m IngredientMapping
|
||||
var aliases []byte
|
||||
if err := rows.Scan(
|
||||
&m.ID, &m.CanonicalName, &m.CanonicalNameRu, &m.SpoonacularID, &aliases,
|
||||
&m.ID, &m.CanonicalName, &m.SpoonacularID, &aliases,
|
||||
&m.Category, &m.DefaultUnit,
|
||||
&m.CaloriesPer100g, &m.ProteinPer100g, &m.FatPer100g, &m.CarbsPer100g, &m.FiberPer100g,
|
||||
&m.StorageDays, &m.CreatedAt, &m.UpdatedAt,
|
||||
|
||||
Reference in New Issue
Block a user