# Error Handling & Logging Strategy

> **Last verified:** 2026-10-31 against the working tree, including a live HTTP audit (`/`, `/seller/demo-vendor`, `/seller/promptschat`, `/vendor/onboarding`, `/vendor/profile`, `/vendor/payouts` → 200 with the sidebar label appearing once), End-to-End Withdrawal & Payout validation (`WDR-XXXXXX`), and bulk Prompts.chat importer packet/reconnect resilience. The PHP-extension and vendor-profile sections reflect the current Linux + PHP 8.5 environment.

## 1. Overview
This document defines exception handling, validation failure procedures, multi-panel authorization handling, storage upload handling, and error logging across the PromptBase application.

---

## 2. Authorization & Panel Exception Handling

### A. Forbidden Access (403 Exceptions) & Onboarding Redirection
- Handled by `canAccessPanel(Panel $panel)` in `App\Models\User` and `EnsureVendorIsVerified` in `App\Http\Middleware\EnsureVendorIsVerified`.
- Any user with `$user->isBanned()` or `$user->is_suspended === true` receives an immediate `403 Forbidden` (or login rejection) when accessing `/admin` or `/vendor/*`.
- Decoupled Vendor Access: Non-suspended, non-banned vendors (`role === 'vendor'`) are never blocked by KYC status; instead, `EnsureVendorOnboardingCompleted` intercepts first-time vendors (`onboarding_completed_at === null`) and 302-redirects them to `/vendor/onboarding` until they complete the 3-step onboarding wizard.
- The vendor profile page is a **singleton** (`App\Filament\Vendor\Pages\Profile`, `/vendor/profile`) that accepts no route parameters, so cross-vendor profile tampering is structurally impossible. `/vendor/vendor-profile` simply 302-redirects to `/vendor/profile`.

### B. Unauthenticated Panel Access & Logout Handling
- Unauthenticated requests to `/admin` or `/vendor/*` are intercepted by `App\Http\Middleware\RedirectToCentralLogin` (extending Filament's `Authenticate`), seamlessly redirecting visitors to `route('login')` (`/login`) without throwing missing route exceptions.
- `App\Http\Responses\CustomLogoutResponse` implements Filament's `LogoutResponse` contract, ensuring logouts from Admin or Vendor panels never fail with `Route [filament.admin.auth.login] not defined` and explicitly purge all 2FA verification session keys before redirecting to `/login`.

### C. Resource Not Found (404 Exceptions)
- Both `show(Product $product)` and `reveal($token)` use `firstOrFail()`.
- Smart route binding in `Product::resolveRouteBinding()` resolves by slug, `product_code` (`PRD-XXXXXX`), or numeric ID.
- `User::resolveRouteBinding()` can resolve `username`, `seller_code` (`VND-XXXXXX`), numeric ID or email — but the storefront route pins the field (`/seller/{user:username}`), so only usernames resolve there and numeric/Seller-Code URLs return `404`.
- `KycPreviewController` returns `404` for malformed base64 paths, paths containing `..`, and files missing from the `kyc_disk`; it returns `403` when the authenticated user is neither the document owner nor an admin.
- Inactive or non-existent items automatically trigger a clean 404 HTTP Exception.

---

## 3. Controller & Webhook Error Handling Procedures

### A. Validation Errors (422 Unprocessable Entity)
- Form inputs (e.g. email on checkout, user role on admin edit, seller registration, 3-step vendor onboarding wizard) are validated.
- Validation errors are flashed to session and rendered under respective inputs in Blade / Filament views.
- **Payout Minimum Threshold & Concurrency Lock (default $20)**: When requesting a payout in `/vendor/payouts` (`VendorBilling::submitWithdrawalRequest()`), `DB::transaction()` + `User::lockForUpdate()` verifies that the account is not payout-frozen (`is_payout_frozen`), has a valid saved `PayoutMethod`, and requests an amount between `config('marketplace.min_withdrawal')` (`MARKETPLACE_MIN_WITHDRAWAL` env, default `$20`) and `$lockedUser->available_balance`. Invalid requests are rejected with clear error notifications.
- **Coupon Validation at Checkout**: `ProductController@checkout` rejects unknown, expired, usage-capped or wrong-vendor coupon codes with a flashed `"Invalid or expired coupon code."` error and `back()` — no order row is created in that case.

### B. FilePond Upload State Sanitization
- In Filament forms with FileUpload components (e.g. the `Profile` page's KYC documents or avatar uploads), Livewire FilePond states may be returned as an associative array with temporary UUID keys or as plain strings.
- Form state processing sanitizes file arrays:
  ```php
  $document = is_array($data['id_document'] ?? null)
      ? (array_values($data['id_document'])[0] ?? null)
      : ($data['id_document'] ?? null);
  ```

### C. Ticket Attachment & File Upload Exceptions
- Validated with `max:10240` (10MB limit) and MIME restrictions (`image/*`, `application/pdf`, `text/plain`).
- File size excesses trigger real-time validation error alerts in the conversational thread UI without breaking the Livewire component state.

### D. Stripe API & Webhook Errors
- In `StripeWebhookController`:
  - `\UnexpectedValueException`: Caught if JSON payload is malformed (Returns `400 Bad Request`).
  - `SignatureVerificationException`: Caught if Stripe signature fails verification (Returns `400 Bad Request`).
- In `ProductController`:
  - Stripe SDK calls are wrapped in exception handlers where needed, providing graceful fallbacks.

---

## 4. Logging & Monitoring
- **Laravel System Logs**: Stored under `storage/logs/laravel.log`.
- **Realtime Log Tailing**: `php artisan pail` runs as part of development to output real-time application exceptions and database query warnings in the terminal.

---

## 5. Database Connection & Schema Exception Handling

### A. Connection Refused (`SQLSTATE[HY000] [2002]`)
- **Symptom**: `No connection could be made because the target machine actively refused it` / `Connection refused` when connecting to MySQL.
- **Root Cause**: MySQL is not running, or `DB_HOST`/`DB_PORT` mismatch in `.env` (e.g. `3305` while MySQL listens on `3306`).
- **Resolution**:
  1. Check the listener: `ss -ltn | grep 3306`.
  2. On this workstation MySQL ships with **XAMPP** — start it with `sudo /opt/lampp/lampp start` (stop with `sudo /opt/lampp/lampp stop`).
  3. Set `DB_HOST=127.0.0.1`, `DB_PORT=3306` in `.env`.
  4. Clear configuration cache: `php artisan config:clear`.

### B. Missing Column Exception (`SQLSTATE[42S22]`)
- **Symptom**: `Unknown column 'seller_code'` or `Unknown column 'is_featured'`.
- **Root Cause**: Existing MySQL table schema is out of date relative to latest migration definitions.
- **Resolution**: Run migrations:
  ```bash
  php artisan migrate
  ```

### C. Bulk Import Packet Size & Transient Reconnect Handling (`ImportPromptsChatCommand`)
- **Symptom**: `SQLSTATE[08S01]: Communication link failure: 1153 Got a packet bigger than 'max_allowed_packet' bytes` or `2006 MySQL server has gone away` during large `prompts.chat` dataset imports (`4,160+` prompts).
- **Root Cause**: Several `SKILL` prompts in `f/prompts.chat` contain 20–40 KB embedded scripts, causing large multi-row `UPSERT` statements to exceed XAMPP MariaDB's default 1 MB `max_allowed_packet`.
- **Resolution (Built into `App\Console\Commands\ImportPromptsChatCommand`)**:
  1. **Byte-Capped Upsert Batching**: `processItems()` tracks `$bufferBytes` and flushes `Product::upsert()` whenever `count($upsertBuffer) >= 25 || $bufferBytes >= 180000` (`~180 KB` max packet size), while capping individual `prompt_text` payloads at `60,000` characters (`TEXT` column safe limit).
  2. **Automatic Reconnect & Backoff (`withDatabaseRetry`)**: Transient connection drops (`2002`, `2006`, `2013`, `1153`, `08S01`) automatically clear `database.connections.mysql.unix_socket`, force TCP `127.0.0.1`, run `DB::purge('mysql'); DB::reconnect('mysql');`, and retry up to 8 times.

---

## 6. PHP Extension Exceptions

The project needs more than `intl`/`gd`/`zip` — the authoritative list lives in **README.md → "Technology Stack"**. On a minimal PHP install the **most common fatal error is a missing `dom`/`xml` extension**.

### A. Fatal `Class "DOMDocument" not found`
- **Symptom**:
  ```
  Error
  Class "DOMDocument" not found
  at vendor/nunomaduro/termwind/src/HtmlRenderer.php:32
  ```
  It masks the *real* exception because Laravel renders errors through Termwind, which needs `DOMDocument`.
- **Root Cause**: `ext-dom` / `ext-xml` / `ext-simplexml` are missing (on Ubuntu they come from the `php8.5-xml` package). 15 packages in `composer.lock` require `ext-dom` and 17 require `ext-mbstring`.
- **Resolution (with sudo — permanent):**
  ```bash
  sudo apt install -y php8.5-xml php8.5-mbstring php8.5-curl php8.5-intl php8.5-mysql \
                      php8.5-zip php8.5-sqlite3 php8.5-gd php8.5-bcmath php8.5-gmp
  ```
- **Resolution (without sudo — what this workstation uses):** the extension `.so` files were extracted into `~/.local/share/php85ext/` and are loaded by the wrapper `~/.local/bin/php85` (symlinked as `php`, with `export PATH=$HOME/.local/bin:$PATH` in `~/.zshrc`). Inspect what is loaded with `php -m`.
- **Verify**: `php -r "echo class_exists('DOMDocument') ? 'OK' : 'MISSING';"` → `OK`.

### B. Other extension failures
- `The "intl" PHP extension is required to use the [format] method.` → `intl` missing (Filament `Number::format`).
- `could not find driver` when touching the database → `pdo_mysql` missing.
- `Module compiled with module API=20230831 ... PHP compiled with module API=20250925` → that `.so` was built for a different PHP version; only load extensions matching `php -i | grep 'PHP API'`.
- After enabling anything, restart `php artisan serve` / `composer run dev` and re-check `php -m`.

---

## 7. Filament Observer & Panel Route Resolution Handling

### A. RouteNotFoundException on Model Observers (`filament.admin.pages...`)
- **Symptom**: `RouteNotFoundException: Route [filament.admin.pages.vendor-followers] not defined.`
- **Root Cause**: When generating URLs inside Model Observers (which run in CLI, queue, or web context where no active Filament panel is bound), `Resource::getUrl()` or `Page::getUrl()` defaults to the default admin panel and cannot resolve vendor routes.
- **Resolution**: Explicitly specify the panel target when invoking `getUrl()`:
  ```php
  VendorFollowers::getUrl(panel: 'vendor');
  VendorSalesResource::getUrl('index', panel: 'vendor');
  Profile::getUrl(panel: 'vendor');                    // singleton page — no record parameter
  VendorTicketResource::getUrl('view', ['record' => $record->ticket_id], panel: 'vendor');
  ```
- **Note:** `Profile` replaced the old `VendorProfile` page in Phase 25. Any snippet still passing `['record' => $user->id]` to `VendorProfile::getUrl()` refers to a class that no longer exists.

---

## 8. Livewire File Upload with Cloudflare R2 / S3 Storage

### A. Livewire "Upload Failed" with FILESYSTEM_DISK=r2
- **Symptom**: Selecting an avatar or file in Filament/Livewire shows "Upload failed" immediately on the client interface.
- **Root Cause**: When `FILESYSTEM_DISK=r2` is set as default, Livewire 3 defaults its `temporary_file_upload.disk` to `r2` and attempts client-side direct S3 pre-signed upload URLs. Cloudflare R2 blocks browser direct pre-signed POSTs unless specific CORS rules are configured.
- **Resolution**: Explicitly set Livewire's temporary upload disk to `'local'` in `config/livewire.php`:
  ```php
  'temporary_file_upload' => [
      'disk' => 'local',
  ],
  ```
- **Related**: if assets must work fully offline, set `FILESYSTEM_DISK=public` in `.env` and run `php artisan storage:link`. Ticket attachments already fall back to the `public` disk automatically when `r2` is not configured.

---

## 9. Frontend Toolchain Errors

### A. `sh: 1: vite: Permission denied`
- **Symptom**: `npm run dev` / `npm run build` aborts with `sh: 1: vite: Permission denied`.
- **Root Cause**: the `node_modules/.bin/*` shims lost their executable bit — usually because the folder was copied from Windows (which also explains the stray `*.cmd` / `*.ps1` shims).
- **Resolution**: `chmod +x node_modules/.bin/*` (and `chmod +x artisan vendor/bin/*`). A fresh `npm install` recreates the correct permissions.

### B. `Vite manifest not found at: .../public/build/manifest.json`
- **Root Cause**: assets were never built and no dev server is running.
- **Resolution**: run `npm run dev` (development) or `npm run build` (production), then hard-refresh (`Ctrl+Shift+R`).

### C. `.npmrc` disables lifecycle scripts
- The repository commits `.npmrc` containing `ignore-scripts=true`. Vite 8 / Rolldown ship their native binaries as optional dependencies, so normal installs work; a package that genuinely needs a postinstall step must be installed with `npm install --ignore-scripts=false <package>`.

## Audit Note — 2026-10-04
Production must use `APP_DEBUG=false`, `LOG_LEVEL=warning`, an error tracker (Sentry/Flare), and a real queue worker (`QUEUE_CONNECTION=database|redis`) so failed exports/notifications are retried and visible in `FailedJobResource`.
