# 06 - CD-01 ADIANTI (cd01.uppi.app.br)

## 1. VISAO GERAL

Cada CD e uma **instancia Adianti independente** com banco de dados proprio.
Opera **offline** do ERP central -- WMS nao depende de conectividade.
Sincronizacao via: eventos Redis (push) + API REST (pull) + reconciliacao cron.

**Path:** `/var/www/cd01.uppi.app.br/`
**Framework:** Adianti 8.4
**Banco Local:** `db_erp_cd01` (20 tabelas)
**Banco Central:** `db_erp` (conexao nomeada para sync com central)

---

## 2. BANCO LOCAL - 20 TABELAS

### Config
| Tabela | Descricao |
|--------|-----------|
| `cd_config` | warehouse_code, api_central_url, api_key, sync_interval, status online |

### Catalogo Sincronizado
| Tabela | Descricao |
|--------|-----------|
| `products_local` | ID, SKU, EAN, NCM, dimensoes (sincronizado do central) |
| `orders_local` | Pedidos do central (order_split_id, endereco entrega com lat/lng) |
| `order_items_local` | Itens do pedido local |

### WMS (10 tabelas)
| Tabela | Descricao |
|--------|-----------|
| `warehouse_zones` | 6 tipos: receiving, storage, picking, packing, shipping, returns |
| `warehouse_locations` | corredor/rack/prateleira/bin |
| `wms_stock` | quantity, reserved, available (GENERATED), lote, validade |
| `wms_stock_movements` | 10 tipos de movimentacao |
| `wms_receiving` | Recebimento com NF-e |
| `wms_receiving_items` | Conferencia itens |
| `wms_picking_orders` | 4 tipos: single, batch, wave, zone |
| `wms_picking_items` | Separacao com barcode |
| `wms_inventory_counts` | Contagem ciclica/completa |
| `wms_inventory_count_items` | Variancia calculada |

### TMS Local (3 tabelas)
| Tabela | Descricao |
|--------|-----------|
| `shipments` | 11 status, tracking, label |
| `tms_routes` | Rotas locais |
| `tms_route_stops` | POD: foto, nome, lat/lng |

### Sync e Usuarios
| Tabela | Descricao |
|--------|-----------|
| `sync_outbox` | Fila de eventos -> central (event_type, payload, sent flag) |
| `users_local` | Operadores: operator, supervisor, manager, driver |

---

## 3. ESTRUTURA DO PROJETO ADIANTI

```
/var/www/cd01.uppi.app.br/
|-- app/
|   |-- config/
|   |   |-- application.php
|   |   |-- dberp.php               # db_erp_cd01 (local)
|   |   |-- dbcentral.php           # db_marketplace (sync, permissoes limitadas) (CRIAR)
|   |
|   |-- control/
|   |   |-- wms/                    # 14 telas
|   |   |   |-- WmsDashboard.php         # KPIs: recebimentos, pickings, estoque critico
|   |   |   |-- ReceivingList.php        # Lista recebimentos pendentes
|   |   |   |-- ReceivingForm.php        # Conferencia de itens
|   |   |   |-- PickingList.php          # Ordens de picking
|   |   |   |-- PickingExecution.php     # Execucao guiada com barcode
|   |   |   |-- StockOverview.php        # Estoque por zona/locacao
|   |   |   |-- StockMovements.php       # Historico movimentacoes
|   |   |   |-- StockAdjustment.php      # Ajuste manual com motivo
|   |   |   |-- StockTransfer.php        # Transferencia entre locacoes
|   |   |   |-- InventoryList.php        # Contagens
|   |   |   |-- InventoryExecution.php   # Contagem com variancia
|   |   |   |-- LocationManager.php      # CRUD locacoes
|   |   |   |-- ZoneManager.php          # CRUD zonas
|   |   |   |-- ReceivingDetail.php      # Detalhe recebimento
|   |   |
|   |   |-- tms/                    # 6 telas
|   |   |   |-- ShipmentList.php         # Envios pendentes
|   |   |   |-- ShipmentForm.php         # Criar/editar envio
|   |   |   |-- RouteList.php            # Rotas do dia
|   |   |   |-- RouteDetail.php          # Mapa + paradas
|   |   |   |-- DeliveryProofs.php       # Provas de entrega
|   |   |   |-- DriverStatus.php         # GPS motoristas em tempo real
|   |   |
|   |   |-- sync/                   # 3 telas
|   |   |   |-- SyncStatus.php           # Status da sincronizacao
|   |   |   |-- SyncOutbox.php           # Fila de envio pendente
|   |   |   |-- SyncConfig.php           # Configuracao do CD
|   |   |
|   |   |-- admin/                  # 2 telas
|   |   |   |-- OperatorManager.php      # CRUD operadores locais
|   |   |   |-- ProductCatalog.php       # Catalogo local (readonly)
|   |
|   |-- model/                      # 19 models TRecord
|   |   |-- CdConfig.php, ProductLocal.php, OrderLocal.php, OrderItemLocal.php
|   |   |-- WarehouseZone.php, WarehouseLocation.php
|   |   |-- WmsStock.php, WmsStockMovement.php
|   |   |-- WmsReceiving.php, WmsReceivingItem.php
|   |   |-- WmsPickingOrder.php, WmsPickingItem.php
|   |   |-- WmsInventoryCount.php, WmsInventoryCountItem.php
|   |   |-- Shipment.php, TmsRoute.php, TmsRouteStop.php
|   |   |-- SyncOutbox.php, UserLocal.php
|   |
|   |-- service/
|   |   |-- WmsStockService.php          # Reserva, baixa, inbound, ajuste
|   |   |-- WmsPickingService.php        # Criacao e execucao picking
|   |   |-- WmsReceivingService.php      # Conferencia e entrada
|   |   |-- TmsRouteService.php          # Criacao e gestao de rotas
|   |   |-- SyncService.php             # Sync outbox -> central
|
|-- menu.xml                         # Menu do CD
```

---

## 4. FLUXO DE OPERACAO

### Pedido chega ao CD
```
1. Marketplace cria order + order_split (db_marketplace)
2. OMS Worker roteia split para CD via RulesEngine + CdSyncService
3. Evento order.routed via Redis
4. CD Sync Worker cria orders_local + order_items_local (db_erp_cd01)
5. Adianti do CD exibe pedido no WmsDashboard
6. Operador inicia picking (PickingExecution ou App Logistico)
7. Picking concluido -> cria shipment local
8. sync_outbox registra evento shipment.created (sent=0)
9. CD Sync Worker envia para central
10. Central atualiza order_split.status + cria shipment em db_marketplace
```

### Sync de Estoque
```
1. Mudanca de estoque no CD (recebimento, picking, ajuste, inventario)
2. Registra em sync_outbox (event_type: stock.updated)
3. SyncService (cron cada 60s) envia para central
4. Central atualiza stock_consolidated
5. Marketplace usa stock_consolidated para exibir disponibilidade
```

### Operacao Offline
```
- Se CD perde conexao: sync_outbox acumula (sent=0)
- WMS continua normalmente no banco local
- Quando conexao volta: SyncService processa backlog
- Central reconcilia via cd_stock_snapshot (cron diario 03:00)
```

---

## 5. MENU DO CD (menu.xml)

```xml
<menuitem label="Dashboard">
    <menuitem label="WMS" image="bi bi-boxes" action="WmsDashboard"/>
</menuitem>

<menuitem label="WMS">
    <menuitem label="Recebimento" image="bi bi-inbox" action="ReceivingList"/>
    <menuitem label="Picking" image="bi bi-cart4" action="PickingList"/>
    <menuitem label="Estoque" image="bi bi-box-seam" action="StockOverview"/>
    <menuitem label="Movimentacoes" image="bi bi-arrow-left-right" action="StockMovements"/>
    <menuitem label="Ajuste" image="bi bi-pencil-square" action="StockAdjustment"/>
    <menuitem label="Transferencia" image="bi bi-arrow-repeat" action="StockTransfer"/>
    <menuitem label="Inventario" image="bi bi-clipboard-check" action="InventoryList"/>
    <menuitem label="Locacoes" image="bi bi-grid-3x3" action="LocationManager"/>
    <menuitem label="Zonas" image="bi bi-layers" action="ZoneManager"/>
</menuitem>

<menuitem label="Expedicao">
    <menuitem label="Envios" image="bi bi-box-arrow-right" action="ShipmentList"/>
    <menuitem label="Rotas" image="bi bi-signpost-2" action="RouteList"/>
    <menuitem label="Provas Entrega" image="bi bi-camera" action="DeliveryProofs"/>
    <menuitem label="Motoristas" image="bi bi-geo-alt" action="DriverStatus"/>
</menuitem>

<menuitem label="Cadastros">
    <menuitem label="Catalogo" image="bi bi-box" action="ProductCatalog"/>
    <menuitem label="Operadores" image="bi bi-people" action="OperatorManager"/>
</menuitem>

<menuitem label="Sync">
    <menuitem label="Status" image="bi bi-arrow-repeat" action="SyncStatus"/>
    <menuitem label="Fila Envio" image="bi bi-send" action="SyncOutbox"/>
    <menuitem label="Configuracao" image="bi bi-gear" action="SyncConfig"/>
</menuitem>
```

---

## 6. CONEXOES DE BANCO

### dberp.php (ja existe - banco local)
```php
<?php
return [
    'host' => "uppi.app.br",
    'user' => "tokstore",
    'pass' => "Gzw41WTagFbmwjJcNZH6C0OxcQY=",
    'type' => "mysql",
    'port' => "3306",
    'name' => "db_erp_cd01",
    'prep' => "1",
];
```

### dbcentral.php (CRIAR — conexao com banco central)
```php
<?php
return [
    'host' => "uppi.app.br",
    'user' => "tokstore",
    'pass' => "Gzw41WTagFbmwjJcNZH6C0OxcQY=",
    'type' => "mysql",
    'port' => "3306",
    'name' => "db_erp",       // Banco central (ERP + marketplace)
    'prep' => "1",
];
```
