Self-hosted fitness tracker. Log workouts, track nutrition, and monitor progress. Docker deployment, mobile-friendly.
docs: Move planning documents to docs folder and add gitignore
Cawlumm1aa138c853f2
diff --git a/.gitignore b/.gitignorenew file mode 100644index 0000000..967047c--- /dev/null+++ b/.gitignore@@ -0,0 +1,48 @@+# Environment variables+.env+.env.local+.env.*.local++# Dependencies+node_modules/+go.sum++# Build artifacts+dist/+build/+*.exe+*.dll+*.so+*.dylib+lyfter-api++# IDE+.idea/+.vscode/+*.swp+*.swo+*~+.DS_Store++# Testing+coverage/+*.test++# Logs+logs/+*.log+npm-debug.log*++# Data+data/+*.db+*.sqlite++# OS+Thumbs.db+.DS_Store++# Temporary files+tmp/+temp/+*.tmpdiff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdnew file mode 100644index 0000000..ca427cc--- /dev/null+++ b/docs/ARCHITECTURE.md@@ -0,0 +1,303 @@+# Lyfter Architecture++## System Overview++```+┌─────────────────────────────────────────────────────────┐+│ USER'S SERVER │+├─────────────────────────────────────────────────────────┤+│ │+│ ┌──────────────┐ ┌──────────────┐ │+│ │ Mobile App │ │ Web Browser │ │+│ │ (React Native│───▶│ (React) │ │+│ │ /Flutter) │ └──────────────┘ │+│ └──────────────┘ │ │+│ │ │ │+│ └────────┬───────────┘ │+│ │ │+│ ┌────────▼─────────┐ │+│ │ REST API │ │+│ │ (Express/Go) │ │+│ └────────┬─────────┘ │+│ │ │+│ ┌────────▼─────────┐ │+│ │ Database │ │+│ │ SQLite (default)│ │+│ │ or PostgreSQL │ │+│ └──────────────────┘ │+│ │+└─────────────────────────────────────────────────────────┘++External (Optional):+- USDA Food Database / Open Food Facts API (read-only)+```++## Backend Architecture++### Go/Gin Stack+```+Backend Structure:+├── main.go # Entry point+├── config/+│ └── config.go # Configuration, env loading+├── routes/+│ ├── auth.go # Auth endpoints+│ ├── workouts.go # Workout endpoints+│ ├── food.go # Food logging endpoints+│ └── weight.go # Weight tracking endpoints+├── controllers/+│ ├── auth.go # Business logic+│ ├── workouts.go+│ ├── food.go+│ └── weight.go+├── models/+│ └── models.go # Data structures+├── middleware/+│ ├── auth.go # JWT verification+│ └── error.go # Error handling+├── db/+│ ├── sqlite.go # SQLite connection+│ ├── postgres.go # PostgreSQL connection+│ └── migrations.go # Schema migrations+├── services/+│ ├── auth.go # Auth service+│ └── food.go # External API calls+├── utils/+│ ├── jwt.go # JWT utilities+│ ├── password.go # Password hashing+│ └── response.go # JSON response helpers+├── tests/+├── go.mod+├── go.sum+└── Dockerfile++Tech Stack:+- Gin (REST framework)+- sqlite3 library (database)+- golang-jwt (JWT auth)+- bcrypt (password hashing)+- godotenv (env loading)+- http.Client (external APIs)+```++### Database Layer+```+Default SQLite Config:+- File: lyfter.db (auto-created)+- Location: ./data/lyfter.db (mounted volume)+- No external dependencies+- Automatic backups via Docker volume++PostgreSQL Option:+- Via docker-compose.yml override+- Connection string from env var+- Same schema, database layer abstraction+- Better for multiple instances+```++## Frontend Architecture++### Mobile (React Native/Expo)+```+Mobile Structure:+├── src/+│ ├── screens/ # Screen components+│ ├── components/ # Reusable UI components+│ ├── navigation/ # React Navigation setup+│ ├── services/ # API client+│ ├── stores/ # State management (Zustand)+│ ├── types/ # TypeScript types+│ ├── utils/ # Helpers+│ └── App.tsx+├── app.json+└── package.json++Key Libraries:+- React Native / Expo+- React Navigation (bottom tabs + stack nav)+- NativeBase (UI components)+- Zustand (state management)+- axios (HTTP client)+- react-query (data fetching/caching)+```++### Web (React)+```+Web Structure:+├── src/+│ ├── pages/ # Page components+│ ├── components/ # Reusable components+│ ├── layout/ # Layout wrappers+│ ├── services/ # API client+│ ├── stores/ # State management+│ ├── types/ # TypeScript types+│ ├── hooks/ # Custom hooks+│ ├── utils/ # Helpers+│ ├── App.tsx+│ └── index.css # Tailwind imports+├── tailwind.config.js+├── vite.config.ts+└── package.json++Key Libraries:+- React 18++- Vite (build tool)+- React Router (navigation)+- TypeScript+- Tailwind CSS (styling)+- Zustand (state management)+- axios (HTTP client)+- react-query (data fetching)+- Chart.js / Recharts (analytics)+```++## Deployment++### Docker Compose (MVP)+```yaml+services:+ backend:+ build: ./backend+ ports: [3000:3000]+ volumes:+ - ./data:/app/data+ - ./logs:/app/logs+ environment:+ - DB_TYPE=sqlite+ - DB_PATH=/app/data/lyfter.db++ web:+ build: ./web+ ports: [5173:5173]+ environment:+ - VITE_API_URL=http://localhost:3000++volumes:+ data:+```++### With PostgreSQL Option+```yaml+# docker-compose.prod.yml+services:+ db:+ image: postgres:15+ volumes:+ - pgdata:/var/lib/postgresql/data+ environment:+ - POSTGRES_DB=lyfter+ - POSTGRES_PASSWORD=<password>++ backend:+ environment:+ - DB_TYPE=postgres+ - DB_HOST=db+ - DB_NAME=lyfter+ - DB_PASSWORD=<password>++volumes:+ pgdata:+```++## API Authentication Flow++```+1. User Registration+ POST /api/auth/register+ { email, password }+ ↓+ Backend: Hash password, create user++2. Login+ POST /api/auth/login+ { email, password }+ ↓+ Backend: Verify, create JWT token+ Response: { accessToken, refreshToken }++3. Authenticated Requests+ GET /api/workouts+ Header: Authorization: Bearer <accessToken>+ ↓+ Backend: Verify JWT, process request++4. Token Refresh+ POST /api/auth/refresh+ { refreshToken }+ ↓+ New accessToken issued+```++## Data Flow Examples++### Log Workout+```+Mobile/Web UI+ ↓+POST /api/workouts+{+ date: "2026-04-18",+ exercises: [+ {+ exerciseId: 1,+ sets: [+ { reps: 8, weight: 275 },+ { reps: 8, weight: 275 },+ { reps: 8, weight: 275 },+ { reps: 8, weight: 275 }+ ]+ }+ ]+}+ ↓+Backend: Validate, insert into DB+ ↓+Response: 201 Created { workoutId, ... }+ ↓+UI: Update local state, refresh workout list+```++### Fetch Weight Trend+```+Mobile/Web UI+ ↓+GET /api/weight?startDate=2026-03-18&endDate=2026-04-18+ ↓+Backend: Query SQLite/PostgreSQL+ ↓+Response: [+ { date: "2026-03-18", value: 188.5 },+ { date: "2026-03-19", value: 188.2 },+ ...+ { date: "2026-04-18", value: 185.0 }+]+ ↓+UI: Plot on chart component+```++## Security Considerations (MVP)++- **Password**: bcryptjs hashing (10 rounds)+- **Auth**: JWT with 1-hour expiry + refresh tokens+- **API**: All endpoints require valid JWT+- **HTTPS**: Users should deploy behind reverse proxy (nginx)+- **CORS**: Configured for localhost + user's domain+- **Input Validation**: Server-side validation on all inputs+- **Database**: User data scoped to authenticated user++## Performance Targets++- API response: <100ms (local)+- Mobile app startup: <2s+- Data sync: On-demand (no background sync in MVP)+- Database queries: Indexed on user_id, date+- Caching: Client-side state management with react-query++## Future Improvements++- Background sync (Expo TaskManager)+- Offline-first with local DB (SQLite for React Native)+- Image storage (meal photos)+- Advanced caching strategies+- Performance monitoring+- Database backups/restore UIdiff --git a/docs/CLAUDE.md b/docs/CLAUDE.mdnew file mode 100644index 0000000..29165a1--- /dev/null+++ b/docs/CLAUDE.md@@ -0,0 +1,326 @@+# Lyfter - Project Context & Guidelines++## Project Overview++**Lyfter** is a self-hosted workout tracking app similar to MacroFactor. Users run both UI and backend on their own servers for complete data privacy and control. The app is designed as a mobile-first experience (iOS/Android app store) with a web interface as a secondary option.++### Key Principles+1. **Self-Hosted First**: SQLite default, zero external cloud dependencies+2. **Privacy**: User data stays on user's server+3. **Developer-Friendly**: Easy to deploy, well-documented+4. **MVP Focus**: Build features in order of user value, not technical complexity++---++## Tech Stack (Locked)++```+Frontend:+- Mobile: React Native (Expo) → iOS/Android app stores+- Web: React + TypeScript + Tailwind CSS+- State: Zustand (minimal, flexible)++Backend:+- Runtime: Go with Gin web framework+- Database: SQLite (default), PostgreSQL (optional via docker-compose)+- Auth: JWT tokens+- API: REST (not GraphQL)++Deployment:+- Docker + Docker Compose (single compose file, users add volumes)+- Default: SQLite in ./data volume+- Optional: PostgreSQL via docker-compose.prod.yml+```++**Why this stack?** See TECH_STACK_DECISIONS.md for detailed rationale.++---++## Project Structure++```+lyftr/+├── backend/ # Go/Gin API service+│ ├── main.go # Entry point+│ ├── routes/+│ │ ├── auth.go # Auth endpoints+│ │ ├── workouts.go # Workout endpoints+│ │ ├── food.go # Food endpoints+│ │ └── weight.go # Weight endpoints+│ ├── controllers/ # Business logic+│ ├── models/ # Data structures+│ ├── middleware/ # Auth, validation, errors+│ ├── services/ # External APIs, helpers+│ ├── db/+│ │ ├── sqlite.go # SQLite config+│ │ ├── postgres.go # PostgreSQL config+│ │ └── migrations.go # Schema migrations+│ ├── go.mod+│ ├── go.sum+│ └── Dockerfile+│+├── web/ # React web app+│ ├── src/+│ │ ├── pages/+│ │ ├── components/+│ │ ├── services/ # API client+│ │ ├── stores/ # Zustand stores+│ │ └── App.tsx+│ ├── tailwind.config.js+│ └── package.json+│+├── mobile/ # React Native (Expo)+│ ├── src/+│ │ ├── screens/+│ │ ├── components/+│ │ ├── navigation/+│ │ ├── services/ # API client+│ │ ├── stores/ # Zustand stores+│ │ └── App.tsx+│ └── package.json+│+├── docs/ # Deployment guides, API docs+├── docker-compose.yml # Dev environment + SQLite+├── docker-compose.prod.yml # PostgreSQL option+├── README.md # Project overview+├── CLAUDE.md # This file+├── MVP_SPEC.md # Feature requirements+├── ARCHITECTURE.md # System design+├── WIREFRAMES.md # UI mockups+└── TECH_STACK_DECISIONS.md+```++---++## MVP Phase (What We're Building First)++See MVP_SPEC.md for complete list. Priority features:++1. **Authentication**: Register/login with email + password+2. **Workout Logging**: Select exercise, input sets/reps/weight+3. **Weight Tracking**: Daily weight entries + trend chart+4. **Macro Tracking**: Food search + logging + daily summary+5. **Dashboard**: Quick overview of today's stats+6. **Deployment**: Docker Compose with SQLite++---++## Development Guidelines++### Code Style+- **Backend**: Go with standard naming conventions (camelCase, exported funcs PascalCase)+- **Frontend**: TypeScript (web & mobile)+- **Naming**: camelCase for variables/functions, PascalCase for types/classes/components+- **Comments**: Only for WHY, not WHAT (good naming explains what)+- **Error handling**: Validate at API boundaries, trust internal code++### Database+- SQLite by default (auto-created at `./data/lyfter.db`)+- All queries scoped to authenticated user (user_id required)+- Indexes on: user_id, date (for range queries)+- Migrations tracked in ./backend/src/db/migrations/++### API Design+- RESTful endpoints (GET, POST, PUT, DELETE)+- JSON request/response bodies+- HTTP status codes (200, 201, 400, 401, 404, 500)+- All endpoints require Authorization header (JWT token)+- Base path: `/api/`++Example:+```+POST /api/auth/login+PUT /api/workouts/:id+GET /api/weight?startDate=2026-04-18&endDate=2026-04-25+DELETE /api/food-logs/:id+```++### Frontend+- Components: Small, single-responsibility+- Props over context (unless truly global like auth)+- Zustand for global state (auth, user settings)+- React Query for server state (workouts, food logs)+- No commented-out code, just delete it++### Mobile (Expo)+- Shared code with web (types, API client, business logic)+- NativeBase for UI components (Tailwind-compatible)+- React Navigation for mobile nav patterns (bottom tabs)+- App Store: TestFlight → release to both stores simultaneously++### Testing+- **Backend**: Go's testing package + table-driven tests+- **Frontend**: Jest for unit tests, React Testing Library for components+- **API**: Go's net/http/httptest for integration tests+- Target: 70%+ coverage for critical paths++---++## Architecture Decision Log++### Database: SQLite Default + PostgreSQL Optional ✅+- **Decision**: Ship with SQLite by default (zero config), provide docker-compose.prod.yml for PostgreSQL+- **Rationale**: Self-hosted users want minimal dependencies; aligns with Vaultwarden model+- **Impact**: Backend must use abstracted database layer (not SQL-specific)++### Authentication: JWT Tokens ✅+- **Decision**: JWT with 1-hour expiry + refresh tokens in HTTP-only cookies+- **Rationale**: Stateless auth scales better for distributed deployments+- **Impact**: Token refresh endpoint required; frontend handles token refresh logic++### API: REST Not GraphQL ✅+- **Decision**: RESTful API for MVP+- **Rationale**: Simpler to implement and cache; MVP doesn't need query flexibility+- **Revisit**: Add GraphQL later if query complexity grows++### Frontend State: Zustand + React Query ✅+- **Decision**: Zustand for client state (auth, settings), React Query for server state (workouts, food)+- **Rationale**: Simpler than Redux; separates concerns+- **Impact**: Less boilerplate, easier to reason about data flow++---++## Before Starting Development++- [ ] Create backend directory structure & go.mod+- [ ] Initialize Go project with Gin dependency+- [ ] Create web directory structure & package.json+- [ ] Create mobile directory structure & package.json+- [ ] Set up Docker Compose (dev environment)+- [ ] Create database schema for MVP tables+- [ ] Set up GitHub Actions for linting/testing (golangci-lint, npm lint)+- [ ] Create CONTRIBUTING.md for future collaborators++---++## Common Tasks & Commands++### Local Development+```bash+# Start everything+docker-compose up -d++# Backend logs+docker-compose logs -f backend++# Reset database+rm data/lyfter.db+docker-compose restart backend++# Run backend tests+cd backend && go test ./...++# Run backend in dev mode+cd backend && go run main.go++# Run web app locally+cd web && npm run dev++# Run mobile locally+cd mobile && npm start+```++### Database+```bash+# Migrations are handled in code (db/migrations.go)+# Run on startup automatically++# Reset database (careful!)+rm data/lyfter.db && docker-compose restart backend++# View database with sqlite3+sqlite3 data/lyfter.db ".schema"+```++### Deployment+```bash+# Build Go binary+cd backend && go build -o lyfter-api++# Build Docker images+docker-compose build++# For PostgreSQL users+docker-compose -f docker-compose.prod.yml up -d++# Users can also run standalone binary+./lyfter-api --port=3000 --db-type=sqlite+```++---++## What Success Looks Like++MVP complete when:+1. ✅ User can register/login+2. ✅ User can log workouts (exercise, sets, reps, weight)+3. ✅ User can track daily weight with trend chart+4. ✅ User can log meals and see macro totals+5. ✅ Dashboard shows today's summary+6. ✅ Mobile app available on TestFlight+7. ✅ Web app works at http://localhost:5173+8. ✅ Docker Compose setup works for self-hosting+9. ✅ All code tested, no console errors+10. ✅ Deployment guide written++---++## When to Revisit Tech Decisions++- **GraphQL instead of REST**: If we need to fetch related data at different depths+- **PostgreSQL instead of SQLite**: If supporting multi-user per instance+- **Flutter instead of React Native**: If performance issues emerge or more native control needed+- **Redux instead of Zustand**: If state becomes unmanageable (unlikely at MVP scale)+- **Rust instead of Go**: Only if Go becomes a bottleneck (unlikely for self-hosted fitness app)++Don't over-engineer. Stay pragmatic. Iterate based on real constraints, not hypotheticals.++---++## Known Limitations (MVP)++- Single user per Lyfter instance (can add multi-user later)+- No image uploads (meal photos, progress pics)+- No offline mode (always online)+- No background sync+- Limited food database (USDA/Open Food Facts read-only)+- No social features (leaderboards, friend tracking)+- No advanced analytics (body measurements, periodization)++These are deliberate scope cuts to ship MVP faster. Add in Phase 2+.++---++## External APIs++**Optional (can add later):**+- USDA FoodData Central (food database)+- Open Food Facts (crowdsourced food database)+- Barcode lookup (EAN/UPC to food)++**Not needed for MVP:**+- Payment processing (no premium tier)+- Email (send notifications later)+- Cloud storage (local storage only)++---++## Deployment Target++**Primary:** Self-hosted Docker on user's server (Raspberry Pi, NAS, VPS, etc.)+**Secondary:** Web browser at their domain (e.g., lyfter.home.local:5173)+**Mobile:** App store (TestFlight for beta, App Store/Play Store for release)++Users should deploy behind reverse proxy (nginx) with SSL certificate.++---++## How to Use This Document++- Reference for architecture decisions+- Onboarding new team members+- When debating "should we add X", check if it's in MVP_SPEC+- When wondering "why did we pick Y", see TECH_STACK_DECISIONS+- Revisit before adding major features (Phase 2+)++Update this file as decisions change. Keep it as the source of truth.diff --git a/docs/GO_BACKEND_GUIDE.md b/docs/GO_BACKEND_GUIDE.mdnew file mode 100644index 0000000..078db13--- /dev/null+++ b/docs/GO_BACKEND_GUIDE.md@@ -0,0 +1,529 @@+# Go Backend Development Guide++Quick reference for building the Lyfter backend in Go.++## Getting Started++### Installation+```bash+# Install Go 1.21+ from https://golang.org/dl++# Verify installation+go version++# Create backend directory+mkdir backend && cd backend++# Initialize Go module+go mod init github.com/Cawlumm/lyfter-backend+```++### Key Dependencies+```bash+# Web framework+go get github.com/gin-gonic/gin++# Database+go get github.com/mattn/go-sqlite3++# PostgreSQL support (optional)+go get github.com/lib/pq++# Password hashing+go get golang.org/x/crypto/bcrypt++# JWT auth+go get github.com/golang-jwt/jwt/v5++# Environment variables+go get github.com/joho/godotenv++# Validation+go get github.com/go-playground/validator/v10+```++## Project Structure++```+backend/+├── main.go # Application entry point+├── config/+│ └── config.go # Load env vars, configuration+├── routes/ # Route handlers+│ ├── auth.go+│ ├── workouts.go+│ ├── food.go+│ └── weight.go+├── controllers/ # Business logic+│ ├── auth.go+│ ├── workouts.go+│ ├── food.go+│ └── weight.go+├── models/ # Data structures+│ └── models.go+├── middleware/ # HTTP middleware+│ ├── auth.go # JWT verification+│ └── error.go # Error handling+├── db/ # Database layer+│ ├── sqlite.go # SQLite initialization+│ ├── postgres.go # PostgreSQL initialization+│ └── migrations.go # Schema setup+├── services/ # External integrations+│ └── food.go # Food database APIs+├── utils/ # Helper functions+│ ├── jwt.go # JWT utilities+│ ├── password.go # Password hashing+│ ├── response.go # JSON response helpers+│ └── errors.go # Custom error types+├── go.mod # Module definition+├── go.sum # Dependency checksums+├── .env.example # Environment template+├── Dockerfile # Docker build+└── docker-compose.yml # (in root)+```++## Basic Example: Creating an Endpoint++### 1. Add to models/models.go+```go+type User struct {+ ID int `json:"id"`+ Email string `json:"email"`+ Password string `json:"-"` // Never expose password+ CreatedAt time.Time `json:"created_at"`+}++type LoginRequest struct {+ Email string `json:"email" binding:"required,email"`+ Password string `json:"password" binding:"required,min=8"`+}++type LoginResponse struct {+ AccessToken string `json:"access_token"`+ RefreshToken string `json:"refresh_token"`+}+```++### 2. Create controller in controllers/auth.go+```go+package controllers++import (+ "net/http"+ "github.com/gin-gonic/gin"+)++func Login(c *gin.Context) {+ var req LoginRequest++ // Bind and validate JSON+ if err := c.ShouldBindJSON(&req); err != nil {+ c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ // Your login logic here+ // Find user, verify password, generate tokens++ c.JSON(http.StatusOK, LoginResponse{+ AccessToken: "token_here",+ RefreshToken: "refresh_here",+ })+}+```++### 3. Register route in routes/auth.go+```go+package routes++import (+ "github.com/gin-gonic/gin"+ "github.com/Cawlumm/lyfter-backend/controllers"+)++func RegisterAuthRoutes(router *gin.Engine) {+ auth := router.Group("/api/auth")+ {+ auth.POST("/login", controllers.Login)+ auth.POST("/register", controllers.Register)+ auth.POST("/refresh", controllers.Refresh)+ }+}+```++### 4. Wire up in main.go+```go+package main++import (+ "github.com/gin-gonic/gin"+ "github.com/Cawlumm/lyfter-backend/routes"+)++func main() {+ router := gin.Default()++ // Register all routes+ routes.RegisterAuthRoutes(router)+ routes.RegisterWorkoutRoutes(router)++ router.Run(":3000")+}+```++## Database Patterns++### Initialize Connection+```go+package db++import (+ "database/sql"+ "os"+ _ "github.com/mattn/go-sqlite3"+)++func InitDB() (*sql.DB, error) {+ dbPath := os.Getenv("DB_PATH")+ if dbPath == "" {+ dbPath = "./data/lyfter.db"+ }++ db, err := sql.Open("sqlite3", dbPath)+ if err != nil {+ return nil, err+ }++ if err := db.Ping(); err != nil {+ return nil, err+ }++ return db, nil+}+```++### Query Pattern (with error handling)+```go+// Get user workouts for date range+const query = `+ SELECT id, date, created_at+ FROM workouts+ WHERE user_id = ? AND date BETWEEN ? AND ?+ ORDER BY date DESC+`++rows, err := db.Query(query, userID, startDate, endDate)+if err != nil {+ return nil, err+}+defer rows.Close()++var workouts []Workout+for rows.Next() {+ var w Workout+ if err := rows.Scan(&w.ID, &w.Date, &w.CreatedAt); err != nil {+ return nil, err+ }+ workouts = append(workouts, w)+}++return workouts, rows.Err()+```++### Prepared Statements (for repeated queries)+```go+// Insert workout+const insertWorkout = `+ INSERT INTO workouts (user_id, date, created_at)+ VALUES (?, ?, ?)+`++stmt, err := db.Prepare(insertWorkout)+if err != nil {+ return 0, err+}+defer stmt.Close()++result, err := stmt.Exec(userID, workout.Date, time.Now())+if err != nil {+ return 0, err+}++id, err := result.LastInsertId()+return id, err+```++## Middleware Pattern++### Authentication Middleware+```go+package middleware++import (+ "net/http"+ "strings"+ "github.com/gin-gonic/gin"+)++func AuthRequired() gin.HandlerFunc {+ return func(c *gin.Context) {+ authHeader := c.GetHeader("Authorization")+ if authHeader == "" {+ c.JSON(http.StatusUnauthorized, gin.H{"error": "missing token"})+ c.Abort()+ return+ }++ // Extract token (format: "Bearer <token>")+ parts := strings.Split(authHeader, " ")+ if len(parts) != 2 || parts[0] != "Bearer" {+ c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid token format"})+ c.Abort()+ return+ }++ token := parts[1]++ // Verify token+ claims, err := VerifyJWT(token)+ if err != nil {+ c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid token"})+ c.Abort()+ return+ }++ // Store user ID in context for later use+ c.Set("user_id", claims.UserID)+ c.Next()+ }+}+```++### Use in Routes+```go+// Protected route+router.GET("/api/workouts", middleware.AuthRequired(), controllers.GetWorkouts)++// Public route (no middleware)+router.POST("/api/auth/login", controllers.Login)+```++## Error Handling++### Define Custom Errors+```go+package utils++type AppError struct {+ Status int+ Message string+ Details string+}++func (e *AppError) Error() string {+ return e.Message+}++func BadRequest(msg, details string) *AppError {+ return &AppError{Status: 400, Message: msg, Details: details}+}++func Unauthorized(msg string) *AppError {+ return &AppError{Status: 401, Message: msg}+}++func NotFound(msg string) *AppError {+ return &AppError{Status: 404, Message: msg}+}++func InternalError(msg string) *AppError {+ return &AppError{Status: 500, Message: msg}+}+```++### Global Error Handler+```go+// In main.go+router.Use(func(c *gin.Context) {+ defer func() {+ if err := recover(); err != nil {+ if appErr, ok := err.(*AppError); ok {+ c.JSON(appErr.Status, gin.H{"error": appErr.Message})+ } else {+ c.JSON(500, gin.H{"error": "internal server error"})+ }+ }+ }()+ c.Next()+})+```++## Testing Pattern++### Unit Test Example+```go+package controllers++import (+ "testing"+ "github.com/stretchr/testify/assert"+)++func TestLogin_ValidCredentials(t *testing.T) {+ // Setup+ email := "[email protected]"+ password := "password123"++ // Execute+ token, err := Login(email, password)++ // Assert+ assert.NoError(t, err)+ assert.NotEmpty(t, token)+}++func TestLogin_InvalidEmail(t *testing.T) {+ token, err := Login("invalid", "password123")+ assert.Error(t, err)+ assert.Empty(t, token)+}+```++### Run Tests+```bash+# Run all tests+go test ./...++# Run with coverage+go test -cover ./...++# Run specific test+go test -run TestLogin ./controllers+```++## Useful Go Commands++```bash+# Format code (automatic)+go fmt ./...++# Lint code (requires golangci-lint)+golangci-lint run++# Build binary+go build -o lyfter-api++# Run directly+go run main.go++# Add dependency+go get github.com/example/package++# Remove unused dependencies+go mod tidy++# View module info+go mod graph+```++## Best Practices++1. **Error handling**: Always check errors, don't ignore them+ ```go+ // Good+ if err != nil {+ return err+ }++ // Bad+ _ = db.Close() // Don't use blank import for errors+ ```++2. **Defer for cleanup**:+ ```go+ rows, err := db.Query(...)+ if err != nil {+ return nil, err+ }+ defer rows.Close() // Always close+ ```++3. **Use interfaces for testing**:+ ```go+ type Database interface {+ GetUser(id int) (*User, error)+ }++ // Can mock this for testing+ ```++4. **Keep functions small**: 10-20 lines is ideal++5. **Use table-driven tests**:+ ```go+ tests := []struct{+ name string+ input string+ want string+ }{+ {"case1", "input1", "want1"},+ {"case2", "input2", "want2"},+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ // test here+ })+ }+ ```++## Environment Variables (.env)++```+# Database+DB_TYPE=sqlite+DB_PATH=./data/lyfter.db++# Or for PostgreSQL:+# DB_TYPE=postgres+# DB_HOST=localhost+# DB_PORT=5432+# DB_NAME=lyfter+# DB_USER=postgres+# DB_PASSWORD=password++# Server+PORT=3000+ENV=development++# JWT+JWT_SECRET=your-secret-key-here-min-32-chars+JWT_EXPIRY=3600++# CORS+CORS_ORIGIN=http://localhost:5173,http://localhost:19006+```++## Common Issues++**Issue**: `package not found`+- **Solution**: Run `go mod tidy` to download dependencies++**Issue**: SQLite: `cannot load library`+- **Solution**: Ensure you have C development tools installed (cgo)++**Issue**: JWT token not working+- **Solution**: Check token format ("Bearer <token>"), expiry time, and secret key match++**Issue**: Database locked+- **Solution**: SQLite has limited concurrency. For development, this is normal. Use PostgreSQL for production if you hit this often.++## Next Steps++1. Start with basic auth (login/register)+2. Set up database migrations+3. Build workout logging endpoints+4. Add weight tracking endpoints+5. Integrate food database API+6. Write tests for critical paths+7. Add Docker supportdiff --git a/docs/MVP_SPEC.md b/docs/MVP_SPEC.mdnew file mode 100644index 0000000..2b24e75--- /dev/null+++ b/docs/MVP_SPEC.md@@ -0,0 +1,154 @@+# Lyfter MVP Specification++## MVP Scope (Phase 1)++### Phase 1A: Core Infrastructure & Authentication+- [ ] Backend API setup (Express/Go)+- [ ] SQLite database schema+- [ ] User registration/login+- [ ] JWT authentication+- [ ] Docker setup for local development+- [ ] Basic API documentation++### Phase 1B: Workout Tracking (Mobile + Web)+- [ ] Exercise database (pre-populated)+- [ ] Log workout UI+ - Select exercise+ - Input sets/reps/weight+ - Notes field+ - Timestamp+- [ ] Workout history view+- [ ] Search/filter workouts+- [ ] Edit/delete workout entries++### Phase 1C: Weight Tracking & Basic Analytics+- [ ] Weight entry logging+- [ ] Weight trend chart (7, 30, 90 day views)+- [ ] Basic statistics (current, avg, min, max)+- [ ] Daily dashboard overview++### Phase 1D: Macro Tracking (Simplified)+- [ ] Food database integration (USDA or Open Food Facts API)+- [ ] Log meal UI+ - Search food+ - Input quantity+ - Quick add favorites+- [ ] Daily macro summary (P/C/F)+- [ ] Daily calorie total++### Phase 1E: Deployment & Documentation+- [ ] Docker Compose for single-instance (SQLite)+- [ ] Deployment guide (self-hosting instructions)+- [ ] API documentation+- [ ] Mobile app build & release process++## Non-MVP Features (Post-MVP)+- Barcode scanning+- Meal plans+- Advanced analytics (body measurements, photos)+- Social features (friend tracking, achievements)+- PostgreSQL support+- Backup/export functionality+- Multiple users per instance+- Advanced macro targets (periodized training phases)++## Data Models++### User+```+- id (PK)+- email (unique)+- password_hash+- created_at+- settings (JSON)+```++### Workout+```+- id (PK)+- user_id (FK)+- date+- created_at+- exercises (JSON array)+```++### WorkoutExercise+```+- id (PK)+- workout_id (FK)+- exercise_id (FK)+- sets (JSON array)+- notes+```++### Exercise+```+- id (PK)+- name+- category (push, pull, legs, cardio, other)+- equipment+- muscle_groups (JSON)+```++### FoodLog+```+- id (PK)+- user_id (FK)+- date+- food_name+- calories+- protein+- carbs+- fat+- quantity+- unit+```++### Weight+```+- id (PK)+- user_id (FK)+- date+- value (lbs/kg)+```++## API Endpoints (MVP)++### Auth+- POST /api/auth/register+- POST /api/auth/login+- POST /api/auth/refresh+- POST /api/auth/logout++### Workouts+- GET /api/workouts (paginated, filtered by date range)+- POST /api/workouts+- PUT /api/workouts/:id+- DELETE /api/workouts/:id+- GET /api/exercises (pre-seeded database)++### Food Logs+- GET /api/food-logs (by date)+- POST /api/food-logs+- PUT /api/food-logs/:id+- DELETE /api/food-logs/:id+- GET /api/food-search (query food database)++### Weight+- GET /api/weight (date range)+- POST /api/weight+- PUT /api/weight/:id+- DELETE /api/weight/:id++### User+- GET /api/user (profile)+- PUT /api/user (settings)+- GET /api/user/stats (quick stats)++## UI/UX Priorities++1. **Speed**: Fast local-first, minimal loading times+2. **Simplicity**: Clean, distraction-free interface+3. **Accessibility**: Easy to navigate, readable text+4. **Data visualization**: Charts that show trends at a glance+5. **Quick entry**: Minimize taps/clicks to log datadiff --git a/docs/README.md b/docs/README.mdnew file mode 100644index 0000000..6f6c0c3--- /dev/null+++ b/docs/README.md@@ -0,0 +1,77 @@+# Lyfter - Self-Hosted Workout Tracking App++A privacy-first, self-hosted workout tracking application similar to MacroFactor. Users can run both the UI and backend on their own servers to maintain complete control over their fitness and nutrition data.++## Vision++- **Self-Hosted**: Full control over infrastructure and data+- **Multi-Platform**: Native app (iOS/Android) + Web interface+- **Privacy-Focused**: Your data, your server, zero cloud dependency+- **Developer-Friendly**: Easy to deploy, well-documented APIs++## Key Features (MVP)++1. **Workout Logging**+ - Exercise tracking with sets/reps/weight+ - Pre-built exercise database+ - Custom exercises++2. **Macro/Calorie Tracking**+ - Food database integration+ - Barcode scanning+ - Quick log shortcuts++3. **Progress Analytics**+ - Weight trends+ - Volume progression+ - Macro adherence charts++4. **User Management**+ - Single or multi-user support per instance+ - Basic auth++## Tech Stack Recommendation++### Frontend+- **Mobile**: React Native (Expo) or Flutter+- **Web**: React + TypeScript+- **State Management**: Zustand or Redux+- **UI Framework**: NativeBase (mobile) + Tailwind (web)++### Backend+- **Runtime**: Go (Gin web framework)+- **Database**:+ - **Default**: SQLite (zero config, perfect for single users)+ - **Optional**: PostgreSQL via Docker (for advanced deployments)+- **Auth**: JWT tokens+- **API**: REST API (GraphQL optional)++### Infrastructure+- **Deployment**: Docker + Docker Compose+- **File Storage**: Local filesystem or MinIO (S3-compatible)++## Database Strategy++**SQLite (Default)**+- Zero external dependencies+- Perfect for personal/single-user instances+- Minimal system requirements+- File-based storage++**PostgreSQL (Optional)**+- Via Docker Compose configuration+- For users wanting multi-instance deployments+- Better concurrency handling+- Advanced features like full-text search++## Project Structure++```+lyftr/+├── backend/ # REST API service+├── web/ # React web app+├── mobile/ # React Native/Flutter app+├── docs/ # Documentation & deployment guides+├── docker-compose.yml+└── README.md+```diff --git a/docs/TECH_STACK_DECISIONS.md b/docs/TECH_STACK_DECISIONS.mdnew file mode 100644index 0000000..c1d2c18--- /dev/null+++ b/docs/TECH_STACK_DECISIONS.md@@ -0,0 +1,292 @@+# Lyfter Tech Stack Decisions++## Summary+- **Mobile**: React Native (Expo) or Flutter+- **Web**: React + TypeScript + Tailwind+- **Backend**: Node.js/Express (or Go/Gin alternative)+- **Database**: SQLite (default) + PostgreSQL (optional)+- **Deployment**: Docker + Docker Compose++---++## Backend Decision: Go/Gin ✅ (Primary Choice)++### Go/Gin ✅++**Pros:**+- Super fast execution (~1000x faster than Node.js for I/O)+- Low memory footprint (~10MB vs 100MB+ for Node)+- Single binary deployment (no runtime needed)+- Great for concurrent connections+- Type-safe compilation catches errors at build time+- Excellent standard library (net/http, json, crypto)+- Simple, clean syntax (easier to learn than Rust)+- Perfect for self-hosted deployments++**Cons:**+- Steeper learning curve than JavaScript+- Slightly slower initial development (but not by much)+- Fewer third-party libraries vs Node.js (but all essentials exist)+- Requires compilation step++**Why we're using it:**+- MVP will ship as single binary (easy distribution)+- Self-hosted users get best performance (important for Raspberry Pi, NAS)+- Excellent for learning systems programming+- Matches deployment needs (Vaultwarden also uses Go)+- Built-in concurrency (goroutines) handles multiple users well+- Fast startup time++---++## Database: SQLite vs PostgreSQL++### SQLite (Default) ✅++**Pros:**+- Zero configuration+- Single file database+- Perfect for self-hosted single users+- No external dependencies+- Tiny deployment footprint+- Easy backups (just copy the file)+- Automatic with Docker volumes++**Cons:**+- Limited concurrency+- Not ideal for high-traffic+- Single machine only (no clustering)++**Why default:**+- Target user is self-hosting+- Single user per instance+- Zero operational overhead+- Vaultwarden model (same approach)++### PostgreSQL (Optional)++**Pros:**+- Better concurrency handling+- Better for multiple instances+- More advanced features+- Can scale horizontally+- Full-text search support++**Cons:**+- Requires additional infrastructure+- More operational complexity+- Higher resource requirements++**When to offer:**+- Via docker-compose.prod.yml+- For users with multiple instances+- For advanced deployments++---++## Frontend: React Native vs Flutter++### React Native/Expo ✅ (Primary Choice)++**Pros:**+- Share code between iOS & Android+- Web app also React (shared components/logic)+- Large ecosystem+- Hot reload for fast development+- Can publish to App Store + Google Play with Expo+- JavaScript developers can transition easily++**Cons:**+- Performance not native-level+- Slightly larger app size+- Bridge overhead++**Why Expo:**+- Easier app distribution+- No need to run iOS/Android build systems locally+- OTA updates capability+- Great for MVP++### Flutter (Alternative)++**Pros:**+- Better performance+- Beautiful UI framework+- Single codebase for everything+- Growing community++**Cons:**+- Different language (Dart)+- Smaller ecosystem+- Web story less mature++**Decision:**+Start with React Native/Expo because:+- Align with web React codebase+- Faster prototyping+- Better tooling maturity for MVP+- Can switch to Flutter later if needed++---++## Web Framework: React vs Vue vs Svelte++### React ✅++**Pros:**+- Largest ecosystem+- Shared components with mobile+- TypeScript support+- Best performance for data-heavy apps+- Easy to hire for+- Great DevTools++**Cons:**+- Slightly more boilerplate than Vue/Svelte+- Larger bundle size++**Why React:**+- Aligns with React Native mobile+- Share types and data models+- Best for analytics dashboards (charts, tables)+- Most ecosystem maturity++---++## CSS: Tailwind vs Styled Components vs CSS Modules++### Tailwind CSS ✅++**Pros:**+- Utility-first (fast styling)+- Small final bundle+- Design system consistency+- Works great with Expo (via NativeBase)+- Great for rapid prototyping++**Why Tailwind:**+- Same tooling for web + mobile (NativeBase for Expo)+- Fast MVP development+- Design consistency across platforms+- Easy theme customization++---++## State Management: Zustand vs Redux vs Context++### Zustand ✅++**Pros:**+- Minimal boilerplate+- Great TypeScript support+- Tiny bundle size (~2KB)+- Easy to learn+- No Provider hell+- Excellent devtools++**Cons:**+- Less community plugins than Redux+- Newer library++**Why Zustand:**+- MVP doesn't need Redux complexity+- Much simpler than Context API+- Great for small-to-medium apps+- Easy to refactor later if needed++---++## API Communication: REST vs GraphQL++### REST ✅++**Pros:**+- Simpler to implement+- Better caching (HTTP caching)+- Easier to understand+- Perfect for MVP+- Great tooling++**Cons:**+- Over/under fetching possible+- Multiple endpoints++**Why REST:**+- MVP simplicity+- Self-hosted endpoints don't need complex queries+- HTTP caching helps with slow connections+- Easier to document (OpenAPI)++**Future:** GraphQL later if queries become complex++---++## Tooling++### Build Tools+- **Web**: Vite (fast, modern)+- **Mobile**: Metro (React Native default)+- **Backend**: Node.js (no build needed, or swc for faster TS)++### Testing+- **Jest** (unit tests)+- **React Testing Library** (component tests)+- **Supertest** (API tests)++### Version Control / CI-CD+- **Git** (obvious)+- **GitHub Actions** (auto-test on PR)+- **Semantic Versioning** for releases++### Documentation+- **OpenAPI/Swagger** for API docs+- **Markdown** for guides+- **Storybook** for component library (later)++---++## Hosting & Deployment++### Development+- Docker Compose (local SQLite)+- Hot reload enabled+- Shared volumes++### Production (User's Server)+- Docker Compose file provided+- SQLite (default) or PostgreSQL (optional)+- Nginx reverse proxy (recommended)+- Environment variable configuration++### App Distribution+- **iOS**: TestFlight → App Store+- **Android**: Google Play+- **Web**: GitHub Pages or self-hosted++---++## Implementation Order++1. **Phase 1**: Backend (Go/Gin) + SQLite+2. **Phase 2**: Web (React + Tailwind)+3. **Phase 3**: Mobile (React Native/Expo)+4. **Phase 4**: Polish, testing, documentation+5. **Phase 5**: PostgreSQL support (optional)++---++## Why This Stack?++The combination allows:+- **Fast MVP development** (Node + React)+- **Single codebase** (React + React Native)+- **Low ops overhead** (Docker + SQLite)+- **Easy self-hosting** (similar to Vaultwarden)+- **Future flexibility** (can replace any layer)+- **Developer happiness** (JavaScript everywhere)++This is the Vaultwarden model:+- Self-hosted option+- Minimal dependencies+- Clear separation of concerns+- Easy to deploy and maintaindiff --git a/docs/WIREFRAMES.md b/docs/WIREFRAMES.mdnew file mode 100644index 0000000..cfc4633--- /dev/null+++ b/docs/WIREFRAMES.md@@ -0,0 +1,261 @@+# Lyfter UI Wireframes & Mockups++## Mobile App Screens++### 1. Login/Register Screen+```+┌─────────────────────┐+│ │+│ LYFTER LOGO │+│ │+├─────────────────────┤+│ │+│ [Email Input] │+│ [Password Input] │+│ [Login Button] │+│ │+│ New user? │+│ [Sign Up Link] │+│ │+└─────────────────────┘+```++### 2. Home/Dashboard Screen+```+┌─────────────────────┐+│ TODAY │+│ April 18, 2026 │+├─────────────────────┤+│ │+│ [Weight: 185 lbs] │+│ [Trend: ↓ -2 lbs] │+│ │+│ Macros Today: │+│ ┌─────────────────┐ │+│ │ P: 140g C: 180g│ │+│ │ F: 60g Cal: 1850+│ │ Target: 2000 │ │+│ └─────────────────┘ │+│ │+│ [Quick Log Workout] │+│ [Quick Log Meal] │+│ [Add Weight] │+│ │+├─────────────────────┤+│ Recent Workouts │+│ • Push Day - 2h ago │+│ • Cardio - 1d ago │+│ │+└─────────────────────┘+```++### 3. Log Workout Screen+```+┌─────────────────────┐+│ NEW WORKOUT │ [X]+├─────────────────────┤+│ Workout Type │+│ [Select...v] │+│ │+│ [+ Add Exercise] │+│ │+│ Push Day │+│ ┌─────────────────┐ │+│ │ Bench Press │ │+│ │ 4 x 8 @ 275 lbs │ │+│ │ [Edit] [Remove] │ │+│ └─────────────────┘ │+│ ┌─────────────────┐ │+│ │ Incline Dumbbell│ │+│ │ 3 x 10 @ 85 lbs │ │+│ │ [Edit] [Remove] │ │+│ └─────────────────┘ │+│ │+│ Notes: [Text...] │+│ │+│ [Cancel] [Save] │+└─────────────────────┘+```++### 4. Exercise Selection Screen+```+┌─────────────────────┐+│ SELECT EXERCISE │ [X]+├─────────────────────┤+│ [Search...search] │+│ │+│ Upper Body │+│ • Bench Press │+│ • Incline Press │+│ • Dumbbell Press │+│ • Barbell Row │+│ • Lat Pulldown │+│ │+│ Lower Body │+│ • Barbell Squat │+│ • Leg Press │+│ • Leg Curl │+│ │+│ Custom │+│ • [Add New+] │+│ │+└─────────────────────┘+```++### 5. Weight Tracking Screen+```+┌─────────────────────┐+│ WEIGHT │+├─────────────────────┤+│ │+│ [Chart showing │+│ 30-day trend] │+│ │+│ Current: 185 lbs │+│ Change: -2 lbs │+│ (7 days) │+│ Average: 186.2 lbs │+│ │+│ 📊 7d 30d 90d All │+│ │+├─────────────────────┤+│ Add Weight Entry │+│ [Date Input] │+│ [Weight Input] │+│ [Add Button] │+│ │+├─────────────────────┤+│ History │+│ Apr 18: 185 lbs │+│ Apr 17: 185.2 lbs │+│ Apr 16: 185.5 lbs │+│ Apr 15: 186 lbs │+│ │+└─────────────────────┘+```++### 6. Food Logging Screen+```+┌─────────────────────┐+│ LOG MEAL │ [X]+├─────────────────────┤+│ [Search foods...] │+│ 🔍 [Scan Barcode] │+│ │+│ Chicken Breast │+│ 200g | 330 cal │+│ P: 62g C: 0g F: 7g │+│ [Qty: 200g] [Add] │+│ │+│ Brown Rice │+│ 1 cup | 215 cal │+│ P: 5g C: 45g F: 2g │+│ [Qty: 1 cup] [Add] │+│ │+│ Added to Today: │+│ • Chicken 200g │+│ • Brown Rice 1 cup │+│ │+│ [Cancel] [Done] │+└─────────────────────┘+```++### 7. Bottom Navigation (All Screens)+```+┌─────────────────────┐+│ [🏠Home] [📈Stats] [⚙️]+│ [💪Workout][🍽️Food]+└─────────────────────┘+```++## Web App Screens++### Dashboard (Desktop View)+```+┌──────────────────────────────────────┐+│ LYFTER [Settings] [User] │+├──────────────────────────────────────┤+│ │+│ TODAY - April 18, 2026 │+│ │+│ ┌──────────────┬──────────────────┐ │+│ │ Weight │ Daily Stats │ │+│ │ 185 lbs │ ┌──────────────┐ │ │+│ │ △ -2 lbs │ │ P: 140 / 150 │ │ │+│ │ │ │ C: 180 / 250 │ │ │+│ │ [Update] │ │ F: 60 / 65 │ │ │+│ │ │ │ Cal: 1850/2000│ │ │+│ │ │ └──────────────┘ │ │+│ └──────────────┴──────────────────┘ │+│ │+│ ┌──────────────────────────────────┐ │+│ │ This Week's Workouts │ │+│ │ • Push Day (2 hours) - April 18 │ │+│ │ • Cardio (45 min) - April 17 │ │+│ │ • Pull Day (2 hours) - April 16 │ │+│ │ │ │+│ │ [View All] [Log New Workout] │ │+│ └──────────────────────────────────┘ │+│ │+│ ┌──────────────────────────────────┐ │+│ │ Weight Trend (30 days) │ │+│ │ [Line Chart - 30 days] │ │+│ │ Current: 185 | Avg: 186.2 │ │+│ └──────────────────────────────────┘ │+│ │+└──────────────────────────────────────┘+```++### Workout Log View+```+┌──────────────────────────────────────┐+│ WORKOUTS │+├──────────────────────────────────────┤+│ [Date Range Filter] [+ Log Workout] │+│ │+│ April 18, 2026 - Push Day │+│ ┌──────────────────────────────────┐ │+│ │ Bench Press │ │+│ │ 4 × 8 @ 275 lbs = 8,800 lbs vol. │ │+│ │ │ │+│ │ Incline Dumbbell Press │ │+│ │ 3 × 10 @ 85 lbs = 2,550 lbs vol. │ │+│ │ │ │+│ │ [Edit] [Delete] [Duplicate] │ │+│ └──────────────────────────────────┘ │+│ │+│ April 17, 2026 - Cardio │+│ ┌──────────────────────────────────┐ │+│ │ Treadmill Running - 45 min │ │+│ │ Distance: 5.2 miles │ │+│ │ [Edit] [Delete] │ │+│ └──────────────────────────────────┘ │+│ │+└──────────────────────────────────────┘+```++## Design Tokens++### Colors+- **Primary**: Deep Blue (#1E40AF)+- **Accent**: Orange (#FB923C) - for progress/achievements+- **Background**: Dark (#0F172A) or Light (#F8FAFC)+- **Text**: Dark text on light bg, light text on dark bg+- **Success**: Green (#22C55E)+- **Warning**: Red (#EF4444)++### Typography+- **Headlines**: Bold, 18-24px+- **Body**: Regular, 14-16px+- **Small**: 12-13px (secondary info)++### Spacing+- Standard padding: 16px+- Card margins: 12px+- Gutter: 8px++### Components+- Rounded corners: 8-12px (cards), 24px (buttons)+- Button height: 44px (mobile, touch-friendly)+- Input height: 40px+- Icons: 24px standard