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:
@@ -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)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user