# GRINDO — Backend Architecture & Foundation

**Stack (as installed):** Laravel 11.9, PHP 8.2 (repo requires `^8.2`), MySQL, Sanctum 4.3, Spatie Permission 6.25, Spatie Activitylog 4.12, Intervention Image 3.11, Yajra DataTables, Maatwebsite Excel, Blade + Velzon Admin.

This document is the contract every future module (Products, Categories, Collections, Users, Enquiries, CMS, ...) must follow. It describes a foundation that has been **built and verified**, not just proposed — every class, config file and route referenced below already exists in the repo and has been smoke-tested (`/api/v1/health` returns 200, existing admin/frontend routes are unaffected).

> No CRUD modules were created as part of this work. Everything here is infrastructure: base classes, contracts, config, middleware, exception handling, and folder scaffolding.

---

## 0. Starting State & Key Decisions

The repo was not a blank Laravel skeleton — it already had a working legacy admin panel (`app/Http/Controllers/Backend/*`) with its own conventions, plus a set of Blade frontend pages already built for GRINDO (home, collections, product-details, cart, wishlist, profile, contact-us, terms/privacy/shipping). Three decisions shaped everything below:

| Decision | Choice | Why |
|---|---|---|
| Laravel version | **Stayed on 11.9** (spec asked for 12) | Confirmed with the project owner; installed PHP is 8.2.12 and the existing `Backend/*` modules are validated against 11.9. All patterns below are 12-compatible so upgrading later is a `composer require laravel/framework:^12` away, not a rewrite. |
| Scope | **Design + physically scaffold** the foundation, not just document it | The brief explicitly says "design and build". No Product/Category/User CRUD was touched. |
| Roles/Permissions | **Spatie Permission installed fresh, legacy system left untouched** | See §10.2 — a real table-name collision was found and resolved by namespacing Spatie's tables (`rbac_*`). The two systems coexist until a dedicated migration module retires the legacy one. |

---

## 1. Layer Responsibilities

```
Request
  │
  ▼
Middleware (auth, role, throttle, localize, force-json)
  │
  ▼
Route  →  FormRequest (validates + authorizes input)
  │
  ▼
Controller (thin — orchestrates, never contains business logic)
  │
  ▼
Service (business logic, transactions, orchestrates repositories + file
          uploads + notifications + activity logs)
  │
  ▼
Repository (the ONLY layer that talks to Eloquent / the query builder)
  │
  ▼
Model (relationships, casts, scopes, traits — no business logic)
  │
  ▼
Database
```

| Layer | Responsibility | Must NOT do |
|---|---|---|
| **Controller** | Receive the request, delegate to a Service, return a `Resource`/`ApiResponse`. One controller = one resource's HTTP surface. | Contain business logic, query the database directly, do validation beyond delegating to a FormRequest. |
| **Service** | Business rules, DB transactions (`BaseService::transaction()`), coordinates multiple repositories, triggers file uploads/notifications/events, logs. | Know about HTTP (`Request`, `response()`), format JSON. |
| **Repository** | Encapsulates Eloquent/query-builder access behind an interface (`Contracts/`). Swappable, mockable, testable in isolation. | Contain business rules or validation. |
| **Interfaces (Contracts)** | Decouple Services from concrete Eloquent implementations; bound in `RepositoryServiceProvider`. | — |
| **Models** | Relationships, casts, accessors, scopes, and opt-in traits (`HasSlug`, `HasSeo`, `HasStatus`, ...). | Business logic, direct HTTP/response concerns. |
| **Policies** | Authorization only (`can()` / `Gate`), one per model. | Validation, business rules. |
| **Observers** | React to model lifecycle events (e.g. cache-bust on save) when the logic doesn't belong in a Service transaction. | Business logic that belongs to a specific request flow — use a Service for that. |
| **Traits** | Cross-cutting, reusable model behaviour (see §18). | Anything module-specific. |
| **Helpers (`app/Support/helpers.php`)** | Small global convenience functions that just delegate to a class (never contain real logic themselves). | — |
| **Events / Listeners** | Decouple side effects (e.g. `ProductCreated` → `ReindexProductSearch`, `SendAdminNotification`) from the Service that triggers them. | — |
| **Notifications** | Multi-channel (mail/database/future push) user-facing messages. | — |
| **Jobs** | Queued, retryable units of work (image processing, bulk emails, exports). | — |
| **Console/Commands** | Scheduled/CLI operations (cache warmups, cleanup). | — |
| **Middleware** | Cross-cutting HTTP concerns (auth, role, throttle, locale). | Business logic. |
| **Providers** | Wiring: bind interfaces to implementations, register rate limiters, view composers. | Business logic. |
| **Resources (API Resources)** | Shape a Model into a JSON-safe array for `ApiResponse`. | Query the database (no lazy-loading N+1 inside a Resource). |
| **Requests (FormRequest)** | Validation rules + authorization for one action. | Business logic beyond simple conditional rules. |
| **Rules** | Reusable custom validation rules. | — |
| **Enums** | Type-safe, closed sets of values (status, role, image type...) with behaviour (`label()`, `folder()`). | — |
| **DTOs** | Typed data carriers between layers (e.g. Service ↔ Repository) when an array is too loose. | — |
| **Exports/Imports** | Maatwebsite Excel classes, one per report/import. | — |
| **Constants** | Static string/key holders that aren't a closed enum set (e.g. `CacheKeys`). | — |

---

## 2. Folder Structure (as built)

```
app/
├── Console/
│   └── Commands/                     (empty — ready for scheduled jobs)
├── Constants/
│   └── CacheKeys.php                 ✅ built
├── DTO/
│   └── BaseDTO.php                   ✅ built
├── Enums/
│   ├── StatusEnum.php                ✅ built
│   ├── RoleEnum.php                  ✅ built
│   ├── NotificationTypeEnum.php      ✅ built
│   └── ImageTypeEnum.php             ✅ built
├── Events/                           (placeholder — .gitkeep)
├── Exceptions/
│   ├── ApiException.php              ✅ built (base — message, errors, status code)
│   ├── BusinessException.php         ✅ built (422 domain-rule violation)
│   └── FileUploadException.php       ✅ built (422 upload failure)
├── Exports/                          (placeholder — .gitkeep)
├── Helpers/
│   └── Helper.php                    (legacy — untouched, still used by Backend/*)
├── Http/
│   ├── Controllers/
│   │   ├── Controller.php            (existing abstract base)
│   │   ├── HomeController.php        (existing — frontend, untouched)
│   │   ├── Backend/                  (existing legacy admin — untouched)
│   │   └── Api/
│   │       ├── Controller.php        ✅ built (base API controller, uses ApiResponser)
│   │       └── V1/
│   │           └── HealthController.php  ✅ built (proves the pipeline end-to-end)
│   ├── Middleware/
│   │   ├── Admin.php                 (existing, untouched)
│   │   ├── CheckPermission.php       (existing legacy, untouched)
│   │   ├── ForceJsonResponse.php     ✅ built
│   │   ├── Localization.php          ✅ built
│   │   └── EnsureUserHasRole.php     ✅ built (role:admin,manager — see §10.2 caveat)
│   ├── Requests/
│   │   └── BaseFormRequest.php       ✅ built
│   └── Resources/                    (placeholder — .gitkeep)
├── Imports/                          (placeholder — .gitkeep)
├── Jobs/                             (placeholder — .gitkeep)
├── Listeners/                        (placeholder — .gitkeep)
├── Mail/                             (existing — untouched)
├── Models/
│   ├── User.php                      (existing — added HasApiTokens only)
│   ├── SeoMeta.php                   ✅ built (polymorphic SEO store, see §4.6)
│   └── ... (existing legacy models — untouched)
├── Notifications/                    (placeholder — .gitkeep)
├── Observers/                        (placeholder — .gitkeep)
├── Policies/                         (existing — untouched)
├── Providers/
│   ├── AppServiceProvider.php        (existing — added rate limiter only)
│   ├── AuthServiceProvider.php       (existing — untouched)
│   ├── MailConfigServiceProvider.php (existing — untouched)
│   └── RepositoryServiceProvider.php ✅ built (interface → implementation bindings)
├── Repositories/
│   ├── Contracts/
│   │   └── BaseRepositoryInterface.php  ✅ built
│   └── Eloquent/
│       └── BaseRepository.php           ✅ built
├── Rules/                            (placeholder — .gitkeep)
├── Services/
│   ├── BaseService.php               ✅ built
│   └── ImageUploadService.php        ✅ built (Intervention Image v3 wrapper)
├── Support/
│   ├── ApiResponse.php               ✅ built (global response envelope)
│   └── helpers.php                   ✅ built (autoloaded via composer.json "files")
├── Traits/
│   ├── HasStatus.php                 ✅ built
│   ├── HasSlug.php                   ✅ built
│   ├── HasSeo.php                    ✅ built
│   ├── HasImage.php                  ✅ built
│   ├── HasUuid.php                   ✅ built
│   ├── HasActivityLog.php            ✅ built (wraps Spatie LogsActivity)
│   └── ApiResponser.php              ✅ built (controller trait)
└── ViewModels/                       (placeholder — .gitkeep)

config/
├── grindo.php                        ✅ built — brand/pagination/cache-ttl/api settings
├── upload.php                        ✅ built — disk, dimensions per image type, webp
├── seo.php                           ✅ built — SEO defaults
├── settings.php                      ✅ built — cache wrapper for the `settings` table
├── constants.php                     ✅ built — statuses/roles/permission modules as arrays
├── sanctum.php                       ✅ published
├── permission.php                    ✅ published — table names namespaced `rbac_*`
└── activitylog.php                   ✅ published

routes/
├── web.php                           (existing — untouched)
├── api.php                           ✅ built — /api/v1/* namespace
└── console.php                       (existing — untouched)
```

**Deliberately not created:** `app/Http/Controllers/Admin/` and `Frontend/` namespaces. The repo already has working conventions (`Backend/*` for admin, flat `Controllers/` for frontend). Introducing a second, empty parallel convention would confuse future developers more than it would help. **New API controllers use `Api/V1/`; new admin/frontend controllers should continue the existing `Backend/*` and flat-root conventions** until a deliberate refactor is scoped (see §20).

---

## 3. Coding Standards

### 3.1 Controllers
- One controller per resource. Methods map to REST verbs (`index`, `store`, `show`, `update`, `destroy`) or are named actions for non-CRUD operations (`status`, `bulkDelete`).
- Constructor-inject the Service, never a Repository directly.
- Every API controller extends `App\Http\Controllers\Api\Controller` (which pulls in `ApiResponser`) — never build a `response()->json()` array by hand.

```php
final class ProductController extends Controller
{
    public function __construct(private readonly ProductService $service) {}

    public function index(ProductIndexRequest $request): JsonResponse
    {
        return $this->paginated(
            $this->service->list($request->validated(), $request->integer('per_page', 15)),
            'Products retrieved successfully.',
            ProductResource::class
        );
    }
}
```

### 3.2 Repositories
- One repository per aggregate root model, extends `App\Repositories\Eloquent\BaseRepository`, implements a dedicated interface extending `BaseRepositoryInterface`.
- Bound in `RepositoryServiceProvider` as **non-singleton** (`bind`, not `singleton`) — `filter()`/`sort()` mutate internal query-builder state (see the docblock on `BaseRepository`), so a fresh instance per resolution keeps that state from leaking across requests.

```php
interface ProductRepositoryInterface extends BaseRepositoryInterface {}

class ProductRepository extends BaseRepository implements ProductRepositoryInterface
{
    public function __construct(Product $model) { parent::__construct($model); }

    public function featured(): Collection
    {
        return $this->model->newQuery()->where('is_featured', true)->get();
    }
}
```

### 3.3 Services
- One per module, extends `App\Services\BaseService`, constructor-injects its repository **interface** (never the Eloquent class).
- All writes go through `$this->transaction(fn () => ...)`.
- File uploads go through `ImageUploadService` (injected or via the `uploadImage()`/`deleteImage()` helpers).

### 3.4 Validation
- One `FormRequest` per action, extends `App\Http\Requests\BaseFormRequest`. It already returns a proper `422` JSON envelope via `ApiResponse` on API routes — never call `validate()` manually in a controller.

### 3.5 Policies
- One policy per model, registered in `AuthServiceProvider::$policies` (existing pattern, keep using it — Laravel 11's auto-discovery is not enabled here, so registration is manual and mandatory).
- Policy methods return `bool`; authorization messages belong in the policy, not the controller.

### 3.6 Resource Responses
- Every API response — success or error — goes through `App\Support\ApiResponse` (directly, via the `ApiResponser` trait, or via the `responseSuccess()`/`responseError()` helpers). Never `return response()->json([...])` ad hoc; the envelope shape is a contract (§7).

### 3.7 Exception Handling
- Domain-rule violations throw `App\Exceptions\BusinessException` (422); upload failures throw `FileUploadException` (422); anything needing a custom status/errors payload extends `ApiException`. All three are rendered centrally in `bootstrap/app.php` — controllers/services never catch them just to format a response.

### 3.8 Dependency Injection
- Type-hint interfaces, not concrete classes, in every Service/Controller constructor. Bind concrete classes in `RepositoryServiceProvider` (repositories) or `AppServiceProvider` (everything else).

### 3.9 Naming Conventions

| Element | Convention | Example |
|---|---|---|
| Namespace | `App\{Layer}\{Module?}` | `App\Services\ProductService` |
| Controller | `{Model}Controller` | `ProductController` |
| Service | `{Model}Service` | `ProductService` |
| Repository | `{Model}Repository` / `{Model}RepositoryInterface` | `ProductRepository`, `ProductRepositoryInterface` |
| Policy | `{Model}Policy` | `ProductPolicy` |
| FormRequest | `{Model}{Action}Request` | `ProductStoreRequest`, `ProductUpdateRequest` |
| Resource | `{Model}Resource` / `{Model}Collection` | `ProductResource` |
| Enum | `{Concept}Enum`, PascalCase cases | `StatusEnum::Active` |
| Event | past tense | `ProductCreated` |
| Listener | verb phrase | `SendProductCreatedNotification` |
| Job | verb phrase | `ProcessProductImage` |
| Method (query) | `get*`, `find*`, `list*` | `getFeaturedProducts()` |
| Method (command) | verb | `activate()`, `archive()` |
| Migration file | `{timestamp}_{verb}_{table}_table` | `2026_07_10_000000_create_products_table` |
| Seeder | `{Model}Seeder` | `ProductSeeder` |
| DB table | snake_case, plural | `products`, `product_categories` |
| DB column | snake_case | `meta_title`, `is_featured` |
| Route name | dot notation, versioned for API | `api.v1.products.index` |
| Route URI | kebab-case, plural | `/api/v1/product-categories` |
| Blade view | kebab-case, folder per module | `frontend.products.show` |

---

## 4. Database Strategy

### 4.1 Normalization
Third normal form as the default for transactional tables (`products`, `categories`, `orders`). Denormalize deliberately and document why when done for read performance (e.g. a cached `products.average_rating` column updated by an Observer rather than computed live).

### 4.2 Relationships & Foreign Keys
- Every foreign key uses `foreignId('x_id')->constrained()->cascadeOnDelete()` or `nullOnDelete()` — decided per relationship, never left as implicit `ON DELETE RESTRICT` by accident.
- Many-to-many junction tables are named `{singular}_{plural}` alphabetically (e.g. `product_tag`), matching Laravel convention so no explicit `table()` call is needed on the relation.

### 4.3 Indexes
- Every foreign key column is indexed (implicit via `constrained()`).
- Every column used in a `WHERE`/`ORDER BY` on a listing page (`status`, `slug`, `is_featured`, `created_at`) gets an explicit index.
- Composite indexes for common filter combinations once a module's query patterns are known (e.g. `(category_id, status)` on `products`) — added in a follow-up migration once the Products module ships, not speculatively now.

### 4.4 Soft Deletes
- Customer-facing catalog data (`Product`, `Category`, `Collection`) uses `SoftDeletes` — accidental deletes must be recoverable, and `BaseRepository::restore()`/`forceDelete()` already assume `withTrashed()` works.
- Pure logs/pivots (`activity_log`, junction tables) do **not** soft-delete.

### 4.5 Audit & Status Fields
- Every domain table gets `status` (tinyint, see `StatusEnum`), `created_at`, `updated_at`. Models that need "who did this" use `HasActivityLog` (§18.6) — Spatie's Activitylog already records the causer, so a manual `created_by`/`updated_by` column pair is only added when it must be queried directly (e.g. filtering "products I created").

### 4.6 IDs: Auto-increment + selective UUID
- Primary keys stay **auto-increment bigint** everywhere (fast joins, small indexes, matches the existing schema). A separate public-facing `uuid` column (via the `HasUuid` trait) is added only where the internal ID must never be guessable or exposed (e.g. a future order-tracking reference), not by default.

### 4.7 Timestamp Strategy
- `created_at`/`updated_at` on every table via `$table->timestamps()`. `deleted_at` added only where §4.4 applies. Application timezone is `Asia/Kolkata` (`.env` `APP_TIMEZONE`); timestamps are stored in UTC in the DB (Laravel default) and converted on output via `formatDate()`.

### 4.8 Image Storage Strategy
Two systems coexist deliberately during the transition (see §9 for full detail):
- **Legacy** (`app/Helpers/Helper.php`): writes directly to `public/uploads/{folder}` — still used by `Backend/*` (Gallery, Testimonials, etc.). Untouched.
- **New foundation** (`ImageUploadService`): writes via the `Storage` disk abstraction to `storage/app/public/{folder}` (symlinked to `public/storage`, already run — see §9). Every new module (Products, Categories, Banners) uses this one.

### 4.9 SEO Tables
Built now (`seo_meta` — migration `2026_07_02_101500_create_seo_meta_table.php`): a **polymorphic** table (`seoable_id`, `seoable_type`) so any future model (`Product`, `Category`, `Collection`, `Page`) gets `meta_title`, `meta_description`, `meta_keywords`, OG fields, `canonical_url`, `is_indexable` for free by adding `use HasSeo;` — no per-model SEO columns needed. This is separate from the existing `meta_tags` table (`App\Models\MetaTag`), which is page-level (keyed by a `page` string) and continues to serve the legacy CMS pages (Terms, Privacy, Shipping) unchanged.

### 4.10 Settings Table
Existing `settings` (key-value) table stays as the single source for site-wide config (already consumed by the `frontend.*` view composer in `AppServiceProvider`). `config/settings.php` defines the cache key/TTL a future `SettingsService` should wrap it with — no schema change needed.

---

## 5. Base Repository — `app/Repositories/Eloquent/BaseRepository.php`

Implements `BaseRepositoryInterface` (`app/Repositories/Contracts/BaseRepositoryInterface.php`):

```php
all(array $columns = ['*']): Collection
paginate(int $perPage = 15, array $columns = ['*']): LengthAwarePaginator
find(int|string $id, array $columns = ['*']): ?Model
findOrFail(int|string $id, array $columns = ['*']): Model
create(array $data): Model
update(int|string $id, array $data): Model
delete(int|string $id): bool
restore(int|string $id): bool
forceDelete(int|string $id): bool
search(string $term, array $columns = []): Collection      // OR-LIKE across $columns, or $model->searchable
filter(array $filters): static                             // fluent — mutates internal query builder
sort(string $column, string $direction = 'asc'): static     // fluent
bulkDelete(array $ids): int
bulkUpdate(array $ids, array $data): int
status(int|string $id, int $status): Model
```

**Usage pattern**: `filter()`/`sort()` are meant to be chained immediately before `paginate()`/`all()` in the same call: `$repo->filter($filters)->sort('name')->paginate(15)`. Module repositories add domain-specific methods (`featured()`, `bySlug()`) on top — never bypass the base methods for a use case they already cover.

## 6. Base Service Layer — `app/Services/BaseService.php`

```php
list(array $filters = [], int $perPage = 15)     // → $repository->filter()->paginate()
find(int|string $id)                             // → findOrFail
create(array $data)                              // wrapped in transaction()
update(int|string $id, array $data)              // wrapped in transaction()
delete(int|string $id): bool                     // wrapped in transaction()
bulkDelete(array $ids): int                      // wrapped in transaction()
toggleStatus(int|string $id, int $status)        // wrapped in transaction()
transaction(Closure $callback): mixed            // DB::transaction() + Log::error() on failure, re-throws
```

Module services extend this and override `create()`/`update()` to add file uploads, notification dispatch, or activity logging **inside the same transaction closure**:

```php
class ProductService extends BaseService
{
    public function __construct(
        ProductRepositoryInterface $repository,
        private readonly ImageUploadService $images,
    ) { parent::__construct($repository); }

    public function create(array $data): Product
    {
        return $this->transaction(function () use ($data) {
            if (isset($data['image'])) {
                $upload = $this->images->upload($data['image'], config('upload.folders.product'), config('upload.dimensions.product'));
                $data['image'] = $upload['path'];
            }
            return $this->repository->create($data);
        });
    }
}
```

## 7. Global Response Structure — `app/Support/ApiResponse.php`

Every API response — success or failure — has this exact shape (verified live at `/api/v1/health`):

```jsonc
// success
{
  "success": true,
  "message": "Products retrieved successfully.",
  "data": [ /* ... */ ],
  "errors": null,
  "pagination": { "current_page": 1, "per_page": 15, "total": 128, "last_page": 9, "from": 1, "to": 15 },
  "meta": null,
  "status": 200
}

// validation error (422) — produced automatically by BaseFormRequest
{
  "success": false,
  "message": "Validation failed.",
  "data": null,
  "errors": { "name": ["The name field is required."] },
  "pagination": null,
  "meta": null,
  "status": 422
}
```

`ApiResponse::success()/error()/paginated()`, the `ApiResponser` controller trait, and the `responseSuccess()`/`responseError()` global helpers all produce this same shape — pick whichever is most convenient at the call site, never hand-roll a `response()->json()` array.

## 8. Global Exception Handling — `bootstrap/app.php` (`withExceptions`)

Centrally rendered to the §7 envelope **only when the request is `api/*` or expects JSON** (`shouldRenderJsonWhen`); Blade/admin routes keep Laravel's normal HTML error pages untouched.

| Exception | Status | Notes |
|---|---|---|
| `ValidationException` | 422 | `errors` = field → messages map |
| `AuthenticationException` | 401 | Unauthenticated (Sanctum) |
| `AuthorizationException` | 403 | Policy/Gate denial |
| `ModelNotFoundException` / `NotFoundHttpException` | 404 | Unified "Resource not found." message |
| `QueryException` | 500 | Reported to logs; message hidden unless `APP_DEBUG=true` |
| `App\Exceptions\ApiException` (and subclasses `BusinessException`, `FileUploadException`) | custom | Message/errors/status carried by the exception itself |
| Anything else (`Throwable`) | 500 | Reported to logs; generic "Server error." unless debug mode |

Verified: hitting an unregistered `api/v1/*` route returns `{"success":false,"message":"Resource not found.",...,"status":404}`, not Laravel's default HTML 404 page.

## 9. File Upload Architecture

**New foundation (`ImageUploadService`, `config/upload.php`):**

```
Storage::disk('public')
└── {folder}/                     e.g. products/, categories/, banners/
    ├── {uuid}.webp                (resized to config('upload.dimensions.{type}.resize'))
    └── thumbnails/
        └── {uuid}.webp            (only if a thumbnail size is configured)
```

- Driver: Intervention Image v3 (`gd` by default, `imagick` via `IMAGE_DRIVER` env).
- Every upload is converted to **WebP** by default (`UPLOAD_CONVERT_WEBP`, toggleable per-call).
- Resize/thumbnail dimensions are **per image type**, defined once in `config('upload.dimensions')` — a module never hardcodes pixel sizes.
- `deleteImage($path)` (helper) / `ImageUploadService::delete()` is called from `HasImage`'s `deleting` model event automatically — a model using `use HasImage;` never needs to remember to clean up its file.
- `php artisan storage:link` has already been run — `public/storage` → `storage/app/public` is live.

**Legacy (`app/Helpers/Helper.php`)**: untouched, still writes straight to `public/uploads/{folder}` for `Backend/*` modules (Gallery, Testimonials, Careers). Do not mix the two within one module — a module either fully adopts the new `ImageUploadService` (recommended for everything new) or stays on the legacy helper if it's extending an existing legacy module.

**Validation**: `config('upload.max_size')` and `config('upload.allowed_mimes')` are the single source of truth for `FormRequest` rules (`image|mimes:jpg,jpeg,png,webp|max:5120`) — reference the config, don't repeat the numbers in every request class.

## 10. Security Architecture

### 10.1 Authentication
- **Sanctum** installed and wired: `User` now uses `HasApiTokens` (`app/Models/User.php`). Token-based auth is ready for `routes/api.php` (`->middleware('auth:sanctum')`) and the future mobile API. The existing session-based `Backend/AuthController` admin login is untouched and unaffected.

### 10.2 Authorization — the Roles/Permissions conflict (read this before building the Roles module)
A real collision was found and resolved: the legacy schema already has a `permissions` table (`App\Models\Permission`, flat page-permission list) and a `permission_user` pivot, consumed by `App\Http\Middleware\CheckPermission` and `User::permissions()`. Spatie Permission's **default** table names are also `permissions`/`roles`/etc.

**Resolution applied:** `config/permission.php` renames Spatie's tables to `rbac_permissions`, `rbac_roles` stays default (no collision), `rbac_model_has_permissions`, `rbac_model_has_roles`, `rbac_role_has_permissions`. Both systems now run side-by-side without conflict; migrations for `rbac_*` have run successfully.

**What is *not* done, and must happen in the dedicated Roles & Permissions module (see §20):** `Spatie\Permission\Traits\HasRoles` is **not yet attached to `User`**, because that trait defines its own `permissions()` relationship method, which would silently shadow/conflict with the legacy `User::permissions()` relation already in use by `CheckPermission` and every `Backend/*` controller's `Auth::user()->can()` calls. Attaching it blind would break existing admin authorization. The Roles module must either (a) rename the legacy relation before attaching `HasRoles`, or (b) fully migrate `Backend/*` off the legacy system first. `App\Http\Middleware\EnsureUserHasRole` (aliased `role:admin,manager`) and Spatie's own `role`/`permission`/`role_or_permission` middleware aliases are already registered in `bootstrap/app.php`, ready to activate the moment that trait is attached.

### 10.3 CSRF
Unchanged — Laravel's default `VerifyCsrfToken` protects all `web` routes (admin panel, frontend forms). `routes/api.php` is stateless (token-based), CSRF-exempt by design.

### 10.4 Rate Limiting
`RateLimiter::for('api', ...)` registered in `AppServiceProvider::configureRateLimiting()`, driven by `config('grindo.api.rate_limit')` (default `60,1` = 60 req/min), keyed by user ID when authenticated, else IP. Applied via `->middleware('throttle:api')` on `routes/api.php`'s `v1` group.

### 10.5 XSS / SQL Injection
- All Eloquent/query-builder usage is parameterized by default (never raw string interpolation into `whereRaw`).
- Blade's `{{ }}` escapes by default — `{!! !!}` is banned outside of trusted, sanitized CMS/rich-text fields.
- `BaseFormRequest` centralizes validation so no controller accepts unvalidated input.

### 10.6 Secure File Upload
- MIME/extension allow-list (`config('upload.allowed_mimes')`), max size enforced in `FormRequest` rules, filenames always regenerated to a UUID (`ImageUploadService`) — the original filename is never trusted or persisted as the stored path.
- Uploaded files are re-encoded (via Intervention Image) rather than moved as-is, which strips embedded scripts/metadata from image files.

### 10.7 Password Policy & Brute Force
- `BCRYPT_ROUNDS=12` (`.env`, already set).
- Laravel's built-in login throttling (`ThrottlesLogins` on the existing `LoginController`) plus the new `throttle:api` limiter cover brute-force on both the admin panel and future API auth endpoints.

## 11. Logging Architecture

| Type | Mechanism | Where |
|---|---|---|
| System/error logs | Laravel's default `stack`/`single` channel (`.env` `LOG_CHANNEL`) | `storage/logs/laravel.log` |
| Activity logs (who changed what) | Spatie Activitylog (`activity_log` table, migrated) via `HasActivityLog` trait — opt-in per model | DB, queryable via `Activity::forSubject($model)` |
| Authentication logs | Laravel's auth events (`Illuminate\Auth\Events\*`) — a `LogAuthenticationAttempts` listener is a one-file addition once needed, wired via `EventServiceProvider`/`Event::listen` in `AppServiceProvider` | future |
| Error/exception logs | `report()` calls already added in `bootstrap/app.php` for `QueryException` and unhandled `Throwable` on API routes | `storage/logs/laravel.log` |
| API request logs | Not built by default (would add overhead to every request) — add a `LogApiRequests` middleware scoped to `routes/api.php` only if/when audit requirements demand it | future, opt-in |

`BaseService::transaction()` already logs every failed write with the service class name and full exception — no module needs to add its own try/catch for that.

## 12. Cache Strategy

**Constraint:** `.env` has `CACHE_STORE=database` — the **database** cache driver does **not** support `Cache::tags()`. `config('grindo.cache.ttl')` defines per-module TTLs (dashboard 300s, settings/categories 3600s, products/collections 1800s, homepage 900s); `App\Constants\CacheKeys` builds deterministic, filter-aware keys (`CacheKeys::products($filters)` → md5 of the filter array) so invalidation is a plain `Cache::forget($key)` / prefix sweep rather than a tag flush.

```php
$key = CacheKeys::products($filters);
$products = Cache::remember($key, config('grindo.cache.ttl.products'), fn () => $repository->filter($filters)->paginate());
// on write:
Cache::forget(CacheKeys::products($filters)); // or bump a version segment in the key
```

**Upgrade path:** switching `CACHE_STORE` to `redis` unlocks `Cache::tags(['products'])->flush()` for true bulk invalidation — the key-builder in `CacheKeys` is designed so that swap doesn't require touching call sites, only how invalidation is triggered.

## 13. Queue System

`.env` already has `QUEUE_CONNECTION=database` (the `jobs` table migration already ran, pre-existing). Candidates for `App\Jobs\*` as modules are built:
- Transactional emails (contact-us confirmation, enquiry notifications) — `ShouldQueue` on the `Mailable`.
- Bulk operations (product import via `Maatwebsite\Excel`, already installed) — queued imports for large files.
- Image processing — if resize/webp conversion of very large batches ever needs to move off the request cycle, wrap `ImageUploadService::upload()` in a queued Job.

No jobs were pre-built (nothing to queue yet without a module generating the work) — the `database` queue driver is already configured and `app/Jobs/` is scaffolded and ready.

## 14. Notification Architecture

- **Database notifications**: Laravel's `notifications` table is not yet migrated (only added via `php artisan notifications:table` when the first `Notification` class is built) — intentionally deferred, no module needs it yet.
- **Email**: `app/Mail/*` already exists and works (`ContactUsMail`, `JobApplicationMail`) — new modules follow the same `Mailable` pattern, queued via `ShouldQueue` per §13.
- **Future push**: `User::fcm_device_token` column already exists in the schema (visible in `User::$fillable`) — a `FcmChannel` for Laravel Notifications is a future, additive piece once mobile API ships.

## 15. Middleware Structure

| Alias | Class | Status |
|---|---|---|
| `admin` | `App\Http\Middleware\Admin` | existing, untouched (no-op passthrough today) |
| `permission.legacy` | `App\Http\Middleware\CheckPermission` | existing, re-aliased for clarity, untouched |
| `role` | `Spatie\Permission\Middleware\RoleMiddleware` | ✅ registered — inert until `HasRoles` is attached (§10.2) |
| `permission` | `Spatie\Permission\Middleware\PermissionMiddleware` | ✅ registered — same caveat |
| `role_or_permission` | `Spatie\Permission\Middleware\RoleOrPermissionMiddleware` | ✅ registered — same caveat |
| `role:admin,manager` (custom) | `App\Http\Middleware\EnsureUserHasRole` | ✅ built — defensive (`method_exists` guard), same caveat |
| `force.json` | `App\Http\Middleware\ForceJsonResponse` | ✅ built — forces `Accept: application/json` |
| `localize` | `App\Http\Middleware\Localization` | ✅ built — reads `X-Locale` header / `?lang=` |
| `throttle:api` | Laravel core | ✅ applied to `routes/api.php`'s `v1` group |
| `guest` / `auth` | Laravel core | already available, no custom class needed |
| Maintenance mode | Laravel core (`php artisan down`, `APP_MAINTENANCE_DRIVER=file`) | already configured in `.env`, no custom class needed |

## 16. Configuration Files

| File | Purpose |
|---|---|
| `config/grindo.php` | Brand name/contact/currency, pagination defaults, per-module cache TTLs, API version + rate limit |
| `config/upload.php` | Disk, driver, quality, WebP toggle, max sizes, allowed mimes, per-image-type folders + resize/thumbnail dimensions, placeholder image |
| `config/seo.php` | Default title/description/keywords/OG image, sitemap + robots toggles |
| `config/settings.php` | Cache key/TTL wrapper for the existing key-value `settings` table |
| `config/constants.php` | Statuses/roles/permission-modules/notification-types/image-types as plain arrays (for Blade, JS-exposed config, DataTables filters — anywhere a PHP `enum` isn't directly consumable) |
| `config/permission.php` | Spatie config — table names namespaced `rbac_*` (§10.2) |
| `config/sanctum.php` | Spatie/Sanctum published defaults, untouched |
| `config/activitylog.php` | Spatie Activitylog published defaults, untouched |

## 17. Helper Functions — `app/Support/helpers.php`

Autoloaded globally via `composer.json`'s `autoload.files` (regenerate with `composer dump-autoload` after editing). Every helper is a thin delegate — logic lives in the class it calls:

```php
uploadImage(UploadedFile $file, string $folder, array $options = []): array   // → ImageUploadService::upload()
deleteImage(?string $path, ?string $disk = null): bool                       // → ImageUploadService::delete()
generateSlug(string $value, ?string $table = null, ...): string              // unique-slug generator, table-aware
generateSKU(string $prefix = 'GRD'): string                                  // GRD-260702-AB3F9 style
responseSuccess(...) / responseError(...)                                    // → ApiResponse::success()/error()
formatDate(mixed $date, string $format = 'd M Y'): ?string
currency(float|int $amount, ?string $symbol = null): string                  // uses config('grindo.currency.symbol')
```

## 18. Reusable Traits — `app/Traits/`

| Trait | Gives the model | Requires |
|---|---|---|
| `HasStatus` | `scopeActive()`, `scopeInactive()`, `isActive()`, `statusLabel()` | `status` int column (`StatusEnum`) |
| `HasSlug` | Auto-generates a unique `slug` on create/update from a source column, `getRouteKeyName() = 'slug'` | `slug` column; optional `protected string $slugSource = 'title';` (defaults to `name`) |
| `HasSeo` | `seo()` morphOne relation, `meta_title`/`meta_description` accessors with config fallback | nothing on the model itself — backed by the polymorphic `seo_meta` table (§4.9) |
| `HasImage` | `image_url` accessor (with placeholder fallback), auto-deletes the file on model `deleting` | `image` column; optional `protected string $imageColumn`/`$imageDisk` overrides |
| `HasUuid` | Auto-generates a `uuid` on create | `uuid` column; optional `protected string $uuidColumn` override |
| `HasActivityLog` | Full Spatie `LogsActivity` wired with sane defaults (fillable-only, dirty-only, non-empty-only, log name = class basename) | nothing extra — just `use HasActivityLog;` |
| `ApiResponser` (controller trait, not a model trait) | `$this->success()/error()/paginated()` in any controller | extend `Api\Controller` or use directly |

## 19. Global Constants

- **Statuses / Roles / Notification types / Image types**: primary source is the `Enums/` (type-safe, has behaviour). `config/constants.php` mirrors them as plain arrays for contexts that can't consume a PHP `enum` directly (Blade `@foreach`, JS-exposed config via `@json`, Yajra DataTables column filters).
- **Permissions**: not enumerated as a closed PHP set — Spatie permissions are DB rows by design (creatable at runtime per module). `config('constants.permission_modules')` lists the *module* names (`products`, `categories`, ...) used to seed permission rows like `products.view`, `products.edit` when the Roles module is built.
- **Cache keys**: `App\Constants\CacheKeys` (§12) — a plain class of `const` strings + key-builder methods, not an enum, because cache keys aren't a closed set (they're parameterized by filters).

## 20. Development Roadmap

Build order for every future module, respecting what already exists and what this foundation unblocks:

1. **Roles & Permissions module** — resolve the `User::permissions()` / Spatie `HasRoles` conflict (§10.2) first; everything else's authorization depends on it.
2. **Categories** — simplest catalog entity, exercises `HasSlug`, `HasSeo`, `HasImage`, `BaseRepository`/`BaseService` end-to-end. Good template module for the pattern.
3. **Products** — depends on Categories; exercises `generateSKU()`, `ImageUploadService` multi-image, filtering/search via `BaseRepository`.
4. **Collections** — curated product groupings; many-to-many with Products.
5. **Banner Management** — homepage/campaign banners; `HasImage`, `HasStatus`, simple.
6. **CMS pages** — formalize the existing `Page`/`MetaTag` models under the new Service/Repository pattern (currently unmanaged CRUD).
7. **Testimonials** — already has a legacy `Backend/TestimonialController`; decide whether to migrate it onto the new pattern now or leave it (low priority, low risk either way).
8. **Product Enquiry** — the core conversion feature (this is an enquiry/showcase site, not e-commerce checkout); reuses the `Contact`-style flow already proven by `Backend/EnquiryController`.
9. **Contact Us** — already functional (`HomeController::contactus`); formalize onto Service/Repository if/when it needs more than a single insert.
10. **Users (customer accounts)** — registration/profile, builds on Sanctum (§10.1) and the already-existing `frontend.profile` view.
11. **Wishlist** — depends on Users + Products.
12. **Cart** — depends on Users + Products; the existing `frontend.cart` view is UI-only today.
13. **SEO** — wire `HasSeo` into Products/Categories/Collections' admin forms; sitemap generation using `config('seo.sitemap_enabled')`.
14. **Settings module** — formal Service around the existing `settings` table + `config('settings.php')` cache wrapper.
15. **Notifications** — `notifications:table` migration + first `Notification` classes (enquiry received, status changed) once there's a real trigger for them.
16. **Analytics / Admin Dashboard widgets** — depends on Products/Categories/Enquiries existing; uses `config('grindo.cache.ttl.dashboard')`.
17. **Mobile API expansion** — `routes/api.php` `v1` group already versioned and ready; add `v2` alongside `v1` (never break `v1`) when mobile needs diverge from web.

Each module PR should: add its migration(s), Model (+ opted-in traits), Repository + interface (bound in `RepositoryServiceProvider`), Service (extends `BaseService`), FormRequests (extend `BaseFormRequest`), Resource(s), Policy (registered in `AuthServiceProvider`), and Controller(s) (`Api/V1/*` and/or `Backend/*` as appropriate) — in that order, mirroring §1's layering.
