- Rename catalog: ingredient/* → product/* (canonical_name, barcode, nutrition per 100g)
- Rename pantry: product/* → userproduct/* (user-owned items with expiry)
- Squash migrations into single 001_initial_schema.sql (clean-db baseline)
- product_categories: add English canonical name column; fix COALESCE in queries
- Remove product_translations: product names are stored in their original language
- Add default_unit_name to product API responses via unit_translations JOIN
- Add cmd/importoff: bulk import from OpenFoodFacts JSONL dump (COPY + ON CONFLICT)
- Diary: support product_id entries alongside dish_id (CHECK num_nonnulls = 1)
- Home: getLoggedCalories joins both recipes and catalog products
- Flutter: rename models/providers/services to match backend rename
- Flutter: add barcode scan flow for diary (mobile_scanner, product_portion_sheet)
- Flutter: localise 6 new keys across 12 languages (barcode scan, portion weight)
- Routes: GET /products/search, GET /products/barcode/{barcode}, /user-products
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
335 lines
12 KiB
Go
335 lines
12 KiB
Go
package product
|
|
|
|
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 catalog products 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 a catalog product (English canonical content).
|
|
// Conflict is resolved on canonical_name.
|
|
func (r *Repository) Upsert(requestContext context.Context, catalogProduct *Product) (*Product, error) {
|
|
query := `
|
|
INSERT INTO products (
|
|
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(requestContext, query,
|
|
catalogProduct.CanonicalName,
|
|
catalogProduct.Category, catalogProduct.DefaultUnit,
|
|
catalogProduct.CaloriesPer100g, catalogProduct.ProteinPer100g, catalogProduct.FatPer100g, catalogProduct.CarbsPer100g, catalogProduct.FiberPer100g,
|
|
catalogProduct.StorageDays,
|
|
)
|
|
return scanProductWrite(row)
|
|
}
|
|
|
|
// GetByID returns a catalog product by UUID.
|
|
// CanonicalName and aliases are resolved for the language stored in requestContext.
|
|
// Returns nil, nil if not found.
|
|
func (r *Repository) GetByID(requestContext context.Context, id string) (*Product, error) {
|
|
lang := locale.FromContext(requestContext)
|
|
query := `
|
|
SELECT p.id,
|
|
p.canonical_name,
|
|
p.category,
|
|
COALESCE(pct.name, pc.name) AS category_name,
|
|
p.default_unit,
|
|
COALESCE(ut.name, p.default_unit) AS unit_name,
|
|
p.calories_per_100g, p.protein_per_100g, p.fat_per_100g, p.carbs_per_100g, p.fiber_per_100g,
|
|
p.storage_days, p.created_at, p.updated_at,
|
|
COALESCE(al.aliases, '[]'::json) AS aliases
|
|
FROM products p
|
|
LEFT JOIN product_categories pc
|
|
ON pc.slug = p.category
|
|
LEFT JOIN product_category_translations pct
|
|
ON pct.product_category_slug = p.category AND pct.lang = $2
|
|
LEFT JOIN unit_translations ut
|
|
ON ut.unit_code = p.default_unit AND ut.lang = $2
|
|
LEFT JOIN LATERAL (
|
|
SELECT json_agg(pa.alias ORDER BY pa.alias) AS aliases
|
|
FROM product_aliases pa
|
|
WHERE pa.product_id = p.id AND pa.lang = $2
|
|
) al ON true
|
|
WHERE p.id = $1`
|
|
|
|
row := r.pool.QueryRow(requestContext, query, id, lang)
|
|
catalogProduct, queryError := scanProductRead(row)
|
|
if errors.Is(queryError, pgx.ErrNoRows) {
|
|
return nil, nil
|
|
}
|
|
return catalogProduct, queryError
|
|
}
|
|
|
|
// GetByBarcode returns a catalog product by barcode value.
|
|
// Returns nil, nil if not found.
|
|
func (r *Repository) GetByBarcode(requestContext context.Context, barcode string) (*Product, error) {
|
|
lang := locale.FromContext(requestContext)
|
|
query := `
|
|
SELECT p.id,
|
|
p.canonical_name,
|
|
p.category,
|
|
COALESCE(pct.name, pc.name) AS category_name,
|
|
p.default_unit,
|
|
COALESCE(ut.name, p.default_unit) AS unit_name,
|
|
p.calories_per_100g, p.protein_per_100g, p.fat_per_100g, p.carbs_per_100g, p.fiber_per_100g,
|
|
p.storage_days, p.created_at, p.updated_at,
|
|
COALESCE(al.aliases, '[]'::json) AS aliases
|
|
FROM products p
|
|
LEFT JOIN product_categories pc
|
|
ON pc.slug = p.category
|
|
LEFT JOIN product_category_translations pct
|
|
ON pct.product_category_slug = p.category AND pct.lang = $2
|
|
LEFT JOIN unit_translations ut
|
|
ON ut.unit_code = p.default_unit AND ut.lang = $2
|
|
LEFT JOIN LATERAL (
|
|
SELECT json_agg(pa.alias ORDER BY pa.alias) AS aliases
|
|
FROM product_aliases pa
|
|
WHERE pa.product_id = p.id AND pa.lang = $2
|
|
) al ON true
|
|
WHERE p.barcode = $1`
|
|
|
|
row := r.pool.QueryRow(requestContext, query, barcode, lang)
|
|
catalogProduct, queryError := scanProductRead(row)
|
|
if errors.Is(queryError, pgx.ErrNoRows) {
|
|
return nil, nil
|
|
}
|
|
return catalogProduct, queryError
|
|
}
|
|
|
|
// UpsertByBarcode inserts or updates a catalog product including its barcode.
|
|
func (r *Repository) UpsertByBarcode(requestContext context.Context, catalogProduct *Product) (*Product, error) {
|
|
query := `
|
|
INSERT INTO products (
|
|
canonical_name, barcode,
|
|
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)
|
|
ON CONFLICT (canonical_name) DO UPDATE SET
|
|
barcode = EXCLUDED.barcode,
|
|
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(requestContext, query,
|
|
catalogProduct.CanonicalName, catalogProduct.Barcode,
|
|
catalogProduct.Category, catalogProduct.DefaultUnit,
|
|
catalogProduct.CaloriesPer100g, catalogProduct.ProteinPer100g, catalogProduct.FatPer100g, catalogProduct.CarbsPer100g, catalogProduct.FiberPer100g,
|
|
catalogProduct.StorageDays,
|
|
)
|
|
return scanProductWrite(row)
|
|
}
|
|
|
|
// FuzzyMatch finds the single best matching catalog product for a given name.
|
|
// Returns nil, nil when no match is found.
|
|
func (r *Repository) FuzzyMatch(requestContext context.Context, name string) (*Product, error) {
|
|
results, searchError := r.Search(requestContext, name, 1)
|
|
if searchError != nil {
|
|
return nil, searchError
|
|
}
|
|
if len(results) == 0 {
|
|
return nil, nil
|
|
}
|
|
return results[0], nil
|
|
}
|
|
|
|
// Search finds catalog products matching the query string.
|
|
// Searches aliases table and translated names for the language in requestContext.
|
|
func (r *Repository) Search(requestContext context.Context, query string, limit int) ([]*Product, error) {
|
|
if limit <= 0 {
|
|
limit = 10
|
|
}
|
|
lang := locale.FromContext(requestContext)
|
|
searchQuery := `
|
|
SELECT p.id,
|
|
p.canonical_name,
|
|
p.category,
|
|
COALESCE(pct.name, pc.name) AS category_name,
|
|
p.default_unit,
|
|
COALESCE(ut.name, p.default_unit) AS unit_name,
|
|
p.calories_per_100g, p.protein_per_100g, p.fat_per_100g, p.carbs_per_100g, p.fiber_per_100g,
|
|
p.storage_days, p.created_at, p.updated_at,
|
|
COALESCE(al.aliases, '[]'::json) AS aliases
|
|
FROM products p
|
|
LEFT JOIN product_categories pc
|
|
ON pc.slug = p.category
|
|
LEFT JOIN product_category_translations pct
|
|
ON pct.product_category_slug = p.category AND pct.lang = $3
|
|
LEFT JOIN unit_translations ut
|
|
ON ut.unit_code = p.default_unit AND ut.lang = $3
|
|
LEFT JOIN LATERAL (
|
|
SELECT json_agg(pa.alias ORDER BY pa.alias) AS aliases
|
|
FROM product_aliases pa
|
|
WHERE pa.product_id = p.id AND pa.lang = $3
|
|
) al ON true
|
|
WHERE EXISTS (
|
|
SELECT 1 FROM product_aliases pa
|
|
WHERE pa.product_id = p.id
|
|
AND (pa.lang = $3 OR pa.lang = 'en')
|
|
AND pa.alias ILIKE '%' || $1 || '%'
|
|
)
|
|
OR p.canonical_name ILIKE '%' || $1 || '%'
|
|
OR similarity(p.canonical_name, $1) > 0.3
|
|
ORDER BY similarity(p.canonical_name, $1) DESC
|
|
LIMIT $2`
|
|
|
|
rows, queryError := r.pool.Query(requestContext, searchQuery, query, limit, lang)
|
|
if queryError != nil {
|
|
return nil, fmt.Errorf("search products: %w", queryError)
|
|
}
|
|
defer rows.Close()
|
|
return collectProductsRead(rows)
|
|
}
|
|
|
|
// Count returns the total number of catalog products.
|
|
func (r *Repository) Count(requestContext context.Context) (int, error) {
|
|
var count int
|
|
if queryError := r.pool.QueryRow(requestContext, `SELECT count(*) FROM products`).Scan(&count); queryError != nil {
|
|
return 0, fmt.Errorf("count products: %w", queryError)
|
|
}
|
|
return count, nil
|
|
}
|
|
|
|
// UpsertAliases inserts aliases for a given catalog product and language.
|
|
func (r *Repository) UpsertAliases(requestContext 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 product_aliases (product_id, lang, alias) VALUES ($1, $2, $3) ON CONFLICT DO NOTHING`,
|
|
id, lang, alias,
|
|
)
|
|
}
|
|
results := r.pool.SendBatch(requestContext, batch)
|
|
defer results.Close()
|
|
for range aliases {
|
|
if _, execError := results.Exec(); execError != nil {
|
|
return fmt.Errorf("upsert product alias %s/%s: %w", id, lang, execError)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// UpsertCategoryTranslation inserts or replaces a localized category name.
|
|
func (r *Repository) UpsertCategoryTranslation(requestContext context.Context, slug, lang, name string) error {
|
|
query := `
|
|
INSERT INTO product_category_translations (product_category_slug, lang, name)
|
|
VALUES ($1, $2, $3)
|
|
ON CONFLICT (product_category_slug, lang) DO UPDATE SET name = EXCLUDED.name`
|
|
|
|
if _, execError := r.pool.Exec(requestContext, query, slug, lang, name); execError != nil {
|
|
return fmt.Errorf("upsert category translation %s/%s: %w", slug, lang, execError)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// --- scan helpers ---
|
|
|
|
func scanProductWrite(row pgx.Row) (*Product, error) {
|
|
var catalogProduct Product
|
|
scanError := row.Scan(
|
|
&catalogProduct.ID, &catalogProduct.CanonicalName, &catalogProduct.Category, &catalogProduct.DefaultUnit,
|
|
&catalogProduct.CaloriesPer100g, &catalogProduct.ProteinPer100g, &catalogProduct.FatPer100g, &catalogProduct.CarbsPer100g, &catalogProduct.FiberPer100g,
|
|
&catalogProduct.StorageDays, &catalogProduct.CreatedAt, &catalogProduct.UpdatedAt,
|
|
)
|
|
if scanError != nil {
|
|
return nil, scanError
|
|
}
|
|
catalogProduct.Aliases = json.RawMessage("[]")
|
|
return &catalogProduct, nil
|
|
}
|
|
|
|
func scanProductRead(row pgx.Row) (*Product, error) {
|
|
var catalogProduct Product
|
|
var aliases []byte
|
|
scanError := row.Scan(
|
|
&catalogProduct.ID, &catalogProduct.CanonicalName, &catalogProduct.Category, &catalogProduct.CategoryName,
|
|
&catalogProduct.DefaultUnit, &catalogProduct.DefaultUnitName,
|
|
&catalogProduct.CaloriesPer100g, &catalogProduct.ProteinPer100g, &catalogProduct.FatPer100g, &catalogProduct.CarbsPer100g, &catalogProduct.FiberPer100g,
|
|
&catalogProduct.StorageDays, &catalogProduct.CreatedAt, &catalogProduct.UpdatedAt, &aliases,
|
|
)
|
|
if scanError != nil {
|
|
return nil, scanError
|
|
}
|
|
catalogProduct.Aliases = json.RawMessage(aliases)
|
|
return &catalogProduct, nil
|
|
}
|
|
|
|
func collectProductsWrite(rows pgx.Rows) ([]*Product, error) {
|
|
var result []*Product
|
|
for rows.Next() {
|
|
var catalogProduct Product
|
|
if scanError := rows.Scan(
|
|
&catalogProduct.ID, &catalogProduct.CanonicalName, &catalogProduct.Category, &catalogProduct.DefaultUnit,
|
|
&catalogProduct.CaloriesPer100g, &catalogProduct.ProteinPer100g, &catalogProduct.FatPer100g, &catalogProduct.CarbsPer100g, &catalogProduct.FiberPer100g,
|
|
&catalogProduct.StorageDays, &catalogProduct.CreatedAt, &catalogProduct.UpdatedAt,
|
|
); scanError != nil {
|
|
return nil, fmt.Errorf("scan product: %w", scanError)
|
|
}
|
|
catalogProduct.Aliases = json.RawMessage("[]")
|
|
result = append(result, &catalogProduct)
|
|
}
|
|
return result, rows.Err()
|
|
}
|
|
|
|
func collectProductsRead(rows pgx.Rows) ([]*Product, error) {
|
|
var result []*Product
|
|
for rows.Next() {
|
|
var catalogProduct Product
|
|
var aliases []byte
|
|
if scanError := rows.Scan(
|
|
&catalogProduct.ID, &catalogProduct.CanonicalName, &catalogProduct.Category, &catalogProduct.CategoryName,
|
|
&catalogProduct.DefaultUnit, &catalogProduct.DefaultUnitName,
|
|
&catalogProduct.CaloriesPer100g, &catalogProduct.ProteinPer100g, &catalogProduct.FatPer100g, &catalogProduct.CarbsPer100g, &catalogProduct.FiberPer100g,
|
|
&catalogProduct.StorageDays, &catalogProduct.CreatedAt, &catalogProduct.UpdatedAt, &aliases,
|
|
); scanError != nil {
|
|
return nil, fmt.Errorf("scan product: %w", scanError)
|
|
}
|
|
catalogProduct.Aliases = json.RawMessage(aliases)
|
|
result = append(result, &catalogProduct)
|
|
}
|
|
return result, rows.Err()
|
|
}
|