# Temas e Cores — Modelagem de Dados

> **Slug do módulo:** `temas-e-cores` (tabela `modulos`, id 2)

## 1. Objetos de dados

| Objeto | Natureza | Papel |
|---|---|---|
| `configurations` (categoria 3 = `temas`) | **Compartilhada** com `configuracoes-da-instituicao`, `lgpd` e `outras-configuracoes` | Armazena as 9 chaves de tema/cor. |
| `category_configurations` | Compartilhada | Categoriza as configurações; a linha `slug='temas'` (id 3) é o filtro do módulo. |
| `layouts` | **Própria do módulo** (modelo 5) | Estrutura de blocos do template personalizável. Sem FK e sem relação com `configurations`. |
| view SQL `configuracoes` | Compartilhada | Lista todas as configurações de todas as categorias. |
| `modulos`, `resources`, `menu_orders` | Compartilhadas | Metadados do módulo e do item de menu. |

## 2. Tabela `configurations` — categoria `temas`

Criada por `v6/database/migrations/2018_05_11_131302_create_configurations_table.php`.
Estrutura verificada com `\d configurations` no banco `prefeituras_v5`:

| Coluna | Tipo | Null | Observação |
|---|---|---|---|
| `id` | `integer` | não | PK (`configurations_pkey`). |
| `title` | `varchar(191)` | não | Rótulo exibido no formulário. |
| `description` | `text` | sim | Texto do tooltip (ícone de interrogação). |
| `small_description` | `text` | sim | Instrução abaixo do campo. |
| `placeholder` | `varchar(191)` | sim | Não usado pela view de temas. |
| `key` | `varchar(191)` | não | **Sem índice único.** |
| `value` | `text` | sim | Valor cru (hex, caminho de arquivo, `modelo1`, `black`). |
| `type` | `varchar(191)` | não | `text`, `file` ou `checkbox` neste módulo. |
| `order` | `integer` | sim | Ordem de renderização do formulário. |
| `max_input` | `integer` | sim | Tamanho máximo da validação. |
| `min_input` | `integer` | sim | Tamanho mínimo da validação. |
| `category_configurations_id` | `integer` | não | FK → `category_configurations.id` (`configurations_category_configurations_id_foreign`). |
| `notnull` | `boolean` | sim | Define `required` na validação dinâmica. |
| `status_create` | `boolean` | sim | Exibição do campo no formulário. |
| `created_at` / `updated_at` | `timestamp` | sim | — |
| `deleted_at` | `timestamp` | sim | Soft delete (`use SoftDeletes`). |

Índices existentes: **apenas** `configurations_pkey`. Não há índice em `key` nem em
`category_configurations_id`.

### 2.1 As 9 configurações ativas da categoria `temas`

Valores lidos do banco `prefeituras_v5` (categoria 3, `deleted_at IS NULL`):

| `id` | `key` | `type` | `title` | `notnull` | `max_input` | `min_input` | `order` | `value` | `description` |
|---|---|---|---|---|---|---|---|---|---|
| 50 | `layout` | `text` | Layout | — | — | — | 46 | `modelo1` | — |
| 51 | `cor_1` | `text` | Cor Principal | t | 50 | 3 | 47 | `#1075ad` | Cor Principal do Portal |
| 52 | `cor_2` | `text` | Cor dos títulos | t | 50 | 3 | 48 | `#66b367` | Cor dos títulos das páginas do portal |
| 53 | `cor_3` | `text` | Cor dos botões | t | 50 | 3 | 49 | `#fece50` | Cor dos botões do portal |
| 54 | `cor_4` | `text` | Cor de fundos de texto | t | 50 | 3 | 50 | `#fece50` | Cor de fundo de alguns textos Ex: 01-01-2001 (em listagem de notícias) |
| 55 | `background` | `file` | Plano de Fundo | f | — | — | 51 | *(vazio)* | small_description: "Tamanho ideal: 1920x1080" |
| 56 | `cor_cms` | `text` | Tema do CMS | t | — | — | 52 | `black` | — |
| 57 | `background_fixed` | `checkbox` | Fixar plano de fundo | f | — | — | 68 | `1` | Quando marcado, o plan de fundo permanecerá fixo durante a rolagem da página |
| 58 | `background_repeat` | `checkbox` | Repetir plano de fundo | f | — | — | 69 | `1` | Cor de fundo do portal, quando não for utilizado plano de fundo |

Observações:

- Não existe coluna `theme_id`, `palette_id` ou qualquer FK para cores: **as cores são texto
  livre** (validação `required|max:50|min:3`), sem verificação de formato hexadecimal.
- `cor_cms` também é `text` livre; a lista de skins válidas existe apenas no array `$temas_lte`
  do controller.
- `background` não tem `max_input`/`min_input`; é do tipo `file` e por isso fica fora das
  regras `required` (o `notnull` é `false`).
- `status_create = true` nas 9 linhas.

## 3. Tabela `category_configurations`

Criada por `v6/database/migrations/2018_04_10_131301_create_category_configurations_table.php`.

| Coluna | Tipo | Null |
|---|---|---|
| `id` | `integer` | não (PK) |
| `name` | `varchar(191)` | não |
| `slug` | `varchar(191)` | não |
| `status_create` | `boolean` | sim |
| `created_at`/`updated_at`/`deleted_at` | `timestamp` | sim |

Categorias (seed `v6/database/seeds/CategoryConfigurationsTableSeeder.php`):
`site`(1), `prefeitura`(2), `temas`(3), `outros`(4), `layout`(5), `covid`(6),
`barra-privacidade`(7), `dashboard`(8). Note que existe uma categoria `layout` (id 5), **vazia**,
distinta do template do portal — não confundir com `temas`.

## 4. Tabela `layouts` (modelo 5 personalizável) — dados próprios do módulo

Criada por `v6/database/migrations/2022_05_30_104340_create_layouts_table.php`; alterada por
`v6/database/migrations/2024_10_20_070912_add_title_to_layout_table.php` (coluna `title`) e
`v6/database/migrations/2025_04_27_225303_add_column_columns_to_layout_table.php` (coluna `columns`).

| Coluna | Tipo | Null | Uso |
|---|---|---|---|
| `id` | `integer` | não (PK) | — |
| `key` | `varchar(191)` | sim | Identificador do bloco (`preview`, `tags`, `logo`, `ultimas-noticias`, `secretarias-grid`, ...). |
| `section` | `varchar(191)` | sim | Agrupamento (`acessibilidade`, `header`, `content`, `home-news`, ...). |
| `type` | `varchar(191)` | sim | `section`, `element` ou `config`. |
| `value` | `text` | sim | HTML do preview/tags; valor `{module}:{subId}` em `secretarias-grid`. |
| `order` | `integer` | sim | Posição dentro da seção. |
| `style` | `text` | sim | CSS inline do elemento. |
| `status` | `boolean` | sim | `false` = oculto. `tags` recebe `status = 0`. |
| `path` | `varchar(191)` | sim | View Blade do bloco (ex.: `portal.layouts.modelo5.home.transparencia`). |
| `title` | `varchar(191)` | sim | Título editável (`Últimas Notícias`, `Mais Lidas`, `Carrossel de Vereadores`, `Lista de Sessões`). |
| `columns` | `varchar(191)` | sim | Nº de colunas do grid (`transparencia-fiscal` = 4, `transparencia-fiscal-grid` = 6). |
| `created_at`/`updated_at` | `timestamp` | sim | — |

Sem FK, sem índice além da PK. **41 linhas** no banco. Linhas de conteúdo (`preview`, `tags`)
guardam HTML de ~76 KB e ~77 KB.

Seções e elementos (extraído do banco):

| `section` | `type` | `key` | `status` | `order` | `path` |
|---|---|---|---|---|---|
| `preview` | — | `preview` | t | — | — |
| `tags` | — | `tags` | t | — | — |
| (vazia) | `section` | `acessibilidade` | t | 1 | `portal.layouts.modelo5.layout.header.acessibilidade` |
| `acessibilidade` | `element` | `ancoras` | t | 1 | idem |
| `acessibilidade` | `element` | `menu` | t | 2 | idem |
| (vazia) | `section` | `header` | t | 1 | `portal.layouts.modelo5.layout.header` |
| `header` | `element` | `logo`, `menu-principal`, `search` | t | 1..3 | `...nav-header` |
| (vazia) | `section` | `content` | t | 1 | `...header` |
| `content` | `section` | `covid` | t | 1 | `portal.layouts.modelo5.home` |
| `covid` | `element` | `vacinometro` | t | 1 | `...home.covid` |
| `content` | `section` | `destaque` | t | 2 | `...home` |
| `destaques` | `element` | `carousel-noticias`, `noticias-destaque` | t | 1..2 | `...home.destaques` |
| `content` | `section` | `home-news` | t | 3 | `...home.news` |
| `home-news` | `element` | `banners`, `ultimas-noticias`, `more-popular` | t | 1..2 | `...home.news.sidebar` / `.more-news` |
| `content` | `section` | `transparencia` | t | 1 | `...home.transparencia` |
| `transparencia` | `element` | `image-transparencia-fiscal`, `transparencia-fiscal` | t | 1..2 | `...home.transparencia` |
| `content` | `section` | `category-news` | t | 1 | `...home.news.category-news` |
| `category-news` | `element` | `news` | t | 1 | idem |
| `content` | `section` | `super-banners` | t | 1 | `...home.super-banners` |
| `super-banners` | `element` | `super-banners-1`, `super-banners-2` | t | 1..2 | idem |
| (vazia) | `section` | `footer` | t | 1 | `portal.layouts.modelo5.layout.footer` |
| `footer` | `element` | `logo-footer`, `menu-footer`, `endereco`, `social` | t | 1..4 | idem |
| `transparencia` | `element` | `transparencia-fiscal-grid` | **f** | 2 | `...home.transparencia` (`columns` = 6) |
| `category-news` | `element` | `news-2` | **f** | 1 | `...home.news.category-news` |
| `home-news` | `element` | `banners-2`, `acesso-rapido` | **f** | 1 | `...home.news.sidebar` |
| `content` | `section` | `vereadores` | t | 99 | `portal.layouts.modelo5.home` |
| `vereadores` | `element` | `vereadores-carousel` | **f** | 1 | `...home.vereadores` (`title` = "Carrossel de Vereadores") |
| `super-banners-carousel-tags` | `element` | `super-banners-carousel` | t | 1 | `...home.super-banners` |
| `content` | `section` | `sessoes` | t | 98 | `portal.layouts.modelo5.home` |
| `sessoes` | `element` | `sessoes-list` | **f** | 1 | `...home.sessoes` (`title` = "Lista de Sessões") |

A linha `secretarias-grid` (usada por `updateModuleStatus`) **não existe** no banco de
referência; é criada sob demanda via `updateOrInsert`.

## 5. Views SQL

| View | Criada por | Conteúdo | Uso no módulo |
|---|---|---|---|
| `configuracoes` | `v6/database/migrations/2023_04_17_144615_create_view_to_configuracoes.php` | Todas as configurações não deletadas, **de todas as categorias**, com `row_number()` como `value`, `titulo`, `categoria`, `id`, `tipo`. | Consumida por `DatatableController@get_configuracoes` (rota `datatable.configuracoes`). **Não é filtrável por categoria** — o datatable lista também as 9 chaves de `temas`. |

## 6. Migrations relevantes

| Migration | Efeito |
|---|---|
| `v6/database/migrations/2018_04_10_131301_create_category_configurations_table.php` | Cria `category_configurations`. |
| `v6/database/migrations/2018_05_11_131302_create_configurations_table.php` | Cria `configurations`. |
| `v6/database/migrations/2023_04_17_144615_create_view_to_configuracoes.php` | Cria a view `configuracoes`. |
| `v6/database/migrations/2022_05_30_104340_create_layouts_table.php` | Cria `layouts`. |
| `v6/database/migrations/2024_10_20_070912_add_title_to_layout_table.php` | Adiciona `layouts.title`. |
| `v6/database/migrations/2025_04_27_225303_add_column_columns_to_layout_table.php` | Adiciona `layouts.columns`. |
| `v6/database/migrations/2026_03_09_145651_add_layout_in_contents.php` | Acrescenta layout a conteúdos (uso fora do escopo deste módulo). |

## 7. Seeds

| Seed | Conteúdo |
|---|---|
| `v6/database/seeds/CategoryConfigurationsTableSeeder.php` | Cria as 8 categorias, incluindo `temas` (id 3). |
| `v6/database/seeds/ConfigurationsTableSeeder.php` | Bloco "Temas e cores": `updateOrCreate` das 9 chaves com `order`, `title`, `type`, `notnull`, `max_input`, `min_input`, `description` e valor padrão. |
| `v6/database/seeds/ResourcesTableSeeder.php` | Cria os recursos `tema-do-portal` e `template-do-portal` (ligados ao módulo 2). |

Trecho real do seed (`v6/database/seeds/ConfigurationsTableSeeder.php`):

```php
/* **** Temas e cores **** */
$config = Configuration::updateOrCreate(['key' => 'cor_1'],
    [
        'order' => 47,
        'title' => 'Cor Principal',
        'category_configurations_id' => $category['temas'],
        'type' => 'text',
        'max_input' => '50',
        'min_input' => '3',
        'notnull' => 'true',
        'description' => 'Cor Principal do Portal',
        'status_create' => 1
    ]
);
    $config->value ?? $config->update(['value' => '#1075ad']);
```

## 8. Relacionamentos (Eloquent)

| Relação | Definição |
|---|---|
| `Configuration::categoryConfiguration()` | `hasOne(CategoryConfiguration::class, 'id', 'category_configurations_id')` — usado por `getConfiguration()`. |
| `Configuration` | `use SoftDeletes`; `protected $table = 'configurations'`; `protected $primaryKey = 'id'`. |
| `Layout` | Sem relação declarada; consultas feitas por `key` (`whereIn('key',['preview','tags'])`) e `type`. `$fillable` contém `'kay'` (typo) e omite `title`, `style`, `columns` — ver `08-GAPS-E-DIVIDAS.md`. |
