Files
Reem-Notas/app/javascript/controllers/apontamento_termo_controller.js

83 lines
2.4 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// app/javascript/controllers/apontamento_termo_controller.js
// Stimulus — Entrega de termo. Lança um lote de N termos para o motorista da tela.
// Entrega sem NF nem código de rastreio: só a quantidade (stepper N +), a um
// preço fixo configurável.
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
static targets = ["modal", "quantidade", "erro", "veiculo"]
static values = { apontarTermoUrl: String, motorista: String }
abrir() {
this.erroTarget.classList.add("hidden")
this.quantidadeTarget.value = "1"
this.modalTarget.classList.remove("hidden")
}
fechar() {
this.modalTarget.classList.add("hidden")
}
// Fecha ao clicar no fundo (fora do card)
fundo(event) {
if (event.target === this.modalTarget) this.fechar()
}
// Stepper
mais() {
this.quantidadeTarget.value = String(this.qtdAtual() + 1)
}
menos() {
this.quantidadeTarget.value = String(Math.max(1, this.qtdAtual() - 1))
}
qtdAtual() {
const n = parseInt(this.quantidadeTarget.value, 10)
return Number.isFinite(n) && n > 0 ? n : 1
}
async adicionar(event) {
event?.preventDefault()
const quantidade = this.qtdAtual()
const motorista = this.motoristaValue.trim()
if (!motorista) { this.mostrarErro("Motorista não identificado."); return }
const btn = event.currentTarget
btn.disabled = true
try {
const resp = await fetch(this.apontarTermoUrlValue, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
"X-CSRF-Token": document.querySelector('meta[name="csrf-token"]').content
},
body: JSON.stringify({
motorista: motorista,
quantidade: quantidade,
vehicle: this.hasVeiculoTarget ? this.veiculoTarget.value : ""
})
})
const data = await resp.json()
if (!resp.ok || data.ok === false) {
this.mostrarErro(data.erro || "Não foi possível adicionar as entregas de termo.")
return
}
// Recarrega para refletir o valor atualizado do motorista.
window.location.reload()
} catch (e) {
this.mostrarErro("Erro ao adicionar as entregas de termo. Tente novamente.")
} finally {
btn.disabled = false
}
}
mostrarErro(msg) {
this.erroTarget.textContent = msg
this.erroTarget.classList.remove("hidden")
}
}