feat: rename ingredients→products, products→user_products; add barcode/OFF import

- 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>
This commit is contained in:
dbastrikin
2026-03-21 12:45:48 +02:00
parent 6861e5e754
commit 205edbdade
72 changed files with 2588 additions and 1444 deletions

View File

@@ -7,14 +7,15 @@ type Entry struct {
ID string `json:"id"`
Date string `json:"date"` // YYYY-MM-DD
MealType string `json:"meal_type"`
Name string `json:"name"` // from dishes JOIN
Name string `json:"name"` // from dishes or products JOIN
Portions float64 `json:"portions"`
Calories *float64 `json:"calories,omitempty"` // recipe.calories_per_serving * portions
Calories *float64 `json:"calories,omitempty"` // recipe.calories_per_serving * portions, or product * portion_g
ProteinG *float64 `json:"protein_g,omitempty"`
FatG *float64 `json:"fat_g,omitempty"`
CarbsG *float64 `json:"carbs_g,omitempty"`
Source string `json:"source"`
DishID string `json:"dish_id"`
DishID *string `json:"dish_id,omitempty"`
ProductID *string `json:"product_id,omitempty"`
RecipeID *string `json:"recipe_id,omitempty"`
PortionG *float64 `json:"portion_g,omitempty"`
JobID *string `json:"job_id,omitempty"`
@@ -23,13 +24,14 @@ type Entry struct {
// CreateRequest is the body for POST /diary.
type CreateRequest struct {
Date string `json:"date"`
MealType string `json:"meal_type"`
Name string `json:"name"` // input-only; used if DishID is nil
Portions float64 `json:"portions"`
Source string `json:"source"`
DishID *string `json:"dish_id"`
RecipeID *string `json:"recipe_id"`
PortionG *float64 `json:"portion_g"`
JobID *string `json:"job_id"`
Date string `json:"date"`
MealType string `json:"meal_type"`
Name string `json:"name"` // input-only; used if DishID is nil and ProductID is nil
Portions float64 `json:"portions"`
Source string `json:"source"`
DishID *string `json:"dish_id"`
ProductID *string `json:"product_id"`
RecipeID *string `json:"recipe_id"`
PortionG *float64 `json:"portion_g"`
JobID *string `json:"job_id"`
}

View File

@@ -82,29 +82,32 @@ func (h *Handler) Create(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusBadRequest, "date and meal_type are required")
return
}
if req.DishID == nil && req.Name == "" {
writeError(w, http.StatusBadRequest, "dish_id or name is required")
if req.DishID == nil && req.ProductID == nil && req.Name == "" {
writeError(w, http.StatusBadRequest, "dish_id, product_id, or name is required")
return
}
if req.DishID == nil {
dishID, _, resolveError := h.dishRepo.FindOrCreate(r.Context(), req.Name)
if resolveError != nil {
slog.Error("resolve dish for diary entry", "name", req.Name, "err", resolveError)
writeError(w, http.StatusInternalServerError, "failed to resolve dish")
return
// Product-based entry: skip dish/recipe resolution entirely.
if req.ProductID == nil {
if req.DishID == nil {
dishID, _, resolveError := h.dishRepo.FindOrCreate(r.Context(), req.Name)
if resolveError != nil {
slog.Error("resolve dish for diary entry", "name", req.Name, "err", resolveError)
writeError(w, http.StatusInternalServerError, "failed to resolve dish")
return
}
req.DishID = &dishID
}
req.DishID = &dishID
}
if req.RecipeID == nil {
recipeID, _, recipeError := h.recipeRepo.FindOrCreateRecipe(r.Context(), *req.DishID, 0, 0, 0, 0)
if recipeError != nil {
slog.Error("find or create recipe for diary entry", "dish_id", *req.DishID, "err", recipeError)
writeError(w, http.StatusInternalServerError, "failed to resolve recipe")
return
if req.RecipeID == nil {
recipeID, _, recipeError := h.recipeRepo.FindOrCreateRecipe(r.Context(), *req.DishID, 0, 0, 0, 0)
if recipeError != nil {
slog.Error("find or create recipe for diary entry", "dish_id", *req.DishID, "err", recipeError)
writeError(w, http.StatusInternalServerError, "failed to resolve recipe")
return
}
req.RecipeID = &recipeID
}
req.RecipeID = &recipeID
}
entry, createError := h.repo.Create(r.Context(), userID, req)

View File

@@ -24,22 +24,35 @@ func NewRepository(pool *pgxpool.Pool) *Repository {
}
// ListByDate returns all diary entries for a user on a given date (YYYY-MM-DD).
// Dish name and macros are computed via JOIN with dishes and recipes.
// Supports both dish-based and catalog product-based entries.
func (r *Repository) ListByDate(ctx context.Context, userID, date string) ([]*Entry, error) {
lang := locale.FromContext(ctx)
rows, err := r.pool.Query(ctx, `
SELECT
md.id, md.date::text, md.meal_type, md.portions,
md.source, md.dish_id::text, md.recipe_id::text, md.portion_g, md.job_id::text, md.created_at,
COALESCE(dt.name, d.name) AS dish_name,
r.calories_per_serving * md.portions,
r.protein_per_serving * md.portions,
r.fat_per_serving * md.portions,
r.carbs_per_serving * md.portions
md.source, md.dish_id::text, md.product_id::text, md.recipe_id::text, md.portion_g, md.job_id::text, md.created_at,
COALESCE(dt.name, d.name, p.canonical_name) AS entry_name,
COALESCE(
r.calories_per_serving * md.portions,
p.calories_per_100g * md.portion_g / 100
),
COALESCE(
r.protein_per_serving * md.portions,
p.protein_per_100g * md.portion_g / 100
),
COALESCE(
r.fat_per_serving * md.portions,
p.fat_per_100g * md.portion_g / 100
),
COALESCE(
r.carbs_per_serving * md.portions,
p.carbs_per_100g * md.portion_g / 100
)
FROM meal_diary md
JOIN dishes d ON d.id = md.dish_id
LEFT JOIN dishes d ON d.id = md.dish_id
LEFT JOIN dish_translations dt ON dt.dish_id = d.id AND dt.lang = $3
LEFT JOIN recipes r ON r.id = md.recipe_id
LEFT JOIN products p ON p.id = md.product_id
WHERE md.user_id = $1 AND md.date = $2::date
ORDER BY md.created_at ASC`, userID, date, lang)
if err != nil {
@@ -72,10 +85,10 @@ func (r *Repository) Create(ctx context.Context, userID string, req CreateReques
var entryID string
insertError := r.pool.QueryRow(ctx, `
INSERT INTO meal_diary (user_id, date, meal_type, portions, source, dish_id, recipe_id, portion_g, job_id)
VALUES ($1, $2::date, $3, $4, $5, $6, $7, $8, $9)
INSERT INTO meal_diary (user_id, date, meal_type, portions, source, dish_id, product_id, recipe_id, portion_g, job_id)
VALUES ($1, $2::date, $3, $4, $5, $6, $7, $8, $9, $10)
RETURNING id`,
userID, req.Date, req.MealType, portions, source, req.DishID, req.RecipeID, req.PortionG, req.JobID,
userID, req.Date, req.MealType, portions, source, req.DishID, req.ProductID, req.RecipeID, req.PortionG, req.JobID,
).Scan(&entryID)
if insertError != nil {
return nil, fmt.Errorf("insert diary entry: %w", insertError)
@@ -84,16 +97,29 @@ func (r *Repository) Create(ctx context.Context, userID string, req CreateReques
row := r.pool.QueryRow(ctx, `
SELECT
md.id, md.date::text, md.meal_type, md.portions,
md.source, md.dish_id::text, md.recipe_id::text, md.portion_g, md.job_id::text, md.created_at,
COALESCE(dt.name, d.name) AS dish_name,
r.calories_per_serving * md.portions,
r.protein_per_serving * md.portions,
r.fat_per_serving * md.portions,
r.carbs_per_serving * md.portions
md.source, md.dish_id::text, md.product_id::text, md.recipe_id::text, md.portion_g, md.job_id::text, md.created_at,
COALESCE(dt.name, d.name, p.canonical_name) AS entry_name,
COALESCE(
r.calories_per_serving * md.portions,
p.calories_per_100g * md.portion_g / 100
),
COALESCE(
r.protein_per_serving * md.portions,
p.protein_per_100g * md.portion_g / 100
),
COALESCE(
r.fat_per_serving * md.portions,
p.fat_per_100g * md.portion_g / 100
),
COALESCE(
r.carbs_per_serving * md.portions,
p.carbs_per_100g * md.portion_g / 100
)
FROM meal_diary md
JOIN dishes d ON d.id = md.dish_id
LEFT JOIN dishes d ON d.id = md.dish_id
LEFT JOIN dish_translations dt ON dt.dish_id = d.id AND dt.lang = $2
LEFT JOIN recipes r ON r.id = md.recipe_id
LEFT JOIN products p ON p.id = md.product_id
WHERE md.id = $1`, entryID, lang)
return scanEntry(row)
}
@@ -121,7 +147,7 @@ func scanEntry(s scannable) (*Entry, error) {
var entry Entry
scanError := s.Scan(
&entry.ID, &entry.Date, &entry.MealType, &entry.Portions,
&entry.Source, &entry.DishID, &entry.RecipeID, &entry.PortionG, &entry.JobID, &entry.CreatedAt,
&entry.Source, &entry.DishID, &entry.ProductID, &entry.RecipeID, &entry.PortionG, &entry.JobID, &entry.CreatedAt,
&entry.Name,
&entry.Calories, &entry.ProteinG, &entry.FatG, &entry.CarbsG,
)

View File

@@ -76,12 +76,21 @@ func (h *Handler) getDailyGoal(ctx context.Context, userID string) int {
}
// getLoggedCalories returns total calories logged in meal_diary for today.
// Supports both recipe-based entries (via recipes JOIN) and catalog product entries (via products JOIN).
func (h *Handler) getLoggedCalories(ctx context.Context, userID, date string) float64 {
var total float64
_ = h.pool.QueryRow(ctx,
`SELECT COALESCE(SUM(calories * portions), 0)
FROM meal_diary
WHERE user_id = $1 AND date::text = $2`,
`SELECT COALESCE(SUM(
COALESCE(
r.calories_per_serving * md.portions,
p.calories_per_100g * md.portion_g / 100,
0
)
), 0)
FROM meal_diary md
LEFT JOIN recipes r ON r.id = md.recipe_id
LEFT JOIN products p ON p.id = md.product_id
WHERE md.user_id = $1 AND md.date::text = $2`,
userID, date,
).Scan(&total)
return total
@@ -153,7 +162,7 @@ func (h *Handler) getExpiringSoon(ctx context.Context, userID string) []Expiring
WITH p AS (
SELECT name, quantity, unit,
(added_at + storage_days * INTERVAL '1 day') AS expires_at
FROM products
FROM user_products
WHERE user_id = $1
)
SELECT name, quantity, unit,

View File

@@ -1,29 +0,0 @@
package ingredient
import (
"encoding/json"
"time"
)
// IngredientMapping is the canonical ingredient record used to link
// user products and recipe ingredients.
// CanonicalName holds the content for the language resolved at query time
// (English by default, or from ingredient_translations when available).
type IngredientMapping struct {
ID string `json:"id"`
CanonicalName string `json:"canonical_name"`
Aliases json.RawMessage `json:"aliases"` // []string, populated by read queries
Category *string `json:"category"`
CategoryName *string `json:"category_name"` // localized category display name
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

@@ -1,57 +0,0 @@
package ingredient
import (
"context"
"encoding/json"
"log/slog"
"net/http"
"strconv"
)
// IngredientSearcher is the data layer interface used by Handler.
type IngredientSearcher interface {
Search(ctx context.Context, query string, limit int) ([]*IngredientMapping, error)
}
// Handler handles ingredient HTTP requests.
type Handler struct {
repo IngredientSearcher
}
// NewHandler creates a new Handler.
func NewHandler(repo IngredientSearcher) *Handler {
return &Handler{repo: repo}
}
// Search handles GET /ingredients/search?q=&limit=10.
func (h *Handler) Search(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query().Get("q")
if q == "" {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte("[]"))
return
}
limit := 10
if s := r.URL.Query().Get("limit"); s != "" {
if n, err := strconv.Atoi(s); err == nil && n > 0 && n <= 50 {
limit = n
}
}
mappings, err := h.repo.Search(r.Context(), q, limit)
if err != nil {
slog.Error("search ingredients", "q", q, "err", err)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write([]byte(`{"error":"search failed"}`))
return
}
if mappings == nil {
mappings = []*IngredientMapping{}
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(mappings)
}

View File

@@ -1,301 +0,0 @@
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()
}

View File

@@ -268,15 +268,15 @@ func (r *Repository) GetPlanIDByWeek(ctx context.Context, userID, weekStart stri
return id, nil
}
// GetIngredientsByPlan returns all ingredients from all recipes in the plan.
// GetIngredientsByPlan returns all products from all recipes in the plan.
func (r *Repository) GetIngredientsByPlan(ctx context.Context, planID string) ([]ingredientRow, error) {
rows, err := r.pool.Query(ctx, `
SELECT ri.name, ri.amount, ri.unit_code, mi.meal_type
SELECT rp.name, rp.amount, rp.unit_code, mi.meal_type
FROM menu_items mi
JOIN recipes rec ON rec.id = mi.recipe_id
JOIN recipe_ingredients ri ON ri.recipe_id = rec.id
JOIN recipe_products rp ON rp.recipe_id = rec.id
WHERE mi.menu_plan_id = $1
ORDER BY ri.sort_order`, planID)
ORDER BY rp.sort_order`, planID)
if err != nil {
return nil, fmt.Errorf("get ingredients by plan: %w", err)
}

View File

@@ -1,41 +1,29 @@
package product
import "time"
import (
"encoding/json"
"time"
)
// Product is a user's food item in their pantry.
// Product is a catalog entry representing a food ingredient or packaged product.
// CanonicalName holds the English name; localized names are resolved at query time.
type Product struct {
ID string `json:"id"`
UserID string `json:"user_id"`
PrimaryIngredientID *string `json:"primary_ingredient_id"`
Name string `json:"name"`
Quantity float64 `json:"quantity"`
Unit string `json:"unit"`
Category *string `json:"category"`
StorageDays int `json:"storage_days"`
AddedAt time.Time `json:"added_at"`
ExpiresAt time.Time `json:"expires_at"`
DaysLeft int `json:"days_left"`
ExpiringSoon bool `json:"expiring_soon"`
}
ID string `json:"id"`
CanonicalName string `json:"canonical_name"`
Aliases json.RawMessage `json:"aliases"` // []string, populated by read queries
Category *string `json:"category"`
CategoryName *string `json:"category_name"` // localized category display name
DefaultUnit *string `json:"default_unit"`
DefaultUnitName *string `json:"default_unit_name,omitempty"`
Barcode *string `json:"barcode,omitempty"`
// CreateRequest is the body for POST /products.
type CreateRequest struct {
PrimaryIngredientID *string `json:"primary_ingredient_id"`
// Accept both "primary_ingredient_id" (new) and "mapping_id" (legacy client) fields.
MappingID *string `json:"mapping_id"`
Name string `json:"name"`
Quantity float64 `json:"quantity"`
Unit string `json:"unit"`
Category *string `json:"category"`
StorageDays int `json:"storage_days"`
}
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"`
// UpdateRequest is the body for PUT /products/{id}.
// All fields are optional (nil = keep existing value).
type UpdateRequest struct {
Name *string `json:"name"`
Quantity *float64 `json:"quantity"`
Unit *string `json:"unit"`
Category *string `json:"category"`
StorageDays *int `json:"storage_days"`
StorageDays *int `json:"storage_days"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}

View File

@@ -3,145 +3,121 @@ package product
import (
"context"
"encoding/json"
"errors"
"log/slog"
"net/http"
"strconv"
"github.com/food-ai/backend/internal/infra/middleware"
"github.com/go-chi/chi/v5"
)
// ProductRepository is the data layer interface used by Handler.
type ProductRepository interface {
List(ctx context.Context, userID string) ([]*Product, error)
Create(ctx context.Context, userID string, req CreateRequest) (*Product, error)
BatchCreate(ctx context.Context, userID string, items []CreateRequest) ([]*Product, error)
Update(ctx context.Context, id, userID string, req UpdateRequest) (*Product, error)
Delete(ctx context.Context, id, userID string) error
// ProductSearcher is the data layer interface used by Handler for search.
type ProductSearcher interface {
Search(ctx context.Context, query string, limit int) ([]*Product, error)
GetByBarcode(ctx context.Context, barcode string) (*Product, error)
UpsertByBarcode(ctx context.Context, catalogProduct *Product) (*Product, error)
}
// Handler handles /products HTTP requests.
// OpenFoodFactsClient fetches product data from Open Food Facts.
type OpenFoodFactsClient interface {
Fetch(requestContext context.Context, barcode string) (*Product, error)
}
// Handler handles catalog product HTTP requests.
type Handler struct {
repo ProductRepository
repo ProductSearcher
openFoodFacts OpenFoodFactsClient
}
// NewHandler creates a new Handler.
func NewHandler(repo ProductRepository) *Handler {
return &Handler{repo: repo}
func NewHandler(repo ProductSearcher, openFoodFacts OpenFoodFactsClient) *Handler {
return &Handler{repo: repo, openFoodFacts: openFoodFacts}
}
// List handles GET /products.
func (h *Handler) List(w http.ResponseWriter, r *http.Request) {
userID := middleware.UserIDFromCtx(r.Context())
products, err := h.repo.List(r.Context(), userID)
if err != nil {
slog.Error("list products", "user_id", userID, "err", err)
writeErrorJSON(w, http.StatusInternalServerError, "failed to list products")
// Search handles GET /products/search?q=&limit=10.
func (handler *Handler) Search(responseWriter http.ResponseWriter, request *http.Request) {
query := request.URL.Query().Get("q")
if query == "" {
responseWriter.Header().Set("Content-Type", "application/json")
_, _ = responseWriter.Write([]byte("[]"))
return
}
limit := 10
if limitStr := request.URL.Query().Get("limit"); limitStr != "" {
if parsedLimit, parseError := strconv.Atoi(limitStr); parseError == nil && parsedLimit > 0 && parsedLimit <= 50 {
limit = parsedLimit
}
}
products, searchError := handler.repo.Search(request.Context(), query, limit)
if searchError != nil {
slog.Error("search catalog products", "q", query, "err", searchError)
responseWriter.Header().Set("Content-Type", "application/json")
responseWriter.WriteHeader(http.StatusInternalServerError)
_, _ = responseWriter.Write([]byte(`{"error":"search failed"}`))
return
}
if products == nil {
products = []*Product{}
}
writeJSON(w, http.StatusOK, products)
responseWriter.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(responseWriter).Encode(products)
}
// Create handles POST /products.
func (h *Handler) Create(w http.ResponseWriter, r *http.Request) {
userID := middleware.UserIDFromCtx(r.Context())
var req CreateRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeErrorJSON(w, http.StatusBadRequest, "invalid request body")
return
}
if req.Name == "" {
writeErrorJSON(w, http.StatusBadRequest, "name is required")
// GetByBarcode handles GET /products/barcode/{barcode}.
// Checks the database first; on miss, fetches from Open Food Facts and caches the result.
func (handler *Handler) GetByBarcode(responseWriter http.ResponseWriter, request *http.Request) {
barcode := chi.URLParam(request, "barcode")
if barcode == "" {
writeErrorJSON(responseWriter, http.StatusBadRequest, "barcode is required")
return
}
p, err := h.repo.Create(r.Context(), userID, req)
if err != nil {
slog.Error("create product", "user_id", userID, "err", err)
writeErrorJSON(w, http.StatusInternalServerError, "failed to create product")
// Check the local catalog first.
catalogProduct, lookupError := handler.repo.GetByBarcode(request.Context(), barcode)
if lookupError != nil {
slog.Error("lookup product by barcode", "barcode", barcode, "err", lookupError)
writeErrorJSON(responseWriter, http.StatusInternalServerError, "lookup failed")
return
}
writeJSON(w, http.StatusCreated, p)
}
// BatchCreate handles POST /products/batch.
func (h *Handler) BatchCreate(w http.ResponseWriter, r *http.Request) {
userID := middleware.UserIDFromCtx(r.Context())
var items []CreateRequest
if err := json.NewDecoder(r.Body).Decode(&items); err != nil {
writeErrorJSON(w, http.StatusBadRequest, "invalid request body")
return
}
if len(items) == 0 {
writeJSON(w, http.StatusCreated, []*Product{})
if catalogProduct != nil {
writeJSON(responseWriter, http.StatusOK, catalogProduct)
return
}
products, err := h.repo.BatchCreate(r.Context(), userID, items)
if err != nil {
slog.Error("batch create products", "user_id", userID, "err", err)
writeErrorJSON(w, http.StatusInternalServerError, "failed to create products")
return
}
writeJSON(w, http.StatusCreated, products)
}
// Update handles PUT /products/{id}.
func (h *Handler) Update(w http.ResponseWriter, r *http.Request) {
userID := middleware.UserIDFromCtx(r.Context())
id := chi.URLParam(r, "id")
var req UpdateRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeErrorJSON(w, http.StatusBadRequest, "invalid request body")
// Not in catalog — fetch from Open Food Facts.
fetchedProduct, fetchError := handler.openFoodFacts.Fetch(request.Context(), barcode)
if fetchError != nil {
slog.Warn("open food facts fetch failed", "barcode", barcode, "err", fetchError)
writeErrorJSON(responseWriter, http.StatusNotFound, "product not found")
return
}
p, err := h.repo.Update(r.Context(), id, userID, req)
if errors.Is(err, ErrNotFound) {
writeErrorJSON(w, http.StatusNotFound, "product not found")
// Persist the fetched product so subsequent lookups are served from the DB.
savedProduct, upsertError := handler.repo.UpsertByBarcode(request.Context(), fetchedProduct)
if upsertError != nil {
slog.Warn("upsert product from open food facts", "barcode", barcode, "err", upsertError)
// Return the fetched data even if we could not cache it.
writeJSON(responseWriter, http.StatusOK, fetchedProduct)
return
}
if err != nil {
slog.Error("update product", "id", id, "err", err)
writeErrorJSON(w, http.StatusInternalServerError, "failed to update product")
return
}
writeJSON(w, http.StatusOK, p)
}
// Delete handles DELETE /products/{id}.
func (h *Handler) Delete(w http.ResponseWriter, r *http.Request) {
userID := middleware.UserIDFromCtx(r.Context())
id := chi.URLParam(r, "id")
if err := h.repo.Delete(r.Context(), id, userID); err != nil {
if errors.Is(err, ErrNotFound) {
writeErrorJSON(w, http.StatusNotFound, "product not found")
return
}
slog.Error("delete product", "id", id, "err", err)
writeErrorJSON(w, http.StatusInternalServerError, "failed to delete product")
return
}
w.WriteHeader(http.StatusNoContent)
writeJSON(responseWriter, http.StatusOK, savedProduct)
}
type errorResponse struct {
Error string `json:"error"`
}
func writeErrorJSON(w http.ResponseWriter, status int, msg string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(errorResponse{Error: msg})
func writeErrorJSON(responseWriter http.ResponseWriter, status int, msg string) {
responseWriter.Header().Set("Content-Type", "application/json")
responseWriter.WriteHeader(status)
_ = json.NewEncoder(responseWriter).Encode(errorResponse{Error: msg})
}
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(v)
func writeJSON(responseWriter http.ResponseWriter, status int, value any) {
responseWriter.Header().Set("Content-Type", "application/json")
responseWriter.WriteHeader(status)
_ = json.NewEncoder(responseWriter).Encode(value)
}

View File

@@ -1,36 +0,0 @@
package mocks
import (
"context"
"github.com/food-ai/backend/internal/domain/product"
)
// MockProductRepository is a test double implementing product.ProductRepository.
type MockProductRepository struct {
ListFn func(ctx context.Context, userID string) ([]*product.Product, error)
CreateFn func(ctx context.Context, userID string, req product.CreateRequest) (*product.Product, error)
BatchCreateFn func(ctx context.Context, userID string, items []product.CreateRequest) ([]*product.Product, error)
UpdateFn func(ctx context.Context, id, userID string, req product.UpdateRequest) (*product.Product, error)
DeleteFn func(ctx context.Context, id, userID string) error
}
func (m *MockProductRepository) List(ctx context.Context, userID string) ([]*product.Product, error) {
return m.ListFn(ctx, userID)
}
func (m *MockProductRepository) Create(ctx context.Context, userID string, req product.CreateRequest) (*product.Product, error) {
return m.CreateFn(ctx, userID, req)
}
func (m *MockProductRepository) BatchCreate(ctx context.Context, userID string, items []product.CreateRequest) ([]*product.Product, error) {
return m.BatchCreateFn(ctx, userID, items)
}
func (m *MockProductRepository) Update(ctx context.Context, id, userID string, req product.UpdateRequest) (*product.Product, error) {
return m.UpdateFn(ctx, id, userID, req)
}
func (m *MockProductRepository) Delete(ctx context.Context, id, userID string) error {
return m.DeleteFn(ctx, id, userID)
}

View File

@@ -0,0 +1,84 @@
package product
import (
"context"
"encoding/json"
"fmt"
"net/http"
)
// OpenFoodFacts is the client for the Open Food Facts public API.
type OpenFoodFacts struct {
httpClient *http.Client
}
// NewOpenFoodFacts creates a new OpenFoodFacts client with the default HTTP client.
func NewOpenFoodFacts() *OpenFoodFacts {
return &OpenFoodFacts{httpClient: &http.Client{}}
}
// offProduct is the JSON shape returned by the Open Food Facts v2 API.
type offProduct struct {
ProductName string `json:"product_name"`
Brands string `json:"brands"`
Nutriments offNutriments `json:"nutriments"`
}
type offNutriments struct {
EnergyKcal100g *float64 `json:"energy-kcal_100g"`
Proteins100g *float64 `json:"proteins_100g"`
Fat100g *float64 `json:"fat_100g"`
Carbohydrates100g *float64 `json:"carbohydrates_100g"`
Fiber100g *float64 `json:"fiber_100g"`
}
type offResponse struct {
Status int `json:"status"`
Product offProduct `json:"product"`
}
// Fetch retrieves a product from Open Food Facts by barcode.
// Returns an error if the product is not found or the API call fails.
func (client *OpenFoodFacts) Fetch(requestContext context.Context, barcode string) (*Product, error) {
url := fmt.Sprintf("https://world.openfoodfacts.org/api/v2/product/%s.json", barcode)
httpRequest, requestError := http.NewRequestWithContext(requestContext, http.MethodGet, url, nil)
if requestError != nil {
return nil, fmt.Errorf("build open food facts request: %w", requestError)
}
httpRequest.Header.Set("User-Agent", "FoodAI/1.0")
httpResponse, fetchError := client.httpClient.Do(httpRequest)
if fetchError != nil {
return nil, fmt.Errorf("open food facts request: %w", fetchError)
}
defer httpResponse.Body.Close()
if httpResponse.StatusCode != http.StatusOK {
return nil, fmt.Errorf("open food facts returned status %d for barcode %s", httpResponse.StatusCode, barcode)
}
var offResp offResponse
if decodeError := json.NewDecoder(httpResponse.Body).Decode(&offResp); decodeError != nil {
return nil, fmt.Errorf("decode open food facts response: %w", decodeError)
}
if offResp.Status == 0 {
return nil, fmt.Errorf("product %s not found in open food facts", barcode)
}
canonicalName := offResp.Product.ProductName
if canonicalName == "" {
canonicalName = barcode // Fall back to barcode as canonical name
}
barcodeValue := barcode
catalogProduct := &Product{
CanonicalName: canonicalName,
Barcode: &barcodeValue,
CaloriesPer100g: offResp.Product.Nutriments.EnergyKcal100g,
ProteinPer100g: offResp.Product.Nutriments.Proteins100g,
FatPer100g: offResp.Product.Nutriments.Fat100g,
CarbsPer100g: offResp.Product.Nutriments.Carbohydrates100g,
FiberPer100g: offResp.Product.Nutriments.Fiber100g,
}
return catalogProduct, nil
}

View File

@@ -2,18 +2,16 @@ package product
import (
"context"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/food-ai/backend/internal/infra/locale"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
// ErrNotFound is returned when a product is not found or does not belong to the user.
var ErrNotFound = errors.New("product not found")
// Repository handles product persistence.
// Repository handles persistence for catalog products and their translations.
type Repository struct {
pool *pgxpool.Pool
}
@@ -23,180 +21,314 @@ func NewRepository(pool *pgxpool.Pool) *Repository {
return &Repository{pool: pool}
}
// expires_at is computed in SQL because TIMESTAMPTZ + INTERVAL is STABLE (not IMMUTABLE),
// which prevents it from being used as a stored generated column.
const selectCols = `id, user_id, primary_ingredient_id, name, quantity, unit, category, storage_days, added_at,
(added_at + storage_days * INTERVAL '1 day') AS expires_at`
// 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`
// List returns all products for a user, sorted by expires_at ASC.
func (r *Repository) List(ctx context.Context, userID string) ([]*Product, error) {
rows, err := r.pool.Query(ctx, `
SELECT `+selectCols+`
FROM products
WHERE user_id = $1
ORDER BY expires_at ASC`, userID)
if err != nil {
return nil, fmt.Errorf("list products: %w", err)
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 collectProducts(rows)
return collectProductsRead(rows)
}
// Create inserts a new product and returns the created record.
func (r *Repository) Create(ctx context.Context, userID string, req CreateRequest) (*Product, error) {
storageDays := req.StorageDays
if storageDays <= 0 {
storageDays = 7
// 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)
}
unit := req.Unit
if unit == "" {
unit = "pcs"
}
qty := req.Quantity
if qty <= 0 {
qty = 1
}
// Accept both new and legacy field names.
primaryID := req.PrimaryIngredientID
if primaryID == nil {
primaryID = req.MappingID
}
row := r.pool.QueryRow(ctx, `
INSERT INTO products (user_id, primary_ingredient_id, name, quantity, unit, category, storage_days)
VALUES ($1, $2, $3, $4, $5, $6, $7)
RETURNING `+selectCols,
userID, primaryID, req.Name, qty, unit, req.Category, storageDays,
)
return scanProduct(row)
return count, nil
}
// BatchCreate inserts multiple products sequentially and returns all created records.
func (r *Repository) BatchCreate(ctx context.Context, userID string, items []CreateRequest) ([]*Product, error) {
var result []*Product
for _, req := range items {
p, err := r.Create(ctx, userID, req)
if err != nil {
return nil, fmt.Errorf("batch create product %q: %w", req.Name, err)
// 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)
}
result = append(result, p)
}
return result, nil
}
// Update modifies an existing product. Only non-nil fields are changed.
// Returns ErrNotFound if the product does not exist or belongs to a different user.
func (r *Repository) Update(ctx context.Context, id, userID string, req UpdateRequest) (*Product, error) {
row := r.pool.QueryRow(ctx, `
UPDATE products SET
name = COALESCE($3, name),
quantity = COALESCE($4, quantity),
unit = COALESCE($5, unit),
category = COALESCE($6, category),
storage_days = COALESCE($7, storage_days)
WHERE id = $1 AND user_id = $2
RETURNING `+selectCols,
id, userID, req.Name, req.Quantity, req.Unit, req.Category, req.StorageDays,
)
p, err := scanProduct(row)
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrNotFound
}
return p, err
}
// Delete removes a product. Returns ErrNotFound if it does not exist or belongs to a different user.
func (r *Repository) Delete(ctx context.Context, id, userID string) error {
tag, err := r.pool.Exec(ctx,
`DELETE FROM products WHERE id = $1 AND user_id = $2`, id, userID)
if err != nil {
return fmt.Errorf("delete product: %w", err)
}
if tag.RowsAffected() == 0 {
return ErrNotFound
}
return nil
}
// ListForPrompt returns a human-readable list of user's products for the AI prompt.
// Expiring soon items are marked with ⚠.
func (r *Repository) ListForPrompt(ctx context.Context, userID string) ([]string, error) {
rows, err := r.pool.Query(ctx, `
WITH p AS (
SELECT name, quantity, unit,
(added_at + storage_days * INTERVAL '1 day') AS expires_at
FROM products
WHERE user_id = $1
)
SELECT name, quantity, unit, expires_at
FROM p
ORDER BY expires_at ASC`, userID)
if err != nil {
return nil, fmt.Errorf("list products for prompt: %w", err)
}
defer rows.Close()
// 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`
var lines []string
now := time.Now()
for rows.Next() {
var name, unit string
var qty float64
var expiresAt time.Time
if err := rows.Scan(&name, &qty, &unit, &expiresAt); err != nil {
return nil, fmt.Errorf("scan product for prompt: %w", err)
}
daysLeft := int(expiresAt.Sub(now).Hours() / 24)
line := fmt.Sprintf("- %s %.0f %s", name, qty, unit)
switch {
case daysLeft <= 0:
line += " (expires today ⚠)"
case daysLeft == 1:
line += " (expires tomorrow ⚠)"
case daysLeft <= 3:
line += fmt.Sprintf(" (expires in %d days ⚠)", daysLeft)
}
lines = append(lines, line)
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 lines, rows.Err()
return nil
}
// --- helpers ---
// --- scan helpers ---
func scanProduct(row pgx.Row) (*Product, error) {
var p Product
err := row.Scan(
&p.ID, &p.UserID, &p.PrimaryIngredientID, &p.Name, &p.Quantity, &p.Unit,
&p.Category, &p.StorageDays, &p.AddedAt, &p.ExpiresAt,
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 err != nil {
return nil, err
if scanError != nil {
return nil, scanError
}
computeDaysLeft(&p)
return &p, nil
catalogProduct.Aliases = json.RawMessage("[]")
return &catalogProduct, nil
}
func collectProducts(rows pgx.Rows) ([]*Product, error) {
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 p Product
if err := rows.Scan(
&p.ID, &p.UserID, &p.PrimaryIngredientID, &p.Name, &p.Quantity, &p.Unit,
&p.Category, &p.StorageDays, &p.AddedAt, &p.ExpiresAt,
); err != nil {
return nil, fmt.Errorf("scan product: %w", err)
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)
}
computeDaysLeft(&p)
result = append(result, &p)
catalogProduct.Aliases = json.RawMessage("[]")
result = append(result, &catalogProduct)
}
return result, rows.Err()
}
func computeDaysLeft(p *Product) {
d := int(time.Until(p.ExpiresAt).Hours() / 24)
if d < 0 {
d = 0
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)
}
p.DaysLeft = d
p.ExpiringSoon = d <= 3
return result, rows.Err()
}

View File

@@ -12,7 +12,7 @@ import (
"github.com/food-ai/backend/internal/adapters/ai"
"github.com/food-ai/backend/internal/domain/dish"
"github.com/food-ai/backend/internal/domain/ingredient"
"github.com/food-ai/backend/internal/domain/product"
"github.com/food-ai/backend/internal/infra/locale"
"github.com/food-ai/backend/internal/infra/middleware"
)
@@ -26,12 +26,10 @@ type DishRepository interface {
AddRecipe(ctx context.Context, dishID string, req dish.CreateRequest) (string, error)
}
// IngredientRepository is the subset of ingredient.Repository used by this handler.
type IngredientRepository interface {
FuzzyMatch(ctx context.Context, name string) (*ingredient.IngredientMapping, error)
Upsert(ctx context.Context, m *ingredient.IngredientMapping) (*ingredient.IngredientMapping, error)
UpsertTranslation(ctx context.Context, id, lang, name string) error
UpsertAliases(ctx context.Context, id, lang string, aliases []string) error
// ProductRepository is the subset of product.Repository used by this handler.
type ProductRepository interface {
FuzzyMatch(ctx context.Context, name string) (*product.Product, error)
Upsert(ctx context.Context, catalogProduct *product.Product) (*product.Product, error)
}
// Recognizer is the AI provider interface for image-based food recognition.
@@ -51,27 +49,27 @@ type KafkaPublisher interface {
// Handler handles POST /ai/* recognition endpoints.
type Handler struct {
recognizer Recognizer
ingredientRepo IngredientRepository
jobRepo JobRepository
kafkaProducer KafkaPublisher
sseBroker *SSEBroker
recognizer Recognizer
productRepo ProductRepository
jobRepo JobRepository
kafkaProducer KafkaPublisher
sseBroker *SSEBroker
}
// NewHandler creates a new Handler with async dish recognition support.
func NewHandler(
recognizer Recognizer,
ingredientRepo IngredientRepository,
productRepo ProductRepository,
jobRepo JobRepository,
kafkaProducer KafkaPublisher,
sseBroker *SSEBroker,
) *Handler {
return &Handler{
recognizer: recognizer,
ingredientRepo: ingredientRepo,
jobRepo: jobRepo,
kafkaProducer: kafkaProducer,
sseBroker: sseBroker,
recognizer: recognizer,
productRepo: productRepo,
jobRepo: jobRepo,
kafkaProducer: kafkaProducer,
sseBroker: sseBroker,
}
}
@@ -293,7 +291,7 @@ func (handler *Handler) GetJob(responseWriter http.ResponseWriter, request *http
// Helpers
// ---------------------------------------------------------------------------
// enrichItems matches each recognized item against ingredient_mappings.
// enrichItems matches each recognized item against the product catalog.
// Items without a match trigger a classification call and upsert into the DB.
func (handler *Handler) enrichItems(ctx context.Context, items []ai.RecognizedItem) []EnrichedItem {
result := make([]EnrichedItem, 0, len(items))
@@ -307,27 +305,27 @@ func (handler *Handler) enrichItems(ctx context.Context, items []ai.RecognizedIt
StorageDays: 7, // sensible default
}
mapping, matchError := handler.ingredientRepo.FuzzyMatch(ctx, item.Name)
catalogProduct, matchError := handler.productRepo.FuzzyMatch(ctx, item.Name)
if matchError != nil {
slog.Warn("fuzzy match ingredient", "name", item.Name, "err", matchError)
slog.Warn("fuzzy match product", "name", item.Name, "err", matchError)
}
if mapping != nil {
id := mapping.ID
if catalogProduct != nil {
id := catalogProduct.ID
enriched.MappingID = &id
if mapping.DefaultUnit != nil {
enriched.Unit = *mapping.DefaultUnit
if catalogProduct.DefaultUnit != nil {
enriched.Unit = *catalogProduct.DefaultUnit
}
if mapping.StorageDays != nil {
enriched.StorageDays = *mapping.StorageDays
if catalogProduct.StorageDays != nil {
enriched.StorageDays = *catalogProduct.StorageDays
}
if mapping.Category != nil {
enriched.Category = *mapping.Category
if catalogProduct.Category != nil {
enriched.Category = *catalogProduct.Category
}
} else {
classification, classifyError := handler.recognizer.ClassifyIngredient(ctx, item.Name)
if classifyError != nil {
slog.Warn("classify unknown ingredient", "name", item.Name, "err", classifyError)
slog.Warn("classify unknown product", "name", item.Name, "err", classifyError)
} else {
saved := handler.saveClassification(ctx, classification)
if saved != nil {
@@ -344,13 +342,13 @@ func (handler *Handler) enrichItems(ctx context.Context, items []ai.RecognizedIt
return result
}
// saveClassification upserts an AI-produced ingredient classification into the DB.
func (handler *Handler) saveClassification(ctx context.Context, classification *ai.IngredientClassification) *ingredient.IngredientMapping {
// saveClassification upserts an AI-produced classification into the product catalog.
func (handler *Handler) saveClassification(ctx context.Context, classification *ai.IngredientClassification) *product.Product {
if classification == nil || classification.CanonicalName == "" {
return nil
}
mapping := &ingredient.IngredientMapping{
catalogProduct := &product.Product{
CanonicalName: classification.CanonicalName,
Category: strPtr(classification.Category),
DefaultUnit: strPtr(classification.DefaultUnit),
@@ -361,29 +359,12 @@ func (handler *Handler) saveClassification(ctx context.Context, classification *
StorageDays: intPtr(classification.StorageDays),
}
saved, upsertError := handler.ingredientRepo.Upsert(ctx, mapping)
saved, upsertError := handler.productRepo.Upsert(ctx, catalogProduct)
if upsertError != nil {
slog.Warn("upsert classified ingredient", "name", classification.CanonicalName, "err", upsertError)
slog.Warn("upsert classified product", "name", classification.CanonicalName, "err", upsertError)
return nil
}
if len(classification.Aliases) > 0 {
if aliasError := handler.ingredientRepo.UpsertAliases(ctx, saved.ID, "en", classification.Aliases); aliasError != nil {
slog.Warn("upsert ingredient aliases", "id", saved.ID, "err", aliasError)
}
}
for _, translation := range classification.Translations {
if translationError := handler.ingredientRepo.UpsertTranslation(ctx, saved.ID, translation.Lang, translation.Name); translationError != nil {
slog.Warn("upsert ingredient translation", "id", saved.ID, "lang", translation.Lang, "err", translationError)
}
if len(translation.Aliases) > 0 {
if aliasError := handler.ingredientRepo.UpsertAliases(ctx, saved.ID, translation.Lang, translation.Aliases); aliasError != nil {
slog.Warn("upsert ingredient translation aliases", "id", saved.ID, "lang", translation.Lang, "err", aliasError)
}
}
}
return saved
}

View File

@@ -0,0 +1,41 @@
package userproduct
import "time"
// UserProduct is a user's food item in their pantry.
type UserProduct struct {
ID string `json:"id"`
UserID string `json:"user_id"`
PrimaryProductID *string `json:"primary_product_id"`
Name string `json:"name"`
Quantity float64 `json:"quantity"`
Unit string `json:"unit"`
Category *string `json:"category"`
StorageDays int `json:"storage_days"`
AddedAt time.Time `json:"added_at"`
ExpiresAt time.Time `json:"expires_at"`
DaysLeft int `json:"days_left"`
ExpiringSoon bool `json:"expiring_soon"`
}
// CreateRequest is the body for POST /user-products.
type CreateRequest struct {
PrimaryProductID *string `json:"primary_product_id"`
// Accept "mapping_id" as a legacy alias for backward compatibility.
MappingID *string `json:"mapping_id"`
Name string `json:"name"`
Quantity float64 `json:"quantity"`
Unit string `json:"unit"`
Category *string `json:"category"`
StorageDays int `json:"storage_days"`
}
// UpdateRequest is the body for PUT /user-products/{id}.
// All fields are optional (nil = keep existing value).
type UpdateRequest struct {
Name *string `json:"name"`
Quantity *float64 `json:"quantity"`
Unit *string `json:"unit"`
Category *string `json:"category"`
StorageDays *int `json:"storage_days"`
}

View File

@@ -0,0 +1,147 @@
package userproduct
import (
"context"
"encoding/json"
"errors"
"log/slog"
"net/http"
"github.com/food-ai/backend/internal/infra/middleware"
"github.com/go-chi/chi/v5"
)
// UserProductRepository is the data layer interface used by Handler.
type UserProductRepository interface {
List(ctx context.Context, userID string) ([]*UserProduct, error)
Create(ctx context.Context, userID string, req CreateRequest) (*UserProduct, error)
BatchCreate(ctx context.Context, userID string, items []CreateRequest) ([]*UserProduct, error)
Update(ctx context.Context, id, userID string, req UpdateRequest) (*UserProduct, error)
Delete(ctx context.Context, id, userID string) error
}
// Handler handles /user-products HTTP requests.
type Handler struct {
repo UserProductRepository
}
// NewHandler creates a new Handler.
func NewHandler(repo UserProductRepository) *Handler {
return &Handler{repo: repo}
}
// List handles GET /user-products.
func (handler *Handler) List(responseWriter http.ResponseWriter, request *http.Request) {
userID := middleware.UserIDFromCtx(request.Context())
userProducts, listError := handler.repo.List(request.Context(), userID)
if listError != nil {
slog.Error("list user products", "user_id", userID, "err", listError)
writeErrorJSON(responseWriter, http.StatusInternalServerError, "failed to list user products")
return
}
if userProducts == nil {
userProducts = []*UserProduct{}
}
writeJSON(responseWriter, http.StatusOK, userProducts)
}
// Create handles POST /user-products.
func (handler *Handler) Create(responseWriter http.ResponseWriter, request *http.Request) {
userID := middleware.UserIDFromCtx(request.Context())
var req CreateRequest
if decodeError := json.NewDecoder(request.Body).Decode(&req); decodeError != nil {
writeErrorJSON(responseWriter, http.StatusBadRequest, "invalid request body")
return
}
if req.Name == "" {
writeErrorJSON(responseWriter, http.StatusBadRequest, "name is required")
return
}
userProduct, createError := handler.repo.Create(request.Context(), userID, req)
if createError != nil {
slog.Error("create user product", "user_id", userID, "err", createError)
writeErrorJSON(responseWriter, http.StatusInternalServerError, "failed to create user product")
return
}
writeJSON(responseWriter, http.StatusCreated, userProduct)
}
// BatchCreate handles POST /user-products/batch.
func (handler *Handler) BatchCreate(responseWriter http.ResponseWriter, request *http.Request) {
userID := middleware.UserIDFromCtx(request.Context())
var items []CreateRequest
if decodeError := json.NewDecoder(request.Body).Decode(&items); decodeError != nil {
writeErrorJSON(responseWriter, http.StatusBadRequest, "invalid request body")
return
}
if len(items) == 0 {
writeJSON(responseWriter, http.StatusCreated, []*UserProduct{})
return
}
userProducts, batchError := handler.repo.BatchCreate(request.Context(), userID, items)
if batchError != nil {
slog.Error("batch create user products", "user_id", userID, "err", batchError)
writeErrorJSON(responseWriter, http.StatusInternalServerError, "failed to create user products")
return
}
writeJSON(responseWriter, http.StatusCreated, userProducts)
}
// Update handles PUT /user-products/{id}.
func (handler *Handler) Update(responseWriter http.ResponseWriter, request *http.Request) {
userID := middleware.UserIDFromCtx(request.Context())
id := chi.URLParam(request, "id")
var req UpdateRequest
if decodeError := json.NewDecoder(request.Body).Decode(&req); decodeError != nil {
writeErrorJSON(responseWriter, http.StatusBadRequest, "invalid request body")
return
}
userProduct, updateError := handler.repo.Update(request.Context(), id, userID, req)
if errors.Is(updateError, ErrNotFound) {
writeErrorJSON(responseWriter, http.StatusNotFound, "user product not found")
return
}
if updateError != nil {
slog.Error("update user product", "id", id, "err", updateError)
writeErrorJSON(responseWriter, http.StatusInternalServerError, "failed to update user product")
return
}
writeJSON(responseWriter, http.StatusOK, userProduct)
}
// Delete handles DELETE /user-products/{id}.
func (handler *Handler) Delete(responseWriter http.ResponseWriter, request *http.Request) {
userID := middleware.UserIDFromCtx(request.Context())
id := chi.URLParam(request, "id")
if deleteError := handler.repo.Delete(request.Context(), id, userID); deleteError != nil {
if errors.Is(deleteError, ErrNotFound) {
writeErrorJSON(responseWriter, http.StatusNotFound, "user product not found")
return
}
slog.Error("delete user product", "id", id, "err", deleteError)
writeErrorJSON(responseWriter, http.StatusInternalServerError, "failed to delete user product")
return
}
responseWriter.WriteHeader(http.StatusNoContent)
}
type errorResponse struct {
Error string `json:"error"`
}
func writeErrorJSON(responseWriter http.ResponseWriter, status int, msg string) {
responseWriter.Header().Set("Content-Type", "application/json")
responseWriter.WriteHeader(status)
_ = json.NewEncoder(responseWriter).Encode(errorResponse{Error: msg})
}
func writeJSON(responseWriter http.ResponseWriter, status int, value any) {
responseWriter.Header().Set("Content-Type", "application/json")
responseWriter.WriteHeader(status)
_ = json.NewEncoder(responseWriter).Encode(value)
}

View File

@@ -0,0 +1,36 @@
package mocks
import (
"context"
"github.com/food-ai/backend/internal/domain/userproduct"
)
// MockUserProductRepository is a test double implementing userproduct.UserProductRepository.
type MockUserProductRepository struct {
ListFn func(ctx context.Context, userID string) ([]*userproduct.UserProduct, error)
CreateFn func(ctx context.Context, userID string, req userproduct.CreateRequest) (*userproduct.UserProduct, error)
BatchCreateFn func(ctx context.Context, userID string, items []userproduct.CreateRequest) ([]*userproduct.UserProduct, error)
UpdateFn func(ctx context.Context, id, userID string, req userproduct.UpdateRequest) (*userproduct.UserProduct, error)
DeleteFn func(ctx context.Context, id, userID string) error
}
func (m *MockUserProductRepository) List(ctx context.Context, userID string) ([]*userproduct.UserProduct, error) {
return m.ListFn(ctx, userID)
}
func (m *MockUserProductRepository) Create(ctx context.Context, userID string, req userproduct.CreateRequest) (*userproduct.UserProduct, error) {
return m.CreateFn(ctx, userID, req)
}
func (m *MockUserProductRepository) BatchCreate(ctx context.Context, userID string, items []userproduct.CreateRequest) ([]*userproduct.UserProduct, error) {
return m.BatchCreateFn(ctx, userID, items)
}
func (m *MockUserProductRepository) Update(ctx context.Context, id, userID string, req userproduct.UpdateRequest) (*userproduct.UserProduct, error) {
return m.UpdateFn(ctx, id, userID, req)
}
func (m *MockUserProductRepository) Delete(ctx context.Context, id, userID string) error {
return m.DeleteFn(ctx, id, userID)
}

View File

@@ -0,0 +1,202 @@
package userproduct
import (
"context"
"errors"
"fmt"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
// ErrNotFound is returned when a user product is not found or does not belong to the user.
var ErrNotFound = errors.New("user product not found")
// Repository handles user product persistence.
type Repository struct {
pool *pgxpool.Pool
}
// NewRepository creates a new Repository.
func NewRepository(pool *pgxpool.Pool) *Repository {
return &Repository{pool: pool}
}
// expires_at is computed in SQL because TIMESTAMPTZ + INTERVAL is STABLE (not IMMUTABLE),
// which prevents it from being used as a stored generated column.
const selectCols = `id, user_id, primary_product_id, name, quantity, unit, category, storage_days, added_at,
(added_at + storage_days * INTERVAL '1 day') AS expires_at`
// List returns all user products sorted by expires_at ASC.
func (r *Repository) List(requestContext context.Context, userID string) ([]*UserProduct, error) {
rows, queryError := r.pool.Query(requestContext, `
SELECT `+selectCols+`
FROM user_products
WHERE user_id = $1
ORDER BY expires_at ASC`, userID)
if queryError != nil {
return nil, fmt.Errorf("list user products: %w", queryError)
}
defer rows.Close()
return collectUserProducts(rows)
}
// Create inserts a new user product and returns the created record.
func (r *Repository) Create(requestContext context.Context, userID string, req CreateRequest) (*UserProduct, error) {
storageDays := req.StorageDays
if storageDays <= 0 {
storageDays = 7
}
unit := req.Unit
if unit == "" {
unit = "pcs"
}
qty := req.Quantity
if qty <= 0 {
qty = 1
}
// Accept both new and legacy field names.
primaryID := req.PrimaryProductID
if primaryID == nil {
primaryID = req.MappingID
}
row := r.pool.QueryRow(requestContext, `
INSERT INTO user_products (user_id, primary_product_id, name, quantity, unit, category, storage_days)
VALUES ($1, $2, $3, $4, $5, $6, $7)
RETURNING `+selectCols,
userID, primaryID, req.Name, qty, unit, req.Category, storageDays,
)
return scanUserProduct(row)
}
// BatchCreate inserts multiple user products sequentially and returns all created records.
func (r *Repository) BatchCreate(requestContext context.Context, userID string, items []CreateRequest) ([]*UserProduct, error) {
var result []*UserProduct
for _, req := range items {
userProduct, createError := r.Create(requestContext, userID, req)
if createError != nil {
return nil, fmt.Errorf("batch create user product %q: %w", req.Name, createError)
}
result = append(result, userProduct)
}
return result, nil
}
// Update modifies an existing user product. Only non-nil fields are changed.
// Returns ErrNotFound if the product does not exist or belongs to a different user.
func (r *Repository) Update(requestContext context.Context, id, userID string, req UpdateRequest) (*UserProduct, error) {
row := r.pool.QueryRow(requestContext, `
UPDATE user_products SET
name = COALESCE($3, name),
quantity = COALESCE($4, quantity),
unit = COALESCE($5, unit),
category = COALESCE($6, category),
storage_days = COALESCE($7, storage_days)
WHERE id = $1 AND user_id = $2
RETURNING `+selectCols,
id, userID, req.Name, req.Quantity, req.Unit, req.Category, req.StorageDays,
)
userProduct, scanError := scanUserProduct(row)
if errors.Is(scanError, pgx.ErrNoRows) {
return nil, ErrNotFound
}
return userProduct, scanError
}
// Delete removes a user product. Returns ErrNotFound if it does not exist or belongs to a different user.
func (r *Repository) Delete(requestContext context.Context, id, userID string) error {
tag, execError := r.pool.Exec(requestContext,
`DELETE FROM user_products WHERE id = $1 AND user_id = $2`, id, userID)
if execError != nil {
return fmt.Errorf("delete user product: %w", execError)
}
if tag.RowsAffected() == 0 {
return ErrNotFound
}
return nil
}
// ListForPrompt returns a human-readable list of user's products for the AI prompt.
// Expiring soon items are marked with ⚠.
func (r *Repository) ListForPrompt(requestContext context.Context, userID string) ([]string, error) {
rows, queryError := r.pool.Query(requestContext, `
WITH up AS (
SELECT name, quantity, unit,
(added_at + storage_days * INTERVAL '1 day') AS expires_at
FROM user_products
WHERE user_id = $1
)
SELECT name, quantity, unit, expires_at
FROM up
ORDER BY expires_at ASC`, userID)
if queryError != nil {
return nil, fmt.Errorf("list user products for prompt: %w", queryError)
}
defer rows.Close()
var lines []string
now := time.Now()
for rows.Next() {
var name, unit string
var qty float64
var expiresAt time.Time
if scanError := rows.Scan(&name, &qty, &unit, &expiresAt); scanError != nil {
return nil, fmt.Errorf("scan user product for prompt: %w", scanError)
}
daysLeft := int(expiresAt.Sub(now).Hours() / 24)
line := fmt.Sprintf("- %s %.0f %s", name, qty, unit)
switch {
case daysLeft <= 0:
line += " (expires today ⚠)"
case daysLeft == 1:
line += " (expires tomorrow ⚠)"
case daysLeft <= 3:
line += fmt.Sprintf(" (expires in %d days ⚠)", daysLeft)
}
lines = append(lines, line)
}
return lines, rows.Err()
}
// --- helpers ---
func scanUserProduct(row pgx.Row) (*UserProduct, error) {
var userProduct UserProduct
scanError := row.Scan(
&userProduct.ID, &userProduct.UserID, &userProduct.PrimaryProductID, &userProduct.Name, &userProduct.Quantity, &userProduct.Unit,
&userProduct.Category, &userProduct.StorageDays, &userProduct.AddedAt, &userProduct.ExpiresAt,
)
if scanError != nil {
return nil, scanError
}
computeDaysLeft(&userProduct)
return &userProduct, nil
}
func collectUserProducts(rows pgx.Rows) ([]*UserProduct, error) {
var result []*UserProduct
for rows.Next() {
var userProduct UserProduct
if scanError := rows.Scan(
&userProduct.ID, &userProduct.UserID, &userProduct.PrimaryProductID, &userProduct.Name, &userProduct.Quantity, &userProduct.Unit,
&userProduct.Category, &userProduct.StorageDays, &userProduct.AddedAt, &userProduct.ExpiresAt,
); scanError != nil {
return nil, fmt.Errorf("scan user product: %w", scanError)
}
computeDaysLeft(&userProduct)
result = append(result, &userProduct)
}
return result, rows.Err()
}
func computeDaysLeft(userProduct *UserProduct) {
days := int(time.Until(userProduct.ExpiresAt).Hours() / 24)
if days < 0 {
days = 0
}
userProduct.DaysLeft = days
userProduct.ExpiringSoon = days <= 3
}