Fold all incremental schema changes into the baseline migration so that
a fresh database only needs to run one file:
- recipe_source enum now includes 'menu'
- recipe_products/recipe_product_translations renamed to
recipe_ingredients/recipe_ingredient_translations; product_id → ingredient_id
- menu_items.meal_type CHECK expanded to all 6 types
(breakfast, second_breakfast, lunch, afternoon_snack, dinner, snack)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Backend fixes:
- migration 003: add 'menu' value to recipe_source enum (was causing SQLSTATE 22P02)
- migration 004: rename recipe_products→recipe_ingredients, product_id→ingredient_id (was causing SQLSTATE 42P01)
- dish/repository.go: fix INSERT INTO tags using $1/$1 for two columns → $1/$2 (was causing SQLSTATE 42P08)
- home/handler.go: replace non-existent saved_recipes table with correct joins (recipes→dishes→dish_translations, user_saved_recipes) so today's plan and recommendations load correctly
- reqlog: new slog.Handler wrapper that adds request_id and stack trace to ERROR-level logs
- all handlers: slog.Error→slog.ErrorContext so error logs include request context; writeError includes request_id in response body
Client:
- home_screen.dart: extend home screen to future dates, show planned meals as ghost entries
- l10n: add new localisation keys for home screen date navigation and planned meal UI
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
VARCHAR(255) was too narrow for some OpenFoodFacts product names.
Switching to TEXT removes the length constraint entirely.
Also trim whitespace from resolved canonical names during import.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Backend:
- GET /dishes/search — hybrid FTS (english + simple) + trgm + ILIKE search
- GET /diary/recent — recently used dishes and products for the current user
- product search upgraded: FTS on canonical_name and product_aliases, ranked by GREATEST(ts_rank, similarity)
- importoff: collect product_name_ru/de/fr/... as product_aliases for multilingual search (e.g. "сникерс" → "Snickers")
- migrations: FTS + trgm indexes merged into 001_initial_schema.sql (002 removed)
Flutter:
- FoodSearchSheet: debounced search field, recently-used section, product/dish results, scan-photo and barcode chips
- DishPortionSheet: quick ½/1/1½/2 buttons + custom input
- + button in meal card now opens FoodSearchSheet instead of going directly to AI scan
- 7 new l10n keys across all 12 languages
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- import-off: show limit/batch/min-scans params in make command examples
- CLAUDE.md: clarify that parameter changes to make targets also require README update
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- 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>
Backend:
- Rename recognition_jobs → dish_recognition_jobs; add target_date and
target_meal_type columns to capture scan context at submission time
- Add job_id FK on meal_diary so entries are linked to their origin job
- New GET /ai/jobs endpoint returns today's unlinked jobs for the current user
- diary.Entry and CreateRequest gain job_id field; repository reads/writes it
- CORS middleware: allow Accept-Language and Cache-Control headers
- Logging middleware: implement http.Flusher on responseWriter (needed for SSE)
- Consolidate migrations into a single 001_initial_schema.sql
Flutter:
- POST /ai/recognize-dish now sends target_date and target_meal_type
- DishResultSheet accepts jobId; _addToDiary includes it in the diary payload,
saves last-used meal type to SharedPreferences, invalidates todayJobsProvider
- TodayJobsNotifier + todayJobsProvider: loads unlinked jobs via GET /ai/jobs
- Home screen shows _TodayJobsWidget (up to 3 tiles) between macros and meals;
tapping a done tile reopens DishResultSheet with the stored result
- Quick Actions row: third button "История" → /scan/history
- New RecognitionHistoryScreen: full-screen list of today's unlinked jobs
- LocalPreferences wrapper over SharedPreferences (last_used_meal_type)
- app_theme: apply Google Fonts Roboto as default font family
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Replace dual-consumer priority WorkerPool with a single consumer per
worker process. WORKER_PLAN=paid|free selects the Kafka topic and
consumer group ID (dish-recognition-paid / dish-recognition-free).
docker-compose now runs worker-paid and worker-free as separate services
for independent scaling. Makefile dev target launches both workers locally.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Add EXTERNAL listener on port 9093 to Kafka so local processes can connect
- Add KAFKA_BROKERS=localhost:9093 to .env.example
- Add dev/dev-infra-up/dev-infra-down targets to Makefile
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Kafka consumers and WorkerPool are moved out of the server process into
a dedicated worker binary. Server now handles HTTP + SSE only; worker
handles Kafka consumption and AI processing.
- cmd/worker/main.go + init.go: new binary with minimal config
(DATABASE_URL, OPENAI_API_KEY, KAFKA_BROKERS)
- cmd/server: remove WorkerPool, paidConsumer, freeConsumer
- Dockerfile: builds both server and worker binaries
- docker-compose.yml: add worker service
- Makefile: add run-worker and docker-logs-worker targets
- README.md: document worker startup and env vars
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
RecognizeDish() and buildRecipePrompt() were generating text in the
user's language and storing it in base tables, violating the project
rule that base tables always hold English canonical text.
- RecognizeDish(): hardcode English for dish_name; enrichDishInBackground()
now correctly translates FROM English into all other languages
- buildRecipePrompt(): remove langName lookup, hardcode English for all
text fields; drop unused locale import
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Remove denormalized columns (name, calories, protein_g, fat_g, carbs_g)
from meal_diary. Name is now resolved via JOIN with dishes/dish_translations;
macros are computed as recipe.*_per_serving * portions at query time.
- Add dish.Repository.FindOrCreateRecipe: finds or creates a minimal recipe
stub seeded with AI-estimated macros
- recognition/handler: resolve recipe_id synchronously per candidate;
simplify enrichDishInBackground to translations-only
- diary/handler: accept dish_id OR name; always resolve recipe_id via
FindOrCreateRecipe before INSERT
- diary/entity: DishID is now non-nullable string; CreateRequest drops macros
- diary/repository: ListByDate and Create use JOIN to return computed macros
- ai/types: add RecipeID field to DishCandidate
- Update tests and wire_gen accordingly
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Avoids conflict with other local Postgres instances.
Container internal port stays 5432; only the host-side mapping changes.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Backend:
- Translate all recognition prompts (receipt, products, dish) from Russian to English
- Add lang parameter to Recognizer interface and pass locale.FromContext in handlers
- DishResult type uses candidates array for multi-candidate responses
Client:
- Add meal tracking: diary provider, date selector, meal type model
- DishResult parser: backward-compatible with legacy flat format and new candidates format
- DishResultScreen: sticky bottom button, full-width portion/meal-type inputs,
КБЖУ disclaimer moved under nutrition card, add date field to diary POST body
- Recognition prompts now return dish/product names in user's preferred language
- Onboarding, profile, home screen visual updates
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Introduce 6-step onboarding screen (Goal → Gender → DOB → Height+Weight
→ Activity → Calories) with per-step accent colors, hero illustration
area (concentric circles + icon), and white card content panel.
Backend user entity and service updated to support onboarding fields
(goal, activity, height, weight, DOB, dailyCalories). Router guards
unauthenticated and onboarding-incomplete users. Profile service and
screen updated to expose language and onboarding preferences.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
goose splits SQL on semicolons and misinterprets dollar-quoted strings
($$...$$) as statement boundaries, causing a parse error on the PL/pgSQL
function body. StatementBegin/End annotations tell goose to treat the
block as a single statement.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
The file no longer contains Firebase-specific code — only the TokenVerifier
interface. Rename to reflect its actual purpose.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Create internal/adapters/firebase/auth.go with Auth, noopAuth, NewAuthOrNoop
(renamed from FirebaseAuth, noopTokenVerifier, NewFirebaseAuthOrNoop)
- Reduce internal/auth/firebase.go to TokenVerifier interface only
- Remove PhotoSearcher interface from adapters/pexels (belongs to consumers)
- Update wire.go and wire_gen.go to use firebase.NewAuthOrNoop
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Add internal/adapters/ai/types.go with neutral shared types
(Recipe, DayPlan, RecognizedItem, IngredientClassification, etc.)
- Remove types from internal/adapters/openai/ — adapter now uses ai.*
- Define Recognizer interface in recognition package
- Define MenuGenerator interface in menu package
- Define RecipeGenerator interface in recommendation package
- Handler structs now hold interfaces, not *openai.Client
- Add wire.Bind entries for the three new interface bindings
To swap OpenAI for another provider: implement the three interfaces
using ai.* types and change the wire.Bind lines in cmd/server/wire.go.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
All test files relocated from internal/X/ to tests/X/ and converted
to package X_test, using only the public API of each package.
- tests/auth/: jwt, service, handler integration tests
- tests/middleware/: auth, request_id, recovery tests
- tests/user/: calories, service, repository integration tests
- tests/locale/: locale tests (already package locale_test, just moved)
- tests/ingredient/: repository integration tests
- tests/recipe/: repository integration tests
mockUserRepo in tests/user/service_test.go redefined locally with
fully-qualified user.* types. Unexported auth.refreshRequest replaced
with a local testRefreshRequest struct in the integration test.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Add google/wire; generate wire_gen.go from wire.go injector
- Move all constructor wiring out of main.go into providers.go / wire.go
- Export recognition.IngredientRepository (was unexported, blocked Wire binding)
- Delete units/cuisine/tag registry.go files (global state + unused NameFor helpers)
- Replace List handlers with NewListHandler(pool) using COALESCE SQL queries
- Remove units/cuisine/tag LoadFromDB from server startup; locale.LoadFromDB kept
(locale.Supported is used by language middleware on every request)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Add units + unit_translations tables with FK constraints on products and ingredient_mappings
- Normalize products.unit from Russian strings (г, кг) to English codes (g, kg)
- Load units at startup (in-memory registry) and serve via GET /units (language-aware)
- Replace hardcoded _units lists and _mapUnit() functions in Flutter with unitsProvider FutureProvider
- Re-fetches automatically when language changes
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- migration 013: create languages table (code PK, native_name, english_name,
is_active, sort_order) with all 12 existing languages seeded
- locale: add Language struct, Languages []Language, LoadFromDB() — queries
languages table at startup and populates both Supported map and Languages
slice; existing Parse/FromContext/FromRequest unchanged
- main.go: call locale.LoadFromDB after pool is ready
- gemini/recipe.go: remove hardcoded langNames map, use locale.Languages
linear lookup for English name in prompt
- language/handler.go: new package with GET /languages handler returning
active languages list (no auth required)
- server.go: register GET /languages as public route
- Flutter: add LanguageRepository + languageRepositoryProvider that fetches
/languages from backend
- language_provider.dart: replace const supportedLanguages map with
supportedLanguagesProvider (FutureProvider) backed by LanguageRepository
- profile_provider.dart: remove supportedLanguages.containsKey validation —
backend is source of truth; sync any non-empty language from preferences
- profile_screen.dart: use supportedLanguagesProvider for display name and
dropdown (async with loading/error states)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Store date_of_birth (DATE) instead of a static age integer so that age
is always computed dynamically from the stored date of birth.
- Migration 011: adds date_of_birth, backfills from age, drops age
- AgeFromDOB helper computes current age from YYYY-MM-DD string
- User model, repository SQL, and service validation updated
- Flutter: User.age becomes a computed getter; profile edit screen
uses a date picker bounded to [today-120y, today-10y]
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Add internal/locale package: Parse(Accept-Language), FromContext/WithLang helpers, 12 supported languages
- Add Language middleware that reads Accept-Language header and stores lang in context
- Register Language middleware globally in server router (after CORS)
Database migrations:
- 009: create recipe_translations, saved_recipe_translations, ingredient_translations tables; migrate existing _ru data
- 010: drop legacy _ru columns (title_ru, description_ru, canonical_name_ru); update FTS index
Models: remove all _ru fields (TitleRu, DescriptionRu, NameRu, UnitRu, CanonicalNameRu)
Repositories:
- recipe: Upsert drops _ru params; GetByID does LEFT JOIN COALESCE on recipe_translations; ListMissingTranslation(lang); UpsertTranslation
- ingredient: same pattern with ingredient_translations; Search now queries translated names/aliases
- savedrecipe: List/GetByID LEFT JOIN COALESCE on saved_recipe_translations; UpsertTranslation
Gemini:
- RecipeRequest/MenuRequest gain Lang field
- buildRecipePrompt rewritten in English with target-language content instruction; image_query always in English
- GenerateMenu propagates Lang to GenerateRecipes
Handlers:
- recommendation/menu: pass locale.FromContext(ctx) as Lang
- recognition: saveClassification stores Russian translation via UpsertTranslation instead of _ru column
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Define uuid_generate_v7() in the first migration and switch all table
primary key defaults to it. Remove the uuid-ossp extension dependency.
Update refresh token and request ID generation in Go code to use
uuid.NewV7() from the existing google/uuid v1.6.0 library.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- api_client.dart: connectTimeout 10s → 60s — Flutter was cancelling
requests to /recommendations after 10s while the server waited for
OpenAI, causing 'context canceled' on the server side
- product/repository.go ListForPrompt: expires_at is computed via
(added_at + storage_days * INTERVAL '1 day'), not a stored column;
wrap in CTE to reference it by alias in SELECT/ORDER BY
- home/handler.go getExpiringSoon: same fix — use CTE to compute
expires_at before filtering/ordering by it
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Backend:
- internal/home: GET /home/summary endpoint
- Today's meal plan from menu_plans/menu_items
- Logged calories sum from meal_diary
- Daily goal from user profile (default 2000)
- Expiring products within 3 days
- Last 3 saved recommendations (no AI call on home load)
- Wire homeHandler in server.go and main.go
Flutter:
- shared/models/home_summary.dart: HomeSummary, TodaySummary,
TodayMealPlan, ExpiringSoon, HomeRecipe
- features/home/home_service.dart + home_provider.dart
- features/home/home_screen.dart: greeting, calorie progress bar,
today's meals card, expiring banner, quick actions row,
recommendations horizontal list
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
pgx v5 cannot scan a PostgreSQL DATE column directly into a Go string.
The WHERE clause already used week_start::text but the SELECT did not,
causing GetByWeek to return a scan error that the GenerateMenu handler
swallowed without logging (just returned 500).
- repository.go: SELECT mp.week_start::text instead of mp.week_start
- handler.go: add slog.Error before the silent 500 branch
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Requesting 21 full recipes in one prompt exceeds the token budget and
returns 403 Forbidden. Replace the single-call approach with three
concurrent GenerateRecipes calls (breakfast ×7, lunch ×7, dinner ×7),
then assemble the 7-day plan from the results.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Replace decommissioned llama-3.2-11b-vision-preview with
meta-llama/llama-4-scout-17b-16e-instruct (Groq deprecation)
- Use XFile.readAsBytes() instead of File(path).readAsBytes() so
Android content URIs (from gallery picks) are read correctly
- Add maxWidth/maxHeight constraints to image picker calls to reduce
payload size
- Increase receiveTimeout from 30s to 120s to accommodate slow vision AI
- Log recognition errors via debugPrint instead of swallowing them
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
TIMESTAMPTZ + INTERVAL is STABLE (depends on timezone), not IMMUTABLE,
so PostgreSQL rejects it in GENERATED ALWAYS AS STORED columns.
Fix: remove generated column and compute expires_at inline in each query
as (added_at + storage_days * INTERVAL '1 day').
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Backend (Go):
- Project structure with chi router, pgxpool, goose migrations
- JWT auth (access/refresh tokens) with Firebase token verification
- NoopTokenVerifier for local dev without Firebase credentials
- PostgreSQL user repository with atomic profile updates (transactions)
- Mifflin-St Jeor calorie calculation based on profile data
- REST API: POST /auth/login, /auth/refresh, /auth/logout, GET/PUT /profile, GET /health
- Middleware: auth, CORS (localhost wildcard), logging, recovery, request_id
- Unit tests (51 passing) and integration tests (testcontainers)
- Docker Compose setup with postgres healthcheck and graceful shutdown
Flutter client:
- Riverpod state management with GoRouter navigation
- Firebase Auth (email/password + Google sign-in with web popup support)
- Platform-aware API URLs (web/Android/iOS)
- Dio HTTP client with JWT auth interceptor and concurrent refresh handling
- Secure token storage
- Screens: Login, Register, Home (tabs: Menu, Recipes, Products, Profile)
- Unit tests (17 passing)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>