feat: implement Iteration 1 — AI recipe recommendations

Backend:
- Add Groq LLM client (llama-3.3-70b) for recipe generation with JSON
  retry strategy (retries only on parse errors, not API errors)
- Add Pexels client for parallel photo search per recipe
- Add saved_recipes table (migration 004) with JSONB fields
- Add GET /recommendations endpoint (profile-aware prompt building)
- Add POST/GET/GET{id}/DELETE /saved-recipes CRUD endpoints
- Wire gemini, pexels, recommendation, savedrecipe packages in main.go

Flutter:
- Add Recipe, SavedRecipe models with json_serializable
- Add RecipeService (getRecommendations, getSavedRecipes, save, delete)
- Add RecommendationsNotifier and SavedRecipesNotifier (Riverpod)
- Add RecommendationsScreen with skeleton loading and refresh FAB
- Add RecipeDetailScreen (SliverAppBar, nutrition tooltip, steps with timer)
- Add SavedRecipesScreen with Dismissible swipe-to-delete and empty state
- Update RecipesScreen to TabBar (Recommendations / Saved)
- Add /recipe-detail route outside ShellRoute (no bottom nav)
- Extend ApiClient with getList() and deleteVoid()

Project:
- Add CLAUDE.md with English-only rule for comments and commit messages

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
dbastrikin
2026-02-21 22:43:29 +02:00
parent 24219b611e
commit e57ff8e06c
41 changed files with 5994 additions and 353 deletions

View File

@@ -0,0 +1,28 @@
package ingredient
import (
"encoding/json"
"time"
)
// IngredientMapping is the canonical ingredient record used to link
// user products, recipe ingredients, and Spoonacular data.
type IngredientMapping struct {
ID string `json:"id"`
CanonicalName string `json:"canonical_name"`
CanonicalNameRu *string `json:"canonical_name_ru"`
SpoonacularID *int `json:"spoonacular_id"`
Aliases json.RawMessage `json:"aliases"` // []string
Category *string `json:"category"`
DefaultUnit *string `json:"default_unit"`
CaloriesPer100g *float64 `json:"calories_per_100g"`
ProteinPer100g *float64 `json:"protein_per_100g"`
FatPer100g *float64 `json:"fat_per_100g"`
CarbsPer100g *float64 `json:"carbs_per_100g"`
FiberPer100g *float64 `json:"fiber_per_100g"`
StorageDays *int `json:"storage_days"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}

View File

@@ -0,0 +1,185 @@
package ingredient
import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
// Repository handles persistence for ingredient_mappings.
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.
// Conflict is resolved on spoonacular_id when set; otherwise a simple insert is done.
func (r *Repository) Upsert(ctx context.Context, m *IngredientMapping) (*IngredientMapping, error) {
query := `
INSERT INTO ingredient_mappings (
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
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
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, 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`
row := r.pool.QueryRow(ctx, query,
m.CanonicalName, m.CanonicalNameRu, 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.
// Returns nil, nil if not found.
func (r *Repository) GetBySpoonacularID(ctx context.Context, id 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 spoonacular_id = $1`
row := r.pool.QueryRow(ctx, query, id)
m, err := scanMapping(row)
if errors.Is(err, pgx.ErrNoRows) {
return nil, nil
}
return m, err
}
// GetByID returns an ingredient mapping by UUID.
// Returns nil, nil if not found.
func (r *Repository) GetByID(ctx context.Context, id string) (*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 id = $1`
row := r.pool.QueryRow(ctx, query, id)
m, err := scanMapping(row)
if errors.Is(err, pgx.ErrNoRows) {
return nil, nil
}
return m, err
}
// 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
}
// ListUntranslated returns ingredients without a Russian name, ordered by id.
func (r *Repository) ListUntranslated(ctx context.Context, 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
LIMIT $1 OFFSET $2`
rows, err := r.pool.Query(ctx, query, limit, offset)
if err != nil {
return nil, fmt.Errorf("list untranslated: %w", 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
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`
if _, err := r.pool.Exec(ctx, query, id, canonicalNameRu, aliasesRu); err != nil {
return fmt.Errorf("update translation %s: %w", id, 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.CanonicalNameRu, &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.CanonicalNameRu, &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()
}

View File

@@ -0,0 +1,250 @@
//go:build integration
package ingredient
import (
"context"
"encoding/json"
"testing"
"github.com/food-ai/backend/internal/testutil"
)
func TestIngredientRepository_Upsert_Insert(t *testing.T) {
pool := testutil.SetupTestDB(t)
repo := NewRepository(pool)
ctx := context.Background()
id := 1001
cat := "produce"
unit := "g"
cal := 52.0
m := &IngredientMapping{
CanonicalName: "apple",
SpoonacularID: &id,
Aliases: json.RawMessage(`["apple", "apples"]`),
Category: &cat,
DefaultUnit: &unit,
CaloriesPer100g: &cal,
}
got, err := repo.Upsert(ctx, m)
if err != nil {
t.Fatalf("upsert: %v", err)
}
if got.ID == "" {
t.Error("expected non-empty ID")
}
if got.CanonicalName != "apple" {
t.Errorf("canonical_name: want apple, got %s", got.CanonicalName)
}
if *got.CaloriesPer100g != 52.0 {
t.Errorf("calories: want 52.0, got %v", got.CaloriesPer100g)
}
}
func TestIngredientRepository_Upsert_ConflictUpdates(t *testing.T) {
pool := testutil.SetupTestDB(t)
repo := NewRepository(pool)
ctx := context.Background()
id := 2001
cat := "produce"
unit := "g"
first := &IngredientMapping{
CanonicalName: "banana",
SpoonacularID: &id,
Aliases: json.RawMessage(`["banana"]`),
Category: &cat,
DefaultUnit: &unit,
}
got1, err := repo.Upsert(ctx, first)
if err != nil {
t.Fatalf("first upsert: %v", err)
}
// Update with same spoonacular_id
cal := 89.0
second := &IngredientMapping{
CanonicalName: "banana_updated",
SpoonacularID: &id,
Aliases: json.RawMessage(`["banana", "bananas"]`),
Category: &cat,
DefaultUnit: &unit,
CaloriesPer100g: &cal,
}
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.CanonicalName != "banana_updated" {
t.Errorf("canonical_name not updated: got %s", got2.CanonicalName)
}
if got2.CaloriesPer100g == nil || *got2.CaloriesPer100g != 89.0 {
t.Errorf("calories not updated: got %v", got2.CaloriesPer100g)
}
}
func TestIngredientRepository_GetBySpoonacularID_Found(t *testing.T) {
pool := testutil.SetupTestDB(t)
repo := NewRepository(pool)
ctx := context.Background()
id := 3001
cat := "dairy"
unit := "g"
_, err := repo.Upsert(ctx, &IngredientMapping{
CanonicalName: "cheese",
SpoonacularID: &id,
Aliases: json.RawMessage(`["cheese"]`),
Category: &cat,
DefaultUnit: &unit,
})
if err != nil {
t.Fatalf("upsert: %v", err)
}
got, err := repo.GetBySpoonacularID(ctx, id)
if err != nil {
t.Fatalf("get: %v", err)
}
if got == nil {
t.Fatal("expected non-nil result")
}
if got.CanonicalName != "cheese" {
t.Errorf("want cheese, got %s", got.CanonicalName)
}
}
func TestIngredientRepository_GetBySpoonacularID_NotFound(t *testing.T) {
pool := testutil.SetupTestDB(t)
repo := NewRepository(pool)
ctx := context.Background()
got, err := repo.GetBySpoonacularID(ctx, 99999999)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if got != nil {
t.Error("expected nil result for missing ID")
}
}
func TestIngredientRepository_ListUntranslated(t *testing.T) {
pool := testutil.SetupTestDB(t)
repo := NewRepository(pool)
ctx := context.Background()
cat := "produce"
unit := "g"
// Insert 3 without translation
for i, name := range []string{"carrot", "onion", "garlic"} {
id := 4000 + i
_, err := repo.Upsert(ctx, &IngredientMapping{
CanonicalName: name,
SpoonacularID: &id,
Aliases: json.RawMessage(`[]`),
Category: &cat,
DefaultUnit: &unit,
})
if err != nil {
t.Fatalf("upsert %s: %v", name, err)
}
}
// Insert 1 with translation (shouldn't appear in untranslated list)
id := 4100
ruName := "помидор"
withTranslation := &IngredientMapping{
CanonicalName: "tomato",
CanonicalNameRu: &ruName,
SpoonacularID: &id,
Aliases: json.RawMessage(`[]`),
Category: &cat,
DefaultUnit: &unit,
}
saved, err := repo.Upsert(ctx, withTranslation)
if err != nil {
t.Fatalf("upsert with translation: %v", err)
}
// The upsert doesn't set canonical_name_ru because the UPDATE clause doesn't include it
// We need to manually set it after
if err := repo.UpdateTranslation(ctx, saved.ID, "помидор", []string{"помидор", "томат"}); err != nil {
t.Fatalf("update translation: %v", err)
}
untranslated, err := repo.ListUntranslated(ctx, 10, 0)
if err != nil {
t.Fatalf("list untranslated: %v", err)
}
// Should return the 3 without translation (carrot, onion, garlic)
// The translated tomato should not appear
for _, m := range untranslated {
if m.CanonicalName == "tomato" {
t.Error("translated ingredient should not appear in ListUntranslated")
}
}
if len(untranslated) < 3 {
t.Errorf("expected at least 3 untranslated, got %d", len(untranslated))
}
}
func TestIngredientRepository_UpdateTranslation(t *testing.T) {
pool := testutil.SetupTestDB(t)
repo := NewRepository(pool)
ctx := context.Background()
id := 5001
cat := "meat"
unit := "g"
saved, err := repo.Upsert(ctx, &IngredientMapping{
CanonicalName: "chicken_breast",
SpoonacularID: &id,
Aliases: json.RawMessage(`["chicken breast"]`),
Category: &cat,
DefaultUnit: &unit,
})
if err != nil {
t.Fatalf("upsert: %v", err)
}
err = repo.UpdateTranslation(ctx, saved.ID, "куриная грудка",
[]string{"куриная грудка", "куриное филе"})
if err != nil {
t.Fatalf("update translation: %v", err)
}
got, err := repo.GetByID(ctx, saved.ID)
if err != nil {
t.Fatalf("get by id: %v", err)
}
if got.CanonicalNameRu == nil || *got.CanonicalNameRu != "куриная грудка" {
t.Errorf("expected canonical_name_ru='куриная грудка', got %v", got.CanonicalNameRu)
}
var aliases []string
if err := json.Unmarshal(got.Aliases, &aliases); err != nil {
t.Fatalf("unmarshal aliases: %v", err)
}
hasRu := false
for _, a := range aliases {
if a == "куриное филе" {
hasRu = true
break
}
}
if !hasRu {
t.Errorf("Russian alias not found in aliases: %v", aliases)
}
}