Backend: - migrations/005: add pg_trgm extension + search indexes on ingredient_mappings - migrations/006: products table with computed expires_at column - ingredient: add Search method (aliases + ILIKE + trgm) + HTTP handler - product: full package — model, repository (CRUD + BatchCreate + ListForPrompt), handler - gemini: add AvailableProducts field to RecipeRequest, include in prompt - recommendation: add ProductLister interface, load user products for personalised prompts - server/main: wire ingredient and product handlers with new routes Flutter: - models: Product, IngredientMapping with json_serializable - ProductService: getProducts, createProduct, updateProduct, deleteProduct, searchIngredients - ProductsNotifier: create/update/delete with optimistic delete - ProductsScreen: expiring-soon section, normal section, swipe-to-delete, edit bottom sheet - AddProductScreen: name field with 300ms debounce autocomplete, qty/unit/days fields - app_router: /products/add route + Badge on Products nav tab showing expiring count - MainShell converted to ConsumerWidget for badge reactivity Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
212 lines
6.8 KiB
Go
212 lines
6.8 KiB
Go
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
|
|
}
|
|
|
|
// Search finds ingredient mappings matching the query string.
|
|
// 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
|
|
}
|
|
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
|
|
LIMIT $2`
|
|
|
|
rows, err := r.pool.Query(ctx, q, query, limit)
|
|
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
|
|
}
|
|
|
|
// 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()
|
|
}
|