// app/javascript/controllers/nota_avulsa_controller.js // Stimulus controller — "Nota avulsa": busca a NF na base de rastreio e, ao // prosseguir, o formulário cria JÁ uma consolidação avulsa para o motorista. import { Controller } from "@hotwired/stimulus" export default class extends Controller { static targets = ["modal", "nf", "erro", "resultados", "confirmar"] static values = { buscarUrl: String } abrir() { this.reset() this.modalTarget.classList.remove("hidden") this.nfTarget.focus() } fechar() { this.modalTarget.classList.add("hidden") } fundo(event) { if (event.target === this.modalTarget) this.fechar() } reset() { this.nfTarget.value = "" this.erroTarget.classList.add("hidden") this.resultadosTarget.innerHTML = "" this.confirmarTarget.classList.add("hidden") } // ── Busca da NF (Enter ou botão) ─────────────────────────── async buscar(event) { event?.preventDefault() const nf = this.nfTarget.value.trim() if (!nf) { this.mostrarErro("Informe o número da nota."); return } this.erroTarget.classList.add("hidden") this.resultadosTarget.innerHTML = `
Buscando…
` this.confirmarTarget.classList.add("hidden") try { const url = `${this.buscarUrlValue}?nf=${encodeURIComponent(nf)}` const resp = await fetch(url, { headers: { "Accept": "application/json" } }) const data = await resp.json() if (!data.ok) { this.resultadosTarget.innerHTML = "" this.mostrarErro(data.erro || "Nota não encontrada.") return } this.renderResultados(data.entregas) } catch (e) { this.resultadosTarget.innerHTML = "" this.mostrarErro("Erro ao buscar a nota. Tente novamente.") } } renderResultados(entregas) { const cards = entregas.map((e, i) => { const pago = e.pago ? `paga` : `${e.status || "pendente"}` return ` ` }).join("") this.resultadosTarget.innerHTML = cards this.confirmarTarget.classList.remove("hidden") } // Garante que há uma entrega selecionada antes de enviar o formulário. validar(event) { const selecionado = this.resultadosTarget.querySelector('input[name="tracking_id"]:checked') if (!selecionado) { event.preventDefault() this.mostrarErro("Busque e selecione uma nota antes de criar.") } } mostrarErro(msg) { this.erroTarget.textContent = msg this.erroTarget.classList.remove("hidden") } }