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:
@@ -140,7 +140,7 @@ func TestCreate_Success(t *testing.T) {
|
||||
Name: "Oatmeal",
|
||||
Portions: 1,
|
||||
Source: "manual",
|
||||
DishID: "dish-1",
|
||||
DishID: strPtr("dish-1"),
|
||||
CreatedAt: time.Now(),
|
||||
}, nil
|
||||
},
|
||||
@@ -207,3 +207,5 @@ func TestDelete_Success(t *testing.T) {
|
||||
t.Errorf("expected 204, got %d", recorder.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func strPtr(s string) *string { return &s }
|
||||
|
||||
@@ -1,25 +1,44 @@
|
||||
package ingredient_test
|
||||
package product_catalog_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/food-ai/backend/internal/domain/ingredient"
|
||||
"github.com/food-ai/backend/internal/domain/product"
|
||||
"github.com/food-ai/backend/internal/infra/middleware"
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
// mockIngredientSearcher is an inline mock for ingredient.IngredientSearcher.
|
||||
type mockIngredientSearcher struct {
|
||||
searchFn func(ctx context.Context, query string, limit int) ([]*ingredient.IngredientMapping, error)
|
||||
// mockProductSearcher is an inline mock for product.ProductSearcher (catalog search only).
|
||||
type mockProductSearcher struct {
|
||||
searchFn func(ctx context.Context, query string, limit int) ([]*product.Product, error)
|
||||
}
|
||||
|
||||
func (m *mockIngredientSearcher) Search(ctx context.Context, query string, limit int) ([]*ingredient.IngredientMapping, error) {
|
||||
return m.searchFn(ctx, query, limit)
|
||||
func (m *mockProductSearcher) Search(ctx context.Context, query string, limit int) ([]*product.Product, error) {
|
||||
if m.searchFn != nil {
|
||||
return m.searchFn(ctx, query, limit)
|
||||
}
|
||||
return []*product.Product{}, nil
|
||||
}
|
||||
|
||||
func (m *mockProductSearcher) GetByBarcode(_ context.Context, _ string) (*product.Product, error) {
|
||||
return nil, errors.New("not implemented")
|
||||
}
|
||||
|
||||
func (m *mockProductSearcher) UpsertByBarcode(_ context.Context, catalogProduct *product.Product) (*product.Product, error) {
|
||||
return catalogProduct, nil
|
||||
}
|
||||
|
||||
// mockOpenFoodFacts is an inline mock for product.OpenFoodFactsClient (unused in search tests).
|
||||
type mockOpenFoodFacts struct{}
|
||||
|
||||
func (m *mockOpenFoodFacts) Fetch(_ context.Context, _ string) (*product.Product, error) {
|
||||
return nil, errors.New("not implemented")
|
||||
}
|
||||
|
||||
type alwaysAuthValidator struct{ userID string }
|
||||
@@ -28,10 +47,10 @@ func (v *alwaysAuthValidator) ValidateAccessToken(_ string) (*middleware.TokenCl
|
||||
return &middleware.TokenClaims{UserID: v.userID}, nil
|
||||
}
|
||||
|
||||
func buildRouter(handler *ingredient.Handler) *chi.Mux {
|
||||
func buildRouter(handler *product.Handler) *chi.Mux {
|
||||
router := chi.NewRouter()
|
||||
router.Use(middleware.Auth(&alwaysAuthValidator{userID: "user-1"}))
|
||||
router.Get("/ingredients/search", handler.Search)
|
||||
router.Get("/products/search", handler.Search)
|
||||
return router
|
||||
}
|
||||
|
||||
@@ -43,11 +62,11 @@ func authorizedRequest(target string) *http.Request {
|
||||
|
||||
func TestSearch_EmptyQuery_ReturnsEmptyArray(t *testing.T) {
|
||||
// When q is empty, the handler returns [] without calling the repository.
|
||||
handler := ingredient.NewHandler(&mockIngredientSearcher{})
|
||||
handler := product.NewHandler(&mockProductSearcher{}, &mockOpenFoodFacts{})
|
||||
router := buildRouter(handler)
|
||||
|
||||
recorder := httptest.NewRecorder()
|
||||
router.ServeHTTP(recorder, authorizedRequest("/ingredients/search"))
|
||||
router.ServeHTTP(recorder, authorizedRequest("/products/search"))
|
||||
|
||||
if recorder.Code != http.StatusOK {
|
||||
t.Errorf("expected 200, got %d", recorder.Code)
|
||||
@@ -60,17 +79,17 @@ func TestSearch_EmptyQuery_ReturnsEmptyArray(t *testing.T) {
|
||||
func TestSearch_LimitTooLarge_UsesDefault(t *testing.T) {
|
||||
// When limit > 50, the handler ignores it and uses default 10.
|
||||
calledLimit := 0
|
||||
mockRepo := &mockIngredientSearcher{
|
||||
searchFn: func(ctx context.Context, query string, limit int) ([]*ingredient.IngredientMapping, error) {
|
||||
mockRepo := &mockProductSearcher{
|
||||
searchFn: func(ctx context.Context, query string, limit int) ([]*product.Product, error) {
|
||||
calledLimit = limit
|
||||
return []*ingredient.IngredientMapping{}, nil
|
||||
return []*product.Product{}, nil
|
||||
},
|
||||
}
|
||||
handler := ingredient.NewHandler(mockRepo)
|
||||
handler := product.NewHandler(mockRepo, &mockOpenFoodFacts{})
|
||||
router := buildRouter(handler)
|
||||
|
||||
recorder := httptest.NewRecorder()
|
||||
router.ServeHTTP(recorder, authorizedRequest("/ingredients/search?q=apple&limit=100"))
|
||||
router.ServeHTTP(recorder, authorizedRequest("/products/search?q=apple&limit=100"))
|
||||
|
||||
if recorder.Code != http.StatusOK {
|
||||
t.Errorf("expected 200, got %d", recorder.Code)
|
||||
@@ -83,17 +102,17 @@ func TestSearch_LimitTooLarge_UsesDefault(t *testing.T) {
|
||||
func TestSearch_DefaultLimit(t *testing.T) {
|
||||
// When no limit is supplied, the handler uses default 10.
|
||||
calledLimit := 0
|
||||
mockRepo := &mockIngredientSearcher{
|
||||
searchFn: func(ctx context.Context, query string, limit int) ([]*ingredient.IngredientMapping, error) {
|
||||
mockRepo := &mockProductSearcher{
|
||||
searchFn: func(ctx context.Context, query string, limit int) ([]*product.Product, error) {
|
||||
calledLimit = limit
|
||||
return []*ingredient.IngredientMapping{}, nil
|
||||
return []*product.Product{}, nil
|
||||
},
|
||||
}
|
||||
handler := ingredient.NewHandler(mockRepo)
|
||||
handler := product.NewHandler(mockRepo, &mockOpenFoodFacts{})
|
||||
router := buildRouter(handler)
|
||||
|
||||
recorder := httptest.NewRecorder()
|
||||
router.ServeHTTP(recorder, authorizedRequest("/ingredients/search?q=apple"))
|
||||
router.ServeHTTP(recorder, authorizedRequest("/products/search?q=apple"))
|
||||
|
||||
if recorder.Code != http.StatusOK {
|
||||
t.Errorf("expected 200, got %d", recorder.Code)
|
||||
@@ -106,17 +125,17 @@ func TestSearch_DefaultLimit(t *testing.T) {
|
||||
func TestSearch_ValidLimit(t *testing.T) {
|
||||
// limit=25 is within range and should be forwarded as-is.
|
||||
calledLimit := 0
|
||||
mockRepo := &mockIngredientSearcher{
|
||||
searchFn: func(ctx context.Context, query string, limit int) ([]*ingredient.IngredientMapping, error) {
|
||||
mockRepo := &mockProductSearcher{
|
||||
searchFn: func(ctx context.Context, query string, limit int) ([]*product.Product, error) {
|
||||
calledLimit = limit
|
||||
return []*ingredient.IngredientMapping{}, nil
|
||||
return []*product.Product{}, nil
|
||||
},
|
||||
}
|
||||
handler := ingredient.NewHandler(mockRepo)
|
||||
handler := product.NewHandler(mockRepo, &mockOpenFoodFacts{})
|
||||
router := buildRouter(handler)
|
||||
|
||||
recorder := httptest.NewRecorder()
|
||||
router.ServeHTTP(recorder, authorizedRequest("/ingredients/search?q=apple&limit=25"))
|
||||
router.ServeHTTP(recorder, authorizedRequest("/products/search?q=apple&limit=25"))
|
||||
|
||||
if recorder.Code != http.StatusOK {
|
||||
t.Errorf("expected 200, got %d", recorder.Code)
|
||||
@@ -127,31 +146,31 @@ func TestSearch_ValidLimit(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestSearch_Success(t *testing.T) {
|
||||
mockRepo := &mockIngredientSearcher{
|
||||
searchFn: func(ctx context.Context, query string, limit int) ([]*ingredient.IngredientMapping, error) {
|
||||
return []*ingredient.IngredientMapping{
|
||||
{ID: "ing-1", CanonicalName: "apple"},
|
||||
mockRepo := &mockProductSearcher{
|
||||
searchFn: func(ctx context.Context, query string, limit int) ([]*product.Product, error) {
|
||||
return []*product.Product{
|
||||
{ID: "prod-1", CanonicalName: "apple"},
|
||||
}, nil
|
||||
},
|
||||
}
|
||||
handler := ingredient.NewHandler(mockRepo)
|
||||
handler := product.NewHandler(mockRepo, &mockOpenFoodFacts{})
|
||||
router := buildRouter(handler)
|
||||
|
||||
recorder := httptest.NewRecorder()
|
||||
router.ServeHTTP(recorder, authorizedRequest("/ingredients/search?q=apple"))
|
||||
router.ServeHTTP(recorder, authorizedRequest("/products/search?q=apple"))
|
||||
|
||||
if recorder.Code != http.StatusOK {
|
||||
t.Errorf("expected 200, got %d", recorder.Code)
|
||||
}
|
||||
|
||||
var mappings []ingredient.IngredientMapping
|
||||
if decodeError := json.NewDecoder(recorder.Body).Decode(&mappings); decodeError != nil {
|
||||
var products []product.Product
|
||||
if decodeError := json.NewDecoder(recorder.Body).Decode(&products); decodeError != nil {
|
||||
t.Fatalf("decode response: %v", decodeError)
|
||||
}
|
||||
if len(mappings) != 1 {
|
||||
t.Errorf("expected 1 result, got %d", len(mappings))
|
||||
if len(products) != 1 {
|
||||
t.Errorf("expected 1 result, got %d", len(products))
|
||||
}
|
||||
if mappings[0].CanonicalName != "apple" {
|
||||
t.Errorf("expected canonical_name=apple, got %q", mappings[0].CanonicalName)
|
||||
if products[0].CanonicalName != "apple" {
|
||||
t.Errorf("expected canonical_name=apple, got %q", products[0].CanonicalName)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,33 +1,33 @@
|
||||
//go:build integration
|
||||
|
||||
package ingredient_test
|
||||
package product_catalog_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"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/testutil"
|
||||
)
|
||||
|
||||
func TestIngredientRepository_Upsert_Insert(t *testing.T) {
|
||||
func TestProductRepository_Upsert_Insert(t *testing.T) {
|
||||
pool := testutil.SetupTestDB(t)
|
||||
repo := ingredient.NewRepository(pool)
|
||||
repo := product.NewRepository(pool)
|
||||
ctx := context.Background()
|
||||
|
||||
cat := "produce"
|
||||
unit := "g"
|
||||
cal := 52.0
|
||||
|
||||
mapping := &ingredient.IngredientMapping{
|
||||
catalogProduct := &product.Product{
|
||||
CanonicalName: "apple",
|
||||
Category: &cat,
|
||||
DefaultUnit: &unit,
|
||||
CaloriesPer100g: &cal,
|
||||
}
|
||||
|
||||
got, upsertError := repo.Upsert(ctx, mapping)
|
||||
got, upsertError := repo.Upsert(ctx, catalogProduct)
|
||||
if upsertError != nil {
|
||||
t.Fatalf("upsert: %v", upsertError)
|
||||
}
|
||||
@@ -42,15 +42,15 @@ func TestIngredientRepository_Upsert_Insert(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestIngredientRepository_Upsert_ConflictUpdates(t *testing.T) {
|
||||
func TestProductRepository_Upsert_ConflictUpdates(t *testing.T) {
|
||||
pool := testutil.SetupTestDB(t)
|
||||
repo := ingredient.NewRepository(pool)
|
||||
repo := product.NewRepository(pool)
|
||||
ctx := context.Background()
|
||||
|
||||
cat := "produce"
|
||||
unit := "g"
|
||||
|
||||
first := &ingredient.IngredientMapping{
|
||||
first := &product.Product{
|
||||
CanonicalName: "banana",
|
||||
Category: &cat,
|
||||
DefaultUnit: &unit,
|
||||
@@ -61,7 +61,7 @@ func TestIngredientRepository_Upsert_ConflictUpdates(t *testing.T) {
|
||||
}
|
||||
|
||||
cal := 89.0
|
||||
second := &ingredient.IngredientMapping{
|
||||
second := &product.Product{
|
||||
CanonicalName: "banana",
|
||||
Category: &cat,
|
||||
DefaultUnit: &unit,
|
||||
@@ -83,15 +83,15 @@ func TestIngredientRepository_Upsert_ConflictUpdates(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestIngredientRepository_GetByID_Found(t *testing.T) {
|
||||
func TestProductRepository_GetByID_Found(t *testing.T) {
|
||||
pool := testutil.SetupTestDB(t)
|
||||
repo := ingredient.NewRepository(pool)
|
||||
repo := product.NewRepository(pool)
|
||||
ctx := context.Background()
|
||||
|
||||
cat := "dairy"
|
||||
unit := "g"
|
||||
|
||||
saved, upsertError := repo.Upsert(ctx, &ingredient.IngredientMapping{
|
||||
saved, upsertError := repo.Upsert(ctx, &product.Product{
|
||||
CanonicalName: "cheese",
|
||||
Category: &cat,
|
||||
DefaultUnit: &unit,
|
||||
@@ -112,9 +112,9 @@ func TestIngredientRepository_GetByID_Found(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestIngredientRepository_GetByID_NotFound(t *testing.T) {
|
||||
func TestProductRepository_GetByID_NotFound(t *testing.T) {
|
||||
pool := testutil.SetupTestDB(t)
|
||||
repo := ingredient.NewRepository(pool)
|
||||
repo := product.NewRepository(pool)
|
||||
ctx := context.Background()
|
||||
|
||||
got, getError := repo.GetByID(ctx, "00000000-0000-0000-0000-000000000000")
|
||||
@@ -126,105 +126,17 @@ func TestIngredientRepository_GetByID_NotFound(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestIngredientRepository_ListMissingTranslation(t *testing.T) {
|
||||
|
||||
|
||||
func TestProductRepository_UpsertAliases(t *testing.T) {
|
||||
pool := testutil.SetupTestDB(t)
|
||||
repo := ingredient.NewRepository(pool)
|
||||
repo := product.NewRepository(pool)
|
||||
ctx := context.Background()
|
||||
|
||||
cat := "produce"
|
||||
unit := "g"
|
||||
|
||||
// Insert 3 without any translation.
|
||||
for _, name := range []string{"carrot", "onion", "garlic"} {
|
||||
_, upsertError := repo.Upsert(ctx, &ingredient.IngredientMapping{
|
||||
CanonicalName: name,
|
||||
Category: &cat,
|
||||
DefaultUnit: &unit,
|
||||
})
|
||||
if upsertError != nil {
|
||||
t.Fatalf("upsert %s: %v", name, upsertError)
|
||||
}
|
||||
}
|
||||
|
||||
// Insert 1 and add a translation — should not appear in the result.
|
||||
saved, upsertError := repo.Upsert(ctx, &ingredient.IngredientMapping{
|
||||
CanonicalName: "tomato",
|
||||
Category: &cat,
|
||||
DefaultUnit: &unit,
|
||||
})
|
||||
if upsertError != nil {
|
||||
t.Fatalf("upsert tomato: %v", upsertError)
|
||||
}
|
||||
if translationError := repo.UpsertTranslation(ctx, saved.ID, "ru", "помидор"); translationError != nil {
|
||||
t.Fatalf("upsert translation: %v", translationError)
|
||||
}
|
||||
|
||||
missing, listError := repo.ListMissingTranslation(ctx, "ru", 10, 0)
|
||||
if listError != nil {
|
||||
t.Fatalf("list missing translation: %v", listError)
|
||||
}
|
||||
|
||||
for _, mapping := range missing {
|
||||
if mapping.CanonicalName == "tomato" {
|
||||
t.Error("translated ingredient should not appear in ListMissingTranslation")
|
||||
}
|
||||
}
|
||||
if len(missing) < 3 {
|
||||
t.Errorf("expected at least 3 untranslated, got %d", len(missing))
|
||||
}
|
||||
}
|
||||
|
||||
func TestIngredientRepository_UpsertTranslation(t *testing.T) {
|
||||
pool := testutil.SetupTestDB(t)
|
||||
repo := ingredient.NewRepository(pool)
|
||||
ctx := context.Background()
|
||||
|
||||
cat := "meat"
|
||||
unit := "g"
|
||||
|
||||
saved, upsertError := repo.Upsert(ctx, &ingredient.IngredientMapping{
|
||||
CanonicalName: "chicken_breast",
|
||||
Category: &cat,
|
||||
DefaultUnit: &unit,
|
||||
})
|
||||
if upsertError != nil {
|
||||
t.Fatalf("upsert: %v", upsertError)
|
||||
}
|
||||
|
||||
if translationError := repo.UpsertTranslation(ctx, saved.ID, "ru", "куриная грудка"); translationError != nil {
|
||||
t.Fatalf("upsert translation: %v", translationError)
|
||||
}
|
||||
|
||||
// Retrieve with Russian context — CanonicalName should be the Russian name.
|
||||
russianContext := locale.WithLang(ctx, "ru")
|
||||
got, getError := repo.GetByID(russianContext, saved.ID)
|
||||
if getError != nil {
|
||||
t.Fatalf("get by id: %v", getError)
|
||||
}
|
||||
if got.CanonicalName != "куриная грудка" {
|
||||
t.Errorf("expected CanonicalName='куриная грудка', got %q", got.CanonicalName)
|
||||
}
|
||||
|
||||
// Retrieve with English context (default) — CanonicalName should be the English name.
|
||||
englishContext := locale.WithLang(ctx, "en")
|
||||
gotEnglish, getEnglishError := repo.GetByID(englishContext, saved.ID)
|
||||
if getEnglishError != nil {
|
||||
t.Fatalf("get by id (en): %v", getEnglishError)
|
||||
}
|
||||
if gotEnglish.CanonicalName != "chicken_breast" {
|
||||
t.Errorf("expected English CanonicalName='chicken_breast', got %q", gotEnglish.CanonicalName)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIngredientRepository_UpsertAliases(t *testing.T) {
|
||||
pool := testutil.SetupTestDB(t)
|
||||
repo := ingredient.NewRepository(pool)
|
||||
ctx := context.Background()
|
||||
|
||||
cat := "produce"
|
||||
unit := "g"
|
||||
|
||||
saved, upsertError := repo.Upsert(ctx, &ingredient.IngredientMapping{
|
||||
saved, upsertError := repo.Upsert(ctx, &product.Product{
|
||||
CanonicalName: "apple_test_aliases",
|
||||
Category: &cat,
|
||||
DefaultUnit: &unit,
|
||||
@@ -238,12 +150,10 @@ func TestIngredientRepository_UpsertAliases(t *testing.T) {
|
||||
t.Fatalf("upsert aliases: %v", aliasError)
|
||||
}
|
||||
|
||||
// Idempotent — second call should not fail.
|
||||
if aliasError := repo.UpsertAliases(ctx, saved.ID, "en", aliases); aliasError != nil {
|
||||
t.Fatalf("second upsert aliases: %v", aliasError)
|
||||
}
|
||||
|
||||
// Retrieve with English context — aliases should appear.
|
||||
englishContext := locale.WithLang(ctx, "en")
|
||||
got, getError := repo.GetByID(englishContext, saved.ID)
|
||||
if getError != nil {
|
||||
@@ -254,15 +164,14 @@ func TestIngredientRepository_UpsertAliases(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestIngredientRepository_UpsertCategoryTranslation(t *testing.T) {
|
||||
func TestProductRepository_UpsertCategoryTranslation(t *testing.T) {
|
||||
pool := testutil.SetupTestDB(t)
|
||||
repo := ingredient.NewRepository(pool)
|
||||
repo := product.NewRepository(pool)
|
||||
ctx := context.Background()
|
||||
|
||||
// Upsert an ingredient with a known category.
|
||||
cat := "dairy"
|
||||
unit := "g"
|
||||
saved, upsertError := repo.Upsert(ctx, &ingredient.IngredientMapping{
|
||||
saved, upsertError := repo.Upsert(ctx, &product.Product{
|
||||
CanonicalName: "milk_test_category",
|
||||
Category: &cat,
|
||||
DefaultUnit: &unit,
|
||||
@@ -271,8 +180,6 @@ func TestIngredientRepository_UpsertCategoryTranslation(t *testing.T) {
|
||||
t.Fatalf("upsert: %v", upsertError)
|
||||
}
|
||||
|
||||
// The migration already inserted Russian translations for known categories.
|
||||
// Retrieve with Russian context — CategoryName should be set.
|
||||
russianContext := locale.WithLang(ctx, "ru")
|
||||
got, getError := repo.GetByID(russianContext, saved.ID)
|
||||
if getError != nil {
|
||||
@@ -282,7 +189,6 @@ func TestIngredientRepository_UpsertCategoryTranslation(t *testing.T) {
|
||||
t.Error("expected non-empty CategoryName for 'dairy' in Russian")
|
||||
}
|
||||
|
||||
// Upsert a new translation and verify it is returned.
|
||||
if translationError := repo.UpsertCategoryTranslation(ctx, "dairy", "de", "Milchprodukte"); translationError != nil {
|
||||
t.Fatalf("upsert category translation: %v", translationError)
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package product_test
|
||||
package userproduct_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
@@ -9,8 +9,8 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/food-ai/backend/internal/domain/product"
|
||||
productmocks "github.com/food-ai/backend/internal/domain/product/mocks"
|
||||
"github.com/food-ai/backend/internal/domain/userproduct"
|
||||
userproductmocks "github.com/food-ai/backend/internal/domain/userproduct/mocks"
|
||||
"github.com/food-ai/backend/internal/infra/middleware"
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
@@ -21,14 +21,14 @@ func (v *alwaysAuthValidator) ValidateAccessToken(_ string) (*middleware.TokenCl
|
||||
return &middleware.TokenClaims{UserID: v.userID}, nil
|
||||
}
|
||||
|
||||
func buildRouter(handler *product.Handler, userID string) *chi.Mux {
|
||||
func buildRouter(handler *userproduct.Handler, userID string) *chi.Mux {
|
||||
router := chi.NewRouter()
|
||||
router.Use(middleware.Auth(&alwaysAuthValidator{userID: userID}))
|
||||
router.Get("/products", handler.List)
|
||||
router.Post("/products", handler.Create)
|
||||
router.Post("/products/batch", handler.BatchCreate)
|
||||
router.Put("/products/{id}", handler.Update)
|
||||
router.Delete("/products/{id}", handler.Delete)
|
||||
router.Get("/user-products", handler.List)
|
||||
router.Post("/user-products", handler.Create)
|
||||
router.Post("/user-products/batch", handler.BatchCreate)
|
||||
router.Put("/user-products/{id}", handler.Update)
|
||||
router.Delete("/user-products/{id}", handler.Delete)
|
||||
return router
|
||||
}
|
||||
|
||||
@@ -39,8 +39,8 @@ func authorizedRequest(method, target string, body []byte) *http.Request {
|
||||
return request
|
||||
}
|
||||
|
||||
func makeProduct(name string) *product.Product {
|
||||
return &product.Product{
|
||||
func makeUserProduct(name string) *userproduct.UserProduct {
|
||||
return &userproduct.UserProduct{
|
||||
ID: "prod-1",
|
||||
UserID: "user-1",
|
||||
Name: name,
|
||||
@@ -54,16 +54,16 @@ func makeProduct(name string) *product.Product {
|
||||
}
|
||||
|
||||
func TestList_Success(t *testing.T) {
|
||||
mockRepo := &productmocks.MockProductRepository{
|
||||
ListFn: func(ctx context.Context, userID string) ([]*product.Product, error) {
|
||||
return []*product.Product{makeProduct("Milk")}, nil
|
||||
mockRepo := &userproductmocks.MockUserProductRepository{
|
||||
ListFn: func(ctx context.Context, userID string) ([]*userproduct.UserProduct, error) {
|
||||
return []*userproduct.UserProduct{makeUserProduct("Milk")}, nil
|
||||
},
|
||||
}
|
||||
handler := product.NewHandler(mockRepo)
|
||||
handler := userproduct.NewHandler(mockRepo)
|
||||
router := buildRouter(handler, "user-1")
|
||||
|
||||
recorder := httptest.NewRecorder()
|
||||
router.ServeHTTP(recorder, authorizedRequest(http.MethodGet, "/products", nil))
|
||||
router.ServeHTTP(recorder, authorizedRequest(http.MethodGet, "/user-products", nil))
|
||||
|
||||
if recorder.Code != http.StatusOK {
|
||||
t.Errorf("expected 200, got %d", recorder.Code)
|
||||
@@ -71,12 +71,12 @@ func TestList_Success(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestCreate_MissingName(t *testing.T) {
|
||||
handler := product.NewHandler(&productmocks.MockProductRepository{})
|
||||
handler := userproduct.NewHandler(&userproductmocks.MockUserProductRepository{})
|
||||
router := buildRouter(handler, "user-1")
|
||||
|
||||
body, _ := json.Marshal(map[string]any{"quantity": 1})
|
||||
recorder := httptest.NewRecorder()
|
||||
router.ServeHTTP(recorder, authorizedRequest(http.MethodPost, "/products", body))
|
||||
router.ServeHTTP(recorder, authorizedRequest(http.MethodPost, "/user-products", body))
|
||||
|
||||
if recorder.Code != http.StatusBadRequest {
|
||||
t.Errorf("expected 400, got %d", recorder.Code)
|
||||
@@ -84,17 +84,17 @@ func TestCreate_MissingName(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestCreate_Success(t *testing.T) {
|
||||
mockRepo := &productmocks.MockProductRepository{
|
||||
CreateFn: func(ctx context.Context, userID string, req product.CreateRequest) (*product.Product, error) {
|
||||
return makeProduct(req.Name), nil
|
||||
mockRepo := &userproductmocks.MockUserProductRepository{
|
||||
CreateFn: func(ctx context.Context, userID string, req userproduct.CreateRequest) (*userproduct.UserProduct, error) {
|
||||
return makeUserProduct(req.Name), nil
|
||||
},
|
||||
}
|
||||
handler := product.NewHandler(mockRepo)
|
||||
handler := userproduct.NewHandler(mockRepo)
|
||||
router := buildRouter(handler, "user-1")
|
||||
|
||||
body, _ := json.Marshal(product.CreateRequest{Name: "Milk", Quantity: 1, Unit: "L"})
|
||||
body, _ := json.Marshal(userproduct.CreateRequest{Name: "Milk", Quantity: 1, Unit: "L"})
|
||||
recorder := httptest.NewRecorder()
|
||||
router.ServeHTTP(recorder, authorizedRequest(http.MethodPost, "/products", body))
|
||||
router.ServeHTTP(recorder, authorizedRequest(http.MethodPost, "/user-products", body))
|
||||
|
||||
if recorder.Code != http.StatusCreated {
|
||||
t.Errorf("expected 201, got %d", recorder.Code)
|
||||
@@ -102,24 +102,24 @@ func TestCreate_Success(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestBatchCreate_Success(t *testing.T) {
|
||||
mockRepo := &productmocks.MockProductRepository{
|
||||
BatchCreateFn: func(ctx context.Context, userID string, items []product.CreateRequest) ([]*product.Product, error) {
|
||||
result := make([]*product.Product, len(items))
|
||||
mockRepo := &userproductmocks.MockUserProductRepository{
|
||||
BatchCreateFn: func(ctx context.Context, userID string, items []userproduct.CreateRequest) ([]*userproduct.UserProduct, error) {
|
||||
result := make([]*userproduct.UserProduct, len(items))
|
||||
for index, item := range items {
|
||||
result[index] = makeProduct(item.Name)
|
||||
result[index] = makeUserProduct(item.Name)
|
||||
}
|
||||
return result, nil
|
||||
},
|
||||
}
|
||||
handler := product.NewHandler(mockRepo)
|
||||
handler := userproduct.NewHandler(mockRepo)
|
||||
router := buildRouter(handler, "user-1")
|
||||
|
||||
body, _ := json.Marshal([]product.CreateRequest{
|
||||
body, _ := json.Marshal([]userproduct.CreateRequest{
|
||||
{Name: "Milk", Quantity: 1, Unit: "L"},
|
||||
{Name: "Eggs", Quantity: 12, Unit: "pcs"},
|
||||
})
|
||||
recorder := httptest.NewRecorder()
|
||||
router.ServeHTTP(recorder, authorizedRequest(http.MethodPost, "/products/batch", body))
|
||||
router.ServeHTTP(recorder, authorizedRequest(http.MethodPost, "/user-products/batch", body))
|
||||
|
||||
if recorder.Code != http.StatusCreated {
|
||||
t.Errorf("expected 201, got %d", recorder.Code)
|
||||
@@ -127,18 +127,18 @@ func TestBatchCreate_Success(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestUpdate_NotFound(t *testing.T) {
|
||||
mockRepo := &productmocks.MockProductRepository{
|
||||
UpdateFn: func(ctx context.Context, id, userID string, req product.UpdateRequest) (*product.Product, error) {
|
||||
return nil, product.ErrNotFound
|
||||
mockRepo := &userproductmocks.MockUserProductRepository{
|
||||
UpdateFn: func(ctx context.Context, id, userID string, req userproduct.UpdateRequest) (*userproduct.UserProduct, error) {
|
||||
return nil, userproduct.ErrNotFound
|
||||
},
|
||||
}
|
||||
handler := product.NewHandler(mockRepo)
|
||||
handler := userproduct.NewHandler(mockRepo)
|
||||
router := buildRouter(handler, "user-1")
|
||||
|
||||
namePtr := "NewName"
|
||||
body, _ := json.Marshal(product.UpdateRequest{Name: &namePtr})
|
||||
body, _ := json.Marshal(userproduct.UpdateRequest{Name: &namePtr})
|
||||
recorder := httptest.NewRecorder()
|
||||
router.ServeHTTP(recorder, authorizedRequest(http.MethodPut, "/products/nonexistent", body))
|
||||
router.ServeHTTP(recorder, authorizedRequest(http.MethodPut, "/user-products/nonexistent", body))
|
||||
|
||||
if recorder.Code != http.StatusNotFound {
|
||||
t.Errorf("expected 404, got %d", recorder.Code)
|
||||
@@ -146,19 +146,19 @@ func TestUpdate_NotFound(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestUpdate_Success(t *testing.T) {
|
||||
mockRepo := &productmocks.MockProductRepository{
|
||||
UpdateFn: func(ctx context.Context, id, userID string, req product.UpdateRequest) (*product.Product, error) {
|
||||
updated := makeProduct(*req.Name)
|
||||
mockRepo := &userproductmocks.MockUserProductRepository{
|
||||
UpdateFn: func(ctx context.Context, id, userID string, req userproduct.UpdateRequest) (*userproduct.UserProduct, error) {
|
||||
updated := makeUserProduct(*req.Name)
|
||||
return updated, nil
|
||||
},
|
||||
}
|
||||
handler := product.NewHandler(mockRepo)
|
||||
handler := userproduct.NewHandler(mockRepo)
|
||||
router := buildRouter(handler, "user-1")
|
||||
|
||||
namePtr := "Oat Milk"
|
||||
body, _ := json.Marshal(product.UpdateRequest{Name: &namePtr})
|
||||
body, _ := json.Marshal(userproduct.UpdateRequest{Name: &namePtr})
|
||||
recorder := httptest.NewRecorder()
|
||||
router.ServeHTTP(recorder, authorizedRequest(http.MethodPut, "/products/prod-1", body))
|
||||
router.ServeHTTP(recorder, authorizedRequest(http.MethodPut, "/user-products/prod-1", body))
|
||||
|
||||
if recorder.Code != http.StatusOK {
|
||||
t.Errorf("expected 200, got %d", recorder.Code)
|
||||
@@ -166,16 +166,16 @@ func TestUpdate_Success(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestDelete_NotFound(t *testing.T) {
|
||||
mockRepo := &productmocks.MockProductRepository{
|
||||
mockRepo := &userproductmocks.MockUserProductRepository{
|
||||
DeleteFn: func(ctx context.Context, id, userID string) error {
|
||||
return product.ErrNotFound
|
||||
return userproduct.ErrNotFound
|
||||
},
|
||||
}
|
||||
handler := product.NewHandler(mockRepo)
|
||||
handler := userproduct.NewHandler(mockRepo)
|
||||
router := buildRouter(handler, "user-1")
|
||||
|
||||
recorder := httptest.NewRecorder()
|
||||
router.ServeHTTP(recorder, authorizedRequest(http.MethodDelete, "/products/nonexistent", nil))
|
||||
router.ServeHTTP(recorder, authorizedRequest(http.MethodDelete, "/user-products/nonexistent", nil))
|
||||
|
||||
if recorder.Code != http.StatusNotFound {
|
||||
t.Errorf("expected 404, got %d", recorder.Code)
|
||||
@@ -183,16 +183,16 @@ func TestDelete_NotFound(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestDelete_Success(t *testing.T) {
|
||||
mockRepo := &productmocks.MockProductRepository{
|
||||
mockRepo := &userproductmocks.MockUserProductRepository{
|
||||
DeleteFn: func(ctx context.Context, id, userID string) error {
|
||||
return nil
|
||||
},
|
||||
}
|
||||
handler := product.NewHandler(mockRepo)
|
||||
handler := userproduct.NewHandler(mockRepo)
|
||||
router := buildRouter(handler, "user-1")
|
||||
|
||||
recorder := httptest.NewRecorder()
|
||||
router.ServeHTTP(recorder, authorizedRequest(http.MethodDelete, "/products/prod-1", nil))
|
||||
router.ServeHTTP(recorder, authorizedRequest(http.MethodDelete, "/user-products/prod-1", nil))
|
||||
|
||||
if recorder.Code != http.StatusNoContent {
|
||||
t.Errorf("expected 204, got %d", recorder.Code)
|
||||
@@ -1,29 +1,29 @@
|
||||
//go:build integration
|
||||
|
||||
package product_test
|
||||
package userproduct_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/food-ai/backend/internal/domain/product"
|
||||
"github.com/food-ai/backend/internal/domain/userproduct"
|
||||
"github.com/food-ai/backend/internal/testutil"
|
||||
)
|
||||
|
||||
func TestProductRepository_Create_Defaults(t *testing.T) {
|
||||
func TestUserProductRepository_Create_Defaults(t *testing.T) {
|
||||
pool := testutil.SetupTestDB(t)
|
||||
repo := product.NewRepository(pool)
|
||||
repo := userproduct.NewRepository(pool)
|
||||
requestContext := context.Background()
|
||||
|
||||
// storage_days=0 → 7; unit="" → "pcs"; quantity=0 → 1
|
||||
created, createError := repo.Create(requestContext, "test-user", product.CreateRequest{
|
||||
created, createError := repo.Create(requestContext, "test-user", userproduct.CreateRequest{
|
||||
Name: "Milk",
|
||||
StorageDays: 0,
|
||||
Unit: "",
|
||||
Quantity: 0,
|
||||
})
|
||||
if createError != nil {
|
||||
t.Fatalf("create product: %v", createError)
|
||||
t.Fatalf("create user product: %v", createError)
|
||||
}
|
||||
if created.StorageDays != 7 {
|
||||
t.Errorf("expected storage_days=7, got %d", created.StorageDays)
|
||||
@@ -36,25 +36,24 @@ func TestProductRepository_Create_Defaults(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestProductRepository_List_OrderByExpiry(t *testing.T) {
|
||||
func TestUserProductRepository_List_OrderByExpiry(t *testing.T) {
|
||||
pool := testutil.SetupTestDB(t)
|
||||
repo := product.NewRepository(pool)
|
||||
repo := userproduct.NewRepository(pool)
|
||||
requestContext := context.Background()
|
||||
|
||||
userID := "list-order-user"
|
||||
// Create product with longer expiry first, shorter expiry second.
|
||||
_, createError := repo.Create(requestContext, userID, product.CreateRequest{Name: "Milk", StorageDays: 14})
|
||||
_, createError := repo.Create(requestContext, userID, userproduct.CreateRequest{Name: "Milk", StorageDays: 14})
|
||||
if createError != nil {
|
||||
t.Fatalf("create Milk: %v", createError)
|
||||
}
|
||||
_, createError = repo.Create(requestContext, userID, product.CreateRequest{Name: "Butter", StorageDays: 3})
|
||||
_, createError = repo.Create(requestContext, userID, userproduct.CreateRequest{Name: "Butter", StorageDays: 3})
|
||||
if createError != nil {
|
||||
t.Fatalf("create Butter: %v", createError)
|
||||
}
|
||||
|
||||
products, listError := repo.List(requestContext, userID)
|
||||
if listError != nil {
|
||||
t.Fatalf("list products: %v", listError)
|
||||
t.Fatalf("list user products: %v", listError)
|
||||
}
|
||||
if len(products) != 2 {
|
||||
t.Fatalf("expected 2 products, got %d", len(products))
|
||||
@@ -65,12 +64,12 @@ func TestProductRepository_List_OrderByExpiry(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestProductRepository_BatchCreate(t *testing.T) {
|
||||
func TestUserProductRepository_BatchCreate(t *testing.T) {
|
||||
pool := testutil.SetupTestDB(t)
|
||||
repo := product.NewRepository(pool)
|
||||
repo := userproduct.NewRepository(pool)
|
||||
requestContext := context.Background()
|
||||
|
||||
products, batchError := repo.BatchCreate(requestContext, "batch-user", []product.CreateRequest{
|
||||
products, batchError := repo.BatchCreate(requestContext, "batch-user", []userproduct.CreateRequest{
|
||||
{Name: "Eggs", Quantity: 12, Unit: "pcs"},
|
||||
{Name: "Flour", Quantity: 500, Unit: "g"},
|
||||
})
|
||||
@@ -82,46 +81,46 @@ func TestProductRepository_BatchCreate(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestProductRepository_Update_NotFound(t *testing.T) {
|
||||
func TestUserProductRepository_Update_NotFound(t *testing.T) {
|
||||
pool := testutil.SetupTestDB(t)
|
||||
repo := product.NewRepository(pool)
|
||||
repo := userproduct.NewRepository(pool)
|
||||
requestContext := context.Background()
|
||||
|
||||
newName := "Ghost"
|
||||
_, updateError := repo.Update(requestContext, "00000000-0000-0000-0000-000000000000", "any-user",
|
||||
product.UpdateRequest{Name: &newName})
|
||||
if updateError != product.ErrNotFound {
|
||||
userproduct.UpdateRequest{Name: &newName})
|
||||
if updateError != userproduct.ErrNotFound {
|
||||
t.Errorf("expected ErrNotFound, got %v", updateError)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProductRepository_Delete_WrongUser(t *testing.T) {
|
||||
func TestUserProductRepository_Delete_WrongUser(t *testing.T) {
|
||||
pool := testutil.SetupTestDB(t)
|
||||
repo := product.NewRepository(pool)
|
||||
repo := userproduct.NewRepository(pool)
|
||||
requestContext := context.Background()
|
||||
|
||||
created, createError := repo.Create(requestContext, "owner-user", product.CreateRequest{Name: "Cheese"})
|
||||
created, createError := repo.Create(requestContext, "owner-user", userproduct.CreateRequest{Name: "Cheese"})
|
||||
if createError != nil {
|
||||
t.Fatalf("create product: %v", createError)
|
||||
t.Fatalf("create user product: %v", createError)
|
||||
}
|
||||
|
||||
deleteError := repo.Delete(requestContext, created.ID, "other-user")
|
||||
if deleteError != product.ErrNotFound {
|
||||
if deleteError != userproduct.ErrNotFound {
|
||||
t.Errorf("expected ErrNotFound when deleting another user's product, got %v", deleteError)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProductRepository_ListForPrompt(t *testing.T) {
|
||||
func TestUserProductRepository_ListForPrompt(t *testing.T) {
|
||||
pool := testutil.SetupTestDB(t)
|
||||
repo := product.NewRepository(pool)
|
||||
repo := userproduct.NewRepository(pool)
|
||||
requestContext := context.Background()
|
||||
|
||||
userID := "prompt-user"
|
||||
_, createError := repo.Create(requestContext, userID, product.CreateRequest{
|
||||
_, createError := repo.Create(requestContext, userID, userproduct.CreateRequest{
|
||||
Name: "Tomatoes", Quantity: 4, Unit: "pcs", StorageDays: 5,
|
||||
})
|
||||
if createError != nil {
|
||||
t.Fatalf("create product: %v", createError)
|
||||
t.Fatalf("create user product: %v", createError)
|
||||
}
|
||||
|
||||
lines, listError := repo.ListForPrompt(requestContext, userID)
|
||||
Reference in New Issue
Block a user