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

@@ -0,0 +1,200 @@
package userproduct_test
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"time"
"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"
)
type alwaysAuthValidator struct{ userID string }
func (v *alwaysAuthValidator) ValidateAccessToken(_ string) (*middleware.TokenClaims, error) {
return &middleware.TokenClaims{UserID: v.userID}, nil
}
func buildRouter(handler *userproduct.Handler, userID string) *chi.Mux {
router := chi.NewRouter()
router.Use(middleware.Auth(&alwaysAuthValidator{userID: userID}))
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
}
func authorizedRequest(method, target string, body []byte) *http.Request {
request := httptest.NewRequest(method, target, bytes.NewReader(body))
request.Header.Set("Authorization", "Bearer test-token")
request.Header.Set("Content-Type", "application/json")
return request
}
func makeUserProduct(name string) *userproduct.UserProduct {
return &userproduct.UserProduct{
ID: "prod-1",
UserID: "user-1",
Name: name,
Quantity: 1,
Unit: "pcs",
StorageDays: 7,
AddedAt: time.Now(),
ExpiresAt: time.Now().AddDate(0, 0, 7),
DaysLeft: 7,
}
}
func TestList_Success(t *testing.T) {
mockRepo := &userproductmocks.MockUserProductRepository{
ListFn: func(ctx context.Context, userID string) ([]*userproduct.UserProduct, error) {
return []*userproduct.UserProduct{makeUserProduct("Milk")}, nil
},
}
handler := userproduct.NewHandler(mockRepo)
router := buildRouter(handler, "user-1")
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, authorizedRequest(http.MethodGet, "/user-products", nil))
if recorder.Code != http.StatusOK {
t.Errorf("expected 200, got %d", recorder.Code)
}
}
func TestCreate_MissingName(t *testing.T) {
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, "/user-products", body))
if recorder.Code != http.StatusBadRequest {
t.Errorf("expected 400, got %d", recorder.Code)
}
}
func TestCreate_Success(t *testing.T) {
mockRepo := &userproductmocks.MockUserProductRepository{
CreateFn: func(ctx context.Context, userID string, req userproduct.CreateRequest) (*userproduct.UserProduct, error) {
return makeUserProduct(req.Name), nil
},
}
handler := userproduct.NewHandler(mockRepo)
router := buildRouter(handler, "user-1")
body, _ := json.Marshal(userproduct.CreateRequest{Name: "Milk", Quantity: 1, Unit: "L"})
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, authorizedRequest(http.MethodPost, "/user-products", body))
if recorder.Code != http.StatusCreated {
t.Errorf("expected 201, got %d", recorder.Code)
}
}
func TestBatchCreate_Success(t *testing.T) {
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] = makeUserProduct(item.Name)
}
return result, nil
},
}
handler := userproduct.NewHandler(mockRepo)
router := buildRouter(handler, "user-1")
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, "/user-products/batch", body))
if recorder.Code != http.StatusCreated {
t.Errorf("expected 201, got %d", recorder.Code)
}
}
func TestUpdate_NotFound(t *testing.T) {
mockRepo := &userproductmocks.MockUserProductRepository{
UpdateFn: func(ctx context.Context, id, userID string, req userproduct.UpdateRequest) (*userproduct.UserProduct, error) {
return nil, userproduct.ErrNotFound
},
}
handler := userproduct.NewHandler(mockRepo)
router := buildRouter(handler, "user-1")
namePtr := "NewName"
body, _ := json.Marshal(userproduct.UpdateRequest{Name: &namePtr})
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, authorizedRequest(http.MethodPut, "/user-products/nonexistent", body))
if recorder.Code != http.StatusNotFound {
t.Errorf("expected 404, got %d", recorder.Code)
}
}
func TestUpdate_Success(t *testing.T) {
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 := userproduct.NewHandler(mockRepo)
router := buildRouter(handler, "user-1")
namePtr := "Oat Milk"
body, _ := json.Marshal(userproduct.UpdateRequest{Name: &namePtr})
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, authorizedRequest(http.MethodPut, "/user-products/prod-1", body))
if recorder.Code != http.StatusOK {
t.Errorf("expected 200, got %d", recorder.Code)
}
}
func TestDelete_NotFound(t *testing.T) {
mockRepo := &userproductmocks.MockUserProductRepository{
DeleteFn: func(ctx context.Context, id, userID string) error {
return userproduct.ErrNotFound
},
}
handler := userproduct.NewHandler(mockRepo)
router := buildRouter(handler, "user-1")
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, authorizedRequest(http.MethodDelete, "/user-products/nonexistent", nil))
if recorder.Code != http.StatusNotFound {
t.Errorf("expected 404, got %d", recorder.Code)
}
}
func TestDelete_Success(t *testing.T) {
mockRepo := &userproductmocks.MockUserProductRepository{
DeleteFn: func(ctx context.Context, id, userID string) error {
return nil
},
}
handler := userproduct.NewHandler(mockRepo)
router := buildRouter(handler, "user-1")
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, authorizedRequest(http.MethodDelete, "/user-products/prod-1", nil))
if recorder.Code != http.StatusNoContent {
t.Errorf("expected 204, got %d", recorder.Code)
}
}

View File

@@ -0,0 +1,137 @@
//go:build integration
package userproduct_test
import (
"context"
"testing"
"github.com/food-ai/backend/internal/domain/userproduct"
"github.com/food-ai/backend/internal/testutil"
)
func TestUserProductRepository_Create_Defaults(t *testing.T) {
pool := testutil.SetupTestDB(t)
repo := userproduct.NewRepository(pool)
requestContext := context.Background()
// storage_days=0 → 7; unit="" → "pcs"; quantity=0 → 1
created, createError := repo.Create(requestContext, "test-user", userproduct.CreateRequest{
Name: "Milk",
StorageDays: 0,
Unit: "",
Quantity: 0,
})
if createError != nil {
t.Fatalf("create user product: %v", createError)
}
if created.StorageDays != 7 {
t.Errorf("expected storage_days=7, got %d", created.StorageDays)
}
if created.Unit != "pcs" {
t.Errorf("expected unit=pcs, got %q", created.Unit)
}
if created.Quantity != 1 {
t.Errorf("expected quantity=1, got %v", created.Quantity)
}
}
func TestUserProductRepository_List_OrderByExpiry(t *testing.T) {
pool := testutil.SetupTestDB(t)
repo := userproduct.NewRepository(pool)
requestContext := context.Background()
userID := "list-order-user"
_, 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, 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 user products: %v", listError)
}
if len(products) != 2 {
t.Fatalf("expected 2 products, got %d", len(products))
}
// Butter (3 days) should come before Milk (14 days).
if products[0].Name != "Butter" {
t.Errorf("expected first product Butter (expires sooner), got %q", products[0].Name)
}
}
func TestUserProductRepository_BatchCreate(t *testing.T) {
pool := testutil.SetupTestDB(t)
repo := userproduct.NewRepository(pool)
requestContext := context.Background()
products, batchError := repo.BatchCreate(requestContext, "batch-user", []userproduct.CreateRequest{
{Name: "Eggs", Quantity: 12, Unit: "pcs"},
{Name: "Flour", Quantity: 500, Unit: "g"},
})
if batchError != nil {
t.Fatalf("batch create: %v", batchError)
}
if len(products) != 2 {
t.Errorf("expected 2 products, got %d", len(products))
}
}
func TestUserProductRepository_Update_NotFound(t *testing.T) {
pool := testutil.SetupTestDB(t)
repo := userproduct.NewRepository(pool)
requestContext := context.Background()
newName := "Ghost"
_, updateError := repo.Update(requestContext, "00000000-0000-0000-0000-000000000000", "any-user",
userproduct.UpdateRequest{Name: &newName})
if updateError != userproduct.ErrNotFound {
t.Errorf("expected ErrNotFound, got %v", updateError)
}
}
func TestUserProductRepository_Delete_WrongUser(t *testing.T) {
pool := testutil.SetupTestDB(t)
repo := userproduct.NewRepository(pool)
requestContext := context.Background()
created, createError := repo.Create(requestContext, "owner-user", userproduct.CreateRequest{Name: "Cheese"})
if createError != nil {
t.Fatalf("create user product: %v", createError)
}
deleteError := repo.Delete(requestContext, created.ID, "other-user")
if deleteError != userproduct.ErrNotFound {
t.Errorf("expected ErrNotFound when deleting another user's product, got %v", deleteError)
}
}
func TestUserProductRepository_ListForPrompt(t *testing.T) {
pool := testutil.SetupTestDB(t)
repo := userproduct.NewRepository(pool)
requestContext := context.Background()
userID := "prompt-user"
_, createError := repo.Create(requestContext, userID, userproduct.CreateRequest{
Name: "Tomatoes", Quantity: 4, Unit: "pcs", StorageDays: 5,
})
if createError != nil {
t.Fatalf("create user product: %v", createError)
}
lines, listError := repo.ListForPrompt(requestContext, userID)
if listError != nil {
t.Fatalf("list for prompt: %v", listError)
}
if len(lines) != 1 {
t.Fatalf("expected 1 line, got %d", len(lines))
}
// Line should start with "- Tomatoes".
if len(lines[0]) < 11 || lines[0][:11] != "- Tomatoes " {
t.Errorf("unexpected prompt line format: %q", lines[0])
}
}