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:
41
backend/internal/domain/userproduct/entity.go
Normal file
41
backend/internal/domain/userproduct/entity.go
Normal 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"`
|
||||
}
|
||||
147
backend/internal/domain/userproduct/handler.go
Normal file
147
backend/internal/domain/userproduct/handler.go
Normal 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)
|
||||
}
|
||||
36
backend/internal/domain/userproduct/mocks/repository.go
Normal file
36
backend/internal/domain/userproduct/mocks/repository.go
Normal 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)
|
||||
}
|
||||
202
backend/internal/domain/userproduct/repository.go
Normal file
202
backend/internal/domain/userproduct/repository.go
Normal 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
|
||||
}
|
||||
Reference in New Issue
Block a user