# 🗄️ Estrutura de Banco de Dados - Route Entity > **Documentação da estrutura de banco de dados gerada pela entidade `RouteEntity` do sistema PraFrota** > > **Arquivo de origem**: `projects/idt_app/src/app/domain/routes/route.entity.ts` > **Data de criação**: Janeiro 2025 > **Banco suportado**: PostgreSQL (requer JSONB e ENUMs) --- ## 📋 **RESUMO EXECUTIVO** A entidade `RouteEntity` criará automaticamente **3 tabelas principais**, **12 tipos ENUM**, **7+ índices** e **2 foreign keys** no banco PostgreSQL. ### **🎯 Objetos Criados:** - ✅ **3 Tabelas**: `routes`, `route_stops`, `route_alerts` - ✅ **12 Tipos ENUM**: Para validação de campos - ✅ **7+ Índices**: Para performance otimizada - ✅ **2 Foreign Keys**: Relacionamentos entre tabelas --- ## 🗄️ **TABELAS PRINCIPAIS** ### **1. 📍 `routes` - Tabela Principal** ```sql -- Entidade: RouteEntity -- Decorator: @Entity('routes') CREATE TABLE routes ( routeid SERIAL PRIMARY KEY, routenumber VARCHAR(50) UNIQUE NOT NULL, companyid INTEGER NOT NULL, company_name VARCHAR(255), icon_logo TEXT, customerid INTEGER, customer_name VARCHAR(255), contractid INTEGER, contractname VARCHAR(255), freighttableid INTEGER, freighttablename VARCHAR(255), -- Informações básicas type routetype DEFAULT 'custom', status routestatus DEFAULT 'pending', priority routepriority DEFAULT 'normal', description TEXT, notes TEXT, -- Localização (JSONB) origin JSONB NOT NULL, destination JSONB NOT NULL, currentlocation JSONB, stops JSONB, -- Distância e duração totaldistance DECIMAL(10,2), estimatedduration INTEGER, actualduration INTEGER, plannedkm DECIMAL(10,2), actualkm DECIMAL(10,2), plannedduration INTEGER, actualdurationcomplete INTEGER, -- Cronograma scheduleddeparture TIMESTAMP NOT NULL, actualdeparture TIMESTAMP, scheduledarrival TIMESTAMP NOT NULL, actualarrival TIMESTAMP, -- Recursos alocados driverid INTEGER, drivername VARCHAR(255), driverrating DECIMAL(3,2), vehicleid INTEGER, vehicleplate VARCHAR(20), vehicletype VARCHAR(100), -- Carga e produtos producttype VARCHAR(255), estimatedpackages INTEGER, actualpackages INTEGER, cargovalue DECIMAL(15,2), weight DECIMAL(10,2), totalweight DECIMAL(10,2), totalvolume DECIMAL(10,3), marketplace marketplace, externalorderid VARCHAR(255), -- Financeiro totalvalue DECIMAL(15,2) NOT NULL, paidvalue DECIMAL(15,2), costperkm DECIMAL(10,4), fuelcost DECIMAL(10,2), tollcost DECIMAL(10,2), driverpayment DECIMAL(10,2), additionalcosts DECIMAL(10,2), -- Performance e métricas ontimedelivery BOOLEAN, customerrating DECIMAL(3,2), deliveryattempts INTEGER DEFAULT 1, averagespeed DECIMAL(6,2), fuelconsumption DECIMAL(8,2), -- Alertas e notificações (JSONB) alerts JSONB, notifications JSONB, -- Documentação (JSONB + Array) documents JSONB, photos TEXT[], signature TEXT, -- Metadados createdat TIMESTAMP DEFAULT NOW(), updatedat TIMESTAMP DEFAULT NOW(), createdby VARCHAR(255), updatedby VARCHAR(255), version INTEGER DEFAULT 1, -- Integração externalid VARCHAR(255), syncstatus syncstatus, lastsync TIMESTAMP ); ``` ### **2. 🛑 `route_stops` - Paradas da Rota** ```sql -- Entidade: RouteStopEntity -- Decorator: @Entity('route_stops') CREATE TABLE route_stops ( stopid SERIAL PRIMARY KEY, routeid INTEGER NOT NULL, sequence INTEGER NOT NULL, location JSONB NOT NULL, type routestoptype NOT NULL, scheduledtime TIMESTAMP NOT NULL, actualtime TIMESTAMP, duration INTEGER, packages INTEGER, status routestopstatus DEFAULT 'pending', notes TEXT, photos TEXT[], signature TEXT, -- Foreign Key CONSTRAINT fk_route_stops_routeid FOREIGN KEY (routeid) REFERENCES routes(routeid) ); ``` ### **3. ⚠️ `route_alerts` - Alertas da Rota** ```sql -- Entidade: RouteAlertEntity -- Decorator: @Entity('route_alerts') CREATE TABLE route_alerts ( alertid SERIAL PRIMARY KEY, routeid INTEGER NOT NULL, type routealerttype NOT NULL, severity routealertseverity NOT NULL, message TEXT NOT NULL, timestamp TIMESTAMP NOT NULL, resolved BOOLEAN DEFAULT false, resolvedat TIMESTAMP, resolvedby VARCHAR(255), -- Foreign Key CONSTRAINT fk_route_alerts_routeid FOREIGN KEY (routeid) REFERENCES routes(routeid) ); ``` --- ## 🎯 **TIPOS ENUM (PostgreSQL)** ### **4. 🚛 `routetype` - Tipos de Rota** ```sql CREATE TYPE routetype AS ENUM ( 'firstMile', -- Coleta em centros de distribuição 'lineHaul', -- Transporte entre cidades/regiões 'lastMile', -- Entrega final ao cliente 'custom' -- Rotas personalizadas ); ``` ### **5. 📊 `routestatus` - Status da Rota** ```sql CREATE TYPE routestatus AS ENUM ( 'pending', -- Aguardando 'inProgress', -- Em andamento 'completed', -- Concluída 'delayed', -- Atrasada 'cancelled' -- Cancelada ); ``` ### **6. 📈 `routepriority` - Prioridade da Rota** ```sql CREATE TYPE routepriority AS ENUM ( 'low', -- Baixa 'normal', -- Normal 'high', -- Alta 'urgent' -- Urgente ); ``` ### **7. 🛒 `marketplace` - Marketplace de Origem** ```sql CREATE TYPE marketplace AS ENUM ( 'mercadolivre', -- Mercado Livre 'shopee', -- Shopee 'amazon', -- Amazon 'custom' -- Personalizado ); ``` ### **8. 🔄 `syncstatus` - Status de Sincronização** ```sql CREATE TYPE syncstatus AS ENUM ( 'pending', -- Pendente 'synced', -- Sincronizado 'error' -- Erro ); ``` ### **9. 🛑 `routestoptype` - Tipos de Parada** ```sql CREATE TYPE routestoptype AS ENUM ( 'pickup', -- Coleta 'delivery', -- Entrega 'rest', -- Descanso 'fuel', -- Combustível 'maintenance' -- Manutenção ); ``` ### **10. ✅ `routestopstatus` - Status da Parada** ```sql CREATE TYPE routestopstatus AS ENUM ( 'pending', -- Pendente 'completed', -- Concluída 'skipped', -- Pulada 'failed' -- Falhou ); ``` ### **11. ⚠️ `routealerttype` - Tipos de Alerta** ```sql CREATE TYPE routealerttype AS ENUM ( 'delay', -- Atraso 'route_deviation', -- Desvio de rota 'vehicle_issue', -- Problema no veículo 'weather', -- Clima 'traffic', -- Trânsito 'security' -- Segurança ); ``` ### **12. 🔴 `routealertseverity` - Severidade do Alerta** ```sql CREATE TYPE routealertseverity AS ENUM ( 'low', -- Baixa 'medium', -- Média 'high', -- Alta 'critical' -- Crítica ); ``` ### **13. 📱 `notificationtype` - Tipos de Notificação** ```sql CREATE TYPE notificationtype AS ENUM ( 'sms', -- SMS 'email', -- E-mail 'push', -- Push notification 'whatsapp' -- WhatsApp ); ``` ### **14. 📨 `notificationstatus` - Status da Notificação** ```sql CREATE TYPE notificationstatus AS ENUM ( 'pending', -- Pendente 'sent', -- Enviada 'delivered', -- Entregue 'failed' -- Falhou ); ``` ### **15. 📄 `documenttype` - Tipos de Documento** ```sql CREATE TYPE documenttype AS ENUM ( 'invoice', -- Nota fiscal 'receipt', -- Recibo 'manifest', -- Manifesto 'insurance', -- Seguro 'permit', -- Permissão 'other' -- Outros ); ``` --- ## 📊 **ÍNDICES ESTRATÉGICOS** ### **16. 🚀 Índices de Performance na Tabela `routes`:** ```sql -- Índices compostos para consultas otimizadas CREATE INDEX idx_routes_companyid_status ON routes(companyid, status); CREATE INDEX idx_routes_type_status ON routes(type, status); CREATE INDEX idx_routes_scheduleddeparture ON routes(scheduleddeparture); CREATE INDEX idx_routes_driverid ON routes(driverid); CREATE INDEX idx_routes_vehicleid ON routes(vehicleid); CREATE INDEX idx_routes_customerid ON routes(customerid); -- Índice único para número da rota CREATE UNIQUE INDEX idx_routes_routenumber ON routes(routenumber); ``` ### **🎯 Otimizações de Consulta:** - **Filtros por empresa + status**: Muito comum no sistema - **Consultas por tipo + status**: Para relatórios e dashboards - **Busca por data de partida**: Para planejamento e acompanhamento - **Relacionamentos**: Driver, Vehicle, Customer para joins eficientes --- ## 🏗️ **ESTRUTURA HIERÁRQUICA** ``` 📦 Sistema de Rotas │ ├── 🗄️ routes (tabela principal) │ ├── 📍 origin (JSONB) │ ├── 📍 destination (JSONB) │ ├── 🛑 stops[] (JSONB array) │ ├── ⚠️ alerts[] (JSONB array) │ ├── 📨 notifications[] (JSONB array) │ ├── 📄 documents[] (JSONB array) │ └── 📸 photos[] (TEXT array) │ ├── 🛑 route_stops (1:N) - opcional/normalizada │ └── 🔗 FK: routeid → routes.routeid │ └── ⚠️ route_alerts (1:N) - opcional/normalizada └── 🔗 FK: routeid → routes.routeid ``` ### **📝 Abordagem Híbrida:** - **JSONB**: Para dados semi-estruturados (localização, paradas, alertas) - **Tabelas normalizadas**: Para dados que precisam de consultas SQL complexas - **ENUMs**: Para validação rigorosa de valores permitidos --- ## 🔧 **COMANDOS PARA CRIAÇÃO MANUAL** ### **Verificar se as tabelas foram criadas:** ```sql -- Listar todas as tabelas criadas SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' AND table_name LIKE '%route%'; -- Listar todos os tipos ENUM criados SELECT typname FROM pg_type WHERE typtype = 'e' AND typname LIKE '%route%'; -- Verificar índices da tabela routes SELECT indexname, indexdef FROM pg_indexes WHERE tablename = 'routes'; ``` ### **Exemplo de consulta otimizada:** ```sql -- Buscar rotas em andamento de uma empresa SELECT r.routeid, r.routenumber, r.status, r.type FROM routes r WHERE r.companyid = 123 AND r.status = 'inProgress' ORDER BY r.scheduleddeparture; -- ↑ Usará o índice idx_routes_companyid_status ``` --- ## 📈 **MÉTRICAS E ESTIMATIVAS** ### **📊 Tamanho Estimado por Registro:** - **`routes`**: ~2-5 KB por rota (devido aos campos JSONB) - **`route_stops`**: ~500 bytes por parada - **`route_alerts`**: ~300 bytes por alerta ### **🚀 Performance Esperada:** - **Consultas indexadas**: < 10ms para até 1M de rotas - **Inserções**: ~500-1000 rotas/segundo - **JSONB queries**: Performance excelente para filtros em campos JSON ### **💾 Estimativa de Armazenamento (100k rotas):** - **Tabela principal**: ~250-500 MB - **Paradas normalizadas**: ~50-100 MB (se usado) - **Alertas normalizados**: ~30-50 MB (se usado) - **Índices**: ~50-100 MB --- ## ⚡ **COMANDOS TYPEORM** ### **Gerar migration:** ```bash npm run typeorm migration:generate -- --name=CreateRouteEntities ``` ### **Executar migrations:** ```bash npm run typeorm migration:run ``` ### **Reverter última migration:** ```bash npm run typeorm migration:revert ``` --- ## 🎯 **CONCLUSÃO** A estrutura criada pela `RouteEntity` é **robusta, escalável e otimizada** para o sistema PraFrota: ### **✅ Pontos Fortes:** - **Flexibilidade**: JSONB para dados semi-estruturados - **Performance**: Índices estratégicos para consultas comuns - **Consistência**: ENUMs para validação rigorosa - **Escalabilidade**: Estrutura preparada para milhões de registros - **Relacionamentos**: Foreign keys para integridade referencial ### **🚀 Próximos Passos:** 1. **Configurar TypeORM** no backend NestJS 2. **Executar migrations** para criar a estrutura 3. **Implementar services** para CRUD operations 4. **Configurar relacionamentos** com outras entidades (Driver, Vehicle, Company) 5. **Otimizar consultas** baseadas nos padrões de uso real --- **📅 Última atualização**: Julho 2025 **📚 Autor**: Jonas Santos **🔧 Versão TypeORM**: 0.3.x **🗄️ Banco recomendado**: PostgreSQL 13+