# Meal Planner for Elderly Care Homes

A digital meal ordering system for elderly care homes, built with Payload CMS 3.x and Next.js 15. This application digitizes the paper-based workflow where caregivers collect meal preferences from residents and kitchen staff prepare meals.

## Features

- **Multi-tenant architecture**: Each care home operates as a separate tenant with isolated data
- **Role-based access control**: Super-admin, tenant admin, caregiver, and kitchen staff roles
- **Meal order management**: Support for breakfast, lunch, and dinner with customizable options
- **Kitchen dashboard**: Aggregated ingredient reports for meal preparation
- **Tablet-friendly caregiver interface**: Touch-optimized UI for creating meal orders
- **Resident management**: Track dietary requirements, aversions, and special notes

## Tech Stack

- **Next.js 15** - React framework with App Router
- **Payload CMS 3.65** - Headless CMS with admin panel
- **SQLite** - Database (easily upgradeable to PostgreSQL)
- **TypeScript** - Type safety
- **SCSS** - Styling

## Quick Start

### Prerequisites

- Node.js 18+
- pnpm (recommended) or npm
- Docker and Docker Compose (for containerized deployment)

### Local Development

```bash
# Clone the repository
git clone <repository-url>
cd meal-planner

# Install dependencies
pnpm install

# Copy environment variables
cp .env.example .env

# Start development server with seeding
SEED_DB=true pnpm dev
```

The application will be available at `http://localhost:3000`.

### Docker Deployment

Run the complete stack with PostgreSQL and MinIO:

```bash
# Build and start all services
docker-compose up --build

# Or run in detached mode
docker-compose up -d --build

# Stop services
docker-compose down

# Stop and remove volumes (clean restart)
docker-compose down -v
```

**Services:**
- **App**: http://localhost:3100
- **PostgreSQL**: localhost:5433
- **MinIO Console**: http://localhost:9101 (credentials: minioadmin/minioadmin)
- **MinIO API**: http://localhost:9100

The Docker setup automatically:
- Uses PostgreSQL instead of SQLite
- Uses MinIO for S3-compatible object storage
- Creates the required storage bucket
- Seeds the database with sample data

### Default Users

The seed script creates the following users:

| Email                  | Password | Role        | Access                              |
|------------------------|----------|-------------|-------------------------------------|
| admin@example.com      | test     | Super Admin | Full system access                  |
| caregiver@example.com  | test     | Caregiver   | Create/view meal orders             |
| kitchen@example.com    | test     | Kitchen     | View orders, update status, reports |

## Application Structure

### URLs

- `/admin` - Payload CMS admin panel
- `/admin/kitchen-dashboard` - Kitchen ingredient report dashboard
- `/caregiver/login` - Caregiver login page
- `/caregiver/dashboard` - Caregiver main dashboard
- `/caregiver/orders/new` - Create new meal order
- `/caregiver/orders` - View meal orders
- `/caregiver/residents` - View residents list

## Data Model

### Collections

#### Tenants (Care Homes)
- `name` - Care home name
- `slug` - URL-friendly identifier
- `domain` - Optional custom domain
- `address` - Physical address
- `phone` - Contact phone

#### Users
Global roles:
- `super-admin` - Full system access
- `user` - Standard user (access based on tenant roles)

Tenant roles:
- `admin` - Full access within tenant
- `caregiver` - Create and manage meal orders
- `kitchen` - View orders, update status, generate reports

#### Residents
- `name` - Full name
- `room` - Room number
- `table` - Table assignment
- `station` - Ward/station
- `highCaloric` - High caloric diet flag
- `aversions` - Food aversions
- `notes` - Additional notes
- `active` - Active status

#### Meal Orders
Core fields:
- `resident` - Reference to resident
- `date` - Order date
- `mealType` - breakfast, lunch, or dinner
- `status` - pending, preparing, or prepared
- `createdBy` - User who created the order

Conditional meal options (based on mealType):
- **Breakfast**: Bread types, spreads, beverages, additions
- **Lunch**: Portion size, soup, dessert, special preparations
- **Dinner**: Bread, spreads, soup, beverages, additions

## Access Control Matrix

| Operation       | Super Admin | Tenant Admin | Caregiver         | Kitchen            |
|-----------------|-------------|--------------|-------------------|--------------------|
| Manage users    | All         | Own tenant   | No                | No                 |
| Manage tenants  | All         | Own tenant   | No                | No                 |
| View residents  | All         | Own tenant   | Own tenant        | Own tenant         |
| Manage residents| All         | Own tenant   | No                | No                 |
| Create orders   | All         | Own tenant   | Own tenant        | No                 |
| View orders     | All         | Own tenant   | Own tenant        | Own tenant         |
| Update orders   | All         | Own tenant   | Own pending only  | Status only        |
| Delete orders   | All         | Own tenant   | No                | No                 |
| Kitchen reports | All         | Own tenant   | No                | Own tenant         |

## Kitchen Dashboard

The kitchen dashboard (`/admin/kitchen-dashboard`) provides:

1. Date and meal type selection
2. Aggregated ingredient counts for all orders
3. Portion size breakdown (for lunch)
4. Total order count

### API Endpoint

```
GET /api/meal-orders/kitchen-report?date=YYYY-MM-DD&mealType=breakfast|lunch|dinner
```

Response:
```json
{
  "date": "2024-01-15",
  "mealType": "breakfast",
  "totalOrders": 45,
  "ingredients": {
    "breadRoll": 32,
    "butter": 40,
    "coffee": 38
  },
  "labels": {
    "breadRoll": "Bread Roll (Brötchen)",
    "butter": "Butter",
    "coffee": "Coffee (Kaffee)"
  }
}
```

## Caregiver Interface

The tablet-optimized caregiver interface provides:

1. **Dashboard**: Today's order statistics and quick actions
2. **New Order Flow**:
   - Step 1: Select date and meal type
   - Step 2: Select resident
   - Step 3: Configure meal options
   - Step 4: Review and submit
3. **Orders List**: Filter by date and meal type
4. **Residents List**: Search and view dietary requirements

## Development

### Scripts

```bash
pnpm dev          # Start development server
pnpm build        # Build for production
pnpm start        # Start production server
pnpm seed         # Run database seed
pnpm generate:types  # Generate TypeScript types
```

### Database

The application uses:
- **SQLite** for local development (`meal-planner.db` file)
- **PostgreSQL** when running via Docker Compose

The configuration automatically switches based on the `DATABASE_URI` environment variable:
- If `DATABASE_URI` is set → PostgreSQL
- If `DATABASE_URI` is empty → SQLite

### Storage

The application uses:
- **Local filesystem** for local development
- **MinIO (S3-compatible)** when running via Docker Compose

The configuration automatically switches based on the `MINIO_ENDPOINT` environment variable.

### Environment Variables

```env
PAYLOAD_SECRET=your-secret-key-here
SEED_DB=true  # Set to seed database on startup
```

## Domain-Based Tenant Selection

For domain-based tenant routing, add entries to `/etc/hosts`:

```
127.0.0.1 sunny-meadows.localhost
```

## Project Structure

```
src/
├── access/                    # Access control utilities
├── app/
│   ├── (app)/                 # Caregiver frontend
│   │   ├── caregiver/
│   │   │   ├── login/         # Login page
│   │   │   ├── dashboard/     # Dashboard
│   │   │   ├── orders/        # Orders list and create
│   │   │   └── residents/     # Residents list
│   │   └── index.scss         # Frontend styles
│   └── (payload)/             # Payload admin
│       └── admin/views/       # Custom admin views
├── collections/
│   ├── Tenants/               # Care homes
│   ├── Users/                 # Users with roles
│   ├── Residents/             # Resident information
│   └── MealOrders/            # Meal orders
├── utilities/                 # Helper functions
├── payload.config.ts          # Payload configuration
└── seed.ts                    # Database seeding
```

## Seed Data

The seed script creates:
- 1 care home (Sunny Meadows Care Home)
- 3 users (admin, caregiver, kitchen)
- 8 residents with varied dietary requirements
- 24 meal orders across different dates and meal types

## License

MIT
