# Architecture

## Principles

1. **Commerce never depends on marketing.** Orders, payments and stock work even if email, CRM, AI or analytics fail.
2. **Server is the source of truth.** Prices, discounts, points, stock and payment status are always recalculated or verified server-side.
3. **Ledgers, not counters.** Stock (and, from Phase 3, points) change only through append-only ledgers.
4. **Shared hosting first, scale later.** Database queue/cache/session today; each is a config swap to Redis/S3/workers later.
5. **Thin controllers and components.** Business logic lives in `app/Services` and `app/Actions`; Blade and Livewire only present.

## Layout

```
app/
  Actions/            single-purpose write operations (SaveProduct, SaveAddress, SaveCoupon…)
  Enums/              backed enums for every status/type column
  Events/ Listeners/  domain events (CustomerRegistered, …) and their subscribers
  Exceptions/         domain exceptions with customer-facing messages
  Http/Controllers/   storefront controllers (Store/), base controller
  Http/Middleware/    admin gate, suspended-account guard, security headers
  Livewire/           interactive UI: Store/, Account/, Admin/
  Models/             Eloquent models (prices/stock are not mass-assignable)
  Policies/           model policies delegating to role gates
  Services/
    Audit/            AuditLogger
    Commerce/Catalog  ProductSearch (MySQL FULLTEXT / LIKE)
    Commerce/Inventory InventoryService (ledger, reservations, bundles)
    Commerce/Pricing  PriceResolver (what it costs now), PriceManager (writes + history)
    Settings/         SettingsService (DB overrides → config defaults)
    Analytics/        report queries for admin
  Support/            ValueObjects (Money), Seo (structured data), helpers
  View/               class components (ProductCard) and view composers
resources/views/
  components/ui/      design-system Blade components (button, input, swatch, modal…)
  components/layouts/ store, admin, account, auth shells
  store/ account/ auth/ livewire/
routes/  web.php (storefront) · admin.php (/admin) · api.php (/api/v1) · webhooks.php (/webhooks)
```

## Key decisions

| Decision | Why |
|---|---|
| Money as integer **kobo** (`unsignedBigInteger`) + `Money` value object | No floating-point drift. ₦12,000 = `1200000`. |
| Hair colours are a **`colours` table** with accent tokens | No colour is hard-coded; adding "Orange" is data entry. The storefront re-themes from `--acc*` CSS variables. |
| **Bundles hold no stock** — `bundle_items` link to component variants | One source of truth for physical units; bundle availability = min(component ÷ qty). |
| **Reservations** (`inventory.reserved`) separate from ledgered `on_hand` | Unpaid checkouts hold stock without polluting the ledger; payment commits, failure/expiry releases. Rows are locked (`SELECT … FOR UPDATE`) in id order to prevent overselling and deadlocks. |
| **Lowest price wins** in `PriceResolver` | Base, manual sale price and every live price rule (variant / product / colour target) are compared; simple to reason about and audit. |
| **Settings** in DB with config fallback | Admins change business rules without deploys; storefront still works if DB/cache is down. |
| Fortify (headless) + own Blade views | Standard Laravel auth without a starter kit's UI or JS framework. |
| Livewire for admin and interactive storefront parts; plain Blade elsewhere | SEO-friendly pages, no SPA build in production. |
| Fonts self-hosted at **build** time | No runtime Google dependency; includes the ₦ glyph (latin-ext). |
| Cached values are arrays/scalars only | Laravel 13 restricts unserialising cached objects. |
| Admin returns **404** to non-staff | Doesn't advertise the admin surface. |

## Request flow examples

- **Product page**: `ProductController@show` → loads variants with colour/inventory → `PriceResolver::quote()` + `InventoryService::available()` per variant → view receives plain arrays; JSON-LD built by `StructuredData`.
- **Admin saves product**: `ProductForm` (Livewire) validates with `SaveProduct::rules()` → `SaveProduct::handle()` in a transaction → `PriceManager::setPrices()` (history + audit) → `InventoryService::receive()` for opening stock.
- **Stock adjustment**: `InventoryIndex` → `InventoryService::adjust()` (reason mandatory, row-locked, can't go negative or below reserved) → `AuditLogger`.

## Checkout and payment flow

```
Cart ──CartCalculator──▶ totals (server prices, coupon, delivery)
  │
  ▼ Checkout (Livewire) — contact, address, delivery choice only
PlaceOrder (idempotent token) ──▶ Order: awaiting_payment, stock RESERVED
  │
  ▼ PaystackService::initialize ──▶ customer pays on Paystack
  │
  ├─▶ /checkout/callback ──verify()──┐
  └─▶ /webhooks/paystack (signed) ───┴─▶ PaymentConfirmation (locks, idempotent)
                                           ├─ checks reference/amount/currency
                                           ├─ stock RESERVED → COMMITTED (ledger)
                                           ├─ coupon redemption, sales counts, clear cart
                                           └─ OrderPaid ─▶ email (queued) · later: points, referrals, creators, CRM
Scheduler: orders:expire-unpaid ── re-verify ─▶ confirm, or cancel + release stock
```

Order status changes, cancellations and refunds go through `OrderService` (state machine in `OrderStatus::allowedNext()`).

## Loyalty, referrals, quiz

- `PointsService` is the only writer of points. Keys like `order:42:purchase`, `referral:7` make every award idempotent; `reverse()` uses the same keys to claw back exactly what was given.
- `LoyaltySubscriber` listens to `CustomerRegistered`, `OrderPaid`, `OrderRefunded`. Each step is wrapped so a loyalty bug can never fail a payment.
- Rewards become personal single-use coupons, so checkout needed no special path — `CouponValidator` gained `variant_ids` / `max_units` conditions for product rewards.
- Referral attribution is stored server-side (`referral_visits`, `referrals`, `orders.attribution`); the cookie only carries the code until sign-up/checkout.
- `QuizEngine` sums per-colour weights from the database; questions, colours and results are all data.

## AI try-on

- `App\Services\AI\TryOnService` owns the whole lifecycle (guard → create → process/complete → save/share/delete → cleanup → purchase attribution). Livewire pages (`Store\TryOn`, `Store\ColourBoard`, `Account\SavedLooks`) share `Concerns\HandlesTryOn` and stay thin.
- Providers implement `App\Contracts\AIImageProviderInterface`; `ProviderManager` resolves the configured one. Generation runs via `dispatchAfterResponse` by default — no worker needed on cPanel — with `wire:poll` on the page.
- `AiSubscriber` listens to `OrderPaid` (records `ai_purchase` from `orders.attribution`) and `Login` (moves guest previews into the account). See [AI.md](AI.md).

## Wall & challenges

- `Community\CommunityService` (submit, own deletes, private storage), `Community\ModerationService` (approve / reject / feature / delete, audit, point reversals) and `Community\ChallengeService` (eligibility, join, entry limits, votes, winner). Livewire components under `Store\Community`, `Account\WallPosts` and `Admin\Community` stay thin.
- A challenge entry is a Wall post with `challenge_id` — one moderation pipeline for everything.
- `CommunitySubscriber` turns `UGCApproved` into points (once per post, once per challenge). `UGCSubmitted` and `ChallengeJoined` are emitted for the Phase 7 campaign engine.

## Creator programme

- `Creators\CreatorProgramme` (applications, approval → profile + coupon + link, status, rates, safe links), `Creators\CreatorAttribution` (click capture and lookup), `Creators\CreatorCommissions` (conversion + commission ledger, refunds, hold period, payouts) and `Creators\CreatorStats` (dashboards, leaderboard).
- A creator code is an ordinary coupon with `creator_profile_id`, so discounts reuse the cart pipeline; a click ID travels in `orders.attribution`.
- `CreatorSubscriber` follows the order lifecycle: `OrderPaid` → `recordSale`, `OrderRefunded` / `OrderCancelled` → `adjustForRefund`. Failures are reported, never thrown into commerce.

## Automation: campaigns, CRM, email

```
domain event ──▶ AutomationSubscriber ──▶ EventBridge::translate() ──▶ AutomationEvent(s)
                   (registered last)            │                         ├─▶ Outbox::recordForCrm()  ─▶ outbox_messages ─▶ outbox:dispatch (cron) ─▶ CRM driver
                                                │                         └─▶ CampaignEngine::handle() ─▶ conditions ─▶ actions (run log)
```

- `EventBridge` is the only class that knows both domain events and trigger names; `OrderPaid` fans out to `order_paid`, `first_purchase` and one `product_purchased` per line.
- Add a trigger: map it in `EventBridge` and list it in `config/campaigns.php`. Add an action: implement `Automation\Actions\CampaignAction` and register it. Add a CRM: implement `Crm\CrmDriver` and add it to `config/crm.php`.
- Emails are queued Laravel notifications (`OrderUpdate`, `CustomerEmail`, `CreatorUpdate`, `CampaignEmail`); `LogEmails` records outcomes. The channel list in each notification is where WhatsApp/SMS would plug in.

## Operations

- **One cron entry** → `routes/console.php`; each task records its last success (`schedule:last:*` cache keys) for *Admin → System* and `beauthentic:doctor` (`App\Services\Ops\HealthChecks`).
- **Backups**: `App\Services\Backups\BackupService` — PHP SQL dump (MySQL/SQLite), ZipArchive media, AES-256, off-site disk, retention.
- **Caching**: `App\Support\Cache\CatalogCache` — versioned keys, bumped by model events on catalogue changes; caches IDs, never models, so prices and stock stay live.
- **Analytics**: live queries plus `daily_metrics` rollups for completed days (`analytics:aggregate`).
- **Errors**: standalone `resources/views/errors/*`; `resources/js/app.js` intercepts Livewire failures; `RedactSecrets` log tap; `ErrorLog` surfaces recent errors in admin.

## Extending the dashboard

Phases register panels in `config/admin.php` (`dashboard_panels`); each class returns `['view' => …, 'data' => …]`.
