- 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>
240 lines
8.2 KiB
Go
240 lines
8.2 KiB
Go
package ingredient
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"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 and their translations.
|
|
type Repository struct {
|
|
pool *pgxpool.Pool
|
|
}
|
|
|
|
// NewRepository creates a new Repository.
|
|
func NewRepository(pool *pgxpool.Pool) *Repository {
|
|
return &Repository{pool: pool}
|
|
}
|
|
|
|
// 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, 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)
|
|
ON CONFLICT (spoonacular_id) DO UPDATE SET
|
|
canonical_name = EXCLUDED.canonical_name,
|
|
aliases = EXCLUDED.aliases,
|
|
category = EXCLUDED.category,
|
|
default_unit = EXCLUDED.default_unit,
|
|
calories_per_100g = EXCLUDED.calories_per_100g,
|
|
protein_per_100g = EXCLUDED.protein_per_100g,
|
|
fat_per_100g = EXCLUDED.fat_per_100g,
|
|
carbs_per_100g = EXCLUDED.carbs_per_100g,
|
|
fiber_per_100g = EXCLUDED.fiber_per_100g,
|
|
storage_days = EXCLUDED.storage_days,
|
|
updated_at = now()
|
|
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.SpoonacularID, m.Aliases,
|
|
m.Category, m.DefaultUnit,
|
|
m.CaloriesPer100g, m.ProteinPer100g, m.FatPer100g, m.CarbsPer100g, m.FiberPer100g,
|
|
m.StorageDays,
|
|
)
|
|
return scanMapping(row)
|
|
}
|
|
|
|
// 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 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, lang)
|
|
m, err := scanMapping(row)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return nil, nil
|
|
}
|
|
return m, err
|
|
}
|
|
|
|
// 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 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, lang)
|
|
m, err := scanMapping(row)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return nil, nil
|
|
}
|
|
return m, err
|
|
}
|
|
|
|
// 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)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if len(results) == 0 {
|
|
return nil, nil
|
|
}
|
|
return results[0], nil
|
|
}
|
|
|
|
// 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 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, lang)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("search ingredient_mappings: %w", err)
|
|
}
|
|
defer rows.Close()
|
|
return collectMappings(rows)
|
|
}
|
|
|
|
// Count returns the total number of ingredient mappings.
|
|
func (r *Repository) Count(ctx context.Context) (int, error) {
|
|
var n int
|
|
if err := r.pool.QueryRow(ctx, `SELECT count(*) FROM ingredient_mappings`).Scan(&n); err != nil {
|
|
return 0, fmt.Errorf("count ingredient_mappings: %w", err)
|
|
}
|
|
return n, nil
|
|
}
|
|
|
|
// 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 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, lang)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("list missing translation (%s): %w", lang, err)
|
|
}
|
|
defer rows.Close()
|
|
return collectMappings(rows)
|
|
}
|
|
|
|
// 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 := `
|
|
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, lang, name, aliases); err != nil {
|
|
return fmt.Errorf("upsert ingredient translation %s/%s: %w", id, lang, err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// --- helpers ---
|
|
|
|
func scanMapping(row pgx.Row) (*IngredientMapping, error) {
|
|
var m IngredientMapping
|
|
var aliases []byte
|
|
|
|
err := row.Scan(
|
|
&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,
|
|
)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
m.Aliases = json.RawMessage(aliases)
|
|
return &m, nil
|
|
}
|
|
|
|
func collectMappings(rows pgx.Rows) ([]*IngredientMapping, error) {
|
|
var result []*IngredientMapping
|
|
for rows.Next() {
|
|
var m IngredientMapping
|
|
var aliases []byte
|
|
if err := rows.Scan(
|
|
&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,
|
|
); err != nil {
|
|
return nil, fmt.Errorf("scan mapping: %w", err)
|
|
}
|
|
m.Aliases = json.RawMessage(aliases)
|
|
result = append(result, &m)
|
|
}
|
|
return result, rows.Err()
|
|
}
|