# Core Project Structure (RPFC / Open Oceans house style)

> Reusable structure guide for our Laravel admin / CRM apps. The same content is installed as the Claude Code skill `laravel-module-structure`.

## Quick prompt (paste into Claude or any AI assistant)

```text
Build this as a Laravel 12 app (PHP 8.2+, MySQL 8) using our house structure:

- One module = its own routes, controller(s), FormRequests and Blade views folder. Never put several screens in one page/controller. Each prototype screen = its own route + controller action + view.
- Routes: routes/admin/auth.php (login/logout) and routes/admin/admin.php (all modules), registered in bootstrap/app.php with middleware ['web','auth','active']. Group routes per module; reads use ->middleware('module:<name>'), changes use 'module:<name>,edit'. Route names <module>.<action>.
- Controllers in app/Http/Controllers/Admin/<Module>Controller.php (thin; sub-resources get their own controller). Validation in app/Http/Requests/Admin/Store|Update<Thing>Request.php with messages().
- String-backed enums in app/Enums with label() and options() (HasLabels trait); cast on models; validate with Rule::enum.
- Models: explicit $fillable, casts() (decimal:2, dates, json, enums), typed relations, scopes, SoftDeletes on business data, polymorphic documents/tasks.
- Shared logic in app/Services/<Module>/..., helpers in app/Support.
- Views: resources/views/admin/layouts/app.blade.php + admin/common (header, nav, flash, pagination); each module has <module>/index, show, partials/, tabs/. Modals as <template> + data-modal, inline editing via PATCH returning JSON. Plain CSS/JS in public/assets (no SPA).
- Permissions: roles + role_permissions (none/view/edit/full per module), built-in Super Admin, nav hides modules the user can't view.
- Migrations grouped by domain; money decimal(15,2), % decimal(6,3); legacy_id on imported tables.
- Docker for local dev (php 8.3 app + mysql 8). If migrating an old DB: clean schema + `php artisan legacy:import --fresh` (one importer per domain, data cleaners, one transaction) + DATABASE.md mapping old→new.
- Keep README.md and PROGRESS.md (done / pending / decisions) updated; commit per module; run Pint.
```


---

## Full guide

Follow this layout for every Laravel app and every new feature. The core rule:
**one module = its own routes, controller(s), form requests and views folder.
Never build several screens into one page or one controller.**

When converting an HTML prototype (single-page JS mock), each prototype "view"
becomes its own route + controller action + Blade view. The prototype's CSS becomes
the app stylesheet; its JS mock data is replaced by Eloquent queries.

## 1. Stack defaults

- Laravel 12, PHP 8.2+ (`"config": {"platform": {"php": "8.2.0"}}` in composer.json so the
  lock file installs on PHP 8.2 servers even if Composer ran on a newer PHP).
- MySQL 8. Server-rendered Blade + small vanilla JS (no SPA framework unless asked).
- Static assets in `public/assets/css` and `public/assets/js`, cache-busted with
  `?v={{ filemtime(public_path(...)) }}` (no Vite build needed to deploy).
- Code style: run `./vendor/bin/pint` before committing.

## 2. Folder layout

```
app/
  Console/Commands/              artisan commands (e.g. LegacyImport)
  Enums/                         string-backed enums + Concerns/HasLabels.php
  Http/
    Controllers/Controller.php   base: authorizeView()/authorizeEdit() helpers
    Controllers/Admin/           <Module>Controller.php (one per module / sub-resource)
    Controllers/Admin/Auth/      AuthController (login/logout)
    Middleware/                  EnsureModuleAccess, EnsureUserIsActive
    Requests/Admin/              Store<Thing>Request, Update<Thing>Request, <Thing>Request
  Models/                        one model per table, relations + casts + scopes
  Services/                      domain logic used by >1 controller
    <Module>/                    e.g. Contacts/ContactProfile.php, Trades/TradeService.php
    LegacyImport/                one importer class per domain + IdMap
  Support/                       small helpers (Money formatting, column registries)
config/<app>.php                 app-specific option lists, templates, per_page
routes/
  web.php                        only `/` redirect (+ public site routes if any)
  admin/auth.php                 login / logout / password routes
  admin/admin.php                every authenticated module route
resources/views/admin/
  layouts/app.blade.php          shell: meta, header, nav, flash, modal, toast, scripts
  common/                        meta, header, nav, flash, pagination
  auth/login.blade.php
  <module>/index.blade.php       list
  <module>/show.blade.php        detail / record page
  <module>/partials/*.blade.php  rows, cells, modals, sidebar cards
  <module>/tabs/*.blade.php      one file per tab on a detail page
public/assets/css/<app>.css      design system (from the prototype)
public/assets/css/app-extras.css additions (links-as-tabs, pager, flash, login)
public/assets/js/app.js          shared behaviours; <module>-detail.js for page-specific JS
docker/ + docker-compose.yml     local dev environment
DATABASE.md  PROGRESS.md  README.md
```

Register the route files in `bootstrap/app.php`:

```php
->withRouting(
    web: __DIR__.'/../routes/web.php',
    commands: __DIR__.'/../routes/console.php',
    health: '/up',
    then: function () {
        Route::middleware('web')->group(base_path('routes/admin/auth.php'));
        Route::middleware(['web', 'auth', 'active'])->group(base_path('routes/admin/admin.php'));
    },
)
->withMiddleware(function (Middleware $middleware): void {
    $middleware->alias(['module' => EnsureModuleAccess::class, 'active' => EnsureUserIsActive::class]);
    $middleware->redirectGuestsTo(fn () => route('login'));
    $middleware->redirectUsersTo(fn () => route('dashboard'));
})
```

## 3. Routes (`routes/admin/admin.php`)

Group per module with a comment header; read routes need View, mutations need Edit:

```php
// ---- Products ----------------------------------------------------------------
Route::middleware('module:products')->group(function () {
    Route::get('products', [ProductController::class, 'index'])->name('products.index');
    Route::get('products/{product}', [ProductController::class, 'show'])->name('products.show');

    Route::middleware('module:products,edit')->group(function () {
        Route::post('products', [ProductController::class, 'store'])->name('products.store');
        Route::patch('products/{product}', [ProductController::class, 'update'])->name('products.update');
        Route::delete('products/{product}', [ProductController::class, 'destroy'])->name('products.destroy');
        Route::post('products/{product}/share-classes', [ProductShareClassController::class, 'store'])->name('products.share-classes.store');
    });
});
```

- Route names `<module>.<action>`, nested resources `<module>.<child>.<action>`.
- Specific routes (`trades/export`) before `{model}` routes.
- Sub-resources of a record get their own controller (`ProductShareClassController`,
  `TradePartyController`, `ContactActivityController`) — keep the main controller small.
- When one route serves two modules (e.g. contacts and leads share a record), check the
  permission inside the controller with `$this->authorizeEdit($this->moduleFor($model))`.

## 4. Controllers

- Thin: validate (FormRequest), call model / service, return view or redirect.
- `index()` = list with filters from the query string (search `q`, status tabs, A–Z
  `letter`, date ranges), `->paginate(config('app-name.per_page'))->withQueryString()`.
- `show()` = record page; eager-load everything the tabs need (avoid N+1); filter out
  relations whose parent was soft-deleted with `whereHas()`.
- `store()` for "+ New X" buttons may create a draft record and redirect to `show()`
  so the user fills it in (prototype pattern), or accept a modal form.
- `update()` for click-to-edit fields returns JSON `{display, message, reload?}`
  via a `<Module>FieldUpdater` service (per-field rules, display HTML, select options).
- Redirect back to a tab with a hash: `redirect()->to(route('x.show', $m).'#tabname')`.
- Flash: `->with('success', '...')` (shown as a toast) or `->with('error', '...')`.

## 5. Form requests (`app/Http/Requests/Admin`)

```php
class StoreLeagueRequest extends FormRequest
{
    public function authorize(): bool { return true; }   // permission is handled by middleware

    public function rules(): array
    {
        return [
            'name' => ['required', 'string', 'max:255'],
            'status' => ['required', Rule::enum(TradeStatus::class)],
            'amount' => ['required', 'numeric', 'min:0'],
        ];
    }

    public function messages(): array
    {
        return ['name.required' => 'Please enter a name.'];
    }
}
```

Use `prepareForValidation()` to normalise input (e.g. strip commas from money).

## 6. Enums (`app/Enums`)

String-backed enums with human labels; values are lower_snake and stored as strings.

```php
enum TradeStatus: string
{
    use HasLabels;              // gives ::options() and ::labelFor()

    case Potential = 'potential';
    case Open = 'open';

    public function label(): string { return ucfirst($this->value); }
    public function color(): string { /* badge colour */ }
    public static function fromLegacy(?string $old): self { /* legacy value mapping */ }
}
```

- Cast enum columns on the model (`'status' => TradeStatus::class`).
- `Module` enum lists every permission-controlled area; `PermissionLevel` = none / view / edit / full.
- Validate with `Rule::enum(X::class)`; build selects with `X::options()`.

## 7. Models

- `$fillable` explicit, `casts()` method for dates, decimals (`'decimal:2'`), booleans,
  JSON arrays, enums.
- Relations typed (`BelongsTo`, `HasMany`, `MorphMany`), scopes for list filters
  (`scopeSearch`, `scopeOpen`, `scopeStartingWith`), small display helpers
  (`initials()`, `money()`, `label()`), no queries in Blade beyond simple lookups.
- `SoftDeletes` on business records. Polymorphic `documents` and `tasks` tables
  (`documentable_*`, `taskable_*`) instead of one table per owner.

## 8. Database / migrations

- One migration file per domain (users & roles, lookups, contacts, products, trades,
  invoices, activity…), not one per table.
- Money `decimal(15,2)`, percentages `decimal(6,3)`, FKs with `constrained()` +
  `nullOnDelete()` / `cascadeOnDelete()`, indexes on filter columns.
- Every table that receives migrated data has `legacy_id` (and `legacy_source` when it
  merges several old tables, unique together).

## 9. Permissions

- `roles` (account types) + `role_permissions` (role_id, module, level).
- Built-in Super Admin role = full access, not editable.
- `User::canViewModule(Module)` / `canEditModule(Module)`; middleware
  `module:<module>[,edit]`; nav links hidden when `! canViewModule()`;
  Blade: `$canEdit = auth()->user()->canEditModule(Module::X);` hides buttons / editors.
- Login by email **or** username; suspended / invited users cannot log in.

## 10. Views

- Every page: `@extends('admin.layouts.app')`, `@section('title')`, `@section('content')`,
  page JS via `@push('scripts')`.
- Lists: page head (title, filter dropdown, search box with `data-autosubmit`, "+ New"),
  status tabs as links with counts, table with `<tr class="clickable" data-href>`,
  `{{ $items->links('admin.common.pagination') }}`.
- Detail: breadcrumb, header card (avatar/icon, editable name, pills, actions menu),
  sidebar cards with click-to-edit rows, tabs (`data-tabs` + `.tabpanel#tabpanel-x`),
  one partial per tab in `tabs/`.
- Modals: `<template id="xModal">` opened by `data-modal="#xModal"`, pre-filled with
  `data-fill='{"form": "/url", "#field": "value"}'`.
- Escape everything (`{{ }}`); only use `{!! !!}` for HTML built and escaped in PHP;
  sanitise stored HTML (strip tags **and** attributes) before printing.

## 11. Shared JS (`public/assets/js/app.js`)

Provides: `toast()`, `api(url, method, data)` (JSON + CSRF), `openModal()/closeModal()`,
`[data-dropdown]` menus, `[data-tabs]` tabs that remember `#hash`, `[data-confirm]`
forms, `.editable-v[data-url][data-field]` inline editing (text / date / select),
`[data-toggle-chips]` multi-select chips, `tr[data-href]` row links (ignore clicks
inside `.no-row-click`), `[data-autosubmit]` search.

## 12. Services

Put logic in `app/Services` when it is shared or non-trivial, e.g. `ActivityLogger`
(timeline entries; a "task" activity also creates a Task), `Mailbox` (send + store
email), `TradeService` (fee recalculation + audit journal), `<Module>Profile` (gathers
all data for a record page), `<Module>FieldUpdater` (inline edits).

## 13. Docker dev environment

`docker-compose.yml`: `app` (php:8.3-cli image with pdo_mysql, gd, zip, intl, bcmath +
composer; `php artisan serve --host=0.0.0.0`) and `mysql` (mysql:8.0). Pick free host
ports (check first). If an old dump is involved, mount it and load it into a second
`<app>_legacy` database via `docker/mysql-init/*.sh`; run MySQL with
`--innodb-strict-mode=OFF` for wide legacy tables. `.env` uses `DB_HOST=mysql` and a
`legacy` connection in `config/database.php`.

## 14. Migrating an old database

- Clean new schema first (rename, normalise, enums), then an artisan command
  `legacy:import {--fresh}` with one importer class per domain extending a base
  importer that has cleaners: `str()` (decode HTML entities, drop "undefined"/"null"),
  `money()`, `pct()`, `date()` (zero / pre-1990 dates → null), `ids()` (CSV id lists),
  `list()` (JSON or CSV arrays). Share an `IdMap` (legacy id → new id per entity).
- Run inside one transaction with FK checks off; skip blank rows; map CSV ids to pivots.
- Re-hash plain-text passwords; never print credentials.
- Write `DATABASE.md`: table map, column map, value mappings, new fields, tables not
  migrated + reason, files to copy, known data issues, import counts.

## 15. Workflow

1. Read the prototype / brief fully and list its screens → modules.
2. Inspect the real data before designing (row counts, value distributions, FK reality).
3. Schema + importer + DATABASE.md, then build modules one at a time:
   controller → requests → routes → views → test in the browser with real data.
4. Keep `PROGRESS.md` (done / pending / decisions) and `README.md` (run steps, module
   status) current; commit per module.
5. Local login: a `LocalAdminSeeder` reading `LOCAL_ADMIN_EMAIL/PASSWORD` from `.env` —
   never test with real migrated staff passwords.
