# Apex Admins — System Architecture Document

**Version:** 1.0  
**Date:** 2026-06-27

---

## 1. Technology Stack

| Layer | Technology |
|-------|------------|
| Backend Framework | Laravel 13.x |
| Language | PHP 8.5 |
| Database | MySQL 8 / MariaDB 10.11+ |
| Cache | Redis |
| Queue | Laravel Queue (Redis driver) |
| Scheduler | Laravel Scheduler (cron) |
| Search | Laravel Scout (database driver) |
| Frontend Templates | Blade |
| Asset Bundler | Vite |
| CSS | Tailwind CSS 4 |
| JS (Reactive) | Alpine.js 3 |
| Animation | GSAP 3 |
| Carousel | Swiper.js 11 |
| Storage | Local filesystem + S3-ready disks |

---

## 2. Architecture Pattern: Modular Monolith

Single deployable Laravel application with feature modules under `app/Modules/`. Each module owns its models, migrations, controllers, services, repositories, policies, and views.

### 2.1 Module List

| Module | Responsibility |
|--------|----------------|
| Admin | Dashboard, admin layout, shared UI |
| Users | Authentication, RBAC |
| Settings | Global settings, theme tokens |
| Media | Upload, folders, optimization |
| SEO | Meta, schema, sitemaps, audit |
| Pages | CMS pages, section builder |
| Blog | Posts, categories, tags |
| Services | Service catalog |
| Industries | Industry pages |
| Locations | Location hub/pages |
| Leads | Forms, submissions |
| CaseStudies | Case study CRUD |
| Careers | Jobs, applications |
| Academy | Courses, lessons |
| CRM | Lead pipeline, Calendly |
| Analytics | Event tracking |
| Contact | Contact page config |
| Menus | Navigation |
| Redirects | 301/302 manager |

### 2.2 Layered Architecture (Per Module)

```
HTTP Request
    → Middleware (auth, permission, redirect)
    → Controller (thin)
    → Form Request (validation)
    → Service (business logic)
    → Action (single-purpose operations)
    → Repository (data access)
    → Model (Eloquent)
    → Database
```

### 2.3 Cross-Cutting Concerns

| Concern | Implementation |
|---------|----------------|
| Authorization | Laravel Policies + `permission` middleware |
| Validation | Form Request classes |
| DTOs | Spatie Laravel Data or plain PHP readonly classes |
| Events | Domain events + queued listeners |
| Caching | Redis via `Cache` facade, tagged caches per module |
| Activity Log | `activity_log` table + `LogsActivity` trait |

---

## 3. Request Flow (Public Page)

```
GET /hire/virtual-assistants
  → RedirectMiddleware (check redirects table)
  → Web Route → HireRoleController@show
  → HirePageService::getBySlug('virtual-assistants')
    → Cache remember (key: hire:virtual-assistants)
    → HireRoleRepository::findPublishedWithRelations()
    → SettingsService::getPublic()
    → SeoMetaResolver::resolve($hireRole)
    → SchemaBuilder::forHireRole($hireRole)
  → View: pages.hire.show with sections JSON rendered via Blade components
  → Response with Cache-Control headers
```

---

## 4. Request Flow (Admin)

```
GET /admin/services/1/edit
  → auth:admin middleware
  → permission:services.update middleware
  → Admin ServiceController@edit
  → ServiceRepository::findOrFail(1)
  → View with SEO audit sidebar partial
```

---

## 5. Module Autoloading

`composer.json` PSR-4:
```json
"Apex\\Modules\\": "app/Modules/"
```

Each module registers via `ModuleServiceProvider` extending base `Apex\Modules\ModuleServiceProvider`:
- Loads migrations from `Database/Migrations`
- Loads views from `Resources/views` with namespace
- Registers routes from `Routes/web.php` and `Routes/admin.php`
- Binds repositories in `register()`

Central `ModuleRegistry` in `AppServiceProvider` bootstraps all modules.

---

## 6. Database Strategy

- All migrations live in module folders, loaded by module providers
- Migration order controlled by timestamp prefixes and dependency seeder
- Polymorphic relations use `morphMap()` for short type names
- Soft deletes on content models (pages, posts, services, etc.)
- `status` enum: draft, published, archived

---

## 7. Caching Strategy

| Cache Key Pattern | TTL | Invalidation |
|-------------------|-----|--------------|
| `settings:public` | 24h | On settings update |
| `settings:theme_css` | 24h | On branding update |
| `page:{slug}` | 1h | On page save |
| `menu:{location}` | 1h | On menu save |
| `sitemap:{type}` | 6h | On content publish + scheduler |

Full-page cache (Phase 10): Redis store for anonymous GET requests, bust on content update.

---

## 8. Queue Jobs

| Job | Queue | Purpose |
|-----|-------|---------|
| OptimizeMediaJob | media | WebP/AVIF generation |
| RunSeoAuditJob | seo | Calculate SEO score |
| RegenerateSitemapJob | default | Rebuild sitemap cache |
| SendFormNotificationJob | mail | Email on form submit |
| SendLeadAssignmentJob | mail | Notify sales rep |

---

## 9. Security Architecture

- Admin guard separate from web guard
- CSRF on all forms
- Rate limiting on login, form submit, API webhooks
- File upload: MIME whitelist, max size, virus scan hook ready
- XSS: Blade auto-escape, `{!! !!}` only for trusted admin HTML
- SQL injection: Eloquent only, no raw user input in queries
- Password hashing: bcrypt/argon2 via Laravel defaults
- `.env` for secrets; never in repository

---

## 10. Deployment Architecture

```
[Browser] → [Nginx/Apache] → [PHP-FPM 8.5] → [Laravel App]
                                    ↓
                              [MySQL ronnie_apex]
                              [Redis cache + queue]
                              [Local/S3 storage]

Cron: * * * * * php artisan schedule:run
Supervisor: php artisan queue:work redis --sleep=3
```

Document root: `public/`  
Existing `.htaccess` at project root redirects to `public/` if needed.

---

## 11. API & Webhooks

`routes/api.php`:
- `POST /api/webhooks/calendly` — booking confirmation → create/update lead
- `POST /api/analytics/events` — batch event ingestion (CSRF exempt, rate limited)
- `POST /api/forms/{slug}` — AJAX form submission

All webhooks verify signatures where applicable.

---

## 12. Error Handling

- Custom 404/500 Blade pages with branding from settings
- Admin: flash messages via session
- Public: toast notifications via Alpine
- Logging: Laravel log channels, separate `seo` and `media` channels optional

---

## 13. Testing Strategy

- **Unit:** Services, Actions, SEO audit calculators, SchemaBuilder
- **Feature:** Admin CRUD, form submission, public page render, sitemap generation
- **Browser (optional):** Dusk for critical conversion flows
- **Static analysis:** Larastan level 5+
- **Style:** Laravel Pint

---

## 14. Future Scalability Path

- Scout → Meilisearch when content exceeds 10k records
- Read replicas for MySQL (config swap)
- CDN for static assets and optimized images
- Horizontal scaling: stateless app servers + shared Redis/DB/S3
