Move all business-logic packages from internal/ root into internal/domain/: auth, cuisine, diary, dish, home, ingredient, language, menu, product, recipe, recognition, recommendation, savedrecipe, tag, units, user Rename model.go → entity.go in packages that hold domain entities: diary, dish, home, ingredient, menu, product, recipe, savedrecipe, user Update all import paths accordingly (adapters, infra/server, cmd/server, tests). No logic changes. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
302 lines
10 KiB
Go
302 lines
10 KiB
Go
package ingredient
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
|
|
"github.com/food-ai/backend/internal/infra/locale"
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
)
|
|
|
|
// Repository handles persistence for ingredients 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 (English canonical content).
|
|
// Conflict is resolved on canonical_name.
|
|
func (r *Repository) Upsert(ctx context.Context, m *IngredientMapping) (*IngredientMapping, error) {
|
|
query := `
|
|
INSERT INTO ingredients (
|
|
canonical_name,
|
|
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)
|
|
ON CONFLICT (canonical_name) DO UPDATE SET
|
|
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, 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.Category, m.DefaultUnit,
|
|
m.CaloriesPer100g, m.ProteinPer100g, m.FatPer100g, m.CarbsPer100g, m.FiberPer100g,
|
|
m.StorageDays,
|
|
)
|
|
return scanMappingWrite(row)
|
|
}
|
|
|
|
// GetByID returns an ingredient by UUID.
|
|
// CanonicalName and aliases are 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.category,
|
|
COALESCE(ict.name, im.category) AS category_name,
|
|
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,
|
|
COALESCE(al.aliases, '[]'::json) AS aliases
|
|
FROM ingredients im
|
|
LEFT JOIN ingredient_translations it
|
|
ON it.ingredient_id = im.id AND it.lang = $2
|
|
LEFT JOIN ingredient_category_translations ict
|
|
ON ict.category_slug = im.category AND ict.lang = $2
|
|
LEFT JOIN LATERAL (
|
|
SELECT json_agg(ia.alias ORDER BY ia.alias) AS aliases
|
|
FROM ingredient_aliases ia
|
|
WHERE ia.ingredient_id = im.id AND ia.lang = $2
|
|
) al ON true
|
|
WHERE im.id = $1`
|
|
|
|
row := r.pool.QueryRow(ctx, query, id, lang)
|
|
m, err := scanMappingRead(row)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return nil, nil
|
|
}
|
|
return m, err
|
|
}
|
|
|
|
// FuzzyMatch finds the single best matching ingredient 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 ingredients matching the query string.
|
|
// Searches aliases table and translated names for the language in ctx.
|
|
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.category,
|
|
COALESCE(ict.name, im.category) AS category_name,
|
|
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,
|
|
COALESCE(al.aliases, '[]'::json) AS aliases
|
|
FROM ingredients im
|
|
LEFT JOIN ingredient_translations it
|
|
ON it.ingredient_id = im.id AND it.lang = $3
|
|
LEFT JOIN ingredient_category_translations ict
|
|
ON ict.category_slug = im.category AND ict.lang = $3
|
|
LEFT JOIN LATERAL (
|
|
SELECT json_agg(ia.alias ORDER BY ia.alias) AS aliases
|
|
FROM ingredient_aliases ia
|
|
WHERE ia.ingredient_id = im.id AND ia.lang = $3
|
|
) al ON true
|
|
WHERE EXISTS (
|
|
SELECT 1 FROM ingredient_aliases ia
|
|
WHERE ia.ingredient_id = im.id
|
|
AND (ia.lang = $3 OR ia.lang = 'en')
|
|
AND ia.alias ILIKE '%' || $1 || '%'
|
|
)
|
|
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 ingredients: %w", err)
|
|
}
|
|
defer rows.Close()
|
|
return collectMappingsRead(rows)
|
|
}
|
|
|
|
// Count returns the total number of ingredients.
|
|
func (r *Repository) Count(ctx context.Context) (int, error) {
|
|
var n int
|
|
if err := r.pool.QueryRow(ctx, `SELECT count(*) FROM ingredients`).Scan(&n); err != nil {
|
|
return 0, fmt.Errorf("count ingredients: %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.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 ingredients 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 collectMappingsWrite(rows)
|
|
}
|
|
|
|
// UpsertTranslation inserts or replaces a name translation for an ingredient.
|
|
func (r *Repository) UpsertTranslation(ctx context.Context, id, lang, name string) error {
|
|
query := `
|
|
INSERT INTO ingredient_translations (ingredient_id, lang, name)
|
|
VALUES ($1, $2, $3)
|
|
ON CONFLICT (ingredient_id, lang) DO UPDATE SET name = EXCLUDED.name`
|
|
|
|
if _, err := r.pool.Exec(ctx, query, id, lang, name); err != nil {
|
|
return fmt.Errorf("upsert ingredient translation %s/%s: %w", id, lang, err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// UpsertAliases inserts aliases for a given ingredient and language.
|
|
// Each alias is inserted with ON CONFLICT DO NOTHING, so duplicates are skipped.
|
|
func (r *Repository) UpsertAliases(ctx context.Context, id, lang string, aliases []string) error {
|
|
if len(aliases) == 0 {
|
|
return nil
|
|
}
|
|
batch := &pgx.Batch{}
|
|
for _, alias := range aliases {
|
|
batch.Queue(
|
|
`INSERT INTO ingredient_aliases (ingredient_id, lang, alias) VALUES ($1, $2, $3) ON CONFLICT DO NOTHING`,
|
|
id, lang, alias,
|
|
)
|
|
}
|
|
results := r.pool.SendBatch(ctx, batch)
|
|
defer results.Close()
|
|
for range aliases {
|
|
if _, err := results.Exec(); err != nil {
|
|
return fmt.Errorf("upsert ingredient alias %s/%s: %w", id, lang, err)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// UpsertCategoryTranslation inserts or replaces a localized category name.
|
|
func (r *Repository) UpsertCategoryTranslation(ctx context.Context, slug, lang, name string) error {
|
|
query := `
|
|
INSERT INTO ingredient_category_translations (category_slug, lang, name)
|
|
VALUES ($1, $2, $3)
|
|
ON CONFLICT (category_slug, lang) DO UPDATE SET name = EXCLUDED.name`
|
|
|
|
if _, err := r.pool.Exec(ctx, query, slug, lang, name); err != nil {
|
|
return fmt.Errorf("upsert category translation %s/%s: %w", slug, lang, err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// --- scan helpers ---
|
|
|
|
// scanMappingWrite scans rows from Upsert / ListMissingTranslation queries
|
|
// (no aliases lateral join, no category_name).
|
|
func scanMappingWrite(row pgx.Row) (*IngredientMapping, error) {
|
|
var m IngredientMapping
|
|
err := row.Scan(
|
|
&m.ID, &m.CanonicalName, &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("[]")
|
|
return &m, nil
|
|
}
|
|
|
|
// scanMappingRead scans rows from GetByID / Search queries
|
|
// (includes category_name and aliases lateral join).
|
|
func scanMappingRead(row pgx.Row) (*IngredientMapping, error) {
|
|
var m IngredientMapping
|
|
var aliases []byte
|
|
err := row.Scan(
|
|
&m.ID, &m.CanonicalName, &m.Category, &m.CategoryName, &m.DefaultUnit,
|
|
&m.CaloriesPer100g, &m.ProteinPer100g, &m.FatPer100g, &m.CarbsPer100g, &m.FiberPer100g,
|
|
&m.StorageDays, &m.CreatedAt, &m.UpdatedAt, &aliases,
|
|
)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
m.Aliases = json.RawMessage(aliases)
|
|
return &m, nil
|
|
}
|
|
|
|
func collectMappingsWrite(rows pgx.Rows) ([]*IngredientMapping, error) {
|
|
var result []*IngredientMapping
|
|
for rows.Next() {
|
|
var m IngredientMapping
|
|
if err := rows.Scan(
|
|
&m.ID, &m.CanonicalName, &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("[]")
|
|
result = append(result, &m)
|
|
}
|
|
return result, rows.Err()
|
|
}
|
|
|
|
func collectMappingsRead(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.Category, &m.CategoryName, &m.DefaultUnit,
|
|
&m.CaloriesPer100g, &m.ProteinPer100g, &m.FatPer100g, &m.CarbsPer100g, &m.FiberPer100g,
|
|
&m.StorageDays, &m.CreatedAt, &m.UpdatedAt, &aliases,
|
|
); err != nil {
|
|
return nil, fmt.Errorf("scan mapping: %w", err)
|
|
}
|
|
m.Aliases = json.RawMessage(aliases)
|
|
result = append(result, &m)
|
|
}
|
|
return result, rows.Err()
|
|
}
|