# Prompts & Guidelines Documentation

> **Last verified:** 2026-10-31 — identifier formats (`PRD-XXXXXX`, `VND-XXXXXX`, `TCK-XXXXXX`, `WDR-XXXXXX`), route table (`/vendor/onboarding`), Prompts.chat importer, Interactive Prompt Engine, and Filament conventions checked against the working tree. Treat this file as the single source of truth when making AI-assisted changes.

## 1. Project Guidelines & Conventions
This document tracks system instructions, prompt templates, and architectural rules used by AI coding assistants (e.g. Antigravity) for developing PromptBase Clone.

---

## 2. UI Layout & Theme Rules
- **Framework**: Laravel Blade + Tailwind CSS + Alpine.js (via Vite compilation).
- **Master Layout**: `layouts/app.blade.php`.
- **View Structure**:
  - All public views must start with `@extends('layouts.app')` and wrap content in `@section('content') ... @endsection`.
  - Color Theme: Deep Charcoal (`#0B0F19`), Slate surfaces (`#111827`), Emerald accents (`#10B981`), Subtle borders (`#1F2937` / `border-gray-800`).
  - Text: White (`text-white`) for headings, Light Gray (`text-gray-300` / `text-gray-400`) for body and subtitles.

---

## 3. Unique Identifiers & Code Formats
```php
// Product Code (Item ID):
// Format: PRD-XXXXXX (6 random digits)
Product::generateUniqueProductCode(); // e.g. PRD-382094

// Seller Unique ID (Seller Code):
// Format: VND-XXXXXX (6 random digits)
User::generateUniqueSellerCode(); // e.g. VND-334901

// Support Ticket ID:
// Format: TCK-XXXXXX (6 random digits)
Ticket::generateUniqueTicketId(); // e.g. TCK-849201

// Withdrawal Request Reference ID:
// Format: WDR-XXXXXX (6 random alphanumeric uppercase chars)
VendorPayout::generateUniqueReferenceId(); // e.g. WDR-948201

// Order Reference (display-only, derived from the primary key):
// Format: #ORD-XXXXX (5 zero-padded digits)
'#ORD-' . str_pad($order->id, 5, '0', STR_PAD_LEFT); // e.g. #ORD-00042
```

---

## 4. Public Creator Storefront Filtering Guidelines
```php
// In SellerController.php:
// Query scoped to approved & active prompts:
$query = $user->products()
    ->where('status', 'approved')
    ->where('is_active', true)
    ->withCount(['reviews' => fn ($q) => $q->where('status', 'approved')])
    ->withCount(['orders' => fn ($q) => $q->where('status', 'paid')])
    ->withAvg(['reviews' => fn ($q) => $q->where('status', 'approved')], 'rating');

// Sort criteria:
// 'newest'     -> orderBy('created_at', 'desc')
// 'oldest'     -> orderBy('created_at', 'asc')
// 'popular'    -> orderByDesc('orders_count')
// 'top_rated'  -> orderByDesc('reviews_avg_rating')
// 'price_low'  -> orderBy('price', 'asc')
// 'price_high' -> orderBy('price', 'desc')

// Dynamic AJAX Partial swap:
if ($request->ajax() || $request->has('ajax')) {
    return view('sellers.partials.prompts-grid', compact('seller', 'prompts'))->render();
}
```

---

## 5. Stripe Integration Prompt Template
```
When implementing Stripe Checkout & Webhooks:
1. Use config('services.stripe.secret') for API keys.
2. Store pending orders prior to redirecting to Stripe Checkout.
3. Use a unique 32-character random access_token for order security.
4. Verify Stripe-Signature header in StripeWebhookController.
```

---

## 6. Filament Admin & Vendor Guidelines
- Keep Filament resource schema synced with database migrations.
- **Role Isolation & Decoupled Vendor Access**: Ensure `canAccessPanel(Panel $panel)` strictly isolates `admin` vs `vendor` panel access (`$panel->getId() === 'admin'` allows only `role === 'admin'`; `$panel->getId() === 'vendor'` allows any non-suspended, non-banned `role === 'vendor'` without waiting for Admin KYC approval).
- **Vendor Query Scoping**: In `ProductResource::getEloquentQuery()`, scope queries to `where('user_id', auth()->id())` when inside the `vendor` panel.
- **Dedicated Vendor Control (`VendorResource`) vs Customers (`UserResource`)**:
  - `App\Filament\Resources\VendorResource` (`/admin/vendors`) manages sellers (`where('role', 'vendor')`) with 9 telemetry columns, operational toggles (`is_verified`, `is_payout_frozen`, `is_suspended`), **Contact, Billing Location & Creator Onboarding Survey** inspection & edit section, `VendorStatsOverviewWidget`, and 6 Relation Managers (`PromptsRelationManager`, `OrdersRelationManager`, `PayoutsRelationManager`, `PayoutMethodsRelationManager`, `ReviewsRelationManager`, `TicketsRelationManager`).
  - `App\Filament\Resources\UserResource` (`/admin/users`) is scoped strictly to regular buyers (`where('role', 'customer')`).
- **Admin 1-Click Prompts.chat Importer**: `App\Filament\Resources\ProductResource\Pages\ListProducts` includes the `importPromptsChat` (`Import from Prompts.chat`) header action modal with import limit (`50`, `200`, `500`, `all`), pricing mode (`free`, `paid`, `mixed`), and image downloading toggle (`fast` mode default).
- **Vendor Dashboard Routing**: Register a custom `Dashboard` page (`App\Filament\Vendor\Pages\Dashboard`) with `protected static string $routePath = '/dashboard';` and `protected static ?string $slug = 'dashboard';` so the dashboard URL is `/vendor/dashboard`, and add `Route::redirect('/vendor', '/vendor/dashboard')` in `routes/web.php`.
- **Dark Theme**: Admin panel sets `->darkMode(true, isForced: true)` with a render hook that injects `document.documentElement.classList.add("dark")`; the Vendor panel sets `->darkMode(true, isForced: false)` (theme switcher available) while `public/css/filament/theme.css` still forces the Deep Charcoal (`#0B0F19`) background, Slate cards (`#111827`) and Emerald accents (`#10B981`) styling globally. Both panels use `->sidebarCollapsibleOnDesktop()`.
- **Singleton Profile Page**: `/vendor/profile` is a parameterless custom page (`App\Filament\Vendor\Pages\Profile`) bound to `auth()->user()` with unified `#0B0F19` / `#111827` dark FinTech header card, 4 KPI cards, **Profile Settings / Storefront Preview** switcher, and 5 tabs (Public Profile, Personal & Location, KYC, Storefront, Security). Always link with `Profile::getUrl(panel: 'vendor')` — the old `VendorProfile` page and its `{id}` / `{seller_code}` parameters were removed in Phase 25 (`/vendor/vendor-profile` only 302-redirects). Keep the sidebar `$navigationLabel` (`Profile & Verification`) and the `VendorPanelProvider::userMenuItems()` label (`Verification Status (…)`) textually distinct — two links to the same URL must never share accessible text (duplicate-link audit rule).
- **Dynamic 7-Day Sparklines**: `VendorStatsOverview` embed mini sparkline line charts dynamically calculated from daily aggregates.
- **Visual Charts**: `VendorRevenueChart` (Gross Sales vs Net 80% Vendor Cut area chart) and `VendorSalesDistributionChart` (AI Model breakdown doughnut chart).
- **Admin KYC Moderation**: `VendorResource` and `UserResource` feature inline **View ID Document Modal** and 1-click **Approve KYC** / **Reject KYC** (with reason note dialog).
- **Categories (admin-only)**: the `categories` table is a self-referencing tree (`parent_id` + `type`). Only `App\Filament\Resources\CategoryResource` exposes management (auto-slug from `name`, Category Level select) — the vendor panel must stay free of category CRUD, vendors only create categories inline via `Category::firstOrCreate` in `UploadPrompt`. Keep taxonomy values in sync with the `category` / `sub_category` / `class_category` string columns on `products`.
- **Site Settings**: global editable content lives in `site_settings` and is read through `SiteSetting::get($key, $default)` / written with `SiteSetting::set($key, $value)`. Adding a key means updating the `ManageSiteSettings` form, `database.md` §K and this document.
- **Account Moderation**: use `User::isBanned()` (backed by `is_banned` + `ban_reason`) and `is_suspended` for any new entry point; `AuthController` rejects banned or suspended users on login.
- **First-Time Onboarding & Decoupled KYC Middleware (`VendorPanelProvider::authMiddleware()`)**:
  - `App\Http\Middleware\EnsureVendorOnboardingCompleted` routes new vendors (`onboarding_completed_at === null`) to `/vendor/onboarding` (`App\Filament\Vendor\Pages\VendorOnboarding`) before accessing other `/vendor/*` routes, and redirects already-onboarded vendors away from `/vendor/onboarding` to `/vendor/dashboard`.
  - `App\Http\Middleware\EnsureVendorIsVerified` enforces account suspension/ban checks while granting unverified vendors full operational access across all 10 Vendor Panel pages (KYC approval only gates the Verified Seller Badge `✓`). Neither middleware is aliased in `bootstrap/app.php`.
- **Unified Centralized Auth & Panel Providers**: Both `AdminPanelProvider` and `VendorPanelProvider` share `authGuard('web')` and have their standalone `->login()` calls decommissioned. `App\Http\Middleware\RedirectToCentralLogin` intercepts unauthenticated panel requests and routes them to `route('login')`. Fallback routes `/admin/login` and `/vendor/login` safely redirect to `/login` (or respective dashboard if authenticated) while preserving `filament.admin.auth.login` and `filament.vendor.auth.login` route names.

---

## 7. Quick Preview Modal & Interactive Prompt Engine Patterns

### 7A. Quick Preview Modal Alpine.js Pattern
```html
<!-- Trigger in product-card.blade.php: -->
<img @click="$dispatch('open-quick-preview', {
    title: '{{ addslashes($product->title) }}',
    coverUrl: '{{ $product->cover_image_url }}',
    price: '{{ number_format($product->price, 2) }}',
    aiModel: '{{ addslashes($product->ai_model) }}',
    url: '{{ route('products.show', $product->slug) }}',
    productCode: '{{ $product->product_code }}',
    favoriteUrl: '{{ route('product.favorite', $product) }}',
    isFavorited: favorited
})" />

<!-- Listener in layouts/app.blade.php: -->
<div x-data="quickPreviewModal()" @open-quick-preview.window="openModal($event.detail)">
    ...
</div>
```

### 7B. Interactive Prompt Engine & Variable Parser Pattern (`resources/views/products/partials/interactive-prompt-engine.blade.php`)
- **Inclusion Rule**:
  - In `resources/views/products/show.blade.php`: rendered **only** when `$isUnlocked` is `true` (`$product->isFree()` or the logged-in buyer owns a `paid` order for `$product`). Unpurchased paid prompts (`price > 0`) never expose `prompt_text` in the DOM.
  - In `resources/views/products/reveal.blade.php`: always rendered for verified `paid` order tokens.
- **Supported Variable Tokens**:
  - `${variable_name:default_value}` — pre-populates input with `default_value` and substitutes live.
  - `${variable_name}` — empty input with placeholder `Enter variable_name...`; falls back to `${variable_name}` until filled.
  - `[Variable Name]` — bracket variable syntax (ignores numeric indices and markdown links `[label](url)`).
- **Direct AI Launch Buttons**:
  - `Open in ChatGPT` → `https://chatgpt.com/?q=` + `encodeURIComponent(compiledPrompt)`
  - `Open in Claude` → `https://claude.ai/new?q=` + `encodeURIComponent(compiledPrompt)`
  - `Open in Perplexity` → `https://www.perplexity.ai/search?q=` + `encodeURIComponent(compiledPrompt)`

### 7C. Artisan CLI Commands Reference
```bash
# Import open-source prompts from f/prompts.chat (JSON + CSV fallback):
php artisan prompts:import-community --limit=200 --pricing=free
php artisan prompts:import-community --limit=all --pricing=mixed --fast

# Pre-deployment security & configuration audit:
php artisan go-live:check

# Emergency Admin TOTP 2FA reset:
php artisan admin:reset-2fa admin@promptery.com
```

---

## 8. Canonical Routes & Documentation Sync Checklist

### 8.1 Canonical Route Table (verification source: `routes/web.php`)
| Method | URI | Name / Handler | Notes |
| :--- | :--- | :--- | :--- |
| GET | `/` | `products.index` | Sectioned marketplace index |
| GET | `/product/{product}` | `products.show` | `Product::resolveRouteBinding()` → slug / `PRD-XXXXXX` / numeric id; unlocks Interactive Prompt Engine for free (`$0.00`) or purchased prompts |
| GET | `/seller/{user:username}` | `seller.show` | **Username only** — numeric and `VND-XXXXXX` URLs return 404 (e.g., `/seller/promptschat`, `/seller/demo-vendor`) |
| POST | `/seller/{user:username}/follow` · `/review` | `seller.follow` · `seller.review` | `auth` |
| POST | `/product/{product}/favorite` · `/review` | `product.favorite` · `product.review` | `auth` |
| GET | `/prompt/reveal/{token}` · `/prompt/download/{token}` | `prompt.reveal` · `prompt.download` | Requires a `paid` order token; includes Interactive Prompt Engine |
| GET/POST | `/chat/messages` · `/chat/send` | `chat.messages` · `chat.send` | JSON live chat (`SupportChatController`) |
| GET/PUT | `/my-library`, `/customer/purchases`, `/my-favorites`, `/following`, `/customer/profile` | `customer.*` | `auth` (`/customer/purchases` aliases `customer.library`) |
| GET/POST | `/checkout/{product}` | `checkout` | Accepts optional `coupon_code`; invalid/expired coupons flash an error and abort |
| GET | `/checkout/success` | `checkout.success` | Stripe return URL |
| GET | `/vendor/kyc/preview/{file}` | `vendor.kyc.preview` | `auth` — owner-or-admin private KYC file (base64 path) |
| GET/POST | `/login`, `/register` · `/admin/login`, `/vendor/login` | `AuthController` / `filament.*.auth.login` | Single centralized login (`/login`) with `#0B0F19` dark theme; `/admin/login` & `/vendor/login` are decommissioned fallback redirects |
| POST | `/api/stripe/webhook` | `StripeWebhookController@handleWebhook` | CSRF-exempt, signature-verified; increments coupon `used_count` |
| GET | `/vendor/onboarding` | `filament.vendor.pages.vendor-onboarding` | 3-step first-time Vendor Onboarding Survey & Store Setup Wizard (`EnsureVendorOnboardingCompleted`) |
| GET | `/vendor/dashboard`, `/vendor/upload`, `/vendor/products`, `/vendor/sales-and-earnings`, `/vendor/payouts`, `/vendor/coupons`, `/vendor/reviews`, `/vendor/followers`, `/vendor/tickets`, `/vendor/profile` | `filament.vendor.*` | 10 modular Vendor Panel pages & resources across 4 navigation groups (`Main`, `Shop Management`, `Finances`, `Community & Support`) |
| GET | `/vendor`, `/vendor/billing`, `/vendor/vendor-followers`, `/vendor/vendor-reviews`, `/vendor/my-prompts`, `/vendor/vendor-profile`, `/vendor/products/create` | redirects | → `/vendor/dashboard`, `/vendor/payouts`, `/vendor/followers`, `/vendor/reviews`, `/vendor/products`, `/vendor/profile`, `/vendor/upload` |
| GET | `/admin/vendors` · `/admin/vendors/{record}` | `filament.admin.resources.vendors.*` | Dedicated Vendor Control & 360° Seller Inspection (`VendorResource`) |
| GET | `/admin/payouts` | `filament.admin.resources.payouts.index` | Admin Withdrawal & Payout Management (`WDR-XXXXXX` processing, completion & balance refund) |
| GET | `/admin/products` | `filament.admin.resources.products.index` | Admin Prompts catalog + 1-Click `Import from Prompts.chat` modal |
| GET | `/admin/orders` | `filament.admin.resources.orders.index` | Orders & Refunds ledger (Filament admin resource) |

### 8.2 Drift Checklist — run before committing anything that touches code
1. **Route changed?** → update §8.1, the URL list in `README.md` and `architecture.md` §3B.
2. **Class/page renamed or made singleton/parameterized?** → grep the old name everywhere: `grep -rn OldName app resources routes *.md`.
3. **Migration added?** → update `database.md` (table/column) and add a `phases.md` entry.
4. **New `.env` key?** → mirror it in `.env.example` and state whether it is required for local dev.
5. **New dependency/extension?** → update the extension list in `README.md` + `architecture.md`.
6. **New/renamed Filament nav item or user-menu item?** → confirm no two links to the same URL share accessible text (duplicate-link audit rule in §6) and update `README.md` + `architecture.md`.
7. **Verify against reality, not memory:** `php artisan route:list`, `php -m`, `php artisan about`.