604 lines
13 KiB
Markdown
604 lines
13 KiB
Markdown
# Troubleshooting - DRE Gerencial
|
|
|
|
## Visão Geral
|
|
|
|
Este guia contém soluções para problemas comuns encontrados durante o desenvolvimento, deploy e manutenção do sistema DRE Gerencial.
|
|
|
|
## Problemas de Desenvolvimento
|
|
|
|
### 1. **Erros de TypeScript**
|
|
|
|
#### Erro: "Cannot find module '@/components/ui/button'"
|
|
```bash
|
|
# Verificar se o arquivo existe
|
|
ls -la src/components/ui/button.tsx
|
|
|
|
# Verificar tsconfig.json
|
|
cat tsconfig.json | grep paths
|
|
|
|
# Solução: Verificar se o path alias está correto
|
|
{
|
|
"compilerOptions": {
|
|
"paths": {
|
|
"@/*": ["./src/*"]
|
|
}
|
|
}
|
|
}
|
|
```
|
|
|
|
#### Erro: "Property 'valor' does not exist on type 'DREItem'"
|
|
```typescript
|
|
// Verificar interface
|
|
interface DREItem {
|
|
valor: string; // ou number
|
|
// outros campos...
|
|
}
|
|
|
|
// Solução: Verificar se o tipo está correto na API
|
|
const valor = typeof item.valor === 'string' ? parseFloat(item.valor) : item.valor;
|
|
```
|
|
|
|
### 2. **Erros de Build**
|
|
|
|
#### Erro: "Module not found: Can't resolve 'xlsx'"
|
|
```bash
|
|
# Instalar dependência
|
|
npm install xlsx
|
|
npm install --save-dev @types/xlsx
|
|
|
|
# Verificar se está no package.json
|
|
cat package.json | grep xlsx
|
|
```
|
|
|
|
#### Erro: "Failed to compile"
|
|
```bash
|
|
# Limpar cache
|
|
rm -rf .next node_modules
|
|
npm install
|
|
npm run build
|
|
|
|
# Verificar se há erros de TypeScript
|
|
npx tsc --noEmit
|
|
```
|
|
|
|
### 3. **Problemas de Performance**
|
|
|
|
#### Componente renderizando muito
|
|
```typescript
|
|
// Solução: Usar useMemo para cálculos pesados
|
|
const expensiveValue = useMemo(() => {
|
|
return data.reduce((sum, item) => sum + item.valor, 0);
|
|
}, [data]);
|
|
|
|
// Usar useCallback para funções
|
|
const handleClick = useCallback((id: string) => {
|
|
// lógica
|
|
}, [dependencies]);
|
|
```
|
|
|
|
#### Lista muito grande causando lag
|
|
```typescript
|
|
// Solução: Implementar virtualização
|
|
import { FixedSizeList as List } from 'react-window';
|
|
|
|
const VirtualizedList = ({ items }) => (
|
|
<List
|
|
height={400}
|
|
itemCount={items.length}
|
|
itemSize={50}
|
|
itemData={items}
|
|
>
|
|
{({ index, style, data }) => (
|
|
<div style={style}>
|
|
{data[index].name}
|
|
</div>
|
|
)}
|
|
</List>
|
|
);
|
|
```
|
|
|
|
## Problemas de Banco de Dados
|
|
|
|
### 1. **Erros de Conexão**
|
|
|
|
#### Erro: "Connection refused"
|
|
```bash
|
|
# Verificar se PostgreSQL está rodando
|
|
sudo systemctl status postgresql
|
|
|
|
# Iniciar PostgreSQL
|
|
sudo systemctl start postgresql
|
|
|
|
# Verificar porta
|
|
netstat -tlnp | grep 5432
|
|
```
|
|
|
|
#### Erro: "Authentication failed"
|
|
```bash
|
|
# Verificar usuário e senha
|
|
psql -h localhost -U postgres -d dre_gerencial
|
|
|
|
# Verificar pg_hba.conf
|
|
sudo nano /etc/postgresql/13/main/pg_hba.conf
|
|
|
|
# Configuração recomendada
|
|
local all postgres peer
|
|
host all all 127.0.0.1/32 md5
|
|
```
|
|
|
|
### 2. **Erros de Query**
|
|
|
|
#### Erro: "relation 'view_dre_gerencial' does not exist"
|
|
```sql
|
|
-- Verificar se a view existe
|
|
\dv view_dre_gerencial
|
|
|
|
-- Criar view se não existir
|
|
CREATE VIEW view_dre_gerencial AS
|
|
SELECT
|
|
codfilial,
|
|
data_competencia,
|
|
data_caixa,
|
|
grupo,
|
|
subgrupo,
|
|
centro_custo,
|
|
codigo_conta,
|
|
conta,
|
|
valor
|
|
FROM fato_financeiro_analitico;
|
|
```
|
|
|
|
#### Erro: "column 'valor' does not exist"
|
|
```sql
|
|
-- Verificar estrutura da tabela
|
|
\d fato_financeiro_analitico
|
|
|
|
-- Verificar se a coluna existe
|
|
SELECT column_name, data_type
|
|
FROM information_schema.columns
|
|
WHERE table_name = 'fato_financeiro_analitico';
|
|
```
|
|
|
|
### 3. **Problemas de Performance**
|
|
|
|
#### Query muito lenta
|
|
```sql
|
|
-- Verificar plano de execução
|
|
EXPLAIN ANALYZE SELECT * FROM fato_financeiro_analitico
|
|
WHERE data_competencia BETWEEN '2024-01-01' AND '2024-12-31';
|
|
|
|
-- Criar índices necessários
|
|
CREATE INDEX idx_fato_financeiro_data_competencia
|
|
ON fato_financeiro_analitico (data_competencia);
|
|
|
|
CREATE INDEX idx_fato_financeiro_centro_custo
|
|
ON fato_financeiro_analitico (codigo_centrocusto);
|
|
```
|
|
|
|
#### Timeout de conexão
|
|
```typescript
|
|
// Aumentar timeout no pool de conexões
|
|
const pool = new Pool({
|
|
database: process.env.POSTGRES_DB,
|
|
host: process.env.POSTGRES_HOST,
|
|
port: Number(process.env.POSTGRES_PORT),
|
|
user: process.env.POSTGRES_USER,
|
|
password: process.env.POSTGRES_PASSWORD,
|
|
connectionTimeoutMillis: 10000,
|
|
idleTimeoutMillis: 30000,
|
|
max: 20,
|
|
});
|
|
```
|
|
|
|
## Problemas de API
|
|
|
|
### 1. **Erros 404**
|
|
|
|
#### Rota não encontrada
|
|
```typescript
|
|
// Verificar se o arquivo de rota existe
|
|
ls -la src/app/api/analitico/route.ts
|
|
|
|
// Verificar se a função está exportada
|
|
export async function GET(request: NextRequest) {
|
|
// implementação
|
|
}
|
|
```
|
|
|
|
#### Parâmetros obrigatórios não fornecidos
|
|
```typescript
|
|
// Verificar validação de parâmetros
|
|
if (!dataInicio || !dataFim) {
|
|
return NextResponse.json(
|
|
{ message: 'Parâmetros obrigatórios: dataInicio, dataFim' },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
```
|
|
|
|
### 2. **Erros 500**
|
|
|
|
#### Erro interno do servidor
|
|
```typescript
|
|
// Adicionar logs detalhados
|
|
try {
|
|
const data = await db.execute(query);
|
|
return NextResponse.json(data.rows);
|
|
} catch (error) {
|
|
console.error('Erro detalhado:', {
|
|
message: error.message,
|
|
stack: error.stack,
|
|
query: query.toString(),
|
|
});
|
|
|
|
return NextResponse.json(
|
|
{ error: 'Erro interno do servidor' },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
```
|
|
|
|
#### Erro de memória
|
|
```bash
|
|
# Verificar uso de memória
|
|
free -h
|
|
|
|
# Aumentar limite de memória do Node.js
|
|
export NODE_OPTIONS="--max-old-space-size=4096"
|
|
npm run dev
|
|
```
|
|
|
|
### 3. **Problemas de CORS**
|
|
|
|
#### Erro: "Access to fetch at '...' from origin '...' has been blocked by CORS policy"
|
|
```typescript
|
|
// Adicionar headers CORS
|
|
export async function GET(request: NextRequest) {
|
|
const response = NextResponse.json(data);
|
|
|
|
response.headers.set('Access-Control-Allow-Origin', '*');
|
|
response.headers.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
|
|
response.headers.set('Access-Control-Allow-Headers', 'Content-Type');
|
|
|
|
return response;
|
|
}
|
|
```
|
|
|
|
## Problemas de Deploy
|
|
|
|
### 1. **Erros de Build em Produção**
|
|
|
|
#### Erro: "Module not found"
|
|
```bash
|
|
# Verificar se todas as dependências estão instaladas
|
|
npm ci --production
|
|
|
|
# Verificar se não há dependências de desenvolvimento em produção
|
|
npm list --production
|
|
```
|
|
|
|
#### Erro: "Out of memory"
|
|
```bash
|
|
# Aumentar memória para build
|
|
export NODE_OPTIONS="--max-old-space-size=4096"
|
|
npm run build
|
|
```
|
|
|
|
### 2. **Problemas de PM2**
|
|
|
|
#### Aplicação não inicia
|
|
```bash
|
|
# Verificar logs
|
|
pm2 logs dre-gerencial
|
|
|
|
# Verificar configuração
|
|
pm2 show dre-gerencial
|
|
|
|
# Reiniciar aplicação
|
|
pm2 restart dre-gerencial
|
|
```
|
|
|
|
#### Aplicação reinicia constantemente
|
|
```bash
|
|
# Verificar uso de memória
|
|
pm2 monit
|
|
|
|
# Ajustar limite de memória
|
|
pm2 start ecosystem.config.js --max-memory-restart 1G
|
|
```
|
|
|
|
### 3. **Problemas de Nginx**
|
|
|
|
#### Erro: "502 Bad Gateway"
|
|
```bash
|
|
# Verificar se a aplicação está rodando
|
|
pm2 status
|
|
|
|
# Verificar logs do Nginx
|
|
sudo tail -f /var/log/nginx/error.log
|
|
|
|
# Testar configuração
|
|
sudo nginx -t
|
|
```
|
|
|
|
#### Erro: "Connection refused"
|
|
```bash
|
|
# Verificar se a aplicação está escutando na porta correta
|
|
netstat -tlnp | grep 3000
|
|
|
|
# Verificar configuração do proxy
|
|
sudo nano /etc/nginx/sites-available/dre-gerencial
|
|
```
|
|
|
|
## Problemas de Dados
|
|
|
|
### 1. **Dados não aparecem**
|
|
|
|
#### Verificar se há dados no banco
|
|
```sql
|
|
-- Verificar se há dados na tabela
|
|
SELECT COUNT(*) FROM fato_financeiro_analitico;
|
|
|
|
-- Verificar se há dados na view
|
|
SELECT COUNT(*) FROM view_dre_gerencial;
|
|
|
|
-- Verificar dados por período
|
|
SELECT COUNT(*) FROM fato_financeiro_analitico
|
|
WHERE data_competencia BETWEEN '2024-01-01' AND '2024-12-31';
|
|
```
|
|
|
|
#### Verificar filtros aplicados
|
|
```typescript
|
|
// Adicionar logs para debug
|
|
console.log('Filtros aplicados:', filtros);
|
|
console.log('Query executada:', query.toString());
|
|
console.log('Resultado:', data.length);
|
|
```
|
|
|
|
### 2. **Dados incorretos**
|
|
|
|
#### Verificar cálculos
|
|
```typescript
|
|
// Verificar se os cálculos estão corretos
|
|
const totalValor = data.reduce((sum, item) => {
|
|
const valor = typeof item.valor === 'string' ? parseFloat(item.valor) : item.valor;
|
|
return sum + (isNaN(valor) ? 0 : valor);
|
|
}, 0);
|
|
|
|
console.log('Total calculado:', totalValor);
|
|
```
|
|
|
|
#### Verificar formatação de datas
|
|
```typescript
|
|
// Verificar se as datas estão sendo formatadas corretamente
|
|
const formatDate = (dateString: string) => {
|
|
try {
|
|
return new Date(dateString).toLocaleDateString('pt-BR');
|
|
} catch (error) {
|
|
console.error('Erro ao formatar data:', dateString, error);
|
|
return 'Data inválida';
|
|
}
|
|
};
|
|
```
|
|
|
|
### 3. **Performance de Dados**
|
|
|
|
#### Query muito lenta
|
|
```sql
|
|
-- Verificar plano de execução
|
|
EXPLAIN ANALYZE SELECT * FROM fato_financeiro_analitico
|
|
WHERE data_competencia BETWEEN '2024-01-01' AND '2024-12-31'
|
|
AND codigo_centrocusto = '001';
|
|
|
|
-- Criar índices compostos
|
|
CREATE INDEX idx_fato_financeiro_composto
|
|
ON fato_financeiro_analitico (data_competencia, codigo_centrocusto);
|
|
```
|
|
|
|
#### Muitos dados carregando
|
|
```typescript
|
|
// Implementar paginação
|
|
const ITEMS_PER_PAGE = 100;
|
|
const [currentPage, setCurrentPage] = useState(1);
|
|
|
|
const paginatedData = data.slice(
|
|
(currentPage - 1) * ITEMS_PER_PAGE,
|
|
currentPage * ITEMS_PER_PAGE
|
|
);
|
|
```
|
|
|
|
## Problemas de Interface
|
|
|
|
### 1. **Componentes não renderizam**
|
|
|
|
#### Verificar se o componente está sendo importado corretamente
|
|
```typescript
|
|
// Verificar import
|
|
import AnaliticoComponent from './analitico';
|
|
|
|
// Verificar se está sendo usado
|
|
{!loading && data.length > 0 && (
|
|
<AnaliticoComponent filtros={analiticoFiltros} />
|
|
)}
|
|
```
|
|
|
|
#### Verificar se há erros no console
|
|
```typescript
|
|
// Adicionar error boundary
|
|
class ErrorBoundary extends Component {
|
|
constructor(props) {
|
|
super(props);
|
|
this.state = { hasError: false };
|
|
}
|
|
|
|
static getDerivedStateFromError(error) {
|
|
return { hasError: true };
|
|
}
|
|
|
|
componentDidCatch(error, errorInfo) {
|
|
console.error('Erro no componente:', error, errorInfo);
|
|
}
|
|
|
|
render() {
|
|
if (this.state.hasError) {
|
|
return <div>Erro ao carregar componente</div>;
|
|
}
|
|
|
|
return this.props.children;
|
|
}
|
|
}
|
|
```
|
|
|
|
### 2. **Problemas de Styling**
|
|
|
|
#### Classes Tailwind não aplicadas
|
|
```bash
|
|
# Verificar se Tailwind está configurado
|
|
cat tailwind.config.js
|
|
|
|
# Verificar se as classes estão sendo incluídas
|
|
npm run build
|
|
```
|
|
|
|
#### Componentes não responsivos
|
|
```typescript
|
|
// Verificar classes responsivas
|
|
<div className="w-full md:w-1/2 lg:w-1/3">
|
|
{/* conteúdo */}
|
|
</div>
|
|
```
|
|
|
|
### 3. **Problemas de Interação**
|
|
|
|
#### Cliques não funcionam
|
|
```typescript
|
|
// Verificar se o evento está sendo capturado
|
|
const handleClick = (event: React.MouseEvent) => {
|
|
event.preventDefault();
|
|
event.stopPropagation();
|
|
|
|
console.log('Clique capturado');
|
|
// lógica
|
|
};
|
|
|
|
// Verificar se o elemento está clicável
|
|
<button
|
|
onClick={handleClick}
|
|
className="cursor-pointer hover:bg-blue-50"
|
|
>
|
|
Clique aqui
|
|
</button>
|
|
```
|
|
|
|
#### Estados não atualizam
|
|
```typescript
|
|
// Verificar se o estado está sendo atualizado corretamente
|
|
const [data, setData] = useState([]);
|
|
|
|
const updateData = (newData) => {
|
|
console.log('Atualizando dados:', newData);
|
|
setData(newData);
|
|
};
|
|
|
|
// Verificar se o useEffect está sendo executado
|
|
useEffect(() => {
|
|
console.log('useEffect executado');
|
|
fetchData();
|
|
}, [dependencies]);
|
|
```
|
|
|
|
## Comandos Úteis para Debug
|
|
|
|
### 1. **Verificar Status do Sistema**
|
|
```bash
|
|
# Status dos serviços
|
|
sudo systemctl status nginx postgresql
|
|
|
|
# Uso de recursos
|
|
htop
|
|
free -h
|
|
df -h
|
|
|
|
# Logs do sistema
|
|
sudo journalctl -f
|
|
```
|
|
|
|
### 2. **Verificar Aplicação**
|
|
```bash
|
|
# Status da aplicação
|
|
pm2 status
|
|
pm2 logs dre-gerencial
|
|
|
|
# Verificar processos
|
|
ps aux | grep node
|
|
|
|
# Verificar portas
|
|
netstat -tlnp | grep :3000
|
|
```
|
|
|
|
### 3. **Verificar Banco de Dados**
|
|
```bash
|
|
# Conectar ao banco
|
|
psql -h localhost -U postgres -d dre_gerencial
|
|
|
|
# Verificar conexões ativas
|
|
SELECT * FROM pg_stat_activity;
|
|
|
|
# Verificar tamanho do banco
|
|
SELECT pg_size_pretty(pg_database_size('dre_gerencial'));
|
|
```
|
|
|
|
## Logs e Monitoramento
|
|
|
|
### 1. **Configurar Logs Detalhados**
|
|
```typescript
|
|
// Adicionar logs estruturados
|
|
const logger = {
|
|
info: (message: string, data?: any) => {
|
|
console.log({
|
|
timestamp: new Date().toISOString(),
|
|
level: 'INFO',
|
|
message,
|
|
data,
|
|
});
|
|
},
|
|
error: (message: string, error?: any) => {
|
|
console.error({
|
|
timestamp: new Date().toISOString(),
|
|
level: 'ERROR',
|
|
message,
|
|
error: error?.message || error,
|
|
stack: error?.stack,
|
|
});
|
|
},
|
|
};
|
|
```
|
|
|
|
### 2. **Monitoramento de Performance**
|
|
```typescript
|
|
// Adicionar métricas de performance
|
|
const performanceMonitor = {
|
|
start: (label: string) => {
|
|
performance.mark(`${label}-start`);
|
|
},
|
|
end: (label: string) => {
|
|
performance.mark(`${label}-end`);
|
|
performance.measure(label, `${label}-start`, `${label}-end`);
|
|
|
|
const measure = performance.getEntriesByName(label)[0];
|
|
console.log(`${label}: ${measure.duration}ms`);
|
|
},
|
|
};
|
|
```
|
|
|
|
## Próximos Passos
|
|
|
|
1. **Implementar sistema de logs** centralizado
|
|
2. **Adicionar monitoramento** em tempo real
|
|
3. **Implementar alertas** automáticos
|
|
4. **Criar dashboard** de saúde do sistema
|
|
5. **Implementar backup** automatizado
|
|
6. **Adicionar testes** de carga
|
|
7. **Implementar rollback** automático
|
|
8. **Criar documentação** de runbooks
|