refactor: introduce internal/domain/ layer, rename model.go → entity.go

Move all business-logic packages from internal/ root into internal/domain/:
  auth, cuisine, diary, dish, home, ingredient, language, menu, product,
  recipe, recognition, recommendation, savedrecipe, tag, units, user

Rename model.go → entity.go in packages that hold domain entities:
  diary, dish, home, ingredient, menu, product, recipe, savedrecipe, user

Update all import paths accordingly (adapters, infra/server, cmd/server,
tests). No logic changes.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
dbastrikin
2026-03-15 22:12:07 +02:00
parent 6548f868c3
commit 6594013b53
58 changed files with 73 additions and 73 deletions

View File

@@ -0,0 +1,41 @@
package product
import "time"
// Product is a user's food item in their pantry.
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"`
}
// 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"`
}
// 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"`
}

View File

@@ -0,0 +1,137 @@
package product
import (
"encoding/json"
"errors"
"log/slog"
"net/http"
"github.com/food-ai/backend/internal/infra/middleware"
"github.com/go-chi/chi/v5"
)
// Handler handles /products HTTP requests.
type Handler struct {
repo *Repository
}
// NewHandler creates a new Handler.
func NewHandler(repo *Repository) *Handler {
return &Handler{repo: repo}
}
// 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")
return
}
if products == nil {
products = []*Product{}
}
writeJSON(w, http.StatusOK, 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")
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")
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{})
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")
return
}
p, err := h.repo.Update(r.Context(), id, userID, req)
if errors.Is(err, ErrNotFound) {
writeErrorJSON(w, http.StatusNotFound, "product not found")
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)
}
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 writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(v)
}

View File

@@ -0,0 +1,202 @@
package product
import (
"context"
"errors"
"fmt"
"time"
"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.
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_ingredient_id, name, quantity, unit, category, storage_days, added_at,
(added_at + storage_days * INTERVAL '1 day') AS expires_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)
}
defer rows.Close()
return collectProducts(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
}
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)
}
// 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)
}
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()
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)
}
return lines, rows.Err()
}
// --- 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,
)
if err != nil {
return nil, err
}
computeDaysLeft(&p)
return &p, nil
}
func collectProducts(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)
}
computeDaysLeft(&p)
result = append(result, &p)
}
return result, rows.Err()
}
func computeDaysLeft(p *Product) {
d := int(time.Until(p.ExpiresAt).Hours() / 24)
if d < 0 {
d = 0
}
p.DaysLeft = d
p.ExpiringSoon = d <= 3
}