Skip to content

Precognition not cleaning errors after 204 response #122

Open
@thiago8844

Description

@thiago8844

Laravel Precognition Plugin Version

0.5.2

Laravel Version

11

Plugin

Alpine

Description

Even though i received many 204 responses saying that there's no errors, it didn't cleaned the form.errors causing the form to never be submitted. Should i clean it manually ? if so how do i have access to this responses.

Image

Steps To Reproduce

``

@Push('scripts')
<script>

        function currencyToNumber(value) {
          return Num(value.replace(/\./g, '').replace(',', '.')).toNumber();
        }

        decimalFormatter = new Intl.NumberFormat('pt-BR', {
            style: 'decimal',
            minimumFractionDigits: 2,
            maximumFractionDigits: 2,
        });

        document.addEventListener('alpine:init', () => {
     
          Alpine.data('nfe', () => ({

              formas_pagamento: @json($formasPagamento),
              estados: @json($estados),
              cidades: null,
              erros_api: {},

              debug_form: null,
              //Cria o formulário do precognition
              init() {

                  this.form = this.$form('POST', '{{ route('nfe-emitir') }}', {
                      //Variáveis porque o precognition é uma bosta
                      unlock_validation: 999,
                      method: null,

                      venda_id: {{ $venda_id }}, 
                      nfe_id: null, //Vai ser preenchido caso ele esteja enviando para uma nota que foi rejeitada
                      numero_nfe: null, //Vai ser preenchido caso ele esteja enviando para uma nota que foi rejeitada
                      serie_nfe: null, //Vai ser preenchido caso ele esteja enviando para uma nota que foi rejeitada
                      // -=-=- Informações da Emissão da NF-e -=-=-
                      natureza: 'Venda de mercadorias conforme itens descritos na nota', //Colocar na configuração de descrição padrão venda
                      data_emissao: null,
                      data_saida: null,
                      finalidade_nfe: '',
                      indicador_presenca: '',
                      // -=-=- Dados destinatário -=-=-
                      nome: '{{ $cliente->nome ?? '' }}',
                      tipo_pessoa: '',
                      cpf: '{{ $cpf }}',
                      cnpj:'{{ $cnpj }}',
                      tipo_contribuinte: null,
                      inscricao_estadual: '{{ $cliente->inscricao_estadual }}',
                      tipo_consumidor: '',
                      //Endereço
                      cep: '{{ $cliente->cep }}',
                      numero_endereco: '{{ $cliente->numero }}',
                      logradouro: '{{ $cliente->logradouro }}',
                      bairro: '{{ $cliente->bairro }}',
                      cidade: '{{ $cliente->cidade_id }}',
                      uf: '{{ $cliente->estado_id }}',
                      // -=-=-=- Itens -=-=-=-
                      itens: @json($produtos),
                      //Totais da nota
                      total_itens: {{ $total_itens }},
                      quantidades: {{ $quantidades }},
                      desconto: {{ $total_desconto }},
                      acrescimo: {{ $total_acrescimo }},
                      total_nfe: {{ $total_nota }},
                      // -=-=-=- Pagamentos -=-=-=-
                      pagamentos: @json($pagamentos),
                      sem_pagamento: false,
                      // -=-=-=- Transportadora -=-=-=- 
                      nome_transportadora: '',
                      placa_veiculo_transportadora: '',
                      cpf_cnpj_transportadora: '',
                      rnct: '',
                      inscricao_estadual_transportadora: '',
                      cep_transportadora: '',
                      logradouro_transportadora: '',
                      uf_transportadora: '',
                      numero_transportadora: '',
                      bairro_transportadora: '',
                      endereco_frete_diferente: false,
                      // -=-=-=- Observações -=-=-=-
                      informacoes_adicionais_fisco: '',
                      informacoes_adicionais_contribuinte: '',
                      informacoes_adicionais_compra: '',
                  },{
                    onStart: () => {
                      this.$store.overlay.open();
                    },
                    onFinish: async () => {



                      const method = this.form.method;

                      if(!this.form.hasErrors) {
                        if(method === 'salvar') {
                          console.log("Vai salvar")
                          await this.salvar(this.form);
                        }

                        if(method === 'emitir') {
                          await this.emitir();
                        }

                      }

                      console.log("fechando overlay")
                      this.$store.overlay.hide();

                    }
                  }
                  /////////////////////////////////////
                  );

                  this.form.setValidationTimeout(2000);

                  // -=-=-=- Formata alguns campos que vieram como float -=-=-=-
                  this.form.itens.forEach(item => {
                    item.preco_unitario = decimalFormatter.format(item.preco_unitario);
                    item.desconto = decimalFormatter.format(item.desconto);
                    item.acrescimo = decimalFormatter.format(item.acrescimo);
                    item.subtotal = decimalFormatter.format(item.subtotal);
                  });
                  
                  this.form.pagamentos.forEach(pagamento => {
                    pagamento.valor_total = decimalFormatter.format(pagamento.valor_total);
                  });

                  this.form.total_itens = decimalFormatter.format(this.form.total_itens);
                  this.form.desconto = decimalFormatter.format(this.form.desconto);
                  this.form.acrescimo = decimalFormatter.format(this.form.acrescimo);
                  this.form.total_nfe = decimalFormatter.format(this.form.total_nfe);
                  
                  // -=-=-=- Funções para carregar certos dados -=-=-=-
                  this.getCities();
                  // -=-=-=- Watches -=-=-=-
                  this.debug_form = JSON.stringify(this.form, null, 4);
                  
                  //Debug
                  this.$watch('form', (value) => {
                      this.debug_form = JSON.stringify(value, null, 4);
                  })

              },
            
              // -=-=-=- Funções Auxiliáres -=-=-=-
              async getCities() {
                const estado_id = this.form.uf;

                if(!estado_id) {
                    return
                }

                const response = await fetch(`/painel/estados/${estado_id}`);
                    
                this.cidades = await response.json();
              },

              // -=-=-=- Precognition -=-=-=-
              //Como o precognition é uma bosta

              async emitir() {
                console.log('hora de emitir')
                //this.form.setErrors({});



                //   let response = await this.form.submit(); //Envia os dados pro controller

                //   if(response.data.sucesso) {
                //     window.location.replace(response.data.redirect);
                //   } 
                //   else {
                //     //Mostra os erros que retornaram
                //     const erros = {}
                //     erros["Erro"] = response.data.mensagem;

                //     if(response.data.erros) {
                //       response.data.erros.forEach(erro => {
                //         erros[erro.campo] = erro.erro;
                //       });
                //     }

                //     this.erros_api = erros;
                //     this.unlockValidation();
                //   }


                       
              },

              async salvar(nf_data) {

                //   const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
                  
                //   const response = await fetch('{{ route('nfe-save') }}', {
                //     method: 'POST',
                //     headers: {
                //       'Content-Type': 'application/json',
                //       'X-CSRF-TOKEN': csrfToken
                //     },
                //     body: JSON.stringify(nf_data)
                //   });

                //   document.dispatchEvent(new CustomEvent('resource.success', {
                //         detail: {
                //           message: 'Nota Salva com Sucesso ! Só que não'
                //         },
                //   }));

              },

              validate(method) {

                this.form.method = method;
                
                const newForm = this.form.validate();

                console.log(newForm);

              },

              unlockValidation() {
                this.form.unlock_validation += 1 
              },

            }));
          
          Alpine.store('currentItem', {
            item: {},
            setItem(item) {
              Object.assign(this.item, item);
            }
          });

      });
     
</script>

@endpush

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions