# Future Developers & Maintainers Engineering Handbook

Welcome to the technical engineering manual for **Eniceberny Bakery and Culinary Hub**. This handbook is authored for software engineers, DevOps maintainers, and architectural contributors tasked with maintaining, scaling, or integrating with the codebase.

---

## 🧭 1. Repository Anatomy & Directory Map

```text
├── app/
│   ├── Enums/                # Backed enums (UserRole, OrderStatus, etc.)
│   ├── Http/
│   │   ├── Controllers/
│   │   │   ├── Admin/        # Operational consoles (Orders, POS, Products, Settings, Reports)
│   │   │   ├── Auth/         # Authentication, OTP email verification
│   │   │   └── Storefront/   # Public commerce (Shop, Cart, Checkout, Invoices, Catering, Docs)
│   │   ├── Middleware/       # Security (AdminMiddleware, RoleGates, TrustedProxies)
│   │   └── Requests/         # Form validation rules (CheckoutRequest, ProductRequest, etc.)
│   ├── Models/               # Eloquent ORM models with relations, casts, and audit logs
│   ├── Services/             # Domain business logic (OrderService, CartService, Payments, Settings)
│   └── helpers.php           # Global presentation helpers (format_currency, site_logo_url, etc.)
├── database/
│   ├── factories/            # Model factories for automated test generation
│   ├── migrations/           # Version-controlled schema migrations
│   └── seeders/              # Authentic culinary menu, category, and sample data seeders
├── docker/                   # Production Apache config, PHP.ini directives, and entrypoint.sh
├── docs/                     # GitBook documentation books (Markdown files & SUMMARY.md)
├── resources/
│   ├── js/                   # JavaScript entry point (Alpine.js, @gitbook/embed)
│   ├── css/                  # Styling & Tailwind design system
│   └── views/                # Modular Blade templates (Storefront, Admin, PDF, Emails)
├── routes/
│   ├── web.php               # Browser routes with CSRF and session cookies
│   └── api.php               # Stateless REST endpoints (/api/v1/*)
├── tests/
│   ├── Feature/              # Comprehensive HTTP and business workflow test suites (85 tests)
│   └── TestCase.php          # Base test harness with SQLite in-memory configuration
├── .github/workflows/ci.yml  # Automated GitHub Actions CI test & asset build pipeline
├── Dockerfile                # Production multi-stage Docker container build
├── gitbook-docs.yaml         # GitBook Site Git Sync configuration
└── render.yaml               # Render PaaS infrastructure as code blueprint
```

---

## ⚙️ 2. Local Development Environment Setup

### Prerequisites:
- **PHP**: `8.4.x` with extensions: `pdo_sqlite`, `pdo_pgsql`, `mbstring`, `bcmath`, `gd`, `zip`, `xml`, `curl`.
- **Composer**: `2.x`.
- **Node.js**: `20.x` or `22.x` and `npm`.

### Step-by-Step Setup:
```bash
# 1. Clone repository
git clone https://github.com/mhiskall282/enicebakery-website.git
cd enicebakery-website

# 2. Install PHP and NPM dependencies
composer install
npm install

# 3. Environment file configuration
cp .env.example .env
php artisan key:generate

# 4. Run database migrations and seed full operational catalog
php artisan migrate --seed

# 5. Build frontend Vite assets
npm run build

# 6. Run local development servers
# Terminal 1: Vite dev server with hot module reload
npm run dev

# Terminal 2: Local PHP web server
php artisan serve
```

---

## 🧩 3. Architectural Design Patterns & Domain Services

### 3.1 Order Service (`App\Services\Order\OrderService`)
The `OrderService` encapsulates transactional order placement, ensuring stock deductions, financial ledgers, and audit trails succeed atomically:

```php
public function createOrder(array $validatedData, Cart $cart, ?User $user = null): Order
{
    return DB::transaction(function () use ($validatedData, $cart, $user) {
        $order = Order::create([
            'order_number' => $this->generateOrderNumber(),
            'user_id' => $user?->id,
            'customer_name' => $validatedData['customer_name'],
            'customer_phone' => $validatedData['customer_phone'],
            'subtotal' => $cart->subtotal,
            'total' => $cart->total,
            'status' => 'pending',
            'payment_status' => 'pending',
        ]);

        foreach ($cart->items as $item) {
            $order->items()->create([
                'product_id' => $item->product_id,
                'product_name' => $item->product->name,
                'quantity' => $item->quantity,
                'unit_price' => $item->unit_price,
                'subtotal' => $item->subtotal,
            ]);

            // Decrement inventory if tracking is enabled
            if ($item->product->track_inventory) {
                $item->product->decrementStock($item->quantity, 'online_order');
            }
        }

        // Record initial status audit trail
        $order->statusHistories()->create([
            'from_status' => null,
            'to_status' => 'pending',
            'comment' => 'Order placed online by customer',
            'user_id' => $user?->id,
        ]);

        return $order;
    });
}
```

### 3.2 Payment Gateway Driver Pattern
Gateways are resolved dynamically through `App\Services\Payments\PaymentManager`:
- To add a new payment gateway (e.g. Hubtel, Slydepay):
  1. Create driver class implementing `PaymentGatewayInterface`.
  2. Register driver in `PaymentManager::driver()`.
  3. Add credentials to `config/services.php` and `.env.example`.

### 3.3 Dynamic Settings & Logo Management
- Settings are cached under the key `all_site_settings`.
- When settings or logos are updated in `/admin/settings`, the cache is invalidated immediately via `Cache::forget('all_site_settings')`.
- Twin keys automatically synchronize (e.g. updating `site_name` updates `business_name`).

---

## 🧪 4. Testing Protocols & CI Automation

All pull requests and commits are verified against **85 automated tests** in [`.github/workflows/ci.yml`](file:///c:/Users/user/Desktop/enicebakery-website/.github/workflows/ci.yml):

```bash
# Execute entire test suite locally
php artisan test

# Execute with coverage report (if xdebug/pcov installed)
php artisan test --coverage

# Filter tests by module
php artisan test --filter AdminTest
php artisan test --filter StorefrontTest
php artisan test --filter Phase2CommerceTest
```

### Pre-Commit Quality Gate:
Before pushing to `main`, verify:
1. `php artisan test` $\rightarrow$ 85 passed, 0 failures.
2. `npm run build` $\rightarrow$ Vite bundles compile cleanly without warnings.
3. `git status` $\rightarrow$ No untracked junk files or debug prints.

---

## 🛠️ 5. Operational Maintenance & Troubleshooting Runbook

### 5.1 Clearing and Re-Warming Caches
If changes to templates, routes, or configurations are not reflecting on production:
```bash
php artisan config:clear
php artisan route:clear
php artisan view:clear
php artisan cache:clear

# Re-optimize for production
php artisan config:cache
php artisan route:cache
php artisan view:cache
```

### 5.2 Background Queue Worker
The application uses background queues for email dispatches and PDF receipt generation:
```bash
# Start queue worker locally
php artisan queue:work --tries=3 --timeout=90

# Restart workers on production deploy
php artisan queue:restart
```

### 5.3 Storage Symlink Repair
If product images or brand logos return HTTP 404:
```bash
php artisan storage:link
```
Verify that `storage/app/public` is accessible via `public/storage`.

### 5.4 Database Migration & Seeding Reset (Local Dev Only)
To reset the development database and re-seed authentic sample business data:
```bash
php artisan migrate:fresh --seed
```

> [!WARNING]
> **Never run `migrate:fresh` in production!** Always use `php artisan migrate --force` for incremental schema updates on production servers.
