# Kitchen Module Implementation Guide

## Overview
Kitchen View is part of the **Production Module** (`production.omnia.test`). It provides a real-time interface for kitchen staff to view and process orders from the Marketing core.

## Architecture

### Module Structure
```
Production Module (production.omnia.test)
├── Kitchen View (Current Focus)
├── Inventory Management (Future)
└── Stock Control (Future)
```

### Kitchen View Purpose
- Display orders from Marketing core with status "printed"
- Allow kitchen staff to view order details
- Mark orders as "packed" when ready
- Update order status back to Marketing core
- **(Future Integration)** Trigger stock reduction in Inventory

## Data Flow

### 1. Order Reading (Marketing → Kitchen)
```
Marketing DB (omnia.orders)
  ↓ (API Call or Direct DB Read)
Kitchen View
  ↓ (Display)
Kitchen Staff Interface
```

**Query Criteria:**
- Status: `printed` (orders that have been printed)
- Order by: `created_at DESC` (newest first)
- Include: order items, customer info, delivery details

### 2. Order Processing (Kitchen → Marketing)
```
Kitchen Staff
  ↓ (Marks as "Packed")
Kitchen API
  ↓ (Update Request)
Marketing Core API
  ↓ (Updates Status)
Marketing DB (omnia.orders)
  Status: printed → packed
```

### 3. Future: Stock Reduction (Kitchen → Inventory)
```
Kitchen Staff (Marks as "Packed")
  ↓
Inventory Service
  ↓ (Reduces Quantity)
Stock Table
  quantity = quantity - order_quantity
```

**Note:** Stock reduction is NOT implemented in Phase 1. Document for future integration.

## Database Schema

### Marketing Core (omnia database)

#### orders table
```sql
- id
- customer_name
- customer_phone
- delivery_address
- status (pending, printed, packed, shipped, delivered, cancelled)
- total_amount
- notes
- created_at
- updated_at
```

#### order_items table
```sql
- id
- order_id (FK)
- product_id (FK)
- product_name (cached for display)
- quantity
- price
- subtotal
- created_at
- updated_at
```

### Production Module Database (omnia_production_db)
**Phase 1:** No separate tables needed - reads directly from Marketing
**Future:** May add kitchen-specific tables for notes, timing, etc.

## SSO Integration

Kitchen module will check for `omnia_session` cookie:

```php
// Check authentication
$sessionId = $_COOKIE['omnia_session'] ?? null;

if (!$sessionId) {
    // Redirect to auth.omnia.test for login
    header('Location: http://127.0.0.1:8001/login');
    exit;
}

// Verify session with Auth service
$response = Http::get('http://127.0.0.1:8001/api/auth/verify', [
    'headers' => ['Cookie' => "omnia_session=$sessionId"]
]);

if (!$response->successful()) {
    // Session invalid - redirect to login
    header('Location: http://127.0.0.1:8001/login');
    exit;
}

$userData = $response->json()['data'];

// Check if user has kitchen.access permission
if (!in_array('kitchen.access', $userData['permissions'])) {
    // Access denied
    abort(403, 'You do not have permission to access Kitchen module');
}

// User authenticated and authorized - proceed
```

## API Endpoints

### Kitchen Module Endpoints

#### GET /api/orders/pending
Get all orders with status "printed" from Marketing

**Response:**
```json
{
  "success": true,
  "data": [
    {
      "id": 1,
      "order_number": "ORD-2025-001",
      "customer_name": "John Doe",
      "customer_phone": "012-3456789",
      "delivery_address": "123 Main St",
      "status": "printed",
      "total_amount": 150.00,
      "items": [
        {
          "product_name": "Nasi Lemak Special",
          "quantity": 2,
          "price": 15.00
        }
      ],
      "notes": "Extra spicy",
      "created_at": "2025-11-25 08:30:00"
    }
  ]
}
```

#### POST /api/orders/{id}/mark-packed
Mark order as packed

**Request:**
```json
{
  "packed_by": "User Name",
  "packed_at": "2025-11-25 09:15:00",
  "notes": "Optional packing notes"
}
```

**Response:**
```json
{
  "success": true,
  "message": "Order marked as packed",
  "data": {
    "order_id": 1,
    "status": "packed"
  }
}
```

### Marketing Core Integration

Kitchen will call Marketing API to update order status:

#### POST http://omnia.test/api/orders/{id}/update-status
```json
{
  "status": "packed",
  "updated_by": "Kitchen Staff Name"
}
```

## UI Components

### Kitchen Dashboard
- Display count of pending orders (status: printed)
- Show orders in card/list view
- Real-time updates (consider WebSocket/polling)
- Filter by time period, customer name

### Order Card
- Order number
- Customer name & phone
- Delivery address
- Order items with quantities
- Total amount
- Time since order created
- "Mark as Packed" button

### Order Details Modal
- Full order information
- Customer contact details
- Special instructions/notes
- Item details
- Packing checklist
- "Confirm Packed" action

## Permissions

Required permission: `kitchen.access`

**Roles with access:**
- admin (full access)
- manager (full access)
- kitchen-staff (view and update only)

## Future Enhancements (Phase 2+)

### 1. Inventory Integration
When order marked as packed:
```php
foreach ($order->items as $item) {
    InventoryService::reduceStock(
        productId: $item->product_id,
        quantity: $item->quantity,
        reason: "Order #{$order->id} packed"
    );
}
```

### 2. Kitchen Timer/KPI
- Track time from "printed" to "packed"
- Average preparation time
- Peak hours analysis
- Staff performance metrics

### 3. Kitchen Notes
- Add internal notes to orders
- Mark special instructions
- Track issues/problems

### 4. Real-time Notifications
- WebSocket for instant order updates
- Sound notification for new orders
- Desktop notifications

### 5. Batch Processing
- Group orders by delivery area
- Batch pack multiple orders
- Print batch labels

## Implementation Steps

### Phase 1: Basic Kitchen View (Current)
1. ✅ Auth service setup (completed)
2. ⏳ Create Production/Kitchen Laravel service
3. ⏳ Setup database connection to Marketing core
4. ⏳ Build order listing view
5. ⏳ Implement "mark as packed" functionality
6. ⏳ Test SSO integration
7. ⏳ Test order status update flow

### Phase 2: Inventory Integration (Future)
1. Create inventory database schema
2. Build inventory service
3. Implement stock reduction on pack
4. Add low stock alerts
5. Inventory reporting

## Development Notes

### Database Access Strategy
**Option 1: Direct Database Connection (Recommended for Phase 1)**
- Kitchen reads directly from Marketing database
- Simpler, faster for same-server deployment
- Configure second DB connection in Laravel

**Option 2: API Communication**
- Kitchen calls Marketing API for data
- Better for distributed systems
- More overhead but more maintainable

**Decision: Use Option 1 for Phase 1, migrate to Option 2 when moving to separate servers**

### Configuration
Kitchen service `.env`:
```env
# Marketing Core Database (Read-Only)
MARKETING_DB_CONNECTION=mysql
MARKETING_DB_HOST=127.0.0.1
MARKETING_DB_PORT=3306
MARKETING_DB_DATABASE=omnia
MARKETING_DB_USERNAME=root
MARKETING_DB_PASSWORD=

# Marketing Core API (For Updates)
MARKETING_API_URL=http://omnia.test/api
MARKETING_API_TOKEN=your-api-token-here

# Auth Service
AUTH_SERVICE_URL=http://127.0.0.1:8001
```

## Security Considerations

1. **Read-Only Database User**
   - Kitchen should have read-only access to Marketing database
   - Updates should go through Marketing API only

2. **API Authentication**
   - Use API tokens for service-to-service communication
   - Validate all requests

3. **Permission Checks**
   - Always verify `kitchen.access` permission
   - Log all order status changes
   - Track who made changes

4. **Data Validation**
   - Validate order exists before updating
   - Check order is in correct status for transition
   - Prevent duplicate status updates

## Testing Checklist

- [ ] User with `kitchen.access` can view orders
- [ ] User without `kitchen.access` gets 403 error
- [ ] Orders with status "printed" display correctly
- [ ] "Mark as packed" updates Marketing database
- [ ] Order status change logs properly
- [ ] SSO cookie works across domains
- [ ] Session expiry redirects to login
- [ ] Multiple simultaneous users work correctly

## Success Metrics

- Time from "printed" to "packed" < 15 minutes
- Zero missed orders (all printed orders processed)
- Staff can find orders in < 5 seconds
- System uptime > 99%

---

**Document Version:** 1.0
**Last Updated:** November 25, 2025
**Author:** OmniaBoss Development Team
