# Destaques — Arquitetura

## 1. Visão geral

O módulo é um CRUD tradicional do CMS (AdminLTE 1.22) acoplado a um carrossel do
portal público (Bootstrap 4). Não existe Repository nem Service: o controller fala
direto com os models Eloquent.

```
┌──────────────────────────── CMS (prefixo /cms) ────────────────────────────┐
│ route: destaques.*  (v6/routes/basepro.php:392)                            │
│   ↓                                                                       │
│ HighlightController (v6/app/Http/Controllers/Prefecture/HighlightController.php)
│   ↓ FormRequest                                                          │
│ HighlightRequest (v6/app/Http/Requests/HighlightRequest.php)               │
│   ↓                                                                       │
│ Highlight (v6/app/Http/Model/Prefecture/Highlight.php) → tabela highlights │
│   ↓ imagem (1:1 opcional)                                                 │
│ Archive  (v6/app/Http/Model/Prefecture/Archive.php)  → tabela archives    │
│   ↓ Storage::disk('public')                                               │
│ storage/highlights/<id>/<arquivo>                                         │
└───────────────────────────────────────────────────────────────────────────┘
                                     │
                                     ▼
┌──────────────────────────── Portal (público) ─────────────────────────────┐
│ PortalController@index (v6/app/Http/Controllers/Portal/PortalController.php:83)│
│   Highlight::with('archive')->where('status', true)->orderBy('position')   │
│                                     │                                      │
│ ConfigHeaderServiceProvider (v6/app/Providers/ConfigHeaderServiceProvider.php:103)│
│   Highlight::where('layout', 1)->where('status', true)->first()            │
│                                     │                                      │
│ Blade: portal/layouts/modelo{1..6}/home/destaque.blade.php                 │
└───────────────────────────────────────────────────────────────────────────┘
```

## 2. Classes envolvidas

| Classe | Caminho | Papel |
|---|---|---|
| `HighlightController` | `v6/app/Http/Controllers/Prefecture/HighlightController.php` | CRUD, upload, reordenação, `toggleStatus` |
| `HighlightRequest` | `v6/app/Http/Requests/HighlightRequest.php` | Validação de título, subtítulo, botão, URL, imagem e posição |
| `Highlight` | `v6/app/Http/Model/Prefecture/Highlight.php` | Eloquent da tabela `highlights`; relação `archive()` |
| `Archive` | `v6/app/Http/Model/Prefecture/Archive.php` | Guarda o arquivo da imagem; `$fillable` inclui `highlight` e `highlight_id` |
| `FileTrait` | `v6/app/Http/Traits/FileTrait.php` | `getFileName()`, `saveUpload()`, `compress()` usados no upload |
| `DatatableController` | `v6/app/Http/Controllers/Prefecture/DatatableController.php` | `get_highlight()` — fonte de dados do grid do CMS (**com bug**) |
| `PortalController` | `v6/app/Http/Controllers/Portal/PortalController.php` | Carrega os destaques e injeta na view da home |
| `ConfigHeaderServiceProvider` | `v6/app/Providers/ConfigHeaderServiceProvider.php` | View composer que injeta `$highlightFullScreen` |
| `MenuServiceProvider` | `v6/app/Providers/MenuServiceProvider.php` | Item de menu "Destaques" (case `destaques`) |
| `Modulos` | `v6/app/Http/Model/Admin/Modulos.php` | Registro do módulo (`slug = 'detaques'`, `status = 0`) |
| `functions.php` | `v6/app/Helpers/functions.php` | `file_exist_destaque()` — imagem padrão quando o arquivo não existe |

## 3. Fluxo detalhado

### 3.1 CMS — listagem

```
GET /cms/destaques
  → HighlightController@index
  → view('prefecture.highlight.index')
  → JS assets/js/custom/contents/highlight/datatable.js
      → GET /cms/datatable/highlight
          → DatatableController@get_highlight
              → DB::table('highlight')->get()   ← view SQL `highlight` (sobre `highlights`)
              → struct_views($destaques, 'destaques')  (permissões por linha)
```

`struct_views` (`v6/app/Http/Controllers/Prefecture/DatatableController.php:504`) injeta
em cada linha os flags `edit`, `delete`, `active` e `inactivate`, calculados por
`has_access("<slug>.edit")` etc.

### 3.2 CMS — criação

```
POST /cms/destaques
  → HighlightController@store(HighlightRequest $request)
      → Highlight::where('position','>=',$pos)->increment('position')
      → Highlight::create($request->all())
      → $request->archive_highlight->storeAs("highlights/{$id}", $name)
      → Archive::create([... 'highlight_id' => $id, 'highlight' => 1])
  → redirect route('destaques.index')
```

Trecho real (`v6/app/Http/Controllers/Prefecture/HighlightController.php:33-58`):

```php
public function store(HighlightRequest $request)
{
    try {
        Highlight::where('position', '>=', $request->position)->increment('position');
        $destaque = Highlight::create($request->all());
        if ($request->has('archive_highlight')) {
            $extension = strtolower($request->archive_highlight->getClientOriginalExtension());
            $name = $this->getFileName($request->archive_highlight);
            $type = $request->archive_highlight->getMimeType();
            $archive = [
                'name' => $name,
                'title' => $name,
                'path' => "storage/highlights/$destaque->id/$name",
                'extension' => $extension,
                'type' => $type,
                'highlight_id' => $destaque->id,
                'highlight' => 1
            ];
            $upload = $request->archive_highlight->storeAs("highlights/$destaque->id", $name);
            $insertArchive = Archive::create($archive);
        }
        return redirect(route('destaques.index'));
    } catch (\Exception $e) {
        return redirect()->back()->withErrors(["error" => 'Não foi possível registrar os dados. Por favor, tente novamente.']);
    }
}
```

### 3.3 CMS — reordenação implícita

Não existe rota dedicada de reordenação: o operador edita o campo numérico
`position` no formulário. O controller rebalanceia os vizinhos:

```php
// v6/app/Http/Controllers/Prefecture/HighlightController.php:69-84
$oldPosition = $content->position;
$newPosition = $request->position;

if ($oldPosition != $newPosition) {
    if ($newPosition > $oldPosition) {
        Highlight::where('position', '>', $oldPosition)
            ->where('position', '<=', $newPosition)
            ->decrement('position');
    } else {
        Highlight::where('position', '>=', $newPosition)
            ->where('position', '<', $oldPosition)
            ->increment('position');
    }
}
```

### 3.4 Portal — home

```
GET /
  → PortalController@index
      → $highlights = Highlight::with('archive')
             ->where('status', true)
             ->orderBy('position', 'asc')
             ->get();
      → view('portal.layouts.<modelo>.home.index', [... 'highlights' => $highlights])
          → @include('portal.layouts.modeloN.home.destaque')
```

`ConfigHeaderServiceProvider` registra um composer para
`portal.layouts.modelo{1..6}.home.index` e `...home.destaque` com
`$highlightFullScreen` (primeiro destaque com `layout = 1` e `status = true`).

## 4. Dependências

| Pacote / recurso | Uso |
|---|---|
| `laravel/framework` 5.5 | Eloquent, FormRequest, Storage |
| `yajra/laravel-datatables-oracle` | `DataTables::of(...)->make(true)` no grid |
| `laracasts/presenter` | Não usado neste módulo |
| `intervention/image` | Indireto, via `v6/app/Http/Traits/FileTrait.php` |
| `cartalyst/sentinel` | `Sentinel::getUser()` nos logs de activity |
| `spatie/laravel-activitylog` | Log de auditoria (implícito nos demais controllers) |
| AdminLTE 1.22 | Layout `admin.layouts.app` do CMS |
| Bootstrap 4 + `lightslider.js` | Carrossel do portal |

## 5. Onde o módulo **não** tem camada

- Não há `Policy` — a autorização é feita por `has_access()` / `Sentinel::inRole()`
  dentro do `DatatableController` e pelos checks de view (`has_access(['destaques.create'])`).
- Não há `ApiResource` para destaques — não existe endpoint JSON.
- Não há `Service`/`Repository` — lógica nos controllers.
- Não há testes automatizados específicos em `v6/tests` para este módulo
  (`v5/database/factories/HighlightFactory.php` é a única fonte de dados de teste).

## 6. Diagrama resumido de dependências

```
              ┌────────────────────┐
              │  routes/basepro.php│ (CMS)
              └─────────┬──────────┘
                        ▼
        ┌───────────────────────────────┐
        │      HighlightController       │
        │  ┌──────────────┐             │
        │  │ FileTrait    │             │
        │  └──────────────┘             │
        └───────┬───────────────┬───────┘
                ▼               ▼
        ┌───────────────┐  ┌────────────┐
        │  Highlight    │  │  Archive   │
        │  (highlights) │◄─┤ (archives) │
        └───────┬───────┘  └────────────┘
                ▼
   ┌────────────────────────┐        ┌──────────────────────────────┐
   │ PortalController@index │        │ ConfigHeaderServiceProvider  │
   │ ConfigHeaderService…   │        │ ($highlightFullScreen)       │
   └───────────┬────────────┘        └──────────────┬───────────────┘
               ▼                                   ▼
   portal/layouts/modelo1/home/destaque.blade.php (e equivalentes em modelo2..modelo6)
```
