# Modern Recipe Management System

A complete modern web application built with Node.js, TypeScript, React, and MySQL - a modern alternative to the existing PHP application.

## 🚀 Architecture Overview

### Backend (Node.js + TypeScript)
- **Express.js** REST API server
- **Prisma ORM** for type-safe database access  
- **TypeScript** for development safety
- **MySQL** database (shared with PHP version)
- **Security** middleware (Helmet, CORS, rate limiting)

### Frontend (React + TypeScript) 
- **React 18** with functional components and hooks
- **TypeScript** for type safety
- **Vite** for fast development and building
- **React Router** for client-side routing
- **Axios** for API communication
- **Modern CSS** with responsive design

### Database
- **MySQL 8.0** (same database as PHP version)
- **Prisma** schema mapped to existing tables
- **Compatible** with current PHP application

## 🌐 Live URLs

- **React Frontend**: http://localhost:5173
- **Node.js API**: http://localhost:3001
- **PHP Application**: http://localhost:8082 (when Docker is running)
- **phpMyAdmin**: http://localhost:8083 (when Docker is running)

## � Quick Start

### ⚙️ Node Version

Empfohlene Node Version: **22.12.0** (oder LTS 20.19.x). Projekt liefert `.nvmrc`.

Mit nvm aktivieren:
```bash
nvm install 22.12.0
nvm use 22.12.0
```
Automatisch beim Wechsel ins Verzeichnis:
```bash
nvm use
```

Falls ohne nvm: Offizielles Binary oder Paketmanager (Node >=22.12.0) installieren.

### 1. Start the Database (existing Docker setup)
```bash
# From main project directory
docker-compose up -d
```

### 2. Start the Node.js Backend
```bash
cd backend
nvm use  # optional, falls nvm
npm install
npm run build
node dist/app.js
```

### 3. Start the React Frontend  
```bash
cd frontend
nvm use  # optional
npm install
npm run dev
```

## 📱 Features Implemented

### ✅ Backend API
- **Health Check** - Server status endpoint
- **Recipe Management** - Full CRUD operations with search/pagination
- **Ingredient Management** - CRUD operations for recipe ingredients  
- **Image Serving** - Static file serving for recipe images
- **Input Validation** - Joi schema validation
- **Error Handling** - Centralized error management
- **Security** - CORS, Helmet, rate limiting, input sanitization

### ✅ Frontend Application
- **Recipe List** - Grid view with search, filtering, pagination
- **Responsive Design** - Mobile-first CSS design
- **Image Display** - Recipe images with fallback handling
- **Navigation** - Clean header with route navigation
- **Search & Filter** - Real-time search and category filtering
- **Error Handling** - User-friendly error messages
- **Loading States** - Visual feedback for API calls

## 🎯 Current Status

### ✅ **COMPLETED**
- Node.js backend with TypeScript
- Prisma ORM with existing database schema
- Complete REST API for recipes, ingredients, images
- React frontend with modern UI
- Database integration working
- Both servers running successfully
- API endpoints tested and working
- Responsive design implemented

### 🔄 **Next Steps**
1. **Recipe Detail View** - Individual recipe pages
2. **Recipe Creation/Editing** - Forms for CRUD operations
3. **Image Upload** - File upload functionality
4. **Ingredient Management** - Dedicated ingredient pages
5. **Docker Configuration** - Containerize Node.js stack
6. **Performance Optimization** - Caching, lazy loading
7. **Testing** - Unit and integration tests

## 📊 API Endpoints

### Recipes
- `GET /api/recipes` - List recipes (pagination, search, filter)
- `GET /api/recipes/:id` - Get single recipe
- `lastUsed` wird nur noch gesetzt/aktualisiert wenn ein Rezept aktiv als "zubereitet" markiert wird (siehe Endpoint unten) – reines Ansehen ändert den Wert nicht mehr.

### Rezept als zubereitet markieren

POST `/api/recipes/:id/cooked`

Antwort:
```
{ "success": true, "message": "Rezept als zubereitet markiert", "data": { "id": 123, "lastUsed": "2025-09-25T18:47:12.123Z" } }
```

Verwendung: Button "Zubereitet" auf der Detailseite oder manuell per API. Dadurch kann die Liste nach "Zuletzt zubereitet" sortiert werden (`?sortBy=lastUsed&sortOrder=desc`).

### Zuletzt zubereitete Rezepte

`GET /api/recipes/recent?limit=10`

Liefert die zuletzt markierten Rezepte (nur solche mit gesetztem `lastUsed`) absteigend sortiert. `limit` (1–50) steuert die Anzahl.

Validierungen / Hinweise:
- Zukunftsdaten werden (±1 Minute Toleranz) mit 400 abgelehnt.
- Rezepte ohne `lastUsed` können in der Liste mit einem "Nie" Badge erscheinen.
- Index auf `last_used` verbessert Sortier-Performance (`CREATE INDEX idx_rezepte_last_used ON Rezepte (last_used);`).
- `POST /api/recipes` - Create recipe
- `PUT /api/recipes/:id` - Update recipe  
- `DELETE /api/recipes/:id` - Delete recipe

### Ingredients
- `GET /api/ingredients` - List ingredients
- `GET /api/ingredients/:id` - Get single ingredient
- `POST /api/ingredients` - Create ingredient
- `PUT /api/ingredients/:id` - Update ingredient
- `DELETE /api/ingredients/:id` - Delete ingredient

### Images
- `GET /api/images/recipe/:recipeId` - Get recipe images
- `GET /api/images/serve/:imagePath` - Serve image file
- `GET /api/images/:id` - Get image metadata
- `POST /api/images/reorder/:recipeId` - Reorder all images for a recipe (body: `{ "order": [imageId1, imageId2, ...] }`) renames files sequentially `<recipeNumber>_0.*`, `<recipeNumber>_1.*`, ...

### Health
- `GET /api/health` - Server health check

## 🔧 Development Commands

### Backend
```bash
cd backend

# Development
npm run dev          # Start with hot reload (if ts-node configured)
npm run build        # Build TypeScript
npm start            # Start production server
node dist/app.js     # Direct node execution

# Database
npm run db:generate  # Generate Prisma client
npm run db:push      # Push schema to database
npm run db:studio    # Open Prisma Studio GUI
```

### Frontend  
```bash
cd frontend

# Development
npm run dev          # Start Vite dev server
npm run build        # Build for production
npm run preview      # Preview production build
npm run lint         # Run ESLint
```

## � Technology Benefits

### vs. PHP Version
- **Type Safety** - TypeScript eliminates runtime type errors
- **Modern Tooling** - Better developer experience with Vite, ESLint, Prettier
- **API-First** - Clean separation enables mobile apps, integrations
- **Maintainability** - Modern patterns, better error handling
- **Performance** - React SPA, optimized builds, lazy loading
- **Security** - Modern security best practices built-in

### Architecture Advantages
- **Separation of Concerns** - API backend, UI frontend
- **Scalability** - Horizontal scaling, microservices ready
- **Testing** - Unit tests, integration tests, E2E tests possible
- **Deployment** - Modern CI/CD, containerization, cloud deployment
- **Extensibility** - Add mobile apps, integrations, webhooks

## � Integration Options

### 1. **Parallel Operation** (Current)
- PHP app on port 8082
- Node.js API on port 3001  
- React app on port 5173
- Same MySQL database

### 2. **Gradual Migration**
- Move features one by one from PHP to Node.js
- Use API versioning for compatibility
- Migrate users gradually

### 3. **Complete Replacement**
- Full React frontend + Node.js backend
- Retire PHP application
- Modern deployment stack

## � UI/UX Features

- **Modern Design** - Clean, professional interface
- **Responsive** - Mobile, tablet, desktop optimized
- **Fast** - React SPA with instant navigation
- **Search** - Real-time recipe search
- **Filtering** - Category-based filtering
- **Pagination** - Efficient large dataset handling
- **Images** - Recipe photo display with fallbacks
- **Navigation** - Intuitive menu structure
- **Feedback** - Loading states, error messages
- **Accessibility** - Semantic HTML, keyboard navigation

## � Deployment Ready

The application is ready for production deployment with:
- **Environment Configuration** - .env files for different environments
- **Build Process** - Optimized production builds
- **Static Assets** - Vite optimization for frontend
- **Security** - Production-ready security headers
- **Error Handling** - Graceful error recovery
- **Monitoring** - Health checks, logging endpoints

This modern stack provides a solid foundation for scaling the recipe management system with contemporary web technologies while maintaining compatibility with your existing data and workflows.