211 lines
6.4 KiB
Markdown
211 lines
6.4 KiB
Markdown
|
|
# Correção do Erro "Nota Fiscal não encontrada"
|
||
|
|
|
||
|
|
## 🚨 **Problema Identificado**
|
||
|
|
|
||
|
|
### **Erro:**
|
||
|
|
```
|
||
|
|
Alert.alert("Erro", "Nota fiscal não encontrada")
|
||
|
|
```
|
||
|
|
|
||
|
|
### **Causa Raiz:**
|
||
|
|
O erro estava ocorrendo porque a busca da nota fiscal na função `handleSubmit` ainda estava usando o campo incorreto `invoiceId` em vez de `invoiceDeliveryId`.
|
||
|
|
|
||
|
|
## 🔍 **Análise do Problema**
|
||
|
|
|
||
|
|
### **1. Inconsistência de Campos**
|
||
|
|
- **Seleção**: Usava `invoice.invoiceDeliveryId` ✅
|
||
|
|
- **Busca**: Usava `invoice.invoiceId` ❌
|
||
|
|
- **Resultado**: IDs diferentes causavam falha na busca
|
||
|
|
|
||
|
|
### **2. Localização do Erro**
|
||
|
|
```typescript
|
||
|
|
// ❌ CÓDIGO INCORRETO (ANTES)
|
||
|
|
const currentInvoice = customerInvoices.find(inv =>
|
||
|
|
`${inv.invoiceId}-${inv.transactionId}` === currentInvoiceId
|
||
|
|
)
|
||
|
|
|
||
|
|
// ✅ CÓDIGO CORRETO (DEPOIS)
|
||
|
|
const currentInvoice = customerInvoices.find(inv =>
|
||
|
|
`${inv.invoiceDeliveryId}-${inv.transactionId}` === currentInvoiceId
|
||
|
|
)
|
||
|
|
```
|
||
|
|
|
||
|
|
### **3. Fluxo do Problema**
|
||
|
|
```
|
||
|
|
1. Usuário seleciona nota → invoiceDeliveryId usado ✅
|
||
|
|
2. Sistema gera uniqueId → invoiceDeliveryId-transactionId ✅
|
||
|
|
3. Busca da nota → invoiceId usado ❌
|
||
|
|
4. Comparação falha → "Nota fiscal não encontrada" ❌
|
||
|
|
```
|
||
|
|
|
||
|
|
## 🛠️ **Solução Implementada**
|
||
|
|
|
||
|
|
### **1. Correção da Busca**
|
||
|
|
```typescript
|
||
|
|
// Antes: Busca incorreta
|
||
|
|
const currentInvoice = customerInvoices.find(inv =>
|
||
|
|
`${inv.invoiceId}-${inv.transactionId}` === currentInvoiceId
|
||
|
|
)
|
||
|
|
|
||
|
|
// Depois: Busca correta
|
||
|
|
const currentInvoice = customerInvoices.find(inv =>
|
||
|
|
`${inv.invoiceDeliveryId}-${inv.transactionId}` === currentInvoiceId
|
||
|
|
)
|
||
|
|
```
|
||
|
|
|
||
|
|
### **2. Logs de Debug Adicionados**
|
||
|
|
```typescript
|
||
|
|
console.log('=== DEBUG: BUSCANDO NOTA FISCAL ===')
|
||
|
|
console.log('selectedInvoiceIds:', selectedInvoiceIds)
|
||
|
|
console.log('currentInvoiceIndex:', currentInvoiceIndex)
|
||
|
|
console.log('currentInvoiceId:', currentInvoiceId)
|
||
|
|
console.log('customerInvoices:', customerInvoices)
|
||
|
|
|
||
|
|
const currentInvoice = customerInvoices.find(inv =>
|
||
|
|
`${inv.invoiceDeliveryId}-${inv.transactionId}` === currentInvoiceId
|
||
|
|
)
|
||
|
|
|
||
|
|
console.log('currentInvoice encontrada:', currentInvoice)
|
||
|
|
|
||
|
|
if (!currentInvoice) {
|
||
|
|
console.error('=== ERRO: NOTA FISCAL NÃO ENCONTRADA ===')
|
||
|
|
console.error('ID buscado:', currentInvoiceId)
|
||
|
|
console.error('Notas disponíveis:', customerInvoices.map(inv =>
|
||
|
|
`${inv.invoiceDeliveryId}-${inv.transactionId}`
|
||
|
|
))
|
||
|
|
console.error('selectedInvoices:', Array.from(selectedInvoices))
|
||
|
|
Alert.alert("Erro", "Nota fiscal não encontrada")
|
||
|
|
return
|
||
|
|
}
|
||
|
|
```
|
||
|
|
|
||
|
|
### **3. Verificação da Estrutura dos Dados**
|
||
|
|
```typescript
|
||
|
|
// Verificar estrutura das notas fiscais
|
||
|
|
if (Array.isArray(invoices) && invoices.length > 0) {
|
||
|
|
console.log('=== DEBUG: ESTRUTURA DA PRIMEIRA NOTA ===')
|
||
|
|
const firstInvoice = invoices[0]
|
||
|
|
console.log('Primeira nota completa:', firstInvoice)
|
||
|
|
console.log('Campos disponíveis:', Object.keys(firstInvoice))
|
||
|
|
console.log('invoiceDeliveryId:', firstInvoice.invoiceDeliveryId)
|
||
|
|
console.log('transactionId:', firstInvoice.transactionId)
|
||
|
|
console.log('Tipo invoiceDeliveryId:', typeof firstInvoice.invoiceDeliveryId)
|
||
|
|
console.log('Tipo transactionId:', typeof firstInvoice.transactionId)
|
||
|
|
}
|
||
|
|
```
|
||
|
|
|
||
|
|
## 📋 **Campos Corrigidos**
|
||
|
|
|
||
|
|
### **Antes (Incorreto):**
|
||
|
|
- `invoice.invoiceId` → Usado incorretamente na busca
|
||
|
|
- `inv.invoiceId` → Usado incorretamente no find
|
||
|
|
|
||
|
|
### **Depois (Correto):**
|
||
|
|
- `invoice.invoiceDeliveryId` → Campo correto para identificação
|
||
|
|
- `inv.invoiceDeliveryId` → Campo correto usado na busca
|
||
|
|
|
||
|
|
## 🔄 **Fluxo Corrigido**
|
||
|
|
|
||
|
|
### **1. Seleção da Nota**
|
||
|
|
```typescript
|
||
|
|
onPress={() => {
|
||
|
|
console.log('=== DEBUG: CLIQUE NA NOTA ===')
|
||
|
|
console.log('InvoiceDeliveryId clicado:', invoice.invoiceDeliveryId)
|
||
|
|
console.log('TransactionId clicado:', invoice.transactionId)
|
||
|
|
toggleInvoiceSelection(invoice.invoiceDeliveryId, invoice.transactionId)
|
||
|
|
}}
|
||
|
|
```
|
||
|
|
|
||
|
|
### **2. Geração do UniqueId**
|
||
|
|
```typescript
|
||
|
|
const uniqueId = `${invoiceDeliveryId}-${transactionId}`
|
||
|
|
// Exemplo: "12345-67890"
|
||
|
|
```
|
||
|
|
|
||
|
|
### **3. Busca da Nota**
|
||
|
|
```typescript
|
||
|
|
const currentInvoice = customerInvoices.find(inv =>
|
||
|
|
`${inv.invoiceDeliveryId}-${inv.transactionId}` === currentInvoiceId
|
||
|
|
)
|
||
|
|
// Agora a busca usa o mesmo campo usado na seleção
|
||
|
|
```
|
||
|
|
|
||
|
|
## 🧪 **Testes de Validação**
|
||
|
|
|
||
|
|
### **1. Teste de Seleção**
|
||
|
|
```bash
|
||
|
|
# Verificar se a seleção gera o ID correto
|
||
|
|
# UniqueId deve ser: invoiceDeliveryId-transactionId
|
||
|
|
```
|
||
|
|
|
||
|
|
### **2. Teste de Busca**
|
||
|
|
```bash
|
||
|
|
# Verificar se a busca encontra a nota selecionada
|
||
|
|
# currentInvoice deve ser encontrada
|
||
|
|
```
|
||
|
|
|
||
|
|
### **3. Teste de Consistência**
|
||
|
|
```bash
|
||
|
|
# Verificar se os campos usados são consistentes
|
||
|
|
# Seleção e busca devem usar invoiceDeliveryId
|
||
|
|
```
|
||
|
|
|
||
|
|
## 📊 **Logs de Debug**
|
||
|
|
|
||
|
|
### **Logs Adicionados:**
|
||
|
|
1. **Busca da Nota**: Mostra IDs e dados da busca
|
||
|
|
2. **Estrutura da API**: Verifica campos retornados
|
||
|
|
3. **Erro Detalhado**: Mostra dados quando falha
|
||
|
|
4. **Consistência**: Confirma campos usados
|
||
|
|
|
||
|
|
### **Exemplo de Log:**
|
||
|
|
```
|
||
|
|
=== DEBUG: BUSCANDO NOTA FISCAL ===
|
||
|
|
selectedInvoiceIds: ["12345-67890", "12346-67891"]
|
||
|
|
currentInvoiceIndex: 0
|
||
|
|
currentInvoiceId: "12345-67890"
|
||
|
|
customerInvoices: [Array(2)]
|
||
|
|
currentInvoice encontrada: {invoiceDeliveryId: 12345, transactionId: 67890, ...}
|
||
|
|
```
|
||
|
|
|
||
|
|
## ✅ **Resultado Esperado**
|
||
|
|
|
||
|
|
### **Antes da Correção:**
|
||
|
|
- ❌ Erro "Nota fiscal não encontrada"
|
||
|
|
- ❌ Falha na finalização da entrega
|
||
|
|
- ❌ Inconsistência entre seleção e busca
|
||
|
|
|
||
|
|
### **Depois da Correção:**
|
||
|
|
- ✅ Nota fiscal encontrada corretamente
|
||
|
|
- ✅ Finalização da entrega funciona
|
||
|
|
- ✅ Consistência entre seleção e busca
|
||
|
|
- ✅ Logs detalhados para troubleshooting
|
||
|
|
|
||
|
|
## 🔮 **Prevenção Futura**
|
||
|
|
|
||
|
|
### **1. Validação de Campos**
|
||
|
|
- Sempre usar `invoiceDeliveryId` para identificação
|
||
|
|
- Verificar consistência entre seleção e busca
|
||
|
|
- Validar estrutura dos dados da API
|
||
|
|
|
||
|
|
### **2. Logs de Debug**
|
||
|
|
- Manter logs detalhados para troubleshooting
|
||
|
|
- Verificar estrutura dos dados retornados
|
||
|
|
- Monitorar IDs gerados e buscados
|
||
|
|
|
||
|
|
### **3. Testes**
|
||
|
|
- Testar seleção de múltiplas notas
|
||
|
|
- Verificar busca em diferentes índices
|
||
|
|
- Validar fluxo completo de finalização
|
||
|
|
|
||
|
|
## 📝 **Resumo da Correção**
|
||
|
|
|
||
|
|
O erro "Nota Fiscal não encontrada" foi causado por uma inconsistência entre os campos usados na seleção (`invoiceDeliveryId`) e na busca (`invoiceId`).
|
||
|
|
|
||
|
|
**Solução implementada:**
|
||
|
|
1. ✅ Corrigir busca para usar `invoiceDeliveryId`
|
||
|
|
2. ✅ Adicionar logs de debug detalhados
|
||
|
|
3. ✅ Verificar estrutura dos dados da API
|
||
|
|
4. ✅ Garantir consistência em todo o fluxo
|
||
|
|
|
||
|
|
A aplicação agora deve funcionar corretamente, permitindo a finalização das entregas sem erros de busca de notas fiscais.
|