feat: implement Iteration 4 — menu planning, shopping list, diary

Backend:
- Migrations 007 (menu_plans, menu_items, shopping_lists) and
  008 (meal_diary)
- gemini/menu.go: GenerateMenu — 7-day × 3-meal plan via one Groq call
- internal/menu: model, repository (GetByWeek, SaveMenuInTx,
  shopping list CRUD), handler (GET/PUT/DELETE /menu,
  POST /ai/generate-menu, shopping list endpoints)
- internal/diary: model, repository, handler (GET/POST/DELETE /diary)
- Increase server WriteTimeout to 120s for long AI calls
- api_client.go: add patch() and postList() helpers

Flutter:
- shared/models: menu.dart, shopping_item.dart, diary_entry.dart
- features/menu: menu_service.dart, menu_provider.dart
  (MenuNotifier, ShoppingListNotifier, DiaryNotifier with family)
- MenuScreen: 7-day view, week nav, skeleton on generation,
  generate FAB with confirmation dialog
- ShoppingListScreen: items by category, optimistic checkbox toggle
- DiaryScreen: daily entries with swipe-to-delete, add-entry sheet
- Router: /menu/shopping-list and /menu/diary routes

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
dbastrikin
2026-02-22 12:00:25 +02:00
parent 612a0eda60
commit ea8e207a45
22 changed files with 2926 additions and 12 deletions

View File

@@ -0,0 +1,110 @@
package diary
import (
"encoding/json"
"log/slog"
"net/http"
"github.com/food-ai/backend/internal/middleware"
"github.com/go-chi/chi/v5"
)
// Handler handles diary endpoints.
type Handler struct {
repo *Repository
}
// NewHandler creates a new Handler.
func NewHandler(repo *Repository) *Handler {
return &Handler{repo: repo}
}
// GetByDate handles GET /diary?date=YYYY-MM-DD
func (h *Handler) GetByDate(w http.ResponseWriter, r *http.Request) {
userID := middleware.UserIDFromCtx(r.Context())
if userID == "" {
writeError(w, http.StatusUnauthorized, "unauthorized")
return
}
date := r.URL.Query().Get("date")
if date == "" {
writeError(w, http.StatusBadRequest, "date query parameter required (YYYY-MM-DD)")
return
}
entries, err := h.repo.ListByDate(r.Context(), userID, date)
if err != nil {
slog.Error("list diary by date", "err", err)
writeError(w, http.StatusInternalServerError, "failed to load diary")
return
}
if entries == nil {
entries = []*Entry{}
}
writeJSON(w, http.StatusOK, entries)
}
// Create handles POST /diary
func (h *Handler) Create(w http.ResponseWriter, r *http.Request) {
userID := middleware.UserIDFromCtx(r.Context())
if userID == "" {
writeError(w, http.StatusUnauthorized, "unauthorized")
return
}
var req CreateRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(w, http.StatusBadRequest, "invalid request body")
return
}
if req.Date == "" || req.Name == "" || req.MealType == "" {
writeError(w, http.StatusBadRequest, "date, meal_type and name are required")
return
}
entry, err := h.repo.Create(r.Context(), userID, req)
if err != nil {
slog.Error("create diary entry", "err", err)
writeError(w, http.StatusInternalServerError, "failed to create diary entry")
return
}
writeJSON(w, http.StatusCreated, entry)
}
// Delete handles DELETE /diary/{id}
func (h *Handler) Delete(w http.ResponseWriter, r *http.Request) {
userID := middleware.UserIDFromCtx(r.Context())
if userID == "" {
writeError(w, http.StatusUnauthorized, "unauthorized")
return
}
id := chi.URLParam(r, "id")
if err := h.repo.Delete(r.Context(), id, userID); err != nil {
if err == ErrNotFound {
writeError(w, http.StatusNotFound, "diary entry not found")
return
}
slog.Error("delete diary entry", "err", err)
writeError(w, http.StatusInternalServerError, "failed to delete diary entry")
return
}
w.WriteHeader(http.StatusNoContent)
}
type errorResponse struct {
Error string `json:"error"`
}
func writeError(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,33 @@
package diary
import "time"
// Entry is a single meal diary record.
type Entry struct {
ID string `json:"id"`
Date string `json:"date"` // YYYY-MM-DD
MealType string `json:"meal_type"`
Name string `json:"name"`
Portions float64 `json:"portions"`
Calories *float64 `json:"calories,omitempty"`
ProteinG *float64 `json:"protein_g,omitempty"`
FatG *float64 `json:"fat_g,omitempty"`
CarbsG *float64 `json:"carbs_g,omitempty"`
Source string `json:"source"`
RecipeID *string `json:"recipe_id,omitempty"`
CreatedAt time.Time `json:"created_at"`
}
// CreateRequest is the body for POST /diary.
type CreateRequest struct {
Date string `json:"date"`
MealType string `json:"meal_type"`
Name string `json:"name"`
Portions float64 `json:"portions"`
Calories *float64 `json:"calories"`
ProteinG *float64 `json:"protein_g"`
FatG *float64 `json:"fat_g"`
CarbsG *float64 `json:"carbs_g"`
Source string `json:"source"`
RecipeID *string `json:"recipe_id"`
}

View File

@@ -0,0 +1,104 @@
package diary
import (
"context"
"errors"
"fmt"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
// ErrNotFound is returned when a diary entry does not exist for the user.
var ErrNotFound = errors.New("diary entry not found")
// Repository handles persistence for meal diary entries.
type Repository struct {
pool *pgxpool.Pool
}
// NewRepository creates a new Repository.
func NewRepository(pool *pgxpool.Pool) *Repository {
return &Repository{pool: pool}
}
// ListByDate returns all diary entries for a user on a given date (YYYY-MM-DD).
func (r *Repository) ListByDate(ctx context.Context, userID, date string) ([]*Entry, error) {
rows, err := r.pool.Query(ctx, `
SELECT id, date::text, meal_type, name, portions,
calories, protein_g, fat_g, carbs_g,
source, recipe_id, created_at
FROM meal_diary
WHERE user_id = $1 AND date = $2::date
ORDER BY created_at ASC`, userID, date)
if err != nil {
return nil, fmt.Errorf("list diary: %w", err)
}
defer rows.Close()
var result []*Entry
for rows.Next() {
e, err := scanEntry(rows)
if err != nil {
return nil, fmt.Errorf("scan diary entry: %w", err)
}
result = append(result, e)
}
return result, rows.Err()
}
// Create inserts a new diary entry and returns the stored record.
func (r *Repository) Create(ctx context.Context, userID string, req CreateRequest) (*Entry, error) {
portions := req.Portions
if portions <= 0 {
portions = 1
}
source := req.Source
if source == "" {
source = "manual"
}
row := r.pool.QueryRow(ctx, `
INSERT INTO meal_diary (user_id, date, meal_type, name, portions,
calories, protein_g, fat_g, carbs_g, source, recipe_id)
VALUES ($1, $2::date, $3, $4, $5, $6, $7, $8, $9, $10, $11)
RETURNING id, date::text, meal_type, name, portions,
calories, protein_g, fat_g, carbs_g, source, recipe_id, created_at`,
userID, req.Date, req.MealType, req.Name, portions,
req.Calories, req.ProteinG, req.FatG, req.CarbsG,
source, req.RecipeID,
)
return scanEntry(row)
}
// Delete removes a diary entry for the given user.
func (r *Repository) Delete(ctx context.Context, id, userID string) error {
tag, err := r.pool.Exec(ctx,
`DELETE FROM meal_diary WHERE id = $1 AND user_id = $2`, id, userID)
if err != nil {
return fmt.Errorf("delete diary entry: %w", err)
}
if tag.RowsAffected() == 0 {
return ErrNotFound
}
return nil
}
// --- helpers ---
type scannable interface {
Scan(dest ...any) error
}
func scanEntry(s scannable) (*Entry, error) {
var e Entry
err := s.Scan(
&e.ID, &e.Date, &e.MealType, &e.Name, &e.Portions,
&e.Calories, &e.ProteinG, &e.FatG, &e.CarbsG,
&e.Source, &e.RecipeID, &e.CreatedAt,
)
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrNotFound
}
return &e, err
}